Repository navigation
token guard enforcement
Part of Token Guard: the four gates that enforce the 200K floor, the read-only
GET /model-configendpoint, and the advisory frontend behavior.
Four gates, one shared predicate. The table is the contract; details follow.
| # | Site | Failure behavior | Blocking? |
|---|---|---|---|
| 1 |
server/__main__.py boot gate |
logger.critical("STARTUP ABORTED: ...") then SystemExit(1)
|
Process exits, nothing serves |
| 2 | agent/core.py::built_agent() |
TokenGuardError propagates to the caller (a WebSocket error chunk) |
Graph not built for that turn |
| 3 |
agent/tools/subagent/spawn/core.py spawn |
TokenGuardError propagates out of the spawn call |
Child agent never constructed |
| 4 | server/service/models_config.py::write_models_config() |
ValueError before the file is touched |
Save rejected, .models unchanged |
server/__main__.py (gate starts at line 72) fails fast before any agent-core work, so a misconfigured .env can never serve a crippled agent:
from config.features import LLM_CLIENT_DEFAULTS, assert_max_token_valid
_main_raw = os.getenv("MAIN_LLM_MAX_TOKEN", "").strip()
_aux_raw = os.getenv("AUXILIARY_LLM_MAX_TOKEN", "").strip()
# an unset AUXILIARY_LLM_MAX_TOKEN falls back to
# LLM_CLIENT_DEFAULTS["aux_remote_max_tokens"] = 121072 (< 200K), so leaving
# it unset blocks startup too. Local mode (AUXILIARY_LLM_MODEL_LOCAL=true)
# is NOT exempt.
_main_val = int(_main_raw) if _main_raw else None
_aux_val = int(_aux_raw) if _aux_raw else LLM_CLIENT_DEFAULTS["aux_remote_max_tokens"]
try:
assert_max_token_valid("MAIN_LLM_MAX_TOKEN", _main_val)
assert_max_token_valid("AUXILIARY_LLM_MAX_TOKEN", _aux_val)
except Exception as e:
logger.critical("STARTUP ABORTED: {}", e)
raise SystemExit(1) from eA bad value produces exactly this line and the process does not start:
CRITICAL STARTUP ABORTED: MAIN_LLM_MAX_TOKEN = 100000 is below the minimum 200000 (200K); agent startup is blocked
agent/core.py (gate at line 117) is the runtime second line of defense. Even if the server booted with a valid .env, a later edit that drops either value below 200K still refuses to build the graph:
_main_raw = os.getenv("MAIN_LLM_MAX_TOKEN", "").strip()
_aux_raw = os.getenv("AUXILIARY_LLM_MAX_TOKEN", "").strip()
_main_val = int(_main_raw) if _main_raw else None
_aux_val = int(_aux_raw) if _aux_raw else LLM_CLIENT_DEFAULTS["aux_remote_max_tokens"]
assert_max_token_valid("MAIN_LLM_MAX_TOKEN", _main_val)
assert_max_token_valid("AUXILIARY_LLM_MAX_TOKEN", _aux_val)TokenGuardError propagates to the caller; server/service/messages.py surfaces it to the client as a WebSocket error chunk.
agent/tools/subagent/spawn/core.py (gate at line 762) validates child LLMs because spawn bypasses built_agent(), so the floor is not inherited implicitly:
# Subagent spawn bypasses built_agent(), so child LLM construction validates
# the same 200K MAX_TOKEN floor here instead of inheriting it implicitly.
...
assert_max_token_valid("MAIN_LLM_MAX_TOKEN", _main_val)
assert_max_token_valid("AUXILIARY_LLM_MAX_TOKEN", _aux_val)server/service/models_config.py (write_models_config()) makes it impossible to persist a sub-200K value from the UI. The model keys live in .models now — PUT /env refuses them outright — and the gate below runs BEFORE the coercion loop, so a non-integer or below-floor value raises ValueError before the file is touched and the backup and the write both stay clean:
for key, value in changes.items():
if key not in TOKEN_KEYS:
continue
try:
num = int(value)
except (TypeError, ValueError):
raise ValueError(f"{key} must be an integer, got: {value}") from None
if num < MIN_REQUIRED_MAX_TOKEN:
raise ValueError(
f"{key} must be >= {MIN_REQUIRED_MAX_TOKEN} (200K); got {num}. Refusing to save."
)The HTTP handler turns that into {"success": False} for the client, and the on-disk .models stays byte-identical.
server/trigger/http/model_config.py registers a read-only endpoint the frontend consults. It reports both resolved values, the threshold, and the verdict:
{
"main_max_token": 200000,
"aux_max_token": 200000,
"min_required": 200000,
"valid": true
}valid is true only when all three conditions hold:
"valid": (
main_val is not None
and main_val >= MIN_REQUIRED_MAX_TOKEN
and aux_val >= MIN_REQUIRED_MAX_TOKEN
),| Situation | main_max_token |
aux_max_token |
valid |
|---|---|---|---|
Both set to 200000
|
200000 |
200000 |
true |
| Main below floor | e.g. 65536
|
200000 |
false |
| Aux unset | 200000 |
121072 (fallback) |
false |
| Main unset | null |
200000 |
false |
There is no write endpoint for this resource (env writes go through the separate /env route); GET /model-config never mutates state.
The client warns early but never blocks the user. The backend remains the enforcer.
client/app/composables/model-config.ts owns the cache:
-
fetchModelConfig()callsGET /model-configwith a cache-busting_tsquery param and replaces an empty body with a default-invalid object. -
getModelConfigCached()fetches once and caches the result module-wide; on fetch failure it caches a default-invalid object (valid: false) so the send path is never broken by a backend hiccup. -
invalidateModelConfigCache()clears the cache.ConfigPanelcalls it after a successful env save, so the nextgetModelConfigCached()refetches.
function invalidModelConfig(): ModelConfig {
return { main_max_token: null, aux_max_token: null, min_required: 200000, valid: false };
}client/app/composables/use-chat-stream.ts (handleSend(), toast at line 433) reads the cached config and shows a 6-second warning toast when valid is false. It does not abort the send:
const cfg = await getModelConfigCached();
if (!cfg.valid) {
toastWarn(t('chat.tokenGuard.title'), t('chat.tokenGuard.detail'), 6000);
}When the config is valid, or when the fetch fails, the toast stays silent. The send still proceeds; if the backend rejects the build, it returns a WebSocket error chunk.
client/app/pages/home/components/LlmModelManager.vue + ConfigPanel.vue:
-
LlmModelManager.vuerenders the amberconfig.env.maxTokenHintunder a guarded input whenMAX_TOKEN_GUARD_KEYScontains its key. - On save,
ConfigPanel.vue'spersistEnvChanges()pre-validates the same keys againstMIN_REQUIRED_MAX_TOKEN. A non-integer or sub-200000value setsconfig.env.maxTokenErrorand returnsfalse, so the PUT is never sent:
import { MAX_TOKEN_GUARD_KEYS, MIN_REQUIRED_MAX_TOKEN } from '@/constants/env';
for (const [key, value] of Object.entries(changes)) {
if (MAX_TOKEN_GUARD_KEYS.includes(key)) {
const num = parseInt(value, 10);
if (Number.isNaN(num) || num < MIN_REQUIRED_MAX_TOKEN) {
envLoadError.value = t('config.env.maxTokenError', { key });
return false;
}
}
}- After a successful write,
invalidateModelConfigCache()runs so the toast guard re-reads fresh values.
| Key | Where | Purpose |
|---|---|---|
chat.tokenGuard.title |
client/app/i18n/locales/{en,zh,ja,ko}.json |
Toast title |
chat.tokenGuard.detail |
same locale files | Toast body (points to System Config then Environment) |
config.env.maxTokenHint |
locale files + component <i18n> fallbacks |
Amber banner text |
config.env.maxTokenError |
locale files + component <i18n> fallbacks |
Pre-save rejection message; {key} interpolates the offending var |
Generated from the repository's wiki/ tree. Source