Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(desktop): sanitize XD Gateway Grok tools (#2444)

Junshanafdf3d266f22
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
index 6525cb7033..36b29c3a2b 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
@@ -2396,8 +2396,8 @@ describe('codex proxy host', () => {
// upstream 是函数形态(每请求现取,model-access 下发可运行期换 endpoint);
// 断言其当前求值 = 网关 base + /v1
upstream: expect.any(Function),
- // [encrypted activeStrip, image generation activeStrip, provider-aware Guardian reviewer, locked Subagent route, instructions 注入, locked Subagent exec guard, Gateway 原生 web_search, 跨来源压缩块兼容, xAI ModelInput activeStrip, strict gateway history 兼容, xAI ModelInput sanitize, DeepSeek V4 custom tool 兼容, xAI Responses 兼容, ByteDance Seed tool 兼容, MiniMax effort 兼容, provider model rewrite, 视觉桥(controller 未注入 → 短路透传), stripNonAnthropicFields]
- transformRequest: [expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), mockState.stripNonAnthropicFields],
+ // [encrypted activeStrip, image generation activeStrip, provider-aware Guardian reviewer, locked Subagent route, instructions 注入, locked Subagent exec guard, Gateway 原生 web_search, 跨来源压缩块兼容, xAI ModelInput activeStrip, strict gateway history 兼容, xAI ModelInput sanitize, DeepSeek V4 custom tool 兼容, xAI Responses 兼容, XD Gateway Grok 兼容, ByteDance Seed tool 兼容, MiniMax effort 兼容, provider model rewrite, 视觉桥(controller 未注入 → 短路透传), stripNonAnthropicFields]
+ transformRequest: [expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), mockState.stripNonAnthropicFields],
routingTransform: expect.any(Function),
recoveryRules: expect.arrayContaining([
expect.objectContaining({ id: 'encrypted_content' }),
@@ -3542,6 +3542,73 @@ describe('codex proxy host', () => {
expect(out.tools).toEqual([{ type: 'x_search' }]);
});
+ it('first-party xAI 过滤空工具后仍保留 tool_choice:none,避免重新注入的 x_search 被调用', async () => {
+ const out = (await runXaiTransforms('none-after-filter', {
+ model: 'xai/grok-4.5',
+ tools: [{ type: 'namespace', name: 'multi_agent_v1', tools: [] }],
+ tool_choice: 'none',
+ parallel_tool_calls: false,
+ input: [{ role: 'user', content: 'hi' }],
+ })) as Record<string, unknown>;
+
+ expect(out.tools).toEqual([{ type: 'x_search' }]);
+ expect(out.tool_choice).toBe('none');
+ // x_search will be re-injected on this path, so preserve the serial
+ // tool-call setting to keep the injected search serial.
+ expect(out.parallel_tool_calls).toBe(false);
+ });
+
+ it('全量过滤后,对象形态的强制 tool_choice 收敛为 none(不删除、不放宽)', async () => {
+ // Every declared tool is unsupported and filtered, while an object-form
+ // forced choice still references one of them. The empty-tools branch
+ // must collapse the now-dangling forced choice to 'none' (x_search is
+ // re-injected afterwards) rather than deleting it — a missing choice
+ // would let Grok auto-call the injected search and widen the caller's
+ // authorization (PR #2444 Codex P1).
+ const out = (await runXaiTransforms('forced-choice-after-full-filter', {
+ model: 'xai/grok-4.5',
+ tools: [{ type: 'namespace', name: 'multi_agent_v1', tools: [] }],
+ tool_choice: { type: 'function', name: 'multi_agent_v1' },
+ input: [{ role: 'user', content: 'hi' }],
+ })) as Record<string, unknown>;
+
+ expect(out.tools).toEqual([{ type: 'x_search' }]);
+ expect(out.tool_choice).toBe('none');
+ });
+
+ it('全量过滤后保留 tool_choice:auto(不收敛为 none),让重新注入的 x_search 可被自动选择', async () => {
+ // 'auto' is a generic "choose any available tool" — it does not reference
+ // a specific (now-filtered) tool. Collapsing it to 'none' would
+ // wrongly prevent Grok from auto-calling the re-injected x_search.
+ // Distinguish it from forced choices that DO reference removed tools
+ // (PR #2444 Codex P2).
+ const out = (await runXaiTransforms('auto-after-full-filter', {
+ model: 'xai/grok-4.5',
+ tools: [{ type: 'namespace', name: 'multi_agent_v1', tools: [] }],
+ tool_choice: 'auto',
+ input: [{ role: 'user', content: 'hi' }],
+ })) as Record<string, unknown>;
+
+ expect(out.tools).toEqual([{ type: 'x_search' }]);
+ expect(out.tool_choice).toBe('auto');
+ });
+
+ it('first-party xAI cache-only search + tool_choice:none 不注入 x_search 且清理控制字段', async () => {
+ const out = (await runXaiTransforms('cache-only-none', {
+ model: 'xai/grok-4.5',
+ tools: [{ type: 'web_search', external_web_access: false }],
+ tool_choice: 'none',
+ parallel_tool_calls: false,
+ input: [{ role: 'user', content: 'hi' }],
+ })) as Record<string, unknown>;
+
+ // cache-only prohibition means x_search must NOT be re-injected, and
+ // without re-injected tools the control fields must be cleaned.
+ expect(out).not.toHaveProperty('tools');
+ expect(out).not.toHaveProperty('tool_choice');
+ expect(out).not.toHaveProperty('parallel_tool_calls');
+ });
+
it('上游已声明 x_search 时不重复注入,也不覆盖其参数', async () => {
const out = (await runXaiTransforms('already-declared', {
model: 'xai/grok-4.5',
@@ -3596,6 +3663,27 @@ describe('codex proxy host', () => {
expect(out.tool_choice).toBe('auto');
});
+ it('强制选择被过滤的 namespace 工具时收敛为 none,不放宽为 auto(即使补了 x_search)', async () => {
+ const out = await runXaiTransforms('forced-filtered', {
+ model: 'xai/grok-4.5',
+ tools: [
+ { type: 'function', name: 'exec_command' },
+ { type: 'namespace', name: 'multi_agent_v1', tools: [] },
+ ],
+ tool_choice: { type: 'namespace', name: 'multi_agent_v1' },
+ input: [{ role: 'user', content: 'hi' }],
+ }) as Record<string, unknown>;
+
+ // The forced namespace choice references a removed tool. Fail closed to
+ // 'none' even though x_search gets re-injected and exec_command survives —
+ // widening to 'auto' would let Grok call tools the caller never selected.
+ expect(out.tools).toEqual([
+ { type: 'function', name: 'exec_command' },
+ { type: 'x_search' },
+ ]);
+ expect(out.tool_choice).toBe('none');
+ });
+
it.each(['xai/grok-code-fast', 'xai/grok-build-preview'])(
'编码模型 %s 不注入(该系列没有 agentic 搜索工具面,带上会被上游拒)',
async (model) => {
@@ -4127,6 +4215,458 @@ describe('codex proxy host', () => {
expect(current).toEqual(original);
});
+ it('drops Codex namespace tools for XD Gateway Grok models', async () => {
+ const host = await freshCodexProxyHost();
+ const { setXdGatewayModels } = await import('../active-catalog.js');
+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');
+ setXdGatewayModels([{ id: 'x-ai/grok-4.5', agents: ['codex'] }]);
+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({
+ url: 'http://127.0.0.1:43210',
+ dispose: vi.fn(async () => undefined),
+ });
+ await host.ensureCodexProxyReady();
+ host.registerComposed('session-xd-grok', 'thread-xd-grok', 'PRODUCT_PROMPT');
+ setSessionProvider('session-xd-grok', 'xd');
+
+ try {
+ const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];
+ let current: unknown = {
+ model: 'x-ai/grok-4.5',
+ tools: [
+ { type: 'function', name: 'exec_command' },
+ { type: 'namespace', name: 'multi_agent_v1', tools: [] },
+ { type: 'web_search', external_web_access: true },
+ ],
+ tool_choice: { type: 'namespace', name: 'multi_agent_v1' },
+ parallel_tool_calls: false,
+ };
+ const ctx = {
+ method: 'POST',
+ url: '/responses',
+ headers: { 'thread-id': 'thread-xd-grok' },
+ };
+ for (const transform of transforms) {
+ const next = transform(current, ctx);
+ if (next !== null && next !== undefined) current = next;
+ }
+
+ expect(current).toEqual({
+ model: 'x-ai/grok-4.5',
+ tools: [
+ { type: 'function', name: 'exec_command' },
+ { type: 'web_search' },
+ ],
+ // The forced namespace choice references a removed tool; fail closed to
+ // 'none' rather than widening to 'auto' (which would let Grok call the
+ // surviving exec_command/web_search the caller never selected).
+ tool_choice: 'none',
+ parallel_tool_calls: false,
+ });
+ } finally {
+ clearSessionProvider('session-xd-grok');
+ setXdGatewayModels([]);
+ }
+ });
+
+ it('still sanitizes implicit-session Grok namespace tools while the gateway catalog is non-authoritative', async () => {
+ // A pending/failed /models fetch leaves xdGatewayModelsAuthoritative=false
+ // with an empty list. The empty list must NOT be used as negative evidence
+ // for an implicit session (no explicit provider): the env-key default route
+ // still sends it to XD, so leaving namespace tools untouched would re-trigger
+ // the schema 400 (PR #2444 Codex P1).
+ const host = await freshCodexProxyHost();
+ const { setXdGatewayModels, markXdGatewayModelAccessUnknown } = await import('../active-catalog.js');
+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');
+ setXdGatewayModels([]);
+ markXdGatewayModelAccessUnknown();
+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({
+ url: 'http://127.0.0.1:43210',
+ dispose: vi.fn(async () => undefined),
+ });
+ await host.ensureCodexProxyReady();
+ host.registerComposed('session-xd-grok-implicit', 'thread-xd-grok-implicit', 'PRODUCT_PROMPT');
+ clearSessionProvider('session-xd-grok-implicit');
+
+ try {
+ const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];
+ let current: unknown = {
+ model: 'x-ai/grok-4.5',
+ tools: [
+ { type: 'function', name: 'exec_command' },
+ { type: 'namespace', name: 'multi_agent_v1', tools: [] },
+ ],
+ };
+ const ctx = {
+ method: 'POST',
+ url: '/responses',
+ headers: { 'thread-id': 'thread-xd-grok-implicit' },
+ };
+ for (const transform of transforms) {
+ const next = transform(current, ctx);
+ if (next !== null && next !== undefined) current = next;
+ }
+
+ expect(current).toMatchObject({
+ model: 'x-ai/grok-4.5',
+ tools: [{ type: 'function', name: 'exec_command' }],
+ });
+ } finally {
+ clearSessionProvider('session-xd-grok-implicit');
+ setXdGatewayModels([], { authoritative: false });
+ }
+ });
+
+ it('sanitizes out-of-scope x-ai/grok tools even when the session belongs to a non-xd provider', async () => {
+ // A provider-oauth xAI session that sends an `x-ai/grok*` request falls
+ // through the xAI scope gate (xAI modelPrefixes cover `xai/`, not the
+ // gateway's `x-ai/` namespace) and is routed back to the XD Gateway by
+ // gatewayDefaultRouteDecision. The compat transform must still clean the
+ // namespace tools; returning early just because providerId === 'xai' left
+ // them untouched and re-triggered the Grok schema 400 (PR #2444 Codex P2).
+ const host = await freshCodexProxyHost();
+ const { setXdGatewayModels } = await import('../active-catalog.js');
+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');
+ setXdGatewayModels([{ id: 'x-ai/grok-4.5', agents: ['codex'] }], { authoritative: true });
+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({
+ url: 'http://127.0.0.1:43210',
+ dispose: vi.fn(async () => undefined),
+ });
+ await host.ensureCodexProxyReady();
+ host.registerComposed('session-xai-grok-fallback', 'thread-xai-grok-fallback', 'PRODUCT_PROMPT');
+ setSessionProvider('session-xai-grok-fallback', 'xai');
+
+ try {
+ const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];
+ let current: unknown = {
+ model: 'x-ai/grok-4.5',
+ tools: [
+ { type: 'function', name: 'exec_command' },
+ { type: 'namespace', name: 'multi_agent_v1', tools: [] },
+ ],
+ };
+ const ctx = {
+ method: 'POST',
+ url: '/responses',
+ headers: { 'thread-id': 'thread-xai-grok-fallback' },
+ };
+ for (const transform of transforms) {
+ const next = transform(current, ctx);
+ if (next !== null && next !== undefined) current = next;
+ }
+
+ expect(current).toMatchObject({
+ model: 'x-ai/grok-4.5',
+ tools: [{ type: 'function', name: 'exec_command' }],
+ });
+ } finally {
+ clearSessionProvider('session-xai-grok-fallback');
+ setXdGatewayModels([]);
+ }
+ });
+
+ it('cleans Grok namespace tools for a built-in openai session under env-key (passthrough to XD)', async () => {
+ // Under env-key auth injection, a built-in session provider (e.g. the
+ // default `openai` catalog entry with universal routing) is NOT adopted by
+ // the router; an x-ai/grok* request passes through to the default XD
+ // Gateway. The compat transform must still clean namespace tools even
+ // though providerRoutingServesWireModel returns true for the universal
+ // openai routing — trusting it would leave the tools untouched and
+ // re-trigger the Grok schema 400 (PR #2444 Codex P2).
+ const host = await freshCodexProxyHost();
+ const { setXdGatewayModels } = await import('../active-catalog.js');
+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');
+ setXdGatewayModels([{ id: 'x-ai/grok-4.5', agents: ['codex'] }], { authoritative: true });
+ host.setCodexProxyAuthInjection('env-key');
+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({
+ url: 'http://127.0.0.1:43210',
+ dispose: vi.fn(async () => undefined),
+ });
+ await host.ensureCodexProxyReady();
+ host.registerComposed('session-openai-envkey', 'thread-openai-envkey', 'PRODUCT_PROMPT');
+ setSessionProvider('session-openai-envkey', 'openai');
+
+ try {
+ const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];
+ let current: unknown = {
+ model: 'x-ai/grok-4.5',
+ tools: [
+ { type: 'function', name: 'exec_command' },
+ { type: 'namespace', name: 'multi_agent_v1', tools: [] },
+ ],
+ };
+ const ctx = {
+ method: 'POST',
+ url: '/responses',
+ headers: { 'thread-id': 'thread-openai-envkey' },
+ };
+ for (const transform of transforms) {
+ const next = transform(current, ctx);
+ if (next !== null && next !== undefined) current = next;
+ }
+
+ expect(current).toMatchObject({
+ model: 'x-ai/grok-4.5',
+ tools: [{ type: 'function', name: 'exec_command' }],
+ });
+ } finally {
+ clearSessionProvider('session-openai-envkey');
+ setXdGatewayModels([]);
+ }
+ });
+
+ it('drops Grok search when live web access is explicitly disabled', async () => {
+ const host = await freshCodexProxyHost();
+ const { setXdGatewayModels } = await import('../active-catalog.js');
+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');
+ setXdGatewayModels([{ id: 'x-ai/grok-4.5', agents: ['codex'] }]);
+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({
+ url: 'http://127.0.0.1:43210',
+ dispose: vi.fn(async () => undefined),
+ });
+ await host.ensureCodexProxyReady();
+ host.registerComposed('session-xd-grok-no-live-search', 'thread-xd-grok-no-live-search', 'PRODUCT_PROMPT');
+ setSessionProvider('session-xd-grok-no-live-search', 'xd');
+
+ try {
+ const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];
+ let current: unknown = {
+ model: 'x-ai/grok-4.5',
+ tools: [
+ { type: 'function', name: 'exec_command' },
+ { type: 'web_search', external_web_access: false },
+ ],
+ tool_choice: { type: 'web_search' },
+ parallel_tool_calls: true,
+ };
+ const ctx = {
+ method: 'POST',
+ url: '/responses',
+ headers: { 'thread-id': 'thread-xd-grok-no-live-search' },
+ };
+ for (const transform of transforms) {
+ const next = transform(current, ctx);
+ if (next !== null && next !== undefined) current = next;
+ }
+
+ expect(current).toEqual({
+ model: 'x-ai/grok-4.5',
+ tools: [{ type: 'function', name: 'exec_command' }],
+ // The forced web_search choice was dropped (cache-only prohibition);
+ // collapsing to 'none' keeps exec_command uncallable instead of
+ // silently widening the request to auto-selected tool calls.
+ tool_choice: 'none',
+ parallel_tool_calls: true,
+ });
+ } finally {
+ clearSessionProvider('session-xd-grok-no-live-search');
+ setXdGatewayModels([]);
+ }
+ });
+
+ it('removes Grok tool controls when every declared tool is unsupported', async () => {
+ const host = await freshCodexProxyHost();
+ const { setXdGatewayModels } = await import('../active-catalog.js');
+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');
+ setXdGatewayModels([{ id: 'x-ai/grok-4.5', agents: ['codex'] }]);
+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({
+ url: 'http://127.0.0.1:43210',
+ dispose: vi.fn(async () => undefined),
+ });
+ await host.ensureCodexProxyReady();
+ host.registerComposed('session-xd-grok-no-tools', 'thread-xd-grok-no-tools', 'PRODUCT_PROMPT');
+ setSessionProvider('session-xd-grok-no-tools', 'xd');
+
+ try {
+ const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];
+ let current: unknown = {
+ model: 'x-ai/grok-4.5',
+ tools: [{ type: 'namespace', name: 'multi_agent_v1', tools: [] }],
+ tool_choice: 'none',
+ parallel_tool_calls: false,
+ };
+ const ctx = {
+ method: 'POST',
+ url: '/responses',
+ headers: { 'thread-id': 'thread-xd-grok-no-tools' },
+ };
+ for (const transform of transforms) {
+ const next = transform(current, ctx);
+ if (next !== null && next !== undefined) current = next;
+ }
+
+ expect(current).toEqual({ model: 'x-ai/grok-4.5' });
+ } finally {
+ clearSessionProvider('session-xd-grok-no-tools');
+ setXdGatewayModels([]);
+ }
+ });
+
+ it('preserves surviving allowed_tools choices after Grok sanitization', async () => {
+ const host = await freshCodexProxyHost();
+ const { setXdGatewayModels } = await import('../active-catalog.js');
+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');
+ setXdGatewayModels([{ id: 'x-ai/grok-4.5', agents: ['codex'] }]);
+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({
+ url: 'http://127.0.0.1:43210',
+ dispose: vi.fn(async () => undefined),
+ });
+ await host.ensureCodexProxyReady();
+ host.registerComposed('session-xd-grok-allowed-tools', 'thread-xd-grok-allowed-tools', 'PRODUCT_PROMPT');
+ setSessionProvider('session-xd-grok-allowed-tools', 'xd');
+
+ try {
+ const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];
+ let current: unknown = {
+ model: 'x-ai/grok-4.5',
+ tools: [
+ { type: 'function', name: 'read_file' },
+ { type: 'namespace', name: 'multi_agent_v1', tools: [] },
+ ],
+ tool_choice: {
+ type: 'allowed_tools',
+ mode: 'required',
+ tools: [
+ { type: 'function', name: 'read_file' },
+ { type: 'namespace', name: 'multi_agent_v1' },
+ ],
+ },
+ };
+ const ctx = {
+ method: 'POST',
+ url: '/responses',
+ headers: { 'thread-id': 'thread-xd-grok-allowed-tools' },
+ };
+ for (const transform of transforms) {
+ const next = transform(current, ctx);
+ if (next !== null && next !== undefined) current = next;
+ }
+
+ expect(current).toMatchObject({
+ tools: [{ type: 'function', name: 'read_file' }],
+ tool_choice: {
+ type: 'allowed_tools',
+ mode: 'required',
+ tools: [{ type: 'function', name: 'read_file' }],
+ },
+ });
+ } finally {
+ clearSessionProvider('session-xd-grok-allowed-tools');
+ setXdGatewayModels([]);
+ }
+ });
+
+ it('sanitizes XD Gateway Grok namespace tools when parent session is on a different provider', async () => {
+ // A subagent can be frozen to x-ai/grok via the catalog even though its
+ // parent session belongs to the default ChatGPT provider. The routing
+ // transform claims this request for xd; the compat transform must match.
+ const host = await freshCodexProxyHost();
+ const { setXdGatewayModels } = await import('../active-catalog.js');
+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');
+ setXdGatewayModels([{ id: 'x-ai/grok-4.5', agents: ['codex'] }]);
+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({
+ url: 'http://127.0.0.1:43210',
+ dispose: vi.fn(async () => undefined),
+ });
+ await host.ensureCodexProxyReady();
+ // Deliberately do NOT set session provider to xd — simulate parent on
+ // default provider while subagent targets Grok.
+ host.registerComposed('session-default', 'thread-default', 'PRODUCT_PROMPT');
+
+ try {
+ const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];
+ let current: unknown = {
+ model: 'x-ai/grok-4.5',
+ tools: [
+ { type: 'function', name: 'read_file' },
+ { type: 'namespace', name: 'multi_agent_v1', tools: [] },
+ ],
+ tool_choice: 'auto',
+ };
+ const ctx = {
+ method: 'POST',
+ url: '/responses',
+ headers: { 'thread-id': 'thread-default' },
+ };
+ for (const transform of transforms) {
+ const next = transform(current, ctx);
+ if (next !== null && next !== undefined) current = next;
+ }
+
+ // namespace tool must be stripped even though session provider is not xd,
+ // because the xd catalog claims this wire model.
+ expect(current).toMatchObject({
+ tools: [{ type: 'function', name: 'read_file' }],
+ });
+ } finally {
+ clearSessionProvider('session-default');
+ setXdGatewayModels([]);
+ }
+ });
+
+ it('still cleans XD Gateway Grok tools on an implicit session even when a non-xd provider lists the same id', async () => {
+ // Regression: when providerId is null (implicit session) and a custom
+ // provider also declares x-ai/grok-* in its catalog, the old nonXdHandoff
+ // check skipped cleanup — but merely listing the id does not route THIS
+ // request there (an explicit selection would set a non-null providerId).
+ // The implicit default/env-key route still lands on the xd gateway, so the
+ // namespace tools must be stripped.
+ const host = await freshCodexProxyHost();
+ const { buildUserProvider } = await import('@cindy/model-providers');
+ const { setCustomProviders, setXdGatewayModels } = await import('../active-catalog.js');
+ const { setCustomProviderKeyReader } = await import('../provider-route.js');
+ setXdGatewayModels([{ id: 'x-ai/grok-4.5', agents: ['codex'] }]);
+ setCustomProviders([
+ buildUserProvider({
+ id: 'grok-alias-provider',
+ name: 'Grok Alias Provider',
+ runtimes: {
+ codex: {
+ baseUrl: 'https://grok-alias.example/v1',
+ wireProtocol: 'openai-responses',
+ models: [{ id: 'x-ai/grok-4.5', name: 'Grok 4.5' }],
+ },
+ },
+ }),
+ ]);
+ setCustomProviderKeyReader(() => null);
+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({
+ url: 'http://127.0.0.1:43210',
+ dispose: vi.fn(async () => undefined),
+ });
+ await host.ensureCodexProxyReady();
+ host.registerComposed('session-implicit-alias', 'thread-implicit-alias', 'PRODUCT_PROMPT');
+
+ try {
+ const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];
+ let current: unknown = {
+ model: 'x-ai/grok-4.5',
+ tools: [
+ { type: 'function', name: 'read_file' },
+ { type: 'namespace', name: 'multi_agent_v1', tools: [] },
+ ],
+ tool_choice: { type: 'namespace', name: 'multi_agent_v1' },
+ };
+ const ctx = {
+ method: 'POST',
+ url: '/responses',
+ headers: { 'thread-id': 'thread-implicit-alias' },
+ };
+ for (const transform of transforms) {
+ const next = transform(current, ctx);
+ if (next !== null && next !== undefined) current = next;
+ }
+
+ expect(current).toMatchObject({
+ tools: [{ type: 'function', name: 'read_file' }],
+ tool_choice: 'none',
+ });
+ } finally {
+ setCustomProviders([]);
+ setCustomProviderKeyReader(() => null);
+ setXdGatewayModels([]);
+ }
+ });
+
it('normalizes requests to ByteDance Seed Responses capabilities', async () => {
const host = await freshCodexProxyHost();
const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');
@@ -4901,7 +5441,7 @@ describe('codex proxy host', () => {
await host.ensureCodexProxyReady();
const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];
- expect(transforms).toHaveLength(19); // encrypted activeStrip, image generation activeStrip, provider-aware Guardian reviewer, locked Subagent route, instructions 注入, locked Subagent exec guard, Gateway 原生 web_search, 跨来源压缩块兼容, xAI ModelInput activeStrip, strict gateway history 兼容, xAI ModelInput sanitize, DeepSeek V4 custom tool 兼容, xAI Responses 兼容, ByteDance Seed tool 兼容, MiniMax effort 兼容, provider model rewrite, 视觉桥(短路), stripNonAnthropicFields, dump
+ expect(transforms).toHaveLength(20); // encrypted activeStrip, image generation activeStrip, provider-aware Guardian reviewer, locked Subagent route, instructions 注入, locked Subagent exec guard, Gateway 原生 web_search, 跨来源压缩块兼容, xAI ModelInput activeStrip, strict gateway history 兼容, xAI ModelInput sanitize, DeepSeek V4 custom tool 兼容, xAI Responses 兼容, XD Gateway Grok 兼容, ByteDance Seed tool 兼容, MiniMax effort 兼容, provider model rewrite, 视觉桥(短路), stripNonAnthropicFields, dump
const ctx = {
method: 'POST',
url: '/v1/responses',
diff --git a/apps/desktop/src/main/maker-host/codex-proxy-host.ts b/apps/desktop/src/main/maker-host/codex-proxy-host.ts
index beeca53dd0..61ca8ebbf4 100644
--- a/apps/desktop/src/main/maker-host/codex-proxy-host.ts
+++ b/apps/desktop/src/main/maker-host/codex-proxy-host.ts
@@ -48,7 +48,11 @@ import path from 'node:path';
import { isCuratedQwen38Tag } from '../../shared/localModelRuntime.js';
import { buildCodexGatewayBaseUrl, CODEX_OAUTH_UPSTREAM } from './codex-gateway-config.js';
import { claudeUpstreamEndpoint } from './runtime-configs.js';
-import { getActiveCatalog, getCatalogModelContextWindow } from './active-catalog.js';
+import {
+ getActiveCatalog,
+ getCatalogModelContextWindow,
+ getXdGatewayModelAccessSnapshot,
+} from './active-catalog.js';
import {
gatewayDefaultRouteDecision,
getProviderRoutingDescriptor,
@@ -1347,7 +1351,36 @@ const XAI_SUPPORTED_TOOL_TYPES = new Set([
'shell',
]);
-function sanitizeXaiTools(body: Record<string, unknown>): Record<string, unknown> | null {
+function xaiToolChoiceAfterSanitize(
+ toolChoice: unknown,
+ tools: readonly unknown[],
+): unknown {
+ if (!isPlainObject(toolChoice) || typeof toolChoice.type !== 'string') return toolChoice;
+
+ const referencesSurvivingTool = (choice: Record<string, unknown>) => tools.some((tool) => {
+ if (!isPlainObject(tool) || tool.type !== choice.type) return false;
+ if (choice.type !== 'function') return true;
+ return typeof choice.name === 'string' && tool.name === choice.name;
+ });
+
+ if (toolChoice.type === 'allowed_tools' && Array.isArray(toolChoice.tools)) {
+ const allowedTools = toolChoice.tools.filter(
+ (choice): choice is Record<string, unknown> => isPlainObject(choice) && referencesSurvivingTool(choice),
+ );
+ return allowedTools.length > 0 ? { ...toolChoice, tools: allowedTools } : 'none';
+ }
+
+ // Fail closed: a forced choice that references a removed tool (e.g. a
+ // cache-only web_search that was dropped, or an unsupported namespace tool)
+ // must NOT widen into 'auto', which would let the model call surviving tools
+ // the caller never authorized. Collapse to 'none' so no tool is callable.
+ return referencesSurvivingTool(toolChoice) ? toolChoice : 'none';
+}
+
+function sanitizeXaiTools(
+ body: Record<string, unknown>,
+ options: { preserveNoneToolChoice?: boolean; preserveSerialToolCalls?: boolean } = {},
+): Record<string, unknown> | null {
if (!Array.isArray(body.tools)) return null;
let changed = false;
@@ -1358,9 +1391,16 @@ function sanitizeXaiTools(body: Record<string, unknown>): Record<string, unknown
continue;
}
if (tool.type === 'web_search') {
+ // A cache-only request must not silently become a live web-search request
+ // just because xAI/Grok cannot represent external_web_access=false.
+ const toolRecord = tool as Record<string, unknown>;
+ if (toolRecord.external_web_access === false) {
+ changed = true;
+ continue;
+ }
const nextTool: Record<string, unknown> = { type: 'web_search' };
for (const key of ['filters', 'enable_image_understanding', 'enable_image_search']) {
- if (key in tool) nextTool[key] = tool[key];
+ if (key in tool) nextTool[key] = toolRecord[key];
}
if (Object.keys(nextTool).length !== Object.keys(tool).length) changed = true;
tools.push(nextTool);
@@ -1371,8 +1411,38 @@ function sanitizeXaiTools(body: Record<string, unknown>): Record<string, unknown
if (!changed) return null;
const next: Record<string, unknown> = { ...body };
- if (tools.length > 0) next.tools = tools;
- else delete next.tools;
+ if (tools.length > 0) {
+ next.tools = tools;
+ next.tool_choice = xaiToolChoiceAfterSanitize(next.tool_choice, tools);
+ } else {
+ delete next.tools;
+ // All declared tools were filtered out. When server-side x_search is
+ // re-injected afterwards, a tool_choice that *references a removed tool*
+ // (an object forced choice, an emptied allowed_tools, or 'required') must
+ // collapse to 'none' so the model cannot widen the caller's authorization
+ // by auto-calling the injected search. 'auto' does NOT reference a
+ // specific tool — it means "choose any available tool" — so it stays,
+ // letting Grok use the re-injected x_search as the caller intended; a
+ // request that had no tool_choice (or already 'none') is left untouched.
+ // When nothing is re-injected (Guardian / cache-only search), drop the
+ // control field entirely — a 'none' with no tools is still an invalid xAI
+ // request (PR #2444 Codex P1/P2).
+ if (options.preserveNoneToolChoice) {
+ const choice = next.tool_choice;
+ if (
+ choice !== undefined
+ && choice !== 'none'
+ && choice !== 'auto'
+ ) {
+ next.tool_choice = 'none';
+ }
+ } else {
+ delete next.tool_choice;
+ }
+ if (!options.preserveSerialToolCalls) {
+ delete next.parallel_tool_calls;
+ }
+ }
return next;
}
@@ -1403,11 +1473,25 @@ function narrowXaiForcedToolChoice(
return { ...body, tool_choice: { type: 'function', name: only.name } };
}
+function hasCacheOnlySearchProhibition(body: Record<string, unknown>): boolean {
+ if (!Array.isArray(body.tools)) return false;
+ return body.tools.some(
+ (tool) => {
+ if (!isPlainObject(tool) || tool.type !== 'web_search') return false;
+ return (tool as Record<string, unknown>).external_web_access === false;
+ },
+ );
+}
+
function ensureXaiServerSideTools(body: Record<string, unknown>): Record<string, unknown> | null {
const realModel = xaiRealModelId(body.model);
if (!realModel) return null;
const serverTools = xaiServerSideTools(realModel);
if (serverTools.length === 0) return null;
+ // A cache-only web_search (external_web_access: false) must not be silently
+ // upgraded to a live x_search. xAI cannot represent the prohibition, so we
+ // dropped the web_search in sanitizeXaiTools; do not re-add a live search.
+ if (hasCacheOnlySearchProhibition(body)) return null;
const existing = Array.isArray(body.tools) ? body.tools : [];
const declaredTypes = new Set(
@@ -1806,7 +1890,24 @@ function createXaiResponsesCompatTransform(): RequestTransform {
if (current) changed = true;
else current = body;
- const withSanitizedTools = sanitizeXaiTools(current);
+ // Preserve tool_choice:'none' / parallel_tool_calls only when server-side
+ // x_search will be re-injected afterwards. For Guardian requests and
+ // cache-only search prohibitions (external_web_access:false) no x_search
+ // is added, so leaving control fields on a now-empty tools list produces
+ // an invalid request. Clean them instead.
+ // Detect cache-only on the ORIGINAL body because sanitizeXaiTools removes
+ // the web_search descriptor before we inspect the result.
+ const isGuardian = Boolean(guardianParentThreadIdFromHeaders(ctx.headers));
+ const realModelId = xaiRealModelId(requestModel);
+ const canInjectServerTools =
+ realModelId !== null && xaiServerSideTools(realModelId).length > 0;
+ const willReinjectTools =
+ !isGuardian && canInjectServerTools && !hasCacheOnlySearchProhibition(body);
+
+ const withSanitizedTools = sanitizeXaiTools(current, {
+ preserveNoneToolChoice: willReinjectTools,
+ preserveSerialToolCalls: willReinjectTools,
+ });
if (withSanitizedTools) {
current = withSanitizedTools;
changed = true;
@@ -1816,7 +1917,9 @@ function createXaiResponsesCompatTransform(): RequestTransform {
// 保证注入项不会被同一轮的裁剪逻辑改形或丢掉。
// Guardian must retain xAI's schema/input compatibility, but it must not
// gain provider-hosted search tools while reviewing another action.
- if (!guardianParentThreadIdFromHeaders(ctx.headers)) {
+ // Cache-only search (external_web_access:false) must not silently become
+ // a live x_search — skip injection on that path too.
+ if (willReinjectTools) {
const withServerSideTools = ensureXaiServerSideTools(current);
if (withServerSideTools) {
current = withServerSideTools;
@@ -1841,6 +1944,111 @@ function createXaiResponsesCompatTransform(): RequestTransform {
};
}
+/**
+ * The XD Gateway claims this wire model for its codex routing when the active
+ * catalog exposes it under `xd.models.codex`. We use the catalog membership
+ * (not `providerRoutingServesWireModel`, which only consults routing
+ * descriptors and is universal for `xd`) so that a non-xd provider that also
+ * lists the same id stays authoritative for its own compat transform.
+ *
+ * When the catalog is non-authoritative (a /models fetch is pending or
+ * failed), an empty codex list must NOT be used as negative evidence: an
+ * implicit session still defaults to the XD Gateway, so skipping cleanup here
+ * would let namespace tools reach Grok untouched and re-trigger the schema 400
+ * this transform exists to prevent. In that state clean unconditionally for
+ * implicit routes (PR #2444 Codex P1).
+ */
+function xdProviderClaimsWireModel(wireModel: string): boolean {
+ if (!wireModel.startsWith('x-ai/grok')) return false;
+ const { authoritative, models } = getXdGatewayModelAccessSnapshot();
+ if (!authoritative) {
+ // Negative evidence is unavailable. The env-key default route and the
+ // implicit-default both resolve to XD when no provider is explicitly
+ // selected, so treat an unverified grok wire model as gateway-owned.
+ return true;
+ }
+ const xdProvider = getActiveCatalog().providers.find((provider) => provider.id === 'xd');
+ if (xdProvider?.models.codex?.some((candidate) => candidate.id === wireModel)) return true;
+ // Authoritative gateway snapshot may also carry wire models outside the
+ // static catalog codex list.
+ return models.some((m) => m.id === wireModel);
+}
+
+/**
+ * The XD Gateway also exposes Grok models under the `x-ai/` namespace. They
+ * stay on the gateway route (unlike the first-party `xai/` OAuth provider),
+ * but the upstream Grok Responses schema still rejects Codex namespace tools.
+ * Keep this transform deliberately narrow: gateway routing and the model
+ * namespace must both match before applying the same tool-shape cleanup.
+ */
+/**
+ * Whether the request's session provider route is actually adopted by the
+ * router for the current auth injection. Mirrors createModelRoutingTransform's
+ * canUseExplicitSessionRoute: under `env-key`, a built-in session provider
+ * (e.g. the default `openai` catalog entry) is NOT adopted — the request
+ * falls through decideCodexRoute/gateway default and lands on the XD gateway
+ * even though the session records a providerId. Trusting that provider's
+ * (universal) routing descriptor would skip Grok cleanup and let namespace
+ * tools reach Grok (PR #2444 Codex P2).
+ */
+function explicitProviderRouteIsAdopted(
+ sessionId: string | undefined,
+ subagentRoute: { providerId: string } | undefined,
+ authInjection: CodexProxyAuthInjection,
+): boolean {
+ if (subagentRoute) return true;
+ if (!sessionId) return false;
+ return (
+ authInjection === 'oauth-bearer'
+ || isUserProviderSession(sessionId)
+ || isHostInjectedAuthSession(sessionId, 'codex')
+ );
+}
+
+function createGatewayGrokResponsesCompatTransform(
+ frozenAuthInjection?: CodexProxyAuthInjection,
+): RequestTransform {
+ return (body, ctx) => {
+ if (!isPlainObject(body)) return null;
+ const requestModel = typeof body.model === 'string' ? body.model : '';
+ if (!requestModel.startsWith('x-ai/grok')) return null;
+ // Use providerContextForRequest so subagent-frozen routes resolve to xd
+ // even when the parent session belongs to a different provider. Only
+ // clean tools when the effective provider for THIS request is xd.
+ const providerContext = providerContextForRequest(ctx.headers, requestModel);
+ if (providerContext.providerId === 'xd') return sanitizeXaiTools(body);
+ // An explicit non-xd provider owns this request only when (a) the router
+ // actually adopts the session route for this auth mode, and (b) that
+ // provider natively serves the wire model. A built-in `openai` session
+ // under env-key is NOT adopted (the request passes through to XD), and a
+ // provider-oauth xAI session with an out-of-scope `x-ai/grok*` request
+ // falls back to XD via gatewayDefaultRouteDecision — in both cases the
+ // namespace tools must still be cleaned (PR #2444 Codex P2).
+ if (
+ providerContext.providerId !== null
+ && explicitProviderRouteIsAdopted(
+ providerContext.sessionId,
+ providerContext.subagentRoute,
+ frozenAuthInjection ?? getCodexProxyAuthInjection(),
+ )
+ && providerRoutingServesWireModel(
+ providerContext.providerId,
+ 'codex',
+ providerContext.catalogModel ?? requestModel,
+ )
+ ) {
+ return null;
+ }
+ // Implicit session (no explicit provider), or an explicit session that is
+ // not adopted under the current auth mode. The request still lands on the
+ // XD gateway when the xd catalog owns this wire model (env-key default
+ // route, or an implicit default that resolves to xd). Clean whenever xd
+ // owns the catalog entry, matching the routing scope.
+ if (!xdProviderClaimsWireModel(requestModel)) return null;
+ return sanitizeXaiTools(body);
+ };
+}
+
/**
* 跨来源恢复的加密压缩历史兼容(Greptile P1, PR #265):
*
@@ -2438,6 +2646,7 @@ function createTransformRequestChain(
createXaiModelInputSanitizeTransform(),
sanitizeDeepSeekV4CustomTools,
createXaiResponsesCompatTransform(),
+ createGatewayGrokResponsesCompatTransform(frozenAuthInjection),
createByteDanceSeedResponsesCompatTransform(),
createMiniMaxResponsesCompatTransform(),
createProviderModelRewriteTransform(),