Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(codex): 优先使用原生压缩并保留切模历史
Dasha44334f8d8f0
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexContextSwitch.native.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexContextSwitch.native.test.tsnew file mode 100644index 0000000000..c487550e75--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/codexContextSwitch.native.test.ts@@ -0,0 +1,110 @@+/** Integration: real Codex, isolated home and scripted loopback provider; no credentials.+ * Regression: a global target budget hid the previous model's larger window.+ * CINDY_CODEX_TEST_BINARY=<absolute path> vitest run <this file>+ */+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { createServer } from 'node:http';+import type { AddressInfo } from 'node:net';+import { expect, it } from 'vitest';+import { CodexAgent } from '../../../../../../packages/maker-core/src/agents/codex/index';+import type { Logger } from '../../../../../../packages/maker-core/src/interfaces/logger';+import { nativeCodexFallbackModel, prepareCodexCustomContextCatalog } from '../codex-custom-context-catalog';++const binary = process.env.CINDY_CODEX_TEST_BINARY;+const logger: Logger = { trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child: () => logger };++it.skipIf(!binary)('cold-resumes the same history, compacts with the larger model, then sends to the smaller model', async () => {+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-context-switch-native-'));+ const home = path.join(root, 'home');+ const work = path.join(root, 'work');+ const windows: Record<string, number> = { 'fixture-wide': 500_000, 'fixture-small': 272_000 };+ const requests: Array<{ model: string; input: unknown[] }> = [];+ const server = createServer(async (req, res) => {+ if (req.method !== 'POST') { res.end('{"models":[]}'); return; }+ let raw = ''; for await (const chunk of req) raw += chunk;+ const body = JSON.parse(raw);+ requests.push(body);+ const text = requests.length === 1 ? 'FIRST_REPLY' : requests.length === 2 ? 'NATIVE_SUMMARY' : 'CONTINUED';+ const inputTokens = requests.length === 1 ? 300_000 : 20;+ const item = { type: 'message', role: 'assistant', id: `msg-${requests.length}`,+ content: [{ type: 'output_text', text, annotations: [] }] };+ res.writeHead(200, { 'content-type': 'text/event-stream' });+ for (const event of [+ { type: 'response.created', response: { id: `r-${requests.length}` } },+ { type: 'response.output_item.done', output_index: 0, item },+ { type: 'response.completed', response: { id: `r-${requests.length}`, status: 'completed', output: [item],+ usage: { input_tokens: inputTokens, output_tokens: 1, total_tokens: inputTokens + 1 } } },+ ]) res.write(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`);+ res.end();+ });+ let agent: CodexAgent | undefined;+ try {+ await fs.mkdir(home); await fs.mkdir(work);+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));+ await fs.writeFile(path.join(home, 'models_cache.json'), JSON.stringify({ models: Object.keys(windows)+ .map(slug => nativeCodexFallbackModel(slug, 'You are a test assistant.')) }));+ await fs.writeFile(path.join(home, 'config.toml'), [+ 'model_provider="fixture"', 'cli_auth_credentials_store="ephemeral"',+ 'check_for_update_on_startup=false', '[analytics]', 'enabled=false',+ '[model_providers.fixture]', 'name="Fixture"',+ `base_url="http://127.0.0.1:${(server.address() as AddressInfo).port}"`,+ 'wire_api="responses"', 'requires_openai_auth=false', 'request_max_retries=0', 'stream_max_retries=0',+ '[mcp_servers.cindy_memory]', 'url="http://127.0.0.1:1/mcp"', 'enabled=false',+ ].join('\n'));+ const makeAgent = () => new CodexAgent({+ binaryPath: binary!, logger, runtimeConfig: {}, resolveCodexLocalAuthPolicy: () => 'isolated',+ resolveCodexThreadContextWindow: (_provider, model) => windows[model] ?? null,+ prepareCodexExtraSpawnConfig: async (_providers, ctx) => {+ expect(ctx.customContextProviderId).toBe('cprov-fixture');+ const catalog = await prepareCodexCustomContextCatalog({ binaryPath: binary!, codexHome: home,+ modelId: ctx.customContextModel!, contextWindow: ctx.customContextWindow!,+ resolveContextWindow: model => windows[model] ?? null });+ return { extraArgs: catalog.extraArgs, extraEnv: {}, codexProxyActive: true };+ },+ auth: {+ getState: async () => ({ authenticated: true }), triggerLogin: async () => ({ authenticated: true }),+ logout: async () => {}, getAuthEnv: async () => ({+ HOME: root, USERPROFILE: root, APPDATA: root, LOCALAPPDATA: root, CODEX_HOME: home, TMPDIR: root,+ OPENAI_API_KEY: '', CODEX_API_KEY: '', HTTP_PROXY: 'http://127.0.0.1:1',+ HTTPS_PROXY: 'http://127.0.0.1:1', ALL_PROXY: 'http://127.0.0.1:1', NO_PROXY: '127.0.0.1,localhost',+ }),+ },+ });+ agent = makeAgent();+ const options = { sessionId: 'context-switch', providerId: 'cprov-fixture', workingDir: work, makerMemoryEnabled: false };+ let handle = await agent.startSession({ ...options, model: 'fixture-wide' });+ const send = async (text: string) => {+ const finished = (async () => {+ for await (const event of handle.events()) {+ if (event.type === 'error') throw new Error(JSON.stringify(event));+ if (event.type === 'done') return;+ }+ throw new Error('Native turn ended without completion');+ })();+ await handle.send({ type: 'user', content: text }, { throwOnStartFailure: true });+ await finished;+ };+ await send('ORIGINAL_HISTORY_MARKER');+ const threadId = handle.id;+ expect(requests).toHaveLength(1);+ expect(handle.getUsageSnapshot().contextWindow).toBe(475_000);+ await handle.close(); await agent.dispose();+ agent = makeAgent();+ handle = await agent.startSession({ ...options, model: 'fixture-small', resumeSessionId: threadId });+ expect(handle.id).toBe(threadId);+ await send('CONTINUE_MARKER');+ expect(requests.map(request => request.model)).toEqual(['fixture-wide', 'fixture-wide', 'fixture-small']);+ expect(JSON.stringify(requests[1]!.input)).toContain('ORIGINAL_HISTORY_MARKER');+ expect(JSON.stringify(requests[1]!.input)).toContain('FIRST_REPLY');+ expect(JSON.stringify(requests[2]!.input)).toContain('NATIVE_SUMMARY');+ expect(JSON.stringify(requests[2]!.input)).toContain('CONTINUE_MARKER');+ expect(handle.getUsageSnapshot().contextWindow).toBe(258_400);+ await handle.close();+ } finally {+ await agent?.dispose();+ await new Promise<void>(resolve => { server.closeAllConnections(); server.close(() => resolve()); });+ await fs.rm(root, { recursive: true, force: true });+ }+}, 30_000);diff --git a/apps/desktop/src/main/maker-host/__tests__/codexCustomContextCatalog.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexCustomContextCatalog.test.tsindex 245e375819..6d84b6f1ae 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexCustomContextCatalog.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexCustomContextCatalog.test.ts@@ -80,7 +80,7 @@ describe('Codex custom context model catalog', () => {).resolves.toEqual(catalog);});- it('keeps context_window at 272K and only raises the selected model maximum', async () => {+ it('sets the selected model budget in its descriptor without changing its sibling', async () => {const otherModel = {slug: 'gpt-5.4-mini',context_window: 128_000,@@ -112,8 +112,9 @@ describe('Codex custom context model catalog', () => {expect(written.models[0]).toMatchObject({slug: 'gpt-5.6-sol',- context_window: 272_000,+ context_window: 700_000,max_context_window: 700_000,+ auto_compact_token_limit: 630_000,base_instructions: 'preserve the full descriptor',});expect(written.models[1]).toEqual(otherModel);@@ -159,7 +160,9 @@ describe('Codex custom context model catalog', () => {expect(written.models).toContainEqual(smartModel);expect(written.models).toContainEqual({...bundledRoot,+ context_window: 1_050_000,max_context_window: 1_050_000,+ auto_compact_token_limit: 945_000,});});@@ -185,7 +188,8 @@ describe('Codex custom context model catalog', () => {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, slug: 'codex/gpt-6-astra', context_window: 1_000_000,+ max_context_window: 1_000_000, auto_compact_token_limit: 900_000 });expect(catalog.models).toContainEqual(native);});@@ -196,7 +200,8 @@ describe('Codex custom context model catalog', () => {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 });+ expect(catalog.models[1]).toEqual({ ...nativeCodexFallbackModel('glm-5.3', instructions),+ context_window: 500_000, max_context_window: 500_000, auto_compact_token_limit: 450_000 });});it('keeps user-owned catalog instructions untouched', async () => {@@ -207,7 +212,8 @@ describe('Codex custom context model catalog', () => {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 });+ expect(catalog.models[0]).toEqual({ ...native, context_window: 500_000,+ max_context_window: 500_000, auto_compact_token_limit: 450_000 });});it('keeps wire aliases independent and preserves native instructions and tools', () => {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.tsindex e7d2a36895..9764545be7 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@@ -352,6 +352,8 @@ export async function prepareCodexCustomContextCatalog(params: {modelId: string;contextWindow: number;scanChunkBytes?: number;+ /** Same-provider budgets for native previous-model compaction after cold resume. */+ resolveContextWindow?: (modelId: string) => number | null;/** In-memory smart Subagent catalog to preserve in the one-session custom-context Host. */baseCatalog?: unknown;}): Promise<{ catalogPath: string; extraArgs: string[] }> {@@ -365,6 +367,17 @@ export async function prepareCodexCustomContextCatalog(params: {params.modelId,params.contextWindow,);+ // A global model_context_window override also applies to the previous model+ // reconstructed by Codex. Keep budgets per descriptor so native can see the+ // old > new relationship and compact with the old model before downshifting.+ patched.models = patched.models.map((model) => {+ const window = model.slug === params.modelId+ ? params.contextWindow : params.resolveContextWindow?.(model.slug);+ if (typeof window !== 'number' || !Number.isSafeInteger(window) || window <= 0) return model;+ return { ...model, context_window: window,+ max_context_window: Math.max(Number(model.max_context_window) || 0, window),+ auto_compact_token_limit: Math.max(1, Math.floor(window * 0.9)) };+ });const content = `${JSON.stringify(patched)}\n`;const catalogPath = await persistCatalog(params.codexHome, content);return {diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex 57aac4bd49..3b94473df2 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -2088,6 +2088,12 @@ export function getMaker(): Maker {codexHome: effectiveCodexHome,modelId,contextWindow,+ resolveContextWindow: (nativeModelId) => {+ const catalog = getDesktopSelectableCatalog();+ const source = resolveDesktopModelContextProviderId(catalog, 'codex', ctx.customContextProviderId, nativeModelId);+ return (source ? readModelContextLimit('codex', source, nativeModelId) : null)+ ?? resolveModelDefaultContextWindow(catalog, 'codex', source, nativeModelId);+ },...(smartSubagentConfig? { baseCatalog: smartSubagentConfig.modelCatalog }: {}),diff --git a/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.tsindex 0379891cec..1d5d8787c7 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts@@ -372,7 +372,7 @@ describe('createContextOverflowRollover', () => {};}- it.each(['cc', 'codex', 'pi'])('checkpoints a pressured %s companion before send, retaining outcomes without replay', async (agentKind) => {+ it.each(['cc', 'pi'])('checkpoints a pressured %s companion before send, retaining outcomes without replay', async (agentKind) => {const deps = makeDeps([msg('user', 'Keep the game keyboard accessible', 'u1'),{ ...msg('tool_use', { toolName: 'Write', input: { file_path: '/game/index.html' } }, 't1'), toolUseId: 'write-1' },@@ -758,7 +758,7 @@ describe('createContextOverflowRollover', () => {expect(deps.setPendingHandoff).toHaveBeenCalledOnce();});- it.each(['cc', 'codex', 'pi'] as const)(+ it.each(['cc', 'pi'] as const)('rebuilds %s native context before a pressured 500K → 272K model switch',async (agentKind) => {const deps = makeDeps([@@ -1903,7 +1903,7 @@ describe('createContextOverflowRollover', () => {expect(deps.replayUserMessage).not.toHaveBeenCalled();});- it('uses the same full-window pressure guard for Claude Code and Codex before send', async () => {+ it('lets Codex handle full-window pressure natively while keeping the Claude guard', async () => {for (const agentKind of ['cc', 'codex'] as const) {const deps = makeDeps([msg('user', '继续', 'u1'), msg('assistant', '好', 'a1')]);deps.getSessionRow.mockResolvedValue({@@ -1919,14 +1919,30 @@ describe('createContextOverflowRollover', () => {});const rollover = createContextOverflowRollover(deps);- await expect(rollover.prepareUnhealthySession(`session-${agentKind}`)).resolves.toBe(true);- expect(deps.commitRebuild).toHaveBeenCalled();+ await expect(rollover.prepareUnhealthySession(`session-${agentKind}`)).resolves.toBe(agentKind === 'cc');+ expect(deps.commitRebuild).toHaveBeenCalledTimes(agentKind === 'cc' ? 1 : 0);deps.commitRebuild.mockClear();}});+ // Unit: the direct/Orca switch path must not bypass the native-first gate.+ // Both persisted and live usage can exceed the target without any native error.+ it.each([false, true])('preserves Codex history through shrink and send preflight (companion=%s)', async (companion) => {+ const deps = makeDeps([msg('user', 'Continue the task', 'u1'), msg('assistant', 'Progress', 'a1')]);+ deps.getSessionRow.mockResolvedValue({ ...await deps.getSessionRow(), agentKind: 'codex',+ ...(companion ? { source: 'bot', botRole: 'canonical' } : {}),+ contextTokens: 480_000, contextWindow: 500_000 });+ const rollover = createContextOverflowRollover(deps);+ await expect(rollover.prepareModelWindowSwitch('s1', { contextWindow: 272_000 })).resolves.toBe('not-needed');+ await expect(rollover.prepareUnhealthySession('s1')).resolves.toBe(false);+ expect(deps.closeSession).not.toHaveBeenCalled();+ expect(deps.commitRebuild).not.toHaveBeenCalled();+ expect(deps.setPendingHandoff).not.toHaveBeenCalled();+ });+it('fails closed when a pre-send rebuild cannot commit', async () => {- const deps = makeDeps([msg('user', '继续', 'u1'), msg('assistant', '好', 'a1')]);+ const deps = makeDeps([msg('user', '继续', 'u1'),+ msg('error', { reason: 'context-overflow', message: 'Context window exceeded' }, 'e1')]);deps.getSessionRow.mockResolvedValue({status: 'active',source: 'desktop',diff --git a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.tsindex 89ca6fc9ac..58d1bdf04e 100644--- a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts+++ b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts@@ -975,6 +975,9 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)if (!sessionRow || sessionRow.status === 'deleted' || !sessionRow.sdkSessionId) {return 'not-needed';}+ // Native Codex can compact with the previous model before the smaller turn.+ // This direct entry also serves automatic/Orca switches outside the UI gate.+ if (sessionRow.agentKind === 'codex') return 'not-needed';const persistedContextTokens =typeof sessionRow.contextTokens === 'number' &&Number.isFinite(sessionRow.contextTokens) &&@@ -1156,13 +1159,13 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)sessionRow.agentKind,);const window = effectiveContextWindow(sessionRow.model, reportedWindow, verified);- // At a send boundary, checkpoint a pressured companion before the next turn- // enters native compaction. Native compaction remains enabled within a turn.+ // Codex owns native pressure compaction, including companions. Other harnesses+ // retain their send-boundary companion checkpoints and full-window guard.// 账本新鲜(复盘已覆盖最近完成轮)时线提前到 70%;不新鲜维持 90%,免得换窗丢掉还没进// 账本的内容。只有落在 70%–90% 之间才去读账本;提前换窗必须拿到渲染好的账本段并原样// 带进交接——同一个快照只读一次,免得判新鲜之后第二次读取失败,交接反而没带账本。let earlyWorkingMemory: string | undefined;- const pressure = botChat+ const pressure = sessionRow.agentKind === 'codex' ? false : botChat? shouldRebuildForContextPressure(usedTokens, window * BOT_CONTEXT_CHECKPOINT_RATIO) ||(shouldRebuildForContextPressure(usedTokens, window * BOT_CONTEXT_CHECKPOINT_RATIO_FRESH) &&(await isWorkingMemoryFresh(sessionId)) &&diff --git a/apps/desktop/src/renderer/__tests__/orcaModelWindowSelection.test.ts b/apps/desktop/src/renderer/__tests__/orcaModelWindowSelection.test.tsindex e7e4d1ff1a..b79f3e4685 100644--- a/apps/desktop/src/renderer/__tests__/orcaModelWindowSelection.test.ts+++ b/apps/desktop/src/renderer/__tests__/orcaModelWindowSelection.test.ts@@ -61,7 +61,7 @@ function setup(options: { agent?: string; role?: string; used?: number; current?}describe('Orca same-Agent window preflight', () => {- it.each(['claude-code', 'codex', 'pi'])('%s overflow must be confirmed before staging for either role', async agent => {+ it.each(['claude-code', 'pi'])('%s overflow must be confirmed before staging for either role', async agent => {for (const role of ['lead', 'worker']) {const h = setup({ agent, role });expect(await h.pick(agent, 'small', 'provider')).toBe(false);@@ -80,8 +80,8 @@ describe('Orca same-Agent window preflight', () => {});it.each([100000, 150000, 180000])('allows existing local warning semantics at %i tokens', async used => {- const h = setup({ used });- expect(await h.pick('codex', 'small', 'provider')).toBe(true);+ const h = setup({ used, agent: 'claude-code' });+ expect(await h.pick('claude-code', 'small', 'provider')).toBe(true);expect(h.confirmDialog).not.toHaveBeenCalled();expect(h.bindings.toast.warning).toHaveBeenCalledTimes(used >= 140000 ? 1 : 0);});@@ -99,15 +99,15 @@ describe('Orca same-Agent window preflight', () => {});it('checks a same-id model on a different provider, using the runtime Agent even with a cross-Agent preview', async () => {- const h = setup({ displayedAgent: 'pi' });- expect(await h.pick('codex', 'old-model', 'small-provider')).toBe(false);+ const h = setup({ agent: 'claude-code', displayedAgent: 'pi' });+ expect(await h.pick('claude-code', 'old-model', 'small-provider')).toBe(false);expect(h.bindings.resolveProviderModelContextWindow).toHaveBeenCalledWith({- providers: [], providerId: 'small-provider', modelId: 'old-model', agentKind: 'codex',+ providers: [], providerId: 'small-provider', modelId: 'old-model', agentKind: 'claude-code',});expect(h.switchSessionAgent).not.toHaveBeenCalled();});- it.each(['claude-code', 'codex', 'pi'])('blocks a pressured device-link %s selection before staging', async agent => {+ it.each(['claude-code', 'pi'])('blocks a pressured device-link %s selection before staging', async agent => {for (const used of [180000, 240000]) {const h = setup({ remote: true, agent, used });expect(await h.pick(agent, 'small', 'provider')).toBe(false);@@ -117,6 +117,16 @@ describe('Orca same-Agent window preflight', () => {}});+ it.each([false, true])('lets Codex stage a pressured switch without a handoff confirmation (remote=%s)', async remote => {+ for (const role of ['lead', 'worker']) {+ const h = setup({ remote, role });+ expect(await h.pick('codex', 'small', 'provider')).toBe(true);+ expect(h.confirmDialog).not.toHaveBeenCalled();+ expect(h.bindings.toast.error).not.toHaveBeenCalled();+ expect(h.switchSessionAgent).toHaveBeenCalledWith('s1', 'codex', 'small', 'provider', 'high', false);+ }+ });+it('retains legacy Pi protection and does not guard a true cross-Agent handoff', async () => {const h = setup({ remote: true, agent: 'pi', hostGuard: false, used: 10000 });expect(await h.pick('pi', 'small', 'provider')).toBe(false);@@ -137,9 +147,9 @@ describe('Orca same-Agent window preflight', () => {});it('does not register a choice if the user leaves the session during confirmation', async () => {- const h = setup();+ const h = setup({ agent: 'claude-code' });h.confirmDialog.mockImplementation(async () => { h.bindings.currentSessionIdRef.current = 's2'; return true; });- expect(await h.pick('codex', 'small', 'provider')).toBe(false);+ expect(await h.pick('claude-code', 'small', 'provider')).toBe(false);expect(h.switchSessionAgent).not.toHaveBeenCalled();expect(h.release).toHaveBeenCalledOnce();});@@ -151,17 +161,17 @@ describe('Orca same-Agent window preflight', () => {});it('rechecks a pending route when selected again, while axis-only edits skip the dialog', async () => {- const h = setup();- h.bindings.makerChatStore.getAgentSwitchIntent = () => ({ target: 'codex', model: 'old-model', providerId: 'old-provider' }) as never;+ const h = setup({ agent: 'claude-code' });+ h.bindings.makerChatStore.getAgentSwitchIntent = () => ({ target: 'claude-code', model: 'old-model', providerId: 'old-provider' }) as never;// The callback holds the same store object; a send rejected for a changed// window must be recoverable by selecting the pending model again.- expect(await h.pick('codex', 'old-model', 'old-provider')).toBe(false);+ expect(await h.pick('claude-code', 'old-model', 'old-provider')).toBe(false);h.confirmDialog.mockResolvedValue(true);- expect(await h.pick('codex', 'old-model', 'old-provider')).toBe(true);- expect(h.switchSessionAgent).toHaveBeenLastCalledWith('s1', 'codex', 'old-model', 'old-provider', 'high', false,+ expect(await h.pick('claude-code', 'old-model', 'old-provider')).toBe(true);+ expect(h.switchSessionAgent).toHaveBeenLastCalledWith('s1', 'claude-code', 'old-model', 'old-provider', 'high', false,{ confirmedContextWindow: 200000 });h.confirmDialog.mockClear();- expect(await h.pick('codex', 'old-model', 'old-provider', { effort: 'high', axesOnly: true })).toBe(true);+ expect(await h.pick('claude-code', 'old-model', 'old-provider', { effort: 'high', axesOnly: true })).toBe(true);expect(h.confirmDialog).not.toHaveBeenCalled();});});diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex 8507bd5c29..eb66bf7287 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -6688,7 +6688,7 @@ export function ChatInput({* 分级语义见 shared/modelSwitchAssessment.ts。overflow 确认后由 host 交接换窗,* 不要再建议用户先 /compact —— 小窗口模型压整段历史同样会失败。* 返回 false = 用户取消, 调用方直接放弃本次切换(无任何副作用)。- * fail-open: 占用未知(0)/ 目标窗口未知时不拦;三个 harness 的强制换窗线统一为 90%。+ * Codex 同引擎切模交原生压缩;其它引擎占用未知/窗口未知时不拦,强制换窗线为 90%。*/const confirmModelSwitchContextGuard = useCallback(async (@@ -6728,6 +6728,9 @@ export function ChatInput({return true;}const targetAgentKind = stagingSameAgentSelection ? runtimeAgentKind : currentModelAgentKind;+ // Same-harness Codex preserves native history and owns downshift compaction.+ // Keep authoritative recovery confirmations and cross-harness handoffs intact.+ if (runtimeAgentKind === 'codex' && targetAgentKind === 'codex' && !requireDestructiveConfirmation) return true;const targetRouteProviderId =targetProviderId !== undefined && targetAgentKind? effectiveSourceIdForModel(diff --git a/apps/desktop/src/shared/__tests__/runtimeModelSwitchGate.test.ts b/apps/desktop/src/shared/__tests__/runtimeModelSwitchGate.test.tsindex 2a1669a21a..32ec192d4b 100644--- a/apps/desktop/src/shared/__tests__/runtimeModelSwitchGate.test.ts+++ b/apps/desktop/src/shared/__tests__/runtimeModelSwitchGate.test.ts@@ -23,6 +23,12 @@ const base = {};describe('assessRuntimeModelSwitchGate', () => {+ // Codex can compact with the previous model before sampling the smaller one.+ // Rebuilding here would discard the native history before it gets that chance.+ it.each([false, true])('leaves Codex shrink compaction to native (remote=%s)', (isRemote) => {+ expect(assessRuntimeModelSwitchGate({ ...base, agentKind: 'codex', isRemote,+ verifiedTargetWindow: twoHundredK })).toEqual({ skipRebuild: true, defer: false });+ });it.each([{name: 'same route idle → hot apply, no rebuild',@@ -184,7 +190,7 @@ describe('assessRuntimeModelSwitchGate', () => {want: { skipRebuild: false, defer: true },},{- name: 'Codex shrink danger running → defer',+ name: 'Codex shrink danger running → native switch without destructive rebuild',input: {...base,agentKind: 'codex',@@ -192,7 +198,7 @@ describe('assessRuntimeModelSwitchGate', () => {verifiedTargetWindow: twoHundredK,contextTokens: 190_000,},- want: { skipRebuild: false, defer: true },+ want: { skipRebuild: true, defer: false },},{name: 'remote running same-route effort-only → still defer',diff --git a/apps/desktop/src/shared/runtimeModelSwitchGate.ts b/apps/desktop/src/shared/runtimeModelSwitchGate.tsindex e02c7b651d..d86bf54cce 100644--- a/apps/desktop/src/shared/runtimeModelSwitchGate.ts+++ b/apps/desktop/src/shared/runtimeModelSwitchGate.ts@@ -3,7 +3,7 @@** 统一选择器把 Harness 与模型叠在一次点选上之后,同引擎切模会打到这条路。* 预检是护栏不是闸门:缺核实窗口或占用未知时放行热切,禁止拿「不确定」挡住用户。- * 只有「核实过的缩窗 + 必须交接」才走重建;跑着无法重建时延期到回合结束,不丢选择。+ * Codex 保留历史并交原生压缩。其它引擎只有「核实缩窗 + 必须交接」才走重建。*/import { composeAtomicModelSelection } from '@cindy/model-providers';@@ -44,6 +44,7 @@ function isPositiveWindow(value: number | null | undefined): value is number {* 矩阵(与单测逐行对应):* - 路由没变 → 热切、不换窗* - 远端 + 回合中 → 延期(不能 live 改远端 turn)+ * - Codex → 跳过交接,由原生处理缩窗(执行句柄仍可按需重载)* - Pi + 回合中 + 路由变了 → 延期(Pi 要在空闲时核实窗口)* - 目标/当前窗口未核实或占用未知 → 热切、不换窗(fail-open)* - 核实缩窗且 danger/overflow:@@ -58,6 +59,9 @@ export function assessRuntimeModelSwitchGate(if (input.isRemote && input.inTurn) {return { skipRebuild: true, defer: true };}+ // Codex owns downshift compaction, including using the previous model. Preserve+ // its rollout; a host/catalog reload is independent of destructive handoff.+ if (input.agentKind === 'codex') return { skipRebuild: true, defer: false };if (input.agentKind === 'pi' && input.inTurn && input.runtimeRouteChanged) {return { skipRebuild: true, defer: true };}diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.mdindex 72f49287f0..48728a8099 100644--- a/docs/dev-rules/maker-core-and-agent-behavior.md+++ b/docs/dev-rules/maker-core-and-agent-behavior.md@@ -98,7 +98,7 @@ Pi 读取独立的设置页百分比,在每次启动或恢复任务时冻结`Agent.continue()` 语义压缩续接。Cindy 只消费 Pi 的 `compaction_start`/`compaction_end` 事件做UI、usage 与 digest 投影,不再向 Pi 注入 host 自动 compact RPC。-本机占用 ≥ 100%,或 host/bridge 自动 compact 已确定性失败(空摘要、compact 路径上的+Claude Code/Pi 本机占用 ≥ 100%,或 host/bridge 自动 compact 已确定性失败(空摘要、compact 路径上的invalid-request 400)时,走`host-controlled rollover + model-controlled bounded retrieval`:host 关闭旧原生窗口、写交接并在下一次发送前 fresh bootstrap,不再继续 compact。Pi 原生 threshold/overflow compact 出现同类@@ -109,7 +109,7 @@ upstream idle watchdog 打断静默 `/compact` 时只清 fired,不得在本次该锁存只活在当前 livecontroller/进程内;重启后没有 live handle 时不凭估算换窗。Orca 空闲 live 直发必须先走与`sendToSessionInternal` 相同的 `prepareUnhealthySession`,不能把消息打进应被关闭的旧窗口。切到更小窗口模型的 `danger`/`overflow`-预检仍按 `assessModelSwitchContext`,与同模型 compact 解耦。不要关闭 Claude Code SDK 或 Pi 原生+预检在 Claude Code/Pi 仍按 `assessModelSwitchContext`,与同模型 compact 解耦。不要关闭 Claude Code SDK 或 Pi 原生自动压缩。远端 Pi 同样依赖原生 auto-compaction;远端没有本地换窗,确定性失败不得伪装成已交接。明确 `context-overflow` 且本轮没有助手输出或工具副作用时,host 才会对失败的 user 消息做一次 wire-only replay;有副作用或分类不确定时必须@@ -129,7 +129,7 @@ Cindy 保底压缩是**一套**交接重建流程。装得进当前约束就不带调用关联的文本结果摘要,省略图片数据;伙伴主对话及显式重启也保留这些结果,其他交接沿用原规则。可剥图不足一半的混合大尾巴有意不救。打开会话不触发;只在终态错误或下次发送时由 main 侧 claim。SSH 不承诺。不确定 fail closed。救援摘要不得依赖额外模型调用。-伙伴 canonical 主对话在发送边界达到已知窗口的 90%,或本地 Codex 图片活尾巴实测超限时,+Claude Code/Pi 伙伴 canonical 主对话在发送边界达到已知窗口的 90%,或本地 Codex 图片活尾巴实测超限时,复用同一持久交接提前重建;保留有界工具结果、按输入取消恢复,后台原生工作未结束时不换窗。权限依据为有效 Bot link 与 active Profile;其它任务保留原来的满窗门槛。伙伴下一次发送也识别已记录、明确来自压缩的空摘要/invalid-request 错误;不扩大原生 latch@@ -153,11 +153,16 @@ Codex 图片历史重建后,普通用户任务和伙伴主对话可在同一同引擎切到更小窗口时,main 在实际 send 持有的 session 锁内按目标窗口评估;用户发送即同意为最终选择执行必要的上下文整理,不再弹出二次确认。仅选择或反复切换模型不构成整理授权;同窗或扩窗不因此触发摘要重建。-Claude Code/Codex/Pi 的强制换窗线+Claude Code/Pi 的强制换窗线统一固定为目标窗口 90%,与各 harness 的日常 auto-compaction 百分比解耦;Claude Code与 Pi 的日常默认值也设为 90%,对齐 Codex 口径,但用户已有显式 override 继续生效。命中`danger`/`overflow` 的本机会话先走同一套 `context_rebuild` bounded handoff,再落目标route,不能 resume 旧原生窗口。+Codex 同引擎切模(包括自动任务、Orca、设备互联与 SSH)保留原生历史,由 Codex 自己判断并执行+压缩;本地冷恢复时可先用旧的大窗口模型压缩,再执行目标模型。不得仅因目标窗口较小、占用到+90%/100% 或伙伴账本新鲜而抢先生成 Cindy 交接。窗口预算与用户 override 保持不变;重载模型+目录或凭证执行句柄不等于重建历史。Cindy 只在明确的上下文超限、原生压缩失败或历史字节超限后+沿用既有兜底及副作用保护。跨引擎交接、显式重启和伙伴空闲间隔刷新仍按各自生命周期规则处理。Codex 跨凭证优先保留同一个原生线程;仅当目标需要另一个 host、旧 host 仍持有原生 writer时,关闭该任务的业务 handle 后使用不剥离历史的原生 fork,并等待一次性 fork host 退出,再以任务 owner 与旧 SDK/路由版本为条件原子保存新 SDK thread 和目标路由。任务 ID 与@@ -242,7 +247,7 @@ HTTP 回退遇到缺失 `Content-Type` 的成功响应时,只允许从明文 S确认事件流并补齐响应头;显式非 SSE 类型、HTML/JSON、空响应与只有心跳的正文不能放行。正在运行的 turn、SSH 远端缺少本地交接能力、或已有恢复动作在途时必须 fail closed,不能先热切再发送。三个 harness 的同模型自动压缩所有权保持不变。token 破了只认:终态超限、-占用 ≥ 100%、官方 compact 确定性失败;普通 timeout 不算。+Claude Code/Pi 占用 ≥ 100%、官方 compact 确定性失败;Codex 单纯占用到线和普通 timeout 不算。Codex 已选远端压缩的本地任务,在原生 `contextCompaction` 生命周期内收到终态失败时,只有明确的 HTTP 400/404/405/422/500/501/502/503 拒绝或失败响应,才自动改用同一模型的diff --git a/docs/dev-rules/model-catalog-runtime.md b/docs/dev-rules/model-catalog-runtime.mdindex a4f6596514..00f20303be 100644--- a/docs/dev-rules/model-catalog-runtime.md+++ b/docs/dev-rules/model-catalog-runtime.md@@ -31,6 +31,11 @@ Codex 的圆环总窗口由绑定的 CLI 配置和原生模型元数据解析;模型目录覆盖。总窗口、可用容量和自动压缩阈值分开展示;读取失败显示未知,不猜 272K。模型配置页的上下文上限统一写入该行所有引擎。未保存覆盖值时,Codex 也必须应用该供应商路由在设置页显示的默认窗口,不能只给自定义供应商注入窗口而漏掉 Gateway/订阅。Codex 使用每个任务独立的原生模型目录与thread 配置,同时设置窗口和 90% 自动压缩预算,保留原生 5% 可用空间预留及原有压缩方式。+本地独立目录将预算写到逐模型 `context_window` / `auto_compact_token_limit`,并保留同供应商+其它原生型号各自的有效预算;不能把目标预算作为全局 `model_context_window` 覆盖旧模型,+否则 Codex 在恢复后的缩窗检查中看不到旧窗口大于新窗口,无法先用旧模型压缩。+同一 live 模型临时改变显式预算仍沿用 thread 冷恢复配置,切模型重载目录时撤掉这个覆盖。+SSH 共享 daemon 保留既有逐 thread 配置,不能传入本机目录路径;原生决定压缩方式。显式设置可以超过原生目录默认最大值;它改变 CLI 预算,不改变供应商实际能接受的长度。已运行任务在当前轮结束后重建执行句柄、保留原生历史;恢复默认删除 override。保存后的运行时刷新失败时,仅恢复本次修改的原账号 override(保留各引擎原值和缺席状态,diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex 0eebd50d6a..f4c64c977a 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -199,10 +199,11 @@ IM 轮次都从这个入口进(`im/shared/turnRunner` 在伙伴守卫之后、天,没有出错,完整记录仍在同一条任务里,把新消息当成当前话题,用户不提就不接旧线索,需要细节用历史工具」;同一条消息因发送失败重试时不重复刷新。它仍是同一条任务:时间线、记忆、文件、专线绑定都不变,界面上只多一条「隔了一段时间再聊,已整理上下文后继续」的分隔卡。-- **容量到线**:已知 token 占用达到窗口的 90%(工作记忆已知 token 占用达到窗口的 90%(工作记忆+- **容量到线(Claude Code/Pi)**:已知 token 占用达到窗口的 90%(工作记忆账本已覆盖最近一条完成回复、且账本段能渲染出来并原样带进交接时提前到 70%:宿主换窗不调用模型,能替掉一次把整窗送去总结的原生压缩;账本不新鲜或渲染不出来则维持 90%,不提前换窗),-或 Codex 本地历史确认存在超大内联图片时,先用已有持久交接重建模型工作上下文。+先用已有持久交接重建模型工作上下文。Codex 的 token 压力和同引擎缩窗交给原生压缩,+仅本地历史确认存在超大内联图片或发生下述明确失败时才用容量兜底。- **已知坏历史**:已持久记录的压缩空摘要/invalid-request 失败、上下文溢出、Pi 无响应,也在下一次发送时由宿主重建;普通网络、鉴权、额度错误不据此换窗。diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex 08a6dac1e1..30f6277eb9 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -1070,6 +1070,8 @@ export interface AgentDeps {customContextModel?: string;/** Requested context window for a one-session custom-context host. */customContextWindow?: number;+ /** Budget route, distinct from the host's OAuth account identity. */+ customContextProviderId?: string | null;/** Unique app-server Host-generation identity used to scope custom-context resources. */customContextHostKey?: string;/**diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex c3640eff28..1d7d225d6c 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -20,6 +20,7 @@ import {AUTO_REVIEW_SOURCE_CONTENT,INHERITED_CAPABILITY_SELECTION,MAIN_OWNED_SEND_CONTEXT,+ LOCAL_AGENT_CLIENT,PINNED_SKILL_INVOCATION,CodexResumePreparationBlockedError,AgentNotAuthenticatedError,@@ -34274,8 +34275,10 @@ 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(945_000);+ // The host catalog carries this model's budget. Thread-global overrides+ // would also overwrite the previous model during native downshift compaction.+ expect(params.config?.model_context_window).toBeUndefined();+ expect(params.config?.model_auto_compact_token_limit).toBeUndefined();await handle.close();});@@ -34331,6 +34334,7 @@ describe('CodexAgent custom provider context window override', () => {hostPurpose: 'custom-context',customContextModel: 'gpt-5.6-sol',customContextWindow: 700_000,+ customContextProviderId: 'mygpt',customContextHostKey: 'local-custom-context:session-custom-host-lifecycle:1',});expect(Array.from(@@ -34889,6 +34893,22 @@ describe('CodexAgent compaction storm escalation', () => {describe('Codex native model context overrides', () => {+ // Host-owned conversations replace the ordinary budget catalog with a restricted+ // tool catalog. Dropping their thread budget would silently restore native 272K.+ it('preserves the budget when a host-tools-only catalog replaces the context catalog', async () => {+ const agent = new CodexAgent(createDeps({}, {+ resolveCodexThreadContextWindow: () => 500_000,+ prepareCodexHostToolCatalog: async () => '/tmp/fixture-host-tools/catalog.json',+ }));+ const host = installFakeHost(agent, method => method === Method.ExperimentalFeatureList+ ? { data: [{ name: 'shell_tool', stage: 'stable', enabled: true }], nextCursor: null } : undefined,+ { userAgent: 'mock-codex/0.159.2' });+ const handle = await agent.startSession({ sessionId: 'host-tools-budget', model: 'gpt-5.4', workingDir: '/repo',+ [LOCAL_AGENT_CLIENT]: { url: 'http://127.0.0.1:1/mcp', token: 'fixture-token', hostToolsOnly: true, mcpName: 'fixture' } });+ const start = host.request.mock.calls.find(([method]) => method === Method.ThreadStart)![1] as { config: Record<string, unknown> };+ expect(start.config).toMatchObject({ model_context_window: 500_000, model_auto_compact_token_limit: 450_000 });+ await handle.close();+ });it.each([{ storedLimit: 100_000, expectedWindow: 100_000, expectedCompact: 90_000 },{ storedLimit: 500_000, expectedWindow: 500_000, expectedCompact: 450_000 },@@ -34920,9 +34940,8 @@ describe('Codex native model context overrides', () => {const startParams = host.request.mock.calls.find(([method]) => method === Method.ThreadStart)![1] as {config: Record<string, unknown>;};- expect(startParams.config).toMatchObject({- model_context_window: expectedWindow, model_auto_compact_token_limit: expectedCompact,- });+ expect(startParams.config.model_context_window).toBe(storedLimit === null ? undefined : expectedWindow);+ expect(startParams.config.model_auto_compact_token_limit).toBe(storedLimit === null ? undefined : expectedCompact);const pushUsage = (turnId: string, reportedWindow: number) => {host.getThreadHandlers()!.tokenUsageUpdated?.({threadId: handle.id, turnId,@@ -34948,9 +34967,8 @@ describe('Codex native model context overrides', () => {const resumed = host.request.mock.calls.find(([method]) => method === Method.ThreadResume)![1] as {config: Record<string, unknown>;};- expect(resumed.config).toMatchObject({- model_context_window: 200_000, model_auto_compact_token_limit: 180_000,- });+ expect(resumed.config.model_context_window).toBeUndefined();+ expect(resumed.config.model_auto_compact_token_limit).toBeUndefined();}pushUsage('custom-budget-2', 190_000);expect(handle.getUsageSnapshot().contextWindow).toBe(190_000);diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 9f2fb1b30b..46f206a2d3 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -2574,6 +2574,7 @@ export class CodexAgent extends BaseAgent {localToolCatalog?: string;customContextModel?: string;customContextWindow?: number;+ customContextProviderId?: string | null;sqliteHome?: string;historyHome?: string;/** 受邀者任务的 app-server:值是分享给它的供应商(见 prepareCodexExtraSpawnConfig)。 */@@ -2811,6 +2812,7 @@ assertRouteCurrent();opts.deviceHostedGuestSessionId,opts.deviceHostedGuestModelIds,opts.localToolCatalog,+ opts.customContextProviderId,).finally(() => {// 成功: this.hosts 已赋值, 后续走快路径; 失败: 清掉 promise 让下次调用能重试const current = this.hostPromises.get(key);@@ -3063,6 +3065,7 @@ assertRouteCurrent();deviceHostedGuestSessionId?: string,deviceHostedGuestModelIds?: readonly string[],localToolCatalog?: string,+ customContextProviderId?: string | null,): Promise<AppServerHost> {const seq = (this.createHostSeqByKey.get(key) ?? 0) + 1;this.createHostSeqByKey.set(key, seq);@@ -3204,6 +3207,7 @@ assertRouteCurrent();? {customContextModel,customContextWindow,+ customContextProviderId,customContextHostKey: `${key}:${generation}`,}: {}),@@ -5183,6 +5187,7 @@ assertRouteCurrent();hostPurpose: 'custom-context' as const,customContextModel: opts.model,customContextWindow: initialCustomContextWindow ?? undefined,+ customContextProviderId: opts.providerId,}: {}),});@@ -6677,9 +6682,14 @@ assertRouteCurrent();&& (!hosted || hostedLocalMcpNames.includes('cindy_memory'))? { 'mcp_servers.cindy_memory.enabled': false }: {}),- // Configure the native window and its 90% compaction budget together.- // Native effective_context_window_percent independently reserves input headroom.+ // Local custom-context hosts carry per-model budgets in their catalog.+ // Global overrides hide the previous model's larger window from native+ // downshift compaction. SSH and the separate host-tools-only catalog+ // still need thread-scoped config. A changed+ // explicit limit on this same live model uses the existing cold-resume+ // refresh; switching models reloads the catalog and drops that override....(typeof threadContextWindow === 'number' && threadContextWindow > 0+ && (!usesCustomContextHost || localToolCatalog || threadContextWindow !== initialCustomContextWindow)? {model_context_window: Math.floor(threadContextWindow),model_auto_compact_token_limit: Math.max(