Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(codex): complete Responses to Chat bridge capabilities (#895)
JiangJiahao68dc9a6b332c
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.tsindex 54e2298886..035e64961e 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts@@ -397,6 +397,17 @@ describe('decideCodexRoute', () => {});describe('chatBridgeCapabilitiesForRoute', () => {+ it('does not forward unsupported passthrough fields into the translator', async () => {+ const { chatBridgeCapabilitiesForRoute } = await freshCodexProxyHost();+ const capabilities = chatBridgeCapabilitiesForRoute(+ 'https://api.deepseek.com/v1',+ 'deepseek-chat',+ );+ expect(capabilities.passthroughFields).not.toContain('n');+ expect(capabilities.passthroughFields).not.toContain('logprobs');+ expect(capabilities.passthroughFields).not.toContain('top_logprobs');+ });+it.each(['https://api.moonshot.cn/v1','https://api.moonshot.ai/v1/',@@ -483,6 +494,37 @@ describe('chatBridgeCapabilitiesForRoute', () => {}),expect.anything(),);+ const localHandler = (decision as {+ localHandler: (input: { rawBody: Buffer; parsedBody: unknown; res: unknown }) => Promise<void>;+ }).localHandler;+ const originalInstructions = [+ { type: 'input_text', text: 'BASE_PROMPT' },+ { type: 'input_image', image_url: 'data:image/png;base64,eA==' },+ ];+ const parsedBody = {+ model: 'kimi-k3',+ instructions: originalInstructions,+ input: 'hello',+ };+ const res = {};+ await localHandler({+ rawBody: Buffer.from(JSON.stringify(parsedBody)),+ parsedBody,+ res,+ });+ const bridgeHandler = mockState.createResponsesChatHandler.mock.results.at(-1)?.value as {+ handle: ReturnType<typeof vi.fn>;+ };+ expect(bridgeHandler.handle).toHaveBeenCalledWith({+ parsedBody: {+ ...parsedBody,+ instructions: [+ ...originalInstructions,+ { type: 'input_text', text: '\n\nPRODUCT_PROMPT' },+ ],+ },+ res,+ });clearSessionProvider('session-kimi-image');setCustomProviderKeyReader(() => null);@@ -1643,6 +1685,160 @@ describe('codex proxy host', () => {clearSessionProvider('session-seed');});+ it('normalizes custom Volcengine Ark Responses routes regardless of the model alias', 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: 'custom-volcengine',+ name: 'Custom Volcengine',+ runtimes: {+ codex: {+ baseUrl: 'https://ark.cn-beijing.volces.com/api/v3',+ models: [{ id: 'production-deployment', name: 'Production Deployment' }],+ },+ },+ }),+ ]);+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({+ url: 'http://127.0.0.1:43210',+ dispose: vi.fn(async () => undefined),+ });+ await host.ensureCodexProxyReady();+ host.registerComposed('session-custom-volcengine', 'thread-custom-volcengine', 'PRODUCT_PROMPT');+ setSessionProvider('session-custom-volcengine', 'custom-volcengine');++ const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];+ let current: unknown = {+ model: 'production-deployment',+ reasoning: { effort: 'high', summary: 'auto' },+ tools: [+ { type: 'function', name: 'exec_command' },+ { type: 'namespace', name: 'mcp__example', tools: [{ type: 'function', name: 'read' }] },+ { type: 'web_search', external_web_access: true },+ ],+ input: [+ { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'earlier' }] },+ ],+ };+ const ctx = {+ method: 'POST',+ url: '/responses',+ headers: { 'thread-id': 'thread-custom-volcengine' },+ };+ for (const transform of transforms) {+ const next = transform(current, ctx);+ if (next !== null && next !== undefined) current = next;+ }++ expect(current).toEqual({+ model: 'production-deployment',+ reasoning: { effort: 'high' },+ tools: [+ { type: 'function', name: 'exec_command' },+ { type: 'web_search' },+ ],+ input: [+ {+ type: 'message',+ role: 'assistant',+ status: 'completed',+ content: [{ type: 'output_text', text: 'earlier' }],+ },+ ],+ });++ clearSessionProvider('session-custom-volcengine');+ setCustomProviders([]);+ });++ it('does not apply the Seed fallback to non-Ark Volces Responses routes', 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: 'custom-volces',+ name: 'Custom Volces',+ runtimes: {+ codex: {+ baseUrl: 'https://gateway.volces.com/api/v3',+ models: [{ id: 'production-deployment', name: 'Production Deployment' }],+ },+ },+ }),+ ]);+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({+ url: 'http://127.0.0.1:43210',+ dispose: vi.fn(async () => undefined),+ });+ await host.ensureCodexProxyReady();+ host.registerComposed('session-custom-volces', 'thread-custom-volces', 'PRODUCT_PROMPT');+ setSessionProvider('session-custom-volces', 'custom-volces');++ const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];+ const original = {+ model: 'production-deployment',+ reasoning: { effort: 'high', summary: 'auto' },+ tools: [+ { type: 'function', name: 'exec_command' },+ { type: 'namespace', name: 'mcp__example', tools: [{ type: 'function', name: 'read' }] },+ { type: 'web_search', external_web_access: true },+ ],+ input: [+ { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'earlier' }] },+ ],+ };+ let current: unknown = original;+ const ctx = {+ method: 'POST',+ url: '/responses',+ headers: { 'thread-id': 'thread-custom-volces' },+ };+ for (const transform of transforms) {+ const next = transform(current, ctx);+ if (next !== null && next !== undefined) current = next;+ }++ expect(current).toEqual(original);++ clearSessionProvider('session-custom-volces');+ setCustomProviders([]);+ });++ it('recognizes Volcengine native doubao Seed model IDs without route metadata', async () => {+ const host = await freshCodexProxyHost();+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({+ url: 'http://127.0.0.1:43210',+ dispose: vi.fn(async () => undefined),+ });+ await host.ensureCodexProxyReady();++ const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];+ let current: unknown = {+ model: 'doubao-seed-2-1-pro-260628',+ tools: [+ { type: 'function', name: 'exec_command' },+ { type: 'namespace', name: 'mcp__example', tools: [{ type: 'function', name: 'read' }] },+ ],+ input: 'hello',+ };+ const ctx = { method: 'POST', url: '/responses', headers: {} };+ for (const transform of transforms) {+ const next = transform(current, ctx);+ if (next !== null && next !== undefined) current = next;+ }++ expect(current).toEqual({+ model: 'doubao-seed-2-1-pro-260628',+ tools: [{ type: 'function', name: 'exec_command' }],+ input: 'hello',+ });+ });+it('removes Seed tool controls when every declared tool is unsupported', async () => {const host = await freshCodexProxyHost();mockState.createAnthropicCompatProxy.mockResolvedValueOnce({diff --git a/apps/desktop/src/main/maker-host/codex-proxy-host.ts b/apps/desktop/src/main/maker-host/codex-proxy-host.tsindex 7256bc20d4..67d49ea843 100644--- a/apps/desktop/src/main/maker-host/codex-proxy-host.ts+++ b/apps/desktop/src/main/maker-host/codex-proxy-host.ts@@ -364,6 +364,23 @@ const CHAT_BRIDGE_DEFAULT_CAPABILITIES: ChatBridgeCapabilities = {maxTokensField: 'max_tokens',reasoningField: 'none',streamUsage: true,+ // Responses fields with direct Chat equivalents. Provider-specific unsupported fields can+ // be removed later when the model capability catalog becomes more granular.+ passthroughFields: [+ 'temperature',+ 'top_p',+ 'frequency_penalty',+ 'presence_penalty',+ 'stop',+ 'seed',+ 'user',+ 'metadata',+ 'service_tier',+ 'response_format',+ 'logit_bias',+ // Token log probabilities are not restored by ChatSseTranslator yet; do not advertise+ // request passthrough until the Responses response shape is implemented.+ ],toolCallReasoningPlaceholder: true,forceAutoToolChoice: true,};@@ -401,7 +418,8 @@ function rewriteChatBridgeModel(model: string, stripPrefix: string | undefined):}/**- * 图片桥接必须按已验证的上游能力显式开启。这里认官方 DNS 边界 + 上游 model+ * 在模型级多模态能力元数据接入路由前,图片桥接先按已验证的上游能力显式开启。+ * 这里认官方 DNS 边界 + 上游 model* (Moonshot 的 Kimi K3、火山方舟的豆包 Seed 系列),不认 provider id(预设创建后* 会生成用户自定义 id),也不对所有 openai-chat 供应商放开。未命中继续沿用* fail-closed 默认——无图片能力的上游(如 DeepSeek)保持发送前显式报错,不静默吞图。@@ -463,7 +481,7 @@ function createChatBridgeDecision(toolCallReasoningPlaceholder: false,forceAutoToolChoice: false,googleThoughtSignaturePlaceholder: true,- }+ }: CHAT_BRIDGE_DEFAULT_CAPABILITIES;const capabilities = chatBridgeCapabilitiesForRoute(route.routing.upstream,@@ -503,12 +521,29 @@ function createChatBridgeDecision(});}if (instructions && isPlainObject(body)) {- const existing = typeof body.instructions === 'string' ? body.instructions : '';+ const existing = body.instructions;+ const existingText = Array.isArray(existing)+ ? existing.map((part) => {+ if (!isPlainObject(part) || typeof part.type !== 'string') return '';+ if (+ (part.type === 'input_text' || part.type === 'output_text' || part.type === 'text')+ && typeof part.text === 'string'+ ) {+ return part.text;+ }+ if (part.type === 'refusal' && typeof part.refusal === 'string') return part.refusal;+ return '';+ }).join('')+ : typeof existing === 'string'+ ? existing+ : '';body = {...body,- instructions: existing.includes(instructions)+ instructions: existingText.includes(instructions)? existing- : [existing, instructions].filter(Boolean).join('\n\n'),+ : Array.isArray(existing)+ ? [...existing, { type: 'input_text', text: `\n\n${instructions}` }]+ : [existingText, instructions].filter(Boolean).join('\n\n'),};}// localHandler 在 transform 链**之前**执行(引擎按路由决策短路),跨来源恢复的@@ -889,7 +924,35 @@ function ensureXaiServerSideTools(body: Record<string, unknown>): Record<string,* is rejected as an unknown field.*/function isByteDanceSeedModel(model: unknown): boolean {- return typeof model === 'string' && model.startsWith('bytedance-seed/');+ return typeof model === 'string' && (+ model.startsWith('bytedance-seed/') ||+ model.startsWith('doubao-seed-')+ );+}++function isVolcengineArkResponsesRouting(ctx: RequestTransformCtx, model: unknown): boolean {+ if (typeof model !== 'string' || model.length === 0) return false;+ const sessionId = sessionIdFromTransformCtx(ctx);+ if (!sessionId) return false;+ const routing = getSessionRoutingDescriptor(sessionId, 'codex', model);+ if (!routing || (routing.wireProtocol ?? 'openai-responses') !== 'openai-responses') return false;++ try {+ const url = new URL(routing.upstream);+ return url.protocol === 'https:' && VOLCENGINE_ARK_CHAT_HOST_RE.test(url.hostname.toLowerCase());+ } catch {+ return false;+ }+}++function isByteDanceSeedRequest(+ body: Record<string, unknown>,+ ctx: RequestTransformCtx,+): boolean {+ // The catalog model uses a provider namespace, while Volcengine's native+ // model IDs use doubao-seed-* and user-defined aliases may use neither.+ // The selected official Ark Responses route is the authoritative fallback.+ return isByteDanceSeedModel(body.model) || isVolcengineArkResponsesRouting(ctx, body.model);}function seedToolChoiceReferencesRemovedTool(@@ -906,7 +969,7 @@ function seedToolChoiceReferencesRemovedTool(}function sanitizeByteDanceSeedTools(body: Record<string, unknown>): Record<string, unknown> | null {- if (!isByteDanceSeedModel(body.model) || !Array.isArray(body.tools)) return null;+ if (!Array.isArray(body.tools)) return null;let changed = false;const tools: Record<string, unknown>[] = [];@@ -979,7 +1042,7 @@ function stripEmptyResponseMessage(item: unknown): { item: unknown; changed: boo/** Volcengine requires replayed assistant messages to carry their output status and non-empty text. */function normalizeByteDanceSeedInput(body: Record<string, unknown>): Record<string, unknown> | null {- if (!isByteDanceSeedModel(body.model) || !Array.isArray(body.input)) return null;+ if (!Array.isArray(body.input)) return null;let changed = false;const input: unknown[] = [];@@ -1108,7 +1171,7 @@ function createStrictGatewayHistoryCompatTransform(): RequestTransform {/** Seed accepts the reasoning effort, but rejects Responses' summary selector. */function sanitizeByteDanceSeedReasoning(body: Record<string, unknown>): Record<string, unknown> | null {- if (!isByteDanceSeedModel(body.model) || !isPlainObject(body.reasoning) || !('summary' in body.reasoning)) {+ if (!isPlainObject(body.reasoning) || !('summary' in body.reasoning)) {return null;}@@ -1122,8 +1185,9 @@ function sanitizeByteDanceSeedReasoning(body: Record<string, unknown>): Record<s}function createByteDanceSeedResponsesCompatTransform(): RequestTransform {- return (body) => {+ return (body, ctx) => {if (!isPlainObject(body)) return null;+ if (!isByteDanceSeedRequest(body, ctx)) return null;let changed = false;let current = body;const withSanitizedTools = sanitizeByteDanceSeedTools(current);diff --git a/packages/responses-chat-bridge/src/__tests__/chat-sse-translator.test.ts b/packages/responses-chat-bridge/src/__tests__/chat-sse-translator.test.tsindex 4ea5f0d395..cef37c563f 100644--- a/packages/responses-chat-bridge/src/__tests__/chat-sse-translator.test.ts+++ b/packages/responses-chat-bridge/src/__tests__/chat-sse-translator.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest';import { ChatSseTranslator } from '../chat-sse-translator.js';+import { ChatBridgeToolContext } from '../tool-context.js';describe('ChatSseTranslator', () => {it('streams text with a valid Responses lifecycle and keeps usage until finish', () => {@@ -99,11 +100,64 @@ describe('ChatSseTranslator', () => {expect(out.at(-1)?.type).toBe('response.completed');});+ it('translates non-streaming message.tool_calls without streaming indexes', () => {+ const translator = new ChatSseTranslator('m');+ const out = [+ ...translator.push({+ id: 'chat_json_tools',+ choices: [{+ message: {+ role: 'assistant',+ tool_calls: [{+ id: 'call_json',+ type: 'function',+ function: { name: 'Bash', arguments: '{"cmd":"pwd"}' },+ }],+ },+ finish_reason: 'tool_calls',+ }],+ }),+ ...translator.finish(),+ ] as Array<Record<string, unknown>>;+ const completed = out.at(-1) as { response: { output: Array<Record<string, unknown>> } };+ expect(completed.response.output).toContainEqual(expect.objectContaining({+ type: 'function_call',+ call_id: 'call_json',+ name: 'Bash',+ arguments: '{"cmd":"pwd"}',+ }));+ });++ it('preserves non-streaming Chat refusal messages as Responses refusal content', () => {+ const translator = new ChatSseTranslator('m');+ const out = [+ ...translator.push({+ id: 'chat_json_refusal',+ choices: [{+ message: {+ role: 'assistant',+ content: null,+ refusal: 'I cannot help with that.',+ },+ finish_reason: 'stop',+ }],+ }),+ ...translator.finish(),+ ] as Array<Record<string, unknown>>;+ expect(out.map((event) => event.type)).toContain('response.refusal.delta');+ expect(out.map((event) => event.type)).toContain('response.refusal.done');+ const completed = out.at(-1) as { response: { output: Array<Record<string, unknown>> } };+ expect(completed.response.output).toContainEqual(expect.objectContaining({+ type: 'message',+ content: [{ type: 'refusal', refusal: 'I cannot help with that.' }],+ }));+ });+it('waits for a streamed tool name before emitting the call item', () => {const translator = new ChatSseTranslator('m');const beforeName = translator.push({id: 'chatcmpl_args_first',- choices: [{ delta: { tool_calls: [{ index: 0, id: 'call_args_first', function: { arguments: '{"x":' } }] } }],+ choices: [{ delta: { tool_calls: [{ index: 0, id: 'call_args_first', function: { arguments: '{"x":1}' } }] } }],}) as Array<Record<string, unknown>>;expect(beforeName.filter((event) => event.type === 'response.output_item.added')).toEqual([]);expect(beforeName.filter((event) => event.type === 'response.function_call_arguments.delta')).toEqual([]);@@ -111,7 +165,7 @@ describe('ChatSseTranslator', () => {const out = [...beforeName,...translator.push({- choices: [{ delta: { tool_calls: [{ index: 0, function: { name: 'Bash', arguments: '1}' } }] }, finish_reason: 'tool_calls' }],+ choices: [{ delta: { tool_calls: [{ index: 0, function: { name: 'Bash' } }] }, finish_reason: 'tool_calls' }],}),...translator.finish(),] as Array<Record<string, unknown>>;@@ -120,6 +174,84 @@ describe('ChatSseTranslator', () => {expect(added.item.name).toBe('Bash');expect(deltas.map((event) => event.delta).join('')).toBe('{"x":1}');});++ it('preserves repeated suffixes split across streamed tool-name fragments', () => {+ const translator = new ChatSseTranslator('m');+ translator.push({+ id: 'chatcmpl_repeated_name',+ choices: [{ delta: { tool_calls: [{ index: 0, id: 'call_repeated', function: { name: 'foo' } }] } }],+ });+ const out = [+ ...translator.push({+ choices: [{+ delta: { tool_calls: [{ index: 0, function: { name: 'foo', arguments: '{}' } }] },+ finish_reason: 'tool_calls',+ }],+ }),+ ...translator.finish(),+ ] as Array<Record<string, unknown>>;+ const completed = out.at(-1) as { response: { output: Array<Record<string, unknown>> } };+ expect(completed.response.output).toContainEqual(expect.objectContaining({+ type: 'function_call',+ name: 'foofoo',+ arguments: '{}',+ }));+ });++ it('continues accumulating a tool name after its output item has been added', () => {+ const translator = new ChatSseTranslator('m');+ const out = [+ ...translator.push({+ id: 'chatcmpl_name_fragments',+ choices: [{+ delta: {+ tool_calls: [{+ index: 0,+ id: 'call_name_fragments',+ function: { name: 'foo', arguments: '{}' },+ }],+ },+ }],+ }),+ ...translator.push({+ choices: [{+ delta: { tool_calls: [{ index: 0, function: { name: 'bar' } }] },+ finish_reason: 'tool_calls',+ }],+ }),+ ...translator.finish(),+ ] as Array<Record<string, unknown>>;++ const completed = out.at(-1) as { response: { output: Array<Record<string, unknown>> } };+ expect(completed.response.output).toContainEqual(expect.objectContaining({+ type: 'function_call',+ name: 'foobar',+ arguments: '{}',+ }));+ });++ it('force-adds name-only zero-argument tool calls when the stream closes without a finish reason', () => {+ const translator = new ChatSseTranslator('m');+ const beforeFinish = translator.push({+ id: 'chatcmpl_name_only',+ choices: [{ delta: { tool_calls: [{ index: 0, id: 'call_name_only', function: { name: 'Bash' } }] } }],+ }) as Array<Record<string, unknown>>;+ expect(beforeFinish.some((event) => event.type === 'response.output_item.added')).toBe(false);++ const afterFinish = translator.finish() as Array<Record<string, unknown>>;+ const addedIndex = afterFinish.findIndex((event) => event.type === 'response.output_item.added');+ const doneIndex = afterFinish.findIndex((event) => event.type === 'response.output_item.done');+ expect(addedIndex).toBeGreaterThanOrEqual(0);+ expect(doneIndex).toBeGreaterThan(addedIndex);+ const completed = afterFinish.at(-1) as { response: { output: Array<Record<string, unknown>> } };+ expect(completed.response.output).toContainEqual(expect.objectContaining({+ type: 'function_call',+ call_id: 'call_name_only',+ name: 'Bash',+ arguments: '',+ }));+ });+it('creates deterministic ids when the provider omits tool call ids', () => {const make = (): unknown[] => {const translator = new ChatSseTranslator('m');@@ -214,4 +346,277 @@ describe('ChatSseTranslator', () => {// fail() 后 translator 已终结,后续 finish() 不再产出。expect(out.filter((e) => e.type === 'response.completed')).toEqual([]);});++ it('restores custom, namespace, and tool-search calls from Chat function deltas', () => {+ const toolContext = ChatBridgeToolContext.fromRequest({+ model: 'm',+ input: [],+ tools: [+ { type: 'custom', name: 'apply_patch' },+ {+ type: 'namespace',+ name: 'mcp',+ tools: [+ { type: 'function', name: 'query' },+ { type: 'custom', name: 'exec' },+ ],+ },+ { type: 'tool_search' },+ ],+ });+ const translator = new ChatSseTranslator('m', { toolContext });+ const out = [+ ...translator.push({+ id: 'custom',+ choices: [{+ delta: {+ tool_calls: [{+ index: 0,+ id: 'c1',+ function: { name: 'apply_patch', arguments: '{"input":"diff"}' },+ }],+ },+ }],+ }),+ ...translator.push({+ choices: [{+ delta: {+ tool_calls: [{+ index: 1,+ id: 'c2',+ function: { name: 'mcp__query', arguments: '{"q":"x"}' },+ }, {+ index: 2,+ id: 'c3',+ function: { name: 'tool_search', arguments: '{"query":"browser"}' },+ }, {+ index: 3,+ id: 'c4',+ function: { name: 'mcp__exec', arguments: '{"input":"code"}' },+ }],+ },+ finish_reason: 'tool_calls',+ }],+ }),+ ...translator.finish(),+ ] as Array<Record<string, unknown>>;+ const items = out+ .filter((event) => event.type === 'response.output_item.done')+ .map((event) => (event as { item: Record<string, unknown> }).item);+ expect(items.map((item) => item.type)).toEqual([+ 'custom_tool_call',+ 'function_call',+ 'tool_search_call',+ 'custom_tool_call',+ ]);+ expect(items[0]).toMatchObject({ call_id: 'c1', name: 'apply_patch', input: 'diff' });+ expect(items[1]).toMatchObject({ call_id: 'c2', name: 'query', namespace: 'mcp' });+ expect(items[2]).toMatchObject({ call_id: 'c3', arguments: { query: 'browser' } });+ expect(items[3]).toMatchObject({+ call_id: 'c4',+ name: 'exec',+ namespace: 'mcp',+ input: 'code',+ });+ });++ it('waits for a catalogued custom tool name before adding its output item', () => {+ const toolContext = ChatBridgeToolContext.fromRequest({+ model: 'm',+ input: [],+ tools: [{ type: 'custom', name: 'apply_patch' }],+ });+ const translator = new ChatSseTranslator('m', { toolContext });++ const first = translator.push({+ id: 'split-custom',+ choices: [{+ delta: {+ tool_calls: [{+ index: 0,+ id: 'call_split_custom',+ function: { name: 'apply', arguments: '{"input":"diff"}' },+ }],+ },+ }],+ }) as Array<Record<string, unknown>>;+ expect(first.filter((event) => event.type === 'response.output_item.added')).toEqual([]);++ const out = [+ ...first,+ ...translator.push({+ choices: [{+ delta: { tool_calls: [{ index: 0, function: { name: '_patch' } }] },+ finish_reason: 'tool_calls',+ }],+ }),+ ...translator.finish(),+ ] as Array<Record<string, unknown>>;+ const completed = out.at(-1) as { response: { output: Array<Record<string, unknown>> } };+ expect(completed.response.output).toContainEqual(expect.objectContaining({+ type: 'custom_tool_call',+ name: 'apply_patch',+ input: 'diff',+ }));+ });++ it('waits when an exact function name is also a prefix of a longer custom name', () => {+ const toolContext = ChatBridgeToolContext.fromRequest({+ model: 'm',+ input: [],+ tools: [+ { type: 'function', name: 'apply' },+ { type: 'custom', name: 'apply_patch' },+ ],+ });+ const translator = new ChatSseTranslator('m', { toolContext });++ const first = translator.push({+ id: 'ambiguous-tool-name',+ choices: [{+ delta: {+ tool_calls: [{+ index: 0,+ id: 'call_ambiguous',+ function: { name: 'apply', arguments: '{"input":"diff"}' },+ }],+ },+ }],+ }) as Array<Record<string, unknown>>;+ expect(first.filter((event) => event.type === 'response.output_item.added')).toEqual([]);++ const out = [+ ...first,+ ...translator.push({+ choices: [{+ delta: { tool_calls: [{ index: 0, function: { name: '_patch' } }] },+ finish_reason: 'tool_calls',+ }],+ }),+ ...translator.finish(),+ ] as Array<Record<string, unknown>>;+ const completed = out.at(-1) as { response: { output: Array<Record<string, unknown>> } };+ expect(completed.response.output).toContainEqual(expect.objectContaining({+ type: 'custom_tool_call',+ name: 'apply_patch',+ input: 'diff',+ }));+ });++ it('extracts reasoning_details and inline think blocks without leaking tags', () => {+ const translator = new ChatSseTranslator('m', { inlineReasoning: true });+ const out = [+ ...translator.push({+ id: 'think',+ choices: [{ delta: { reasoning_details: [{ text: 'structured ' }] } }],+ }),+ ...translator.push({+ choices: [{ delta: { content: '<think>inline</think>answer' }, finish_reason: 'stop' }],+ }),+ ...translator.finish(),+ ] as Array<Record<string, unknown>>;+ const response = (out.at(-1) as { response: { output: Array<Record<string, unknown>> } }).response;+ const reasoning = response.output.filter((item) => item.type === 'reasoning');+ const message = response.output.find((item) => item.type === 'message') as {+ content: Array<{ text: string }>;+ };+ expect(reasoning.map((item) => item.summary)).toEqual([+ [{ type: 'summary_text', text: 'structured inline' }],+ ]);+ expect(message.content[0].text).toBe('answer');+ });++ it('preserves literal think tags unless the inline reasoning dialect is enabled', () => {+ const translator = new ChatSseTranslator('m');+ const out = [+ ...translator.push({+ id: 'literal-think',+ choices: [{ delta: { content: '<think>literal</think> answer' }, finish_reason: 'stop' }],+ }),+ ...translator.finish(),+ ] as Array<Record<string, unknown>>;+ const response = (out.at(-1) as { response: { output: Array<Record<string, unknown>> } }).response;+ expect(response.output.filter((item) => item.type === 'reasoning')).toEqual([]);+ expect(response.output.find((item) => item.type === 'message')).toMatchObject({+ content: [{ text: '<think>literal</think> answer' }],+ });+ });++ it('starts streamed tool items with empty arguments and emits the bytes as deltas', () => {+ const translator = new ChatSseTranslator('m');+ const out = [+ ...translator.push({+ id: 'tool-prefix',+ choices: [{+ delta: {+ tool_calls: [{+ index: 0,+ id: 'call_prefix',+ function: { name: 'Bash', arguments: '{"cmd":' },+ }],+ },+ }],+ }),+ ...translator.push({+ choices: [{ delta: { tool_calls: [{ index: 0, function: { arguments: '"pwd"}' } }] }, finish_reason: 'tool_calls' }],+ }),+ ...translator.finish(),+ ] as Array<Record<string, unknown>>;+ const added = out.find((event) => event.type === 'response.output_item.added') as { item: { arguments: string } };+ const deltas = out.filter((event) => event.type === 'response.function_call_arguments.delta') as Array<{ delta: string }>;+ expect(added.item.arguments).toBe('');+ expect(deltas.map((event) => event.delta).join('')).toBe('{"cmd":"pwd"}');+ });++ it('normalizes citations and emits complete zero usage when the provider omits usage', () => {+ const translator = new ChatSseTranslator('m');+ const out = [+ ...translator.push({+ id: 'cite',+ choices: [{+ delta: {+ content: 'answer',+ annotations: [{ type: 'url_citation', url: 'https://example.com', title: 'Source' }],+ },+ finish_reason: 'stop',+ }],+ }),+ ...translator.finish(),+ ] as Array<Record<string, unknown>>;+ const response = (out.at(-1) as { response: {+ usage: Record<string, unknown>;+ output: Array<{ type: string; content?: Array<{ annotations?: unknown[] }> }>;+ } }).response;+ expect(response.usage).toEqual({+ input_tokens: 0,+ output_tokens: 0,+ total_tokens: 0,+ input_tokens_details: { cached_tokens: 0 },+ output_tokens_details: { reasoning_tokens: 0 },+ });+ expect(response.output.find((item) => item.type === 'message')?.content?.[0]?.annotations).toEqual([+ {+ type: 'url_citation',+ url: 'https://example.com',+ title: 'Source',+ start_index: 0,+ end_index: 0,+ },+ ]);+ });++ it('preserves the provider service tier in the terminal Responses object', () => {+ const translator = new ChatSseTranslator('m');+ const out = [+ ...translator.push({+ id: 'service-tier',+ service_tier: 'flex',+ choices: [{ delta: { content: 'answer' }, finish_reason: 'stop' }],+ }),+ ...translator.finish(),+ ] as Array<Record<string, unknown>>;++ const completed = out.at(-1) as { response: { service_tier?: string } };+ expect(completed.response.service_tier).toBe('flex');+ });});diff --git a/packages/responses-chat-bridge/src/__tests__/handler.test.ts b/packages/responses-chat-bridge/src/__tests__/handler.test.tsindex 2a5de4afaf..3931015a38 100644--- a/packages/responses-chat-bridge/src/__tests__/handler.test.ts+++ b/packages/responses-chat-bridge/src/__tests__/handler.test.ts@@ -144,7 +144,7 @@ describe('createResponsesChatHandler', () => {expect(buildHeaders).not.toHaveBeenCalled();});- it('posts capability-gated image_url content without logging image data', async () => {+ it('posts image_url content by default without logging image data', async () => {const imageUrl = 'data:image/png;base64,SECRET_IMAGE_DATA';const logger = {debug: vi.fn(),@@ -298,33 +298,6 @@ describe('createResponsesChatHandler', () => {expect(buildHeaders).not.toHaveBeenCalled();});- it('keeps image input disabled by default and rejects it before credentials or network', async () => {- const buildHeaders = vi.fn(async () => ({ authorization: 'Bearer secret' }));- const fetchImpl = vi.fn<typeof fetch>();- const handler = createResponsesChatHandler({- upstreamBase: 'https://provider.example/v1',- buildHeaders,- }, { fetchImpl });- const res = new FakeResponse();-- await handler.handle({- parsedBody: {- model: 'm',- input: [{- type: 'message',- role: 'user',- content: [{ type: 'input_image', image_url: 'data:image/png;base64,eA==' }],- }],- },- res: res as never,- });-- expect(res.status).toBe(400);- expect(res.chunks.join('')).toContain('unsupported_feature');- expect(buildHeaders).not.toHaveBeenCalled();- expect(fetchImpl).not.toHaveBeenCalled();- });-it('runs the provider error callback before returning the original status', async () => {const order: string[] = [];const handler = createResponsesChatHandler({@@ -352,4 +325,120 @@ describe('createResponsesChatHandler', () => {expect(res.status).toBe(429);expect(res.chunks.join('')).toContain('slow down');});++ it('translates non-streaming Chat JSON into a non-streaming Responses response', async () => {+ const fetchImpl = vi.fn(async () => new Response(JSON.stringify({+ id: 'chat_json',+ model: 'real-model',+ choices: [{+ message: { role: 'assistant', content: 'hello' },+ finish_reason: 'stop',+ }],+ usage: { prompt_tokens: 2, completion_tokens: 1, total_tokens: 3 },+ }), { status: 200, headers: { 'content-type': 'application/json' } })) as typeof fetch;+ const handler = createResponsesChatHandler({+ upstreamBase: 'https://provider.example/v1',+ buildHeaders: async () => ({}),+ }, { fetchImpl });+ const res = new FakeResponse();+ await handler.handle({+ parsedBody: { model: 'm', input: 'hi', stream: false },+ res: res as never,+ });+ const response = JSON.parse(res.chunks.join('')) as {+ status: string;+ output: Array<{ type: string; content?: Array<{ text: string }> }>;+ usage: { total_tokens: number };+ };+ expect(res.status).toBe(200);+ expect(response.status).toBe('completed');+ expect(response.output[0].content?.[0].text).toBe('hello');+ expect(response.usage.total_tokens).toBe(3);+ });++ it('returns only the terminal Responses object when a non-streaming request receives SSE', async () => {+ const fetchImpl = vi.fn(async () => streamResponse([+ { id: 'chat_sse_json', choices: [{ delta: { content: 'hello ' } }] },+ { id: 'chat_sse_json', choices: [{ delta: { content: 'world' } }] },+ { id: 'chat_sse_json', choices: [{ delta: {}, finish_reason: 'stop' }] },+ ])) as typeof fetch;+ const handler = createResponsesChatHandler({+ upstreamBase: 'https://provider.example/v1',+ buildHeaders: async () => ({}),+ }, { fetchImpl });+ const res = new FakeResponse();+ await handler.handle({+ parsedBody: { model: 'm', input: 'hi', stream: false },+ res: res as never,+ });+ const response = JSON.parse(res.chunks.join('')) as {+ status: string;+ output: Array<{ type: string; content?: Array<{ text: string }> }>;+ };+ expect(res.status).toBe(200);+ expect(response.status).toBe('completed');+ expect(response.output.find((item) => item.type === 'message')?.content?.[0]?.text).toBe('hello world');+ expect(res.chunks.join('')).not.toContain('response.output_text.delta');+ });++ it('adapts a JSON response even when a streaming provider ignores stream=true', async () => {+ const fetchImpl = vi.fn(async () => new Response(JSON.stringify({+ id: 'chat_json',+ choices: [{ message: { role: 'assistant', content: 'hello' }, finish_reason: 'stop' }],+ }), { status: 200, headers: { 'content-type': 'application/json' } })) as typeof fetch;+ const handler = createResponsesChatHandler({+ upstreamBase: 'https://provider.example/v1',+ buildHeaders: async () => ({}),+ }, { fetchImpl });+ const res = new FakeResponse();+ await handler.handle({+ parsedBody: { model: 'm', input: 'hi' },+ res: res as never,+ });+ expect(res.status).toBe(200);+ expect(res.chunks.join('')).toContain('event: response.completed');+ });++ it('cancels an oversized non-SSE body after parsing the bounded JSON prefix', async () => {+ const json = JSON.stringify({+ id: 'chat_bounded',+ choices: [{ message: { role: 'assistant', content: 'bounded' }, finish_reason: 'stop' }],+ });+ const encoder = new TextEncoder();+ const padding = new Uint8Array(1024 * 1024).fill(0x20);+ let paddingChunks = 0;+ const cancel = vi.fn();+ const body = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(encoder.encode(json));+ },+ pull(controller) {+ paddingChunks += 1;+ if (paddingChunks <= 17) controller.enqueue(padding);+ else controller.close();+ },+ cancel,+ });+ const fetchImpl = vi.fn(async () => new Response(body, {+ status: 200,+ headers: { 'content-type': 'application/json' },+ })) as typeof fetch;+ const handler = createResponsesChatHandler({+ upstreamBase: 'https://provider.example/v1',+ buildHeaders: async () => ({}),+ }, { fetchImpl });+ const res = new FakeResponse();++ await handler.handle({+ parsedBody: { model: 'm', input: 'hi', stream: false },+ res: res as never,+ });++ const response = JSON.parse(res.chunks.join('')) as {+ output: Array<{ content?: Array<{ text?: string }> }>;+ };+ expect(res.status).toBe(200);+ expect(response.output[0].content?.[0].text).toBe('bounded');+ expect(cancel).toHaveBeenCalledOnce();+ });});diff --git a/packages/responses-chat-bridge/src/__tests__/translate-request.test.ts b/packages/responses-chat-bridge/src/__tests__/translate-request.test.tsindex 5bc1e0983e..7b887dadb0 100644--- a/packages/responses-chat-bridge/src/__tests__/translate-request.test.ts+++ b/packages/responses-chat-bridge/src/__tests__/translate-request.test.ts@@ -1,6 +1,10 @@import { describe, expect, it } from 'vitest';-import { translateResponsesRequest } from '../translate-request.js';+import {+ translateResponsesRequest,+ translateResponsesRequestWithContext,+} from '../translate-request.js';+import { ChatBridgeToolContext } from '../tool-context.js';import { UnsupportedResponsesFeatureError, type ResponsesRequest } from '../types.js';function base(overrides: Partial<ResponsesRequest> = {}): ResponsesRequest {@@ -71,6 +75,43 @@ describe('translateResponsesRequest', () => {expect(keep.messages[1]).toEqual({ role: 'developer', content: 'mid-conversation dev note' });});+ it.each([+ { type: 'input_image', image_url: 'https://example.com/image.png' },+ { type: 'input_file', file_data: 'data:text/plain;base64,eA==' },+ { type: 'input_audio', input_audio: { data: 'YQ==', format: 'wav' } },+ { type: 'input_text' },+ { type: 'unknown_part' },+ ])('rejects unsupported or malformed instruction parts: $type', (part) => {+ expect(() => translateResponsesRequest(base({ instructions: [part] }))).toThrow(+ /instructions\[0\]/,+ );+ });++ it('keeps probing when a collision occupies the first custom fallback name', () => {+ const fallback = ChatBridgeToolContext.fromRequest({+ model: 'm',+ input: [],+ tools: [+ { type: 'function', name: 'foo' },+ { type: 'custom', name: 'foo' },+ ],+ }).chatNameForResponse('foo', undefined, 'custom');+ const context = ChatBridgeToolContext.fromRequest({+ model: 'm',+ input: [],+ tools: [+ { type: 'function', name: 'foo' },+ { type: 'function', name: fallback },+ { type: 'custom', name: 'foo' },+ ],+ });++ const customName = context.chatNameForResponse('foo', undefined, 'custom');+ expect(customName).not.toBe(fallback);+ expect(context.lookupChatName(customName)).toEqual(expect.objectContaining({ kind: 'custom' }));+ expect(context.chatTools).toHaveLength(3);+ });+it('converts assistant calls and tool outputs while keeping call ids', () => {const out = translateResponsesRequest(base({input: [@@ -240,6 +281,15 @@ describe('translateResponsesRequest', () => {}],},{ role: 'tool', tool_call_id: 'custom_1', content: 'done\nok' },+ {+ role: 'assistant',+ content: null,+ tool_calls: [{+ id: 'function_1',+ type: 'function',+ function: { name: 'unknown_tool', arguments: '{}' },+ }],+ },{ role: 'tool', tool_call_id: 'function_1', content: '{"ok":true}' },]);});@@ -299,8 +349,7 @@ describe('translateResponsesRequest', () => {}))).toThrowError(UnsupportedResponsesFeatureError);});- it('drops replayed Codex tool_search items without breaking tool-call merging', () => {- const dropped: Array<[string, number]> = [];+ it('round-trips replayed Codex tool_search items without breaking tool-call merging', () => {const out = translateResponsesRequest(base({input: [{ type: 'message', role: 'user', content: 'hi' },@@ -315,7 +364,7 @@ describe('translateResponsesRequest', () => {{ type: 'tool_search_call_output', call_id: 'ts_1', output: {} },{ type: 'function_call_output', call_id: 'call_1', output: 'ok' },],- }), { onDroppedInputItem: (type, index) => dropped.push([type, index]) });+ }));expect(out.messages).toEqual([{ role: 'user', content: 'hi' },@@ -323,20 +372,44 @@ describe('translateResponsesRequest', () => {role: 'assistant',content: null,tool_calls: [+ { id: 'ts_1', type: 'function', function: { name: 'tool_search', arguments: '{}' } },{ id: 'call_1', type: 'function', function: { name: 'shell', arguments: '{"cmd":"ls"}' } },],},+ { role: 'tool', tool_call_id: 'ts_1', content: '{}' },{ role: 'tool', tool_call_id: 'call_1', content: 'ok' },]);- expect(dropped).toEqual([- ['tool_search_call', 1],- ['tool_search_output', 3],- ['tool_search_call_output', 4],+ });++ it('serializes tools from tool_search outputs when output is absent', () => {+ const tools = [{+ type: 'function',+ name: 'search_result',+ parameters: { type: 'object' },+ }];+ const out = translateResponsesRequest(base({+ input: [+ { type: 'tool_search_call', id: 'ts_1' },+ { type: 'tool_search_output', id: 'ts_1', tools },+ ],+ }));+ expect(out.messages).toEqual([+ {+ role: 'assistant',+ content: null,+ tool_calls: [+ { id: 'ts_1', type: 'function', function: { name: 'tool_search', arguments: '{}' } },+ ],+ },+ {+ role: 'tool',+ tool_call_id: 'ts_1',+ content: JSON.stringify(tools),+ },]);});- it('does not let dropped tool_search items split assistant merging', () => {- const dropped: string[] = [];+ it('does not let replayed tool_search items split assistant merging', () => {const out = translateResponsesRequest(base({input: [{@@ -362,12 +435,20 @@ describe('translateResponsesRequest', () => {{ type: 'function_call_output', call_id: 'call_1', output: 'a' },{ type: 'function_call_output', call_id: 'call_2', output: 'b' },],- }), { onDroppedInputItem: (type) => dropped.push(type) });+ }));expect(out.messages).toEqual([{role: 'assistant',content: 'planning',+ tool_calls: [+ { id: 'ts_1', type: 'function', function: { name: 'tool_search', arguments: '{}' } },+ ],+ },+ { role: 'tool', tool_call_id: 'ts_1', content: '{}' },+ {+ role: 'assistant',+ content: null,tool_calls: [{ id: 'call_1', type: 'function', function: { name: 'shell', arguments: '{"cmd":"ls"}' } },{ id: 'call_2', type: 'function', function: { name: 'shell', arguments: '{"cmd":"pwd"}' } },@@ -376,10 +457,9 @@ describe('translateResponsesRequest', () => {{ role: 'tool', tool_call_id: 'call_1', content: 'a' },{ role: 'tool', tool_call_id: 'call_2', content: 'b' },]);- expect(dropped).toEqual(['tool_search_call', 'tool_search_output', 'tool_search_call_output']);});- it('translates capability-gated Kimi user images and preserves replayed history order', () => {+ it('translates user images when the upstream capability is enabled and preserves replayed history order', () => {const imageUrl = 'data:image/png;base64,aW1hZ2U=';const out = translateResponsesRequest(base({input: [@@ -458,29 +538,35 @@ describe('translateResponsesRequest', () => {{ type: 'input_text', text: ' world' },],}],- }), { capabilities: { imageInput: 'image_url' } });+ }));expect(out.messages).toEqual([{ role: 'user', content: 'hello world' }]);});- it('keeps invalid or non-user image inputs fail-closed even with image capability', () => {- const capabilities = { imageInput: 'image_url' as const };+ it('keeps invalid or non-user image inputs fail-closed', () => {expect(() => translateResponsesRequest(base({input: [{ type: 'message', role: 'user', content: [{ type: 'input_image', file_id: 'file_1' }] }],- }), { capabilities })).toThrow("input content part 'input_image'");+ }))).toThrow("input content part 'input_image'");+ expect(() => translateResponsesRequest(base({+ input: [{+ type: 'message',+ role: 'user',+ content: [{ type: 'input_image', file_id: 'file_1', image_url: 'https://example.com/image.png' }],+ }],+ }), { capabilities: { imageInput: 'image_url' } })).toThrow('input_image.file_id');expect(() => translateResponsesRequest(base({input: [{ type: 'message', role: 'user', content: [{ type: 'input_image' }] }],- }), { capabilities })).toThrow("input content part 'input_image'");+ }))).toThrow("input content part 'input_image'");expect(() => translateResponsesRequest(base({input: [{type: 'message',role: 'assistant',content: [{ type: 'input_image', image_url: 'data:image/png;base64,eA==' }],}],- }), { capabilities })).toThrow("input content part 'input_image'");+ }))).toThrow("input content part 'input_image'");expect(() => translateResponsesRequest(base({input: [{ type: 'message', role: 'user', content: [{ type: 'input_audio', audio_url: 'x' }] }],- }), { capabilities })).toThrow("input content part 'input_audio'");+ }))).toThrow("input content part 'input_audio'");});it('allows normalized user-like roles such as latest_reminder to carry images', () => {@@ -499,7 +585,7 @@ describe('translateResponsesRequest', () => {}]);});- it('drops Codex built-in tools (namespace/web_search) but keeps standard function tools', () => {+ it('flattens namespace tools, drops unsupported built-ins, and keeps standard functions', () => {const dropped: Array<[string, number]> = [];const out = translateResponsesRequest(base({tools: [@@ -508,11 +594,18 @@ describe('translateResponsesRequest', () => {{ type: 'web_search' },],}), { onDroppedTool: (type, index) => dropped.push([type, index]) });- // 只保留标准 function 工具;Codex 内建工具剥掉(降级),不再让整条请求 fail。+ // namespace 子工具展平为 Chat function;真正没有 Chat 等价物的内建工具仍降级丢弃。expect(out.tools).toEqual([{ type: 'function', function: { name: 'Bash', parameters: { type: 'object' } } },+ {+ type: 'function',+ function: {+ name: 'multi_agent_v1__close_agent',+ parameters: { type: 'object', properties: {} },+ },+ },]);- expect(dropped).toEqual([['namespace', 1], ['web_search', 2]]);+ expect(dropped).toEqual([['web_search', 2]]);});it('omits the tools field entirely when every tool is a dropped built-in', () => {@@ -520,9 +613,482 @@ describe('translateResponsesRequest', () => {expect(out.tools).toBeUndefined();});- it('still fail-closes on unsupported input content (context must not be silently dropped)', () => {+ it('preserves image detail from Responses content parts', () => {+ const out = translateResponsesRequest(base({+ input: [{+ type: 'message',+ role: 'user',+ content: [{+ type: 'input_image',+ image_url: { url: 'https://example.com/image.png', detail: 'high' },+ }],+ }],+ }), { capabilities: { imageInput: 'image_url' } });++ expect(out.messages).toEqual([{+ role: 'user',+ content: [{+ type: 'image_url',+ image_url: { url: 'https://example.com/image.png', detail: 'high' },+ }],+ }]);+ });++ it('maps custom, namespace, and tool-search declarations into reversible Chat tools', () => {+ const out = translateResponsesRequest(base({+ tools: [+ { type: 'custom', name: 'apply_patch', description: 'edit files' },+ {+ type: 'namespace',+ name: 'mcp',+ tools: [{ type: 'function', name: 'query', parameters: { type: 'object' } }],+ },+ { type: 'tool_search' },+ ],+ tool_choice: { type: 'custom', name: 'apply_patch' },+ }));+ expect(out.tools?.map((tool) => tool.function.name)).toEqual([+ 'apply_patch',+ 'mcp__query',+ 'tool_search',+ ]);+ expect(out.tools?.[0].function.parameters).toEqual({+ type: 'object',+ properties: { input: { type: 'string', description: expect.any(String) } },+ required: ['input'],+ });+ expect(out.tool_choice).toEqual({+ type: 'function',+ function: { name: 'apply_patch' },+ });+ });++ it('keeps the built-in tool-search adapter distinct from a user tool_search name', () => {+ const out = translateResponsesRequest(base({+ tools: [+ { type: 'function', name: 'tool_search', parameters: { type: 'object' } },+ { type: 'tool_search' },+ ],+ input: [{ type: 'tool_search_call', id: 'ts_1' }],+ }));+ const toolNames = out.tools?.map((tool) => tool.function.name) ?? [];+ expect(toolNames).toHaveLength(2);+ expect(new Set(toolNames).size).toBe(2);+ expect(toolNames).toContain('tool_search');+ expect((out.messages[0] as {+ tool_calls?: Array<{ function: { name: string } }>;+ }).tool_calls?.[0]?.function.name).not.toBe('tool_search');+ });++ it('keeps function and custom tools with the same name distinct', () => {+ const { request, toolContext } = translateResponsesRequestWithContext(base({+ tools: [+ { type: 'function', name: 'shared', parameters: { type: 'object' } },+ { type: 'custom', name: 'shared' },+ ],+ tool_choice: { type: 'custom', name: 'shared' },+ input: [{ type: 'custom_tool_call', call_id: 'c1', name: 'shared', input: 'raw' }],+ }));+ const toolNames = request.tools?.map((tool) => tool.function.name) ?? [];+ const customName = (request.tool_choice as {+ function: { name: string };+ }).function.name;+ expect(toolNames).toHaveLength(2);+ expect(new Set(toolNames).size).toBe(2);+ expect(toolNames).toContain('shared');+ expect(customName).not.toBe('shared');+ expect((request.messages[0] as {+ tool_calls?: Array<{ function: { name: string } }>;+ }).tool_calls?.[0]?.function.name).toBe(customName);+ expect(toolContext.lookupChatName(customName)?.kind).toBe('custom');+ });++ it('collects declarations only from top-level tool-search outputs', () => {+ const out = translateResponsesRequest(base({+ input: [+ { type: 'function_call', call_id: 'c1', name: 'inspect', arguments: '{}' },+ {+ type: 'function_call_output',+ call_id: 'c1',+ output: {+ nestedCall: { type: 'custom_tool_call', name: 'injected_custom' },+ nestedSearch: {+ type: 'tool_search_output',+ tools: [{ type: 'function', name: 'injected_function' }],+ },+ },+ },+ { type: 'tool_search_call', id: 'ts_1' },+ {+ type: 'tool_search_output',+ id: 'ts_1',+ tools: [{ type: 'function', name: 'loaded_function' }],+ },+ ],+ }));+ expect(out.tools?.map((tool) => tool.function.name)).toEqual([+ 'tool_search',+ 'loaded_function',+ ]);+ });++ it('preserves namespaces when cataloging custom tools from replayed history', () => {+ const { request, toolContext } = translateResponsesRequestWithContext(base({+ input: [{+ type: 'custom_tool_call',+ call_id: 'c1',+ namespace: 'mcp',+ name: 'exec',+ input: 'raw',+ }],+ }));+ expect(request.tools?.[0].function.name).toBe('mcp__exec');+ expect((request.messages[0] as {+ tool_calls?: Array<{ function: { name: string } }>;+ }).tool_calls?.[0]?.function.name).toBe('mcp__exec');+ expect(toolContext.lookupChatName('mcp__exec')).toMatchObject({+ kind: 'custom',+ name: 'exec',+ namespace: 'mcp',+ });+ });++ it('gates replayed reasoning history by provider capability', () => {+ const source = base({+ input: [+ { type: 'reasoning', summary: [{ type: 'summary_text', text: 'plan ' }] },+ { type: 'function_call', call_id: 'c1', name: 'Bash', arguments: '{}' },+ { type: 'function_call_output', call_id: 'c1', output: 'ok' },+ { type: 'reasoning', content: [{ type: 'reasoning_text', text: 'finish' }] },+ { type: 'message', role: 'assistant', content: 'done' },+ ],+ });+ expect(translateResponsesRequest(source).messages).toEqual([+ {+ role: 'assistant',+ content: null,+ tool_calls: [{+ id: 'c1',+ type: 'function',+ function: { name: 'Bash', arguments: '{}' },+ }],+ },+ { role: 'tool', tool_call_id: 'c1', content: 'ok' },+ { role: 'assistant', content: 'done' },+ ]);++ const out = translateResponsesRequest(source, {+ capabilities: { reasoningHistoryField: 'reasoning_content' },+ });+ expect(out.messages).toEqual([+ {+ role: 'assistant',+ content: null,+ reasoning_content: 'plan ',+ tool_calls: [{+ id: 'c1',+ type: 'function',+ function: { name: 'Bash', arguments: '{}' },+ }],+ },+ { role: 'tool', tool_call_id: 'c1', content: 'ok' },+ { role: 'assistant', content: 'done', reasoning_content: 'finish' },+ ]);+ });++ it('repairs a dangling tool round without moving the following user barrier ahead of results', () => {+ const out = translateResponsesRequest(base({+ input: [+ { type: 'function_call', call_id: 'c1', name: 'Bash', arguments: '{}' },+ { type: 'message', role: 'user', content: 'continue' },+ ],+ }));+ expect(out.messages).toEqual([+ {+ role: 'assistant',+ content: null,+ tool_calls: [{+ id: 'c1',+ type: 'function',+ function: { name: 'Bash', arguments: '{}' },+ }],+ },+ {+ role: 'tool',+ tool_call_id: 'c1',+ content: expect.stringContaining('execution status is unknown'),+ },+ { role: 'user', content: 'continue' },+ ]);+ });++ it('keeps real tool outputs when a later assistant round reuses the same call id', () => {+ const out = translateResponsesRequest(base({+ input: [+ { type: 'function_call', call_id: 'c1', name: 'Bash', arguments: '{"round":1}' },+ { type: 'function_call_output', call_id: 'c1', output: 'first result' },+ { type: 'function_call', call_id: 'c1', name: 'Bash', arguments: '{"round":2}' },+ { type: 'function_call_output', call_id: 'c1', output: 'second result' },+ ],+ }));++ expect(out.messages.filter((message) => message.role === 'tool')).toEqual([+ { role: 'tool', tool_call_id: 'c1', content: 'first result' },+ { role: 'tool', tool_call_id: 'c1', content: 'second result' },+ ]);+ expect(out.messages).not.toEqual(expect.arrayContaining([+ expect.objectContaining({ content: expect.stringContaining('execution status is unknown') }),+ ]));+ });++ it('ignores a late duplicate from an older round while a deferred barrier opens a new round', () => {+ const out = translateResponsesRequest(base({+ input: [+ { type: 'function_call', call_id: 'old_1', name: 'Bash', arguments: '{"round":1}' },+ { type: 'function_call', call_id: 'old_2', name: 'Bash', arguments: '{"round":1,"part":2}' },+ { type: 'function_call_output', call_id: 'old_1', output: 'first result' },+ { type: 'message', role: 'user', content: 'continue' },+ { type: 'function_call', call_id: 'new_1', name: 'Bash', arguments: '{"round":2}' },+ { type: 'function_call_output', call_id: 'old_1', output: 'late duplicate' },+ { type: 'function_call_output', call_id: 'new_1', output: 'second result' },+ ],+ }));++ expect(out.messages.filter((message) => message.role === 'tool')).toEqual([+ { role: 'tool', tool_call_id: 'old_1', content: 'first result' },+ {+ role: 'tool',+ tool_call_id: 'old_2',+ content: expect.stringContaining('execution status is unknown'),+ },+ { role: 'tool', tool_call_id: 'new_1', content: 'second result' },+ ]);+ expect(out.messages).not.toEqual(expect.arrayContaining([+ { role: 'tool', tool_call_id: 'old_1', content: 'late duplicate' },+ ]));+ });++ it('ignores late results for synthesized missing calls without closing a newer tool round', () => {+ const out = translateResponsesRequest(base({+ input: [+ { type: 'function_call', call_id: 'old_1', name: 'Bash', arguments: '{"round":1}' },+ { type: 'message', role: 'user', content: 'continue' },+ { type: 'function_call', call_id: 'new_1', name: 'Bash', arguments: '{"round":2}' },+ { type: 'function_call_output', call_id: 'old_1', output: 'late result' },+ { type: 'function_call_output', call_id: 'new_1', output: 'new result' },+ ],+ }));++ expect(out.messages.filter((message) => message.role === 'tool')).toEqual([+ {+ role: 'tool',+ tool_call_id: 'old_1',+ content: expect.stringContaining('execution status is unknown'),+ },+ { role: 'tool', tool_call_id: 'new_1', content: 'new result' },+ ]);+ expect(out.messages).not.toEqual(expect.arrayContaining([+ { role: 'tool', tool_call_id: 'old_1', content: 'late result' },+ expect.objectContaining({+ role: 'tool',+ tool_call_id: 'new_1',+ content: expect.stringContaining('execution status is unknown'),+ }),+ ]));+ });++ it('normalizes synthesized orphan tool calls for reasoning and Gemini providers', () => {+ const out = translateResponsesRequest(base({+ input: [+ { type: 'function_call_output', call_id: 'orphan_1', output: 'ok' },+ ],+ }), {+ capabilities: {+ toolCallReasoningPlaceholder: true,+ googleThoughtSignaturePlaceholder: true,+ },+ });+ expect(out.messages[0]).toMatchObject({+ role: 'assistant',+ content: null,+ reasoning_content: 'tool call',+ tool_calls: [{+ id: 'orphan_1',+ extra_content: {+ google: { thought_signature: 'skip_thought_signature_validator' },+ },+ }],+ });+ });++ it('converts file/audio input and moves tool-result media into a user multimodal message', () => {+ const out = translateResponsesRequest(base({+ input: [+ {+ type: 'message',+ role: 'user',+ content: [+ { type: 'input_file', file_data: 'BASE64_FILE', filename: 'notes.txt' },+ { type: 'input_audio', input_audio: { data: 'BASE64', format: 'wav' } },+ ],+ },+ { type: 'function_call', call_id: 'c1', name: 'inspect', arguments: '{}' },+ {+ type: 'function_call_output',+ call_id: 'c1',+ output: [{ type: 'input_text', text: 'see' }, { type: 'input_image', image_url: 'data:image/png;base64,x' }],+ },+ ],+ }), {+ capabilities: {+ imageInput: 'image_url',+ fileInput: 'file',+ audioInput: 'input_audio',+ },+ });+ expect(out.messages).toContainEqual({+ role: 'tool',+ tool_call_id: 'c1',+ content: 'see\n[media moved to the following user message]',+ });+ expect(out.messages).toContainEqual({+ role: 'user',+ content: [+ { type: 'text', text: 'Media returned by the preceding tool result:' },+ { type: 'image_url', image_url: { url: 'data:image/png;base64,x' } },+ ],+ });+ expect(out.messages[0]).toEqual({+ role: 'user',+ content: [+ { type: 'file', file: { file_data: 'BASE64_FILE', filename: 'notes.txt' } },+ { type: 'input_audio', input_audio: { data: 'BASE64', format: 'wav' } },+ ],+ });+ });++ it('rejects provider-scoped input_file ids instead of forwarding them cross-provider', () => {expect(() => translateResponsesRequest(base({- input: [{ type: 'message', role: 'user', content: [{ type: 'input_image', image_url: 'x' }] }],- }))).toThrow("input content part 'input_image'");+ input: [{+ type: 'message',+ role: 'user',+ content: [{ type: 'input_file', file_id: 'file_1', filename: 'notes.txt' }],+ }],+ }), { capabilities: { fileInput: 'file' } })).toThrow('input_file.file_id');+ });++ it('fails closed for file and audio inputs unless each capability is enabled', () => {+ expect(() => translateResponsesRequest(base({+ input: [{+ type: 'message',+ role: 'user',+ content: [{ type: 'input_file', file_data: 'BASE64', filename: 'notes.txt' }],+ }],+ }))).toThrow("input content part 'input_file'");+ expect(() => translateResponsesRequest(base({+ input: [{+ type: 'message',+ role: 'user',+ content: [{ type: 'input_audio', input_audio: { data: 'BASE64', format: 'wav' } }],+ }],+ }))).toThrow("input content part 'input_audio'");+ });++ it('rejects file-backed images in tool results instead of silently dropping the file id', () => {+ expect(() => translateResponsesRequest(base({+ input: [+ { type: 'function_call', call_id: 'c1', name: 'inspect', arguments: '{}' },+ {+ type: 'function_call_output',+ call_id: 'c1',+ output: [{ type: 'input_image', file_id: 'file_1', image_url: 'https://example.com/image.png' }],+ },+ ],+ }), { capabilities: { imageInput: 'image_url' } })).toThrow('input_image.file_id');+ });++ it('rejects unsupported media inside tool results instead of serializing it as text', () => {+ for (const part of [+ { type: 'input_image', image_url: 'https://example.com/image.png' },+ { type: 'input_file', file_data: 'BASE64' },+ { type: 'input_audio', input_audio: { data: 'BASE64', format: 'wav' } },+ ]) {+ expect(() => translateResponsesRequest(base({+ input: [+ { type: 'function_call', call_id: 'c1', name: 'inspect', arguments: '{}' },+ { type: 'function_call_output', call_id: 'c1', output: [part] },+ ],+ }))).toThrow(part.type);+ }+ });++ it('does not reject non-media metadata with a media-like type', () => {+ const metadata = { type: 'image', description: 'output schema metadata' };+ const out = translateResponsesRequest(base({+ input: [+ { type: 'function_call', call_id: 'c1', name: 'inspect', arguments: '{}' },+ { type: 'function_call_output', call_id: 'c1', output: { metadata } },+ ],+ }));+ expect(out.messages).toContainEqual({+ role: 'tool',+ tool_call_id: 'c1',+ content: JSON.stringify({ metadata }),+ });+ });++ it('forwards only capability-approved Chat tuning fields and maps reasoning dialects', () => {+ const out = translateResponsesRequest(base({+ temperature: 0.2,+ top_p: 0.8,+ response_format: { type: 'json_object' },+ reasoning: { effort: 'high' },+ }), {+ capabilities: {+ passthroughFields: ['temperature', 'top_p', 'response_format'],+ reasoningField: 'enable_thinking',+ reasoningEffortMap: { high: true },+ },+ });+ expect(out.temperature).toBe(0.2);+ expect(out.top_p).toBe(0.8);+ expect(out.response_format).toEqual({ type: 'json_object' });+ expect(out.enable_thinking).toBe(true);+ expect(out).not.toHaveProperty('frequency_penalty');+ });++ it('falls back to the original reasoning effort for string dialects when a boolean map is supplied', () => {+ const out = translateResponsesRequest(base({+ reasoning: { effort: 'high' },+ }), {+ capabilities: {+ reasoningField: 'reasoning_effort',+ reasoningEffortMap: { high: true },+ },+ });+ expect(out.reasoning_effort).toBe('high');+ });++ it('converts Responses json_schema text.format to Chat response_format shape', () => {+ const out = translateResponsesRequest(base({+ text: {+ format: {+ type: 'json_schema',+ name: 'answer',+ description: 'structured answer',+ schema: { type: 'object', properties: { value: { type: 'string' } } },+ strict: true,+ },+ },+ }), { capabilities: { passthroughFields: ['response_format'] } });+ expect(out.response_format).toEqual({+ type: 'json_schema',+ json_schema: {+ name: 'answer',+ description: 'structured answer',+ schema: { type: 'object', properties: { value: { type: 'string' } } },+ strict: true,+ },+ });});});diff --git a/packages/responses-chat-bridge/src/chat-sse-translator.ts b/packages/responses-chat-bridge/src/chat-sse-translator.tsindex e3616f7768..0dd94c3415 100644--- a/packages/responses-chat-bridge/src/chat-sse-translator.ts+++ b/packages/responses-chat-bridge/src/chat-sse-translator.ts@@ -1,5 +1,7 @@import { createHash } from 'node:crypto';+import type { ChatBridgeToolContext } from './tool-context.js';+interface ToolState {outputIndex: number;itemId: string;@@ -11,12 +13,38 @@ interface ToolState {done: boolean;}+interface ReasoningState {+ outputIndex: number;+ itemId: string;+ text: string;+ added: boolean;+ done: boolean;+}+interface UsageShape {prompt_tokens?: number;completion_tokens?: number;total_tokens?: number;+ input_tokens?: number;+ output_tokens?: number;prompt_tokens_details?: { cached_tokens?: number };+ input_tokens_details?: { cached_tokens?: number };completion_tokens_details?: { reasoning_tokens?: number };+ output_tokens_details?: { reasoning_tokens?: number };+}++interface ResponseAnnotation {+ type: 'url_citation';+ url: string;+ title?: string;+ start_index: number;+ end_index: number;+}++export interface ChatSseTranslatorOptions {+ toolContext?: ChatBridgeToolContext;+ zeroUsageOnMissing?: boolean;+ inlineReasoning?: boolean;}function isPlainObject(value: unknown): value is Record<string, unknown> {@@ -36,11 +64,75 @@ function deterministicId(prefix: string, responseId: string, index: number): strreturn `${prefix}_${digest}`;}+function reasoningText(value: unknown): string {+ if (typeof value === 'string') return value;+ if (Array.isArray(value)) return value.map(reasoningText).filter(Boolean).join('');+ if (!isPlainObject(value)) return '';+ for (const key of ['reasoning_content', 'content', 'text', 'summary']) {+ const text = reasoningText(value[key]);+ if (text) return text;+ }+ return '';+}++function extractReasoning(delta: Record<string, unknown>): string {+ for (const key of ['reasoning_content', 'reasoning', 'reasoning_details']) {+ const text = reasoningText(delta[key]);+ if (text) return text;+ }+ return '';+}++function annotationsFrom(value: unknown): ResponseAnnotation[] {+ if (!Array.isArray(value)) return [];+ const result: ResponseAnnotation[] = [];+ for (const entry of value) {+ if (!isPlainObject(entry)) continue;+ const source = isPlainObject(entry.url_citation) ? entry.url_citation : entry;+ if (typeof source.url !== 'string' || !source.url) continue;+ result.push({+ type: 'url_citation',+ url: source.url,+ ...(typeof source.title === 'string' ? { title: source.title } : {}),+ start_index: typeof source.start_index === 'number' ? source.start_index : 0,+ end_index: typeof source.end_index === 'number' ? source.end_index : 0,+ });+ }+ return result;+}++function inlineCitationAnnotations(value: unknown): ResponseAnnotation[] {+ if (!Array.isArray(value)) return [];+ return value.flatMap((entry) => {+ if (typeof entry === 'string' && /^https?:\/\//.test(entry)) {+ return [{ type: 'url_citation' as const, url: entry, start_index: 0, end_index: 0 }];+ }+ return annotationsFrom([entry]);+ });+}++function customInput(argumentsText: string): string {+ try {+ const parsed: unknown = JSON.parse(argumentsText);+ if (isPlainObject(parsed) && typeof parsed.input === 'string') return parsed.input;+ } catch {+ // A provider may return a raw freeform argument buffer.+ }+ return argumentsText;+}++function toolSearchArguments(argumentsText: string): Record<string, unknown> {+ try {+ const parsed: unknown = JSON.parse(argumentsText);+ return isPlainObject(parsed) ? parsed : {};+ } catch {+ return {};+ }+}+/**- * Chat Completions SSE → OpenAI Responses SSE 状态机。- *- * tool call 以 Chat 的 `index` 为 identity;id/name/arguments 可以在不同 chunk 抵达,- * translator 会为每个 index 独立累积,避免并行工具参数串线。+ * Chat Completions SSE → OpenAI Responses SSE state machine. The state is deliberately+ * request-scoped so flattened namespace/custom/tool-search names can be restored exactly.*/export class ChatSseTranslator {private responseId = '';@@ -53,21 +145,31 @@ export class ChatSseTranslator {private messageItemId = '';private messageStarted = false;private messageDone = false;+ private textStarted = false;+ private textContentIndex: number | null = null;private text = '';+ private refusalStarted = false;+ private refusalContentIndex: number | null = null;+ private refusal = '';+ private nextMessageContentIndex = 0;private pendingFinishReason: string | null = null;private sawTerminalMarker = false;- // reasoning(思考)通道:DeepSeek/GLM 等 reasoner 在 delta.reasoning_content 里流式吐思考,- // 映射成 Responses reasoning summary 事件(reasoner 必须排在 message 之前)。- private reasoningOutputIndex: number | null = null;- private reasoningItemId = '';- private reasoningStarted = false;- private reasoningDone = false;- private reasoningText = '';+ private readonly reasoningItems: ReasoningState[] = [];private readonly tools = new Map<number, ToolState>();+ private readonly annotations: ResponseAnnotation[] = [];private usage: UsageShape | undefined;+ private serviceTier = '';+ private inlineThinkMode: 'undecided' | 'reasoning' | 'text' = 'undecided';+ private inlineThinkBuffer = '';+ private readonly toolContext?: ChatBridgeToolContext;+ private readonly zeroUsageOnMissing: boolean;+ private readonly inlineReasoning: boolean;- constructor(model: string) {+ constructor(model: string, options: ChatSseTranslatorOptions = {}) {this.model = model;+ this.toolContext = options.toolContext;+ this.zeroUsageOnMissing = options.zeroUsageOnMissing !== false;+ this.inlineReasoning = options.inlineReasoning === true;}push(raw: unknown): unknown[] {@@ -79,53 +181,51 @@ export class ChatSseTranslator {if (rawModel) this.model = rawModel;const rawCreated = numberField(raw.created);if (rawCreated) this.created = rawCreated;+ const rawServiceTier = stringField(raw.service_tier);+ if (rawServiceTier) this.serviceTier = rawServiceTier;this.ensureStarted(out);- // 部分 Chat 上游在 `200 text/event-stream` 里用顶层 `error` 帧报错(而非 HTTP 非 2xx)。- // 没有 choices,若不识别就只会被当成空帧,最终 finish() 发出"成功但空"的 completed,- // Codex 会把失败当成功轮。检测到顶层 error → 直接走 fail() 终态,把错误如实透出。if (isPlainObject(raw.error)) {- const message = stringField((raw.error as { message?: unknown }).message)- || 'provider returned an error event';+ const message = stringField(raw.error.message) || 'provider returned an error event';for (const event of this.fail(message)) out.push(event);return out;}-if (isPlainObject(raw.usage)) this.usage = raw.usage as UsageShape;const choices = Array.isArray(raw.choices) ? raw.choices : [];for (const choiceValue of choices) {if (!isPlainObject(choiceValue)) continue;- const delta = isPlainObject(choiceValue.delta) ? choiceValue.delta : {};- // 思考内容先于正文:reasoner 在 delta.reasoning_content 流式吐思考。- const reasoning = stringField(delta.reasoning_content);+ const delta = isPlainObject(choiceValue.delta)+ ? choiceValue.delta+ : isPlainObject(choiceValue.message)+ ? choiceValue.message+ : {};+ const reasoning = extractReasoning(delta);if (reasoning) {+ this.flushInlineThinkAtBoundary(out);this.ensureReasoning(out);- this.reasoningText += reasoning;- out.push({- type: 'response.reasoning_summary_text.delta',- item_id: this.reasoningItemId,- output_index: this.reasoningOutputIndex,- summary_index: 0,- delta: reasoning,- });- }- const content = stringField(delta.content);- if (content) {- this.ensureMessage(out);- this.text += content;- out.push({- type: 'response.output_text.delta',- // item_id 必填:codex 靠它把 delta 绑定到已 added 的 message output_item 做**增量渲染**;- // 缺了 codex 无法增量,只能等 output_item.done 的完整 text 一次性渲染(表现为"非流式")。- item_id: this.messageItemId,- response_id: this.responseId,- output_index: this.messageOutputIndex,- content_index: 0,- delta: content,- });+ this.appendReasoning(reasoning, out);}+ const content = typeof delta.content === 'string'+ ? delta.content+ : Array.isArray(delta.content)+ ? delta.content.map((part) => isPlainObject(part) ? stringField(part.text) : '').join('')+ : '';+ if (content) this.consumeContent(content, out);+ const refusal = stringField(delta.refusal);+ if (refusal) this.pushRefusal(refusal, out);+ this.annotations.push(+ ...annotationsFrom(delta.annotations),+ ...inlineCitationAnnotations(delta.citations),+ ...annotationsFrom(choiceValue.annotations),+ );if (Array.isArray(delta.tool_calls)) {- for (const toolCall of delta.tool_calls) this.consumeToolDelta(toolCall, out);+ this.flushInlineThinkAtBoundary(out);+ for (const [toolIndex, toolCall] of delta.tool_calls.entries()) {+ const normalizedToolCall = isPlainObject(toolCall) && typeof toolCall.index !== 'number'+ ? { ...toolCall, index: toolIndex }+ : toolCall;+ this.consumeToolDelta(normalizedToolCall, out);+ }}const finishReason = typeof choiceValue.finish_reason === 'string' ? choiceValue.finish_reason : null;if (finishReason) {@@ -136,7 +236,6 @@ export class ChatSseTranslator {return out;}- /** Mark the upstream SSE stream as having delivered its explicit terminal marker. */markTerminal(): void {this.sawTerminalMarker = true;}@@ -148,6 +247,7 @@ export class ChatSseTranslator {}const out: unknown[] = [];this.ensureStarted(out);+ this.flushInlineThinkAtBoundary(out);this.complete(this.pendingFinishReason ?? 'stop', out);return out;}@@ -156,13 +256,12 @@ export class ChatSseTranslator {if (this.terminal) return [];const out: unknown[] = [];this.ensureStarted(out);+ this.flushInlineThinkAtBoundary(out);this.closeOpenItems(out);this.terminal = true;out.push({type: 'response.failed',- response: this.responseObject('failed', {- error: { code: 'upstream_stream_error', message },- }),+ response: this.responseObject('failed', { error: { code: 'upstream_stream_error', message } }),});return out;}@@ -175,82 +274,210 @@ export class ChatSseTranslator {out.push({ type: 'response.in_progress', response: this.responseObject('in_progress') });}- private ensureReasoning(out: unknown[]): void {- if (this.reasoningStarted) return;- this.reasoningStarted = true;- this.reasoningOutputIndex = this.nextOutputIndex++;- this.reasoningItemId = deterministicId('rs', this.responseId, this.reasoningOutputIndex);+ private ensureReasoning(out: unknown[]): ReasoningState {+ const current = this.reasoningItems.find((item) => !item.done);+ if (current) return current;+ const outputIndex = this.nextOutputIndex++;+ const state: ReasoningState = {+ outputIndex,+ itemId: deterministicId('rs', this.responseId, outputIndex),+ text: '',+ added: true,+ done: false,+ };+ this.reasoningItems.push(state);out.push({type: 'response.output_item.added',response_id: this.responseId,- output_index: this.reasoningOutputIndex,- item: { id: this.reasoningItemId, type: 'reasoning', status: 'in_progress', summary: [] },+ output_index: outputIndex,+ item: { id: state.itemId, type: 'reasoning', status: 'in_progress', summary: [] },});out.push({type: 'response.reasoning_summary_part.added',- item_id: this.reasoningItemId,- output_index: this.reasoningOutputIndex,+ item_id: state.itemId,+ output_index: outputIndex,summary_index: 0,part: { type: 'summary_text', text: '' },});+ return state;}- private closeReasoning(out: unknown[]): void {- if (!this.reasoningStarted || this.reasoningDone || this.reasoningOutputIndex === null) return;- this.reasoningDone = true;+ private appendReasoning(reasoning: string, out: unknown[]): void {+ const state = this.ensureReasoning(out);+ state.text += reasoning;+ out.push({+ type: 'response.reasoning_summary_text.delta',+ item_id: state.itemId,+ output_index: state.outputIndex,+ summary_index: 0,+ delta: reasoning,+ });+ }++ private closeReasoning(state: ReasoningState, out: unknown[]): void {+ if (state.done) return;+ state.done = true;out.push({type: 'response.reasoning_summary_text.done',- item_id: this.reasoningItemId,- output_index: this.reasoningOutputIndex,+ item_id: state.itemId,+ output_index: state.outputIndex,summary_index: 0,- text: this.reasoningText,+ text: state.text,});out.push({type: 'response.reasoning_summary_part.done',- item_id: this.reasoningItemId,- output_index: this.reasoningOutputIndex,+ item_id: state.itemId,+ output_index: state.outputIndex,summary_index: 0,- part: { type: 'summary_text', text: this.reasoningText },+ part: { type: 'summary_text', text: state.text },});- // reasoning summary item 完成态刻意不带 status(对齐参考实现)。out.push({type: 'response.output_item.done',response_id: this.responseId,- output_index: this.reasoningOutputIndex,- item: { id: this.reasoningItemId, type: 'reasoning', summary: [{ type: 'summary_text', text: this.reasoningText }] },+ output_index: state.outputIndex,+ item: { id: state.itemId, type: 'reasoning', summary: [{ type: 'summary_text', text: state.text }] },+ });+ }++ private closeActiveReasoning(out: unknown[]): void {+ const current = this.reasoningItems.find((item) => !item.done);+ if (current) this.closeReasoning(current, out);+ }++ private consumeContent(content: string, out: unknown[]): void {+ if (!this.inlineReasoning) {+ this.pushText(content, out);+ return;+ }+ if (this.inlineThinkMode === 'text') {+ this.pushText(content, out);+ return;+ }+ this.inlineThinkBuffer += content;+ const trimmed = this.inlineThinkBuffer.trimStart();+ if (this.inlineThinkMode === 'undecided') {+ if ('<think>'.startsWith(trimmed.toLowerCase())) return;+ if (trimmed.toLowerCase().startsWith('<think>')) {+ this.inlineThinkMode = 'reasoning';+ this.inlineThinkBuffer = trimmed.slice('<think>'.length);+ } else {+ this.inlineThinkMode = 'text';+ const text = this.inlineThinkBuffer;+ this.inlineThinkBuffer = '';+ this.pushText(text, out);+ return;+ }+ }+ const closeTag = '</think>';+ const lower = this.inlineThinkBuffer.toLowerCase();+ const closeIndex = lower.indexOf(closeTag);+ if (closeIndex >= 0) {+ const thinking = this.inlineThinkBuffer.slice(0, closeIndex);+ if (thinking) this.appendReasoning(thinking, out);+ this.closeActiveReasoning(out);+ this.inlineThinkMode = 'text';+ const answer = this.inlineThinkBuffer.slice(closeIndex + closeTag.length);+ this.inlineThinkBuffer = '';+ if (answer) this.pushText(answer, out);+ return;+ }+ const keep = closeTag.length - 1;+ const emitLength = Math.max(0, this.inlineThinkBuffer.length - keep);+ if (emitLength > 0) {+ this.appendReasoning(this.inlineThinkBuffer.slice(0, emitLength), out);+ this.inlineThinkBuffer = this.inlineThinkBuffer.slice(emitLength);+ }+ }++ private flushInlineThinkAtBoundary(out: unknown[]): void {+ if (!this.inlineReasoning) return;+ if (this.inlineThinkMode === 'undecided') {+ if (this.inlineThinkBuffer) this.pushText(this.inlineThinkBuffer, out);+ } else if (this.inlineThinkMode === 'reasoning') {+ if (this.inlineThinkBuffer) this.appendReasoning(this.inlineThinkBuffer, out);+ }+ this.inlineThinkMode = this.inlineThinkMode === 'reasoning' ? 'text' : this.inlineThinkMode;+ this.inlineThinkBuffer = '';+ }++ private pushText(content: string, out: unknown[]): void {+ this.closeActiveReasoning(out);+ this.ensureText(out);+ this.text += content;+ out.push({+ type: 'response.output_text.delta',+ item_id: this.messageItemId,+ response_id: this.responseId,+ output_index: this.messageOutputIndex,+ content_index: this.textContentIndex,+ delta: content,});}private ensureMessage(out: unknown[]): void {if (this.messageStarted) return;- // reasoning 必须在 message 之前完整关闭(参考:reasoning precedes message)。- this.closeReasoning(out);this.messageStarted = true;this.messageOutputIndex = this.nextOutputIndex++;this.messageItemId = deterministicId('msg', this.responseId, this.messageOutputIndex);- const item = { id: this.messageItemId, type: 'message', status: 'in_progress', role: 'assistant', content: [] };- out.push({ type: 'response.output_item.added', response_id: this.responseId, output_index: this.messageOutputIndex, item });+ out.push({+ type: 'response.output_item.added',+ response_id: this.responseId,+ output_index: this.messageOutputIndex,+ item: { id: this.messageItemId, type: 'message', status: 'in_progress', role: 'assistant', content: [] },+ });+ }++ private ensureText(out: unknown[]): void {+ this.ensureMessage(out);+ if (this.textStarted) return;+ this.textStarted = true;+ this.textContentIndex = this.nextMessageContentIndex++;out.push({type: 'response.content_part.added',response_id: this.responseId,item_id: this.messageItemId,output_index: this.messageOutputIndex,- content_index: 0,+ content_index: this.textContentIndex,part: { type: 'output_text', text: '', annotations: [] },});}+ private pushRefusal(refusal: string, out: unknown[]): void {+ this.closeActiveReasoning(out);+ this.ensureMessage(out);+ if (!this.refusalStarted) {+ this.refusalStarted = true;+ this.refusalContentIndex = this.nextMessageContentIndex++;+ out.push({+ type: 'response.content_part.added',+ response_id: this.responseId,+ item_id: this.messageItemId,+ output_index: this.messageOutputIndex,+ content_index: this.refusalContentIndex,+ part: { type: 'refusal', refusal: '' },+ });+ }+ this.refusal += refusal;+ out.push({+ type: 'response.refusal.delta',+ response_id: this.responseId,+ item_id: this.messageItemId,+ output_index: this.messageOutputIndex,+ content_index: this.refusalContentIndex,+ delta: refusal,+ });+ }+private consumeToolDelta(raw: unknown, out: unknown[]): void {if (!isPlainObject(raw) || typeof raw.index !== 'number') return;const index = raw.index;let state = this.tools.get(index);if (!state) {const outputIndex = this.nextOutputIndex++;- const callId = stringField(raw.id) || deterministicId('call', this.responseId, index);state = {outputIndex,itemId: deterministicId('fc', this.responseId, index),- callId,+ callId: stringField(raw.id) || deterministicId('call', this.responseId, index),name: '',arguments: '',emittedArgumentsLength: 0,@@ -261,44 +488,16 @@ export class ChatSseTranslator {}const callId = stringField(raw.id);if (callId && !state.added) state.callId = callId;- const fn = isPlainObject(raw.function) ? raw.function : {};- const name = stringField(fn.name);- if (name && !state.added) state.name += name;- if (!state.added && state.name) {- state.added = true;- out.push({- type: 'response.output_item.added',- response_id: this.responseId,- output_index: state.outputIndex,- item: {- id: state.itemId,- type: 'function_call',- status: 'in_progress',- name: state.name,- call_id: state.callId,- arguments: '',- },- });- const bufferedArgs = state.arguments.slice(state.emittedArgumentsLength);- if (bufferedArgs) {- state.emittedArgumentsLength = state.arguments.length;- out.push({- type: 'response.function_call_arguments.delta',- response_id: this.responseId,- item_id: state.itemId,- output_index: state.outputIndex,- delta: bufferedArgs,- });- }- }- const args = stringField(fn.arguments);- if (args) {- state.arguments += args;- // Some providers stream argument bytes before the function name. Keep the- // bytes buffered so the first output_item.added event has a usable name.- if (state.added) {- const delta = state.arguments.slice(state.emittedArgumentsLength);- state.emittedArgumentsLength = state.arguments.length;+ const functionPart = isPlainObject(raw.function) ? raw.function : {};+ const name = stringField(functionPart.name);+ if (name) state.name += name;+ const args = stringField(functionPart.arguments);+ if (args) state.arguments += args;+ this.addToolWhenReady(state, out);+ if (state.added) {+ const delta = state.arguments.slice(state.emittedArgumentsLength);+ state.emittedArgumentsLength = state.arguments.length;+ if (delta && !this.isCustomOrToolSearch(state.name)) {out.push({type: 'response.function_call_arguments.delta',response_id: this.responseId,@@ -310,26 +509,110 @@ export class ChatSseTranslator {}}- private closeMessage(out: unknown[]): void {- if (!this.messageStarted || this.messageDone || this.messageOutputIndex === null) return;- this.messageDone = true;- out.push({- type: 'response.output_text.done',- response_id: this.responseId,- item_id: this.messageItemId,- output_index: this.messageOutputIndex,- content_index: 0,- text: this.text,- });- const content = [{ type: 'output_text', text: this.text, annotations: [] }];+ private isCustomOrToolSearch(name: string): boolean {+ const kind = this.toolContext?.lookupChatName(name)?.kind;+ return kind === 'custom' || kind === 'tool_search';+ }++ private toolItem(state: ToolState, status: 'in_progress' | 'completed'): Record<string, unknown> {+ const spec = this.toolContext?.lookupChatName(state.name);+ if (spec?.kind === 'custom') {+ return {+ id: state.itemId,+ type: 'custom_tool_call',+ status,+ call_id: state.callId,+ name: spec.name,+ ...(spec.namespace ? { namespace: spec.namespace } : {}),+ input: status === 'in_progress' ? '' : customInput(state.arguments),+ };+ }+ if (spec?.kind === 'tool_search') {+ return {+ id: state.itemId,+ type: 'tool_search_call',+ status,+ call_id: state.callId,+ execution: 'client',+ arguments: status === 'in_progress' ? {} : toolSearchArguments(state.arguments),+ };+ }+ return {+ id: state.itemId,+ type: 'function_call',+ status,+ call_id: state.callId,+ name: spec?.name ?? state.name,+ ...(spec?.namespace ? { namespace: spec.namespace } : {}),+ arguments: status === 'in_progress' ? '' : state.arguments,+ };+ }++ private addToolWhenReady(state: ToolState, out: unknown[], force = false): void {+ if (+ state.added+ || !state.name+ || (!force && !state.arguments && !this.pendingFinishReason)+ ) return;+ const spec = this.toolContext?.lookupChatName(state.name);+ if (!force && this.toolContext?.hasChatNamePrefix(state.name)) return;+ const kind = spec?.kind;+ state.itemId = deterministicId(+ kind === 'custom' ? 'ctc' : kind === 'tool_search' ? 'tsc' : 'fc',+ this.responseId,+ state.outputIndex,+ );+ state.added = true;out.push({- type: 'response.content_part.done',+ type: 'response.output_item.added',response_id: this.responseId,- item_id: this.messageItemId,- output_index: this.messageOutputIndex,- content_index: 0,- part: content[0],+ output_index: state.outputIndex,+ item: this.toolItem(state, 'in_progress'),});+ }++ private closeMessage(out: unknown[]): void {+ if (!this.messageStarted || this.messageDone || this.messageOutputIndex === null) return;+ this.messageDone = true;+ const content = this.messageContent();+ if (this.textStarted && this.textContentIndex !== null) {+ const part = content[this.textContentIndex];+ out.push({+ type: 'response.output_text.done',+ response_id: this.responseId,+ item_id: this.messageItemId,+ output_index: this.messageOutputIndex,+ content_index: this.textContentIndex,+ text: this.text,+ });+ out.push({+ type: 'response.content_part.done',+ response_id: this.responseId,+ item_id: this.messageItemId,+ output_index: this.messageOutputIndex,+ content_index: this.textContentIndex,+ part,+ });+ }+ if (this.refusalStarted && this.refusalContentIndex !== null) {+ const part = content[this.refusalContentIndex];+ out.push({+ type: 'response.refusal.done',+ response_id: this.responseId,+ item_id: this.messageItemId,+ output_index: this.messageOutputIndex,+ content_index: this.refusalContentIndex,+ refusal: this.refusal,+ });+ out.push({+ type: 'response.content_part.done',+ response_id: this.responseId,+ item_id: this.messageItemId,+ output_index: this.messageOutputIndex,+ content_index: this.refusalContentIndex,+ part,+ });+ }out.push({type: 'response.output_item.done',response_id: this.responseId,@@ -338,52 +621,66 @@ export class ChatSseTranslator {});}+ private messageContent(): Array<Record<string, unknown>> {+ const content: Array<{ contentIndex: number; part: Record<string, unknown> }> = [];+ if (this.textStarted && this.textContentIndex !== null) {+ content.push({+ contentIndex: this.textContentIndex,+ part: { type: 'output_text', text: this.text, annotations: this.uniqueAnnotations() },+ });+ }+ if (this.refusalStarted && this.refusalContentIndex !== null) {+ content.push({+ contentIndex: this.refusalContentIndex,+ part: { type: 'refusal', refusal: this.refusal },+ });+ }+ return content.sort((a, b) => a.contentIndex - b.contentIndex).map((entry) => entry.part);+ }+private closeTools(out: unknown[]): void {for (const state of [...this.tools.values()].sort((a, b) => a.outputIndex - b.outputIndex)) {if (state.done) continue;+ this.addToolWhenReady(state, out, true);state.done = true;- if (!state.added) {- state.added = true;+ const item = this.toolItem(state, 'completed');+ const kind = this.toolContext?.lookupChatName(state.name)?.kind;+ if (kind === 'custom') {+ const input = customInput(state.arguments);+ if (input) out.push({+ type: 'response.custom_tool_call_input.delta',+ response_id: this.responseId,+ item_id: state.itemId,+ output_index: state.outputIndex,+ delta: input,+ });out.push({- type: 'response.output_item.added',+ type: 'response.custom_tool_call_input.done',response_id: this.responseId,+ item_id: state.itemId,output_index: state.outputIndex,- item: {- id: state.itemId,- type: 'function_call',- status: 'in_progress',- name: state.name,- call_id: state.callId,- arguments: '',- },+ input,+ });+ } else if (kind !== 'tool_search') {+ out.push({+ type: 'response.function_call_arguments.done',+ response_id: this.responseId,+ item_id: state.itemId,+ output_index: state.outputIndex,+ arguments: state.arguments,});}- out.push({- type: 'response.function_call_arguments.done',- response_id: this.responseId,- item_id: state.itemId,- output_index: state.outputIndex,- arguments: state.arguments,- });out.push({type: 'response.output_item.done',response_id: this.responseId,output_index: state.outputIndex,- item: {- id: state.itemId,- type: 'function_call',- status: 'completed',- name: state.name,- call_id: state.callId,- arguments: state.arguments,- },+ item,});}}private closeOpenItems(out: unknown[]): void {- // reasoning 先于 message 关闭(顺序不变量);message 若已在 ensureMessage 里关过 reasoning 则 no-op。- this.closeReasoning(out);+ for (const reasoning of this.reasoningItems) this.closeReasoning(reasoning, out);this.closeMessage(out);this.closeTools(out);}@@ -395,23 +692,34 @@ export class ChatSseTranslator {const incomplete = reason === 'length' || reason === 'content_filter';out.push({type: incomplete ? 'response.incomplete' : 'response.completed',- response: this.responseObject(incomplete ? 'incomplete' : 'completed', incomplete- ? { incomplete_details: { reason: reason === 'length' ? 'max_output_tokens' : 'content_filter' } }- : {}),+ response: this.responseObject(+ incomplete ? 'incomplete' : 'completed',+ incomplete+ ? { incomplete_details: { reason: reason === 'length' ? 'max_output_tokens' : 'content_filter' } }+ : {},+ ),+ });+ }++ private uniqueAnnotations(): ResponseAnnotation[] {+ const seen = new Set<string>();+ return this.annotations.filter((annotation) => {+ const key = `${annotation.url}\0${annotation.start_index}\0${annotation.end_index}`;+ if (seen.has(key)) return false;+ seen.add(key);+ return true;});}private responseObject(status: string, extra: Record<string, unknown> = {}): Record<string, unknown> {- // Responses 协议里 output 数组位置 = output index(item 不带显式 index 字段)。- // message 与 function_call 必须**统一按 outputIndex 排序**,不能无条件把 message 排在前面——- // 否则模型先发工具调用、后补正文时(agentic 第三方模型常见),回放为下一轮 input 的顺序会颠倒。const items: Array<{ outputIndex: number; item: Record<string, unknown> }> = [];- if (this.reasoningDone && this.reasoningOutputIndex !== null) {- items.push({- outputIndex: this.reasoningOutputIndex,- // reasoning summary item 完成态不带 status(对齐参考实现)。- item: { id: this.reasoningItemId, type: 'reasoning', summary: [{ type: 'summary_text', text: this.reasoningText }] },- });+ for (const reasoning of this.reasoningItems) {+ if (reasoning.done) {+ items.push({+ outputIndex: reasoning.outputIndex,+ item: { id: reasoning.itemId, type: 'reasoning', summary: [{ type: 'summary_text', text: reasoning.text }] },+ });+ }}if (this.messageDone && this.messageOutputIndex !== null) {items.push({@@ -421,38 +729,35 @@ export class ChatSseTranslator {type: 'message',status: 'completed',role: 'assistant',- content: [{ type: 'output_text', text: this.text, annotations: [] }],+ content: this.messageContent(),},});}for (const state of this.tools.values()) {- if (!state.done) continue;- items.push({- outputIndex: state.outputIndex,- item: {- id: state.itemId,- type: 'function_call',- status: 'completed',- name: state.name,- call_id: state.callId,- arguments: state.arguments,- },- });+ if (state.done) items.push({ outputIndex: state.outputIndex, item: this.toolItem(state, 'completed') });}const output = items.sort((a, b) => a.outputIndex - b.outputIndex).map((entry) => entry.item);- const inputTokens = numberField(this.usage?.prompt_tokens);- const outputTokens = numberField(this.usage?.completion_tokens);- const usage = this.usage ? {- input_tokens: inputTokens,- output_tokens: outputTokens,- total_tokens: numberField(this.usage.total_tokens) || inputTokens + outputTokens,- input_tokens_details: {- cached_tokens: numberField(this.usage.prompt_tokens_details?.cached_tokens),- },- output_tokens_details: {- reasoning_tokens: numberField(this.usage.completion_tokens_details?.reasoning_tokens),- },- } : undefined;+ const inputTokens = numberField(this.usage?.prompt_tokens ?? this.usage?.input_tokens);+ const outputTokens = numberField(this.usage?.completion_tokens ?? this.usage?.output_tokens);+ const usage = this.usage || this.zeroUsageOnMissing+ ? {+ input_tokens: inputTokens,+ output_tokens: outputTokens,+ total_tokens: numberField(this.usage?.total_tokens) || inputTokens + outputTokens,+ input_tokens_details: {+ cached_tokens: numberField(+ this.usage?.prompt_tokens_details?.cached_tokens+ ?? this.usage?.input_tokens_details?.cached_tokens,+ ),+ },+ output_tokens_details: {+ reasoning_tokens: numberField(+ this.usage?.completion_tokens_details?.reasoning_tokens+ ?? this.usage?.output_tokens_details?.reasoning_tokens,+ ),+ },+ }+ : undefined;return {id: this.responseId,object: 'response',@@ -460,6 +765,7 @@ export class ChatSseTranslator {status,model: this.model,output,+ ...(this.serviceTier ? { service_tier: this.serviceTier } : {}),...(usage ? { usage } : {}),...extra,};diff --git a/packages/responses-chat-bridge/src/handler.ts b/packages/responses-chat-bridge/src/handler.tsindex 220f07994a..5c214d9536 100644--- a/packages/responses-chat-bridge/src/handler.ts+++ b/packages/responses-chat-bridge/src/handler.ts@@ -1,7 +1,7 @@import type { ServerResponse } from 'node:http';import { ChatSseTranslator } from './chat-sse-translator.js';-import { translateResponsesRequest } from './translate-request.js';+import { translateResponsesRequestWithContext } from './translate-request.js';import {UnsupportedResponsesFeatureError,type ChatBridgeLogger,@@ -11,6 +11,7 @@ import {} from './types.js';const MAX_ERROR_BODY_CHARS = 16 * 1024;+const MAX_RESPONSE_BODY_BYTES = 16 * 1024 * 1024;const MAX_SSE_BUFFER_CHARS = 1024 * 1024;function isPlainObject(value: unknown): value is Record<string, unknown> {@@ -101,6 +102,42 @@ async function readErrorText(upstream: Response): Promise<string> {}}+async function readResponseText(upstream: Response): Promise<string> {+ const reader = upstream.body?.getReader();+ if (!reader) return '';+ const decoder = new TextDecoder();+ const chunks: string[] = [];+ let bytesRead = 0;+ try {+ while (bytesRead < MAX_RESPONSE_BODY_BYTES) {+ const { done, value } = await reader.read();+ if (done) {+ chunks.push(decoder.decode());+ return chunks.join('');+ }+ const remaining = MAX_RESPONSE_BODY_BYTES - bytesRead;+ const bounded = value.byteLength > remaining ? value.subarray(0, remaining) : value;+ bytesRead += bounded.byteLength;+ chunks.push(decoder.decode(bounded, { stream: true }));+ if (bounded.byteLength < value.byteLength || bytesRead >= MAX_RESPONSE_BODY_BYTES) {+ await reader.cancel();+ return chunks.join('');+ }+ }+ await reader.cancel();+ return chunks.join('');+ } catch {+ try {+ await reader.cancel();+ } catch {+ // Ignore cancellation failures after a body read error.+ }+ return '';+ } finally {+ reader.releaseLock();+ }+}+export interface ResponsesChatHandlerOptions {logger?: ChatBridgeLogger;fetchImpl?: typeof fetch;@@ -122,19 +159,14 @@ export function createResponsesChatHandler(}const request = parsedBody as ResponsesRequest;const realModel = provider.rewriteModel?.(request.model) ?? request.model;- let chatRequest;+ let translated;try {- chatRequest = translateResponsesRequest(request, {+ translated = translateResponsesRequestWithContext(request, {model: realModel,capabilities: provider.capabilities,onDroppedTool: (type, index) => {log.warn?.('responses-chat bridge dropped non-function tool', { type, index });},- onDroppedInputItem: (type, index) => {- // tool_search_* 是 Codex 每轮重放的历史内建 item,属于预期兼容路径,- // 不发 warn 避免随会话长度二次增长日志。- log.debug?.('responses-chat bridge dropped built-in input item', { type, index });- },});} catch (error) {if (error instanceof UnsupportedResponsesFeatureError) {@@ -147,6 +179,7 @@ export function createResponsesChatHandler(}throw error;}+ const { request: chatRequest, toolContext } = translated;let upstreamUrl: string;try {@@ -232,7 +265,50 @@ export function createResponsesChatHandler(const contentType = upstream.headers.get('content-type')?.toLowerCase() ?? '';if (!contentType.startsWith('text/event-stream')) {- const text = await readErrorText(upstream);+ const text = await readResponseText(upstream);+ let jsonBody: unknown;+ try {+ jsonBody = JSON.parse(text);+ } catch {+ jsonBody = undefined;+ }+ if (isPlainObject(jsonBody) && Array.isArray(jsonBody.choices)) {+ const translator = new ChatSseTranslator(request.model, {+ toolContext,+ zeroUsageOnMissing: provider.capabilities?.zeroUsageOnMissing,+ inlineReasoning: provider.capabilities?.inlineReasoning,+ });+ const events = [+ ...translator.push(jsonBody),+ ...translator.finish(),+ ];+ const terminal = [...events].reverse().find((event) => (+ isPlainObject(event)+ && (+ event.type === 'response.completed'+ || event.type === 'response.incomplete'+ || event.type === 'response.failed'+ )+ && isPlainObject(event.response)+ )) as Record<string, unknown> | undefined;+ if (request.stream !== false) {+ res.writeHead(200, {+ 'content-type': 'text/event-stream; charset=utf-8',+ 'cache-control': 'no-cache',+ connection: 'keep-alive',+ });+ let sequenceNumber = 0;+ for (const event of events) writeSse(res, event, sequenceNumber++);+ res.end();+ res.off('close', abortUpstream);+ return;+ }+ res.off('close', abortUpstream);+ writeJson(res, 200, terminal && isPlainObject(terminal.response)+ ? terminal.response+ : responsesError(502, 'invalid_upstream_response', 'provider response could not be translated'));+ return;+ }log.warn?.('responses-chat bridge upstream returned non-SSE response', {model: request.model,status: upstream.status,@@ -247,19 +323,40 @@ export function createResponsesChatHandler(return;}- res.writeHead(200, {- 'content-type': 'text/event-stream; charset=utf-8',- 'cache-control': 'no-cache',- connection: 'keep-alive',+ if (request.stream !== false) {+ res.writeHead(200, {+ 'content-type': 'text/event-stream; charset=utf-8',+ 'cache-control': 'no-cache',+ connection: 'keep-alive',+ });+ }+ const translator = new ChatSseTranslator(request.model, {+ toolContext,+ zeroUsageOnMissing: provider.capabilities?.zeroUsageOnMissing,+ inlineReasoning: provider.capabilities?.inlineReasoning,});- const translator = new ChatSseTranslator(request.model);const reader = upstream.body.getReader();const decoder = new TextDecoder();let buffer = '';let streamFailed = false;// 全响应连续递增的 SSE sequence_number(Responses 协议要求)。let seq = 0;+ let terminalEvent: Record<string, unknown> | undefined;const emit = (output: unknown): void => {+ if (request.stream === false) {+ if (+ isPlainObject(output)+ && (+ output.type === 'response.completed'+ || output.type === 'response.incomplete'+ || output.type === 'response.failed'+ )+ && isPlainObject(output.response)+ ) {+ terminalEvent = output;+ }+ return;+ }writeSse(res, output, seq++);};const parseDataPayload = (payload: string): void => {@@ -326,7 +423,13 @@ export function createResponsesChatHandler(if (!streamFailed && !abort.signal.aborted) {for (const output of translator.finish(true)) emit(output);}- res.end();+ if (request.stream === false) {+ writeJson(res, 200, terminalEvent && isPlainObject(terminalEvent.response)+ ? terminalEvent.response+ : responsesError(502, 'invalid_upstream_response', 'provider response could not be translated'));+ } else {+ res.end();+ }}},};diff --git a/packages/responses-chat-bridge/src/index.ts b/packages/responses-chat-bridge/src/index.tsindex f3eee89aad..16f4e9ff0e 100644--- a/packages/responses-chat-bridge/src/index.ts+++ b/packages/responses-chat-bridge/src/index.ts@@ -1,6 +1,12 @@-export { ChatSseTranslator } from './chat-sse-translator.js';+export { ChatSseTranslator, type ChatSseTranslatorOptions } from './chat-sse-translator.js';export { createResponsesChatHandler, type ResponsesChatHandlerOptions } from './handler.js';-export { translateResponsesRequest, type TranslateResponsesRequestOptions } from './translate-request.js';+export {+ translateResponsesRequest,+ translateResponsesRequestWithContext,+ type TranslatedResponsesChatRequest,+ type TranslateResponsesRequestOptions,+} from './translate-request.js';+export { ChatBridgeToolContext, type ChatBridgeToolKind, type ChatBridgeToolSpec } from './tool-context.js';export {UnsupportedResponsesFeatureError,type ChatBridgeCapabilities,@@ -9,8 +15,11 @@ export {type ChatBridgeProviderConfig,type ChatBridgeUpstreamErrorInfo,type ChatCompletionsRequest,+ type ChatAudioInput,+ type ChatFileInput,type ChatImageInput,type ChatImageUrlContentPart,+ type ChatReasoningHistoryField,type ChatTextContentPart,type ChatUserContentPart,type ChatUserMessage,diff --git a/packages/responses-chat-bridge/src/tool-context.ts b/packages/responses-chat-bridge/src/tool-context.tsnew file mode 100644index 0000000000..7c841cd1fa--- /dev/null+++ b/packages/responses-chat-bridge/src/tool-context.ts@@ -0,0 +1,259 @@+import { createHash } from 'node:crypto';++import type {+ ChatCompletionsRequest,+ ResponsesCustomTool,+ ResponsesFunctionTool,+ ResponsesNamespaceTool,+ ResponsesRequest,+} from './types.js';++type ResponseTool = NonNullable<ResponsesRequest['tools']>[number];+const CHAT_TOOL_NAME_MAX_LENGTH = 64;+const TOOL_SEARCH_CHAT_NAME = 'tool_search';+const CUSTOM_TOOL_INPUT_DESCRIPTION =+ 'Raw string input for the original custom tool. Preserve formatting exactly.';++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function shortHash(value: string): string {+ return createHash('sha256').update(value).digest('hex').slice(0, 12);+}++function clampChatToolName(name: string): string {+ if (name.length <= CHAT_TOOL_NAME_MAX_LENGTH) return name;+ const suffix = `__${shortHash(name)}`;+ return `${name.slice(0, CHAT_TOOL_NAME_MAX_LENGTH - suffix.length)}${suffix}`;+}++function normalizeFunctionParameters(parameters: unknown): Record<string, unknown> {+ if (!isPlainObject(parameters)) return { type: 'object', properties: {} };+ return parameters.type === 'object'+ ? { ...parameters }+ : { ...parameters, type: 'object' };+}++function stableToolDescription(tool: unknown): string {+ try {+ return `Original Responses custom tool definition:\n${JSON.stringify(tool)}`;+ } catch {+ return 'Original Responses custom tool definition is unavailable.';+ }+}++export type ChatBridgeToolKind = 'function' | 'namespace' | 'custom' | 'tool_search';+type ResponseToolIdentityKind = 'function' | 'custom' | 'tool_search';++export interface ChatBridgeToolSpec {+ kind: ChatBridgeToolKind;+ chatName: string;+ name: string;+ namespace?: string;+}++function responseToolIdentity(+ kind: ResponseToolIdentityKind,+ name: string,+ namespace?: string,+): string {+ return `${kind}\0${namespace ?? ''}\0${name}`;+}++function specIdentity(spec: ChatBridgeToolSpec): string {+ const kind = spec.kind === 'custom' || spec.kind === 'tool_search'+ ? spec.kind+ : 'function';+ return responseToolIdentity(kind, spec.name, spec.namespace);+}++/**+ * One request-scoped catalog for the lossy Chat `function` namespace. It makes request and+ * response translation symmetrical: names flattened for Chat are restored to their Responses+ * function/custom/tool_search representation on the way back.+ */+export class ChatBridgeToolContext {+ private readonly chatToolsValue: NonNullable<ChatCompletionsRequest['tools']> = [];+ private readonly specsByChatName = new Map<string, ChatBridgeToolSpec>();+ private readonly chatNamesByResponseName = new Map<string, string>();++ static fromRequest(request: ResponsesRequest): ChatBridgeToolContext {+ const context = new ChatBridgeToolContext();+ for (const tool of request.tools ?? []) context.addResponseTool(tool);+ context.collectHistoryTools(request.input);+ return context;+ }++ get chatTools(): ChatCompletionsRequest['tools'] {+ return this.chatToolsValue.length > 0 ? this.chatToolsValue : undefined;+ }++ lookupChatName(chatName: string): ChatBridgeToolSpec | undefined {+ return this.specsByChatName.get(chatName);+ }++ /** Whether a streamed name may still resolve to a longer catalogued Chat tool name. */+ hasChatNamePrefix(prefix: string): boolean {+ if (!prefix) return false;+ for (const chatName of this.specsByChatName.keys()) {+ if (chatName !== prefix && chatName.startsWith(prefix)) return true;+ }+ return false;+ }++ chatNameForResponse(+ name: string,+ namespace?: string,+ kind: ResponseToolIdentityKind = 'function',+ ): string {+ return this.chatNamesByResponseName.get(responseToolIdentity(kind, name, namespace))+ ?? clampChatToolName(namespace ? `${namespace}__${name}` : name);+ }++ private reserveName(preferred: string, identity: string): string {+ const clamped = clampChatToolName(preferred);+ const existing = this.specsByChatName.get(clamped);+ if (!existing) return clamped;+ if (specIdentity(existing) === identity) return clamped;+ for (let attempt = 0; ; attempt += 1) {+ const suffix = `__${shortHash(attempt === 0 ? identity : `${identity}\0${attempt}`)}`;+ const candidate = `${clamped.slice(0, CHAT_TOOL_NAME_MAX_LENGTH - suffix.length)}${suffix}`;+ const occupant = this.specsByChatName.get(candidate);+ if (!occupant || specIdentity(occupant) === identity) return candidate;+ }+ }++ private addFunction(tool: ResponsesFunctionTool, namespace?: string): void {+ const nested = isPlainObject((tool as unknown as Record<string, unknown>).function)+ ? (tool as unknown as Record<string, unknown>).function+ : undefined;+ const source = nested ? { ...tool, ...nested } as ResponsesFunctionTool : tool;+ if (!source.name?.trim()) return;+ const identity = responseToolIdentity('function', source.name, namespace);+ const chatName = this.reserveName(namespace ? `${namespace}__${source.name}` : source.name, identity);+ if (this.specsByChatName.has(chatName)) return;+ const spec: ChatBridgeToolSpec = {+ kind: namespace ? 'namespace' : 'function',+ chatName,+ name: source.name,+ ...(namespace ? { namespace } : {}),+ };+ this.specsByChatName.set(chatName, spec);+ this.chatNamesByResponseName.set(identity, chatName);+ this.chatToolsValue.push({+ type: 'function',+ function: {+ name: chatName,+ ...(source.description ? { description: source.description } : {}),+ parameters: normalizeFunctionParameters(source.parameters),+ ...(typeof source.strict === 'boolean' ? { strict: source.strict } : {}),+ },+ });+ }++ private addCustom(tool: ResponsesCustomTool, namespace?: string): void {+ if (!tool.name?.trim()) return;+ const identity = responseToolIdentity('custom', tool.name, namespace);+ const chatName = this.reserveName(namespace ? `${namespace}__${tool.name}` : tool.name, identity);+ if (this.specsByChatName.has(chatName)) return;+ const spec: ChatBridgeToolSpec = {+ kind: 'custom',+ chatName,+ name: tool.name,+ ...(namespace ? { namespace } : {}),+ };+ this.specsByChatName.set(chatName, spec);+ this.chatNamesByResponseName.set(identity, chatName);+ this.chatToolsValue.push({+ type: 'function',+ function: {+ name: chatName,+ description: tool.description+ ? `${tool.description}\n\n${stableToolDescription(tool)}`+ : stableToolDescription(tool),+ parameters: {+ type: 'object',+ properties: {+ input: {+ type: 'string',+ description: CUSTOM_TOOL_INPUT_DESCRIPTION,+ },+ },+ required: ['input'],+ },+ },+ });+ }++ private addToolSearch(): void {+ const identity = responseToolIdentity('tool_search', TOOL_SEARCH_CHAT_NAME);+ const chatName = this.reserveName(TOOL_SEARCH_CHAT_NAME, identity);+ if (this.specsByChatName.has(chatName)) return;+ const spec: ChatBridgeToolSpec = {+ kind: 'tool_search',+ chatName,+ name: TOOL_SEARCH_CHAT_NAME,+ };+ this.specsByChatName.set(chatName, spec);+ this.chatNamesByResponseName.set(identity, chatName);+ this.chatToolsValue.push({+ type: 'function',+ function: {+ name: chatName,+ description: 'Search and load Codex tools, plugins, connectors, and MCP namespaces.',+ parameters: {+ type: 'object',+ properties: {+ query: { type: 'string', description: 'Search query for tools or connectors to load.' },+ limit: { type: 'integer', description: 'Maximum number of tool groups to return.' },+ },+ required: ['query'],+ },+ },+ });+ }++ private addNamespace(tool: ResponsesNamespaceTool): void {+ if (!tool.name?.trim()) return;+ for (const child of tool.tools ?? tool.children ?? []) {+ if (!isPlainObject(child) || typeof child.name !== 'string') continue;+ if (child.type === 'function') this.addFunction(child as unknown as ResponsesFunctionTool, tool.name);+ if (child.type === 'custom') this.addCustom(child as unknown as ResponsesCustomTool, tool.name);+ }+ }++ private addResponseTool(tool: ResponseTool): void {+ if (typeof tool === 'string') {+ this.addCustom({ type: 'custom', name: tool });+ return;+ }+ if (!isPlainObject(tool)) return;+ if (tool.type === 'function') this.addFunction(tool as unknown as ResponsesFunctionTool);+ if (tool.type === 'custom') this.addCustom(tool as unknown as ResponsesCustomTool);+ if (tool.type === 'tool_search') this.addToolSearch();+ if (tool.type === 'namespace') this.addNamespace(tool as unknown as ResponsesNamespaceTool);+ }++ private collectHistoryTools(input: ResponsesRequest['input']): void {+ if (!Array.isArray(input)) return;+ for (const item of input) {+ if (!isPlainObject(item)) continue;+ if (item.type === 'tool_search_call') this.addToolSearch();+ if (item.type === 'custom_tool_call' && typeof item.name === 'string') {+ this.addCustom(+ { type: 'custom', name: item.name },+ typeof item.namespace === 'string' ? item.namespace : undefined,+ );+ }+ if (+ (item.type === 'tool_search_output' || item.type === 'tool_search_call_output')+ && Array.isArray(item.tools)+ ) {+ for (const tool of item.tools) {+ this.addResponseTool(tool as ResponseTool);+ }+ }+ }+ }+}diff --git a/packages/responses-chat-bridge/src/translate-request.ts b/packages/responses-chat-bridge/src/translate-request.tsindex cbf6269448..27be2db28d 100644--- a/packages/responses-chat-bridge/src/translate-request.ts+++ b/packages/responses-chat-bridge/src/translate-request.ts@@ -1,17 +1,31 @@import {UnsupportedResponsesFeatureError,type ChatAssistantMessage,+ type ChatAudioInput,type ChatBridgeCapabilities,- type ChatDeveloperRole,type ChatCompletionsRequest,+ type ChatDeveloperRole,+ type ChatFileInput,type ChatImageInput,type ChatMessage,+ type ChatPassthroughField,+ type ChatReasoningHistoryField,type ChatToolCallExtraContent,type ChatUserContentPart,- type ResponsesFunctionTool,type ResponsesInputItem,type ResponsesRequest,} from './types.js';+import { ChatBridgeToolContext } from './tool-context.js';++const TOOL_CALL_REASONING_PLACEHOLDER = 'tool call';+const GOOGLE_THOUGHT_SIGNATURE_PLACEHOLDER = 'skip_thought_signature_validator';+const TOOL_RESULT_MEDIA_MOVED_MARKER = '[media moved to the following user message]';++interface ChatMediaCapabilities {+ imageInput?: ChatImageInput;+ fileInput?: ChatFileInput;+ audioInput?: ChatAudioInput;+}function isPlainObject(value: unknown): value is Record<string, unknown> {return typeof value === 'object' && value !== null && !Array.isArray(value);@@ -26,6 +40,149 @@ function cloneToolCallExtraContent(value: unknown): ChatToolCallExtraContent | u};}+function normalizeRole(role: string, developerRole: ChatDeveloperRole): 'system' | 'developer' | 'user' {+ if (role === 'system' || role === 'developer') return developerRole;+ return 'user';+}++function imagePart(part: Record<string, unknown>): ChatUserContentPart | undefined {+ if (part.file_id !== undefined) {+ throw new UnsupportedResponsesFeatureError('input_image.file_id');+ }+ const imageUrl = typeof part.image_url === 'string'+ ? part.image_url+ : isPlainObject(part.image_url) && typeof part.image_url.url === 'string'+ ? part.image_url.url+ : undefined;+ if (!imageUrl) return undefined;+ const detail = typeof part.detail === 'string' && part.detail+ ? part.detail+ : isPlainObject(part.image_url) && typeof part.image_url.detail === 'string'+ ? part.image_url.detail+ : undefined;+ return {+ type: 'image_url',+ image_url: { url: imageUrl, ...(detail ? { detail } : {}) },+ };+}++function filePart(part: Record<string, unknown>): ChatUserContentPart | undefined {+ const source = isPlainObject(part.file) ? part.file : part;+ if (source.file_id !== undefined) {+ throw new UnsupportedResponsesFeatureError('input_file.file_id');+ }+ const file = {+ ...(typeof source.file_data === 'string' ? { file_data: source.file_data } : {}),+ ...(typeof source.file_url === 'string' ? { file_url: source.file_url } : {}),+ ...(typeof source.filename === 'string' ? { filename: source.filename } : {}),+ };+ return Object.keys(file).length > 0 ? { type: 'file', file } : undefined;+}++function audioPart(part: Record<string, unknown>): ChatUserContentPart | undefined {+ const source = isPlainObject(part.input_audio) ? part.input_audio : part;+ if (typeof source.data !== 'string' || typeof source.format !== 'string') return undefined;+ return { type: 'input_audio', input_audio: { data: source.data, format: source.format } };+}++function hasImageSource(part: Record<string, unknown>): boolean {+ return part.file_id !== undefined+ || (typeof part.image_url === 'string' && part.image_url.length > 0)+ || (+ isPlainObject(part.image_url)+ && typeof part.image_url.url === 'string'+ && part.image_url.url.length > 0+ );+}++function hasFileSource(part: Record<string, unknown>): boolean {+ const source = isPlainObject(part.file) ? part.file : part;+ return source.file_id !== undefined+ || typeof source.file_data === 'string'+ || typeof source.file_url === 'string';+}++function hasAudioSource(part: Record<string, unknown>): boolean {+ const source = isPlainObject(part.input_audio) ? part.input_audio : part;+ return typeof source.data === 'string' && typeof source.format === 'string';+}++function mediaPart(+ part: Record<string, unknown>,+ capabilities: ChatMediaCapabilities,+ failClosed = false,+): ChatUserContentPart | undefined {+ if (part.type === 'input_image' || part.type === 'image_url' || part.type === 'image') {+ if (!hasImageSource(part)) return undefined;+ if (capabilities.imageInput !== 'image_url') {+ if (failClosed) throw new UnsupportedResponsesFeatureError(String(part.type));+ return undefined;+ }+ return imagePart(part);+ }+ if (part.type === 'input_file' || part.type === 'file') {+ if (!hasFileSource(part)) return undefined;+ if (capabilities.fileInput !== 'file') {+ if (failClosed) throw new UnsupportedResponsesFeatureError(String(part.type));+ return undefined;+ }+ return filePart(part);+ }+ if (part.type === 'input_audio') {+ if (!hasAudioSource(part)) return undefined;+ if (capabilities.audioInput !== 'input_audio') {+ if (failClosed) throw new UnsupportedResponsesFeatureError(String(part.type));+ return undefined;+ }+ return audioPart(part);+ }+ return undefined;+}++function messageContent(+ item: Extract<ResponsesInputItem, { role: string }>,+ itemIndex: number,+ developerRole: ChatDeveloperRole,+ mediaCapabilities: ChatMediaCapabilities,+): string | ChatUserContentPart[] {+ if (typeof item.content === 'string') return item.content;+ if (!Array.isArray(item.content)) {+ throw new UnsupportedResponsesFeatureError(`input[${itemIndex}].content`);+ }++ const normalizedRole = item.role === 'assistant'+ ? 'assistant'+ : normalizeRole(item.role, developerRole);+ let text = '';+ let hasMedia = false;+ const content: ChatUserContentPart[] = [];+ for (const rawPart of item.content) {+ if (!isPlainObject(rawPart) || typeof rawPart.type !== 'string') {+ throw new UnsupportedResponsesFeatureError(`input[${itemIndex}].content`);+ }+ if (rawPart.type === 'input_text' || rawPart.type === 'output_text' || rawPart.type === 'text') {+ if (typeof rawPart.text !== 'string') {+ throw new UnsupportedResponsesFeatureError(`input[${itemIndex}].content.${rawPart.type}`);+ }+ text += rawPart.text;+ content.push({ type: 'text', text: rawPart.text });+ continue;+ }+ if (rawPart.type === 'refusal' && typeof rawPart.refusal === 'string') {+ text += rawPart.refusal;+ content.push({ type: 'text', text: rawPart.refusal });+ continue;+ }+ const translatedMedia = mediaPart(rawPart, mediaCapabilities);+ if (normalizedRole !== 'user' || !translatedMedia) {+ throw new UnsupportedResponsesFeatureError(`input content part '${rawPart.type}'`);+ }+ hasMedia = true;+ content.push(translatedMedia);+ }+ return hasMedia ? content : text;+}+function stringifyToolOutput(output: unknown): string {if (typeof output === 'string') return output;if (Array.isArray(output)) {@@ -40,140 +197,122 @@ function stringifyToolOutput(output: unknown): string {if (textParts.every((part): part is string => part !== null)) return textParts.join('\n');}try {- return JSON.stringify(output);+ const serialized = JSON.stringify(output);+ return typeof serialized === 'string' ? serialized : String(output ?? '');} catch {return String(output);}}+function replaceToolMedia(+ value: unknown,+ media: ChatUserContentPart[],+ mediaCapabilities: ChatMediaCapabilities,+): unknown {+ if (Array.isArray(value)) {+ return value.map((part) => replaceToolMedia(part, media, mediaCapabilities));+ }+ if (!isPlainObject(value)) return value;+ const translated = mediaPart(value, mediaCapabilities, true);+ if (translated) {+ media.push(translated);+ return { type: 'text', text: TOOL_RESULT_MEDIA_MOVED_MARKER };+ }+ return Object.fromEntries(+ Object.entries(value).map(+ ([key, child]) => [key, replaceToolMedia(child, media, mediaCapabilities)],+ ),+ );+}++function splitToolOutput(+ output: unknown,+ mediaCapabilities: ChatMediaCapabilities,+): { content: string; media: ChatUserContentPart[] } {+ const media: ChatUserContentPart[] = [];+ const replaced = replaceToolMedia(output, media, mediaCapabilities);+ return {+ content: stringifyToolOutput(media.length > 0 ? replaced : output),+ media,+ };+}+function customToolArguments(input: unknown): string {- if (input == null) return '{}';- if (typeof input === 'string') {+ let rawInput: string;+ if (typeof input === 'string') rawInput = input;+ else {try {- const parsed: unknown = JSON.parse(input);- return JSON.stringify(isPlainObject(parsed) ? parsed : { input: parsed });+ rawInput = JSON.stringify(input ?? '');} catch {- return JSON.stringify({ input });+ rawInput = String(input ?? '');+ }+ }+ return JSON.stringify({ input: rawInput });+}++function toolArguments(value: unknown): string {+ if (typeof value === 'string') {+ try {+ JSON.parse(value);+ return value;+ } catch {+ return JSON.stringify({ input: value });}}try {- return JSON.stringify(isPlainObject(input) ? input : { input });+ return JSON.stringify(value ?? {});} catch {- return JSON.stringify({ input: String(input) });+ return '{}';}}-function messageContent(- item: Extract<ResponsesInputItem, { role: string }>,- itemIndex: number,- developerRole: ChatDeveloperRole,- imageInput: ChatImageInput | undefined,-): string | ChatUserContentPart[] {- if (typeof item.content === 'string') return item.content;- if (!Array.isArray(item.content)) {- throw new UnsupportedResponsesFeatureError(`input[${itemIndex}].content`);- }-- let text = '';- let hasImage = false;- const multimodal: ChatUserContentPart[] = [];- for (const part of item.content) {- if (!isPlainObject(part) || typeof part.type !== 'string') {- throw new UnsupportedResponsesFeatureError(`input[${itemIndex}].content`);- }- if (part.type === 'input_text' || part.type === 'output_text' || part.type === 'text') {- if (typeof part.text !== 'string') {- throw new UnsupportedResponsesFeatureError(`input[${itemIndex}].content.${part.type}`);- }- text += part.text;- multimodal.push({ type: 'text', text: part.text });- continue;- }- if (part.type === 'input_image') {- const normalizedRole = item.role === 'assistant'- ? 'assistant'- : normalizeRole(item.role, developerRole);- if (- normalizedRole !== 'user'- || imageInput !== 'image_url'- || part.file_id !== undefined- || typeof part.image_url !== 'string'- || part.image_url.length === 0- ) {- throw new UnsupportedResponsesFeatureError(`input content part '${part.type}'`);- }- hasImage = true;- multimodal.push({- type: 'image_url',- image_url: { url: part.image_url },- });- continue;- }- throw new UnsupportedResponsesFeatureError(`input content part '${part.type}'`);+function reasoningText(value: unknown): string {+ if (typeof value === 'string') return value;+ if (Array.isArray(value)) return value.map(reasoningText).filter(Boolean).join('');+ if (!isPlainObject(value)) return '';+ for (const key of ['reasoning_content', 'content', 'text', 'summary']) {+ const text = reasoningText(value[key]);+ if (text) return text;}- // 无图片时维持历史 JSON 形态(string),不让 capability 改变纯文本供应商请求。- return hasImage ? multimodal : text;+ return '';}interface TranslateInputOptions {developerRole: ChatDeveloperRole;- /** 仅明确支持视觉的 Chat 上游开启;未声明时 input_image 继续 fail closed。 */- imageInput?: ChatImageInput;- /** thinking 模型:为带 tool_calls 但缺 reasoning_content 的 assistant 消息注入占位。 */+ mediaCapabilities: ChatMediaCapabilities;+ reasoningHistoryField?: ChatReasoningHistoryField;toolCallReasoningPlaceholder: boolean;- /** Gemini 3 OpenAI 兼容层:为每步首个回放 tool call 注入官方允许的签名跳过值。 */googleThoughtSignaturePlaceholder: boolean;- /** 丢弃的无上下文内建 input item(Codex tool_search 等)回调,供 handler 记 log。 */- onDroppedInputItem?: (type: string, index: number) => void;+ toolContext: ChatBridgeToolContext;}-/** cc-switch 的占位口径:kimi/DeepSeek 要求 tool_call assistant 消息带非空 reasoning_content。 */-const TOOL_CALL_REASONING_PLACEHOLDER = 'tool call';-/** Google 官方文档允许在无法取得原始签名的注入式 function call 上使用的校验跳过值。 */-const GOOGLE_THOUGHT_SIGNATURE_PLACEHOLDER = 'skip_thought_signature_validator';--function flushAssistant(- messages: ChatMessage[],- pending: ChatAssistantMessage | null,- opts: TranslateInputOptions,-): null {- if (!pending) return null;- const hasToolCalls = (pending.tool_calls?.length ?? 0) > 0;- // 空 assistant(无 content / tool_calls)整条跳过 —— 部分后端(DeepSeek/xAI)拒收空 assistant。- if (pending.content == null && !hasToolCalls) return null;- if (hasToolCalls && opts.toolCallReasoningPlaceholder && !pending.reasoning_content) {- pending.reasoning_content = TOOL_CALL_REASONING_PLACEHOLDER;- }- if (hasToolCalls && opts.googleThoughtSignaturePlaceholder) {- const firstCall = pending.tool_calls?.[0];- const thoughtSignature = firstCall?.extra_content?.google?.thought_signature;- if (- firstCall- && (typeof thoughtSignature !== 'string' || thoughtSignature.trim().length === 0)- ) {- firstCall.extra_content = {- ...firstCall.extra_content,- google: {- ...firstCall.extra_content?.google,- thought_signature: GOOGLE_THOUGHT_SIGNATURE_PLACEHOLDER,- },- };- }- }- messages.push(pending);- return null;+interface PendingToolCall {+ id: string;+ name: string;}-/** Responses 角色 → Chat 角色。system/developer 归一到 capability 指定角色;- * user / latest_reminder / 未知一律归 user(不能透传,上游只认 system/user/assistant/tool)。 */-function normalizeRole(role: string, developerRole: ChatDeveloperRole): 'system' | 'developer' | 'user' {- if (role === 'system' || role === 'developer') return developerRole;- return 'user';+function ensureToolCallCompatibility(message: ChatAssistantMessage, opts: TranslateInputOptions): void {+ const hasToolCalls = (message.tool_calls?.length ?? 0) > 0;+ if (hasToolCalls && opts.toolCallReasoningPlaceholder && !message.reasoning_content?.trim()) {+ message.reasoning_content = TOOL_CALL_REASONING_PLACEHOLDER;+ }+ if (!hasToolCalls || !opts.googleThoughtSignaturePlaceholder) return;+ const firstCall = message.tool_calls?.[0];+ const signature = firstCall?.extra_content?.google?.thought_signature;+ if (!firstCall || (typeof signature === 'string' && signature.trim())) return;+ firstCall.extra_content = {+ ...firstCall.extra_content,+ google: {+ ...firstCall.extra_content?.google,+ thought_signature: GOOGLE_THOUGHT_SIGNATURE_PLACEHOLDER,+ },+ };}/**- * Responses input 是按时间排序的 item 列表,Chat 则把 assistant 文本和紧随其后的- * function_call 合并进同一条 assistant message。其它角色/工具结果会结束该合并段。+ * Convert the Responses item timeline to strict Chat history. Besides format conversion this+ * repairs dangling/orphan tool rounds, because Kimi/Moonshot and several llama.cpp templates+ * reject any assistant tool call not followed immediately by its tool result.*/function translateInput(input: ResponsesRequest['input'], opts: TranslateInputOptions): ChatMessage[] {if (typeof input === 'string') return [{ role: 'user', content: input }];@@ -181,39 +320,178 @@ function translateInput(input: ResponsesRequest['input'], opts: TranslateInputOpconst messages: ChatMessage[] = [];let assistant: ChatAssistantMessage | null = null;+ let pendingReasoning = '';+ let pendingToolCalls: PendingToolCall[] = [];+ const resolvedToolCallIds = new Set<string>();+ let deferredBarriers: ChatMessage[] = [];+ let pendingMedia: ChatUserContentPart[] = [];+ let mintedCallId = 0;++ const mintCallId = (prefix: string): string => `call_bridge_${prefix}_${++mintedCallId}`;++ const attachReasoningToLastAssistant = (): void => {+ const text = pendingReasoning;+ pendingReasoning = '';+ if (!text.trim()) return;+ for (let index = messages.length - 1; index >= 0; index -= 1) {+ const message = messages[index];+ if (message.role !== 'assistant') continue;+ message.reasoning_content = message.reasoning_content+ ? `${message.reasoning_content}${text}`+ : text;+ return;+ }+ };++ const flushPendingMedia = (): void => {+ if (pendingMedia.length === 0) return;+ messages.push({+ role: 'user',+ content: [+ { type: 'text', text: 'Media returned by the preceding tool result:' },+ ...pendingMedia,+ ],+ });+ pendingMedia = [];+ };++ const releaseDeferredBarriers = (): void => {+ flushPendingMedia();+ if (deferredBarriers.length === 0) return;+ messages.push(...deferredBarriers);+ deferredBarriers = [];+ };++ const closeUnresolvedToolRound = (): void => {+ if (pendingToolCalls.length === 0) {+ releaseDeferredBarriers();+ return;+ }+ for (const call of pendingToolCalls) {+ messages.push({+ role: 'tool',+ tool_call_id: call.id,+ content:+ `No tool result was recorded for "${call.name}"; execution status is unknown. `+ + 'Do not treat this as success, failure, or user-provided input.',+ });+ resolvedToolCallIds.add(call.id);+ }+ pendingToolCalls = [];+ releaseDeferredBarriers();+ };++ const flushAssistant = (): void => {+ if (!assistant) return;+ const reasoning = pendingReasoning;+ pendingReasoning = '';+ if (reasoning.trim()) {+ assistant.reasoning_content = assistant.reasoning_content+ ? `${assistant.reasoning_content}${reasoning}`+ : reasoning;+ }+ const hasToolCalls = (assistant.tool_calls?.length ?? 0) > 0;+ if (assistant.content == null && !hasToolCalls && !assistant.reasoning_content) {+ assistant = null;+ return;+ }+ if (assistant.content == null && !hasToolCalls && assistant.reasoning_content) assistant.content = '';+ ensureToolCallCompatibility(assistant, opts);+ messages.push(assistant);+ // Preserve completed IDs from older rounds so late duplicates remain detectable, but retire+ // an ID when the new assistant round explicitly reuses it.+ if (hasToolCalls) {+ for (const call of assistant.tool_calls ?? []) resolvedToolCallIds.delete(call.id);+ }+ pendingToolCalls = (assistant.tool_calls ?? []).map((call) => ({+ id: call.id,+ name: call.function.name,+ }));+ assistant = null;+ };++ const pushBarrier = (message: ChatMessage): void => {+ flushAssistant();+ if (pendingReasoning) attachReasoningToLastAssistant();+ if (pendingToolCalls.length > 0) deferredBarriers.push(message);+ else {+ releaseDeferredBarriers();+ messages.push(message);+ }+ };++ const pushToolOutput = (item: Record<string, unknown>, output: unknown): void => {+ let callId = typeof item.call_id === 'string' && item.call_id+ ? item.call_id+ : typeof item.id === 'string' && item.id+ ? item.id+ : '';+ const bufferedAssistantReusesCallId = callId+ ? assistant?.tool_calls?.some((call) => call.id === callId) === true+ : false;+ // A late duplicate from the completed round must not flush unrelated buffered calls. The+ // same ID in the buffered assistant instead starts a legitimate new round and takes priority.+ if (callId && resolvedToolCallIds.has(callId) && !bufferedAssistantReusesCallId) return;+ flushAssistant();+ if (callId && resolvedToolCallIds.has(callId)) return;+ let matchIndex = callId+ ? pendingToolCalls.findIndex((call) => call.id === callId)+ : -1;+ if (matchIndex < 0) {+ closeUnresolvedToolRound();+ if (!callId) callId = mintCallId('orphan');+ const fallbackName = typeof item.name === 'string' && item.name ? item.name : 'unknown_tool';+ const synthesizedAssistant: ChatAssistantMessage = {+ role: 'assistant',+ content: null,+ tool_calls: [{+ id: callId,+ type: 'function',+ function: { name: fallbackName, arguments: '{}' },+ }],+ };+ ensureToolCallCompatibility(synthesizedAssistant, opts);+ messages.push(synthesizedAssistant);+ pendingToolCalls = [{ id: callId, name: fallbackName }];+ matchIndex = 0;+ }+ const transformed = splitToolOutput(output, opts.mediaCapabilities);+ messages.push({ role: 'tool', tool_call_id: callId, content: transformed.content });+ pendingMedia.push(...transformed.media);+ pendingToolCalls.splice(matchIndex, 1);+ resolvedToolCallIds.add(callId);+ if (pendingToolCalls.length === 0) releaseDeferredBarriers();+ };+for (let index = 0; index < input.length; index += 1) {const item = input[index];if (!isPlainObject(item)) throw new UnsupportedResponsesFeatureError(`input[${index}]`);- const itemType = typeof item.type === 'string' ? item.type : undefined;- if (- itemType === 'tool_search_call'- || itemType === 'tool_search_output'- || itemType === 'tool_search_call_output'- ) {- // Codex 内建 tool_search 的回放 item:与 namespace/web_search 工具声明同口径,- // 对第三方 Chat 上游无意义且不承载用户上下文,必须作为“非边界”item 剥掉降级- // —— 在 flushAssistant 之前处理,避免拆分本应合并的 assistant message。- opts.onDroppedInputItem?.(itemType, index);- continue;- }+ const record = item as Record<string, unknown>;if ('role' in item && typeof item.role === 'string') {const content = messageContent(item as Extract<ResponsesInputItem, { role: string }>,index,opts.developerRole,- opts.imageInput,+ opts.mediaCapabilities,);if (item.role === 'assistant') {- // messageContent 只会为 user 图片返回数组;这里再守一次类型边界,避免未来扩展误放行。if (typeof content !== 'string') {throw new UnsupportedResponsesFeatureError(`input[${index}].content`);}- if (!assistant) assistant = { role: 'assistant', content };- else if (assistant.content == null) assistant.content = content;- else if (content) assistant.content += content;+ if (!assistant && pendingToolCalls.length > 0) closeUnresolvedToolRound();+ assistant ??= { role: 'assistant', content: null };+ assistant.content = `${assistant.content ?? ''}${content}`;+ if (opts.reasoningHistoryField === 'reasoning_content') {+ const embeddedReasoning = reasoningText({+ reasoning_content: record.reasoning_content,+ reasoning: record.reasoning,+ });+ if (embeddedReasoning) {+ assistant.reasoning_content = `${assistant.reasoning_content ?? ''}${embeddedReasoning}`;+ }+ }} else {- assistant = flushAssistant(messages, assistant, opts);const role = normalizeRole(item.role, opts.developerRole);if (role === 'user') {// 空 user(纯空白文本且无图片)整条跳过 —— Codex auto-compact 会把@@ -222,194 +500,282 @@ function translateInput(input: ResponsesRequest['input'], opts: TranslateInputOpconst isEmptyUser =(typeof content === 'string' && content.trim().length === 0)|| (Array.isArray(content) && content.length === 0);- if (!isEmptyUser) messages.push({ role, content });+ if (!isEmptyUser) pushBarrier({ role, content });} else {if (typeof content !== 'string') {throw new UnsupportedResponsesFeatureError(`input[${index}].content`);}- messages.push({ role, content });+ pushBarrier({ role, content });}}continue;}- if (item.type === 'custom_tool_call') {- if (typeof item.call_id !== 'string' || typeof item.name !== 'string') {- throw new UnsupportedResponsesFeatureError(`input[${index}].custom_tool_call`);- }- assistant ??= { role: 'assistant', content: null, tool_calls: [] };- assistant.tool_calls ??= [];- assistant.tool_calls.push({- id: item.call_id,- type: 'function',- function: { name: item.name, arguments: customToolArguments(item.input) },- });- continue;- }-- if (item.type === 'custom_tool_call_output') {- assistant = flushAssistant(messages, assistant, opts);- if (typeof item.call_id !== 'string') {- throw new UnsupportedResponsesFeatureError(`input[${index}].custom_tool_call_output`);+ if (item.type === 'reasoning') {+ if (opts.reasoningHistoryField === 'reasoning_content') {+ pendingReasoning += reasoningText(item);}- messages.push({- role: 'tool',- tool_call_id: item.call_id,- content: stringifyToolOutput(item.output),- });continue;}- if (item.type === 'function_call') {- if (typeof item.call_id !== 'string' || typeof item.name !== 'string' || typeof item.arguments !== 'string') {- throw new UnsupportedResponsesFeatureError(`input[${index}].function_call`);+ if (item.type === 'function_call' || item.type === 'custom_tool_call' || item.type === 'tool_search_call') {+ if (!assistant && pendingToolCalls.length > 0) closeUnresolvedToolRound();+ const callId = typeof record.call_id === 'string' && record.call_id+ ? record.call_id+ : typeof record.id === 'string' && record.id+ ? record.id+ : mintCallId('missing');+ let name: string;+ let args: string;+ if (item.type === 'tool_search_call') {+ name = opts.toolContext.chatNameForResponse('tool_search', undefined, 'tool_search');+ args = toolArguments(record.arguments ?? {+ ...(typeof record.query === 'string' ? { query: record.query } : {}),+ ...(typeof record.limit === 'number' ? { limit: record.limit } : {}),+ });+ } else {+ if (typeof item.name !== 'string' || !item.name) {+ throw new UnsupportedResponsesFeatureError(`input[${index}].${item.type}`);+ }+ name = opts.toolContext.chatNameForResponse(+ String(record.name),+ typeof record.namespace === 'string' ? record.namespace : undefined,+ item.type === 'custom_tool_call' ? 'custom' : 'function',+ );+ args = item.type === 'custom_tool_call'+ ? customToolArguments(record.input)+ : toolArguments(record.arguments);}assistant ??= { role: 'assistant', content: null, tool_calls: [] };assistant.tool_calls ??= [];const extraContent = cloneToolCallExtraContent(item.extra_content);assistant.tool_calls.push({- id: item.call_id,+ id: callId,type: 'function',- function: { name: item.name, arguments: item.arguments },+ function: { name, arguments: args },...(extraContent ? { extra_content: extraContent } : {}),});continue;}- assistant = flushAssistant(messages, assistant, opts);- if (item.type === 'function_call_output') {- if (typeof item.call_id !== 'string') {- throw new UnsupportedResponsesFeatureError(`input[${index}].function_call_output`);- }- messages.push({- role: 'tool',- tool_call_id: item.call_id,- content: stringifyToolOutput(item.output),- });- continue;- }- if (item.type === 'reasoning') {- // Responses 会把上一轮 reasoning item 回放进 input。Chat 没有安全的等价输入形态;- // reasoning 本身不承载用户/工具上下文,明确丢弃而不是伪造 assistant 文本。+ if (+ item.type === 'function_call_output'+ || item.type === 'custom_tool_call_output'+ || item.type === 'tool_search_output'+ || item.type === 'tool_search_call_output'+ ) {+ const output = record.output !== undefined+ ? record.output+ : item.type === 'tool_search_output' || item.type === 'tool_search_call_output'+ ? record.tools+ : undefined;+ pushToolOutput(record, output);continue;}+throw new UnsupportedResponsesFeatureError(`input item '${String(item.type)}'`);}- flushAssistant(messages, assistant, opts);++ flushAssistant();+ if (pendingReasoning) attachReasoningToLastAssistant();+ closeUnresolvedToolRound();return messages;}-/**- * 工具是**能力声明**,不是上下文:Chat Completions 只认标准 `function` 工具,而 Codex 每次- * 请求都会注入自己的内建工具(`namespace` 多智能体分组、`local_shell`、`web_search`、- * `image_generation` 等)。这些对第三方 Chat 上游无意义,必须**剥掉降级**(与 codex proxy- * 的 xAI 兼容层同口径),不能 fail-closed —— 否则 Codex 首轮就带 namespace,整条桥接 100% 不可用。- * 被剥掉的类型经 onDropped 回调交给 handler 记 log(no silent caps)。- */-function translateTools(+function reportDroppedTools(tools: ResponsesRequest['tools'],onDropped?: (type: string, index: number) => void,-): ChatCompletionsRequest['tools'] {- if (!tools?.length) return undefined;- const out: NonNullable<ChatCompletionsRequest['tools']> = [];- tools.forEach((tool, index) => {- if (!isPlainObject(tool) || tool.type !== 'function' || typeof tool.name !== 'string') {- onDropped?.(isPlainObject(tool) ? String(tool.type) : typeof tool, index);- return;- }- const functionTool = tool as unknown as ResponsesFunctionTool;- out.push({- type: 'function' as const,- function: {- name: functionTool.name,- ...(functionTool.description ? { description: functionTool.description } : {}),- // Kimi 等要求 root parameters.type 恰为 "object";Codex 偶尔发 null/缺失 → 归一。- parameters: normalizeFunctionParameters(functionTool.parameters),- ...(typeof functionTool.strict === 'boolean' ? { strict: functionTool.strict } : {}),- },- });+): void {+ tools?.forEach((tool, index) => {+ if (typeof tool === 'string') return;+ if (+ isPlainObject(tool)+ && ['function', 'custom', 'namespace', 'tool_search'].includes(String(tool.type))+ ) return;+ onDropped?.(isPlainObject(tool) ? String(tool.type) : typeof tool, index);});- return out.length > 0 ? out : undefined;}-function normalizeFunctionParameters(parameters: unknown): Record<string, unknown> {- if (!isPlainObject(parameters)) return { type: 'object', properties: {} };- if (parameters.type == null) return { ...parameters, type: 'object' };- return parameters;-}--/**- * tool_choice 归一。forceAutoToolChoice(思考模型)时,具名 / required 一律降级为 'auto' ——- * DeepSeek reasoner 明确拒绝强制工具(`Thinking mode does not support this tool_choice`)。- */-function translateToolChoice(choice: unknown, forceAuto: boolean): unknown {+function translateToolChoice(+ choice: unknown,+ forceAuto: boolean,+ context: ChatBridgeToolContext,+): unknown {if (choice === undefined || choice === 'auto' || choice === 'none') return choice;if (choice === 'required') return forceAuto ? 'auto' : choice;- if (isPlainObject(choice) && choice.type === 'function' && typeof choice.name === 'string') {- return forceAuto ? 'auto' : { type: 'function', function: { name: choice.name } };+ if (!isPlainObject(choice)) throw new UnsupportedResponsesFeatureError('tool_choice');+ if (forceAuto) return 'auto';+ if (+ (choice.type === 'function' || choice.type === 'custom')+ && typeof choice.name === 'string'+ ) {+ return {+ type: 'function',+ function: {+ name: context.chatNameForResponse(+ choice.name,+ typeof choice.namespace === 'string' ? choice.namespace : undefined,+ choice.type,+ ),+ },+ };+ }+ if (choice.type === 'tool_search') {+ return {+ type: 'function',+ function: { name: context.chatNameForResponse('tool_search', undefined, 'tool_search') },+ };}throw new UnsupportedResponsesFeatureError('tool_choice');}+function applyReasoning(+ out: ChatCompletionsRequest,+ input: ResponsesRequest,+ capabilities: ChatBridgeCapabilities,+): void {+ const effort = input.reasoning?.effort;+ const field = capabilities.reasoningField ?? 'none';+ if (typeof effort !== 'string' || field === 'none') return;+ const mapped = capabilities.reasoningEffortMap?.[effort] ?? effort;+ const mappedString = typeof mapped === 'string' ? mapped : effort;+ switch (field) {+ case 'reasoning_effort':+ out.reasoning_effort = mappedString;+ break;+ case 'reasoning.effort':+ out.reasoning = { effort: mappedString };+ break;+ case 'thinking.type':+ out.thinking = { type: mappedString };+ break;+ case 'enable_thinking':+ out.enable_thinking = typeof mapped === 'boolean'+ ? mapped+ : !['none', 'off', 'disabled', 'minimal'].includes(String(mapped).toLowerCase());+ break;+ case 'reasoning_split':+ out.reasoning_split = typeof mapped === 'boolean'+ ? mapped+ : !['none', 'off', 'disabled'].includes(String(mapped).toLowerCase());+ break;+ }+}++function chatResponseFormat(value: unknown): unknown {+ if (!isPlainObject(value) || value.type !== 'json_schema' || value.json_schema !== undefined) {+ return value;+ }+ const { type: _type, ...jsonSchema } = value;+ return { type: 'json_schema', json_schema: jsonSchema };+}++function applyPassthrough(+ out: ChatCompletionsRequest,+ input: ResponsesRequest,+ fields: readonly ChatPassthroughField[] | undefined,+): void {+ for (const field of fields ?? []) {+ const value = field === 'response_format'+ ? chatResponseFormat(input.response_format ?? input.text?.format)+ : input[field];+ if (value !== undefined) {+ (out as unknown as Record<string, unknown>)[field] = value;+ }+ }+}+export interface TranslateResponsesRequestOptions {model?: string;capabilities?: ChatBridgeCapabilities;- /** 被剥掉的非 function 工具(Codex 内建 namespace / local_shell 等)回调,供 handler 记 log。 */onDroppedTool?: (type: string, index: number) => void;- /** 被剥掉的无上下文内建 input item(Codex tool_search 等)回调,供 handler 记 log。 */+ /** Retained for callers compiled against the previous bridge API; supported built-in history is no longer dropped. */onDroppedInputItem?: (type: string, index: number) => void;}-/** Convert a Codex Responses request to a streaming Chat Completions request. */-export function translateResponsesRequest(+export interface TranslatedResponsesChatRequest {+ request: ChatCompletionsRequest;+ toolContext: ChatBridgeToolContext;+}++/** Convert a Responses request and retain the request-scoped tool catalog for response restoration. */+export function translateResponsesRequestWithContext(input: ResponsesRequest,opts: TranslateResponsesRequestOptions = {},-): ChatCompletionsRequest {+): TranslatedResponsesChatRequest {if (!input || typeof input.model !== 'string' || input.model.length === 0) {throw new UnsupportedResponsesFeatureError('model');}const capabilities = opts.capabilities ?? {};const developerRole = capabilities.developerRole ?? 'system';+ const toolContext = ChatBridgeToolContext.fromRequest(input);+ reportDroppedTools(input.tools, opts.onDroppedTool);const messages = translateInput(input.input, {developerRole,- imageInput: capabilities.imageInput,+ mediaCapabilities: capabilities,+ reasoningHistoryField: capabilities.reasoningHistoryField,toolCallReasoningPlaceholder: capabilities.toolCallReasoningPlaceholder === true,googleThoughtSignaturePlaceholder: capabilities.googleThoughtSignaturePlaceholder === true,- onDroppedInputItem: opts.onDroppedInputItem,+ toolContext,});if (input.instructions) {- messages.unshift({ role: developerRole, content: input.instructions });+ const instructions = typeof input.instructions === 'string'+ ? input.instructions+ : input.instructions.map((part, index) => {+ if (!isPlainObject(part) || typeof part.type !== 'string') {+ throw new UnsupportedResponsesFeatureError(`instructions[${index}]`);+ }+ if (+ (part.type === 'input_text' || part.type === 'output_text' || part.type === 'text')+ && typeof part.text === 'string'+ ) {+ return part.text;+ }+ if (part.type === 'refusal' && typeof part.refusal === 'string') {+ return part.refusal;+ }+ throw new UnsupportedResponsesFeatureError(`instructions[${index}].${part.type}`);+ }).join('');+ if (instructions) messages.unshift({ role: developerRole, content: instructions });}- const out: ChatCompletionsRequest = {+ const request: ChatCompletionsRequest = {model: opts.model ?? input.model,messages,- stream: true,+ stream: input.stream !== false,};- const tools = translateTools(input.tools, opts.onDroppedTool);- // 空 tools 时**必须**连 tool_choice / parallel_tool_calls 一起省略:剥掉 Codex 内建工具后- // tools 可能变空,而 vLLM / 企业网关在没有 tools 却带 tool_choice 时会 400/503(cc-switch 同款守卫)。+ const tools = toolContext.chatTools;if (tools) {- out.tools = tools;- const toolChoice = translateToolChoice(input.tool_choice, capabilities.forceAutoToolChoice === true);- if (toolChoice !== undefined) out.tool_choice = toolChoice;+ request.tools = tools;+ const toolChoice = translateToolChoice(+ input.tool_choice,+ capabilities.forceAutoToolChoice === true,+ toolContext,+ );+ if (toolChoice !== undefined) request.tool_choice = toolChoice;if (capabilities.parallelToolCalls !== false && typeof input.parallel_tool_calls === 'boolean') {- out.parallel_tool_calls = input.parallel_tool_calls;+ request.parallel_tool_calls = input.parallel_tool_calls;}}if (typeof input.max_output_tokens === 'number') {switch (capabilities.maxTokensField ?? 'omit') {- case 'max_tokens': out.max_tokens = input.max_output_tokens; break;- case 'max_completion_tokens': out.max_completion_tokens = input.max_output_tokens; break;+ case 'max_tokens': request.max_tokens = input.max_output_tokens; break;+ case 'max_completion_tokens': request.max_completion_tokens = input.max_output_tokens; break;case 'omit': break;}}- if (- (capabilities.reasoningField ?? 'none') === 'reasoning_effort' &&- typeof input.reasoning?.effort === 'string'- ) {- out.reasoning_effort = input.reasoning.effort;+ applyReasoning(request, input, capabilities);+ applyPassthrough(request, input, capabilities.passthroughFields);+ if (request.stream && capabilities.streamUsage === true) {+ request.stream_options = { include_usage: true };}- if (capabilities.streamUsage === true) out.stream_options = { include_usage: true };- return out;+ return { request, toolContext };+}++/** Backward-compatible request-only entry point used by package consumers and unit tests. */+export function translateResponsesRequest(+ input: ResponsesRequest,+ opts: TranslateResponsesRequestOptions = {},+): ChatCompletionsRequest {+ return translateResponsesRequestWithContext(input, opts).request;}diff --git a/packages/responses-chat-bridge/src/types.ts b/packages/responses-chat-bridge/src/types.tsindex 491e74105e..46f6a9865a 100644--- a/packages/responses-chat-bridge/src/types.ts+++ b/packages/responses-chat-bridge/src/types.ts@@ -14,11 +14,38 @@ export interface ResponsesInputTextPart {export interface ResponsesInputImagePart {type: 'input_image';- image_url?: string;+ image_url?: string | {+ url: string;+ detail?: string;+ };file_id?: string;+ detail?: string;+}++export interface ResponsesInputFilePart {+ type: 'input_file';+ file_id?: string;+ file_data?: string;+ file_url?: string;+ filename?: string;+}++export interface ResponsesInputAudioPart {+ type: 'input_audio';+ input_audio?: {+ data: string;+ format: string;+ };+ data?: string;+ format?: string;}-export type ResponsesContentPart = ResponsesInputTextPart | ResponsesInputImagePart | {+export type ResponsesContentPart =+ | ResponsesInputTextPart+ | ResponsesInputImagePart+ | ResponsesInputFilePart+ | ResponsesInputAudioPart+ | {type: string;[key: string]: unknown;};@@ -66,15 +93,51 @@ export interface ResponsesFunctionTool {strict?: boolean;}+export interface ResponsesCustomTool {+ type: 'custom';+ name: string;+ description?: string;+ [key: string]: unknown;+}++export interface ResponsesNamespaceTool {+ type: 'namespace';+ name: string;+ tools?: Array<ResponsesFunctionTool | ResponsesCustomTool | { type: string; [key: string]: unknown }>;+ children?: Array<ResponsesFunctionTool | ResponsesCustomTool | { type: string; [key: string]: unknown }>;+ [key: string]: unknown;+}+export interface ResponsesRequest {model: string;- instructions?: string;+ instructions?: string | ResponsesContentPart[];input: string | ResponsesInputItem[];- tools?: Array<ResponsesFunctionTool | { type: string; [key: string]: unknown }>;+ tools?: Array<+ | string+ | ResponsesFunctionTool+ | ResponsesCustomTool+ | ResponsesNamespaceTool+ | { type: string; [key: string]: unknown }+ >;tool_choice?: unknown;parallel_tool_calls?: boolean;max_output_tokens?: number;reasoning?: { effort?: string; [key: string]: unknown };+ temperature?: number;+ top_p?: number;+ frequency_penalty?: number;+ presence_penalty?: number;+ stop?: string | string[];+ seed?: number;+ user?: string;+ metadata?: Record<string, unknown>;+ service_tier?: string;+ response_format?: unknown;+ text?: { format?: unknown; [key: string]: unknown };+ logit_bias?: Record<string, number>;+ logprobs?: boolean;+ top_logprobs?: number;+ n?: number;stream?: boolean;store?: boolean;[key: string]: unknown;@@ -89,10 +152,33 @@ export interface ChatImageUrlContentPart {type: 'image_url';image_url: {url: string;+ detail?: string;+ };+}++export interface ChatFileContentPart {+ type: 'file';+ file: {+ file_id?: string;+ file_data?: string;+ file_url?: string;+ filename?: string;};}-export type ChatUserContentPart = ChatTextContentPart | ChatImageUrlContentPart;+export interface ChatInputAudioContentPart {+ type: 'input_audio';+ input_audio: {+ data: string;+ format: string;+ };+}++export type ChatUserContentPart =+ | ChatTextContentPart+ | ChatImageUrlContentPart+ | ChatFileContentPart+ | ChatInputAudioContentPart;export interface ChatTextMessage {role: 'system' | 'developer';@@ -143,14 +229,54 @@ export interface ChatCompletionsRequest {max_tokens?: number;max_completion_tokens?: number;reasoning_effort?: string;- stream: true;+ reasoning?: { effort: string };+ thinking?: { type: string };+ enable_thinking?: boolean;+ reasoning_split?: boolean;+ temperature?: number;+ top_p?: number;+ frequency_penalty?: number;+ presence_penalty?: number;+ stop?: string | string[];+ seed?: number;+ user?: string;+ metadata?: Record<string, unknown>;+ service_tier?: string;+ response_format?: unknown;+ logit_bias?: Record<string, number>;+ logprobs?: boolean;+ top_logprobs?: number;+ stream: boolean;stream_options?: { include_usage: true };}export type ChatDeveloperRole = 'developer' | 'system';export type ChatMaxTokensField = 'max_tokens' | 'max_completion_tokens' | 'omit';-export type ChatReasoningField = 'reasoning_effort' | 'none';export type ChatImageInput = 'image_url';+export type ChatFileInput = 'file';+export type ChatAudioInput = 'input_audio';+export type ChatReasoningField =+ | 'reasoning_effort'+ | 'reasoning.effort'+ | 'thinking.type'+ | 'enable_thinking'+ | 'reasoning_split'+ | 'none';+export type ChatReasoningHistoryField = 'reasoning_content';+export type ChatPassthroughField =+ | 'temperature'+ | 'top_p'+ | 'frequency_penalty'+ | 'presence_penalty'+ | 'stop'+ | 'seed'+ | 'user'+ | 'metadata'+ | 'service_tier'+ | 'response_format'+ | 'logit_bias'+ | 'logprobs'+ | 'top_logprobs';/** 同协议族内的上游差异,全部由数据表达(对齐 cc-switch / opencodex 的 per-provider 处理)。 */export interface ChatBridgeCapabilities {@@ -158,12 +284,27 @@ export interface ChatBridgeCapabilities {parallelToolCalls?: boolean;maxTokensField?: ChatMaxTokensField;reasoningField?: ChatReasoningField;- streamUsage?: boolean;/**- * Responses `input_image` 的上游等价形态。默认未声明 = fail closed;只有已确认支持- * Chat Completions 视觉输入的运行时才开启,避免把图片静默丢掉或误发给纯文本上游。+ * Responses reasoning history 的 Chat 消息字段。默认未声明 = 省略历史 reasoning;+ * 只有明确接受厂商扩展 `reasoning_content` 的上游才应开启。+ */+ reasoningHistoryField?: ChatReasoningHistoryField;+ /**+ * Responses `input_image` 的上游等价形态。默认未声明 = fail closed;只由+ * 已确认支持视觉输入的运行时(当前为 upstream 白名单)开启。*/imageInput?: ChatImageInput;+ /** Responses `input_file` 的上游等价形态;默认未声明 = fail closed。 */+ fileInput?: ChatFileInput;+ /** Responses `input_audio` 的上游等价形态;默认未声明 = fail closed。 */+ audioInput?: ChatAudioInput;+ /** 仅对明确采用 `<think>...</think>` 内联推理方言的上游启用标签解析。 */+ inlineReasoning?: boolean;+ /** 将 Responses reasoning.effort 映射成供应商接受的枚举值。未声明时原样使用。 */+ reasoningEffortMap?: Readonly<Record<string, string | boolean>>;+ /** 只有显式列入的 Chat 可选字段才会转发,避免严格兼容端点因未知字段返回 400。 */+ passthroughFields?: readonly ChatPassthroughField[];+ streamUsage?: boolean;/*** thinking 模型(DeepSeek/Kimi/Moonshot)要求每个带 tool_calls 的 assistant 消息携带非空* reasoning_content,否则上游报 `reasoning_content is missing in assistant tool call message`。@@ -181,6 +322,8 @@ export interface ChatBridgeCapabilities {* `skip_thought_signature_validator`,避免桥接历史在首个工具调用后稳定 400。*/googleThoughtSignaturePlaceholder?: boolean;+ /** 缺少上游 usage 时仍生成 Responses 要求的完整零值 usage 结构。默认开启。 */+ zeroUsageOnMissing?: boolean;}export interface ChatBridgeLogger {