Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(codex): 修复切换压缩工具 ID 错配及独立代理恢复 (#4129)
Chris Zhang10928e638226
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexExecFunctionAdapter.e2e.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexExecFunctionAdapter.e2e.test.tsindex fc972622fd..2aad78156c 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexExecFunctionAdapter.e2e.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexExecFunctionAdapter.e2e.test.ts@@ -131,6 +131,7 @@ describe.skipIf(!codexBoundaryAvailable)('Codex custom exec function adapter E2Eit('reads a fixture through a real commandExecution and returns it without Web Search', async () => {const providerRequests: Array<Record<string, unknown>> = [];+ const codexRequests: Array<Record<string, unknown>> = [];const idPrefixViolations: string[] = [];let execFunctionName = '';const command =@@ -253,7 +254,10 @@ describe.skipIf(!codexBoundaryAvailable)('Codex custom exec function adapter E2Econst adapter = createResponsesCustomToolFunctionAdapter(['exec']);const proxy: ProxyHandle = await createAnthropicCompatProxy({upstream: providerUrl,- transformRequest: [(body, ctx) => adapter.adaptRequest(body, ctx.reqId)],+ transformRequest: [(body, ctx) => {+ codexRequests.push(structuredClone(body) as Record<string, unknown>);+ return adapter.adaptRequest(body, ctx.reqId);+ }],transformResponse: (ctx) =>adapter.createResponseTransform(ctx.reqId, {contentType: ctx.responseHeaders['content-type'] ?? '',@@ -375,6 +379,16 @@ stream_max_retries = 0expect.objectContaining({ type: 'custom', name: 'exec' }),);+ // Inspect the native replay BEFORE outbound adaptation can hide a response-side mismatch.+ // This is the same custom-tool history a native compact endpoint would validate.+ const nativeInput = codexRequests[1]?.input as Array<Record<string, unknown>>;+ expect(nativeInput).toContainEqual(expect.objectContaining({+ type: 'custom_tool_call', id: 'ctc_exec_call_1', call_id: 'exec-call-1',+ }));+ expect(nativeInput).toContainEqual(expect.objectContaining({+ type: 'custom_tool_call_output', call_id: 'exec-call-1',+ }));+const secondInput = providerRequests[1]?.input as Array<Record<string, unknown>>;const execOutput = secondInput.find((item) => item.type === 'function_call_output' && item.call_id === 'exec-call-1',diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.tsindex 21e3ddcc0b..2eafa66037 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts@@ -1,4 +1,6 @@import fs from 'node:fs';+import { once } from 'node:events';+import { WebSocket, WebSocketServer } from 'ws';import { createServer, request as httpRequest } from 'node:http';import type { AddressInfo } from 'node:net';import os from 'node:os';@@ -2703,13 +2705,13 @@ describe('codex proxy host', () => {// upstream 是函数形态(每请求现取,model-access 下发可运行期换 endpoint);// 断言其当前求值 = 网关 base + /v1upstream: expect.any(Function),- // [encrypted activeStrip, image generation activeStrip, provider-aware Guardian reviewer, locked Subagent route, instructions 注入, locked Subagent exec guard, Gateway 原生 web_search, 跨来源压缩块兼容, xAI ModelInput activeStrip, 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, 视觉桥(controller 未注入 → 短路透传), stripNonAnthropicFields]+ // [encrypted activeStrip, image generation activeStrip, provider-aware Guardian reviewer, locked Subagent route, instructions 注入, locked Subagent exec guard, Gateway 原生 web_search, 跨来源压缩块兼容, xAI ModelInput activeStrip, 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, 视觉桥(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),- mockState.stripNonAnthropicFields,+ expect.any(Function), expect.any(Function),],transformResponse: expect.any(Function),routingTransform: expect.any(Function),@@ -2734,6 +2736,10 @@ describe('codex proxy host', () => {);expect(requestScopedTransforms).toHaveLength(1);expect(requestScopedTransforms[0]?.errorMode).toBe('reject-request');+ const strip = mockState.createAnthropicCompatProxy.mock.calls[0][0].transformRequest.at(-1);+ const body = { model: 'gpt-5', input: [] };+ strip(body, { url: '/responses' });+ expect(mockState.stripNonAnthropicFields).toHaveBeenCalledWith(body, { url: '/responses' });});it('only resolves the websocket upstream for the oauth-bearer spawn identity', async () => {@@ -2828,6 +2834,139 @@ describe('codex proxy host', () => {expect(disconnectWebSocketsForThread).toHaveBeenCalledWith('thread-image');});+ it.each(['shared', 'custom-context', 'control-plane'] as const)(+ 'repairs legacy IDs after a WebSocket rejection on the %s proxy, preserving sibling connections', async (proxyKind) => {+ const host = await freshCodexProxyHost();+ const errorMessage = "Invalid 'input[285].id': 'fc_legacy'. Expected an ID that begins with 'ctc'.";+ const legacy = { model: 'gpt-6', input: [+ { type: 'custom_tool_call', id: 'fc_legacy', name: 'exec', call_id: 'call_legacy', input: 'text(1)' },+ { type: 'custom_tool_call_output', id: 'ctco_result', call_id: 'call_legacy', output: '1' },+ ] };+ const httpBodies: Array<{ input: typeof legacy.input }> = [];+ const wsBodies: unknown[] = [];+ 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 = body.input[0].id === 'ctc_legacy';+ res.writeHead(valid ? 200 : 400, { 'content-type': 'application/json' });+ res.end(JSON.stringify(valid ? { output: [] } : { error: { message: errorMessage } }));+ });+ 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-recovery', 'oauth-bearer', []);+ proxyUrl = host.getCodexCustomContextProxyEndpoint('context-recovery');+ } else {+ await host.ensureCodexControlPlaneProxyReady('oauth-bearer');+ proxyUrl = host.getCodexControlPlaneProxyEndpoint('oauth-bearer');+ }+ await host.ensureCodexCustomContextProxyReady('context-sibling', 'oauth-bearer', []);+ host.registerComposed('session-bad-ids', 'thread-bad-ids', 'PRODUCT_PROMPT');+ host.registerComposed('session-good-ids', 'thread-good-ids', 'PRODUCT_PROMPT');+ const connect = async (thread: string, endpoint = proxyUrl) => {+ const client = new WebSocket(endpoint.replace(/^http/, 'ws') + '/v1/responses', { headers: { 'thread-id': thread } });+ clients.push(client);+ await once(client, 'open');+ return client;+ };+ const bad = await connect('thread-bad-ids');+ const good = await connect('thread-good-ids');+ const independent = await connect('thread-independent', host.getCodexCustomContextProxyEndpoint('context-sibling'));+ expect(host.armCodexHttpRecovery({ sessionId: 'session-unknown', threadId: 'thread-without-socket', message: errorMessage })).toBeNull();+ const rejection = once(bad, 'message');+ bad.send(JSON.stringify(legacy));+ const [payload] = await rejection;+ expect(wsBodies[0]).toEqual(legacy); // WS really bypassed the request transforms.+ expect(httpBodies).toHaveLength(0);+ const closed = once(bad, 'close');+ expect(host.armCodexHttpRecovery({ sessionId: 'session-bad-ids', threadId: 'thread-bad-ids', message: JSON.parse(payload.toString()).error.message })).toBe('tool_item_id');+ await closed;+ const retry = new WebSocket(proxyUrl.replace(/^http/, 'ws') + '/v1/responses', { headers: { 'thread-id': 'thread-bad-ids' } });+ 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);+ // Native Codex falls back to HTTP after 426. Exercise both ordinary replay and unary compact.+ for (const endpoint of ['/v1/responses', '/v1/responses/compact']) {+ const code = await new Promise<number | undefined>((resolve, reject) => {+ const req = httpRequest(proxyUrl + endpoint, { method: 'POST', headers: { 'content-type': 'application/json', 'thread-id': 'thread-bad-ids' } }, res => {+ res.resume(); res.once('end', () => resolve(res.statusCode));+ });+ req.once('error', reject); req.end(JSON.stringify(legacy));+ });+ expect(code).toBe(200);+ }+ expect(httpBodies).toHaveLength(2);+ for (const body of httpBodies) expect(body.input).toEqual([{ ...legacy.input[0], id: 'ctc_legacy' }, legacy.input[1]]);+ // Unregister must clear the marker and each owning proxy's successful-WS proof.+ host.unregister('session-bad-ids');+ host.registerComposed('session-bad-ids', 'thread-bad-ids', 'PRODUCT_PROMPT');+ const resumed = await connect('thread-bad-ids');+ const resumedClosed = once(resumed, 'close');+ host.unregister('session-bad-ids');+ await resumedClosed;+ for (const sibling of [good, independent]) {+ 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 });+ }+ } finally {+ for (const client of clients) { client.on('error', () => {}); client.terminate(); }+ for (const ws of wss.clients) ws.terminate();+ host.unregister('session-bad-ids'); host.unregister('session-good-ids');+ await host.disposeCodexProxy();+ await new Promise<void>(resolve => wss.close(() => resolve()));+ upstream.closeAllConnections();+ await new Promise<void>(resolve => upstream.close(() => resolve()));+ }+ });++ it.each([+ ["Invalid 'input[2].id': 'ctc_old'. Expected an ID that begins with 'fc'.", 'tool_item_id'],+ [JSON.stringify({ error: { message: "Invalid \"input[2].id\": \"fco_old\". Expected an ID that begins with \"ctco\"." } }), 'tool_item_id'],+ ["Invalid 'input[2].call_id': 'fc_old'. Expected an ID that begins with 'ctc'.", null],+ ["Invalid 'input[2].id': 'fc_old'. Expected an ID that begins with 'msg'.", null],+ ["Invalid 'input[2].id': 'unknown_old'. Expected an ID that begins with 'ctc'.", null],+ ["Invalid 'input[2].id': 'FC_old'. Expected an ID that begins with 'ctc'.", null],+ ['invalid_value', null],+ ])('arms recovery only for repairable tool item errors: %s', async (message, expected) => {+ const host = await freshCodexProxyHost();+ const disconnect = vi.fn(() => 1);+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({ url: 'http://127.0.0.1:43210', disconnectWebSocketsForThread: disconnect, dispose: vi.fn(async () => undefined) });+ await host.ensureCodexProxyReady();+ expect(host.armCodexHttpRecovery({ sessionId: 'session-prefix', threadId: 'thread-prefix', message: 'Bad request', additionalDetails: message })).toBe(expected);+ expect(disconnect).toHaveBeenCalledTimes(expected ? 1 : 0);+ });+it('keeps the parent websocket while observing every subagent over HTTP', async () => {// cindy_openai 保持父线程 WS 能力;collab_spawn child upgrade 一律回 null//(426 → Codex 按子会话降到 HTTP),这样 proxy 才能按请求模型路由并记录真实身份。@@ -3928,7 +4067,7 @@ describe('codex proxy host', () => {{ type: 'reasoning', id: 'rs_1', summary: [], encrypted_content: 'gAAA' },{type: 'function_call',- id: 'ctc_1',+ id: 'fc_1',name: 'exec',arguments: '{"input":"console.log(1)"}',call_id: 'call_exec_1',@@ -4556,6 +4695,30 @@ describe('codex proxy host', () => {});});+ it.each(['env-key', 'oauth-bearer'] as const)('repairs legacy tool ids in tool-less compact requests (%s)', async (auth) => {+ const host = await freshCodexProxyHost();+ host.setCodexProxyAuthInjection(auth);+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({ url: 'http://127.0.0.1:43210', dispose: vi.fn(async () => undefined) });+ await host.ensureCodexProxyReady();+ const config = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0];+ const original = {+ model: 'gpt-6',+ input: [+ { type: 'custom_tool_call', id: 'fc_legacy', name: 'exec', call_id: 'call_legacy', input: 'text(1)' },+ { type: 'custom_tool_call_output', id: 'ctco_result', call_id: 'call_legacy', output: '1' },+ ],+ };+ let current: unknown = original;+ for (const transform of config.transformRequest) {+ current = transform(current, { reqId: 8001, method: 'POST', url: '/responses/compact', headers: {} }) ?? current;+ }+ expect(current).toMatchObject({ input: [+ { ...original.input[0], id: 'ctc_legacy' }, original.input[1],+ ] });+ expect(original.input[0].id).toBe('fc_legacy');+ expect(config.transformResponse({ reqId: 8001, responseHeaders: { 'content-type': 'application/json' } })).toBeNull();+ });+it('round-trips exec for a custom Responses Provider that lacks native custom tools', async () => {const host = await freshCodexProxyHost();const { buildUserProvider } = await import('@cindy/model-providers');@@ -4640,7 +4803,7 @@ describe('codex proxy host', () => {responseTransform.once('end', resolve);responseTransform.once('error', reject);});- const call = { type: 'function_call', name: 'exec', call_id: 'call_exec', arguments: '' };+ const call = { type: 'function_call', id: 'fc_1', name: 'exec', call_id: 'call_exec', arguments: '' };responseTransform.end([{ type: 'response.output_item.added', output_index: 0, item: call },{ type: 'response.function_call_arguments.done', item_id: 'fc_1', output_index: 0,@@ -4657,8 +4820,10 @@ describe('codex proxy host', () => {'response.custom_tool_call_input.done','response.output_item.done',]);- expect(events[1]).toMatchObject({ item_id: 'fc_1', delta: 'text("local")' });+ expect(events[1]).toMatchObject({ item_id: 'ctc_1', delta: 'text("local")' });+ expect(events[0].item.id).toBe('ctc_1');expect(events[3].item).toEqual({+ id: 'ctc_1',type: 'custom_tool_call',name: 'exec',call_id: 'call_exec',@@ -6061,7 +6226,7 @@ describe('codex proxy host', () => {await host.ensureCodexProxyReady();const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];- expect(transforms).toHaveLength(21); // encrypted activeStrip, image generation activeStrip, provider-aware Guardian reviewer, locked Subagent route, instructions 注入, locked Subagent exec guard, Gateway 原生 web_search, 跨来源压缩块兼容, xAI ModelInput activeStrip, 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, 视觉桥(短路), stripNonAnthropicFields, dump+ expect(transforms).toHaveLength(22); // encrypted activeStrip, image generation activeStrip, provider-aware Guardian reviewer, locked Subagent route, instructions 注入, locked Subagent exec guard, Gateway 原生 web_search, 跨来源压缩块兼容, xAI ModelInput activeStrip, 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, 视觉桥(短路), 工具 ID 校正, stripNonAnthropicFields, dumpconst ctx = {method: 'POST',url: '/v1/responses',@@ -7345,6 +7510,80 @@ describe('createModelRoutingTransform —— custom Provider native imagegen pre}});+ it('repairs namespaced Responses history over HTTP without rewriting native fields or image JSON', async () => {+ const received: Array<{ path: string; body: string }> = [];+ const upstream = createServer((req, res) => {+ const chunks: Buffer[] = [];+ req.on('data', (chunk: Buffer) => chunks.push(chunk));+ req.on('end', () => {+ received.push({ path: req.url ?? '', body: Buffer.concat(chunks).toString('utf8') });+ res.writeHead(200, { 'content-type': 'application/json' }).end('{}');+ });+ });+ await new Promise<void>((resolve) => upstream.listen(0, '127.0.0.1', resolve));+ const host = await freshCodexProxyHost();+ const actualProxy = await vi.importActual<typeof import('@cindy/anthropic-compat-proxy')>(+ '@cindy/anthropic-compat-proxy',+ );+ mockState.createAnthropicCompatProxy.mockImplementationOnce(actualProxy.createAnthropicCompatProxy);+ const { BUNDLED_CATALOG, buildUserProvider } = await import('@cindy/model-providers');+ const { setActiveCatalog } = await import('../active-catalog.js');+ const { setCustomProviderKeyReader } = await import('../provider-route.js');+ const { deriveCodexCustomProviderRoutes } = await import('../codex-custom-provider-route.js');+ const provider = buildUserProvider({+ id: 'native-tool-id-provider', name: 'Native tools',+ runtimes: { codex: {+ baseUrl: `http://127.0.0.1:${(upstream.address() as AddressInfo).port}/v1`,+ wireProtocol: 'openai-responses', supportsImageGeneration: true,+ models: [{ id: 'codex/native-model', name: 'Native model' }],+ } },+ });+ const catalog = { ...BUNDLED_CATALOG, providers: [...BUNDLED_CATALOG.providers, provider] };+ setActiveCatalog(catalog);+ setCustomProviderKeyReader(() => 'fake-native-key');+ const route = deriveCodexCustomProviderRoutes(catalog)[0]!;+ host.setCodexAppliedCustomProviderRoutes([route]);+ try {+ await host.ensureCodexProxyReady();+ const endpoint = host.getCodexProxyEndpoint();+ const body = {+ model: 'codex/native-model', max_tokens: 123, vendor_field: { retain: true },+ tools: [{ type: 'custom', name: 'exec', format: { type: 'text' } }],+ input: [+ { type: 'custom_tool_call', id: 'fc_legacy', call_id: 'call_same', name: 'exec', input: '你好' },+ { type: 'custom_tool_call_output', id: 'fco_legacy', call_id: 'call_same', output: 'result' },+ { type: 'item_reference', id: 'fc_server_owned' },+ { type: 'compaction', encrypted_content: 'opaque' },+ ],+ };+ const repaired = { ...body, input: body.input.map((item, index) => index < 2+ ? { ...item, id: index === 0 ? 'ctc_legacy' : 'ctco_legacy' } : item) };+ const post = async (path: string, raw: string) => {+ const response = await fetch(`${endpoint}/_cindy/custom-provider/${route.routeId}/${path}`, {+ method: 'POST', headers: { 'content-type': 'application/json' }, body: raw,+ });+ expect(response.status).toBe(200);+ await response.text();+ };+ await post('responses?native=true', JSON.stringify(body));+ expect(received[0]?.path).toBe('/v1/responses?native=true');+ expect(JSON.parse(received[0]!.body)).toEqual(repaired);+ const unchanged = JSON.stringify(repaired, null, 2);+ await post('responses', unchanged);+ expect(received[1]?.body).toBe(unchanged);+ // Even an image JSON body containing tool-shaped input remains byte-identical.+ const imageBody = JSON.stringify({ ...body, model: 'gpt-image-2', prompt: 'draw' }, null, 2);+ await post('images/generations', imageBody);+ expect(received[2]?.body).toBe(imageBody);+ } finally {+ await host.disposeCodexProxy();+ host.setCodexAppliedCustomProviderRoutes([]);+ setCustomProviderKeyReader(() => null);+ setActiveCatalog(BUNDLED_CATALOG);+ await new Promise<void>((resolve) => upstream.close(() => resolve()));+ }+ });+it('owns every private custom Provider prefix before opaque body transforms', async () => {const host = await freshCodexProxyHost();mockState.createAnthropicCompatProxy.mockResolvedValueOnce({@@ -7369,7 +7608,7 @@ describe('createModelRoutingTransform —— custom Provider native imagegen preurl: '/_cindy/custom-provider/0123456789abcdefabcd/responses',},),- ).toBe(true);+ ).toBe(false);expect(options.routeOpaqueRequestBody({url: '/_cindy/custom-provider%2F0123456789abcdefabcd%2Fimages%2Fedits',diff --git a/apps/desktop/src/main/maker-host/codex-proxy-host.ts b/apps/desktop/src/main/maker-host/codex-proxy-host.tsindex c265fdf8a3..8877581987 100644--- a/apps/desktop/src/main/maker-host/codex-proxy-host.ts+++ b/apps/desktop/src/main/maker-host/codex-proxy-host.ts@@ -41,6 +41,7 @@ import {import { buildVisionBridgeProxyTransform } from '../vision-bridge/vision-bridge-controller.js';import {createResponsesCustomToolFunctionAdapter,+ normalizeResponsesToolItemIds,createResponsesChatHandler,type ChatBridgeCapabilities,} from '@cindy/responses-chat-bridge';@@ -168,6 +169,12 @@ const _customContextStartPromises = new Map<{ authInjection: CodexProxyAuthInjection; routeSignature: string; promise: Promise<void> }>();const _customContextGenerations = new Map<string, number>();+/** Each handle owns its live thread/socket mapping, including isolated Host proxies. */+function* activeCodexProxyHandles(): Iterable<ProxyHandle> {+ if (_handle) yield _handle;+ yield* _controlPlaneHandles.values();+ for (const entry of _customContextHandles.values()) yield entry.handle;+}let _disposeGeneration = 0;let dumpSeq = 0;@@ -191,10 +198,20 @@ const CODEX_BODY_RECOVERY_RULES = [vllmResponsesCompatibilityRule,] as const;+/** Only fall back for the exact dialect mismatches the outgoing normalizer can repair. */+function isRepairableToolItemIdError(errorText: string): boolean {+ // Codex additionalDetails may contain an escaped JSON error inside another error envelope.+ const text = errorText.replace(/\\+(?=["'])/g, '');+ const match = /Invalid\s+["']input\[\d+\]\.id["']:\s*["'](fc|fco|ctc|ctco)_[^"']+["']\.?\s+Expected an ID that begins with ["'](fc|fco|ctc|ctco)_?["']/i.exec(text);+ if (!match) return false;+ return ({ fc: 'ctc', fco: 'ctco', ctc: 'fc', ctco: 'fco' } as Record<string, string>)[match[1]!]+ === match[2]!;+}+/*** WS 已建立后 proxy 只转发 socket,真正的上游请求错误会由 app-server 报给 maker-core。- * maker-core 把错误文本回传到这里,由与 HTTP recovery 完全相同的 rule 判定并登记:- * 下一次 upgrade 返回 426,Codex 原生 transport 随即切到 HTTP,既有 strip+retry 接管。+ * maker-core 把错误文本回传到这里,仅识别 HTTP recovery rule 或已知可校正的工具 ID 错配。+ * 下一次 upgrade 返回 426,Codex 原生 transport 随即切到 HTTP,由请求校正/strip 接管。*/export function armCodexHttpRecovery(args: {sessionId: string;@@ -212,7 +229,8 @@ export function armCodexHttpRecovery(args: {const rule = CODEX_BODY_RECOVERY_RULES.find((candidate) => candidate.enabled() && candidate.matches(errorText),);- if (!rule) return null;+ const reason = rule?.id ?? (isRepairableToolItemIdError(errorText) ? 'tool_item_id' : null);+ if (!reason) return null;const sessionId = args.sessionId.trim();const existingSessionId = threadToSession.get(threadId);@@ -224,8 +242,11 @@ export function armCodexHttpRecovery(args: {});return null;}- httpRecoveryReasonByThread.set(threadId, rule.id);- const disconnectedWebSockets = _handle?.disconnectWebSocketsForThread?.(threadId) ?? 0;+ httpRecoveryReasonByThread.set(threadId, reason);+ let disconnectedWebSockets = 0;+ for (const handle of activeCodexProxyHandles()) {+ disconnectedWebSockets += handle.disconnectWebSocketsForThread?.(threadId) ?? 0;+ }if (disconnectedWebSockets === 0) {httpRecoveryReasonByThread.delete(threadId);// startup-prewarm 没有稳定 thread header,且 shared app-server 会跨业务 session@@ -234,7 +255,7 @@ export function armCodexHttpRecovery(args: {log.info('codex websocket recovery left to native transport; no scoped socket found', {sessionId,threadId,- reason: rule.id,+ reason,});return null;}@@ -250,10 +271,10 @@ export function armCodexHttpRecovery(args: {log.info('codex websocket recovery fallback armed', {sessionId,threadId,- reason: rule.id,+ reason,disconnectedWebSockets,});- return rule.id;+ return reason;}// codex 走 Responses API,每轮**全量重发**整个 thread 历史;导入的存量长会话@@ -3245,6 +3266,9 @@ function createTransformRequestChain(// 注入后把纯文本模型请求 input[] 里的 input_image 转成文字描述。放在 strip 之前与// Anthropic 链一致,避免未来 strip 扩展覆盖 Responses input_image 时吃掉图。buildVisionBridgeProxyTransform(log),+ // Run after every provider dialect rewrite: xAI can also turn custom calls into functions.+ // This covers native-custom routes and tool-less /responses/compact without changing call_id.+ normalizeResponsesToolItemIds,stripNonAnthropicFields,];if (process.env.XDT_CODEX_PROXY_DUMP_TRANSFORMED_BODY === '1') {@@ -3353,9 +3377,26 @@ function createCodexProxyHandle(return createAnthropicCompatProxy({// 默认上游 = gateway(含 /v1);普通模型 + oauth 由 routingTransform 覆盖到 ChatGPT。upstream: () => buildCodexGatewayBaseUrl(),- transformRequest: createTransformRequestChain(frozenAuthInjection, execAdapter),+ transformRequest: createTransformRequestChain(frozenAuthInjection, execAdapter).map(+ (transform): RequestTransform => {+ // Namespaced Responses use a frozen Provider route. Preserve its native+ // fields and model; only repair known tool ID mismatches on this path.+ if (transform === normalizeResponsesToolItemIds) return transform;+ const scoped: RequestTransform = (body, ctx) =>+ isCodexCustomProviderNamespacePath(ctx.url) ? null : transform(body, ctx);+ // Keep adapter rejection and request-state cleanup on ordinary routes.+ scoped.errorMode = transform.errorMode;+ scoped.onRequestSettled = transform.onRequestSettled;+ return scoped;+ },+ ),routeOpaqueRequestBody: (ctx) => isCodexCustomProviderNamespacePath(ctx.url),- bypassRequestTransforms: (_body, ctx) => isCodexCustomProviderNamespacePath(ctx.url),+ bypassRequestTransforms: (_body, ctx) => {+ const path = parseCodexCustomProviderPath(ctx.url);+ // Image payloads (including JSON) retain their byte-for-byte bypass.+ return path.kind !== 'not-custom-provider-route'+ && !(path.kind === 'route' && path.pathKind === 'responses');+ },transformResponse: (ctx) => execAdapter.createResponseTransform(ctx.reqId, {contentType: ctx.responseHeaders['content-type'] ?? '',contentEncoding: ctx.responseHeaders['content-encoding'] ?? '',@@ -3822,7 +3863,9 @@ function clearSessionThreads(sessionId: string): string[] {// Session 关闭既可能是普通释放,也可能是 OAuth ↔ 第三方模型的 route 切换。// 两种情况都必须撤销旧 thread 的 WS 成功证明:第三方恢复使用 cindy_gateway/HTTP,// 迟到的旧 upgrade 不能命中本次新增的 Cindy 侧 WS 保活;其他 thread 不受影响。- _handle?.forgetWebSocketStateForThread?.(threadId);+ for (const handle of activeCodexProxyHandles()) {+ handle.forgetWebSocketStateForThread?.(threadId);+ }threadToSession.delete(threadId);registry.delete(threadId);subagentRouteByParentThread.delete(threadId);diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex a29c187535..8e4cae24c3 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -8985,8 +8985,11 @@ describe('CodexAgent MCP thread context hooks', () => {});}- it('arms HTTP fallback and retries the same zero-output turn once', async () => {- const armCodexHttpRecovery = vi.fn(() => 'encrypted_content');+ it.each([+ ['encrypted_content', ENCRYPTED_ERROR],+ ['tool_item_id', "Invalid 'input[285].id': 'fc_legacy'. Expected an ID that begins with 'ctc'."],+ ])('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 }));const host = installRecoveryHost(agent);const handle = await agent.startSession({@@ -9009,7 +9012,7 @@ describe('CodexAgent MCP thread context hooks', () => {willRetry: false,error: {message: 'Bad request',- additionalDetails: ENCRYPTED_ERROR,+ additionalDetails: recoveryError,codexErrorInfo: 'badRequest',},});@@ -9021,7 +9024,7 @@ describe('CodexAgent MCP thread context hooks', () => {turn: {id: 'turn-1',status: 'failed',- error: { message: ENCRYPTED_ERROR },+ error: { message: recoveryError },},});@@ -9035,7 +9038,7 @@ describe('CodexAgent MCP thread context hooks', () => {sessionId: 'session-ws-body-recovery',threadId: 'start-thread-id',message: 'Bad request',- additionalDetails: ENCRYPTED_ERROR,+ additionalDetails: recoveryError,});expect(events.some(@@ -9051,7 +9054,7 @@ describe('CodexAgent MCP thread context hooks', () => {turn: {id: 'turn-1',status: 'failed',- error: { message: ENCRYPTED_ERROR },+ error: { message: recoveryError },},});expect(handle.getCurrentTurnId?.()).toBe('turn-2');@@ -9370,8 +9373,11 @@ describe('CodexAgent MCP thread context hooks', () => {await handle.close();});- it('does not replay a recovery error after the turn has produced output', async () => {- const armCodexHttpRecovery = vi.fn(() => 'image_generation_id');+ it.each([+ ['image_generation_id', 'Image generation items without `id` are not supported for this request.'],+ ['tool_item_id', "Invalid 'input[285].id': 'fc_legacy'. Expected an ID that begins with 'ctc'."],+ ])('does not replay a recovery error after the turn has produced output (%s)', async (reason, recoveryError) => {+ const armCodexHttpRecovery = vi.fn(() => reason);const agent = new CodexAgent(createDeps({}, { armCodexHttpRecovery }));const host = installRecoveryHost(agent);const handle = await agent.startSession({@@ -9395,7 +9401,7 @@ describe('CodexAgent MCP thread context hooks', () => {turnId: 'turn-1',willRetry: false,error: {- message: 'Image generation items without `id` are not supported for this request.',+ message: recoveryError,codexErrorInfo: 'badRequest',},});diff --git a/packages/responses-chat-bridge/src/__tests__/custom-tool-function-adapter.test.ts b/packages/responses-chat-bridge/src/__tests__/custom-tool-function-adapter.test.tsindex b6a2130208..155e167992 100644--- a/packages/responses-chat-bridge/src/__tests__/custom-tool-function-adapter.test.ts+++ b/packages/responses-chat-bridge/src/__tests__/custom-tool-function-adapter.test.ts@@ -3,7 +3,7 @@ import type { Transform } from "node:stream";import { afterEach, describe, expect, it, vi } from "vitest";-import { createResponsesCustomToolFunctionAdapter } from "../custom-tool-function-adapter.js";+import { createResponsesCustomToolFunctionAdapter, normalizeResponsesToolItemIds } from "../custom-tool-function-adapter.js";async function collect(transform: Transform, body: string): Promise<string> {const chunks: Buffer[] = [];@@ -31,11 +31,99 @@ function execRequest() {};}+describe("legacy Responses tool item ids", () => {+ it("repairs tool-less compact history without changing invocation ids, payloads or opaque items", () => {+ const body = { model: "gpt-6", input: [+ { type: "custom_tool_call", id: "fc_old", call_id: "fc_invocation", name: "exec", input: "fc_literal" },+ { type: "custom_tool_call_output", id: "fco_old", call_id: "fc_invocation", output: [{ type: "input_text", text: "fc_literal" }] },+ { type: "function_call", id: "ctc_old2", call_id: "ctc_invocation", arguments: "{}" },+ { type: "function_call_output", id: "ctco_old2", call_id: "ctc_invocation", output: "ok" },+ { type: "item_reference", id: "fc_old" },+ { type: "compaction", id: "fc_opaque", encrypted_content: "unchanged" },+ { type: "message", id: "fc_message", content: "unchanged" },+ { type: "custom_tool_call", id: "opaque_provider", call_id: "opaque" },+ { type: "custom_tool_call", call_id: "legacy" },+ { type: "function_call", id: "fc_valid", call_id: "valid" },+ ] };+ const original = structuredClone(body);+ const repaired = normalizeResponsesToolItemIds(body)!;+ const items = repaired.input as typeof body.input;+ expect(items.map(item => item.id)).toEqual([+ "ctc_old", "ctco_old", "fc_old2", "fco_old2", "fc_old", "fc_opaque", "fc_message",+ "opaque_provider", undefined, "fc_valid",+ ]);+ expect(items[0]).toEqual({ ...body.input[0], id: "ctc_old" });+ expect(items[1]).toEqual({ ...body.input[1], id: "ctco_old" });+ expect(items[1]!.output).toBe(body.input[1]!.output);+ expect(body).toEqual(original);+ expect(normalizeResponsesToolItemIds(repaired)).toBeNull();+ expect(normalizeResponsesToolItemIds({ input: "hello" })).toBeNull();+ });+});+describe("Responses custom-tool function adapter", () => {afterEach(() => {vi.useRealTimers();});+ it.each([false, true])("keeps response ids consistent across parallel calls and final output (SSE=%s)", async (sse) => {+ const adapter = createResponsesCustomToolFunctionAdapter(["exec"]);+ adapter.adaptRequest(execRequest(), 1);+ const calls = ["a", "b"].map(key => ({+ type: "function_call", id: `fc_${key}`, call_id: `call_${key}`, name: "exec",+ arguments: JSON.stringify({ input: `text("你好 ${key}")` }),+ }));+ const unrelated = { type: "function_call", id: "fc_other", call_id: "call_other", name: "read_file", arguments: "{}" };+ const final = { type: "response.completed", response: { output: [...calls, unrelated] } };+ const events = [+ ...calls.map((item, output_index) => ({ type: "response.output_item.added", output_index, item: { ...item, arguments: "" } })),+ { type: "response.output_item.added", output_index: 2, item: unrelated },+ { type: "response.function_call_arguments.done", output_index: 2, item_id: unrelated.id, arguments: "{}" },+ ...[1, 0].flatMap(output_index => {+ const item = calls[output_index]!;+ return [+ { type: "response.function_call_arguments.delta", output_index, item_id: item.id, delta: item.arguments },+ { type: "response.function_call_arguments.done", output_index, item_id: item.id, arguments: item.arguments },+ { type: "response.output_item.done", output_index, item },+ ];+ }),+ final,+ ];+ const transform = adapter.createResponseTransform(1, { contentType: sse ? "text/event-stream" : "application/json", contentEncoding: "" })!;+ const body = sse ? events.map(event => `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`).join("") : JSON.stringify(final.response);+ const chunks: Buffer[] = [];+ transform.on("data", chunk => chunks.push(Buffer.from(chunk)));+ const completed = new Promise<void>((resolve, reject) => { transform.on("end", resolve); transform.on("error", reject); });+ // Exercise split framing and multi-byte text while two calls are in flight.+ const bytes = Buffer.from(body);+ for (let offset = 0; offset < bytes.length; offset += 7) transform.write(bytes.subarray(offset, offset + 7));+ transform.end();+ await completed;+ const output = Buffer.concat(chunks).toString("utf8");+ const rewritten = sse ? output.split("\n").filter(line => line.startsWith("data: ")).map(line => JSON.parse(line.slice(6))) : [];+ const response = sse ? rewritten.at(-1).response : JSON.parse(output);+ expect(response.output).toEqual([+ ...calls.map((call, index) => ({ type: "custom_tool_call", id: index ? "ctc_b" : "ctc_a", call_id: call.call_id, name: "exec", input: JSON.parse(call.arguments).input })),+ unrelated,+ ]);+ if (sse) {+ expect(rewritten.filter(event => event.type === "response.custom_tool_call_input.done").map(event => event.item_id)).toEqual(["ctc_b", "ctc_a"]);+ for (const event of rewritten) {+ if (event.output_index === 0 || event.output_index === 1) {+ const expected = event.output_index === 0 ? "ctc_a" : "ctc_b";+ if (event.item) expect(event.item.id).toBe(expected);+ if (event.item_id) expect(event.item_id).toBe(expected);+ }+ }+ expect(rewritten).toContainEqual(events[3]);+ }+ const compactBody = { model: "gpt-6", input: response.output };+ expect(normalizeResponsesToolItemIds(compactBody)).toBeNull();+ const adapted = adapter.adaptRequest({ ...execRequest(), input: response.output }, 2) as { input: Array<{ id: string; call_id: string }> };+ expect(adapted.input.map(item => item.id)).toEqual(["fc_a", "fc_b", "fc_other"]);+ expect(adapted.input.map(item => item.call_id)).toEqual(["call_a", "call_b", "call_other"]);+ });+it("flips dialect-coupled item id prefixes and drops ids in neither dialect", () => {const adapter = createResponsesCustomToolFunctionAdapter(["exec"]);const adapted = adapter.adaptRequest(diff --git a/packages/responses-chat-bridge/src/custom-tool-function-adapter.ts b/packages/responses-chat-bridge/src/custom-tool-function-adapter.tsindex 0c449d33d2..2a6cc995d0 100644--- a/packages/responses-chat-bridge/src/custom-tool-function-adapter.ts+++ b/packages/responses-chat-bridge/src/custom-tool-function-adapter.ts@@ -80,6 +80,43 @@ function adaptItemId(item: Record<string, unknown>): Record<string, unknown> {return next;}+/** Repair only known dialect mismatches; opaque provider ids and absent ids stay intact.+ * `call_id` identifies the invocation/result pair and must never be rewritten.+ */+function normalizeToolItemId(item: Record<string, unknown>): Record<string, unknown> {+ const prefixes: readonly [string, string] | null = item.type === 'custom_tool_call' ? ['fc_', 'ctc_']+ : item.type === 'custom_tool_call_output' ? ['fco_', 'ctco_']+ : item.type === 'function_call' ? ['ctc_', 'fc_']+ : item.type === 'function_call_output' ? ['ctco_', 'fco_'] : null;+ if (!prefixes || typeof item.id !== 'string' || !item.id.startsWith(prefixes[0])) return item;+ return { ...item, id: prefixes[1] + item.id.slice(prefixes[0].length) };+}++/**+ * Repair legacy histories on the wire, including tool-less compact requests and native-custom+ * routes. Do not rewrite the rollout, tool payloads, opaque compaction blobs or unrelated ids.+ * Return null for an unchanged body, following the proxy request-transform contract.+ */+export function normalizeResponsesToolItemIds(body: unknown): Record<string, unknown> | null {+ if (!isObject(body) || !Array.isArray(body.input)) return null;+ let changed = false;+ const input = body.input.map((item: unknown) => {+ if (!isObject(item)) return item;+ const next = normalizeToolItemId(item);+ if (next !== item) changed = true;+ return next;+ });+ // item_reference ids address server-owned stored items, not local payloads. Keep them opaque.+ return changed ? { ...body, input } : null;+}++/** SSE argument events reference the output item, not the invocation's call_id. */+function customToolEvent(event: Record<string, unknown>): Record<string, unknown> {+ return typeof event.item_id === 'string' && event.item_id.startsWith('fc_')+ ? { ...event, item_id: 'ctc_' + event.item_id.slice(3) }+ : event;+}+interface AdaptedCall {spec: ChatBridgeToolSpec;arguments: string;@@ -118,7 +155,7 @@ class CustomToolResponseTransform extends Transform {input: call?.input ?? unwrapArguments(call?.arguments ?? item.arguments),};delete next.arguments;- return next;+ return normalizeToolItemId(next);}private rewriteEvent(event: unknown): Record<string, unknown>[] | null {if (!isObject(event) || typeof event.type !== 'string') return null;@@ -149,7 +186,7 @@ class CustomToolResponseTransform extends Transform {...event.item, type: 'custom_tool_call', name: spec.name, input: '',};delete item.arguments;- return [{ ...event, item }];+ return [{ ...customToolEvent(event), item: normalizeToolItemId(item) }];}const call = this.calls.get(index);@@ -167,10 +204,10 @@ class CustomToolResponseTransform extends Transform {if (event.type === 'response.function_call_arguments.done' && call) {call.input = unwrapArguments(typeof event.arguments === 'string' ? event.arguments : call.arguments);const delta: Record<string, unknown> = {- ...event, type: 'response.custom_tool_call_input.delta', delta: call.input,+ ...customToolEvent(event), type: 'response.custom_tool_call_input.delta', delta: call.input,};const done: Record<string, unknown> = {- ...event, type: 'response.custom_tool_call_input.done', input: call.input,+ ...customToolEvent(event), type: 'response.custom_tool_call_input.done', input: call.input,};delete delta.arguments;delete done.arguments;@@ -181,7 +218,7 @@ class CustomToolResponseTransform extends Transform {if (!item) return null;this.calls.delete(index);this.responseArgumentBytes -= call ? Buffer.byteLength(call.arguments, 'utf8') : 0;- return [{ ...event, item }];+ return [{ ...customToolEvent(event), item }];}if (isObject(event.response) && Array.isArray(event.response.output)) {let changed = false;diff --git a/packages/responses-chat-bridge/src/index.ts b/packages/responses-chat-bridge/src/index.tsindex 34367c8bb5..aaab95a60a 100644--- a/packages/responses-chat-bridge/src/index.ts+++ b/packages/responses-chat-bridge/src/index.ts@@ -17,6 +17,7 @@ export {export { ChatBridgeToolContext, type ChatBridgeToolKind, type ChatBridgeToolSpec } from './tool-context.js';export {createResponsesCustomToolFunctionAdapter,+ normalizeResponsesToolItemIds,type ResponsesCustomToolFunctionAdapter,} from './custom-tool-function-adapter.js';export {