Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): restore Gateway web_search for GPT-5.6 (#938)
DavidShenXD961b433bba8e
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.tsindex bbe565ad33..babb5e2c86 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts@@ -566,8 +566,8 @@ describe('codex proxy host', () => {// upstream 是函数形态(每请求现取,model-access 下发可运行期换 endpoint);// 断言其当前求值 = 网关 base + /v1upstream: expect.any(Function),- // [encrypted activeStrip, image generation activeStrip, instructions 注入, 跨来源压缩块兼容, strict gateway history 兼容, xAI Responses 兼容, ByteDance Seed tool 兼容, MiniMax effort 兼容, provider model rewrite, stripNonAnthropicFields]- transformRequest: [expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), mockState.stripNonAnthropicFields],+ // [encrypted activeStrip, image generation activeStrip, instructions 注入, Gateway 原生 web_search, 跨来源压缩块兼容, strict gateway history 兼容, xAI Responses 兼容, ByteDance Seed tool 兼容, MiniMax effort 兼容, provider model rewrite, stripNonAnthropicFields]+ transformRequest: [expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), mockState.stripNonAnthropicFields],routingTransform: expect.any(Function),recoveryRules: expect.arrayContaining([expect.objectContaining({ id: 'encrypted_content' }),@@ -602,6 +602,130 @@ describe('codex proxy host', () => {expect(mockState.capturedRegistry?.get('thread-1')).toBeUndefined();});+ 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');+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({+ url: 'http://127.0.0.1:43210',+ dispose: vi.fn(async () => undefined),+ });+ await host.ensureCodexProxyReady();+ host.registerComposed('session-gateway-search', 'thread-gateway-search', 'PRODUCT_PROMPT');+ setSessionProvider('session-gateway-search', 'xd');++ const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];+ let current: unknown = {+ model: 'gpt-5.6-sol',+ tools: [{ type: 'function', name: 'read_file' }],+ };+ const ctx = { method: 'POST', url: '/responses', headers: { 'thread-id': 'thread-gateway-search' } };+ for (const transform of transforms) {+ const next = transform(current, ctx);+ if (next !== null && next !== undefined) current = next;+ }++ expect(current).toEqual({+ model: 'gpt-5.6-sol',+ tools: [+ { type: 'function', name: 'read_file' },+ { type: 'web_search' },+ ],+ });++ // 未显式选择来源的 codex/ 模型仍由默认路由送往 Gateway。+ clearSessionProvider('session-gateway-search');+ current = { model: 'codex/gpt-5.6-sol' };+ for (const transform of transforms) {+ const next = transform(current, ctx);+ if (next !== null && next !== undefined) current = next;+ }+ expect(current).toEqual({+ model: 'codex/gpt-5.6-sol',+ tools: [{ type: 'web_search' }],+ });++ current = {+ model: 'codex/gpt-5.6-sol',+ tools: [{ type: 'web_search', external_web_access: false }],+ };+ for (const transform of transforms) {+ const next = transform(current, ctx);+ if (next !== null && next !== undefined) current = next;+ }+ expect(current).toEqual({+ model: 'codex/gpt-5.6-sol',+ tools: [{ type: 'web_search', external_web_access: false }],+ });+ });++ it('does not add Gateway native search to non-Gateway GPT-5.6 sessions', async () => {+ const host = await freshCodexProxyHost();+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({+ url: 'http://127.0.0.1:43210',+ dispose: vi.fn(async () => undefined),+ });+ await host.ensureCodexProxyReady();+ host.registerComposed('session-subscription-search', 'thread-subscription-search', 'PRODUCT_PROMPT');+ setSessionProvider('session-subscription-search', 'openai');+ host.setCodexProxyAuthInjection('oauth-bearer');++ const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];+ const routingTransform = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.routingTransform;+ const original = { model: 'gpt-5.6-sol' };+ let current: unknown = original;+ const ctx = { method: 'POST', url: '/responses', headers: { 'thread-id': 'thread-subscription-search' } };+ for (const transform of transforms) {+ const next = transform(current, ctx);+ if (next !== null && next !== undefined) current = next;+ }++ expect(current).toEqual(original);+ await expect(Promise.resolve(routingTransform(current, ctx))).resolves.toEqual({+ upstreamOverride: 'https://chatgpt.com/backend-api/codex',+ });+ host.clearCodexProxyAuthInjection();+ clearSessionProvider('session-subscription-search');+ });++ it('does not add native search when an OAuth Gateway session resolves to passthrough', async () => {+ const host = await freshCodexProxyHost();+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({+ url: 'http://127.0.0.1:43210',+ dispose: vi.fn(async () => undefined),+ });+ await host.ensureCodexProxyReady();+ host.registerComposed('session-gateway-passthrough', 'thread-gateway-passthrough', 'PRODUCT_PROMPT');+ setSessionProvider('session-gateway-passthrough', 'xd');+ host.setCodexProxyAuthInjection('oauth-bearer');+ host.setCodexProxyGatewayKeyReader(() => null);++ const proxyOptions = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0];+ const transforms = proxyOptions?.transformRequest ?? [];+ const routingTransform = proxyOptions?.routingTransform;+ const original = { model: 'gpt-5.6-sol' };+ const ctx = {+ method: 'POST',+ url: '/responses',+ headers: { 'thread-id': 'thread-gateway-passthrough' },+ };+ let transformed: unknown = original;+ for (const transform of transforms) {+ const next = transform(transformed, ctx);+ if (next !== null && next !== undefined) transformed = next;+ }++ expect(transformed).toEqual(original);+ expect(routingTransform(original, ctx)).toEqual({+ upstreamOverride: 'https://chatgpt.com/backend-api/codex',+ });++ host.clearCodexProxyAuthInjection();+ host.setCodexProxyGatewayKeyReader(() => null);+ clearSessionProvider('session-gateway-passthrough');+ });+it('normalizes xAI Codex Responses body before forwarding requests', async () => {const host = await freshCodexProxyHost();const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');@@ -1568,6 +1692,47 @@ describe('codex proxy host', () => {clearSessionProvider('session-xai-foreign');});+ it('restores native search when provider-oauth foreign-model fallback lands on Gateway', async () => {+ const host = await freshCodexProxyHost();+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({+ url: 'http://127.0.0.1:43210',+ dispose: vi.fn(async () => undefined),+ });+ await host.ensureCodexProxyReady();+ host.registerComposed('session-xai-search-fallback', 'thread-xai-search-fallback', 'PRODUCT_PROMPT');+ setSessionProvider('session-xai-search-fallback', 'xai');+ host.setCodexProxyAuthInjection('provider-oauth');+ host.setCodexProxyGatewayKeyReader(() => 'gw-key');++ const proxyOptions = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0];+ const transforms = proxyOptions?.transformRequest ?? [];+ const routingTransform = proxyOptions?.routingTransform;+ const current: Record<string, unknown> = { model: 'gpt-5.6-sol' };+ const ctx = {+ method: 'POST',+ url: '/responses',+ headers: { 'thread-id': 'thread-xai-search-fallback' },+ };+ let transformed: unknown = current;+ for (const transform of transforms) {+ const next = transform(transformed, ctx);+ if (next !== null && next !== undefined) transformed = next;+ }++ expect(transformed).toEqual({+ model: 'gpt-5.6-sol',+ tools: [{ type: 'web_search' }],+ });+ expect(routingTransform(current, ctx)).toEqual({+ headerOverride: { authorization: 'Bearer gw-key' },+ });++ host.clearCodexProxyAuthInjection();+ host.setCodexProxyGatewayKeyReader(() => null);+ clearSessionProvider('session-xai-search-fallback');+ });+it('dumps transformed request bodies when the debug env gate is enabled', async () => {process.env.XDT_CODEX_PROXY_DUMP_TRANSFORMED_BODY = '1';const host = await freshCodexProxyHost();@@ -1590,7 +1755,7 @@ describe('codex proxy host', () => {await host.ensureCodexProxyReady();const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];- expect(transforms).toHaveLength(11); // encrypted activeStrip, image generation activeStrip, instructions 注入, 跨来源压缩块兼容, strict gateway history 兼容, xAI Responses 兼容, ByteDance Seed tool 兼容, MiniMax effort 兼容, provider model rewrite, stripNonAnthropicFields, dump+ expect(transforms).toHaveLength(12); // encrypted activeStrip, image generation activeStrip, instructions 注入, Gateway 原生 web_search, 跨来源压缩块兼容, strict gateway history 兼容, xAI Responses 兼容, ByteDance Seed tool 兼容, MiniMax effort 兼容, provider model rewrite, stripNonAnthropicFields, dumpconst ctx = {method: 'POST',url: '/v1/responses',diff --git a/apps/desktop/src/main/maker-host/codex-proxy-host.ts b/apps/desktop/src/main/maker-host/codex-proxy-host.tsindex aad9da04a5..8d7719ba0b 100644--- a/apps/desktop/src/main/maker-host/codex-proxy-host.ts+++ b/apps/desktop/src/main/maker-host/codex-proxy-host.ts@@ -186,6 +186,56 @@ function createCodexTransform(): RequestTransform {return createInstructionsInjectionTransform({ registry, logger: log });}+/**+ * Codex Code Mode 对部分 GPT-5.6 网关模型不会发出 Responses 原生搜索声明:+ * 目录里的 `supports_search_tool` / `webSearch` 能力虽为 true,但 Gateway 只看最终+ * 请求的 `tools`。插件搜索是增强项,不能作为该基础能力的前置条件,因此在明确走+ * Cindy Gateway 的 GPT-5.6 请求中补回标准 `web_search` 工具;已有声明保持原样。+ */+function createGatewayNativeWebSearchTransform(): RequestTransform {+ return (body, ctx) => {+ if (!isPlainObject(body) || typeof body.model !== 'string') return null;+ const path = ctx.url.split('?', 1)[0] ?? ctx.url;+ if (ctx.method !== 'POST' || (!path.endsWith('/responses') && path !== '/responses')) return null;++ const model = body.model;+ const gatewayModel = model.replace(/^codex\//, '');+ if (!/^gpt-5\.6(?:$|[-.])/.test(gatewayModel)) return null;++ const sessionId = sessionIdFromTransformCtx(ctx);+ const authInjection = getCodexProxyAuthInjection();+ const canUseExplicitSessionRoute = Boolean(sessionId && (+ authInjection === 'oauth-bearer' ||+ isUserProviderSession(sessionId) ||+ isHostInjectedAuthSession(sessionId, 'codex')+ ));+ const explicitRouting = canUseExplicitSessionRoute && sessionId+ ? getSessionRoutingDescriptor(sessionId, 'codex', model)+ : null;+ const resolvedExplicitRoute = explicitRouting+ && sessionId+ && (authInjection === 'oauth-bearer' || authInjection === 'provider-oauth')+ ? resolveSessionRouteDecision(sessionId, 'codex', _readGatewayKey(), model)+ : null;+ const providerOAuthGatewayFallback = authInjection === 'provider-oauth'+ ? gatewayDefaultRouteDecision('codex', _readGatewayKey())+ : null;+ const isGatewaySession = explicitRouting+ ? explicitRouting.authStrategy === 'gateway-key' &&+ (authInjection === 'env-key' || resolvedExplicitRoute !== null)+ // provider-oauth 的显式来源越界后,实际路由会回落默认 Gateway;没有 descriptor+ // 时也必须与 createModelRoutingTransform 保持同源。+ : model.startsWith('codex/') ||+ authInjection === 'env-key' ||+ providerOAuthGatewayFallback !== null;+ if (!isGatewaySession) return null;++ const existingTools = Array.isArray(body.tools) ? body.tools : [];+ if (existingTools.some((tool) => isPlainObject(tool) && tool.type === 'web_search')) return null;+ return { ...body, tools: [...existingTools, { type: 'web_search' }] };+ };+}+function sessionIdFromTransformCtx(ctx: RequestTransformCtx): string | undefined {const threadId = selectedThreadIdFromHeaders(ctx.headers);return threadId ? threadToSession.get(threadId) : undefined;@@ -1462,6 +1512,7 @@ function createTransformRequestChain(): RequestTransform[] {strip: stripImageGenerationItemsWithoutIdFromBody,}),createCodexTransform(),+ createGatewayNativeWebSearchTransform(),// 必须先于 xAI/MiniMax 兼容改写:加密压缩块换成明文占位 message 后,后续// 针对具体供应商的 input 归一化才能按标准 message 处理它。createCrossProviderCompactionCompatTransform(),diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 5b7daaa132..d7094fe1c9 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -701,6 +701,15 @@ 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])+ cindy-protocol/packages/content-moderation-protocol:+ devDependencies:+ typescript:+ specifier: ^5.7.0+ version: 5.9.3+ 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])+cindy-protocol/packages/device-link-protocol:devDependencies:typescript: