Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(desktop): 修复第三方 Responses Provider 丢失 Codex exec (#3256)

Zanebffe68140d84
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.ts
new file mode 100644
index 0000000000..11efab303e
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/codexExecFunctionAdapter.e2e.test.ts
@@ -0,0 +1,345 @@
+import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
+import { rm } from 'node:fs/promises';
+import { createServer, type Server } from 'node:http';
+import type { AddressInfo } from 'node:net';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { createAnthropicCompatProxy, type ProxyHandle } from '@cindy/anthropic-compat-proxy';
+import { createResponsesCustomToolFunctionAdapter } from '@cindy/responses-chat-bridge';
+import { afterEach, describe, expect, it } from 'vitest';
+
+import type { Logger } from '../../../../../../packages/maker-core/src/interfaces/logger.js';
+import { AppServerHost } from '../../../../../../packages/maker-core/src/agents/codex/app-server/host.js';
+import {
+ Method,
+ type ItemEnvelope,
+ type ThreadStartResponse,
+} from '../../../../../../packages/maker-core/src/agents/codex/app-server/protocol.js';
+import { createStdioTransport } from '../../../../../../packages/maker-core/src/agents/codex/app-server/stdioTransport.js';
+
+const repoRoot = path.resolve(fileURLToPath(new URL('.', import.meta.url)), '../../../../../..');
+const codexBinary = path.join(
+ repoRoot,
+ 'apps',
+ 'codex-bin',
+ `${process.platform}-${process.arch}`,
+ process.platform === 'win32' ? 'codex.exe' : 'codex',
+);
+const codexBoundaryAvailable = existsSync(codexBinary);
+const fixtureContents = 'issue-3168-real-command-result';
+
+const logger: Logger = {
+ trace: () => {},
+ debug: () => {},
+ info: () => {},
+ warn: () => {},
+ error: () => {},
+ fatal: () => {},
+ child: () => logger,
+};
+
+function sse(events: unknown[]): string {
+ return events
+ .map((event) => {
+ const type = (event as { type: string }).type;
+ return `event: ${type}\ndata: ${JSON.stringify(event)}\n\n`;
+ })
+ .join('');
+}
+
+function responseCreated(id: string): unknown {
+ return { type: 'response.created', response: { id } };
+}
+
+function responseCompleted(id: string): unknown {
+ return {
+ type: 'response.completed',
+ response: {
+ id,
+ usage: {
+ input_tokens: 0,
+ input_tokens_details: null,
+ output_tokens: 0,
+ output_tokens_details: null,
+ total_tokens: 0,
+ },
+ },
+ };
+}
+
+function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {
+ return new Promise<T>((resolve, reject) => {
+ const timer = setTimeout(
+ () => reject(new Error(`${label} timed out after ${timeoutMs}ms`)),
+ timeoutMs,
+ );
+ timer.unref?.();
+ promise.then(
+ (value) => {
+ clearTimeout(timer);
+ resolve(value);
+ },
+ (error) => {
+ clearTimeout(timer);
+ reject(error);
+ },
+ );
+ });
+}
+
+async function listen(server: Server): Promise<string> {
+ await new Promise<void>((resolve, reject) => {
+ server.once('error', reject);
+ server.listen(0, '127.0.0.1', () => {
+ server.off('error', reject);
+ resolve();
+ });
+ });
+ return `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+}
+
+describe.skipIf(!codexBoundaryAvailable)('Codex custom exec function adapter E2E', () => {
+ const cleanups: Array<() => Promise<void> | void> = [];
+
+ afterEach(async () => {
+ while (cleanups.length > 0) await cleanups.pop()?.();
+ });
+
+ it('reads a fixture through a real commandExecution and returns it without Web Search', async () => {
+ const providerRequests: Array<Record<string, unknown>> = [];
+ let execFunctionName = '';
+ const command =
+ process.platform === 'win32'
+ ? "Get-Content -LiteralPath 'issue-3168-fixture.txt' -Raw"
+ : "cat 'issue-3168-fixture.txt'";
+ const code = [
+ 'const result = typeof tools.exec_command === "function"',
+ ` ? await tools.exec_command(${JSON.stringify({ cmd: command })})`,
+ ` : await tools.shell_command(${JSON.stringify({ command })});`,
+ 'text(JSON.stringify(result));',
+ ].join('\n');
+
+ const provider = createServer(async (req, res) => {
+ const chunks: Buffer[] = [];
+ for await (const chunk of req) chunks.push(Buffer.from(chunk));
+ if (req.method !== 'POST' || !req.url?.endsWith('/responses')) {
+ res.writeHead(404).end();
+ return;
+ }
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8')) as Record<string, unknown>;
+ providerRequests.push(body);
+
+ let responseBody: string;
+ if (providerRequests.length === 1) {
+ const tools = Array.isArray(body.tools)
+ ? (body.tools as Array<Record<string, unknown>>)
+ : [];
+ const execFunction = tools.find((tool) => {
+ const parameters = tool.parameters as { required?: string[] } | undefined;
+ return tool.type === 'function' && parameters?.required?.includes('input');
+ });
+ execFunctionName = typeof execFunction?.name === 'string' ? execFunction.name : '';
+ const args = JSON.stringify({ input: code });
+ responseBody = sse([
+ responseCreated('response-1'),
+ {
+ type: 'response.output_item.added',
+ output_index: 0,
+ item: {
+ id: 'function-call-1',
+ type: 'function_call',
+ status: 'in_progress',
+ call_id: 'exec-call-1',
+ name: execFunctionName,
+ arguments: '',
+ },
+ },
+ {
+ type: 'response.function_call_arguments.done',
+ item_id: 'function-call-1',
+ output_index: 0,
+ arguments: args,
+ },
+ {
+ type: 'response.output_item.done',
+ output_index: 0,
+ item: {
+ id: 'function-call-1',
+ type: 'function_call',
+ status: 'completed',
+ call_id: 'exec-call-1',
+ name: execFunctionName,
+ arguments: args,
+ },
+ },
+ responseCompleted('response-1'),
+ ]);
+ } else if (providerRequests.length === 2) {
+ responseBody = sse([
+ responseCreated('response-2'),
+ {
+ type: 'response.output_item.done',
+ output_index: 0,
+ item: {
+ id: 'message-1',
+ type: 'message',
+ status: 'completed',
+ role: 'assistant',
+ content: [{ type: 'output_text', text: fixtureContents }],
+ },
+ },
+ responseCompleted('response-2'),
+ ]);
+ } else {
+ res.writeHead(500).end('unexpected extra Responses request');
+ return;
+ }
+
+ res.writeHead(200, { 'content-type': 'text/event-stream', connection: 'close' });
+ res.end(responseBody);
+ });
+ const providerUrl = await listen(provider);
+ cleanups.push(() => new Promise<void>((resolve) => provider.close(() => resolve())));
+
+ const adapter = createResponsesCustomToolFunctionAdapter(['exec']);
+ const proxy: ProxyHandle = await createAnthropicCompatProxy({
+ upstream: providerUrl,
+ transformRequest: [(body, ctx) => adapter.adaptRequest(body, ctx.reqId)],
+ transformResponse: (ctx) =>
+ adapter.createResponseTransform(ctx.reqId, {
+ contentType: ctx.responseHeaders['content-type'] ?? '',
+ contentEncoding: ctx.responseHeaders['content-encoding'] ?? '',
+ }),
+ });
+ cleanups.push(() => proxy.dispose());
+
+ const tempRoot = mkdtempSync(path.join(tmpdir(), 'cindy-issue-3168-e2e-'));
+ const codexHome = path.join(tempRoot, 'codex-home');
+ const workingDir = path.join(tempRoot, 'workdir');
+ mkdirSync(codexHome, { recursive: true });
+ mkdirSync(workingDir, { recursive: true });
+ writeFileSync(path.join(workingDir, 'issue-3168-fixture.txt'), fixtureContents);
+ writeFileSync(
+ path.join(codexHome, 'config.toml'),
+ `
+model = "stealth/ox-alpha"
+model_provider = "mock_provider"
+approval_policy = "never"
+sandbox_mode = "read-only"
+
+[features.code_mode]
+enabled = true
+
+[model_providers.mock_provider]
+name = "Issue 3168 loopback fake Provider"
+base_url = "${proxy.url}/v1"
+wire_api = "responses"
+request_max_retries = 0
+stream_max_retries = 0
+`,
+ );
+ cleanups.push(() =>
+ rm(tempRoot, {
+ recursive: true,
+ force: true,
+ maxRetries: 20,
+ retryDelay: 100,
+ }),
+ );
+
+ const host = new AppServerHost({
+ createTransport: () =>
+ createStdioTransport({
+ binaryPath: codexBinary,
+ cwd: workingDir,
+ env: {
+ ...process.env,
+ CODEX_HOME: codexHome,
+ OPENAI_API_KEY: 'test-key',
+ },
+ }),
+ logger,
+ clientInfo: { name: 'cindy-issue-3168-e2e', version: '0.0.0' },
+ });
+ cleanups.push(() => host.shutdown());
+
+ const thread = await withTimeout(
+ host.request<ThreadStartResponse>(
+ Method.ThreadStart,
+ {
+ model: 'stealth/ox-alpha',
+ modelProvider: 'mock_provider',
+ cwd: workingDir,
+ approvalPolicy: 'never',
+ sandbox: 'read-only',
+ },
+ { timeoutMs: 20_000 },
+ ),
+ 25_000,
+ 'thread/start',
+ );
+
+ let resolveTurnCompleted!: () => void;
+ const turnCompleted = new Promise<void>((resolve) => {
+ resolveTurnCompleted = resolve;
+ });
+ const startedItems: ItemEnvelope[] = [];
+ const completedItems: ItemEnvelope[] = [];
+ const subscription = host.subscribeThread(thread.thread.id, {
+ turnCompleted: () => resolveTurnCompleted(),
+ itemStarted: ({ item }) => startedItems.push(item),
+ itemCompleted: ({ item }) => completedItems.push(item),
+ });
+ cleanups.push(() => subscription.release());
+
+ await withTimeout(
+ host.request(
+ Method.TurnStart,
+ {
+ threadId: thread.thread.id,
+ input: [
+ { type: 'text', text: 'Read issue-3168-fixture.txt and return its exact contents.' },
+ ],
+ },
+ { timeoutMs: 20_000 },
+ ),
+ 25_000,
+ 'turn/start',
+ );
+ await withTimeout(turnCompleted, 30_000, 'turn/completed');
+
+ expect(providerRequests).toHaveLength(2);
+ const firstTools = providerRequests[0]?.tools as Array<Record<string, unknown>>;
+ expect(execFunctionName).not.toBe('');
+ expect(firstTools).toContainEqual(
+ expect.objectContaining({ type: 'function', name: execFunctionName }),
+ );
+ expect(firstTools).not.toContainEqual(
+ expect.objectContaining({ type: 'custom', name: 'exec' }),
+ );
+
+ 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',
+ );
+ expect(JSON.stringify(execOutput?.output)).toContain(fixtureContents);
+ expect(startedItems).toContainEqual(expect.objectContaining({ type: 'commandExecution' }));
+ expect(completedItems).toContainEqual(
+ expect.objectContaining({
+ type: 'commandExecution',
+ status: 'completed',
+ }),
+ );
+ expect(completedItems).toContainEqual(
+ expect.objectContaining({
+ type: 'agentMessage',
+ text: fixtureContents,
+ }),
+ );
+ expect([...startedItems, ...completedItems].some((item) => item.type === 'webSearch')).toBe(
+ false,
+ );
+ }, 45_000);
+});
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
index 36b29c3a2b..bfd50525c5 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
@@ -119,7 +119,8 @@ vi.mock('@cindy/anthropic-compat-proxy', async (importOriginal) => {
};
});
-vi.mock('@cindy/responses-chat-bridge', () => ({
+vi.mock('@cindy/responses-chat-bridge', async (importOriginal) => ({
+ ...await importOriginal<typeof import('@cindy/responses-chat-bridge')>(),
createResponsesChatHandler: mockState.createResponsesChatHandler,
}));
@@ -2396,8 +2397,15 @@ describe('codex proxy host', () => {
// upstream 是函数形态(每请求现取,model-access 下发可运行期换 endpoint);
// 断言其当前求值 = 网关 base + /v1
upstream: 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, 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]
- 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), mockState.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 未注入 → 短路透传), 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,
+ ],
+ transformResponse: expect.any(Function),
routingTransform: expect.any(Function),
recoveryRules: expect.arrayContaining([
expect.objectContaining({ id: 'encrypted_content' }),
@@ -2408,8 +2416,17 @@ describe('codex proxy host', () => {
);
const proxyOpts = mockState.createAnthropicCompatProxy.mock.calls[0][0] as {
upstream: () => string;
+ transformRequest: Array<{
+ errorMode?: 'reject-request';
+ onRequestSettled?: (requestId: number) => void;
+ }>;
};
expect(proxyOpts.upstream()).toBe(`${XD_GATEWAY_BASE_URL}/v1`);
+ const requestScopedTransforms = proxyOpts.transformRequest.filter(
+ (transform) => transform.onRequestSettled,
+ );
+ expect(requestScopedTransforms).toHaveLength(1);
+ expect(requestScopedTransforms[0]?.errorMode).toBe('reject-request');
});
it('only resolves the websocket upstream for the oauth-bearer spawn identity', async () => {
@@ -4102,43 +4119,207 @@ describe('codex proxy host', () => {
});
});
- it('removes unsupported DeepSeek V4 custom tools but retains apply_patch', async () => {
+ 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');
+ const { setCustomProviders } = await import('../active-catalog.js');
+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');
+ setCustomProviders([buildUserProvider({
+ id: 'stealth',
+ name: 'Stealth',
+ runtimes: {
+ codex: {
+ baseUrl: 'http://127.0.0.1:43168/v1',
+ wireProtocol: 'openai-responses',
+ models: [{ id: 'stealth/ox-alpha', name: 'OX Alpha' }],
+ },
+ },
+ })]);
+ host.registerComposed('session-stealth-exec', 'thread-stealth-exec', 'PRODUCT_PROMPT');
+ setSessionProvider('session-stealth-exec', 'stealth');
+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({
+ url: 'http://127.0.0.1:43210',
+ dispose: vi.fn(async () => undefined),
+ });
+ try {
+ await host.ensureCodexProxyReady();
+
+ const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];
+ let current: unknown = {
+ model: 'stealth/ox-alpha',
+ tools: [
+ { type: 'custom', name: 'exec', description: 'run a command' },
+ { type: 'custom', name: 'apply_patch', description: 'edit files' },
+ { type: 'function', name: 'read_file', parameters: { type: 'object' } },
+ ],
+ tool_choice: { type: 'custom', name: 'exec' },
+ input: [
+ { type: 'custom_tool_call', id: 'ctc_1', status: 'completed',
+ name: 'exec', call_id: 'old_call', input: 'text("old")' },
+ { type: 'custom_tool_call_output', call_id: 'old_call', output: 'old result' },
+ ],
+ };
+ const ctx = {
+ reqId: 3168,
+ method: 'POST',
+ url: '/responses',
+ headers: { 'thread-id': 'thread-stealth-exec' },
+ };
+ for (const transform of transforms) {
+ const next = transform(current, ctx);
+ if (next !== null && next !== undefined) current = next;
+ }
+
+ expect(current).toMatchObject({
+ tools: [
+ expect.objectContaining({
+ type: 'function',
+ name: 'exec',
+ description: expect.stringContaining('run a command'),
+ parameters: expect.objectContaining({ type: 'object', required: ['input'] }),
+ }),
+ { type: 'custom', name: 'apply_patch', description: 'edit files' },
+ { type: 'function', name: 'read_file', parameters: { type: 'object' } },
+ ],
+ tool_choice: { type: 'function', name: 'exec' },
+ input: [
+ expect.objectContaining({
+ type: 'function_call', id: 'ctc_1', status: 'completed', name: 'exec',
+ arguments: '{"input":"text(\\"old\\")"}',
+ }),
+ { type: 'function_call_output', call_id: 'old_call', output: 'old result' },
+ ],
+ });
+
+ const responseTransform = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformResponse({
+ reqId: 3168,
+ responseHeaders: { 'content-type': 'text/event-stream' },
+ });
+ const chunks: Buffer[] = [];
+ responseTransform.on('data', (chunk: Buffer) => chunks.push(chunk));
+ const completed = new Promise<void>((resolve, reject) => {
+ responseTransform.once('end', resolve);
+ responseTransform.once('error', reject);
+ });
+ const call = { type: 'function_call', 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,
+ arguments: '{"input":"text(\\"local\\")"}' },
+ { type: 'response.output_item.done', output_index: 0,
+ item: { ...call, arguments: '{"input":"text(\\"local\\")"}' } },
+ ].map((value) => `data: ${JSON.stringify(value)}\n\n`).join(''));
+ await completed;
+ const events = Buffer.concat(chunks).toString('utf8').split('\n')
+ .filter((line) => line.startsWith('data: ')).map((line) => JSON.parse(line.slice(6)));
+ expect(events.map((event) => event.type)).toEqual([
+ 'response.output_item.added',
+ 'response.custom_tool_call_input.delta',
+ 'response.custom_tool_call_input.done',
+ 'response.output_item.done',
+ ]);
+ expect(events[1]).toMatchObject({ item_id: 'fc_1', delta: 'text("local")' });
+ expect(events[3].item).toEqual({
+ type: 'custom_tool_call',
+ name: 'exec',
+ call_id: 'call_exec',
+ input: 'text("local")',
+ });
+ } finally {
+ host.unregister('session-stealth-exec');
+ clearSessionProvider('session-stealth-exec');
+ setCustomProviders([]);
+ }
+ });
+
+ it('adapts exec when env-key falls through a built-in OpenAI session to XD', async () => {
+ const host = await freshCodexProxyHost();
+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');
+ host.setCodexProxyAuthInjection('env-key');
mockState.createAnthropicCompatProxy.mockResolvedValueOnce({
url: 'http://127.0.0.1:43210',
dispose: vi.fn(async () => undefined),
});
await host.ensureCodexProxyReady();
+ host.registerComposed('session-openai-envkey-exec', 'thread-openai-envkey-exec', 'PRODUCT_PROMPT');
+ setSessionProvider('session-openai-envkey-exec', 'openai');
- const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];
- let current: unknown = {
- model: 'deepseek/deepseek-v4-pro',
- tools: [
- 'exec',
- 'apply_patch',
- { type: 'custom', name: 'exec', description: 'run a command' },
- { type: 'custom', name: 'apply_patch', description: 'edit files' },
- { type: 'function', name: 'read_file', parameters: { type: 'object' } },
- ],
- tool_choice: { type: 'custom', name: 'exec' },
- input: 'review this file',
- };
- const ctx = { method: 'POST', url: '/responses', headers: {} };
- for (const transform of transforms) {
- const next = transform(current, ctx);
- if (next !== null && next !== undefined) current = next;
+ try {
+ const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];
+ let current: unknown = {
+ model: 'gpt-5.5',
+ tools: [
+ { type: 'custom', name: 'exec', description: 'run a command' },
+ { type: 'function', name: 'read_file', parameters: { type: 'object' } },
+ ],
+ tool_choice: { type: 'custom', name: 'exec' },
+ };
+ const ctx = {
+ reqId: 3262,
+ method: 'POST',
+ url: '/responses',
+ headers: { 'thread-id': 'thread-openai-envkey-exec' },
+ };
+ for (const transform of transforms) {
+ const next = transform(current, ctx);
+ if (next !== null && next !== undefined) current = next;
+ }
+
+ expect(current).toMatchObject({
+ tools: [
+ expect.objectContaining({
+ type: 'function',
+ name: 'exec',
+ parameters: expect.objectContaining({ required: ['input'] }),
+ }),
+ { type: 'function', name: 'read_file', parameters: { type: 'object' } },
+ ],
+ tool_choice: expect.objectContaining({ type: 'function' }),
+ });
+ } finally {
+ host.unregister('session-openai-envkey-exec');
+ clearSessionProvider('session-openai-envkey-exec');
}
+ });
- expect(current).toEqual({
- model: 'deepseek/deepseek-v4-pro',
- tools: [
- 'apply_patch',
- { type: 'custom', name: 'apply_patch', description: 'edit files' },
- { type: 'function', name: 'read_file', parameters: { type: 'object' } },
- ],
- tool_choice: 'auto',
- input: 'review this file',
+ it('keeps native exec when oauth-bearer adopts the built-in OpenAI session', async () => {
+ const host = await freshCodexProxyHost();
+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');
+ host.setCodexProxyAuthInjection('oauth-bearer');
+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({
+ url: 'http://127.0.0.1:43210',
+ dispose: vi.fn(async () => undefined),
});
+ await host.ensureCodexProxyReady();
+ host.registerComposed('session-openai-oauth-exec', 'thread-openai-oauth-exec', 'PRODUCT_PROMPT');
+ setSessionProvider('session-openai-oauth-exec', 'openai');
+
+ try {
+ const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];
+ let current: unknown = {
+ model: 'gpt-5.5',
+ tools: [{ type: 'custom', name: 'exec', description: 'run a command' }],
+ tool_choice: { type: 'custom', name: 'exec' },
+ };
+ const ctx = {
+ reqId: 3263,
+ method: 'POST',
+ url: '/responses',
+ headers: { 'thread-id': 'thread-openai-oauth-exec' },
+ };
+ for (const transform of transforms) {
+ const next = transform(current, ctx);
+ if (next !== null && next !== undefined) current = next;
+ }
+
+ expect(current).toMatchObject({
+ tools: [{ type: 'custom', name: 'exec' }],
+ tool_choice: { type: 'custom', name: 'exec' },
+ });
+ } finally {
+ host.unregister('session-openai-oauth-exec');
+ clearSessionProvider('session-openai-oauth-exec');
+ }
});
it('keeps parallel strict-gateway tool calls grouped before their matched outputs', async () => {
@@ -5441,7 +5622,7 @@ describe('codex proxy host', () => {
await host.ensureCodexProxyReady();
const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];
- expect(transforms).toHaveLength(20); // encrypted activeStrip, image generation activeStrip, provider-aware Guardian reviewer, locked Subagent route, instructions 注入, locked Subagent exec guard, Gateway 原生 web_search, 跨来源压缩块兼容, xAI ModelInput activeStrip, 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(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
const 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.ts
index 61ca8ebbf4..f5d78996a1 100644
--- a/apps/desktop/src/main/maker-host/codex-proxy-host.ts
+++ b/apps/desktop/src/main/maker-host/codex-proxy-host.ts
@@ -37,6 +37,7 @@ import {
} from '@cindy/anthropic-compat-proxy';
import { buildVisionBridgeProxyTransform } from '../vision-bridge/vision-bridge-controller.js';
import {
+ createResponsesCustomToolFunctionAdapter,
createResponsesChatHandler,
type ChatBridgeCapabilities,
} from '@cindy/responses-chat-bridge';
@@ -1944,6 +1945,59 @@ function createXaiResponsesCompatTransform(): RequestTransform {
};
}
+function needsExecFunctionAdapter(
+ body: Record<string, unknown>,
+ ctx: RequestTransformCtx,
+ frozenAuthInjection?: CodexProxyAuthInjection,
+): boolean {
+ const requestModel = typeof body.model === 'string' ? body.model : '';
+ const providerContext = providerContextForRequest(ctx.headers, requestModel);
+ const authInjection = frozenAuthInjection ?? getCodexProxyAuthInjection();
+ const implicitProviderId = inferProviderIdForModel(requestModel, 'codex');
+ let routing: ReturnType<typeof getProviderRoutingDescriptor> = null;
+
+ if (providerContext.subagentRoute) {
+ routing = getProviderRoutingDescriptor(
+ providerContext.subagentRoute.providerId,
+ 'codex',
+ providerContext.subagentRoute.catalogModel,
+ );
+ } else if (providerContext.providerId) {
+ // A built-in provider recorded on the session is not necessarily the
+ // provider that receives the request. In env-key mode, for example, the
+ // built-in OpenAI session still falls through to the default XD gateway.
+ // Compatibility transforms must inspect that same effective route rather
+ // than the session's stale provider label.
+ const adopted = explicitProviderRouteIsAdopted(
+ providerContext.sessionId,
+ undefined,
+ authInjection,
+ );
+ routing = adopted
+ ? getSessionRoutingDescriptor(providerContext.sessionId!, 'codex', requestModel)
+ : getProviderRoutingDescriptor('xd', 'codex', requestModel);
+ } else if (implicitProviderId) {
+ // Only implicit provider-oauth routes are adopted without a session. A
+ // user/API-key provider merely sharing a model id does not win routing.
+ const inferred = getProviderRoutingDescriptor(implicitProviderId, 'codex', requestModel);
+ routing = inferred?.authStrategy === 'provider-oauth-header' ? inferred : null;
+ }
+
+ if (!routing) {
+ // Mirror decideCodexRoute's default destination: oauth-bearer regular
+ // models stay on ChatGPT, while env-key/provider-oauth and codex/* models
+ // use the XD gateway's Responses compatibility contract.
+ const defaultProviderId =
+ authInjection === 'oauth-bearer' && gatewayProviderIdForRewrittenModel(requestModel) === null
+ ? 'openai'
+ : 'xd';
+ routing = getProviderRoutingDescriptor(defaultProviderId, 'codex', requestModel);
+ }
+
+ return (routing?.wireProtocol ?? 'openai-responses') === 'openai-responses'
+ && routing?.supportsResponsesCustomTools === false;
+}
+
/**
* The XD Gateway claims this wire model for its codex routing when the active
* catalog exposes it under `xd.models.codex`. We use the catalog membership
@@ -2607,7 +2661,16 @@ export function createModelRoutingTransform(
function createTransformRequestChain(
frozenAuthInjection?: CodexProxyAuthInjection,
+ execAdapter = createResponsesCustomToolFunctionAdapter(['exec']),
): RequestTransform[] {
+ const execFunctionAdapterTransform: RequestTransform = (body, ctx) =>
+ isPlainObject(body) && needsExecFunctionAdapter(body, ctx, frozenAuthInjection)
+ ? execAdapter.adaptRequest(body, ctx.reqId)
+ : null;
+ execFunctionAdapterTransform.errorMode = 'reject-request';
+ execFunctionAdapterTransform.onRequestSettled = (requestId) => {
+ execAdapter.releaseResponse(requestId);
+ };
const transforms: RequestTransform[] = [
createActiveStripTransform({
controller: encryptedStripController,
@@ -2640,6 +2703,10 @@ function createTransformRequestChain(
enabled: () => true,
strip: sanitizeXaiModelInputFromBody,
}),
+ // Providers that explicitly lack Responses custom tools still accept ordinary
+ // functions. Adapt before provider sanitizers, then restore custom_tool_call
+ // events on the matching response stream.
+ execFunctionAdapterTransform,
createStrictGatewayHistoryCompatTransform(),
// Gateway / LiteLLM / 自定义 grok 不走 xAI 订阅 transform,但仍必须在
// ModelInput deserialize 前洗 input[]。订阅直连那条会再洗一次(幂等)。
@@ -2757,10 +2824,15 @@ export function withCodexUpstreamRecording(
function createCodexProxyHandle(
frozenAuthInjection?: CodexProxyAuthInjection,
): Promise<ProxyHandle> {
+ const execAdapter = createResponsesCustomToolFunctionAdapter(['exec']);
return createAnthropicCompatProxy({
// 默认上游 = gateway(含 /v1);普通模型 + oauth 由 routingTransform 覆盖到 ChatGPT。
upstream: () => buildCodexGatewayBaseUrl(),
- transformRequest: createTransformRequestChain(frozenAuthInjection),
+ transformRequest: createTransformRequestChain(frozenAuthInjection, execAdapter),
+ transformResponse: (ctx) => execAdapter.createResponseTransform(ctx.reqId, {
+ contentType: ctx.responseHeaders['content-type'] ?? '',
+ contentEncoding: ctx.responseHeaders['content-encoding'] ?? '',
+ }),
// 常规 session proxy 继续读取当前全局 spawn 形态;control-plane proxy 在创建时
// 冻结自己的形态,两个 app-server 并行时不会互相改写路由。
routingTransform: withCodexUpstreamRecording(
diff --git a/packages/anthropic-compat-proxy/src/index.ts b/packages/anthropic-compat-proxy/src/index.ts
index 0216397a20..a24e7286a8 100644
--- a/packages/anthropic-compat-proxy/src/index.ts
+++ b/packages/anthropic-compat-proxy/src/index.ts
@@ -88,6 +88,7 @@ export type {
ResponseObserver,
ResponseObserverCtx,
ResponseObserverSink,
+ ResponseTransform,
RequestTransform,
RequestTransformCtx,
RoutingDecision,
diff --git a/packages/anthropic-compat-proxy/src/server.test.ts b/packages/anthropic-compat-proxy/src/server.test.ts
index 5d27a9c447..5a6369ad80 100644
--- a/packages/anthropic-compat-proxy/src/server.test.ts
+++ b/packages/anthropic-compat-proxy/src/server.test.ts
@@ -6,6 +6,7 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { gzipSync } from 'node:zlib';
import { EventEmitter } from 'node:events';
+import { Transform } from 'node:stream';
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
@@ -29,7 +30,7 @@ import {
import { createXaiModelInputRecoveryRule } from './xai-model-input.js';
import { listenOnAvailableLoopbackPort } from './test-loopback-server.js';
import { createThreadStripController } from './thread-strip-controller.js';
-import type { ProxyHandle } from './types.js';
+import type { ProxyHandle, RequestTransform } from './types.js';
const TEST_REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');
const TEST_PI_BINARY = path.join(
@@ -142,6 +143,140 @@ describe('anthropic-compat-proxy loopback port guard', () => {
expect(result).toEqual({ status: 200, text: JSON.stringify({ ok: true }) });
});
+ it('pipes successful response bodies through a request-scoped transform', async () => {
+ const upstream = await startFakeUpstream((_idx, _body, res) => {
+ const payload = '{"source":"upstream"}';
+ res.writeHead(200, {
+ 'content-type': 'application/json', 'content-length': String(payload.length),
+ }).end(payload);
+ });
+ upstreamClose = upstream.close;
+ let requestBody = '';
+
+ proxy = await createAnthropicCompatProxy({
+ upstream: upstream.url,
+ transformRequest: [(body) => ({ ...(body as object), routed: true })],
+ transformResponse: (ctx) => {
+ requestBody = ctx.requestBody.toString('utf8');
+ return new Transform({
+ transform(chunk, _encoding, callback) {
+ callback(null, String(chunk).replace('upstream', 'adapted-provider'));
+ },
+ });
+ },
+ });
+
+ const response = await fetch(`${proxy.url}/v1/responses`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' }, body: '{"model":"test-model"}',
+ });
+ expect(await response.json()).toEqual({ source: 'adapted-provider' });
+ expect(response.headers.get('content-length')).toBeNull();
+ expect(JSON.parse(requestBody)).toEqual({ model: 'test-model', routed: true });
+ });
+
+ it('settles request-scoped transform state after a non-2xx response', async () => {
+ const upstream = await startFakeUpstream((_idx, _body, res) => {
+ res.writeHead(503, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ error: { type: 'provider_unavailable' } }));
+ });
+ upstreamClose = upstream.close;
+ const onRequestSettled = vi.fn();
+ const requestTransform: RequestTransform = (body) => body;
+ requestTransform.onRequestSettled = onRequestSettled;
+
+ proxy = await createAnthropicCompatProxy({
+ upstream: upstream.url,
+ transformRequest: [requestTransform],
+ });
+
+ const response = await post(proxy.url, { model: 'test-model' });
+
+ expect(response.status).toBe(503);
+ expect(onRequestSettled).toHaveBeenCalledOnce();
+ expect(onRequestSettled).toHaveBeenCalledWith(1);
+ });
+
+ it('settles request-scoped transform state when the client closes during an async transform', async () => {
+ const upstream = await startFakeUpstream((_idx, _body, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' }).end('{}');
+ });
+ upstreamClose = upstream.close;
+ let resolveTransform!: () => void;
+ let markTransformStarted!: () => void;
+ const transformStarted = new Promise<void>((resolve) => {
+ markTransformStarted = resolve;
+ });
+ const transformReleased = new Promise<void>((resolve) => {
+ resolveTransform = resolve;
+ });
+ const onRequestSettled = vi.fn();
+ const requestTransform: RequestTransform = async (body) => {
+ markTransformStarted();
+ await transformReleased;
+ return body;
+ };
+ requestTransform.onRequestSettled = onRequestSettled;
+ proxy = await createAnthropicCompatProxy({
+ upstream: upstream.url,
+ transformRequest: [requestTransform],
+ });
+
+ const controller = new AbortController();
+ const response = fetch(`${proxy.url}/v1/responses`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: '{"model":"test-model"}',
+ signal: controller.signal,
+ }).catch(() => null);
+ await transformStarted;
+ controller.abort();
+ await response;
+ expect(onRequestSettled).not.toHaveBeenCalled();
+
+ resolveTransform();
+ await vi.waitFor(() => expect(onRequestSettled).toHaveBeenCalledOnce());
+ expect(onRequestSettled).toHaveBeenCalledWith(1);
+ });
+
+ it('fails the client when a response transform rejects during async flush', async () => {
+ const upstream = await startFakeUpstream((_idx, _body, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end('{"ok":true}');
+ });
+ upstreamClose = upstream.close;
+ proxy = await createAnthropicCompatProxy({
+ upstream: upstream.url,
+ transformRequest: [],
+ transformResponse: () => new Transform({
+ transform(chunk, _encoding, callback) {
+ callback(null, chunk);
+ },
+ flush(callback) {
+ setImmediate(() => callback(new Error('response transform flush failed')));
+ },
+ }),
+ });
+
+ const controller = new AbortController();
+ const resultPromise = fetch(`${proxy.url}/v1/responses`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: '{"model":"test-model"}',
+ signal: controller.signal,
+ }).then(async (response) => {
+ await response.text();
+ return 'resolved' as const;
+ }).catch(() => 'rejected' as const);
+ const result = await Promise.race([
+ resultPromise,
+ new Promise<'timeout'>((resolve) => setTimeout(() => resolve('timeout'), 1_000)),
+ ]);
+ controller.abort();
+
+ expect(result).toBe('rejected');
+ });
+
it('jumps out of a Windows excluded-port range after EACCES and cleans listeners', async () => {
const attemptedPorts: number[] = [];
let boundPort = 0;
@@ -1457,6 +1592,29 @@ describe('anthropic-compat-proxy mixed sync+async transform chain', () => {
// 抛错的 async transform 被跳过,后续 sync transform 照常执行。
expect(JSON.parse(custom.bodies[0]).survived).toBe(true);
});
+
+ it('rejects locally when a fail-closed request transform throws', async () => {
+ const custom = await startFakeUpstream((_i, _body, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end('{}');
+ });
+ upstreamClose = custom.close;
+ const rejectingTransform: RequestTransform = () => {
+ throw new Error('request cannot be adapted safely');
+ };
+ rejectingTransform.errorMode = 'reject-request';
+
+ proxy = await createAnthropicCompatProxy({
+ upstream: custom.url,
+ transformRequest: [rejectingTransform],
+ });
+
+ const response = await post(proxy.url, { model: 'original', input: [] });
+
+ expect(response.status).toBe(502);
+ expect(JSON.parse(response.text)).toMatchObject({ error: { type: 'proxy_error' } });
+ expect(custom.bodies).toHaveLength(0);
+ });
});
// 跨厂商切回 Anthropic 模型: 历史里 gpt 留下的空壳 thinking 块 + 后面一句 text。
diff --git a/packages/anthropic-compat-proxy/src/server.ts b/packages/anthropic-compat-proxy/src/server.ts
index 8185ffa121..4a057b6877 100644
--- a/packages/anthropic-compat-proxy/src/server.ts
+++ b/packages/anthropic-compat-proxy/src/server.ts
@@ -3,7 +3,7 @@
*
* 设计要点 / 性能保证:
* 1. 监听 127.0.0.1 随机端口,避开 Fetch 禁用端口,纯进程内 loopback,不暴露任何外部接口
- * 2. 响应路径: 字节级 pipe,完全不解析(SSE 流式响应低延迟的命脉)
+ * 2. 响应路径默认字节级 pipe;只有显式协议适配器会进入流式 Transform
* 3. 请求路径:
* - 非 POST / Content-Type 不是 JSON → 整条字节透传
* - JSON POST → 缓冲到完整 body,跑 transform 链,re-serialize 后转发
@@ -16,6 +16,7 @@
import { createServer, request as httpRequest, type ClientRequest, type IncomingMessage, type RequestOptions, type Server, type ServerResponse } from 'node:http';
import { request as httpsRequest } from 'node:https';
import type { Socket, TcpSocketConnectOpts } from 'node:net';
+import type { Transform } from 'node:stream';
import { URL } from 'node:url';
import { brotliDecompressSync, gunzipSync, inflateRawSync, inflateSync } from 'node:zlib';
@@ -49,6 +50,7 @@ import type {
RequestTransformCtx,
ResponseObserver,
ResponseObserverSink,
+ ResponseTransform,
RoutingDecision,
} from './types.js';
@@ -563,7 +565,7 @@ function respondRequestTooLarge(opts: {
}
/**
- * 跑 transform 链。任一 transform 抛错 → 返回 null(走透传保命)。
+ * 跑 transform 链。transform 默认抛错时跳过;显式标记 reject-request 时中止请求。
* 所有 transform 都返回 null → 也返回 null(透传)。
* 至少一个 transform 改了 body → 返回最新的 body。
*
@@ -600,6 +602,7 @@ async function runTransforms(
mutated = true;
}
} catch (err) {
+ if (t.errorMode === 'reject-request') throw err;
logger.warn?.('transform threw, skipping it', { err: String(err) });
}
}
@@ -765,6 +768,7 @@ function forward(
// 转发前从 outbound headers 删除的字段(大小写不敏感)。在 headerOverride 合并之后应用。
headerDelete?: readonly string[],
responseObserver?: ResponseObserver,
+ transformResponse?: ResponseTransform,
// 原始客户端 model id。provider transform 可能在出站前去掉命名空间;recovery
// controller 必须记原值,才能和下一轮主动 strip 看到的入站 model 对上。
clientModel = '',
@@ -877,6 +881,11 @@ function forward(
// upstreamReq.error 或 upstreamRes.error。request 侧通过这个回调汇入当前
// response 的终态处理,保证 observer 与下游收口语义不受事件先后影响。
let failActiveResponse: ((err: unknown) => void) | null = null;
+ // upstreamRes emits `end` before a request-scoped response Transform finishes
+ // its _flush. Keep those downstream transforms pending so an async flush
+ // error can still fail the client instead of being mistaken for a harmless
+ // post-end event.
+ const pendingResponseTransforms = new Set<Transform>();
const finishClientAfterUpstreamFailure = (
err: Error,
@@ -1041,6 +1050,7 @@ function forward(
headerOverride,
headerDelete,
responseObserver,
+ transformResponse,
clientModel,
outboundProxy,
pathOverride,
@@ -1155,7 +1165,10 @@ function forward(
reason: 'error' | 'aborted' | 'close',
rawError?: unknown,
): void => {
- if (upstreamResponseTerminal !== null) return;
+ const isPendingTransformFailure =
+ upstreamResponseTerminal === 'end' && pendingResponseTransforms.size > 0;
+ if (upstreamResponseTerminal !== null && !isPendingTransformFailure) return;
+ if (isPendingTransformFailure) pendingResponseTransforms.clear();
upstreamResponseTerminal = reason;
// 客户端主动停止是预期的取消路径,不应再通知 observer 为上游故障。
if (clientAborted || clientRes.destroyed) return;
@@ -1181,6 +1194,33 @@ function forward(
};
failActiveResponse = (err) => failStreamingResponse('error', err);
+ let responseBodyTransform: Transform | null = null;
+ if (transformResponse && status >= 200 && status < 300) {
+ try {
+ responseBodyTransform = transformResponse({
+ reqId,
+ method,
+ url: path,
+ upstreamBase: formatUpstreamBase(actualTarget),
+ status,
+ requestHeaders: headers,
+ outboundHeaders: actualHeaders,
+ responseHeaders: flattenResponseHeaders(upstreamRes.headers),
+ requestBody: body,
+ }) ?? null;
+ } catch (err) {
+ const responseError = err instanceof Error ? err : new Error(String(err));
+ observerError(responseError);
+ upstreamRes.resume();
+ finishClientAfterUpstreamFailure(
+ responseError,
+ `upstream response cannot be adapted safely: ${String(err)}`,
+ 'response_transform_unavailable',
+ );
+ return;
+ }
+ }
+
// kimi 撞车 id 的响应流改名(仅当请求历史带铸造形态 id 且响应是 SSE 才接管;
// 否则保持字节级 pipe,与扩展前一致)。observer 仍吃上游原始字节(计数/错误体
// 收集语义不变),CLI 客户端拿到的是改名后的流。
@@ -1239,6 +1279,10 @@ function forward(
toolUseIdRewrite = new ToolUseIdRewriteTransform(rewriter);
toolUseIdRewrite.on('error', (err) => failStreamingResponse('error', err));
}
+ if (responseBodyTransform) {
+ delete respHeaders['content-length'];
+ responseBodyTransform.on('error', (err) => failStreamingResponse('error', err));
+ }
// ── 流式请求的成功响应有效性门(#2242)──────────────────────────────
// 请求显式声明 stream:true 时,2xx 响应不再「先 writeHead 再 pipe」:上游或
@@ -1262,18 +1306,26 @@ function forward(
if (streamGateCommitted) return;
streamGateCommitted = true;
clientRes.writeHead(status, upstreamRes.statusMessage, respHeaders);
- const dest = toolUseIdRewrite ?? clientRes;
+ const responseTransforms = [responseBodyTransform, toolUseIdRewrite]
+ .filter((value): value is Transform => value !== null);
+ for (const transform of responseTransforms) {
+ pendingResponseTransforms.add(transform);
+ const settle = () => pendingResponseTransforms.delete(transform);
+ transform.once('end', settle);
+ }
+ const dest = responseTransforms[0] ?? clientRes;
// 门控期间积累的待发字节(非门控路径恒为空)先写出,再切回字节级 pipe ——
// pipe 是 SSE 零延迟的命脉('data' 监听只做计数+错误体收集,不影响流)。
for (const chunk of pendingChunks) dest.write(chunk);
pendingChunks.length = 0;
pendingText = '';
- if (toolUseIdRewrite) {
+ if (responseTransforms.length > 0) {
// 客户端断开 / 上游故障收口时把 transform 一并拆掉,避免上游继续灌进无消费者的流。
- const rewriteStream = toolUseIdRewrite;
- clientRes.on('close', () => rewriteStream.destroy());
- upstreamRes.pipe(rewriteStream);
- rewriteStream.pipe(clientRes);
+ clientRes.on('close', () => responseTransforms.forEach((transform) => transform.destroy()));
+ upstreamRes.pipe(responseTransforms[0]);
+ for (let index = 0; index < responseTransforms.length; index += 1) {
+ responseTransforms[index].pipe(responseTransforms[index + 1] ?? clientRes);
+ }
} else {
upstreamRes.pipe(clientRes);
}
@@ -1606,7 +1658,29 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Pr
const server: Server = createServer(async (req, res) => {
inflight++;
const reqId = ++reqIdSeq;
- res.on('close', () => { inflight--; });
+ let responseSettled = false;
+ let transformsCompleted = false;
+ let transformSettlementNotified = false;
+ const notifyTransformSettlement = (): void => {
+ if (!responseSettled || !transformsCompleted || transformSettlementNotified) return;
+ transformSettlementNotified = true;
+ for (const transform of transforms) {
+ try {
+ transform.onRequestSettled?.(reqId);
+ } catch (err) {
+ logger.warn?.('request transform settlement hook threw', { reqId, err: String(err) });
+ }
+ }
+ };
+ const markResponseSettled = (): void => {
+ responseSettled = true;
+ notifyTransformSettlement();
+ };
+ res.once('finish', markResponseSettled);
+ res.once('close', () => {
+ inflight--;
+ markResponseSettled();
+ });
const method = req.method ?? 'GET';
const url = req.url ?? '/';
@@ -1668,6 +1742,7 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Pr
route.headerOverride,
route.headerDelete,
opts.responseObserver,
+ opts.transformResponse,
'',
await resolveOutboundForTarget(route.target, reqId),
route.pathOverride,
@@ -1780,7 +1855,24 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Pr
...requestCtx,
upstreamBase: formatUpstreamBase(route.target),
};
- const transformed = await runTransforms(rawBody, contentType, transforms, transformCtx, logger);
+ let transformed: Buffer | null;
+ try {
+ transformed = await runTransforms(rawBody, contentType, transforms, transformCtx, logger);
+ } catch (err) {
+ transformsCompleted = true;
+ notifyTransformSettlement();
+ logger.warn?.('request transform rejected request', { reqId, err: String(err) });
+ res.writeHead(502, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({
+ error: {
+ type: 'proxy_error',
+ message: 'request could not be transformed safely',
+ },
+ }));
+ return;
+ }
+ transformsCompleted = true;
+ notifyTransformSettlement();
const outBody = transformed ?? rawBody;
let parsedForRewrite: unknown = rawParsed;
@@ -1864,6 +1956,7 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Pr
route.headerOverride,
route.headerDelete,
opts.responseObserver,
+ opts.transformResponse,
extractBodyModel(rawBody),
await resolveOutboundForTarget(route.target, reqId),
route.pathOverride,
diff --git a/packages/anthropic-compat-proxy/src/types.ts b/packages/anthropic-compat-proxy/src/types.ts
index 7928029cdb..576862eb1c 100644
--- a/packages/anthropic-compat-proxy/src/types.ts
+++ b/packages/anthropic-compat-proxy/src/types.ts
@@ -4,13 +4,14 @@
* 设计要点:
* - 请求 transform 是数组,按顺序串联,任一返回 null 表示"我不动这条",继续下一个
* 或者最终走字节透传(整条 JSON 全程不解析,延迟 0)
- * - 响应不开 transform —— 流式 SSE 一旦 parse/改写就丧失低延迟,代价不值;
- * 只提供可选 observer 做只读 tee,默认关闭
+ * - 响应默认字节透传;协议兼容场景可显式注入 request-scoped Transform,
+ * observer 仍只做只读 tee
* - logger 全可选,host 不传就静默(包本身永远不 console.log)
*/
import type { Buffer } from "node:buffer";
import type { ServerResponse } from "node:http";
+import type { Transform } from "node:stream";
import type { OutboundProxyResolver } from "./outbound-proxy.js";
@@ -45,10 +46,22 @@ export interface RequestTransformCtx {
* - 新的 body 对象 → 代理用它替换原 body 转发上游
* - null → 不改写,这一步跳过(还会继续跑后续 transform;全部跳过则字节透传)
*/
-export type RequestTransform = (
- body: unknown,
- ctx: RequestTransformCtx,
-) => unknown | null | Promise<unknown | null>;
+export interface RequestTransform {
+ (
+ body: unknown,
+ ctx: RequestTransformCtx,
+ ): unknown | null | Promise<unknown | null>;
+ /**
+ * Error handling for this transform. The default keeps the historical fail-open behavior;
+ * transforms that must not expose their unadapted input upstream can reject the request.
+ */
+ errorMode?: 'reject-request';
+ /**
+ * Optional cleanup for request-scoped state created while evaluating this transform.
+ * Called once after a request that entered the transform chain finishes or closes.
+ */
+ onRequestSettled?: (requestId: number) => void;
+}
/**
* 本地 handler —— 路由决策命中 `localHandler` 时,代理**不转发上游**,由 handler 直接消费
@@ -151,6 +164,9 @@ export type ResponseObserver = (
ctx: ResponseObserverCtx,
) => ResponseObserverSink | null | undefined | void;
+/** 请求级响应体改写;null 保持零拷贝,Transform 仍由代理统一收口生命周期与 headers。 */
+export type ResponseTransform = (ctx: ResponseObserverCtx) => Transform | null | undefined;
+
/**
* 一条 400 透明重试规则。
*
@@ -234,6 +250,8 @@ export interface ProxyOptions {
* 不能改写响应或阻塞流式 pipe。
*/
responseObserver?: ResponseObserver;
+ /** 可选响应体 transform 工厂。默认关闭,响应字节原样透传。 */
+ transformResponse?: ResponseTransform;
/** 可选 logger,不传则静默 */
logger?: ProxyLogger;
/**
diff --git a/packages/model-providers/catalog/providers.json b/packages/model-providers/catalog/providers.json
index 38224fa988..544d532bd1 100644
--- a/packages/model-providers/catalog/providers.json
+++ b/packages/model-providers/catalog/providers.json
@@ -44,6 +44,7 @@
"codex": {
"upstream": "https://api.x.ai/v1",
"authStrategy": "provider-oauth-header",
+ "supportsResponsesCustomTools": false,
"modelIdRewrite": {
"stripPrefix": "xai/"
},
diff --git a/packages/model-providers/src/__tests__/catalog.test.ts b/packages/model-providers/src/__tests__/catalog.test.ts
index f9995138c8..5b546f9690 100644
--- a/packages/model-providers/src/__tests__/catalog.test.ts
+++ b/packages/model-providers/src/__tests__/catalog.test.ts
@@ -181,6 +181,12 @@ describe('bundled catalog validity (dynamic-first contract)', () => {
}
});
+ it('declares native Responses custom-tool support on each built-in Codex Responses route', () => {
+ expect(provider('openai').routing.codex?.supportsResponsesCustomTools).toBe(true);
+ expect(provider('xd').routing.codex?.supportsResponsesCustomTools).toBe(false);
+ expect(provider('xai').routing.codex?.supportsResponsesCustomTools).toBe(false);
+ });
+
it('declares access separately from model names', () => {
expect(provider('anthropic').access).toEqual({ kind: 'subscription', product: 'Claude.ai' });
expect(provider('openai').access).toEqual({ kind: 'subscription', product: 'ChatGPT' });
diff --git a/packages/model-providers/src/__tests__/source-registry.test.ts b/packages/model-providers/src/__tests__/source-registry.test.ts
index f9bd91eb58..4e17d8571f 100644
--- a/packages/model-providers/src/__tests__/source-registry.test.ts
+++ b/packages/model-providers/src/__tests__/source-registry.test.ts
@@ -461,6 +461,61 @@ describe('mergeWithBundled', () => {
).toBeUndefined();
});
+ it('旧目录在官方 Codex 路由未声明 custom tool 能力时继承 bundled 能力', () => {
+ const oldProviders = BUNDLED_CATALOG.providers.map((provider) => {
+ const oldProvider = structuredClone(provider);
+ if (oldProvider.routing.codex) {
+ delete oldProvider.routing.codex.supportsResponsesCustomTools;
+ }
+ return oldProvider;
+ });
+
+ const merged = mergeWithBundled({ version: '2', providers: oldProviders });
+
+ expect(merged.providers.find((provider) => provider.id === 'openai')
+ ?.routing.codex?.supportsResponsesCustomTools).toBe(true);
+ expect(merged.providers.find((provider) => provider.id === 'xai')
+ ?.routing.codex?.supportsResponsesCustomTools).toBe(false);
+ expect(merged.providers.find((provider) => provider.id === 'xd')
+ ?.routing.codex?.supportsResponsesCustomTools).toBe(false);
+
+ const explicitOpenai = structuredClone(
+ oldProviders.find((provider) => provider.id === 'openai')!,
+ );
+ explicitOpenai.routing.codex!.supportsResponsesCustomTools = false;
+ expect(mergeWithBundled({ version: '2', providers: [explicitOpenai] })
+ .providers.find((provider) => provider.id === 'openai')
+ ?.routing.codex?.supportsResponsesCustomTools).toBe(false);
+ });
+
+ it('不为改变鉴权或 upstream 的同名 Provider 猜测 custom tool 能力', () => {
+ const bundledOpenai = structuredClone(
+ BUNDLED_CATALOG.providers.find((provider) => provider.id === 'openai')!,
+ );
+ delete bundledOpenai.routing.codex!.supportsResponsesCustomTools;
+ const apiKeyOpenai: Provider = {
+ ...bundledOpenai,
+ auth: { method: 'apiKey' },
+ };
+ const reroutedOpenai: Provider = {
+ ...bundledOpenai,
+ routing: {
+ ...bundledOpenai.routing,
+ codex: {
+ ...bundledOpenai.routing.codex!,
+ upstream: 'https://responses.example.test/v1',
+ },
+ },
+ };
+
+ expect(mergeWithBundled({ version: '2', providers: [apiKeyOpenai] })
+ .providers.find((provider) => provider.id === 'openai')
+ ?.routing.codex?.supportsResponsesCustomTools).toBeUndefined();
+ expect(mergeWithBundled({ version: '2', providers: [reroutedOpenai] })
+ .providers.find((provider) => provider.id === 'openai')
+ ?.routing.codex?.supportsResponsesCustomTools).toBeUndefined();
+ });
+
it('does not infer bundled billing when a same-id primary changes auth or upstream', () => {
const apiKeyPrimary: Catalog = {
...MINIMAL,
diff --git a/packages/model-providers/src/__tests__/user-provider.test.ts b/packages/model-providers/src/__tests__/user-provider.test.ts
index dbe31bed02..dc4f8bd6a4 100644
--- a/packages/model-providers/src/__tests__/user-provider.test.ts
+++ b/packages/model-providers/src/__tests__/user-provider.test.ts
@@ -65,10 +65,24 @@ describe("buildUserProvider (per-runtime)", () => {
expect(p.routing.codex).toEqual({
upstream: "https://openrouter.ai/api/v1",
authStrategy: "api-key-header",
+ supportsResponsesCustomTools: false,
});
expect(p.routing.codex?.headerOverride).toBeUndefined();
});
+ it("marks only a custom Codex Responses runtime as lacking native custom tools", () => {
+ const responses = buildUserProvider(codexOnly);
+ const chat = buildUserProvider({
+ ...codexOnly,
+ runtimes: {
+ codex: { ...codexOnly.runtimes.codex!, wireProtocol: "openai-chat" },
+ },
+ });
+
+ expect(responses.routing.codex?.supportsResponsesCustomTools).toBe(false);
+ expect(chat.routing.codex?.supportsResponsesCustomTools).toBeUndefined();
+ });
+
it("preserves an explicit Chat Completions protocol for Codex routing", () => {
const p = buildUserProvider({
...codexOnly,
diff --git a/packages/model-providers/src/builtin.ts b/packages/model-providers/src/builtin.ts
index 873fa09573..7e5197aab2 100644
--- a/packages/model-providers/src/builtin.ts
+++ b/packages/model-providers/src/builtin.ts
@@ -161,6 +161,7 @@ const OPENAI_PROVIDER: Provider = {
codex: {
upstream: 'https://chatgpt.com/backend-api/codex',
authStrategy: 'oauth-passthrough',
+ supportsResponsesCustomTools: true,
},
'claude-code': {
upstream: 'https://chatgpt.com/backend-api/codex',
@@ -220,6 +221,7 @@ const XD_PROVIDER: Provider = {
codex: {
upstream: 'https://xd-gateway.invalid/v1',
authStrategy: 'gateway-key',
+ supportsResponsesCustomTools: false,
},
// pi 直连网关 anthropic-messages 面(与 claude-code 同可达面);upstream 同为占位。
pi: {
diff --git a/packages/model-providers/src/catalog.ts b/packages/model-providers/src/catalog.ts
index af089d1c18..cb587e0175 100644
--- a/packages/model-providers/src/catalog.ts
+++ b/packages/model-providers/src/catalog.ts
@@ -338,6 +338,12 @@ function validateProvider(p: Provider): void {
`provider '${p.id}' routing[${agent}].requestPath invalid`,
);
}
+ if (routing.supportsResponsesCustomTools !== undefined) {
+ assert(
+ typeof routing.supportsResponsesCustomTools === 'boolean',
+ `provider '${p.id}' routing[${agent}].supportsResponsesCustomTools must be boolean`,
+ );
+ }
// modelPrefixes(路由服务范围)提供了就必须是命名空间前缀形态(`xai/` 这类,以 `/` 结尾)——
// 结构上保证 claude-* 等裸 wire model 永远不会命中,防止把 scope 声明成误伤辅助请求的形状。
if (routing.modelPrefixes !== undefined) {
diff --git a/packages/model-providers/src/source.ts b/packages/model-providers/src/source.ts
index 93d167c60f..a8985315dd 100644
--- a/packages/model-providers/src/source.ts
+++ b/packages/model-providers/src/source.ts
@@ -196,6 +196,31 @@ function legacyAccessFor(primary: Provider, bundled: Provider): Provider['access
return sameRoutes ? bundled.access : undefined;
}
+/**
+ * 回填新增的 Responses custom-tool capability 只认同一条官方 Codex 路由。
+ * 旧远端快照没有这个 append-only 字段;同 id 但改变了鉴权或 upstream 的供应商可能具备
+ * 完全不同的协议能力,不能因为名字相同就套用 bundled 结论。
+ */
+function bundledResponsesCustomToolCapabilityFor(
+ primary: Provider,
+ bundled: Provider,
+): boolean | undefined {
+ const current = primary.routing.codex;
+ const baseline = bundled.routing.codex;
+ if (
+ current === undefined
+ || baseline === undefined
+ || current.supportsResponsesCustomTools !== undefined
+ || baseline.supportsResponsesCustomTools === undefined
+ || primary.auth.method !== bundled.auth.method
+ || current.upstream !== baseline.upstream
+ || current.authStrategy !== baseline.authStrategy
+ ) {
+ return undefined;
+ }
+ return baseline.supportsResponsesCustomTools;
+}
+
/** 图片能力只可沿用到未声明 access,或仍明确属于同一 bundled 订阅的旧条目。 */
function allowsBundledImageInheritance(
primaryAccess: Provider['access'],
@@ -278,6 +303,9 @@ export function mergeWithBundled(primary: Catalog): Catalog {
const withBundledMetadata = primary.providers.map((p) => {
const bundled = bundledById.get(p.id);
const bundledAccess = bundled ? legacyAccessFor(p, bundled) : undefined;
+ const bundledResponsesCustomToolCapability = bundled
+ ? bundledResponsesCustomToolCapabilityFor(p, bundled)
+ : undefined;
if (!bundled) return p;
// Pi became a first-class provider runtime in catalog v3. Production may still serve a v2
// xAI block that is otherwise the same SuperGrok subscription provider; whole-provider
@@ -320,12 +348,15 @@ export function mergeWithBundled(primary: Catalog): Catalog {
bundled.embeddingModels !== undefined &&
bundledAccess !== undefined &&
allowsBundledImageInheritance(p.access, bundledAccess);
+ const inheritResponsesCustomToolCapability =
+ bundledResponsesCustomToolCapability !== undefined;
if (
!(p.access === undefined && bundledAccess !== undefined) &&
!inheritPiRuntime &&
!inheritImage &&
!inheritVideo &&
- !inheritEmbedding
+ !inheritEmbedding &&
+ !inheritResponsesCustomToolCapability
) {
return p;
}
@@ -335,10 +366,25 @@ export function mergeWithBundled(primary: Catalog): Catalog {
...(inheritPiRuntime
? {
agents: [...p.agents, 'pi' as const],
- routing: { ...p.routing, pi: bundled.routing.pi },
models: { ...p.models, pi: bundled.models.pi },
}
: {}),
+ ...(inheritPiRuntime || inheritResponsesCustomToolCapability
+ ? {
+ routing: {
+ ...p.routing,
+ ...(inheritPiRuntime ? { pi: bundled.routing.pi } : {}),
+ ...(inheritResponsesCustomToolCapability
+ ? {
+ codex: {
+ ...p.routing.codex!,
+ supportsResponsesCustomTools: bundledResponsesCustomToolCapability,
+ },
+ }
+ : {}),
+ },
+ }
+ : {}),
...(inheritImage
? {
imageModels: bundled.imageModels,
diff --git a/packages/model-providers/src/types.ts b/packages/model-providers/src/types.ts
index 190a03e195..0e5be112da 100644
--- a/packages/model-providers/src/types.ts
+++ b/packages/model-providers/src/types.ts
@@ -164,6 +164,12 @@ export interface RoutingDescriptor {
* Codex 的 openai-chat / anthropic-messages 会分别进入对应的本地 Responses bridge。
*/
wireProtocol?: ProviderWireProtocol;
+ /**
+ * 此 Codex Responses 上游是否原生接受 `type: "custom"` 工具。
+ * `false` 时 Desktop 可把选定的 custom tool 对称转换为普通 function tool;
+ * 未声明表示没有足够能力信息,调用方不得按模型名猜测。
+ */
+ supportsResponsesCustomTools?: boolean;
/** 真实上游 base URL(direct 时是供应商自家;gateway 时是 XD 网关 base)。 */
upstream: string;
/**
diff --git a/packages/model-providers/src/user-provider.ts b/packages/model-providers/src/user-provider.ts
index 0e23e2e1c8..5033f6f107 100644
--- a/packages/model-providers/src/user-provider.ts
+++ b/packages/model-providers/src/user-provider.ts
@@ -215,6 +215,10 @@ function toRouting(
const r: RoutingDescriptor = {
upstream: baseUrl,
authStrategy: strategy,
+ ...(agent === 'codex'
+ && (wireProtocol ?? defaultWireProtocol(agent)) === 'openai-responses'
+ ? { supportsResponsesCustomTools: false }
+ : {}),
...(strategy === "none" &&
(!isLoopbackProviderUrl(baseUrl) ||
(modelsUrl !== undefined && !isLoopbackProviderUrl(modelsUrl)))
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.ts
new file mode 100644
index 0000000000..9e8035b376
--- /dev/null
+++ b/packages/responses-chat-bridge/src/__tests__/custom-tool-function-adapter.test.ts
@@ -0,0 +1,454 @@
+import { Buffer } from "node:buffer";
+import type { Transform } from "node:stream";
+
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { createResponsesCustomToolFunctionAdapter } from "../custom-tool-function-adapter.js";
+
+async function collect(transform: Transform, body: string): Promise<string> {
+ const chunks: Buffer[] = [];
+ transform.on("data", (chunk: Buffer) => chunks.push(chunk));
+ const completed = new Promise<void>((resolve, reject) => {
+ transform.once("end", resolve);
+ transform.once("error", reject);
+ });
+ transform.end(body);
+ await completed;
+ return Buffer.concat(chunks).toString("utf8");
+}
+
+function execRequest() {
+ return {
+ model: "stealth/ox-alpha",
+ tools: [
+ {
+ type: "custom",
+ name: "exec",
+ description: "Run Code Mode JavaScript.",
+ },
+ ],
+ input: [],
+ };
+}
+
+describe("Responses custom-tool function adapter", () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("round-trips collision-safe names, tool choice, history, and parallel SSE calls", async () => {
+ const adapter = createResponsesCustomToolFunctionAdapter(["exec"]);
+ const adapted = adapter.adaptRequest(
+ {
+ model: "stealth/ox-alpha",
+ parallel_tool_calls: true,
+ tools: [
+ {
+ type: "function",
+ name: "exec",
+ description: "An unrelated function.",
+ parameters: { type: "object" },
+ },
+ {
+ type: "custom",
+ name: "exec",
+ description: "Run Code Mode JavaScript.",
+ },
+ {
+ type: "function",
+ name: "read_file",
+ parameters: { type: "object" },
+ },
+ ],
+ tool_choice: { type: "custom", name: "exec" },
+ input: [
+ {
+ type: "custom_tool_call",
+ call_id: "old-call",
+ name: "exec",
+ input: 'text("old")',
+ },
+ {
+ type: "custom_tool_call_output",
+ call_id: "old-call",
+ output: "old result",
+ },
+ ],
+ },
+ 1,
+ ) as Record<string, unknown>;
+
+ const tools = adapted.tools as Array<Record<string, unknown>>;
+ const execFunction = tools.find((tool) => {
+ const parameters = tool.parameters as { required?: string[] } | undefined;
+ return (
+ tool.type === "function" && parameters?.required?.includes("input")
+ );
+ });
+ expect(execFunction?.name).toEqual(expect.stringMatching(/^exec__/));
+ expect(tools).toContainEqual(
+ expect.objectContaining({ type: "function", name: "exec" }),
+ );
+ expect(tools).toContainEqual(
+ expect.objectContaining({ type: "function", name: "read_file" }),
+ );
+ expect(adapted.parallel_tool_calls).toBe(true);
+ expect(adapted.tool_choice).toEqual({
+ type: "function",
+ name: execFunction?.name,
+ });
+ expect(adapted.input).toEqual([
+ expect.objectContaining({
+ type: "function_call",
+ call_id: "old-call",
+ name: execFunction?.name,
+ arguments: '{"input":"text(\\"old\\")"}',
+ }),
+ {
+ type: "function_call_output",
+ call_id: "old-call",
+ output: "old result",
+ },
+ ]);
+
+ const responseTransform = adapter.createResponseTransform(1, {
+ contentType: "text/event-stream; charset=utf-8",
+ contentEncoding: "",
+ });
+ expect(responseTransform).not.toBeNull();
+ const functionName = execFunction?.name as string;
+ const output = await collect(
+ responseTransform!,
+ [
+ {
+ type: "response.output_item.added",
+ output_index: 0,
+ item: {
+ type: "function_call",
+ name: functionName,
+ call_id: "call-1",
+ arguments: "",
+ },
+ },
+ {
+ type: "response.output_item.added",
+ output_index: 1,
+ item: {
+ type: "function_call",
+ name: functionName,
+ call_id: "call-2",
+ arguments: "",
+ },
+ },
+ {
+ type: "response.function_call_arguments.delta",
+ output_index: 1,
+ delta: '{"input":"text(\\"two\\")"}',
+ },
+ {
+ type: "response.function_call_arguments.done",
+ output_index: 1,
+ arguments: '{"input":"text(\\"two\\")"}',
+ },
+ {
+ type: "response.output_item.done",
+ output_index: 1,
+ item: {
+ type: "function_call",
+ name: functionName,
+ call_id: "call-2",
+ arguments: '{"input":"text(\\"two\\")"}',
+ },
+ },
+ {
+ type: "response.function_call_arguments.done",
+ output_index: 0,
+ arguments: '{"input":"text(\\"one\\")"}',
+ },
+ {
+ type: "response.output_item.done",
+ output_index: 0,
+ item: {
+ type: "function_call",
+ name: functionName,
+ call_id: "call-1",
+ arguments: '{"input":"text(\\"one\\")"}',
+ },
+ },
+ ]
+ .map((event) => `data: ${JSON.stringify(event)}\n\n`)
+ .join(""),
+ );
+ const events = output
+ .split("\n")
+ .filter((line) => line.startsWith("data: "))
+ .map((line) => JSON.parse(line.slice(6)) as Record<string, unknown>);
+
+ expect(
+ events.filter((event) => event.type === "response.output_item.done"),
+ ).toEqual([
+ expect.objectContaining({
+ item: expect.objectContaining({
+ type: "custom_tool_call",
+ name: "exec",
+ call_id: "call-2",
+ input: 'text("two")',
+ }),
+ }),
+ expect.objectContaining({
+ item: expect.objectContaining({
+ type: "custom_tool_call",
+ name: "exec",
+ call_id: "call-1",
+ input: 'text("one")',
+ }),
+ }),
+ ]);
+ });
+
+ it("keeps namespaced same-name custom tool history untouched", () => {
+ const adapter = createResponsesCustomToolFunctionAdapter(["exec"]);
+ const namespacedHistory = [
+ {
+ type: "custom_tool_call",
+ call_id: "plugin-exec-call",
+ namespace: "plugin",
+ name: "exec",
+ input: "plugin input",
+ },
+ {
+ type: "custom_tool_call_output",
+ call_id: "plugin-exec-call",
+ output: "plugin output",
+ },
+ ];
+
+ const adapted = adapter.adaptRequest(
+ {
+ ...execRequest(),
+ tools: [
+ ...execRequest().tools,
+ {
+ type: "namespace",
+ name: "plugin",
+ tools: [{ type: "custom", name: "exec" }],
+ },
+ ],
+ input: namespacedHistory,
+ },
+ 7,
+ ) as Record<string, unknown>;
+
+ expect(adapted.input).toEqual(namespacedHistory);
+ });
+
+ it("restores adapted function calls in a JSON response", async () => {
+ const adapter = createResponsesCustomToolFunctionAdapter(["exec"]);
+ const adapted = adapter.adaptRequest(execRequest(), 2) as {
+ tools: Array<{ name: string }>;
+ };
+ const functionName = adapted.tools[0]!.name;
+ const responseTransform = adapter.createResponseTransform(2, {
+ contentType: "application/json",
+ contentEncoding: "identity",
+ });
+
+ const output = await collect(
+ responseTransform!,
+ JSON.stringify({
+ id: "response-1",
+ output: [
+ {
+ type: "function_call",
+ name: functionName,
+ call_id: "call-json",
+ arguments: '{"input":"text(\\"json\\")"}',
+ },
+ ],
+ }),
+ );
+ expect(JSON.parse(output)).toMatchObject({
+ output: [
+ {
+ type: "custom_tool_call",
+ name: "exec",
+ call_id: "call-json",
+ input: 'text("json")',
+ },
+ ],
+ });
+ });
+
+ it("fails explicitly instead of discarding live request mappings at the capacity limit", () => {
+ const adapter = createResponsesCustomToolFunctionAdapter(["exec"]);
+ for (let requestId = 1; requestId <= 256; requestId += 1) {
+ expect(adapter.adaptRequest(execRequest(), requestId)).not.toBeNull();
+ }
+
+ expect(() => adapter.adaptRequest(execRequest(), 257)).toThrow(
+ /too many in-flight custom tool requests/i,
+ );
+ expect(
+ adapter.createResponseTransform(1, {
+ contentType: "text/event-stream",
+ contentEncoding: "",
+ }),
+ ).not.toBeNull();
+ expect(
+ adapter.createResponseTransform(256, {
+ contentType: "application/json",
+ contentEncoding: "",
+ }),
+ ).not.toBeNull();
+ });
+
+ it("releases settled request mappings before the timeout", () => {
+ const adapter = createResponsesCustomToolFunctionAdapter(["exec"]);
+ for (let requestId = 1; requestId <= 256; requestId += 1) {
+ expect(adapter.adaptRequest(execRequest(), requestId)).not.toBeNull();
+ adapter.releaseResponse(requestId);
+ }
+
+ expect(adapter.adaptRequest(execRequest(), 257)).not.toBeNull();
+ expect(
+ adapter.createResponseTransform(257, {
+ contentType: "application/json",
+ contentEncoding: "",
+ }),
+ ).not.toBeNull();
+ });
+
+ it("bounds incomplete parallel response calls", async () => {
+ const adapter = createResponsesCustomToolFunctionAdapter(["exec"]);
+ const adapted = adapter.adaptRequest(execRequest(), 5) as {
+ tools: Array<{ name: string }>;
+ };
+ const functionName = adapted.tools[0]!.name;
+ const responseTransform = adapter.createResponseTransform(5, {
+ contentType: "text/event-stream",
+ contentEncoding: "",
+ });
+ const frames = Array.from({ length: 257 }, (_, outputIndex) => (
+ `data: ${JSON.stringify({
+ type: "response.output_item.added",
+ output_index: outputIndex,
+ item: {
+ type: "function_call",
+ name: functionName,
+ call_id: `call-${outputIndex}`,
+ arguments: "",
+ },
+ })}\n\n`
+ )).join("");
+
+ await expect(collect(responseTransform!, frames)).rejects.toThrow(
+ /too many active calls/i,
+ );
+ });
+
+ it("bounds accumulated response call arguments", async () => {
+ const adapter = createResponsesCustomToolFunctionAdapter(["exec"]);
+ const adapted = adapter.adaptRequest(execRequest(), 6) as {
+ tools: Array<{ name: string }>;
+ };
+ const functionName = adapted.tools[0]!.name;
+ const responseTransform = adapter.createResponseTransform(6, {
+ contentType: "text/event-stream",
+ contentEncoding: "",
+ });
+ const frames = [
+ `data: ${JSON.stringify({
+ type: "response.output_item.added",
+ output_index: 0,
+ item: {
+ type: "function_call",
+ name: functionName,
+ call_id: "call-0",
+ arguments: "",
+ },
+ })}\n\n`,
+ `data: ${JSON.stringify({
+ type: "response.function_call_arguments.delta",
+ output_index: 0,
+ delta: "x".repeat(16 * 1024 * 1024 + 1),
+ })}\n\n`,
+ ].join("");
+
+ await expect(collect(responseTransform!, frames)).rejects.toThrow(
+ /arguments exceed the 16 MiB limit/i,
+ );
+ });
+
+ it("keeps live mappings beyond five minutes instead of expiring them by wall clock", () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-08-22T00:00:00Z"));
+ const adapter = createResponsesCustomToolFunctionAdapter(["exec"]);
+ for (let requestId = 1; requestId <= 255; requestId += 1) {
+ adapter.adaptRequest(execRequest(), requestId);
+ }
+
+ vi.advanceTimersByTime(6 * 60 * 1000);
+ adapter.adaptRequest(execRequest(), 256);
+
+ expect(
+ adapter.createResponseTransform(1, {
+ contentType: "application/json",
+ contentEncoding: "",
+ }),
+ ).not.toBeNull();
+ expect(
+ adapter.createResponseTransform(256, {
+ contentType: "application/json",
+ contentEncoding: "",
+ }),
+ ).not.toBeNull();
+ });
+
+ it("reclaims mappings only after the proxy socket timeout has elapsed", () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-08-22T00:00:00Z"));
+ const adapter = createResponsesCustomToolFunctionAdapter(["exec"]);
+ for (let requestId = 1; requestId <= 255; requestId += 1) {
+ adapter.adaptRequest(execRequest(), requestId);
+ }
+
+ vi.advanceTimersByTime(16 * 60 * 1000);
+ adapter.adaptRequest(execRequest(), 256);
+ for (let requestId = 257; requestId <= 511; requestId += 1) {
+ adapter.adaptRequest(execRequest(), requestId);
+ }
+
+ expect(
+ adapter.createResponseTransform(1, {
+ contentType: "application/json",
+ contentEncoding: "",
+ }),
+ ).toBeNull();
+ expect(
+ adapter.createResponseTransform(256, {
+ contentType: "application/json",
+ contentEncoding: "",
+ }),
+ ).not.toBeNull();
+ });
+
+ it("rejects compressed or unknown response formats rather than translating unsafely", () => {
+ const compressed = createResponsesCustomToolFunctionAdapter(["exec"]);
+ compressed.adaptRequest(execRequest(), 3);
+ expect(() =>
+ compressed.createResponseTransform(3, {
+ contentType: "application/json",
+ contentEncoding: "gzip",
+ }),
+ ).toThrow(/compressed custom tool responses/i);
+
+ const unknown = createResponsesCustomToolFunctionAdapter(["exec"]);
+ unknown.adaptRequest(execRequest(), 4);
+ expect(() =>
+ unknown.createResponseTransform(4, {
+ contentType: "text/plain",
+ contentEncoding: "",
+ }),
+ ).toThrow(/unsupported content type/i);
+ });
+});
diff --git a/packages/responses-chat-bridge/src/custom-tool-function-adapter.ts b/packages/responses-chat-bridge/src/custom-tool-function-adapter.ts
new file mode 100644
index 0000000000..4195ccfd80
--- /dev/null
+++ b/packages/responses-chat-bridge/src/custom-tool-function-adapter.ts
@@ -0,0 +1,340 @@
+import { Buffer } from 'node:buffer';
+import { Transform, type TransformCallback } from 'node:stream';
+import { TextDecoder } from 'node:util';
+
+import { ChatBridgeToolContext, type ChatBridgeToolSpec } from './tool-context.js';
+import type { ResponsesRequest } from './types.js';
+
+const MAX_PENDING_BYTES = 16 * 1024 * 1024;
+const MAX_PENDING_REQUESTS = 256;
+const MAX_ACTIVE_RESPONSE_CALLS = 256;
+const MAX_RESPONSE_ARGUMENT_BYTES = 16 * 1024 * 1024;
+// The desktop proxy's upstream socket timeout is ten minutes. Keep mappings strictly longer so
+// no request that can still be live is evicted, while failed/cancelled requests are eventually
+// reclaimed instead of exhausting the bounded map for the rest of the process lifetime.
+const PENDING_REQUEST_TTL_MS = 15 * 60 * 1000;
+
+function isObject(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function customToolName(tool: unknown): string | null {
+ if (typeof tool === 'string') return tool;
+ return isObject(tool) && tool.type === 'custom' && typeof tool.name === 'string'
+ ? tool.name
+ : null;
+}
+
+function stringifyInput(value: unknown): string {
+ if (typeof value === 'string') return value;
+ const serialized = JSON.stringify(value ?? '');
+ if (serialized === undefined) throw new Error('custom tool input is not JSON-serializable');
+ return serialized;
+}
+
+function unwrapArguments(value: unknown): string {
+ if (typeof value !== 'string') throw new Error('adapted custom tool call has no function arguments');
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(value);
+ } catch {
+ throw new Error('adapted custom tool call arguments are not valid JSON');
+ }
+ if (!isObject(parsed) || typeof parsed.input !== 'string') {
+ throw new Error('adapted custom tool call arguments have no string input');
+ }
+ return parsed.input;
+}
+
+interface AdaptedCall {
+ spec: ChatBridgeToolSpec;
+ arguments: string;
+ input?: string;
+}
+
+/**
+ * Restores one adapted upstream response to the Responses custom-tool dialect.
+ *
+ * SSE frames may split UTF-8, JSON, and parallel function arguments across chunks, so `pending`
+ * holds incomplete framing while `calls` tracks each output index until its matching done event.
+ * Non-streaming JSON is buffered until EOF. Invalid adapted arguments and oversized buffers fail
+ * explicitly because passing a function call through would make Codex execute the wrong protocol.
+ */
+class CustomToolResponseTransform extends Transform {
+ private readonly decoder = new TextDecoder();
+ private readonly calls = new Map<number, AdaptedCall>();
+ private pending = '';
+ private responseArgumentBytes = 0;
+
+ constructor(
+ private readonly specs: ReadonlyMap<string, ChatBridgeToolSpec>,
+ private readonly sse: boolean,
+ ) {
+ super();
+ }
+
+ private rewriteItem(item: unknown, call?: AdaptedCall): Record<string, unknown> | null {
+ if (!isObject(item) || item.type !== 'function_call') return null;
+ const spec = call?.spec ?? (typeof item.name === 'string' ? this.specs.get(item.name) : undefined);
+ if (!spec) return null;
+ const next: Record<string, unknown> = {
+ ...item,
+ type: 'custom_tool_call',
+ name: spec.name,
+ input: call?.input ?? unwrapArguments(call?.arguments ?? item.arguments),
+ };
+ delete next.arguments;
+ return next;
+ }
+ private rewriteEvent(event: unknown): Record<string, unknown>[] | null {
+ if (!isObject(event) || typeof event.type !== 'string') return null;
+ const index = typeof event.output_index === 'number' ? event.output_index : -1;
+ if (event.type === 'response.output_item.added' && isObject(event.item)) {
+ const spec = event.item.type === 'function_call' && typeof event.item.name === 'string'
+ ? this.specs.get(event.item.name)
+ : undefined;
+ if (!spec || index < 0) return null;
+ const argumentsText = typeof event.item.arguments === 'string' ? event.item.arguments : '';
+ const previous = this.calls.get(index);
+ if (!previous && this.calls.size >= MAX_ACTIVE_RESPONSE_CALLS) {
+ throw new Error('adapted custom tool response has too many active calls');
+ }
+ const nextArgumentBytes =
+ this.responseArgumentBytes
+ - (previous ? Buffer.byteLength(previous.arguments, 'utf8') : 0)
+ + Buffer.byteLength(argumentsText, 'utf8');
+ if (nextArgumentBytes > MAX_RESPONSE_ARGUMENT_BYTES) {
+ throw new Error('adapted custom tool response arguments exceed the 16 MiB limit');
+ }
+ this.responseArgumentBytes = nextArgumentBytes;
+ this.calls.set(index, {
+ spec,
+ arguments: argumentsText,
+ });
+ const item: Record<string, unknown> = {
+ ...event.item, type: 'custom_tool_call', name: spec.name, input: '',
+ };
+ delete item.arguments;
+ return [{ ...event, item }];
+ }
+
+ const call = this.calls.get(index);
+ if (event.type === 'response.function_call_arguments.delta' && call) {
+ if (typeof event.delta === 'string') {
+ const deltaBytes = Buffer.byteLength(event.delta, 'utf8');
+ if (this.responseArgumentBytes + deltaBytes > MAX_RESPONSE_ARGUMENT_BYTES) {
+ throw new Error('adapted custom tool response arguments exceed the 16 MiB limit');
+ }
+ call.arguments += event.delta;
+ this.responseArgumentBytes += deltaBytes;
+ }
+ return [];
+ }
+ 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,
+ };
+ const done: Record<string, unknown> = {
+ ...event, type: 'response.custom_tool_call_input.done', input: call.input,
+ };
+ delete delta.arguments;
+ delete done.arguments;
+ return [delta, done];
+ }
+ if (event.type === 'response.output_item.done') {
+ const item = this.rewriteItem(event.item, call);
+ if (!item) return null;
+ this.calls.delete(index);
+ this.responseArgumentBytes -= call ? Buffer.byteLength(call.arguments, 'utf8') : 0;
+ return [{ ...event, item }];
+ }
+ if (isObject(event.response) && Array.isArray(event.response.output)) {
+ let changed = false;
+ const output = event.response.output.map((item) => {
+ const next = this.rewriteItem(item);
+ if (!next) return item;
+ changed = true;
+ return next;
+ });
+ if (changed) return [{ ...event, response: { ...event.response, output } }];
+ }
+ return null;
+ }
+ private rewriteFrame(frame: string, delimiter: string): string {
+ const lines = frame.split(/\r?\n/);
+ const data = lines.filter((line) => line.startsWith('data:'))
+ .map((line) => line.slice(5).trimStart()).join('\n');
+ if (!data || data === '[DONE]') return frame + delimiter;
+ let event: unknown;
+ try {
+ event = JSON.parse(data);
+ } catch {
+ return frame + delimiter;
+ }
+ const rewritten = this.rewriteEvent(event);
+ if (rewritten === null) return frame + delimiter;
+ const named = lines.some((line) => line.startsWith('event:'));
+ return rewritten.map((next) => (
+ `${named ? `event: ${String(next.type)}\n` : ''}data: ${JSON.stringify(next)}${delimiter}`
+ )).join('');
+ }
+ private drainFrames(): void {
+ // Keep the incomplete tail in `pending`; only complete SSE frames are safe to rewrite.
+ for (;;) {
+ const lf = this.pending.indexOf('\n\n');
+ const crlf = this.pending.indexOf('\r\n\r\n');
+ const index = lf < 0 ? crlf : crlf < 0 ? lf : Math.min(lf, crlf);
+ if (index < 0) return;
+ const delimiter = index === crlf ? '\r\n\r\n' : '\n\n';
+ this.push(this.rewriteFrame(this.pending.slice(0, index), delimiter));
+ this.pending = this.pending.slice(index + delimiter.length);
+ }
+ }
+ override _transform(chunk: Buffer, _encoding: string, callback: TransformCallback): void {
+ try {
+ this.pending += this.decoder.decode(chunk, { stream: true });
+ if (this.sse) this.drainFrames();
+ if (Buffer.byteLength(this.pending, 'utf8') > MAX_PENDING_BYTES) {
+ throw new Error('adapted custom tool response exceeds the 16 MiB buffer limit');
+ }
+ callback();
+ } catch (error) {
+ callback(error as Error);
+ }
+ }
+ override _flush(callback: TransformCallback): void {
+ try {
+ this.pending += this.decoder.decode();
+ if (this.sse) {
+ this.drainFrames();
+ if (this.pending) this.push(this.rewriteFrame(this.pending, ''));
+ } else {
+ // A JSON response has no stable item boundary before EOF, so rewrite it as one document.
+ const parsed = JSON.parse(this.pending) as unknown;
+ const rewritten = this.rewriteEvent({ type: 'response.completed', response: parsed });
+ this.push(JSON.stringify(rewritten?.[0]?.response ?? parsed));
+ }
+ this.pending = '';
+ callback();
+ } catch (error) {
+ callback(error as Error);
+ }
+ }
+}
+
+export interface ResponsesCustomToolFunctionAdapter {
+ adaptRequest(body: unknown, requestId: number): unknown | null;
+ /** Idempotently release request-scoped response metadata after the request settles. */
+ releaseResponse(requestId: number): void;
+ createResponseTransform(requestId: number, response: {
+ contentType: string; contentEncoding: string;
+ }): Transform | null;
+}
+
+/** Symmetric adapter for Responses providers that only accept function tools. */
+export function createResponsesCustomToolFunctionAdapter(
+ customToolNames: readonly string[],
+): ResponsesCustomToolFunctionAdapter {
+ const selected = new Set(customToolNames);
+ const responseSpecs = new Map<number, {
+ specs: Map<string, ChatBridgeToolSpec>;
+ createdAt: number;
+ }>();
+
+ const discardExpiredResponseSpecs = (now: number): void => {
+ for (const [requestId, pending] of responseSpecs) {
+ if (now - pending.createdAt >= PENDING_REQUEST_TTL_MS) responseSpecs.delete(requestId);
+ }
+ };
+
+ return {
+ adaptRequest(body, requestId) {
+ if (!isObject(body) || !Array.isArray(body.tools)) return null;
+ const context = ChatBridgeToolContext.fromRequest(body as unknown as ResponsesRequest);
+ const specs = new Map<string, ChatBridgeToolSpec>();
+ const functionNames = new Map<string, string>();
+ const tools: unknown[] = [];
+ for (const tool of body.tools) {
+ const name = customToolName(tool);
+ if (!name || !selected.has(name)) {
+ tools.push(tool);
+ continue;
+ }
+ if (functionNames.has(name)) continue;
+ const functionName = context.chatNameForResponse(name, undefined, 'custom');
+ const spec = context.lookupChatName(functionName);
+ const chatTool = context.chatTools?.find((item) => item.function.name === functionName);
+ if (!spec || !chatTool) throw new Error(`cannot adapt Responses custom tool '${name}'`);
+ functionNames.set(name, functionName);
+ specs.set(functionName, spec);
+ tools.push({ type: 'function', ...chatTool.function });
+ }
+ if (specs.size === 0) return null;
+
+ const calls = new Map<string, string>();
+ if (Array.isArray(body.input)) {
+ for (const item of body.input) {
+ if (isObject(item) && item.type === 'custom_tool_call'
+ && !Object.hasOwn(item, 'namespace')
+ && typeof item.name === 'string' && typeof item.call_id === 'string') {
+ const functionName = functionNames.get(item.name);
+ if (functionName) calls.set(item.call_id, functionName);
+ }
+ }
+ }
+ const input = Array.isArray(body.input) ? body.input.map((item) => {
+ if (!isObject(item) || typeof item.call_id !== 'string') return item;
+ const functionName = calls.get(item.call_id);
+ if (!functionName) return item;
+ if (item.type === 'custom_tool_call') {
+ const next: Record<string, unknown> = {
+ ...item, type: 'function_call', name: functionName,
+ arguments: JSON.stringify({ input: stringifyInput(item.input) }),
+ };
+ delete next.input;
+ delete next.namespace;
+ return next;
+ }
+ return item.type === 'custom_tool_call_output'
+ ? { ...item, type: 'function_call_output' }
+ : item;
+ }) : body.input;
+ let toolChoice = body.tool_choice;
+ if (isObject(toolChoice) && toolChoice.type === 'custom' && typeof toolChoice.name === 'string') {
+ const name = functionNames.get(toolChoice.name);
+ if (name) toolChoice = { type: 'function', name };
+ }
+ const now = Date.now();
+ discardExpiredResponseSpecs(now);
+ if (!responseSpecs.has(requestId) && responseSpecs.size >= MAX_PENDING_REQUESTS) {
+ throw new Error('too many in-flight custom tool requests to adapt safely');
+ }
+ responseSpecs.set(requestId, { specs, createdAt: now });
+ const adapted: Record<string, unknown> = { ...body, tools, input };
+ if (Object.hasOwn(body, 'tool_choice')) adapted.tool_choice = toolChoice;
+ return adapted;
+ },
+
+ releaseResponse(requestId) {
+ responseSpecs.delete(requestId);
+ },
+
+ createResponseTransform(requestId, response) {
+ const pending = responseSpecs.get(requestId);
+ responseSpecs.delete(requestId);
+ const specs = pending?.specs;
+ if (!specs?.size) return null;
+ const encoding = response.contentEncoding.trim().toLowerCase();
+ if (encoding && encoding !== 'identity') {
+ throw new Error('compressed custom tool responses cannot be adapted safely');
+ }
+ const contentType = response.contentType.toLowerCase();
+ const sse = contentType.startsWith('text/event-stream');
+ if (!sse && !contentType.includes('application/json')) {
+ throw new Error(`custom tool response has unsupported content type '${response.contentType}'`);
+ }
+ return new CustomToolResponseTransform(specs, sse);
+ },
+ };
+}
diff --git a/packages/responses-chat-bridge/src/index.ts b/packages/responses-chat-bridge/src/index.ts
index dfe936c408..e9630016be 100644
--- a/packages/responses-chat-bridge/src/index.ts
+++ b/packages/responses-chat-bridge/src/index.ts
@@ -7,6 +7,10 @@ export {
type TranslateResponsesRequestOptions,
} from './translate-request.js';
export { ChatBridgeToolContext, type ChatBridgeToolKind, type ChatBridgeToolSpec } from './tool-context.js';
+export {
+ createResponsesCustomToolFunctionAdapter,
+ type ResponsesCustomToolFunctionAdapter,
+} from './custom-tool-function-adapter.js';
export {
isResponsesImageContentPartType,
isUnsupportedResponsesImageErrorPayload,