Skip to content

Commit 715c379

Browse files
authored
refactor(config): consolidate context budget to one per-model knob (#124665)
* refactor(config): consolidate context budget settings * test(config): type legacy context fixtures * test(config): align context budget fixtures * fix(status): honor runtime context discovery * docs(config): clarify context budget fallbacks * fix(ci): resolve context budget lint failures * test(ci): align context budget shard fixtures * fix(models): preserve catalog context metadata * fix(config): surface context migration diagnostics * test(plugin-sdk): keep live catalog coverage focused
1 parent 4d872fb commit 715c379

125 files changed

Lines changed: 1261 additions & 1705 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/concepts/model-providers.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ Reference for **LLM/model providers** (not chat channels like WhatsApp/Telegram)
1616
- Model refs use `provider/model` (example: `opencode/claude-opus-4-6`).
1717
- `agents.defaults.models` stores aliases and per-model settings; `agents.defaults.modelPolicy.allow` is the optional explicit override allowlist.
1818
- CLI helpers: `openclaw onboard`, `openclaw models list`, `openclaw models set <provider/model>`.
19-
- `models.providers.*.contextWindow` / `contextTokens` / `maxTokens` set provider-level defaults; `models.providers.*.models[].contextWindow` / `contextTokens` / `maxTokens` override them per model.
19+
- `models.providers.*.maxTokens` sets the provider-level output-token default. On each `models.providers.*.models[]` entry, `contextWindow` declares the native window, `contextTokens` caps active input, and `maxTokens` overrides output capacity for that model.
2020
- Fallback rules, cooldown probes, and session-override persistence: [Model failover](/concepts/model-failover).
2121

2222
</Accordion>
@@ -673,9 +673,10 @@ Example (OpenAI-compatible):
673673
- `reasoning: false`
674674
- `input: ["text"]`
675675
- `cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }`
676-
- `contextWindow: 200000`
677676
- `maxTokens: 8192`
678677

678+
An omitted `contextWindow` remains unset so authored native-window metadata is unambiguous. When neither discovery nor per-model context metadata is available, context-budget callers use the standard `200000`-token fallback.
679+
679680
Recommended: set explicit values that match your proxy/model limits.
680681

681682
</Accordion>

‎docs/gateway/config-agents.md‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -382,7 +382,6 @@ date context. Falls back to the host timezone.
382382
elevatedDefault: "on",
383383
timeoutSeconds: 600,
384384
mediaMaxMb: 5,
385-
contextTokens: 200000,
386385
maxConcurrent: 4,
387386
},
388387
},
@@ -424,7 +423,7 @@ date context. Falls back to the host timezone.
424423
- `reasoningDefault`: default reasoning visibility for agents. Values: `"off"`, `"on"`, `"stream"`. Per-agent `agents.entries.*.reasoningDefault` overrides this default. Configured reasoning defaults are only applied for owners, authorized senders, or operator-admin gateway contexts when no per-message or session reasoning override is set.
425424
- `elevatedDefault`: default elevated-output level for agents. Values: `"off"`, `"on"`, `"ask"`, `"full"`. Default: `"on"`.
426425
- `model.primary`: format `provider/model` (e.g. `openai/gpt-5.6-sol` for Codex OAuth access). If you omit the provider, OpenClaw tries an alias first, then a unique configured-provider match for that exact model id, and only then falls back to the configured default provider (deprecated compatibility behavior, so prefer explicit `provider/model`). If that provider no longer exposes the configured default model, OpenClaw falls back to the first configured provider/model instead of surfacing a stale removed-provider default.
427-
- `contextTokens`: optional agent-wide cap. It can lower the effective budget of a larger model but cannot raise a model above its configured or discovered `contextTokens`. To opt one direct OpenAI model into its larger native window, set `models.providers.openai.models[].contextWindow` and `contextTokens` for that model; see [OpenAI context window defaults](/providers/openai#context-window-defaults-and-long-context-opt-in).
426+
- To cap active input for one model, set `models.providers.<provider>.models[].contextTokens`; use `contextWindow` on the same entry for its native window. See [OpenAI context window defaults](/providers/openai#context-window-defaults-and-long-context-opt-in).
428427
- `models`: configured aliases and per-model settings. Each entry can include `alias` (shortcut) and `params` (provider-specific, for example `temperature`, `maxTokens`, `cacheRetention`, `context1m`, `anthropicServerCompaction`, `anthropicCompactThreshold`, `responsesServerCompaction`, `responsesCompactThreshold`, OpenRouter `provider` routing, `chat_template_kwargs`, `extra_body`/`extraBody`). Adding entries does not restrict model overrides.
429428
- Use `provider/*` entries such as `"openai/*": {}` or `"vllm/*": {}` to show all discovered models for selected providers without manually listing every model id.
430429
- Add `agentRuntime` to a `provider/*` entry when every dynamically discovered model for that provider should use the same runtime. Exact `provider/model` runtime policy still wins over the wildcard.

‎docs/gateway/config-tools.md‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -526,8 +526,6 @@ Configuring a custom/local provider `baseUrl` is also the narrow network trust d
526526
- `models.providers.*.api`: request adapter (`openai-completions`, `openai-responses`, `openai-chatgpt-responses`, `anthropic-messages`, `google-generative-ai`, `google-vertex`, `github-copilot`, `bedrock-converse-stream`, `ollama`, `azure-openai-responses`). For self-hosted `/v1/chat/completions` backends such as MLX, vLLM, SGLang, and most OpenAI-compatible local servers, use `openai-completions`. A custom provider with `baseUrl` but no `api` defaults to `openai-completions`; set `openai-responses` only when the backend supports `/v1/responses`.
527527
- `models.providers.*.apiKey`: provider credential (prefer SecretRef/env substitution).
528528
- `models.providers.*.auth`: auth strategy (`api-key`, `token`, `oauth`, `aws-sdk`).
529-
- `models.providers.*.contextWindow`: default native context window for models under this provider when the model entry does not set `contextWindow`.
530-
- `models.providers.*.contextTokens`: default effective runtime context cap for models under this provider when the model entry does not set `contextTokens`.
531529
- `models.providers.*.maxTokens`: default output-token cap for models under this provider when the model entry does not set `maxTokens`.
532530
- `models.providers.*.timeoutSeconds`: optional per-provider model HTTP request timeout in seconds, including connect, headers, body, and total request abort handling.
533531
- `models.providers.*.injectNumCtxForOpenAICompat`: for Ollama + `openai-completions`, inject `options.num_ctx` into requests (default: `true`).
@@ -549,8 +547,8 @@ Configuring a custom/local provider `baseUrl` is also the narrow network trust d
549547
<Accordion title="Model catalog entries">
550548
- `models.providers.*.models`: explicit provider model catalog entries.
551549
- `models.providers.*.models.*.input`: model input modalities. Use `["text"]` for text-only models and `["text", "image"]` for native image/vision models. Image attachments are only injected into agent turns when the selected model is marked image-capable.
552-
- `models.providers.*.models.*.contextWindow`: native model context window metadata. This overrides provider-level `contextWindow` for that model.
553-
- `models.providers.*.models.*.contextTokens`: optional runtime context cap. This overrides provider-level `contextTokens`; use it when you want a smaller effective context budget than the model's native `contextWindow`; `openclaw models list` shows both values when they differ.
550+
- `models.providers.*.models.*.contextWindow`: native context-window metadata for that model.
551+
- `models.providers.*.models.*.contextTokens`: optional active-input cap for that model; use it when you want an effective budget distinct from the model's native `contextWindow`; `openclaw models list` shows both when they differ.
554552

555553
#### Custom provider capability declarations
556554

‎docs/gateway/local-models.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,7 @@ If the model loads cleanly but full agent turns misbehave, work top-down: confir
276276
- **Gateway can't reach the proxy?** `curl http://127.0.0.1:1234/v1/models`.
277277
- **LM Studio model unloaded?** Reload; cold start is a common "hanging" cause.
278278
- **Local server says `terminated`, `ECONNRESET`, or closes the stream mid-turn?** OpenClaw records a low-cardinality `model.call.error.failureKind` plus the OpenClaw process RSS/heap snapshot in diagnostics. For LM Studio/Ollama memory pressure, match that timestamp against the server log or a macOS crash/jetsam log to confirm whether the model server was killed.
279-
- **Context errors?** OpenClaw derives context-window preflight thresholds from the detected model window (or the capped window when `agents.defaults.contextTokens` lowers it), warning below 20% with an **8k** floor and hard-blocking below 10% with a **4k** floor (capped to the effective context window so oversized model metadata can't reject a valid user cap). Lower `contextWindow` or raise the server/model context limit.
279+
- **Context errors?** OpenClaw derives context-window preflight thresholds from the detected model window or the per-model `models.providers.<provider>.models[].contextTokens` cap, warning below 20% with an **8k** floor and hard-blocking below 10% with a **4k** floor. Lower that model entry's `contextTokens` or raise the server/model context limit.
280280
- **`messages[].content ... expected a string`?** Add `compat.requiresStringContent: true` on that model entry.
281281
- **`validation.keys`, or "message entries only allow `role` and `content`"?** Add `compat.strictMessageKeys: true` on that model entry.
282282
- **Direct `/v1/chat/completions` calls work, but `openclaw infer model run --local` fails on Gemma or another local model?** Check the provider URL, model ref, auth marker, and server logs first - `model run` skips agent tools entirely. If `model run` succeeds but larger agent turns fail, reduce the tool surface with `localModelLean` or `compat.supportsTools: false`.

‎docs/plugins/hooks.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -672,9 +672,9 @@ bodies, or provider request IDs. These hooks include stable metadata such as
672672
`durationMs`/`outcome`, and `upstreamRequestIdHash` when OpenClaw can derive a
673673
bounded provider request-id hash. When the runtime has resolved
674674
context-window metadata, the hook event and context also include
675-
`contextTokenBudget`, the effective token budget after model/config/agent
676-
caps, plus `contextWindowSource` and `contextWindowReferenceTokens` when a
677-
lower cap was applied.
675+
`contextTokenBudget`, the effective token budget after model configuration,
676+
fixed model contracts, and runtime discovery, plus `contextWindowSource` and
677+
`contextWindowReferenceTokens` when a lower cap was applied.
678678

679679
`before_agent_finalize` runs only when a harness is about to accept a natural
680680
final assistant answer. It is not the `/stop` cancellation path and does not

‎docs/providers/ollama.md‎

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -574,14 +574,14 @@ Replace model IDs with exact names from `ollama list` or
574574
apiKey: "ollama-local",
575575
api: "ollama",
576576
timeoutSeconds: 300,
577-
contextWindow: 32768,
578577
maxTokens: 8192,
579578
models: [
580579
{
581580
id: "qwen3.5:9b",
582581
name: "qwen3.5:9b",
583582
reasoning: true,
584583
input: ["text"],
584+
contextTokens: 32768,
585585
params: {
586586
num_ctx: 32768,
587587
thinking: false,
@@ -600,9 +600,9 @@ Replace model IDs with exact names from `ollama list` or
600600
}
601601
```
602602

603-
`contextWindow` is OpenClaw's context budget; `params.num_ctx` is sent to
604-
Ollama. Keep them aligned when hardware cannot run the model's full
605-
advertised context.
603+
`contextTokens` caps OpenClaw's active-input budget; `params.num_ctx` sets
604+
Ollama's request context. Keep them aligned when hardware cannot run the
605+
model's full advertised context.
606606

607607
</Accordion>
608608

@@ -694,17 +694,19 @@ Replace model IDs with exact names from `ollama list` or
694694
baseUrl: "http://mini.local:11434",
695695
apiKey: "ollama-local",
696696
api: "ollama",
697-
contextWindow: 32768,
698-
models: [{ id: "gemma4", name: "gemma4", input: ["text"] }],
697+
models: [
698+
{ id: "gemma4", name: "gemma4", input: ["text"], contextTokens: 32768 },
699+
],
699700
},
700701
"ollama-large": {
701702
baseUrl: "http://gpu-box.local:11434",
702703
apiKey: "ollama-local",
703704
api: "ollama",
704705
timeoutSeconds: 420,
705-
contextWindow: 131072,
706706
maxTokens: 16384,
707-
models: [{ id: "qwen3.5:27b", name: "qwen3.5:27b", input: ["text"] }],
707+
models: [
708+
{ id: "qwen3.5:27b", name: "qwen3.5:27b", input: ["text"], contextTokens: 131072 },
709+
],
708710
},
709711
},
710712
},
@@ -749,12 +751,12 @@ Replace model IDs with exact names from `ollama list` or
749751
baseUrl: "http://127.0.0.1:11434",
750752
apiKey: "ollama-local",
751753
api: "ollama",
752-
contextWindow: 32768,
753754
models: [
754755
{
755756
id: "gemma4",
756757
name: "gemma4",
757758
input: ["text"],
759+
contextTokens: 32768,
758760
params: { num_ctx: 32768 },
759761
compat: { supportsTools: false },
760762
},
@@ -956,17 +958,17 @@ For full setup and behavior, see [Ollama Web Search](/tools/ollama-search).
956958
Modelfiles; otherwise it falls back to OpenClaw's default Ollama context
957959
window.
958960

959-
Provider-level `contextWindow`, `contextTokens`, and `maxTokens` set
960-
defaults for every model under that provider and can be overridden per
961-
model. `contextWindow` is OpenClaw's own prompt/compaction budget. Native
961+
Per-model `contextWindow` declares native window metadata, and per-model
962+
`contextTokens` caps active input. Provider-level `maxTokens` remains an
963+
output-token default; a model entry can override it. Native
962964
`/api/chat` requests leave `options.num_ctx` unset unless you set
963965
`params.num_ctx` explicitly, so Ollama applies its own model,
964966
`OLLAMA_CONTEXT_LENGTH`, or VRAM-based default; invalid, zero, negative,
965-
or non-finite `params.num_ctx` values are ignored. If an older config used
966-
only `contextWindow`/`maxTokens` to force native request context, run
967-
`openclaw doctor --fix` to copy those into `params.num_ctx`. The
967+
or non-finite `params.num_ctx` values are ignored. After upgrading an older
968+
configuration, run `openclaw doctor --fix`, then set `params.num_ctx`
969+
explicitly when you need to force native request context. The
968970
OpenAI-compatible adapter still injects `options.num_ctx` by default from
969-
the configured `params.num_ctx` or `contextWindow`; disable with
971+
`params.num_ctx` or the matching model entry's `contextWindow`; disable with
970972
`injectNumCtxForOpenAICompat: false` if the upstream rejects `options`.
971973

972974
Native model entries also accept common Ollama runtime options under
@@ -986,11 +988,11 @@ For full setup and behavior, see [Ollama Web Search](/tools/ollama-search).
986988
models: {
987989
providers: {
988990
ollama: {
989-
contextWindow: 32768,
990991
models: [
991992
{
992993
id: "llama3.3",
993994
contextWindow: 131072,
995+
contextTokens: 32768,
994996
maxTokens: 65536,
995997
params: {
996998
num_ctx: 32768,
@@ -1304,12 +1306,12 @@ For full setup and behavior, see [Ollama Web Search](/tools/ollama-search).
13041306
models: {
13051307
providers: {
13061308
ollama: {
1307-
contextWindow: 32768,
13081309
maxTokens: 8192,
13091310
models: [
13101311
{
13111312
id: "qwen3.5:9b",
13121313
name: "qwen3.5:9b",
1314+
contextTokens: 32768,
13131315
params: { num_ctx: 32768, thinking: false },
13141316
},
13151317
],
@@ -1319,7 +1321,7 @@ For full setup and behavior, see [Ollama Web Search](/tools/ollama-search).
13191321
}
13201322
```
13211323

1322-
Lower `contextWindow` if OpenClaw sends too much prompt. Lower
1324+
Lower the model entry's `contextTokens` if OpenClaw sends too much prompt. Lower
13231325
`params.num_ctx` if Ollama's runtime context is too large for the machine.
13241326
Lower `maxTokens` if generation runs too long.
13251327

‎docs/providers/openai.md‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -479,17 +479,16 @@ for the full example.
479479
OpenClaw treats native model capacity and the active runtime budget as
480480
separate values:
481481

482-
- `contextWindow` declares the provider's total model window.
482+
- `contextWindow` declares the model's native window.
483483
- `contextTokens` caps how much of that window OpenClaw uses for active input.
484484

485485
ChatGPT/Codex OAuth follows the live Codex account catalog. The current
486486
catalog commonly advertises a `272000` token active window for GPT-5.6.
487487
Direct API-key GPT-5.5 and GPT-5.6 models also default to `272000`
488488
`contextTokens`, even though the Platform API exposes a larger native
489489
window. This keeps the normal latency, quality, and cost profile consistent
490-
across auth modes. A configured `agents.defaults.contextTokens` value can
491-
lower that budget further, but it cannot raise a model above its configured
492-
`contextTokens` cap.
490+
across auth modes. Override a direct model's active-input budget with
491+
`models.providers.openai.models[].contextTokens` on that exact model entry.
493492

494493
For direct API-key GPT-5.5 and GPT-5.6, OpenAI documents a `1050000`
495494
token provider window and `128000` maximum output tokens. Reserving the

‎extensions/github-copilot/models.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,9 @@ function compareCopilotStarterCandidates(
179179
if (categoryDelta !== 0) {
180180
return categoryDelta;
181181
}
182-
const contextDelta = right.contextWindow - left.contextWindow;
182+
const contextDelta =
183+
(right.contextWindow ?? DEFAULT_CONTEXT_WINDOW) -
184+
(left.contextWindow ?? DEFAULT_CONTEXT_WINDOW);
183185
if (contextDelta !== 0) {
184186
return contextDelta;
185187
}

‎extensions/lmstudio/src/embedding-provider.test.ts‎

Lines changed: 4 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -118,47 +118,21 @@ describe("createLmstudioEmbeddingProvider preload context length", () => {
118118

119119
it.each([
120120
{
121-
name: "model contextTokens before every fallback",
121+
name: "model contextTokens before its native window",
122122
model: { contextTokens: 4096, contextWindow: 8192 },
123-
provider: { contextTokens: 2048, contextWindow: 16384 },
124123
expected: 4096,
125124
},
126125
{
127-
name: "provider contextTokens as the model's effective cap",
126+
name: "model contextWindow when no active-input cap is set",
128127
model: { contextWindow: 8192 },
129-
provider: { contextTokens: 4096, contextWindow: 16384 },
130-
expected: 4096,
131-
},
132-
{
133-
name: "model contextWindow when below the provider cap",
134-
model: { contextWindow: 8192 },
135-
provider: { contextTokens: 16384, contextWindow: 32768 },
136-
expected: 8192,
137-
},
138-
{
139-
name: "provider contextTokens when the model has no context fields",
140-
provider: { contextTokens: 4096, contextWindow: 16384 },
141-
expected: 4096,
142-
},
143-
{
144-
name: "model contextWindow before provider contextWindow",
145-
model: { contextWindow: 8192 },
146-
provider: { contextWindow: 16384 },
147128
expected: 8192,
148129
},
149-
{
150-
name: "provider contextWindow as the final configured fallback",
151-
provider: { contextWindow: 16384 },
152-
expected: 16384,
153-
},
154130
{
155131
name: "the loader default when no context is configured",
156132
expected: undefined,
157133
},
158-
])("uses $name", async ({ model, provider, expected }) => {
159-
await expect(readRequestedContextLength(buildConfig({ model, provider }))).resolves.toBe(
160-
expected,
161-
);
134+
])("uses $name", async ({ model, expected }) => {
135+
await expect(readRequestedContextLength(buildConfig({ model }))).resolves.toBe(expected);
162136
});
163137

164138
it.each(["lmstudio", "lmstudio-spark"])(

0 commit comments

Comments
 (0)