Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): cc proxy 防御 kimi 序号 tool id 复用与配对断裂致会话瘫痪 (#1001)
yan83216aebc886
diff --git a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.tsindex eec98aebea..f9a557cf77 100644--- a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts+++ b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts@@ -19,11 +19,15 @@import {createAnthropicCompatProxy,createActiveStripTransform,+ createDuplicateToolUseIdRecoveryRule,createEmptyAssistantMessageRecoveryRule,createEmptyTextRecoveryRule,createEmptyThinkingRecoveryRule,createEncryptedContentRecoveryRule,+ createToolExchangeAdjacencyRecoveryRule,createToolUseProviderSpecificFieldsRecoveryRule,+ dedupeDuplicateToolUseIds,+ repairToolExchangeAdjacency,stripEmptyAssistantMessagesFromBody,stripEmptyTextFromBody,stripEmptyThinkingFromBody,@@ -327,6 +331,17 @@ export async function ensureAnthropicCompatProxyReady(): Promise<void> {enabled: () => true,strip: stripEmptyAssistantMessagesFromBody,}),+ // tool 配对断裂修复 —— always-on 检测即修(孤儿/前置/超编 result 丢弃 ++ // 错位前移 + 非 trailing 缺失合成占位;与 kimi code projector 的+ // consumed-scan 接力配对同构)。**必须在 dedupe 之前**:它产出的结构+ // 合法历史上 result 与 call 严格同序,dedupe 的顺序配对才等于真实配对+ // (复审实测反例: 前置 result 白占序号会致 dedupe 张冠李戴)。+ repairToolExchangeAdjacency,+ // 重复 tool_use id 唯一化 —— always-on 检测即修(moonshot/kimi 序号 id+ // 跨 turn 复用致会话安静瘫痪,2026-07 两个会话实测 `Edit_306`/`Bash_256`+ // 各复用 20+ 次;重写方案与 kosong normalize 同构,详见 transform.ts 头注)。+ // 无重复返回 null 字节透传,不需要 controller(异常在请求体里可直接检测)。+ dedupeDuplicateToolUseIds,// LiteLLM/provider adapter 可能把 provider_specific_fields(null) 挂到 tool_use 上,// 严格 Anthropic 入站 schema 不接受该扩展字段。stripToolUseProviderSpecificFields,@@ -354,6 +369,16 @@ export async function ensureAnthropicCompatProxyReady(): Promise<void> {onRetry: (threadId, model) => emptyAssistantStripController.markActive(threadId, model),}),createToolUseProviderSpecificFieldsRecoveryRule(),+ // tool 配对断裂 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。+ // 两条 tool exchange 规则的 strip 同为 repairToolExchangeStructureFromBody+ // (内建 repair → dedupe 顺序,与上方主动链一致;命中顺序不再影响正确性)。+ createToolExchangeAdjacencyRecoveryRule(),+ // 重复 tool_use id 400(``tool_use` ids must be unique`)→ 组合结构修复+ // 重发,always-on(moonshot 实测不报错,但 LiteLLM 版本差 / 真 Anthropic+ // 上游会报;主动 transform 已检测即修,此为第二道防线)。+ createDuplicateToolUseIdRecoveryRule(),],logger: log,// 请求体 dump 默认关(dev trace 级别 + agent 高并发会刷爆 main event loopdiff --git a/packages/anthropic-compat-proxy/src/index.ts b/packages/anthropic-compat-proxy/src/index.tsindex 2e2936cac9..925535d9ad 100644--- a/packages/anthropic-compat-proxy/src/index.ts+++ b/packages/anthropic-compat-proxy/src/index.ts@@ -35,12 +35,19 @@ export {} from './instructions-injection.js';export {createActiveStripTransform,+ createDuplicateToolUseIdRecoveryRule,createEmptyAssistantMessageRecoveryRule,createEmptyTextRecoveryRule,createEmptyThinkingRecoveryRule,createEncryptedContentRecoveryRule,createImageGenerationIdRecoveryRule,+ createToolExchangeAdjacencyRecoveryRule,createToolUseProviderSpecificFieldsRecoveryRule,+ dedupeDuplicateToolUseIds,+ dedupeDuplicateToolUseIdsFromBody,+ repairToolExchangeAdjacency,+ repairToolExchangeAdjacencyFromBody,+ repairToolExchangeStructureFromBody,stripEmptyAssistantMessagesFromBody,stripEmptyTextFromBody,stripEmptyThinkingFromBody,diff --git a/packages/anthropic-compat-proxy/src/server.test.ts b/packages/anthropic-compat-proxy/src/server.test.tsindex 230d1000a0..7d353a5c20 100644--- a/packages/anthropic-compat-proxy/src/server.test.ts+++ b/packages/anthropic-compat-proxy/src/server.test.ts@@ -10,11 +10,15 @@ import {} from './server.js';import {createActiveStripTransform,+ createDuplicateToolUseIdRecoveryRule,createEmptyAssistantMessageRecoveryRule,createEmptyThinkingRecoveryRule,createEncryptedContentRecoveryRule,createImageGenerationIdRecoveryRule,+ createToolExchangeAdjacencyRecoveryRule,createToolUseProviderSpecificFieldsRecoveryRule,+ dedupeDuplicateToolUseIds,+ repairToolExchangeAdjacency,stripEncryptedContentFromBody,} from './transform.js';import { listenOnAvailableLoopbackPort } from './test-loopback-server.js';@@ -1335,6 +1339,236 @@ function kimiBodyWithEmptyAssistant(): unknown {};}+// ───────────────────────────────────────────────────────────────────────────+// 重复 tool_use id(moonshot/kimi 序号 id 跨 turn 复用,2026-07 两个会话实测+// `Edit_306` / `Bash_256` 各复用 20+ 次致安静瘫痪)的全链路防御实测。+// ───────────────────────────────────────────────────────────────────────────++// kimi-k3 事故会话形态: 同一序号 id 的两对完整 tool 交换跨 turn 出现。+function kimiBodyWithDuplicatedToolUseIds(): Record<string, unknown> {+ return {+ model: 'moonshot/kimi-k3',+ messages: [+ { role: 'user', content: '把 race-2 修掉' },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'Edit_306', name: 'Edit', input: { file: 'a.ts', old: 'x', new: 'y' } }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'Edit_306', content: 'has been updated successfully' }] },+ { role: 'assistant', content: [{ type: 'text', text: '继续修复计划' }, { type: 'tool_use', id: 'Edit_306', name: 'Edit', input: { file: 'a.ts', old: 'x', new: 'y' } }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'Edit_306', content: 'String to replace not found' }] },+ ],+ };+}++// Anthropic 文案的重复 id 400(LiteLLM 版本差 / 真 Anthropic 上游可见)。+const DUPLICATE_TOOL_USE_ID_ERROR_BODY = JSON.stringify({+ error: { type: 'invalid_request_error', message: 'messages: `tool_use` ids must be unique' },+});++// moonshot chatcmpl 校验透出的孤儿 result 400(原文双空格,kimi kosong 注释同款)。+const MOONSHOT_TOOL_CALL_ID_NOT_FOUND_BODY = JSON.stringify({+ error: { type: 'invalid_request_error', message: 'Invalid request: tool_call_id is not found' },+});++describe('anthropic-compat-proxy duplicate tool_use id (kimi/moonshot 序号 id 复用)', () => {+ it('proactively rewrites duplicated ids before forwarding — no 400 needed', async () => {+ const upstream = await startFakeUpstream((_idx, _body, res) => {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ ok: true }));+ });+ upstreamClose = upstream.close;+ proxy = await createAnthropicCompatProxy({+ upstream: upstream.url,+ transformRequest: [repairToolExchangeAdjacency, dedupeDuplicateToolUseIds], // host 同序: repair 先于 dedupe+ recoveryRules: [],+ });++ const r = await post(proxy.url, kimiBodyWithDuplicatedToolUseIds());++ expect(r.status).toBe(200);+ // 只发一次:主动 transform 在转发前修好,不等上游报错。+ expect(upstream.bodies).toHaveLength(1);+ const sent = JSON.parse(upstream.bodies[0]);+ // 第二对 Edit_306 被唯一化,首对与配对关系保持完整。+ expect(sent.messages[1].content[0].id).toBe('Edit_306');+ expect(sent.messages[2].content[0].tool_use_id).toBe('Edit_306');+ expect(sent.messages[3].content[1].id).toBe('Edit_306_2');+ expect(sent.messages[4].content[0].tool_use_id).toBe('Edit_306_2');+ // text 块与业务 input 原样保留。+ expect(sent.messages[3].content[0]).toEqual({ type: 'text', text: '继续修复计划' });+ expect(sent.messages[3].content[1].input).toEqual({ file: 'a.ts', old: 'x', new: 'y' });+ });++ it('passes a clean paired history through byte-identical (zero interference)', async () => {+ const upstream = await startFakeUpstream((_idx, _body, res) => {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ ok: true }));+ });+ upstreamClose = upstream.close;+ proxy = await createAnthropicCompatProxy({+ upstream: upstream.url,+ transformRequest: [repairToolExchangeAdjacency, dedupeDuplicateToolUseIds], // host 同序: repair 先于 dedupe+ recoveryRules: [],+ });++ const cleanBody = {+ model: 'moonshot/kimi-k3',+ messages: [+ { role: 'user', content: 'run ls' },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'Bash_256', name: 'Bash', input: { command: 'ls' } }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'Bash_256', content: 'ok' }] },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'Read_257', name: 'Read', input: { file: 'a.ts' } }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'Read_257', content: 'file content' }] },+ ],+ };+ const r = await post(proxy.url, cleanBody);++ expect(r.status).toBe(200);+ expect(upstream.bodies).toHaveLength(1);+ // cache 安全契约在链路上的实测:无异常时 upstream 收到的字节与客户端发出的一致。+ expect(upstream.bodies[0]).toBe(JSON.stringify(cleanBody));+ });++ it('recovers from a 400 "`tool_use` ids must be unique" via transparent retry', async () => {+ const upstream = await startFakeUpstream((idx, _body, res) => {+ if (idx === 0) {+ res.writeHead(400, { 'content-type': 'application/json' });+ res.end(DUPLICATE_TOOL_USE_ID_ERROR_BODY);+ } else {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ ok: true }));+ }+ });+ upstreamClose = upstream.close;+ proxy = await createAnthropicCompatProxy({+ upstream: upstream.url,+ // 空 transform 链:验证 recovery 在主动 transform 未接入的链路上独立工作。+ transformRequest: [],+ recoveryRules: [createDuplicateToolUseIdRecoveryRule({ enabled: () => true })],+ });++ const r = await post(proxy.url, kimiBodyWithDuplicatedToolUseIds());++ expect(r.status).toBe(200);+ expect(upstream.bodies).toHaveLength(2);+ // 第一次原样发出(重复 id 还在),第二次已唯一化。+ expect(upstream.bodies[0]).toBe(JSON.stringify(kimiBodyWithDuplicatedToolUseIds()));+ const retried = JSON.parse(upstream.bodies[1]);+ expect(retried.messages[3].content[1].id).toBe('Edit_306_2');+ expect(retried.messages[4].content[0].tool_use_id).toBe('Edit_306_2');+ });++ it('recovers from the moonshot "tool_call_id is not found" 400 by dropping the orphan result', async () => {+ const upstream = await startFakeUpstream((idx, _body, res) => {+ if (idx === 0) {+ res.writeHead(400, { 'content-type': 'application/json' });+ res.end(MOONSHOT_TOOL_CALL_ID_NOT_FOUND_BODY);+ } else {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ ok: true }));+ }+ });+ upstreamClose = upstream.close;+ proxy = await createAnthropicCompatProxy({+ upstream: upstream.url,+ transformRequest: [],+ recoveryRules: [createToolExchangeAdjacencyRecoveryRule({ enabled: () => true })],+ });++ const r = await post(proxy.url, {+ model: 'moonshot/kimi-k3',+ messages: [+ { role: 'user', content: 'go' },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'Bash_1', name: 'Bash', input: {} }] },+ {+ role: 'user',+ content: [+ { type: 'tool_result', tool_use_id: 'Bash_1', content: 'ok' },+ { type: 'tool_result', tool_use_id: 'Edit_999', content: 'stray' },+ ],+ },+ ],+ });++ expect(r.status).toBe(200);+ expect(upstream.bodies).toHaveLength(2);+ const retried = JSON.parse(upstream.bodies[1]);+ // 孤儿块被丢,合法配对保留。+ expect(retried.messages[2].content).toEqual([+ { type: 'tool_result', tool_use_id: 'Bash_1', content: 'ok' },+ ]);+ });++ it('returns the 400 as-is when the history has nothing to repair', async () => {+ const upstream = await startFakeUpstream((_idx, _body, res) => {+ res.writeHead(400, { 'content-type': 'application/json' });+ res.end(DUPLICATE_TOOL_USE_ID_ERROR_BODY);+ });+ upstreamClose = upstream.close;+ proxy = await createAnthropicCompatProxy({+ upstream: upstream.url,+ transformRequest: [],+ recoveryRules: [createDuplicateToolUseIdRecoveryRule({ enabled: () => true })],+ });++ const r = await post(proxy.url, {+ model: 'moonshot/kimi-k3',+ messages: [{ role: 'user', content: 'hi' }],+ });++ // strip 无东西可改 → 不重试,400 原样回客户端(不误伤)。+ expect(r.status).toBe(400);+ expect(upstream.bodies).toHaveLength(1);+ });++ it('repairs a multiply-polluted history in one proactive pass (host chain order)', async () => {+ // host 装配顺序的组合场景: 同一请求同时含重复 id + 错位 result + 缺失 result,+ // repair → dedupe 链式应用后一次修好,只发一次(不等 400)。+ const upstream = await startFakeUpstream((_idx, _body, res) => {+ res.writeHead(200, { 'content-type': 'application/json' });+ res.end(JSON.stringify({ ok: true }));+ });+ upstreamClose = upstream.close;+ proxy = await createAnthropicCompatProxy({+ upstream: upstream.url,+ transformRequest: [repairToolExchangeAdjacency, dedupeDuplicateToolUseIds], // host 同序: repair 先于 dedupe+ recoveryRules: [],+ });++ const r = await post(proxy.url, {+ model: 'moonshot/kimi-k3',+ messages: [+ { role: 'user', content: 'go' },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'Edit_306', name: 'Edit', input: { a: 1 } }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'Edit_306', content: 'ok' }] },+ // 第二对: 同 id(重复)且 result 错位(隔了一条 user text)。+ { role: 'assistant', content: [{ type: 'tool_use', id: 'Edit_306', name: 'Edit', input: { a: 2 } }] },+ { role: 'user', content: [{ type: 'text', text: 'intervening' }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'Edit_306', content: 'late' }] },+ // 第三个 call: 同 id 且从此无 result(缺失,后面有 assistant 推进 → 非 trailing)。+ { role: 'assistant', content: [{ type: 'tool_use', id: 'Edit_306', name: 'Edit', input: { a: 3 } }] },+ { role: 'assistant', content: [{ type: 'text', text: '我以为发出去了' }] },+ ],+ });++ expect(r.status).toBe(200);+ expect(upstream.bodies).toHaveLength(1);+ const sent = JSON.parse(upstream.bodies[0]);+ // dedupe: 三个同 id call → Edit_306 / Edit_306_2 / Edit_306_3。+ const callIds = sent.messages+ .filter((m: { role: string }) => m.role === 'assistant')+ .flatMap((m: { content: Array<{ id?: string }> }) => m.content)+ .filter((b: { id?: string }) => b.id !== undefined)+ .map((b: { id?: string }) => b.id);+ expect(callIds).toEqual(['Edit_306', 'Edit_306_2', 'Edit_306_3']);+ // repair: 错位的 result(已改名 Edit_306_2)前移到第二对 call 紧邻的 user 消息开头;+ // 第三个 call 合成占位(Edit_306_3),新建 user 消息插入在两个 assistant 之间。+ const roles = sent.messages.map((m: { role: string }) => m.role);+ expect(roles).toEqual(['user', 'assistant', 'user', 'assistant', 'user', 'assistant', 'user', 'assistant']);+ expect(sent.messages[4].content[0]).toMatchObject({ type: 'tool_result', tool_use_id: 'Edit_306_2', content: 'late' });+ expect(sent.messages[6].content[0]).toMatchObject({ type: 'tool_result', tool_use_id: 'Edit_306_3' });+ // 每个 tool_use 都有紧邻的配对 result —— 修复后的历史对 strict 上游合法。+ });+});+describe('anthropic-compat-proxy empty-assistant-message recovery (moonshot/kimi)', () => {it('drops the empty assistant message and retries once on the moonshot 400', async () => {const upstream = await startFakeUpstream((idx, _body, res) => {diff --git a/packages/anthropic-compat-proxy/src/transform.test.ts b/packages/anthropic-compat-proxy/src/transform.test.tsindex 27b6698ac8..0625c02998 100644--- a/packages/anthropic-compat-proxy/src/transform.test.ts+++ b/packages/anthropic-compat-proxy/src/transform.test.ts@@ -3,12 +3,19 @@ import { describe, expect, it } from 'vitest';import { createThreadStripController } from './thread-strip-controller.js';import {createActiveStripTransform,+ createDuplicateToolUseIdRecoveryRule,createEmptyAssistantMessageRecoveryRule,createEmptyTextRecoveryRule,createEmptyThinkingRecoveryRule,createEncryptedContentRecoveryRule,createImageGenerationIdRecoveryRule,+ createToolExchangeAdjacencyRecoveryRule,createToolUseProviderSpecificFieldsRecoveryRule,+ dedupeDuplicateToolUseIds,+ dedupeDuplicateToolUseIdsFromBody,+ repairToolExchangeAdjacency,+ repairToolExchangeAdjacencyFromBody,+ repairToolExchangeStructureFromBody,stripEmptyAssistantMessagesFromBody,stripEmptyTextFromBody,stripEmptyThinkingFromBody,@@ -926,3 +933,830 @@ describe('stripNonAnthropicFields · glm-5.2 tool_result 图像降级 (#794)', (expect(stripNonAnthropicFields(body, ctx)).toBeNull();});});++// ───────────────────────────────────────────────────────────────────────────+// Tool exchange 结构修复(kimi/moonshot 序号 id 复用 + 配对断裂)+// 背景: 2026-07 两个独立会话实测,moonshot 序号 id 跨 turn 复用(Edit_306 /+// Bash_256 各 20+ 次)致会话安静瘫痪;修复方案与 kimi code 官方客户端+// (kosong normalize + agent-core projector)同构。+// ───────────────────────────────────────────────────────────────────────────++describe('dedupeDuplicateToolUseIdsFromBody', () => {+ it('rewrites the 2nd occurrence of a duplicated id and its paired result', () => {+ // 线上事故形态: 同 id 的完整配对历史重复出现。+ const body = buf({+ model: 'moonshot/kimi-k3',+ messages: [+ { role: 'user', content: 'fix it' },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'Edit_306', name: 'Edit', input: { a: 1 } }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'Edit_306', content: 'ok' }] },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'Edit_306', name: 'Edit', input: { a: 2 } }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'Edit_306', content: 'not found' }] },+ ],+ });+ const out = dedupeDuplicateToolUseIdsFromBody(body);+ expect(out).not.toBeNull();+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages[1].content[0].id).toBe('Edit_306');+ expect(parsed.messages[2].content[0].tool_use_id).toBe('Edit_306');+ expect(parsed.messages[3].content[0].id).toBe('Edit_306_2');+ expect(parsed.messages[4].content[0].tool_use_id).toBe('Edit_306_2');+ // 业务数据(input / result content)原样保留。+ expect(parsed.messages[3].content[0].input).toEqual({ a: 2 });+ expect(parsed.messages[4].content[0].content).toBe('not found');+ });++ it('numbers the 3rd+ occurrences sequentially', () => {+ const mk = (input: unknown) => ({+ role: 'assistant',+ content: [{ type: 'tool_use', id: 'Bash_256', name: 'Bash', input }],+ });+ const mkRes = (content: string) => ({+ role: 'user',+ content: [{ type: 'tool_result', tool_use_id: 'Bash_256', content }],+ });+ const body = buf({+ messages: [+ { role: 'user', content: 'go' },+ mk({ c: 1 }), mkRes('r1'), mk({ c: 2 }), mkRes('r2'), mk({ c: 3 }), mkRes('r3'),+ ],+ });+ const out = dedupeDuplicateToolUseIdsFromBody(body);+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages[1].content[0].id).toBe('Bash_256');+ expect(parsed.messages[3].content[0].id).toBe('Bash_256_2');+ expect(parsed.messages[5].content[0].id).toBe('Bash_256_3');+ expect(parsed.messages[6].content[0].tool_use_id).toBe('Bash_256_3');+ });++ it('skips a suffix candidate that collides with a pre-existing distinct id', () => {+ // 历史里已有一个独立的 Edit_306_2(不同 call) → Edit_306 的第 2 次出现顺延到 _3。+ const body = buf({+ messages: [+ { role: 'user', content: 'go' },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'Edit_306', name: 'Edit', input: {} }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'Edit_306', content: 'r1' }] },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'Edit_306_2', name: 'Edit', input: {} }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'Edit_306_2', content: 'r2' }] },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'Edit_306', name: 'Edit', input: {} }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'Edit_306', content: 'r3' }] },+ ],+ });+ const out = dedupeDuplicateToolUseIdsFromBody(body);+ const parsed = JSON.parse(out!.toString('utf8'));+ // 独立的 Edit_306_2 不动;重复的 Edit_306 第 2 次顺延到 _3,配对 result 同步。+ expect(parsed.messages[3].content[0].id).toBe('Edit_306_2');+ expect(parsed.messages[5].content[0].id).toBe('Edit_306_3');+ expect(parsed.messages[6].content[0].tool_use_id).toBe('Edit_306_3');+ });++ it('dedupes parallel duplicate calls inside a single assistant message', () => {+ // 同一条 assistant 消息内两个同 id tool_use(parallel 形态)+ 同一条 user 内两个 result。+ const body = buf({+ messages: [+ { role: 'user', content: 'go' },+ {+ role: 'assistant',+ content: [+ { type: 'tool_use', id: 'Read_305', name: 'Read', input: { f: 'a' } },+ { type: 'tool_use', id: 'Read_305', name: 'Read', input: { f: 'b' } },+ ],+ },+ {+ role: 'user',+ content: [+ { type: 'tool_result', tool_use_id: 'Read_305', content: 'a-content' },+ { type: 'tool_result', tool_use_id: 'Read_305', content: 'b-content' },+ ],+ },+ ],+ });+ const out = dedupeDuplicateToolUseIdsFromBody(body);+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages[1].content.map((b: { id: string }) => b.id)).toEqual(['Read_305', 'Read_305_2']);+ expect(parsed.messages[2].content.map((b: { tool_use_id: string }) => b.tool_use_id)).toEqual(['Read_305', 'Read_305_2']);+ // 顺序配对: 第二个 result(b-content)跟随第二个 call。+ expect(parsed.messages[2].content[1].content).toBe('b-content');+ });++ it('leaves a result without a matching Nth call untouched', () => {+ // 2 个 call、3 个 result: 第 3 个 result 无第 3 个 call 可配,保持原样(指向首现+ // call,协议合法;孤儿清理由 repairToolExchangeAdjacency 负责)。+ const body = buf({+ messages: [+ { role: 'user', content: 'go' },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'X_1', name: 'X', input: {} }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'X_1', content: 'r1' }] },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'X_1', name: 'X', input: {} }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'X_1', content: 'r2' }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'X_1', content: 'r3-stray' }] },+ ],+ });+ const out = dedupeDuplicateToolUseIdsFromBody(body);+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages[3].content[0].id).toBe('X_1_2');+ expect(parsed.messages[4].content[0].tool_use_id).toBe('X_1_2');+ expect(parsed.messages[5].content[0].tool_use_id).toBe('X_1');+ });++ it('returns null when every id is unique (cache-safe no-op)', () => {+ const body = buf({+ model: 'moonshot/kimi-k3',+ messages: [+ { role: 'user', content: 'go' },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'Edit_1', name: 'Edit', input: {} }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'Edit_1', content: 'ok' }] },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'Edit_2', name: 'Edit', input: {} }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'Edit_2', content: 'ok' }] },+ ],+ });+ expect(dedupeDuplicateToolUseIdsFromBody(body)).toBeNull();+ });++ it('returns null for non-JSON body / missing messages', () => {+ expect(dedupeDuplicateToolUseIdsFromBody(Buffer.from('not json', 'utf8'))).toBeNull();+ expect(dedupeDuplicateToolUseIdsFromBody(buf({ model: 'x' }))).toBeNull();+ });++ it('tolerates string content and id-less blocks without crashing', () => {+ const body = buf({+ messages: [+ { role: 'user', content: 'plain string' },+ { role: 'assistant', content: 'plain assistant string' },+ { role: 'assistant', content: [{ type: 'tool_use', name: 'Edit', input: {} }] }, // 缺 id+ { role: 'user', content: [{ type: 'tool_result', content: 'no id' }] }, // 缺 tool_use_id+ ],+ });+ expect(dedupeDuplicateToolUseIdsFromBody(body)).toBeNull();+ });+});++describe('dedupeDuplicateToolUseIds (RequestTransform)', () => {+ it('rewrites via the object form and does not mutate the input', () => {+ const original: { model: string; messages: Array<{ role: string; content: Array<Record<string, unknown>> }> } = {+ model: 'moonshot/kimi-k3',+ messages: [+ { role: 'assistant', content: [{ type: 'tool_use', id: 'E_1', name: 'E', input: {} }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'E_1', content: 'r1' }] },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'E_1', name: 'E', input: {} }] },+ ],+ };+ const out = dedupeDuplicateToolUseIds(original, ctx) as typeof original | null;+ expect(out).not.toBeNull();+ expect(out!.messages[2].content[0].id).toBe('E_1_2');+ // 输入对象未被原地改写。+ expect(original.messages[2].content[0].id).toBe('E_1');+ });++ it('returns null for a clean body', () => {+ expect(+ dedupeDuplicateToolUseIds(+ { messages: [{ role: 'assistant', content: [{ type: 'tool_use', id: 'E_1', name: 'E', input: {} }] }] },+ ctx,+ ),+ ).toBeNull();+ });+});++describe('repairToolExchangeAdjacencyFromBody', () => {+ it('returns null for a well-formed paired history (cache-safe no-op)', () => {+ const body = buf({+ messages: [+ { role: 'user', content: 'go' },+ { role: 'assistant', content: [{ type: 'tool_use', id: 't1', name: 'Bash', input: {} }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 't1', content: 'ok' }] },+ { role: 'assistant', content: [{ type: 'text', text: 'done' }] },+ ],+ });+ expect(repairToolExchangeAdjacencyFromBody(body)).toBeNull();+ });++ it('drops an orphan result block but keeps the sibling text', () => {+ const body = buf({+ messages: [+ { role: 'user', content: 'go' },+ { role: 'assistant', content: [{ type: 'tool_use', id: 't1', name: 'Bash', input: {} }] },+ {+ role: 'user',+ content: [+ { type: 'tool_result', tool_use_id: 't1', content: 'ok' },+ { type: 'tool_result', tool_use_id: 'orphan_999', content: 'stray' },+ { type: 'text', text: 'note' },+ ],+ },+ ],+ });+ const out = repairToolExchangeAdjacencyFromBody(body);+ expect(out).not.toBeNull();+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages).toHaveLength(3);+ expect(parsed.messages[2].content).toEqual([+ { type: 'tool_result', tool_use_id: 't1', content: 'ok' },+ { type: 'text', text: 'note' },+ ]);+ });++ it('drops a user message left empty by orphan removal and closes the stranded call', () => {+ // 孤儿块是唯一内容 → 整条 user 丢弃;stranded call(t1)后面有 assistant 推进+ // → 非 trailing,合成占位封闭(新建 user 消息紧邻插入)。+ const body = buf({+ messages: [+ { role: 'user', content: 'go' },+ { role: 'assistant', content: [{ type: 'tool_use', id: 't1', name: 'Bash', input: {} }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'orphan_9', content: 'stray' }] },+ { role: 'assistant', content: [{ type: 'text', text: 'done' }] },+ ],+ });+ const out = repairToolExchangeAdjacencyFromBody(body);+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages.map((m: { role: string }) => m.role)).toEqual([+ 'user', 'assistant', 'user', 'assistant',+ ]);+ expect(parsed.messages[2].content).toEqual([+ {+ type: 'tool_result',+ tool_use_id: 't1',+ content: 'Tool result is not available in the current context. Do not assume the tool completed successfully.',+ },+ ]);+ });++ it('prepends a synthetic result into the immediately following user message', () => {+ const body = buf({+ messages: [+ { role: 'user', content: 'go' },+ { role: 'assistant', content: [{ type: 'tool_use', id: 't1', name: 'Bash', input: {} }] },+ { role: 'user', content: [{ type: 'text', text: '还有问题' }] },+ ],+ });+ const out = repairToolExchangeAdjacencyFromBody(body);+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages).toHaveLength(3);+ // result 块在 text 前(Anthropic 惯例)。+ expect(parsed.messages[2].content.map((b: { type: string }) => b.type)).toEqual(['tool_result', 'text']);+ expect(parsed.messages[2].content[0].tool_use_id).toBe('t1');+ });++ it('converts a string-content user message to an array when prepending', () => {+ const body = buf({+ messages: [+ { role: 'user', content: 'go' },+ { role: 'assistant', content: [{ type: 'tool_use', id: 't1', name: 'Bash', input: {} }] },+ { role: 'user', content: 'next question' },+ ],+ });+ const out = repairToolExchangeAdjacencyFromBody(body);+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages).toHaveLength(3);+ expect(parsed.messages[2].content).toEqual([+ {+ type: 'tool_result',+ tool_use_id: 't1',+ content: 'Tool result is not available in the current context. Do not assume the tool completed successfully.',+ },+ { type: 'text', text: 'next question' },+ ]);+ });++ it('closes multiple missing calls of one assistant message in order', () => {+ const body = buf({+ messages: [+ { role: 'user', content: 'go' },+ {+ role: 'assistant',+ content: [+ { type: 'tool_use', id: 't1', name: 'Bash', input: {} },+ { type: 'tool_use', id: 't2', name: 'Read', input: {} },+ ],+ },+ { role: 'user', content: [{ type: 'text', text: 'next' }] },+ ],+ });+ const out = repairToolExchangeAdjacencyFromBody(body);+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages[2].content.map((b: { tool_use_id?: string }) => b.tool_use_id)).toEqual(['t1', 't2', undefined]);+ });++ it('leaves a trailing open exchange untouched (call may still be in flight)', () => {+ const body = buf({+ messages: [+ { role: 'user', content: 'go' },+ { role: 'assistant', content: [{ type: 'tool_use', id: 't1', name: 'Bash', input: {} }] },+ ],+ });+ expect(repairToolExchangeAdjacencyFromBody(body)).toBeNull();+ });++ it('treats a pure tool_result tail as part of the trailing exchange', () => {+ // user(result t1) 是纯 result 消息,不算对话推进点;同 assistant 的 t2 未配对+ // 但之后没有推进点 → trailing,不动。+ const body = buf({+ messages: [+ { role: 'user', content: 'go' },+ {+ role: 'assistant',+ content: [+ { type: 'tool_use', id: 't1', name: 'Bash', input: {} },+ { type: 'tool_use', id: 't2', name: 'Read', input: {} },+ ],+ },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 't1', content: 'ok' }] },+ ],+ });+ expect(repairToolExchangeAdjacencyFromBody(body)).toBeNull();+ });++ it('closes a mid-history stranded call even when a later assistant exists', () => {+ // user, A(callX 未配对), B(text): B 证明模型已 move on → 非 trailing,封闭。+ const body = buf({+ messages: [+ { role: 'user', content: 'go' },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'X', name: 'Bash', input: {} }] },+ { role: 'assistant', content: [{ type: 'text', text: '我以为发出去了' }] },+ ],+ });+ const out = repairToolExchangeAdjacencyFromBody(body);+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages.map((m: { role: string }) => m.role)).toEqual(['user', 'assistant', 'user', 'assistant']);+ expect(parsed.messages[2].content[0].tool_use_id).toBe('X');+ });++ it('moves a displaced result back next to its call (kimi consumed-scan)', () => {+ // review 反例: result 存在但与 call 之间隔了一条 user(text) —— 全局配对视角+ // "有应答",但 Anthropic strict adjacency 仍非法 → 必须前移重排。+ const body = buf({+ messages: [+ { role: 'user', content: 'go' },+ { role: 'assistant', content: [{ type: 'tool_use', id: 't1', name: 'Bash', input: {} }] },+ { role: 'user', content: [{ type: 'text', text: 'intervening' }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 't1', content: 'late result' }] },+ ],+ });+ const out = repairToolExchangeAdjacencyFromBody(body);+ expect(out).not.toBeNull();+ const parsed = JSON.parse(out!.toString('utf8'));+ // result 前移到 call 紧邻的 user 消息开头;原位置 user 消息清空 → 整条丢。+ expect(parsed.messages).toHaveLength(3);+ expect(parsed.messages[2].content).toEqual([+ { type: 'tool_result', tool_use_id: 't1', content: 'late result' },+ { type: 'text', text: 'intervening' },+ ]);+ });++ it('reorders a result that sits after a text block in the adjacent user message', () => {+ // 块级错位(review 反例): result 在紧邻 user 消息里,但排在 text 之后 ——+ // 消息级"已邻接",块级仍非法 → 移进前导 tool_result 区间。+ const body = buf({+ messages: [+ { role: 'user', content: 'go' },+ { role: 'assistant', content: [{ type: 'tool_use', id: 't1', name: 'Bash', input: {} }] },+ {+ role: 'user',+ content: [+ { type: 'text', text: 'note first' },+ { type: 'tool_result', tool_use_id: 't1', content: 'r1' },+ ],+ },+ ],+ });+ const out = repairToolExchangeAdjacencyFromBody(body);+ expect(out).not.toBeNull();+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages[2].content).toEqual([+ { type: 'tool_result', tool_use_id: 't1', content: 'r1' },+ { type: 'text', text: 'note first' },+ ]);+ });++ it('keeps leading results in place and reorders only the trailing one (parallel calls)', () => {+ // 多 call: t1 已在前导区间(不动),t2 落在 text 后 → 只重排 t2,+ // 插到前导区间末尾(保持与 call 顺序一致)。+ const body = buf({+ messages: [+ { role: 'user', content: 'go' },+ {+ role: 'assistant',+ content: [+ { type: 'tool_use', id: 't1', name: 'Bash', input: {} },+ { type: 'tool_use', id: 't2', name: 'Read', input: {} },+ ],+ },+ {+ role: 'user',+ content: [+ { type: 'tool_result', tool_use_id: 't1', content: 'r1' },+ { type: 'text', text: 'middle' },+ { type: 'tool_result', tool_use_id: 't2', content: 'r2' },+ ],+ },+ ],+ });+ const out = repairToolExchangeAdjacencyFromBody(body);+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages[2].content).toEqual([+ { type: 'tool_result', tool_use_id: 't1', content: 'r1' },+ { type: 'tool_result', tool_use_id: 't2', content: 'r2' },+ { type: 'text', text: 'middle' },+ ]);+ });++ it('drops a surplus result for the same call id (one call, one answer)', () => {+ // 同 id 第二个 result: 不是孤儿(callIds 里有),但一个 call 恰应有一个应答 →+ // 接力消费后池中剩余,丢弃(与 kimi duplicate_tool_result_dropped 同语义)。+ const body = buf({+ messages: [+ { role: 'user', content: 'go' },+ { role: 'assistant', content: [{ type: 'tool_use', id: 't1', name: 'Bash', input: {} }] },+ {+ role: 'user',+ content: [+ { type: 'tool_result', tool_use_id: 't1', content: 'first' },+ { type: 'tool_result', tool_use_id: 't1', content: 'surplus' },+ ],+ },+ { role: 'assistant', content: [{ type: 'text', text: 'done' }] },+ ],+ });+ const out = repairToolExchangeAdjacencyFromBody(body);+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages[2].content).toEqual([+ { type: 'tool_result', tool_use_id: 't1', content: 'first' },+ ]);+ });++ it('drops a result that precedes its call and closes the call with a placeholder', () => {+ // result 出现在 call 之前 = 引用未来 call,上游必然 400;接力消费只取 call+ // 之后的 result,前置块留在池中 → 丢弃,call 按缺失合成。+ const body = buf({+ messages: [+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 't1', content: 'too early' }] },+ { role: 'assistant', content: [{ type: 'tool_use', id: 't1', name: 'Bash', input: {} }] },+ { role: 'user', content: 'next' },+ ],+ });+ const out = repairToolExchangeAdjacencyFromBody(body);+ const parsed = JSON.parse(out!.toString('utf8'));+ // 前置 result 所在 user 消息清空 → 整条丢;call 后紧邻 user 并入合成占位。+ expect(parsed.messages.map((m: { role: string }) => m.role)).toEqual(['assistant', 'user']);+ expect(parsed.messages[1].content[0]).toEqual({+ type: 'tool_result',+ tool_use_id: 't1',+ content: 'Tool result is not available in the current context. Do not assume the tool completed successfully.',+ });+ });++ it('keeps trailing-exchange results: fully paired trailing calls stay byte-clean', () => {+ // trailing assistant 的 parallel calls + 尾部纯 result 消息 = 正常末尾交换,+ // 接力消费后池空、无插入 → null(尾部 result 不得误判为残留)。+ const body = buf({+ messages: [+ { role: 'user', content: 'go' },+ {+ role: 'assistant',+ content: [+ { type: 'tool_use', id: 't1', name: 'Bash', input: {} },+ { type: 'tool_use', id: 't2', name: 'Read', input: {} },+ ],+ },+ {+ role: 'user',+ content: [+ { type: 'tool_result', tool_use_id: 't1', content: 'r1' },+ { type: 'tool_result', tool_use_id: 't2', content: 'r2' },+ ],+ },+ ],+ });+ expect(repairToolExchangeAdjacencyFromBody(body)).toBeNull();+ });++ it('does not append a text block when prepending into a whitespace-only string user', () => {+ // 空白 string content 转数组时不附加 text 块 —— 否则新造空 text 块,+ // 转头命中 "text content blocks must be non-empty" 400。+ const body = buf({+ messages: [+ { role: 'user', content: 'go' },+ { role: 'assistant', content: [{ type: 'tool_use', id: 't1', name: 'Bash', input: {} }] },+ { role: 'user', content: ' ' },+ { role: 'assistant', content: [{ type: 'text', text: 'done' }] },+ ],+ });+ const out = repairToolExchangeAdjacencyFromBody(body);+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages[2].content).toEqual([+ {+ type: 'tool_result',+ tool_use_id: 't1',+ content: 'Tool result is not available in the current context. Do not assume the tool completed successfully.',+ },+ ]);+ });++ it('does not steal a later call\'s real result for an earlier same-id gap (Greptile P1)', () => {+ // Greptile P1 反例: 较早的同 id call 缺 result、较晚 call 有真实结果。+ // 位置配对必须优先 —— r2 只能配给 call#2;call#1 合成占位,不得张冠李戴。+ const body = buf({+ messages: [+ { role: 'assistant', content: [{ type: 'tool_use', id: 'X', name: 'Edit', input: { a: 1 } }] },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'X', name: 'Edit', input: { a: 2 } }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'X', content: 'r2-real' }] },+ { role: 'user', content: '继续' },+ ],+ });+ const out = repairToolExchangeAdjacencyFromBody(body);+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages.map((m: { role: string }) => m.role)).toEqual([+ 'assistant', 'user', 'assistant', 'user', 'user',+ ]);+ // call#1 得到合成占位;call#2 保留真实结果 r2。+ expect(parsed.messages[1].content[0]).toMatchObject({+ type: 'tool_result',+ tool_use_id: 'X',+ content: 'Tool result is not available in the current context. Do not assume the tool completed successfully.',+ });+ expect(parsed.messages[3].content[0]).toMatchObject({ tool_use_id: 'X', content: 'r2-real' });+ });++ it('positional pairing wins over relay even when the later call is trailing', () => {+ // 变体: 较晚 call 是 trailing(末尾交换)。它紧邻位置的真实 result 仍归它+ // (trailing 参与位置配对),较早缺口 call 合成,池不被越权消费。+ const body = buf({+ messages: [+ { role: 'user', content: 'go' },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'X', name: 'Edit', input: { a: 1 } }] },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'X', name: 'Edit', input: { a: 2 } }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'X', content: 'r2-real' }] },+ ],+ });+ const out = repairToolExchangeAdjacencyFromBody(body);+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages.map((m: { role: string }) => m.role)).toEqual([+ 'user', 'assistant', 'user', 'assistant', 'user',+ ]);+ expect(parsed.messages[2].content[0].content).toContain('Tool result is not available');+ expect(parsed.messages[4].content[0]).toMatchObject({ tool_use_id: 'X', content: 'r2-real' });+ });++ it('relay stays inside the owning interval: a later call\'s displaced result is not stolen', () => {+ // Greptile 第二轮反例: 两个同 id call 都无紧邻 result(位置配对均失败),+ // call#2 的真实 result 错位在更后 —— 接力按归属区间(到下一个同 id call+ // 为止)取块:r2 归 call#2 前移,call#1 合成,不再先到先得。+ const body = buf({+ messages: [+ { role: 'user', content: 'go' },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'X', name: 'Edit', input: { a: 1 } }] },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'X', name: 'Edit', input: { a: 2 } }] },+ { role: 'user', content: [{ type: 'text', text: '之间' }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'X', content: 'r2-real' }] },+ { role: 'user', content: '继续' },+ ],+ });+ const out = repairToolExchangeAdjacencyFromBody(body);+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages.map((m: { role: string }) => m.role)).toEqual([+ 'user', 'assistant', 'user', 'assistant', 'user', 'user',+ ]);+ // call#1 → 新建 user 合成占位;call#2 → r2 前移到其紧邻 user(之间)的前导区间。+ expect(parsed.messages[2].content[0].content).toContain('Tool result is not available');+ expect(parsed.messages[4].content).toEqual([+ { type: 'tool_result', tool_use_id: 'X', content: 'r2-real' },+ { type: 'text', text: '之间' },+ ]);+ });++ it('keeps trailing parallel results arriving in separate messages (no kill)', () => {+ // trailing parallel calls 的 result 分多条纯 result 消息回来 = 合法末尾+ // 交换。t2 位置配对失败(i+1 里只有 t1),trailing 接力只消费保护不修复,+ // 不得被"池剩余丢弃"误杀 → 整体 byte-clean 返回 null。+ const body = buf({+ messages: [+ { role: 'user', content: 'go' },+ {+ role: 'assistant',+ content: [+ { type: 'tool_use', id: 't1', name: 'Bash', input: {} },+ { type: 'tool_use', id: 't2', name: 'Read', input: {} },+ ],+ },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 't1', content: 'r1' }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 't2', content: 'r2' }] },+ ],+ });+ expect(repairToolExchangeAdjacencyFromBody(body)).toBeNull();+ });++ it('same-message parallel same-id calls pair a stray result in call order', () => {+ // 同一条 assistant 消息内的 parallel 同 id calls 同批发出,其中一个+ // result 丢失时归属在原理上不可判定(两种归属的世界序列化后字节相同)。+ // 这里锁定的是**稳定 tie-breaker 契约**:区间内涵 call 块顺序配序+ // (受典型 client serializer 支持:SDK Tool Runner Promise.all 的结果数组+ // 保持输入序)—— 是可复现的默认约定,不是"证明 stray 属于 call#1"。+ // (归属区间按 exchange 粒度计算,同消息 calls 共享区间。)+ const body = buf({+ messages: [+ { role: 'user', content: 'go' },+ {+ role: 'assistant',+ content: [+ { type: 'tool_use', id: 'X', name: 'Edit', input: { a: 1 } },+ { type: 'tool_use', id: 'X', name: 'Edit', input: { a: 2 } },+ ],+ },+ { role: 'user', content: [{ type: 'text', text: '之间' }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'X', content: 'stray' }] },+ { role: 'user', content: '继续' },+ ],+ });+ const out = repairToolExchangeAdjacencyFromBody(body);+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages.map((m: { role: string }) => m.role)).toEqual([+ 'user', 'assistant', 'user', 'user',+ ]);+ // stray 前移到紧邻 user(之间)前导区间(配 call#1),call#2 合成紧随其后。+ expect(parsed.messages[2].content).toEqual([+ { type: 'tool_result', tool_use_id: 'X', content: 'stray' },+ {+ type: 'tool_result',+ tool_use_id: 'X',+ content: 'Tool result is not available in the current context. Do not assume the tool completed successfully.',+ },+ { type: 'text', text: '之间' },+ ]);+ });++ it('two displaced same-id results keep pool order onto call order (stable serializer contract)', () => {+ // 契约测试: 同消息 parallel 同 id calls 均无紧邻 result,池中两个错位+ // result 按位置顺序 zip 到 call 顺序(r1→call#1、r2→call#2)—— 锁定+ // stable tie-breaker 在多元件下的可复现性。+ const body = buf({+ messages: [+ { role: 'user', content: 'go' },+ {+ role: 'assistant',+ content: [+ { type: 'tool_use', id: 'X', name: 'Edit', input: { a: 1 } },+ { type: 'tool_use', id: 'X', name: 'Edit', input: { a: 2 } },+ ],+ },+ { role: 'user', content: [{ type: 'text', text: '之间' }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'X', content: 'r1' }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'X', content: 'r2' }] },+ { role: 'user', content: '继续' },+ ],+ });+ const out = repairToolExchangeAdjacencyFromBody(body);+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages.map((m: { role: string }) => m.role)).toEqual([+ 'user', 'assistant', 'user', 'user',+ ]);+ expect(parsed.messages[2].content).toEqual([+ { type: 'tool_result', tool_use_id: 'X', content: 'r1' },+ { type: 'tool_result', tool_use_id: 'X', content: 'r2' },+ { type: 'text', text: '之间' },+ ]);+ });++ it('returns null for non-JSON body / missing messages', () => {+ expect(repairToolExchangeAdjacencyFromBody(Buffer.from('not json', 'utf8'))).toBeNull();+ expect(repairToolExchangeAdjacencyFromBody(buf({ model: 'x' }))).toBeNull();+ });+});++describe('repairToolExchangeAdjacency (RequestTransform)', () => {+ it('repairs via the object form and does not mutate the input', () => {+ const original = {+ messages: [+ { role: 'user', content: 'go' },+ { role: 'assistant', content: [{ type: 'tool_use', id: 't1', name: 'Bash', input: {} }] },+ { role: 'user', content: [{ type: 'text', text: 'next' }] },+ ],+ };+ const out = repairToolExchangeAdjacency(original, ctx) as typeof original | null;+ expect(out).not.toBeNull();+ expect((out!.messages[2].content as unknown[]).length).toBe(2);+ // 输入未被原地改写。+ expect((original.messages[2].content as unknown[]).length).toBe(1);+ });+});++describe('duplicate tool_use id / tool exchange adjacency recovery rules', () => {+ it('duplicate id rule: matches the anthropic error, strips dupes, ignores others', () => {+ const rule = createDuplicateToolUseIdRecoveryRule();+ expect(rule.id).toBe('duplicate_tool_use_id');+ expect(rule.enabled()).toBe(true);+ expect(rule.matches('messages: `tool_use` ids must be unique')).toBe(true);+ expect(rule.matches('{"error":{"message":"messages.5: `tool_use` ids must be unique"}}')).toBe(true);+ expect(rule.matches('some other 400')).toBe(false);+ // 无重复可修 → strip null(该规则让位)。+ expect(rule.strip(buf({ messages: [{ role: 'user', content: 'hi' }] }))).toBeNull();+ });++ it('adjacency rule: matches moonshot / anthropic phrasings, not a plain 404', () => {+ const rule = createToolExchangeAdjacencyRecoveryRule();+ expect(rule.id).toBe('tool_exchange_adjacency');+ expect(rule.enabled()).toBe(true);+ // Moonshot chatcmpl 校验透出(原文双空格)。+ expect(rule.matches('Invalid request: tool_call_id is not found')).toBe(true);+ // Anthropic 孤儿 result。+ expect(rule.matches("messages.0.content.0: unexpected `tool_use_id` found in `tool_result` blocks")).toBe(true);+ // Anthropic 未配对 call。+ expect(rule.matches('messages.3: `tool_use` ids were found without `tool_result` blocks immediately after: toolu_01ABC')).toBe(true);+ // OpenAI 系(LiteLLM 版本差异可能透出): 孤儿 tool 消息 / 未配对 call。+ expect(rule.matches("messages with role 'tool' must be a response to a preceding message with 'tool_calls'")).toBe(true);+ expect(rule.matches('the following tool_call_ids did not have response messages: call_1')).toBe(true);+ expect(rule.matches('unexpected `tool_result` block')).toBe(true);+ // 404 类 not found 不命中(锚定 tool_call_id)。+ expect(rule.matches('404 model not found')).toBe(false);+ });+});++describe('repair → dedupe 链式顺序(host 主动链同序)', () => {+ it('同消息 parallel 同 id + 一个错位 result:真实 R→X、合成→X_2(端到端契约)', () => {+ // 端到端契约: repair 先把 stray 配给 call#1(稳定 tie-breaker)、call#2+ // 合成,dedupe 再把 call#2 改名 X_2、第 2 个 result(合成块)同步改名。+ const body = {+ model: 'moonshot/kimi-k3',+ messages: [+ { role: 'user', content: 'go' },+ {+ role: 'assistant',+ content: [+ { type: 'tool_use', id: 'X', name: 'Edit', input: { a: 1 } },+ { type: 'tool_use', id: 'X', name: 'Edit', input: { a: 2 } },+ ],+ },+ { role: 'user', content: [{ type: 'text', text: '之间' }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'X', content: 'stray' }] },+ { role: 'user', content: '继续' },+ ],+ };+ const afterRepair = repairToolExchangeAdjacency(body, ctx) as typeof body | null;+ expect(afterRepair).not.toBeNull();+ const afterBoth = dedupeDuplicateToolUseIds(afterRepair!, ctx) as typeof body | null;+ expect(afterBoth).not.toBeNull();+ const messages = afterBoth!.messages as Array<{ role: string; content: Array<Record<string, unknown>> }>;+ expect(messages.map((m) => m.role)).toEqual(['user', 'assistant', 'user', 'user']);+ const calls = messages[1].content;+ expect(calls[0].id).toBe('X');+ expect(calls[1].id).toBe('X_2');+ // 真实 stray 配 call#1(保持 X);合成块配 call#2(同步改名 X_2)。+ expect(messages[2].content[0]).toMatchObject({ tool_use_id: 'X', content: 'stray' });+ expect(messages[2].content[1]).toMatchObject({ tool_use_id: 'X_2' });+ expect(String(messages[2].content[1].content)).toContain('Tool result is not available');+ });++ it('前置 same-id result 不污染 dedupe 的配对序号(复审反例)', () => {+ // 复审反例: dedupe 先跑时,'early' 白占 result 序号 1,本属 call#1 的 r1+ // 被改名给 call#2,repair 按改名后 id 配对 → 张冠李戴。repair 先跑则+ // 前置块先被丢弃,result 与 call 严格同序,dedupe 配对正确。+ const body = {+ model: 'moonshot/kimi-k3',+ messages: [+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'X', content: 'early' }] },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'X', name: 'Edit', input: { a: 1 } }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'X', content: 'r1' }] },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'X', name: 'Edit', input: { a: 2 } }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'X', content: 'r2' }] },+ { role: 'assistant', content: [{ type: 'text', text: 'done' }] },+ ],+ };+ const afterRepair = repairToolExchangeAdjacency(body, ctx) as typeof body | null;+ expect(afterRepair).not.toBeNull();+ const afterBoth = dedupeDuplicateToolUseIds(afterRepair!, ctx) as typeof body | null;+ expect(afterBoth).not.toBeNull();+ const messages = afterBoth!.messages as Array<{ role: string; content: Array<Record<string, unknown>> }>;+ // 前置 'early' 所在 user 整条丢;call#1 → X(配 r1),call#2 → X_2(配 r2)。+ expect(messages.map((m) => m.role)).toEqual(['assistant', 'user', 'assistant', 'user', 'assistant']);+ expect(messages[0].content[0].id).toBe('X');+ expect(messages[1].content[0]).toMatchObject({ tool_use_id: 'X', content: 'r1' });+ expect(messages[2].content[0].id).toBe('X_2');+ expect(messages[3].content[0]).toMatchObject({ tool_use_id: 'X_2', content: 'r2' });+ });++ it('组合 strip(recovery 共用)同序修复且不改写干净 body', () => { // 同一 body 经组合函数: 前置丢弃 + 合成/重排 + 唯一化一次完成。+ const polluted = buf({+ messages: [+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'X', content: 'early' }] },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'X', name: 'Edit', input: { a: 1 } }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'X', content: 'r1' }] },+ { role: 'assistant', content: [{ type: 'tool_use', id: 'X', name: 'Edit', input: { a: 2 } }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'X', content: 'r2' }] },+ ],+ });+ const out = repairToolExchangeStructureFromBody(polluted);+ expect(out).not.toBeNull();+ const parsed = JSON.parse(out!.toString('utf8'));+ expect(parsed.messages.map((m: { role: string }) => m.role)).toEqual(['assistant', 'user', 'assistant', 'user']);+ expect(parsed.messages[1].content[0]).toMatchObject({ tool_use_id: 'X', content: 'r1' });+ expect(parsed.messages[3].content[0]).toMatchObject({ tool_use_id: 'X_2', content: 'r2' });+ // 干净 body → null(两步都无改动)。+ const clean = buf({+ messages: [+ { role: 'user', content: 'hi' },+ { role: 'assistant', content: [{ type: 'tool_use', id: 't1', name: 'Bash', input: {} }] },+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 't1', content: 'ok' }] },+ ],+ });+ expect(repairToolExchangeStructureFromBody(clean)).toBeNull();+ });+});diff --git a/packages/anthropic-compat-proxy/src/transform.ts b/packages/anthropic-compat-proxy/src/transform.tsindex 4642bd2fff..9e3ffb51f2 100644--- a/packages/anthropic-compat-proxy/src/transform.ts+++ b/packages/anthropic-compat-proxy/src/transform.ts@@ -520,6 +520,511 @@ export function stripEmptyAssistantMessagesFromBody(rawBody: Buffer): Buffer | n}}+// ───────────────────────────────────────────────────────────────────────────+// 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 / 翻译 / 改值。@@ -713,6 +1218,29 @@ const IMAGE_GENERATION_WITHOUT_ID_RE =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 设置,默认关)。@@ -829,3 +1357,46 @@ export function createEmptyAssistantMessageRecoveryRule(opts: {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,+ };+}