Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(codex): 让模型上下文设置实际生效并自动恢复压缩失败 (#4016)

Chris Zhange17d32d7fe64
diff --git a/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts b/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts
index fb7866bdf6..292965ce71 100644
--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts
@@ -132,7 +132,8 @@ describe('active-catalog discovered augment', () => {
expect(projected).toMatchObject({
id: 'chatgpt/gpt-5.7',
piApi: 'openai-responses',
- contextWindow: 400_000,
+ contextWindow: 272_000,
+ contextWindowMax: 400_000,
});
});
@@ -379,7 +380,7 @@ describe('active-catalog discovered augment', () => {
// 动态快照决定存在性,且明确返回的运行时能力高于 registry 基线。
const openai = getActiveCatalog().providers.find((p) => p.id === 'openai');
expect((openai?.models.codex ?? []).find((m) => m.id === 'gpt-5.5')?.contextWindow).toBe(
- 400000,
+ 272000,
);
});
@@ -391,7 +392,7 @@ describe('active-catalog discovered augment', () => {
const openai = getActiveCatalog().providers.find((p) => p.id === 'openai');
const m55 = (openai?.models.codex ?? []).find((m) => m.id === 'gpt-5.5');
// 动态快照决定存在性和明确能力;legacy 静态条目不复活。
- expect(m55?.contextWindow).toBe(400000);
+ expect(m55).toMatchObject({ contextWindow: 272000, contextWindowMax: 400000 });
});
it('paired projection 使用同一纯名称和 sortOrder,且按 sortOrder 稳定排序', () => {
diff --git a/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts b/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts
index bd052d31b4..ee7b75bf1c 100644
--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts
@@ -37,6 +37,30 @@ afterEach(() => {
});
describe('XD 网关权威模型清单重建', () => {
+ it('defaults every maintained GPT route to 272K while retaining capacity and smaller/non-GPT windows', () => {
+ const ids = [
+ 'codex/gpt-6-astra', 'openai/gpt-6-astra',
+ 'codex/gpt-5.6-sol', 'codex/gpt-5.6-terra', 'codex/gpt-5.6-luna',
+ 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna',
+ 'codex/gpt-5.5', 'codex/gpt-5.5:auto', 'gpt-5.5',
+ 'gpt-5.4', 'gpt-5.4-mini', 'gpt-5.4-nano', 'codex/gpt-5.4-mini',
+ ];
+ setActiveCatalog(BUNDLED_CATALOG);
+ setXdGatewayModels([
+ ...ids.map(id => ({ id, name: id, agents: ['claude-code', 'codex', 'pi'] as const,
+ contextWindow: 1_050_000 })),
+ { id: 'gpt-4-small', agents: ['codex'] as const, contextWindow: 128_000 },
+ { id: 'z-ai/glm-5.3-flash', agents: ['codex'] as const, contextWindow: 1_000_000 },
+ ].map(m => ({ ...m, agents: [...m.agents] })));
+ for (const agent of ['claude-code', 'codex', 'pi'] as const) {
+ for (const id of ids) expect(xdModels(agent).find(m => m.id === id)).toMatchObject({
+ contextWindow: 272_000, contextWindowMax: 1_050_000,
+ });
+ }
+ expect(xdModels('codex').find(m => m.id === 'gpt-4-small')?.contextWindow).toBe(128_000);
+ expect(xdModels('codex').find(m => m.id === 'z-ai/glm-5.3-flash')?.contextWindow).toBe(1_000_000);
+ });
+
it('未拉到实时清单时不暴露任何 XD 模型', () => {
setActiveCatalog(BUNDLED_CATALOG);
expect(xdModels('claude-code')).toEqual([]);
@@ -514,7 +538,8 @@ describe('XD 网关权威模型清单重建', () => {
expect(list[0]).toMatchObject({
name: 'GPT-5.6-Sol',
group: 'gpt-budget',
- contextWindow: 372_000,
+ contextWindow: 272_000,
+ contextWindowMax: 372_000,
efforts: ['low', 'medium', 'high', 'xhigh'],
defaultEffort: 'medium',
});
@@ -567,7 +592,7 @@ describe('XD 网关权威模型清单重建', () => {
expect(xdModels('codex').map((model) => model.id)).toEqual(['chat-model']);
});
- it('perAgent 覆盖块按 tab 应用(cc 无 Fast + 1M 窗口;codex 保持基线)', () => {
+ it('perAgent Fast 差异保留,GPT 工作窗口采用保守默认', () => {
setActiveCatalog(BUNDLED_CATALOG);
setXdGatewayModels([
{
@@ -583,7 +608,7 @@ describe('XD 网关权威模型清单重建', () => {
]);
const cc = xdModels('claude-code')[0];
const codex = xdModels('codex')[0];
- expect(cc).toMatchObject({ contextWindow: 1_000_000, supportsFastMode: false });
+ expect(cc).toMatchObject({ contextWindow: 272_000, supportsFastMode: false });
expect(codex).toMatchObject({ contextWindow: 272_000, supportsFastMode: true });
// 覆盖块没动的字段沿用基线。
expect(cc.efforts).toEqual(['low', 'medium', 'high', 'xhigh']);
diff --git a/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts b/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts
index 0d1e429c0a..2b31d39b71 100644
--- a/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts
@@ -22,7 +22,7 @@ import {
resolvePiGatewayDescriptorProviderId,
resolvePiRuntimeModelDescriptor,
resolveVerifiedContextWindow,
- resolveExplicitCustomContextWindow,
+ resolveModelDefaultContextWindow,
} from '../catalog-to-descriptors.js';
import { sanitizeModelCatalogOverrides } from '../model-plane/localCatalogOverrides.js';
@@ -769,7 +769,7 @@ describe('resolveVerifiedContextWindow — 按路由解析已核实窗口', () =
});
});
-describe('resolveExplicitCustomContextWindow — 只注入用户显式填写的自定义窗口', () => {
+describe('resolveModelDefaultContextWindow — settings defaults configure the same native route', () => {
function catalogWithCustom(solContextWindow?: number): Catalog {
const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
catalog.providers.push(
@@ -797,34 +797,33 @@ describe('resolveExplicitCustomContextWindow — 只注入用户显式填写的
it('用户显式填写的窗口返回该值', () => {
const catalog = catalogWithCustom(1_050_000);
expect(
- resolveExplicitCustomContextWindow(catalog, 'codex', 'mygpt', 'gpt-5.6-sol'),
+ resolveModelDefaultContextWindow(catalog, 'codex', 'mygpt', 'gpt-5.6-sol'),
).toBe(1_050_000);
});
- it('未填写窗口的自定义模型不注入(200K 展示兜底)', () => {
+ it('applies the displayed default for custom models without a saved override', () => {
const catalog = catalogWithCustom();
- expect(
- resolveExplicitCustomContextWindow(catalog, 'codex', 'mygpt', 'gpt-5.6-sol'),
- ).toBeNull();
- expect(
- resolveExplicitCustomContextWindow(catalog, 'codex', 'mygpt', 'gpt-5.4-mini'),
- ).toBeNull();
+ expect(resolveModelDefaultContextWindow(catalog, 'codex', 'mygpt', 'gpt-5.6-sol')).toBe(200_000);
});
- it('官方 / 网关路由不注入', () => {
- const catalog = catalogWithCustom(1_050_000);
- expect(
- resolveExplicitCustomContextWindow(catalog, 'codex', 'xd', 'gpt-5.6-sol'),
- ).toBeNull();
- expect(
- resolveExplicitCustomContextWindow(catalog, 'codex', 'openai', 'gpt-5.6-sol'),
- ).toBeNull();
+ it('applies Gateway and subscription defaults independently for the same model id', () => {
+ const catalog = catalogWithCustom(500_000);
+ for (const [id, window] of [['xd', 1_050_000], ['openai', 272_000]] as const) {
+ const provider = catalog.providers.find(p => p.id === id)!;
+ const model = catalog.providers.find(p => p.id === 'mygpt')!.models.codex![0]!;
+ provider.models.codex = [{ ...model, contextWindow: window }];
+ expect(resolveModelDefaultContextWindow(catalog, 'codex', id, model.id)).toBe(window);
+ }
+ expect(resolveModelDefaultContextWindow(catalog, 'codex', 'mygpt', 'gpt-5.6-sol')).toBe(500_000);
+ expect(resolveModelDefaultContextWindow(catalog, 'codex', 'xd', 'missing')).toBeNull();
+ catalog.providers.find(p => p.id === 'xd')!.routing.codex!.disabled = true;
+ expect(resolveModelDefaultContextWindow(catalog, 'codex', 'xd', 'gpt-5.6-sol')).toBeNull();
});
it('没有 providerId 不注入', () => {
const catalog = catalogWithCustom(1_050_000);
expect(
- resolveExplicitCustomContextWindow(catalog, 'codex', null, 'gpt-5.6-sol'),
+ resolveModelDefaultContextWindow(catalog, 'codex', null, 'gpt-5.6-sol'),
).toBeNull();
});
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexContextWindow.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexContextWindow.test.ts
new file mode 100644
index 0000000000..19d986ff45
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/codexContextWindow.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest';
+import { resolveCodexContextWindowInfo } from '../codex-context-window';
+const sol = { context_window: 272_000, max_context_window: 872_000, effective_context_window_percent: 95 };
+describe('native Codex context facts', () => {
+ it('keeps total, usable capacity and compaction distinct', () => {
+ expect(resolveCodexContextWindowInfo(sol, {}, 258_400)).toEqual({
+ contextWindow: 272_000, usableContextWindow: 258_400, autoCompactTokenLimit: 244_800,
+ modelMaxContextWindow: 872_000, source: 'runtime', fallbackModel: false,
+ });
+ });
+ it('clips CLI overrides to the native maximum and supports earlier compaction', () => {
+ expect(resolveCodexContextWindowInfo(sol, { model_context_window: 1_000_000, model_auto_compact_token_limit: 400_000 }))
+ .toMatchObject({ contextWindow: 872_000, usableContextWindow: 828_400, autoCompactTokenLimit: 400_000 });
+ });
+ it('preserves the running thread when defaults change', () => {
+ expect(resolveCodexContextWindowInfo(sol, { model_context_window: 500_000 }, 258_400))
+ .toMatchObject({ contextWindow: 272_000, usableContextWindow: 258_400 });
+ });
+ it('uses the model headroom instead of always dividing by 95%', () => {
+ expect(resolveCodexContextWindowInfo({ ...sol, context_window: 128_000, effective_context_window_percent: 100 }, {}, 128_000))
+ .toMatchObject({ contextWindow: 128_000, usableContextWindow: 128_000 });
+ });
+ it('does not treat GLM configured 500K as native support', () => {
+ expect(resolveCodexContextWindowInfo(undefined, { model_context_window: 500_000 }))
+ .toMatchObject({ contextWindow: 272_000, fallbackModel: true });
+ });
+ it('honors an installed native catalog for a third-party model', () => {
+ expect(resolveCodexContextWindowInfo({ context_window: 500_000, max_context_window: 500_000 }, {}))
+ .toMatchObject({ contextWindow: 500_000, usableContextWindow: 475_000, fallbackModel: false });
+ });
+ it('does not invent capacity from invalid native metadata', () => {
+ expect(resolveCodexContextWindowInfo({ context_window: 0 }, {})).toBeNull();
+ expect(resolveCodexContextWindowInfo({ ...sol, effective_context_window_percent: 0 }, {}, 258_400)).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexCredentialSwitch.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexCredentialSwitch.test.ts
index 844b08dfad..1dcb7bee5e 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexCredentialSwitch.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexCredentialSwitch.test.ts
@@ -50,6 +50,13 @@ describe('shouldCloseSessionForCredentialSwitch codex mode', () => {
})).toBe(false);
});
+ it('keeps a task on its sticky native summary fallback', () => {
+ expect(isCodexThreadModelProviderIdentityMismatch({ agentKind: 'codex',
+ currentProviderId: 'xd', nextProviderId: 'xd', currentModel: 'codex/gpt-6-astra', nextModel: 'codex/gpt-6-astra',
+ currentCodexProxyActive: true, currentCodexThreadModelProviderId: 'cindy_summary',
+ })).toBe(false);
+ });
+
it('keeps a matching Cindy Codex remote-compaction thread for Cindy codex model changes', () => {
const input = {
agentKind: 'codex',
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexCustomContextCatalog.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexCustomContextCatalog.test.ts
index e13c4c6b96..e165b50c0e 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexCustomContextCatalog.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexCustomContextCatalog.test.ts
@@ -3,11 +3,13 @@ import os from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
+import nativeFallbackPrompt from '../codex-native-fallback-prompt.md?raw';
import {
- bundledCodexCatalogHasModel,
extractBundledCodexModelCatalog,
prepareCodexCustomContextCatalog,
+ patchCodexModelMaxContextWindow,
+ nativeCodexFallbackModel,
} from '../codex-custom-context-catalog.js';
const tempRoots: string[] = [];
@@ -108,19 +110,6 @@ describe('Codex custom context model catalog', () => {
]);
});
- it('preflights catalog membership without synthesizing unknown model metadata', async () => {
- const { binaryPath } = await createFixtureBinary({
- models: [{ slug: 'gpt-5.6-sol', context_window: 272_000, max_context_window: 272_000 }],
- });
-
- await expect(bundledCodexCatalogHasModel(binaryPath, 'gpt-5.6-sol', {
- scanChunkBytes: 64,
- })).resolves.toBe(true);
- await expect(bundledCodexCatalogHasModel(binaryPath, 'MiniMax-M3', {
- scanChunkBytes: 64,
- })).resolves.toBe(false);
- });
-
it('patches an in-memory smart catalog while preserving routed models and the exact bundled root descriptor', async () => {
const bundledRoot = {
slug: 'gpt-5.6-sol',
@@ -161,7 +150,7 @@ describe('Codex custom context model catalog', () => {
});
});
- it('fails closed when the exact real model slug is absent', async () => {
+ it('fails visibly if an unknown model fallback cannot be verified against this binary', async () => {
const { root, binaryPath } = await createFixtureBinary({
models: [{ slug: 'gpt-5.4', context_window: 272_000, max_context_window: 272_000 }],
});
@@ -172,7 +161,54 @@ describe('Codex custom context model catalog', () => {
modelId: 'gpt-5.6-sol',
contextWindow: 700_000,
scanChunkBytes: 64,
- })).rejects.toThrow('exactly one model named "gpt-5.6-sol"');
+ })).rejects.toThrow('native fallback metadata changed');
+ });
+
+ it('uses a newly discovered GPT model absent from the installed binary', async () => {
+ const { root, binaryPath } = await createFixtureBinary({ models: [{ slug: 'gpt-5.4' }] });
+ const native = { slug: 'gpt-6-astra', context_window: 272_000, max_context_window: 872_000,
+ model_messages: { instructions_template: 'latest native prompt' }, comp_hash: 'native-compaction-id' };
+ await fs.writeFile(path.join(root, 'models_cache.json'), JSON.stringify({ models: [native] }));
+ const result = await prepareCodexCustomContextCatalog({ binaryPath, codexHome: root,
+ modelId: 'codex/gpt-6-astra', contextWindow: 1_000_000, scanChunkBytes: 64 });
+ const catalog = JSON.parse(await fs.readFile(result.catalogPath, 'utf8'));
+ expect(catalog.models).toContainEqual({ ...native, slug: 'codex/gpt-6-astra', max_context_window: 1_000_000 });
+ expect(catalog.models).toContainEqual(native);
+ });
+
+ it.each(['\n', '\r\n'] as const)('preserves verified native unknown-model behavior with %j line endings', async (lineEnding) => {
+ const { root, binaryPath } = await createFixtureBinary({ models: [{ slug: 'gpt-5.4' }] }, lineEnding);
+ const instructions = nativeFallbackPrompt.replace(/\r?\n/g, lineEnding);
+ await fs.appendFile(binaryPath, instructions);
+ const result = await prepareCodexCustomContextCatalog({ binaryPath, codexHome: root,
+ modelId: 'glm-5.3', contextWindow: 500_000, scanChunkBytes: 64 });
+ const catalog = JSON.parse(await fs.readFile(result.catalogPath, 'utf8'));
+ expect(catalog.models[1]).toEqual({ ...nativeCodexFallbackModel('glm-5.3', instructions), max_context_window: 500_000 });
+ });
+
+ it('keeps user-owned catalog instructions untouched', async () => {
+ const { root, binaryPath } = await createFixtureBinary({ models: [{ slug: 'gpt-5.4' }] });
+ const native = { slug: 'glm', base_instructions: '## Planning\nYou have access to an `update_plan` tool\nUser-owned text.\n' };
+ await fs.writeFile(path.join(root, 'custom.json'), JSON.stringify({ models: [native] }));
+ await fs.writeFile(path.join(root, 'config.toml'), 'model_catalog_json = "custom.json"');
+ const result = await prepareCodexCustomContextCatalog({ binaryPath, codexHome: root,
+ modelId: 'glm', contextWindow: 500_000, scanChunkBytes: 64 });
+ const catalog = JSON.parse(await fs.readFile(result.catalogPath, 'utf8'));
+ expect(catalog.models[0]).toEqual({ ...native, max_context_window: 500_000 });
+ });
+
+ it('keeps wire aliases independent and preserves native instructions and tools', () => {
+ const native = { slug: 'gpt-6-astra', context_window: 272_000, max_context_window: 872_000,
+ model_messages: { instructions_template: 'native prompt' }, shell_type: 'unified_exec', comp_hash: 'opaque' };
+ const result = patchCodexModelMaxContextWindow({ models: [native] }, 'codex/gpt-6-astra', 1_000_000);
+ expect(result.models[0]).toEqual(native);
+ expect(result.models[1]).toEqual({ ...native, slug: 'codex/gpt-6-astra', max_context_window: 1_000_000 });
+ });
+
+ it('uses native unknown-model defaults for GLM instead of cloning GPT behavior', () => {
+ const result = patchCodexModelMaxContextWindow({ models: [{ slug: 'gpt-5.4', multi_agent_version: 'v2' }] }, 'glm-5.3', 500_000);
+ expect(result.models[1]).toEqual({ ...nativeCodexFallbackModel('glm-5.3'), max_context_window: 500_000 });
+ expect(result.models[1].multi_agent_version).toBeUndefined();
});
it('reuses one immutable catalog across concurrent session starts', async () => {
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
index 2aa2c7fe8e..412fac7259 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
@@ -336,6 +336,16 @@ describe('withCodexUpstreamRecording', () => {
});
describe('codex gateway config', () => {
+ it.each(['oauth-bearer', 'env-key', 'provider-oauth'] as const)('summary fallback preserves %s credentials and endpoint', async (mode) => {
+ const { buildCodexProxySpawnArgs } = await import('../codex-gateway-config.js');
+ const args = buildCodexProxySpawnArgs('http://127.0.0.1:12345', mode);
+ const provider = (id: string) => Object.fromEntries(args.filter(v => v.startsWith(`model_providers.${id}.`))
+ .map(v => { const [key, ...value] = v.slice(`model_providers.${id}.`.length).split('='); return [key, value.join('=')]; }));
+ const gateway = provider('cindy_gateway');
+ expect(provider('cindy_summary')).toEqual({ ...gateway, name: '"Cindy Summary"' });
+ expect(provider('cindy_codex').name).toBe('"OpenAI"');
+ });
+
it('所有认证模式都让缺少 model metadata 的 Codex 模型使用 CodeModeOnly', async () => {
const { buildCodexProxySpawnArgs } = await import('../codex-gateway-config.js');
diff --git a/apps/desktop/src/main/maker-host/__tests__/model-context-limit-store.test.ts b/apps/desktop/src/main/maker-host/__tests__/model-context-limit-store.test.ts
index 68cf50229b..cd34455d7b 100644
--- a/apps/desktop/src/main/maker-host/__tests__/model-context-limit-store.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/model-context-limit-store.test.ts
@@ -31,6 +31,7 @@ import {
resetModelContextLimits,
writeModelContextLimit,
writeModelContextLimits,
+ writeModelContextLimitsWithRefresh,
} from '../model-context-limit-store';
const PREFS = path.join(tempRoot, 'test-owner', 'model-context-limit-prefs.json');
@@ -48,6 +49,49 @@ describe('model context limit store', () => {
__testing.invalidate();
});
+ it.each([1_000_000, null])('rolls back failed refresh for limit %s, including mixed/absent aliases', async (limit) => {
+ const targets = [
+ { agent: 'codex' as const, providerId: 'xd', modelId: 'gpt' },
+ { agent: 'pi' as const, providerId: 'xd', modelId: 'gpt' },
+ { agent: 'claude-code' as const, providerId: 'xd', modelId: 'gpt' },
+ ];
+ writeModelContextLimit('codex', 'xd', 'gpt', 272_000);
+ writeModelContextLimit('pi', 'xd', 'gpt', 500_000);
+ await expect(writeModelContextLimitsWithRefresh(targets, limit, async () => {
+ expect(readModelContextLimit('codex', 'xd', 'gpt')).toBe(limit);
+ writeModelContextLimit('codex', 'xd', 'unrelated', 128_000);
+ throw new Error('runtime close failed');
+ })).rejects.toThrow('runtime close failed');
+ expect(readModelContextLimit('codex', 'xd', 'gpt')).toBe(272_000);
+ expect(readModelContextLimit('pi', 'xd', 'gpt')).toBe(500_000);
+ expect(readModelContextLimit('claude-code', 'xd', 'gpt')).toBeNull();
+ expect(readModelContextLimit('codex', 'xd', 'unrelated')).toBe(128_000);
+ });
+
+ it('rolls back the original owner after an account switch without changing the new owner', async () => {
+ const target = { agent: 'codex' as const, providerId: 'xd', modelId: 'gpt' };
+ writeModelContextLimit('codex', 'xd', 'gpt', 272_000);
+ await expect(writeModelContextLimitsWithRefresh([target], 1_000_000, async () => {
+ ownerId = 'other-owner';
+ writeModelContextLimit('codex', 'xd', 'gpt', 500_000);
+ throw new Error('account changed');
+ })).rejects.toThrow('account changed');
+ expect(readModelContextLimit('codex', 'xd', 'gpt')).toBe(500_000);
+ ownerId = 'test-owner';
+ expect(readModelContextLimit('codex', 'xd', 'gpt')).toBe(272_000);
+ });
+
+ it('keeps successful changes and never overwrites a newer external edit on rollback', async () => {
+ const target = { agent: 'codex' as const, providerId: 'xd', modelId: 'gpt' };
+ await writeModelContextLimitsWithRefresh([target], 1_000_000, async () => {});
+ expect(readModelContextLimit('codex', 'xd', 'gpt')).toBe(1_000_000);
+ await expect(writeModelContextLimitsWithRefresh([target], 272_000, async () => {
+ writeModelContextLimit('codex', 'xd', 'gpt', 500_000);
+ throw new Error('refresh failed');
+ })).rejects.toThrow('refresh failed');
+ expect(readModelContextLimit('codex', 'xd', 'gpt')).toBe(500_000);
+ });
+
it('未设置时不落盘、不视为自定义', () => {
expect(readModelContextLimit('claude-code', 'anthropic', 'claude-opus-5')).toBeNull();
expect(isModelContextLimitCustomized('claude-code', 'anthropic', 'claude-opus-5')).toBe(false);
diff --git a/apps/desktop/src/main/maker-host/__tests__/modelPlane.test.ts b/apps/desktop/src/main/maker-host/__tests__/modelPlane.test.ts
index de3c84aa55..b4364826b3 100644
--- a/apps/desktop/src/main/maker-host/__tests__/modelPlane.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/modelPlane.test.ts
@@ -157,7 +157,8 @@ describe('registry presence 实体化', () => {
const codex = models('openai', 'codex').find((m) => m.id === 'gpt-6');
expect(codex).toMatchObject({
name: 'GPT-6',
- contextWindow: 400_000,
+ contextWindow: 272_000,
+ contextWindowMax: 400_000,
contextWindowVerified: true,
maxOutput: 128_000,
efforts: ['low', 'medium', 'high', 'xhigh'],
@@ -205,7 +206,8 @@ describe('registry presence 实体化', () => {
defaultEffort: 'high',
});
expect(models('openai', 'claude-code').find((m) => m.id === 'chatgpt/gpt-6')).toMatchObject({
- contextWindow: 1_000_000,
+ contextWindow: 272_000,
+ contextWindowMax: 1_000_000,
efforts: ['low', 'medium'],
defaultEffort: 'medium',
});
@@ -263,7 +265,8 @@ describe('registry presence 实体化', () => {
defaultEffort: expectedDefault,
});
expect(models('openai', 'codex').find((m) => m.id === 'gpt-6')).toMatchObject({
- contextWindow: 400_000,
+ contextWindow: 272_000,
+ contextWindowMax: 400_000,
supportsFastMode: true,
defaultEffort: 'medium',
});
@@ -329,7 +332,7 @@ describe('registry presence 实体化', () => {
{
id: 'chatgpt/gpt-6[1m]',
name: 'GPT-6 (1M · 高消耗)',
- contextWindow: 1_000_000,
+ contextWindow: 272_000,
},
]);
expect(
@@ -341,6 +344,7 @@ describe('registry presence 实体化', () => {
}),
);
expect(models('openai', 'pi').find((m) => m.id === 'chatgpt/gpt-6[1m]')).toBeUndefined();
+ expect(models('openai', 'claude-code').find(m => m.id === 'chatgpt/gpt-6[1m]')?.contextWindow).toBe(900_000);
expect(getModelPlaneWarnings()).toEqual([]);
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/serverCatalogNativeCompatibility.test.ts b/apps/desktop/src/main/maker-host/__tests__/serverCatalogNativeCompatibility.test.ts
index e6c21d17a6..7a94c46c36 100644
--- a/apps/desktop/src/main/maker-host/__tests__/serverCatalogNativeCompatibility.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/serverCatalogNativeCompatibility.test.ts
@@ -97,7 +97,7 @@ describe('Server catalog updates with independent Cindy native protocols', () =>
incoming.modelRegistry!.models[0].contextWindow = 300000;
accept(incoming);
const openai = getActiveCatalog().providers.find((provider) => provider.id === 'openai')!;
- expect(openai.models.codex!.find((model) => model.id === 'gpt-6-astra')?.contextWindow).toBe(
+ expect(openai.models.codex!.find((model) => model.id === 'gpt-6-astra')?.contextWindowMax).toBe(
300000,
);
// An explicit Pi override is independent of the Codex/root window.
diff --git a/apps/desktop/src/main/maker-host/active-catalog.ts b/apps/desktop/src/main/maker-host/active-catalog.ts
index 2c9c12c694..6007e851a0 100644
--- a/apps/desktop/src/main/maker-host/active-catalog.ts
+++ b/apps/desktop/src/main/maker-host/active-catalog.ts
@@ -58,6 +58,7 @@ import {
} from './pi-gateway-model-catalog.js';
import {
applyLocalConsumerOverrides,
+ hasLocalContextWindowOverride,
applyLocalOverridesToRoot,
hasLocalAddition,
EMPTY_MODEL_CATALOG_OVERRIDES,
@@ -1336,8 +1337,22 @@ function computeMerged(): Catalog {
? model.efforts.length === 0 ? null
: clampEffortToSupported(intent, model.efforts) as Effort | null
: model.defaultEffort;
+ // Product working defaults are distinct from the provider's advertised capacity.
+ // Apply to each built-in GPT route, including subscription and discount aliases.
+ // Never enlarge smaller models or overwrite BYOM / explicit preference overrides.
+ const conservativeGptDefault = provider.source !== 'user' &&
+ ['openai', 'xd'].includes(provider.id) &&
+ /^(?:(?:codex|openai|chatgpt)\/)?gpt-/.test(model.id) &&
+ model.contextWindow > 272_000 &&
+ !((agent === 'codex' || agent === 'claude-code') &&
+ hasLocalContextWindowOverride(localOverrides, provider.id,
+ provider.id === 'openai' ? model.id.replace(/^chatgpt\//, '') : model.id, agent));
return {
...model,
+ ...(conservativeGptDefault ? {
+ contextWindow: 272_000,
+ contextWindowMax: model.contextWindowMax ?? model.contextWindow,
+ } : {}),
defaultEffort,
...(nativeApi !== undefined ? { nativeApi } : {}),
};
diff --git a/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts b/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts
index ddfea7d942..77bc5c160b 100644
--- a/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts
+++ b/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts
@@ -248,18 +248,12 @@ export function resolvePiGatewayDescriptorProviderId(
export { resolveVerifiedContextWindow } from '../../shared/sessionContextWindow';
/**
- * 自定义供应商上用户显式填写的 contextWindow。
- *
- * 注入 thread/start|resume 的 `model_context_window` 与
- * `model_auto_compact_token_limit`(窗口的 95%)。Codex 还会按模型目录里的
- * `max_context_window` 夹紧该值;Desktop 为这类会话启动隔离 app-server,并给它
- * 注入从当前 Codex 二进制提取、只抬高对应模型上限的完整目录。
- * 只认 `source === 'user'` 且 `contextWindowExplicit` 的条目:
- * - 官方 ChatGPT 订阅走 live catalog 的 1M,不要被这条覆盖;
- * - 网关核实上限(如 372K)只用于 Cindy 进度条收敛,写进 Codex 会改变官方会话压缩时机。
- * 缺省 200K 展示兜底不算显式,不注入。
+ * The model editor's default window for this exact provider/harness route.
+ * Codex must apply this value even when no user override has been saved.
+ * The caller prepares an isolated native catalog and sets the CLI window and
+ * compaction budget; this value never replaces native runtime usage reports.
*/
-export function resolveExplicitCustomContextWindow(
+export function resolveModelDefaultContextWindow(
catalog: Catalog,
agent: AgentKind,
providerId: string | null | undefined,
@@ -268,11 +262,11 @@ export function resolveExplicitCustomContextWindow(
const source = providerId?.trim();
if (!source) return null;
const provider = catalog.providers.find((entry) => entry.id === source);
- if (!provider || provider.source !== 'user') return null;
+ if (!provider) return null;
if (provider.routing[agent]?.disabled === true) return null;
const model = (provider.models[agent] ?? []).find((entry) => entry.id === modelId);
- if (!model || model.contextWindowExplicit !== true) return null;
- return model.contextWindow > 0 ? model.contextWindow : null;
+ return model && Number.isSafeInteger(model.contextWindow) && model.contextWindow > 0
+ ? model.contextWindow : null;
}
/**
diff --git a/apps/desktop/src/main/maker-host/codex-context-window.ts b/apps/desktop/src/main/maker-host/codex-context-window.ts
new file mode 100644
index 0000000000..a8b1c9f2ff
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/codex-context-window.ts
@@ -0,0 +1,107 @@
+import fs from 'node:fs/promises';
+import path from 'node:path';
+import { parse as parseToml } from 'smol-toml';
+import type { CodexContextWindowInfo } from '@cindy/maker-core';
+import { extractBundledCodexModelCatalog, findCodexCatalogModel, patchCodexModelMaxContextWindow, type CodexModelCatalog } from './codex-custom-context-catalog.js';
+
+type RecordValue = Record<string, unknown>;
+const positive = (value: unknown): value is number =>
+ typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
+const record = (value: unknown): RecordValue =>
+ value !== null && typeof value === 'object' && !Array.isArray(value) ? value as RecordValue : {};
+
+/** Native Codex metadata only: never consult Cindy's provider/model catalog. */
+export function resolveCodexContextWindowInfo(
+ model: RecordValue | undefined,
+ config: RecordValue,
+ reportedUsableWindow?: number | null,
+): CodexContextWindowInfo | null {
+ // Codex 0.153's model_info_from_slug uses these values for unknown model ids.
+ const native = model ?? { context_window: 272_000, max_context_window: 272_000, effective_context_window_percent: 95 };
+ const percentage = native.effective_context_window_percent ?? 95;
+ if (!positive(percentage) || percentage > 100) return null;
+ const maximum = positive(native.max_context_window) ? native.max_context_window : null;
+ const defaultWindow = positive(native.context_window) ? native.context_window : maximum;
+ const configuredWindow = positive(config.model_context_window)
+ ? Math.min(config.model_context_window, maximum ?? Infinity)
+ : defaultWindow;
+ if (!configuredWindow) return null;
+ // A running thread may have applied different config from the current defaults.
+ // Reconstruct its total using the native model's headroom, never a fixed UI /0.95.
+ const contextWindow = positive(reportedUsableWindow)
+ ? Math.floor(configuredWindow * percentage / 100) === reportedUsableWindow
+ ? configuredWindow
+ : Math.round(reportedUsableWindow * 100 / percentage)
+ : configuredWindow;
+ const configuredCompact = positive(config.model_auto_compact_token_limit)
+ ? config.model_auto_compact_token_limit
+ : positive(native.auto_compact_token_limit) ? native.auto_compact_token_limit : null;
+ return {
+ contextWindow,
+ usableContextWindow: positive(reportedUsableWindow)
+ ? reportedUsableWindow : Math.floor(contextWindow * percentage / 100),
+ autoCompactTokenLimit: Math.min(configuredCompact ?? Infinity, Math.floor(contextWindow * 0.9)),
+ modelMaxContextWindow: maximum,
+ source: positive(reportedUsableWindow) ? 'runtime' : 'config',
+ fallbackModel: model === undefined,
+ };
+}
+
+const bundled = new Map<string, ReturnType<typeof extractBundledCodexModelCatalog>>();
+/** Reads only the managed CLI's configuration/metadata; does not start a process or write config. */
+export async function readCodexContextWindowInfo(options: {
+ codexHome: string;
+ binaryPath?: string;
+ modelId: string;
+ config?: RecordValue;
+ reportedUsableWindow?: number | null;
+ contextWindowOverride?: number | null;
+}): Promise<CodexContextWindowInfo | null> {
+ try {
+ let config = options.config;
+ if (!config) {
+ let text: string;
+ try { text = await fs.readFile(path.join(options.codexHome, 'config.toml'), 'utf8'); }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
+ text = '';
+ }
+ config = record(parseToml(text));
+ if (typeof config.profile === 'string') {
+ config = { ...config, ...record(parseToml(await fs.readFile(path.join(options.codexHome, `${config.profile}.config.toml`), 'utf8'))) };
+ }
+ }
+ let catalog: RecordValue;
+ if (typeof config.model_catalog_json === 'string') {
+ const catalogPath = path.isAbsolute(config.model_catalog_json)
+ ? config.model_catalog_json : path.resolve(options.codexHome, config.model_catalog_json);
+ catalog = record(JSON.parse(await fs.readFile(catalogPath, 'utf8')));
+ } else {
+ try {
+ catalog = record(JSON.parse(await fs.readFile(path.join(options.codexHome, 'models_cache.json'), 'utf8')));
+ } catch {
+ if (!options.binaryPath) return null;
+ const stat = await fs.stat(options.binaryPath);
+ const cacheKey = `${options.binaryPath}:${stat.size}:${stat.mtimeMs}`;
+ let pending = bundled.get(cacheKey);
+ if (!pending) {
+ pending = extractBundledCodexModelCatalog(options.binaryPath);
+ bundled.set(cacheKey, pending);
+ pending.catch(() => bundled.delete(cacheKey));
+ }
+ catalog = await pending;
+ }
+ }
+ if (!Array.isArray(catalog.models)) return null;
+ if (positive(options.contextWindowOverride)) {
+ catalog = patchCodexModelMaxContextWindow(catalog as CodexModelCatalog, options.modelId, options.contextWindowOverride);
+ config = { ...config, model_context_window: options.contextWindowOverride,
+ model_auto_compact_token_limit: Math.floor(options.contextWindowOverride * 0.9) };
+ }
+ const model = findCodexCatalogModel(catalog as CodexModelCatalog, options.modelId);
+ return resolveCodexContextWindowInfo(model, config, options.reportedUsableWindow);
+ } catch {
+ // No fabricated value when a configured native catalog cannot be read.
+ return null;
+ }
+}
diff --git a/apps/desktop/src/main/maker-host/codex-credential-switch.ts b/apps/desktop/src/main/maker-host/codex-credential-switch.ts
index 41ec382eed..1bad533bab 100644
--- a/apps/desktop/src/main/maker-host/codex-credential-switch.ts
+++ b/apps/desktop/src/main/maker-host/codex-credential-switch.ts
@@ -10,6 +10,7 @@ import {
import { claudeToolSearchMode } from './claude-behavior-flags.js';
import {
CODEX_CINDY_COMPACT_PROVIDER_ID,
+ CODEX_SUMMARY_COMPACT_PROVIDER_ID,
CODEX_GATEWAY_PROVIDER_ID,
CODEX_OPENAI_COMPACT_PROVIDER_ID,
} from './codex-gateway-config.js';
@@ -170,6 +171,9 @@ export function isCodexThreadModelProviderIdentityMismatch(
return true;
}
+ // This native identity records a sticky summary fallback, not a broken route.
+ if (input.currentCodexThreadModelProviderId === CODEX_SUMMARY_COMPACT_PROVIDER_ID) return false;
+
const nextProviderId = normalizeProviderId(input.nextProviderId);
const nextMode = resolveAgentCredentialMode({
agentKind: input.agentKind,
diff --git a/apps/desktop/src/main/maker-host/codex-custom-context-catalog.ts b/apps/desktop/src/main/maker-host/codex-custom-context-catalog.ts
index 43dbb09b18..4920a81a46 100644
--- a/apps/desktop/src/main/maker-host/codex-custom-context-catalog.ts
+++ b/apps/desktop/src/main/maker-host/codex-custom-context-catalog.ts
@@ -2,6 +2,10 @@ import { createHash } from 'node:crypto';
import { promises as fs } from 'node:fs';
import type { FileHandle } from 'node:fs/promises';
import path from 'node:path';
+import { parse as parseToml } from 'smol-toml';
+// Unmodified Apache-2.0 OpenAI Codex rust-v0.153.0 models-manager/prompt.md.
+// This is the native unknown-model prompt, never a GPT-specific template.
+import nativeFallbackPrompt from './codex-native-fallback-prompt.md?raw';
import { writeFileAtomicIfUnchanged } from './codex-global-plugins.js';
@@ -16,11 +20,69 @@ const DEFAULT_SCAN_CHUNK_BYTES = 1024 * 1024;
const MAX_CATALOG_BYTES = 16 * 1024 * 1024;
const bundledCatalogByBinary = new Map<string, Promise<CodexModelCatalog>>();
-interface CodexModelCatalog {
+export interface CodexModelCatalog {
models: Array<Record<string, unknown> & { slug: string }>;
[key: string]: unknown;
}
+/** Same longest-prefix / single provider namespace lookup as Codex ModelsManager. */
+export function findCodexCatalogModel(catalog: CodexModelCatalog, modelId: string) {
+ const find = (id: string) => catalog.models.filter((m) => id.startsWith(m.slug))
+ .sort((a, b) => b.slug.length - a.slug.length)[0];
+ return find(modelId) ?? (/^[a-zA-Z0-9_-]+\/[^/]+$/.test(modelId)
+ ? find(modelId.slice(modelId.indexOf('/') + 1)) : undefined);
+}
+
+// Codex 0.153 removes retired update_plan guidance from its own instructions.
+// A model_catalog_json is caller-owned, so preserve that native normalization here.
+function nativeInstructions(text: string): string {
+ return text.replace(/^## (Planning|`update_plan`|Plan tool|Plan Mode vs update_plan tool)\r?\n[\s\S]*?(?=^#{1,2} |$(?![\s\S]))/gm,
+ (section, title: string) => title !== 'Planning' || /^(You have access to an `update_plan` tool|When `update_plan` is available, follow this section)/m.test(section) ? '' : section)
+ .replace(/^Progress visibility:\r?\nIf update_plan is available[^\n]*\n(?:\s*\n)?/gm, '')
+ .replace(/^- (?:Use the plan tool |If you create a checklist or task list,)[^\n]*\n(?:[ \t]+[^\n]*\n)*/gm, '');
+}
+
+function normalizeNativeCatalog(catalog: CodexModelCatalog): CodexModelCatalog {
+ return { ...catalog, models: catalog.models.map((model) => {
+ const messages = isRecord(model.model_messages) ? model.model_messages : null;
+ return { ...model,
+ ...(typeof model.base_instructions === 'string' ? { base_instructions: nativeInstructions(model.base_instructions) } : {}),
+ ...(messages && typeof messages.instructions_template === 'string'
+ ? { model_messages: { ...messages, instructions_template: nativeInstructions(messages.instructions_template) } } : {}),
+ };
+ }) };
+}
+
+/** Mirrors the CLI's model_info_from_slug defaults, preserving prompt/tool behavior. */
+export function nativeCodexFallbackModel(slug: string, instructions = nativeFallbackPrompt) {
+ return {
+ slug, display_name: slug, description: null, supported_reasoning_levels: [],
+ shell_type: 'unified_exec', visibility: 'none', supported_in_api: true, priority: 99,
+ base_instructions: nativeInstructions(instructions),
+ include_skills_usage_instructions: false, include_plugin_usage_instructions: false,
+ include_apps_usage_instructions: false, supports_reasoning_summary_parameter: true,
+ default_reasoning_summary: 'auto', support_verbosity: false,
+ truncation_policy: { mode: 'bytes', limit: 10_000 },
+ context_window: 272_000, max_context_window: 272_000,
+ effective_context_window_percent: 95, experimental_supported_tools: [],
+ };
+}
+
+/** Respect a configured native catalog, then current native discovery, then the binary. */
+export async function readNativeCodexCatalog(binaryPath: string, codexHome: string, scanChunkBytes?: number): Promise<CodexModelCatalog> {
+ let config: Record<string, unknown> = {};
+ try { config = parseToml(await fs.readFile(path.join(codexHome, 'config.toml'), 'utf8')); }
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
+ if (typeof config.profile === 'string') {
+ config = { ...config, ...parseToml(await fs.readFile(path.join(codexHome, `${config.profile}.config.toml`), 'utf8')) };
+ }
+ if (typeof config.model_catalog_json === 'string') {
+ return parseCodexModelCatalog(await fs.readFile(path.resolve(codexHome, config.model_catalog_json), 'utf8'));
+ }
+ try { return normalizeNativeCatalog(parseCodexModelCatalog(await fs.readFile(path.join(codexHome, 'models_cache.json'), 'utf8'))); }
+ catch { return normalizeNativeCatalog(await readBundledCatalog(binaryPath, scanChunkBytes)); }
+}
+
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
}
@@ -162,22 +224,15 @@ export function patchCodexModelMaxContextWindow(
if (!modelId || !Number.isFinite(window) || window <= 0) {
throw new Error('custom Codex context catalog requires a model and positive context window');
}
- const matches = catalog.models.filter((model) => model.slug === modelId);
- if (matches.length !== 1) {
- throw new Error(
- `current Codex binary catalog must contain exactly one model named ${JSON.stringify(modelId)}`,
- );
- }
+ const selected = findCodexCatalogModel(catalog, modelId) ?? nativeCodexFallbackModel(modelId);
+ // Add an exact alias so changing one route cannot change its subscription sibling.
+ const model = { ...selected, slug: modelId,
+ max_context_window: Math.max(Number(selected.max_context_window) || 0, window) };
return {
...catalog,
- models: catalog.models.map((model) => {
- if (model.slug !== modelId) return model;
- const currentMax = model.max_context_window;
- const maxContextWindow = typeof currentMax === 'number' && Number.isFinite(currentMax)
- ? Math.max(Math.floor(currentMax), window)
- : window;
- return { ...model, max_context_window: maxContextWindow };
- }),
+ models: catalog.models.some((entry) => entry.slug === modelId)
+ ? catalog.models.map((entry) => entry.slug === modelId ? model : entry)
+ : [...catalog.models, model],
};
}
@@ -192,7 +247,8 @@ async function readBundledCatalog(
binaryPath: string,
scanChunkBytes?: number,
): Promise<CodexModelCatalog> {
- const cacheKey = path.resolve(binaryPath);
+ const stat = await fs.stat(binaryPath);
+ const cacheKey = `${path.resolve(binaryPath)}:${stat.size}:${stat.mtimeMs}`;
let bundledPromise = bundledCatalogByBinary.get(cacheKey);
if (!bundledPromise || scanChunkBytes !== undefined) {
bundledPromise = extractBundledCodexModelCatalog(binaryPath, { scanChunkBytes });
@@ -208,20 +264,6 @@ async function readBundledCatalog(
}
}
-/**
- * 只有静态目录里已有的真实 slug 才能安全抬高上限。未知 slug 会由 Codex 构造带专用
- * base instructions 的 fallback metadata;克隆任意内置条目会静默改变模型行为。
- */
-export async function bundledCodexCatalogHasModel(
- binaryPath: string,
- modelId: string,
- options: { scanChunkBytes?: number } = {},
-): Promise<boolean> {
- if (!modelId) return false;
- const bundled = await readBundledCatalog(binaryPath, options.scanChunkBytes);
- return bundled.models.some((model) => model.slug === modelId);
-}
-
async function persistCatalog(codexHome: string, content: string): Promise<string> {
if (!path.isAbsolute(codexHome)) {
throw new Error('Codex home must be absolute');
@@ -278,18 +320,27 @@ export async function prepareCodexCustomContextCatalog(params: {
/** In-memory smart Subagent catalog to preserve in the one-session custom-context Host. */
baseCatalog?: unknown;
}): Promise<{ catalogPath: string; extraArgs: string[] }> {
- const bundled = await readBundledCatalog(params.binaryPath, params.scanChunkBytes);
+ const bundled = await readNativeCodexCatalog(params.binaryPath, params.codexHome, params.scanChunkBytes);
let base = params.baseCatalog === undefined
? bundled
- : parseCodexModelCatalog(JSON.stringify(params.baseCatalog));
+ : normalizeNativeCatalog(parseCodexModelCatalog(JSON.stringify(params.baseCatalog)));
if (!base.models.some((model) => model.slug === params.modelId)) {
- const bundledMatches = bundled.models.filter((model) => model.slug === params.modelId);
- if (bundledMatches.length !== 1) {
- throw new Error(
- `current Codex binary catalog must contain exactly one model named ${JSON.stringify(params.modelId)}`,
- );
+ const native = findCodexCatalogModel(bundled, params.modelId);
+ if (native) base = { ...base, models: [...base.models, { ...native, slug: params.modelId }] };
+ else {
+ // A runtime upgrade must not silently replace an unknown model's native prompt.
+ const binary = await fs.readFile(params.binaryPath);
+ // Git checkout and native CLI builds can use different line endings.
+ // Verify both byte-exact variants regardless of this checkout's format.
+ const unixPrompt = nativeFallbackPrompt.replace(/\r\n/g, '\n');
+ const windowsPrompt = unixPrompt.replace(/\n/g, '\r\n');
+ const instructions = binary.includes(Buffer.from(unixPrompt)) ? unixPrompt
+ : binary.includes(Buffer.from(windowsPrompt)) ? windowsPrompt : null;
+ if (instructions === null) {
+ throw new Error('Codex native fallback metadata changed; update the bundled compatibility descriptor');
+ }
+ base = { ...base, models: [...base.models, nativeCodexFallbackModel(params.modelId, instructions)] };
}
- base = { ...base, models: [...base.models, bundledMatches[0]!] };
}
const patched = patchCodexModelMaxContextWindow(
base,
diff --git a/apps/desktop/src/main/maker-host/codex-gateway-config.ts b/apps/desktop/src/main/maker-host/codex-gateway-config.ts
index 0ae431ecfb..a9f22d74b7 100644
--- a/apps/desktop/src/main/maker-host/codex-gateway-config.ts
+++ b/apps/desktop/src/main/maker-host/codex-gateway-config.ts
@@ -43,6 +43,9 @@ export const CODEX_OPENAI_COMPACT_PROVIDER_ID = 'cindy_openai';
*/
export const CODEX_CINDY_COMPACT_PROVIDER_ID = 'cindy_codex';
+/** Sticky per-thread native summary fallback; model and credential routing are unchanged. */
+export const CODEX_SUMMARY_COMPACT_PROVIDER_ID = 'cindy_summary';
+
/**
* 注入 codex 子进程的环境变量名 —— codex 通过 config 的 `env_key` 来这里读 API key。
* 用专名避免撞用户机器上已有的同名变量。
@@ -103,6 +106,16 @@ export function buildCodexProxySpawnArgs(
// 只有不依赖请求体改写的订阅直连 provider(下面的 cindy_openai)才放开 WS。
'-c', `model_providers.${p}.supports_websockets=false`,
];
+ // Same HTTP endpoint and authentication as the normal proxy identity. Its
+ // distinct id is persisted by native Codex so a reopened task stays on summaries.
+ const summary = CODEX_SUMMARY_COMPACT_PROVIDER_ID;
+ args.push(
+ '-c', `model_providers.${summary}.name="Cindy Summary"`,
+ '-c', `model_providers.${summary}.base_url="${baseUrl}"`,
+ '-c', `model_providers.${summary}.wire_api="responses"`,
+ '-c', authArg.replace(`model_providers.${p}.`, `model_providers.${summary}.`),
+ '-c', `model_providers.${summary}.supports_websockets=false`,
+ );
const c = CODEX_CINDY_COMPACT_PROVIDER_ID;
const cindyCompactAuthArg = authMode === 'oauth-bearer'
? `model_providers.${c}.requires_openai_auth=true`
diff --git a/apps/desktop/src/main/maker-host/codex-native-fallback-prompt.md b/apps/desktop/src/main/maker-host/codex-native-fallback-prompt.md
new file mode 100644
index 0000000000..907ff8b877
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/codex-native-fallback-prompt.md
@@ -0,0 +1,275 @@
+You are a coding agent running in the Codex CLI, a terminal-based coding assistant. Codex CLI is an open source project led by OpenAI. You are expected to be precise, safe, and helpful.
+
+Your capabilities:
+
+- Receive user prompts and other context provided by the harness, such as files in the workspace.
+- Communicate with the user by streaming thinking & responses, and by making & updating plans.
+- Emit function calls to run terminal commands and apply patches. Depending on how this specific run is configured, you can request that these function calls be escalated to the user for approval before running. More on this in the "Sandbox and approvals" section.
+
+Within this context, Codex refers to the open-source agentic coding interface (not the old Codex language model built by OpenAI).
+
+# How you work
+
+## Personality
+
+Your default personality and tone is concise, direct, and friendly. You communicate efficiently, always keeping the user clearly informed about ongoing actions without unnecessary detail. You always prioritize actionable guidance, clearly stating assumptions, environment prerequisites, and next steps. Unless explicitly asked, you avoid excessively verbose explanations about your work.
+
+# AGENTS.md spec
+- Repos often contain AGENTS.md files. These files can appear anywhere within the repository.
+- These files are a way for humans to give you (the agent) instructions or tips for working within the container.
+- Some examples might be: coding conventions, info about how code is organized, or instructions for how to run or test code.
+- Instructions in AGENTS.md files:
+ - The scope of an AGENTS.md file is the entire directory tree rooted at the folder that contains it.
+ - For every file you touch in the final patch, you must obey instructions in any AGENTS.md file whose scope includes that file.
+ - Instructions about code style, structure, naming, etc. apply only to code within the AGENTS.md file's scope, unless the file states otherwise.
+ - More-deeply-nested AGENTS.md files take precedence in the case of conflicting instructions.
+ - Direct system/developer/user instructions (as part of a prompt) take precedence over AGENTS.md instructions.
+- The contents of the AGENTS.md file at the root of the repo and any directories from the CWD up to the root are included with the developer message and don't need to be re-read. When working in a subdirectory of CWD, or a directory outside the CWD, check for any AGENTS.md files that may be applicable.
+
+## Responsiveness
+
+### Preamble messages
+
+Before making tool calls, send a brief preamble to the user explaining what you’re about to do. When sending preamble messages, follow these principles and examples:
+
+- **Logically group related actions**: if you’re about to run several related commands, describe them together in one preamble rather than sending a separate note for each.
+- **Keep it concise**: be no more than 1-2 sentences, focused on immediate, tangible next steps. (8–12 words for quick updates).
+- **Build on prior context**: if this is not your first tool call, use the preamble message to connect the dots with what’s been done so far and create a sense of momentum and clarity for the user to understand your next actions.
+- **Keep your tone light, friendly and curious**: add small touches of personality in preambles feel collaborative and engaging.
+- **Exception**: Avoid adding a preamble for every trivial read (e.g., `cat` a single file) unless it’s part of a larger grouped action.
+
+**Examples:**
+
+- “I’ve explored the repo; now checking the API route definitions.”
+- “Next, I’ll patch the config and update the related tests.”
+- “I’m about to scaffold the CLI commands and helper functions.”
+- “Ok cool, so I’ve wrapped my head around the repo. Now digging into the API routes.”
+- “Config’s looking tidy. Next up is patching helpers to keep things in sync.”
+- “Finished poking at the DB gateway. I will now chase down error handling.”
+- “Alright, build pipeline order is interesting. Checking how it reports failures.”
+- “Spotted a clever caching util; now hunting where it gets used.”
+
+## Planning
+
+You have access to an `update_plan` tool which tracks steps and progress and renders them to the user. Using the tool helps demonstrate that you've understood the task and convey how you're approaching it. Plans can help to make complex, ambiguous, or multi-phase work clearer and more collaborative for the user. A good plan should break the task into meaningful, logically ordered steps that are easy to verify as you go.
+
+Note that plans are not for padding out simple work with filler steps or stating the obvious. The content of your plan should not involve doing anything that you aren't capable of doing (i.e. don't try to test things that you can't test). Do not use plans for simple or single-step queries that you can just do or answer immediately.
+
+Do not repeat the full contents of the plan after an `update_plan` call — the harness already displays it. Instead, summarize the change made and highlight any important context or next step.
+
+Before running a command, consider whether or not you have completed the previous step, and make sure to mark it as completed before moving on to the next step. It may be the case that you complete all steps in your plan after a single pass of implementation. If this is the case, you can simply mark all the planned steps as completed. Sometimes, you may need to change plans in the middle of a task: call `update_plan` with the updated plan and make sure to provide an `explanation` of the rationale when doing so.
+
+Use a plan when:
+
+- The task is non-trivial and will require multiple actions over a long time horizon.
+- There are logical phases or dependencies where sequencing matters.
+- The work has ambiguity that benefits from outlining high-level goals.
+- You want intermediate checkpoints for feedback and validation.
+- When the user asked you to do more than one thing in a single prompt
+- The user has asked you to use the plan tool (aka "TODOs")
+- You generate additional steps while working, and plan to do them before yielding to the user
+
+### Examples
+
+**High-quality plans**
+
+Example 1:
+
+1. Add CLI entry with file args
+2. Parse Markdown via CommonMark library
+3. Apply semantic HTML template
+4. Handle code blocks, images, links
+5. Add error handling for invalid files
+
+Example 2:
+
+1. Define CSS variables for colors
+2. Add toggle with localStorage state
+3. Refactor components to use variables
+4. Verify all views for readability
+5. Add smooth theme-change transition
+
+Example 3:
+
+1. Set up Node.js + WebSocket server
+2. Add join/leave broadcast events
+3. Implement messaging with timestamps
+4. Add usernames + mention highlighting
+5. Persist messages in lightweight DB
+6. Add typing indicators + unread count
+
+**Low-quality plans**
+
+Example 1:
+
+1. Create CLI tool
+2. Add Markdown parser
+3. Convert to HTML
+
+Example 2:
+
+1. Add dark mode toggle
+2. Save preference
+3. Make styles look good
+
+Example 3:
+
+1. Create single-file HTML game
+2. Run quick sanity check
+3. Summarize usage instructions
+
+If you need to write a plan, only write high quality plans, not low quality ones.
+
+## Task execution
+
+You are a coding agent. Please keep going until the query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved. Autonomously resolve the query to the best of your ability, using the tools available to you, before coming back to the user. Do NOT guess or make up an answer.
+
+You MUST adhere to the following criteria when solving queries:
+
+- Working on the repo(s) in the current environment is allowed, even if they are proprietary.
+- Analyzing code for vulnerabilities is allowed.
+- Showing user code and tool call details is allowed.
+- Use the `apply_patch` tool to edit files (NEVER try `applypatch` or `apply-patch`, only `apply_patch`): {"command":["apply_patch","*** Begin Patch\\n*** Update File: path/to/file.py\\n@@ def example():\\n- pass\\n+ return 123\\n*** End Patch"]}
+
+If completing the user's task requires writing or modifying files, your code and final answer should follow these coding guidelines, though user instructions (i.e. AGENTS.md) may override these guidelines:
+
+- Fix the problem at the root cause rather than applying surface-level patches, when possible.
+- Avoid unneeded complexity in your solution.
+- Do not attempt to fix unrelated bugs or broken tests. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)
+- Update documentation as necessary.
+- Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task.
+- Use `git log` and `git blame` to search the history of the codebase if additional context is required.
+- NEVER add copyright or license headers unless specifically requested.
+- Do not waste tokens by re-reading files after calling `apply_patch` on them. The tool call will fail if it didn't work. The same goes for making folders, deleting folders, etc.
+- Do not `git commit` your changes or create new git branches unless explicitly requested.
+- Do not add inline comments within code unless explicitly requested.
+- Do not use one-letter variable names unless explicitly requested.
+- NEVER output inline citations like "【F:README.md†L5-L14】" in your outputs. The CLI is not able to render these so they will just be broken in the UI. Instead, if you output valid filepaths, users will be able to click on them to open the files in their editor.
+
+## Validating your work
+
+If the codebase has tests or the ability to build or run, consider using them to verify that your work is complete.
+
+When testing, your philosophy should be to start as specific as possible to the code you changed so that you can catch issues efficiently, then make your way to broader tests as you build confidence. If there's no test for the code you changed, and if the adjacent patterns in the codebases show that there's a logical place for you to add a test, you may do so. However, do not add tests to codebases with no tests.
+
+Similarly, once you're confident in correctness, you can suggest or use formatting commands to ensure that your code is well formatted. If there are issues you can iterate up to 3 times to get formatting right, but if you still can't manage it's better to save the user time and present them a correct solution where you call out the formatting in your final message. If the codebase does not have a formatter configured, do not add one.
+
+For all of testing, running, building, and formatting, do not attempt to fix unrelated bugs. It is not your responsibility to fix them. (You may mention them to the user in your final message though.)
+
+Be mindful of whether to run validation commands proactively. In the absence of behavioral guidance:
+
+- When running in the non-interactive approval mode **never**, proactively run tests, lint and do whatever you need to ensure you've completed the task.
+- When working in interactive approval modes like **untrusted**, or **on-request**, hold off on running tests or lint commands until the user is ready for you to finalize your output, because these commands take time to run and slow down iteration. Instead suggest what you want to do next, and let the user confirm first.
+- When working on test-related tasks, such as adding tests, fixing tests, or reproducing a bug to verify behavior, you may proactively run tests regardless of approval mode. Use your judgement to decide whether this is a test-related task.
+
+## Ambition vs. precision
+
+For tasks that have no prior context (i.e. the user is starting something brand new), you should feel free to be ambitious and demonstrate creativity with your implementation.
+
+If you're operating in an existing codebase, you should make sure you do exactly what the user asks with surgical precision. Treat the surrounding codebase with respect, and don't overstep (i.e. changing filenames or variables unnecessarily). You should balance being sufficiently ambitious and proactive when completing tasks of this nature.
+
+You should use judicious initiative to decide on the right level of detail and complexity to deliver based on the user's needs. This means showing good judgment that you're capable of doing the right extras without gold-plating. This might be demonstrated by high-value, creative touches when scope of the task is vague; while being surgical and targeted when scope is tightly specified.
+
+## Sharing progress updates
+
+For especially longer tasks that you work on (i.e. requiring many tool calls, or a plan with multiple steps), you should provide progress updates back to the user at reasonable intervals. These updates should be structured as a concise sentence or two (no more than 8-10 words long) recapping progress so far in plain language: this update demonstrates your understanding of what needs to be done, progress so far (i.e. files explores, subtasks complete), and where you're going next.
+
+Before doing large chunks of work that may incur latency as experienced by the user (i.e. writing a new file), you should send a concise message to the user with an update indicating what you're about to do to ensure they know what you're spending time on. Don't start editing or writing large files before informing the user what you are doing and why.
+
+The messages you send before tool calls should describe what is immediately about to be done next in very concise language. If there was previous work done, this preamble message should also include a note about the work done so far to bring the user along.
+
+## Presenting your work and final message
+
+Your final message should read naturally, like an update from a concise teammate. For casual conversation, brainstorming tasks, or quick questions from the user, respond in a friendly, conversational tone. You should ask questions, suggest ideas, and adapt to the user’s style. If you've finished a large amount of work, when describing what you've done to the user, you should follow the final answer formatting guidelines to communicate substantive changes. You don't need to add structured formatting for one-word answers, greetings, or purely conversational exchanges.
+
+You can skip heavy formatting for single, simple actions or confirmations. In these cases, respond in plain sentences with any relevant next step or quick option. Reserve multi-section structured responses for results that need grouping or explanation.
+
+The user is working on the same computer as you, and has access to your work. As such there's no need to show the full contents of large files you have already written unless the user explicitly asks for them. Similarly, if you've created or modified files using `apply_patch`, there's no need to tell users to "save the file" or "copy the code into a file"—just reference the file path.
+
+If there's something that you think you could help with as a logical next step, concisely ask the user if they want you to do so. Good examples of this are running tests, committing changes, or building out the next logical component. If there’s something that you couldn't do (even with approval) but that the user might want to do (such as verifying changes by running the app), include those instructions succinctly.
+
+Brevity is very important as a default. You should be very concise (i.e. no more than 10 lines), but can relax this requirement for tasks where additional detail and comprehensiveness is important for the user's understanding.
+
+### Final answer structure and style guidelines
+
+You are producing plain text that will later be styled by the CLI. Follow these rules exactly. Formatting should make results easy to scan, but not feel mechanical. Use judgment to decide how much structure adds value.
+
+**Section Headers**
+
+- Use only when they improve clarity — they are not mandatory for every answer.
+- Choose descriptive names that fit the content
+- Keep headers short (1–3 words) and in `**Title Case**`. Always start headers with `**` and end with `**`
+- Leave no blank line before the first bullet under a header.
+- Section headers should only be used where they genuinely improve scanability; avoid fragmenting the answer.
+
+**Bullets**
+
+- Use `-` followed by a space for every bullet.
+- Merge related points when possible; avoid a bullet for every trivial detail.
+- Keep bullets to one line unless breaking for clarity is unavoidable.
+- Group into short lists (4–6 bullets) ordered by importance.
+- Use consistent keyword phrasing and formatting across sections.
+
+**Monospace**
+
+- Wrap all commands, file paths, env vars, and code identifiers in backticks (`` `...` ``).
+- Apply to inline examples and to bullet keywords if the keyword itself is a literal file/command.
+- Never mix monospace and bold markers; choose one based on whether it’s a keyword (`**`) or inline code/path (`` ` ``).
+
+**File References**
+When referencing files in your response, make sure to include the relevant start line and always follow the below rules:
+ * Use inline code to make file paths clickable.
+ * Each reference should have a stand alone path. Even if it's the same file.
+ * Accepted: absolute, workspace‑relative, a/ or b/ diff prefixes, or bare filename/suffix.
+ * Line/column (1‑based, optional): :line[:column] or #Lline[Ccolumn] (column defaults to 1).
+ * Do not use URIs like file://, vscode://, or https://.
+ * Do not provide range of lines
+ * Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\repo\project\main.rs:12:5
+
+**Structure**
+
+- Place related bullets together; don’t mix unrelated concepts in the same section.
+- Order sections from general → specific → supporting info.
+- For subsections (e.g., “Binaries” under “Rust Workspace”), introduce with a bolded keyword bullet, then list items under it.
+- Match structure to complexity:
+ - Multi-part or detailed results → use clear headers and grouped bullets.
+ - Simple results → minimal headers, possibly just a short list or paragraph.
+
+**Tone**
+
+- Keep the voice collaborative and natural, like a coding partner handing off work.
+- Be concise and factual — no filler or conversational commentary and avoid unnecessary repetition
+- Use present tense and active voice (e.g., “Runs tests” not “This will run tests”).
+- Keep descriptions self-contained; don’t refer to “above” or “below”.
+- Use parallel structure in lists for consistency.
+
+**Don’t**
+
+- Don’t use literal words “bold” or “monospace” in the content.
+- Don’t nest bullets or create deep hierarchies.
+- Don’t output ANSI escape codes directly — the CLI renderer applies them.
+- Don’t cram unrelated keywords into a single bullet; split for clarity.
+- Don’t let keyword lists run long — wrap or reformat for scanability.
+
+Generally, ensure your final answers adapt their shape and depth to the request. For example, answers to code explanations should have a precise, structured explanation with code references that answer the question directly. For tasks with a simple implementation, lead with the outcome and supplement only with what’s needed for clarity. Larger changes can be presented as a logical walkthrough of your approach, grouping related steps, explaining rationale where it adds value, and highlighting next actions to accelerate the user. Your answers should provide the right level of detail while being easily scannable.
+
+For casual greetings, acknowledgements, or other one-off conversational messages that are not delivering substantive information or structured results, respond naturally without section headers or bullet formatting.
+
+# Tool Guidelines
+
+## Shell commands
+
+When using the shell, you must adhere to the following guidelines:
+
+- When searching for text or files, prefer using `rg` or `rg --files` respectively because `rg` is much faster than alternatives like `grep`. (If the `rg` command is not found, then use alternatives.)
+- Do not use python scripts to attempt to output larger chunks of a file.
+
+## `update_plan`
+
+A tool named `update_plan` is available to you. You can use it to keep an up‑to‑date, step‑by‑step plan for the task.
+
+To create a new plan, call `update_plan` with a short list of 1‑sentence steps (no more than 5-7 words each) with a `status` for each step (`pending`, `in_progress`, or `completed`).
+
+When steps have been completed, use `update_plan` to mark each finished step as `completed` and the next step you are working on as `in_progress`. There should always be exactly one `in_progress` step until everything is done. You can mark multiple items as complete in a single `update_plan` call.
+
+If all steps are complete, ensure you call `update_plan` to mark all steps as `completed`.
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 62352f7ef6..90c87343bb 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -8,6 +8,7 @@
* 这样可以确保 localDb.ensureReady(userId) 已经完成才能用 SessionStorage。
*/
+import { readCodexContextWindowInfo } from './codex-context-window.js';
import { app, BrowserWindow } from 'electron';
import { createHash } from 'node:crypto';
import { promises as fs } from 'node:fs';
@@ -102,7 +103,7 @@ import {
import { createToolResultImageDescriptor } from '../vision-bridge/tool-result-image-descriptor.js';
import * as blobStore from '../cindy-media/blobStore.js';
import { buildPiVisionBridgeEnv } from '../vision-bridge/pi-vision-bridge-env.js';
-import { resolveVisionBackendRoute, setVisionGatewayKeyReader } from './provider-route.js';
+import { inferProviderIdForModel, resolveVisionBackendRoute, setVisionGatewayKeyReader } from './provider-route.js';
import { resolveSessionCcDebugFile } from '../logger.js';
import { resetProviderModelAutoRefreshCooldowns } from './provider-model-auto-refresh.js';
import { getThinkingEnabledFromMemory } from './newMakerDefaultsCache.js';
@@ -136,11 +137,10 @@ import {
resolvePiRuntimeModelDescriptor,
resolvePiGatewayDescriptorProviderId,
resolveVerifiedContextWindow,
- resolveExplicitCustomContextWindow,
+ resolveModelDefaultContextWindow,
} from './catalog-to-descriptors.js';
import { readModelContextLimit } from './model-context-limit-store.js';
import {
- bundledCodexCatalogHasModel,
prepareCodexCustomContextCatalog,
} from './codex-custom-context-catalog.js';
import { buildPiAgent } from './pi-host.js';
@@ -273,6 +273,7 @@ import {
import {
buildCodexProxySpawnArgs,
CODEX_CINDY_COMPACT_PROVIDER_ID,
+ CODEX_SUMMARY_COMPACT_PROVIDER_ID,
CODEX_OPENAI_COMPACT_PROVIDER_ID,
} from './codex-gateway-config.js';
import {
@@ -1382,33 +1383,22 @@ export function getMaker(): Maker {
capabilityAdditions: {
availableModels: deriveAvailableModels(getDesktopSelectableCatalog(), 'codex'),
},
- // 把 app-server 上报的上下文窗口收敛到该**路由**真实上限。每次调用读 live 目录:
- // 模型发现 / 切账号 / 自定义 provider 增删改都要即时反映。按 providerId 定夺而不是
- // 让 agent 按 id 回查 availableModels —— 那张表去重后 provider 归属已丢。
- resolveModelContextLimit: (providerId, modelId) =>
- providerId ? readModelContextLimit('codex', providerId, modelId) : null,
+ // Resolve settings by the actual provider route. Model specifications never
+ // overwrite a native usage report; explicit settings configure the CLI itself.
+ resolveModelContextLimit: (providerId, modelId) => {
+ const source = providerId ?? inferProviderIdForModel(modelId, 'codex');
+ return source ? readModelContextLimit('codex', source, modelId) : null;
+ },
resolveVerifiedContextWindow: (providerId, modelId) =>
resolveVerifiedContextWindow(getDesktopSelectableCatalog(), 'codex', providerId, modelId),
- resolveCodexThreadContextWindow: async (providerId, modelId) => {
- const contextWindow = resolveExplicitCustomContextWindow(
- getDesktopSelectableCatalog(),
- 'codex',
- providerId,
- modelId,
+ resolveCodexContextWindowInfo: (modelId, config, reportedUsableWindow) =>
+ readCodexContextWindowInfo({ codexHome: getCodexHome(), binaryPath: codexPath, modelId, config, reportedUsableWindow }),
+ resolveCodexThreadContextWindow: (providerId, modelId) => {
+ const source = providerId ?? inferProviderIdForModel(modelId, 'codex');
+ const override = source ? readModelContextLimit('codex', source, modelId) : null;
+ return override ?? resolveModelDefaultContextWindow(
+ getDesktopSelectableCatalog(), 'codex', source, modelId,
);
- if (contextWindow === null) return null;
- try {
- if (await bundledCodexCatalogHasModel(codexPath, modelId)) return contextWindow;
- desktopMakerLogger.debug(
- 'Codex custom context override skipped: bundled catalog has no matching model',
- );
- } catch (error) {
- desktopMakerLogger.warn(
- 'Codex custom context catalog preflight failed; using fallback model metadata',
- { error: error instanceof Error ? error.message : String(error) },
- );
- }
- return null;
},
onCodexLocalModelsListed: (models) => {
setDiscoveredCodexModels(mapCodexAppServerModelsToCatalog(models));
@@ -1693,7 +1683,8 @@ export function getMaker(): Maker {
}
: {}),
...(ready
- ? { codexCindyRemoteCompactionProviderId: CODEX_CINDY_COMPACT_PROVIDER_ID }
+ ? { codexCindyRemoteCompactionProviderId: CODEX_CINDY_COMPACT_PROVIDER_ID,
+ codexLocalCompactionProviderId: CODEX_SUMMARY_COMPACT_PROVIDER_ID }
: {}),
// oauth spawn 额外定义订阅直连 identity;Cindy codex/* 使用上面的 HTTP identity。
...(useOAuthBearer && ready
diff --git a/apps/desktop/src/main/maker-host/model-context-limit-store.ts b/apps/desktop/src/main/maker-host/model-context-limit-store.ts
index f91b2db93c..eca2b73ac3 100644
--- a/apps/desktop/src/main/maker-host/model-context-limit-store.ts
+++ b/apps/desktop/src/main/maker-host/model-context-limit-store.ts
@@ -108,8 +108,8 @@ function normalize(raw: unknown): ModelContextLimitPrefs {
return { limits: sanitizeLimits((raw as { limits?: unknown }).limits) };
}
-const store = createOverrideSettingsFile<ModelContextLimitPrefs>({
- filePath: () => ownerScopedUserDataPath('model-context-limit-prefs.json'),
+const createStore = (filePath: () => string) => createOverrideSettingsFile<ModelContextLimitPrefs>({
+ filePath,
defaults: DEFAULTS,
normalize,
log,
@@ -118,6 +118,8 @@ const store = createOverrideSettingsFile<ModelContextLimitPrefs>({
preserveUnreadableFile: true,
});
+let store = createStore(() => ownerScopedUserDataPath('model-context-limit-prefs.json'));
+
function readPrefs(): ModelContextLimitPrefs {
// 隐藏配置层级的文件也是正式契约:mtime 守卫让「直接手改文件」在下一次读取生效。
store.invalidateIfChanged();
@@ -182,6 +184,38 @@ export function writeModelContextLimits(
return next;
}
+/** Roll back only this edit if its dependent runtime refresh fails. */
+export async function writeModelContextLimitsWithRefresh(
+ targets: readonly { agent: AgentKind; providerId: string; modelId: string }[],
+ limit: number | null,
+ refresh: () => Promise<void>,
+): Promise<void> {
+ // Capture the original owner's file; an account switch must never restore into
+ // the new owner's preferences. Preserve mixed aliases and absent overrides.
+ const filePath = ownerScopedUserDataPath('model-context-limit-prefs.json');
+ const previous = { ...readModelContextLimits() };
+ const written = writeModelContextLimits(targets, limit);
+ try {
+ await refresh();
+ } catch (error) {
+ const originalStore = createStore(() => filePath);
+ const limits = { ...originalStore.read().limits };
+ for (const target of targets) {
+ const key = modelContextLimitKey(target.agent, target.providerId, target.modelId);
+ // Do not undo a newer edit made outside the serialized IPC writer.
+ if ((limits[key] ?? null) !== written) continue;
+ if (previous[key] === undefined) delete limits[key];
+ else limits[key] = previous[key];
+ }
+ try {
+ originalStore.writePatch({ limits });
+ } finally {
+ store = createStore(() => ownerScopedUserDataPath('model-context-limit-prefs.json'));
+ }
+ throw error;
+ }
+}
+
/** 清空全部上限 override(供应商级 / 整体「恢复默认」用)。 */
export function resetModelContextLimits(): void {
store.reset();
diff --git a/apps/desktop/src/main/maker-host/model-plane/localCatalogOverrides.ts b/apps/desktop/src/main/maker-host/model-plane/localCatalogOverrides.ts
index 532245b182..6bdfa444ee 100644
--- a/apps/desktop/src/main/maker-host/model-plane/localCatalogOverrides.ts
+++ b/apps/desktop/src/main/maker-host/model-plane/localCatalogOverrides.ts
@@ -486,3 +486,17 @@ export function hasLocalAddition(
if (!entry) return false;
return entryRootAgents(entry, providerId).includes(agent);
}
+
+/** A working default must not replace a context value explicitly supplied locally. */
+export function hasLocalContextWindowOverride(
+ overrides: ModelCatalogOverrides,
+ providerId: string,
+ modelId: string,
+ agent: RootAgentKind,
+): boolean {
+ return (['additions', 'patches'] as const).some(section => {
+ const entry = overrides[section][`${providerId}:${modelId}`];
+ return entry && entryMembershipAgents(entry, providerId).includes(agent) &&
+ effectiveFields(entry, agent).contextWindow !== undefined;
+ });
+}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
index 1946585f77..3c7d9bbe48 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
@@ -3652,6 +3652,24 @@ describe('model context limit IPC', () => {
const related = { providerId: 'openai', agent: 'claude-code' as const, modelId: 'chatgpt/gpt-6' };
const stamp = { dataOwnerId: 'owner-a', ownerGeneration: 1 };
+ it('returns native facts separately from model preferences without writing or launching a task', async () => {
+ const harness = new IpcHarness();
+ const native = { contextWindow: 272_000, usableContextWindow: 258_400, autoCompactTokenLimit: 244_800,
+ modelMaxContextWindow: 872_000, source: 'runtime' as const, fallbackModel: false };
+ const readCodexContextWindowInfo = vi.fn(async () => native);
+ const writeModelContextLimit = vi.fn();
+ registerProviderHandlers(harness, makeDeps({
+ readModelContextLimit: () => ({ limit: 1_000_000, isCustomized: true }),
+ writeModelContextLimit, readCodexContextWindowInfo,
+ }));
+ await expect(harness.invoke(MAKER_INVOKE.MODEL_CONTEXT_LIMIT_GET, { ...primary, sessionId: 'live-codex' }))
+ .resolves.toMatchObject({ limit: 1_000_000, codexContext: native });
+ expect(readCodexContextWindowInfo).toHaveBeenCalledWith(primary, 'live-codex');
+ expect(writeModelContextLimit).not.toHaveBeenCalled();
+ await expect(harness.invoke(MAKER_INVOKE.MODEL_CONTEXT_LIMIT_GET, { ...primary, sessionId: 123 }))
+ .rejects.toThrow();
+ });
+
it('validates every alias then writes one atomic edit with the current owner', async () => {
const harness = new IpcHarness();
const deps = makeDeps({
@@ -3670,6 +3688,32 @@ describe('model context limit IPC', () => {
expect(deps.writeModelContextLimit).toHaveBeenCalledTimes(1);
});
+ it('does not save a window when native catalog preparation fails', async () => {
+ const harness = new IpcHarness();
+ const writeModelContextLimit = vi.fn();
+ registerProviderHandlers(harness, makeDeps({
+ currentOwnerSession: () => ({ dataOwnerId: 'owner-a', generation: 1 }),
+ listProviders: async () => [catalogView('openai', { codex: ['gpt-6'] })],
+ readModelContextLimit: () => ({ limit: null, isCustomized: false }),
+ validateModelContextLimit: async () => { throw new Error('native catalog unavailable'); },
+ writeModelContextLimit,
+ }));
+ await expect(harness.invoke(MAKER_INVOKE.MODEL_CONTEXT_LIMIT_SET, primary, 1_000_000, stamp)).rejects.toThrow('native catalog unavailable');
+ expect(writeModelContextLimit).not.toHaveBeenCalled();
+ });
+
+ it('waits for runtime reconfiguration and reports failures for both save and reset', async () => {
+ const harness = new IpcHarness();
+ registerProviderHandlers(harness, makeDeps({
+ currentOwnerSession: () => ({ dataOwnerId: 'owner-a', generation: 1 }),
+ listProviders: async () => [catalogView('openai', { codex: ['gpt-6'] })],
+ readModelContextLimit: () => ({ limit: null, isCustomized: false }),
+ writeModelContextLimit: async () => { throw new Error('runtime refresh failed'); },
+ }));
+ await expect(harness.invoke(MAKER_INVOKE.MODEL_CONTEXT_LIMIT_SET, primary, 1_000_000, stamp)).rejects.toThrow();
+ await expect(harness.invoke(MAKER_INVOKE.MODEL_CONTEXT_LIMIT_RESET, primary, stamp)).rejects.toThrow();
+ });
+
it('rejects an owner change during asynchronous catalog validation without writing', async () => {
const harness = new IpcHarness();
let generation = 1;
diff --git a/apps/desktop/src/main/maker-ipc/providerHandlers.ts b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
index 12833b2ad5..42dbc8970d 100644
--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
@@ -14,6 +14,7 @@
* handler body 可脱 Electron 用 IpcHarness + 内存 db 直接 invoke 单测(规则 14)。
*/
+import type { CodexContextWindowInfo } from '@cindy/maker-core';
import {
isLoopbackProviderUrl,
isProviderRequestPath,
@@ -397,8 +398,10 @@ export interface ProviderHandlerDeps {
* 能区分「跟随默认」与「设了一个刚好等于默认的值」。write 传 null = 恢复默认(删 override)。
* 可选 —— 未注入(单测最小桩)时对应 handler 报 INTERNAL 而不是静默成功。
*/
+ readCodexContextWindowInfo?(target: ModelPriceOverrideTarget, sessionId?: string): Promise<CodexContextWindowInfo | null>;
readModelContextLimit?(target: ModelPriceOverrideTarget): ModelContextLimitView;
- writeModelContextLimit?(targets: readonly ModelPriceOverrideTarget[], limit: number | null): void;
+ validateModelContextLimit?(targets: readonly ModelPriceOverrideTarget[], limit: number): Promise<void>;
+ writeModelContextLimit?(targets: readonly ModelPriceOverrideTarget[], limit: number | null): void | Promise<void>;
}
/** 上下文上限的读回视图(与写入返回同形,UI 一次拿齐当前值与是否自定义)。 */
@@ -1502,7 +1505,15 @@ export function registerProviderHandlers(
assertTrustedProviderMutationSender(event);
const targets = parseContextTargets(input);
// 读不做目录成员校验:目录漂移后 UI 仍要能显示并清掉指向已下架 id 的陈旧 override。
- return readContextTargets(targets);
+ const view = readContextTargets(targets);
+ if (targets.length === 1 && targets[0]!.agent === 'codex') {
+ const sessionId = (input as { sessionId?: unknown }).sessionId;
+ if (sessionId !== undefined && (typeof sessionId !== 'string' || sessionId.length === 0 || sessionId.length > 200)) {
+ throwIpcError('INVALID_PARAMS', 'invalid context session id');
+ }
+ return { ...view, codexContext: await deps.readCodexContextWindowInfo?.(targets[0]!, sessionId as string | undefined) ?? null };
+ }
+ return view;
});
registry.handle(
@@ -1528,12 +1539,13 @@ export function registerProviderHandlers(
// 写入才校验目标在目录里:挡「合法长度但不存在的 id」被批量预埋进这份
// 无界 key-value 文件(与停用轴同一条防线)。
if (limit !== null) for (const t of targets) await requirePriceTargetModel(t);
+ if (limit !== null) await deps.validateModelContextLimit?.(targets, limit);
assertProviderMutationOwner(
ownerAtIngress,
'active account changed before persisting context limit override',
);
try {
- write(targets, limit);
+ await write(targets, limit);
} catch (err) {
log.warn('model context limit persist failed', {
providerId: target.providerId,
@@ -1563,7 +1575,7 @@ export function registerProviderHandlers(
'active account changed before resetting context limit override',
);
try {
- write(targets, null);
+ await write(targets, null);
} catch (err) {
log.warn('model context limit reset failed', {
providerId: target.providerId,
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 8107a29c33..3ca83a0dc1 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -10,6 +10,11 @@
* 老的 cc-agent:* / codex:* IPC handler 完全不动,新链路与老链路并行。
*/
+import { readCodexContextWindowInfo } from '../maker-host/codex-context-window.js';
+import { prepareCodexCustomContextCatalog } from '../maker-host/codex-custom-context-catalog.js';
+import { inferProviderIdForModel } from '../maker-host/provider-route.js';
+import { getCodexHome } from '../maker-host/auth-adapters.js';
+import { getCachedBinaryStatus } from '../agent-binaries/index.js';
import { AsyncLocalStorage } from 'node:async_hooks';
import { promises as fsp } from 'node:fs';
import os from 'node:os';
@@ -776,11 +781,11 @@ import {
} from '../maker-host/session-provider-store.js';
import { getActiveCatalog, setDiscoveredProviderModels } from '../maker-host/active-catalog.js';
import { readCompactionPct } from '../maker-host/compaction-settings-store.js';
-import { resolveVerifiedContextWindow } from '../maker-host/catalog-to-descriptors.js';
+import { resolveVerifiedContextWindow, resolveModelDefaultContextWindow } from '../maker-host/catalog-to-descriptors.js';
import {
isModelContextLimitCustomized,
readModelContextLimit,
- writeModelContextLimits,
+ writeModelContextLimitsWithRefresh,
} from '../maker-host/model-context-limit-store.js';
import { refreshXaiMediaModels } from '../maker-host/model-discovery/xai-media.js';
import { testProviderConnection } from '../maker-host/provider-diagnostics.js';
@@ -5314,8 +5319,24 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
clearModelPriceOverride,
stageClearProviderModelPriceOverrides: stageProviderModelPriceOverridesClear,
broadcastPricingChanged: broadcastReferenceModelPricing,
- // 上下文上限:不广播 —— 它不改任何已展示的目录字段,只影响**下一次**窗口评估
- // (resolveVerifiedContextWindow 每次调用现读 store)。写完 renderer 用返回值就地更新。
+ // Keep the catalog specification unchanged. Persist the override and refresh only
+ // matching Codex tasks at a turn boundary; the editor reads back the effective value.
+ readCodexContextWindowInfo: async (target, sessionId) => {
+ if (sessionId) {
+ const session = maker.getSession(sessionId);
+ if (session) return session.agentKind === 'codex' ? session.getCodexContextWindowInfo() : null;
+ }
+ const configured = await readCodexContextWindowInfo({
+ codexHome: getCodexHome(),
+ binaryPath: getCachedBinaryStatus('codex').binaryPath,
+ modelId: target.modelId,
+ contextWindowOverride: readModelContextLimit('codex', target.providerId, target.modelId)
+ ?? resolveModelDefaultContextWindow(getDesktopSelectableCatalog(), 'codex', target.providerId, target.modelId),
+ });
+ // Configuration refresh releases idle handles; the next send recreates one.
+ // Expose the actual next-start configuration, explicitly marked as pending.
+ return configured && sessionId ? { ...configured, pendingApply: true } : configured;
+ },
readModelContextLimit: (target) => ({
limit: readModelContextLimit(target.agent, target.providerId, target.modelId),
isCustomized: isModelContextLimitCustomized(
@@ -5324,8 +5345,40 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
target.modelId,
),
}),
- writeModelContextLimit: (targets, limit) => {
- writeModelContextLimits(targets, limit);
+ validateModelContextLimit: async (targets, limit) => {
+ for (const target of targets.filter((t) => t.agent === 'codex')) {
+ const binaryPath = getCachedBinaryStatus('codex').binaryPath;
+ if (!binaryPath) throw new Error('Codex runtime is unavailable');
+ await prepareCodexCustomContextCatalog({
+ binaryPath, codexHome: getCodexHome(), modelId: target.modelId, contextWindow: limit,
+ });
+ }
+ },
+ writeModelContextLimit: async (targets, limit) => {
+ const owner = getActiveAppSession();
+ await writeModelContextLimitsWithRefresh(targets, limit, async () => {
+ for (const active of maker.listActiveSessions()) {
+ if (getActiveAppSession().generation !== owner.generation) throw new Error('Account changed during context configuration');
+ const session = maker.getSession(active.id);
+ if (!session || session.agentKind !== 'codex' || session.remoteHostId) continue;
+ const source = getSessionProvider(active.id) ?? inferProviderIdForModel(session.model, 'codex');
+ if (!targets.some((t) => t.agent === 'codex' && t.providerId === source && t.modelId === session.model)) continue;
+ // An already pending model/provider switch will rebuild with the latest settings.
+ // Never replace that user intention with a same-model settings refresh.
+ if (getPendingCredentialSwitchTarget(active.id)) continue;
+ await applyRuntimeSetModelChange({
+ maker, sessionId: active.id, model: session.model,
+ providerId: getSessionProvider(active.id), forceSessionRebuild: true,
+ isSessionInTurn,
+ registerPendingCredentialSwitch: registerPendingCredentialSwitchForSession,
+ clearPendingCredentialSwitch: clearPendingCredentialSwitchForSession,
+ wakeSessionInputQueue: wakeSessionInputAfterCredentialSwitch,
+ getPendingCredentialSwitch: getPendingCredentialSwitchTarget,
+ codexAuthInjection: getCodexProxyAuthInjectionState(), logger: log,
+ });
+ }
+ if (getActiveAppSession().generation !== owner.generation) throw new Error('Account changed during context configuration');
+ });
},
// 通用 OAuth(目录 auth.oauth 描述符驱动):login 成功后 best-effort 拉动态模型发现
// (additions-only merge 进 active-catalog) 并广播 PROVIDER_CHANGED 让 UI 刷新连接态。
diff --git a/apps/desktop/src/renderer/__tests__/contextWindowDisplay.test.ts b/apps/desktop/src/renderer/__tests__/contextWindowDisplay.test.ts
index 30ad213b83..e20c619add 100644
--- a/apps/desktop/src/renderer/__tests__/contextWindowDisplay.test.ts
+++ b/apps/desktop/src/renderer/__tests__/contextWindowDisplay.test.ts
@@ -4,6 +4,35 @@ import { resolveDisplayContextWindow } from '@/lib/contextWindow';
import { makerChatStore } from '@/lib/makerChatStore';
describe('resolveDisplayContextWindow', () => {
+ it('does not combine previous usage with a window pending CLI restart', () => {
+ const input = { sdkContextWindow: 258_400, nativeContextWindow: 1_000_000,
+ runtimeWindowAuthoritative: true, modelContextWindow: 1_050_000 };
+ expect(resolveDisplayContextWindow({ ...input, nativeContextPending: true })).toBe(0);
+ expect(resolveDisplayContextWindow({ ...input, nativeContextPending: false })).toBe(1_000_000);
+ });
+ it.each([100_000, 128_000, 200_000, 272_000, 872_000])(
+ 'shows native Codex total %s regardless of model specs or usable-window snapshot',
+ (nativeContextWindow) => {
+ for (const verifiedContextWindow of [272_000, 1_050_000]) {
+ expect(resolveDisplayContextWindow({
+ sdkContextWindow: Math.floor(nativeContextWindow * 0.95),
+ nativeContextWindow,
+ runtimeWindowAuthoritative: true,
+ modelContextWindow: 1_050_000,
+ verifiedContextWindow,
+ })).toBe(nativeContextWindow);
+ }
+ },
+ );
+
+ it('shows unknown until native Codex total is read, even with catalog metadata', () => {
+ expect(resolveDisplayContextWindow({
+ sdkContextWindow: 258_400,
+ runtimeWindowAuthoritative: true,
+ verifiedContextWindow: 1_050_000,
+ })).toBe(0);
+ });
+
it('replaces a restored large window only with verified route metadata', () => {
expect(resolveDisplayContextWindow({
sdkContextWindow: 1_050_000,
@@ -56,6 +85,17 @@ describe('resolveDisplayContextWindow', () => {
});
describe('makerChatStore context window refresh', () => {
+ it('preserves Codex usage when a model selection supplies another catalog window', () => {
+ const sessionId = 'codex-context-window-switch-test';
+ makerChatStore.purgeSession(sessionId);
+ makerChatStore.setContextWindow(sessionId, 258_400);
+ makerChatStore.setSessionRuntime(sessionId, { agentKind: 'codex' });
+
+ makerChatStore.setContextWindow(sessionId, 1_050_000);
+ expect(makerChatStore.getSnapshot(sessionId).agentStatus.contextWindow).toBe(258_400);
+ makerChatStore.purgeSession(sessionId);
+ });
+
it('updates the displayed context window without waiting for the next turn', () => {
const sessionId = 'context-window-switch-test';
makerChatStore.purgeSession(sessionId);
diff --git a/apps/desktop/src/renderer/__tests__/useCodexContextWindow.test.tsx b/apps/desktop/src/renderer/__tests__/useCodexContextWindow.test.tsx
new file mode 100644
index 0000000000..c03e15ad2c
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/useCodexContextWindow.test.tsx
@@ -0,0 +1,50 @@
+// @vitest-environment jsdom
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { useCodexContextWindow } from '@/hooks/useCodexContextWindow';
+vi.mock('@/contexts/dataOwnerGeneration', () => ({
+ getDataOwnerGeneration: () => ({ generation: 1 }),
+ isDataOwnerGenerationCurrent: () => true,
+}));
+const originalApi = window.electronAPI;
+afterEach(() => Object.defineProperty(window, 'electronAPI', { configurable: true, value: originalApi }));
+function installApi(getModelContextLimit: unknown) {
+ Object.defineProperty(window, 'electronAPI', { configurable: true, value: { maker: { getModelContextLimit } } });
+}
+const info = { contextWindow: 272_000, usableContextWindow: 258_400, autoCompactTokenLimit: 244_800 };
+describe('native Codex capacity lookup', () => {
+ it('refreshes pending configuration when inspecting an idle task again', async () => {
+ const getModelContextLimit = vi.fn()
+ .mockResolvedValueOnce({ codexContext: { ...info, pendingApply: true } })
+ .mockResolvedValue({ codexContext: { ...info, contextWindow: 1_000_000, pendingApply: true } });
+ installApi(getModelContextLimit);
+ const { result, rerender } = renderHook(({ refreshKey }) => useCodexContextWindow({
+ enabled: true, providerId: 'xd', modelId: 'gpt', sessionId: 'idle-task', refreshKey,
+ }), { initialProps: { refreshKey: 'idle:0' } });
+ await waitFor(() => expect(result.current?.contextWindow).toBe(272_000));
+ rerender({ refreshKey: 'idle:1' });
+ await waitFor(() => expect(result.current).toMatchObject({ contextWindow: 1_000_000, pendingApply: true }));
+ });
+ it('queries only the existing task and ignores model preference limits', async () => {
+ const getModelContextLimit = vi.fn(async () => ({ limit: 1_000_000, codexContext: info }));
+ installApi(getModelContextLimit);
+ const { result } = renderHook(() => useCodexContextWindow({
+ enabled: true, providerId: 'xd', modelId: 'glm', sessionId: 'running-task', reportedWindow: 258_400,
+ }));
+ await waitFor(() => expect(result.current).toEqual(info));
+ expect(getModelContextLimit).toHaveBeenCalledWith({ agent: 'codex', providerId: 'xd', modelId: 'glm', sessionId: 'running-task' });
+ });
+ it('rejects delayed facts from the previously selected model', async () => {
+ let finish!: (value: unknown) => void;
+ const getModelContextLimit = vi.fn()
+ .mockReturnValueOnce(new Promise((resolve) => { finish = resolve; }))
+ .mockResolvedValue({ limit: 500_000 });
+ installApi(getModelContextLimit);
+ const { result, rerender } = renderHook(({ modelId }) => useCodexContextWindow({ enabled: true, providerId: 'xd', modelId }), {
+ initialProps: { modelId: 'gpt' },
+ });
+ rerender({ modelId: 'glm' });
+ await act(async () => finish({ codexContext: info }));
+ expect(result.current).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx b/apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx
index 4f982c9d42..baee153972 100644
--- a/apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx
@@ -1,3 +1,4 @@
+import { useCodexContextWindow } from '@/hooks/useCodexContextWindow';
import { localizedModelName } from '@/lib/modelDisplayNames';
import { Star, Zap } from 'lucide-react';
import { useTranslation } from 'react-i18next';
@@ -79,10 +80,10 @@ export function ModelConfigFlyout({
const displayName = localizedModelName(entry.displayName, t);
const showSlider = config.efforts.length > 1;
const contextWindow = config.capability?.contextWindow ?? 0;
- const codexDefaultContext =
- config.engine === 'codex' &&
- ['xd', 'openai', 'anthropic', 'xai'].includes(entry.providerId) &&
- contextWindow > 272_000;
+ const codexDefaultContext = config.engine === 'codex';
+ const codexContext = useCodexContextWindow({
+ enabled: codexDefaultContext, providerId: entry.providerId, modelId: config.wireModelId ?? entry.modelId,
+ });
const starred = state === 'favorite' || justFavorited;
const discount = price?.kind === 'priced' ? price.discount : undefined;
@@ -151,18 +152,18 @@ export function ModelConfigFlyout({
{contextWindow > 0 && (
<>
{' · '}
- {codexDefaultContext
- ? t('settings.providers.models.advanced.codexContextDefault')
- : t('newChat.modelSelector.meta.context', {
- value: formatContextWindow(contextWindow),
- })}
+ {t('newChat.modelSelector.meta.context', {
+ value: codexDefaultContext
+ ? codexContext ? formatContextWindow(codexContext.contextWindow) : t('settings.providers.models.advanced.codexContextUnknown')
+ : formatContextWindow(contextWindow),
+ })}
</>
)}
</div>
{codexDefaultContext && (
<p className="pt-1.5 text-11 leading-relaxed text-[var(--text-tertiary)]">
- {t('settings.providers.models.advanced.codexContextAdvanced')}
+ {t('ccAgent.layout.contextRing.codexAutoHint')}
</p>
)}
diff --git a/apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx b/apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx
index c75e55441f..323a57b353 100644
--- a/apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx
+++ b/apps/desktop/src/renderer/components/settings/ModelAdvancedDrawer.tsx
@@ -227,13 +227,7 @@ export function ModelAdvancedDrawer({
null;
const primaryModel = row && primaryAgent ? (row.byAgent[primaryAgent] ?? null) : null;
- // Built-in Codex uses its own process/model ceiling. A shared row edit must not
- // promise to expand it or silently write a Codex override along with Pi/Claude.
- const separateCodexContext = provider.source !== 'user' && Boolean(row?.byAgent.codex);
- const contextAgent =
- separateCodexContext && primaryAgent === 'codex'
- ? (row?.avail.find((agent) => agent !== 'codex') ?? null)
- : primaryAgent;
+ const contextAgent = primaryAgent;
const contextModel = contextAgent ? row?.byAgent[contextAgent] : null;
const contextTarget = useMemo(
@@ -244,20 +238,21 @@ export function ModelAdvancedDrawer({
agent: contextAgent,
modelId: contextModel.id,
relatedTargets: (row?.avail ?? [])
- .filter((a) => a !== contextAgent && !(separateCodexContext && a === 'codex'))
+ .filter((a) => a !== contextAgent)
.flatMap((agent) => {
const model = row?.byAgent[agent];
return model ? [{ providerId: provider.id, agent, modelId: model.id }] : [];
}),
}
: null,
- [contextAgent, contextModel, provider.id, row, separateCodexContext],
+ [contextAgent, contextModel, provider.id, row],
);
const ctx = useModelContextLimit(open ? contextTarget : null);
const [ctxDraft, setCtxDraft] = useState('');
const ctxDirtyRef = useRef(false);
- const defaultWindow = contextModel?.contextWindow ?? 0;
+ const defaultWindow = contextAgent === 'codex' && ctx.codexContext
+ ? ctx.codexContext.contextWindow : contextModel?.contextWindow ?? 0;
const routeWindow = primaryModel?.contextWindowMax ?? primaryModel?.contextWindow ?? 0;
const effectiveLimit = ctx.limit ?? (defaultWindow > 0 ? defaultWindow : null);
useEffect(() => {
@@ -632,30 +627,12 @@ export function ModelAdvancedDrawer({
{conversational && (
<Section
title={t('settings.providers.models.advanced.contextLimit')}
- hint={t('settings.providers.models.advanced.contextLimitHint')}
+ hint={t(/^(?:(?:codex|openai|chatgpt)\/)?gpt-/.test(primaryModel.id) && provider.source !== 'user' && ['openai', 'xd'].includes(provider.id)
+ ? 'settings.providers.models.advanced.contextLimitGptHint'
+ : 'settings.providers.models.advanced.contextLimitHint')}
>
- {separateCodexContext && (
- <p
- data-codex-context-note
- className="mb-2 text-12 leading-relaxed text-[var(--text-secondary)]"
- >
- {t('settings.providers.models.advanced.codexContextHint')}
- </p>
- )}
{contextTarget && (
<>
- {separateCodexContext && (
- <p className="mb-1 text-11 text-[var(--text-tertiary)]">
- {[
- contextTarget.agent,
- ...(contextTarget.relatedTargets ?? []).map(
- (target) => target.agent,
- ),
- ]
- .map((agent) => AGENT_LABEL[agent])
- .join(' / ')}
- </p>
- )}
<div className="mt-1 flex flex-wrap items-center gap-2.5">
<span
className={cn(
diff --git a/apps/desktop/src/renderer/components/settings/__tests__/ModelAdvancedDrawer.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/ModelAdvancedDrawer.test.tsx
index 1dedc8cae0..86e6032600 100644
--- a/apps/desktop/src/renderer/components/settings/__tests__/ModelAdvancedDrawer.test.tsx
+++ b/apps/desktop/src/renderer/components/settings/__tests__/ModelAdvancedDrawer.test.tsx
@@ -142,7 +142,7 @@ describe('model advanced editor', () => {
expect(setModelVisibility).not.toHaveBeenCalled();
});
- it('shows the exact maximum but excludes built-in Codex from shared context edits', () => {
+ it('shows the exact maximum and includes Codex in shared context edits', () => {
draw();
expect(screen.getByText('1,050,000')).toBeTruthy();
const input = screen.getByRole('textbox', {
@@ -158,13 +158,13 @@ describe('model advanced editor', () => {
expect(input.getAttribute('aria-invalid')).toBe('true');
expect(mocks.target).toHaveBeenLastCalledWith({
providerId: 'openai',
- agent: 'claude-code',
- modelId: 'chatgpt/gpt-6',
- relatedTargets: [],
+ agent: 'codex',
+ modelId: 'gpt-6',
+ relatedTargets: [{ providerId: 'openai', agent: 'claude-code', modelId: 'chatgpt/gpt-6' }],
});
});
- it('keeps a Codex-only built-in route read-only without removing the model specification', () => {
+ it('edits a Codex-only route without removing the model specification', () => {
render(
<ModelAdvancedDrawer
provider={provider}
@@ -177,14 +177,15 @@ describe('model advanced editor', () => {
paymentRequired={false}
/>,
);
- expect(screen.queryByRole('textbox')).toBeNull();
- expect(mocks.target).toHaveBeenLastCalledWith(null);
+ const input = screen.getByRole('textbox');
+ fireEvent.change(input, { target: { value: '1000' } });
+ fireEvent.blur(input);
+ expect(mocks.setLimit).toHaveBeenCalledWith(1_000_000);
expect(screen.getByText('1,050,000')).toBeTruthy();
- expect(screen.getByText('settings.providers.models.advanced.codexContextHint')).toBeTruthy();
- expect(mocks.setLimit).not.toHaveBeenCalled();
+ expect(screen.queryByText('settings.providers.models.advanced.codexContextHint')).toBeNull();
});
- it('preserves the explicit context editor for a custom Codex provider', () => {
+ it('uses the same context editor for custom Codex providers', () => {
render(
<ModelAdvancedDrawer
provider={{ ...provider, id: 'custom', source: 'user' }}
@@ -197,13 +198,11 @@ describe('model advanced editor', () => {
paymentRequired={false}
/>,
);
- expect(screen.getByRole('textbox')).toBeTruthy();
- expect(mocks.target).toHaveBeenLastCalledWith({
- providerId: 'custom',
- agent: 'codex',
- modelId: model.id,
- relatedTargets: [],
- });
+ const input = screen.getByRole('textbox');
+ fireEvent.change(input, { target: { value: '1000' } });
+ fireEvent.blur(input);
+ expect(mocks.setLimit).toHaveBeenCalledWith(1_000_000);
+ expect(screen.getAllByText('272K').length).toBeGreaterThan(0);
expect(screen.queryByText('settings.providers.models.advanced.codexContextHint')).toBeNull();
});
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
index 65e2defef6..16a30c9c63 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx
@@ -13,6 +13,7 @@
* F-FP-5: workingDir read-only display
*/
+import { useCodexContextWindow } from '@/hooks/useCodexContextWindow';
import {
Profiler,
useCallback,
@@ -5354,6 +5355,9 @@ export function CCAgentSessionView({
deviceLinkDeviceId={remoteDeviceId ?? null}
/>
<ContextCapacityRing
+ isRunning={agentStatus.isRunning}
+ sessionId={sessionId}
+ providerId={session?.providerId}
contextTokens={agentStatus.contextTokens}
model={agentSwitchIntent?.model ?? session?.model ?? ''}
vendorKey={normalizeDbAgentKind(displayAgentKind)}
@@ -5886,6 +5890,9 @@ function getModelContextWindow(
}
function ContextCapacityRing({
+ isRunning,
+ sessionId,
+ providerId,
contextTokens,
model,
vendorKey,
@@ -5894,6 +5901,9 @@ function ContextCapacityRing({
deviceId,
onCompact,
}: {
+ isRunning?: boolean;
+ sessionId?: string;
+ providerId?: string | null;
contextTokens: number;
model: string;
vendorKey: 'cc' | 'codex' | 'pi';
@@ -5906,9 +5916,18 @@ function ContextCapacityRing({
onCompact?: () => void;
}) {
const { t } = useTranslation();
+ const [contextInspection, setContextInspection] = useState(0);
+ const codexContext = useCodexContextWindow({
+ enabled: vendorKey === 'codex' && !deviceId && Boolean(sessionId),
+ providerId, modelId: model, sessionId, reportedWindow: sdkContextWindow,
+ refreshKey: `${isRunning}:${contextInspection}`,
+ });
const contextWindow = resolveDisplayContextWindow({
sdkContextWindow,
verifiedContextWindow,
+ runtimeWindowAuthoritative: vendorKey === 'codex',
+ nativeContextWindow: codexContext?.contextWindow,
+ nativeContextPending: codexContext?.pendingApply,
modelContextWindow: getModelContextWindow(model, vendorKey, deviceId),
});
const pct =
@@ -5971,7 +5990,7 @@ function ContextCapacityRing({
/>
</svg>
<span className="text-12 font-medium leading-none" style={{ color: fillColor }}>
- {pct}%
+ {contextWindow > 0 ? `${pct}%` : '—'}
</span>
</>
);
@@ -5985,10 +6004,18 @@ function ContextCapacityRing({
<div>{t('ccAgent.layout.contextRing.compactHint')}</div>
</>
) : vendorKey === 'codex' ? (
- // codex 协议没有手动 compact 入口(server 侧自动压缩),圆环不可点击;
- // tooltip 里说明原因,避免用户疑惑为什么 Claude 能点 codex 不能。
+ // Native Codex manages compaction; this control only reads its capacity.
<>
- <div>{tooltipText}</div>
+ <div>{codexContext?.pendingApply
+ ? t('ccAgent.layout.contextRing.codexPendingHint')
+ : tooltipText}</div>
+ <div>{codexContext
+ ? t('settings.providers.models.advanced.codexContextValues', {
+ total: codexContext.contextWindow.toLocaleString(),
+ usable: codexContext.usableContextWindow.toLocaleString(),
+ compact: codexContext.autoCompactTokenLimit.toLocaleString(),
+ })
+ : t('settings.providers.models.advanced.codexContextUnknown')}</div>
<div>{t('ccAgent.layout.contextRing.codexAutoHint')}</div>
</>
) : (
@@ -6006,7 +6033,10 @@ function ContextCapacityRing({
{ringContent}
</button>
) : (
- <div className="flex shrink-0 items-center gap-1">{ringContent}</div>
+ <div className="flex shrink-0 items-center gap-1"
+ onMouseEnter={() => { if (vendorKey === 'codex') setContextInspection(n => n + 1); }}>
+ {ringContent}
+ </div>
)}
</Tip>
);
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useModelContextLimit.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useModelContextLimit.test.ts
index 0d7fd6b486..75894dd53b 100644
--- a/apps/desktop/src/renderer/hooks/__tests__/useModelContextLimit.test.ts
+++ b/apps/desktop/src/renderer/hooks/__tests__/useModelContextLimit.test.ts
@@ -59,8 +59,36 @@ describe('context editor request ownership', () => {
expect(hook.result.current.limit).toBeNull();
hook.unmount();
});
+ it('rereads the actual committed value when a save rejects', async () => {
+ get.mockResolvedValueOnce(view(272_000)).mockResolvedValue(view(500_000));
+ set.mockRejectedValueOnce(new Error('runtime refresh/rollback failed'));
+ const hook = renderHook(() => useModelContextLimit(target));
+ await act(async () => {});
+ await act(async () => { await hook.result.current.setLimit(1_000_000); });
+ expect(get).toHaveBeenCalledTimes(2);
+ expect(hook.result.current.limit).toBe(500_000);
+ expect(hook.result.current.error).toBe(true);
+ hook.unmount();
+ });
+
+ it('ignores a failure recovery read after switching models', async () => {
+ const delayed = deferred<ReturnType<typeof view>>();
+ get.mockResolvedValueOnce(view(272_000)).mockReturnValueOnce(delayed.promise)
+ .mockResolvedValueOnce(view(128_000));
+ set.mockRejectedValueOnce(new Error('refresh failed'));
+ const hook = renderHook(({ modelId }) => useModelContextLimit({ ...target, modelId }),
+ { initialProps: { modelId: 'old' } });
+ await act(async () => {});
+ await act(async () => { void hook.result.current.setLimit(1_000_000); });
+ await act(async () => { hook.rerender({ modelId: 'new' }); });
+ await act(async () => { delayed.resolve(view(500_000)); });
+ expect(hook.result.current.limit).toBe(128_000);
+ expect(hook.result.current.error).toBe(false);
+ hook.unmount();
+ });
+
it('restores defaults by deletion and exposes failed saves', async () => {
- get.mockResolvedValue(view(500_000));
+ get.mockResolvedValueOnce(view(500_000)).mockResolvedValue(view(null));
set.mockResolvedValueOnce(view(null)).mockRejectedValueOnce(new Error('disk full'));
const hook = renderHook(() => useModelContextLimit(target));
await act(async () => {});
diff --git a/apps/desktop/src/renderer/hooks/useCodexContextWindow.ts b/apps/desktop/src/renderer/hooks/useCodexContextWindow.ts
new file mode 100644
index 0000000000..7b4e0f8f76
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/useCodexContextWindow.ts
@@ -0,0 +1,33 @@
+import { useEffect, useState } from 'react';
+import type { CodexContextWindowInfo } from '@cindy/maker-core';
+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
+
+/** Native read-only facts. Missing/old hosts stay unknown, never fall back to a model catalog. */
+export function useCodexContextWindow(options: {
+ enabled: boolean;
+ providerId?: string | null;
+ modelId: string;
+ sessionId?: string;
+ reportedWindow?: number;
+ refreshKey?: boolean | string;
+}) {
+ const { enabled, providerId, modelId, sessionId, reportedWindow, refreshKey } = options;
+ const key = JSON.stringify([providerId, modelId, sessionId, reportedWindow]);
+ const [state, setState] = useState<{ key: string; info: CodexContextWindowInfo | null }>({ key: '', info: null });
+ useEffect(() => {
+ if (!enabled || (!providerId && !sessionId) || !modelId) return;
+ let cancelled = false;
+ const owner = getDataOwnerGeneration();
+ const request = window.electronAPI?.maker?.getModelContextLimit?.({
+ agent: 'codex', providerId: providerId ?? 'codex', modelId, ...(sessionId ? { sessionId } : {}),
+ });
+ if (!request) return;
+ void request.then((view) => {
+ if (!cancelled && isDataOwnerGenerationCurrent(owner)) setState({ key, info: view.codexContext ?? null });
+ }).catch(() => {
+ if (!cancelled) setState({ key, info: null });
+ });
+ return () => { cancelled = true; };
+ }, [enabled, providerId, modelId, sessionId, reportedWindow, refreshKey, key]);
+ return enabled && state.key === key ? state.info : null;
+}
diff --git a/apps/desktop/src/renderer/hooks/useModelContextLimit.ts b/apps/desktop/src/renderer/hooks/useModelContextLimit.ts
index 198c2b2a4f..80ef48b921 100644
--- a/apps/desktop/src/renderer/hooks/useModelContextLimit.ts
+++ b/apps/desktop/src/renderer/hooks/useModelContextLimit.ts
@@ -32,12 +32,26 @@ export function useModelContextLimit(target: ModelContextLimitTarget | null) {
const current = () => request === generation.current && isDataOwnerGenerationCurrent(owner);
setState((prev) => ({ ...prev, loading: true, error: false }));
try {
- const view = write
+ let view = write
? await window.electronAPI.maker.setModelContextLimit(stableTarget, write.limit, stamp)
: await window.electronAPI.maker.getModelContextLimit(stableTarget);
+ if (write && stableTarget.agent === 'codex' && current()) {
+ view = await window.electronAPI.maker.getModelContextLimit(stableTarget);
+ }
if (current()) setState({ ...view, loading: false, error: false });
} catch (error) {
log.warn('model context limit request failed', error);
+ // A failed runtime refresh is rolled back by main. Read the committed
+ // value even if rollback/readback also failed; never retain a stale edit.
+ if (write && current()) {
+ try {
+ const view = await window.electronAPI.maker.getModelContextLimit(stableTarget);
+ if (current()) setState({ ...view, loading: false, error: true });
+ return;
+ } catch (readError) {
+ log.warn('model context limit recovery read failed', readError);
+ }
+ }
if (current()) setState((prev) => ({ ...prev, loading: false, error: true }));
}
},
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 74466ae7ab..624218d359 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -1799,7 +1799,7 @@
"defaultEffort": "Default reasoning effort",
"defaultEffortHint": "The initial effort for new tasks. You can still adjust it within a task.",
"contextLimit": "Context limit",
- "contextLimitHint": "Edit in whole K, rounded down for display. Exact configuration is preserved until edited. Saved changes apply to new or reopened tasks.",
+ "contextLimitHint": "Applies to all available engines for this model. Edit in whole K (1 K = 1,000 tokens); untouched values retain their precision. Saved changes apply to subsequent runs without interrupting a response. Actual capacity remains subject to the model service’s limits.",
"contextLimitAria": "Context limit (thousands of tokens)",
"contextLimitRoute": "Current {{tokens}} tokens · 1 K = 1,000 tokens",
"contextLimitOverWindow": "Above the provider’s declared window; requests may fail.",
@@ -1847,14 +1847,14 @@
"matching": "Native support",
"unknown": "Protocol unconfirmed"
},
- "codexContextDefault": "Codex defaults to 272K context",
- "codexContextHint": "Codex defaults to 272K context and compacts before reaching that limit. Changes here apply only to other engines. Larger windows require separate Codex configuration and are not recommended for everyday use.",
- "codexContextAdvanced": "Larger windows require separate Codex configuration and are not recommended for everyday use.",
"lifecycle": {
"alpha": "Early access",
"deprecated": "No longer recommended",
"retired": "Retired"
- }
+ },
+ "codexContextUnknown": "CLI configuration unavailable",
+ "codexContextValues": "Total {{total}} · Usable {{usable}} · Auto-compact {{compact}} tokens",
+ "contextLimitGptHint": "GPT defaults to at most 272K; you can set it to 1M here. Codex applies the window and automatic compaction threshold together, retaining 5% headroom. Actual capacity depends on the model service."
},
"kindFilter": {
"all": "All",
@@ -2841,7 +2841,7 @@
},
"compaction": {
"title": "Context compaction",
- "description": "Control when Claude Code and Pi automatically compact context. Codex manages context compaction separately.",
+ "description": "Adjust Claude Code and Pi compaction ratios here. Codex derives its threshold from the model context setting. If remote compaction fails, it automatically switches to summary compaction and keeps using it for the current task.",
"card": {
"label": "Compaction trigger threshold",
"badge": "Claude Code",
@@ -9106,7 +9106,8 @@
"projectContextLoaded": "Project Knowledge Base loaded",
"contextRing": {
"compactHint": "Click to compact context",
- "codexAutoHint": "Codex compacts automatically on the server side; manual compaction is not supported",
+ "codexPendingHint": "Settings apply on the next send. Current usage is not yet available.",
+ "codexAutoHint": "Codex CLI manages context and automatic compaction. This control is read-only.",
"confirmTitle": "Compact context?",
"confirmDescription": "Current usage: {{used}} / {{total}} ({{pct}}%). This silently compacts context — the agent summarizes chat history to free up context space.",
"confirmAction": "Compact",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 30a268dc50..3cfa22c6c4 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -1798,7 +1798,7 @@
"defaultEffort": "既定の推論強度",
"defaultEffortHint": "新しいタスクの初期推論強度です。タスク内でも変更できます。",
"contextLimit": "コンテキスト上限",
- "contextLimitHint": "整数 K で編集し、表示時は切り捨てます。編集するまで正確な設定を保持します。保存後は新規または再度開いたタスクに適用されます。",
+ "contextLimitHint": "このモデルのすべての利用可能なエンジンに適用されます。整数 K(1 K = 1,000 tokens)で編集します。未編集の値は精度を保持します。保存した変更は以降の実行に適用され、生成中の応答を中断しません。実際に利用できる長さはモデルサービスの制限に従います。",
"contextLimitAria": "コンテキスト上限(千 tokens)",
"contextLimitRoute": "現在 {{tokens}} tokens · 1 K = 1,000 tokens",
"contextLimitOverWindow": "プロバイダーが宣言した上限を超えています。リクエストが失敗する可能性があります。",
@@ -1846,14 +1846,14 @@
"matching": "ネイティブ対応",
"unknown": "プロトコル未確認"
},
- "codexContextDefault": "Codex の既定コンテキストは 272K",
- "codexContextHint": "Codex の既定コンテキストは 272K で、上限に達する前に自動圧縮します。ここでの変更は他のエンジンにのみ適用されます。拡張には Codex の個別設定が必要で、通常の利用には推奨しません。",
- "codexContextAdvanced": "拡張には Codex の個別設定が必要で、通常の利用には推奨しません。",
"lifecycle": {
"alpha": "試用版",
"deprecated": "非推奨",
"retired": "提供終了"
- }
+ },
+ "codexContextUnknown": "CLI 設定を取得できません",
+ "codexContextValues": "総容量 {{total}} · 使用可能 {{usable}} · 自動圧縮 {{compact}} tokens",
+ "contextLimitGptHint": "GPT は既定で最大 272K を使用します。ここで 1M に変更できます。Codex はウィンドウと自動圧縮のしきい値を同時に適用し、5% の余裕を確保します。実際の容量はモデルサービスに依存します。"
},
"kindFilter": {
"all": "すべて",
@@ -2840,7 +2840,7 @@
},
"compaction": {
"title": "コンテキスト圧縮",
- "description": "Claude Code と Pi がコンテキストを自動圧縮するタイミングを制御します。Codex は独自にコンテキスト圧縮を管理します。",
+ "description": "Claude Code と Pi の圧縮率をここで調整します。Codex はモデルのコンテキスト設定からしきい値を決定します。リモート圧縮に失敗すると要約による圧縮に自動で切り替え、現在のタスクで継続します。",
"card": {
"label": "圧縮トリガーしきい値",
"badge": "Claude Code",
@@ -9091,7 +9091,8 @@
"projectContextLoaded": "プロジェクトナレッジベースを読み込みました",
"contextRing": {
"compactHint": "クリックでコンテキストを圧縮",
- "codexAutoHint": "Codex はサーバー側で自動圧縮されるため、手動での圧縮はできません",
+ "codexPendingHint": "次回の送信時に設定が適用されます。現在の使用量はまだ取得されていません。",
+ "codexAutoHint": "コンテキストと自動圧縮は Codex CLI が管理します。ここは読み取り専用です。",
"confirmTitle": "コンテキストを圧縮しますか?",
"confirmDescription": "現在の使用量: {{used}} / {{total}}({{pct}}%)。コンテキストを静かに圧縮し、Agent が会話履歴を要約してコンテキスト領域を解放します。",
"confirmAction": "圧縮",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index f506099847..edc1657c29 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -1798,7 +1798,7 @@
"defaultEffort": "기본 추론 강도",
"defaultEffortHint": "새 작업의 초기 추론 강도입니다. 작업 안에서도 변경할 수 있습니다.",
"contextLimit": "컨텍스트 상한",
- "contextLimitHint": "정수 K로 편집하며 표시는 내림합니다. 편집 전까지 정확한 설정을 유지합니다. 저장하면 새 작업이나 다시 연 작업에 적용됩니다.",
+ "contextLimitHint": "이 모델의 모든 사용 가능한 엔진에 적용됩니다. 정수 K 단위로 편집합니다(1 K = 1,000 tokens). 수정하지 않은 값은 정밀도를 유지합니다. 저장한 변경 사항은 이후 실행에 적용되며 생성 중인 응답을 중단하지 않습니다. 실제로 사용할 수 있는 길이는 모델 서비스의 제한을 따릅니다.",
"contextLimitAria": "컨텍스트 상한(천 tokens)",
"contextLimitRoute": "현재 {{tokens}} tokens · 1 K = 1,000 tokens",
"contextLimitOverWindow": "공급업체가 명시한 한도를 초과하여 요청이 실패할 수 있습니다.",
@@ -1846,14 +1846,14 @@
"matching": "기본 지원",
"unknown": "프로토콜 미확인"
},
- "codexContextDefault": "Codex 기본 컨텍스트 272K",
- "codexContextHint": "Codex는 기본적으로 272K 컨텍스트를 사용하며 한도에 도달하기 전에 자동 압축합니다. 여기서 변경한 값은 다른 엔진에만 적용됩니다. 더 큰 창은 Codex를 별도로 설정해야 하며 일상적인 사용에는 권장하지 않습니다.",
- "codexContextAdvanced": "더 큰 창은 Codex를 별도로 설정해야 하며 일상적인 사용에는 권장하지 않습니다.",
"lifecycle": {
"alpha": "체험판",
"deprecated": "더 이상 권장하지 않음",
"retired": "제공 종료"
- }
+ },
+ "codexContextUnknown": "CLI 설정을 읽을 수 없음",
+ "codexContextValues": "전체 {{total}} · 사용 가능 {{usable}} · 자동 압축 {{compact}} tokens",
+ "contextLimitGptHint": "GPT는 기본적으로 최대 272K를 사용하며 여기서 1M으로 변경할 수 있습니다. Codex는 창과 자동 압축 임계값을 함께 적용하고 5%의 여유를 유지합니다. 실제 용량은 모델 서비스에 따라 다릅니다."
},
"kindFilter": {
"all": "전체",
@@ -2840,7 +2840,7 @@
},
"compaction": {
"title": "컨텍스트 압축",
- "description": "Claude Code와 Pi가 컨텍스트를 자동 압축할 시점을 제어합니다. Codex는 별도로 컨텍스트 압축을 관리합니다.",
+ "description": "여기서 Claude Code와 Pi의 압축 비율을 조정합니다. Codex는 모델 컨텍스트 설정에 따라 임계값을 정합니다. 원격 압축이 실패하면 요약 압축으로 자동 전환하고 현재 작업에서 계속 사용합니다.",
"card": {
"label": "압축 트리거 임계값",
"badge": "Claude Code",
@@ -9091,7 +9091,8 @@
"projectContextLoaded": "프로젝트 지식베이스 로드됨",
"contextRing": {
"compactHint": "클릭하여 컨텍스트 압축",
- "codexAutoHint": "Codex는 서버 측에서 자동으로 압축되며 수동 압축은 지원되지 않습니다",
+ "codexPendingHint": "다음 전송 시 설정이 적용됩니다. 현재 사용량은 아직 확인되지 않았습니다.",
+ "codexAutoHint": "Codex CLI가 컨텍스트와 자동 압축을 관리합니다. 여기서는 읽기만 가능합니다.",
"confirmTitle": "컨텍스트를 압축할까요?",
"confirmDescription": "현재 사용량: {{used}} / {{total}}({{pct}}%). 컨텍스트를 조용히 압축하여 Agent가 대화 기록을 요약하고 컨텍스트 공간을 확보합니다.",
"confirmAction": "압축",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index bdc37010df..eae98b6f51 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -1798,7 +1798,7 @@
"defaultEffort": "默认推理强度",
"defaultEffortHint": "新任务选中该模型时的初始档位,任务内仍可临时调整。",
"contextLimit": "上下文上限",
- "contextLimitHint": "以整数 K 编辑,显示时向下取整;未编辑时保留精确配置。保存后用于新建或重新打开的任务。",
+ "contextLimitHint": "用于此模型的所有可用引擎。以整数 K 编辑(1 K = 1,000 tokens);未编辑时保留精确值。保存后用于后续运行,正在生成的内容不受影响。实际可用长度仍受模型服务限制。",
"contextLimitAria": "上下文上限(千 tokens)",
"contextLimitRoute": "当前 {{tokens}} tokens · 1 K = 1,000 tokens",
"contextLimitOverWindow": "已超过上游声明的长度,可能导致请求失败。",
@@ -1846,14 +1846,14 @@
"matching": "原生支持",
"unknown": "协议待确认"
},
- "codexContextDefault": "Codex 默认 272K 上下文",
- "codexContextHint": "Codex 默认使用 272K 上下文,并提前自动压缩。这里的调整仅用于其他引擎;更大窗口需单独调整 Codex 配置,不建议日常使用。",
- "codexContextAdvanced": "更大窗口需单独调整 Codex 配置,不建议日常使用。",
"lifecycle": {
"alpha": "试用版",
"deprecated": "不再推荐",
"retired": "已下架"
- }
+ },
+ "codexContextUnknown": "未读取到 CLI 配置",
+ "codexContextValues": "总窗口 {{total}} · 可用 {{usable}} · 自动压缩 {{compact}} tokens",
+ "contextLimitGptHint": "GPT 默认最多使用 272K;可在此自定义到 1M。Codex 会同步应用窗口与自动压缩阈值,保留 5% 余量;实际容量受模型服务限制。"
},
"kindFilter": {
"all": "全部",
@@ -2840,7 +2840,7 @@
},
"compaction": {
"title": "上下文压缩",
- "description": "控制 Claude Code 和 Pi 何时自动压缩上下文。Codex 单独管理上下文压缩。",
+ "description": "Claude Code 和 Pi 的压缩比例在此调整。Codex 随模型设置的上下文上限自动调整压缩阈值;远端压缩失败时自动改用摘要压缩,并在当前任务中保持。",
"card": {
"label": "压缩触发阈值",
"badge": "Claude Code",
@@ -9091,7 +9091,8 @@
"projectContextLoaded": "项目知识库已加载",
"contextRing": {
"compactHint": "点击压缩上下文",
- "codexAutoHint": "Codex 由服务端自动压缩,不支持手动触发",
+ "codexPendingHint": "配置将在下次发送时应用,当前用量尚未读取。",
+ "codexAutoHint": "Codex CLI 管理上下文与自动压缩,此处只读。",
"confirmTitle": "压缩上下文?",
"confirmDescription": "当前已使用 {{used}} / {{total}}({{pct}}%)。将静默压缩上下文,由 Agent 总结历史对话并释放上下文空间。",
"confirmAction": "压缩",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 02d91fa7ff..0d2e60784e 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -1798,7 +1798,7 @@
"defaultEffort": "預設推理強度",
"defaultEffortHint": "新任務選中該模型時的初始檔位,任務內仍可臨時調整。",
"contextLimit": "上下文上限",
- "contextLimitHint": "以整數 K 編輯,顯示時向下取整;未編輯時保留精確設定。儲存後用於新建或重新開啟的任務。",
+ "contextLimitHint": "套用至此模型所有可用引擎。以整數 K 編輯(1 K = 1,000 tokens);未編輯時保留精確值。儲存後用於後續執行,不影響正在產生的內容。實際可用長度仍受模型服務限制。",
"contextLimitAria": "上下文上限(千 tokens)",
"contextLimitRoute": "目前 {{tokens}} tokens · 1 K = 1,000 tokens",
"contextLimitOverWindow": "已超過上游宣告的長度,可能導致請求失敗。",
@@ -1846,14 +1846,14 @@
"matching": "原生支援",
"unknown": "協定待確認"
},
- "codexContextDefault": "Codex 預設 272K 上下文",
- "codexContextHint": "Codex 預設使用 272K 上下文,並提前自動壓縮。這裡的調整僅用於其他引擎;更大視窗需另行調整 Codex 設定,不建議日常使用。",
- "codexContextAdvanced": "更大視窗需另行調整 Codex 設定,不建議日常使用。",
"lifecycle": {
"alpha": "試用版",
"deprecated": "不再推薦",
"retired": "已下架"
- }
+ },
+ "codexContextUnknown": "未讀取到 CLI 設定",
+ "codexContextValues": "總視窗 {{total}} · 可用 {{usable}} · 自動壓縮 {{compact}} tokens",
+ "contextLimitGptHint": "GPT 預設最多使用 272K;可在此自訂為 1M。Codex 會同步套用視窗與自動壓縮門檻,保留 5% 餘量;實際容量受模型服務限制。"
},
"kindFilter": {
"all": "全部",
@@ -2840,7 +2840,7 @@
},
"compaction": {
"title": "上下文壓縮",
- "description": "控制 Claude Code 和 Pi 何時自動壓縮上下文。Codex 會單獨管理上下文壓縮。",
+ "description": "Claude Code 和 Pi 的壓縮比例在此調整。Codex 隨模型設定的上下文上限自動調整壓縮門檻;遠端壓縮失敗時自動改用摘要壓縮,並在目前任務中保持。",
"card": {
"label": "壓縮觸發閾值",
"badge": "Claude Code",
@@ -9091,7 +9091,8 @@
"projectContextLoaded": "專案知識庫已載入",
"contextRing": {
"compactHint": "點選壓縮上下文",
- "codexAutoHint": "Codex 由服務端自動壓縮,不支援手動觸發",
+ "codexPendingHint": "設定將在下次傳送時套用,目前用量尚未讀取。",
+ "codexAutoHint": "Codex CLI 管理上下文與自動壓縮,此處唯讀。",
"confirmTitle": "壓縮上下文?",
"confirmDescription": "當前已使用 {{used}} / {{total}}({{pct}}%)。將靜默壓縮上下文,由 Agent 總結歷史對話並釋放上下文空間。",
"confirmAction": "壓縮",
diff --git a/apps/desktop/src/renderer/lib/contextWindow.ts b/apps/desktop/src/renderer/lib/contextWindow.ts
index 51f099f749..084750a978 100644
--- a/apps/desktop/src/renderer/lib/contextWindow.ts
+++ b/apps/desktop/src/renderer/lib/contextWindow.ts
@@ -4,6 +4,11 @@ interface ResolveDisplayContextWindowOptions {
sdkContextWindow: number;
modelContextWindow?: number;
verifiedContextWindow?: number | null;
+ /** Total capacity resolved from native CLI config/metadata, not its usable-window report. */
+ nativeContextWindow?: number | null;
+ nativeContextPending?: boolean;
+ /** Codex must not use provider metadata or a usable-window snapshot as its total. */
+ runtimeWindowAuthoritative?: boolean;
}
/**
@@ -17,7 +22,15 @@ export function resolveDisplayContextWindow({
sdkContextWindow,
modelContextWindow,
verifiedContextWindow,
+ runtimeWindowAuthoritative = false,
+ nativeContextWindow,
+ nativeContextPending = false,
}: ResolveDisplayContextWindowOptions): number {
+ if (runtimeWindowAuthoritative) {
+ if (nativeContextPending) return 0;
+ return Number.isFinite(nativeContextWindow) && (nativeContextWindow ?? 0) > 0
+ ? Math.floor(nativeContextWindow!) : 0;
+ }
// Restored snapshots and SDK values share this slot. Only route-verified
// metadata may supersede it, matching the host's runtime normalization.
if (Number.isFinite(verifiedContextWindow) && (verifiedContextWindow ?? 0) > 0) {
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index f6d404c760..c54af28b82 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -15211,6 +15211,8 @@ function setContextWindow(sessionId: string, contextWindow: number | undefined):
return;
const nextContextWindow = Math.floor(contextWindow);
setState(sessionId, (s) => {
+ // Model-selection metadata must not overwrite Codex's native usage snapshot.
+ if (s.agentKind === 'codex') return s;
if (s.agentStatus.contextWindow === nextContextWindow) return s;
return {
...s,
diff --git a/apps/desktop/src/shared/__tests__/sessionContextWindow.test.ts b/apps/desktop/src/shared/__tests__/sessionContextWindow.test.ts
index ae688d4eb2..366b7f4c02 100644
--- a/apps/desktop/src/shared/__tests__/sessionContextWindow.test.ts
+++ b/apps/desktop/src/shared/__tests__/sessionContextWindow.test.ts
@@ -22,7 +22,7 @@ function provider(id: string, row: CatalogModel = model): Provider {
};
}
const session = {
- agentKind: 'codex',
+ agentKind: 'cc',
model: model.id,
providerId: 'openai',
contextTokens: 140_500,
@@ -31,7 +31,7 @@ const session = {
const catalog: Pick<Catalog, 'providers'> = { providers: [provider('openai')] };
describe('session context read projection', () => {
- it.each(['cc', 'codex'])(
+ it.each(['cc', 'claude-code'])(
'corrects %s history without mutating its stored snapshot',
(agentKind) => {
const saved = { ...session, agentKind };
@@ -54,9 +54,11 @@ describe('session context read projection', () => {
expect(resolveSessionContextWindow(routes, { ...session, providerId: 'missing' })).toBeNull();
});
- it('preserves Pi runtime snapshots and unknown or unverified routes', () => {
+ it('preserves Codex and Pi runtime snapshots and unknown or unverified routes', () => {
for (const saved of [
{ ...session, agentKind: 'pi' },
+ { ...session, agentKind: 'codex', contextWindow: 258_400 },
+ { ...session, agentKind: 'codex', contextWindow: 828_400 },
{ ...session, model: '' },
]) {
expect(
diff --git a/apps/desktop/src/shared/modelContextLimit.ts b/apps/desktop/src/shared/modelContextLimit.ts
index 916d718802..45e2e9fdda 100644
--- a/apps/desktop/src/shared/modelContextLimit.ts
+++ b/apps/desktop/src/shared/modelContextLimit.ts
@@ -1,7 +1,10 @@
+import type { CodexContextWindowInfo } from '@cindy/maker-core';
import type { ModelPriceOverrideTarget } from './modelPriceOverride';
/** One model row can use different wire ids in different harnesses. */
export interface ModelContextLimitTarget extends ModelPriceOverrideTarget {
+ /** Read-only lookup of an existing task; never starts/resumes one. */
+ sessionId?: string;
relatedTargets?: ModelPriceOverrideTarget[];
}
export interface ModelContextLimitOwner {
@@ -9,6 +12,7 @@ export interface ModelContextLimitOwner {
ownerGeneration: number;
}
export interface ModelContextLimitView {
+ codexContext?: CodexContextWindowInfo | null;
limit: number | null;
isCustomized: boolean;
/** Legacy per-harness overrides differ; an edit/reset applies to the whole row. */
diff --git a/apps/desktop/src/shared/sessionContextWindow.ts b/apps/desktop/src/shared/sessionContextWindow.ts
index 323b275cef..3999e02778 100644
--- a/apps/desktop/src/shared/sessionContextWindow.ts
+++ b/apps/desktop/src/shared/sessionContextWindow.ts
@@ -9,8 +9,9 @@ export interface ContextWindowSession {
}
/**
- * Shared with runtime usage normalization: only an unambiguous, verified route
- * may replace a reported window. Never borrow a same-id model from another provider.
+ * Resolve catalog metadata for an unambiguous, verified route. Callers decide
+ * whether it is a fallback or a projection; it cannot replace native Codex usage.
+ * Never borrow a same-id model from another provider.
*/
export function resolveVerifiedContextWindow(
catalog: Pick<Catalog, 'providers'>,
@@ -32,12 +33,12 @@ export function resolveVerifiedContextWindow(
return Number.isFinite(only.contextWindow) && only.contextWindow > 0 ? only.contextWindow : null;
}
-/** Pi's runtime window can differ from its catalog; preserve its saved snapshot. */
+/** Codex and Pi report their effective runtime windows; catalogs cannot replace them. */
export function resolveSessionContextWindow(
catalog: Pick<Catalog, 'providers'>,
session: ContextWindowSession,
): number | null {
- if (!session.model || session.agentKind === 'pi') return null;
+ if (!session.model || session.agentKind === 'pi' || session.agentKind === 'codex') return null;
return resolveVerifiedContextWindow(
catalog,
dbToMakerAgentKind(session.agentKind),
diff --git a/docs/assets/codex-context-settings/gpt-default-dark.png b/docs/assets/codex-context-settings/gpt-default-dark.png
new file mode 100644
index 0000000000..49dd291f85
Binary files /dev/null and b/docs/assets/codex-context-settings/gpt-default-dark.png differ
diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.md
index 4cc400c727..c9655535f7 100644
--- a/docs/dev-rules/maker-core-and-agent-behavior.md
+++ b/docs/dev-rules/maker-core-and-agent-behavior.md
@@ -59,6 +59,17 @@ route,不能 resume 旧原生窗口。
先热切再发送。三个 harness 的同模型自动压缩所有权保持不变。token 破了只认:终态超限、
占用 ≥ 100%、官方 compact 确定性失败;普通 timeout 不算。
+Codex 已选远端压缩的本地任务,在原生 `contextCompaction` 生命周期内收到终态失败时,
+只有明确的 HTTP 400/404/405/422/500/501/502/503 拒绝或失败响应,才自动改用同一模型的
+原生摘要压缩;包括远端压缩耗尽内部重试后的短时 429,使用同一账号
+仅接替一次。明确的账号/任务额度耗尽、鉴权与已有密文硬失败交接分类保持原处理。
+这不是换窗交接:native fork 保留完整历史,Cindy 业务任务不变,不改模型或全局压缩设置。
+Codex 0.153 的 unsubscribe 会延迟卸载 30 分钟,不能靠立即 resume 假称 provider 已更新。
+接替身份保存在原生任务的 modelProvider 中,重新打开继续沿用,无 UI 开关、无自动切回。
+已有本轮模型/工具输出时以空输入续接,不重放用户请求;尚未进入生成的 pre-turn 失败才重投
+冻结输入。本地摘要再失败即正常报错,不循环切换。尚未结算的原生 exec continuation 无法跨
+线程迁移,不得重建后声称它仍可恢复。普通生成 502 与 stderr 文案不得触发此路径。
+
Codex 的 120 秒 reconnect watchdog 只是 fallback 收口,不是根因诊断。stderr 仍只作诊断日志,
不得用 `remote compaction v2` 文案驱动恢复动作。普通 timeout、纯文本大历史和网络失败
不得进入这套压缩,也不得进入自动续跑死循环。
diff --git a/docs/dev-rules/model-catalog-maintenance.md b/docs/dev-rules/model-catalog-maintenance.md
index ec37701ff0..3e5fca6d16 100644
--- a/docs/dev-rules/model-catalog-maintenance.md
+++ b/docs/dev-rules/model-catalog-maintenance.md
@@ -144,6 +144,21 @@ Gateway 先投影原生/兼容引擎与可用性,再选默认型号,不能
持久化快照及显示优先级。数据库里同一个大窗口数值,可能来自过去的上报,也可能来自
当前错误目录被当作 verified 写入;**仅凭旧任务或截图不能判断是哪一种**。
+Codex 的圆环总窗口由绑定的 CLI 配置和原生模型元数据解析;运行期的
+`modelContextWindow` 是预留空间后的可用容量,不能直接当作总窗口,也不能由 Cindy
+模型目录覆盖。总窗口、可用容量和自动压缩阈值分开展示;读取失败显示未知,不猜 272K。
+模型配置页的上下文上限统一写入该行所有引擎。未保存覆盖值时,Codex 也必须应用该供应商路由在设置页显示的默认窗口,不能只给自定义供应商注入窗口而漏掉 Gateway/订阅。Codex 使用每个任务独立的原生模型目录与
+thread 配置,同时设置窗口和 90% 自动压缩预算,保留原生 5% 可用空间预留及原有压缩方式。
+显式设置可以超过原生目录默认最大值;它改变 CLI 预算,不改变供应商实际能接受的长度。
+已运行任务在当前轮结束后重建执行句柄、保留原生历史;恢复默认删除 override。
+保存后的运行时刷新失败时,仅恢复本次修改的原账号 override(保留各引擎原值和缺席状态,
+不覆盖之后的外部修改);界面失败后重新读回实际持久值,不沿用旧快照。
+空闲任务释放执行句柄后,提示可读取下一次启动将应用的 CLI 配置,但必须标记待应用;不能把它当运行期窗口计算旧用量百分比。尚无实际用量时显示未知,不显示 0%。
+未知模型保留 Codex 原生 fallback 的提示词和工具元数据,不克隆 GPT 模板。
+`codex-native-fallback-prompt.md` 原样来自 OpenAI Codex `rust-v0.153.0` 的
+`codex-rs/models-manager/prompt.md`(Apache-2.0);升级 CLI 时需同步其 fallback 元数据与
+原生提示词清理规则,并以实际 CLI 验证窗口、压缩触发、历史恢复和提示词/工具不变。
+
修复显示时复用运行时已有的路由判定,保留数据来源边界。目录错误应回到 Server/发布
源修正;不要把某个模型的正确数字硬编码进圆环,也不要用取最小值一律压掉显式长窗口。
@@ -197,3 +212,14 @@ wire 字段或修改远程目录优先级。Server 仍可按原 schema/revision
不能用上游未翻译文本兜底、隐藏整个模型或阻断目录更新。不得按显示名称匹配简介,避免
用户重命名改变匹配;使用稳定的模型 ID。添加系列时补齐五语资源,覆盖测试遍历本地
Registry 的全部模型及其 routes,防止只翻译当前默认启用的几款。
+
+### GPT 日常窗口与 Codex Chat Completions(2026-09-06 用户裁决)
+
+- 内置 OpenAI 订阅与 XD 的 GPT 路由采用至多 272,000 tokens 的日常默认窗口,
+ 覆盖普通、`codex/`、`openai/`、`chatgpt/` 别名及各引擎。较小模型不扩容。
+ `contextWindowMax` 保留供应商容量;这是客户端工作默认策略,不修改服务端能力声明。
+- 显式上下文 override 仍优先,可设置 1M;恢复默认删除 override 后采用 272K。
+ 自定义供应商与非 GPT 模型不套用此默认策略。
+- Codex CLI 0.153.0 已移除原生 Chat Completions。Cindy 的既有转换路径仍可使用,
+ 但按 2026-09-07 用户更正,界面恢复「兼容模式」、默认关闭,允许用户手动开启。
+ 不新增「支持」协议分类;用户显式开关保持优先。GPT 窗口默认与自动压缩修复不回退。
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index a016a8de48..90e87ce84c 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -409,6 +409,8 @@ export interface CodexExtraSpawnConfig {
codexRemoteCompactionProviderId?: string;
/** Cindy Provider codex/* 的内部 OpenAI transport identity;固定走 HTTP。 */
codexCindyRemoteCompactionProviderId?: string;
+ /** Native summary identity persisted per thread after remote auto-compaction fails. */
+ codexLocalCompactionProviderId?: string;
/** Generic custom Provider identities and capabilities frozen into this app-server spawn. */
codexCustomProviderRoutes?: Array<{
providerId: string;
@@ -825,38 +827,35 @@ export interface AgentDeps {
ensureCodexBrowserUseReady: () => Promise<boolean>;
}) => CapabilityRoutingPolicy | undefined | Promise<CapabilityRoutingPolicy | undefined>;
- /**
- * 解析某条**具体路由**上该模型已核实的上下文窗口上限(host 注入);没有则返回 null。
- *
- * 用于把上游上报的窗口收敛到真实上限:app-server 对网关路由的模型常报**基础模型**的窗口
- * (例:目录 372K 的 GPT-5.6-Sol 被报成 1M),虚高值会让上下文占比被低估、memory flush
- * 阈值跟着推迟。
- *
- * 为什么不让 agent 自己查 `capabilities.availableModels`:那是跨 provider 去重后的扁平表,
- * 同一 model id 由多个 provider 提供时归属已丢,按 id 回查可能命中另一条路由的元数据 ——
- * 用错路由的上限收敛比不收敛更糟。host 同时持有完整目录与 provider 维度,由它按
- * (providerId, modelId) 定夺;目录里那些**派生兜底**的窗口(上游不给元数据时补的常量)
- * 一律不作为上限。
- *
- * 返回 null / 缺省不注入 = 不收敛,直接采信上报值(改动前行为)。
- */
/** Explicit user context budget for this route. Missing means native/catalog defaults. */
resolveModelContextLimit?: (
providerId: string | null | undefined,
modelId: string,
) => number | null;
+ /** Resolve native metadata using the exact app-server config and usage report. */
+ resolveCodexContextWindowInfo?: (
+ modelId: string,
+ config: Record<string, unknown>,
+ reportedUsableWindow: number | null,
+ ) => Promise<CodexContextWindowInfo | null>;
+
+ /**
+ * Resolve verified catalog capacity for a concrete (provider, model) route.
+ * Return null for unknown, ambiguous, or derived fallback metadata. Do not use
+ * the provider-deduplicated capabilities.availableModels table for this lookup.
+ * Codex uses this only until native reports its effective usable window;
+ * catalog metadata must not overwrite an observed native capacity.
+ */
resolveVerifiedContextWindow?: (
providerId: string | null | undefined,
modelId: string,
) => number | null;
/**
- * 自定义 Codex 供应商上用户显式填写的 contextWindow。会话启动时据此选择隔离
- * app-server,并写入 thread/start|resume 的 `config.model_context_window` 与
- * `config.model_auto_compact_token_limit`,让 app-server 按该窗口 auto-compact。
- * 可异步核对 Codex 静态目录;返回 null / 缺省 = 不覆盖(官方订阅继续用 live
- * catalog,目录外自定义 slug 继续走 Codex fallback metadata)。
+ * Per-model requested context window (user override first, explicit provider default second).
+ * A one-session native catalog permits this window without changing sibling routes.
+ * null preserves native defaults. A changed value requires a handle rebuild, preserving rollout.
*/
resolveCodexThreadContextWindow?: (
providerId: string | null | undefined,
@@ -893,9 +892,9 @@ export interface AgentDeps {
requestedCredentialMode?: AgentCredentialMode;
/** Marks app-server work that must not share the normal local task host. */
hostPurpose?: 'control-plane' | 'review' | 'custom-context';
- /** Exact real model slug whose static catalog entry must allow the custom window. */
+ /** Wire model id whose native catalog entry must allow the requested window. */
customContextModel?: string;
- /** Explicit custom-provider context window for a one-session custom-context host. */
+ /** Requested context window for a one-session custom-context host. */
customContextWindow?: number;
/** Unique app-server Host-generation identity used to scope custom-context resources. */
customContextHostKey?: string;
@@ -1927,11 +1926,24 @@ export interface AgentSessionTeardownOptions {
readonly reason: AgentSessionTeardownReason;
}
+/** Read-only native Codex capacity, separate from provider catalog specifications. */
+export interface CodexContextWindowInfo {
+ contextWindow: number;
+ usableContextWindow: number;
+ autoCompactTokenLimit: number;
+ modelMaxContextWindow: number | null;
+ source: 'runtime' | 'config';
+ fallbackModel: boolean;
+ /** No live CLI handle: these settings will be applied on the next send. */
+ pendingApply?: boolean;
+}
+
/**
* 一个已启动的 agent 会话句柄。
* 上层 Session 类持有此句柄并对外暴露 UI 友好的 API。
*/
export interface AgentSessionHandle {
+ getCodexContextWindowInfo?(): Promise<CodexContextWindowInfo | null>;
/** SDK 内部 sessionId,session.started 后会回填 */
readonly id: string;
readonly agentKind: AgentKind;
diff --git a/packages/maker-core/src/agents/codex/app-server/host.ts b/packages/maker-core/src/agents/codex/app-server/host.ts
index 5ad4e65da9..8a3c9ace41 100644
--- a/packages/maker-core/src/agents/codex/app-server/host.ts
+++ b/packages/maker-core/src/agents/codex/app-server/host.ts
@@ -278,6 +278,7 @@ export interface AppServerHostOptions {
remoteCompactionProviderId?: string;
/** Cindy Provider codex/* 的内部 OpenAI transport identity。 */
cindyRemoteCompactionProviderId?: string;
+ localCompactionProviderId?: string;
/** Generic custom Provider identities and capabilities frozen into this process. */
codexCustomProviderRoutes?: Array<{
providerId: string;
@@ -459,6 +460,10 @@ export class AppServerHost {
return this.opts.remoteCompactionProviderId ?? null;
}
+ getLocalCompactionProviderId(): string | null {
+ return this.opts.localCompactionProviderId ?? null;
+ }
+
getCindyRemoteCompactionProviderId(): string | null {
return this.opts.cindyRemoteCompactionProviderId ?? null;
}
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 449802745b..2d90216491 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -600,6 +600,7 @@ function installFakeHost(
codexBrowserMcpToolAvailable?: boolean;
remoteCompactionProviderId?: string;
cindyRemoteCompactionProviderId?: string;
+ localCompactionProviderId?: string;
codexCustomProviderRoutes?: Array<{
providerId: string;
modelProviderId: string;
@@ -741,6 +742,7 @@ function installFakeHost(
waitForMcpTool,
getRemoteCompactionProviderId,
getCindyRemoteCompactionProviderId,
+ getLocalCompactionProviderId: () => opts.localCompactionProviderId ?? null,
getCustomProviderModelProviderId,
getCustomProviderThreadPolicy,
getSessionMcpConfig,
@@ -4303,6 +4305,57 @@ describe('CodexAgent.startSession developerInstructions', () => {
await xaiHandle.close();
});
+ it.each([
+ { providerId: 'xd', resume: false },
+ { providerId: undefined, resume: false },
+ { providerId: 'xd', resume: true },
+ { providerId: undefined, resume: true },
+ ])('preserves remote compaction for Gateway GPT-6 (provider=$providerId, resume=$resume)', async ({ providerId, resume }) => {
+ const registerCodexSystemPromptForThread = vi.fn();
+ const agent = new CodexAgent(createDeps(
+ { systemPrompt: 'HOST PRODUCT PROMPT' },
+ { registerCodexSystemPromptForThread },
+ ));
+ const host = installFakeHost(agent, undefined, {
+ codexProxyActive: true,
+ remoteCompactionProviderId: 'cindy_openai',
+ cindyRemoteCompactionProviderId: 'cindy_codex',
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-gateway-gpt6',
+ model: 'codex/gpt-6-astra',
+ providerId,
+ workingDir: '/repo',
+ ...(resume ? { resumeSessionId: '11111111-1111-1111-1111-111111111111' } : {}),
+ });
+ const params = host.request.mock.calls.find(
+ ([method]) => method === (resume ? Method.ThreadResume : Method.ThreadStart),
+ )?.[1] as { model?: string; modelProvider?: string; developerInstructions?: string };
+ expect(params.model).toBe('codex/gpt-6-astra');
+ expect(params.modelProvider).toBe('cindy_codex');
+ expect(params.developerInstructions).toBeUndefined();
+ expect(registerCodexSystemPromptForThread).toHaveBeenCalled();
+ await handle.close();
+ });
+
+ it('preserves remote compaction for subscription GPT-6', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, undefined, {
+ codexProxyActive: true,
+ remoteCompactionProviderId: 'cindy_openai',
+ cindyRemoteCompactionProviderId: 'cindy_codex',
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-subscription-gpt6',
+ model: 'gpt-6-astra',
+ providerId: 'openai',
+ workingDir: '/repo',
+ });
+ expect(host.request.mock.calls.find(([method]) => method === Method.ThreadStart)?.[1])
+ .toMatchObject({ model: 'gpt-6-astra', modelProvider: 'cindy_openai' });
+ await handle.close();
+ });
+
it('selects one generic custom Provider identity for every eligible Responses model', async () => {
const registerCodexSystemPromptForThread = vi.fn();
const agent = new CodexAgent(createDeps(
@@ -8564,6 +8617,249 @@ describe('CodexAgent MCP thread context hooks', () => {
expect(host.subscribeThread).toHaveBeenCalledTimes(1);
});
+ describe('automatic remote compaction summary fallback', () => {
+ const failure = { message: 'unexpected status 502 Bad Gateway', codexErrorInfo: 'other' as const };
+ const nativeId = '0199ae4e-d6b0-7755-a755-66754cd7a847';
+ function setup(savedProvider = 'cindy_codex', resolveModelContextLimit = () => 1_000_000) {
+ const agent = new CodexAgent(createDeps({}, { resolveModelContextLimit }));
+ let turns = 0;
+ const host = installFakeHost(agent, (method, raw) => {
+ const params = raw as { threadId?: string; modelProvider?: string };
+ if (method === Method.TurnStart) return { turn: { id: `turn-${++turns}` } };
+ if (method === Method.ThreadFork) return { thread: { id: 'fork-thread-id' }, model: 'codex/gpt-6-astra', modelProvider: params.modelProvider };
+ if (method === Method.ThreadResume || method === Method.ThreadStart) {
+ return { thread: { id: params.threadId ?? nativeId }, model: 'codex/gpt-6-astra', modelProvider: params.modelProvider };
+ }
+ if (method === 'thread/read') return { thread: { id: nativeId, modelProvider: savedProvider } };
+ if (method === Method.TurnInterrupt) return {};
+ return undefined;
+ }, { codexProxyActive: true, cindyRemoteCompactionProviderId: 'cindy_codex', localCompactionProviderId: 'cindy_summary' });
+ return { agent, host };
+ }
+ async function start(savedProvider?: string) {
+ const { agent, host } = setup(savedProvider);
+ const handle = await agent.startSession({ sessionId: 'summary-task', providerId: 'xd',
+ model: 'codex/gpt-6-astra', workingDir: '/repo', ...(savedProvider ? { resumeSessionId: nativeId } : {}) });
+ const events: AgentEvent[] = [];
+ void (async () => { for await (const e of handle.events()) events.push(e); })();
+ await handle.send({ type: 'user', content: 'Finish my existing work.' });
+ return { host, handle, events };
+ }
+ function compact(host: ReturnType<typeof installFakeHost>, turnId = 'turn-1') {
+ host.getThreadHandlers()!.itemStarted!({ threadId: nativeId, turnId, item: { id: 'compact', type: 'contextCompaction' } });
+ }
+ function fail(host: ReturnType<typeof installFakeHost>, turnId = 'turn-1', error = failure) {
+ const h = host.getThreadHandlers()!;
+ h.error!({ threadId: nativeId, turnId, willRetry: false, error });
+ h.turnCompleted!({ threadId: nativeId, turn: { id: turnId, status: 'failed', error } });
+ }
+ it.each([false, true])('retains task history via a native fork, with partial output=%s', async (partial) => {
+ const { host, handle, events } = await start();
+ if (partial) host.getThreadHandlers()!.itemStarted!({ threadId: nativeId, turnId: 'turn-1',
+ item: { id: 'tool-done', type: 'commandExecution', command: 'echo done', cwd: '/repo' } });
+ compact(host);
+ fail(host);
+ await waitForExpectation(() => expect(handle.getCurrentTurnId?.()).toBe('turn-2'));
+
+ const resume = host.request.mock.calls.find(([m]) => m === Method.ThreadFork)![1];
+ expect(resume).toMatchObject({ threadId: nativeId, model: 'codex/gpt-6-astra', modelProvider: 'cindy_summary' });
+ const turns = host.request.mock.calls.filter(([m]) => m === Method.TurnStart);
+ expect(turns).toHaveLength(2);
+ expect(turns[1][1]).toMatchObject({ threadId: 'fork-thread-id', input: partial ? [] : [{ type: 'text', text: 'Finish my existing work.' }] });
+ expect(events.some(e => e.type === 'done' || e.type === 'error' && (e.data as { isTerminal?: boolean }).isTerminal)).toBe(false);
+ expect(events.filter(e => e.type === 'session_id')).toContainEqual({ type: 'session_id', data: 'fork-thread-id', source: 'codex' });
+ // Neither duplicate remote terminal nor a later local failure can retry again.
+ fail(host);
+ expect(handle.getCurrentTurnId?.()).toBe('turn-2');
+ compact(host, 'turn-2');
+ fail(host, 'turn-2');
+ await waitForExpectation(() => expect(handle.isTurnRunning?.()).toBe(false));
+ expect(host.request.mock.calls.filter(([m]) => m === Method.TurnStart)).toHaveLength(2);
+ await handle.close();
+ });
+ it('switches after remote compact exhausts 429 retries, only when the native turn finishes', async () => {
+ const { host, handle } = await start();
+ const error = { message: 'Error running remote compact task: exceeded retry limit, last status: 429 Too Many Requests',
+ codexErrorInfo: 'responseTooManyFailedAttempts' as const };
+ compact(host);
+ const h = host.getThreadHandlers()!;
+ h.error!({ threadId: nativeId, turnId: 'turn-1', willRetry: true, error });
+ expect(host.request.mock.calls.filter(([m]) => m === Method.ThreadFork)).toHaveLength(0);
+ h.error!({ threadId: nativeId, turnId: 'turn-1', willRetry: false, error });
+ expect(host.request.mock.calls.filter(([m]) => m === Method.ThreadFork)).toHaveLength(0);
+ h.turnCompleted!({ threadId: nativeId, turn: { id: 'turn-1', status: 'failed', error } });
+ await waitForExpectation(() => expect(handle.getCurrentTurnId?.()).toBe('turn-2'));
+ expect(host.request.mock.calls.find(([m]) => m === Method.ThreadFork)![1]).toMatchObject({
+ threadId: nativeId, modelProvider: 'cindy_summary', model: 'codex/gpt-6-astra',
+ });
+ await handle.close();
+ });
+ it.each(['usageLimitExceeded', 'sessionBudgetExceeded'] as const)('does not switch for exhausted %s', async (codexErrorInfo) => {
+ const { host, handle } = await start();
+ compact(host);
+ const error = { message: 'exceeded retry limit, last status: 429 Too Many Requests', codexErrorInfo };
+ const h = host.getThreadHandlers()!;
+ h.error!({ threadId: nativeId, turnId: 'turn-1', willRetry: false, error });
+ h.turnCompleted!({ threadId: nativeId, turn: { id: 'turn-1', status: 'failed', error } });
+ await new Promise(resolve => setTimeout(resolve, 10));
+ expect(host.request.mock.calls.filter(([m]) => m === Method.ThreadFork)).toHaveLength(0);
+ await handle.close();
+ });
+ it.each([
+ 'request timed out', 'network error: connection lost',
+ 'upstream unavailable', 'stream disconnected before completion',
+ 'unexpected status 408 Request Timeout', 'unexpected status 504 Gateway Timeout',
+ 'unexpected status 502: connection reset by peer',
+ ])('does not fork an uncertain compact failure: %s', async (message) => {
+ const { host, handle } = await start();
+ compact(host);
+ fail(host, 'turn-1', { message, codexErrorInfo: 'other' });
+ await waitForExpectation(() => expect(handle.isTurnRunning?.()).toBe(false));
+ expect(host.request.mock.calls.filter(([m]) => m === Method.ThreadFork)).toHaveLength(0);
+ await handle.close();
+ });
+ it.each([502, 503])('recovers explicit compact HTTP %s after the native turn has failed', async (status) => {
+ const { host, handle } = await start();
+ compact(host);
+ fail(host, 'turn-1', { message: `unexpected status ${status}`, codexErrorInfo: 'other' });
+ await waitForExpectation(() => expect(handle.getCurrentTurnId?.()).toBe('turn-2'));
+ expect(host.request.mock.calls.filter(([m]) => m === Method.ThreadFork)).toHaveLength(1);
+ await handle.close();
+ });
+ it('keeps the active native window when settings change during compaction', async () => {
+ let limit = 1_000_000;
+ const { agent, host } = setup('cindy_codex', () => limit);
+ const handle = await agent.startSession({ sessionId: 'summary-frozen-window', providerId: 'xd',
+ model: 'codex/gpt-6-astra', workingDir: '/repo' });
+ await handle.send({ type: 'user', content: 'Finish the work.' });
+ limit = 500_000;
+ compact(host); fail(host);
+ await waitForExpectation(() => expect(handle.getCurrentTurnId?.()).toBe('turn-2'));
+ expect(host.request.mock.calls.find(([m]) => m === Method.ThreadFork)![1]).toMatchObject({
+ config: { model_context_window: 1_000_000, model_auto_compact_token_limit: 900_000 },
+ });
+ await handle.close();
+ });
+ it.each([false, true])('retries transient 429 after summary only before user work; partial=%s', async (partial) => {
+ const { host, handle } = await start();
+ vi.useFakeTimers();
+ try {
+ compact(host); fail(host);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(handle.getCurrentTurnId?.()).toBe('turn-2');
+ const h = host.getThreadHandlers()!;
+ h.itemStarted!({ threadId: 'fork-thread-id', turnId: 'turn-2',
+ item: { id: 'summary-done', type: 'contextCompaction' } });
+ h.itemCompleted!({ threadId: 'fork-thread-id', turnId: 'turn-2',
+ item: { id: 'summary-done', type: 'contextCompaction' } });
+ if (partial) h.reasoningTextDelta?.({ threadId: 'fork-thread-id', turnId: 'turn-2', itemId: 'work', delta: 'doing user work' });
+ const error = { message: 'exceeded retry limit, last status: 429 Too Many Requests',
+ codexErrorInfo: 'responseTooManyFailedAttempts' as const };
+ const rateFail = (turnId: string) => {
+ h.error!({ threadId: 'fork-thread-id', turnId, willRetry: false, error });
+ h.turnCompleted!({ threadId: 'fork-thread-id', turn: { id: turnId, status: 'failed', error } });
+ };
+ rateFail('turn-2');
+ await vi.advanceTimersByTimeAsync(31_000);
+ let turns = host.request.mock.calls.filter(([m]) => m === Method.TurnStart);
+ expect(turns).toHaveLength(partial ? 2 : 3);
+ if (!partial) {
+ expect(turns[2][1]).toMatchObject({ threadId: 'fork-thread-id', input: [] });
+ rateFail('turn-3');
+ await vi.advanceTimersByTimeAsync(31_000);
+ turns = host.request.mock.calls.filter(([m]) => m === Method.TurnStart);
+ expect(turns).toHaveLength(4);
+ expect(turns[3][1]).toMatchObject({ threadId: 'fork-thread-id', input: [] });
+ rateFail('turn-4');
+ await vi.advanceTimersByTimeAsync(31_000);
+ expect(host.request.mock.calls.filter(([m]) => m === Method.TurnStart)).toHaveLength(4);
+ expect(host.request.mock.calls.filter(([m]) => m === Method.ThreadFork)).toHaveLength(1);
+ }
+ await handle.close();
+ } finally { vi.useRealTimers(); }
+ });
+ it('does not bill inherited usage again when the native fork replays it', async () => {
+ const { host, handle } = await start();
+ const old = { totalTokens: 100, inputTokens: 80, outputTokens: 20, cachedInputTokens: 0 };
+ host.getThreadHandlers()!.tokenUsageUpdated!({ threadId: nativeId, turnId: 'turn-1',
+ tokenUsage: { total: old, last: old } });
+ compact(host); fail(host);
+ await waitForExpectation(() => expect(handle.getCurrentTurnId?.()).toBe('turn-2'));
+ const usageBeforeReplay = handle.getUsageSnapshot().tokenUsage;
+ const handlers = host.getThreadHandlers()!;
+ handlers.tokenUsageUpdated!({ threadId: 'fork-thread-id', turnId: 'turn-2',
+ tokenUsage: { total: old, last: old } });
+ expect(handle.getUsageSnapshot().tokenUsage).toBe(usageBeforeReplay);
+ handlers.tokenUsageUpdated!({ threadId: 'fork-thread-id', turnId: 'turn-2', tokenUsage: {
+ total: { totalTokens: 110, inputTokens: 88, outputTokens: 22, cachedInputTokens: 0 },
+ last: { totalTokens: 10, inputTokens: 8, outputTokens: 2, cachedInputTokens: 0 },
+ } });
+ expect(handle.getUsageSnapshot().tokenUsage).toBe(usageBeforeReplay + 10);
+ await handle.close();
+ });
+ it('honors the persisted summary provider when reopening the task', async () => {
+ const { host, handle } = await start('cindy_summary');
+ expect(host.request.mock.calls.find(([m]) => m === Method.ThreadResume)![1]).toMatchObject({ modelProvider: 'cindy_summary' });
+ compact(host); fail(host);
+ expect(host.request.mock.calls.filter(([m]) => m === Method.TurnStart)).toHaveLength(1);
+ await handle.close();
+ });
+ it('does not switch on an ordinary generation 502', async () => {
+ const { host, handle } = await start();
+ fail(host);
+ expect(host.unsubscribeThread).not.toHaveBeenCalled();
+ expect(host.request.mock.calls.filter(([m]) => m === Method.TurnStart)).toHaveLength(1);
+ await handle.close();
+ });
+ it('does not switch after a successful compaction followed by a generation error', async () => {
+ const { host, handle } = await start();
+ compact(host);
+ host.getThreadHandlers()!.itemCompleted!({ threadId: nativeId, turnId: 'turn-1', item: { id: 'compact', type: 'contextCompaction' } });
+ fail(host);
+ expect(host.unsubscribeThread).not.toHaveBeenCalled();
+ await handle.close();
+ });
+ it('honors Stop while waiting for the failed native turn to finish', async () => {
+ const { host, handle } = await start();
+ compact(host);
+ host.getThreadHandlers()!.error!({ threadId: nativeId, turnId: 'turn-1', willRetry: false, error: failure });
+ await handle.abort();
+ fail(host);
+ expect(host.unsubscribeThread).not.toHaveBeenCalled();
+ expect(host.request.mock.calls.filter(([m]) => m === Method.TurnStart)).toHaveLength(1);
+ await handle.close();
+ });
+ it('does not continue if Stop arrives while the history fork is pending', async () => {
+ const { host, handle } = await start();
+ const original = host.request.getMockImplementation()!;
+ let resolveFork!: (value: unknown) => void;
+ host.request.mockImplementation((method, params) => method === Method.ThreadFork
+ ? new Promise(resolve => { resolveFork = resolve; }) : original(method, params));
+ compact(host); fail(host);
+ await waitForExpectation(() => expect(resolveFork).toBeTypeOf('function'));
+ await handle.abort();
+ resolveFork({ thread: { id: 'fork-thread-id' }, model: 'codex/gpt-6-astra', modelProvider: 'cindy_summary' });
+ await new Promise(resolve => setTimeout(resolve, 10));
+ expect(host.request.mock.calls.filter(([m]) => m === Method.TurnStart)).toHaveLength(1);
+ expect(handle.isTurnRunning?.()).toBe(false);
+ await handle.close();
+ });
+ it('surfaces a failed history fork without leaving the task running', async () => {
+ const { host, handle, events } = await start();
+ const original = host.request.getMockImplementation()!;
+ host.request.mockImplementation(async (method, params) => {
+ if (method === Method.ThreadFork) throw new Error('fork unavailable');
+ return original(method, params);
+ });
+ compact(host); fail(host);
+ await waitForExpectation(() => expect(events.some(e => e.type === 'error' && (e.data as { isTerminal?: boolean }).isTerminal)).toBe(true));
+ expect(handle.isTurnRunning?.()).toBe(false);
+ expect(host.request.mock.calls.filter(([m]) => m === Method.TurnStart)).toHaveLength(1);
+ await handle.close();
+ });
+
+ });
+
describe('websocket body recovery auto-retry', () => {
const ENCRYPTED_ERROR =
'Encrypted content could not be decrypted or parsed. code=invalid_encrypted_content';
@@ -28801,6 +29097,26 @@ describe('CodexAgent reconnect-stall watchdog', () => {
}
});
+ it('successful native compaction clears the old reconnect deadline before continuation', async () => {
+ vi.useFakeTimers();
+ try {
+ const agent = new CodexAgent(createDeps());
+ const { handle, handlers, seen } = await startReconnectTurn(agent, 'session-compact-recovered');
+ handlers.itemStarted?.({ threadId: 'start-thread-id', turnId: 'turn-1',
+ item: { id: 'compact-recovery', type: 'contextCompaction' } });
+ emitReconnect(handlers, 1);
+ await vi.advanceTimersByTimeAsync(100_000);
+ handlers.itemCompleted?.({ threadId: 'start-thread-id', turnId: 'turn-1',
+ item: { id: 'compact-recovery', type: 'contextCompaction' } });
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(seen.some(event => event.type === 'compact_boundary')).toBe(true);
+ expect(seen.some(event => event.type === 'error'
+ && (event.data as { reason?: string }).reason === 'codex_reconnect_stalled')).toBe(false);
+ expect(handle.isTurnRunning?.()).toBe(true);
+ await handle.close();
+ } finally { vi.useRealTimers(); }
+ });
+
it('deadline 内重新收到 thinking 或工具产出后不再触发', async () => {
vi.useFakeTimers();
try {
@@ -29213,7 +29529,7 @@ describe('CodexAgent context window reporting', () => {
reasoningOutputTokens: 3,
};
- function pushUsage(handlers: ThreadEventHandlers, turnId: string, appServerWindow: number): void {
+ function pushUsage(handlers: ThreadEventHandlers, turnId: string, appServerWindow: number | null): void {
handlers.tokenUsageUpdated?.({
threadId: 'start-thread-id',
turnId,
@@ -29229,7 +29545,7 @@ describe('CodexAgent context window reporting', () => {
agent: CodexAgent,
sessionId: string,
model: string,
- appServerWindow: number,
+ appServerWindow: number | null,
): Promise<number> {
const host = installFakeHost(agent);
const handle = await agent.startSession({ sessionId, model, workingDir: '/repo' });
@@ -29247,7 +29563,52 @@ describe('CodexAgent context window reporting', () => {
return contextWindow;
}
- it('把 app-server 上报的基础模型窗口收敛到该路由已核实的上限', async () => {
+ it('does not let a resumed historical usage window override the newly accepted runtime configuration', async () => {
+ const resolveCodexContextWindowInfo = vi.fn(async () => null);
+ const agent = new CodexAgent(createDeps({}, {
+ resolveModelContextLimit: () => 1_000_000, resolveCodexContextWindowInfo,
+ }));
+ const host = installFakeHost(agent, method => {
+ if (method === Method.ConfigRead) return { config: {} };
+ if (method === Method.TurnStart) return { turn: { id: 'turn-new' } };
+ return undefined;
+ });
+ const handle = await agent.startSession({ sessionId: 'resumed-window-generation', model: GATEWAY_MODEL, workingDir: '/repo' });
+ const handlers = host.getThreadHandlers()!;
+ // A real app-server cold resume can replay the previous run's 32K usage.
+ pushUsage(handlers, '', 30_400);
+ await handle.send({ type: 'user', content: 'Continue with the expanded context.' });
+ await handle.getCodexContextWindowInfo?.();
+ expect(resolveCodexContextWindowInfo).toHaveBeenLastCalledWith(GATEWAY_MODEL,
+ expect.objectContaining({ model_context_window: 1_000_000, model_auto_compact_token_limit: 900_000 }), null);
+ pushUsage(handlers, 'turn-new', 950_000);
+ await handle.getCodexContextWindowInfo?.();
+ expect(resolveCodexContextWindowInfo).toHaveBeenLastCalledWith(GATEWAY_MODEL,
+ expect.objectContaining({ model_context_window: 1_000_000 }), 950_000);
+ await handle.close();
+ });
+
+ it('reads the bound CLI configuration without changing it or using the provider catalog', async () => {
+ const nativeInfo = { contextWindow: 272_000, usableContextWindow: 258_400, autoCompactTokenLimit: 244_800,
+ modelMaxContextWindow: 872_000, source: 'runtime' as const, fallbackModel: false };
+ const resolveCodexContextWindowInfo = vi.fn(async () => nativeInfo);
+ const agent = new CodexAgent(createDeps({}, { resolveCodexContextWindowInfo, resolveVerifiedContextWindow: () => 1_050_000 }));
+ const host = installFakeHost(agent, (method) => method === Method.ConfigRead
+ ? { config: { model_context_window: 500_000, model_catalog_json: '/native/models.json' } }
+ : undefined);
+ const handle = await agent.startSession({ sessionId: 'native-context-facts', model: GATEWAY_MODEL, workingDir: '/repo' });
+ const handlers = host.getThreadHandlers()!;
+ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-1' } } as never);
+ pushUsage(handlers, 'turn-1', 258_400);
+ const callsBefore = host.request.mock.calls.length;
+ await expect(handle.getCodexContextWindowInfo!()).resolves.toEqual(nativeInfo);
+ expect(resolveCodexContextWindowInfo).toHaveBeenCalledWith(GATEWAY_MODEL,
+ { model_context_window: 500_000, model_catalog_json: '/native/models.json' }, 258_400);
+ expect(host.request.mock.calls.slice(callsBefore).map(([method]) => method)).toEqual([Method.ConfigRead]);
+ await handle.close();
+ });
+
+ it('保留 app-server 实际窗口,不被较小的目录值覆盖', async () => {
expect(
await reportedContextWindow(
agentWithWindows({ [GATEWAY_MODEL]: 372_000 }),
@@ -29255,15 +29616,10 @@ describe('CodexAgent context window reporting', () => {
GATEWAY_MODEL,
1_000_000,
),
- ).toBe(372_000);
+ ).toBe(1_000_000);
});
- // 2026-08-04 语义变更: 上报值更小时**不再**取上报值。原先的 min() 前提是「上报值可信,
- // 只是可能虚高」, 实测证伪 —— 会话中途切模型后 codex 继续上报切换前那个模型的窗口
- // (旧模型 258400 vs 新模型的真实窗口), min() 会把已核实的正确窗口拉回旧值, 上下文占比
- // 与 memory flush 阈值全程按错的窗口走。「路由真被降窗」与「上报值陈旧」在协议上无法
- // 区分(都只是一个更小的数字), 二选一时信我们自己按 (provider, model) 核实过的那份。
- it('上报值更小时仍取已核实窗口(与陈旧上报值无法区分,不采信)', async () => {
+ it('保留 native 较小的可用窗口,不被较大的目录值覆盖', async () => {
expect(
await reportedContextWindow(
agentWithWindows({ [GATEWAY_MODEL]: 372_000 }),
@@ -29271,12 +29627,10 @@ describe('CodexAgent context window reporting', () => {
GATEWAY_MODEL,
128_000,
),
- ).toBe(372_000);
+ ).toBe(128_000);
});
- // 本次故障的核心回归 (rollout 019fcd52 实测): 切模型后 codex 一直上报旧模型的
- // 258400, 新模型的已核实窗口必须压过它 —— 否则整个会话按旧窗口核算上下文。
- it('切模型后上游仍报旧模型窗口时,按新模型的已核实窗口核算', async () => {
+ it('切模型后仍保留 native 实际窗口,等待新上报更新', async () => {
const agent = agentWithVerified((_p, modelId) =>
modelId === 'claude-opus-5' ? 1_000_000 : 258_400,
);
@@ -29296,11 +29650,19 @@ describe('CodexAgent context window reporting', () => {
if (!handle.setModel) throw new Error('expected setModel support');
await handle.setModel('claude-opus-5');
- // 切模型后的新 turn: 上游**仍**报 258400(这正是上游的 bug), 我们必须按新模型算。
+ // 目录切换不代表 native 已扩大窗口; 容量仍以新 turn 的实际报告为准。
await handle.send({ type: 'user', content: 'again' });
handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-2' } } as never);
pushUsage(handlers, 'turn-2', 258_400);
- expect(handle.getUsageSnapshot().contextWindow).toBe(1_000_000);
+ expect(handle.getUsageSnapshot().contextWindow).toBe(258_400);
+ pushUsage(handlers, 'turn-2', null);
+ expect(handle.getUsageSnapshot().contextWindow).toBe(258_400);
+ pushUsage(handlers, 'turn-2', 950_000);
+ expect(handle.getUsageSnapshot().contextWindow).toBe(950_000);
+ for (const missingWindow of [null, 0, -1, NaN, Infinity]) {
+ pushUsage(handlers, 'turn-2', missingWindow);
+ expect(handle.getUsageSnapshot().contextWindow).toBe(950_000);
+ }
await handle.close();
});
@@ -29328,9 +29690,7 @@ describe('CodexAgent context window reporting', () => {
).toBe(1_000_000);
});
- // 解析器每次调用都读 live 目录(host 侧实现如此),所以会话中途的目录刷新即时生效 ——
- // 不能在会话启动时把结果缓存住。
- it('解析结果随目录刷新即时生效,不被会话启动时缓存住', async () => {
+ it('目录刷新不能替换 native 实际窗口', async () => {
let live = 200_000;
const agent = agentWithVerified((_p, modelId) => (modelId === GATEWAY_MODEL ? live : null));
const host = installFakeHost(agent);
@@ -29350,13 +29710,13 @@ describe('CodexAgent context window reporting', () => {
handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-1' } } as never);
pushUsage(handlers, 'turn-1', 1_000_000);
- expect(handle.getUsageSnapshot().contextWindow).toBe(372_000);
+ expect(handle.getUsageSnapshot().contextWindow).toBe(1_000_000);
await handle.close();
});
// 会话实际路由的 provider 必须传给 host —— 同一个无前缀 id 可能同时来自订阅直连与网关,
// 只有按 providerId 才能取到该路由声明的上限(否则这个常见配置下收敛会整个失效)。
- it('把会话的 providerId 传给解析器', async () => {
+ it('缺失 native 窗口时按 providerId 解析目录兜底', async () => {
const seen: Array<string | null | undefined> = [];
const agent = agentWithVerified((providerId, modelId) => {
seen.push(providerId);
@@ -29376,7 +29736,7 @@ describe('CodexAgent context window reporting', () => {
if (!handlers) throw new Error('expected thread handlers');
handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-1' } } as never);
- pushUsage(handlers, 'turn-1', 1_000_000);
+ pushUsage(handlers, 'turn-1', null);
expect(handle.getUsageSnapshot().contextWindow).toBe(372_000);
expect(seen).toContain('xd');
@@ -29385,7 +29745,7 @@ describe('CodexAgent context window reporting', () => {
// daemon 重启后 turn/start 报 "thread not found" 会走 thread/resume + 重投; 若会话是用
// 'gpt-5' 哨兵启动的, resume 会把它解析成具体路由模型并重写 turnParams.model。快照必须
- // 跟着改写走 —— 否则重投 turn 的用量按 'gpt-5' 去问 host(拿不到上限), 保留 1M。
+ // 跟着改写走 —— 否则重投 turn 的用量按 'gpt-5' 去问 host(拿不到上限), 无法取得兜底。
it('daemon 恢复重写模型后刷新 turn 模型快照', async () => {
const agent = agentWithWindows({ [GATEWAY_MODEL]: 372_000 });
let turnStartCount = 0;
@@ -29419,7 +29779,7 @@ describe('CodexAgent context window reporting', () => {
const handlers = host.getThreadHandlers();
if (!handlers) throw new Error('expected thread handlers');
handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-2' } } as never);
- pushUsage(handlers, 'turn-2', 1_000_000);
+ pushUsage(handlers, 'turn-2', null);
expect(handle.getUsageSnapshot().contextWindow).toBe(372_000);
await handle.close();
@@ -29427,7 +29787,7 @@ describe('CodexAgent context window reporting', () => {
// server 会把请求的 model id 规范化后经 thread/settings/updated 回带(实测 `gpt-5.4` →
// `gpt-5.4-codex`),那个 wire 变体在产品目录里不存在。窗口上限按目录条目精确查,所以
- // 快照必须用**目录 id**而不是 wire 值 —— 否则规范化之后就再也查不到、停止收敛。
+ // 快照必须用**目录 id**而不是 wire 值 —— 否则规范化之后就再也查不到、丢失兜底。
it('server 规范化 model id 后仍按目录 id 解析上限', async () => {
const asked: string[] = [];
const agent = agentWithVerified((_providerId, modelId) => {
@@ -29452,9 +29812,9 @@ describe('CodexAgent context window reporting', () => {
await handle.send({ type: 'user', content: 'go' });
handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-1' } } as never);
- pushUsage(handlers, 'turn-1', 1_000_000);
+ pushUsage(handlers, 'turn-1', null);
- // 收敛仍按目录 id 生效,而不是拿 wire 变体去查(那会查不到 → 保留 1M)。
+ // 缺失窗口时仍按目录 id 兜底,而不是拿 wire 变体去查(那会查不到 → 无法取得兜底)。
expect(handle.getUsageSnapshot().contextWindow).toBe(272_000);
expect(asked).toContain('gpt-5.4');
expect(asked).not.toContain('gpt-5.4-codex');
@@ -29485,7 +29845,7 @@ describe('CodexAgent context window reporting', () => {
await handle.send({ type: 'user', content: 'go' });
handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-1' } } as never);
- pushUsage(handlers, 'turn-1', 1_000_000);
+ pushUsage(handlers, 'turn-1', null);
expect(handle.getUsageSnapshot().contextWindow).toBe(372_000);
// 同一个 model id 换到另一条路由(真实上限不同)。
@@ -29494,7 +29854,7 @@ describe('CodexAgent context window reporting', () => {
await handle.send({ type: 'user', content: 'again' });
handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-2' } } as never);
- pushUsage(handlers, 'turn-2', 1_000_000);
+ pushUsage(handlers, 'turn-2', null);
expect(handle.getUsageSnapshot().contextWindow).toBe(900_000);
expect(seen).toContainEqual(['other', 'gpt-5.6-sol']);
@@ -29523,14 +29883,14 @@ describe('CodexAgent context window reporting', () => {
if (!handle.setModel) throw new Error('expected setModel support');
await handle.setModel(WIDE_MODEL);
- // 这条 usage 属于仍在产出的 372K turn,必须按 372K 收敛
- pushUsage(handlers, 'turn-1', 1_000_000);
+ // 这条 usage 属于仍在产出的 372K turn,缺失窗口时必须按该 turn 的 372K 兜底
+ pushUsage(handlers, 'turn-1', null);
expect(handle.getUsageSnapshot().contextWindow).toBe(372_000);
// 下一 turn 才轮到新模型:它的 1M 上限不再被旧模型压住
await handle.send({ type: 'user', content: 'again' });
handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-2' } } as never);
- pushUsage(handlers, 'turn-2', 1_000_000);
+ pushUsage(handlers, 'turn-2', null);
expect(handle.getUsageSnapshot().contextWindow).toBe(1_000_000);
await handle.close();
@@ -30799,7 +31159,7 @@ describe('CodexAgent custom provider context window override', () => {
);
expect(params.model).toBe('gpt-5.6-sol');
expect(params.config?.model_context_window).toBe(1_050_000);
- expect(params.config?.model_auto_compact_token_limit).toBe(997_500);
+ expect(params.config?.model_auto_compact_token_limit).toBe(945_000);
await handle.close();
});
@@ -31366,9 +31726,9 @@ describe('CodexAgent compaction storm escalation', () => {
describe('Codex native model context overrides', () => {
it.each([
{ storedLimit: 100_000, expectedWindow: 100_000, expectedCompact: 90_000 },
- { storedLimit: 500_000, expectedWindow: 200_000, expectedCompact: 180_000 },
- { storedLimit: null, expectedWindow: 200_000, expectedCompact: 190_000 },
- ])('uses the same custom-provider window for config and usage with limit $storedLimit', async ({
+ { storedLimit: 500_000, expectedWindow: 500_000, expectedCompact: 450_000 },
+ { storedLimit: null, expectedWindow: 200_000, expectedCompact: 180_000 },
+ ])('preserves native usable capacity independently of requested config with limit $storedLimit', async ({
storedLimit, expectedWindow, expectedCompact,
}) => {
let limit: number | null = storedLimit;
@@ -31377,7 +31737,7 @@ describe('Codex native model context overrides', () => {
provider === 'mygpt' && model === 'gpt-5.6-sol' ? 200_000 : null,
resolveModelContextLimit: (provider, model) =>
provider === 'mygpt' && model === 'gpt-5.6-sol' ? limit : null,
- // A catalog or app-server fallback must not replace the applied thread window.
+ // Catalog metadata must not replace the native usage report.
resolveVerifiedContextWindow: () => 1_050_000,
}));
let turnSeq = 0;
@@ -31398,23 +31758,23 @@ describe('Codex native model context overrides', () => {
expect(startParams.config).toMatchObject({
model_context_window: expectedWindow, model_auto_compact_token_limit: expectedCompact,
});
- const pushUsage = (turnId: string) => {
+ const pushUsage = (turnId: string, reportedWindow: number) => {
host.getThreadHandlers()!.tokenUsageUpdated?.({
threadId: handle.id, turnId,
tokenUsage: {
total: { totalTokens: 110, inputTokens: 100, cachedInputTokens: 0, outputTokens: 10 },
last: { totalTokens: 110, inputTokens: 100, cachedInputTokens: 0, outputTokens: 10 },
- modelContextWindow: 258_400,
+ modelContextWindow: reportedWindow,
},
} as never);
};
await handle.send({ type: 'user', content: 'hello' });
- pushUsage('custom-budget-1');
- expect(handle.getUsageSnapshot().contextWindow).toBe(expectedWindow);
+ pushUsage('custom-budget-1', 95_000);
+ expect(handle.getUsageSnapshot().contextWindow).toBe(95_000);
limit = null;
// Changing settings while a turn runs must not change that turn's usage window.
- pushUsage('custom-budget-1');
- expect(handle.getUsageSnapshot().contextWindow).toBe(expectedWindow);
+ pushUsage('custom-budget-1', 95_000);
+ expect(handle.getUsageSnapshot().contextWindow).toBe(95_000);
host.getThreadHandlers()!.turnCompleted?.({
threadId: handle.id, turn: { id: 'custom-budget-1', status: 'completed' },
});
@@ -31424,11 +31784,11 @@ describe('Codex native model context overrides', () => {
config: Record<string, unknown>;
};
expect(resumed.config).toMatchObject({
- model_context_window: 200_000, model_auto_compact_token_limit: 190_000,
+ model_context_window: 200_000, model_auto_compact_token_limit: 180_000,
});
}
- pushUsage('custom-budget-2');
- expect(handle.getUsageSnapshot().contextWindow).toBe(200_000);
+ pushUsage('custom-budget-2', 190_000);
+ expect(handle.getUsageSnapshot().contextWindow).toBe(190_000);
await handle.close();
});
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index daa1bdcc71..37ba700ce0 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -113,6 +113,7 @@ import {
} from '../shared/overload-error.js';
import { isRemoteCompactEncryptedContentError } from '../shared/remote-compact-encrypted-error.js';
import { buildCodexEnv } from './env-builder.js';
+import type { CodexErrorInfo } from './app-server/protocol.js';
import {
buildCodexBotSkillConfigOverrides,
buildCodexBotMcpConfigOverrides,
@@ -2718,6 +2719,7 @@ export class CodexAgent extends BaseAgent {
let codexBrowserUseStartupTimeoutMs: number | undefined;
let remoteCompactionProviderId: string | undefined;
let cindyRemoteCompactionProviderId: string | undefined;
+ let localCompactionProviderId: string | undefined;
let codexCustomProviderRoutes: CodexExtraSpawnConfig['codexCustomProviderRoutes'];
let buildSessionMcpConfig: CodexExtraSpawnConfig['buildSessionMcpConfig'];
let subagentModelFallback: string | undefined;
@@ -2751,6 +2753,7 @@ export class CodexAgent extends BaseAgent {
codexBrowserUseStartupTimeoutMs = undefined;
remoteCompactionProviderId = undefined;
cindyRemoteCompactionProviderId = undefined;
+ localCompactionProviderId = undefined;
codexCustomProviderRoutes = undefined;
buildSessionMcpConfig = undefined;
subagentModelFallback = undefined;
@@ -2820,6 +2823,7 @@ export class CodexAgent extends BaseAgent {
}
if (codexProxyActive && cfg.codexCindyRemoteCompactionProviderId) {
cindyRemoteCompactionProviderId = cfg.codexCindyRemoteCompactionProviderId;
+ localCompactionProviderId = cfg.codexLocalCompactionProviderId;
}
if (codexProxyActive && cfg.codexCustomProviderRoutes?.length) {
codexCustomProviderRoutes = cfg.codexCustomProviderRoutes;
@@ -2922,6 +2926,7 @@ export class CodexAgent extends BaseAgent {
codexBrowserUseStartupTimeoutMs,
remoteCompactionProviderId,
cindyRemoteCompactionProviderId,
+ localCompactionProviderId,
codexCustomProviderRoutes,
buildSessionMcpConfig,
subagentModelFallback,
@@ -3256,45 +3261,28 @@ export class CodexAgent extends BaseAgent {
* (provider, model) 解析, 只更新 model 会让下一 turn 拿新模型去问**旧路由**。
*/
let activeTurnProviderId: string | null | undefined = opts.providerId;
+ let lastNativeContextWindow: number | null = null;
+ let lastNativeContextWindowTurnId: string | null = null;
+ let hasActivatedRootTurn = false;
/**
- * 把 app-server 上报的 modelContextWindow 收敛到模型目录的真实上限。
- *
- * app-server 对网关路由的模型常报**基础模型**的窗口, 忽略该路由的实际限制 ——
- * 例如目录 372K 的 GPT-5.6-Sol 会被报成 1M。虚高值会让上下文占比被低估,
- * memory flush 阈值也跟着推迟。
- *
- * **已核实窗口存在时一律用它, 不与上报值取小** (2026-08-04 修正)。原先取
- * `min(verified, reported)` 隐含「上报值可信, 只是可能虚高」; 实测证伪了这个
- * 前提 —— 会话中途切模型后 codex 不刷新 modelContextWindow, 整个会话继续上报
- * **切换前**那个模型的窗口, 于是 min() 把我们已经算对的新模型窗口又拉回旧值,
- * 上下文占比与 memory flush 阈值全程按错的窗口走。取小本是为了防虚高, 而
- * verified 本身就是这条路由的核实上限, 直接用它不会虚高。
- *
- * 代价说清楚: 上游「路由真被降窗」而报出更小值的情形不再被采纳。这个场景与
- * 「上报值陈旧」在协议上无法区分 (两者都只是一个更小的数字), 二选一时优先信
- * 我们自己按 (provider, model) 核实过的那份 —— 它至少不会指向一个用户已经切走
- * 的模型。
- *
- * 两个约束都不是可省的细节:
- * - **按 turn 归属模型**, 不读 mutableModel: 见 activeTurnModel 注释。
- * - **取值交给 host 的 resolveVerifiedContextWindow**, 不自己查 availableModels:
- * 那张表是跨 provider 去重后的扁平结构, 同一 model id 由多个 provider 提供时
- * 归属已丢(订阅直连发现的 `gpt-5.6-sol` 与网关下发的同 id), 按 id 回查可能命中
- * 另一条路由的元数据 —— 用错路由的上限收敛比不收敛更糟。host 同时持有完整目录、
- * provider 维度与「这个窗口是显式声明还是派生兜底」的信息, 也天然读的是 live 目录
- * (模型发现 / 切账号 / 自定义 provider 增删改都即时反映), 见该 dep 的注释。
- *
- * 拿不到已核实窗口时(host 未注入、目录未覆盖、'gpt-5' 这类 server 默认哨兵、只有
- * 兜底值、或 provider 归属有歧义)沿用上报值 —— 即改动前行为。
+ * Native usage reports the effective usable window, including model limits and
+ * reserved headroom. Catalog windows and requested limits cannot replace it,
+ * even after a model switch. Only use turn-scoped configuration/catalog data
+ * as a fallback until native has reported a valid window. Missing fields in
+ * later events must not erase an already observed native capacity.
*/
- const capContextWindow = (reported: number | null): number | null => {
+ const resolveUsageContextWindow = (reported: number | null): number | null => {
+ if (reported !== null && Number.isFinite(reported) && reported > 0) {
+ lastNativeContextWindow = reported;
+ return reported;
+ }
+ if (lastNativeContextWindow !== null) return lastNativeContextWindow;
const configured = activeTurnContextLimit;
if (configured && Number.isFinite(configured) && configured > 0) return configured;
const verified = activeTurnModel
? (this.deps.resolveVerifiedContextWindow?.(activeTurnProviderId, activeTurnModel) ?? null)
: null;
- if (!verified || verified <= 0) return reported;
- return verified;
+ return verified !== null && Number.isFinite(verified) && verified > 0 ? verified : null;
};
let sdkSessionId: string | undefined;
@@ -3853,13 +3841,22 @@ export class CodexAgent extends BaseAgent {
* 按 id 记账后跨轮污染在结构上就不成立, 也不再需要"换 turn 才清零"这类时序守卫。
*/
const producedOutputTurnIds = new Set<string>();
+ // Capture whether normal model work preceded this compaction. The compaction
+ // item itself also counts as model work in the generic overload guard.
+ const compactingTurnIds = new Set<string>();
+ const completedSummaryRecoveryTurnIds = new Set<string>();
+ const normalModelWorkTurnIds = new Set<string>();
+ const noteRecoveryModelWork = (turnId: string, item?: unknown): void => {
+ if ((item as { type?: unknown } | undefined)?.type !== 'contextCompaction') normalModelWorkTurnIds.add(turnId);
+ };
+ const SUMMARY_RECOVERY = 'remote-compaction-summary';
/**
* 服务过载退避重投状态。`retry` 由 send() 每轮登记,闭包持有该 turn 的
* turnParams 与响应处理逻辑,因此重投投递的是同一条用户消息、同一套策略,
* 不会因为期间 mutable 配置变化而偷偷换参数。
*/
let overloadRetry: {
- retry: () => Promise<void>;
+ retry: (continueHistory?: boolean) => Promise<void>;
/**
* 同一 logical send 已消耗的外层重放次数,所有 provider failure policy 共享。
* policy 切换不重置:否则 capacity 4 次 + terminal-rate-limit 2 次会把同一条
@@ -3867,13 +3864,13 @@ export class CodexAgent extends BaseAgent {
* maxAttempts 是它愿意接受的**总重放上限**,不是独立配额。
*/
attempt: number;
- /** 同一逻辑 send 最多接管一次 WS→HTTP body recovery,避免坏响应形成重投环。 */
- httpRecoveryRetryAttempted: boolean;
+ /** One automatic recovery per logical send; a failed fallback cannot loop. */
+ automaticRecoveryAttempted: boolean;
/**
* `error` notification 只登记恢复意图;权威的 turn/completed 到达后才真正重投。
* 单一事实源放在 logical send 状态上,不再分散到各个 turn/start 请求条目。
*/
- pendingHttpRecovery: { deadTurnId: string; reason: string } | null;
+ pendingAutomaticRecovery: { deadTurnId: string; reason: string } | null;
timer: ReturnType<typeof setTimeout> | null;
/**
* 重投的 turn/start RPC 是否在途。计时器到点后 `timer` 已清空、新 turn 又
@@ -5513,8 +5510,10 @@ export class CodexAgent extends BaseAgent {
const unsubscribeDetachedThread = async (
detachedThreadId: string,
reason: string,
+ retireHostOnFailure = true,
): Promise<boolean> => runThreadCleanupOrRetire({
cleanupThreadId: detachedThreadId,
+ retireHostOnFailure,
reason,
cleanup: () => host.unsubscribeThread(detachedThreadId),
});
@@ -5560,16 +5559,15 @@ export class CodexAgent extends BaseAgent {
const limit = this.deps.resolveModelContextLimit?.(mutableProviderId, mutableCatalogModel ?? mutableModel);
return typeof limit === 'number' && Number.isSafeInteger(limit) && limit > 0 ? limit : null;
};
- // The stored setting is a cap on the provider's explicit window. Keep the raw
- // setting for refresh detection (including reset), but use one effective
- // window for both native thread configuration and turn-owned usage reporting.
+ // The user override takes precedence over the provider default. Keep the raw
+ // setting for refresh detection (including reset). This requested window is
+ // only a usage fallback until native reports its actual usable capacity.
const effectiveThreadContextWindow = (contextLimit: number | null): number | null => {
const customWindow = typeof initialCustomContextWindow === 'number'
&& Number.isFinite(initialCustomContextWindow) && initialCustomContextWindow >= 1
? Math.floor(initialCustomContextWindow)
: null;
- return contextLimit === null ? customWindow
- : customWindow === null ? contextLimit : Math.min(contextLimit, customWindow);
+ return contextLimit ?? customWindow;
};
let appliedContextLimit = currentContextLimit();
activeTurnContextLimit = effectiveThreadContextWindow(appliedContextLimit);
@@ -5604,15 +5602,14 @@ export class CodexAgent extends BaseAgent {
...(!makerMemoryEnabled && !opts.botRuntimeProfile
? { 'mcp_servers.cindy_memory.enabled': false }
: {}),
- // Write the resolved window once: a custom-provider default must not
- // overwrite the user's cap. Preserve 95% for an explicit provider window
- // without an override, and 90% for a user-configured cap.
+ // Configure the native window and its 90% compaction budget together.
+ // Native effective_context_window_percent independently reserves input headroom.
...(typeof threadContextWindow === 'number' && threadContextWindow > 0
? {
model_context_window: Math.floor(threadContextWindow),
model_auto_compact_token_limit: Math.max(
1,
- Math.floor(threadContextWindow * (contextLimit === null ? 0.95 : 0.9)),
+ Math.floor(threadContextWindow * 0.9),
),
}
: {}),
@@ -5808,7 +5805,7 @@ export class CodexAgent extends BaseAgent {
: {}),
};
}
- const threadModelProvider = opts.remoteHostId
+ let threadModelProvider = opts.remoteHostId
? undefined
: customProviderModelProvider
? customProviderModelProvider
@@ -5818,6 +5815,25 @@ export class CodexAgent extends BaseAgent {
? host.getRemoteCompactionProviderId?.() ?? undefined
: undefined;
+ const isLikelyValidThreadId = (id: string | undefined): id is string =>
+ typeof id === 'string' && id.length > 0 && !id.startsWith('<') && /^[0-9a-fA-F-]+$/.test(id);
+ const localSummaryProvider = opts.remoteHostId ? null : host.getLocalCompactionProviderId?.();
+ if (localSummaryProvider && opts.resumeSessionId && isLikelyValidThreadId(opts.resumeSessionId)) {
+ // Native modelProvider is durable thread metadata. Read it before overriding
+ // resume defaults so recovery survives closing/reopening this same task.
+ try {
+ const saved = await host.request<{ thread: { modelProvider?: string } }>(
+ 'thread/read', { threadId: opts.resumeSessionId, includeTurns: false },
+ { timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS },
+ );
+ if (saved.thread.modelProvider === localSummaryProvider) threadModelProvider = localSummaryProvider;
+ } catch (error) {
+ // Let the existing resume path recover an unused thread without a rollout.
+ // Other read failures must not silently reset a saved summary identity.
+ if (!isExactNoRolloutThreadResumeError(error, opts.resumeSessionId)) throw error;
+ }
+ }
+
/**
* 本 thread 的 Responses 请求是否走 WebSocket。
*
@@ -5828,7 +5844,8 @@ export class CodexAgent extends BaseAgent {
* 单独起名是为了把「选没选 provider」和「实际走不走 WS」分开,避免 prompt 注入
* 通道错误地只看 provider 身份。
*/
- const threadUsesWebSocket = !customProviderThreadPolicy.dynamicIdentity
+ let threadUsesWebSocket = threadModelProvider !== localSummaryProvider
+ && !customProviderThreadPolicy.dynamicIdentity
&& !cindyProviderRemoteCompaction
&& !!threadModelProvider
&& (host.getOpenAiWebSocketsEnabled?.() ?? true);
@@ -5886,8 +5903,6 @@ export class CodexAgent extends BaseAgent {
// 防御: resumeSessionId 偶尔会是上次失败 session 残留的占位 ('<failed>' / '<pending>')
// 或非 UUID 格式 — server 直接 -32600 invalid thread id, 整个 session 起不来。
// 看到不像 UUID 就走新 thread/start, 不让 ghost id 阻塞用户。
- const isLikelyValidThreadId = (id: string | undefined): id is string =>
- typeof id === 'string' && id.length > 0 && !id.startsWith('<') && /^[0-9a-fA-F-]+$/.test(id);
if (opts.resumeSessionId && !isLikelyValidThreadId(opts.resumeSessionId)) {
log.warn('resumeSessionId looks invalid, falling back to thread/start', {
resumeSessionId: opts.resumeSessionId,
@@ -6232,12 +6247,13 @@ export class CodexAgent extends BaseAgent {
});
/**
- * A thread that has not accepted a turn has no rollout and cannot be
- * resumed. Recreate that unused thread with the current profile instead,
- * then move the live subscription and thread-scoped registrations.
+ * Apply configuration in a fresh native runtime, then move the existing Cindy
+ * task's subscription and registrations. Unused threads have no rollout;
+ * automatic summary recovery instead forks the intact persisted history.
*/
- const replaceUnusedThreadWithCurrentProfile = async (
+ const replaceThreadWithCurrentProfile = async (
signal?: AbortSignal,
+ retainHistory = false,
): Promise<void> => {
const previousThreadId = threadId;
const replacementProfileFingerprint = currentWorkspacePermissionProfileFingerprint();
@@ -6249,9 +6265,11 @@ export class CodexAgent extends BaseAgent {
const resp = await requestProfileLifecycle<ThreadStartResponse>({
action: 'replacement',
signal,
- request: () => host.request<ThreadStartResponse>(Method.ThreadStart, {
+ request: () => host.request<ThreadStartResponse>(retainHistory ? Method.ThreadFork : Method.ThreadStart, {
+ ...(retainHistory ? { threadId: previousThreadId, excludeTurns: true } : {}),
cwd: opts.workingDir,
- ...currentThreadWorkspaceConfig(),
+ // Recovery belongs to the running send, whose catalog/window is already frozen.
+ ...currentThreadWorkspaceConfig(retainHistory ? appliedContextLimit : undefined),
...(sessionDynamicTools.length > 0 ? { dynamicTools: sessionDynamicTools } : {}),
...(threadModelProvider ? { modelProvider: threadModelProvider } : {}),
...(mutableModel && mutableModel !== 'gpt-5' ? { model: mutableModel } : {}),
@@ -6263,7 +6281,7 @@ export class CodexAgent extends BaseAgent {
if (lateThreadId === previousThreadId) return;
const cleaned = await unsubscribeDetachedThread(
lateThreadId,
- 'late unused profile replacement cleanup',
+ 'late profile replacement cleanup', !retainHistory,
);
if (!cleaned) return;
log.debug('discarded late unused profile replacement', {
@@ -6277,7 +6295,7 @@ export class CodexAgent extends BaseAgent {
if (closed) {
await unsubscribeDetachedThread(
nextThreadId,
- 'unused profile replacement cleanup after close',
+ 'profile replacement cleanup after close', !retainHistory,
);
throw new Error('Codex session closed during workspace permission profile replacement');
}
@@ -6287,10 +6305,14 @@ export class CodexAgent extends BaseAgent {
) {
mutableServiceTier = normalizeServiceTier(resp.serviceTier) ?? null;
}
+ if (retainHistory && resp.modelProvider !== localSummaryProvider) {
+ await unsubscribeDetachedThread(nextThreadId, 'summary fallback identity mismatch', false);
+ throw new Error('Codex did not apply the summary compaction provider');
+ }
codexThreadModelProviderId = resp.modelProvider?.trim() || undefined;
if (nextThreadId !== previousThreadId) {
const released = await releaseCurrentThreadSubscription(
- 'unused profile replacement release',
+ retainHistory ? 'summary fallback release' : 'unused profile replacement release', { retireHostOnFailure: !retainHistory },
);
if (!released) {
throw staleHostError('workspace permission profile replacement cleanup');
@@ -6299,12 +6321,20 @@ export class CodexAgent extends BaseAgent {
if (closed) {
await unsubscribeDetachedThread(
nextThreadId,
- 'unused profile replacement cleanup after concurrent close',
+ 'profile replacement cleanup after concurrent close', !retainHistory,
);
throw new Error('Codex session closed during workspace permission profile replacement');
}
threadId = nextThreadId;
sdkSessionId = nextThreadId;
+ if (retainHistory) {
+ // A native fork replays the inherited cumulative usage snapshot.
+ // Carry its accepted cursor before subscribing to buffered frames.
+ const cursor = acceptedUsageTotalByThread.get(previousThreadId);
+ if (cursor) acceptedUsageTotalByThread.set(nextThreadId, {
+ generation: cursor.generation, total: { ...cursor.total },
+ });
+ }
subscription = host.subscribeThread(threadId, handlers);
registerRootCodexMcpContext();
refreshCodexAutoReviewerRoute(threadId);
@@ -6330,8 +6360,8 @@ export class CodexAgent extends BaseAgent {
workspacePermissionProfileFingerprint = workspacePermissionProfileActive
? replacementProfileFingerprint
: null;
- threadMayHaveRollout = false;
- log.debug('unused thread replaced with workspace permission profile', {
+ threadMayHaveRollout = retainHistory;
+ log.debug('thread replaced with workspace permission profile', {
previousThreadId,
threadId,
referenceRoots: mutableExtraDirs.length,
@@ -6364,7 +6394,7 @@ export class CodexAgent extends BaseAgent {
workspacePermissionProfileFingerprint === targetFingerprint
) return;
if (!threadMayHaveRollout) {
- await replaceUnusedThreadWithCurrentProfile(signal);
+ await replaceThreadWithCurrentProfile(signal);
continue;
}
const resumeThreadWorkspaceConfig = currentThreadWorkspaceConfig();
@@ -6390,7 +6420,7 @@ export class CodexAgent extends BaseAgent {
if (!isExactNoRolloutThreadResumeError(e, threadId)) throw e;
if (signal?.aborted) throw new Error('Codex send cancelled before acceptance');
threadMayHaveRollout = false;
- await replaceUnusedThreadWithCurrentProfile(signal);
+ await replaceThreadWithCurrentProfile(signal);
continue;
}
assertCurrentHost('workspace permission profile refresh');
@@ -6424,7 +6454,7 @@ export class CodexAgent extends BaseAgent {
return (async () => {
if (signal?.aborted || closed) throw new Error('Codex context settings update cancelled');
if (!threadMayHaveRollout) {
- await replaceUnusedThreadWithCurrentProfile(signal);
+ await replaceThreadWithCurrentProfile(signal);
} else {
const released = await releaseCurrentThreadSubscription('context settings refresh', { retireHostOnFailure: false });
if (!released) throw new Error('Codex context settings update could not release the thread');
@@ -6465,6 +6495,9 @@ export class CodexAgent extends BaseAgent {
}
}
appliedContextLimit = desired;
+ hasActivatedRootTurn = false;
+ lastNativeContextWindow = null;
+ usageTracker.setContextWindow(0);
})();
};
@@ -7206,6 +7239,16 @@ export class CodexAgent extends BaseAgent {
isTurnInFlight = true;
bindYieldContinuationTurn(turnId);
if (!isNewTurn) return;
+ if (!hasActivatedRootTurn) {
+ // Resume replays the previous run's usage window before this run starts.
+ // Its history usage is useful, but its old capacity cannot override the
+ // configuration accepted by the fresh native runtime.
+ hasActivatedRootTurn = true;
+ if (lastNativeContextWindowTurnId !== turnId) {
+ lastNativeContextWindow = null;
+ usageTracker.setContextWindow(0);
+ }
+ }
resetCodexGenerationTiming(translatorRt);
turnDiffSnapshots.clear();
@@ -7476,6 +7519,7 @@ export class CodexAgent extends BaseAgent {
}
if (
event.type === 'thinking' ||
+ event.type === 'compact_boundary' ||
event.type === 'tool_use' ||
event.type === 'tool_result' ||
event.type === 'tool_result_full' ||
@@ -9265,7 +9309,7 @@ export class CodexAgent extends BaseAgent {
};
const armHttpRecoveryForError = (
- error: { message?: string; additionalDetails?: unknown } | null | undefined,
+ error: { message?: string; additionalDetails?: unknown; codexErrorInfo?: CodexErrorInfo | null } | null | undefined,
): string | null => {
if (opts.remoteHostId || !this.deps.armCodexHttpRecovery) return null;
const message = typeof error?.message === 'string' ? error.message : '';
@@ -9293,16 +9337,18 @@ export class CodexAgent extends BaseAgent {
};
/**
- * 已确认是 HTTP proxy 可恢复的 WS 请求校验错误时,立即重投同一份冻结 turnParams。
- * host 已把 thread 标成 HTTP-only;重投新建 transport 时会收到 426 并走既有
- * recoveryRules。只接管本 logical send、零产出、无其它 start 在飞的明确 turn。
+ * Continue one logical send after its authoritative failed terminal. HTTP body
+ * recovery may replay only zero-output turns. Summary recovery preserves the
+ * native history and uses empty input after model/tool output, avoiding replay.
*/
- const retryTurnViaHttpRecovery = (deadTurnId: string, reason: string): boolean => {
+ const retryTurnAfterAutomaticRecovery = (deadTurnId: string, reason: string): boolean => {
const state = overloadRetry;
- if (!state || closed || state.httpRecoveryRetryAttempted || state.isCancelled()) return false;
+ if (!state || closed || state.automaticRecoveryAttempted || state.isCancelled()) return false;
const origin = turnOriginByTurnId.get(deadTurnId);
if (origin?.sendGen !== state.sendGen) return false;
- if (producedOutputTurnIds.has(deadTurnId)) {
+ const summaryRecovery = reason === SUMMARY_RECOVERY;
+ const continueHistory = summaryRecovery && normalModelWorkTurnIds.has(deadTurnId);
+ if (!summaryRecovery && producedOutputTurnIds.has(deadTurnId)) {
log.info('codex WS body recovery error after partial output — not auto-retrying', {
threadId,
deadTurnId,
@@ -9325,7 +9371,7 @@ export class CodexAgent extends BaseAgent {
return false;
}
- state.httpRecoveryRetryAttempted = true;
+ state.automaticRecoveryAttempted = true;
terminalErroredTurnIds.add(deadTurnId);
dismissPendingUserInputForTurn(deadTurnId, 'turn_failed');
clearActiveToolContextsForTurn(deadTurnId);
@@ -9338,13 +9384,39 @@ export class CodexAgent extends BaseAgent {
) {
pendingTightenInterrupt = true;
}
- log.info('codex WS body recovery error — retrying turn through HTTP fallback', {
+ log.info('codex automatic recovery — continuing the current task', {
threadId,
deadTurnId,
reason,
});
- void state.retry().catch((retryError) => {
+ state.inFlight = true;
+ void (async () => {
+ if (summaryRecovery) {
+ const previousProvider = threadModelProvider;
+ const previousWebSocket = threadUsesWebSocket;
+ const previousThread = threadId;
+ threadModelProvider = localSummaryProvider!;
+ threadUsesWebSocket = false;
+ // unsubscribe retains a loaded Codex 0.153 thread for 30 minutes;
+ // resume would ignore provider overrides. Native fork preserves its
+ // full history in a fresh runtime while Cindy keeps this business task.
+ try {
+ await replaceThreadWithCurrentProfile(undefined, true);
+ } catch (error) {
+ if (threadId === previousThread) {
+ threadModelProvider = previousProvider;
+ threadUsesWebSocket = previousWebSocket;
+ }
+ throw error;
+ }
+ if (closed || overloadRetry !== state || state.isCancelled()) {
+ if (overloadRetry === state) settleCancelledOverloadRetry(state, 'cancelled during summary recovery');
+ return;
+ }
+ }
+ await state.retry(continueHistory);
+ })().catch((retryError) => {
if (closed || overloadRetry !== state || state.isCancelled()) {
log.info('codex HTTP recovery retry rejected after cancellation — not surfacing', {
threadId,
@@ -9353,7 +9425,7 @@ export class CodexAgent extends BaseAgent {
});
return;
}
- log.error('codex HTTP recovery turn/start retry failed', {
+ log.error('codex automatic recovery failed', {
threadId,
reason,
error: retryError instanceof Error ? retryError.message : String(retryError),
@@ -9365,7 +9437,7 @@ export class CodexAgent extends BaseAgent {
eventQueue.push({
type: 'error',
data: {
- message: `turn/start HTTP recovery retry failed: ${String(retryError)}`,
+ message: `Codex automatic recovery failed: ${String(retryError)}`,
isTerminal: true,
},
source: 'codex',
@@ -9386,25 +9458,61 @@ export class CodexAgent extends BaseAgent {
* turn/completed 驱动。这样无论 error / completed / turn-start response
* 如何乱序,都只有一个执行入口。
*/
- const recordHttpRecoveryIntent = (
+ const canRecoverRemoteCompaction = (deadTurnId: string, error: { message?: string; additionalDetails?: unknown; codexErrorInfo?: CodexErrorInfo | null } | null | undefined): boolean => {
+ if (!localSummaryProvider || !threadModelProvider || !hostUsesCodexProxy || threadModelProvider === localSummaryProvider) return false;
+ if (threadModelProvider !== host.getCindyRemoteCompactionProviderId?.()
+ && threadModelProvider !== host.getRemoteCompactionProviderId?.()) return false;
+ if (!compactingTurnIds.has(deadTurnId)) return false;
+ // In-memory exec continuations cannot be moved to another native thread.
+ if (activeYieldContinuationClaim() || cellsForCompletedTurn(deadTurnId).length > 0) return false;
+ const text = `${error?.message ?? ''}\n${typeof error?.additionalDetails === 'string' ? error.additionalDetails : ''}`;
+ const signals = extractNonSecretErrorSignals(text);
+ // A compact endpoint can exhaust its own retries while ordinary generation works.
+ // Try the same model/account summary once; explicit exhausted quota stays terminal.
+ const compactRateLimit = isTerminalRateLimitRetryExhaustion(text, signals.errorStatus, error?.codexErrorInfo);
+ const tag = codexErrorInfoTag(error?.codexErrorInfo);
+ if (tag === 'usageLimitExceeded' || tag === 'sessionBudgetExceeded' || tag === 'unauthorized') return false;
+ // A terminal turn alone does not prove an upstream compact request failed:
+ // transport loss/timeouts can leave its result unknown. Accept explicit
+ // endpoint rejection/failure responses (including the observed 502/503),
+ // plus the existing exhausted-429 case; never infer success from exclusions.
+ const info = error?.codexErrorInfo;
+ // The shared redaction helper deliberately extracts only auth/rate-limit
+ // statuses. Parse Codex's explicit HTTP failure wording locally as well.
+ const statusMatch = /\b(?:HTTP(?:\/\d(?:\.\d)?)?(?:\s+status)?|(?:unexpected|last)\s+status(?:\s+code)?)\s*:?\s*(\d{3})\b/i.exec(text);
+ const textStatus = statusMatch ? Number(statusMatch[1]) : signals.errorStatus;
+ const httpStatus = info && typeof info === 'object' && 'httpConnectionFailed' in info
+ ? info.httpConnectionFailed.httpStatusCode ?? textStatus
+ : textStatus;
+ const rejectedRequest = [400, 404, 405, 422, 500, 501, 502, 503].includes(httpStatus ?? 0);
+ const uncertainTransport = tag === 'responseStreamDisconnected' || tag === 'responseStreamConnectionFailed'
+ || /timeout|timed out|ECONNRESET|ECONNREFUSED|ENOTFOUND|connection reset|network error|stream disconnected/i.test(text);
+ return !uncertainTransport
+ && !isAuthRelatedErrorMessage(text)
+ && ((rejectedRequest && !signals.usageLimit) || compactRateLimit)
+ && !isRemoteCompactEncryptedContentError(text);
+ };
+
+ const recordAutomaticRecoveryIntent = (
deadTurnId: string,
- error: { message?: string; additionalDetails?: unknown } | null | undefined,
+ error: { message?: string; additionalDetails?: unknown; codexErrorInfo?: CodexErrorInfo | null } | null | undefined,
): boolean => {
const state = overloadRetry;
+ const summaryRecovery = canRecoverRemoteCompaction(deadTurnId, error);
if (
!deadTurnId
|| !state
|| closed
- || state.httpRecoveryRetryAttempted
+ || state.automaticRecoveryAttempted
|| state.isCancelled()
|| state.timer !== null
|| state.deferredCapacityFailure !== null
- || producedOutputTurnIds.has(deadTurnId)
+ || (!summaryRecovery && producedOutputTurnIds.has(deadTurnId))
) {
return false;
}
- if (state.pendingHttpRecovery) {
- return state.pendingHttpRecovery.deadTurnId === deadTurnId;
+ if (state.pendingAutomaticRecovery) {
+ return state.pendingAutomaticRecovery.deadTurnId === deadTurnId;
}
const origin = turnOriginByTurnId.get(deadTurnId);
@@ -9424,9 +9532,9 @@ export class CodexAgent extends BaseAgent {
return false;
}
- const reason = armHttpRecoveryForError(error);
+ const reason = summaryRecovery ? SUMMARY_RECOVERY : armHttpRecoveryForError(error);
if (!reason) return false;
- state.pendingHttpRecovery = {
+ state.pendingAutomaticRecovery = {
deadTurnId,
reason,
};
@@ -9525,18 +9633,18 @@ export class CodexAgent extends BaseAgent {
if (reconnectStallTurnId === turn.id) clearReconnectStall();
let recoveryState = overloadRetry;
let pendingRecovery =
- recoveryState?.pendingHttpRecovery?.deadTurnId === turn.id
- ? recoveryState.pendingHttpRecovery
+ recoveryState?.pendingAutomaticRecovery?.deadTurnId === turn.id
+ ? recoveryState.pendingAutomaticRecovery
: null;
if (
turn.status === 'failed'
&& (!terminalErroredTurnIds.has(turn.id) || pendingRecovery)
) {
- if (!pendingRecovery && turn.error && recordHttpRecoveryIntent(turn.id, turn.error)) {
+ if (!pendingRecovery && turn.error && recordAutomaticRecoveryIntent(turn.id, turn.error)) {
recoveryState = overloadRetry;
pendingRecovery =
- recoveryState?.pendingHttpRecovery?.deadTurnId === turn.id
- ? recoveryState.pendingHttpRecovery
+ recoveryState?.pendingAutomaticRecovery?.deadTurnId === turn.id
+ ? recoveryState.pendingAutomaticRecovery
: null;
}
if (recoveryState && pendingRecovery) {
@@ -9561,8 +9669,12 @@ export class CodexAgent extends BaseAgent {
}
}
- recoveryState.pendingHttpRecovery = null;
- if (retryTurnViaHttpRecovery(turn.id, pendingRecovery.reason)) return;
+ recoveryState.pendingAutomaticRecovery = null;
+ if (retryTurnAfterAutomaticRecovery(turn.id, pendingRecovery.reason)) {
+ // Settle old-turn accounting behind its tombstone without ending the logical send.
+ handleTurnCompleted(params);
+ return;
+ }
// 已登记但归属后来未能坐实时,恢复原终态处理;不能吞掉失败让 UI 悬空。
terminalErroredTurnIds.delete(turn.id);
log.warn('codex HTTP recovery intent could not be executed; surfacing turn failure', {
@@ -9572,10 +9684,10 @@ export class CodexAgent extends BaseAgent {
});
}
}
- if (pendingRecovery && recoveryState?.pendingHttpRecovery?.deadTurnId === turn.id) {
+ if (pendingRecovery && recoveryState?.pendingAutomaticRecovery?.deadTurnId === turn.id) {
// 极端协议形状:先报可恢复 terminal error,最终 turn 却不是 failed。
// 以权威 completed 为准,取消本次恢复意图并正常收口。
- recoveryState.pendingHttpRecovery = null;
+ recoveryState.pendingAutomaticRecovery = null;
terminalErroredTurnIds.delete(turn.id);
}
// turn/start RPC 响应未回时就收到终态 → 记墓碑, 阻止稍后到达的
@@ -9590,6 +9702,9 @@ export class CodexAgent extends BaseAgent {
// 同一个墓碑也负责拦截该 turn 随后迟到的 item / reasoning / started 事件。
if (completedTurnIds.has(turn.id)) return;
completedTurnIds.add(turn.id);
+ compactingTurnIds.delete(turn.id);
+ normalModelWorkTurnIds.delete(turn.id);
+ completedSummaryRecoveryTurnIds.delete(turn.id);
// A controlled MCP request may already be waiting for a steer ACK. The
// completed tombstone is authoritative, so release it immediately to
// decline instead of waiting for the local ACK timeout.
@@ -10077,6 +10192,7 @@ export class CodexAgent extends BaseAgent {
// 有产出, 对用户报硬失败 —— 而那一轮其实什么副作用都没发生(review #844 codex P1)。
if (bufferedModelWorkTurnIds.has(turnId)) {
producedOutputTurnIds.add(turnId);
+ noteRecoveryModelWork(turnId);
log.info('codex adopted turn had buffered events — treating as produced output', {
turnId,
threadId,
@@ -10132,7 +10248,7 @@ export class CodexAgent extends BaseAgent {
* - `inFlight`:计时器已到点、重投 RPC 在途、新 turn 尚未激活;
* - `deferredCapacityFailure !== null`:失败已记账、等在途 turn/start settle 后
* 补排(那一刻既没有计时器也没有 inFlight)。
- * - `pendingHttpRecovery !== null`:WS body 错误已登记、等权威 turn/completed。
+ * - `pendingAutomaticRecovery !== null`:WS body 错误已登记、等权威 turn/completed。
*
* 抽成单一判据是因为它同时决定三件事: 会话忙不忙(isTurnRunning)、取消要不要收口
* (signal abort)、权限收紧要不要作用到重投。前几轮每处各写一份, 第三种状态加进来
@@ -10146,7 +10262,7 @@ export class CodexAgent extends BaseAgent {
state.timer != null
|| state.inFlight
|| state.deferredCapacityFailure !== null
- || state.pendingHttpRecovery !== null
+ || state.pendingAutomaticRecovery !== null
);
/**
@@ -10361,7 +10477,13 @@ export class CodexAgent extends BaseAgent {
// null, 即这个 turn 的 turnStarted 还没到, 它的 item / reasoning 不可能被记到自己
// 名下(全被 stale 闸或缓冲挡住)。缓冲事件那种"看不见的产出"由
// adoptUnidentifiedDeadTurn 在响应回来、id 已知时补记, 补排再查一次就拦住了。
- if (deadTurnId && producedOutputTurnIds.has(deadTurnId)) {
+ // A successful fallback summary is internal progress, not completed user work.
+ // If its following generation hits a transient 429 before producing anything,
+ // reuse the bounded retry policy and continue the compacted native history.
+ const continueSummaryHistory = policy.kind === 'terminal-rate-limit'
+ && deadTurnId !== null && completedSummaryRecoveryTurnIds.has(deadTurnId)
+ && !normalModelWorkTurnIds.has(deadTurnId);
+ if (deadTurnId && producedOutputTurnIds.has(deadTurnId) && !continueSummaryHistory) {
log.info('codex replayable error after partial output — not auto-retrying', {
kind: policy.kind,
threadId,
@@ -10477,7 +10599,7 @@ export class CodexAgent extends BaseAgent {
state.timer = setTimeout(() => {
state.timer = null;
if (closed || overloadRetry !== state) return;
- void state.retry().catch((error) => {
+ void state.retry(continueSummaryHistory).catch((error) => {
// 取消之后 RPC 才 reject:Stop / close / 新 send 都已经各自收口过这一轮
// (abort 与新 send 会把 overloadRetry 置 null,close 会置 closed)。
// 此时再报一次 terminal error + Done 会让 UI 二次收口,并把用户主动停止
@@ -10913,7 +11035,11 @@ export class CodexAgent extends BaseAgent {
tokenUsageUpdated: (params) => {
if (enqueueIfBufferedTurn(params.turnId, () => handlers.tokenUsageUpdated?.(params))) return;
if (shouldIgnoreStaleTurnEvent(params.turnId)) return;
- lastModelContextWindow = capContextWindow(params.tokenUsage?.modelContextWindow ?? null);
+ const reportedWindow = params.tokenUsage?.modelContextWindow;
+ if (typeof reportedWindow === 'number' && Number.isFinite(reportedWindow) && reportedWindow > 0) {
+ lastNativeContextWindowTurnId = params.turnId || null;
+ }
+ lastModelContextWindow = resolveUsageContextWindow(reportedWindow ?? null);
usageTracker.setContextWindow(lastModelContextWindow ?? 0);
const last = params.tokenUsage?.last;
if (!last) return;
@@ -11068,6 +11194,9 @@ export class CodexAgent extends BaseAgent {
discardPendingSpawnLineageIds(reservedChildThreadIds);
return;
}
+ if (params.item.type === 'contextCompaction' && !compactingTurnIds.has(params.turnId)) {
+ compactingTurnIds.add(params.turnId);
+ }
if (interceptProposedPlanItem(params.turnId, params.item)) {
discardPendingSpawnLineageIds(reservedChildThreadIds);
return;
@@ -11151,7 +11280,10 @@ export class CodexAgent extends BaseAgent {
}
// 模型已开始产出 → 本 turn 不再适合被过载重投整体重放。SDK echo 类 item
// (userMessage 等)不算产出, 见 itemRepresentsModelWork。
- if (itemRepresentsModelWork(params.item)) producedOutputTurnIds.add(params.turnId);
+ if (itemRepresentsModelWork(params.item)) {
+ producedOutputTurnIds.add(params.turnId);
+ noteRecoveryModelWork(params.turnId, params.item);
+ }
noteActiveToolContext(params.item, params.turnId);
noteToolItemLifecycle(params.item, 'started');
// 先登记再翻译:子线程通知可能紧随 spawn item 到达,映射就位才不丢首帧。
@@ -11193,6 +11325,7 @@ export class CodexAgent extends BaseAgent {
noteObservedModelItem(params.turnId, params.item);
clearApprovalPolicyDenialOnProgress(params.turnId, params.item.id);
producedOutputTurnIds.add(params.turnId);
+ noteRecoveryModelWork(params.turnId, params.item);
}
noteActiveToolContext(params.item, params.turnId);
rememberYieldedExecCells(params.turnId, params.item, 'updated');
@@ -11253,10 +11386,17 @@ export class CodexAgent extends BaseAgent {
return;
}
if (collabTerminalKey) handledCollabTerminalItemIds.add(collabTerminalKey);
+ if (params.item.type === 'contextCompaction') {
+ compactingTurnIds.delete(params.turnId);
+ if (threadModelProvider === localSummaryProvider && overloadRetry?.automaticRecoveryAttempted) {
+ completedSummaryRecoveryTurnIds.add(params.turnId);
+ }
+ }
if (itemRepresentsModelWork(params.item)) {
noteObservedModelItem(params.turnId, params.item);
clearApprovalPolicyDenialOnProgress(params.turnId, params.item.id);
producedOutputTurnIds.add(params.turnId);
+ noteRecoveryModelWork(params.turnId, params.item);
}
noteAssistantReplyCandidate(params.turnId, params.item);
completeActiveToolContext(params.item, params.turnId);
@@ -11330,6 +11470,7 @@ export class CodexAgent extends BaseAgent {
if (shouldIgnoreStaleTurnEvent(params.turnId)) return;
clearApprovalPolicyDenialOnProgress(params.turnId, params.itemId);
producedOutputTurnIds.add(params.turnId);
+ noteRecoveryModelWork(params.turnId);
translateAgentMessageDelta(params, eventQueue, { rt: translatorRt, log });
},
turnPlanUpdated: (params) => {
@@ -11345,6 +11486,7 @@ export class CodexAgent extends BaseAgent {
// thinking 流也算产出:模型已经在这一轮里工作了,整体重放不再等价。
clearApprovalPolicyDenialOnProgress(params.turnId, params.itemId);
producedOutputTurnIds.add(params.turnId);
+ noteRecoveryModelWork(params.turnId);
translateReasoningSummaryTextDelta(params, eventQueue, { rt: translatorRt, log });
},
reasoningSummaryPartAdded: (params) => {
@@ -11353,6 +11495,7 @@ export class CodexAgent extends BaseAgent {
if (shouldIgnoreStaleTurnEvent(params.turnId)) return;
clearApprovalPolicyDenialOnProgress(params.turnId, params.itemId);
producedOutputTurnIds.add(params.turnId);
+ noteRecoveryModelWork(params.turnId);
translateReasoningSummaryPartAdded(params, eventQueue, { rt: translatorRt, log });
},
reasoningTextDelta: (params) => {
@@ -11361,6 +11504,7 @@ export class CodexAgent extends BaseAgent {
if (shouldIgnoreStaleTurnEvent(params.turnId)) return;
clearApprovalPolicyDenialOnProgress(params.turnId, params.itemId);
producedOutputTurnIds.add(params.turnId);
+ noteRecoveryModelWork(params.turnId);
translateReasoningTextDelta(params, eventQueue, { rt: translatorRt, log });
},
accountRateLimitsUpdated: (params) =>
@@ -11625,7 +11769,7 @@ export class CodexAgent extends BaseAgent {
const recoveryTurnId = effectiveParams.turnId || currentTurnId || '';
// error notification 只登记恢复意图并保持 logical turn 运行;
// 权威 turn/completed 才负责收口旧 turn 与发起一次 HTTP 重投。
- if (recordHttpRecoveryIntent(recoveryTurnId, effectiveParams.error)) return;
+ if (recordAutomaticRecoveryIntent(recoveryTurnId, effectiveParams.error)) return;
}
// 服务过载(模型容量不足)时接管重投:translator 命中 capacity 才回调,
// 拿到进度就把错误透成非终止状态,本函数随后跳过 Done 收口。
@@ -12013,10 +12157,10 @@ export class CodexAgent extends BaseAgent {
const handleTurnStartResp = (resp: TurnStartResponse, ownerSeq: number): void => {
if (resp.turn?.id) {
const startEntry = inFlightStarts.get(ownerSeq);
- const pendingHttpRecovery = overloadRetry?.pendingHttpRecovery;
+ const pendingAutomaticRecovery = overloadRetry?.pendingAutomaticRecovery;
if (
startEntry
- && pendingHttpRecovery?.deadTurnId === resp.turn.id
+ && pendingAutomaticRecovery?.deadTurnId === resp.turn.id
&& startEntry.sendGen === overloadRetry?.sendGen
) {
// completed 已经把该 turn 记为终态,下面不会重新激活;这里仅补权威
@@ -12187,10 +12331,11 @@ export class CodexAgent extends BaseAgent {
// turn-start status 抽样、planMode 武装态消耗都是"用户发了一条消息"的
// 一次性副作用,重投是同一条消息的再次投递,重跑那些会让用量统计与
// 计划模式状态错乱。
+ let continueNativeHistory = false;
overloadRetry = {
attempt: 0,
- httpRecoveryRetryAttempted: false,
- pendingHttpRecovery: null,
+ automaticRecoveryAttempted: false,
+ pendingAutomaticRecovery: null,
timer: null,
inFlight: false,
isCancelled: () => sendOpts?.signal?.aborted === true,
@@ -12199,7 +12344,8 @@ export class CodexAgent extends BaseAgent {
sendGen: mySendGen,
deferredCapacityFailure: null,
disposeSignalWatch: null,
- retry: async () => {
+ retry: async (continueHistory = false) => {
+ continueNativeHistory ||= continueHistory;
const state = overloadRetry;
// 发出前复检:本轮 send 的取消信号在退避等待期间才 abort(coordinator
// 撤单、上层超时)时不走 handle.abort(),计时器到点仍会把一条已被取消
@@ -12229,7 +12375,8 @@ export class CodexAgent extends BaseAgent {
// 必须带超时:AppServerHost.request 默认不超时,daemon / 远端传输
// 卡住时这个 RPC 会永久在飞,而 inFlight 被算作忙 → 会话永久卡死
// 且无人可解(review #844 codex P1)。与正常 turn/start 同款边界。
- const resp = await host.request<TurnStartResponse>(Method.TurnStart, turnParams, {
+ const resp = await host.request<TurnStartResponse>(Method.TurnStart,
+ { ...turnParams, threadId, ...(continueNativeHistory ? { input: [] } : {}) }, {
timeoutMs: CRITICAL_THREAD_RPC_TIMEOUT_MS,
});
// **发出后再复检**:RPC 在途期间 Stop / close / 撤单都拦不住它——
@@ -12272,7 +12419,7 @@ export class CodexAgent extends BaseAgent {
} finally {
state.inFlight = false;
if (!rpcSettledOk && overloadRetry === state) {
- state.pendingHttpRecovery = null;
+ state.pendingAutomaticRecovery = null;
}
// 注销本次请求(isTurnStartPending 由登记表重算, 不会误清别的请求的状态)。
endTurnStart(retryStartSeq);
@@ -12307,7 +12454,7 @@ export class CodexAgent extends BaseAgent {
// 判据用 attempt > 0 限定在"本轮确实被重投接管过"上: 没发生过重投的
// 普通 send 里 signal 仍只是**受理前**的取消边界, 语义不变。
const retryOwnsActiveTurn =
- (armedRetryState.attempt > 0 || armedRetryState.httpRecoveryRetryAttempted)
+ (armedRetryState.attempt > 0 || armedRetryState.automaticRecoveryAttempted)
&& (currentTurnId !== null || isTurnInFlight);
if (!overloadRetryPending(armedRetryState) && !retryOwnsActiveTurn) return;
cancelOverloadRetry('send signal aborted');
@@ -12462,7 +12609,7 @@ export class CodexAgent extends BaseAgent {
!initialStartSettledOk
&& overloadRetry?.sendGen === mySendGen
) {
- overloadRetry.pendingHttpRecovery = null;
+ overloadRetry.pendingAutomaticRecovery = null;
}
// 先注销本次请求(isTurnStartPending 由登记表重算) —— 无条件置 false 会在两个
// start 并存时清掉属于**另一个**请求的状态(review #844 codex P1)。注销必须早于
@@ -12867,6 +13014,30 @@ export class CodexAgent extends BaseAgent {
return consumedEventStream();
},
+ getCodexContextWindowInfo: async () => {
+ if (opts.remoteHostId || !this.deps.resolveCodexContextWindowInfo) return null;
+ const model = activeTurnModel ?? mutableModel;
+ const reportedWindow = lastNativeContextWindow;
+ const contextLimit = activeTurnContextLimit;
+ const compactRatio = 0.9;
+ try {
+ const response = await host.request<{ config?: Record<string, unknown> }>(
+ Method.ConfigRead, { includeLayers: false, cwd: opts.workingDir }, { timeoutMs: 5_000 },
+ );
+ if (!response.config) return null;
+ const config = { ...response.config };
+ if (contextLimit !== null) {
+ config.model_context_window = contextLimit;
+ config.model_auto_compact_token_limit = Math.floor(
+ contextLimit * compactRatio,
+ );
+ }
+ return await this.deps.resolveCodexContextWindowInfo(
+ model, config, reportedWindow,
+ );
+ } catch { return null; }
+ },
+
getUsageSnapshot(): UsageSnapshot {
return liveUsageSnapshot();
},
diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts
index bc52f5a463..71574bf240 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -1386,6 +1386,10 @@ export class Session {
}
}
+ async getCodexContextWindowInfo() {
+ return this.handle.getCodexContextWindowInfo?.() ?? null;
+ }
+
getUsageSnapshot(): UsageSnapshot {
return this.handle.getUsageSnapshot();
}
diff --git a/packages/model-providers/src/__tests__/modelProtocol.test.ts b/packages/model-providers/src/__tests__/modelProtocol.test.ts
index 815c0db91f..dde4e52e7b 100644
--- a/packages/model-providers/src/__tests__/modelProtocol.test.ts
+++ b/packages/model-providers/src/__tests__/modelProtocol.test.ts
@@ -55,6 +55,22 @@ describe('per-model protocol comparison', () => {
expect(pickRecommendedAgent(provider, model.id, ['claude-code', 'codex'])).toBe('claude-code');
});
+ it.each(['openai-chat', 'openai-responses'] as const)(
+ 'marks Chat Completions via %s as compatibility without misreporting the native CLI transport',
+ (wireProtocol) => {
+ const { provider, byAgent } = fixture('openai-completions');
+ provider.routing.codex!.wireProtocol = wireProtocol;
+ expect(modelProtocolComparison(provider, byAgent).forAgent('codex')).toMatchObject({
+ harness: 'openai-responses',
+ outbound: wireProtocol === 'openai-chat' ? 'openai-completions' : 'openai-responses',
+ localConversion: wireProtocol === 'openai-chat',
+ mode: 'compatibility',
+ });
+ expect(resolveAgentCapability([{ ...provider, connected: true }], 'xd', model.id, 'codex')?.protocolMode)
+ .toBe('compatibility');
+ },
+ );
+
it('does not infer a native Google route or recommendation from a Gemini name', () => {
const { provider, byAgent } = fixture('openai-responses');
for (const entry of Object.values(byAgent)) entry.id = 'google/gemini-future';