Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(codex): honor user context caps for custom providers
Chris06879b776b1a
diff --cc packages/maker-core/src/agents/codex/index.test.tsindex 6eba4d9387,6729cd819a..705fa36736--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@@ -31040,43 -31040,3 +31040,111 @@@ describe('CodexAgent compaction storm eawait handle.close();});});+++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, expectedWindow, expectedCompact,++ }) => {++ let limit: number | null = storedLimit;++ const agent = new CodexAgent(createDeps({}, {++ resolveCodexThreadContextWindow: async (provider, model) =>++ 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.++ resolveVerifiedContextWindow: () => 1_050_000,++ }));++ let turnSeq = 0;++ const host = installFakeHost(agent, (method, params) => {++ if (method === Method.TurnStart) return { turn: { id: `custom-budget-${++turnSeq}` } };++ if (method === Method.ThreadResume) return {++ thread: { id: (params as { threadId: string }).threadId },++ model: 'gpt-5.6-sol', modelProvider: 'mygpt',++ };++ return undefined;++ });++ const handle = await agent.startSession({++ sessionId: 'custom-context-budget', model: 'gpt-5.6-sol', providerId: 'mygpt', workingDir: '/repo',++ });++ 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,++ });++ const pushUsage = (turnId: string) => {++ 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,++ },++ } as never);++ };++ await handle.send({ type: 'user', content: 'hello' });++ pushUsage('custom-budget-1');++ expect(handle.getUsageSnapshot().contextWindow).toBe(expectedWindow);++ 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);++ host.getThreadHandlers()!.turnCompleted?.({++ threadId: handle.id, turn: { id: 'custom-budget-1', status: 'completed' },++ });++ await handle.send({ type: 'user', content: 'next' });++ if (storedLimit !== null) {++ 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: 190_000,++ });++ }++ pushUsage('custom-budget-2');++ expect(handle.getUsageSnapshot().contextWindow).toBe(200_000);++ await handle.close();++ });+++ it('sends explicit limits to native compaction and removes them on cold resume after reset', async () => {+ let limit: number | null = 500_000;+ const resolveModelContextLimit = vi.fn((provider, model) => provider === 'openai' && model === 'gpt-5.4' ? limit : null);+ const agent = new CodexAgent(createDeps({}, { resolveModelContextLimit }));+ let turnSeq = 0;+ const host = installFakeHost(agent, (method, params) => {+ if (method === Method.TurnStart) return { turn: { id: `budget-turn-${++turnSeq}` } };+ if (method === Method.ThreadResume) return { thread: { id: (params as { threadId: string }).threadId }, model: 'gpt-5.4', modelProvider: 'openai' };+ return undefined;+ });+ const handle = await agent.startSession({ sessionId: 'context-budget', model: 'gpt-5.4', providerId: 'openai', workingDir: '/repo' });+ const startParams = host.request.mock.calls.find(([method]) => method === Method.ThreadStart)![1] as { config: Record<string, unknown> };+ expect(startParams.config).toMatchObject({ model_context_window: 500_000, model_auto_compact_token_limit: 450_000 });+ await handle.send({ type: 'user', content: 'hello' });+ const originalSubscription = host.subscribeThread.mock.results[0]!.value;+ // Native turn completion makes the next send eligible for a settings refresh.+ host.getThreadHandlers()!.turnCompleted?.({ threadId: handle.id, turn: { id: 'budget-turn-1', status: 'completed' } });+ limit = null;+ await handle.send({ type: 'user', content: 'next' });+ expect(originalSubscription.release).toHaveBeenCalledOnce();+ const resumed = host.request.mock.calls.find(([method]) => method === Method.ThreadResume)![1] as { config?: Record<string, unknown> };+ expect(resumed.config?.model_context_window).toBeUndefined();+ expect(resumed.config?.model_auto_compact_token_limit).toBeUndefined();+ expect(host.subscribeThread).toHaveBeenCalledTimes(2);+ await handle.close();+ });++ it('leaves native defaults untouched when no local override exists', async () => {+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent);+ const handle = await agent.startSession({ sessionId: 'default-budget', model: 'gpt-5.4', workingDir: '/repo' });+ const params = host.request.mock.calls.find(([method]) => method === Method.ThreadStart)![1] as { config?: Record<string, unknown> };+ expect(params.config?.model_context_window).toBeUndefined();+ expect(params.config?.model_auto_compact_token_limit).toBeUndefined();+ await handle.close();+ });+});diff --cc packages/maker-core/src/agents/codex/index.tsindex 0b0e4e1233,ce32d4a79b..a055bff14b--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@@ -5479,13 -5476,8 +5479,25 @@@ export class CodexAgent extends BaseAge}let customProviderThreadConfig: Record<string, unknown> = {};+ const currentContextLimit = (): number | null => {+ 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.++ 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);++ };+ let appliedContextLimit = currentContextLimit();++ activeTurnContextLimit = effectiveThreadContextWindow(appliedContextLimit);- function currentThreadWorkspaceConfig(): Pick<+ function currentThreadWorkspaceConfig(contextLimit = currentContextLimit()): Pick<ThreadStartParams,| 'approvalPolicy'| 'approvalsReviewer'@@@ -5495,7 -5487,7 +5507,7 @@@| 'config'> {const { approvalPolicy, approvalsReviewer, sandbox } = currentApprovalConfig();-- const threadContextWindow = initialCustomContextWindow;++ const threadContextWindow = effectiveThreadContextWindow(contextLimit);const config = {...capabilityRoutingConfig,...customProviderThreadConfig,@@@ -5516,15 -5504,15 +5524,15 @@@}: {}),...(reviewMode ? {} : host.getSessionMcpConfig(opts.sessionInstanceId)),-- // 自定义供应商显式窗口。隔离 app-server 的静态模型目录先放开-- // `max_context_window`,这里再按 thread 设置实际窗口和 95% 自动压缩阈值。-- // 官方会话继续走共享 app-server + live catalog,不受该静态目录影响。++ // 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....(typeof threadContextWindow === 'number' && threadContextWindow > 0? {model_context_window: Math.floor(threadContextWindow),model_auto_compact_token_limit: Math.max(1,-- Math.floor(threadContextWindow * 0.95),++ Math.floor(threadContextWindow * (contextLimit === null ? 0.95 : 0.9)),),}: {}),@@@ -11851,7 -11785,6 +11859,7 @@@// 这一 turn 的用量按这里发出去的 (provider, model) 归属上下文窗口 —— 之后 setModel// 立即改这两个值也不会串到还在产出的本 turn (见 activeTurnModel / capContextWindow)。activeTurnModel = mutableCatalogModel;- activeTurnContextLimit = appliedContextLimit;++ activeTurnContextLimit = effectiveThreadContextWindow(appliedContextLimit);activeTurnProviderId = mutableProviderId;const markTurnConfigAccepted = (): void => {threadMayHaveRollout = true;@@@ -12279,7 -12212,6 +12287,7 @@@// 恢复路径可能把 'gpt-5' 哨兵解析成具体路由模型 —— 重投的 turn 用的是新值,// 窗口归属必须跟着改写走, 否则查不到目录条目、沿用 app-server 的基础模型窗口。activeTurnModel = mutableCatalogModel;- activeTurnContextLimit = appliedContextLimit;++ activeTurnContextLimit = effectiveThreadContextWindow(appliedContextLimit);activeTurnProviderId = mutableProviderId;if (mutableServiceTier !== undefined) {turnParams.serviceTier = mutableServiceTier ?? null;