Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(codex): 修复跨模型推理历史的自动恢复 (#6502)
GaoWei Liub2f8ba587a6f
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.tsindex 169e085b5a..1aaf21b835 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts@@ -31,6 +31,7 @@ const mockState = vi.hoisted(() => {error: vi.fn(),},createAnthropicCompatProxy: vi.fn(),+ realStripTransforms: false,createPiProviderFetch: vi.fn(() => vi.fn()),handlePiProviderRequest: vi.fn(async () => undefined),createResponsesChatHandler: vi.fn(() => ({ handle: vi.fn(async () => undefined) })),@@ -99,8 +100,9 @@ vi.mock('@cindy/anthropic-compat-proxy', async (importOriginal) => {...actual,createAnthropicCompatProxy: mockState.createAnthropicCompatProxy,createInstructionsInjectionTransform: mockState.createInstructionsInjectionTransform,- createActiveStripTransform: () => (() => null),- createThreadStripController: () => ({ markActive: () => {}, reconcile: () => {}, shouldStrip: () => false, clear: () => {} }),+ createActiveStripTransform: (...args: Parameters<typeof actual.createActiveStripTransform>) =>+ mockState.realStripTransforms ? actual.createActiveStripTransform(...args) : (() => null),+ createThreadStripController: actual.createThreadStripController,createEncryptedContentRecoveryRule: (opts: { enabled: () => boolean }) => ({id: 'encrypted_content',enabled: opts.enabled,@@ -162,7 +164,8 @@ vi.mock('@cindy/responses-anthropic-bridge', () => ({// generations) plus the boot-time injections a case may have overridden.// Re-importing the whole graph per case instead cost 105s for this file versus// ~7s (2026-10-16), and order-shuffled runs confirm cases stay independent.-async function freshCodexProxyHost() {+async function freshCodexProxyHost(realStripTransforms = false) {+ mockState.realStripTransforms = realStripTransforms;const host = await import('../codex-proxy-host.js');await host.disposeCodexProxy();host.resetCodexThreadUpstreamForTest();@@ -1631,7 +1634,7 @@ describe('chatBridgeCapabilitiesForRoute', () => {reasoning: { effort: 'medium' },input: [],};- for (const transform of transforms.slice(0, 5)) {+ for (const transform of transforms.slice(0, 7)) {const next = transform(transformed, requestContext);if (next !== null && next !== undefined) transformed = next;}@@ -2729,15 +2732,15 @@ describe('codex proxy host', () => {// upstream 是函数形态(每请求现取,model-access 下发可运行期换 endpoint);// 断言其当前求值 = 网关 base + /v1upstream: expect.any(Function),- // [armed HTTP recovery strip(WS 错误后落回 HTTP 即激活对应 strip), encrypted activeStrip, image generation activeStrip, provider-aware Guardian reviewer, locked Subagent route, instructions 注入, locked Subagent exec guard, Gateway 原生 web_search, 跨来源压缩块兼容, xAI ModelInput activeStrip, responses item id activeStrip(#4738), responses item id length activeStrip(#4227), exec function adapter, strict gateway history 兼容, xAI ModelInput sanitize, DeepSeek V4 custom tool 兼容, xAI Responses 兼容, XD Gateway Grok 兼容, ByteDance Seed tool 兼容, MiniMax effort 兼容, provider model rewrite, provider 参数归一, 视觉桥(controller 未注入 → 短路透传), 工具 ID 校正, stripNonAnthropicFields]+ // [armed HTTP recovery strip(WS 错误后落回 HTTP 即激活对应 strip), encrypted activeStrip, image generation activeStrip, provider-aware Guardian reviewer, locked Subagent route, instructions 注入, locked Subagent exec guard, Gateway 原生 web_search, 跨来源压缩块兼容, xAI ModelInput activeStrip, responses item id activeStrip(#4738), responses item id length activeStrip(#4227), exec function adapter, strict gateway history 兼容, xAI ModelInput sanitize, DeepSeek V4 custom tool 兼容, xAI Responses 兼容, XD Gateway Grok 兼容, ByteDance Seed tool 兼容, MiniMax effort 兼容, provider model rewrite, provider 参数归一, routed-model armed HTTP recovery strip, raw reasoning activeStrip, 视觉桥(controller 未注入 → 短路透传), 工具 ID 校正, stripNonAnthropicFields]transformRequest: [expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function),expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function),expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function),expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function),expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function),- expect.any(Function), expect.any(Function), // frozen custom-provider effort- expect.any(Function),+ expect.any(Function), expect.any(Function), expect.any(Function), // frozen custom-provider effort+ expect.any(Function), expect.any(Function),],transformResponse: expect.any(Function),routingTransform: expect.any(Function),@@ -2747,6 +2750,7 @@ describe('codex proxy host', () => {expect.objectContaining({ id: 'image_generation_id' }),expect.objectContaining({ id: 'responses_item_id_prefix' }),expect.objectContaining({ id: 'responses_item_id_length' }),+ expect.objectContaining({ id: 'responses_reasoning_content' }),expect.objectContaining({ id: 'xai_model_input' }),]),}),@@ -2990,6 +2994,205 @@ describe('codex proxy host', () => {}});+ it.each((['shared', 'custom-context', 'control-plane'] as const).flatMap(proxyKind =>+ ['gpt-6.1-sol', 'gpt-6-astra'].map(model => ({ proxyKind, model })),+ ))('recovers DeepSeek reasoning on $proxyKind → $model without losing conversation history', async ({ proxyKind, model }) => {+ const host = await freshCodexProxyHost(true);+ const errorMessage = "Invalid 'input[15].content': array too long. Expected an array with maximum length 0, but got an array with length 1 instead.";+ const reasoning = { type: 'reasoning', summary: [], content: [{ type: 'reasoning_text', text: 'Provider-private reasoning' }], encrypted_content: 'deepseek-blob' };+ const kept = [+ { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'Continue verification' }] },+ { type: 'reasoning', id: 'rs_native', summary: [], encrypted_content: 'openai-blob' },+ { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'The service is running.' }] },+ { type: 'function_call', id: 'fc_native', call_id: 'call_native', name: 'inspect', arguments: '{}' },+ { type: 'function_call_output', id: 'fco_native', call_id: 'call_native', output: 'Verified' },+ { type: 'compaction', encrypted_content: 'compaction-blob' },+ ];+ const history = { model, input: [reasoning, ...kept] };+ const original = JSON.stringify(history);+ const httpBodies: Array<{ input: unknown[] }> = [];+ const wsBodies: unknown[] = [];+ let rejectRawReasoning = true;+ const upstream = createServer(async (req, res) => {+ const chunks: Buffer[] = [];+ for await (const chunk of req) chunks.push(Buffer.from(chunk));+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));+ httpBodies.push(body);+ const valid = !rejectRawReasoning || !body.input.some((item: { content?: unknown; type?: string }) => item.type === 'reasoning' && Array.isArray(item.content) && item.content.length > 0);+ res.writeHead(valid ? 200 : 400, { 'content-type': 'application/json' });+ res.end(JSON.stringify(valid ? { output: [] } : { error: { message: errorMessage, code: 'array_above_max_length' } }));+ });+ const wss = new WebSocketServer({ noServer: true });+ upstream.on('upgrade', (req, socket, head) => wss.handleUpgrade(req, socket, head, ws => {+ ws.on('message', data => {+ const body = JSON.parse(data.toString());+ wsBodies.push(body);+ ws.send(JSON.stringify(body.input ? { error: { message: errorMessage } } : { pong: true }));+ });+ }));+ await new Promise<void>(resolve => upstream.listen(0, '127.0.0.1', resolve));+ const upstreamUrl = `http://127.0.0.1:${(upstream.address() as AddressInfo).port}`;+ const actual = await vi.importActual<typeof import('@cindy/anthropic-compat-proxy')>('@cindy/anthropic-compat-proxy');+ mockState.createAnthropicCompatProxy.mockImplementation((opts: Parameters<typeof actual.createAnthropicCompatProxy>[0]) =>+ actual.createAnthropicCompatProxy({+ ...opts, upstream: upstreamUrl, resolveOutboundProxy: () => null,+ resolveWebSocketUpstream: ctx => opts.resolveWebSocketUpstream?.(ctx) ? upstreamUrl : null,+ routingTransform: async (body, ctx) => ({ ...(await opts.routingTransform?.(body, ctx)), upstreamOverride: upstreamUrl }),+ }),+ );+ host.setCodexProxyAuthInjection('oauth-bearer');+ const clients: WebSocket[] = [];+ try {+ let proxyUrl: string;+ if (proxyKind === 'shared') {+ await host.ensureCodexProxyReady();+ proxyUrl = host.getCodexProxyEndpoint()!;+ } else if (proxyKind === 'custom-context') {+ await host.ensureCodexCustomContextProxyReady('context-reasoning', 'oauth-bearer', []);+ proxyUrl = host.getCodexCustomContextProxyEndpoint('context-reasoning');+ } else {+ await host.ensureCodexControlPlaneProxyReady('oauth-bearer');+ proxyUrl = host.getCodexControlPlaneProxyEndpoint('oauth-bearer');+ }+ host.registerComposed('session-reasoning', 'thread-reasoning', 'PRODUCT_PROMPT');+ host.registerComposed('session-sibling', 'thread-sibling', 'PRODUCT_PROMPT');+ const connect = async (thread: string) => {+ const client = new WebSocket(proxyUrl.replace(/^http/, 'ws') + '/v1/responses', { headers: { 'thread-id': thread } });+ clients.push(client);+ await once(client, 'open');+ return client;+ };+ const bad = await connect('thread-reasoning');+ const sibling = await connect('thread-sibling');+ expect(host.armCodexHttpRecovery({ sessionId: 'unknown', threadId: 'unknown', message: errorMessage })).toBeNull();+ const rejection = once(bad, 'message');+ bad.send(original);+ const [payload] = await rejection;+ expect(wsBodies[0]).toEqual(history);+ // Codex can close the rejected socket before delivering the error callback.+ const closed = once(bad, 'close'); bad.close(); await closed;+ expect(host.armCodexHttpRecovery({ sessionId: 'session-reasoning', threadId: 'thread-reasoning', message: 'Bad request', additionalDetails: JSON.parse(payload.toString()).error.message })).toBe('responses_reasoning_content');+ const retry = new WebSocket(proxyUrl.replace(/^http/, 'ws') + '/v1/responses', { headers: { 'thread-id': 'thread-reasoning' } });+ clients.push(retry);+ const status = await new Promise<number | undefined>((resolve, reject) => {+ retry.once('unexpected-response', (_req, res) => { res.resume(); resolve(res.statusCode); });+ retry.once('error', reject);+ });+ expect(status).toBe(426);+ const post = (threadId = 'thread-reasoning') => new Promise<number | undefined>((resolve, reject) => {+ const req = httpRequest(proxyUrl + '/v1/responses', { method: 'POST', headers: { 'content-type': 'application/json', 'thread-id': threadId } }, res => {+ res.resume(); res.once('end', () => resolve(res.statusCode));+ });+ req.once('error', reject); req.end(original);+ });+ expect(await post()).toBe(200);+ expect(httpBodies).toHaveLength(1); // WS rejection activates the strip before the first HTTP replay.+ expect(httpBodies[0].input).toEqual(kept);+ expect(await post()).toBe(200);+ expect(httpBodies).toHaveLength(2); // Subsequent turn pre-cleans without another 400.+ expect(httpBodies[1].input).toEqual(kept);+ // HTTP-only requests have no WS evidence: retain history until an explicit rejection.+ host.registerComposed('session-http-only', 'thread-http-only', 'PRODUCT_PROMPT');+ expect(await post('thread-http-only')).toBe(200);+ expect(httpBodies).toHaveLength(4);+ expect(httpBodies[2].input).toEqual(history.input);+ expect(httpBodies[3].input).toEqual(kept);+ expect(JSON.stringify(history)).toBe(original);+ expect(sibling.readyState).toBe(WebSocket.OPEN);+ const pong = once(sibling, 'message'); sibling.send(JSON.stringify({ ping: true }));+ expect(JSON.parse((await pong)[0].toString())).toEqual({ pong: true });+ host.unregister('session-reasoning');+ host.registerComposed('session-reasoning', 'thread-reasoning', 'PRODUCT_PROMPT');+ rejectRawReasoning = false;+ expect(await post()).toBe(200);+ expect(httpBodies).toHaveLength(5);+ expect(httpBodies[4].input).toEqual(history.input); // Unregister cleared the pre-clean marker.+ } finally {+ for (const client of clients) { client.on('error', () => {}); client.terminate(); }+ for (const ws of wss.clients) ws.terminate();+ host.unregister('session-reasoning'); host.unregister('session-sibling'); host.unregister('session-http-only');+ await host.disposeCodexProxy();+ await new Promise<void>(resolve => wss.close(() => resolve()));+ upstream.closeAllConnections();+ await new Promise<void>(resolve => upstream.close(() => resolve()));+ mockState.realStripTransforms = false;+ }+ });++ // The client keeps codex-auto-review while the parent changes its routed model.+ // Exercise the real proxy so both retry callbacks and pre-cleaning must agree+ // on the effective model (unit tier; the old constant alias deleted valid history).+ it('preserves Guardian reasoning after switching its routed model back', async () => {+ const host = await freshCodexProxyHost(true);+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');+ const actual = await vi.importActual<typeof import('@cindy/anthropic-compat-proxy')>('@cindy/anthropic-compat-proxy');+ const errorMessage = "Invalid 'input[0].content': array too long. Expected an array with maximum length 0, but got an array with length 1 instead.";+ const history = {+ model: 'codex-auto-review',+ input: [+ { type: 'reasoning', summary: [], content: [{ type: 'reasoning_text', text: 'Valid DeepSeek reasoning' }], encrypted_content: 'deepseek-blob' },+ { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'Review the change' }] },+ ],+ };+ const original = JSON.stringify(history);+ const headers = {+ 'thread-id': 'guardian-reasoning-child',+ 'x-openai-subagent': 'guardian',+ 'x-codex-parent-thread-id': 'guardian-reasoning-parent',+ };+ const bodies: Array<typeof history> = [];+ const upstream = createServer(async (req, res) => {+ const chunks: Buffer[] = [];+ for await (const chunk of req) chunks.push(Buffer.from(chunk));+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));+ bodies.push(body);+ const rejected = body.model === 'gpt-6.1-sol' && body.input.some((item: { type?: string }) => item.type === 'reasoning');+ res.writeHead(rejected ? 400 : 200, { 'content-type': 'application/json' });+ res.end(JSON.stringify(rejected ? { error: { message: errorMessage } } : { output: [] }));+ });+ await new Promise<void>(resolve => upstream.listen(0, '127.0.0.1', resolve));+ const upstreamUrl = `http://127.0.0.1:${(upstream.address() as AddressInfo).port}`;+ mockState.createAnthropicCompatProxy.mockImplementation((opts: Parameters<typeof actual.createAnthropicCompatProxy>[0]) =>+ actual.createAnthropicCompatProxy({+ ...opts, upstream: upstreamUrl, resolveOutboundProxy: () => null,+ routingTransform: async (body, ctx) => ({ ...(await opts.routingTransform?.(body, ctx)), upstreamOverride: upstreamUrl }),+ }),+ );+ try {+ host.setCodexProxyAuthInjection('env-key');+ host.setCodexProxyGatewayKeyReader(() => 'fixture-gateway-key');+ setSessionProvider('guardian-reasoning-session', 'xd');+ host.registerReviewerRouteContext('guardian-reasoning-session', 'guardian-reasoning-parent', 'gpt-6.1-sol');+ await host.ensureCodexProxyReady();+ const proxyUrl = host.getCodexProxyEndpoint()!;+ const post = () => new Promise<number | undefined>((resolve, reject) => {+ const req = httpRequest(proxyUrl + '/v1/responses', { method: 'POST', headers: { ...headers, 'content-type': 'application/json' } }, res => {+ res.resume(); res.once('end', () => resolve(res.statusCode));+ });+ req.once('error', reject); req.end(original);+ });+ expect(await post()).toBe(200);+ expect(bodies).toHaveLength(2);+ expect(bodies.at(-1)?.input).toEqual(history.input.slice(1));+ const afterRecovery = bodies.length;+ expect(await post()).toBe(200);+ expect(bodies).toHaveLength(afterRecovery + 1); // No repeated rejection for the same effective model.+ expect(bodies.at(-1)?.input).toEqual(history.input.slice(1));+ host.registerReviewerRouteContext('guardian-reasoning-session', 'guardian-reasoning-parent', 'deepseek/deepseek-v4');+ expect(await post()).toBe(200);+ expect(bodies).toHaveLength(afterRecovery + 2);+ expect(bodies.at(-1)?.input).toEqual(history.input);+ expect(JSON.stringify(history)).toBe(original);+ } finally {+ host.unregister('guardian-reasoning-session');+ clearSessionProvider('guardian-reasoning-session');+ await host.disposeCodexProxy();+ upstream.closeAllConnections();+ await new Promise<void>(resolve => upstream.close(() => resolve()));+ mockState.realStripTransforms = false;+ }+ });+it('repairs null array fields in passthrough Responses SSE before Codex parses them (#4251)', async () => {const host = await freshCodexProxyHost();// Minimal reproduction from #4251: a third-party model behind the Responses passthrough@@ -6853,7 +7056,7 @@ describe('codex proxy host', () => {await host.ensureCodexProxyReady();const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];- expect(transforms).toHaveLength(27); // ordinary transforms + dump + frozen custom-provider effort+ expect(transforms).toHaveLength(29); // ordinary transforms + dump + frozen custom-provider effortconst ctx = {method: 'POST',url: '/v1/responses',diff --git a/apps/desktop/src/main/maker-host/codex-proxy-host.ts b/apps/desktop/src/main/maker-host/codex-proxy-host.tsindex e68dac77b6..e82610560a 100644--- a/apps/desktop/src/main/maker-host/codex-proxy-host.ts+++ b/apps/desktop/src/main/maker-host/codex-proxy-host.ts@@ -44,6 +44,7 @@ import {createAnthropicCompatProxy,createActiveStripTransform,createEncryptedContentRecoveryRule,+ createResponsesReasoningContentRecoveryRule,createImageGenerationIdRecoveryRule,createResponsesItemIdPrefixRecoveryRule,createResponsesItemIdLengthRecoveryRule,@@ -55,6 +56,7 @@ import {sanitizeXaiModelInputBody,sanitizeXaiModelInputFromBody,stripEncryptedContentFromBody,+ stripResponsesReasoningContentFromBody,stripImageGenerationItemsWithoutIdFromBody,stripNonCanonicalResponsesItemIdsFromBody,shortenOversizedResponsesItemIdsFromBody,@@ -132,6 +134,7 @@ import {imageGenerationStripController,responsesItemIdStripController,responsesItemIdLengthStripController,+ responsesReasoningContentStripController,xaiModelInputStripController,} from './thread-strip-controllers.js';import { createMakerLogger } from './logger-adapter.js';@@ -233,6 +236,9 @@ const responsesItemIdPrefixRecoveryRule = createResponsesItemIdPrefixRecoveryRulconst responsesItemIdLengthRecoveryRule = createResponsesItemIdLengthRecoveryRule({onRetry: (threadId, model) => responsesItemIdLengthStripController.markActive(threadId, model),});+const responsesReasoningContentRecoveryRule = createResponsesReasoningContentRecoveryRule({+ onRetry: (threadId, model) => responsesReasoningContentStripController.markActive(threadId, model),+});const xaiModelInputRecoveryRule = createXaiModelInputRecoveryRule({onRetry: (threadId, model) => xaiModelInputStripController.markActive(threadId, model),});@@ -242,6 +248,7 @@ const CODEX_BODY_RECOVERY_RULES = [imageGenerationIdRecoveryRule,responsesItemIdPrefixRecoveryRule,responsesItemIdLengthRecoveryRule,+ responsesReasoningContentRecoveryRule,xaiModelInputRecoveryRule,vllmResponsesCompatibilityRule,] as const;@@ -343,16 +350,18 @@ export function armCodexHttpRecovery(args: {* 同一历史走 HTTP 时却回 200 + SSE error 事件;只认 400/422 的 recoveryRules 永远不触发,* 任务每轮都以 "stream closed before response.completed" 失败(2026-10-18 实测)。* 激活与上游 400 触发的 rule.onRetry 等价:按本次请求的 model 标记,换模型后照常 reconcile。- * 必须排在各 active strip transform 之前,同一请求即生效。+ * 必须排在各 active strip transform 之前,同一请求即生效。使用最终模型的规则+ * 在 provider model rewrite 后激活,避免 Guardian 等固定别名掩盖真实模型切换。*/-function createArmedHttpRecoveryStripTransform(): RequestTransform {+function createArmedHttpRecoveryStripTransform(useUpstreamModel = false): RequestTransform {return (body, ctx) => {if (!isPlainObject(body) || typeof body.model !== 'string' || !body.model) return null;const threadId = selectedThreadIdFromHeaders(ctx.headers);const reason = pendingHttpRecoveryStripByThread.get(threadId);if (!reason) return null;- pendingHttpRecoveryStripByThread.delete(threadId);const rule = CODEX_BODY_RECOVERY_RULES.find((candidate) => candidate.id === reason);+ if (Boolean(rule?.useUpstreamModel) !== useUpstreamModel) return null;+ pendingHttpRecoveryStripByThread.delete(threadId);if (!rule?.enabled() || !rule.onRetry) return null;rule.onRetry(threadId, body.model);log.info('codex HTTP recovery strip activated from websocket error', { threadId, reason, model: body.model });@@ -3181,7 +3190,6 @@ function createTransformRequestChain(enabled: () => true,strip: stripImageGenerationItemsWithoutIdFromBody,}),-// Guardian uses an isolated child thread. Resolve its parent business// session and select that session's real provider model before provider// compatibility transforms inspect the request.@@ -3230,6 +3238,12 @@ function createTransformRequestChain(createMiniMaxResponsesCompatTransform(),createProviderModelRewriteTransform(frozenAuthInjection),providerRequestTransform,+ createArmedHttpRecoveryStripTransform(true),+ createActiveStripTransform({+ controller: responsesReasoningContentStripController,+ enabled: () => true,+ strip: stripResponsesReasoningContentFromBody,+ }),// 视觉桥透明替换(层 A,Responses 格式):controller 未注入时短路透传,零干扰;// 注入后把纯文本模型请求 input[] 里的 input_image 转成文字描述。放在 strip 之前与// Anthropic 链一致,避免未来 strip 扩展覆盖 Responses input_image 时吃掉图。@@ -3912,6 +3926,7 @@ function clearSessionThreads(sessionId: string): string[] {observedSubagentIdentityByThread.delete(threadId);httpRecoveryReasonByThread.delete(threadId);pendingHttpRecoveryStripByThread.delete(threadId);+ responsesReasoningContentStripController.clear(threadId);}}return threadIds;@@ -3949,6 +3964,7 @@ export async function disposeCodexProxy(): Promise<void> {dumpSeq = 0;for (const threadId of threadToSession.keys()) {registry.delete(threadId);+ responsesReasoningContentStripController.clear(threadId);}sessionToThread.clear();sessionToThreads.clear();diff --git a/apps/desktop/src/main/maker-host/thread-strip-controllers.ts b/apps/desktop/src/main/maker-host/thread-strip-controllers.tsindex ddf75ecc86..00bbdcb7ae 100644--- a/apps/desktop/src/main/maker-host/thread-strip-controllers.ts+++ b/apps/desktop/src/main/maker-host/thread-strip-controllers.ts@@ -19,6 +19,9 @@ export const responsesItemIdStripController = createThreadStripController();// id 切 OpenAI 后被 64 上限拒绝)—— always-on; 恢复一次后该 thread 发送前预改写。export const responsesItemIdLengthStripController = createThreadStripController();+// Raw reasoning content rejected after a provider switch; marked only by its own recovery rule.+export const responsesReasoningContentStripController = createThreadStripController();+// 空 thinking 块主动剥离 —— always-on(删空块零成本)。必须与上面是独立实例。export const emptyThinkingStripController = createThreadStripController();diff --git a/packages/anthropic-compat-proxy/src/index.ts b/packages/anthropic-compat-proxy/src/index.tsindex 7996713192..ab79dbb0a8 100644--- a/packages/anthropic-compat-proxy/src/index.ts+++ b/packages/anthropic-compat-proxy/src/index.ts@@ -43,6 +43,7 @@ export {createEmptyTextRecoveryRule,createEmptyThinkingRecoveryRule,createEncryptedContentRecoveryRule,+ createResponsesReasoningContentRecoveryRule,createImageGenerationIdRecoveryRule,createResponsesItemIdPrefixRecoveryRule,createResponsesItemIdLengthRecoveryRule,@@ -59,6 +60,7 @@ export {stripEmptyTextFromBody,stripEmptyThinkingFromBody,stripEncryptedContentFromBody,+ stripResponsesReasoningContentFromBody,stripImageGenerationItemsWithoutIdFromBody,stripNonAnthropicFields,stripNonCanonicalResponsesItemIdsFromBody,diff --git a/packages/anthropic-compat-proxy/src/server.ts b/packages/anthropic-compat-proxy/src/server.tsindex 69663d937f..8a9b0c65b7 100644--- a/packages/anthropic-compat-proxy/src/server.ts+++ b/packages/anthropic-compat-proxy/src/server.ts@@ -1272,10 +1272,12 @@ function forward(strippedBytes: retryBody.length,});const threadId = selectedHeaderValue(headers, rule.threadIdHeaders ?? DEFAULT_THREAD_ID_HEADERS);- const model = clientModel || extractBodyModel(body);- if (threadId && model) {+ if (threadId) {for (const appliedRule of appliedRules) {- appliedRule.onRetry?.(threadId, model);+ const model = appliedRule.useUpstreamModel+ ? extractBodyModel(body)+ : clientModel || extractBodyModel(body);+ if (model) appliedRule.onRetry?.(threadId, model);}}const retry = (): void => {diff --git a/packages/anthropic-compat-proxy/src/transform.test.ts b/packages/anthropic-compat-proxy/src/transform.test.tsindex ebd81d0051..44738c5aa6 100644--- a/packages/anthropic-compat-proxy/src/transform.test.ts+++ b/packages/anthropic-compat-proxy/src/transform.test.ts@@ -9,6 +9,7 @@ import {createEmptyTextRecoveryRule,createEmptyThinkingRecoveryRule,createEncryptedContentRecoveryRule,+ createResponsesReasoningContentRecoveryRule,createImageGenerationIdRecoveryRule,createToolExchangeAdjacencyRecoveryRule,createToolUseProviderSpecificFieldsRecoveryRule,@@ -21,6 +22,7 @@ import {stripEmptyTextFromBody,stripEmptyThinkingFromBody,stripEncryptedContentFromBody,+ stripResponsesReasoningContentFromBody,stripImageGenerationItemsWithoutIdFromBody,stripNonAnthropicFields,stripNonCanonicalResponsesItemIdsFromBody,@@ -960,6 +962,78 @@ describe('stripEmptyAssistantMessagesFromBody', () => {});});+describe('Responses raw reasoning recovery', () => {+ const error = "Invalid 'input[15].content': array too long. Expected an array with maximum length 0, but got an array with length 1 instead.";+ const rawReasoning = {+ type: 'reasoning', summary: [], encrypted_content: 'deepseek-only-blob',+ content: [{ type: 'reasoning_text', text: 'Private provider reasoning' }],+ };++ it('recognizes only the observed zero-length content rejection', () => {+ const rule = createResponsesReasoningContentRecoveryRule();+ expect(rule.enabled()).toBe(true);+ expect(rule.matches(error)).toBe(true);+ expect(rule.matches(JSON.stringify({ error: { message: error, code: 'array_above_max_length' } }))).toBe(true);+ expect(rule.matches(JSON.stringify({ message: error.replaceAll("'", '"') }))).toBe(true);+ for (const other of [+ error.replace('.content', '.summary'),+ error.replace('input[15].content', 'tools'),+ error.replace('maximum length 0', 'maximum length 10'),+ 'array_above_max_length',+ 'invalid_encrypted_content',+ ]) expect(rule.matches(other)).toBe(false);+ // This destructive repair must neither piggyback on unrelated errors nor+ // cascade into broad encrypted-content stripping on the same retry.+ expect(rule.applyOnUnmatchedRetry).toBe(false);+ expect(rule.allowExtraRules).toBe(false);+ });++ it('preserves conversation, tool payloads, valid GPT reasoning and compaction without mutating history', () => {+ const kept = [+ { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'Continue verification' }, { type: 'input_image', image_url: 'fixture:image' }] },+ { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'The service is running.' }] },+ { type: 'reasoning', id: 'rs_native', summary: [{ type: 'summary_text', text: 'A useful summary' }], encrypted_content: 'openai-blob' },+ { type: 'reasoning', summary: [], content: [], encrypted_content: 'openai-empty-content' },+ { type: 'compaction', encrypted_content: 'compact-blob' },+ { type: 'context_compaction', encrypted_content: 'context-blob' },+ { type: 'function_call', call_id: 'call_fn', name: 'inspect', arguments: JSON.stringify(rawReasoning) },+ { type: 'function_call_output', call_id: 'call_fn', output: JSON.stringify(rawReasoning) },+ { type: 'custom_tool_call', call_id: 'call_custom', name: 'exec', input: JSON.stringify(rawReasoning) },+ { type: 'custom_tool_call_output', call_id: 'call_custom', output: JSON.stringify(rawReasoning) },+ { type: 'message', role: 'user', content: [{ ...rawReasoning }] },+ ];+ const history = { model: 'gpt-6.1-sol', instructions: 'Keep working', input: [rawReasoning, ...kept, { ...rawReasoning, encrypted_content: undefined }] };+ const original = JSON.stringify(history);+ const body = buf(history);+ const result = stripResponsesReasoningContentFromBody(body)!;+ expect(JSON.parse(result.toString())).toEqual({ ...history, input: kept });+ expect(body.toString()).toBe(original);+ expect(JSON.stringify(history)).toBe(original);+ expect(stripResponsesReasoningContentFromBody(result)).toBeNull();+ });++ it('leaves unrelated or malformed bodies unchanged', () => {+ for (const body of [+ Buffer.from('not json'), buf(null), buf({}), buf({ input: 'text' }),+ buf({ input: [{ type: 'message', content: [{ type: 'reasoning_text', text: 'ordinary content' }] }] }),+ buf({ input: [{ type: 'reasoning', content: [], encrypted_content: 'native' }] }),+ ]) expect(stripResponsesReasoningContentFromBody(body)).toBeNull();+ });++ it('pre-cleans only the recovered thread and model, and forgets the marker on a model switch', () => {+ const controller = createThreadStripController();+ const rule = createResponsesReasoningContentRecoveryRule({ onRetry: (thread, model) => controller.markActive(thread, model) });+ const transform = createActiveStripTransform({ controller, enabled: () => true, strip: rule.strip });+ const body = { model: 'gpt-6-astra', input: [rawReasoning, { role: 'user', content: 'Continue' }] };+ expect(transform(body, ctx)).toBeNull();+ rule.onRetry?.('thread-a', body.model);+ expect(transform(body, ctx)).toEqual({ ...body, input: [body.input[1]] });+ expect(transform(body, { ...ctx, headers: { 'thread-id': 'thread-b' } })).toBeNull();+ expect(transform({ ...body, model: 'deepseek/deepseek-v4.1-flash' }, ctx)).toBeNull();+ expect(transform(body, ctx)).toBeNull();+ });+});+describe('createThreadStripController', () => {it('marks active threads and clears them when model changes', () => {const controller = createThreadStripController();diff --git a/packages/anthropic-compat-proxy/src/transform.ts b/packages/anthropic-compat-proxy/src/transform.tsindex 00e11aacec..ef5499aea2 100644--- a/packages/anthropic-compat-proxy/src/transform.ts+++ b/packages/anthropic-compat-proxy/src/transform.ts@@ -9,6 +9,7 @@ export {createResponsesItemIdLengthRecoveryRule,stripToolUseProviderSpecificFields,stripEncryptedContentFromBody,+ stripResponsesReasoningContentFromBody,stripImageGenerationItemsWithoutIdFromBody,stripEmptyThinkingFromBody,stripEmptyTextFromBody,@@ -23,6 +24,7 @@ export {stripNonAnthropicFields,createActiveStripTransform,createEncryptedContentRecoveryRule,+ createResponsesReasoningContentRecoveryRule,createImageGenerationIdRecoveryRule,createToolUseProviderSpecificFieldsRecoveryRule,createEmptyThinkingRecoveryRule,diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 6f035e4346..12e7f3f395 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -11377,6 +11377,7 @@ describe('CodexAgent MCP thread context hooks', () => {it.each([['encrypted_content', ENCRYPTED_ERROR],['tool_item_id', "Invalid 'input[285].id': 'fc_legacy'. Expected an ID that begins with 'ctc'."],+ ['responses_reasoning_content', "Invalid 'input[15].content': array too long. Expected an array with maximum length 0, but got an array with length 1 instead."],])('arms HTTP fallback and retries the same zero-output turn once (%s)', async (reason, recoveryError) => {const armCodexHttpRecovery = vi.fn(() => reason);const agent = new CodexAgent(createDeps({}, { armCodexHttpRecovery }));diff --git a/packages/model-compat/src/cindy/proxy/transform.ts b/packages/model-compat/src/cindy/proxy/transform.tsindex f198563b0f..5ec9767f6b 100644--- a/packages/model-compat/src/cindy/proxy/transform.ts+++ b/packages/model-compat/src/cindy/proxy/transform.ts@@ -264,6 +264,28 @@ export function stripEncryptedContentFromBody(rawBody: Buffer): Buffer | null {}}+/**+ * OpenAI rejects replayed raw reasoning content from providers such as DeepSeek.+ * Drop only those protocol items, including their provider-bound blob: retaining+ * the blob after deleting content would immediately cause another rejection.+ * Ordinary messages, tool payloads and compacted context are never traversed.+ */+export function stripResponsesReasoningContentFromBody(rawBody: Buffer): Buffer | null {+ let parsed: unknown;+ try {+ parsed = JSON.parse(rawBody.toString('utf8'));+ } catch {+ return null;+ }+ if (!isPlainObject(parsed) || !Array.isArray(parsed.input)) return null;+ const input = parsed.input.filter((item) => !(+ isPlainObject(item) && item.type === 'reasoning' && Array.isArray(item.content) &&+ item.content.some((part) => isPlainObject(part) && part.type === 'reasoning_text')+ ));+ if (input.length === parsed.input.length) return null;+ return Buffer.from(JSON.stringify({ ...parsed, input }), 'utf8');+}+function isImageGenerationType(type: unknown): boolean {if (typeof type !== 'string') return false;return type.startsWith('image_generation') || type.startsWith('imageGeneration');@@ -1601,6 +1623,11 @@ const RESPONSES_ITEM_ID_PREFIX_RE =const RESPONSES_ITEM_ID_LENGTH_RE =/input\[\d+\]\.id\\?["']?[\s\S]{0,120}?(?:string too long|string_above_max_length)|string_above_max_length[\s\S]{0,120}?input\[\d+\]\.id/i;+// DeepSeek history resumed on OpenAI (2026-10-20): raw reasoning content is+// output-only on that route. Do not treat other array limits as this repair.+const RESPONSES_REASONING_CONTENT_RE =+ /Invalid\s+\\?["']input\[\d+\]\.content\\?["']:\s*array too long\.\s*Expected an array with maximum length 0, but got an array with length [1-9]\d* instead\./i;+// Azure/LiteLLM 400: "Image generation items without `id` are not supported for this request."const IMAGE_GENERATION_WITHOUT_ID_RE =/image generation items without [`']?id[`']? are not supported/i;@@ -1663,6 +1690,24 @@ export function createEncryptedContentRecoveryRule(opts: {};}+/** Recover only after the target explicitly rejects raw reasoning content. */+export function createResponsesReasoningContentRecoveryRule(opts: {+ onRetry?: (threadId: string, model: string) => void;+} = {}): RecoveryRule {+ return {+ id: 'responses_reasoning_content',+ useUpstreamModel: true,+ enabled: () => true,+ matches: (text) => RESPONSES_REASONING_CONTENT_RE.test(text),+ strip: stripResponsesReasoningContentFromBody,+ // Raw reasoning is valid on its original provider. Neither apply this rule+ // on unrelated errors nor let broad encrypted strips remove valid GPT state.+ applyOnUnmatchedRetry: false,+ allowExtraRules: false,+ onRetry: opts.onRetry,+ };+}+/*** 缺 id 的 image generation item 恢复规则: 剥掉坏历史 item 后重发。* 默认 always-on;只在明确命中上游错误时触发,正常请求字节透传。diff --git a/packages/model-compat/src/cindy/proxy/types.ts b/packages/model-compat/src/cindy/proxy/types.tsindex 7800ef68e3..7148244c5c 100644--- a/packages/model-compat/src/cindy/proxy/types.ts+++ b/packages/model-compat/src/cindy/proxy/types.ts@@ -75,6 +75,8 @@ export interface RecoveryRule {unrecoverableCode?: (body: Buffer) => string | null;/** 命中并成功 strip 后触发(用于 Layer-2 markActive)。 */onRetry?: (threadId: string, model: string) => void;+ /** Use the final wire model for retry markers; its active strip must run after model rewrites. */+ useUpstreamModel?: boolean;/** 取 threadId 的 header 候选名;省略用默认 DEFAULT_THREAD_ID_HEADERS。 */threadIdHeaders?: readonly string[];/**