Skip to content

Commit 58d2b9d

Browse files
committed
fix: add runtime model contextTokens caps
1 parent 45675c1 commit 58d2b9d

25 files changed

Lines changed: 350 additions & 52 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ Docs: https://docs.openclaw.ai
2222
### Fixes
2323

2424
- Providers/OpenAI: preserve native `reasoning.effort: "none"` and strict tool schemas on direct OpenAI-family endpoints, keep OpenAI-compatible proxies on the older compat shim path, and enable OpenAI WebSocket warm-up by default for native Responses routes.
25+
- Providers/OpenAI Codex: split native `contextWindow` from runtime `contextTokens` for `openai-codex/gpt-5.4`, keep the default effective cap at `272000`, and expose a per-model config override via `models.providers.*.models[].contextTokens`.
2526
- Skills/uv install: block workspace `.env` from overriding `UV_PYTHON` and strip related interpreter override keys from uv skill-install subprocesses so repository-controlled env files cannot steer the selected Python runtime. (#59178) Thanks @pgondhi987.
2627
- Telegram/reactions: preserve `reactionNotifications: "own"` across gateway restarts by persisting sent-message ownership state instead of treating cold cache as a permissive fallback. (#59207) Thanks @samzong.
2728
- Gateway/startup: detect PID recycling in gateway lock files on Windows and macOS, and add startup progress so stale lock conflicts no longer block healthy restarts. (#59843) Thanks @TonyDerek-dot.

‎docs/concepts/model-providers.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ For model selection rules, see [/concepts/models](/concepts/models).
1818
- CLI helpers: `openclaw onboard`, `openclaw models list`, `openclaw models set <provider/model>`.
1919
- Fallback runtime rules, cooldown probes, and session-override persistence are
2020
documented in [/concepts/model-failover](/concepts/model-failover).
21+
- `models.providers.*.models[].contextWindow` is native model metadata;
22+
`models.providers.*.models[].contextTokens` is the effective runtime cap.
2123
- Provider plugins can inject model catalogs via `registerProvider({ catalog })`;
2224
OpenClaw merges that output into `models.providers` before writing
2325
`models.json`.
@@ -187,6 +189,7 @@ OpenClaw ships with the pi‑ai catalog. These providers require **no**
187189
- `params.serviceTier` is also forwarded on native Codex Responses requests (`chatgpt.com/backend-api`)
188190
- Shares the same `/fast` toggle and `params.fastMode` config as direct `openai/*`; OpenClaw maps that to `service_tier=priority`
189191
- `openai-codex/gpt-5.3-codex-spark` remains available when the Codex OAuth catalog exposes it; entitlement-dependent
192+
- `openai-codex/gpt-5.4` keeps native `contextWindow = 1050000` and a default runtime `contextTokens = 272000`; override the runtime cap with `models.providers.openai-codex.models[].contextTokens`
190193
- Policy note: OpenAI Codex OAuth is explicitly supported for external tools/workflows like OpenClaw.
191194

192195
```json5
@@ -195,6 +198,18 @@ OpenClaw ships with the pi‑ai catalog. These providers require **no**
195198
}
196199
```
197200

201+
```json5
202+
{
203+
models: {
204+
providers: {
205+
"openai-codex": {
206+
models: [{ id: "gpt-5.4", contextTokens: 160000 }],
207+
},
208+
},
209+
},
210+
}
211+
```
212+
198213
### Other subscription-style hosted options
199214

200215
- [Qwen / Model Studio](/providers/qwen_modelstudio): Alibaba Cloud Standard pay-as-you-go and Coding Plan subscription endpoints

‎docs/gateway/configuration-reference.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2186,6 +2186,7 @@ OpenClaw uses the built-in model catalog. Add custom providers via `models.provi
21862186
input: ["text"],
21872187
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
21882188
contextWindow: 128000,
2189+
contextTokens: 96000,
21892190
maxTokens: 32000,
21902191
},
21912192
],
@@ -2204,6 +2205,7 @@ OpenClaw uses the built-in model catalog. Add custom providers via `models.provi
22042205
- SecretRef-managed provider header values are refreshed from source markers (`secretref-env:ENV_VAR_NAME` for env refs, `secretref-managed` for file/exec refs).
22052206
- Empty or missing agent `apiKey`/`baseUrl` fall back to `models.providers` in config.
22062207
- Matching model `contextWindow`/`maxTokens` use the higher value between explicit config and implicit catalog values.
2208+
- Matching model `contextTokens` preserves an explicit runtime cap when present; use it to limit effective context without changing native model metadata.
22072209
- Use `models.mode: "replace"` when you want config to fully rewrite `models.json`.
22082210
- Marker persistence is source-authoritative: markers are written from the active source config snapshot (pre-resolution), not from resolved runtime secret values.
22092211

@@ -2219,6 +2221,8 @@ OpenClaw uses the built-in model catalog. Add custom providers via `models.provi
22192221
- `models.providers.*.baseUrl`: upstream API base URL.
22202222
- `models.providers.*.headers`: extra static headers for proxy/tenant routing.
22212223
- `models.providers.*.models`: explicit provider model catalog entries.
2224+
- `models.providers.*.models.*.contextWindow`: native model context window metadata.
2225+
- `models.providers.*.models.*.contextTokens`: optional runtime context cap. Use this when you want a smaller effective context budget than the model's native `contextWindow`.
22222226
- `models.providers.*.models.*.compat.supportsDeveloperRole`: optional compatibility hint. For `api: "openai-completions"` with a non-empty non-native `baseUrl` (host not `api.openai.com`), OpenClaw forces this to `false` at runtime. Empty/omitted `baseUrl` keeps default OpenAI behavior.
22232227
- `models.bedrockDiscovery`: Bedrock auto-discovery settings root.
22242228
- `models.bedrockDiscovery.enabled`: turn discovery polling on/off.

‎docs/providers/openai.md‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,41 @@ discovers it. Treat it as entitlement-dependent and experimental: Codex Spark is
143143
separate from GPT-5.4 `/fast`, and availability depends on the signed-in Codex /
144144
ChatGPT account.
145145

146+
### Codex context window cap
147+
148+
OpenClaw treats the Codex model metadata and the runtime context cap as separate
149+
values.
150+
151+
For `openai-codex/gpt-5.4`:
152+
153+
- native `contextWindow`: `1050000`
154+
- default runtime `contextTokens` cap: `272000`
155+
156+
That keeps model metadata truthful while preserving the smaller default runtime
157+
window that has better latency and quality characteristics in practice.
158+
159+
If you want a different effective cap, set `models.providers.<provider>.models[].contextTokens`:
160+
161+
```json5
162+
{
163+
models: {
164+
providers: {
165+
"openai-codex": {
166+
models: [
167+
{
168+
id: "gpt-5.4",
169+
contextTokens: 160000,
170+
},
171+
],
172+
},
173+
},
174+
},
175+
}
176+
```
177+
178+
Use `contextWindow` only when you are declaring or overriding native model
179+
metadata. Use `contextTokens` when you want to limit the runtime context budget.
180+
146181
### Transport default
147182

148183
OpenClaw uses `pi-ai` for model streaming. For both `openai/*` and

‎extensions/openai/openai-codex-provider.test.ts‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,4 +86,69 @@ describe("openai codex provider", () => {
8686
"Deprecated profile. Run `openclaw models auth login --provider openai-codex` or `openclaw configure`.",
8787
);
8888
});
89+
90+
it("resolves gpt-5.4 with native contextWindow plus default contextTokens cap", () => {
91+
const provider = buildOpenAICodexProviderPlugin();
92+
93+
const model = provider.resolveDynamicModel?.({
94+
provider: "openai-codex",
95+
modelId: "gpt-5.4",
96+
modelRegistry: {
97+
find: vi.fn((providerId: string, modelId: string) => {
98+
if (providerId === "openai-codex" && modelId === "gpt-5.3-codex") {
99+
return {
100+
id: "gpt-5.3-codex",
101+
name: "gpt-5.3-codex",
102+
provider: "openai-codex",
103+
api: "openai-codex-responses",
104+
baseUrl: "https://chatgpt.com/backend-api",
105+
reasoning: true,
106+
input: ["text", "image"],
107+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
108+
contextWindow: 272_000,
109+
maxTokens: 128_000,
110+
};
111+
}
112+
return null;
113+
}),
114+
},
115+
});
116+
117+
expect(model).toMatchObject({
118+
id: "gpt-5.4",
119+
contextWindow: 1_050_000,
120+
contextTokens: 272_000,
121+
maxTokens: 128_000,
122+
});
123+
});
124+
125+
it("augments catalog with gpt-5.4 native contextWindow and runtime cap", () => {
126+
const provider = buildOpenAICodexProviderPlugin();
127+
128+
const entries = provider.augmentModelCatalog?.({
129+
provider: "openai-codex",
130+
entries: [
131+
{
132+
id: "gpt-5.3-codex",
133+
name: "gpt-5.3-codex",
134+
provider: "openai-codex",
135+
api: "openai-codex-responses",
136+
baseUrl: "https://chatgpt.com/backend-api",
137+
reasoning: true,
138+
input: ["text", "image"],
139+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
140+
contextWindow: 272_000,
141+
maxTokens: 128_000,
142+
},
143+
],
144+
});
145+
146+
expect(entries).toContainEqual(
147+
expect.objectContaining({
148+
id: "gpt-5.4",
149+
contextWindow: 1_050_000,
150+
contextTokens: 272_000,
151+
}),
152+
);
153+
});
89154
});

‎extensions/openai/openai-codex-provider.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,8 @@ import { wrapOpenAICodexProviderStream } from "./stream-hooks.js";
3333
const PROVIDER_ID = "openai-codex";
3434
const OPENAI_CODEX_BASE_URL = "https://chatgpt.com/backend-api";
3535
const OPENAI_CODEX_GPT_54_MODEL_ID = "gpt-5.4";
36-
const OPENAI_CODEX_GPT_54_CONTEXT_TOKENS = 400_000;
36+
const OPENAI_CODEX_GPT_54_NATIVE_CONTEXT_TOKENS = 1_050_000;
37+
const OPENAI_CODEX_GPT_54_DEFAULT_CONTEXT_TOKENS = 272_000;
3738
const OPENAI_CODEX_GPT_54_MAX_TOKENS = 128_000;
3839
const OPENAI_CODEX_GPT_54_COST = {
3940
input: 2.5,
@@ -100,7 +101,8 @@ function resolveCodexForwardCompatModel(
100101
if (lower === OPENAI_CODEX_GPT_54_MODEL_ID) {
101102
templateIds = OPENAI_CODEX_GPT_54_TEMPLATE_MODEL_IDS;
102103
patch = {
103-
contextWindow: OPENAI_CODEX_GPT_54_CONTEXT_TOKENS,
104+
contextWindow: OPENAI_CODEX_GPT_54_NATIVE_CONTEXT_TOKENS,
105+
contextTokens: OPENAI_CODEX_GPT_54_DEFAULT_CONTEXT_TOKENS,
104106
maxTokens: OPENAI_CODEX_GPT_54_MAX_TOKENS,
105107
cost: OPENAI_CODEX_GPT_54_COST,
106108
};
@@ -140,6 +142,7 @@ function resolveCodexForwardCompatModel(
140142
input: ["text", "image"],
141143
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
142144
contextWindow: patch?.contextWindow ?? DEFAULT_CONTEXT_TOKENS,
145+
contextTokens: patch?.contextTokens,
143146
maxTokens: patch?.maxTokens ?? DEFAULT_CONTEXT_TOKENS,
144147
} as ProviderRuntimeModel)
145148
);
@@ -217,6 +220,7 @@ function buildSyntheticCatalogEntry(
217220
reasoning: boolean;
218221
input: readonly ("text" | "image")[];
219222
contextWindow: number;
223+
contextTokens?: number;
220224
},
221225
) {
222226
if (!template) {
@@ -229,6 +233,7 @@ function buildSyntheticCatalogEntry(
229233
reasoning: entry.reasoning,
230234
input: [...entry.input],
231235
contextWindow: entry.contextWindow,
236+
...(entry.contextTokens === undefined ? {} : { contextTokens: entry.contextTokens }),
232237
};
233238
}
234239

@@ -312,7 +317,8 @@ export function buildOpenAICodexProviderPlugin(): ProviderPlugin {
312317
id: OPENAI_CODEX_GPT_54_MODEL_ID,
313318
reasoning: true,
314319
input: ["text", "image"],
315-
contextWindow: OPENAI_CODEX_GPT_54_CONTEXT_TOKENS,
320+
contextWindow: OPENAI_CODEX_GPT_54_NATIVE_CONTEXT_TOKENS,
321+
contextTokens: OPENAI_CODEX_GPT_54_DEFAULT_CONTEXT_TOKENS,
316322
}),
317323
buildSyntheticCatalogEntry(sparkTemplate, {
318324
id: OPENAI_CODEX_GPT_53_SPARK_MODEL_ID,

‎src/agents/compaction.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -524,5 +524,7 @@ export function pruneHistoryForContextShare(params: {
524524
}
525525

526526
export function resolveContextWindowTokens(model?: ExtensionContext["model"]): number {
527-
return Math.max(1, Math.floor(model?.contextWindow ?? DEFAULT_CONTEXT_TOKENS));
527+
const effective =
528+
(model as { contextTokens?: number } | undefined)?.contextTokens ?? model?.contextWindow;
529+
return Math.max(1, Math.floor(effective ?? DEFAULT_CONTEXT_TOKENS));
528530
}

‎src/agents/context-window-guard.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,45 @@ describe("context-window-guard", () => {
8585
expect(guard.shouldBlock).toBe(true);
8686
});
8787

88+
it("prefers models.providers.*.models[].contextTokens over contextWindow", () => {
89+
const cfg = {
90+
models: {
91+
providers: {
92+
openrouter: {
93+
baseUrl: "http://localhost",
94+
apiKey: "x",
95+
models: [
96+
{
97+
id: "tiny",
98+
name: "tiny",
99+
reasoning: false,
100+
input: ["text"],
101+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
102+
contextWindow: 1_050_000,
103+
contextTokens: 12_000,
104+
maxTokens: 256,
105+
},
106+
],
107+
},
108+
},
109+
},
110+
} satisfies OpenClawConfig;
111+
112+
const info = resolveContextWindowInfo({
113+
cfg,
114+
provider: "openrouter",
115+
modelId: "tiny",
116+
modelContextWindow: 64_000,
117+
modelContextTokens: 48_000,
118+
defaultTokens: 200_000,
119+
});
120+
121+
expect(info).toEqual({
122+
source: "modelsConfig",
123+
tokens: 12_000,
124+
});
125+
});
126+
88127
it("normalizes provider aliases when reading models config context windows", () => {
89128
const cfg = {
90129
models: {

‎src/agents/context-window-guard.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,19 +23,25 @@ export function resolveContextWindowInfo(params: {
2323
cfg: OpenClawConfig | undefined;
2424
provider: string;
2525
modelId: string;
26+
modelContextTokens?: number;
2627
modelContextWindow?: number;
2728
defaultTokens: number;
2829
}): ContextWindowInfo {
2930
const fromModelsConfig = (() => {
3031
const providers = params.cfg?.models?.providers as
31-
| Record<string, { models?: Array<{ id?: string; contextWindow?: number }> }>
32+
| Record<
33+
string,
34+
{ models?: Array<{ id?: string; contextTokens?: number; contextWindow?: number }> }
35+
>
3236
| undefined;
3337
const providerEntry = findNormalizedProviderValue(providers, params.provider);
3438
const models = Array.isArray(providerEntry?.models) ? providerEntry.models : [];
3539
const match = models.find((m) => m?.id === params.modelId);
36-
return normalizePositiveInt(match?.contextWindow);
40+
return normalizePositiveInt(match?.contextTokens) ?? normalizePositiveInt(match?.contextWindow);
3741
})();
38-
const fromModel = normalizePositiveInt(params.modelContextWindow);
42+
const fromModel =
43+
normalizePositiveInt(params.modelContextTokens) ??
44+
normalizePositiveInt(params.modelContextWindow);
3945
const baseInfo = fromModelsConfig
4046
? { tokens: fromModelsConfig, source: "modelsConfig" as const }
4147
: fromModel

‎src/agents/context.lookup.test.ts‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
22

3-
type DiscoveredModel = { id: string; contextWindow: number };
3+
type DiscoveredModel = { id: string; contextWindow?: number; contextTokens?: number };
44
type ContextModule = typeof import("./context.js");
55

66
function mockContextDeps(params: {
@@ -120,6 +120,21 @@ describe("lookupContextTokens", () => {
120120
);
121121
});
122122

123+
it("prefers config contextTokens over contextWindow on first lookup", async () => {
124+
mockContextModuleDeps(() => ({
125+
models: {
126+
providers: {
127+
"openai-codex": {
128+
models: [{ id: "gpt-5.4", contextWindow: 1_050_000, contextTokens: 272_000 }],
129+
},
130+
},
131+
},
132+
}));
133+
134+
const { lookupContextTokens } = await importContextModule();
135+
expect(lookupContextTokens("gpt-5.4", { allowAsyncLoad: false })).toBe(272_000);
136+
});
137+
123138
it("rehydrates config-backed cache entries after module reload when runtime config survives", async () => {
124139
const firstLoadConfigMock = vi.fn(() => ({
125140
models: {

0 commit comments

Comments
 (0)