Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
refactor(model): consolidate compatibility with pinned OpenCodex patches
Chris38658f3bc208
diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex e343fba0d3..70f1f4c885 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -69,6 +69,7 @@"@cindy/maker-scheduler": "workspace:*","@cindy/maker-shared": "workspace:*","@cindy/mcps": "workspace:*",+ "@cindy/model-compat": "workspace:*","@cindy/model-providers": "workspace:*","@cindy/orca-workflow": "workspace:*","@cindy/plugin-protocol": "workspace:*",diff --git a/apps/desktop/scripts/build-remote-bundles.mjs b/apps/desktop/scripts/build-remote-bundles.mjsindex 4cb18cba00..8be1d9a8fc 100644--- a/apps/desktop/scripts/build-remote-bundles.mjs+++ b/apps/desktop/scripts/build-remote-bundles.mjs@@ -16,10 +16,11 @@// change are sub-100ms (just stat + copy if dest also needs refresh).import { spawnSync } from 'node:child_process';-import { copyFileSync, existsSync, mkdirSync, readdirSync, statSync } from 'node:fs';+import { copyFileSync, existsSync, mkdirSync, statSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import process from 'node:process';+import { newestBundleInputMtime } from './remote-bundle-inputs.mjs';const here = dirname(fileURLToPath(import.meta.url));const DESKTOP_ROOT = resolve(here, '..');@@ -37,6 +38,7 @@ const TARGETS = [},{pkgName: '@cindy/anthropic-compat-proxy',+ dependencyDirs: [resolve(MONOREPO_ROOT, 'packages', 'model-compat')],pkgDir: resolve(MONOREPO_ROOT, 'packages', 'anthropic-compat-proxy'),bundleFile: 'dist/proxy.mjs',destDir: resolve(DESKTOP_ROOT, 'resources', 'anthropic-compat-proxy'),@@ -58,27 +60,6 @@ const TARGETS = [},];-function newestMtime(rootDir, relPaths) {- let newest = 0;- for (const rel of relPaths) {- const abs = join(rootDir, rel);- if (!existsSync(abs)) continue;- const st = statSync(abs);- if (st.isDirectory()) {- // Recursive walk; readdirSync({recursive:true}) is Node 20+ stable.- const entries = readdirSync(abs, { recursive: true, withFileTypes: true });- for (const e of entries) {- if (!e.isFile()) continue;- const child = statSync(join(e.parentPath ?? abs, e.name));- if (child.mtimeMs > newest) newest = child.mtimeMs;- }- } else {- if (st.mtimeMs > newest) newest = st.mtimeMs;- }- }- return newest;-}-function bundleIfStale(target) {const bundleAbs = join(target.pkgDir, target.bundleFile);const bundleMtime = existsSync(bundleAbs) ? statSync(bundleAbs).mtimeMs : 0;@@ -86,7 +67,7 @@ function bundleIfStale(target) {// package.json (deps could change). pnpm-lock.yaml is at monorepo root —// skipping it intentionally; an esbuild bump would touch package.json// either way via devDependencies.- const srcMtime = newestMtime(target.pkgDir, ['src', 'build.mjs', 'package.json']);+ const srcMtime = newestBundleInputMtime(target.pkgDir, target.dependencyDirs);if (bundleMtime >= srcMtime && bundleMtime > 0) {return false; // up-to-date}diff --git a/apps/desktop/scripts/remote-bundle-inputs.mjs b/apps/desktop/scripts/remote-bundle-inputs.mjsnew file mode 100644index 0000000000..0d44bc4bf0--- /dev/null+++ b/apps/desktop/scripts/remote-bundle-inputs.mjs@@ -0,0 +1,28 @@+import { existsSync, readdirSync, statSync } from 'node:fs';+import { join } from 'node:path';++function newestMtime(rootDir, relPaths) {+ let newest = 0;+ for (const rel of relPaths) {+ const abs = join(rootDir, rel);+ if (!existsSync(abs)) continue;+ const st = statSync(abs);+ if (st.isDirectory()) {+ for (const entry of readdirSync(abs, { recursive: true, withFileTypes: true })) {+ if (!entry.isFile()) continue;+ newest = Math.max(newest, statSync(join(entry.parentPath ?? abs, entry.name)).mtimeMs);+ }+ } else newest = Math.max(newest, st.mtimeMs);+ }+ return newest;+}++/** A workspace dependency can change without touching the consuming package's source. */+export function newestBundleInputMtime(pkgDir, dependencyDirs = []) {+ let newest = newestMtime(pkgDir, ['src', 'build.mjs', 'package.json']);+ for (const dependency of dependencyDirs) {+ if (!existsSync(dependency)) throw new Error(`Remote bundle source dependency is missing: ${dependency}`);+ newest = Math.max(newest, newestMtime(dependency, ['src', 'package.json', 'LICENSE.opencodex']));+ }+ return newest;+}diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.tsindex 2179e77f93..a98e8389b3 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts@@ -2708,13 +2708,13 @@ describe('codex proxy host', () => {// upstream 是函数形态(每请求现取,model-access 下发可运行期换 endpoint);// 断言其当前求值 = 网关 base + /v1upstream: 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, exec function adapter, strict gateway history 兼容, xAI ModelInput sanitize, DeepSeek V4 custom tool 兼容, xAI Responses 兼容, XD Gateway Grok 兼容, ByteDance Seed tool 兼容, MiniMax effort 兼容, provider model rewrite, 视觉桥(controller 未注入 → 短路透传), 工具 ID 校正, stripNonAnthropicFields]+ // [encrypted activeStrip, image generation activeStrip, provider-aware Guardian reviewer, locked Subagent route, instructions 注入, locked Subagent exec guard, Gateway 原生 web_search, 跨来源压缩块兼容, xAI ModelInput activeStrip, exec function adapter, strict gateway history 兼容, xAI ModelInput sanitize, DeepSeek V4 custom tool 兼容, xAI Responses 兼容, XD Gateway Grok 兼容, ByteDance Seed tool 兼容, MiniMax effort 兼容, provider model rewrite, provider 参数归一, 视觉桥(controller 未注入 → 短路透传), 工具 ID 校正, 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), expect.any(Function),- expect.any(Function), expect.any(Function),+ expect.any(Function), expect.any(Function), expect.any(Function),],transformResponse: expect.any(Function),routingTransform: expect.any(Function),@@ -4181,7 +4181,9 @@ describe('codex proxy host', () => {reasoning: { effort: 'high', summary: 'auto' },tools: [{ type: 'function', name: 'read_file' },- { type: 'web_search', filters: { allowed_domains: ['docs.x.ai'] }, enable_image_search: true },+ // Namespace tools now survive through OpenCodex's reversible flattening.+ { type: 'function', name: 'multi_agent_v1__close_agent' },+ { type: 'web_search', filters: { allowed_domains: ['docs.x.ai'] }, enable_image_search: true, user_location: { type: 'approximate', country: 'US' } },// Codex 不知道 xAI 还有 x_search;由 host 恒定补在末尾,Grok 才有 X 的实时视野。{ type: 'x_search' },],@@ -5632,6 +5634,7 @@ describe('codex proxy host', () => {tools: [{ type: 'function', name: 'exec_command' },{ type: 'function', name: 'write_stdin' },+ { type: 'function', name: 'multi_agent_v1__close_agent' },{ type: 'web_search' },],tool_choice: 'auto',@@ -5720,6 +5723,7 @@ describe('codex proxy host', () => {reasoning: { effort: 'high' },tools: [{ type: 'function', name: 'exec_command' },+ { type: 'function', name: 'mcp__example__read' },{ type: 'web_search' },],input: [@@ -5816,7 +5820,7 @@ describe('codex proxy host', () => {expect(current).toEqual({model: 'doubao-seed-2-1-pro-260628',- tools: [{ type: 'function', name: 'exec_command' }],+ tools: [{ type: 'function', name: 'exec_command' }, { type: 'function', name: 'mcp__example__read' }],input: 'hello',});});@@ -6351,7 +6355,7 @@ describe('codex proxy host', () => {await host.ensureCodexProxyReady();const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];- expect(transforms).toHaveLength(22); // encrypted activeStrip, image generation activeStrip, provider-aware Guardian reviewer, locked Subagent route, instructions 注入, locked Subagent exec guard, Gateway 原生 web_search, 跨来源压缩块兼容, xAI ModelInput activeStrip, exec function adapter, strict gateway history 兼容, xAI ModelInput sanitize, DeepSeek V4 custom tool 兼容, xAI Responses 兼容, XD Gateway Grok 兼容, ByteDance Seed tool 兼容, MiniMax effort 兼容, provider model rewrite, 视觉桥(短路), 工具 ID 校正, stripNonAnthropicFields, dump+ expect(transforms).toHaveLength(23); // encrypted activeStrip, image generation activeStrip, provider-aware Guardian reviewer, locked Subagent route, instructions 注入, locked Subagent exec guard, Gateway 原生 web_search, 跨来源压缩块兼容, xAI ModelInput activeStrip, exec function adapter, strict gateway history 兼容, xAI ModelInput sanitize, DeepSeek V4 custom tool 兼容, xAI Responses 兼容, XD Gateway Grok 兼容, ByteDance Seed tool 兼容, MiniMax effort 兼容, provider model rewrite, provider 参数归一, 视觉桥(短路), 工具 ID 校正, stripNonAnthropicFields, dumpconst ctx = {method: 'POST',url: '/v1/responses',diff --git a/apps/desktop/src/main/maker-host/codex-proxy-host.ts b/apps/desktop/src/main/maker-host/codex-proxy-host.tsindex 35e3389c06..6c8520cd9b 100644--- a/apps/desktop/src/main/maker-host/codex-proxy-host.ts+++ b/apps/desktop/src/main/maker-host/codex-proxy-host.ts@@ -1,3 +1,5 @@+import { normalizeProviderRequest, normalizeMiniMaxResponsesReasoning } from '@cindy/model-compat';+import { createCodexResponsesCompatibilityAdapter, sanitizeXaiTools, hasCacheOnlySearchProhibition, sanitizeByteDanceSeedTools, normalizeByteDanceSeedInput, sanitizeByteDanceSeedReasoning, normalizeStrictGatewayHistory, sanitizeDeepSeekV4CustomTools } from '@cindy/model-compat';import { peekGrokAccessToken } from './grok-oauth-login.js';import { bearerAccessTokenFromHeaders } from './chatgpt-bridge-auth-invalidation.js';import { isAppSessionBoundaryPending } from '../appSessionState.js';@@ -45,7 +47,6 @@ import {import { buildVisionBridgeProxyTransform } from '../vision-bridge/vision-bridge-controller.js';import {chainResponseTransforms,- createResponsesCustomToolFunctionAdapter,createResponsesNullArrayRepairTransform,normalizeResponsesToolItemIds,createResponsesChatHandler,@@ -1554,113 +1555,6 @@ function stripUnsupportedXaiReasoning(body: Record<string, unknown>): Record<strreturn changed ? next : null;}-const XAI_SUPPORTED_TOOL_TYPES = new Set([- 'function',- 'web_search',- 'x_search',- 'collections_search',- 'file_search',- 'code_execution',- 'code_interpreter',- 'mcp',- 'shell',-]);--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;- const tools: unknown[] = [];- for (const tool of body.tools) {- if (!isPlainObject(tool) || typeof tool.type !== 'string' || !XAI_SUPPORTED_TOOL_TYPES.has(tool.type)) {- changed = true;- 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] = toolRecord[key];- }- if (Object.keys(nextTool).length !== Object.keys(tool).length) changed = true;- tools.push(nextTool);- continue;- }- tools.push(tool);- }- if (!changed) return null;-- const next: Record<string, unknown> = { ...body };- 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;-}-/*** 给 xAI 会话恒定补上 xAI 的服务端搜索工具(当前是 `x_search`,Grok 原生搜 X)。*@@ -1688,16 +1582,6 @@ 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;@@ -1767,225 +1651,6 @@ function isByteDanceSeedRequest(return isByteDanceSeedModel(body.model) || isVolcengineArkResponsesRouting(ctx, body.model);}-function seedToolChoiceReferencesRemovedTool(- toolChoice: unknown,- tools: Record<string, unknown>[],-): boolean {- if (!isPlainObject(toolChoice) || typeof toolChoice.type !== 'string') return false;-- return !tools.some((tool) => {- if (tool.type !== toolChoice.type) return false;- if (toolChoice.type !== 'function') return true;- return typeof toolChoice.name === 'string' && tool.name === toolChoice.name;- });-}--function sanitizeByteDanceSeedTools(body: Record<string, unknown>): Record<string, unknown> | null {- if (!Array.isArray(body.tools)) return null;-- let changed = false;- const tools: Record<string, unknown>[] = [];- for (const tool of body.tools) {- if (!isPlainObject(tool)) {- changed = true;- continue;- }- if (tool.type === 'function') {- tools.push(tool);- continue;- }- if (tool.type === 'web_search') {- // Seed cannot represent Codex's cache-only search policy. Dropping the- // tool preserves the caller's explicit prohibition on live web access.- if (tool.external_web_access === false) {- changed = true;- continue;- }- tools.push({ type: 'web_search' });- if (Object.keys(tool).length !== 1) changed = true;- continue;- }- changed = true;- }- if (!changed) return null;-- const next: Record<string, unknown> = { ...body };- if (tools.length > 0) {- next.tools = tools;- if (seedToolChoiceReferencesRemovedTool(next.tool_choice, tools)) next.tool_choice = 'auto';- } else {- delete next.tools;- delete next.tool_choice;- delete next.parallel_tool_calls;- }- return next;-}--const STRICT_GATEWAY_TOOL_HISTORY_MODELS = new Set([- 'moonshot/kimi-k3',- 'moonshotai/kimi-k3',- 'deepseek/deepseek-v4-pro',- 'deepseek/deepseek-v4-flash',-]);-// DeepSeek V4's Responses compatibility endpoint accepts the host's patch-// custom tool, but rejects every other custom tool (notably Codex's `exec`).-// Keep ordinary function tools untouched: the restriction is specifically on-// the Responses `custom` tool dialect, not on function calling as a whole.-const DEEPSEEK_V4_MODELS = new Set([- 'deepseek/deepseek-v4-pro',- 'deepseek/deepseek-v4-flash',-]);-const DEEPSEEK_V4_SUPPORTED_CUSTOM_TOOL_NAMES = new Set(['apply_patch']);-const RESPONSE_TOOL_CALL_TYPES = new Set(['function_call', 'custom_tool_call']);-const RESPONSE_TOOL_OUTPUT_TYPES = new Set(['function_call_output', 'custom_tool_call_output']);--function responseToolCallId(item: unknown, output: boolean): string | null {- if (!isPlainObject(item)) return null;- const supportedTypes = output ? RESPONSE_TOOL_OUTPUT_TYPES : RESPONSE_TOOL_CALL_TYPES;- if (!supportedTypes.has(typeof item.type === 'string' ? item.type : '')) return null;- return typeof item.call_id === 'string' && item.call_id.length > 0 ? item.call_id : null;-}--function stripEmptyResponseMessage(item: unknown): { item: unknown; changed: boolean } | null {- if (!isPlainObject(item) || item.type !== 'message') return { item, changed: false };- if (item.content === '') return null;- if (!Array.isArray(item.content)) return { item, changed: false };-- const content = item.content.filter((part) => !(- isPlainObject(part) &&- (part.type === 'input_text' || part.type === 'output_text') &&- part.text === ''- ));- if (content.length === 0) return null;- return content.length === item.content.length- ? { item, changed: false }- : { item: { ...item, content }, changed: true };-}--/** Volcengine requires replayed assistant messages to carry their output status and non-empty text. */-function normalizeByteDanceSeedInput(body: Record<string, unknown>): Record<string, unknown> | null {- if (!Array.isArray(body.input)) return null;-- let changed = false;- const input: unknown[] = [];- for (const item of body.input) {- const normalized = stripEmptyResponseMessage(item);- if (!normalized) {- changed = true;- continue;- }- if (normalized.changed) changed = true;-- const nextItem = normalized.item;- if (- isPlainObject(nextItem) &&- nextItem.type === 'message' &&- nextItem.role === 'assistant' &&- typeof nextItem.status !== 'string'- ) {- changed = true;- input.push({ ...nextItem, status: 'completed' });- continue;- }- input.push(nextItem);- }- return changed ? { ...body, input } : null;-}--/**- * LiteLLM converts gateway Responses history to Chat Completions for these models.- * Their native APIs require every assistant tool call to be followed immediately- * by its tool result, while Codex may persist an assistant progress message between- * the Responses function_call and function_call_output items. Codex may also persist- * empty assistant output_text items, which Moonshot rejects after history conversion.- * Consecutive calls form one parallel assistant group, so their matched outputs must- * be moved after the whole group rather than inserted between calls.- */-function normalizeStrictGatewayHistory(- body: Record<string, unknown>,- routingModel = typeof body.model === 'string' ? body.model : '',-): Record<string, unknown> | null {- if (- !STRICT_GATEWAY_TOOL_HISTORY_MODELS.has(routingModel) ||- !Array.isArray(body.input)- ) {- return null;- }-- const originalInput = body.input;- const normalizedInput: unknown[] = [];- for (const item of originalInput) {- const normalized = stripEmptyResponseMessage(item);- if (normalized) normalizedInput.push(normalized.item);- }-- const matchedOutputs = new Map<number, number>();- const usedOutputIndexes = new Set<number>();- const outputIndexesByCallId = new Map<string, number[]>();- const outputCursorByCallId = new Map<string, number>();- for (let index = 0; index < normalizedInput.length; index += 1) {- const outputCallId = responseToolCallId(normalizedInput[index], true);- if (!outputCallId) continue;- const indexes = outputIndexesByCallId.get(outputCallId) ?? [];- indexes.push(index);- outputIndexesByCallId.set(outputCallId, indexes);- }-- for (let callIndex = 0; callIndex < normalizedInput.length; callIndex += 1) {- const callId = responseToolCallId(normalizedInput[callIndex], false);- if (!callId) continue;-- const outputIndexes = outputIndexesByCallId.get(callId);- if (!outputIndexes) continue;- let cursor = outputCursorByCallId.get(callId) ?? 0;- while (cursor < outputIndexes.length && outputIndexes[cursor] <= callIndex) cursor += 1;- if (cursor >= outputIndexes.length) continue;-- const outputIndex = outputIndexes[cursor];- outputCursorByCallId.set(callId, cursor + 1);- matchedOutputs.set(callIndex, outputIndex);- usedOutputIndexes.add(outputIndex);- }-- const outputIndexesByGroupEnd = new Map<number, number[]>();- for (let groupStart = 0; groupStart < normalizedInput.length;) {- if (!responseToolCallId(normalizedInput[groupStart], false)) {- groupStart += 1;- continue;- }- let groupEnd = groupStart;- while (- groupEnd + 1 < normalizedInput.length &&- responseToolCallId(normalizedInput[groupEnd + 1], false)- ) {- groupEnd += 1;- }- const outputIndexes: number[] = [];- for (let callIndex = groupStart; callIndex <= groupEnd; callIndex += 1) {- const outputIndex = matchedOutputs.get(callIndex);- if (outputIndex !== undefined) outputIndexes.push(outputIndex);- }- if (outputIndexes.length > 0) {- outputIndexesByGroupEnd.set(groupEnd, outputIndexes.sort((a, b) => a - b));- }- groupStart = groupEnd + 1;- }-- const input: unknown[] = [];- for (let index = 0; index < normalizedInput.length; index += 1) {- if (usedOutputIndexes.has(index)) continue;- input.push(normalizedInput[index]);- const outputIndexes = outputIndexesByGroupEnd.get(index);- if (outputIndexes) {- for (const outputIndex of outputIndexes) input.push(normalizedInput[outputIndex]);- }- }- const changed =- input.length !== originalInput.length ||- input.some((item, index) => item !== originalInput[index]);- return changed ? { ...body, input } : null;-}-function createStrictGatewayHistoryCompatTransform(): RequestTransform {return (body, ctx) => {if (!isPlainObject(body) || typeof body.model !== 'string') return null;@@ -1994,73 +1659,6 @@ function createStrictGatewayHistoryCompatTransform(): RequestTransform {};}-function deepSeekToolChoiceReferencesRemovedCustomTool(- toolChoice: unknown,- tools: readonly unknown[],-): boolean {- if (!isPlainObject(toolChoice) || toolChoice.type !== 'custom' || typeof toolChoice.name !== 'string') {- return false;- }- return !tools.some((tool) =>- tool === toolChoice.name ||- (isPlainObject(tool) && tool.type === 'custom' && tool.name === toolChoice.name),- );-}--/**- * DeepSeek V4 rejects Codex's general-purpose custom `exec` tool before it- * reaches the model, while accepting `apply_patch`. Filter only that custom- * tool dialect so function/MCP declarations keep their existing semantics.- */-function sanitizeDeepSeekV4CustomTools(body: unknown): Record<string, unknown> | null {- if (!isPlainObject(body)) return null;- if (!DEEPSEEK_V4_MODELS.has(typeof body.model === 'string' ? body.model : '')) return null;- if (!Array.isArray(body.tools)) return null;-- let changed = false;- const tools: unknown[] = [];- for (const tool of body.tools) {- const customToolName =- typeof tool === 'string'- ? tool- : isPlainObject(tool) && tool.type === 'custom' && typeof tool.name === 'string'- ? tool.name- : null;- if (customToolName !== null && !DEEPSEEK_V4_SUPPORTED_CUSTOM_TOOL_NAMES.has(customToolName)) {- changed = true;- continue;- }- tools.push(tool);- }- if (!changed) return null;-- const next: Record<string, unknown> = { ...body };- if (tools.length > 0) {- next.tools = tools;- if (deepSeekToolChoiceReferencesRemovedCustomTool(next.tool_choice, tools)) next.tool_choice = 'auto';- } else {- delete next.tools;- delete next.tool_choice;- delete next.parallel_tool_calls;- }- return next;-}--/** Seed accepts the reasoning effort, but rejects Responses' summary selector. */-function sanitizeByteDanceSeedReasoning(body: Record<string, unknown>): Record<string, unknown> | null {- if (!isPlainObject(body.reasoning) || !('summary' in body.reasoning)) {- return null;- }-- const reasoning = { ...body.reasoning };- delete reasoning.summary;-- const next: Record<string, unknown> = { ...body };- if (Object.keys(reasoning).length > 0) next.reasoning = reasoning;- else delete next.reasoning;- return next;-}-function createByteDanceSeedResponsesCompatTransform(): RequestTransform {return (body, ctx) => {if (!isPlainObject(body)) return null;@@ -2160,11 +1758,11 @@ function createXaiResponsesCompatTransform(): RequestTransform {};}-function needsExecFunctionAdapter(+function responsesCompatibilityRouting(body: Record<string, unknown>,ctx: RequestTransformCtx,frozenAuthInjection?: CodexProxyAuthInjection,-): boolean {+) {const requestModel = typeof body.model === 'string' ? body.model : '';const providerContext = providerContextForRequest(ctx.headers, requestModel);const authInjection = frozenAuthInjection ?? getCodexProxyAuthInjection();@@ -2209,8 +1807,7 @@ function needsExecFunctionAdapter(routing = getProviderRoutingDescriptor(defaultProviderId, 'codex', requestModel);}- return (routing?.wireProtocol ?? 'openai-responses') === 'openai-responses'- && routing?.supportsResponsesCustomTools === false;+ return routing;}/**@@ -2439,19 +2036,7 @@ function createMiniMaxResponsesCompatTransform(): RequestTransform {|| typeof body.model !== 'string'|| !isMiniMaxResponsesSession(ctx, body.model)) return null;- const reasoning = body.reasoning;- if (!isPlainObject(reasoning)) return null;- let changed = false;- const nextReasoning = { ...reasoning };- if (nextReasoning.effort === 'xhigh') {- nextReasoning.effort = 'high';- changed = true;- }- if ('summary' in nextReasoning) {- delete nextReasoning.summary;- changed = true;- }- return changed ? { ...body, reasoning: nextReasoning } : null;+ return normalizeMiniMaxResponsesReasoning(body);};}@@ -3214,12 +2799,33 @@ export function createModelRoutingTransform(function createTransformRequestChain(frozenAuthInjection?: CodexProxyAuthInjection,- execAdapter = createResponsesCustomToolFunctionAdapter(['exec']),+ execAdapter = createCodexResponsesCompatibilityAdapter(),): RequestTransform[] {- const execFunctionAdapterTransform: RequestTransform = (body, ctx) =>- isPlainObject(body) && needsExecFunctionAdapter(body, ctx, frozenAuthInjection)- ? execAdapter.adaptRequest(body, ctx.reqId)- : null;+ const execFunctionAdapterTransform: RequestTransform = (body, ctx) => {+ if (!isPlainObject(body)) return null;+ const routing = responsesCompatibilityRouting(body, ctx, frozenAuthInjection);+ if ((routing?.wireProtocol ?? 'openai-responses') !== 'openai-responses'+ || routing?.supportsResponsesCustomTools !== false) return null;+ const upstreamBase = ctx.upstreamBase ?? routing.upstream;+ const model = rewriteChatBridgeModel(String(body.model ?? ''), routing.modelIdRewrite?.stripPrefix);+ // Only known provider endpoints or the existing XD model contract lower namespaces.+ const endpoint = new URL(upstreamBase);+ const gateway = new URL(getProviderRoutingDescriptor('xd', 'codex', String(body.model ?? ''))?.upstream ?? upstreamBase);+ const knownEndpoint = ['api.x.ai', 'cli-chat-proxy.grok.com', 'api.deepseek.com'].includes(endpoint.hostname)+ || VOLCENGINE_ARK_CHAT_HOST_RE.test(endpoint.hostname);+ const gatewayDialect = endpoint.origin === gateway.origin && /^(?:x-ai\/grok|deepseek\/|bytedance-seed\/|doubao-seed-)/.test(String(body.model ?? ''));+ return execAdapter.adaptRequest(body, ctx.reqId,+ { harness: 'codex', protocol: 'openai-responses', upstreamBase, model }, knownEndpoint || gatewayDialect);+ };+ const providerRequestTransform: RequestTransform = (body, ctx) => {+ if (!isPlainObject(body) || !ctx.upstreamBase) return null;+ const routing = responsesCompatibilityRouting(body, ctx, frozenAuthInjection);+ if ((routing?.wireProtocol ?? 'openai-responses') !== 'openai-responses') return null;+ // This runs after model rewriting and existing fail-closed search policy.+ const next = normalizeProviderRequest(body, { harness: 'codex', protocol: 'openai-responses', upstreamBase: ctx.upstreamBase, model: String(body.model ?? '') });+ return next === body ? null : next;+ };+ providerRequestTransform.errorMode = 'reject-request';execFunctionAdapterTransform.errorMode = 'reject-request';execFunctionAdapterTransform.onRequestSettled = (requestId) => {execAdapter.releaseResponse(requestId);@@ -3270,6 +2876,7 @@ function createTransformRequestChain(createByteDanceSeedResponsesCompatTransform(),createMiniMaxResponsesCompatTransform(),createProviderModelRewriteTransform(),+ providerRequestTransform,// 视觉桥透明替换(层 A,Responses 格式):controller 未注入时短路透传,零干扰;// 注入后把纯文本模型请求 input[] 里的 input_image 转成文字描述。放在 strip 之前与// Anthropic 链一致,避免未来 strip 扩展覆盖 Responses input_image 时吃掉图。@@ -3381,7 +2988,7 @@ function createCodexProxyHandle(frozenAuthInjection?: CodexProxyAuthInjection,frozenCustomProviderRoutes?: readonly CodexCustomProviderRoute[],): Promise<ProxyHandle> {- const execAdapter = createResponsesCustomToolFunctionAdapter(['exec']);+ const execAdapter = createCodexResponsesCompatibilityAdapter();return createAnthropicCompatProxy({// 默认上游 = gateway(含 /v1);普通模型 + oauth 由 routingTransform 覆盖到 ChatGPT。upstream: () => buildCodexGatewayBaseUrl(),diff --git a/package.json b/package.jsonindex 303899cb17..c2880c3506 100644--- a/package.json+++ b/package.json@@ -125,7 +125,7 @@"licenses:generate": "node scripts/generate-third-party-notices.mjs","lint": "pnpm -r lint","format": "pnpm -r format",- "test:runner": "node --test scripts/__tests__/test-workspaces.test.mjs scripts/__tests__/test-related.test.mjs scripts/__tests__/desktop-worker-benchmark.test.mjs scripts/__tests__/dev-docs-contract.test.mjs scripts/__tests__/restart-desktop-remote.test.mjs scripts/__tests__/dev-migration-policy.test.mjs scripts/__tests__/ensure-deps.test.mjs scripts/__tests__/client-endpoint-build-env.test.mjs scripts/__tests__/log-upload-build-env.test.mjs scripts/__tests__/desktop-dev-region.test.mjs scripts/__tests__/endpoint-consistency.test.mjs scripts/__tests__/endpoint-local-file.test.mjs scripts/__tests__/ensure-agent-binaries.test.mjs scripts/__tests__/ensure-android-platform-tools.test.mjs scripts/__tests__/fetch-with-timeout.test.mjs scripts/__tests__/agent-binary-cdn-fallback.test.mjs scripts/__tests__/ensure-binary-fallback.test.mjs scripts/__tests__/verify-sha256.test.mjs scripts/__tests__/codex-package-update-layout.test.mjs scripts/__tests__/pi-update-layout.test.mjs scripts/__tests__/migration-freeze.test.mjs scripts/__tests__/third-party-notices.test.mjs scripts/__tests__/brand-identity-sync.test.mjs scripts/__tests__/check-dco.test.mjs scripts/__tests__/package-args.test.mjs scripts/__tests__/notarize-mac-app.test.mjs scripts/__tests__/glossary-rules.test.mjs scripts/__tests__/design-inventory.test.mjs scripts/__tests__/hardcoded-color-audit.test.mjs",+ "test:runner": "node --test scripts/__tests__/test-workspaces.test.mjs scripts/__tests__/remote-bundle-inputs.test.mjs scripts/__tests__/test-related.test.mjs scripts/__tests__/desktop-worker-benchmark.test.mjs scripts/__tests__/dev-docs-contract.test.mjs scripts/__tests__/restart-desktop-remote.test.mjs scripts/__tests__/dev-migration-policy.test.mjs scripts/__tests__/ensure-deps.test.mjs scripts/__tests__/client-endpoint-build-env.test.mjs scripts/__tests__/log-upload-build-env.test.mjs scripts/__tests__/desktop-dev-region.test.mjs scripts/__tests__/endpoint-consistency.test.mjs scripts/__tests__/endpoint-local-file.test.mjs scripts/__tests__/ensure-agent-binaries.test.mjs scripts/__tests__/ensure-android-platform-tools.test.mjs scripts/__tests__/fetch-with-timeout.test.mjs scripts/__tests__/agent-binary-cdn-fallback.test.mjs scripts/__tests__/ensure-binary-fallback.test.mjs scripts/__tests__/verify-sha256.test.mjs scripts/__tests__/codex-package-update-layout.test.mjs scripts/__tests__/pi-update-layout.test.mjs scripts/__tests__/migration-freeze.test.mjs scripts/__tests__/third-party-notices.test.mjs scripts/__tests__/brand-identity-sync.test.mjs scripts/__tests__/check-dco.test.mjs scripts/__tests__/package-args.test.mjs scripts/__tests__/notarize-mac-app.test.mjs scripts/__tests__/glossary-rules.test.mjs scripts/__tests__/design-inventory.test.mjs scripts/__tests__/hardcoded-color-audit.test.mjs","test:workspaces": "node scripts/test-workspaces.mjs","test:unit": "pnpm test:runner && node scripts/test-workspaces.mjs --tier unit","test:unit:related": "node scripts/test-workspaces.mjs --tier unit --related",diff --git a/packages/anthropic-compat-proxy/build.mjs b/packages/anthropic-compat-proxy/build.mjsindex c3627726e8..4bb0523772 100644--- a/packages/anthropic-compat-proxy/build.mjs+++ b/packages/anthropic-compat-proxy/build.mjs@@ -21,6 +21,8 @@ const normalizeEolPlugin = {},};+const opencodexLicense = (await readFile(new URL('../model-compat/LICENSE.opencodex', import.meta.url), 'utf8')).replace(/\r\n/g, '\n');+await esbuild.build({entryPoints: ['src/bin/proxy.ts'],bundle: true,@@ -28,7 +30,8 @@ await esbuild.build({target: 'node20',format: 'esm',outfile: 'dist/proxy.mjs',- banner: { js: '#!/usr/bin/env node' },+ // SSH deployment copies this single file, so its third-party notice must travel with it.+ banner: { js: '#!/usr/bin/env node\n/*\n' + opencodexLicense.replace(/\*\//g, '* /') + '\n*/' },external: [],legalComments: 'none',minify: false,diff --git a/packages/anthropic-compat-proxy/package.json b/packages/anthropic-compat-proxy/package.jsonindex c3b8bd6081..c30581cbd3 100644--- a/packages/anthropic-compat-proxy/package.json+++ b/packages/anthropic-compat-proxy/package.json@@ -30,5 +30,8 @@"typescript": "^5.7.0","typescript-eslint": "^8.0.0","vitest": "^3.2.4"+ },+ "dependencies": {+ "@cindy/model-compat": "workspace:*"}}diff --git a/packages/anthropic-compat-proxy/src/headers.ts b/packages/anthropic-compat-proxy/src/headers.tsindex c86743c8fb..0fa891cc81 100644--- a/packages/anthropic-compat-proxy/src/headers.ts+++ b/packages/anthropic-compat-proxy/src/headers.ts@@ -1,50 +1,7 @@-/**- * 共享的请求 header 读取工具。- *- * transform.ts 与 server.ts 都要从 flatten 后的 headers 里按名取值(大小写不敏感),- * 收口到这里避免两份相同实现随时间漂移。- */--/**- * 取 threadId 的默认 header 候选名(按序取第一个非空)。收口到一处,避免- * server.ts / transform.ts / host 各写一份字面量随时间漂移。- *- * 顺序按"稳定性"排:- * - x-claude-code-session-id —— Claude Code 每个会话稳定(cc-code client.ts 注入),- * Layer-2 主动剥离要靠它跨 turn 命中同一会话的标记。- * - thread-id —— Codex app-server 每个 thread 稳定。- * - x-client-request-id —— **每请求唯一**,只作最后兜底;命中它时 Layer-2 标记- * 跨不过下一请求(但 Layer-1 反应式仍每轮兜底,功能不受影响,只是少省一次往返)。- */-export const STABLE_THREAD_ID_HEADERS = [- 'x-claude-code-session-id',- 'thread-id',-] as const;--export const DEFAULT_THREAD_ID_HEADERS = [- ...STABLE_THREAD_ID_HEADERS,- 'x-client-request-id',-] as const;--/** 取单个 header 值(大小写不敏感),取不到返回空串。 */-export function headerValue(headers: Readonly<Record<string, string>>, name: string): string {- const direct = headers[name];- if (typeof direct === 'string' && direct.trim()) return direct.trim();- const lower = name.toLowerCase();- for (const [key, value] of Object.entries(headers)) {- if (key.toLowerCase() === lower && value.trim()) return value.trim();- }- return '';-}--/** 按候选名顺序取第一个非空 header 值,都没有则返回空串。 */-export function selectedHeaderValue(- headers: Readonly<Record<string, string>>,- names: readonly string[],-): string {- for (const name of names) {- const value = headerValue(headers, name);- if (value) return value;- }- return '';-}+/** Compatibility implementation is owned by the shared package; preserve this import contract. */+export {+ STABLE_THREAD_ID_HEADERS,+ DEFAULT_THREAD_ID_HEADERS,+ headerValue,+ selectedHeaderValue+} from '@cindy/model-compat';diff --git a/packages/anthropic-compat-proxy/src/thread-strip-controller.ts b/packages/anthropic-compat-proxy/src/thread-strip-controller.tsindex a073eeb7fc..93e55c54a5 100644--- a/packages/anthropic-compat-proxy/src/thread-strip-controller.ts+++ b/packages/anthropic-compat-proxy/src/thread-strip-controller.ts@@ -1,58 +1,7 @@-/**- * Tracks threads that should proactively apply a body strip on every request,- * after a thread has recovered once from a corresponding upstream 400.- *- * The controller is condition-agnostic (just a thread→model marker with a- * model-change reset). Run ONE instance per independent strip condition — e.g.- * one for encrypted_content, a separate one for empty thinking blocks. Sharing a- * single instance across conditions would cross-contaminate: a recovery for one- * condition would set shouldStrip=true and make the OTHER condition's active-strip- * transform fire (e.g. stripping encrypted_content with no encrypted 400 — a real- * cost: losing the model's reasoning chain).- *- * State is intentionally in-memory and per-instance. A process restart returns- * every thread to the reactive retry path, and a model change clears the mark.- */-export interface ThreadStripController {- /** 标记某 thread 进入主动剥离(记下当时的 model)。 */- markActive(threadId: string, model: string): void;- /**- * 状态收敛(有副作用):若该 thread 已标记但 model 变了(切了模型/供应商),清除标记。- * 每个请求周期在 shouldStrip 之前调用一次。- */- reconcile(threadId: string, model: string): void;- /** 纯读:该 thread 当前是否处于主动剥离状态(不修改任何状态)。 */- shouldStrip(threadId: string): boolean;- clear(threadId: string): void;-}--export function createThreadStripController(): ThreadStripController {- const activeByThread = new Map<string, string>();-- return {- markActive(threadId, model) {- const tid = threadId.trim();- const mid = model.trim();- if (!tid || !mid) return;- activeByThread.set(tid, mid);- },-- reconcile(threadId, model) {- const tid = threadId.trim();- const mid = model.trim();- if (!tid || !mid) return;- const activeModel = activeByThread.get(tid);- if (activeModel && activeModel !== mid) {- activeByThread.delete(tid);- }- },-- shouldStrip(threadId) {- return activeByThread.has(threadId.trim());- },-- clear(threadId) {- activeByThread.delete(threadId.trim());- },- };-}+/** Compatibility implementation is owned by the shared package; preserve this import contract. */+export {+ createThreadStripController+} from '@cindy/model-compat';+export type {+ ThreadStripController+} from '@cindy/model-compat';diff --git a/packages/anthropic-compat-proxy/src/transform.ts b/packages/anthropic-compat-proxy/src/transform.tsindex b4d1096518..5d8f1f188d 100644--- a/packages/anthropic-compat-proxy/src/transform.ts+++ b/packages/anthropic-compat-proxy/src/transform.ts@@ -1,1685 +1,28 @@-/**- * 内置默认 transform —— 解决 "Claude Code SDK 在请求体里塞了 Anthropic-only 字段,- * 但请求被路由到 OpenAI/Azure/litellm 后端,后端不认这些字段直接 400" 的问题。- *- * 设计: 每个有问题的 model 一个独立 handler 函数,自己决定怎么改写 body- * (删字段 / 翻译字段 / 改值 / 条件改写 ...都可以)。字典里没有的 model 默认完全- * 字节透传,proxy 对它们零干预。- *- * 加 handler 的判定标准: 该 model 在 XD.inc gateway 的实际请求被观察到 400- * (典型: litellm.BadRequestError "Unknown parameter: 'XXX'") —— 截 maker.log- * 留证据。不要凭"它跟 gpt-5.4 应该一样" 之类的推测扩。- */--import { Buffer } from 'node:buffer';--import { DEFAULT_THREAD_ID_HEADERS, selectedHeaderValue } from './headers.js';-import type { ThreadStripController } from './thread-strip-controller.js';-import type { RecoveryRule, RequestTransform, RequestTransformCtx } from './types.js';--export { createVllmResponsesCompatibilityRule } from './vllm-responses-compatibility.js';--/**- * 单个 model 的请求改写 handler。- *- * @param body 已经 parse 好的 plain object,调用前已确认 typeof body === 'object'- * 且 body.model 命中字典 key。handler 内部不需要再做这些校验。- * @returns 新的 body 对象 → 代理用它替换原 body 转发上游;- * null → 显式表示"虽然命中我但不需要改",代理走透传。- */-type ModelStripHandler = (body: Record<string, unknown>) => Record<string, unknown> | null;--function isPlainObject(v: unknown): v is Record<string, unknown> {- return typeof v === 'object' && v !== null && !Array.isArray(v);-}--/**- * 工具函数: 递归从对象 / 数组任意嵌套层级删除指定 key 集合。- * handler 内部按需调用。- *- * 性能: 只对 plain object 和 array 递归,字符串/数字/null 直接返回。- * keys 用 Set —— 每个对象的每个 key 都要查一次,O(1) 比 includes 更稳。- */-function deepDeleteKeys(node: unknown, keys: ReadonlySet<string>): void {- if (Array.isArray(node)) {- for (const item of node) deepDeleteKeys(item, keys);- return;- }- if (isPlainObject(node)) {- for (const k of keys) {- if (k in node) delete node[k];- }- for (const key of Object.keys(node)) {- deepDeleteKeys(node[key], keys);- }- }-}--/**- * 删除 Anthropic `tool_use` content block 上由 provider adapter 附加的- * `provider_specific_fields`。只处理 tool_use 自身的字段,不触碰工具 input- * 内同名的业务字段,避免把用户传给工具的参数误删。- */-function deepDeleteToolUseProviderSpecificFields(node: unknown): number {- let removed = 0;- if (Array.isArray(node)) {- for (const item of node) removed += deepDeleteToolUseProviderSpecificFields(item);- return removed;- }- if (!isPlainObject(node)) return 0;-- if (node.type === 'tool_use') {- if ('provider_specific_fields' in node) {- delete node.provider_specific_fields;- removed += 1;- }- // tool input is opaque user data. It may itself contain objects shaped like- // Anthropic content blocks, so never recurse below an actual tool_use block.- return removed;- }- for (const key of Object.keys(node)) {- removed += deepDeleteToolUseProviderSpecificFields(node[key]);- }- return removed;-}--/**- * 递归删除请求历史中 `tool_use.provider_specific_fields`,供主动 transform- * 和 400 recovery 共用同一份字段清理逻辑。- */-export function stripToolUseProviderSpecificFieldsFromBody(rawBody: Buffer): Buffer | null {- let parsed: unknown;- try {- parsed = JSON.parse(rawBody.toString('utf8'));- } catch {- return null;- }- if (deepDeleteToolUseProviderSpecificFields(parsed) === 0) return null;- try {- return Buffer.from(JSON.stringify(parsed), 'utf8');- } catch {- return null;- }-}--/**- * 请求 transform 版本:body 已经由 proxy 解析为 plain object。- * 无命中时返回 null,保持 clean request 的字节级透传语义。- */-export const stripToolUseProviderSpecificFields: RequestTransform = (body) => {- if (!isPlainObject(body)) return null;- return deepDeleteToolUseProviderSpecificFields(body) > 0 ? body : null;-};--/**- * Responses `input[]` 里的上下文压缩块 (OpenAI `/v1/responses/compact` 与 xAI 同名接口- * 都回这个形态)。它的 `encrypted_content` 装的是**压缩 blob 本体** —— 压缩点之前的- * 全部历史,不是可有可无的推理链。- */-function isCompactionItem(node: Record<string, unknown>): boolean {- return node.type === 'compaction' || node.type === 'context_compaction';-}--/**- * Drop Codex agent-to-agent ciphertext at its protocol-defined location.- *- * A spawned Codex agent can call `send_message` from an otherwise ordinary- * session; the resulting `agent_message` carries readable text and an optional- * `{ type: 'encrypted_content', encrypted_content: '...' }` part. Deleting only- * the field leaves a schema-invalid encrypted-content shell, so remove the- * whole part before the generic recursive key strip. If the message contained- * only ciphertext, the message itself has no replayable content and is dropped.- *- * This intentionally inspects only top-level Responses `input[]`; nested- * business objects with a similarly shaped `content` array are not protocol- * history and must not be interpreted by shape.- */-function dropEncryptedAgentMessageContentParts(body: unknown): number {- if (!isPlainObject(body) || !Array.isArray(body.input)) return 0;-- let removed = 0;- const input: unknown[] = [];- for (const item of body.input) {- if (!isPlainObject(item) || item.type !== 'agent_message' || !Array.isArray(item.content)) {- input.push(item);- continue;- }-- const content = item.content.filter((part) => {- if (!isPlainObject(part) || part.type !== 'encrypted_content') return true;- removed += 1;- return false;- });- if (content.length === item.content.length) {- input.push(item);- } else if (content.length > 0) {- input.push({ ...item, content });- }- }-- if (removed > 0) body.input = input;- return removed;-}--/**- * 递归删除 body 里所有 `encrypted_content` 键, 返回删掉的个数。- * 用于 invalid_encrypted_content 报错后的透明重试 (见 stripEncryptedContentFromBody)。- *- * **压缩块整块跳过**: 剥掉压缩 blob 换不回一个可用请求 —— 上游收到没有 blob 的- * 压缩空壳会直接判 "Could not decode the compaction blob. Ensure it is unmodified- * from the compact response." (xAI 实报, 2026-07 Grok 会话卡死)。压缩块该怎么处置- * 由上层按目标上游决定 (codex-proxy 的跨来源压缩兼容 transform 会把读不懂的加密块- * 换成明文占位), 而那条兼容路径正是以"encrypted_content 非空"为触发条件 —— 在这里- * 先剥就等于把它一并绕过。- */-function deepDeleteEncryptedContent(node: unknown): number {- let removed = 0;- if (Array.isArray(node)) {- for (const item of node) removed += deepDeleteEncryptedContent(item);- return removed;- }- if (isPlainObject(node)) {- if (isCompactionItem(node)) return 0;- if ('encrypted_content' in node) {- delete node.encrypted_content;- removed += 1;- }- for (const key of Object.keys(node)) {- removed += deepDeleteEncryptedContent(node[key]);- }- }- return removed;-}--/** Responses `input[]` 里剥掉 encrypted_content 后已无密文的 reasoning 空壳。 */-function isReasoningItemWithoutEncryptedContent(item: unknown): boolean {- if (!isPlainObject(item) || item.type !== 'reasoning') return false;- return typeof item.encrypted_content !== 'string' || item.encrypted_content.length === 0;-}--/**- * 缺 blob 的 `compaction` 空壳 —— 上游无法解码, 留着必 400, 只能丢。- *- * **只认 `compaction`, 不认 `context_compaction`**: codex wire 上 `Compaction.encrypted_content`- * 必填、`ContextCompaction.encrypted_content` 可选 —— 后者不带密文是合法的可读压缩变体- * (codex-proxy 的跨来源压缩兼容 transform 同样只处理带密文的项, 明文变体原样透传)。- * 把它当空壳删掉会静默丢掉真实的压缩上下文。- */-function isCompactionShellWithoutBlob(item: unknown): boolean {- if (!isPlainObject(item) || item.type !== 'compaction') return false;- return typeof item.encrypted_content !== 'string' || item.encrypted_content.length === 0;-}--/**- * 丢掉 Responses 请求体**协议层** `input[]` 里解不开也修不好的空壳 item:- * - 缺 blob 的 `compaction` (**恒丢**): 本模块不再制造这种空壳- * (见 deepDeleteEncryptedContent), 但请求体可能已经带着它进来, 兜底丢掉,- * 别让它打到上游换一个 400;- * - 无 encrypted_content 的 reasoning (**仅 dropReasoningShells**): 只删- * encrypted_content 键时,xAI 会把残留 reasoning item 判成 ModelInput 反序列化失败- * (422)。这一条只在本轮确实剥掉过密文时才做 —— 没剥过的请求里,"reasoning 只带- * summary" 是合法形态, 不该顺手删掉。- *- * **只看顶层 `input`, 不递归**: Responses 请求体的协议历史只有顶层这一个 `input[]`;- * 嵌套结构里同名的 `input` 数组(工具参数、业务对象等)不是协议历史, 按 `type` 形状- * 猜着删会静默改坏别人的数据。删密文键可以全树递归(定向删键, 只会少发不会发错),- * 判定"整项该不该留"必须锚在协议层。- */-function dropEncryptedShellInputItems(body: unknown, dropReasoningShells: boolean): number {- if (!isPlainObject(body) || !Array.isArray(body.input)) return 0;-- let removed = 0;- const kept: unknown[] = [];- for (const item of body.input) {- if (- isCompactionShellWithoutBlob(item) ||- (dropReasoningShells && isReasoningItemWithoutEncryptedContent(item))- ) {- removed += 1;- continue;- }- kept.push(item);- }- if (removed > 0) body.input = kept;- return removed;-}--/**- * 把请求体里所有 `encrypted_content` 键递归删掉 (压缩块除外), 并丢掉解不开也修不好的- * 空壳 input item, 返回新的 Buffer。- *- * 背景: gpt-5.5 等模型经 litellm/Azure 走 OpenAI Responses API (/v1/responses) 时,- * 请求体的 reasoning item 带 `encrypted_content` (gAAA... 加密推理)。多部署负载均衡把- * 后续请求路由到另一部署时, 它解不开上一部署的加密推理 → 400 invalid_encrypted_content。- * xAI 同类失败文案是 "Could not decrypt the provided encrypted_content" (400/422)。- * 删掉 encrypted_content 再重发即可恢复 (代价: 模型丢失上一轮的加密推理链, 可见对话保留)。- * 若只删键、保留 type=reasoning 空壳,xAI 会再报 ModelInput 422 —— 所以空壳一并丢掉。- *- * **上下文压缩块除外**: 它的 encrypted_content 是压缩 blob 本体, 剥掉只会把请求变成- * 上游无法解码的空壳 (详见 deepDeleteEncryptedContent)。- *- * 仅在 server.ts 收到该 400/422 后的"透明重试"路径调用, 正常请求不经过此函数。- *- * @returns 删掉了至少一个键或空壳 → 新 Buffer; body 非 JSON / 无可剥内容 → null (调用方据此决定不重试)- */-export function stripEncryptedContentFromBody(rawBody: Buffer): Buffer | null {- let parsed: unknown;- try {- parsed = JSON.parse(rawBody.toString('utf8'));- } catch {- return null;- }- // agent_message 的密文是 content part;必须在通用递归删键之前整块移除,否则会留下- // `{ type: 'encrypted_content' }` 并被 OpenAI 拒绝为 missing_required_parameter。- const removedAgentMessageParts = dropEncryptedAgentMessageContentParts(parsed);- const removedKeys = deepDeleteEncryptedContent(parsed);- // 空壳清理独立计数: 请求体里可能只带着一个缺 blob 的 compaction 空壳 (没有任何- // encrypted_content 键可删), 那一样是必须处理的坏 payload, 不能因 removedKeys=0 放行。- // 这一步只扫顶层 input[] (单次线性扫描), 不是第二遍深度遍历。- const removedShells = dropEncryptedShellInputItems(parsed, removedKeys > 0);- if (removedAgentMessageParts === 0 && removedKeys === 0 && removedShells === 0) return null;- try {- return Buffer.from(JSON.stringify(parsed), 'utf8');- } catch {- return null;- }-}--function isImageGenerationType(type: unknown): boolean {- if (typeof type !== 'string') return false;- return type.startsWith('image_generation') || type.startsWith('imageGeneration');-}--function isImageGenerationItemWithoutId(item: unknown): boolean {- if (!isPlainObject(item)) return false;- if (!isImageGenerationType(item.type)) return false;- const id = item.id;- return typeof id !== 'string' || id.trim().length === 0;-}--function deepDeleteImageGenerationItemsWithoutId(node: unknown, inResponsesInputArray = false): number {- let removed = 0;- if (Array.isArray(node)) {- let writeIndex = 0;- for (const item of node) {- if (inResponsesInputArray && isImageGenerationItemWithoutId(item)) {- removed += 1;- continue;- }- removed += deepDeleteImageGenerationItemsWithoutId(item);- node[writeIndex] = item;- writeIndex += 1;- }- node.length = writeIndex;- return removed;- }- if (isPlainObject(node)) {- for (const key of Object.keys(node)) {- removed += deepDeleteImageGenerationItemsWithoutId(node[key], key === 'input');- }- }- return removed;-}--/**- * 删除 Responses 请求体里缺 `id` 的 image generation 历史 item。- *- * 背景: Codex rollout 会同时记录 event_msg:image_generation_end 和- * response_item:image_generation_call。2026-07 实测 XD gateway → litellm/Azure- * 会把缺 `id` 的 image_generation_end 回灌进下一轮 Responses input, Azure 直接 400:- * "Image generation items without `id` are not supported for this request."- *- * 只删 Responses input 历史数组中 type 以 image_generation / imageGeneration 开头- * 且缺 id 的对象;tools 里的 image_generation 工具声明、用户图片输入 input_image、- * 已有 id 的 image_generation_call 都保留。- */-export function stripImageGenerationItemsWithoutIdFromBody(rawBody: Buffer): Buffer | null {- let parsed: unknown;- try {- parsed = JSON.parse(rawBody.toString('utf8'));- } catch {- return null;- }- const removed = deepDeleteImageGenerationItemsWithoutId(parsed);- if (removed === 0) return null;- try {- return Buffer.from(JSON.stringify(parsed), 'utf8');- } catch {- return null;- }-}--/** thinking 块的 `thinking` 字段是否为空(空串 / 缺失 / 非字符串都算空)。 */-function isEmptyThinkingBlock(block: unknown): boolean {- if (!isPlainObject(block)) return false;- if (block.type !== 'thinking') return false;- const t = block.thinking;- return typeof t !== 'string' || t.trim().length === 0;-}--/**- * 删除请求体里"空内容" thinking 块,返回新 Buffer;没改动 / 非 JSON / 无 messages → null。- *- * 背景: 跨厂商切模型时,Claude Code 会话历史累积了非 Anthropic 厂商产出的 thinking 块。- * gpt-5.5 等"推理加密"模型产出空壳 {type:"thinking", thinking:"", signature:""}(真实推理在- * encrypted_content 里,litellm 转 Anthropic 格式只留空壳)。切回真 Anthropic 模型时 API 400:- * "messages.N.content.0.thinking: each thinking block must contain thinking"。- *- * 判别式只看 thinking 内容是否为空 —— deepseek 那种"有内容、签名空"的块被 gateway 容忍,- * 不删;真 Anthropic 块有内容 + 有签名,更不会命中。删空块零代价(块里本就没内容)。- *- * 边界:- * - 某条 message 的 content 删空后 → 整条 message 丢弃(Anthropic 也拒空 content)。- * - 被删块所在轮若含 tool_use(开 thinking 时可能换来另一个 400)→ 保留不动 + 调用方按需记日志;- * 该状态本就已坏,no-loop 保证下不会更糟,强行丢残轮风险更高。- *- * @returns 删掉至少一个空块 → 新 Buffer; body 非 JSON / messages 非数组 / 无空块 → null- * (返回 null 是 cache 安全契约:让代理字节透传,正常会话零影响)。- */-export function stripEmptyThinkingFromBody(rawBody: Buffer): Buffer | null {- let parsed: unknown;- try {- parsed = JSON.parse(rawBody.toString('utf8'));- } catch {- return null;- }- if (!isPlainObject(parsed)) return null;- const messages = parsed.messages;- if (!Array.isArray(messages)) return null;-- let removed = 0;- const keptMessages: unknown[] = [];- for (const msg of messages) {- if (!isPlainObject(msg) || !Array.isArray(msg.content)) {- keptMessages.push(msg);- continue;- }- const keptContent = msg.content.filter((block) => {- if (isEmptyThinkingBlock(block)) {- removed += 1;- return false;- }- return true;- });- if (keptContent.length === msg.content.length) {- keptMessages.push(msg); // 该 message 没动- } else if (keptContent.length === 0) {- // content 被清空 → 整条 message 丢弃(边界 a);removed 已累加,下方仍判定有改动。- } else {- keptMessages.push({ ...msg, content: keptContent });- }- }-- if (removed === 0) return null; // ← cache 安全契约:无改动 → null → 字节透传- parsed.messages = keptMessages;- try {- return Buffer.from(JSON.stringify(parsed), 'utf8');- } catch {- return null;- }-}--/** text 块的 `text` 字段是否为空(空串 / 纯空白 / 缺失 / 非字符串都算空)。 */-function isEmptyTextBlock(block: unknown): boolean {- if (!isPlainObject(block)) return false;- if (block.type !== 'text') return false;- const t = block.text;- return typeof t !== 'string' || t.trim().length === 0;-}--/**- * 删除请求体里空内容 text 块,返回新 Buffer;没改动 / 非 JSON / 无 messages → null。- *- * 背景: anthropic-responses-bridge 修复前会把纯工具轮的 message item 落成- * `{type:"text", text:""}` 空块写进 Claude Code 会话历史(eager 开块被 function_call- * 抢占强制关掉)。会话切到真 Anthropic 模型时历史原样回放,API 400:- * "messages.N.content.M: text content blocks must be non-empty"。bridge 已改为惰性- * 开块不再产出新空块;本函数负责修复期之前累积的存量脏历史 —— 命中 400 后剥掉- * 空块透明重试(结构与 stripEmptyThinkingFromBody 一致)。- *- * 只处理 messages[].content 顶层块,不深入 tool_result 嵌套 content(实测命中的- * 只有顶层;嵌套形态被打脸再扩)。- *- * 边界: 某条 message 的 content 删空后 → 整条 message 丢弃(Anthropic 也拒空 content)。- *- * @returns 删掉至少一个空块 → 新 Buffer; body 非 JSON / messages 非数组 / 无空块 → null- * (返回 null 是 cache 安全契约:让代理字节透传,正常会话零影响)。- */-export function stripEmptyTextFromBody(rawBody: Buffer): Buffer | null {- let parsed: unknown;- try {- parsed = JSON.parse(rawBody.toString('utf8'));- } catch {- return null;- }- if (!isPlainObject(parsed)) return null;- const messages = parsed.messages;- if (!Array.isArray(messages)) return null;-- let removed = 0;- const keptMessages: unknown[] = [];- for (const msg of messages) {- if (!isPlainObject(msg) || !Array.isArray(msg.content)) {- keptMessages.push(msg);- continue;- }- const keptContent = msg.content.filter((block) => {- if (isEmptyTextBlock(block)) {- removed += 1;- return false;- }- return true;- });- if (keptContent.length === msg.content.length) {- keptMessages.push(msg); // 该 message 没动- } else if (keptContent.length === 0) {- // content 被清空 → 整条 message 丢弃;removed 已累加,下方仍判定有改动。- } else {- keptMessages.push({ ...msg, content: keptContent });- }- }-- if (removed === 0) return null; // ← cache 安全契约:无改动 → null → 字节透传- parsed.messages = keptMessages;- try {- return Buffer.from(JSON.stringify(parsed), 'utf8');- } catch {- return null;- }-}--/**- * 丢弃请求历史里的空 assistant 消息(含剥掉空 thinking 块后变空壳的),返回新 Buffer;- * 没改动 / 非 JSON / 无 messages → null。- *- * 背景: moonshot/kimi-k3 经 LiteLLM 原生转发(/anthropic/v1/messages passthrough)时,- * 其 Anthropic 兼容流首包是空 thinking 占位 {type:"thinking",thinking:"",signature:""}- * (kimi 官方确认 by design);流被 429/中断切断后,客户端把未完成的占位 block 当成完整- * assistant 持久化,回放时 moonshot 400:- * "Invalid request: the message at position 693 with role 'assistant' must not be empty"- * (2026-07-28 线上实测,两个独立会话 position 693 / 275,重试 35+ 次全部失败,- * 会话级永久卡死——每轮请求历史都带污染消息)。- *- * 处理(与 kimi code 官方客户端的兜底策略同构——发送出去的请求不允许带空 assistant):- * 1. assistant 消息 content 为 string 且为空白 → 整条丢弃;- * 2. assistant 消息 content 为数组:先剥空 thinking 块与空 text 块(判别式与- * stripEmptyThinkingFromBody / stripEmptyTextFromBody 一致,有内容/签名空的块- * 保留),剥完为空(含原生 content:[])→ 整条丢弃;剥完仍有 text/tool_use →- * 保留净化后的消息。空 text 块一并剥的原因:moonshot 的 must-not-be-empty 校验- * 对 bridge 清理路径产出的 text-only 空块消息同样命中(PR #821 review 实测反馈),- * 只剥 thinking 会让该形态 strip 不出东西、重试被跳过,会话继续卡死。- * user 消息一律不动(线上命中的只有 assistant;user 空消息无实测证据,不扩散)。- *- * 安全性: 空消息不含任何对话信息,丢弃不改变语义;含 tool_use 的轮次剥完非空,- * tool_use/tool_result 配对不会被打破。- *- * @returns 丢弃/净化至少一条 → 新 Buffer; 无改动 → null (cache 安全契约:字节透传)。- */-export function stripEmptyAssistantMessagesFromBody(rawBody: Buffer): Buffer | null {- let parsed: unknown;- try {- parsed = JSON.parse(rawBody.toString('utf8'));- } catch {- return null;- }- if (!isPlainObject(parsed)) return null;- const messages = parsed.messages;- if (!Array.isArray(messages)) return null;-- let changed = false;- const keptMessages: unknown[] = [];- for (const msg of messages) {- if (!isPlainObject(msg) || msg.role !== 'assistant') {- keptMessages.push(msg);- continue;- }- const content = msg.content;- if (typeof content === 'string') {- if (content.trim().length === 0) {- changed = true; // 空 string content → 整条丢弃- continue;- }- keptMessages.push(msg);- continue;- }- if (!Array.isArray(content)) {- keptMessages.push(msg); // 异常形态不猜,原样保留- continue;- }- const keptContent = content.filter((block) => !isEmptyThinkingBlock(block) && !isEmptyTextBlock(block));- if (keptContent.length === 0) {- changed = true; // 空壳(content:[] 或剥空 thinking/空 text 后为空)→ 整条丢弃- continue;- }- if (keptContent.length !== content.length) {- changed = true;- keptMessages.push({ ...msg, content: keptContent });- continue;- }- keptMessages.push(msg);- }-- if (!changed) return null; // ← cache 安全契约:无改动 → null → 字节透传- parsed.messages = keptMessages;- try {- return Buffer.from(JSON.stringify(parsed), 'utf8');- } catch {- return null;- }-}--// ───────────────────────────────────────────────────────────────────────────-// Tool exchange 结构修复 —— 与 kimi code 官方客户端的投影修复同构-// (kosong normalizeToolCallIdsForProvider + agent-core projector),移植到-// Anthropic Messages wire 格式:-// - tool_use 块在 assistant 消息 content 内;tool_result 块在 user 消息-// content 内(kimi 内部格式里 tool result 是独立的 role:'tool' 消息)。-// - 两个 transform 都是**检测即修**:扫描发现协议级异常才改写,无异常返回-// null(cache 安全契约:字节透传,正常会话零影响)。不需要 ThreadStripController-// —— 重复 id / 配对断裂在请求体里可直接检测,不像 encrypted_content 要靠-// 撞 400 才能判定该剥。-// ───────────────────────────────────────────────────────────────────────────--function isToolUseBlock(block: unknown): block is Record<string, unknown> & { id: string } {- return (- isPlainObject(block) &&- block.type === 'tool_use' &&- typeof block.id === 'string' &&- block.id.length > 0- );-}--function isToolResultBlock(- block: unknown,-): block is Record<string, unknown> & { tool_use_id: string } {- return (- isPlainObject(block) &&- block.type === 'tool_result' &&- typeof block.tool_use_id === 'string' &&- block.tool_use_id.length > 0- );-}--/**- * 重复 tool_use id 唯一化(检测即修),返回新 messages;无重复 → null。- *- * 背景: moonshot/kimi 系的 tool_call id 是服务端按序号铸造的(`Edit_306` /- * `Bash_256` 这类 `${name}_${index}` 形态,经 LiteLLM 字符清洗后冒号变下划线)。- * 长会话里序号生成会卡住,同一个 id 被跨 turn 反复复用(2026-07 两个独立会话- * 实测各复用 20+ 次)——模型看回放历史时工具交换错乱,表现为"工具调用凭空- * 消失"、安静瘫痪。kimi code 官方对原始重复 id 的处理是 400 后 strict resend- * 丢弃(agent-core projector dedupeDuplicateToolCalls),但 moonshot 容忍重复- * id 不报 400,strict 路径永远触发不了 → 这里改为发送前检测即修。- *- * 与 kimi strict 的**丢弃**不同,这里选择**重写**(kosong normalize 思路):- * 首现保留,第 N 次出现重写为 `${id}_${N}`(与现存 id 撞车时顺延后缀),- * 顺序配对的第 N 个 tool_result 同步改写。每个重复对背后是不同的逻辑调用,- * 丢弃会抹历史;重写保持配对完整,且 `_N` 后缀在 Anthropic id 合法字符集- * (`[a-zA-Z0-9_-]`)内,对任何上游都是协议修复而非篡改。- *- * 配对规则: 按出现顺序,第 N 个 result 配第 N 个 call(正常历史里 result 紧跟- * 其 call,顺序配对即真实配对)。result 比 call 多的尾部块保持原样(指向首现- * call;超编残留的清理由 repairToolExchangeAdjacency 负责)。- *- * 边界(刻意不做): id 字符集 sanitize(kimi kosong 会把 `Edit:306` 的冒号洗成- * 下划线)不在本 transform 范围 —— 本链路上游(LiteLLM)已做过清洗,非法字符- * id 无实测证据;实测命中再扩。`_N` 后缀只含合法字符,不会把合法 id 改非法。- *- * rename key 用 ` ` 分隔 id 与出现序号:Anthropic 合法 id 字符集不含空格,- * 不会与真实 id 撞 key;病态含空格 id 的重写结果仍由 usedIds 保证唯一。- */-function dedupeToolUseIdsInMessages(messages: unknown[]): unknown[] | null {- // pass 1: 统计每个 call id 出现次数。usedIds(后缀撞车判定)只在确有重复、- // 进入改名阶段时才从 counts.keys() 构建 —— clean 请求(绝大多数)零 Set 分配。- const counts = new Map<string, number>();- for (const msg of messages) {- if (!isPlainObject(msg) || msg.role !== 'assistant' || !Array.isArray(msg.content)) continue;- for (const block of msg.content) {- if (!isToolUseBlock(block)) continue;- counts.set(block.id, (counts.get(block.id) ?? 0) + 1);- }- }- let hasDuplicate = false;- for (const n of counts.values()) {- if (n > 1) {- hasDuplicate = true;- break;- }- }- if (!hasDuplicate) return null; // cache 安全契约:无重复 → 透传-- // pass 2a: 给每个 call 的第 N(N≥2) 次出现分配全局唯一新 id。- const usedIds = new Set(counts.keys());- const renameByOccurrence = new Map<string, string>();- const callSeen = new Map<string, number>();- for (const msg of messages) {- if (!isPlainObject(msg) || msg.role !== 'assistant' || !Array.isArray(msg.content)) continue;- for (const block of msg.content) {- if (!isToolUseBlock(block)) continue;- const n = (callSeen.get(block.id) ?? 0) + 1;- callSeen.set(block.id, n);- if (n === 1) continue;- let suffix = n;- let candidate = `${block.id}_${suffix}`;- while (usedIds.has(candidate)) {- suffix += 1;- candidate = `${block.id}_${suffix}`;- }- usedIds.add(candidate);- renameByOccurrence.set(`${block.id} ${n}`, candidate);- }- }-- // pass 2b: 重写 call 与顺序配对的 result(第 N 个 result 查第 N 次 call 的改名;- // 查不到 = 该 result 无对应第 N 个 call,保持原样)。- const callWriteSeen = new Map<string, number>();- const resultSeen = new Map<string, number>();- const nextMessages = messages.map((msg) => {- if (!isPlainObject(msg) || !Array.isArray(msg.content)) return msg;- let msgChanged = false;- const nextContent = msg.content.map((block) => {- if (msg.role === 'assistant' && isToolUseBlock(block)) {- const n = (callWriteSeen.get(block.id) ?? 0) + 1;- callWriteSeen.set(block.id, n);- const renamed = renameByOccurrence.get(`${block.id} ${n}`);- if (renamed === undefined) return block;- msgChanged = true;- return { ...block, id: renamed };- }- if (msg.role === 'user' && isToolResultBlock(block)) {- const n = (resultSeen.get(block.tool_use_id) ?? 0) + 1;- resultSeen.set(block.tool_use_id, n);- const renamed = renameByOccurrence.get(`${block.tool_use_id} ${n}`);- if (renamed === undefined) return block;- msgChanged = true;- return { ...block, tool_use_id: renamed };- }- return block;- });- return msgChanged ? { ...msg, content: nextContent } : msg;- });- return nextMessages;-}--/**- * Buffer 版: 重复 tool_use id 唯一化。供 400 recovery(``tool_use` ids must be- * unique`)与主动 transform 共用同一份修复逻辑。- */-export function dedupeDuplicateToolUseIdsFromBody(rawBody: Buffer): Buffer | null {- let parsed: unknown;- try {- parsed = JSON.parse(rawBody.toString('utf8'));- } catch {- return null;- }- if (!isPlainObject(parsed)) return null;- const messages = parsed.messages;- if (!Array.isArray(messages)) return null;- const nextMessages = dedupeToolUseIdsInMessages(messages);- if (nextMessages === null) return null;- parsed.messages = nextMessages;- try {- return Buffer.from(JSON.stringify(parsed), 'utf8');- } catch {- return null;- }-}--/**- * 主动 transform 版: body 已由 proxy 解析为 plain object。- * 无重复返回 null,保持 clean request 的字节级透传语义。- */-export const dedupeDuplicateToolUseIds: RequestTransform = (body) => {- if (!isPlainObject(body)) return null;- const messages = body.messages;- if (!Array.isArray(messages)) return null;- const nextMessages = dedupeToolUseIdsInMessages(messages);- if (nextMessages === null) return null;- return { ...body, messages: nextMessages };-};--/**- * 未配对 call 的合成占位 result 文本(与 kimi code projector 的- * SYNTHETIC_TOOL_RESULT_TEXT 同文案同语义:明确告知结果缺失、禁止假设成功;- * 不设 is_error —— "上下文里结果不可用"≠"工具执行失败",避免模型误重试)。- */-const SYNTHETIC_TOOL_RESULT_TEXT =- 'Tool result is not available in the current context. Do not assume the tool completed successfully.';--/**- * tool_use/tool_result 配对断裂修复(检测即修),返回新 messages;无断裂 → null。- *- * 与 kimi code projector 的 repairToolExchangeAdjacency + dropOrphanResults- * 同构(consumed-scan),移植到 Anthropic 格式:- * 1. 位置配对优先: 每个 call 先消费紧邻下一条消息里同 id 的未消费 result- * 块(CC 投影的正常形态,位置证据最强的配对);全部 call(含 trailing)- * 做完位置配对后才进入接力 —— 否则较早的同 id 缺口 call 会抢走较晚- * call 紧邻位置的真实 result,造成张冠李戴。- * 2. 接力补缺 + 错位重排: 位置配对失败的 call 从结果池取**归属区间**(本- * assistant 消息到下一条含同 id call 的 assistant 消息之间 —— agentic- * loop 串行,出现在下一个同 id exchange 之后的 result 只属于后面的- * exchange,较早缺口不得越界抢走;同消息 parallel calls 的归属不可判定- * 时按稳定 tie-breaker 沿 call 块顺序配序,该约定受典型 client- * serializer 支持但非 wire 可证明)内的第一个未消费块;不在合法位置- * (跨消息,或同消息内落在 text 之后)的前移至紧邻消息的前导- * tool_result 区间,原位置移除。Anthropic 要求 result 紧跟 call 所在- * assistant 且居于 text 前,留在错误位置仍是 400。- * 3. 缺失合成: 非 trailing 的 call 无候选 → 紧邻位置合成占位(kimi 同文案- * 同语义;不设 is_error —— "结果不可用"≠"执行失败")。插入规则与重排- * 相同;string content 转等价数组,空白 string 不附加 text 块。- * 4. 丢弃: 孤儿 result(全历史无匹配 call)、池中剩余(前置 result —— 引用- * 未来 call 本身非法;同 id 超编残留 —— 一个 call 恰应有一个应答)全部- * 移除;user 消息 content 因此清空 → 整条丢弃。- * 5. trailing 豁免: 最后一个「对话推进点」处的 assistant(末尾交换)只消费- * 不修复 —— 缺失 result 可能真在飞,不合成、不重排;其后的纯 result- * 消息视为交换一部分,不会误判为残留丢弃。- */-/**- * 最后一个「对话推进点」下标: assistant 消息,或含非 tool_result 内容的 user- * 消息(纯 tool_result 的 user 消息可能是 trailing 交换的一部分,不算推进点);- * 异常形态(非 plain object / string content)保守按推进点计。无 → -1。- */-function findLastConversationIndex(messages: unknown[]): number {- for (let i = messages.length - 1; i >= 0; i--) {- const msg = messages[i];- if (!isPlainObject(msg)) return i;- if (msg.role === 'assistant' || !Array.isArray(msg.content)) return i;- if (msg.role === 'user' && msg.content.some((block) => !isToolResultBlock(block))) return i;- }- return -1;-}--/**- * content 前导 tool_result 区间的长度(开头连续 tool_result 块数)。- * Anthropic 惯例(CC 原生形态): 一条 user 消息里所有 tool_result 块在最前,- * text 等其它块在后;result 落在 text 之后 = 块级错位,需重排进前导区间。- */-function leadingToolResultCount(content: unknown[]): number {- let k = 0;- while (k < content.length && isToolResultBlock(content[k])) k += 1;- return k;-}--function repairToolExchangeAdjacencyInMessages(messages: unknown[]): unknown[] | null {- // pass A: 全历史 call id 集合 + result 块位置池(per id 按出现升序)。- // 孤儿 result(无匹配 call)不入池,直接进丢弃清单。- const callIds = new Set<string>();- for (const msg of messages) {- if (!isPlainObject(msg) || msg.role !== 'assistant' || !Array.isArray(msg.content)) continue;- for (const block of msg.content) {- if (isToolUseBlock(block)) callIds.add(block.id);- }- }- const resultPool = new Map<string, Array<{ msgIdx: number; blockIdx: number }>>();- const drops: Array<{ msgIdx: number; blockIdx: number }> = [];- for (let i = 0; i < messages.length; i++) {- const msg = messages[i];- if (!isPlainObject(msg) || msg.role !== 'user' || !Array.isArray(msg.content)) continue;- for (let b = 0; b < msg.content.length; b++) {- const block = msg.content[b];- if (!isToolResultBlock(block)) continue;- if (!callIds.has(block.tool_use_id)) {- drops.push({ msgIdx: i, blockIdx: b });- continue;- }- const list = resultPool.get(block.tool_use_id) ?? [];- list.push({ msgIdx: i, blockIdx: b });- resultPool.set(block.tool_use_id, list);- }- }-- // pass B1: 位置配对 —— 每个 call 优先消费紧邻下一条消息里同 id 的未消费- // result 块(CC 投影的正常形态,位置证据最强的配对)。**全部 call(含- // trailing)先做完位置配对再做接力**:否则较早的同 id 缺口 call 会在接力时- // 抢走较晚 call 紧邻位置的真实 result(张冠李戴,Greptile P1 实测反例:- // call#1 缺 result、call#2 有真实 result → call#1 越权消费、call#2 反得- // 合成占位)。trailing call 参与位置配对(消费合法尾部 result)但不做修复。- const lastConversationIndex = findLastConversationIndex(messages);- const consumed = new Set<string>(); // `${msgIdx}:${blockIdx}`- // assistant 下标 → (call 块下标 → 要插入的 result 块),按 call 顺序组装。- const insertPlans = new Map<number, Map<number, unknown>>();- const recordInsert = (assistantIdx: number, callBlockIdx: number, block: unknown) => {- const plan = insertPlans.get(assistantIdx) ?? new Map<number, unknown>();- plan.set(callBlockIdx, block);- insertPlans.set(assistantIdx, plan);- };- const missingCalls: Array<{ i: number; id: string; trailing: boolean; callBlockIdx: number }> = [];- for (let i = 0; i <= lastConversationIndex; i++) {- const msg = messages[i];- if (!isPlainObject(msg) || msg.role !== 'assistant' || !Array.isArray(msg.content)) continue;- const trailing = i >= lastConversationIndex;- const nextMsg = messages[i + 1];- const nextContent =- isPlainObject(nextMsg) && nextMsg.role === 'user' && Array.isArray(nextMsg.content)- ? nextMsg.content- : null;- for (let cb = 0; cb < msg.content.length; cb++) {- const block = msg.content[cb];- if (!isToolUseBlock(block)) continue;- const id = block.id;- let hit: { msgIdx: number; blockIdx: number } | undefined;- if (nextContent !== null) {- for (let b = 0; b < nextContent.length; b++) {- const cand = nextContent[b];- if (isToolResultBlock(cand) && cand.tool_use_id === id && !consumed.has(`${i + 1}:${b}`)) {- hit = { msgIdx: i + 1, blockIdx: b };- break;- }- }- }- if (hit !== undefined) {- consumed.add(`${hit.msgIdx}:${hit.blockIdx}`);- // 已邻接判定到块级: 位于前导 tool_result 区间则不动;落在 text 之后- // = 块级错位 → 前移进前导区间( trailing 只消费不修复)。- if (!trailing && hit.blockIdx >= leadingToolResultCount(nextContent!)) {- drops.push(hit);- recordInsert(i, cb, nextContent![hit.blockIdx]);- }- } else {- missingCalls.push({ i, id, trailing, callBlockIdx: cb });- }- }- }-- // pass B2: 接力 —— 位置配对失败的 call,从结果池取**归属区间**内的第一个- // 未消费块前移(错位重排);无候选 → 非 trailing 合成占位。- //- // 归属区间 = (本 assistant 消息下标, 下一条含同 id call 的 assistant 消息- // 下标) —— 即"同 id exchange"边界。依据 agentic loop 串行:下一个 exchange- // 的同 id call 发出时,本 exchange 的同 id result 必已回来(或丢失),出现在- // 下一个 exchange 之后的 result 只属于后面的 exchange;较早缺口 exchange- // 不得越界抢较晚 exchange 的错位真实结果(Greptile 第二轮反例)。- //- // 边界粒度刻意是 exchange(消息)而非单个 call:同一条 assistant 消息内的- // parallel 同 id calls 同批发出、result 同批回来,其中一个丢失时归属在- // 原理上不可判定(信息论:两种归属的世界序列化后字节完全相同,缺失不留- // 位置痕迹)—— 此时采用**稳定 tie-breaker**:区间内涵 call 块顺序配序。- // 该约定受典型 client serializer 支持(CC SDK 的 Tool Runner 以- // Promise.all 并发执行、但结果数组保持输入 tool_use 顺序),可复现且最大- // 保留信息;但只是默认约定,不是 wire 可证明的归属 —— 真正消除歧义只能- // 在丢失前由 source adapter 持久化 occurrence/call index(provenance),- // 本层对已有 body 无法补造这个 bit。- //- // trailing missing call 同样消费区间内的块,但**只消费不修复**(不移、不- // 合成)——保护 trailing 交换的合法尾部 result(如 parallel trailing calls- // 的 result 分多条消息回来)不被下方"池剩余丢弃"误杀。- const callIndicesById = new Map<string, number[]>();- for (let i = 0; i <= lastConversationIndex; i++) {- const msg = messages[i];- if (!isPlainObject(msg) || msg.role !== 'assistant' || !Array.isArray(msg.content)) continue;- for (const block of msg.content) {- if (!isToolUseBlock(block)) continue;- const list = callIndicesById.get(block.id) ?? [];- list.push(i);- callIndicesById.set(block.id, list);- }- }- for (const mc of missingCalls) {- const pool = resultPool.get(mc.id) ?? [];- const indices = callIndicesById.get(mc.id) ?? [];- let nextIdx = Number.POSITIVE_INFINITY;- for (const idx of indices) {- if (idx > mc.i) {- nextIdx = idx;- break;- }- }- let hit: { msgIdx: number; blockIdx: number } | undefined;- for (const cand of pool) {- const key = `${cand.msgIdx}:${cand.blockIdx}`;- if (consumed.has(key)) continue;- if (cand.msgIdx <= mc.i || cand.msgIdx >= nextIdx) continue; // 区间外(前置/归后面的 call)- hit = cand;- break;- }- if (hit !== undefined) {- consumed.add(`${hit.msgIdx}:${hit.blockIdx}`);- if (!mc.trailing) {- drops.push(hit);- const srcMsg = messages[hit.msgIdx] as Record<string, unknown>;- recordInsert(mc.i, mc.callBlockIdx, (srcMsg.content as unknown[])[hit.blockIdx]);- }- // trailing: 仅 consumed 保护,不动位置。- } else if (!mc.trailing) {- recordInsert(mc.i, mc.callBlockIdx, {- type: 'tool_result',- tool_use_id: mc.id,- content: SYNTHETIC_TOOL_RESULT_TEXT,- });- }- }- // 池中剩余(前置 / 超编 / 永不配对)→ 全部丢弃。- for (const pool of resultPool.values()) {- for (const cand of pool) {- const key = `${cand.msgIdx}:${cand.blockIdx}`;- if (consumed.has(key)) continue;- drops.push(cand);- consumed.add(key);- }- }- // 每个 assistant 的插入块按 call 块顺序拼装(位置配对与接力分两遍收集,- // 顺序不一定与 call 顺序一致)。- const insertBlocksAfter = new Map<number, unknown[]>();- for (const [assistantIdx, plan] of insertPlans) {- insertBlocksAfter.set(- assistantIdx,- [...plan.entries()].sort((a, b) => a[0] - b[0]).map(([, block]) => block),- );- }-- if (drops.length === 0 && insertBlocksAfter.size === 0) return null; // cache 安全契约-- // pass C: 单遍组装。drops 按消息分组过滤;插入计划落在 assistant 之后 ——- // 下一条是 user 消息则标记 prepend(遍历到它时并入其 content 的前导- // tool_result 区间末尾,保持 result 在前、与 call 顺序一致),否则就地新建- // user 消息。user 消息过滤后(含 prepend)content 空 → 整条丢。- const dropsByMsg = new Map<number, Set<number>>();- for (const d of drops) {- const set = dropsByMsg.get(d.msgIdx) ?? new Set<number>();- set.add(d.blockIdx);- dropsByMsg.set(d.msgIdx, set);- }- const prependByMsg = new Map<number, unknown[]>();- const out: unknown[] = [];- for (let i = 0; i < messages.length; i++) {- const msg = messages[i];- let current = msg;- if (isPlainObject(msg) && msg.role === 'user') {- const dropsHere = dropsByMsg.get(i);- const prepend = prependByMsg.get(i);- if (Array.isArray(msg.content) && (dropsHere !== undefined || prepend !== undefined)) {- const filtered = dropsHere ? msg.content.filter((_, b) => !dropsHere.has(b)) : [...msg.content];- const k = leadingToolResultCount(filtered);- const content = [...filtered.slice(0, k), ...(prepend ?? []), ...filtered.slice(k)];- if (content.length === 0) continue; // content 清空 → 整条丢- current = { ...msg, content };- } else if (typeof msg.content === 'string' && prepend !== undefined) {- // string content 转等价数组并入;空白 string 不附加 text 块(避免新造- // 空 text 块,转头命中 "text content blocks must be non-empty" 400)。- const text = msg.content.trim().length > 0 ? [{ type: 'text', text: msg.content }] : [];- current = { ...msg, content: [...prepend, ...text] };- }- }- out.push(current);- const inserts = insertBlocksAfter.get(i);- if (inserts !== undefined && inserts.length > 0) {- const next = messages[i + 1];- if (isPlainObject(next) && next.role === 'user') {- prependByMsg.set(i + 1, [...(prependByMsg.get(i + 1) ?? []), ...inserts]);- } else {- out.push({ role: 'user', content: inserts });- }- }- }- return out;-}--/**- * Buffer 版: 配对断裂修复。供 400 recovery(tool_call_id not found /- * unexpected tool_use_id / tool_use without tool_result)与主动 transform 共用。- */-export function repairToolExchangeAdjacencyFromBody(rawBody: Buffer): Buffer | null {- let parsed: unknown;- try {- parsed = JSON.parse(rawBody.toString('utf8'));- } catch {- return null;- }- if (!isPlainObject(parsed)) return null;- const messages = parsed.messages;- if (!Array.isArray(messages)) return null;- const nextMessages = repairToolExchangeAdjacencyInMessages(messages);- if (nextMessages === null) return null;- parsed.messages = nextMessages;- try {- return Buffer.from(JSON.stringify(parsed), 'utf8');- } catch {- return null;- }-}--/**- * 主动 transform 版: body 已由 proxy 解析为 plain object。- * 无断裂返回 null,保持 clean request 的字节级透传语义。- */-export const repairToolExchangeAdjacency: RequestTransform = (body) => {- if (!isPlainObject(body)) return null;- const messages = body.messages;- if (!Array.isArray(messages)) return null;- const nextMessages = repairToolExchangeAdjacencyInMessages(messages);- if (nextMessages === null) return null;- return { ...body, messages: nextMessages };-};--/**- * 组合结构修复: 先 adjacency 接力配对,再重复 id 唯一化 —— 顺序不可颠倒。- *- * 为什么必须 repair 在前: dedupe 的「第 N 个 result 配第 N 个 call」依赖- * result 顺序与 call 顺序一一对应,而病态历史里的前置 result(在 call 之前)- * 会白占一个序号,把本属前一个 call 的 result 改名给后一个 call,repair 再按- * 改名后的 id 配对 → 张冠李戴(复审实测反例: call#1 收到 call#2 的真实结果、- * call#1 自己的结果被丢)。repair 先跑会丢弃前置/超编块、把错位块归位,产出的- * 结构合法历史上 result 与 call 严格同序,dedupe 的顺序配对才等于真实配对。- *- * 供两条 recovery rule 共用: server.ts 的透明重试是「命中规则先 strip,其余按- * 数组顺序顺手应用」,命中顺序会打乱数组里声明的修复顺序,只有组合函数能强制- * repair → dedupe。两步各自检测驱动,无对应异常时该步原样传递。- */-export function repairToolExchangeStructureFromBody(rawBody: Buffer): Buffer | null {- const afterRepair = repairToolExchangeAdjacencyFromBody(rawBody);- const stage1 = afterRepair ?? rawBody;- const afterDedupe = dedupeDuplicateToolUseIdsFromBody(stage1);- if (afterRepair === null && afterDedupe === null) return null; // 两步都无改动- return afterDedupe ?? stage1;-}--// ───────────────────────────────────────────────────────────────────────────-// Per-model handlers ——-// 每个 model 一个独立函数,内部自由实现 strip / 翻译 / 改值。-// 加新 case: 写一个 handler + 在下面 STRIP_HANDLERS 字典里登记。-// ───────────────────────────────────────────────────────────────────────────--/**- * gpt-5.4 (XD.inc litellm → Azure OpenAI backend)- *- * 实测报错:- * AzureException BadRequestError - Unknown parameter: 'output_config'- *- * 处理: 只删 output_config 这一个实测命中的字段。其他 Anthropic-only 字段- * (thinking / cache_control / betas) 暂不动 —— 实测被打脸再加。- */-const stripGpt54: ModelStripHandler = (body) => {- const next: Record<string, unknown> = { ...body };- delete next.output_config;- return next;-};--/**- * gpt-5.4-mini (XD.inc litellm → Azure OpenAI backend)- *- * 实测报错:- * AzureException BadRequestError - Unknown parameter: 'output_config'- *- * 先与 gpt-5.4 保持同样的最小修复面,后续若 mini 需要单独兼容其它字段,- * 直接在这个 handler 扩即可,不影响 gpt-5.4。- */-const stripGpt54Mini: ModelStripHandler = (body) => {- const next: Record<string, unknown> = { ...body };- delete next.output_config;- return next;-};--/**- * 纯文本模型的 tool_result 图像降级(#794)。- *- * 实测(z-ai/glm-5.2,Anthropic 兼容直通):tool_result 里的 image block 原样发给- * 上游,上游静默丢弃且不报错——模型把工具结果当成空,反复重读或直接臆造图片内容- * (实测单任务空转 66 分钟并编造译文)。把 image block 替换为说明性占位文本:- * 明确告知有图但当前模型收不到、禁止臆测、引导贴文本或换视觉模型。- *- * 只处理 tool_result 内嵌图像;user 消息图像走各桥接的 input_image 路径,不归这里。- */-const TOOL_RESULT_IMAGE_OMITTED_TEXT =- '[image omitted: this tool returned an image, but the current model is text-only, '- + 'so the image could not be delivered. Do NOT guess or fabricate what the image '- + 'contains. Tell the user the image could not be delivered to the current model, '- + 'and ask them to paste the relevant content as text or switch to a vision-capable '- + 'model.]';--export function replaceToolResultImagesWithNotice(- body: Record<string, unknown>,- noticeText = TOOL_RESULT_IMAGE_OMITTED_TEXT,-): Record<string, unknown> | null {- const messages = body.messages;- if (!Array.isArray(messages)) return null;-- let replaced = 0;- const nextMessages = messages.map((msg) => {- if (!isPlainObject(msg) || !Array.isArray(msg.content)) return msg;- let msgChanged = false;- const nextContent = msg.content.map((block) => {- if (!isPlainObject(block) || block.type !== 'tool_result' || !Array.isArray(block.content)) {- return block;- }- let blockChanged = false;- const nextInner = block.content.map((inner) => {- if (!isPlainObject(inner) || inner.type !== 'image') return inner;- replaced += 1;- blockChanged = true;- return { type: 'text', text: noticeText };- });- if (!blockChanged) return block;- msgChanged = true;- return { ...block, content: nextInner };- });- return msgChanged ? { ...msg, content: nextContent } : msg;- });-- if (replaced === 0) return null; // cache 安全契约:无改动 → null → 字节透传- return { ...body, messages: nextMessages };-}--/**- * Compact image-heavy conversation history for a request that already crossed- * the proxy's hard body limit.- *- * This is deliberately a synchronous, local-only pass. The newest user- * message is kept intact so the current prompt/image is never silently- * removed. Older history images are dropped before the newest tool-result- * image, with the current prompt always protected. The original media- * remains in the media library; the- * request-local replacement is only a small, explicit text notice.- *- * The function mutates the parsed request object in place (the proxy has- * already paid the JSON.parse cost for an oversized request) and returns it- * only when at least one image was replaced. `targetBytes` is used as a- * cheap estimate while selecting candidates; the proxy performs the final- * serialized-byte check after all regular transforms have run.- */-const OVERSIZED_IMAGE_OMITTED_TEXT =- '[Earlier image omitted to keep this request within the provider size limit. '- + 'Do not infer its contents; ask the user to resend it if it is needed.]';--interface OversizedImageCandidate {- container: unknown[];- index: number;- replacement: Record<string, string>;- /** 0 = old tool-result, 1 = other history, 2 = newest tool-result. */- priority: number;- /** Older messages are removed before newer messages. */- age: number;-}--function jsonByteLength(value: unknown): number {- return Buffer.byteLength(JSON.stringify(value), 'utf8');-}--function collectOversizedAnthropicImages(- messages: unknown[],- candidates: OversizedImageCandidate[],-): void {- let newestToolResultCandidateIndex = -1;- let latestUserIndex = -1;- for (let i = messages.length - 1; i >= 0; i -= 1) {- const message = messages[i];- if (!isPlainObject(message) || message.role !== 'user') continue;- // Anthropic represents tool results as `role: user` messages too. A- // trailing tool_result therefore must not hide the actual prompt message- // whose images are still part of the current turn. Treat a user message- // as a prompt when it has any non-tool_result block (plain text content is- // a prompt as well); tool_result-only messages remain compactable history.- const content = message.content;- const isPrompt = !Array.isArray(content)- || content.some((block) => !isPlainObject(block) || block.type !== 'tool_result');- if (isPrompt) {- latestUserIndex = i;- break;- }- }-- const scan = (content: unknown[], messageIndex: number, inToolResult: boolean): void => {- for (let index = 0; index < content.length; index += 1) {- const block = content[index];- if (!isPlainObject(block)) continue;- if (block.type === 'image') {- // Preserve every image in the newest user message, including images- // nested in its tool_result content.- if (messageIndex === latestUserIndex) continue;- const candidate: OversizedImageCandidate = {- container: content,- index,- replacement: { type: 'text', text: OVERSIZED_IMAGE_OMITTED_TEXT },- priority: inToolResult ? 0 : 1,- age: messageIndex,- };- candidates.push(candidate);- if (- inToolResult- && (- newestToolResultCandidateIndex < 0- // `index` is local to each nested content array, so it cannot- // order images from separate tool_result blocks in one message.- // Candidates are collected in wire order; the later candidate is- // the newer image when message ages tie.- || candidate.age >= candidates[newestToolResultCandidateIndex].age- )- ) {- newestToolResultCandidateIndex = candidates.length - 1;- }- continue;- }- if (block.type === 'tool_result' && Array.isArray(block.content)) {- scan(block.content, messageIndex, true);- }- }- };-- for (let messageIndex = 0; messageIndex < messages.length; messageIndex += 1) {- const message = messages[messageIndex];- if (!isPlainObject(message) || !Array.isArray(message.content)) continue;- scan(message.content, messageIndex, false);- }- // Keep the most recent tool-result image behind older history images. It- // may still be removed as a last resort when no other candidate can bring- // the request under the hard limit, but it is never the first image dropped- // merely because tool results use role=user in Anthropic's wire format.- if (newestToolResultCandidateIndex >= 0) {- candidates[newestToolResultCandidateIndex].priority = 2;- }-}--function isResponsesUserMessage(item: Record<string, unknown>): boolean {- // Responses clients in the wild omit `type` for ordinary user messages;- // explicit non-message item types must remain ineligible for protection.- return item.role === 'user' && (item.type === 'message' || item.type === undefined);-}--function collectOversizedOpenAiChatImages(- messages: unknown[],- candidates: OversizedImageCandidate[],-): void {- let latestUserIndex = -1;- for (let i = messages.length - 1; i >= 0; i -= 1) {- const message = messages[i];- if (isPlainObject(message) && message.role === 'user') {- latestUserIndex = i;- break;- }- }-- for (let messageIndex = 0; messageIndex < messages.length; messageIndex += 1) {- const message = messages[messageIndex];- if (!isPlainObject(message) || !Array.isArray(message.content)) continue;- for (let index = 0; index < message.content.length; index += 1) {- const block = message.content[index];- if (!isPlainObject(block) || block.type !== 'image_url') continue;- // OpenAI Chat uses a normal role=user message for the current prompt;- // keep every image in that newest user message intact.- if (messageIndex === latestUserIndex) continue;- candidates.push({- container: message.content,- index,- replacement: { type: 'text', text: OVERSIZED_IMAGE_OMITTED_TEXT },- priority: 1,- age: messageIndex,- });- }- }-}--function collectOversizedResponsesImages(- input: unknown[],- candidates: OversizedImageCandidate[],-): void {- let latestUserIndex = -1;- for (let i = input.length - 1; i >= 0; i -= 1) {- const item = input[i];- if (isPlainObject(item) && isResponsesUserMessage(item)) {- latestUserIndex = i;- break;- }- }-- for (let itemIndex = 0; itemIndex < input.length; itemIndex += 1) {- const item = input[itemIndex];- if (!isPlainObject(item)) continue;- const content = Array.isArray(item.content) ? item.content : null;- if (!content) continue;- for (let index = 0; index < content.length; index += 1) {- const block = content[index];- if (!isPlainObject(block) || block.type !== 'input_image') continue;- if (itemIndex === latestUserIndex) continue;- candidates.push({- container: content,- index,- replacement: { type: 'input_text', text: OVERSIZED_IMAGE_OMITTED_TEXT },- priority: 1,- age: itemIndex,- });- }- }-}--export function compactOversizedImageHistory(- body: Record<string, unknown>,- targetBytes: number,-): Record<string, unknown> | null {- if (!Number.isFinite(targetBytes) || targetBytes <= 0) return null;-- const candidates: OversizedImageCandidate[] = [];- if (Array.isArray(body.messages)) {- collectOversizedAnthropicImages(body.messages, candidates);- collectOversizedOpenAiChatImages(body.messages, candidates);- }- if (Array.isArray(body.input)) {- collectOversizedResponsesImages(body.input, candidates);- }- // Avoid serializing a potentially huge text-only history: the common- // oversized-text case has no safe image candidate to compact.- if (candidates.length === 0) return null;-- let estimatedBytes: number;- try {- estimatedBytes = jsonByteLength(body);- } catch {- return null;- }- if (estimatedBytes <= targetBytes) return null;-- candidates.sort((a, b) => a.priority - b.priority || a.age - b.age);- let replaced = 0;- for (const candidate of candidates) {- const previousBytes = jsonByteLength(candidate.container[candidate.index]);- const replacementBytes = jsonByteLength(candidate.replacement);- candidate.container[candidate.index] = candidate.replacement;- estimatedBytes += replacementBytes - previousBytes;- replaced += 1;- if (estimatedBytes <= targetBytes) break;- }-- return replaced > 0 ? body : null;-}--/** glm-5.2 (智谱,官方仅文本/代码模态) —— 直通与网关两条路由同一 model id。 */-const stripGlm52: ModelStripHandler = (body) => replaceToolResultImagesWithNotice(body);--// ───────────────────────────────────────────────────────────────────────────-// 分发表-// ───────────────────────────────────────────────────────────────────────────--/**- * Per-model handler 字典 —— key = model id (与 body.model 严格相等比较)。- * 不在表里的 model 一律字节透传,proxy 零干预。- */-const STRIP_HANDLERS: Readonly<Record<string, ModelStripHandler>> = {- 'gpt-5.4': stripGpt54,- 'gpt-5.4-mini': stripGpt54Mini,- // 「折扣GPT」低价路由 —— 与 gpt-5.4 打同一个 Azure 后端, 同样会因 output_config 报 400,- // 镜像 gpt-5.4 的 strip 行为 (复用同一 handler)。codex/gpt-5.5 暂不加, 与 gpt-5.5 一致。- 'codex/gpt-5.4': stripGpt54,- // 纯文本模型 tool_result 图像会被上游静默吞掉 (#794) —— 带/不带命名空间前缀,- // 以及 claude-code SDK 按目录 1M 窗口追加 [1m] 后缀 (toSdkModelString) 的形态- // 都登记 (直通路由 body.model 可能保留 z-ai/ 前缀与 [1m] 后缀)。- 'glm-5.2': stripGlm52,- 'z-ai/glm-5.2': stripGlm52,- 'glm-5.2[1m]': stripGlm52,- 'z-ai/glm-5.2[1m]': stripGlm52,-};--/**- * 默认 transform —— 按 model 分发到对应 handler;查不到就透传。- */-export const stripNonAnthropicFields: RequestTransform = (body) => {- if (!isPlainObject(body)) return null;-- const model = body.model;- if (typeof model !== 'string' || model.length === 0) return null;-- const handler = STRIP_HANDLERS[model];- if (!handler) return null;-- return handler(body);-};--/**- * 主动剥离 transform —— 某 thread 因对应 400 恢复过一次后(controller 已 markActive),- * 后续请求发送前就提前剥,省掉每轮重撞 400。`strip` 决定剥什么(encrypted 传- * stripEncryptedContentFromBody,thinking 传 stripEmptyThinkingFromBody);controller- * 必须与对应 recovery rule 是同一实例,且每个剥离条件用各自独立实例(详见 ThreadStripController)。- */-export function createActiveStripTransform(opts: {- controller: ThreadStripController;- enabled: () => boolean;- /** 对已标记 thread 主动剥离用的函数(与对应 recovery rule 的 strip 一致)。 */- strip: (rawBody: Buffer) => Buffer | null;- threadIdHeaders?: readonly string[];-}): RequestTransform {- const threadIdHeaders = opts.threadIdHeaders ?? DEFAULT_THREAD_ID_HEADERS;- return (body: unknown, ctx: RequestTransformCtx): unknown | null => {- if (!opts.enabled()) return null;- if (!isPlainObject(body)) return null;-- const threadId = selectedHeaderValue(ctx.headers, threadIdHeaders);- const model = body.model;- if (!threadId || typeof model !== 'string' || model.length === 0) return null;- opts.controller.reconcile(threadId, model);- if (!opts.controller.shouldStrip(threadId)) return null;-- const stripped = opts.strip(Buffer.from(JSON.stringify(body), 'utf8'));- if (!stripped) return null;-- try {- return JSON.parse(stripped.toString('utf8'));- } catch {- return null;- }- };-}--// ───────────────────────────────────────────────────────────────────────────-// Recovery rules —— 上游 400 透明重试规则(server.ts 的 forward() 按序应用第一条命中的)。-// 每条规则把"错误体匹配正则 + 对应 strip 函数"绑在一起,正则与 strip 就近放,单一真相源。-// ───────────────────────────────────────────────────────────────────────────--// 上游 400/422 错误体命中以下任一 → 判定为"协议加密推理内容解不开"。-// litellm/Azure: code "invalid_encrypted_content" + "Encrypted content could not be decrypted or parsed."-// xAI Responses: code "invalid-argument" + "Could not decrypt the provided encrypted_content..."-const INVALID_ENCRYPTED_CONTENT_RE =- /invalid_encrypted_content|invalid-argument[\s\S]{0,160}encrypted_content|could not decrypt(?: the provided)? encrypted_content|encrypted content could not be (?:decrypted|verified|parsed)/i;--// Anthropic 400: "messages.N.content.M.thinking: each thinking block must contain thinking"-// 只匹配不变的核心短语,不锚定会变的 messages.N.content.M 下标前缀。-const EMPTY_THINKING_RE = /each thinking block must contain thinking/i;--// Anthropic 400: "messages.N.content.M: text content blocks must be non-empty"-// (纯空白变体: "text content blocks must contain non-whitespace text")。-// 同样只匹配核心短语,不锚定下标前缀。-const EMPTY_TEXT_RE = /text content blocks must (?:be non-empty|contain non-whitespace text)/i;--// moonshot 400 (经 LiteLLM /anthropic/v1/messages passthrough,2026-07-28 实测):-// "Invalid request: the message at position 693 with role 'assistant' must not be empty"-// 只匹配不变的 role + 校验短语,不锚定会变的 position 数字。-const EMPTY_ASSISTANT_MESSAGE_RE = /with role 'assistant' must not be empty/i;--// Azure/LiteLLM 400: "Image generation items without `id` are not supported for this request."-const IMAGE_GENERATION_WITHOUT_ID_RE =- /image generation items without [`']?id[`']? are not supported/i;--const TOOL_USE_PROVIDER_SPECIFIC_FIELDS_RE =- /\.tool_use\.provider_specific_fields[^"\r\n|]*extra inputs are not permitted|extra inputs are not permitted[^"\r\n|]*\.tool_use\.provider_specific_fields/i;--// Anthropic 400: "messages: `tool_use` ids must be unique"(kimi kosong-// STRUCTURAL_REQUEST 同族正则)。moonshot 实测容忍重复 id 不报错(静默错乱),-// 但 LiteLLM 版本差异 / 真 Anthropic 上游会报;命中时用与主动 transform-// 相同的唯一化 strip 重发。-const DUPLICATE_TOOL_USE_ID_RE = /tool_use[\s\S]*ids must be unique/i;--// tool 配对断裂 400 家族(kimi kosong TOOL_EXCHANGE_ADJACENCY 同族,按本链路-// 可见措辞收敛):-// - Moonshot(chatcmpl 校验透出): "tool_call_id is not found"(孤儿 result,-// 原文双空格;锚定 tool_call_id,404 类 "not found" 不会误命中)-// - Anthropic 孤儿 result: "unexpected `tool_use_id` found in `tool_result`-// blocks"(两个锚点都限定,避免命中非 tool_result 上下文的 unexpected)-// - Anthropic 未配对 call: "`tool_use` ids were found without `tool_result`-// blocks immediately after"-// - OpenAI 系(LiteLLM 版本差异可能透出): 孤儿 tool 消息 "unexpected-// `tool_result`" / "messages with role 'tool' must be a response to a-// preceding message with 'tool_calls'";未配对 call "the following-// tool_call_ids did not have response messages: ..."-// roles-must-alternate / first-message-must-be-user 不在此列: 本修复不处理-// 合并与 leading 裁剪,匹配了也 strip 不出东西(实测命中再扩)。-const TOOL_EXCHANGE_ADJACENCY_RE =- /tool_call_id[\s\S]*not found|unexpected\s+`?tool_use_id`?[\s\S]*tool_result|unexpected\s+`?tool_result|`?tool_use`?\s+ids were found without|tool_call_ids? did not have response messages|role\s+['"`]?tool['"`]?\s+must be a response to a preceding message/i;--/**- * invalid_encrypted_content 恢复规则: 剥掉请求体里所有 encrypted_content 重发。- * 受 enabled() gate(由 host 接 silentEncryptedRetry 设置,默认开,用户可关闭)。- */-export function createEncryptedContentRecoveryRule(opts: {- enabled: () => boolean;- onRetry?: (threadId: string, model: string) => void;- threadIdHeaders?: readonly string[];-}): RecoveryRule {- return {- id: 'encrypted_content',- enabled: opts.enabled,- matches: (text) => INVALID_ENCRYPTED_CONTENT_RE.test(text),- strip: stripEncryptedContentFromBody,- unrecoverableCode: (body) => {- // Only compaction remains opaque. A standalone reasoning rejection must retain- // the ordinary retry/error behavior and must never request a context rebuild.- if (stripEncryptedContentFromBody(body)) return null;- try {- const input = JSON.parse(body.toString('utf8')).input;- return Array.isArray(input) && input.some((item) => item?.type === 'compaction' &&- typeof item.encrypted_content === 'string' && item.encrypted_content.length > 0)- ? 'CINDY_ENCRYPTED_COMPACTION_INCOMPATIBLE' : null;- } catch {- return null;- }- },- onRetry: opts.onRetry,- threadIdHeaders: opts.threadIdHeaders,- };-}--/**- * 缺 id 的 image generation item 恢复规则: 剥掉坏历史 item 后重发。- * 默认 always-on;只在明确命中上游错误时触发,正常请求字节透传。- */-export function createImageGenerationIdRecoveryRule(opts: {- enabled?: () => boolean;- onRetry?: (threadId: string, model: string) => void;- threadIdHeaders?: readonly string[];-} = {}): RecoveryRule {- return {- id: 'image_generation_id',- enabled: opts.enabled ?? (() => true),- matches: (text) => IMAGE_GENERATION_WITHOUT_ID_RE.test(text),- strip: stripImageGenerationItemsWithoutIdFromBody,- onRetry: opts.onRetry,- threadIdHeaders: opts.threadIdHeaders,- };-}--/**- * `tool_use.provider_specific_fields` 400 恢复规则:清理历史后透明重试一次。- * 主动 transform 通常会先移除该字段;该规则覆盖 transform 未接入、旧会话- * 或其它兼容链路绕过主动清理的情况。- */-export function createToolUseProviderSpecificFieldsRecoveryRule(opts: {- enabled?: () => boolean;- onRetry?: (threadId: string, model: string) => void;- threadIdHeaders?: readonly string[];-} = {}): RecoveryRule {- return {- id: 'tool_use_provider_specific_fields',- enabled: opts.enabled ?? (() => true),- matches: (text) => TOOL_USE_PROVIDER_SPECIFIC_FIELDS_RE.test(text),- strip: stripToolUseProviderSpecificFieldsFromBody,- onRetry: opts.onRetry,- threadIdHeaders: opts.threadIdHeaders,- };-}--/**- * 空 thinking 块恢复规则: 跨厂商切回 Anthropic 模型时,剥掉历史里的空内容 thinking 块重发。- * 默认 always-on(删空块零代价,无需用户权衡)。- */-export function createEmptyThinkingRecoveryRule(opts: {- enabled?: () => boolean;- onRetry?: (threadId: string, model: string) => void;- threadIdHeaders?: readonly string[];-} = {}): RecoveryRule {- return {- id: 'empty_thinking',- enabled: opts.enabled ?? (() => true),- matches: (text) => EMPTY_THINKING_RE.test(text),- strip: stripEmptyThinkingFromBody,- onRetry: opts.onRetry,- threadIdHeaders: opts.threadIdHeaders,- };-}--/**- * 空 text 块恢复规则: 历史被 bridge 修复前的空 `{type:"text",text:""}` 块污染的会话,- * 切到真 Anthropic 模型时 400 → 剥掉空块重发。默认 always-on(删空块零代价)。- */-export function createEmptyTextRecoveryRule(opts: {- enabled?: () => boolean;- onRetry?: (threadId: string, model: string) => void;- threadIdHeaders?: readonly string[];-} = {}): RecoveryRule {- return {- id: 'empty_text',- enabled: opts.enabled ?? (() => true),- matches: (text) => EMPTY_TEXT_RE.test(text),- strip: stripEmptyTextFromBody,- onRetry: opts.onRetry,- threadIdHeaders: opts.threadIdHeaders,- };-}--/**- * 空 assistant 消息恢复规则: moonshot/kimi 系(Anthropic 兼容流空 thinking 占位被- * 客户端中断持久化后)回放 400 → 丢掉空 assistant 消息重发。- * 默认 always-on(空消息不含对话信息,丢弃零代价)。背景详见- * stripEmptyAssistantMessagesFromBody 头注。- */-export function createEmptyAssistantMessageRecoveryRule(opts: {- enabled?: () => boolean;- onRetry?: (threadId: string, model: string) => void;- threadIdHeaders?: readonly string[];-} = {}): RecoveryRule {- return {- id: 'empty_assistant_message',- enabled: opts.enabled ?? (() => true),- matches: (text) => EMPTY_ASSISTANT_MESSAGE_RE.test(text),- strip: stripEmptyAssistantMessagesFromBody,- onRetry: opts.onRetry,- threadIdHeaders: opts.threadIdHeaders,- };-}--/**- * 重复 tool_use id 恢复规则: 上游 400 ``tool_use` ids must be unique` →- * 组合结构修复(先 adjacency 后唯一化,顺序约束见- * repairToolExchangeStructureFromBody)后重发。默认 always-on(修复是协议- * 级的,无异常时 strip 返回 null 自然跳过)。kimi code 的 strict resend 同族处理。- */-export function createDuplicateToolUseIdRecoveryRule(opts: {- enabled?: () => boolean;- onRetry?: (threadId: string, model: string) => void;- threadIdHeaders?: readonly string[];-} = {}): RecoveryRule {- return {- id: 'duplicate_tool_use_id',- enabled: opts.enabled ?? (() => true),- matches: (text) => DUPLICATE_TOOL_USE_ID_RE.test(text),- strip: repairToolExchangeStructureFromBody,- onRetry: opts.onRetry,- threadIdHeaders: opts.threadIdHeaders,- };-}--/**- * tool 配对断裂恢复规则: 孤儿 result / 未配对 call 的 400(moonshot- * `tool_call_id is not found` / Anthropic `unexpected tool_use_id` /- * `tool_use ids were found without tool_result` / OpenAI 系 wording)→- * 组合结构修复后重发。默认 always-on(与 kimi code projector 的 adjacency- * 修复同构)。- */-export function createToolExchangeAdjacencyRecoveryRule(opts: {- enabled?: () => boolean;- onRetry?: (threadId: string, model: string) => void;- threadIdHeaders?: readonly string[];-} = {}): RecoveryRule {- return {- id: 'tool_exchange_adjacency',- enabled: opts.enabled ?? (() => true),- matches: (text) => TOOL_EXCHANGE_ADJACENCY_RE.test(text),- strip: repairToolExchangeStructureFromBody,- onRetry: opts.onRetry,- threadIdHeaders: opts.threadIdHeaders,- };-}+/** Compatibility implementation is owned by the shared package; preserve this import contract. */+export {+ createVllmResponsesCompatibilityRule,+ stripToolUseProviderSpecificFieldsFromBody,+ stripToolUseProviderSpecificFields,+ stripEncryptedContentFromBody,+ stripImageGenerationItemsWithoutIdFromBody,+ stripEmptyThinkingFromBody,+ stripEmptyTextFromBody,+ stripEmptyAssistantMessagesFromBody,+ dedupeDuplicateToolUseIdsFromBody,+ dedupeDuplicateToolUseIds,+ repairToolExchangeAdjacencyFromBody,+ repairToolExchangeAdjacency,+ repairToolExchangeStructureFromBody,+ replaceToolResultImagesWithNotice,+ compactOversizedImageHistory,+ stripNonAnthropicFields,+ createActiveStripTransform,+ createEncryptedContentRecoveryRule,+ createImageGenerationIdRecoveryRule,+ createToolUseProviderSpecificFieldsRecoveryRule,+ createEmptyThinkingRecoveryRule,+ createEmptyTextRecoveryRule,+ createEmptyAssistantMessageRecoveryRule,+ createDuplicateToolUseIdRecoveryRule,+ createToolExchangeAdjacencyRecoveryRule+} from '@cindy/model-compat';diff --git a/packages/anthropic-compat-proxy/src/types.ts b/packages/anthropic-compat-proxy/src/types.tsindex 7d7ddca0b1..7050bc3dc7 100644--- a/packages/anthropic-compat-proxy/src/types.ts+++ b/packages/anthropic-compat-proxy/src/types.ts@@ -1,3 +1,5 @@+import type { RequestTransformCtx, RequestTransform, RecoveryRule } from '@cindy/model-compat';+export type { RequestTransformCtx, RequestTransform, RecoveryRule } from '@cindy/model-compat';/*** 公开类型 —— 给 host 注入 transform 链 / logger 用。*@@ -15,54 +17,6 @@ import type { Transform } from "node:stream";import type { OutboundProxyResolver } from "./outbound-proxy.js";-/**- * 请求 transform 上下文。- * - method/url/headers 是只读快照,transform 不应该尝试通过这些改写 outbound 请求- * (改 method/url 没意义,改 headers 通过专用 transform 接口未来再加)- */-export interface RequestTransformCtx {- /** Monotonic identifier shared with the eventual response observer for this request. */- readonly reqId: number;- readonly method: string;- readonly url: string;- readonly headers: Readonly<Record<string, string>>;- /**- * 本请求**最终**发往的上游 baseURL(routingTransform 的 per-request override 已生效,- * 与 ResponseObserverCtx.upstreamBase 同构)。仅在请求 transform 链的 ctx 里出现;- * routingTransform / localHandler 的 ctx 中为 undefined(路由尚未/无需解析)。- * 供「按目标上游做兼容改写」的 transform 使用(如跨供应商时转换上游读不懂的历史项),- * 避免 host 侧为判断路由去向而复刻整套路由逻辑。- */- readonly upstreamBase?: string;-}--/**- * 请求 body transform。- *- * 允许返回 Promise(视觉桥等需要出网调用的 transform 用)。引擎用 isPromiseLike- * 统一 await:同步 transform 返回值原样通过,语义与 async 化前逐字节一致。- *- * @returns- * - 新的 body 对象 → 代理用它替换原 body 转发上游- * - null → 不改写,这一步跳过(还会继续跑后续 transform;全部跳过则字节透传)- */-export interface RequestTransform {- (- body: unknown,- ctx: RequestTransformCtx,- ): unknown | null | Promise<unknown | null>;- /**- * Error handling for this transform. The default keeps the historical fail-open behavior;- * transforms that must not expose their unadapted input upstream can reject the request.- */- errorMode?: 'reject-request';- /**- * Optional cleanup for request-scoped state created while evaluating this transform.- * Called once after a request that entered the transform chain finishes or closes.- */- onRequestSettled?: (requestId: number) => void;-}-/*** A bounded, request-local compactor used only when the inbound body is over* the normal forwarding limit. It must be deterministic and must not perform@@ -219,45 +173,6 @@ export type ResponseObserver = (/** 请求级响应体改写;null 保持零拷贝,Transform 仍由代理统一收口生命周期与 headers。 */export type ResponseTransform = (ctx: ResponseObserverCtx) => Transform | null | undefined;-/**- * 一条 400 透明重试规则。- *- * forward() 命中上游 400 时,按顺序找第一条 `enabled() && matches(decodedErrBodyText)- * && strip(body) !== null` 的规则,用其 strip 结果重发一次(canRetry=false,防循环)。- * 多条规则并列(例: encrypted_content / empty_thinking),互不耦合;regex 互斥,- * 命中顺序仅在两条都可能匹配同一错误体时才有意义(实际不会)。- */-export interface RecoveryRule {- /** 诊断用稳定 id,进日志(例 'encrypted_content' / 'empty_thinking')。 */- id: string;- /** gate: false 时该规则完全跳过(thinking 永远 true;encrypted 跟 silentEncryptedRetry 设置)。 */- enabled: () => boolean;- /** 对解压后的 400 错误体文本判定是否命中本规则。- * 命名避开 `match`:与 String.prototype.match 同名会让 CodeQL 把动态文本误判为- * 正则模式(js/regex-injection 误报)。 */- matches: (decodedErrorBodyText: string) => boolean;- /** 改写请求 body;返回 null = 没有可改的东西(本规则不适用,继续找下一条)。 */- strip: (body: Buffer) => Buffer | null;- /** Classify a matched terminal rejection from the actual sent body, after safe retries. */- unrecoverableCode?: (body: Buffer) => string | null;- /** 命中并成功 strip 后触发(用于 Layer-2 markActive)。 */- 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;-}-/*** 极简 logger 接口 —— 跟 maker-core/Logger 形态对齐,host 可以直接传同一个 logger 适配器进来。* 全可选,不传任何方法就完全静默。diff --git a/packages/anthropic-compat-proxy/src/vllm-responses-compatibility.ts b/packages/anthropic-compat-proxy/src/vllm-responses-compatibility.tsindex c42b50a9e3..8e56ed44d0 100644--- a/packages/anthropic-compat-proxy/src/vllm-responses-compatibility.ts+++ b/packages/anthropic-compat-proxy/src/vllm-responses-compatibility.ts@@ -1,97 +1,5 @@-import type { RecoveryRule } from './types.js';--interface ResponsesCompatibilityBody {- instructions?: unknown;- input?: unknown;- reasoning?: { effort?: unknown };- [key: string]: unknown;-}--interface ResponsesCompatibilityMessage {- type?: unknown;- role?: unknown;- content?: unknown;- [key: string]: unknown;-}--const REASONING_EFFORT_ERROR_RE =- /Unexpected reasoning effort high\. Supported types are xhigh \(default\), medium, and low\./i;-const UNEXPECTED_MESSAGE_ROLE_RE = /Unexpected message role\./i;--function isRecord(value: unknown): value is Record<string, unknown> {- return typeof value === 'object' && value !== null && !Array.isArray(value);-}--function isMessage(value: unknown): value is ResponsesCompatibilityMessage {- return isRecord(value) && typeof value.role === 'string';-}--function normalizeRoles(input: readonly unknown[]): { input: unknown[]; changed: boolean } {- let changed = false;- const normalized = input.map((item) => {- if (!isMessage(item) || item.role !== 'developer') return item;- changed = true;- return { ...item, role: 'system' };- });- return { input: normalized, changed };-}--/**- * Convert only the Responses fields that Qwen's vLLM chat template rejected.- * This runs after an exact 400, so native Responses endpoints keep byte-for-byte- * requests; normal endpoints never see the rewritten shape.- */-export function normalizeVllmResponsesRequest(body: unknown): object | null {- if (!isRecord(body)) return null;- const source = body as ResponsesCompatibilityBody;- let changed = false;- const next: ResponsesCompatibilityBody = { ...source };-- if (source.reasoning?.effort === 'high') {- next.reasoning = { ...source.reasoning, effort: 'xhigh' };- changed = true;- }-- let input: unknown = source.input;- if (Array.isArray(source.input)) {- const roles = normalizeRoles(source.input);- input = roles.input;- changed ||= roles.changed;- }-- if (source.instructions !== undefined && source.instructions !== null && source.instructions !== '') {- const systemMessage = { type: 'message', role: 'system', content: source.instructions };- // Responses 允许 input 为纯字符串(等价单条 user 消息)。重试时必须把它转成- // 显式 user 消息追加在 system 之后,绝不能被 instructions 的 system 消息覆盖。- if (typeof input === 'string') {- input = [systemMessage, { type: 'message', role: 'user', content: input }];- } else if (Array.isArray(input)) {- input = [systemMessage, ...input];- } else {- input = [systemMessage];- }- delete next.instructions;- changed = true;- }- next.input = input;-- return changed ? next : null;-}--export function createVllmResponsesCompatibilityRule(): RecoveryRule {- return {- id: 'vllm_responses_compat',- enabled: () => true,- matches: (errorText) =>- REASONING_EFFORT_ERROR_RE.test(errorText) || UNEXPECTED_MESSAGE_ROLE_RE.test(errorText),- strip: (body) => {- try {- const normalized = normalizeVllmResponsesRequest(JSON.parse(body.toString('utf8')));- return normalized ? Buffer.from(JSON.stringify(normalized), 'utf8') : null;- } catch {- return null;- }- },- applyOnUnmatchedRetry: false,- };-}+/** Compatibility implementation is owned by the shared package; preserve this import contract. */+export {+ normalizeVllmResponsesRequest,+ createVllmResponsesCompatibilityRule+} from '@cindy/model-compat';diff --git a/packages/anthropic-compat-proxy/src/xai-model-input.ts b/packages/anthropic-compat-proxy/src/xai-model-input.tsindex 587dd8283d..5cceb5dc2d 100644--- a/packages/anthropic-compat-proxy/src/xai-model-input.ts+++ b/packages/anthropic-compat-proxy/src/xai-model-input.ts@@ -1,659 +1,14 @@-/**- * 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,- };-}+/** Compatibility implementation is owned by the shared package; preserve this import contract. */+export {+ looksLikeXaiResponsesModel,+ xaiBareModelId,+ supportsXaiReasoningModel,+ sanitizeXaiModelInputBody,+ sanitizeXaiModelInputFromBody,+ createXaiModelInputSanitizeTransform,+ createXaiModelInputRecoveryRule+} from '@cindy/model-compat';+export type {+ SanitizeXaiModelInputOptions,+ XaiModelInputCompatOptions+} from '@cindy/model-compat';diff --git a/packages/anthropic-responses-bridge/package.json b/packages/anthropic-responses-bridge/package.jsonindex aaaf4b0d4b..e9dd3d9738 100644--- a/packages/anthropic-responses-bridge/package.json+++ b/packages/anthropic-responses-bridge/package.json@@ -27,5 +27,8 @@"typescript": "^5.7.0","typescript-eslint": "^8.0.0","vitest": "^3.2.4"+ },+ "dependencies": {+ "@cindy/model-compat": "workspace:*"}}diff --git a/packages/anthropic-responses-bridge/src/handler.ts b/packages/anthropic-responses-bridge/src/handler.tsindex 531722df19..e8f3038ce6 100644--- a/packages/anthropic-responses-bridge/src/handler.ts+++ b/packages/anthropic-responses-bridge/src/handler.ts@@ -1,3 +1,4 @@+import { normalizeProviderRequest } from '@cindy/model-compat';/*** Bridge handler ——*@@ -374,6 +375,13 @@ export function createResponsesHandler(opts: ResponsesHandlerOptions): ResponsesstrictFunctionTools: provider.strictFunctionTools?.(realModel) === true|| (wireDiagnosticsEnabled && opts.wireDiagnosticsStrict === true),});+ let finalRequest: unknown;+ try {+ finalRequest = normalizeProviderRequest(responsesReq, { harness: 'claude-code', protocol: 'openai-responses', upstreamBase: provider.upstreamBase, model: responsesReq.model });+ } catch {+ writeJson(res, 400, { type: 'error', error: { type: 'invalid_request_error', message: 'request cannot be represented by the selected provider protocol' } });+ return;+ }const diagnostics = wireDiagnosticsEnabled? new WireDiagnosticsSession(log, {requestId: ctx.reqId ?? reqId,@@ -400,7 +408,7 @@ export function createResponsesHandler(opts: ResponsesHandlerOptions): Responses// 由下游缓冲满足。accept: 'text/event-stream',},- body: JSON.stringify(responsesReq),+ body: JSON.stringify(finalRequest),signal: abort.signal,});} catch (err) {diff --git a/packages/anthropic-responses-bridge/src/strict-schema.ts b/packages/anthropic-responses-bridge/src/strict-schema.tsindex afaa19216d..89b73b3bac 100644--- a/packages/anthropic-responses-bridge/src/strict-schema.ts+++ b/packages/anthropic-responses-bridge/src/strict-schema.ts@@ -1,117 +1 @@-/**- * OpenAI 式 strict function-tool 的 schema 兼容性判定(fail-closed)。- *- * strict 约束解码只接受一个受限 JSON Schema 子集:对象节点必须- * `additionalProperties:false` 且**所有** property 进 `required`,关键字限于少数白名单。- * Claude Code 内置工具(如 Edit 的可选 replace_all)和复杂 MCP schema- * (propertyNames / maxItems / oneOf …)普遍不满足。- *- * 判定取保守面:任何未知关键字、未覆盖形态一律判不兼容,由调用方回落 strict:false。- * 回落只是少一层约束(与现状一致),误开 strict 才有上游 400 / 语义漂移风险;- * 因此**不做 optional→nullable 的 schema 改写**,不改变工具语义。- *- * 结果是 schema 内容的纯函数:同一会话内工具集稳定 ⇒ 每轮各工具的 strict 位稳定,- * 不破坏请求前缀一致性(docs/dev-rules/maker-core-and-agent-behavior.md §3.1)。- */--/** strict 子集允许的 schema 关键字。白名单外(pattern/format/oneOf/propertyNames…)一律不兼容。 */-const ALLOWED_KEYS = new Set([- 'type',- 'description',- 'enum',- 'const',- 'properties',- 'required',- 'additionalProperties',- 'items',- 'anyOf',-]);--const ALLOWED_TYPES = new Set(['object', 'array', 'string', 'number', 'integer', 'boolean', 'null']);--/** 递归深度上限:防御性边界,真实工具 schema 远达不到;超深直接判不兼容。 */-const MAX_DEPTH = 16;--function isPlainObject(value: unknown): value is Record<string, unknown> {- return typeof value === 'object' && value !== null && !Array.isArray(value);-}--/**- * 该 function-tool 参数 schema 是否可以安全地声明 `strict: true`。- * 根节点必须是 `type:'object'`(Responses function parameters 的硬要求)。- */-export function isStrictCompatibleSchema(schema: unknown): boolean {- if (!isPlainObject(schema)) return false;- if (schema.type !== 'object') return false;- return nodeOk(schema, MAX_DEPTH);-}--function nodeOk(node: Record<string, unknown>, depth: number): boolean {- if (depth <= 0) return false;- for (const key of Object.keys(node)) {- if (!ALLOWED_KEYS.has(key)) return false;- }-- // anyOf 节点:只能与 description 共存,分支各自校验(strict 子集不支持 anyOf 与- // type/properties 等结构字段同级混写)。- if (node.anyOf !== undefined) {- for (const key of Object.keys(node)) {- if (key !== 'anyOf' && key !== 'description') return false;- }- if (!Array.isArray(node.anyOf) || node.anyOf.length === 0) return false;- return node.anyOf.every((branch) => isPlainObject(branch) && nodeOk(branch, depth - 1));- }-- const types = typeList(node.type);- if (!types) return false;-- if (types.includes('object')) {- if (node.additionalProperties !== false) return false;- if (!isPlainObject(node.properties)) return false;- const propertyKeys = Object.keys(node.properties).sort();- // required 必须**恰好**覆盖全部 property(缺一个 = 存在 optional 字段,不兼容;- // 多一个 = required 指向不存在的字段,同样不兼容)。- if (!Array.isArray(node.required)) return false;- const required = node.required.filter((item): item is string => typeof item === 'string');- if (required.length !== node.required.length) return false;- const sortedRequired = [...required].sort();- if (- sortedRequired.length !== propertyKeys.length- || sortedRequired.some((key, index) => key !== propertyKeys[index])- ) {- return false;- }- for (const value of Object.values(node.properties)) {- if (!isPlainObject(value) || !nodeOk(value, depth - 1)) return false;- }- } else if (- node.properties !== undefined- || node.required !== undefined- || node.additionalProperties !== undefined- ) {- return false;- }-- if (types.includes('array')) {- if (!isPlainObject(node.items) || !nodeOk(node.items, depth - 1)) return false;- } else if (node.items !== undefined) {- return false;- }-- // enum/const 的成员是任意 JSON 值,strict 子集接受,成员内容无需校验;- // 但空 enum 连普通 grammar 编译都会被上游 400(docs.x.ai structured-outputs),判不合规。- if (node.enum !== undefined && (!Array.isArray(node.enum) || node.enum.length === 0)) return false;- return true;-}--/** type 归一化:字符串或字符串数组(nullable 联合如 ['string','null']),全部落在允许集合内。 */-function typeList(type: unknown): string[] | null {- const raw = typeof type === 'string' ? [type] : Array.isArray(type) ? type : null;- if (!raw || raw.length === 0) return null;- const out: string[] = [];- for (const entry of raw) {- if (typeof entry !== 'string' || !ALLOWED_TYPES.has(entry)) return null;- out.push(entry);- }- return out;-}+export { isStrictCompatibleSchema } from '@cindy/model-compat';diff --git a/packages/model-compat/LICENSE.opencodex b/packages/model-compat/LICENSE.opencodexnew file mode 100644index 0000000000..b034f41c97--- /dev/null+++ b/packages/model-compat/LICENSE.opencodex@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 opencodex contributors++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/packages/model-compat/README.md b/packages/model-compat/README.mdnew file mode 100644index 0000000000..e44ca1047a--- /dev/null+++ b/packages/model-compat/README.md@@ -0,0 +1,135 @@+# Cindy model compatibility++This package owns provider protocol corrections shared by Cindy's existing transports. It combines+pinned OpenCodex source with Cindy's established fixes. It does not own accounts, model catalogs,+pricing, routing, SDK installation, configuration export, or credential discovery.++Upstream: [lidge-jun/opencodex](https://github.com/lidge-jun/opencodex), commit+`c155cc7923dbc0102e27d79185505a85d4357b2c` (MIT; see `LICENSE.opencodex`).+`UPSTREAM.json` records the original and ported SHA-256 for every imported module and test.+`upstream.patch` records the reviewed changes to those modules. Pure helpers extracted from larger+adapters are listed by symbol, with a reproducible import prefix, in the same manifest.++## Entry points and ownership++| Existing Cindy consumer | Shared behavior | Behavior that remains with the consumer |+| --- | --- | --- |+| Codex Responses proxy | Request-owned custom/function and namespace conversion; tool discovery; reverse JSON/SSE conversion; provider parameters and schemas; existing history/input repairs | Effective route resolution, OAuth, model rewriting, Guardian restrictions, server tool injection, recovery lifecycle |+| Codex Responses → Chat bridge | Existing Code Mode schema/context, upstream provider capabilities, final Chat parameter normalization | Responses/Chat protocol translation and stream transport |+| Codex Responses → Anthropic bridge | Existing bridge and shared proxy repairs remain in place | Anthropic serializer, auth and response translation |+| Claude Code Messages proxy | Existing empty thinking/text, duplicate tool IDs, tool-result adjacency, provider-field and image-history repairs now live here | Session routing and recovery decision wiring |+| Claude Code Messages → Responses bridge | Shared strict-schema predicate; final provider normalization (including xAI subscription schema) | Messages/Responses translation; no Codex custom/namespace conversion |+| Pi native SDK and native subscription forwarding | Existing shared proxy repairs continue through their existing callers | Pi SDK's native serializers, native forwarding and tool contract; no new Codex dialect adapter |+| Mobile / remote UI | Uses the selected Desktop execution path | No second model transport is introduced on the UI client |++`harness`, `protocol`, `upstreamBase`, and the **actual wire model ID** describe a request, not a+new user setting. Merely setting `harness: 'pi'` in a pure helper test does not mean the Pi host+calls that helper. Pi's existing native forwarding tests exercise its actual entry points.++Namespace support and custom-tool support are independent. Codex conversion is selected using+Cindy's existing `supportsResponsesCustomTools` route capability. Namespace lowering additionally+requires a known target endpoint or Cindy's explicit XD model dialect. A model named `xai/...`+on an unrelated custom gateway does not opt that gateway into xAI normalization.++## Consolidated implementation++| Previous location | Single implementation owner |+| --- | --- |+| `anthropic-compat-proxy/src/transform.ts` | `src/cindy/proxy/transform.ts` |+| Proxy headers / thread-strip controller / vLLM / xAI ModelInput | `src/cindy/proxy/` |+| `responses-chat-bridge` custom adapter / tool context / null-array repair / shared types | `src/cindy/` |+| `anthropic-responses-bridge/src/strict-schema.ts` | `src/cindy/strict-schema.ts` |+| Codex host xAI tool sanitizer and tool-choice reconciliation | `src/providers/xai.ts` |+| Codex host Seed tool/input/reasoning corrections | `src/providers/seed.ts` |+| Codex host strict gateway tool history | `src/providers/history.ts` |+| Codex host DeepSeek legacy custom-tool fallback | `src/providers/deepseek.ts` |+| Codex host MiniMax Responses reasoning correction | `src/providers/minimax.ts` |++The remote SSH companion build tracks this package as a source dependency, so a compatibility-only+sync invalidates its cached bundle. Its single-file artifact embeds the OpenCodex MIT notice.++Old module paths are explicit re-export facades for existing consumers and tests, not independent+implementations. Protocol bridges remain bridges; they are not replaced with OpenCodex's server,+configuration files, or account manager. Cindy's collision-safe `exec` conversion is retained ahead+of upstream's generic conversion, with reverse transforms applied in reverse order.++## Imported provider policy++`src/upstream-profiles.json` contains compatibility declarations extracted statically from all+92 entries in the pinned upstream registry. No upstream registry code or credential code is+executed. Matching requires exact URL origin and path boundaries. Equal endpoint identities that+cannot be distinguished are left unresolved, rather than choosing an account/provider by name.+Unclassified gateways retain Cindy's existing route-specific rules; they do not inherit every+patch for models with a familiar name.++Active mappings include unsupported sampling fields; Chat reasoning wire mappings/budget/toggle;+reasoning replay/placeholder and automatic-tool-choice capabilities; Moonshot function schemas;+Responses verbosity/reasoning policy; DeepSeek adjacency, empty result annotation, search history+query fields and item IDs; xAI Responses web-search fields and subscription-only function schemas;+OpenCode Go additional-tool declarations; and Codex custom/namespace/tool-search round trips.++The imported declarations also retain upstream transport metadata (`modelWireDefaults`,+`responsesPath`, `googleMode`, `authKind`) and policies owned by OpenCodex's transport+(`modelResponsesTerminalRepair`, `openaiChatEofTolerance`, `promptCacheKey`,+`escapeBuiltinToolNames`). They are **not automatically activated** in Cindy. In particular:++- `modelWireDefaults` does not change Cindy's selected wire protocol or model catalog.+- Native Pi Gemini/Anthropic SDKs are not replaced with another serializer.+- The upstream Gemini sanitizer, snapshot repair, field-backfill and undeclared-tool guard are+ available source modules; importing them alone does not enable them for every transport.+- OpenCodex's Cursor/Kiro/CodeBuddy/Qoder execution backends require their own authentication and+ executors. They are not generic provider patches and this package does not enable those accounts.+- A stateless Responses request with an unexpanded `previous_response_id` is rejected explicitly.+ This package does not discard the reference and pretend its missing history was reconstructed.++These boundaries must remain visible when reporting coverage. “92 declarations imported” does+not mean 92 live providers or all OpenCodex execution backends were tested or newly enabled.++## Search semantics and local delta++xAI `external_web_access: true` is removed while retaining a valid search declaration. An explicit+non-true value fails closed: remove that search declaration and reconcile dependent selectors and+empty-tool controls. Cindy's existing server-search injection checks the original prohibition+before normalization; moving normalization ahead of that check would silently re-enable search.+Top-level tools and `input[].additional_tools` are both covered. `tool_search` is client tool+discovery and is handled independently of hosted `web_search`.++The local vendor patch also keeps Cindy's `index_gated_web_access` cleanup and restricts upstream+custom-tool traversal to protocol containers. Schemas, defaults, metadata and tool-result payloads+may contain objects shaped like tool declarations; those literal values must remain unchanged.+Other deltas remove unused runtime/configuration imports from the vendored dependency closure.++This migration does not establish the root cause of the installed Grok incident. That still needs+the exact packaged route and redacted final outbound request; existing first-party xAI cleanup+already existed before this work.++## Repeatable sync++From the repository root:++```sh+# Fast local integrity check.+node packages/model-compat/scripts/sync-upstream.mjs++# Reproduce modules, reviewed patch, original tests and provider data from the pinned source.+node packages/model-compat/scripts/sync-upstream.mjs --source /path/to/opencodex++# Update from an explicitly selected, clean checkout at a full commit SHA.+node packages/model-compat/scripts/sync-upstream.mjs --source /path/to/opencodex --update --commit FULL_40_CHARACTER_SHA+```++The updater checks current port hashes, prepares changes in a unique temporary directory, applies+`upstream.patch`, regenerates the selected helpers/tests and statically extracts provider policy+before writing tracked files. Unknown selected expressions, changed test dependencies and patch+conflicts fail with an explicit error. The updater does not fetch or run upstream code.++`upstream-inventory.json` inventories **all upstream source files**, including unimported adapters.+An update writes `UPSTREAM-CHANGES.json` with new, changed and deleted paths. Review this report as+well as the ported diff: a new upstream compatibility module outside the imported closure requires+an explicit port decision. Sync is a reviewed dependency update, not a promise that upstream can+change arbitrarily without integration work. Preserve upstream license notices on every update.++Run package conformance tests and all affected bridge/host tests, package typechecks and the+repository's `pnpm test:unit:related` gate before delivery. Original Bun tests are transpiled to+JavaScript with only their runner/import paths changed; their assertions are retained. Live-account+checks are separate and must be reported separately from deterministic request/stream tests.diff --git a/packages/model-compat/UPSTREAM.json b/packages/model-compat/UPSTREAM.jsonnew file mode 100644index 0000000000..1583e5ce5b--- /dev/null+++ b/packages/model-compat/UPSTREAM.json@@ -0,0 +1,364 @@+{+ "repository": "https://github.com/lidge-jun/opencodex",+ "commit": "c155cc7923dbc0102e27d79185505a85d4357b2c",+ "files": [+ {+ "source": "src/adapters/google-tool-schema.ts",+ "target": "src/upstream/adapters/google-tool-schema.ts",+ "upstreamSha256": "d5bcf65418bfade8a3d98a26c7ffc1b657f943eca0e44528e8817a9ef4f5e4ac",+ "portedSha256": "d5bcf65418bfade8a3d98a26c7ffc1b657f943eca0e44528e8817a9ef4f5e4ac"+ },+ {+ "source": "src/adapters/opencode-go-additional-tools.ts",+ "target": "src/upstream/adapters/opencode-go-additional-tools.ts",+ "upstreamSha256": "42090cb27e20503d3d6ad0680b1a45b918b19d878c2e6db6ed031ca57f17c1ee",+ "portedSha256": "42090cb27e20503d3d6ad0680b1a45b918b19d878c2e6db6ed031ca57f17c1ee"+ },+ {+ "source": "src/adapters/responses-tool-schema.ts",+ "target": "src/upstream/adapters/responses-tool-schema.ts",+ "upstreamSha256": "11bd2246eb174cf197af6885c96565407f1ab53b7782b9cd27020a65ac9b192d",+ "portedSha256": "11bd2246eb174cf197af6885c96565407f1ab53b7782b9cd27020a65ac9b192d"+ },+ {+ "source": "src/adapters/xai-schema-analysis.ts",+ "target": "src/upstream/adapters/xai-schema-analysis.ts",+ "upstreamSha256": "7bb784364955564052ca8b237782101a9e0478432c2ce231a5cdd0cd216fd157",+ "portedSha256": "7bb784364955564052ca8b237782101a9e0478432c2ce231a5cdd0cd216fd157"+ },+ {+ "source": "src/adapters/xai-tool-schema.ts",+ "target": "src/upstream/adapters/xai-tool-schema.ts",+ "upstreamSha256": "f178d9f9aa7d33fd98c2dd034d6c180773fc2f05abd6b86371a678d9fb16bf63",+ "portedSha256": "f178d9f9aa7d33fd98c2dd034d6c180773fc2f05abd6b86371a678d9fb16bf63"+ },+ {+ "source": "src/adapters/xai-web-search.ts",+ "target": "src/upstream/adapters/xai-web-search.ts",+ "upstreamSha256": "6bbf215df9072dd4842eb0dbea27ad8de0aa51669f23027e0c064e6597f0c383",+ "portedSha256": "433513174b8e82449cda71987f14684c3878cc01a23058288c7004e2e2b67a5e"+ },+ {+ "source": "src/lib/tool-argument-integers.ts",+ "target": "src/upstream/lib/tool-argument-integers.ts",+ "upstreamSha256": "0ed323ea85d13016cb88e048d20238b7d87fe2beae39406229d9f970f1402b2c",+ "portedSha256": "0ed323ea85d13016cb88e048d20238b7d87fe2beae39406229d9f970f1402b2c"+ },+ {+ "source": "src/lib/translator-budget.ts",+ "target": "src/upstream/lib/translator-budget.ts",+ "upstreamSha256": "4d79fed2d10e23b87af2c67ea0a979ce580eb232ac35e1f6851b5f02ef5a07d7",+ "portedSha256": "4d79fed2d10e23b87af2c67ea0a979ce580eb232ac35e1f6851b5f02ef5a07d7"+ },+ {+ "source": "src/providers/xai-transport.ts",+ "target": "src/upstream/providers/xai-transport.ts",+ "upstreamSha256": "1ac6638465ad2b2a36603ee36aa53176474f9c6ca3253db0a43933ed7b20371d",+ "portedSha256": "42bd85d56c44527b3b37611f8600fff1ff2d01258dca79b9af43a78229d0abdc"+ },+ {+ "source": "src/responses/apply-patch-envelope.ts",+ "target": "src/upstream/responses/apply-patch-envelope.ts",+ "upstreamSha256": "2145bd3995c8811c6f21510b606e32eea84809ea3d4a602ab252d1adc40f4fb9",+ "portedSha256": "2145bd3995c8811c6f21510b606e32eea84809ea3d4a602ab252d1adc40f4fb9"+ },+ {+ "source": "src/responses/code-mode-helper-compat.ts",+ "target": "src/upstream/responses/code-mode-helper-compat.ts",+ "upstreamSha256": "efa332720f717230c9feb1ef5132f0f658af21604044649ceff4577299f59f8b",+ "portedSha256": "efa332720f717230c9feb1ef5132f0f658af21604044649ceff4577299f59f8b"+ },+ {+ "source": "src/responses/compaction.ts",+ "target": "src/upstream/responses/compaction.ts",+ "upstreamSha256": "8ca98f68e5e6957e32762b9f6d006d53083bece1b086988560a719b701e7a867",+ "portedSha256": "c7885a830cf5bf7f92c541904cac839efb8903185814a79e4362fa9cbd142394"+ },+ {+ "source": "src/responses/custom-tool-compat.ts",+ "target": "src/upstream/responses/custom-tool-compat.ts",+ "upstreamSha256": "1545dee0ee7f29d0c489dc4bf3975984fd9648dbca5de50effc97f7df9adc024",+ "portedSha256": "d223fcb889bf3e529dcc4b7535edd0605f7068c37af5ae0a78482bfe65940500"+ },+ {+ "source": "src/responses/function-call-compat.ts",+ "target": "src/upstream/responses/function-call-compat.ts",+ "upstreamSha256": "642c72c2d9aeaad9c6840059eaab33e3729733447ac746197ad122e3c18b779b",+ "portedSha256": "642c72c2d9aeaad9c6840059eaab33e3729733447ac746197ad122e3c18b779b"+ },+ {+ "source": "src/responses/namespace-tool-compat.ts",+ "target": "src/upstream/responses/namespace-tool-compat.ts",+ "upstreamSha256": "29ab7614e0757cde8bf81ad86da407afc8cb6d05027da22375fcca9a95de63b0",+ "portedSha256": "29ab7614e0757cde8bf81ad86da407afc8cb6d05027da22375fcca9a95de63b0"+ },+ {+ "source": "src/responses/tool-groups.ts",+ "target": "src/upstream/responses/tool-groups.ts",+ "upstreamSha256": "b2750b33ec7bb5a7f76f27584bf99372fac4f253dd287849b2f3f9821db574cd",+ "portedSha256": "b2750b33ec7bb5a7f76f27584bf99372fac4f253dd287849b2f3f9821db574cd"+ },+ {+ "source": "src/responses/tool-name-aliases.ts",+ "target": "src/upstream/responses/tool-name-aliases.ts",+ "upstreamSha256": "19338602099c6ea9947200310bddd36b1f86ee93f5d5def2019182d0e71255bd",+ "portedSha256": "19338602099c6ea9947200310bddd36b1f86ee93f5d5def2019182d0e71255bd"+ },+ {+ "source": "src/responses/tool-search-compat.ts",+ "target": "src/upstream/responses/tool-search-compat.ts",+ "upstreamSha256": "25ddbc4dd8f04ce43804aab64fdf5dcc402703529b8252d2c64bbb5749ece4a6",+ "portedSha256": "25ddbc4dd8f04ce43804aab64fdf5dcc402703529b8252d2c64bbb5749ece4a6"+ },+ {+ "source": "src/server/relay.ts",+ "target": "src/upstream/server/relay.ts",+ "upstreamSha256": "0fd1843a6cfef03ac35ce43976b89a22a70bd9631bfb327d8605414d2f78c223",+ "portedSha256": "d68f0a2a04f57ccbe744ee1d01865e11cb19d465c391c4290600f4789755b607"+ },+ {+ "source": "src/server/responses-custom-tool-repair.ts",+ "target": "src/upstream/server/responses-custom-tool-repair.ts",+ "upstreamSha256": "9b29bc429d83cd5ab46b358eed46356514b88f9508716afa8080b93dca848f84",+ "portedSha256": "9b29bc429d83cd5ab46b358eed46356514b88f9508716afa8080b93dca848f84"+ },+ {+ "source": "src/server/responses-function-tool-repair.ts",+ "target": "src/upstream/server/responses-function-tool-repair.ts",+ "upstreamSha256": "e32fc0a7669cc6c085c3a6287f3382bfc12223dc78ff96cea90927fc3bbaa0a6",+ "portedSha256": "e32fc0a7669cc6c085c3a6287f3382bfc12223dc78ff96cea90927fc3bbaa0a6"+ },+ {+ "source": "src/server/responses-item-id-repair.ts",+ "target": "src/upstream/server/responses-item-id-repair.ts",+ "upstreamSha256": "02341fe16358093c2b57f816a5ae583d49f3b48c486cba8e9066175fe7678e39",+ "portedSha256": "02341fe16358093c2b57f816a5ae583d49f3b48c486cba8e9066175fe7678e39"+ },+ {+ "source": "src/server/responses-model-rewrite.ts",+ "target": "src/upstream/server/responses-model-rewrite.ts",+ "upstreamSha256": "78ccff83ff54f7687d1f5ed04e326a17a9a37187ec470947ee960f4266a34a4f",+ "portedSha256": "78ccff83ff54f7687d1f5ed04e326a17a9a37187ec470947ee960f4266a34a4f"+ },+ {+ "source": "src/server/responses-reasoning-summary-rewrite.ts",+ "target": "src/upstream/server/responses-reasoning-summary-rewrite.ts",+ "upstreamSha256": "9a49932cb6bac6402f8e57f3188bdb86e3671f6fe55d1711fb84b9ad81b1d487",+ "portedSha256": "9a49932cb6bac6402f8e57f3188bdb86e3671f6fe55d1711fb84b9ad81b1d487"+ },+ {+ "source": "src/server/responses-self-named-namespace-scrub.ts",+ "target": "src/upstream/server/responses-self-named-namespace-scrub.ts",+ "upstreamSha256": "fe4a833cbc6ba27664fb7f4892a9ac6982b1dc3c84d5a950f08955dbbdd7560a",+ "portedSha256": "fe4a833cbc6ba27664fb7f4892a9ac6982b1dc3c84d5a950f08955dbbdd7560a"+ },+ {+ "source": "src/server/responses-snapshot-codec.ts",+ "target": "src/upstream/server/responses-snapshot-codec.ts",+ "upstreamSha256": "37bd6288b65d0bfe1cba21d9608412ab64ab8c4e6a386e94e340497eba5ede8d",+ "portedSha256": "37bd6288b65d0bfe1cba21d9608412ab64ab8c4e6a386e94e340497eba5ede8d"+ },+ {+ "source": "src/server/responses-snapshot-repair.ts",+ "target": "src/upstream/server/responses-snapshot-repair.ts",+ "upstreamSha256": "082997b9c23a1238aee5ad341d7e083cf86ea3c8d62126c035e4c0c63bacc55b",+ "portedSha256": "082997b9c23a1238aee5ad341d7e083cf86ea3c8d62126c035e4c0c63bacc55b"+ },+ {+ "source": "src/server/responses-tool-search-repair.ts",+ "target": "src/upstream/server/responses-tool-search-repair.ts",+ "upstreamSha256": "7462d6b58dc03d2b520774b99fc2c8103a20e55ab758eef19831df906bdde86d",+ "portedSha256": "7462d6b58dc03d2b520774b99fc2c8103a20e55ab758eef19831df906bdde86d"+ },+ {+ "source": "src/server/responses-undeclared-tool-guard.ts",+ "target": "src/upstream/server/responses-undeclared-tool-guard.ts",+ "upstreamSha256": "8570d91b8a5a2a4b636de2af8b75855d59fd28905783fad24da6fb2d43303ace",+ "portedSha256": "8570d91b8a5a2a4b636de2af8b75855d59fd28905783fad24da6fb2d43303ace"+ },+ {+ "source": "src/server/responses/responses-field-backfill.ts",+ "target": "src/upstream/server/responses/responses-field-backfill.ts",+ "upstreamSha256": "4374724d6a107d3f1766efcd964459c4c749cf767370ab4b35c5130357d8f35f",+ "portedSha256": "4374724d6a107d3f1766efcd964459c4c749cf767370ab4b35c5130357d8f35f"+ },+ {+ "source": "src/server/sse-payload-rewrite.ts",+ "target": "src/upstream/server/sse-payload-rewrite.ts",+ "upstreamSha256": "c1f631a601557f630d27caa95a9676e95c2aec509b4a76c7022bef8d7e878600",+ "portedSha256": "c1f631a601557f630d27caa95a9676e95c2aec509b4a76c7022bef8d7e878600"+ },+ {+ "source": "src/types.ts",+ "target": "src/upstream/types.ts",+ "upstreamSha256": "4a8c13fbedde0ec6b3e0e1fab7980f561c7b710cfbd4e96c026b94cbe5530d6f",+ "portedSha256": "b4fdb1a57cb928e0b7e9403d7cae357e4859826a347fb812129e0f0b69f436eb"+ },+ {+ "source": "src/types/provider.ts",+ "target": "src/upstream/types/provider.ts",+ "upstreamSha256": "b97e8bd5f3f82dae9cb246cc71772f61a6c5eb9644f2204da16e25ce7b0c19fb",+ "portedSha256": "b97e8bd5f3f82dae9cb246cc71772f61a6c5eb9644f2204da16e25ce7b0c19fb"+ },+ {+ "source": "src/types/tools.ts",+ "target": "src/upstream/types/tools.ts",+ "upstreamSha256": "0e2cbb7bf64aad984d6a453dda2428cda2aa994935d20968bc39817b675effb6",+ "portedSha256": "0e2cbb7bf64aad984d6a453dda2428cda2aa994935d20968bc39817b675effb6"+ },+ {+ "source": "src/types/wire.ts",+ "target": "src/upstream/types/wire.ts",+ "upstreamSha256": "ce5d1a7fabef76c800b469bea4a08db0e45259e54e19b60b7b00fbfb85d28973",+ "portedSha256": "ce5d1a7fabef76c800b469bea4a08db0e45259e54e19b60b7b00fbfb85d28973"+ },+ {+ "source": "src/adapters/cursor/mcp-config.ts",+ "target": "src/upstream/adapters/cursor/mcp-config.ts",+ "upstreamSha256": "3ef083c37f6488881bf7da3ca8c0b6bb6a4ccb71d26231a07fd039c023df6468",+ "portedSha256": "3ef083c37f6488881bf7da3ca8c0b6bb6a4ccb71d26231a07fd039c023df6468"+ },+ {+ "source": "src/adapters/cursor/desktop-executor-contract.ts",+ "target": "src/upstream/adapters/cursor/desktop-executor-contract.ts",+ "upstreamSha256": "c12754b08175a21439047a2c39e2cb277da732e536b44b532d81e1d7445042d6",+ "portedSha256": "c12754b08175a21439047a2c39e2cb277da732e536b44b532d81e1d7445042d6"+ },+ {+ "source": "src/adapters/openai-chat.ts",+ "target": "src/upstream/adapters/openai-chat.ts",+ "upstreamSha256": "ff1f2275e2f45e769a5f4e2e6e79445fec56950c86006f2a98fd7bd8e6bfc016",+ "portedSha256": "135a2b6febd8ec4993d897bd7e488a1b0ab55d12caf186f93ca17bf85e801f74",+ "extractSymbols": [+ "stripBracketedModelSuffix",+ "reasoningDetailSegmentForWire",+ "thinkingBudgetForEffort",+ "MOONSHOT_SCHEMA_HOSTNAMES",+ "isMoonshotSchemaTarget",+ "ensureRootObjectType",+ "isXaiObjectSchema",+ "moonshotRefTargetKeys",+ "MOONSHOT_MAX_REF_EXPANSIONS",+ "MOONSHOT_MAX_SCHEMA_DEPTH",+ "MOONSHOT_MAX_SCHEMA_NODES",+ "unionRequired",+ "MOONSHOT_DATA_VALUED_KEYWORDS",+ "MOONSHOT_BOUND_KEYWORDS",+ "intersectBound",+ "composeProperties",+ "MoonshotNormalizeState",+ "normalizeMoonshotSchemaNode",+ "normalizeMoonshotToolParameters"+ ],+ "extractionPrefix": "// Pure parameter/schema helpers extracted from the upstream Chat adapter.\nimport type { OcxProviderConfig } from \"../types\";\nimport { lookupLocalJsonPointer } from \"./xai-schema-analysis\";\ninterface OcxParsedRequest { options: { reasoning?: string } }\n"+ },+ {+ "source": "src/adapters/openai-responses.ts",+ "target": "src/upstream/adapters/openai-responses.ts",+ "upstreamSha256": "5eef85b5c6a109bc14bc324dca15bc1f9292445614673d331850ffeac80187e7",+ "portedSha256": "eb53ffd4657890f9bb660d88497b3db95d9a40203306abf4139307292039a37a",+ "extractSymbols": [+ "isPlainObject",+ "CANONICAL_ONLY_TOOL_FIELDS",+ "stripCanonicalOnlyToolFields",+ "backfillWebSearchQueries",+ "normalizeResponsesToolResultAdjacency",+ "isToolOutputEmpty",+ "annotateEmptyResponsesToolOutputs"+ ],+ "extractionPrefix": "// Pure protocol helpers extracted verbatim from the pinned upstream adapter.\nimport { EMPTY_TOOL_OUTPUT_ANNOTATION, isWhitespaceOnlyTextPartArray } from \"./empty-tool-output-annotation\";\n"+ },+ {+ "source": "src/adapters/empty-tool-output-annotation.ts",+ "target": "src/upstream/adapters/empty-tool-output-annotation.ts",+ "upstreamSha256": "cd00654218db3a30c451608f953256148fa288020e6afb6e4275280b1dcfec8d",+ "portedSha256": "cd00654218db3a30c451608f953256148fa288020e6afb6e4275280b1dcfec8d"+ },+ {+ "source": "src/reasoning-effort.ts",+ "target": "src/upstream/reasoning-effort.ts",+ "upstreamSha256": "9eb83f657f48c2582dd6846d3ba1e3f584197025c779bbece5953d552fac1322",+ "portedSha256": "9eb83f657f48c2582dd6846d3ba1e3f584197025c779bbece5953d552fac1322"+ }+ ],+ "tests": [+ {+ "source": "tests/responses/responses-field-backfill.test.ts",+ "target": "src/__tests__/upstream/responses/responses-field-backfill.test.js",+ "upstreamSha256": "6bff97867410eacf2a7d0dc5e568db1308a0e2b642e8dd092815c196008920a9",+ "portedSha256": "d2c942eb202a890909ba08aceda5a15bb4e0eb7fcb5ec977c922d072bf5713d6",+ "adaptation": "Bun test imports to Vitest; TypeScript transpile to ES2022 (assertions unchanged)"+ },+ {+ "source": "tests/responses/apply-patch-envelope.test.ts",+ "target": "src/__tests__/upstream/responses/apply-patch-envelope.test.js",+ "upstreamSha256": "4ab7f200595ad525bb3ce8e140f6fc5d5565f63d1b780f6b21d878edeea67adb",+ "portedSha256": "f3f36ccd5b54772a55273d829b5988ffca25d4fa8009608c7db70161a47040ec",+ "adaptation": "Bun test imports to Vitest; TypeScript transpile to ES2022 (assertions unchanged)"+ },+ {+ "source": "tests/responses/custom-tool-compat.test.ts",+ "target": "src/__tests__/upstream/responses/custom-tool-compat.test.js",+ "upstreamSha256": "7da2732da9dd886646bca288d065034903455842cbb8d06e63c3732520b55bad",+ "portedSha256": "892b9c804f98bcf0683c6296d9d52731382315856a5ea315afbb0a57c7e621bb",+ "adaptation": "Bun test imports to Vitest; TypeScript transpile to ES2022 (assertions unchanged)"+ },+ {+ "source": "tests/responses/legacy-shell-compat.test.ts",+ "target": "src/__tests__/upstream/responses/legacy-shell-compat.test.js",+ "upstreamSha256": "76c49010d3b1f7afc9bfe9411d3fdebcbc4af777b1de2ea0f24f06700c65ebf3",+ "portedSha256": "e7e06a465f953bb6b252a764bde8013a7d75c997d8b31f189cba2d1fe2f52540",+ "adaptation": "Bun test imports to Vitest; TypeScript transpile to ES2022 (assertions unchanged)"+ },+ {+ "source": "tests/responses/namespace-tool-compat.test.ts",+ "target": "src/__tests__/upstream/responses/namespace-tool-compat.test.js",+ "upstreamSha256": "3ab46d5c76aade93ea82758e68d732bcc4eb53ac4ff8307fb48cdaad4750573e",+ "portedSha256": "6c92dfa1dbcfe24f2eddd4415e1dc718e45c6563ad7788dda6265874e12bb0a6",+ "adaptation": "Bun test imports to Vitest; TypeScript transpile to ES2022 (assertions unchanged)"+ },+ {+ "source": "tests/responses/responses-tool-groups.test.ts",+ "target": "src/__tests__/upstream/responses/responses-tool-groups.test.js",+ "upstreamSha256": "8949508d064b9d5551a01cedcfd078e967fbb369f81dde882f52f87f50929886",+ "portedSha256": "f996e06157774ed8baba4264ecfd2b589acf1297af21f624dab12995ccc20b4c",+ "adaptation": "Bun test imports to Vitest; TypeScript transpile to ES2022 (assertions unchanged)"+ },+ {+ "source": "tests/responses/responses-reasoning-summary-rewrite.test.ts",+ "target": "src/__tests__/upstream/responses/responses-reasoning-summary-rewrite.test.js",+ "upstreamSha256": "fb0d897a70fed41c868f7f51157b7c1a2499c5d9ebd610f65244f96a2b3be844",+ "portedSha256": "851988f1aa51e8fbf06f071921ad3d2e8e080e0ec3fd3f057cd2ae5558dff1d8",+ "adaptation": "Bun test imports to Vitest; TypeScript transpile to ES2022 (assertions unchanged)"+ },+ {+ "source": "tests/adapters/tool-choice-performance.test.ts",+ "target": "src/__tests__/upstream/adapters/tool-choice-performance.test.js",+ "upstreamSha256": "c19976b506437710480bbeac937306e27dcabe1a6f46811861d6e110e92b172b",+ "portedSha256": "f22b8de57b7b95007e004b1be31b38e7d61df745fdfa7338141287a218f6e5b9",+ "adaptation": "Bun test imports to Vitest; TypeScript transpile to ES2022 (assertions unchanged)"+ },+ {+ "source": "tests/adapters/google/google-tool-schema.test.ts",+ "target": "src/__tests__/upstream/adapters/google/google-tool-schema.test.js",+ "upstreamSha256": "2e612eb8699927b78179bc03a90dc0849b538197b1ed2e7420e977df1cc9ad03",+ "portedSha256": "ac4b92612101975f32c5eec81646396dffff69c0d7a19ee617c38f6ce9e15498",+ "adaptation": "Bun test imports to Vitest; TypeScript transpile to ES2022 (assertions unchanged)"+ }+ ],+ "registrySources": [+ {+ "source": "src/providers/registry.ts",+ "sha256": "eaa03f044258d51d5d49c741ff73bde6bc582f20e6740b918ed64c958938a063"+ },+ {+ "source": "src/providers/kiro-models.ts",+ "sha256": "81a323255ab20e27b1040178b01b9cf567d0411b4171107bd47cc9a7ba46be4d"+ },+ {+ "source": "src/providers/base-url-choices.ts",+ "sha256": "f75c050dd851d38fd90335def782699aea43f89930dfff95060fa88d9724a9a6"+ }+ ],+ "profilesSha256": "9b7aa8a6f83d8da85b178a871673649f37fccd11c04d78e514abd028b221c81d"+}diff --git a/packages/model-compat/eslint.config.mjs b/packages/model-compat/eslint.config.mjsnew file mode 100644index 0000000000..2ac12a2072--- /dev/null+++ b/packages/model-compat/eslint.config.mjs@@ -0,0 +1,10 @@+import js from '@eslint/js';+import tseslint from 'typescript-eslint';++export default tseslint.config(+ // Keep vendored source and transpiled upstream assertions reproducible. Their integrity,+ // typechecking and behavioral tests run independently of Cindy's source style rules.+ { ignores: ['dist/', 'src/upstream/**', 'src/__tests__/upstream/**'] },+ js.configs.recommended,+ ...tseslint.configs.recommended,+);diff --git a/packages/model-compat/package.json b/packages/model-compat/package.jsonnew file mode 100644index 0000000000..8063694247--- /dev/null+++ b/packages/model-compat/package.json@@ -0,0 +1,27 @@+{+ "name": "@cindy/model-compat",+ "version": "0.0.0",+ "private": true,+ "description": "Provider protocol compatibility with pinned OpenCodex modules and Cindy route policies.",+ "type": "module",+ "main": "./src/index.ts",+ "types": "./src/index.ts",+ "exports": {+ ".": "./src/index.ts"+ },+ "scripts": {+ "build": "tsc --noEmit",+ "typecheck": "tsc --noEmit",+ "test": "vitest run",+ "lint": "eslint src/"+ },+ "license": "Apache-2.0",+ "devDependencies": {+ "@eslint/js": "^9.0.0",+ "@types/node": "*",+ "eslint": "^9.0.0",+ "typescript": "^5.7.0",+ "typescript-eslint": "^8.0.0",+ "vitest": "^3.2.4"+ }+}diff --git a/packages/model-compat/scripts/provider-profiles.mjs b/packages/model-compat/scripts/provider-profiles.mjsnew file mode 100644index 0000000000..286de2c8cf--- /dev/null+++ b/packages/model-compat/scripts/provider-profiles.mjs@@ -0,0 +1,170 @@+/** Static extraction only. Never imports or executes an upstream registry or credential module. */+import fs from 'node:fs';+import path from 'node:path';+import ts from 'typescript';+import { createHash } from 'node:crypto';++export const COMPATIBILITY_FIELDS = new Set([+ 'omitReasoningEffortWithToolsModels',+ 'id', 'adapter', 'baseUrl', 'authKind', 'supportsOpenAiWebSearchToolFields',+ 'supportsResponsesCustomTools', 'parallelToolCalls', 'modelSupportsVerbosity',+ 'supportsVerbosity', 'modelWireDefaults', 'noReasoningModels', 'preserveReasoningContentModels',+ 'modelReasoningEffortMap', 'modelSuffixBracketStrip', 'promptCacheKey', 'noTemperatureModels',+ 'noTopPModels', 'noPenaltyModels', 'autoToolChoiceOnlyModels', 'escapeBuiltinToolNames',+ 'openaiChatEofTolerance', 'statelessResponses', 'modelSupportsReasoningSummaries',+ 'thinkingToggleModels', 'thinkingBudgetModels', 'reasoningWireFormat', 'googleMode',+ 'modelResponsesTerminalRepair', 'responsesItemIdRepair', 'responsesPath',+ 'preserveResponsesReasoningContent', 'requiresAdjacentResponsesToolResults',+ 'annotateEmptyToolOutputs', 'requiresReasoningPlaceholderModels', 'directReasoningEffortModels',+ 'reasoningSplitModels', 'reasoningDetailsModels', 'reasoningEffortMap',+]);++export function extractProviderProfiles(root) {+ const parsed = new Map();+ const parse = relative => {+ if (!parsed.has(relative)) {+ const text = fs.readFileSync(path.join(root, relative), 'utf8');+ parsed.set(relative, ts.createSourceFile(relative, text, ts.ScriptTarget.Latest, true));+ }+ return parsed.get(relative);+ };+ const variables = sf => new Map(sf.statements.filter(ts.isVariableStatement)+ .flatMap(statement => [...statement.declarationList.declarations])+ .filter(declaration => ts.isIdentifier(declaration.name))+ .map(declaration => [declaration.name.text, declaration.initializer]));+ const unwrap = node => {+ while (node && (ts.isAsExpression(node) || ts.isSatisfiesExpression(node) || ts.isParenthesizedExpression(node))) node = node.expression;+ return node;+ };+ const scopes = [new Map()];+ const known = value => !(value && typeof value === 'object' && 'expression' in value);+ const resolve = (node, sf, seen = new Set()) => {+ node = unwrap(node);+ if (!node) return null;+ if (ts.isStringLiteralLike(node)) return node.text;+ if (ts.isNumericLiteral(node)) return Number(node.text);+ if (node.kind === ts.SyntaxKind.TrueKeyword) return true;+ if (node.kind === ts.SyntaxKind.FalseKeyword) return false;+ if (node.kind === ts.SyntaxKind.NullKeyword) return null;+ if (ts.isArrayLiteralExpression(node)) return node.elements.flatMap(element => {+ const spread = ts.isSpreadElement(element);+ const value = resolve(spread ? element.expression : element, sf, new Set(seen));+ return spread && Array.isArray(value) ? value : [value];+ });+ if (ts.isObjectLiteralExpression(node)) {+ const object = {};+ for (const property of node.properties) {+ if (ts.isPropertyAssignment(property)) {+ const key = ts.isComputedPropertyName(property.name)+ ? resolve(property.name.expression, sf, new Set(seen))+ : property.name.getText(sf).replace(/^['"]|['"]$/g, '');+ object[key] = resolve(property.initializer, sf, new Set(seen));+ } else if (ts.isSpreadAssignment(property)) {+ const value = resolve(property.expression, sf, new Set(seen));+ if (value && typeof value === 'object' && !value.expression) Object.assign(object, value);+ else object['...' + property.expression.getText(sf)] = value;+ }+ }+ return object;+ }+ if (ts.isTemplateExpression(node)) {+ let text = node.head.text;+ for (const span of node.templateSpans) {+ const value = resolve(span.expression, sf, new Set(seen));+ if (!known(value)) throw new Error('Unresolved template in compatibility registry');+ text += String(value) + span.literal.text;+ }+ return text;+ }+ if (ts.isArrowFunction(node) && !ts.isBlock(node.body)) {+ const captured = new Map(scopes.at(-1));+ return (...args) => {+ const scope = new Map(captured);+ node.parameters.forEach((parameter, index) => scope.set(parameter.name.getText(sf), args[index]));+ scopes.push(scope);+ try { return resolve(node.body, sf); } finally { scopes.pop(); }+ };+ }+ if (ts.isConditionalExpression(node)) {+ const condition = resolve(node.condition, sf, new Set(seen));+ if (known(condition)) return resolve(condition ? node.whenTrue : node.whenFalse, sf, new Set(seen));+ }+ if (ts.isBinaryExpression(node)) {+ const left = resolve(node.left, sf, new Set(seen));+ const right = resolve(node.right, sf, new Set(seen));+ if (known(left) && known(right)) {+ if (node.operatorToken.kind === ts.SyntaxKind.EqualsEqualsEqualsToken) return left === right;+ if (node.operatorToken.kind === ts.SyntaxKind.ExclamationEqualsEqualsToken) return left !== right;+ if (node.operatorToken.kind === ts.SyntaxKind.PlusToken) return left + right;+ if (node.operatorToken.kind === ts.SyntaxKind.BarBarToken) return left || right;+ if (node.operatorToken.kind === ts.SyntaxKind.AmpersandAmpersandToken) return left && right;+ }+ }+ if (ts.isCallExpression(node)) {+ const args = node.arguments.map(argument => resolve(argument, sf, new Set(seen)));+ if (ts.isPropertyAccessExpression(node.expression)) {+ const owner = node.expression.expression;+ const method = node.expression.name.text;+ if (owner.getText(sf) === 'Object' && method === 'fromEntries' && Array.isArray(args[0])) return Object.fromEntries(args[0]);+ const receiver = resolve(owner, sf, new Set(seen));+ if (Array.isArray(receiver) && ['map', 'filter'].includes(method) && typeof args[0] === 'function') return receiver[method](args[0]);+ if ((Array.isArray(receiver) || typeof receiver === 'string') && method === 'includes') return receiver.includes(args[0]);+ if (typeof receiver === 'string' && ['toLowerCase', 'toUpperCase', 'startsWith', 'endsWith'].includes(method)) return receiver[method](...args);+ } else {+ const callable = resolve(node.expression, sf, new Set(seen));+ if (typeof callable === 'function') return callable(...args);+ }+ }+ if (ts.isIdentifier(node)) {+ if (scopes.at(-1).has(node.text)) return scopes.at(-1).get(node.text);+ const key = sf.fileName + ':' + node.text;+ if (!seen.has(key)) {+ seen.add(key);+ const local = variables(sf).get(node.text);+ if (local) return resolve(local, sf, seen);+ for (const declaration of sf.statements) {+ if (!ts.isImportDeclaration(declaration)) continue;+ const bindings = declaration.importClause?.namedBindings;+ if (!bindings || !ts.isNamedImports(bindings)) continue;+ const binding = bindings.elements.find(element => element.name.text === node.text);+ const spec = declaration.moduleSpecifier.text;+ if (!binding || !spec.startsWith('.')) continue;+ const base = path.posix.normalize(path.posix.join(path.posix.dirname(sf.fileName), spec));+ const relative = [base, base + '.ts', base + '/index.ts'].find(candidate => candidate.endsWith('.ts') && fs.existsSync(path.join(root, candidate)));+ if (relative) {+ const imported = parse(relative);+ const value = variables(imported).get(binding.propertyName?.text ?? binding.name.text);+ if (value) return resolve(value, imported, seen);+ }+ }+ }+ }+ return { expression: node.getText(sf), source: sf.fileName, line: sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1 };+ };+ const registry = parse('src/providers/registry.ts');+ const declaration = unwrap(variables(registry).get('PROVIDER_REGISTRY'));+ if (!declaration || !ts.isArrayLiteralExpression(declaration)) throw new Error('Upstream registry shape changed; review extractor.');+ const profiles = declaration.elements.map(element => {+ // Resolve selected properties only, avoiding unrelated account, pricing, and model catalog data.+ const object = unwrap(element);+ if (!ts.isObjectLiteralExpression(object)) throw new Error('Upstream provider declaration shape changed.');+ const result = {};+ for (const property of object.properties) {+ if (!ts.isPropertyAssignment(property)) throw new Error('Upstream provider spread needs review.');+ const key = property.name.getText(registry).replace(/^['"]|['"]$/g, '');+ if (COMPATIBILITY_FIELDS.has(key)) result[key] = resolve(property.initializer, registry);+ }+ if (typeof result.id !== 'string' || typeof result.baseUrl !== 'string') throw new Error('Unresolved provider identity.');+ return result;+ });+ const assertResolved = value => {+ if (!value || typeof value !== 'object') return;+ if (typeof value.expression === 'string' && typeof value.source === 'string') {+ throw new Error(`Unresolved compatibility expression at ${value.source}:${value.line}: ${value.expression}`);+ }+ for (const child of Object.values(value)) assertResolved(child);+ };+ assertResolved(profiles);+ const sources = [...parsed].map(([source, sf]) => ({ source, sha256: createHash('sha256').update(sf.text).digest('hex') }));+ return { profiles, sources };+}diff --git a/packages/model-compat/scripts/sync-upstream.mjs b/packages/model-compat/scripts/sync-upstream.mjsnew file mode 100644index 0000000000..266d59fcce--- /dev/null+++ b/packages/model-compat/scripts/sync-upstream.mjs@@ -0,0 +1,122 @@+#!/usr/bin/env node+/** Reproduce a reviewed OpenCodex port without executing any upstream code.+ * Usage: node scripts/sync-upstream.mjs --source /checkout [--update --commit <full-sha>]+ * Default verifies both the local port and pinned source. Updates apply the reviewed patch+ * in an isolated temporary directory before writing any tracked target.+ */+import fs from 'node:fs/promises';+import path from 'node:path';+import os from 'node:os';+import { fileURLToPath } from 'node:url';+import { createHash } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import ts from 'typescript';+import { inventoryUpstream, inventoryDelta } from './upstream-inventory.mjs';+import { extractProviderProfiles } from './provider-profiles.mjs';++const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const args = process.argv.slice(2);+const value = flag => { const index = args.indexOf(flag); return index < 0 ? undefined : args[index + 1]; };+const source = value('--source');+const update = args.includes('--update');+const commit = value('--commit');+const hash = bytes => createHash('sha256').update(bytes).digest('hex');+const manifest = JSON.parse(await fs.readFile(path.join(root, 'UPSTREAM.json'), 'utf8'));+const files = [...manifest.files, ...manifest.tests];+if (hash(await fs.readFile(path.join(root, 'src/upstream-profiles.json'))) !== manifest.profilesSha256) throw new Error('Local provider profile data changed; regenerate/review before syncing.');+for (const entry of files) {+ const bytes = await fs.readFile(path.join(root, entry.target));+ if (hash(bytes) !== entry.portedSha256) throw new Error(`Local port changed: ${entry.target}; record/review the patch before syncing.`);+}+if (!source) {+ if (update) throw new Error('--update requires --source and --commit');+ console.log(`Verified ${files.length} ported files at ${manifest.commit}.`);+ process.exit(0);+}+const sourceRoot = await fs.realpath(source);+if (update) {+ if (!/^[a-f0-9]{40}$/.test(commit ?? '')) throw new Error('Update requires a full --commit SHA.');+ const head = execFileSync('git', ['-C', sourceRoot, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim();+ if (head !== commit) throw new Error('Source checkout does not match --commit.');+ if (execFileSync('git', ['-C', sourceRoot, 'status', '--porcelain'], { encoding: 'utf8' }).trim()) throw new Error('Source checkout must be clean.');+}+const inventory = inventoryUpstream(sourceRoot);+const previousInventory = JSON.parse(await fs.readFile(path.join(root, 'upstream-inventory.json'), 'utf8'));+const changes = inventoryDelta(previousInventory, inventory);+if (!update && Object.values(changes).some(items => items.length)) throw new Error('Pinned upstream inventory changed.');+const license = await fs.readFile(path.join(sourceRoot, 'LICENSE'));+if (!update && !license.equals(await fs.readFile(path.join(root, 'LICENSE.opencodex')))) throw new Error('Pinned upstream license changed.');+const extracted = extractProviderProfiles(sourceRoot);+const profilesText = JSON.stringify(extracted.profiles, null, 2) + '\n';+if (!update && profilesText !== await fs.readFile(path.join(root, 'src/upstream-profiles.json'), 'utf8')) throw new Error('Provider profiles are not reproducible from the pinned registry.');+const scratch = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-model-compat-sync-'));+try {+ const originals = new Map();+ for (const entry of files) {+ const bytes = await fs.readFile(path.join(sourceRoot, entry.source));+ if (!update && hash(bytes) !== entry.upstreamSha256) throw new Error(`Pinned upstream file differs: ${entry.source}`);+ originals.set(entry.source, bytes);+ const dest = path.join(scratch, entry.source);+ await fs.mkdir(path.dirname(dest), { recursive: true });+ await fs.writeFile(dest, bytes);+ }+ const patch = await fs.readFile(path.join(root, 'upstream.patch'));+ execFileSync('git', ['apply', '--check', '-'], { cwd: scratch, input: patch });+ execFileSync('git', ['apply', '-'], { cwd: scratch, input: patch });+ const outputs = new Map();+ for (const entry of manifest.files) {+ let bytes = await fs.readFile(path.join(scratch, entry.source));+ if (entry.extractSymbols) {+ const sf = ts.createSourceFile(entry.source, bytes.toString('utf8'), ts.ScriptTarget.Latest, true);+ const declarations = sf.statements.filter(node => entry.extractSymbols.includes(node.name?.text ?? (ts.isVariableStatement(node) ? node.declarationList.declarations[0]?.name?.getText(sf) : undefined)));+ if (declarations.length !== entry.extractSymbols.length) throw new Error('Upstream helper extraction changed: ' + entry.source);+ bytes = Buffer.from(entry.extractionPrefix + declarations.map(node =>+ (node.modifiers?.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword) ? '' : 'export ') + node.getText(sf)).join('\n\n') + '\n');+ }+ outputs.set(entry.target, bytes);+ }+ for (const entry of manifest.tests) {+ let text = originals.get(entry.source).toString('utf8');+ const sf = ts.createSourceFile(entry.source, text, ts.ScriptTarget.Latest, true);+ const edits = [];+ for (const node of sf.statements) {+ if (!ts.isImportDeclaration(node) || !ts.isStringLiteral(node.moduleSpecifier)) continue;+ const spec = node.moduleSpecifier.text;+ let replacement = spec;+ if (spec === 'bun:test') replacement = 'vitest';+ else if (spec.startsWith('.')) {+ const imported = path.posix.normalize(path.posix.join(path.posix.dirname(entry.source), spec)).replace(/\.ts$/, '') + '.ts';+ const mapped = manifest.files.find(candidate => candidate.source === imported);+ if (!mapped) throw new Error(`New upstream test dependency needs review: ${imported}`);+ replacement = path.relative(path.dirname(path.join(root, entry.target)), path.join(root, mapped.target)).split(path.sep).join('/').replace(/\.ts$/, '');+ }+ edits.push([node.moduleSpecifier.getStart(sf), node.moduleSpecifier.end, JSON.stringify(replacement)]);+ }+ for (const [start, end, replacement] of edits.reverse()) text = text.slice(0, start) + replacement + text.slice(end);+ const result = ts.transpileModule(text, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext } }).outputText;+ outputs.set(entry.target, Buffer.from(result));+ }+ if (!update) {+ for (const entry of files) if (hash(outputs.get(entry.target)) !== entry.portedSha256) throw new Error(`Port is not reproducible: ${entry.target}`);+ console.log(`Verified pinned source, patch, and ${files.length} reproduced files.`);+ } else {+ // All patch applications and test dependency checks have passed before the first source write.+ for (const entry of files) {+ const bytes = outputs.get(entry.target);+ await fs.writeFile(path.join(root, entry.target), bytes);+ entry.upstreamSha256 = hash(originals.get(entry.source));+ entry.portedSha256 = hash(bytes);+ }+ await fs.writeFile(path.join(root, 'src/upstream-profiles.json'), profilesText);+ await fs.writeFile(path.join(root, 'LICENSE.opencodex'), license);+ await fs.writeFile(path.join(root, 'upstream-inventory.json'), JSON.stringify(inventory, null, 2) + '\n');+ await fs.writeFile(path.join(root, 'UPSTREAM-CHANGES.json'), JSON.stringify({ from: manifest.commit, to: commit, ...changes }, null, 2) + '\n');+ manifest.registrySources = extracted.sources;+ manifest.profilesSha256 = hash(profilesText);+ manifest.commit = commit;+ await fs.writeFile(path.join(root, 'UPSTREAM.json'), JSON.stringify(manifest, null, 2) + '\n');+ console.log('Updated modules and provider declarations. Review UPSTREAM-CHANGES.json, including new/unported modules, then run conformance and consumer tests before committing.');+ }+} finally {+ await fs.rm(scratch, { recursive: true, force: true });+}diff --git a/packages/model-compat/scripts/upstream-inventory.mjs b/packages/model-compat/scripts/upstream-inventory.mjsnew file mode 100644index 0000000000..6f51df3b89--- /dev/null+++ b/packages/model-compat/scripts/upstream-inventory.mjs@@ -0,0 +1,27 @@+import fs from 'node:fs';+import path from 'node:path';+import { createHash } from 'node:crypto';++/** Inventory all source files, including adapters not executed by Cindy. A sync must expose+ * new compatibility code outside the imported closure instead of silently overlooking it. */+export function inventoryUpstream(root) {+ const files = {};+ const visit = relative => {+ for (const entry of fs.readdirSync(path.join(root, relative), { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name, 'en'))) {+ const name = path.posix.join(relative, entry.name);+ if (entry.isDirectory()) visit(name);+ else if (entry.isFile()) {+ files[name] = createHash('sha256').update(fs.readFileSync(path.join(root, name))).digest('hex');+ }+ }+ };+ visit('src');+ return files;+}+export function inventoryDelta(before, after) {+ return {+ added: Object.keys(after).filter(name => !(name in before)),+ removed: Object.keys(before).filter(name => !(name in after)),+ changed: Object.keys(after).filter(name => name in before && after[name] !== before[name]),+ };+}diff --git a/packages/model-compat/src/__tests__/boundaries.test.ts b/packages/model-compat/src/__tests__/boundaries.test.tsnew file mode 100644index 0000000000..d21618ab7b--- /dev/null+++ b/packages/model-compat/src/__tests__/boundaries.test.ts@@ -0,0 +1,93 @@+import { describe, expect, it } from 'vitest';+import { createCodexResponsesCompatibilityAdapter, prepareResponsesCompatibility, normalizeProviderRequest, chatCompatibilityCapabilities, sanitizeXaiTools } from '../index';++describe('protocol data boundaries', () => {+ it('does not rewrite custom-shaped literals in schemas, metadata or tool output', () => {+ const literal = { type: 'custom', name: 'run', description: 'literal value' };+ const body = {+ tools: [{ type: 'custom', name: 'run', description: 'actual tool' },+ { type: 'function', name: 'save', parameters: { type: 'object', properties: { payload: { default: literal } } } }],+ metadata: literal,+ input: [{ type: 'function_call_output', call_id: 'ordinary', output: literal }],+ };+ const prepared = prepareResponsesCompatibility(body, { customTools: 'functions' });+ const result = prepared.body as typeof body;+ expect(result.tools[0]!.type).toBe('function');+ expect(result.tools[1]).toEqual(body.tools[1]);+ expect(result.metadata).toBe(literal);+ expect(result.input[0]!.output).toBe(literal);+ expect(body.tools[0]!.type).toBe('custom');+ });+ it('does not infer namespace support from a provider-shaped model name', () => {+ const adapter = createCodexResponsesCompatibilityAdapter();+ const body = { model: 'xai/grok-4.6', tools: [{ type: 'namespace', name: 'files', tools: [{ type: 'function', name: 'read' }] }] };+ expect(adapter.adaptRequest(body, 1, { harness: 'codex', protocol: 'openai-responses', upstreamBase: 'https://proxy.example/v1', model: 'xai/grok-4.6' })).toBeNull();+ adapter.releaseResponse(1);+ });+ it('releases both adapter mappings after an invalid response encoding', () => {+ const adapter = createCodexResponsesCompatibilityAdapter();+ adapter.adaptRequest({ tools: [{ type: 'custom', name: 'exec', description: 'JavaScript' }] }, 7);+ expect(() => adapter.createResponseTransform(7, { contentType: 'application/json', contentEncoding: 'gzip' })).toThrow();+ expect(adapter.createResponseTransform(7, { contentType: 'application/json', contentEncoding: '' })).toBeNull();+ });+ it('uses DeepSeek declarations for the endpoint and keeps explicit route capabilities', () => {+ const route = { harness: 'codex' as const, protocol: 'openai-chat' as const, upstreamBase: 'https://api.deepseek.com', model: 'deepseek-v4-pro' };+ const capabilities = chatCompatibilityCapabilities(route, { parallelToolCalls: false });+ expect(capabilities.parallelToolCalls).toBe(false);+ const body = { model: route.model, reasoning_effort: 'high' };+ const normalized = normalizeProviderRequest(body, route) as typeof body;+ expect(normalized.model).toBe(body.model);+ expect(normalizeProviderRequest(body, { ...route, upstreamBase: 'https://api.deepseek.com.evil.test' })).toBe(body);+ });+});++describe('provider replay regression', () => {+ const route = { harness: 'codex' as const, protocol: 'openai-responses' as const, upstreamBase: 'https://api.deepseek.com', model: 'deepseek-v4-pro' };+ it('normalizes DeepSeek search history and effort without discarding plaintext reasoning', () => {+ const body = { model: route.model, reasoning: { effort: 'medium' }, input: [+ { type: 'reasoning', content: [{ type: 'reasoning_text', text: 'retained reasoning' }] },+ { type: 'web_search_call', action: { type: 'search', query: 'weather' } },+ ] };+ const result = normalizeProviderRequest(body, route) as typeof body & { store: boolean };+ expect(result.reasoning.effort).toBe('high');+ expect(result.store).toBe(false);+ expect(result.input[0]).toBe(body.input[0]);+ expect(result.input[1]!.action).toEqual({ type: 'search', query: 'weather', queries: ['weather'] });+ expect(body.reasoning.effort).toBe('medium');+ });+ it('keeps parallel calls grouped with their results and explicitly annotates empty output', () => {+ const call = { type: 'function_call', call_id: 'a', name: 'read', arguments: '{}' };+ const message = { type: 'message', role: 'assistant', content: [] };+ const result = normalizeProviderRequest({ input: [call, message, { type: 'function_call_output', call_id: 'a', output: '' }] }, route) as { input: Array<Record<string, unknown>> };+ expect(result.input[0]).toBe(call);+ expect(result.input[1]!.type).toBe('function_call_output');+ expect(result.input[1]!.output).toBe('[ocx] empty tool output: the tool ran but produced no stdout or return value; do not treat this as success, failure, or user-provided input.');+ expect(result.input[2]).toBe(message);+ });+ it('rejects a stateless continuation whose history has not been expanded', () => {+ expect(() => normalizeProviderRequest({ previous_response_id: 'resp_missing' }, route)).toThrow(/expanded/);+ });+ it('converts apply_patch for the actual xAI subscription endpoint', () => {+ const adapter = createCodexResponsesCompatibilityAdapter();+ const body = { tools: [{ type: 'custom', name: 'apply_patch', description: 'Apply a patch' }] };+ const result = adapter.adaptRequest(body, 1, { ...route, model: 'grok-4.6', upstreamBase: 'https://cli-chat-proxy.grok.com/v1' }, true) as typeof body;+ expect(result.tools[0]!.type).toBe('function');+ adapter.releaseResponse(1);+ });+});+++it('cleans both xAI tool catalogs without retaining a removed top-level declaration', () => {+ const body = { tools: [{ type: 'unsupported' }], input: [{ type: 'additional_tools', tools: [{ type: 'function', name: 'read' }, { type: 'unsupported' }] }], tool_choice: { type: 'function', name: 'read' } };+ const result = sanitizeXaiTools(body)!;+ expect(result).not.toHaveProperty('tools');+ expect(result.input).toEqual([{ type: 'additional_tools', tools: [{ type: 'function', name: 'read' }] }]);+ expect(result.tool_choice).toEqual(body.tool_choice);+ expect(body.tools).toEqual([{ type: 'unsupported' }]);+});+++it('preserves an explicit native Chat reasoning disable when no provider wire map overrides it', () => {+ const input = { model: 'gpt-5.4', reasoning_effort: 'none' };+ expect(normalizeProviderRequest(input, { harness: 'codex', protocol: 'openai-chat', upstreamBase: 'https://api.openai.com/v1', model: input.model })).toEqual(input);+});diff --git a/packages/model-compat/src/__tests__/compatibility.test.ts b/packages/model-compat/src/__tests__/compatibility.test.tsnew file mode 100644index 0000000000..8ad6c41efe--- /dev/null+++ b/packages/model-compat/src/__tests__/compatibility.test.ts@@ -0,0 +1,83 @@+import { describe, expect, it } from 'vitest';+import { Readable } from 'node:stream';+import { createCodexResponsesCompatibilityAdapter, normalizeProviderRequest, prepareResponsesCompatibility, resolveProviderCompatibilityProfile, sanitizeXaiTools, hasCacheOnlySearchProhibition } from '../index';++async function responseText(transform: NodeJS.ReadWriteStream, text: string) {+ const output: Buffer[] = [];+ const done = new Promise<string>((resolve, reject) => {+ transform.on('data', chunk => output.push(Buffer.from(chunk)));+ transform.on('error', reject);+ transform.on('end', () => resolve(Buffer.concat(output).toString()));+ });+ Readable.from([...Buffer.from(text)].map(byte => Buffer.from([byte]))).pipe(transform);+ return done;+}++describe('request-owned Responses compatibility', () => {+ it.each(['application/json', 'text/event-stream'])('restores namespace and Code Mode identities (%s)', async contentType => {+ const adapter = createCodexResponsesCompatibilityAdapter();+ const input = {+ model: 'xai/grok-4.6',+ tools: [+ { type: 'custom', name: 'exec', description: 'Run JavaScript' },+ { type: 'namespace', name: 'files', tools: [{ type: 'function', name: 'read', parameters: { type: 'object', properties: { path: { type: 'string' } } } }] },+ ],+ };+ const request = adapter.adaptRequest(input, 1, { harness: 'codex', protocol: 'openai-responses', upstreamBase: 'https://cli-chat-proxy.grok.com/v1', model: 'grok-4.6' }, true) as typeof input;+ expect(request.tools.map(tool => tool.name)).toEqual(['exec', 'files__read']);+ const result = { id: 'resp_test', output: [+ { type: 'function_call', id: 'fc_a', call_id: 'a', name: 'exec', arguments: JSON.stringify({ input: 'text("你好")' }) },+ { type: 'function_call', id: 'fc_b', call_id: 'b', name: 'files__read', arguments: '{"path":"README.md"}' },+ ] };+ const sse = contentType === 'text/event-stream';+ const wire = sse ? `data: ${JSON.stringify({ type: 'response.completed', response: result })}\n\n` : JSON.stringify(result);+ const transformed = await responseText(adapter.createResponseTransform(1, { contentType, contentEncoding: '' })!, wire);+ const parsed = JSON.parse(sse ? transformed.trim().slice(6) : transformed);+ const response = sse ? parsed.response : parsed;+ expect(response.output[0]).toMatchObject({ type: 'custom_tool_call', call_id: 'a', name: 'exec', input: 'text("你好")' });+ expect(response.output[1]).toMatchObject({ type: 'function_call', call_id: 'b', namespace: 'files', name: 'read' });+ expect(input.tools[1]!.type).toBe('namespace');+ });++ it('keeps native GPT namespaces and no-op response bodies unchanged', () => {+ const input = { model: 'gpt-5.4', tools: [{ type: 'namespace', name: 'files', tools: [{ type: 'function', name: 'read' }] }] };+ const adapter = createCodexResponsesCompatibilityAdapter();+ expect(adapter.adaptRequest(input, 1)).toBeNull();+ adapter.releaseResponse(1);+ expect(adapter.createResponseTransform(1, { contentType: 'application/json', contentEncoding: '' })).toBeNull();+ });++ it('restores tool discovery independently from web search', () => {+ const prepared = prepareResponsesCompatibility({ tools: [{ type: 'tool_search' }] }, { toolSearch: 'function' });+ const body = prepared.body as { tools: Array<{ name: string }> };+ const output = JSON.parse(prepared.restoreJson(JSON.stringify({ output: [{ type: 'function_call', name: body.tools[0]!.name, call_id: 'a', arguments: '{"query":"read files"}' }] })));+ expect(output.output[0].type).toBe('tool_search_call');+ });+});++describe('provider policy boundaries across harnesses', () => {+ it.each(['codex', 'claude-code', 'pi'] as const)('only normalizes an actual xAI Responses endpoint for %s', harness => {+ const body = { tools: [{ type: 'web_search', external_web_access: true, user_location: { country: 'CN' } }] };+ const route = { harness, protocol: 'openai-responses' as const, upstreamBase: 'https://api.x.ai/v1', model: 'grok-4.6' };+ expect(normalizeProviderRequest(body, route)).toEqual({ tools: [{ type: 'web_search', user_location: { country: 'CN' } }] });+ expect(normalizeProviderRequest(body, { ...route, upstreamBase: 'https://api.x.ai.evil.test/v1' })).toBe(body);+ expect(normalizeProviderRequest(body, { ...route, protocol: 'openai-chat' })).toBe(body);+ });+ it.each([false, null, 'false'])('does not widen an explicit non-live search declaration (%s)', external_web_access => {+ const body = { tools: [{ type: 'function', name: 'read' }], input: [{ type: 'additional_tools', tools: [{ type: 'web_search_preview', external_web_access }] }], tool_choice: { type: 'web_search_preview' } };+ expect(hasCacheOnlySearchProhibition(body)).toBe(true);+ expect(sanitizeXaiTools(body)).toMatchObject({ tools: [{ type: 'function', name: 'read' }], tool_choice: 'none', input: [] });+ });+ it('strips subscription-only schema markers without touching literals or the public xAI API', () => {+ const parameters = { $schema: 'https://json-schema.org/draft/2020-12/schema', type: 'object', properties: { encrypted: { type: 'string', default: 'encrypted' } }, additionalProperties: false };+ const body = { tools: [{ type: 'function', name: 'read', parameters }] };+ const route = { harness: 'claude-code' as const, protocol: 'openai-responses' as const, model: 'grok-4.6', upstreamBase: 'https://cli-chat-proxy.grok.com/v1' };+ const output = normalizeProviderRequest(body, route) as typeof body;+ expect(output.tools[0]!.parameters).not.toHaveProperty('$schema');+ expect(output.tools[0]!.parameters.properties.encrypted.default).toBe('encrypted');+ expect(normalizeProviderRequest(body, { ...route, upstreamBase: 'https://api.x.ai/v1' })).toBe(body);+ });+ it('does not inherit compatibility by a familiar model name on an unknown gateway', () => {+ expect(resolveProviderCompatibilityProfile({ harness: 'codex', protocol: 'openai-responses', model: 'deepseek-v4-pro', upstreamBase: 'https://gateway.example/v1' })).toBeNull();+ });+});diff --git a/packages/model-compat/src/__tests__/sync.test.js b/packages/model-compat/src/__tests__/sync.test.jsnew file mode 100644index 0000000000..209a2f9f8e--- /dev/null+++ b/packages/model-compat/src/__tests__/sync.test.js@@ -0,0 +1,38 @@+import { describe, expect, it } from 'vitest';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { extractProviderProfiles } from '../../scripts/provider-profiles.mjs';++function fixture(source, run) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-profile-test-'));+ try {+ fs.mkdirSync(path.join(root, 'src/providers'), { recursive: true });+ fs.writeFileSync(path.join(root, 'src/providers/registry.ts'), source);+ return run(root);+ } finally { fs.rmSync(root, { recursive: true, force: true }); }+}+describe('upstream synchronization contract', () => {+ it('extracts compatibility data deterministically without evaluating upstream side effects', () => {+ const source = `throw new Error('must never execute');+ const IDS = ['reasoner'];+ export const PROVIDER_REGISTRY = [{ id: 'test', adapter: 'openai-chat', baseUrl: 'https://provider.example',+ noTemperatureModels: IDS, modelReasoningEffortMap: Object.fromEntries(IDS.map(id => [id, { high: 'enabled' }])),+ credentials: process.env.SECRET }];`;+ fixture(source, root => {+ const first = extractProviderProfiles(root);+ expect(first).toEqual(extractProviderProfiles(root));+ expect(first.profiles).toEqual([{ id: 'test', adapter: 'openai-chat', baseUrl: 'https://provider.example', noTemperatureModels: ['reasoner'], modelReasoningEffortMap: { reasoner: { high: 'enabled' } } }]);+ });+ });+ it('fails instead of silently losing a new dynamic compatibility expression', () => {+ fixture(`export const PROVIDER_REGISTRY = [{ id: 'test', baseUrl: 'https://provider.example', noTemperatureModels: unknownNewHelper() }];`, root => {+ expect(() => extractProviderProfiles(root)).toThrow(/Unresolved compatibility expression/);+ });+ });+ it('rejects registry structure changes that need a human port review', () => {+ fixture(`export const PROVIDER_REGISTRY = buildRegistry();`, root => {+ expect(() => extractProviderProfiles(root)).toThrow(/registry shape changed/);+ });+ });+});diff --git a/packages/model-compat/src/__tests__/upstream/adapters/google/google-tool-schema.test.js b/packages/model-compat/src/__tests__/upstream/adapters/google/google-tool-schema.test.jsnew file mode 100644index 0000000000..578161fca7--- /dev/null+++ b/packages/model-compat/src/__tests__/upstream/adapters/google/google-tool-schema.test.js@@ -0,0 +1,458 @@+import { describe, expect, test } from "vitest";+import { sanitizeGeminiToolParameters } from "../../../../upstream/adapters/google-tool-schema";+function countSchemaNodes(value) {+ if (!value || typeof value !== "object" || Array.isArray(value))+ return 0;+ const schema = value;+ let count = 1;+ if (schema.properties && typeof schema.properties === "object" && !Array.isArray(schema.properties)) {+ for (const child of Object.values(schema.properties))+ count += countSchemaNodes(child);+ }+ if (schema.items !== undefined)+ count += countSchemaNodes(schema.items);+ return count;+}+describe("sanitizeGeminiToolParameters", () => {+ test("drops JSON-Schema keywords outside Google's documented function-schema subset", () => {+ const out = sanitizeGeminiToolParameters({+ $schema: "http://json-schema.org/draft-07/schema#",+ $id: "x",+ $comment: "c",+ type: "object",+ properties: {+ a: { type: "string", examples: ["x"], pattern: "^a$" },+ b: { type: "array", items: { type: "string" }, uniqueItems: true },+ },+ patternProperties: { "^x": { type: "string" } },+ if: { x: 1 },+ then: { y: 2 },+ });+ expect(out.$schema).toBeUndefined();+ expect(out.$id).toBeUndefined();+ expect(out.$comment).toBeUndefined();+ expect(out.patternProperties).toBeUndefined();+ expect(out.if).toBeUndefined();+ expect(out.then).toBeUndefined();+ const props = out.properties;+ expect(props.a.examples).toBeUndefined();+ expect(props.a.pattern).toBeUndefined();+ expect(props.b.uniqueItems).toBeUndefined();+ expect(props.b.items.type).toBe("string");+ });+ test("drops Codex's Responses-only encrypted marker recursively (issue #85)", () => {+ // Upstream codex stamps `encrypted: true` on v2 collaboration tool schemas+ // (spawn_agent/send_message/followup_task `message`); CCA 400s on the unknown name.+ const input = {+ type: "object",+ properties: {+ message: { type: "string", description: "...", encrypted: true },+ nested: {+ type: "object",+ properties: { inner: { type: "string", encrypted: false } },+ },+ list: { type: "array", items: { type: "string", encrypted: true } },+ },+ required: ["message"],+ };+ const before = JSON.stringify(input);+ const out = sanitizeGeminiToolParameters(input);+ const props = out.properties;+ expect(props.message.encrypted).toBeUndefined();+ expect(props.message.type).toBe("string");+ const inner = props.nested.properties.inner;+ expect(inner.encrypted).toBeUndefined(); // `encrypted: false` is equally unsupported+ expect(props.list.items.encrypted).toBeUndefined();+ expect(out.required).toEqual(["message"]);+ expect(JSON.stringify(input)).toBe(before); // input object is never mutated+ });+ test("drops MCP header annotations that CCA rejects recursively", () => {+ const out = sanitizeGeminiToolParameters({+ type: "object",+ properties: {+ token: { type: "string", "x-mcp-header": "Authorization" },+ nested: {+ type: "object",+ properties: {+ trace: { type: "string", "x-mcp-header": "X-Trace-Id" },+ },+ },+ headers: {+ type: "array",+ items: { type: "string", "x-mcp-header": true },+ },+ },+ });+ const props = out.properties;+ expect(props.token["x-mcp-header"]).toBeUndefined();+ const nested = props.nested.properties;+ expect(nested.trace["x-mcp-header"]).toBeUndefined();+ expect(props.headers.items["x-mcp-header"]).toBeUndefined();+ expect(props.token.type).toBe("string");+ });+ test("drops draft 2020-12 keywords outside OpenAPI 3.0 subset", () => {+ const out = sanitizeGeminiToolParameters({+ type: "object",+ $vocabulary: { "https://json-schema.org/draft/2020-12/vocab/core": true },+ $anchor: "root",+ properties: {+ payload: {+ type: "string",+ contentMediaType: "application/json",+ contentEncoding: "base64",+ contentSchema: { type: "object" },+ deprecated: true,+ },+ tuple: {+ type: "array",+ prefixItems: [{ type: "string" }, { type: "number" }],+ items: { type: "string" },+ },+ refLike: {+ $dynamicRef: "#node",+ $dynamicAnchor: "node",+ type: "object",+ },+ },+ });+ expect(out.$vocabulary).toBeUndefined();+ expect(out.$anchor).toBeUndefined();+ const props = out.properties;+ expect(props.payload.contentMediaType).toBeUndefined();+ expect(props.payload.contentEncoding).toBeUndefined();+ expect(props.payload.contentSchema).toBeUndefined();+ expect(props.payload.deprecated).toBeUndefined();+ expect(props.payload.type).toBe("string");+ expect(props.tuple.prefixItems).toBeUndefined();+ expect(props.tuple.items.type).toBe("string");+ expect(props.refLike.$dynamicRef).toBeUndefined();+ expect(props.refLike.$dynamicAnchor).toBeUndefined();+ expect(props.refLike.type).toBe("object");+ });+ test("collapses type arrays to a single nullable type", () => {+ const out = sanitizeGeminiToolParameters({+ type: "object",+ properties: { a: { type: ["string", "null"] } },+ });+ const a = out.properties.a;+ expect(a.type).toBe("string");+ expect(a.nullable).toBe(true);+ });+ test("rewrites string const to enum and drops unsupported exclusive bounds", () => {+ const out = sanitizeGeminiToolParameters({+ type: "object",+ properties: {+ a: { const: "fixed" },+ n: { type: "number", exclusiveMinimum: 0, exclusiveMaximum: 10 },+ },+ });+ const props = out.properties;+ expect(props.a.enum).toEqual(["fixed"]);+ expect(props.a.const).toBeUndefined();+ expect(props.n.minimum).toBeUndefined();+ expect(props.n.maximum).toBeUndefined();+ expect(props.n.exclusiveMinimum).toBeUndefined();+ });+ test("deduplicates required names for Claude-on-Antigravity", () => {+ expect(sanitizeGeminiToolParameters({+ type: "object",+ properties: { query: { type: "string" } },+ required: ["query", "query", 42],+ }).required).toEqual(["query"]);+ });+ test("drops size constraints outside the strict Google allowlist", () => {+ const out = sanitizeGeminiToolParameters({+ type: "object",+ properties: {+ text: { type: "string", minLength: -1, maxLength: -2 },+ list: { type: "array", minItems: -1, maxItems: -2, items: { type: "string" } },+ object: { type: "object", minProperties: -1, maxProperties: -2, properties: {} },+ zeroIsValid: { type: "string", minLength: 0 },+ },+ });+ const props = out.properties;+ expect(props.text.minLength).toBeUndefined();+ expect(props.text.maxLength).toBeUndefined();+ expect(props.list.minItems).toBeUndefined();+ expect(props.list.maxItems).toBeUndefined();+ expect(props.object.minProperties).toBeUndefined();+ expect(props.object.maxProperties).toBeUndefined();+ expect(props.zeroIsValid.minLength).toBeUndefined();+ });+ test("collapses same-type enum anyOf branches for Claude-on-Antigravity", () => {+ const out = sanitizeGeminiToolParameters({+ type: "object",+ properties: {+ status: {+ description: "New status for the task",+ anyOf: [+ { type: "string", enum: ["pending", "in_progress", "completed"] },+ { type: "string", enum: ["deleted"] },+ ],+ },+ },+ });+ const status = out.properties.status;+ expect(status).toEqual({+ description: "New status for the task",+ type: "string",+ enum: ["pending", "in_progress", "completed", "deleted"],+ });+ });+ test("collapses Serena nullable anyOf schemas for Claude-on-Antigravity", () => {+ const out = sanitizeGeminiToolParameters({+ type: "object",+ properties: {+ occurrence_ids: {+ anyOf: [+ { type: "array", items: { type: "string" } },+ { type: "null" },+ ],+ default: null,+ title: "Occurrence Ids",+ description: "Optional occurrence ids from a dry run.",+ },+ },+ });+ const occurrenceIds = out.properties.occurrence_ids;+ expect(occurrenceIds).toEqual({+ type: "array",+ items: { type: "string" },+ nullable: true,+ description: "Optional occurrence ids from a dry run.",+ });+ });+ test("widens unsupported typed anyOf unions instead of forwarding a request-breaking schema", () => {+ const out = sanitizeGeminiToolParameters({+ type: "object",+ properties: {+ value: {+ description: "A string or number.",+ anyOf: [+ { type: "string", minLength: 1 },+ { type: "number", minimum: 0 },+ ],+ },+ },+ });+ const value = out.properties.value;+ expect(value).toEqual({ description: "A string or number." });+ });+ test("enforces an object root without composition for Claude tool input schemas", () => {+ expect(sanitizeGeminiToolParameters({})).toEqual({+ type: "object",+ properties: {},+ });+ expect(sanitizeGeminiToolParameters({+ anyOf: [+ { type: "string" },+ { type: "number" },+ ],+ })).toEqual({+ type: "object",+ properties: {},+ });+ });+ test("emits only the documented Google function-schema allowlist recursively", () => {+ const out = sanitizeGeminiToolParameters({+ type: "object",+ title: "Dropped root title",+ default: {},+ futureKeyword: { surprise: true },+ properties: {+ safe: {+ type: "string",+ description: "Kept description",+ format: "date-time",+ title: "Dropped nested title",+ default: "x",+ pattern: "^x$",+ minLength: 1,+ "x-future-keyword": true,+ },+ title: { type: "string" },+ },+ });+ expect(out).toEqual({+ type: "object",+ properties: {+ safe: {+ type: "string",+ description: "Kept description",+ format: "date-time",+ },+ title: { type: "string" },+ },+ });+ });+ test("falls back to an open object schema when hostile refs cannot be decoded", () => {+ expect(sanitizeGeminiToolParameters({+ $ref: "#/$defs/%E0%A4%A",+ $defs: { safe: { type: "string" } },+ })).toEqual({+ type: "object",+ properties: {},+ });+ });+ test("never leaks the internal null type used while normalizing unions", () => {+ const out = sanitizeGeminiToolParameters({+ type: "object",+ properties: {+ impossible: {+ anyOf: [+ { type: "null", enum: ["x"] },+ { type: "null", enum: ["y"] },+ ],+ },+ },+ });+ expect(out.properties.impossible).toEqual({});+ });+ test("preserves property names that overlap JavaScript prototype keys", () => {+ const properties = JSON.parse('{"__proto__":{"type":"string"},"constructor":{"type":"number"}}');+ const out = sanitizeGeminiToolParameters({ type: "object", properties });+ const sanitized = out.properties;+ expect(Object.prototype.hasOwnProperty.call(sanitized, "__proto__")).toBe(true);+ expect(sanitized.__proto__).toEqual({ type: "string" });+ expect(sanitized.constructor).toEqual({ type: "number" });+ });+ test("inlines local $ref into $defs and removes the defs bag", () => {+ const out = sanitizeGeminiToolParameters({+ type: "object",+ properties: { node: { $ref: "#/$defs/Node" } },+ $defs: { Node: { type: "object", properties: { id: { type: "string" } } } },+ });+ expect(out.$defs).toBeUndefined();+ const node = out.properties.node;+ expect(node.type).toBe("object");+ expect(node.properties.id.type).toBe("string");+ });+ test("does not enumerate unsupported definition keys for repeated refs", () => {+ let enumeratedDefinition = false;+ const definition = new Proxy({+ type: "object",+ properties: { id: { type: "string" } },+ }, {+ ownKeys() {+ enumeratedDefinition = true;+ throw new Error("enumerated the full definition");+ },+ });+ const out = sanitizeGeminiToolParameters({+ type: "object",+ properties: {+ first: { $ref: "#/$defs/Wide" },+ second: { $ref: "#/$defs/Wide" },+ },+ $defs: { Wide: definition },+ });+ const properties = out.properties;+ expect(enumeratedDefinition).toBe(false);+ expect(properties.first).toEqual({+ type: "object",+ properties: { id: { type: "string" } },+ });+ expect(properties.second).toEqual(properties.first);+ });+ test("widens recursive $refs without expanding sibling branches", () => {+ const out = sanitizeGeminiToolParameters({+ type: "object",+ properties: { tree: { $ref: "#/$defs/Tree" } },+ $defs: {+ Tree: {+ type: "object",+ properties: {+ left: { $ref: "#/$defs/Tree" },+ right: { $ref: "#/$defs/Tree" },+ },+ },+ },+ });+ const tree = out.properties.tree;+ expect(tree.type).toBe("object");+ expect(tree.properties).toEqual({ left: {}, right: {} });+ });+ test("bounds acyclic shared-definition fan-out by node budget", () => {+ const defs = {};+ for (let index = 17; index >= 0; index--) {+ defs[`Node${index}`] = index === 17+ ? { type: "string" }+ : {+ type: "object",+ properties: {+ left: { $ref: `#/$defs/Node${index + 1}` },+ right: { $ref: `#/$defs/Node${index + 1}` },+ },+ };+ }+ const out = sanitizeGeminiToolParameters({+ type: "object",+ properties: { tree: { $ref: "#/$defs/Node0" } },+ $defs: defs,+ });+ expect(countSchemaNodes(out)).toBeLessThanOrEqual(1_024);+ });+ test("truncates wide properties without dangling required names", () => {+ const names = Array.from({ length: 2_000 }, (_, index) => `field_${index}`);+ const out = sanitizeGeminiToolParameters({+ type: "object",+ properties: Object.fromEntries(names.map(name => [name, { type: "string" }])),+ required: names,+ });+ const properties = out.properties;+ const retainedNames = Object.keys(properties);+ expect(retainedNames).toHaveLength(1_023);+ expect(out.required).toEqual(retainedNames);+ expect(Object.hasOwn(properties, names[1_023])).toBe(false);+ expect(countSchemaNodes(out)).toBe(1_024);+ });+ test("stops reading anyOf branches when the budget is exhausted", () => {+ const branches = Array.from({ length: 2_000 }, () => ({ type: "string" }));+ let readPastBudget = false;+ Object.defineProperty(branches, 1_022, {+ configurable: true,+ get() {+ readPastBudget = true;+ throw new Error("read past schema budget");+ },+ });+ const out = sanitizeGeminiToolParameters({+ type: "object",+ properties: {+ choice: {+ description: "kept",+ anyOf: branches,+ },+ },+ });+ const choice = out.properties.choice;+ expect(readPastBudget).toBe(false);+ expect(choice).toEqual({ description: "kept" });+ });+ test("does not read items after earlier traversal exhausts the budget", () => {+ const container = {+ type: "array",+ properties: Object.fromEntries(Array.from({ length: 1_022 }, (_, index) => [`field_${index}`, { type: "string" }])),+ };+ let readItems = false;+ Object.defineProperty(container, "items", {+ configurable: true,+ get() {+ readItems = true;+ throw new Error("read items past schema budget");+ },+ });+ const out = sanitizeGeminiToolParameters({+ type: "object",+ properties: { container },+ });+ const sanitized = out.properties.container;+ expect(readItems).toBe(false);+ expect(sanitized.items).toBeUndefined();+ expect(countSchemaNodes(out)).toBe(1_024);+ });+ test("falls back to an object schema for non-object input", () => {+ expect(sanitizeGeminiToolParameters(undefined)).toEqual({ type: "object", properties: {} });+ expect(sanitizeGeminiToolParameters("nope")).toEqual({ type: "object", properties: {} });+ });+});diff --git a/packages/model-compat/src/__tests__/upstream/adapters/tool-choice-performance.test.js b/packages/model-compat/src/__tests__/upstream/adapters/tool-choice-performance.test.jsnew file mode 100644index 0000000000..a1a129d71e--- /dev/null+++ b/packages/model-compat/src/__tests__/upstream/adapters/tool-choice-performance.test.js@@ -0,0 +1,74 @@+import { expect, test } from "vitest";+import { toolChoiceCandidates, toolChoiceToolPredicate } from "../../../upstream/types";+test("allowed_tools resolves an ambiguous bare name without replaying the candidate list", () => {+ const size = 256;+ const backingTools = Array.from({ length: size }, (_, index) => ({+ namespace: `namespace_${index}`,+ name: "shared_name",+ description: "",+ parameters: {},+ }));+ let catalogReads = 0;+ const tools = new Proxy(backingTools, {+ get(target, property, receiver) {+ if (typeof property === "string" && /^\d+$/.test(property))+ catalogReads += 1;+ return Reflect.get(target, property, receiver);+ },+ });+ const arrayIterator = Object.getOwnPropertyDescriptor(Array.prototype, Symbol.iterator);+ let ambiguousCandidateIterations = 0;+ Object.defineProperty(Array.prototype, Symbol.iterator, {+ ...arrayIterator,+ value: function () {+ const iterator = arrayIterator.value.call(this);+ const tracksCandidateList = this !== backingTools+ && this !== tools+ && this.length === size+ && this[0] === backingTools[0]+ && this[size - 1] === backingTools[size - 1];+ return {+ next() {+ const result = iterator.next();+ if (tracksCandidateList && !result.done)+ ambiguousCandidateIterations += 1;+ return result;+ },+ [Symbol.iterator]() {+ return this;+ },+ };+ },+ });+ let filtered;+ try {+ const allowed = toolChoiceToolPredicate({ allowedTools: ["shared_name"], mode: "auto" }, tools);+ filtered = tools.filter(allowed);+ }+ finally {+ Object.defineProperty(Array.prototype, Symbol.iterator, arrayIterator);+ }+ expect(filtered).toEqual([]);+ expect(catalogReads).toBeLessThanOrEqual(size * 2);+ expect(ambiguousCandidateIterations).toBe(0);+});+test("public candidate lookups rebuild after a mutable caller changes its catalog", () => {+ const tools = [{ namespace: "first", name: "shared", description: "", parameters: {} }];+ const firstLookup = toolChoiceCandidates(tools, "shared");+ expect(firstLookup).toHaveLength(1);+ expect(firstLookup[0]).toBe(tools[0]);+ tools.push({ namespace: "second", name: "shared", description: "", parameters: {} });+ const secondLookup = toolChoiceCandidates(tools, "shared");+ expect(secondLookup).toHaveLength(2);+ expect(secondLookup[0]).toBe(tools[0]);+ expect(secondLookup[1]).toBe(tools[1]);+ const allowed = toolChoiceToolPredicate({ allowedTools: ["shared"], mode: "auto" }, tools);+ expect(tools.filter(allowed)).toEqual([]);+});+test("a compiled resolver fails closed when its catalog objects change", () => {+ const tools = [{ namespace: "stable", name: "shared", description: "", parameters: {} }];+ const allowed = toolChoiceToolPredicate({ allowedTools: ["shared"], mode: "auto" }, tools);+ tools[0].name = "changed_after_compile";+ tools.push({ namespace: "late", name: "shared", description: "", parameters: {} });+ expect(tools.filter(allowed)).toEqual([]);+});diff --git a/packages/model-compat/src/__tests__/upstream/responses/apply-patch-envelope.test.js b/packages/model-compat/src/__tests__/upstream/responses/apply-patch-envelope.test.jsnew file mode 100644index 0000000000..9c99e914eb--- /dev/null+++ b/packages/model-compat/src/__tests__/upstream/responses/apply-patch-envelope.test.js@@ -0,0 +1,168 @@+import { describe, expect, test } from "vitest";+import { isCompletePatchEnvelope, mayBecomePatchEnvelope, normalizeApplyPatchDelimiters, repairFreeformToolInput, } from "../../../upstream/responses/apply-patch-envelope";+import { compileCodeModeHelperInput, resolveCodeModeHelperName } from "../../../upstream/responses/code-mode-helper-compat";+const DECORATED_PATCH = `*** Begin Patch ***+*** Update File: README.md+@@+-old++new+*** End Patch ***`;+const CANONICAL_PATCH = `*** Begin Patch+*** Update File: README.md+@@+-old++new+*** End Patch`;+describe("apply_patch envelope repair", () => {+ test("repairs only the outer lines of a complete top-level apply_patch payload", () => {+ expect(repairFreeformToolInput(DECORATED_PATCH, "apply_patch")).toBe(CANONICAL_PATCH);+ expect(normalizeApplyPatchDelimiters(DECORATED_PATCH)).toBe(CANONICAL_PATCH);+ });+ test("preserves CRLF and an existing trailing newline", () => {+ const decorated = DECORATED_PATCH.replaceAll("\n", "\r\n") + "\r\n";+ const canonical = CANONICAL_PATCH.replaceAll("\n", "\r\n") + "\r\n";+ expect(repairFreeformToolInput(decorated, "apply_patch")).toBe(canonical);+ });+ test("unwraps the function-call {input} wrapper before top-level repair", () => {+ expect(repairFreeformToolInput(JSON.stringify({ input: DECORATED_PATCH }), "apply_patch")).toBe(CANONICAL_PATCH);+ });+ test("repairs only bare and reserved-functions apply_patch grammars", () => {+ const wrapped = JSON.stringify({ input: DECORATED_PATCH });+ expect(repairFreeformToolInput(wrapped, "apply_patch", "functions")).toBe(CANONICAL_PATCH);+ expect(repairFreeformToolInput(wrapped, "apply_patch", "mcp")).toBe(DECORATED_PATCH);+ });+ test("keeps exec JavaScript strings, comments, templates, and regexes byte-identical", () => {+ const cases = [+ 'const sample = "tools.apply_patch({ input: patchText })";',+ "// tools.apply_patch({ input: patchText })\nconst ok = true;",+ "const source = `await tools.apply_patch(\\`*** Begin Patch ***\\`)`;",+ "const marker = /\\*\\*\\* Begin Patch \\*\\*\\*/;",+ `await tools.apply_patch(\`*** Begin Patch ***+*** Update File: README.md+@@+-old++new+*** End Patch ***\`)`,+ ];+ for (const source of cases) {+ expect(repairFreeformToolInput(source, "exec")).toBe(source);+ }+ });+ // `repairFreeformToolInput` itself never compiles: exec bodies come back byte-identical.+ // Recognizing a raw envelope as an implicit apply_patch call is a separate decision made+ // one level up, by `resolveCodeModeHelperName` at the bridge and native-restore+ // boundaries. See devlog/_plan/260905_apply_patch_envelope_gap.+ test("repairFreeformToolInput never compiles a raw exec body into a helper call", () => {+ expect(repairFreeformToolInput(DECORATED_PATCH, "exec")).toBe(DECORATED_PATCH);+ expect(repairFreeformToolInput(JSON.stringify({ input: DECORATED_PATCH }), "exec")).toBe(DECORATED_PATCH);+ });+ test("does not rewrite decorated delimiter text inside patch-file content", () => {+ const body = `*** Begin Patch+*** Update File: docs.md+@@+-old++A patch starts with *** Begin Patch *** if you add extra stars.++Do not rewrite *** End Patch *** in file content.+*** End Patch`;+ expect(repairFreeformToolInput(body, "apply_patch")).toBe(body);+ expect(normalizeApplyPatchDelimiters(body)).toBe(body);+ });+ test("leaves incomplete, prefixed, suffixed, and non-operation envelopes alone", () => {+ const cases = [+ "*** Begin Patch ***",+ `prefix\n${DECORATED_PATCH}`,+ `${DECORATED_PATCH}\nsuffix`,+ "*** Begin Patch ***\nplain text\n*** End Patch ***",+ ];+ for (const source of cases) {+ expect(repairFreeformToolInput(source, "apply_patch")).toBe(source);+ }+ });+ test("repairs one decorated outer line without touching an already canonical peer", () => {+ const decoratedBegin = CANONICAL_PATCH.replace("*** Begin Patch", "*** Begin Patch ***");+ const decoratedEnd = CANONICAL_PATCH.replace("*** End Patch", "*** End Patch ***");+ expect(repairFreeformToolInput(decoratedBegin, "apply_patch")).toBe(CANONICAL_PATCH);+ expect(repairFreeformToolInput(decoratedEnd, "apply_patch")).toBe(CANONICAL_PATCH);+ });+ test("unwraps other freeform tools without changing their body", () => {+ const body = "*** Begin Patch ***";+ expect(repairFreeformToolInput(JSON.stringify({ input: body }), "render_diagram")).toBe(body);+ expect(repairFreeformToolInput(body, "")).toBe(body);+ });+});+// A complete envelope submitted as the `exec` body is never valid JavaScript, so the+// callers retarget it to the apply_patch helper. See+// devlog/_plan/260905_apply_patch_envelope_gap.+describe("raw exec patch envelope recognition", () => {+ // Recognition requires a genuine code-mode catalog, not merely a tool named `exec`.+ const CODE_MODE = new Set(["exec"]);+ const ADD = "*** Begin Patch\n*** Add File: a.txt\n+hi\n*** End Patch";+ const DELETE = "*** Begin Patch\n*** Delete File: a.txt\n*** End Patch";+ test("accepts a complete envelope for every file operation, canonical or decorated", () => {+ for (const body of [CANONICAL_PATCH, DECORATED_PATCH, ADD, DELETE]) {+ expect(isCompletePatchEnvelope(body)).toBe(true);+ expect(resolveCodeModeHelperName(undefined, "exec", body, undefined, CODE_MODE)).toBe("apply_patch");+ }+ });+ test("compiles a recognized envelope into an apply_patch helper call", () => {+ const helper = resolveCodeModeHelperName(undefined, "exec", DECORATED_PATCH, undefined, CODE_MODE);+ const source = compileCodeModeHelperInput(DECORATED_PATCH, helper);+ expect(source).toContain("await tools.apply_patch(");+ // The patch travels as a JSON string argument, never as interpolated source, and the+ // decorated delimiters are normalized on the way through.+ expect(source).toContain(JSON.stringify(CANONICAL_PATCH));+ expect(source).not.toContain("*** Begin Patch ***");+ });+ test("refuses JavaScript that merely mentions an envelope", () => {+ const cases = [+ "const sample = \"tools.apply_patch({ input: patchText })\";",+ "// tools.apply_patch({ input: patchText })\nconst ok = true;",+ "const marker = /\\*\\*\\* Begin Patch \\*\\*\\*/;",+ "const a = 1;\n/*** Begin Patch ***/\nawait tools.exec_command({ cmd: \"id\" });",+ "await tools.apply_patch(`" + DECORATED_PATCH + "`);",+ ];+ for (const source of cases) {+ expect(isCompletePatchEnvelope(source)).toBe(false);+ expect(resolveCodeModeHelperName(undefined, "exec", source, undefined, CODE_MODE)).toBeUndefined();+ expect(repairFreeformToolInput(source, "exec")).toBe(source);+ }+ });+ test("refuses incomplete, prefixed, suffixed, and operation-free envelopes", () => {+ const cases = [+ "*** Begin Patch ***",+ `prefix\n${DECORATED_PATCH}`,+ `${DECORATED_PATCH}\nsuffix`,+ "*** Begin Patch ***\nplain text\n*** End Patch ***",+ "",+ ];+ for (const source of cases) {+ expect(isCompletePatchEnvelope(source)).toBe(false);+ expect(resolveCodeModeHelperName(undefined, "exec", source, undefined, CODE_MODE)).toBeUndefined();+ }+ });+ test("stays scoped to a bare exec call and never double-wraps a named helper", () => {+ expect(resolveCodeModeHelperName(undefined, "exec", CANONICAL_PATCH, "mcp", CODE_MODE)).toBeUndefined();+ expect(resolveCodeModeHelperName(undefined, "apply_patch", CANONICAL_PATCH, undefined, CODE_MODE)).toBeUndefined();+ expect(resolveCodeModeHelperName(undefined, "render_diagram", CANONICAL_PATCH, undefined, CODE_MODE)).toBeUndefined();+ // An already-resolved name-based helper wins and is returned unchanged.+ expect(resolveCodeModeHelperName("write_stdin", "exec", CANONICAL_PATCH, undefined, CODE_MODE)).toBe("write_stdin");+ });+ // `exec` beside a bare shell bridge is the flat-catalog shape, not code mode: there a+ // caller-defined `exec` may legitimately take patch text.+ test("refuses a catalog that is not genuine code mode", () => {+ for (const declared of [undefined, new Set(), new Set(["exec", "exec_command"]), new Set(["exec", "shell_command"]), new Set(["apply_patch"])]) {+ expect(resolveCodeModeHelperName(undefined, "exec", CANONICAL_PATCH, undefined, declared)).toBeUndefined();+ }+ });+ test("unwraps the {input} function wrapper before recognizing the envelope", () => {+ expect(resolveCodeModeHelperName(undefined, "exec", JSON.stringify({ input: DECORATED_PATCH }), undefined, CODE_MODE)).toBe("apply_patch");+ });+ test("holds a streaming buffer that could still become an envelope", () => {+ for (const partial of ["*** Be", "*** Begin Patch", "*** Begin Patch\n*** Add File: a.txt"]) {+ expect(mayBecomePatchEnvelope(partial)).toBe(true);+ }+ for (const partial of ["", "const x = 1;", "await tools.exec_command({"]) {+ expect(mayBecomePatchEnvelope(partial)).toBe(false);+ }+ });+});diff --git a/packages/model-compat/src/__tests__/upstream/responses/custom-tool-compat.test.js b/packages/model-compat/src/__tests__/upstream/responses/custom-tool-compat.test.jsnew file mode 100644index 0000000000..48f3d91b1d--- /dev/null+++ b/packages/model-compat/src/__tests__/upstream/responses/custom-tool-compat.test.js@@ -0,0 +1,133 @@+import { describe, expect, test } from "vitest";+import { rewriteRoutedCustomToolsForUpstream } from "../../../upstream/responses/custom-tool-compat";+function convertedInputDescription(name) {+ const result = rewriteRoutedCustomToolsForUpstream({+ tools: [{ type: "custom", name, description: "client tool", format: { type: "text" } }],+ });+ const body = result.body;+ return body.tools?.[0]?.parameters?.properties?.input?.description;+}+describe("routed custom-tool compatibility", () => {+ test.each([+ ["absent", undefined],+ ["true", true],+ ])("keeps apply_patch byte-identical when custom-tool support is %s", (_label, support) => {+ const raw = {+ tools: [{ type: "custom", name: "apply_patch", description: "Apply a patch", format: { type: "text" } }],+ input: [+ { type: "custom_tool_call", id: "ctc_patch", call_id: "call_patch", name: "apply_patch", input: "noop" },+ { type: "custom_tool_call_output", call_id: "call_patch", output: "done" },+ ],+ };+ const before = JSON.stringify(raw);+ const rewritten = rewriteRoutedCustomToolsForUpstream(raw, support);+ expect(rewritten.body).toBe(raw);+ expect(JSON.stringify(rewritten.body)).toBe(before);+ expect(rewritten.names).toEqual(new Set());+ expect(rewritten.repairNames).toEqual(new Set(["apply_patch"]));+ });+ test("repairs apply_patch only when bare or in the reserved functions namespace", () => {+ const rewritten = rewriteRoutedCustomToolsForUpstream({+ tools: [+ {+ type: "namespace",+ name: "mcp",+ tools: [{ type: "custom", name: "apply_patch", description: "Remote patch grammar" }],+ },+ {+ type: "namespace",+ name: "functions",+ tools: [{ type: "custom", name: "apply_patch", description: "Built-in patch grammar" }],+ },+ ],+ });+ expect(rewritten.repairNames).toEqual(new Set(["apply_patch"]));+ });+ test.each([+ ["none", "none"],+ ["a forced other tool", { type: "function", name: "ordinary" }],+ ["a same-name function selector", { type: "function", name: "apply_patch" }],+ ["an allowlist exclusion", {+ type: "allowed_tools",+ mode: "required",+ tools: [{ type: "function", name: "ordinary" }],+ }],+ ["a same-name function allowlist", {+ type: "allowed_tools",+ mode: "required",+ tools: [{ type: "function", name: "apply_patch" }],+ }],+ ])("does not arm apply_patch repair under %s", (_label, toolChoice) => {+ const rewritten = rewriteRoutedCustomToolsForUpstream({+ tools: [+ { type: "custom", name: "apply_patch", description: "Apply a patch", format: { type: "text" } },+ { type: "function", name: "ordinary", parameters: { type: "object" } },+ ],+ tool_choice: toolChoice,+ });+ expect(rewritten.repairNames).toEqual(new Set());+ });+ test.each([+ { type: "custom", name: "apply_patch" },+ {+ type: "allowed_tools",+ mode: "required",+ tools: [{ type: "custom", name: "apply_patch" }],+ },+ ])("arms apply_patch repair when the selector authorizes it", toolChoice => {+ const rewritten = rewriteRoutedCustomToolsForUpstream({+ tools: [{ type: "custom", name: "apply_patch", description: "Apply a patch", format: { type: "text" } }],+ tool_choice: toolChoice,+ });+ expect(rewritten.repairNames).toEqual(new Set(["apply_patch"]));+ });+ test("lowers apply_patch declarations and replay items on an explicit capability denial", () => {+ const raw = {+ tools: [{ type: "custom", name: "apply_patch", description: "Apply a patch", format: { type: "text" } }],+ input: [+ { type: "custom_tool_call", id: "ctc_patch", call_id: "call_patch", name: "apply_patch", input: "noop" },+ { type: "custom_tool_call_output", call_id: "call_patch", output: "done" },+ ],+ };+ const rewritten = rewriteRoutedCustomToolsForUpstream(raw, false);+ const body = rewritten.body;+ expect(rewritten.names).toEqual(new Set(["apply_patch"]));+ expect(rewritten.repairNames).toEqual(new Set());+ expect(body.tools[0]).toMatchObject({+ type: "function",+ name: "apply_patch",+ parameters: { required: ["input"] },+ });+ expect(body.input[0]).toMatchObject({+ type: "function_call",+ call_id: "call_patch",+ name: "apply_patch",+ arguments: JSON.stringify({ input: "noop" }),+ });+ expect(body.input[1]).toMatchObject({+ type: "function_call_output",+ call_id: "call_patch",+ output: "done",+ });+ });+ test.each([undefined, true, false])("keeps lowering other custom tools when support is %p", support => {+ const rewritten = rewriteRoutedCustomToolsForUpstream({+ tools: [{ type: "custom", name: "review_patch", description: "Review", format: { type: "text" } }],+ }, support);+ const body = rewritten.body;+ expect(body.tools[0]).toMatchObject({ type: "function", name: "review_patch" });+ expect(rewritten.names).toEqual(new Set(["review_patch"]));+ expect(rewritten.repairNames).toEqual(new Set());+ });+ test("converted exec preserves the JavaScript input contract", () => {+ const description = convertedInputDescription("exec");+ expect(description).toContain("JavaScript");+ expect(description).toContain("tools.exec_command");+ expect(description).toContain("text(...)");+ expect(description).toContain("do not provide a bare shell command");+ });+ test("other converted custom tools keep the generic raw-input contract", () => {+ expect(convertedInputDescription("review_patch"))+ .toBe("Raw input for this client-executed custom tool.");+ });+});diff --git a/packages/model-compat/src/__tests__/upstream/responses/legacy-shell-compat.test.js b/packages/model-compat/src/__tests__/upstream/responses/legacy-shell-compat.test.jsnew file mode 100644index 0000000000..cd9dc93eb5--- /dev/null+++ b/packages/model-compat/src/__tests__/upstream/responses/legacy-shell-compat.test.js@@ -0,0 +1,90 @@+import { describe, expect, test } from "vitest";+import { compileCodeModeHelperInput } from "../../../upstream/responses/code-mode-helper-compat";+const AsyncFunction = Object.getPrototypeOf(async function () { }).constructor;+describe("code-mode helper compatibility", () => {+ test("exec_command arguments remain data when generated JavaScript runs", async () => {+ const command = "printf '%s' \"$HOME\"; }); throw new Error('escaped') //";+ const source = compileCodeModeHelperInput(JSON.stringify({ cmd: command, workdir: "/tmp", yield_time_ms: 1_000 }), "exec_command");+ let received;+ let output;+ const run = new AsyncFunction("tools", "text", source);+ await run({+ exec_command: async (args) => {+ received = args;+ return { exit_code: 0, output: "ok" };+ },+ }, (value) => { output = value; });+ expect(received).toEqual({ cmd: command, workdir: "/tmp", yield_time_ms: 1_000 });+ expect(output).toEqual({ exit_code: 0, output: "ok" });+ });+ test("shell_command maps command to the nested exec cmd field", async () => {+ const source = compileCodeModeHelperInput(JSON.stringify({ command: "pwd", workdir: "/tmp" }), "shell_command");+ let received;+ const run = new AsyncFunction("tools", "text", source);+ await run({+ exec_command: async (args) => {+ received = args;+ return "ok";+ },+ }, () => { });+ expect(received).toEqual({ workdir: "/tmp", cmd: "pwd" });+ });+ test("write_stdin arguments remain data and target the nested helper", async () => {+ const args = {+ session_id: 17,+ chars: "`); throw new Error('escaped') //",+ yield_time_ms: 1_000,+ };+ const source = compileCodeModeHelperInput(JSON.stringify(args), "write_stdin");+ let received;+ let output;+ const run = new AsyncFunction("tools", "text", source);+ await run({+ write_stdin: async (value) => {+ received = value;+ return { output: "more" };+ },+ }, (value) => { output = value; });+ expect(received).toEqual(args);+ expect(output).toEqual({ output: "more" });+ });+ test("apply_patch text remains one string argument", async () => {+ const patch = "*** Begin Patch\n*** Add File: note.txt\n+`); throw new Error('escaped')\n*** End Patch";+ const source = compileCodeModeHelperInput(patch, "apply_patch");+ let received;+ const run = new AsyncFunction("tools", "text", source);+ await run({+ apply_patch: async (input) => {+ received = input;+ return "done";+ },+ }, () => { });+ expect(received).toBe(patch);+ });+ test("apply_patch normalizes decorated outer delimiters before execution", async () => {+ const decorated = "*** Begin Patch ***\n*** Add File: note.txt\n+hello\n*** End Patch ***";+ const canonical = "*** Begin Patch\n*** Add File: note.txt\n+hello\n*** End Patch";+ let received;+ const run = new AsyncFunction("tools", "text", compileCodeModeHelperInput(JSON.stringify({ input: decorated }), "apply_patch"));+ await run({+ apply_patch: async (input) => {+ received = input;+ return "done";+ },+ }, () => { });+ expect(received).toBe(canonical);+ });+ test("invalid structured shell input remains data instead of becoming JavaScript", async () => {+ for (const input of ["{not-json", "[]"]) {+ let received;+ const run = new AsyncFunction("tools", "text", compileCodeModeHelperInput(input, "exec_command"));+ await run({+ exec_command: async (args) => {+ received = args;+ return "rejected";+ },+ }, () => { });+ expect(received).toEqual(input === "[]" ? [] : input);+ }+ });+});diff --git a/packages/model-compat/src/__tests__/upstream/responses/namespace-tool-compat.test.js b/packages/model-compat/src/__tests__/upstream/responses/namespace-tool-compat.test.jsnew file mode 100644index 0000000000..bf5c66df80--- /dev/null+++ b/packages/model-compat/src/__tests__/upstream/responses/namespace-tool-compat.test.js@@ -0,0 +1,529 @@+import { describe, expect, test } from "vitest";+import { restoreRoutedCustomCalls, rewriteRoutedCustomToolsForUpstream } from "../../../upstream/responses/custom-tool-compat";+import { createRoutedNamespaceCallRestoreRewrite, restoreRoutedNamespaceCalls, restoreRoutedNamespaceCallsInJson, rewriteRoutedNamespaceToolsForUpstream, } from "../../../upstream/responses/namespace-tool-compat";+describe("Responses namespace tool compatibility", () => {+ test("flattens builtin and routed namespaces across declarations, selectors, and replay", () => {+ const rewritten = rewriteRoutedNamespaceToolsForUpstream({+ model: "routed-model",+ tools: [+ {+ type: "namespace",+ name: "functions",+ tools: [{ type: "custom", name: "exec", description: "run" }],+ },+ {+ type: "namespace",+ name: "collaboration",+ tools: [{ type: "function", name: "spawn_agent", parameters: {} }],+ },+ ],+ input: [+ {+ type: "function_call",+ namespace: "collaboration",+ name: "spawn_agent",+ call_id: "call_spawn",+ arguments: "{}",+ },+ {+ type: "custom_tool_call",+ namespace: "functions",+ name: "exec",+ call_id: "call_exec",+ input: "text(true)",+ },+ ],+ tool_choice: {+ type: "allowed_tools",+ mode: "required",+ tools: [+ { type: "function", namespace: "collaboration", name: "spawn_agent" },+ { type: "custom", namespace: "functions", name: "exec" },+ ],+ },+ });+ const body = rewritten.body;+ expect(body.tools).toEqual([+ { type: "custom", name: "exec", description: "run" },+ { type: "function", name: "collaboration__spawn_agent", parameters: {} },+ ]);+ expect(body.input[0]).toMatchObject({ name: "collaboration__spawn_agent", call_id: "call_spawn" });+ expect(body.input[0]).not.toHaveProperty("namespace");+ expect(body.input[1]).toMatchObject({ name: "exec", call_id: "call_exec" });+ expect(body.input[1]).not.toHaveProperty("namespace");+ expect(body.tool_choice.tools).toEqual([+ { type: "function", name: "collaboration__spawn_agent" },+ { type: "custom", name: "exec" },+ ]);+ expect([...rewritten.aliases]).toEqual([+ ["collaboration__spawn_agent", { namespace: "collaboration", name: "spawn_agent", kind: "function" }],+ ["collaboration.spawn_agent", { namespace: "collaboration", name: "spawn_agent", kind: "function" }],+ ]);+ });+ test("rewrites a unique bare selector but leaves an ambiguous one unchanged", () => {+ const unique = rewriteRoutedNamespaceToolsForUpstream({+ tools: [{+ type: "namespace",+ name: "one",+ tools: [{ type: "function", name: "read" }],+ }],+ tool_choice: { type: "function", name: "read" },+ }).body;+ expect(unique.tool_choice.name).toBe("one__read");+ const ambiguous = rewriteRoutedNamespaceToolsForUpstream({+ tools: [+ { type: "namespace", name: "one", tools: [{ type: "function", name: "read" }] },+ { type: "namespace", name: "two", tools: [{ type: "function", name: "read" }] },+ ],+ tool_choice: { type: "function", name: "read" },+ }).body;+ expect(ambiguous.tool_choice.name).toBe("read");+ const directCollision = rewriteRoutedNamespaceToolsForUpstream({+ tools: [+ { type: "function", name: "read" },+ { type: "namespace", name: "workspace", tools: [{ type: "function", name: "read" }] },+ ],+ tool_choice: { type: "function", name: "read" },+ }).body;+ expect(directCollision.tools.map(tool => tool.name)).toEqual(["read", "workspace__read"]);+ expect(directCollision.tool_choice.name).toBe("read");+ });+ test("only arms response aliases authorized by tool_choice", () => {+ const tools = [{+ type: "namespace",+ name: "collaboration",+ tools: [+ { type: "function", name: "safe" },+ { type: "function", name: "excluded" },+ ],+ }];+ const allowed = rewriteRoutedNamespaceToolsForUpstream({+ tools,+ tool_choice: {+ type: "allowed_tools",+ mode: "required",+ tools: [{ type: "function", namespace: "collaboration", name: "safe" }],+ },+ });+ expect([...allowed.aliases]).toEqual([+ ["collaboration__safe", { namespace: "collaboration", name: "safe", kind: "function" }],+ ["collaboration.safe", { namespace: "collaboration", name: "safe", kind: "function" }],+ ]);+ expect(restoreRoutedNamespaceCalls({+ type: "function_call",+ name: "collaboration__excluded",+ }, allowed.aliases).changed).toBe(false);+ expect(rewriteRoutedNamespaceToolsForUpstream({+ tools,+ tool_choice: { type: "function", namespace: "collaboration", name: "safe" },+ }).aliases.has("collaboration__excluded")).toBe(false);+ expect(rewriteRoutedNamespaceToolsForUpstream({ tools, tool_choice: "none" }).aliases.size).toBe(0);+ });+ // The authorization boundary is per-request, and `allowed_tools` is where it was+ // leaking: entries are typed `{type: string}` by the schema, so the accepted set is+ // open-ended, and matching on `name` alone let a selector for a DIFFERENT KIND of+ // tool authorize a client namespace function call.+ //+ // This is not a naming nit. The upstream sees every flattened declaration even when+ // `tool_choice` narrows what may be called, so a non-canonical upstream can answer+ // with `{type: "function_call", name: "<wire-name>"}`; if the alias survived, the+ // restore path rewrites it into `{namespace, name}` and the client executes a tool+ // the caller never permitted. The undeclared-tool guard does not catch it either —+ // that guard authorizes from the declared catalog, not from `tool_choice`.+ describe("allowed_tools authorization is restricted by tool type", () => {+ const namespaceTools = [{+ type: "namespace",+ name: "collaboration",+ tools: [{ type: "function", name: "safe" }],+ }];+ const wireName = "collaboration__safe";+ // Every non-function/custom kind the runtime and schema know about, plus an+ // unknown future one. The whitelist has to close all of them, including kinds+ // nobody has written yet — which is exactly why it is a whitelist.+ test.each([+ "file_search",+ "web_search",+ "web_search_preview",+ "computer_use",+ "computer_use_preview",+ "code_interpreter",+ "image_generation",+ "image_gen",+ "mcp",+ "tool_search",+ "local_shell",+ "x_search",+ "namespace",+ "some_future_tool_kind",+ ])("a %s entry naming the wire tool authorizes nothing", kind => {+ const { aliases } = rewriteRoutedNamespaceToolsForUpstream({+ tools: namespaceTools,+ tool_choice: { type: "allowed_tools", mode: "required", tools: [{ type: kind, name: wireName }] },+ });+ expect(aliases.size).toBe(0);+ // The map is the whole authorization surface, so an upstream call carrying that+ // wire name must stay unrestored rather than becoming a namespaced client call.+ const restored = restoreRoutedNamespaceCalls({ type: "function_call", name: wireName }, aliases);+ expect(restored.changed).toBe(false);+ expect(restored.value.namespace).toBeUndefined();+ });+ test.each(["function", "custom"])("a %s entry authorizes a tool declared that same kind", kind => {+ const { aliases } = rewriteRoutedNamespaceToolsForUpstream({+ tools: [{ type: "namespace", name: "collaboration", tools: [{ type: kind, name: "safe" }] }],+ tool_choice: { type: "allowed_tools", mode: "required", tools: [{ type: kind, name: wireName }] },+ });+ // Proving the whitelist is not deny-all: without this, a filter that rejected+ // everything would pass every test above.+ expect(aliases.get(wireName)).toEqual({ namespace: "collaboration", name: "safe", kind });+ expect(restoreRoutedNamespaceCalls({ type: "function_call", name: wireName }, aliases).changed).toBe(true);+ });+ // A wire name says WHICH tool, not what kind of call may carry it. Selecting a+ // tool as the wrong kind is the same name/kind mismatch as selecting it with a+ // foreign selector — narrower, but the same class, and reachable because+ // `allowed_tools[].type` accepts any string.+ test.each([+ ["function", "custom"],+ ["custom", "function"],+ ])("a tool declared %s is not authorized by a %s selector", (declared, selected) => {+ const build = (choice) => rewriteRoutedNamespaceToolsForUpstream({+ tools: [{ type: "namespace", name: "collaboration", tools: [{ type: declared, name: "safe" }] }],+ tool_choice: choice,+ }).aliases;+ const viaAllowed = build({ type: "allowed_tools", mode: "required", tools: [{ type: selected, name: wireName }] });+ expect(viaAllowed.size).toBe(0);+ expect(restoreRoutedNamespaceCalls({ type: "function_call", name: wireName }, viaAllowed).changed).toBe(false);+ // The forced-selector branch has to agree, or the narrowing only holds for+ // one of the two shapes a caller can write.+ const viaForced = build({ type: selected, name: wireName });+ expect(viaForced.size).toBe(0);+ });+ test("a foreign entry cannot ride alongside an authorized one", () => {+ const { aliases } = rewriteRoutedNamespaceToolsForUpstream({+ tools: [{+ type: "namespace",+ name: "collaboration",+ tools: [{ type: "function", name: "safe" }, { type: "function", name: "excluded" }],+ }],+ tool_choice: {+ type: "allowed_tools",+ mode: "required",+ tools: [+ { type: "function", name: wireName },+ { type: "file_search", name: "collaboration__excluded" },+ ],+ },+ });+ expect([...aliases.keys()]).toEqual([wireName, "collaboration.safe"]);+ });+ });+ test("default and absent tool_choice keep every alias", () => {+ const tools = [{+ type: "namespace",+ name: "collaboration",+ tools: [{ type: "function", name: "safe" }, { type: "function", name: "other" }],+ }];+ // Narrowing only applies when the caller actually narrowed. These three are the+ // "no restriction stated" cases and must not be collapsed by the filter.+ for (const choice of [undefined, "auto", "required"]) {+ const { aliases } = rewriteRoutedNamespaceToolsForUpstream(choice === undefined ? { tools } : { tools, tool_choice: choice });+ expect(aliases.size).toBe(4);+ }+ // A top-level selector for another tool kind states a restriction that no+ // namespace call satisfies, so it authorizes nothing.+ expect(rewriteRoutedNamespaceToolsForUpstream({+ tools,+ tool_choice: { type: "file_search" },+ }).aliases.size).toBe(0);+ });+ // A selector's `namespace` is either absent — meaning "unqualified, resolve the bare+ // name" — or a string naming the group. A present-but-malformed value is neither, and+ // treating it as absent let it resolve to a namespace wire name and authorize an alias+ // the caller never qualified. Fail closed instead: an unqualified selector is a+ // deliberate shape, a malformed one is not.+ describe("a malformed namespace field authorizes nothing", () => {+ const namespaceTools = [{+ type: "namespace",+ name: "collaboration",+ tools: [{ type: "function", name: "safe" }],+ }];+ const wireName = "collaboration__safe";+ test.each([+ ["a number", 1],+ ["null", null],+ ["an object", {}],+ ["an array", ["collaboration"]],+ ["a boolean", true],+ ])("a forced selector whose namespace is %s", (_label, namespace) => {+ const { aliases } = rewriteRoutedNamespaceToolsForUpstream({+ tools: namespaceTools,+ tool_choice: { type: "function", namespace, name: "safe" },+ });+ expect(aliases.size).toBe(0);+ expect(restoreRoutedNamespaceCalls({ type: "function_call", name: wireName }, aliases).changed).toBe(false);+ });+ test("an allowed_tools entry whose namespace is malformed", () => {+ const { aliases } = rewriteRoutedNamespaceToolsForUpstream({+ tools: namespaceTools,+ tool_choice: { type: "allowed_tools", mode: "required", tools: [{ type: "function", namespace: 1, name: "safe" }] },+ });+ expect(aliases.size).toBe(0);+ });+ // Refusing to REWRITE a malformed selector is not enough on its own. If its name is+ // already the flattened wire name, it matches the alias map exactly and arms it+ // anyway — so authorization has to reject the selector itself, whatever name it+ // carries. Both selector shapes, because a caller can write either.+ test("a malformed selector already using the flattened wire name authorizes nothing", () => {+ const forced = rewriteRoutedNamespaceToolsForUpstream({+ tools: namespaceTools,+ tool_choice: { type: "function", namespace: 1, name: wireName },+ });+ expect(forced.aliases.size).toBe(0);+ expect(restoreRoutedNamespaceCalls({ type: "function_call", name: wireName }, forced.aliases).changed).toBe(false);+ const allowed = rewriteRoutedNamespaceToolsForUpstream({+ tools: namespaceTools,+ tool_choice: { type: "allowed_tools", mode: "required", tools: [{ type: "function", namespace: 1, name: wireName }] },+ });+ expect(allowed.aliases.size).toBe(0);+ });+ test("an unqualified selector using the wire name still authorizes", () => {+ // The legitimate shape this must not break: no namespace field at all, naming+ // the flattened tool directly.+ const { aliases } = rewriteRoutedNamespaceToolsForUpstream({+ tools: namespaceTools,+ tool_choice: { type: "function", name: wireName },+ });+ expect(aliases.get(wireName)).toBeDefined();+ });+ test("a correctly qualified selector still authorizes, so this is not deny-all", () => {+ const { aliases } = rewriteRoutedNamespaceToolsForUpstream({+ tools: namespaceTools,+ tool_choice: { type: "function", namespace: "collaboration", name: "safe" },+ });+ expect(aliases.get(wireName)).toEqual({ namespace: "collaboration", name: "safe", kind: "function" });+ });+ test("an unqualified selector keeps resolving by bare name", () => {+ // The absent case is the one legitimate reason the fallback exists; narrowing+ // malformed values must not take it away.+ const { aliases } = rewriteRoutedNamespaceToolsForUpstream({+ tools: namespaceTools,+ tool_choice: { type: "function", name: "safe" },+ });+ expect(aliases.get(wireName)).toBeDefined();+ });+ });+ test("fails closed when flattening would collide with a declared wire name", () => {+ expect(() => rewriteRoutedNamespaceToolsForUpstream({+ tools: [+ { type: "function", name: "workspace__read" },+ { type: "namespace", name: "workspace", tools: [{ type: "function", name: "read" }] },+ ],+ })).toThrow('namespace tool wire-name collision for "workspace__read"');+ });+ // Relaying `type: "namespace"` is what the strict gateway rejects, and it rejects the request+ // rather than the tool — so a group this layer cannot represent costs every tool in the turn.+ // Dropping what cannot be expressed costs only that.+ test("lowers every namespace group rather than relaying the private shape", () => {+ const body = rewriteRoutedNamespaceToolsForUpstream({+ tools: [+ { type: "namespace", name: "empty", tools: [] },+ {+ type: "namespace",+ name: "partial",+ tools: [+ { type: "namespace", name: "nested", tools: [] },+ { type: "function", name: "", parameters: {} },+ { type: "function", name: "ok", parameters: {} },+ ],+ },+ ],+ }).body;+ expect(body.tools).toEqual([{ type: "function", name: "partial__ok", parameters: {} }]);+ expect(body.tools.some(tool => tool.type === "namespace")).toBe(false);+ });+ // The identity key joins namespace and name with NUL, so a name carrying one could otherwise+ // forge another tool's identity and silently take over its wire name.+ test("drops children whose names cannot become a wire name", () => {+ const NUL = String.fromCharCode(0);+ const body = rewriteRoutedNamespaceToolsForUpstream({+ tools: [+ { type: "namespace", name: "a", tools: [{ type: "function", name: `b${NUL}c` }] },+ { type: "namespace", name: `a${NUL}b`, tools: [{ type: "function", name: "c" }] },+ { type: "namespace", name: "ok", tools: [{ type: "function", name: "run" }] },+ ],+ }).body;+ expect(body.tools).toEqual([{ type: "function", name: "ok__run" }]);+ });+ // `buildTools` flattens the reserved group without a namespace, so the parser treats these as one+ // logical tool and tolerates the duplicate; `promoteClientLoadedTools` produces exactly this shape.+ test("treats a bare declaration and a functions child of the same name as one tool", () => {+ const rewritten = rewriteRoutedNamespaceToolsForUpstream({+ tools: [+ { type: "function", name: "exec", parameters: {} },+ { type: "namespace", name: "functions", tools: [{ type: "function", name: "exec", parameters: {} }] },+ ],+ });+ const body = rewritten.body;+ expect(body.tools).toEqual([{ type: "function", name: "exec", parameters: {} }]);+ expect([...rewritten.aliases]).toEqual([]);+ });+ test("chooses the bare declaration regardless of which tool container comes first", () => {+ const bare = {+ type: "function",+ name: "exec",+ description: "canonical bare declaration",+ parameters: { type: "object", properties: { input: { type: "string" } } },+ };+ const functionsGroup = {+ type: "namespace",+ name: "functions",+ tools: [{+ type: "function",+ name: "exec",+ description: "namespace duplicate",+ parameters: { type: "object", properties: {} },+ }],+ };+ const flatten = (bodyTools, additionalTools) => {+ const rewritten = rewriteRoutedNamespaceToolsForUpstream({+ tools: bodyTools,+ input: [{ type: "additional_tools", role: "developer", tools: additionalTools }],+ }).body;+ return [...rewritten.tools, ...rewritten.input[0].tools];+ };+ expect(flatten([bare], [functionsGroup])).toEqual([bare]);+ expect(flatten([functionsGroup], [bare])).toEqual([bare]);+ });+ // A catalog can be absent or change mid-session, but the client can still replay items this+ // layer's own restoration stamped with a private `namespace`.+ test("lowers replayed calls even when this turn declares no namespace", () => {+ const body = rewriteRoutedNamespaceToolsForUpstream({+ input: [+ { type: "function_call", namespace: "collaboration", name: "spawn_agent", call_id: "c1", arguments: "{}" },+ { type: "custom_tool_call", namespace: "functions", name: "exec", call_id: "c2", input: "run" },+ ],+ }).body;+ expect(body.input[0]).toEqual({+ type: "function_call",+ name: "collaboration__spawn_agent",+ call_id: "c1",+ arguments: "{}",+ });+ expect(body.input[1]).toEqual({+ type: "custom_tool_call",+ name: "exec",+ call_id: "c2",+ input: "run",+ });+ expect(JSON.stringify(body)).not.toContain("namespace");+ });+ // A history item records which tool actually ran. Resolving its bare name through a same-named+ // namespace child would rewrite that record on a coincidence rather than translate it.+ test("does not re-point a replayed bare-named call at a namespace child", () => {+ const body = rewriteRoutedNamespaceToolsForUpstream({+ tools: [{ type: "namespace", name: "workspace", tools: [{ type: "function", name: "read" }] }],+ input: [{ type: "function_call", name: "read", call_id: "c1", arguments: "{}" }],+ tool_choice: { type: "function", name: "read" },+ }).body;+ expect(body.input[0].name).toBe("read");+ expect(body.tool_choice.name).toBe("workspace__read");+ });+ test("restores only aliases authorized by this request in JSON and SSE payloads", () => {+ const aliases = new Map([+ ["collaboration__spawn_agent", { namespace: "collaboration", name: "spawn_agent", kind: "function" }],+ ["collaboration.spawn_agent", { namespace: "collaboration", name: "spawn_agent", kind: "function" }],+ ]);+ const payload = {+ type: "response.completed",+ response: {+ output: [+ { type: "function_call", name: "collaboration__spawn_agent", call_id: "call_1" },+ { type: "function_call", name: "untrusted__tool", call_id: "call_2" },+ ],+ },+ };+ expect(restoreRoutedNamespaceCalls(payload, aliases).value).toMatchObject({+ response: {+ output: [+ { type: "function_call", namespace: "collaboration", name: "spawn_agent" },+ { type: "function_call", name: "untrusted__tool" },+ ],+ },+ });+ const text = JSON.stringify(payload);+ expect(JSON.parse(restoreRoutedNamespaceCallsInJson(text, aliases))).toMatchObject({+ response: { output: [+ { namespace: "collaboration", name: "spawn_agent" },+ { name: "untrusted__tool" },+ ] },+ });+ expect(JSON.parse(createRoutedNamespaceCallRestoreRewrite(aliases)(text))).toMatchObject({+ response: { output: [+ { namespace: "collaboration", name: "spawn_agent" },+ { name: "untrusted__tool" },+ ] },+ });+ expect(restoreRoutedNamespaceCallsInJson("not-json", aliases)).toBe("not-json");+ });+});+describe("dotted namespace restoration uses the declaration collision boundary", () => {+ const ping = { type: "namespace", name: "mcp", tools: [{ type: "function", name: "ping", parameters: {} }] };+ test.each(["mcp.ping", "mcp__ping"])("preserves a custom call whose alias %s declares an ordinary function", name => {+ const { aliases } = rewriteRoutedNamespaceToolsForUpstream({ tools: [ping] });+ expect(aliases.get(name)?.kind).toBe("function");+ for (const namespace of [undefined, "mcp"]) {+ const call = { type: "custom_tool_call", name, call_id: "call_ping", input: "raw custom input",+ ...(namespace === undefined ? {} : { namespace }) };+ expect(restoreRoutedNamespaceCalls(call, aliases)).toEqual({ value: call, changed: false });+ expect(restoreRoutedNamespaceCalls(call, aliases).value).toBe(call);+ const text = JSON.stringify({ type: "response.completed", response: { output: [call] } }, null, 2);+ expect(restoreRoutedNamespaceCallsInJson(text, aliases)).toBe(text);+ expect(createRoutedNamespaceCallRestoreRewrite(aliases)(text)).toBe(text);+ }+ });+ test.each(["mcp.run", "mcp__run"])("restores the declared custom tool after upstream function downgrade via %s", name => {+ const downgraded = rewriteRoutedCustomToolsForUpstream({+ tools: [{ type: "namespace", name: "mcp", tools: [{ type: "custom", name: "run", description: "Run raw input" }] }],+ }, false);+ const namespaced = rewriteRoutedNamespaceToolsForUpstream(downgraded.body, downgraded.names);+ expect(namespaced.body).toMatchObject({ tools: [{ type: "function", name: "mcp__run" }] });+ expect(downgraded.names.has("mcp__run")).toBe(true);+ expect(namespaced.aliases.get(name)?.kind).toBe("custom");+ const call = { type: "function_call", name, id: "fc_run", call_id: "call_run", arguments: '{"input":"echo ready"}' };+ const restored = restoreRoutedNamespaceCalls(call, namespaced.aliases);+ expect(restored).toEqual({ changed: true, value: { ...call, name: "run", namespace: "mcp" } });+ expect(restoreRoutedCustomCalls({ output: [restored.value] }, downgraded.names).value).toEqual({+ output: [{ type: "custom_tool_call", name: "run", namespace: "mcp", id: "ctc_run", call_id: "call_run", input: "echo ready" }],+ });+ const nativeCustom = { type: "custom_tool_call", name, input: "raw custom input" };+ expect(restoreRoutedNamespaceCalls(nativeCustom, namespaced.aliases).value)+ .toEqual({ ...nativeCustom, name: "run", namespace: "mcp" });+ });+ test("restores the dotted spelling after canonical tool-choice authorization", () => {+ const { aliases } = rewriteRoutedNamespaceToolsForUpstream({ tools: [ping], tool_choice: { type: "function", namespace: "mcp", name: "ping" } });+ expect(restoreRoutedNamespaceCalls({ type: "function_call", name: "mcp.ping", arguments: "{}" }, aliases).value)+ .toEqual({ type: "function_call", name: "ping", namespace: "mcp", arguments: "{}" });+ const conflicting = { type: "function_call", name: "mcp.ping", namespace: "other", arguments: "{}" };+ expect(restoreRoutedNamespaceCalls(conflicting, aliases).value).toEqual(conflicting);+ });+ test.each([+ { type: "function", name: "mcp.ping", parameters: {} },+ { type: "namespace", name: "functions", tools: [{ type: "function", name: "mcp.ping", parameters: {} }] },+ ])("a bare canonical declaration prevents dotted shadowing in either order", collision => {+ for (const tools of [[ping, collision], [collision, ping]]) {+ const { aliases } = rewriteRoutedNamespaceToolsForUpstream({ tools, tool_choice: { type: "function", namespace: "mcp", name: "ping" } });+ expect(aliases.has("mcp.ping")).toBe(false);+ expect(aliases.has("mcp__ping")).toBe(true);+ }+ });+ test("different dotted coordinates remain ambiguous and canonical forms remain distinct", () => {+ for (const tools of [+ [{ type: "namespace", name: "a.b", tools: [{ type: "function", name: "c" }] }, { type: "namespace", name: "a", tools: [{ type: "function", name: "b.c" }] }],+ [{ type: "namespace", name: "a", tools: [{ type: "function", name: "b.c" }] }, { type: "namespace", name: "a.b", tools: [{ type: "function", name: "c" }] }],+ ]) {+ const { aliases } = rewriteRoutedNamespaceToolsForUpstream({ tools });+ expect(aliases.has("a.b.c")).toBe(false);+ expect(aliases.has("a.b__c")).toBe(true);+ expect(aliases.has("a__b.c")).toBe(true);+ }+ });+});diff --git a/packages/model-compat/src/__tests__/upstream/responses/responses-field-backfill.test.js b/packages/model-compat/src/__tests__/upstream/responses/responses-field-backfill.test.jsnew file mode 100644index 0000000000..b4cde35893--- /dev/null+++ b/packages/model-compat/src/__tests__/upstream/responses/responses-field-backfill.test.js@@ -0,0 +1,680 @@+import { describe, expect, test } from "vitest";+import { createResponsesFieldBackfillBlockRewrite, backfillResponsesFieldsJson, } from "../../../upstream/server/responses/responses-field-backfill";+const rewrite = createResponsesFieldBackfillBlockRewrite();+function apply(block) {+ return [...rewrite(block)];+}+function sseBlock(data) {+ return `event: ${data.type}\ndata: ${JSON.stringify(data)}\n\n`;+}+function parseData(blocks) {+ return blocks.map((b) => {+ const match = b.match(/^data: (.+)$/m);+ return JSON.parse(match[1]);+ });+}+describe("responses-field-backfill", () => {+ test("adds annotations to output_item.done message content", () => {+ const event = {+ type: "response.output_item.done",+ output_index: 0,+ item: {+ type: "message",+ id: "msg_1",+ role: "assistant",+ status: "completed",+ content: [{ type: "output_text", text: "hello" }],+ },+ };+ const [out] = apply(sseBlock(event));+ const parsed = parseData([out])[0];+ expect(parsed.item.content[0].annotations).toEqual([]);+ expect(parsed.item.content[0].text).toBe("hello");+ });+ test("preserves existing annotations", () => {+ const existing = [{ type: "url_citation", url: "https://example.com" }];+ const event = {+ type: "response.output_item.done",+ output_index: 0,+ item: {+ type: "message",+ id: "msg_1",+ role: "assistant",+ status: "completed",+ content: [{ type: "output_text", text: "hi", annotations: existing }],+ },+ };+ const [out] = apply(sseBlock(event));+ const parsed = parseData([out])[0];+ expect(parsed.item.content[0].annotations).toEqual(existing);+ });+ test("adds annotations to content_part.added", () => {+ const event = {+ type: "response.content_part.added",+ item_id: "msg_1",+ output_index: 0,+ content_index: 0,+ part: { type: "output_text", text: "" },+ };+ const [out] = apply(sseBlock(event));+ const parsed = parseData([out])[0];+ expect(parsed.part.annotations).toEqual([]);+ });+ test("adds annotations to response.completed output items", () => {+ const event = {+ type: "response.completed",+ sequence_number: 42,+ response: {+ id: "resp_1",+ object: "response",+ status: "completed",+ model: "grok-4.5",+ output: [+ {+ type: "message",+ id: "msg_1",+ role: "assistant",+ status: "completed",+ content: [{ type: "output_text", text: "answer" }],+ },+ ],+ usage: {+ input_tokens: 10,+ output_tokens: 5,+ total_tokens: 15,+ input_tokens_details: { cached_tokens: 0 },+ output_tokens_details: { reasoning_tokens: 0 },+ },+ },+ };+ const [out] = apply(sseBlock(event));+ const parsed = parseData([out])[0];+ expect(parsed.response.output[0].content[0].annotations).toEqual([]);+ });+ test("does not modify events without output_text parts", () => {+ const event = {+ type: "response.output_item.added",+ output_index: 0,+ item: {+ type: "function_call",+ id: "fc_1",+ call_id: "call_1",+ name: "do_thing",+ arguments: "{}",+ },+ };+ const result = apply(sseBlock(event));+ expect(result).toHaveLength(1);+ expect(result[0]).toBe(sseBlock(event));+ });+ test("handles multiple content parts with mixed types", () => {+ const event = {+ type: "response.output_item.done",+ output_index: 0,+ item: {+ type: "message",+ id: "msg_1",+ role: "assistant",+ status: "completed",+ content: [+ { type: "output_text", text: "first" },+ { type: "refusal", refusal: "no" },+ { type: "output_text", text: "second", annotations: [] },+ ],+ },+ };+ const [out] = apply(sseBlock(event));+ const parsed = parseData([out])[0];+ expect(parsed.item.content[0].annotations).toEqual([]);+ expect(parsed.item.content[1]).not.toHaveProperty("annotations");+ expect(parsed.item.content[2].annotations).toEqual([]);+ });+ test("backfillResponsesFieldsJson adds missing annotations and preserves existing", () => {+ const response = {+ id: "resp_1",+ object: "response",+ status: "completed",+ output: [+ {+ type: "message",+ id: "msg_1",+ role: "assistant",+ status: "completed",+ content: [+ { type: "output_text", text: "no annotations" },+ { type: "output_text", text: "has annotations", annotations: [{ type: "url_citation", url: "https://example.com" }] },+ { type: "output_text", text: "null annotations", annotations: null },+ { type: "output_text", text: "malformed annotations", annotations: "not-an-array" },+ { type: "output_text", text: "object annotations", annotations: { unexpected: true } },+ ],+ },+ ],+ };+ const result = JSON.parse(backfillResponsesFieldsJson(JSON.stringify(response)));+ expect(result.output[0].content[0].annotations).toEqual([]);+ expect(result.output[0].content[1].annotations).toEqual([{ type: "url_citation", url: "https://example.com" }]);+ expect(result.output[0].content[2].annotations).toBeNull();+ expect(result.output[0].content[3].annotations).toBe("not-an-array");+ expect(result.output[0].content[4].annotations).toEqual({ unexpected: true });+ });+ test("backfills missing ids on response.completed output items", () => {+ const event = {+ type: "response.completed",+ sequence_number: 42,+ response: {+ id: "resp_1",+ object: "response",+ status: "completed",+ output: [+ { type: "reasoning", summary: [{ type: "summary_text", text: "thinking" }] },+ {+ type: "message",+ role: "assistant",+ status: "completed",+ content: [{ type: "output_text", text: "hello" }],+ },+ {+ type: "function_call",+ call_id: "call_1",+ name: "todo_write",+ arguments: "{}",+ },+ ],+ },+ };+ const [out] = apply(sseBlock(event));+ const parsed = parseData([out])[0];+ expect(parsed.response.output[0].id).toBe("rs_ocx_0");+ expect(parsed.response.output[1].id).toBe("msg_ocx_1");+ expect(parsed.response.output[2].id).toBe("fc_ocx_2");+ });+ test("preserves existing item ids", () => {+ const event = {+ type: "response.completed",+ sequence_number: 42,+ response: {+ id: "resp_1",+ object: "response",+ status: "completed",+ output: [+ { type: "message", id: "msg_real", role: "assistant", content: [{ type: "output_text", text: "hi" }] },+ ],+ },+ };+ const [out] = apply(sseBlock(event));+ const parsed = parseData([out])[0];+ expect(parsed.response.output[0].id).toBe("msg_real");+ });+ test("uses output_index when backfilling output_item.done id", () => {+ const event = {+ type: "response.output_item.done",+ output_index: 3,+ item: {+ type: "message",+ role: "assistant",+ status: "completed",+ content: [{ type: "output_text", text: "hi" }],+ },+ };+ const [out] = apply(sseBlock(event));+ const parsed = parseData([out])[0];+ expect(parsed.item.id).toBe("msg_ocx_3");+ });+ test("falls back to item_ prefix for inherited type names", () => {+ const event = {+ type: "response.output_item.done",+ output_index: 0,+ item: {+ type: "toString",+ role: "assistant",+ status: "completed",+ content: [{ type: "output_text", text: "hi" }],+ },+ };+ const [out] = apply(sseBlock(event));+ const parsed = parseData([out])[0];+ expect(parsed.item.id).toBe("item_ocx_0");+ });+ test("an invalid output_index still yields a well-formed synthesized id", () => {+ for (const badIndex of [-1, 1.5, NaN, Infinity, "0", null, undefined]) {+ const event = {+ type: "response.output_item.done",+ output_index: badIndex,+ item: {+ type: "message",+ role: "assistant",+ status: "completed",+ content: [{ type: "output_text", text: "hi" }],+ },+ };+ const [out] = apply(sseBlock(event));+ const parsed = parseData([out])[0];+ // The fallback carries its own namespace so it can never equal an index-derived id.+ expect(parsed.item.id).toMatch(/^msg_ocx_fallback_\d+$/);+ }+ });+ test("two items with an unusable output_index do not collide on one id", () => {+ // Collapsing an unusable index to 0 would synthesize `msg_ocx_0` twice, which is the+ // duplicate-id defect this backfill exists to prevent. Position is unrecoverable here;+ // uniqueness is not optional.+ const event = (text) => ({+ type: "response.output_item.done",+ item: {+ type: "message",+ role: "assistant",+ status: "completed",+ content: [{ type: "output_text", text }],+ },+ });+ const first = parseData(apply(sseBlock(event("one"))))[0];+ const second = parseData(apply(sseBlock(event("two"))))[0];+ expect(first.item.id).toMatch(/^msg_ocx_fallback_\d+$/);+ expect(second.item.id).toMatch(/^msg_ocx_fallback_\d+$/);+ expect(first.item.id).not.toBe(second.item.id);+ });+ test("a well-formed output_index still produces the stable index-derived id", () => {+ const event = {+ type: "response.output_item.done",+ output_index: 3,+ item: {+ type: "message",+ role: "assistant",+ status: "completed",+ content: [{ type: "output_text", text: "hi" }],+ },+ };+ // Stability across events referencing the same item is the whole point of index-derivation,+ // so the fallback must not leak into the well-formed path.+ expect(parseData(apply(sseBlock(event)))[0].item.id).toBe("msg_ocx_3");+ expect(parseData(apply(sseBlock(event)))[0].item.id).toBe("msg_ocx_3");+ });+ test("backfillResponsesFieldsJson backfills missing ids on output items", () => {+ const response = {+ id: "resp_1",+ object: "response",+ status: "completed",+ output: [+ { type: "reasoning", summary: [{ type: "summary_text", text: "thinking" }] },+ {+ type: "message",+ role: "assistant",+ status: "completed",+ content: [{ type: "output_text", text: "hello" }],+ },+ {+ type: "function_call",+ call_id: "call_1",+ name: "todo_write",+ arguments: "{}",+ },+ ],+ };+ const result = JSON.parse(backfillResponsesFieldsJson(JSON.stringify(response)));+ expect(result.output[0].id).toBe("rs_ocx_0");+ expect(result.output[1].id).toBe("msg_ocx_1");+ expect(result.output[2].id).toBe("fc_ocx_2");+ });+ test("backfillResponsesFieldsJson preserves existing item ids", () => {+ const response = {+ id: "resp_1",+ object: "response",+ status: "completed",+ output: [+ { type: "message", id: "msg_real", role: "assistant", content: [{ type: "output_text", text: "hi" }] },+ ],+ };+ const result = JSON.parse(backfillResponsesFieldsJson(JSON.stringify(response)));+ expect(result.output[0].id).toBe("msg_real");+ });+ test("backfills missing status on output_item.done message", () => {+ const event = {+ type: "response.output_item.done",+ output_index: 0,+ item: {+ type: "message",+ id: "msg_1",+ role: "assistant",+ content: [{ type: "output_text", text: "hi" }],+ },+ };+ const [out] = apply(sseBlock(event));+ const parsed = parseData([out])[0];+ expect(parsed.item.status).toBe("completed");+ });+ test("preserves existing status on message items", () => {+ const event = {+ type: "response.output_item.done",+ output_index: 0,+ item: {+ type: "message",+ id: "msg_1",+ role: "assistant",+ status: "in_progress",+ content: [{ type: "output_text", text: "hi" }],+ },+ };+ const [out] = apply(sseBlock(event));+ const parsed = parseData([out])[0];+ expect(parsed.item.status).toBe("in_progress");+ });+ test("backfills missing status on response.completed output items", () => {+ const event = {+ type: "response.completed",+ sequence_number: 42,+ response: {+ id: "resp_1",+ object: "response",+ status: "completed",+ output: [+ {+ type: "message",+ id: "msg_1",+ role: "assistant",+ content: [{ type: "output_text", text: "hello" }],+ },+ ],+ },+ };+ const [out] = apply(sseBlock(event));+ const parsed = parseData([out])[0];+ expect(parsed.response.output[0].status).toBe("completed");+ });+ test("does not add status to non-message items", () => {+ const event = {+ type: "response.output_item.done",+ output_index: 0,+ item: {+ type: "function_call",+ id: "fc_1",+ call_id: "call_1",+ name: "do_thing",+ arguments: "{}",+ },+ };+ const [out] = apply(sseBlock(event));+ const parsed = parseData([out])[0];+ expect(parsed.item).not.toHaveProperty("status");+ });+ test("backfillResponsesFieldsJson backfills missing status on message items", () => {+ const response = {+ id: "resp_1",+ object: "response",+ status: "completed",+ output: [+ {+ type: "message",+ id: "msg_1",+ role: "assistant",+ content: [{ type: "output_text", text: "hello" }],+ },+ ],+ };+ const result = JSON.parse(backfillResponsesFieldsJson(JSON.stringify(response)));+ expect(result.output[0].status).toBe("completed");+ });+ // `queued` is a real Responses lifecycle status: the response exists but has not+ // started generating. It is neither a valid OutputMessage status nor covered by the+ // event-type table, so before these cases it fell through to the `completed`+ // default — marking an unstarted message as finished, which is exactly the+ // overclaim messageStatusFromResponseStatus exists to prevent.+ test("a queued response marks its message items in_progress, not completed", () => {+ const event = {+ type: "response.queued",+ sequence_number: 1,+ response: {+ id: "resp_1",+ object: "response",+ status: "queued",+ model: "grok-4.5",+ output: [+ {+ type: "message",+ id: "msg_1",+ role: "assistant",+ content: [{ type: "output_text", text: "" }],+ },+ ],+ },+ };+ const [out] = apply(sseBlock(event));+ const parsed = parseData([out])[0];+ expect(parsed.response.output[0].status).toBe("in_progress");+ });+ test("backfillResponsesFieldsJson treats a queued response as in_progress", () => {+ const response = {+ id: "resp_1",+ object: "response",+ status: "queued",+ output: [+ {+ type: "message",+ id: "msg_1",+ role: "assistant",+ content: [{ type: "output_text", text: "" }],+ },+ ],+ };+ const result = JSON.parse(backfillResponsesFieldsJson(JSON.stringify(response)));+ expect(result.output[0].status).toBe("in_progress");+ });+ test("backfillResponsesFieldsJson derives incomplete status on message items", () => {+ const response = {+ id: "resp_1",+ object: "response",+ status: "incomplete",+ output: [+ {+ type: "message",+ id: "msg_1",+ role: "assistant",+ content: [{ type: "output_text", text: "partial" }],+ },+ ],+ };+ const result = JSON.parse(backfillResponsesFieldsJson(JSON.stringify(response)));+ expect(result.output[0].status).toBe("incomplete");+ });+ test("backfills in_progress status on output_item.added message", () => {+ const event = {+ type: "response.output_item.added",+ output_index: 0,+ item: {+ type: "message",+ id: "msg_1",+ role: "assistant",+ content: [{ type: "output_text", text: "" }],+ },+ };+ const [out] = apply(sseBlock(event));+ const parsed = parseData([out])[0];+ // output_item.added means the item is still being generated; marking it "completed"+ // would misrepresent the stream state to strict clients.+ expect(parsed.item.status).toBe("in_progress");+ });+ test("backfills in_progress status on response.created output items", () => {+ const event = {+ type: "response.created",+ sequence_number: 1,+ response: {+ id: "resp_1",+ object: "response",+ status: "in_progress",+ model: "grok-4.5",+ output: [+ {+ type: "message",+ id: "msg_1",+ role: "assistant",+ content: [{ type: "output_text", text: "" }],+ },+ ],+ },+ };+ const [out] = apply(sseBlock(event));+ const parsed = parseData([out])[0];+ expect(parsed.response.output[0].status).toBe("in_progress");+ });+ test("backfills in_progress when both response status and item status are absent", () => {+ // response.created with no status on either the response or the message item:+ // the event type alone must drive the inference, not a "completed" default.+ const event = {+ type: "response.created",+ sequence_number: 1,+ response: {+ id: "resp_1",+ object: "response",+ model: "grok-4.5",+ output: [+ {+ type: "message",+ id: "msg_1",+ role: "assistant",+ content: [{ type: "output_text", text: "" }],+ },+ ],+ },+ };+ const [out] = apply(sseBlock(event));+ const parsed = parseData([out])[0];+ expect(parsed.response.output[0].status).toBe("in_progress");+ });+ test("backfills incomplete status on response.incomplete output items", () => {+ const event = {+ type: "response.incomplete",+ sequence_number: 10,+ response: {+ id: "resp_1",+ object: "response",+ status: "incomplete",+ model: "grok-4.5",+ output: [+ {+ type: "message",+ id: "msg_1",+ role: "assistant",+ content: [{ type: "output_text", text: "partial" }],+ },+ ],+ },+ };+ const [out] = apply(sseBlock(event));+ const parsed = parseData([out])[0];+ expect(parsed.response.output[0].status).toBe("incomplete");+ });+ test("maps response.failed to incomplete message status", () => {+ // response.failed carries status: "failed" on the response object, but+ // OutputMessage.status only accepts in_progress/completed/incomplete.+ // "failed" means the message did not finish generating, so "incomplete"+ // is the correct semantic mapping — not "completed", which would falsely+ // claim the message is whole.+ const event = {+ type: "response.failed",+ sequence_number: 5,+ response: {+ id: "resp_1",+ object: "response",+ status: "failed",+ model: "grok-4.5",+ output: [+ {+ type: "message",+ id: "msg_1",+ role: "assistant",+ content: [{ type: "output_text", text: "partial" }],+ },+ ],+ },+ };+ const [out] = apply(sseBlock(event));+ const parsed = parseData([out])[0];+ expect(parsed.response.output[0].status).toBe("incomplete");+ });+ test("the canonical image_generation_call type gets its own prefix", () => {+ const response = {+ id: "resp_1",+ object: "response",+ status: "completed",+ output: [{ type: "image_generation_call", result: "..." }],+ };+ const result = JSON.parse(backfillResponsesFieldsJson(JSON.stringify(response)));+ // The wire type is `image_generation_call`; keying the table on the short spelling alone+ // silently demoted every real one to the generic `item_` prefix.+ expect(result.output[0].id).toBe("ig_ocx_0");+ });+ // A routed tool_search lowering is restored as `tool_search_call` with no id, so this+ // backfill names it. The generic `item_` fallback was not cosmetic: `stripInvalidItemIds`+ // in the Responses adapter deletes an id whose prefix does not match its type, so the item+ // silently lost its id on the NEXT turn and the client could no longer correlate it.+ test("tool_search_call gets the prefix the request serializer accepts", () => {+ const response = {+ id: "resp_1",+ object: "response",+ status: "completed",+ output: [{ type: "tool_search_call", call_id: "call_x", execution: "client" }],+ };+ const result = JSON.parse(backfillResponsesFieldsJson(JSON.stringify(response)));+ expect(result.output[0].id).toBe("tsc_ocx_0");+ });+ test("custom_tool_call gets its own prefix too", () => {+ const response = {+ id: "resp_1",+ object: "response",+ status: "completed",+ output: [{ type: "custom_tool_call", call_id: "call_y" }],+ };+ const result = JSON.parse(backfillResponsesFieldsJson(JSON.stringify(response)));+ expect(result.output[0].id).toBe("ctc_ocx_0");+ });+ // A malformed `output_index` falls back to a counter. While that counter lived in the same+ // numeric namespace as real indexes, a response whose real index reached the counter's base+ // produced the SAME id as a fallback — a duplicate, which is the one thing this backfill+ // exists to prevent.+ test("a fallback id cannot collide with any index-derived id", () => {+ const malformed = parseData(apply(sseBlock({+ type: "response.output_item.added",+ output_index: "not-a-number",+ item: { type: "message", role: "assistant", content: [] },+ })));+ const fallbackId = malformed[0].item.id;+ // Every index-derived id is `msg_ocx_<digits>`; the fallback namespace is lexically+ // disjoint from it, so no integer index can ever produce this string.+ expect(fallbackId).toMatch(/^msg_ocx_fallback_\d+$/);+ expect(fallbackId).not.toMatch(/^msg_ocx_\d+$/);+ for (const index of [0, 1, 1_000_000, 1_000_001, 1_000_002]) {+ const derived = parseData(apply(sseBlock({+ type: "response.output_item.added",+ output_index: index,+ item: { type: "message", role: "assistant", content: [] },+ })));+ expect(derived[0].item.id).not.toBe(fallbackId);+ }+ });+ test("consecutive malformed indexes still get distinct ids", () => {+ const ids = [0, 1].map(() => {+ const out = parseData(apply(sseBlock({+ type: "response.output_item.added",+ item: { type: "message", role: "assistant", content: [] },+ })));+ return out[0].item.id;+ });+ expect(new Set(ids).size).toBe(2);+ });+ // The compact wire family is the /v1/responses/compact format, not Responses output items: they+ // carry no id in that contract, clients compare the body exactly, and the client replays the item+ // on every later turn where the minting backend rejects a modified one. Synthesizing an id here+ // changed a response that had nothing to do with strict Responses decoding — a defect that only+ // appeared once this backfill and the compact endpoint were on the same tree. It originally+ // covered `compaction` alone, so the sibling types kept receiving synthesized ids.+ test("every compact wire item type is returned byte-for-byte", () => {+ for (const type of ["compaction", "compaction_summary", "context_compaction"]) {+ const item = { type, encrypted_content: "gAAAAAB-test-opaque" };+ const response = { id: "resp_1", object: "response", status: "completed", output: [item] };+ const result = JSON.parse(backfillResponsesFieldsJson(JSON.stringify(response)));+ expect(result.output[0]).toEqual(item);+ expect(result.output[0]).not.toHaveProperty("id");+ const streamed = parseData(apply(sseBlock({ type: "response.output_item.done", output_index: 0, item })));+ expect(streamed[0].item).toEqual(item);+ expect(streamed[0].item).not.toHaveProperty("id");+ }+ });+});diff --git a/packages/model-compat/src/__tests__/upstream/responses/responses-reasoning-summary-rewrite.test.js b/packages/model-compat/src/__tests__/upstream/responses/responses-reasoning-summary-rewrite.test.jsnew file mode 100644index 0000000000..938f21f35c--- /dev/null+++ b/packages/model-compat/src/__tests__/upstream/responses/responses-reasoning-summary-rewrite.test.js@@ -0,0 +1,250 @@+import { describe, expect, test } from "vitest";+import { createReasoningSummaryChannelPayloadRewrite, routeUsesContentChannelReasoning, rewriteReasoningSummaryInJson, rewriteReasoningSummaryInJsonString, } from "../../../upstream/server/responses-reasoning-summary-rewrite";+const rewrite = createReasoningSummaryChannelPayloadRewrite();+function apply(payload) {+ return JSON.parse(rewrite(JSON.stringify(payload)));+}+describe("responses reasoning summary channel rewrite", () => {+ test("routes reasoning_text.delta through the summary channel", () => {+ expect(apply({+ type: "response.reasoning_text.delta",+ content_index: 0,+ delta: "think",+ item_id: "rs_1",+ output_index: 0,+ sequence_number: 4,+ })).toEqual({+ type: "response.reasoning_summary_text.delta",+ summary_index: 0,+ delta: "think",+ item_id: "rs_1",+ output_index: 0,+ sequence_number: 4,+ });+ });+ test("routes reasoning_text.done through the summary channel", () => {+ expect(apply({+ type: "response.reasoning_text.done",+ content_index: 0,+ text: "full thinking",+ item_id: "rs_1",+ output_index: 0,+ })).toEqual({+ type: "response.reasoning_summary_text.done",+ summary_index: 0,+ text: "full thinking",+ item_id: "rs_1",+ output_index: 0,+ });+ });+ test("moves reasoning item content into summary on output_item.done", () => {+ expect(apply({+ type: "response.output_item.done",+ output_index: 0,+ item: {+ type: "reasoning",+ id: "rs_1",+ status: "completed",+ content: [{ type: "reasoning_text", text: "thinking" }],+ summary: [],+ },+ })).toEqual({+ type: "response.output_item.done",+ output_index: 0,+ item: {+ type: "reasoning",+ id: "rs_1",+ status: "completed",+ summary: [{ type: "summary_text", text: "thinking" }],+ },+ });+ });+ test("moves reasoning item content into summary inside response.completed", () => {+ const payload = {+ type: "response.completed",+ response: {+ id: "resp_1",+ status: "completed",+ output: [+ {+ type: "reasoning",+ id: "rs_1",+ status: "completed",+ content: [{ type: "reasoning_text", text: "thinking" }],+ summary: [],+ },+ { type: "message", id: "msg_1", status: "completed", content: [{ type: "output_text", text: "OK" }] },+ ],+ },+ };+ const result = apply(payload);+ expect(result.response.output[0]).toEqual({+ type: "reasoning",+ id: "rs_1",+ status: "completed",+ summary: [{ type: "summary_text", text: "thinking" }],+ });+ expect(result.response.output[1]).toEqual(payload.response.output[1]);+ });+ test("leaves summary-channel and message events untouched", () => {+ const untouched = [+ { type: "response.reasoning_summary_text.delta", summary_index: 0, delta: "s", item_id: "rs_1", output_index: 0 },+ { type: "response.output_text.delta", content_index: 0, delta: "OK", item_id: "msg_1", output_index: 1 },+ { type: "response.output_item.added", output_index: 1, item: { type: "message", id: "msg_1", status: "in_progress", content: [] } },+ ];+ for (const payload of untouched) {+ expect(apply(payload)).toEqual(payload);+ }+ });+ test("leaves a reasoning item without content text untouched", () => {+ expect(apply({+ type: "response.output_item.done",+ output_index: 0,+ item: { type: "reasoning", id: "rs_1", status: "completed", content: [], summary: [] },+ })).toEqual({+ type: "response.output_item.done",+ output_index: 0,+ item: { type: "reasoning", id: "rs_1", status: "completed", content: [], summary: [] },+ });+ });+ test("preserves a summary-channel reasoning item as-is", () => {+ expect(apply({+ type: "response.output_item.done",+ output_index: 0,+ item: {+ type: "reasoning",+ id: "rs_1",+ status: "completed",+ content: [],+ summary: [{ type: "summary_text", text: "already summarized" }],+ },+ })).toEqual({+ type: "response.output_item.done",+ output_index: 0,+ item: {+ type: "reasoning",+ id: "rs_1",+ status: "completed",+ content: [],+ summary: [{ type: "summary_text", text: "already summarized" }],+ },+ });+ });+ test("rewrites reasoning items inside a bare completed response document", () => {+ const doc = {+ id: "resp_1",+ object: "response",+ status: "completed",+ output: [+ {+ type: "reasoning",+ id: "rs_1",+ status: "completed",+ content: [{ type: "reasoning_text", text: "thinking" }],+ summary: [],+ },+ { type: "message", id: "msg_1", status: "completed", content: [{ type: "output_text", text: "OK" }] },+ ],+ };+ const result = rewriteReasoningSummaryInJson(doc);+ expect(result.output[0]).toEqual({+ type: "reasoning",+ id: "rs_1",+ status: "completed",+ summary: [{ type: "summary_text", text: "thinking" }],+ });+ expect(result.output[1]).toEqual(doc.output[1]);+ });+ test("rewrites reasoning items inside an SSE completed event document", () => {+ const doc = {+ type: "response.completed",+ response: {+ id: "resp_1",+ status: "completed",+ output: [+ {+ type: "reasoning",+ id: "rs_1",+ status: "completed",+ content: [{ type: "reasoning_text", text: "thinking" }],+ summary: [],+ },+ ],+ },+ };+ const result = rewriteReasoningSummaryInJson(doc);+ expect(result.response.output[0]).toEqual({+ type: "reasoning",+ id: "rs_1",+ status: "completed",+ summary: [{ type: "summary_text", text: "thinking" }],+ });+ });+ test("string-level rewrite leaves summary-channel documents untouched", () => {+ const doc = JSON.stringify({+ id: "resp_1",+ output: [{ type: "reasoning", id: "rs_1", summary: [{ type: "summary_text", text: "already summarized" }] }],+ });+ expect(rewriteReasoningSummaryInJsonString(doc)).toBe(doc);+ });+ test("malformed payloads pass through unchanged", () => {+ expect(rewrite("not json")).toBe("not json");+ expect(rewrite("[1,2]")).toBe("[1,2]");+ });+ // `encrypted_content` is opaque, state-bearing provider data, so preserve the complete item+ // shape defensively when the client replays it. This rewrite's round-trip was verified against+ // DeepSeek, which is stateless and issues no blob; providers that do issue one joined later+ // through `preserveReasoningContentModels`.+ describe("items carrying encrypted_content", () => {+ const blobItem = {+ type: "reasoning",+ id: "rs_1",+ status: "completed",+ encrypted_content: "gAAAAAB-upstream-issued-blob",+ content: [{ type: "reasoning_text", text: "thinking" }],+ summary: [],+ };+ test("are returned byte-for-byte on output_item.done", () => {+ const payload = { type: "response.output_item.done", output_index: 0, item: blobItem };+ expect(apply(payload)).toEqual(payload);+ });+ test("are returned byte-for-byte inside response.completed output", () => {+ const payload = {+ type: "response.completed",+ response: { id: "resp_1", output: [blobItem] },+ };+ expect(apply(payload)).toEqual(payload);+ });+ test("are returned byte-for-byte through the non-streaming document rewrite", () => {+ const doc = { id: "resp_1", object: "response", output: [blobItem] };+ expect(rewriteReasoningSummaryInJson(doc)).toBe(doc);+ const json = JSON.stringify(doc);+ expect(rewriteReasoningSummaryInJsonString(json)).toBe(json);+ });+ // Only the stored item is protected: the live trace Codex renders comes from the delta events,+ // which carry no blob and are still routed to the summary channel.+ test("do not disable the delta rewrite that renders the live trace", () => {+ expect(apply({+ type: "response.reasoning_text.delta",+ delta: "think",+ item_id: "rs_1",+ output_index: 0,+ })).toMatchObject({ type: "response.reasoning_summary_text.delta", delta: "think" });+ });+ });+});+describe("routeUsesContentChannelReasoning", () => {+ test("statelessResponses providers use the content channel", () => {+ expect(routeUsesContentChannelReasoning({ statelessResponses: true }, "deepseek-v4-flash")).toBe(true);+ });+ test("preserveReasoningContentModels lists qualify", () => {+ expect(routeUsesContentChannelReasoning({ preserveReasoningContentModels: ["deepseek-v4-flash"] }, "deepseek-v4-flash")).toBe(true);+ });+ test("model matching is case-insensitive on both sides", () => {+ expect(routeUsesContentChannelReasoning({ preserveReasoningContentModels: ["DeepSeek-V4-Flash"] }, "deepseek-v4-flash")).toBe(true);+ expect(routeUsesContentChannelReasoning({ preserveReasoningContentModels: ["deepseek-v4-flash"] }, "DeepSeek-V4-Flash")).toBe(true);+ });+ test("other providers do not", () => {+ expect(routeUsesContentChannelReasoning({}, "gpt-5.5")).toBe(false);+ });+});diff --git a/packages/model-compat/src/__tests__/upstream/responses/responses-tool-groups.test.js b/packages/model-compat/src/__tests__/upstream/responses/responses-tool-groups.test.jsnew file mode 100644index 0000000000..11c1fd8db2--- /dev/null+++ b/packages/model-compat/src/__tests__/upstream/responses/responses-tool-groups.test.js@@ -0,0 +1,27 @@+import { describe, expect, test } from "vitest";+import { collectResponsesToolGroups } from "../../../upstream/responses/tool-groups";+describe("Responses tool-group collection", () => {+ test("collects top-level and Responses Lite tools in wire order", () => {+ const topLevel = [{ type: "web_search" }];+ const firstNested = [{ type: "function", name: "image_gen.imagegen" }];+ const secondNested = [{ type: "function", name: "exec_command" }];+ const groups = collectResponsesToolGroups({+ tools: topLevel,+ input: [+ { type: "message", role: "user", content: "hello" },+ { type: "additional_tools", tools: firstNested },+ { type: "additional_tools", tools: "invalid" },+ { type: "additional_tools", tools: secondNested },+ ],+ });+ expect(groups).toHaveLength(3);+ expect(groups[0]).toBe(topLevel);+ expect(groups[1]).toBe(firstNested);+ expect(groups[2]).toBe(secondNested);+ });+ test("ignores malformed request containers", () => {+ expect(collectResponsesToolGroups(undefined)).toEqual([]);+ expect(collectResponsesToolGroups([])).toEqual([]);+ expect(collectResponsesToolGroups({ tools: {}, input: "invalid" })).toEqual([]);+ });+});diff --git a/packages/model-compat/src/chat.ts b/packages/model-compat/src/chat.tsnew file mode 100644index 0000000000..2125cd16e4--- /dev/null+++ b/packages/model-compat/src/chat.ts@@ -0,0 +1,17 @@+import type { ChatBridgeCapabilities } from './cindy/types';+import { resolveProviderCompatibilityProfile, profileModelListed, type CompatibilityRoute } from './profiles';++/** Convert upstream declarations into the existing bridge's serializer capabilities.+ * Cindy's explicit route capabilities stay authoritative; upstream declarations fill gaps.+ */+export function chatCompatibilityCapabilities(route: CompatibilityRoute, existing: ChatBridgeCapabilities = {}): ChatBridgeCapabilities {+ if (route.protocol !== 'openai-chat') return existing;+ const profile = resolveProviderCompatibilityProfile(route);+ if (!profile) return existing;+ const baseline: ChatBridgeCapabilities = {};+ if (typeof profile.parallelToolCalls === 'boolean') baseline.parallelToolCalls = profile.parallelToolCalls;+ if (profileModelListed(profile.preserveReasoningContentModels, route.model)) baseline.reasoningHistoryField = 'reasoning_content';+ if (profileModelListed(profile.requiresReasoningPlaceholderModels ?? profile.preserveReasoningContentModels, route.model)) baseline.toolCallReasoningPlaceholder = true;+ if (profileModelListed(profile.autoToolChoiceOnlyModels, route.model)) baseline.forceAutoToolChoice = true;+ return { ...baseline, ...existing };+}diff --git a/packages/model-compat/src/cindy/custom-tool-function-adapter.ts b/packages/model-compat/src/cindy/custom-tool-function-adapter.tsnew file mode 100644index 0000000000..2a6cc995d0--- /dev/null+++ b/packages/model-compat/src/cindy/custom-tool-function-adapter.ts@@ -0,0 +1,411 @@+import { Buffer } from 'node:buffer';+import { Transform, type TransformCallback } from 'node:stream';+import { TextDecoder } from 'node:util';++import { ChatBridgeToolContext, type ChatBridgeToolSpec } from './tool-context.js';+import type { ResponsesRequest } from './types.js';++const MAX_PENDING_BYTES = 16 * 1024 * 1024;+const MAX_PENDING_REQUESTS = 256;+const MAX_ACTIVE_RESPONSE_CALLS = 256;+const MAX_RESPONSE_ARGUMENT_BYTES = 16 * 1024 * 1024;+// The desktop proxy's upstream socket timeout is ten minutes. Keep mappings strictly longer so+// no request that can still be live is evicted, while failed/cancelled requests are eventually+// reclaimed instead of exhausting the bounded map for the rest of the process lifetime.+const PENDING_REQUEST_TTL_MS = 15 * 60 * 1000;++function isObject(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function customToolName(tool: unknown): string | null {+ if (typeof tool === 'string') return tool;+ return isObject(tool) && tool.type === 'custom' && typeof tool.name === 'string'+ ? tool.name+ : null;+}++function stringifyInput(value: unknown): string {+ if (typeof value === 'string') return value;+ const serialized = JSON.stringify(value ?? '');+ if (serialized === undefined) throw new Error('custom tool input is not JSON-serializable');+ return serialized;+}++function unwrapArguments(value: unknown): string {+ if (typeof value !== 'string') throw new Error('adapted custom tool call has no function arguments');+ let parsed: unknown;+ try {+ parsed = JSON.parse(value);+ } catch {+ throw new Error('adapted custom tool call arguments are not valid JSON');+ }+ if (!isObject(parsed) || typeof parsed.input !== 'string') {+ throw new Error('adapted custom tool call arguments have no string input');+ }+ return parsed.input;+}++/**+ * Item ids are dialect-coupled. Codex >=0.152 stamps a `<kind>_<uuid7>` id on every input item+ * it replays, and a Responses upstream rejects an item whose id prefix disagrees with its type+ * (`Invalid 'input[n].id' ... Expected an ID that begins with 'fc'`). Flipping an item to the+ * function dialect therefore has to flip its id prefix too.+ */+const CUSTOM_TO_FUNCTION_ID_PREFIXES: ReadonlyArray<readonly [string, string]> = [+ ['ctco_', 'fco_'],+ ['ctc_', 'fc_'],+];++/**+ * Rewrites one adapted item's id for the function dialect.+ *+ * Ids already in the function dialect are left untouched: the upstream minted them, so it is the+ * authority on what it accepts, and `fc` is the prefix its own validator asks for. An id that is+ * in neither dialect is dropped rather than forwarded — omitting `id` is exactly what Codex did+ * before 0.152 and every Responses upstream accepts it, so a future Codex prefix we do not know+ * about degrades to a missing id instead of failing the whole request. The+ * `codexExecFunctionAdapter` e2e enforces this invariant against the pinned binary so a new+ * prefix surfaces on the next bump instead of in production.+ */+function adaptItemId(item: Record<string, unknown>): Record<string, unknown> {+ const id = item.id;+ if (typeof id !== 'string') return item;+ for (const [from, to] of CUSTOM_TO_FUNCTION_ID_PREFIXES) {+ if (id.startsWith(from)) return { ...item, id: `${to}${id.slice(from.length)}` };+ }+ if (id.startsWith('fc')) return item;+ const next = { ...item };+ delete next.id;+ return next;+}++/** Repair only known dialect mismatches; opaque provider ids and absent ids stay intact.+ * `call_id` identifies the invocation/result pair and must never be rewritten.+ */+function normalizeToolItemId(item: Record<string, unknown>): Record<string, unknown> {+ const prefixes: readonly [string, string] | null = item.type === 'custom_tool_call' ? ['fc_', 'ctc_']+ : item.type === 'custom_tool_call_output' ? ['fco_', 'ctco_']+ : item.type === 'function_call' ? ['ctc_', 'fc_']+ : item.type === 'function_call_output' ? ['ctco_', 'fco_'] : null;+ if (!prefixes || typeof item.id !== 'string' || !item.id.startsWith(prefixes[0])) return item;+ return { ...item, id: prefixes[1] + item.id.slice(prefixes[0].length) };+}++/**+ * Repair legacy histories on the wire, including tool-less compact requests and native-custom+ * routes. Do not rewrite the rollout, tool payloads, opaque compaction blobs or unrelated ids.+ * Return null for an unchanged body, following the proxy request-transform contract.+ */+export function normalizeResponsesToolItemIds(body: unknown): Record<string, unknown> | null {+ if (!isObject(body) || !Array.isArray(body.input)) return null;+ let changed = false;+ const input = body.input.map((item: unknown) => {+ if (!isObject(item)) return item;+ const next = normalizeToolItemId(item);+ if (next !== item) changed = true;+ return next;+ });+ // item_reference ids address server-owned stored items, not local payloads. Keep them opaque.+ return changed ? { ...body, input } : null;+}++/** SSE argument events reference the output item, not the invocation's call_id. */+function customToolEvent(event: Record<string, unknown>): Record<string, unknown> {+ return typeof event.item_id === 'string' && event.item_id.startsWith('fc_')+ ? { ...event, item_id: 'ctc_' + event.item_id.slice(3) }+ : event;+}++interface AdaptedCall {+ spec: ChatBridgeToolSpec;+ arguments: string;+ input?: string;+}++/**+ * Restores one adapted upstream response to the Responses custom-tool dialect.+ *+ * SSE frames may split UTF-8, JSON, and parallel function arguments across chunks, so `pending`+ * holds incomplete framing while `calls` tracks each output index until its matching done event.+ * Non-streaming JSON is buffered until EOF. Invalid adapted arguments and oversized buffers fail+ * explicitly because passing a function call through would make Codex execute the wrong protocol.+ */+class CustomToolResponseTransform extends Transform {+ private readonly decoder = new TextDecoder();+ private readonly calls = new Map<number, AdaptedCall>();+ private pending = '';+ private responseArgumentBytes = 0;++ constructor(+ private readonly specs: ReadonlyMap<string, ChatBridgeToolSpec>,+ private readonly sse: boolean,+ ) {+ super();+ }++ private rewriteItem(item: unknown, call?: AdaptedCall): Record<string, unknown> | null {+ if (!isObject(item) || item.type !== 'function_call') return null;+ const spec = call?.spec ?? (typeof item.name === 'string' ? this.specs.get(item.name) : undefined);+ if (!spec) return null;+ const next: Record<string, unknown> = {+ ...item,+ type: 'custom_tool_call',+ name: spec.name,+ input: call?.input ?? unwrapArguments(call?.arguments ?? item.arguments),+ };+ delete next.arguments;+ return normalizeToolItemId(next);+ }+ private rewriteEvent(event: unknown): Record<string, unknown>[] | null {+ if (!isObject(event) || typeof event.type !== 'string') return null;+ const index = typeof event.output_index === 'number' ? event.output_index : -1;+ if (event.type === 'response.output_item.added' && isObject(event.item)) {+ const spec = event.item.type === 'function_call' && typeof event.item.name === 'string'+ ? this.specs.get(event.item.name)+ : undefined;+ if (!spec || index < 0) return null;+ const argumentsText = typeof event.item.arguments === 'string' ? event.item.arguments : '';+ const previous = this.calls.get(index);+ if (!previous && this.calls.size >= MAX_ACTIVE_RESPONSE_CALLS) {+ throw new Error('adapted custom tool response has too many active calls');+ }+ const nextArgumentBytes =+ this.responseArgumentBytes+ - (previous ? Buffer.byteLength(previous.arguments, 'utf8') : 0)+ + Buffer.byteLength(argumentsText, 'utf8');+ if (nextArgumentBytes > MAX_RESPONSE_ARGUMENT_BYTES) {+ throw new Error('adapted custom tool response arguments exceed the 16 MiB limit');+ }+ this.responseArgumentBytes = nextArgumentBytes;+ this.calls.set(index, {+ spec,+ arguments: argumentsText,+ });+ const item: Record<string, unknown> = {+ ...event.item, type: 'custom_tool_call', name: spec.name, input: '',+ };+ delete item.arguments;+ return [{ ...customToolEvent(event), item: normalizeToolItemId(item) }];+ }++ const call = this.calls.get(index);+ if (event.type === 'response.function_call_arguments.delta' && call) {+ if (typeof event.delta === 'string') {+ const deltaBytes = Buffer.byteLength(event.delta, 'utf8');+ if (this.responseArgumentBytes + deltaBytes > MAX_RESPONSE_ARGUMENT_BYTES) {+ throw new Error('adapted custom tool response arguments exceed the 16 MiB limit');+ }+ call.arguments += event.delta;+ this.responseArgumentBytes += deltaBytes;+ }+ return [];+ }+ if (event.type === 'response.function_call_arguments.done' && call) {+ call.input = unwrapArguments(typeof event.arguments === 'string' ? event.arguments : call.arguments);+ const delta: Record<string, unknown> = {+ ...customToolEvent(event), type: 'response.custom_tool_call_input.delta', delta: call.input,+ };+ const done: Record<string, unknown> = {+ ...customToolEvent(event), type: 'response.custom_tool_call_input.done', input: call.input,+ };+ delete delta.arguments;+ delete done.arguments;+ return [delta, done];+ }+ if (event.type === 'response.output_item.done') {+ const item = this.rewriteItem(event.item, call);+ if (!item) return null;+ this.calls.delete(index);+ this.responseArgumentBytes -= call ? Buffer.byteLength(call.arguments, 'utf8') : 0;+ return [{ ...customToolEvent(event), item }];+ }+ if (isObject(event.response) && Array.isArray(event.response.output)) {+ let changed = false;+ const output = event.response.output.map((item) => {+ const next = this.rewriteItem(item);+ if (!next) return item;+ changed = true;+ return next;+ });+ if (changed) return [{ ...event, response: { ...event.response, output } }];+ }+ return null;+ }+ private rewriteFrame(frame: string, delimiter: string): string {+ const lines = frame.split(/\r?\n/);+ const data = lines.filter((line) => line.startsWith('data:'))+ .map((line) => line.slice(5).trimStart()).join('\n');+ if (!data || data === '[DONE]') return frame + delimiter;+ let event: unknown;+ try {+ event = JSON.parse(data);+ } catch {+ return frame + delimiter;+ }+ const rewritten = this.rewriteEvent(event);+ if (rewritten === null) return frame + delimiter;+ const named = lines.some((line) => line.startsWith('event:'));+ return rewritten.map((next) => (+ `${named ? `event: ${String(next.type)}\n` : ''}data: ${JSON.stringify(next)}${delimiter}`+ )).join('');+ }+ private drainFrames(): void {+ // Keep the incomplete tail in `pending`; only complete SSE frames are safe to rewrite.+ for (;;) {+ const lf = this.pending.indexOf('\n\n');+ const crlf = this.pending.indexOf('\r\n\r\n');+ const index = lf < 0 ? crlf : crlf < 0 ? lf : Math.min(lf, crlf);+ if (index < 0) return;+ const delimiter = index === crlf ? '\r\n\r\n' : '\n\n';+ this.push(this.rewriteFrame(this.pending.slice(0, index), delimiter));+ this.pending = this.pending.slice(index + delimiter.length);+ }+ }+ override _transform(chunk: Buffer, _encoding: string, callback: TransformCallback): void {+ try {+ this.pending += this.decoder.decode(chunk, { stream: true });+ if (this.sse) this.drainFrames();+ if (Buffer.byteLength(this.pending, 'utf8') > MAX_PENDING_BYTES) {+ throw new Error('adapted custom tool response exceeds the 16 MiB buffer limit');+ }+ callback();+ } catch (error) {+ callback(error as Error);+ }+ }+ override _flush(callback: TransformCallback): void {+ try {+ this.pending += this.decoder.decode();+ if (this.sse) {+ this.drainFrames();+ if (this.pending) this.push(this.rewriteFrame(this.pending, ''));+ } else {+ // A JSON response has no stable item boundary before EOF, so rewrite it as one document.+ const parsed = JSON.parse(this.pending) as unknown;+ const rewritten = this.rewriteEvent({ type: 'response.completed', response: parsed });+ this.push(JSON.stringify(rewritten?.[0]?.response ?? parsed));+ }+ this.pending = '';+ callback();+ } catch (error) {+ callback(error as Error);+ }+ }+}++export interface ResponsesCustomToolFunctionAdapter {+ adaptRequest(body: unknown, requestId: number): unknown | null;+ /** Idempotently release request-scoped response metadata after the request settles. */+ releaseResponse(requestId: number): void;+ createResponseTransform(requestId: number, response: {+ contentType: string; contentEncoding: string;+ }): Transform | null;+}++/** Symmetric adapter for Responses providers that only accept function tools. */+export function createResponsesCustomToolFunctionAdapter(+ customToolNames: readonly string[],+): ResponsesCustomToolFunctionAdapter {+ const selected = new Set(customToolNames);+ const responseSpecs = new Map<number, {+ specs: Map<string, ChatBridgeToolSpec>;+ createdAt: number;+ }>();++ const discardExpiredResponseSpecs = (now: number): void => {+ for (const [requestId, pending] of responseSpecs) {+ if (now - pending.createdAt >= PENDING_REQUEST_TTL_MS) responseSpecs.delete(requestId);+ }+ };++ return {+ adaptRequest(body, requestId) {+ if (!isObject(body) || !Array.isArray(body.tools)) return null;+ const context = ChatBridgeToolContext.fromRequest(body as unknown as ResponsesRequest);+ const specs = new Map<string, ChatBridgeToolSpec>();+ const functionNames = new Map<string, string>();+ const tools: unknown[] = [];+ for (const tool of body.tools) {+ const name = customToolName(tool);+ if (!name || !selected.has(name)) {+ tools.push(tool);+ continue;+ }+ if (functionNames.has(name)) continue;+ const functionName = context.chatNameForResponse(name, undefined, 'custom');+ const spec = context.lookupChatName(functionName);+ const chatTool = context.chatTools?.find((item) => item.function.name === functionName);+ if (!spec || !chatTool) throw new Error(`cannot adapt Responses custom tool '${name}'`);+ functionNames.set(name, functionName);+ specs.set(functionName, spec);+ tools.push({ type: 'function', ...chatTool.function });+ }+ if (specs.size === 0) return null;++ const calls = new Map<string, string>();+ if (Array.isArray(body.input)) {+ for (const item of body.input) {+ if (isObject(item) && item.type === 'custom_tool_call'+ && !Object.hasOwn(item, 'namespace')+ && typeof item.name === 'string' && typeof item.call_id === 'string') {+ const functionName = functionNames.get(item.name);+ if (functionName) calls.set(item.call_id, functionName);+ }+ }+ }+ const input = Array.isArray(body.input) ? body.input.map((item) => {+ if (!isObject(item) || typeof item.call_id !== 'string') return item;+ const functionName = calls.get(item.call_id);+ if (!functionName) return item;+ if (item.type === 'custom_tool_call') {+ const next: Record<string, unknown> = {+ ...adaptItemId(item), type: 'function_call', name: functionName,+ arguments: JSON.stringify({ input: stringifyInput(item.input) }),+ };+ delete next.input;+ delete next.namespace;+ return next;+ }+ return item.type === 'custom_tool_call_output'+ ? { ...adaptItemId(item), type: 'function_call_output' }+ : item;+ }) : body.input;+ let toolChoice = body.tool_choice;+ if (isObject(toolChoice) && toolChoice.type === 'custom' && typeof toolChoice.name === 'string') {+ const name = functionNames.get(toolChoice.name);+ if (name) toolChoice = { type: 'function', name };+ }+ const now = Date.now();+ discardExpiredResponseSpecs(now);+ if (!responseSpecs.has(requestId) && responseSpecs.size >= MAX_PENDING_REQUESTS) {+ throw new Error('too many in-flight custom tool requests to adapt safely');+ }+ responseSpecs.set(requestId, { specs, createdAt: now });+ const adapted: Record<string, unknown> = { ...body, tools, input };+ if (Object.hasOwn(body, 'tool_choice')) adapted.tool_choice = toolChoice;+ return adapted;+ },++ releaseResponse(requestId) {+ responseSpecs.delete(requestId);+ },++ createResponseTransform(requestId, response) {+ const pending = responseSpecs.get(requestId);+ responseSpecs.delete(requestId);+ const specs = pending?.specs;+ if (!specs?.size) return null;+ const encoding = response.contentEncoding.trim().toLowerCase();+ if (encoding && encoding !== 'identity') {+ throw new Error('compressed custom tool responses cannot be adapted safely');+ }+ const contentType = response.contentType.toLowerCase();+ const sse = contentType.startsWith('text/event-stream');+ if (!sse && !contentType.includes('application/json')) {+ throw new Error(`custom tool response has unsupported content type '${response.contentType}'`);+ }+ return new CustomToolResponseTransform(specs, sse);+ },+ };+}diff --git a/packages/model-compat/src/cindy/proxy/headers.ts b/packages/model-compat/src/cindy/proxy/headers.tsnew file mode 100644index 0000000000..c86743c8fb--- /dev/null+++ b/packages/model-compat/src/cindy/proxy/headers.ts@@ -0,0 +1,50 @@+/**+ * 共享的请求 header 读取工具。+ *+ * transform.ts 与 server.ts 都要从 flatten 后的 headers 里按名取值(大小写不敏感),+ * 收口到这里避免两份相同实现随时间漂移。+ */++/**+ * 取 threadId 的默认 header 候选名(按序取第一个非空)。收口到一处,避免+ * server.ts / transform.ts / host 各写一份字面量随时间漂移。+ *+ * 顺序按"稳定性"排:+ * - x-claude-code-session-id —— Claude Code 每个会话稳定(cc-code client.ts 注入),+ * Layer-2 主动剥离要靠它跨 turn 命中同一会话的标记。+ * - thread-id —— Codex app-server 每个 thread 稳定。+ * - x-client-request-id —— **每请求唯一**,只作最后兜底;命中它时 Layer-2 标记+ * 跨不过下一请求(但 Layer-1 反应式仍每轮兜底,功能不受影响,只是少省一次往返)。+ */+export const STABLE_THREAD_ID_HEADERS = [+ 'x-claude-code-session-id',+ 'thread-id',+] as const;++export const DEFAULT_THREAD_ID_HEADERS = [+ ...STABLE_THREAD_ID_HEADERS,+ 'x-client-request-id',+] as const;++/** 取单个 header 值(大小写不敏感),取不到返回空串。 */+export function headerValue(headers: Readonly<Record<string, string>>, name: string): string {+ const direct = headers[name];+ if (typeof direct === 'string' && direct.trim()) return direct.trim();+ const lower = name.toLowerCase();+ for (const [key, value] of Object.entries(headers)) {+ if (key.toLowerCase() === lower && value.trim()) return value.trim();+ }+ return '';+}++/** 按候选名顺序取第一个非空 header 值,都没有则返回空串。 */+export function selectedHeaderValue(+ headers: Readonly<Record<string, string>>,+ names: readonly string[],+): string {+ for (const name of names) {+ const value = headerValue(headers, name);+ if (value) return value;+ }+ return '';+}diff --git a/packages/model-compat/src/cindy/proxy/thread-strip-controller.ts b/packages/model-compat/src/cindy/proxy/thread-strip-controller.tsnew file mode 100644index 0000000000..a073eeb7fc--- /dev/null+++ b/packages/model-compat/src/cindy/proxy/thread-strip-controller.ts@@ -0,0 +1,58 @@+/**+ * Tracks threads that should proactively apply a body strip on every request,+ * after a thread has recovered once from a corresponding upstream 400.+ *+ * The controller is condition-agnostic (just a thread→model marker with a+ * model-change reset). Run ONE instance per independent strip condition — e.g.+ * one for encrypted_content, a separate one for empty thinking blocks. Sharing a+ * single instance across conditions would cross-contaminate: a recovery for one+ * condition would set shouldStrip=true and make the OTHER condition's active-strip+ * transform fire (e.g. stripping encrypted_content with no encrypted 400 — a real+ * cost: losing the model's reasoning chain).+ *+ * State is intentionally in-memory and per-instance. A process restart returns+ * every thread to the reactive retry path, and a model change clears the mark.+ */+export interface ThreadStripController {+ /** 标记某 thread 进入主动剥离(记下当时的 model)。 */+ markActive(threadId: string, model: string): void;+ /**+ * 状态收敛(有副作用):若该 thread 已标记但 model 变了(切了模型/供应商),清除标记。+ * 每个请求周期在 shouldStrip 之前调用一次。+ */+ reconcile(threadId: string, model: string): void;+ /** 纯读:该 thread 当前是否处于主动剥离状态(不修改任何状态)。 */+ shouldStrip(threadId: string): boolean;+ clear(threadId: string): void;+}++export function createThreadStripController(): ThreadStripController {+ const activeByThread = new Map<string, string>();++ return {+ markActive(threadId, model) {+ const tid = threadId.trim();+ const mid = model.trim();+ if (!tid || !mid) return;+ activeByThread.set(tid, mid);+ },++ reconcile(threadId, model) {+ const tid = threadId.trim();+ const mid = model.trim();+ if (!tid || !mid) return;+ const activeModel = activeByThread.get(tid);+ if (activeModel && activeModel !== mid) {+ activeByThread.delete(tid);+ }+ },++ shouldStrip(threadId) {+ return activeByThread.has(threadId.trim());+ },++ clear(threadId) {+ activeByThread.delete(threadId.trim());+ },+ };+}diff --git a/packages/model-compat/src/cindy/proxy/transform.ts b/packages/model-compat/src/cindy/proxy/transform.tsnew file mode 100644index 0000000000..11c083199e--- /dev/null+++ b/packages/model-compat/src/cindy/proxy/transform.ts@@ -0,0 +1,1663 @@+/**+ * 内置默认 transform —— 解决 "Claude Code SDK 在请求体里塞了 Anthropic-only 字段,+ * 但请求被路由到 OpenAI/Azure/litellm 后端,后端不认这些字段直接 400" 的问题。+ *+ * 设计: 每个有问题的 model 一个独立 handler 函数,自己决定怎么改写 body+ * (删字段 / 翻译字段 / 改值 / 条件改写 ...都可以)。字典里没有的 model 默认完全+ * 字节透传,proxy 对它们零干预。+ *+ * 加 handler 的判定标准: 该 model 在 XD.inc gateway 的实际请求被观察到 400+ * (典型: litellm.BadRequestError "Unknown parameter: 'XXX'") —— 截 maker.log+ * 留证据。不要凭"它跟 gpt-5.4 应该一样" 之类的推测扩。+ */++import { Buffer } from 'node:buffer';++import { DEFAULT_THREAD_ID_HEADERS, selectedHeaderValue } from './headers.js';+import type { ThreadStripController } from './thread-strip-controller.js';+import type { RecoveryRule, RequestTransform, RequestTransformCtx } from './types.js';++export { createVllmResponsesCompatibilityRule } from './vllm-responses-compatibility.js';++/**+ * 单个 model 的请求改写 handler。+ *+ * @param body 已经 parse 好的 plain object,调用前已确认 typeof body === 'object'+ * 且 body.model 命中字典 key。handler 内部不需要再做这些校验。+ * @returns 新的 body 对象 → 代理用它替换原 body 转发上游;+ * null → 显式表示"虽然命中我但不需要改",代理走透传。+ */+type ModelStripHandler = (body: Record<string, unknown>) => Record<string, unknown> | null;++function isPlainObject(v: unknown): v is Record<string, unknown> {+ return typeof v === 'object' && v !== null && !Array.isArray(v);+}++/**+ * 删除 Anthropic `tool_use` content block 上由 provider adapter 附加的+ * `provider_specific_fields`。只处理 tool_use 自身的字段,不触碰工具 input+ * 内同名的业务字段,避免把用户传给工具的参数误删。+ */+function deepDeleteToolUseProviderSpecificFields(node: unknown): number {+ let removed = 0;+ if (Array.isArray(node)) {+ for (const item of node) removed += deepDeleteToolUseProviderSpecificFields(item);+ return removed;+ }+ if (!isPlainObject(node)) return 0;++ if (node.type === 'tool_use') {+ if ('provider_specific_fields' in node) {+ delete node.provider_specific_fields;+ removed += 1;+ }+ // tool input is opaque user data. It may itself contain objects shaped like+ // Anthropic content blocks, so never recurse below an actual tool_use block.+ return removed;+ }+ for (const key of Object.keys(node)) {+ removed += deepDeleteToolUseProviderSpecificFields(node[key]);+ }+ return removed;+}++/**+ * 递归删除请求历史中 `tool_use.provider_specific_fields`,供主动 transform+ * 和 400 recovery 共用同一份字段清理逻辑。+ */+export function stripToolUseProviderSpecificFieldsFromBody(rawBody: Buffer): Buffer | null {+ let parsed: unknown;+ try {+ parsed = JSON.parse(rawBody.toString('utf8'));+ } catch {+ return null;+ }+ if (deepDeleteToolUseProviderSpecificFields(parsed) === 0) return null;+ try {+ return Buffer.from(JSON.stringify(parsed), 'utf8');+ } catch {+ return null;+ }+}++/**+ * 请求 transform 版本:body 已经由 proxy 解析为 plain object。+ * 无命中时返回 null,保持 clean request 的字节级透传语义。+ */+export const stripToolUseProviderSpecificFields: RequestTransform = (body) => {+ if (!isPlainObject(body)) return null;+ return deepDeleteToolUseProviderSpecificFields(body) > 0 ? body : null;+};++/**+ * Responses `input[]` 里的上下文压缩块 (OpenAI `/v1/responses/compact` 与 xAI 同名接口+ * 都回这个形态)。它的 `encrypted_content` 装的是**压缩 blob 本体** —— 压缩点之前的+ * 全部历史,不是可有可无的推理链。+ */+function isCompactionItem(node: Record<string, unknown>): boolean {+ return node.type === 'compaction' || node.type === 'context_compaction';+}++/**+ * Drop Codex agent-to-agent ciphertext at its protocol-defined location.+ *+ * A spawned Codex agent can call `send_message` from an otherwise ordinary+ * session; the resulting `agent_message` carries readable text and an optional+ * `{ type: 'encrypted_content', encrypted_content: '...' }` part. Deleting only+ * the field leaves a schema-invalid encrypted-content shell, so remove the+ * whole part before the generic recursive key strip. If the message contained+ * only ciphertext, the message itself has no replayable content and is dropped.+ *+ * This intentionally inspects only top-level Responses `input[]`; nested+ * business objects with a similarly shaped `content` array are not protocol+ * history and must not be interpreted by shape.+ */+function dropEncryptedAgentMessageContentParts(body: unknown): number {+ if (!isPlainObject(body) || !Array.isArray(body.input)) return 0;++ let removed = 0;+ const input: unknown[] = [];+ for (const item of body.input) {+ if (!isPlainObject(item) || item.type !== 'agent_message' || !Array.isArray(item.content)) {+ input.push(item);+ continue;+ }++ const content = item.content.filter((part) => {+ if (!isPlainObject(part) || part.type !== 'encrypted_content') return true;+ removed += 1;+ return false;+ });+ if (content.length === item.content.length) {+ input.push(item);+ } else if (content.length > 0) {+ input.push({ ...item, content });+ }+ }++ if (removed > 0) body.input = input;+ return removed;+}++/**+ * 递归删除 body 里所有 `encrypted_content` 键, 返回删掉的个数。+ * 用于 invalid_encrypted_content 报错后的透明重试 (见 stripEncryptedContentFromBody)。+ *+ * **压缩块整块跳过**: 剥掉压缩 blob 换不回一个可用请求 —— 上游收到没有 blob 的+ * 压缩空壳会直接判 "Could not decode the compaction blob. Ensure it is unmodified+ * from the compact response." (xAI 实报, 2026-07 Grok 会话卡死)。压缩块该怎么处置+ * 由上层按目标上游决定 (codex-proxy 的跨来源压缩兼容 transform 会把读不懂的加密块+ * 换成明文占位), 而那条兼容路径正是以"encrypted_content 非空"为触发条件 —— 在这里+ * 先剥就等于把它一并绕过。+ */+function deepDeleteEncryptedContent(node: unknown): number {+ let removed = 0;+ if (Array.isArray(node)) {+ for (const item of node) removed += deepDeleteEncryptedContent(item);+ return removed;+ }+ if (isPlainObject(node)) {+ if (isCompactionItem(node)) return 0;+ if ('encrypted_content' in node) {+ delete node.encrypted_content;+ removed += 1;+ }+ for (const key of Object.keys(node)) {+ removed += deepDeleteEncryptedContent(node[key]);+ }+ }+ return removed;+}++/** Responses `input[]` 里剥掉 encrypted_content 后已无密文的 reasoning 空壳。 */+function isReasoningItemWithoutEncryptedContent(item: unknown): boolean {+ if (!isPlainObject(item) || item.type !== 'reasoning') return false;+ return typeof item.encrypted_content !== 'string' || item.encrypted_content.length === 0;+}++/**+ * 缺 blob 的 `compaction` 空壳 —— 上游无法解码, 留着必 400, 只能丢。+ *+ * **只认 `compaction`, 不认 `context_compaction`**: codex wire 上 `Compaction.encrypted_content`+ * 必填、`ContextCompaction.encrypted_content` 可选 —— 后者不带密文是合法的可读压缩变体+ * (codex-proxy 的跨来源压缩兼容 transform 同样只处理带密文的项, 明文变体原样透传)。+ * 把它当空壳删掉会静默丢掉真实的压缩上下文。+ */+function isCompactionShellWithoutBlob(item: unknown): boolean {+ if (!isPlainObject(item) || item.type !== 'compaction') return false;+ return typeof item.encrypted_content !== 'string' || item.encrypted_content.length === 0;+}++/**+ * 丢掉 Responses 请求体**协议层** `input[]` 里解不开也修不好的空壳 item:+ * - 缺 blob 的 `compaction` (**恒丢**): 本模块不再制造这种空壳+ * (见 deepDeleteEncryptedContent), 但请求体可能已经带着它进来, 兜底丢掉,+ * 别让它打到上游换一个 400;+ * - 无 encrypted_content 的 reasoning (**仅 dropReasoningShells**): 只删+ * encrypted_content 键时,xAI 会把残留 reasoning item 判成 ModelInput 反序列化失败+ * (422)。这一条只在本轮确实剥掉过密文时才做 —— 没剥过的请求里,"reasoning 只带+ * summary" 是合法形态, 不该顺手删掉。+ *+ * **只看顶层 `input`, 不递归**: Responses 请求体的协议历史只有顶层这一个 `input[]`;+ * 嵌套结构里同名的 `input` 数组(工具参数、业务对象等)不是协议历史, 按 `type` 形状+ * 猜着删会静默改坏别人的数据。删密文键可以全树递归(定向删键, 只会少发不会发错),+ * 判定"整项该不该留"必须锚在协议层。+ */+function dropEncryptedShellInputItems(body: unknown, dropReasoningShells: boolean): number {+ if (!isPlainObject(body) || !Array.isArray(body.input)) return 0;++ let removed = 0;+ const kept: unknown[] = [];+ for (const item of body.input) {+ if (+ isCompactionShellWithoutBlob(item) ||+ (dropReasoningShells && isReasoningItemWithoutEncryptedContent(item))+ ) {+ removed += 1;+ continue;+ }+ kept.push(item);+ }+ if (removed > 0) body.input = kept;+ return removed;+}++/**+ * 把请求体里所有 `encrypted_content` 键递归删掉 (压缩块除外), 并丢掉解不开也修不好的+ * 空壳 input item, 返回新的 Buffer。+ *+ * 背景: gpt-5.5 等模型经 litellm/Azure 走 OpenAI Responses API (/v1/responses) 时,+ * 请求体的 reasoning item 带 `encrypted_content` (gAAA... 加密推理)。多部署负载均衡把+ * 后续请求路由到另一部署时, 它解不开上一部署的加密推理 → 400 invalid_encrypted_content。+ * xAI 同类失败文案是 "Could not decrypt the provided encrypted_content" (400/422)。+ * 删掉 encrypted_content 再重发即可恢复 (代价: 模型丢失上一轮的加密推理链, 可见对话保留)。+ * 若只删键、保留 type=reasoning 空壳,xAI 会再报 ModelInput 422 —— 所以空壳一并丢掉。+ *+ * **上下文压缩块除外**: 它的 encrypted_content 是压缩 blob 本体, 剥掉只会把请求变成+ * 上游无法解码的空壳 (详见 deepDeleteEncryptedContent)。+ *+ * 仅在 server.ts 收到该 400/422 后的"透明重试"路径调用, 正常请求不经过此函数。+ *+ * @returns 删掉了至少一个键或空壳 → 新 Buffer; body 非 JSON / 无可剥内容 → null (调用方据此决定不重试)+ */+export function stripEncryptedContentFromBody(rawBody: Buffer): Buffer | null {+ let parsed: unknown;+ try {+ parsed = JSON.parse(rawBody.toString('utf8'));+ } catch {+ return null;+ }+ // agent_message 的密文是 content part;必须在通用递归删键之前整块移除,否则会留下+ // `{ type: 'encrypted_content' }` 并被 OpenAI 拒绝为 missing_required_parameter。+ const removedAgentMessageParts = dropEncryptedAgentMessageContentParts(parsed);+ const removedKeys = deepDeleteEncryptedContent(parsed);+ // 空壳清理独立计数: 请求体里可能只带着一个缺 blob 的 compaction 空壳 (没有任何+ // encrypted_content 键可删), 那一样是必须处理的坏 payload, 不能因 removedKeys=0 放行。+ // 这一步只扫顶层 input[] (单次线性扫描), 不是第二遍深度遍历。+ const removedShells = dropEncryptedShellInputItems(parsed, removedKeys > 0);+ if (removedAgentMessageParts === 0 && removedKeys === 0 && removedShells === 0) return null;+ try {+ return Buffer.from(JSON.stringify(parsed), 'utf8');+ } catch {+ return null;+ }+}++function isImageGenerationType(type: unknown): boolean {+ if (typeof type !== 'string') return false;+ return type.startsWith('image_generation') || type.startsWith('imageGeneration');+}++function isImageGenerationItemWithoutId(item: unknown): boolean {+ if (!isPlainObject(item)) return false;+ if (!isImageGenerationType(item.type)) return false;+ const id = item.id;+ return typeof id !== 'string' || id.trim().length === 0;+}++function deepDeleteImageGenerationItemsWithoutId(node: unknown, inResponsesInputArray = false): number {+ let removed = 0;+ if (Array.isArray(node)) {+ let writeIndex = 0;+ for (const item of node) {+ if (inResponsesInputArray && isImageGenerationItemWithoutId(item)) {+ removed += 1;+ continue;+ }+ removed += deepDeleteImageGenerationItemsWithoutId(item);+ node[writeIndex] = item;+ writeIndex += 1;+ }+ node.length = writeIndex;+ return removed;+ }+ if (isPlainObject(node)) {+ for (const key of Object.keys(node)) {+ removed += deepDeleteImageGenerationItemsWithoutId(node[key], key === 'input');+ }+ }+ return removed;+}++/**+ * 删除 Responses 请求体里缺 `id` 的 image generation 历史 item。+ *+ * 背景: Codex rollout 会同时记录 event_msg:image_generation_end 和+ * response_item:image_generation_call。2026-07 实测 XD gateway → litellm/Azure+ * 会把缺 `id` 的 image_generation_end 回灌进下一轮 Responses input, Azure 直接 400:+ * "Image generation items without `id` are not supported for this request."+ *+ * 只删 Responses input 历史数组中 type 以 image_generation / imageGeneration 开头+ * 且缺 id 的对象;tools 里的 image_generation 工具声明、用户图片输入 input_image、+ * 已有 id 的 image_generation_call 都保留。+ */+export function stripImageGenerationItemsWithoutIdFromBody(rawBody: Buffer): Buffer | null {+ let parsed: unknown;+ try {+ parsed = JSON.parse(rawBody.toString('utf8'));+ } catch {+ return null;+ }+ const removed = deepDeleteImageGenerationItemsWithoutId(parsed);+ if (removed === 0) return null;+ try {+ return Buffer.from(JSON.stringify(parsed), 'utf8');+ } catch {+ return null;+ }+}++/** thinking 块的 `thinking` 字段是否为空(空串 / 缺失 / 非字符串都算空)。 */+function isEmptyThinkingBlock(block: unknown): boolean {+ if (!isPlainObject(block)) return false;+ if (block.type !== 'thinking') return false;+ const t = block.thinking;+ return typeof t !== 'string' || t.trim().length === 0;+}++/**+ * 删除请求体里"空内容" thinking 块,返回新 Buffer;没改动 / 非 JSON / 无 messages → null。+ *+ * 背景: 跨厂商切模型时,Claude Code 会话历史累积了非 Anthropic 厂商产出的 thinking 块。+ * gpt-5.5 等"推理加密"模型产出空壳 {type:"thinking", thinking:"", signature:""}(真实推理在+ * encrypted_content 里,litellm 转 Anthropic 格式只留空壳)。切回真 Anthropic 模型时 API 400:+ * "messages.N.content.0.thinking: each thinking block must contain thinking"。+ *+ * 判别式只看 thinking 内容是否为空 —— deepseek 那种"有内容、签名空"的块被 gateway 容忍,+ * 不删;真 Anthropic 块有内容 + 有签名,更不会命中。删空块零代价(块里本就没内容)。+ *+ * 边界:+ * - 某条 message 的 content 删空后 → 整条 message 丢弃(Anthropic 也拒空 content)。+ * - 被删块所在轮若含 tool_use(开 thinking 时可能换来另一个 400)→ 保留不动 + 调用方按需记日志;+ * 该状态本就已坏,no-loop 保证下不会更糟,强行丢残轮风险更高。+ *+ * @returns 删掉至少一个空块 → 新 Buffer; body 非 JSON / messages 非数组 / 无空块 → null+ * (返回 null 是 cache 安全契约:让代理字节透传,正常会话零影响)。+ */+export function stripEmptyThinkingFromBody(rawBody: Buffer): Buffer | null {+ let parsed: unknown;+ try {+ parsed = JSON.parse(rawBody.toString('utf8'));+ } catch {+ return null;+ }+ if (!isPlainObject(parsed)) return null;+ const messages = parsed.messages;+ if (!Array.isArray(messages)) return null;++ let removed = 0;+ const keptMessages: unknown[] = [];+ for (const msg of messages) {+ if (!isPlainObject(msg) || !Array.isArray(msg.content)) {+ keptMessages.push(msg);+ continue;+ }+ const keptContent = msg.content.filter((block) => {+ if (isEmptyThinkingBlock(block)) {+ removed += 1;+ return false;+ }+ return true;+ });+ if (keptContent.length === msg.content.length) {+ keptMessages.push(msg); // 该 message 没动+ } else if (keptContent.length === 0) {+ // content 被清空 → 整条 message 丢弃(边界 a);removed 已累加,下方仍判定有改动。+ } else {+ keptMessages.push({ ...msg, content: keptContent });+ }+ }++ if (removed === 0) return null; // ← cache 安全契约:无改动 → null → 字节透传+ parsed.messages = keptMessages;+ try {+ return Buffer.from(JSON.stringify(parsed), 'utf8');+ } catch {+ return null;+ }+}++/** text 块的 `text` 字段是否为空(空串 / 纯空白 / 缺失 / 非字符串都算空)。 */+function isEmptyTextBlock(block: unknown): boolean {+ if (!isPlainObject(block)) return false;+ if (block.type !== 'text') return false;+ const t = block.text;+ return typeof t !== 'string' || t.trim().length === 0;+}++/**+ * 删除请求体里空内容 text 块,返回新 Buffer;没改动 / 非 JSON / 无 messages → null。+ *+ * 背景: anthropic-responses-bridge 修复前会把纯工具轮的 message item 落成+ * `{type:"text", text:""}` 空块写进 Claude Code 会话历史(eager 开块被 function_call+ * 抢占强制关掉)。会话切到真 Anthropic 模型时历史原样回放,API 400:+ * "messages.N.content.M: text content blocks must be non-empty"。bridge 已改为惰性+ * 开块不再产出新空块;本函数负责修复期之前累积的存量脏历史 —— 命中 400 后剥掉+ * 空块透明重试(结构与 stripEmptyThinkingFromBody 一致)。+ *+ * 只处理 messages[].content 顶层块,不深入 tool_result 嵌套 content(实测命中的+ * 只有顶层;嵌套形态被打脸再扩)。+ *+ * 边界: 某条 message 的 content 删空后 → 整条 message 丢弃(Anthropic 也拒空 content)。+ *+ * @returns 删掉至少一个空块 → 新 Buffer; body 非 JSON / messages 非数组 / 无空块 → null+ * (返回 null 是 cache 安全契约:让代理字节透传,正常会话零影响)。+ */+export function stripEmptyTextFromBody(rawBody: Buffer): Buffer | null {+ let parsed: unknown;+ try {+ parsed = JSON.parse(rawBody.toString('utf8'));+ } catch {+ return null;+ }+ if (!isPlainObject(parsed)) return null;+ const messages = parsed.messages;+ if (!Array.isArray(messages)) return null;++ let removed = 0;+ const keptMessages: unknown[] = [];+ for (const msg of messages) {+ if (!isPlainObject(msg) || !Array.isArray(msg.content)) {+ keptMessages.push(msg);+ continue;+ }+ const keptContent = msg.content.filter((block) => {+ if (isEmptyTextBlock(block)) {+ removed += 1;+ return false;+ }+ return true;+ });+ if (keptContent.length === msg.content.length) {+ keptMessages.push(msg); // 该 message 没动+ } else if (keptContent.length === 0) {+ // content 被清空 → 整条 message 丢弃;removed 已累加,下方仍判定有改动。+ } else {+ keptMessages.push({ ...msg, content: keptContent });+ }+ }++ if (removed === 0) return null; // ← cache 安全契约:无改动 → null → 字节透传+ parsed.messages = keptMessages;+ try {+ return Buffer.from(JSON.stringify(parsed), 'utf8');+ } catch {+ return null;+ }+}++/**+ * 丢弃请求历史里的空 assistant 消息(含剥掉空 thinking 块后变空壳的),返回新 Buffer;+ * 没改动 / 非 JSON / 无 messages → null。+ *+ * 背景: moonshot/kimi-k3 经 LiteLLM 原生转发(/anthropic/v1/messages passthrough)时,+ * 其 Anthropic 兼容流首包是空 thinking 占位 {type:"thinking",thinking:"",signature:""}+ * (kimi 官方确认 by design);流被 429/中断切断后,客户端把未完成的占位 block 当成完整+ * assistant 持久化,回放时 moonshot 400:+ * "Invalid request: the message at position 693 with role 'assistant' must not be empty"+ * (2026-07-28 线上实测,两个独立会话 position 693 / 275,重试 35+ 次全部失败,+ * 会话级永久卡死——每轮请求历史都带污染消息)。+ *+ * 处理(与 kimi code 官方客户端的兜底策略同构——发送出去的请求不允许带空 assistant):+ * 1. assistant 消息 content 为 string 且为空白 → 整条丢弃;+ * 2. assistant 消息 content 为数组:先剥空 thinking 块与空 text 块(判别式与+ * stripEmptyThinkingFromBody / stripEmptyTextFromBody 一致,有内容/签名空的块+ * 保留),剥完为空(含原生 content:[])→ 整条丢弃;剥完仍有 text/tool_use →+ * 保留净化后的消息。空 text 块一并剥的原因:moonshot 的 must-not-be-empty 校验+ * 对 bridge 清理路径产出的 text-only 空块消息同样命中(PR #821 review 实测反馈),+ * 只剥 thinking 会让该形态 strip 不出东西、重试被跳过,会话继续卡死。+ * user 消息一律不动(线上命中的只有 assistant;user 空消息无实测证据,不扩散)。+ *+ * 安全性: 空消息不含任何对话信息,丢弃不改变语义;含 tool_use 的轮次剥完非空,+ * tool_use/tool_result 配对不会被打破。+ *+ * @returns 丢弃/净化至少一条 → 新 Buffer; 无改动 → null (cache 安全契约:字节透传)。+ */+export function stripEmptyAssistantMessagesFromBody(rawBody: Buffer): Buffer | null {+ let parsed: unknown;+ try {+ parsed = JSON.parse(rawBody.toString('utf8'));+ } catch {+ return null;+ }+ if (!isPlainObject(parsed)) return null;+ const messages = parsed.messages;+ if (!Array.isArray(messages)) return null;++ let changed = false;+ const keptMessages: unknown[] = [];+ for (const msg of messages) {+ if (!isPlainObject(msg) || msg.role !== 'assistant') {+ keptMessages.push(msg);+ continue;+ }+ const content = msg.content;+ if (typeof content === 'string') {+ if (content.trim().length === 0) {+ changed = true; // 空 string content → 整条丢弃+ continue;+ }+ keptMessages.push(msg);+ continue;+ }+ if (!Array.isArray(content)) {+ keptMessages.push(msg); // 异常形态不猜,原样保留+ continue;+ }+ const keptContent = content.filter((block) => !isEmptyThinkingBlock(block) && !isEmptyTextBlock(block));+ if (keptContent.length === 0) {+ changed = true; // 空壳(content:[] 或剥空 thinking/空 text 后为空)→ 整条丢弃+ continue;+ }+ if (keptContent.length !== content.length) {+ changed = true;+ keptMessages.push({ ...msg, content: keptContent });+ continue;+ }+ keptMessages.push(msg);+ }++ if (!changed) return null; // ← cache 安全契约:无改动 → null → 字节透传+ parsed.messages = keptMessages;+ try {+ return Buffer.from(JSON.stringify(parsed), 'utf8');+ } catch {+ return null;+ }+}++// ───────────────────────────────────────────────────────────────────────────+// Tool exchange 结构修复 —— 与 kimi code 官方客户端的投影修复同构+// (kosong normalizeToolCallIdsForProvider + agent-core projector),移植到+// Anthropic Messages wire 格式:+// - tool_use 块在 assistant 消息 content 内;tool_result 块在 user 消息+// content 内(kimi 内部格式里 tool result 是独立的 role:'tool' 消息)。+// - 两个 transform 都是**检测即修**:扫描发现协议级异常才改写,无异常返回+// null(cache 安全契约:字节透传,正常会话零影响)。不需要 ThreadStripController+// —— 重复 id / 配对断裂在请求体里可直接检测,不像 encrypted_content 要靠+// 撞 400 才能判定该剥。+// ───────────────────────────────────────────────────────────────────────────++function isToolUseBlock(block: unknown): block is Record<string, unknown> & { id: string } {+ return (+ isPlainObject(block) &&+ block.type === 'tool_use' &&+ typeof block.id === 'string' &&+ block.id.length > 0+ );+}++function isToolResultBlock(+ block: unknown,+): block is Record<string, unknown> & { tool_use_id: string } {+ return (+ isPlainObject(block) &&+ block.type === 'tool_result' &&+ typeof block.tool_use_id === 'string' &&+ block.tool_use_id.length > 0+ );+}++/**+ * 重复 tool_use id 唯一化(检测即修),返回新 messages;无重复 → null。+ *+ * 背景: moonshot/kimi 系的 tool_call id 是服务端按序号铸造的(`Edit_306` /+ * `Bash_256` 这类 `${name}_${index}` 形态,经 LiteLLM 字符清洗后冒号变下划线)。+ * 长会话里序号生成会卡住,同一个 id 被跨 turn 反复复用(2026-07 两个独立会话+ * 实测各复用 20+ 次)——模型看回放历史时工具交换错乱,表现为"工具调用凭空+ * 消失"、安静瘫痪。kimi code 官方对原始重复 id 的处理是 400 后 strict resend+ * 丢弃(agent-core projector dedupeDuplicateToolCalls),但 moonshot 容忍重复+ * id 不报 400,strict 路径永远触发不了 → 这里改为发送前检测即修。+ *+ * 与 kimi strict 的**丢弃**不同,这里选择**重写**(kosong normalize 思路):+ * 首现保留,第 N 次出现重写为 `${id}_${N}`(与现存 id 撞车时顺延后缀),+ * 顺序配对的第 N 个 tool_result 同步改写。每个重复对背后是不同的逻辑调用,+ * 丢弃会抹历史;重写保持配对完整,且 `_N` 后缀在 Anthropic id 合法字符集+ * (`[a-zA-Z0-9_-]`)内,对任何上游都是协议修复而非篡改。+ *+ * 配对规则: 按出现顺序,第 N 个 result 配第 N 个 call(正常历史里 result 紧跟+ * 其 call,顺序配对即真实配对)。result 比 call 多的尾部块保持原样(指向首现+ * call;超编残留的清理由 repairToolExchangeAdjacency 负责)。+ *+ * 边界(刻意不做): id 字符集 sanitize(kimi kosong 会把 `Edit:306` 的冒号洗成+ * 下划线)不在本 transform 范围 —— 本链路上游(LiteLLM)已做过清洗,非法字符+ * id 无实测证据;实测命中再扩。`_N` 后缀只含合法字符,不会把合法 id 改非法。+ *+ * rename key 用 ` ` 分隔 id 与出现序号:Anthropic 合法 id 字符集不含空格,+ * 不会与真实 id 撞 key;病态含空格 id 的重写结果仍由 usedIds 保证唯一。+ */+function dedupeToolUseIdsInMessages(messages: unknown[]): unknown[] | null {+ // pass 1: 统计每个 call id 出现次数。usedIds(后缀撞车判定)只在确有重复、+ // 进入改名阶段时才从 counts.keys() 构建 —— clean 请求(绝大多数)零 Set 分配。+ const counts = new Map<string, number>();+ for (const msg of messages) {+ if (!isPlainObject(msg) || msg.role !== 'assistant' || !Array.isArray(msg.content)) continue;+ for (const block of msg.content) {+ if (!isToolUseBlock(block)) continue;+ counts.set(block.id, (counts.get(block.id) ?? 0) + 1);+ }+ }+ let hasDuplicate = false;+ for (const n of counts.values()) {+ if (n > 1) {+ hasDuplicate = true;+ break;+ }+ }+ if (!hasDuplicate) return null; // cache 安全契约:无重复 → 透传++ // pass 2a: 给每个 call 的第 N(N≥2) 次出现分配全局唯一新 id。+ const usedIds = new Set(counts.keys());+ const renameByOccurrence = new Map<string, string>();+ const callSeen = new Map<string, number>();+ for (const msg of messages) {+ if (!isPlainObject(msg) || msg.role !== 'assistant' || !Array.isArray(msg.content)) continue;+ for (const block of msg.content) {+ if (!isToolUseBlock(block)) continue;+ const n = (callSeen.get(block.id) ?? 0) + 1;+ callSeen.set(block.id, n);+ if (n === 1) continue;+ let suffix = n;+ let candidate = `${block.id}_${suffix}`;+ while (usedIds.has(candidate)) {+ suffix += 1;+ candidate = `${block.id}_${suffix}`;+ }+ usedIds.add(candidate);+ renameByOccurrence.set(`${block.id} ${n}`, candidate);+ }+ }++ // pass 2b: 重写 call 与顺序配对的 result(第 N 个 result 查第 N 次 call 的改名;+ // 查不到 = 该 result 无对应第 N 个 call,保持原样)。+ const callWriteSeen = new Map<string, number>();+ const resultSeen = new Map<string, number>();+ const nextMessages = messages.map((msg) => {+ if (!isPlainObject(msg) || !Array.isArray(msg.content)) return msg;+ let msgChanged = false;+ const nextContent = msg.content.map((block) => {+ if (msg.role === 'assistant' && isToolUseBlock(block)) {+ const n = (callWriteSeen.get(block.id) ?? 0) + 1;+ callWriteSeen.set(block.id, n);+ const renamed = renameByOccurrence.get(`${block.id} ${n}`);+ if (renamed === undefined) return block;+ msgChanged = true;+ return { ...block, id: renamed };+ }+ if (msg.role === 'user' && isToolResultBlock(block)) {+ const n = (resultSeen.get(block.tool_use_id) ?? 0) + 1;+ resultSeen.set(block.tool_use_id, n);+ const renamed = renameByOccurrence.get(`${block.tool_use_id} ${n}`);+ if (renamed === undefined) return block;+ msgChanged = true;+ return { ...block, tool_use_id: renamed };+ }+ return block;+ });+ return msgChanged ? { ...msg, content: nextContent } : msg;+ });+ return nextMessages;+}++/**+ * Buffer 版: 重复 tool_use id 唯一化。供 400 recovery(``tool_use` ids must be+ * unique`)与主动 transform 共用同一份修复逻辑。+ */+export function dedupeDuplicateToolUseIdsFromBody(rawBody: Buffer): Buffer | null {+ let parsed: unknown;+ try {+ parsed = JSON.parse(rawBody.toString('utf8'));+ } catch {+ return null;+ }+ if (!isPlainObject(parsed)) return null;+ const messages = parsed.messages;+ if (!Array.isArray(messages)) return null;+ const nextMessages = dedupeToolUseIdsInMessages(messages);+ if (nextMessages === null) return null;+ parsed.messages = nextMessages;+ try {+ return Buffer.from(JSON.stringify(parsed), 'utf8');+ } catch {+ return null;+ }+}++/**+ * 主动 transform 版: body 已由 proxy 解析为 plain object。+ * 无重复返回 null,保持 clean request 的字节级透传语义。+ */+export const dedupeDuplicateToolUseIds: RequestTransform = (body) => {+ if (!isPlainObject(body)) return null;+ const messages = body.messages;+ if (!Array.isArray(messages)) return null;+ const nextMessages = dedupeToolUseIdsInMessages(messages);+ if (nextMessages === null) return null;+ return { ...body, messages: nextMessages };+};++/**+ * 未配对 call 的合成占位 result 文本(与 kimi code projector 的+ * SYNTHETIC_TOOL_RESULT_TEXT 同文案同语义:明确告知结果缺失、禁止假设成功;+ * 不设 is_error —— "上下文里结果不可用"≠"工具执行失败",避免模型误重试)。+ */+const SYNTHETIC_TOOL_RESULT_TEXT =+ 'Tool result is not available in the current context. Do not assume the tool completed successfully.';++/**+ * tool_use/tool_result 配对断裂修复(检测即修),返回新 messages;无断裂 → null。+ *+ * 与 kimi code projector 的 repairToolExchangeAdjacency + dropOrphanResults+ * 同构(consumed-scan),移植到 Anthropic 格式:+ * 1. 位置配对优先: 每个 call 先消费紧邻下一条消息里同 id 的未消费 result+ * 块(CC 投影的正常形态,位置证据最强的配对);全部 call(含 trailing)+ * 做完位置配对后才进入接力 —— 否则较早的同 id 缺口 call 会抢走较晚+ * call 紧邻位置的真实 result,造成张冠李戴。+ * 2. 接力补缺 + 错位重排: 位置配对失败的 call 从结果池取**归属区间**(本+ * assistant 消息到下一条含同 id call 的 assistant 消息之间 —— agentic+ * loop 串行,出现在下一个同 id exchange 之后的 result 只属于后面的+ * exchange,较早缺口不得越界抢走;同消息 parallel calls 的归属不可判定+ * 时按稳定 tie-breaker 沿 call 块顺序配序,该约定受典型 client+ * serializer 支持但非 wire 可证明)内的第一个未消费块;不在合法位置+ * (跨消息,或同消息内落在 text 之后)的前移至紧邻消息的前导+ * tool_result 区间,原位置移除。Anthropic 要求 result 紧跟 call 所在+ * assistant 且居于 text 前,留在错误位置仍是 400。+ * 3. 缺失合成: 非 trailing 的 call 无候选 → 紧邻位置合成占位(kimi 同文案+ * 同语义;不设 is_error —— "结果不可用"≠"执行失败")。插入规则与重排+ * 相同;string content 转等价数组,空白 string 不附加 text 块。+ * 4. 丢弃: 孤儿 result(全历史无匹配 call)、池中剩余(前置 result —— 引用+ * 未来 call 本身非法;同 id 超编残留 —— 一个 call 恰应有一个应答)全部+ * 移除;user 消息 content 因此清空 → 整条丢弃。+ * 5. trailing 豁免: 最后一个「对话推进点」处的 assistant(末尾交换)只消费+ * 不修复 —— 缺失 result 可能真在飞,不合成、不重排;其后的纯 result+ * 消息视为交换一部分,不会误判为残留丢弃。+ */+/**+ * 最后一个「对话推进点」下标: assistant 消息,或含非 tool_result 内容的 user+ * 消息(纯 tool_result 的 user 消息可能是 trailing 交换的一部分,不算推进点);+ * 异常形态(非 plain object / string content)保守按推进点计。无 → -1。+ */+function findLastConversationIndex(messages: unknown[]): number {+ for (let i = messages.length - 1; i >= 0; i--) {+ const msg = messages[i];+ if (!isPlainObject(msg)) return i;+ if (msg.role === 'assistant' || !Array.isArray(msg.content)) return i;+ if (msg.role === 'user' && msg.content.some((block) => !isToolResultBlock(block))) return i;+ }+ return -1;+}++/**+ * content 前导 tool_result 区间的长度(开头连续 tool_result 块数)。+ * Anthropic 惯例(CC 原生形态): 一条 user 消息里所有 tool_result 块在最前,+ * text 等其它块在后;result 落在 text 之后 = 块级错位,需重排进前导区间。+ */+function leadingToolResultCount(content: unknown[]): number {+ let k = 0;+ while (k < content.length && isToolResultBlock(content[k])) k += 1;+ return k;+}++function repairToolExchangeAdjacencyInMessages(messages: unknown[]): unknown[] | null {+ // pass A: 全历史 call id 集合 + result 块位置池(per id 按出现升序)。+ // 孤儿 result(无匹配 call)不入池,直接进丢弃清单。+ const callIds = new Set<string>();+ for (const msg of messages) {+ if (!isPlainObject(msg) || msg.role !== 'assistant' || !Array.isArray(msg.content)) continue;+ for (const block of msg.content) {+ if (isToolUseBlock(block)) callIds.add(block.id);+ }+ }+ const resultPool = new Map<string, Array<{ msgIdx: number; blockIdx: number }>>();+ const drops: Array<{ msgIdx: number; blockIdx: number }> = [];+ for (let i = 0; i < messages.length; i++) {+ const msg = messages[i];+ if (!isPlainObject(msg) || msg.role !== 'user' || !Array.isArray(msg.content)) continue;+ for (let b = 0; b < msg.content.length; b++) {+ const block = msg.content[b];+ if (!isToolResultBlock(block)) continue;+ if (!callIds.has(block.tool_use_id)) {+ drops.push({ msgIdx: i, blockIdx: b });+ continue;+ }+ const list = resultPool.get(block.tool_use_id) ?? [];+ list.push({ msgIdx: i, blockIdx: b });+ resultPool.set(block.tool_use_id, list);+ }+ }++ // pass B1: 位置配对 —— 每个 call 优先消费紧邻下一条消息里同 id 的未消费+ // result 块(CC 投影的正常形态,位置证据最强的配对)。**全部 call(含+ // trailing)先做完位置配对再做接力**:否则较早的同 id 缺口 call 会在接力时+ // 抢走较晚 call 紧邻位置的真实 result(张冠李戴,Greptile P1 实测反例:+ // call#1 缺 result、call#2 有真实 result → call#1 越权消费、call#2 反得+ // 合成占位)。trailing call 参与位置配对(消费合法尾部 result)但不做修复。+ const lastConversationIndex = findLastConversationIndex(messages);+ const consumed = new Set<string>(); // `${msgIdx}:${blockIdx}`+ // assistant 下标 → (call 块下标 → 要插入的 result 块),按 call 顺序组装。+ const insertPlans = new Map<number, Map<number, unknown>>();+ const recordInsert = (assistantIdx: number, callBlockIdx: number, block: unknown) => {+ const plan = insertPlans.get(assistantIdx) ?? new Map<number, unknown>();+ plan.set(callBlockIdx, block);+ insertPlans.set(assistantIdx, plan);+ };+ const missingCalls: Array<{ i: number; id: string; trailing: boolean; callBlockIdx: number }> = [];+ for (let i = 0; i <= lastConversationIndex; i++) {+ const msg = messages[i];+ if (!isPlainObject(msg) || msg.role !== 'assistant' || !Array.isArray(msg.content)) continue;+ const trailing = i >= lastConversationIndex;+ const nextMsg = messages[i + 1];+ const nextContent =+ isPlainObject(nextMsg) && nextMsg.role === 'user' && Array.isArray(nextMsg.content)+ ? nextMsg.content+ : null;+ for (let cb = 0; cb < msg.content.length; cb++) {+ const block = msg.content[cb];+ if (!isToolUseBlock(block)) continue;+ const id = block.id;+ let hit: { msgIdx: number; blockIdx: number } | undefined;+ if (nextContent !== null) {+ for (let b = 0; b < nextContent.length; b++) {+ const cand = nextContent[b];+ if (isToolResultBlock(cand) && cand.tool_use_id === id && !consumed.has(`${i + 1}:${b}`)) {+ hit = { msgIdx: i + 1, blockIdx: b };+ break;+ }+ }+ }+ if (hit !== undefined) {+ consumed.add(`${hit.msgIdx}:${hit.blockIdx}`);+ // 已邻接判定到块级: 位于前导 tool_result 区间则不动;落在 text 之后+ // = 块级错位 → 前移进前导区间( trailing 只消费不修复)。+ if (!trailing && hit.blockIdx >= leadingToolResultCount(nextContent!)) {+ drops.push(hit);+ recordInsert(i, cb, nextContent![hit.blockIdx]);+ }+ } else {+ missingCalls.push({ i, id, trailing, callBlockIdx: cb });+ }+ }+ }++ // pass B2: 接力 —— 位置配对失败的 call,从结果池取**归属区间**内的第一个+ // 未消费块前移(错位重排);无候选 → 非 trailing 合成占位。+ //+ // 归属区间 = (本 assistant 消息下标, 下一条含同 id call 的 assistant 消息+ // 下标) —— 即"同 id exchange"边界。依据 agentic loop 串行:下一个 exchange+ // 的同 id call 发出时,本 exchange 的同 id result 必已回来(或丢失),出现在+ // 下一个 exchange 之后的 result 只属于后面的 exchange;较早缺口 exchange+ // 不得越界抢较晚 exchange 的错位真实结果(Greptile 第二轮反例)。+ //+ // 边界粒度刻意是 exchange(消息)而非单个 call:同一条 assistant 消息内的+ // parallel 同 id calls 同批发出、result 同批回来,其中一个丢失时归属在+ // 原理上不可判定(信息论:两种归属的世界序列化后字节完全相同,缺失不留+ // 位置痕迹)—— 此时采用**稳定 tie-breaker**:区间内涵 call 块顺序配序。+ // 该约定受典型 client serializer 支持(CC SDK 的 Tool Runner 以+ // Promise.all 并发执行、但结果数组保持输入 tool_use 顺序),可复现且最大+ // 保留信息;但只是默认约定,不是 wire 可证明的归属 —— 真正消除歧义只能+ // 在丢失前由 source adapter 持久化 occurrence/call index(provenance),+ // 本层对已有 body 无法补造这个 bit。+ //+ // trailing missing call 同样消费区间内的块,但**只消费不修复**(不移、不+ // 合成)——保护 trailing 交换的合法尾部 result(如 parallel trailing calls+ // 的 result 分多条消息回来)不被下方"池剩余丢弃"误杀。+ const callIndicesById = new Map<string, number[]>();+ for (let i = 0; i <= lastConversationIndex; i++) {+ const msg = messages[i];+ if (!isPlainObject(msg) || msg.role !== 'assistant' || !Array.isArray(msg.content)) continue;+ for (const block of msg.content) {+ if (!isToolUseBlock(block)) continue;+ const list = callIndicesById.get(block.id) ?? [];+ list.push(i);+ callIndicesById.set(block.id, list);+ }+ }+ for (const mc of missingCalls) {+ const pool = resultPool.get(mc.id) ?? [];+ const indices = callIndicesById.get(mc.id) ?? [];+ let nextIdx = Number.POSITIVE_INFINITY;+ for (const idx of indices) {+ if (idx > mc.i) {+ nextIdx = idx;+ break;+ }+ }+ let hit: { msgIdx: number; blockIdx: number } | undefined;+ for (const cand of pool) {+ const key = `${cand.msgIdx}:${cand.blockIdx}`;+ if (consumed.has(key)) continue;+ if (cand.msgIdx <= mc.i || cand.msgIdx >= nextIdx) continue; // 区间外(前置/归后面的 call)+ hit = cand;+ break;+ }+ if (hit !== undefined) {+ consumed.add(`${hit.msgIdx}:${hit.blockIdx}`);+ if (!mc.trailing) {+ drops.push(hit);+ const srcMsg = messages[hit.msgIdx] as Record<string, unknown>;+ recordInsert(mc.i, mc.callBlockIdx, (srcMsg.content as unknown[])[hit.blockIdx]);+ }+ // trailing: 仅 consumed 保护,不动位置。+ } else if (!mc.trailing) {+ recordInsert(mc.i, mc.callBlockIdx, {+ type: 'tool_result',+ tool_use_id: mc.id,+ content: SYNTHETIC_TOOL_RESULT_TEXT,+ });+ }+ }+ // 池中剩余(前置 / 超编 / 永不配对)→ 全部丢弃。+ for (const pool of resultPool.values()) {+ for (const cand of pool) {+ const key = `${cand.msgIdx}:${cand.blockIdx}`;+ if (consumed.has(key)) continue;+ drops.push(cand);+ consumed.add(key);+ }+ }+ // 每个 assistant 的插入块按 call 块顺序拼装(位置配对与接力分两遍收集,+ // 顺序不一定与 call 顺序一致)。+ const insertBlocksAfter = new Map<number, unknown[]>();+ for (const [assistantIdx, plan] of insertPlans) {+ insertBlocksAfter.set(+ assistantIdx,+ [...plan.entries()].sort((a, b) => a[0] - b[0]).map(([, block]) => block),+ );+ }++ if (drops.length === 0 && insertBlocksAfter.size === 0) return null; // cache 安全契约++ // pass C: 单遍组装。drops 按消息分组过滤;插入计划落在 assistant 之后 ——+ // 下一条是 user 消息则标记 prepend(遍历到它时并入其 content 的前导+ // tool_result 区间末尾,保持 result 在前、与 call 顺序一致),否则就地新建+ // user 消息。user 消息过滤后(含 prepend)content 空 → 整条丢。+ const dropsByMsg = new Map<number, Set<number>>();+ for (const d of drops) {+ const set = dropsByMsg.get(d.msgIdx) ?? new Set<number>();+ set.add(d.blockIdx);+ dropsByMsg.set(d.msgIdx, set);+ }+ const prependByMsg = new Map<number, unknown[]>();+ const out: unknown[] = [];+ for (let i = 0; i < messages.length; i++) {+ const msg = messages[i];+ let current = msg;+ if (isPlainObject(msg) && msg.role === 'user') {+ const dropsHere = dropsByMsg.get(i);+ const prepend = prependByMsg.get(i);+ if (Array.isArray(msg.content) && (dropsHere !== undefined || prepend !== undefined)) {+ const filtered = dropsHere ? msg.content.filter((_, b) => !dropsHere.has(b)) : [...msg.content];+ const k = leadingToolResultCount(filtered);+ const content = [...filtered.slice(0, k), ...(prepend ?? []), ...filtered.slice(k)];+ if (content.length === 0) continue; // content 清空 → 整条丢+ current = { ...msg, content };+ } else if (typeof msg.content === 'string' && prepend !== undefined) {+ // string content 转等价数组并入;空白 string 不附加 text 块(避免新造+ // 空 text 块,转头命中 "text content blocks must be non-empty" 400)。+ const text = msg.content.trim().length > 0 ? [{ type: 'text', text: msg.content }] : [];+ current = { ...msg, content: [...prepend, ...text] };+ }+ }+ out.push(current);+ const inserts = insertBlocksAfter.get(i);+ if (inserts !== undefined && inserts.length > 0) {+ const next = messages[i + 1];+ if (isPlainObject(next) && next.role === 'user') {+ prependByMsg.set(i + 1, [...(prependByMsg.get(i + 1) ?? []), ...inserts]);+ } else {+ out.push({ role: 'user', content: inserts });+ }+ }+ }+ return out;+}++/**+ * Buffer 版: 配对断裂修复。供 400 recovery(tool_call_id not found /+ * unexpected tool_use_id / tool_use without tool_result)与主动 transform 共用。+ */+export function repairToolExchangeAdjacencyFromBody(rawBody: Buffer): Buffer | null {+ let parsed: unknown;+ try {+ parsed = JSON.parse(rawBody.toString('utf8'));+ } catch {+ return null;+ }+ if (!isPlainObject(parsed)) return null;+ const messages = parsed.messages;+ if (!Array.isArray(messages)) return null;+ const nextMessages = repairToolExchangeAdjacencyInMessages(messages);+ if (nextMessages === null) return null;+ parsed.messages = nextMessages;+ try {+ return Buffer.from(JSON.stringify(parsed), 'utf8');+ } catch {+ return null;+ }+}++/**+ * 主动 transform 版: body 已由 proxy 解析为 plain object。+ * 无断裂返回 null,保持 clean request 的字节级透传语义。+ */+export const repairToolExchangeAdjacency: RequestTransform = (body) => {+ if (!isPlainObject(body)) return null;+ const messages = body.messages;+ if (!Array.isArray(messages)) return null;+ const nextMessages = repairToolExchangeAdjacencyInMessages(messages);+ if (nextMessages === null) return null;+ return { ...body, messages: nextMessages };+};++/**+ * 组合结构修复: 先 adjacency 接力配对,再重复 id 唯一化 —— 顺序不可颠倒。+ *+ * 为什么必须 repair 在前: dedupe 的「第 N 个 result 配第 N 个 call」依赖+ * result 顺序与 call 顺序一一对应,而病态历史里的前置 result(在 call 之前)+ * 会白占一个序号,把本属前一个 call 的 result 改名给后一个 call,repair 再按+ * 改名后的 id 配对 → 张冠李戴(复审实测反例: call#1 收到 call#2 的真实结果、+ * call#1 自己的结果被丢)。repair 先跑会丢弃前置/超编块、把错位块归位,产出的+ * 结构合法历史上 result 与 call 严格同序,dedupe 的顺序配对才等于真实配对。+ *+ * 供两条 recovery rule 共用: server.ts 的透明重试是「命中规则先 strip,其余按+ * 数组顺序顺手应用」,命中顺序会打乱数组里声明的修复顺序,只有组合函数能强制+ * repair → dedupe。两步各自检测驱动,无对应异常时该步原样传递。+ */+export function repairToolExchangeStructureFromBody(rawBody: Buffer): Buffer | null {+ const afterRepair = repairToolExchangeAdjacencyFromBody(rawBody);+ const stage1 = afterRepair ?? rawBody;+ const afterDedupe = dedupeDuplicateToolUseIdsFromBody(stage1);+ if (afterRepair === null && afterDedupe === null) return null; // 两步都无改动+ return afterDedupe ?? stage1;+}++// ───────────────────────────────────────────────────────────────────────────+// Per-model handlers ——+// 每个 model 一个独立函数,内部自由实现 strip / 翻译 / 改值。+// 加新 case: 写一个 handler + 在下面 STRIP_HANDLERS 字典里登记。+// ───────────────────────────────────────────────────────────────────────────++/**+ * gpt-5.4 (XD.inc litellm → Azure OpenAI backend)+ *+ * 实测报错:+ * AzureException BadRequestError - Unknown parameter: 'output_config'+ *+ * 处理: 只删 output_config 这一个实测命中的字段。其他 Anthropic-only 字段+ * (thinking / cache_control / betas) 暂不动 —— 实测被打脸再加。+ */+const stripGpt54: ModelStripHandler = (body) => {+ const next: Record<string, unknown> = { ...body };+ delete next.output_config;+ return next;+};++/**+ * gpt-5.4-mini (XD.inc litellm → Azure OpenAI backend)+ *+ * 实测报错:+ * AzureException BadRequestError - Unknown parameter: 'output_config'+ *+ * 先与 gpt-5.4 保持同样的最小修复面,后续若 mini 需要单独兼容其它字段,+ * 直接在这个 handler 扩即可,不影响 gpt-5.4。+ */+const stripGpt54Mini: ModelStripHandler = (body) => {+ const next: Record<string, unknown> = { ...body };+ delete next.output_config;+ return next;+};++/**+ * 纯文本模型的 tool_result 图像降级(#794)。+ *+ * 实测(z-ai/glm-5.2,Anthropic 兼容直通):tool_result 里的 image block 原样发给+ * 上游,上游静默丢弃且不报错——模型把工具结果当成空,反复重读或直接臆造图片内容+ * (实测单任务空转 66 分钟并编造译文)。把 image block 替换为说明性占位文本:+ * 明确告知有图但当前模型收不到、禁止臆测、引导贴文本或换视觉模型。+ *+ * 只处理 tool_result 内嵌图像;user 消息图像走各桥接的 input_image 路径,不归这里。+ */+const TOOL_RESULT_IMAGE_OMITTED_TEXT =+ '[image omitted: this tool returned an image, but the current model is text-only, '+ + 'so the image could not be delivered. Do NOT guess or fabricate what the image '+ + 'contains. Tell the user the image could not be delivered to the current model, '+ + 'and ask them to paste the relevant content as text or switch to a vision-capable '+ + 'model.]';++export function replaceToolResultImagesWithNotice(+ body: Record<string, unknown>,+ noticeText = TOOL_RESULT_IMAGE_OMITTED_TEXT,+): Record<string, unknown> | null {+ const messages = body.messages;+ if (!Array.isArray(messages)) return null;++ let replaced = 0;+ const nextMessages = messages.map((msg) => {+ if (!isPlainObject(msg) || !Array.isArray(msg.content)) return msg;+ let msgChanged = false;+ const nextContent = msg.content.map((block) => {+ if (!isPlainObject(block) || block.type !== 'tool_result' || !Array.isArray(block.content)) {+ return block;+ }+ let blockChanged = false;+ const nextInner = block.content.map((inner) => {+ if (!isPlainObject(inner) || inner.type !== 'image') return inner;+ replaced += 1;+ blockChanged = true;+ return { type: 'text', text: noticeText };+ });+ if (!blockChanged) return block;+ msgChanged = true;+ return { ...block, content: nextInner };+ });+ return msgChanged ? { ...msg, content: nextContent } : msg;+ });++ if (replaced === 0) return null; // cache 安全契约:无改动 → null → 字节透传+ return { ...body, messages: nextMessages };+}++/**+ * Compact image-heavy conversation history for a request that already crossed+ * the proxy's hard body limit.+ *+ * This is deliberately a synchronous, local-only pass. The newest user+ * message is kept intact so the current prompt/image is never silently+ * removed. Older history images are dropped before the newest tool-result+ * image, with the current prompt always protected. The original media+ * remains in the media library; the+ * request-local replacement is only a small, explicit text notice.+ *+ * The function mutates the parsed request object in place (the proxy has+ * already paid the JSON.parse cost for an oversized request) and returns it+ * only when at least one image was replaced. `targetBytes` is used as a+ * cheap estimate while selecting candidates; the proxy performs the final+ * serialized-byte check after all regular transforms have run.+ */+const OVERSIZED_IMAGE_OMITTED_TEXT =+ '[Earlier image omitted to keep this request within the provider size limit. '+ + 'Do not infer its contents; ask the user to resend it if it is needed.]';++interface OversizedImageCandidate {+ container: unknown[];+ index: number;+ replacement: Record<string, string>;+ /** 0 = old tool-result, 1 = other history, 2 = newest tool-result. */+ priority: number;+ /** Older messages are removed before newer messages. */+ age: number;+}++function jsonByteLength(value: unknown): number {+ return Buffer.byteLength(JSON.stringify(value), 'utf8');+}++function collectOversizedAnthropicImages(+ messages: unknown[],+ candidates: OversizedImageCandidate[],+): void {+ let newestToolResultCandidateIndex = -1;+ let latestUserIndex = -1;+ for (let i = messages.length - 1; i >= 0; i -= 1) {+ const message = messages[i];+ if (!isPlainObject(message) || message.role !== 'user') continue;+ // Anthropic represents tool results as `role: user` messages too. A+ // trailing tool_result therefore must not hide the actual prompt message+ // whose images are still part of the current turn. Treat a user message+ // as a prompt when it has any non-tool_result block (plain text content is+ // a prompt as well); tool_result-only messages remain compactable history.+ const content = message.content;+ const isPrompt = !Array.isArray(content)+ || content.some((block) => !isPlainObject(block) || block.type !== 'tool_result');+ if (isPrompt) {+ latestUserIndex = i;+ break;+ }+ }++ const scan = (content: unknown[], messageIndex: number, inToolResult: boolean): void => {+ for (let index = 0; index < content.length; index += 1) {+ const block = content[index];+ if (!isPlainObject(block)) continue;+ if (block.type === 'image') {+ // Preserve every image in the newest user message, including images+ // nested in its tool_result content.+ if (messageIndex === latestUserIndex) continue;+ const candidate: OversizedImageCandidate = {+ container: content,+ index,+ replacement: { type: 'text', text: OVERSIZED_IMAGE_OMITTED_TEXT },+ priority: inToolResult ? 0 : 1,+ age: messageIndex,+ };+ candidates.push(candidate);+ if (+ inToolResult+ && (+ newestToolResultCandidateIndex < 0+ // `index` is local to each nested content array, so it cannot+ // order images from separate tool_result blocks in one message.+ // Candidates are collected in wire order; the later candidate is+ // the newer image when message ages tie.+ || candidate.age >= candidates[newestToolResultCandidateIndex].age+ )+ ) {+ newestToolResultCandidateIndex = candidates.length - 1;+ }+ continue;+ }+ if (block.type === 'tool_result' && Array.isArray(block.content)) {+ scan(block.content, messageIndex, true);+ }+ }+ };++ for (let messageIndex = 0; messageIndex < messages.length; messageIndex += 1) {+ const message = messages[messageIndex];+ if (!isPlainObject(message) || !Array.isArray(message.content)) continue;+ scan(message.content, messageIndex, false);+ }+ // Keep the most recent tool-result image behind older history images. It+ // may still be removed as a last resort when no other candidate can bring+ // the request under the hard limit, but it is never the first image dropped+ // merely because tool results use role=user in Anthropic's wire format.+ if (newestToolResultCandidateIndex >= 0) {+ candidates[newestToolResultCandidateIndex].priority = 2;+ }+}++function isResponsesUserMessage(item: Record<string, unknown>): boolean {+ // Responses clients in the wild omit `type` for ordinary user messages;+ // explicit non-message item types must remain ineligible for protection.+ return item.role === 'user' && (item.type === 'message' || item.type === undefined);+}++function collectOversizedOpenAiChatImages(+ messages: unknown[],+ candidates: OversizedImageCandidate[],+): void {+ let latestUserIndex = -1;+ for (let i = messages.length - 1; i >= 0; i -= 1) {+ const message = messages[i];+ if (isPlainObject(message) && message.role === 'user') {+ latestUserIndex = i;+ break;+ }+ }++ for (let messageIndex = 0; messageIndex < messages.length; messageIndex += 1) {+ const message = messages[messageIndex];+ if (!isPlainObject(message) || !Array.isArray(message.content)) continue;+ for (let index = 0; index < message.content.length; index += 1) {+ const block = message.content[index];+ if (!isPlainObject(block) || block.type !== 'image_url') continue;+ // OpenAI Chat uses a normal role=user message for the current prompt;+ // keep every image in that newest user message intact.+ if (messageIndex === latestUserIndex) continue;+ candidates.push({+ container: message.content,+ index,+ replacement: { type: 'text', text: OVERSIZED_IMAGE_OMITTED_TEXT },+ priority: 1,+ age: messageIndex,+ });+ }+ }+}++function collectOversizedResponsesImages(+ input: unknown[],+ candidates: OversizedImageCandidate[],+): void {+ let latestUserIndex = -1;+ for (let i = input.length - 1; i >= 0; i -= 1) {+ const item = input[i];+ if (isPlainObject(item) && isResponsesUserMessage(item)) {+ latestUserIndex = i;+ break;+ }+ }++ for (let itemIndex = 0; itemIndex < input.length; itemIndex += 1) {+ const item = input[itemIndex];+ if (!isPlainObject(item)) continue;+ const content = Array.isArray(item.content) ? item.content : null;+ if (!content) continue;+ for (let index = 0; index < content.length; index += 1) {+ const block = content[index];+ if (!isPlainObject(block) || block.type !== 'input_image') continue;+ if (itemIndex === latestUserIndex) continue;+ candidates.push({+ container: content,+ index,+ replacement: { type: 'input_text', text: OVERSIZED_IMAGE_OMITTED_TEXT },+ priority: 1,+ age: itemIndex,+ });+ }+ }+}++export function compactOversizedImageHistory(+ body: Record<string, unknown>,+ targetBytes: number,+): Record<string, unknown> | null {+ if (!Number.isFinite(targetBytes) || targetBytes <= 0) return null;++ const candidates: OversizedImageCandidate[] = [];+ if (Array.isArray(body.messages)) {+ collectOversizedAnthropicImages(body.messages, candidates);+ collectOversizedOpenAiChatImages(body.messages, candidates);+ }+ if (Array.isArray(body.input)) {+ collectOversizedResponsesImages(body.input, candidates);+ }+ // Avoid serializing a potentially huge text-only history: the common+ // oversized-text case has no safe image candidate to compact.+ if (candidates.length === 0) return null;++ let estimatedBytes: number;+ try {+ estimatedBytes = jsonByteLength(body);+ } catch {+ return null;+ }+ if (estimatedBytes <= targetBytes) return null;++ candidates.sort((a, b) => a.priority - b.priority || a.age - b.age);+ let replaced = 0;+ for (const candidate of candidates) {+ const previousBytes = jsonByteLength(candidate.container[candidate.index]);+ const replacementBytes = jsonByteLength(candidate.replacement);+ candidate.container[candidate.index] = candidate.replacement;+ estimatedBytes += replacementBytes - previousBytes;+ replaced += 1;+ if (estimatedBytes <= targetBytes) break;+ }++ return replaced > 0 ? body : null;+}++/** glm-5.2 (智谱,官方仅文本/代码模态) —— 直通与网关两条路由同一 model id。 */+const stripGlm52: ModelStripHandler = (body) => replaceToolResultImagesWithNotice(body);++// ───────────────────────────────────────────────────────────────────────────+// 分发表+// ───────────────────────────────────────────────────────────────────────────++/**+ * Per-model handler 字典 —— key = model id (与 body.model 严格相等比较)。+ * 不在表里的 model 一律字节透传,proxy 零干预。+ */+const STRIP_HANDLERS: Readonly<Record<string, ModelStripHandler>> = {+ 'gpt-5.4': stripGpt54,+ 'gpt-5.4-mini': stripGpt54Mini,+ // 「折扣GPT」低价路由 —— 与 gpt-5.4 打同一个 Azure 后端, 同样会因 output_config 报 400,+ // 镜像 gpt-5.4 的 strip 行为 (复用同一 handler)。codex/gpt-5.5 暂不加, 与 gpt-5.5 一致。+ 'codex/gpt-5.4': stripGpt54,+ // 纯文本模型 tool_result 图像会被上游静默吞掉 (#794) —— 带/不带命名空间前缀,+ // 以及 claude-code SDK 按目录 1M 窗口追加 [1m] 后缀 (toSdkModelString) 的形态+ // 都登记 (直通路由 body.model 可能保留 z-ai/ 前缀与 [1m] 后缀)。+ 'glm-5.2': stripGlm52,+ 'z-ai/glm-5.2': stripGlm52,+ 'glm-5.2[1m]': stripGlm52,+ 'z-ai/glm-5.2[1m]': stripGlm52,+};++/**+ * 默认 transform —— 按 model 分发到对应 handler;查不到就透传。+ */+export const stripNonAnthropicFields: RequestTransform = (body) => {+ if (!isPlainObject(body)) return null;++ const model = body.model;+ if (typeof model !== 'string' || model.length === 0) return null;++ const handler = STRIP_HANDLERS[model];+ if (!handler) return null;++ return handler(body);+};++/**+ * 主动剥离 transform —— 某 thread 因对应 400 恢复过一次后(controller 已 markActive),+ * 后续请求发送前就提前剥,省掉每轮重撞 400。`strip` 决定剥什么(encrypted 传+ * stripEncryptedContentFromBody,thinking 传 stripEmptyThinkingFromBody);controller+ * 必须与对应 recovery rule 是同一实例,且每个剥离条件用各自独立实例(详见 ThreadStripController)。+ */+export function createActiveStripTransform(opts: {+ controller: ThreadStripController;+ enabled: () => boolean;+ /** 对已标记 thread 主动剥离用的函数(与对应 recovery rule 的 strip 一致)。 */+ strip: (rawBody: Buffer) => Buffer | null;+ threadIdHeaders?: readonly string[];+}): RequestTransform {+ const threadIdHeaders = opts.threadIdHeaders ?? DEFAULT_THREAD_ID_HEADERS;+ return (body: unknown, ctx: RequestTransformCtx): unknown | null => {+ if (!opts.enabled()) return null;+ if (!isPlainObject(body)) return null;++ const threadId = selectedHeaderValue(ctx.headers, threadIdHeaders);+ const model = body.model;+ if (!threadId || typeof model !== 'string' || model.length === 0) return null;+ opts.controller.reconcile(threadId, model);+ if (!opts.controller.shouldStrip(threadId)) return null;++ const stripped = opts.strip(Buffer.from(JSON.stringify(body), 'utf8'));+ if (!stripped) return null;++ try {+ return JSON.parse(stripped.toString('utf8'));+ } catch {+ return null;+ }+ };+}++// ───────────────────────────────────────────────────────────────────────────+// Recovery rules —— 上游 400 透明重试规则(server.ts 的 forward() 按序应用第一条命中的)。+// 每条规则把"错误体匹配正则 + 对应 strip 函数"绑在一起,正则与 strip 就近放,单一真相源。+// ───────────────────────────────────────────────────────────────────────────++// 上游 400/422 错误体命中以下任一 → 判定为"协议加密推理内容解不开"。+// litellm/Azure: code "invalid_encrypted_content" + "Encrypted content could not be decrypted or parsed."+// xAI Responses: code "invalid-argument" + "Could not decrypt the provided encrypted_content..."+const INVALID_ENCRYPTED_CONTENT_RE =+ /invalid_encrypted_content|invalid-argument[\s\S]{0,160}encrypted_content|could not decrypt(?: the provided)? encrypted_content|encrypted content could not be (?:decrypted|verified|parsed)/i;++// Anthropic 400: "messages.N.content.M.thinking: each thinking block must contain thinking"+// 只匹配不变的核心短语,不锚定会变的 messages.N.content.M 下标前缀。+const EMPTY_THINKING_RE = /each thinking block must contain thinking/i;++// Anthropic 400: "messages.N.content.M: text content blocks must be non-empty"+// (纯空白变体: "text content blocks must contain non-whitespace text")。+// 同样只匹配核心短语,不锚定下标前缀。+const EMPTY_TEXT_RE = /text content blocks must (?:be non-empty|contain non-whitespace text)/i;++// moonshot 400 (经 LiteLLM /anthropic/v1/messages passthrough,2026-07-28 实测):+// "Invalid request: the message at position 693 with role 'assistant' must not be empty"+// 只匹配不变的 role + 校验短语,不锚定会变的 position 数字。+const EMPTY_ASSISTANT_MESSAGE_RE = /with role 'assistant' must not be empty/i;++// Azure/LiteLLM 400: "Image generation items without `id` are not supported for this request."+const IMAGE_GENERATION_WITHOUT_ID_RE =+ /image generation items without [`']?id[`']? are not supported/i;++const TOOL_USE_PROVIDER_SPECIFIC_FIELDS_RE =+ /\.tool_use\.provider_specific_fields[^"\r\n|]*extra inputs are not permitted|extra inputs are not permitted[^"\r\n|]*\.tool_use\.provider_specific_fields/i;++// Anthropic 400: "messages: `tool_use` ids must be unique"(kimi kosong+// STRUCTURAL_REQUEST 同族正则)。moonshot 实测容忍重复 id 不报错(静默错乱),+// 但 LiteLLM 版本差异 / 真 Anthropic 上游会报;命中时用与主动 transform+// 相同的唯一化 strip 重发。+const DUPLICATE_TOOL_USE_ID_RE = /tool_use[\s\S]*ids must be unique/i;++// tool 配对断裂 400 家族(kimi kosong TOOL_EXCHANGE_ADJACENCY 同族,按本链路+// 可见措辞收敛):+// - Moonshot(chatcmpl 校验透出): "tool_call_id is not found"(孤儿 result,+// 原文双空格;锚定 tool_call_id,404 类 "not found" 不会误命中)+// - Anthropic 孤儿 result: "unexpected `tool_use_id` found in `tool_result`+// blocks"(两个锚点都限定,避免命中非 tool_result 上下文的 unexpected)+// - Anthropic 未配对 call: "`tool_use` ids were found without `tool_result`+// blocks immediately after"+// - OpenAI 系(LiteLLM 版本差异可能透出): 孤儿 tool 消息 "unexpected+// `tool_result`" / "messages with role 'tool' must be a response to a+// preceding message with 'tool_calls'";未配对 call "the following+// tool_call_ids did not have response messages: ..."+// roles-must-alternate / first-message-must-be-user 不在此列: 本修复不处理+// 合并与 leading 裁剪,匹配了也 strip 不出东西(实测命中再扩)。+const TOOL_EXCHANGE_ADJACENCY_RE =+ /tool_call_id[\s\S]*not found|unexpected\s+`?tool_use_id`?[\s\S]*tool_result|unexpected\s+`?tool_result|`?tool_use`?\s+ids were found without|tool_call_ids? did not have response messages|role\s+['"`]?tool['"`]?\s+must be a response to a preceding message/i;++/**+ * invalid_encrypted_content 恢复规则: 剥掉请求体里所有 encrypted_content 重发。+ * 受 enabled() gate(由 host 接 silentEncryptedRetry 设置,默认开,用户可关闭)。+ */+export function createEncryptedContentRecoveryRule(opts: {+ enabled: () => boolean;+ onRetry?: (threadId: string, model: string) => void;+ threadIdHeaders?: readonly string[];+}): RecoveryRule {+ return {+ id: 'encrypted_content',+ enabled: opts.enabled,+ matches: (text) => INVALID_ENCRYPTED_CONTENT_RE.test(text),+ strip: stripEncryptedContentFromBody,+ unrecoverableCode: (body) => {+ // Only compaction remains opaque. A standalone reasoning rejection must retain+ // the ordinary retry/error behavior and must never request a context rebuild.+ if (stripEncryptedContentFromBody(body)) return null;+ try {+ const input = JSON.parse(body.toString('utf8')).input;+ return Array.isArray(input) && input.some((item) => item?.type === 'compaction' &&+ typeof item.encrypted_content === 'string' && item.encrypted_content.length > 0)+ ? 'CINDY_ENCRYPTED_COMPACTION_INCOMPATIBLE' : null;+ } catch {+ return null;+ }+ },+ onRetry: opts.onRetry,+ threadIdHeaders: opts.threadIdHeaders,+ };+}++/**+ * 缺 id 的 image generation item 恢复规则: 剥掉坏历史 item 后重发。+ * 默认 always-on;只在明确命中上游错误时触发,正常请求字节透传。+ */+export function createImageGenerationIdRecoveryRule(opts: {+ enabled?: () => boolean;+ onRetry?: (threadId: string, model: string) => void;+ threadIdHeaders?: readonly string[];+} = {}): RecoveryRule {+ return {+ id: 'image_generation_id',+ enabled: opts.enabled ?? (() => true),+ matches: (text) => IMAGE_GENERATION_WITHOUT_ID_RE.test(text),+ strip: stripImageGenerationItemsWithoutIdFromBody,+ onRetry: opts.onRetry,+ threadIdHeaders: opts.threadIdHeaders,+ };+}++/**+ * `tool_use.provider_specific_fields` 400 恢复规则:清理历史后透明重试一次。+ * 主动 transform 通常会先移除该字段;该规则覆盖 transform 未接入、旧会话+ * 或其它兼容链路绕过主动清理的情况。+ */+export function createToolUseProviderSpecificFieldsRecoveryRule(opts: {+ enabled?: () => boolean;+ onRetry?: (threadId: string, model: string) => void;+ threadIdHeaders?: readonly string[];+} = {}): RecoveryRule {+ return {+ id: 'tool_use_provider_specific_fields',+ enabled: opts.enabled ?? (() => true),+ matches: (text) => TOOL_USE_PROVIDER_SPECIFIC_FIELDS_RE.test(text),+ strip: stripToolUseProviderSpecificFieldsFromBody,+ onRetry: opts.onRetry,+ threadIdHeaders: opts.threadIdHeaders,+ };+}++/**+ * 空 thinking 块恢复规则: 跨厂商切回 Anthropic 模型时,剥掉历史里的空内容 thinking 块重发。+ * 默认 always-on(删空块零代价,无需用户权衡)。+ */+export function createEmptyThinkingRecoveryRule(opts: {+ enabled?: () => boolean;+ onRetry?: (threadId: string, model: string) => void;+ threadIdHeaders?: readonly string[];+} = {}): RecoveryRule {+ return {+ id: 'empty_thinking',+ enabled: opts.enabled ?? (() => true),+ matches: (text) => EMPTY_THINKING_RE.test(text),+ strip: stripEmptyThinkingFromBody,+ onRetry: opts.onRetry,+ threadIdHeaders: opts.threadIdHeaders,+ };+}++/**+ * 空 text 块恢复规则: 历史被 bridge 修复前的空 `{type:"text",text:""}` 块污染的会话,+ * 切到真 Anthropic 模型时 400 → 剥掉空块重发。默认 always-on(删空块零代价)。+ */+export function createEmptyTextRecoveryRule(opts: {+ enabled?: () => boolean;+ onRetry?: (threadId: string, model: string) => void;+ threadIdHeaders?: readonly string[];+} = {}): RecoveryRule {+ return {+ id: 'empty_text',+ enabled: opts.enabled ?? (() => true),+ matches: (text) => EMPTY_TEXT_RE.test(text),+ strip: stripEmptyTextFromBody,+ onRetry: opts.onRetry,+ threadIdHeaders: opts.threadIdHeaders,+ };+}++/**+ * 空 assistant 消息恢复规则: moonshot/kimi 系(Anthropic 兼容流空 thinking 占位被+ * 客户端中断持久化后)回放 400 → 丢掉空 assistant 消息重发。+ * 默认 always-on(空消息不含对话信息,丢弃零代价)。背景详见+ * stripEmptyAssistantMessagesFromBody 头注。+ */+export function createEmptyAssistantMessageRecoveryRule(opts: {+ enabled?: () => boolean;+ onRetry?: (threadId: string, model: string) => void;+ threadIdHeaders?: readonly string[];+} = {}): RecoveryRule {+ return {+ id: 'empty_assistant_message',+ enabled: opts.enabled ?? (() => true),+ matches: (text) => EMPTY_ASSISTANT_MESSAGE_RE.test(text),+ strip: stripEmptyAssistantMessagesFromBody,+ onRetry: opts.onRetry,+ threadIdHeaders: opts.threadIdHeaders,+ };+}++/**+ * 重复 tool_use id 恢复规则: 上游 400 ``tool_use` ids must be unique` →+ * 组合结构修复(先 adjacency 后唯一化,顺序约束见+ * repairToolExchangeStructureFromBody)后重发。默认 always-on(修复是协议+ * 级的,无异常时 strip 返回 null 自然跳过)。kimi code 的 strict resend 同族处理。+ */+export function createDuplicateToolUseIdRecoveryRule(opts: {+ enabled?: () => boolean;+ onRetry?: (threadId: string, model: string) => void;+ threadIdHeaders?: readonly string[];+} = {}): RecoveryRule {+ return {+ id: 'duplicate_tool_use_id',+ enabled: opts.enabled ?? (() => true),+ matches: (text) => DUPLICATE_TOOL_USE_ID_RE.test(text),+ strip: repairToolExchangeStructureFromBody,+ onRetry: opts.onRetry,+ threadIdHeaders: opts.threadIdHeaders,+ };+}++/**+ * tool 配对断裂恢复规则: 孤儿 result / 未配对 call 的 400(moonshot+ * `tool_call_id is not found` / Anthropic `unexpected tool_use_id` /+ * `tool_use ids were found without tool_result` / OpenAI 系 wording)→+ * 组合结构修复后重发。默认 always-on(与 kimi code projector 的 adjacency+ * 修复同构)。+ */+export function createToolExchangeAdjacencyRecoveryRule(opts: {+ enabled?: () => boolean;+ onRetry?: (threadId: string, model: string) => void;+ threadIdHeaders?: readonly string[];+} = {}): RecoveryRule {+ return {+ id: 'tool_exchange_adjacency',+ enabled: opts.enabled ?? (() => true),+ matches: (text) => TOOL_EXCHANGE_ADJACENCY_RE.test(text),+ strip: repairToolExchangeStructureFromBody,+ onRetry: opts.onRetry,+ threadIdHeaders: opts.threadIdHeaders,+ };+}diff --git a/packages/model-compat/src/cindy/proxy/types.ts b/packages/model-compat/src/cindy/proxy/types.tsnew file mode 100644index 0000000000..7800ef68e3--- /dev/null+++ b/packages/model-compat/src/cindy/proxy/types.ts@@ -0,0 +1,92 @@+import type { Buffer } from "node:buffer";++/**+ * 请求 transform 上下文。+ * - method/url/headers 是只读快照,transform 不应该尝试通过这些改写 outbound 请求+ * (改 method/url 没意义,改 headers 通过专用 transform 接口未来再加)+ */+export interface RequestTransformCtx {+ /** Monotonic identifier shared with the eventual response observer for this request. */+ readonly reqId: number;+ readonly method: string;+ readonly url: string;+ readonly headers: Readonly<Record<string, string>>;+ /**+ * 本请求**最终**发往的上游 baseURL(routingTransform 的 per-request override 已生效,+ * 与 ResponseObserverCtx.upstreamBase 同构)。仅在请求 transform 链的 ctx 里出现;+ * routingTransform / localHandler 的 ctx 中为 undefined(路由尚未/无需解析)。+ * 供「按目标上游做兼容改写」的 transform 使用(如跨供应商时转换上游读不懂的历史项),+ * 避免 host 侧为判断路由去向而复刻整套路由逻辑。+ */+ readonly upstreamBase?: string;+}++++/**+ * 请求 body transform。+ *+ * 允许返回 Promise(视觉桥等需要出网调用的 transform 用)。引擎用 isPromiseLike+ * 统一 await:同步 transform 返回值原样通过,语义与 async 化前逐字节一致。+ *+ * @returns+ * - 新的 body 对象 → 代理用它替换原 body 转发上游+ * - null → 不改写,这一步跳过(还会继续跑后续 transform;全部跳过则字节透传)+ */+export interface RequestTransform {+ (+ body: unknown,+ ctx: RequestTransformCtx,+ ): unknown | null | Promise<unknown | null>;+ /**+ * Error handling for this transform. The default keeps the historical fail-open behavior;+ * transforms that must not expose their unadapted input upstream can reject the request.+ */+ errorMode?: 'reject-request';+ /**+ * Optional cleanup for request-scoped state created while evaluating this transform.+ * Called once after a request that entered the transform chain finishes or closes.+ */+ onRequestSettled?: (requestId: number) => void;+}++++/**+ * 一条 400 透明重试规则。+ *+ * forward() 命中上游 400 时,按顺序找第一条 `enabled() && matches(decodedErrBodyText)+ * && strip(body) !== null` 的规则,用其 strip 结果重发一次(canRetry=false,防循环)。+ * 多条规则并列(例: encrypted_content / empty_thinking),互不耦合;regex 互斥,+ * 命中顺序仅在两条都可能匹配同一错误体时才有意义(实际不会)。+ */+export interface RecoveryRule {+ /** 诊断用稳定 id,进日志(例 'encrypted_content' / 'empty_thinking')。 */+ id: string;+ /** gate: false 时该规则完全跳过(thinking 永远 true;encrypted 跟 silentEncryptedRetry 设置)。 */+ enabled: () => boolean;+ /** 对解压后的 400 错误体文本判定是否命中本规则。+ * 命名避开 `match`:与 String.prototype.match 同名会让 CodeQL 把动态文本误判为+ * 正则模式(js/regex-injection 误报)。 */+ matches: (decodedErrorBodyText: string) => boolean;+ /** 改写请求 body;返回 null = 没有可改的东西(本规则不适用,继续找下一条)。 */+ strip: (body: Buffer) => Buffer | null;+ /** Classify a matched terminal rejection from the actual sent body, after safe retries. */+ unrecoverableCode?: (body: Buffer) => string | null;+ /** 命中并成功 strip 后触发(用于 Layer-2 markActive)。 */+ 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/model-compat/src/cindy/proxy/vllm-responses-compatibility.ts b/packages/model-compat/src/cindy/proxy/vllm-responses-compatibility.tsnew file mode 100644index 0000000000..c42b50a9e3--- /dev/null+++ b/packages/model-compat/src/cindy/proxy/vllm-responses-compatibility.ts@@ -0,0 +1,97 @@+import type { RecoveryRule } from './types.js';++interface ResponsesCompatibilityBody {+ instructions?: unknown;+ input?: unknown;+ reasoning?: { effort?: unknown };+ [key: string]: unknown;+}++interface ResponsesCompatibilityMessage {+ type?: unknown;+ role?: unknown;+ content?: unknown;+ [key: string]: unknown;+}++const REASONING_EFFORT_ERROR_RE =+ /Unexpected reasoning effort high\. Supported types are xhigh \(default\), medium, and low\./i;+const UNEXPECTED_MESSAGE_ROLE_RE = /Unexpected message role\./i;++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function isMessage(value: unknown): value is ResponsesCompatibilityMessage {+ return isRecord(value) && typeof value.role === 'string';+}++function normalizeRoles(input: readonly unknown[]): { input: unknown[]; changed: boolean } {+ let changed = false;+ const normalized = input.map((item) => {+ if (!isMessage(item) || item.role !== 'developer') return item;+ changed = true;+ return { ...item, role: 'system' };+ });+ return { input: normalized, changed };+}++/**+ * Convert only the Responses fields that Qwen's vLLM chat template rejected.+ * This runs after an exact 400, so native Responses endpoints keep byte-for-byte+ * requests; normal endpoints never see the rewritten shape.+ */+export function normalizeVllmResponsesRequest(body: unknown): object | null {+ if (!isRecord(body)) return null;+ const source = body as ResponsesCompatibilityBody;+ let changed = false;+ const next: ResponsesCompatibilityBody = { ...source };++ if (source.reasoning?.effort === 'high') {+ next.reasoning = { ...source.reasoning, effort: 'xhigh' };+ changed = true;+ }++ let input: unknown = source.input;+ if (Array.isArray(source.input)) {+ const roles = normalizeRoles(source.input);+ input = roles.input;+ changed ||= roles.changed;+ }++ if (source.instructions !== undefined && source.instructions !== null && source.instructions !== '') {+ const systemMessage = { type: 'message', role: 'system', content: source.instructions };+ // Responses 允许 input 为纯字符串(等价单条 user 消息)。重试时必须把它转成+ // 显式 user 消息追加在 system 之后,绝不能被 instructions 的 system 消息覆盖。+ if (typeof input === 'string') {+ input = [systemMessage, { type: 'message', role: 'user', content: input }];+ } else if (Array.isArray(input)) {+ input = [systemMessage, ...input];+ } else {+ input = [systemMessage];+ }+ delete next.instructions;+ changed = true;+ }+ next.input = input;++ return changed ? next : null;+}++export function createVllmResponsesCompatibilityRule(): RecoveryRule {+ return {+ id: 'vllm_responses_compat',+ enabled: () => true,+ matches: (errorText) =>+ REASONING_EFFORT_ERROR_RE.test(errorText) || UNEXPECTED_MESSAGE_ROLE_RE.test(errorText),+ strip: (body) => {+ try {+ const normalized = normalizeVllmResponsesRequest(JSON.parse(body.toString('utf8')));+ return normalized ? Buffer.from(JSON.stringify(normalized), 'utf8') : null;+ } catch {+ return null;+ }+ },+ applyOnUnmatchedRetry: false,+ };+}diff --git a/packages/model-compat/src/cindy/proxy/xai-model-input.ts b/packages/model-compat/src/cindy/proxy/xai-model-input.tsnew file mode 100644index 0000000000..587dd8283d--- /dev/null+++ b/packages/model-compat/src/cindy/proxy/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,+ };+}diff --git a/packages/model-compat/src/cindy/responses-null-array-repair.ts b/packages/model-compat/src/cindy/responses-null-array-repair.tsnew file mode 100644index 0000000000..47687f4b92--- /dev/null+++ b/packages/model-compat/src/cindy/responses-null-array-repair.ts@@ -0,0 +1,245 @@+import { Transform, type TransformCallback } from "node:stream";++/**+ * Repairs Responses output items whose required array fields were serialized as `null`.+ *+ * Some third-party models proxied through a Responses passthrough emit+ * `response.output_item.added` items such as `{ type: 'reasoning', summary: null }` or+ * `{ type: 'message', content: null }`. Codex's `ResponseItem` parser tolerates missing ids and+ * unknown fields but requires these arrays, so the item is dropped and every following+ * `output_text.delta` is discarded as "without active item" (#4251). The wire contract says+ * these fields are arrays, so the only semantics-preserving repair is `null -> []`.+ *+ * Nothing else is touched: item types, ids, call ids and unknown fields pass through byte for+ * byte, and frames that need no repair are re-emitted exactly as received.+ */++interface JsonObject {+ [key: string]: unknown;+}++function isObject(value: unknown): value is JsonObject {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++/** Array fields Codex requires per item type. `reasoning.content` is optional and stays as is. */+const REQUIRED_ARRAY_FIELDS: Readonly<Record<string, readonly string[]>> = {+ reasoning: ["summary"],+ message: ["content"],+};++/** Returns the repaired item, or null when the item needs no repair. */+export function repairResponsesItemNullArrays(+ item: unknown,+): JsonObject | null {+ if (!isObject(item) || typeof item.type !== "string") return null;+ const fields = REQUIRED_ARRAY_FIELDS[item.type];+ if (!fields) return null;+ let next: JsonObject | null = null;+ for (const field of fields) {+ if (item[field] !== null) continue;+ next ??= { ...item };+ next[field] = [];+ }+ return next;+}++function repairOutputList(output: unknown): unknown[] | null {+ if (!Array.isArray(output)) return null;+ let changed = false;+ const next = output.map((item) => {+ const repaired = repairResponsesItemNullArrays(item);+ if (!repaired) return item;+ changed = true;+ return repaired;+ });+ return changed ? next : null;+}++/**+ * Returns the repaired Responses SSE event, or null when the event needs no repair.+ *+ * Covers `response.output_item.added` / `response.output_item.done` (`event.item`) and every+ * event carrying a full `response.output` array (`response.completed`, `response.incomplete`,+ * non-streaming bodies wrapped by the caller).+ */+export function repairResponsesEventNullArrays(+ event: unknown,+): JsonObject | null {+ if (!isObject(event) || typeof event.type !== "string") return null;+ if (+ event.type === "response.output_item.added" ||+ event.type === "response.output_item.done"+ ) {+ const item = repairResponsesItemNullArrays(event.item);+ return item ? { ...event, item } : null;+ }+ if (isObject(event.response)) {+ const output = repairOutputList(event.response.output);+ return output+ ? { ...event, response: { ...event.response, output } }+ : null;+ }+ return null;+}++/**+ * A single SSE frame is never larger than a few KiB in practice; a frame that grows past this+ * bound without a delimiter is forwarded verbatim instead of being buffered forever. Failing+ * open here is deliberate: this transform only repairs, it must never turn a working stream+ * into a proxy error.+ */+const MAX_PENDING_FRAME_BYTES = 16 * 1024 * 1024;++/** One SSE event boundary: a line break (LF or CRLF) followed by an empty line. */+const FRAME_BOUNDARY = /\r?\n\r?\n/;++/** SSE frame rewriter; frames that need no repair are re-emitted byte for byte. */+export class ResponsesNullArrayRepairTransform extends Transform {+ private readonly decoder = new TextDecoder();+ private pending = "";++ private rewriteFrame(frame: string, delimiter: string): string {+ const lines = frame.split(/\r?\n/);+ const data = lines+ .filter((line) => line.startsWith("data:"))+ .map((line) => line.slice(5).trimStart())+ .join("\n");+ if (!data || data === "[DONE]") return frame + delimiter;+ let event: unknown;+ try {+ event = JSON.parse(data);+ } catch {+ return frame + delimiter;+ }+ const repaired = repairResponsesEventNullArrays(event);+ if (!repaired) return frame + delimiter;+ const eventLine = lines.find((line) => line.startsWith("event:"));+ return `${eventLine ? `${eventLine}\n` : ""}data: ${JSON.stringify(repaired)}${delimiter}`;+ }++ private drainFrames(): void {+ // SSE ends a line with LF or CRLF and an event with a blank line, so the four+ // boundaries `\n\n`, `\r\n\r\n`, `\n\r\n` and `\r\n\n` are all legal and may be+ // mixed by one upstream (same convention as the proxy's own frame reader).+ // The matched delimiter is re-emitted verbatim.+ for (;;) {+ const match = FRAME_BOUNDARY.exec(this.pending);+ if (!match) return;+ const delimiter = match[0];+ this.push(+ this.rewriteFrame(this.pending.slice(0, match.index), delimiter),+ );+ this.pending = this.pending.slice(match.index + delimiter.length);+ }+ }++ override _transform(+ chunk: Buffer,+ _encoding: string,+ callback: TransformCallback,+ ): void {+ this.pending += this.decoder.decode(chunk, { stream: true });+ this.drainFrames();+ if (Buffer.byteLength(this.pending, "utf8") > MAX_PENDING_FRAME_BYTES) {+ this.push(this.pending);+ this.pending = "";+ }+ callback();+ }++ override _flush(callback: TransformCallback): void {+ this.pending += this.decoder.decode();+ this.drainFrames();+ if (this.pending) this.push(this.rewriteFrame(this.pending, ""));+ this.pending = "";+ callback();+ }+}++/**+ * Builds the repair transform for one upstream response, or null when the body is not a plain+ * (uncompressed) SSE stream. Non-SSE and compressed bodies are left untouched rather than+ * rejected: the repair is best effort and must not change how such responses are delivered.+ */+export function createResponsesNullArrayRepairTransform(response: {+ contentType: string;+ contentEncoding: string;+}): Transform | null {+ const encoding = response.contentEncoding.trim().toLowerCase();+ if (encoding && encoding !== "identity") return null;+ if (+ !response.contentType.trim().toLowerCase().startsWith("text/event-stream")+ )+ return null;+ return new ResponsesNullArrayRepairTransform();+}++/**+ * Chains response transforms into one so a proxy that accepts a single transform can run+ * several. Bytes flow `head -> ... -> tail`; the chained transform ends only after the tail+ * ends, and an error in any stage fails the whole chain. Null stages are skipped.+ */+export function chainResponseTransforms(+ ...stages: Array<Transform | null | undefined>+): Transform | null {+ const present = stages.filter(+ (stage): stage is Transform => stage instanceof Transform,+ );+ if (present.length === 0) return null;+ if (present.length === 1) return present[0]!;+ return new ChainedTransform(present);+}++class ChainedTransform extends Transform {+ private readonly head: Transform;+ private readonly tail: Transform;+ private readonly stages: readonly Transform[];++ constructor(stages: readonly Transform[]) {+ super();+ this.stages = stages;+ this.head = stages[0]!;+ this.tail = stages[stages.length - 1]!;+ for (let index = 0; index < stages.length; index += 1) {+ const stage = stages[index]!;+ stage.on("error", (error: Error) => this.destroy(error));+ const next = stages[index + 1];+ if (next) stage.pipe(next);+ }+ // Readable-side backpressure: when the consumer stops reading, stop pulling+ // from the tail (pipe then throttles every earlier stage) until `_read` runs.+ this.tail.on("data", (chunk: Buffer) => {+ if (!this.push(chunk)) this.tail.pause();+ });+ }++ override _read(size: number): void {+ if (this.tail.isPaused()) this.tail.resume();+ super._read(size);+ }++ override _transform(+ chunk: Buffer,+ _encoding: string,+ callback: TransformCallback,+ ): void {+ if (this.head.write(chunk)) callback();+ else this.head.once("drain", () => callback());+ }++ override _flush(callback: TransformCallback): void {+ this.tail.once("end", () => callback());+ this.head.end();+ }++ override _destroy(+ error: Error | null,+ callback: (error: Error | null) => void,+ ): void {+ for (const stage of this.stages) {+ if (!stage.destroyed) stage.destroy();+ }+ callback(error);+ }+}diff --git a/packages/model-compat/src/cindy/strict-schema.ts b/packages/model-compat/src/cindy/strict-schema.tsnew file mode 100644index 0000000000..afaa19216d--- /dev/null+++ b/packages/model-compat/src/cindy/strict-schema.ts@@ -0,0 +1,117 @@+/**+ * OpenAI 式 strict function-tool 的 schema 兼容性判定(fail-closed)。+ *+ * strict 约束解码只接受一个受限 JSON Schema 子集:对象节点必须+ * `additionalProperties:false` 且**所有** property 进 `required`,关键字限于少数白名单。+ * Claude Code 内置工具(如 Edit 的可选 replace_all)和复杂 MCP schema+ * (propertyNames / maxItems / oneOf …)普遍不满足。+ *+ * 判定取保守面:任何未知关键字、未覆盖形态一律判不兼容,由调用方回落 strict:false。+ * 回落只是少一层约束(与现状一致),误开 strict 才有上游 400 / 语义漂移风险;+ * 因此**不做 optional→nullable 的 schema 改写**,不改变工具语义。+ *+ * 结果是 schema 内容的纯函数:同一会话内工具集稳定 ⇒ 每轮各工具的 strict 位稳定,+ * 不破坏请求前缀一致性(docs/dev-rules/maker-core-and-agent-behavior.md §3.1)。+ */++/** strict 子集允许的 schema 关键字。白名单外(pattern/format/oneOf/propertyNames…)一律不兼容。 */+const ALLOWED_KEYS = new Set([+ 'type',+ 'description',+ 'enum',+ 'const',+ 'properties',+ 'required',+ 'additionalProperties',+ 'items',+ 'anyOf',+]);++const ALLOWED_TYPES = new Set(['object', 'array', 'string', 'number', 'integer', 'boolean', 'null']);++/** 递归深度上限:防御性边界,真实工具 schema 远达不到;超深直接判不兼容。 */+const MAX_DEPTH = 16;++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++/**+ * 该 function-tool 参数 schema 是否可以安全地声明 `strict: true`。+ * 根节点必须是 `type:'object'`(Responses function parameters 的硬要求)。+ */+export function isStrictCompatibleSchema(schema: unknown): boolean {+ if (!isPlainObject(schema)) return false;+ if (schema.type !== 'object') return false;+ return nodeOk(schema, MAX_DEPTH);+}++function nodeOk(node: Record<string, unknown>, depth: number): boolean {+ if (depth <= 0) return false;+ for (const key of Object.keys(node)) {+ if (!ALLOWED_KEYS.has(key)) return false;+ }++ // anyOf 节点:只能与 description 共存,分支各自校验(strict 子集不支持 anyOf 与+ // type/properties 等结构字段同级混写)。+ if (node.anyOf !== undefined) {+ for (const key of Object.keys(node)) {+ if (key !== 'anyOf' && key !== 'description') return false;+ }+ if (!Array.isArray(node.anyOf) || node.anyOf.length === 0) return false;+ return node.anyOf.every((branch) => isPlainObject(branch) && nodeOk(branch, depth - 1));+ }++ const types = typeList(node.type);+ if (!types) return false;++ if (types.includes('object')) {+ if (node.additionalProperties !== false) return false;+ if (!isPlainObject(node.properties)) return false;+ const propertyKeys = Object.keys(node.properties).sort();+ // required 必须**恰好**覆盖全部 property(缺一个 = 存在 optional 字段,不兼容;+ // 多一个 = required 指向不存在的字段,同样不兼容)。+ if (!Array.isArray(node.required)) return false;+ const required = node.required.filter((item): item is string => typeof item === 'string');+ if (required.length !== node.required.length) return false;+ const sortedRequired = [...required].sort();+ if (+ sortedRequired.length !== propertyKeys.length+ || sortedRequired.some((key, index) => key !== propertyKeys[index])+ ) {+ return false;+ }+ for (const value of Object.values(node.properties)) {+ if (!isPlainObject(value) || !nodeOk(value, depth - 1)) return false;+ }+ } else if (+ node.properties !== undefined+ || node.required !== undefined+ || node.additionalProperties !== undefined+ ) {+ return false;+ }++ if (types.includes('array')) {+ if (!isPlainObject(node.items) || !nodeOk(node.items, depth - 1)) return false;+ } else if (node.items !== undefined) {+ return false;+ }++ // enum/const 的成员是任意 JSON 值,strict 子集接受,成员内容无需校验;+ // 但空 enum 连普通 grammar 编译都会被上游 400(docs.x.ai structured-outputs),判不合规。+ if (node.enum !== undefined && (!Array.isArray(node.enum) || node.enum.length === 0)) return false;+ return true;+}++/** type 归一化:字符串或字符串数组(nullable 联合如 ['string','null']),全部落在允许集合内。 */+function typeList(type: unknown): string[] | null {+ const raw = typeof type === 'string' ? [type] : Array.isArray(type) ? type : null;+ if (!raw || raw.length === 0) return null;+ const out: string[] = [];+ for (const entry of raw) {+ if (typeof entry !== 'string' || !ALLOWED_TYPES.has(entry)) return null;+ out.push(entry);+ }+ return out;+}diff --git a/packages/model-compat/src/cindy/tool-context.ts b/packages/model-compat/src/cindy/tool-context.tsnew file mode 100644index 0000000000..4914ce9482--- /dev/null+++ b/packages/model-compat/src/cindy/tool-context.ts@@ -0,0 +1,282 @@+import { Buffer } from 'node:buffer';+import { createHash } from 'node:crypto';++import type {+ ChatCompletionsRequest,+ ResponsesCustomTool,+ ResponsesFunctionTool,+ ResponsesNamespaceTool,+ ResponsesRequest,+} from './types.js';++type ResponseTool = NonNullable<ResponsesRequest['tools']>[number];+const CHAT_TOOL_NAME_MAX_LENGTH = 64;+const TOOL_SEARCH_CHAT_NAME = 'tool_search';+const CUSTOM_TOOL_INPUT_DESCRIPTION =+ 'Raw string input for the original custom tool. Preserve formatting exactly.';+const CUSTOM_EXEC_DESCRIPTION_MAX_BYTES = 32 * 1024;+const COMPACT_CUSTOM_EXEC_DESCRIPTION = [+ 'Execute JavaScript in the Code Mode runtime. Pass the complete JavaScript source in `input`.',+ 'Call tools on the global `tools` object with `await tools.<name>(...)`; namespace tools use',+ 'the flattened `await tools.<namespace>__<name>(...)` form.',+ 'Inspect `ALL_TOOLS` for available shell, patch, plugin, connector, and MCP tools.',+ 'Use `yield_control()` to yield while execution continues, and `exit()` to stop early.',+ 'Return user-visible output with `text(...)`, `image(...)`, `audio(...)`, or',+ '`generatedImage(...)`. Share serializable state across exec calls with `store(key, value)`',+ 'and `load(key)`, and report progress with `notify(value)`.',+].join(' ');++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function shortHash(value: string): string {+ return createHash('sha256').update(value).digest('hex').slice(0, 12);+}++function clampChatToolName(name: string): string {+ if (name.length <= CHAT_TOOL_NAME_MAX_LENGTH) return name;+ const suffix = `__${shortHash(name)}`;+ return `${name.slice(0, CHAT_TOOL_NAME_MAX_LENGTH - suffix.length)}${suffix}`;+}++function normalizeFunctionParameters(parameters: unknown): Record<string, unknown> {+ if (!isPlainObject(parameters)) return { type: 'object', properties: {} };+ return parameters.type === 'object'+ ? { ...parameters }+ : { ...parameters, type: 'object' };+}++function stableToolDescription(tool: ResponsesCustomTool): string {+ const metadata: Record<string, unknown> = { ...tool };+ delete metadata.description;+ try {+ return `Original Responses custom tool metadata:\n${JSON.stringify(metadata)}`;+ } catch {+ return 'Original Responses custom tool metadata is unavailable.';+ }+}++function chatCustomToolDescription(tool: ResponsesCustomTool, namespace?: string): string {+ const metadata = stableToolDescription(tool);+ if (!tool.description) return metadata;+ const description = namespace === undefined+ && tool.name === 'exec'+ && Buffer.byteLength(tool.description, 'utf8') > CUSTOM_EXEC_DESCRIPTION_MAX_BYTES+ ? COMPACT_CUSTOM_EXEC_DESCRIPTION+ : tool.description;+ return `${description}\n\n${metadata}`;+}++export type ChatBridgeToolKind = 'function' | 'namespace' | 'custom' | 'tool_search';+type ResponseToolIdentityKind = 'function' | 'custom' | 'tool_search';++export interface ChatBridgeToolSpec {+ kind: ChatBridgeToolKind;+ chatName: string;+ name: string;+ namespace?: string;+}++function responseToolIdentity(+ kind: ResponseToolIdentityKind,+ name: string,+ namespace?: string,+): string {+ return `${kind}\0${namespace ?? ''}\0${name}`;+}++function specIdentity(spec: ChatBridgeToolSpec): string {+ const kind = spec.kind === 'custom' || spec.kind === 'tool_search'+ ? spec.kind+ : 'function';+ return responseToolIdentity(kind, spec.name, spec.namespace);+}++/**+ * One request-scoped catalog for the lossy Chat `function` namespace. It makes request and+ * response translation symmetrical: names flattened for Chat are restored to their Responses+ * function/custom/tool_search representation on the way back.+ */+export class ChatBridgeToolContext {+ private readonly chatToolsValue: NonNullable<ChatCompletionsRequest['tools']> = [];+ private readonly specsByChatName = new Map<string, ChatBridgeToolSpec>();+ private readonly chatNamesByResponseName = new Map<string, string>();++ static fromRequest(request: ResponsesRequest): ChatBridgeToolContext {+ const context = new ChatBridgeToolContext();+ for (const tool of request.tools ?? []) context.addResponseTool(tool);+ context.collectHistoryTools(request.input);+ return context;+ }++ get chatTools(): ChatCompletionsRequest['tools'] {+ return this.chatToolsValue.length > 0 ? this.chatToolsValue : undefined;+ }++ lookupChatName(chatName: string): ChatBridgeToolSpec | undefined {+ return this.specsByChatName.get(chatName);+ }++ /** Whether a streamed name may still resolve to a longer catalogued Chat tool name. */+ hasChatNamePrefix(prefix: string): boolean {+ if (!prefix) return false;+ for (const chatName of this.specsByChatName.keys()) {+ if (chatName !== prefix && chatName.startsWith(prefix)) return true;+ }+ return false;+ }++ chatNameForResponse(+ name: string,+ namespace?: string,+ kind: ResponseToolIdentityKind = 'function',+ ): string {+ return this.chatNamesByResponseName.get(responseToolIdentity(kind, name, namespace))+ ?? clampChatToolName(namespace ? `${namespace}__${name}` : name);+ }++ private reserveName(preferred: string, identity: string): string {+ const clamped = clampChatToolName(preferred);+ const existing = this.specsByChatName.get(clamped);+ if (!existing) return clamped;+ if (specIdentity(existing) === identity) return clamped;+ for (let attempt = 0; ; attempt += 1) {+ const suffix = `__${shortHash(attempt === 0 ? identity : `${identity}\0${attempt}`)}`;+ const candidate = `${clamped.slice(0, CHAT_TOOL_NAME_MAX_LENGTH - suffix.length)}${suffix}`;+ const occupant = this.specsByChatName.get(candidate);+ if (!occupant || specIdentity(occupant) === identity) return candidate;+ }+ }++ private addFunction(tool: ResponsesFunctionTool, namespace?: string): void {+ const nested = isPlainObject((tool as unknown as Record<string, unknown>).function)+ ? (tool as unknown as Record<string, unknown>).function+ : undefined;+ const source = nested ? { ...tool, ...nested } as ResponsesFunctionTool : tool;+ if (!source.name?.trim()) return;+ const identity = responseToolIdentity('function', source.name, namespace);+ const chatName = this.reserveName(namespace ? `${namespace}__${source.name}` : source.name, identity);+ if (this.specsByChatName.has(chatName)) return;+ const spec: ChatBridgeToolSpec = {+ kind: namespace ? 'namespace' : 'function',+ chatName,+ name: source.name,+ ...(namespace ? { namespace } : {}),+ };+ this.specsByChatName.set(chatName, spec);+ this.chatNamesByResponseName.set(identity, chatName);+ this.chatToolsValue.push({+ type: 'function',+ function: {+ name: chatName,+ ...(source.description ? { description: source.description } : {}),+ parameters: normalizeFunctionParameters(source.parameters),+ ...(typeof source.strict === 'boolean' ? { strict: source.strict } : {}),+ },+ });+ }++ private addCustom(tool: ResponsesCustomTool, namespace?: string): void {+ if (!tool.name?.trim()) return;+ const identity = responseToolIdentity('custom', tool.name, namespace);+ const chatName = this.reserveName(namespace ? `${namespace}__${tool.name}` : tool.name, identity);+ if (this.specsByChatName.has(chatName)) return;+ const spec: ChatBridgeToolSpec = {+ kind: 'custom',+ chatName,+ name: tool.name,+ ...(namespace ? { namespace } : {}),+ };+ this.specsByChatName.set(chatName, spec);+ this.chatNamesByResponseName.set(identity, chatName);+ this.chatToolsValue.push({+ type: 'function',+ function: {+ name: chatName,+ description: chatCustomToolDescription(tool, namespace),+ parameters: {+ type: 'object',+ properties: {+ input: {+ type: 'string',+ description: CUSTOM_TOOL_INPUT_DESCRIPTION,+ },+ },+ required: ['input'],+ },+ },+ });+ }++ private addToolSearch(): void {+ const identity = responseToolIdentity('tool_search', TOOL_SEARCH_CHAT_NAME);+ const chatName = this.reserveName(TOOL_SEARCH_CHAT_NAME, identity);+ if (this.specsByChatName.has(chatName)) return;+ const spec: ChatBridgeToolSpec = {+ kind: 'tool_search',+ chatName,+ name: TOOL_SEARCH_CHAT_NAME,+ };+ this.specsByChatName.set(chatName, spec);+ this.chatNamesByResponseName.set(identity, chatName);+ this.chatToolsValue.push({+ type: 'function',+ function: {+ name: chatName,+ description: 'Search and load Codex tools, plugins, connectors, and MCP namespaces.',+ parameters: {+ type: 'object',+ properties: {+ query: { type: 'string', description: 'Search query for tools or connectors to load.' },+ limit: { type: 'integer', description: 'Maximum number of tool groups to return.' },+ },+ required: ['query'],+ },+ },+ });+ }++ private addNamespace(tool: ResponsesNamespaceTool): void {+ if (!tool.name?.trim()) return;+ for (const child of tool.tools ?? tool.children ?? []) {+ if (!isPlainObject(child) || typeof child.name !== 'string') continue;+ if (child.type === 'function') this.addFunction(child as unknown as ResponsesFunctionTool, tool.name);+ if (child.type === 'custom') this.addCustom(child as unknown as ResponsesCustomTool, tool.name);+ }+ }++ private addResponseTool(tool: ResponseTool): void {+ if (typeof tool === 'string') {+ this.addCustom({ type: 'custom', name: tool });+ return;+ }+ if (!isPlainObject(tool)) return;+ if (tool.type === 'function') this.addFunction(tool as unknown as ResponsesFunctionTool);+ if (tool.type === 'custom') this.addCustom(tool as unknown as ResponsesCustomTool);+ if (tool.type === 'tool_search') this.addToolSearch();+ if (tool.type === 'namespace') this.addNamespace(tool as unknown as ResponsesNamespaceTool);+ }++ private collectHistoryTools(input: ResponsesRequest['input']): void {+ if (!Array.isArray(input)) return;+ for (const item of input) {+ if (!isPlainObject(item)) continue;+ if (item.type === 'tool_search_call') this.addToolSearch();+ if (item.type === 'custom_tool_call' && typeof item.name === 'string') {+ this.addCustom(+ { type: 'custom', name: item.name },+ typeof item.namespace === 'string' ? item.namespace : undefined,+ );+ }+ if (+ (item.type === 'tool_search_output' || item.type === 'tool_search_call_output')+ && Array.isArray(item.tools)+ ) {+ for (const tool of item.tools) {+ this.addResponseTool(tool as ResponseTool);+ }+ }+ }+ }+}diff --git a/packages/model-compat/src/cindy/types.ts b/packages/model-compat/src/cindy/types.tsnew file mode 100644index 0000000000..b019c902d4--- /dev/null+++ b/packages/model-compat/src/cindy/types.ts@@ -0,0 +1,474 @@+/**+ * OpenAI Responses / Chat Completions 的 bridge 最小公开类型。+ *+ * 这里只声明转换器实际读写的字段。Responses 请求来自 Codex,遇到未知 input item+ * 必须 fail-closed,不能静默删除上下文;其它顶层未知字段由转换器明确忽略。+ */++import type { ServerResponse } from 'node:http';++export interface ResponsesInputTextPart {+ type: 'input_text' | 'output_text' | 'text';+ text: string;+}++export interface ResponsesInputImagePart {+ type: 'input_image';+ image_url?: string | {+ url: string;+ detail?: string;+ };+ file_id?: string;+ detail?: string;+}++export interface ResponsesInputFilePart {+ type: 'input_file';+ file_id?: string;+ file_data?: string;+ file_url?: string;+ filename?: string;+}++export interface ResponsesInputAudioPart {+ type: 'input_audio';+ input_audio?: {+ data: string;+ format: string;+ };+ data?: string;+ format?: string;+}++export type ResponsesContentPart =+ | ResponsesInputTextPart+ | ResponsesInputImagePart+ | ResponsesInputFilePart+ | ResponsesInputAudioPart+ | {+ type: string;+ [key: string]: unknown;+};++export interface ChatToolCallExtraContent {+ [key: string]: unknown;+ google?: {+ [key: string]: unknown;+ thought_signature?: string;+ };+}++export type ResponsesInputItem =+ | {+ type?: 'message';+ role: 'user' | 'assistant' | 'system' | 'developer';+ content: string | ResponsesContentPart[];+ }+ | {+ type: 'function_call';+ call_id: string;+ name: string;+ arguments: string;+ extra_content?: ChatToolCallExtraContent;+ }+ | {+ type: 'function_call_output';+ call_id: string;+ output: unknown;+ }+ | {+ type: 'reasoning';+ [key: string]: unknown;+ }+ | {+ type: string;+ [key: string]: unknown;+ };++export interface ResponsesFunctionTool {+ type: 'function';+ name: string;+ description?: string;+ parameters?: Record<string, unknown>;+ strict?: boolean;+}++export interface ResponsesCustomTool {+ type: 'custom';+ name: string;+ description?: string;+ [key: string]: unknown;+}++export interface ResponsesNamespaceTool {+ type: 'namespace';+ name: string;+ tools?: Array<ResponsesFunctionTool | ResponsesCustomTool | { type: string; [key: string]: unknown }>;+ children?: Array<ResponsesFunctionTool | ResponsesCustomTool | { type: string; [key: string]: unknown }>;+ [key: string]: unknown;+}++export interface ResponsesRequest {+ model: string;+ instructions?: string | ResponsesContentPart[];+ input: string | ResponsesInputItem[];+ tools?: Array<+ | string+ | ResponsesFunctionTool+ | ResponsesCustomTool+ | ResponsesNamespaceTool+ | { type: string; [key: string]: unknown }+ >;+ tool_choice?: unknown;+ parallel_tool_calls?: boolean;+ max_output_tokens?: number;+ reasoning?: { effort?: string; [key: string]: unknown };+ temperature?: number;+ top_p?: number;+ frequency_penalty?: number;+ presence_penalty?: number;+ stop?: string | string[];+ seed?: number;+ user?: string;+ metadata?: Record<string, unknown>;+ service_tier?: string;+ response_format?: unknown;+ text?: { format?: unknown; [key: string]: unknown };+ logit_bias?: Record<string, number>;+ logprobs?: boolean;+ top_logprobs?: number;+ n?: number;+ stream?: boolean;+ store?: boolean;+ [key: string]: unknown;+}++export interface ChatTextContentPart {+ type: 'text';+ text: string;+}++export interface ChatImageUrlContentPart {+ type: 'image_url';+ image_url: {+ url: string;+ detail?: string;+ };+}++export interface ChatFileContentPart {+ type: 'file';+ file: {+ file_id?: string;+ file_data?: string;+ file_url?: string;+ filename?: string;+ };+}++export interface ChatInputAudioContentPart {+ type: 'input_audio';+ input_audio: {+ data: string;+ format: string;+ };+}++export type ChatUserContentPart =+ | ChatTextContentPart+ | ChatImageUrlContentPart+ | ChatFileContentPart+ | ChatInputAudioContentPart;++export interface ChatTextMessage {+ role: 'system' | 'developer';+ content: string;+}++export interface ChatUserMessage {+ role: 'user';+ content: string | ChatUserContentPart[];+}++export interface ChatAssistantMessage {+ role: 'assistant';+ content?: string | null;+ /** DeepSeek/Kimi/Moonshot 的思考模型要求带 tool_calls 的 assistant 消息携带非空 reasoning_content。 */+ reasoning_content?: string;+ tool_calls?: Array<{+ id: string;+ type: 'function';+ function: { name: string; arguments: string };+ /** OpenAI 兼容层的厂商扩展;当前仅用于 Google Gemini thought signature。 */+ extra_content?: ChatToolCallExtraContent;+ }>;+}++export interface ChatToolMessage {+ role: 'tool';+ tool_call_id: string;+ content: string;+}++export type ChatMessage = ChatTextMessage | ChatUserMessage | ChatAssistantMessage | ChatToolMessage;++export interface ChatCompletionsRequest {+ model: string;+ messages: ChatMessage[];+ tools?: Array<{+ type: 'function';+ function: {+ name: string;+ description?: string;+ parameters: Record<string, unknown>;+ strict?: boolean;+ };+ }>;+ tool_choice?: unknown;+ parallel_tool_calls?: boolean;+ max_tokens?: number;+ max_completion_tokens?: number;+ reasoning_effort?: string;+ reasoning?: { effort: string };+ thinking?: { type: string };+ enable_thinking?: boolean;+ reasoning_split?: boolean;+ temperature?: number;+ top_p?: number;+ frequency_penalty?: number;+ presence_penalty?: number;+ stop?: string | string[];+ seed?: number;+ user?: string;+ metadata?: Record<string, unknown>;+ service_tier?: string;+ response_format?: unknown;+ logit_bias?: Record<string, number>;+ logprobs?: boolean;+ top_logprobs?: number;+ stream: boolean;+ stream_options?: { include_usage: true };+}++export type ChatDeveloperRole = 'developer' | 'system';+export type ChatMaxTokensField = 'max_tokens' | 'max_completion_tokens' | 'omit';+export type ChatImageInput = 'image_url';+export type ChatFileInput = 'file';+export type ChatAudioInput = 'input_audio';+export type ChatReasoningField =+ | 'reasoning_effort'+ | 'reasoning.effort'+ | 'thinking.type'+ | 'enable_thinking'+ | 'reasoning_split'+ | 'none';+export type ChatReasoningHistoryField = 'reasoning_content';+export type ChatPassthroughField =+ | 'temperature'+ | 'top_p'+ | 'frequency_penalty'+ | 'presence_penalty'+ | 'stop'+ | 'seed'+ | 'user'+ | 'metadata'+ | 'service_tier'+ | 'response_format'+ | 'logit_bias'+ | 'logprobs'+ | 'top_logprobs';++/** 同协议族内的上游差异,全部由数据表达(对齐 cc-switch / opencodex 的 per-provider 处理)。 */+export interface ChatBridgeCapabilities {+ developerRole?: ChatDeveloperRole;+ parallelToolCalls?: boolean;+ maxTokensField?: ChatMaxTokensField;+ reasoningField?: ChatReasoningField;+ /**+ * Responses reasoning history 的 Chat 消息字段。默认未声明 = 省略历史 reasoning;+ * 只有明确接受厂商扩展 `reasoning_content` 的上游才应开启。+ */+ reasoningHistoryField?: ChatReasoningHistoryField;+ /**+ * Responses `input_image` 的上游等价形态。默认未声明 = fail closed;只由+ * 已确认支持视觉输入的运行时(当前为 upstream 白名单)开启。+ */+ imageInput?: ChatImageInput;+ /** Responses `input_file` 的上游等价形态;默认未声明 = fail closed。 */+ fileInput?: ChatFileInput;+ /** Responses `input_audio` 的上游等价形态;默认未声明 = fail closed。 */+ audioInput?: ChatAudioInput;+ /** 仅对明确采用 `<think>...</think>` 内联推理方言的上游启用标签解析。 */+ inlineReasoning?: boolean;+ /** 将 Responses reasoning.effort 映射成供应商接受的枚举值。未声明时原样使用。 */+ reasoningEffortMap?: Readonly<Record<string, string | boolean>>;+ /** 只有显式列入的 Chat 可选字段才会转发,避免严格兼容端点因未知字段返回 400。 */+ passthroughFields?: readonly ChatPassthroughField[];+ streamUsage?: boolean;+ /**+ * thinking 模型(DeepSeek/Kimi/Moonshot)要求每个带 tool_calls 的 assistant 消息携带非空+ * reasoning_content,否则上游报 `reasoning_content is missing in assistant tool call message`。+ * 开启后为缺失的 tool_call assistant 消息注入占位文本。+ */+ toolCallReasoningPlaceholder?: boolean;+ /**+ * reasoning 模型拒绝强制 tool_choice(如 DeepSeek `Thinking mode does not support this tool_choice`)。+ * 开启后把具名 / required 的 tool_choice 降级为 'auto'。+ */+ forceAutoToolChoice?: boolean;+ /**+ * Gemini 3 在工具结果下一轮强制校验 thought signature。Responses 历史不承载 Google 的+ * `tool_calls[].extra_content`,开启后按 Google 官方兼容说明给每步首个 call 写入+ * `skip_thought_signature_validator`,避免桥接历史在首个工具调用后稳定 400。+ */+ googleThoughtSignaturePlaceholder?: boolean;+ /** 缺少上游 usage 时仍生成 Responses 要求的完整零值 usage 结构。默认开启。 */+ zeroUsageOnMissing?: boolean;+ /**+ * Ollama/Qwen Chat 模板要求 system 只能出现在消息列表开头。+ * `coalesce-leading` 把所有 system/developer 按原顺序合并成唯一的首条 system。+ */+ systemMessagePolicy?: 'preserve' | 'coalesce-leading';+}++export interface ChatBridgeLogger {+ debug?: (msg: string, meta?: Record<string, unknown>) => void;+ info?: (msg: string, meta?: Record<string, unknown>) => void;+ warn?: (msg: string, meta?: Record<string, unknown>) => void;+ error?: (msg: string, meta?: Record<string, unknown>) => void;+}++export interface ChatBridgeUpstreamErrorInfo {+ status: number;+ body: string;+ /** 可能含凭证,只能用于内存态关联,禁止写日志。 */+ requestHeaders: Readonly<Record<string, string>>;+}++export interface ChatBridgeProviderConfig {+ upstreamBase: string;+ /** 缺省 `/chat/completions`;少数厂商可显式覆盖。 */+ chatCompletionsPath?: string;+ buildHeaders: () => Promise<Record<string, string>>;+ /** 把 wire model 改成上游真实 model;缺省原样。 */+ rewriteModel?: (model: string) => string;+ capabilities?: ChatBridgeCapabilities;+ onUpstreamError?: (info: ChatBridgeUpstreamErrorInfo) => void | Promise<void>;+}++export interface ChatBridgeHandleArgs {+ parsedBody: unknown;+ res: ServerResponse;+ /**+ * 经本地代理验证过的入站请求头快照(#4073)。bridge **不**透传它们,只从中解析稳定会话+ * 标识映射为出站 `x-opencode-session`(见 session-header.ts);省略 = 不附加会话头。+ */+ requestHeaders?: Readonly<Record<string, string>>;+}++export interface ResponsesChatBridgeHandler {+ handle(args: ChatBridgeHandleArgs): Promise<void>;+}++const UNSUPPORTED_RESPONSES_FEATURE_MESSAGE_PREFIX =+ 'Responses feature is not supported by the Chat Completions bridge: ';+const RESPONSES_IMAGE_CONTENT_PART_TYPES = new Set(['input_image', 'image_url', 'image']);+const CODEX_UNEXPECTED_BAD_REQUEST_PREFIX = /^unexpected status 400(?: Bad Request)?: /;+const CODEX_ERROR_METADATA_MARKERS = [+ ', url: ',+ ', cf-ray: ',+ ', request id: ',+ ', auth error: ',+ ', auth error code: ',+] as const;++export function isResponsesImageContentPartType(+ value: unknown,+): value is 'input_image' | 'image_url' | 'image' {+ return typeof value === 'string' && RESPONSES_IMAGE_CONTENT_PART_TYPES.has(value);+}++function unsupportedResponsesFeatureFromMessage(message: string): string | null {+ return message.startsWith(UNSUPPORTED_RESPONSES_FEATURE_MESSAGE_PREFIX)+ ? message.slice(UNSUPPORTED_RESPONSES_FEATURE_MESSAGE_PREFIX.length)+ : null;+}++function isUnsupportedResponsesImageFeature(feature: string): boolean {+ const contentPartMatch = /^input content part '([^']+)'$/.exec(feature);+ const contentPartType = contentPartMatch?.[1] ?? feature;+ return isResponsesImageContentPartType(contentPartType)+ || contentPartType.startsWith('input_image.');+}++function isUnsupportedResponsesImageErrorObject(value: unknown): boolean {+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;+ const error = (value as Record<string, unknown>).error;+ if (typeof error !== 'object' || error === null || Array.isArray(error)) return false;+ const { code, message } = error as Record<string, unknown>;+ if (code !== 'unsupported_feature' || typeof message !== 'string') return false;+ const feature = unsupportedResponsesFeatureFromMessage(message);+ return feature !== null && isUnsupportedResponsesImageFeature(feature);+}++function parseJson(value: string): unknown {+ try {+ return JSON.parse(value) as unknown;+ } catch {+ return null;+ }+}++function parseCodexWrappedJson(value: string): unknown {+ const jsonStart = value.indexOf('{');+ if (jsonStart < 0) return null;++ // Codex may append transport metadata after the serialized response body. Walk closing braces+ // from right to left so braces in that metadata cannot prevent recovery of the response object.+ let jsonEnd = value.lastIndexOf('}');+ while (jsonEnd > jsonStart) {+ const parsed = parseJson(value.slice(jsonStart, jsonEnd + 1));+ if (parsed !== null) return parsed;+ jsonEnd = value.lastIndexOf('}', jsonEnd - 1);+ }+ return null;+}++function stripCodexErrorMetadata(value: string): string {+ let end = value.length;+ for (const marker of CODEX_ERROR_METADATA_MARKERS) {+ const index = value.indexOf(marker);+ if (index >= 0 && index < end) end = index;+ }+ return value.slice(0, end);+}++/**+ * Classifies an unsupported-image error emitted by this bridge. Direct OpenAI-style response+ * bodies and Codex's `unexpected status 400 ...` rendering are both accepted; current Codex+ * extracts `error.message`, while older/future runtimes may retain the serialized body. Both the+ * current content-part feature and the legacy direct `input_image` feature remain recoverable.+ */+export function isUnsupportedResponsesImageErrorPayload(payload: string | null): boolean {+ if (!payload) return false;+ if (isUnsupportedResponsesImageErrorObject(parseJson(payload))) return true;++ const codexPrefix = CODEX_UNEXPECTED_BAD_REQUEST_PREFIX.exec(payload);+ if (!codexPrefix) return false;+ const renderedBody = payload.slice(codexPrefix[0].length);+ if (isUnsupportedResponsesImageErrorObject(parseCodexWrappedJson(renderedBody))) return true;++ const message = stripCodexErrorMetadata(renderedBody);+ const feature = unsupportedResponsesFeatureFromMessage(message);+ return feature !== null && isUnsupportedResponsesImageFeature(feature);+}++export class UnsupportedResponsesFeatureError extends Error {+ readonly feature: string;++ constructor(feature: string) {+ super(`${UNSUPPORTED_RESPONSES_FEATURE_MESSAGE_PREFIX}${feature}`);+ this.name = 'UnsupportedResponsesFeatureError';+ this.feature = feature;+ }+}diff --git a/packages/model-compat/src/codex.ts b/packages/model-compat/src/codex.tsnew file mode 100644index 0000000000..99733a1b5e--- /dev/null+++ b/packages/model-compat/src/codex.ts@@ -0,0 +1,83 @@+import { resolveProviderCompatibilityProfile, type CompatibilityRoute } from './profiles';+import { routeUsesContentChannelReasoning } from './upstream/server/responses-reasoning-summary-rewrite';+import type { ResponsesItemIdRepairConfig } from './upstream/types/provider';+import { isPlainObject } from './object';+import { createResponsesCustomToolFunctionAdapter } from './cindy/custom-tool-function-adapter';+import { chainResponseTransforms } from './cindy/responses-null-array-repair';+import { createResponsesCompatibilityAdapter } from './responses';++/** Codex's code-mode contract includes Cindy's helper names and collision-safe aliases.+ * Keep that conversion ahead of upstream generic custom/namespace/tool-search lowering,+ * and restore in reverse order. This adapter is selected only for Responses routes whose+ * actual routing descriptor declares that Codex custom tools are unsupported.+ */+export function createCodexResponsesCompatibilityAdapter() {+ const codeMode = createResponsesCustomToolFunctionAdapter(['exec']);+ const makeUpstream = (lowerNamespaces: boolean) => createResponsesCompatibilityAdapter({+ customTools: 'preserve-apply-patch',+ namespaceTools: lowerNamespaces ? 'functions' : 'native',+ toolSearch: 'function',+ repairFunctionArguments: true,+ });+ const generic = makeUpstream(false);+ const lowered = makeUpstream(true);+ const selected = new Map<number, { adapter: typeof generic; at: number }>();+ return {+ adaptRequest(body: unknown, requestId: number, route?: CompatibilityRoute, lowerNamespaces = false): unknown | null {+ // The host supplies namespace support from the effective route, independently of+ // custom-tool support. A familiar model name is not a routing capability.+ codeMode.releaseResponse(requestId);+ selected.get(requestId)?.adapter.releaseResponse(requestId);+ selected.delete(requestId);+ const now = Date.now();+ for (const [id, entry] of selected) {+ if (now - entry.at < 15 * 60_000) continue;+ codeMode.releaseResponse(id);+ entry.adapter.releaseResponse(id);+ selected.delete(id);+ }+ if (!selected.has(requestId) && selected.size >= 256) throw new Error('too many in-flight compatibility requests');+ const upstream = lowerNamespaces ? lowered : generic;+ selected.set(requestId, { adapter: upstream, at: now });+ try {+ const code = codeMode.adaptRequest(body, requestId) ?? body;+ const profile = route ? resolveProviderCompatibilityProfile(route) : null;+ const overrides = profile ? {+ ...(profile.supportsResponsesCustomTools === false ? { customTools: 'functions' as const } : {}),+ ...(isPlainObject(profile.responsesItemIdRepair) ? { itemIdRepair: profile.responsesItemIdRepair as ResponsesItemIdRepairConfig } : {}),+ contentChannelReasoning: routeUsesContentChannelReasoning({+ statelessResponses: profile.statelessResponses === true,+ preserveReasoningContentModels: Array.isArray(profile.preserveReasoningContentModels) ? profile.preserveReasoningContentModels.filter((value): value is string => typeof value === 'string') : undefined,+ }, route!.model),+ } : {};+ const tools = upstream.adaptRequest(code, requestId, overrides) ?? code;+ return tools === body ? null : tools;+ } catch (error) {+ codeMode.releaseResponse(requestId);+ upstream.releaseResponse(requestId);+ selected.delete(requestId);+ throw error;+ }+ },+ releaseResponse(requestId: number): void {+ codeMode.releaseResponse(requestId);+ generic.releaseResponse(requestId);+ lowered.releaseResponse(requestId);+ selected.delete(requestId);+ },+ createResponseTransform(requestId: number, response: { contentType: string; contentEncoding: string }) {+ const upstream = selected.get(requestId)?.adapter;+ selected.delete(requestId);+ let first: ReturnType<typeof generic.createResponseTransform> = null;+ try {+ first = upstream?.createResponseTransform(requestId, response) ?? null;+ return chainResponseTransforms(first, codeMode.createResponseTransform(requestId, response));+ } catch (error) {+ first?.destroy();+ codeMode.releaseResponse(requestId);+ upstream?.releaseResponse(requestId);+ throw error;+ }+ },+ };+}diff --git a/packages/model-compat/src/index.ts b/packages/model-compat/src/index.tsnew file mode 100644index 0000000000..229e33248a--- /dev/null+++ b/packages/model-compat/src/index.ts@@ -0,0 +1,25 @@+export { prepareResponsesCompatibility, createResponsesCompatibilityAdapter, type ResponsesCompatibilityPolicy } from './responses';+export { normalizeXaiResponsesWebSearch } from './upstream/adapters/xai-web-search';+export { normalizeXaiToolParameters, isXaiSchemaTarget } from './upstream/adapters/xai-tool-schema';+export { stripResponsesOnlyEncryptedMarker } from './upstream/adapters/responses-tool-schema';+export { sanitizeGeminiToolParameters } from './upstream/adapters/google-tool-schema';+export * from './providers/xai';+export * from './providers/seed';+export * from './providers/history';+export * from './providers/deepseek';+export * from './cindy/custom-tool-function-adapter';+export * from './cindy/tool-context';+export * from './cindy/types';+export * from './cindy/responses-null-array-repair';+export { createCodexResponsesCompatibilityAdapter } from './codex';+export * from './cindy/proxy/transform';+export * from './cindy/proxy/xai-model-input';+export * from './cindy/proxy/vllm-responses-compatibility';+export * from './cindy/proxy/headers';+export * from './cindy/proxy/thread-strip-controller';+export type * from './cindy/proxy/types';+export { resolveProviderCompatibilityProfile, profileModelValue, profileModelListed, type CompatibilityRoute, type CompatibilityHarness, type CompatibilityProtocol } from './profiles';+export { normalizeProviderRequest } from './request';+export { chatCompatibilityCapabilities } from './chat';+export { isStrictCompatibleSchema } from './cindy/strict-schema';+export { normalizeMiniMaxResponsesReasoning } from './providers/minimax';diff --git a/packages/model-compat/src/object.ts b/packages/model-compat/src/object.tsnew file mode 100644index 0000000000..d741704f90--- /dev/null+++ b/packages/model-compat/src/object.ts@@ -0,0 +1,3 @@+export function isPlainObject(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === "object" && !Array.isArray(value);+}diff --git a/packages/model-compat/src/profiles.ts b/packages/model-compat/src/profiles.tsnew file mode 100644index 0000000000..18eea03c56--- /dev/null+++ b/packages/model-compat/src/profiles.ts@@ -0,0 +1,50 @@+import { isXaiSchemaTarget } from './upstream/adapters/xai-tool-schema';+import { modelRecordValue } from './upstream/reasoning-effort';+import profiles from './upstream-profiles.json';+import { isPlainObject } from './object';++export type CompatibilityHarness = 'codex' | 'claude-code' | 'pi';+export type CompatibilityProtocol = 'openai-responses' | 'openai-chat' | 'anthropic' | 'google';+/** Execution facts, never inferred from the display name or a user's account identity. */+export interface CompatibilityRoute {+ harness: CompatibilityHarness;+ protocol: CompatibilityProtocol;+ upstreamBase: string;+ model: string;+ authMode?: 'oauth' | 'api-key';+}+export type ProviderCompatibilityProfile = Record<string, unknown> & { id: string; baseUrl: string; adapter: string };++/** Exact origin and path boundaries prevent a provider's patch leaking to a lookalike or proxy. */+function servesEndpoint(base: string, actual: string): boolean {+ try {+ const expected = new URL(base);+ const target = new URL(actual);+ const prefix = expected.pathname.replace(/\/+$/, '');+ return expected.origin === target.origin && (target.pathname === prefix || target.pathname.startsWith(prefix + '/'));+ } catch { return false; }+}++/** Upstream provider declarations are compatibility data only: they never add accounts or models. */+export function resolveProviderCompatibilityProfile(route: CompatibilityRoute): ProviderCompatibilityProfile | null {+ // OpenCodex's xAI OAuth transport rewrites the public registry base to this exact+ // subscription endpoint. Reuse that transport predicate, not a model-name alias.+ if (isXaiSchemaTarget({ baseUrl: route.upstreamBase })) {+ return (profiles as ProviderCompatibilityProfile[]).find(profile => profile.id === 'xai') ?? null;+ }+ const matches = (profiles as ProviderCompatibilityProfile[]).filter(profile => servesEndpoint(profile.baseUrl, route.upstreamBase));+ matches.sort((a, b) => b.baseUrl.length - a.baseUrl.length);+ // Multiple provider identities at the same endpoint cannot be resolved by the model label alone.+ if (matches.length > 1 && matches[0]!.baseUrl === matches[1]!.baseUrl) return null;+ return matches[0] ?? null;+}++/** OpenCodex uses exact model membership, with a colon variant falling back to its base. */+export function profileModelValue(value: unknown, model: string): unknown {+ if (!isPlainObject(value)) return undefined;+ return modelRecordValue(value, model);+}+export function profileModelListed(value: unknown, model: string): boolean {+ if (!Array.isArray(value)) return false;+ return value.includes(model) || (model.includes(':') && value.includes(model.slice(0, model.indexOf(':'))));+}diff --git a/packages/model-compat/src/providers/deepseek.ts b/packages/model-compat/src/providers/deepseek.tsnew file mode 100644index 0000000000..7b72aa7732--- /dev/null+++ b/packages/model-compat/src/providers/deepseek.ts@@ -0,0 +1,56 @@+/** Cindy provider policies, consolidated from codex-proxy-host. Route selection stays in the host. */+import { isPlainObject } from "../object";++export const DEEPSEEK_V4_MODELS = new Set([+ 'deepseek/deepseek-v4-pro',+ 'deepseek/deepseek-v4-flash',+]);++export const DEEPSEEK_V4_SUPPORTED_CUSTOM_TOOL_NAMES = new Set(['apply_patch']);++export function deepSeekToolChoiceReferencesRemovedCustomTool(+ toolChoice: unknown,+ tools: readonly unknown[],+): boolean {+ if (!isPlainObject(toolChoice) || toolChoice.type !== 'custom' || typeof toolChoice.name !== 'string') {+ return false;+ }+ return !tools.some((tool) =>+ tool === toolChoice.name ||+ (isPlainObject(tool) && tool.type === 'custom' && tool.name === toolChoice.name),+ );+}++export function sanitizeDeepSeekV4CustomTools(body: unknown): Record<string, unknown> | null {+ if (!isPlainObject(body)) return null;+ if (!DEEPSEEK_V4_MODELS.has(typeof body.model === 'string' ? body.model : '')) return null;+ if (!Array.isArray(body.tools)) return null;++ let changed = false;+ const tools: unknown[] = [];+ for (const tool of body.tools) {+ const customToolName =+ typeof tool === 'string'+ ? tool+ : isPlainObject(tool) && tool.type === 'custom' && typeof tool.name === 'string'+ ? tool.name+ : null;+ if (customToolName !== null && !DEEPSEEK_V4_SUPPORTED_CUSTOM_TOOL_NAMES.has(customToolName)) {+ changed = true;+ continue;+ }+ tools.push(tool);+ }+ if (!changed) return null;++ const next: Record<string, unknown> = { ...body };+ if (tools.length > 0) {+ next.tools = tools;+ if (deepSeekToolChoiceReferencesRemovedCustomTool(next.tool_choice, tools)) next.tool_choice = 'auto';+ } else {+ delete next.tools;+ delete next.tool_choice;+ delete next.parallel_tool_calls;+ }+ return next;+}diff --git a/packages/model-compat/src/providers/history.ts b/packages/model-compat/src/providers/history.tsnew file mode 100644index 0000000000..edba97df0d--- /dev/null+++ b/packages/model-compat/src/providers/history.ts@@ -0,0 +1,106 @@+/** Cindy provider policies, consolidated from codex-proxy-host. Route selection stays in the host. */+import { isPlainObject } from "../object";+import { stripEmptyResponseMessage } from "./seed";++export const STRICT_GATEWAY_TOOL_HISTORY_MODELS = new Set([+ 'moonshot/kimi-k3',+ 'moonshotai/kimi-k3',+ 'deepseek/deepseek-v4-pro',+ 'deepseek/deepseek-v4-flash',+]);++export const RESPONSE_TOOL_CALL_TYPES = new Set(['function_call', 'custom_tool_call']);++export const RESPONSE_TOOL_OUTPUT_TYPES = new Set(['function_call_output', 'custom_tool_call_output']);++export function responseToolCallId(item: unknown, output: boolean): string | null {+ if (!isPlainObject(item)) return null;+ const supportedTypes = output ? RESPONSE_TOOL_OUTPUT_TYPES : RESPONSE_TOOL_CALL_TYPES;+ if (!supportedTypes.has(typeof item.type === 'string' ? item.type : '')) return null;+ return typeof item.call_id === 'string' && item.call_id.length > 0 ? item.call_id : null;+}++export function normalizeStrictGatewayHistory(+ body: Record<string, unknown>,+ routingModel = typeof body.model === 'string' ? body.model : '',+): Record<string, unknown> | null {+ if (+ !STRICT_GATEWAY_TOOL_HISTORY_MODELS.has(routingModel) ||+ !Array.isArray(body.input)+ ) {+ return null;+ }++ const originalInput = body.input;+ const normalizedInput: unknown[] = [];+ for (const item of originalInput) {+ const normalized = stripEmptyResponseMessage(item);+ if (normalized) normalizedInput.push(normalized.item);+ }++ const matchedOutputs = new Map<number, number>();+ const usedOutputIndexes = new Set<number>();+ const outputIndexesByCallId = new Map<string, number[]>();+ const outputCursorByCallId = new Map<string, number>();+ for (let index = 0; index < normalizedInput.length; index += 1) {+ const outputCallId = responseToolCallId(normalizedInput[index], true);+ if (!outputCallId) continue;+ const indexes = outputIndexesByCallId.get(outputCallId) ?? [];+ indexes.push(index);+ outputIndexesByCallId.set(outputCallId, indexes);+ }++ for (let callIndex = 0; callIndex < normalizedInput.length; callIndex += 1) {+ const callId = responseToolCallId(normalizedInput[callIndex], false);+ if (!callId) continue;++ const outputIndexes = outputIndexesByCallId.get(callId);+ if (!outputIndexes) continue;+ let cursor = outputCursorByCallId.get(callId) ?? 0;+ while (cursor < outputIndexes.length && outputIndexes[cursor] <= callIndex) cursor += 1;+ if (cursor >= outputIndexes.length) continue;++ const outputIndex = outputIndexes[cursor];+ outputCursorByCallId.set(callId, cursor + 1);+ matchedOutputs.set(callIndex, outputIndex);+ usedOutputIndexes.add(outputIndex);+ }++ const outputIndexesByGroupEnd = new Map<number, number[]>();+ for (let groupStart = 0; groupStart < normalizedInput.length;) {+ if (!responseToolCallId(normalizedInput[groupStart], false)) {+ groupStart += 1;+ continue;+ }+ let groupEnd = groupStart;+ while (+ groupEnd + 1 < normalizedInput.length &&+ responseToolCallId(normalizedInput[groupEnd + 1], false)+ ) {+ groupEnd += 1;+ }+ const outputIndexes: number[] = [];+ for (let callIndex = groupStart; callIndex <= groupEnd; callIndex += 1) {+ const outputIndex = matchedOutputs.get(callIndex);+ if (outputIndex !== undefined) outputIndexes.push(outputIndex);+ }+ if (outputIndexes.length > 0) {+ outputIndexesByGroupEnd.set(groupEnd, outputIndexes.sort((a, b) => a - b));+ }+ groupStart = groupEnd + 1;+ }++ const input: unknown[] = [];+ for (let index = 0; index < normalizedInput.length; index += 1) {+ if (usedOutputIndexes.has(index)) continue;+ input.push(normalizedInput[index]);+ const outputIndexes = outputIndexesByGroupEnd.get(index);+ if (outputIndexes) {+ for (const outputIndex of outputIndexes) input.push(normalizedInput[outputIndex]);+ }+ }+ const changed =+ input.length !== originalInput.length ||+ input.some((item, index) => item !== originalInput[index]);+ return changed ? { ...body, input } : null;+}diff --git a/packages/model-compat/src/providers/minimax.ts b/packages/model-compat/src/providers/minimax.tsnew file mode 100644index 0000000000..d9ed2b2136--- /dev/null+++ b/packages/model-compat/src/providers/minimax.ts@@ -0,0 +1,11 @@+import { isPlainObject } from '../object';++/** Cindy's existing MiniMax Responses contract; selected only by the host's actual route. */+export function normalizeMiniMaxResponsesReasoning(body: Record<string, unknown>): Record<string, unknown> | null {+ const reasoning = body.reasoning;+ if (!isPlainObject(reasoning)) return null;+ const next = { ...reasoning };+ if (next.effort === 'xhigh') next.effort = 'high';+ delete next.summary;+ return next.effort !== reasoning.effort || 'summary' in reasoning ? { ...body, reasoning: next } : null;+}diff --git a/packages/model-compat/src/providers/seed.ts b/packages/model-compat/src/providers/seed.tsnew file mode 100644index 0000000000..3f340e0aae--- /dev/null+++ b/packages/model-compat/src/providers/seed.ts@@ -0,0 +1,116 @@+/** Cindy provider policies, consolidated from codex-proxy-host. Route selection stays in the host. */+import { isPlainObject } from "../object";++export function seedToolChoiceReferencesRemovedTool(+ toolChoice: unknown,+ tools: Record<string, unknown>[],+): boolean {+ if (!isPlainObject(toolChoice) || typeof toolChoice.type !== 'string') return false;++ return !tools.some((tool) => {+ if (tool.type !== toolChoice.type) return false;+ if (toolChoice.type !== 'function') return true;+ return typeof toolChoice.name === 'string' && tool.name === toolChoice.name;+ });+}++export function sanitizeByteDanceSeedTools(body: Record<string, unknown>): Record<string, unknown> | null {+ if (!Array.isArray(body.tools)) return null;++ let changed = false;+ const tools: Record<string, unknown>[] = [];+ for (const tool of body.tools) {+ if (!isPlainObject(tool)) {+ changed = true;+ continue;+ }+ if (tool.type === 'function') {+ tools.push(tool);+ continue;+ }+ if (tool.type === 'web_search') {+ // Seed cannot represent Codex's cache-only search policy. Dropping the+ // tool preserves the caller's explicit prohibition on live web access.+ if (tool.external_web_access === false) {+ changed = true;+ continue;+ }+ tools.push({ type: 'web_search' });+ if (Object.keys(tool).length !== 1) changed = true;+ continue;+ }+ changed = true;+ }+ changed ||= tools.length === 0 && (body.tool_choice !== undefined || body.parallel_tool_calls !== undefined);+ if (!changed) return null;++ const next: Record<string, unknown> = { ...body };+ if (tools.length > 0) {+ next.tools = tools;+ if (seedToolChoiceReferencesRemovedTool(next.tool_choice, tools)) next.tool_choice = 'auto';+ } else {+ delete next.tools;+ delete next.tool_choice;+ delete next.parallel_tool_calls;+ }+ return next;+}++export function stripEmptyResponseMessage(item: unknown): { item: unknown; changed: boolean } | null {+ if (!isPlainObject(item) || item.type !== 'message') return { item, changed: false };+ if (item.content === '') return null;+ if (!Array.isArray(item.content)) return { item, changed: false };++ const content = item.content.filter((part) => !(+ isPlainObject(part) &&+ (part.type === 'input_text' || part.type === 'output_text') &&+ part.text === ''+ ));+ if (content.length === 0) return null;+ return content.length === item.content.length+ ? { item, changed: false }+ : { item: { ...item, content }, changed: true };+}++export function normalizeByteDanceSeedInput(body: Record<string, unknown>): Record<string, unknown> | null {+ if (!Array.isArray(body.input)) return null;++ let changed = false;+ const input: unknown[] = [];+ for (const item of body.input) {+ const normalized = stripEmptyResponseMessage(item);+ if (!normalized) {+ changed = true;+ continue;+ }+ if (normalized.changed) changed = true;++ const nextItem = normalized.item;+ if (+ isPlainObject(nextItem) &&+ nextItem.type === 'message' &&+ nextItem.role === 'assistant' &&+ typeof nextItem.status !== 'string'+ ) {+ changed = true;+ input.push({ ...nextItem, status: 'completed' });+ continue;+ }+ input.push(nextItem);+ }+ return changed ? { ...body, input } : null;+}++export function sanitizeByteDanceSeedReasoning(body: Record<string, unknown>): Record<string, unknown> | null {+ if (!isPlainObject(body.reasoning) || !('summary' in body.reasoning)) {+ return null;+ }++ const reasoning = { ...body.reasoning };+ delete reasoning.summary;++ const next: Record<string, unknown> = { ...body };+ if (Object.keys(reasoning).length > 0) next.reasoning = reasoning;+ else delete next.reasoning;+ return next;+}diff --git a/packages/model-compat/src/providers/xai.ts b/packages/model-compat/src/providers/xai.tsnew file mode 100644index 0000000000..aec219fb6b--- /dev/null+++ b/packages/model-compat/src/providers/xai.ts@@ -0,0 +1,115 @@+/** Cindy provider policies, consolidated from codex-proxy-host. Route selection stays in the host. */+import { isPlainObject } from "../object";+import { normalizeXaiResponsesWebSearch } from "../upstream/adapters/xai-web-search";++export const XAI_SUPPORTED_TOOL_TYPES = new Set([+ 'function',+ 'web_search',+ 'x_search',+ 'collections_search',+ 'file_search',+ 'code_execution',+ 'code_interpreter',+ 'mcp',+ 'shell',+]);++export 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';+}++export function sanitizeXaiTools(+ body: Record<string, unknown>,+ options: { preserveNoneToolChoice?: boolean; preserveSerialToolCalls?: boolean } = {},+): Record<string, unknown> | null {+ // This policy is invoked only after the host selects the xAI dialect, including its+ // explicitly identified gateway route. The vendor predicate remains exact-host scoped.+ const normalized = normalizeXaiResponsesWebSearch(body, { baseUrl: 'https://api.x.ai/v1' });+ const source = isPlainObject(normalized) ? normalized : body;+ let changed = source !== body;+ const declared = Array.isArray(source.tools) ? source.tools : [];+ const tools = declared.filter(tool => isPlainObject(tool)+ && typeof tool.type === 'string' && XAI_SUPPORTED_TOOL_TYPES.has(tool.type));+ changed ||= tools.length !== declared.length;+ const next: Record<string, unknown> = { ...source };+ const loadedTools: unknown[] = [];+ if (Array.isArray(source.input)) {+ const input = source.input.flatMap(item => {+ if (!isPlainObject(item) || item.type !== 'additional_tools' || !Array.isArray(item.tools)) return [item];+ const supported = item.tools.filter(tool => isPlainObject(tool)+ && typeof tool.type === 'string' && XAI_SUPPORTED_TOOL_TYPES.has(tool.type));+ loadedTools.push(...supported);+ if (supported.length === item.tools.length) return [item];+ changed = true;+ return supported.length ? [{ ...item, tools: supported }] : [];+ });+ if (changed) next.input = input;+ }+ const choice = xaiToolChoiceAfterSanitize(source.tool_choice, [...tools, ...loadedTools]);+ changed ||= choice !== source.tool_choice;+ changed ||= tools.length === 0 && loadedTools.length === 0 && (Array.isArray(source.tools) || source.tool_choice !== undefined || source.parallel_tool_calls !== undefined);+ if (!changed) return null;+ if (tools.length > 0 || loadedTools.length > 0) {+ if (tools.length > 0) next.tools = tools; else delete next.tools;+ if (choice !== undefined) next.tool_choice = choice;+ } 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;+}++export function hasCacheOnlySearchProhibition(body: Record<string, unknown>): boolean {+ const groups = [body.tools, ...(Array.isArray(body.input) ? body.input.flatMap(item =>+ isPlainObject(item) && item.type === 'additional_tools' ? [item.tools] : []) : [])];+ return groups.some(group => Array.isArray(group) && group.some(tool =>+ isPlainObject(tool) && (tool.type === 'web_search' || tool.type === 'web_search_preview')+ && Object.hasOwn(tool, 'external_web_access') && tool.external_web_access !== true));+}diff --git a/packages/model-compat/src/request.ts b/packages/model-compat/src/request.tsnew file mode 100644index 0000000000..2897c5b1d1--- /dev/null+++ b/packages/model-compat/src/request.ts@@ -0,0 +1,125 @@+import { mapReasoningEffort, REASONING_EFFORT_OMIT_SENTINEL } from './upstream/reasoning-effort';+import type { OcxProviderConfig } from './upstream/types/provider';+import { backfillWebSearchQueries, normalizeResponsesToolResultAdjacency, annotateEmptyResponsesToolOutputs } from './upstream/adapters/openai-responses';+import { stripBracketedModelSuffix, reasoningDetailSegmentForWire, thinkingBudgetForEffort, normalizeMoonshotToolParameters, isMoonshotSchemaTarget } from './upstream/adapters/openai-chat';+import { isPlainObject } from './object';+import { resolveProviderCompatibilityProfile, profileModelListed, profileModelValue, type CompatibilityRoute } from './profiles';+import { normalizeXaiResponsesWebSearch } from './upstream/adapters/xai-web-search';+import { isXaiSchemaTarget, normalizeXaiToolParameters } from './upstream/adapters/xai-tool-schema';+import { stripResponsesOnlyEncryptedMarker } from './upstream/adapters/responses-tool-schema';+import { normalizeOpenCodeGoAdditionalTools } from './upstream/adapters/opencode-go-additional-tools';++/** Provider parameter policy shared by all harnesses, after protocol translation.+ * A harness's private tool dialect is handled separately in the request-owned Responses adapter.+ */+export function normalizeProviderRequest(body: unknown, route: CompatibilityRoute, options: { reasoningEffortAlreadyMapped?: boolean } = {}): unknown {+ if (!isPlainObject(body)) return body;+ const profile = resolveProviderCompatibilityProfile(route);+ let next = body;+ const set = (key: string, value: unknown) => {+ if (next[key] === value) return;+ if (next === body) next = { ...body };+ if (value === undefined) delete next[key]; else next[key] = value;+ };+ if (route.protocol === 'openai-chat' && isMoonshotSchemaTarget({ baseUrl: route.upstreamBase } as OcxProviderConfig) && Array.isArray(next.tools)) {+ const tools = next.tools.map(tool => {+ if (!isPlainObject(tool) || tool.type !== 'function' || !isPlainObject(tool.function)) return tool;+ return { ...tool, function: { ...tool.function, parameters: normalizeMoonshotToolParameters(tool.function.parameters) } };+ });+ set('tools', tools);+ }+ if (profile) {+ if (profileModelListed(profile.noTemperatureModels, route.model)) set('temperature', undefined);+ if (profileModelListed(profile.noTopPModels, route.model)) set('top_p', undefined);+ if (profileModelListed(profile.noPenaltyModels, route.model)) {+ set('frequency_penalty', undefined); set('presence_penalty', undefined);+ }+ const noReasoning = profileModelListed(profile.noReasoningModels, route.model);+ if (route.protocol === 'openai-responses') {+ const history = backfillWebSearchQueries(next);+ if (isPlainObject(history)) next = history;+ if (profile.requiresAdjacentResponsesToolResults === true) {+ const adjacent = normalizeResponsesToolResultAdjacency(next);+ if (isPlainObject(adjacent)) next = adjacent;+ }+ if (profile.annotateEmptyToolOutputs === true) {+ const annotated = annotateEmptyResponsesToolOutputs(next, true);+ if (isPlainObject(annotated)) next = annotated;+ }++ if (noReasoning) set('reasoning', undefined);+ if (isPlainObject(next.reasoning)) {+ const reasoning = { ...next.reasoning };+ if (profileModelValue(profile.modelSupportsReasoningSummaries, route.model) === false) delete reasoning.summary;+ const wire = profileModelValue(profile.modelWireDefaults, route.model);+ if ((profile.adapter === 'openai-responses' || (isPlainObject(wire) && wire.wire === 'openai-responses')) && typeof reasoning.effort === 'string') {+ const mapped = mapReasoningEffort(profile as unknown as OcxProviderConfig, route.model, reasoning.effort);+ if (mapped !== undefined) reasoning.effort = mapped;+ }+ if (JSON.stringify(reasoning) !== JSON.stringify(next.reasoning)) set('reasoning', Object.keys(reasoning).length ? reasoning : undefined);+ }+ if (profile.statelessResponses === true) {+ set('store', false);+ // A continuation id without expanded history cannot be silently discarded.+ if (typeof next.previous_response_id === 'string') throw new Error('stateless provider requires expanded Responses continuation history');+ }+ const verbosity = profileModelValue(profile.modelSupportsVerbosity, route.model) ?? profile.supportsVerbosity;+ if (verbosity === false && isPlainObject(next.text) && Object.hasOwn(next.text, 'verbosity')) {+ const text = { ...next.text }; delete text.verbosity; set('text', Object.keys(text).length ? text : undefined);+ }+ } else if (route.protocol === 'openai-chat') {+ if (profile.modelSuffixBracketStrip === true && typeof next.model === 'string') set('model', stripBracketedModelSuffix(next.model));+ if (profileModelListed(profile.reasoningSplitModels, route.model)) set('reasoning_split', true);+ if (noReasoning) set('reasoning_effort', undefined);+ const originalEffort = typeof next.reasoning_effort === 'string' ? next.reasoning_effort : undefined;+ const omitWithTools = Array.isArray(next.tools) && next.tools.length > 0 && profileModelListed(profile.omitReasoningEffortWithToolsModels, route.model);+ const wireMap = profileModelValue(profile.modelReasoningEffortMap, route.model) ?? profile.reasoningEffortMap;+ const mapped = mapReasoningEffort(profile as unknown as OcxProviderConfig, route.model, originalEffort);+ const explicitOmission = originalEffort !== undefined && isPlainObject(wireMap)+ && wireMap[originalEffort === 'ultra' ? 'max' : originalEffort] === REASONING_EFFORT_OMIT_SENTINEL;+ const effort = omitWithTools ? undefined : options.reasoningEffortAlreadyMapped ? originalEffort+ : explicitOmission ? undefined : mapped ?? originalEffort;+ if (effort === undefined && originalEffort !== undefined) set('reasoning_effort', undefined);+ if (!noReasoning && !omitWithTools && originalEffort === 'none' && profile.reasoningWireFormat === 'gateway-object') {+ set('reasoning', { enabled: false });+ } else if (effort !== undefined) {+ if (profile.reasoningWireFormat === 'gateway-object') {+ set('reasoning', effort === 'none' ? { enabled: false } : { enabled: true, effort });+ set('reasoning_effort', undefined);+ } else if (profileModelListed(profile.thinkingBudgetModels, route.model)) {+ const budget = thinkingBudgetForEffort({ options: { reasoning: originalEffort } }, effort, typeof next.max_tokens === 'number' ? next.max_tokens : undefined);+ if (budget !== undefined) { set('thinking_budget', budget); set('reasoning_effort', undefined); }+ } else if (profileModelListed(profile.thinkingToggleModels, route.model)) {+ if (['enabled', 'disabled', 'adaptive'].includes(effort)) { set('thinking', { type: effort }); set('reasoning_effort', undefined); }+ } else set('reasoning_effort', effort);+ }+ if (profileModelListed(profile.reasoningDetailsModels, route.model) && Array.isArray(next.messages)) {+ const messages = next.messages.map(message => {+ if (!isPlainObject(message) || message.role !== 'assistant' || typeof message.reasoning_content !== 'string' || message.reasoning_details !== undefined) return message;+ const result: Record<string, unknown> = { ...message, reasoning_details: [reasoningDetailSegmentForWire(message.reasoning_content)] };+ delete result.reasoning_content;+ return result;+ });+ if (messages.some((message, index) => message !== (next.messages as unknown[])[index])) set('messages', messages);+ }+ }+ }+ if (route.protocol !== 'openai-responses') return next;+ const normalized = normalizeXaiResponsesWebSearch(next, { baseUrl: route.upstreamBase });+ if (isPlainObject(normalized)) next = normalized;+ const promoted = normalizeOpenCodeGoAdditionalTools(next, route.upstreamBase.replace(/\/+$/, '') + '/responses');+ if (isPlainObject(promoted)) next = promoted;+ if (isXaiSchemaTarget({ baseUrl: route.upstreamBase })) {+ const rewriteTools = (tools: unknown[]): unknown[] => tools.map(tool => {+ if (!isPlainObject(tool) || tool.type !== 'function' || !Object.hasOwn(tool, 'parameters')) return tool;+ const parameters = normalizeXaiToolParameters(stripResponsesOnlyEncryptedMarker(tool.parameters));+ if (parameters === undefined) throw new Error('xAI subscription cannot represent this function tool schema');+ return { ...tool, parameters };+ });+ if (Array.isArray(next.tools)) next = { ...next, tools: rewriteTools(next.tools) };+ if (Array.isArray(next.input)) next = { ...next, input: next.input.map(item =>+ isPlainObject(item) && item.type === 'additional_tools' && Array.isArray(item.tools)+ ? { ...item, tools: rewriteTools(item.tools) } : item) };+ }+ return next;+}diff --git a/packages/model-compat/src/responses.ts b/packages/model-compat/src/responses.tsnew file mode 100644index 0000000000..bd68aa9275--- /dev/null+++ b/packages/model-compat/src/responses.ts@@ -0,0 +1,161 @@+import { stripCanonicalOnlyToolFields } from './upstream/adapters/openai-responses';+import type { ResponsesItemIdRepairConfig } from './upstream/types/provider';+import { createResponsesItemIdPayloadRewrite, repairResponsesJsonItemIds } from './upstream/server/responses-item-id-repair';+import { createResponsesSnapshotBlockRewrite, repairResponsesSnapshotJson } from './upstream/server/responses-snapshot-repair';+import { createReasoningSummaryChannelPayloadRewrite, rewriteReasoningSummaryInJsonString } from './upstream/server/responses-reasoning-summary-rewrite';+import { collectSelfNamedNamespaceScrubAuthorization, createSelfNamedToolCallNamespaceScrubRewrite, scrubSelfNamedToolCallNamespaceInJson } from './upstream/server/responses-self-named-namespace-scrub';+import { Transform, type TransformCallback } from 'node:stream';+import { StringDecoder } from 'node:string_decoder';+import { rewriteRoutedCustomToolsForUpstream, restoreRoutedCustomCallsInJson } from './upstream/responses/custom-tool-compat';+import { rewriteRoutedNamespaceToolsForUpstream, restoreRoutedNamespaceCallsInJson } from './upstream/responses/namespace-tool-compat';+import { rewriteRoutedToolSearchForUpstream, restoreRoutedToolSearchCallsInJson } from './upstream/responses/tool-search-compat';+import { collectFunctionCallRepairSchemas, repairFunctionCallsInJson } from './upstream/responses/function-call-compat';+import { createRoutedCustomToolRestoreBlockRewrite } from './upstream/server/responses-custom-tool-repair';+import { createRoutedToolSearchRestoreBlockRewrite } from './upstream/server/responses-tool-search-repair';+import { createResponsesFunctionToolRepairBlockRewrite } from './upstream/server/responses-function-tool-repair';+import { createResponsesFieldBackfillBlockRewrite, backfillResponsesFieldsJson } from './upstream/server/responses/responses-field-backfill';+import { createTranslatorBudget } from './upstream/lib/translator-budget';+import { collectDeclaredWireToolNames } from './upstream/server/responses-undeclared-tool-guard';+import { composeSseBlockRewrites, payloadRewriteAsBlockRewrite, nextSseBlock, type SseBlockRewrite } from './upstream/server/sse-payload-rewrite';++/** Selected from the actual route; native OpenAI and non-Responses traffic do not enter this adapter. */+export interface ResponsesCompatibilityPolicy {+ customTools?: 'native' | 'functions' | 'preserve-apply-patch';+ namespaceTools?: 'native' | 'functions';+ toolSearch?: 'native' | 'function';+ repairFunctionArguments?: boolean;+ backfillResponseFields?: boolean;+ itemIdRepair?: ResponsesItemIdRepairConfig;+ snapshotRepair?: boolean;+ contentChannelReasoning?: boolean;+}++/** One request owns both forward conversion and reverse tool identities. */+export function prepareResponsesCompatibility(body: unknown, policy: ResponsesCompatibilityPolicy) {+ const custom = policy.customTools && policy.customTools !== 'native'+ ? rewriteRoutedCustomToolsForUpstream(body, policy.customTools === 'functions' ? false : undefined)+ : { body, names: new Set<string>(), repairNames: new Set<string>() };+ const search = policy.toolSearch === 'function'+ ? rewriteRoutedToolSearchForUpstream(custom.body)+ : { body: custom.body, names: new Set<string>() };+ const namespace = policy.namespaceTools === 'functions'+ ? rewriteRoutedNamespaceToolsForUpstream(search.body, custom.names)+ : { body: search.body, aliases: new Map() };+ const schemas = policy.repairFunctionArguments ? collectFunctionCallRepairSchemas(body) : new Map();+ const declared = collectDeclaredWireToolNames(body);+ const scrubAuthorization = collectSelfNamedNamespaceScrubAuthorization(body, new Set([...custom.names, ...custom.repairNames]), new Set(schemas.keys()));+ const restoreNamespace = (text: string) => restoreRoutedNamespaceCallsInJson(text, namespace.aliases);+ return {+ body: policy.namespaceTools === 'functions' ? stripCanonicalOnlyToolFields(namespace.body, false) : namespace.body,+ needsResponseTransform: Boolean(policy.itemIdRepair || policy.snapshotRepair || policy.contentChannelReasoning) || custom.names.size > 0 || custom.repairNames.size > 0 || search.names.size > 0 || namespace.aliases.size > 0 || schemas.size > 0 || policy.backfillResponseFields === true,+ restoreJson(text: string): string {+ let next = restoreNamespace(scrubSelfNamedToolCallNamespaceInJson(text, scrubAuthorization));+ if (policy.itemIdRepair) {+ const parsed: unknown = JSON.parse(next);+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) next = JSON.stringify(repairResponsesJsonItemIds(parsed as Record<string, unknown>, policy.itemIdRepair));+ }+ if (policy.snapshotRepair) next = repairResponsesSnapshotJson(next, body);+ if (policy.contentChannelReasoning) next = rewriteReasoningSummaryInJsonString(next);+ next = restoreRoutedCustomCallsInJson(next, custom.names, custom.repairNames, declared);+ next = restoreRoutedToolSearchCallsInJson(next, search.names);+ next = repairFunctionCallsInJson(next, schemas);+ return policy.backfillResponseFields ? backfillResponsesFieldsJson(next) : next;+ },+ createStreamRewrite() {+ const budget = createTranslatorBudget();+ const stages: SseBlockRewrite[] = [+ payloadRewriteAsBlockRewrite(createSelfNamedToolCallNamespaceScrubRewrite(scrubAuthorization)),+ payloadRewriteAsBlockRewrite(restoreNamespace),+ createRoutedCustomToolRestoreBlockRewrite(custom.names, budget, custom.repairNames, declared),+ createRoutedToolSearchRestoreBlockRewrite(search.names, budget),+ createResponsesFunctionToolRepairBlockRewrite(schemas, budget),+ ];+ // Transport/id reconstruction precedes tool completion; all stages share one budget.+ const before: SseBlockRewrite[] = [];+ if (policy.itemIdRepair) before.push(payloadRewriteAsBlockRewrite(createResponsesItemIdPayloadRewrite(policy.itemIdRepair, budget)));+ if (policy.snapshotRepair) before.push(createResponsesSnapshotBlockRewrite(body, budget));+ if (policy.contentChannelReasoning) before.push(payloadRewriteAsBlockRewrite(createReasoningSummaryChannelPayloadRewrite()));+ stages.unshift(...before);+ if (policy.backfillResponseFields) stages.push(createResponsesFieldBackfillBlockRewrite());+ const rewrite = composeSseBlockRewrites(...stages);+ const dispose = rewrite.dispose;+ rewrite.dispose = () => { dispose?.(); budget.dispose(); };+ return rewrite;+ },+ };+}++type Prepared = ReturnType<typeof prepareResponsesCompatibility>;+const MAX_RESPONSE_BYTES = 32 * 1024 * 1024;++/** Node transport shell only; the vendored upstream owns protocol rewrites and bounded collectors. */+class CompatibilityResponseTransform extends Transform {+ private readonly decoder = new StringDecoder('utf8');+ private buffer = '';+ private readonly rewrite: SseBlockRewrite | undefined;+ constructor(private readonly prepared: Prepared, private readonly sse: boolean) {+ super();+ if (sse) this.rewrite = prepared.createStreamRewrite();+ }+ private drain(final = false): void {+ if (this.sse) {+ let frame;+ while ((frame = nextSseBlock(this.buffer))) {+ if (Buffer.byteLength(frame.block) > MAX_RESPONSE_BYTES) throw new Error('model compatibility response buffer exceeded');+ this.buffer = frame.rest;+ for (const block of this.rewrite!(frame.block)) this.push(block + frame.delimiter);+ }+ if (final && this.buffer) {+ if (Buffer.byteLength(this.buffer) > MAX_RESPONSE_BYTES) throw new Error('model compatibility response buffer exceeded');+ for (const block of this.rewrite!(this.buffer)) this.push(block + '\n\n');+ this.buffer = '';+ }+ } else if (final) {+ if (Buffer.byteLength(this.buffer) > MAX_RESPONSE_BYTES) throw new Error('model compatibility response buffer exceeded');+ this.push(this.prepared.restoreJson(this.buffer));+ this.buffer = '';+ }+ if (Buffer.byteLength(this.buffer) > MAX_RESPONSE_BYTES) throw new Error('model compatibility response buffer exceeded');+ }+ override _transform(chunk: Buffer, _encoding: BufferEncoding, callback: TransformCallback): void {+ try { this.buffer += this.decoder.write(chunk); this.drain(); callback(); }+ catch (error) { callback(error as Error); }+ }+ override _flush(callback: TransformCallback): void {+ try { this.buffer += this.decoder.end(); this.drain(true); callback(); }+ catch (error) { callback(error as Error); }+ }+ override _destroy(error: Error | null, callback: (error?: Error | null) => void): void {+ this.buffer = '';+ this.rewrite?.dispose?.();+ callback(error);+ }+}++/** Retains only in-flight reverse mappings; callers release on every settled request, including errors. */+export function createResponsesCompatibilityAdapter(policy: ResponsesCompatibilityPolicy) {+ const pending = new Map<number, { prepared: Prepared; at: number }>();+ return {+ adaptRequest(body: unknown, requestId: number, overrides: ResponsesCompatibilityPolicy = {}): unknown | null {+ pending.delete(requestId);+ const now = Date.now();+ for (const [id, entry] of pending) if (now - entry.at >= 15 * 60_000) pending.delete(id);+ if (!pending.has(requestId) && pending.size >= 256) throw new Error('too many in-flight compatibility requests');+ const prepared = prepareResponsesCompatibility(body, { ...policy, ...overrides });+ if (prepared.needsResponseTransform) pending.set(requestId, { prepared, at: now });+ return prepared.body === body ? null : prepared.body;+ },+ releaseResponse(requestId: number): void { pending.delete(requestId); },+ createResponseTransform(requestId: number, response: { contentType: string; contentEncoding: string }): Transform | null {+ const entry = pending.get(requestId);+ pending.delete(requestId);+ if (!entry) return null;+ const encoding = response.contentEncoding.trim().toLowerCase();+ if (encoding && encoding !== 'identity') throw new Error('compressed compatibility response cannot be rewritten');+ const type = response.contentType.toLowerCase();+ const sse = type.startsWith('text/event-stream');+ if (!sse && !type.includes('application/json')) throw new Error('unsupported compatibility response content type');+ return new CompatibilityResponseTransform(entry.prepared, sse);+ },+ };+}diff --git a/packages/model-compat/src/upstream-profiles.json b/packages/model-compat/src/upstream-profiles.jsonnew file mode 100644index 0000000000..96a3059b9c--- /dev/null+++ b/packages/model-compat/src/upstream-profiles.json@@ -0,0 +1,1565 @@+[+ {+ "id": "openai",+ "adapter": "openai-responses",+ "baseUrl": "https://chatgpt.com/backend-api/codex",+ "authKind": "forward"+ },+ {+ "id": "cursor",+ "adapter": "cursor",+ "baseUrl": "https://api2.cursor.sh",+ "authKind": "oauth"+ },+ {+ "id": "xai",+ "adapter": "openai-chat",+ "baseUrl": "https://api.x.ai/v1",+ "authKind": "oauth",+ "supportsOpenAiWebSearchToolFields": false,+ "supportsResponsesCustomTools": false,+ "parallelToolCalls": true,+ "modelSupportsVerbosity": {+ "grok-4.6": false,+ "grok-4.5": false,+ "grok-4.3": false,+ "grok-4.20-multi-agent-0309": false,+ "grok-4.20-0309-reasoning": false,+ "grok-4.20-0309-non-reasoning": false,+ "grok-build-0.1": false,+ "grok-composer-2.5-fast": false+ },+ "supportsVerbosity": false,+ "modelWireDefaults": {+ "grok-4.6": {+ "wire": "openai-responses",+ "inbound": [+ "responses"+ ],+ "authModes": [+ "oauth"+ ],+ "forwardCallerServiceTier": false+ },+ "grok-4.5": {+ "wire": "openai-responses",+ "inbound": [+ "responses"+ ],+ "authModes": [+ "oauth"+ ],+ "forwardCallerServiceTier": false+ },+ "grok-4.20-multi-agent-0309": {+ "wire": "openai-responses",+ "inbound": [+ "responses",+ "chat",+ "anthropic"+ ],+ "forwardCallerServiceTier": false+ }+ },+ "noReasoningModels": [+ "grok-4.20-0309-non-reasoning",+ "grok-build-0.1",+ "grok-composer-2.5-fast"+ ],+ "preserveReasoningContentModels": [+ "grok-4.6",+ "grok-4.5",+ "grok-4.3",+ "grok-4.20-0309-reasoning"+ ]+ },+ {+ "id": "command-code",+ "adapter": "command-code",+ "baseUrl": "https://api.commandcode.ai",+ "authKind": "oauth",+ "parallelToolCalls": false+ },+ {+ "id": "orcarouter-oauth",+ "adapter": "openai-chat",+ "baseUrl": "https://api.orcarouter.ai/v1",+ "authKind": "oauth",+ "modelReasoningEffortMap": {+ "deepseek/deepseek-v4-pro": {+ "low": "low",+ "medium": "high",+ "high": "high",+ "xhigh": "high",+ "max": "max"+ }+ },+ "preserveReasoningContentModels": [+ "deepseek/deepseek-v4-pro"+ ]+ },+ {+ "id": "anthropic",+ "adapter": "anthropic",+ "baseUrl": "https://api.anthropic.com",+ "authKind": "oauth"+ },+ {+ "id": "anthropic-apikey",+ "adapter": "anthropic",+ "baseUrl": "https://api.anthropic.com",+ "authKind": "key"+ },+ {+ "id": "kimi",+ "adapter": "openai-chat",+ "baseUrl": "https://api.kimi.com/coding/v1",+ "authKind": "oauth",+ "modelSuffixBracketStrip": true,+ "promptCacheKey": true,+ "noReasoningModels": [+ "k3",+ "k3[1m]",+ "kimi-k2.7-code",+ "kimi-k2.7-code-highspeed",+ "kimi-k2.6",+ "kimi-k2.5",+ "kimi-for-coding"+ ],+ "modelReasoningEffortMap": {+ "k3": {+ "none": "none",+ "low": "low",+ "medium": "high",+ "high": "high",+ "xhigh": "max",+ "max": "max"+ },+ "k3[1m]": {+ "none": "none",+ "low": "low",+ "medium": "high",+ "high": "high",+ "xhigh": "max",+ "max": "max"+ }+ },+ "noTemperatureModels": [+ "k3",+ "k3[1m]",+ "kimi-k2.7-code",+ "kimi-k2.7-code-highspeed",+ "kimi-k2.6",+ "kimi-k2.5",+ "kimi-for-coding"+ ],+ "noTopPModels": [+ "k3",+ "k3[1m]",+ "kimi-k2.7-code",+ "kimi-k2.7-code-highspeed",+ "kimi-k2.6",+ "kimi-k2.5",+ "kimi-for-coding"+ ],+ "noPenaltyModels": [+ "k3",+ "k3[1m]",+ "kimi-k2.7-code",+ "kimi-k2.7-code-highspeed",+ "kimi-k2.6",+ "kimi-k2.5",+ "kimi-for-coding"+ ],+ "autoToolChoiceOnlyModels": [+ "kimi-k2.7-code",+ "kimi-k2.7-code-highspeed",+ "kimi-for-coding"+ ],+ "preserveReasoningContentModels": [+ "k3",+ "k3[1m]",+ "kimi-k2.7-code",+ "kimi-k2.7-code-highspeed",+ "kimi-k2.6",+ "kimi-k2.5",+ "kimi-for-coding"+ ]+ },+ {+ "id": "kiro",+ "adapter": "kiro",+ "baseUrl": "https://runtime.us-east-1.kiro.dev",+ "authKind": "oauth",+ "modelSupportsVerbosity": {+ "kiro-auto": false,+ "gpt-5.6-sol": false,+ "gpt-5.6-terra": false,+ "gpt-5.6-luna": false,+ "claude-sonnet-5": false,+ "claude-opus-5": false,+ "claude-opus-4.8": false,+ "claude-opus-4.7": false,+ "claude-opus-4.6": false,+ "claude-opus-4.5": false,+ "claude-sonnet-4.6": false,+ "claude-sonnet-4.5": false,+ "claude-sonnet-4.0": false,+ "claude-haiku-4.5": false,+ "deepseek-3.2": false,+ "minimax-m2.5": false,+ "minimax-m2.1": false,+ "glm-5": false,+ "qwen3-coder-next": false+ }+ },+ {+ "id": "nous",+ "adapter": "openai-chat",+ "baseUrl": "https://inference-api.nousresearch.com/v1",+ "authKind": "oauth"+ },+ {+ "id": "openai-apikey",+ "adapter": "openai-responses",+ "baseUrl": "https://api.openai.com/v1",+ "authKind": "key"+ },+ {+ "id": "meta-model",+ "adapter": "openai-responses",+ "baseUrl": "https://api.meta.ai/v1",+ "authKind": "key",+ "modelReasoningEffortMap": {+ "muse-spark-1.3": {+ "minimal": "minimal",+ "low": "low",+ "medium": "medium",+ "high": "high",+ "xhigh": "xhigh"+ },+ "muse-spark-1.3-contributor": {+ "minimal": "minimal",+ "low": "low",+ "medium": "medium",+ "high": "high",+ "xhigh": "xhigh"+ }+ }+ },+ {+ "id": "meta-muse",+ "adapter": "openai-responses",+ "baseUrl": "https://api.meta.ai/v1",+ "authKind": "oauth",+ "modelReasoningEffortMap": {+ "muse-spark-1.3": {+ "minimal": "minimal",+ "low": "low",+ "medium": "medium",+ "high": "high",+ "xhigh": "xhigh"+ },+ "muse-spark-1.3-contributor": {+ "minimal": "minimal",+ "low": "low",+ "medium": "medium",+ "high": "high",+ "xhigh": "xhigh"+ }+ }+ },+ {+ "id": "umans",+ "adapter": "anthropic",+ "baseUrl": "https://api.code.umans.ai",+ "authKind": "key",+ "escapeBuiltinToolNames": true+ },+ {+ "id": "opencode-go",+ "adapter": "openai-chat",+ "baseUrl": "https://opencode.ai/zen/go/v1",+ "authKind": "key",+ "openaiChatEofTolerance": true,+ "statelessResponses": true,+ "modelWireDefaults": {+ "gpt-5.6-luna": "openai-responses",+ "grok-4.6": "openai-responses",+ "muse-spark-1.3-contributor": "openai-responses",+ "muse-spark-1.2-contributor": "openai-responses"+ },+ "modelReasoningEffortMap": {+ "kimi-k3": {+ "none": "none",+ "low": "low",+ "medium": "high",+ "high": "high",+ "xhigh": "max",+ "max": "max"+ },+ "mimo-v2.5": {+ "none": "disabled",+ "minimal": "disabled",+ "low": "disabled",+ "medium": "enabled",+ "high": "enabled",+ "xhigh": "enabled",+ "max": "enabled"+ },+ "mimo-v2.5-pro": {+ "none": "disabled",+ "minimal": "disabled",+ "low": "disabled",+ "medium": "enabled",+ "high": "enabled",+ "xhigh": "enabled",+ "max": "enabled"+ },+ "glm-5": {+ "none": "disabled",+ "minimal": "disabled",+ "low": "disabled",+ "medium": "enabled",+ "high": "enabled",+ "xhigh": "enabled",+ "max": "enabled"+ },+ "glm-5.1": {+ "none": "disabled",+ "minimal": "disabled",+ "low": "disabled",+ "medium": "enabled",+ "high": "enabled",+ "xhigh": "enabled",+ "max": "enabled"+ },+ "deepseek-v4-pro": {+ "low": "low",+ "medium": "high",+ "high": "high",+ "xhigh": "high",+ "max": "max"+ },+ "deepseek-v4-flash": {+ "low": "low",+ "medium": "high",+ "high": "high",+ "xhigh": "high",+ "max": "max"+ }+ },+ "modelSupportsReasoningSummaries": {+ "glm-5.3": true,+ "glm-5.3-flash": true,+ "glm-5.2": true,+ "glm-5.1": true,+ "glm-5": true,+ "deepseek-v4-pro": true,+ "deepseek-v4-flash": true+ },+ "thinkingToggleModels": [+ "mimo-v2.5",+ "mimo-v2.5-pro",+ "glm-5",+ "glm-5.1"+ ],+ "thinkingBudgetModels": [+ "qwen3.5-397b",+ "qwen3.6-35b",+ "qwen3.5-plus",+ "qwen3.6-plus",+ "qwen3.7-max",+ "qwen3.7-plus"+ ],+ "noReasoningModels": [+ "kimi-k2.7-code",+ "kimi-k2.7-code-highspeed"+ ],+ "noTemperatureModels": [+ "kimi-k3",+ "kimi-k2.7-code",+ "kimi-k2.7-code-highspeed"+ ],+ "noTopPModels": [+ "kimi-k3",+ "kimi-k2.7-code",+ "kimi-k2.7-code-highspeed"+ ],+ "noPenaltyModels": [+ "kimi-k3",+ "kimi-k2.7-code",+ "kimi-k2.7-code-highspeed"+ ],+ "autoToolChoiceOnlyModels": [+ "kimi-k2.7-code",+ "kimi-k2.7-code-highspeed"+ ],+ "preserveReasoningContentModels": [+ "glm-5.3",+ "glm-5.3-flash",+ "glm-5.2",+ "kimi-k3",+ "kimi-k2.7-code",+ "kimi-k2.7-code-highspeed",+ "deepseek-v4-pro",+ "deepseek-v4-flash"+ ]+ },+ {+ "id": "neuralwatt",+ "adapter": "openai-chat",+ "baseUrl": "https://api.neuralwatt.com/v1",+ "authKind": "key",+ "thinkingBudgetModels": [+ "qwen3.5-397b",+ "qwen3.6-35b",+ "qwen3.5-plus",+ "qwen3.6-plus",+ "qwen3.7-max",+ "qwen3.7-plus"+ ],+ "noReasoningModels": [+ "glm-5.3-fast",+ "glm-5.3-short-fast",+ "glm-5.2-fast",+ "glm-5.2-short-fast",+ "kimi-k2.6-fast",+ "qwen3.5-397b-fast",+ "qwen3.6-35b-fast"+ ],+ "noTemperatureModels": [+ "kimi-k2.7-code"+ ],+ "noTopPModels": [+ "kimi-k2.7-code"+ ],+ "noPenaltyModels": [+ "kimi-k2.7-code"+ ],+ "autoToolChoiceOnlyModels": [+ "kimi-k2.7-code"+ ],+ "preserveReasoningContentModels": [+ "glm-5.3",+ "glm-5.3-short",+ "glm-5.3-flash",+ "glm-5.2",+ "glm-5.2-short",+ "kimi-k2.6",+ "kimi-k2.7-code",+ "qwen3.5-397b",+ "qwen3.6-35b"+ ]+ },+ {+ "id": "openrouter",+ "adapter": "openai-chat",+ "baseUrl": "https://openrouter.ai/api/v1",+ "authKind": "key"+ },+ {+ "id": "cline-pass",+ "adapter": "openai-chat",+ "baseUrl": "https://api.cline.bot/api/v1",+ "authKind": "key",+ "reasoningWireFormat": "gateway-object"+ },+ {+ "id": "cline",+ "adapter": "openai-chat",+ "baseUrl": "https://api.cline.bot/api/v1",+ "authKind": "key"+ },+ {+ "id": "orcarouter",+ "adapter": "openai-chat",+ "baseUrl": "https://api.orcarouter.ai/v1",+ "authKind": "key",+ "modelReasoningEffortMap": {+ "deepseek/deepseek-v4-pro": {+ "low": "low",+ "medium": "high",+ "high": "high",+ "xhigh": "high",+ "max": "max"+ }+ },+ "preserveReasoningContentModels": [+ "deepseek/deepseek-v4-pro"+ ]+ },+ {+ "id": "packycode",+ "adapter": "openai-chat",+ "baseUrl": "https://cf.api.fan/v1",+ "authKind": "key"+ },+ {+ "id": "bizrouter",+ "adapter": "openai-chat",+ "baseUrl": "https://api.bizrouter.ai/v1",+ "authKind": "key"+ },+ {+ "id": "groq",+ "adapter": "openai-chat",+ "baseUrl": "https://api.groq.com/openai/v1",+ "authKind": "key"+ },+ {+ "id": "google",+ "adapter": "google",+ "baseUrl": "https://generativelanguage.googleapis.com",+ "authKind": "key"+ },+ {+ "id": "google-vertex",+ "adapter": "google",+ "baseUrl": "https://aiplatform.googleapis.com",+ "authKind": "key",+ "googleMode": "vertex"+ },+ {+ "id": "google-antigravity",+ "adapter": "google",+ "baseUrl": "https://daily-cloudcode-pa.googleapis.com",+ "authKind": "oauth",+ "googleMode": "cloud-code-assist"+ },+ {+ "id": "azure-openai",+ "adapter": "azure-openai",+ "baseUrl": "https://{resource}.openai.azure.com/openai",+ "authKind": "key"+ },+ {+ "id": "ollama",+ "adapter": "openai-chat",+ "baseUrl": "http://localhost:11434/v1",+ "authKind": "local"+ },+ {+ "id": "vllm",+ "adapter": "openai-chat",+ "baseUrl": "http://localhost:8000/v1",+ "authKind": "local"+ },+ {+ "id": "lm-studio",+ "adapter": "openai-chat",+ "baseUrl": "http://localhost:1234/v1",+ "authKind": "local"+ },+ {+ "id": "deepseek",+ "baseUrl": "https://api.deepseek.com",+ "adapter": "openai-chat",+ "authKind": "key",+ "modelWireDefaults": {+ "deepseek-v4-flash": {+ "wire": "openai-responses",+ "inbound": [+ "responses"+ ]+ },+ "deepseek-v4-pro": {+ "wire": "openai-responses",+ "inbound": [+ "responses"+ ]+ }+ },+ "modelResponsesTerminalRepair": {+ "deepseek-v4-flash": {+ "graceMs": 5000+ },+ "deepseek-v4-pro": {+ "graceMs": 5000+ }+ },+ "responsesItemIdRepair": {+ "repairInvalidIds": true,+ "repairMissingTerminalIds": true+ },+ "responsesPath": "/responses",+ "preserveResponsesReasoningContent": true,+ "statelessResponses": true,+ "requiresAdjacentResponsesToolResults": true,+ "annotateEmptyToolOutputs": true,+ "modelReasoningEffortMap": {+ "deepseek-v4-pro": {+ "low": "low",+ "medium": "high",+ "high": "high",+ "xhigh": "high",+ "max": "max"+ },+ "deepseek-v4-flash": {+ "low": "low",+ "medium": "high",+ "high": "high",+ "xhigh": "high",+ "max": "max"+ }+ },+ "modelSupportsReasoningSummaries": {+ "deepseek-v4-pro": true,+ "deepseek-v4-flash": true+ },+ "preserveReasoningContentModels": [+ "deepseek-v4-pro",+ "deepseek-v4-flash"+ ]+ },+ {+ "id": "cerebras",+ "baseUrl": "https://api.cerebras.ai/v1",+ "adapter": "openai-chat",+ "authKind": "key"+ },+ {+ "id": "chutes",+ "baseUrl": "https://llm.chutes.ai/v1",+ "adapter": "openai-chat",+ "authKind": "key",+ "parallelToolCalls": false+ },+ {+ "id": "deepinfra",+ "baseUrl": "https://api.deepinfra.com/v1/openai",+ "adapter": "openai-chat",+ "authKind": "key"+ },+ {+ "id": "hyperbolic",+ "baseUrl": "https://api.hyperbolic.xyz/v1",+ "adapter": "openai-chat",+ "authKind": "key"+ },+ {+ "id": "nscale",+ "baseUrl": "https://inference.api.nscale.com/v1",+ "adapter": "openai-chat",+ "authKind": "key",+ "parallelToolCalls": false+ },+ {+ "id": "vultr",+ "baseUrl": "https://api.vultrinference.com/v1",+ "adapter": "openai-chat",+ "authKind": "key",+ "parallelToolCalls": false+ },+ {+ "id": "baseten",+ "baseUrl": "https://inference.baseten.co/v1",+ "adapter": "openai-chat",+ "authKind": "key",+ "parallelToolCalls": true,+ "modelReasoningEffortMap": {+ "deepseek-ai/DeepSeek-V4-Pro": {+ "none": "none",+ "minimal": "minimal"+ },+ "thinkingmachines/inkling": {+ "none": "none",+ "minimal": "minimal"+ },+ "openai/gpt-oss-120b": {+ "none": "none",+ "minimal": "minimal"+ },+ "moonshotai/Kimi-K3": {+ "none": "none"+ },+ "zai-org/GLM-5.3": {+ "none": "none"+ },+ "zai-org/GLM-5.3-Fast": {+ "none": "none"+ },+ "zai-org/GLM-5.2": {+ "none": "none"+ },+ "zai-org/GLM-5.2-Fast": {+ "none": "none"+ }+ }+ },+ {+ "id": "commandcode",+ "adapter": "openai-chat",+ "baseUrl": "https://api.commandcode.ai/provider/v1",+ "authKind": "key",+ "promptCacheKey": true+ },+ {+ "id": "sambanova",+ "baseUrl": "https://api.sambanova.ai/v1",+ "adapter": "openai-chat",+ "authKind": "key",+ "parallelToolCalls": false+ },+ {+ "id": "nebius",+ "baseUrl": "https://api.tokenfactory.nebius.com/v1",+ "adapter": "openai-chat",+ "authKind": "key",+ "parallelToolCalls": false+ },+ {+ "id": "digitalocean",+ "baseUrl": "https://inference.do-ai.run/v1",+ "adapter": "openai-chat",+ "authKind": "key",+ "parallelToolCalls": false+ },+ {+ "id": "scaleway",+ "baseUrl": "https://api.scaleway.ai/v1",+ "adapter": "openai-chat",+ "authKind": "key",+ "parallelToolCalls": false+ },+ {+ "id": "featherless",+ "baseUrl": "https://api.featherless.ai/v1",+ "adapter": "openai-chat",+ "authKind": "key",+ "parallelToolCalls": false+ },+ {+ "id": "novita",+ "baseUrl": "https://api.novita.ai/openai/v1",+ "adapter": "openai-chat",+ "authKind": "key",+ "parallelToolCalls": false+ },+ {+ "id": "together",+ "baseUrl": "https://api.together.xyz/v1",+ "adapter": "openai-chat",+ "authKind": "key"+ },+ {+ "id": "fireworks",+ "baseUrl": "https://api.fireworks.ai/inference/v1",+ "adapter": "openai-chat",+ "authKind": "key"+ },+ {+ "id": "firepass",+ "baseUrl": "https://api.fireworks.ai/inference/v1",+ "adapter": "openai-chat",+ "authKind": "key"+ },+ {+ "id": "moonshot",+ "baseUrl": "https://api.moonshot.ai/v1",+ "adapter": "openai-chat",+ "authKind": "key",+ "noReasoningModels": [+ "kimi-k2.7-code",+ "kimi-k2.7-code-highspeed",+ "kimi-k2.6",+ "kimi-k2.5"+ ],+ "noTemperatureModels": [+ "kimi-k3",+ "kimi-k2.7-code",+ "kimi-k2.7-code-highspeed",+ "kimi-k2.6",+ "kimi-k2.5"+ ],+ "noTopPModels": [+ "kimi-k3",+ "kimi-k2.7-code",+ "kimi-k2.7-code-highspeed",+ "kimi-k2.6",+ "kimi-k2.5"+ ],+ "noPenaltyModels": [+ "kimi-k3",+ "kimi-k2.7-code",+ "kimi-k2.7-code-highspeed",+ "kimi-k2.6",+ "kimi-k2.5"+ ],+ "autoToolChoiceOnlyModels": [+ "kimi-k2.7-code",+ "kimi-k2.7-code-highspeed"+ ],+ "preserveReasoningContentModels": [+ "kimi-k3",+ "kimi-k2.7-code",+ "kimi-k2.7-code-highspeed",+ "kimi-k2.6",+ "kimi-k2.5"+ ]+ },+ {+ "id": "huggingface",+ "baseUrl": "https://router.huggingface.co/v1",+ "adapter": "openai-chat",+ "authKind": "key"+ },+ {+ "id": "nvidia",+ "baseUrl": "https://integrate.api.nvidia.com/v1",+ "adapter": "openai-chat",+ "authKind": "key",+ "parallelToolCalls": false,+ "noReasoningModels": [+ "moonshotai/kimi-k2.6",+ "moonshotai/kimi-k2.5",+ "moonshotai/kimi-k2-thinking",+ "moonshotai/kimi-k2-instruct",+ "moonshotai/kimi-k2-instruct-0905"+ ],+ "preserveReasoningContentModels": [+ "moonshotai/kimi-k2.6",+ "moonshotai/kimi-k2.5",+ "moonshotai/kimi-k2-thinking"+ ]+ },+ {+ "id": "venice",+ "baseUrl": "https://api.venice.ai/api/v1",+ "adapter": "openai-chat",+ "authKind": "key"+ },+ {+ "id": "zai",+ "baseUrl": "https://api.z.ai/api/coding/paas/v4",+ "adapter": "openai-chat",+ "authKind": "key",+ "modelSuffixBracketStrip": true,+ "modelSupportsReasoningSummaries": {+ "glm-5.3": true,+ "glm-5.3[1m]": true,+ "glm-5.3-flash": true,+ "glm-5.2": true,+ "glm-5.2[1m]": true+ },+ "preserveReasoningContentModels": [+ "glm-5.3",+ "glm-5.3[1m]",+ "glm-5.3-flash",+ "glm-5.2",+ "glm-5.2[1m]"+ ]+ },+ {+ "id": "zhipu-bigmodel",+ "baseUrl": "https://open.bigmodel.cn/api/paas/v4",+ "adapter": "openai-chat",+ "authKind": "key",+ "thinkingToggleModels": [+ "glm-4.6",+ "glm-4.7",+ "glm-5",+ "glm-5.1",+ "glm-5.2",+ "glm-5.3",+ "glm-5.3-flash"+ ],+ "modelReasoningEffortMap": {+ "glm-4.6": {+ "none": "disabled",+ "minimal": "disabled",+ "low": "disabled",+ "medium": "enabled",+ "high": "enabled",+ "xhigh": "enabled",+ "max": "enabled"+ },+ "glm-4.7": {+ "none": "disabled",+ "minimal": "disabled",+ "low": "disabled",+ "medium": "enabled",+ "high": "enabled",+ "xhigh": "enabled",+ "max": "enabled"+ },+ "glm-5": {+ "none": "disabled",+ "minimal": "disabled",+ "low": "disabled",+ "medium": "enabled",+ "high": "enabled",+ "xhigh": "enabled",+ "max": "enabled"+ },+ "glm-5.1": {+ "none": "disabled",+ "minimal": "disabled",+ "low": "disabled",+ "medium": "enabled",+ "high": "enabled",+ "xhigh": "enabled",+ "max": "enabled"+ },+ "glm-5.2": {+ "none": "disabled",+ "minimal": "disabled",+ "low": "disabled",+ "medium": "enabled",+ "high": "enabled",+ "xhigh": "enabled",+ "max": "enabled"+ },+ "glm-5.3": {+ "none": "disabled",+ "minimal": "disabled",+ "low": "disabled",+ "medium": "enabled",+ "high": "enabled",+ "xhigh": "enabled",+ "max": "enabled"+ },+ "glm-5.3-flash": {+ "none": "disabled",+ "minimal": "disabled",+ "low": "disabled",+ "medium": "enabled",+ "high": "enabled",+ "xhigh": "enabled",+ "max": "enabled"+ }+ },+ "modelSupportsReasoningSummaries": {+ "glm-4.6": true,+ "glm-4.7": true,+ "glm-5": true,+ "glm-5.1": true,+ "glm-5.2": true,+ "glm-5.3": true,+ "glm-5.3-flash": true+ },+ "preserveReasoningContentModels": [+ "glm-4.6",+ "glm-4.7",+ "glm-5",+ "glm-5.1",+ "glm-5.2",+ "glm-5.3",+ "glm-5.3-flash"+ ],+ "requiresReasoningPlaceholderModels": []+ },+ {+ "id": "zhipu-bigmodel-coding",+ "baseUrl": "https://open.bigmodel.cn/api/coding/paas/v4",+ "adapter": "openai-chat",+ "authKind": "key",+ "modelSuffixBracketStrip": true,+ "modelSupportsReasoningSummaries": {+ "glm-5.3": true,+ "glm-5.3[1m]": true,+ "glm-5.3-flash": true,+ "glm-5.2": true,+ "glm-5.2[1m]": true+ },+ "preserveReasoningContentModels": [+ "glm-5.3",+ "glm-5.3[1m]",+ "glm-5.3-flash",+ "glm-5.2",+ "glm-5.2[1m]"+ ]+ },+ {+ "id": "zhipu-bigmodel-responses",+ "baseUrl": "https://open.bigmodel.cn/api/v1",+ "adapter": "openai-responses",+ "authKind": "key",+ "modelSupportsReasoningSummaries": {+ "glm-5.3": true,+ "glm-5.3-flash": true,+ "glm-5-turbo": true+ },+ "preserveResponsesReasoningContent": true+ },+ {+ "id": "nanogpt",+ "baseUrl": "https://nano-gpt.com/api/v1",+ "adapter": "openai-chat",+ "authKind": "key"+ },+ {+ "id": "synthetic",+ "baseUrl": "https://api.synthetic.new/openai/v1",+ "adapter": "openai-chat",+ "authKind": "key"+ },+ {+ "id": "siliconflow",+ "baseUrl": "https://api.siliconflow.cn/v1",+ "adapter": "openai-chat",+ "authKind": "key"+ },+ {+ "id": "qwen-cloud",+ "baseUrl": "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",+ "adapter": "openai-chat",+ "authKind": "key"+ },+ {+ "id": "tencent-coding-plan",+ "baseUrl": "https://api.lkeap.cloud.tencent.com/coding/v3",+ "adapter": "openai-chat",+ "authKind": "key"+ },+ {+ "id": "volcengine",+ "baseUrl": "https://ark.cn-beijing.volces.com/api/v3",+ "adapter": "openai-chat",+ "authKind": "key",+ "modelReasoningEffortMap": {+ "doubao-seed-2-1-pro-260628": {+ "none": "disabled",+ "minimal": "disabled",+ "low": "disabled",+ "medium": "enabled",+ "high": "enabled",+ "xhigh": "enabled",+ "max": "enabled"+ },+ "doubao-seed-2-1-turbo-260628": {+ "none": "disabled",+ "minimal": "disabled",+ "low": "disabled",+ "medium": "enabled",+ "high": "enabled",+ "xhigh": "enabled",+ "max": "enabled"+ },+ "doubao-seed-evolving": {+ "none": "disabled",+ "minimal": "disabled",+ "low": "disabled",+ "medium": "enabled",+ "high": "enabled",+ "xhigh": "enabled",+ "max": "enabled"+ }+ },+ "thinkingToggleModels": [+ "doubao-seed-2-1-pro-260628",+ "doubao-seed-2-1-turbo-260628",+ "doubao-seed-evolving"+ ],+ "preserveReasoningContentModels": [+ "deepseek-v4-pro-260425",+ "deepseek-v4-flash-260425",+ "glm-5-2-260617",+ "glm-4-7-251222"+ ]+ },+ {+ "id": "volcengine-coding-plan",+ "baseUrl": "https://ark.cn-beijing.volces.com/api/coding/v3",+ "adapter": "openai-chat",+ "authKind": "key",+ "modelReasoningEffortMap": {+ "deepseek-v4-pro": {+ "low": "low",+ "medium": "high",+ "high": "high",+ "xhigh": "high",+ "max": "max"+ },+ "deepseek-v4-flash": {+ "low": "low",+ "medium": "high",+ "high": "high",+ "xhigh": "high",+ "max": "max"+ }+ },+ "preserveReasoningContentModels": [+ "deepseek-v4-pro",+ "deepseek-v4-flash"+ ]+ },+ {+ "id": "volcengine-agent-plan",+ "baseUrl": "https://ark.cn-beijing.volces.com/api/plan/v3",+ "responsesPath": "/responses",+ "adapter": "openai-responses",+ "authKind": "key"+ },+ {+ "id": "qianfan",+ "baseUrl": "https://qianfan.baidubce.com/v2",+ "adapter": "openai-chat",+ "authKind": "key"+ },+ {+ "id": "alibaba",+ "baseUrl": "https://coding-intl.dashscope.aliyuncs.com/v1",+ "adapter": "openai-chat",+ "authKind": "key"+ },+ {+ "id": "alibaba-token-plan",+ "baseUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",+ "adapter": "openai-chat",+ "authKind": "key",+ "modelReasoningEffortMap": {+ "deepseek-v4-pro": {+ "low": "low",+ "medium": "high",+ "high": "high",+ "xhigh": "high",+ "max": "max"+ }+ },+ "directReasoningEffortModels": [+ "qwen3.8-max"+ ],+ "thinkingBudgetModels": [+ "qwen3.7-max",+ "qwen3.7-plus",+ "qwen3.6-flash"+ ],+ "preserveReasoningContentModels": [+ "glm-5.3",+ "glm-5.3-flash",+ "glm-5.2",+ "deepseek-v4-pro",+ "qwen3.8-max",+ "qwen3.7-max",+ "qwen3.7-plus",+ "qwen3.6-flash"+ ]+ },+ {+ "id": "alibaba-token-plan-intl",+ "baseUrl": "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",+ "adapter": "openai-chat",+ "authKind": "key",+ "modelReasoningEffortMap": {+ "deepseek-v4-pro": {+ "low": "low",+ "medium": "high",+ "high": "high",+ "xhigh": "high",+ "max": "max"+ },+ "deepseek-v4-flash": {+ "low": "low",+ "medium": "high",+ "high": "high",+ "xhigh": "high",+ "max": "max"+ }+ },+ "directReasoningEffortModels": [+ "qwen3.8-max"+ ],+ "thinkingBudgetModels": [+ "qwen3.7-max",+ "qwen3.7-plus",+ "qwen3.6-plus",+ "qwen3.6-flash"+ ],+ "preserveReasoningContentModels": [+ "glm-5.3",+ "glm-5.3-flash",+ "glm-5.2",+ "deepseek-v4-pro",+ "deepseek-v4-flash",+ "qwen3.8-max",+ "qwen3.7-max",+ "qwen3.7-plus",+ "qwen3.6-plus",+ "qwen3.6-flash"+ ],+ "noReasoningModels": [+ "kimi-k2.7-code",+ "kimi-k2.6",+ "kimi-k2.5",+ "deepseek-v3.2",+ "glm-5.1",+ "glm-5",+ "MiniMax-M2.5"+ ]+ },+ {+ "id": "parallel",+ "baseUrl": "https://platform.parallel.ai",+ "adapter": "openai-chat",+ "authKind": "key"+ },+ {+ "id": "zenmux",+ "baseUrl": "https://zenmux.ai/api/v1",+ "adapter": "openai-chat",+ "authKind": "key"+ },+ {+ "id": "litellm",+ "baseUrl": "http://localhost:4000/v1",+ "adapter": "openai-chat",+ "authKind": "key"+ },+ {+ "id": "ollama-cloud",+ "baseUrl": "https://ollama.com/v1",+ "adapter": "ollama-native",+ "authKind": "key",+ "supportsVerbosity": false+ },+ {+ "id": "mistral",+ "baseUrl": "https://api.mistral.ai/v1",+ "adapter": "openai-chat",+ "authKind": "key"+ },+ {+ "id": "minimax",+ "baseUrl": "https://api.minimax.io/v1",+ "adapter": "openai-chat",+ "authKind": "key",+ "modelReasoningEffortMap": {+ "MiniMax-M3": {+ "none": "disabled",+ "minimal": "disabled",+ "low": "disabled",+ "medium": "adaptive",+ "high": "adaptive",+ "xhigh": "adaptive",+ "max": "adaptive"+ }+ },+ "preserveReasoningContentModels": [+ "MiniMax-M3",+ "MiniMax-M2.7",+ "MiniMax-M2.7-highspeed",+ "MiniMax-M2.5",+ "MiniMax-M2.5-highspeed",+ "MiniMax-M2.1",+ "MiniMax-M2.1-highspeed",+ "MiniMax-M2"+ ],+ "requiresReasoningPlaceholderModels": [],+ "reasoningSplitModels": [+ "MiniMax-M3",+ "MiniMax-M2.7",+ "MiniMax-M2.7-highspeed",+ "MiniMax-M2.5",+ "MiniMax-M2.5-highspeed",+ "MiniMax-M2.1",+ "MiniMax-M2.1-highspeed",+ "MiniMax-M2"+ ],+ "reasoningDetailsModels": [+ "MiniMax-M3",+ "MiniMax-M2.7",+ "MiniMax-M2.7-highspeed",+ "MiniMax-M2.5",+ "MiniMax-M2.5-highspeed",+ "MiniMax-M2.1",+ "MiniMax-M2.1-highspeed",+ "MiniMax-M2"+ ],+ "thinkingToggleModels": [+ "MiniMax-M3"+ ]+ },+ {+ "id": "minimax-cn",+ "baseUrl": "https://api.minimaxi.com/v1",+ "adapter": "openai-chat",+ "authKind": "key",+ "modelReasoningEffortMap": {+ "MiniMax-M3": {+ "none": "disabled",+ "minimal": "disabled",+ "low": "disabled",+ "medium": "adaptive",+ "high": "adaptive",+ "xhigh": "adaptive",+ "max": "adaptive"+ }+ },+ "preserveReasoningContentModels": [+ "MiniMax-M3",+ "MiniMax-M2.7",+ "MiniMax-M2.7-highspeed",+ "MiniMax-M2.5",+ "MiniMax-M2.5-highspeed",+ "MiniMax-M2.1",+ "MiniMax-M2.1-highspeed",+ "MiniMax-M2"+ ],+ "requiresReasoningPlaceholderModels": [],+ "reasoningSplitModels": [+ "MiniMax-M3",+ "MiniMax-M2.7",+ "MiniMax-M2.7-highspeed",+ "MiniMax-M2.5",+ "MiniMax-M2.5-highspeed",+ "MiniMax-M2.1",+ "MiniMax-M2.1-highspeed",+ "MiniMax-M2"+ ],+ "reasoningDetailsModels": [+ "MiniMax-M3",+ "MiniMax-M2.7",+ "MiniMax-M2.7-highspeed",+ "MiniMax-M2.5",+ "MiniMax-M2.5-highspeed",+ "MiniMax-M2.1",+ "MiniMax-M2.1-highspeed",+ "MiniMax-M2"+ ],+ "thinkingToggleModels": [+ "MiniMax-M3"+ ]+ },+ {+ "id": "kimi-code",+ "baseUrl": "https://api.kimi.com/coding/v1",+ "adapter": "openai-chat",+ "authKind": "key",+ "modelSuffixBracketStrip": true,+ "promptCacheKey": true,+ "noReasoningModels": [+ "k3",+ "k3[1m]",+ "kimi-k2.7-code",+ "kimi-k2.7-code-highspeed",+ "kimi-k2.6",+ "kimi-k2.5",+ "kimi-for-coding"+ ],+ "modelReasoningEffortMap": {+ "k3": {+ "none": "none",+ "low": "low",+ "medium": "high",+ "high": "high",+ "xhigh": "max",+ "max": "max"+ },+ "k3[1m]": {+ "none": "none",+ "low": "low",+ "medium": "high",+ "high": "high",+ "xhigh": "max",+ "max": "max"+ }+ },+ "noTemperatureModels": [+ "k3",+ "k3[1m]",+ "kimi-k2.7-code",+ "kimi-k2.7-code-highspeed",+ "kimi-k2.6",+ "kimi-k2.5",+ "kimi-for-coding"+ ],+ "noTopPModels": [+ "k3",+ "k3[1m]",+ "kimi-k2.7-code",+ "kimi-k2.7-code-highspeed",+ "kimi-k2.6",+ "kimi-k2.5",+ "kimi-for-coding"+ ],+ "noPenaltyModels": [+ "k3",+ "k3[1m]",+ "kimi-k2.7-code",+ "kimi-k2.7-code-highspeed",+ "kimi-k2.6",+ "kimi-k2.5",+ "kimi-for-coding"+ ],+ "autoToolChoiceOnlyModels": [+ "kimi-k2.7-code",+ "kimi-k2.7-code-highspeed",+ "kimi-for-coding"+ ],+ "preserveReasoningContentModels": [+ "k3",+ "k3[1m]",+ "kimi-k2.7-code",+ "kimi-k2.7-code-highspeed",+ "kimi-k2.6",+ "kimi-k2.5",+ "kimi-for-coding"+ ]+ },+ {+ "id": "opencode-zen",+ "baseUrl": "https://opencode.ai/zen/v1",+ "adapter": "openai-chat",+ "authKind": "key",+ "modelReasoningEffortMap": {+ "deepseek-v4-pro": {+ "low": "low",+ "medium": "high",+ "high": "high",+ "xhigh": "high",+ "max": "max"+ },+ "deepseek-v4-flash": {+ "low": "low",+ "medium": "high",+ "high": "high",+ "xhigh": "high",+ "max": "max"+ },+ "deepseek-v4-flash-free": {+ "low": "low",+ "medium": "high",+ "high": "high",+ "xhigh": "high",+ "max": "max"+ }+ },+ "preserveReasoningContentModels": [+ "deepseek-v4-pro",+ "deepseek-v4-flash",+ "deepseek-v4-flash-free"+ ]+ },+ {+ "id": "vercel-ai-gateway",+ "baseUrl": "https://ai-gateway.vercel.sh/v1",+ "adapter": "openai-chat",+ "authKind": "key"+ },+ {+ "id": "opencode-free",+ "adapter": "openai-chat",+ "baseUrl": "https://opencode.ai/zen/v1",+ "authKind": "key",+ "modelReasoningEffortMap": {+ "deepseek-v4-flash-free": {+ "low": "low",+ "medium": "high",+ "high": "high",+ "xhigh": "high",+ "max": "max"+ }+ },+ "preserveReasoningContentModels": [+ "deepseek-v4-flash-free"+ ]+ },+ {+ "id": "xiaomi",+ "baseUrl": "https://api.xiaomimimo.com/anthropic",+ "adapter": "anthropic",+ "authKind": "key"+ },+ {+ "id": "xiaomi-mimo",+ "baseUrl": "https://api.xiaomimimo.com/v1",+ "adapter": "openai-chat",+ "authKind": "key",+ "reasoningEffortMap": {+ "xhigh": "high",+ "max": "high",+ "ultra": "high"+ }+ },+ {+ "id": "kilo",+ "baseUrl": "https://api.kilo.ai/api/gateway",+ "adapter": "openai-chat",+ "authKind": "key"+ },+ {+ "id": "mimo-free",+ "adapter": "mimo-free",+ "baseUrl": "https://api.xiaomimimo.com/api/free-ai/openai/chat",+ "authKind": "key",+ "reasoningEffortMap": {+ "xhigh": "high",+ "max": "high",+ "ultra": "high"+ }+ },+ {+ "id": "mimo",+ "baseUrl": "https://token-plan-cn.xiaomimimo.com/v1",+ "adapter": "openai-chat",+ "authKind": "key",+ "reasoningEffortMap": {+ "xhigh": "high",+ "max": "high",+ "ultra": "high"+ }+ },+ {+ "id": "cloudflare-ai-gateway",+ "baseUrl": "https://gateway.ai.cloudflare.com/v1/{account-id}/{gateway}/anthropic",+ "adapter": "anthropic",+ "authKind": "key"+ },+ {+ "id": "cloudflare-workers-ai",+ "baseUrl": "https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/v1",+ "adapter": "openai-chat",+ "authKind": "key"+ },+ {+ "id": "github-copilot",+ "baseUrl": "https://api.githubcopilot.com",+ "adapter": "openai-chat",+ "authKind": "oauth",+ "modelWireDefaults": {+ "gpt-5.3-codex": "openai-responses",+ "gpt-5.4": "openai-responses",+ "gpt-5.4-mini": "openai-responses",+ "gpt-5.5": "openai-responses",+ "gpt-5.6-luna": "openai-responses",+ "gpt-5.6-sol": "openai-responses",+ "gpt-5.6-terra": "openai-responses",+ "gpt-6-astra": "openai-responses",+ "grok-4.5": "openai-responses",+ "grok-4.6": "openai-responses",+ "mai-code-1.1-flash": "openai-responses",+ "mai-code-1-flash-picker": "openai-responses"+ }+ },+ {+ "id": "gitlab-duo",+ "baseUrl": "https://cloud.gitlab.com/ai/v1/proxy/openai/v1",+ "adapter": "openai-chat",+ "authKind": "key"+ },+ {+ "id": "qoder",+ "adapter": "qoder",+ "baseUrl": "https://qoder.com",+ "authKind": "key"+ },+ {+ "id": "qoder-cn",+ "adapter": "qoder",+ "baseUrl": "https://qoder.cn",+ "authKind": "key"+ },+ {+ "id": "codebuddy",+ "adapter": "codebuddy",+ "baseUrl": "https://www.codebuddy.ai",+ "authKind": "key"+ },+ {+ "id": "codebuddy-cn",+ "adapter": "codebuddy",+ "baseUrl": "https://www.codebuddy.cn",+ "authKind": "key"+ }+]diff --git a/packages/model-compat/src/upstream/adapters/cursor/desktop-executor-contract.ts b/packages/model-compat/src/upstream/adapters/cursor/desktop-executor-contract.tsnew file mode 100644index 0000000000..2d89a7fa46--- /dev/null+++ b/packages/model-compat/src/upstream/adapters/cursor/desktop-executor-contract.ts@@ -0,0 +1,15 @@+/**+ * Opt-in external executor for computer-use / record-screen. opencodex is a headless proxy and+ * cannot drive a screen itself; set these commands only when running on a host that can. Each+ * command receives the request as JSON on stdin and must print a JSON result on stdout.+ */+export interface DesktopExecutorConfig {+ /** Command (run via the platform shell) handling computer-use. Receives `{toolCallId, actions}` on stdin. */+ computerUseCommand?: string;+ /** Command handling record-screen. Receives `{mode, toolCallId, saveAsFilename?}` on stdin. */+ recordScreenCommand?: string;+ cwd?: string;+ env?: Record<string, string>;+ /** Max time to wait for the external process. Default 30s. */+ timeoutMs?: number;+}diff --git a/packages/model-compat/src/upstream/adapters/cursor/mcp-config.ts b/packages/model-compat/src/upstream/adapters/cursor/mcp-config.tsnew file mode 100644index 0000000000..30bb655d55--- /dev/null+++ b/packages/model-compat/src/upstream/adapters/cursor/mcp-config.ts@@ -0,0 +1,42 @@+import type { OcxProviderConfig } from "../../types";++/**+ * One MCP server opencodex starts/connects and exposes to the Cursor agent as callable tools.+ * Either `command` (stdio: opencodex spawns the server as a child process) or `url`+ * (streamable-http: opencodex connects to a remote MCP server) must be set.+ */+export interface CursorMcpServerConfig {+ /** stdio: executable to spawn (e.g. "npx", "node", "uvx"). */+ command?: string;+ /** stdio: arguments for the spawned command. */+ args?: string[];+ /** stdio: extra environment variables for the child process. */+ env?: Record<string, string>;+ /** stdio: working directory for the child process. */+ cwd?: string;+ /** streamable-http: remote MCP server URL (alternative to `command`). */+ url?: string;+ /** streamable-http: extra headers for the remote connection. */+ headers?: Record<string, string>;+ /** Set false to keep the server in config but not connect. Default true. */+ enabled?: boolean;+ /** Optional namespace prepended to advertised tool names to avoid collisions. */+ toolPrefix?: string;+}++export interface ResolvedMcpServer extends CursorMcpServerConfig {+ serverName: string;+}++/**+ * Resolve the enabled, connectable MCP servers from a provider config. A server is+ * connectable only if it declares either a `command` (stdio) or a `url` (http).+ */+export function resolveMcpServers(provider: OcxProviderConfig): ResolvedMcpServer[] {+ const raw = provider.mcpServers;+ if (!raw) return [];+ return Object.entries(raw)+ .map(([serverName, cfg]) => ({ serverName, ...cfg }))+ .filter(server => server.enabled !== false)+ .filter(server => Boolean(server.command || server.url));+}diff --git a/packages/model-compat/src/upstream/adapters/empty-tool-output-annotation.ts b/packages/model-compat/src/upstream/adapters/empty-tool-output-annotation.tsnew file mode 100644index 0000000000..9eb287e396--- /dev/null+++ b/packages/model-compat/src/upstream/adapters/empty-tool-output-annotation.ts@@ -0,0 +1,43 @@+/**+ * Shared wire text and emptiness contract for present-but-empty tool outputs.+ *+ * Both the OpenAI Chat and Responses adapters use this module so the two wires+ * cannot drift again: only a pure text/refusal part array whose joined content+ * trims empty is "present but empty". Image, file, encrypted-content and any+ * other non-text part is real output and is never replaced by the annotation.+ */++/** Wire text used when a present-but-empty tool output must stay visible to the model. */+export const EMPTY_TOOL_OUTPUT_ANNOTATION =+ "[ocx] empty tool output: the tool ran but produced no stdout or return value; do not treat this as success, failure, or user-provided input.";++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++/** Part types that carry wire text on either adapter (Chat uses `text`, Responses uses `input_text`/`output_text`). */+const TEXT_PART_TYPES = new Set(["text", "input_text", "output_text"]);++/**+ * True when every part is text/refusal and the joined text/refusal content trims+ * empty. An empty array is the array twin of a blank string. Any image, file,+ * encrypted-content or other non-text part makes the array non-empty so the+ * model still receives the real payload.+ */+export function isWhitespaceOnlyTextPartArray(parts: readonly unknown[]): boolean {+ if (parts.length === 0) return true;+ let joined = "";+ for (const part of parts) {+ if (!isPlainObject(part)) return false;+ if (typeof part.type === "string" && TEXT_PART_TYPES.has(part.type) && typeof part.text === "string") {+ joined += part.text;+ continue;+ }+ if (part.type === "refusal" && typeof part.refusal === "string") {+ joined += part.refusal;+ continue;+ }+ return false;+ }+ return joined.trim() === "";+}diff --git a/packages/model-compat/src/upstream/adapters/google-tool-schema.ts b/packages/model-compat/src/upstream/adapters/google-tool-schema.tsnew file mode 100644index 0000000000..aad7d96bb4--- /dev/null+++ b/packages/model-compat/src/upstream/adapters/google-tool-schema.ts@@ -0,0 +1,238 @@+type Schema = Record<string, unknown>;++// Google documents this function-schema subset: type, nullable, required, format, description,+// properties, items, enum, anyOf, $ref, and $defs. We inline local refs and normalize anyOf, so+// only the eight scalar/container keywords below are ever emitted. Building from an allowlist+// prevents new MCP/JSON-Schema annotations from turning into provider-wide 400 responses.+const ALLOWED_TYPES = new Set(["string", "integer", "number", "boolean", "array", "object"]);+const MAX_SCHEMA_DEPTH = 24; // Google's documented nesting limit is 32; leave headroom for CCA.+const MAX_DEREF_DEPTH = 16;+const MAX_SCHEMA_NODES = 1_024;+const BUDGET_EXHAUSTED = Symbol("schema-budget-exhausted");+const MERGED_SCHEMA_KEYS = [+ "type",+ "nullable",+ "description",+ "format",+ "enum",+ "const",+ "properties",+ "items",+ "required",+ "anyOf",+] as const;++type SanitizeResult = Schema | typeof BUDGET_EXHAUSTED;++interface SanitizeState {+ activeRefs: Set<string>;+ remainingNodes: number;+}++function isRecord(value: unknown): value is Schema {+ return !!value && typeof value === "object" && !Array.isArray(value);+}++function resolveRef(ref: string, defs: Map<string, unknown>): unknown {+ // Only local pointers into the schema's own $defs/definitions are safe to inline.+ const match = /^#\/(?:\$defs|definitions)\/(.+)$/.exec(ref);+ if (!match) return undefined;+ try {+ return defs.get(decodeURIComponent(match[1].replace(/~1/g, "/").replace(/~0/g, "~")));+ } catch {+ return undefined;+ }+}++function collectDefs(root: unknown, defs: Map<string, unknown>): void {+ if (!isRecord(root)) return;+ for (const bag of ["$defs", "definitions"] as const) {+ const group = root[bag];+ if (!isRecord(group)) continue;+ for (const [name, value] of Object.entries(group)) {+ if (!defs.has(name)) defs.set(name, value);+ }+ }+}++function mergeRefTarget(target: Schema, overlay: Schema): Schema {+ const merged: Schema = {};+ if (Object.hasOwn(target, "$ref")) merged.$ref = target.$ref;+ for (const key of MERGED_SCHEMA_KEYS) {+ if (Object.hasOwn(overlay, key)) merged[key] = overlay[key];+ else if (Object.hasOwn(target, key)) merged[key] = target[key];+ }+ return merged;+}++function normalizeType(value: unknown, out: Schema, preserveNullType: boolean): void {+ const candidates = Array.isArray(value) ? value : [value];+ let sawNull = false;++ for (const candidate of candidates) {+ if (typeof candidate !== "string") continue;+ const type = candidate.toLowerCase();+ if (type === "null") {+ sawNull = true;+ } else if (out.type === undefined && ALLOWED_TYPES.has(type)) {+ out.type = type;+ }+ }++ if (!sawNull) return;+ if (out.type !== undefined) out.nullable = true;+ else if (preserveNullType) out.type = "null";+ else out.nullable = true;+}++function sanitizeEnum(value: unknown): string[] | undefined {+ if (!Array.isArray(value)) return undefined;+ const values = [...new Set(value.filter((item): item is string => typeof item === "string"))];+ return values.length > 0 ? values : undefined;+}++function normalizeAnyOf(+ value: unknown,+ defs: Map<string, unknown>,+ depth: number,+ refDepth: number,+ state: SanitizeState,+): Schema {+ if (!Array.isArray(value) || value.length === 0) return {};+ const schemas: Schema[] = [];+ for (let index = 0; index < value.length; index++) {+ if (state.remainingNodes <= 0) return {};+ const schema = sanitizeSchema(value[index], defs, depth + 1, refDepth, true, state);+ if (schema === BUDGET_EXHAUSTED) return {};+ schemas.push(schema);+ }++ const nonNullSchemas = schemas.filter(schema => schema.type !== "null");+ const nullSchemas = schemas.filter(schema => schema.type === "null");+ if (+ nonNullSchemas.length === 1+ && nullSchemas.length > 0+ && nullSchemas.every(schema => Object.keys(schema).every(key => key === "type"))+ ) {+ return { ...nonNullSchemas[0], nullable: true };+ }++ const type = schemas[0]?.type;+ const sameType = schemas.length > 0 && schemas.every(schema => schema.type === type);+ const enumOnly = schemas.every(schema => {+ const allowedKeys = type === undefined ? new Set(["enum"]) : new Set(["type", "enum"]);+ return Array.isArray(schema.enum) && Object.keys(schema).every(key => allowedKeys.has(key));+ });+ if (sameType && enumOnly && type !== "null") {+ const values = sanitizeEnum(schemas.flatMap(schema => schema.enum as unknown[]));+ if (values) return { ...(typeof type === "string" ? { type } : {}), enum: values };+ }++ // CCA's Claude bridge turns typed anyOf branches into an invalid input_schema. Widen only this+ // node when a union cannot be collapsed losslessly; parent annotations and structure survive.+ return {};+}++function sanitizeProperties(+ value: unknown,+ defs: Map<string, unknown>,+ depth: number,+ refDepth: number,+ state: SanitizeState,+): Record<string, Schema> | undefined {+ if (!isRecord(value)) return undefined;+ const properties: Record<string, Schema> = Object.create(null) as Record<string, Schema>;+ for (const name in value) {+ if (!Object.hasOwn(value, name)) continue;+ if (state.remainingNodes <= 0) break;+ // Property names form a name bag and must never be interpreted as schema keywords.+ const schema = sanitizeSchema(value[name], defs, depth + 1, refDepth, false, state);+ if (schema === BUDGET_EXHAUSTED) break;+ properties[name] = schema;+ }+ return properties;+}++function sanitizeSchema(+ node: unknown,+ defs: Map<string, unknown>,+ depth: number,+ refDepth: number,+ preserveNullType: boolean,+ state: SanitizeState,+): SanitizeResult {+ if (state.remainingNodes <= 0) return BUDGET_EXHAUSTED;+ state.remainingNodes -= 1;+ if (depth >= MAX_SCHEMA_DEPTH || !isRecord(node)) return {};++ if (typeof node.$ref === "string" && refDepth < MAX_DEREF_DEPTH) {+ const target = resolveRef(node.$ref, defs);+ if (isRecord(target)) {+ if (state.activeRefs.has(node.$ref)) return {};+ state.activeRefs.add(node.$ref);+ // Select only inputs the sanitizer can consume. Spreading an untrusted definition here would+ // enumerate and allocate every unsupported annotation before the node budget can stop work.+ const merged = mergeRefTarget(target, node);+ try {+ return sanitizeSchema(merged, defs, depth, refDepth + 1, preserveNullType, state);+ } finally {+ state.activeRefs.delete(node.$ref);+ }+ }+ }++ const out: Schema = {};+ normalizeType(node.type, out, preserveNullType);++ if (typeof node.nullable === "boolean") out.nullable = node.nullable;+ if (typeof node.description === "string") out.description = node.description;+ if (typeof node.format === "string") out.format = node.format;++ const enumValues = sanitizeEnum(node.enum ?? (typeof node.const === "string" ? [node.const] : undefined));+ if (enumValues) out.enum = enumValues;++ const properties = sanitizeProperties(node.properties, defs, depth, refDepth, state);+ if (properties) out.properties = properties;++ if (properties && Array.isArray(node.required)) {+ const required = [...new Set(node.required.filter((item): item is string => (+ typeof item === "string" && Object.hasOwn(properties, item)+ )))];+ if (required.length > 0) out.required = required;+ }++ if (state.remainingNodes <= 0) return out;++ if (isRecord(node.items)) {+ const items = sanitizeSchema(node.items, defs, depth + 1, refDepth, false, state);+ if (items !== BUDGET_EXHAUSTED) out.items = items;+ }++ if (state.remainingNodes <= 0) return out;+ if (node.anyOf !== undefined) {+ Object.assign(out, normalizeAnyOf(node.anyOf, defs, depth, refDepth, state));+ }+ return out;+}++export function sanitizeGeminiToolParameters(parameters: unknown): Record<string, unknown> {+ try {+ const defs = new Map<string, unknown>();+ collectDefs(parameters, defs);+ const state: SanitizeState = {+ activeRefs: new Set(),+ remainingNodes: MAX_SCHEMA_NODES,+ };+ const sanitized = sanitizeSchema(parameters, defs, 0, 0, false, state);+ const root = sanitized === BUDGET_EXHAUSTED ? {} : sanitized;++ // Function arguments are always an object. Claude additionally rejects root composition and a+ // missing root type even when those forms are valid general-purpose JSON Schema.+ root.type = "object";+ if (!isRecord(root.properties)) root.properties = {};+ return root;+ } catch {+ // Last-resort containment: no third-party schema may break every tool in the request.+ return { type: "object", properties: {} };+ }+}diff --git a/packages/model-compat/src/upstream/adapters/openai-chat.ts b/packages/model-compat/src/upstream/adapters/openai-chat.tsnew file mode 100644index 0000000000..ce7b637528--- /dev/null+++ b/packages/model-compat/src/upstream/adapters/openai-chat.ts@@ -0,0 +1,240 @@+// Pure parameter/schema helpers extracted from the upstream Chat adapter.+import type { OcxProviderConfig } from "../types";+import { lookupLocalJsonPointer } from "./xai-schema-analysis";+interface OcxParsedRequest { options: { reasoning?: string } }+export function stripBracketedModelSuffix(modelId: string): string {+ const suffixEnd = modelId.trimEnd().length;+ if (suffixEnd === 0 || modelId[suffixEnd - 1] !== "]") return modelId;++ let suffixStart = -1;+ for (let i = suffixEnd - 2; i >= 0 && modelId[i] !== "]"; i--) {+ if (modelId[i] === "[") suffixStart = i;+ }+ return suffixStart === -1 ? modelId : modelId.slice(0, suffixStart);+}++export function reasoningDetailSegmentForWire(text: string): Record<string, unknown> {+ return { type: "reasoning.text", id: "reasoning-text-1", format: "MiniMax-response-v1", index: 0, text };+}++export const MOONSHOT_SCHEMA_HOSTNAMES = new Set([+ "api.kimi.com",+ "api.moonshot.ai",+ "api.moonshot.cn",+]);++export function isMoonshotSchemaTarget(provider: OcxProviderConfig): boolean {+ try {+ return MOONSHOT_SCHEMA_HOSTNAMES.has(new URL(provider.baseUrl).hostname);+ } catch {+ return false;+ }+}++export function ensureRootObjectType(parameters: unknown): Record<string, unknown> {+ if (!parameters || typeof parameters !== "object" || Array.isArray(parameters)) {+ return { type: "object", properties: {} };+ }+ const obj = parameters as Record<string, unknown>;+ if (obj.type === "object") return obj;+ return { ...obj, type: "object" };+}++export function isXaiObjectSchema(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);+}++export function moonshotRefTargetKeys(node: Record<string, unknown>): string[] {+ return Object.keys(node).filter(key => key !== "$ref");+}++export const MOONSHOT_MAX_REF_EXPANSIONS = 512;++export const MOONSHOT_MAX_SCHEMA_DEPTH = 64;++export const MOONSHOT_MAX_SCHEMA_NODES = 4_096;++export function unionRequired(target: unknown, sibling: unknown): unknown {+ if (!Array.isArray(target) || !Array.isArray(sibling)) return sibling;+ const seen = new Set<unknown>();+ const out: unknown[] = [];+ for (const name of [...target, ...sibling]) {+ if (seen.has(name)) continue;+ seen.add(name);+ out.push(name);+ }+ return out;+}++export const MOONSHOT_DATA_VALUED_KEYWORDS = new Set(["enum", "const", "default", "examples"]);++export const MOONSHOT_BOUND_KEYWORDS: Record<string, "max" | "min"> = {+ minLength: "max",+ minItems: "max",+ minProperties: "max",+ minimum: "max",+ exclusiveMinimum: "max",+ maxLength: "min",+ maxItems: "min",+ maxProperties: "min",+ maximum: "min",+ exclusiveMaximum: "min",+};++export function intersectBound(target: unknown, sibling: unknown, direction: "max" | "min"): unknown {+ const a = typeof target === "number" && Number.isFinite(target) ? target : null;+ const b = typeof sibling === "number" && Number.isFinite(sibling) ? sibling : null;+ if (a === null) return b === null ? sibling : sibling;+ if (b === null) return target;+ return direction === "max" ? Math.max(a, b) : Math.min(a, b);+}++export function composeProperties(+ target: Record<string, unknown>,+ sibling: Record<string, unknown>,+): Record<string, unknown> {+ const combined: Record<string, unknown> = Object.create(null) as Record<string, unknown>;+ for (const [name, sub] of Object.entries(target)) combined[name] = sub;+ for (const [name, sub] of Object.entries(sibling)) {+ const existing = combined[name];+ if (isXaiObjectSchema(existing) && isXaiObjectSchema(sub)) {+ const member: Record<string, unknown> = Object.create(null) as Record<string, unknown>;+ for (const [k, v] of Object.entries(existing)) member[k] = v;+ for (const [k, v] of Object.entries(sub)) {+ if (k === "required") {+ member[k] = unionRequired(member[k], v);+ continue;+ }+ if (k === "properties" && isXaiObjectSchema(member[k]) && isXaiObjectSchema(v)) {+ member[k] = composeProperties(member[k] as Record<string, unknown>, v);+ continue;+ }+ const boundDirection = MOONSHOT_BOUND_KEYWORDS[k];+ if (boundDirection && k in member) {+ member[k] = intersectBound(member[k], v, boundDirection);+ continue;+ }+ member[k] = v;+ }+ combined[name] = member;+ continue;+ }+ combined[name] = sub;+ }+ return combined;+}++export interface MoonshotNormalizeState {+ activeRefs: Set<string>;+ remainingExpansions: number;+ remainingNodes: number;+}++export function normalizeMoonshotSchemaNode(+ node: unknown,+ root: Record<string, unknown>,+ state: MoonshotNormalizeState,+ depth = 0,+): unknown {+ if (Array.isArray(node)) {+ if (depth >= MOONSHOT_MAX_SCHEMA_DEPTH) return [];+ return node.map(item => normalizeMoonshotSchemaNode(item, root, state, depth + 1));+ }+ if (!isXaiObjectSchema(node)) return node;++ // Fail closed for this node rather than emitting a partially weakened schema: an empty+ // object is the one shape that asserts nothing it cannot back up.+ if (depth >= MOONSHOT_MAX_SCHEMA_DEPTH || state.remainingNodes <= 0) return {};+ state.remainingNodes -= 1;++ const ref = node.$ref;+ const hasSiblings = moonshotRefTargetKeys(node).length > 0;++ if (typeof ref === "string" && hasSiblings) {+ // A cycle cannot be inlined. Keeping the bare `$ref` is the lossy-but-valid fallback:+ // Moonshot accepts it, and the alternative (dropping the ref) would erase the recursion.+ if (state.activeRefs.has(ref) || state.remainingExpansions <= 0) return { $ref: ref };++ const target = lookupLocalJsonPointer(root, ref);+ if (isXaiObjectSchema(target)) {+ state.remainingExpansions -= 1;+ state.activeRefs.add(ref);+ const resolvedTarget = normalizeMoonshotSchemaNode(target, root, state, depth + 1);+ state.activeRefs.delete(ref);+ const merged: Record<string, unknown> = Object.create(null) as Record<string, unknown>;+ if (isXaiObjectSchema(resolvedTarget)) {+ for (const [key, value] of Object.entries(resolvedTarget)) merged[key] = value;+ }+ // "Alongside the target" is conjunction, not replacement. For most keywords the node+ // narrows the target and overwriting is the narrower reading, but `required` and+ // `properties` are set-valued: letting the sibling win DROPPED the target's own+ // members, so a tool requiring `a` beside a node requiring `b` shipped requiring only+ // `b`. Those two compose; everything else keeps the narrowing overwrite.+ for (const [key, value] of Object.entries(node)) {+ if (key === "$ref") continue;+ if (MOONSHOT_DATA_VALUED_KEYWORDS.has(key)) {+ merged[key] = value;+ continue;+ }+ const normalized = normalizeMoonshotSchemaNode(value, root, state, depth + 1);+ if (key === "required") {+ merged[key] = unionRequired(merged[key], normalized);+ continue;+ }+ if (key === "properties" && isXaiObjectSchema(merged[key]) && isXaiObjectSchema(normalized)) {+ merged[key] = composeProperties(merged[key] as Record<string, unknown>, normalized);+ continue;+ }+ // Numeric bounds intersect rather than overwrite: both the node and its target+ // apply, so the surviving bound is the stricter of the two in whichever direction+ // that keyword tightens.+ const boundDirection = MOONSHOT_BOUND_KEYWORDS[key];+ if (boundDirection && key in merged) {+ merged[key] = intersectBound(merged[key], normalized, boundDirection);+ continue;+ }+ merged[key] = normalized;+ }+ return merged;+ }++ // Unresolvable pointer: a remote ref, a malformed path, or a non-object target. Dropping+ // the ref and keeping the siblings silently discards whatever the reference constrained,+ // which is the one outcome we cannot detect downstream. A bare `$ref` is lossy in the+ // other direction - it loses the node's own keywords - but it preserves the identity of+ // what was asked for, and Moonshot accepts it.+ return { $ref: ref };+ }++ const out: Record<string, unknown> = Object.create(null) as Record<string, unknown>;+ for (const [key, value] of Object.entries(node)) {+ out[key] = key === "$ref" || MOONSHOT_DATA_VALUED_KEYWORDS.has(key)+ ? value+ : normalizeMoonshotSchemaNode(value, root, state, depth + 1);+ }+ return out;+}++export function normalizeMoonshotToolParameters(parameters: unknown): Record<string, unknown> {+ const rooted = ensureRootObjectType(parameters);+ const normalized = normalizeMoonshotSchemaNode(rooted, rooted, {+ activeRefs: new Set<string>(),+ remainingExpansions: MOONSHOT_MAX_REF_EXPANSIONS,+ remainingNodes: MOONSHOT_MAX_SCHEMA_NODES,+ });+ return isXaiObjectSchema(normalized) ? normalized : rooted;+}++export function thinkingBudgetForEffort(parsed: OcxParsedRequest, reasoningEffort: string, maxOutputTokens?: number): number | undefined {+ if (parsed.options.reasoning === "minimal") return 0;+ const maxBudget = maxOutputTokens ?? 32768;+ const fractions: Record<string, number> = {+ low: 0.20,+ medium: 0.50,+ high: 0.75,+ xhigh: 0.90,+ max: 1.0,+ };+ const fraction = fractions[reasoningEffort];+ return fraction === undefined ? undefined : Math.max(1, Math.floor(maxBudget * fraction));+}diff --git a/packages/model-compat/src/upstream/adapters/openai-responses.ts b/packages/model-compat/src/upstream/adapters/openai-responses.tsnew file mode 100644index 0000000000..dfd7d4c200--- /dev/null+++ b/packages/model-compat/src/upstream/adapters/openai-responses.ts@@ -0,0 +1,217 @@+// Pure protocol helpers extracted verbatim from the pinned upstream adapter.+import { EMPTY_TOOL_OUTPUT_ANNOTATION, isWhitespaceOnlyTextPartArray } from "./empty-tool-output-annotation";+export const CANONICAL_ONLY_TOOL_FIELDS: readonly { field: string; toolTypes?: ReadonlySet<string>; capabilityGated?: boolean }[] = [+ // ChatGPT's browsing policy bit. The public hosted tool is enabled by its presence alone.+ // OWNERSHIP: official OpenAI API-key traffic and unclassified gateways ACCEPT this field, so+ // it is only stripped when the provider capability denies it (supportsOpenAiWebSearchToolFields+ // === false), matching stripOpenAiOnlyWebSearchFields; see+ // tests/responses/responses-routed-web-search-fields.test.ts.+ { field: "external_web_access", toolTypes: new Set(["web_search", "web_search_preview"]), capabilityGated: true },+ // Deferred-discovery marker. `activateDeferredTool` clears it only for tools a `tool_search_output`+ // already loaded, so a still-deferred declaration — including one promoted out of a namespace+ // group — otherwise reaches the wire carrying it.+ { field: "defer_loading" },+];++export function stripCanonicalOnlyToolFields(body: unknown, includeCapabilityGated: boolean): unknown {+ if (!isPlainObject(body)) return body;++ const rewriteTools = (tools: unknown[]): unknown[] => {+ let changed = false;+ const rewritten = tools.map(tool => {+ if (!isPlainObject(tool)) return tool;+ let next = tool;+ for (const { field, toolTypes, capabilityGated } of CANONICAL_ONLY_TOOL_FIELDS) {+ if (capabilityGated && !includeCapabilityGated) continue;+ if (!Object.hasOwn(next, field)) continue;+ if (toolTypes && (typeof next.type !== "string" || !toolTypes.has(next.type))) continue;+ const { [field]: _private, ...rest } = next;+ next = rest;+ }+ if (next === tool) return tool;+ changed = true;+ return next;+ });+ return changed ? rewritten : tools;+ };++ let rewrittenBody = body;+ if (Array.isArray(body.tools)) {+ const tools = rewriteTools(body.tools);+ if (tools !== body.tools) rewrittenBody = { ...rewrittenBody, tools };+ }+ if (!Array.isArray(body.input)) return rewrittenBody;++ let input: unknown[] | undefined;+ for (let index = 0; index < body.input.length; index += 1) {+ const item = body.input[index];+ if (!isPlainObject(item) || item.type !== "additional_tools" || !Array.isArray(item.tools)) continue;+ const tools = rewriteTools(item.tools);+ if (tools === item.tools) continue;+ input ??= [...body.input];+ input[index] = { ...item, tools };+ }+ return input ? { ...rewrittenBody, input } : rewrittenBody;+}++export function isPlainObject(v: unknown): v is Record<string, unknown> {+ return !!v && typeof v === "object" && !Array.isArray(v);+}++export function isToolOutputEmpty(output: unknown): boolean {+ if (typeof output === "string") return output.trim() === "";+ if (Array.isArray(output)) {+ // Mirror the Chat wire rule through the shared contract: only a pure+ // text/refusal part array whose joined content trims empty is annotated.+ // input_image, encrypted_content, input_file and any other non-text part is+ // real output and must never be replaced.+ return isWhitespaceOnlyTextPartArray(output);+ }+ // A missing or null `output` is not a present-but-empty result: it is an+ // incomplete payload. Leave it untouched so the upstream contract fails+ // closed, and the orphan repair can surface it honestly instead of claiming+ // the tool ran with no output.+ return false;+}++export function annotateEmptyResponsesToolOutputs(body: unknown, enabled: boolean): unknown {+ if (!enabled || !isPlainObject(body) || !Array.isArray(body.input)) return body;+ let changed = false;+ const input = body.input.map(item => {+ if (!isPlainObject(item) || (item.type !== "function_call_output" && item.type !== "custom_tool_call_output")) return item;+ if (!isToolOutputEmpty(item.output)) return item;+ changed = true;+ return { ...item, output: EMPTY_TOOL_OUTPUT_ANNOTATION };+ });+ return changed ? { ...body, input } : body;+}++export function backfillWebSearchQueries(body: unknown): unknown {+ if (!isPlainObject(body) || !Array.isArray(body.input)) return body;+ let changed = false;+ const input = body.input.map(item => {+ if (!isPlainObject(item) || item.type !== "web_search_call") return item;+ const action = item.action;+ if (!isPlainObject(action) || action.type !== "search") return item;+ // Repair whichever side is missing so both strict parsers pass:+ // DeepSeek native Responses requires `queries`; Console Go requires `query`.+ const rep: Record<string, unknown> = { ...action };+ let itemChanged = false;+ const hasQuery = typeof action.query === "string";+ const queries = Array.isArray(action.queries) ? action.queries : undefined;+ if (queries !== undefined && queries.length === 0) {+ // An empty array satisfies neither validator. Canonicalize to the empty-search+ // shape the bridge emits, keeping an existing query rather than discarding it.+ const query = hasQuery ? action.query as string : "";+ rep.query = query;+ rep.queries = [query];+ itemChanged = true;+ } else if (!hasQuery && queries !== undefined) {+ // A plural array is only a usable source for the singular field when EVERY member+ // is a string: deriving `query` from a partly-malformed array would satisfy Console+ // Go while leaving DeepSeek to reject the same replay. Wholly malformed arrays are+ // left untouched — coercing or dropping members would invent semantics the stored+ // item never had.+ if (queries.every(entry => typeof entry === "string")) {+ rep.query = queries[0]; // multi-query item recorded before the fix+ itemChanged = true;+ }+ } else if (hasQuery && queries === undefined) {+ rep.queries = [action.query]; // single-query item recorded before the fix+ itemChanged = true;+ }+ if (itemChanged) changed = true;+ return itemChanged ? { ...item, action: rep } : item;+ });+ return changed ? { ...body, input } : body;+}++export function normalizeResponsesToolResultAdjacency(body: unknown): unknown {+ if (!isPlainObject(body) || !Array.isArray(body.input)) return body;+ const input = body.input;+ const calls = new Map<string, number[]>();+ const outputs = new Map<string, number[]>();++ const appendIndex = (map: Map<string, number[]>, key: string, index: number): void => {+ const existing = map.get(key);+ if (existing) existing.push(index);+ else map.set(key, [index]);+ };++ for (let index = 0; index < input.length; index += 1) {+ const item = input[index];+ if (!isPlainObject(item) || typeof item.call_id !== "string" || item.call_id.length === 0) continue;+ if (item.type === "function_call" || item.type === "local_shell_call") {+ appendIndex(calls, `function:${item.call_id}`, index);+ } else if (item.type === "custom_tool_call") {+ appendIndex(calls, `custom:${item.call_id}`, index);+ } else if (item.type === "function_call_output") {+ appendIndex(outputs, `function:${item.call_id}`, index);+ } else if (item.type === "custom_tool_call_output") {+ appendIndex(outputs, `custom:${item.call_id}`, index);+ }+ }++ const pairs: Array<{ callIndex: number; outputIndex: number }> = [];+ for (const [key, callIndices] of calls) {+ const outputIndices = outputs.get(key);+ if (!outputIndices) return body;+ if (callIndices.length !== 1 || outputIndices.length !== 1) return body;+ const callIndex = callIndices[0]!;+ const outputIndex = outputIndices[0]!;+ if (outputIndex <= callIndex) return body;+ pairs.push({ callIndex, outputIndex });+ }+ // Reject any collected output that lacks exactly one matching call. A lone or+ // duplicated output is ambiguous, and normalizing on top of it could sever a+ // result from the reasoning-bearing call turn it belongs to.+ for (const [key, outputIndices] of outputs) {+ const callIndices = calls.get(key);+ if (!callIndices || callIndices.length !== 1 || outputIndices.length !== 1) return body;+ }+ pairs.sort((left, right) => left.callIndex - right.callIndex);++ const movedIndices = new Set<number>();+ const batchAt = new Map<number, unknown[]>();+ for (let cursor = 0; cursor < pairs.length;) {+ const group = [pairs[cursor]!];+ let firstOutputIndex = pairs[cursor]!.outputIndex;+ let next = cursor + 1;+ while (next < pairs.length && pairs[next]!.callIndex < firstOutputIndex) {+ group.push(pairs[next]!);+ firstOutputIndex = Math.min(firstOutputIndex, pairs[next]!.outputIndex);+ next += 1;+ }++ // Within one reasoning turn the outputs must appear in the same order as their+ // calls. If they are reversed, normalizing would fabricate a new output order;+ // leave the ambiguous history untouched instead.+ for (let groupIndex = 1; groupIndex < group.length; groupIndex += 1) {+ if (group[groupIndex]!.outputIndex < group[groupIndex - 1]!.outputIndex) return body;+ }++ const batch = [+ ...group.map(pair => input[pair.callIndex]),+ ...group.map(pair => input[pair.outputIndex]),+ ];+ const anchor = group[0]!.callIndex;+ const alreadyContiguous = batch.every((item, offset) => input[anchor + offset] === item);+ if (!alreadyContiguous) {+ batchAt.set(anchor, batch);+ for (const pair of group) {+ movedIndices.add(pair.callIndex);+ movedIndices.add(pair.outputIndex);+ }+ }+ cursor = next;+ }+ if (batchAt.size === 0) return body;++ const normalized: unknown[] = [];+ for (let index = 0; index < input.length; index += 1) {+ const batch = batchAt.get(index);+ if (batch) normalized.push(...batch);+ if (!movedIndices.has(index)) normalized.push(input[index]);+ }+ return { ...body, input: normalized };+}diff --git a/packages/model-compat/src/upstream/adapters/opencode-go-additional-tools.ts b/packages/model-compat/src/upstream/adapters/opencode-go-additional-tools.tsnew file mode 100644index 0000000000..35e3aaa3e4--- /dev/null+++ b/packages/model-compat/src/upstream/adapters/opencode-go-additional-tools.ts@@ -0,0 +1,35 @@+function isRecord(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}++/** Console Go accepts public tools but rejects the private additional_tools input wrapper. */+export function normalizeOpenCodeGoAdditionalTools(body: unknown, responseUrl: string): unknown {+ let destination: URL;+ try {+ destination = new URL(responseUrl);+ } catch {+ return body;+ }+ if (destination.origin !== "https://opencode.ai"+ || destination.pathname !== "/zen/go/v1/responses"+ || destination.username || destination.password+ || destination.href.includes("?") || destination.href.includes("#")) return body;+ if (!isRecord(body) || !Array.isArray(body.input)) return body;+ // Do not replace a malformed top-level catalog with a partial promoted one.+ if (body.tools !== undefined && !Array.isArray(body.tools)) return body;++ const input: unknown[] = [];+ const promoted: unknown[] = [];+ let changed = false;+ for (const item of body.input) {+ if (isRecord(item) && item.type === "additional_tools" && Array.isArray(item.tools)) {+ changed = true;+ // Custom/search/namespace lowering already owns identity and deduplication. This pass+ // only moves declarations, including hosted tools that intentionally have no name.+ for (const tool of item.tools) promoted.push(tool);+ } else {+ input.push(item);+ }+ }+ return changed ? { ...body, input, tools: [...(body.tools ?? []), ...promoted] } : body;+}diff --git a/packages/model-compat/src/upstream/adapters/responses-tool-schema.ts b/packages/model-compat/src/upstream/adapters/responses-tool-schema.tsnew file mode 100644index 0000000000..7d10b9beec--- /dev/null+++ b/packages/model-compat/src/upstream/adapters/responses-tool-schema.ts@@ -0,0 +1,172 @@+// Keys whose *children's names* are caller-chosen rather than schema keywords, and keys whose+// values are literal payloads rather than schemas. Shared by both strippers below: each one has+// to tell "the keyword `x`" apart from "a property someone named `x`".+const SCHEMA_NAME_BAG_KEYS = new Set([+ "properties",+ "patternProperties",+ "$defs",+ "definitions",+ "dependencies",+ "dependentSchemas",+ "dependentRequired",+]);+const SCHEMA_LITERAL_VALUE_KEYS = new Set(["const", "default", "enum", "examples"]);++// These subtrees depend on property evaluation, polarity, branch selection or references.+// Preserve their complete argument contract rather than guessing whether a local relaxation+// remains a relaxation in the containing schema. The destination reports unsupported regexes.+const PRESERVED_PATTERN_SUBTREES = new Set([+ "patternProperties", "not", "oneOf", "if", "contains", "$defs", "definitions",+]);++/**+ * Codex multi-agent v2 stamps a Responses-only `encrypted: true` marker on collaboration tool+ * schemas (openai/codex 5f4d06ef; issue #85). It is an annotation for the ChatGPT backend only,+ * so translated provider schemas must drop it without removing properties or definitions+ * literally named `encrypted`.+ *+ * The schema is caller-supplied, so its nesting depth is attacker-influenced. Native recursion+ * would turn a deep schema into a stack overflow that takes down the request path, so this walks+ * an explicit stack instead: depth costs heap, which is bounded and recoverable.+ */+export function stripResponsesOnlyEncryptedMarker(node: unknown, inNameBag = false): unknown {+ type Assign = (value: unknown) => void;+ interface Frame { node: unknown; inNameBag: boolean; assign: Assign }++ let result: unknown;+ const stack: Frame[] = [{ node, inNameBag, assign: value => { result = value; } }];++ while (stack.length > 0) {+ const frame = stack.pop()!;+ const current = frame.node;++ if (Array.isArray(current)) {+ const out: unknown[] = new Array(current.length);+ frame.assign(out);+ // Array items are schemas in their own right, never a name bag.+ for (let i = current.length - 1; i >= 0; i--) {+ stack.push({ node: current[i], inNameBag: false, assign: value => { out[i] = value; } });+ }+ continue;+ }+ if (!current || typeof current !== "object") {+ frame.assign(current);+ continue;+ }++ // A schema name may be `__proto__`; a null-prototype record keeps it as data.+ const out: Record<string, unknown> = Object.create(null) as Record<string, unknown>;+ frame.assign(out);++ for (const [key, value] of Object.entries(current as Record<string, unknown>)) {+ if (frame.inNameBag) {+ // Inside a name bag every key is a caller-chosen name, so `encrypted` here is data.+ stack.push({ node: value, inNameBag: false, assign: v => { out[key] = v; } });+ } else if (key !== "encrypted") {+ if (SCHEMA_LITERAL_VALUE_KEYS.has(key)) {+ // Literal payloads are values, not schemas: an `encrypted` key inside them is data.+ out[key] = value;+ } else {+ const childInNameBag = SCHEMA_NAME_BAG_KEYS.has(key);+ stack.push({ node: value, inNameBag: childInNameBag, assign: v => { out[key] = v; } });+ }+ }+ }+ }++ return result;+}++/**+ * `\p{…}` is an escape only when the backslash introducing it is itself unescaped: in `\\p{2}`+ * the pair is a literal backslash and the `p{2}` that follows is an ordinary quantified `p`,+ * which Python compiles fine. Scanning for the raw substring would misread that as a property+ * escape and discard a working pattern.+ */+function usesUnicodePropertyEscape(pattern: string): boolean {+ for (let i = 0; i < pattern.length; i++) {+ if (pattern[i] !== "\\") continue;+ const next = pattern[i + 1];+ if (next === "\\") {+ i++;+ continue;+ }+ if ((next === "p" || next === "P") && pattern[i + 2] === "{") return true;+ }+ return false;+}++/**+ * Remove unsupported Unicode property escapes from scalar `pattern` constraints in ordinary+ * positive schema positions. This keeps built-in Artifact tools usable on Python-re backends;+ * the omitted constraint is not enforced by this proxy and tools must validate their inputs.+ *+ * Regex-keyed objects are preserved. Removing a matcher can lose evaluated-property annotations+ * needed by an ancestor's unevaluatedProperties, even when the local object appears open.+ * Negation, exclusive alternatives, conditions, contains and reusable definitions are also+ * preserved: loosening a nested constraint can instead reject an input in those contexts.+ * Unsupported patterns there remain the destination's validation responsibility.+ *+ * Returns `node` itself when nothing was dropped. Uses an explicit stack for caller-controlled+ * nesting depth; the separate Responses-only encrypted-marker normalization is unchanged.+ */+export function stripUnicodePropertyPatterns(node: unknown, inNameBag = false): unknown {+ type Assign = (value: unknown) => void;+ interface Frame { node: unknown; inNameBag: boolean; assign: Assign }++ let result: unknown;+ let dropped = 0;+ const stack: Frame[] = [{ node, inNameBag, assign: value => { result = value; } }];++ while (stack.length > 0) {+ const frame = stack.pop()!;+ const current = frame.node;++ if (Array.isArray(current)) {+ const out: unknown[] = new Array(current.length);+ frame.assign(out);+ // Array items are schemas in their own right, never a name bag.+ for (let i = current.length - 1; i >= 0; i--) {+ stack.push({ node: current[i], inNameBag: false, assign: value => { out[i] = value; } });+ }+ continue;+ }+ if (!current || typeof current !== "object") {+ frame.assign(current);+ continue;+ }++ // A schema name may be `__proto__`; a null-prototype record keeps it as data.+ const out: Record<string, unknown> = Object.create(null) as Record<string, unknown>;+ frame.assign(out);++ for (const [key, value] of Object.entries(current as Record<string, unknown>)) {+ if (frame.inNameBag) {+ // Inside a name bag every key is a caller-chosen name, so `pattern` here is a property+ // name; its value is still a schema and is walked as one.+ stack.push({ node: value, inNameBag: false, assign: v => { out[key] = v; } });+ continue;+ }+ if (PRESERVED_PATTERN_SUBTREES.has(key)) {+ out[key] = value;+ continue;+ }+ if (key === "pattern" && typeof value === "string" && usesUnicodePropertyEscape(value)) {+ dropped++;+ continue;+ }+ if (SCHEMA_LITERAL_VALUE_KEYS.has(key)) {+ // Literal payloads are values, not schemas: a `pattern` key inside them is data.+ out[key] = value;+ continue;+ }+ stack.push({+ node: value,+ inNameBag: SCHEMA_NAME_BAG_KEYS.has(key),+ assign: v => { out[key] = v; },+ });+ }+ }++ return dropped === 0 ? node : result;+}diff --git a/packages/model-compat/src/upstream/adapters/xai-schema-analysis.ts b/packages/model-compat/src/upstream/adapters/xai-schema-analysis.tsnew file mode 100644index 0000000000..5e19c4d87d--- /dev/null+++ b/packages/model-compat/src/upstream/adapters/xai-schema-analysis.ts@@ -0,0 +1,86 @@+export function isSchemaObject(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);+}++function decodeJsonPointerToken(token: string): string {+ return token.replace(/~1/g, "/").replace(/~0/g, "~");+}++/** Resolve a local `#/`-rooted JSON Pointer against `root`; undefined when it does not resolve. */+export function lookupLocalJsonPointer(root: unknown, ref: string): unknown {+ if (ref === "#" || ref === "#/") return root;+ if (!ref.startsWith("#/")) return undefined;+ let current: unknown = root;+ for (const token of ref.slice(2).split("/").map(decodeJsonPointerToken)) {+ if (!isSchemaObject(current) || !Object.hasOwn(current, token)) return undefined;+ current = current[token];+ }+ return current;+}++/** Values a schema pins through `const`/`enum`, or undefined when it pins none. */+function xaiLiteralValues(schema: unknown): unknown[] | undefined {+ if (!isSchemaObject(schema)) return undefined;+ if (Object.hasOwn(schema, "const")) return [schema.const];+ if (Array.isArray(schema.enum)) return schema.enum;+ return undefined;+}++/** JSON type name for a literal, so it can be compared against a `type` keyword. */+function xaiJsonTypeOf(value: unknown): string {+ if (value === null) return "null";+ if (Array.isArray(value)) return "array";+ if (typeof value === "string") return "string";+ if (typeof value === "boolean") return "boolean";+ if (typeof value === "number") return Number.isInteger(value) ? "integer" : "number";+ return "object";+}++/** Types a schema declares, or undefined when it constrains none. */+function xaiDeclaredTypes(schema: unknown): Set<string> | undefined {+ if (!isSchemaObject(schema)) return undefined;+ const type = schema.type;+ if (typeof type === "string") return new Set([type]);+ if (Array.isArray(type) && type.every(item => typeof item === "string")) return new Set(type as string[]);+ return undefined;+}++/** `integer` is a subset of `number`, so those two names overlap rather than exclude. */+function xaiTypesOverlap(left: string, right: string): boolean {+ if (left === right) return true;+ return (left === "integer" && right === "number") || (left === "number" && right === "integer");+}++/**+ * Conservative mutual-exclusion test: true only when no instance can satisfy both schemas.+ * Proof comes from disjoint literal sets or disjoint declared types; anything it cannot prove+ * is reported as overlapping so the caller refuses the merge instead of widening the schema.+ */+function xaiSchemasAreProvablyDisjoint(left: unknown, right: unknown): boolean {+ const leftValues = xaiLiteralValues(left);+ const rightValues = xaiLiteralValues(right);+ if (leftValues && rightValues) {+ const seen = new Set(rightValues.map(value => JSON.stringify(value)));+ return leftValues.every(value => !seen.has(JSON.stringify(value)));+ }+ const leftTypes = xaiDeclaredTypes(left);+ const rightTypes = xaiDeclaredTypes(right);+ const literalsExcludedByTypes = (values: unknown[], types: Set<string>): boolean =>+ values.every(value => ![...types].some(type => xaiTypesOverlap(xaiJsonTypeOf(value), type)));+ if (leftValues && rightTypes) return literalsExcludedByTypes(leftValues, rightTypes);+ if (rightValues && leftTypes) return literalsExcludedByTypes(rightValues, leftTypes);+ if (leftTypes && rightTypes) {+ return ![...leftTypes].some(leftType => [...rightTypes].some(rightType => xaiTypesOverlap(leftType, rightType)));+ }+ return false;+}++/** Every pair provably disjoint, so a union over them accepts each instance exactly once. */+export function xaiSchemasArePairwiseDisjoint(schemas: unknown[]): boolean {+ for (let i = 0; i < schemas.length; i += 1) {+ for (let j = i + 1; j < schemas.length; j += 1) {+ if (!xaiSchemasAreProvablyDisjoint(schemas[i], schemas[j])) return false;+ }+ }+ return true;+}diff --git a/packages/model-compat/src/upstream/adapters/xai-tool-schema.ts b/packages/model-compat/src/upstream/adapters/xai-tool-schema.tsnew file mode 100644index 0000000000..e853296526--- /dev/null+++ b/packages/model-compat/src/upstream/adapters/xai-tool-schema.ts@@ -0,0 +1,351 @@+import type { OcxProviderConfig } from "../types";+export { lookupLocalJsonPointer } from "./xai-schema-analysis";+import { isSchemaObject, lookupLocalJsonPointer, xaiSchemasArePairwiseDisjoint } from "./xai-schema-analysis";++export function isXaiSchemaTarget(provider: Pick<OcxProviderConfig, "baseUrl">): boolean {+ try {+ // Public api.x.ai accepts native root object unions. Only the Grok CLI proxy+ // 400s on a root oneOf/anyOf, so flattening/omitting is scoped to that host.+ return new URL(provider.baseUrl).hostname === "cli-chat-proxy.grok.com";+ } catch {+ return false;+ }+}++/** A tool this proxy had to omit is still named by `tool_choice`; the caller maps this to a 400. */+export class XaiToolSchemaCompatibilityError extends Error {}++function stringRequiredFields(value: unknown): string[] {+ return Array.isArray(value)+ ? value.filter((item): item is string => typeof item === "string")+ : [];+}++/** Variant keys the merger can keep. Anything else is refused, not silently dropped. */+const XAI_VARIANT_MERGE_KEYS = new Set([+ "type",+ "properties",+ "required",+ "additionalProperties",+ "description",+ "title",+ "$comment",+ "$defs",+ "definitions",+]);++/**+ * A root union expands combinatorially: n nested binary unions yield 2^n variants, and a+ * diamond of `$ref`s amplifies node count the same way without ever cycling. Either one can+ * exhaust memory before the schema is judged unflattenable, so depth, node, and variant+ * budgets bound the walk. Exceeding any of them omits that one function — the same fallback+ * an unflattenable schema already takes. Mirrors the node budgets in openai-chat.ts.+ */+const XAI_MAX_SCHEMA_DEPTH = 64;+const XAI_MAX_SCHEMA_NODES = 4_096;+const XAI_MAX_ROOT_VARIANTS = 256;++/** Mutable walk budget, shared across ref resolution and root-union expansion for one tool. */+interface XaiSchemaBudget {+ remainingNodes: number;+ remainingVariants: number;+}++/** One budget per tool: a large catalog must not let one schema spend another's allowance. */+function createXaiSchemaBudget(): XaiSchemaBudget {+ return { remainingNodes: XAI_MAX_SCHEMA_NODES, remainingVariants: XAI_MAX_ROOT_VARIANTS };+}++/** Resolve local `#/` `$ref`s. Unresolvable, cyclic, or over-budget refs return undefined. */+function resolveXaiSchemaRefs(+ schema: unknown,+ root: Record<string, unknown>,+ budget: XaiSchemaBudget,+ stack: Set<string> = new Set(),+ depth = 0,+): unknown | undefined {+ if (!isSchemaObject(schema)) return schema;+ if (depth >= XAI_MAX_SCHEMA_DEPTH || budget.remainingNodes <= 0) return undefined;+ budget.remainingNodes -= 1;+ if (typeof schema.$ref === "string") {+ const ref = schema.$ref;+ if (stack.has(ref)) return undefined;+ const target = lookupLocalJsonPointer(root, ref);+ if (target === undefined) return undefined;+ stack.add(ref);+ const resolvedTarget = resolveXaiSchemaRefs(target, root, budget, stack, depth + 1);+ stack.delete(ref);+ if (resolvedTarget === undefined) return undefined;+ const rest: Record<string, unknown> = { ...schema };+ delete rest.$ref;+ if (Object.keys(rest).length === 0) return resolvedTarget;+ const resolvedRest = resolveXaiSchemaRefs(rest, root, budget, stack, depth + 1);+ if (resolvedRest === undefined || !isSchemaObject(resolvedTarget) || !isSchemaObject(resolvedRest)) {+ return undefined;+ }+ return composeXaiObjectSchemas(resolvedTarget, resolvedRest);+ }++ const resolved: Record<string, unknown> = {};+ for (const [key, value] of Object.entries(schema)) {+ if ((key === "oneOf" || key === "anyOf") && Array.isArray(value)) {+ const items: unknown[] = [];+ for (const item of value) {+ const next = resolveXaiSchemaRefs(item, root, budget, stack, depth + 1);+ if (next === undefined) return undefined;+ items.push(next);+ }+ resolved[key] = items;+ continue;+ }+ if (key === "properties" && isSchemaObject(value)) {+ const properties: Record<string, unknown> = {};+ for (const [name, property] of Object.entries(value)) {+ const next = resolveXaiSchemaRefs(property, root, budget, stack, depth + 1);+ if (next === undefined) return undefined;+ properties[name] = next;+ }+ resolved[key] = properties;+ continue;+ }+ resolved[key] = value;+ }+ return resolved;+}++/** A variant is mergeable only when it is an object whose every key the merger preserves. */+function xaiVariantIsConcreteObject(variant: Record<string, unknown>): boolean {+ if (variant.type !== undefined && variant.type !== "object") return false;+ return Object.keys(variant).every(key => XAI_VARIANT_MERGE_KEYS.has(key));+}++function variantProperties(variant: Record<string, unknown>): Record<string, unknown> {+ return isSchemaObject(variant.properties) ? variant.properties : {};+}++/**+ * Independent per-property anyOf is lossless only when every property name exists+ * on every variant (absence is meaningful under xAI's default additionalProperties:+ * false, and promoting a branch-local key also tightens explicit-true variants)+ * and at most one property schema differs.+ */+function xaiPropertyMergeIsLossless(variants: Record<string, unknown>[]): boolean {+ const names = new Set<string>();+ const props = variants.map(variant => {+ const properties = variantProperties(variant);+ for (const name of Object.keys(properties)) names.add(name);+ return properties;+ });+ let schemaConflicts = 0;+ for (const name of names) {+ const values = props.map(property => property[name]);+ if (values.some(value => value === undefined)) return false;+ if (values.some(value => JSON.stringify(value) !== JSON.stringify(values[0]))) schemaConflicts += 1;+ }+ return schemaConflicts <= 1;+}++function xaiRequiredSetsMatch(variants: Record<string, unknown>[]): boolean {+ const serialized = variants.map(variant => [...stringRequiredFields(variant.required)].sort().join("\0"));+ return serialized.every(value => value === serialized[0]);+}++/** Deduplicate schemas by serialized shape, preserving first-seen order. */+function uniqueXaiSchemas(values: unknown[]): unknown[] {+ const unique: unknown[] = [];+ const serialized = new Set<string>();+ for (const value of values) {+ const key = JSON.stringify(value);+ if (serialized.has(key)) continue;+ serialized.add(key);+ unique.push(value);+ }+ return unique;+}++function mergeXaiAdditionalProperties(+ variants: Record<string, unknown>[],+): { ok: true; value?: unknown } | { ok: false } {+ const values = variants.map(variant => variant.additionalProperties);+ const explicit = values.filter(value => value !== undefined);+ if (explicit.length === 0) return { ok: true };+ if (explicit.length !== values.length) return { ok: false };+ const hasFalse = explicit.some(value => value === false);+ const permissive = explicit.filter(value => value !== false);+ if (hasFalse && permissive.length > 0) return { ok: false };+ if (hasFalse) return { ok: true, value: false };+ const unique = uniqueXaiSchemas(permissive);+ if (unique.length !== 1) return { ok: false };+ return { ok: true, value: unique[0] };+}++/** Compose root siblings into a branch so properties/required are not overwritten. */+function composeXaiObjectSchemas(+ inherited: Record<string, unknown>,+ branch: Record<string, unknown>,+): Record<string, unknown> {+ const composed: Record<string, unknown> = { ...inherited, ...branch };+ const inheritedProps = isSchemaObject(inherited.properties) ? inherited.properties : undefined;+ const branchProps = isSchemaObject(branch.properties) ? branch.properties : undefined;+ if (inheritedProps || branchProps) {+ const properties: Record<string, unknown> = { ...(inheritedProps ?? {}) };+ for (const [name, value] of Object.entries(branchProps ?? {})) {+ const inheritedValue = inheritedProps?.[name];+ properties[name] = inheritedValue !== undefined && JSON.stringify(inheritedValue) !== JSON.stringify(value)+ ? { allOf: [inheritedValue, value] }+ : value;+ }+ composed.properties = properties;+ }+ const required = [...new Set([+ ...stringRequiredFields(inherited.required),+ ...stringRequiredFields(branch.required),+ ])];+ if (required.length > 0) composed.required = required;+ else delete composed.required;+ return composed;+}++/** Flattened root variants, plus the shape of the union tree they came from. */+interface XaiRootExpansion {+ variants: Record<string, unknown>[];+ /** This node was itself a union, as opposed to a plain object leaf. */+ isUnion: boolean;+ /**+ * True when a `oneOf` was expanded anywhere in the tree. `oneOf` rejects an instance that+ * matches more than one branch, so its variants must stay mutually exclusive after merging;+ * `anyOf` carries no such obligation.+ */+ exclusive: boolean;+ /**+ * True when a branch was itself a union. Nested `anyOf` flattens associatively and stays+ * exact, but a `oneOf` mixed into a nest no longer maps onto one flat variant list: its+ * exclusivity binds only its own branch group, which a merged root cannot express.+ */+ nestedUnion: boolean;+}++function expandXaiRootObjectSchemas(+ schema: unknown,+ budget: XaiSchemaBudget,+ depth = 0,+): XaiRootExpansion | undefined {+ if (!isSchemaObject(schema) || depth >= XAI_MAX_SCHEMA_DEPTH) return undefined;+ const compositionKey = ["oneOf", "anyOf"].find(key => Array.isArray(schema[key]));+ if (!compositionKey) {+ if (schema.type !== undefined && schema.type !== "object") return undefined;+ if (budget.remainingVariants <= 0) return undefined;+ budget.remainingVariants -= 1;+ return { variants: [{ ...schema, type: "object" }], isUnion: false, exclusive: false, nestedUnion: false };+ }++ const siblings = Object.fromEntries(Object.entries(schema).filter(([key]) => key !== compositionKey));+ const branches = schema[compositionKey];+ if (!Array.isArray(branches)) return undefined;+ const expanded: Record<string, unknown>[] = [];+ let exclusive = compositionKey === "oneOf";+ let nestedUnion = false;+ for (const branch of branches) {+ const nested = expandXaiRootObjectSchemas(branch, budget, depth + 1);+ if (!nested) return undefined;+ exclusive ||= nested.exclusive;+ nestedUnion ||= nested.isUnion || nested.nestedUnion;+ for (const variant of nested.variants) expanded.push(composeXaiObjectSchemas(siblings, variant));+ }+ return expanded.length > 0 ? { variants: expanded, isUnion: true, exclusive, nestedUnion } : undefined;+}++/**+ * The Grok CLI proxy rejects a function parameter schema whose root remains oneOf/anyOf.+ * Flatten only when the merge is lossless: local $refs resolve inside the walk budget, every+ * variant is a concrete object whose keys we can preserve, required sets match,+ * additionalProperties does not change meaning, every property name exists on every variant,+ * and at most one property schema differs.+ *+ * A `oneOf` carries one more obligation than `anyOf`: it rejects an instance matching several+ * branches. Only the destination's ROOT rejects a union, so exclusivity survives by moving the+ * union down onto the one differing property rather than by widening it — with every other+ * property, the required set, and additionalProperties already identical across branches, a+ * property-level `oneOf` accepts exactly what the root `oneOf` accepted. Branches that are+ * provably disjoint keep emitting `anyOf`, since there the two keywords describe the same set.+ * The remaining hole is an optional discriminator: absent, it matches every branch, which the+ * root `oneOf` rejects and a per-property union would accept, so that property is promoted into+ * `required`.+ *+ * Two deliberate widenings remain, and both widen only from the EMPTY set. A `oneOf` listing the+ * same branch twice accepts nothing at all. Neither does a root `additionalProperties: false`+ * placed over branches that declare properties the root itself does not: the restriction cannot+ * see into an applicator, so it forbids the very keys those branches require (same for a `$ref`+ * target's restriction against a sibling's properties). No author intends either, no root object+ * schema can express "accepts nothing", and the emitted schema still carries the restriction — so+ * the tool stays usable instead of disappearing over a source-schema bug. A union whose branch+ * properties ARE declared on the root is satisfiable and is normalized losslessly, which is why+ * the presence of `additionalProperties` alone is not grounds to refuse.+ */+export function normalizeXaiToolParameters(parameters: unknown): Record<string, unknown> | undefined {+ if (!isSchemaObject(parameters)) return undefined;+ const budget = createXaiSchemaBudget();+ const resolved = resolveXaiSchemaRefs(parameters, parameters, budget);+ if (!isSchemaObject(resolved)) return undefined;++ const normalizedRoot = { ...resolved };+ delete normalizedRoot.$schema;++ const expansion = expandXaiRootObjectSchemas(normalizedRoot, budget);+ if (!expansion) return undefined;+ const { variants, exclusive, nestedUnion } = expansion;+ if (variants.length === 1) {+ return xaiVariantIsConcreteObject(variants[0]) ? variants[0] : undefined;+ }+ if (!variants.every(xaiVariantIsConcreteObject) || !xaiRequiredSetsMatch(variants)) return undefined;+ const additionalProperties = mergeXaiAdditionalProperties(variants);+ if (!additionalProperties.ok) return undefined;+ if (!xaiPropertyMergeIsLossless(variants)) return undefined;++ const metadata = Object.fromEntries(Object.entries(normalizedRoot).filter(([key]) => key !== "oneOf" && key !== "anyOf" && key !== "type"));+ delete metadata.properties;+ delete metadata.required;+ delete metadata.additionalProperties;++ const propertyValues = new Map<string, unknown[]>();+ for (const variant of variants) {+ if (!isSchemaObject(variant.properties)) continue;+ for (const [name, value] of Object.entries(variant.properties)) {+ const values = propertyValues.get(name) ?? [];+ values.push(value);+ propertyValues.set(name, values);+ }+ }++ const properties: Record<string, unknown> = {};+ const differingNames: string[] = [];+ for (const [name, values] of propertyValues) {+ const unique = uniqueXaiSchemas(values);+ if (unique.length === 1) {+ properties[name] = unique[0];+ continue;+ }+ // A `oneOf` nested among other unions binds exclusivity to its own branch group only, so a+ // single flat variant list cannot say what the original said — in either direction. Refuse.+ if (exclusive && nestedUnion) return undefined;+ differingNames.push(name);+ // Disjoint branches make `anyOf` and `oneOf` describe the same set, so prefer the keyword+ // already proven on this wire; overlapping branches need the exclusivity kept verbatim.+ properties[name] = exclusive && !xaiSchemasArePairwiseDisjoint(unique)+ ? { oneOf: unique }+ : { anyOf: unique };+ }++ let required = stringRequiredFields(variants[0]?.required);+ if (exclusive && differingNames.length > 0) {+ required = [...new Set([...required, ...differingNames])];+ }++ return {+ ...metadata,+ type: "object",+ properties,+ ...(required.length > 0 ? { required } : {}),+ ...("value" in additionalProperties ? { additionalProperties: additionalProperties.value } : {}),+ };+}diff --git a/packages/model-compat/src/upstream/adapters/xai-web-search.ts b/packages/model-compat/src/upstream/adapters/xai-web-search.tsnew file mode 100644index 0000000000..48de70e005--- /dev/null+++ b/packages/model-compat/src/upstream/adapters/xai-web-search.ts@@ -0,0 +1,246 @@+import type { OcxProviderConfig } from "../types";+import { isXaiResponsesDestination } from "../providers/xai-transport";++const CODEX_WEB_SEARCH_TOOL = "web_search";+const CODEX_WEB_SEARCH_PREVIEW_TOOL = "web_search_preview";+const XAI_SEARCH_TOOL = "x_search";++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}++function isCodexWebSearchToolType(value: unknown): boolean {+ return value === CODEX_WEB_SEARCH_TOOL || value === CODEX_WEB_SEARCH_PREVIEW_TOOL;+}++type ToolGroupRewrite = {+ tools: unknown[];+ changed: boolean;+};++/**+ * Translate Codex-private hosted-search fields to xAI's public Responses schema.+ *+ * xAI web search is live-only. A Codex cached/index-only declaration carries+ * `external_web_access: false`; dropping that flag while keeping the tool would silently widen+ * network access, so the whole tool is omitted instead. `true` maps to xAI's ordinary live+ * `{type:"web_search"}` declaration. Requests that omit the private flag are already public-API+ * shaped and retain their live-search behavior.+ */+function normalizeToolGroup(tools: unknown[]): ToolGroupRewrite {+ const normalized: unknown[] = [];+ let changed = false;++ for (const tool of tools) {+ if (!isPlainObject(tool) || !isCodexWebSearchToolType(tool.type)) {+ normalized.push(tool);+ continue;+ }++ const hasExternalAccess = Object.hasOwn(tool, "external_web_access");+ if (hasExternalAccess && tool.external_web_access !== true) {+ // xAI has no cached/index-only equivalent. Fail closed instead of turning it into live search.+ changed = true;+ continue;+ }++ const searchContentTypes = Array.isArray(tool.search_content_types)+ ? tool.search_content_types+ : undefined;+ const enableImageSearch = searchContentTypes?.includes("image") === true;+ const next: Record<string, unknown> = { ...tool, type: CODEX_WEB_SEARCH_TOOL };+ // Only the two fields xAI actually refuses are removed. Probed 2026-08-22, one field per+ // request, against BOTH xAI destinations (api.x.ai and cli-chat-proxy.grok.com): they behave+ // identically — `external_web_access` 400s on every value including `true`, and+ // `search_context_size` 400s, while `user_location`, `search_content_types`, `filters` and+ // `enable_image_search` are all accepted. Deleting the accepted ones was a silent capability+ // loss, and it contradicted the sibling layer, whose own probe note already records+ // user_location/filters as accepted (tests/responses/responses-routed-web-search-fields.test.ts).+ delete next.external_web_access;+ // Cindy also receives this Codex-private flag; preserve its existing stripping behavior.+ delete next.index_gated_web_access;+ delete next.search_context_size;+ if (enableImageSearch && !Object.hasOwn(next, "enable_image_search")) {+ next.enable_image_search = true;+ }++ const toolChanged = Object.keys(next).length !== Object.keys(tool).length+ || Object.entries(next).some(([key, value]) => tool[key] !== value);+ changed ||= toolChanged;+ normalized.push(toolChanged ? next : tool);+ }++ return { tools: changed ? normalized : tools, changed };+}++function hasWebSearchTool(body: Record<string, unknown>): boolean {+ if (Array.isArray(body.tools) && body.tools.some(tool =>+ isPlainObject(tool) && isCodexWebSearchToolType(tool.type)+ )) return true;+ return Array.isArray(body.input) && body.input.some(item =>+ isPlainObject(item)+ && item.type === "additional_tools"+ && Array.isArray(item.tools)+ && item.tools.some(tool => isPlainObject(tool) && isCodexWebSearchToolType(tool.type))+ );+}++function hasAnyDeclaredTool(body: Record<string, unknown>): boolean {+ if (Array.isArray(body.tools) && body.tools.length > 0) return true;+ return Array.isArray(body.input) && body.input.some(item =>+ isPlainObject(item)+ && item.type === "additional_tools"+ && Array.isArray(item.tools)+ && item.tools.length > 0+ );+}++/** Remove selectors that would still force a cached-only tool omitted above. */+function normalizeToolChoice(body: Record<string, unknown>): Record<string, unknown> {+ const choice = body.tool_choice;+ if (choice === undefined) return body;+ const hasSearch = hasWebSearchTool(body);++ if (isPlainObject(choice) && isCodexWebSearchToolType(choice.type)) {+ if (!hasSearch) return { ...body, tool_choice: "none" };+ return choice.type === CODEX_WEB_SEARCH_TOOL+ ? body+ : { ...body, tool_choice: { ...choice, type: CODEX_WEB_SEARCH_TOOL } };+ }+ if (isPlainObject(choice) && choice.type === "allowed_tools" && Array.isArray(choice.tools)) {+ let changed = false;+ const tools: unknown[] = [];+ for (const tool of choice.tools) {+ if (!isPlainObject(tool) || !isCodexWebSearchToolType(tool.type)) {+ tools.push(tool);+ continue;+ }+ if (!hasSearch) {+ changed = true;+ continue;+ }+ if (tool.type === CODEX_WEB_SEARCH_PREVIEW_TOOL) {+ tools.push({ ...tool, type: CODEX_WEB_SEARCH_TOOL });+ changed = true;+ } else {+ tools.push(tool);+ }+ }+ if (!changed) return body;+ return {+ ...body,+ tool_choice: tools.length > 0 ? { ...choice, tools } : "none",+ };+ }+ if (choice === "required" && !hasAnyDeclaredTool(body)) {+ return { ...body, tool_choice: "none" };+ }+ return body;+}++function currentInputStart(inputLength: number, replayPrefixLength: number | undefined): number {+ if (typeof replayPrefixLength !== "number" || !Number.isFinite(replayPrefixLength)) return 0;+ return Math.min(inputLength, Math.max(0, Math.trunc(replayPrefixLength)));+}++function hasToolType(tools: unknown, type: string): boolean {+ return Array.isArray(tools) && tools.some(tool => isPlainObject(tool) && tool.type === type);+}++/**+ * Make Codex's hosted web-search declaration acceptable to xAI Responses without changing other+ * providers or mutating the caller-owned request body.+ *+ * Scoped to BOTH xAI Responses hosts, not just the public API. The 2026-08-22 probe recorded in+ * `normalizeToolGroup` and in `isXaiResponsesDestination` already found the two hosts to be one+ * dialect, but this gate stayed on `api.x.ai` alone, so the Grok CLI proxy — the OAuth lane — was+ * left unnormalized. Re-probed 2026-08-27 against `cli-chat-proxy.grok.com`:+ * `web_search_preview` -> 422 `unknown variant`, `external_web_access` -> 400 on every value,+ * `search_context_size` -> 400, while `user_location` and `search_content_types` -> 200. Identical+ * to the public API, which is what makes one shared gate correct.+ */+export function normalizeXaiResponsesWebSearch(+ body: unknown,+ provider: Pick<OcxProviderConfig, "baseUrl">,+): unknown {+ if (!isXaiResponsesDestination(provider) || !isPlainObject(body)) return body;++ let next: Record<string, unknown> = body;+ if (Array.isArray(body.tools)) {+ const rewritten = normalizeToolGroup(body.tools);+ if (rewritten.changed) {+ next = { ...next };+ if (rewritten.tools.length > 0) next.tools = rewritten.tools;+ else delete next.tools;+ }+ }++ if (Array.isArray(next.input)) {+ let inputChanged = false;+ const input: unknown[] = [];+ for (const item of next.input) {+ if (!isPlainObject(item) || item.type !== "additional_tools" || !Array.isArray(item.tools)) {+ input.push(item);+ continue;+ }+ const rewritten = normalizeToolGroup(item.tools);+ if (!rewritten.changed) {+ input.push(item);+ continue;+ }+ inputChanged = true;+ if (rewritten.tools.length > 0) input.push({ ...item, tools: rewritten.tools });+ }+ if (inputChanged) next = { ...next, input };+ }++ return normalizeToolChoice(next);+}++function isLiveWebSearchTool(tool: unknown): boolean {+ return isPlainObject(tool)+ && tool.type === CODEX_WEB_SEARCH_TOOL+ && (!Object.hasOwn(tool, "external_web_access") || tool.external_web_access === true);+}++/**+ * Add xAI's hosted X search declaration without changing web-search normalization or selectors.+ * Destination classification belongs only to this opt-in injection path; the public-API+ * normalizer above intentionally retains its narrower causality boundary.+ */+export function injectXaiResponsesXSearch(+ body: unknown,+ provider: Pick<OcxProviderConfig, "baseUrl" | "xaiResponsesXSearch">,+ replayPrefixLength?: number,+): unknown {+ if (+ !isPlainObject(body)+ || !isXaiResponsesDestination(provider)+ || provider.xaiResponsesXSearch !== true+ ) return body;++ const input = Array.isArray(body.input) ? body.input : undefined;+ const inputStart = input ? currentInputStart(input.length, replayPrefixLength) : 0;+ const currentInput = input?.slice(inputStart) ?? [];+ const currentXSearchDeclared = hasToolType(body.tools, XAI_SEARCH_TOOL)+ || currentInput.some(item =>+ isPlainObject(item)+ && item.type === "additional_tools"+ && hasToolType(item.tools, XAI_SEARCH_TOOL)+ );+ if (currentXSearchDeclared) return body;++ const liveWebSearchSurvives = Array.isArray(body.tools) && body.tools.some(isLiveWebSearchTool)+ || currentInput.some(item =>+ isPlainObject(item)+ && item.type === "additional_tools"+ && Array.isArray(item.tools)+ && item.tools.some(isLiveWebSearchTool)+ );+ if (!liveWebSearchSurvives) return body;++ // Declaration does not grant selection when `tool_choice` names a specific tool or carries an+ // `allowed_tools` set that excludes x_search, so leave that selector byte-shape untouched.+ const tools = Array.isArray(body.tools) ? body.tools : [];+ return { ...body, tools: [...tools, { type: XAI_SEARCH_TOOL }] };+}diff --git a/packages/model-compat/src/upstream/lib/tool-argument-integers.ts b/packages/model-compat/src/upstream/lib/tool-argument-integers.tsnew file mode 100644index 0000000000..171bc241a2--- /dev/null+++ b/packages/model-compat/src/upstream/lib/tool-argument-integers.ts@@ -0,0 +1,253 @@+// Schema-aware repair for tool arguments whose serialized representation disagrees+// with the declared schema in a way that has exactly one faithful reading.+//+// Case 1 — integer fields arriving as integral floats (issue #1611).+//+// Grok serializes integer tool-call arguments through a float representation, so+// `yield_time_ms: 120000` leaves the provider as `120000.0`. Codex declares those+// fields as Rust integer types, so it rejects the call BEFORE running the tool:+//+// failed to parse function arguments: invalid type: floating point `120000.0`, expected u64+//+// That is a hard failure, not a degradation — the model gets no result and retries+// the same float. Nothing on the routed path reconciled argument values against the+// declared schema, so the `.0` passed straight through.+//+// The boundary this file draws is INTENT, not convenience:+// - an integral float in an integer-typed field is a representation artifact, and+// `120000.0` has exactly one integer reading, so it is repaired;+// - `1.5` in an integer field is a genuine disagreement with the schema and is left+// alone so it still fails, rather than being truncated into a plausible lie.+//+// Case 2 — string fields arriving as bare integers (issue #1938).+//+// Cursor-served models emit `{"cell_id": 4}` where the schema declares+// `{"type": "string"}`. Codex rejects the call before the tool runs (invalid type:+// integer `4`, expected a string), and the model never self-corrects, so every such+// call is a hard failure loop. A safely-integral JSON number in a string-declared+// field has exactly one faithful string reading (`4` -> `"4"`), so it is repaired+// under the same intent boundary:+// - only when the field declares `string` and no numeric type (a+// `["integer","string"]` union accepts the number as-is and is left alone);+// - a non-integral number (`4.5`) in a string field is a genuine disagreement and+// is left alone so it still fails;+// - beyond 2^53-1 the parsed value may differ from the serialized text, so the+// original bytes stay.+//+// Anything without a declared `integer`/`string` type is never touched.++/** JSON Schema subset we need; provider tool schemas are untrusted input. */+type SchemaNode = Record<string, unknown>;++function asSchema(value: unknown): SchemaNode | undefined {+ return value && typeof value === "object" && !Array.isArray(value)+ ? value as SchemaNode+ : undefined;+}++/** True when the node declares `integer`, including `["integer","null"]` unions. */+function declaresInteger(schema: SchemaNode): boolean {+ const type = schema.type;+ if (type === "integer") return true;+ return Array.isArray(type) && type.includes("integer");+}++/** True when the node declares `string`, including `["string","null"]` unions. */+function declaresString(schema: SchemaNode): boolean {+ const type = schema.type;+ if (type === "string") return true;+ return Array.isArray(type) && type.includes("string");+}++// Issue #2316: Codex advertises `multi_agent_v1__wait_agent`'s `timeout_ms` as a JSON+// Schema `number`, but its Rust runtime deserializes the field as `u64` and rejects+// `120000.0` with "invalid type: floating point `120000.0`, expected u64" before the+// tool ever runs. The schema lookup is not the problem — the error text comes from+// Codex's own deserializer, so the call reached it — the problem is that `number`+// alone never authorizes the integral-float repair below.+//+// This allowlist is deliberately one field wide. It names only what has a live+// reproduction against a real `u64`, because the repair is only unambiguous for a+// field that cannot legitimately hold a fraction. Generic names (`start`, `end`,+// `priority`, `port`) would silently rewrite a third-party tool's fractional value,+// so a new entry needs its own evidence, not a plausible-sounding name.+//+// Cursor's sibling `yield_time_ms` (src/adapters/cursor/tool-definitions.ts) is also+// declared `number`; it is NOT included here because no rejection has been captured+// against it. It gets its own change when it gets its own reproduction.+const U64_NUMBER_FIELDS = new Set(["timeout_ms"]);++// Issue #2443 / #2451: Codex Desktop's bare `wait` tool has the same schema/runtime+// split for `yield_time_ms` and `max_tokens`. Scope these names to that bare tool so a+// third-party or namespaced tool can still use fractional values legitimately.+// #2448 allowlisted the hyphenated `yield-time_ms`; live Grok 4.6 calls and the+// advertised wait schema both use the underscore form, so that name is the one+// with a captured u64 rejection. Cursor still uses the same underscore name on a+// namespaced tool; the wait-only map keeps that path byte-identical.+const U64_NUMBER_FIELDS_BY_TOOL = new Map<string, ReadonlySet<string>>([+ ["wait", new Set(["yield_time_ms", "max_tokens"])],+]);++/** True when the node accepts a JSON number (`integer` or `number`), so a numeric+ * value is already schema-valid and must not be rewritten into a string. */+function declaresNumeric(schema: SchemaNode): boolean {+ const type = schema.type;+ if (type === "integer" || type === "number") return true;+ return Array.isArray(type) && (type.includes("integer") || type.includes("number"));+}++/**+ * Resolve a local `$ref` (`#/$defs/Foo`, `#/definitions/Foo`).+ *+ * Only same-document refs are followed: a remote ref is not fetchable here, and a+ * schema we cannot resolve must leave its values untouched rather than guessed at.+ */+function resolveRef(schema: SchemaNode, root: SchemaNode, seen: Set<string>): SchemaNode | undefined {+ const ref = schema.$ref;+ if (typeof ref !== "string" || !ref.startsWith("#/")) return schema;+ if (seen.has(ref)) return undefined; // cyclic $ref: stop rather than recurse forever+ seen.add(ref);+ let node: unknown = root;+ for (const rawSegment of ref.slice(2).split("/")) {+ const segment = rawSegment.replace(/~1/g, "/").replace(/~0/g, "~");+ const current = asSchema(node);+ if (!current) return undefined;+ node = current[segment];+ }+ const resolved = asSchema(node);+ return resolved ? resolveRef(resolved, root, seen) : undefined;+}++/** Composition keywords whose branches may carry the integer declaration. */+const COMPOSITION_KEYS = ["anyOf", "oneOf", "allOf"] as const;++function compositionBranches(schema: SchemaNode): SchemaNode[] {+ const branches: SchemaNode[] = [];+ for (const key of COMPOSITION_KEYS) {+ const value = schema[key];+ if (!Array.isArray(value)) continue;+ for (const branch of value) {+ const node = asSchema(branch);+ if (node) branches.push(node);+ }+ }+ return branches;+}++/**+ * A JS number can only represent integers exactly up to 2^53-1. Beyond that a+ * rewrite would emit a silently different value, so the original text stays.+ */+function safelyIntegral(value: number): boolean {+ return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER;+}++interface CoerceResult {+ value: unknown;+ changed: boolean;+}++function coerceValue(+ value: unknown,+ schema: SchemaNode | undefined,+ root: SchemaNode,+ depth: number,+ toolName?: string,+ propertyName?: string,+): CoerceResult {+ // A hostile or deeply nested schema must not blow the stack.+ if (depth > 64) return { value, changed: false };+ const resolved = schema ? resolveRef(schema, root, new Set()) : undefined;++ if (typeof value === "number") {+ if (!resolved) return { value, changed: false };+ const branches = compositionBranches(resolved);+ // #2316: a known Codex-native u64 field counts as integer-declared even when the+ // advertised schema says `number`, but only when the field really is numeric —+ // an allowlisted name over a string-typed field is a disagreement, not a repair.+ const nativeU64Field = propertyName !== undefined+ && (+ U64_NUMBER_FIELDS.has(propertyName)+ || U64_NUMBER_FIELDS_BY_TOOL.get(toolName ?? "")?.has(propertyName) === true+ );+ const nativeU64Declared = nativeU64Field+ && (declaresNumeric(resolved) || branches.some(declaresNumeric));+ const integerDeclared = declaresInteger(resolved)+ || branches.some(declaresInteger)+ || nativeU64Declared;+ if (!integerDeclared && safelyIntegral(value)) {+ // Issue #1938: a bare integer in a string-only field has exactly one faithful+ // string reading. A field that also accepts a numeric type keeps the number.+ const stringDeclared = declaresString(resolved) || branches.some(declaresString);+ const numericDeclared = declaresNumeric(resolved) || branches.some(declaresNumeric);+ if (stringDeclared && !numericDeclared) {+ return { value: String(value), changed: true };+ }+ }+ // Not an integer field, already an integer, non-integral, or unrepresentable:+ // in every one of those cases the received value is the right thing to keep.+ if (!integerDeclared || !safelyIntegral(value)) return { value, changed: false };+ // `120000.0` and `120000` are the same JS number; the difference is only in the+ // serialized text, which is repaired by re-stringifying the parsed value.+ return { value, changed: true };+ }++ if (Array.isArray(value)) {+ const itemSchema = resolved ? asSchema(resolved.items) : undefined;+ let changed = false;+ const next = value.map(entry => {+ // Array items have no property name of their own; passing the array's key would+ // let `timeout_ms: [1.5]` inherit the allowlist. Items are judged by schema only.+ const result = coerceValue(entry, itemSchema, root, depth + 1, toolName);+ if (result.changed) changed = true;+ return result.value;+ });+ return changed ? { value: next, changed } : { value, changed: false };+ }++ const object = asSchema(value);+ if (!object) return { value, changed: false };++ const properties = resolved ? asSchema(resolved.properties) : undefined;+ const additional = resolved ? asSchema(resolved.additionalProperties) : undefined;+ let changed = false;+ const next: Record<string, unknown> = {};+ for (const [key, entry] of Object.entries(object)) {+ const childSchema = asSchema(properties?.[key]) ?? additional;+ const result = coerceValue(entry, childSchema, root, depth + 1, toolName, key);+ if (result.changed) changed = true;+ next[key] = result.value;+ }+ return changed ? { value: next, changed } : { value, changed: false };+}++/**+ * Repair integral floats in a tool-call arguments STRING against the tool's declared+ * parameter schema.+ *+ * Returns the original string unchanged when there is no schema, the payload does not+ * parse, or nothing needed repair — so an unaffected call keeps its exact bytes and+ * this stays a no-op for every provider that already emits real integers.+ */+export function coerceIntegerToolArguments(+ args: string,+ parameters: Record<string, unknown> | undefined,+ toolName?: string,+): string {+ if (!parameters || !args) return args;+ // Cheap reject: a payload with no digit cannot need either repair (integral-float+ // -> integer, or bare-integer -> string).+ if (!/\d/.test(args)) return args;+ let parsed: unknown;+ try {+ parsed = JSON.parse(args);+ } catch {+ // Malformed or still-streaming arguments are not this function's problem; the+ // existing paths already handle them.+ return args;+ }+ const root = parameters as SchemaNode;+ const result = coerceValue(parsed, root, root, 0, toolName);+ if (!result.changed) return args;+ return JSON.stringify(result.value);+}diff --git a/packages/model-compat/src/upstream/lib/translator-budget.ts b/packages/model-compat/src/upstream/lib/translator-budget.tsnew file mode 100644index 0000000000..18400eebf7--- /dev/null+++ b/packages/model-compat/src/upstream/lib/translator-budget.ts@@ -0,0 +1,400 @@+export const TRANSLATOR_MAX_CALL_ARGUMENT_BYTES = 2 * 1024 * 1024;+export const TRANSLATOR_MAX_TURN_BYTES = 32 * 1024 * 1024;+export const TRANSLATOR_MAX_SSE_EVENT_BYTES = 32 * 1024 * 1024;+export const CURSOR_MAX_CONNECT_FRAME_BYTES = 32 * 1024 * 1024;+export const CURSOR_MAX_EFFECTIVE_CONNECT_PAYLOAD_BYTES = 16 * 1024 * 1024;+export const CURSOR_TRANSPORT_MAX_BUFFERED_BYTES = 32 * 1024 * 1024;+export const CURSOR_TRANSPORT_RESUME_BYTES = 16 * 1024 * 1024;+export const CURSOR_MAX_PENDING_FRAMES = 1024;+export const CURSOR_PENDING_FRAMES_RESUME = 512;+export const MAX_PENDING_IMAGE_FULFILLMENTS = 64;+export const MAX_PENDING_OAUTH_MUTATIONS = 128;++export type TranslatorBufferKind =+ | "tool_args"+ | "retained_collectors"+ | "live_transient"+ | "reasoning"+ | "item_ids"+ | "tool_search_sources"+ | "cursor_transport"+ | "cursor_kv"+ | "request_copies";++export type ExternallyCappedKind = "passthrough_serialization" | "mcp_payload";++export class TranslatorBudgetExceededError extends Error {+ readonly code = "translation_buffer_limit";++ constructor(readonly kind: TranslatorBufferKind, readonly limitBytes: number) {+ super(`translator ${kind} buffer exceeded ${limitBytes} bytes`);+ this.name = "TranslatorBudgetExceededError";+ }+}++export function isTranslatorBudgetExceededError(error: unknown): error is TranslatorBudgetExceededError {+ return error instanceof TranslatorBudgetExceededError+ || (error instanceof Error && (error as { code?: unknown }).code === "translation_buffer_limit");+}++export interface TranslatorBudgetSnapshot {+ currentBytes: number;+ highWaterBytes: number;+ activeCalls: number;+ overflows: number;+}++export interface TranslatorBudgetOptions {+ maxCallArgumentBytes?: number;+ maxTurnBytes?: number;+}++export interface TranslatorTransientReservation {+ commitRetained(): void;+ release(): void;+}++export interface TranslatorBudget {+ openCall(id: string): void;+ closeCall(id: string): void;+ reserveTransient(+ bytes: number,+ scope: { kind: TranslatorBufferKind; callId?: string },+ ): TranslatorTransientReservation;+ chargeRetained(delta: number, scope: { kind: TranslatorBufferKind; callId?: string }): void;+ releaseRetained(bytes: number, scope: { kind: TranslatorBufferKind; callId?: string }): void;+ observeAcceptedRequestCopy(bytes: number): () => void;+ observeExternallyCapped(kind: ExternallyCappedKind, bytes: number): () => void;+ snapshot(): TranslatorBudgetSnapshot;+ dispose(): void;+}++const retainedEventOwnership = new WeakMap<object, { budget: TranslatorBudget; bytes: number }>();++/**+ * Charge one event appended to an incrementally materialized adapter-event batch.+ * The newest event owns the closing array bracket; moving that byte from the old+ * tail keeps in-order release accounting equal to the still-retained JSON array.+ */+export function retainTranslatedEvent<T extends object>(+ event: T,+ budget: TranslatorBudget,+ previousTail?: object,+): void {+ if (retainedEventOwnership.has(event)) {+ throw new Error("translated event is already retained");+ }+ if (previousTail === event) {+ throw new Error("incremental translated event tail must be a distinct object");+ }+ const previousOwnership = previousTail === undefined+ ? undefined+ : retainedEventOwnership.get(previousTail);+ if (+ previousTail !== undefined+ && (!previousOwnership || previousOwnership.budget !== budget || previousOwnership.bytes < 2)+ ) {+ throw new Error("incremental translated event tail is not retained by this budget");+ }++ const serializedBytes = Buffer.byteLength(JSON.stringify(event));+ budget.chargeRetained(serializedBytes + (previousTail === undefined ? 2 : 1), {+ kind: "retained_collectors",+ });+ if (previousOwnership) previousOwnership.bytes -= 1;+ retainedEventOwnership.set(event, { budget, bytes: serializedBytes + 2 });+}++/**+ * Charge a materialized adapter-event batch and attach its lease to the events themselves.+ * A copied event array (for example terminal-guard collection) preserves the event objects, so+ * the response builder can consume each source lease immediately after its replacement lands.+ */+export function retainTranslatedEventBatch<T extends object>(events: T[], budget: TranslatorBudget): void {+ if (events.length === 0) return;+ const serialized = events.map(event => JSON.stringify(event));+ const totalBytes = Buffer.byteLength(`[${serialized.join(",")}]`);+ budget.chargeRetained(totalBytes, { kind: "retained_collectors" });+ for (let index = 0; index < events.length; index++) {+ const delimiterBytes = index === events.length - 1 ? 2 : 1;+ retainedEventOwnership.set(events[index]!, {+ budget,+ bytes: Buffer.byteLength(serialized[index]!) + delimiterBytes,+ });+ }+}++/** Transfer one charged adapter event to the response builder's newly materialized owner. */+export function releaseTranslatedEvent(event: object, budget: TranslatorBudget): void {+ const ownership = retainedEventOwnership.get(event);+ if (!ownership || ownership.budget !== budget) return;+ retainedEventOwnership.delete(event);+ budget.releaseRetained(ownership.bytes, { kind: "retained_collectors" });+}++const liveBudgets = new Set<Budget>();+let aggregateCurrentBytes = 0;+let aggregateActiveCalls = 0;+let aggregateHighWaterBytes = 0;+let aggregateOverflows = 0;++function normalizeBytes(bytes: number): number {+ return Number.isFinite(bytes) && bytes > 0 ? Math.floor(bytes) : 0;+}++function observeAggregate(): void {+ aggregateHighWaterBytes = Math.max(aggregateHighWaterBytes, aggregateCurrentBytes);+}++class Budget implements TranslatorBudget {+ private readonly calls = new Map<string, { logicalBytes: number; physicalBytes: number }>();+ private readonly charged = new Map<TranslatorBufferKind, number>();+ private hardChargedBytes = 0;+ private observedBytes = 0;+ private currentBytes = 0;+ private highWaterBytes = 0;+ private overflowCount = 0;+ private disposed = false;++ constructor(+ private readonly maxCallArgumentBytes: number,+ private readonly maxTurnBytes: number,+ ) {}++ private chargedBytes(): number {+ return this.hardChargedBytes;+ }++ observedCurrentBytes(): number {+ return this.currentBytes;+ }++ private changed(): void {+ const nextBytes = this.hardChargedBytes + this.observedBytes;+ aggregateCurrentBytes += nextBytes - this.currentBytes;+ this.currentBytes = nextBytes;+ this.highWaterBytes = Math.max(this.highWaterBytes, nextBytes);+ observeAggregate();+ }++ private reject(kind: TranslatorBufferKind, limitBytes: number): never {+ this.overflowCount += 1;+ aggregateOverflows += 1;+ throw new TranslatorBudgetExceededError(kind, limitBytes);+ }++ private admit(kind: TranslatorBufferKind, bytes: number): number {+ const admitted = normalizeBytes(bytes);+ if (this.chargedBytes() + admitted > this.maxTurnBytes) this.reject(kind, this.maxTurnBytes);+ return admitted;+ }++ openCall(id: string): void {+ if (!this.calls.has(id)) {+ this.calls.set(id, { logicalBytes: 0, physicalBytes: 0 });+ aggregateActiveCalls += 1;+ }+ }++ closeCall(id: string): void {+ const call = this.calls.get(id);+ if (!call) return;+ this.hardChargedBytes = Math.max(0, this.hardChargedBytes - call.physicalBytes);+ this.calls.delete(id);+ aggregateActiveCalls = Math.max(0, aggregateActiveCalls - 1);+ this.changed();+ }++ reserveTransient(+ bytes: number,+ scope: { kind: TranslatorBufferKind; callId?: string },+ ): TranslatorTransientReservation {+ const admitted = normalizeBytes(bytes);+ if (scope.callId && admitted > this.maxCallArgumentBytes) {+ this.reject("tool_args", this.maxCallArgumentBytes);+ }+ this.admit(scope.kind, admitted);+ this.charged.set(scope.kind, (this.charged.get(scope.kind) ?? 0) + admitted);+ this.hardChargedBytes += admitted;+ this.changed();+ let state: "reserved" | "committed" | "released" = "reserved";+ return {+ commitRetained: () => {+ if (state !== "reserved") return;+ state = "committed";+ if (!scope.callId) return;+ const call = this.calls.get(scope.callId) ?? { logicalBytes: 0, physicalBytes: 0 };+ this.charged.set(scope.kind, Math.max(0, (this.charged.get(scope.kind) ?? 0) - admitted));+ call.logicalBytes = admitted;+ call.physicalBytes += admitted;+ this.calls.set(scope.callId, call);+ this.changed();+ },+ release: () => {+ if (state !== "reserved") return;+ state = "released";+ this.charged.set(scope.kind, Math.max(0, (this.charged.get(scope.kind) ?? 0) - admitted));+ this.hardChargedBytes = Math.max(0, this.hardChargedBytes - admitted);+ this.changed();+ },+ };+ }++ chargeRetained(delta: number, scope: { kind: TranslatorBufferKind; callId?: string }): void {+ const admitted = normalizeBytes(delta);+ if (scope.callId) {+ const call = this.calls.get(scope.callId) ?? { logicalBytes: 0, physicalBytes: 0 };+ if (call.logicalBytes + admitted > this.maxCallArgumentBytes) {+ this.reject("tool_args", this.maxCallArgumentBytes);+ }+ this.admit(scope.kind, admitted);+ call.logicalBytes += admitted;+ call.physicalBytes += admitted;+ this.calls.set(scope.callId, call);+ } else {+ this.admit(scope.kind, admitted);+ this.charged.set(scope.kind, (this.charged.get(scope.kind) ?? 0) + admitted);+ }+ this.hardChargedBytes += admitted;+ this.changed();+ }++ releaseRetained(bytes: number, scope: { kind: TranslatorBufferKind; callId?: string }): void {+ const released = normalizeBytes(bytes);+ if (scope.callId) {+ const call = this.calls.get(scope.callId);+ if (call) {+ const actual = Math.min(released, call.physicalBytes);+ call.physicalBytes -= actual;+ this.hardChargedBytes = Math.max(0, this.hardChargedBytes - actual);+ }+ } else {+ const current = this.charged.get(scope.kind) ?? 0;+ const actual = Math.min(released, current);+ this.charged.set(scope.kind, current - actual);+ this.hardChargedBytes = Math.max(0, this.hardChargedBytes - actual);+ }+ this.changed();+ }++ private observe(bytes: number): () => void {+ const observed = normalizeBytes(bytes);+ this.observedBytes += observed;+ this.changed();+ let released = false;+ return () => {+ if (released) return;+ released = true;+ this.observedBytes = Math.max(0, this.observedBytes - observed);+ this.changed();+ };+ }++ observeAcceptedRequestCopy(bytes: number): () => void {+ return this.observe(bytes);+ }++ observeExternallyCapped(_kind: ExternallyCappedKind, bytes: number): () => void {+ return this.observe(bytes);+ }++ snapshot(): TranslatorBudgetSnapshot {+ return {+ currentBytes: this.observedCurrentBytes(),+ highWaterBytes: this.highWaterBytes,+ activeCalls: this.calls.size,+ overflows: this.overflowCount,+ };+ }++ dispose(): void {+ if (this.disposed) return;+ this.disposed = true;+ aggregateActiveCalls = Math.max(0, aggregateActiveCalls - this.calls.size);+ aggregateCurrentBytes = Math.max(0, aggregateCurrentBytes - this.currentBytes);+ this.calls.clear();+ this.charged.clear();+ this.hardChargedBytes = 0;+ this.observedBytes = 0;+ this.currentBytes = 0;+ liveBudgets.delete(this);+ observeAggregate();+ }+}++export function createTranslatorBudget(options: TranslatorBudgetOptions = {}): TranslatorBudget {+ const budget = new Budget(+ options.maxCallArgumentBytes ?? TRANSLATOR_MAX_CALL_ARGUMENT_BYTES,+ options.maxTurnBytes ?? TRANSLATOR_MAX_TURN_BYTES,+ );+ liveBudgets.add(budget);+ observeAggregate();+ return budget;+}++export function translatorObservedBufferSnapshot(): {+ currentBytes: number;+ highWaterBytes: number;+ active: number;+} {+ return {+ currentBytes: aggregateCurrentBytes,+ highWaterBytes: aggregateHighWaterBytes,+ active: aggregateActiveCalls,+ };+}++/** Internal diagnostics used by focused tests; never registered with app-owned memory. */+export function translatorObservedOverflowCount(): number {+ return aggregateOverflows;+}++/** Test-only: proves owned default budgets are disposed on every stream-death path. */+export function translatorLiveBudgetCountForTests(): number {+ return liveBudgets.size;+}++/** Test-only: proves no charge survives against a disposed budget (cancel race). */+export function translatorAggregateCurrentBytesForTests(): number {+ return aggregateCurrentBytes;+}++/** Clears process-wide translator diagnostics and disposes leaked test budgets. */+export function resetTranslatorAggregateForTests(): void {+ for (const budget of liveBudgets) budget.dispose();+ aggregateCurrentBytes = 0;+ aggregateActiveCalls = 0;+ aggregateHighWaterBytes = 0;+ aggregateOverflows = 0;+}++export function finalizeTranslatorBudgetResponse(response: Response, budget: TranslatorBudget): Response {+ if (!response.body) {+ budget.dispose();+ return response;+ }+ const reader = response.body.getReader();+ let finalized = false;+ const finalize = () => {+ if (finalized) return;+ finalized = true;+ budget.dispose();+ };+ return new Response(new ReadableStream<Uint8Array>({+ async pull(controller) {+ try {+ const result = await reader.read();+ if (result.done) {+ finalize();+ controller.close();+ } else controller.enqueue(result.value);+ } catch (error) {+ finalize();+ controller.error(error);+ }+ },+ async cancel(reason) {+ try { await reader.cancel(reason); } finally { finalize(); }+ },+ }), { status: response.status, statusText: response.statusText, headers: response.headers });+}diff --git a/packages/model-compat/src/upstream/providers/xai-transport.ts b/packages/model-compat/src/upstream/providers/xai-transport.tsnew file mode 100644index 0000000000..85973343fb--- /dev/null+++ b/packages/model-compat/src/upstream/providers/xai-transport.ts@@ -0,0 +1,22 @@+import type { OcxProviderConfig } from "../types";+/** The two hosts that serve xAI's Responses API: the public API and the Grok CLI proxy. */+const XAI_RESPONSES_HOSTS = new Set(["api.x.ai", "cli-chat-proxy.grok.com"]);++/**+ * True when this provider's Responses traffic terminates at xAI itself.+ *+ * Probed 2026-08-22 one field per request: the two hosts accept and refuse exactly the same+ * web_search fields, so they are one dialect rather than two. Matching is exact-host over+ * https, which keeps lookalikes (`api.x.ai.evil.test`) and nonstandard ports out.+ */+export function isXaiResponsesDestination(provider: Pick<OcxProviderConfig, "baseUrl">): boolean {+ try {+ const url = new URL(provider.baseUrl);+ return url.protocol === "https:"+ && XAI_RESPONSES_HOSTS.has(url.hostname.toLowerCase())+ && (url.port === "" || url.port === "443");+ } catch {+ return false;+ }+}+diff --git a/packages/model-compat/src/upstream/reasoning-effort.ts b/packages/model-compat/src/upstream/reasoning-effort.tsnew file mode 100644index 0000000000..6342159d31--- /dev/null+++ b/packages/model-compat/src/upstream/reasoning-effort.ts@@ -0,0 +1,232 @@+import type { OcxProviderConfig } from "./types";+import { modelInList } from "./types";++// Descriptions mirror the upstream bundled models.json canonical wording (openai/codex PR #31684).+export const CODEX_REASONING_LEVELS: { effort: string; description: string }[] = [+ { effort: "low", description: "Fast responses with lighter reasoning" },+ { effort: "medium", description: "Balances speed and reasoning depth for everyday tasks" },+ { effort: "high", description: "Greater reasoning depth for complex problems" },+ { effort: "xhigh", description: "Extra high reasoning depth for complex problems" },+ { effort: "max", description: "Maximum reasoning depth for the hardest problems" },+ { effort: "ultra", description: "Maximum reasoning with automatic task delegation" },+];++const CODEX_REASONING_ORDER = CODEX_REASONING_LEVELS.map(l => l.effort);+const CODEX_REASONING_SET = new Set(CODEX_REASONING_ORDER);++/**+ * Sentinel wire value in reasoningEffortMap / modelReasoningEffortMap to explicitly+ * omit the reasoning_effort field from the upstream wire request (issue #2356).+ */+export const REASONING_EFFORT_OMIT_SENTINEL = "__omit__";++export function isReasoningEffortOmitted(wireEffort: string | undefined): boolean {+ return wireEffort === REASONING_EFFORT_OMIT_SENTINEL;+}++/** True when `effort` is a member of the Codex reasoning ladder (low..ultra). */+export function isCodexReasoningEffort(effort: string): boolean {+ return CODEX_REASONING_SET.has(effort);+}++/**+ * True for ladder members plus the `none`/`minimal` sentinels. Both are valid declared+ * efforts (OpenAI accepts `minimal`; Codex validates `none` against+ * `supported_reasoning_levels` for no-reasoning subagent spawns, #883/#962) but are NOT+ * part of the low..ultra ladder: they never appear in default ladders, ranks, or clamps+ * (`minimal` is mapped to `low` on the wire by requestToCodexEffort).+ */+export function isDeclaredReasoningEffort(effort: string): boolean {+ return effort === "none" || effort === "minimal" || CODEX_REASONING_SET.has(effort);+}++/**+ * Reorder any declared subset (low..ultra, plus the optional `none`/`minimal` sentinels+ * first, in that order) into canonical order and drop duplicates. Catalog+ * `supported_reasoning_levels` follow the input order and the fallback default picks the+ * first entry, so a caller-chosen order would otherwise leak into the catalog.+ */+export function canonicalizeReasoningEfforts(values: readonly string[]): string[] {+ const seen = new Set(values);+ const ordered = CODEX_REASONING_ORDER.filter(effort => seen.has(effort));+ const sentinels = ["none", "minimal"].filter(effort => seen.has(effort));+ return [...sentinels, ...ordered];+}++/**+ * Reasoning ladder accepted for the OpenAI vision sidecar. `ultra` is deliberately excluded:+ * the vision describer is a single helper call, and `ultra` would be collapsed to `max` by the+ * upstream client boundary anyway.+ */+export const VISION_REASONING_EFFORTS = ["low", "medium", "high", "xhigh", "max"] as const;+export type VisionReasoningEffort = typeof VISION_REASONING_EFFORTS[number];++/** True when `effort` is one of the vision sidecar's supported Responses reasoning levels. */+export function isVisionReasoningEffort(effort: unknown): effort is VisionReasoningEffort {+ return typeof effort === "string" && (VISION_REASONING_EFFORTS as readonly string[]).includes(effort);+}++/**+ * Normalize a persisted/configured vision reasoning value. Invalid values (hand-edited config,+ * stale files) degrade to `undefined` so the caller falls back to the documented default instead+ * of forwarding an upstream-rejected effort.+ */+export function sanitizeVisionReasoning(effort: unknown): VisionReasoningEffort | undefined {+ return isVisionReasoningEffort(effort) ? effort : undefined;+}++/** Position of `effort` in the Codex ladder (low=0 .. ultra=5), or -1 when not a ladder member. */+export function codexEffortRank(effort: string): number {+ return CODEX_REASONING_ORDER.indexOf(effort);+}++/**+ * Resolve a requested effort against the rungs a target actually supports, never+ * raising above the request.+ *+ * Returns the request itself when supported, otherwise the highest supported rung+ * at or below it, otherwise the lowest supported rung, and `undefined` when the+ * supported set contains no rankable rung at all (including the empty ladder, which+ * is how a no-reasoning model is expressed).+ *+ * This lives here rather than beside its first caller because two very different+ * planes need the same answer: the catalog advertises a combo's default effort, and+ * the request path injects one. When they disagreed, the catalog promised `max` and+ * the runtime silently sent nothing, so the provider default applied instead (#3108).+ * `reasoning-effort.ts` is a leaf — its only import is `./types` — so the request+ * path can share this without pulling the catalog plane along.+ */+export function resolveEffortAtOrBelow(+ requested: string | null | undefined,+ supported: readonly string[],+): string | undefined {+ if (!requested) return undefined;+ if (supported.includes(requested)) return requested;+ const requestedRank = codexEffortRank(requested);+ const ranked = supported+ .map(effort => ({ effort, rank: codexEffortRank(effort) }))+ .filter(item => item.rank >= 0)+ .sort((a, b) => a.rank - b.rank);+ if (ranked.length === 0) return undefined;+ const atOrBelow = ranked.filter(item => item.rank <= requestedRank);+ return atOrBelow.at(-1)?.effort ?? ranked[0]!.effort;+}++export function modelRecordValue<T>(record: Record<string, T> | undefined, modelId: string): T | undefined {+ if (!record) return undefined;+ if (Object.prototype.hasOwnProperty.call(record, modelId)) return record[modelId];+ const colon = modelId.indexOf(":");+ if (colon > 0) {+ const family = modelId.slice(0, colon);+ if (Object.prototype.hasOwnProperty.call(record, family)) return record[family];+ }+ const folded = modelId.toLowerCase();+ for (const [key, value] of Object.entries(record)) {+ if (key.toLowerCase() === folded) return value;+ }+ return undefined;+}++export function sanitizeCodexReasoningEfforts(efforts: readonly string[] | undefined): string[] | undefined {+ if (efforts === undefined) return undefined;+ const seen = new Set<string>();+ const out: string[] = [];+ for (const effort of efforts) {+ // `none`/`minimal` are valid declared sentinels, kept and sorted first (rank -1); they+ // never appear in the default ladder.+ if ((effort !== "none" && effort !== "minimal" && !CODEX_REASONING_SET.has(effort)) || seen.has(effort)) continue;+ seen.add(effort);+ out.push(effort);+ }+ return out.sort((a, b) => CODEX_REASONING_ORDER.indexOf(a) - CODEX_REASONING_ORDER.indexOf(b));+}++/**+ * Provider/model configured reasoning levels for the Codex catalog. `undefined` means “no override”,+ * while an empty array means “intentionally expose no effort control for this model”.+ */+export function configuredReasoningEfforts(provider: OcxProviderConfig, modelId: string): string[] | undefined {+ if (modelInList(provider.noReasoningModels, modelId)) return [];+ const modelEfforts = modelRecordValue(provider.modelReasoningEfforts, modelId);+ if (modelEfforts !== undefined) return healMappedTiers(provider, modelId, sanitizeCodexReasoningEfforts(modelEfforts) ?? []);+ if (provider.reasoningEfforts !== undefined) return healMappedTiers(provider, modelId, sanitizeCodexReasoningEfforts(provider.reasoningEfforts) ?? []);+ return undefined;+}++/**+ * Stale-ladder self-heal: a registry wire map is authoritative evidence of the upstream tiers+ * it can emit. Merge Codex-native map values into an older persisted ladder so newly documented+ * tiers appear without rewriting the user's config. Non-Codex values such as enabled/disabled+ * and Kimi's none sentinel are ignored here; they remain request-only wire aliases.+ */+function healMappedTiers(provider: OcxProviderConfig, modelId: string, efforts: string[]): string[] {+ if (efforts.length === 0) return efforts;+ const wireMap = reasoningEffortMapFor(provider, modelId);+ if (!wireMap) return efforts;+ const mappedTiers = Object.values(wireMap).filter(isCodexReasoningEffort);+ if (mappedTiers.length === 0) return efforts;+ return sanitizeCodexReasoningEfforts([...efforts, ...mappedTiers]) ?? efforts;+}++function requestToCodexEffort(requested: string): string | undefined {+ if (requested === "none") return undefined;+ if (requested === "minimal") return "low";+ return CODEX_REASONING_SET.has(requested) ? requested : undefined;+}++function clampToSupportedCodexEffort(requested: string, supported: readonly string[]): string | undefined {+ if (supported.length === 0) return undefined;+ const codex = requestToCodexEffort(requested);+ if (!codex) return undefined;+ if (supported.includes(codex)) return codex;++ const requestedRank = CODEX_REASONING_ORDER.indexOf(codex);+ let best = supported[0];+ let bestRank = CODEX_REASONING_ORDER.indexOf(best);+ for (const effort of supported) {+ const rank = CODEX_REASONING_ORDER.indexOf(effort);+ if (rank <= requestedRank && rank >= bestRank) {+ best = effort;+ bestRank = rank;+ }+ }+ // If every supported tier is above the requested tier, choose the lowest supported tier.+ return best;+}++export function reasoningEffortMapFor(provider: OcxProviderConfig, modelId: string): Record<string, string> | undefined {+ return modelRecordValue(provider.modelReasoningEffortMap, modelId) ?? provider.reasoningEffortMap;+}++/**+ * Translate Codex's reasoning label into the provider's real wire value. Prefer identity labels+ * (`xhigh` stays `xhigh`, `max` stays `max`); provider maps are only for real upstream aliases.+ */+export function mapReasoningEffort(provider: OcxProviderConfig, modelId: string, requested: string | undefined): string | undefined {+ if (!requested) return undefined;+ if (modelInList(provider.noReasoningModels, modelId)) return undefined;++ // Upstream codex-rs converts ultra -> max before ANY provider request (core/src/client.rs+ // `reasoning_effort_for_request`), so "ultra" must never influence the provider wire — not even+ // through a raw alias. Apply the boundary before alias/clamp resolution.+ const boundary = requested === "ultra" ? "max" : requested;++ const wireMap = reasoningEffortMapFor(provider, modelId);+ if (wireMap && Object.prototype.hasOwnProperty.call(wireMap, boundary)) {+ const mapped = wireMap[boundary];+ return mapped === REASONING_EFFORT_OMIT_SENTINEL ? undefined : mapped;+ }++ const supported = configuredReasoningEfforts(provider, modelId);+ const codexEffort = supported !== undefined ? clampToSupportedCodexEffort(boundary, supported) : requestToCodexEffort(boundary);+ if (!codexEffort) return undefined;++ // Belt for the odd config where the supported ladder is ultra-only and the clamp lands on it.+ const wire = codexEffort === "ultra" ? "max" : codexEffort;+ if (wireMap && Object.prototype.hasOwnProperty.call(wireMap, wire)) {+ const mapped = wireMap[wire];+ return mapped === REASONING_EFFORT_OMIT_SENTINEL ? undefined : mapped;+ }+ if (wire === REASONING_EFFORT_OMIT_SENTINEL) return undefined;+ return wire;+}diff --git a/packages/model-compat/src/upstream/responses/apply-patch-envelope.ts b/packages/model-compat/src/upstream/responses/apply-patch-envelope.tsnew file mode 100644index 0000000000..5763084170--- /dev/null+++ b/packages/model-compat/src/upstream/responses/apply-patch-envelope.ts@@ -0,0 +1,109 @@+// Representation repair for top-level Codex apply_patch custom-tool payloads.+//+// Some routed models decorate the first and last lines as+// `*** Begin Patch ***` / `*** End Patch ***`. Codex rejects those otherwise+// valid custom-tool payloads. Repair is deliberately limited to a complete,+// structurally recognizable top-level patch: arbitrary `exec` JavaScript is+// caller-authored executable input and must remain byte-identical.+//+// This is the same intent boundary as `src/lib/tool-argument-integers.ts`:+// repair the one faithful reading, leave genuine patch content alone.+//+// One accepted exception, added 2026-09-05: a body that is ITSELF one complete+// operation-bearing envelope, submitted as the `exec` body. That shape is never valid+// JavaScript — `*** Begin Patch` fails to parse at the leading `**` — so it has zero+// executable readings and exactly one faithful one. `isCompletePatchEnvelope` recognizes+// it and the CALLERS retarget it to the apply_patch helper; the repair functions here are+// unchanged and still return every exec body byte-identical. JavaScript that merely+// mentions an envelope keeps a real executable reading and is left alone.+// See devlog/_plan/260905_apply_patch_envelope_gap.++const PATCH_BEGIN = "*** Begin Patch";+const PATCH_END = "*** End Patch";+const TOP_LEVEL_PATCH_ENVELOPE = /^(\*\*\* Begin Patch(?: \*\*\*)?)(\r?\n)([\s\S]*)(\r?\n)(\*\*\* End Patch(?: \*\*\*)?)(\r?\n)?$/;+const PATCH_OPERATION_LINE = /^\*\*\* (?:Add|Update|Delete) File: .+$/m;++/** Unwrap the `{input:string}` function-call wrapper used for freeform tools. */+export function unwrapFreeformToolInput(argumentsText: unknown): string {+ if (typeof argumentsText !== "string") return "";+ try {+ const parsed: unknown = JSON.parse(argumentsText);+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {+ const input = (parsed as { input?: unknown }).input;+ if (typeof input === "string") return input;+ }+ } catch {+ // The string is the freeform body, not nested JSON.+ }+ return argumentsText;+}++/**+ * Strip trailing `***` only from the outer lines of one complete patch.+ * Internal patch content, incomplete envelopes, and non-patch text are exact+ * pass-throughs.+ */+export function normalizeApplyPatchDelimiters(text: string): string {+ const match = TOP_LEVEL_PATCH_ENVELOPE.exec(text);+ if (!match) return text;+ const [, begin, beginBreak, body, endBreak, end, trailingBreak = ""] = match;+ if (!PATCH_OPERATION_LINE.test(body)) return text;+ if (begin === PATCH_BEGIN && end === PATCH_END) return text;+ return `${PATCH_BEGIN}${beginBreak}${body}${endBreak}${PATCH_END}${trailingBreak}`;+}++/**+ * True when a body is one COMPLETE top-level patch envelope carrying a real file+ * operation.+ *+ * A code-mode `exec` body is JavaScript, and this shape is never valid JavaScript: a+ * leading `*** Begin Patch` fails to parse at the `**`. So a body satisfying this+ * predicate cannot be a program the caller meant to run, which is what makes reading it+ * as an apply_patch call the one faithful reading rather than a guess.+ *+ * Deliberately strict, and reusing the same two checks `normalizeApplyPatchDelimiters`+ * uses: a second, looser notion of "looks like a patch" is how a repair boundary drifts.+ * JavaScript that merely CONTAINS an envelope in a string, template, or comment fails the+ * anchored match and is left alone.+ */+export function isCompletePatchEnvelope(text: string): boolean {+ const match = TOP_LEVEL_PATCH_ENVELOPE.exec(text);+ if (!match) return false;+ return PATCH_OPERATION_LINE.test(match[3] ?? "");+}++/**+ * True when a PARTIAL buffer could still grow into a complete patch envelope.+ *+ * Streaming decides per delta, before the body is complete, while+ * `isCompletePatchEnvelope` can only answer once it is. Without this the bridge would+ * stream raw envelope bytes and then replace them with compiled helper JavaScript at+ * completion — the rewind that path explicitly refuses to perform.+ *+ * Deliberately one-sided: it holds a buffer that MIGHT become an envelope and never+ * claims one will. A held buffer that turns out to be something else still reaches the+ * client in the authoritative completed item; only the live preview is skipped.+ */+export function mayBecomePatchEnvelope(text: string): boolean {+ if (text === "") return false;+ return text.startsWith(PATCH_BEGIN) || PATCH_BEGIN.startsWith(text);+}++/**+ * Repair freeform input before Codex sees it.+ *+ * Only a bare or reserved-`functions` `apply_patch` payload may receive delimiter+ * repair. Remote namespaces own their grammar; those bodies and every other+ * freeform input are unwrapped and left byte-exact.+ */+export function repairFreeformToolInput(+ argumentsText: unknown,+ toolName = "",+ namespace?: string,+): string {+ const unwrapped = unwrapFreeformToolInput(argumentsText);+ const ownsApplyPatchGrammar = namespace === undefined || namespace === "functions";+ return ownsApplyPatchGrammar && toolName === "apply_patch"+ ? normalizeApplyPatchDelimiters(unwrapped)+ : unwrapped;+}diff --git a/packages/model-compat/src/upstream/responses/code-mode-helper-compat.ts b/packages/model-compat/src/upstream/responses/code-mode-helper-compat.tsnew file mode 100644index 0000000000..726c5dcf19--- /dev/null+++ b/packages/model-compat/src/upstream/responses/code-mode-helper-compat.ts@@ -0,0 +1,91 @@+import {+ isCompletePatchEnvelope,+ normalizeApplyPatchDelimiters,+ unwrapFreeformToolInput,+} from "./apply-patch-envelope";+import { declaresCodeModeExec } from "../types/tools";++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}++function unwrapPatchInput(value: string): string {+ try {+ const parsed: unknown = JSON.parse(value);+ if (isPlainObject(parsed)) {+ if (typeof parsed.input === "string") return parsed.input;+ if (typeof parsed.patch === "string") return parsed.patch;+ }+ } catch {+ // Native custom calls carry the patch body directly.+ }+ return value;+}++/**+ * Convert a nested Code Mode helper call into unified-exec JavaScript.+ *+ * Parsed values are serialized as data, never interpolated as source, so command and patch text+ * cannot escape the generated call. Invalid structured helper payloads are also passed as data so+ * nested-tool validation can reject them without evaluating provider text as JavaScript.+ */+export function compileCodeModeHelperInput(argumentsText: unknown, toolName: string): string {+ if (typeof argumentsText !== "string") return "";+ if (toolName === "apply_patch") {+ const patch = normalizeApplyPatchDelimiters(unwrapPatchInput(argumentsText));+ return `const result = await tools.apply_patch(${JSON.stringify(patch)});\ntext(result);`;+ }+ let parsed: unknown = argumentsText;+ try {+ parsed = JSON.parse(argumentsText);+ } catch {+ // Keep malformed provider text as data rather than executable source.+ }+ const args: unknown = isPlainObject(parsed) ? { ...parsed } : parsed;+ if (+ toolName === "shell_command"+ && isPlainObject(args)+ && typeof args.command === "string"+ && args.cmd === undefined+ ) {+ args.cmd = args.command;+ delete args.command;+ }+ if (toolName === "write_stdin") {+ return `const result = await tools.write_stdin(${JSON.stringify(args)});\ntext(result);`;+ }+ return `const result = await tools.exec_command(${JSON.stringify(args)});\ntext(result);`;+}++/**+ * Resolve the effective code-mode helper for one freeform call.+ *+ * `codeModeHelperName` already covers the NAME-based case: a provider emitted+ * `apply_patch` under a declared `exec` catalog, so `normalizeDeclaredToolName` rewrote+ * the name and recorded the original. That decision happens at tool-call start, before+ * any arguments exist, so it cannot see a provider that got the NAME right and the BODY+ * wrong.+ *+ * This adds that second case: the name is already `exec` so nothing was rewritten, but+ * the body is a complete patch envelope and therefore cannot be the JavaScript that+ * `exec` runs. Same inference the name-based path makes, drawn from the payload.+ *+ * Returns undefined for everything else, including JavaScript that merely mentions a+ * patch envelope — that body is a real program and is forwarded byte-identical.+ */+export function resolveCodeModeHelperName(+ codeModeHelperName: string | undefined,+ toolName: string,+ argumentsText: unknown,+ namespace?: string,+ declaredNames?: ReadonlySet<string>,+): string | undefined {+ if (codeModeHelperName) return codeModeHelperName;+ if (toolName !== "exec" || namespace !== undefined) return undefined;+ // `exec` is a name, not a guarantee. Without a catalog that is genuinely code mode, a+ // caller-defined `exec` could legitimately take patch text, and handing it generated+ // `tools.apply_patch(...)` JavaScript would be the mis-route this repair exists to avoid.+ if (!declaresCodeModeExec(declaredNames)) return undefined;+ if (typeof argumentsText !== "string" || argumentsText === "") return undefined;+ return isCompletePatchEnvelope(unwrapFreeformToolInput(argumentsText)) ? "apply_patch" : undefined;+}diff --git a/packages/model-compat/src/upstream/responses/compaction.ts b/packages/model-compat/src/upstream/responses/compaction.tsnew file mode 100644index 0000000000..dc2beb8a0d--- /dev/null+++ b/packages/model-compat/src/upstream/responses/compaction.ts@@ -0,0 +1,10 @@+const COMPACTION_ITEM_TYPES: ReadonlySet<string> = new Set([+ "compaction",+ "compaction_summary",+ "context_compaction",+]);++export function isCompactionItemType(type: unknown): boolean {+ return typeof type === "string" && COMPACTION_ITEM_TYPES.has(type);+}+diff --git a/packages/model-compat/src/upstream/responses/custom-tool-compat.ts b/packages/model-compat/src/upstream/responses/custom-tool-compat.tsnew file mode 100644index 0000000000..d92df9a14e--- /dev/null+++ b/packages/model-compat/src/upstream/responses/custom-tool-compat.ts@@ -0,0 +1,403 @@+import { namespacedToolName, normalizeDeclaredToolName } from "../types";+import {+ normalizeApplyPatchDelimiters,+ repairFreeformToolInput,+ unwrapFreeformToolInput,+} from "./apply-patch-envelope";+import { compileCodeModeHelperInput, resolveCodeModeHelperName } from "./code-mode-helper-compat";+import { collectResponsesToolGroups } from "./tool-groups";++const ROUTED_CUSTOM_TOOL_PASSTHROUGH = new Set(["apply_patch"]);+const BUILTIN_FUNCTIONS_NAMESPACE = "functions";++function routedCustomToolPassesThrough(+ name: string,+ supportsResponsesCustomTools: boolean | undefined,+): boolean {+ return supportsResponsesCustomTools !== false && ROUTED_CUSTOM_TOOL_PASSTHROUGH.has(name);+}++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}++function customToolWireName(namespace: string | undefined, name: string): string {+ return namespace === BUILTIN_FUNCTIONS_NAMESPACE ? name : namespacedToolName(namespace, name);+}++function toolChoiceAllowsRoutedCustomTool(+ body: unknown,+ wireName: string,+ candidateNames: ReadonlySet<string>,+): boolean {+ if (!isPlainObject(body)) return true;+ const choice = body.tool_choice;+ if (choice === undefined || choice === null || choice === "auto" || choice === "required") {+ return true;+ }+ if (choice === "none") return false;+ if (!isPlainObject(choice)) return true;++ const selectorAllows = (selector: unknown): boolean => {+ if (!isPlainObject(selector) || typeof selector.name !== "string") return false;+ if (selector.type !== "custom") return false;+ if (typeof selector.namespace === "string") {+ return customToolWireName(selector.namespace, selector.name) === wireName;+ }+ if (selector.name === wireName) return true;+ const suffix = `__${selector.name}`;+ const candidates = [...candidateNames].filter(name => name.endsWith(suffix));+ return candidates.length === 1 && candidates[0] === wireName;+ };++ if (choice.type === "function" || choice.type === "custom") return selectorAllows(choice);+ if (choice.type === "allowed_tools" && Array.isArray(choice.tools)) {+ return choice.tools.some(selectorAllows);+ }+ return false;+}++/** Final upstream identity of a call, including a namespace restored by an earlier rewrite. */+export function routedCustomToolWireName(value: unknown): string | undefined {+ if (!isPlainObject(value) || typeof value.name !== "string") return undefined;+ return customToolWireName(+ typeof value.namespace === "string" ? value.namespace : undefined,+ value.name,+ );+}++/** Resolve a provider-emitted wire name to the routed custom tool the client declared. */+export function routedCustomToolTargetName(+ value: unknown,+ names: ReadonlySet<string>,+ declaredNames?: ReadonlySet<string>,+): string | undefined {+ const wireName = routedCustomToolWireName(value);+ if (wireName === undefined) return undefined;+ if (names.has(wireName)) return wireName;+ if (!isPlainObject(value) || typeof value.namespace === "string") return undefined;+ const normalized = normalizeDeclaredToolName(wireName, declaredNames);+ return normalized !== wireName && names.has(normalized) ? normalized : undefined;+}++/**+ * Names of custom declarations after namespace lowering. The selection flag separates converted+ * names from native passthrough names while keeping same-named function and custom children distinct.+ */+function collectRoutedCustomToolWireNames(+ body: unknown,+ supportsResponsesCustomTools?: boolean,+ passthrough = false,+): Set<string> {+ const names = new Set<string>();+ const groups = collectResponsesToolGroups(body);+ const bareWireNames = new Set<string>();+ for (const group of groups) {+ for (const tool of group) {+ if (+ isPlainObject(tool)+ && tool.type !== "namespace"+ && typeof tool.name === "string"+ ) bareWireNames.add(tool.name);+ }+ }++ for (const group of groups) {+ for (const tool of group) {+ if (!isPlainObject(tool)) continue;+ if (+ tool.type === "custom"+ && typeof tool.name === "string"+ && routedCustomToolPassesThrough(tool.name, supportsResponsesCustomTools) === passthrough+ ) {+ names.add(tool.name);+ continue;+ }+ if (tool.type !== "namespace" || typeof tool.name !== "string" || !Array.isArray(tool.tools)) {+ continue;+ }+ for (const child of tool.tools) {+ if (+ isPlainObject(child)+ && child.type === "custom"+ && typeof child.name === "string"+ && routedCustomToolPassesThrough(child.name, supportsResponsesCustomTools) === passthrough+ && (!passthrough || tool.name === BUILTIN_FUNCTIONS_NAMESPACE)+ && !(tool.name === BUILTIN_FUNCTIONS_NAMESPACE && bareWireNames.has(child.name))+ ) names.add(customToolWireName(tool.name, child.name));+ }+ }+ }+ return names;+}+export function customToolItemId(id: unknown): unknown {+ if (typeof id !== "string") return id;+ return id.startsWith("fc_") ? `ctc_${id.slice(3)}` : id;+}++export function collectRoutedCustomToolNames(+ body: unknown,+ supportsResponsesCustomTools?: boolean,+): Set<string> {+ const names = new Set<string>();+ const visit = (value: unknown): void => {+ if (Array.isArray(value)) {+ for (const entry of value) visit(entry);+ return;+ }+ if (!isPlainObject(value)) return;+ if (+ value.type === "custom"+ && typeof value.name === "string"+ && !routedCustomToolPassesThrough(value.name, supportsResponsesCustomTools)+ ) {+ names.add(value.name);+ }+ // Only protocol containers contain declarations; schemas, metadata and tool payloads+ // can legitimately contain {type: "custom", name: ...} as literal user data.+ for (const key of ["tools", "input", "tool_choice"]) visit(value[key]);+ };+ visit(body);+ return names;+}++function collectConvertedCallIds(value: unknown, names: ReadonlySet<string>, out: Set<string>): void {+ if (Array.isArray(value)) {+ for (const entry of value) collectConvertedCallIds(entry, names, out);+ return;+ }+ if (!isPlainObject(value)) return;+ if (+ (value.type === "custom_tool_call" || value.type === "function_call")+ && typeof value.name === "string"+ && names.has(value.name)+ && typeof value.call_id === "string"+ ) {+ out.add(value.call_id);+ }+ if (Array.isArray(value.input)) collectConvertedCallIds(value.input, names, out);+}++function rewriteForUpstream(+ value: unknown,+ names: ReadonlySet<string>,+ callIds: ReadonlySet<string>,+): unknown {+ if (Array.isArray(value)) return value.map(entry => rewriteForUpstream(entry, names, callIds));+ if (!isPlainObject(value)) return value;++ if (value.type === "custom" && typeof value.name === "string" && names.has(value.name)) {+ const { format: _format, ...rest } = value;+ const isDefinition = typeof value.description === "string"+ || isPlainObject(value.format)+ || isPlainObject(value.parameters);+ if (!isDefinition) return { ...rest, type: "function" };+ const inputDescription = value.name === "exec"+ ? "JavaScript source for unified exec. Use await tools.exec_command(...) for shell commands and text(...) to return textual output; do not provide a bare shell command."+ : "Raw input for this client-executed custom tool.";+ return {+ ...rest,+ type: "function",+ parameters: {+ type: "object",+ properties: {+ input: {+ type: "string",+ description: inputDescription,+ },+ },+ required: ["input"],+ additionalProperties: false,+ },+ };+ }++ if (+ value.type === "custom_tool_call"+ && typeof value.name === "string"+ && names.has(value.name)+ ) {+ const { input, id: _id, ...rest } = value;+ return {+ ...rest,+ type: "function_call",+ arguments: JSON.stringify({ input: typeof input === "string" ? input : "" }),+ };+ }++ if (+ value.type === "custom_tool_call_output"+ && typeof value.call_id === "string"+ && callIds.has(value.call_id)+ ) {+ return { ...value, type: "function_call_output" };+ }++ let changed = false;+ const next: Record<string, unknown> = {};+ for (const [key, entry] of Object.entries(value)) {+ const rewritten = ["tools", "input", "tool_choice"].includes(key)+ ? rewriteForUpstream(entry, names, callIds) : entry;+ next[key] = rewritten;+ changed ||= rewritten !== entry;+ }+ return changed ? next : value;+}++export function rewriteRoutedCustomToolsForUpstream(+ body: unknown,+ supportsResponsesCustomTools?: boolean,+): {+ body: unknown;+ names: Set<string>;+ repairNames: Set<string>;+} {+ const conversionNames = collectRoutedCustomToolNames(body, supportsResponsesCustomTools);+ const names = collectRoutedCustomToolWireNames(body, supportsResponsesCustomTools);+ const repairNames = collectRoutedCustomToolWireNames(body, supportsResponsesCustomTools, true);+ for (const name of repairNames) {+ if (!toolChoiceAllowsRoutedCustomTool(body, name, repairNames)) repairNames.delete(name);+ }+ if (conversionNames.size === 0) return { body, names, repairNames };+ const callIds = new Set<string>();+ collectConvertedCallIds(body, conversionNames, callIds);+ return { body: rewriteForUpstream(body, conversionNames, callIds), names, repairNames };+}++export function restoreRoutedCustomCalls(+ value: unknown,+ names: ReadonlySet<string>,+ repairNames: ReadonlySet<string> = new Set(),+ declaredNames?: ReadonlySet<string>,+): { value: unknown; changed: boolean } {+ if (!isPlainObject(value)) return { value, changed: false };++ const restoreItem = (item: unknown): { value: unknown; changed: boolean } => {+ if (!isPlainObject(item)) return { value: item, changed: false };+ const wireName = routedCustomToolWireName(item);+ const targetName = routedCustomToolTargetName(item, names, declaredNames);+ if (+ (item.type === "function_call" || item.type === "custom_tool_call")+ && typeof item.name === "string"+ && wireName !== undefined+ && targetName !== undefined+ ) {+ const sourceInput = item.type === "function_call" ? item.arguments : item.input;+ const aliased = targetName !== wireName;+ const itemNamespace = typeof item.namespace === "string" ? item.namespace : undefined;+ // Name-based alias first; otherwise let a raw patch envelope submitted as the `exec`+ // body resolve to the same apply_patch helper (devlog/_plan/260905_apply_patch_envelope_gap).+ const helper = aliased && sourceInput !== ""+ ? item.name+ : resolveCodeModeHelperName(undefined, targetName, sourceInput, itemNamespace, declaredNames);+ // Native custom input is already the tool's raw grammar. Only a recognized+ // helper/envelope may reinterpret it; a JSON-looking native body is not a wrapper.+ if (item.type === "custom_tool_call" && !aliased && !helper) {+ const input = repairNames.has(wireName) && typeof sourceInput === "string"+ ? normalizeApplyPatchDelimiters(sourceInput)+ : sourceInput;+ return input !== sourceInput+ ? { value: { ...item, input }, changed: true }+ : { value: item, changed: false };+ }+ const restored: Record<string, unknown> = {+ ...item,+ type: "custom_tool_call",+ id: customToolItemId(item.id),+ name: aliased ? targetName : item.name,+ input: helper+ ? compileCodeModeHelperInput(sourceInput, helper)+ : repairFreeformToolInput(+ sourceInput,+ targetName,+ itemNamespace,+ ),+ };+ delete restored.arguments;+ if (aliased) delete restored.namespace;+ return { value: restored, changed: true };+ }+ if (+ item.type === "custom_tool_call"+ && typeof item.name === "string"+ && wireName !== undefined+ && repairNames.has(wireName)+ && typeof item.input === "string"+ ) {+ const input = normalizeApplyPatchDelimiters(item.input);+ if (input !== item.input) return { value: { ...item, input }, changed: true };+ }+ return { value: item, changed: false };+ };++ const restoreOutput = (output: unknown): { value: unknown; changed: boolean } => {+ if (!Array.isArray(output)) return { value: output, changed: false };+ let changed = false;+ const restored = output.map(item => {+ const result = restoreItem(item);+ changed ||= result.changed;+ return result.value;+ });+ return changed ? { value: restored, changed: true } : { value: output, changed: false };+ };++ let changed = false;+ const restored: Record<string, unknown> = { ...value };+ const output = restoreOutput(value.output);+ if (output.changed) {+ restored.output = output.value;+ changed = true;+ }++ if (+ (value.type === "response.output_item.added" || value.type === "response.output_item.done")+ && isPlainObject(value.item)+ ) {+ const item = restoreItem(value.item);+ if (item.changed) {+ restored.item = item.value;+ changed = true;+ }+ }++ if (+ typeof value.type === "string"+ && value.type.startsWith("response.")+ && isPlainObject(value.response)+ ) {+ const response = restoreRoutedCustomCalls(value.response, names, repairNames, declaredNames);+ if (response.changed) {+ restored.response = response.value;+ changed = true;+ }+ }++ return changed ? { value: restored, changed: true } : { value, changed: false };+}++export function restoreRoutedCustomCallsInJson(+ text: string,+ names: ReadonlySet<string>,+ repairNames: ReadonlySet<string> = new Set(),+ declaredNames?: ReadonlySet<string>,+): string {+ if (names.size === 0 && repairNames.size === 0) return text;+ let payload: unknown;+ try {+ payload = JSON.parse(text);+ } catch {+ return text;+ }+ const restored = restoreRoutedCustomCalls(payload, names, repairNames, declaredNames);+ return restored.changed ? JSON.stringify(restored.value) : text;+}++export function unwrapRoutedCustomToolArguments(+ argumentsText: unknown,+ toolName = "",+ namespace?: string,+): string {+ return toolName+ ? repairFreeformToolInput(argumentsText, toolName, namespace)+ : unwrapFreeformToolInput(argumentsText);+}diff --git a/packages/model-compat/src/upstream/responses/function-call-compat.ts b/packages/model-compat/src/upstream/responses/function-call-compat.tsnew file mode 100644index 0000000000..c4888cf1f7--- /dev/null+++ b/packages/model-compat/src/upstream/responses/function-call-compat.ts@@ -0,0 +1,173 @@+import { coerceIntegerToolArguments } from "../lib/tool-argument-integers";+import { namespacedToolName } from "../types/tools";+import { rewriteRoutedNamespaceToolsForUpstream } from "./namespace-tool-compat";+import { collectResponsesToolGroups } from "./tool-groups";++export interface FunctionCallRepairSchema {+ name: string;+ namespace?: string;+ parameters?: Record<string, unknown>;+}++/** Keys are canonical original identities, never a bare-name fallback for a namespace. */+export type FunctionCallRepairSchemas = ReadonlyMap<string, FunctionCallRepairSchema>;++function isObject(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === "object" && !Array.isArray(value);+}++/** JSON object member order is immaterial; array elements retain their exact order. */+function sameSchemaValue(left: unknown, right: unknown): boolean {+ if (left === right) return true;+ if (Array.isArray(left) || Array.isArray(right)) {+ return Array.isArray(left) && Array.isArray(right) && left.length === right.length+ && left.every((value, index) => sameSchemaValue(value, right[index]));+ }+ if (!isObject(left) || !isObject(right)) return false;+ const keys = Object.keys(left);+ return keys.length === Object.keys(right).length+ && keys.every(key => Object.hasOwn(right, key) && sameSchemaValue(left[key], right[key]));+}++function namespaceOf(value: unknown): string | undefined {+ return typeof value === "string" && value !== "functions" ? value : undefined;+}++function selectorAllows(+ selector: unknown,+ lowered: unknown,+ wireName: string,+ identity: FunctionCallRepairSchema,+): boolean {+ if (!isObject(selector) || selector.type !== "function" || typeof selector.name !== "string") return false;+ if ("namespace" in selector) {+ if (typeof selector.namespace !== "string" || selector.namespace.length === 0) return false;+ return namespaceOf(selector.namespace) === identity.namespace && selector.name === identity.name;+ }+ return isObject(lowered) && lowered.type === "function" && lowered.name === wireName;+}++/** Caller supplies currentTurnWireToolCatalogBody BEFORE provider schema lowering. */+export function collectFunctionCallRepairSchemas(body: unknown): Map<string, FunctionCallRepairSchema> {+ const schemas = new Map<string, FunctionCallRepairSchema>();+ if (!isObject(body)) return schemas;+ const groups = collectResponsesToolGroups(body);+ if (Array.isArray(body.input)) {+ for (const entry of body.input) {+ if (isObject(entry) && entry.type === "tool_search_output" && Array.isArray(entry.tools)) groups.push(entry.tools);+ }+ }+ // Reuse namespace selector resolution, retaining schemas from the original objects below.+ // This local catalog view includes loaded definitions without revisiting replay history or+ // teaching the shared tool-group collector a new transport-wide interpretation.+ const lowered = rewriteRoutedNamespaceToolsForUpstream({ ...body, tools: groups.flat(), input: [] }).body;+ const choice = body.tool_choice;+ const loweredChoice = isObject(lowered) ? lowered.tool_choice : undefined;+ const occupied = new Map<string, { kind: unknown; identity: FunctionCallRepairSchema } | null>();+ const register = (tool: unknown, namespace?: string): void => {+ if (!isObject(tool) || typeof tool.name !== "string" || tool.name.length === 0) return;+ const identity: FunctionCallRepairSchema = {+ name: tool.name,+ ...(namespace ? { namespace } : {}),+ ...(isObject(tool.parameters) ? { parameters: tool.parameters } : {}),+ };+ const key = namespacedToolName(namespace, tool.name);+ if (occupied.has(key)) {+ const previous = occupied.get(key);+ // Conflicting duplicate declarations cannot choose a schema by insertion order.+ if (!previous || previous.kind !== tool.type+ || previous.identity.namespace !== namespace+ || previous.identity.name !== tool.name+ || !sameSchemaValue(previous.identity.parameters, identity.parameters)) {+ occupied.set(key, null);+ }+ } else occupied.set(key, { kind: tool.type, identity });+ };+ for (const group of groups) {+ for (const tool of group) {+ if (!isObject(tool)) continue;+ if (tool.type === "namespace") {+ if (typeof tool.name !== "string" || !tool.name || !Array.isArray(tool.tools)) continue;+ for (const child of tool.tools) register(child, namespaceOf(tool.name));+ } else if (tool.type === "function" && isObject(tool.function)) {+ register({ ...tool.function, type: "function" });+ } else register(tool);+ }+ }+ for (const [key, entry] of occupied) {+ if (!entry || entry.kind !== "function") continue;+ let allowed = choice === undefined || choice === "auto" || choice === "required";+ if (isObject(choice)) {+ if (choice.type === "allowed_tools" && Array.isArray(choice.tools)) {+ const selectors = isObject(loweredChoice) && Array.isArray(loweredChoice.tools) ? loweredChoice.tools : [];+ allowed = choice.tools.some((selector, index) => selectorAllows(selector, selectors[index], key, entry.identity));+ } else allowed = selectorAllows(choice, loweredChoice, key, entry.identity);+ }+ if (allowed) schemas.set(key, entry.identity);+ }+ return schemas;+}++function repairItem(item: unknown, schemas: FunctionCallRepairSchemas, completed: boolean): unknown {+ if (!isObject(item) || item.type !== "function_call" || typeof item.name !== "string"+ || typeof item.arguments !== "string") return item;+ if (item.status !== "completed" && !(item.status === undefined && completed)) return item;+ if ("namespace" in item && (typeof item.namespace !== "string" || !item.namespace)) return item;+ const namespace = namespaceOf(item.namespace);+ const schema = schemas.get(namespacedToolName(namespace, item.name));+ if (!schema) return item;+ // An explicit namespace is an identity coordinate, not another spelling to guess at.+ if ("namespace" in item && (schema.namespace !== namespace || schema.name !== item.name)) return item;+ const raw = item.arguments;+ if (raw !== "") {+ try {+ let unsafe = false;+ JSON.parse(raw, (_key, value: unknown) => {+ if (typeof value === "number" && (!Number.isFinite(value)+ || (Number.isInteger(value) && !Number.isSafeInteger(value)))) unsafe = true;+ return value;+ });+ // Re-stringifying another repaired field must not round an unsafe sibling number.+ if (unsafe) return item;+ } catch { return item; }+ }+ const argumentsText = coerceIntegerToolArguments(raw || "{}", schema.parameters, schema.namespace ? undefined : schema.name);+ return argumentsText === raw ? item : { ...item, arguments: argumentsText };+}++/** Only executable completion slots are visited; metadata and custom input are opaque. */+export function repairFunctionCalls(+ value: unknown,+ schemas: FunctionCallRepairSchemas,+): { value: unknown; changed: boolean } {+ if (schemas.size === 0 || !isObject(value)) return { value, changed: false };+ if (typeof value.status === "string" && ["failed", "incomplete", "cancelled", "in_progress", "queued"].includes(value.status)) return { value, changed: false };+ let next: unknown = value;+ if (value.type === "function_call") next = repairItem(value, schemas, false);+ else if (value.type === "response.output_item.done") {+ const item = repairItem(value.item, schemas, true);+ if (item !== value.item) next = { ...value, item };+ } else if (value.type === "response.completed" && isObject(value.response)) {+ const response = value.response;+ if ((response.status === undefined || response.status === "completed") && Array.isArray(response.output)) {+ const original = response.output;+ const output = original.map(item => repairItem(item, schemas, true));+ if (output.some((item, index) => item !== original[index])) next = { ...value, response: { ...response, output } };+ }+ } else if (typeof value.type !== "string" || !value.type.startsWith("response.")) {+ if (Array.isArray(value.output)) {+ const original = value.output;+ const output = original.map(item => repairItem(item, schemas, value.status === "completed"));+ if (output.some((item, index) => item !== original[index])) next = { ...value, output };+ }+ }+ return { value: next, changed: next !== value };+}++export function repairFunctionCallsInJson(text: string, schemas: FunctionCallRepairSchemas): string {+ if (schemas.size === 0) return text;+ let payload: unknown;+ try { payload = JSON.parse(text); } catch { return text; }+ const repaired = repairFunctionCalls(payload, schemas);+ return repaired.changed ? JSON.stringify(repaired.value) : text;+}diff --git a/packages/model-compat/src/upstream/responses/namespace-tool-compat.ts b/packages/model-compat/src/upstream/responses/namespace-tool-compat.tsnew file mode 100644index 0000000000..24b26e8a2e--- /dev/null+++ b/packages/model-compat/src/upstream/responses/namespace-tool-compat.ts@@ -0,0 +1,458 @@+import { dottedToolName, namespacedToolName } from "../types";+import { collectResponsesToolGroups } from "./tool-groups";+import { collectAmbiguousDottedAliases, dottedAliasIsUnambiguous } from "./tool-name-aliases";++export interface RoutedNamespaceToolIdentity {+ namespace: string;+ name: string;+ /**+ * The kind the tool was DECLARED as. Restoration and `tool_choice` matching both+ * need it: a wire name identifies which tool, not which kind of call may carry it,+ * so without this a tool declared `function` could be selected by a `custom`+ * selector and come back as a `custom_tool_call` — the same name/kind mismatch+ * that motivated narrowing the alias map in the first place.+ */+ kind: "function" | "custom";+}++export type RoutedNamespaceToolAliases = ReadonlyMap<string, RoutedNamespaceToolIdentity>;++const BUILTIN_FUNCTIONS_NAMESPACE = "functions";++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}++function namespaceIdentity(namespace: string, name: string): string {+ return `${namespace}\u0000${name}`;+}++/**+ * A name that can become a wire tool name. Control characters are rejected because the identity+ * key below joins namespace and name with NUL: a name carrying one could otherwise forge another+ * tool's identity and silently take over its wire name.+ */+function isRepresentableName(name: unknown): name is string {+ if (typeof name !== "string" || name.length === 0) return false;+ for (let index = 0; index < name.length; index += 1) {+ const code = name.charCodeAt(index);+ // C0 controls and DEL, written as code points so this source never carries one itself.+ if (code <= 0x1f || code === 0x7f) return false;+ }+ return true;+}++type NamespaceGroup = {+ namespace: string;+ /** Children that can be lowered to a flat declaration; unrepresentable ones are omitted. */+ children: Record<string, unknown>[];+};++/**+ * Read a private namespace group, or return undefined when the value is not one.+ *+ * Children that cannot be expressed as a flat declaration — a nested group, a missing name, a+ * control character in the name — are dropped, and a group left with no children is dropped whole+ * by the rewrite. Preserving the private `namespace` shape instead would lose every tool in the+ * request rather than one: the strict gateways this layer exists for reject that tool type before+ * inference, which is the failure the layer was written to prevent.+ */+function parseNamespaceGroup(tool: unknown): NamespaceGroup | undefined {+ if (+ !isPlainObject(tool)+ || tool.type !== "namespace"+ || !isRepresentableName(tool.name)+ || !Array.isArray(tool.tools)+ ) return undefined;+ const children: Record<string, unknown>[] = [];+ for (const child of tool.tools) {+ if (!isPlainObject(child) || child.type === "namespace" || !isRepresentableName(child.name)) continue;+ children.push(child);+ }+ return { namespace: tool.name, children };+}++/**+ * Wire identity of a lowered tool. A `functions` child and an identical top-level declaration share+ * one identity because they denote the same logical tool: `buildTools` flattens the reserved group+ * without a namespace, so the parser already treats them as one and tolerates the duplicate.+ */+function loweredIdentity(namespace: string, name: string): string {+ return namespace === BUILTIN_FUNCTIONS_NAMESPACE+ ? namespaceIdentity(BUILTIN_FUNCTIONS_NAMESPACE, name)+ : namespaceIdentity(namespace, name);+}++function loweredWireName(namespace: string, name: string): string {+ return namespace === BUILTIN_FUNCTIONS_NAMESPACE ? name : namespacedToolName(namespace, name);+}++function addSelector(+ selectors: Map<string, string | null>,+ selector: string,+ wireName: string,+): void {+ const current = selectors.get(selector);+ if (current === undefined) selectors.set(selector, wireName);+ else if (current !== wireName) selectors.set(selector, null);+}++type NamespaceRewritePlan = {+ aliases: Map<string, RoutedNamespaceToolIdentity>;+ bareWireNames: Set<string>;+ identities: Map<string, string>;+ selectors: Map<string, string | null>;+};++/** Two distinct logical tools would occupy one wire name; the caller maps this to a 400. */+export class NamespaceToolCollisionError extends Error {}++function buildRewritePlan(groups: readonly unknown[][]): NamespaceRewritePlan {+ const aliases = new Map<string, RoutedNamespaceToolIdentity>();+ const bareWireNames = new Set<string>();+ const identities = new Map<string, string>();+ const selectors = new Map<string, string | null>();+ const wireOwners = new Map<string, string>();++ for (const group of groups) {+ for (const tool of group) {+ if (isPlainObject(tool) && tool.type !== "namespace" && isRepresentableName(tool.name)) {+ // A bare declaration is the reserved group's flattened form, so it claims that identity:+ // declaring the same tool both ways is the duplicate the parser already tolerates, not a+ // collision, and `promoteClientLoadedTools` produces exactly that shape.+ wireOwners.set(tool.name, loweredIdentity(BUILTIN_FUNCTIONS_NAMESPACE, tool.name));+ bareWireNames.add(tool.name);+ addSelector(selectors, tool.name, tool.name);+ }+ }+ }++ for (const group of groups) {+ for (const tool of group) {+ const parsed = parseNamespaceGroup(tool);+ if (!parsed) continue;+ for (const child of parsed.children) {+ const childName = child.name as string;+ const identity = loweredIdentity(parsed.namespace, childName);+ const wireName = loweredWireName(parsed.namespace, childName);+ const owner = wireOwners.get(wireName);+ if (owner !== undefined && owner !== identity) {+ throw new NamespaceToolCollisionError(+ `namespace tool wire-name collision for "${wireName}"; rename one of the colliding tools`,+ );+ }+ wireOwners.set(wireName, identity);+ identities.set(identity, wireName);+ addSelector(selectors, wireName, wireName);+ addSelector(selectors, `${parsed.namespace}.${childName}`, wireName);+ addSelector(selectors, childName, wireName);+ if (parsed.namespace !== BUILTIN_FUNCTIONS_NAMESPACE) {+ // A child declared `custom` stays custom; everything else lowers to a+ // function, which is how `buildTools` flattens it upstream.+ const kind = child.type === "custom" ? "custom" : "function";+ aliases.set(wireName, { namespace: parsed.namespace, name: childName, kind });+ }+ }+ }+ }++ return { aliases, bareWireNames, identities, selectors };+}++/**+ * Lower every namespace group in one tool container. `emitted` is shared across the whole body so+ * a tool declared both bare and under `functions` is written once rather than twice.+ *+ * No `type: "namespace"` value survives this pass, including a group this layer cannot read:+ * relaying the private shape is what the strict gateway rejects.+ */+function rewriteToolList(+ tools: unknown[],+ plan: NamespaceRewritePlan,+ emitted: Set<string>,+): unknown[] {+ let changed = false;+ const rewritten: unknown[] = [];+ for (const tool of tools) {+ if (isPlainObject(tool) && tool.type === "namespace") {+ changed = true;+ const parsed = parseNamespaceGroup(tool);+ if (!parsed) continue;+ for (const child of parsed.children) {+ const wireName = plan.identities.get(loweredIdentity(parsed.namespace, child.name as string));+ // A bare declaration is the canonical representation of a `functions` child. Decide that+ // from the complete catalog rather than whichever container happens to be rewritten first.+ if (+ wireName === undefined+ || (parsed.namespace === BUILTIN_FUNCTIONS_NAMESPACE && plan.bareWireNames.has(wireName))+ || emitted.has(wireName)+ ) continue;+ emitted.add(wireName);+ rewritten.push(wireName === child.name ? child : { ...child, name: wireName });+ }+ continue;+ }+ if (isPlainObject(tool) && isRepresentableName(tool.name)) {+ if (emitted.has(tool.name)) {+ changed = true;+ continue;+ }+ emitted.add(tool.name);+ }+ rewritten.push(tool);+ }+ return changed ? rewritten : tools;+}++/**+ * Resolve one `{namespace?, name}` reference to its wire name and drop the private `namespace` key.+ *+ * `bareFallback` is for tool_choice, where a bare name is a selector the caller expects resolved+ * against the catalog. Replayed call items pass `false`: a history item records which tool actually+ * ran, so resolving a bare name through a same-named namespace child would rewrite history on a+ * coincidence rather than translate it.+ *+ * An explicit namespace is always lowered, even when this turn's catalog no longer declares that+ * group — a compaction turn drops the whole catalog, and a catalog can change mid-session. Leaving+ * the key in place ships a Codex-private field to a gateway that rejects unknown fields, which is+ * the failure this layer exists to prevent, and this layer's own response restoration is what put+ * the key on the item.+ */+/**+ * A selector's `namespace` is either absent — meaning "unqualified, resolve the bare+ * name" — or a string naming the group. A present-but-non-string value is neither, and+ * a malformed selector must not authorize anything: not through the unqualified+ * fallback, and not by happening to carry an already-flattened wire name, which would+ * otherwise match the alias map exactly and arm it anyway.+ */+function hasMalformedNamespace(value: Record<string, unknown>): boolean {+ return "namespace" in value && typeof value.namespace !== "string";+}++function rewriteNamedSelector(+ value: unknown,+ plan: NamespaceRewritePlan,+ bareFallback: boolean,+): unknown {+ if (!isPlainObject(value) || typeof value.name !== "string") return value;+ // Malformed: hand it back untouched so no rewrite occurs. Authorization rejects it+ // separately — returning it unchanged is not by itself enough, because the name it+ // carries may already BE a wire name.+ if (hasMalformedNamespace(value)) return value;+ const namespace = value.namespace;+ if (typeof namespace !== "string") {+ if (!bareFallback) return value;+ const wireName = plan.selectors.get(value.name) ?? undefined;+ return wireName === undefined || wireName === value.name ? value : { ...value, name: wireName };+ }+ const { namespace: _dropped, ...rest } = value;+ const wireName = plan.identities.get(loweredIdentity(namespace, value.name))+ ?? loweredWireName(namespace, value.name);+ return { ...rest, name: wireName };+}++function rewriteToolChoice(value: unknown, plan: NamespaceRewritePlan): unknown {+ if (!isPlainObject(value)) return value;+ if ((value.type === "function" || value.type === "custom") && typeof value.name === "string") {+ return rewriteNamedSelector(value, plan, true);+ }+ if (value.type !== "allowed_tools" || !Array.isArray(value.tools)) return value;+ let changed = false;+ const tools = value.tools.map(tool => {+ if (!isPlainObject(tool) || typeof tool.name !== "string") return tool;+ const rewritten = rewriteNamedSelector(tool, plan, true);+ changed ||= rewritten !== tool;+ return rewritten;+ });+ return changed ? { ...value, tools } : value;+}++/**+ * Keep response restoration inside the caller's per-turn tool authorization boundary. The+ * upstream sees every flattened declaration even when `tool_choice` narrows the tools it may call,+ * so its output cannot be trusted merely because a wire name appeared in that catalog.+ */+function authorizedAliases(+ aliases: Map<string, RoutedNamespaceToolIdentity>,+ toolChoice: unknown,+): Map<string, RoutedNamespaceToolIdentity> {+ if (toolChoice === undefined || toolChoice === "auto" || toolChoice === "required") return aliases;+ if (toolChoice === "none" || !isPlainObject(toolChoice)) return new Map();++ // name -> the kind the selector claimed. A selector authorizes a tool only when it+ // names it AND agrees about what kind of tool it is.+ let authorized: Map<string, "function" | "custom">;+ if (+ (toolChoice.type === "function" || toolChoice.type === "custom")+ && typeof toolChoice.name === "string"+ ) {+ // A malformed namespace makes the whole selector untrustworthy, even when its+ // name is already a flattened wire name that would match the alias map exactly.+ if (hasMalformedNamespace(toolChoice)) return new Map();+ authorized = new Map([[toolChoice.name, toolChoice.type]]);+ } else if (toolChoice.type === "allowed_tools" && Array.isArray(toolChoice.tools)) {+ authorized = new Map();+ for (const tool of toolChoice.tools) {+ // Match the top-level branch above: only a function/custom selector can+ // authorize a client namespace call. `allowed_tools` entries are typed+ // `{type: string}` by the schema, so the accepted set is open-ended and+ // an allowlist is the only closure that also covers kinds added later.+ // Without this, `{type: "file_search", name: "<wire-name>"}` keeps the+ // alias, and an upstream `function_call` carrying that name is restored+ // into a namespace call the caller never permitted.+ if (!isPlainObject(tool)) continue;+ if (tool.type !== "function" && tool.type !== "custom") continue;+ if (typeof tool.name !== "string") continue;+ if (hasMalformedNamespace(tool)) continue;+ authorized.set(tool.name, tool.type);+ }+ } else {+ // An explicit selector for another tool kind does not authorize a client namespace call.+ return new Map();+ }++ // The kind must agree too. A wire name says WHICH tool, not what kind of call may+ // carry it, so a `custom` selector naming a tool declared `function` is the same+ // name/kind mismatch as a `file_search` selector naming it — narrower, but the+ // same class, and `allowed_tools[].type` accepts any string so both are reachable.+ return new Map(+ [...aliases].filter(([wireName, identity]) => authorized.get(wireName) === identity.kind),+ );+}++function rewriteInputItem(item: unknown, plan: NamespaceRewritePlan, emitted: Set<string>): unknown {+ if (!isPlainObject(item)) return item;+ if (item.type === "additional_tools" && Array.isArray(item.tools)) {+ const tools = rewriteToolList(item.tools, plan, emitted);+ return tools === item.tools ? item : { ...item, tools };+ }+ if (+ (item.type === "function_call" || item.type === "custom_tool_call")+ && typeof item.name === "string"+ ) return rewriteNamedSelector(item, plan, false);+ return item;+}++/**+ * Lower Codex's private Responses namespace declarations for public/third-party gateways.+ *+ * Codex 0.147 groups ordinary tools under the reserved `functions` namespace; those children+ * become bare top-level declarations. Other namespaces use the same collision-checked+ * `<namespace>__<name>` wire identity as the chat adapters. The returned request-local aliases+ * are the only names response restoration is allowed to expand.+ */+export function rewriteRoutedNamespaceToolsForUpstream(+ body: unknown,+ convertedCustomToolNames?: ReadonlySet<string>,+): {+ body: unknown;+ aliases: Map<string, RoutedNamespaceToolIdentity>;+} {+ if (!isPlainObject(body)) return { body, aliases: new Map() };+ const groups = collectResponsesToolGroups(body);+ const plan = buildRewritePlan(groups);++ // Deliberately not gated on the plan being non-empty: a turn whose catalog is absent can still+ // replay call items carrying a private `namespace`.+ const emitted = new Set<string>();+ const tools = Array.isArray(body.tools) ? rewriteToolList(body.tools, plan, emitted) : body.tools;++ let input = body.input;+ if (Array.isArray(body.input)) {+ let inputChanged = false;+ const rewrittenInput = body.input.map(item => {+ const next = rewriteInputItem(item, plan, emitted);+ if (next !== item) inputChanged = true;+ return next;+ });+ if (inputChanged) input = rewrittenInput;+ }++ const toolChoice = rewriteToolChoice(body.tool_choice, plan);+ const aliases = authorizedAliases(plan.aliases, toolChoice);+ const ambiguousDotted = collectAmbiguousDottedAliases(groups);+ // Authorize canonical identities first, then add only unambiguous spellings.+ // Selection cannot hide a collision elsewhere in the original declaration set.+ for (const identity of [...aliases.values()]) {+ const dotted = dottedToolName(identity.namespace, identity.name);+ if (dottedAliasIsUnambiguous(identity.namespace, identity.name)+ && !ambiguousDotted.has(dotted) && !plan.bareWireNames.has(dotted)+ && !aliases.has(dotted)) aliases.set(dotted, identity);+ }+ // The adapter lowers custom tools before namespaces. Preserve their declared+ // kind only in already-authorized response aliases; wire selectors remain lowered.+ for (const identity of aliases.values()) {+ if (convertedCustomToolNames?.has(namespacedToolName(identity.namespace, identity.name))) identity.kind = "custom";+ }+ return {+ body: {+ ...body,+ ...(tools !== body.tools ? { tools } : {}),+ ...(input !== body.input ? { input } : {}),+ ...(toolChoice !== body.tool_choice ? { tool_choice: toolChoice } : {}),+ },+ aliases,+ };+}++export function restoreRoutedNamespaceCalls(+ value: unknown,+ aliases: RoutedNamespaceToolAliases,+): { value: unknown; changed: boolean } {+ if (Array.isArray(value)) {+ let changed = false;+ const restored = value.map(entry => {+ const result = restoreRoutedNamespaceCalls(entry, aliases);+ changed ||= result.changed;+ return result.value;+ });+ return changed ? { value: restored, changed: true } : { value, changed: false };+ }+ if (!isPlainObject(value)) return { value, changed: false };++ let changed = false;+ const restored: Record<string, unknown> = {};+ for (const [key, entry] of Object.entries(value)) {+ const result = restoreRoutedNamespaceCalls(entry, aliases);+ restored[key] = result.value;+ changed ||= result.changed;+ }++ if (+ (value.type === "function_call" || value.type === "custom_tool_call")+ && typeof value.name === "string"+ ) {+ const identity = aliases.get(value.name);+ if (identity+ // Custom declarations may be lowered to function calls upstream, but an+ // ordinary function declaration never authorizes a custom call payload.+ && (value.type !== "custom_tool_call" || identity.kind === "custom")+ && (!Object.hasOwn(value, "namespace") || value.namespace === identity.namespace)) {+ restored.name = identity.name;+ restored.namespace = identity.namespace;+ changed = true;+ }+ }+ return changed ? { value: restored, changed: true } : { value, changed: false };+}++export function restoreRoutedNamespaceCallsInJson(+ text: string,+ aliases: RoutedNamespaceToolAliases,+): string {+ if (aliases.size === 0) return text;+ let payload: unknown;+ try {+ payload = JSON.parse(text);+ } catch {+ return text;+ }+ const restored = restoreRoutedNamespaceCalls(payload, aliases);+ return restored.changed ? JSON.stringify(restored.value) : text;+}++export function createRoutedNamespaceCallRestoreRewrite(+ aliases: RoutedNamespaceToolAliases,+): (payload: string) => string {+ return payload => restoreRoutedNamespaceCallsInJson(payload, aliases);+}diff --git a/packages/model-compat/src/upstream/responses/tool-groups.ts b/packages/model-compat/src/upstream/responses/tool-groups.tsnew file mode 100644index 0000000000..4a4af73fa3--- /dev/null+++ b/packages/model-compat/src/upstream/responses/tool-groups.ts@@ -0,0 +1,19 @@+function isPlainObject(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}++/** Collect top-level and Responses Lite tool containers without altering their order. */+export function collectResponsesToolGroups(body: unknown): unknown[][] {+ if (!isPlainObject(body)) return [];++ const groups: unknown[][] = [];+ if (Array.isArray(body.tools)) groups.push(body.tools);+ if (!Array.isArray(body.input)) return groups;++ for (const item of body.input) {+ if (isPlainObject(item) && item.type === "additional_tools" && Array.isArray(item.tools)) {+ groups.push(item.tools);+ }+ }+ return groups;+}diff --git a/packages/model-compat/src/upstream/responses/tool-name-aliases.ts b/packages/model-compat/src/upstream/responses/tool-name-aliases.tsnew file mode 100644index 0000000000..1943a686bf--- /dev/null+++ b/packages/model-compat/src/upstream/responses/tool-name-aliases.ts@@ -0,0 +1,79 @@+import { dottedToolName, namespacedToolName } from "../types";++const BUILTIN_FUNCTIONS_NAMESPACE = "functions";+function isPlainObject(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}++/**+ * A dotted spelling is a safe alias only when it cannot ALSO be read as some other identity's+ * canonical `ns__name`.+ *+ * `{namespace: "x__y", name: "z"}` produces the dotted spelling "x__y.z", which is exactly the+ * canonical wire name of `{namespace: "x", name: "y.z"}`. If only the latter is declared, an+ * echoed call for the former would still find "x__y.z" in the declared set and be authorized as+ * a tool the caller never granted. Requiring both halves to be free of the `__` separator keeps+ * a dotted alias from ever impersonating a canonical name.+ */+export function dottedAliasIsUnambiguous(namespace: string, name: string): boolean {+ return !namespace.includes("__") && !name.includes("__");+}++export function wireToolInnerName(tool: unknown): string | undefined {+ if (!isPlainObject(tool)) return undefined;+ const nestedFunction = tool.type === "function" && isPlainObject(tool.function)+ ? tool.function+ : undefined;+ return typeof tool.name === "string" && tool.name.length > 0+ ? tool.name+ : typeof nestedFunction?.name === "string" && nestedFunction.name.length > 0+ ? nestedFunction.name+ : undefined;+}++/**+ * Dotted aliases that more than one declared identity would claim, plus dotted aliases that+ * collide with a canonical or bare declared name.+ *+ * Resolved over the WHOLE catalog before any name is registered, so which identity "wins" can+ * never depend on declaration order -- an order the caller controls.+ */+export function collectAmbiguousDottedAliases(specGroups: readonly unknown[]): Set<string> {+ const owners = new Map<string, string | null>();+ const claim = (alias: string, identity: string): void => {+ const owner = owners.get(alias);+ if (owner === undefined) owners.set(alias, identity);+ else if (owner !== identity) owners.set(alias, null);+ };+ for (const specs of specGroups) {+ if (!Array.isArray(specs)) continue;+ for (const spec of specs) {+ if (!isPlainObject(spec)) continue;+ if (spec.type === "namespace" && Array.isArray(spec.tools)) {+ const namespace = typeof spec.name === "string" ? spec.name : undefined;+ if (!namespace) continue;+ for (const inner of spec.tools) {+ const name = wireToolInnerName(inner);+ if (!name) continue;+ if (namespace === BUILTIN_FUNCTIONS_NAMESPACE) {+ claim(name, JSON.stringify([undefined, name]));+ continue;+ }+ const identity = JSON.stringify([namespace, name]);+ claim(dottedToolName(namespace, name), identity);+ // A canonical or bare name already owned by a different identity poisons the dotted+ // alias that would shadow it.+ claim(namespacedToolName(namespace, name), identity);+ claim(name, identity);+ }+ continue;+ }+ const name = wireToolInnerName(spec);+ if (name) claim(name, JSON.stringify([undefined, name]));+ }+ }+ const ambiguous = new Set<string>();+ for (const [alias, owner] of owners) if (owner === null) ambiguous.add(alias);+ return ambiguous;+}+diff --git a/packages/model-compat/src/upstream/responses/tool-search-compat.ts b/packages/model-compat/src/upstream/responses/tool-search-compat.tsnew file mode 100644index 0000000000..38eb6deb8b--- /dev/null+++ b/packages/model-compat/src/upstream/responses/tool-search-compat.ts@@ -0,0 +1,301 @@+export const TOOL_SEARCH_FUNCTION_NAME = "tool_search";+export const TOOL_SEARCH_DEFAULT_DESCRIPTION = "Search for additional tools to load for the next turn.";+const TOOL_SEARCH_WIRE_ALIAS_PREFIX = "opencodex_tool_search";++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}++export function toolSearchDescription(tool: unknown): string {+ return isPlainObject(tool) && typeof tool.description === "string"+ ? tool.description+ : TOOL_SEARCH_DEFAULT_DESCRIPTION;+}++export function toolSearchParameters(tool: unknown): Record<string, unknown> {+ if (isPlainObject(tool) && isPlainObject(tool.parameters)) return tool.parameters;+ // Fresh per parse/build: downstream normalizers are allowed to clone or extend schemas, and a+ // shared mutable default would couple otherwise unrelated requests.+ return {+ type: "object",+ properties: {+ query: { type: "string", description: "Search query for tools to load." },+ limit: { type: "number", description: "Maximum number of tools to return." },+ },+ required: ["query"],+ };+}++function collectToolDeclarationNames(tools: unknown[], names: Set<string>, namespace?: string): void {+ for (const tool of tools) {+ if (!isPlainObject(tool) || tool.type === "tool_search") continue;+ if (tool.type === "function" && isPlainObject(tool.function) && typeof tool.function.name === "string") {+ names.add(tool.function.name);+ }+ if (typeof tool.name === "string") {+ names.add(tool.name);+ if (namespace) names.add(`${namespace}__${tool.name}`);+ }+ if (tool.type === "namespace" && Array.isArray(tool.tools)) {+ collectToolDeclarationNames(tool.tools, names, typeof tool.name === "string" ? tool.name : undefined);+ }+ }+}++function declaredToolNames(body: Record<string, unknown>): Set<string> {+ const names = new Set<string>();+ if (Array.isArray(body.tools)) collectToolDeclarationNames(body.tools, names);+ if (Array.isArray(body.input)) {+ for (const item of body.input) {+ if (isPlainObject(item) && item.type === "additional_tools" && Array.isArray(item.tools)) {+ collectToolDeclarationNames(item.tools, names);+ }+ }+ }+ return names;+}++function hasToolSearchDeclaration(tools: unknown[]): boolean {+ return tools.some(tool => isPlainObject(tool) && tool.type === "tool_search");+}++function chooseToolSearchWireName(usedNames: ReadonlySet<string>): string {+ if (!usedNames.has(TOOL_SEARCH_FUNCTION_NAME)) return TOOL_SEARCH_FUNCTION_NAME;+ if (!usedNames.has(TOOL_SEARCH_WIRE_ALIAS_PREFIX)) return TOOL_SEARCH_WIRE_ALIAS_PREFIX;+ for (let suffix = 2; ; suffix++) {+ const candidate = `${TOOL_SEARCH_WIRE_ALIAS_PREFIX}_${suffix}`;+ if (!usedNames.has(candidate)) return candidate;+ }+}++function rewriteToolList(tools: unknown[], wireName: string): { tools: unknown[]; changed: boolean } {+ let changed = false;+ const rewritten = tools.map(tool => {+ if (!isPlainObject(tool) || tool.type !== "tool_search") return tool;+ const {+ execution: _execution,+ defer_loading: _deferLoading,+ ...rest+ } = tool;+ changed = true;+ return {+ ...rest,+ type: "function",+ name: wireName,+ description: toolSearchDescription(tool),+ parameters: toolSearchParameters(tool),+ };+ });+ return changed ? { tools: rewritten, changed: true } : { tools, changed: false };+}++function rewriteToolChoice(choice: unknown, wireName: string): unknown {+ if (!isPlainObject(choice)) return choice;+ if (choice.type === "tool_search") {+ return { type: "function", name: wireName };+ }+ if (choice.type !== "allowed_tools" || !Array.isArray(choice.tools)) return choice;+ let changed = false;+ const tools = choice.tools.map(tool => {+ if (!isPlainObject(tool) || tool.type !== "tool_search") return tool;+ changed = true;+ return { type: "function", name: wireName };+ });+ return changed ? { ...choice, tools } : choice;+}++function toolChoiceAllowsPrivateSearch(choice: unknown): boolean {+ if (choice === undefined || choice === null || choice === "auto" || choice === "required") return true;+ if (choice === "none") return false;+ if (!isPlainObject(choice)) return true;+ if (choice.type === "tool_search") return true;+ if (choice.type === "allowed_tools" && Array.isArray(choice.tools)) {+ return choice.tools.some(tool => isPlainObject(tool) && tool.type === "tool_search");+ }+ // A forced ordinary function named `tool_search` is distinct from the private tool kind.+ return false;+}++function upstreamToolSearchItemId(id: unknown): unknown {+ if (typeof id !== "string") return id;+ return id.startsWith("tsc_") ? `fc_${id.slice(4)}` : id;+}++function toolSearchArgumentsText(value: unknown): string {+ if (typeof value === "string") return value;+ return JSON.stringify(isPlainObject(value) ? value : {});+}++function toolSearchOutputText(value: Record<string, unknown>): string {+ const payload: Record<string, unknown> = {+ tools: Array.isArray(value.tools) ? value.tools : [],+ };+ if (typeof value.status === "string") payload.status = value.status;+ return JSON.stringify(payload);+}++function rewriteHistoryItem(item: Record<string, unknown>, wireName: string): Record<string, unknown> {+ if (item.type === "tool_search_call") {+ const {+ execution: _execution,+ arguments: argumentsValue,+ id,+ ...rest+ } = item;+ return {+ ...rest,+ type: "function_call",+ ...(id === undefined ? {} : { id: upstreamToolSearchItemId(id) }),+ name: wireName,+ arguments: toolSearchArgumentsText(argumentsValue),+ };+ }+ if (item.type === "tool_search_output") {+ const {+ execution: _execution,+ id: _id,+ tools: _tools,+ status: _status,+ ...rest+ } = item;+ return {+ ...rest,+ type: "function_call_output",+ output: toolSearchOutputText(item),+ };+ }+ return item;+}++/**+ * Third-party Responses gateways generally implement the public function-tool schema, not Codex's+ * private client-executed `tool_search` declaration. Lower only request catalogs sent to a+ * noncanonical upstream; the caller-facing response is restored separately.+ */+export function rewriteRoutedToolSearchForUpstream(body: unknown): {+ body: unknown;+ names: Set<string>;+} {+ const names = new Set<string>();+ if (!isPlainObject(body)) return { body, names };++ const topLevelSearch = Array.isArray(body.tools) && hasToolSearchDeclaration(body.tools);+ const inputItems = Array.isArray(body.input) ? body.input : [];+ const additionalSearch = inputItems.some(item =>+ isPlainObject(item)+ && item.type === "additional_tools"+ && Array.isArray(item.tools)+ && hasToolSearchDeclaration(item.tools));+ const historySearch = inputItems.some(item =>+ isPlainObject(item)+ && (item.type === "tool_search_call" || item.type === "tool_search_output"));+ if (!topLevelSearch && !additionalSearch && !historySearch) return { body, names };++ const wireName = chooseToolSearchWireName(declaredToolNames(body));+ const declarationChanged = topLevelSearch || additionalSearch;++ let tools = body.tools;+ if (Array.isArray(tools)) {+ const result = rewriteToolList(tools, wireName);+ tools = result.tools;+ }++ let input = body.input;+ let historyLowered = false;+ if (Array.isArray(input)) {+ input = input.map(item => {+ if (!isPlainObject(item)) return item;+ if (item.type === "additional_tools" && Array.isArray(item.tools)) {+ const result = rewriteToolList(item.tools, wireName);+ return result.changed ? { ...item, tools: result.tools } : item;+ }+ const rewritten = rewriteHistoryItem(item, wireName);+ if (rewritten !== item) historyLowered = true;+ return rewritten;+ });+ }++ // A turn can replay `tool_search_call` history WITHOUT re-declaring the tool — Codex normally+ // sends the declaration, but a history-only body is legal. The history is lowered to+ // `function_call` either way, so restoration has to be armed on that too: leaving `names`+ // empty there would hand the client a public `function_call` for what it issued as a private+ // search call, and the round trip would silently stop matching.+ if ((declarationChanged || historyLowered) && toolChoiceAllowsPrivateSearch(body.tool_choice)) {+ names.add(wireName);+ }+ const toolChoice = declarationChanged ? rewriteToolChoice(body.tool_choice, wireName) : body.tool_choice;+ return {+ body: {+ ...body,+ ...(tools !== body.tools ? { tools } : {}),+ ...(input !== body.input ? { input } : {}),+ ...(toolChoice !== body.tool_choice ? { tool_choice: toolChoice } : {}),+ },+ names,+ };+}++export function toolSearchItemId(id: unknown): unknown {+ if (typeof id !== "string") return id;+ return id.startsWith("fc_") ? `tsc_${id.slice(3)}` : id;+}++function toolSearchArguments(value: unknown): Record<string, unknown> {+ if (isPlainObject(value)) return value;+ if (typeof value !== "string" || value.length === 0) return {};+ try {+ const parsed: unknown = JSON.parse(value);+ return isPlainObject(parsed) ? parsed : {};+ } catch {+ return {};+ }+}++export function restoreRoutedToolSearchCalls(+ value: unknown,+ names: ReadonlySet<string>,+): { value: unknown; changed: boolean } {+ if (Array.isArray(value)) {+ let changed = false;+ const restored = value.map(entry => {+ const result = restoreRoutedToolSearchCalls(entry, names);+ changed ||= result.changed;+ return result.value;+ });+ return changed ? { value: restored, changed: true } : { value, changed: false };+ }+ if (!isPlainObject(value)) return { value, changed: false };++ let changed = false;+ const restored: Record<string, unknown> = {};+ for (const [key, entry] of Object.entries(value)) {+ const result = restoreRoutedToolSearchCalls(entry, names);+ restored[key] = result.value;+ changed ||= result.changed;+ }++ if (value.type === "function_call" && typeof value.name === "string" && names.has(value.name)) {+ restored.type = "tool_search_call";+ restored.id = toolSearchItemId(value.id);+ restored.execution = "client";+ restored.arguments = toolSearchArguments(value.arguments);+ delete restored.name;+ changed = true;+ }+ return changed ? { value: restored, changed: true } : { value, changed: false };+}++export function restoreRoutedToolSearchCallsInJson(+ text: string,+ names: ReadonlySet<string>,+): string {+ if (names.size === 0) return text;+ let payload: unknown;+ try {+ payload = JSON.parse(text);+ } catch {+ return text;+ }+ const restored = restoreRoutedToolSearchCalls(payload, names);+ return restored.changed ? JSON.stringify(restored.value) : text;+}diff --git a/packages/model-compat/src/upstream/server/relay.ts b/packages/model-compat/src/upstream/server/relay.tsnew file mode 100644index 0000000000..b90d91bc12--- /dev/null+++ b/packages/model-compat/src/upstream/server/relay.ts@@ -0,0 +1,2 @@+export const MAX_COMPLETED_OUTPUT_ITEMS = 256;+export const MAX_COMPLETED_OUTPUT_ITEM_SOURCE_BYTES = 8 * 1024 * 1024;diff --git a/packages/model-compat/src/upstream/server/responses-custom-tool-repair.ts b/packages/model-compat/src/upstream/server/responses-custom-tool-repair.tsnew file mode 100644index 0000000000..c9d8527ebc--- /dev/null+++ b/packages/model-compat/src/upstream/server/responses-custom-tool-repair.ts@@ -0,0 +1,399 @@+import type { TranslatorBudget } from "../lib/translator-budget";+import { mayBecomePatchEnvelope, normalizeApplyPatchDelimiters } from "../responses/apply-patch-envelope";+import { compileCodeModeHelperInput, resolveCodeModeHelperName } from "../responses/code-mode-helper-compat";+import { declaresCodeModeExec } from "../types/tools";+import {+ customToolItemId,+ restoreRoutedCustomCalls,+ routedCustomToolTargetName,+ routedCustomToolWireName,+ unwrapRoutedCustomToolArguments,+} from "../responses/custom-tool-compat";+import {+ replaceSseDataPayload,+ sseDataPayload,+ type SseBlockRewrite,+} from "./sse-payload-rewrite";++/** Exact compact prefix used by our upstream rewriter; progressive matching also+ * tolerates insignificant JSON whitespace via FREEFORM_WRAP_PREFIX_RE. */+const FREEFORM_WRAP_PREFIX = '{"input":"';+const FREEFORM_WRAP_PREFIX_RE = /^\s*\{\s*"input"\s*:\s*"/;++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}++/**+ * Progressive decode of the freeform `{ "input": "…" }` wrapper.+ * Returns null when the accumulated text does not (yet) match that wrapper so+ * callers suppress deltas and rely on `response.custom_tool_call_input.done`.+ */+function partialCustomToolInput(argumentsText: string): string | null {+ const match = FREEFORM_WRAP_PREFIX_RE.exec(argumentsText);+ if (!match) return null;+ const body = argumentsText.slice(match[0]!.length);+ let output = "";+ for (let index = 0; index < body.length; index++) {+ const char = body[index];+ if (char === '"') break;+ if (char !== "\\") {+ output += char;+ continue;+ }+ const escaped = body[index + 1];+ if (escaped === undefined) break;+ index += 1;+ if (escaped === "n") output += "\n";+ else if (escaped === "t") output += "\t";+ else if (escaped === "r") output += "\r";+ else if (escaped === "b") output += "\b";+ else if (escaped === "f") output += "\f";+ else if (escaped === "u") {+ const hex = body.slice(index + 1, index + 5);+ if (hex.length !== 4 || !/^[0-9a-fA-F]{4}$/.test(hex)) break;+ output += String.fromCharCode(Number.parseInt(hex, 16));+ index += 4;+ } else output += escaped;+ }+ return output;+}++function replaceSseEventName(block: string, type: string): string {+ const newline = block.includes("\r\n") ? "\r\n" : "\n";+ const lines = block.split(/\r?\n/);+ let replaced = false;+ const next = lines.map(line => {+ if (!replaced && line.startsWith("event:")) {+ replaced = true;+ return `event: ${type}`;+ }+ return line;+ });+ return next.join(newline);+}++type OpenCustomCall = {+ argumentsText: string;+ emittedInput: string;+ retainedBytes: number;+};++type PendingArgumentBlock = {+ block: string;+ itemId?: string;+ outputIndex?: number;+ retainedBytes: number;+};++export function createRoutedCustomToolRestoreBlockRewrite(+ names: ReadonlySet<string>,+ budget?: TranslatorBudget,+ repairNames: ReadonlySet<string> = new Set(),+ declaredNames?: ReadonlySet<string>,+): SseBlockRewrite {+ const itemNames = new Map<string, { name: string; aliased: boolean; namespace?: string }>();+ // Native helper aliases and genuine bare code-mode exec calls share completion repair.+ const customExecItemNames = new Map<string, string>();+ const repairItemNames = new Map<string, string>();+ const ordinaryItemIds = new Set<string>();+ const openCalls = new Map<string, OpenCustomCall>();+ let pendingArguments: PendingArgumentBlock[] = [];+ let disposed = false;++ const releaseCall = (itemId: string): void => {+ const open = openCalls.get(itemId);+ if (!open) return;+ if (open.retainedBytes > 0) {+ budget?.releaseRetained(open.retainedBytes, { kind: "retained_collectors" });+ }+ openCalls.delete(itemId);+ };++ const releaseAll = (): void => {+ if (disposed) return;+ disposed = true;+ for (const itemId of openCalls.keys()) releaseCall(itemId);+ const pendingBytes = pendingArguments.reduce((total, pending) => total + pending.retainedBytes, 0);+ if (pendingBytes > 0) {+ budget?.releaseRetained(pendingBytes, { kind: "retained_collectors" });+ }+ pendingArguments = [];+ itemNames.clear();+ customExecItemNames.clear();+ repairItemNames.clear();+ ordinaryItemIds.clear();+ };++ const retainPendingArgument = (+ block: string,+ itemId: string | undefined,+ outputIndex: number | undefined,+ ): void => {+ const retainedBytes = Buffer.byteLength(block, "utf8");+ if (retainedBytes > 0) budget?.chargeRetained(retainedBytes, { kind: "retained_collectors" });+ pendingArguments.push({ block, itemId, outputIndex, retainedBytes });+ };++ const takePendingArguments = (+ itemId: string | undefined,+ outputIndex: number | undefined,+ ): string[] => {+ const matched: PendingArgumentBlock[] = [];+ const remaining: PendingArgumentBlock[] = [];+ for (const pending of pendingArguments) {+ const matches = pending.itemId !== undefined+ ? itemId !== undefined && pending.itemId === itemId+ : outputIndex !== undefined && pending.outputIndex === outputIndex;+ (matches ? matched : remaining).push(pending);+ }+ pendingArguments = remaining;+ const retainedBytes = matched.reduce((total, pending) => total + pending.retainedBytes, 0);+ if (retainedBytes > 0) {+ budget?.releaseRetained(retainedBytes, { kind: "retained_collectors" });+ }+ // Index-matched entries carry no item id. Stamp the resolved id so replay+ // classifies the event instead of buffering it a second time.+ return matched.map(pending => {+ if (pending.itemId !== undefined || itemId === undefined) return pending.block;+ const payload = sseDataPayload(pending.block);+ if (payload === null) return pending.block;+ try {+ const parsed: unknown = JSON.parse(payload);+ if (!isPlainObject(parsed)) return pending.block;+ return replaceSseDataPayload(pending.block, JSON.stringify({ ...parsed, item_id: itemId }));+ } catch {+ return pending.block;+ }+ });+ };++ const rewrite: SseBlockRewrite = (block: string): readonly string[] => {+ if (disposed) return [block];+ const payload = sseDataPayload(block);+ if (payload === null || payload === "[DONE]") return [block];+ let parsed: unknown;+ try {+ parsed = JSON.parse(payload);+ } catch {+ return [block];+ }+ if (!isPlainObject(parsed)) return [block];++ const type = typeof parsed.type === "string" ? parsed.type : "";+ const outputIndex = typeof parsed.output_index === "number"+ && Number.isInteger(parsed.output_index)+ && parsed.output_index >= 0+ ? parsed.output_index+ : undefined;+ if (+ (type === "response.output_item.added" || type === "response.output_item.done")+ && isPlainObject(parsed.item)+ && parsed.item.type === "custom_tool_call"+ && typeof parsed.item.name === "string"+ ) {+ const upstreamItemId = typeof parsed.item.id === "string" ? parsed.item.id : undefined;+ const wireName = routedCustomToolWireName(parsed.item);+ const targetName = routedCustomToolTargetName(parsed.item, names, declaredNames);+ const aliased = targetName !== undefined && targetName !== wireName;+ const codeModeExec = targetName === "exec" && parsed.item.name === "exec"+ && parsed.item.namespace === undefined && declaresCodeModeExec(declaredNames);+ if (upstreamItemId && (aliased || codeModeExec)) {+ customExecItemNames.set(upstreamItemId, parsed.item.name);+ if (type === "response.output_item.added") {+ openCalls.set(upstreamItemId, { argumentsText: "", emittedInput: "", retainedBytes: 0 });+ }+ }+ const repairable = wireName !== undefined && repairNames.has(wireName);+ if (upstreamItemId && repairable) repairItemNames.set(upstreamItemId, parsed.item.name);+ const restored = repairable || aliased || codeModeExec+ ? restoreRoutedCustomCalls(parsed, names, repairNames, declaredNames)+ : { value: parsed, changed: false };+ if (type === "response.output_item.done" && upstreamItemId) releaseCall(upstreamItemId);+ return restored.changed+ ? [replaceSseDataPayload(block, JSON.stringify(restored.value))]+ : [block];+ }+ if (+ (type === "response.output_item.added" || type === "response.output_item.done")+ && isPlainObject(parsed.item)+ && parsed.item.type === "function_call"+ && typeof parsed.item.name === "string"+ ) {+ const upstreamItemId = typeof parsed.item.id === "string" ? parsed.item.id : undefined;+ const targetName = routedCustomToolTargetName(parsed.item, names, declaredNames);+ const routed = targetName !== undefined;+ const wireName = routedCustomToolWireName(parsed.item);+ if (upstreamItemId) {+ if (routed) {+ itemNames.set(upstreamItemId, {+ name: parsed.item.name,+ aliased: targetName !== wireName,+ ...(typeof parsed.item.namespace === "string" ? { namespace: parsed.item.namespace } : {}),+ });+ ordinaryItemIds.delete(upstreamItemId);+ } else {+ ordinaryItemIds.add(upstreamItemId);+ }+ if (routed && type === "response.output_item.added") {+ openCalls.set(upstreamItemId, { argumentsText: "", emittedInput: "", retainedBytes: 0 });+ }+ }+ const pending = takePendingArguments(upstreamItemId, outputIndex);+ if (!routed) {+ if (type === "response.output_item.done" && upstreamItemId) ordinaryItemIds.delete(upstreamItemId);+ return [...pending, block];+ }+ if (upstreamItemId && pending.length > 0 && !openCalls.has(upstreamItemId)) {+ openCalls.set(upstreamItemId, { argumentsText: "", emittedInput: "", retainedBytes: 0 });+ }+ const restored = restoreRoutedCustomCalls(parsed, names, repairNames, declaredNames);+ const restoredBlock = restored.changed+ ? replaceSseDataPayload(block, JSON.stringify(restored.value))+ : block;+ const replayed = pending.flatMap(pendingBlock => rewrite(pendingBlock));+ if (type === "response.output_item.done" && upstreamItemId) releaseCall(upstreamItemId);+ return type === "response.output_item.added"+ ? [restoredBlock, ...replayed]+ : [...replayed, restoredBlock];+ }++ const upstreamItemId = typeof parsed.item_id === "string" ? parsed.item_id : undefined;+ if (+ type === "response.custom_tool_call_input.delta"+ && upstreamItemId+ && customExecItemNames.has(upstreamItemId)+ ) {+ const open = openCalls.get(upstreamItemId) ?? { argumentsText: "", emittedInput: "", retainedBytes: 0 };+ const delta = typeof parsed.delta === "string" ? parsed.delta : "";+ const deltaBytes = Buffer.byteLength(delta, "utf8");+ if (deltaBytes > 0) budget?.chargeRetained(deltaBytes, { kind: "retained_collectors" });+ open.argumentsText += delta;+ open.retainedBytes += deltaBytes;+ openCalls.set(upstreamItemId, open);+ if (customExecItemNames.get(upstreamItemId) !== "exec"+ || mayBecomePatchEnvelope(open.argumentsText)+ // JSON.parse accepts whitespace, escaped keys and arbitrary property order.+ // Any object prefix may still wrap a patch; keep it until authoritative completion.+ || open.argumentsText.trimStart() === ""+ || open.argumentsText.trimStart().startsWith("{")) return [];+ // If a held prefix turns out to be ordinary JavaScript, release the entire+ // un-emitted suffix. Native custom input remains byte-exact.+ const inputDelta = open.argumentsText.slice(open.emittedInput.length);+ open.emittedInput = open.argumentsText;+ return inputDelta ? [replaceSseDataPayload(block, JSON.stringify({ ...parsed, delta: inputDelta }))] : [];+ }+ if (+ type === "response.custom_tool_call_input.done"+ && upstreamItemId+ && customExecItemNames.has(upstreamItemId)+ ) {+ const source = typeof parsed.input === "string"+ ? parsed.input+ : openCalls.get(upstreamItemId)?.argumentsText ?? "";+ const name = customExecItemNames.get(upstreamItemId)!;+ const helper = name === "exec"+ ? resolveCodeModeHelperName(undefined, name, source, undefined, declaredNames)+ : name;+ releaseCall(upstreamItemId);+ return [replaceSseDataPayload(block, JSON.stringify({+ ...parsed,+ input: helper ? compileCodeModeHelperInput(source, helper) : source,+ }))];+ }+ if (+ type === "response.custom_tool_call_input.done"+ && upstreamItemId+ && repairItemNames.has(upstreamItemId)+ && typeof parsed.input === "string"+ ) {+ const input = normalizeApplyPatchDelimiters(parsed.input);+ if (input !== parsed.input) {+ return [replaceSseDataPayload(block, JSON.stringify({ ...parsed, input }))];+ }+ }+ const argumentEvent = type === "response.function_call_arguments.delta"+ || type === "response.function_call_arguments.done";+ if (argumentEvent && (!upstreamItemId || (!itemNames.has(upstreamItemId) && !ordinaryItemIds.has(upstreamItemId)))) {+ retainPendingArgument(block, upstreamItemId, outputIndex);+ return [];+ }+ if (+ type === "response.function_call_arguments.delta"+ && upstreamItemId+ && itemNames.has(upstreamItemId)+ ) {+ const open = openCalls.get(upstreamItemId) ?? { argumentsText: "", emittedInput: "", retainedBytes: 0 };+ const delta = typeof parsed.delta === "string" ? parsed.delta : "";+ const deltaBytes = Buffer.byteLength(delta, "utf8");+ if (deltaBytes > 0) budget?.chargeRetained(deltaBytes, { kind: "retained_collectors" });+ open.argumentsText += delta;+ open.retainedBytes += deltaBytes;+ openCalls.set(upstreamItemId, open);+ // A helper alias will become JavaScript at completion, never raw patch/JSON.+ if (itemNames.get(upstreamItemId)?.aliased) return [];+ // Still accumulating toward the compact wrapper, or an unrecognized shape:+ // suppress progressive emission and let the done event carry input.+ if (FREEFORM_WRAP_PREFIX.startsWith(open.argumentsText)) return [];+ const fullInput = partialCustomToolInput(open.argumentsText);+ if (fullInput === null) return [];+ // Hold a buffer that could still become a complete patch envelope. The done event+ // recompiles such a body into an apply_patch helper call, so streaming the envelope+ // bytes first and replacing them at completion is the rewind this path forbids.+ // Mirrors the same hold in `src/bridge.ts`.+ if (+ declaresCodeModeExec(declaredNames)+ && itemNames.get(upstreamItemId)?.namespace === undefined+ && itemNames.get(upstreamItemId)?.name === "exec"+ && mayBecomePatchEnvelope(fullInput)+ ) return [];+ if (!fullInput.startsWith(open.emittedInput) || fullInput.length === open.emittedInput.length) return [];+ const inputDelta = fullInput.slice(open.emittedInput.length);+ open.emittedInput = fullInput;+ const nextType = "response.custom_tool_call_input.delta";+ const next = {+ ...parsed,+ type: nextType,+ item_id: customToolItemId(upstreamItemId),+ delta: inputDelta,+ };+ return [replaceSseDataPayload(replaceSseEventName(block, nextType), JSON.stringify(next))];+ }++ if (+ type === "response.function_call_arguments.done"+ && upstreamItemId+ && itemNames.has(upstreamItemId)+ ) {+ const nextType = "response.custom_tool_call_input.done";+ const source = typeof parsed.arguments === "string"+ ? parsed.arguments+ : openCalls.get(upstreamItemId)?.argumentsText ?? "";+ const { arguments: _arguments, ...rest } = parsed;+ const itemName = itemNames.get(upstreamItemId);+ // Name-based alias first; otherwise a raw patch envelope submitted as the `exec` body+ // resolves to the same apply_patch helper (devlog/_plan/260905_apply_patch_envelope_gap).+ const helper = itemName?.aliased+ ? itemName.name+ : resolveCodeModeHelperName(undefined, itemName?.name ?? "", source, itemName?.namespace, declaredNames);+ const next = {+ ...rest,+ type: nextType,+ item_id: customToolItemId(upstreamItemId),+ input: helper+ ? compileCodeModeHelperInput(source, helper)+ : unwrapRoutedCustomToolArguments(source, itemName?.name ?? "", itemName?.namespace),+ };+ return [replaceSseDataPayload(replaceSseEventName(block, nextType), JSON.stringify(next))];+ }++ const restored = restoreRoutedCustomCalls(parsed, names, repairNames, declaredNames);+ const terminal = type === "response.completed" || type === "response.failed" || type === "response.incomplete";+ if (terminal) releaseAll();+ return restored.changed+ ? [replaceSseDataPayload(block, JSON.stringify(restored.value))]+ : [block];+ };+ rewrite.dispose = releaseAll;+ return rewrite;+}diff --git a/packages/model-compat/src/upstream/server/responses-function-tool-repair.ts b/packages/model-compat/src/upstream/server/responses-function-tool-repair.tsnew file mode 100644index 0000000000..48bb7e51b2--- /dev/null+++ b/packages/model-compat/src/upstream/server/responses-function-tool-repair.ts@@ -0,0 +1,183 @@+import {+ TRANSLATOR_MAX_TURN_BYTES,+ TranslatorBudgetExceededError,+ type TranslatorBudget,+} from "../lib/translator-budget";+import { repairFunctionCalls, type FunctionCallRepairSchemas } from "../responses/function-call-compat";+import { replaceSseDataPayload, sseDataPayload, type SseBlockRewrite } from "./sse-payload-rewrite";++type Identity = {+ itemId?: string;+ outputIndex?: number;+ item: Record<string, unknown>;+ bytes: number;+};+type PendingCompletion = {+ block: string;+ itemId?: string;+ outputIndex?: number;+ bytes: number;+};+const ENTRY_OVERHEAD_BYTES = 64;++function isObject(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === "object" && !Array.isArray(value);+}++function outputIndexOf(value: unknown): number | undefined {+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined;+}++/** Ordinary deltas remain upstream previews; only authoritative completions are repaired. */+export function createResponsesFunctionToolRepairBlockRewrite(+ schemas: FunctionCallRepairSchemas,+ budget?: TranslatorBudget,+): SseBlockRewrite {+ if (schemas.size === 0) return block => [block];+ const byId = new Map<string, Identity>();+ const byIndex = new Map<number, Identity>();+ let pending: PendingCompletion[] = [];+ let retainedBytes = 0;+ let disposed = false;++ const retain = (bytes: number): void => {+ if (retainedBytes + bytes > TRANSLATOR_MAX_TURN_BYTES) {+ throw new TranslatorBudgetExceededError("retained_collectors", TRANSLATOR_MAX_TURN_BYTES);+ }+ budget?.chargeRetained(bytes, { kind: "retained_collectors" });+ retainedBytes += bytes;+ };+ const release = (bytes: number): void => {+ budget?.releaseRetained(bytes, { kind: "retained_collectors" });+ retainedBytes -= bytes;+ };+ const releaseIdentity = (identity: Identity): void => {+ if (identity.itemId !== undefined) byId.delete(identity.itemId);+ if (identity.outputIndex !== undefined) byIndex.delete(identity.outputIndex);+ release(identity.bytes);+ };+ const dispose = (): void => {+ if (disposed) return;+ disposed = true;+ release(retainedBytes);+ byId.clear();+ byIndex.clear();+ pending = [];+ };+ const lookup = (itemId: string | undefined, index: number | undefined): Identity | undefined => {+ const identity = itemId === undefined ? undefined : byId.get(itemId);+ if (identity) return index === undefined || identity.outputIndex === undefined || identity.outputIndex === index ? identity : undefined;+ const indexed = index === undefined ? undefined : byIndex.get(index);+ return indexed && (itemId === undefined || indexed.itemId === undefined || indexed.itemId === itemId) ? indexed : undefined;+ };+ const register = (item: Record<string, unknown>, index: number | undefined): Identity | undefined => {+ const itemId = typeof item.id === "string" && item.id ? item.id : undefined;+ if (itemId === undefined && index === undefined) return undefined;+ // Repeated snapshots replace metadata; never retain provider argument bodies here.+ const previous = new Set<Identity>();+ if (itemId !== undefined && byId.has(itemId)) previous.add(byId.get(itemId)!);+ if (index !== undefined && byIndex.has(index)) previous.add(byIndex.get(index)!);+ for (const identity of previous) releaseIdentity(identity);+ const metadata = {+ type: item.type,+ name: item.name,+ ...("namespace" in item ? { namespace: item.namespace } : {}),+ ...(item.status !== undefined && item.status !== "in_progress" && item.status !== "completed" ? { status: item.status } : {}),+ };+ const bytes = ENTRY_OVERHEAD_BYTES + Buffer.byteLength(JSON.stringify([itemId, index, metadata]), "utf8");+ retain(bytes);+ const identity = { itemId, outputIndex: index, item: metadata, bytes };+ if (itemId !== undefined) byId.set(itemId, identity);+ if (index !== undefined) byIndex.set(index, identity);+ return identity;+ };+ const repairCompletion = (block: string, event: Record<string, unknown>, identity: Identity): string => {+ if (typeof event.arguments !== "string") return block;+ const resolved = (typeof event.item_id !== "string" || event.item_id === "") && identity.itemId !== undefined+ ? { ...event, item_id: identity.itemId }+ : event;+ const repaired = repairFunctionCalls({ ...identity.item, status: identity.item.status ?? "completed", arguments: event.arguments }, schemas);+ if (repaired.changed && isObject(repaired.value)) {+ return replaceSseDataPayload(block, JSON.stringify({ ...resolved, arguments: repaired.value.arguments }));+ }+ return resolved === event ? block : replaceSseDataPayload(block, JSON.stringify(resolved));+ };+ const flushPending = (identity: Identity): string[] => {+ const output: string[] = [];+ const remaining: PendingCompletion[] = [];+ for (const completion of pending) {+ const matches = completion.itemId !== undefined+ ? completion.itemId === identity.itemId+ && (completion.outputIndex === undefined || identity.outputIndex === undefined || completion.outputIndex === identity.outputIndex)+ : completion.outputIndex !== undefined && completion.outputIndex === identity.outputIndex;+ if (!matches) { remaining.push(completion); continue; }+ release(completion.bytes);+ const payload = sseDataPayload(completion.block);+ const event: unknown = payload === null ? undefined : JSON.parse(payload);+ output.push(isObject(event) ? repairCompletion(completion.block, event, identity) : completion.block);+ }+ pending = remaining;+ return output;+ };++ const rewrite: SseBlockRewrite = block => {+ if (disposed) return [block];+ const payload = sseDataPayload(block);+ if (payload === null) return [block];+ if (payload === "[DONE]") {+ const unfinished = pending.map(entry => entry.block);+ dispose();+ return [...unfinished, block];+ }+ let event: unknown;+ try { event = JSON.parse(payload); } catch { return [block]; }+ if (!isObject(event)) return [block];+ const index = outputIndexOf(event.output_index);+ const itemId = typeof event.item_id === "string" && event.item_id ? event.item_id : undefined;+ try {+ if ((event.type === "response.output_item.added" || event.type === "response.output_item.done") && isObject(event.item)) {+ const identity = register(event.item, index);+ const replayed = identity ? flushPending(identity) : [];+ const repaired = repairFunctionCalls(event, schemas);+ const output = repaired.changed ? replaceSseDataPayload(block, JSON.stringify(repaired.value)) : block;+ if (identity && (event.type === "response.output_item.done" || replayed.length > 0)) releaseIdentity(identity);+ return event.type === "response.output_item.added" ? [output, ...replayed] : [...replayed, output];+ }+ if (event.type === "response.function_call_arguments.done" && typeof event.arguments === "string") {+ const identity = lookup(itemId, index);+ if (identity) {+ const output = repairCompletion(block, event, identity);+ releaseIdentity(identity);+ return [output];+ }+ if (itemId !== undefined || index !== undefined) {+ const bytes = ENTRY_OVERHEAD_BYTES + Buffer.byteLength(block, "utf8");+ retain(bytes);+ pending.push({ block, itemId, outputIndex: index, bytes });+ return [];+ }+ }+ if (typeof event.type === "string" && ["response.completed", "response.failed", "response.incomplete", "response.cancelled"].includes(event.type)) {+ const replayed: string[] = [];+ if (event.type === "response.completed" && isObject(event.response) && Array.isArray(event.response.output)+ && (event.response.status === undefined || event.response.status === "completed")) {+ for (const [slot, item] of event.response.output.entries()) {+ if (!isObject(item)) continue;+ const identity = register(item, slot);+ if (identity) replayed.push(...flushPending(identity));+ }+ }+ replayed.push(...pending.map(entry => entry.block));+ const repaired = repairFunctionCalls(event, schemas);+ dispose();+ return [...replayed, repaired.changed ? replaceSseDataPayload(block, JSON.stringify(repaired.value)) : block];+ }+ return [block];+ } catch (error) {+ dispose();+ throw error;+ }+ };+ rewrite.dispose = dispose;+ return rewrite;+}diff --git a/packages/model-compat/src/upstream/server/responses-item-id-repair.ts b/packages/model-compat/src/upstream/server/responses-item-id-repair.tsnew file mode 100644index 0000000000..9187f25da2--- /dev/null+++ b/packages/model-compat/src/upstream/server/responses-item-id-repair.ts@@ -0,0 +1,272 @@+import { randomUUID } from "node:crypto";+import type { ResponsesItemIdRepairConfig } from "../types";+import { relaySseWithPayloadRewrite, type SsePayloadRewrite } from "./sse-payload-rewrite";+import type { TranslatorBudget } from "../lib/translator-budget";++type RepairableItemType = "message" | "reasoning";++interface ResponsesItemIdRepairState {+ readonly repairMissingTerminalIds: boolean;+ readonly repairInvalidIds: boolean;+ readonly placeholders: Record<RepairableItemType, ReadonlySet<string>>;+ readonly outputIds: Record<RepairableItemType, Map<number, string>>;+ /** JSON [outputIndex, rawId] -> canonical id, for exact item_id rewrites on part/delta events. */+ readonly rawIds: Map<string, string>;+ readonly scope: string;+ readonly budget?: TranslatorBudget;+}++const REPAIRABLE_PREFIXES: Record<RepairableItemType, string> = {+ message: "msg_",+ reasoning: "rs_",+};++const ITEM_ID_EVENT_TYPES: Readonly<Record<string, RepairableItemType>> = {+ "response.content_part.added": "message",+ "response.content_part.done": "message",+ "response.output_text.annotation.added": "message",+ "response.output_text.delta": "message",+ "response.output_text.done": "message",+ "response.refusal.delta": "message",+ "response.refusal.done": "message",+ "response.reasoning_summary_part.added": "reasoning",+ "response.reasoning_summary_part.done": "reasoning",+ "response.reasoning_summary_text.delta": "reasoning",+ "response.reasoning_summary_text.done": "reasoning",+ "response.reasoning_text.delta": "reasoning",+ "response.reasoning_text.done": "reasoning",+};++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}++function asOutputIndex(value: unknown): number | null {+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : null;+}++function repairableItemType(item: Record<string, unknown>): RepairableItemType | null {+ return item.type === "message" || item.type === "reasoning" ? item.type : null;+}++function mintCanonicalId(type: RepairableItemType, scope: string, outputIndex: number): string {+ return `${REPAIRABLE_PREFIXES[type]}ocx_${scope}_${outputIndex}`;+}++function createRepairState(config: ResponsesItemIdRepairConfig, budget?: TranslatorBudget): ResponsesItemIdRepairState {+ const state = {+ repairMissingTerminalIds: config.repairMissingTerminalIds === true,+ repairInvalidIds: config.repairInvalidIds === true,+ placeholders: {+ message: new Set(config.message ?? []),+ reasoning: new Set(config.reasoning ?? []),+ },+ outputIds: {+ message: new Map<number, string>(),+ reasoning: new Map<number, string>(),+ },+ rawIds: new Map<string, string>(),+ scope: randomUUID().replace(/-/g, ""),+ budget,+ };+ budget?.chargeRetained(new TextEncoder().encode(JSON.stringify({+ message: [...state.placeholders.message],+ reasoning: [...state.placeholders.reasoning],+ scope: state.scope,+ })).byteLength, { kind: "item_ids" });+ return state;+}++function rememberMappedId(+ state: ResponsesItemIdRepairState,+ outputIndex: number,+ item: Record<string, unknown>,+): string | null {+ const type = repairableItemType(item);+ if (!type) return null;+ const existing = state.outputIds[type].get(outputIndex);+ if (existing) return existing;+ const rawId = typeof item.id === "string" ? item.id : undefined;+ if (!rawId) return null;+ const mapped = state.placeholders[type].has(rawId)+ ? mintCanonicalId(type, state.scope, outputIndex)+ : state.repairInvalidIds && !rawId.startsWith(REPAIRABLE_PREFIXES[type])+ // An existing id without the canonical msg_/rs_ prefix (bare UUIDs from+ // DeepSeek's Responses route) leaves Codex stuck on Thinking (#938).+ ? mintCanonicalId(type, state.scope, outputIndex)+ : state.repairMissingTerminalIds+ ? rawId+ : null;+ if (!mapped) return null;+ state.budget?.chargeRetained(new TextEncoder().encode(JSON.stringify([outputIndex, rawId, mapped])).byteLength, { kind: "item_ids" });+ state.outputIds[type].set(outputIndex, mapped);+ // Keyed by (index, rawId): an upstream that reuses one placeholder id across+ // several items must not collapse them into the last item's canonical id.+ if (rawId !== mapped) state.rawIds.set(JSON.stringify([outputIndex, rawId]), mapped);+ return mapped;+}++function rewriteOutputItem(+ state: ResponsesItemIdRepairState,+ outputIndex: number,+ item: Record<string, unknown>,+): { item: Record<string, unknown>; changed: boolean } {+ const mapped = rememberMappedId(state, outputIndex, item);+ if (!mapped) return { item, changed: false };+ const currentId = typeof item.id === "string" ? item.id : undefined;+ if (currentId === mapped) return { item, changed: false };+ if (currentId === undefined && !state.repairMissingTerminalIds) return { item, changed: false };+ return { item: { ...item, id: mapped }, changed: true };+}++function rewriteItemIdField(+ state: ResponsesItemIdRepairState,+ event: Record<string, unknown>,+ outputIndex: number,+): { event: Record<string, unknown>; changed: boolean } {+ const eventType = typeof event.type === "string" ? ITEM_ID_EVENT_TYPES[event.type] : undefined;+ if (!eventType) return { event, changed: false };+ const currentId = typeof event.item_id === "string" ? event.item_id : undefined;+ // content_part.* events are shared between message and reasoning items (DeepSeek's+ // streamed reasoning wraps its text in content parts), so the static event-type map+ // can point at the wrong id table. The rewrite is therefore exact-only when the+ // event carries an item_id: it fires when (output_index, item_id) names an id the+ // item stream already repaired, and otherwise leaves the event alone — an unknown+ // id belongs to an item this repair never touched (function_call, already-canonical+ // ids), and guessing by index could borrow a sibling item's identity. The index+ // table serves only events with NO item_id, where repairMissingTerminalIds+ // explicitly opts into the positional guess (the pre-existing contract).+ if (currentId !== undefined) {+ const mapped = state.rawIds.get(JSON.stringify([outputIndex, currentId]));+ if (!mapped || currentId === mapped) return { event, changed: false };+ return { event: { ...event, item_id: mapped }, changed: true };+ }+ if (!state.repairMissingTerminalIds) return { event, changed: false };+ const mapped = state.outputIds[eventType].get(outputIndex);+ if (!mapped) return { event, changed: false };+ return { event: { ...event, item_id: mapped }, changed: true };+}++function rewriteResponseSnapshot(+ state: ResponsesItemIdRepairState,+ response: Record<string, unknown>,+): { response: Record<string, unknown>; changed: boolean } {+ if (!Array.isArray(response.output)) return { response, changed: false };+ let changed = false;+ const output = response.output.map((item, outputIndex) => {+ if (!isPlainObject(item)) return item;+ const rewritten = rewriteOutputItem(state, outputIndex, item);+ changed = changed || rewritten.changed;+ return rewritten.item;+ });+ return changed ? { response: { ...response, output }, changed: true } : { response, changed: false };+}++function repairEventPayload(+ payload: string,+ state: ResponsesItemIdRepairState,+): string {+ let event: unknown;+ try {+ event = JSON.parse(payload);+ } catch {+ return payload;+ }+ if (!isPlainObject(event)) return payload;++ let changed = false;+ let nextEvent = event;+ const outputIndex = asOutputIndex(event.output_index);+ if (outputIndex !== null && isPlainObject(event.item)) {+ const rewritten = rewriteOutputItem(state, outputIndex, event.item);+ if (rewritten.changed) {+ nextEvent = { ...nextEvent, item: rewritten.item };+ changed = true;+ }+ }+ if (outputIndex !== null) {+ const rewritten = rewriteItemIdField(state, nextEvent, outputIndex);+ if (rewritten.changed) {+ nextEvent = rewritten.event;+ changed = true;+ }+ }+ if (isPlainObject(event.response)) {+ const rewritten = rewriteResponseSnapshot(state, event.response);+ if (rewritten.changed) {+ nextEvent = { ...nextEvent, response: rewritten.response };+ changed = true;+ }+ }+ if (!changed) return payload;+ const rewritten = JSON.stringify(nextEvent);+ const bytes = new TextEncoder().encode(rewritten).byteLength;+ const reservation = state.budget?.reserveTransient(bytes, { kind: "item_ids" });+ reservation?.commitRetained();+ if (state.budget) queueMicrotask(() => state.budget?.releaseRetained(bytes, { kind: "item_ids" }));+ return rewritten;+}++/**+ * [Decision Log]+ * - 목적과 의도: 일부 openai-responses 호환 게이트웨이가 재사용/누락하는 message·reasoning item id를+ * downstream SSE에서만 선택적으로 보정해 Codex Desktop 카드 상관관계를 안정화한다.+ * - 기존 구현 및 제약 조건: 기본 passthrough는 바이트 단위 그대로 relay되고, local replay 상태는 raw+ * upstream 응답을 기억한다. function_call id / call_id는 upstream 의미가 있으므로 절대 바꾸면 안 된다.+ * - 검토한 주요 대안: 모든 passthrough SSE를 항상 재작성하기, raw inspect 분기까지 함께 재작성하기,+ * function_call 포함 전체 item id를 정규화하기.+ * - 선택한 방식: provider-local opt-in 설정이 있을 때만 client-facing SSE 분기에 한정해 exact+ * message/reasoning placeholder id와 missing terminal id를 item type + output_index 기준으로 보정하고,+ * event-level item_id는 명시적인 message/reasoning lifecycle allowlist에서만 바꾼다.+ * - 다른 대안 대신 이 방식을 선택한 이유: disabled-by-default byte-for-byte passthrough를 유지하면서,+ * previous_response_id replay는 raw upstream snapshot을 계속 사용해 synthetic id가 upstream으로+ * 역류하지 않게 막을 수 있다.+ * - 장점, 단점 및 영향: 기본 경로는 변하지 않는다. malformed stream이 output_index를 다른 item+ * type에 재사용해도 function_call id/call_id는 보존된다. opt-in 게이트웨이는 sequential streams에서도+ * 고유한 canonical id를 얻지만, 보정이 필요한 경우에만 JS stream 재작성 비용을 지불한다.+ */+/** Stateful payload rewrite for composition with other client-facing SSE transforms. */+export function createResponsesItemIdPayloadRewrite(+ config: ResponsesItemIdRepairConfig,+ budget?: TranslatorBudget,+): SsePayloadRewrite {+ const state = createRepairState(config, budget);+ return (payload) => repairEventPayload(payload, state);+}++export function relaySseWithResponsesItemIdRepair(+ body: ReadableStream<Uint8Array>,+ config: ResponsesItemIdRepairConfig,+ budget: TranslatorBudget,+): ReadableStream<Uint8Array> {+ return relaySseWithPayloadRewrite(body, createResponsesItemIdPayloadRewrite(config, budget), budget);+}++export function hasResponsesItemIdRepair(config: ResponsesItemIdRepairConfig | undefined): boolean {+ return config?.repairMissingTerminalIds === true+ || config?.repairInvalidIds === true+ || (config?.message?.length ?? 0) > 0+ || (config?.reasoning?.length ?? 0) > 0;+}++/**+ * Client-facing id normalization for a WHOLE bounded-JSON Responses object.+ *+ * The bounded-JSON policy (#875) answers a streaming client by synthesizing SSE+ * from a completed JSON body, and reframes the same body into events for WS+ * turns. Neither path goes through the SSE relay, so neither picks up the SSE+ * item-id rewrite — a provider that needs id repair would get it on a streaming+ * response and silently lose it the moment the reliability policy switched the+ * upstream to bounded JSON. This applies the same rewrite to the object so all+ * three paths agree. Raw recorded state is untouched: recording happens before+ * any normalization.+ */+export function repairResponsesJsonItemIds(+ response: Record<string, unknown>,+ config: ResponsesItemIdRepairConfig,+ budget?: TranslatorBudget,+): Record<string, unknown> {+ const state = createRepairState(config, budget);+ const rewritten = rewriteResponseSnapshot(state, response);+ return rewritten.changed ? rewritten.response : response;+}diff --git a/packages/model-compat/src/upstream/server/responses-model-rewrite.ts b/packages/model-compat/src/upstream/server/responses-model-rewrite.tsnew file mode 100644index 0000000000..b0ed8a3e6c--- /dev/null+++ b/packages/model-compat/src/upstream/server/responses-model-rewrite.ts@@ -0,0 +1,29 @@+import type { SsePayloadRewrite } from "./sse-payload-rewrite";++function rewriteResponseObjectModel(value: unknown, responseModelId: string): boolean {+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;+ const response = value as Record<string, unknown>;+ if (typeof response.model !== "string" || response.model === responseModelId) return false;+ response.model = responseModelId;+ return true;+}++/** Rewrite only existing Responses model metadata; unrelated and malformed payloads stay byte-identical. */+export function rewriteResponsesModelJson(json: string, responseModelId: string): string {+ let parsed: unknown;+ try {+ parsed = JSON.parse(json);+ } catch {+ return json;+ }+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return json;+ const record = parsed as Record<string, unknown>;+ const rootChanged = rewriteResponseObjectModel(record, responseModelId);+ const nestedChanged = rewriteResponseObjectModel(record.response, responseModelId);+ const changed = rootChanged || nestedChanged;+ return changed ? JSON.stringify(record) : json;+}++export function createResponsesModelPayloadRewrite(responseModelId: string): SsePayloadRewrite {+ return payload => rewriteResponsesModelJson(payload, responseModelId);+}diff --git a/packages/model-compat/src/upstream/server/responses-reasoning-summary-rewrite.ts b/packages/model-compat/src/upstream/server/responses-reasoning-summary-rewrite.tsnew file mode 100644index 0000000000..55c6d8ae7b--- /dev/null+++ b/packages/model-compat/src/upstream/server/responses-reasoning-summary-rewrite.ts@@ -0,0 +1,178 @@+import type { SsePayloadRewrite } from "./sse-payload-rewrite";++/**+ * Route content-channel reasoning from native-Responses upstreams through the+ * expandable summary channel (issue #45).+ *+ * Codex renders the expandable reasoning trace from the Responses reasoning+ * item's `summary[]` channel. DeepSeek's native `/responses` endpoint emits+ * raw thinking on the content channel instead (`response.reasoning_text.delta`+ * plus items with `content: [{type: "reasoning_text", text}]` and an empty+ * `summary`), so routed DeepSeek turns showed the "Worked for Xs" timer with+ * nothing to expand. Native OpenAI upstreams already emit summary-channel+ * events; this rewrite is a no-op for them (no reasoning_text events to+ * rewrite) and only engages when the upstream produces content-channel+ * reasoning.+ *+ * Replay compatibility: Codex echoes the reasoning item it received back into+ * the next request's input. DeepSeek's Responses API accepts summary-shaped+ * reasoning input items (verified live), so the rewrite round-trips.+ */++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}++function reasoningTextOf(item: Record<string, unknown>): string {+ if (!Array.isArray(item.content)) return "";+ return item.content+ .filter((part): part is Record<string, unknown> => isPlainObject(part) && part.type === "reasoning_text")+ .map(part => (typeof part.text === "string" ? part.text : ""))+ .join("");+}++/** Move a reasoning item's content channel into the summary channel. */+function reasoningItemToSummaryShape(item: Record<string, unknown>): Record<string, unknown> {+ if (item.type !== "reasoning") return item;+ // `encrypted_content` is opaque, state-bearing provider data, so the entire item must retain its+ // upstream shape unless that backend has an explicit replay contract permitting a rewrite. This+ // defensively protects content-channel backends that do issue blobs when the client replays the+ // stored item. The delta rewrite can still provide the expandable trace for the live turn.+ // DeepSeek — the provider this rewrite was verified against — is `statelessResponses` and issues+ // no blob, so it is unaffected.+ if (typeof item.encrypted_content === "string" && item.encrypted_content.length > 0) return item;+ const text = reasoningTextOf(item);+ // Items that already use the summary channel (or carry no content text at+ // all) are left untouched: rewriting them could clear a valid summary.+ if (text.length === 0) return item;+ const next: Record<string, unknown> = { ...item };+ delete next.content;+ next.summary = [{ type: "summary_text", text }];+ return next;+}++/**+ * Rewrite one parsed SSE payload in place of the content channel, or return+ * `null` when nothing changed (caller keeps the original payload).+ */+function rewritePayload(payload: Record<string, unknown>): Record<string, unknown> | null {+ switch (payload.type) {+ case "response.reasoning_text.delta": {+ const next: Record<string, unknown> = {+ type: "response.reasoning_summary_text.delta",+ item_id: payload.item_id,+ output_index: payload.output_index,+ summary_index: 0,+ delta: payload.delta,+ };+ if (payload.sequence_number !== undefined) next.sequence_number = payload.sequence_number;+ return next;+ }+ case "response.reasoning_text.done": {+ const next: Record<string, unknown> = {+ type: "response.reasoning_summary_text.done",+ item_id: payload.item_id,+ output_index: payload.output_index,+ summary_index: 0,+ text: payload.text,+ };+ if (payload.sequence_number !== undefined) next.sequence_number = payload.sequence_number;+ return next;+ }+ default: {+ let changed = false;+ const next: Record<string, unknown> = { ...payload };+ if (isPlainObject(next.item) && next.item.type === "reasoning") {+ const rewritten = reasoningItemToSummaryShape(next.item);+ if (rewritten !== next.item) {+ next.item = rewritten;+ changed = true;+ }+ }+ // SSE event shape: {type: "response.completed", response: {output}}.+ const response = isPlainObject(next.response) ? { ...next.response } : null;+ if (response && Array.isArray(response.output)) {+ const output = response.output.map(item => {+ if (!isPlainObject(item) || item.type !== "reasoning") return item;+ const rewritten = reasoningItemToSummaryShape(item);+ if (rewritten !== item) changed = true;+ return rewritten;+ });+ if (changed) {+ response.output = output;+ next.response = response;+ }+ }+ // Bare response document shape (non-streaming passthrough):+ // {object: "response", output: [...]}.+ if (Array.isArray(next.output)) {+ const output = next.output.map(item => {+ if (!isPlainObject(item) || item.type !== "reasoning") return item;+ const rewritten = reasoningItemToSummaryShape(item);+ if (rewritten !== item) changed = true;+ return rewritten;+ });+ if (changed) next.output = output;+ }+ return changed ? next : null;+ }+ }+}++/** Payload rewrite for passthrough relays whose upstream emits content-channel reasoning. */+export function createReasoningSummaryChannelPayloadRewrite(): SsePayloadRewrite {+ return (payload: string): string => {+ let parsed: unknown;+ try {+ parsed = JSON.parse(payload);+ } catch {+ return payload;+ }+ if (!isPlainObject(parsed)) return payload;+ const rewritten = rewritePayload(parsed);+ return rewritten !== null ? JSON.stringify(rewritten) : payload;+ };+}++/**+ * Object-level variant for the non-streaming passthrough: the bounded-JSON+ * relay bypasses the SSE payload rewrite, so reasoning items inside a full+ * Responses JSON document need the same normalization before plain JSON+ * serialization or forced JSON-to-SSE reframing. Returns the same reference+ * when nothing changed.+ */+export function rewriteReasoningSummaryInJson(value: unknown): unknown {+ if (!isPlainObject(value)) return value;+ const rewritten = rewritePayload(value);+ return rewritten !== null ? rewritten : value;+}++/** String-level variant of {@link rewriteReasoningSummaryInJson}. */+export function rewriteReasoningSummaryInJsonString(json: string): string {+ let parsed: unknown;+ try {+ parsed = JSON.parse(json);+ } catch {+ return json;+ }+ const rewritten = rewriteReasoningSummaryInJson(parsed);+ return rewritten === parsed ? json : JSON.stringify(rewritten);+}++/**+ * True when a routed native-Responses provider emits content-channel reasoning+ * (raw `reasoning_text`) instead of the summary channel. DeepSeek's+ * `/responses` endpoint is the current example: it ships raw thinking with an+ * empty `summary` and keeps `preserveReasoningContentModels` so multi-turn+ * replays round-trip.+ */+export function routeUsesContentChannelReasoning(+ provider: { statelessResponses?: boolean; preserveReasoningContentModels?: string[] },+ modelId: string,+): boolean {+ if (provider.statelessResponses === true) return true;+ const preserved = provider.preserveReasoningContentModels;+ const normalizedModelId = modelId.toLowerCase();+ return Array.isArray(preserved)+ && preserved.some(id => id.toLowerCase() === normalizedModelId);+}diff --git a/packages/model-compat/src/upstream/server/responses-self-named-namespace-scrub.ts b/packages/model-compat/src/upstream/server/responses-self-named-namespace-scrub.tsnew file mode 100644index 0000000000..b0de5d8348--- /dev/null+++ b/packages/model-compat/src/upstream/server/responses-self-named-namespace-scrub.ts@@ -0,0 +1,181 @@+import type { SsePayloadRewrite } from "./sse-payload-rewrite";++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}++export interface SelfNamedNamespaceScrubAuthorization {+ customToolCallNames: ReadonlySet<string>;+ functionCallNames: ReadonlySet<string>;+}++function collectBareToolSpecs(+ bareCustomNames: Set<string>,+ bareFunctionNames: Set<string>,+ sameNameNamespacedCustomNames: Set<string>,+ sameNameNamespacedFunctionNames: Set<string>,+ specs: unknown,+): void {+ if (!Array.isArray(specs)) return;+ for (const spec of specs) {+ if (!isPlainObject(spec)) continue;+ if (spec.type === "namespace" && Array.isArray(spec.tools)) {+ const namespace = typeof spec.name === "string" ? spec.name : undefined;+ for (const inner of spec.tools) {+ if (!isPlainObject(inner) || typeof inner.name !== "string") continue;+ if (namespace !== "functions" && namespace === inner.name) {+ if (inner.type === "custom") sameNameNamespacedCustomNames.add(inner.name);+ else if (inner.type === "function") sameNameNamespacedFunctionNames.add(inner.name);+ }+ if (namespace === "functions") {+ if (inner.type === "custom") bareCustomNames.add(inner.name);+ else if (inner.type === "function") bareFunctionNames.add(inner.name);+ }+ }+ continue;+ }+ // `buildTools` (parser.ts) also accepts the Chat-shaped `{ type: "function", function: { name } }`+ // declaration, and the undeclared-tool guard authorizes it the same way. Reading only+ // `spec.name` here left such a function out of the raw-body set, so the intersection dropped+ // it and a self-named echo for it reached Codex again.+ const nestedFunction = spec.type === "function" && isPlainObject(spec.function) ? spec.function : undefined;+ const name = typeof spec.name === "string" && spec.name.length > 0+ ? spec.name+ : typeof nestedFunction?.name === "string" && nestedFunction.name.length > 0+ ? nestedFunction.name+ : undefined;+ if (!name) continue;+ const namespace = typeof spec.namespace === "string" ? spec.namespace : undefined;+ if (namespace !== "functions" && namespace === name) {+ if (spec.type === "custom") sameNameNamespacedCustomNames.add(name);+ else if (spec.type === "function") sameNameNamespacedFunctionNames.add(name);+ }+ if (!namespace || namespace === "functions") {+ if (spec.type === "custom") bareCustomNames.add(name);+ else if (spec.type === "function") bareFunctionNames.add(name);+ }+ }+}++/** Bare custom tools authorized by this turn, scoped to each response call type. */+export function collectSelfNamedNamespaceScrubAuthorization(+ body: unknown,+ authorizedBareCustomToolNames: ReadonlySet<string>,+ authorizedBareFunctionToolNames: ReadonlySet<string>,+): SelfNamedNamespaceScrubAuthorization {+ const bareCustomNames = new Set<string>();+ const bareFunctionNames = new Set<string>();+ const sameNameNamespacedCustomNames = new Set<string>();+ const sameNameNamespacedFunctionNames = new Set<string>();+ if (isPlainObject(body)) {+ collectBareToolSpecs(+ bareCustomNames,+ bareFunctionNames,+ sameNameNamespacedCustomNames,+ sameNameNamespacedFunctionNames,+ body.tools,+ );+ if (Array.isArray(body.input)) {+ for (const item of body.input) {+ if (+ isPlainObject(item)+ && (item.type === "additional_tools" || item.type === "tool_search_output")+ ) {+ collectBareToolSpecs(+ bareCustomNames,+ bareFunctionNames,+ sameNameNamespacedCustomNames,+ sameNameNamespacedFunctionNames,+ item.tools,+ );+ }+ }+ }+ }+ const authorizedCustomNames = [...bareCustomNames]+ .filter(name => authorizedBareCustomToolNames.has(name));+ const authorizedFunctionNames = new Set([+ ...authorizedCustomNames,+ ...[...bareFunctionNames].filter(name => authorizedBareFunctionToolNames.has(name)),+ ]);+ return {+ customToolCallNames: new Set(+ authorizedCustomNames.filter(name => !sameNameNamespacedCustomNames.has(name)),+ ),+ functionCallNames: new Set(+ [...authorizedFunctionNames].filter(name => !sameNameNamespacedFunctionNames.has(name)),+ ),+ };+}++/**+ * Drop a tool-call `namespace` that merely repeats the call's own `name` (#3217).+ *+ * codex-rs resolves a client tool call as `ToolName::new(namespace, name)` and treats only+ * `None | "" | "functions"` as the default namespace; anything else is concatenated into a flat+ * name before routing. A backend answer of `{ name: "exec", namespace: "exec" }` therefore+ * becomes `execexec`, which no client tool matches, and Codex re-issues the same call forever.+ * The malformed Spark shape is scrubbed only when the current turn authorized a bare custom tool+ * with that name. A genuine namespaced tool may intentionally use the same namespace and name.+ * The adapter fix that stops provoking the answer lives in `stripSparkCompatibility`; this is the+ * belt to that suspender.+ */+export function scrubSelfNamedToolCallNamespace(+ value: unknown,+ authorization: SelfNamedNamespaceScrubAuthorization,+): { value: unknown; changed: boolean } {+ if (Array.isArray(value)) {+ let changed = false;+ const out = value.map(entry => {+ const result = scrubSelfNamedToolCallNamespace(entry, authorization);+ changed ||= result.changed;+ return result.value;+ });+ return changed ? { value: out, changed: true } : { value, changed: false };+ }+ if (!isPlainObject(value)) return { value, changed: false };+ let changed = false;+ const out: Record<string, unknown> = {};+ for (const [key, entry] of Object.entries(value)) {+ const result = scrubSelfNamedToolCallNamespace(entry, authorization);+ out[key] = result.value;+ changed ||= result.changed;+ }+ const authorizedNames = value.type === "custom_tool_call"+ ? authorization.customToolCallNames+ : value.type === "function_call"+ ? authorization.functionCallNames+ : undefined;+ if (+ authorizedNames+ && typeof value.name === "string"+ && value.name.length > 0+ && value.namespace === value.name+ && authorizedNames.has(value.name)+ ) {+ delete out.namespace;+ changed = true;+ }+ return changed ? { value: out, changed: true } : { value, changed: false };+}++export function scrubSelfNamedToolCallNamespaceInJson(+ text: string,+ authorization: SelfNamedNamespaceScrubAuthorization,+): string {+ if (!text.includes("\"namespace\"")) return text;+ let payload: unknown;+ try {+ payload = JSON.parse(text);+ } catch {+ return text;+ }+ const result = scrubSelfNamedToolCallNamespace(payload, authorization);+ return result.changed ? JSON.stringify(result.value) : text;+}++export function createSelfNamedToolCallNamespaceScrubRewrite(+ authorization: SelfNamedNamespaceScrubAuthorization,+): SsePayloadRewrite {+ return payload => scrubSelfNamedToolCallNamespaceInJson(payload, authorization);+}diff --git a/packages/model-compat/src/upstream/server/responses-snapshot-codec.ts b/packages/model-compat/src/upstream/server/responses-snapshot-codec.tsnew file mode 100644index 0000000000..2de390fe35--- /dev/null+++ b/packages/model-compat/src/upstream/server/responses-snapshot-codec.ts@@ -0,0 +1,14 @@+/** Shared snapshot wire primitives; no retention state or policy. */++export function isPlainObject(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}++export type RetainedOutputItem = {+ item: Record<string, unknown>;+ sourceBytes: number;+};++export function jsonBlock(event: Record<string, unknown>): string {+ return `data: ${JSON.stringify(event)}`;+}diff --git a/packages/model-compat/src/upstream/server/responses-snapshot-repair.ts b/packages/model-compat/src/upstream/server/responses-snapshot-repair.tsnew file mode 100644index 0000000000..389b837490--- /dev/null+++ b/packages/model-compat/src/upstream/server/responses-snapshot-repair.ts@@ -0,0 +1,609 @@+/**+ * Provider-opt-in repair for Responses-compatible gateways that return sparse+ * lifecycle snapshots (#893): field backfills for missing canonical fields,+ * AND lifecycle event injection so Codex clients actually commit the turn.+ *+ * Field-repair semantics (snapshot fields, item/part backfills, retention+ * bounds) are adopted from PR #928 (0xWinner98) with attribution. The+ * lifecycle-completion layer is new: #928's exact-issue test expects no+ * `output_item.done` and a terminal `output: []` — normalization without+ * commitment, which the canonical bridge contract (src/bridge.ts) shows is+ * not enough for Codex to commit the message.+ *+ * Design:+ * - One stateful tracker per stream. Existing upstream values are always+ * authoritative; only absent or structurally invalid fields are backfilled.+ * - Event injection happens only for items PROVEN open at a terminal event+ * (never for content the gateway closed itself).+ * - Ambiguous, gapped, malformed, oversized, or contradictory shapes taint+ * the tracker: no injections and no output reconstruction afterwards+ * (fail closed; explicit `output: []` from the gateway stays authoritative).+ */++import type { TranslatorBudget } from "../lib/translator-budget";+import {+ MAX_COMPLETED_OUTPUT_ITEMS,+ MAX_COMPLETED_OUTPUT_ITEM_SOURCE_BYTES,+} from "./relay";+import { sseDataPayload, type SseBlockRewrite } from "./sse-payload-rewrite";+import { isPlainObject, jsonBlock, type RetainedOutputItem } from "./responses-snapshot-codec";++const RESPONSE_EVENT_STATUSES: Readonly<Record<string, string>> = {+ "response.created": "in_progress",+ "response.in_progress": "in_progress",+ "response.completed": "completed",+ "response.failed": "failed",+ "response.incomplete": "incomplete",+ "response.queued": "queued",+};++type RequestDefaults = {+ parallelToolCalls: boolean;+ toolChoice: unknown;+ tools: unknown[];+};++function isStructurallyValidToolChoice(value: unknown): boolean {+ return (typeof value === "string" && value.trim().length > 0)+ || (isPlainObject(value) && typeof value.type === "string" && value.type.trim().length > 0);+}++function requestDefaults(requestBody: unknown): RequestDefaults {+ const request = isPlainObject(requestBody) ? requestBody : {};+ return {+ parallelToolCalls: typeof request.parallel_tool_calls === "boolean"+ ? request.parallel_tool_calls+ : true,+ toolChoice: isStructurallyValidToolChoice(request.tool_choice) ? request.tool_choice : "auto",+ tools: Array.isArray(request.tools) ? request.tools : [],+ };+}++function repairOutputTextPart(part: Record<string, unknown>): Record<string, unknown> {+ if (part.type !== "output_text") return part;+ const needsText = typeof part.text !== "string";+ const needsAnnotations = !Array.isArray(part.annotations);+ if (!needsText && !needsAnnotations) return part;+ return {+ ...part,+ ...(needsText ? { text: "" } : {}),+ ...(needsAnnotations ? { annotations: [] } : {}),+ };+}++function repairSummaryPart(part: Record<string, unknown>): Record<string, unknown> {+ if (part.type !== "summary_text" || typeof part.text === "string") return part;+ return { ...part, text: "" };+}++function repairOutputItem(+ item: Record<string, unknown>,+ inferredStatus?: string,+): Record<string, unknown> {+ let repaired = item;+ let changed = false;++ if (item.type === "reasoning") {+ const rawSummary = item.summary;+ const summary = Array.isArray(rawSummary)+ ? rawSummary.map((part) => isPlainObject(part) ? repairSummaryPart(part) : part)+ : [];+ changed = !Array.isArray(rawSummary)+ || summary.some((part, index) => part !== rawSummary[index]);+ if (changed) repaired = { ...repaired, summary };+ } else if (item.type === "message") {+ const rawContent = item.content;+ const content = Array.isArray(rawContent)+ ? rawContent.map((part) => isPlainObject(part) ? repairOutputTextPart(part) : part)+ : [];+ changed = !Array.isArray(rawContent)+ || content.some((part, index) => part !== rawContent[index]);+ // Responses output-message roles are the literal "assistant"; input roles are invalid here.+ changed = changed || item.role !== "assistant";+ if (changed) repaired = { ...repaired, content, role: "assistant" };+ }++ if (inferredStatus && (typeof repaired.status !== "string" || repaired.status.trim().length === 0)) {+ repaired = { ...repaired, status: inferredStatus };+ }+ return repaired;+}++function repairResponseSnapshot(+ response: Record<string, unknown>,+ defaultStatus: string,+ defaults: RequestDefaults,+ reconstructedOutput?: Record<string, unknown>[],+): Record<string, unknown> {+ const repaired = { ...response };+ let changed = false;+ const effectiveResponseStatus = typeof response.status === "string" && response.status.trim().length > 0+ ? response.status+ : defaultStatus;+ const outputStatus = effectiveResponseStatus === "completed" || effectiveResponseStatus === "incomplete"+ ? effectiveResponseStatus+ : undefined;++ if (reconstructedOutput) {+ repaired.output = reconstructedOutput;+ changed = true;+ } else if (Array.isArray(repaired.output)) {+ const output = repaired.output.map((item) => {+ if (!isPlainObject(item)) return item;+ const next = repairOutputItem(item, outputStatus);+ changed = changed || next !== item;+ return next;+ });+ if (changed) repaired.output = output;+ }+ if (typeof repaired.parallel_tool_calls !== "boolean") {+ repaired.parallel_tool_calls = defaults.parallelToolCalls;+ changed = true;+ }+ if (!isStructurallyValidToolChoice(repaired.tool_choice)) {+ repaired.tool_choice = defaults.toolChoice;+ changed = true;+ }+ if (!Array.isArray(repaired.tools)) {+ repaired.tools = defaults.tools;+ changed = true;+ }+ if (typeof repaired.status !== "string" || repaired.status.trim().length === 0) {+ repaired.status = defaultStatus;+ changed = true;+ }++ return changed ? repaired : response;+}++type OpenItem = {+ itemId: string;+ outputIndex: number;+ type: string;+ /** Message/reasoning items get lifecycle injections; other types never do. */+ injectable: boolean;+ /** The gateway opened a content part explicitly (or we injected one). */+ contentPartOpen: boolean;+ /** The gateway sent output_text.done for this item. */+ textDone: boolean;+ /** The gateway sent content_part.done for this item. */+ partDone: boolean;+ text: string;+ item: Record<string, unknown>;+};++/** Open-item retention bounds (#893 review): aggregate, not just per-item. */+const MAX_OPEN_ITEMS = MAX_COMPLETED_OUTPUT_ITEMS;+const MAX_OPEN_ITEM_AGGREGATE_TEXT_BYTES = MAX_COMPLETED_OUTPUT_ITEM_SOURCE_BYTES;++/**+ * Stateful block rewrite: field backfills + lifecycle completion injection.+ * `budget` bounds retained completed items (reconstruction only).+ */+export function createResponsesSnapshotBlockRewrite(+ requestBody?: unknown,+ budget?: TranslatorBudget,+): SseBlockRewrite {+ const defaults = requestDefaults(requestBody);+ const openItems = new Map<number, OpenItem>();+ const completedItems = new Map<number, RetainedOutputItem>();+ let aggregateItemBytes = 0;+ let aggregateOpenTextBytes = 0;+ let tainted = false;++ const releaseRetained = (): void => {+ if (aggregateItemBytes > 0) {+ budget?.releaseRetained(aggregateItemBytes, { kind: "retained_collectors" });+ }+ completedItems.clear();+ openItems.clear();+ aggregateItemBytes = 0;+ aggregateOpenTextBytes = 0;+ tainted = false;+ };++ const taintAndRelease = (): void => {+ // Fail closed means stop RETAINING too: open state and charged collectors+ // are released immediately, and no further state accumulates (#893 review).+ if (aggregateItemBytes > 0) {+ budget?.releaseRetained(aggregateItemBytes, { kind: "retained_collectors" });+ }+ completedItems.clear();+ openItems.clear();+ aggregateItemBytes = 0;+ aggregateOpenTextBytes = 0;+ tainted = true;+ };++ /** Drop one open item and refund its accumulated text from the aggregate. */+ const closeOpenItem = (index: number): void => {+ const open = openItems.get(index);+ if (!open) return;+ aggregateOpenTextBytes -= Buffer.byteLength(open.text, "utf8");+ openItems.delete(index);+ };++ const retainCompletedItem = (index: number, item: Record<string, unknown>): void => {+ if (tainted) return; // fail closed means stop retaining (#893 review)+ const sourceBytes = Buffer.byteLength(JSON.stringify(item), "utf8");+ const previous = completedItems.get(index);+ if (sourceBytes > MAX_COMPLETED_OUTPUT_ITEM_SOURCE_BYTES) {+ if (previous) {+ completedItems.delete(index);+ aggregateItemBytes -= previous.sourceBytes;+ budget?.releaseRetained(previous.sourceBytes, { kind: "retained_collectors" });+ }+ taintAndRelease();+ return;+ }+ const retainedDelta = sourceBytes - (previous?.sourceBytes ?? 0);+ if (retainedDelta > 0) {+ budget?.chargeRetained(retainedDelta, { kind: "retained_collectors" });+ } else if (retainedDelta < 0) {+ budget?.releaseRetained(-retainedDelta, { kind: "retained_collectors" });+ }+ completedItems.set(index, { item, sourceBytes });+ aggregateItemBytes += retainedDelta;+ while (completedItems.size > MAX_COMPLETED_OUTPUT_ITEMS+ || aggregateItemBytes > MAX_COMPLETED_OUTPUT_ITEM_SOURCE_BYTES) {+ let highestIndex = -1;+ for (const retainedIndex of completedItems.keys()) {+ if (retainedIndex > highestIndex) highestIndex = retainedIndex;+ }+ const evicted = completedItems.get(highestIndex);+ if (!evicted) break;+ completedItems.delete(highestIndex);+ aggregateItemBytes -= evicted.sourceBytes;+ budget?.releaseRetained(evicted.sourceBytes, { kind: "retained_collectors" });+ taintAndRelease();+ return;+ }+ };++ const completedItemSnapshot = (open: OpenItem): Record<string, unknown> => {+ if (open.type === "message") {+ return repairOutputItem({+ ...open.item,+ status: "completed",+ role: "assistant",+ content: [{ type: "output_text", text: open.text, annotations: [] }],+ }, "completed");+ }+ return repairOutputItem({ ...open.item, status: "completed" }, "completed");+ };++ const rewrite: SseBlockRewrite = (block: string): readonly string[] => {+ const payload = sseDataPayload(block);+ if (payload === null) return [block];+ let event: unknown;+ try {+ event = JSON.parse(payload);+ } catch {+ return [block];+ }+ if (!isPlainObject(event)) return [block];+ const type = typeof event.type === "string" ? event.type : "";+ let nextEvent: Record<string, unknown> = event;+ let changed = false;+ const outputIndex = Number.isInteger(event.output_index) && (event.output_index as number) >= 0+ ? event.output_index as number+ : undefined;+ const itemId = typeof event.item_id === "string" ? event.item_id : undefined;++ // --- item lifecycle tracking + field backfills -------------------------+ if (type === "response.output_item.added" && isPlainObject(event.item)) {+ const itemType = typeof event.item.type === "string" ? event.item.type : "";+ const id = typeof event.item.id === "string" ? event.item.id : undefined;+ if (outputIndex === undefined || !id) {+ taintAndRelease();+ } else {+ if (openItems.has(outputIndex)) taintAndRelease(); // contradictory reuse of an open index+ if (openItems.size >= MAX_OPEN_ITEMS) taintAndRelease(); // aggregate retention bound+ // Unsupported types (function_call, …) reserve their index but are+ // never injected — a sparse gateway that leaves one open blocks only+ // the terminal reconstruction, not message repair (#893 review).+ const injectable = itemType === "message" || itemType === "reasoning";+ if (!tainted) {+ openItems.set(outputIndex, {+ itemId: id,+ outputIndex,+ type: itemType,+ injectable,+ contentPartOpen: false,+ textDone: false,+ partDone: false,+ text: "",+ item: event.item,+ });+ }+ }+ const item = repairOutputItem(event.item, "in_progress");+ if (item !== event.item) {+ nextEvent = { ...nextEvent, item };+ changed = true;+ }+ }++ if (type === "response.output_item.done" && !isPlainObject(event.item)) {+ taintAndRelease();+ }++ if (type === "response.output_item.done" && isPlainObject(event.item)) {+ const item = repairOutputItem(event.item, "completed");+ if (item !== event.item) {+ nextEvent = { ...nextEvent, item };+ changed = true;+ }+ // Identity correlation: a done event only closes the tracked item when+ // id AND type agree — a mismatched done is a contradictory stream and+ // must go fail-closed rather than close/reconstruct the wrong item.+ const tracked = outputIndex !== undefined ? openItems.get(outputIndex) : undefined;+ const doneId = typeof event.item.id === "string" ? event.item.id : undefined;+ const doneType = typeof event.item.type === "string" ? event.item.type : undefined;+ if (tracked && (doneId !== tracked.itemId || doneType !== tracked.type)) {+ taintAndRelease();+ return [changed ? jsonBlock(nextEvent) : block];+ }+ if (outputIndex !== undefined && typeof item.type === "string" && item.type.trim().length > 0) {+ closeOpenItem(outputIndex);+ retainCompletedItem(outputIndex, item);+ } else {+ taintAndRelease();+ }+ }++ if ((type === "response.content_part.added" || type === "response.content_part.done")+ && isPlainObject(event.part)) {+ if (outputIndex !== undefined) {+ const open = openItems.get(outputIndex);+ // A PRESENT-but-mismatched item_id is contradictory lifecycle evidence,+ // exactly like output_item.done and output_text.done: the stream is+ // telling us our identity model for this index is wrong. Merely+ // ignoring it left the item open and let the terminal fabricate a full+ // closure sequence (content_part.added → output_text.done →+ // content_part.done → output_item.done) on top of a stream we do not+ // understand. Go fail-closed instead. An OMITTED item_id stays+ // legitimate and is still correlated by output_index.+ if (open && itemId !== undefined && itemId !== open.itemId) {+ taintAndRelease();+ return [changed ? jsonBlock(nextEvent) : block];+ }+ // Correlate by item_id when present: a mismatched event must not+ // mutate (or suppress injections for) the tracked item (#893 review).+ if (open && (itemId === undefined || itemId === open.itemId)) {+ if (type === "response.content_part.added") open.contentPartOpen = true;+ else open.partDone = true;+ }+ }+ const part = repairOutputTextPart(event.part);+ if (part !== event.part) {+ nextEvent = { ...nextEvent, part };+ changed = true;+ }+ }++ if ((type === "response.reasoning_summary_part.added"+ || type === "response.reasoning_summary_part.done") && isPlainObject(event.part)) {+ const part = repairSummaryPart(event.part);+ if (part !== event.part) {+ nextEvent = { ...nextEvent, part };+ changed = true;+ }+ }++ if ((type === "response.output_text.delta" || type === "response.output_text.done")+ && !Array.isArray(event.logprobs)) {+ nextEvent = { ...nextEvent, logprobs: [] };+ changed = true;+ }+ if (type === "response.output_text.delta" && typeof event.delta === "string" && outputIndex !== undefined) {+ const open = openItems.get(outputIndex);+ // Same identity contract as the *.done terminals: a present-but-foreign+ // item_id on a tracked index means our model of this index is wrong, and+ // reconstructing from the text we DID accept would ship a message the+ // upstream never assembled that way.+ if (open && itemId !== undefined && itemId !== open.itemId) {+ taintAndRelease();+ return [changed ? jsonBlock(nextEvent) : block];+ }+ if (open && (itemId === undefined || itemId === open.itemId)) {+ const deltaBytes = Buffer.byteLength(event.delta, "utf8");+ open.text += event.delta;+ aggregateOpenTextBytes += deltaBytes;+ // Unbounded text accumulation is a retention hole (#893 review):+ // overshoot per-item or aggregate caps and the stream goes fail-closed.+ if (Buffer.byteLength(open.text, "utf8") > MAX_COMPLETED_OUTPUT_ITEM_SOURCE_BYTES+ || aggregateOpenTextBytes > MAX_OPEN_ITEM_AGGREGATE_TEXT_BYTES) {+ taintAndRelease();+ }+ }+ }+ if (type === "response.output_text.done") {+ if (outputIndex !== undefined) {+ const open = openItems.get(outputIndex);+ // Identity correlation, same contract as output_item.done above: a+ // text-done carrying a DIFFERENT item_id for a tracked index is a+ // contradictory stream. Silently ignoring it used to leave the item+ // open, so the terminal then synthesized a second output_text.done and+ // output_item.done — a double close built on a stream we do not+ // understand (#1025 review blocker 2). Go fail-closed instead: forward+ // the block untouched and stop injecting for the rest of the stream.+ if (open && itemId !== undefined && itemId !== open.itemId) {+ taintAndRelease();+ return [changed ? jsonBlock(nextEvent) : block];+ }+ if (open && (itemId === undefined || itemId === open.itemId)) {+ open.textDone = true;+ if (typeof event.text === "string") {+ // Replacement must keep the aggregate honest and bounded, the+ // same as delta accumulation (#893 review).+ const previousBytes = Buffer.byteLength(open.text, "utf8");+ const nextBytes = Buffer.byteLength(event.text, "utf8");+ open.text = event.text;+ aggregateOpenTextBytes += nextBytes - previousBytes;+ if (nextBytes > MAX_COMPLETED_OUTPUT_ITEM_SOURCE_BYTES+ || aggregateOpenTextBytes > MAX_OPEN_ITEM_AGGREGATE_TEXT_BYTES) {+ taintAndRelease();+ }+ }+ }+ }+ if (typeof event.text !== "string") {+ nextEvent = { ...nextEvent, text: "" };+ changed = true;+ }+ }++ // --- lifecycle response snapshots --------------------------------------+ const responseStatus = Object.prototype.hasOwnProperty.call(RESPONSE_EVENT_STATUSES, type)+ ? RESPONSE_EVENT_STATUSES[type]+ : undefined;+ const isTerminal = type === "response.completed"+ || type === "response.failed"+ || type === "response.incomplete";++ if (responseStatus && isPlainObject(event.response)) {+ // Terminal output reconstruction stays in the injection layer below;+ // here the snapshot only gets field backfills.+ const response = repairResponseSnapshot(event.response, responseStatus, defaults);+ if (response !== event.response) {+ nextEvent = { ...nextEvent, response };+ changed = true;+ }+ }++ // --- lifecycle completion injection ------------------------------------+ // Only response.completed justifies synthesized closing events: a failed+ // or incomplete terminal must never fabricate completed output (#893 review).+ const isCompletedTerminal = type === "response.completed";+ const out: string[] = [];+ if (!tainted) {+ // A text delta for an item whose content part was never opened needs the+ // opening event first, or Codex never binds the text to a committed part.+ if (type === "response.output_text.delta" && outputIndex !== undefined) {+ const open = openItems.get(outputIndex);+ if (open && open.type === "message" && !open.contentPartOpen) {+ out.push(jsonBlock({+ type: "response.content_part.added",+ item_id: open.itemId,+ output_index: open.outputIndex,+ content_index: 0,+ part: { type: "output_text", text: "", annotations: [] },+ }));+ open.contentPartOpen = true;+ }+ }++ if (isCompletedTerminal && openItems.size > 0) {+ const closing = [...openItems.values()].sort((a, b) => a.outputIndex - b.outputIndex);+ for (const open of closing) {+ if (open.injectable && open.type === "message") {+ if (!open.contentPartOpen) {+ out.push(jsonBlock({+ type: "response.content_part.added",+ item_id: open.itemId,+ output_index: open.outputIndex,+ content_index: 0,+ part: { type: "output_text", text: "", annotations: [] },+ }));+ open.contentPartOpen = true;+ }+ if (!open.textDone) {+ out.push(jsonBlock({+ type: "response.output_text.done",+ item_id: open.itemId,+ output_index: open.outputIndex,+ content_index: 0,+ logprobs: [],+ text: open.text,+ }));+ open.textDone = true;+ }+ if (!open.partDone) {+ out.push(jsonBlock({+ type: "response.content_part.done",+ item_id: open.itemId,+ output_index: open.outputIndex,+ content_index: 0,+ part: { type: "output_text", text: open.text, annotations: [] },+ }));+ open.partDone = true;+ }+ }+ if (!open.injectable) continue; // never fabricate completions for other types+ const snapshot = completedItemSnapshot(open);+ out.push(jsonBlock({+ type: "response.output_item.done",+ output_index: open.outputIndex,+ item: snapshot,+ }));+ closeOpenItem(open.outputIndex);+ retainCompletedItem(open.outputIndex, snapshot);+ }+ }+ }++ // Terminal output reconstruction/canonical backfill: an explicit+ // `output: []` is authoritative; absent or malformed output on a+ // completed terminal becomes the retained items or the canonical empty+ // list (#893 review). Leftover non-injectable open items block+ // reconstruction only, not the message closing above.+ if (isCompletedTerminal && !tainted && isPlainObject(nextEvent.response)) {+ const response = nextEvent.response;+ const outputValue = (response as Record<string, unknown>).output;+ const outputExplicitArray = Array.isArray(outputValue);+ if (!outputExplicitArray) {+ const injectableOpen = [...openItems.values()].filter(open => open.injectable);+ const nonInjectableOpen = [...openItems.values()].filter(open => !open.injectable);+ if (completedItems.size > 0 && injectableOpen.length === 0 && nonInjectableOpen.length === 0) {+ const ordered = [...completedItems.entries()].sort(([left], [right]) => left - right);+ if (ordered.every(([index], position) => index === position)) {+ nextEvent = {+ ...nextEvent,+ response: { ...response, output: ordered.map(([, retained]) => retained.item) },+ };+ changed = true;+ } else {+ // A gap means at least one completed item is missing. Never compact+ // later indexes into a shorter array that only appears complete.+ tainted = true;+ }+ } else if (completedItems.size === 0 && openItems.size === 0) {+ nextEvent = { ...nextEvent, response: { ...response, output: [] } };+ changed = true;+ }+ }+ }++ out.push(changed ? jsonBlock(nextEvent) : block);+ if (isTerminal) releaseRetained();+ return out;+ };+ // Relays call this on every teardown path (terminal, EOF, cancel, error):+ // retained collectors and open-item state never outlive the stream.+ rewrite.dispose = releaseRetained;+ return rewrite;+}++/** Repair a non-streaming Responses JSON object without changing raw inspection state. */+export function repairResponsesSnapshotJson(payload: string, requestBody?: unknown): string {+ let response: unknown;+ try {+ response = JSON.parse(payload);+ } catch {+ return payload;+ }+ if (!isPlainObject(response)) return payload;+ // Canonical output for non-stream completed responses: absent or malformed+ // output becomes the canonical empty list; explicit arrays stay authoritative.+ if (!Array.isArray(response.output)) {+ const repaired = repairResponseSnapshot({ ...response, output: [] }, "completed", requestDefaults(requestBody));+ return JSON.stringify(repaired);+ }+ const repaired = repairResponseSnapshot(response, "completed", requestDefaults(requestBody));+ return repaired === response ? payload : JSON.stringify(repaired);+}++export function hasResponsesSnapshotRepair(enabled: boolean | undefined): enabled is true {+ return enabled === true;+}diff --git a/packages/model-compat/src/upstream/server/responses-tool-search-repair.ts b/packages/model-compat/src/upstream/server/responses-tool-search-repair.tsnew file mode 100644index 0000000000..1116173531--- /dev/null+++ b/packages/model-compat/src/upstream/server/responses-tool-search-repair.ts@@ -0,0 +1,267 @@+import {+ isTranslatorBudgetExceededError,+ TranslatorBudgetExceededError,+ type TranslatorBudget,+} from "../lib/translator-budget";+import {+ restoreRoutedToolSearchCalls,+} from "../responses/tool-search-compat";+import {+ replaceSseDataPayload,+ sseDataPayload,+ type SseBlockRewrite,+} from "./sse-payload-rewrite";++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}++type PendingArgumentBlock = {+ block: string;+ itemId?: string;+ outputIndex?: number;+ retainedBytes: number;+};++const MAX_PENDING_ARGUMENT_FRAMES = 256;+const MAX_PENDING_ARGUMENT_BYTES = 1024 * 1024;+const MAX_CLASSIFIED_ITEM_IDS = 256;+const MAX_CLASSIFIED_ITEM_ID_BYTES = 256 * 1024;++class ClassifiedItemIdCountExceededError extends Error {+ readonly code = "translation_buffer_limit";+ readonly kind = "item_ids";+ readonly limitItems = MAX_CLASSIFIED_ITEM_IDS;++ constructor() {+ super(`translator item_ids count exceeded ${MAX_CLASSIFIED_ITEM_IDS} items`);+ this.name = "ClassifiedItemIdCountExceededError";+ }+}++/**+ * Public Responses gateways stream a lowered search as a normal function lifecycle. Codex expects+ * only `tool_search_call` items, so classify each item before dropping its function-argument+ * frames. Unknown early argument frames stay bounded until their item arrives.+ */+export function createRoutedToolSearchRestoreBlockRewrite(+ names: ReadonlySet<string>,+ budget?: TranslatorBudget,+): SseBlockRewrite {+ const routedItemIds = new Set<string>();+ const ordinaryItemIds = new Set<string>();+ let classifiedItemIdBytes = 0;+ let pendingArguments: PendingArgumentBlock[] = [];+ let pendingArgumentBytes = 0;+ let passthrough = false;+ let disposed = false;++ const releaseAll = (): void => {+ if (disposed) return;+ disposed = true;+ if (pendingArgumentBytes > 0) {+ budget?.releaseRetained(pendingArgumentBytes, { kind: "retained_collectors" });+ }+ pendingArguments = [];+ pendingArgumentBytes = 0;+ if (classifiedItemIdBytes > 0) {+ budget?.releaseRetained(classifiedItemIdBytes, { kind: "item_ids" });+ }+ classifiedItemIdBytes = 0;+ routedItemIds.clear();+ ordinaryItemIds.clear();+ };++ const clearOrdinaryItemIds = (): void => {+ let releasedBytes = 0;+ for (const itemId of ordinaryItemIds) {+ releasedBytes += Buffer.byteLength(JSON.stringify(itemId), "utf8");+ }+ ordinaryItemIds.clear();+ classifiedItemIdBytes = Math.max(0, classifiedItemIdBytes - releasedBytes);+ if (releasedBytes > 0) budget?.releaseRetained(releasedBytes, { kind: "item_ids" });+ };++ const classifyItemId = (itemId: string, routed: boolean): void => {+ const target = routed ? routedItemIds : ordinaryItemIds;+ const previous = routed ? ordinaryItemIds : routedItemIds;+ if (target.has(itemId)) return;+ if (previous.delete(itemId)) {+ target.add(itemId);+ return;+ }++ if (routedItemIds.size + ordinaryItemIds.size >= MAX_CLASSIFIED_ITEM_IDS) {+ throw new ClassifiedItemIdCountExceededError();+ }+ const retainedBytes = Buffer.byteLength(JSON.stringify(itemId), "utf8");+ if (classifiedItemIdBytes + retainedBytes > MAX_CLASSIFIED_ITEM_ID_BYTES) {+ throw new TranslatorBudgetExceededError("item_ids", MAX_CLASSIFIED_ITEM_ID_BYTES);+ }+ budget?.chargeRetained(retainedBytes, { kind: "item_ids" });+ target.add(itemId);+ classifiedItemIdBytes += retainedBytes;+ };++ const retainPending = (+ block: string,+ itemId: string | undefined,+ outputIndex: number | undefined,+ ): readonly string[] | null => {+ const retainedBytes = Buffer.byteLength(block, "utf8");+ const overflow = pendingArguments.length >= MAX_PENDING_ARGUMENT_FRAMES+ || pendingArgumentBytes + retainedBytes > MAX_PENDING_ARGUMENT_BYTES;+ if (overflow) {+ const flushed = [...pendingArguments.map(pending => pending.block), block];+ if (pendingArgumentBytes > 0) {+ budget?.releaseRetained(pendingArgumentBytes, { kind: "retained_collectors" });+ }+ pendingArguments = [];+ pendingArgumentBytes = 0;+ passthrough = true;+ // Deliberately KEEP routedItemIds. Overflow means we stop buffering UNKNOWN frames, not+ // that we forget what we already classified: an item restored to `tool_search_call`+ // upstream of here would otherwise start emitting `function_call_arguments.*` again and+ // the client would see a mixed private/public lifecycle for one call.+ clearOrdinaryItemIds();+ return flushed;+ }+ if (retainedBytes > 0) {+ try {+ budget?.chargeRetained(retainedBytes, { kind: "retained_collectors" });+ } catch (error) {+ if (!isTranslatorBudgetExceededError(error)) throw error;+ const flushed = [...pendingArguments.map(pending => pending.block), block];+ if (pendingArgumentBytes > 0) {+ budget?.releaseRetained(pendingArgumentBytes, { kind: "retained_collectors" });+ }+ pendingArguments = [];+ pendingArgumentBytes = 0;+ passthrough = true;+ // Same reasoning as the frame/byte overflow above: an already-restored routed item+ // must keep its frames suppressed even once buffering stops.+ clearOrdinaryItemIds();+ return flushed;+ }+ }+ pendingArguments.push({ block, itemId, outputIndex, retainedBytes });+ pendingArgumentBytes += retainedBytes;+ return null;+ };++ const takePending = (+ itemId: string | undefined,+ outputIndex: number | undefined,+ ): string[] => {+ const matched: PendingArgumentBlock[] = [];+ const remaining: PendingArgumentBlock[] = [];+ for (const pending of pendingArguments) {+ const matches = pending.itemId !== undefined+ ? itemId !== undefined && pending.itemId === itemId+ : outputIndex !== undefined && pending.outputIndex === outputIndex;+ (matches ? matched : remaining).push(pending);+ }+ pendingArguments = remaining;+ const retainedBytes = matched.reduce((total, pending) => total + pending.retainedBytes, 0);+ if (retainedBytes > 0) {+ budget?.releaseRetained(retainedBytes, { kind: "retained_collectors" });+ pendingArgumentBytes = Math.max(0, pendingArgumentBytes - retainedBytes);+ }+ return matched.map(pending => {+ if (pending.itemId !== undefined || itemId === undefined) return pending.block;+ const payload = sseDataPayload(pending.block);+ if (payload === null) return pending.block;+ try {+ const parsed: unknown = JSON.parse(payload);+ return isPlainObject(parsed)+ ? replaceSseDataPayload(pending.block, JSON.stringify({ ...parsed, item_id: itemId }))+ : pending.block;+ } catch {+ return pending.block;+ }+ });+ };++ const rewrite: SseBlockRewrite = (block: string): readonly string[] => {+ if (disposed) return [block];+ const payload = sseDataPayload(block);+ if (payload === null) return [block];+ if (payload === "[DONE]") {+ releaseAll();+ return [block];+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(payload);+ } catch {+ return [block];+ }+ if (!isPlainObject(parsed)) return [block];++ const type = typeof parsed.type === "string" ? parsed.type : "";+ const terminal = type === "response.completed" || type === "response.failed" || type === "response.incomplete";+ // After overflow we stop BUFFERING unknown frames, but an item already restored to+ // `tool_search_call` must keep its public argument frames suppressed — otherwise the client+ // receives a private item followed by `function_call_arguments.*` for the same id, which is+ // exactly the mixed lifecycle this rewrite exists to prevent. Everything else passes through.+ if (passthrough) {+ if (terminal) {+ releaseAll();+ return [block];+ }+ const passthroughItemId = typeof parsed.item_id === "string" ? parsed.item_id : undefined;+ const isArgumentEvent = type === "response.function_call_arguments.delta"+ || type === "response.function_call_arguments.done";+ if (isArgumentEvent && passthroughItemId && routedItemIds.has(passthroughItemId)) return [];+ return [block];+ }+ const outputIndex = typeof parsed.output_index === "number"+ && Number.isInteger(parsed.output_index)+ && parsed.output_index >= 0+ ? parsed.output_index+ : undefined;+ if (+ (type === "response.output_item.added" || type === "response.output_item.done")+ && isPlainObject(parsed.item)+ && parsed.item.type === "function_call"+ && typeof parsed.item.name === "string"+ ) {+ const itemId = typeof parsed.item.id === "string" ? parsed.item.id : undefined;+ const routed = names.has(parsed.item.name);+ if (itemId) classifyItemId(itemId, routed);+ const pending = takePending(itemId, outputIndex);+ const restored = routed ? restoreRoutedToolSearchCalls(parsed, names) : { value: parsed, changed: false };+ const restoredBlock = restored.changed+ ? replaceSseDataPayload(block, JSON.stringify(restored.value))+ : block;+ // Classification is retained past `output_item.done` for BOTH kinds, until the terminal+ // event releases the bounded, budgeted state.+ //+ // `done` ends the item, not the id's relevance. Forgetting a ROUTED id let a trailing+ // `function_call_arguments.*` — which some upstreams emit after done — fall through to+ // the unknown-id branch and reach the client as a public frame for an item the client+ // was told is a private `tool_search_call`: the mixed lifecycle this rewrite exists to+ // prevent. Forgetting an ORDINARY id is not leak-shaped but is not free either, because+ // the same fall-through buffers its trailing frames as unknown and delays them until an+ // item that will never arrive. Neither id is dropped early.+ return routed ? [restoredBlock] : [...pending, restoredBlock];+ }++ const itemId = typeof parsed.item_id === "string" ? parsed.item_id : undefined;+ const argumentEvent = type === "response.function_call_arguments.delta"+ || type === "response.function_call_arguments.done";+ if (argumentEvent && (!itemId || (!routedItemIds.has(itemId) && !ordinaryItemIds.has(itemId)))) {+ return retainPending(block, itemId, outputIndex) ?? [];+ }+ if (argumentEvent && itemId && routedItemIds.has(itemId)) return [];++ if (!terminal) return [block];+ const restored = restoreRoutedToolSearchCalls(parsed, names);+ releaseAll();+ return restored.changed+ ? [replaceSseDataPayload(block, JSON.stringify(restored.value))]+ : [block];+ };+ rewrite.dispose = releaseAll;+ return rewrite;+}diff --git a/packages/model-compat/src/upstream/server/responses-undeclared-tool-guard.ts b/packages/model-compat/src/upstream/server/responses-undeclared-tool-guard.tsnew file mode 100644index 0000000000..cad1b39011--- /dev/null+++ b/packages/model-compat/src/upstream/server/responses-undeclared-tool-guard.ts@@ -0,0 +1,414 @@+import { collectAmbiguousDottedAliases, dottedAliasIsUnambiguous, wireToolInnerName } from "../responses/tool-name-aliases";+import {+ CODE_MODE_EXEC_TOOL_NAME,+ dottedToolName,+ namespacedToolName,+ normalizeDeclaredToolName,+} from "../types";+import { sseDataPayload, type SseBlockRewrite } from "./sse-payload-rewrite";++/** Item types the client executes through a request-declared wire name. */+const CLIENT_EXECUTED_CALL_TYPES = new Set(["function_call", "custom_tool_call"]);+/** Codex groups ordinary top-level tools here; unlike an MCP namespace, it has no wire prefix. */+const BUILTIN_FUNCTIONS_NAMESPACE = "functions";++/**+ * Hosted declarations whose response items the PROVIDER executes, keyed by the request+ * declaration type. These need no client answer, so their names are deliberately absent from+ * the request catalog and must not be read as an undeclared client tool.+ *+ * xAI surfaces hosted `x_search` as `custom_tool_call`. Probed 2026-08-23 against the OAuth CLI+ * destination: its hosted calls use an `xs_call-` call-id prefix. Observed call names were+ * `x_keyword_search`, `x_semantic_search`, and `x_user_search` — three literals for one tool,+ * which is why authorization keys on the declaration, item type, and call-id prefix, never on+ * the name.+ */+export type ProviderExecutedCallType = Readonly<{+ itemType: string;+ callIdPrefix: string;+}>;++type ProviderExecutedCallTypes = ReadonlySet<ProviderExecutedCallType>;++export const PROVIDER_EXECUTED_DECLARATION_CALL_TYPES = new Map<string, ProviderExecutedCallType>([+ ["x_search", { itemType: "custom_tool_call", callIdPrefix: "xs_call-" }],+]);++/** Nameless declaration kinds whose response items still require client execution. */+const NAMELESS_CLIENT_DECLARATION_CALL_TYPES = new Map([+ ["local_shell", "local_shell_call"],+ ["tool_search", "tool_search_call"],+ ["computer_use_preview", "computer_call"],+ ["computer_use", "computer_call"],+]);++const NAMELESS_CLIENT_CALL_DISPLAY_NAMES = new Map([+ ["local_shell_call", "local_shell"],+ ["tool_search_call", "tool_search"],+ ["computer_call", "computer_use"],+]);++const EMPTY_DECLARED_NAMELESS_CLIENT_CALL_TYPES: ReadonlySet<string> = new Set();+const EMPTY_PROVIDER_EXECUTED_CALL_TYPES: ReadonlySet<ProviderExecutedCallType> = new Set();++/** Supported hosted/private declarations that carry no client-executable wire name. */+const NAMELESS_TOOL_SPEC_TYPES = new Set([+ "web_search",+ "web_search_preview",+ "file_search",+ "computer_use_preview",+ "computer_use",+ "code_interpreter",+ "image_generation",+ "image_gen",+ "mcp",+ "tool_search",+ "local_shell",+ "x_search",+]);++/** An upstream-supplied name reaches the error message; keep it bounded. */+const MAX_REPORTED_NAME_CHARS = 100;++export const UNDECLARED_TOOL_CALL_ERROR_CODE = "undeclared_tool_call";++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}++function addWireToolName(+ names: Set<string>,+ tool: unknown,+ namespace?: string,+ ambiguousDottedAliases?: ReadonlySet<string>,+): void {+ if (!isPlainObject(tool)) return;+ const name = wireToolInnerName(tool);+ if (!name) return;+ // Codex routes MCP calls by an explicit `namespace` field, so the same tool is reachable+ // as a bare inner name or as the flattened form; accept both rather than guess which+ // coordinate system this provider echoes back.+ if (!namespace || namespace === BUILTIN_FUNCTIONS_NAMESPACE) {+ names.add(name);+ return;+ }+ names.add(namespacedToolName(namespace, name));+ // Some routed providers echo the flattened wire name with a dot (`ns.name`, observed with+ // muse-spark via opencode-go) instead of `ns__name`. It is the same tool identity, so register+ // the dotted spelling too, mirroring `toolChoiceAliases` (#3402) -- but only while that+ // spelling names exactly one declared tool. Dots are legal inside both a namespace and a+ // name, so two distinct identities can flatten onto one dotted alias; accepting it then would+ // authorize a call the caller never declared under that identity. Ambiguous aliases fall back+ // to the unambiguous `ns__name` form.+ const dotted = dottedToolName(namespace, name);+ if (dottedAliasIsUnambiguous(namespace, name) && !ambiguousDottedAliases?.has(dotted)) {+ names.add(dotted);+ }+ // `exec` is the one name that also switches on nested-helper normalization, so a bare alias+ // for a namespaced MCP tool would silently authorize `exec_command`/`shell_command`/+ // `apply_patch` the request never declared. Every other inner name keeps the bare alias.+ if (name !== CODE_MODE_EXEC_TOOL_NAME) names.add(name);+}++/**+ * Catalog view owned by the current Responses turn.+ *+ * `previous_response_id` expansion prepends stored input items, including historical+ * `additional_tools` declarations. Those items remain conversation history but cannot grant+ * execution authority to this turn. Top-level `tools` always belongs to the current request;+ * only input catalogs at or after the replay boundary are current.+ */+export function currentTurnWireToolCatalogBody(+ body: unknown,+ replayPrefixLength: number | undefined,+): unknown {+ if (!isPlainObject(body) || !Array.isArray(body.input)) return body;+ if (typeof replayPrefixLength !== "number" || !Number.isFinite(replayPrefixLength)) return body;+ const start = Math.min(body.input.length, Math.max(0, Math.trunc(replayPrefixLength)));+ if (start === 0) return body;+ return { ...body, input: body.input.slice(start) };+}++function addWireToolSpecs(+ names: Set<string>,+ specs: unknown,+ ambiguousDottedAliases?: ReadonlySet<string>,+): void {+ if (!Array.isArray(specs)) return;+ for (const spec of specs) {+ if (!isPlainObject(spec)) continue;+ if (spec.type === "namespace" && Array.isArray(spec.tools)) {+ const namespace = typeof spec.name === "string" ? spec.name : undefined;+ for (const inner of spec.tools) addWireToolName(names, inner, namespace, ambiguousDottedAliases);+ continue;+ }+ addWireToolName(names, spec, undefined, ambiguousDottedAliases);+ }+}++/**+ * Tool names the OUTBOUND Responses body actually declared.+ *+ * This reads the body that goes upstream rather than the parsed internal tool list: the+ * passthrough forwards wire shapes (namespaced MCP groups, `additional_tools` items carried+ * inside `input`, routed custom-tool rewrites) that the internal list flattens or renames, and+ * only the wire names can be compared against what the provider echoes back.+ */+export function collectDeclaredWireToolNames(body: unknown): Set<string> {+ const names = new Set<string>();+ if (!isPlainObject(body)) return names;+ const specGroups: unknown[] = [body.tools];+ if (Array.isArray(body.input)) {+ for (const item of body.input) {+ if (+ isPlainObject(item)+ && (item.type === "additional_tools" || item.type === "tool_search_output")+ ) specGroups.push(item.tools);+ }+ }+ const ambiguousDottedAliases = collectAmbiguousDottedAliases(specGroups);+ for (const specs of specGroups) addWireToolSpecs(names, specs, ambiguousDottedAliases);+ return names;+}++function addNamelessClientCallTypes(callTypes: Set<string>, specs: unknown): void {+ if (!Array.isArray(specs)) return;+ for (const spec of specs) {+ if (!isPlainObject(spec) || typeof spec.type !== "string") continue;+ const callType = NAMELESS_CLIENT_DECLARATION_CALL_TYPES.get(spec.type);+ if (callType) callTypes.add(callType);+ }+}++function addProviderExecutedCallTypes(+ callTypes: Set<ProviderExecutedCallType>,+ specs: unknown,+): void {+ if (!Array.isArray(specs)) return;+ for (const spec of specs) {+ if (!isPlainObject(spec) || typeof spec.type !== "string") continue;+ const callType = PROVIDER_EXECUTED_DECLARATION_CALL_TYPES.get(spec.type);+ if (callType) callTypes.add(callType);+ }+}++/**+ * Item types this turn's hosted declarations authorize the PROVIDER to emit unnamed.+ *+ * Caller must gate this on the destination actually being that provider; a declaration alone+ * is not authority, or any upstream could claim a hosted shape it never serves.+ */+export function collectProviderExecutedCallTypes(body: unknown): Set<ProviderExecutedCallType> {+ const callTypes = new Set<ProviderExecutedCallType>();+ if (!isPlainObject(body)) return callTypes;+ addProviderExecutedCallTypes(callTypes, body.tools);+ if (Array.isArray(body.input)) {+ for (const item of body.input) {+ if (+ isPlainObject(item)+ && (item.type === "additional_tools" || item.type === "tool_search_output")+ ) addProviderExecutedCallTypes(callTypes, item.tools);+ }+ }+ return callTypes;+}++function isAuthorizedProviderExecutedCall(+ item: Record<string, unknown>,+ callTypes: ProviderExecutedCallTypes,+): boolean {+ if (typeof item.call_id !== "string") return false;+ for (const callType of callTypes) {+ if (+ item.type === callType.itemType+ && item.call_id.startsWith(callType.callIdPrefix)+ ) return true;+ }+ return false;+}++/** Nameless client-call item types authorized by supported request tool declarations. */+export function collectDeclaredNamelessClientCallTypes(body: unknown): Set<string> {+ const callTypes = new Set<string>();+ if (!isPlainObject(body)) return callTypes;+ addNamelessClientCallTypes(callTypes, body.tools);+ if (Array.isArray(body.input)) {+ for (const item of body.input) {+ if (+ isPlainObject(item)+ && (item.type === "additional_tools" || item.type === "tool_search_output")+ ) {+ addNamelessClientCallTypes(callTypes, item.tools);+ }+ }+ }+ return callTypes;+}++function isReadableWireToolSpec(spec: unknown): boolean {+ if (!isPlainObject(spec) || typeof spec.type !== "string" || spec.type.length === 0) return false;+ if (spec.type === "function") {+ return (typeof spec.name === "string" && spec.name.length > 0)+ || (isPlainObject(spec.function)+ && typeof spec.function.name === "string"+ && spec.function.name.length > 0);+ }+ if (spec.type === "custom") return typeof spec.name === "string" && spec.name.length > 0;+ if (spec.type === "namespace") {+ return typeof spec.name === "string"+ && spec.name.length > 0+ && Array.isArray(spec.tools)+ && (spec.tools.length === 0 || spec.tools.some(inner =>+ isPlainObject(inner)+ && (inner.type === "function" || inner.type === "custom")+ && typeof inner.name === "string"+ && inner.name.length > 0+ ));+ }+ if (NAMELESS_TOOL_SPEC_TYPES.has(spec.type)) return true;+ return typeof spec.name === "string" && spec.name.length > 0;+}++function isReadableWireToolCatalog(value: unknown): boolean {+ return Array.isArray(value)+ && (value.length === 0 || value.some(isReadableWireToolSpec));+}++/** Whether a request contains a supported catalog, including an explicit empty deny-all array. */+export function hasExplicitWireToolCatalog(body: unknown): boolean {+ if (!isPlainObject(body)) return false;+ if (isReadableWireToolCatalog(body.tools)) return true;+ if (!Array.isArray(body.input)) return false;+ return body.input.some(item =>+ isPlainObject(item)+ && item.type === "additional_tools"+ && isReadableWireToolCatalog(item.tools)+ );+}++function undeclaredNameInItem(+ item: unknown,+ declared: ReadonlySet<string>,+ declaredNamelessClientCallTypes: ReadonlySet<string>,+ providerExecutedCallTypes: ProviderExecutedCallTypes = EMPTY_PROVIDER_EXECUTED_CALL_TYPES,+): string | undefined {+ if (!isPlainObject(item)) return undefined;+ if (typeof item.type !== "string") return undefined;+ // The provider executes this exact measured shape itself, so there is no client name to+ // authorize. The caller supplies these signatures only for the matching destination and+ // declarations; the item must additionally carry the hosted call-id prefix.+ if (isAuthorizedProviderExecutedCall(item, providerExecutedCallTypes)) return undefined;+ const namelessDisplayName = NAMELESS_CLIENT_CALL_DISPLAY_NAMES.get(item.type);+ if (namelessDisplayName !== undefined) {+ // Only Codex's explicit `execution: "client"` form delegates tool search to the client.+ if (item.type === "tool_search_call" && item.execution !== "client") return undefined;+ return declaredNamelessClientCallTypes.has(item.type) ? undefined : namelessDisplayName;+ }+ if (!CLIENT_EXECUTED_CALL_TYPES.has(item.type)) return undefined;+ const name = item.name;+ if (typeof name !== "string" || name.length === 0) return undefined;+ if (typeof item.namespace === "string") {+ // Namespaced calls are matched by their full wire name only — never legacy-normalize+ // them, or an undeclared namespaced `exec_command` could slip through as bare `exec`.+ // Both flattened spellings (`ns__name` and the dotted `ns.name` some providers echo,+ // #3402) name the same tool identity.+ if (declared.has(namespacedToolName(item.namespace, name))) return undefined;+ // Only consult the dotted spelling when it cannot double as another identity's canonical+ // name; otherwise a stranger's `ns__name` would authorize this call.+ if (+ dottedAliasIsUnambiguous(item.namespace, name)+ && declared.has(dottedToolName(item.namespace, name))+ ) return undefined;+ return name;+ }+ const effectiveName = normalizeDeclaredToolName(name, declared);+ if (declared.has(effectiveName)) return undefined;+ return name;+}++/** First undeclared client tool named by a Responses SSE payload, or undefined. */+export function undeclaredToolCallName(+ payload: unknown,+ declared: ReadonlySet<string>,+ declaredNamelessClientCallTypes: ReadonlySet<string> = EMPTY_DECLARED_NAMELESS_CLIENT_CALL_TYPES,+ providerExecutedCallTypes: ProviderExecutedCallTypes = EMPTY_PROVIDER_EXECUTED_CALL_TYPES,+): string | undefined {+ if (!isPlainObject(payload)) return undefined;+ if (payload.type === "response.output_item.added" || payload.type === "response.output_item.done") {+ return undeclaredNameInItem(payload.item, declared, declaredNamelessClientCallTypes, providerExecutedCallTypes);+ }+ // Sparse gateways skip incremental items and only ever ship the terminal snapshot.+ if (payload.type === "response.completed" || payload.type === "response.incomplete") {+ return undeclaredToolCallNameInResponse(payload.response, declared, declaredNamelessClientCallTypes, providerExecutedCallTypes);+ }+ return undefined;+}++/** First undeclared client tool in a Responses object's `output` array, or undefined. */+export function undeclaredToolCallNameInResponse(+ response: unknown,+ declared: ReadonlySet<string>,+ declaredNamelessClientCallTypes: ReadonlySet<string> = EMPTY_DECLARED_NAMELESS_CLIENT_CALL_TYPES,+ providerExecutedCallTypes: ProviderExecutedCallTypes = EMPTY_PROVIDER_EXECUTED_CALL_TYPES,+): string | undefined {+ if (!isPlainObject(response) || !Array.isArray(response.output)) return undefined;+ for (const item of response.output) {+ const name = undeclaredNameInItem(item, declared, declaredNamelessClientCallTypes, providerExecutedCallTypes);+ if (name !== undefined) return name;+ }+ return undefined;+}++export function undeclaredToolCallMessage(name: string): string {+ const reported = name.slice(0, MAX_REPORTED_NAME_CHARS);+ return `routed provider emitted undeclared client tool "${reported}"; only request-declared tools may be called`;+}++function failedBlocks(name: string, newline: string): readonly string[] {+ const failure = {+ type: "upstream_error",+ code: UNDECLARED_TOOL_CALL_ERROR_CODE,+ message: undeclaredToolCallMessage(name),+ };+ const payload = JSON.stringify({+ type: "response.failed",+ response: { status: "failed", error: failure, last_error: failure },+ });+ return [`event: response.failed${newline}data: ${payload}`, "data: [DONE]"];+}++/**+ * Fail closed when a routed provider calls a tool the request never declared (#1700).+ *+ * The bridged paths already refuse such a call (`declaredToolNames` in src/bridge.ts), but the+ * native Responses passthrough relayed it verbatim: Codex received a `function_call` for a tool+ * it has no top-level handler for — `apply_patch`, which under code mode exists only as a nested+ * `tools.apply_patch(...)` helper inside `exec` — and the turn surfaced as a bare `aborted` with+ * no output and no explanation. Replacing the offending event with an explicit `response.failed`+ * turns that silent dead end into a compatibility error naming the tool.+ *+ * Everything after the trip is dropped so a later `response.completed` cannot contradict the+ * terminal already sent. Non-JSON and non-item blocks pass through untouched.+ */+export function createUndeclaredToolCallGuardBlockRewrite(+ declared: ReadonlySet<string>,+ declaredNamelessClientCallTypes: ReadonlySet<string> = EMPTY_DECLARED_NAMELESS_CLIENT_CALL_TYPES,+ providerExecutedCallTypes: ProviderExecutedCallTypes = EMPTY_PROVIDER_EXECUTED_CALL_TYPES,+): SseBlockRewrite {+ let tripped = false;+ return (block: string) => {+ if (tripped) return [];+ const payload = sseDataPayload(block);+ if (payload === null || payload === "[DONE]") return [block];+ let parsed: unknown;+ try {+ parsed = JSON.parse(payload);+ } catch {+ return [block];+ }+ const name = undeclaredToolCallName(parsed, declared, declaredNamelessClientCallTypes, providerExecutedCallTypes);+ if (name === undefined) return [block];+ tripped = true;+ return failedBlocks(name, block.includes("\r\n") ? "\r\n" : "\n");+ };+}diff --git a/packages/model-compat/src/upstream/server/responses/responses-field-backfill.ts b/packages/model-compat/src/upstream/server/responses/responses-field-backfill.tsnew file mode 100644index 0000000000..c404a52e59--- /dev/null+++ b/packages/model-compat/src/upstream/server/responses/responses-field-backfill.ts@@ -0,0 +1,343 @@+/**+ * Stateless SSE block rewrite that backfills the `annotations` field on+ * `output_text` content parts in Responses SSE events.+ *+ * The Responses API spec defines `annotations` as a required field on+ * `OutputTextContent` (it is `Vec<Annotation>`, not `Option<Vec>`). Some+ * upstream relays omit it when there are no annotations, which is technically+ * spec-non-compliant. Strict deserializers — any client that follows the+ * schema without `#[serde(default)]` on that field — fail with+ * `missing field `annotations`` when the field is absent.+ *+ * This rewrite scans every SSE event for output_text content parts — whether+ * they appear in item.content[], part, or response.output[].content[] — and+ * adds annotations: [] if missing.+ *+ * Stateless: no retained buffers, no lifecycle tracking, no fail-closed.+ * Existing values are always authoritative; only absent fields are added.+ * The field is always valid on the wire, so adding it when absent is safe+ * for all clients including Codex CLI/App.+ */++import {+ replaceSseDataPayload,+ sseDataPayload,+ type SseBlockRewrite,+} from "../sse-payload-rewrite";+import { isCompactionItemType } from "../../responses/compaction";++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}++/** Wire prefixes for Responses output item ids, matching OpenAI's id shapes. */+const ITEM_ID_PREFIXES: Readonly<Record<string, string>> = {+ message: "msg_",+ reasoning: "rs_",+ function_call: "fc_",+ custom_tool_call: "ctc_",+ // A routed tool_search lowering is restored to `tool_search_call` without an id, so this+ // backfill is what names it. The generic `item_` fallback is not merely cosmetic here:+ // `stripInvalidItemIds` in the Responses adapter deletes any id whose prefix does not match+ // the type, so an `item_`-named tool_search_call silently loses its id on the NEXT turn and+ // the client sees an item it cannot correlate. The prefixes here must stay a superset of the+ // ones that serializer enforces.+ tool_search_call: "tsc_",+ web_search_call: "ws_",+ file_search_call: "fs_",+ code_interpreter_call: "ci_",+ computer_call: "cc_",+ // The Responses wire type is `image_generation_call`; `image_gen_call` is kept only so a+ // relay that emits the short spelling is not silently demoted to the generic `item_`.+ image_generation_call: "ig_",+ image_gen_call: "ig_",+};++/**+ * Backfill a required id on an output item when absent. Strict Responses+ * decoders (e.g. grok-build serde types) fail with "missing field id" when a+ * message or reasoning item has no id, which some upstream relays omit. The+ * generated id is deterministic per (type, output index) so it stays stable+ * across streaming events that reference the same item.+ */+function backfillItemId(item: Record<string, unknown>, slot: ItemIdSlot): Record<string, unknown> {+ if (typeof item.id === "string" && item.id.length > 0) return item;+ const type = typeof item.type === "string" ? item.type : "";+ const prefix = Object.prototype.hasOwnProperty.call(ITEM_ID_PREFIXES, type) ? ITEM_ID_PREFIXES[type] : "item_";+ return { ...item, id: prefix + "ocx_" + (slot.kind === "index" ? String(slot.index) : "fallback_" + slot.ordinal) };+}++/**+ * Which namespace a synthesized id comes from.+ *+ * Keeping the fallback counter in the SAME numeric namespace as real output indexes only+ * pushed the collision out of reach rather than removing it: a response whose real index+ * happened to be 1_000_001 would produce the same id as the first malformed-index fallback,+ * and a duplicate id is exactly what this backfill exists to prevent. The namespaces are now+ * lexically disjoint, so no index value can ever collide with a fallback.+ */+type ItemIdSlot = { kind: "index"; index: number } | { kind: "fallback"; ordinal: number };++/**+ * Monotonic ordinal for an event whose `output_index` is absent or malformed.+ *+ * Process-global rather than per-response because this module is stateless by design and the+ * value only has to be unique, not meaningful. It carries its own `fallback_` namespace, so+ * uniqueness no longer depends on a real index never reaching some arbitrary ceiling.+ */+let syntheticItemOrdinal = 0;+function nextSyntheticItemSlot(): ItemIdSlot {+ syntheticItemOrdinal += 1;+ return { kind: "fallback", ordinal: syntheticItemOrdinal };+}++/**+ * Backfill `status` on a message output item if missing.+ *+ * The Responses API spec defines `status` as a required field on+ * `OutputMessage`. Some upstream relays omit it, which causes strict+ * deserializers (e.g. grok-build's serde types) to fail with+ * `missing field 'status'`. Only message items carry this field in the+ * Responses schema; reasoning, function_call, and other item types do not.+ *+ * The value is inferred from the event context: `output_item.added` and+ * `response.created` / `response.in_progress` mean the message is still+ * being generated (`in_progress`); `output_item.done` and+ * `response.completed` / `response.incomplete` mean the message is+ * finalized (`completed` / `incomplete` respectively).+ *+ * Returns the same object reference if no change is needed.+ */+function backfillItemStatus(item: Record<string, unknown>, inferredStatus: string): Record<string, unknown> {+ if (item.type !== "message") return item;+ if ("status" in item) return item;+ return { ...item, status: inferredStatus };+}++/**+ * Backfill annotations: [] on an output_text content part if missing.+ * Returns the same object reference if no change is needed.+ */+function backfillOutputTextPart(part: Record<string, unknown>): Record<string, unknown> {+ if (part.type !== "output_text") return part;+ // Only add annotations when the key is entirely absent — preserve any+ // existing value (even null or a malformed type) so we never overwrite+ // what the upstream actually sent.+ if ("annotations" in part) return part;+ return { ...part, annotations: [] };+}++/**+ * Walk a content array and backfill output_text parts.+ * Returns the same array reference if nothing changed.+ */+function backfillContentArray(content: unknown): unknown {+ if (!Array.isArray(content)) return content;+ let changed = false;+ const repaired = content.map((part) => {+ if (!isPlainObject(part)) return part;+ const next = backfillOutputTextPart(part);+ if (next !== part) changed = true;+ return next;+ });+ return changed ? repaired : content;+}++/**+ * Walk an output item and backfill output_text parts in its content.+ * Also backfills a missing required id and status on the item itself.+ * Returns the same object reference if nothing changed.+ */+function backfillOutputItem(item: unknown, slot: ItemIdSlot, inferredStatus: string): unknown {+ if (!isPlainObject(item)) return item;+ // The compact wire family is the `/v1/responses/compact` format, not a Responses output item.+ // Those items have no `id` in that contract, so synthesizing one changes a response body the+ // client compares exactly — and the client replays the item on every later turn, where the+ // minting backend rejects it as modified. The backfill exists to satisfy strict Responses+ // decoders; a shape those decoders never see is outside its remit.+ if (isCompactionItemType(item.type)) return item;+ const content = item.content;+ const repaired = backfillContentArray(content);+ const withId = backfillItemId(item, slot);+ const withStatus = backfillItemStatus(withId, inferredStatus);+ if (repaired === content && withStatus === item) return item;+ return { ...withStatus, ...(repaired === content ? {} : { content: repaired }) };+}++/**+ * Walk a response object's output[] and backfill output_text parts.+ *+ * `inferredItemStatus` is the status to backfill on message items that lack+ * one — derived from the event type so `output_item.added` / `response.created`+ * gets `in_progress` while `output_item.done` / `response.completed` gets+ * `completed`.+ *+ * Deliberately does NOT backfill `created_at`. #2639 proposed it for the same+ * strict-decoder reason as `status`, but the proxy also relays some upstream+ * responses verbatim, and `tests/server/server-combo-failover-e2e.test.ts` asserts a+ * combo backup response is returned byte-exact. Injecting a field the upstream+ * never sent breaks that contract. Both cannot hold for the same body, so the+ * `created_at` half needs its own decision about which contract yields; it is+ * not a detail to slip in beside `status`.+ *+ * Returns the same object reference if nothing changed.+ */+function backfillResponseOutput(response: unknown, inferredItemStatus: string): unknown {+ if (!isPlainObject(response)) return response;+ const output = response.output;+ if (!Array.isArray(output)) return response;+ let changed = false;+ const repaired = output.map((item, idx) => {+ if (!isPlainObject(item)) return item;+ const next = backfillOutputItem(item, { kind: "index", index: idx }, inferredItemStatus);+ if (next !== item) changed = true;+ return next;+ });+ return changed ? { ...response, output: repaired } : response;+}++/**+ * Infer the status to backfill on a message item from the event type.+ *+ * `output_item.added` means the item is still being generated (`in_progress`);+ * `output_item.done` means it is finalized (`completed`). Response-level events+ * infer from the response's own status field — which is authoritative when present.+ * If the response status is also absent, the event type itself determines the phase:+ * `response.created` / `response.in_progress` → `in_progress`,+ * `response.completed` → `completed`, `response.incomplete` → `incomplete`.+ */+function inferredStatusForEventType(eventType: string): string {+ if (eventType === "response.output_item.added") return "in_progress";+ if (eventType === "response.output_item.done") return "completed";+ if (eventType === "response.created" || eventType === "response.in_progress") return "in_progress";+ // `queued` is a real Responses lifecycle status: the response exists but has not+ // started generating. Without this row it falls through to the `completed`+ // default below, which would mark an unstarted message as finished.+ if (eventType === "response.queued") return "in_progress";+ if (eventType === "response.incomplete" || eventType === "response.failed") return "incomplete";+ return "completed";+}++/**+ * Map a response-level lifecycle status to a valid OutputMessage status.+ *+ * `OutputMessage.status` accepts only `in_progress`, `completed`, or+ * `incomplete`. Response-level statuses like `failed` or `cancelled` have no+ * direct message-level equivalent, but `incomplete` is the correct semantic+ * mapping: the message did not finish generating. Writing `completed` would+ * assert something the upstream never claimed — a client branching on+ * `status === "completed"` would treat a truncated message as whole.+ */+function messageStatusFromResponseStatus(status: string): string | null {+ if (status === "in_progress" || status === "completed" || status === "incomplete") return status;+ // A queued response has not begun generating, so its message items are+ // in_progress — never completed. Returning null here would fall back to the+ // event-type inference, whose default is `completed`.+ if (status === "queued") return "in_progress";+ if (status === "failed" || status === "cancelled") return "incomplete";+ return null;+}++/**+ * Statelessly rewrite one SSE event: backfill annotations+ * on any output_text content part found in the event payload.+ */+function rewriteEvent(event: Record<string, unknown>): Record<string, unknown> {+ const type = typeof event.type === "string" ? event.type : "";+ const inferredItemStatus = inferredStatusForEventType(type);+ let next = event;+ let changed = false;++ // output_item.added / output_item.done: item.content[] -> output_text parts+ if ((type === "response.output_item.added" || type === "response.output_item.done")+ && isPlainObject(event.item)) {+ const rawIndex = event.output_index;+ // A malformed or absent `output_index` must not collapse to 0: two such events would then+ // both synthesize `msg_ocx_0`, and duplicate ids are the very thing this backfill exists to+ // prevent. Fall back to a per-process counter so the synthesized id stays unique. Position+ // is not recoverable in that case, but a unique id is what strict decoders require, and a+ // well-formed stream still gets the stable index-derived id.+ const item = typeof rawIndex === "number" && Number.isInteger(rawIndex) && rawIndex >= 0+ ? backfillOutputItem(event.item, { kind: "index", index: rawIndex }, inferredItemStatus)+ : backfillOutputItem(event.item, nextSyntheticItemSlot(), inferredItemStatus);+ if (item !== event.item) {+ next = { ...next, item };+ changed = true;+ }+ }++ // content_part.added / content_part.done: part -> output_text+ if ((type === "response.content_part.added" || type === "response.content_part.done")+ && isPlainObject(event.part)) {+ const part = backfillOutputTextPart(event.part);+ if (part !== event.part) {+ next = { ...next, part };+ changed = true;+ }+ }++ // response.created / in_progress / completed / incomplete / failed:+ // response.output[].content[] -> output_text parts+ if (isPlainObject(event.response)) {+ // For response-level events, prefer the response's own status when it is a valid+ // OutputMessage status. Response lifecycle statuses like "failed" or "cancelled"+ // have no message-level equivalent — fall back to the event-type inference instead.+ const responseStatus = typeof event.response.status === "string"+ ? messageStatusFromResponseStatus(event.response.status) ?? inferredItemStatus+ : inferredItemStatus;+ const response = backfillResponseOutput(event.response, responseStatus);+ if (response !== event.response) {+ next = { ...next, response };+ changed = true;+ }+ }++ return changed ? next : event;+}++/**+ * Create a stateless SSE block rewrite that backfills annotations and+ * message status on output_text content parts and message items.+ * Unconditional: both are required canonical Responses fields, so adding+ * them when absent is safe for all clients.+ */+export function createResponsesFieldBackfillBlockRewrite(): SseBlockRewrite {+ const rewrite: SseBlockRewrite = (block: string): readonly string[] => {+ const payload = sseDataPayload(block);+ if (payload === null) return [block];+ let event: unknown;+ try {+ event = JSON.parse(payload);+ } catch {+ return [block];+ }+ if (!isPlainObject(event)) return [block];+ const rewritten = rewriteEvent(event);+ if (rewritten === event) return [block];+ return [replaceSseDataPayload(block, JSON.stringify(rewritten))];+ };+ return rewrite;+}++/**+ * Backfill annotations on a non-streaming Responses JSON+ * object. Mirrors the SSE block rewrite for the bounded-JSON passthrough+ * path. Returns the original string if no change is needed.+ */+export function backfillResponsesFieldsJson(payload: string): string {+ let response: unknown;+ try {+ response = JSON.parse(payload);+ } catch {+ return payload;+ }+ if (!isPlainObject(response)) return payload;+ // For a non-streaming response, derive the item status from the response's own+ // status field when it is a valid OutputMessage status; fall back to "completed".+ const inferredItemStatus = typeof response.status === "string"+ ? messageStatusFromResponseStatus(response.status) ?? "completed"+ : "completed";+ const repaired = backfillResponseOutput(response, inferredItemStatus);+ if (repaired === response) return payload;+ return JSON.stringify(repaired);+}diff --git a/packages/model-compat/src/upstream/server/sse-payload-rewrite.ts b/packages/model-compat/src/upstream/server/sse-payload-rewrite.tsnew file mode 100644index 0000000000..f9fb62065d--- /dev/null+++ b/packages/model-compat/src/upstream/server/sse-payload-rewrite.ts@@ -0,0 +1,265 @@+import type { TranslatorBudget } from "../lib/translator-budget";++/**+ * Shared client-facing SSE payload rewrite shell.+ *+ * Multiple opt-in transforms (image-gen namespace restore, item-id repair, …) compose into one+ * parse/stringify pass so a tee'd stream is not re-framed twice per event.+ */++export type SsePayloadRewrite = (payload: string) => string;++/**+ * Block-level SSE rewrite: maps one complete SSE event block (without its+ * blank-line delimiter) to zero or more replacement blocks. This is the+ * contract lifecycle repair needs: injecting missing canonical events+ * (#893) is impossible in the one-payload-in/one-payload-out model.+ *+ * `dispose` releases any retained state (budget-charged collectors) when the+ * relay tears down — terminal, EOF, cancel, or error. Relays call it exactly+ * once per teardown path.+ */+export type SseBlockRewrite = ((block: string) => readonly string[]) & {+ dispose?: () => void;+};++/** Adapt a payload rewrite to the block contract (replace only on change). */+export function payloadRewriteAsBlockRewrite(rewrite: SsePayloadRewrite): SseBlockRewrite {+ return (block) => {+ const payload = sseDataPayload(block);+ if (payload === null) return [block];+ const rewritten = rewrite(payload);+ return rewritten !== payload ? [replaceSseDataPayload(block, rewritten)] : [block];+ };+}++/** Chain block rewrites: every block stage N emits feeds stage N+1. */+export function composeSseBlockRewrites(...rewrites: SseBlockRewrite[]): SseBlockRewrite {+ const active = rewrites.filter(Boolean);+ if (active.length === 0) return Object.assign((block: string) => [block], {});+ const composed: SseBlockRewrite = (block: string) => {+ let blocks: readonly string[] = [block];+ for (const rewrite of active) {+ const next: string[] = [];+ for (const current of blocks) next.push(...rewrite(current));+ blocks = next;+ }+ return blocks;+ };+ // Child disposal is part of the contract: one idempotent disposer for the+ // whole chain, so relay teardown never leaks a nested collector.+ let disposed = false;+ composed.dispose = () => {+ if (disposed) return;+ disposed = true;+ for (const rewrite of active) {+ try { rewrite.dispose?.(); } catch { /* teardown must not throw */ }+ }+ };+ return composed;+}++/** Split one complete SSE event block while retaining its original blank-line delimiter. */+export function nextSseBlock(buffer: string): { block: string; delimiter: string; rest: string } | null {+ const match = buffer.match(/\r?\n\r?\n/);+ if (!match || match.index === undefined) return null;+ return {+ block: buffer.slice(0, match.index),+ delimiter: match[0],+ rest: buffer.slice(match.index + match[0].length),+ };+}++/** Join all data lines from one SSE event according to the event-stream field rules. */+export function sseDataPayload(block: string): string | null {+ const data: string[] = [];+ for (const line of block.split(/\r?\n/)) {+ if (!line.startsWith("data:")) continue;+ const value = line.slice(5);+ data.push(value.startsWith(" ") ? value.slice(1) : value);+ }+ return data.length > 0 ? data.join("\n") : null;+}++/** Replace an SSE event's data field while preserving non-data fields and newline style. */+export function replaceSseDataPayload(block: string, payload: string): string {+ const newline = block.includes("\r\n") ? "\r\n" : "\n";+ const lines = block.split(/\r?\n/);+ const rewritten: string[] = [];+ let replaced = false;+ for (const line of lines) {+ if (!line.startsWith("data:")) {+ rewritten.push(line);+ continue;+ }+ if (!replaced) {+ rewritten.push(`data: ${payload}`);+ replaced = true;+ }+ }+ return replaced ? rewritten.join(newline) : block;+}++/** Apply rewrites left-to-right; empty list is identity. */+export function composeSsePayloadRewrites(...rewrites: SsePayloadRewrite[]): SsePayloadRewrite {+ if (rewrites.length === 0) return (payload) => payload;+ if (rewrites.length === 1) return rewrites[0]!;+ return (payload) => {+ let next = payload;+ for (const rewrite of rewrites) next = rewrite(next);+ return next;+ };+}++/**+ * Relay an SSE body through a single JS pull wrapper, rewriting each event's data payload in place.+ * Non-data fields and framing are preserved; invalid JSON payloads are left to the rewrite callback.+ */+export function relaySseWithPayloadRewrite(+ body: ReadableStream<Uint8Array>,+ rewrite: SsePayloadRewrite,+ translatorBudget: TranslatorBudget,+): ReadableStream<Uint8Array> {+ return relaySseWithBlockRewrite(body, payloadRewriteAsBlockRewrite(rewrite), translatorBudget);+}++/**+ * Relay an SSE body through a single JS pull wrapper, applying a block-level+ * rewrite that may emit zero or more blocks per upstream event (lifecycle+ * event injection, #893). The original stream's delimiter style is preserved+ * for every emitted block.+ */+export function relaySseWithBlockRewrite(+ body: ReadableStream<Uint8Array>,+ rewrite: SseBlockRewrite,+ translatorBudget: TranslatorBudget,+): ReadableStream<Uint8Array> {+ const reader = body.getReader();+ const decoder = new TextDecoder();+ const encoder = new TextEncoder();+ let buffer = "";+ let bufferBytes = 0;+ // Relays have several independent teardown paths; disposal is exactly once.+ let disposed = false;+ let cancelled = false;+ const disposeRewrite = (): void => {+ if (disposed) return;+ disposed = true;+ try { rewrite.dispose?.(); } catch { /* teardown must not throw */ }+ };++ const appendBuffer = (fragment: string): void => {+ if (!fragment) return;+ const nextBytes = bufferBytes + encoder.encode(fragment).byteLength;+ const reservation = translatorBudget.reserveTransient(nextBytes, { kind: "live_transient" });+ try {+ buffer += fragment;+ reservation.commitRetained();+ translatorBudget.releaseRetained(bufferBytes, { kind: "live_transient" });+ bufferBytes = nextBytes;+ } catch (error) {+ reservation.release();+ throw error;+ }+ };++ const replaceBuffer = (next: string): void => {+ const nextBytes = encoder.encode(next).byteLength;+ const reservation = translatorBudget.reserveTransient(nextBytes, { kind: "live_transient" });+ reservation.commitRetained();+ buffer = next;+ translatorBudget.releaseRetained(bufferBytes, { kind: "live_transient" });+ bufferBytes = nextBytes;+ };++ const enqueueText = (+ controller: ReadableStreamDefaultController<Uint8Array>,+ text: string,+ ): void => {+ const bytes = encoder.encode(text).byteLength;+ const reservation = translatorBudget.reserveTransient(bytes, { kind: "live_transient" });+ try {+ const encoded = encoder.encode(text);+ reservation.commitRetained();+ controller.enqueue(encoded);+ translatorBudget.releaseRetained(bytes, { kind: "live_transient" });+ } catch (error) {+ reservation.release();+ throw error;+ }+ };++ const releaseBuffer = (): void => {+ translatorBudget.releaseRetained(bufferBytes, { kind: "live_transient" });+ buffer = "";+ bufferBytes = 0;+ };++ const emitProcessedBlocks = (+ controller: ReadableStreamDefaultController<Uint8Array>,+ flushFinal = false,+ ): number => {+ let emitted = 0;+ let next: { block: string; delimiter: string; rest: string } | null;+ while ((next = nextSseBlock(buffer))) {+ replaceBuffer(next.rest);+ for (const outBlock of rewrite(next.block)) {+ enqueueText(controller, outBlock + next.delimiter);+ emitted += 1;+ }+ }+ if (flushFinal && buffer.length > 0) {+ const tailBlocks = rewrite(buffer);+ // A trailing fragment has no delimiter of its own; multiple emitted+ // blocks must still be framed as separate events (#893 review).+ const tailDelimiter = buffer.includes("\r\n") ? "\r\n\r\n" : "\n\n";+ for (let i = 0; i < tailBlocks.length; i++) {+ enqueueText(controller, tailBlocks[i]! + (i < tailBlocks.length - 1 ? tailDelimiter : ""));+ emitted += 1;+ }+ releaseBuffer();+ }+ return emitted;+ };++ return new ReadableStream<Uint8Array>({+ async pull(controller) {+ try {+ // A network chunk is not an SSE-event boundary. Bun may not issue a+ // second pull after a fulfilled pull enqueues nothing, so keep reading+ // until at least one complete rewritten block is available or EOF is+ // reached. This also handles block rewrites that intentionally drop an+ // event without parking the client stream.+ for (;;) {+ const { done, value } = await reader.read();+ // A cancel raced this pending read: never feed the rewriter again+ // after its disposal (#893 review).+ if (cancelled) return;+ if (done) {+ appendBuffer(decoder.decode());+ emitProcessedBlocks(controller, true);+ releaseBuffer();+ disposeRewrite();+ controller.close();+ return;+ }+ appendBuffer(decoder.decode(value, { stream: true }));+ if (emitProcessedBlocks(controller) > 0) return;+ }+ } catch (error) {+ releaseBuffer();+ disposeRewrite();+ // Cancelling one tee branch waits for its sibling. Surface the failure+ // now so downstream can abort upstream and release the inspection branch.+ void reader.cancel(error).catch(() => {});+ controller.error(error);+ }+ },+ cancel(reason) {+ cancelled = true;+ releaseBuffer();+ disposeRewrite();+ reader.cancel(reason).catch(() => {});+ },+ });+}diff --git a/packages/model-compat/src/upstream/types.ts b/packages/model-compat/src/upstream/types.tsnew file mode 100644index 0000000000..09e35e15b5--- /dev/null+++ b/packages/model-compat/src/upstream/types.ts@@ -0,0 +1,2 @@+export * from "./types/tools";+export type * from "./types/provider";diff --git a/packages/model-compat/src/upstream/types/provider.ts b/packages/model-compat/src/upstream/types/provider.tsnew file mode 100644index 0000000000..0beb5d3371--- /dev/null+++ b/packages/model-compat/src/upstream/types/provider.ts@@ -0,0 +1,821 @@+import type { UpstreamHttpVersion, ReasoningSummaryDelivery, CodexAccountMode } from "./wire";++/**+ * Per-provider proactive-refresh policy. The guardian only ever touches a provider whose EFFECTIVE+ * policy is "proactive"; "lazy-only" keeps today's on-demand refresh, "disabled" forbids the+ * guardian entirely (used for providers whose ToS actively enforces against non-official-client+ * token traffic, e.g. Anthropic subscription OAuth). See devlog 260703_oauth-multi-account-refresh-and-tos.+ */+export type RefreshPolicy = "proactive" | "lazy-only" | "disabled";++/** Request-owned identity of the configured key, before env/keychain resolution. */+export interface ProviderApiKeySelection {+ entryId?: string;+ reference?: string;+ revision?: string;+}++export interface OpenRouterProviderRouting {+ /** OpenRouter provider slugs to try first, in priority order. */+ order?: string[];+ /** Restrict routing to these OpenRouter provider slugs. */+ only?: string[];+ /** Whether OpenRouter may use providers outside `order`. Defaults to OpenRouter's policy. */+ allowFallbacks?: boolean;+}++export interface VercelGatewayRouting {+ /** Vercel AI Gateway provider slugs to try first, in priority order. */+ order?: string[];+ /** Restrict routing to these Vercel AI Gateway provider slugs. */+ only?: string[];+ /** Sort providers by "cost", "ttft", or "tps". */+ sort?: "cost" | "ttft" | "tps";+}++export interface ResponsesItemIdRepairConfig {+ /** Exact `message` item ids that the proxy should rewrite to request-local canonical ids. */+ message?: string[];+ /** Exact `reasoning` item ids that the proxy should rewrite to request-local canonical ids. */+ reasoning?: string[];+ /** Backfill missing `output_item.done` / terminal snapshot ids from the matching output_index. */+ repairMissingTerminalIds?: boolean;+ /**+ * Treat existing message/reasoning ids without the canonical `msg_`/`rs_` prefix (e.g. bare+ * UUIDs from DeepSeek's Responses route) as invalid and mint canonical replacements (#938).+ * function_call ids and call_id pairing are never rewritten.+ */+ repairInvalidIds?: boolean;+}++/**+ * Opt-in retry for pre-stream transient upstream statuses (500/502/503/504/520/521/522) on+ * `providers.<name>.transientRetryOn5xx`.+ *+ * Disabled unless the object is present; a bare `{}` opts in with defaults. Separate from+ * `retryOn429`, which handles rate limiting with its own waits.+ */+export interface TransientRetryPolicy {+ /** Master switch. Presence of the object also enables the policy (default true). */+ enabled?: boolean;+ /**+ * TOTAL upstream sends allowed for one request, including the first (1..10, default 3).+ *+ * Not a per-layer retry count: the connection-reset and transient-status recovery layers+ * share this single budget, so `3` means at most three real requests reach the provider.+ */+ attempts?: number;+}++/**+ * Same-target 429 wait-and-retry policy (`providers.<name>.retryOn429`). When present and not+ * explicitly disabled, the proxy waits and replays the identical request on the same key before+ * any key failover. All fields optional; the runtime applies defaults (attempts=3,+ * intervalMs=5000, maxIntervalMs=60000, respectRetryAfter=true, enabled=true).+ */+export interface RateLimitRetryPolicy {+ /** Master switch. The presence of the object also enables the policy (default true). */+ enabled?: boolean;+ /** Extra replay attempts after the first 429 (1..20, default 3). */+ attempts?: number;+ /** Fixed wait between attempts when the upstream sends no usable Retry-After (default 5000). */+ intervalMs?: number;+ /** Cap for any single wait, including an upstream Retry-After (default 60000). */+ maxIntervalMs?: number;+ /** Prefer the upstream Retry-After header when present and parseable (default true). */+ respectRetryAfter?: boolean;+}++/**+ * Backend ids admitted by `providers.<name>.webSearchBridge.backend`. Only `"ollama"` has a+ * shipped executor; every other id is explicit-only and inert, the same contract the top-level+ * `webSearchSidecar` uses for backends whose executor has not landed. Naming one of them keeps+ * the bridge disarmed rather than silently falling back to a different search provider — in+ * particular it never auto-selects a paid Luna or Exa search.+ */+export const PROVIDER_WEB_SEARCH_BRIDGE_BACKENDS = [+ "ollama",+ "openai",+ "anthropic",+ "xai",+ "gemini",+ "exa",+] as const;++export type ProviderWebSearchBridgeBackend = typeof PROVIDER_WEB_SEARCH_BRIDGE_BACKENDS[number];++/**+ * Opt-in hosted-web-search bridge for a KEY-auth Responses passthrough provider+ * (`providers.<name>.webSearchBridge`), default OFF (#3761).+ *+ * Codex always declares the hosted `{type:"web_search"}` tool. On the passthrough the proxy+ * treats that as "the destination runs search itself" and relays it unchanged, which is true for+ * the ChatGPT backend and for xAI but false for an OpenAI-shaped key gateway such as Ollama+ * Cloud: the model answers with a `function_call` named `web_search` that nothing executes,+ * and the undeclared-tool guard ends the turn. With this block enabled the proxy intercepts that+ * call, runs the configured search backend itself, feeds the result back upstream, and shows+ * Codex a hosted `web_search_call` cell.+ *+ * Never armed for `authMode: "forward"` (ChatGPT) or for a provider that executes hosted search+ * upstream; see `planPassthroughWebSearchBridge` in `src/web-search/passthrough-bridge.ts`.+ */+export interface ProviderWebSearchBridgeConfig {+ /** Master switch. Absent or false keeps today's relay-and-fail behavior exactly. */+ enabled?: boolean;+ /** Which executor runs the search. Absent disarms the bridge; there is no implicit default. */+ backend?: ProviderWebSearchBridgeBackend;+ /** Searches executed per turn before the bridge refuses further ones (1..10, default 3). */+ maxSearches?: number;+ /** Per-search deadline in milliseconds (1000..600000, default 60000). */+ timeoutMs?: number;+ /**+ * Absolute search-API URL. Required to use the `ollama` backend against anything other than+ * the canonical `https://ollama.com` origin, which is the only origin derived automatically.+ * The bridge sends the PROVIDER's own API key to this URL, so an operator setting it is+ * authorizing that key for this destination.+ */+ endpoint?: string;+}++/**+ * User-configured display price for one model (USD per 1M tokens).+ * Mirrors the `Cost4` shape used by the usage cost estimator; structurally+ * compatible so config rows can be lifted directly into price overlays.+ */+export interface ProviderCostOverlay {+ input: number;+ output: number;+ cacheRead: number;+ cacheWrite: number;+}++export interface RequestPacingRule {+ /** Evenly spread request starts to this many requests per minute. */+ requestsPerMinute?: number;+ /** Minimum delay between request starts. The slower configured value wins. */+ minIntervalMs?: number;+}++export interface ProviderRequestPacingConfig extends RequestPacingRule {+ /** False preserves legacy behavior with no client-side waiting. */+ enabled: boolean;+ /** Exact upstream model-id overrides; other models inherit the provider rule. */+ models?: Record<string, RequestPacingRule>;+}++export interface FastWire {+ /**+ * How the provider expresses Fast on the wire. `service-tier` is OpenAI's+ * `service_tier` request field; `cursor-variant` is a MODEL-VARIANT switch, because+ * Cursor has no tier field — its fast product is a different model id+ * (`claude-opus-5-thinking-high-fast`) or a `{id:"fast"}` request parameter for Grok.+ */+ kind: "service-tier" | "anthropic-speed" | "cursor-variant";+ /** Canonical tier name to upstream wire spelling. */+ canonicalToWire: Readonly<Record<string, string>>;+ /** Policy for non-canonical caller-provided tier values. */+ foreignCallerTiers: "verbatim" | "drop";+ /** Anthropic speed headers/betas reserved for the later wire implementation. */+ betas?: readonly string[];+}++/** Durable per-attempt service-tier fact produced at the adapter serialization boundary. */+export interface AttemptTierOutcome {+ canonical?: "priority";+ wireKind?: FastWire["kind"] | null;+ wireValue?: string | null;+ fastOutcome: "not-requested" | "applied" | "downgraded" | "unknown";+ fastDowngradeReason?: "route-unsupported" | "wire-unavailable" | "response-declined";+ callerTierDropped?: boolean;+ callerFastSuppressedByConfig?: boolean;+ confirmation: "confirmed" | "assumed" | "downgraded" | "unknown";+ responseServiceTier?: string;+}++/**+ * Request-local observation inputs captured before the final tier action mutates the parsed view.+ * This is not persisted; the final adapter turns it into AttemptTierOutcome after serialization.+ */+export interface TierObservationContext {+ capability: boolean | undefined;+ eligibility:+ | "eligible"+ | "capability-unsupported"+ | "unclassified"+ | "wire-unavailable"+ | "pin-unavailable";+ fastWire: FastWire | null;+ demandDecision: "force-fast" | "force-default" | "inherit";+ callerTier?: string;+ /**+ * Whether the destination's echoed `service_tier` is authoritative about Fast scheduling.+ *+ * The ChatGPT-internal Codex backend returns `service_tier: "default"` on turns that were in+ * fact scheduled as priority, so treating its echo as a downgrade produced a false+ * `response-declined` on every Fast request (#2558). Absent means "assume authoritative",+ * preserving the behaviour for the public API where the echo does mean what it says.+ */+ responseTierAuthoritative?: boolean;+}++export type TierDecision =+ | { readonly kind: "forward-caller" }+ | { readonly kind: "drop" }+ | { readonly kind: "set"; readonly value: string };++/**+ * One configured provider entry. `authMode` (default `"key"`) decides whether same-target 429+ * retries are allowed; OAuth/forward credentials and local runtimes are never replayed.+ */+export interface OcxProviderConfig {+ /** Optional short provider namespace used only at request/catalog presentation time. */+ alias?: string;+ /** Native model id -> short, slash-free request alias. */+ modelAliases?: Record<string, string>;+ /** Display-only labels for exact native model ids discovered under this provider. */+ modelDisplayNames?: Record<string, string>;+ /** Override the global built-in model-alias switch for this provider. */+ defaultAliases?: boolean;+ adapter: string;+ /**+ * Codex tool calling mode for routed models.+ * "code_mode_only" (default) sets entry.tool_mode = "code_mode_only" (unified exec helper tool).+ * "shell" leaves tool_mode unset so Codex declares top-level shell tools (exec_command).+ */+ codexToolMode?: "code_mode_only" | "shell";+ /** Optional outbound request-start pacing shared by this provider and its model overrides. */+ requestPacing?: ProviderRequestPacingConfig;+ /** Cursor MCP compatibility bounds; positive integers when configured. */+ mcpMaxTools?: number;+ mcpMaxSchemaBytes?: number;+ mcpMaxResultBytes?: number;+ /**+ * Per-model wire override, keyed by the upstream native model id (after namespace+ * and combo resolution). A single gateway can front models that speak different+ * wires — Grok needs the Responses API for hosted web_search while a sibling model+ * is fine on chat completions (#404).+ *+ * Only OpenAI-shaped wires may be selected; see MODEL_ADAPTER_OVERRIDE_ALLOWED.+ * Absent or empty means the provider-wide `adapter` applies to everything, exactly+ * as before.+ */+ modelAdapters?: Record<string, string>;+ /**+ * Fast-wire declaration. `null` explicitly disables adapter-derived defaults;+ * absence derives from the final model adapter.+ */+ fastWire?: FastWire | null;+ baseUrl: string;+ /**+ * Optional relative resource path for key-auth openai-responses requests. Must start with `/`+ * and must not include a URL scheme, query string, or fragment. When omitted, the adapter keeps+ * the legacy `/v1/responses` construction.+ */+ responsesPath?: string;+ /**+ * Command Code protocol version sent as `x-command-code-version` on /alpha/generate requests.+ * The internal endpoint's schema drifts with the CLI version; operators can pin a known-good+ * version here instead of waiting for a code change. Absent uses the adapter's current default.+ */+ commandCodeVersion?: string;+ /**+ * Responses upstream that stores nothing server-side (DeepSeek documents "the API+ * is stateless"). Stateful request parameters are dropped, `store` is pinned false,+ * and orphaned tool results left by a replay miss are repaired rather than+ * forwarded to an upstream that cannot resolve their pair.+ */+ statelessResponses?: boolean;+ /**+ * Responses upstream whose parser requires an unambiguous call batch and its matched+ * result batch to remain contiguous. Hook-injected context that splits the batch is+ * preserved after it, and parallel calls stay together with the reasoning turn that produced them.+ */+ requiresAdjacentResponsesToolResults?: boolean;+ /**+ * When enabled, a tool result that is present but empty (no usable text or content+ * part) is rewritten to an explicit annotation before it reaches the upstream wire,+ * so models do not silently accept an empty result or re-issue the same call.+ * Non-empty results and missing-result placeholders stay byte-identical.+ * Seeded true for DeepSeek; absent keeps legacy behavior for every other provider.+ * Only the OpenAI-family adapters (openai-chat / openai-responses) read this option;+ * other adapters ignore it.+ */+ annotateEmptyToolOutputs?: boolean;+ /**+ * Provider fallback for canonical Fast capability over an OpenAI `service_tier` wire.+ * This pure tri-state feeds catalog publication, routing eligibility, compatibility+ * fingerprints, and proxy-owned canonical Fast injection on both Responses and Chat routes.+ * Tri-state: `true` lets fast mode inject/remove the canonical field; `false` strips it and+ * never injects, because an upstream documented as not supporting the parameter+ * must not receive it; absent (`undefined`) leaves the provider unclassified — fast mode never+ * injects or translates, and caller values pass only under the final wire's forwarding permission.+ * On Chat, that CallerTierForward permission is `chatServiceTier`; Responses retains passthrough.+ * An explicit config value always wins over the registry default.+ */+ supportsServiceTier?: boolean;+ /** Exact upstream model ids that override the provider-level service-tier capability. */+ modelSupportsServiceTier?: Record<string, boolean>;+ /**+ * Responses upstream whose native contract accepts plaintext reasoning replay+ * (DeepSeek documents reasoning items with plaintext content). When set, the+ * passthrough serializer keeps `reasoning_text` content on replayed reasoning+ * items instead of blanking it the way the ChatGPT backend requires; proxy-minted+ * `ocxr1` envelopes are still stripped because no upstream can decrypt them.+ */+ preserveResponsesReasoningContent?: boolean;+ /**+ * Explicit opt-in for a relay that genuinely fronts OpenAI and can decode native+ * compaction blobs. Absent or false degrades foreign blobs to an opaque note.+ */+ decodesNativeCompactionBlobs?: boolean;+ /**+ * Trust this direct key-auth Responses provider to consume or relay opaque encrypted+ * V2 agent tasks. OpenCodex does not decrypt, translate, or recover an eligible task.+ * Absent or false keeps the existing recovery/fail-closed behavior.+ */+ allowEncryptedV2AgentTasks?: boolean;+ /**+ * Explicit opt-in for non-registry private-network destinations such as localhost, RFC1918,+ * link-local, or unique-local upstreams. Metadata endpoints remain blocked.+ */+ allowPrivateNetwork?: boolean;+ /**+ * Pin the HTTP version used for upstream provider requests. Bun's fetch negotiates+ * HTTP/2 via TLS ALPN by default; some Cloudflare-fronted SSE endpoints hang on+ * HTTP/2 streaming responses (issue #1668). "http1.1" / "h1" forces HTTP/1.1,+ * "http2" / "h2" forces HTTP/2. Absent or "auto" keeps Bun's default negotiation+ * (current behavior unchanged). Only meaningful for https: base URLs.+ */+ upstreamHttpVersion?: UpstreamHttpVersion;+ /**+ * Opt-in upstream Responses WebSocket transport for `openai-responses` requests. When true,+ * streaming POST turns use the configured Responses path (default `/v1/responses`): forward+ * providers use `{baseUrl}/responses`, while key-auth providers use `responsesPath` or the+ * legacy `/v1/responses` fallback. HTTPS providers use wss and are re-encoded to SSE; HTTP+ * providers continue using SSE, and `openai-chat` requests stay on HTTP. This mirrors the+ * canonical ChatGPT backend optimization for any OpenAI-compatible gateway that speaks the+ * Responses WebSocket protocol (for example an aggregator like sub2api whose WS ingress is+ * measurably faster than its SSE queue). Default false. Canonical ChatGPT backend WS selection+ * is independent of this flag.+ */+ upstreamWebsocket?: boolean;+ /**+ * Google only. When `false`, the AI Studio (direct) path sends Gemini Flash ids+ * unchanged to the wire instead of applying the `-tiered` suffix (`gemini-3.7-flash`+ * -> `gemini-3.7-flash-tiered`). Set this to `false` when the configured upstream still+ * serves the bare ids. Absent (default) keeps the rename.+ */+ directGeminiWireRenames?: boolean;+ /** Keep provider settings on disk but exclude it from routing and model/catalog listings. */+ disabled?: boolean;+ /**+ * Codex account-selection mode. Valid ONLY on the canonical built-in `openai` forward provider.+ * "pool" (default) rotates main + added Codex accounts through the affinity/quota/cooldown/+ * failover engine; "direct" pins the caller's main Codex login and never touches pool state.+ */+ codexAccountMode?: CodexAccountMode;+ apiKey?: string;+ /**+ * Key-auth header style for Anthropic-compatible providers.+ * Defaults to the native Anthropic `x-api-key`; gateways may require+ * `Authorization: Bearer <key>` instead.+ */+ apiKeyTransport?: "x-api-key" | "bearer";+ /**+ * Multi-key pool (API-key twin of OAuth multiauth). `apiKey` always mirrors the ACTIVE+ * entry so routing stays single-key; managed via /api/providers/keys. A legacy bare+ * `apiKey` seeds a one-entry pool on first management touch.+ */+ apiKeyPool?: Array<{ id: string; key: string; label?: string; addedAt?: number }>;+ /** Changes on manual selection (including re-selection) and committed automatic allocation. */+ apiKeySelectionRevision?: string;+ /** Runtime only. Never expose in management responses or persist a routed provider. */+ _apiKeyAttempt?: ProviderApiKeySelection;+ defaultModel?: string;+ models?: string[];+ /**+ * Fetch the provider's live `/models` endpoint. Defaults to true.+ * Set false when `models` is an intentional allowlist or a provider's live catalog is too large+ * or too flaky for startup/catalog sync.+ */+ liveModels?: boolean;+ /**+ * Per-provider catalog allowlist. When non-empty, ONLY these model ids are emitted to Codex's+ * catalog and `/v1/models` — live discovery still runs, this just narrows what ships (so a proxy+ * exposing thousands of models, or an aggregator like OpenRouter, doesn't bloat the catalog).+ * Empty/undefined = expose all. The admin `/api/models` list is unaffected (it always shows the+ * full set so the user can pick). See devlog issue_052_provider-model-allowlist.+ */+ selectedModels?: string[];+ /** Registration-owned state. Absent means legacy or OAuth-exempt, not uninitialized. */+ initialModelSelection?: {+ version: 1;+ registrationId: string;+ status: "pending" | "ready" | "all-off";+ modelCount?: number;+ };+ /**+ * Per-provider retention allowlist for authoritative live discovery. When non-empty, any+ * model id in this list is preserved in the routed catalog even if the live `/models`+ * endpoint omits it (ad-hoc / private providers whose live discovery drops callable ids).+ * Mirrors the built-in `kimi`/`xai` compatibility tables — opt-in for every other provider.+ * Ids listed here need not be repeated in `models`: discovery folds them into the configured+ * seed, so they exist under `liveModels: false` too. `selectedModels` still narrows what is+ * visible. Empty/undefined = no opt-in (default behavior). See #1690.+ */+ retainModels?: string[];+ /** Override for newly discovered models. Absent/"inherit" uses the install policy. */+ newModelPolicy?: "on" | "off" | "inherit";+ /**+ * Model-preset marker for `selectedModels` (#2465). Absent means "all", exactly today's+ * semantics — an existing provider is never narrowed by an upgrade.+ *+ * The preset is a SEED, not a lock: `selectedModels` holds concrete ids materialized from+ * the shipped rules, so every existing consumer and older binaries keep working against a+ * plain allowlist. Divergence is detected at the WRITE path rather than by diffing — any user+ * edit while the mode is "preset" flips it to "custom", after which the proxy never+ * re-materializes. That collapses upgrade reconciliation to a version compare.+ *+ * Deliberately distinct from `deriveProviderPresets`, which curates WHICH PROVIDERS to offer.+ * This curates which MODELS a provider exposes; the code says "model preset" throughout.+ */+ modelPreset?: {+ mode: "preset" | "all" | "custom";+ /** MODEL_PRESETS version materialized into `selectedModels`. */+ appliedVersion?: number;+ appliedAt?: string;+ /**+ * Set when materialization matched nothing and the provider fell back to "all". A preset+ * must never write an empty allowlist, because empty means ALL and would silently+ * un-curate; the fallback marker lets the next convergence retry.+ */+ fallback?: "preset-empty";+ };+ /** Provider-wide fallback when context metadata is absent; otherwise caps the reported window. */+ contextWindow?: number;+ /** Per-model fallback when context metadata is absent; otherwise caps the reported window. */+ modelContextWindows?: Record<string, number>;+ /** Model-specific Codex catalog input modalities, e.g. ["text"] or ["text", "image"]. */+ modelInputModalities?: Record<string, string[]>;+ /** Model-specific max input token limits. Values cap auto_compact_token_limit. */+ modelMaxInputTokens?: Record<string, number>;+ /**+ * Per-model soft compaction budgets. Values may only lower the effective+ * context/max-input envelope; they never raise hard admission limits.+ */+ modelAutoCompactTokenLimits?: Record<string, number>;+ /**+ * Provider-wide fallback for chat-completions `max_tokens` when the caller omits+ * Responses `max_output_tokens`. Adapters still let an explicit request win.+ */+ defaultMaxOutputTokens?: number;+ /** Model-specific fallback output token budgets. Exact/model-pattern entries beat the provider default. */+ modelMaxOutputTokens?: Record<string, number>;+ /**+ * Per-model display prices (USD per 1M tokens) keyed by exact model id —+ * opencode-style per-model pricing in ocx's flat `modelXxx` convention:+ * `{ "deepseek-v4-flash": { "input": 0.14, "output": 0.28, "cacheRead": 0.0028, "cacheWrite": 0 } }`.+ * User-configured prices win over the built-in jawcode/expected catalogs in+ * the Logs `~$` estimate. Display-time estimation only; never billing. An+ * all-zero entry means "not billable here" and falls through to the catalogs.+ */+ modelCosts?: Record<string, ProviderCostOverlay>;+ headers?: Record<string, string>;+ /** Default provider-routing preferences for models sent through the canonical OpenRouter API. */+ openRouterRouting?: OpenRouterProviderRouting;+ /** Exact model-id overrides for `openRouterRouting`. Each matching entry replaces the default. */+ modelOpenRouterRouting?: Record<string, OpenRouterProviderRouting>;+ /** Default provider-routing preferences for models sent through Vercel AI Gateway (issue #1406). */+ vercelGatewayRouting?: VercelGatewayRouting;+ /** Exact model-id overrides for `vercelGatewayRouting`. Each matching entry replaces the default. */+ modelVercelGatewayRouting?: Record<string, VercelGatewayRouting>;+ /**+ * "key" (default): authenticate upstream with `apiKey`.+ * "forward": relay the caller's incoming auth headers verbatim (OAuth passthrough; gpt only).+ * "oauth": resolve a stored OAuth access token (auto-refreshed) and use it as the Bearer key.+ * Only the openai-responses adapter implements "forward"; openai-chat uses its own key/token.+ * "local": local runtime (Ollama etc.) — no remote key required. Valid only for+ * providers whose registry entry declares authKind "local" (management API enforces).+ */+ authMode?: "key" | "forward" | "oauth" | "local";+ /**+ * Per-provider override for the generic OAuth PROACTIVE account preference (#2568, #695).+ *+ * Reactive 429 rotation is presence-driven and cannot be refused here — 2+ logged-in accounts+ * activate it, and a 429 with an idle second account is a defect rather than a preference.+ * Proactive exhaustion avoidance requires explicit `true`; a healthy selected account+ * retains priority. This overrides global `oauthAccountFailover` in either direction.+ * Reactive 429 rotation remains available even when proactive routing is disabled.+ */+ oauthAccountFailover?: {+ enabled?: boolean;+ /**+ * Generic OAuth pool selection strategy (#695). Persisted through the pool-settings+ * contract; the selector does not consume it yet, so omitted keeps today's behavior.+ */+ strategy?: "quota" | "round-robin" | "fill-first";+ /** 0-100 usage percent at which a proactive switch may be considered (#695); inert today. */+ autoSwitchThreshold?: number;+ };+ /** Allow an explicitly key/oauth provider to run without a credential (for keyless local proxies). */+ keyOptional?: boolean;+ /**+ * Free-tier pricing flag for UI/catalog (Free badge, Free filter). Not the same as+ * `keyOptional` — free tiers may still require an API key (e.g. NVIDIA NIM free credits).+ */+ freeTier?: boolean;+ /** Optional human note shown in the providers UI (not used for routing). */+ note?: string;+ /** Strip one trailing bracketed suffix from model ids before sending them upstream. */+ modelSuffixBracketStrip?: boolean;+ /**+ * Override the guardian's proactive-refresh policy for this provider. When unset, the provider's+ * built-in risk-tiered default applies (see OAUTH_PROVIDERS in src/oauth/index.ts). Set "proactive"+ * to opt this provider into background refresh; "disabled"/"lazy-only" to forbid/limit it.+ */+ refreshPolicy?: RefreshPolicy;+ /**+ * Provider-wide Codex-visible reasoning tiers for routed models. Use only Codex-supported labels+ * here (`low`, `medium`, `high`, `xhigh`, `max`); translate provider aliases with+ * `reasoningEffortMap` / `modelReasoningEffortMap` below.+ */+ reasoningEfforts?: string[];+ /** Model-specific Codex-visible reasoning tiers. An empty array means “do not expose effort”. */+ modelReasoningEfforts?: Record<string, string[]>;+ /** Model-specific default Codex reasoning tier; must also be present in the visible tier list. */+ modelDefaultReasoningEfforts?: Record<string, string>;+ /** Operator-owned effort override; none omits effort and uses the provider default. */+ pinnedReasoningEffort?: string;+ /** Per-model operator override, ahead of provider-wide and global pins; caps still apply. */+ modelPinnedReasoningEfforts?: Record<string, string>;+ /**+ * Model-specific Codex reasoning-summary capability. Set false when an OpenAI-compatible+ * Responses backend rejects Codex summary-delivery fields for that model.+ */+ modelSupportsReasoningSummaries?: Record<string, boolean>;+ /**+ * Model-specific Codex Responses verbosity capability. Set false when the upstream ignores+ * `text.verbosity`; the catalog hides the no-op picker and the Responses adapter strips stale+ * or caller-supplied values while preserving other `text` fields.+ */+ modelSupportsVerbosity?: Record<string, boolean>;+ /**+ * Provider-wide Codex Responses verbosity capability, applied to models the per-model map+ * does not enumerate (a live-discovered id, for example). Materialized from the registry at+ * seed/enrich time so the catalog hint pass never has to read PROVIDER_REGISTRY.+ */+ supportsVerbosity?: boolean;+ /**+ * Per-model wire value for Responses `stream_options.reasoning_summary_delivery`.+ * Presence also advertises reasoning-summary support for that routed model.+ */+ modelReasoningSummaryDelivery?: Record<string, ReasoningSummaryDelivery>;+ /**+ * Exact-model hosted tools that win collisions with Codex client tool declarations.+ * Use for non-forward Responses gateways that reserve a hosted tool namespace server-side.+ */+ modelPreferHostedTools?: Record<string, string[]>;+ /**+ * Whether the Responses upstream accepts OpenAI's extended hosted web_search fields.+ * Set false only for a provider whose native contract rejects them; absence preserves+ * passthrough compatibility for OpenAI and unclassified gateways.+ */+ supportsOpenAiWebSearchToolFields?: boolean;+ /**+ * Opt xAI Responses destinations into the provider-hosted `x_search` declaration when a live+ * `web_search` tool survives final request normalization. Disabled by default. This is separate+ * from the web-search sidecar's `search.xSearch` options and never widens caller tool selectors.+ */+ xaiResponsesXSearch?: boolean;+ /** One-time Grok subscription wire upgrade; later explicit Chat choices remain authoritative. */+ xaiResponsesDefaultVersion?: number;+ /**+ * Whether the Responses upstream accepts native custom tools and custom_tool_call items.+ * Set false only for a provider whose native contract rejects them; absence preserves+ * apply_patch passthrough compatibility for OpenAI and unclassified gateways.+ */+ supportsResponsesCustomTools?: boolean;+ /**+ * Provider-local repair for Responses gateways whose lifecycle snapshots omit canonical+ * fields or closing events (#893). Disabled by default and applied only to client-facing+ * SSE/JSON; raw inspection state remains authoritative.+ */+ responsesSnapshotRepair?: boolean;+ /**+ * Opt-in hosted-web-search bridge for this KEY-auth Responses passthrough provider (#3761).+ * Absent or disabled leaves the passthrough byte-identical to today.+ */+ webSearchBridge?: ProviderWebSearchBridgeConfig;+ /**+ * Provider-wide mapping from Codex effort labels to upstream `reasoning_effort` values.+ * Map a label to the reserved value `"__omit__"` to send no reasoning field at all for that+ * effort, so the upstream model's own default applies. The sentinel is+ * `REASONING_EFFORT_OMIT_SENTINEL` in `src/reasoning-effort.ts`; it suppresses+ * `reasoning_effort` on an OpenAI-compatible wire and Ollama's native `think` field on the+ * Ollama native adapter (#2356).+ */+ reasoningEffortMap?: Record<string, string>;+ /**+ * Model-specific mapping from Codex effort labels to upstream `reasoning_effort` values.+ * Map a label to the reserved value `"__omit__"` to send no reasoning field at all for that+ * effort, so the upstream model's own default applies. Same sentinel as+ * `reasoningEffortMap`, resolved per model first.+ */+ modelReasoningEffortMap?: Record<string, Record<string, string>>;+ /** OpenAI-compatible gateway reasoning wire shape. Default sends `reasoning_effort`. */+ reasoningWireFormat?: "gateway-object";+ /**+ * Model ids that do NOT support a reasoning/thinking parameter. The openai-chat adapter drops+ * reasoning_effort for these even when Codex selects a reasoning level (e.g. xAI grok-build-0.1).+ */+ noReasoningModels?: string[];+ /** Model ids that reject caller-specified temperature. */+ noTemperatureModels?: string[];+ /** Model ids that reject caller-specified top_p. */+ noTopPModels?: string[];+ /** Model ids that reject caller-specified presence/frequency penalty values. */+ noPenaltyModels?: string[];+ /**+ * Model ids whose Chat Completions endpoint rejects `response_format`.+ * Structured-output translation remains enabled by default; this is a narrow+ * per-model compatibility escape hatch for mixed-capability gateways.+ */+ noStructuredOutputModels?: string[];+ /**+ * Model ids that accept a reasoning-effort field on an ordinary turn but reject it+ * once function tools are present. The model keeps its advertised effort ladder;+ * OpenCodex omits the wire field for tool-bearing requests only and lets the+ * upstream default apply. Narrower than `noReasoningModels`, which strips reasoning+ * from every request and costs the model its picker entirely.+ */+ omitReasoningEffortWithToolsModels?: string[];+ /**+ * Allow multiple tool calls per completion. DEFAULT-ON for openai-chat providers (the+ * buffered stream parser assembles interleaved/fragmented multi-call turns safely);+ * set `false` to force `parallel_tool_calls:false` upstream and drop the catalog's+ * `supports_parallel_tool_calls` bit for that provider. Non-chat adapters advertise+ * only on explicit `true`. See devlog/_plan/260709_parallel_tool_calls.+ */+ parallelToolCalls?: boolean;+ /**+ * Opt-in: when `parallelToolCalls` is `false`, actually send `parallel_tool_calls: false`+ * on the `/chat/completions` wire for this provider. By default an opted-out provider only+ * OMITS the field (strict OpenAI-compatible hosts reject unknown knobs), and the NVIDIA NIM+ * baseUrl is the sole built-in exception that pins the wire bit. Some self-hosted gateways+ * (Kimi/GLM-family, vLLM, etc.) do honor `parallel_tool_calls` and keep emitting concurrent+ * tool calls unless it is present; enable this to pin the bit without hardcoding their URL.+ * No effect unless `parallelToolCalls === false`; ignored by non-`openai-chat` adapters.+ */+ pinParallelToolCallsFalse?: boolean;+ /**+ * Opt-in: extend the no-tool-call terminal continuation guard to this provider's+ * `openai-chat` routed turns. The guard (originally Anthropic-only, see+ * devlog/_fin/260706_previous-response-id-400) issues one bounded internal re-ask when a+ * model announces work but ends the turn without emitting a tool call. Self-hosted+ * OpenAI-compatible gateways (GLM/Kimi-family, etc.) hit the same premature-completion+ * pattern, but the heuristic that decides a "suspicious no-tool stop" was tuned on+ * Anthropic turns, so it stays OFF by default for the many registry providers that share+ * the `openai-chat` adapter. Enable only for a provider whose models are known to stop+ * mid-work; non-`openai-chat` adapters ignore this flag.+ */+ terminalContinuationGuard?: boolean;+ /**+ * Opt-in for OpenAI-compatible chat gateways that may close after emitting a complete+ * tool-call delta without `finish_reason` or `[DONE]`. The adapter accepts that EOF only+ * when every pending call has a non-empty name and complete JSON-object arguments;+ * incomplete JSON, missing arguments, and empty streams remain truncation errors.+ */+ openaiChatEofTolerance?: boolean;+ /**+ * Opt-in: forward `prompt_cache_key` to the upstream `/chat/completions` body.+ * OpenAI-specific extension; strict backends (Groq, Cerebras, etc.) reject unknown+ * fields. Default off; only enable for providers that document this parameter.+ */+ promptCacheKey?: boolean;+ /**+ * Opt-in: forward caller `service_tier` values to the upstream `/chat/completions` body.+ * On a classified route it governs foreign values (for example `flex`), not proxy-owned+ * canonical Fast after capability validation. On an unclassified route it governs every caller+ * value, including canonical spellings, because no Fast capability has been validated.+ * OpenAI-specific extension with the same hazard as `promptCacheKey` — strict backends+ * reject unknown fields, and 66 registry providers share the `openai-chat` adapter, so a+ * caller-supplied `service_tier` would otherwise turn working requests into upstream 400s.+ * Exact-model `true` enables canonical Fast capability but does not grant foreign-tier+ * forwarding; provider-level `supportsServiceTier: false` remains a global denial. Default off;+ * only enable for providers that document this parameter on the chat wire.+ */+ chatServiceTier?: boolean;+ /**+ * Provider-local passthrough SSE repair for broken openai-responses gateways that reuse exact+ * placeholder message/reasoning ids or omit the terminal id after a stable added event.+ * Disabled by default; function_call ids and call_id pairing are never rewritten.+ */+ responsesItemIdRepair?: ResponsesItemIdRepairConfig;+ /** Model ids whose tool_choice only accepts `auto` or `none`; forced/named choices are downgraded. */+ autoToolChoiceOnlyModels?: string[];+ /** Model ids that expect prior assistant `reasoning_content` to be preserved in chat history. */+ preserveReasoningContentModels?: string[];+ /**+ * Model ids whose upstream hard-rejects a tool_call continuation missing+ * `reasoning_content` (DeepSeek thinking mode: HTTP 400). When the replay+ * cache misses, the adapter injects a minimal placeholder for these models.+ * Defaults to `preserveReasoningContentModels` when unset; set `[]` to opt+ * out explicitly (e.g. MiniMax, where low effort disables thinking).+ */+ requiresReasoningPlaceholderModels?: string[];+ /**+ * Opt-in same-target 429 retry policy. Codex itself never retries 429 (it retries 5xx only,+ * openai/codex#30471), and single-key pools have no failover, so the proxy waits and replays+ * the identical request on the same key before any failover. Pre-stream only: a 429 arrives+ * before any response bytes are relayed, so the replay is lossless.+ */+ retryOn429?: RateLimitRetryPolicy;+ /**+ * Opt-in retry for pre-stream transient upstream statuses+ * (`providers.<name>.transientRetryOn5xx`). Disabled unless present; a bare `{}` opts in+ * with defaults. Key-auth `openai-chat` only.+ */+ transientRetryOn5xx?: TransientRetryPolicy;+ /**+ * Model ids whose OpenAI-compatible chat endpoint accepts `reasoning_split: true` and returns+ * thinking separately in `reasoning_content` / `reasoning_details` instead of visible content.+ */+ reasoningSplitModels?: string[];+ /**+ * Model ids whose chat endpoint carries thinking as a structured `reasoning_details` array+ * (MiniMax M-series with `reasoning_split`): stream deltas repeat each detail's `text` as a+ * cumulative snapshot, so the adapter prefix-diffs instead of appending, and preserved+ * reasoning replays as a `reasoning_details` array rather than a `reasoning_content` string+ * (upstream requires the array back verbatim to keep interleaved thinking intact).+ */+ reasoningDetailsModels?: string[];+ /**+ * Model ids whose reasoning is a vendor `thinking: {type}` toggle on the+ * chat-completions wire (MiMo v2.x, GLM 5/5.1 style), NOT an OpenAI `reasoning_effort` ladder.+ * The openai-chat adapter translates the mapped effort into the thinking toggle for these.+ */+ thinkingToggleModels?: string[];+ /**+ * Model ids whose reasoning is a `thinking_budget` integer on the chat-completions wire+ * (Qwen3.x style), NOT an OpenAI `reasoning_effort` ladder. The openai-chat adapter maps the+ * Codex effort to a budget fraction.+ */+ thinkingBudgetModels?: string[];+ /** Anthropic-compatible gateways that need custom tool names escaped on the wire. */+ escapeBuiltinToolNames?: boolean;+ /**+ * Anthropic-compatible gateways (e.g. AgentRouter) that may close the stream before+ * `message_stop`. With this enabled the adapter completes an otherwise-clean EOF only when+ * visible text was received or an open tool call has complete JSON-object arguments; all+ * other EOFs remain truncation errors. Absent = strict default behavior.+ */+ anthropicEofTolerance?: boolean;+ /**+ * Model ids that do NOT accept image inputs. The proxy gives them "eyes" via the vision sidecar:+ * attached images are described by a gpt vision model and replaced with text before the call.+ */+ noVisionModels?: string[];+ /**+ * Google adapter mode. "ai-studio" (default) = Generative Language API + x-goog-api-key.+ * "vertex" = Vertex AI project/location endpoints with GCP ADC (or x-goog-api-key).+ * "cloud-code-assist" = Google Antigravity (Cloud Code Assist) OAuth + CCA envelope.+ */+ googleMode?: "ai-studio" | "vertex" | "cloud-code-assist";+ /** Vertex AI GCP project id (or GOOGLE_CLOUD_PROJECT / GCLOUD_PROJECT env). */+ project?: string;+ /** Vertex AI location, e.g. "us-central1" or "global" (or GOOGLE_CLOUD_LOCATION env). */+ location?: string;+ /**+ * Cursor adapter only: MCP servers opencodex starts/connects and exposes to the Cursor agent+ * as callable tools. Each entry is spawned (stdio `command`) or connected (`url`) lazily per+ * stream; their tools are advertised to the Cursor server and executed against the live server.+ */+ mcpServers?: Record<string, import("../adapters/cursor/mcp-config").CursorMcpServerConfig>;+ /**+ * Cursor adapter only: opt-in external executor for computer-use / record-screen. opencodex is+ * headless and cannot control a screen itself; provide commands here only when running on a host+ * that can. With no executor, these tools honestly report "not supported".+ */+ desktopExecutor?: import("../adapters/cursor/desktop-executor-contract").DesktopExecutorConfig;+ /**+ * Cursor adapter only: unsafe opt-in escape hatch for Cursor server-driven built-in local+ * read/write/delete/ls/grep/shell/fetch execution. Prefer `nativeLocalExec: "on"` for new+ * configs; this legacy boolean remains a server-local explicit opt-in for existing operators.+ * Defaults to false so remote Cursor messages cannot bypass Codex approval/sandbox semantics.+ * Explicit MCP and desktop executors remain controlled by their own opt-in config.+ */+ unsafeAllowNativeLocalExec?: boolean;+ /**+ * Cursor adapter only: native local exec policy mode (exec-policy.ts).+ * "off" (default) rejects server-driven local exec; "on" always allows it for this+ * provider and should be used only for a trusted local experiment on a host where every+ * data-plane caller is trusted. "codex-sandbox" is accepted for backwards compatibility+ * but is fail-closed like "off": Responses instructions/system/developer text is+ * caller-controlled prose, and opencodex has no trustworthy per-request attestation that it+ * reflects a real Codex sandbox state. The default loopback bind admits ANY local process+ * without auth (including other local users on multi-user machines), and+ * isAllowedRequestOrigin blocks non-loopback browser origins by default but not+ * loopback-origin or origin-less callers.+ */+ nativeLocalExec?: "off" | "codex-sandbox" | "on";+}diff --git a/packages/model-compat/src/upstream/types/tools.ts b/packages/model-compat/src/upstream/types/tools.tsnew file mode 100644index 0000000000..bb91ebe63f--- /dev/null+++ b/packages/model-compat/src/upstream/types/tools.ts@@ -0,0 +1,274 @@+export interface OcxTool {+ name: string;+ description: string;+ parameters: Record<string, unknown>;+ strict?: boolean;+ /** MCP namespace (e.g. "mcp__context7") for tools flattened out of a Responses "namespace" tool. */+ namespace?: string;+ /** Freeform/custom tool (e.g. apply_patch): the model's call must be relayed as a custom_tool_call. */+ freeform?: boolean;+ /** Client-executed tool discovery (tool_search): the model's call must be relayed as a tool_search_call. */+ toolSearch?: boolean;+ /** Tool definition restored from a prior tool_search output; transports may prioritize it when catalogs are bounded. */+ loadedFromToolSearch?: boolean;+ /** Cursor-only synthetic exact-match edit tool; never inferred from the wire name. */+ cursorStructuredEdit?: true;+ /** Synthetic web_search tool: the model's call is executed by the gpt-5.4-mini sidecar, not relayed to Codex. */+ webSearch?: boolean;+ /** Synthetic image_gen tool: the model's call is executed by the xAI image bridge sidecar, not relayed to Codex. */+ imageGeneration?: boolean;+ /** Synthetic video_gen tool: executed by the xAI video bridge sidecar. */+ videoGeneration?: boolean;+}++/**+ * Wire name a chat model sees for a tool. Namespaced (MCP) tools are flattened to+ * "<namespace>__<name>" so they survive the chat-completions function-tool format;+ * the proxy maps this back to {namespace, name} on the return trip (Codex routes MCP+ * calls by an explicit `namespace` field, not by parsing the name).+ */+export function namespacedToolName(namespace: string | undefined, name: string): string {+ return namespace ? `${namespace}__${name}` : name;+}++/**+ * Dotted alias of a namespaced tool's wire name. Some routed providers (observed: muse-spark+ * via opencode-go) echo a namespaced tool call as "<namespace>.<name>" instead of the flattened+ * "<namespace>__<name>" form. It names the same tool identity+�u���T never a new grant"��y��y� so the+ * undeclared-tool guard and the tool bridge maps accept it wherever the wire name is accepted+ * (mirroring the second entry of `toolChoiceAliases`). See #3402.+ */+export function dottedToolName(namespace: string | undefined, name: string): string {+ return namespace ? `${namespace}.${name}` : name;+}++/**+ * Codex unified-exec name normalization.+ *+ * Codex's code-mode shell tool is declared as `exec` (a freeform custom tool whose own+ * description mentions the nested `await tools.exec_command(...)` helper). Some routed providers+ * echo that helper name as the tool-call name, emitting `exec_command`, `write_stdin`, or+ * `apply_patch` instead of the declared `exec`. Accept these nested helper names only when the+ * request catalog actually declares `exec` and does not itself declare the emitted name (an MCP+ * server may legitimately advertise one under its own namespace).+ */+const LEGACY_SHELL_BRIDGE_TOOL_NAMES = ["exec_command", "shell_command"] as const;+const CODE_MODE_HELPER_TOOL_NAMES = [+ ...LEGACY_SHELL_BRIDGE_TOOL_NAMES,+ "write_stdin",+ "apply_patch",+] as const;++/**+ * The one declared name that turns nested-helper normalization on. Declaring it is not just a+ * name: it also decides whether an emitted helper name is accepted as that shell tool, so callers+ * that build declared-name sets must add it only for a genuine bare declaration.+ */+export const CODE_MODE_EXEC_TOOL_NAME = "exec";++export function normalizeDeclaredToolName(+ name: string,+ declared: ReadonlySet<string> | undefined,+): string {+ if (!declared || !declared.has(CODE_MODE_EXEC_TOOL_NAME)) return name;+ if (declared.has(name)) return name;+ if (name === "apply_patch") return CODE_MODE_EXEC_TOOL_NAME;+ // When the catalog explicitly declares any legacy shell bridge name, the environment+ // genuinely exposes that tool — turn normalization off so a call is never mis-routed+ // to `exec`.+ if ((LEGACY_SHELL_BRIDGE_TOOL_NAMES as readonly string[]).some(legacy => declared.has(legacy))) {+ return name;+ }+ return (CODE_MODE_HELPER_TOOL_NAMES as readonly string[]).includes(name)+ ? CODE_MODE_EXEC_TOOL_NAME+ : name;+}++/**+ * True when a declared catalog is the genuine Codex code-mode shape.+ *+ * `exec` is a name, not a guarantee. A catalog that lists `exec` NEXT TO a bare+ * `exec_command` or `shell_command` is the flat-bridge shape: there `exec` may be an+ * ordinary caller-defined tool, and nested `tools.*` helpers are not what it runs.+ * `normalizeDeclaredToolName` already refuses to reinterpret helper names in that shape,+ * and anything inferring code mode from the bare name owes the same check.+ */+export function declaresCodeModeExec(declared: ReadonlySet<string> | undefined): boolean {+ if (!declared || !declared.has(CODE_MODE_EXEC_TOOL_NAME)) return false;+ return !(LEGACY_SHELL_BRIDGE_TOOL_NAMES as readonly string[]).some(legacy => declared.has(legacy));+}++export function toolChoiceAliases(tool: Pick<OcxTool, "namespace" | "name">): string[] {+ const wireName = namespacedToolName(tool.namespace, tool.name);+ return tool.namespace ? [wireName, dottedToolName(tool.namespace, tool.name)] : [wireName];+}++function sameToolIdentity(+ left: Pick<OcxTool, "namespace" | "name">,+ right: Pick<OcxTool, "namespace" | "name">,+): boolean {+ return left.namespace === right.namespace && left.name === right.name;+}++type ToolIdentity = Readonly<Pick<OcxTool, "namespace" | "name">>;++function snapshotToolIdentity(tool: Pick<OcxTool, "namespace" | "name">): ToolIdentity {+ return Object.freeze({+ name: tool.name,+ ...(tool.namespace === undefined ? {} : { namespace: tool.namespace }),+ });+}++function buildToolChoiceCatalog(+ tools: readonly ToolIdentity[],+): {+ candidatesByName: ReadonlyMap<string, readonly ToolIdentity[]>;+ sourceCandidatesByName: ReadonlyMap<string, readonly ToolIdentity[]>;+ identitiesByTool: WeakMap<object, ToolIdentity>;+} {+ const index = new Map<string, ToolIdentity[]>();+ const sourceIndex = new Map<string, ToolIdentity[]>();+ const identities = new Map<string, Set<string>>();+ const identitiesByTool = new WeakMap<object, ToolIdentity>();+ for (const tool of tools) {+ const snapshot = snapshotToolIdentity(tool);+ identitiesByTool.set(tool, snapshot);+ const identity = JSON.stringify([snapshot.namespace ?? null, snapshot.name]);+ for (const selector of [...toolChoiceAliases(snapshot), snapshot.name]) {+ const candidates = index.get(selector);+ if (!candidates) {+ index.set(selector, [snapshot]);+ sourceIndex.set(selector, [tool]);+ identities.set(selector, new Set([identity]));+ } else if (!identities.get(selector)!.has(identity)) {+ candidates.push(snapshot);+ sourceIndex.get(selector)!.push(tool);+ identities.get(selector)!.add(identity);+ }+ }+ }+ return { candidatesByName: index, sourceCandidatesByName: sourceIndex, identitiesByTool };+}++/** Compile one immutable view of a request's tool catalog for repeated policy checks. */+export function createToolChoiceResolver(tools: readonly ToolIdentity[] | undefined) {+ const compiled = tools ? buildToolChoiceCatalog(tools) : undefined;+ const candidatesByName = compiled?.candidatesByName;+ const snapshotFor = (tool: ToolIdentity): ToolIdentity | undefined => {+ const snapshot = compiled?.identitiesByTool.get(tool);+ return snapshot && sameToolIdentity(snapshot, tool) ? snapshot : undefined;+ };+ return {+ candidates(name: string): ToolIdentity[] {+ return (candidatesByName?.get(name) ?? []).map(candidate => ({ ...candidate }));+ },+ candidateCount(name: string): number {+ return candidatesByName?.get(name)?.length ?? 0;+ },+ allows(tool: ToolIdentity, allowedTools: ReadonlySet<string>): boolean {+ if (!candidatesByName) return toolChoiceAliases(tool).some(name => allowedTools.has(name));+ const snapshot = snapshotFor(tool);+ return snapshot ? toolAllowedByChoiceFromIndex(snapshot, allowedTools, candidatesByName) : false;+ },+ selects(tool: ToolIdentity, name: string): boolean {+ const snapshot = snapshotFor(tool);+ const candidates = candidatesByName?.get(name);+ return !!snapshot && candidates?.length === 1 && sameToolIdentity(candidates[0], snapshot);+ },+ };+}++/**+ * All tools that could be selected by one client-facing name. Bare logical names are included+ * here because they are a compatibility selector for namespaced tools, while wire and dotted+ * aliases come from `toolChoiceAliases`. A selector with more than one candidate is invalid.+ */+export function toolChoiceCandidates(+ tools: readonly Pick<OcxTool, "namespace" | "name">[] | undefined,+ name: string,+): Pick<OcxTool, "namespace" | "name">[] {+ if (!tools) return [];+ return [...(buildToolChoiceCatalog(tools).sourceCandidatesByName.get(name) ?? [])];+}++/**+ * Newer Codex clients can select a tool nested in a namespace by its bare name. Resolve that+ * shorthand only when the request contains one tool with the logical name, so an ambiguous name+ * cannot authorize a tool from an unintended namespace.+ */+export function toolAllowedByChoice(+ tool: Pick<OcxTool, "namespace" | "name">,+ allowedTools: ReadonlySet<string>,+ tools?: readonly Pick<OcxTool, "namespace" | "name">[],+): boolean {+ if (!tools) return toolChoiceAliases(tool).some(name => allowedTools.has(name));+ return toolAllowedByChoiceFromIndex(+ snapshotToolIdentity(tool),+ allowedTools,+ buildToolChoiceCatalog(tools).candidatesByName,+ );+}++function toolAllowedByChoiceFromIndex(+ tool: ToolIdentity,+ allowedTools: ReadonlySet<string>,+ candidatesByName: ReadonlyMap<string, readonly ToolIdentity[]>,+): boolean {+ for (const name of [...toolChoiceAliases(tool), tool.name]) {+ if (!allowedTools.has(name)) continue;+ const candidates = candidatesByName.get(name);+ if (candidates?.length === 1 && sameToolIdentity(candidates[0], tool)) return true;+ }+ return false;+}++export function resolveToolChoiceWireName(tools: readonly Pick<OcxTool, "namespace" | "name">[] | undefined, name: string): string {+ const candidates = toolChoiceCandidates(tools, name);+ if (candidates.length === 1) {+ const match = candidates[0];+ return namespacedToolName(match.namespace, match.name);+ }+ // Keep unknown/ambiguous names unchanged for callers that only serialize a selector. The+ // catalog-aware predicate rejects them, and parseRequest rejects ambiguous request selectors.+ return name;+}++/**+ * Whether `modelId` is in a per-provider classification list (e.g. `noVisionModels`). Matches the full+ * id, OR — for Ollama-style ids — the family before the ":size" tag, so a `gpt-oss` entry covers+ * `gpt-oss:120b`/`gpt-oss:20b`. Colon-less ids (e.g. `grok-build-0.1`) still match exactly only.+ */+export function modelInList(list: string[] | undefined, modelId: string): boolean {+ if (!list || list.length === 0) return false;+ if (list.includes(modelId)) return true;+ const colon = modelId.indexOf(":");+ return colon > 0 && list.includes(modelId.slice(0, colon));+}++export type OcxToolChoice =+ | "auto"+ | "none"+ | "required"+ | { name: string }+ | { allowedTools: string[]; mode: "auto" | "required" };++export function isAllowedToolChoice(value: OcxToolChoice | undefined): value is { allowedTools: string[]; mode: "auto" | "required" } {+ return typeof value === "object" && value !== null && "allowedTools" in value;+}++/** Compile the request's tool-choice policy into a reusable advertisement/restoration predicate. */+export function toolChoiceToolPredicate(+ choice: OcxToolChoice | undefined,+ tools?: readonly Pick<OcxTool, "namespace" | "name">[],+): (tool: Pick<OcxTool, "namespace" | "name">) => boolean {+ if (!choice || choice === "auto" || choice === "required") return () => true;+ if (choice === "none") return () => false;+ if (isAllowedToolChoice(choice)) {+ const allowed = new Set(choice.allowedTools);+ const resolver = createToolChoiceResolver(tools);+ return tool => resolver.allows(tool, allowed);+ }+ if (!tools) return tool => toolChoiceAliases(tool).includes(choice.name);+ const resolver = createToolChoiceResolver(tools);+ return tool => resolver.selects(tool, choice.name);+}diff --git a/packages/model-compat/src/upstream/types/wire.ts b/packages/model-compat/src/upstream/types/wire.tsnew file mode 100644index 0000000000..0800bca428--- /dev/null+++ b/packages/model-compat/src/upstream/types/wire.ts@@ -0,0 +1,80 @@+/**+ * Accepted values for the per-provider upstream HTTP-version pin (#1668). Shared by the+ * zod load schema, the management write boundary (POST/PATCH), and the fetch runtime, so+ * a value that one boundary accepts can never be rejected by another.+ */+export const UPSTREAM_HTTP_VERSION_VALUES = [+ "auto",+ "http1.1",+ "h1",+ "http2",+ "h2",+] as const;++export type UpstreamHttpVersion = (typeof UPSTREAM_HTTP_VERSION_VALUES)[number];++export const REASONING_SUMMARY_DELIVERY_VALUES = [+ "sequential",+ "sequential_cutoff",+ "concurrent",+ "concurrent_cutoff",+] as const;++export type ReasoningSummaryDelivery = typeof REASONING_SUMMARY_DELIVERY_VALUES[number];++/** Trusted runtime ownership for Codex-account credentials. Never persisted per provider. */+export type CodexAccountMode = "direct" | "pool";++export const OPENAI_PROVIDER_TIER_VERSION = 2 as const;++/**+ * Wires that a per-model `modelAdapters` override may select.+ *+ * Deliberately narrow: provider-specific adapters (cursor, kiro, google, ...) carry+ * their own credential and base-URL semantics, so exposing them here would widen the+ * auth boundary rather than pick a wire. Widening this set needs a per-adapter+ * credential threat model first (#404).+ */+export const MODEL_ADAPTER_OVERRIDE_ALLOWED: ReadonlySet<string> = new Set([+ "openai-chat",+ "openai-responses",+]);++/**+ * Providers whose listed model ids must be driven over the Anthropic wire even when+ * the provider's configured adapter says otherwise — the upstream only speaks+ * Anthropic for these models.+ */+const ANTHROPIC_WIRE_MODELS: Record<string, ReadonlySet<string>> = {+ "opencode-go": new Set(["minimax-m2.5", "minimax-m2.7", "minimax-m3"]),+};++function anthropicWireModelsForProvider(providerName: string): ReadonlySet<string> | undefined {+ return Object.hasOwn(ANTHROPIC_WIRE_MODELS, providerName)+ ? ANTHROPIC_WIRE_MODELS[providerName]+ : undefined;+}++/** Detached provider-local hard-pin table for pure wire-policy resolution. */+export function captureWireAdapterHardPins(providerName: string): Readonly<Record<string, string>> {+ const models = anthropicWireModelsForProvider(providerName);+ if (!models) return Object.freeze({});+ return Object.freeze(Object.fromEntries([...models].map(modelId => [modelId, "anthropic"])));+}++/**+ * True when the upstream speaks exactly one wire for this model, so a configured+ * override must not apply.+ *+ * Deliberately independent of the provider's current adapter: the wire resolver runs+ * more than once per request, and a check phrased as "pin differs from the current+ * adapter" would pass on the first pass and then let the override win on the second.+ */+export function isWirePinnedModel(providerName: string, modelId: string): boolean {+ return anthropicWireModelsForProvider(providerName)?.has(modelId) ?? false;+}++/** The wire a pinned model must use, or undefined when the model is not pinned. */+export function pinnedWireAdapter(providerName: string, modelId: string): string | undefined {+ return isWirePinnedModel(providerName, modelId) ? "anthropic" : undefined;+}diff --git a/packages/model-compat/tsconfig.json b/packages/model-compat/tsconfig.jsonnew file mode 100644index 0000000000..fefb71da01--- /dev/null+++ b/packages/model-compat/tsconfig.json@@ -0,0 +1,17 @@+{+ "compilerOptions": {+ "target": "ESNext",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "resolveJsonModule": true,+ "isolatedModules": true,+ "noEmit": true,+ "sourceMap": true,+ "baseUrl": "."+ },+ "include": ["src/**/*"]+}diff --git a/packages/model-compat/upstream-inventory.json b/packages/model-compat/upstream-inventory.jsonnew file mode 100644index 0000000000..715b7813c2--- /dev/null+++ b/packages/model-compat/upstream-inventory.json@@ -0,0 +1,1017 @@+{+ "src/adapters/agentrouter.ts": "04d9db08d5d6a9d33eaac1bd11a527440e742d7844009eddddf3e08602ad4bd1",+ "src/adapters/anthropic-image-codec.ts": "3e6508e16d71e52580df0cd40683d7060f29213f930fbd78c2d811a3ad1815ed",+ "src/adapters/anthropic-image-guard.ts": "ee4d66e70b7445f6ed946bbe058fc59dbd6d5844e6064eeb72e776648ccb89ab",+ "src/adapters/anthropic-image-normalize.ts": "2f7a058266706a822fd215d27fd3507aa64d6cfbced85363d915d10b29c50dbb",+ "src/adapters/anthropic-output-schema.ts": "ee07b2e75242100805a72f59271a52a6008d587013f871b777ed91e706fd8d6b",+ "src/adapters/anthropic.ts": "53af30d134ff1b1519b339c09fb740b8c76d1bc2aeb32ed314426832e5cfd471",+ "src/adapters/azure.ts": "9eeea6a4138c92c5bf895cb23b2cd714b9b21c3571e47a9281f68ced40a91b9d",+ "src/adapters/base.ts": "a7d585f6dfdf07086971fcd93184da1df6ad55fb88e5a3b6777acf6884246947",+ "src/adapters/client-fingerprint.ts": "8a321c8d1bbb727de120d0facf676f1f046cc6d28c3b3f77f915d7445ecff22c",+ "src/adapters/cline-pass-deepseek-v4-tool-replay.ts": "da664327db4e0bae8ab689230deec415ad3f6d0f18c596dcc5b94c8a8d08a345",+ "src/adapters/codebuddy/adapter.ts": "72e26de5520d2a9c22c8ac0b2eaefa61c67e5084c3505f8fdcb150ecf1ad2b6c",+ "src/adapters/codebuddy/profiles.ts": "b69bd75fc0fc11f4d1c599dc56baf52dd5e491e5725d33a58031aff7008ad356",+ "src/adapters/coding-agent/profile.ts": "aaca42aae64ccbc845b26daca057fceb786d41b7af96d57d7f6912b5d5ceec82",+ "src/adapters/coding-agent/protocol.ts": "e8be36d947baf5981691192f6902dedab09b3fb30b0dad5e72cef61c02236e8d",+ "src/adapters/coding-agent/turn.ts": "50a609716b73a6dad7d482d8e87ffa4aa5fd4ce3f40ea319f4b0109a0bb5e577",+ "src/adapters/command-code.ts": "65b24b72214199a91e96af23d43abe743b76cc735c7a9b1017fadc7f237798cf",+ "src/adapters/cursor/arg-codec.ts": "607316e8f490421b81432498875da03f353dd189c71d112c4222a8fbea621c43",+ "src/adapters/cursor/arg-normalize.ts": "22653d0079149de74d3b2d2b8af13768a3e1e0e9e676a9452c987f723cbe40b6",+ "src/adapters/cursor/call-id.ts": "0556c3244bc4bb1975b63c9c55f5dcf5ad688293200794ac60f89e2a3972606b",+ "src/adapters/cursor/catalog.ts": "b70cf4ca5f700f3db00b3dc8ceebecbc084bcd4faf76c50dc9e2ff062d5e3d87",+ "src/adapters/cursor/checkpoint-store.ts": "6bb5a6661bd251dd43ebc096adf207c0198fa145cc3d0246cd22920b7efafb8e",+ "src/adapters/cursor/claude-id.ts": "1be7fb39ce50b0407ba98f6052ecbb9092fcb2220cf5388336f14c04f32c15b6",+ "src/adapters/cursor/cursor-errors.ts": "2baae75f883e4f09b3cb20084be8124f00d727f007ccdfbd898f61052a59fd4b",+ "src/adapters/cursor/desktop-executor-contract.ts": "c12754b08175a21439047a2c39e2cb277da732e536b44b532d81e1d7445042d6",+ "src/adapters/cursor/discovery.ts": "6ea681e67ef8e1669d96970420de6620e10d43adc93b33c7613a33e4b9c1331e",+ "src/adapters/cursor/effort-map.ts": "620b1369e1594445753f5c9c5bb2c486b12e7fa5ee4f2a29d3be23a2eaa498c8",+ "src/adapters/cursor/envelope-echo.ts": "837f3742957fc5b931dd489555d4b24954aa2b5caff938ae6f870975601aaf39",+ "src/adapters/cursor/exec-policy.ts": "737d62a9b4006ccbc54744472614f6f557d02738aa7bf525ec70c1abeadd5350",+ "src/adapters/cursor/framing.ts": "c6fb07b8df6c1b7282be52e8bf34364f358d67c7cedc174a32011011063edaba",+ "src/adapters/cursor/gen/agent_pb.ts": "819da889962a89f5b761cb14e76786f6e455e85bb49f59fdaf6778474b106012",+ "src/adapters/cursor/h2-pool.ts": "53bab2c504350ce2a985553e6e391a61bba900bb0b58d6c99675eea1e0c1c84e",+ "src/adapters/cursor/http1-bidi.ts": "351a05fa5bab54709c5fcb1bbbaaae2974f041ea6033283b854812d97df53c7d",+ "src/adapters/cursor/images.ts": "c09bc18020e3738162e8f26fdbda05a722dc493cd72ba74988e94f68925cec45",+ "src/adapters/cursor/kv-store.ts": "9699c3b4bf5c61f42f2a6653755dc46d662513b728e0e284ca2b46a1006c57ed",+ "src/adapters/cursor/live-models.ts": "14952cb90aff21691c8690dd227ca9c011e8eac945ada84886aca6c663cba827",+ "src/adapters/cursor/live-smoke-gate.ts": "717f742f7a8b777826170075d28d863601868cec13fbaf0464ae88a8dd985b64",+ "src/adapters/cursor/live-transport.ts": "cb419678e11b57eaa568d1b54f0263042b8967cefd4b9c701988a078da0dafda",+ "src/adapters/cursor/mcp-config.ts": "3ef083c37f6488881bf7da3ca8c0b6bb6a4ccb71d26231a07fd039c023df6468",+ "src/adapters/cursor/mcp-manager.ts": "be7b78c97606b2138fae0c4dfb5f5dcc71c17b93d7619a1bb16d5a934f92d587",+ "src/adapters/cursor/message-mapper.ts": "cf5ad7878ab7fd53dcd95eb57907a27c038ebdd35b01bca7aeb5011b852eb442",+ "src/adapters/cursor/native-exec-common.ts": "4682a899e9e626fc7fe7a481bf565468c44641d30414d2e3de560c703ce090b8",+ "src/adapters/cursor/native-exec-desktop.ts": "c319207f8ee40747192c2b06fde2f08e923cd91e258bca1dc5359fdcc0b98e66",+ "src/adapters/cursor/native-exec-fs.ts": "725ccae2f8573ef591e8784a0b3687d0049a1e493330dd479d5edec74d4a7e87",+ "src/adapters/cursor/native-exec-mcp.ts": "ee3707def79833823fe00d018da7a7faf3465a774f85965c89a38f74ddb85d15",+ "src/adapters/cursor/native-exec-network.ts": "409b8530732516b092728c0fd69ad9a186b7f3f72599bd2f46e0fbef263e9359",+ "src/adapters/cursor/native-exec-shell.ts": "c3518140081f1757942e551397506bab5516e8f4294a0e6eb12d6e023879203e",+ "src/adapters/cursor/native-exec-tools.ts": "3e19b4308c9fd12251f1e22e88f474fad16ca5d2f8f3ba7785cc7353ac519b16",+ "src/adapters/cursor/native-exec.ts": "dfddbb2feaad03147a1d1bbfb5be0e0b17bac60c19d005ae6d790211af2cf5cd",+ "src/adapters/cursor/protobuf-events.ts": "e6b77507b05bc21880dbb4fb158f53dd8ae81af67d4aa6af15f94f98f5208eac",+ "src/adapters/cursor/protobuf-request.ts": "c5d009802d7b1154697ac6a3823cff3cf70e07db2afbffde484bead322af3e74",+ "src/adapters/cursor/request-builder.ts": "34e9cc4365d4740dbfb8edb8e7d16f41725f2f92b3c0acc6ffd6dadc2bde67a9",+ "src/adapters/cursor/thread-continuity.ts": "56972b722418dc54dfb58136abd3d36fc87e630dc6f3e7c87d2a569c54b0bcf8",+ "src/adapters/cursor/tool-definitions.ts": "3aa052f5b70fc54ae59f78ba23e87b8a7c8f1e83f6ed60a31e359a5bcd3baca0",+ "src/adapters/cursor/tool-guidance.ts": "9da31c647045af018fac2601b378be902665613bf17e3f91fc45794367ec15fe",+ "src/adapters/cursor/tool-naming.ts": "47f7fb1de1e4fd06d2b29c0811f472cd3380dee0b633d646683dcaab5c959976",+ "src/adapters/cursor/tool-result-normalize.ts": "751e8cd8da026ff7bb4cf92552573ec7563e7acd063719ceeec73898ee4eb31c",+ "src/adapters/cursor/tool-schemas.ts": "e30dea6deed9ce06d3ecdc51a911137800a36e5ada8687f8c653cc85bbcaf2f9",+ "src/adapters/cursor/transport-retry.ts": "c0b339bc1edd7406a1b388cdef5ecb399e915b2a88ed639e7c1ab3635f2cc9dc",+ "src/adapters/cursor/transport.ts": "91d5379a51e358becf030d2946cb6ebfb8f3ad775da53ce29986e25f2e11f309",+ "src/adapters/cursor/types.ts": "4a14f2f57a8f7801e1ef5b316e6b4c68554761008ae1c6a6831eafa9a9d180af",+ "src/adapters/cursor.ts": "87d46d80b3a6960157d36bd5c27d3296b44646052bc9d763f74e68ec9eaaa5ff",+ "src/adapters/empty-tool-output-annotation.ts": "cd00654218db3a30c451608f953256148fa288020e6afb6e4275280b1dcfec8d",+ "src/adapters/exec-tool-result-normalize.ts": "1db5452bb42c5ba4ca1379ba82686b80b56a1611dfab6531576c6b151aae217b",+ "src/adapters/google-antigravity-replay.ts": "1d730dfea9db3bd42a0718cf0264788d84a73e04716ace61d64ec9369ef7ee20",+ "src/adapters/google-antigravity-wire.ts": "5865b21ff20181703f9e02091441902f5a87bd141670669286f2daad0dc4261c",+ "src/adapters/google-errors.ts": "d3f5cea26f2d8455b09af6fb2c21410624d3d600e90ab6544e13ae6d7b1aa2c9",+ "src/adapters/google-http.ts": "bab2485fcfbf428df507e66370b9bd9508ad3025e25e51e950a4020bed094c1e",+ "src/adapters/google-tool-schema.ts": "d5bcf65418bfade8a3d98a26c7ffc1b657f943eca0e44528e8817a9ef4f5e4ac",+ "src/adapters/google-truncation.ts": "9e8d317ec04b6c11314a3a47bc14cd57c4e1f8cc5bbe7dbbe91a1e787d1928a6",+ "src/adapters/google-wire-compiler.ts": "23e981c264293f5c6d4839f6e14fdb1428e37af8f91a918ef0e92fd8ffa4637d",+ "src/adapters/google.ts": "e56351e4bb69809687928ea9b72808435746ef9255637cc87b4b93dd82cf726d",+ "src/adapters/identity.ts": "21a147b96b5c5d6741d1b793be71d8b73944649f84f0c4c351cd149d9bf9e562",+ "src/adapters/image.ts": "22050d49c59581ab4a3db7d64c73d0cce3eed2274bdd9bd0ae4a78fbfdb4e71e",+ "src/adapters/kiro-calibration.ts": "7e1a7d70d107f30a8824696ab6de78234a5904a0f815d0c2f0dd1bc76818db67",+ "src/adapters/kiro-constants.ts": "c0263c63a34d8e1e49c321c1c101f009a622d3e9895b16ba9497cda40ab21031",+ "src/adapters/kiro-errors.ts": "9ea0e3cdf55c307453493e0e2c3276f1efd4bdd60769df11a1d5bba49c02931c",+ "src/adapters/kiro-events.ts": "5db4ca3ba61f97075667acde07aa686389ee9534bb15d48b742f5393d06928c7",+ "src/adapters/kiro-images.ts": "3eb03461d85d2f11ecc53870a953737ff2836b093e4bd0881b5d4e0b40ed03d7",+ "src/adapters/kiro-retry.ts": "8d8ee6d26ffb95226978d4191721b32b4cd531f502833be42aa66d9f40c9a4df",+ "src/adapters/kiro-thinking.ts": "c7093dd20dc16156aee4d6a37de0b71f6e646c09f2ba99be8f3c6a388703a981",+ "src/adapters/kiro-tool-fallback.ts": "2dd54a3b3f3c2abb3a6c2fa6d2653d6bb2e56d000be3bf4c64ec52763a10d69e",+ "src/adapters/kiro-tools.ts": "e95c33d75f4562eb3245de75c384a1a071d775db5c340a2a503a5b0a5d9d96c0",+ "src/adapters/kiro-truncation.ts": "3dccd7bce574b3a9a57ef01677e7354cc5fa7db7671863434afebb97626bcfaa",+ "src/adapters/kiro-wire.ts": "3e50d4e073e7b5b61794231e9d3bde9437539456f7b013342e65c08e5858f003",+ "src/adapters/kiro.ts": "8ff6fa8a255eef161b927f56ec41d45cf8998fddd997010b1ef06f412aec1b97",+ "src/adapters/mimo-free.ts": "939c111fc90abd00e5415ea3a47e5c567c64de2ef444d3cf89f6179f4764c501",+ "src/adapters/ollama-native-url.ts": "c7c6dc000c29b41b67b3487f35eef89a4861c65c82abeca788ea168f175c97d0",+ "src/adapters/ollama-native.ts": "1ad4bb11cee29d6f428a4da3f46bd9957791a5524a7ef10a9ec99d4fb3534f58",+ "src/adapters/openai-chat-url.ts": "3309bcebcf21f35e5a395187a06db326173cd0a7a652a5ecb8abc20713eb8f96",+ "src/adapters/openai-chat.ts": "ff1f2275e2f45e769a5f4e2e6e79445fec56950c86006f2a98fd7bd8e6bfc016",+ "src/adapters/openai-responses-url.ts": "ff38228d2033b9f73dbb011b1d5eb3ac09795519ae8b57958d7d8f6253b4d5e4",+ "src/adapters/openai-responses.ts": "5eef85b5c6a109bc14bc324dca15bc1f9292445614673d331850ffeac80187e7",+ "src/adapters/opencode-go-additional-tools.ts": "42090cb27e20503d3d6ad0680b1a45b918b19d878c2e6db6ed031ca57f17c1ee",+ "src/adapters/qoder/adapter.ts": "dbb669e2112f342cafb470ff8137a93655699cba724274e4164c38a5e6bad494",+ "src/adapters/qoder/live-models.ts": "09ac2d7c66b9fe73e5f28a3a93d6f62065d6469fe50a9c223e39821e6f4bdddb",+ "src/adapters/qoder/profiles.ts": "d6b96f7dac75a4562d9b01653b44d32138b2f1d06a5f2e7a63483d5c94cf1060",+ "src/adapters/qoder/scaffold-guard.ts": "67f7a11f743ae512f72835818e2c029fe561b98515f3537f497b023c32451e58",+ "src/adapters/registry.ts": "c7f86f18831c56b4751f58eb7f131831ca8e7054b6663885a58944682c11bac6",+ "src/adapters/responses-code-mode.ts": "40f4a75071c5eefcdbc1070811f99b29bff24bcfc5a1bfb709f6c302a5899cf1",+ "src/adapters/responses-tool-schema.ts": "11bd2246eb174cf197af6885c96565407f1ab53b7782b9cd27020a65ac9b192d",+ "src/adapters/routed-agent-messages.ts": "3617b10e10db2ebfd573a479f7c345c254c49f3b139cc2d0290011c007c05c8b",+ "src/adapters/run-turn-queue.ts": "31b12f11c9c35f3e499c418bf943762f299755d8a68d7bba9fa9371fa5684a43",+ "src/adapters/tool-call-id.ts": "1426793f965af96c96e297d5ceab7a3dcb36bc19088f6407f89f340b40e94577",+ "src/adapters/tool-catalog-nudge.ts": "aae87888360b7a8cb03bd13ba6a286ec8fe9277c6418b05321027e57f97f4745",+ "src/adapters/upstream-http-error.ts": "4875e77e46d96131e7a3e6c0feb15a54ffcb3901efceac2360abe28b7a0f414b",+ "src/adapters/xai-schema-analysis.ts": "7bb784364955564052ca8b237782101a9e0478432c2ce231a5cdd0cd216fd157",+ "src/adapters/xai-tool-schema.ts": "f178d9f9aa7d33fd98c2dd034d6c180773fc2f05abd6b86371a678d9fb16bf63",+ "src/adapters/xai-web-search.ts": "6bbf215df9072dd4842eb0dbea27ad8de0aa51669f23027e0c064e6597f0c383",+ "src/AGENTS.md": "11d12d7a2a8e2c4ecca700627fcc114c81d1ec12d8faedefdd783c15f16577c1",+ "src/bridge.ts": "b42e66e07ca87deabc7711aa4272009c4dd1dfe9e9d065430e43e2fa14fc90c9",+ "src/chat/inbound.ts": "d30d857c807402c026e41b3b64c6706e301ab8328d59df323362767cff8aae4f",+ "src/chat/outbound.ts": "a7912ce4fde3601115b1bb3b92470a365136ffb5b8f346cc871cef72bcdcfe97",+ "src/claude/agents-inject.ts": "df72b3ef12fb989bd87b41d9f4c9c512bd17fdb510eaf907a6ea414387847cf5",+ "src/claude/alias.ts": "da8ab081e174938525d73d3e4c87b788f17404746dd1bdffb2261b209598b4db",+ "src/claude/auth-detect.ts": "6a4382a820a42fd9cb5a9cc7e150eaebc4fe70bdff7883c4e519c1756f81a009",+ "src/claude/auth-mode-migration.ts": "9452420e404aed3fba631efeb1e2afc0caf626bf05b839d658f4bb6bf3a824d8",+ "src/claude/auth-mode.ts": "c2850d987754a58d258c9199901ec71634e3388498b229c09fa622cee65f81ac",+ "src/claude/compatibility.ts": "cc28522a80a180a922dc63ada519847687d69578af28f0d4431ceb0983b937e3",+ "src/claude/context-windows.ts": "c400f4b76319ec14855128af40fe52b60d31d217b89e291641522a51d2583d97",+ "src/claude/desktop-3p-guard.ts": "4f072b87224221b777b8faf8e302da9eb5e985daf78e6dff566a05b506fd8cbd",+ "src/claude/desktop-3p-library.ts": "4e33c8a4e640af1d9211f1ad3bfbb465af92f3124d8f417c47facb6483f7a481",+ "src/claude/desktop-3p-paths.ts": "a2416122048a269af4e1a57edd0d300af7d182bf8f6c145df19eece06b809836",+ "src/claude/desktop-3p.ts": "283abb1f0162e1d60b4dce0bf5e52fac8ca6fd7488abe9eb4dd6699a270fbb16",+ "src/claude/desktop-discovery-inputs.ts": "87f206d43212f41dd3004808a8d6bc1685e1c6f84462751b86f0d9f0583fcc79",+ "src/claude/desktop-health.ts": "5709154ad0b0677db31519799b6f2c6e4fe6aaeacebcc69a13a990020d25545f",+ "src/claude/desktop-policy.ts": "075b2095e007b55a9a4c7a5daa88cfbe7d4b67e31beca8059babec2dc19c1adc",+ "src/claude/desktop-profile.ts": "85dd31e72ef6af65ed825427c434ffb421190e08ad38f00d62a37d220f35acd6",+ "src/claude/desktop-remote-store-artifact.ts": "57d3f1185c86f00d11b6ea5ce3f6d0a18f27cdeb616f4fc6c74fd90d862af683",+ "src/claude/desktop-remote-store-io.ts": "5a770bebad77f986396253f708047b77febc301114fbb4bed73d85a8827b0e51",+ "src/claude/desktop-remote-store-state.ts": "f1a5bddc8b5a9d41063052c109009593c1aa869bcd7991dd180a80a686dfb0c8",+ "src/claude/desktop-remote-store.ts": "82fb74bd22d79b1ef5b36a1be7b4e786d008839f0196fbf94c1e1e09fc2ca235",+ "src/claude/gateway-cache.ts": "d800fd00f607cdfe8940b3f12f104645fc786a03dd20f936276471f5731471e5",+ "src/claude/inbound-content-options.ts": "5bd23dd382a52ed889ad5b42535f86cd214bc35617fdbf80c8daa8f34a4a763d",+ "src/claude/inbound-debug.ts": "fe1951e34e834ef08c2fe9392f72ff67692fc0bc3beba5e3bad83a27ef2d6514",+ "src/claude/inbound-model-options.ts": "b0719316cf26e773af74e486892349c64945754c7d680b5ccd3ca773d2046c9f",+ "src/claude/inbound-records.ts": "e9d4502b3be672682c0728177eb3423bacd27f0ef8eea27a3eee6ed96ea44cc3",+ "src/claude/inbound.ts": "c1717eeef2fc0a20b36e5b12f5d32146067e43bd8795b3f78fe9e27985dd4617",+ "src/claude/model-info.ts": "ac4dd859de82c6f6033c2754faea80a15bf538f284e19be673098f388a90aec7",+ "src/claude/outbound.ts": "363bce625cf0933bc0cb12b6352a15fd13cb5c8420e7f01e5e9d3ba4b4500486",+ "src/cli/access.ts": "f8a3be70b2f1697e546b20b1c5e1a8b79429bd2e94a09c3ff0ea8ea0c45034e7",+ "src/cli/account-api.ts": "7d3cbd39c4044cebe42153c9a094e401ec20937b49aa801e335f9de0597b25a3",+ "src/cli/account-auth.ts": "0c001076b7f2fbb9617e14536c826fb0505a4bfc8eaf84ddd24b68edf70901a9",+ "src/cli/account-catalog-refresh.ts": "fcca845b4fbd3732ae70f608a3bd577e62341ff812d43475bc056cc5baab6b48",+ "src/cli/account-extended.ts": "c28be00939345f17711f12b04963dece4503be36a3020cd65fb021d4b41e98ab",+ "src/cli/account-main.ts": "b9b2aba9b8e43bf73b6bc69d183b971ca626077a73a1293febc07c74bd54ce9f",+ "src/cli/account.ts": "03c2bce1515d967c1e72b487aba92fd927504412843f2f9cc33d5710d1168200",+ "src/cli/agent-driven.ts": "4ec164d37c3953c43078de3123747ab17491e3f46e2abfd5e42fbba63fd5fadc",+ "src/cli/agent.ts": "2f57c73c65010955b15d62638781cd6f211639294d06f921373c5e8e6c4bd692",+ "src/cli/alias.ts": "ed2d470ab353004c32d4e02a41b6a74da845d4e17c451692e9627a1b3e9f601c",+ "src/cli/aside-profiles.ts": "02de4b9bc05b065fd444ba84d6cdb146a310121ae87873f7982b815094ca244d",+ "src/cli/capabilities-command.ts": "c1101d205b90889f5b988d29976e6e69eaea8a964be086810e63544c38e69065",+ "src/cli/capabilities.ts": "28cc41a07ed7f806f044e913615109964c2658c383ec86c3399308a1178c32b4",+ "src/cli/catalog-prewarm.ts": "e8361fe04f7f97615b6446e91e1e11b0372f90e14cbcebf7ab5792949e1bf266",+ "src/cli/claude-agent-startup-sync.ts": "15bcf2187a9e7954275625d3c79ba806092a3c8bacff5673cfbb618e47f51857",+ "src/cli/claude-desktop.ts": "98378d62a136cbcfb7def05d3f78e343f27d28e40a9f1e29da2122e73effa607",+ "src/cli/claude.ts": "c09ca9ae9e10cfc332b3513e25985815a49ad4bfd4e3a79297c9dec3d4af87c0",+ "src/cli/codex-cli-update.ts": "124ceb293db0bb6b011490f61303d8c001f54e9b7ff8afa809ab953decb870b6",+ "src/cli/codex-log-guard-doctor.ts": "e6a62a5c9cbf65e900ec3523598a225f5ccd1238abb8da9cae232d60da6fdabf",+ "src/cli/codex-shim-autorestore.ts": "cac51c864181d9e652a014041aa1cc3f82cad1a2b528b28461aa01213f109cba",+ "src/cli/codex-shim-readiness.ts": "bed0c8348dcd5440734cf003512bd5ef8cc0283e1cbacbf0f7950983a34ba7e2",+ "src/cli/combo.ts": "8d238e67943c5e28bbc55477db6051fda6dd29ca2b8e3019292282c0d6a4215c",+ "src/cli/config-command.ts": "365d96e1c9397fc9199cad1eda7c68622c52ee5a81394e78d522d9c9d0da0b5e",+ "src/cli/connect.ts": "3b9dd9040d7f748e9b214dd4e1e653dd1b7494c44d18a9d5284be9bdfc3465e5",+ "src/cli/debug.ts": "5a9506da313a5ebd5778530935117f57a54f90cdb496130e32516fb3d1d576ec",+ "src/cli/dispatch.ts": "e3d2d9f3f58a65c4580de16e09d4bc9e79a8d8e67ae466e20b328f1c09faaea9",+ "src/cli/doctor.ts": "fa6a405bd00e4d00de038d3cffd99656978f836a6bc5135dcdeed65c7917d18a",+ "src/cli/effort.ts": "2e13a088099b17922727ae9e728b04b3e82a518470490f5100ee83fd8f2fd346",+ "src/cli/ensure-desired-integrations.ts": "e18c3fbd47c66a46ea7f16b7584a6517a7c3b94741208f0ba88e9420d0c7c956",+ "src/cli/export-command.ts": "0022d2900c3e6120070873a94d4ea794880b0a00d94e9072529e226936e59823",+ "src/cli/gui-pair-client.ts": "bb889bbffb9df45d4140c39ec99c4f0576ac5b9fb6bc081cc7c33729dcc8fadc",+ "src/cli/gui.ts": "18582e745bafcccc268061d02cd92c2d550270c3bd0c93b00d987c5e9be916bf",+ "src/cli/help.ts": "71455a3ef6bd2c11392cd96ca03e1ecad1c5c4b9065d0b77b58543c68853f066",+ "src/cli/hub.ts": "ec5a6e08002aec1d06a0ce0908da00e2983091c5975ec738fcac758a2def41d9",+ "src/cli/index.ts": "8c601bd8386f856272e55b6a82a6f8948409ac9e6d40bea208063939ee499153",+ "src/cli/init.ts": "0283ef8c97b467219a8e9f77015c18c83023c7068b445b3e29df7111ac18fdcb",+ "src/cli/inspect.ts": "8d20a779a72d5b17d73d13e33b790fbb62e3978823dda439766895c0818a8b99",+ "src/cli/integrations.ts": "391860b07788176406ec78e7e4824e8b31113b1222bb3ebc73f358e3d6870321",+ "src/cli/interactive-confirm.ts": "9fdc081a5f8e7a8c74612371e044f34054151a20b9692c0fd81a2bb41e86f9e5",+ "src/cli/lab.ts": "1a9b3f10824fabd4c4bdb192a9a2dcaafd3f3aea6b840f46330e2202906aeda9",+ "src/cli/launcher-context.ts": "402f4af60b0e79ca4f7791fe460ca86144f753d8a9a2e5906ed152eb312c9625",+ "src/cli/minimax.ts": "30f17ca0c9a92a289a2fb2ffad1e42c8efdadf72cbeeacb9fb4e3bf45de22122",+ "src/cli/model-selection-guidance.ts": "4757438a0bfa2e6b3a6363928a5174b2d1c116154f06d3478fd6e6c57b11b7a0",+ "src/cli/models-runtime-subcommands.ts": "53bc90b785f6a1d3ae61f0f35112eb585d5dc59eacfd797b382d0f81edba479e",+ "src/cli/models-runtime.ts": "ec3a814a6ce176bf347c3d6ef869418bf04e9b450a54c932e2f94e0d573c4ffb",+ "src/cli/models.ts": "c991307ecee7a91693e4be1c6be08088ff1acf167a17e9a712a2001ee9cda528",+ "src/cli/observe.ts": "7db16ad49b1992c5cfe8101438fefd007c87a9c4e9f99c31a4b860d8fa829875",+ "src/cli/opencode.ts": "1b319ec1be28bee8645a2ee55037fdf5e641a285ed85bb66a1778fb86df6cbd6",+ "src/cli/provider-runtime.ts": "c0ece5df25922cca1fbe907fbbded74a13ebd6150c0b6930bfda869a2fa320b9",+ "src/cli/provider.ts": "fd8e3e0d4cb1314df08a1011bc34535b477006a993937b6b72f4fbf4156cea8a",+ "src/cli/ready.ts": "644005f263c4a0394aac287c5b448b130588afc733c8707cf8d7490bef003e41",+ "src/cli/registry.ts": "49c01d4bb11c55c64bb5ca157ebf22f551d6e528844c13ed30255f38e6d6b3a4",+ "src/cli/root.ts": "19c8d84e3d829d07a9ac8e3115e0cd1a3f3fd7d04416aa8a4754a057104b1ee2",+ "src/cli/route-policy.ts": "1a37d07d7e2dd1fadff66a445cf3b1cde0f295e3bb4664a8c40f25a66110c865",+ "src/cli/runtime-api.ts": "7339dfb8b0dbb8c3a5e70924efa79f5d65ac62ad6065b8c9fe3b5ac6d335dc14",+ "src/cli/star-prompt.ts": "3ae058ab15fcca12bf3cb5b332bee25bcaf9fbaaf5ed66f5e021c6fdeb9c677e",+ "src/cli/status-oauth.ts": "9f1523a644083c9371b6e8d95b4724ecc12ef54338991648a8c37183a1bfa86a",+ "src/cli/status-probes.ts": "221af2a9dce6ab1718b9be3b9389a293f12f2c61e397bf5ea7191c4d0ae86566",+ "src/cli/status.ts": "3889606013b5b338fa8977c749d95112e66064318d49d9a53eb3f65b8e8c5da9",+ "src/cli/storage.ts": "38d324645b27e1595e9cc580f9ccd2d9ef99431c91294235b5cb3e4a85790adf",+ "src/cli/system-command.ts": "660243bea52a47c22c22ff564ee22fa1c7099dec6cf9826faf8b9984e65dbf6b",+ "src/cli/system-restart-client.ts": "7171fe2e431fe6aae7f3b4c8df770c0b2ae6b8f53802cc98f8197166221b12c8",+ "src/cli/tray-proxy.ts": "35878717b3b9c9e9d7793fc88a72ddf21d7b2c9b41c3a6dd12f5bb5d5343a6d5",+ "src/cli/uninstall-client-state.ts": "9bff03c801a8de750e412c0d990f46b5a2f45fe31e82e7760736c2b240ab8608",+ "src/cli/uninstall-plan.ts": "786c9f754b76a8a7fbf11a1893f8eb9a228138e822eee50c21513ea248ece34e",+ "src/cli/usage-report.ts": "938874eb940d87ca0a6e1a0642913a79b1fa22b0a265fe874decd2573f58bc3d",+ "src/cli/v2.ts": "bee42074b6cf31c207ce9c08f6d3bf68a9c725dfb39df9abdea09e45fa25ddb2",+ "src/cli/version-skew.ts": "368b7708202d164fb5752478274244fb3e6992e12d51cb49ff78508ff2eee191",+ "src/cli.ts": "61296f41b700c01d55eaa784f1a19f889b1fd511fbbe703b8aa2be9cafdcd780",+ "src/client/catalog-compatibility.ts": "e2c0c1eacc25a9eb2dfbb3655fc30ca3cae7eb21c482f6743143ae7885b15ab7",+ "src/client/connect.ts": "7956e3cd0a06d28a6f4a33eaad60c883f5ad2953b75909418793af69b6cd15e3",+ "src/client/hub-client.ts": "969c0437a45916d79c5848bc3e6bfb9992415ab31bbd6b7663b0611fbc8fb809",+ "src/client/hub-relay.ts": "8a5cb8879067b0cef3c63ac05a56d69dc6db8276210fa91f8b98aa9ae02a17dc",+ "src/client/hub-state.ts": "85516b2faf23c9e6f9f4d6fe805288b12e416d4c8568153b991ba6d782a8e300",+ "src/client/lifecycle-lock.ts": "e7ecce111807b7575a7e472d09c14f68e99d6f0ed86f89190d4040e106ba3ba4",+ "src/client/machine-api.ts": "489b2dcd72030876eddc61b312c8b553cf9c945205e38a54ad6eff7fbdda8bc4",+ "src/client/machine-auth.ts": "8e1d7a5cf5e6954017c39a5059dc11c343fb67d43425965d0582fb72911ed37c",+ "src/client/machine-listener.ts": "b598e74f4a48e018c691d41f3f32f41946553e43614e1dd632d861065942e8fe",+ "src/client/runtime.ts": "bc1e3fd00a620ccaaac4dfd7afa92c33e7b53fdabc56c00a5bd9fe35c80c55c1",+ "src/client/state.ts": "4ea17f7d26cbc18bf2373743027d71817d23b8b340d6a42147c633a4bb00ed10",+ "src/clients/aside-profiles.ts": "a02f8f25268d3a2eddebd9cc70a9a021b225e0369b00efa073adb08b8090276b",+ "src/clients/config-export/constants.ts": "14c082d09c72a74cb9067173bdb4074286cc2c006c4308b9cbd733ea86a10e44",+ "src/clients/config-export/contracts.ts": "0e4e71d6b4d38e3a16a81b77935403cff7dcb26027aee746bc3c138a1e6395eb",+ "src/clients/config-export/dsh.ts": "538adf385050143949170a38886d0ba72a7e5eca3b1ce4ac2c1b9afc56b2cb8d",+ "src/clients/config-export/fast-models.ts": "1e7f22c859427c080d4ff853424299e146584e68f8e89f10246e669297d7533a",+ "src/clients/config-export/mcode.ts": "279fabec4adb06a2b92d1ac334d6e235b052e3cc5025cd87ed096f6589c20c8e",+ "src/clients/config-export/model-metadata.ts": "4ff3d8a612790028d3ad680a6aedcaffd7c80fcf0b4a1fae7b07b0d5eaa96236",+ "src/clients/config-export/omp.ts": "a770072e1818ea4b6fe2358f65c83700a6a17506c14994242427d41046515bbb",+ "src/clients/config-export/raycast.ts": "624cf5c2acf9e5ad9fb2da54e8a3b80a6ec3c2dfc0303c1724497788d51d222c",+ "src/clients/config-export/zcode.ts": "256aa37df1a6a9b2e9cc7f3d619c0a444574e1c32689f16d8ae0cc962f6b4485",+ "src/clients/config-export.ts": "8cfffac81b2efc1e97f80d161cd98452730510528b635154400310f3541c8291",+ "src/clients/model-presentation.ts": "ff7f94612422eb62be505324c4f3c40174e3de28c8644202094972addb5628cb",+ "src/codex/account-id.ts": "beaa9a9fe8a2588cd1f98fc4c4d16b39b3f224dcced1b5e1c3dd10eb8fe5c8a3",+ "src/codex/account-label.ts": "b48a6a2385a8da93679bc8deca761d9b798b7483d0b768553800371a5499a29e",+ "src/codex/account-lifecycle.ts": "96f6566e7e5b6a6f799c26f0affef7165783f3b9243a2659b9f5cfbb9a6de904",+ "src/codex/account-namespace-match.ts": "4e59b699166bdbdf7d8c2ec0ca1205b83e7d42477147b45adae3352d8ed39656",+ "src/codex/account-namespaces.ts": "7e6bac76b6695e8dd697f96a69d1070774b06aadec587dfafbee589a77d7b99e",+ "src/codex/account-pause.ts": "77ae91684c998d7e6f41999939ad8e09e8cc8415f3e0f0d87e89309c55552b71",+ "src/codex/account-priority.ts": "d9110914b8f146b9f58890d05fbca1316e67c94b6468285480ce574fe494c387",+ "src/codex/account-runtime-state.ts": "a230c3d8df1c937f1a91f7e88435e26c558c9d03f6d2737219d8ff6d3e2105e5",+ "src/codex/account-store.ts": "e94ecaf554d2e16f2f65bfc0a3f6d0e2f63f6c8b51b87fe3803a76b64c2140f3",+ "src/codex/account-usability.ts": "1fc3254300080dd91811a631f70d6ddc0918f914976a8ec8e7895866d3985e03",+ "src/codex/admission.ts": "4578fbcee3cf4367c300480efb2aee2c230bc7776d528636923784c8534b59d2",+ "src/codex/affinity-debug.ts": "2acc776e0979556776e132ef4016a7e4dd99745003230001f2877dfbedaed97e",+ "src/codex/app-server-processes.ts": "23a816702a01f0a694cd1592af5bb90e600d4423285693854f8de9c4f1c41ff6",+ "src/codex/app-server-restart-service.ts": "975b84bd6ce1b51e14081b44904605fec298bf386165466f8197570aa6cb2b27",+ "src/codex/auth-api.ts": "e8b8a012db657e93a456083cab8ab8f72aab630289c5951351d528f5fc13632d",+ "src/codex/auth-collision.ts": "2217561c3c1df33c8e2c615c9f457d5b0c051a3bda94db22a8a1c06b786bbde5",+ "src/codex/auth-context.ts": "5d70de8e56d850f66f0659dea39d6d7591a1ec83f1b4c9337edca3b49e11146d",+ "src/codex/autostart-health.ts": "89a5e5d1bfb7397f2951d023af7298e2faa2e8aeddcebbd0c346ba278aed904a",+ "src/codex/catalog/account-models.ts": "d1cfc4e3e7daa333d6c505a654fb0be3276901b7e91833db680c2daba0b07c4e",+ "src/codex/catalog/aggregation.ts": "6b0ebcf21c86fe5ae0880ed51922f487a3baa647a3d58e15b8f6a8dd48529f69",+ "src/codex/catalog/bundled.ts": "2f78c3050a278e8d32dec332e504202339b4c3373ed8ff1d9c824d5bed443af9",+ "src/codex/catalog/effort.ts": "e7ab404c696e738814ef95575581fe73c1a84621b9dd64e28b69d3beb9fd1226",+ "src/codex/catalog/filesystem-evidence.ts": "fde4b84ebda1835a10b753ff58b9c161127ef8d75dd3f73ae89b650e747ae8ff",+ "src/codex/catalog/kinds.ts": "83803872b38d618f7d4f75ac6389cdf36de49c301d49cacc44f1a32f0ffe1f7d",+ "src/codex/catalog/metadata.ts": "4e584b56f883d62ba2ce037d1cab618699f43fbc80b09f18c2ed56e48e209550",+ "src/codex/catalog/native-models.ts": "d16479347f3f2fb35c71fcccccf7026de7c9d308d5365cab2aae9d721751c49d",+ "src/codex/catalog/parsing.ts": "f06a627708ab952feeaf550370b464449f7fbdaa61859a00c2260651b20a8c31",+ "src/codex/catalog/provider-fetch.ts": "fb45f0fe5cf54f0e6c877d5c3b83aa90f1619f0f00f597f1cae72832a849cf2e",+ "src/codex/catalog/reserve.ts": "0bc37836efe667af075bef728a62708c30afd080036f4b020112f9a54feea9f8",+ "src/codex/catalog/sync.ts": "60668bb7d7764ec3fbabeea3efdfcdbd4444e458922e01c714a579c23151f175",+ "src/codex/catalog-admission.ts": "56409c9d41b58e990a35f8b4305ec58ff1ffad173e2a43a7ff0e0b671546b2ba",+ "src/codex/catalog-refresh-status.ts": "8e908b7a42f010b16c00fcda1194ec35fc8a6de6acf7e53ccce50df5238555bc",+ "src/codex/catalog-write-serialization.ts": "462e8fa4acff845e61c6498d91cb0f84549b92f0893b0fcbe49e0aa7673d9fbe",+ "src/codex/catalog.ts": "e15f0b3c3827591cef846b255630586867703f0a1f37f846f0815f45ec2fd655",+ "src/codex/cli-install-provenance.ts": "de2f9e8ef6910ac6863b50ac3b863dcb94ce727904461f20642ea6bf408bbd33",+ "src/codex/codex-write-lock.ts": "b879bf9247011489692a1dab75de2d55673919d133ff6d5231b73be98e80cbac",+ "src/codex/convergence-types.ts": "2b4a5f91f23cce67a616851c6147e67fcba3b08cbced0357eae45c9075da8475",+ "src/codex/convergence.ts": "64323a64fc2ee76e6daf424f6b8632eadcf0097a4ebea9b3e3e206e9511901dc",+ "src/codex/coordinator-doctor.ts": "8b96fccfcebec924abf6b1c03bb8ef17f6e89469fb6f556c1f0d517654eaf941",+ "src/codex/credential-mutation-epoch.ts": "fa23b49b0c53eceee61f0bcc5d74685aa5052031cc40e2c0cdab6b72bd478b51",+ "src/codex/custom-model-catalog-migration.ts": "eb6c1420bc61b27c67772255a20192cb94605c988f6b597608e69b6346464c77",+ "src/codex/data/upstream-models.json": "16966988a8fbcf64279202b9f03b324b95828966b76c8348177b3c2067394913",+ "src/codex/desired-state.ts": "a8bd52abd84b852beded6aac4fc243d115c114dece277fab1cd0dc97d8e7ead0",+ "src/codex/desktop-app-restart.ts": "ba997ce741bae049697337ef7687f88e891a204b3bb434c43860247b26c08c7b",+ "src/codex/exec-invocation.ts": "bbcc07eb26ce53fb1b1447d2351b4122e0314cffffcff85ffe5af956a70da1ce",+ "src/codex/features.ts": "2d2e3ff6e5c0cddd31188fbe76f38c5fc50bce83b0800ff3a44fa36a2362aa7e",+ "src/codex/forward-transport-headers.ts": "02a644118b534bb9454f4b91efc2513d86730f7e36eb7fbd0d133c5740aa4b3c",+ "src/codex/generation.ts": "16cf25ab05fe2b9eceb146304ed2f6f4c794fb375d8258f92b638c7203cc81b1",+ "src/codex/history-job.ts": "de26dbf66f1829fa414f787507256e1cb2c9e0977c8de389445b27546d1ab462",+ "src/codex/history-lock.ts": "d927dafdcc839ae987ad95cf08ae7b8f04bb8ba4d0479554b712fdf29669304e",+ "src/codex/history-manifest.ts": "92431ddf0d11bab671c89a4b99e86049b1794b7ac9f07e7ba2709508d349cab8",+ "src/codex/history-migration-guardian.ts": "d70c403826ea2cbc87ee7d46987ae48fb490bfe4e0c294ece94516a88629d96b",+ "src/codex/history-provider.ts": "1dd6c56defc42647592d5858147655fbd618368db0cccffc8234dd76135a0a86",+ "src/codex/history-transition.ts": "1b82496f6b93618d44431b8c0185cb858358bf5b6e4818b8089afe4f6aa6f84d",+ "src/codex/history-worker.ts": "f3dc8ad9a64af62423eac8d106e76a87d5f8be1aa098cc204fd7c8d7bbc9daae",+ "src/codex/home.ts": "5f2fc9d901e77e81de1d343fa53a451025f8086c5d175104685739e1f81a0a43",+ "src/codex/inject-coordination.ts": "cbd2a57300f6023727c8b4c89614749dd944c4717c5679c6aace17db24a70e59",+ "src/codex/inject.ts": "8c8378b52abcf487f7ab9f4881bd48b75b7fd4e02c160cbe3e8fb52ddaab6a04",+ "src/codex/injected-marker.ts": "e5f2ad207839ef89ee03db9866bfc9b9ba82494f4cc4ca3331d7595094d1cbac",+ "src/codex/integration-record.ts": "938f1f55ff89a91a607022ec25ba35d99b11f11e545e1ab1f3a23b13eff79585",+ "src/codex/internal/catalog-writer.ts": "d59f218683c102f5f629ee092a0076deeefb01cc8a20ecde13d197d3ec4a034b",+ "src/codex/internal/history-writer.ts": "1f6fe80a7865083fae3e45b27d705abc07d13051425ad890bfc7f2c162f3bec5",+ "src/codex/journal.ts": "609c26f8c9e2ab909858d3b01f0b800c17318dcca73b2b2d026caa40225af771",+ "src/codex/legacy-config-keys.ts": "73f3b948566595b82e739dc030c631062155b92cb7e8c219c1b665edeca94906",+ "src/codex/log-guard/inspect-schema.ts": "857d69c0cc4fdf70dfbfc44dbfbe93b53b728c57dd5561e8136efe7920d38ebc",+ "src/codex/log-guard/inspect.ts": "2f3e759d80e252e42ff29049b010df11de0d968b1c519f43eb19b0df55899629",+ "src/codex/log-guard/lock.ts": "b4ce32198272163541652b9864f892eeff8f681e7807de67c321c6c8901b4384",+ "src/codex/log-guard/maintenance.ts": "f11d9c7d774719715a8b3b33e7573ab09eca33fa4f57e853479a4fb5d8617786",+ "src/codex/log-guard/path-safety.ts": "4c967fe1e04202d44d2e23df99d0f8935350025c3c28e7d23546821218616e9a",+ "src/codex/log-guard/policy.ts": "ba282dba9271822d1778256f28dd4e8087f83dd282ce63dc06539e46db0da58b",+ "src/codex/log-guard/processes.ts": "a1388d9adfedc5918d0fdce83ae1f0577ede9a23f07789ba46ced5351a05edb1",+ "src/codex/log-guard/protection.ts": "92c1e86ec698bba7953f1e0d389383e76d1c7f05206d6beaa5f1eccc451e9b9b",+ "src/codex/log-guard/sqlite-errors.ts": "aa4335d71cf642e9b98b066af9204e6d66fff49a7f95b14c50b4c82abd1cce6f",+ "src/codex/loopback-target.ts": "74af07ed6c41b94c5da4e4302516d49668090e8a72fb47c57530081f32d7b7f1",+ "src/codex/main-account-cache.ts": "607388fb38415cf90bafa5517b6877ac4222313426cfaa9f6a46952487a67fdd",+ "src/codex/main-account-hard-lock.ts": "eb597c994ce22daac924648072448b0d41492724391c2023fca6dcc2d7d7ebdc",+ "src/codex/main-account.ts": "79c0217c922dc773f79a20c45223f3cfa33d96ba4ab0af8a25d17d9bc172aaa9",+ "src/codex/management-convergence.ts": "5334c6684271070a0e3d9ad6f23e1ee30de42525ac54511ee78fe16fdeeee028",+ "src/codex/model-cache.ts": "ae304d9f72cd1d293cce3e1431db5faff1f7d5680fb01fab65b0234cd97f3651",+ "src/codex/model-entitlements.ts": "a21db9fc98bfad86aaaf6aff404c2ee1e3990c1b1598c7d9ab7af91af1c2b601",+ "src/codex/multi-agent-mode-policy.ts": "8559eddf8c697993997778665daf21060ae1971c289fbb70bc971e5bbef6084a",+ "src/codex/native-main-admission.ts": "1f4956299bf243980bb06c7ddcfdadf71497cd874d3c1c49cb28465f27f6c85f",+ "src/codex/native-main-auth-temp.ts": "3671239d275a6ad13b55dd2bc123a2780dd4ba7d7e78f09752dd1c06c89dbbab",+ "src/codex/native-main-claim.ts": "f68443d088f08ef8b84e663939d83d8010157a7a6377eb85142e5c09f8247931",+ "src/codex/native-main-lock-file.ts": "96248ccb3b7352b3ad70ba73a75cadccaf5a5463162f721e600621b2e0ffa9b1",+ "src/codex/native-main-owner.ts": "a16ef678a47530d6e190263d26407365c3ffe47ca4e285c4f136072740cf2d9b",+ "src/codex/native-profile-api.ts": "19f3ad9555cc0c0ce107d2fdc092473c5637b55003de2015c3ea7d3f90fd895c",+ "src/codex/native-profile-manager.ts": "5fe33a50c243b01400cbdba6d320e7bc87f123c96aa7096f36fe5a2d8a203e53",+ "src/codex/native-profile-processes.ts": "91c26933154a2993093775caf47fe68b13c15d9af3376f0bcd01c5679d8019d1",+ "src/codex/native-profile-recovery.ts": "3bdb25ce98a98ff98a6420af43555c9a1ac0da657cf19fb33b12985752e88218",+ "src/codex/native-profile-stage-store.ts": "40a1e81d40db577ab2e7fb3f0eb4e8fceb8904510d36cbb742c2e3c61d69359b",+ "src/codex/native-profile-startup.ts": "fa5bcbfab12c5436c6c5229851be4be5995c27a0a75842ead9a0c423fb3fde2b",+ "src/codex/native-profile-store.ts": "5e0fe1c4b791d3c772fbea5d95e2a474172fad374ce050b7ca764b5728735edd",+ "src/codex/native-profile-types.ts": "e5bf51bb3f11c44ff62c2ebaf722afcf5b87c3e3c85da20806bbe789bcaee7be",+ "src/codex/native-residue.ts": "c637526ec0f9b7773317f3897d400ade16b0df5b8152796e233c86f7c5a1a46b",+ "src/codex/ocx-compaction-history.ts": "1eae04ea8578a9334673d3a1eb4f4ecc27fe388ab7250d461f6fdaab7055f817",+ "src/codex/paths.ts": "f14512fec482d38044172cee72532372bb32757f964b4c2c90f1349c4d07c32c",+ "src/codex/plan-from-token.ts": "0cac2a3518bfc07c6726f2e8fa9fd3b343e460b745455c85c6f7638d76f01262",+ "src/codex/plan.ts": "31eef78c9f144e9ad35e110f9885b08dcf2f9647e41ac0affb9e0cc1b155581f",+ "src/codex/plugins-doctor.ts": "51344b58e99a143d2c7d397481e5b2a26c86ab0a1c61db5b153068793e4d3cab",+ "src/codex/pool-rotation.ts": "993ae5806a1125b66bb8836578d35749e2df2e81f49567669047e44e1654d383",+ "src/codex/project-config-warnings.ts": "5272b02fb81ac17e076106450c37810ab32a73d940e91573bf7d98690a37b79c",+ "src/codex/prompt-journal.ts": "c458312300c4c4670d9d065bbae7122cf98a13d682ade615d5e7a87e0f74d4e6",+ "src/codex/prompt-layers/encoding.ts": "b6031cae7a49767fbee03bead363544172e3939fd2b420b66e438e2158a434f2",+ "src/codex/prompt-layers/paths.ts": "f2306be5b953f677e56b49696bdfdb22bf1c69cd8d65558bc631fe6a75ea444e",+ "src/codex/prompt-layers/revision.ts": "3c2d34da64321d9856f91b321a3b9c41976a79b8c4b320d56f2c66567f8a7991",+ "src/codex/prompt-layers/toml-edit.ts": "94e7b73b6f3eb09a63f5270779d14f2115b3164c682525a21566ab0ae9dd0614",+ "src/codex/prompt-layers/toml-read.ts": "7c0be7405a022ae2eeceb473abbd1f1f2faa84466c44978e802d8198ee910b16",+ "src/codex/prompt-layers.ts": "99074b4ff438026e29ba53b27f34cf3ef4a961df478f9fe1b59f1365e8281bef",+ "src/codex/prompt-lock.ts": "640c7acca611269353e550dede9ae9b0611d81846ad43eb89c1572dd1207d664",+ "src/codex/prompt-text-probe.ts": "6ab1a59afb4f0a5a7239490d5c3ec6d07f52f8cc323a60462a1776eff065e028",+ "src/codex/quota-401-recovery.ts": "a7098de48a250f10212da8f26a098e3f139649adf295f7f9df789ad6e3e8ff52",+ "src/codex/quota-auto-refresh-state.ts": "d589db1aaba036749ed07e182ad6030f4f7a7f0280f8b8600e417df444be45fb",+ "src/codex/quota-auto-refresh.ts": "bcc3d61092f99bfd14d51c1ec6b310a5ea7334417be94dd205c74bec7ec23da4",+ "src/codex/quota-recovery-timing.ts": "b8c0c6911b8ef908bfc81919005942f73672e7e0d51a593200736d3557bfce43",+ "src/codex/quota-refresh-outcome.ts": "cad44472c097db6ba85d5bdeae76b3ed778ea70479c4f4968dc9c36241c8ef75",+ "src/codex/quota-rejection.ts": "610c38395e08eaeb318cfed5c8472d9c0c8f1b818dd79dc6f45c5b6fbdbce226",+ "src/codex/quota-types.ts": "55dce58bca5fa3aef447c16b2843bc0c7de5ecd63beeaf65cdb3fe953dc55b6f",+ "src/codex/quota.ts": "9dfe98b8992781c38260fdfa538e57c6c263e509856cb3f51a436950ec320f02",+ "src/codex/refresh.ts": "648be78879375346ac2bf134f29a7523a8a436026d862bfaef0482d3840d8daa",+ "src/codex/reserve-availability.ts": "789255c66db98251ed7be0e05a33c0d27f175d6be396624995c003d547e0726e",+ "src/codex/reset-credit-auto-redeem.ts": "7d5a443e6fa6b4c36b8daa59d6d2ca8131ac7a086b3e85bc51d2b337ff43047d",+ "src/codex/reset-credit-operation-ledger.ts": "045f3a1c2d124ea93673ab4c19f29204fec556ce12771754645c0a1afb1bfc91",+ "src/codex/reset-credit-recovery.ts": "0978c72f8f254cfcaf61637d139b25e1c23c879d86258816dedcb467116e87de",+ "src/codex/routing.ts": "334d9790b48ed25f57723b257677622894389f2ab974cdbcc619e7bcb2a2f4fe",+ "src/codex/runtime.ts": "57ee095315e6488c2a995643a65a05f0bd63251efcf5eccb357945e6855dd2b7",+ "src/codex/shim.ts": "08c28d3daafaeee903ddab78ff396d6a6bf46118893640ae316ece111e8a3e38",+ "src/codex/subagent-defaults.ts": "66ac781355642d64e6926676f05d8e44f68bc27cc26c2edd66c9e0ffd19d5613",+ "src/codex/subagent-model-fallback.ts": "9df6cef74f20e8a5c140d3aa042e8fd032181485db3f559073113945349a6f75",+ "src/codex/sync.ts": "433c3c84cf6332ff04f978cb6f9e6dc7c27f45452540cb4fde84e984b62942ca",+ "src/codex/transition-state.ts": "cfa8b2c3c0e161a542416f1f4f88f3f2e229d5c0b6d4c3ef9cad389413dbd6f2",+ "src/codex/upstream-host-health.ts": "fcdf4fc3285d3c522f965b32793fe2e916c71e8094f795f1702f6aa75ccb9150",+ "src/codex/user-identity.ts": "139c28e3f638dfbe1363aa0c86a629357a1a4dc7ed4d40ab035f38067175d6d8",+ "src/codex/warmup.ts": "889225edcb0d60934ac17f442a370f36c66e2869c69ad7373f93fda2a20fa682",+ "src/codex/websocket-registry.ts": "739b0b64aa4a2f788a1092de0b0b5f753570430206246c2fd057cbe3b49637ed",+ "src/codex/write-coordination.ts": "af62b71a2638bb5f288b0b4ef0bf0d4566f2cba18808b7bedaeec02e37eaea68",+ "src/combos/failover.ts": "970a0550063a3e29d4ca21924431a08a1b60ebbc7876ee9172e676bb666fc558",+ "src/combos/identifiers.ts": "e839733c0f50efeeba8e00a8614016d3cc7f63dd5e049ef194ef34baa7446509",+ "src/combos/index.ts": "94317ebd008b0c7e42077ae3786e121b100ef31b718b1c2d8049e8d19ed9e8e8",+ "src/combos/request.ts": "ff45756529eb9eed88d23b6b8545647b5833e0360b99c0f20920a542ac8c7031",+ "src/combos/reset-window.ts": "24596b817a8a1e7c9c20dff78d5a6176e8b8551ef0a9ae1a7441b84ab08d78e7",+ "src/combos/resolve.ts": "43d75a46bf2dd2a366ea2cca28ada43dc38379f302be4f56f5e666e8a8b4ec72",+ "src/combos/types.ts": "2c8d666863947cdc31f2e8a0fbb1a5b51aab36b96103e06192eaa4c03ae51432",+ "src/compatibility/index.ts": "3399dc9eaafc45384ee28f8233fd440fd46c3db64d3dfac686cde6f7f590c895",+ "src/compatibility/manifest.ts": "e195ef7f6b970df6d709f1098191661e9de44758260cbe95fbdbb118d364f97e",+ "src/compatibility/openai-responses.ts": "c76aefec425a6c9b2360899216863ca97e7a88cf9ce76e7154fb1df7b168c0f7",+ "src/config/atomic-write.ts": "e4e0e2c3bb3adc7a2e02c7411718d4faad8417870c27143742ba72f9d6f6ab3a",+ "src/config/initialize.ts": "eddee7d5cbef36444f4d73d193b5e16bbe623d5fbf408ef4a47b40bc9daefa3c",+ "src/config/paths.ts": "c95e06d52ea41a77d5edcab36d259d167e688a294362121949ad712b9a8a39b1",+ "src/config/pending-teardown-names.d.mts": "8e56b8414ad9b3eacd2ca9711c766edc1b6254b92839245b473fee55f6f122a9",+ "src/config/pending-teardown-names.mjs": "3fe7314b6dabda15bd2ecb673145ab56a19fc4dabd3d097a2899137a962566f1",+ "src/config/pending-teardown.ts": "45d013fc3bfa22715187cff72893782376d8020b86ccfb996d69fc1ffb3a06e0",+ "src/config/process-state.ts": "248fed86efbbb2f5c653ce3e08af7a3471ea28a3c04dff094c33916d8a3a9f01",+ "src/config/provider-name.ts": "3b19ad53e350808174a5e40fc1c873054e8b869c3ae463d984ee608e9d5bbcb3",+ "src/config/provider-validation.ts": "47b410a0c1e47c4fb21483654293991197d5d850cf04e4ff72ae1a47d7a6fd2f",+ "src/config/rebase-provenance.ts": "97dc1c17ccb9298ac963b67c1cd2f15d5ec853648c03b0505492941986e72e0f",+ "src/config/subagent-models.ts": "d47a1dfd0f57cceb090fc1a9922a59b080c51828831462e99d9a0a50d07d33fd",+ "src/config.ts": "9b31c81739387d0d554a03ee78f3682bb627e40ed0f5f6d25a149572790323ff",+ "src/generated/model-metadata.ts": "1d0baea1ede9e15a7d859109233ea2020eff5ac9770e97958d252e4a2d003e9e",+ "src/github/star-state.ts": "b9da7a4c5757685d227a9981112096608036fbccde9e1889149a9bd150777cbc",+ "src/grok/catalog.ts": "5e5e2117060847d5678ec4c70fd7777136fa4460a8043061b46265547751ef33",+ "src/grok/effort.ts": "3619f6dc8b0ce496c52dd6d72564eb0574812ca2e84f4b75258a81ff055d2ba4",+ "src/grok/inject.ts": "6b1890e7ddbb26fbf94b844a5d6391097bb88525d32792ca3e6158eb79314780",+ "src/grok/inspect.ts": "b47f64f43ff8a7dc6b9c36b94b19188c2e362e1083eb949ab4f5f40d161d6914",+ "src/grok/models.ts": "86309a5ee941df1d6acd4d5e48ebf6dc9697168df976b985ac9f4c65c1741666",+ "src/grok/status.ts": "87b2f7f4ed1aff2fb9d7c2ddf85243d066c0e08950f8e9a92a9bbf6dc5011bdf",+ "src/grok/sync.ts": "cb1126e20de6ba55076a6a0df479095d5da01940a69c361210ce77d04377d800",+ "src/images/artifacts.ts": "6ee18c60c3654991c3bc55b15660cb927dcc4eef285e1816f3737f640f30ce96",+ "src/images/fulfill-video.ts": "ee33e95f28fa853c34df6583df49bc8ab4cc71d94c1ba7e563c3ee39f9bc8da1",+ "src/images/fulfill.ts": "43b54f063cda82e31607eff59c389512dcb6004d5f838d4de879dea62142a018",+ "src/images/index.ts": "ec5fed6adfe3b59d0c1a8cb7533b13eff247562427016b7b4bde1b14d501ffe9",+ "src/images/loop.ts": "5d990b3b240576464675d39fdabc96e806a13fb71c21d33da77ed15893a70f39",+ "src/images/plan.ts": "e20fdb8a37c7c04a8a07c6a1677c431fea67f020c1ffa1d62cc3b199208996d4",+ "src/images/synthetic-tool.ts": "a88ae6e304a28c162e03293647c1065705c7d8267eda62b6b45306f5ec61fc32",+ "src/images/types.ts": "1fd24cb1b05b71dc1320c08499d0a0d4b0d2e3257ec7225e26797a3cfeccc755",+ "src/images/xai-client.ts": "5d8bdc9776f11e65d242656de5da280370ecaa7e1ffe7c390c85d0cf5690230b",+ "src/images/xai-video-client.ts": "90b3e532b75c4ed9660d356c2fee8441788e2d951b6885c9ad4542dc7ccbaae3",+ "src/index.ts": "89a4d0267a7a99c195b6c02eda4fa8ae7ac2bed2230ce1ffcd12f5e3db550621",+ "src/integrations/aside-profile-context.ts": "7c89a9840433d5c7c07bfdd3ae517a0bd1ff5e2398180f997d964c384b77e394",+ "src/integrations/aside-profile-journal.ts": "69661e9974e396273209c1446325e92992a82c801723fc8d4541be0d4b0a296d",+ "src/integrations/aside-profiles.ts": "053cfe61fa32cc433a3531389204d747b88f37d65fd4ed74e4b454b3116c2f00",+ "src/integrations/catalog-refresh.ts": "bca9d33e50690ebb9f26e17857856fe40acf5b27fd2909b64d864f190bb472ed",+ "src/integrations/config-io.ts": "81bcd7431ac9ab2b44ec1475a4df3c95e1f39f88964ba3be7575a2e56b9b0869",+ "src/integrations/cursor-detect.ts": "ec3c7c03cb7652bd7c89eee4a285fefd0c2c0fa4c641238fda91b977ac12f02c",+ "src/integrations/cursor-effort-table.ts": "01aaf416476550049fa9676f1aa8710e618000733e096d014d17fb63c94d801a",+ "src/integrations/cursor-seen.ts": "ed100257d59585f2f42c46157f844a44f0f53ec66f82cbd267675baef798e231",+ "src/integrations/journal.ts": "84774fa4994c25d807465deca89e0774fc957972fc842477dd3ac7167ae046a2",+ "src/integrations/merge.ts": "3509078efcd76dbaae5bd74ed73317f69ada32a8cfd23633898946802a039564",+ "src/integrations/mutation-flight.ts": "45db29b914deda3b5cb569c360cf87928d49f41fbea467d6cb1b37f2d02adc52",+ "src/integrations/native/ownership-preflight.ts": "f82c011fd3764595329cc19b23a7d7fb17b09a0a6fb40fedf63809a409373f5f",+ "src/integrations/omp-yaml-source.ts": "ba30982af0520ffe5c841b7254ab6d73e2a9fb53636f3c5096c9fa6ccfc41005",+ "src/integrations/owned-refresh.ts": "45ec0b341681ff077771c66f9e02c0c1490381a127e6c39eb03bf735d68f12e7",+ "src/integrations/ownership-policy.ts": "1079d8fad8d4cf3adb1700f12e3c9497ec0ad3d9acd0d140c05a8675cff68f35",+ "src/integrations/ownership.ts": "974d740dc6deab816726879b1d814a660769dce39b2d4856e41c4d0de05ca150",+ "src/integrations/raycast-detect.ts": "29f4702d711a7547c1d71eb60e8b80c9674ca023bf5a26513c4021cc0d626b2c",+ "src/integrations/registry.ts": "3baff876e792d4e6daedd05de3217673b820796681ead31d23ce310fa74e4f1b",+ "src/integrations/serialize.ts": "0560601276b25d82eaf6e5460c815e0a67ecb4cf1cf6e378952c60dedfb333e6",+ "src/integrations/state.ts": "9e3de25e823089c1affe558f5be31d7b91e14fe02ea2675638c80b1ff9f2e920",+ "src/integrations/store.ts": "ae019a98970df0c34950333149fbd8faa3504f096f61fc740e20d48f6a513e65",+ "src/integrations/writer-lock.ts": "4e133b69db94784460351a2ce947172fd6499235029fdf866fa3eff2afc477b5",+ "src/integrations/writer.ts": "46c56802eee2da6cd55751cbfb358768871cdd3db697263dd3925434c44f90a7",+ "src/lab/artifacts/sanitize.ts": "e854b69ac9088be7c44a1dae4fa4e7ea4fffd325f440efb2fb420316a2d6f11d",+ "src/lab/artifacts/secure-fs.ts": "3bcb1d15436df4101e4eb3a37c2e5d1471dde09ffa32f31b037b04d6f35e7592",+ "src/lab/artifacts/store.ts": "1fc47ea9052087793aee0fab654bb71c898be945c687e11459f9b6796894d413",+ "src/lab/automation/budgets.ts": "d55766298d74530293927fb9fcf6a6706b33a1cb7a6efe1c93df0c9a42145ed0",+ "src/lab/automation/config-persistence.ts": "a058bbe3df8280ef4786527054d476370cde8dda9b59615c906751f22f84b650",+ "src/lab/automation/constants.ts": "c1f7b6496d8244f0c9d1acbcf1a30ea23e39cf35d177b74271c1424baf8f42a6",+ "src/lab/automation/cooldown.ts": "8420b44acaac9b22d6e1be15d4ab9091476f8fa37d750f3ab1346a69861f5c98",+ "src/lab/automation/dispatch.ts": "ee1e48c8e8c3eefad98cf5662f16e67ca31a0203e2af75d489db4d787f312cf4",+ "src/lab/automation/index.ts": "ee9158ccda643191dc476982fb10254e2724b775c6fc8ffd4fa55dcfbbcaabe4",+ "src/lab/automation/orchestrator.ts": "5f10d45593ea6464f6ecd1db6ee922bc7627fc6578fe6f3f93b7a35c1b479df8",+ "src/lab/automation/persistence.ts": "de236e2b77ef829e54d9ef11cc64ca410f7a3a968e4c50e237cbe4e42de208e9",+ "src/lab/automation/planner.ts": "3ecb49b9d45444be491325b4b3a54a62db66519e9e9a1d624248d19fd5fa8c90",+ "src/lab/automation/policy.ts": "8cfc6c30034838a04c9a77cdd70630d78758982a6b2cc691a60d8cd9b8ecc0bd",+ "src/lab/automation/queue.ts": "7fceec660bc2470c92cccde0c333acfaffc550dca702ce46ec5ac3c6d1c82e4c",+ "src/lab/automation/recovery.ts": "b1008ab1cd7259e19a8b1218779713666b9a3c74d6d2cc9ef6e1dc343f6fc708",+ "src/lab/automation/route-context.ts": "28fcfb20a91c598282e34f9ab30bfb89602e37910326cf61e4fd0083f8b31575",+ "src/lab/automation/run-key.ts": "9d0ad83795ffe990254c81e2400cb886869ff9bcaf560b8a58baa918f89f6bd6",+ "src/lab/automation/runs-query.ts": "67ae149e8c45bb017d4ad11429bc24fe7cfb946f811631379f76d7e5ec67a71c",+ "src/lab/automation/types.ts": "3476e6259f927ce29d2e048572b21fb4068a9bcc8d6839112b3dc1fb35822b19",+ "src/lab/conformance/assertion.ts": "f28d47b93b6237028d8a070911a3a7105f0a95330098a941c7e89dfa091a1946",+ "src/lab/conformance/digest.ts": "3381d42470656d4714f715bff0fca922b298b49152512a2817a208b70446bee3",+ "src/lab/conformance/executor.ts": "653f9434d3d1f886728c5adb001d145c32f5244dc1a909de5fdc406a08c957fa",+ "src/lab/conformance/fixture-provider.ts": "8ebd3b7f1d27a6aba95fce3149bac4dc919b9d3dd0d7184393a2005aca96495f",+ "src/lab/conformance/fixtures/live-v1-cases.json": "00844c7ded7a00265ee5ee7d520588ca182ac65a17e94d08d6d21f9a2cf6ccc0",+ "src/lab/conformance/fixtures/protocol-v1-cases.json": "f83c19cef9d8f228eb7f95111283e87bfc159f664a157f78c6f86eda64cb7486",+ "src/lab/conformance/harness-budget.ts": "dafb6816b3ebc80ed1f7878c24a29dc812eea8e7ef620bfe798a228d02579822",+ "src/lab/conformance/index.ts": "b7e480643369b1dbc3652c15e54d1c235e19352a1aebc03982ed740c3c9ba821",+ "src/lab/conformance/jcs.ts": "95fb75fb61c8e37f611550e768b2280e6ebe117548f112841a70af931f869c99",+ "src/lab/conformance/json-pointer.ts": "c591395ca444cbc2d0a54a44fb2156a428c05da893968caa3c3780eed4c28b11",+ "src/lab/conformance/manifest.ts": "b61a5693c50ba14858e436596c0bde790550b7c37370d5f1561391ff793496b3",+ "src/lab/conformance/mcp-stub.ts": "e5e50b0358a592778d7a914b6dabf348431912f1ffd2b9d44b5e9e42fe8caa77",+ "src/lab/conformance/negative-controls.ts": "2224774fe5cd9aa6856240420fc1607addd55fbfe1221007a6b6e8d39b87ce10",+ "src/lab/conformance/observation.ts": "9a0dc654d98fb401f87284ada889c2c291e508d78d6468265d36fe92a8ac57b5",+ "src/lab/conformance/runner.ts": "67ff41044d4c6416860ed9ffc2f512efa3dd442079c79307e709c48074bfa00f",+ "src/lab/conformance/sse-normalize.ts": "eaf1ce1a4d3de55a6dac9dd729f64baa73e48fa018259445cb5157c9525e5b46",+ "src/lab/conformance/suite-manifest.ts": "5cbf6378275318b4ecd063ab47c62b0dfe1f4b112f0da7ebca3362022d035fd4",+ "src/lab/conformance/types.ts": "bd055d9332dac5d83fe990dbd814555712998d270dff55d80de4d2b889cafd14",+ "src/lab/constants.ts": "59654eedddda0f17824d3c8d19a9c4b5c00f88e7b890405d97ce1706e03981fb",+ "src/lab/digest.ts": "5a9a966df6ed5a8f90edb9f49206ba85f08d4cb9a79b84785a64da47c11eb558",+ "src/lab/events/errors.ts": "e025e756b938c4b504e050e8fcad8ae9ed857d51e10f75a5835c8cb0ab75fc5b",+ "src/lab/events/limits.ts": "5a0b2f2f63ccfa530d028c03d55ce51474e6b8b86cffdec811f335da68c263e0",+ "src/lab/events/types.ts": "69cece45c8e01fd59e56dd105916772d10af66770425409aca0250376a564184",+ "src/lab/events/validate.ts": "effbe30dc8d8a2a1c9cd7a45bca32156de0ad44468248589e7711d015f4524b3",+ "src/lab/fabric/constants.ts": "658e7daa585d47fb3115dff06d9f41e903df4c391910128fbd570050d8f402cc",+ "src/lab/fabric/executor.ts": "0ef9546bbbff1ca242ee6f3a2776b08ccd8c35acfe4df2ca805cbe6abce75220",+ "src/lab/fabric/index.ts": "cb270b6341c759078f17dbd0166ea2faefa2bbe477d3ec8ac04ce8e67df9606e",+ "src/lab/fabric/manifest.ts": "d893e349ed0a9afd7567313ce025b0e2fe502e155d1396ff4b136fd55eef2c25",+ "src/lab/fabric/observe.ts": "9bfa6afb311a87615ea399a2a607e90de66fbac62417a20ed1bc1a5f15b6e372",+ "src/lab/fabric/patch.ts": "b2acfe7761dc63899a4a587bf9d9c9dff75beb8087fbdcf43734a69fbe773695",+ "src/lab/fabric/producer-child.ts": "a76e692f3d55a538535f0527df7f394ac0055608a77b613795f16cf727231085",+ "src/lab/fabric/producer-isolate.ts": "71fb160dc9be4444f11fbef768b62f6e2b0300c09188b362271dd7f61368d0ac",+ "src/lab/fabric/producer-protocol.ts": "3c032f55c28606fdb956b0728663e09316442a77b3283b17ac1282dbb3acadf4",+ "src/lab/fabric/scratch.ts": "928715d9e299337f855230027593f87aba45dad372e7842a2b31d63461ba3bda",+ "src/lab/fabric/subject.ts": "6f74da7559bac3dd16f07665cd7d5371fed9a3442c139eb41f7977bacc30d117",+ "src/lab/fabric/types.ts": "39ffb693b6c893745ab61eba51b91b10df74fc141a8e8ef4919db3ed5356414b",+ "src/lab/fabric/verifier.ts": "6df6fdc3a19f1c6c6bd669bcdbda85dcad84f682bf9d2205d2a55c74716c0aef",+ "src/lab/index.ts": "9d7641ada15ef4b2f0fe5f99beeb1d6629be47ccdcd747d96e9ac0064a8c722d",+ "src/lab/ledger/artifact-refs.ts": "ff45f38dbd2feb6396d2725288b5b8428dbf6403f133956d96f98ad982fa92c0",+ "src/lab/ledger/invalidation.ts": "8cae25ead7ba0b28f18d06ab71de56736bf9c4e777bae3294c05316c22706cfe",+ "src/lab/ledger/purge.ts": "75db44dea82f8b07cbe80d1ee2ae5d155a5d68330cdd77c5013f532ea2952ebd",+ "src/lab/ledger/store.ts": "489be24da99f309aaac4dc509fb79921da9be66471ea1cd5ca1996974ede73f7",+ "src/lab/live/credential-lease.ts": "98dd56ae7a0d0164478f99dd2dc4cd3799246354e9ade8559d399826b54c6003",+ "src/lab/live/destination.ts": "003432b3302dbbc9c71a343b19e50ebf74a8c70441c2c1a0a1862dd618cb5944",+ "src/lab/live/executor.ts": "f98a3755b75b36f9d7def03760789f388c4236b7c818c51adf70e0c4a3e99ccc",+ "src/lab/live/inert-tools.ts": "4ef4beb0470eacb4835bf6c4020aca07c42cfe882af79a31e634e06a0196a4db",+ "src/lab/live/manifest.ts": "75ac32d510bd9f3f5b90276a18ac524fcd92e3bb4530ed42e664af73d7a5de3a",+ "src/lab/live/mcp-loopback.ts": "a09a43d410d9c482185e7ae3bd960abd36f3460e868f3ee5b6af28ac9479115e",+ "src/lab/live/runner.ts": "377a9750b4cbabe2c9a8e9afb4cdd97c127a0f026e6e50987aa63ffb2da2af35",+ "src/lab/live/sandbox.ts": "12695dbf4da2818e7b5b31a3613ceb056e3b2c8b14185f7212d43a32d8100e80",+ "src/lab/live/suite-manifest.ts": "c740a8b118bb3901584b96593c1d1773630873791015176adf08faef5a66d0c9",+ "src/lab/live/transport.ts": "bab59e2980b99decdf983898e671b7868e7d51f8759f59b8e439c9d71c9b17ae",+ "src/lab/live/types.ts": "c521f069d495576a848929a10cfb5679f13691fa47657aef0561cd7f9bcd1676",+ "src/lab/observe/from-conformance.ts": "8c6b5e06bc895d4be12b0588410fcf5206f13523b01c1b1a0ac5e6ac90cc7ffd",+ "src/lab/observe/from-live.ts": "ad019c524cac33bea664bc356070292c441a8adb9e71b75748bde2ab3c8b717f",+ "src/lab/paths.ts": "57284828817109fca6a40fb74f4aa65a99ec73f4b8ca1ef503b8345a7b851e9b",+ "src/lab/projection/rebuild.ts": "9de9cfcd613634b5afa7ba8bbea7fc24327ff1fb103ae2c70c6f5475e70695c3",+ "src/lab/projection/schema.ts": "5c02a7ee33ff94699cd3f618409a977503967757590257e0ed1c8286db3fde85",+ "src/lab/projection/verdicts.ts": "702686a432b271cd848c12f2c0a71700f7b91da2155595c88195f0059fec906f",+ "src/lab/projection/verification.ts": "c6158165da7bf5256af00c4a261cebffe1aa8d3b781dfd8c130a8e375593f39d",+ "src/lab/public/bundle.ts": "891ebb566a7f825df8b3cf5d5a92cd67e89a05e8007da6b67feeb274e2326cf2",+ "src/lab/public/community-authority.ts": "2c8a3ed764d85793bbb750b93ee87808a664c9459a05f0d182b56e6453618ae1",+ "src/lab/public/community-files.ts": "c3320a510c9fd7d8007bbefd0be2aa17d05c9f6d72eca0129082e3f1ba4ab243",+ "src/lab/public/community.ts": "fd83811a5013267af45b7cd99ffc83727786d3b937b89259ababf3173eb6aeda",+ "src/lab/public/file-safety.ts": "6207b639875350d9974d976133261a1a915d861e4938a1a341d7c86eae19c432",+ "src/lab/public/ids.ts": "f63111bb8f1b659acd7dd201317a07afd690f01256e72f41c5351d634c70e42c",+ "src/lab/public/index.ts": "5dfb84c81cbce10982a9ec6bc8d4eb80c12df12e893c093c5d082123cacaab96",+ "src/lab/public/mutation-lock.ts": "cb253abe796d05ca5c97926695a827cf9af680cae855f2375e007a5897f61156",+ "src/lab/public/operator.ts": "b3b09989ce323a4b6e6dbea4feda9cbcff8cf0dd9f08c11c8bd323487cc61098",+ "src/lab/public/origin-purge.ts": "c8273ee61104c326ea4fd5954b5702ee4a1e8a37f1601ecc0d08e81db4d20837",+ "src/lab/public/origin.ts": "3b34f7ddc4e68a493375bbeaa15d1184600d86ec82216717f8c3bdaec7c34c24",+ "src/lab/public/privacy.ts": "7e094c63615bda5f8b9e1e91cf431e832ee1a8d552ef76a753ad813e65eaeb32",+ "src/lab/public/private-file.ts": "bc0a291c2bab814e12f7cb4d769ec1346dc8e0091b64653b63706e123a18f68e",+ "src/lab/public/project.ts": "7e66e021c0bec56c2616d6650ce37210d13e678737114f6f2d112de924251651",+ "src/lab/public/purge-test-fault.ts": "c191e5512ae5a0b2c9f8d41b5d7a971a79c4333282199534d47010c154c3e7ea",+ "src/lab/public/purge.ts": "ed18c892d73410102eb7c802896c39495468b1a29c96f2b69488a38019a6e9fb",+ "src/lab/public/registry.ts": "4fe99614bd1acff21bc2e132a4ed9835e5c6a4abd3b11fd9a00c2cece50eaf2c",+ "src/lab/public/revocation.ts": "25839f10ea4d160dc43161dd691494e79702d686aee8eee2567aa30d48e789ee",+ "src/lab/public/signature.ts": "bc9aad045972c3dc69912f0c5865bc47d61ab7897d94807d9905911e0794a94e",+ "src/lab/public/storage.ts": "6bba3e0ab8a2d790575c8042006410d86677c68e7c33a0815f95b8a882513f1a",+ "src/lab/public/strict-json.ts": "6ceb7b915b421ba1072fd794f5868068c05f5d157c0100758784c9de713c93bf",+ "src/lab/public/time.ts": "60195bfcd50d4af69b6ecd5fbb04829a7064b24d665527244f0fbf778c2f19fc",+ "src/lab/public/types.ts": "f2b88b4dd99e56e172a2c73657eb8d5096ad3291fd1a0b1e6a3fab8a3123b1d2",+ "src/lab/public/validate.ts": "ed12038cd0fd08f8e9fe4dee30fc4d31285b596e69865fb3edaa51ebf467d8b2",+ "src/lab/query/catalog.ts": "e98d9f5e5b66d609bcff45abf81d23e63e4049028245462d833bd5b0ba803575",+ "src/lab/query/connection.ts": "ba0489e284c8d1f48ccbab3d7d89392ca65dd2d632fc5fe7039905d8a99a1070",+ "src/lab/query/constants.ts": "c1b9eddb3d510ebe70fbfe44e296d633ac51a1f689084f1a551fd320d80a3275",+ "src/lab/query/cursor.ts": "57459fa1d7074deb4b20253dc78c20ad2c91fc1a46ef57a6bc191bccec18bb83",+ "src/lab/query/dto-map.ts": "1e3892e627bf7a2aa15876411c5429cc8db2b65a8afd45ffecf856ebc157cfe0",+ "src/lab/query/errors.ts": "8ce8a900a20f8cd5491ada22bbcb744deb792f5b948ad2ba2b005c49403cb2bf",+ "src/lab/query/freshness.ts": "5f88e7af150bccf1004c67b6bea5306c197f330abb894bc8852a0b87717ea744",+ "src/lab/query/index.ts": "6fe717611eb2d2c94968d7504af3424a83604456f1df8dd0ba7ccb9df6ba4222",+ "src/lab/query/latest-observation.ts": "5a3c62823399fee40455bd4e93c4bc76cce584555e7aa3e0ae2fd710ca6ae6b0",+ "src/lab/query/passive-production.ts": "0f3dc4bb455f7429d73a4663f7175b698a82f9463f7b778e965a1686323df326",+ "src/lab/query/queries.ts": "0608e8daa20439d008e371c9d6807fbb877879ad868fda2a2af13f120e453684",+ "src/lab/query/types.ts": "1b5db1b861b2bdf7942dd5b4126215d7ad6d57110221d71b5560d1de02d9ec81",+ "src/lab/subject/behavior-fingerprint.ts": "9dc54211f2550f404dbe85505938c9b4c559548d3fa733db82860ddb50ea2d9f",+ "src/lab/subject/installation-salt.ts": "292ae399517d544d12d1d009510baa43fb150b24e4dcccadc6b5d4db151c2911",+ "src/lab/subject/protocol-subject.ts": "3f57e59f805bfb88315648ee72f7753eafb5f7eb7245587a9392b4b62be761ef",+ "src/lab/subject/route-subject.ts": "3c99427afe6c0eac88363d1346c5743ab6c056fd65becd5ee98f49a88fad2933",+ "src/lib/abort.ts": "303d4fef28a1fdf7c6a8f1feb612ff084d16f6a901648f1c768f518795ed2b26",+ "src/lib/account-selection-events.ts": "a3397b42052052ab153b7abba43a814b882c4b51c129e91631fa8bbdad1ee855",+ "src/lib/admin-secrets.ts": "4a2b0b36bbde05e58046c89d4b9a9a5ae5948b8329e71eabb365f81f519a88f9",+ "src/lib/admission.ts": "d10a13bbb09f7d8bdffac9b120bd75373ac7938a0bb333f3ee2f43a457727fb3",+ "src/lib/app-owned-memory-stores.ts": "aa59512ac53de389e9779b8c1d93661cf3e362fa053492c5453746d8e8f5d0fe",+ "src/lib/app-owned-memory.ts": "9602393dfd51ecb695d4adf018399bd77d33f364d8f463eebadbc4ab77692e66",+ "src/lib/bounded-body.ts": "8a271580ec37de198755769bcbda25a9beecf7ece6ba36bb08266fc78b950a04",+ "src/lib/bounded-subprocess.ts": "d4c3c7a3d5658670390fc615b9c8cf681fea720154a339a05bbca26f11420bcc",+ "src/lib/bun-binary-validator.d.mts": "dec6eb67be41660293d373603ba2c886a3d6411213d42dca3c36a17aaa3a59e5",+ "src/lib/bun-binary-validator.mjs": "aff2c48484e29c3a67aff9726425c2c6e123e58ba51e775bb6df5ac85399ebc3",+ "src/lib/bun-runtime.ts": "c1d7b01e8a4f3b0c3248f1416978f7bc5488ad5ee26797a31e7d7ac0bc3a3b58",+ "src/lib/bun-stream-caps.ts": "d2255a860bc9ea451abc7913cca76779c41656d35965d80ce10c63ad94e032aa",+ "src/lib/codex-restart-contract.ts": "25518ea4ef7f482da904bd862d165fc7cee19add6cead5ced5b1126362077a15",+ "src/lib/config-ownership.ts": "26c496ca9ab78b0f9e4297c5285f1fc0a92139b81ca42075f03996697f885be6",+ "src/lib/crash-guard.ts": "4cdeab19b61d8cf912b57d815c64ddb061150e83d0291fac0834066717a6aceb",+ "src/lib/debug-log-buffer.ts": "2c6a5592716ee67b871306b90912ff17b8edf68ad206c63924533bc8a4ed0757",+ "src/lib/debug-settings.ts": "6b7c20b98114ad5309b3143af12475233c58c6097eba145af78d22a471e0ee68",+ "src/lib/debug.ts": "c99495ef25013882e7d5e3207579a45d236e8126ae930dcdb41566f98783e4a5",+ "src/lib/destination-policy.ts": "c0730619192e47b9c3049915797ce91cd92be2895c35c165cc77a14d1950bf45",+ "src/lib/errors.ts": "747ec5cd5605aba968da6429eadb68460b3cb97ceebe8a788b5d07f84664d87a",+ "src/lib/eventstream-decoder.ts": "c39ebd4a206fdefbd76814ffe1eab003305356b89490f3dafbeb01ae0145d265",+ "src/lib/fabric-task-execution-authority.ts": "a75156b9e28419b9ecf4041f3cb2d360ec126af13900799fdf49357a1fc2db1c",+ "src/lib/fabric-task-host.ts": "211c6acaa29cac405f2ee8f608b9961ae2975c58573668ff792820f65446d316",+ "src/lib/gcp-adc.ts": "09de636d27b8b122088cf1322235567e54ce1a8cf6b00dd349e59856733045da",+ "src/lib/gui-pair-capability.ts": "2ca748224810e785295bdbe75a30035984953d39a4425802be2b09e9417d2900",+ "src/lib/injection-debug-log.ts": "ab3b8e53c546c0ff43dc129d29c0b11c2d258f86e9d12475d87bf55510eb02c9",+ "src/lib/json-byte-size.ts": "e4c31eb29bc21baef7c1994abec3393fe608626871087ed84d5df0dd847b3152",+ "src/lib/lab-activation.ts": "d1345dc867095f90b9ec2f4e911cc7d2e9bcd4e4a24265f58a2768e7181a1ba0",+ "src/lib/lab-live-execution-authority.ts": "7a4c488521b861ad70a87f560d85cb5c9f552e16493c5d44e19734947b4ac714",+ "src/lib/lab-live-host.ts": "d4304ca28e3b5ab72f146d564447c57074a318302d4bd2448bfd1d3f337f1dda",+ "src/lib/lab-live-pinned-sender.ts": "11de6956e99955d67c025754849a0be4978d8a996f9ac1da8008906132b84969",+ "src/lib/lab-live-route-production.ts": "63667b79600192bdc1ece145cff783c5ecf9509c8dfb0a7334d0c240a9a557d4",+ "src/lib/lab-passive-linker-registration.ts": "5f88d3428f87f1773f944e43d812356b96e881dcb8bd13d34baf504ce509e54c",+ "src/lib/local-destinations.ts": "6a2ced356ca604afbb943cbe24b4880a29e474ef55afccba07b410c722cc9379",+ "src/lib/local-management-attestation.ts": "1bccf8f85ecd89cb017224024ca3d199d97c8ce88f5ac936dbc1419845a77f6e",+ "src/lib/local-management-capability.ts": "1150af62dd3f0d45337d5b3b681224bea89eab293d42d6e3c9dba3c8245fbb67",+ "src/lib/local-provider-reload-contract.ts": "5f8d45771de21edf801129e9221e2b2a8ba43a3328472b36362f21198d0af260",+ "src/lib/open-url.ts": "a6db7ec7181ccb4e95411b2c7499fdd00f3dd48bebcdaca099da086c0dae2e59",+ "src/lib/optional-shutdown-hooks.ts": "0d0a20ce244b59a2ce8f88487f86648705580007774e3eeb44da6c477b65e17d",+ "src/lib/package-tree-integrity.ts": "50cc54124a87ef738c717659a4233bc7e5b010959a0204fa996f36f9e5e08679",+ "src/lib/pinned-http.ts": "ac1cd748e53b16109aaae86194fddac88424b508f00bb2e7c7090869f58c9b22",+ "src/lib/privacy.ts": "532cf8f9e52e8b25e3c4063ce1fe6d77c1e501900428d51a2e491f48fc8d0034",+ "src/lib/process-control.ts": "ca6f69d135f673fde59e3af932c69b37dba6ac96ba6c14381ee8aff4b809d61c",+ "src/lib/provider-outbound.ts": "ec930f168efee41e6c7c4d24205281b3268eab3c2b4dc30af53158ea5cd3db93",+ "src/lib/provider-url.ts": "0949cf528110343b532512ab5660752c12db1944a26a714938ed24e4ad5e864f",+ "src/lib/proxy-env.ts": "7624b73aef012e403121f4d4d3ed36b5a30df9768371953b6efc29af6a1276f4",+ "src/lib/redact-folding.ts": "a6f095a3362d0725b15c99b7e8106ceb5cafc2644e04c48038a2d0270fbd6e63",+ "src/lib/redact.ts": "753767b50c1e28d5d308a1f943f0a97ed7411a9ff095e47e35e73077e3faf975",+ "src/lib/retry-after.ts": "dfbffd50f527cb251f2c20f5191f0c6eb34975fe43d2e91dd8b326e143c937de",+ "src/lib/self-launch-argv.ts": "0723eaae3d4a03a8acdaeccf58bba6995b3a2084052d0021b8b1a4bfbb8ccd6b",+ "src/lib/server-resource-ownership.ts": "8248c3758eccbc6abc9150fe041e89fb2d05f114f9fc26cb1fb70a6c3b7403ed",+ "src/lib/service-secrets.ts": "0fa6a4fa2213c1babdc5dfa34da620ee97829ebc233745eba9b42a3a594f434c",+ "src/lib/shadow-call.ts": "08c638e921f815ded6f6d6b41de8aebbf6e2643229a117896ad9ddfb368debd5",+ "src/lib/sidecar-tracker.ts": "a28d7c7be69d972d4919f726ceb76f257d575fed090ab1f119c366e229681892",+ "src/lib/sse-decoder.ts": "97cdfbdafe03dc2f8ba2b0b5fd7069313d73042c23b4737b2beee82982a28b67",+ "src/lib/state-store-registrations.ts": "7aa40b75b379f4b8f4c450bf3a0eeea2d0d7619c919be09df3aba73b58f9f57d",+ "src/lib/state-store-sweeper.ts": "470ad47c4d7bd4b1c41886f4a30f6073e55ad63c4ce5cb2f02d3bb30d6a39dd8",+ "src/lib/strict-semver.ts": "d4d81713842d7baa62e9971fa81b81e3b97ec724ff521a6b8dce814ab0dff395",+ "src/lib/system-restart-contract.ts": "5bd6d639da7571788922bfa90757bd0edf82f3bfaa5f347c927bb8d0978d10e4",+ "src/lib/test-home-guard.ts": "c39d78c859cd9bcd88729544166aaa4d689700203866a888e15b13533b155e14",+ "src/lib/token-estimate.ts": "ff758c8a88127824c425436a4b3bf9450fb3419496b0ebcbcb1523be2b6c7118",+ "src/lib/tool-argument-integers.ts": "0ed323ea85d13016cb88e048d20238b7d87fe2beae39406229d9f970f1402b2c",+ "src/lib/translator-budget.ts": "4d79fed2d10e23b87af2c67ea0a979ce580eb232ac35e1f6851b5f02ef5a07d7",+ "src/lib/upstream-http-version.ts": "9f2a6708401aaa63436efd07ee657e063b8f02df204bdf59fdc3b466657cfddf",+ "src/lib/upstream-reachability.ts": "20ad0882301ec5c6b0f8de039f2505fc3f4eb744c8e15bcc7f1696e43736a033",+ "src/lib/upstream-retry.ts": "42e2940486f43ddd57946839410f0a9c6a6d5e9a94726fae6841aa58d245a83b",+ "src/lib/win-exec.ts": "96b9c3bfc48aabb7506e060ae81b6ab1b3de0dba4f3d0538d4ff226abfd2881d",+ "src/lib/win-paths.ts": "83a0d8c32865a5fc3ed34dd10520f2c5f99db7356aaf5f856a0a24a10790ca9c",+ "src/lib/windows-atomic-replace.ts": "8cd18190140182a7628178be7c03ec97c6e87f81f7d7df08ea92c1d776cf1334",+ "src/lib/windows-elevation.ts": "3dec32d9b73ca730d5b8e0cd118bb109c0d32c8e796f99d9ec887bb9962a4906",+ "src/lib/windows-secret-acl.ts": "361952975f0379faaf3fae33088bac8386bb55e90be95bf2d051a4d2abbfcb27",+ "src/lib/windows-service-mutation-lock.ts": "00ab6da61fcbcc680baf221aa82ba9f40711978a93dd0a47c2ef1220bef7e4da",+ "src/lib/windows-service-wrappers.ts": "45fa37399e5d6875eb1f7bcfb93950ec80abb4de09a7abf278e269c88255ba28",+ "src/lib/windows-system-proxy.ts": "c88f6c94490ce705e5500b1105a63904d4f8d21d257efdc433611d47f91c8e76",+ "src/lib/windows-text.ts": "d4238e2cd6be054908e39a6357ca48c58e50d657218e7ec724e9edee5ac634af",+ "src/lib/windows-user-principal.ts": "e9408a8135354911ad5f627900a4b661272d6942a29f7ba458829d61a5ca5a98",+ "src/lib/winsw.ts": "d4e1db7f179f8fd7674039fd2a69d61db8c7c63f33b7dd7e44a05c1599a7b16b",+ "src/oauth/account-import/google-antigravity-adapter.ts": "3989c5cb9436468f839d245b967d8feb55015eae11ff25b3e0ad004ee0f77e35",+ "src/oauth/account-import/index.ts": "9547c25faf13f26baf8069c1b2ecb263fe74aed50958dd8b8818f75692679bcb",+ "src/oauth/account-import/parser.ts": "6ae10cac85be7a133324f8239b12900e42573617b4e67cc389c95044771960ca",+ "src/oauth/account-import/registry.ts": "70b34ada3942e835108a369377f010eeedb51d040036875a926ab74f79db81fa",+ "src/oauth/account-import/service.ts": "b11410b3370118af33d0e40a01fd3ea0f1f96d80b71924f55fdb017c784eec87",+ "src/oauth/account-import/types.ts": "157cf151ff51f28ba569f00ded3164d141987ac082b778a67150d1baa3e4d1e0",+ "src/oauth/account-quota-rank.ts": "887bf27bf4684f43331aacc6ff1b1b9296d9f09f8227d14814ca7a33f8ece04d",+ "src/oauth/anthropic-routing.ts": "0cae1a382e319349d92d589be77528a123aca5d65274732eb3f4de2cd4b2c076",+ "src/oauth/anthropic.ts": "e09817a0f46855c12678bb919d01611f5815357ace010940c67533945a0eff62",+ "src/oauth/callback-server.ts": "3c481c4b26bcaaee246aff098be3fa402e1c0f813adf0f00a4122af92d8d5264",+ "src/oauth/chatgpt-device.ts": "c3021b86c4c94b4b64bb0ee26d67e57cf0b155390a7a7a8d1ab56c8281c4ef8a",+ "src/oauth/chatgpt.ts": "ff709bd766df8e02bd91bf66b4f8669fa432f45cb7b875a263acd93b6d147578",+ "src/oauth/command-code.ts": "75ef37ec5186139f0a6d976c64b376ec1d7865463e97e5946ada291b194ad0be",+ "src/oauth/cursor.ts": "afc515c357f5bc9f788c07e40a0a1fce6ef3d9887759906e5a48113a720d5673",+ "src/oauth/generic-account-failover.ts": "b29afbdea7c75b02945a0d4b0a5f28109496e4784d33a17d0d4543b8c072978b",+ "src/oauth/github-copilot.ts": "e0bfa9fa518ffc9b04ec81090540cf614ca217ca7ca3f356bc6f74efb6b1e38f",+ "src/oauth/google-antigravity.ts": "c31b22b4e6152236290f53a0a155956da46408590c7c01850830ec4520b7da5f",+ "src/oauth/health.ts": "2546c5f311b8b43a0fb45c4fe355c0dc6623d7f89b5cfab0382149c1fb61b5cb",+ "src/oauth/index.ts": "89faf1fbeef4a91739c2d81668c539ea00385d7b098ccac5aef7e1e6ac9ea3f4",+ "src/oauth/key-providers.ts": "fd6abafb98e00c8f5fcdfebd5540574b8b10ceccee40ad5aabe4d6a84264fd2c",+ "src/oauth/kimi.ts": "cbbd772bfcf74c1bf6357d494b1b87034c59fbc9ebeda0ccc93e31df431d4a30",+ "src/oauth/kiro-credentials.ts": "240cbc9a961e2c5a0fb09b727ce88fbf33162df47d7f1de1bc39606a46ace267",+ "src/oauth/kiro.ts": "81cf6027776e471bf1cfa5122b79e8fb8db7492e905f1521ebc7edcea7861231",+ "src/oauth/local-token-detect.ts": "528369fcd23bc88a7ee444a1a6f0dd7a4601ab5403819d3e0a9acf1fc84f44b3",+ "src/oauth/log.ts": "bafd097b059bc2aaa81b1f0a50dad867ab32673218732ea592d7e84b5bc376d0",+ "src/oauth/login-cli.ts": "4a28cd6dad0c427a6517b2e273cfa9ed041d8a83b0dc56e97f109c043d437fb4",+ "src/oauth/meta-muse.ts": "6e14e3132fa45e90e3cf6bbefc5e8ae88b283f2282b5ab04a41d678114e268ba",+ "src/oauth/nous.ts": "49fb089b01a8a118e575069d2308912b7fd661ef882913193b0e9f4d8df28201",+ "src/oauth/open-browser-choice.ts": "f4ef3a89b0df0db5d5ae853378029e4983cd3a239cc97a36535350d939066bbb",+ "src/oauth/orcarouter.ts": "8bee94d25263e5ddf792a35839772c6927ff9c0ef15d44246d1c90fdbbb61fc1",+ "src/oauth/pkce.ts": "8e2798e44de278bc4db99ceaeded806e4d80a141f4d81bd81e4ab6fd22189509",+ "src/oauth/pool-settings-capability.ts": "47ae68efaaef419a60bf56cc5ecc35524b17ce54678aed75c6732efbe325f5d2",+ "src/oauth/store.ts": "09d92b83ef9c70a0c5d25562784d803633d6dd45569fb03f7dc9c8c86ca96344",+ "src/oauth/token-guardian.ts": "903e5dad757dbe5bd13354e4d7b19a79faa9203095498e6c660b0436ea873271",+ "src/oauth/types.ts": "c519696137b018881be64b76d75d8cb27666a234614afbd9a718e17cf1df7d3d",+ "src/oauth/xai.ts": "75873febeda264ad17634609ef071f08aa5e4a708f31c65291ea2d8e258277e9",+ "src/providers/account-quota-disk.ts": "771dda1a93ad4102f98934d127f6a25450985d1177d73d5680fbb7e44cf40164",+ "src/providers/alibaba-region-backup.ts": "dad4ff4e385764335557a1584d351097028cbc6acebc0e7080167ab3ba9276bb",+ "src/providers/alibaba-region-migration.ts": "92dfc8a11e4037ae8b2d03bc8ea6c76f79ddfbb3df7cbf50ed21ec432c71bf96",+ "src/providers/alibaba-region-startup.ts": "310b2a0575bdaea6bd7fb5d5ac8dba1228f8e383e258755b7e93c72f7ef01ec1",+ "src/providers/antigravity-models.ts": "48d33a66f89b30ebbb3679341850ffa1e679994702bd9799b1af5c5c82432a9a",+ "src/providers/api-key-selection-capture.ts": "fb1664a462cffb4985aebc97352bb85e64c631f01e27df3824ff0690d90ac52d",+ "src/providers/api-key-selection.ts": "cf1da602c168f6a0ac0a8fb8f979c95d1875cf1fa075faead4bdf8917b72fd10",+ "src/providers/api-keys.ts": "926c5004b355edec7434afdef1e28fdbb9b01b7071a0ad3e3f02f13b7185e190",+ "src/providers/auto-compact-budget.ts": "574d38c410f507f590a2285086b78b34318b01f233fabf322a6cef0b817b5eb9",+ "src/providers/base-url-choices.ts": "f75c050dd851d38fd90335def782699aea43f89930dfff95060fa88d9724a9a6",+ "src/providers/caller-authorization.ts": "474cf01fa68340fef4e1381844784db623ac0d9c38cc629a4f6964a16f8ece8f",+ "src/providers/codebuddy-models.ts": "e846c102e90b3932f2a5c4a64144daa6205b577cdcabf47089b52b001cd6dcc6",+ "src/providers/codex-capacity.ts": "18f6ea26ed34753f6a06bf2243d79ffeba1678cebeb2143c36bd0a4c9cf6c97f",+ "src/providers/command-code-efforts.ts": "a0494b5501e38f1296645825613d96f0ccf18344dfd2c400976b9ac084745a70",+ "src/providers/context-cap.ts": "886a124b10f639f6f7761d570df0168f9150d89cdda4c421105735bb904a8c3d",+ "src/providers/cursor-pool.ts": "26c8cb42be69a3089577ed9907673d12705f5496ede163baaf288fc2c288bfcd",+ "src/providers/default-aliases.ts": "190c2b85e92ff3d686efefa4c7dac0db75a4897b670e5ee5ff3d3e8055d4eb35",+ "src/providers/derive.ts": "f024f6b74f598fa663b6b427d16e031a593fafad3ca22d282e2c8bad06f99d8a",+ "src/providers/fastwire.ts": "702957c2b95d46f52818c1a3cf082e5351c9fb177f1bd0dfc2e0dfc4adc765c8",+ "src/providers/free-directory.ts": "994baff7c59acae168f6bc480632d254ac484cb16bfe859bd4cc675e2ade1211",+ "src/providers/github-copilot-transport.ts": "78c11415c8423eaf89a5a4e5fe8cf46b55a6c13078cd035ba9662369f895954c",+ "src/providers/google-ai-studio-model-discovery.ts": "4ee16b9712a50ec868010265f234b4d23c5082d761aeddfc051273b4eb5d3ce1",+ "src/providers/google-vertex-location.ts": "0e30a1dfd3dafa742f710c38d1c856d3f016c9b9ac15e748edb6965b93c59a5e",+ "src/providers/initial-model-selection-runtime.ts": "685886bb162fd08960ae43599ea429b1140dd52094c1ded308c29f78fd92a1f2",+ "src/providers/initial-model-selection.ts": "e0644e6470ec5e3292eb3c0d8ec4a33bd10efdd7a53168adfb594835b554bfca",+ "src/providers/key-failover.ts": "d0d62b784a34c82cf436bcff2978b91a494545bb4fd1b281f00dececfaca2e13",+ "src/providers/key-store.ts": "505246208f9fa354edd27ac25f458409ee11d302df8d54f3a91fd0372e0edfc3",+ "src/providers/kiro-models.ts": "81a323255ab20e27b1040178b01b9cf567d0411b4171107bd47cc9a7ba46be4d",+ "src/providers/kiro-usage.ts": "93abc9a38f96d80a31845f66285161c2626b517aef84f08d5d596510f7b40a94",+ "src/providers/label.ts": "be2c96c35f8913b31c3e11948b6ea0a2f690059be5662e372f71ca94c1e6d168",+ "src/providers/model-discovery-limits.ts": "bb6870dd31ec3f5336471f71f5ac4e80c4346c67665fe1f94c00f5db5413227d",+ "src/providers/model-discovery.ts": "947de0c9e2d96ea659325a18c2c25478d18050dc18479e9c9e9548527a5f0b38",+ "src/providers/model-presets.ts": "e535aef937e20cf43f7334e7c17f3ad5bb2364b3ff8e3c74a2bf5121e49f95d2",+ "src/providers/model-rename-migration.ts": "96e4c91654ae437ff77fe0811bd36a45086501ee8b38045b8ffa423791131c3b",+ "src/providers/model-rename-startup.ts": "a32e9a1660172990ee009df51340158588d4c1ffa397a95a63ca8e256167be19",+ "src/providers/muse-subscription-usage.ts": "e4e7ee3aa1632122177d2552137e1a97faedd5686b58d304c56741fff78fd564",+ "src/providers/new-model-policy.ts": "02c7c4000aa9a8bdd8264027fa4e07844f09c92eda516afec7c2270818ae1618",+ "src/providers/ollama-show.ts": "b08bfca5a2919ef4ddc8fe8999e663a3220634c21cffcd06bc07c59dae188d0a",+ "src/providers/openai-sidecar.ts": "60d6651d0f20613d20c9ccecb14434a8d1ed17719729ffee8e132a443e13edf5",+ "src/providers/openai-tier-startup.ts": "41256c1ef4b2271168a52dcfb3ab986077cfa8edc0386230a01f5b196155ca42",+ "src/providers/openai-tiers-destination.ts": "9750b2925dcad9031fb33ed9c5f16e617ca9d340ac7f9ed604810247459b5ca0",+ "src/providers/openai-tiers.ts": "a746a382e59383405a38f91fcb0f500c416bc9a766cd292ca0d082e6dfade232",+ "src/providers/openai-virtual-models.ts": "ecfc4e44a6b19342a5822dae75c84baef2fda29c716f0e0aff505d2173939cbf",+ "src/providers/opencode-go-transport.ts": "73734f2bb40ffe5eac5261b21077a98dadc7c957e1f1c79e9ff11613b952c5e2",+ "src/providers/opencode-zen-rate-limit.ts": "053dcfa187711c4574cfecaca05f3ee13806305a5b3ac245a74be1114c5d4507",+ "src/providers/openrouter-routing.ts": "1e39e9f483af63213b152f65fdd2be04cdc6c76f64424bbcff80ae38083e7521",+ "src/providers/provider-id-rewrite.ts": "a9dfea93d89163086e0c0c047c53b2902f7ca804a66c58e2f40333e28d6b9aa1",+ "src/providers/qoder-models.ts": "96dc3b7c3904b2453c786dc77edfd9319a00afdbcce5d015ed959c83b30d243d",+ "src/providers/quota-key-accounts.ts": "aefc0cefdf517fa10cd949c0d556573331410a4e973e952807be2856e7610a46",+ "src/providers/quota-routing-cache.ts": "4127d10012e852541e3884f2ab13057c555c2ccbd4fa7e336028f58b833d12e6",+ "src/providers/quota-types.ts": "9303de39c0e59d0d578ce73e8b1a1cac61a84b5d5105fb09b18195fc531c3915",+ "src/providers/quota-wire.ts": "9ec100a6173fae14cdfbfc6456ecf8035bbb1e91a81043ccf02741d7bf4e85dd",+ "src/providers/quota.ts": "bb8dd359cd0cd0ae751b959d645360e5fc3be6a48ded8a6e336e7295293c1684",+ "src/providers/registry.ts": "eaa03f044258d51d5d49c741ff73bde6bc582f20e6740b918ed64c958938a063",+ "src/providers/request-pacing.ts": "dd003015cb487945d088e49e6f92e3fd1692553f2181d5e00a6dbe6a503e26fa",+ "src/providers/service-tier.ts": "657fc25f91b481b8300bd260e464ac31ba96f287192392e4187e6b7f74f5b890",+ "src/providers/slug-codec.ts": "b3fbe9cfdad3a5ccde17d25820066a5175ee7fd709ae12b5817df735c71020e0",+ "src/providers/static-model-discovery.ts": "a5f71ae479374ff7e531a8c42a136e50d87bfcc6826ee11462c07196e8a72484",+ "src/providers/vercel-gateway-routing.ts": "dd6fedd791a6cbc371f2cc93cdb081090b339fe452a80bc8d4b8b100ff7bfd19",+ "src/providers/xai-responses-opt-in.ts": "eb5a2f9e0a2f08f2951054df71686c954ad9b3aa27377b177b032216a8647867",+ "src/providers/xai-transport.ts": "1ac6638465ad2b2a36603ee36aa53176474f9c6ca3253db0a43933ed7b20371d",+ "src/quota/reset-activation.ts": "97eb08abf8d5dbede7250eaa4e9eb8ade15b8512c2fbc9f70f5e4bb81a8239db",+ "src/quota/reset-detector.ts": "d0e380213166035e879a27fa2c39e6d81e21c518d78dee953b865170e8b17eba",+ "src/quota/reset-notify-config.ts": "1dfe6ff330547f0852d459cb660e1338951dce44b4b456edb4fd3b9d17d07302",+ "src/quota/reset-observer.ts": "7236fe8aa18cfcd5f269e41529d95408c9f3b738f91d35fbe302ae6a073db15b",+ "src/quota/reset-poller.ts": "b30205d8216a4ce063f64435cfeec9b563e884e9d6fc284e7ae688bea8fcf963",+ "src/quota/reset-seen-store.ts": "aa9368cd8fca414becba5132dcc9c1fb4662a8f0445d253e55021d6ba9e395df",+ "src/quota/reset-sinks.ts": "b4860be883a7dbdc6477f2dc0a8415b1176f64aa766d3835c1a1074b036fb3c1",+ "src/quota/window-mapping.ts": "6d2285e3c026afad26dd1456d23c6e1f001050d41c1b7784983c96a4a694bfa6",+ "src/reasoning-effort.ts": "9eb83f657f48c2582dd6846d3ba1e3f584197025c779bbece5953d552fac1322",+ "src/remote/hub-state.ts": "d0be22900aaca4a361ae03f010d89f89f480f471a80b8305907d670e35dd5ebe",+ "src/remote/protocol.ts": "0a4fd661b9a54aacecdbf1922f043e62d09fefba36a7ec40bf0d4d3a9af99df8",+ "src/responses/apply-patch-envelope.ts": "2145bd3995c8811c6f21510b606e32eea84809ea3d4a602ab252d1adc40f4fb9",+ "src/responses/citation-markers.ts": "95b0e17d99bab39e25aa599381839417c10702471c7af8cbfb0b587301c7f131",+ "src/responses/code-mode-helper-compat.ts": "efa332720f717230c9feb1ef5132f0f658af21604044649ceff4577299f59f8b",+ "src/responses/compaction.ts": "8ca98f68e5e6957e32762b9f6d006d53083bece1b086988560a719b701e7a867",+ "src/responses/custom-tool-compat.ts": "1545dee0ee7f29d0c489dc4bf3975984fd9648dbca5de50effc97f7df9adc024",+ "src/responses/function-call-compat.ts": "642c72c2d9aeaad9c6840059eaab33e3729733447ac746197ad122e3c18b779b",+ "src/responses/hosted-tool-policy.ts": "2c963d67c44c03d85273fdaac825f6b37bcc63257c5448b72472d4095aabbb53",+ "src/responses/namespace-tool-compat.ts": "29ab7614e0757cde8bf81ad86da407afc8cb6d05027da22375fcca9a95de63b0",+ "src/responses/parser-content.ts": "0e286170758455bee028c9a4abf5aa756d8025574915e68670e930cd6bb9812a",+ "src/responses/parser-text-format.ts": "123c762ad0457db0f2024c26a2ab2caaf12163a7262dae57b5b0c32e9f3ccda2",+ "src/responses/parser-tools.ts": "2fe62848231819b9f4b19491d608729198a353d051e22662993d71c36fa56673",+ "src/responses/parser.ts": "f6d3f2447c94680c246ed7dcda910eb69e5cd5eb8ba27f90e3af723d6eebae4b",+ "src/responses/provider-continuation.ts": "046113cf1e2b51329d4e04e1e966edf7dcadfcd30604a2beed65eb3cecc56598",+ "src/responses/provider-opaque-metadata.ts": "44acebbbd8efe49c974b2beefd6738a2d49e6ea707a425b08f59d3e776d0b371",+ "src/responses/reasoning-envelope.ts": "854af4fda4a4a6d15a1b9df5a4a73ebe010f9f372c5c3df9e887e3354e4fccda",+ "src/responses/reasoning-replay-cache.ts": "9d4d4908e890fc5cde7e93312138f85f967c549b4f98ff1ddc2e56913c55c692",+ "src/responses/schema.ts": "e6e83143c142dfc8f91cf592b0494aafbf44ded58b267d62a873e9de4820bfde",+ "src/responses/spill-store.ts": "9f00a1428339343463dcda5641da17bfeea9fa254dedee29d447ed006179132b",+ "src/responses/state.ts": "f90df1f12e7606ce18c078277ddc43697851d23eac799fd81ca2fc4471e96e5f",+ "src/responses/task-input.ts": "5bef66c5479cbcbf1b700ffc055595801772e3a627c6ef90b1bef97b922394b8",+ "src/responses/thought-signature-replay.ts": "4d1d65f8231af543f59e5493f2bb17f0a3c2f74f201e975812277462e5944843",+ "src/responses/tool-groups.ts": "b2750b33ec7bb5a7f76f27584bf99372fac4f253dd287849b2f3f9821db574cd",+ "src/responses/tool-name-aliases.ts": "19338602099c6ea9947200310bddd36b1f86ee93f5d5def2019182d0e71255bd",+ "src/responses/tool-search-compat.ts": "25ddbc4dd8f04ce43804aab64fdf5dcc402703529b8252d2c64bbb5749ece4a6",+ "src/responses/truncated-stop-reason.ts": "44a1876c045a63f9275410fb9169d2c47ce0c1de309e9cc00a0f51c72698a6dd",+ "src/responses/turn-termination.ts": "bdfad46010472abd180a2807d54b92795ec5d318607f97dc5c3cc59727e764e3",+ "src/router.ts": "7614fe021401289df2f2bdf5524b6faf9941015c780df9efaa8b1b5d27f04af9",+ "src/routing/analytics.ts": "896ca10c2364f61ede0e2759d26055a0c7ba24fdfd21aa55bb9e0fe79698bebe",+ "src/routing/capability.ts": "4568de82d6aa92d53ca2c4ff6370650ce5c5d2b4e536e422d305e39c4c300ad7",+ "src/routing/compatibility/assemble.ts": "5b870fa9b831ed5dc87815bb999d35e2c11912b0edee9a552675272ba2ed81c8",+ "src/routing/compatibility/behavior.ts": "99a85b286aa66b5f46a2f95b9da32294a1bb3a9e8c00737d0aafa45063b37476",+ "src/routing/compatibility/catalog.ts": "06671fb5599debd9e0833f686451e7adee3517952278d649136c6edd613dd9b0",+ "src/routing/compatibility/endpoint.ts": "38578440e02ce712f8d84fa97ec2d1bc3396f31983be9b6e5b0010ef6edd146b",+ "src/routing/compatibility/lab-evidence-provider.ts": "352a65b6d95c8e6eaa7e6f81fca49284b49a9ddf7bd1895be192b858784fd861",+ "src/routing/compatibility/policy.ts": "d903d561ef2ae16c86d16c7ec157556ee0c78557aaa7e83dad46c1abc0e6530c",+ "src/routing/compatibility/provider-slot.ts": "9f02fa21cfac67f0903ea1141d4c4e8b604435393b25ab16dce823721eb4b51a",+ "src/routing/compatibility/reader.ts": "c48943c0b660609bbdf4d47896de6338cd46b2c9144f1c916646221fe437a678",+ "src/routing/compatibility/subject.ts": "af2c43d2c593d119bb3fdbceb81757f17fce44165f16a795eda0259b9bd8d25a",+ "src/routing/compatibility/types.ts": "287448ce2c6efa68d68656fff89574b414b7c3a1d401820be1f59ff6c4170536",+ "src/routing/compatibility/version.ts": "32b97a1fb10447309f5c4788df6154e1264f27efbf5ba498722559d69f07d56b",+ "src/routing/cost.ts": "bbec36250ff804aee460ec08f2d9a9b8dcfe101e51dd512205f88ba391c6afcc",+ "src/routing/evaluator.ts": "59b2b315820717b6f7220719a8f93fd850687e452b1df1ca83ff38b592357cdc",+ "src/routing/health.ts": "5bfc824578e2c04357d4e4348fcd94014a46263531d58417d747aadd29ac16c4",+ "src/routing/history/cursor.ts": "5437f295133cdd7a1817b3c3dd220cdd4bb43a7a250c740dcf4037172c32f6dc",+ "src/routing/history/indexer.ts": "bc5265d4e33a8b2c1fd8bfbbf3479c6f31c6455c74a59edfbb42fef7c8eec459",+ "src/routing/history/schema.ts": "289b655f265ae752df56bbeee6839e648f086cfe18076585bfcc1afdb6d84a8e",+ "src/routing/profile-namespace.ts": "aa27a35e3002359c1425c2a76f224e415238ddc215b3e59535010afaf72b1c4e",+ "src/routing/profile.ts": "3ce7c68aff2b8b646d48c5c14b10336f0cf699df46ccd7abe0bbaf97fb939e06",+ "src/routing/quota.ts": "d2624d589ccdfc92cfbc0c5cb6a7f275c432bba9c098e8b915c36ed734d12c9e",+ "src/routing/request-evidence.ts": "ccc282cdddf6f6803b6d061abeab5dba312447ba2348139160ff18834cb88a4b",+ "src/routing/trace.ts": "4c4160a86433ab1ea8825b81e4838ee7fd401da6fb3325cfa9d9dc409da7f2cd",+ "src/server/adapter-resolve.ts": "82c41afe2ba5cc6a1ec675345f92d933987d47d0f90343ecc68fe34b3ea22352",+ "src/server/auth-cors.ts": "a15efd0f68db1cbfb3dbee1bea4e8b2105e159643a98afd1c2e662d7692b38c5",+ "src/server/background-lifecycle.ts": "d653fafa1765db4dd2378fbee281f1f9b99131145c1c8fc68158de39bd12571e",+ "src/server/catalog-download.ts": "4ab2299744831509f34a51cd92a96ab73dd997c3007db746e93a897559f5f472",+ "src/server/chat-completions.ts": "27ad55992328419982e12830223257df67ff6911aa97a119f78b245d5acf86f0",+ "src/server/chat-native-sse.ts": "ddf56df7b59df2d5d818c7b394f11dc3d0948adf00e14fbf4350c652dc9829bb",+ "src/server/chat-native.ts": "f4a31b1f294c93b4ec52b5a7c0c3bd9e0bfe06bfe0ca03e0c6ae531712eda44e",+ "src/server/claude-messages.ts": "15346a4597992bf9d047e29bbc39b2a53b4c2919d3df6f7331605795e21d439b",+ "src/server/direct-local-http.ts": "4cdeb115d076e6efbb137b532568f826b5760acd4f99e902e0f61833d98b2f39",+ "src/server/effort-policy.ts": "7245e9b3546d554a282af47f80d06b84cb61ab6197704f5a287b06b1838839a0",+ "src/server/effort-row.ts": "e86afad04052e7efef1c64496cce8262d6fb7680f735afbb076c53db13bcfa42",+ "src/server/fast-row.ts": "1880dc10c3c8d9d22a5a9838f23953c110f3cbb84732abeee15e2fc8d5e0abcd",+ "src/server/github-copilot-responses-repair.ts": "7cff66ca0b8e1b4ff64e29c3b353d876d053a9612a0c357ea5af9603c8400629",+ "src/server/grok-responses-control-frame.ts": "65c809ec37742b3a35d7d18a6f98cf802f414a8485755f1140673fc8a9e21f7a",+ "src/server/grok-responses-snapshot-repair.ts": "d5a84a2fb2b8707a30fb5cde48342968af2a0898a5e92cd843faa53e0cb73ef6",+ "src/server/gui-session.ts": "20cfd02871fdac992f1b5a25149eedffc8b7a962d0fe6b52d5b59e2ed1fb0464",+ "src/server/gui-static.ts": "5667d324e121b213f45759c2e18f3c9c75c96b45b0dcade32d53633c2a08af8d",+ "src/server/hub-state.ts": "0ba90f574fb32670d14f4d607eb1444923f48eee7b6861ebc792f76e53661189",+ "src/server/image-retry.ts": "c7024f3da1578d35bef3ce06770051ceabec15a04300b41b3dcf640f28c82b55",+ "src/server/images.ts": "da1cf0777f53d56c74d2d3e9586ed2e4f2acda609b7c3544990a9595b84ecacd",+ "src/server/index.ts": "79cdbefb79eed034ab976055f731d3141c0d8460e01a3a4371952d5dd2202947",+ "src/server/lifecycle.ts": "2d91d67e9dd1412dad89a88b3670587ccd31f42a6ad564cd13f88e1ef2509095",+ "src/server/live.ts": "5e68c7830a9a143f218bed2686dd794d0df7aa9a79cacc118c11b13690c630d4",+ "src/server/local-management-read-client.ts": "d5603e4887568dc7a4a854bd56849f35a62c7eb600f3a79d2ec0c41764463915",+ "src/server/local-provider-reload-client.ts": "ea92a85ac9fc5b28b396c39f753f10b07e120e6522579cdfe2ac07177922b104",+ "src/server/management/account-selection-stream.ts": "bee57e7ff98e9e4288e8e556f019a6a9fc87497768a8eec772d16e44c45be895",+ "src/server/management/agent-settings-routes.ts": "a771aa9da4a4b2b0efebd4367f10b792347881baec056bc375ee8821373f8df8",+ "src/server/management/api-access.ts": "db8c4d87ce0d2f6770f29b392b3da18d88a77775ef3e3d84d36a695af4520b80",+ "src/server/management/api-key-rotation.ts": "ae48461dd5163d331c9270e4713285b36b4aa5c83958713ac8e9af27a376ed75",+ "src/server/management/api-key-usage.ts": "b43e83b249ad82ba1f4f04504c0a19ddd5d7e4f5a23292eaf2309dec58838a3f",+ "src/server/management/aside-profile-routes.ts": "5004537275dc7ba0c40d218ab85a5d1de10e64649fb0ba1ac79fed10080a3f9e",+ "src/server/management/body.ts": "3839e768c3a698faca0d3213eca9187d113f38ad60b5c47fa1849347ca96e20a",+ "src/server/management/codex-prompt-routes.ts": "0e2eb3d826bbe082fdc1a5f964791e9c4f04b58be4713804ab371b186a400470",+ "src/server/management/combo-routes.ts": "832d87b6ffa4716e3e203a8f704dae7691227433536887d910769bc823aa8e7e",+ "src/server/management/config-routes.ts": "efaac40697e86d8cee5e7bdbb8ce6d3316e795994c4a7db54d0799ae2677ce71",+ "src/server/management/context.ts": "e5b56be133796f0c8d942e0912e499c465e7fa7bf06203e0e59929b561791a19",+ "src/server/management/cursor-integration-routes.ts": "b277f6f26c89d9ba993767258b61a879fb693747e2455bcb8b39f0df90c7c14b",+ "src/server/management/integration-routes.ts": "206da4ffcb06f4ad5b4fa47d767d03d148b513b3ec0c6ff4fe2fcbb3b6ea6971",+ "src/server/management/lab-automation-routes.ts": "74e94c24c5a7480c5d5a81dec472840abc8318875e29c55e07ea6c21efd08462",+ "src/server/management/lab-routes.ts": "4901b20e19f8c61edb3b5085cb492e5b16673b58593cc853a68338a2b30015e4",+ "src/server/management/logs-usage-routes.ts": "ea333850428a1d55170bd10edbeda850ade63071ba90956402917a2cd8eb48bb",+ "src/server/management/model-routes.ts": "758e3a528375331c180ff3a3287dfc7d03593877362551dda80f4f7148531ab8",+ "src/server/management/model-rows.ts": "e4b54304d4488673b56b109b9ce7e09a6e9893801288c750f1efcc9b30f5c24f",+ "src/server/management/native-integration-routes.ts": "78b0e9740eb7154087d66041add0365a7e2cdc28b81687af15a7f817423ab188",+ "src/server/management/oauth-account-routes.ts": "2e35a9bda8cdb6807f6a83d55ec701602c1482469ef86c6b709e9c4cf9bb65a2",+ "src/server/management/provider-capability-config.ts": "46ca4f28dd0fdd9073865f4f51a50add1c743b28c50fb23704e1f06ce70a1f11",+ "src/server/management/provider-routes.ts": "8fee28f9ffab897af5352b1bcd4325d20f958aacc149ef6c47146c1a471dcbab",+ "src/server/management/quota-reset-routes.ts": "a8f8541801650c62530d304c7e8151dee700ca05793c6ea27927d62b1a534c9a",+ "src/server/management/request-history-routes.ts": "ad08207130fb23c0dfa30600bbfdd603c6b3a60d017a5b5cb8981dbfc77fd1af",+ "src/server/management/route-registry.ts": "c45a547d396e70fa633831eb111ffb53140cea3a508e33219a647e93d1c99729",+ "src/server/management/routing-analytics-routes.ts": "d6cff11ef0a4844095c4b6008b2dfe745ee3c3c5d3ef02fd70518cfee15c6258",+ "src/server/management/routing-profile-routes.ts": "d7400986805779203c3d78d0a7b105f6464c8d18bef11ca4ef25eca1fe07998b",+ "src/server/management/session-routes.ts": "47c58cdf441aea0908bff140280147e19a9716313822e07a357ddcc2decfe3a8",+ "src/server/management/shadow-call-validation.ts": "ee8856f07e7a3d6c6c9824c28da8888dca36989fe65f1f6a6239c35d89352c02",+ "src/server/management/shared.ts": "0111e4205d35487c8f5ec18245cfc682bb9a0fe7f925ef7b462c6a142d82e52e",+ "src/server/management/sidebar-routes.ts": "0926c61288d6344456516c4208ea788192739d5d4c47c5566baf861313b75301",+ "src/server/management/storage-log-guard-routes.ts": "76491da8b595410593405d8ae7fbfa0b870653277f801b75c01086fa69ca3445",+ "src/server/management/sync-response.ts": "580cd5b67c1b1c7ac2a25262da00dc4dd31c7959e506622fc13a2f240d800786",+ "src/server/management/system-restart.ts": "d550ce46371882aab29866246b121e5b2c65ce31765889b32c67e5295101ebfc",+ "src/server/management/system-routes.ts": "ecb096286c4d3f9f14965845d1eee14daec5a688b6ac2407221e8185708fe852",+ "src/server/management/usage-aggregate-cache.ts": "7663d6a1584cabb450e728d812bf7da0825c8071ab69523eb05a350363baec77",+ "src/server/management/usage-summary-cache.ts": "2c3f036a2bb01d0adf156397feeb69b20574b1e3325f028ddf30c966b09f5a67",+ "src/server/management/vision-sidecar-options.ts": "797f8328eff1a0eedc3a3c4345ab00bda62c39af7c141c60b1f3d8c7f7f0a798",+ "src/server/management/web-search-sidecar-options.ts": "b62738c5ba15a9c37d54c74850bfea9f8a6d928770565c253a92ea05bca72810",+ "src/server/management-api.ts": "d09313a12780ebaf2f23fa9c7a8b3dba3b3725bd5aba4971970860afb8fbbe21",+ "src/server/management-auth.ts": "4e3829e484be143121a332287e15251bdc19f7fe720851a15886b28e4bfece02",+ "src/server/memory-watchdog.ts": "d2f7f5cd03316cdfb0bd23abd77b4c28d87986a9a1cb9e0f53e3890695f07f4c",+ "src/server/models-capabilities.ts": "30a0c40cb9f6f53c03fc125e6f69f7c5f4ff84144dcd1af40b8c108b17bc3d28",+ "src/server/passive-route-linker.ts": "1cf21be7d35d87f6642358ed3f068c5fb647099da52f68b49d1b5535c84cca14",+ "src/server/port-reclaim.ts": "ba9894de11ccabcefeec2bd39921b729b893fcfc4f10c5ce4bd461f54cfdffb4",+ "src/server/ports.ts": "ca3cab24064280971ff3b3a11633a7c55015d5f95568e581f98500cca9892e37",+ "src/server/proxy-liveness.ts": "aa65e28c10b2152c04d7cce9a89938e4f555fd7265826379bcc7e4cf61aeae0a",+ "src/server/readiness.ts": "d7a0cc4581ad8da8c06bc85182a02c2052f7ce6ddbc27ac5b2185e94ddc9a8cb",+ "src/server/relay-eager.ts": "fdb94f2b2433d23bc273e785e325f190ba1cba447a427d54696356e2ea830921",+ "src/server/relay.ts": "0fd1843a6cfef03ac35ce43976b89a22a70bd9631bfb327d8605414d2f78c223",+ "src/server/request-decompress.ts": "a631097fb0e50b92436e4117f6012aab020e35e31fcbe9fb744740d6a88fa6d2",+ "src/server/request-log-conversation.ts": "997162377a7c97a7e1a6d1b0dce808f68e61aeab64a42fedc16f3470a26620af",+ "src/server/request-log-cursor.ts": "4ccac2e6a8741d3a745fcd6fddcab182bd6f7193887ef1473c8d2f27db05baf5",+ "src/server/request-log.ts": "544bf0412e35f14b0135db94c50f23fb46af5dbcbaa3ab5b98104609488c563d",+ "src/server/responses/agent-task-recovery-cache.ts": "73944718c95c4f770c5dadfb7f99066ad5993c9bc9edd107c8e3e3d103dded1d",+ "src/server/responses/agent-task-recovery.ts": "281ea00aa47e4a980a5bdf80856b1a69788db4ade9ffbcd7485daf211759cc27",+ "src/server/responses/codex-auth-error.ts": "75dcca68c89be189799ca9196531662319e1c8dc967323ff6ebd7cb5491e4aca",+ "src/server/responses/codex-ws-correlation.ts": "2decaefd490915acc77b185c78b1a56ffb313c2c2365a8f32ec48fda65117b51",+ "src/server/responses/codex-ws-exchange.ts": "7e8f4101a15a11c0c830c19fc5269d6ce4a394eaa83afe77bdaa503c8fb6d049",+ "src/server/responses/codex-ws-metadata.ts": "fbfc4aaf749ada692feeadc1249d4c2f070896d3cdb6496803d4eadc93c5cccd",+ "src/server/responses/codex-ws-pool.ts": "c9573ac68b1d9ca9626d4b0892d05cd3012d216fc69c343405eb899e1286bebb",+ "src/server/responses/codex-ws-request.ts": "87a2d3f358f2537c777cd3dfd094fe65fe14344f15e2617d89990d89f83621f0",+ "src/server/responses/codex-ws-session.ts": "3471205712bf7105971df4f06759e2816e74443190cdbd4befd877dc587c3c7a",+ "src/server/responses/codex-ws-wire.ts": "9c77f0c024b4d6e697c5f9f5295043b07d905317bd011856a2c5b794a8c6ce98",+ "src/server/responses/collaboration.ts": "ffd395e9f59c27a388d16d1d8d6fb30654fa81e3b296877beff11eab35f3d8b1",+ "src/server/responses/combo-session-recall.ts": "4401cbfadaeaeff14dd14c8afb25f0b8e61cadc1009393b35fe9bd25c6796f20",+ "src/server/responses/combo-stream-preflight.ts": "5e3d4cf23dc3cdc67ed49ad7c4a185419844a01e65d68e523b5a98b51120d406",+ "src/server/responses/compact.ts": "1007f2143ec8def46dab174caa0ceaf78054b4f7c757f24fa320ae46f2d8f917",+ "src/server/responses/context-overflow.ts": "b04ec1c780f61c90b3e5cd38ee0497eb87090a83c84f245ac1bb54542088b775",+ "src/server/responses/core.ts": "1c9530053a1397d63dd176bcd12d606cabac01c7d9b9691fb1829739cf176c36",+ "src/server/responses/empty-completion-guard.ts": "069cdad33a1fd996d37541d13be189223dda4971e2e54b9bd65c76dda97102ce",+ "src/server/responses/encrypted-payload.ts": "e9a5edf2ed2c9bda8e5244e50687b3ef9526841a0846fa325ce9cce6209188a7",+ "src/server/responses/fetch-helpers.ts": "d02e3ca2f0ab7611ff13db9d55f5dad7bc67b9295cd68edb9f2b7a655a182a33",+ "src/server/responses/input-admission.ts": "7f11d5a8125eeb5c3734696ba8d307107cbde2681077d7656d6911157c6b7d9d",+ "src/server/responses/outbound-body-guard.ts": "d6073c677abe1a00ea85991b6a58335e28a6386ec88baceeecc84642ea437cdb",+ "src/server/responses/pacing-overload.ts": "8452743c408082ed87edc143d5bf6e3ea9776e9249bdb6edfd1298eb595b7d9a",+ "src/server/responses/passthrough-error.ts": "5b33a2c8f9e5798ea995e3ffa3b3f93f64b7b8ee46a3c6fc99c83664ed90abee",+ "src/server/responses/policy-fallback.ts": "fe9a5057df4337932b67ddd5e70c9e054ee2ea5ba1376728da9807acd261b447",+ "src/server/responses/responses-field-backfill.ts": "4374724d6a107d3f1766efcd964459c4c749cf767370ab4b35c5130357d8f35f",+ "src/server/responses/terminal-guard.ts": "cf14f438f183ec51bf71c43d3271d5df85c1c538ed445f55335ea64ce210b2ca",+ "src/server/responses/upstream-error.ts": "bd0d3d5d7c8c98fd023132ba78a1a5e260d499bebc435200dc1e5e51ede83baa",+ "src/server/responses/ws-upstream.ts": "47a1ca10d4697fafc07d7d9547959c4643a22fc3ff18bac8393b06474a40f0eb",+ "src/server/responses-custom-tool-repair.ts": "9b29bc429d83cd5ab46b358eed46356514b88f9508716afa8080b93dca848f84",+ "src/server/responses-function-tool-repair.ts": "e32fc0a7669cc6c085c3a6287f3382bfc12223dc78ff96cea90927fc3bbaa0a6",+ "src/server/responses-image-gen-repair.ts": "c6e6e60e6ed87c17058f3f19f8c3ac159a11eb0d9dc90da536906a7b78524afd",+ "src/server/responses-item-id-repair.ts": "02341fe16358093c2b57f816a5ae583d49f3b48c486cba8e9066175fe7678e39",+ "src/server/responses-json-events.ts": "1e713e30e76ccc0b657adb18fdc2ad814bea4158df944cb41346f08e9e0faefa",+ "src/server/responses-model-rewrite.ts": "78ccff83ff54f7687d1f5ed04e326a17a9a37187ec470947ee960f4266a34a4f",+ "src/server/responses-reasoning-summary-rewrite.ts": "9a49932cb6bac6402f8e57f3188bdb86e3671f6fe55d1711fb84b9ad81b1d487",+ "src/server/responses-self-named-namespace-scrub.ts": "fe4a833cbc6ba27664fb7f4892a9ac6982b1dc3c84d5a950f08955dbbdd7560a",+ "src/server/responses-snapshot-codec.ts": "37bd6288b65d0bfe1cba21d9608412ab64ab8c4e6a386e94e340497eba5ede8d",+ "src/server/responses-snapshot-repair.ts": "082997b9c23a1238aee5ad341d7e083cf86ea3c8d62126c035e4c0c63bacc55b",+ "src/server/responses-terminal-repair.ts": "2d4f00a617e9c4275d3350ce7ae331e8bde8fcab43aff45542ca0b0afb7c3f6b",+ "src/server/responses-tool-search-repair.ts": "7462d6b58dc03d2b520774b99fc2c8103a20e55ab758eef19831df906bdde86d",+ "src/server/responses-undeclared-tool-guard.ts": "8570d91b8a5a2a4b636de2af8b75855d59fd28905783fad24da6fb2d43303ace",+ "src/server/responses.ts": "b5a7c538e73c6c5d1245faae2a6a8968f16870796aa2c0bdbfb8e19fe2c95ed5",+ "src/server/safe-response-headers.ts": "44ff47ac0ed062ce65d0e89855fec20d68fb02f2432bf73fdccbe567eb93345b",+ "src/server/search.ts": "baac289b631692dbd829a50af80831d1d113d14d29f0961c1c4bb20e4f38f3d0",+ "src/server/sse-frame-buffer.ts": "16d991c67b25bf3c848d47bd6ff01e3b2e24b16be5f2cd4a266bb83591319924",+ "src/server/sse-payload-rewrite.ts": "c1f631a601557f630d27caa95a9676e95c2aec509b4a76c7022bef8d7e878600",+ "src/server/startup-action-control.ts": "171d2d5200c31b226ac74c45920b89fb64800da3c98887872a1001aa88a11f63",+ "src/server/startup-health-cache.ts": "af752edc08b6c0b973c0abb03dbbb8f494d894716d5f437c1ec3c7504531324b",+ "src/server/stop-teardown.ts": "8e0dcffcc7e2acc0f8751830a623fd1a4f9b81e7e09eaa6e67abd1ef319f01ce",+ "src/server/subagent-models-startup.ts": "a47381691ed2b4380959d58db85135dd09e30bcff3c36a34a5dd67d7dd3f4da8",+ "src/server/system-env-shell.ts": "97103c4727b86b4685c03da1c212644f35dc21150a80db9f6dab800a6eaa9607",+ "src/server/system-env.ts": "097113ecc7c43d2fc1547bad639516ca3450b3ba997a982124356ccc2be6f010",+ "src/server/windows-tcp-drop.ts": "808174ceb0f3cbbcc8b23d727c9da947527c5680d4b9655d84bc950e805cd565",+ "src/server/windows-tray-control.ts": "ed950e098dec75d63e7c4472a8c1ea5de730cb2a04aa4aaeb56e56bce855de58",+ "src/server/ws-bridge.ts": "c263ed5e69ace9521ea3ddef225ff71ae486afec01fd553efe45763b6abd0b5d",+ "src/server/xai-responses-startup.ts": "8e6524f420b4917c55465609c69af28ad8373374c8c01ef89cc4d0defdf366da",+ "src/service-manager-probe.ts": "a639b5717834b0e98043c41a3628957e571682e23ede0f5332880c2853cb25e2",+ "src/service.ts": "8ebd05fbf18e79a8193e4411cbacadead2e032302f8d21e1cb7ed24c11615246",+ "src/sidecar/auth.ts": "5c8fce4c6677858826c626cd43ac9e59871f7677e155bff036320ce65cec8bb3",+ "src/sidecar/candidates.ts": "9248b5d5b213d15de616cf4546dbe4af12b7925f7ef260253c6367acc303ad8e",+ "src/stall-timeout.ts": "abd4f8883bf90e2e84495a72a0cd59ce2b2491416396f9ac01e075fef164a0de",+ "src/storage/cleanup-job.ts": "1d6dae9c9f8aac7e07f12c60ce1b67211a7b14356c285ef0b235b620a09d03b3",+ "src/storage/cleanup.ts": "09cc65bcc56b95493d942c6863c7da53a97138cc30dbbec54bbc07137a68e38f",+ "src/storage/policy-job.ts": "6c2da43d4aef0c5cc0fa10e70148c0e5c98666629f32e785c274e69daf448263",+ "src/storage/policy-scheduler.ts": "e25d3879b05dd7fe6f27cfc7c51ff3f715f937be7c55c11c61be3e1570a7a56c",+ "src/storage/policy-worker.ts": "e4637c162efd2f91cf291d9eecc575f71ca8322afa1868146e4a6f387bbaaee7",+ "src/storage/policy.ts": "b9192dd06aacfa90f263a86c7dcc62da4a9f1a640f9fd44df0c5bc37a6ae6113",+ "src/storage/restore-job.ts": "b3bd80c88d96cd79a57fb964f58b3134a00d556e56bac01f5d4718515306048e",+ "src/storage/restore-worker.ts": "a74ecc8a3ef5d1991da15bcb24a60d43c877ee1bd698e65f0ba86d97750bf96d",+ "src/storage/scanner.ts": "4ccceefb2cd14e4ed1d371a547bcb7bc87b779f7ee7b369a765a32b1d39bf9ee",+ "src/storage/storage-mutation-coordinator.ts": "ec0eb359b2034bced073a32aa2d1c7904794f75cd81fdafc830c252f5a7d575e",+ "src/storage/worker-lifecycle.ts": "d7c7ba4be4cca53c65b7bc8a3fc20278202ca6c8ef1fa1071d7d1812567fde13",+ "src/tray/assets/opencodex-tray-offline.ico": "20a3452c2e8ee6a881c3c99b92b09f5b473d1944e98a5a681f2158f848f7a9a4",+ "src/tray/assets/opencodex-tray-online.ico": "55496f5ec5fd6025bfcb5c252355ec67746cfe606b48b0068e9b45941091731b",+ "src/tray/assets/opencodex-tray-warning.ico": "1b91a553ca154f080ea542e50f0786a21dba847f15d5fa9da37200d24849cab0",+ "src/tray/assets/opencodex-tray.png": "de6aafa7d193eecf0ee8905e0230417afcdd11971a2272e4cf184676fd7ba90d",+ "src/tray/windows-tray.ps1": "68ab514c4d70f9465d03aa3d0fbdba0bc4b6e8b8b2ca6ffa83689868a1efc4b6",+ "src/tray/windows.ts": "09e18b70f0edf677cf73905e28e9fd728db19eac00b416f64371c1554adcbbfc",+ "src/types/accounts.ts": "16d3698f4dfcbbd87b5fc8656f1624d54cb88133e73dd1df99c43db01338dff3",+ "src/types/config.ts": "2adae2e68921b01128403e43f4df72eb299ebf03011e4e6e7c69c2388cb60c7c",+ "src/types/provider.ts": "b97e8bd5f3f82dae9cb246cc71772f61a6c5eb9644f2204da16e25ce7b0c19fb",+ "src/types/request.ts": "ab409fcbf3068411f35d4192e42e8994e49ea1dd1ff4eca4c065017495e5c13b",+ "src/types/tools.ts": "0e2cbb7bf64aad984d6a453dda2428cda2aa994935d20968bc39817b675effb6",+ "src/types/wire.ts": "ce5d1a7fabef76c800b469bea4a08db0e45259e54e19b60b7b00fbfb85d28973",+ "src/types.ts": "4a8c13fbedde0ec6b3e0e1fab7980f561c7b710cfbd4e96c026b94cbe5530d6f",+ "src/update/badge.ts": "32a1aceac2a702598eea592adbacb42901cb672eada4fb16a324f12f7960f7f6",+ "src/update/codex-cli-update-launch-policy.d.mts": "78a67e9e83690ce53b696264c7e8fa5efb6f8245d0db2cdf1cdf7a74b0e05ccd",+ "src/update/codex-cli-update-launch-policy.mjs": "58fa63c59c80361771080b49815e5d3fb37e35cd6616c60408d472b4ff691354",+ "src/update/index.ts": "1240b3c13474a2b78bcea68c05f25fe240b81e9843616a223fd5afe270baf4ed",+ "src/update/install-detection.d.mts": "909f52ac74086b79369a2030c03e19e46c0c55a8b951bc7915a4c70006eb577f",+ "src/update/install-detection.mjs": "dcf67b52dcf1fe06d02500f277a591d9b3fe462450018668a802074c08251cb6",+ "src/update/job.ts": "bc758f9319f29555528b406ab5271e507b59da47a8c64590eefd1d065a4ca5dd",+ "src/update/notify.ts": "f427d0a2d4ac07de402742ec5299fa160ec60efb3a81174f34c2a4da3e836341",+ "src/update/npm-cache-preflight.d.mts": "a1356e4258dbe0c50e8392409002d9e33b41f53e545c01bb7dcec213e541fe68",+ "src/update/npm-cache-preflight.mjs": "e6acc3bcfc617bafa963015d12302c2dbd397dc52eb7c0f59c3fdee52f55ed8b",+ "src/update/npm-invocation.d.mts": "5ea407241c83cf54e17a383ef56f069d5aea264c6abf518df02b5e2f6db1ef36",+ "src/update/npm-invocation.mjs": "25292222b9fa1ed00fc01164e9e9f25e82ca1820c73c20643171380467b4628b",+ "src/update/pnpm-global-install.d.mts": "983b0e2e8add02d90fc2504b5595fe75db38ee06614957058458c969d81bcd0f",+ "src/update/pnpm-global-install.mjs": "f395e7fa2063d28b2711721b050446ef21bc902eaf27f25d63b3c81d3bbb467c",+ "src/update/pnpm-invocation.d.mts": "d8441a22c1ac8e563ac55d76c22a9991821274390ab6abb6a8abe9e618d35383",+ "src/update/pnpm-invocation.mjs": "aa0d16931bf22e0ebd48ad910ec994f47b512d745332fd1fb505bab38a699f36",+ "src/update/proxy-liveness-probe.d.mts": "14b2051f2e14542720190a02ee950f1cbd79eefd044380a735c8e6a53edc5864",+ "src/update/proxy-liveness-probe.mjs": "5edce8e566742a174f4262a124b62d8b69120117ff622398f09105fde2361349",+ "src/update/registry-integrity.d.mts": "2fd62581afc1d435c6416accfdeb16ec15f68eea8afd97e5cd1d20e7afe72cb9",+ "src/update/registry-integrity.mjs": "7f0a9742b729f5dbd7acc08d2dc2452f4825056624fe8890fb34cad1196b3273",+ "src/update/stop-contract.d.mts": "e284b5830ee058aed46f09eee2cdcab7ddca54cdc4564df07102fd080551461d",+ "src/update/stop-contract.mjs": "006056e10a136927c5bc5e2afc047064e7f7516827ce3646a6e7717ffd9d548f",+ "src/update/stop-decision.d.mts": "23cbb6e3ecd1051b0258f7fe4cea8ce54fc6e39c997bd73e3fe17df538f332e9",+ "src/update/stop-decision.mjs": "3e9a210b820171d03f862a094077da6623c047e113b116d72d73b830cd0adf2c",+ "src/update/transactional-install.d.mts": "bfdc2d32da22b96787af7dee00deecfc09612620a7a30c41b3015478f426d476",+ "src/update/transactional-install.mjs": "76f7a377e904d3f180ed7879390b3794c203079d3e2c274d6e74da7e3b9c3518",+ "src/update/tray-update-plan.d.mts": "d8f3da715ba2ced1a52d7d08f0bcda031a25e342a3a879ceaf7a5244e21020fe",+ "src/update/tray-update-plan.mjs": "d9fa1da75a01d29850d1afa0fecc42a094a4b48a44360e2ad460aa6da441dd7d",+ "src/usage/cost.ts": "c48f6f846584d62242a24f6431c6dd379b7bdf785abfb0e1b1183d0ceb99e06a",+ "src/usage/debug.ts": "4968569b4c7dd4b1e5e0bdb062495a1c21117dc294d15637458728e094967a65",+ "src/usage/expected-prices.ts": "4d0233c378c3dda6df95e58b8826fe1d34425d360f522fdba8f8f2aad76c11d3",+ "src/usage/ledger-scanner.ts": "2e7d8e65319a34105f8e7f3e9701c9df09b886156b8dceccef13ca6cf43754c4",+ "src/usage/log.ts": "49ad54dfacd1d9ca92121ac10bb0bdb4f4f6463e867232e782e2da1db6c61757",+ "src/usage/model-identity.ts": "cce96d46d807f71fdcf161dd9977604d5396ff0dffed96db4ae7be101c043e76",+ "src/usage/summary.ts": "ef0c5645c34087a5855cb364cc3e3b46184a109b1a77f56147db275cb19fcf54",+ "src/usage/time-range.ts": "77155f4bd28faca0d53ec68e78c4d281e2a1ebf05297fba145bf5f8da04d65c1",+ "src/usage/totals.ts": "491e89fb39d06dc33b305d5d130bf956841106a13a7ee200fdc35365d860882e",+ "src/usage/user-cost-overlay-reconciler.ts": "5b54f9dc49124fe2ba607d7b0e19acdece88dc32565c3003fb3eba414c8804b6",+ "src/usage/user-cost-overlays.ts": "3f7da5c041838f7cf33ed91b335cc20aed9ba6277efbece92a55e0dd2b47fe6d",+ "src/vision/anthropic-describe.ts": "79ba364be622020e81b176a6c88706b944a1eac247a18b5565cec5101041f274",+ "src/vision/backends.ts": "f330298c7effd21e26fa200858b44742a97cc64100be2f84964faceb35a59eaa",+ "src/vision/describe.ts": "108c3de11142e8bde3516b976620a4ed1d6a7934de8c6e29e1fe2f573a202e6e",+ "src/vision/eligibility.ts": "232243b48dd985eb57f6cd3ec2bfa39f943965d878828b5164b594614247df5e",+ "src/vision/image-rewrite.ts": "a6fad4066936a296ba81ef633b2f205cb230cfb62078fcf81a11f4a9950f633b",+ "src/vision/index.ts": "c258cc0e8764b3bb6d3460deb446d148c1e7c67374d6cd16ea42988de9792494",+ "src/vision/plan.ts": "06d54c9c89584992f77118a8841afc55deb7daba96d467357217f9ef7f948a92",+ "src/vision/reasoning.ts": "7b5ba571d9e727304f9cc053baaf82a5023fd2dad92f7fbf01af7edb8cfca21a",+ "src/vision/routed-describe.ts": "28b6eb15d7f2fe2c8dc8665705f6b35a0cb1c769c0e62d8677316897d8096fc4",+ "src/vision/timeout-bounds.ts": "65a3124c6817cda51eb529520652576ffb1e92db433112162c0065104954eaba",+ "src/web-search/anthropic-executor.ts": "c5bc05c4444ce46475344f6e74be1f16fd681ba2a7409ea9fac75cabf6324806",+ "src/web-search/backends.ts": "f9bd7647eb9d45c07c6fbbb36546a14652a2f611da53eda68e91bb35890fb40a",+ "src/web-search/exa-executor.ts": "cca634a50dff5e719bc6bb9ad4b024c5e3bde81491a95b171628fd01ebbe8417",+ "src/web-search/executor.ts": "d91918525a16dde549c011e90806cf3eec3335272253fdc30da106ea0863904d",+ "src/web-search/format-result.ts": "d0698e78c55bd5d861645f27af5f0cc7ce122f50a81c8fba57d9c4d3f4e8d010",+ "src/web-search/gemini-executor.ts": "cbab2af79849f5a3e6672706f2923b35717a58362f63cfc773e507d6541333fc",+ "src/web-search/index.ts": "214aed55e357620dd077626568c35cc4517983329dd4b8b9153e4adc249c2eeb",+ "src/web-search/loop.ts": "0cf6ba9bb8c26d6e6c4763e348464754539532acb7c3ec0ceee993c859d2bea6",+ "src/web-search/ollama-executor.ts": "d092ffeb34e29264da3c4c70561f4910bb895c4250df8d92cde2284fbdc2d649",+ "src/web-search/parse.ts": "d2511ca70abfdee209323c577c26c987aff791a1bf54d6615fe35916f4c44eca",+ "src/web-search/passthrough-bridge.ts": "3863f9d7b942aef4cf3cee7d81377121ac00bb9f68953f64ada524f32bf1ca0d",+ "src/web-search/progress-stream.ts": "0b743935e725b7bdfaf285ba973bb3fcc0faaca6225c8ba3113ce504af328126",+ "src/web-search/sources.ts": "1b4d77d514dde268edbc3354192fe9c6edb623f977753506ef89aa77b61d6571",+ "src/web-search/synthetic-tool.ts": "d462a555aa335abd0007e64d1bb18f72e2d0cd9e67909b94b7008950587553b8",+ "src/web-search/xai-executor.ts": "ce5714c313d6f60a07c4990f6b31cc67b2ce39470856a0c0579a95960a724fd2"+}diff --git a/packages/model-compat/upstream.patch b/packages/model-compat/upstream.patchnew file mode 100644index 0000000000..c4cffb4924--- /dev/null+++ b/packages/model-compat/upstream.patch@@ -0,0 +1,1961 @@+--- a/src/adapters/xai-web-search.ts++++ b/src/adapters/xai-web-search.ts+@@ -57,6 +57,8 @@+ // loss, and it contradicted the sibling layer, whose own probe note already records+ // user_location/filters as accepted (tests/responses/responses-routed-web-search-fields.test.ts).+ delete next.external_web_access;++ // Cindy also receives this Codex-private flag; preserve its existing stripping behavior.++ delete next.index_gated_web_access;+ delete next.search_context_size;+ if (enableImageSearch && !Object.hasOwn(next, "enable_image_search")) {+ next.enable_image_search = true;+--- a/src/providers/xai-transport.ts++++ b/src/providers/xai-transport.ts+@@ -1,9 +1,4 @@+-import { createHash, randomUUID } from "node:crypto";+ import type { OcxProviderConfig } from "../types";+-import { resolveGithubCopilotTransport } from "./github-copilot-transport";+-+-export const XAI_GROK_CLI_BASE_URL = "https://cli-chat-proxy.grok.com/v1";+-+ /** The two hosts that serve xAI's Responses API: the public API and the Grok CLI proxy. */+ const XAI_RESPONSES_HOSTS = new Set(["api.x.ai", "cli-chat-proxy.grok.com"]);++@@ -25,145 +20,3 @@+ }+ }++-export const XAI_GROK_COMPATIBILITY = {+- version: "0.2.93",+- userAgent: "opencodex-grok/0.2.93",+- headers: {+- clientIdentifier: "x-grok-client-identifier",+- clientVersion: "x-grok-client-version",+- tokenAuth: "x-xai-token-auth",+- authenticateResponse: "x-authenticateresponse",+- conversationId: "x-grok-conv-id",+- requestId: "x-grok-req-id",+- sessionId: "x-grok-session-id",+- userAgent: "User-Agent",+- },+-} as const;+-+-export const XAI_GROK_CLIENT_VERSION = XAI_GROK_COMPATIBILITY.version;+-export const XAI_CONV_ID_HEADER = XAI_GROK_COMPATIBILITY.headers.conversationId;+-+-export type OcxProviderTransport = OcxProviderConfig & {+- /** Request executor used only at runtime; never persisted. */+- fetch?: typeof globalThis.fetch;+-};+-+-const XAI_GROK_CLI_HEADERS: Readonly<Record<string, string>> = {+- [XAI_GROK_COMPATIBILITY.headers.clientIdentifier]: "opencodex",+- [XAI_GROK_COMPATIBILITY.headers.clientVersion]: XAI_GROK_CLIENT_VERSION,+- [XAI_GROK_COMPATIBILITY.headers.tokenAuth]: "xai-grok-cli",+- [XAI_GROK_COMPATIBILITY.headers.authenticateResponse]: "authenticate-response",+-};+-+-function hasHeaderCaseInsensitive(+- headers: Record<string, string> | undefined,+- name: string,+-): boolean {+- const target = name.toLowerCase();+- return Object.keys(headers ?? {}).some(key => key.toLowerCase() === target);+-}+-+-function withoutUserOverridden(+- defaults: Readonly<Record<string, string>>,+- userHeaders: Record<string, string> | undefined,+-): Record<string, string> {+- return Object.fromEntries(+- Object.entries(defaults).filter(([name]) => !hasHeaderCaseInsensitive(userHeaders, name)),+- );+-}+-+-function withGeneratedRequestId(+- init: RequestInit | undefined,+- pinnedRequestId: string,+- stableHeaders: Readonly<Record<string, string>>,+-): RequestInit {+- const headers = new Headers(init?.headers);+- for (const [name, value] of Object.entries(stableHeaders)) {+- if (!headers.has(name)) headers.set(name, value);+- }+- if (!headers.has(XAI_GROK_COMPATIBILITY.headers.requestId)) {+- headers.set(+- XAI_GROK_COMPATIBILITY.headers.requestId,+- pinnedRequestId,+- );+- }+- return { ...init, headers };+-}+-+-function findHeaderCaseInsensitive(+- headers: Record<string, string> | undefined,+- name: string,+-): string | undefined {+- const target = name.toLowerCase();+- return Object.entries(headers ?? {}).find(([key]) => key.toLowerCase() === target)?.[1];+-}+-+-export function deriveXaiConvId(promptCacheKey: string): string {+- return createHash("sha256").update(promptCacheKey).digest("hex").slice(0, 32);+-}+-+-/**+- * Resolve xAI's runtime transport without mutating persisted config. Conversation/session+- * affinity is stable for this resolved transport; request identity is pinned per resolved+- * transport (= per logical request until key rotation), so same-target replays and transient+- * retries carry the same id while a rotated key gets a fresh one.+- * Agent, deployment, model-override, turn, mode, and user identity headers are intentionally+- * omitted because opencodex has no truthful values for the official fields.+- */+-export function resolveProviderTransport(+- providerName: string,+- provider: OcxProviderTransport,+- promptCacheKey?: string,+- apiBaseUrl?: string,+-): OcxProviderTransport {+- if (providerName === "github-copilot") {+- return resolveGithubCopilotTransport(provider, apiBaseUrl);+- }+- if (providerName !== "xai") return provider;+-+- const cacheKey = promptCacheKey?.trim();+- const affinity = cacheKey ? deriveXaiConvId(cacheKey) : undefined;+- const stableDefaults: Record<string, string> = {+- [XAI_GROK_COMPATIBILITY.headers.userAgent]: XAI_GROK_COMPATIBILITY.userAgent,+- ...(affinity+- ? {+- [XAI_GROK_COMPATIBILITY.headers.conversationId]: affinity,+- [XAI_GROK_COMPATIBILITY.headers.sessionId]: affinity,+- }+- : {}),+- ...(provider.authMode === "oauth" ? XAI_GROK_CLI_HEADERS : {}),+- };+- const stableHeaders = {+- ...withoutUserOverridden(stableDefaults, provider.headers),+- ...(provider.headers ?? {}),+- };+- // Keep API-key provider metadata compatible with key-pool rotation; session/UA defaults+- // remain transport-scoped and are applied by the wrapper immediately below.+- const headers = provider.authMode === "oauth"+- ? stableHeaders+- : {+- ...(affinity && !hasHeaderCaseInsensitive(provider.headers, XAI_GROK_COMPATIBILITY.headers.conversationId)+- ? { [XAI_GROK_COMPATIBILITY.headers.conversationId]: affinity }+- : {}),+- ...(provider.headers ?? {}),+- };+- const configuredRequestId = findHeaderCaseInsensitive(+- provider.headers,+- XAI_GROK_COMPATIBILITY.headers.requestId,+- );+- // Pin the request id per resolved transport (= per logical request until key rotation):+- // same-target 429 replays must carry the SAME x-grok-req-id as the original dispatch, and+- // transient retries reuse one id so the upstream can dedupe them. A rotated key resolves a+- // fresh transport, which gets its own id.+- const requestId = configuredRequestId ?? randomUUID();+- const baseFetch = provider.fetch ?? globalThis.fetch;+- const attemptFetch = ((input, init) =>+- baseFetch(input, withGeneratedRequestId(init, requestId, stableHeaders))) as typeof globalThis.fetch;+-+- return {+- ...provider,+- ...(provider.authMode === "oauth" ? { baseUrl: XAI_GROK_CLI_BASE_URL } : {}),+- headers,+- fetch: attemptFetch,+- };+-}+--- a/src/responses/compaction.ts++++ b/src/responses/compaction.ts+@@ -1,50 +1,3 @@+-/**+- * Remote compaction v2 support for ROUTED providers.+- *+- * Codex decides "this provider supports remote compaction" by provider name (built-in `OpenAI`),+- * and Design B points that provider at this proxy — so Codex sends remote compaction v2 requests+- * for EVERY routed model. The request is a normal /responses call whose input ends with+- * `{"type":"compaction_trigger"}`; codex-rs `collect_compaction_output` then requires the stream+- * to carry EXACTLY ONE `{"type":"compaction","encrypted_content":...}` output item+- * (compact_remote_v2.rs) or it fatals with "expected exactly one compaction output item".+- *+- * Routed models cannot produce OpenAI's encrypted blob, so the proxy runs the model as a plain+- * summarizer and wraps the summary text in a transparent envelope: `ocx1:` + base64(utf8 summary).+- * Codex stores the item and replays it in later input; the parser decodes our envelope back into+- * plain text for routed models. Real OpenAI-encrypted blobs (no `ocx1:` prefix) are opaque —+- * routed models get a short "history was compacted" note instead.+- */+-+-export const OCX_COMPACTION_PREFIX = "ocx1:";+-+-export const OCX_NATIVE_REPLAY_RECOVERY_NOTE =+- "Threads compacted through a routed provider can contain OpenCodeX-owned ocx1 state. "+- + "Before resuming one through native Codex, run `ocx recover-history --ocx-compaction <thread-id> --yes`.";+-+-/** Mirrors codex-rs core/templates/compact/prompt.md (the local-compaction instruction). */+-export const COMPACT_PROMPT = `You are performing a CONTEXT CHECKPOINT COMPACTION. Create a handoff summary for another LLM that will resume the task.+-+-Include:+-- Current progress and key decisions made+-- Important context, constraints, or user preferences+-- What remains to be done (clear next steps)+-- Any critical data, examples, or references needed to continue+-+-Be concise, structured, and focused on helping the next LLM seamlessly continue the work.`;+-+-/** Mirrors codex-rs core/templates/compact/summary_prefix.md (framing for a replayed summary). */+-export const SUMMARY_PREFIX = "Another language model started to solve this problem and produced a summary of its thinking process. You also have access to the state of the tools that were used by that language model. Use this to build on the work that has already been done and avoid duplicating work. Here is the summary produced by the other language model, use the information in this summary to assist with your own analysis:";+-+-export const OPAQUE_COMPACTION_NOTE = "[earlier conversation was compacted; the summary is stored in a format this model cannot read]";+-+-/**+- * Item types in the compact wire family. Each carries an `encrypted_content` blob the client+- * replays verbatim on every later turn, and the minting backend verifies it is unmodified.+- *+- * Keep this the only enumeration: a copy that listed just `compaction` let the response-side+- * field backfill synthesize ids into the other two, which the client then replayed as "modified+- * from the compact response".+- */+ const COMPACTION_ITEM_TYPES: ReadonlySet<string> = new Set([+ "compaction",+ "compaction_summary",+@@ -55,92 +8,3 @@+ return typeof type === "string" && COMPACTION_ITEM_TYPES.has(type);+ }++-export function encodeCompactionSummary(summary: string): string {+- return OCX_COMPACTION_PREFIX + Buffer.from(summary, "utf-8").toString("base64");+-}+-+-/** Decode an `ocx1:` envelope; returns null for real (OpenAI-encrypted) blobs or garbage. */+-export function decodeCompactionSummary(encryptedContent: string): string | null {+- if (!encryptedContent.startsWith(OCX_COMPACTION_PREFIX)) return null;+- try {+- return Buffer.from(encryptedContent.slice(OCX_COMPACTION_PREFIX.length), "base64").toString("utf-8");+- } catch {+- return null;+- }+-}+-+-/** Render a replayed compaction item as plain user-visible text for a routed model. */+-export function compactionItemToText(encryptedContent: string | undefined): string {+- const decoded = typeof encryptedContent === "string" ? decodeCompactionSummary(encryptedContent) : null;+- return decoded ? `${SUMMARY_PREFIX}\n\n${decoded}` : OPAQUE_COMPACTION_NOTE;+-}+-+-/**+- * Remote compaction v1 (`POST /responses/compact`, unary) — codex-rs installs the returned+- * `{"output":[ResponseItem...]}` as the REPLACEMENT history (compact_remote.rs+- * process_compacted_history). Mirror codex-rs local `build_compacted_history`: recent real user+- * messages within a token budget, then one user message `SUMMARY_PREFIX\n<summary>`. Plain user+- * message items parse as real user messages on the codex side (event_mapping parse_user_message);+- * contextual wrappers are filtered there, and v2-style `compaction` items are NOT expected here.+- */+-+-/** codex-rs compact.rs COMPACT_USER_MESSAGE_MAX_TOKENS = 20k tokens (~4 chars/token). */+-const COMPACT_V1_RETAINED_CHAR_BUDGET = 20_000 * 4;+-+-/** Extract plain-text user messages from a Responses `input` array (for v1 compact retention). */+-export function extractCompactUserMessages(input: unknown): string[] {+- if (!Array.isArray(input)) return [];+- const out: string[] = [];+- for (const item of input) {+- if (!item || typeof item !== "object" || Array.isArray(item)) continue;+- const rec = item as { type?: string; role?: string; content?: unknown };+- if (rec.type !== undefined && rec.type !== "message") continue;+- if (rec.role !== "user") continue;+- let text = "";+- if (typeof rec.content === "string") text = rec.content;+- else if (Array.isArray(rec.content)) {+- text = rec.content+- .map(b => {+- if (!b || typeof b !== "object") return "";+- const block = b as { type?: string; text?: string };+- return (block.type === "input_text" || block.type === "text") && typeof block.text === "string" ? block.text : "";+- })+- .join("");+- }+- if (text.trim().length > 0) out.push(text);+- }+- return out;+-}+-+-function compactUserMessageItem(text: string): Record<string, unknown> {+- return { type: "message", role: "user", content: [{ type: "input_text", text }] };+-}+-+-/** Build the v1 compact `output` array: retained recent user messages + the summary message. */+-export function buildCompactV1Output(userMessages: string[], summary: string): Record<string, unknown>[] {+- const selected: string[] = [];+- let remaining = COMPACT_V1_RETAINED_CHAR_BUDGET;+- for (let i = userMessages.length - 1; i >= 0 && remaining > 0; i--) {+- const msg = userMessages[i];+- if (msg.length <= remaining) {+- selected.push(msg);+- remaining -= msg.length;+- } else {+- // Budget partially covers this older message: keep its tail (most recent context) and stop.+- let tailStart = msg.length - remaining;+- // Never start the retained tail on a lone LOW surrogate: the pair's+- // other half would be lost and encoding substitutes U+FFFD.+- if (tailStart > 0 && tailStart < msg.length) {+- const first = msg.charCodeAt(tailStart);+- if (first >= 0xdc00 && first <= 0xdfff) tailStart += 1;+- }+- selected.push(msg.slice(tailStart));+- break;+- }+- }+- selected.reverse();+- // codex-rs compact.rs uses "{SUMMARY_PREFIX}\n{summary}" (single newline) and detects stored+- // summaries by that exact prefix — keep the same shape.+- const summaryText = summary.trim().length > 0 ? `${SUMMARY_PREFIX}\n${summary}` : "(no summary available)";+- return [...selected.map(compactUserMessageItem), compactUserMessageItem(summaryText)];+-}+--- a/src/responses/custom-tool-compat.ts++++ b/src/responses/custom-tool-compat.ts+@@ -153,7 +153,9 @@+ ) {+ names.add(value.name);+ }+- for (const entry of Object.values(value)) visit(entry);++ // Only protocol containers contain declarations; schemas, metadata and tool payloads++ // can legitimately contain {type: "custom", name: ...} as literal user data.++ for (const key of ["tools", "input", "tool_choice"]) visit(value[key]);+ };+ visit(body);+ return names;+@@ -173,7 +175,7 @@+ ) {+ out.add(value.call_id);+ }+- for (const entry of Object.values(value)) collectConvertedCallIds(entry, names, out);++ if (Array.isArray(value.input)) collectConvertedCallIds(value.input, names, out);+ }++ function rewriteForUpstream(+@@ -234,7 +236,8 @@+ let changed = false;+ const next: Record<string, unknown> = {};+ for (const [key, entry] of Object.entries(value)) {+- const rewritten = rewriteForUpstream(entry, names, callIds);++ const rewritten = ["tools", "input", "tool_choice"].includes(key)++ ? rewriteForUpstream(entry, names, callIds) : entry;+ next[key] = rewritten;+ changed ||= rewritten !== entry;+ }+--- a/src/server/relay.ts++++ b/src/server/relay.ts+@@ -1,1484 +1,2 @@+-import type { ResponsesTerminalStatus } from "../bridge";+-import {+- cyberPolicyErrorType,+- CYBER_POLICY_ERROR_CODE,+- CYBER_POLICY_FALLBACK_MESSAGE,+- isCyberPolicyCode,+- isCyberPolicyMessage,+- upstreamErrorMessageFromPayload,+-} from "../lib/errors";+-import { redactSecretString } from "../lib/redact";+-import { isTranslatorBudgetExceededError } from "../lib/translator-budget";+-import { isUsageDebugEnabled } from "../usage/debug";+-import {+- addRequestLog,+- addFinalRequestLog,+- httpStatusForRequestLogTerminal,+- inspectResponseLogJson,+- inspectResponseLogSsePayloadParsed,+- recordFirstOutput,+- type RequestLogContext,+- type RequestLogEntry,+-} from "./request-log";+-import {+- BoundedSseFrameBuffer,+- joinSseFrameBytes,+- MAX_CLIENT_SSE_FRAME_BYTES,+-} from "./sse-frame-buffer";+-import { replaceSseDataPayload } from "./sse-payload-rewrite";+-+-const nativePassthroughSseResponses = new WeakSet<Response>();+-const eagerRelaySseResponses = new WeakSet<Response>();+-+-export const MAX_INSPECTION_SSE_FRAME_BYTES = MAX_CLIENT_SSE_FRAME_BYTES;+ export const MAX_COMPLETED_OUTPUT_ITEMS = 256;+ export const MAX_COMPLETED_OUTPUT_ITEM_SOURCE_BYTES = 8 * 1024 * 1024;+-export const MAX_TAIL_ERROR_MESSAGE_CHARS = 512;+-const ADAPTER_EOF_INCOMPLETE_PAYLOAD = JSON.stringify({+- type: "response.incomplete",+- response: {+- status: "incomplete",+- incomplete_details: { reason: "adapter_eof" },+- },+-});+-const DONE_SSE_FRAME_TEXT = "data: [DONE]\n\n";+-const FAILED_TAIL_FALLBACK_PAYLOAD = JSON.stringify({+- type: "response.failed",+- response: {+- status: "failed",+- error: {+- type: "upstream_error",+- code: "upstream_reset",+- message: "Upstream stream terminated unexpectedly",+- },+- last_error: {+- type: "upstream_error",+- code: "upstream_reset",+- message: "Upstream stream terminated unexpectedly",+- },+- },+-});+-+-export type InspectionCounters = {+- frameBufferHighWaterBytes: number;+- completedItemsMaxCount: number;+- frameCapOverflows: number;+- itemCapEvictions: number;+- postCancelDrainStops: number;+-};+-+-const inspectionCounters: InspectionCounters = {+- frameBufferHighWaterBytes: 0,+- completedItemsMaxCount: 0,+- frameCapOverflows: 0,+- itemCapEvictions: 0,+- postCancelDrainStops: 0,+-};+-+-export function getInspectionCounters(): InspectionCounters {+- return { ...inspectionCounters };+-}+-+-export function resetInspectionCountersForTest(): void {+- inspectionCounters.frameBufferHighWaterBytes = 0;+- inspectionCounters.completedItemsMaxCount = 0;+- inspectionCounters.frameCapOverflows = 0;+- inspectionCounters.itemCapEvictions = 0;+- inspectionCounters.postCancelDrainStops = 0;+-}+-+-export function relayWithAbort(+- body: ReadableStream<Uint8Array> | null,+- upstream: AbortController,+- onClientGone?: (reason?: unknown) => void,+-): ReadableStream<Uint8Array> | null {+- if (!body) return null;+- const reader = body.getReader();+- return new ReadableStream<Uint8Array>({+- async pull(controller) {+- try {+- const { done, value } = await reader.read();+- if (done) {+- controller.close();+- return;+- }+- controller.enqueue(value);+- } catch (err) {+- try { controller.error(err); } catch { /* already torn down */ }+- }+- },+- cancel(reason) {+- // A tee caller may transfer abort ownership to its bounded inspection pump.+- if (onClientGone) onClientGone(reason);+- else upstream.abort(reason);+- reader.cancel(reason).catch(() => {});+- },+- });+-}+-+-export function buildFailedTailPayload(err: unknown): string {+- const translatorOverflow = isTranslatorBudgetExceededError(err);+- const message = (translatorOverflow+- ? "upstream translation buffer exceeded the safe limit"+- : `Upstream stream terminated unexpectedly: ${err instanceof Error ? err.message : String(err)}`)+- .slice(0, MAX_TAIL_ERROR_MESSAGE_CHARS);+- const failure = {+- type: "upstream_error",+- code: translatorOverflow ? "translation_buffer_limit" : "upstream_reset",+- message,+- };+- return JSON.stringify({+- type: "response.failed",+- response: { status: "failed", error: failure, last_error: failure },+- });+-}+-+-function buildFailedTailPayloadOrFallback(err: unknown): string {+- try {+- return buildFailedTailPayload(err);+- } catch {+- // Error.message and String(error) may execute hostile accessors. Preserve a+- // bounded protocol terminal even when diagnostic serialization is unsafe.+- return FAILED_TAIL_FALLBACK_PAYLOAD;+- }+-}+-+-export function failedTailFrame(encoder: TextEncoder, err: unknown): Uint8Array {+- const payload = buildFailedTailPayloadOrFallback(err);+- return encoder.encode(`\n\nevent: response.failed\ndata: ${payload}\n\n${DONE_SSE_FRAME_TEXT}`);+-}+-+-export function upstreamErrorTailFrame(encoder: TextEncoder, message: string): Uint8Array {+- const error = {+- type: "upstream_error",+- code: "upstream_server_error",+- message: redactSecretString(message).slice(0, MAX_TAIL_ERROR_MESSAGE_CHARS),+- };+- return encoder.encode(`event: response.failed\ndata: ${JSON.stringify({+- type: "response.failed",+- response: { status: "failed", error, last_error: error },+- })}\n\n`);+-}+-+-function boundedBareUpstreamErrorMessage(payload: unknown): string | undefined {+- if (!payload || typeof payload !== "object" || Array.isArray(payload)+- || (payload as { type?: unknown }).type !== "error") return undefined;+- const message = upstreamErrorMessageFromPayload(payload);+- return message ? redactSecretString(message).slice(0, MAX_TAIL_ERROR_MESSAGE_CHARS) : undefined;+-}+-+-export type SseTerminalOutputBoundary = {+- feed(chunk: Uint8Array): Uint8Array;+- finish(): Uint8Array;+- terminalSeen(): boolean;+- doneSeen(): boolean;+- upstreamError(): string | undefined;+- dispose(): void;+-};+-+-/**+- * Frame-aware client output boundary shared by both native Responses relays.+- * It buffers only the current incomplete SSE block under the same hard byte+- * cap as inspection, forwards complete blocks through the first Responses+- * terminal, and drops every later block/byte. A premature [DONE] is held until+- * a terminal arrives so clean EOF can synthesize one terminal and one sentinel.+- */+-export function createSseTerminalOutputBoundary(): SseTerminalOutputBoundary {+- const decoder = new TextDecoder();+- const encoder = new TextEncoder();+- const framer = new BoundedSseFrameBuffer(MAX_INSPECTION_SSE_FRAME_BYTES);+- let terminal = false;+- let done = false;+- let pendingDone: { block: Uint8Array; delimiter: Uint8Array } | null = null;+- let disposed = false;+- let upstreamError: string | undefined;+-+- const processFrames = (+- frames: ReturnType<BoundedSseFrameBuffer["feed"]>,+- ): Uint8Array => {+- if (disposed || terminal || frames.length === 0) return new Uint8Array(0);+- const output: Uint8Array[] = [];+- let responsesTerminal = false;+- for (const frame of frames) {+- const payload = sseDataPayload(decoder.decode(frame.block));+- const isDone = payload === "[DONE]";+- const parsed = payload === null ? undefined : parseSsePayload(payload);+- // Observe on the client reader itself: a tee inspection branch may lag+- // behind EOF, so its log context cannot determine the outgoing terminal.+- const message = boundedBareUpstreamErrorMessage(parsed);+- if (message !== undefined) upstreamError = message;+- const policyError = parsed !== undefined && isPolicyRewriteType(parsed)+- ? cyberPolicyTerminalError(parsed)+- : undefined;+- const outboundBlock = policyError+- ? encoder.encode(rewritePolicyTerminalBlock(+- decoder.decode(frame.block),+- policyFailurePayload(policyError, parsed),+- ))+- : frame.block;+- if (isDone) {+- done = true;+- if (responsesTerminal) {+- output.push(outboundBlock, frame.delimiter);+- } else if (!pendingDone) {+- // Do not expose a sentinel before a Responses terminal. If EOF+- // follows, the synthetic incomplete path owns the one sentinel;+- // if a terminal arrives later, this pending frame is emitted then.+- pendingDone = { block: outboundBlock, delimiter: frame.delimiter };+- }+- continue;+- }+- // Preserve every frame through the first Responses terminal. Every+- // later non-DONE frame is dropped.+- if (!responsesTerminal) output.push(outboundBlock, frame.delimiter);+- if (!responsesTerminal && payload && terminalStatusFromParsed(parsed)) {+- responsesTerminal = true;+- if (pendingDone) {+- output.push(pendingDone.block, pendingDone.delimiter);+- pendingDone = null;+- }+- }+- }+- if (responsesTerminal) {+- terminal = true;+- framer.dispose();+- }+- return joinSseFrameBytes(output);+- };+-+- return {+- feed(chunk) {+- if (disposed || terminal) return new Uint8Array(0);+- return processFrames(framer.feed(chunk));+- },+- finish() {+- if (disposed || terminal) return new Uint8Array(0);+- const tail = framer.finish();+- if (tail.byteLength === 0) return new Uint8Array(0);+- // EOF may cut off the final SSE block before its blank-line delimiter.+- // Feed it through the exact same parser/rewrite/terminal path as a+- // complete frame, using a synthetic delimiter so the client receives a+- // dispatchable event rather than an unterminated tail.+- const tailText = decoder.decode(tail);+- const delimiter = encoder.encode(tailText.includes("\r\n") ? "\r\n\r\n" : "\n\n");+- return processFrames([{ block: tail, delimiter }]);+- },+- terminalSeen: () => terminal,+- doneSeen: () => done,+- upstreamError: () => upstreamError,+- dispose() {+- if (disposed) return;+- disposed = true;+- pendingDone = null;+- framer.dispose();+- },+- };+-}+-+-/**+- * Relay a passthrough SSE body like relayWithAbort, but convert a MID-STREAM failure (upstream+- * reset after headers) into a clean terminal: any partial block is closed off, then a synthetic+- * `response.failed` event and `data: [DONE]` are emitted and the stream closes. Without this the+- * client sees a raw socket teardown with no terminal SSE event. Deliberately NOT a resend: the+- * upstream already committed the request (duplicate-completion risk — same policy as cursor's+- * committed=non-replayable transport retry).+- */+-export function relaySseWithFailedTail(+- body: ReadableStream<Uint8Array>,+- upstream: AbortController,+- onClientGone?: (reason?: unknown) => void,+- opts?: { upstreamError?: string },+-): ReadableStream<Uint8Array> {+- const reader = body.getReader();+- const encoder = new TextEncoder();+- const terminalBoundary = createSseTerminalOutputBoundary();+- let closed = false;+- const relayChunk = (+- controller: ReadableStreamDefaultController<Uint8Array>,+- value: Uint8Array,+- ): "terminal" | "output" | "buffered" => {+- const outbound = terminalBoundary.feed(value);+- if (outbound.byteLength > 0) controller.enqueue(outbound);+- if (!terminalBoundary.terminalSeen()) return outbound.byteLength > 0 ? "output" : "buffered";+-+- // A Responses terminal frame is the protocol boundary. Some compatible+- // gateways leave the HTTP connection open after response.completed, which+- // otherwise leaves Codex waiting forever even though the model turn is done.+- // Preserve through the terminal block only, add the conventional sentinel+- // when there was no real [DONE] data event, then stop reading upstream.+- if (!terminalBoundary.doneSeen()) {+- controller.enqueue(doneFrame(encoder));+- }+- closed = true;+- controller.close();+- const reason = "Responses terminal event received";+- // Notify the tee inspection branch as well. It has already received the+- // same terminal-bearing upstream chunk, so its bounded drain records the+- // real terminal and then releases the turn/upstream keep-alive connection.+- onClientGone?.(reason);+- reader.cancel(reason).catch(() => {});+- terminalBoundary.dispose();+- return "terminal";+- };+- return new ReadableStream<Uint8Array>({+- async pull(controller) {+- try {+- for (;;) {+- const { done, value } = await reader.read();+- if (done) {+- const tail = terminalBoundary.finish();+- if (tail.byteLength > 0) controller.enqueue(tail);+- if (terminalBoundary.terminalSeen()) {+- if (!terminalBoundary.doneSeen()) controller.enqueue(doneFrame(encoder));+- } else {+- // A clean upstream EOF is still a failed Responses turn when no+- // protocol terminal arrived. Make that state explicit so Codex+- // does not treat HTTP 200 + bare EOF as a retryable disconnect.+- const upstreamError = terminalBoundary.upstreamError() ?? opts?.upstreamError;+- controller.enqueue(upstreamError === undefined+- ? adapterEofIncompleteFrame(encoder)+- : upstreamErrorTailFrame(encoder, upstreamError));+- controller.enqueue(doneFrame(encoder));+- }+- terminalBoundary.dispose();+- controller.close();+- return;+- }+- const result = relayChunk(controller, value);+- if (result !== "buffered") return;+- }+- } catch (err) {+- let partial: Uint8Array = new Uint8Array(0);+- let tailTerminal = false;+- try {+- partial = terminalBoundary.finish();+- tailTerminal = terminalBoundary.terminalSeen();+- } catch {+- // A near-cap ambiguous delimiter tail may itself overflow at EOF.+- // Preserve the original read/framing failure and continue emitting+- // the bounded failed tail instead of letting cleanup throw again.+- }+- terminalBoundary.dispose();+- if (closed) return;+- try {+- if (partial.byteLength > 0) controller.enqueue(partial);+- if (tailTerminal) {+- if (!terminalBoundary.doneSeen()) controller.enqueue(doneFrame(encoder));+- } else {+- // Leading blank line terminates a partial SSE block so the failed frame parses cleanly.+- controller.enqueue(failedTailFrame(encoder, err));+- }+- controller.close();+- } catch { /* client already torn down */ }+- upstream.abort();+- }+- },+- cancel(reason) {+- terminalBoundary.dispose();+- if (onClientGone) onClientGone(reason);+- else upstream.abort(reason);+- reader.cancel(reason).catch(() => {});+- },+- });+-}+-+-export function nextSseBlock(buffer: string): { block: string; delimiter: string; rest: string } | null {+- const match = buffer.match(/\r?\n\r?\n/);+- if (!match || match.index === undefined) return null;+- return {+- block: buffer.slice(0, match.index),+- delimiter: match[0],+- rest: buffer.slice(match.index + match[0].length),+- };+-}+-+-export function sseDataPayload(block: string): string | null {+- const data: string[] = [];+- for (const line of block.split(/\r?\n/)) {+- if (!line.startsWith("data:")) continue;+- const value = line.slice(5);+- data.push(value.startsWith(" ") ? value.slice(1) : value);+- }+- return data.length > 0 ? data.join("\n") : null;+-}+-+-type JsonRecord = Record<string, unknown>;+-+-function asJsonRecord(value: unknown): JsonRecord | null {+- return value !== null && typeof value === "object" && !Array.isArray(value)+- ? value as JsonRecord+- : null;+-}+-+-function stringField(record: JsonRecord | null, key: string): string | undefined {+- const value = record?.[key];+- return typeof value === "string" && value.trim() ? value.trim() : undefined;+-}+-+-/**+- * Return a high-confidence policy error carried by an upstream terminal shape.+- * Deliberately inspect structured error fields and known refusal copy only — a+- * bare `cyber_policy` token in an unrelated payload is not sufficient.+- */+-function cyberPolicyTerminalError(parsed: unknown): { message: string; type?: string } | undefined {+- const root = asJsonRecord(parsed);+- if (!root) return undefined;+- const response = asJsonRecord(root.response);+- const candidates = [+- asJsonRecord(root.error),+- asJsonRecord(root.last_error),+- asJsonRecord(response?.error),+- asJsonRecord(response?.incomplete_details),+- root,+- response,+- ];+- for (const candidate of candidates) {+- if (!candidate) continue;+- if (isCyberPolicyCode(stringField(candidate, "code"))) {+- return {+- message: stringField(candidate, "message")+- ?? CYBER_POLICY_FALLBACK_MESSAGE,+- ...(stringField(candidate, "type") ? { type: stringField(candidate, "type") } : {}),+- };+- }+- }+- for (const candidate of candidates) {+- const message = stringField(candidate, "message");+- if (message && isCyberPolicyMessage(message)) {+- return {+- message,+- ...(stringField(candidate, "type") ? { type: stringField(candidate, "type") } : {}),+- };+- }+- }+- return undefined;+-}+-+-function parseSsePayload(payload: string): unknown | undefined {+- if (payload === "[DONE]") return undefined;+- try {+- return JSON.parse(payload);+- } catch {+- return undefined;+- }+-}+-+-function isPolicyRewriteType(parsed: unknown): boolean {+- const type = asJsonRecord(parsed)?.type;+- return type === "response.failed" || type === "response.incomplete" || type === "error";+-}+-+-function rewritePolicyTerminalBlock(block: string, payload: string): string {+- const newline = block.includes("\r\n") ? "\r\n" : "\n";+- const rewritten = replaceSseDataPayload(block, payload);+- const lines = rewritten.split(/\r?\n/);+- let eventRewritten = false;+- const withEvent = lines.map(line => {+- if (!eventRewritten && line.startsWith("event:")) {+- eventRewritten = true;+- return "event: response.failed";+- }+- return line;+- });+- if (!eventRewritten) withEvent.unshift("event: response.failed");+- return withEvent.join(newline);+-}+-+-function policyFailurePayload(policyError: { message: string; type?: string }, parsed: unknown): string {+- const error = {+- type: cyberPolicyErrorType(policyError.type),+- code: CYBER_POLICY_ERROR_CODE,+- message: redactSecretString(policyError.message).slice(0, MAX_TAIL_ERROR_MESSAGE_CHARS),+- };+- const root = asJsonRecord(parsed);+- const originalResponse = asJsonRecord(root?.response);+- const preservedResponse = Object.fromEntries(+- Object.entries(originalResponse ?? {}).filter(([key]) => key !== "incomplete_details"),+- );+- const response = {+- ...preservedResponse,+- status: "failed",+- error,+- last_error: error,+- retryable: false,+- };+- // Responses event metadata such as sequence_number is normally top-level.+- // Keep it (and any other non-error, non-response fields) while replacing only+- // the protocol type and error envelope.+- const preservedRoot = root+- ? Object.fromEntries(Object.entries(root).filter(([key]) => (+- key !== "type"+- && key !== "response"+- && key !== "error"+- && key !== "last_error"+- && key !== "retryable"+- )))+- : {};+- return JSON.stringify({+- ...preservedRoot,+- type: "response.failed",+- retryable: false,+- response,+- });+-}+-+-export function adapterEofIncompleteFrame(encoder: TextEncoder): Uint8Array {+- return encoder.encode(`event: response.incomplete\ndata: ${ADAPTER_EOF_INCOMPLETE_PAYLOAD}\n\n`);+-}+-+-export function doneFrame(encoder: TextEncoder): Uint8Array {+- return encoder.encode(DONE_SSE_FRAME_TEXT);+-}+-+-export function terminalStatusFromSsePayload(payload: string): ResponsesTerminalStatus | null {+- if (payload === "[DONE]") return null;+- return terminalStatusFromParsed(parseSsePayload(payload));+-}+-+-/** True when a native Responses SSE payload carries the FIRST kind of non-empty model output. */+-export function isFirstOutputSsePayload(payload: string | null): boolean {+- if (!payload || payload === "[DONE]") return false;+- try {+- return firstOutputFromParsed(JSON.parse(payload));+- } catch {+- return false;+- }+-}+-+-export function firstOutputFromParsed(parsed: unknown): boolean {+- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return false;+- const event = parsed as { type?: unknown; delta?: unknown };+- return (event.type === "response.output_text.delta"+- || event.type === "response.reasoning_summary_text.delta"+- || event.type === "response.reasoning_text.delta")+- && typeof event.delta === "string"+- && event.delta.length > 0;+-}+-+-function createFirstOutputReporter(onFirstOutput?: () => void): {+- payload: (payload: string | null) => void;+- parsed: (parsed: unknown) => void;+-} {+- let reported = false;+- const report = (isFirst: boolean) => {+- if (reported || !isFirst) return;+- reported = true;+- try { onFirstOutput?.(); } catch { /* metrics must not break the stream */ }+- };+- return {+- payload: payload => report(isFirstOutputSsePayload(payload)),+- parsed: parsed => report(firstOutputFromParsed(parsed)),+- };+-}+-+-export function terminalStatusFromParsed(parsed: unknown): ResponsesTerminalStatus | null {+- const type = asJsonRecord(parsed)?.type;+- switch (type) {+- case "response.completed":+- return "completed";+- case "response.failed":+- return "failed";+- case "response.incomplete":+- return cyberPolicyTerminalError(parsed) ? "failed" : "incomplete";+- case "error":+- return cyberPolicyTerminalError(parsed) ? "failed" : null;+- default:+- return null;+- }+-}+-+-/** Extract the response object from a `response.completed` SSE payload, or null. */+-export function completedResponseFromSsePayload(payload: string): { id?: unknown; output?: unknown; status?: unknown } | null {+- if (payload === "[DONE]") return null;+- try {+- const json = JSON.parse(payload) as { type?: unknown; response?: unknown };+- return completedResponseFromParsedEvent(json);+- } catch {+- return null;+- }+-}+-+-/** Extract the response object from an already-parsed `response.completed` event, or null. */+-export function completedResponseFromParsedEvent(+- json: unknown,+-): { id?: unknown; output?: unknown; status?: unknown } | null {+- if (!json || typeof json !== "object" || Array.isArray(json)+- || (json as { type?: unknown }).type !== "response.completed") return null;+- const response = (json as { response?: unknown }).response;+- if (!response || typeof response !== "object" || Array.isArray(response)) return null;+- return response as { id?: unknown; output?: unknown; status?: unknown };+-}+-+-export function trackSseForRequestLog(+- body: ReadableStream<Uint8Array>,+- onTerminal: (status: ResponsesTerminalStatus) => void,+- onCancel: () => void,+- logCtx?: RequestLogContext,+- onFirstOutput?: () => void,+-): ReadableStream<Uint8Array> {+- const reader = body.getReader();+- let terminalReported = false;+- let cancelled = false;+-+- const reportTerminal = (status: ResponsesTerminalStatus) => {+- if (terminalReported) return;+- terminalReported = true;+- onTerminal(status);+- };+- // Reuse the byte-bounded inspector so translated responses cannot retain an+- // unterminated upstream frame or parse the same event once per observer.+- const inspector = createSseInspector({+- onTerminal: reportTerminal,+- logCtx,+- onFirstOutput,+- });+-+- return new ReadableStream<Uint8Array>({+- async pull(controller) {+- try {+- const { done, value } = await reader.read();+- if (done) {+- if (!cancelled) {+- inspector.finish();+- if (!terminalReported) reportTerminal("incomplete");+- }+- inspector.dispose();+- controller.close();+- return;+- }+- inspector.feed(value);+- controller.enqueue(value);+- } catch (err) {+- // The upstream read rejected: the 200 body died mid-flight. Client+- // cancellation is the caller's separate 499 path, so a cancel-drained+- // pending read (cancelled=true) must not carry the truncation marker.+- if (!cancelled && !terminalReported && logCtx?.activeAttempt) {+- logCtx.activeAttempt.streamAborted = true;+- }+- if (!cancelled && !terminalReported) reportTerminal("incomplete");+- inspector.dispose();+- try { controller.error(err); } catch { /* already torn down */ }+- }+- },+- cancel(reason) {+- cancelled = true;+- inspector.dispose();+- onCancel();+- reader.cancel(reason).catch(() => {});+- },+- });+-}+-+-export function responseWithDeferredRequestLog(+- response: Response,+- requestId: string,+- start: number,+- logCtx: RequestLogContext,+- addLog: (entry: RequestLogEntry) => void = addRequestLog,+-): Response {+- const contentType = response.headers.get("content-type")?.toLowerCase() ?? "";+- if (isUsageDebugEnabled() && !logCtx.usageDebugContentType && contentType) {+- logCtx.usageDebugContentType = contentType;+- }+- if (isNativePassthroughSseResponse(response)) {+- return response;+- }+- if (!response.body || !contentType.includes("text/event-stream")) {+- if (response.body && (contentType.includes("application/json") || response.status >= 400)) {+- const finalizeJsonLog = async () => {+- const text = await response.text();+- // Non-JSON error bodies: inspect/log only a bounded prefix (the stored+- // upstreamError is 500 chars anyway); the FULL text is still forwarded to the+- // client below, unchanged. JSON bodies keep full inspection (usage parsing).+- const isJson = contentType.includes("application/json");+- inspectResponseLogJson(logCtx, isJson ? text : text.slice(0, 8192));+- addFinalRequestLog(requestId, start, logCtx, response.status, { closeReason: "non_stream" }, addLog);+- return text;+- };+- const body = new ReadableStream<Uint8Array>({+- async start(controller) {+- try {+- controller.enqueue(new TextEncoder().encode(await finalizeJsonLog()));+- controller.close();+- } catch (err) {+- addFinalRequestLog(requestId, start, logCtx, 502, { closeReason: "non_stream" }, addLog);+- try { controller.error(err); } catch { /* already torn down */ }+- }+- },+- });+- return new Response(body, {+- status: response.status,+- statusText: response.statusText,+- headers: response.headers,+- });+- }+- if (isUsageDebugEnabled() && logCtx.usageDebugBodyKind === undefined) {+- logCtx.usageDebugBodyKind = response.body ? "other" : "none";+- }+- addFinalRequestLog(requestId, start, logCtx, response.status, { closeReason: "non_stream" }, addLog);+- return response;+- }+-+- let logged = false;+- const body = trackSseForRequestLog(+- response.body,+- status => {+- if (logged) return;+- logged = true;+- addFinalRequestLog(requestId, start, logCtx, httpStatusForRequestLogTerminal(status, logCtx), {+- terminalStatus: status,+- closeReason: "terminal",+- }, addLog);+- },+- () => {+- if (logged) return;+- logged = true;+- addFinalRequestLog(requestId, start, logCtx, 499, { closeReason: "client_cancel" }, addLog);+- },+- logCtx,+- () => recordFirstOutput(logCtx, start),+- );+- return new Response(body, {+- status: response.status,+- statusText: response.statusText,+- headers: response.headers,+- });+-}+-+-export function markNativePassthroughSseResponse(response: Response): Response {+- nativePassthroughSseResponses.add(response);+- return response;+-}+-+-export function isNativePassthroughSseResponse(response: Response): boolean {+- return nativePassthroughSseResponses.has(response);+-}+-+-export function markEagerRelaySseResponse(response: Response): Response {+- eagerRelaySseResponses.add(response);+- return response;+-}+-+-/** Test-only path identity seam; runtime behavior must not branch on this marker. */+-export function isEagerRelaySseResponse(response: Response): boolean {+- return eagerRelaySseResponses.has(response);+-}+-+-export function relaySseWithHeartbeat(+- body: ReadableStream<Uint8Array> | null,+- upstream: AbortController,+- heartbeatMs = 15_000,+- onTerminal?: (status: ResponsesTerminalStatus) => void,+- options?: { onStart?: () => void; onDone?: () => void },+-): ReadableStream<Uint8Array> | null {+- if (!body) return null;+- const reader = body.getReader();+- const heartbeat = new TextEncoder().encode(": opencodex keepalive\n\n");+- let timer: ReturnType<typeof setInterval> | undefined;+- let closed = false;+- let clientCancelled = false;+- let terminalReported = false;+-+- const reportTerminal = (status: ResponsesTerminalStatus) => {+- if (terminalReported || clientCancelled || closed) return;+- terminalReported = true;+- onTerminal?.(status);+- };+- const inspector = createSseInspector({ onTerminal: reportTerminal });+-+- const cleanup = () => {+- if (closed) return;+- closed = true;+- inspector.dispose();+- if (timer) clearInterval(timer);+- timer = undefined;+- options?.onDone?.();+- };+-+- return new ReadableStream<Uint8Array>({+- start(controller) {+- options?.onStart?.();+- timer = setInterval(() => {+- if (closed) return;+- try {+- controller.enqueue(heartbeat);+- } catch {+- cleanup();+- }+- }, heartbeatMs);+- },+- async pull(controller) {+- try {+- const { done, value } = await reader.read();+- if (done) {+- inspector.finish();+- if (!terminalReported && !clientCancelled) reportTerminal("incomplete");+- cleanup();+- controller.close();+- return;+- }+- inspector.feed(value);+- controller.enqueue(value);+- } catch (err) {+- if (!clientCancelled) reportTerminal("incomplete");+- cleanup();+- try { controller.error(err); } catch { /* already torn down */ }+- }+- },+- cancel(reason) {+- clientCancelled = true;+- cleanup();+- upstream.abort(reason);+- reader.cancel(reason).catch(() => {});+- },+- });+-}+-+-/**+- * Background-consume an SSE stream purely for terminal-outcome inspection (quota tracking).+- * Does not produce output; safe to ignore errors (the client-facing stream is separate).+- */+-export type SseInspector = {+- /** Feed one upstream chunk through the SSE scanning state machine. */+- feed(chunk: Uint8Array): void;+- /** Flush the decoder + trailing unterminated buffer (upstream cleanly done). */+- finish(): void;+- /** Drop every retained frame/item reference without parsing. Idempotent. */+- dispose(): void;+- /** True once a protocol terminal was detected and reported. */+- reported(): boolean;+- /** True once any protocol terminal was parsed, including metadata-only inspectors. */+- terminalSeen(): boolean;+-};+-+-export type SseInspectorHandlers = {+- onTerminal?: (status: ResponsesTerminalStatus, httpStatusOverride?: number) => void;+- logCtx?: RequestLogContext;+- onCompletedResponse?: (response: { id?: unknown; output?: unknown; status?: unknown }) => void;+- /**+- * Every parsed SSE payload, delivered BEFORE any onCompletedResponse derived from that same+- * payload. A caller that must decide on the whole turn -- not just its terminal snapshot --+- * needs to see the incremental events, because a stream can announce an item and then close+- * with an empty `output`.+- */+- onParsedPayload?: (payload: unknown) => void;+- onFirstOutput?: () => void;+- /**+- * Provider-scoped compatibility: persist the completed snapshot under the+- * first response id exposed to the client when an upstream changes ids+- * between `response.created` and `response.completed`.+- */+- pinCompletedResponseIdToFirstSeen?: boolean;+-};+-+-type CompletedOutputItem = { item: unknown; sourceBytes: number };+-+-function delimiterLengthAt(+- index: number,+- length: number,+- byteAt: (index: number) => number,+-): number | 0 | undefined {+- const first = byteAt(index);+- if (first === 10) {+- if (index + 1 >= length) return undefined;+- const second = byteAt(index + 1);+- if (second === 10) return 2;+- if (second !== 13) return 0;+- if (index + 2 >= length) return undefined;+- return byteAt(index + 2) === 10 ? 3 : 0;+- }+- if (first !== 13) return 0;+- if (index + 1 >= length) return undefined;+- if (byteAt(index + 1) !== 10) return 0;+- if (index + 2 >= length) return undefined;+- const third = byteAt(index + 2);+- if (third === 10) return 3;+- if (third !== 13) return 0;+- if (index + 3 >= length) return undefined;+- return byteAt(index + 3) === 10 ? 4 : 0;+-}+-+-/**+- * Per-chunk SSE inspection state machine shared by consumeForInspection,+- * consumeForResponseLogMetadata, and the eager bounded relay (relay-eager.ts).+- *+- * Extraction-fidelity invariants (devlog/_plan/260723_win_mem_safestream/020):+- * - logCtx SSE inspection is gated on !reported; in the metadata configuration+- * (no onTerminal) `reported` stays permanently false, which reproduces the+- * metadata consumer's unconditional inspection through the same gate.+- * - finish() skips the trailing-buffer scan once reported, while per-block+- * onCompletedResponse continues firing after reported — an intentional+- * asymmetry inherited from consumeForInspection.+- * - logCtx.transportPhase/terminalSource are mutated BEFORE onTerminal fires.+- * - Synthetic terminals (incomplete / failed-502) are the CALLER's decision:+- * the caller owns `cancelled` state and reads `reported()` to decide.+- */+-export function createSseInspector(handlers: SseInspectorHandlers): SseInspector {+- let decoder: TextDecoder | null = new TextDecoder();+- let reported = false;+- let sawTerminal = false;+- let disposed = false;+- let delimiterTail: Uint8Array = new Uint8Array(0);+- let candidate: Uint8Array = new Uint8Array(0);+- let candidateBytes = 0;+- let discardingOversizedFrame = false;+- const reportFirstOutput = createFirstOutputReporter(handlers.onFirstOutput);+- // Allocate reconstruction state only for persistence-capable inspectors.+- const completedItemsByOutputIndex = handlers.onCompletedResponse+- ? new Map<number, CompletedOutputItem>()+- : null;+- let aggregateItemBytes = 0;+- let reconstructionTainted = false;+- let firstResponseId: string | undefined;+-+- const clearFrameState = (): void => {+- delimiterTail = new Uint8Array(0);+- candidate = new Uint8Array(0);+- candidateBytes = 0;+- discardingOversizedFrame = false;+- };+-+- const clearCompletedItems = (): void => {+- completedItemsByOutputIndex?.clear();+- aggregateItemBytes = 0;+- reconstructionTainted = false;+- };+-+- const dispose = (): void => {+- if (disposed) return;+- disposed = true;+- decoder = null;+- clearFrameState();+- clearCompletedItems();+- firstResponseId = undefined;+- };+-+- const ensureCandidateCapacity = (requiredBytes: number): void => {+- if (candidate.byteLength >= requiredBytes) return;+- let capacity = candidate.byteLength === 0+- ? Math.min(MAX_INSPECTION_SSE_FRAME_BYTES, Math.max(requiredBytes, 4096))+- : candidate.byteLength;+- while (capacity < requiredBytes) {+- capacity = Math.min(+- MAX_INSPECTION_SSE_FRAME_BYTES,+- Math.max(requiredBytes, capacity * 2),+- );+- }+- const grown = new Uint8Array(capacity);+- if (candidateBytes > 0) grown.set(candidate.subarray(0, candidateBytes));+- candidate = grown;+- };+-+- const takeCandidate = (): Uint8Array => {+- if (candidateBytes === 0) return new Uint8Array(0);+- const frame = candidate.slice(0, candidateBytes);+- candidate = new Uint8Array(0);+- candidateBytes = 0;+- return frame;+- };+-+- const retainCandidateSlice = (slice: Uint8Array): void => {+- if (slice.byteLength === 0 || discardingOversizedFrame) return;+- const nextBytes = candidateBytes + slice.byteLength;+- inspectionCounters.frameBufferHighWaterBytes = Math.max(+- inspectionCounters.frameBufferHighWaterBytes,+- Math.min(nextBytes, MAX_INSPECTION_SSE_FRAME_BYTES),+- );+- if (nextBytes > MAX_INSPECTION_SSE_FRAME_BYTES) {+- candidate = new Uint8Array(0);+- candidateBytes = 0;+- discardingOversizedFrame = true;+- inspectionCounters.frameCapOverflows += 1;+- // The rejected frame may have carried an output item we will never see;+- // any later empty-output terminal must not synthesize a partial replay+- // from the surviving map entries (same taint rule as item eviction).+- reconstructionTainted = true;+- return;+- }+- ensureCandidateCapacity(nextBytes);+- candidate.set(slice, candidateBytes);+- candidateBytes = nextBytes;+- };+-+- const retainCompletedItem = (index: number, item: unknown, sourceBytes: number): void => {+- const previous = completedItemsByOutputIndex!.get(index);+- if (previous) {+- aggregateItemBytes -= previous.sourceBytes;+- completedItemsByOutputIndex!.delete(index);+- }+- if (sourceBytes > MAX_COMPLETED_OUTPUT_ITEM_SOURCE_BYTES) {+- reconstructionTainted = true;+- inspectionCounters.itemCapEvictions += 1;+- return;+- }+- completedItemsByOutputIndex!.set(index, { item, sourceBytes });+- aggregateItemBytes += sourceBytes;+- while (completedItemsByOutputIndex!.size > MAX_COMPLETED_OUTPUT_ITEMS+- || aggregateItemBytes > MAX_COMPLETED_OUTPUT_ITEM_SOURCE_BYTES) {+- let highestIndex = -1;+- for (const retainedIndex of completedItemsByOutputIndex!.keys()) {+- if (retainedIndex > highestIndex) highestIndex = retainedIndex;+- }+- const evicted = completedItemsByOutputIndex!.get(highestIndex);+- if (!evicted) break;+- completedItemsByOutputIndex!.delete(highestIndex);+- aggregateItemBytes -= evicted.sourceBytes;+- reconstructionTainted = true;+- inspectionCounters.itemCapEvictions += 1;+- }+- inspectionCounters.completedItemsMaxCount = Math.max(+- inspectionCounters.completedItemsMaxCount,+- completedItemsByOutputIndex!.size,+- );+- };+-+- const scanPayload = (payload: string | null, sourceBytes: number): void => {+- if (!payload) return;+- let parsed: unknown | undefined;+- if (payload !== "[DONE]") {+- try {+- parsed = JSON.parse(payload);+- } catch {+- /* malformed SSE payloads remain best-effort/no-throw */+- }+- }+- if (!reported && handlers.logCtx) {+- inspectResponseLogSsePayloadParsed(handlers.logCtx, payload, parsed);+- }+- // Before any terminal handling: a consumer deciding on the whole turn must observe this+- // payload even when the terminal snapshot that follows no longer mentions it.+- if (handlers.onParsedPayload && parsed !== undefined) {+- try { handlers.onParsedPayload(parsed); } catch { /* inspection must never throw into the pump */ }+- }+- reportFirstOutput.parsed(parsed);+- const status = terminalStatusFromParsed(parsed);+- const policyTerminal = status === "failed"+- && isPolicyRewriteType(parsed)+- && cyberPolicyTerminalError(parsed) !== undefined;+- if (status) sawTerminal = true;+- if (!reported && handlers.onTerminal && status) {+- try {+- reported = true;+- if (handlers.logCtx) {+- handlers.logCtx.transportPhase = "terminal_sse";+- handlers.logCtx.terminalSource = "upstream";+- }+- handlers.onTerminal(status, policyTerminal ? 400 : undefined);+- } finally {+- if (status === "failed" || status === "incomplete") clearCompletedItems();+- }+- } else if (status === "failed" || status === "incomplete") {+- clearCompletedItems();+- }+- if (handlers.onCompletedResponse) {+- type ParsedSseEvent = { type?: unknown; output_index?: unknown; item?: unknown; response?: unknown };+- const parsedEvent = parsed && typeof parsed === "object" && !Array.isArray(parsed)+- ? parsed as ParsedSseEvent+- : null;+- const responseRecord = parsedEvent+- && typeof parsedEvent.response === "object"+- && parsedEvent.response !== null+- && !Array.isArray(parsedEvent.response)+- ? parsedEvent.response as { id?: unknown }+- : null;+- if (handlers.pinCompletedResponseIdToFirstSeen+- && responseRecord+- && typeof responseRecord.id === "string") {+- firstResponseId ??= responseRecord.id;+- }+- const doneItem = parsedEvent?.type === "response.output_item.done" ? parsedEvent.item : undefined;+- if (parsedEvent+- && doneItem !== undefined+- && Number.isInteger(parsedEvent.output_index)+- && (parsedEvent.output_index as number) >= 0+- && typeof doneItem === "object"+- && doneItem !== null+- && !Array.isArray(doneItem)+- && typeof (doneItem as { type?: unknown }).type === "string") {+- retainCompletedItem(parsedEvent.output_index as number, doneItem, sourceBytes);+- }+-+- let response = completedResponseFromParsedEvent(parsedEvent);+- if (response) {+- if (handlers.pinCompletedResponseIdToFirstSeen+- && firstResponseId !== undefined+- && response.id !== firstResponseId) {+- response = { ...response, id: firstResponseId };+- }+- // Authoritative output is a NON-EMPTY ARRAY only. Anything else+- // (missing, null, scalar, object) keeps the historical backfill+- // behavior so a malformed terminal cannot reach rememberResponseState+- // and destroy continuation state (review C1-2).+- const hasAuthoritativeOutput = Array.isArray(response.output)+- && response.output.length > 0;+- if (!hasAuthoritativeOutput && reconstructionTainted) {+- clearCompletedItems();+- return;+- }+- if (!hasAuthoritativeOutput && completedItemsByOutputIndex!.size > 0) {+- response = {+- ...response,+- output: [...completedItemsByOutputIndex!.entries()]+- .sort(([left], [right]) => left - right)+- .map(([, retained]) => retained.item),+- };+- }+- try {+- handlers.onCompletedResponse(response);+- } finally {+- clearCompletedItems();+- }+- } else if (parsedEvent?.type === "response.completed") {+- clearCompletedItems();+- }+- }+- };+-+- const completeCandidate = (): void => {+- if (discardingOversizedFrame) {+- discardingOversizedFrame = false;+- return;+- }+- const sourceBytes = candidateBytes;+- const frame = takeCandidate();+- if (reported && !handlers.onCompletedResponse) return;+- const decoded = decoder!.decode(frame);+- scanPayload(sseDataPayload(decoded), sourceBytes);+- };+-+- const scanChunk = (chunk: Uint8Array): void => {+- const previousTail = delimiterTail;+- delimiterTail = new Uint8Array(0);+- const tailLength = previousTail.byteLength;+- const totalLength = tailLength + chunk.byteLength;+- const byteAt = (index: number): number => index < tailLength+- ? previousTail[index]!+- : chunk[index - tailLength]!;+- const retainRange = (start: number, end: number): void => {+- if (end <= start || discardingOversizedFrame) return;+- if (start < tailLength) {+- retainCandidateSlice(previousTail.subarray(start, Math.min(end, tailLength)));+- }+- if (end > tailLength) {+- retainCandidateSlice(chunk.subarray(Math.max(0, start - tailLength), end - tailLength));+- }+- };+- let index = 0;+- let retainedThrough = 0;+- while (index < totalLength) {+- const delimiterLength = delimiterLengthAt(index, totalLength, byteAt);+- if (delimiterLength === undefined) break;+- if (delimiterLength > 0) {+- retainRange(retainedThrough, index);+- completeCandidate();+- index += delimiterLength;+- retainedThrough = index;+- continue;+- }+- index += 1;+- }+- retainRange(retainedThrough, index);+- if (index < totalLength) {+- delimiterTail = new Uint8Array(totalLength - index);+- for (let offset = 0; offset < delimiterTail.byteLength; offset += 1) {+- delimiterTail[offset] = byteAt(index + offset);+- }+- }+- };+-+- return {+- feed(chunk) {+- if (!disposed) scanChunk(chunk);+- },+- finish() {+- if (disposed) return;+- try {+- retainCandidateSlice(delimiterTail);+- delimiterTail = new Uint8Array(0);+- if (!discardingOversizedFrame && candidateBytes > 0 && !reported) {+- const sourceBytes = candidateBytes;+- const decoded = decoder!.decode(takeCandidate());+- scanPayload(decoded.trim() ? sseDataPayload(decoded) : null, sourceBytes);+- }+- } finally {+- clearFrameState();+- clearCompletedItems();+- }+- },+- dispose,+- reported: () => reported,+- terminalSeen: () => sawTerminal,+- };+-}+-+-export type InspectionDrainBounds = { ms: number; bytes: number };+-+-export type InspectionConsumerOptions = {+- clientGoneSignal?: AbortSignal;+- drainBounds?: Partial<InspectionDrainBounds>;+- upstream?: AbortController;+- now?: () => number;+- /** Forward provider-scoped response-id pinning to the owned inspector. */+- pinCompletedResponseIdToFirstSeen?: boolean;+- /** Observe every parsed SSE payload on the inspection side; see SseInspectorHandlers. */+- onParsedPayload?: (payload: unknown) => void;+- /** Test seam for proving both public consumers dispose their owned inspector. */+- inspectorFactory?: (handlers: SseInspectorHandlers) => SseInspector;+-};+-+-const DEFAULT_INSPECTION_DRAIN_MS = 15_000;+-const DEFAULT_INSPECTION_DRAIN_BYTES = 32 * 1024 * 1024;+-type InspectionPumpOptions = InspectionConsumerOptions & {+- reader: ReadableStreamDefaultReader<Uint8Array>;+- inspector: SseInspector;+- signal?: AbortSignal;+- onDone?: () => void;+- onCancel?: () => void;+- onCleanEof?: () => void;+- onReadError?: () => void;+-};+-+-function startBoundedInspectionPump(options: InspectionPumpOptions): void {+- const { reader, inspector, signal, clientGoneSignal } = options;+- let cancelled = false;+- let clientGone = false;+- let clientGoneReason: unknown;+- let drainedBytes = 0;+- let drainDeadline = Number.POSITIVE_INFINITY;+- let drainTimer: ReturnType<typeof setTimeout> | undefined;+- let drainStopped = false;+- const drainMs = options.drainBounds?.ms ?? DEFAULT_INSPECTION_DRAIN_MS;+- const drainBytes = options.drainBounds?.bytes ?? DEFAULT_INSPECTION_DRAIN_BYTES;+- const now = options.now ?? Date.now;+- let cancelFired = false;+- const fireCancel = () => {+- if (cancelFired) return;+- cancelFired = true;+- options.onCancel?.();+- };+- const markClientGone = () => {+- if (clientGone || cancelled) return;+- clientGone = true;+- clientGoneReason = clientGoneSignal?.reason;+- drainDeadline = now() + drainMs;+- if (inspector.terminalSeen() || drainMs <= 0 || drainBytes <= 0) {+- stopDrain();+- return;+- }+- // Do not unref: on Bun/Windows a pending `reader.read()` can be the only+- // wake source; an unref'd timer may never run, so a silent post-cancel+- // drain (time bound, no bytes) hangs the suite until the job timeout.+- drainTimer = setTimeout(stopDrain, drainMs);+- };+- // Ends the bounded drain by cancelling the reader: the pending read settles+- // and the pump loop observes `drainStopped`. Deliberately NOT a shared+- // Promise.race companion — racing every read against one pending promise+- // retains O(chunk-count) reactions on long streams (review C1-1), the exact+- // retention class this phase removes.+- const stopDrain = () => {+- if (drainStopped || cancelled) return;+- drainStopped = true;+- reader.cancel(clientGoneReason).catch(() => {});+- };+- const abortImmediately = () => {+- if (cancelled) return;+- cancelled = true;+- reader.cancel(signal?.reason).catch(() => {});+- fireCancel();+- };+-+- if (signal?.aborted) {+- cancelled = true;+- reader.cancel(signal.reason).catch(() => {});+- inspector.dispose();+- fireCancel();+- options.onDone?.();+- return;+- }+- signal?.addEventListener("abort", abortImmediately, { once: true });+- clientGoneSignal?.addEventListener("abort", markClientGone, { once: true });+- if (clientGoneSignal?.aborted) markClientGone();+-+- const pump = async () => {+- let clientGoneWithoutTerminal = false;+- let boundEndedDrain = false;+- try {+- for (;;) {+- const { done, value } = await reader.read();+- if (clientGoneSignal?.aborted) markClientGone();+- if (drainStopped) {+- // stopDrain() cancelled the reader; the settled read is the wake-up.+- clientGoneWithoutTerminal = !inspector.terminalSeen();+- boundEndedDrain = clientGoneWithoutTerminal;+- break;+- }+- if (done) {+- inspector.finish();+- if (clientGone) clientGoneWithoutTerminal = !inspector.terminalSeen();+- else if (!cancelled) options.onCleanEof?.();+- break;+- }+- if (!clientGone) {+- inspector.feed(value);+- continue;+- }+- if (now() >= drainDeadline) {+- clientGoneWithoutTerminal = true;+- boundEndedDrain = true;+- break;+- }+- const remainingBytes = Math.max(0, drainBytes - drainedBytes);+- const inspectedValue = value.byteLength > remainingBytes+- ? value.subarray(0, remainingBytes)+- : value;+- if (inspectedValue.byteLength > 0) inspector.feed(inspectedValue);+- drainedBytes += inspectedValue.byteLength;+- if (inspector.terminalSeen()) break;+- if (value.byteLength > remainingBytes+- || drainedBytes >= drainBytes+- || now() >= drainDeadline) {+- clientGoneWithoutTerminal = true;+- boundEndedDrain = true;+- break;+- }+- }+- } catch {+- // Bun can settle a fetch body read before dispatching all abort listeners.+- // Observe the signal itself before classifying that rejection as upstream.+- if (clientGoneSignal?.aborted) markClientGone();+- // A read error can follow a final SSE block without its blank-line+- // delimiter. Flush that candidate before classifying the transport as a+- // synthetic reset; otherwise a real completed/failed/policy terminal is+- // downgraded to 502 on the inspection branch.+- if (!cancelled) {+- try { inspector.finish(); } catch { /* preserve the original read error */ }+- }+- if (clientGone) clientGoneWithoutTerminal = !inspector.terminalSeen();+- else if (!cancelled) options.onReadError?.();+- } finally {+- if (drainTimer) clearTimeout(drainTimer);+- signal?.removeEventListener("abort", abortImmediately);+- clientGoneSignal?.removeEventListener("abort", markClientGone);+- if (clientGone) {+- if (boundEndedDrain) inspectionCounters.postCancelDrainStops += 1;+- if (clientGoneWithoutTerminal) fireCancel();+- options.upstream?.abort(clientGoneReason);+- reader.cancel(clientGoneReason).catch(() => {});+- }+- inspector.dispose();+- options.onDone?.();+- }+- };+- void pump();+-}+-+-export function consumeForInspection(+- body: ReadableStream<Uint8Array>,+- onTerminal: (status: ResponsesTerminalStatus, httpStatusOverride?: number) => void,+- signal?: AbortSignal,+- onDone?: () => void,+- logCtx?: RequestLogContext,+- onCancel?: () => void,+- onCompletedResponse?: (response: { id?: unknown; output?: unknown; status?: unknown }) => void,+- onFirstOutput?: () => void,+- options?: InspectionConsumerOptions,+-): void {+- const reader = body.getReader();+- let bareUpstreamError: string | undefined;+- const inspector = (options?.inspectorFactory ?? createSseInspector)({+- onTerminal,+- logCtx,+- onCompletedResponse,+- onParsedPayload: payload => {+- const message = boundedBareUpstreamErrorMessage(payload);+- if (message !== undefined) bareUpstreamError = message;+- options?.onParsedPayload?.(payload);+- },+- onFirstOutput,+- pinCompletedResponseIdToFirstSeen: options?.pinCompletedResponseIdToFirstSeen,+- });+- startBoundedInspectionPump({+- ...options,+- reader,+- inspector,+- signal,+- onDone,+- onCancel,+- onCleanEof: () => {+- if (!inspector.reported()) {+- if (logCtx) logCtx.terminalSource = "synthetic";+- if (bareUpstreamError !== undefined) {+- onTerminal("failed", httpStatusForRequestLogTerminal("failed", logCtx));+- } else {+- onTerminal("incomplete");+- }+- }+- },+- onReadError: () => {+- // Upstream read failure after HTTP 200 (mid-stream socket reset) is not a+- // protocol `response.incomplete` terminal. Report a synthetic 502 so account+- // health treats it as transient; abort-driven client cancellation still wins.+- if (!inspector.reported()) {+- if (logCtx) {+- logCtx.transportPhase = "mid_stream";+- logCtx.terminalSource = "synthetic";+- // A truncated 200 body must not meter as a success the client never+- // received; the router's equivalent turn carries 502 + streamAborted+- // (codex-router #139).+- if (logCtx.activeAttempt) logCtx.activeAttempt.streamAborted = true;+- }+- onTerminal("failed", 502);+- }+- },+- });+-}+-+-export function consumeForResponseLogMetadata(+- body: ReadableStream<Uint8Array>,+- logCtx: RequestLogContext,+- signal?: AbortSignal,+- onDone?: () => void,+- onCompletedResponse?: (response: { id?: unknown; output?: unknown; status?: unknown }) => void,+- onFirstOutput?: () => void,+- options?: InspectionConsumerOptions,+-): void {+- const reader = body.getReader();+- // No onTerminal → the inspector's `reported` gate stays permanently false,+- // reproducing this consumer's unconditional logCtx inspection.+- const inspector = (options?.inspectorFactory ?? createSseInspector)({+- logCtx,+- onCompletedResponse,+- onParsedPayload: options?.onParsedPayload,+- onFirstOutput,+- pinCompletedResponseIdToFirstSeen: options?.pinCompletedResponseIdToFirstSeen,+- });+- startBoundedInspectionPump({ ...options, reader, inspector, signal, onDone });+-}+-+-/**+- * Bun's fetch auto-decompresses the response body but leaves the upstream `content-encoding`+- * (and a now-stale `content-length`) on `response.headers`. Relaying those with the already-decoded+- * body makes the caller (Codex) double-decode / truncate → "stream error" on every gpt passthrough.+- * Drop encoding + hop-by-hop headers; relay everything else (content-type, etc.) verbatim.+- */+-export function sanitizePassthroughHeaders(upstream: Headers): Headers {+- const DROP = new Set([+- "content-encoding",+- "content-length",+- "transfer-encoding",+- "connection",+- "keep-alive",+- "proxy-authenticate",+- "proxy-authorization",+- "set-cookie",+- "set-cookie2",+- "te",+- "trailer",+- "upgrade",+- ]);+- const out = new Headers();+- upstream.forEach((value, key) => {+- if (!DROP.has(key.toLowerCase())) out.set(key, value);+- });+- return out;+-}+--- a/src/types.ts++++ b/src/types.ts+@@ -1,122 +1,2 @@+-// AUTO-SPLIT barrel: src/types.ts re-exports every historical name; bodies live in src/types/*.+-// Values (runtime): tools + wire. Types (erased): request + config + provider + accounts.+-+-export type { OcxTool, OcxToolChoice } from "./types/tools";+-export {+- CODE_MODE_EXEC_TOOL_NAME,+- dottedToolName,+- namespacedToolName,+- normalizeDeclaredToolName,+- toolChoiceAliases,+- createToolChoiceResolver,+- toolChoiceCandidates,+- toolAllowedByChoice,+- resolveToolChoiceWireName,+- modelInList,+- isAllowedToolChoice,+- toolChoiceToolPredicate,+- declaresCodeModeExec,+-} from "./types/tools";+-+-export type { UpstreamHttpVersion, ReasoningSummaryDelivery, CodexAccountMode } from "./types/wire";+-export {+- UPSTREAM_HTTP_VERSION_VALUES,+- REASONING_SUMMARY_DELIVERY_VALUES,+- OPENAI_PROVIDER_TIER_VERSION,+- MODEL_ADAPTER_OVERRIDE_ALLOWED,+- captureWireAdapterHardPins,+- isWirePinnedModel,+- pinnedWireAdapter,+-} from "./types/wire";+-+-export type {+- OcxReasoningReplayIdentity,+- OcxReasoningReplayScopeRef,+- OcxParsedRequest,+- OcxContext,+- OcxMessage,+- OcxUserMessage,+- OcxAssistantMessage,+- OcxDeveloperMessage,+- OcxToolResultMessage,+- OcxTextContent,+- OcxImageContent,+- OcxContentPart,+- OcxThinkingContent,+- OcxToolCall,+- OcxProviderOpaqueToolCallMetadata,+- OcxAssistantContentPart,+- OcxRequestOptions,+- OcxMessagePhase,+- OcxProviderContinuationOwner,+- OcxProviderContinuationState,+- AdapterEvent,+- OcxUrlCitation,+- OcxUsage,+-} from "./types/request";+-+-export type {+- OcxClaudeCodeConfig,+- OcxClaudeDesktopFamily,+- OcxClaudeDesktopAssignment,+- OcxClaudeDesktopProfile,+- StorageCleanupPolicy,+- OcxCustomModel,+- OcxApiKeyEntry,+- OcxClientIntegrationsConfig,+- OcxConfigRebaseProvenance,+- OcxHubConfig,+- OcxRemoteGuiConfig,+- OcxConnectedClientId,+- OcxClientConnectionConfig,+- OcxConfig,+- OcxAccountPoolRotationStrategy,+- OcxAccountPoolQuotaWindow,+- OcxComboStrategy,+- OcxComboDefaultEffort,+- OcxComboReasoningEffortMode,+- OcxComboTarget,+- OcxComboConfig,+- OcxRoutingUnknownEvidenceMode,+- OcxRoutingProfileCandidate,+- OcxRoutingProfileRequirements,+- OcxRoutingProfileOptimize,+- OcxRoutingUnknownCostCapMode,+- OcxRoutingProfileLimits,+- OcxRoutingProfileUnknownEvidence,+- OcxRoutingProfileCompatibilitySuite,+- OcxRoutingProfileCompatibility,+- OcxRoutingProfileConfig,+- OcxTokenGuardianConfig,+- OcxImagesConfig,+- OcxSearchConfig,+- OcxVisionSidecarConfig,+- OcxWebSearchSidecarConfig,+-} from "./types/config";+-+-export type {+- RefreshPolicy,+- OpenRouterProviderRouting,+- VercelGatewayRouting,+- ResponsesItemIdRepairConfig,+- RateLimitRetryPolicy,+- TransientRetryPolicy,+- ProviderWebSearchBridgeBackend,+- ProviderWebSearchBridgeConfig,+- ProviderCostOverlay,+- RequestPacingRule,+- ProviderRequestPacingConfig,+- FastWire,+- AttemptTierOutcome,+- TierObservationContext,+- TierDecision,+- OcxProviderConfig,+-} from "./types/provider";+-+-export { PROVIDER_WEB_SEARCH_BRIDGE_BACKENDS } from "./types/provider";+-+-export type {+- CodexAccount,+- CodexAccountCredentials,+- CodexAccountCredentialRecord,+-} from "./types/accounts";++export * from "./types/tools";++export type * from "./types/provider";diff --git a/packages/responses-chat-bridge/package.json b/packages/responses-chat-bridge/package.jsonindex ce26a7d87d..1af26567a7 100644--- a/packages/responses-chat-bridge/package.json+++ b/packages/responses-chat-bridge/package.json@@ -27,5 +27,8 @@"typescript": "^5.7.0","typescript-eslint": "^8.0.0","vitest": "^3.2.4"+ },+ "dependencies": {+ "@cindy/model-compat": "workspace:*"}}diff --git a/packages/responses-chat-bridge/src/custom-tool-function-adapter.ts b/packages/responses-chat-bridge/src/custom-tool-function-adapter.tsindex 2a6cc995d0..424d53edb4 100644--- a/packages/responses-chat-bridge/src/custom-tool-function-adapter.ts+++ b/packages/responses-chat-bridge/src/custom-tool-function-adapter.ts@@ -1,411 +1,8 @@-import { Buffer } from 'node:buffer';-import { Transform, type TransformCallback } from 'node:stream';-import { TextDecoder } from 'node:util';--import { ChatBridgeToolContext, type ChatBridgeToolSpec } from './tool-context.js';-import type { ResponsesRequest } from './types.js';--const MAX_PENDING_BYTES = 16 * 1024 * 1024;-const MAX_PENDING_REQUESTS = 256;-const MAX_ACTIVE_RESPONSE_CALLS = 256;-const MAX_RESPONSE_ARGUMENT_BYTES = 16 * 1024 * 1024;-// The desktop proxy's upstream socket timeout is ten minutes. Keep mappings strictly longer so-// no request that can still be live is evicted, while failed/cancelled requests are eventually-// reclaimed instead of exhausting the bounded map for the rest of the process lifetime.-const PENDING_REQUEST_TTL_MS = 15 * 60 * 1000;--function isObject(value: unknown): value is Record<string, unknown> {- return typeof value === 'object' && value !== null && !Array.isArray(value);-}--function customToolName(tool: unknown): string | null {- if (typeof tool === 'string') return tool;- return isObject(tool) && tool.type === 'custom' && typeof tool.name === 'string'- ? tool.name- : null;-}--function stringifyInput(value: unknown): string {- if (typeof value === 'string') return value;- const serialized = JSON.stringify(value ?? '');- if (serialized === undefined) throw new Error('custom tool input is not JSON-serializable');- return serialized;-}--function unwrapArguments(value: unknown): string {- if (typeof value !== 'string') throw new Error('adapted custom tool call has no function arguments');- let parsed: unknown;- try {- parsed = JSON.parse(value);- } catch {- throw new Error('adapted custom tool call arguments are not valid JSON');- }- if (!isObject(parsed) || typeof parsed.input !== 'string') {- throw new Error('adapted custom tool call arguments have no string input');- }- return parsed.input;-}--/**- * Item ids are dialect-coupled. Codex >=0.152 stamps a `<kind>_<uuid7>` id on every input item- * it replays, and a Responses upstream rejects an item whose id prefix disagrees with its type- * (`Invalid 'input[n].id' ... Expected an ID that begins with 'fc'`). Flipping an item to the- * function dialect therefore has to flip its id prefix too.- */-const CUSTOM_TO_FUNCTION_ID_PREFIXES: ReadonlyArray<readonly [string, string]> = [- ['ctco_', 'fco_'],- ['ctc_', 'fc_'],-];--/**- * Rewrites one adapted item's id for the function dialect.- *- * Ids already in the function dialect are left untouched: the upstream minted them, so it is the- * authority on what it accepts, and `fc` is the prefix its own validator asks for. An id that is- * in neither dialect is dropped rather than forwarded — omitting `id` is exactly what Codex did- * before 0.152 and every Responses upstream accepts it, so a future Codex prefix we do not know- * about degrades to a missing id instead of failing the whole request. The- * `codexExecFunctionAdapter` e2e enforces this invariant against the pinned binary so a new- * prefix surfaces on the next bump instead of in production.- */-function adaptItemId(item: Record<string, unknown>): Record<string, unknown> {- const id = item.id;- if (typeof id !== 'string') return item;- for (const [from, to] of CUSTOM_TO_FUNCTION_ID_PREFIXES) {- if (id.startsWith(from)) return { ...item, id: `${to}${id.slice(from.length)}` };- }- if (id.startsWith('fc')) return item;- const next = { ...item };- delete next.id;- return next;-}--/** Repair only known dialect mismatches; opaque provider ids and absent ids stay intact.- * `call_id` identifies the invocation/result pair and must never be rewritten.- */-function normalizeToolItemId(item: Record<string, unknown>): Record<string, unknown> {- const prefixes: readonly [string, string] | null = item.type === 'custom_tool_call' ? ['fc_', 'ctc_']- : item.type === 'custom_tool_call_output' ? ['fco_', 'ctco_']- : item.type === 'function_call' ? ['ctc_', 'fc_']- : item.type === 'function_call_output' ? ['ctco_', 'fco_'] : null;- if (!prefixes || typeof item.id !== 'string' || !item.id.startsWith(prefixes[0])) return item;- return { ...item, id: prefixes[1] + item.id.slice(prefixes[0].length) };-}--/**- * Repair legacy histories on the wire, including tool-less compact requests and native-custom- * routes. Do not rewrite the rollout, tool payloads, opaque compaction blobs or unrelated ids.- * Return null for an unchanged body, following the proxy request-transform contract.- */-export function normalizeResponsesToolItemIds(body: unknown): Record<string, unknown> | null {- if (!isObject(body) || !Array.isArray(body.input)) return null;- let changed = false;- const input = body.input.map((item: unknown) => {- if (!isObject(item)) return item;- const next = normalizeToolItemId(item);- if (next !== item) changed = true;- return next;- });- // item_reference ids address server-owned stored items, not local payloads. Keep them opaque.- return changed ? { ...body, input } : null;-}--/** SSE argument events reference the output item, not the invocation's call_id. */-function customToolEvent(event: Record<string, unknown>): Record<string, unknown> {- return typeof event.item_id === 'string' && event.item_id.startsWith('fc_')- ? { ...event, item_id: 'ctc_' + event.item_id.slice(3) }- : event;-}--interface AdaptedCall {- spec: ChatBridgeToolSpec;- arguments: string;- input?: string;-}--/**- * Restores one adapted upstream response to the Responses custom-tool dialect.- *- * SSE frames may split UTF-8, JSON, and parallel function arguments across chunks, so `pending`- * holds incomplete framing while `calls` tracks each output index until its matching done event.- * Non-streaming JSON is buffered until EOF. Invalid adapted arguments and oversized buffers fail- * explicitly because passing a function call through would make Codex execute the wrong protocol.- */-class CustomToolResponseTransform extends Transform {- private readonly decoder = new TextDecoder();- private readonly calls = new Map<number, AdaptedCall>();- private pending = '';- private responseArgumentBytes = 0;-- constructor(- private readonly specs: ReadonlyMap<string, ChatBridgeToolSpec>,- private readonly sse: boolean,- ) {- super();- }-- private rewriteItem(item: unknown, call?: AdaptedCall): Record<string, unknown> | null {- if (!isObject(item) || item.type !== 'function_call') return null;- const spec = call?.spec ?? (typeof item.name === 'string' ? this.specs.get(item.name) : undefined);- if (!spec) return null;- const next: Record<string, unknown> = {- ...item,- type: 'custom_tool_call',- name: spec.name,- input: call?.input ?? unwrapArguments(call?.arguments ?? item.arguments),- };- delete next.arguments;- return normalizeToolItemId(next);- }- private rewriteEvent(event: unknown): Record<string, unknown>[] | null {- if (!isObject(event) || typeof event.type !== 'string') return null;- const index = typeof event.output_index === 'number' ? event.output_index : -1;- if (event.type === 'response.output_item.added' && isObject(event.item)) {- const spec = event.item.type === 'function_call' && typeof event.item.name === 'string'- ? this.specs.get(event.item.name)- : undefined;- if (!spec || index < 0) return null;- const argumentsText = typeof event.item.arguments === 'string' ? event.item.arguments : '';- const previous = this.calls.get(index);- if (!previous && this.calls.size >= MAX_ACTIVE_RESPONSE_CALLS) {- throw new Error('adapted custom tool response has too many active calls');- }- const nextArgumentBytes =- this.responseArgumentBytes- - (previous ? Buffer.byteLength(previous.arguments, 'utf8') : 0)- + Buffer.byteLength(argumentsText, 'utf8');- if (nextArgumentBytes > MAX_RESPONSE_ARGUMENT_BYTES) {- throw new Error('adapted custom tool response arguments exceed the 16 MiB limit');- }- this.responseArgumentBytes = nextArgumentBytes;- this.calls.set(index, {- spec,- arguments: argumentsText,- });- const item: Record<string, unknown> = {- ...event.item, type: 'custom_tool_call', name: spec.name, input: '',- };- delete item.arguments;- return [{ ...customToolEvent(event), item: normalizeToolItemId(item) }];- }-- const call = this.calls.get(index);- if (event.type === 'response.function_call_arguments.delta' && call) {- if (typeof event.delta === 'string') {- const deltaBytes = Buffer.byteLength(event.delta, 'utf8');- if (this.responseArgumentBytes + deltaBytes > MAX_RESPONSE_ARGUMENT_BYTES) {- throw new Error('adapted custom tool response arguments exceed the 16 MiB limit');- }- call.arguments += event.delta;- this.responseArgumentBytes += deltaBytes;- }- return [];- }- if (event.type === 'response.function_call_arguments.done' && call) {- call.input = unwrapArguments(typeof event.arguments === 'string' ? event.arguments : call.arguments);- const delta: Record<string, unknown> = {- ...customToolEvent(event), type: 'response.custom_tool_call_input.delta', delta: call.input,- };- const done: Record<string, unknown> = {- ...customToolEvent(event), type: 'response.custom_tool_call_input.done', input: call.input,- };- delete delta.arguments;- delete done.arguments;- return [delta, done];- }- if (event.type === 'response.output_item.done') {- const item = this.rewriteItem(event.item, call);- if (!item) return null;- this.calls.delete(index);- this.responseArgumentBytes -= call ? Buffer.byteLength(call.arguments, 'utf8') : 0;- return [{ ...customToolEvent(event), item }];- }- if (isObject(event.response) && Array.isArray(event.response.output)) {- let changed = false;- const output = event.response.output.map((item) => {- const next = this.rewriteItem(item);- if (!next) return item;- changed = true;- return next;- });- if (changed) return [{ ...event, response: { ...event.response, output } }];- }- return null;- }- private rewriteFrame(frame: string, delimiter: string): string {- const lines = frame.split(/\r?\n/);- const data = lines.filter((line) => line.startsWith('data:'))- .map((line) => line.slice(5).trimStart()).join('\n');- if (!data || data === '[DONE]') return frame + delimiter;- let event: unknown;- try {- event = JSON.parse(data);- } catch {- return frame + delimiter;- }- const rewritten = this.rewriteEvent(event);- if (rewritten === null) return frame + delimiter;- const named = lines.some((line) => line.startsWith('event:'));- return rewritten.map((next) => (- `${named ? `event: ${String(next.type)}\n` : ''}data: ${JSON.stringify(next)}${delimiter}`- )).join('');- }- private drainFrames(): void {- // Keep the incomplete tail in `pending`; only complete SSE frames are safe to rewrite.- for (;;) {- const lf = this.pending.indexOf('\n\n');- const crlf = this.pending.indexOf('\r\n\r\n');- const index = lf < 0 ? crlf : crlf < 0 ? lf : Math.min(lf, crlf);- if (index < 0) return;- const delimiter = index === crlf ? '\r\n\r\n' : '\n\n';- this.push(this.rewriteFrame(this.pending.slice(0, index), delimiter));- this.pending = this.pending.slice(index + delimiter.length);- }- }- override _transform(chunk: Buffer, _encoding: string, callback: TransformCallback): void {- try {- this.pending += this.decoder.decode(chunk, { stream: true });- if (this.sse) this.drainFrames();- if (Buffer.byteLength(this.pending, 'utf8') > MAX_PENDING_BYTES) {- throw new Error('adapted custom tool response exceeds the 16 MiB buffer limit');- }- callback();- } catch (error) {- callback(error as Error);- }- }- override _flush(callback: TransformCallback): void {- try {- this.pending += this.decoder.decode();- if (this.sse) {- this.drainFrames();- if (this.pending) this.push(this.rewriteFrame(this.pending, ''));- } else {- // A JSON response has no stable item boundary before EOF, so rewrite it as one document.- const parsed = JSON.parse(this.pending) as unknown;- const rewritten = this.rewriteEvent({ type: 'response.completed', response: parsed });- this.push(JSON.stringify(rewritten?.[0]?.response ?? parsed));- }- this.pending = '';- callback();- } catch (error) {- callback(error as Error);- }- }-}--export interface ResponsesCustomToolFunctionAdapter {- adaptRequest(body: unknown, requestId: number): unknown | null;- /** Idempotently release request-scoped response metadata after the request settles. */- releaseResponse(requestId: number): void;- createResponseTransform(requestId: number, response: {- contentType: string; contentEncoding: string;- }): Transform | null;-}--/** Symmetric adapter for Responses providers that only accept function tools. */-export function createResponsesCustomToolFunctionAdapter(- customToolNames: readonly string[],-): ResponsesCustomToolFunctionAdapter {- const selected = new Set(customToolNames);- const responseSpecs = new Map<number, {- specs: Map<string, ChatBridgeToolSpec>;- createdAt: number;- }>();-- const discardExpiredResponseSpecs = (now: number): void => {- for (const [requestId, pending] of responseSpecs) {- if (now - pending.createdAt >= PENDING_REQUEST_TTL_MS) responseSpecs.delete(requestId);- }- };-- return {- adaptRequest(body, requestId) {- if (!isObject(body) || !Array.isArray(body.tools)) return null;- const context = ChatBridgeToolContext.fromRequest(body as unknown as ResponsesRequest);- const specs = new Map<string, ChatBridgeToolSpec>();- const functionNames = new Map<string, string>();- const tools: unknown[] = [];- for (const tool of body.tools) {- const name = customToolName(tool);- if (!name || !selected.has(name)) {- tools.push(tool);- continue;- }- if (functionNames.has(name)) continue;- const functionName = context.chatNameForResponse(name, undefined, 'custom');- const spec = context.lookupChatName(functionName);- const chatTool = context.chatTools?.find((item) => item.function.name === functionName);- if (!spec || !chatTool) throw new Error(`cannot adapt Responses custom tool '${name}'`);- functionNames.set(name, functionName);- specs.set(functionName, spec);- tools.push({ type: 'function', ...chatTool.function });- }- if (specs.size === 0) return null;-- const calls = new Map<string, string>();- if (Array.isArray(body.input)) {- for (const item of body.input) {- if (isObject(item) && item.type === 'custom_tool_call'- && !Object.hasOwn(item, 'namespace')- && typeof item.name === 'string' && typeof item.call_id === 'string') {- const functionName = functionNames.get(item.name);- if (functionName) calls.set(item.call_id, functionName);- }- }- }- const input = Array.isArray(body.input) ? body.input.map((item) => {- if (!isObject(item) || typeof item.call_id !== 'string') return item;- const functionName = calls.get(item.call_id);- if (!functionName) return item;- if (item.type === 'custom_tool_call') {- const next: Record<string, unknown> = {- ...adaptItemId(item), type: 'function_call', name: functionName,- arguments: JSON.stringify({ input: stringifyInput(item.input) }),- };- delete next.input;- delete next.namespace;- return next;- }- return item.type === 'custom_tool_call_output'- ? { ...adaptItemId(item), type: 'function_call_output' }- : item;- }) : body.input;- let toolChoice = body.tool_choice;- if (isObject(toolChoice) && toolChoice.type === 'custom' && typeof toolChoice.name === 'string') {- const name = functionNames.get(toolChoice.name);- if (name) toolChoice = { type: 'function', name };- }- const now = Date.now();- discardExpiredResponseSpecs(now);- if (!responseSpecs.has(requestId) && responseSpecs.size >= MAX_PENDING_REQUESTS) {- throw new Error('too many in-flight custom tool requests to adapt safely');- }- responseSpecs.set(requestId, { specs, createdAt: now });- const adapted: Record<string, unknown> = { ...body, tools, input };- if (Object.hasOwn(body, 'tool_choice')) adapted.tool_choice = toolChoice;- return adapted;- },-- releaseResponse(requestId) {- responseSpecs.delete(requestId);- },-- createResponseTransform(requestId, response) {- const pending = responseSpecs.get(requestId);- responseSpecs.delete(requestId);- const specs = pending?.specs;- if (!specs?.size) return null;- const encoding = response.contentEncoding.trim().toLowerCase();- if (encoding && encoding !== 'identity') {- throw new Error('compressed custom tool responses cannot be adapted safely');- }- const contentType = response.contentType.toLowerCase();- const sse = contentType.startsWith('text/event-stream');- if (!sse && !contentType.includes('application/json')) {- throw new Error(`custom tool response has unsupported content type '${response.contentType}'`);- }- return new CustomToolResponseTransform(specs, sse);- },- };-}+/** Compatibility implementation is owned by the shared package; preserve this import contract. */+export {+ normalizeResponsesToolItemIds,+ createResponsesCustomToolFunctionAdapter+} from '@cindy/model-compat';+export type {+ ResponsesCustomToolFunctionAdapter+} from '@cindy/model-compat';diff --git a/packages/responses-chat-bridge/src/handler.ts b/packages/responses-chat-bridge/src/handler.tsindex d7be35aa60..c7a28627f3 100644--- a/packages/responses-chat-bridge/src/handler.ts+++ b/packages/responses-chat-bridge/src/handler.ts@@ -1,3 +1,4 @@+import { chatCompatibilityCapabilities, normalizeProviderRequest } from '@cindy/model-compat';import type { ServerResponse } from 'node:http';import { ChatSseTranslator } from './chat-sse-translator.js';@@ -197,11 +198,12 @@ export function createResponsesChatHandler(}const request = parsedBody as ResponsesRequest;const realModel = provider.rewriteModel?.(request.model) ?? request.model;+ const compatibilityRoute = { harness: 'codex' as const, protocol: 'openai-chat' as const, upstreamBase: provider.upstreamBase, model: realModel };let translated;try {translated = translateResponsesRequestWithContext(request, {model: realModel,- capabilities: provider.capabilities,+ capabilities: chatCompatibilityCapabilities(compatibilityRoute, provider.capabilities),onDroppedTool: (type, index) => {if (type === 'web_search') {log.warn?.('responses-chat bridge dropped unsupported built-in tool', {@@ -278,7 +280,7 @@ export function createResponsesChatHandler('content-type': 'application/json',accept: 'text/event-stream',},- body: JSON.stringify(chatRequest),+ body: JSON.stringify(normalizeProviderRequest(chatRequest, compatibilityRoute, { reasoningEffortAlreadyMapped: provider.capabilities?.reasoningEffortMap !== undefined })),signal: abort.signal,});upstream = await send();diff --git a/packages/responses-chat-bridge/src/responses-null-array-repair.ts b/packages/responses-chat-bridge/src/responses-null-array-repair.tsindex 47687f4b92..70b4aabdbc 100644--- a/packages/responses-chat-bridge/src/responses-null-array-repair.ts+++ b/packages/responses-chat-bridge/src/responses-null-array-repair.ts@@ -1,245 +1,8 @@-import { Transform, type TransformCallback } from "node:stream";--/**- * Repairs Responses output items whose required array fields were serialized as `null`.- *- * Some third-party models proxied through a Responses passthrough emit- * `response.output_item.added` items such as `{ type: 'reasoning', summary: null }` or- * `{ type: 'message', content: null }`. Codex's `ResponseItem` parser tolerates missing ids and- * unknown fields but requires these arrays, so the item is dropped and every following- * `output_text.delta` is discarded as "without active item" (#4251). The wire contract says- * these fields are arrays, so the only semantics-preserving repair is `null -> []`.- *- * Nothing else is touched: item types, ids, call ids and unknown fields pass through byte for- * byte, and frames that need no repair are re-emitted exactly as received.- */--interface JsonObject {- [key: string]: unknown;-}--function isObject(value: unknown): value is JsonObject {- return typeof value === "object" && value !== null && !Array.isArray(value);-}--/** Array fields Codex requires per item type. `reasoning.content` is optional and stays as is. */-const REQUIRED_ARRAY_FIELDS: Readonly<Record<string, readonly string[]>> = {- reasoning: ["summary"],- message: ["content"],-};--/** Returns the repaired item, or null when the item needs no repair. */-export function repairResponsesItemNullArrays(- item: unknown,-): JsonObject | null {- if (!isObject(item) || typeof item.type !== "string") return null;- const fields = REQUIRED_ARRAY_FIELDS[item.type];- if (!fields) return null;- let next: JsonObject | null = null;- for (const field of fields) {- if (item[field] !== null) continue;- next ??= { ...item };- next[field] = [];- }- return next;-}--function repairOutputList(output: unknown): unknown[] | null {- if (!Array.isArray(output)) return null;- let changed = false;- const next = output.map((item) => {- const repaired = repairResponsesItemNullArrays(item);- if (!repaired) return item;- changed = true;- return repaired;- });- return changed ? next : null;-}--/**- * Returns the repaired Responses SSE event, or null when the event needs no repair.- *- * Covers `response.output_item.added` / `response.output_item.done` (`event.item`) and every- * event carrying a full `response.output` array (`response.completed`, `response.incomplete`,- * non-streaming bodies wrapped by the caller).- */-export function repairResponsesEventNullArrays(- event: unknown,-): JsonObject | null {- if (!isObject(event) || typeof event.type !== "string") return null;- if (- event.type === "response.output_item.added" ||- event.type === "response.output_item.done"- ) {- const item = repairResponsesItemNullArrays(event.item);- return item ? { ...event, item } : null;- }- if (isObject(event.response)) {- const output = repairOutputList(event.response.output);- return output- ? { ...event, response: { ...event.response, output } }- : null;- }- return null;-}--/**- * A single SSE frame is never larger than a few KiB in practice; a frame that grows past this- * bound without a delimiter is forwarded verbatim instead of being buffered forever. Failing- * open here is deliberate: this transform only repairs, it must never turn a working stream- * into a proxy error.- */-const MAX_PENDING_FRAME_BYTES = 16 * 1024 * 1024;--/** One SSE event boundary: a line break (LF or CRLF) followed by an empty line. */-const FRAME_BOUNDARY = /\r?\n\r?\n/;--/** SSE frame rewriter; frames that need no repair are re-emitted byte for byte. */-export class ResponsesNullArrayRepairTransform extends Transform {- private readonly decoder = new TextDecoder();- private pending = "";-- private rewriteFrame(frame: string, delimiter: string): string {- const lines = frame.split(/\r?\n/);- const data = lines- .filter((line) => line.startsWith("data:"))- .map((line) => line.slice(5).trimStart())- .join("\n");- if (!data || data === "[DONE]") return frame + delimiter;- let event: unknown;- try {- event = JSON.parse(data);- } catch {- return frame + delimiter;- }- const repaired = repairResponsesEventNullArrays(event);- if (!repaired) return frame + delimiter;- const eventLine = lines.find((line) => line.startsWith("event:"));- return `${eventLine ? `${eventLine}\n` : ""}data: ${JSON.stringify(repaired)}${delimiter}`;- }-- private drainFrames(): void {- // SSE ends a line with LF or CRLF and an event with a blank line, so the four- // boundaries `\n\n`, `\r\n\r\n`, `\n\r\n` and `\r\n\n` are all legal and may be- // mixed by one upstream (same convention as the proxy's own frame reader).- // The matched delimiter is re-emitted verbatim.- for (;;) {- const match = FRAME_BOUNDARY.exec(this.pending);- if (!match) return;- const delimiter = match[0];- this.push(- this.rewriteFrame(this.pending.slice(0, match.index), delimiter),- );- this.pending = this.pending.slice(match.index + delimiter.length);- }- }-- override _transform(- chunk: Buffer,- _encoding: string,- callback: TransformCallback,- ): void {- this.pending += this.decoder.decode(chunk, { stream: true });- this.drainFrames();- if (Buffer.byteLength(this.pending, "utf8") > MAX_PENDING_FRAME_BYTES) {- this.push(this.pending);- this.pending = "";- }- callback();- }-- override _flush(callback: TransformCallback): void {- this.pending += this.decoder.decode();- this.drainFrames();- if (this.pending) this.push(this.rewriteFrame(this.pending, ""));- this.pending = "";- callback();- }-}--/**- * Builds the repair transform for one upstream response, or null when the body is not a plain- * (uncompressed) SSE stream. Non-SSE and compressed bodies are left untouched rather than- * rejected: the repair is best effort and must not change how such responses are delivered.- */-export function createResponsesNullArrayRepairTransform(response: {- contentType: string;- contentEncoding: string;-}): Transform | null {- const encoding = response.contentEncoding.trim().toLowerCase();- if (encoding && encoding !== "identity") return null;- if (- !response.contentType.trim().toLowerCase().startsWith("text/event-stream")- )- return null;- return new ResponsesNullArrayRepairTransform();-}--/**- * Chains response transforms into one so a proxy that accepts a single transform can run- * several. Bytes flow `head -> ... -> tail`; the chained transform ends only after the tail- * ends, and an error in any stage fails the whole chain. Null stages are skipped.- */-export function chainResponseTransforms(- ...stages: Array<Transform | null | undefined>-): Transform | null {- const present = stages.filter(- (stage): stage is Transform => stage instanceof Transform,- );- if (present.length === 0) return null;- if (present.length === 1) return present[0]!;- return new ChainedTransform(present);-}--class ChainedTransform extends Transform {- private readonly head: Transform;- private readonly tail: Transform;- private readonly stages: readonly Transform[];-- constructor(stages: readonly Transform[]) {- super();- this.stages = stages;- this.head = stages[0]!;- this.tail = stages[stages.length - 1]!;- for (let index = 0; index < stages.length; index += 1) {- const stage = stages[index]!;- stage.on("error", (error: Error) => this.destroy(error));- const next = stages[index + 1];- if (next) stage.pipe(next);- }- // Readable-side backpressure: when the consumer stops reading, stop pulling- // from the tail (pipe then throttles every earlier stage) until `_read` runs.- this.tail.on("data", (chunk: Buffer) => {- if (!this.push(chunk)) this.tail.pause();- });- }-- override _read(size: number): void {- if (this.tail.isPaused()) this.tail.resume();- super._read(size);- }-- override _transform(- chunk: Buffer,- _encoding: string,- callback: TransformCallback,- ): void {- if (this.head.write(chunk)) callback();- else this.head.once("drain", () => callback());- }-- override _flush(callback: TransformCallback): void {- this.tail.once("end", () => callback());- this.head.end();- }-- override _destroy(- error: Error | null,- callback: (error: Error | null) => void,- ): void {- for (const stage of this.stages) {- if (!stage.destroyed) stage.destroy();- }- callback(error);- }-}+/** Compatibility implementation is owned by the shared package; preserve this import contract. */+export {+ repairResponsesItemNullArrays,+ repairResponsesEventNullArrays,+ ResponsesNullArrayRepairTransform,+ createResponsesNullArrayRepairTransform,+ chainResponseTransforms+} from '@cindy/model-compat';diff --git a/packages/responses-chat-bridge/src/tool-context.ts b/packages/responses-chat-bridge/src/tool-context.tsindex 4914ce9482..b39420b36c 100644--- a/packages/responses-chat-bridge/src/tool-context.ts+++ b/packages/responses-chat-bridge/src/tool-context.ts@@ -1,282 +1,8 @@-import { Buffer } from 'node:buffer';-import { createHash } from 'node:crypto';--import type {- ChatCompletionsRequest,- ResponsesCustomTool,- ResponsesFunctionTool,- ResponsesNamespaceTool,- ResponsesRequest,-} from './types.js';--type ResponseTool = NonNullable<ResponsesRequest['tools']>[number];-const CHAT_TOOL_NAME_MAX_LENGTH = 64;-const TOOL_SEARCH_CHAT_NAME = 'tool_search';-const CUSTOM_TOOL_INPUT_DESCRIPTION =- 'Raw string input for the original custom tool. Preserve formatting exactly.';-const CUSTOM_EXEC_DESCRIPTION_MAX_BYTES = 32 * 1024;-const COMPACT_CUSTOM_EXEC_DESCRIPTION = [- 'Execute JavaScript in the Code Mode runtime. Pass the complete JavaScript source in `input`.',- 'Call tools on the global `tools` object with `await tools.<name>(...)`; namespace tools use',- 'the flattened `await tools.<namespace>__<name>(...)` form.',- 'Inspect `ALL_TOOLS` for available shell, patch, plugin, connector, and MCP tools.',- 'Use `yield_control()` to yield while execution continues, and `exit()` to stop early.',- 'Return user-visible output with `text(...)`, `image(...)`, `audio(...)`, or',- '`generatedImage(...)`. Share serializable state across exec calls with `store(key, value)`',- 'and `load(key)`, and report progress with `notify(value)`.',-].join(' ');--function isPlainObject(value: unknown): value is Record<string, unknown> {- return typeof value === 'object' && value !== null && !Array.isArray(value);-}--function shortHash(value: string): string {- return createHash('sha256').update(value).digest('hex').slice(0, 12);-}--function clampChatToolName(name: string): string {- if (name.length <= CHAT_TOOL_NAME_MAX_LENGTH) return name;- const suffix = `__${shortHash(name)}`;- return `${name.slice(0, CHAT_TOOL_NAME_MAX_LENGTH - suffix.length)}${suffix}`;-}--function normalizeFunctionParameters(parameters: unknown): Record<string, unknown> {- if (!isPlainObject(parameters)) return { type: 'object', properties: {} };- return parameters.type === 'object'- ? { ...parameters }- : { ...parameters, type: 'object' };-}--function stableToolDescription(tool: ResponsesCustomTool): string {- const metadata: Record<string, unknown> = { ...tool };- delete metadata.description;- try {- return `Original Responses custom tool metadata:\n${JSON.stringify(metadata)}`;- } catch {- return 'Original Responses custom tool metadata is unavailable.';- }-}--function chatCustomToolDescription(tool: ResponsesCustomTool, namespace?: string): string {- const metadata = stableToolDescription(tool);- if (!tool.description) return metadata;- const description = namespace === undefined- && tool.name === 'exec'- && Buffer.byteLength(tool.description, 'utf8') > CUSTOM_EXEC_DESCRIPTION_MAX_BYTES- ? COMPACT_CUSTOM_EXEC_DESCRIPTION- : tool.description;- return `${description}\n\n${metadata}`;-}--export type ChatBridgeToolKind = 'function' | 'namespace' | 'custom' | 'tool_search';-type ResponseToolIdentityKind = 'function' | 'custom' | 'tool_search';--export interface ChatBridgeToolSpec {- kind: ChatBridgeToolKind;- chatName: string;- name: string;- namespace?: string;-}--function responseToolIdentity(- kind: ResponseToolIdentityKind,- name: string,- namespace?: string,-): string {- return `${kind}\0${namespace ?? ''}\0${name}`;-}--function specIdentity(spec: ChatBridgeToolSpec): string {- const kind = spec.kind === 'custom' || spec.kind === 'tool_search'- ? spec.kind- : 'function';- return responseToolIdentity(kind, spec.name, spec.namespace);-}--/**- * One request-scoped catalog for the lossy Chat `function` namespace. It makes request and- * response translation symmetrical: names flattened for Chat are restored to their Responses- * function/custom/tool_search representation on the way back.- */-export class ChatBridgeToolContext {- private readonly chatToolsValue: NonNullable<ChatCompletionsRequest['tools']> = [];- private readonly specsByChatName = new Map<string, ChatBridgeToolSpec>();- private readonly chatNamesByResponseName = new Map<string, string>();-- static fromRequest(request: ResponsesRequest): ChatBridgeToolContext {- const context = new ChatBridgeToolContext();- for (const tool of request.tools ?? []) context.addResponseTool(tool);- context.collectHistoryTools(request.input);- return context;- }-- get chatTools(): ChatCompletionsRequest['tools'] {- return this.chatToolsValue.length > 0 ? this.chatToolsValue : undefined;- }-- lookupChatName(chatName: string): ChatBridgeToolSpec | undefined {- return this.specsByChatName.get(chatName);- }-- /** Whether a streamed name may still resolve to a longer catalogued Chat tool name. */- hasChatNamePrefix(prefix: string): boolean {- if (!prefix) return false;- for (const chatName of this.specsByChatName.keys()) {- if (chatName !== prefix && chatName.startsWith(prefix)) return true;- }- return false;- }-- chatNameForResponse(- name: string,- namespace?: string,- kind: ResponseToolIdentityKind = 'function',- ): string {- return this.chatNamesByResponseName.get(responseToolIdentity(kind, name, namespace))- ?? clampChatToolName(namespace ? `${namespace}__${name}` : name);- }-- private reserveName(preferred: string, identity: string): string {- const clamped = clampChatToolName(preferred);- const existing = this.specsByChatName.get(clamped);- if (!existing) return clamped;- if (specIdentity(existing) === identity) return clamped;- for (let attempt = 0; ; attempt += 1) {- const suffix = `__${shortHash(attempt === 0 ? identity : `${identity}\0${attempt}`)}`;- const candidate = `${clamped.slice(0, CHAT_TOOL_NAME_MAX_LENGTH - suffix.length)}${suffix}`;- const occupant = this.specsByChatName.get(candidate);- if (!occupant || specIdentity(occupant) === identity) return candidate;- }- }-- private addFunction(tool: ResponsesFunctionTool, namespace?: string): void {- const nested = isPlainObject((tool as unknown as Record<string, unknown>).function)- ? (tool as unknown as Record<string, unknown>).function- : undefined;- const source = nested ? { ...tool, ...nested } as ResponsesFunctionTool : tool;- if (!source.name?.trim()) return;- const identity = responseToolIdentity('function', source.name, namespace);- const chatName = this.reserveName(namespace ? `${namespace}__${source.name}` : source.name, identity);- if (this.specsByChatName.has(chatName)) return;- const spec: ChatBridgeToolSpec = {- kind: namespace ? 'namespace' : 'function',- chatName,- name: source.name,- ...(namespace ? { namespace } : {}),- };- this.specsByChatName.set(chatName, spec);- this.chatNamesByResponseName.set(identity, chatName);- this.chatToolsValue.push({- type: 'function',- function: {- name: chatName,- ...(source.description ? { description: source.description } : {}),- parameters: normalizeFunctionParameters(source.parameters),- ...(typeof source.strict === 'boolean' ? { strict: source.strict } : {}),- },- });- }-- private addCustom(tool: ResponsesCustomTool, namespace?: string): void {- if (!tool.name?.trim()) return;- const identity = responseToolIdentity('custom', tool.name, namespace);- const chatName = this.reserveName(namespace ? `${namespace}__${tool.name}` : tool.name, identity);- if (this.specsByChatName.has(chatName)) return;- const spec: ChatBridgeToolSpec = {- kind: 'custom',- chatName,- name: tool.name,- ...(namespace ? { namespace } : {}),- };- this.specsByChatName.set(chatName, spec);- this.chatNamesByResponseName.set(identity, chatName);- this.chatToolsValue.push({- type: 'function',- function: {- name: chatName,- description: chatCustomToolDescription(tool, namespace),- parameters: {- type: 'object',- properties: {- input: {- type: 'string',- description: CUSTOM_TOOL_INPUT_DESCRIPTION,- },- },- required: ['input'],- },- },- });- }-- private addToolSearch(): void {- const identity = responseToolIdentity('tool_search', TOOL_SEARCH_CHAT_NAME);- const chatName = this.reserveName(TOOL_SEARCH_CHAT_NAME, identity);- if (this.specsByChatName.has(chatName)) return;- const spec: ChatBridgeToolSpec = {- kind: 'tool_search',- chatName,- name: TOOL_SEARCH_CHAT_NAME,- };- this.specsByChatName.set(chatName, spec);- this.chatNamesByResponseName.set(identity, chatName);- this.chatToolsValue.push({- type: 'function',- function: {- name: chatName,- description: 'Search and load Codex tools, plugins, connectors, and MCP namespaces.',- parameters: {- type: 'object',- properties: {- query: { type: 'string', description: 'Search query for tools or connectors to load.' },- limit: { type: 'integer', description: 'Maximum number of tool groups to return.' },- },- required: ['query'],- },- },- });- }-- private addNamespace(tool: ResponsesNamespaceTool): void {- if (!tool.name?.trim()) return;- for (const child of tool.tools ?? tool.children ?? []) {- if (!isPlainObject(child) || typeof child.name !== 'string') continue;- if (child.type === 'function') this.addFunction(child as unknown as ResponsesFunctionTool, tool.name);- if (child.type === 'custom') this.addCustom(child as unknown as ResponsesCustomTool, tool.name);- }- }-- private addResponseTool(tool: ResponseTool): void {- if (typeof tool === 'string') {- this.addCustom({ type: 'custom', name: tool });- return;- }- if (!isPlainObject(tool)) return;- if (tool.type === 'function') this.addFunction(tool as unknown as ResponsesFunctionTool);- if (tool.type === 'custom') this.addCustom(tool as unknown as ResponsesCustomTool);- if (tool.type === 'tool_search') this.addToolSearch();- if (tool.type === 'namespace') this.addNamespace(tool as unknown as ResponsesNamespaceTool);- }-- private collectHistoryTools(input: ResponsesRequest['input']): void {- if (!Array.isArray(input)) return;- for (const item of input) {- if (!isPlainObject(item)) continue;- if (item.type === 'tool_search_call') this.addToolSearch();- if (item.type === 'custom_tool_call' && typeof item.name === 'string') {- this.addCustom(- { type: 'custom', name: item.name },- typeof item.namespace === 'string' ? item.namespace : undefined,- );- }- if (- (item.type === 'tool_search_output' || item.type === 'tool_search_call_output')- && Array.isArray(item.tools)- ) {- for (const tool of item.tools) {- this.addResponseTool(tool as ResponseTool);- }- }- }- }-}+/** Compatibility implementation is owned by the shared package; preserve this import contract. */+export {+ ChatBridgeToolContext+} from '@cindy/model-compat';+export type {+ ChatBridgeToolKind,+ ChatBridgeToolSpec+} from '@cindy/model-compat';diff --git a/packages/responses-chat-bridge/src/types.ts b/packages/responses-chat-bridge/src/types.tsindex b019c902d4..77a0d582da 100644--- a/packages/responses-chat-bridge/src/types.ts+++ b/packages/responses-chat-bridge/src/types.ts@@ -1,474 +1,44 @@-/**- * OpenAI Responses / Chat Completions 的 bridge 最小公开类型。- *- * 这里只声明转换器实际读写的字段。Responses 请求来自 Codex,遇到未知 input item- * 必须 fail-closed,不能静默删除上下文;其它顶层未知字段由转换器明确忽略。- */--import type { ServerResponse } from 'node:http';--export interface ResponsesInputTextPart {- type: 'input_text' | 'output_text' | 'text';- text: string;-}--export interface ResponsesInputImagePart {- type: 'input_image';- image_url?: string | {- url: string;- detail?: string;- };- file_id?: string;- detail?: string;-}--export interface ResponsesInputFilePart {- type: 'input_file';- file_id?: string;- file_data?: string;- file_url?: string;- filename?: string;-}--export interface ResponsesInputAudioPart {- type: 'input_audio';- input_audio?: {- data: string;- format: string;- };- data?: string;- format?: string;-}--export type ResponsesContentPart =- | ResponsesInputTextPart- | ResponsesInputImagePart- | ResponsesInputFilePart- | ResponsesInputAudioPart- | {- type: string;- [key: string]: unknown;-};--export interface ChatToolCallExtraContent {- [key: string]: unknown;- google?: {- [key: string]: unknown;- thought_signature?: string;- };-}--export type ResponsesInputItem =- | {- type?: 'message';- role: 'user' | 'assistant' | 'system' | 'developer';- content: string | ResponsesContentPart[];- }- | {- type: 'function_call';- call_id: string;- name: string;- arguments: string;- extra_content?: ChatToolCallExtraContent;- }- | {- type: 'function_call_output';- call_id: string;- output: unknown;- }- | {- type: 'reasoning';- [key: string]: unknown;- }- | {- type: string;- [key: string]: unknown;- };--export interface ResponsesFunctionTool {- type: 'function';- name: string;- description?: string;- parameters?: Record<string, unknown>;- strict?: boolean;-}--export interface ResponsesCustomTool {- type: 'custom';- name: string;- description?: string;- [key: string]: unknown;-}--export interface ResponsesNamespaceTool {- type: 'namespace';- name: string;- tools?: Array<ResponsesFunctionTool | ResponsesCustomTool | { type: string; [key: string]: unknown }>;- children?: Array<ResponsesFunctionTool | ResponsesCustomTool | { type: string; [key: string]: unknown }>;- [key: string]: unknown;-}--export interface ResponsesRequest {- model: string;- instructions?: string | ResponsesContentPart[];- input: string | ResponsesInputItem[];- tools?: Array<- | string- | ResponsesFunctionTool- | ResponsesCustomTool- | ResponsesNamespaceTool- | { type: string; [key: string]: unknown }- >;- tool_choice?: unknown;- parallel_tool_calls?: boolean;- max_output_tokens?: number;- reasoning?: { effort?: string; [key: string]: unknown };- temperature?: number;- top_p?: number;- frequency_penalty?: number;- presence_penalty?: number;- stop?: string | string[];- seed?: number;- user?: string;- metadata?: Record<string, unknown>;- service_tier?: string;- response_format?: unknown;- text?: { format?: unknown; [key: string]: unknown };- logit_bias?: Record<string, number>;- logprobs?: boolean;- top_logprobs?: number;- n?: number;- stream?: boolean;- store?: boolean;- [key: string]: unknown;-}--export interface ChatTextContentPart {- type: 'text';- text: string;-}--export interface ChatImageUrlContentPart {- type: 'image_url';- image_url: {- url: string;- detail?: string;- };-}--export interface ChatFileContentPart {- type: 'file';- file: {- file_id?: string;- file_data?: string;- file_url?: string;- filename?: string;- };-}--export interface ChatInputAudioContentPart {- type: 'input_audio';- input_audio: {- data: string;- format: string;- };-}--export type ChatUserContentPart =- | ChatTextContentPart- | ChatImageUrlContentPart- | ChatFileContentPart- | ChatInputAudioContentPart;--export interface ChatTextMessage {- role: 'system' | 'developer';- content: string;-}--export interface ChatUserMessage {- role: 'user';- content: string | ChatUserContentPart[];-}--export interface ChatAssistantMessage {- role: 'assistant';- content?: string | null;- /** DeepSeek/Kimi/Moonshot 的思考模型要求带 tool_calls 的 assistant 消息携带非空 reasoning_content。 */- reasoning_content?: string;- tool_calls?: Array<{- id: string;- type: 'function';- function: { name: string; arguments: string };- /** OpenAI 兼容层的厂商扩展;当前仅用于 Google Gemini thought signature。 */- extra_content?: ChatToolCallExtraContent;- }>;-}--export interface ChatToolMessage {- role: 'tool';- tool_call_id: string;- content: string;-}--export type ChatMessage = ChatTextMessage | ChatUserMessage | ChatAssistantMessage | ChatToolMessage;--export interface ChatCompletionsRequest {- model: string;- messages: ChatMessage[];- tools?: Array<{- type: 'function';- function: {- name: string;- description?: string;- parameters: Record<string, unknown>;- strict?: boolean;- };- }>;- tool_choice?: unknown;- parallel_tool_calls?: boolean;- max_tokens?: number;- max_completion_tokens?: number;- reasoning_effort?: string;- reasoning?: { effort: string };- thinking?: { type: string };- enable_thinking?: boolean;- reasoning_split?: boolean;- temperature?: number;- top_p?: number;- frequency_penalty?: number;- presence_penalty?: number;- stop?: string | string[];- seed?: number;- user?: string;- metadata?: Record<string, unknown>;- service_tier?: string;- response_format?: unknown;- logit_bias?: Record<string, number>;- logprobs?: boolean;- top_logprobs?: number;- stream: boolean;- stream_options?: { include_usage: true };-}--export type ChatDeveloperRole = 'developer' | 'system';-export type ChatMaxTokensField = 'max_tokens' | 'max_completion_tokens' | 'omit';-export type ChatImageInput = 'image_url';-export type ChatFileInput = 'file';-export type ChatAudioInput = 'input_audio';-export type ChatReasoningField =- | 'reasoning_effort'- | 'reasoning.effort'- | 'thinking.type'- | 'enable_thinking'- | 'reasoning_split'- | 'none';-export type ChatReasoningHistoryField = 'reasoning_content';-export type ChatPassthroughField =- | 'temperature'- | 'top_p'- | 'frequency_penalty'- | 'presence_penalty'- | 'stop'- | 'seed'- | 'user'- | 'metadata'- | 'service_tier'- | 'response_format'- | 'logit_bias'- | 'logprobs'- | 'top_logprobs';--/** 同协议族内的上游差异,全部由数据表达(对齐 cc-switch / opencodex 的 per-provider 处理)。 */-export interface ChatBridgeCapabilities {- developerRole?: ChatDeveloperRole;- parallelToolCalls?: boolean;- maxTokensField?: ChatMaxTokensField;- reasoningField?: ChatReasoningField;- /**- * Responses reasoning history 的 Chat 消息字段。默认未声明 = 省略历史 reasoning;- * 只有明确接受厂商扩展 `reasoning_content` 的上游才应开启。- */- reasoningHistoryField?: ChatReasoningHistoryField;- /**- * Responses `input_image` 的上游等价形态。默认未声明 = fail closed;只由- * 已确认支持视觉输入的运行时(当前为 upstream 白名单)开启。- */- imageInput?: ChatImageInput;- /** Responses `input_file` 的上游等价形态;默认未声明 = fail closed。 */- fileInput?: ChatFileInput;- /** Responses `input_audio` 的上游等价形态;默认未声明 = fail closed。 */- audioInput?: ChatAudioInput;- /** 仅对明确采用 `<think>...</think>` 内联推理方言的上游启用标签解析。 */- inlineReasoning?: boolean;- /** 将 Responses reasoning.effort 映射成供应商接受的枚举值。未声明时原样使用。 */- reasoningEffortMap?: Readonly<Record<string, string | boolean>>;- /** 只有显式列入的 Chat 可选字段才会转发,避免严格兼容端点因未知字段返回 400。 */- passthroughFields?: readonly ChatPassthroughField[];- streamUsage?: boolean;- /**- * thinking 模型(DeepSeek/Kimi/Moonshot)要求每个带 tool_calls 的 assistant 消息携带非空- * reasoning_content,否则上游报 `reasoning_content is missing in assistant tool call message`。- * 开启后为缺失的 tool_call assistant 消息注入占位文本。- */- toolCallReasoningPlaceholder?: boolean;- /**- * reasoning 模型拒绝强制 tool_choice(如 DeepSeek `Thinking mode does not support this tool_choice`)。- * 开启后把具名 / required 的 tool_choice 降级为 'auto'。- */- forceAutoToolChoice?: boolean;- /**- * Gemini 3 在工具结果下一轮强制校验 thought signature。Responses 历史不承载 Google 的- * `tool_calls[].extra_content`,开启后按 Google 官方兼容说明给每步首个 call 写入- * `skip_thought_signature_validator`,避免桥接历史在首个工具调用后稳定 400。- */- googleThoughtSignaturePlaceholder?: boolean;- /** 缺少上游 usage 时仍生成 Responses 要求的完整零值 usage 结构。默认开启。 */- zeroUsageOnMissing?: boolean;- /**- * Ollama/Qwen Chat 模板要求 system 只能出现在消息列表开头。- * `coalesce-leading` 把所有 system/developer 按原顺序合并成唯一的首条 system。- */- systemMessagePolicy?: 'preserve' | 'coalesce-leading';-}--export interface ChatBridgeLogger {- debug?: (msg: string, meta?: Record<string, unknown>) => void;- info?: (msg: string, meta?: Record<string, unknown>) => void;- warn?: (msg: string, meta?: Record<string, unknown>) => void;- error?: (msg: string, meta?: Record<string, unknown>) => void;-}--export interface ChatBridgeUpstreamErrorInfo {- status: number;- body: string;- /** 可能含凭证,只能用于内存态关联,禁止写日志。 */- requestHeaders: Readonly<Record<string, string>>;-}--export interface ChatBridgeProviderConfig {- upstreamBase: string;- /** 缺省 `/chat/completions`;少数厂商可显式覆盖。 */- chatCompletionsPath?: string;- buildHeaders: () => Promise<Record<string, string>>;- /** 把 wire model 改成上游真实 model;缺省原样。 */- rewriteModel?: (model: string) => string;- capabilities?: ChatBridgeCapabilities;- onUpstreamError?: (info: ChatBridgeUpstreamErrorInfo) => void | Promise<void>;-}--export interface ChatBridgeHandleArgs {- parsedBody: unknown;- res: ServerResponse;- /**- * 经本地代理验证过的入站请求头快照(#4073)。bridge **不**透传它们,只从中解析稳定会话- * 标识映射为出站 `x-opencode-session`(见 session-header.ts);省略 = 不附加会话头。- */- requestHeaders?: Readonly<Record<string, string>>;-}--export interface ResponsesChatBridgeHandler {- handle(args: ChatBridgeHandleArgs): Promise<void>;-}--const UNSUPPORTED_RESPONSES_FEATURE_MESSAGE_PREFIX =- 'Responses feature is not supported by the Chat Completions bridge: ';-const RESPONSES_IMAGE_CONTENT_PART_TYPES = new Set(['input_image', 'image_url', 'image']);-const CODEX_UNEXPECTED_BAD_REQUEST_PREFIX = /^unexpected status 400(?: Bad Request)?: /;-const CODEX_ERROR_METADATA_MARKERS = [- ', url: ',- ', cf-ray: ',- ', request id: ',- ', auth error: ',- ', auth error code: ',-] as const;--export function isResponsesImageContentPartType(- value: unknown,-): value is 'input_image' | 'image_url' | 'image' {- return typeof value === 'string' && RESPONSES_IMAGE_CONTENT_PART_TYPES.has(value);-}--function unsupportedResponsesFeatureFromMessage(message: string): string | null {- return message.startsWith(UNSUPPORTED_RESPONSES_FEATURE_MESSAGE_PREFIX)- ? message.slice(UNSUPPORTED_RESPONSES_FEATURE_MESSAGE_PREFIX.length)- : null;-}--function isUnsupportedResponsesImageFeature(feature: string): boolean {- const contentPartMatch = /^input content part '([^']+)'$/.exec(feature);- const contentPartType = contentPartMatch?.[1] ?? feature;- return isResponsesImageContentPartType(contentPartType)- || contentPartType.startsWith('input_image.');-}--function isUnsupportedResponsesImageErrorObject(value: unknown): boolean {- if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;- const error = (value as Record<string, unknown>).error;- if (typeof error !== 'object' || error === null || Array.isArray(error)) return false;- const { code, message } = error as Record<string, unknown>;- if (code !== 'unsupported_feature' || typeof message !== 'string') return false;- const feature = unsupportedResponsesFeatureFromMessage(message);- return feature !== null && isUnsupportedResponsesImageFeature(feature);-}--function parseJson(value: string): unknown {- try {- return JSON.parse(value) as unknown;- } catch {- return null;- }-}--function parseCodexWrappedJson(value: string): unknown {- const jsonStart = value.indexOf('{');- if (jsonStart < 0) return null;-- // Codex may append transport metadata after the serialized response body. Walk closing braces- // from right to left so braces in that metadata cannot prevent recovery of the response object.- let jsonEnd = value.lastIndexOf('}');- while (jsonEnd > jsonStart) {- const parsed = parseJson(value.slice(jsonStart, jsonEnd + 1));- if (parsed !== null) return parsed;- jsonEnd = value.lastIndexOf('}', jsonEnd - 1);- }- return null;-}--function stripCodexErrorMetadata(value: string): string {- let end = value.length;- for (const marker of CODEX_ERROR_METADATA_MARKERS) {- const index = value.indexOf(marker);- if (index >= 0 && index < end) end = index;- }- return value.slice(0, end);-}--/**- * Classifies an unsupported-image error emitted by this bridge. Direct OpenAI-style response- * bodies and Codex's `unexpected status 400 ...` rendering are both accepted; current Codex- * extracts `error.message`, while older/future runtimes may retain the serialized body. Both the- * current content-part feature and the legacy direct `input_image` feature remain recoverable.- */-export function isUnsupportedResponsesImageErrorPayload(payload: string | null): boolean {- if (!payload) return false;- if (isUnsupportedResponsesImageErrorObject(parseJson(payload))) return true;-- const codexPrefix = CODEX_UNEXPECTED_BAD_REQUEST_PREFIX.exec(payload);- if (!codexPrefix) return false;- const renderedBody = payload.slice(codexPrefix[0].length);- if (isUnsupportedResponsesImageErrorObject(parseCodexWrappedJson(renderedBody))) return true;-- const message = stripCodexErrorMetadata(renderedBody);- const feature = unsupportedResponsesFeatureFromMessage(message);- return feature !== null && isUnsupportedResponsesImageFeature(feature);-}--export class UnsupportedResponsesFeatureError extends Error {- readonly feature: string;-- constructor(feature: string) {- super(`${UNSUPPORTED_RESPONSES_FEATURE_MESSAGE_PREFIX}${feature}`);- this.name = 'UnsupportedResponsesFeatureError';- this.feature = feature;- }-}+/** Compatibility implementation is owned by the shared package; preserve this import contract. */+export {+ isResponsesImageContentPartType,+ isUnsupportedResponsesImageErrorPayload,+ UnsupportedResponsesFeatureError+} from '@cindy/model-compat';+export type {+ ResponsesInputTextPart,+ ResponsesInputImagePart,+ ResponsesInputFilePart,+ ResponsesInputAudioPart,+ ResponsesContentPart,+ ChatToolCallExtraContent,+ ResponsesInputItem,+ ResponsesFunctionTool,+ ResponsesCustomTool,+ ResponsesNamespaceTool,+ ResponsesRequest,+ ChatTextContentPart,+ ChatImageUrlContentPart,+ ChatFileContentPart,+ ChatInputAudioContentPart,+ ChatUserContentPart,+ ChatTextMessage,+ ChatUserMessage,+ ChatAssistantMessage,+ ChatToolMessage,+ ChatMessage,+ ChatCompletionsRequest,+ ChatDeveloperRole,+ ChatMaxTokensField,+ ChatImageInput,+ ChatFileInput,+ ChatAudioInput,+ ChatReasoningField,+ ChatReasoningHistoryField,+ ChatPassthroughField,+ ChatBridgeCapabilities,+ ChatBridgeLogger,+ ChatBridgeUpstreamErrorInfo,+ ChatBridgeProviderConfig,+ ChatBridgeHandleArgs,+ ResponsesChatBridgeHandler+} from '@cindy/model-compat';diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 4551fd5934..062236115d 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -118,6 +118,9 @@ importers:'@cindy/mcps':specifier: workspace:*version: link:../../packages/lizi-mcps+ '@cindy/model-compat':+ specifier: workspace:*+ version: link:../../packages/model-compat'@cindy/model-providers':specifier: workspace:*version: link:../../packages/model-providers@@ -791,6 +794,10 @@ importers:version: 3.2.7(@types/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected])([email protected])([email protected])([email protected])packages/anthropic-compat-proxy:+ dependencies:+ '@cindy/model-compat':+ specifier: workspace:*+ version: link:../model-compatdevDependencies:'@eslint/js':specifier: ^9.0.0@@ -818,6 +825,10 @@ importers:version: 3.2.7(@types/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected])([email protected])([email protected])([email protected])packages/anthropic-responses-bridge:+ dependencies:+ '@cindy/model-compat':+ specifier: workspace:*+ version: link:../model-compatdevDependencies:'@eslint/js':specifier: ^9.0.0@@ -1289,6 +1300,27 @@ importers:specifier: ^3.2.4version: 3.2.7(@types/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected])([email protected])([email protected])([email protected])+ packages/model-compat:+ devDependencies:+ '@eslint/js':+ specifier: ^9.0.0+ version: 9.39.5+ '@types/node':+ specifier: '*'+ version: 25.9.5+ eslint:+ specifier: ^9.0.0+ version: 9.39.5([email protected])+ typescript:+ specifier: ^5.7.0+ version: 5.9.3+ typescript-eslint:+ specifier: ^8.0.0+ vitest:+ specifier: ^3.2.4+ version: 3.2.7(@types/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected])([email protected])([email protected])([email protected])+packages/model-providers:devDependencies:'@types/node':@@ -1452,6 +1484,10 @@ importers:version: 3.2.7(@types/[email protected])(@types/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected])([email protected])([email protected])([email protected])packages/responses-chat-bridge:+ dependencies:+ '@cindy/model-compat':+ specifier: workspace:*+ version: link:../model-compatdevDependencies:'@eslint/js':specifier: ^9.0.0diff --git a/scripts/__tests__/remote-bundle-inputs.test.mjs b/scripts/__tests__/remote-bundle-inputs.test.mjsnew file mode 100644index 0000000000..f9692ce779--- /dev/null+++ b/scripts/__tests__/remote-bundle-inputs.test.mjs@@ -0,0 +1,39 @@+import assert from 'node:assert/strict';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import test from 'node:test';+import { newestBundleInputMtime } from '../../apps/desktop/scripts/remote-bundle-inputs.mjs';++function fixture(run) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-remote-bundle-inputs-'));+ const write = (name, seconds) => {+ const file = path.join(root, name);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, 'fixture');+ fs.utimesSync(file, seconds, seconds);+ };+ try { run(root, write); } finally { fs.rmSync(root, { recursive: true, force: true }); }+}++test('a compatibility dependency update invalidates a newer consumer bundle', () => fixture((root, write) => {+ write('proxy/src/index.ts', 1000);+ write('proxy/dist/proxy.mjs', 1500);+ write('compat/src/upstream/provider.ts', 2000);+ const newest = newestBundleInputMtime(path.join(root, 'proxy'), [path.join(root, 'compat')]);+ assert.equal(newest, 2000000);+ assert.ok(newest > fs.statSync(path.join(root, 'proxy/dist/proxy.mjs')).mtimeMs);+}));++test('license changes invalidate the single-file remote artifact, generated output does not', () => fixture((root, write) => {+ write('proxy/src/index.ts', 1000);+ write('proxy/dist/proxy.mjs', 9000);+ write('compat/src/index.ts', 2000);+ write('compat/LICENSE.opencodex', 3000);+ assert.equal(newestBundleInputMtime(path.join(root, 'proxy'), [path.join(root, 'compat')]), 3000000);+}));++test('missing declared dependency does not leave a stale bundle silently marked fresh', () => fixture((root, write) => {+ write('proxy/src/index.ts', 1000);+ assert.throws(() => newestBundleInputMtime(path.join(root, 'proxy'), [path.join(root, 'missing')]), /dependency is missing/);+}));diff --git a/scripts/test-workspaces.config.mjs b/scripts/test-workspaces.config.mjsindex 529e6734c4..6a1746a9ae 100644--- a/scripts/test-workspaces.config.mjs+++ b/scripts/test-workspaces.config.mjs@@ -233,6 +233,7 @@ export default {requiredUnitWorkspace('@cindy/anthropic-compat-proxy', 'packages/anthropic-compat-proxy'),requiredUnitWorkspace('@cindy/anthropic-responses-bridge', 'packages/anthropic-responses-bridge'),requiredUnitWorkspace('@cindy/responses-anthropic-bridge', 'packages/responses-anthropic-bridge'),+ requiredUnitWorkspace('@cindy/model-compat', 'packages/model-compat'),requiredUnitWorkspace('@cindy/responses-chat-bridge', 'packages/responses-chat-bridge'),requiredUnitWorkspace('@cindy/auth-client', 'packages/auth-client'),requiredUnitWorkspace('@cindy/browser-control-runtime', 'packages/browser-control-runtime'),