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): 修复 Gateway/LiteLLM Grok 的 ModelInput 422 (#2909)

Dashe02ac4918bfa
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 9e230941e6..b6dcb67c15 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
@@ -80,40 +80,44 @@ vi.mock('../../model-access/effectiveEndpoint.js', async () => {
return { effectiveXdGatewayBaseUrl: () => TEST_XD_GATEWAY_BASE_URL };
});
-vi.mock('@cindy/anthropic-compat-proxy', () => ({
- createAnthropicCompatProxy: mockState.createAnthropicCompatProxy,
- createInstructionsInjectionTransform: mockState.createInstructionsInjectionTransform,
- createActiveStripTransform: () => (() => null),
- createThreadStripController: () => ({ markActive: () => {}, reconcile: () => {}, shouldStrip: () => false, clear: () => {} }),
- createEncryptedContentRecoveryRule: (opts: { enabled: () => boolean }) => ({
- id: 'encrypted_content',
- enabled: opts.enabled,
- matches: (text: string) =>
- /invalid_encrypted_content|could not decrypt the provided encrypted_content/i.test(text),
- strip: () => null,
- }),
- createImageGenerationIdRecoveryRule: () => ({
- id: 'image_generation_id',
- enabled: () => true,
- matches: (text: string) =>
- /image generation items without [`']?id[`']? are not supported/i.test(text),
- strip: () => null,
- }),
- stripEncryptedContentFromBody: () => null,
- stripImageGenerationItemsWithoutIdFromBody: () => null,
- stripNonAnthropicFields: mockState.stripNonAnthropicFields,
- // 视觉桥 transform:默认短路(controller 未注入 → shouldBridge 恒 false → null 透传)。
- createVisionBridgeTransform: () => (() => null),
- createInstructionsRegistry: () => {
- const map = new Map<string, string>();
- return {
- set: (threadId: string, text: string) => { map.set(threadId, text); },
- get: (threadId: string) => map.get(threadId),
- delete: (threadId: string) => { map.delete(threadId); },
- get size() { return map.size; },
- };
- },
-}));
+vi.mock('@cindy/anthropic-compat-proxy', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@cindy/anthropic-compat-proxy')>();
+ return {
+ ...actual,
+ createAnthropicCompatProxy: mockState.createAnthropicCompatProxy,
+ createInstructionsInjectionTransform: mockState.createInstructionsInjectionTransform,
+ createActiveStripTransform: () => (() => null),
+ createThreadStripController: () => ({ markActive: () => {}, reconcile: () => {}, shouldStrip: () => false, clear: () => {} }),
+ createEncryptedContentRecoveryRule: (opts: { enabled: () => boolean }) => ({
+ id: 'encrypted_content',
+ enabled: opts.enabled,
+ matches: (text: string) =>
+ /invalid_encrypted_content|could not decrypt the provided encrypted_content/i.test(text),
+ strip: () => null,
+ }),
+ createImageGenerationIdRecoveryRule: () => ({
+ id: 'image_generation_id',
+ enabled: () => true,
+ matches: (text: string) =>
+ /image generation items without [`']?id[`']? are not supported/i.test(text),
+ strip: () => null,
+ }),
+ stripEncryptedContentFromBody: () => null,
+ stripImageGenerationItemsWithoutIdFromBody: () => null,
+ stripNonAnthropicFields: mockState.stripNonAnthropicFields,
+ // 视觉桥 transform:默认短路(controller 未注入 → shouldBridge 恒 false → null 透传)。
+ createVisionBridgeTransform: () => (() => null),
+ createInstructionsRegistry: () => {
+ const map = new Map<string, string>();
+ return {
+ set: (threadId: string, text: string) => { map.set(threadId, text); },
+ get: (threadId: string) => map.get(threadId),
+ delete: (threadId: string) => { map.delete(threadId); },
+ get size() { return map.size; },
+ };
+ },
+ };
+});
vi.mock('@cindy/responses-chat-bridge', () => ({
createResponsesChatHandler: mockState.createResponsesChatHandler,
@@ -2403,12 +2407,13 @@ 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, 跨来源压缩块兼容, strict gateway history 兼容, 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), 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, 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), mockState.stripNonAnthropicFields],
routingTransform: expect.any(Function),
recoveryRules: expect.arrayContaining([
expect.objectContaining({ id: 'encrypted_content' }),
expect.objectContaining({ id: 'image_generation_id' }),
+ expect.objectContaining({ id: 'xai_model_input' }),
]),
}),
);
@@ -3667,6 +3672,119 @@ describe('codex proxy host', () => {
});
});
+ it('sanitizes ModelInput for gateway grok without an xAI subscription session', 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-grok', 'thread-gateway-grok', 'PRODUCT_PROMPT');
+ setSessionProvider('session-gateway-grok', 'xd');
+
+ const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];
+ let current: unknown = {
+ model: 'x-ai/grok-4.5',
+ input: [
+ { type: 'message', role: 'user', content: 'go' },
+ {
+ type: 'agent_message',
+ author: '/root',
+ content: [{ type: 'input_text', text: 'done' }],
+ },
+ {
+ type: 'reasoning',
+ id: 'rs_1',
+ content: null,
+ encrypted_content: 'BLOB',
+ },
+ ],
+ };
+ const ctx = {
+ method: 'POST',
+ url: '/responses',
+ headers: { 'thread-id': 'thread-gateway-grok' },
+ };
+ for (const transform of transforms) {
+ const next = transform(current, ctx);
+ if (next !== null && next !== undefined) current = next;
+ }
+
+ const input = (current as { input: Array<Record<string, unknown>> }).input;
+ expect(input).toEqual(expect.arrayContaining([
+ { type: 'message', role: 'user', content: 'go' },
+ {
+ type: 'message',
+ role: 'assistant',
+ content: [{ type: 'output_text', text: '[collab /root]\ndone' }],
+ },
+ { type: 'reasoning', id: 'rs_1', summary: [], encrypted_content: 'BLOB' },
+ ]));
+ expect(input.some((item) => item.type === 'agent_message')).toBe(false);
+ expect(JSON.stringify(current)).not.toContain('"content":null');
+ clearSessionProvider('session-gateway-grok');
+ });
+
+ it.each(['x-ai/grok-code-fast', 'x-ai/grok-build-0.1'])(
+ 'drops reasoning for gateway non-reasoning model %s',
+ async (model) => {
+ 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();
+ const sessionId = `session-gateway-${model}`;
+ const threadId = `thread-gateway-${model}`;
+ host.registerComposed(sessionId, threadId, 'PRODUCT_PROMPT');
+ setSessionProvider(sessionId, 'xd');
+
+ const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];
+ let current: unknown = {
+ model,
+ input: [
+ { type: 'reasoning', id: 'rs_1', summary: [], encrypted_content: 'BLOB' },
+ { type: 'message', role: 'user', content: 'hi' },
+ ],
+ };
+ const ctx = {
+ method: 'POST',
+ url: '/responses',
+ headers: { 'thread-id': threadId },
+ };
+ for (const transform of transforms) {
+ const next = transform(current, ctx);
+ if (next !== null && next !== undefined) current = next;
+ }
+
+ const input = (current as { input: Array<Record<string, unknown>> }).input;
+ expect(input.some((item) => item.type === 'reasoning')).toBe(false);
+ expect(input).toEqual(expect.arrayContaining([
+ { type: 'message', role: 'user', content: 'hi' },
+ ]));
+ clearSessionProvider(sessionId);
+ },
+ );
+
+ it('registers a ModelInput 422 recovery rule for LiteLLM-wrapped xAI errors', async () => {
+ const host = await freshCodexProxyHost();
+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({
+ url: 'http://127.0.0.1:43210',
+ dispose: vi.fn(async () => undefined),
+ });
+ await host.ensureCodexProxyReady();
+ const rules = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.recoveryRules ?? [];
+ const rule = rules.find((candidate: { id?: string }) => candidate.id === 'xai_model_input');
+ expect(rule).toBeDefined();
+ expect(rule.matches(
+ 'unexpected status 422 Unprocessable Entity: litellm.BadRequestError: XaiException - '
+ + '{"error":"Failed to deserialize the JSON body into the target type: '
+ + 'data did not match any variant of untagged enum ModelInput"}',
+ )).toBe(true);
+ });
+
it('leaves custom_tool_call history untouched for non-xAI requests', async () => {
const host = await freshCodexProxyHost();
const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');
@@ -4630,7 +4748,7 @@ describe('codex proxy host', () => {
await host.ensureCodexProxyReady();
const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];
- expect(transforms).toHaveLength(16); // encrypted activeStrip, image generation activeStrip, provider-aware Guardian reviewer, locked Subagent route, instructions 注入, locked Subagent exec guard, Gateway 原生 web_search, 跨来源压缩块兼容, strict gateway history 兼容, xAI Responses 兼容, ByteDance Seed tool 兼容, MiniMax effort 兼容, provider model rewrite, 视觉桥(短路), stripNonAnthropicFields, dump
+ expect(transforms).toHaveLength(18); // 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, xAI Responses 兼容, 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/__tests__/piNativeSubscriptionForwarding.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts
index 9ef83e4a85..bdf0b455d5 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts
@@ -320,6 +320,86 @@ describe('PI native subscription forwarding', () => {
},
);
+ it('sanitizes native xAI Responses input before forwarding', async () => {
+ const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => new Response('event: done\n\n', {
+ status: 200,
+ headers: { 'content-type': 'text/event-stream' },
+ }));
+ const handler = getPiNativeSubscriptionHandler('xai', 'session-model-input', deps({
+ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],
+ }));
+ const parsedBody = {
+ model: 'grok-4.5',
+ input: [
+ { type: 'message', role: 'user', content: 'go' },
+ { type: 'agent_message', author: '/root', content: 'done' },
+ { type: 'reasoning', id: 'rs_1', content: null, encrypted_content: 'BLOB' },
+ ],
+ };
+
+ await handler({
+ rawBody: Buffer.from(JSON.stringify(parsedBody)),
+ parsedBody,
+ ctx: {
+ reqId: 8,
+ method: 'POST',
+ url: '/v1/responses',
+ headers: { 'content-type': 'application/json' },
+ },
+ res: responseRecorder(),
+ } as never);
+
+ const request = JSON.parse(Buffer.from(fetchMock.mock.calls[0]![1]?.body as Uint8Array).toString('utf8'));
+ expect(request.input).toEqual([
+ { type: 'message', role: 'user', content: 'go' },
+ {
+ type: 'message',
+ role: 'assistant',
+ content: [{ type: 'output_text', text: '[collab /root]\ndone' }],
+ },
+ { type: 'reasoning', id: 'rs_1', summary: [], encrypted_content: 'BLOB' },
+ ]);
+ expect(request.tools).toEqual([{ type: 'x_search' }]);
+ });
+
+ it.each(['grok-code-fast', 'grok-build-0.1'])(
+ 'drops reasoning items on native non-reasoning model %s',
+ async (model) => {
+ const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => new Response('event: done\n\n', {
+ status: 200,
+ headers: { 'content-type': 'text/event-stream' },
+ }));
+ const handler = getPiNativeSubscriptionHandler('xai', `session-reason-${model}`, deps({
+ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],
+ }));
+ const parsedBody = {
+ model,
+ input: [
+ { type: 'reasoning', id: 'rs_1', summary: [], encrypted_content: 'BLOB' },
+ { type: 'message', role: 'user', content: 'hi' },
+ ],
+ };
+
+ await handler({
+ rawBody: Buffer.from(JSON.stringify(parsedBody)),
+ parsedBody,
+ ctx: {
+ reqId: 9,
+ method: 'POST',
+ url: '/v1/responses',
+ headers: { 'content-type': 'application/json' },
+ },
+ res: responseRecorder(),
+ } as never);
+
+ const request = JSON.parse(Buffer.from(fetchMock.mock.calls[0]![1]?.body as Uint8Array).toString('utf8'));
+ expect(request.input).toEqual([
+ { type: 'message', role: 'user', content: 'hi' },
+ ]);
+ expect(request.tools).toBeUndefined();
+ },
+ );
+
it('forwards xAI Chat Completions natively and invalidates the failed host token', async () => {
const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => new Response('{"error":"expired"}', {
status: 401,
diff --git a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts
index 65558dab5c..c8bfeaebcf 100644
--- a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts
+++ b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts
@@ -26,8 +26,11 @@ import {
createEncryptedContentRecoveryRule,
createToolExchangeAdjacencyRecoveryRule,
createToolUseProviderSpecificFieldsRecoveryRule,
+ createXaiModelInputRecoveryRule,
+ createXaiModelInputSanitizeTransform,
dedupeDuplicateToolUseIds,
repairToolExchangeAdjacency,
+ sanitizeXaiModelInputFromBody,
stripEmptyAssistantMessagesFromBody,
stripEmptyTextFromBody,
stripEmptyThinkingFromBody,
@@ -78,6 +81,7 @@ import {
emptyTextStripController,
emptyThinkingStripController,
encryptedStripController,
+ xaiModelInputStripController,
} from './thread-strip-controllers.js';
import { createMakerLogger } from './logger-adapter.js';
import { resolveDesktopOutboundProxy } from './outbound-proxy-resolver.js';
@@ -592,6 +596,14 @@ export async function ensureAnthropicCompatProxyReady(): Promise<void> {
// image block、不碰 tool_use 结构,位于 repair/dedupe 之后安全;未命中时返回 null,
// 旧 #794 strip 继续兜底。
buildVisionBridgeProxyTransform(log),
+ // PI / Claude 走本 proxy 的 /responses 时(Gateway grok、自定义 LiteLLM)
+ // 不会经过 Codex 的 xAI 订阅 transform,必须在这里洗 ModelInput。
+ createActiveStripTransform({
+ controller: xaiModelInputStripController,
+ enabled: () => true,
+ strip: sanitizeXaiModelInputFromBody,
+ }),
+ createXaiModelInputSanitizeTransform(),
stripNonAnthropicFields,
],
recoveryRules: [
@@ -626,6 +638,10 @@ export async function ensureAnthropicCompatProxyReady(): Promise<void> {
// 重发,always-on(moonshot 实测不报错,但 LiteLLM 版本差 / 真 Anthropic
// 上游会报;主动 transform 已检测即修,此为第二道防线)。
createDuplicateToolUseIdRecoveryRule(),
+ // xAI ModelInput 422(含 LiteLLM 包装的 XaiException)→ 洗 input[] 重发。
+ createXaiModelInputRecoveryRule({
+ onRetry: (threadId, model) => xaiModelInputStripController.markActive(threadId, model),
+ }),
],
logger: log,
// 请求体 dump 默认关(dev trace 级别 + agent 高并发会刷爆 main event loop
diff --git a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
index 2b7d51faa6..96e6d350ca 100644
--- a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
+++ b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
@@ -24,7 +24,10 @@ import path from 'node:path';
import { promisify } from 'node:util';
import { zstdCompress, zstdDecompress } from 'node:zlib';
-import type { LocalRequestHandler } from '@cindy/anthropic-compat-proxy';
+import {
+ sanitizeXaiModelInputBody,
+ type LocalRequestHandler,
+} from '@cindy/anthropic-compat-proxy';
import { createResponsesHandler, type BridgeProviderConfig, type ResponsesBridgeHandler } from '@cindy/anthropic-responses-bridge';
import { createMakerLogger } from './logger-adapter.js';
@@ -450,6 +453,15 @@ async function rewriteOpenaiContextProfileRequest(
}
}
+function parseJsonRecord(rawBody: Buffer): Record<string, unknown> | null {
+ try {
+ const parsed: unknown = JSON.parse(rawBody.toString('utf8'));
+ return isPlainRecord(parsed) ? parsed : null;
+ } catch {
+ return null;
+ }
+}
+
/**
* PI already emits xAI-native payloads, so this path bypasses the Messages →
* Responses bridge that normally supplies xAI's model-gated server tools.
@@ -570,9 +582,14 @@ export function getPiNativeSubscriptionHandler(
contentEncoding = rewritten.contentEncoding;
}
} else if (providerId === 'xai') {
- const withServerTools = withNativeXaiServerSideTools(parsedBody);
- if (withServerTools) {
- outboundBody = Buffer.from(JSON.stringify(withServerTools));
+ const parsed = isPlainRecord(parsedBody)
+ ? parsedBody
+ : parseJsonRecord(rawBody);
+ const sanitized = parsed ? sanitizeXaiModelInputBody(parsed) : null;
+ const current = sanitized ?? parsed;
+ const withServerTools = current ? withNativeXaiServerSideTools(current) : null;
+ if (sanitized || withServerTools) {
+ outboundBody = Buffer.from(JSON.stringify(withServerTools ?? current));
// The proxy parsed a plain JSON request. After reserializing it the
// original content encoding, if any, no longer describes the bytes.
contentEncoding = undefined;
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 973c433610..64b878b070 100644
--- a/apps/desktop/src/main/maker-host/codex-proxy-host.ts
+++ b/apps/desktop/src/main/maker-host/codex-proxy-host.ts
@@ -20,6 +20,10 @@ import {
createImageGenerationIdRecoveryRule,
createInstructionsInjectionTransform,
createInstructionsRegistry,
+ createXaiModelInputRecoveryRule,
+ createXaiModelInputSanitizeTransform,
+ sanitizeXaiModelInputBody,
+ sanitizeXaiModelInputFromBody,
stripEncryptedContentFromBody,
stripImageGenerationItemsWithoutIdFromBody,
stripNonAnthropicFields,
@@ -76,7 +80,11 @@ import {
import { createProviderUpstreamErrorObserver, reportProviderUpstreamError } from './provider-upstream-error-observer.js';
import { createXaiProxyAuthInvalidationObserver } from './xai-auth-invalidation-host.js';
import { xaiServerSideTools } from './xai-server-side-tools.js';
-import { encryptedStripController, imageGenerationStripController } from './thread-strip-controllers.js';
+import {
+ encryptedStripController,
+ imageGenerationStripController,
+ xaiModelInputStripController,
+} from './thread-strip-controllers.js';
import { createMakerLogger } from './logger-adapter.js';
import { resolveDesktopOutboundProxy } from './outbound-proxy-resolver.js';
import { outboundFetch } from './outbound-fetch.js';
@@ -118,9 +126,13 @@ const encryptedContentRecoveryRule = createEncryptedContentRecoveryRule({
const imageGenerationIdRecoveryRule = createImageGenerationIdRecoveryRule({
onRetry: (threadId, model) => imageGenerationStripController.markActive(threadId, model),
});
+const xaiModelInputRecoveryRule = createXaiModelInputRecoveryRule({
+ onRetry: (threadId, model) => xaiModelInputStripController.markActive(threadId, model),
+});
const CODEX_BODY_RECOVERY_RULES = [
encryptedContentRecoveryRule,
imageGenerationIdRecoveryRule,
+ xaiModelInputRecoveryRule,
] as const;
/**
@@ -1255,7 +1267,7 @@ function moveInstructionsIntoInput(body: Record<string, unknown>): Record<string
function xaiRealModelId(model: unknown): string | null {
if (typeof model !== 'string' || model.length === 0) return null;
- return model.startsWith('xai/') ? model.slice('xai/'.length) : model;
+ return model.includes('/') ? model.slice(model.lastIndexOf('/') + 1) : model;
}
function supportsXaiReasoning(model: string | null): boolean {
@@ -1278,287 +1290,6 @@ function stripUnsupportedXaiReasoning(body: Record<string, unknown>): Record<str
return changed ? next : null;
}
-function isXaiUnsupportedInputItem(item: unknown, opts: { supportsReasoning: boolean }): boolean {
- if (!isPlainObject(item) || typeof item.type !== 'string') return false;
- if (item.type === 'reasoning') {
- return !opts.supportsReasoning || typeof item.encrypted_content !== 'string' || item.encrypted_content.length === 0;
- }
- return item.type.startsWith('image_generation') ||
- item.type.startsWith('imageGeneration');
-}
-
-/**
- * Codex code-mode / app-server 历史里会回放 `custom_tool_call*` / `agent_message` 等
- * 非 Responses 标准 item,且 tool output 常是 `[{type:"input_text",text}]` 数组。
- * xAI Responses 的 untagged `ModelInput` 只认 message / function_call /
- * function_call_output / reasoning 等标准变体;原样转发会 422:
- * "data did not match any variant of untagged enum ModelInput"。
- * 仅在 xAI 路由里把这些历史 item 归一成 xAI 可反序列化的形态;未知 type 直接丢掉,
- * 避免跨源 resume(如 OpenAI collab → Grok)整轮卡死。
- */
-/** xAI ModelInput 可反序列化的 input item type(归一化后的白名单)。 */
-const XAI_MODEL_INPUT_TYPES = new Set([
- 'message',
- 'function_call',
- 'function_call_output',
- 'reasoning',
-]);
-
-function textFromResponsesContent(value: unknown): string {
- if (typeof value === 'string') return value;
- if (typeof value === 'number' || typeof value === 'boolean') return String(value);
- if (value == null) return '';
- if (Array.isArray(value)) {
- return value
- .map((part) => {
- if (typeof part === 'string') return part;
- if (!isPlainObject(part)) return '';
- if (typeof part.text === 'string') return part.text;
- if (typeof part.input_text === 'string') return part.input_text;
- if (typeof part.output_text === 'string') return part.output_text;
- return '';
- })
- .filter((part) => part.length > 0)
- .join('\n');
- }
- if (isPlainObject(value)) {
- if (typeof value.text === 'string') return value.text;
- try {
- return JSON.stringify(value);
- } catch {
- return String(value);
- }
- }
- return String(value);
-}
-
-function argumentsFromCustomToolInput(value: unknown): string {
- if (value == null) return '{}';
-
- if (typeof value === 'string') {
- try {
- const parsed = JSON.parse(value);
- return JSON.stringify(isPlainObject(parsed) ? parsed : { input: parsed });
- } catch {
- return JSON.stringify({ input: value });
- }
- }
-
- try {
- return JSON.stringify(isPlainObject(value) ? value : { input: value });
- } catch {
- return JSON.stringify({ input: String(value) });
- }
-}
-
-function normalizeXaiInputItem(item: unknown): { item: unknown; changed: boolean } {
- if (!isPlainObject(item)) {
- return { item, changed: false };
- }
-
- // EasyInput 兼容:只有 role/content、缺 type 的 message 先补 type。
- const base: Record<string, unknown> = (!('type' in item) && typeof item.role === 'string' && 'content' in item)
- ? { type: 'message', ...item }
- : item;
- const typedFromEasy = base !== item;
- const type = typeof base.type === 'string' ? base.type : undefined;
-
- if (type === 'custom_tool_call') {
- const name = typeof base.name === 'string' ? base.name : '';
- const callId = typeof base.call_id === 'string'
- ? base.call_id
- : (typeof base.id === 'string' ? base.id : '');
- const next: Record<string, unknown> = {
- type: 'function_call',
- name,
- arguments: argumentsFromCustomToolInput(base.input),
- call_id: callId,
- };
- if (typeof base.id === 'string') next.id = base.id;
- return { item: next, changed: true };
- }
-
- if (type === 'custom_tool_call_output') {
- return {
- item: {
- type: 'function_call_output',
- call_id: typeof base.call_id === 'string' ? base.call_id : '',
- output: textFromResponsesContent(base.output),
- },
- changed: true,
- };
- }
-
- // Codex multi-agent collab 历史项。OpenAI 会话里的 agent_message 带着 author/
- // recipient 和 content 里的 encrypted_content part;xAI ModelInput 不认这个 type,
- // 跨源 resume 到 grok 时整轮 422。降级成 assistant message,只保留可读文本
- // (collab 密文 part 解不开,丢掉)。
- if (type === 'agent_message') {
- const bodyText = textFromResponsesContent(base.content).trim();
- const author = typeof base.author === 'string' && base.author.length > 0
- ? base.author
- : 'agent';
- const text = bodyText.length > 0
- ? `[collab ${author}]\n${bodyText}`
- : `[collab message from ${author}; encrypted payload omitted]`;
- return {
- item: {
- type: 'message',
- role: 'assistant',
- content: [{ type: 'output_text', text }],
- },
- changed: true,
- };
- }
-
- if (type === 'function_call') {
- const normalizedArguments = argumentsFromCustomToolInput(base.arguments);
- const next: Record<string, unknown> = {
- type: 'function_call',
- name: typeof base.name === 'string' ? base.name : '',
- arguments: normalizedArguments,
- call_id: typeof base.call_id === 'string'
- ? base.call_id
- : (typeof base.id === 'string' ? base.id : ''),
- };
- if (typeof base.id === 'string') next.id = base.id;
- const changed = typedFromEasy
- || normalizedArguments !== base.arguments
- || typeof base.call_id !== 'string'
- || typeof base.name !== 'string'
- || 'status' in base
- || Object.keys(base).some((key) => !['type', 'name', 'arguments', 'call_id', 'id'].includes(key));
- return changed ? { item: next, changed: true } : { item: base, changed: false };
- }
-
- if (type === 'function_call_output') {
- const next: Record<string, unknown> = {
- type: 'function_call_output',
- call_id: typeof base.call_id === 'string' ? base.call_id : '',
- output: typeof base.output === 'string' ? base.output : textFromResponsesContent(base.output),
- };
- const changed = typedFromEasy
- || typeof base.output !== 'string'
- || typeof base.call_id !== 'string'
- || Object.keys(base).some((key) => !['type', 'call_id', 'output'].includes(key));
- return changed ? { item: next, changed: true } : { item: base, changed: false };
- }
-
- // 回放的 reasoning 项必须逐字回到上游签发时的形状 —— xAI 校验不过就整轮 400
- // "Could not decode the compaction blob. Ensure it is unmodified from the compact response."
- // codex 的结构体会把自己没用上的 `Option` 字段一并序列化(实测 `content: null`),
- // 那是 xAI 从没发过的键;带着它回放等于「被改过」。这里收敛成 Responses 契约里
- // reasoning 该有的四个键 —— 与 anthropic-responses-bridge 回放的形状同口径
- // (那条路上的 grok-4.5 一直是通的)。
- // encrypted_content / summary / id 原样搬,一个字节都不改写。
- if (type === 'reasoning') {
- const next: Record<string, unknown> = { type: 'reasoning' };
- if (typeof base.id === 'string' && base.id.length > 0) next.id = base.id;
- next.summary = Array.isArray(base.summary) ? base.summary : [];
- if (typeof base.encrypted_content === 'string') next.encrypted_content = base.encrypted_content;
- // changed 必须覆盖「键在允许列表里、但值被上面丢掉了」的情况(如 id 是空串
- // 或非 string):只数键名会让这些项拿着原值原样发出去 —— 等于算出了规范形状
- // 又扔掉。逐字段比对 next 与 base,判定和构造才是同一套口径。
- const changed =
- typedFromEasy ||
- !Array.isArray(base.summary) ||
- ('id' in base && next.id !== base.id) ||
- ('encrypted_content' in base && next.encrypted_content !== base.encrypted_content) ||
- Object.keys(base).some((key) => !['type', 'id', 'summary', 'encrypted_content'].includes(key));
- return changed ? { item: next, changed: true } : { item: base, changed: false };
- }
-
- if (type === 'message') {
- let changed = typedFromEasy;
- const next: Record<string, unknown> = { type: 'message' };
- const role = base.role === 'developer' ? 'system' : base.role;
- if (role !== base.role) changed = true;
- if (typeof role === 'string') next.role = role;
- if ('content' in base) next.content = base.content;
- if (typeof base.id === 'string') next.id = base.id;
- for (const key of Object.keys(base)) {
- if (key === 'type' || key === 'role' || key === 'content' || key === 'id') continue;
- // phase / internal_* / 其它扩展键一律丢掉。
- changed = true;
- }
- // content part 只保留 text 类;缺 type 的纯文本 part 补 input_text。
- if (Array.isArray(next.content)) {
- const parts: unknown[] = [];
- for (const part of next.content) {
- if (typeof part === 'string') {
- parts.push({ type: 'input_text', text: part });
- changed = true;
- continue;
- }
- if (!isPlainObject(part)) {
- changed = true;
- continue;
- }
- const partType = typeof part.type === 'string' ? part.type : undefined;
- if (partType === 'text') {
- parts.push({ type: role === 'assistant' ? 'output_text' : 'input_text', text: typeof part.text === 'string' ? part.text : '' });
- changed = true;
- continue;
- }
- if (partType === 'input_text' || partType === 'output_text') {
- parts.push({ type: partType, text: typeof part.text === 'string' ? part.text : '' });
- if (Object.keys(part).some((k) => k !== 'type' && k !== 'text')) changed = true;
- continue;
- }
- if (partType === 'input_image') {
- const imageUrl = typeof part.image_url === 'string' ? part.image_url : undefined;
- if (imageUrl) parts.push({ type: 'input_image', image_url: imageUrl });
- else changed = true;
- if (Object.keys(part).some((k) => k !== 'type' && k !== 'image_url')) changed = true;
- continue;
- }
- changed = true;
- }
- next.content = parts;
- } else if (typeof next.content !== 'string') {
- // 非法 content → 降级空字符串,避免整个 ModelInput 反序列化失败。
- next.content = textFromResponsesContent(next.content);
- changed = true;
- }
- return changed ? { item: next, changed: true } : { item: base, changed: false };
- }
-
- // 未知 type 不透传:xAI untagged ModelInput 任一 item 对不上就整包 422。
- // 调用方按 changed=true + 非白名单 type 丢弃(见 normalizeXaiInputItems)。
- return { item: base, changed: typedFromEasy || (typeof type === 'string' && !XAI_MODEL_INPUT_TYPES.has(type)) };
-}
-
-function normalizeXaiInputItems(body: Record<string, unknown>): Record<string, unknown> | null {
- if (!Array.isArray(body.input)) return null;
-
- // xAI supports encrypted reasoning replay, but not Codex/OpenAI image replay items in `input[]`.
- // Codex custom_tool_call* / agent_message 等必须在 ModelInput deserialize 前洗掉或改写。
- const supportsReasoning = supportsXaiReasoning(xaiRealModelId(body.model));
- let changed = false;
- const input: unknown[] = [];
- for (const raw of body.input) {
- if (isXaiUnsupportedInputItem(raw, { supportsReasoning })) {
- changed = true;
- continue;
- }
- const normalized = normalizeXaiInputItem(raw);
- if (normalized.changed) changed = true;
- // 归一化后仍不在白名单(或未知 type 原样返回)→ 丢掉,别把 422 留给上游。
- if (
- !isPlainObject(normalized.item)
- || typeof normalized.item.type !== 'string'
- || !XAI_MODEL_INPUT_TYPES.has(normalized.item.type)
- ) {
- changed = true;
- continue;
- }
- input.push(normalized.item);
- }
- if (!changed) return null;
-
- return { ...body, input };
-}
-
const XAI_SUPPORTED_TOOL_TYPES = new Set([
'function',
'web_search',
@@ -1993,7 +1724,9 @@ function createXaiResponsesCompatTransform(): RequestTransform {
changed = true;
}
- const withNormalizedInputItems = normalizeXaiInputItems(current);
+ const withNormalizedInputItems = sanitizeXaiModelInputBody(current, {
+ supportsReasoning: supportsXaiReasoning(xaiRealModelId(current.model)),
+ });
if (withNormalizedInputItems) {
current = withNormalizedInputItems;
changed = true;
@@ -2561,6 +2294,7 @@ function createTransformRequestChain(
enabled: () => true,
strip: stripImageGenerationItemsWithoutIdFromBody,
}),
+
// Guardian uses an isolated child thread. Resolve its parent business
// session and select that session's real provider model before provider
// compatibility transforms inspect the request.
@@ -2574,7 +2308,17 @@ function createTransformRequestChain(
// 必须先于 xAI/MiniMax 兼容改写:先把供应商绑定的历史项降级成标准 message,
// 后续针对具体供应商的 input 归一化才能稳定处理。
createCrossProviderCompactionCompatTransform(),
+ // 必须在 compaction 降级之后:自定义 LiteLLM 别名首次 422 会激活本 strip,
+ // 若先于降级跑,会把 compaction 当未知 type 丢掉,明文「早期上下文不可用」提示就没了。
+ createActiveStripTransform({
+ controller: xaiModelInputStripController,
+ enabled: () => true,
+ strip: sanitizeXaiModelInputFromBody,
+ }),
createStrictGatewayHistoryCompatTransform(),
+ // Gateway / LiteLLM / 自定义 grok 不走 xAI 订阅 transform,但仍必须在
+ // ModelInput deserialize 前洗 input[]。订阅直连那条会再洗一次(幂等)。
+ createXaiModelInputSanitizeTransform(),
createXaiResponsesCompatTransform(),
createByteDanceSeedResponsesCompatTransform(),
createMiniMaxResponsesCompatTransform(),
diff --git a/apps/desktop/src/main/maker-host/thread-strip-controllers.ts b/apps/desktop/src/main/maker-host/thread-strip-controllers.ts
index 3a08d1e682..16705e2e43 100644
--- a/apps/desktop/src/main/maker-host/thread-strip-controllers.ts
+++ b/apps/desktop/src/main/maker-host/thread-strip-controllers.ts
@@ -21,3 +21,7 @@ export const emptyTextStripController = createThreadStripController();
// 空 assistant 消息主动剥离 —— always-on(moonshot/kimi 空 thinking 占位被中断
// 持久化后回放 400 "with role 'assistant' must not be empty")。必须与上面是独立实例。
export const emptyAssistantStripController = createThreadStripController();
+
+// xAI ModelInput 422 主动剥离 —— always-on(Gateway / LiteLLM 中转 grok 时
+// Codex 历史里的非 ModelInput item 会整包 422;恢复一次后该 thread 发送前预洗)。
+export const xaiModelInputStripController = createThreadStripController();
diff --git a/packages/anthropic-compat-proxy/src/index.ts b/packages/anthropic-compat-proxy/src/index.ts
index efaff3bb7e..a63451b588 100644
--- a/packages/anthropic-compat-proxy/src/index.ts
+++ b/packages/anthropic-compat-proxy/src/index.ts
@@ -57,6 +57,15 @@ export {
stripToolUseProviderSpecificFields,
stripToolUseProviderSpecificFieldsFromBody,
} from './transform.js';
+export {
+ createXaiModelInputRecoveryRule,
+ createXaiModelInputSanitizeTransform,
+ looksLikeXaiResponsesModel,
+ sanitizeXaiModelInputBody,
+ sanitizeXaiModelInputFromBody,
+ supportsXaiReasoningModel,
+ xaiBareModelId,
+} from './xai-model-input.js';
export { createVisionBridgeTransform } from './vision-bridge-transform.js';
export { createThreadStripController } from './thread-strip-controller.js';
export type { ThreadStripController } from './thread-strip-controller.js';
diff --git a/packages/anthropic-compat-proxy/src/server.test.ts b/packages/anthropic-compat-proxy/src/server.test.ts
index 6bbda30136..5d27a9c447 100644
--- a/packages/anthropic-compat-proxy/src/server.test.ts
+++ b/packages/anthropic-compat-proxy/src/server.test.ts
@@ -26,6 +26,7 @@ import {
repairToolExchangeAdjacency,
stripEncryptedContentFromBody,
} from './transform.js';
+import { createXaiModelInputRecoveryRule } from './xai-model-input.js';
import { listenOnAvailableLoopbackPort } from './test-loopback-server.js';
import { createThreadStripController } from './thread-strip-controller.js';
import type { ProxyHandle } from './types.js';
@@ -479,6 +480,124 @@ describe('anthropic-compat-proxy encrypted content retry', () => {
expect(upstream.bodies[1]).not.toContain('encrypted_content');
});
+ it('retries LiteLLM-wrapped xAI ModelInput 422 after sanitizing input', async () => {
+ const upstream = await startFakeUpstream((idx, _body, res) => {
+ if (idx === 0) {
+ res.writeHead(422, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({
+ error: 'litellm.BadRequestError: XaiException - {"error":"Failed to deserialize the JSON body into the target type: data did not match any variant of untagged enum ModelInput"}',
+ }));
+ } else {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ ok: true, attempt: idx }));
+ }
+ });
+ upstreamClose = upstream.close;
+ proxy = await createAnthropicCompatProxy({
+ upstream: upstream.url,
+ transformRequest: [],
+ recoveryRules: [createXaiModelInputRecoveryRule()],
+ });
+
+ const r = await post(proxy.url, {
+ model: 'my-custom-grok',
+ input: [
+ { type: 'message', role: 'user', content: 'hi' },
+ { type: 'agent_message', author: 'bot', content: 'done' },
+ ],
+ });
+
+ expect(r.status).toBe(200);
+ expect(JSON.parse(r.text)).toMatchObject({ ok: true });
+ expect(upstream.bodies).toHaveLength(2);
+ expect(upstream.bodies[0]).toContain('agent_message');
+ expect(upstream.bodies[1]).not.toContain('agent_message');
+ expect(JSON.parse(upstream.bodies[1]).input).toEqual([
+ { type: 'message', role: 'user', content: 'hi' },
+ {
+ type: 'message',
+ role: 'assistant',
+ content: [{ type: 'output_text', text: '[collab bot]\ndone' }],
+ },
+ ]);
+ });
+
+ it('does not rewrite OpenAI collab history when another recovery rule retries', async () => {
+ const upstream = await startFakeUpstream((idx, _body, res) => {
+ if (idx === 0) {
+ res.writeHead(400, { 'content-type': 'application/json' });
+ res.end(ENC_ERROR_BODY);
+ } else {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ ok: true, attempt: idx }));
+ }
+ });
+ upstreamClose = upstream.close;
+ proxy = await createAnthropicCompatProxy({
+ upstream: upstream.url,
+ transformRequest: [],
+ recoveryRules: [
+ createEncryptedContentRecoveryRule({ enabled: () => true }),
+ createXaiModelInputRecoveryRule(),
+ ],
+ });
+
+ const r = await post(proxy.url, {
+ model: 'gpt-5.5',
+ input: [
+ { type: 'reasoning', encrypted_content: 'gAAAsecret' },
+ { type: 'agent_message', author: 'bot', content: 'keep me' },
+ ],
+ });
+
+ expect(r.status).toBe(200);
+ expect(upstream.bodies).toHaveLength(2);
+ expect(JSON.parse(upstream.bodies[1]).input).toEqual([
+ { type: 'agent_message', author: 'bot', content: 'keep me' },
+ ]);
+ });
+
+ it('does not stack encrypted-content strip onto a ModelInput 422 retry', async () => {
+ const upstream = await startFakeUpstream((idx, _body, res) => {
+ if (idx === 0) {
+ res.writeHead(422, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({
+ error: 'litellm.BadRequestError: XaiException - {"error":"data did not match any variant of untagged enum ModelInput"}',
+ }));
+ } else {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ ok: true, attempt: idx }));
+ }
+ });
+ upstreamClose = upstream.close;
+ proxy = await createAnthropicCompatProxy({
+ upstream: upstream.url,
+ transformRequest: [],
+ recoveryRules: [
+ createEncryptedContentRecoveryRule({ enabled: () => true }),
+ createXaiModelInputRecoveryRule(),
+ ],
+ });
+
+ const r = await post(proxy.url, {
+ model: 'grok-4.5',
+ input: [
+ { type: 'reasoning', id: 'rs_1', summary: [], encrypted_content: 'gAAAkeep' },
+ { type: 'agent_message', author: 'bot', content: 'done' },
+ ],
+ });
+
+ expect(r.status).toBe(200);
+ expect(JSON.parse(upstream.bodies[1]).input).toEqual([
+ { type: 'reasoning', id: 'rs_1', summary: [], encrypted_content: 'gAAAkeep' },
+ {
+ type: 'message',
+ role: 'assistant',
+ content: [{ type: 'output_text', text: '[collab bot]\ndone' }],
+ },
+ ]);
+ });
+
it('keeps proactive stripping active when a provider transform rewrites the model id', async () => {
const upstream = await startFakeUpstream((_idx, body, res) => {
if (body.includes('encrypted_content')) {
diff --git a/packages/anthropic-compat-proxy/src/server.ts b/packages/anthropic-compat-proxy/src/server.ts
index c5610c13a0..3946be8307 100644
--- a/packages/anthropic-compat-proxy/src/server.ts
+++ b/packages/anthropic-compat-proxy/src/server.ts
@@ -998,12 +998,19 @@ function forward(
const appliedRules: RecoveryRule[] = [rule];
// 透明重试只有一次。若同一历史里同时存在多类已知坏 payload,在这一次 retry
// 前把其它安全 strip 也顺手应用掉,避免第一类 400 恢复后立刻撞第二类 400。
- for (const [extraIndex, extraRule] of activeRules.entries()) {
- if (extraIndex === matchedIndex) continue;
- const extraStripped = extraRule.strip(retryBody);
- if (!extraStripped) continue;
- retryBody = extraStripped;
- appliedRules.push(extraRule);
+ // applyOnUnmatchedRetry === false 的规则只在自己 matches 时跑,不能叠到
+ // 别人的 400 上(xAI ModelInput 清洗会改写 OpenAI collab 历史)。
+ // allowExtraRules === false 的主匹配禁止整轮叠洗(ModelInput 422 叠
+ // encrypted-content 会删掉 xAI 本可回放的 reasoning blob)。
+ if (rule.allowExtraRules !== false) {
+ for (const [extraIndex, extraRule] of activeRules.entries()) {
+ if (extraIndex === matchedIndex) continue;
+ if (extraRule.applyOnUnmatchedRetry === false) continue;
+ const extraStripped = extraRule.strip(retryBody);
+ if (!extraStripped) continue;
+ retryBody = extraStripped;
+ appliedRules.push(extraRule);
+ }
}
logger.info?.(`◀ upstream ${status} [${rule.id}] → 透明重试 (strip + 重发)`, {
reqId,
diff --git a/packages/anthropic-compat-proxy/src/types.ts b/packages/anthropic-compat-proxy/src/types.ts
index 297ddceb31..7928029cdb 100644
--- a/packages/anthropic-compat-proxy/src/types.ts
+++ b/packages/anthropic-compat-proxy/src/types.ts
@@ -9,10 +9,10 @@
* - logger 全可选,host 不传就静默(包本身永远不 console.log)
*/
-import type { Buffer } from 'node:buffer';
-import type { ServerResponse } from 'node:http';
+import type { Buffer } from "node:buffer";
+import type { ServerResponse } from "node:http";
-import type { OutboundProxyResolver } from './outbound-proxy.js';
+import type { OutboundProxyResolver } from "./outbound-proxy.js";
/**
* 请求 transform 上下文。
@@ -174,6 +174,18 @@ export interface RecoveryRule {
onRetry?: (threadId: string, model: string) => void;
/** 取 threadId 的 header 候选名;省略用默认 DEFAULT_THREAD_ID_HEADERS。 */
threadIdHeaders?: readonly string[];
+ /**
+ * 别的规则命中 400/422 时,是否把本规则的 strip 顺手叠上去。
+ * 默认 true(encrypted / empty thinking 这类对任意上游都安全)。
+ * 语义绑在特定上游的规则必须显式 false,否则会在 GPT 的
+ * invalid_encrypted_content 重试里改写 OpenAI 历史。
+ */
+ applyOnUnmatchedRetry?: boolean;
+ /**
+ * 本规则作为主匹配时,是否还叠其它 extra strip。默认 true。
+ * xAI ModelInput 必须 false:叠 encrypted-content 会删掉本来可回放的 reasoning blob。
+ */
+ allowExtraRules?: boolean;
}
/**
diff --git a/packages/anthropic-compat-proxy/src/xai-model-input.test.ts b/packages/anthropic-compat-proxy/src/xai-model-input.test.ts
new file mode 100644
index 0000000000..7a0c399310
--- /dev/null
+++ b/packages/anthropic-compat-proxy/src/xai-model-input.test.ts
@@ -0,0 +1,648 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ createXaiModelInputRecoveryRule,
+ createXaiModelInputSanitizeTransform,
+ looksLikeXaiResponsesModel,
+ sanitizeXaiModelInputBody,
+ sanitizeXaiModelInputFromBody,
+ supportsXaiReasoningModel,
+} from "./xai-model-input.js";
+
+describe("looksLikeXaiResponsesModel", () => {
+ it.each([
+ "grok-4.5",
+ "xai/grok-4.5",
+ "x-ai/grok-4.5",
+ "X-AI/Grok-4.20",
+ "litellm/grok-code-fast",
+ ])("accepts %s", (model) => {
+ expect(looksLikeXaiResponsesModel(model)).toBe(true);
+ });
+
+ it.each([
+ "gpt-5.5",
+ "openai/gpt-5.5",
+ "claude-sonnet-4-5",
+ "x-ai-not-grok",
+ "",
+ 1,
+ null,
+ ])("rejects %s", (model) => {
+ expect(looksLikeXaiResponsesModel(model)).toBe(false);
+ });
+});
+
+describe("sanitizeXaiModelInputBody", () => {
+ it("returns null when input is already xAI-safe", () => {
+ expect(
+ sanitizeXaiModelInputBody({
+ model: "grok-4.5",
+ input: [{ type: "message", role: "user", content: "hi" }],
+ }),
+ ).toBeNull();
+ });
+
+ it("rewrites Codex collab + custom tool history and LiteLLM chat leftovers", () => {
+ const out = sanitizeXaiModelInputBody({
+ model: "x-ai/grok-4.5",
+ input: [
+ { role: "user", content: "go" },
+ {
+ type: "agent_message",
+ author: "/root",
+ content: [
+ { type: "input_text", text: "done" },
+ { type: "encrypted_content", encrypted_content: "gAAA" },
+ ],
+ },
+ {
+ type: "custom_tool_call",
+ id: "ctc_1",
+ call_id: "call_1",
+ name: "exec",
+ input: "console.log(1)",
+ },
+ {
+ type: "custom_tool_call_output",
+ call_id: "call_1",
+ output: [{ type: "input_text", text: "ok" }],
+ },
+ {
+ type: "function",
+ id: "call_2",
+ function: { name: "read_file", arguments: '{"path":"a"}' },
+ },
+ { role: "tool", tool_call_id: "call_2", content: "file body" },
+ {
+ type: "reasoning",
+ id: "rs_1",
+ content: null,
+ encrypted_content: "BLOB",
+ },
+ { type: "web_search_call", id: "ws_1", status: "completed" },
+ "plain text item",
+ ],
+ });
+
+ expect(out?.input).toEqual([
+ { type: "message", role: "user", content: "go" },
+ {
+ type: "message",
+ role: "assistant",
+ content: [{ type: "output_text", text: "[collab /root]\ndone" }],
+ },
+ {
+ type: "function_call",
+ id: "ctc_1",
+ name: "exec",
+ arguments: '{"input":"console.log(1)"}',
+ call_id: "call_1",
+ },
+ { type: "function_call_output", call_id: "call_1", output: "ok" },
+ {
+ type: "function_call",
+ id: "call_2",
+ name: "read_file",
+ arguments: '{"path":"a"}',
+ call_id: "call_2",
+ },
+ { type: "function_call_output", call_id: "call_2", output: "file body" },
+ { type: "reasoning", id: "rs_1", summary: [], encrypted_content: "BLOB" },
+ { type: "web_search_call", id: "ws_1", status: "completed" },
+ { type: "message", role: "user", content: "plain text item" },
+ ]);
+ });
+
+ it("keeps official attachments and server-side tool items when rewriting a bad sibling", () => {
+ const filePart = {
+ type: "input_file",
+ file_id: "file_123",
+ filename: "notes.pdf",
+ };
+ const imagePart = {
+ type: "input_image",
+ image_url: "https://example.com/a.png",
+ detail: "high",
+ };
+ const webSearch = {
+ type: "web_search_call",
+ id: "ws_1",
+ status: "completed",
+ action: { type: "search", query: "xai responses" },
+ };
+ const code = {
+ type: "code_interpreter_call",
+ id: "ci_1",
+ status: "completed",
+ };
+ const files = { type: "file_search_call", id: "fs_1", status: "completed" };
+ const out = sanitizeXaiModelInputBody({
+ model: "x-ai/grok-4.6",
+ input: [
+ {
+ type: "message",
+ role: "user",
+ content: [
+ { type: "input_text", text: "see these" },
+ filePart,
+ imagePart,
+ ],
+ },
+ { type: "agent_message", author: "bot", content: "ok" },
+ webSearch,
+ code,
+ files,
+ ],
+ });
+
+ expect(out?.input).toEqual([
+ {
+ type: "message",
+ role: "user",
+ content: [
+ { type: "input_text", text: "see these" },
+ filePart,
+ imagePart,
+ ],
+ },
+ {
+ type: "message",
+ role: "assistant",
+ content: [{ type: "output_text", text: "[collab bot]\nok" }],
+ },
+ webSearch,
+ code,
+ files,
+ ]);
+ });
+
+ it("keeps host-allowed xAI server tool replay items", () => {
+ const shellCall = {
+ type: "shell_call",
+ id: "sh_1",
+ status: "completed",
+ };
+ const shellOut = {
+ type: "shell_call_output",
+ call_id: "sh_1",
+ output: "ok",
+ };
+ const execCall = { type: "code_execution_call", id: "ce_1" };
+ const collections = { type: "collections_search_call", id: "cs_1" };
+ const out = sanitizeXaiModelInputBody({
+ model: "x-ai/grok-4.6",
+ input: [
+ { type: "agent_message", author: "bot", content: "ok" },
+ shellCall,
+ shellOut,
+ execCall,
+ collections,
+ ],
+ });
+ expect(out?.input).toEqual([
+ {
+ type: "message",
+ role: "assistant",
+ content: [{ type: "output_text", text: "[collab bot]\nok" }],
+ },
+ shellCall,
+ shellOut,
+ execCall,
+ collections,
+ ]);
+ });
+
+ it("flattens Chat-compat {image_url:{url,detail}} into Responses string + detail", () => {
+ const out = sanitizeXaiModelInputBody({
+ model: "x-ai/grok-4.6",
+ input: [
+ {
+ type: "message",
+ role: "user",
+ content: [
+ {
+ type: "input_image",
+ image_url: {
+ url: "https://example.com/a.png",
+ detail: "high",
+ },
+ },
+ ],
+ },
+ ],
+ });
+ expect(out?.input).toEqual([
+ {
+ type: "message",
+ role: "user",
+ content: [
+ {
+ type: "input_image",
+ image_url: "https://example.com/a.png",
+ detail: "high",
+ },
+ ],
+ },
+ ]);
+ });
+
+ it("rewrites compaction blobs into a readable context note instead of dropping them", () => {
+ const out = sanitizeXaiModelInputBody({
+ model: "my-custom-alias",
+ input: [
+ { type: "compaction", encrypted_content: "OPENAI-BLOB" },
+ { type: "message", role: "user", content: "continue" },
+ ],
+ });
+ expect(out?.input).toEqual([
+ {
+ type: "message",
+ role: "user",
+ content: [
+ {
+ type: "input_text",
+ text: expect.stringContaining(
+ "not readable on the current model provider",
+ ),
+ },
+ ],
+ },
+ { type: "message", role: "user", content: "continue" },
+ ]);
+ });
+
+ it("maps Anthropic tool_result.tool_use_id and drops outputs with no id", () => {
+ const out = sanitizeXaiModelInputBody({
+ model: "x-ai/grok-4.6",
+ input: [
+ {
+ type: "tool_result",
+ tool_use_id: "t1",
+ content: "ok",
+ },
+ { type: "tool_result", content: "orphan" },
+ ],
+ });
+ expect(out?.input).toEqual([
+ { type: "function_call_output", call_id: "t1", output: "ok" },
+ ]);
+ });
+
+ it("does not treat output item id as a call association", () => {
+ const out = sanitizeXaiModelInputBody({
+ model: "x-ai/grok-4.6",
+ input: [
+ { type: "function_call", name: "ok", arguments: "{}", call_id: "c1" },
+ { type: "function_call_output", id: "msg_abc", output: "nope" },
+ { role: "tool", id: "msg_def", content: "also nope" },
+ { type: "function_call_output", call_id: "c1", output: "ok" },
+ ],
+ });
+ expect(out?.input).toEqual([
+ {
+ type: "function_call",
+ name: "ok",
+ arguments: "{}",
+ call_id: "c1",
+ },
+ { type: "function_call_output", call_id: "c1", output: "ok" },
+ ]);
+ });
+
+ it("drops tool calls that have no non-empty call id", () => {
+ const out = sanitizeXaiModelInputBody({
+ model: "x-ai/grok-4.6",
+ input: [
+ { type: "custom_tool_call", name: "exec", input: "pwd" },
+ {
+ type: "function",
+ function: { name: "read_file", arguments: "{}" },
+ },
+ { type: "function_call", name: "ok", arguments: "{}", call_id: "c1" },
+ ],
+ });
+ expect(out?.input).toEqual([
+ {
+ type: "function_call",
+ name: "ok",
+ arguments: "{}",
+ call_id: "c1",
+ },
+ ]);
+ });
+
+ it("drops empty reasoning shells and image generation items", () => {
+ const out = sanitizeXaiModelInputBody({
+ model: "grok-4.5",
+ input: [
+ { type: "message", role: "user", content: "hi" },
+ { type: "reasoning", summary: [] },
+ { type: "image_generation_call", status: "completed" },
+ ],
+ });
+ expect(out?.input).toEqual([
+ { type: "message", role: "user", content: "hi" },
+ ]);
+ });
+
+ it.each([
+ "grok-code-fast",
+ "x-ai/grok-code-fast",
+ "grok-build-0.1",
+ "xai/grok-build-preview",
+ ])("drops reasoning by default for non-reasoning model %s", (model) => {
+ expect(supportsXaiReasoningModel(model)).toBe(false);
+ const out = sanitizeXaiModelInputBody({
+ model,
+ input: [
+ {
+ type: "reasoning",
+ id: "rs_1",
+ summary: [],
+ encrypted_content: "BLOB",
+ },
+ { type: "message", role: "user", content: "hi" },
+ ],
+ });
+ expect(out?.input).toEqual([
+ { type: "message", role: "user", content: "hi" },
+ ]);
+ });
+
+ it("keeps well-formed reasoning for general Grok models by default", () => {
+ expect(supportsXaiReasoningModel("x-ai/grok-4.6")).toBe(true);
+ expect(
+ sanitizeXaiModelInputBody({
+ model: "x-ai/grok-4.6",
+ input: [
+ {
+ type: "reasoning",
+ id: "rs_1",
+ summary: [],
+ encrypted_content: "BLOB",
+ },
+ { type: "message", role: "user", content: "hi" },
+ ],
+ }),
+ ).toBeNull();
+ });
+
+ it("drops reasoning for unrecognized LiteLLM aliases", () => {
+ const out = sanitizeXaiModelInputBody({
+ model: "litellm-hidden-coding",
+ input: [
+ {
+ type: "reasoning",
+ id: "rs_1",
+ summary: [],
+ encrypted_content: "BLOB",
+ },
+ { type: "agent_message", author: "bot", content: "hi" },
+ ],
+ });
+ expect(out?.input).toEqual([
+ {
+ type: "message",
+ role: "assistant",
+ content: [{ type: "output_text", text: "[collab bot]\nhi" }],
+ },
+ ]);
+ });
+
+ it("uses output_text for assistant string parts and string content", () => {
+ const out = sanitizeXaiModelInputBody({
+ model: "x-ai/grok-4.6",
+ input: [
+ {
+ type: "message",
+ role: "assistant",
+ content: ["reply"],
+ },
+ {
+ type: "message",
+ role: "assistant",
+ content: "also a reply",
+ },
+ {
+ type: "message",
+ role: "assistant",
+ content: [{ type: "input_text", text: "legacy" }],
+ },
+ ],
+ });
+ expect(out?.input).toEqual([
+ {
+ type: "message",
+ role: "assistant",
+ content: [{ type: "output_text", text: "reply" }],
+ },
+ {
+ type: "message",
+ role: "assistant",
+ content: [{ type: "output_text", text: "also a reply" }],
+ },
+ {
+ type: "message",
+ role: "assistant",
+ content: [{ type: "output_text", text: "legacy" }],
+ },
+ ]);
+ });
+
+ it("converts refusal parts to output_text instead of emptying the message", () => {
+ const out = sanitizeXaiModelInputBody({
+ model: "x-ai/grok-4.6",
+ input: [
+ {
+ type: "message",
+ role: "assistant",
+ content: [{ type: "refusal", refusal: "I can't help with that." }],
+ },
+ ],
+ });
+ expect(out?.input).toEqual([
+ {
+ type: "message",
+ role: "assistant",
+ content: [{ type: "output_text", text: "I can't help with that." }],
+ },
+ ]);
+ });
+
+ it("emits empty-string text when input_text.text is not a string", () => {
+ const out = sanitizeXaiModelInputBody({
+ model: "x-ai/grok-4.6",
+ input: [
+ {
+ type: "message",
+ role: "user",
+ content: [{ type: "input_text", text: null }],
+ },
+ ],
+ });
+ expect(out?.input).toEqual([
+ {
+ type: "message",
+ role: "user",
+ content: [{ type: "input_text", text: "" }],
+ },
+ ]);
+ });
+
+ it("wraps a single object input into an array before sanitizing", () => {
+ const out = sanitizeXaiModelInputBody({
+ model: "grok-4.5",
+ input: { role: "user", content: "hi" },
+ });
+ expect(out?.input).toEqual([
+ { type: "message", role: "user", content: "hi" },
+ ]);
+ });
+});
+
+describe("createXaiModelInputSanitizeTransform", () => {
+ const transform = createXaiModelInputSanitizeTransform();
+ const ctx = { reqId: 1, method: "POST", url: "/responses", headers: {} };
+
+ it("sanitizes gateway grok models even without an xAI session", () => {
+ const out = transform(
+ {
+ model: "x-ai/grok-4.5",
+ input: [{ type: "agent_message", author: "bot", content: "hi" }],
+ },
+ ctx,
+ );
+ expect(out).toMatchObject({
+ input: [{ type: "message", role: "assistant" }],
+ });
+ });
+
+ it("does not rewrite GPT history", () => {
+ const body = {
+ model: "gpt-5.5",
+ input: [{ type: "agent_message", author: "bot", content: "hi" }],
+ };
+ expect(transform(body, ctx)).toBeNull();
+ });
+
+ it("drops reasoning on gateway coding models without an explicit override", () => {
+ const out = transform(
+ {
+ model: "x-ai/grok-code-fast",
+ input: [
+ {
+ type: "reasoning",
+ id: "rs_1",
+ summary: [],
+ encrypted_content: "BLOB",
+ },
+ { type: "message", role: "user", content: "hi" },
+ ],
+ },
+ ctx,
+ );
+ expect(out).toEqual({
+ model: "x-ai/grok-code-fast",
+ input: [{ type: "message", role: "user", content: "hi" }],
+ });
+ });
+});
+
+describe("createXaiModelInputRecoveryRule", () => {
+ const rule = createXaiModelInputRecoveryRule();
+
+ it("matches the LiteLLM-wrapped xAI 422 the client actually surfaces", () => {
+ const error =
+ "unexpected status 422 Unprocessable Entity: litellm.BadRequestError: XaiException - " +
+ '{"error":"Failed to deserialize the JSON body into the target type: ' +
+ 'data did not match any variant of untagged enum ModelInput"}, ' +
+ "url: http://127.0.0.1:55081/responses";
+ expect(rule.matches(error)).toBe(true);
+ });
+
+ it("does not match unrelated 422s", () => {
+ expect(
+ rule.matches("Could not decrypt the provided encrypted_content"),
+ ).toBe(false);
+ });
+
+ it("strips the offending items so a retry can proceed", () => {
+ const stripped = rule.strip(
+ Buffer.from(
+ JSON.stringify({
+ model: "my-grok-alias",
+ input: [
+ { type: "message", role: "user", content: "hi" },
+ { type: "agent_message", author: "bot", content: "secret" },
+ ],
+ }),
+ ),
+ );
+ expect(stripped).not.toBeNull();
+ expect(JSON.parse(stripped!.toString("utf8")).input).toEqual([
+ { type: "message", role: "user", content: "hi" },
+ {
+ type: "message",
+ role: "assistant",
+ content: [{ type: "output_text", text: "[collab bot]\nsecret" }],
+ },
+ ]);
+ });
+
+ it("drops reasoning on grok-code when retrying a ModelInput 422", () => {
+ const stripped = rule.strip(
+ Buffer.from(
+ JSON.stringify({
+ model: "x-ai/grok-code-fast",
+ input: [
+ { type: "reasoning", encrypted_content: "BLOB" },
+ { type: "agent_message", author: "bot", content: "hi" },
+ ],
+ }),
+ ),
+ );
+ expect(JSON.parse(stripped!.toString("utf8")).input).toEqual([
+ {
+ type: "message",
+ role: "assistant",
+ content: [{ type: "output_text", text: "[collab bot]\nhi" }],
+ },
+ ]);
+ });
+
+ it("drops reasoning when recovering a hidden coding-model alias", () => {
+ const stripped = rule.strip(
+ Buffer.from(
+ JSON.stringify({
+ model: "litellm-hidden-coding",
+ input: [
+ { type: "reasoning", encrypted_content: "BLOB" },
+ { type: "agent_message", author: "bot", content: "hi" },
+ ],
+ }),
+ ),
+ );
+ expect(JSON.parse(stripped!.toString("utf8")).input).toEqual([
+ {
+ type: "message",
+ role: "assistant",
+ content: [{ type: "output_text", text: "[collab bot]\nhi" }],
+ },
+ ]);
+ });
+
+ it("returns null when there is nothing to rewrite", () => {
+ expect(sanitizeXaiModelInputFromBody(Buffer.from("not json"))).toBeNull();
+ expect(
+ sanitizeXaiModelInputFromBody(
+ Buffer.from(
+ JSON.stringify({
+ model: "grok-4.5",
+ input: [{ type: "message", role: "user", content: "hi" }],
+ }),
+ ),
+ ),
+ ).toBeNull();
+ });
+});
diff --git a/packages/anthropic-compat-proxy/src/xai-model-input.ts b/packages/anthropic-compat-proxy/src/xai-model-input.ts
new file mode 100644
index 0000000000..587dd8283d
--- /dev/null
+++ b/packages/anthropic-compat-proxy/src/xai-model-input.ts
@@ -0,0 +1,659 @@
+/**
+ * xAI Responses `input[]` 归一化。
+ *
+ * Codex / PI / LiteLLM 历史里的 `agent_message`、`custom_tool_call`、
+ * Chat 形态 `role:"tool"`、reasoning 空壳对不上 xAI 的 untagged
+ * `ModelInput` 就会整包 422。但官方下一轮要 append 的 `response.output`
+ * (`web_search_call` / `code_interpreter_call` / `file_search_call` 等)
+ * 以及 `input_file` / `input_image.detail` 是合法回放,不能当未知项丢掉。
+ *
+ * 本模块是单一真相源:订阅直连、Gateway / LiteLLM 中转、PI 原生转发、
+ * 以及 422 透明重试都走这里。只改顶层 `input[]`,不动 tools / messages。
+ */
+
+import type { RecoveryRule, RequestTransform } from "./types.js";
+
+/**
+ * xAI / OpenAI Responses 官方会回放的 server-side tool item。
+ * 下一轮应原样 append `response.output`,不得当未知 type 丢掉。
+ */
+const XAI_PASSTHROUGH_INPUT_TYPES = new Set([
+ "web_search_call",
+ "file_search_call",
+ "code_interpreter_call",
+ "code_execution_call",
+ "code_execution_call_output",
+ "x_search_call",
+ "collections_search_call",
+ "shell_call",
+ "shell_call_output",
+ "local_shell_call",
+ "local_shell_call_output",
+ "computer_call",
+ "computer_call_output",
+ "mcp_call",
+ "mcp_list_tools",
+ "mcp_approval_request",
+ "mcp_approval_response",
+]);
+
+/** 归一化后允许进入 xAI `input[]` 的 type。 */
+const XAI_MODEL_INPUT_TYPES = new Set([
+ "message",
+ "function_call",
+ "function_call_output",
+ "reasoning",
+ ...XAI_PASSTHROUGH_INPUT_TYPES,
+]);
+
+const XAI_MODEL_INPUT_RE =
+ /did not match any variant of untagged enum ModelInput/i;
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+/**
+ * 网关 `x-ai/grok-*`、订阅 `xai/grok-*`、裸 `grok-*` 都算 xAI Responses 上游。
+ * 不依赖 catalog:本包零 runtime 依赖,判定只看 id 形态。
+ */
+export function looksLikeXaiResponsesModel(model: unknown): boolean {
+ if (typeof model !== "string" || model.trim().length === 0) return false;
+ const id = model.trim().toLowerCase();
+ const bare = id.includes("/") ? id.slice(id.lastIndexOf("/") + 1) : id;
+ return (
+ id.startsWith("xai/") || id.startsWith("x-ai/") || bare.startsWith("grok")
+ );
+}
+
+/** 去掉 `xai/` / `x-ai/` / LiteLLM 命名空间后的裸 model id。 */
+export function xaiBareModelId(model: unknown): string | null {
+ if (typeof model !== "string" || model.trim().length === 0) return null;
+ const id = model.trim();
+ return id.includes("/") ? id.slice(id.lastIndexOf("/") + 1) : id;
+}
+
+/**
+ * 与 anthropic-responses-bridge / oneShotCandidates 同源:
+ * `grok-code*` / `grok-build*` 不支持 reasoning(带上会 400)。
+ * 未知通用 Grok 默认当作支持,避免每出新模型就误剥回放。
+ */
+export function supportsXaiReasoningModel(model: unknown): boolean {
+ const bare = xaiBareModelId(model)?.toLowerCase();
+ if (!bare) return true;
+ return !(bare.startsWith("grok-code") || bare.startsWith("grok-build"));
+}
+
+function isXaiUnsupportedInputItem(
+ item: unknown,
+ opts: { supportsReasoning: boolean },
+): boolean {
+ if (!isPlainObject(item) || typeof item.type !== "string") return false;
+ if (item.type === "reasoning") {
+ return (
+ !opts.supportsReasoning ||
+ typeof item.encrypted_content !== "string" ||
+ item.encrypted_content.length === 0
+ );
+ }
+ return (
+ item.type.startsWith("image_generation") ||
+ item.type.startsWith("imageGeneration")
+ );
+}
+
+function textFromResponsesContent(value: unknown): string {
+ if (typeof value === "string") return value;
+ if (typeof value === "number" || typeof value === "boolean")
+ return String(value);
+ if (value == null) return "";
+ if (Array.isArray(value)) {
+ return value
+ .map((part) => {
+ if (typeof part === "string") return part;
+ if (!isPlainObject(part)) return "";
+ if (typeof part.text === "string") return part.text;
+ if (typeof part.input_text === "string") return part.input_text;
+ if (typeof part.output_text === "string") return part.output_text;
+ return "";
+ })
+ .filter((part) => part.length > 0)
+ .join("\n");
+ }
+ if (isPlainObject(value)) {
+ if (typeof value.text === "string") return value.text;
+ try {
+ return JSON.stringify(value);
+ } catch {
+ return String(value);
+ }
+ }
+ return String(value);
+}
+
+function argumentsFromCustomToolInput(value: unknown): string {
+ if (value == null) return "{}";
+
+ if (typeof value === "string") {
+ try {
+ const parsed = JSON.parse(value);
+ return JSON.stringify(isPlainObject(parsed) ? parsed : { input: parsed });
+ } catch {
+ return JSON.stringify({ input: value });
+ }
+ }
+
+ try {
+ return JSON.stringify(isPlainObject(value) ? value : { input: value });
+ } catch {
+ return JSON.stringify({ input: String(value) });
+ }
+}
+
+const COMPACTION_UNAVAILABLE_NOTE =
+ "[context note] Earlier conversation history was compacted into an encrypted snapshot by the " +
+ "OpenAI subscription backend and is not readable on the current model provider. Treat the " +
+ "conversation from this point on as the available context; ask the user if earlier details are needed.";
+
+function textPartTypeForRole(role: unknown): "input_text" | "output_text" {
+ return role === "assistant" ? "output_text" : "input_text";
+}
+
+function callIdFrom(
+ item: Record<string, unknown>,
+ kind: "call" | "output" = "call",
+): string {
+ if (typeof item.call_id === "string" && item.call_id.length > 0)
+ return item.call_id;
+ if (typeof item.tool_use_id === "string" && item.tool_use_id.length > 0)
+ return item.tool_use_id;
+ if (typeof item.tool_call_id === "string" && item.tool_call_id.length > 0)
+ return item.tool_call_id;
+ if (kind === "call" && typeof item.id === "string" && item.id.length > 0) {
+ return item.id;
+ }
+ return "";
+}
+
+function functionCallOutputFrom(
+ item: Record<string, unknown>,
+ output: unknown,
+): { item: unknown; changed: boolean } {
+ const callId = callIdFrom(item, "output");
+ if (!callId) return { item: null, changed: true };
+ return {
+ item: {
+ type: "function_call_output",
+ call_id: callId,
+ output:
+ typeof output === "string" ? output : textFromResponsesContent(output),
+ },
+ changed: true,
+ };
+}
+
+function functionCallFrom(
+ item: Record<string, unknown>,
+ name: string,
+ args: string,
+): { item: unknown; changed: boolean } {
+ const callId = callIdFrom(item);
+ if (!callId) return { item: null, changed: true };
+ const next: Record<string, unknown> = {
+ type: "function_call",
+ name,
+ arguments: args,
+ call_id: callId,
+ };
+ if (typeof item.id === "string") next.id = item.id;
+ return { item: next, changed: true };
+}
+
+function normalizeXaiInputItem(item: unknown): {
+ item: unknown;
+ changed: boolean;
+} {
+ if (typeof item === "string") {
+ return {
+ item: { type: "message", role: "user", content: item },
+ changed: true,
+ };
+ }
+ if (!isPlainObject(item)) {
+ return { item, changed: false };
+ }
+
+ // EasyInput 兼容:只有 role/content、缺 type 的 message 先补 type。
+ const base: Record<string, unknown> =
+ !("type" in item) && typeof item.role === "string" && "content" in item
+ ? { type: "message", ...item }
+ : item;
+ const typedFromEasy = base !== item;
+ const type = typeof base.type === "string" ? base.type : undefined;
+
+ if (type && XAI_PASSTHROUGH_INPUT_TYPES.has(type)) {
+ return { item: base, changed: typedFromEasy };
+ }
+
+ if (type === "compaction" || type === "context_compaction") {
+ return {
+ item: {
+ type: "message",
+ role: "user",
+ content: [{ type: "input_text", text: COMPACTION_UNAVAILABLE_NOTE }],
+ },
+ changed: true,
+ };
+ }
+
+ if (type === "custom_tool_call") {
+ return functionCallFrom(
+ base,
+ typeof base.name === "string" ? base.name : "",
+ argumentsFromCustomToolInput(base.input),
+ );
+ }
+
+ if (type === "custom_tool_call_output" || type === "tool_result") {
+ return functionCallOutputFrom(base, base.output ?? base.content);
+ }
+
+ // LiteLLM / Chat Completions 回放: `{type:"function"|"tool_call", function:{name,arguments}}`
+ if (type === "function" || type === "tool_call") {
+ const fn = isPlainObject(base.function) ? base.function : base;
+ const name =
+ typeof fn.name === "string"
+ ? fn.name
+ : typeof base.name === "string"
+ ? base.name
+ : "";
+ return functionCallFrom(
+ base,
+ name,
+ argumentsFromCustomToolInput(
+ fn.arguments ?? base.arguments ?? base.input,
+ ),
+ );
+ }
+
+ // Codex multi-agent collab 历史项。OpenAI 会话里的 agent_message 带着 author/
+ // recipient 和 content 里的 encrypted_content part;xAI ModelInput 不认这个 type,
+ // 跨源 resume 到 grok 时整轮 422。降级成 assistant message,只保留可读文本
+ // (collab 密文 part 解不开,丢掉)。
+ if (type === "agent_message") {
+ const bodyText = textFromResponsesContent(base.content).trim();
+ const author =
+ typeof base.author === "string" && base.author.length > 0
+ ? base.author
+ : "agent";
+ const text =
+ bodyText.length > 0
+ ? `[collab ${author}]\n${bodyText}`
+ : `[collab message from ${author}; encrypted payload omitted]`;
+ return {
+ item: {
+ type: "message",
+ role: "assistant",
+ content: [{ type: "output_text", text }],
+ },
+ changed: true,
+ };
+ }
+
+ if (type === "function_call") {
+ const callId = callIdFrom(base);
+ if (!callId) return { item: null, changed: true };
+ const normalizedArguments = argumentsFromCustomToolInput(base.arguments);
+ const next: Record<string, unknown> = {
+ type: "function_call",
+ name: typeof base.name === "string" ? base.name : "",
+ arguments: normalizedArguments,
+ call_id: callId,
+ };
+ if (typeof base.id === "string") next.id = base.id;
+ const changed =
+ typedFromEasy ||
+ normalizedArguments !== base.arguments ||
+ typeof base.call_id !== "string" ||
+ typeof base.name !== "string" ||
+ "status" in base ||
+ Object.keys(base).some(
+ (key) => !["type", "name", "arguments", "call_id", "id"].includes(key),
+ );
+ return changed
+ ? { item: next, changed: true }
+ : { item: base, changed: false };
+ }
+
+ if (type === "function_call_output") {
+ const callId = callIdFrom(base, "output");
+ if (!callId) return { item: null, changed: true };
+ const next: Record<string, unknown> = {
+ type: "function_call_output",
+ call_id: callId,
+ output:
+ typeof base.output === "string"
+ ? base.output
+ : textFromResponsesContent(base.output),
+ };
+ const changed =
+ typedFromEasy ||
+ typeof base.output !== "string" ||
+ typeof base.call_id !== "string" ||
+ Object.keys(base).some(
+ (key) => !["type", "call_id", "output"].includes(key),
+ );
+ return changed
+ ? { item: next, changed: true }
+ : { item: base, changed: false };
+ }
+
+ // 回放的 reasoning 项必须逐字回到上游签发时的形状 —— xAI 校验不过就整轮 400
+ // "Could not decode the compaction blob. Ensure it is unmodified from the compact response."
+ // codex 的结构体会把自己没用上的 `Option` 字段一并序列化(实测 `content: null`),
+ // 那是 xAI 从没发过的键;带着它回放等于「被改过」。这里收敛成 Responses 契约里
+ // reasoning 该有的四个键 —— 与 anthropic-responses-bridge 回放的形状同口径
+ // (那条路上的 grok-4.5 一直是通的)。
+ // encrypted_content / summary / id 原样搬,一个字节都不改写。
+ if (type === "reasoning") {
+ const next: Record<string, unknown> = { type: "reasoning" };
+ if (typeof base.id === "string" && base.id.length > 0) next.id = base.id;
+ next.summary = Array.isArray(base.summary) ? base.summary : [];
+ if (typeof base.encrypted_content === "string")
+ next.encrypted_content = base.encrypted_content;
+ const changed =
+ typedFromEasy ||
+ !Array.isArray(base.summary) ||
+ ("id" in base && next.id !== base.id) ||
+ ("encrypted_content" in base &&
+ next.encrypted_content !== base.encrypted_content) ||
+ Object.keys(base).some(
+ (key) => !["type", "id", "summary", "encrypted_content"].includes(key),
+ );
+ return changed
+ ? { item: next, changed: true }
+ : { item: base, changed: false };
+ }
+
+ if (type === "message") {
+ // LiteLLM / Chat Completions 把 tool 结果写成 role=tool 的 message。
+ // xAI message 变体不认这个 role,转成 function_call_output。
+ if (base.role === "tool" || base.role === "function") {
+ return functionCallOutputFrom(base, base.content);
+ }
+
+ let changed = typedFromEasy;
+ const next: Record<string, unknown> = { type: "message" };
+ const role = base.role === "developer" ? "system" : base.role;
+ if (role !== base.role) changed = true;
+ if (typeof role === "string") next.role = role;
+ if ("content" in base) next.content = base.content;
+ if (typeof base.id === "string") next.id = base.id;
+ for (const key of Object.keys(base)) {
+ if (key === "type" || key === "role" || key === "content" || key === "id")
+ continue;
+ changed = true;
+ }
+ if (Array.isArray(next.content)) {
+ const parts: unknown[] = [];
+ for (const part of next.content) {
+ if (typeof part === "string") {
+ parts.push({ type: textPartTypeForRole(role), text: part });
+ changed = true;
+ continue;
+ }
+ if (!isPlainObject(part)) {
+ changed = true;
+ continue;
+ }
+ const partType = typeof part.type === "string" ? part.type : undefined;
+ if (partType === "text") {
+ parts.push({
+ type: textPartTypeForRole(role),
+ text: typeof part.text === "string" ? part.text : "",
+ });
+ changed = true;
+ continue;
+ }
+ if (partType === "input_text" || partType === "output_text") {
+ const text = typeof part.text === "string" ? part.text : "";
+ const nextType = textPartTypeForRole(role);
+ parts.push({ type: nextType, text });
+ if (
+ nextType !== partType ||
+ typeof part.text !== "string" ||
+ Object.keys(part).some((k) => k !== "type" && k !== "text")
+ ) {
+ changed = true;
+ }
+ continue;
+ }
+ if (partType === "input_image") {
+ const nextPart: Record<string, unknown> = { type: "input_image" };
+ if (typeof part.image_url === "string") {
+ nextPart.image_url = part.image_url;
+ } else if (isPlainObject(part.image_url)) {
+ if (typeof part.image_url.url === "string") {
+ nextPart.image_url = part.image_url.url;
+ }
+ if (
+ !("detail" in part) &&
+ typeof part.image_url.detail === "string"
+ ) {
+ nextPart.detail = part.image_url.detail;
+ }
+ changed = true;
+ }
+ if ("detail" in part) nextPart.detail = part.detail;
+ if (typeof part.file_id === "string") nextPart.file_id = part.file_id;
+ if (!("image_url" in nextPart) && !("file_id" in nextPart)) {
+ changed = true;
+ continue;
+ }
+ const allowed = ["type", "image_url", "detail", "file_id"];
+ if (Object.keys(part).some((key) => !allowed.includes(key)))
+ changed = true;
+ parts.push(nextPart);
+ continue;
+ }
+ if (partType === "input_file") {
+ parts.push(part);
+ continue;
+ }
+ if (partType === "refusal") {
+ parts.push({
+ type: textPartTypeForRole(role),
+ text: typeof part.refusal === "string" ? part.refusal : "",
+ });
+ changed = true;
+ continue;
+ }
+ if (typeof part.text === "string" && part.text.length > 0) {
+ parts.push({
+ type: textPartTypeForRole(role),
+ text: part.text,
+ });
+ changed = true;
+ continue;
+ }
+ if (typeof part.refusal === "string" && part.refusal.length > 0) {
+ parts.push({
+ type: textPartTypeForRole(role),
+ text: part.refusal,
+ });
+ changed = true;
+ continue;
+ }
+ changed = true;
+ }
+ next.content = parts;
+ } else if (typeof next.content === "string") {
+ if (role === "assistant") {
+ next.content = [{ type: "output_text", text: next.content }];
+ changed = true;
+ }
+ } else {
+ next.content = textFromResponsesContent(next.content);
+ changed = true;
+ }
+ return changed
+ ? { item: next, changed: true }
+ : { item: base, changed: false };
+ }
+
+ // 未知 type 不透传:xAI untagged ModelInput 任一 item 对不上就整包 422。
+ return {
+ item: base,
+ changed:
+ typedFromEasy ||
+ (typeof type === "string" && !XAI_MODEL_INPUT_TYPES.has(type)),
+ };
+}
+
+export interface SanitizeXaiModelInputOptions {
+ /**
+ * false = 丢掉全部 reasoning(含带密文的)。
+ * 省略时:能识别的 grok-code* / grok-build* 为 false,能识别的通用 Grok
+ * 为 true;看不出底层型号的自定义别名保守为 false(否则 coding 模型
+ * 会在修完 agent_message 后仍因 reasoning 被拒)。
+ */
+ supportsReasoning?: boolean;
+}
+
+export interface XaiModelInputCompatOptions {
+ /** 覆盖默认的 grok-code / grok-build 判定;订阅直连可注入 catalog。 */
+ supportsReasoningForModel?: (model: unknown) => boolean;
+}
+
+/**
+ * 把 Responses 请求体的 `input[]` 收成 xAI 可反序列化的形态。
+ * 无 input 数组 / 无需改写 → null。
+ */
+export function sanitizeXaiModelInputBody(
+ body: Record<string, unknown>,
+ opts: SanitizeXaiModelInputOptions = {},
+): Record<string, unknown> | null {
+ const supportsReasoning =
+ opts.supportsReasoning ?? defaultSupportsReasoning(body.model);
+ let source = body;
+ let wrappedSingleItem = false;
+ if (isPlainObject(body.input) && !Array.isArray(body.input)) {
+ source = { ...body, input: [body.input] };
+ wrappedSingleItem = true;
+ }
+ if (!Array.isArray(source.input)) return null;
+
+ let changed = wrappedSingleItem;
+ const input: unknown[] = [];
+ for (const raw of source.input) {
+ if (isXaiUnsupportedInputItem(raw, { supportsReasoning })) {
+ changed = true;
+ continue;
+ }
+ const normalized = normalizeXaiInputItem(raw);
+ if (normalized.changed) changed = true;
+ if (
+ !isPlainObject(normalized.item) ||
+ typeof normalized.item.type !== "string" ||
+ !XAI_MODEL_INPUT_TYPES.has(normalized.item.type)
+ ) {
+ changed = true;
+ continue;
+ }
+ input.push(normalized.item);
+ }
+ if (!changed) return null;
+ return { ...source, input };
+}
+
+function defaultSupportsReasoning(model: unknown): boolean {
+ // 自定义 LiteLLM 别名看不出底层是 grok-4.5 还是 grok-code:保守丢掉 reasoning,
+ // 避免唯一一次 422 重试修完非法 item 后仍被 coding 模型拒。
+ if (!looksLikeXaiResponsesModel(model)) return false;
+ return supportsXaiReasoningModel(model);
+}
+
+function resolveSupportsReasoning(
+ model: unknown,
+ opts: {
+ supportsReasoning?: boolean;
+ supportsReasoningForModel?: (model: unknown) => boolean;
+ } = {},
+): boolean {
+ if (typeof opts.supportsReasoning === "boolean")
+ return opts.supportsReasoning;
+ if (opts.supportsReasoningForModel)
+ return opts.supportsReasoningForModel(model);
+ return defaultSupportsReasoning(model);
+}
+
+/** Recovery / active-strip 用:非 JSON 或无需改写 → null。 */
+export function sanitizeXaiModelInputFromBody(
+ rawBody: Buffer,
+ opts: {
+ supportsReasoning?: boolean;
+ supportsReasoningForModel?: (model: unknown) => boolean;
+ } = {},
+): Buffer | null {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(rawBody.toString("utf8"));
+ } catch {
+ return null;
+ }
+ if (!isPlainObject(parsed)) return null;
+ const sanitized = sanitizeXaiModelInputBody(parsed, {
+ supportsReasoning: resolveSupportsReasoning(parsed.model, opts),
+ });
+ if (!sanitized) return null;
+ try {
+ return Buffer.from(JSON.stringify(sanitized), "utf8");
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * 发送前主动清洗:只对 grok / xAI 形态的 model 动手,GPT / Claude 历史原样透传。
+ */
+export function createXaiModelInputSanitizeTransform(
+ opts: XaiModelInputCompatOptions = {},
+): RequestTransform {
+ return (body) => {
+ if (!isPlainObject(body) || !looksLikeXaiResponsesModel(body.model))
+ return null;
+ return sanitizeXaiModelInputBody(body, {
+ supportsReasoning: resolveSupportsReasoning(body.model, {
+ supportsReasoningForModel: opts.supportsReasoningForModel,
+ }),
+ });
+ };
+}
+
+/**
+ * 422 ModelInput 恢复规则:命中后按同一套清洗重发一次。
+ * 模型 id 不像 grok 的自定义 LiteLLM 路由靠这条兜底;onRetry 后由
+ * active-strip 在后续 turn 发送前预洗。
+ */
+export function createXaiModelInputRecoveryRule(
+ opts: {
+ enabled?: () => boolean;
+ onRetry?: (threadId: string, model: string) => void;
+ threadIdHeaders?: readonly string[];
+ supportsReasoningForModel?: (model: unknown) => boolean;
+ } = {},
+): RecoveryRule {
+ return {
+ id: "xai_model_input",
+ enabled: opts.enabled ?? (() => true),
+ matches: (text) => XAI_MODEL_INPUT_RE.test(text),
+ strip: (rawBody) =>
+ sanitizeXaiModelInputFromBody(rawBody, {
+ supportsReasoningForModel: opts.supportsReasoningForModel,
+ }),
+ onRetry: opts.onRetry,
+ threadIdHeaders: opts.threadIdHeaders,
+ applyOnUnmatchedRetry: false,
+ allowExtraRules: false,
+ };
+}