Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(codex): bridge Anthropic models through Responses (#1055)
JiangJiahao0724583073f6
diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex f28bd77717..b05ae0253a 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -77,6 +77,7 @@"@lezer/highlight": "^1.2.3","@cindy/anthropic-compat-proxy": "workspace:*","@cindy/anthropic-responses-bridge": "workspace:*",+ "@cindy/responses-anthropic-bridge": "workspace:*","@cindy/responses-chat-bridge": "workspace:*","@cindy/browser-control-runtime": "workspace:*","@cindy/device-link": "workspace:*",diff --git a/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts b/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.tsindex e270d49130..ff20d3c0a1 100644--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts@@ -8,7 +8,12 @@*/import { afterEach, describe, expect, it } from 'vitest';-import { BUNDLED_CATALOG, type Catalog, type CatalogModel } from '@cindy/model-providers';+import {+ BUNDLED_CATALOG,+ type AgentKind,+ type Catalog,+ type CatalogModel,+} from '@cindy/model-providers';import {getActiveCatalog,@@ -156,9 +161,9 @@ const anthro = (id: string, name: string, sortOrder: number): CatalogModel => ({status: 'active',});-function anthropicList(): CatalogModel[] {+function anthropicList(agent: AgentKind = 'claude-code'): CatalogModel[] {const p = getActiveCatalog().providers.find((x) => x.id === 'anthropic');- return p?.models['claude-code'] ?? [];+ return p?.models[agent] ?? [];}describe('anthropic 发现条目的 cindyModelMeta 元数据基线', () => {@@ -193,6 +198,12 @@ describe('anthropic 发现条目的 cindyModelMeta 元数据基线', () => {['claude-sonnet-4-5', 'Sonnet 4.5'],['claude-haiku-4-5', 'Haiku 4.5'],]);+ expect(anthropicList('codex')).toEqual(+ anthropicList('claude-code').map((model) => ({+ ...model,+ supportsFastMode: false,+ })),+ );expect(Object.fromEntries(['claude-fable-5','claude-opus-5',diff --git a/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts b/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.tsindex b14794127a..612e9b97c9 100644--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts@@ -15,10 +15,12 @@ import { BUNDLED_CATALOG, type CatalogModel } from '@cindy/model-providers';import {getActiveCatalog,+ isXdCodexAnthropicBridgeModel,setActiveCatalog,setAnthropicDiscoveredModels,setXdGatewayModels,} from '../active-catalog.js';+import { deriveAvailableModels } from '../catalog-to-descriptors.js';function xdModels(agent: 'claude-code' | 'codex') {const xd = getActiveCatalog().providers.find((p) => p.id === 'xd');@@ -45,11 +47,12 @@ describe('XD 网关权威模型清单重建', () => {expect(xdModels('codex')).toEqual([]);});- it('未登记模型的确定性默认:3 档 effort + fast=false + 仅 cc tab + 200k 窗口', () => {+ it('未登记模型按 Claude-only 兜底并投影到 Codex bridge:3 档 effort + fast=false + 200k 窗口', () => {setActiveCatalog(BUNDLED_CATALOG);setXdGatewayModels([{ id: 'brand-new-model' }]);const cc = xdModels('claude-code');+ const codex = xdModels('codex');expect(cc.map((m) => m.id)).toEqual(['brand-new-model']);expect(cc[0]).toMatchObject({name: 'brand-new-model',@@ -58,7 +61,31 @@ describe('XD 网关权威模型清单重建', () => {defaultEffort: 'high',supportsFastMode: false,});- expect(xdModels('codex')).toEqual([]);+ expect(codex).toEqual([+ {+ ...cc[0],+ codexCompatibilityWireProtocol: 'anthropic-messages',+ },+ ]);+ expect('codexCompatibilityWireProtocol' in cc[0]).toBe(false);+ expect(isXdCodexAnthropicBridgeModel('brand-new-model')).toBe(true);+ expect(+ deriveAvailableModels(getActiveCatalog(), 'codex').map((model) => model.id),+ ).toContain('brand-new-model');+ });++ it('Claude-only 模型投影到 Codex bridge 时清除未实现的 Fast 能力', () => {+ setActiveCatalog(BUNDLED_CATALOG);+ setXdGatewayModels([{+ id: 'fast-claude-only',+ agents: ['claude-code'],+ supportsFastMode: true,+ }]);+ expect(xdModels('claude-code')[0]?.supportsFastMode).toBe(true);+ expect(xdModels('codex')[0]).toMatchObject({+ supportsFastMode: false,+ codexCompatibilityWireProtocol: 'anthropic-messages',+ });});it('显式登记 efforts=[] 表示不可调,不合成 3 档;fast 显式 false 尊重', () => {@@ -101,6 +128,23 @@ describe('XD 网关权威模型清单重建', () => {defaultEffort: 'high',});}+ expect(isXdCodexAnthropicBridgeModel('gpt-5.6-sol')).toBe(false);+ expect('codexCompatibilityWireProtocol' in xdModels('codex')[0]).toBe(false);+ });++ it('仅 codex 的原生模型不投影到 Claude tab,也不标记为 bridge', () => {+ setActiveCatalog(BUNDLED_CATALOG);+ setXdGatewayModels([+ {+ id: 'codex-native-only',+ agents: ['codex'],+ name: 'Codex Native Only',+ },+ ]);++ expect(xdModels('claude-code')).toEqual([]);+ expect(xdModels('codex').map((model) => model.id)).toEqual(['codex-native-only']);+ expect(isXdCodexAnthropicBridgeModel('codex-native-only')).toBe(false);});it('perAgent 覆盖块按 tab 应用(cc 无 Fast + 1M 窗口;codex 保持基线)', () => {@@ -234,9 +278,9 @@ describe('XD 网关权威模型清单重建', () => {});describe('Anthropic 权威模型清单注入', () => {- function anthropicModels() {+ function anthropicModels(agent: 'claude-code' | 'codex' = 'claude-code') {const p = getActiveCatalog().providers.find((x) => x.id === 'anthropic');- return p?.models['claude-code'] ?? [];+ return p?.models[agent] ?? [];}const opus: CatalogModel = {@@ -261,8 +305,13 @@ describe('Anthropic 权威模型清单注入', () => {setAnthropicDiscoveredModels([opus]);expect(anthropicModels().map((m) => m.id)).toEqual(['claude-opus-4-8']);expect(anthropicModels()[0]).toMatchObject({ name: 'Opus 4.8', supportsFastMode: true });+ expect(anthropicModels('codex')[0]).toMatchObject({+ name: 'Opus 4.8',+ supportsFastMode: false,+ });setAnthropicDiscoveredModels([]);expect(anthropicModels()).toEqual([]);+ expect(anthropicModels('codex')).toEqual([]);});it('注入 anthropic 不影响其它供应商(xai 静态清单逐字不变)', () => {diff --git a/apps/desktop/src/main/maker-host/__tests__/anthropicImageCodec.test.ts b/apps/desktop/src/main/maker-host/__tests__/anthropicImageCodec.test.tsnew file mode 100644index 0000000000..4ebea04c8a--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/anthropicImageCodec.test.ts@@ -0,0 +1,84 @@+import { Buffer } from 'node:buffer';++import sharp from 'sharp';+import { describe, expect, it } from 'vitest';++import { desktopAnthropicImageCodec } from '../anthropic-image-codec.js';++const TINY_PNG =+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=';++describe('desktopAnthropicImageCodec', () => {+ it('passes through a small valid PNG without changing its bytes or media type', async () => {+ await expect(desktopAnthropicImageCodec.normalize({+ data: TINY_PNG,+ mediaType: 'image/png',+ maxEdge: 2000,+ qualities: [80],+ hardCap: 2 * 1024 * 1024,+ })).resolves.toEqual({ data: TINY_PNG, mediaType: 'image/png' });+ });++ it('uses the decoded image format instead of an untrusted declared media type', async () => {+ const jpeg = await sharp({+ create: {+ width: 2,+ height: 2,+ channels: 3,+ background: '#336699',+ },+ }).jpeg().toBuffer();+ const data = jpeg.toString('base64');++ await expect(desktopAnthropicImageCodec.normalize({+ data,+ mediaType: 'image/png',+ maxEdge: 2000,+ qualities: [80],+ hardCap: 2 * 1024 * 1024,+ })).resolves.toEqual({ data, mediaType: 'image/jpeg' });+ });++ it('rejects malformed base64 before decoding', async () => {+ await expect(desktopAnthropicImageCodec.normalize({+ data: 'not*base64',+ mediaType: 'image/png',+ maxEdge: 2000,+ qualities: [80],+ hardCap: 2 * 1024 * 1024,+ })).resolves.toBeNull();+ });++ it('resizes an oversized image and re-encodes it as JPEG', async () => {+ const input = await sharp({+ create: {+ width: 3000,+ height: 2000,+ channels: 3,+ background: '#336699',+ },+ }).png().toBuffer();+ const output = await desktopAnthropicImageCodec.normalize({+ data: input.toString('base64'),+ mediaType: 'image/png',+ maxEdge: 1024,+ qualities: [70, 50],+ hardCap: 512 * 1024,+ });+ expect(output?.mediaType).toBe('image/jpeg');+ const metadata = await sharp(Buffer.from(output!.data, 'base64')).metadata();+ expect(Math.max(metadata.width ?? 0, metadata.height ?? 0)).toBeLessThanOrEqual(1024);+ });++ it('rejects image inputs above the decoded pixel safety limit', async () => {+ const svg =+ '<svg xmlns="http://www.w3.org/2000/svg" width="10001" height="10001"><rect width="100%" height="100%"/></svg>';+ await expect(desktopAnthropicImageCodec.normalize({+ data: Buffer.from(svg).toString('base64'),+ mediaType: 'image/svg+xml',+ maxEdge: 2000,+ qualities: [80],+ hardCap: 2 * 1024 * 1024,+ })).resolves.toBeNull();+ });+});diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.tsindex 035e64961e..9b40a56e28 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts@@ -25,6 +25,7 @@ const mockState = vi.hoisted(() => {},createAnthropicCompatProxy: vi.fn(),createResponsesChatHandler: vi.fn(() => ({ handle: vi.fn(async () => undefined) })),+ createResponsesAnthropicHandler: vi.fn(() => ({ handle: vi.fn(async () => undefined) })),injectionTransform: vi.fn<(body: unknown, ctx: unknown) => unknown | null>(() => null),stripNonAnthropicFields: vi.fn<(body: unknown, ctx: unknown) => unknown | null>(() => null),recordXaiRateLimitSnapshot: vi.fn(),@@ -104,10 +105,15 @@ vi.mock('@cindy/responses-chat-bridge', () => ({createResponsesChatHandler: mockState.createResponsesChatHandler,}));+vi.mock('@cindy/responses-anthropic-bridge', () => ({+ createResponsesAnthropicHandler: mockState.createResponsesAnthropicHandler,+}));+async function freshCodexProxyHost() {vi.resetModules();mockState.createAnthropicCompatProxy.mockReset();mockState.createResponsesChatHandler.mockClear();+ mockState.createResponsesAnthropicHandler.mockClear();mockState.createInstructionsInjectionTransform.mockClear();mockState.injectionTransform.mockReset();mockState.injectionTransform.mockReturnValue(null);@@ -226,6 +232,57 @@ describe('withCodexUpstreamRecording', () => {}});+ it('records the Anthropic bridge upstream even though it routes through a localHandler', async () => {+ const host = await freshCodexProxyHost();+ host.resetCodexThreadUpstreamForTest();+ const { buildUserProvider } = await import('@cindy/model-providers');+ const { setCustomProviders } = await import('../active-catalog.js');+ const { setCustomProviderKeyReader } = await import('../provider-route.js');+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');+ setCustomProviders([+ buildUserProvider({+ id: 'anthropic-compatible',+ name: 'Anthropic Compatible',+ runtimes: {+ codex: {+ baseUrl: 'https://messages.provider.example/v1',+ wireProtocol: 'anthropic-messages',+ models: [{ id: 'claude-compatible', name: 'Claude Compatible' }],+ },+ },+ }),+ ]);+ setCustomProviderKeyReader(() => 'provider-key');+ host.registerComposed('session-anthropic-diag', 'thread-anthropic-diag', 'PRODUCT_PROMPT');+ setSessionProvider('session-anthropic-diag', 'anthropic-compatible');+ host.setCodexProxyAuthInjection('env-key');++ try {+ const decision = await Promise.resolve(host.createModelRoutingTransform()(+ { model: 'claude-compatible' },+ {+ reqId: 1,+ method: 'POST',+ url: '/responses',+ headers: { 'thread-id': 'thread-anthropic-diag' },+ },+ ));+ expect(decision).toEqual(expect.objectContaining({ localHandler: expect.any(Function) }));+ expect(host.getCodexThreadUpstreamOrigin('thread-anthropic-diag')).toBe(+ 'https://messages.provider.example',+ );+ const anthropicHandlerCalls = mockState.createResponsesAnthropicHandler.mock.calls as unknown as Array<[+ { promptCaching: boolean; automaticPromptCaching: boolean },+ ]>;+ const config = anthropicHandlerCalls.at(-1)?.[0];+ expect(config?.promptCaching).toBe(false);+ expect(config?.automaticPromptCaching).toBe(false);+ } finally {+ clearSessionProvider('session-anthropic-diag');+ setCustomProviders([]);+ }+ });+it('never lets a recording failure affect forwarding', async () => {// 诊断旁路:默认上游取值抛错也不能影响 decision。const host = await freshCodexProxyHost();@@ -530,6 +587,732 @@ describe('chatBridgeCapabilitiesForRoute', () => {setCustomProviderKeyReader(() => null);setCustomProviders([]);});++ it('routes a custom Codex Anthropic Messages runtime to the local bridge with provider-owned auth', async () => {+ const host = await freshCodexProxyHost();+ const { buildUserProvider } = await import('@cindy/model-providers');+ const { setCustomProviders } = await import('../active-catalog.js');+ const { setCustomProviderKeyReader } = await import('../provider-route.js');+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');+ setCustomProviders([+ buildUserProvider({+ id: 'custom-anthropic',+ name: 'Custom Anthropic',+ runtimes: {+ codex: {+ baseUrl: 'https://api.anthropic.com',+ wireProtocol: 'anthropic-messages',+ models: [{ id: 'claude-sonnet-4-6', name: 'Claude Sonnet 4.6' }],+ },+ },+ }),+ ]);+ setCustomProviderKeyReader(() => 'anthropic-key');+ host.registerComposed('session-anthropic', 'thread-anthropic', 'PRODUCT_PROMPT');+ setSessionProvider('session-anthropic', 'custom-anthropic');+ host.setCodexProxyAuthInjection('env-key');++ const decision = await Promise.resolve(host.createModelRoutingTransform()(+ {+ model: 'claude-sonnet-4-6',+ input: [{ role: 'user', content: 'hello' }],+ },+ {+ reqId: 1,+ method: 'POST',+ url: '/responses',+ headers: { 'thread-id': 'thread-anthropic' },+ },+ ));++ expect(decision).toEqual(expect.objectContaining({ localHandler: expect.any(Function) }));+ expect(mockState.createResponsesAnthropicHandler).toHaveBeenCalledWith(+ expect.objectContaining({+ upstreamBase: 'https://api.anthropic.com',+ buildHeaders: expect.any(Function),+ }),+ expect.anything(),+ );+ const anthropicHandlerCalls = mockState.createResponsesAnthropicHandler.mock.calls as unknown as Array<[+ {+ promptCaching: boolean;+ automaticPromptCaching: boolean;+ strictTools: boolean;+ buildHeaders: () => Promise<Record<string, string>>;+ },+ ]>;+ const config = anthropicHandlerCalls.at(-1)?.[0];+ expect(config).toBeDefined();+ if (!config) throw new Error('Anthropic bridge config was not captured');+ expect(await config.buildHeaders()).toEqual({+ 'x-api-key': 'anthropic-key',+ authorization: 'Bearer anthropic-key',+ });+ expect(config.promptCaching).toBe(true);+ expect(config.automaticPromptCaching).toBe(true);+ expect(config.strictTools).toBe(true);++ clearSessionProvider('session-anthropic');+ setCustomProviderKeyReader(() => null);+ setCustomProviders([]);+ });++ it('routes the built-in Anthropic subscription through the bridge with host-owned Claude.ai OAuth', async () => {+ const host = await freshCodexProxyHost();+ const { setAnthropicDiscoveredModels } = await import('../active-catalog.js');+ const { setProviderOAuthTokenReader } = await import('../provider-route.js');+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');+ setAnthropicDiscoveredModels([+ {+ id: 'claude-opus-5',+ name: 'Opus 5',+ contextWindow: 1_000_000,+ efforts: ['low', 'medium', 'high'],+ defaultEffort: 'high',+ status: 'active',+ },+ {+ id: 'claude-sonnet-4-5',+ name: 'Sonnet 4.5',+ contextWindow: 200_000,+ efforts: ['low', 'medium', 'high'],+ defaultEffort: 'high',+ status: 'active',+ },+ ]);+ setProviderOAuthTokenReader((providerId, agent) =>+ providerId === 'anthropic' && agent === 'codex'+ ? Promise.resolve('claude-subscription-token')+ : null,+ );+ host.registerComposed(+ 'session-anthropic-subscription',+ 'thread-anthropic-subscription',+ 'PRODUCT_PROMPT',+ );+ setSessionProvider('session-anthropic-subscription', 'anthropic');+ host.setCodexProxyAuthInjection('oauth-bearer');++ const decision = await Promise.resolve(host.createModelRoutingTransform()(+ {+ model: 'claude-opus-5',+ input: [{ role: 'user', content: 'hello' }],+ },+ {+ reqId: 1,+ method: 'POST',+ url: '/responses',+ headers: {+ 'thread-id': 'thread-anthropic-subscription',+ authorization: 'Bearer codex-openai-token-must-not-leak',+ 'chatgpt-account-id': 'account-must-not-leak',+ },+ },+ ));++ expect(decision).toEqual(expect.objectContaining({ localHandler: expect.any(Function) }));+ const anthropicHandlerCalls = mockState.createResponsesAnthropicHandler.mock.calls as unknown as Array<[+ {+ buildHeaders: () => Promise<Record<string, string>>;+ rewriteModel: (model: string) => string;+ },+ ]>;+ const config = anthropicHandlerCalls.at(-1)?.[0];+ expect(config).toBeDefined();+ if (!config) throw new Error('Anthropic subscription bridge config was not captured');+ const headers = await config.buildHeaders();+ expect(headers).toEqual(expect.objectContaining({+ 'anthropic-version': '2023-06-01',+ authorization: 'Bearer claude-subscription-token',+ 'x-app': 'cli',+ 'x-stainless-runtime': 'node',+ 'x-claude-code-session-id': expect.any(String),+ 'x-client-request-id': expect.any(String),+ }));+ expect(headers['anthropic-beta']?.split(',')).toEqual([+ 'claude-code-20250219',+ 'oauth-2025-04-20',+ 'context-1m-2025-08-07',+ ]);+ expect(config.rewriteModel('claude-opus-5[1m]')).toBe('claude-opus-5');++ await Promise.resolve(host.createModelRoutingTransform()(+ {+ model: 'claude-sonnet-4-5',+ input: [{ role: 'user', content: 'short context' }],+ },+ {+ reqId: 2,+ method: 'POST',+ url: '/responses',+ headers: {+ 'thread-id': 'thread-anthropic-subscription',+ },+ },+ ));+ const ordinaryConfig = (mockState.createResponsesAnthropicHandler.mock.calls as unknown as Array<[+ { buildHeaders: () => Promise<Record<string, string>> },+ ]>).at(-1)?.[0];+ expect(ordinaryConfig).toBeDefined();+ if (!ordinaryConfig) throw new Error('ordinary Anthropic bridge config was not captured');+ expect((await ordinaryConfig.buildHeaders())['anthropic-beta']?.split(',')).toEqual([+ 'claude-code-20250219',+ 'oauth-2025-04-20',+ ]);++ clearSessionProvider('session-anthropic-subscription');+ setProviderOAuthTokenReader(() => null);+ setAnthropicDiscoveredModels([]);+ });++ it('refreshes non-Anthropic provider OAuth without applying Claude.ai credentials or policy', async () => {+ const host = await freshCodexProxyHost();+ const { BUNDLED_CATALOG } = await import('@cindy/model-providers');+ const { setActiveCatalog } = await import('../active-catalog.js');+ const { setProviderOAuthTokenReader } = await import('../provider-route.js');+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');+ const catalog = structuredClone(BUNDLED_CATALOG);+ const xai = catalog.providers.find((provider) => provider.id === 'xai');+ if (!xai?.routing.codex) throw new Error('expected bundled xAI Codex route');+ xai.routing.codex = {+ ...xai.routing.codex,+ wireProtocol: 'anthropic-messages',+ };+ setActiveCatalog(catalog);+ const tokenReader = vi.fn((providerId: string, agent: string, options?: { forceRefresh?: boolean }) => (+ providerId === 'xai' && agent === 'codex'+ ? options?.forceRefresh ? 'xai-refreshed-token' : 'xai-initial-token'+ : null+ ));+ setProviderOAuthTokenReader(tokenReader);+ host.registerComposed('session-xai-anthropic-wire', 'thread-xai-anthropic-wire', 'PRODUCT_PROMPT');+ setSessionProvider('session-xai-anthropic-wire', 'xai');+ host.setCodexProxyAuthInjection('oauth-bearer');++ try {+ const decision = await Promise.resolve(host.createModelRoutingTransform()(+ {+ model: 'xai/grok-4.3',+ input: [{ role: 'user', content: 'hello' }],+ },+ {+ reqId: 1,+ method: 'POST',+ url: '/responses',+ headers: { 'thread-id': 'thread-xai-anthropic-wire' },+ },+ ));+ expect(decision).toEqual(expect.objectContaining({ localHandler: expect.any(Function) }));+ const anthropicHandlerCalls = mockState.createResponsesAnthropicHandler.mock.calls as unknown as Array<[+ {+ authMode: string;+ buildHeaders: () => Promise<Record<string, string>>;+ refreshHeaders: (input: {+ status: 401 | 403;+ body: string;+ requestHeaders: Readonly<Record<string, string>>;+ }) => Promise<Record<string, string> | null>;+ },+ ]>;+ const config = anthropicHandlerCalls.at(-1)?.[0];+ expect(config).toBeDefined();+ if (!config) throw new Error('xAI Anthropic bridge config was not captured');+ expect(config.authMode).toBe('api-key');+ const initialHeaders = await config.buildHeaders();+ expect(initialHeaders.authorization).toBe('Bearer xai-initial-token');+ expect(initialHeaders).not.toHaveProperty('x-app');+ expect(initialHeaders).not.toHaveProperty('x-claude-code-session-id');++ const refreshedHeaders = await config.refreshHeaders({+ status: 401,+ body: 'expired',+ requestHeaders: initialHeaders,+ });+ expect(refreshedHeaders?.authorization).toBe('Bearer xai-refreshed-token');+ expect(refreshedHeaders).not.toHaveProperty('x-app');+ expect(tokenReader).toHaveBeenLastCalledWith('xai', 'codex', {+ forceRefresh: true,+ staleToken: 'xai-initial-token',+ });+ expect(tokenReader.mock.calls.some(([providerId]) => providerId === 'anthropic')).toBe(false);+ } finally {+ clearSessionProvider('session-xai-anthropic-wire');+ setProviderOAuthTokenReader(() => null);+ setActiveCatalog(BUNDLED_CATALOG);+ }+ });++ it('routes only XD Claude-only models through the Anthropic bridge in env-key mode', async () => {+ const host = await freshCodexProxyHost();+ const { setXdGatewayModels } = await import('../active-catalog.js');+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');+ setXdGatewayModels([+ { id: 'gpt-native', agents: ['claude-code', 'codex'] },+ { id: 'claude-bridge', agents: ['claude-code'] },+ ]);+ host.setCodexProxyGatewayKeyReader(() => 'xd-gateway-key');+ host.registerComposed('session-xd-bridge', 'thread-xd-bridge', 'PRODUCT_PROMPT');+ setSessionProvider('session-xd-bridge', 'xd');+ host.setCodexProxyAuthInjection('env-key');++ const bridgeDecision = await Promise.resolve(host.createModelRoutingTransform()(+ {+ model: 'claude-bridge[1m]',+ input: [{ role: 'user', content: 'hello' }],+ },+ {+ reqId: 1,+ method: 'POST',+ url: '/responses',+ headers: {+ 'thread-id': 'thread-xd-bridge',+ authorization: 'Bearer codex-token-must-not-leak',+ 'chatgpt-account-id': 'account-must-not-leak',+ },+ },+ ));++ expect(bridgeDecision).toEqual(expect.objectContaining({ localHandler: expect.any(Function) }));+ expect(host.registerChildThread('thread-xd-bridge', 'thread-xd-child')).toBe(true);+ const childBridgeDecision = await Promise.resolve(host.createModelRoutingTransform()(+ {+ model: 'claude-bridge',+ input: [{ role: 'user', content: 'child hello' }],+ },+ {+ reqId: 2,+ method: 'POST',+ url: '/responses',+ headers: { 'thread-id': 'thread-xd-child' },+ },+ ));+ expect(childBridgeDecision).toEqual(expect.objectContaining({ localHandler: expect.any(Function) }));++ expect(host.registerChildThread('thread-xd-child', 'thread-xd-grandchild')).toBe(true);+ const grandchildBridgeDecision = await Promise.resolve(host.createModelRoutingTransform()(+ {+ model: 'claude-bridge',+ input: [{ role: 'user', content: 'grandchild hello' }],+ },+ {+ reqId: 3,+ method: 'POST',+ url: '/responses',+ headers: { 'thread-id': 'thread-xd-grandchild' },+ },+ ));+ expect(grandchildBridgeDecision).toEqual(expect.objectContaining({ localHandler: expect.any(Function) }));++ const anthropicHandlerCalls = mockState.createResponsesAnthropicHandler.mock.calls as unknown as Array<[+ {+ upstreamBase: string;+ promptCaching: boolean;+ automaticPromptCaching: boolean;+ strictTools: boolean;+ buildHeaders: () => Promise<Record<string, string>>;+ rewriteModel: (model: string) => string;+ },+ ]>;+ const config = anthropicHandlerCalls[0]?.[0];+ expect(config).toBeDefined();+ if (!config) throw new Error('XD Anthropic bridge config was not captured');+ expect(config.upstreamBase).toBe(XD_GATEWAY_BASE_URL);+ expect(config.promptCaching).toBe(true);+ expect(config.automaticPromptCaching).toBe(false);+ expect(config.strictTools).toBe(false);+ expect(await config.buildHeaders()).toEqual({+ 'x-api-key': 'xd-gateway-key',+ authorization: 'Bearer xd-gateway-key',+ 'anthropic-beta': 'context-1m-2025-08-07',+ });+ expect(config.rewriteModel('claude-bridge[1m]')).toBe('claude-bridge');++ const nativeDecision = await Promise.resolve(host.createModelRoutingTransform()(+ {+ model: 'gpt-native',+ input: [{ role: 'user', content: 'hello' }],+ },+ {+ reqId: 4,+ method: 'POST',+ url: '/responses',+ headers: { 'thread-id': 'thread-xd-grandchild' },+ },+ ));+ expect(nativeDecision).toBeNull();+ expect(mockState.createResponsesAnthropicHandler).toHaveBeenCalledTimes(3);++ host.unregister('session-xd-bridge');+ expect(host.registerChildThread('thread-xd-bridge', 'thread-after-close')).toBe(false);+ expect(host.registerChildThread('thread-xd-child', 'thread-after-child-close')).toBe(false);+ expect(host.registerChildThread('thread-xd-grandchild', 'thread-after-grandchild-close')).toBe(false);+ const closedChildDecision = await Promise.resolve(host.createModelRoutingTransform()(+ {+ model: 'claude-bridge',+ input: [{ role: 'user', content: 'closed child' }],+ },+ {+ reqId: 5,+ method: 'POST',+ url: '/responses',+ headers: { 'thread-id': 'thread-xd-child' },+ },+ ));+ expect(closedChildDecision).toBeNull();+ expect(mockState.createResponsesAnthropicHandler).toHaveBeenCalledTimes(3);++ clearSessionProvider('session-xd-bridge');+ setXdGatewayModels([]);+ host.setCodexProxyGatewayKeyReader(() => null);+ });++ it('routes an implicit XD Claude-only model through the Anthropic bridge', async () => {+ const host = await freshCodexProxyHost();+ const {+ getActiveCatalog,+ setAnthropicDiscoveredModels,+ setXdGatewayModels,+ } = await import('../active-catalog.js');+ const { setProviderViewsReader } = await import('../provider-route.js');+ const { clearSessionProvider } = await import('../session-provider-store.js');+ setAnthropicDiscoveredModels([{+ id: 'claude-implicit-xd',+ name: 'Implicit Shared Claude',+ group: 'anthropic',+ contextWindow: 200_000,+ efforts: ['low', 'medium', 'high'],+ defaultEffort: 'high',+ status: 'active',+ }]);+ setXdGatewayModels([{ id: 'claude-implicit-xd', agents: ['claude-code'] }]);+ setProviderViewsReader(async () => getActiveCatalog().providers.map((provider) => ({+ ...provider,+ connected: provider.id === 'xd' || provider.id === 'anthropic',+ })));+ host.setCodexProxyGatewayKeyReader(() => 'xd-gateway-key');+ host.registerComposed(+ 'session-implicit-xd',+ 'thread-implicit-xd',+ 'PRODUCT_PROMPT',+ );+ clearSessionProvider('session-implicit-xd');+ host.setCodexProxyAuthInjection('env-key');++ try {+ const decision = await Promise.resolve(host.createModelRoutingTransform()(+ {+ model: 'claude-implicit-xd[1m]',+ input: [{ role: 'user', content: 'hello' }],+ },+ {+ reqId: 1,+ method: 'POST',+ url: '/responses',+ headers: { 'thread-id': 'thread-implicit-xd' },+ },+ ));++ expect(decision).toEqual(expect.objectContaining({ localHandler: expect.any(Function) }));+ const anthropicHandlerCalls = mockState.createResponsesAnthropicHandler.mock.calls as unknown as Array<[+ {+ upstreamBase: string;+ authMode: string;+ buildHeaders: () => Promise<Record<string, string>>;+ },+ ]>;+ const config = anthropicHandlerCalls.at(-1)?.[0];+ expect(config).toBeDefined();+ if (!config) throw new Error('implicit XD Anthropic bridge config was not captured');+ expect(config.upstreamBase).toBe(XD_GATEWAY_BASE_URL);+ expect(config.authMode).toBe('api-key');+ expect(await config.buildHeaders()).toEqual({+ 'x-api-key': 'xd-gateway-key',+ authorization: 'Bearer xd-gateway-key',+ 'anthropic-beta': 'context-1m-2025-08-07',+ });+ } finally {+ host.unregister('session-implicit-xd');+ clearSessionProvider('session-implicit-xd');+ setAnthropicDiscoveredModels([]);+ setXdGatewayModels([]);+ setProviderViewsReader(async () => []);+ host.setCodexProxyGatewayKeyReader(() => null);+ }+ });++ it('does not read live ProviderView credentials for a native Codex model', async () => {+ const host = await freshCodexProxyHost();+ const { setProviderViewsReader } = await import('../provider-route.js');+ const { setXdGatewayModels } = await import('../active-catalog.js');+ const { clearSessionProvider } = await import('../session-provider-store.js');+ const providerViewsReader = vi.fn(async () => {+ throw new Error('native model must not read provider credentials');+ });+ setProviderViewsReader(providerViewsReader);+ setXdGatewayModels([{ id: 'gpt-native-hot-path', agents: ['codex'] }]);+ host.registerComposed(+ 'session-native-hot-path',+ 'thread-native-hot-path',+ 'PRODUCT_PROMPT',+ );+ clearSessionProvider('session-native-hot-path');+ host.setCodexProxyAuthInjection('env-key');++ try {+ const decision = await Promise.resolve(host.createModelRoutingTransform()(+ {+ model: 'gpt-native-hot-path',+ input: [{ role: 'user', content: 'hello' }],+ },+ {+ reqId: 1,+ method: 'POST',+ url: '/responses',+ headers: { 'thread-id': 'thread-native-hot-path' },+ },+ ));++ expect(decision).toBeNull();+ expect(providerViewsReader).not.toHaveBeenCalled();+ } finally {+ host.unregister('session-native-hot-path');+ clearSessionProvider('session-native-hot-path');+ setProviderViewsReader(async () => []);+ setXdGatewayModels([]);+ }+ });++ it('does not overwrite a child thread that is already owned by another session', async () => {+ const host = await freshCodexProxyHost();+ host.registerComposed('session-parent', 'thread-parent', 'PARENT_PROMPT');+ host.registerComposed('session-owner', 'thread-owned', 'OWNER_PROMPT');++ expect(host.registerChildThread('thread-parent', 'thread-owned')).toBe(false);++ host.unregister('session-parent');+ expect(host.registerChildThread('thread-owned', 'thread-owned-child')).toBe(true);++ host.unregister('session-owner');+ });++ it('fails an XD bridged model locally when the gateway key is unavailable', async () => {+ const host = await freshCodexProxyHost();+ const { setXdGatewayModels } = await import('../active-catalog.js');+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');+ setXdGatewayModels([{ id: 'claude-bridge', agents: ['claude-code'] }]);+ host.setCodexProxyGatewayKeyReader(() => null);+ host.registerComposed('session-xd-no-key', 'thread-xd-no-key', 'PRODUCT_PROMPT');+ setSessionProvider('session-xd-no-key', 'xd');+ host.setCodexProxyAuthInjection('env-key');++ const decision = await Promise.resolve(host.createModelRoutingTransform()(+ {+ model: 'claude-bridge',+ input: [{ role: 'user', content: 'hello' }],+ },+ {+ reqId: 1,+ method: 'POST',+ url: '/responses',+ headers: { 'thread-id': 'thread-xd-no-key' },+ },+ ));++ expect(decision).toEqual(expect.objectContaining({ localHandler: expect.any(Function) }));+ expect(mockState.createResponsesAnthropicHandler).not.toHaveBeenCalled();++ clearSessionProvider('session-xd-no-key');+ setXdGatewayModels([]);+ });++ it('fails the built-in Anthropic subscription bridge locally when Claude.ai OAuth is missing', async () => {+ const host = await freshCodexProxyHost();+ const { setProviderOAuthTokenReader } = await import('../provider-route.js');+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');+ setProviderOAuthTokenReader(() => null);+ host.registerComposed(+ 'session-anthropic-no-auth',+ 'thread-anthropic-no-auth',+ 'PRODUCT_PROMPT',+ );+ setSessionProvider('session-anthropic-no-auth', 'anthropic');++ const decision = await Promise.resolve(host.createModelRoutingTransform()(+ {+ model: 'claude-opus-5',+ input: [{ role: 'user', content: 'hello' }],+ },+ {+ reqId: 1,+ method: 'POST',+ url: '/responses',+ headers: { 'thread-id': 'thread-anthropic-no-auth' },+ },+ ));++ expect(decision).toEqual(expect.objectContaining({ localHandler: expect.any(Function) }));+ expect(mockState.createResponsesAnthropicHandler).not.toHaveBeenCalled();++ clearSessionProvider('session-anthropic-no-auth');+ });++ it('routes an implicit Anthropic-only model through the subscription bridge', async () => {+ const host = await freshCodexProxyHost();+ const {+ getActiveCatalog,+ setAnthropicDiscoveredModels,+ setXdGatewayModels,+ } = await import('../active-catalog.js');+ const {+ setProviderOAuthTokenReader,+ setProviderViewsReader,+ } = await import('../provider-route.js');+ const { clearSessionProvider } = await import('../session-provider-store.js');+ setAnthropicDiscoveredModels([{+ id: 'claude-implicit-anthropic',+ name: 'Implicit Anthropic',+ group: 'anthropic',+ contextWindow: 200_000,+ efforts: ['low', 'medium', 'high'],+ defaultEffort: 'high',+ status: 'active',+ }]);+ setXdGatewayModels([]);+ setProviderViewsReader(async () => getActiveCatalog().providers.map((provider) => ({+ ...provider,+ connected: provider.id === 'anthropic',+ })));+ setProviderOAuthTokenReader((providerId, agent) => (+ providerId === 'anthropic' && agent === 'codex'+ ? 'claude-subscription-token'+ : null+ ));+ host.registerComposed(+ 'session-implicit-anthropic',+ 'thread-implicit-anthropic',+ 'PRODUCT_PROMPT',+ );+ clearSessionProvider('session-implicit-anthropic');+ host.setCodexProxyAuthInjection('oauth-bearer');++ try {+ const decision = await Promise.resolve(host.createModelRoutingTransform()(+ {+ model: 'claude-implicit-anthropic',+ input: [{ role: 'user', content: 'hello' }],+ },+ {+ reqId: 1,+ method: 'POST',+ url: '/responses',+ headers: { 'thread-id': 'thread-implicit-anthropic' },+ },+ ));++ expect(decision).toEqual(expect.objectContaining({ localHandler: expect.any(Function) }));+ const anthropicHandlerCalls = mockState.createResponsesAnthropicHandler.mock.calls as unknown as Array<[+ {+ upstreamBase: string;+ authMode: string;+ buildHeaders: () => Promise<Record<string, string>>;+ },+ ]>;+ const config = anthropicHandlerCalls.at(-1)?.[0];+ expect(config).toBeDefined();+ if (!config) throw new Error('implicit Anthropic bridge config was not captured');+ expect(config.upstreamBase).toBe('https://api.anthropic.com');+ expect(config.authMode).toBe('oauth');+ expect(await config.buildHeaders()).toEqual(expect.objectContaining({+ authorization: 'Bearer claude-subscription-token',+ 'x-app': 'cli',+ }));+ } finally {+ host.unregister('session-implicit-anthropic');+ clearSessionProvider('session-implicit-anthropic');+ setProviderOAuthTokenReader(() => null);+ setProviderViewsReader(async () => []);+ setAnthropicDiscoveredModels([]);+ }+ });++ it('falls back to connected Anthropic when XD advertises the model without credentials', async () => {+ const host = await freshCodexProxyHost();+ const {+ getActiveCatalog,+ setAnthropicDiscoveredModels,+ setXdGatewayModels,+ } = await import('../active-catalog.js');+ const {+ setProviderOAuthTokenReader,+ setProviderViewsReader,+ } = await import('../provider-route.js');+ const { clearSessionProvider } = await import('../session-provider-store.js');+ const model: import('@cindy/model-providers').CatalogModel = {+ id: 'claude-connected-anthropic',+ name: 'Connected Anthropic',+ group: 'anthropic',+ contextWindow: 200_000,+ efforts: ['low', 'medium', 'high'],+ defaultEffort: 'high',+ status: 'active',+ };+ setAnthropicDiscoveredModels([model]);+ setXdGatewayModels([{ id: model.id, agents: ['claude-code'] }]);+ setProviderViewsReader(async () => getActiveCatalog().providers.map((provider) => ({+ ...provider,+ connected: provider.id === 'anthropic',+ })));+ setProviderOAuthTokenReader((providerId, agent) => (+ providerId === 'anthropic' && agent === 'codex'+ ? 'claude-subscription-token'+ : null+ ));+ host.registerComposed(+ 'session-connected-anthropic',+ 'thread-connected-anthropic',+ 'PRODUCT_PROMPT',+ );+ clearSessionProvider('session-connected-anthropic');+ host.setCodexProxyGatewayKeyReader(() => null);+ host.setCodexProxyAuthInjection('oauth-bearer');++ try {+ const decision = await Promise.resolve(host.createModelRoutingTransform()(+ {+ model: model.id,+ input: [{ role: 'user', content: 'hello' }],+ },+ {+ reqId: 1,+ method: 'POST',+ url: '/responses',+ headers: { 'thread-id': 'thread-connected-anthropic' },+ },+ ));++ expect(decision).toEqual(expect.objectContaining({ localHandler: expect.any(Function) }));+ const config = (mockState.createResponsesAnthropicHandler.mock.calls as unknown as Array<[+ {+ upstreamBase: string;+ authMode: string;+ buildHeaders: () => Promise<Record<string, string>>;+ },+ ]>).at(-1)?.[0];+ expect(config?.upstreamBase).toBe('https://api.anthropic.com');+ expect(config?.authMode).toBe('oauth');+ expect(await config?.buildHeaders()).toEqual(expect.objectContaining({+ authorization: 'Bearer claude-subscription-token',+ }));+ } finally {+ host.unregister('session-connected-anthropic');+ clearSessionProvider('session-connected-anthropic');+ setProviderOAuthTokenReader(() => null);+ setProviderViewsReader(async () => []);+ setAnthropicDiscoveredModels([]);+ setXdGatewayModels([]);+ host.setCodexProxyGatewayKeyReader(() => null);+ }+ });});describe('createModelRoutingTransform —— session-less 控制面请求(桶③)', () => {@@ -1053,6 +1836,84 @@ describe('codex proxy host', () => {setCustomProviders([]);});+ it('passes the parent session model into a Guardian request handled by the Anthropic bridge', async () => {+ const host = await freshCodexProxyHost();+ const { buildUserProvider } = await import('@cindy/model-providers');+ const { setCustomProviders } = await import('../active-catalog.js');+ const { setCustomProviderKeyReader } = await import('../provider-route.js');+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');+ setCustomProviders([+ buildUserProvider({+ id: 'guardian-anthropic-provider',+ name: 'Guardian Anthropic Provider',+ runtimes: {+ codex: {+ baseUrl: 'https://anthropic-provider.example',+ wireProtocol: 'anthropic-messages',+ models: [{ id: 'claude-sonnet-4-6', name: 'Claude Sonnet 4.6' }],+ },+ },+ }),+ ]);+ setCustomProviderKeyReader(() => 'anthropic-provider-key');+ host.setCodexProxyAuthInjection('env-key');+ host.registerReviewerRouteContext(+ 'session-anthropic-review',+ 'thread-anthropic-parent',+ 'claude-sonnet-4-6',+ );+ setSessionProvider('session-anthropic-review', 'guardian-anthropic-provider');++ const rawGuardianBody = {+ model: 'codex-auto-review',+ tools: [+ { type: 'function', name: 'shell' },+ { type: 'web_search' },+ { type: 'x_search' },+ ],+ input: [{ role: 'user', content: 'review this action' }],+ };+ const ctx = {+ reqId: 1,+ method: 'POST',+ url: '/responses',+ headers: {+ 'thread-id': 'guardian-child-anthropic',+ 'x-openai-subagent': 'guardian',+ 'x-codex-parent-thread-id': 'thread-anthropic-parent',+ },+ };+ const decision = await Promise.resolve(+ host.createModelRoutingTransform()(rawGuardianBody, ctx),+ );+ expect(decision).toEqual(expect.objectContaining({ localHandler: expect.any(Function) }));+ if (!decision?.localHandler) throw new Error('expected Anthropic bridge local handler');++ const res = {} as never;+ await decision.localHandler({+ rawBody: Buffer.from(JSON.stringify(rawGuardianBody)),+ parsedBody: rawGuardianBody,+ ctx,+ res,+ });+ const bridge = mockState.createResponsesAnthropicHandler.mock.results.at(-1)?.value as+ | { handle: ReturnType<typeof vi.fn> }+ | undefined;+ expect(bridge?.handle).toHaveBeenCalledWith({+ parsedBody: {+ ...rawGuardianBody,+ model: 'claude-sonnet-4-6',+ tools: [{ type: 'function', name: 'shell' }],+ },+ ctx,+ res,+ });++ clearSessionProvider('session-anthropic-review');+ setCustomProviderKeyReader(() => null);+ setCustomProviders([]);+ });+it('restores native web_search for Gateway GPT-5.6 when Codex omitted the declaration', async () => {const host = await freshCodexProxyHost();const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');diff --git a/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts b/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.tsindex 15e0a7b2b4..2efa2c8596 100644--- a/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts@@ -258,6 +258,21 @@ describe('custom-provider-store CRUD (per-runtime)', () => {expect((await getCustomProvider('openrouter'))?.runtimes.codex?.wireProtocol).toBe('openai-chat');});+ it('round-trips an explicit Anthropic Messages protocol for Codex', async () => {+ mountDb();+ await createCustomProvider({+ ...valid,+ runtimes: {+ codex: {+ ...valid.runtimes.codex!,+ baseUrl: 'https://api.anthropic.com',+ wireProtocol: 'anthropic-messages',+ },+ },+ });+ expect((await getCustomProvider('openrouter'))?.runtimes.codex?.wireProtocol).toBe('anthropic-messages');+ });+it('preserves legacy remote auth:none records for repair without deleting them', async () => {mountDb();raw!.prepare(diff --git a/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.tsindex a06241a624..ec729a607e 100644--- a/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/providerCatalogRealmReload.test.ts@@ -83,6 +83,7 @@ vi.mock('../provider-route.js', () => ({setCustomProviderKeyReader: () => undefined,setOAuthTokenReader: () => undefined,setProviderOAuthTokenReader: () => undefined,+ setProviderViewsReader: () => undefined,}));vi.mock('../provider-diagnostics.js', () => ({setDiagnosticsKeyReader: () => undefined,diff --git a/apps/desktop/src/main/maker-host/__tests__/providerDiagnostics.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerDiagnostics.test.tsindex 3e3028b49d..03500add1a 100644--- a/apps/desktop/src/main/maker-host/__tests__/providerDiagnostics.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/providerDiagnostics.test.ts@@ -81,6 +81,55 @@ describe('classifyProviderError', () => {});describe('buildProbeRequest', () => {+ it('Codex Anthropic Messages probe uses x-api-key and Messages endpoint', () => {+ const { url, init } = buildProbeRequest({+ agent: 'codex',+ wireProtocol: 'anthropic-messages',+ baseUrl: 'https://api.anthropic.com',+ modelId: 'claude-opus-5',+ apiKey: 'sk-test',+ headers: {+ 'Anthropic-Version': 'custom-version',+ 'Content-Type': 'text/plain',+ },+ });+ expect(url).toBe('https://api.anthropic.com/v1/messages');+ const headers = init.headers as Record<string, string>;+ expect(headers['anthropic-version']).toBe('custom-version');+ expect(headers['Anthropic-Version']).toBeUndefined();+ expect(headers['content-type']).toBe('application/json');+ expect(headers['Content-Type']).toBeUndefined();+ expect(headers['x-api-key']).toBe('sk-test');+ expect(headers.authorization).toBe('Bearer sk-test');+ expect(JSON.parse(String(init.body))).toMatchObject({+ model: 'claude-opus-5',+ max_tokens: 1,+ });+ });++ it('Codex Anthropic Messages probe matches runtime joining for a versioned base URL', () => {+ const { url } = buildProbeRequest({+ agent: 'codex',+ wireProtocol: 'anthropic-messages',+ baseUrl: 'https://provider.example/v1',+ modelId: 'claude-sonnet-4-6',+ });+ expect(url).toBe('https://provider.example/v1/messages');+ });++ it('Codex Anthropic Messages probe preserves custom path and query joining', () => {+ const { url } = buildProbeRequest({+ agent: 'codex',+ wireProtocol: 'anthropic-messages',+ baseUrl: 'https://provider.example/api/v1?tenant=alpha',+ requestPath: '/tenant/messages?beta=true',+ modelId: 'claude-sonnet-4-6',+ });+ expect(url).toBe(+ 'https://provider.example/api/v1/tenant/messages?tenant=alpha&beta=true',+ );+ });+it('cc wire:/v1/messages + anthropic-version + 双鉴权头(与 api-key-header 路由分支对齐)', () => {const { url, init } = buildProbeRequest({agent: 'claude-code',@@ -218,7 +267,7 @@ describe('buildProbeRequest', () => {});expect(init.headers).toEqual({'content-type': 'application/json',- 'X-Tenant': 'local',+ 'x-tenant': 'local',});});});@@ -343,8 +392,10 @@ describe('resolveSavedProbeSpec / testProviderConnection(saved)', () => {});const headers = buildProbeRequest(spec).init.headers as Record<string, string>;- expect(headers.Authorization).toBe('Bearer stale');- expect(headers['X-API-Key']).toBe('stale');+ expect(headers.authorization).toBe('Bearer stale');+ expect(headers['x-api-key']).toBe('stale');+ expect(headers.Authorization).toBeUndefined();+ expect(headers['X-API-Key']).toBeUndefined();});it('api-key-header + openai-chat 供应商:saved 探测带上 wireProtocol → 打 /chat/completions', async () => {diff --git a/apps/desktop/src/main/maker-host/__tests__/providerModelFetch.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerModelFetch.test.tsindex ee4088c561..38e514a700 100644--- a/apps/desktop/src/main/maker-host/__tests__/providerModelFetch.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/providerModelFetch.test.ts@@ -70,6 +70,21 @@ describe('buildModelsFetchRequest', () => {expect(codex['authorization']).toBe('Bearer sk-test');});+ it('Codex Anthropic Messages bridge sends provider-owned x-api-key and Bearer', () => {+ const headers = buildModelsFetchRequest(+ spec({+ agent: 'codex',+ wireProtocol: 'anthropic-messages',+ baseUrl: 'https://api.anthropic.com',+ headers: { 'Anthropic-Version': 'custom-version' },+ }),+ ).init.headers as Record<string, string>;+ expect(headers['anthropic-version']).toBe('custom-version');+ expect(headers['Anthropic-Version']).toBeUndefined();+ expect(headers['x-api-key']).toBe('sk-test');+ expect(headers.authorization).toBe('Bearer sk-test');+ });+it('omits auth headers without apiKey and keeps custom headers', () => {const h = buildModelsFetchRequest(spec({ apiKey: null, headers: { 'x-extra': '1' } })).init.headers as Record<string, string>;@@ -204,4 +219,23 @@ describe('fetchProviderModels', () => {expect(seenHeaders['x-api-key']).toBe('sk-test');expect(seenHeaders['anthropic-version']).toBe('2023-06-01');});++ it('end-to-end Codex Anthropic discovery uses the Messages authentication headers', async () => {+ let seenHeaders: Record<string, string> = {};+ const result = await fetchProviderModels(+ spec({+ agent: 'codex',+ wireProtocol: 'anthropic-messages',+ baseUrl: 'https://api.anthropic.com',+ }),+ async (_url, init) => {+ seenHeaders = (init?.headers ?? {}) as Record<string, string>;+ return fakeResponse(200, JSON.stringify({ data: [{ id: 'claude-opus-5' }] }));+ },+ );+ expect(result.ok).toBe(true);+ expect(seenHeaders['x-api-key']).toBe('sk-test');+ expect(seenHeaders.authorization).toBe('Bearer sk-test');+ expect(seenHeaders['anthropic-version']).toBe('2023-06-01');+ });});diff --git a/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.ts b/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.tsindex c75bd96a7f..9acba1af3b 100644--- a/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/providerRoute.test.ts@@ -14,6 +14,8 @@ import {beginProviderRouteMutation,buildLocalHandlerHeaders,buildRouteDecision,+ getSessionRoutingDescriptor,+ resolveSessionRoute,resolveSessionRouteDecision,inferProviderIdForModel,isUserProviderSession,@@ -57,6 +59,8 @@ afterEach(() => {setProviderOAuthTokenReader(() => null);clearSessionProvider('s-xai');clearSessionProvider('s-xai-rewrite');+ clearSessionProvider('s-anthropic-codex');+ clearSessionProvider('s-xd-model-wire');setXdGatewayModels([]);});@@ -124,6 +128,25 @@ describe('codex: buildRouteDecision no-break 基线', () => {headerOverride: { authorization: 'Bearer xdt-missing-provider-oauth-token' },}));});++ it('Anthropic subscription → Claude.ai bearer + OAuth beta,不透传 Codex 账号头', () => {+ const fromCatalog = buildRouteDecision(+ descriptor('anthropic', 'codex'),+ KEY,+ 'codex',+ null,+ 'claude-subscription-token',+ );+ expect(fromCatalog).toEqual({+ upstreamOverride: 'https://api.anthropic.com',+ headerOverride: {+ 'anthropic-version': '2023-06-01',+ 'anthropic-beta': 'claude-code-20250219,oauth-2025-04-20',+ authorization: 'Bearer claude-subscription-token',+ },+ headerDelete: CODEX_ACCOUNT_HEADER_DELETE,+ });+ });});describe('resolveSessionRouteDecision (per-session 选择 → 路由;no-break fallback)', () => {@@ -153,6 +176,36 @@ describe('resolveSessionRouteDecision (per-session 选择 → 路由;no-break fa});});+ it('codex 会话选 XD:原生模型保持 Responses,Claude-only 投影模型派生 Anthropic bridge wire', async () => {+ setXdGatewayModels([+ { id: 'gpt-native', agents: ['claude-code', 'codex'] },+ { id: 'claude-bridge', agents: ['claude-code'] },+ ]);+ setSessionProvider('s-xd-model-wire', 'xd');++ expect(getSessionRoutingDescriptor('s-xd-model-wire', 'codex', 'gpt-native'))+ .toMatchObject({+ authStrategy: 'gateway-key',+ });+ expect(getSessionRoutingDescriptor('s-xd-model-wire', 'codex', 'gpt-native')?.wireProtocol)+ .toBeUndefined();++ expect(getSessionRoutingDescriptor('s-xd-model-wire', 'codex', 'claude-bridge[1m]'))+ .toMatchObject({+ authStrategy: 'gateway-key',+ wireProtocol: 'anthropic-messages',+ });+ await expect(resolveSessionRoute('s-xd-model-wire', 'codex', 'claude-bridge[1m]'))+ .resolves.toMatchObject({+ providerId: 'xd',+ providerSource: 'builtin',+ routing: {+ authStrategy: 'gateway-key',+ wireProtocol: 'anthropic-messages',+ },+ });+ });+it('codex 会话选 xAI → 异步读取 xAI OAuth token 并路由到 api.x.ai', async () => {setSessionProvider('s-xai', 'xai');setProviderOAuthTokenReader((providerId, agent) =>@@ -190,9 +243,44 @@ describe('resolveSessionRouteDecision (per-session 选择 → 路由;no-break fasetProviderOAuthTokenReader(() => null);});- it('选的供应商对该 agent 无效(Anthropic 用在 codex)→ null(回落默认)', () => {- setSessionProvider('s-mismatch', 'anthropic');- expect(resolveSessionRouteDecision('s-mismatch', 'codex', KEY)).toBeNull();+ it('codex 会话选 Anthropic → 本地桥读取 Claude.ai OAuth,缺失时也 fail closed', async () => {+ setSessionProvider('s-anthropic-codex', 'anthropic');+ setProviderOAuthTokenReader((providerId, agent) =>+ providerId === 'anthropic' && agent === 'codex'+ ? Promise.resolve('claude-subscription-token')+ : null,+ );+ const route = await resolveSessionRoute(+ 's-anthropic-codex',+ 'codex',+ 'claude-opus-5',+ );+ expect(route).toMatchObject({+ providerId: 'anthropic',+ providerSource: 'builtin',+ oauthToken: 'claude-subscription-token',+ routing: {+ wireProtocol: 'anthropic-messages',+ authStrategy: 'provider-oauth-header',+ },+ });+ expect(buildLocalHandlerHeaders(route!, 'codex')).toEqual({+ headers: {+ 'anthropic-version': '2023-06-01',+ 'anthropic-beta': 'claude-code-20250219,oauth-2025-04-20',+ authorization: 'Bearer claude-subscription-token',+ },+ headerDelete: CODEX_ACCOUNT_HEADER_DELETE,+ });++ setProviderOAuthTokenReader(() => null);+ const missing = await resolveSessionRoute(+ 's-anthropic-codex',+ 'codex',+ 'claude-opus-5',+ );+ expect(buildLocalHandlerHeaders(missing!, 'codex').headers.authorization)+ .toBe('Bearer xdt-missing-provider-oauth-token');});it('按 catalog modelIdRewrite 剥 xAI 内部前缀', () => {diff --git a/apps/desktop/src/main/maker-host/active-catalog.ts b/apps/desktop/src/main/maker-host/active-catalog.tsindex 71380b1b51..6ba76b6191 100644--- a/apps/desktop/src/main/maker-host/active-catalog.ts+++ b/apps/desktop/src/main/maker-host/active-catalog.ts@@ -108,6 +108,14 @@ export interface XdGatewayModelInfo {* - 目录里有、网关没有 → 不展示。*/let xdGatewayModels: XdGatewayModelInfo[] = [];+/**+ * XD 服务端只声明 claude-code、未声明 codex 的聊天模型。+ *+ * 这些模型在客户端投影进 Codex 选择器,但请求必须走本地+ * Responses → Anthropic Messages bridge,不能误用 XD 的原生 Responses 路由。+ * Set 在模型目录刷新时一次性派生,路由热路径只做 O(1) 查询。+ */+let xdCodexAnthropicBridgeModelIds = new Set<string>();/*** Anthropic(Claude.ai 订阅)的**权威模型清单**(2026-07-19 统一重构):由 host 的@@ -129,6 +137,35 @@ const VALID_EFFORTS: ReadonlySet<string> = new Set([type Effort = CatalogModel['efforts'][number];+function xdGatewayTargetAgents(model: XdGatewayModelInfo): AgentKind[] {+ return model.agents && model.agents.length > 0 ? model.agents : ['claude-code'];+}++function deriveXdCodexAnthropicBridgeModelIds(+ models: XdGatewayModelInfo[],+): Set<string> {+ const support = new Map<string, { claudeCode: boolean; codex: boolean }>();+ for (const model of models) {+ const current = support.get(model.id) ?? { claudeCode: false, codex: false };+ for (const agent of xdGatewayTargetAgents(model)) {+ if (agent === 'claude-code') current.claudeCode = true;+ else if (agent === 'codex') current.codex = true;+ }+ support.set(model.id, current);+ }+ return new Set(+ [...support]+ .filter(([, agents]) => agents.claudeCode && !agents.codex)+ .map(([modelId]) => modelId),+ );+}++/** 当前 XD 模型是否由客户端投影给 Codex、并应走 Anthropic Messages bridge。 */+export function isXdCodexAnthropicBridgeModel(modelId: string): boolean {+ // Codex 会把 1M 上下文选择编码成 wire model 后缀;目录身份仍是原始 model id。+ return xdCodexAnthropicBridgeModelIds.has(modelId.replace(/\[1m\]$/, ''));+}+function nonNegativeFiniteOrUndefined(value: number | undefined): number | undefined {return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;}@@ -486,8 +523,21 @@ function computeMerged(): Catalog {const overlaid = sortModelsByOrder(anthropicModels.map((m) => overlayCindyMeta(m, metaIndex.get(m.id))),);+ const codexBridgeModels = overlaid.map((model) => ({+ ...model,+ supportsFastMode: false,+ }));providers = providers.map((p) =>- p.id === 'anthropic' ? { ...p, models: { ...p.models, 'claude-code': overlaid } } : p,+ p.id === 'anthropic'+ ? {+ ...p,+ models: {+ ...p.models,+ 'claude-code': overlaid,+ codex: codexBridgeModels,+ },+ }+ : p,);}@@ -510,8 +560,7 @@ function computeMerged(): Catalog {for (const agent of agentKeys) models[agent] = [];for (const gm of gwModels) {// tab 归属:服务端 agents > 仅 claude-code(网关 /v1/messages 翻译覆盖面最广,不猜)- const targetAgents: AgentKind[] =- gm.agents && gm.agents.length > 0 ? gm.agents : ['claude-code'];+ const targetAgents = xdGatewayTargetAgents(gm);for (const agent of targetAgents) {if (!models[agent]) continue; // 未知 agent 键防御(wire 数据)const ov = gm.perAgent?.[agent] ?? {};@@ -554,6 +603,21 @@ function computeMerged(): Catalog {models[agent]!.push(merged);}}+ // 服务端明确没有 codex 的 Claude-wire 模型仍可由本地 bridge 服务。选择器需要看到+ // 它们,但路由身份保留在 xdCodexAnthropicBridgeModelIds,不能把投影误当原生支持。+ const claudeModels = models['claude-code'] ?? [];+ const codexModels = models.codex;+ if (codexModels) {+ for (const model of claudeModels) {+ if (xdCodexAnthropicBridgeModelIds.has(model.id)) {+ codexModels.push({+ ...model,+ supportsFastMode: false,+ codexCompatibilityWireProtocol: 'anthropic-messages',+ });+ }+ }+ }// 每个 tab 内按 sortOrder 稳定排序(无 sortOrder 的合成条目排最后,按进入序)。for (const agent of agentKeys) {models[agent] = models[agent]!.map((model, index) => ({ model, index }))@@ -580,6 +644,33 @@ export function getActiveCatalog(): Catalog {return merged;}+/**+ * 返回指定 provider/agent 下模型的目录上下文窗口。+ *+ * Codex wire model 可能带有 `[1m]` 展示后缀,或被 route 的 stripPrefix+ * 包了一层;目录始终保存原始模型 id,因此查询在这里统一做去后缀/去前缀+ * 候选归一,避免各个上游 bridge 自己复制一份模型匹配逻辑。+ */+export function getCatalogModelContextWindow(+ providerId: string,+ agent: AgentKind,+ modelId: string,+ stripPrefix?: string,+): number | null {+ const candidates = new Set<string>([+ modelId,+ modelId.replace(/\[1m\]$/, ''),+ ]);+ if (stripPrefix && modelId.startsWith(stripPrefix)) {+ const stripped = modelId.slice(stripPrefix.length);+ candidates.add(stripped);+ candidates.add(stripped.replace(/\[1m\]$/, ''));+ }+ const provider = getActiveCatalog().providers.find((entry) => entry.id === providerId);+ const model = provider?.models[agent]?.find((entry) => candidates.has(entry.id));+ return model?.contextWindow ?? null;+}+/** 由 host 的目录加载器(ensureActiveCatalogLoaded)在拉取成功后写入基础目录。 */export function setActiveCatalog(catalog: Catalog): void {base = catalog;@@ -648,6 +739,7 @@ export function setDiscoveredProviderModels(*/export function setXdGatewayModels(models: XdGatewayModelInfo[]): void {xdGatewayModels = [...models];+ xdCodexAnthropicBridgeModelIds = deriveXdCodexAnthropicBridgeModelIds(models);markChanged();}diff --git a/apps/desktop/src/main/maker-host/anthropic-image-codec.ts b/apps/desktop/src/main/maker-host/anthropic-image-codec.tsnew file mode 100644index 0000000000..59dec63860--- /dev/null+++ b/apps/desktop/src/main/maker-host/anthropic-image-codec.ts@@ -0,0 +1,97 @@+import type {+ AnthropicImageCodec,+ AnthropicImageCodecInput,+ AnthropicImageCodecOutput,+} from '@cindy/responses-anthropic-bridge';+import { Buffer } from 'node:buffer';+import sharp from 'sharp';++const MAX_INPUT_PIXELS = 100_000_000;+const PASSTHROUGH_MEDIA_TYPES = new Set([+ 'image/jpeg',+ 'image/png',+ 'image/gif',+ 'image/webp',+]);+const MEDIA_TYPE_BY_SHARP_FORMAT: Readonly<Record<string, string>> = {+ jpeg: 'image/jpeg',+ png: 'image/png',+ gif: 'image/gif',+ webp: 'image/webp',+};++function strictBase64Bytes(data: string): Buffer | null {+ const compact = data.replace(/\s/g, '');+ if (+ compact.length === 0+ || compact.length % 4 === 1+ || !/^[A-Za-z0-9+/]*={0,2}$/.test(compact)+ ) return null;+ try {+ return Buffer.from(compact, 'base64');+ } catch {+ return null;+ }+}++/**+ * Desktop's native Sharp-backed codec. It performs the actual decode/resize work while+ * the bridge package remains responsible for age tiers, request budgets, and ordering.+ */+class DesktopAnthropicImageCodec implements AnthropicImageCodec {+ async normalize(input: AnthropicImageCodecInput): Promise<AnthropicImageCodecOutput | null> {+ const bytes = strictBase64Bytes(input.data);+ if (!bytes) return null;+ try {+ const source = sharp(bytes, {+ failOn: 'error',+ limitInputPixels: MAX_INPUT_PIXELS,+ animated: false,+ }).rotate();+ const metadata = await source.metadata();+ const width = metadata.width ?? 0;+ const height = metadata.height ?? 0;+ const decodedMediaType = metadata.format+ ? MEDIA_TYPE_BY_SHARP_FORMAT[metadata.format]+ : undefined;+ if (+ width <= 0+ || height <= 0+ || width * height > MAX_INPUT_PIXELS+ ) return null;++ if (+ decodedMediaType+ && PASSTHROUGH_MEDIA_TYPES.has(decodedMediaType)+ && width <= input.maxEdge+ && height <= input.maxEdge+ && input.data.length <= input.hardCap+ ) {+ // metadata() is header-only; force one decoded pixel before trusting passthrough.+ await source.clone().resize(1, 1).jpeg({ quality: 1 }).toBuffer();+ return { data: input.data, mediaType: decodedMediaType };+ }++ const resized = source.resize({+ width: input.maxEdge,+ height: input.maxEdge,+ fit: 'inside',+ withoutEnlargement: true,+ });+ let last: Buffer | null = null;+ for (const quality of input.qualities) {+ last = await resized.clone().jpeg({ quality }).toBuffer();+ const data = last.toString('base64');+ if (data.length <= input.hardCap) return { data, mediaType: 'image/jpeg' };+ }+ return last+ ? { data: last.toString('base64'), mediaType: 'image/jpeg' }+ : null;+ } catch {+ return null;+ }+ }+}++export const desktopAnthropicImageCodec: AnthropicImageCodec =+ new DesktopAnthropicImageCodec();diff --git a/apps/desktop/src/main/maker-host/codex-proxy-host.ts b/apps/desktop/src/main/maker-host/codex-proxy-host.tsindex 67d49ea843..1e56543860 100644--- a/apps/desktop/src/main/maker-host/codex-proxy-host.ts+++ b/apps/desktop/src/main/maker-host/codex-proxy-host.ts@@ -35,11 +35,14 @@ import {createResponsesChatHandler,type ChatBridgeCapabilities,} from '@cindy/responses-chat-bridge';+import { createResponsesAnthropicHandler } from '@cindy/responses-anthropic-bridge';+import { createHash, randomUUID } from 'node:crypto';import fs from 'node:fs';import path from 'node:path';import { buildCodexGatewayBaseUrl, CODEX_OAUTH_UPSTREAM } from './codex-gateway-config.js';-import { getActiveCatalog } from './active-catalog.js';+import { claudeUpstreamEndpoint } from './runtime-configs.js';+import { getActiveCatalog, getCatalogModelContextWindow } from './active-catalog.js';import {gatewayDefaultRouteDecision,getSessionRoutingDescriptor,@@ -50,7 +53,9 @@ import {isHostInjectedAuthSession,isUserProviderSession,getUserProviderIdForSession,+ readProviderOAuthToken,providerRoutingServesWireModel,+ resolveImplicitLocalBridgeRoute,resolveImplicitProviderOAuthRouteDecision,resolveProviderOAuthControlRouteDecision,rewriteImplicitModelIdForRoute,@@ -65,6 +70,7 @@ import { encryptedStripController, imageGenerationStripController } from './threimport { createMakerLogger } from './logger-adapter.js';import { resolveDesktopOutboundProxy } from './outbound-proxy-resolver.js';import { outboundFetch } from './outbound-fetch.js';+import { desktopAnthropicImageCodec } from './anthropic-image-codec.js';import { readSilentEncryptedRetrySettings } from './silent-encrypted-retry-store.js';import { getLogDir } from '../logger.js';import { recordXaiRateLimitSnapshot } from '../usageBroadcaster.js';@@ -74,6 +80,7 @@ const log = createMakerLogger('codex-proxy');const registry = createInstructionsRegistry();const sessionToThread = new Map<string, string>();+const sessionToThreads = new Map<string, Set<string>>();const threadToSession = new Map<string, string>();const reviewerModelBySession = new Map<string, string>();@@ -505,64 +512,372 @@ function createChatBridgeDecision(}, { logger: log, fetchImpl: outboundFetch });return {localHandler: ({ rawBody, parsedBody, res }) => {- let body = parsedBody;- const strippedBody = stripImageGenerationItemsWithoutIdFromBody(rawBody);- if (strippedBody) {- try {- body = JSON.parse(strippedBody.toString('utf8'));- } catch {- // Keep the already parsed body if the defensive strip result cannot be parsed.+ const body = prepareLocalBridgeBody({+ rawBody,+ parsedBody,+ instructions,+ requestModelOverride,+ bridge: 'chat',+ providerId,+ upstreamBase: route.routing.upstream,+ });+ return handler.handle({ parsedBody: body, res });+ },+ };+}++interface PrepareLocalBridgeBodyOptions {+ rawBody: Buffer;+ parsedBody: unknown;+ instructions?: string;+ requestModelOverride?: string;+ bridge: 'chat' | 'anthropic';+ providerId: string;+ upstreamBase: string;+}++/**+ * localHandler runs before the shared request transform chain. Keep the preprocessing+ * needed by every Responses bridge in one place so adding another wire adapter cannot+ * accidentally lose product instructions or cross-provider compaction recovery.+ */+function prepareLocalBridgeBody(opts: PrepareLocalBridgeBodyOptions): unknown {+ let body = opts.parsedBody;+ const strippedBody = stripImageGenerationItemsWithoutIdFromBody(opts.rawBody);+ if (strippedBody) {+ try {+ body = JSON.parse(strippedBody.toString('utf8'));+ } catch {+ // Keep the already parsed body if the defensive strip result cannot be parsed.+ }+ }+ if (opts.requestModelOverride && isPlainObject(body)) {+ body = stripGuardianProviderSearchTools({+ ...body,+ model: opts.requestModelOverride,+ });+ }+ if (opts.instructions && isPlainObject(body)) {+ 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 (requestModelOverride && isPlainObject(body)) {- body = stripGuardianProviderSearchTools({- ...body,- model: requestModelOverride,+ if (part.type === 'refusal' && typeof part.refusal === 'string') return part.refusal;+ return '';+ }).join('')+ : typeof existing === 'string'+ ? existing+ : '';+ body = {+ ...body,+ instructions: existingText.includes(opts.instructions)+ ? existing+ : Array.isArray(existing)+ ? [...existing, { type: 'input_text', text: `\n\n${opts.instructions}` }]+ : [existingText, opts.instructions].filter(Boolean).join('\n\n'),+ };+ }+ const compactionSafe = replaceEncryptedCompactionItems(body);+ if (compactionSafe) {+ log.info('replaced encrypted compaction history for local bridge upstream', {+ bridge: opts.bridge,+ providerId: opts.providerId,+ upstreamBase: opts.upstreamBase,+ });+ body = compactionSafe;+ }+ return body;+}++function rewriteAnthropicBridgeModel(model: string, stripPrefix: string | undefined): string {+ const stripped = stripPrefix && model.startsWith(stripPrefix) ? model.slice(stripPrefix.length) : model;+ return stripped.replace(/\[1m\]$/, '');+}++function isOfficialAnthropicUpstream(value: string): boolean {+ try {+ return new URL(value).hostname.toLowerCase() === 'api.anthropic.com';+ } catch {+ return false;+ }+}++function anthropicBridgeUpstreamBase(+ route: NonNullable<Awaited<ReturnType<typeof resolveSessionRoute>>>,+): string {+ const isXdGatewayBridge =+ route.providerId === 'xd' && route.routing.authStrategy === 'gateway-key';+ return isXdGatewayBridge+ ? claudeUpstreamEndpoint().trim()+ : route.routing.upstream;+}++function appendCommaSeparatedHeaderToken(+ headers: Record<string, string>,+ name: string,+ token: string,+): void {+ const existingName = Object.keys(headers).find((candidate) => (+ candidate.toLowerCase() === name.toLowerCase()+ ));+ const existing = existingName ? headers[existingName] : '';+ const values = existing+ .split(',')+ .map((value) => value.trim())+ .filter(Boolean);+ if (!values.includes(token)) values.push(token);+ if (existingName && existingName !== name) delete headers[existingName];+ headers[name] = values.join(',');+}++function claudeCodeSessionId(token: string): string {+ const hash = createHash('sha256')+ .update(`claude-code-session:${token}`, 'utf8')+ .digest('hex');+ const variant = ((Number.parseInt(hash[16], 16) & 0x3) | 0x8).toString(16);+ return `${hash.slice(0, 8)}-${hash.slice(8, 12)}-4${hash.slice(13, 16)}-${variant}${hash.slice(17, 20)}-${hash.slice(20, 32)}`;+}++function claudeOAuthHeaders(+ base: Record<string, string>,+ token: string,+): Record<string, string> {+ return {+ ...base,+ authorization: `Bearer ${token}`,+ 'anthropic-beta': 'claude-code-20250219,oauth-2025-04-20',+ 'user-agent': '@anthropic-ai/sdk/0.74.0',+ 'x-app': 'cli',+ 'x-stainless-retry-count': '0',+ 'x-stainless-runtime': 'node',+ 'x-stainless-lang': 'js',+ 'x-stainless-timeout': '600',+ 'x-stainless-arch': process.arch,+ 'x-stainless-os': process.platform,+ 'x-stainless-package-version': '0.74.0',+ 'x-stainless-runtime-version': process.version.slice(1),+ 'x-claude-code-session-id': claudeCodeSessionId(token),+ 'x-client-request-id': randomUUID(),+ };+}++/**+ * Responses → Anthropic Messages local bridge. The bridge owns both request and+ * response translation; this host layer only resolves the selected provider, supplies+ * provider-owned credentials, and restores preprocessing skipped by localHandler.+ */+function createAnthropicBridgeDecision(+ route: Awaited<ReturnType<typeof resolveSessionRoute>>,+ instructions: string | undefined,+ wireModel: string,+ requestModelOverride?: string,+): RoutingDecision | null {+ if (!route || route.routing.wireProtocol !== 'anthropic-messages') return null;+ const isXdGatewayBridge =+ route.providerId === 'xd' && route.routing.authStrategy === 'gateway-key';+ const gatewayKey = isXdGatewayBridge ? _readGatewayKey() : null;+ const upstreamBase = anthropicBridgeUpstreamBase(route);+ if (isXdGatewayBridge && (!gatewayKey || !upstreamBase)) {+ return {+ localHandler: async ({ res }) => {+ res.writeHead(503, {+ 'content-type': 'application/json; charset=utf-8',+ 'cache-control': 'no-store',});- }- if (instructions && isPlainObject(body)) {- 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: existingText.includes(instructions)- ? existing- : Array.isArray(existing)- ? [...existing, { type: 'input_text', text: `\n\n${instructions}` }]- : [existingText, instructions].filter(Boolean).join('\n\n'),- };- }- // localHandler 在 transform 链**之前**执行(引擎按路由决策短路),跨来源恢复的- // 加密压缩块不会被 createCrossProviderCompactionCompatTransform 处理;而 bridge- // 的翻译层遇到 compaction 项会按不支持的输入 400(Greptile P1 第二轮)。Chat- // bridge 目标上游定义上永远不是 ChatGPT,这里无条件做同一份替换。- const compactionSafe = replaceEncryptedCompactionItems(body);- if (compactionSafe) {- log.info('replaced encrypted compaction history for chat-bridge upstream', {- providerId,- upstreamBase: route.routing.upstream,+ res.end(JSON.stringify({+ error: {+ type: 'authentication_error',+ code: 'cindy_gateway_credentials_unavailable',+ message: 'Cindy AI credentials are not ready for this bridged model.',+ },+ }));+ },+ };+ }+ // For Codex, provider-oauth-header is the subscription-safe route: the host+ // injects the Claude.ai token and never forwards the Codex/OpenAI bearer.+ if (+ route.providerId === 'anthropic'+ && route.providerSource === 'builtin'+ && route.routing.authStrategy === 'provider-oauth-header'+ && !route.oauthToken+ ) {+ return {+ localHandler: async ({ res }) => {+ res.writeHead(401, {+ 'content-type': 'application/json; charset=utf-8',+ 'cache-control': 'no-store',});- body = compactionSafe;+ res.end(JSON.stringify({+ error: {+ type: 'authentication_error',+ code: 'anthropic_subscription_auth_required',+ message: 'Connect a Claude.ai subscription before using Anthropic models in Codex.',+ },+ }));+ },+ };+ }+ const usesProviderOAuth = route.routing.authStrategy === 'provider-oauth-header';+ const isAnthropicSubscriptionOAuth =+ usesProviderOAuth+ && route.providerId === 'anthropic'+ && route.providerSource === 'builtin';+ const buildProviderHeaders = (token: string | null): Record<string, string> => {+ const { headers: baseHeaders } = buildLocalHandlerHeaders(+ token === route.oauthToken ? route : { ...route, oauthToken: token },+ 'codex',+ );+ let headers = { ...baseHeaders };+ if (isAnthropicSubscriptionOAuth) {+ if (token) headers = claudeOAuthHeaders(headers, token);+ } else if (route.routing.authStrategy === 'api-key-header') {+ if (route.apiKey) {+ headers['x-api-key'] = route.apiKey;+ } else if (!headerValue(headers, 'x-api-key')) {+ headers['x-api-key'] = 'cindy-missing-custom-provider-api-key';}- return handler.handle({ parsedBody: body, res });+ } else if (isXdGatewayBridge && gatewayKey) {+ // 上游 wire 是 Anthropic Messages,复用 Claude Code 的网关鉴权形态;同时覆盖+ // Authorization,确保 Codex/ChatGPT bearer 永远不会离开本机。+ headers['x-api-key'] = gatewayKey;+ headers.authorization = `Bearer ${gatewayKey}`;+ } else if (route.routing.authStrategy === 'none') {+ delete headers.authorization;+ delete headers['x-api-key'];+ }+ const catalogContextWindow = getCatalogModelContextWindow(+ providerId,+ 'codex',+ wireModel,+ stripPrefix,+ );+ if (+ wireModel.endsWith('[1m]')+ || (+ isOfficialAnthropicUpstream(upstreamBase)+ && catalogContextWindow !== null+ && catalogContextWindow >= 1_000_000+ )+ ) {+ appendCommaSeparatedHeaderToken(+ headers,+ 'anthropic-beta',+ 'context-1m-2025-08-07',+ );+ }+ return headers;+ };+ const providerId = route.providerId;+ const providerName = getActiveCatalog().providers.find((p) => p.id === providerId)?.name ?? providerId;+ const stripPrefix = route.routing.modelIdRewrite?.stripPrefix;+ const supportsPromptCaching =+ isXdGatewayBridge || isOfficialAnthropicUpstream(upstreamBase);+ const onUpstreamError = route.providerSource === 'user'+ ? ({ status, body }: { status: number; body: string }): void => {+ reportProviderUpstreamError({ agent: 'codex', providerId, providerName, status, bodyText: body });+ }+ : undefined;+ const handler = createResponsesAnthropicHandler({+ upstreamBase,+ ...(route.routing.requestPath ? { requestPath: route.routing.requestPath } : {}),+ authMode: isAnthropicSubscriptionOAuth ? 'oauth' : 'api-key',+ buildHeaders: async () => buildProviderHeaders(route.oauthToken),+ ...(usesProviderOAuth+ ? {+ refreshHeaders: async ({+ requestHeaders,+ }: {+ status: 401 | 403;+ body: string;+ requestHeaders: Readonly<Record<string, string>>;+ }) => {+ const authorization = headerValue(requestHeaders, 'authorization');+ const staleToken = authorization?.replace(/^Bearer\s+/i, '');+ const token = await readProviderOAuthToken(providerId, 'codex', {+ forceRefresh: true,+ ...(staleToken ? { staleToken } : {}),+ });+ return token ? buildProviderHeaders(token) : null;+ },+ }+ : {}),+ rewriteModel: (model) => rewriteAnthropicBridgeModel(model, stripPrefix),+ promptCaching: supportsPromptCaching,+ automaticPromptCaching: isOfficialAnthropicUpstream(upstreamBase),+ strictTools: isOfficialAnthropicUpstream(upstreamBase),+ supportsThinking: isOfficialAnthropicUpstream(upstreamBase) || isXdGatewayBridge+ ? undefined+ : () => false,+ supportsAdaptiveThinking: isOfficialAnthropicUpstream(upstreamBase) || isXdGatewayBridge+ ? undefined+ : () => false,+ imageCodec: desktopAnthropicImageCodec,+ ...(onUpstreamError ? { onUpstreamError } : {}),+ }, {+ logger: log,+ fetchImpl: outboundFetch,+ });+ return {+ localHandler: ({ rawBody, parsedBody, ctx, res }) => {+ const body = prepareLocalBridgeBody({+ rawBody,+ parsedBody,+ instructions,+ requestModelOverride,+ bridge: 'anthropic',+ providerId,+ upstreamBase,+ });+ return handler.handle({ parsedBody: body, ctx, res });},};}+function createLocalBridgeDecision(+ route: Awaited<ReturnType<typeof resolveSessionRoute>>,+ instructions: string | undefined,+ wireModel: string,+ requestModelOverride: string | undefined,+ threadId: string,+): RoutingDecision | null {+ if (!route) return null;+ if (route.routing.wireProtocol === 'openai-chat') {+ const decision = createChatBridgeDecision(+ route,+ instructions,+ wireModel,+ requestModelOverride,+ );+ if (decision) {+ recordCodexThreadUpstreamForDiagnostics(threadId, route.routing.upstream);+ }+ return decision;+ }+ if (route.routing.wireProtocol === 'anthropic-messages') {+ const decision = createAnthropicBridgeDecision(+ route,+ instructions,+ wireModel,+ requestModelOverride,+ );+ if (decision) {+ recordCodexThreadUpstreamForDiagnostics(+ threadId,+ anthropicBridgeUpstreamBase(route),+ );+ }+ return decision;+ }+ return null;+}+function moveInstructionsIntoInput(body: Record<string, unknown>): Record<string, unknown> | null {const instructions = body.instructions;if (typeof instructions !== 'string' || instructions.length === 0) return null;@@ -1619,6 +1934,17 @@ export function createModelRoutingTransform(requestModel;const threadId = selectedThreadIdFromHeaders(ctx.headers);const sessionId = sessionIdFromHeaders(ctx.headers);+ const explicitProviderId = sessionId ? getSessionProvider(sessionId) : null;+ const selectedRouting = sessionId+ ? getSessionRoutingDescriptor(sessionId, 'codex', model || undefined)+ : null;+ const selectedUsesLocalBridge =+ ctx.method === 'POST'+ && Boolean(model)+ && (+ selectedRouting?.wireProtocol === 'openai-chat'+ || selectedRouting?.wireProtocol === 'anthropic-messages'+ );// ① 该会话显式选了供应商 → 据 catalog 统一路由。thread-id header → threadToSession 反解 xdt sessionId。// oauth-bearer 态全量适用;env-key 态默认全量走网关、per-session 无意义(与 decideCodexRoute 的@@ -1628,27 +1954,18 @@ export function createModelRoutingTransform(if (sessionId && (authInjection === 'oauth-bearer' ||isUserProviderSession(sessionId) ||- isHostInjectedAuthSession(sessionId, 'codex')+ isHostInjectedAuthSession(sessionId, 'codex') ||+ selectedUsesLocalBridge)) {- const selectedRouting = getSessionRoutingDescriptor(sessionId, 'codex', model || undefined);- if (selectedRouting?.wireProtocol === 'openai-chat' && ctx.method === 'POST' && model) {+ if (selectedUsesLocalBridge && model) {return resolveSessionRoute(sessionId, 'codex', model).then((localRoute) => {- const decision = createChatBridgeDecision(+ return createLocalBridgeDecision(localRoute,threadId ? registry.get(threadId) : undefined,model,model !== requestModel ? model : undefined,+ threadId,);- // chat bridge 走 localHandler,但它**确实出网** —— handler 自己用- // outboundFetch 打 route.routing.upstream(绕开转发层,却走同一个出站代理- // 解析器),所以照样会产生出站路径快照。这里必须补记 thread→上游映射:- // 漏了的话该供应商不可达时诊断查不到记录,静默退回通用猜测清单。- // 包装层(withCodexUpstreamRecording)看不到 localHandler 背后的上游,- // 只能由产生它的分支自己记。- if (decision && localRoute?.routing.upstream) {- recordCodexThreadUpstreamForDiagnostics(threadId, localRoute.routing.upstream);- }- return decision;});}// model 传给 scope 门(空串 = 控制面 GET,不受范围限制);声明了 modelPrefixes 的@@ -1666,11 +1983,31 @@ export function createModelRoutingTransform(}}- // ①.5 隐式来源(providerId/sessionProvider=null)但 model 自带唯一供应商命名空间。- // 典型:xai/grok-* 来自默认/调度/IM 路径时不写 sessionProvider,但仍必须走 api.x.ai- // + SuperGrok OAuth + modelIdRewrite,不能掉到 Codex 默认 ChatGPT/XD 分支。- const explicitProviderId = sessionId ? getSessionProvider(sessionId) : null;+ // ①.5 隐式来源(providerId/sessionProvider=null):+ // - Chat / Anthropic Messages wire 按模型选择器相同的默认来源进入本地 bridge;+ // - xai/grok-* 等唯一 provider-oauth 来源仍注入对应 OAuth 并透明转发。+ // 两者都必须先于 Codex 默认 ChatGPT/XD 分支,避免协议或凭证落错上游。if (!explicitProviderId && model) {+ if (sessionId && ctx.method === 'POST') {+ return resolveImplicitLocalBridgeRoute(model, 'codex').then((localRoute) => {+ if (localRoute) {+ return createLocalBridgeDecision(+ localRoute,+ threadId ? registry.get(threadId) : undefined,+ model,+ model !== requestModel ? model : undefined,+ threadId,+ );+ }+ const implicitProviderOAuth = resolveImplicitProviderOAuthRouteDecision(+ model,+ 'codex',+ gatewayKey,+ );+ if (implicitProviderOAuth) return implicitProviderOAuth;+ return decideCodexRoute({ model, authInjection, gatewayKey });+ });+ }const implicitProviderOAuth = resolveImplicitProviderOAuthRouteDecision(model, 'codex', gatewayKey);if (implicitProviderOAuth) return implicitProviderOAuth;}@@ -2008,17 +2345,18 @@ export function registerComposed(sessionId: string, threadId: string, text: strifunction bindThreadToSession(sessionId: string, threadId: string): void {const previousThreadId = sessionToThread.get(sessionId);if (previousThreadId && previousThreadId !== threadId) {- registry.delete(previousThreadId);- threadToSession.delete(previousThreadId);+ clearSessionThreads(sessionId);}const previousSessionId = threadToSession.get(threadId);if (previousSessionId && previousSessionId !== sessionId) {- sessionToThread.delete(previousSessionId);- reviewerModelBySession.delete(previousSessionId);+ clearSessionThreads(previousSessionId);}sessionToThread.set(sessionId, threadId);+ const threads = sessionToThreads.get(sessionId) ?? new Set<string>();+ threads.add(threadId);+ sessionToThreads.set(sessionId, threads);threadToSession.set(threadId, sessionId);}@@ -2039,19 +2377,71 @@ export function registerReviewerRouteContext(}/**- * 清理业务 session 对应的 thread prompt。由后续 Layer 4 接到 onClose 调用。+ * 让 Codex 子 Agent thread 继承父 thread 的业务 session、桥接路由和产品 prompt。+ * app-server 的 thread/started 通知在子 thread 首个请求前同步调用这里。*/-export function unregister(sessionId: string): void {- const threadId = sessionToThread.get(sessionId);- if (!threadId) return;+export function registerChildThread(parentThreadId: string, childThreadId: string): boolean {+ if (!parentThreadId || !childThreadId || parentThreadId === childThreadId) return false;++ const sessionId = threadToSession.get(parentThreadId);+ const text = registry.get(parentThreadId);+ if (!sessionId || text === undefined) {+ log.warn('cannot inherit codex child thread route from unknown parent', {+ parentThreadId,+ childThreadId,+ });+ return false;+ }++ const previousSessionId = threadToSession.get(childThreadId);+ if (previousSessionId && previousSessionId !== sessionId) {+ log.warn('refusing to overwrite codex child thread owned by another session', {+ parentThreadId,+ childThreadId,+ sessionId,+ previousSessionId,+ });+ return false;+ }+ const threads = sessionToThreads.get(sessionId) ?? new Set<string>();+ threads.add(childThreadId);+ sessionToThreads.set(sessionId, threads);+ threadToSession.set(childThreadId, sessionId);+ registry.set(childThreadId, text);+ log.debug('registered codex child thread route', {+ sessionId,+ parentThreadId,+ childThreadId,+ registrySize: registry.size,+ });+ return true;+}++function clearSessionThreads(sessionId: string): string[] {+ const threadIds = Array.from(sessionToThreads.get(sessionId) ?? []);+ sessionToThreads.delete(sessionId);sessionToThread.delete(sessionId);- threadToSession.delete(threadId);- registry.delete(threadId);reviewerModelBySession.delete(sessionId);+ for (const threadId of threadIds) {+ if (threadToSession.get(threadId) === sessionId) {+ threadToSession.delete(threadId);+ registry.delete(threadId);+ }+ }+ return threadIds;+}++/**+ * 清理业务 session 对应的 thread prompt。由后续 Layer 4 接到 onClose 调用。+ */+export function unregister(sessionId: string): void {+ const threadIds = clearSessionThreads(sessionId);+ if (threadIds.length === 0) return;+log.debug('unregistered codex prompt for session', {sessionId,- threadId,+ threadIds,registrySize: registry.size,});}@@ -2072,10 +2462,11 @@ export function isCodexProxyHandleReady(): boolean {export async function disposeCodexProxy(): Promise<void> {_disposeGeneration += 1;dumpSeq = 0;- for (const threadId of sessionToThread.values()) {+ for (const threadId of threadToSession.keys()) {registry.delete(threadId);}sessionToThread.clear();+ sessionToThreads.clear();threadToSession.clear();reviewerModelBySession.clear();diff --git a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts b/apps/desktop/src/main/maker-host/createDesktopProviderService.tsindex d798df6399..eb4ee907be 100644--- a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts+++ b/apps/desktop/src/main/maker-host/createDesktopProviderService.ts@@ -52,7 +52,12 @@ import {import { createProviderService, type ProviderService } from './provider-service.js';import { readModelDisableOverrides } from './model-disable-store.js';import { listCustomProviders } from './custom-provider-store.js';-import { setCustomProviderKeyReader, setOAuthTokenReader, setProviderOAuthTokenReader } from './provider-route.js';+import {+ setCustomProviderKeyReader,+ setOAuthTokenReader,+ setProviderOAuthTokenReader,+ setProviderViewsReader,+} from './provider-route.js';import { setDiagnosticsKeyReader, setDiagnosticsOAuthTokenReader } from './provider-diagnostics.js';import {configureGenericOAuth,@@ -64,6 +69,7 @@ import { genericOAuthSecretIo, addProviderSecretsClearedListener } from '../secrimport { readClaudeApiKey, desktopCodexAuthAdapter } from './auth-adapters.js';import { getProviderSecretStore, readCustomProviderKey } from '../secrets/providerSecretStore.js';import { hasClaudeAiOAuth, hasClaudeAiOAuthUnbound } from './claude-credentials-store.js';+import { getValidClaudeAiOAuth } from './claude-oauth-refresh.js';import {getGrokAccessToken,hasGrokOAuthLogin,@@ -217,7 +223,16 @@ export function ensureActiveCatalogLoaded(): Promise<Catalog> {// 接通自定义供应商密钥读取器(idempotent):provider-route 用 setter 注入避免触电,// 这里在路由发生前(splash 早于任何 turn)把真实 safeStorage 读取接进去。setCustomProviderKeyReader(readCustomProviderKey);- setProviderOAuthTokenReader((providerId) => (providerId === 'xai' ? getGrokAccessToken() : null));+ setProviderOAuthTokenReader((providerId, agent, options) => {+ if (providerId === 'xai') return getGrokAccessToken();+ // Codex's child process carries a ChatGPT/OpenAI bearer. The Anthropic+ // bridge must instead read the Claude.ai subscription credential owned by+ // the host (and allow the existing refresher to rotate it when needed).+ if (providerId === 'anthropic' && agent === 'codex') {+ return getValidClaudeAiOAuth(options).then((oauth) => oauth?.accessToken ?? null);+ }+ return null;+ });// 测试连接探测与路由同源读 key(同 setter 模式,见 provider-diagnostics.ts)。setDiagnosticsKeyReader(readCustomProviderKey);// 通用 OAuth Runner 接线(idempotent):safeStorage blob IO + 系统浏览器拉起;@@ -241,6 +256,13 @@ export function ensureActiveCatalogLoaded(): Promise<Catalog> {};setOAuthTokenReader(readOAuthToken);setDiagnosticsOAuthTokenReader(readOAuthToken);+ // 在启动期固定 service 实例,避免请求路由热路径重复进入 getter 里的 legacy+ // owner 绑定迁移;每次 listProviders 仍会实时读取凭证连接态。+ const providerService = getDesktopProviderService();+ setProviderViewsReader(() => providerService.listProviders({+ allowSideEffects: false,+ catalog: getActiveCatalog(),+ }));if (activeLoaded) return Promise.resolve(getActiveCatalog());if (!activeInflight) {const source = buildSource();diff --git a/apps/desktop/src/main/maker-host/custom-provider-store.ts b/apps/desktop/src/main/maker-host/custom-provider-store.tsindex 751c026212..7f23825392 100644--- a/apps/desktop/src/main/maker-host/custom-provider-store.ts+++ b/apps/desktop/src/main/maker-host/custom-provider-store.ts@@ -113,7 +113,7 @@ function validateRuntime(agent: string, rt: unknown): ValidationResult {if (r.wireProtocol !== undefined) {const allowed = agent === 'claude-code'? ['anthropic-messages']- : ['openai-responses', 'openai-chat'];+ : ['openai-responses', 'openai-chat', 'anthropic-messages'];if (typeof r.wireProtocol !== 'string' || !allowed.includes(r.wireProtocol)) {return invalid(`runtime '${agent}' wireProtocol invalid`);}diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex 0d615c3f36..e6c50e7e96 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -117,6 +117,7 @@ import {setCodexProxyGatewayKeyReader,registerComposed as registerCodexProxyComposed,registerReviewerRouteContext as registerCodexReviewerRouteContext,+ registerChildThread as registerCodexProxyChildThread,unregister as unregisterCodexProxyPrompt,} from './codex-proxy-host.js';import { createDesktopMcpProviders } from '../mcp-integrations/mcp-providers.js';@@ -1102,6 +1103,9 @@ export function getMaker(): Maker {registerCodexProxyComposed(sessionId, threadId, text),registerCodexReviewerRouteContext: ({ sessionId, threadId, model }) =>registerCodexReviewerRouteContext(sessionId, threadId, model),+ registerCodexChildThreadForParent: ({ parentThreadId, childThreadId }) => {+ registerCodexProxyChildThread(parentThreadId, childThreadId);+ },// host 自家、用户已通过 OAuth/账号授权过且完成权限 review 的 MCP server,// 按精确 server name 自动通过 Codex MCP elicitation,避免每次可信写操作都弹// PermissionPrompt。`cindy_` 只是 namespace,不构成信任边界;新 providerdiff --git a/apps/desktop/src/main/maker-host/provider-diagnostics.ts b/apps/desktop/src/main/maker-host/provider-diagnostics.tsindex 9c1076e0bf..7816c06877 100644--- a/apps/desktop/src/main/maker-host/provider-diagnostics.ts+++ b/apps/desktop/src/main/maker-host/provider-diagnostics.ts@@ -21,6 +21,7 @@ import {type AgentKind,type ProviderWireProtocol,} from '@cindy/model-providers';+import { joinAnthropicMessagesUrl } from '@cindy/responses-anthropic-bridge';import {classifyProviderError,@@ -81,33 +82,41 @@ export function setDiagnosticsKeyReader(reader: KeyReader): void {function withoutCredentialHeaders(headers: Record<string, string> | undefined,): Record<string, string> {- return Object.fromEntries(- Object.entries(headers ?? {}).filter(([name]) => {- const normalized = name.toLowerCase();- return normalized !== 'authorization' && normalized !== 'x-api-key';- }),- );+ const normalized: Record<string, string> = {};+ for (const [name, value] of Object.entries(headers ?? {})) {+ const lower = name.toLowerCase();+ if (lower !== 'authorization' && lower !== 'x-api-key') normalized[lower] = value;+ }+ return normalized;+}++function normalizedHeaders(headers: Record<string, string> | undefined): Record<string, string> {+ const normalized: Record<string, string> = {};+ for (const [name, value] of Object.entries(headers ?? {})) {+ normalized[name.toLowerCase()] = value;+ }+ return normalized;}/** 构造探测请求(纯函数,单测直断言)。header 组合与 provider-route 的 api-key-header 分支对齐。 */export function buildProbeRequest(spec: ProviderProbeSpec): { url: string; init: RequestInit } {const mustStripCredentialHeaders =!!spec.apiKey || spec.authMethod === 'none' || spec.authMethod === 'oauth';- const headers: Record<string, string> = {- 'content-type': 'application/json',- ...(mustStripCredentialHeaders- ? withoutCredentialHeaders(spec.headers)- : (spec.headers ?? {})),- };- if (spec.agent === 'claude-code') {- // Anthropic Messages wire。anthropic-version 为兼容端点普遍要求的必带头。+ const headers = mustStripCredentialHeaders+ ? withoutCredentialHeaders(spec.headers)+ : normalizedHeaders(spec.headers);+ headers['content-type'] = 'application/json';+ const anthropicMessages =+ spec.wireProtocol === 'anthropic-messages'+ || (spec.wireProtocol === undefined && spec.agent === 'claude-code');+ if (anthropicMessages) {headers['anthropic-version'] = headers['anthropic-version'] ?? '2023-06-01';if (spec.apiKey) {headers['x-api-key'] = spec.apiKey;headers['authorization'] = `Bearer ${spec.apiKey}`;}return {- url: appendProviderRequestPath(spec.baseUrl, spec.requestPath ?? '/v1/messages'),+ url: joinAnthropicMessagesUrl(spec.baseUrl, spec.requestPath ?? '/v1/messages'),init: {method: 'POST',headers,diff --git a/apps/desktop/src/main/maker-host/provider-model-fetch.ts b/apps/desktop/src/main/maker-host/provider-model-fetch.tsindex 60e401781d..f471abdf76 100644--- a/apps/desktop/src/main/maker-host/provider-model-fetch.ts+++ b/apps/desktop/src/main/maker-host/provider-model-fetch.ts@@ -11,7 +11,11 @@* - fetch 可注入(单测不联网)。*/-import { isLoopbackProviderUrl, type AgentKind } from '@cindy/model-providers';+import {+ isLoopbackProviderUrl,+ type AgentKind,+ type ProviderWireProtocol,+} from '@cindy/model-providers';import {classifyProviderError,@@ -28,6 +32,8 @@ const MAX_ERROR_BODY_BYTES = 16 * 1024;/** 一次「获取模型列表」的完整参数(表单值内存透传,不落盘)。 */export interface ProviderModelsFetchSpec {agent: AgentKind;+ /** 上游 wire protocol;用于区分 Codex 原生 OpenAI 与 Anthropic Messages 桥。 */+ wireProtocol?: ProviderWireProtocol;baseUrl: string;/** 表单态鉴权方式;main IPC 用它强制 none 只访问 loopback。 */authMethod?: 'apiKey' | 'oauth' | 'none';@@ -64,12 +70,20 @@ function sameOrigin(a: string, b: string): boolean {function withoutCredentialHeaders(headers: Record<string, string> | undefined,): Record<string, string> {- return Object.fromEntries(- Object.entries(headers ?? {}).filter(([name]) => {- const normalized = name.toLowerCase();- return normalized !== 'authorization' && normalized !== 'x-api-key';- }),- );+ const normalized: Record<string, string> = {};+ for (const [name, value] of Object.entries(headers ?? {})) {+ const lower = name.toLowerCase();+ if (lower !== 'authorization' && lower !== 'x-api-key') normalized[lower] = value;+ }+ return normalized;+}++function normalizedHeaders(headers: Record<string, string> | undefined): Record<string, string> {+ const normalized: Record<string, string> = {};+ for (const [name, value] of Object.entries(headers ?? {})) {+ normalized[name.toLowerCase()] = value;+ }+ return normalized;}/** 构造列模型请求(纯函数,单测直断言)。鉴权头组合与 buildProbeRequest 同口径。 */@@ -78,12 +92,17 @@ export function buildModelsFetchRequest(spec: ProviderModelsFetchSpec): { url: s!!spec.apiKey || spec.authMethod === 'none' || spec.authMethod === 'oauth';const headers: Record<string, string> = mustStripCredentialHeaders? withoutCredentialHeaders(spec.headers)- : { ...(spec.headers ?? {}) };- if (spec.agent === 'claude-code') {+ : normalizedHeaders(spec.headers);+ const anthropicMessages =+ spec.wireProtocol === 'anthropic-messages'+ || (spec.wireProtocol === undefined && spec.agent === 'claude-code');+ if (anthropicMessages) {// Anthropic wire 的所有端点(含 GET /v1/models)都要求 anthropic-version,缺失直接 400。headers['anthropic-version'] = headers['anthropic-version'] ?? '2023-06-01';if (spec.apiKey) {headers['x-api-key'] = spec.apiKey;+ // `buildLocalHandlerHeaders` 已把 agent 自带凭证替换为 Provider-owned key。+ // 同时发送标准 Anthropic x-api-key 与兼容网关常用的 Bearer,和真实会话保持一致。headers['authorization'] = `Bearer ${spec.apiKey}`;}} else if (spec.apiKey) {diff --git a/apps/desktop/src/main/maker-host/provider-route.ts b/apps/desktop/src/main/maker-host/provider-route.tsindex 82f820f4f1..a703327572 100644--- a/apps/desktop/src/main/maker-host/provider-route.ts+++ b/apps/desktop/src/main/maker-host/provider-route.ts@@ -19,10 +19,19 @@* token 覆盖 authorization,避免把子进程里其它供应商的 OAuth bearer 泄漏过去(如 Codex → xAI)。*/-import type { AgentKind, RoutingDescriptor } from '@cindy/model-providers';+import {+ effectiveSourceIdForModel,+ type AgentKind,+ type Provider,+ type ProviderView,+ type RoutingDescriptor,+} from '@cindy/model-providers';import type { RoutingDecision } from '@cindy/anthropic-compat-proxy';-import { getActiveCatalog } from './active-catalog.js';+import {+ getActiveCatalog,+ isXdCodexAnthropicBridgeModel,+} from './active-catalog.js';import { getAppCapabilities } from '../appCapabilities.js';import { getSessionProvider } from './session-provider-store.js';@@ -92,7 +101,16 @@ export function hasCustomProviderKey(providerId: string, agent: AgentKind): boolreturn Boolean(customProviderKeyReader(providerId, agent));}-type ProviderOAuthTokenReader = (providerId: string, agent: AgentKind) => string | null | Promise<string | null>;+export interface ProviderOAuthTokenReadOptions {+ forceRefresh?: boolean;+ staleToken?: string;+}++type ProviderOAuthTokenReader = (+ providerId: string,+ agent: AgentKind,+ options?: ProviderOAuthTokenReadOptions,+) => string | null | Promise<string | null>;let providerOAuthTokenReader: ProviderOAuthTokenReader = () => null;/** host 启动期接通内置 OAuth 供应商 token 读取(如 xAI/SuperGrok)。 */@@ -100,6 +118,26 @@ export function setProviderOAuthTokenReader(reader: ProviderOAuthTokenReader): vproviderOAuthTokenReader = reader;}+type ProviderViewsReader = () => Promise<ProviderView[]>;+let providerViewsReader: ProviderViewsReader = async () => [];++/**+ * 注入 Main 侧实时 ProviderView 读取器。隐式来源必须与模型选择器共用连接态,+ * 不能只看 active catalog:目录表示“可提供”,凭证状态才表示“当前可路由”。+ */+export function setProviderViewsReader(reader: ProviderViewsReader): void {+ providerViewsReader = reader;+}++/** Read a provider OAuth token for a local bridge retry without exposing the reader itself. */+export function readProviderOAuthToken(+ providerId: string,+ agent: AgentKind,+ options?: ProviderOAuthTokenReadOptions,+): Promise<string | null> {+ return Promise.resolve(providerOAuthTokenReader(providerId, agent, options)).catch(() => null);+}+const MISSING_PROVIDER_OAUTH_TOKEN = 'xdt-missing-provider-oauth-token';/**@@ -363,6 +401,34 @@ function routingServesWireModel(routing: RoutingDescriptor, wireModel: string |return routing.modelPrefixes.some((prefix) => wireModel.startsWith(prefix));}+/**+ * 解析 provider × agent × model 的最终 wire。+ *+ * 绝大多数路由直接使用 provider 级描述符;XD 是一个 provider 内同时存在两种 Codex wire+ * 的特例:服务端原生声明 codex 的模型走 Responses,只声明 claude-code 的模型由客户端+ * 投影给 Codex,并复用同一 provider 的 Claude Messages 路由进入本地 bridge。+ */+function providerRoutingForModel(+ provider: Provider,+ agent: AgentKind,+ wireModel: string | undefined,+): RoutingDescriptor | null {+ if (+ provider.id === 'xd'+ && agent === 'codex'+ && wireModel+ && isXdCodexAnthropicBridgeModel(wireModel)+ ) {+ const claudeRouting = provider.routing['claude-code'];+ if (!claudeRouting) return null;+ return {+ ...claudeRouting,+ wireProtocol: 'anthropic-messages',+ };+ }+ return provider.routing[agent] ?? null;+}+/*** 某 provider 对某 agent 的路由是否服务该 wire model(modelPrefixes 语义;未声明 = true,* provider 无该 agent 路由 = false)。@@ -377,7 +443,8 @@ export function providerRoutingServesWireModel(wireModel: string | undefined,): boolean {if (providerId === 'xd' && !getAppCapabilities().canUseCindyGateway) return false;- const routing = getActiveCatalog().providers.find((p) => p.id === providerId)?.routing[agent];+ const provider = getActiveCatalog().providers.find((p) => p.id === providerId);+ const routing = provider ? providerRoutingForModel(provider, agent, wireModel) : null;if (!routing) return false;return routingServesWireModel(routing, wireModel);}@@ -406,7 +473,8 @@ export function getSessionRoutingDescriptor(const providerId = getSessionProvider(sessionId);if (!providerId) return null;if (isProviderRouteMutationInProgress(providerId)) return null;- const routing = getActiveCatalog().providers.find((provider) => provider.id === providerId)?.routing[agent];+ const provider = getActiveCatalog().providers.find((candidate) => candidate.id === providerId);+ const routing = provider ? providerRoutingForModel(provider, agent, wireModel) : null;if (!routing || !routingServesWireModel(routing, wireModel)) return null;return routing;}@@ -419,20 +487,14 @@ export interface ResolvedSessionRoute {oauthToken: string | null;}-/**- * 解析会话选定来源的完整运行时素材,供需要本地协议 handler 的路径使用。- * 普通透明转发仍走 resolveSessionRouteDecision,避免改变历史返回形态。- */-export async function resolveSessionRoute(- sessionId: string,+async function resolveProviderRouteById(+ providerId: string,agent: AgentKind,wireModel?: string,): Promise<ResolvedSessionRoute | null> {- const providerId = getSessionProvider(sessionId);- if (!providerId) return null;if (isProviderRouteMutationInProgress(providerId)) return null;const provider = getActiveCatalog().providers.find((candidate) => candidate.id === providerId);- const routing = provider?.routing[agent];+ const routing = provider ? providerRoutingForModel(provider, agent, wireModel) : null;if (!provider || !routing || !routingServesWireModel(routing, wireModel)) return null;const { apiKey, oauthToken } = await readProviderRouteCredentials(provider, routing, agent);return {@@ -444,6 +506,20 @@ export async function resolveSessionRoute(};}+/**+ * 解析会话选定来源的完整运行时素材,供需要本地协议 handler 的路径使用。+ * 普通透明转发仍走 resolveSessionRouteDecision,避免改变历史返回形态。+ */+export async function resolveSessionRoute(+ sessionId: string,+ agent: AgentKind,+ wireModel?: string,+): Promise<ResolvedSessionRoute | null> {+ const providerId = getSessionProvider(sessionId);+ if (!providerId) return null;+ return resolveProviderRouteById(providerId, agent, wireModel);+}+/** Build outbound headers for an already resolved local protocol handler. */export function buildLocalHandlerHeaders(route: ResolvedSessionRoute, agent: AgentKind): {headers: Record<string, string>;@@ -562,7 +638,7 @@ export function resolveSessionRouteDecision(}if (providerId === 'xd' && !getAppCapabilities().canUseCindyGateway) return null;const provider = getActiveCatalog().providers.find((p) => p.id === providerId);- const routing = provider?.routing[agent];+ const routing = provider ? providerRoutingForModel(provider, agent, wireModel) : null;if (!routing) return null;if (routing.disabled) return disabledProviderRouteDecision(providerId);if (!routingServesWireModel(routing, wireModel)) return null;@@ -597,6 +673,22 @@ function providersForModel(modelId: string, agent: AgentKind) {);}+async function connectedDefaultProviderForModel(modelId: string, agent: AgentKind) {+ const providers = await providerViewsReader();+ const defaultId = effectiveSourceIdForModel(providers, null, modelId, agent);+ return providers.find((provider) => provider.id === defaultId) ?? null;+}++function hasImplicitLocalBridgeCandidate(modelId: string, agent: AgentKind): boolean {+ return providersForModel(modelId, agent).some((provider) => {+ const routing = providerRoutingForModel(provider, agent, modelId);+ return (+ routing?.wireProtocol === 'openai-chat'+ || routing?.wireProtocol === 'anthropic-messages'+ );+ });+}+function uniqueProviderForModel(modelId: string, agent: AgentKind) {const providers = providersForModel(modelId, agent);return providers.length === 1 ? providers[0] : null;@@ -610,6 +702,37 @@ export function inferProviderIdForModel(modelId: string, agent: AgentKind): strireturn uniqueProviderForModel(modelId, agent)?.id ?? null;}+/**+ * 隐式本地 bridge 来源:会话未显式选 Provider 时,按模型选择器相同的原生默认来源+ * 解析 Provider;只有最终来源明确声明 Chat / Anthropic Messages wire 才接管。+ *+ * 这里不能使用 uniqueProviderForModel:Claude 模型通常同时由 Anthropic 与 XD 提供,+ * 但 Codex 的默认来源仍应稳定选择 XD;XD 不可用时才落到候选首项(如 Anthropic)。+ */+export function resolveImplicitLocalBridgeRoute(+ modelId: string,+ agent: AgentKind,+): Promise<ResolvedSessionRoute | null> {+ const catalogModelId = modelId.replace(/\[1m\]$/, '');+ // Most Codex requests are native OpenAI Responses and do not need provider+ // connection resolution. Keep credential-store reads off that hot path; only+ // bridge-capable catalog models need the live connected-provider snapshot.+ if (!hasImplicitLocalBridgeCandidate(catalogModelId, agent)) {+ return Promise.resolve(null);+ }+ return connectedDefaultProviderForModel(catalogModelId, agent).then((provider) => {+ if (!provider) return null;+ const routing = providerRoutingForModel(provider, agent, modelId);+ if (+ routing?.wireProtocol !== 'openai-chat'+ && routing?.wireProtocol !== 'anthropic-messages'+ ) {+ return null;+ }+ return resolveProviderRouteById(provider.id, agent, modelId);+ });+}+/*** 隐式 provider OAuth 路由:providerId/sessionProvider 为空时,按 model 唯一来源推断出* provider-oauth-header 路由。只接管这类必须由 proxy 注入供应商 OAuth 的路径,避免改变@@ -649,6 +772,11 @@ export function resolveProviderOAuthControlRouteDecision(!isProviderRouteMutationInProgress(provider.id)&& provider.agents.includes(agent)&& routing?.authStrategy === 'provider-oauth-header'+ // Session-less Codex control requests use the OpenAI control-plane+ // protocol. Local inference bridges (Chat / Anthropic Messages) obtain+ // their model lists through Cindy's provider discovery and must not+ // compete for transparent GET /models routing.+ && (routing.wireProtocol === undefined || routing.wireProtocol === 'openai-responses'));});if (providers.length !== 1) return null;diff --git a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.tsindex d795f0db3d..ef0a8bf4b7 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts@@ -1521,6 +1521,30 @@ describe('provider:models-fetch handler', () => {});});+ it('preserves the Codex Anthropic Messages wire protocol for API-key discovery', async () => {+ const harness = new IpcHarness();+ const fetchModels = vi.fn(async () => ({ ok: true as const, models: [] }));+ registerProviderHandlers(harness, makeDeps({ fetchModels }));++ await harness.invoke(MAKER_INVOKE.PROVIDER_MODELS_FETCH, {+ agent: 'codex',+ wireProtocol: 'anthropic-messages',+ baseUrl: 'https://api.anthropic.com',+ authMethod: 'apiKey',+ apiKey: 'sk-test',+ });++ expect(fetchModels).toHaveBeenCalledWith({+ agent: 'codex',+ wireProtocol: 'anthropic-messages',+ baseUrl: 'https://api.anthropic.com',+ authMethod: 'apiKey',+ modelsUrl: null,+ apiKey: 'sk-test',+ headers: undefined,+ });+ });+it('rejects remote no-auth model discovery URLs before invoking fetch', async () => {const harness = new IpcHarness();const deps = makeDeps();diff --git a/apps/desktop/src/main/maker-ipc/providerHandlers.ts b/apps/desktop/src/main/maker-ipc/providerHandlers.tsindex 5eeb88c27b..2d6bf4384b 100644--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts@@ -316,7 +316,7 @@ function parseTestInput(input: unknown): ProviderTestInput | null {if (spec.wireProtocol !== undefined) {const allowed = spec.agent === 'claude-code'? ['anthropic-messages']- : ['openai-responses', 'openai-chat'];+ : ['openai-responses', 'openai-chat', 'anthropic-messages'];if (typeof spec.wireProtocol !== 'string' || !allowed.includes(spec.wireProtocol)) return null;}if (spec.requestPath !== undefined && !isProviderRequestPath(spec.requestPath)) return null;@@ -371,6 +371,12 @@ function parseModelsFetchInput(input: unknown): ProviderModelsFetchSpec | null {)) return null;if (spec.apiKey !== undefined && spec.apiKey !== null && typeof spec.apiKey !== 'string') return null;+ if (spec.wireProtocol !== undefined) {+ const allowed = spec.agent === 'claude-code'+ ? ['anthropic-messages']+ : ['openai-responses', 'openai-chat', 'anthropic-messages'];+ if (typeof spec.wireProtocol !== 'string' || !allowed.includes(spec.wireProtocol)) return null;+ }if (spec.headers !== undefined) {if (!spec.headers || typeof spec.headers !== 'object' || Array.isArray(spec.headers)) return null;if (Object.values(spec.headers as Record<string, unknown>).some((v) => typeof v !== 'string')) return null;@@ -382,6 +388,9 @@ function parseModelsFetchInput(input: unknown): ProviderModelsFetchSpec | null {modelsUrl: (spec.modelsUrl as string | null | undefined) ?? null,apiKey: (spec.apiKey as string | null | undefined) ?? null,headers: spec.headers as Record<string, string> | undefined,+ ...(typeof spec.wireProtocol === 'string'+ ? { wireProtocol: spec.wireProtocol as ProviderModelsFetchSpec['wireProtocol'] }+ : {}),};}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex eef097e285..cac5913801 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -3958,6 +3958,7 @@ contextBridge.exposeInMainWorld('electronAPI', {agent: 'claude-code' | 'codex';baseUrl: string;authMethod: 'apiKey' | 'oauth' | 'none';+ wireProtocol?: import('@cindy/model-providers').ProviderWireProtocol;modelsUrl?: string | null;apiKey?: string | null;headers?: Record<string, string>;diff --git a/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx b/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsxindex 6426f16c0c..f4bc817ea7 100644--- a/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx+++ b/apps/desktop/src/renderer/__tests__/addProviderWizardPresetEntry.test.tsx@@ -178,7 +178,7 @@ describe('AddProviderWizard — preset 直达', () => {expect(screen.getByText('settings.providers.wizard.nameLabel')).not.toBeNull(),);expect(screen.getByDisplayValue('Anthropic API')).not.toBeNull();- expect(screen.getByText(/api\.anthropic\.com/)).not.toBeNull();+ expect(screen.getAllByText(/api\.anthropic\.com/)).toHaveLength(2);});it('官方 API 预设:列模型失败 → 第三步仍有推荐模型预勾,可完成(Greptile P1 回归)', async () => {@@ -244,6 +244,18 @@ describe('AddProviderWizard — preset 直达', () => {expect.objectContaining({ id: 'claude-haiku-4-5', contextWindow: 200_000 }),]),);+ const codex = config.runtimes.codex;+ expect(codex?.wireProtocol).toBe('anthropic-messages');+ expect(codex?.baseUrl).toBe('https://api.anthropic.com');+ expect(codex?.models).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ id: 'claude-opus-5', contextWindow: 1_000_000 }),+ expect.objectContaining({ id: 'claude-sonnet-5', contextWindow: 1_000_000 }),+ expect.objectContaining({ id: 'claude-haiku-4-5', contextWindow: 200_000 }),+ ]),+ );+ const keys = vi.mocked(createCustomProvider).mock.calls[0][1];+ expect(keys).toMatchObject({ 'claude-code': 'sk-test', codex: 'sk-test' });});it('editable preset saves the edited base URL and exact request path', async () => {diff --git a/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts b/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.tsindex 1269d0a2d2..80ec6c5cdb 100644--- a/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts+++ b/apps/desktop/src/renderer/__tests__/modelSelectorTriggerVariant.test.ts@@ -28,6 +28,7 @@ vi.mock('react-i18next', async (importOriginal) => ({const translations: Record<string, string> = {'effortLevels.xhigh': '超高','settings.providers.anthropic.title': 'Anthropic',+ 'settings.providers.xd.title': 'Cindy AI','newChat.modelSelector.trigger.placeholder': '选择模型','newChat.modelSelector.trigger.agent.claudeCode': 'Claude Code','newChat.modelSelector.trigger.agent.codex': 'Codex',@@ -40,6 +41,9 @@ vi.mock('react-i18next', async (importOriginal) => ({if (key === 'newChat.modelSelector.meta.context') {return `${options?.value} context`;}+ if (key === 'newChat.modelSelector.meta.codexCompatibilityMode') {+ return 'Codex compatibility mode';+ }if (key === 'newChat.modelSelector.source.viaSource') {return `Source: ${options?.source}`;}@@ -282,6 +286,7 @@ interface VisibleModelFixture {defaultEffort: string | null;effortDisplayNames?: Record<string, string>;supportsFastMode?: boolean;+ codexCompatibilityWireProtocol?: 'openai-chat' | 'anthropic-messages';}const visibleModelsRef = vi.hoisted(() => ({@@ -1179,6 +1184,116 @@ describe('ModelSelector trigger variants', () => {expect(within(information).queryByRole('option')).toBeNull();});+ it.each([+ {+ label: 'OpenAI Chat → Responses',+ providerProtocol: 'openai-chat',+ modelProtocol: undefined,+ visible: true,+ },+ {+ label: 'Anthropic Messages → Responses',+ providerProtocol: 'anthropic-messages',+ modelProtocol: undefined,+ visible: true,+ },+ {+ label: 'Cindy AI 模型级 Anthropic bridge',+ providerProtocol: 'openai-responses',+ modelProtocol: 'anthropic-messages',+ visible: true,+ },+ {+ label: '原生 Responses',+ providerProtocol: 'openai-responses',+ modelProtocol: undefined,+ visible: false,+ },+ ] as const)(+ '$label 的模型详情兼容模式标记 visible=$visible',+ ({ providerProtocol, modelProtocol, visible }) => {+ const currentModel: VisibleModelFixture = {+ id: 'bridge-fixture-model',+ displayName: 'Bridge Fixture',+ contextWindow: 1_000_000,+ efforts: ['high'],+ defaultEffort: 'high',+ ...(modelProtocol ? { codexCompatibilityWireProtocol: modelProtocol } : {}),+ };+ const originalCapabilities = agentCapabilitiesRef.capabilities;+ visibleModelsRef.models = [currentModel];+ agentCapabilitiesRef.capabilities = {+ availableModels: [currentModel],+ effortLevels: [{ id: 'high', displayName: 'High' }],+ hasFastMode: false,+ };+ providersRef.providers = [+ {+ id: modelProtocol ? 'xd' : 'fixture',+ name: modelProtocol ? 'Cindy AI' : 'Fixture',+ source: modelProtocol ? 'builtin' : 'user',+ connected: true,+ agents: ['codex'],+ auth: { method: 'none' },+ routing: {+ codex: {+ upstream: 'https://example.test',+ authStrategy: 'none',+ wireProtocol: providerProtocol,+ },+ },+ models: {+ codex: [+ {+ ...currentModel,+ name: currentModel.displayName,+ },+ ],+ },+ },+ ];++ try {+ render(+ React.createElement(ModelSelectorContent, {+ modelId: currentModel.id,+ effort: 'high',+ onModelChange: vi.fn(),+ onEffortChange: vi.fn(),+ vendorKey: 'codex',+ currentProviderId: modelProtocol ? 'xd' : 'fixture',+ onProviderChange: vi.fn(),+ }),+ );++ fireEvent.pointerEnter(screen.getByRole('option', { name: /Bridge Fixture/ }));+ const details = screen.getByRole('group', { name: /Bridge Fixture/ });+ const compatibilityLabel = within(details).queryByText('Codex compatibility mode');+ if (visible) {+ expect(compatibilityLabel).toBeTruthy();+ const detailText = details.textContent ?? '';+ const sourceText = modelProtocol ? 'Source: Cindy AI' : 'Source: Fixture';+ expect(detailText.indexOf(sourceText)).toBeLessThan(detailText.indexOf('1M context'));+ expect(detailText.indexOf('1M context')).toBeLessThan(+ detailText.indexOf('Codex compatibility mode'),+ );+ expect(compatibilityLabel).not.toBe(+ within(details).getByText(sourceText).parentElement,+ );+ expect(compatibilityLabel).not.toBe(+ within(details).getByText('1M context').parentElement,+ );+ } else {+ expect(compatibilityLabel).toBeNull();+ }+ } finally {+ visibleModelsRef.models = null;+ agentCapabilitiesRef.capabilities = originalCapabilities;+ providersRef.providers = providersRef.DEFAULT_PROVIDERS;+ }+ },+ );+it('filters provider-ignored models from flat model-only selectors', () => {modelVisibilityRef.isEnabled = (_agent, _providerId, model) => model.id !== 'claude-sonnet-4-6';try {diff --git a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsxindex a4868aedf8..17778bca1d 100644--- a/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx@@ -57,6 +57,7 @@ import {modelSupportsFastMode,providerOffersModel,resolveModelIconKind,+ resolveCodexCompatibilityWireProtocol,sourcesForModel,visibleModelUnion,type ProviderView,@@ -246,6 +247,8 @@ interface RowModel {defaultEffort: Effort | null;effortDisplayNames?: Partial<Record<string, string>>;supportsFastMode?: boolean;+ /** 模型级 Codex bridge 协议;仅同一 Provider 内混合原生/桥接模型时存在。 */+ codexCompatibilityWireProtocol?: 'openai-chat' | 'anthropic-messages';/** 展示图标 id(AI Gateway / 目录设定,SectionModel.icon);flat 列表的 ModelDescriptor 无此字段。 */icon?: string;}@@ -1122,6 +1125,9 @@ function ModelSelectorContentView({const editingPricePresentation = editingModel? pricePresentationOf(editingProvider?.id ?? editingProviderId, editingModel.id): null;+ const editingCodexCompatibilityProtocol = editingProvider+ ? resolveCodexCompatibilityWireProtocol(editingProvider, currentAgentKind, editingModel)+ : null;const editingDiscount =editingPricePresentation?.kind === 'priced' ? editingPricePresentation.discount : undefined;const editingPromotionLabel =@@ -1286,6 +1292,11 @@ function ModelSelectorContentView({<span>{t('newChat.modelSelector.meta.fastBadge')}</span>)}</div>+ {editingCodexCompatibilityProtocol && (+ <div className="mt-0.5 text-11 font-normal leading-[1.4] text-[var(--text-tertiary)]">+ {t('newChat.modelSelector.meta.codexCompatibilityMode')}+ </div>+ )}</div></div>) : null;diff --git a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsxindex 2d5bed2657..e8c959a59d 100644--- a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx+++ b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx@@ -108,9 +108,16 @@ function isValidEditablePresetBaseUrl(value: string): boolean {* (缺省由 baseUrl 推导 …/v1/models,见 provider-model-fetch);同时内置少量* 推荐模型兜底——拉取因网络/限流失败时降级为「仅推荐模型」仍可完成创建,* 不把用户堵死(与目录预设同语义;Greptile P1 反馈 2026-07-24)。- * cc runtime 需 Anthropic 兼容端点、codex 需 OpenAI 兼容端点,故 openai/xai- * 仅声明 codex(两家无 Anthropic 兼容端点),表单会自动展示「仅支持 X」说明行。+ * 每个 runtime 都独立声明 wire protocol:Anthropic API 同时提供 Claude Code 的+ * Messages 与 Codex 桥接所需的 Messages 端点;openai/xai 仅声明 Codex(两家无+ * Anthropic 兼容端点),表单会自动展示「仅支持 X」说明行。*/+const ANTHROPIC_API_MODELS = [+ { id: 'claude-opus-5', name: 'Claude Opus 5', contextWindow: 1_000_000 },+ { id: 'claude-sonnet-5', name: 'Claude Sonnet 5', contextWindow: 1_000_000 },+ { id: 'claude-haiku-4-5', name: 'Claude Haiku 4.5', contextWindow: 200_000 },+];+const OFFICIAL_API_PRESETS: Record<string, ProviderPreset> = {anthropic: {id: 'anthropic-api',@@ -122,11 +129,15 @@ const OFFICIAL_API_PRESETS: Record<string, ProviderPreset> = {// contextWindow 必须与目录(providers.json)一致:保存时它是窗口的唯一来源// (拉取的模型列表不带窗口),缺省会落 200k 默认 → toSdkModelString 剥掉// 1M 模型的 [1m] 路由,用户拿到 1/5 窗口。- models: [- { id: 'claude-opus-5', name: 'Claude Opus 5', contextWindow: 1_000_000 },- { id: 'claude-sonnet-5', name: 'Claude Sonnet 5', contextWindow: 1_000_000 },- { id: 'claude-haiku-4-5', name: 'Claude Haiku 4.5', contextWindow: 200_000 },- ],+ models: ANTHROPIC_API_MODELS,+ },+ // Codex 通过 Responses → Anthropic Messages 本地桥接访问同一官方 API。+ // 这不是 Claude.ai OAuth 路由:API key 由该 runtime 独立存储,出站只使用+ // x-api-key,Codex 自带的 OpenAI Authorization 永不透传到 Anthropic。+ codex: {+ wireProtocol: 'anthropic-messages',+ baseUrl: 'https://api.anthropic.com',+ models: ANTHROPIC_API_MODELS,},},},@@ -598,6 +609,7 @@ export function AddProviderWizard({authMethod: preset.authMethod ?? 'apiKey',modelsUrl: rt.modelsUrl ?? null,apiKey: apiKey.trim() || null,+ ...(rt.wireProtocol ? { wireProtocol: rt.wireProtocol } : {}),...(rt.headers ? { headers: rt.headers } : {}),});return { agent, ok: !!(r.ok && r.models), models: r.models ?? [] };diff --git a/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx b/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsxindex b39206d388..d34786b37a 100644--- a/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx+++ b/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx@@ -47,6 +47,11 @@ import {stripCredentialHeaders,type CustomProviderAuthMode,} from '@/lib/providerModelFetch';+import {+ CUSTOM_PROVIDER_CODEX_WIRE_PROTOCOLS,+ customProviderCodexWireProtocolOption,+ type CustomProviderCodexWireProtocol,+} from '@/lib/customProviderWireProtocols';import { isProviderRequestPath, sortPresetsForLocale } from '@cindy/model-providers';import type {@@ -464,7 +469,7 @@ export function CustomProviderDialog({/** 切换协议时保留用户已填写的 endpoint,仅使旧测试结果失效。 */const changeCodexWireProtocol = useCallback(- (wireProtocol: 'openai-responses' | 'openai-chat') => {+ (wireProtocol: CustomProviderCodexWireProtocol) => {setRtSynced((prev) => ({...prev,codex: { ...prev.codex, wireProtocol },@@ -568,6 +573,7 @@ export function CustomProviderDialog({agent,baseUrl,authMethod: authMode,+ ...(rf.wireProtocol ? { wireProtocol: rf.wireProtocol } : {}),modelsUrl: rf.modelsUrl.trim() || null,apiKey: authMode === 'apiKey' ? rf.apiKey.trim() || null : null,...(Object.keys(requestHeaders).length > 0 ? { headers: requestHeaders } : {}),@@ -1064,34 +1070,30 @@ export function CustomProviderDialog({{activeTab === 'codex' && (<div className="flex flex-col gap-[7px]"><FieldLabel>{t('settings.providers.custom.fields.wireProtocol')}</FieldLabel>- <div className="flex gap-1.5">- {(['openai-responses', 'openai-chat'] as const).map((protocol) => (+ <div className="flex flex-wrap gap-1.5">+ {CUSTOM_PROVIDER_CODEX_WIRE_PROTOCOLS.map((option) => (<button- key={protocol}+ key={option.value}type="button"- onClick={() => changeCodexWireProtocol(protocol)}+ onClick={() => changeCodexWireProtocol(option.value)}className={cn('rounded-full border px-3 py-1.5 text-12 font-medium transition-colors',- f.wireProtocol === protocol+ f.wireProtocol === option.value? 'border-[var(--settings-input-border-focus)] text-[var(--settings-section-title)]': 'border-[var(--settings-input-border)] text-[var(--text-secondary)] hover:bg-[var(--surface-hover)]',)}style={- f.wireProtocol === protocol+ f.wireProtocol === option.value? { backgroundColor: 'var(--surface-elevated)' }: undefined}>- {t(- `settings.providers.custom.wireProtocol.${protocol === 'openai-responses' ? 'responses' : 'chat'}`,- )}+ {t(option.labelKey)}</button>))}</div><span className="text-12 leading-snug text-[var(--text-tertiary)]">- {t(- `settings.providers.custom.wireProtocol.${f.wireProtocol === 'openai-chat' ? 'chatHelp' : 'responsesHelp'}`,- )}+ {t(customProviderCodexWireProtocolOption(f.wireProtocol).helpKey)}</span></div>)}@@ -1115,9 +1117,7 @@ export function CustomProviderDialog({placeholder={activeTab === 'claude-code'? '/v1/messages'- : f.wireProtocol === 'openai-chat'- ? '/chat/completions'- : '/responses'+ : customProviderCodexWireProtocolOption(f.wireProtocol).defaultRequestPath}/><span className="text-12 leading-snug text-[var(--text-tertiary)]">diff --git a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsxindex f401caad6c..771e933e28 100644--- a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx+++ b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx@@ -1617,6 +1617,7 @@ export function ProvidersSection() {agent,baseUrl: rt.baseUrl,authMethod,+ ...(rt.wireProtocol ? { wireProtocol: rt.wireProtocol } : {}),modelsUrl: rt.modelsUrl ?? null,apiKey,...(rt.headers ? { headers: rt.headers } : {}),diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex a7f2f8009b..e6dfb5f241 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -1296,14 +1296,16 @@"wireProtocol": {"responses": "OpenAI Responses (native)","chat": "Chat Completions (Cindy bridge)",+ "anthropic": "Anthropic Messages (Cindy bridge)","responsesHelp": "The provider supports the Responses API natively, so Cindy forwards its event stream unchanged.",- "chatHelp": "For providers that only expose Chat Completions. Cindy converts streaming text and function tool calls; some advanced Responses features are unavailable."+ "chatHelp": "For providers that only expose Chat Completions. Cindy converts streaming text and function tool calls; some advanced Responses features are unavailable.",+ "anthropicHelp": "For providers that expose the Anthropic Messages API. Cindy converts Responses messages, images, tools, reasoning, and streaming events."},"protocol": {"claude": "Claude Code","claudeDesc": "Claude Code follows the Anthropic protocol (auth via x-api-key). Enter this source's baseURL, key, and models for Claude Code; leave blank to skip Claude Code for this source.","codex": "Codex",- "codexDesc": "Codex speaks the OpenAI Responses protocol. Choose a native Responses upstream or let Cindy bridge a provider that only supports Chat Completions. Enter this source's base URL, key, and models for Codex; leave blank to skip Codex for this source."+ "codexDesc": "Codex speaks the OpenAI Responses protocol. Choose native Responses, or let Cindy bridge Chat Completions or Anthropic Messages. Enter this source's base URL, key, and models for Codex; leave blank to skip Codex for this source."},"errors": {"nameRequired": "Display name is required",@@ -4466,6 +4468,7 @@},"meta": {"context": "{{value}} context",+ "codexCompatibilityMode": "Codex compatibility mode","price": "{{input}}/{{output}} per 1M","fastBadge": "Fast","budgetDiscount": "Special discount"diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 430d25fb95..27919018b3 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -1296,14 +1296,16 @@"wireProtocol": {"responses": "OpenAI Responses(ネイティブ)","chat": "Chat Completions(Cindy ブリッジ)",+ "anthropic": "Anthropic Messages(Cindy ブリッジ)","responsesHelp": "プロバイダーが Responses API をネイティブ対応しているため、Cindy はイベントストリームをそのまま転送します。",- "chatHelp": "Chat Completions のみを提供するプロバイダー向けです。Cindy がストリーミングテキストと関数ツール呼び出しを変換します。一部の高度な Responses 機能は利用できません。"+ "chatHelp": "Chat Completions のみを提供するプロバイダー向けです。Cindy がストリーミングテキストと関数ツール呼び出しを変換します。一部の高度な Responses 機能は利用できません。",+ "anthropicHelp": "Anthropic Messages API を提供するプロバイダー向けです。Cindy が Responses のメッセージ、画像、ツール、推論内容、ストリーミングイベントを変換します。"},"protocol": {"claude": "Claude Code","claudeDesc": "Claude Code は Anthropic プロトコルに従います(x-api-key で認証)。この提供元の Claude Code 用 baseURL・キー・モデルを入力します。空欄にするとこの提供元は Claude Code を提供しません。","codex": "Codex",- "codexDesc": "Codex は OpenAI Responses プロトコルを使用します。Responses ネイティブの上流、または Chat Completions のみを提供するプロバイダーを Cindy でブリッジする方式を選べます。このプロバイダーの Codex 用ベース URL・キー・モデルを入力します。空欄にすると Codex では利用しません。"+ "codexDesc": "Codex は OpenAI Responses プロトコルを使用します。Responses ネイティブ、または Chat Completions / Anthropic Messages を Cindy でブリッジする方式を選べます。このプロバイダーの Codex 用ベース URL・キー・モデルを入力します。空欄にすると Codex では利用しません。"},"errors": {"nameRequired": "表示名を入力してください",@@ -4465,6 +4467,7 @@},"meta": {"context": "コンテキスト {{value}}",+ "codexCompatibilityMode": "Codex 互換モード","price": "{{input}}/{{output}} / 100万","fastBadge": "高速","budgetDiscount": "特別割引"diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex ae9c4812bc..c365ae8b45 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -1296,14 +1296,16 @@"wireProtocol": {"responses": "OpenAI Responses(네이티브)","chat": "Chat Completions(Cindy 브리지)",+ "anthropic": "Anthropic Messages(Cindy 브리지)","responsesHelp": "제공자가 Responses API를 네이티브로 지원하므로 Cindy가 이벤트 스트림을 그대로 전달합니다.",- "chatHelp": "Chat Completions만 제공하는 업체용입니다. Cindy가 스트리밍 텍스트와 함수 도구 호출을 변환하며 일부 고급 Responses 기능은 사용할 수 없습니다."+ "chatHelp": "Chat Completions만 제공하는 업체용입니다. Cindy가 스트리밍 텍스트와 함수 도구 호출을 변환하며 일부 고급 Responses 기능은 사용할 수 없습니다.",+ "anthropicHelp": "Anthropic Messages API를 제공하는 업체용입니다. Cindy가 Responses 메시지, 이미지, 도구, 추론 내용 및 스트리밍 이벤트를 변환합니다."},"protocol": {"claude": "Claude Code","claudeDesc": "Claude Code는 Anthropic 프로토콜을 따릅니다(x-api-key 인증). 이 제공자의 Claude Code용 baseURL・키・모델을 입력하세요. 비워 두면 이 제공자는 Claude Code를 제공하지 않습니다.","codex": "Codex",- "codexDesc": "Codex는 OpenAI Responses 프로토콜을 사용합니다. Responses를 네이티브로 지원하는 업스트림이나 Chat Completions만 지원하는 제공자를 Cindy로 브리지하는 방식을 선택할 수 있습니다. 이 제공자의 Codex용 기본 URL, 키와 모델을 입력하세요. 비워 두면 Codex에서 사용하지 않습니다."+ "codexDesc": "Codex는 OpenAI Responses 프로토콜을 사용합니다. Responses를 네이티브로 사용하거나 Chat Completions 또는 Anthropic Messages를 Cindy로 브리지하는 방식을 선택할 수 있습니다. 이 제공자의 Codex용 기본 URL, 키와 모델을 입력하세요. 비워 두면 Codex에서 사용하지 않습니다."},"errors": {"nameRequired": "표시 이름을 입력하세요",@@ -4465,6 +4467,7 @@},"meta": {"context": "컨텍스트 {{value}}",+ "codexCompatibilityMode": "Codex 호환 모드","price": "{{input}}/{{output}} / 100만","fastBadge": "고속","budgetDiscount": "특별 할인"diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex dfc6470cdf..8417bcdf3d 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -1296,14 +1296,16 @@"wireProtocol": {"responses": "OpenAI Responses(原生)","chat": "Chat Completions(Cindy 桥接)",+ "anthropic": "Anthropic Messages(Cindy 桥接)","responsesHelp": "供应商原生支持 Responses API,Cindy 透明转发完整事件。",- "chatHelp": "适用于仅提供 Chat Completions 的供应商。Cindy 转换流式文本和函数工具调用;部分高级 Responses 能力不可用。"+ "chatHelp": "适用于仅提供 Chat Completions 的供应商。Cindy 转换流式文本和函数工具调用;部分高级 Responses 能力不可用。",+ "anthropicHelp": "适用于提供 Anthropic Messages API 的供应商。Cindy 转换 Responses 消息、图片、工具、推理内容与流式事件。"},"protocol": {"claude": "Claude Code","claudeDesc": "Claude Code 遵循 Anthropic 协议(用 x-api-key 鉴权)。填该来源用于 Claude Code 的 baseURL、密钥与模型,留空则此来源不提供 Claude Code。","codex": "Codex",- "codexDesc": "Codex 使用 OpenAI Responses 协议。上游可选择原生 Responses,或由 Cindy 桥接仅支持 Chat Completions 的供应商。填该来源用于 Codex 的 baseURL、密钥与模型,留空则此来源不提供 Codex。"+ "codexDesc": "Codex 使用 OpenAI Responses 协议。上游可选择原生 Responses,或由 Cindy 桥接 Chat Completions、Anthropic Messages。填该来源用于 Codex 的 baseURL、密钥与模型,留空则此来源不提供 Codex。"},"errors": {"nameRequired": "请填写显示名称",@@ -4465,6 +4467,7 @@},"meta": {"context": "{{value}} 上下文",+ "codexCompatibilityMode": "Codex 兼容模式","price": "{{input}}/{{output}} / 百万","fastBadge": "快速","budgetDiscount": "特别折扣"diff --git a/apps/desktop/src/renderer/lib/__tests__/customProviderWireProtocols.test.ts b/apps/desktop/src/renderer/lib/__tests__/customProviderWireProtocols.test.tsnew file mode 100644index 0000000000..82da18e16f--- /dev/null+++ b/apps/desktop/src/renderer/lib/__tests__/customProviderWireProtocols.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from 'vitest';++import {+ CUSTOM_PROVIDER_CODEX_WIRE_PROTOCOLS,+ customProviderCodexWireProtocolOption,+} from '../customProviderWireProtocols';++describe('custom provider Codex wire protocols', () => {+ it('offers every supported Codex route including the Anthropic Messages bridge', () => {+ expect(CUSTOM_PROVIDER_CODEX_WIRE_PROTOCOLS.map((option) => option.value)).toEqual([+ 'openai-responses',+ 'openai-chat',+ 'anthropic-messages',+ ]);+ });++ it('uses the Anthropic Messages endpoint as its default request path', () => {+ expect(customProviderCodexWireProtocolOption('anthropic-messages')).toMatchObject({+ helpKey: 'settings.providers.custom.wireProtocol.anthropicHelp',+ defaultRequestPath: '/v1/messages',+ });+ });+});diff --git a/apps/desktop/src/renderer/lib/customProviderWireProtocols.ts b/apps/desktop/src/renderer/lib/customProviderWireProtocols.tsnew file mode 100644index 0000000000..2713254b90--- /dev/null+++ b/apps/desktop/src/renderer/lib/customProviderWireProtocols.ts@@ -0,0 +1,41 @@+import type { ProviderWireProtocol } from '@cindy/model-providers';++export type CustomProviderCodexWireProtocol = Extract<+ ProviderWireProtocol,+ 'openai-responses' | 'openai-chat' | 'anthropic-messages'+>;++interface CustomProviderWireProtocolOption {+ value: CustomProviderCodexWireProtocol;+ labelKey: string;+ helpKey: string;+ defaultRequestPath: string;+}++export const CUSTOM_PROVIDER_CODEX_WIRE_PROTOCOLS = [+ {+ value: 'openai-responses',+ labelKey: 'settings.providers.custom.wireProtocol.responses',+ helpKey: 'settings.providers.custom.wireProtocol.responsesHelp',+ defaultRequestPath: '/responses',+ },+ {+ value: 'openai-chat',+ labelKey: 'settings.providers.custom.wireProtocol.chat',+ helpKey: 'settings.providers.custom.wireProtocol.chatHelp',+ defaultRequestPath: '/chat/completions',+ },+ {+ value: 'anthropic-messages',+ labelKey: 'settings.providers.custom.wireProtocol.anthropic',+ helpKey: 'settings.providers.custom.wireProtocol.anthropicHelp',+ defaultRequestPath: '/v1/messages',+ },+] as const satisfies readonly CustomProviderWireProtocolOption[];++export function customProviderCodexWireProtocolOption(+ protocol: ProviderWireProtocol,+): (typeof CUSTOM_PROVIDER_CODEX_WIRE_PROTOCOLS)[number] {+ return CUSTOM_PROVIDER_CODEX_WIRE_PROTOCOLS.find((option) => option.value === protocol)+ ?? CUSTOM_PROVIDER_CODEX_WIRE_PROTOCOLS[0];+}diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 68927ef598..7dc504dc2e 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -3752,6 +3752,7 @@ interface ElectronAPI {agent: 'claude-code' | 'codex';baseUrl: string;authMethod: 'apiKey' | 'oauth' | 'none';+ wireProtocol?: import('@cindy/model-providers').ProviderWireProtocol;modelsUrl?: string | null;apiKey?: string | null;headers?: Record<string, string>;diff --git a/docs/dev-rules/repo-map.md b/docs/dev-rules/repo-map.mdindex 8b0a3ffed5..fae29cb04d 100644--- a/docs/dev-rules/repo-map.md+++ b/docs/dev-rules/repo-map.md@@ -46,6 +46,7 @@| `model-providers` | 模型供应商目录 + 路由抽象(Anthropic/OpenAI/XD),纯逻辑 | desktop + mobile || `anthropic-compat-proxy` | 本地回环 HTTP 代理:剥离 Anthropic 专有字段,让 Claude Code SDK 可经网关访问非 Anthropic 后端 | desktop || `anthropic-responses-bridge` | 本地回环 HTTP 桥:Anthropic Messages API ↔ OpenAI Responses API 转换 | desktop |+| `responses-anthropic-bridge` | 本地 Responses → Anthropic Messages 桥:请求、图片/工具/thinking 转换与 Responses SSE 回译 | desktop || `lizi-mcps` | 可复用 MCP server 集合(Google 套件、GitHub/GitLab、浏览器、scheduler 等) | desktop || `cindy-tools` | 意识(Ghost)系统内部工具集(MCP),含 ghost 总机(`ghost_list` / `ghost_call`) | desktop || `browser-control-runtime` | 浏览器自动化运行时适配层(playwright-core + MCP) | desktop、lizi-mcps |diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.mdindex 7e8199a6e8..cbc3edcd4d 100644--- a/i18n/GLOSSARY.md+++ b/i18n/GLOSSARY.md@@ -124,6 +124,10 @@**注意别指望 `--update-baseline` 帮你收尾。** `proposed` 存在的理由正是「已知有存量不一致」,改成 `decided` 的那一刻这些告警会变成阻断违规;而 `--update-baseline` 只删不加,遇到 baseline 里没有的指纹会直接拒绝。所以裁决时只有两条路:要么把命中逐条读语境改掉,要么先人工把已 review 过的指纹写进 `i18n/glossary-baseline.json` 冻结存量,之后再用 `--update-baseline` 做修剪。+### Anthropic Messages++Anthropic Messages API / wire protocol 的用户可见名称。四语统一保留官方英文名称,避免与普通的“消息”概念混译;先登记为 proposed,待产品术语评审后固化。+### Global region企业认证与业务服务所在区域的用户可见名称,用于组织登录检测到 Global 服务区域时的确认文案;它描述连接的服务区域,不是对当前安装版本的标签,也不同于项目配置里的 generic global scope。先按现有四语文案登记为 proposed。diff --git a/i18n/glossary.json b/i18n/glossary.jsonindex 4cf9be1404..9be146793e 100644--- a/i18n/glossary.json+++ b/i18n/glossary.json@@ -54,6 +54,17 @@},"note": "远端主机上由 Cindy 管理的 Codex 凭证目录(~/.xdt-server/v1/codex-home/),与用户本机 ~/.codex 相区分。四语统一保留英文原词(home 小写),避免各语言自造「Codex 主目录」等不同说法;syncAuth 与 codexAuthMissing 等远端登录态文案使用。"},+ {+ "id": "anthropic-messages",+ "status": "proposed",+ "en": "Anthropic Messages",+ "translations": {+ "zh-CN": "Anthropic Messages",+ "ja": "Anthropic Messages",+ "ko": "Anthropic Messages"+ },+ "note": "Anthropic Messages API / wire protocol 的用户可见名称。四语统一保留官方英文名称,避免与普通的“消息”概念混译;先登记为 proposed,待产品术语评审后固化。"+ },{"id": "wechat","status": "proposed",diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex 11abe74862..a05d7077a9 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -409,6 +409,18 @@ export interface AgentDeps {*/registerCodexReviewerRouteContext?: (args: CodexReviewerRouteContextArgs) => boolean;+ /**+ * Codex 专用:app-server 创建子 Agent thread 后,把明确的父子 thread 关系同步给宿主。+ *+ * 子 thread 会独立发起 Responses 请求,但仍属于父业务 session;宿主据此继承+ * provider / bridge 路由和 proxy prompt。该钩子必须是同步内存操作,确保在子+ * thread 首个网络请求前完成登记。+ */+ registerCodexChildThreadForParent?: (args: {+ parentThreadId: string;+ childThreadId: string;+ }) => void;+/*** Claude 专用: host 明确认定可无提示执行的只读工具名, 透传到 SDK* `options.allowedTools`。maker-core 不维护任何产品工具名, 也不做 wildcard /diff --git a/packages/maker-core/src/agents/codex/app-server/host.test.ts b/packages/maker-core/src/agents/codex/app-server/host.test.tsindex 4ade47b9e7..28a6eba0e0 100644--- a/packages/maker-core/src/agents/codex/app-server/host.test.ts+++ b/packages/maker-core/src/agents/codex/app-server/host.test.ts@@ -69,6 +69,49 @@ class DelayedTransport implements Transport {}}+class NotificationTransport implements Transport {+ private readonly lineHandlers = new Set<LineHandler>();+ private readonly closeHandlers = new Set<CloseHandler>();+ readonly lines: string[] = [];++ async writeLine(line: string): Promise<void> {+ this.lines.push(line);+ const msg = JSON.parse(line) as { id?: unknown; method?: string };+ if (msg.id == null) return;+ const result = msg.method === 'initialize'+ ? {+ userAgent: 'mock-codex/test',+ codexHome: '/tmp/codex-home',+ platformOs: 'linux',+ }+ : {};+ this.emit({ id: msg.id, result });+ }++ onLine(handler: LineHandler): () => void {+ this.lineHandlers.add(handler);+ return () => this.lineHandlers.delete(handler);+ }++ onClose(handler: CloseHandler): () => void {+ this.closeHandlers.add(handler);+ return () => this.closeHandlers.delete(handler);+ }++ onStderr(_handler: StderrHandler): () => void {+ return () => {};+ }++ async close(reason = 'test close'): Promise<void> {+ for (const handler of this.closeHandlers) handler({ reason });+ }++ emit(message: unknown): void {+ const line = JSON.stringify(message);+ for (const handler of this.lineHandlers) handler(line);+ }+}+const logger: Logger = {trace: vi.fn(),debug: vi.fn(),@@ -165,3 +208,266 @@ describe('AppServerHost.ensureStartedWithTimeout', () => {await host.shutdown();});});++describe('AppServerHost descendant thread routing', () => {+ it('routes child and grandchild thread/started events to the root subscription', async () => {+ const transport = new NotificationTransport();+ const host = new AppServerHost({+ createTransport: () => transport,+ logger,+ clientInfo: { name: 'cindy-test', version: '0.0.0' },+ });+ await host.ensureStarted();++ const descendantThreadStarted = vi.fn();+ const subscription = host.subscribeThread('root-thread', {+ descendantThreadStarted,+ });++ transport.emit({+ method: 'thread/started',+ params: {+ thread: {+ id: 'child-thread',+ parentThreadId: 'root-thread',+ },+ },+ });+ transport.emit({+ method: 'thread/started',+ params: {+ thread: {+ id: 'grandchild-thread',+ parentThreadId: 'child-thread',+ },+ },+ });++ expect(descendantThreadStarted).toHaveBeenNthCalledWith(1, {+ thread: {+ id: 'child-thread',+ parentThreadId: 'root-thread',+ },+ });+ expect(descendantThreadStarted).toHaveBeenNthCalledWith(2, {+ thread: {+ id: 'grandchild-thread',+ parentThreadId: 'child-thread',+ },+ });++ await subscription.release();+ transport.emit({+ method: 'thread/started',+ params: {+ thread: {+ id: 'great-grandchild-thread',+ parentThreadId: 'grandchild-thread',+ },+ },+ });+ expect(descendantThreadStarted).toHaveBeenCalledTimes(2);++ await host.shutdown();+ });++ it('rebuilds buffered descendant lineage when the root subscribes after child starts', async () => {+ const transport = new NotificationTransport();+ const host = new AppServerHost({+ createTransport: () => transport,+ logger,+ clientInfo: { name: 'cindy-test', version: '0.0.0' },+ });+ await host.ensureStarted();++ // Cross-thread notifications can arrive out of lineage order. Both starts are+ // buffered under their own child ids because the root has not subscribed yet.+ transport.emit({+ method: 'thread/started',+ params: {+ thread: {+ id: 'grandchild-thread',+ parentThreadId: 'child-thread',+ },+ },+ });+ transport.emit({+ method: 'thread/started',+ params: {+ thread: {+ id: 'child-thread',+ parentThreadId: 'root-thread',+ },+ },+ });++ const descendantThreadStarted = vi.fn();+ const subscription = host.subscribeThread('root-thread', {+ descendantThreadStarted,+ });++ expect(descendantThreadStarted).toHaveBeenCalledTimes(2);+ expect(descendantThreadStarted).toHaveBeenCalledWith({+ thread: {+ id: 'child-thread',+ parentThreadId: 'root-thread',+ },+ });+ expect(descendantThreadStarted).toHaveBeenCalledWith({+ thread: {+ id: 'grandchild-thread',+ parentThreadId: 'child-thread',+ },+ });++ await subscription.release();+ await host.shutdown();+ });++ it('routes descendant server requests to the root subscription handlers', async () => {+ const transport = new NotificationTransport();+ const host = new AppServerHost({+ createTransport: () => transport,+ logger,+ clientInfo: { name: 'cindy-test', version: '0.0.0' },+ });+ await host.ensureStarted();++ const commandExecutionApproval = vi.fn(async () => ({ decision: 'accept' as const }));+ const fileChangeApproval = vi.fn(async () => ({ decision: 'accept' as const }));+ const mcpServerElicitation = vi.fn(async () => ({+ action: 'accept' as const,+ content: { value: 'ok' },+ _meta: null,+ }));+ const permissionsApproval = vi.fn(async () => ({+ permissions: { network: true },+ scope: 'turn' as const,+ }));+ const requestUserInput = vi.fn(async (_params, meta) => ({+ answers: { q1: { answers: [`request:${String(meta.requestId)}`] } },+ }));+ const dynamicToolCall = vi.fn(async (_params, meta) => ({+ contentItems: [{ type: 'inputText' as const, text: `request:${String(meta.requestId)}` }],+ success: true,+ }));+ const subscription = host.subscribeThread('root-thread', {+ commandExecutionApproval,+ fileChangeApproval,+ mcpServerElicitation,+ permissionsApproval,+ requestUserInput,+ dynamicToolCall,+ });++ transport.emit({+ method: 'thread/started',+ params: { thread: { id: 'child-thread', parentThreadId: 'root-thread' } },+ });++ const requests = [+ {+ id: 'server-command',+ method: 'item/commandExecution/requestApproval',+ params: { threadId: 'child-thread', turnId: 'turn-1', itemId: 'item-1' },+ expected: { decision: 'accept' },+ },+ {+ id: 'server-file',+ method: 'item/fileChange/requestApproval',+ params: { threadId: 'child-thread', turnId: 'turn-1', itemId: 'item-2' },+ expected: { decision: 'accept' },+ },+ {+ id: 'server-elicitation',+ method: 'mcpServer/elicitation/request',+ params: {+ threadId: 'child-thread',+ turnId: 'turn-1',+ serverName: 'test-mcp',+ mode: 'form',+ _meta: null,+ message: 'Confirm',+ requestedSchema: {},+ },+ expected: { action: 'accept', content: { value: 'ok' }, _meta: null },+ },+ {+ id: 'server-permissions',+ method: 'item/permissions/requestApproval',+ params: {+ threadId: 'child-thread',+ turnId: 'turn-1',+ itemId: 'item-3',+ permissions: { network: true },+ },+ expected: { permissions: { network: true }, scope: 'turn' },+ },+ {+ id: 'server-input',+ method: 'item/tool/requestUserInput',+ params: {+ threadId: 'child-thread',+ turnId: 'turn-1',+ itemId: 'item-4',+ questions: [],+ },+ expected: { answers: { q1: { answers: ['request:server-input'] } } },+ },+ {+ id: 'server-tool',+ method: 'item/tool/call',+ params: {+ threadId: 'child-thread',+ turnId: 'turn-1',+ callId: 'call-1',+ namespace: null,+ tool: 'test_tool',+ arguments: {},+ },+ expected: {+ contentItems: [{ type: 'inputText', text: 'request:server-tool' }],+ success: true,+ },+ },+ ] as const;++ const initialLineCount = transport.lines.length;+ for (const request of requests) {+ transport.emit(request);+ }++ await vi.waitFor(() => {+ expect(transport.lines.length).toBe(initialLineCount + requests.length);+ });+ const responses = transport.lines+ .slice(initialLineCount)+ .map((line) => JSON.parse(line) as { id: string; result: unknown });+ expect(responses).toEqual(+ requests.map((request) => ({ id: request.id, result: request.expected })),+ );+ expect(commandExecutionApproval).toHaveBeenCalledWith(+ expect.objectContaining({ threadId: 'child-thread' }),+ );+ expect(fileChangeApproval).toHaveBeenCalledWith(+ expect.objectContaining({ threadId: 'child-thread' }),+ );+ expect(mcpServerElicitation).toHaveBeenCalledWith(+ expect.objectContaining({ threadId: 'child-thread' }),+ );+ expect(permissionsApproval).toHaveBeenCalledWith(+ expect.objectContaining({ threadId: 'child-thread' }),+ );+ expect(requestUserInput).toHaveBeenCalledWith(+ expect.objectContaining({ threadId: 'child-thread' }),+ { requestId: 'server-input' },+ );+ expect(dynamicToolCall).toHaveBeenCalledWith(+ expect.objectContaining({ threadId: 'child-thread' }),+ { requestId: 'server-tool' },+ );++ await subscription.release();+ await host.shutdown();+ });+});diff --git a/packages/maker-core/src/agents/codex/app-server/host.ts b/packages/maker-core/src/agents/codex/app-server/host.tsindex bdea8ecb42..9036263852 100644--- a/packages/maker-core/src/agents/codex/app-server/host.ts+++ b/packages/maker-core/src/agents/codex/app-server/host.ts@@ -122,6 +122,7 @@ function extractThreadId(method: string, params: unknown): string | null {export interface ThreadEventHandlers {threadStarted?: (params: ThreadStartedNotification['params']) => void;+ descendantThreadStarted?: (params: ThreadStartedNotification['params']) => void;turnStarted?: (params: TurnStartedNotification['params']) => void;turnCompleted?: (params: TurnCompletedNotification['params']) => void;/** 每次 turn 都会推一次 (turn 完成前), 与 turn/completed 在同 turnId 下成对出现。 */@@ -252,6 +253,8 @@ export class AppServerHost {private startPromise: Promise<InitializeResponse> | null = null;private readonly subscribers = new Map<string, ThreadEventHandlers>();+ /** root / descendant threadId → 当前拥有该子树订阅的 root threadId。 */+ private readonly lineageRoots = new Map<string, string>();/** 找不到 subscriber 时按 threadId 暂存的 notification, drain on subscribe。 */private readonly buffered = new Map<string, BufferedNotification[]>();/**@@ -360,7 +363,7 @@ export class AppServerHost {// 防 server 在握手过程中就发出 approval (虽然实际不会, 但 defensive)。client.setRequestHandler(Method.CommandExecutionRequestApproval, async (rawParams) => {const params = rawParams as CommandExecutionRequestApprovalParams;- const handlers = this.subscribers.get(params.threadId);+ const handlers = this.handlersForThread(params.threadId);if (!handlers?.commandExecutionApproval) {this.logger.warn('commandExecution approval without subscriber → decline', {threadId: params.threadId,@@ -381,7 +384,7 @@ export class AppServerHost {client.setRequestHandler(Method.FileChangeRequestApproval, async (rawParams) => {const params = rawParams as FileChangeRequestApprovalParams;- const handlers = this.subscribers.get(params.threadId);+ const handlers = this.handlersForThread(params.threadId);if (!handlers?.fileChangeApproval) {this.logger.warn('fileChange approval without subscriber → decline', {threadId: params.threadId,@@ -402,7 +405,7 @@ export class AppServerHost {client.setRequestHandler(Method.McpServerElicitationRequest, async (rawParams) => {const params = rawParams as McpServerElicitationRequestParams;- const handlers = this.subscribers.get(params.threadId);+ const handlers = this.handlersForThread(params.threadId);if (!handlers?.mcpServerElicitation) {this.logger.warn('MCP server elicitation without subscriber -> decline', {threadId: params.threadId,@@ -424,7 +427,7 @@ export class AppServerHost {client.setRequestHandler(Method.PermissionsRequestApproval, async (rawParams) => {const params = rawParams as PermissionsRequestApprovalParams;- const handlers = this.subscribers.get(params.threadId);+ const handlers = this.handlersForThread(params.threadId);if (!handlers?.permissionsApproval) {this.logger.warn('permissions approval without subscriber → decline', {threadId: params.threadId,@@ -444,7 +447,7 @@ export class AppServerHost {client.setRequestHandler(Method.ToolRequestUserInput, async (rawParams, meta) => {const params = rawParams as ToolRequestUserInputParams;- const handlers = this.subscribers.get(params.threadId);+ const handlers = this.handlersForThread(params.threadId);if (!handlers?.requestUserInput) {this.logger.warn('requestUserInput without subscriber -> empty response', {threadId: params.threadId,@@ -466,7 +469,7 @@ export class AppServerHost {client.setRequestHandler(Method.DynamicToolCall, async (rawParams, meta) => {const params = rawParams as DynamicToolCallParams;- const handlers = this.subscribers.get(params.threadId);+ const handlers = this.handlersForThread(params.threadId);if (!handlers?.dynamicToolCall) {this.logger.warn('dynamicToolCall without subscriber -> failed result', {threadId: params.threadId,@@ -589,6 +592,7 @@ export class AppServerHost {if (this.shuttingDown) return;this.shuttingDown = true;this.subscribers.clear();+ this.lineageRoots.clear();this.buffered.clear();const c = this.client;this.client = null;@@ -651,6 +655,7 @@ export class AppServerHost {this.logger.warn('overwriting thread subscription', { threadId });}this.subscribers.set(threadId, handlers);+ this.lineageRoots.set(threadId, threadId);// 排空缓存 (thread/started 比 subscribe 早到的固有竞争)const buf = this.buffered.get(threadId);@@ -660,6 +665,7 @@ export class AppServerHost {this.dispatchToHandlers(handlers, item.method, item.params);}}+ this.replayBufferedDescendantThreadStarts(threadId);// 账号配额 snapshot replay — 让新 session 立即看到当前账号配额, 不必等下次 turn。if (this.lastAccountRateLimits && handlers.accountRateLimitsUpdated) {@@ -686,6 +692,7 @@ export class AppServerHost {return Promise.resolve();}this.subscribers.delete(threadId);+ this.deleteLineageForRoot(threadId);this.buffered.delete(threadId);localReleased = true;} else if (this.subscribers.has(threadId)) {@@ -745,6 +752,9 @@ export class AppServerHost {this.logger.warn('notification missing threadId', { method });return;}+ if (method === 'thread/started') {+ this.routeDescendantThreadStarted(params as ThreadStartedNotification['params']);+ }const handlers = this.subscribers.get(threadId);if (handlers) {this.dispatchToHandlers(handlers, method, params);@@ -755,6 +765,79 @@ export class AppServerHost {this.bufferNotification(threadId, method, params);}+ /**+ * Server requests from descendant threads must use the root subscription's+ * handlers, just like descendant notifications. The app-server only knows+ * the concrete child thread id, while approvals / elicitation / dynamic+ * tool callbacks belong to the Cindy session that owns the root thread.+ */+ private handlersForThread(threadId: string): ThreadEventHandlers | undefined {+ const rootThreadId = this.lineageRoots.get(threadId)+ ?? (this.subscribers.has(threadId) ? threadId : null);+ return rootThreadId ? this.subscribers.get(rootThreadId) : undefined;+ }++ private routeDescendantThreadStarted(params: ThreadStartedNotification['params']): void {+ const childThreadId = params.thread.id;+ const parentThreadId = params.thread.parentThreadId;+ if (!parentThreadId || parentThreadId === childThreadId) return;++ const rootThreadId = this.lineageRoots.get(parentThreadId)+ ?? (this.subscribers.has(parentThreadId) ? parentThreadId : null);+ if (!rootThreadId) return;+ if (this.lineageRoots.get(childThreadId) === rootThreadId) return;++ const handlers = this.subscribers.get(rootThreadId);+ if (!handlers) return;++ this.lineageRoots.set(childThreadId, rootThreadId);+ if (!handlers.descendantThreadStarted) return;+ try {+ handlers.descendantThreadStarted(params);+ } catch (e) {+ this.logger.error('descendant thread handler threw', {+ rootThreadId,+ parentThreadId,+ childThreadId,+ message: (e as Error).message,+ });+ }+ }++ private replayBufferedDescendantThreadStarts(rootThreadId: string): void {+ // thread/started is buffered under the child id. A root subscription therefore+ // cannot drain those entries directly; rebuild the lineage iteratively so an+ // already-buffered child can unlock an already-buffered grandchild as well.+ for (;;) {+ let discovered = 0;+ for (const notifications of this.buffered.values()) {+ for (const item of notifications) {+ if (item.method !== 'thread/started') continue;+ const params = item.params as ThreadStartedNotification['params'];+ const childThreadId = params.thread?.id;+ const parentThreadId = params.thread?.parentThreadId;+ if (+ !childThreadId+ || !parentThreadId+ || this.lineageRoots.has(childThreadId)+ || this.lineageRoots.get(parentThreadId) !== rootThreadId+ ) continue;+ this.routeDescendantThreadStarted(params);+ if (this.lineageRoots.get(childThreadId) === rootThreadId) discovered += 1;+ }+ }+ if (discovered === 0) return;+ }+ }++ private deleteLineageForRoot(rootThreadId: string): void {+ for (const [threadId, ownerRootThreadId] of this.lineageRoots) {+ if (ownerRootThreadId === rootThreadId) {+ this.lineageRoots.delete(threadId);+ }+ }+ }+private dispatchToHandlers(handlers: ThreadEventHandlers, method: string, params: unknown): void {let fn: ((p: never) => void) | undefined;switch (method) {diff --git a/packages/maker-core/src/agents/codex/app-server/protocol.ts b/packages/maker-core/src/agents/codex/app-server/protocol.tsindex 76a0b09222..359f7accab 100644--- a/packages/maker-core/src/agents/codex/app-server/protocol.ts+++ b/packages/maker-core/src/agents/codex/app-server/protocol.ts@@ -775,7 +775,14 @@ export interface DynamicToolCallResponse {*/export interface ThreadStartedNotification {method: 'thread/started';- params: { thread: { id: string; [k: string]: unknown }; [k: string]: unknown };+ params: {+ thread: {+ id: string;+ parentThreadId?: string | null;+ [k: string]: unknown;+ };+ [k: string]: unknown;+ };}export interface TurnStartedNotification {diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 00861d6552..2ef2671860 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -1879,6 +1879,70 @@ describe('CodexAgent.startSession developerInstructions', () => {await proxyHandle.close();});+ it('reports Codex child and descendant threads to the host-owned proxy route registry', async () => {+ const registerCodexChildThreadForParent = vi.fn();+ const registerCodexMcpThreadContext = vi.fn();+ const unregisterCodexMcpThreadContext = vi.fn();+ const agent = new CodexAgent(createDeps(+ { systemPrompt: 'HOST PRODUCT PROMPT' },+ {+ registerCodexSystemPromptForThread: vi.fn(),+ registerCodexChildThreadForParent,+ registerCodexMcpThreadContext,+ unregisterCodexMcpThreadContext,+ },+ ));+ const host = installFakeHost(agent, undefined, { codexProxyActive: true });+ const handle = await agent.startSession({+ sessionId: 'session-child-route',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });++ const handlers = host.getThreadHandlers();+ if (!handlers?.descendantThreadStarted) {+ throw new Error('expected descendantThreadStarted handler');+ }+ handlers.descendantThreadStarted({+ thread: {+ id: 'child-thread-id',+ parentThreadId: 'start-thread-id',+ },+ });+ handlers.descendantThreadStarted({+ thread: {+ id: 'grandchild-thread-id',+ parentThreadId: 'child-thread-id',+ },+ });++ expect(registerCodexChildThreadForParent).toHaveBeenNthCalledWith(1, {+ parentThreadId: 'start-thread-id',+ childThreadId: 'child-thread-id',+ });+ expect(registerCodexChildThreadForParent).toHaveBeenNthCalledWith(2, {+ parentThreadId: 'child-thread-id',+ childThreadId: 'grandchild-thread-id',+ });+ expect(registerCodexMcpThreadContext).toHaveBeenNthCalledWith(2, {+ threadId: 'child-thread-id',+ sessionId: 'session-child-route',+ workingDir: '/repo',+ vendorOptions: {},+ });+ expect(registerCodexMcpThreadContext).toHaveBeenNthCalledWith(3, {+ threadId: 'grandchild-thread-id',+ sessionId: 'session-child-route',+ workingDir: '/repo',+ vendorOptions: {},+ });++ await handle.close();+ expect(unregisterCodexMcpThreadContext).toHaveBeenCalledWith('start-thread-id');+ expect(unregisterCodexMcpThreadContext).toHaveBeenCalledWith('child-thread-id');+ expect(unregisterCodexMcpThreadContext).toHaveBeenCalledWith('grandchild-thread-id');+ });+it('omits thread/resume developerInstructions and registers prompt when codex proxy is active', async () => {const runtimeConfig = { systemPrompt: 'HOST PRODUCT PROMPT' };const userPrompt = [diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 4ae52de518..f3dbc441ed 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -2779,6 +2779,18 @@ export class CodexAgent extends BaseAgent {log.warn('unregisterCodexMcpThreadContext threw', { error: String(e) });}};+ const descendantMcpThreadIds = new Set<string>();+ const registerDescendantCodexMcpContext = (descendantThreadId: string): void => {+ if (descendantThreadId === threadId || descendantMcpThreadIds.has(descendantThreadId)) return;+ descendantMcpThreadIds.add(descendantThreadId);+ registerCodexMcpContext(descendantThreadId);+ };+ const unregisterDescendantCodexMcpContexts = (): void => {+ for (const descendantThreadId of descendantMcpThreadIds) {+ unregisterCodexMcpContext(descendantThreadId);+ }+ descendantMcpThreadIds.clear();+ };function currentApprovalConfig(): CodexPermissionConfig {return mapPermissionToCodex(mutablePermissionMode,@@ -5877,6 +5889,16 @@ export class CodexAgent extends BaseAgent {eventQueue.push({ type: 'session_id', data: sdkSessionId, source: 'codex' });}},+ descendantThreadStarted: (params) => {+ const childThreadId = params.thread.id;+ const parentThreadId = params.thread.parentThreadId;+ if (!parentThreadId || childThreadId === parentThreadId) return;+ registerDescendantCodexMcpContext(childThreadId);+ this.deps.registerCodexChildThreadForParent?.({+ parentThreadId,+ childThreadId,+ });+ },turnStarted: (params) => {// turn/start RPC 已失败(超时/拒绝)但 daemon 实际已建 turn — 迟到的孤儿// turnStarted 不得重新激活已报终态错误的会话 (greptile P1): 立墓碑 +@@ -7246,6 +7268,7 @@ export class CodexAgent extends BaseAgent {closed = true;resetUpstreamIdleForTurnEnd();unregisterCodexMcpContext(threadId);+ unregisterDescendantCodexMcpContexts();// close 时 buffer 里可能还有等对账的挂起请求 (codex R17 P2):// 统一按拒绝释放, 否则 handler 永远悬挂, dispatchServerRequest// 永不返回, server 侧请求卡死。@@ -7409,6 +7432,9 @@ export class CodexAgent extends BaseAgent {// host bridge see runtime Orca role/workflow updates by reference.Object.assign(vo, patch);registerCodexMcpContext(threadId);+ for (const descendantThreadId of descendantMcpThreadIds) {+ registerCodexMcpContext(descendantThreadId);+ }log.debug('setVendorOptions', {patchKeys: Object.keys(patch),});diff --git a/packages/model-providers/src/__tests__/catalog.test.ts b/packages/model-providers/src/__tests__/catalog.test.tsindex 25dce5e8d3..8f3a111800 100644--- a/packages/model-providers/src/__tests__/catalog.test.ts+++ b/packages/model-providers/src/__tests__/catalog.test.ts@@ -52,10 +52,12 @@ function runtimeCatalog(): Catalog {const clone = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;for (const p of clone.providers) {if (p.id === 'anthropic') {- p.models['claude-code'] = [+ const anthropic = [model('claude-opus-4-8', { name: 'Opus 4.8', contextWindow: 1_000_000, supportsFastMode: true }),model('claude-sonnet-4-6', { name: 'Sonnet 4.6', contextWindow: 1_000_000 }),];+ p.models['claude-code'] = anthropic;+ p.models.codex = anthropic;}if (p.id === 'openai') {p.models.codex = [model('gpt-5.5', { name: 'GPT-5.5', supportsFastMode: true })];@@ -362,11 +364,12 @@ describe('routing wireProtocol per-agent 契约', () => {expect(() => parseCatalog(bad)).toThrow(/openai-chat/);});- it('parseCatalog 拒绝 codex 使用 anthropic-messages(codex host 只实现 Responses 与本地 Chat 桥)', () => {+ it('parseCatalog 允许 codex 使用 anthropic-messages(由本地 Responses→Anthropic bridge 接管)', () => {const bad = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;const xai = bad.providers.find((p) => p.id === 'xai')!;xai.routing.codex = { ...xai.routing.codex!, wireProtocol: 'anthropic-messages' };- expect(() => parseCatalog(bad)).toThrow(/anthropic-messages/);+ expect(parseCatalog(bad).providers.find((p) => p.id === 'xai')?.routing.codex?.wireProtocol)+ .toBe('anthropic-messages');});});diff --git a/packages/model-providers/src/__tests__/codexCompatibility.test.ts b/packages/model-providers/src/__tests__/codexCompatibility.test.tsnew file mode 100644index 0000000000..d89f9a688d--- /dev/null+++ b/packages/model-providers/src/__tests__/codexCompatibility.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest';++import { resolveCodexCompatibilityWireProtocol } from '../codexCompatibility.js';+import type { CatalogModel, Provider, ProviderWireProtocol } from '../types.js';++function provider(wireProtocol?: ProviderWireProtocol): Provider {+ return {+ id: 'fixture',+ name: 'Fixture',+ source: 'user',+ agents: ['codex'],+ auth: { method: 'none' },+ routing: {+ codex: {+ upstream: 'https://example.test',+ authStrategy: 'none',+ ...(wireProtocol ? { wireProtocol } : {}),+ },+ },+ models: { codex: [] },+ };+}++const model: Pick<CatalogModel, 'codexCompatibilityWireProtocol'> = {};++describe('resolveCodexCompatibilityWireProtocol', () => {+ it.each([+ ['openai-chat', 'openai-chat'],+ ['anthropic-messages', 'anthropic-messages'],+ ['openai-responses', null],+ [undefined, null],+ ] as const)('把 Provider 级 %s 解析为 %s', (wireProtocol, expected) => {+ expect(resolveCodexCompatibilityWireProtocol(provider(wireProtocol), 'codex', model)).toBe(+ expected,+ );+ });++ it('模型级协议覆盖 Provider 的原生 Responses 路由', () => {+ expect(+ resolveCodexCompatibilityWireProtocol(provider('openai-responses'), 'codex', {+ codexCompatibilityWireProtocol: 'anthropic-messages',+ }),+ ).toBe('anthropic-messages');+ });++ it('非 Codex agent 不显示兼容模式', () => {+ expect(+ resolveCodexCompatibilityWireProtocol(provider('anthropic-messages'), 'claude-code', model),+ ).toBeNull();+ });+});diff --git a/packages/model-providers/src/__tests__/sections.test.ts b/packages/model-providers/src/__tests__/sections.test.tsindex f2acf7479a..fdb46217ad 100644--- a/packages/model-providers/src/__tests__/sections.test.ts+++ b/packages/model-providers/src/__tests__/sections.test.ts@@ -160,6 +160,30 @@ describe('buildProviderSections', () => {expect(models.find((m) => m.id === 'claude-fable-5')?.icon).toBe('claude');expect('icon' in (models.find((m) => m.id === 'gpt-5.5') ?? {})).toBe(false);});++ it('模型级 Codex bridge 协议透传进 SectionModel;缺省不带字段', () => {+ const bridged = provider('xd', 'XD', [+ {+ ...model('claude-opus-4-8', 'Opus 4.8'),+ codexCompatibilityWireProtocol: 'anthropic-messages',+ },+ model('gpt-5.5', 'GPT-5.5'),+ ]);+ bridged.agents = ['codex'];+ bridged.models = { codex: bridged.models['claude-code'] };+ const sections = buildProviderSections({+ providers: [bridged],+ agent: 'codex',+ isVisible: () => true,+ });+ const models = sections[0].models;+ expect(models.find((m) => m.id === 'claude-opus-4-8')?.codexCompatibilityWireProtocol).toBe(+ 'anthropic-messages',+ );+ expect('codexCompatibilityWireProtocol' in (models.find((m) => m.id === 'gpt-5.5') ?? {})).toBe(+ false,+ );+ });});describe('resolveModelIconKind', () => {diff --git a/packages/model-providers/src/__tests__/source-registry.test.ts b/packages/model-providers/src/__tests__/source-registry.test.tsindex 38b16aa411..2ed4bef027 100644--- a/packages/model-providers/src/__tests__/source-registry.test.ts+++ b/packages/model-providers/src/__tests__/source-registry.test.ts@@ -59,7 +59,9 @@ function runtimeCatalog(): Catalog {const clone = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;for (const p of clone.providers) {if (p.id === 'anthropic') {- p.models['claude-code'] = [model('claude-opus-4-8', { name: 'Opus 4.8', contextWindow: 1_000_000 })];+ const models = [model('claude-opus-4-8', { name: 'Opus 4.8', contextWindow: 1_000_000 })];+ p.models['claude-code'] = models;+ p.models.codex = models;}if (p.id === 'openai') {p.models.codex = [model('gpt-5.5', { name: 'GPT-5.5' })];@@ -348,7 +350,7 @@ describe('registry visibility & sources(运行时注入 fixture)', () => {it('providersForAgent ignores connection', () => {expect(providersForAgent(views, 'claude-code').map((p) => p.id).sort()).toEqual(['anthropic', 'openai', 'xai', 'xd']);- expect(providersForAgent(views, 'codex').map((p) => p.id).sort()).toEqual(['openai', 'xai', 'xd']);+ expect(providersForAgent(views, 'codex').map((p) => p.id).sort()).toEqual(['anthropic', 'openai', 'xai', 'xd']);});it('connectedProvidersForAgent honors connection', () => {@@ -517,6 +519,19 @@ describe('resolveRoute(运行时注入 fixture)', () => {expect(r?.routing.authStrategy).toBe('oauth-passthrough');});+ it('anthropic claude (codex) → Anthropic Messages bridge + host-owned OAuth', () => {+ const r = resolveRoute(views, 'anthropic', 'claude-opus-4-8', 'codex');+ expect(r?.routing).toMatchObject({+ upstream: 'https://api.anthropic.com',+ wireProtocol: 'anthropic-messages',+ authStrategy: 'provider-oauth-header',+ headerOverride: {+ 'anthropic-version': '2023-06-01',+ 'anthropic-beta': 'claude-code-20250219,oauth-2025-04-20',+ },+ });+ });+it('xd claude (claude-code) → gateway, gateway-key, 不删 anthropic-beta(fast 经网关透传)', () => {const r = resolveRoute(views, 'xd', 'claude-opus-4-8', 'claude-code');expect(r?.routing.upstream).toBe(xdRouting?.['claude-code']?.upstream);@@ -540,7 +555,6 @@ describe('resolveRoute(运行时注入 fixture)', () => {it('rejects unsupported (provider, model, agent) combos', () => {expect(resolveRoute(views, 'anthropic', 'gpt-5.5', 'claude-code')).toBeNull();- expect(resolveRoute(views, 'anthropic', 'claude-opus-4-8', 'codex')).toBeNull();expect(resolveRoute(views, 'openai', 'claude-opus-4-8', 'codex')).toBeNull();expect(resolveRoute(views, 'nope', 'claude-opus-4-8', 'claude-code')).toBeNull();});diff --git a/packages/model-providers/src/__tests__/user-provider.test.ts b/packages/model-providers/src/__tests__/user-provider.test.tsindex ed6b3250ac..7f0354d214 100644--- a/packages/model-providers/src/__tests__/user-provider.test.ts+++ b/packages/model-providers/src/__tests__/user-provider.test.ts@@ -63,6 +63,20 @@ describe('buildUserProvider (per-runtime)', () => {});});+ it('preserves an explicit Anthropic Messages protocol for Codex routing', () => {+ const p = buildUserProvider({+ ...codexOnly,+ runtimes: {+ codex: { ...codexOnly.runtimes.codex!, wireProtocol: 'anthropic-messages' },+ },+ });+ expect(p.routing.codex).toMatchObject({+ upstream: 'https://openrouter.ai/api/v1',+ authStrategy: 'api-key-header',+ wireProtocol: 'anthropic-messages',+ });+ });+it('preserves a non-standard inference request path in routing', () => {const p = buildUserProvider({...codexOnly,diff --git a/packages/model-providers/src/builtin.ts b/packages/model-providers/src/builtin.tsindex f4d85cf25d..22addc4717 100644--- a/packages/model-providers/src/builtin.ts+++ b/packages/model-providers/src/builtin.ts@@ -69,7 +69,11 @@ const ANTHROPIC_PROVIDER: Provider = {id: 'anthropic',name: 'Anthropic',source: 'builtin',- agents: ['claude-code'],+ // Claude.ai OAuth can be used by both native Claude Code and the Codex →+ // Anthropic Messages bridge. The two runtimes deliberately use different+ // auth strategies below: Claude Code may pass its native OAuth through,+ // while Codex must receive a host-owned Claude.ai token.+ agents: ['claude-code', 'codex'],auth: { method: 'oauth' },access: { kind: 'subscription', product: 'Claude.ai' },titleModel: 'claude-haiku-4-5',@@ -78,8 +82,18 @@ const ANTHROPIC_PROVIDER: Provider = {upstream: 'https://api.anthropic.com',authStrategy: 'oauth-passthrough',},+ codex: {+ upstream: 'https://api.anthropic.com',+ wireProtocol: 'anthropic-messages',+ authStrategy: 'provider-oauth-header',+ headerOverride: {+ 'anthropic-version': '2023-06-01',+ 'anthropic-beta': 'claude-code-20250219,oauth-2025-04-20',+ },+ headerDelete: ['chatgpt-account-id', 'openai-beta', 'originator', 'session_id'],+ },},- models: { 'claude-code': [] },+ models: { 'claude-code': [], codex: [] },};/** OpenAI(ChatGPT 订阅 OAuth)。模型清单来自 codex 注册表,此处恒为空。 */diff --git a/packages/model-providers/src/catalog.ts b/packages/model-providers/src/catalog.tsindex ae87654e01..867d835550 100644--- a/packages/model-providers/src/catalog.ts+++ b/packages/model-providers/src/catalog.ts@@ -230,14 +230,9 @@ function validateProvider(p: Provider): void {`provider '${p.id}' routing[${agent}] cannot use openai-chat`,);}- // Codex host 只实现原生 Responses 与本地 Responses→Chat 桥;anthropic-messages 会掉进- // 透明路由、把 Responses body 直发上游 → 确定性 4xx。热更目录里的坏 runtime 在此拦下。- if (agent === 'codex') {- assert(- routing.wireProtocol !== 'anthropic-messages',- `provider '${p.id}' routing[${agent}] cannot use anthropic-messages`,- );- }+ // Codex supports native Responses, Responses→Chat and Responses→Anthropic local+ // bridges. The latter is deliberately a local handler path; transparent forwarding+ // must never be used for an Anthropic Messages runtime.}if (routing.requestPath !== undefined) {assert(@@ -387,7 +382,6 @@ function isValidPreset(v: unknown): v is ProviderPreset {}if (r.wireProtocol !== undefined && !isWireProtocol(r.wireProtocol)) return false;if (agent === 'claude-code' && r.wireProtocol === 'openai-chat') return false;- if (agent === 'codex' && r.wireProtocol === 'anthropic-messages') return false;if (r.headers !== undefined) {if (!r.headers || typeof r.headers !== 'object' || Array.isArray(r.headers)) return false;if (Object.values(r.headers as Record<string, unknown>).some((x) => typeof x !== 'string')) return false;diff --git a/packages/model-providers/src/codexCompatibility.ts b/packages/model-providers/src/codexCompatibility.tsnew file mode 100644index 0000000000..67f1f8f1ab--- /dev/null+++ b/packages/model-providers/src/codexCompatibility.ts@@ -0,0 +1,33 @@+import type {+ AgentKind,+ CatalogModel,+ CodexCompatibilityWireProtocol,+ Provider,+ ProviderWireProtocol,+} from './types.js';++function isCodexCompatibilityWireProtocol(+ protocol: ProviderWireProtocol | undefined,+): protocol is CodexCompatibilityWireProtocol {+ return protocol === 'openai-chat' || protocol === 'anthropic-messages';+}++/**+ * 解析某个 (provider, agent, model) 是否通过本地 bridge 兼容 Codex。+ *+ * Provider 级 wire protocol 是常规来源;模型级覆盖仅用于 XD 这类同一 Provider 内+ * 同时存在原生 Responses 与桥接模型的情况。Renderer、远程设备视图与其它展示面应+ * 复用本函数,避免按 Provider id 或模型名复制路由判断。+ */+export function resolveCodexCompatibilityWireProtocol(+ provider: Pick<Provider, 'routing'>,+ agent: AgentKind | null | undefined,+ model: Pick<CatalogModel, 'codexCompatibilityWireProtocol'> | null | undefined,+): CodexCompatibilityWireProtocol | null {+ if (agent !== 'codex') return null;+ if (model?.codexCompatibilityWireProtocol) {+ return model.codexCompatibilityWireProtocol;+ }+ const providerProtocol = provider.routing.codex?.wireProtocol;+ return isCodexCompatibilityWireProtocol(providerProtocol) ? providerProtocol : null;+}diff --git a/packages/model-providers/src/index.ts b/packages/model-providers/src/index.tsindex 2ba1e8fe73..b81e6a5a56 100644--- a/packages/model-providers/src/index.ts+++ b/packages/model-providers/src/index.ts@@ -10,6 +10,7 @@export type {AgentKind,ProviderWireProtocol,+ CodexCompatibilityWireProtocol,Effort,ProviderSource,AuthMethod,@@ -30,6 +31,8 @@ export type {OAuthProviderDescriptor,} from './types.js';+export { resolveCodexCompatibilityWireProtocol } from './codexCompatibility.js';+export { BUNDLED_CATALOG, BUILTIN_PROVIDERS, parseCatalog, presetDisplayName, sanitizePresets, sortPresetsForLocale } from './catalog.js';export { buildUserProvider, DEFAULT_CUSTOM_CONTEXT_WINDOW } from './user-provider.js';diff --git a/packages/model-providers/src/sections.ts b/packages/model-providers/src/sections.tsindex 3b815b2885..9be5c62b33 100644--- a/packages/model-providers/src/sections.ts+++ b/packages/model-providers/src/sections.ts@@ -37,6 +37,8 @@ export interface SectionModel {defaultEffort: Effort | null;effortDisplayNames?: Record<string, string>;supportsFastMode?: boolean;+ /** 模型级 Codex bridge 协议;Provider 级协议仍从 section.provider.routing 读取。 */+ codexCompatibilityWireProtocol?: CatalogModel['codexCompatibilityWireProtocol'];contextWindow: number;/** 展示图标 id(AI Gateway / 目录设定,见 CatalogModel.icon);缺省回落来源供应商标。 */icon?: string;@@ -175,6 +177,9 @@ export function buildProviderSections(args: {if (m.description !== undefined) sm.description = m.description;if (m.effortDisplayNames !== undefined) sm.effortDisplayNames = m.effortDisplayNames;if (m.supportsFastMode !== undefined) sm.supportsFastMode = m.supportsFastMode;+ if (m.codexCompatibilityWireProtocol !== undefined) {+ sm.codexCompatibilityWireProtocol = m.codexCompatibilityWireProtocol;+ }if (m.icon !== undefined) sm.icon = m.icon;return sm;}),diff --git a/packages/model-providers/src/types.ts b/packages/model-providers/src/types.tsindex 5e6231d5f4..7f34943fef 100644--- a/packages/model-providers/src/types.ts+++ b/packages/model-providers/src/types.ts@@ -30,6 +30,12 @@ export type ProviderWireProtocol =| 'openai-responses'| 'openai-chat';+/** Codex 通过本地 bridge 兼容的两种非原生 Responses wire protocol。 */+export type CodexCompatibilityWireProtocol = Extract<+ ProviderWireProtocol,+ 'anthropic-messages' | 'openai-chat'+>;+/** 供应商来源:内置 vs 用户自定义(自定义本轮不实现,类型先留位)。 */export type ProviderSource = 'builtin' | 'user';@@ -56,7 +62,8 @@ export type ProviderAccess =* 是否透传 chatgpt-account-id)由该 runtime 的代理实现,本字段只表达意图:* - oauth-passthrough : 直连供应商自家上游,透传二进制已带的 OAuth bearer。* - provider-oauth-header : 直连供应商自家上游,但用 host 保存的该供应商 OAuth token- * 覆盖 Authorization;用于子进程 OAuth 不属于目标供应商的场景(如 Codex → xAI)。+ * 覆盖 Authorization;用于子进程 OAuth 不属于目标供应商的场景+ * (如 Codex → xAI / Claude.ai subscription)。* - api-key-header : 直连供应商自家上游,用该供应商自己的 API key 覆盖鉴权头。* - gateway-key : 走 XD 共享网关,把鉴权头换成网关 key。* - oauth-token : 直连供应商自家上游,用 host 侧通用 OAuth Runner 持有的@@ -136,7 +143,8 @@ export type OAuthProviderDescriptor =export interface RoutingDescriptor {/*** 上游 wire protocol。缺省按 agent 保持历史语义:Claude Code = anthropic-messages,- * Codex = openai-responses。只有显式 openai-chat 才进入本地 Responses→Chat bridge。+ * Codex = openai-responses。Codex 的 openai-chat / anthropic-messages 会分别进入+ * 对应的本地 Responses bridge。*/wireProtocol?: ProviderWireProtocol;/** 真实上游 base URL(direct 时是供应商自家;gateway 时是 XD 网关 base)。 */@@ -278,6 +286,16 @@ export interface CatalogModel {* 不能读跨 provider 拍平去重后的列表(那只保留首个 provider 的值,会错)。*/supportsFastMode?: boolean;+ /**+ * 该模型在 Codex 下使用的模型级兼容 bridge 协议。+ *+ * 通常 wire protocol 由 Provider.routing.codex 决定;只有同一 Provider 内不同模型+ * 需要走不同 Codex wire 时才写本字段。典型是 XD:服务端原生声明 Codex 的模型走+ * Responses,只声明 Claude Code 的模型投影进 Codex 后走 Anthropic Messages bridge。+ *+ * 这是按 agent 嵌套的目录元数据,不代表模型能力;缺省时回落 Provider 级路由。+ */+ codexCompatibilityWireProtocol?: CodexCompatibilityWireProtocol;/*** 展示图标 id —— 模型行 / composer 药丸上显示什么图标,**以 AI Gateway / 目录设定为准*** (XD 模型经 model-access-server GET /models 下发,其它供应商可由 OSS 目录配置)。diff --git a/packages/responses-anthropic-bridge/eslint.config.mjs b/packages/responses-anthropic-bridge/eslint.config.mjsnew file mode 100644index 0000000000..d599395947--- /dev/null+++ b/packages/responses-anthropic-bridge/eslint.config.mjs@@ -0,0 +1,10 @@+import js from '@eslint/js';+import tseslint from 'typescript-eslint';++export default tseslint.config(+ {+ ignores: ['dist/**'],+ },+ js.configs.recommended,+ ...tseslint.configs.recommended,+);diff --git a/packages/responses-anthropic-bridge/package.json b/packages/responses-anthropic-bridge/package.jsonnew file mode 100644index 0000000000..2a565aa92d--- /dev/null+++ b/packages/responses-anthropic-bridge/package.json@@ -0,0 +1,31 @@+{+ "name": "@cindy/responses-anthropic-bridge",+ "version": "0.0.0",+ "private": true,+ "description": "In-process bridge that translates OpenAI Responses requests and events to and from Anthropic Messages compatible providers.",+ "type": "module",+ "main": "./src/index.ts",+ "types": "./src/index.ts",+ "exports": {+ ".": "./src/index.ts"+ },+ "scripts": {+ "build": "tsc --noEmit",+ "typecheck": "tsc --noEmit",+ "test": "vitest run",+ "lint": "eslint src/"+ },+ "author": {+ "name": "XD Inc.",+ "email": "[email protected]"+ },+ "license": "Apache-2.0",+ "devDependencies": {+ "@eslint/js": "^9.0.0",+ "@types/node": "*",+ "eslint": "^9.0.0",+ "typescript": "^5.7.0",+ "typescript-eslint": "^8.0.0",+ "vitest": "^3.2.4"+ }+}diff --git a/packages/responses-anthropic-bridge/src/__tests__/anthropic-images.test.ts b/packages/responses-anthropic-bridge/src/__tests__/anthropic-images.test.tsnew file mode 100644index 0000000000..30a4a66c40--- /dev/null+++ b/packages/responses-anthropic-bridge/src/__tests__/anthropic-images.test.ts@@ -0,0 +1,138 @@+import { describe, expect, it, vi } from 'vitest';++import {+ enforceAnthropicImageLimits,+ MAX_INPUT_BASE64_LENGTH,+ normalizeAnthropicImages,+ requestHasInlineImage,+} from '../anthropic-images.js';++const tinyPng = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=';++describe('Anthropic image limits and normalization', () => {+ it('keeps the newest 20 images when many remote images have unknown dimensions', () => {+ const content = Array.from({ length: 21 }, (_, index) => ({+ type: 'image',+ source: { type: 'url', url: `https://example.com/${index}.png` },+ }));+ const messages = [{ role: 'user', content }];+ enforceAnthropicImageLimits(messages);+ expect(content[0]).toMatchObject({ type: 'text' });+ expect(content[20]).toMatchObject({ type: 'image' });+ });++ it('normalizes inline images through the injected codec and preserves image presence', async () => {+ const normalize = vi.fn(async () => ({ data: tinyPng, mediaType: 'image/png' }));+ const messages = [{+ role: 'user',+ content: [{ type: 'image', source: { type: 'base64', media_type: 'image/png', data: tinyPng } }],+ }];+ await normalizeAnthropicImages(messages, {+ codec: { normalize },+ });+ expect(normalize).toHaveBeenCalled();+ expect(requestHasInlineImage(messages)).toBe(true);+ });++ it('preserves supported inline images when the host has no native codec', async () => {+ const messages = [{+ role: 'user',+ content: [{ type: 'image', source: { type: 'base64', media_type: 'image/png', data: tinyPng } }],+ }];+ await normalizeAnthropicImages(messages);+ expect(messages[0].content[0]).toEqual({+ type: 'image',+ source: { type: 'base64', media_type: 'image/png', data: tinyPng },+ });+ });++ it('drops an inline image that exceeds the single-image base64 cap', () => {+ const messages = [{+ role: 'user',+ content: [{+ type: 'image',+ source: {+ type: 'base64',+ media_type: 'image/png',+ data: 'A'.repeat(5 * 1024 * 1024 + 1),+ },+ }],+ }];+ enforceAnthropicImageLimits(messages);+ expect(messages[0].content[0]).toMatchObject({ type: 'text' });+ });++ it('rejects oversized raw input before invoking the native codec', async () => {+ const normalize = vi.fn();+ const messages = [{+ role: 'user',+ content: [{+ type: 'image',+ source: {+ type: 'base64',+ media_type: 'image/png',+ data: 'A'.repeat(MAX_INPUT_BASE64_LENGTH + 1),+ },+ }],+ }];+ await normalizeAnthropicImages(messages, { codec: { normalize } });+ expect(normalize).not.toHaveBeenCalled();+ expect(messages[0].content[0]).toMatchObject({ type: 'text' });+ });++ it('serializes native normalization to bound concurrent decode memory', async () => {+ let active = 0;+ let peak = 0;+ const normalize = vi.fn(async () => {+ active += 1;+ peak = Math.max(peak, active);+ await Promise.resolve();+ active -= 1;+ return { data: tinyPng, mediaType: 'image/png' };+ });+ const messages = [{+ role: 'user',+ content: Array.from({ length: 4 }, () => ({+ type: 'image',+ source: { type: 'base64', media_type: 'image/png', data: tinyPng },+ })),+ }];+ await normalizeAnthropicImages(messages, { codec: { normalize } });+ expect(normalize).toHaveBeenCalledTimes(4);+ expect(peak).toBe(1);+ });++ it('serializes native normalization across concurrent requests sharing one codec', async () => {+ let active = 0;+ let peak = 0;+ let releaseFirst!: () => void;+ const firstBlocked = new Promise<void>((resolve) => {+ releaseFirst = resolve;+ });+ const normalize = vi.fn(async () => {+ active += 1;+ peak = Math.max(peak, active);+ if (normalize.mock.calls.length === 1) await firstBlocked;+ active -= 1;+ return { data: tinyPng, mediaType: 'image/png' };+ });+ const codec = { normalize };+ const messages = () => [{+ role: 'user',+ content: [{+ type: 'image',+ source: { type: 'base64', media_type: 'image/png', data: tinyPng },+ }],+ }];++ const first = normalizeAnthropicImages(messages(), { codec });+ await vi.waitFor(() => expect(normalize).toHaveBeenCalledTimes(1));+ const second = normalizeAnthropicImages(messages(), { codec });+ await Promise.resolve();+ expect(normalize).toHaveBeenCalledTimes(1);+ releaseFirst();+ await Promise.all([first, second]);+ expect(normalize).toHaveBeenCalledTimes(2);+ expect(peak).toBe(1);+ });+});diff --git a/packages/responses-anthropic-bridge/src/__tests__/handler.test.ts b/packages/responses-anthropic-bridge/src/__tests__/handler.test.tsnew file mode 100644index 0000000000..6eb77e0f78--- /dev/null+++ b/packages/responses-anthropic-bridge/src/__tests__/handler.test.ts@@ -0,0 +1,609 @@+import { EventEmitter } from 'node:events';++import { describe, expect, it, vi } from 'vitest';++import { createResponsesAnthropicHandler } from '../handler.js';++class FakeResponse extends EventEmitter {+ status = 0;+ headers: Record<string, string> = {};+ chunks: string[] = [];+ ended = false;+ headersSent = false;++ writeHead(status: number, headers: Record<string, string>): this {+ this.status = status;+ this.headers = headers;+ this.headersSent = true;+ return this;+ }++ write(chunk: string): boolean {+ this.chunks.push(chunk);+ return true;+ }++ end(chunk?: string): this {+ if (chunk) this.chunks.push(chunk);+ this.ended = true;+ return this;+ }+}++function anthropicStream(): Response {+ const body = [+ 'event: message_start',+ 'data: {"type":"message_start","message":{"id":"msg_1","model":"claude","usage":{"input_tokens":2}}}',+ '',+ 'event: content_block_start',+ 'data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}',+ '',+ 'event: content_block_delta',+ 'data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hello"}}',+ '',+ 'event: content_block_stop',+ 'data: {"type":"content_block_stop","index":0}',+ '',+ 'event: message_delta',+ 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}',+ '',+ 'event: message_stop',+ 'data: {"type":"message_stop"}',+ '',+ ].join('\n');+ return new Response(body, {+ status: 200,+ headers: { 'content-type': 'text/event-stream' },+ });+}++const ctx = {+ method: 'POST',+ url: 'http://127.0.0.1/responses',+ headers: {},+};++describe('createResponsesAnthropicHandler', () => {+ it('posts an Anthropic request and emits Responses SSE', async () => {+ const fetchImpl = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {+ const body = JSON.parse(String(init?.body));+ expect(body).toMatchObject({+ model: 'claude-sonnet-4-6',+ system: [{ type: 'text', text: 'be brief' }],+ messages: [{ role: 'user', content: [{ type: 'text', text: 'hello' }] }],+ max_tokens: 8192,+ stream: true,+ });+ expect((init?.headers as Record<string, string>)['x-api-key']).toBe('secret');+ expect((init?.headers as Record<string, string>)['anthropic-version']).toBe('2023-06-01');+ expect((init?.headers as Record<string, string>).accept).toBe('application/json');+ return anthropicStream();+ }) as typeof fetch;+ const handler = createResponsesAnthropicHandler({+ upstreamBase: 'https://provider.example',+ buildHeaders: async () => ({ 'x-api-key': 'secret' }),+ }, { fetchImpl });+ const res = new FakeResponse();+ await handler.handle({+ parsedBody: {+ model: 'claude-sonnet-4-6',+ instructions: 'be brief',+ input: [{ role: 'user', content: 'hello' }],+ },+ ctx,+ res: res as never,+ });+ expect(fetchImpl).toHaveBeenCalledWith('https://provider.example/v1/messages', expect.anything());+ expect(res.status).toBe(200);+ expect(res.chunks.join('')).toContain('event: response.output_text.delta');+ expect(res.chunks.join('')).toContain('event: response.completed');+ expect(res.chunks.join('')).toContain('"sequence_number":0');+ expect(res.ended).toBe(true);+ });++ it('normalizes provider header names before applying bridge-owned values', async () => {+ const fetchImpl = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {+ expect(init?.headers).toEqual({+ 'anthropic-version': 'custom-version',+ 'content-type': 'application/json',+ accept: 'application/json',+ 'x-api-key': 'secret',+ });+ return anthropicStream();+ }) as typeof fetch;+ const handler = createResponsesAnthropicHandler({+ upstreamBase: 'https://provider.example',+ buildHeaders: async () => ({+ 'Anthropic-Version': 'custom-version',+ 'Content-Type': 'text/plain',+ Accept: 'text/event-stream',+ 'X-Api-Key': 'secret',+ }),+ }, { fetchImpl });+ const res = new FakeResponse();+ await handler.handle({ parsedBody: { model: 'claude', input: 'hi' }, ctx, res: res as never });+ expect(fetchImpl).toHaveBeenCalledOnce();+ expect(res.status).toBe(200);+ });++ it('does not duplicate /v1 when a provider stores the versioned base URL', async () => {+ const fetchImpl = vi.fn(async () => anthropicStream()) as typeof fetch;+ const handler = createResponsesAnthropicHandler({+ upstreamBase: 'https://provider.example/v1/',+ buildHeaders: async () => ({}),+ }, { fetchImpl });+ const res = new FakeResponse();+ await handler.handle({ parsedBody: { model: 'claude', input: 'hi' }, ctx, res: res as never });+ expect(fetchImpl).toHaveBeenCalledWith('https://provider.example/v1/messages', expect.anything());+ });++ it('converts a non-streaming JSON provider response into Responses SSE', async () => {+ const fetchImpl = vi.fn(async () => new Response(JSON.stringify({+ id: 'msg_json',+ type: 'message',+ model: 'claude',+ content: [{ type: 'text', text: 'json' }],+ stop_reason: 'end_turn',+ usage: { input_tokens: 1, output_tokens: 1 },+ }), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ })) as typeof fetch;+ const handler = createResponsesAnthropicHandler({+ upstreamBase: 'https://provider.example',+ buildHeaders: async () => ({}),+ }, { fetchImpl });+ const res = new FakeResponse();+ await handler.handle({ parsedBody: { model: 'claude', input: 'hi' }, ctx, res: res as never });+ const wire = res.chunks.join('');+ expect(wire).toContain('event: response.output_text.delta');+ expect(wire).toContain('event: response.completed');+ });++ it('sniffs a complete JSON body for a streaming caller when Content-Type is wrong', async () => {+ const fetchImpl = vi.fn(async () => new Response(JSON.stringify({+ id: 'msg_stream_json',+ type: 'message',+ model: 'claude',+ content: [{ type: 'text', text: 'buffered JSON' }],+ stop_reason: 'end_turn',+ usage: { input_tokens: 1, output_tokens: 2 },+ }), {+ status: 200,+ headers: { 'content-type': 'text/plain' },+ })) as typeof fetch;+ const handler = createResponsesAnthropicHandler({+ upstreamBase: 'https://provider.example',+ buildHeaders: async () => ({}),+ }, { fetchImpl });+ const res = new FakeResponse();+ await handler.handle({ parsedBody: { model: 'claude', input: 'hi' }, ctx, res: res as never });+ const wire = res.chunks.join('');+ expect(wire).toContain('event: response.output_text.delta');+ expect(wire).toContain('"delta":"buffered JSON"');+ expect(wire).toContain('event: response.completed');+ expect(wire).not.toContain('stream_truncated');+ });++ it('preserves an unmarked JSON error envelope for a streaming caller', async () => {+ const fetchImpl = vi.fn(async () => new Response(JSON.stringify({+ type: 'error',+ error: { type: 'overloaded_error', message: 'busy' },+ }), { status: 200 })) as typeof fetch;+ const handler = createResponsesAnthropicHandler({+ upstreamBase: 'https://provider.example',+ buildHeaders: async () => ({}),+ }, { fetchImpl });+ const res = new FakeResponse();+ await handler.handle({ parsedBody: { model: 'claude', input: 'hi' }, ctx, res: res as never });+ const wire = res.chunks.join('');+ expect(wire).toContain('event: response.failed');+ expect(wire).toContain('busy');+ expect(wire).not.toContain('stream_truncated');+ });++ it('maps a bodyless successful upstream response to a 502 bridge error', async () => {+ const fetchImpl = vi.fn(async () => new Response(null, { status: 204 })) as typeof fetch;+ const handler = createResponsesAnthropicHandler({+ upstreamBase: 'https://provider.example',+ buildHeaders: async () => ({}),+ }, { fetchImpl });+ const res = new FakeResponse();+ await handler.handle({ parsedBody: { model: 'claude', input: 'hi' }, ctx, res: res as never });+ expect(res.status).toBe(502);+ expect(res.chunks.join('')).toContain('upstream_empty_response');+ });++ it('uses the SSE event name when the data object omits type', async () => {+ const body = [+ 'event: message_start',+ 'data: {"message":{"id":"msg_event_name","model":"claude"}}',+ '',+ 'event: content_block_start',+ 'data: {"index":0,"content_block":{"type":"text","text":""}}',+ '',+ 'event: content_block_delta',+ 'data: {"index":0,"delta":{"type":"text_delta","text":"fallback"}}',+ '',+ 'event: content_block_stop',+ 'data: {"index":0}',+ '',+ 'event: message_delta',+ 'data: {"delta":{"stop_reason":"end_turn"}}',+ '',+ 'event: message_stop',+ 'data: {}',+ '',+ ].join('\n');+ const fetchImpl = vi.fn(async () => new Response(body, {+ status: 200,+ headers: { 'content-type': 'text/event-stream' },+ })) as typeof fetch;+ const handler = createResponsesAnthropicHandler({+ upstreamBase: 'https://provider.example',+ buildHeaders: async () => ({}),+ }, { fetchImpl });+ const res = new FakeResponse();+ await handler.handle({ parsedBody: { model: 'claude', input: 'hi' }, ctx, res: res as never });+ const wire = res.chunks.join('');+ expect(wire).toContain('"delta":"fallback"');+ expect(wire).toContain('event: response.completed');+ });++ it('returns a JSON Responses object when the caller requests stream:false', async () => {+ const fetchImpl = vi.fn(async () => new Response(JSON.stringify({+ id: 'msg_json_non_stream',+ type: 'message',+ model: 'claude',+ content: [{ type: 'text', text: 'json' }],+ stop_reason: 'end_turn',+ usage: { input_tokens: 1, output_tokens: 1 },+ }), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ })) as typeof fetch;+ const handler = createResponsesAnthropicHandler({+ upstreamBase: 'https://provider.example',+ buildHeaders: async () => ({}),+ }, { fetchImpl });+ const res = new FakeResponse();+ await handler.handle({+ parsedBody: { model: 'claude', stream: false, input: 'hi' },+ ctx,+ res: res as never,+ });+ expect(res.headers['content-type']).toContain('application/json');+ const body = JSON.parse(res.chunks.join('')) as { object: string; status: string };+ expect(body.object).toBe('response');+ expect(body.status).toBe('completed');+ });++ it('sniffs an unmarked JSON body for a non-streaming caller', async () => {+ const fetchImpl = vi.fn(async () => new Response(JSON.stringify({+ id: 'msg_unmarked_json',+ type: 'message',+ model: 'claude',+ content: [{ type: 'text', text: 'json without a content type' }],+ stop_reason: 'end_turn',+ usage: { input_tokens: 1, output_tokens: 1 },+ }), { status: 200 })) as typeof fetch;+ const handler = createResponsesAnthropicHandler({+ upstreamBase: 'https://provider.example',+ buildHeaders: async () => ({}),+ }, { fetchImpl });+ const res = new FakeResponse();+ await handler.handle({+ parsedBody: { model: 'claude', stream: false, input: 'hi' },+ ctx,+ res: res as never,+ });+ const body = JSON.parse(res.chunks.join('')) as {+ status: string;+ output: Array<{ content?: Array<{ text?: string }> }>;+ };+ expect(body.status).toBe('completed');+ expect(body.output[0]?.content?.[0]?.text).toBe('json without a content type');+ });++ it('cancels an oversized unmarked body before buffering it for a non-streaming caller', async () => {+ let cancelled = false;+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(new TextEncoder().encode('x'.repeat(1024 * 1024 + 1)));+ },+ cancel() {+ cancelled = true;+ },+ });+ const fetchImpl = vi.fn(async () => new Response(stream, { status: 200 })) as typeof fetch;+ const handler = createResponsesAnthropicHandler({+ upstreamBase: 'https://provider.example',+ buildHeaders: async () => ({}),+ }, { fetchImpl });+ const res = new FakeResponse();+ await handler.handle({+ parsedBody: { model: 'claude', stream: false, input: 'hi' },+ ctx,+ res: res as never,+ });+ expect(cancelled).toBe(true);+ expect(res.status).toBe(502);+ expect(res.chunks.join('')).toContain('upstream response exceeds 1 MiB');+ });++ it('counts UTF-8 bytes and cancels an oversized unmarked streaming frame', async () => {+ let cancelled = false;+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(new TextEncoder().encode('你'.repeat(350_000)));+ },+ cancel() {+ cancelled = true;+ },+ });+ const fetchImpl = vi.fn(async () => new Response(stream, { status: 200 })) as typeof fetch;+ const handler = createResponsesAnthropicHandler({+ upstreamBase: 'https://provider.example',+ buildHeaders: async () => ({}),+ }, { fetchImpl });+ const res = new FakeResponse();+ await handler.handle({+ parsedBody: { model: 'claude', input: 'hi' },+ ctx,+ res: res as never,+ });+ expect(cancelled).toBe(true);+ expect(res.chunks.join('')).toContain('event: response.failed');+ expect(res.chunks.join('')).toContain('upstream SSE frame exceeds 1 MiB');+ });++ it('retries one OAuth request after a provider 401 with refreshed headers', async () => {+ const fetchMock = vi.fn()+ .mockResolvedValueOnce(new Response('expired', { status: 401 }))+ .mockResolvedValueOnce(anthropicStream());+ const fetchImpl = fetchMock as unknown as typeof fetch;+ const refreshHeaders = vi.fn(async () => ({ authorization: 'Bearer fresh' }));+ const handler = createResponsesAnthropicHandler({+ upstreamBase: 'https://provider.example',+ authMode: 'oauth',+ buildHeaders: async () => ({ authorization: 'Bearer stale' }),+ refreshHeaders,+ }, { fetchImpl });+ const res = new FakeResponse();+ await handler.handle({ parsedBody: { model: 'claude', input: 'hi' }, ctx, res: res as never });+ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(refreshHeaders).toHaveBeenCalledTimes(1);+ const second = fetchMock.mock.calls[1]?.[1] as RequestInit;+ expect((second.headers as Record<string, string>).authorization).toBe('Bearer fresh');+ expect(res.status).toBe(200);+ });++ it('refreshes provider OAuth even when Claude request policy uses API-key mode', async () => {+ const fetchMock = vi.fn()+ .mockResolvedValueOnce(new Response('expired', { status: 401 }))+ .mockResolvedValueOnce(anthropicStream());+ const fetchImpl = fetchMock as unknown as typeof fetch;+ const refreshHeaders = vi.fn(async () => ({ authorization: 'Bearer fresh' }));+ const handler = createResponsesAnthropicHandler({+ upstreamBase: 'https://provider.example',+ authMode: 'api-key',+ buildHeaders: async () => ({ authorization: 'Bearer stale' }),+ refreshHeaders,+ }, { fetchImpl });+ const res = new FakeResponse();+ await handler.handle({ parsedBody: { model: 'claude', input: 'hi' }, ctx, res: res as never });+ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(refreshHeaders).toHaveBeenCalledTimes(1);+ const second = fetchMock.mock.calls[1]?.[1] as RequestInit;+ expect((second.headers as Record<string, string>).authorization).toBe('Bearer fresh');+ expect(res.status).toBe(200);+ });++ it('retries one 413 request with a lower image normalization tier', async () => {+ const maxEdges: number[] = [];+ const fetchMock = vi.fn()+ .mockResolvedValueOnce(new Response('too large', { status: 413 }))+ .mockResolvedValueOnce(anthropicStream());+ const fetchImpl = fetchMock as unknown as typeof fetch;+ const handler = createResponsesAnthropicHandler({+ upstreamBase: 'https://provider.example',+ buildHeaders: async () => ({}),+ imageCodec: {+ normalize: async ({ maxEdge }) => {+ maxEdges.push(maxEdge);+ return { data: 'abc', mediaType: 'image/png' };+ },+ },+ }, { fetchImpl });+ const res = new FakeResponse();+ await handler.handle({+ parsedBody: {+ model: 'claude',+ input: [{ role: 'user', content: [{ type: 'input_image', image_url: 'data:image/png;base64,abc' }] }],+ },+ ctx,+ res: res as never,+ });+ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(maxEdges[0]).toBe(2000);+ expect(maxEdges).toContain(1024);+ });++ it('cancels an oversized 413 body before retrying image normalization', async () => {+ let cancelled = false;+ const oversizedBody = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(new TextEncoder().encode('x'.repeat(16 * 1024 + 1)));+ },+ cancel() {+ cancelled = true;+ },+ });+ const fetchMock = vi.fn()+ .mockResolvedValueOnce(new Response(oversizedBody, { status: 413 }))+ .mockResolvedValueOnce(anthropicStream());+ const handler = createResponsesAnthropicHandler({+ upstreamBase: 'https://provider.example',+ buildHeaders: async () => ({}),+ imageCodec: {+ normalize: async () => ({ data: 'abc', mediaType: 'image/png' }),+ },+ }, { fetchImpl: fetchMock as unknown as typeof fetch });+ const res = new FakeResponse();+ await handler.handle({+ parsedBody: {+ model: 'claude',+ input: [{+ role: 'user',+ content: [{ type: 'input_image', image_url: 'data:image/png;base64,abc' }],+ }],+ },+ ctx,+ res: res as never,+ });+ expect(cancelled).toBe(true);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(res.status).toBe(200);+ });++ it('keeps refreshed OAuth headers across a following image-size retry', async () => {+ const fetchMock = vi.fn()+ .mockResolvedValueOnce(new Response('expired', { status: 401 }))+ .mockResolvedValueOnce(new Response('too large', { status: 413 }))+ .mockResolvedValueOnce(anthropicStream());+ const buildHeaders = vi.fn(async () => ({ authorization: 'Bearer stale' }));+ const handler = createResponsesAnthropicHandler({+ upstreamBase: 'https://provider.example',+ authMode: 'oauth',+ buildHeaders,+ refreshHeaders: async () => ({ authorization: 'Bearer fresh' }),+ imageCodec: {+ normalize: async () => ({ data: 'abc', mediaType: 'image/png' }),+ },+ }, { fetchImpl: fetchMock as unknown as typeof fetch });+ const res = new FakeResponse();+ await handler.handle({+ parsedBody: {+ model: 'claude',+ input: [{+ role: 'user',+ content: [{ type: 'input_image', image_url: 'data:image/png;base64,abc' }],+ }],+ },+ ctx,+ res: res as never,+ });+ expect(fetchMock).toHaveBeenCalledTimes(3);+ expect(buildHeaders).toHaveBeenCalledTimes(1);+ for (const call of fetchMock.mock.calls.slice(1)) {+ const init = call[1] as RequestInit;+ expect((init.headers as Record<string, string>).authorization).toBe('Bearer fresh');+ }+ expect(res.status).toBe(200);+ });++ it('returns a Responses error for unsupported file_id images before fetch', async () => {+ const fetchImpl = vi.fn() as unknown as typeof fetch;+ const handler = createResponsesAnthropicHandler({+ upstreamBase: 'https://provider.example',+ buildHeaders: async () => ({}),+ }, { fetchImpl });+ const res = new FakeResponse();+ await handler.handle({+ parsedBody: {+ model: 'claude',+ input: [{ role: 'user', content: [{ type: 'input_image', file_id: 'file_1' }] }],+ },+ ctx,+ res: res as never,+ });+ expect(res.status).toBe(400);+ expect(res.chunks.join('')).toContain('unsupported_feature');+ expect(fetchImpl).not.toHaveBeenCalled();+ });++ it('distinguishes invalid tool requests from unsupported bridge features', async () => {+ const fetchImpl = vi.fn() as unknown as typeof fetch;+ const handler = createResponsesAnthropicHandler({+ upstreamBase: 'https://provider.example',+ buildHeaders: async () => ({}),+ }, { fetchImpl });+ const res = new FakeResponse();+ await handler.handle({+ parsedBody: {+ model: 'claude',+ input: 'hi',+ stop: [123],+ },+ ctx,+ res: res as never,+ });+ expect(res.status).toBe(400);+ expect(res.chunks.join('')).toContain('"code":"invalid_request"');+ expect(fetchImpl).not.toHaveBeenCalled();+ });++ it('rejects Responses sampling values outside the Anthropic range before fetch', async () => {+ const fetchImpl = vi.fn() as unknown as typeof fetch;+ const handler = createResponsesAnthropicHandler({+ upstreamBase: 'https://provider.example',+ buildHeaders: async () => ({}),+ }, { fetchImpl });+ const res = new FakeResponse();+ await handler.handle({+ parsedBody: {+ model: 'claude',+ input: 'hi',+ reasoning: { effort: 'none' },+ temperature: 1.5,+ },+ ctx,+ res: res as never,+ });+ expect(res.status).toBe(400);+ expect(res.chunks.join('')).toContain('"code":"invalid_request"');+ expect(res.chunks.join('')).toContain('temperature must be between 0 and 1');+ expect(fetchImpl).not.toHaveBeenCalled();+ });++ it('maps upstream HTTP errors without leaking request credentials', async () => {+ const onUpstreamError = vi.fn();+ const fetchImpl = vi.fn(async () => new Response('bad key', { status: 401 })) as typeof fetch;+ const handler = createResponsesAnthropicHandler({+ upstreamBase: 'https://provider.example',+ buildHeaders: async () => ({ authorization: 'Bearer secret' }),+ onUpstreamError,+ }, { fetchImpl });+ const res = new FakeResponse();+ await handler.handle({ parsedBody: { model: 'claude', input: 'hi' }, ctx, res: res as never });+ expect(res.status).toBe(401);+ expect(res.chunks.join('')).toContain('authentication_error');+ expect(onUpstreamError).toHaveBeenCalledWith(expect.objectContaining({ status: 401, body: 'bad key' }));+ });++ it('cancels and truncates an oversized upstream error body', async () => {+ let cancelled = false;+ const stream = new ReadableStream<Uint8Array>({+ start(controller) {+ controller.enqueue(new TextEncoder().encode(`bad key:${'x'.repeat(16 * 1024 + 1)}`));+ },+ cancel() {+ cancelled = true;+ },+ });+ const onUpstreamError = vi.fn();+ const fetchImpl = vi.fn(async () => new Response(stream, { status: 401 })) as typeof fetch;+ const handler = createResponsesAnthropicHandler({+ upstreamBase: 'https://provider.example',+ buildHeaders: async () => ({}),+ onUpstreamError,+ }, { fetchImpl });+ const res = new FakeResponse();+ await handler.handle({ parsedBody: { model: 'claude', input: 'hi' }, ctx, res: res as never });+ expect(cancelled).toBe(true);+ expect(res.status).toBe(401);+ const body = onUpstreamError.mock.calls[0]?.[0]?.body as string;+ expect(new TextEncoder().encode(body).byteLength).toBe(16 * 1024);+ expect(res.chunks.join('').length).toBeLessThan(17 * 1024);+ });+});diff --git a/packages/responses-anthropic-bridge/src/__tests__/responses-sse-translator.test.ts b/packages/responses-anthropic-bridge/src/__tests__/responses-sse-translator.test.tsnew file mode 100644index 0000000000..0bdfda85ed--- /dev/null+++ b/packages/responses-anthropic-bridge/src/__tests__/responses-sse-translator.test.ts@@ -0,0 +1,418 @@+import { describe, expect, it } from 'vitest';++import { AnthropicSseTranslator } from '../responses-sse-translator.js';+import { encodeThinkingBlock } from '../translate-request.js';++function translator() {+ return new AnthropicSseTranslator('claude', {+ byWireName: new Map([[+ 'mcp__read',+ { wireName: 'mcp__read', name: 'read', namespace: 'mcp', kind: 'namespace' },+ ]]),+ byResponseName: new Map(),+ });+}++describe('Anthropic SSE → Responses translation', () => {+ it('emits the Responses lifecycle, text deltas, and sequence-compatible events', () => {+ const t = translator();+ const events = [+ ...t.push({ type: 'message_start', message: { id: 'msg_1', model: 'claude', usage: { input_tokens: 5 } } }),+ ...t.push({ type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }),+ ...t.push({ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'Hello' } }),+ ...t.push({ type: 'content_block_stop', index: 0 }),+ ...t.push({ type: 'message_delta', delta: { stop_reason: 'end_turn' }, usage: { output_tokens: 2 } }),+ ...t.push({ type: 'message_stop' }),+ ];+ expect(events).toEqual(expect.arrayContaining([+ expect.objectContaining({ type: 'response.created' }),+ expect.objectContaining({ type: 'response.output_text.delta', delta: 'Hello' }),+ expect.objectContaining({ type: 'response.completed' }),+ ]));+ const completed = events.find((event) => (event as { type?: string }).type === 'response.completed') as { response: Record<string, unknown> };+ expect(completed.response.status).toBe('completed');+ expect((completed.response.usage as Record<string, unknown>).input_tokens).toBe(5);+ });++ it('maps tool_use to a namespaced function_call and keeps start-carried input', () => {+ const t = translator();+ const events = [+ ...t.push({ type: 'message_start', message: { id: 'msg_tool', model: 'claude' } }),+ ...t.push({+ type: 'content_block_start',+ index: 0,+ content_block: { type: 'tool_use', id: 'call_1', name: 'mcp__read', input: { path: 'a' } },+ }),+ ...t.push({ type: 'content_block_stop', index: 0 }),+ ...t.push({ type: 'message_delta', delta: { stop_reason: 'tool_use' } }),+ ...t.push({ type: 'message_stop' }),+ ];+ const done = events.find((event) => (+ (event as { type?: string }).type === 'response.output_item.done'+ && (event as { item?: { type?: string } }).item?.type === 'function_call'+ )) as { item: Record<string, unknown> };+ expect(done.item).toMatchObject({+ type: 'function_call',+ name: 'read',+ namespace: 'mcp',+ arguments: '{"path":"a"}',+ });+ });++ it('restores custom tool input from the compatibility wrapper', () => {+ const t = new AnthropicSseTranslator('claude', {+ byWireName: new Map([[+ 'apply_patch',+ { wireName: 'apply_patch', name: 'apply_patch', kind: 'custom' },+ ]]),+ byResponseName: new Map(),+ });+ const events = [+ ...t.push({ type: 'message_start', message: { id: 'msg_custom', model: 'claude' } }),+ ...t.push({+ type: 'content_block_start',+ index: 0,+ content_block: {+ type: 'tool_use',+ id: 'call_custom',+ name: 'apply_patch',+ },+ }),+ ...t.push({+ type: 'content_block_delta',+ index: 0,+ delta: {+ type: 'input_json_delta',+ partial_json: '{"input":"*** Begin Patch"}',+ },+ }),+ ...t.push({ type: 'content_block_stop', index: 0 }),+ ...t.push({ type: 'message_delta', delta: { stop_reason: 'tool_use' } }),+ ...t.push({ type: 'message_stop' }),+ ];+ const done = events.find((event) => (+ (event as { type?: string }).type === 'response.output_item.done'+ && (event as { item?: { type?: string } }).item?.type === 'custom_tool_call'+ )) as { item: Record<string, unknown> };+ expect(done.item).toMatchObject({+ type: 'custom_tool_call',+ input: '*** Begin Patch',+ });+ expect(events).toContainEqual(expect.objectContaining({+ type: 'response.custom_tool_call_input.done',+ input: '*** Begin Patch',+ }));+ expect(events.some((event) => (+ (event as { type?: string }).type === 'response.custom_tool_call_input.delta'+ ))).toBe(false);+ });++ it('restores tool_search with the Responses object shape and no function-call deltas', () => {+ const t = new AnthropicSseTranslator('claude', {+ byWireName: new Map([[+ 'tool_search',+ { wireName: 'tool_search', name: 'tool_search', kind: 'tool_search' },+ ]]),+ byResponseName: new Map(),+ });+ const events = [+ ...t.push({ type: 'message_start', message: { id: 'msg_search', model: 'claude' } }),+ ...t.push({+ type: 'content_block_start',+ index: 0,+ content_block: { type: 'tool_use', id: 'search_1', name: 'tool_search' },+ }),+ ...t.push({+ type: 'content_block_delta',+ index: 0,+ delta: {+ type: 'input_json_delta',+ partial_json: '{"query":"bridge tests","limit":3}',+ },+ }),+ ...t.push({ type: 'content_block_stop', index: 0 }),+ ...t.push({ type: 'message_delta', delta: { stop_reason: 'tool_use' } }),+ ...t.push({ type: 'message_stop' }),+ ];+ const done = events.find((event) => (+ (event as { type?: string }).type === 'response.output_item.done'+ && (event as { item?: { type?: string } }).item?.type === 'tool_search_call'+ )) as { item: Record<string, unknown> };+ expect(done.item).toMatchObject({+ type: 'tool_search_call',+ call_id: 'search_1',+ execution: 'client',+ status: 'completed',+ arguments: { query: 'bridge tests', limit: 3 },+ });+ expect(done.item).not.toHaveProperty('name');+ expect(events.some((event) => (+ (event as { type?: string }).type === 'response.function_call_arguments.delta'+ || (event as { type?: string }).type === 'response.function_call_arguments.done'+ ))).toBe(false);+ });++ it('drops an empty pages argument from the Read tool after streaming completes', () => {+ const t = new AnthropicSseTranslator('claude', {+ byWireName: new Map([[+ 'custom_Read',+ { wireName: 'custom_Read', name: 'Read', kind: 'function' },+ ]]),+ byResponseName: new Map(),+ });+ const events = [+ ...t.push({ type: 'message_start', message: { id: 'msg_read', model: 'claude' } }),+ ...t.push({+ type: 'content_block_start',+ index: 0,+ content_block: { type: 'tool_use', id: 'call_read', name: 'custom_Read' },+ }),+ ...t.push({+ type: 'content_block_delta',+ index: 0,+ delta: {+ type: 'input_json_delta',+ partial_json: '{"file_path":"/tmp/a","pages":""}',+ },+ }),+ ...t.push({ type: 'content_block_stop', index: 0 }),+ ...t.push({ type: 'message_stop' }),+ ];+ expect(events).toContainEqual(expect.objectContaining({+ type: 'response.function_call_arguments.done',+ arguments: '{"file_path":"/tmp/a"}',+ }));+ expect(events.some((event) => (+ (event as { type?: string }).type === 'response.function_call_arguments.delta'+ ))).toBe(false);+ });++ it('preserves pages for a user-defined tool that only shares the Read name', () => {+ const t = new AnthropicSseTranslator('claude', {+ byWireName: new Map([[+ 'custom_Read__user',+ { wireName: 'custom_Read__user', name: 'Read', kind: 'function' },+ ]]),+ byResponseName: new Map(),+ });+ const events = [+ ...t.push({ type: 'message_start', message: { id: 'msg_user_read', model: 'claude' } }),+ ...t.push({+ type: 'content_block_start',+ index: 0,+ content_block: { type: 'tool_use', id: 'call_user_read', name: 'custom_Read__user' },+ }),+ ...t.push({+ type: 'content_block_delta',+ index: 0,+ delta: {+ type: 'input_json_delta',+ partial_json: '{"file_path":"/tmp/a","pages":""}',+ },+ }),+ ...t.push({ type: 'content_block_stop', index: 0 }),+ ...t.push({ type: 'message_stop' }),+ ];+ expect(events).toContainEqual(expect.objectContaining({+ type: 'response.function_call_arguments.done',+ arguments: '{"file_path":"/tmp/a","pages":""}',+ }));+ });++ it('carries signed thinking in encrypted_content for the next request', () => {+ const t = translator();+ const events = [+ ...t.push({ type: 'message_start', message: { id: 'msg_reason', model: 'claude' } }),+ ...t.push({ type: 'content_block_start', index: 0, content_block: { type: 'thinking', thinking: '' } }),+ ...t.push({ type: 'content_block_delta', index: 0, delta: { type: 'thinking_delta', thinking: 'hmm' } }),+ ...t.push({ type: 'content_block_delta', index: 0, delta: { type: 'signature_delta', signature: 'sig_123456789' } }),+ ...t.push({ type: 'content_block_stop', index: 0 }),+ ...t.push({ type: 'message_stop' }),+ ];+ const done = events.find((event) => (+ (event as { type?: string }).type === 'response.output_item.done'+ && (event as { item?: { type?: string } }).item?.type === 'reasoning'+ )) as { item: Record<string, unknown> };+ expect(done.item.encrypted_content).toBe(encodeThinkingBlock({+ type: 'thinking',+ thinking: 'hmm',+ signature: 'sig_123456789',+ }));+ });++ it('treats reasoning blocks as reasoning in both streaming and JSON responses', () => {+ const streamed = translator();+ const streamEvents = [+ ...streamed.push({ type: 'message_start', message: { id: 'msg_reasoning', model: 'claude' } }),+ ...streamed.push({ type: 'content_block_start', index: 0, content_block: { type: 'reasoning' } }),+ ...streamed.push({+ type: 'content_block_delta',+ index: 0,+ delta: { type: 'reasoning_delta', reasoning: 'working' },+ }),+ ...streamed.push({ type: 'content_block_stop', index: 0 }),+ ...streamed.push({ type: 'message_stop' }),+ ];+ expect(streamEvents).toContainEqual(expect.objectContaining({+ type: 'response.reasoning_summary_text.delta',+ delta: 'working',+ }));+ expect(streamEvents.some((event) => (+ (event as { type?: string; item?: { type?: string } }).type === 'response.output_item.added'+ && (event as { item?: { type?: string } }).item?.type === 'message'+ ))).toBe(false);++ const jsonEvents = translator().pushJson({+ id: 'msg_reasoning_json',+ type: 'message',+ model: 'claude',+ content: [{ type: 'reasoning', reasoning: 'json reasoning' }],+ stop_reason: 'end_turn',+ });+ const jsonDone = jsonEvents.find((event) => (+ (event as { type?: string }).type === 'response.output_item.done'+ && (event as { item?: { type?: string } }).item?.type === 'reasoning'+ )) as { item: { summary: Array<{ text: string }> } };+ expect(jsonDone.item.summary).toEqual([{ type: 'summary_text', text: 'json reasoning' }]);+ });++ it('turns a JSON response into the same SSE lifecycle', () => {+ const events = new AnthropicSseTranslator('claude', {+ byWireName: new Map(),+ byResponseName: new Map(),+ }).pushJson({+ id: 'msg_json',+ type: 'message',+ model: 'claude',+ content: [{ type: 'text', text: 'json' }],+ stop_reason: 'end_turn',+ usage: { input_tokens: 3, output_tokens: 1 },+ });+ expect(events.some((event) => (event as { type?: string }).type === 'response.output_text.delta')).toBe(true);+ expect(events.some((event) => (event as { type?: string }).type === 'response.completed')).toBe(true);+ });++ it('keeps both thinking text and its signature when translating JSON', () => {+ const events = new AnthropicSseTranslator('claude', {+ byWireName: new Map(),+ byResponseName: new Map(),+ }).pushJson({+ id: 'msg_thinking_json',+ type: 'message',+ model: 'claude',+ content: [{+ type: 'thinking',+ thinking: 'hmm',+ signature: 'sig_123456789',+ }],+ stop_reason: 'end_turn',+ });+ const done = events.find((event) => (+ (event as { type?: string }).type === 'response.output_item.done'+ && (event as { item?: { type?: string } }).item?.type === 'reasoning'+ )) as { item: Record<string, unknown> };+ expect(done.item.encrypted_content).toBe(encodeThinkingBlock({+ type: 'thinking',+ thinking: 'hmm',+ signature: 'sig_123456789',+ }));+ });++ it('starts the Responses lifecycle before reporting an upstream error frame', () => {+ const events = new AnthropicSseTranslator('claude', {+ byWireName: new Map(),+ byResponseName: new Map(),+ }).push({ type: 'error', error: { message: 'bad request' } });+ expect(events.map((event) => (event as { type: string }).type)).toEqual([+ 'response.created',+ 'response.in_progress',+ 'response.failed',+ ]);+ });++ it('reports a stream that ends without a stop reason as failed while preserving partial output', () => {+ const t = translator();+ const events = [+ ...t.push({ type: 'message_start', message: { id: 'msg_partial', model: 'claude' } }),+ ...t.push({ type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }),+ ...t.push({ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'partial' } }),+ ...t.finish(),+ ];+ expect(events.some((event) => (event as { type?: string }).type === 'response.failed')).toBe(true);+ const terminal = events.find((event) => ['response.completed', 'response.incomplete', 'response.failed'].includes((event as { type?: string }).type ?? '')) as { response: { status: string } };+ expect(terminal.response.status).toBe('failed');+ expect(terminal.response).toMatchObject({+ error: {+ code: 'upstream_error',+ message: expect.stringContaining('stream_truncated'),+ },+ });+ const item = events.find((event) => (+ (event as { type?: string }).type === 'response.output_item.done'+ )) as { item: { status: string } };+ expect(item.item.status).toBe('incomplete');+ });++ it('reports max_tokens as incomplete even when the stream ends before message_stop', () => {+ const t = translator();+ const events = [+ ...t.push({ type: 'message_start', message: { id: 'msg_max_tokens', model: 'claude' } }),+ ...t.push({ type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }),+ ...t.push({ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'partial' } }),+ ...t.push({ type: 'message_delta', delta: { stop_reason: 'max_tokens' } }),+ ...t.finish(),+ ];+ const terminal = events.find((event) => (+ (event as { type?: string }).type === 'response.incomplete'+ )) as { response: { status: string; incomplete_details: { reason: string } } };+ expect(terminal.response).toMatchObject({+ status: 'incomplete',+ incomplete_details: { reason: 'max_output_tokens' },+ });+ expect(events.some((event) => (event as { type?: string }).type === 'response.failed')).toBe(false);+ });++ it('accepts reasoning_delta as an alias for thinking_delta', () => {+ const t = translator();+ t.push({ type: 'message_start', message: { id: 'msg_reasoning_delta', model: 'claude' } });+ t.push({ type: 'content_block_start', index: 0, content_block: { type: 'thinking' } });+ const events = t.push({+ type: 'content_block_delta',+ index: 0,+ delta: { type: 'reasoning_delta', reasoning: 'working' },+ });+ expect(events).toEqual(expect.arrayContaining([+ expect.objectContaining({+ type: 'response.reasoning_summary_text.delta',+ delta: 'working',+ }),+ ]));+ });++ it('does not mark a truncated tool call as completed', () => {+ const t = translator();+ const events = [+ ...t.push({ type: 'message_start', message: { id: 'msg_partial_tool', model: 'claude' } }),+ ...t.push({+ type: 'content_block_start',+ index: 0,+ content_block: { type: 'tool_use', id: 'call_1', name: 'mcp__read' },+ }),+ ...t.push({+ type: 'content_block_delta',+ index: 0,+ delta: { type: 'input_json_delta', partial_json: '{"path":' },+ }),+ ...t.finish(),+ ];+ expect(events.some((event) => (+ (event as { type?: string }).type === 'response.function_call_arguments.done'+ ))).toBe(false);+ expect(events.some((event) => (+ (event as { type?: string; item?: { status?: string } }).item?.status === 'incomplete'+ ))).toBe(true);+ expect(events.some((event) => (+ (event as { type?: string }).type === 'response.failed'+ ))).toBe(true);+ });+});diff --git a/packages/responses-anthropic-bridge/src/__tests__/translate-request.test.ts b/packages/responses-anthropic-bridge/src/__tests__/translate-request.test.tsnew file mode 100644index 0000000000..33a6836801--- /dev/null+++ b/packages/responses-anthropic-bridge/src/__tests__/translate-request.test.ts@@ -0,0 +1,959 @@+import { describe, expect, it } from 'vitest';++import {+ decodeThinkingBlock,+ encodeThinkingBlock,+ translateResponsesRequest,+} from '../translate-request.js';++describe('Responses → Anthropic request translation', () => {+ it('moves instructions/developer messages to system and preserves text/image order', () => {+ const result = translateResponsesRequest({+ model: 'claude-sonnet-4-6',+ instructions: 'system one',+ input: [+ { type: 'message', role: 'developer', content: [{ type: 'input_text', text: 'system two' }] },+ {+ type: 'message',+ role: 'user',+ content: [+ { type: 'input_text', text: 'look' },+ { type: 'input_image', image_url: 'data:image/png;base64,abc' },+ { type: 'input_text', text: 'at this' },+ ],+ },+ ],+ prompt_cache_key: 'session-1',+ });+ expect(result.request.system?.[0].text).toBe('system one\n\nsystem two');+ expect(result.request.messages[0]).toMatchObject({+ role: 'user',+ content: [+ { type: 'text', text: 'look' },+ { type: 'image', source: { type: 'base64', media_type: 'image/png', data: 'abc' } },+ { type: 'text', text: 'at this' },+ ],+ });+ expect(JSON.stringify(result.request)).not.toContain('prompt_cache_key');+ expect(JSON.stringify(result.request)).toContain('cache_control');+ });++ it('parses text and refusal content parts from top-level instructions', () => {+ const result = translateResponsesRequest({+ model: 'claude',+ instructions: [+ { type: 'input_text', text: 'system one' },+ { type: 'refusal', refusal: '\n\nsystem two' },+ ],+ input: 'hello',+ });+ expect(result.request.system?.[0].text).toBe('system one\n\nsystem two');++ expect(() => translateResponsesRequest({+ model: 'claude',+ instructions: [{ type: 'input_image', image_url: 'https://example.com/a.png' }],+ input: 'hello',+ })).toThrowError('instructions[0].input_image');+ });++ it('rejects structured-output constraints instead of silently dropping them', () => {+ expect(() => translateResponsesRequest({+ model: 'claude',+ input: 'hello',+ text: {+ format: {+ type: 'json_schema',+ name: 'answer',+ schema: { type: 'object', properties: { value: { type: 'string' } } },+ },+ },+ })).toThrowError('text.format');++ expect(() => translateResponsesRequest({+ model: 'claude',+ input: 'hello',+ response_format: { type: 'json_object' },+ })).toThrowError('response_format');++ expect(translateResponsesRequest({+ model: 'claude',+ input: 'hello',+ text: { format: { type: 'text' } },+ }).request.messages).toHaveLength(1);+ });++ it('flattens namespace tools and restores their mapping in the context', () => {+ const result = translateResponsesRequest({+ model: 'claude',+ input: [+ { type: 'function_call', call_id: 'c1', name: 'mcp_files__read', arguments: '{"path":"a"}' },+ { type: 'function_call_output', call_id: 'c1', output: 'ok' },+ ],+ tools: [{+ type: 'namespace',+ name: 'mcp_files',+ tools: [{ type: 'function', name: 'read', parameters: { type: 'object' } }],+ }],+ });+ expect(result.request.tools).toEqual([{+ name: 'mcp_files__read',+ input_schema: { type: 'object', properties: {} },+ }]);+ const assistant = result.request.messages.find((message) => message.role === 'assistant')!;+ expect((assistant.content as Array<Record<string, unknown>>)[0]).toMatchObject({+ type: 'tool_use',+ name: 'mcp_files__read',+ input: { path: 'a' },+ });+ expect(result.toolContext.byWireName.get('mcp_files__read')).toMatchObject({+ name: 'read',+ namespace: 'mcp_files',+ kind: 'namespace',+ });+ });++ it('round-trips signed and redacted thinking only through the provider envelope', () => {+ const thinking = { type: 'thinking', thinking: 'reason', signature: 'sig_1234567890' };+ const redacted = { type: 'redacted_thinking', data: 'opaque' };+ const thinkingEncoded = encodeThinkingBlock(thinking);+ const redactedEncoded = encodeThinkingBlock(redacted);+ expect(thinkingEncoded).toMatch(/^cindy-anthropic-thinking-v1:/);+ expect(decodeThinkingBlock(thinkingEncoded!)).toEqual(thinking);+ expect(decodeThinkingBlock(redactedEncoded!)).toEqual(redacted);+ expect(decodeThinkingBlock('other-provider:abc')).toBeNull();++ const result = translateResponsesRequest({+ model: 'claude-sonnet-5',+ max_output_tokens: 8192,+ reasoning: { effort: 'high' },+ input: [+ { type: 'reasoning', encrypted_content: thinkingEncoded },+ { type: 'function_call', call_id: 'c1', name: 'read', arguments: '{}' },+ { type: 'function_call_output', call_id: 'c1', output: 'ok' },+ ],+ });+ const assistant = result.request.messages.find((message) => message.role === 'assistant')!;+ expect((assistant.content as Array<Record<string, unknown>>)[0]).toEqual(thinking);+ expect(result.request.thinking).toEqual({ type: 'adaptive' });+ expect(result.request.output_config).toEqual({ effort: 'high' });+ });++ it('preserves tool-result images as Anthropic media blocks', () => {+ const result = translateResponsesRequest({+ model: 'claude',+ input: [+ { type: 'function_call', call_id: 'c1', name: 'inspect', arguments: '{}' },+ {+ type: 'function_call_output',+ call_id: 'c1',+ output: [+ { type: 'output_text', text: 'caption' },+ { type: 'input_image', image_url: 'https://example.com/a.png' },+ { type: 'image', mimeType: 'image/webp', data: 'mcp-bytes' },+ ],+ },+ ],+ });+ const resultMessage = result.request.messages.find((message) => (+ message.content as Array<Record<string, unknown>>+ ).some((block) => block.type === 'tool_result'))!;+ const resultContent = ((resultMessage.content as Array<Record<string, unknown>>)[0].content+ ?? []) as Array<Record<string, unknown>>;+ expect(resultContent).toEqual([+ { type: 'text', text: 'caption' },+ { type: 'image', source: { type: 'url', url: 'https://example.com/a.png' } },+ { type: 'image', source: { type: 'base64', media_type: 'image/webp', data: 'mcp-bytes' } },+ ]);+ });++ it('extracts nested MCP/Anthropic media serialized inside a tool result string', () => {+ const result = translateResponsesRequest({+ model: 'claude',+ input: [+ { type: 'function_call', call_id: 'c1', name: 'inspect', arguments: '{}' },+ {+ type: 'function_call_output',+ call_id: 'c1',+ output: JSON.stringify({+ content: [+ { type: 'text', text: 'caption' },+ {+ type: 'image',+ source: { type: 'base64', media_type: 'image/png', data: 'nested-png' },+ },+ ],+ }),+ },+ ],+ });+ const resultMessage = result.request.messages.find((message) => (+ (message.content as Array<Record<string, unknown>>)+ .some((block) => block.type === 'tool_result')+ ))!;+ expect((resultMessage.content as Array<Record<string, unknown>>)[0].content).toEqual([+ { type: 'text', text: 'caption' },+ {+ type: 'image',+ source: { type: 'base64', media_type: 'image/png', data: 'nested-png' },+ },+ ]);+ });++ it('adds tools loaded by tool_search_output and maps a tool_search choice', () => {+ const result = translateResponsesRequest({+ model: 'claude',+ tool_choice: { type: 'tool_search' },+ input: [+ {+ type: 'tool_search_output',+ tools: [{+ type: 'function',+ name: 'loaded_read',+ description: 'Read a loaded resource',+ parameters: { type: 'object', properties: { path: { type: 'string' } } },+ }],+ },+ { type: 'tool_search_call', call_id: 'search_1', name: 'tool_search', arguments: '{}' },+ { type: 'tool_search_output', call_id: 'search_1', output: 'loaded' },+ ],+ });+ expect(result.request.tools).toEqual(expect.arrayContaining([+ expect.objectContaining({ name: 'tool_search' }),+ expect.objectContaining({ name: 'loaded_read' }),+ ]));+ expect(result.request.tool_choice).toEqual({ type: 'tool', name: 'tool_search' });+ });++ it('preserves id-correlated tool_search outputs and serializes discovered tools', () => {+ const tools = [{+ type: 'function',+ name: 'loaded_read',+ parameters: { type: 'object' },+ }];+ const result = translateResponsesRequest({+ model: 'claude',+ input: [+ { type: 'tool_search_call', id: 'search_1' },+ { type: 'tool_search_output', id: 'search_1', tools },+ ],+ });+ expect(result.request.tools?.map((tool) => (tool as { name: string }).name)).toEqual(+ expect.arrayContaining(['tool_search', 'loaded_read']),+ );+ const resultMessage = result.request.messages.find((message) => (+ (message.content as Array<Record<string, unknown>>)+ .some((block) => block.type === 'tool_result')+ ))!;+ expect(resultMessage.content).toEqual([{+ type: 'tool_result',+ tool_use_id: 'search_1',+ content: JSON.stringify(tools),+ }]);+ });++ it('collects dynamic tool declarations only from top-level tool-search outputs', () => {+ const result = translateResponsesRequest({+ model: 'claude',+ tools: [{ type: 'function', name: 'inspect', parameters: { type: 'object' } }],+ input: [+ { type: 'function_call', call_id: 'c1', name: 'inspect', arguments: '{}' },+ {+ type: 'function_call_output',+ call_id: 'c1',+ output: {+ nestedSearch: {+ type: 'tool_search_output',+ tools: [{ type: 'function', name: 'injected_function' }],+ },+ },+ },+ { type: 'tool_search_call', id: 'search_1' },+ {+ type: 'tool_search_output',+ id: 'search_1',+ tools: [{ type: 'function', name: 'loaded_function' }],+ },+ ],+ });+ const names = result.request.tools?.map((tool) => (tool as { name: string }).name);+ expect(names).toEqual(expect.arrayContaining(['inspect', 'tool_search', 'loaded_function']));+ expect(names).not.toContain('injected_function');+ });++ it('keeps same-named function and custom tools distinct and reversible', () => {+ const result = translateResponsesRequest({+ model: 'claude',+ 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 = result.request.tools?.map((tool) => (tool as { name: string }).name) ?? [];+ const customWireName = (result.request.tool_choice as { name: string }).name;+ expect(toolNames).toHaveLength(2);+ expect(new Set(toolNames).size).toBe(2);+ expect(toolNames).toContain('shared');+ expect(customWireName).not.toBe('shared');+ const assistant = result.request.messages.find((message) => message.role === 'assistant')!;+ expect((assistant.content as Array<Record<string, unknown>>)[0]).toMatchObject({+ type: 'tool_use',+ name: customWireName,+ });+ expect(result.toolContext.byWireName.get(customWireName)?.kind).toBe('custom');+ });++ it('filters allowed_tools while preserving Anthropic auto/any semantics', () => {+ const result = translateResponsesRequest({+ model: 'claude',+ tool_choice: {+ type: 'allowed_tools',+ mode: 'required',+ tools: [{ type: 'function', name: 'keep' }],+ },+ input: [{ role: 'user', content: 'use the allowed tool' }],+ tools: [+ { type: 'function', name: 'keep', parameters: {} },+ { type: 'function', name: 'drop', parameters: {} },+ ],+ });+ expect(result.request.tools?.map((tool) => (tool as { name: string }).name)).toEqual(['keep']);+ expect(result.request.tool_choice).toEqual({ type: 'any' });+ });++ it('rejects a required tool choice when no bridge-compatible tools remain', () => {+ expect(() => translateResponsesRequest({+ model: 'claude',+ tool_choice: 'required',+ input: [{ role: 'user', content: 'search the web' }],+ tools: [{ type: 'web_search' }],+ })).toThrowError('tool_choice requires a bridge-compatible tool');++ expect(() => translateResponsesRequest({+ model: 'claude',+ tool_choice: {+ type: 'allowed_tools',+ mode: 'required',+ tools: [{ type: 'function', name: 'missing' }],+ },+ input: [{ role: 'user', content: 'use the missing tool' }],+ tools: [{ type: 'function', name: 'available', parameters: {} }],+ })).toThrowError('tool_choice requires a bridge-compatible tool');++ expect(() => translateResponsesRequest({+ model: 'claude',+ tool_choice: { type: 'web_search' },+ input: [{ role: 'user', content: 'search the web' }],+ tools: [{ type: 'web_search' }],+ })).toThrowError("tool_choice type 'web_search'");++ expect(() => translateResponsesRequest({+ model: 'claude',+ tool_choice: { type: 'web_search' },+ input: [{ role: 'user', content: 'search the web' }],+ tools: [{ type: 'function', name: 'local', parameters: {} }],+ })).toThrowError("tool_choice type 'web_search'");+ });++ it('keeps allowed_tools filtering specific to same-named tool kinds', () => {+ const result = translateResponsesRequest({+ model: 'claude',+ tool_choice: {+ type: 'allowed_tools',+ mode: 'required',+ tools: [{ type: 'custom', name: 'shared' }],+ },+ input: [{ role: 'user', content: 'use the custom tool' }],+ tools: [+ { type: 'function', name: 'shared', parameters: {} },+ { type: 'custom', name: 'shared' },+ ],+ });+ const tools = result.request.tools as Array<{ name: string }>;+ expect(tools).toHaveLength(1);+ expect(result.toolContext.byWireName.get(tools[0].name)?.kind).toBe('custom');+ expect(result.request.tool_choice).toEqual({ type: 'any' });+ });++ it('filters OAuth allowed_tools after applying the custom_ wire prefix', () => {+ const result = translateResponsesRequest({+ model: 'claude-sonnet-5',+ tool_choice: {+ type: 'allowed_tools',+ mode: 'auto',+ tools: [{ type: 'function', name: 'keep' }],+ },+ input: [{ role: 'user', content: 'use only the selected tool' }],+ tools: [+ { type: 'function', name: 'keep', parameters: {} },+ { type: 'function', name: 'drop', parameters: {} },+ ],+ }, { authMode: 'oauth' });+ expect(result.request.tools?.map((tool) => (tool as { name: string }).name)).toEqual([+ 'custom_keep',+ ]);+ expect(result.request.tool_choice).toEqual({ type: 'auto' });+ });++ it('accepts object-form image_url and preserves a namespaced call supplied with namespace', () => {+ const result = translateResponsesRequest({+ model: 'claude',+ input: [+ {+ role: 'user',+ content: [{+ type: 'input_image',+ image_url: { url: 'https://example.com/a.png', detail: 'high' },+ }],+ },+ {+ type: 'function_call',+ call_id: 'c1',+ namespace: 'mcp_files',+ name: 'read',+ arguments: '{}',+ },+ ],+ tools: [{+ type: 'namespace',+ name: 'mcp_files',+ tools: [{ type: 'function', name: 'read', parameters: { type: 'object' } }],+ }],+ });+ expect(result.request.messages[0].content).toEqual([{+ type: 'image',+ source: { type: 'url', url: 'https://example.com/a.png' },+ }]);+ expect((result.request.messages[1].content as Array<Record<string, unknown>>)[0]).toMatchObject({+ type: 'tool_use',+ name: 'mcp_files__read',+ });+ });++ it('rejects malformed input images instead of silently dropping them', () => {+ expect(() => translateResponsesRequest({+ model: 'claude',+ input: [{+ role: 'user',+ content: [{ type: 'input_image', image_url: '' }],+ }],+ })).toThrow('input_image.image_url');+ });++ it('normalizes missing tool results and assistant-tail history', () => {+ const result = translateResponsesRequest({+ model: 'claude',+ input: [+ { type: 'function_call', call_id: 'c1', name: 'run', arguments: '{}' },+ ],+ });+ expect(result.request.messages).toHaveLength(3);+ expect(result.request.messages[1].role).toBe('assistant');+ expect(result.request.messages[2].role).toBe('user');+ expect((result.request.messages[2].content as Array<Record<string, unknown>>)[0]).toMatchObject({+ type: 'tool_result',+ tool_use_id: 'c1',+ is_error: true,+ });+ });++ it('uses legacy thinking for older Claude and preserves the budget headroom invariant', () => {+ const result = translateResponsesRequest({+ model: 'claude-sonnet-4-6',+ max_output_tokens: 10000,+ reasoning: { effort: 'medium' },+ input: [{ role: 'user', content: 'hi' }],+ temperature: 0.2,+ top_p: 0.8,+ });+ expect(result.request.thinking).toEqual({ type: 'enabled', budget_tokens: 5904 });+ expect(result.request.temperature).toBeUndefined();+ expect(result.request.top_p).toBeUndefined();+ });++ it('keeps sampling fields when reasoning is explicitly disabled', () => {+ const result = translateResponsesRequest({+ model: 'claude-sonnet-4-6',+ reasoning: { effort: 'none' },+ input: [{ role: 'user', content: 'hi' }],+ temperature: 0.2,+ top_p: 0.8,+ });+ expect(result.request.thinking).toEqual({ type: 'disabled' });+ expect(result.request.temperature).toBe(0.2);+ expect(result.request.top_p).toBe(0.8);+ });++ it('rejects sampling values outside the Anthropic 0-1 range', () => {+ expect(() => translateResponsesRequest({+ model: 'claude-sonnet-4-6',+ reasoning: { effort: 'none' },+ input: [{ role: 'user', content: 'hi' }],+ temperature: 1.5,+ })).toThrow('Responses temperature must be between 0 and 1');++ expect(() => translateResponsesRequest({+ model: 'claude-sonnet-4-6',+ reasoning: { effort: 'none' },+ input: [{ role: 'user', content: 'hi' }],+ top_p: -0.1,+ })).toThrow('Responses top_p must be between 0 and 1');+ });++ it('maps Responses stop strings and arrays to Anthropic stop_sequences', () => {+ const single = translateResponsesRequest({+ model: 'claude',+ input: 'hi',+ stop: 'DONE',+ });+ expect(single.request.stop_sequences).toEqual(['DONE']);++ const multiple = translateResponsesRequest({+ model: 'claude',+ input: 'hi',+ stop: ['DONE', 'HALT'],+ });+ expect(multiple.request.stop_sequences).toEqual(['DONE', 'HALT']);+ });++ it('disables thinking when a forced tool choice must be preserved', () => {+ const result = translateResponsesRequest({+ model: 'claude-sonnet-5',+ reasoning: { effort: 'high' },+ input: [{ role: 'user', content: 'run the tool' }],+ tools: [{ type: 'function', name: 'run', parameters: { type: 'object' } }],+ tool_choice: { type: 'function', name: 'run' },+ });+ expect(result.request.tool_choice).toEqual({ type: 'tool', name: 'run' });+ expect(result.request.thinking).toEqual({ type: 'disabled' });+ expect(result.request.output_config).toBeUndefined();+ });++ it('does not enable thinking for an unsigned tool-result continuation', () => {+ const result = translateResponsesRequest({+ model: 'claude-sonnet-5',+ reasoning: { effort: 'high' },+ input: [+ { type: 'function_call', call_id: 'c1', name: 'run', arguments: '{}' },+ { type: 'function_call_output', call_id: 'c1', output: 'ok' },+ ],+ tools: [{ type: 'function', name: 'run', parameters: { type: 'object' } }],+ });+ expect(result.request.thinking).toEqual({ type: 'disabled' });+ expect(result.request.output_config).toBeUndefined();+ });++ it('applies the Claude Code identity and custom tool prefix only in OAuth mode', () => {+ const result = translateResponsesRequest({+ model: 'claude-sonnet-5',+ input: [+ { type: 'function_call', call_id: 'c1', name: 'run-command', arguments: '{}' },+ { type: 'function_call_output', call_id: 'c1', output: 'ok' },+ ],+ tools: [{ type: 'function', name: 'run-command', parameters: { type: 'object' } }],+ }, { authMode: 'oauth' });+ expect(result.request.system?.[0]).toEqual({+ type: 'text',+ text: "You are a Claude agent, built on Anthropic's Claude Agent SDK.",+ });+ expect(result.request.tools?.[0]).toMatchObject({ name: 'custom_run-command' });+ expect((result.request.messages[1].content as Array<Record<string, unknown>>)[0]).toMatchObject({+ type: 'tool_use',+ name: 'custom_run-command',+ });+ });++ it('models custom tools as free-form input and restores the raw input', () => {+ const request = translateResponsesRequest({+ model: 'claude',+ tools: [{ type: 'custom', name: 'apply_patch', description: 'Apply a patch' }],+ input: [+ { type: 'custom_tool_call', call_id: 'c1', name: 'apply_patch', input: '{"patch":true}' },+ { type: 'custom_tool_call_output', call_id: 'c1', output: 'ok' },+ ],+ });+ expect(request.request.tools?.[0]).toMatchObject({+ name: 'apply_patch',+ input_schema: {+ type: 'object',+ required: ['input'],+ properties: { input: { type: 'string' } },+ },+ });+ expect((request.request.messages[1].content as Array<Record<string, unknown>>)[0]).toMatchObject({+ type: 'tool_use',+ input: { input: '{"patch":true}' },+ });+ });++ it('preserves root tool-schema composition constraints', () => {+ const result = translateResponsesRequest({+ model: 'claude',+ input: 'open one location',+ tools: [{+ type: 'function',+ name: 'open',+ parameters: {+ oneOf: [+ {+ type: 'object',+ properties: { path: { type: 'string' } },+ required: ['path'],+ },+ {+ type: 'object',+ properties: { url: { type: 'string' } },+ required: ['url'],+ },+ ],+ },+ }],+ });+ expect(result.request.tools?.[0]).toMatchObject({+ input_schema: {+ type: 'object',+ properties: {},+ oneOf: [+ { required: ['path'] },+ { required: ['url'] },+ ],+ },+ });+ });++ it('preserves strict tool definitions only for capable upstreams and drops incomplete historical tool turns', () => {+ const result = translateResponsesRequest({+ model: 'claude',+ tools: [{+ type: 'function',+ name: 'read',+ strict: true,+ parameters: { type: 'object' },+ }],+ input: [+ {+ type: 'function_call',+ status: 'incomplete',+ call_id: 'bad',+ name: 'read',+ arguments: '{"path":',+ },+ { type: 'function_call_output', call_id: 'bad', output: 'partial' },+ { role: 'user', content: 'continue safely' },+ ],+ }, { strictTools: true });+ expect(result.request.tools?.[0]).toMatchObject({ name: 'read', strict: true });+ expect(JSON.stringify(result.request.messages)).not.toContain('bad');+ expect(JSON.stringify(result.request.messages)).not.toContain('partial');++ const compatibleGateway = translateResponsesRequest({+ model: 'claude',+ tools: [{+ type: 'function',+ name: 'read',+ strict: true,+ parameters: { type: 'object' },+ }],+ input: [{ role: 'user', content: 'read safely' }],+ });+ expect(compatibleGateway.request.tools?.[0]).toMatchObject({ name: 'read' });+ expect(compatibleGateway.request.tools?.[0]).not.toHaveProperty('strict');+ });++ it('filters whitespace-only text blocks that Anthropic rejects', () => {+ const result = translateResponsesRequest({+ model: 'claude',+ instructions: ' ',+ input: [+ { role: 'user', content: [{ type: 'input_text', text: ' ' }] },+ { role: 'user', content: [{ type: 'input_text', text: 'hello' }] },+ ],+ });+ expect(result.request.system).toBeUndefined();+ expect(result.request.messages).toEqual([{+ role: 'user',+ content: [{ type: 'text', text: 'hello' }],+ }]);+ });++ it('preserves refusal parts from assistant history as text', () => {+ const result = translateResponsesRequest({+ model: 'claude',+ input: [{+ role: 'assistant',+ content: [{ type: 'refusal', refusal: 'I cannot do that.' }],+ }],+ });+ expect(result.request.messages).toContainEqual({+ role: 'assistant',+ content: [{ type: 'text', text: 'I cannot do that.' }],+ });+ });++ it('converts top-level files and structured tool-result files to documents', () => {+ const result = translateResponsesRequest({+ model: 'claude',+ input: [+ {+ type: 'input_file',+ file_data: 'data:application/pdf;base64,JVBERiQ=',+ filename: 'report.pdf',+ },+ { type: 'function_call', call_id: 'c1', name: 'inspect', arguments: '{}' },+ {+ type: 'function_call_output',+ call_id: 'c1',+ output: [{ type: 'input_file', file_url: 'https://example.com/report.pdf', filename: 'report.pdf' }],+ },+ ],+ });+ expect(result.request.messages[0].content).toEqual([{+ type: 'document',+ source: { type: 'base64', media_type: 'application/pdf', data: 'JVBERiQ=' },+ title: 'report.pdf',+ }]);+ const toolResult = result.request.messages+ .flatMap((message) => message.content as Array<Record<string, unknown>>)+ .find((block) => block.type === 'tool_result')!;+ expect(toolResult.content).toEqual([{+ type: 'document',+ source: { type: 'url', url: 'https://example.com/report.pdf' },+ title: 'report.pdf',+ }]);+ });++ it('converts inline plain-text files to Anthropic text document sources', () => {+ const result = translateResponsesRequest({+ model: 'claude',+ input: [{+ type: 'input_file',+ file_data: 'data:text/plain;base64,SGVsbG8gQ2xhdWRlIQ==',+ filename: 'hello.txt',+ }],+ });+ expect(result.request.messages[0].content).toEqual([{+ type: 'document',+ source: {+ type: 'text',+ media_type: 'text/plain',+ data: 'Hello Claude!',+ },+ title: 'hello.txt',+ }]);+ });++ it('rejects unsupported inline document MIME types before reaching Anthropic', () => {+ expect(() => translateResponsesRequest({+ model: 'claude',+ input: [{+ type: 'input_file',+ file_data: 'data:application/json;base64,eyJvayI6dHJ1ZX0=',+ }],+ })).toThrow("input_file media type 'application/json'");+ });++ it('normalizes long and invalid tool names deterministically', () => {+ const longName = 'tool.'.repeat(30);+ const first = translateResponsesRequest({+ model: 'claude',+ input: [{ role: 'user', content: 'hi' }],+ tools: [{ type: 'function', name: longName, parameters: {} }],+ });+ const second = translateResponsesRequest({+ model: 'claude',+ input: [{ role: 'user', content: 'hi' }],+ tools: [{ type: 'function', name: longName, parameters: {} }],+ });+ const firstName = first.request.tools?.[0] as Record<string, unknown>;+ const secondName = second.request.tools?.[0] as Record<string, unknown>;+ expect(String(firstName.name)).toHaveLength(64);+ expect(firstName.name).toBe(secondName.name);+ });++ it('keeps explicit max_output_tokens unchanged for adaptive thinking', () => {+ const result = translateResponsesRequest({+ model: 'claude-sonnet-5',+ max_output_tokens: 2048,+ reasoning: { effort: 'high' },+ input: [{ role: 'user', content: 'hi' }],+ });+ expect(result.request.max_tokens).toBe(2048);+ expect(result.request.thinking).toEqual({ type: 'adaptive' });+ });++ it('rejects a requested reasoning budget that cannot fit in max_output_tokens', () => {+ expect(() => translateResponsesRequest({+ model: 'claude-sonnet-4-6',+ max_output_tokens: 1024,+ reasoning: { effort: 'high' },+ input: [{ role: 'user', content: 'hi' }],+ })).toThrow('reasoning effort cannot fit');+ });++ it('can disable thinking policy for generic Anthropic-compatible endpoints', () => {+ const result = translateResponsesRequest({+ model: 'custom-model',+ max_output_tokens: 1024,+ reasoning: { effort: 'high' },+ input: [{ role: 'user', content: 'hi' }],+ }, { supportsThinking: () => false });+ expect(result.request.thinking).toBeUndefined();+ expect(result.request.max_tokens).toBe(1024);+ });++ it('normalizes text and rejects unsupported tool-result document MIME types', () => {+ const text = translateResponsesRequest({+ model: 'claude',+ input: [+ { type: 'function_call', call_id: 'c1', name: 'inspect', arguments: '{}' },+ {+ type: 'function_call_output',+ call_id: 'c1',+ output: [{+ type: 'document',+ source: { type: 'base64', media_type: 'text/plain', data: 'SGk=' },+ }],+ },+ ],+ });+ const textResult = text.request.messages+ .flatMap((message) => message.content as Array<Record<string, unknown>>)+ .find((block) => block.type === 'tool_result');+ expect(textResult).toMatchObject({+ type: 'tool_result',+ content: [{ type: 'document', source: { type: 'text', data: 'Hi' } }],+ });+ const unsupported = translateResponsesRequest({+ model: 'claude',+ input: [+ { type: 'function_call', call_id: 'c1', name: 'inspect', arguments: '{}' },+ {+ type: 'function_call_output',+ call_id: 'c1',+ output: [{+ type: 'document',+ source: { type: 'base64', media_type: 'application/json', data: 'e30=' },+ }],+ },+ ],+ });+ const unsupportedResult = unsupported.request.messages+ .flatMap((message) => message.content as Array<Record<string, unknown>>)+ .find((block) => block.type === 'tool_result');+ expect(unsupportedResult).toMatchObject({+ type: 'tool_result',+ content: [{ type: 'text' }],+ });+ });++ it('bounds deeply nested structured tool output', () => {+ let nested: unknown = { type: 'text', text: 'leaf' };+ for (let index = 0; index < 20; index += 1) nested = { content: [nested] };+ const result = translateResponsesRequest({+ model: 'claude',+ input: [+ { type: 'function_call', call_id: 'c1', name: 'inspect', arguments: '{}' },+ { type: 'function_call_output', call_id: 'c1', output: nested },+ ],+ });+ expect(result.request.messages).toHaveLength(3);+ });++ it('does not enable optional adaptive thinking without a requested effort', () => {+ const result = translateResponsesRequest({+ model: 'claude-opus-4-8',+ input: [{ role: 'user', content: 'hi' }],+ });+ expect(result.request.thinking).toBeUndefined();+ });++ it('cannot disable thinking on fable and mythos models', () => {+ for (const model of ['claude-fable-5', 'claude-mythos-5']) {+ const result = translateResponsesRequest({+ model,+ reasoning: { effort: 'none' },+ input: [{ role: 'user', content: 'hi' }],+ });+ expect(result.request.thinking).toEqual({ type: 'adaptive' });+ expect(result.request.output_config).toEqual({ effort: 'low' });+ }+ });++ it('keeps automatic prompt caching off the moving last user block', () => {+ const result = translateResponsesRequest({+ model: 'claude-sonnet-5',+ input: [+ { role: 'user', content: 'first' },+ { role: 'assistant', content: 'reply' },+ { role: 'user', content: 'second' },+ ],+ }, {+ promptCaching: true,+ automaticPromptCaching: true,+ });+ expect(result.request.cache_control).toEqual({ type: 'ephemeral' });+ const firstUser = result.request.messages[0].content as Array<Record<string, unknown>>;+ const lastUser = result.request.messages[2].content as Array<Record<string, unknown>>;+ expect(firstUser[0].cache_control).toEqual({ type: 'ephemeral' });+ expect(lastUser[0].cache_control).toBeUndefined();+ });++ it('rejects non-http image URLs instead of passing them to Anthropic', () => {+ expect(() => translateResponsesRequest({+ model: 'claude',+ input: [{ role: 'user', content: [{ type: 'input_image', image_url: 'file:///tmp/a.png' }] }],+ })).toThrow('input_image.image_url scheme');+ });++ it('textifies invalid tool-result media URLs instead of forwarding them', () => {+ const result = translateResponsesRequest({+ model: 'claude',+ input: [+ { type: 'function_call', call_id: 'c1', name: 'inspect', arguments: '{}' },+ {+ type: 'function_call_output',+ call_id: 'c1',+ output: [+ { type: 'image', source: { type: 'url', url: 'file:///tmp/a.png' } },+ { type: 'image', source: { type: 'url', url: 'https://user:[email protected]/a.png' } },+ { type: 'image', source: { type: 'url', url: 'https://example.com/a.png' } },+ ],+ },+ ],+ });+ const resultMessage = result.request.messages.find((message) => (+ (message.content as Array<Record<string, unknown>>).some((block) => block.type === 'tool_result')+ ))!;+ const toolResult = (resultMessage.content as Array<Record<string, unknown>>)+ .find((block) => block.type === 'tool_result') as Record<string, unknown>;+ expect(toolResult.content).toEqual([+ {+ type: 'text',+ text: JSON.stringify({ type: 'image', source: { type: 'url', url: 'file:///tmp/a.png' } }),+ },+ {+ type: 'text',+ text: JSON.stringify({+ type: 'image',+ source: { type: 'url', url: 'https://user:[email protected]/a.png' },+ }),+ },+ { type: 'image', source: { type: 'url', url: 'https://example.com/a.png' } },+ ]);+ });++ it('places tool results before user text and textifies orphan results', () => {+ const result = translateResponsesRequest({+ model: 'claude',+ input: [+ { role: 'user', content: 'before' },+ { type: 'function_call_output', call_id: 'orphan', output: 'lost' },+ ],+ });+ expect(result.request.messages[0].content).toEqual([+ { type: 'text', text: 'before' },+ { type: 'text', text: '[orphan tool_result orphan omitted from replay]' },+ ]);+ });+});diff --git a/packages/responses-anthropic-bridge/src/anthropic-images.ts b/packages/responses-anthropic-bridge/src/anthropic-images.tsnew file mode 100644index 0000000000..8132ce813f--- /dev/null+++ b/packages/responses-anthropic-bridge/src/anthropic-images.ts@@ -0,0 +1,442 @@+import { Buffer } from 'node:buffer';++import type { AnthropicImageCodec } from './types.js';++export const MANY_IMAGE_THRESHOLD = 20;+export const MANY_IMAGE_MAX_DIMENSION = 2000;+export const ABSOLUTE_MAX_DIMENSION = 8000;+export const MAX_IMAGES_PER_REQUEST = 100;+export const MAX_IMAGE_BASE64_LENGTH = 5 * 1024 * 1024;+export const TOTAL_IMAGE_BASE64_BUDGET = 20 * 1024 * 1024;+export const MAX_INPUT_BASE64_LENGTH = 20 * 1024 * 1024;++// Sharp holds the decoded input and resized output concurrently. Keep one worker per+// request, then additionally serialize all requests sharing the same native codec+// instance below so large-but-admissible images cannot multiply that peak.+const IMAGE_NORMALIZE_CONCURRENCY = 1;+const codecNormalizeTails = new WeakMap<AnthropicImageCodec, Promise<void>>();+const ALLOWED_IMAGE_MEDIA_TYPES = new Set([+ 'image/jpeg',+ 'image/png',+ 'image/gif',+ 'image/webp',+]);+const OMITTED_TEXT =+ '[image omitted: Anthropic request exceeded its image-count or dimension limits; older screenshots were dropped]';+const OVERSIZED_TEXT = "[image omitted: exceeds Anthropic's 8000px per-side limit]";+const PER_IMAGE_TOO_LARGE_TEXT = "[image omitted: exceeds Anthropic's 5MB per-image limit]";+const BYTE_BUDGET_TEXT =+ '[image omitted: total image payload exceeded the provider request budget; older screenshots were dropped]';+const UNDECODABLE_TEXT = '[image omitted: undecodable or corrupt image data]';+const BOMB_TEXT = '[image omitted: image too large to process safely]';++interface ImageDimensions {+ width: number;+ height: number;+}++interface ImageBlockRef {+ container: unknown[];+ index: number;+ base64: string | null;+ mediaType: string;+}++interface TierSpec {+ maxEdge: number;+ qualities: readonly number[];+ hardCap: number;+}++const TIER_SPECS: readonly TierSpec[] = [+ { maxEdge: 2000, qualities: [80, 60, 40, 30], hardCap: 2 * 1024 * 1024 },+ { maxEdge: 1024, qualities: [70, 50], hardCap: 512 * 1024 },+ { maxEdge: 700, qualities: [60, 40], hardCap: 192 * 1024 },+ { maxEdge: 500, qualities: [40], hardCap: 100 * 1024 },+ { maxEdge: 400, qualities: [30], hardCap: 100 * 1024 },+ { maxEdge: 320, qualities: [25], hardCap: Number.POSITIVE_INFINITY },+];+const TERMINAL_TIER = TIER_SPECS.length - 1;++function objectValue(value: unknown): Record<string, unknown> | null {+ return typeof value === 'object' && value !== null && !Array.isArray(value)+ ? value as Record<string, unknown>+ : null;+}++function u16be(bytes: Uint8Array, offset: number): number {+ return (bytes[offset] << 8) | bytes[offset + 1];+}++function u32be(bytes: Uint8Array, offset: number): number {+ return (+ (bytes[offset] << 24)+ | (bytes[offset + 1] << 16)+ | (bytes[offset + 2] << 8)+ | bytes[offset + 3]+ ) >>> 0;+}++function u16le(bytes: Uint8Array, offset: number): number {+ return bytes[offset] | (bytes[offset + 1] << 8);+}++function u24le(bytes: Uint8Array, offset: number): number {+ return bytes[offset] | (bytes[offset + 1] << 8) | (bytes[offset + 2] << 16);+}++function pngDimensions(bytes: Uint8Array): ImageDimensions | null {+ if (+ bytes.length < 24+ || bytes[0] !== 0x89+ || bytes[1] !== 0x50+ || bytes[2] !== 0x4e+ || bytes[3] !== 0x47+ ) return null;+ return { width: u32be(bytes, 16), height: u32be(bytes, 20) };+}++function jpegDimensions(bytes: Uint8Array): ImageDimensions | null {+ if (bytes.length < 4 || bytes[0] !== 0xff || bytes[1] !== 0xd8) return null;+ let offset = 2;+ while (offset + 9 < bytes.length) {+ if (bytes[offset] !== 0xff) {+ offset += 1;+ continue;+ }+ const marker = bytes[offset + 1];+ if (marker === 0xff) {+ offset += 1;+ continue;+ }+ if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {+ offset += 2;+ continue;+ }+ if (+ marker >= 0xc0+ && marker <= 0xcf+ && marker !== 0xc4+ && marker !== 0xc8+ && marker !== 0xcc+ ) {+ return {+ height: u16be(bytes, offset + 5),+ width: u16be(bytes, offset + 7),+ };+ }+ if (marker === 0xd9 || marker === 0xda) return null;+ const length = u16be(bytes, offset + 2);+ if (length < 2) return null;+ offset += 2 + length;+ }+ return null;+}++function gifDimensions(bytes: Uint8Array): ImageDimensions | null {+ if (+ bytes.length < 10+ || bytes[0] !== 0x47+ || bytes[1] !== 0x49+ || bytes[2] !== 0x46+ ) return null;+ return { width: u16le(bytes, 6), height: u16le(bytes, 8) };+}++function webpDimensions(bytes: Uint8Array): ImageDimensions | null {+ if (+ bytes.length < 30+ || bytes[0] !== 0x52+ || bytes[1] !== 0x49+ || bytes[2] !== 0x46+ || bytes[3] !== 0x46+ || bytes[8] !== 0x57+ || bytes[9] !== 0x45+ || bytes[10] !== 0x42+ || bytes[11] !== 0x50+ ) return null;+ const fourcc = String.fromCharCode(bytes[12], bytes[13], bytes[14], bytes[15]);+ if (fourcc === 'VP8X') {+ return { width: u24le(bytes, 24) + 1, height: u24le(bytes, 27) + 1 };+ }+ if (fourcc === 'VP8 ') {+ if (bytes[23] !== 0x9d || bytes[24] !== 0x01 || bytes[25] !== 0x2a) return null;+ return { width: u16le(bytes, 26) & 0x3fff, height: u16le(bytes, 28) & 0x3fff };+ }+ if (fourcc === 'VP8L') {+ if (bytes[20] !== 0x2f) return null;+ const raw = bytes[21] | (bytes[22] << 8) | (bytes[23] << 16) | (bytes[24] << 24);+ return {+ width: (raw & 0x3fff) + 1,+ height: ((raw >> 14) & 0x3fff) + 1,+ };+ }+ return null;+}++export function sniffImageDimensions(base64: string): ImageDimensions | null {+ const slice = base64.slice(0, 65_536);+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(slice)) return null;+ let bytes: Uint8Array;+ try {+ bytes = Uint8Array.from(Buffer.from(slice, 'base64'));+ } catch {+ return null;+ }+ return pngDimensions(bytes)+ ?? jpegDimensions(bytes)+ ?? gifDimensions(bytes)+ ?? webpDimensions(bytes)+ ?? null;+}++function collectImageRefs(messages: unknown[]): ImageBlockRef[] {+ const refs: ImageBlockRef[] = [];+ const scan = (content: unknown[]): void => {+ for (let index = 0; index < content.length; index += 1) {+ const block = objectValue(content[index]);+ if (!block) continue;+ if (block.type === 'image') {+ const source = objectValue(block.source);+ refs.push({+ container: content,+ index,+ base64: source?.type === 'base64' && typeof source.data === 'string'+ ? source.data+ : null,+ mediaType: typeof source?.media_type === 'string'+ ? source.media_type.toLowerCase()+ : '',+ });+ } else if (block.type === 'tool_result' && Array.isArray(block.content)) {+ scan(block.content);+ }+ }+ };+ for (const message of messages) {+ const content = objectValue(message)?.content;+ if (Array.isArray(content)) scan(content);+ }+ return refs;+}++function textify(ref: ImageBlockRef, text: string): void {+ ref.container[ref.index] = { type: 'text', text };+}++function replaceImage(ref: ImageBlockRef, data: string, mediaType: string): void {+ ref.container[ref.index] = {+ type: 'image',+ source: { type: 'base64', media_type: mediaType, data },+ };+ ref.base64 = data;+ ref.mediaType = mediaType;+}++function initialTier(newestFirstIndex: number, bias: number): number {+ const base = newestFirstIndex < 6 ? 0 : newestFirstIndex < 20 ? 1 : 2;+ return Math.min(base + Math.max(0, bias), TERMINAL_TIER);+}++async function runCodecNormalization<T>(+ codec: AnthropicImageCodec,+ operation: () => Promise<T>,+): Promise<T> {+ const previous = codecNormalizeTails.get(codec) ?? Promise.resolve();+ let release!: () => void;+ const current = new Promise<void>((resolve) => {+ release = resolve;+ });+ const tail = previous.then(() => current);+ codecNormalizeTails.set(codec, tail);+ await previous;+ try {+ return await operation();+ } finally {+ release();+ if (codecNormalizeTails.get(codec) === tail) codecNormalizeTails.delete(codec);+ }+}++async function normalizeAtTier(+ data: string,+ mediaType: string,+ startTier: number,+ codec: AnthropicImageCodec | undefined,+): Promise<{ data: string; mediaType: string; tier: number } | null> {+ if (!codec) {+ // A host without a native decoder cannot resize or fully validate the payload.+ // Preserve supported inputs here and let the deterministic guard below enforce+ // per-image/count/request budgets. Unknown dimensions are intentionally fail-open+ // for <=20 images, matching Anthropic's own validation boundary.+ return ALLOWED_IMAGE_MEDIA_TYPES.has(mediaType)+ ? { data, mediaType, tier: startTier }+ : null;+ }+ for (let tier = startTier; tier <= TERMINAL_TIER; tier += 1) {+ const spec = TIER_SPECS[tier];+ const normalized = await runCodecNormalization(codec, () => codec.normalize({+ data,+ mediaType,+ maxEdge: spec.maxEdge,+ qualities: spec.qualities,+ hardCap: spec.hardCap,+ }));+ if (normalized && (normalized.data.length <= spec.hardCap || tier === TERMINAL_TIER)) {+ return { ...normalized, tier };+ }+ }+ return null;+}++interface NormalizedEntry {+ ref: ImageBlockRef;+ originalData: string;+ originalMediaType: string;+ tier: number;+ size: number;+ live: boolean;+}++/**+ * Normalize inline images in memory, preserving newest screenshots at the highest+ * fidelity. URL images are counted by the deterministic guard but are never fetched.+ */+export async function normalizeAnthropicImages(+ messages: unknown[],+ options: { codec?: AnthropicImageCodec; tierBias?: number } = {},+): Promise<void> {+ const refs = collectImageRefs(messages);+ if (refs.length === 0) return;++ const entries: Array<NormalizedEntry | null> = new Array(refs.length).fill(null);+ let cursor = 0;+ const workers = Array.from(+ { length: Math.min(IMAGE_NORMALIZE_CONCURRENCY, refs.length) },+ async () => {+ for (;;) {+ const index = cursor++;+ if (index >= refs.length) return;+ const ref = refs[index];+ if (!ref.base64) continue;+ if (ref.base64.length > MAX_INPUT_BASE64_LENGTH) {+ textify(ref, BOMB_TEXT);+ continue;+ }+ const originalData = ref.base64;+ const originalMediaType = ref.mediaType;+ const normalized = await normalizeAtTier(+ originalData,+ originalMediaType,+ initialTier(refs.length - 1 - index, options.tierBias ?? 0),+ options.codec,+ );+ if (!normalized) {+ textify(ref, UNDECODABLE_TEXT);+ continue;+ }+ replaceImage(ref, normalized.data, normalized.mediaType);+ entries[index] = {+ ref,+ originalData,+ originalMediaType,+ tier: normalized.tier,+ size: normalized.data.length,+ live: true,+ };+ }+ },+ );+ await Promise.all(workers);++ let total = entries.reduce((sum, entry) => sum + (entry?.live ? entry.size : 0), 0);+ while (total > TOTAL_IMAGE_BASE64_BUDGET) {+ const candidate = entries.find((entry) => entry?.live && entry.tier < TERMINAL_TIER);+ if (!candidate) break;+ const normalized = await normalizeAtTier(+ candidate.originalData,+ candidate.originalMediaType,+ candidate.tier + 1,+ options.codec,+ );+ if (!normalized) {+ textify(candidate.ref, UNDECODABLE_TEXT);+ candidate.live = false;+ total -= candidate.size;+ continue;+ }+ total += normalized.data.length - candidate.size;+ candidate.size = normalized.data.length;+ candidate.tier = normalized.tier;+ replaceImage(candidate.ref, normalized.data, normalized.mediaType);+ }++ if (total > TOTAL_IMAGE_BASE64_BUDGET) {+ for (const entry of entries) {+ if (!entry?.live || total <= TOTAL_IMAGE_BASE64_BUDGET) continue;+ textify(entry.ref, BYTE_BUDGET_TEXT);+ entry.live = false;+ total -= entry.size;+ }+ }+ enforceAnthropicImageLimits(messages);+}++/** Deterministic backstop for inputs a native codec could not shrink or inspect. */+export function enforceAnthropicImageLimits(messages: unknown[]): void {+ const refs = collectImageRefs(messages);+ if (refs.length === 0) return;+ const dimensions = refs.map((ref) => ref.base64 ? sniffImageDimensions(ref.base64) : null);+ const live = new Set<number>(refs.keys());++ for (let index = 0; index < refs.length; index += 1) {+ const dims = dimensions[index];+ if (dims && (dims.width > ABSOLUTE_MAX_DIMENSION || dims.height > ABSOLUTE_MAX_DIMENSION)) {+ textify(refs[index], OVERSIZED_TEXT);+ live.delete(index);+ continue;+ }+ const data = refs[index].base64;+ if (data && data.length > MAX_IMAGE_BASE64_LENGTH) {+ textify(refs[index], PER_IMAGE_TOO_LARGE_TEXT);+ live.delete(index);+ }+ }++ const riskyForMany = [...live].some((index) => {+ const dims = dimensions[index];+ return dims === null+ || dims.width > MANY_IMAGE_MAX_DIMENSION+ || dims.height > MANY_IMAGE_MAX_DIMENSION;+ });+ if (riskyForMany && live.size > MANY_IMAGE_THRESHOLD) {+ for (const index of [...live]) {+ if (live.size <= MANY_IMAGE_THRESHOLD) break;+ textify(refs[index], OMITTED_TEXT);+ live.delete(index);+ }+ }+ if (live.size > MAX_IMAGES_PER_REQUEST) {+ for (const index of [...live]) {+ if (live.size <= MAX_IMAGES_PER_REQUEST) break;+ textify(refs[index], OMITTED_TEXT);+ live.delete(index);+ }+ }++ let total = [...live].reduce(+ (sum, index) => sum + (refs[index].base64?.length ?? 0),+ 0,+ );+ for (const index of [...live]) {+ if (total <= TOTAL_IMAGE_BASE64_BUDGET) break;+ const data = refs[index].base64;+ if (!data) continue;+ textify(refs[index], BYTE_BUDGET_TEXT);+ total -= data.length;+ }+}++export function requestHasInlineImage(messages: unknown[]): boolean {+ return collectImageRefs(messages).some((ref) => ref.base64 !== null);+}diff --git a/packages/responses-anthropic-bridge/src/handler.ts b/packages/responses-anthropic-bridge/src/handler.tsnew file mode 100644index 0000000000..158d336d75--- /dev/null+++ b/packages/responses-anthropic-bridge/src/handler.ts@@ -0,0 +1,570 @@+import type { ServerResponse } from 'node:http';++import { normalizeAnthropicImages, requestHasInlineImage } from './anthropic-images.js';+import { AnthropicSseTranslator } from './responses-sse-translator.js';+import { translateResponsesRequest } from './translate-request.js';+import {+ InvalidResponsesRequestError,+ type ResponsesAnthropicHandler,+ type ResponsesAnthropicLogger,+ type ResponsesAnthropicProviderConfig,+ type ResponsesRequest,+ UnsupportedResponsesFeatureError,+} from './types.js';++const MAX_ERROR_BODY_BYTES = 16 * 1024;+const MAX_STREAM_BUFFER_BYTES = 1024 * 1024;+const UTF8_ENCODER = new TextEncoder();++function isObject(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function utf8ByteLength(value: string): number {+ return UTF8_ENCODER.encode(value).byteLength;+}++function trimTrailingSlashes(value: string): string {+ let end = value.length;+ while (end > 0 && value.charCodeAt(end - 1) === 0x2f) end -= 1;+ return value.slice(0, end);+}++export function joinAnthropicMessagesUrl(base: string, requestPath: string): string {+ const url = new URL(base);+ if (+ (url.protocol !== 'http:' && url.protocol !== 'https:')+ || url.username+ || url.password+ ) {+ throw new TypeError('invalid upstream base URL');+ }+ const path = requestPath.startsWith('/') ? requestPath : `/${requestPath}`;+ if (+ path.length > 2048+ || path.startsWith('//')+ || path.includes('\\')+ || path.includes('#')+ || /[^\u0021-\u007e]/.test(path)+ || /%(?:2f|5c)/i.test(path)+ || /%(?![0-9A-Fa-f]{2})/.test(path)+ || path.split('/').some((segment) => segment.replace(/%2e/gi, '.') === '..')+ ) {+ throw new TypeError('invalid Anthropic messages path');+ }+ const queryIndex = path.indexOf('?');+ const pathname = queryIndex === -1 ? path : path.slice(0, queryIndex);+ const pathQuery = queryIndex === -1 ? '' : path.slice(queryIndex + 1);+ const baseQuery = url.search.slice(1);+ // Provider forms commonly store an Anthropic base as either `https://host` or+ // `https://host/v1`. The default `/v1/messages` path must not become `/v1/v1/messages`;+ // preserve other base path prefixes (for example `/api/v1`) when joining.+ const basePath = pathname.startsWith('/v1/')+ || pathname === '/v1'+ ? url.pathname.replace(/\/v1\/?$/, '')+ : url.pathname;+ url.pathname = `${trimTrailingSlashes(basePath)}${pathname}`;+ url.search = [baseQuery, pathQuery].filter(Boolean).join('&');+ url.hash = '';+ return url.toString();+}++function responsesError(status: number, code: string, message: string): Record<string, unknown> {+ return {+ error: {+ type: status === 401 || status === 403+ ? 'authentication_error'+ : status === 429+ ? 'rate_limit_error'+ : status >= 500 ? 'server_error' : 'invalid_request_error',+ code,+ message,+ },+ };+}++function writeJson(res: ServerResponse, status: number, body: unknown): void {+ if (res.headersSent) return;+ res.writeHead(status, {+ 'content-type': 'application/json; charset=utf-8',+ 'cache-control': 'no-store',+ });+ res.end(JSON.stringify(body));+}++function writeSse(res: ServerResponse, event: unknown, sequenceNumber: number): void {+ if (!isObject(event) || typeof event.type !== 'string') return;+ const payload = { ...event, sequence_number: sequenceNumber };+ res.write(`event: ${event.type}\ndata: ${JSON.stringify(payload)}\n\n`);+}++async function readBody(response: Response): Promise<string> {+ try {+ return await readBodyWithLimit(response, MAX_ERROR_BODY_BYTES);+ } catch {+ return '';+ }+}++async function readBodyWithLimit(+ response: Response,+ limitBytes: number,+ limitMessage?: string,+): Promise<string> {+ if (!response.body) return '';+ const reader = response.body.getReader();+ const decoder = new TextDecoder();+ let body = '';+ let bytesRead = 0;+ try {+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ const remaining = limitBytes - bytesRead;+ if (value.byteLength > remaining) {+ if (limitMessage) throw new Error(limitMessage);+ if (remaining > 0) {+ body += decoder.decode(value.subarray(0, remaining), { stream: true });+ }+ await reader.cancel();+ body += decoder.decode();+ return body;+ }+ bytesRead += value.byteLength;+ body += decoder.decode(value, { stream: true });+ }+ body += decoder.decode();+ return body;+ } catch (error) {+ try {+ await reader.cancel();+ } catch {+ // Best effort only: preserve the original parse/limit failure.+ }+ throw error;+ } finally {+ reader.releaseLock();+ }+}++function parseSseBlock(block: string): unknown | null {+ const data: string[] = [];+ let eventName = '';+ for (const line of block.split(/\r?\n/)) {+ if (line.startsWith('data:')) data.push(line.slice(5).trimStart());+ else if (line.startsWith('event:')) eventName = line.slice(6).trim();+ }+ if (data.length === 0) return null;+ const payload = data.join('\n').trim();+ if (!payload || payload === '[DONE]') return null;+ const parsed = JSON.parse(payload) as unknown;+ if (eventName && isObject(parsed) && typeof parsed.type !== 'string') {+ return { ...parsed, type: eventName };+ }+ return parsed;+}++function upstreamRequestHeaders(providerHeaders: Record<string, string>): Record<string, string> {+ const normalized: Record<string, string> = {};+ for (const [name, value] of Object.entries(providerHeaders)) {+ normalized[name.toLowerCase()] = value;+ }+ normalized['anthropic-version'] ??= '2023-06-01';+ normalized['content-type'] = 'application/json';+ // Native Anthropic SDKs request application/json even when stream:true; the body+ // flag selects SSE. Strict Messages gateways reject event-stream Accept with 406.+ normalized.accept = 'application/json';+ return normalized;+}++export interface ResponsesAnthropicHandlerOptions {+ logger?: ResponsesAnthropicLogger;+ fetchImpl?: typeof fetch;+}++export function createResponsesAnthropicHandler(+ provider: ResponsesAnthropicProviderConfig,+ options: ResponsesAnthropicHandlerOptions = {},+): ResponsesAnthropicHandler {+ const log = options.logger ?? {};+ const fetchImpl = options.fetchImpl ?? fetch;+ const upstreamBase = trimTrailingSlashes(provider.upstreamBase);++ return {+ async handle({ parsedBody, res }): Promise<void> {+ if (!isObject(parsedBody) || typeof parsedBody.model !== 'string') {+ writeJson(res, 400, responsesError(400, 'invalid_request', 'invalid Responses request body'));+ return;+ }+ const incoming = parsedBody as ResponsesRequest;+ const realModel = provider.rewriteModel?.(incoming.model) ?? incoming.model;+ let translated;+ try {+ translated = translateResponsesRequest(incoming, {+ model: realModel,+ defaultMaxTokens: provider.defaultMaxTokens,+ supportsAdaptiveThinking: provider.supportsAdaptiveThinking,+ supportsThinking: provider.supportsThinking,+ promptCaching: provider.promptCaching,+ automaticPromptCaching: provider.automaticPromptCaching,+ strictTools: provider.strictTools,+ authMode: provider.authMode,+ });+ } catch (error) {+ if (error instanceof UnsupportedResponsesFeatureError || error instanceof InvalidResponsesRequestError) {+ log.warn?.('responses-anthropic bridge rejected unsupported feature', {+ model: incoming.model,+ feature: error instanceof UnsupportedResponsesFeatureError ? error.feature : 'invalid_request',+ });+ writeJson(+ res,+ 400,+ responsesError(+ 400,+ error instanceof InvalidResponsesRequestError+ ? 'invalid_request'+ : 'unsupported_feature',+ error.message,+ ),+ );+ return;+ }+ throw error;+ }++ let upstreamUrl: string;+ try {+ upstreamUrl = joinAnthropicMessagesUrl(upstreamBase, provider.requestPath ?? '/v1/messages');+ } catch (error) {+ log.error?.('responses-anthropic bridge invalid upstream configuration', {+ model: incoming.model,+ error: error instanceof Error ? error.message : String(error),+ });+ writeJson(res, 502, responsesError(502, 'invalid_upstream_config', 'provider upstream configuration is invalid'));+ return;+ }++ const abort = new AbortController();+ const abortUpstream = (): void => abort.abort();+ res.once('close', abortUpstream);+ let providerHeaders: Record<string, string> = {};+ let upstream: Response | null = null;+ let imageTierBias = 0;+ let imageRetried = false;+ let authRetried = false;+ let retryHeaders: Record<string, string> | null = null;+ const hasInlineImage = requestHasInlineImage(translated.request.messages);++ for (;;) {+ if (imageTierBias > 0) {+ translated = translateResponsesRequest(incoming, {+ model: realModel,+ defaultMaxTokens: provider.defaultMaxTokens,+ supportsAdaptiveThinking: provider.supportsAdaptiveThinking,+ supportsThinking: provider.supportsThinking,+ promptCaching: provider.promptCaching,+ automaticPromptCaching: provider.automaticPromptCaching,+ strictTools: provider.strictTools,+ authMode: provider.authMode,+ });+ }+ await normalizeAnthropicImages(translated.request.messages, {+ codec: provider.imageCodec,+ tierBias: imageTierBias,+ });+ try {+ providerHeaders = retryHeaders ?? await provider.buildHeaders();+ } catch (error) {+ res.off('close', abortUpstream);+ log.error?.('responses-anthropic bridge auth unavailable', {+ model: incoming.model,+ error: error instanceof Error ? error.message : String(error),+ });+ writeJson(res, 502, responsesError(502, 'authentication_unavailable', 'provider authentication is unavailable'));+ return;+ }+ try {+ upstream = await fetchImpl(upstreamUrl, {+ method: 'POST',+ headers: upstreamRequestHeaders(providerHeaders),+ body: JSON.stringify(translated.request),+ signal: abort.signal,+ });+ } catch (error) {+ res.off('close', abortUpstream);+ if (abort.signal.aborted) return;+ log.warn?.('responses-anthropic bridge upstream unreachable', {+ model: incoming.model,+ error: error instanceof Error ? error.message : String(error),+ });+ writeJson(res, 502, responsesError(502, 'upstream_unreachable', 'provider upstream is unreachable'));+ return;+ }++ if (+ upstream.status === 401+ || upstream.status === 403+ ) {+ const body = await readBody(upstream);+ if (+ !authRetried+ && provider.refreshHeaders+ ) {+ authRetried = true;+ let refreshed: Record<string, string> | null = null;+ try {+ refreshed = await provider.refreshHeaders({+ status: upstream.status,+ body,+ requestHeaders: providerHeaders,+ });+ } catch (error) {+ log.warn?.('responses-anthropic bridge auth refresh failed', {+ model: incoming.model,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ if (refreshed) {+ // Keep the rotated credential for any subsequent image-size retry in+ // this same request. Falling back to buildHeaders() could re-read the+ // stale route snapshot and turn a 401→413 recovery into a final 401.+ retryHeaders = refreshed;+ continue;+ }+ }+ // The final error path below reports the already-consumed body.+ upstream = new Response(body, { status: upstream.status, headers: upstream.headers });+ } else if (+ upstream.status === 413+ && !imageRetried+ && hasInlineImage+ && provider.imageCodec+ ) {+ await readBody(upstream);+ imageRetried = true;+ imageTierBias = 1;+ continue;+ }+ break;+ }+ if (!upstream) {+ res.off('close', abortUpstream);+ writeJson(res, 502, responsesError(502, 'upstream_unreachable', 'provider request did not return a response'));+ return;+ }++ const reportUpstreamError = async (status: number, body: string): Promise<void> => {+ if (!provider.onUpstreamError) return;+ try {+ await provider.onUpstreamError({ status, body, requestHeaders: providerHeaders });+ } catch (error) {+ log.warn?.('responses-anthropic bridge onUpstreamError failed', {+ model: incoming.model,+ status,+ error: error instanceof Error ? error.message : String(error),+ });+ }+ };++ if (!upstream.ok || !upstream.body) {+ const body = await readBody(upstream);+ await reportUpstreamError(upstream.status, body);+ res.off('close', abortUpstream);+ const status = upstream.ok ? 502 : upstream.status;+ writeJson(+ res,+ status,+ responsesError(+ status,+ upstream.ok ? 'upstream_empty_response' : 'upstream_error',+ body || (+ upstream.ok+ ? 'provider returned a successful response without a body'+ : `provider returned HTTP ${upstream.status}`+ ),+ ),+ );+ return;+ }++ const translator = new AnthropicSseTranslator(incoming.model, translated.toolContext);+ let sequence = 0;+ const collected: unknown[] = [];+ const emit = (event: unknown): void => {+ if (incoming.stream === false) collected.push(event);+ else writeSse(res, event, sequence++);+ };+ if (incoming.stream !== false) {+ res.writeHead(200, {+ 'content-type': 'text/event-stream; charset=utf-8',+ 'cache-control': 'no-cache',+ connection: 'keep-alive',+ });+ }+ const contentType = upstream.headers.get('content-type')?.toLowerCase() ?? '';++ try {+ if (contentType.includes('application/json')) {+ const body = await readBodyWithLimit(+ upstream,+ MAX_STREAM_BUFFER_BYTES,+ 'upstream JSON response exceeds 1 MiB',+ );+ const json = JSON.parse(body) as unknown;+ for (const event of translator.pushJson(json)) emit(event);+ } else if (incoming.stream === false) {+ // Some Anthropic-compatible gateways omit Content-Type. Buffering is already+ // required for a non-streaming caller, so sniff JSON first and otherwise+ // aggregate the unmarked Anthropic SSE body, with the same hard cap used+ // while sniffing streaming responses.+ const body = await readBodyWithLimit(+ upstream,+ MAX_STREAM_BUFFER_BYTES,+ 'upstream response exceeds 1 MiB',+ );+ const trimmed = body.trimStart();+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) {+ const json = JSON.parse(body) as unknown;+ for (const event of translator.pushJson(json)) emit(event);+ } else {+ let buffer = body;+ let terminal = false;+ const consume = (block: string): void => {+ let event: unknown;+ try {+ event = parseSseBlock(block);+ } catch {+ throw new Error('upstream SSE frame is malformed');+ }+ if (!event) return;+ if (isObject(event) && event.type === 'message_stop') terminal = true;+ for (const output of translator.push(event)) emit(output);+ };+ let boundary: number;+ while ((boundary = buffer.search(/\r?\n\r?\n/)) >= 0) {+ const block = buffer.slice(0, boundary);+ if (utf8ByteLength(block) > MAX_STREAM_BUFFER_BYTES) {+ throw new Error('upstream SSE frame exceeds 1 MiB');+ }+ const separator = buffer.slice(boundary).startsWith('\r\n\r\n') ? 4 : 2;+ buffer = buffer.slice(boundary + separator);+ consume(block);+ }+ if (utf8ByteLength(buffer) > MAX_STREAM_BUFFER_BYTES) {+ throw new Error('upstream SSE frame exceeds 1 MiB');+ }+ if (buffer.trim()) consume(buffer);+ if (!terminal) for (const output of translator.finish()) emit(output);+ }+ } else {+ const reader = upstream.body.getReader();+ const decoder = new TextDecoder();+ let buffer = '';+ let receivedBytes = 0;+ let terminal = false;+ let bodyKind: 'unknown' | 'json' | 'sse' = 'unknown';+ const consume = (block: string): void => {+ let event: unknown;+ try {+ event = parseSseBlock(block);+ } catch {+ throw new Error('upstream SSE frame is malformed');+ }+ if (!event) return;+ if (isObject(event) && event.type === 'message_stop') terminal = true;+ for (const output of translator.push(event)) emit(output);+ };+ try {+ for (;;) {+ const { done, value } = await reader.read();+ if (done) break;+ receivedBytes += value.byteLength;+ buffer += decoder.decode(value, { stream: true });+ if (bodyKind === 'unknown') {+ const trimmed = buffer.trimStart();+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) bodyKind = 'json';+ else if (trimmed.length > 0) bodyKind = 'sse';+ }+ if (bodyKind === 'json') {+ if (receivedBytes > MAX_STREAM_BUFFER_BYTES) {+ throw new Error('upstream JSON response exceeds 1 MiB');+ }+ continue;+ }+ let boundary: number;+ while ((boundary = buffer.search(/\r?\n\r?\n/)) >= 0) {+ const block = buffer.slice(0, boundary);+ if (utf8ByteLength(block) > MAX_STREAM_BUFFER_BYTES) {+ throw new Error('upstream SSE frame exceeds 1 MiB');+ }+ const separator = buffer.slice(boundary).startsWith('\r\n\r\n') ? 4 : 2;+ buffer = buffer.slice(boundary + separator);+ consume(block);+ }+ if (utf8ByteLength(buffer) > MAX_STREAM_BUFFER_BYTES) {+ throw new Error('upstream SSE frame exceeds 1 MiB');+ }+ }+ buffer += decoder.decode();+ } catch (error) {+ try {+ await reader.cancel();+ } catch {+ // Preserve the original parse/limit failure.+ }+ throw error;+ }+ if (bodyKind === 'unknown') {+ const trimmed = buffer.trimStart();+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) bodyKind = 'json';+ else if (trimmed.length > 0) bodyKind = 'sse';+ }+ if (bodyKind === 'json') {+ if (receivedBytes > MAX_STREAM_BUFFER_BYTES) {+ throw new Error('upstream JSON response exceeds 1 MiB');+ }+ const json = JSON.parse(buffer) as unknown;+ for (const output of translator.pushJson(json)) emit(output);+ } else {+ if (utf8ByteLength(buffer) > MAX_STREAM_BUFFER_BYTES) {+ throw new Error('upstream SSE frame exceeds 1 MiB');+ }+ if (buffer.trim()) consume(buffer);+ if (!terminal) for (const output of translator.finish()) emit(output);+ }+ }+ } catch (error) {+ if (!abort.signal.aborted) {+ const message = error instanceof Error ? error.message : String(error);+ log.warn?.('responses-anthropic bridge stream failed', {+ model: incoming.model,+ error: message,+ });+ if (incoming.stream === false && !res.headersSent) {+ writeJson(res, 502, responsesError(502, 'upstream_stream_error', message));+ return;+ }+ for (const output of translator.fail(message)) emit(output);+ }+ } finally {+ res.off('close', abortUpstream);+ if (incoming.stream === false && !res.headersSent) {+ const terminal = [...collected].reverse().find((event) => (+ isObject(event)+ && (+ event.type === 'response.completed'+ || event.type === 'response.incomplete'+ || event.type === 'response.failed'+ )+ ));+ if (isObject(terminal) && terminal.response) {+ writeJson(res, 200, terminal.response);+ } else {+ writeJson(res, 502, responsesError(502, 'upstream_empty_response', 'provider returned no Responses result'));+ }+ }+ if (incoming.stream !== false || !res.headersSent) res.end();+ }+ },+ };+}diff --git a/packages/responses-anthropic-bridge/src/index.ts b/packages/responses-anthropic-bridge/src/index.tsnew file mode 100644index 0000000000..155f8aa084--- /dev/null+++ b/packages/responses-anthropic-bridge/src/index.ts@@ -0,0 +1,45 @@+/**+ * @cindy/responses-anthropic-bridge+ *+ * Local-handler protocol adapter for Codex: OpenAI Responses requests are translated+ * to Anthropic Messages, then Anthropic SSE/JSON is translated back to Responses SSE.+ *+ * This is the inverse direction of @cindy/anthropic-responses-bridge. Keeping each+ * direction in its own package prevents provider auth/routing concerns from leaking+ * into either wire translator.+ */+export {+ createResponsesAnthropicHandler,+ joinAnthropicMessagesUrl,+} from './handler.js';+export {+ translateResponsesRequest,+ encodeThinkingBlock,+ decodeThinkingBlock,+ type TranslateResponsesRequestOptions,+} from './translate-request.js';+export { AnthropicSseTranslator } from './responses-sse-translator.js';+export { InvalidResponsesRequestError } from './types.js';+export {+ enforceAnthropicImageLimits,+ normalizeAnthropicImages,+ requestHasInlineImage,+ sniffImageDimensions,+} from './anthropic-images.js';+export type {+ AnthropicImageCodec,+ AnthropicImageCodecInput,+ AnthropicImageCodecOutput,+ AnthropicRequest,+ CacheControl,+ ResponsesAnthropicAuthRetryInfo,+ ResponsesAnthropicErrorInfo,+ ResponsesAnthropicHandleArgs,+ ResponsesAnthropicHandler,+ ResponsesAnthropicLogger,+ ResponsesAnthropicProviderConfig,+ ResponsesRequest,+ ToolCallKind,+ ToolCallMapping,+ ToolContext,+} from './types.js';diff --git a/packages/responses-anthropic-bridge/src/responses-sse-translator.ts b/packages/responses-anthropic-bridge/src/responses-sse-translator.tsnew file mode 100644index 0000000000..5bc952319e--- /dev/null+++ b/packages/responses-anthropic-bridge/src/responses-sse-translator.ts@@ -0,0 +1,604 @@+import { createHash } from 'node:crypto';++import { encodeThinkingBlock } from './translate-request.js';+import type { ToolCallMapping, ToolContext } from './types.js';++type JsonObject = Record<string, unknown>;++interface Usage {+ input_tokens?: number;+ output_tokens?: number;+ cache_read_input_tokens?: number;+ cache_creation_input_tokens?: number;+ output_tokens_details?: { thinking_tokens?: number; reasoning_tokens?: number };+}++interface BlockState {+ kind: 'text' | 'tool_use' | 'thinking' | 'redacted_thinking';+ outputIndex: number;+ itemId: string;+ callId: string;+ wireName: string;+ text: string;+ args: string;+ signature: string;+ source: JsonObject;+ startInput: string;+ visibleSummary: boolean;+ done: boolean;+}++function isObject(value: unknown): value is JsonObject {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function text(value: unknown): string {+ return typeof value === 'string' ? value : '';+}++function number(value: unknown): number {+ return typeof value === 'number' && Number.isFinite(value) ? value : 0;+}++function deterministicId(prefix: string, responseId: string, index: number): string {+ const digest = createHash('sha256').update(`${responseId}\0${index}`).digest('hex').slice(0, 20);+ return `${prefix}_${digest}`;+}++function mapUsage(usage: Usage | undefined): JsonObject | undefined {+ if (!usage) return undefined;+ const fresh = number(usage.input_tokens);+ const read = number(usage.cache_read_input_tokens);+ const write = number(usage.cache_creation_input_tokens);+ const output = number(usage.output_tokens);+ const reasoning = number(usage.output_tokens_details?.thinking_tokens)+ || number(usage.output_tokens_details?.reasoning_tokens);+ return {+ input_tokens: fresh + read + write,+ output_tokens: output,+ total_tokens: fresh + read + write + output,+ input_tokens_details: { cached_tokens: read, cache_write_tokens: write },+ output_tokens_details: { reasoning_tokens: reasoning },+ };+}++function mappingFor(context: ToolContext, wireName: string): ToolCallMapping {+ return context.byWireName.get(wireName) ?? {+ wireName,+ name: wireName,+ kind: 'function',+ };+}++function customToolInputFromArguments(argumentsText: string): string {+ if (argumentsText.trim().length === 0) return '';+ try {+ const parsed = JSON.parse(argumentsText) as unknown;+ if (isObject(parsed) && typeof parsed.input === 'string') return parsed.input;+ } catch {+ // Anthropic-compatible providers may emit free-form arguments rather than JSON.+ }+ return argumentsText;+}++function toolSearchArgumentsFromText(argumentsText: string): JsonObject {+ if (argumentsText.trim().length === 0) return {};+ try {+ const parsed = JSON.parse(argumentsText) as unknown;+ if (isObject(parsed)) return parsed;+ } catch {+ // Preserve free-form search text from permissive Anthropic-compatible gateways.+ }+ return { query: argumentsText };+}++function sanitizeToolArguments(+ argumentsText: string,+ mapping: ToolCallMapping,+): string {+ const fallback = argumentsText.trim().length > 0 ? argumentsText : '{}';+ // Claude OAuth exposes its built-in Read tool on the reserved custom_Read wire+ // identity. User-defined tools may share the display name without this identity.+ if (mapping.kind !== 'function' || mapping.wireName !== 'custom_Read') return fallback;+ try {+ const parsed = JSON.parse(fallback) as unknown;+ if (!isObject(parsed)) return fallback;+ if (parsed.pages === '') delete parsed.pages;+ return JSON.stringify(parsed);+ } catch {+ return fallback;+ }+}++function outputCallItem(+ state: BlockState,+ context: ToolContext,+ status: 'in_progress' | 'completed' | 'incomplete',+): JsonObject {+ const mapping = mappingFor(context, state.wireName);+ if (mapping.kind === 'custom') {+ return {+ id: state.itemId,+ type: 'custom_tool_call',+ status,+ call_id: state.callId,+ name: mapping.name,+ input: customToolInputFromArguments(state.args),+ ...(mapping.namespace ? { namespace: mapping.namespace } : {}),+ };+ }+ if (mapping.kind === 'tool_search') {+ return {+ id: state.itemId,+ type: 'tool_search_call',+ status,+ call_id: state.callId,+ execution: 'client',+ arguments: toolSearchArgumentsFromText(state.args),+ };+ }+ return {+ id: state.itemId,+ type: 'function_call',+ status,+ call_id: state.callId,+ name: mapping.name,+ arguments: state.args,+ ...(mapping.namespace ? { namespace: mapping.namespace } : {}),+ };+}++function stopReasonToCompletion(reason: string | null): { status: string; incomplete?: string } {+ if (reason === 'max_tokens' || reason === 'model_context_window_exceeded') {+ return { status: 'incomplete', incomplete: 'max_output_tokens' };+ }+ if (reason === 'refusal' || reason === 'content_filter') {+ return { status: 'incomplete', incomplete: 'content_filter' };+ }+ return { status: 'completed' };+}++export class AnthropicSseTranslator {+ private responseId = '';+ private model = '';+ private started = false;+ private terminal = false;+ private terminalMarker = false;+ private nextOutputIndex = 0;+ private stopReason: string | null = null;+ private usage: Usage | undefined;+ private readonly blocks = new Map<number, BlockState>();+ private readonly outputItems = new Map<number, JsonObject>();++ constructor(+ private readonly wireModel: string,+ private readonly toolContext: ToolContext,+ ) {+ this.model = wireModel;+ }++ push(raw: unknown): unknown[] {+ if (this.terminal || !isObject(raw)) return [];+ const type = text(raw.type);+ if (type === 'error') {+ return this.fail(this.errorMessage(raw));+ }+ if (type === 'message_start') return this.messageStart(raw);+ if (type === 'content_block_start') return this.blockStart(raw);+ if (type === 'content_block_delta') return this.blockDelta(raw);+ if (type === 'content_block_stop') return this.blockStop(raw);+ if (type === 'message_delta') return this.messageDelta(raw);+ if (type === 'message_stop') {+ this.terminalMarker = true;+ return this.complete();+ }+ return [];+ }++ pushJson(message: unknown): unknown[] {+ if (!isObject(message)) return this.fail('Anthropic returned an invalid JSON response');+ if (message.type === 'error' || message.error) return this.fail(this.errorMessage(message));+ const output: unknown[] = [];+ const start = { type: 'message_start', message: { ...message, content: [] } };+ output.push(...this.push(start));+ const content = Array.isArray(message.content) ? message.content : [];+ content.forEach((block, index) => {+ if (!isObject(block)) return;+ // A JSON Messages response is converted into the same delta sequence as SSE.+ // Do not seed blockStart with text/thinking/signature, otherwise the synthetic+ // deltas below would be accumulated a second time.+ const startBlock = { ...block };+ delete startBlock.text;+ delete startBlock.thinking;+ delete startBlock.reasoning;+ delete startBlock.signature;+ output.push(...this.push({+ type: 'content_block_start',+ index,+ content_block: startBlock,+ }));+ if (block.type === 'text' && text(block.text)) {+ output.push(...this.push({+ type: 'content_block_delta',+ index,+ delta: { type: 'text_delta', text: block.text },+ }));+ } else if (+ (block.type === 'thinking' && text(block.thinking))+ || (block.type === 'reasoning' && text(block.reasoning))+ ) {+ output.push(...this.push({+ type: 'content_block_delta',+ index,+ delta: block.type === 'reasoning'+ ? { type: 'reasoning_delta', reasoning: block.reasoning }+ : { type: 'thinking_delta', thinking: block.thinking },+ }));+ }+ if (+ (block.type === 'thinking' || block.type === 'reasoning')+ && text(block.signature)+ ) {+ output.push(...this.push({+ type: 'content_block_delta',+ index,+ delta: { type: 'signature_delta', signature: block.signature },+ }));+ } else if (block.type === 'tool_use') {+ const input = typeof block.input === 'string'+ ? block.input+ : block.input === undefined+ ? ''+ : JSON.stringify(block.input);+ if (input) {+ output.push(...this.push({+ type: 'content_block_delta',+ index,+ delta: { type: 'input_json_delta', partial_json: input },+ }));+ }+ }+ output.push(...this.push({ type: 'content_block_stop', index }));+ });+ output.push(...this.push({+ type: 'message_delta',+ delta: { stop_reason: text(message.stop_reason) },+ usage: message.usage,+ }));+ output.push(...this.push({ type: 'message_stop' }));+ return output;+ }++ finish(): unknown[] {+ if (this.terminal) return [];+ if (this.stopReason || this.terminalMarker) return this.complete();+ return this.fail('upstream stream ended before message_stop (stream_truncated)');+ }++ fail(message: string): unknown[] {+ if (this.terminal) return [];+ const out: unknown[] = [];+ this.ensureStarted(out);+ out.push(...this.closeBlocks('incomplete'));+ this.terminal = true;+ out.push({+ type: 'response.failed',+ response: this.responseObject('failed', {+ error: { code: 'upstream_error', message },+ }),+ });+ return out;+ }++ private ensureStarted(out: unknown[]): void {+ if (this.started) return;+ this.started = true;+ if (!this.responseId) this.responseId = deterministicId('resp', this.wireModel, 0);+ const response = this.responseObject('in_progress');+ out.push({ type: 'response.created', response });+ out.push({ type: 'response.in_progress', response });+ }++ private messageStart(raw: JsonObject): unknown[] {+ const message = isObject(raw.message) ? raw.message : raw;+ const id = text(message.id);+ if (id) this.responseId = id.startsWith('resp_') ? id : `resp_${id}`;+ const model = text(message.model);+ if (model) this.model = model;+ if (isObject(message.usage)) this.usage = message.usage as Usage;+ const out: unknown[] = [];+ this.ensureStarted(out);+ return out;+ }++ private blockStart(raw: JsonObject): unknown[] {+ const index = number(raw.index);+ const block = isObject(raw.content_block) ? raw.content_block : {};+ const kind = text(block.type);+ const reasoning = kind === 'thinking' || kind === 'reasoning';+ const toolMapping = kind === 'tool_use'+ ? mappingFor(this.toolContext, text(block.name))+ : null;+ const outputIndex = this.nextOutputIndex++;+ const itemPrefix = toolMapping?.kind === 'tool_search'+ ? 'tsc'+ : toolMapping?.kind === 'custom'+ ? 'ctc'+ : kind === 'tool_use'+ ? 'fc'+ : reasoning || kind === 'redacted_thinking'+ ? 'rs'+ : 'msg';+ const source = kind === 'reasoning'+ ? {+ ...block,+ type: 'thinking',+ thinking: text(block.reasoning),+ }+ : { ...block };+ const itemId = deterministicId(itemPrefix, this.responseId || this.wireModel, outputIndex);+ const state: BlockState = {+ kind: kind === 'tool_use'+ ? 'tool_use'+ : reasoning+ ? 'thinking'+ : kind === 'redacted_thinking'+ ? 'redacted_thinking'+ : 'text',+ outputIndex,+ itemId,+ callId: text(block.id),+ wireName: text(block.name),+ text: text(block.text) || text(block.thinking) || text(block.reasoning),+ args: '',+ signature: text(block.signature),+ source,+ startInput: isObject(block.input) ? JSON.stringify(block.input) : '',+ visibleSummary: reasoning,+ done: false,+ };+ this.blocks.set(index, state);+ const out: unknown[] = [];+ this.ensureStarted(out);+ if (state.kind === 'text') {+ out.push({+ type: 'response.output_item.added',+ response_id: this.responseId,+ output_index: outputIndex,+ item: { id: itemId, type: 'message', status: 'in_progress', role: 'assistant', content: [] },+ });+ out.push({+ type: 'response.content_part.added',+ response_id: this.responseId,+ item_id: itemId,+ output_index: outputIndex,+ content_index: 0,+ part: { type: 'output_text', text: '', annotations: [] },+ });+ } else if (state.kind === 'tool_use') {+ out.push({+ type: 'response.output_item.added',+ response_id: this.responseId,+ output_index: outputIndex,+ item: outputCallItem(state, this.toolContext, 'in_progress'),+ });+ } else {+ out.push({+ type: 'response.output_item.added',+ response_id: this.responseId,+ output_index: outputIndex,+ item: { id: itemId, type: 'reasoning', summary: [], status: 'in_progress' },+ });+ if (state.visibleSummary) {+ out.push({+ type: 'response.reasoning_summary_part.added',+ response_id: this.responseId,+ item_id: itemId,+ output_index: outputIndex,+ summary_index: 0,+ part: { type: 'summary_text', text: '' },+ });+ }+ }+ return out;+ }++ private blockDelta(raw: JsonObject): unknown[] {+ const state = this.blocks.get(number(raw.index));+ if (!state) return [];+ const delta = isObject(raw.delta) ? raw.delta : {};+ const type = text(delta.type);+ if (type === 'text_delta') {+ const value = text(delta.text);+ state.text += value;+ return [{+ type: 'response.output_text.delta',+ response_id: this.responseId,+ item_id: state.itemId,+ output_index: state.outputIndex,+ content_index: 0,+ delta: value,+ }];+ }+ if (type === 'thinking_delta' || type === 'reasoning_delta') {+ const value = type === 'reasoning_delta'+ ? text(delta.reasoning)+ : text(delta.thinking);+ state.text += value;+ state.source.thinking = state.text;+ return [{+ type: 'response.reasoning_summary_text.delta',+ response_id: this.responseId,+ item_id: state.itemId,+ output_index: state.outputIndex,+ summary_index: 0,+ delta: value,+ }];+ }+ if (type === 'signature_delta') {+ state.signature = text(delta.signature);+ state.source.signature = state.signature;+ return [];+ }+ if (type === 'input_json_delta') {+ const value = text(delta.partial_json);+ state.args += value;+ const mapping = mappingFor(this.toolContext, state.wireName);+ // Anthropic represents custom-tool free-form input as a compatibility JSON+ // object. Read also needs its arguments sanitized after the complete JSON has+ // arrived. Emitting either partial form would poison Codex before the done event.+ if (+ mapping.kind === 'custom'+ || mapping.kind === 'tool_search'+ || mapping.name === 'Read'+ ) return [];+ return [{+ type: 'response.function_call_arguments.delta',+ response_id: this.responseId,+ item_id: state.itemId,+ output_index: state.outputIndex,+ delta: value,+ }];+ }+ return [];+ }++ private blockStop(raw: JsonObject, terminalStatus: 'completed' | 'incomplete' = 'completed'): unknown[] {+ const state = this.blocks.get(number(raw.index));+ if (!state || state.done) return [];+ state.done = true;+ if (state.kind === 'tool_use' && state.args.length === 0) state.args = state.startInput || '{}';+ const out: unknown[] = [];+ if (state.kind === 'text') {+ const content = [{ type: 'output_text', text: state.text, annotations: [] }];+ out.push({+ type: 'response.output_text.done',+ response_id: this.responseId,+ item_id: state.itemId,+ output_index: state.outputIndex,+ content_index: 0,+ text: state.text,+ });+ out.push({+ type: 'response.content_part.done',+ response_id: this.responseId,+ item_id: state.itemId,+ output_index: state.outputIndex,+ content_index: 0,+ part: content[0],+ });+ const item = {+ id: state.itemId,+ type: 'message',+ status: terminalStatus,+ role: 'assistant',+ content,+ };+ this.outputItems.set(state.outputIndex, item);+ out.push({ type: 'response.output_item.done', response_id: this.responseId, output_index: state.outputIndex, item });+ } else if (state.kind === 'tool_use') {+ const mapping = mappingFor(this.toolContext, state.wireName);+ state.args = sanitizeToolArguments(state.args, mapping);+ const item = outputCallItem(state, this.toolContext, terminalStatus);+ if (terminalStatus === 'completed' && mapping.kind !== 'tool_search') {+ out.push({+ type: mapping.kind === 'custom'+ ? 'response.custom_tool_call_input.done'+ : 'response.function_call_arguments.done',+ response_id: this.responseId,+ item_id: state.itemId,+ output_index: state.outputIndex,+ ...(mapping.kind === 'custom'+ ? { input: customToolInputFromArguments(state.args) }+ : { arguments: state.args }),+ });+ }+ this.outputItems.set(state.outputIndex, item);+ out.push({ type: 'response.output_item.done', response_id: this.responseId, output_index: state.outputIndex, item });+ } else {+ const source = {+ ...state.source,+ ...(state.kind === 'thinking' ? { thinking: state.text, signature: state.signature } : {}),+ };+ const encryptedContent = encodeThinkingBlock(source);+ const item = {+ id: state.itemId,+ type: 'reasoning',+ status: terminalStatus,+ summary: state.visibleSummary ? [{ type: 'summary_text', text: state.text }] : [],+ ...(encryptedContent ? { encrypted_content: encryptedContent } : {}),+ };+ if (state.visibleSummary) {+ out.push({+ type: 'response.reasoning_summary_text.done',+ response_id: this.responseId,+ item_id: state.itemId,+ output_index: state.outputIndex,+ summary_index: 0,+ text: state.text,+ });+ out.push({+ type: 'response.reasoning_summary_part.done',+ response_id: this.responseId,+ item_id: state.itemId,+ output_index: state.outputIndex,+ summary_index: 0,+ part: { type: 'summary_text', text: state.text },+ });+ }+ this.outputItems.set(state.outputIndex, item);+ out.push({ type: 'response.output_item.done', response_id: this.responseId, output_index: state.outputIndex, item });+ }+ return out;+ }++ private messageDelta(raw: JsonObject): unknown[] {+ const delta = isObject(raw.delta) ? raw.delta : {};+ const reason = text(delta.stop_reason);+ if (reason) this.stopReason = reason;+ if (isObject(raw.usage)) this.usage = { ...(this.usage ?? {}), ...(raw.usage as Usage) };+ return [];+ }++ private closeBlocks(terminalStatus: 'completed' | 'incomplete' = 'completed'): unknown[] {+ const out: unknown[] = [];+ for (const [index, block] of this.blocks) {+ if (!block.done) out.push(...this.blockStop({ index }, terminalStatus));+ }+ return out;+ }++ private complete(): unknown[] {+ if (this.terminal) return [];+ const out = this.closeBlocks();+ this.terminal = true;+ const result = stopReasonToCompletion(this.stopReason);+ const extra = result.incomplete ? { incomplete_details: { reason: result.incomplete } } : {};+ out.push({+ type: result.status === 'completed' ? 'response.completed' : 'response.incomplete',+ response: this.responseObject(result.status, extra),+ });+ return out;+ }++ private responseObject(status: string, extra: JsonObject = {}): JsonObject {+ const output = [...this.outputItems.entries()]+ .sort(([a], [b]) => a - b)+ .map(([, item]) => item);+ return {+ id: this.responseId || deterministicId('resp', this.wireModel, 0),+ object: 'response',+ created_at: Math.floor(Date.now() / 1000),+ status,+ model: this.model || this.wireModel,+ output,+ ...(mapUsage(this.usage) ? { usage: mapUsage(this.usage) } : {}),+ ...extra,+ };+ }++ private errorMessage(raw: JsonObject): string {+ const error = isObject(raw.error) ? raw.error : raw;+ return text(error.message) || 'Anthropic upstream error';+ }+}diff --git a/packages/responses-anthropic-bridge/src/translate-request.ts b/packages/responses-anthropic-bridge/src/translate-request.tsnew file mode 100644index 0000000000..c23e949c48--- /dev/null+++ b/packages/responses-anthropic-bridge/src/translate-request.ts@@ -0,0 +1,1333 @@+import { Buffer } from 'node:buffer';+import { createHash } from 'node:crypto';++import {+ type AnthropicRequest,+ type CacheControl,+ type ResponsesRequest,+ type ToolCallKind,+ type ToolCallMapping,+ type ToolContext,+ InvalidResponsesRequestError,+ UnsupportedResponsesFeatureError,+} from './types.js';++const THINKING_PREFIX = 'cindy-anthropic-thinking-v1:';+const DEFAULT_MAX_TOKENS = 8192;+const MIN_THINKING_BUDGET = 1024;+const OUTPUT_HEADROOM = 4096;+const MAX_CACHE_BREAKPOINTS = 4;+const CONTINUE_TEXT = '(continue)';+const TOOL_NAME_MAX_LENGTH = 64;+const CLAUDE_CODE_SYSTEM_INSTRUCTION =+ "You are a Claude agent, built on Anthropic's Claude Agent SDK.";+const CLAUDE_OAUTH_TOOL_PREFIX = 'custom_';+const ANTHROPIC_BUILTIN_TOOLS = new Set([+ 'web_search',+ 'code_execution',+ 'text_editor',+ 'computer',+]);+const ANTHROPIC_IMAGE_MEDIA_TYPES = new Set([+ 'image/jpeg',+ 'image/png',+ 'image/gif',+ 'image/webp',+]);+const ANTHROPIC_BASE64_DOCUMENT_MEDIA_TYPES = new Set([+ 'application/pdf',+]);+const ANTHROPIC_TEXT_DOCUMENT_MEDIA_TYPES = new Set([+ 'text/plain',+]);++type JsonObject = Record<string, unknown>;++function isObject(value: unknown): value is JsonObject {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function stringValue(value: unknown): string | undefined {+ return typeof value === 'string' ? value : undefined;+}++function numberValue(value: unknown): number | undefined {+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined;+}++function anthropicSamplingValue(+ field: 'temperature' | 'top_p',+ value: unknown,+): number | undefined {+ const sampling = numberValue(value);+ if (sampling === undefined) return undefined;+ if (sampling < 0 || sampling > 1) {+ throw new InvalidResponsesRequestError(+ `Responses ${field} must be between 0 and 1 for the Anthropic bridge`,+ );+ }+ return sampling;+}++function textPart(text: string): { type: 'text'; text: string } {+ return { type: 'text', text };+}++function isMeaningfulText(value: string): boolean {+ return value.trim().length > 0;+}++function instructionsText(value: ResponsesRequest['instructions']): string {+ if (typeof value === 'string') return value;+ if (!Array.isArray(value)) return '';+ return value.map((part, index) => {+ if (!isObject(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('');+}++function parseDataUrl(value: string): { mediaType: string; data: string } | null {+ const match = /^data:([^;,]+)(?:;[^,]*)*;base64,([\s\S]+)$/i.exec(value);+ if (!match) return null;+ const data = match[2].replace(/\s/g, '');+ if (+ data.length === 0+ || data.length % 4 === 1+ || !/^[A-Za-z0-9+/]*={0,2}$/.test(data)+ ) return null;+ return { mediaType: match[1].toLowerCase(), data };+}++function validatedHttpUrl(value: string): string | null {+ try {+ const url = new URL(value);+ return (+ (url.protocol === 'http:' || url.protocol === 'https:')+ && !url.username+ && !url.password+ ) ? url.toString() : null;+ } catch {+ return null;+ }+}++function imageUrlFromPart(part: JsonObject): string | undefined {+ if (typeof part.image_url === 'string') return part.image_url;+ if (isObject(part.image_url)) return stringValue(part.image_url.url);+ return undefined;+}++function imageBlockFromPart(part: JsonObject): JsonObject {+ const imageUrl = imageUrlFromPart(part);+ if (imageUrl?.trim()) {+ const data = parseDataUrl(imageUrl);+ if (data && !ANTHROPIC_IMAGE_MEDIA_TYPES.has(data.mediaType)) {+ throw new UnsupportedResponsesFeatureError(`input_image media type '${data.mediaType}'`);+ }+ const remoteUrl = data ? null : validatedHttpUrl(imageUrl);+ if (!data && !remoteUrl) {+ throw new UnsupportedResponsesFeatureError('input_image.image_url scheme');+ }+ return {+ type: 'image',+ source: data+ ? { type: 'base64', media_type: data.mediaType, data: data.data }+ : { type: 'url', url: remoteUrl },+ };+ }+ const fileId = stringValue(part.file_id);+ if (fileId) {+ throw new UnsupportedResponsesFeatureError('input_image.file_id');+ }+ throw new UnsupportedResponsesFeatureError('input_image.image_url');+}++function documentBlockFromPart(part: JsonObject): JsonObject {+ const filename = stringValue(part.filename)?.trim();+ const fileUrl = stringValue(part.file_url);+ const fileData = stringValue(part.file_data);+ const remoteUrl = fileUrl ? validatedHttpUrl(fileUrl) : null;+ const data = fileData ? parseDataUrl(fileData) : null;+ if (fileUrl && !remoteUrl) {+ throw new UnsupportedResponsesFeatureError('input_file.file_url scheme');+ }+ if (fileData && !data) {+ throw new UnsupportedResponsesFeatureError('input_file.file_data');+ }+ if (!remoteUrl && !data) {+ if (stringValue(part.file_id)) {+ throw new UnsupportedResponsesFeatureError('input_file.file_id');+ }+ throw new UnsupportedResponsesFeatureError('input_file.file_url/file_data');+ }+ if (data && ANTHROPIC_TEXT_DOCUMENT_MEDIA_TYPES.has(data.mediaType)) {+ return {+ type: 'document',+ source: {+ type: 'text',+ media_type: 'text/plain',+ data: Buffer.from(data.data, 'base64').toString('utf8'),+ },+ ...(filename ? { title: filename } : {}),+ };+ }+ if (data && !ANTHROPIC_BASE64_DOCUMENT_MEDIA_TYPES.has(data.mediaType)) {+ throw new UnsupportedResponsesFeatureError(+ `input_file media type '${data.mediaType}'`,+ );+ }+ return {+ type: 'document',+ source: remoteUrl+ ? { type: 'url', url: remoteUrl }+ : { type: 'base64', media_type: data!.mediaType, data: data!.data },+ ...(filename ? { title: filename } : {}),+ };+}++function mediaBlockFromToolPart(part: JsonObject): JsonObject | null {+ const type = stringValue(part.type);+ if (type === 'input_image' || type === 'output_image' || type === 'image_url') {+ return imageBlockFromPart(part);+ }+ if (type === 'image') {+ if (stringValue(part.data)) {+ return {+ type: 'image',+ source: {+ type: 'base64',+ media_type: stringValue(part.mimeType) ?? stringValue(part.media_type) ?? 'image/png',+ data: part.data,+ },+ };+ }+ const source = isObject(part.source) ? part.source : null;+ if (source?.type === 'base64' && stringValue(source.data)) {+ return {+ type: 'image',+ source: {+ type: 'base64',+ media_type: stringValue(source.media_type) ?? 'image/png',+ data: source.data,+ },+ };+ }+ const sourceUrl = stringValue(source?.url);+ if (source?.type === 'url' && sourceUrl) {+ const url = validatedHttpUrl(sourceUrl);+ if (!url) return null;+ return {+ type: 'image',+ source: { type: 'url', url },+ };+ }+ }+ if (type === 'document' && isObject(part.source)) {+ const source = part.source;+ if (source.type === 'base64' && stringValue(source.data) && stringValue(source.media_type)) {+ const mediaType = stringValue(source.media_type)!.toLowerCase();+ if (mediaType === 'text/plain') {+ return {+ type: 'document',+ source: {+ type: 'text',+ media_type: 'text/plain',+ data: Buffer.from(stringValue(source.data)!, 'base64').toString('utf8'),+ },+ ...(stringValue(part.title) ? { title: part.title } : {}),+ };+ }+ if (!ANTHROPIC_BASE64_DOCUMENT_MEDIA_TYPES.has(mediaType)) return null;+ return {+ type: 'document',+ source: {+ type: 'base64',+ media_type: mediaType,+ data: source.data,+ },+ ...(stringValue(part.title) ? { title: part.title } : {}),+ };+ }+ const sourceUrl = stringValue(source.url);+ if (source.type === 'url' && sourceUrl) {+ const url = validatedHttpUrl(sourceUrl);+ if (!url) return null;+ return {+ type: 'document',+ source: { type: 'url', url },+ ...(stringValue(part.title) ? { title: part.title } : {}),+ };+ }+ }+ if (type === 'input_file' || type === 'file') {+ return documentBlockFromPart(part);+ }+ return null;+}++const MAX_TOOL_OUTPUT_JSON_DEPTH = 8;+const MAX_TOOL_OUTPUT_JSON_CHARS = 2 * 1024 * 1024;++function hasMediaBlocks(value: unknown): boolean {+ return Array.isArray(value) && value.some((item) => (+ isObject(item) && (item.type === 'image' || item.type === 'document')+ ));+}++function toolOutputBlocks(output: unknown, depth = 0): unknown {+ if (depth > MAX_TOOL_OUTPUT_JSON_DEPTH) {+ try {+ return JSON.stringify(output) ?? '(empty tool output)';+ } catch {+ return String(output);+ }+ }+ if (typeof output === 'string') {+ // MCP servers commonly serialize an Anthropic/OpenAI content array into the+ // function output string. Parse only bounded, JSON-looking strings and keep the+ // original text when no media was found, preserving the legacy wire payload.+ if (+ depth < MAX_TOOL_OUTPUT_JSON_DEPTH+ && output.length <= MAX_TOOL_OUTPUT_JSON_CHARS+ && /^[\s]*(?:\{|\[)/.test(output)+ ) {+ try {+ const parsed = JSON.parse(output) as unknown;+ const parsedBlocks = toolOutputBlocks(parsed, depth + 1);+ if (hasMediaBlocks(parsedBlocks)) return parsedBlocks;+ } catch {+ // Not JSON (or too deeply nested): keep it as ordinary tool text.+ }+ }+ return isMeaningfulText(output) ? output : '(empty tool output)';+ }+ if (!Array.isArray(output)) {+ if (isObject(output)) {+ const directMedia = mediaBlockFromToolPart(output);+ if (directMedia) return [directMedia];+ const nested = Array.isArray(output.content)+ ? toolOutputBlocks(output.content, depth + 1)+ : Array.isArray(output.output)+ ? toolOutputBlocks(output.output, depth + 1)+ : null;+ if (nested && hasMediaBlocks(nested)) return nested;+ }+ try {+ return JSON.stringify(output) ?? '(empty tool output)';+ } catch {+ return String(output);+ }+ }+ const blocks: JsonObject[] = [];+ for (const raw of output) {+ if (typeof raw === 'string') {+ if (isMeaningfulText(raw)) blocks.push(textPart(raw));+ continue;+ }+ if (!isObject(raw)) {+ blocks.push(textPart(String(raw)));+ continue;+ }+ const media = mediaBlockFromToolPart(raw);+ if (media) {+ blocks.push(media);+ continue;+ }+ const nested = Array.isArray(raw.content)+ ? toolOutputBlocks(raw.content, depth + 1)+ : Array.isArray(raw.output)+ ? toolOutputBlocks(raw.output, depth + 1)+ : null;+ if (nested && hasMediaBlocks(nested)) {+ if (Array.isArray(nested)) blocks.push(...nested.filter(isObject));+ continue;+ }+ const type = stringValue(raw.type);+ if (type === 'input_text' || type === 'output_text' || type === 'text' || type === 'refusal') {+ const text = stringValue(raw.text) ?? stringValue(raw.refusal);+ if (text && isMeaningfulText(text)) blocks.push(textPart(text));+ continue;+ }+ if (type === 'input_file' || type === 'file') {+ blocks.push(documentBlockFromPart(raw));+ continue;+ }+ blocks.push(textPart(JSON.stringify(raw)));+ }+ return blocks.length > 0 ? blocks : '(empty tool output)';+}++function collectToolSearchTools(value: unknown): unknown[] {+ if (!Array.isArray(value)) return [];+ const output: unknown[] = [];+ for (const item of value) {+ if (+ isObject(item)+ && (item.type === 'tool_search_output' || item.type === 'tool_search_call_output')+ && Array.isArray(item.tools)+ ) {+ output.push(...item.tools);+ }+ }+ return output;+}++function containsTopLevelItemType(value: unknown, expected: string): boolean {+ return Array.isArray(value)+ && value.some((item) => isObject(item) && item.type === expected);+}++const SCHEMA_NAME_BAGS = new Set(['properties', 'patternProperties', '$defs', 'definitions']);+const SCHEMA_LITERAL_VALUE_KEYS = new Set(['const', 'default', 'enum', 'examples']);++function stripEncryptedSchemaMarker(+ value: unknown,+ inNameBag = false,+): unknown {+ if (Array.isArray(value)) return value.map((item) => stripEncryptedSchemaMarker(item));+ if (!isObject(value)) return value;+ const output: JsonObject = {};+ for (const [key, child] of Object.entries(value)) {+ if (inNameBag) {+ output[key] = stripEncryptedSchemaMarker(child);+ } else if (key !== 'encrypted') {+ output[key] = SCHEMA_LITERAL_VALUE_KEYS.has(key)+ ? child+ : stripEncryptedSchemaMarker(child, SCHEMA_NAME_BAGS.has(key));+ }+ }+ return output;+}++function schemaForAnthropic(value: unknown): JsonObject {+ const stripped = stripEncryptedSchemaMarker(value);+ const source = isObject(stripped) ? stripped : {};+ // Anthropic requires a root object schema, but oneOf/anyOf/allOf remain valid+ // constraints on that object. Preserve them verbatim instead of merging variants,+ // which would weaken mutually exclusive required-property contracts.+ return {+ ...source,+ type: 'object',+ properties: isObject(source.properties) ? source.properties : {},+ };+}++function safeToolName(value: string, fallback: string): string {+ const trimmed = value.trim();+ return trimmed.length > 0 ? trimmed : fallback;+}++function shortHash(value: string): string {+ return createHash('sha256').update(value, 'utf8').digest('hex').slice(0, 12);+}++function clampToolName(value: string): string {+ const normalized = value.replace(/[^A-Za-z0-9_-]/g, '_') || 'tool';+ const changed = normalized !== value;+ const suffix = changed ? `__${shortHash(value)}` : '';+ if (!changed && normalized.length <= TOOL_NAME_MAX_LENGTH) return normalized;+ const hashSuffix = suffix || `__${shortHash(value)}`;+ return `${normalized.slice(0, TOOL_NAME_MAX_LENGTH - hashSuffix.length)}${hashSuffix}`;+}++function wireToolName(+ responseName: string,+ namespace: string | undefined,+ oauth: boolean,+): string {+ const flat = namespace ? `${namespace}__${responseName}` : responseName;+ const prefixed = oauth+ && !ANTHROPIC_BUILTIN_TOOLS.has(responseName.toLowerCase())+ && !flat.toLowerCase().startsWith(CLAUDE_OAUTH_TOOL_PREFIX)+ ? `${CLAUDE_OAUTH_TOOL_PREFIX}${flat}`+ : flat;+ return clampToolName(prefixed);+}++function responseToolIdentity(+ kind: ToolCallKind,+ name: string,+ namespace?: string,+): string {+ const identityKind = kind === 'namespace' ? 'function' : kind;+ return `${identityKind}\0${namespace ?? ''}\0${name}`;+}++function sameResponseToolKind(left: ToolCallKind, right: ToolCallKind): boolean {+ const normalizedLeft = left === 'namespace' ? 'function' : left;+ const normalizedRight = right === 'namespace' ? 'function' : right;+ return normalizedLeft === normalizedRight;+}++function reserveWireToolName(+ preferred: string,+ mapping: ToolCallMapping,+ existingByWireName: ReadonlyMap<string, ToolCallMapping>,+): string {+ const identity = responseToolIdentity(mapping.kind, mapping.name, mapping.namespace);+ const existing = existingByWireName.get(preferred);+ if (!existing || responseToolIdentity(existing.kind, existing.name, existing.namespace) === identity) {+ return preferred;+ }+ for (let attempt = 0; ; attempt += 1) {+ const suffix = `__${shortHash(attempt === 0 ? identity : `${identity}\0${attempt}`)}`;+ const candidate = `${preferred.slice(0, TOOL_NAME_MAX_LENGTH - suffix.length)}${suffix}`;+ const occupant = existingByWireName.get(candidate);+ if (+ !occupant+ || responseToolIdentity(occupant.kind, occupant.name, occupant.namespace) === identity+ ) {+ return candidate;+ }+ }+}++function flattenTools(+ tools: unknown[] | undefined,+ oauth: boolean,+ strictTools: boolean,+): { tools?: unknown[]; context: ToolContext } {+ if (!tools?.length) {+ return { context: { byWireName: new Map(), byResponseName: new Map() } };+ }+ const converted: unknown[] = [];+ const byWireName = new Map<string, ToolCallMapping>();+ const byResponseName = new Map<string, ToolCallMapping>();++ const add = (+ name: string,+ description: string | undefined,+ parameters: unknown,+ kind: ToolCallKind,+ namespace?: string,+ strict?: boolean,+ ): void => {+ const responseName = safeToolName(name, 'tool');+ const baseMapping = {+ wireName: '',+ name: responseName,+ ...(namespace ? { namespace } : {}),+ kind,+ } satisfies ToolCallMapping;+ const wireName = reserveWireToolName(+ wireToolName(responseName, namespace, oauth),+ baseMapping,+ byWireName,+ );+ const mapping: ToolCallMapping = { ...baseMapping, wireName };+ if (byWireName.has(wireName)) return;+ byWireName.set(wireName, mapping);+ byResponseName.set(responseToolIdentity(kind, responseName, namespace), mapping);+ const inputSchema = kind === 'custom'+ ? {+ type: 'object',+ properties: {+ input: {+ type: 'string',+ description: 'The free-form input for this custom tool.',+ },+ },+ required: ['input'],+ }+ : schemaForAnthropic(parameters);+ converted.push({+ name: wireName,+ ...(description ? { description } : {}),+ input_schema: inputSchema,+ ...(strictTools && strict !== undefined ? { strict } : {}),+ });+ };++ for (const raw of tools) {+ if (!isObject(raw)) continue;+ const type = stringValue(raw.type);+ if (type === 'function' || type === 'custom') {+ add(+ stringValue(raw.name) ?? (isObject(raw.function) ? stringValue(raw.function.name) : undefined) ?? 'tool',+ stringValue(raw.description) ?? (isObject(raw.function) ? stringValue(raw.function.description) : undefined),+ raw.parameters ?? (isObject(raw.function) ? raw.function.parameters : undefined),+ type === 'custom' ? 'custom' : 'function',+ undefined,+ typeof raw.strict === 'boolean'+ ? raw.strict+ : isObject(raw.function) && typeof raw.function.strict === 'boolean'+ ? raw.function.strict+ : undefined,+ );+ continue;+ }+ if (type === 'namespace') {+ const namespace = safeToolName(stringValue(raw.name) ?? 'namespace', 'namespace');+ const members = Array.isArray(raw.tools)+ ? raw.tools+ : Array.isArray(raw.functions)+ ? raw.functions+ : [];+ for (const member of members) {+ if (!isObject(member)) continue;+ const memberType = stringValue(member.type);+ if (memberType !== 'function' && memberType !== 'custom') continue;+ add(+ stringValue(member.name) ?? (isObject(member.function) ? stringValue(member.function.name) : undefined) ?? 'tool',+ stringValue(member.description) ?? (isObject(member.function) ? stringValue(member.function.description) : undefined),+ member.parameters ?? (isObject(member.function) ? member.function.parameters : undefined),+ memberType === 'custom' ? 'custom' : 'namespace',+ namespace,+ typeof member.strict === 'boolean'+ ? member.strict+ : isObject(member.function) && typeof member.function.strict === 'boolean'+ ? member.function.strict+ : undefined,+ );+ }+ continue;+ }+ if (type === 'tool_search' || type === 'tool_search_call') {+ add('tool_search', stringValue(raw.description), raw.parameters, 'tool_search');+ continue;+ }+ // Hosted tools such as web_search are not executable by Cindy's local tool loop. They+ // must not make the whole bridge fail; the model can still use regular function tools.+ }+ return {+ tools: converted.length > 0 ? converted : undefined,+ context: { byWireName, byResponseName },+ };+}++function decodeBase64Url(value: string): string | null {+ try {+ const normalized = value.replace(/-/g, '+').replace(/_/g, '/');+ return Buffer.from(normalized, 'base64').toString('utf8');+ } catch {+ return null;+ }+}++export function encodeThinkingBlock(block: JsonObject): string | null {+ const type = stringValue(block.type);+ const valid = (type === 'thinking' && typeof block.signature === 'string' && block.signature.length > 0)+ || (type === 'redacted_thinking' && typeof block.data === 'string' && block.data.length > 0);+ if (!valid) return null;+ return `${THINKING_PREFIX}${Buffer.from(JSON.stringify(block), 'utf8').toString('base64url')}`;+}++export function decodeThinkingBlock(value: string): JsonObject | null {+ if (!value.startsWith(THINKING_PREFIX)) return null;+ const decoded = decodeBase64Url(value.slice(THINKING_PREFIX.length));+ if (!decoded) return null;+ try {+ const block = JSON.parse(decoded) as unknown;+ return isObject(block) && encodeThinkingBlock(block) !== null ? block : null;+ } catch {+ return null;+ }+}++function responseNameForMapping(+ context: ToolContext,+ name: string,+ namespace?: string,+ kind: ToolCallKind = 'function',+ oauth = false,+): ToolCallMapping {+ const normalizedNamespace = namespace?.trim();+ const byIdentity = context.byResponseName.get(+ responseToolIdentity(kind, name, normalizedNamespace),+ );+ const byWireName = context.byWireName.get(+ normalizedNamespace ? `${normalizedNamespace}__${name}` : name,+ );+ const exact = byIdentity ?? (+ byWireName && sameResponseToolKind(byWireName.kind, kind)+ ? byWireName+ : undefined+ );+ return exact ?? {+ wireName: wireToolName(name, normalizedNamespace, oauth),+ name,+ ...(normalizedNamespace ? { namespace: normalizedNamespace } : {}),+ kind: kind === 'function' && normalizedNamespace ? 'namespace' : kind,+ };+}++function reasoningBlock(item: JsonObject): JsonObject | null {+ const encrypted = stringValue(item.encrypted_content);+ return encrypted ? decodeThinkingBlock(encrypted) : null;+}++function inputContentToAnthropic(+ content: unknown,+ role: 'user' | 'assistant',+): JsonObject[] {+ if (typeof content === 'string') return isMeaningfulText(content) ? [textPart(content)] : [];+ if (!Array.isArray(content)) throw new UnsupportedResponsesFeatureError('message.content');+ const blocks: JsonObject[] = [];+ for (const raw of content) {+ if (!isObject(raw)) throw new UnsupportedResponsesFeatureError('message.content');+ const type = stringValue(raw.type);+ if (type === 'input_text' || type === 'output_text' || type === 'text') {+ const text = stringValue(raw.text);+ if (text && isMeaningfulText(text)) blocks.push(textPart(text));+ continue;+ }+ if (type === 'refusal') {+ const refusal = stringValue(raw.refusal);+ if (refusal && isMeaningfulText(refusal)) blocks.push(textPart(refusal));+ continue;+ }+ if (type === 'input_image') {+ const image = imageBlockFromPart(raw);+ blocks.push(image);+ continue;+ }+ if (type === 'image_url') {+ blocks.push(imageBlockFromPart(raw));+ continue;+ }+ if (type === 'input_file' || type === 'file') {+ blocks.push(documentBlockFromPart(raw));+ continue;+ }+ throw new UnsupportedResponsesFeatureError(`message.content.${type ?? 'unknown'}`);+ }+ // Anthropic assistant messages cannot contain input_image blocks. Avoid a silent+ // role change: fail clearly so a caller can remove the invalid history item.+ if (+ role === 'assistant'+ && blocks.some((block) => block.type === 'image' || block.type === 'document')+ ) {+ throw new UnsupportedResponsesFeatureError('assistant image content');+ }+ return blocks;+}++function appendMessage(+ messages: Array<{ role: 'user' | 'assistant'; content: JsonObject[] }>,+ role: 'user' | 'assistant',+ content: JsonObject[],+): void {+ if (content.length === 0) return;+ const last = messages[messages.length - 1];+ if (last?.role === role) last.content.push(...content);+ else messages.push({ role, content });+}++function orphanToolResultBlock(block: JsonObject): JsonObject {+ const id = typeof block.tool_use_id === 'string' ? block.tool_use_id : 'unknown';+ return textPart(`[orphan tool_result ${id} omitted from replay]`);+}++function repairToolHistory(+ messages: Array<{ role: 'user' | 'assistant'; content: JsonObject[] }>,+): void {+ for (let i = 0; i < messages.length; i += 1) {+ const message = messages[i];+ if (message.role === 'user') {+ const previous = messages[i - 1];+ const followsToolUse = previous?.role === 'assistant'+ && previous.content.some((block) => block.type === 'tool_use');+ if (!followsToolUse) {+ message.content = message.content.map((block) => (+ block.type === 'tool_result' ? orphanToolResultBlock(block) : block+ ));+ }+ continue;+ }++ const thinking = message.content.filter((block) => (+ block.type === 'thinking' || block.type === 'redacted_thinking'+ ));+ const nonThinking = message.content.filter((block) => (+ block.type !== 'thinking' && block.type !== 'redacted_thinking'+ ));+ message.content = [...thinking, ...nonThinking];+ const calls = message.content.filter((block) => (+ block.type === 'tool_use' && typeof block.id === 'string'+ ));+ if (calls.length === 0) continue;++ const next = messages[i + 1];+ if (!next || next.role !== 'user') {+ messages.splice(i + 1, 0, {+ role: 'user',+ content: calls.map((call) => ({+ type: 'tool_result',+ tool_use_id: String(call.id),+ content: '[missing tool_result in history]',+ is_error: true,+ })),+ });+ i += 1;+ continue;+ }++ const resultBlocks = next.content.filter((block) => block.type === 'tool_result');+ const otherBlocks = next.content.filter((block) => block.type !== 'tool_result');+ const consumed = new Set<number>();+ const ordered: JsonObject[] = [];+ for (const call of calls) {+ const id = String(call.id);+ const resultIndex = resultBlocks.findIndex((block, index) => (+ !consumed.has(index) && block.tool_use_id === id+ ));+ if (resultIndex >= 0) {+ consumed.add(resultIndex);+ ordered.push(resultBlocks[resultIndex]);+ } else {+ ordered.push({+ type: 'tool_result',+ tool_use_id: id,+ content: '[missing tool_result in history]',+ is_error: true,+ });+ }+ }+ const orphans = resultBlocks+ .filter((_, index) => !consumed.has(index))+ .map(orphanToolResultBlock);+ next.content = [...ordered, ...orphans, ...otherBlocks];+ i += 1;+ }+}++function normalizeMessages(+ messages: Array<{ role: 'user' | 'assistant'; content: JsonObject[] }>,+): Array<{ role: 'user' | 'assistant'; content: JsonObject[] }> {+ const compacted: Array<{ role: 'user' | 'assistant'; content: JsonObject[] }> = [];+ for (const message of messages) appendMessage(compacted, message.role, message.content);+ if (compacted.length === 0) {+ compacted.push({ role: 'user', content: [textPart(CONTINUE_TEXT)] });+ } else if (compacted[0].role !== 'user') {+ // Anthropic history must begin with user, but dropping an assistant/tool turn would+ // lose the exact call ids Codex replays. Keep the history and add a deterministic+ // resume marker before it.+ compacted.unshift({ role: 'user', content: [textPart(CONTINUE_TEXT)] });+ }+ repairToolHistory(compacted);+ const last = compacted[compacted.length - 1];+ if (last.role === 'assistant') compacted.push({ role: 'user', content: [textPart(CONTINUE_TEXT)] });+ return compacted;+}++/**+ * Anthropic requires a tool-result continuation to replay the signed thinking block+ * from the immediately preceding assistant tool turn. A fresh user turn is always safe.+ */+function trailingTurnSupportsThinking(+ messages: Array<{ role: 'user' | 'assistant'; content: JsonObject[] }>,+): boolean {+ const userIndex = messages.findLastIndex((message) => message.role === 'user');+ if (userIndex < 0) return true;+ const results = messages[userIndex].content.filter((block) => block.type === 'tool_result');+ if (results.length === 0) return true;+ const assistant = messages[userIndex - 1];+ if (!assistant || assistant.role !== 'assistant') return false;+ const signedThinking = assistant.content.some((block) => (+ (block.type === 'thinking' && typeof block.signature === 'string' && block.signature.length > 0)+ || (block.type === 'redacted_thinking' && typeof block.data === 'string' && block.data.length > 0)+ ));+ if (!signedThinking) return false;+ const callIds = new Set(+ assistant.content+ .filter((block) => block.type === 'tool_use' && typeof block.id === 'string')+ .map((block) => String(block.id)),+ );+ return results.every((block) => (+ typeof block.tool_use_id === 'string' && callIds.has(block.tool_use_id)+ ));+}++function effortBudget(effort: string | undefined): number | null {+ switch ((effort ?? '').trim().toLowerCase()) {+ case 'minimal': return 2048;+ case 'low': return 4096;+ case 'medium': return 8192;+ case 'high': return 16384;+ case 'xhigh':+ case 'max':+ case 'ultra': return 24576;+ default: return null;+ }+}++function normalizedEffort(effort: string | undefined): string | null {+ switch ((effort ?? '').trim().toLowerCase()) {+ case 'minimal':+ case 'low': return 'low';+ case 'medium': return 'medium';+ case 'high': return 'high';+ case 'xhigh':+ case 'max':+ case 'ultra': return 'max';+ default: return null;+ }+}++function supportsAdaptiveThinkingByModel(model: string): boolean {+ const normalized = model.trim().toLowerCase().replace(/[._]/g, '-');+ return ['fable-5', 'mythos-5', 'mythos-preview', 'sonnet-5']+ .some((needle) => normalized.includes(needle))+ || /claude-opus-4-(?:7|8)(?:-|$)/.test(normalized)+ || /claude-sonnet-5(?:-|$)/.test(normalized);+}++function adaptiveThinkingByDefault(model: string): boolean {+ const normalized = model.trim().toLowerCase().replace(/[._]/g, '-');+ return ['fable-5', 'mythos-5', 'mythos-preview', 'sonnet-5']+ .some((needle) => normalized.includes(needle));+}++function thinkingCannotBeDisabled(model: string): boolean {+ const normalized = model.trim().toLowerCase().replace(/[._]/g, '-');+ return normalized.includes('fable-5') || normalized.includes('mythos-5');+}++function mapToolChoice(value: unknown, context: ToolContext, oauth: boolean): unknown {+ if (typeof value === 'string') {+ if (value === 'required') return { type: 'any' };+ if (value === 'none') return { type: 'none' };+ return { type: 'auto' };+ }+ if (!isObject(value)) return { type: 'auto' };+ if (value.type === 'function' || value.type === 'custom') {+ const nestedFunction = isObject(value.function) ? value.function : undefined;+ const name = stringValue(value.name) ?? stringValue(nestedFunction?.name) ?? '';+ const mapping = responseNameForMapping(+ context,+ name,+ stringValue(value.namespace),+ value.type === 'custom' ? 'custom' : 'function',+ oauth,+ );+ return { type: 'tool', name: mapping.wireName };+ }+ if (value.type === 'tool_search') {+ const mapping = responseNameForMapping(context, 'tool_search', undefined, 'tool_search', oauth);+ return { type: 'tool', name: mapping.wireName };+ }+ if (value.type === 'allowed_tools') {+ return { type: value.mode === 'required' ? 'any' : 'auto' };+ }+ return { type: 'auto' };+}++function assertSupportedToolChoice(value: unknown): void {+ if (!isObject(value)) return;+ const type = stringValue(value.type);+ if (+ type === 'function'+ || type === 'custom'+ || type === 'tool_search'+ || type === 'allowed_tools'+ || type === 'auto'+ || type === 'none'+ ) {+ return;+ }+ throw new UnsupportedResponsesFeatureError(`tool_choice type '${type ?? 'unknown'}'`);+}++function filterToolsForChoice(+ tools: unknown[] | undefined,+ choice: unknown,+ context: ToolContext,+ oauth: boolean,+): unknown[] | undefined {+ if (!tools?.length || !isObject(choice) || choice.type !== 'allowed_tools' || !Array.isArray(choice.tools)) {+ return tools;+ }+ const allowed = new Set<string>();+ for (const raw of choice.tools) {+ if (typeof raw === 'string' && raw.trim()) {+ const name = raw.trim();+ const mapping = responseNameForMapping(context, name, undefined, 'function', oauth);+ allowed.add(mapping.wireName);+ continue;+ }+ if (!isObject(raw)) continue;+ const name = stringValue(raw.name)+ ?? (isObject(raw.function) ? stringValue(raw.function.name) : undefined);+ const namespace = stringValue(raw.namespace);+ if (name) {+ const kind = raw.type === 'custom'+ ? 'custom'+ : raw.type === 'tool_search'+ ? 'tool_search'+ : 'function';+ const mapping = responseNameForMapping(context, name, namespace, kind, oauth);+ allowed.add(mapping.wireName);+ }+ }+ if (allowed.size === 0) return [];+ return tools.filter((tool) => (+ isObject(tool) && typeof tool.name === 'string' && allowed.has(tool.name)+ ));+}++function requiresToolCall(value: unknown): boolean {+ if (value === 'required') return true;+ if (!isObject(value)) return false;+ if (value.type === 'allowed_tools') return value.mode === 'required';+ if (value.type === 'auto' || value.type === 'none') return false;+ return true;+}++function forcedToolChoice(value: unknown): boolean {+ if (!isObject(value)) return false;+ return value.type === 'any' || value.type === 'tool' || (+ value.type === 'allowed_tools' && value.mode === 'required'+ );+}++function stopSequences(value: ResponsesRequest['stop']): string[] | undefined {+ if (value === undefined || value === null) return undefined;+ const values = typeof value === 'string' ? [value] : value;+ if (!Array.isArray(values) || values.some((entry) => typeof entry !== 'string')) {+ throw new InvalidResponsesRequestError('Responses stop must be a string or an array of strings');+ }+ const nonEmpty = values.filter((entry) => entry.length > 0);+ return nonEmpty.length > 0 ? nonEmpty : undefined;+}++function assertSupportedResponseFormat(raw: ResponsesRequest): void {+ const formats: Array<[string, unknown]> = [+ ['response_format', raw.response_format],+ ['text.format', isObject(raw.text) ? raw.text.format : undefined],+ ];+ for (const [field, value] of formats) {+ if (value === undefined) continue;+ if (isObject(value) && value.type === 'text') continue;+ throw new UnsupportedResponsesFeatureError(field);+ }+}++function applyPromptCaching(+ body: AnthropicRequest,+ enabled: boolean,+ automatic = false,+): void {+ if (!enabled) return;+ const cc: CacheControl = { type: 'ephemeral' };+ if (automatic) body.cache_control = cc;+ const explicitLimit = automatic ? MAX_CACHE_BREAKPOINTS - 1 : MAX_CACHE_BREAKPOINTS;+ let used = 0;+ const tools = body.tools as JsonObject[] | undefined;+ if (tools?.length) {+ tools[tools.length - 1] = { ...tools[tools.length - 1], cache_control: cc };+ used += 1;+ }+ if (used < explicitLimit && body.system?.length) {+ const last = body.system.length - 1;+ body.system[last] = { ...body.system[last], cache_control: cc };+ used += 1;+ }+ const userIndexes = body.messages+ .map((message, index) => message.role === 'user' ? index : -1)+ .filter((index) => index >= 0);+ // Native automatic caching already follows the moving final block. Explicitly+ // marking that same last user block wastes a breakpoint; retain only the stable+ // penultimate user turn in automatic mode.+ const cacheableUserIndexes = automatic+ ? userIndexes.slice(-2, -1)+ : userIndexes.slice(-2);+ for (const index of cacheableUserIndexes) {+ if (used >= explicitLimit) break;+ const message = body.messages[index];+ if (!Array.isArray(message.content) || message.content.length === 0) continue;+ const textIndex = [...message.content].map((block, i) => block.type === 'text' ? i : -1)+ .filter((i) => i >= 0).pop();+ const target = textIndex ?? message.content.length - 1;+ message.content[target] = { ...message.content[target], cache_control: cc };+ used += 1;+ }+}++export interface TranslateResponsesRequestOptions {+ model?: string;+ defaultMaxTokens?: number;+ supportsAdaptiveThinking?: (model: string) => boolean;+ supportsThinking?: (model: string) => boolean;+ promptCaching?: boolean;+ automaticPromptCaching?: boolean;+ strictTools?: boolean;+ authMode?: 'api-key' | 'oauth';+}++export interface TranslatedResponsesRequest {+ request: AnthropicRequest;+ toolContext: ToolContext;+}++export function translateResponsesRequest(+ raw: ResponsesRequest,+ options: TranslateResponsesRequestOptions = {},+): TranslatedResponsesRequest {+ if (!isObject(raw) || typeof raw.model !== 'string' || raw.model.length === 0) {+ throw new UnsupportedResponsesFeatureError('model');+ }+ assertSupportedResponseFormat(raw);+ const model = options.model ?? raw.model;+ const systemParts: string[] = [];+ const instructions = instructionsText(raw.instructions);+ if (isMeaningfulText(instructions)) systemParts.push(instructions);+ const oauth = options.authMode === 'oauth';+ if (oauth) systemParts.unshift(CLAUDE_CODE_SYSTEM_INSTRUCTION);+ const messages: Array<{ role: 'user' | 'assistant'; content: JsonObject[] }> = [];+ const dynamicTools = collectToolSearchTools(raw.input);+ const needsToolSearch = containsTopLevelItemType(raw.input, 'tool_search_call')+ || (isObject(raw.tool_choice) && raw.tool_choice.type === 'tool_search');+ const declaredTools = raw.tools?.length || dynamicTools.length || needsToolSearch+ ? [+ ...(raw.tools ?? []),+ ...dynamicTools,+ ...(needsToolSearch ? [{ type: 'tool_search', name: 'tool_search' }] : []),+ ]+ : undefined;+ const context = flattenTools(declaredTools, oauth, options.strictTools === true);+ assertSupportedToolChoice(raw.tool_choice);+ const input = raw.input;+ const items = typeof input === 'string'+ ? [{ role: 'user', content: input }]+ : Array.isArray(input) ? input : [];+ let assistant: { role: 'assistant'; content: JsonObject[] } | null = null;+ const incompleteCallIds = new Set<string>();+ const flushAssistant = (): void => {+ if (!assistant || assistant.content.length === 0) {+ assistant = null;+ return;+ }+ appendMessage(messages, 'assistant', assistant.content);+ assistant = null;+ };++ for (const rawItem of items) {+ if (!isObject(rawItem)) throw new UnsupportedResponsesFeatureError('input item');+ const type = stringValue(rawItem.type);+ if (type === 'reasoning') {+ const block = reasoningBlock(rawItem);+ if (block) {+ assistant ??= { role: 'assistant', content: [] };+ assistant.content.push(block);+ }+ continue;+ }+ if (type === 'function_call' || type === 'custom_tool_call' || type === 'tool_search_call') {+ const callId = stringValue(rawItem.call_id) ?? stringValue(rawItem.id);+ const rawName = stringValue(rawItem.name) ?? (type === 'tool_search_call' ? 'tool_search' : '');+ if (!callId || !rawName) throw new UnsupportedResponsesFeatureError(`${type}.call_id/name`);+ if (rawItem.status === 'incomplete') {+ incompleteCallIds.add(callId);+ continue;+ }+ const mapping = responseNameForMapping(+ context.context,+ rawName,+ stringValue(rawItem.namespace),+ type === 'custom_tool_call'+ ? 'custom'+ : type === 'tool_search_call'+ ? 'tool_search'+ : 'function',+ oauth,+ );+ assistant ??= { role: 'assistant', content: [] };+ let inputValue: JsonObject = {};+ if (type === 'custom_tool_call') {+ const customInput = rawItem.input;+ inputValue = isObject(customInput)+ && typeof customInput.input === 'string'+ ? customInput+ : { input: typeof customInput === 'string' ? customInput : JSON.stringify(customInput ?? '') };+ } else if (isObject(rawItem.arguments)) {+ inputValue = rawItem.arguments;+ } else if (typeof rawItem.arguments === 'string' && rawItem.arguments.trim()) {+ try {+ const parsed = JSON.parse(rawItem.arguments) as unknown;+ if (isObject(parsed)) inputValue = parsed;+ } catch {+ // A poisoned historical call must not invent a provider-specific input field.+ }+ }+ assistant.content.push({+ type: 'tool_use',+ id: callId,+ name: mapping.wireName,+ input: inputValue,+ });+ continue;+ }+ if (type === 'input_text' || type === 'input_image' || type === 'input_file') {+ flushAssistant();+ appendMessage(messages, 'user', inputContentToAnthropic([rawItem], 'user'));+ continue;+ }+ // A tool_search_output carrying discovered definitions is a control/history item,+ // not a tool result. Only the call-correlated form becomes tool_result content.+ if (+ type === 'tool_search_output'+ && !stringValue(rawItem.call_id)+ && !stringValue(rawItem.id)+ && Array.isArray(rawItem.tools)+ ) {+ continue;+ }+ if (+ type === 'function_call_output'+ || type === 'custom_tool_call_output'+ || type === 'tool_search_output'+ || type === 'tool_search_call_output'+ ) {+ flushAssistant();+ const callId = stringValue(rawItem.call_id) ?? stringValue(rawItem.id);+ if (!callId) throw new UnsupportedResponsesFeatureError(`${type}.call_id`);+ if (incompleteCallIds.has(callId)) continue;+ const output = rawItem.output+ ?? rawItem.content+ ?? (+ (type === 'tool_search_output' || type === 'tool_search_call_output')+ && Array.isArray(rawItem.tools)+ ? JSON.stringify(rawItem.tools)+ : ''+ );+ appendMessage(messages, 'user', [{+ type: 'tool_result',+ tool_use_id: callId,+ content: toolOutputBlocks(output),+ ...(rawItem.is_error === true ? { is_error: true } : {}),+ }]);+ continue;+ }+ if (typeof rawItem.role === 'string') {+ const role = rawItem.role;+ if (role === 'system' || role === 'developer') {+ const parts = inputContentToAnthropic(rawItem.content, 'user');+ for (const part of parts) if (part.type === 'text') systemParts.push(String(part.text));+ continue;+ }+ if (role !== 'user' && role !== 'assistant') throw new UnsupportedResponsesFeatureError(`input role '${role}'`);+ const parts = inputContentToAnthropic(rawItem.content, role);+ if (role === 'assistant') {+ assistant ??= { role: 'assistant', content: [] };+ assistant.content.push(...parts);+ } else {+ flushAssistant();+ appendMessage(messages, 'user', parts);+ }+ continue;+ }+ throw new UnsupportedResponsesFeatureError(`input item '${type ?? 'unknown'}'`);+ }+ flushAssistant();+ const normalizedMessages = normalizeMessages(messages);+ const maxTokens = Math.max(+ 1,+ Math.floor(numberValue(raw.max_output_tokens) ?? options.defaultMaxTokens ?? DEFAULT_MAX_TOKENS),+ );+ const effort = stringValue(raw.reasoning?.effort);+ const explicitlyDisabled = ['none', 'off', 'disabled'].includes((effort ?? '').toLowerCase());+ const budget = effortBudget(effort);+ const thinkingSupported = options.supportsThinking?.(model) ?? true;+ const adaptiveSupported =+ options.supportsAdaptiveThinking?.(model) ?? supportsAdaptiveThinkingByModel(model);+ const adaptive = adaptiveSupported+ && (adaptiveThinkingByDefault(model) || budget !== null);+ const cannotDisableThinking = thinkingSupported && thinkingCannotBeDisabled(model);+ const anth: AnthropicRequest = {+ model,+ messages: normalizedMessages,+ max_tokens: maxTokens,+ stream: raw.stream !== false,+ };+ if (systemParts.length > 0) {+ anth.system = oauth+ ? systemParts.map((text) => ({ type: 'text', text }))+ : [{ type: 'text', text: systemParts.join('\n\n') }];+ }+ const selectedTools = filterToolsForChoice(context.tools, raw.tool_choice, context.context, oauth);+ if ((!selectedTools || selectedTools.length === 0) && requiresToolCall(raw.tool_choice)) {+ throw new UnsupportedResponsesFeatureError(+ 'tool_choice requires a bridge-compatible tool',+ );+ }+ if (selectedTools && selectedTools.length > 0) anth.tools = selectedTools;+ if (anth.tools && raw.tool_choice !== undefined && raw.tool_choice !== 'none') {+ anth.tool_choice = mapToolChoice(raw.tool_choice, context.context, oauth);+ } else if (raw.tool_choice === 'none' && anth.tools) {+ anth.tool_choice = { type: 'none' };+ }+ if (raw.parallel_tool_calls === false && anth.tools) {+ const choice = isObject(anth.tool_choice) ? anth.tool_choice : { type: 'auto' };+ anth.tool_choice = { ...choice, disable_parallel_tool_use: true };+ }+ if (thinkingSupported) {+ if (explicitlyDisabled && cannotDisableThinking) {+ anth.thinking = { type: 'adaptive' };+ anth.output_config = { effort: 'low' };+ } else if (explicitlyDisabled) {+ anth.thinking = { type: 'disabled' };+ } else if (adaptive) {+ anth.thinking = { type: 'adaptive' };+ const normalized = normalizedEffort(effort);+ if (normalized) anth.output_config = { effort: normalized };+ if (numberValue(raw.max_output_tokens) === undefined) {+ anth.max_tokens = Math.max(anth.max_tokens, (budget ?? 8192) + OUTPUT_HEADROOM);+ }+ } else if (budget !== null) {+ const thinkingBudget = Math.max(MIN_THINKING_BUDGET, Math.min(budget, Math.max(MIN_THINKING_BUDGET, anth.max_tokens - OUTPUT_HEADROOM)));+ if (thinkingBudget >= MIN_THINKING_BUDGET && anth.max_tokens > thinkingBudget) {+ anth.thinking = { type: 'enabled', budget_tokens: thinkingBudget };+ }+ }+ }+ if (thinkingSupported && budget !== null && !explicitlyDisabled && !anth.thinking) {+ throw new InvalidResponsesRequestError(+ 'Responses reasoning effort cannot fit within max_output_tokens for the Anthropic bridge',+ );+ }+ if (+ anth.thinking+ && anth.thinking.type !== 'disabled'+ && (+ !trailingTurnSupportsThinking(normalizedMessages)+ || forcedToolChoice(anth.tool_choice)+ )+ ) {+ // Forced tool choice is incompatible with extended thinking. An unsigned+ // tool-result continuation is also rejected because its previous thinking block+ // cannot be replayed. Preserve tool/history correctness and disable thinking.+ if (cannotDisableThinking) {+ throw new InvalidResponsesRequestError(+ 'This Anthropic model requires signed thinking history for tool continuation or forced tool choice',+ );+ }+ anth.thinking = { type: 'disabled' };+ delete anth.output_config;+ }+ if (!anth.thinking || anth.thinking.type === 'disabled') {+ const temperature = anthropicSamplingValue('temperature', raw.temperature);+ const topP = anthropicSamplingValue('top_p', raw.top_p);+ if (temperature !== undefined) anth.temperature = temperature;+ if (topP !== undefined) anth.top_p = topP;+ }+ const mappedStopSequences = stopSequences(raw.stop);+ if (mappedStopSequences) anth.stop_sequences = mappedStopSequences;+ applyPromptCaching(+ anth,+ options.promptCaching !== false+ && (Boolean(raw.prompt_cache_key) || options.automaticPromptCaching === true),+ options.automaticPromptCaching === true,+ );+ return { request: anth, toolContext: context.context };+}diff --git a/packages/responses-anthropic-bridge/src/types.ts b/packages/responses-anthropic-bridge/src/types.tsnew file mode 100644index 0000000000..77cca7da0f--- /dev/null+++ b/packages/responses-anthropic-bridge/src/types.ts@@ -0,0 +1,164 @@+import type { ServerResponse } from 'node:http';++export interface ResponsesAnthropicLogger {+ debug?: (message: string, meta?: Record<string, unknown>) => void;+ info?: (message: string, meta?: Record<string, unknown>) => void;+ warn?: (message: string, meta?: Record<string, unknown>) => void;+ error?: (message: string, meta?: Record<string, unknown>) => void;+}++export interface ResponsesAnthropicRequestContext {+ readonly method: string;+ readonly url: string;+ readonly headers: Readonly<Record<string, string>>;+}++export interface ResponsesAnthropicErrorInfo {+ status: number;+ body: string;+ requestHeaders: Readonly<Record<string, string>>;+}++export interface ResponsesAnthropicAuthRetryInfo {+ status: 401 | 403;+ body: string;+ requestHeaders: Readonly<Record<string, string>>;+}++export interface AnthropicImageCodecInput {+ data: string;+ mediaType: string;+ maxEdge: number;+ qualities: readonly number[];+ hardCap: number;+}++export interface AnthropicImageCodecOutput {+ data: string;+ mediaType: string;+}++/**+ * Host-owned image codec. The bridge owns limit policy and ordering, while the host+ * supplies the native decoder/encoder available in its runtime.+ */+export interface AnthropicImageCodec {+ normalize(input: AnthropicImageCodecInput): Promise<AnthropicImageCodecOutput | null>;+}++export interface ResponsesAnthropicProviderConfig {+ /** Anthropic-compatible base URL; the default endpoint is `/v1/messages`. */+ upstreamBase: string;+ /** Optional exact endpoint path, for gateways that do not use `/v1/messages`. */+ requestPath?: string;+ /**+ * Request-policy mode only: API keys use the plain Messages contract, while+ * Claude.ai OAuth needs Claude Code policy. Credential refresh is controlled+ * independently by refreshHeaders.+ */+ authMode?: 'api-key' | 'oauth';+ /** Provider-owned headers. Never pass Codex/OpenAI OAuth headers here. */+ buildHeaders: () => Promise<Record<string, string>>;+ /** One-shot provider credential refresh hook invoked only after an upstream 401/403. */+ refreshHeaders?: (+ info: ResponsesAnthropicAuthRetryInfo,+ ) => Promise<Record<string, string> | null>;+ /** Rewrite the Responses wire model before sending it upstream. */+ rewriteModel?: (model: string) => string;+ /** Default max_tokens because Anthropic requires it even when Responses omits it. */+ defaultMaxTokens?: number;+ /** Whether this model family accepts `thinking: {type:"adaptive"}`. */+ supportsAdaptiveThinking?: (model: string) => boolean;+ /** Whether the upstream accepts Anthropic thinking fields at all. */+ supportsThinking?: (model: string) => boolean;+ /** Disable prompt cache breakpoints for a provider that does not implement them. */+ promptCaching?: boolean;+ /** Native Anthropic endpoints support top-level automatic prompt caching. */+ automaticPromptCaching?: boolean;+ /** Preserve Responses `strict` on tools only when the upstream Messages schema supports it. */+ strictTools?: boolean;+ /** Optional native image codec; limits still apply when no codec is available. */+ imageCodec?: AnthropicImageCodec;+ /** Called after a non-2xx response, before the translated error is returned. */+ onUpstreamError?: (info: ResponsesAnthropicErrorInfo) => void | Promise<void>;+}++export interface ResponsesAnthropicHandleArgs {+ parsedBody: unknown;+ ctx: ResponsesAnthropicRequestContext;+ res: ServerResponse;+}++export interface ResponsesAnthropicHandler {+ handle(args: ResponsesAnthropicHandleArgs): Promise<void>;+}++export interface ResponsesRequest {+ model: string;+ instructions?: string | unknown[];+ input?: string | unknown[];+ tools?: unknown[];+ tool_choice?: unknown;+ parallel_tool_calls?: boolean;+ max_output_tokens?: number;+ reasoning?: { effort?: string; [key: string]: unknown };+ stream?: boolean;+ prompt_cache_key?: string;+ temperature?: number;+ top_p?: number;+ stop?: string | string[] | null;+ [key: string]: unknown;+}++export interface AnthropicRequest {+ model: string;+ system?: Array<{ type: 'text'; text: string; cache_control?: CacheControl }>;+ messages: Array<{ role: 'user' | 'assistant'; content: unknown }>;+ tools?: unknown[];+ tool_choice?: unknown;+ max_tokens: number;+ stream: boolean;+ thinking?: { type: 'enabled'; budget_tokens: number } | { type: 'adaptive' } | { type: 'disabled' };+ output_config?: { effort: string };+ temperature?: number;+ top_p?: number;+ stop_sequences?: string[];+ cache_control?: CacheControl;+ [key: string]: unknown;+}++export interface CacheControl {+ type: 'ephemeral';+ ttl?: '5m' | '1h';+}++export type ToolCallKind = 'function' | 'namespace' | 'custom' | 'tool_search';++export interface ToolCallMapping {+ wireName: string;+ name: string;+ namespace?: string;+ kind: ToolCallKind;+}++export interface ToolContext {+ byWireName: ReadonlyMap<string, ToolCallMapping>;+ byResponseName: ReadonlyMap<string, ToolCallMapping>;+}++export class UnsupportedResponsesFeatureError extends Error {+ readonly feature: string;++ constructor(feature: string) {+ super(`Responses feature is not supported by the Anthropic bridge: ${feature}`);+ this.name = 'UnsupportedResponsesFeatureError';+ this.feature = feature;+ }+}++export class InvalidResponsesRequestError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'InvalidResponsesRequestError';+ }+}diff --git a/packages/responses-anthropic-bridge/tsconfig.json b/packages/responses-anthropic-bridge/tsconfig.jsonnew file mode 100644index 0000000000..fefb71da01--- /dev/null+++ b/packages/responses-anthropic-bridge/tsconfig.json@@ -0,0 +1,17 @@+{+ "compilerOptions": {+ "target": "ESNext",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "resolveJsonModule": true,+ "isolatedModules": true,+ "noEmit": true,+ "sourceMap": true,+ "baseUrl": "."+ },+ "include": ["src/**/*"]+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d7094fe1c9..531993b9a8 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -107,6 +107,9 @@ importers:'@cindy/remote-file-service':specifier: workspace:*version: link:../../packages/remote-file-service+ '@cindy/responses-anthropic-bridge':+ specifier: workspace:*+ version: link:../../packages/responses-anthropic-bridge'@cindy/responses-chat-bridge':specifier: workspace:*version: link:../../packages/responses-chat-bridge@@ -1299,6 +1302,27 @@ importers:specifier: ^3.2.4version: 3.2.7(@types/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected])([email protected])([email protected])([email protected])+ packages/responses-anthropic-bridge:+ devDependencies:+ '@eslint/js':+ specifier: ^9.0.0+ version: 9.39.5+ '@types/node':+ specifier: '*'+ version: 25.9.5+ eslint:+ specifier: ^9.0.0+ version: 9.39.5([email protected])+ typescript:+ specifier: ^5.7.0+ version: 5.9.3+ typescript-eslint:+ specifier: ^8.0.0+ vitest:+ specifier: ^3.2.4+ version: 3.2.7(@types/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected])([email protected])([email protected])([email protected])+packages/responses-chat-bridge:devDependencies:'@eslint/js':diff --git a/scripts/test-workspaces.config.mjs b/scripts/test-workspaces.config.mjsindex 86726b5b3d..b0a9f62ae3 100644--- a/scripts/test-workspaces.config.mjs+++ b/scripts/test-workspaces.config.mjs@@ -190,6 +190,7 @@ export default {requiredUnitWorkspace('mobile', 'apps/mobile', { workers: 4, execution: 'exclusive' }),requiredUnitWorkspace('@cindy/anthropic-compat-proxy', 'packages/anthropic-compat-proxy'),requiredUnitWorkspace('@cindy/anthropic-responses-bridge', 'packages/anthropic-responses-bridge'),+ requiredUnitWorkspace('@cindy/responses-anthropic-bridge', 'packages/responses-anthropic-bridge'),requiredUnitWorkspace('@cindy/responses-chat-bridge', 'packages/responses-chat-bridge'),requiredUnitWorkspace('@cindy/auth-client', 'packages/auth-client'),requiredUnitWorkspace('@cindy/browser-control-runtime', 'packages/browser-control-runtime'),