Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix: KIMI(kimi-k3) Claude Code 下空消息腐蚀——转录归一化+响应流撞车改名自愈 (#1327)

yan1dc37098cade
diff --git a/packages/anthropic-compat-proxy/src/index.ts b/packages/anthropic-compat-proxy/src/index.ts
index 925535d9ad..0ecc7855f8 100644
--- a/packages/anthropic-compat-proxy/src/index.ts
+++ b/packages/anthropic-compat-proxy/src/index.ts
@@ -59,6 +59,11 @@ export {
} from './transform.js';
export { createThreadStripController } from './thread-strip-controller.js';
export type { ThreadStripController } from './thread-strip-controller.js';
+export {
+ collectToolUseIdsForResponseRewrite,
+ ToolUseIdDedupeRewriter,
+ ToolUseIdRewriteTransform,
+} from './tool-use-id-stream-rewrite.js';
export type {
InstructionsInjectionTransformOptions,
InstructionsRegistry,
diff --git a/packages/anthropic-compat-proxy/src/server.test.ts b/packages/anthropic-compat-proxy/src/server.test.ts
index 0c9e7b4c0e..1fea4f5e62 100644
--- a/packages/anthropic-compat-proxy/src/server.test.ts
+++ b/packages/anthropic-compat-proxy/src/server.test.ts
@@ -2133,3 +2133,333 @@ describe('anthropic-compat-proxy 入站请求体 dump 开关(debugDumpRequestBod
expect(inbound?.ctx).not.toHaveProperty('body');
});
});
+
+describe('tool_use id 响应流去重改写(kimi 撞车自愈)', () => {
+ const SSE_BODY =
+ 'event: message_start\n' +
+ 'data: {"type":"message_start","message":{"id":"chatcmpl-x","role":"assistant","content":[]}}\n\n' +
+ 'event: content_block_start\n' +
+ 'data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":"想"}}\n\n' +
+ 'event: content_block_start\n' +
+ 'data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"Bash_210","name":"Bash","input":{}}}\n\n' +
+ 'event: content_block_start\n' +
+ 'data: {"type":"content_block_start","index":2,"content_block":{"type":"tool_use","id":"Bash_999","name":"Bash","input":{}}}\n\n' +
+ 'event: message_stop\n' +
+ 'data: {"type":"message_stop"}\n\n';
+
+ function sseUpstream() {
+ return startFakeUpstream((_i, _b, res) => {
+ res.writeHead(200, { 'content-type': 'text/event-stream' });
+ res.end(SSE_BODY);
+ });
+ }
+
+ it('请求历史带铸造形态 id 时, 响应里撞车的 tool_use id 被改名, 新 id 不动', async () => {
+ const upstream = await sseUpstream();
+ upstreamClose = upstream.close;
+ const infos: Array<{ msg: string; ctx?: Record<string, unknown> }> = [];
+ proxy = await createAnthropicCompatProxy({
+ upstream: upstream.url,
+ transformRequest: [],
+ logger: { info: (msg, ctx) => infos.push({ msg, ctx }) },
+ });
+
+ const res = await post(proxy.url, {
+ model: 'kimi-k3',
+ messages: [
+ { role: 'user', content: '分析' },
+ { role: 'assistant', content: [{ type: 'tool_use', id: 'Bash_210', name: 'Bash', input: {} }] },
+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'Bash_210', content: 'ok' }] },
+ ],
+ });
+ expect(res.status).toBe(200);
+ // 撞车 id 被改名; 新 id(Bash_999)与历史无关 → 不动
+ expect(res.text).toContain('"id":"Bash_210_dup2"');
+ expect(res.text).toContain('"id":"Bash_999"');
+ expect(res.text).not.toContain('"id":"Bash_210"');
+ // thinking / 事件框架行原样
+ expect(res.text).toContain('event: message_stop');
+ expect(
+ infos.some(
+ (l) => l.msg.includes('renamed duplicate tool_use id') && l.ctx?.from === 'Bash_210' && l.ctx?.to === 'Bash_210_dup2',
+ ),
+ ).toBe(true);
+ });
+
+ it('请求历史无铸造形态 id 时, 响应流字节透传(零干预)', async () => {
+ const upstream = await sseUpstream();
+ upstreamClose = upstream.close;
+ proxy = await createAnthropicCompatProxy({
+ upstream: upstream.url,
+ transformRequest: [],
+ });
+
+ const res = await post(proxy.url, {
+ model: 'claude-sonnet-4',
+ messages: [
+ { role: 'user', content: '分析' },
+ { role: 'assistant', content: [{ type: 'tool_use', id: 'toolu_01Jx4AbC', name: 'Bash', input: {} }] },
+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'toolu_01Jx4AbC', content: 'ok' }] },
+ ],
+ });
+ expect(res.status).toBe(200);
+ expect(res.text).toBe(SSE_BODY);
+ });
+
+ it('非 SSE 响应不接管(字节透传)', async () => {
+ const upstream = await startFakeUpstream((_i, _b, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(
+ JSON.stringify({
+ id: 'chatcmpl-x',
+ content: [{ type: 'tool_use', id: 'Bash_210', name: 'Bash', input: {} }],
+ }),
+ );
+ });
+ upstreamClose = upstream.close;
+ proxy = await createAnthropicCompatProxy({
+ upstream: upstream.url,
+ transformRequest: [],
+ });
+
+ const res = await post(proxy.url, {
+ model: 'kimi-k3',
+ messages: [
+ { role: 'assistant', content: [{ type: 'tool_use', id: 'Bash_210', name: 'Bash', input: {} }] },
+ ],
+ });
+ expect(res.status).toBe(200);
+ expect(res.text).toContain('"id":"Bash_210"');
+ });
+
+ it('SSE 改写长度变化时自动剥离 content-length,客户端不截断(GPT-5.5 第 5 轮 P1)', async () => {
+ const upstream = await startFakeUpstream((_i, _b, res) => {
+ const sseBody =
+ 'event: content_block_start\n' +
+ 'data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"Bash_210","name":"Bash","input":{}}}\n\n' +
+ 'event: message_stop\n' +
+ 'data: {"type":"message_stop"}\n\n';
+ // upstream 发出定长 content-length(改写后 body 会变得更长)
+ res.writeHead(200, {
+ 'content-type': 'text/event-stream',
+ 'content-length': String(Buffer.byteLength(sseBody)),
+ });
+ res.end(sseBody);
+ });
+ upstreamClose = upstream.close;
+ proxy = await createAnthropicCompatProxy({
+ upstream: upstream.url,
+ transformRequest: [],
+ });
+
+ const res = await post(proxy.url, {
+ model: 'kimi-k3',
+ messages: [
+ { role: 'assistant', content: [{ type: 'tool_use', id: 'Bash_210', name: 'Bash', input: {} }] },
+ ],
+ });
+ expect(res.status).toBe(200);
+ // 改写后 id 被改名,且完整的 SSE 帧无截断(message_stop 存在)
+ expect(res.text).toContain('"id":"Bash_210_dup2"');
+ expect(res.text).toContain('"type":"message_stop"');
+ });
+});
+
+describe('压缩 SSE 不接管(Greptile review)', () => {
+ it('content-encoding 存在时保持字节透传,不改名、不删 content-length', async () => {
+ const { gzipSync } = await import('node:zlib');
+ const upstream = await startFakeUpstream((_i, _b, res) => {
+ const sseBody =
+ 'event: content_block_start\n' +
+ 'data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"Bash_210","name":"Bash","input":{}}}\n\n';
+ // 真实 gzip 压缩的 SSE:改写器不得接管(压缩字节按明文行切分会漏改/误改)
+ const gzipped = gzipSync(Buffer.from(sseBody, 'utf8'));
+ res.writeHead(200, {
+ 'content-type': 'text/event-stream',
+ 'content-encoding': 'gzip',
+ 'content-length': String(gzipped.length),
+ });
+ res.end(gzipped);
+ });
+ upstreamClose = upstream.close;
+ proxy = await createAnthropicCompatProxy({
+ upstream: upstream.url,
+ transformRequest: [],
+ });
+
+ const res = await post(proxy.url, {
+ model: 'kimi-k3',
+ messages: [
+ { role: 'assistant', content: [{ type: 'tool_use', id: 'Bash_210', name: 'Bash', input: {} }] },
+ ],
+ });
+ expect(res.status).toBe(200);
+ // 字节透传:客户端自解压后内容完整、id 不改名(未进入改写器)
+ expect(res.text).toContain('"id":"Bash_210"');
+ expect(res.text).not.toContain('Bash_210_dup2');
+ });
+
+ it('content-encoding: identity(明文,不压缩)仍接管改写(Greptile P1)', async () => {
+ const upstream = await startFakeUpstream((_i, _b, res) => {
+ const sseBody =
+ 'event: content_block_start\n' +
+ 'data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"Bash_210","name":"Bash","input":{}}}\n\n';
+ res.writeHead(200, {
+ 'content-type': 'text/event-stream',
+ 'content-encoding': 'identity',
+ 'content-length': String(Buffer.byteLength(sseBody)),
+ });
+ res.end(sseBody);
+ });
+ upstreamClose = upstream.close;
+ proxy = await createAnthropicCompatProxy({
+ upstream: upstream.url,
+ transformRequest: [],
+ });
+
+ const res = await post(proxy.url, {
+ model: 'kimi-k3',
+ messages: [
+ { role: 'assistant', content: [{ type: 'tool_use', id: 'Bash_210', name: 'Bash', input: {} }] },
+ ],
+ });
+ expect(res.status).toBe(200);
+ // identity 是明文:必须接管并改名(改写后长度变化,content-length 被剥离)
+ expect(res.text).toContain('"id":"Bash_210_dup2"');
+ });
+});
+
+describe('per-thread 已见 id 缓存(codex-connector P1:请求体缺席历史 id 时仍拦截重铸)', () => {
+ const MINTED_SSE =
+ 'event: content_block_start\n' +
+ 'data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"Bash_210","name":"Bash","input":{}}}\n\n';
+
+ function mintingUpstream() {
+ return startFakeUpstream((_i, _b, res) => {
+ res.writeHead(200, { 'content-type': 'text/event-stream' });
+ res.end(MINTED_SSE);
+ });
+ }
+
+ // per-thread 缓存需要**同一 proxy 实例**跨请求累积(每个请求独立建 proxy 会丢缓存),
+ // 因此 postAs 复用同一个 upstream + proxy。
+ async function setupSingleProxy(): Promise<void> {
+ const upstream = await mintingUpstream();
+ upstreamClose = upstream.close;
+ proxy = await createAnthropicCompatProxy({ upstream: upstream.url, transformRequest: [] });
+ }
+
+ async function postAs(sessionId: string, body: unknown): Promise<string> {
+ const res = await fetch(`${proxy!.url}/v1/responses`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', 'x-claude-code-session-id': sessionId },
+ body: JSON.stringify(body),
+ });
+ return res.text();
+ }
+
+ it('全新 kimi 会话(无 minted id 历史)仍接管并记录首个 streamed id(codex-connector P1)', async () => {
+ await setupSingleProxy();
+ // 全新 kimi 会话: 请求体无任何铸造形态 id → requestedIds null, cache 空;
+ // 修复前 responseToolUseIds 也 null → 不接管 → 首 fresh id 未记录。
+ // 修复后: 请求体 model=kimi 判定接管, onObserved 记录 Bash_210。
+ const r1 = await postAs('sess-fresh', {
+ model: 'moonshot/kimi-k3',
+ messages: [{ role: 'user', content: '你好' }],
+ });
+ expect(r1).toContain('"id":"Bash_210"'); // fresh id 透传(无撞车)
+
+ // 第二次请求(同 session, 无铸造 id 历史, 模拟 rewind): 缓存里已有 Bash_210
+ // → 响应铸 Bash_210 仍被拦截改名
+ const r2 = await postAs('sess-fresh', {
+ model: 'moonshot/kimi-k3',
+ messages: [{ role: 'user', content: '继续' }],
+ });
+ expect(r2).not.toContain('"id":"Bash_210"');
+ expect(r2).toMatch(/Bash_210_dup\d+/);
+ });
+
+ it('Kimi Code 的 k3 模型 id 同样判定为 kimi 会话(codex-connector P1)', async () => {
+ await setupSingleProxy();
+ // catalog 里 moonshot-kimi-code provider 的 claude-code runtime model id 是裸 `k3`
+ // (Kimi K3), 不带 kimi 前缀 —— 修复前 isKimiRequest 对 k3 返回 false → 不接管
+ const r1 = await postAs('sess-k3', {
+ model: 'k3',
+ messages: [{ role: 'user', content: '你好' }],
+ });
+ expect(r1).toContain('"id":"Bash_210"'); // fresh id 透传(无撞车)
+
+ // 第二次请求(同 session, 模拟 rewind): 缓存里已有 Bash_210 → 拦截改名
+ const r2 = await postAs('sess-k3', {
+ model: 'k3',
+ messages: [{ role: 'user', content: '继续' }],
+ });
+ expect(r2).not.toContain('"id":"Bash_210"');
+ expect(r2).toMatch(/Bash_210_dup\d+/);
+ });
+
+ it('请求1(历史含 Bash_210)改名;请求2(同 session,历史不含 Bash_210)仍拦截重铸', async () => {
+ await setupSingleProxy();
+ // 请求1: 历史带 Bash_210 → 响应铸 Bash_210 → 撞车 → 改名; Bash_210 进线程缓存
+ const r1 = await postAs('sess-1', {
+ model: 'kimi-k3',
+ messages: [
+ { role: 'assistant', content: [{ type: 'tool_use', id: 'Bash_210', name: 'Bash', input: {} }] },
+ ],
+ });
+ expect(r1).toContain('"id":"Bash_210_dup2"');
+
+ // 请求2: 同 session, 历史**不含** Bash_210(模拟 rewind 后历史缺席)
+ // → 若只从请求体建 usedIds, 该 id 会被当「新 id」放行; per-thread 缓存必须拦截
+ const r2 = await postAs('sess-1', {
+ model: 'kimi-k3',
+ messages: [{ role: 'user', content: '继续分析' }],
+ });
+ // 缓存让 r2 仍设防:响应铸 Bash_210 被改名(后缀可能顺延为 _dup3,因为 r1
+ // 的 onRename 已把 _dup2 写进缓存),绝不能原样放行 Bash_210
+ expect(r2).not.toContain('"id":"Bash_210"');
+ expect(r2).toMatch(/Bash_210_dup\d+/);
+ });
+
+ it('请求2 仍含部分铸造 id 时,缓存里缺席的旧 id 也并入种子(codex-connector P1)', async () => {
+ await setupSingleProxy();
+ // 请求1: 历史带 Bash_210 → 改名 → 进缓存
+ const r1 = await postAs('sess-partial', {
+ model: 'kimi-k3',
+ messages: [
+ { role: 'assistant', content: [{ type: 'tool_use', id: 'Bash_210', name: 'Bash', input: {} }] },
+ ],
+ });
+ expect(r1).toContain('"id":"Bash_210_dup2"');
+
+ // 请求2: 同 session, 请求体**仍含另一个**铸造 id(Read_5, 使 requestedIds 非空),
+ // 但 Bash_210 缺席 —— 若只从请求体建种子, Bash_210 会漏; 缓存必须并入。
+ // fake upstream 恒铸 Bash_210 → 必须仍被改名, 不得原样放行。
+ const r2 = await postAs('sess-partial', {
+ model: 'kimi-k3',
+ messages: [
+ { role: 'assistant', content: [{ type: 'tool_use', id: 'Read_5', name: 'Read', input: {} }] },
+ ],
+ });
+ expect(r2).not.toContain('"id":"Bash_210"');
+ expect(r2).toMatch(/Bash_210_dup\d+/);
+ });
+
+ it('不同 session 的缓存互不串扰', async () => {
+ await setupSingleProxy();
+ // 请求1 在 sess-A 铸 Bash_210(缓存入 sess-A)
+ await postAs('sess-A', {
+ model: 'kimi-k3',
+ messages: [
+ { role: 'assistant', content: [{ type: 'tool_use', id: 'Bash_210', name: 'Bash', input: {} }] },
+ ],
+ });
+ // 请求2 在 sess-B(全新会话, 无缓存)铸 Bash_210 → 请求体不带历史 id → 应放行
+ const r2 = await postAs('sess-B', {
+ model: 'kimi-k3',
+ messages: [{ role: 'user', content: '你好' }],
+ });
+ expect(r2).toContain('"id":"Bash_210"');
+ expect(r2).not.toContain('Bash_210_dup2');
+ });
+});
diff --git a/packages/anthropic-compat-proxy/src/server.ts b/packages/anthropic-compat-proxy/src/server.ts
index 4f39d16fc0..d91ef46583 100644
--- a/packages/anthropic-compat-proxy/src/server.ts
+++ b/packages/anthropic-compat-proxy/src/server.ts
@@ -34,6 +34,11 @@ import {
} from './outbound-proxy.js';
import { Socks5HttpAgent, Socks5HttpsAgent } from './socks5.js';
import { stripNonAnthropicFields, stripToolUseProviderSpecificFields } from './transform.js';
+import {
+ collectToolUseIdsForResponseRewrite,
+ ToolUseIdDedupeRewriter,
+ ToolUseIdRewriteTransform,
+} from './tool-use-id-stream-rewrite.js';
import type {
LocalRequestHandler,
ProxyHandle,
@@ -105,6 +110,44 @@ const DEBUG_REQUEST_DUMP_MAX_BYTES = 64 * 1024;
// (~几百字节),给 16KB 已经非常宽裕,超出按相同截断策略尾部追加 "... (truncated, total N bytes)"。
const ERROR_RESPONSE_DUMP_MAX_BYTES = 16 * 1024;
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+// per-thread 已见 id 缓存的有界上限(Copilot review 防内存 DoS;proxy 只绑
+// loopback 不暴露外部,属防御性上限)。
+const MAX_CACHED_THREADS = 1024;
+const MAX_IDS_PER_THREAD = 8192;
+
+/**
+ * 往 per-thread 已见 id 缓存写入一条(id 去重)。有界:线程数超限 FIFO 淘汰最老
+ * (re-insert 到 Map 末尾近似 LRU),单线程 id 超限丢最老(Set 按插入序)。
+ */
+function addThreadMintedId(
+ threadMintedIdCache: Map<string, Set<string>>,
+ threadIdKey: string,
+ id: string,
+): void {
+ let set = threadMintedIdCache.get(threadIdKey);
+ if (!set) {
+ threadMintedIdCache.delete(threadIdKey); // 已存在则触底(近似 LRU)
+ threadMintedIdCache.set(threadIdKey, new Set<string>());
+ set = threadMintedIdCache.get(threadIdKey);
+ while (threadMintedIdCache.size > MAX_CACHED_THREADS) {
+ const oldest = threadMintedIdCache.keys().next().value as string | undefined;
+ if (oldest === undefined) break;
+ threadMintedIdCache.delete(oldest);
+ }
+ }
+ if (set && !set.has(id)) {
+ set.add(id);
+ if (set.size > MAX_IDS_PER_THREAD) {
+ const oldestId = set.keys().next().value as string | undefined;
+ if (oldestId !== undefined) set.delete(oldestId);
+ }
+ }
+}
+
interface UpstreamTarget {
hostname: string;
port: number;
@@ -719,6 +762,15 @@ function forward(
outboundProxy?: ResolvedOutboundProxy,
// 精确推理路径覆盖;省略时沿用客户端原始 path。
pathOverride?: string,
+ // 请求历史里「铸造形态」的 tool_use id 集合(moonshot/kimi 的 ${name}_${index}
+ // id);非空时响应 SSE 流经过撞车改名,防 CLI 把重复 id 写进转录后被
+ // ensureToolResultPairing 整段丢弃(运行中会话的空消息腐蚀,见
+ // tool-use-id-stream-rewrite.ts 头注)。null/undefined → 响应字节透传。
+ responseToolUseIds?: Set<string> | null,
+ // per-thread 已见 id 缓存:改名产物(_dupN)落缓存,防「请求体缺席历史 id 但
+ // 同底再铸」的自激循环(codex-connector review P1)。由 createAnthropicCompatProxy
+ // 注入,forward 是模块级函数取不到闭包作用域。
+ threadMintedIdCache?: Map<string, Set<string>> | null,
): void {
// 客户端已断开(典型:400 缓冲期间断开后走到透明重试)——'close' 已经发过,
// 下面挂的中断传播 listener 永远不会触发,直接不发起上游请求。
@@ -967,6 +1019,8 @@ function forward(
clientModel,
outboundProxy,
pathOverride,
+ responseToolUseIds,
+ threadMintedIdCache,
);
return;
}
@@ -1101,6 +1155,65 @@ function forward(
};
failActiveResponse = (err) => failStreamingResponse('error', err);
+ // kimi 撞车 id 的响应流改名(仅当请求历史带铸造形态 id 且响应是 SSE 才接管;
+ // 否则保持字节级 pipe,与扩展前一致)。observer 仍吃上游原始字节(计数/错误体
+ // 收集语义不变),CLI 客户端拿到的是改名后的流。
+ // 必须在 writeHead 前判定:改名会改变 body 长度,上游 content-length 必须删掉,
+ // 否则客户端按旧值读取 → 截断(GPT-5.5 review 第 5 轮 P1,本地 fake upstream
+ // 复现确认)。
+ // 压缩 SSE(gzip/br)不接管:改写器按明文换行切行,压缩字节会漏改甚至误改;
+ // 压缩流下保持字节透传(不删 content-length,客户端自行解压),与扩展前一致
+ // (Greptile review)。identity 是合法的「不压缩」编码,不视为压缩(Greptile
+ // review P1,否则明文 SSE 被误跳过改写)。
+ const isSse = String(upstreamRes.headers['content-type'] ?? '')
+ .toLowerCase()
+ .startsWith('text/event-stream');
+ const contentEncoding = String(upstreamRes.headers['content-encoding'] ?? '')
+ .trim()
+ .toLowerCase();
+ const isCompressed = contentEncoding !== '' && contentEncoding !== 'identity';
+ let toolUseIdRewrite: ToolUseIdRewriteTransform | null = null;
+ if (responseToolUseIds && isSse && !isCompressed) {
+ // 压缩 SSE(gzip/br)不改写: 字节按明文换行切分会漏改/误改, 保持透传
+ // (Greptile 指出此路径撞车 id 不设防; 但 LLM 流式响应不 gzip, 实测链路
+ // 均明文 SSE, 属理论场景)。为压缩流做解压-改写-重压收益趋零、风险高,
+ // 不做; 压缩透传的撞车 id 不会污染明文转录, 下一轮明文请求仍由缓存拦截)。
+ delete respHeaders['content-length'];
+ // 响应流改写涉及线程缓存读(onObserved 写 / sharedSeen 读),二者必须用同一
+ // thread id,否则并发流 A 写入的 id 流 B 读不到,共享缓存检查形同虚设。
+ const streamThreadId = selectedHeaderValue(headers, STABLE_THREAD_ID_HEADERS) ?? '';
+ const rewriter = new ToolUseIdDedupeRewriter(
+ responseToolUseIds,
+ (from, to) => {
+ logger.info?.('⇄ renamed duplicate tool_use id in response stream (kimi mint collision)', {
+ reqId,
+ from,
+ to,
+ });
+ },
+ // 每个 streamed id(含 fresh 非碰撞路径)都进线程缓存:rewind/中断让下一
+ // 请求体不含该 id 时,缓存仍能拦截重铸。只记录 rename 产物会漏掉
+ // fresh id 首次出现即被 rewind 的场景(codex-connector review:
+ // Persist every streamed tool ID in the thread cache)。
+ (observed) => {
+ if (streamThreadId && threadMintedIdCache) {
+ addThreadMintedId(threadMintedIdCache, streamThreadId, observed);
+ }
+ },
+ // 共享缓存实时检查:同一 thread 的并发响应流(如同步 subagent)各自持有本
+ // rewriter, 都从请求开始快照构建 —— 若快照都空, 流 A 放行并缓存 Bash_210
+ // 后, 流 B 仍当 fresh 放行, CLI 追加重复 id 重新引入腐蚀。resolve 时实时查
+ // 线程缓存: 别处已见 → 按碰撞改名(codex-connector P1: Check the live cache
+ // before accepting fresh IDs)。JS 单线程事件循环保证同 tick 内 check-then-
+ // add 原子; 跨 tick 的并发流由共享缓存拦截。
+ (id) => (streamThreadId && threadMintedIdCache
+ ? (threadMintedIdCache.get(streamThreadId)?.has(id) ?? false)
+ : false),
+ );
+ toolUseIdRewrite = new ToolUseIdRewriteTransform(rewriter);
+ toolUseIdRewrite.on('error', (err) => failStreamingResponse('error', err));
+ }
+
clientRes.writeHead(status, upstreamRes.statusMessage, respHeaders);
// 收 body: 总字节始终累加;status >= 400 时额外收集前 ERROR_RESPONSE_DUMP_MAX_BYTES
@@ -1168,7 +1281,15 @@ function forward(
failStreamingResponse('close');
});
- upstreamRes.pipe(clientRes); // ← 字节级 pipe,SSE 零延迟的命脉('data' 只是计数+错误体收集, 不影响流)
+ if (toolUseIdRewrite) {
+ // 客户端断开 / 上游故障收口时把 transform 一并拆掉,避免上游继续灌进无消费者的流。
+ const rewriteStream = toolUseIdRewrite;
+ clientRes.on('close', () => rewriteStream.destroy());
+ upstreamRes.pipe(toolUseIdRewrite);
+ toolUseIdRewrite.pipe(clientRes);
+ } else {
+ upstreamRes.pipe(clientRes); // ← 字节级 pipe,SSE 零延迟的命脉('data' 只是计数+错误体收集, 不影响流)
+ }
});
upstreamReq.on('error', (err) => {
@@ -1361,6 +1482,7 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Pr
const url = req.url ?? '/';
const headers = flattenRequestHeaders(req.headers);
const requestCtx: RequestTransformCtx = { reqId, method, url, headers };
+ const threadId = selectedHeaderValue(headers, STABLE_THREAD_ID_HEADERS) ?? '';
const contentType = headers['content-type'] ?? '';
// 非 POST / 没 body(GET / HEAD / DELETE 等)→ 不收集 stream,但仍跑一次路由决策:
@@ -1524,6 +1646,58 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Pr
const transformed = runTransforms(rawBody, contentType, transforms, transformCtx, logger);
const outBody = transformed ?? rawBody;
+ let parsedForRewrite: unknown = rawParsed;
+ if (parsedForRewrite === undefined && contentType.toLowerCase().startsWith('application/json')) {
+ try {
+ parsedForRewrite = JSON.parse(rawBody.toString('utf8'));
+ } catch {
+ parsedForRewrite = undefined;
+ }
+ }
+ const requestedIds = collectToolUseIdsForResponseRewrite(parsedForRewrite);
+ // 全新/刚归一化的 kimi 会话,请求体可能还没有任何铸造形态 id(历史缺席),
+ // 但模型仍会铸 minted id —— 用请求体 model 判定 kimi,确保首 fresh id 也
+ // 被接管记录(codex-connector review: Cache first streamed Kimi tool IDs)。
+ // 覆盖 moonshot-kimi-code provider 的 `k3` 模型 id(Kimi K3,catalog 里
+ // claude-code runtime 的 model id 就是裸 `k3`,不带 kimi 前缀;codex-connector
+ // review: Treat Kimi Code k3 as a Kimi stream)。
+ const isKimiRequest =
+ isRecord(parsedForRewrite) && typeof parsedForRewrite.model === 'string'
+ ? /(^|[\/_-])(kimi|k3)([\/_-]|$)/i.test(parsedForRewrite.model)
+ : false;
+
+ // per-thread 已见 id 缓存(跨请求并入 usedIds):rewind / 中断 / CLI 压缩会让
+ // 历史撞车 id 缺席于某个请求体,若只从请求体建 usedIds,该 id 重铸时 proxy
+ // 认作「新 id」放行,转录出现重复 → 下轮 ensureToolResultPairing 丢弃 → 请求
+ // 体更缺 → 自激循环(codex-connector review P1)。缓存让本线程内见过的 minted
+ // 形态 id 持续设防。副作用:rewind 后 kimi 本可安全复用的旧号被改名(无害,
+ // _dupN 后缀不影响语义)。
+ //
+ // 注意:缓存读取**不能**依赖 requestedIds 非空 —— rewind 后请求体恰恰
+ // 可能不含任何铸造 id(历史缺席),而缓存里留有上次见过的撞车 id,这正
+ // 是缓存存在的意义。请求体无铸造 id 但缓存非空时,用缓存建 usedIds 设防。
+ let responseToolUseIds: Set<string> | null = null;
+ if (threadId) {
+ const cache = threadMintedIdCache.get(threadId);
+ if (requestedIds) {
+ responseToolUseIds = requestedIds;
+ // 缓存里本线程见过但缺席当前请求体的撞车 id 也必须并入 —— rewind 后
+ // 请求体可能只含部分铸造 id,漏掉这些会让 kimi 重铸同号时被当新 id
+ // 放行(codex-connector review: Merge cached tool IDs into rewrite seeds)。
+ if (cache && cache.size > 0) {
+ for (const id of cache) responseToolUseIds.add(id);
+ }
+ for (const id of requestedIds) addThreadMintedId(threadMintedIdCache, threadId, id);
+ } else if (cache && cache.size > 0) {
+ responseToolUseIds = new Set(cache);
+ } else if (isKimiRequest) {
+ // 全新 kimi 会话:空种子集接管响应流,onObserved 记录首个 streamed id。
+ responseToolUseIds = new Set<string>();
+ }
+ } else {
+ responseToolUseIds = requestedIds;
+ }
+
if (transformed) {
logger.debug?.('⇄ transformed request body', {
reqId,
@@ -1552,6 +1726,8 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Pr
extractBodyModel(rawBody),
await resolveOutboundForTarget(route.target, reqId),
route.pathOverride,
+ responseToolUseIds,
+ threadMintedIdCache,
);
});
@@ -1559,6 +1735,10 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Pr
// 容量控制属于 Codex / 上游职责;proxy 自设上限会凭空制造本地 503,让 Cindy 的
// at-capacity 体验反而劣于同版本 Codex。刻意不并入 inflight —— WS 是长连接,
// 计入会让 dispose 的清零等待永不满足。
+ // per-thread 已见 tool_use id 缓存(跨请求),供响应流撞车改名的 usedIds 并入。
+ // 有界见 addThreadMintedId(Copilot review 防内存 DoS)。
+ const threadMintedIdCache = new Map<string, Set<string>>();
+
let liveWebSockets = 0;
interface LiveWebSocket {
readonly threadId: string;
diff --git a/packages/anthropic-compat-proxy/src/tool-use-id-stream-rewrite.test.ts b/packages/anthropic-compat-proxy/src/tool-use-id-stream-rewrite.test.ts
new file mode 100644
index 0000000000..6abb07c4c2
--- /dev/null
+++ b/packages/anthropic-compat-proxy/src/tool-use-id-stream-rewrite.test.ts
@@ -0,0 +1,332 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ collectToolUseIdsForResponseRewrite,
+ ToolUseIdDedupeRewriter,
+ ToolUseIdRewriteTransform,
+} from './tool-use-id-stream-rewrite.js';
+
+// ── collectToolUseIdsForResponseRewrite ─────────────────────────────────
+
+describe('collectToolUseIdsForResponseRewrite', () => {
+ it('历史含铸造形态 id 时返回**全量** tool_use id 集合(P1-A: 改名产物也在内)', () => {
+ const ids = collectToolUseIdsForResponseRewrite({
+ messages: [
+ {
+ role: 'assistant',
+ content: [
+ { type: 'tool_use', id: 'Bash_210' },
+ { type: 'tool_use', id: 'Bash_210_dup2' }, // 上一轮改名产物
+ { type: 'tool_use', id: 'toolu_01Jx4AbC' }, // 非铸造形态也收(防撞基准)
+ { type: 'text', text: 'x' },
+ ],
+ },
+ { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'Bash_210' }] },
+ { role: 'assistant', content: [{ type: 'tool_use', id: 'TaskCreate_35' }] },
+ ],
+ });
+ expect(ids).toEqual(new Set(['Bash_210', 'Bash_210_dup2', 'toolu_01Jx4AbC', 'TaskCreate_35']));
+ });
+
+ it('纯 Anthropic toolu_* / OpenAI call_<random> / 无 tool 调用 → null', () => {
+ expect(
+ collectToolUseIdsForResponseRewrite({
+ messages: [{ role: 'assistant', content: [{ type: 'tool_use', id: 'toolu_01Jx4AbC' }] }],
+ }),
+ ).toBeNull();
+ expect(
+ collectToolUseIdsForResponseRewrite({
+ messages: [
+ { role: 'assistant', content: [{ type: 'tool_use', id: 'call_5teL1yyaqGpp3UKFRv22MkQu' }] },
+ ],
+ }),
+ ).toBeNull();
+ expect(collectToolUseIdsForResponseRewrite({ messages: [{ role: 'user', content: '你好' }] })).toBeNull();
+ });
+
+ it('非 messages 请求 / 非对象 → null', () => {
+ expect(collectToolUseIdsForResponseRewrite(undefined)).toBeNull();
+ expect(collectToolUseIdsForResponseRewrite(null)).toBeNull();
+ expect(collectToolUseIdsForResponseRewrite('junk')).toBeNull();
+ expect(collectToolUseIdsForResponseRewrite({ model: 'kimi-k3' })).toBeNull();
+ });
+
+ it('归一化后的 _x 形态 id 不命中接管开关(与转录归一化幂等互补)', () => {
+ expect(
+ collectToolUseIdsForResponseRewrite({
+ messages: [{ role: 'assistant', content: [{ type: 'tool_use', id: 'Bash_x210' }] }],
+ }),
+ ).toBeNull();
+ });
+
+ it('MCP 下划线工具名的铸造 id 命中(P1-E)', () => {
+ const ids = collectToolUseIdsForResponseRewrite({
+ messages: [
+ {
+ role: 'assistant',
+ content: [{ type: 'tool_use', id: 'mcp__cindy_memory__call_tool_5' }],
+ },
+ ],
+ });
+ expect(ids).toEqual(new Set(['mcp__cindy_memory__call_tool_5']));
+ });
+
+ it('带连字符的 MCP 工具名 id 命中(codex-connector P1)', () => {
+ const ids = collectToolUseIdsForResponseRewrite({
+ messages: [
+ {
+ role: 'assistant',
+ content: [
+ {
+ type: 'tool_use',
+ id: 'mcp__feishu-delegate__feishu_read_messages_5',
+ name: 'mcp__feishu-delegate__feishu_read_messages',
+ },
+ ],
+ },
+ ],
+ });
+ expect(ids).toEqual(new Set(['mcp__feishu-delegate__feishu_read_messages_5']));
+ });
+});
+
+// ── ToolUseIdDedupeRewriter.resolve ──────────────────────────────────────
+
+describe('ToolUseIdDedupeRewriter.resolve', () => {
+ it('新 id 原样通过; 撞历史的 id 改写为 _dup2, 再次撞车 _dup3', () => {
+ const renamed: Array<[string, string]> = [];
+ const rewriter = new ToolUseIdDedupeRewriter(new Set(['Bash_210']), (from, to) =>
+ renamed.push([from, to]),
+ );
+ expect(rewriter.resolve('Bash_219')).toBe('Bash_219'); // 新 id 不动
+ expect(rewriter.resolve('Bash_210')).toBe('Bash_210_dup2'); // 撞历史
+ expect(rewriter.resolve('Bash_210')).toBe('Bash_210_dup3'); // 再撞(含本响应已改名的)
+ expect(rewriter.renameCount).toBe(2);
+ expect(renamed).toEqual([
+ ['Bash_210', 'Bash_210_dup2'],
+ ['Bash_210', 'Bash_210_dup3'],
+ ]);
+ });
+
+ it('P1-A: 历史已含 _dup2(上一轮改名产物)时,同底 id 再撞顺延到 _dup3', () => {
+ // 事故主态:同一 id 被重铸多次。种子集合含 Bash_210_dup2 时,
+ // 新铸 Bash_210 必须给 _dup3,而不是再产出一个 _dup2 与历史撞车。
+ const rewriter = new ToolUseIdDedupeRewriter(new Set(['Bash_210', 'Bash_210_dup2']));
+ expect(rewriter.resolve('Bash_210')).toBe('Bash_210_dup3');
+ });
+
+ it('onObserved: 每个 resolve 的 id(含 fresh 非碰撞)都回调,线程缓存不漏 fresh id', () => {
+ // 场景:响应 stream 一个 fresh id(fresh_1, 非碰撞),然后 rewind/中断,
+ // 下一请求体不含它 —— 若缓存只记 rename 产物,重铸 fresh_1 就漏防。
+ const observed: string[] = [];
+ const rewriter = new ToolUseIdDedupeRewriter(
+ new Set(['Bash_210']),
+ undefined,
+ (id) => observed.push(id),
+ );
+ rewriter.resolve('fresh_1'); // 非碰撞 → 只走 onObserved
+ rewriter.resolve('Bash_210'); // 碰撞 → rename + onObserved
+ expect(observed).toEqual(['fresh_1', 'Bash_210_dup2']);
+ expect(rewriter.renameCount).toBe(1);
+ });
+
+ it('P1: sharedSeen 实时检查 —— 共享缓存(并发流)已见的 id 按碰撞改名, 不再放行', () => {
+ // 同一 thread 的两个并发响应流各持 rewriter, 都从空快照构建。流 A 放行 Bash_210
+ // 并写入共享缓存后, 流 B 的 rewriter(usedIds 仍空)resolve Bash_210 时, sharedSeen
+ // 返回 true → 必须改名, 否则 CLI 追加重复 id 重新引入 (no content) 腐蚀。
+ const sharedCache = new Set<string>();
+ const rewriterA = new ToolUseIdDedupeRewriter(new Set(), undefined, (id) => sharedCache.add(id));
+ const rewriterB = new ToolUseIdDedupeRewriter(
+ new Set(),
+ undefined,
+ (id) => sharedCache.add(id),
+ (id) => sharedCache.has(id),
+ );
+ // 流 A: fresh 放行, 写入共享缓存
+ expect(rewriterA.resolve('Bash_210')).toBe('Bash_210');
+ // 流 B: sharedSeen 命中 → 改名
+ expect(rewriterB.resolve('Bash_210')).toBe('Bash_210_dup2');
+ expect(rewriterB.renameCount).toBe(1);
+ // 流 B 再次看到 Bash_210(本流也缓存了) → 顺延 _dup3
+ expect(rewriterB.resolve('Bash_210')).toBe('Bash_210_dup3');
+ });
+
+ it('P1: sharedSeen 对改名产物同样设防 —— 并发流已占用的 _dupN 不重复产出', () => {
+ const sharedCache = new Set<string>();
+ const rewriterA = new ToolUseIdDedupeRewriter(new Set(), undefined, (id) => sharedCache.add(id));
+ const rewriterB = new ToolUseIdDedupeRewriter(
+ new Set(),
+ undefined,
+ (id) => sharedCache.add(id),
+ (id) => sharedCache.has(id),
+ );
+ // 流 A: Bash_210 已是历史 → _dup2, 共享缓存含 Bash_210_dup2
+ rewriterA.resolve('Bash_210'); // fresh 放行
+ rewriterA.resolve('Bash_210'); // 本流内撞车 → _dup2
+ // 流 B: Bash_210 也已是历史(sharedSeen) → 必须给 _dup3, 不能与流 A 的 _dup2 撞
+ expect(rewriterB.resolve('Bash_210')).toBe('Bash_210_dup3');
+ });
+});
+
+// ── ToolUseIdRewriteTransform(SSE 字节流) ────────────────────────────────
+
+function sseToolUseStart(id: string, name = 'Bash', index = 1): string {
+ return (
+ `event: content_block_start\n` +
+ `data: {"type":"content_block_start","index":${index},"content_block":{"type":"tool_use","id":"${id}","name":"${name}","input":{}}}\n\n`
+ );
+}
+
+async function runTransform(chunks: Buffer[], rewriter: ToolUseIdDedupeRewriter): Promise<Buffer> {
+ const transform = new ToolUseIdRewriteTransform(rewriter);
+ const out: Buffer[] = [];
+ transform.on('data', (c: Buffer) => out.push(c));
+ const done = new Promise<void>((resolve, reject) => {
+ transform.on('end', resolve);
+ transform.on('error', reject);
+ });
+ for (const chunk of chunks) transform.write(chunk);
+ transform.end();
+ await done;
+ return Buffer.concat(out);
+}
+
+describe('ToolUseIdRewriteTransform', () => {
+ const SSE_BODY =
+ 'event: message_start\n' +
+ 'data: {"type":"message_start","message":{"id":"chatcmpl-x","role":"assistant","content":[]}}\n\n' +
+ 'event: content_block_start\n' +
+ 'data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}\n\n' +
+ sseToolUseStart('Bash_210') +
+ sseToolUseStart('Bash_219', 'Bash', 2) +
+ 'event: content_block_delta\n' +
+ 'data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\\"command\\":\\"ls\\"}"}}\n\n' +
+ 'event: message_stop\n' +
+ 'data: {"type":"message_stop"}\n\n';
+
+ it('撞历史的 tool_use id 在流中被改名, 其余字节不动', async () => {
+ const rewriter = new ToolUseIdDedupeRewriter(new Set(['Bash_210']));
+ const out = await runTransform([Buffer.from(SSE_BODY, 'utf8')], rewriter);
+ const text = out.toString('utf8');
+ expect(text).toContain('"id":"Bash_210_dup2"'); // 撞车 → 改名
+ expect(text).toContain('"id":"Bash_219"'); // 新 id → 不动
+ expect(text).not.toContain('"id":"Bash_210"'); // 原始撞车 id 不再出现
+ expect(rewriter.renameCount).toBe(1);
+ });
+
+ it('P1-D: 上游 JSON 带空格风格(python json.dumps)同样命中', async () => {
+ // LiteLLM / Moonshot anthropic 端点若是 python 系,序列化是 {"type": "..."} 带空格;
+ // 逐字节前缀假设会整体静默失效,放宽后的匹配必须覆盖。
+ const body =
+ 'event: content_block_start\n' +
+ 'data: {"type": "content_block_start", "index": 1, "content_block": {"type": "tool_use", "id": "Bash_210", "name": "Bash", "input": {}}}\n\n';
+ const rewriter = new ToolUseIdDedupeRewriter(new Set(['Bash_210']));
+ const out = await runTransform([Buffer.from(body, 'utf8')], rewriter);
+ expect(out.toString('utf8')).toContain('"id":"Bash_210_dup2"');
+ });
+
+ it('P1-D: data: 后多个空格 / 键序变化也命中', async () => {
+ const body =
+ 'data: { "content_block": { "id": "Bash_210", "name": "Bash", "type": "tool_use", "input": {} }, "index": 1, "type": "content_block_start" }\n\n';
+ const rewriter = new ToolUseIdDedupeRewriter(new Set(['Bash_210']));
+ const out = await runTransform([Buffer.from(body, 'utf8')], rewriter);
+ expect(out.toString('utf8')).toContain('"id":"Bash_210_dup2"');
+ });
+
+ it('P1-D: pydantic 字段序(type 末尾)+ MCP 长工具名也命中(Fable-5 复现形态)', async () => {
+ // anthropic python SDK / pydantic model_dump 的字段序是 content_block, index, type 末尾;
+ // MCP 长名时 marker 落在 ~150 字节处,扫描窗口必须按此威胁面校准。
+ const mcpId = 'mcp__xd_atlassian__call_tool_210';
+ const body =
+ 'event: content_block_start\n' +
+ `data: {"content_block":{"id":"${mcpId}","name":"mcp__xd_atlassian__call_tool","type":"tool_use","input":{}},"index":1,"type":"content_block_start"}\n\n`;
+ const rewriter = new ToolUseIdDedupeRewriter(new Set([mcpId]));
+ const out = await runTransform([Buffer.from(body, 'utf8')], rewriter);
+ expect(out.toString('utf8')).toContain(`"id":"${mcpId}_dup2"`);
+ // json.dumps 带空格风格(marker 更靠后,~165)
+ const spaced =
+ 'event: content_block_start\n' +
+ `data: { "content_block": { "id": "${mcpId}", "name": "mcp__xd_atlassian__call_tool", "type": "tool_use", "input": {} }, "index": 1, "type": "content_block_start" }\n\n`;
+ const rewriter2 = new ToolUseIdDedupeRewriter(new Set([mcpId]));
+ const out2 = await runTransform([Buffer.from(spaced, 'utf8')], rewriter2);
+ expect(out2.toString('utf8')).toContain(`"id":"${mcpId}_dup2"`);
+ });
+
+ it('data 行跨 chunk 切割也能正确改写', async () => {
+ const rewriter = new ToolUseIdDedupeRewriter(new Set(['Bash_210']));
+ const bytes = Buffer.from(SSE_BODY, 'utf8');
+ // 以 7 字节碎片喂入,覆盖行被任意切开的场景
+ const chunks: Buffer[] = [];
+ for (let i = 0; i < bytes.length; i += 7) chunks.push(bytes.subarray(i, i + 7));
+ const out = await runTransform(chunks, rewriter);
+ const text = out.toString('utf8');
+ expect(text).toContain('"id":"Bash_210_dup2"');
+ expect(text).toContain('"id":"Bash_219"');
+ // 除改名行外,总内容等价(去掉改名差异后与原文一致)
+ expect(text.replace('Bash_210_dup2', 'Bash_210')).toBe(SSE_BODY);
+ });
+
+ it('无撞车时整流字节透传(与原流逐字节一致)', async () => {
+ const rewriter = new ToolUseIdDedupeRewriter(new Set(['Edit_999']));
+ const out = await runTransform([Buffer.from(SSE_BODY, 'utf8')], rewriter);
+ expect(out.toString('utf8')).toBe(SSE_BODY);
+ expect(rewriter.renameCount).toBe(0);
+ });
+
+ it('同一响应内重复出现的 id 也会被改名(并行调用同名工具)', async () => {
+ const body = sseToolUseStart('Bash_210') + sseToolUseStart('Bash_210', 'Bash', 2);
+ const rewriter = new ToolUseIdDedupeRewriter(new Set());
+ const out = await runTransform([Buffer.from(body, 'utf8')], rewriter);
+ const text = out.toString('utf8');
+ expect(text).toContain('"id":"Bash_210"');
+ expect(text).toContain('"id":"Bash_210_dup2"');
+ });
+
+ it('畸形 JSON 的 content_block_start 行 fail-open 原样通过', async () => {
+ const body = 'data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":BROKEN\n\n';
+ const rewriter = new ToolUseIdDedupeRewriter(new Set(['Bash_210']));
+ const out = await runTransform([Buffer.from(body, 'utf8')], rewriter);
+ expect(out.toString('utf8')).toBe(body);
+ });
+
+ it('\\r\\n 行尾保留', async () => {
+ const body =
+ 'event: content_block_start\r\n' +
+ 'data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"Bash_210","name":"Bash","input":{}}}\r\n\r\n';
+ const rewriter = new ToolUseIdDedupeRewriter(new Set(['Bash_210']));
+ const out = await runTransform([Buffer.from(body, 'utf8')], rewriter);
+ const text = out.toString('utf8');
+ expect(text).toContain('"id":"Bash_210_dup2"');
+ expect(text.endsWith('\r\n\r\n')).toBe(true);
+ });
+
+ it('末尾无换行的残行在 flush 时处理', async () => {
+ const body = 'data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"Bash_210","name":"Bash","input":{}}}';
+ const rewriter = new ToolUseIdDedupeRewriter(new Set(['Bash_210']));
+ const out = await runTransform([Buffer.from(body, 'utf8')], rewriter);
+ expect(out.toString('utf8')).toContain('"id":"Bash_210_dup2"');
+ });
+
+ it('病态超长无换行行:超上限直接透传,不拖垮内存', async () => {
+ const rewriter = new ToolUseIdDedupeRewriter(new Set(['Bash_210']));
+ const big = Buffer.alloc(5 * 1024 * 1024, 0x61); // 5MB 'a' 无 \n
+ const tail = Buffer.from('\ndata: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"Bash_210","name":"Bash","input":{}}}\n', 'utf8');
+ const out = await runTransform([big, tail], rewriter);
+ // 超长行原样透传(逐字节不变)
+ expect(out.subarray(0, big.length).equals(big)).toBe(true);
+ // 超长行透传后,后续正常行仍能改写(改名使尾部多 _dup2 的 5 字节)
+ expect(out.toString('utf8', big.length)).toContain('"id":"Bash_210_dup2"');
+ });
+
+ it('UTF-8 BOM 前缀的 data 行也能命中(GPT-5.5 review 第 2 轮 P2)', async () => {
+ const bom = Buffer.from([0xef, 0xbb, 0xbf]);
+ const body = Buffer.concat([
+ Buffer.from('data: ', 'utf8'),
+ bom,
+ Buffer.from('{"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"Bash_210","name":"Bash","input":{}}}\n', 'utf8'),
+ ]);
+ const rewriter = new ToolUseIdDedupeRewriter(new Set(['Bash_210']));
+ const out = await runTransform([body], rewriter);
+ expect(out.toString('utf8')).toContain('"id":"Bash_210_dup2"');
+ });
+});
diff --git a/packages/anthropic-compat-proxy/src/tool-use-id-stream-rewrite.ts b/packages/anthropic-compat-proxy/src/tool-use-id-stream-rewrite.ts
new file mode 100644
index 0000000000..46764931ef
--- /dev/null
+++ b/packages/anthropic-compat-proxy/src/tool-use-id-stream-rewrite.ts
@@ -0,0 +1,249 @@
+/**
+ * 响应流 tool_use id 去重改写 —— 让**运行中**的会话在 kimi 铸出撞车 id 时自愈,
+ * 不必重启 / 重开会话。
+ *
+ * 背景(2026-07-31 moonshot/kimi-k3「空消息」事故,全链路证据见
+ * maker-core/src/agents/claude-code/jsonl-tool-id-normalize.ts 头注):
+ * 1. kimi 模型按「当前上下文可见的 tool 调用数」生成递增序号的 tool_call id
+ * (原生形态 `functions.{name}:{idx}`,经 LiteLLM/Moonshot anthropic 端点
+ * 清洗为 `${ToolName}_${index}`);会话 rewind/中断导致可见数回落后,新铸
+ * id 与历史撞车 —— **不需要重启,会话运行中(如中途 rewind)同样会发生**。
+ * 2. CC CLI 的 ensureToolResultPairing 把重复 id 的 tool exchange 从后续请求
+ * 里整段丢弃,掏空的 user 消息以 "(no content)" 占位,模型上下文被腐蚀。
+ * 3. resume 前的转录归一化只能清理存量;已经运行中的 CLI 进程持有的内存态
+ * 历史不受影响,腐蚀会持续到进程结束。
+ *
+ * 本层在响应流到达 CLI 之前把撞车 id 改名(`${id}_dup${N}`,后缀语义与请求侧
+ * dedupeDuplicateToolUseIds / 转录归一化一致):CLI 记录进转录的历史**从不带
+ * 重复**,ensureToolResultPairing 无可丢之物,腐蚀无从发生。与转录归一化互补:
+ * 它治存量(下次 resume),本层防新发(当前进程立即生效)。
+ *
+ * 判定集合必须是**全量** tool_use id(不只铸造形态):改名产物 `_dupN` 也会进
+ * 转录,同一底 id 第二次撞车时,若集合里没有它,改写器会再次给出同一个
+ * `_dupN` 与历史撞车(Fable-5 review P1-A:事故数据里同一 id 被重铸 9×/27×,
+ * 多次撞车是主态而非角例)。「是否接管响应流」的开关才看铸造形态。
+ *
+ * 成本纪律(SSE 是延迟命脉,见 server.ts 头注):
+ * - 历史不含铸造形态 id 时(纯 Anthropic 会话 / 无 tool 调用)返回 null,
+ * 调用方完全不改管响应路径 —— 零成本;
+ * - 命中时按行扫 SSE,只对以 `data:` 开头且行首内含 `"content_block_start"`
+ * 的行做 JSON 解析(每响应寥寥数行),text delta 行只做一次字节级比较;
+ * - 行匹配不假设上游的 JSON 序列化风格(空格/键序):`data:` + 任意空白 +
+ * `{` 且前缀窗口内含标记子串即解析,结构校验(content_block.type)才是
+ * 真正的门(Fable-5 review P1-D:逐字节前缀假设在 Python json.dumps 风格
+ * 上游下会整体静默失效)。
+ *
+ * 只处理 Anthropic SSE;非流式 JSON 响应不改写(CC 主循环恒走流式,未实测到
+ * 非流式携带 tool_use 的上游,fail-open 与扩展前行为一致)。
+ */
+
+import { Transform, type TransformCallback } from 'node:stream';
+
+/**
+ * kimi 铸造器形态的 tool_call id:末段为纯数字(`Bash_210` / `TaskCreate_35` /
+ * `mcp__cindy_memory__call_tool_5` —— MCP 工具名带下划线,实测 MCP id 当前为
+ * `call_<random>` 无撞车风险,此处按威胁面放宽防御,Fable-5 review P1-E)。
+ */
+const MINTED_TOOL_USE_ID_RE = /^[A-Za-z][A-Za-z0-9_-]*_\d+$/;
+
+/** SSE data 行前缀。 */
+const SSE_DATA_PREFIX = 'data: ';
+/**
+ * `"content_block_start"` 的扫描窗口:扫描本身限界在行前 512 字节
+ * (Buffer.indexOf 原生实现,成本可忽略;text delta 行不付全行扫描)。
+ * 512 按威胁面取:content_block_start 行 = 事件头 + id + name + 空 input,
+ * pydantic/model_dump 字段序(content_block、index、type 末尾)+ MCP 最长
+ * 工具名(64 字符)+ json.dumps 空格风格合计 ~300 字节,512 给足余量;
+ * 再大就是破坏流式约定的内联大 input,fail-open 与扩展前一致。
+ * (Fable-5 review:120 字节窗口是按短名 Bash 的测试擦线校准,type 末尾键序
+ * + MCP 长名时 marker 落到 ~150 → 静默 no-op,专漏 P1-E 要保护的 MCP 场景。)
+ */
+const CONTENT_BLOCK_START_SCAN_WINDOW = 512;
+/** 不完整行的缓冲上限:病态上游发无 \n 长流时直接透传放弃改写,防内存膨胀。 */
+const MAX_PENDING_LINE_BYTES = 4 * 1024 * 1024;
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+/**
+ * 从已解析请求体收集响应改写的判定集合。
+ *
+ * @returns 历史含铸造形态 id(撞车可能发生)→ **全量** tool_use id 集合;
+ * 否则(纯 Anthropic / 无 tool 调用 / 非 messages 请求)→ null
+ * (调用方据此完全跳过响应改写)。
+ */
+export function collectToolUseIdsForResponseRewrite(body: unknown): Set<string> | null {
+ if (!isRecord(body) || !Array.isArray(body.messages)) return null;
+ let ids: Set<string> | null = null;
+ let hasMintedShape = false;
+ for (const msg of body.messages) {
+ if (!isRecord(msg) || !Array.isArray(msg.content)) continue;
+ for (const block of msg.content) {
+ if (!isRecord(block) || block.type !== 'tool_use') continue;
+ if (typeof block.id !== 'string' || block.id.length === 0) continue;
+ (ids ??= new Set()).add(block.id);
+ if (MINTED_TOOL_USE_ID_RE.test(block.id)) hasMintedShape = true;
+ }
+ }
+ return hasMintedShape ? ids : null;
+}
+
+/**
+ * 单个响应流的去重改写器:以**全量**历史 id 为种子,叠加本响应已见 id。
+ * 撞上已见集合的 id 改写为 `${id}_dup${N}`(N 取未占用的最小值 ≥ 2)。
+ */
+export class ToolUseIdDedupeRewriter {
+ private readonly usedIds: Set<string>;
+ /** 已改写的 id 个数(诊断 / 测试用)。 */
+ renameCount = 0;
+
+ constructor(
+ historyIds: ReadonlySet<string>,
+ private readonly onRename?: (from: string, to: string) => void,
+ /** 每个 resolve 的 id(无论是否撞车)都回调 —— 线程缓存据此记录 fresh id。 */
+ private readonly onObserved?: (id: string) => void,
+ /**
+ * 共享缓存检查:同一 thread 的并发响应流(如同步 subagent)各自持有本 rewriter,
+ * 都从请求开始时的快照构建 usedIds —— 若两个快照都空, 流 A 放行并缓存 Bash_210
+ * 后, 流 B 仍把它当 fresh 放行, CLI 追加重复 id 重新引入腐蚀。resolve 每个 id
+ * 时先问共享缓存: 别处已见过 → 按碰撞改名, 不重复放行(codex-connector P1:
+ * Check the live cache before accepting fresh IDs)。
+ */
+ private readonly sharedSeen?: (id: string) => boolean,
+ ) {
+ this.usedIds = new Set(historyIds);
+ }
+
+ /** 返回(可能)改写后的 id;不改写时返回原字符串(同引用)。 */
+ resolve(id: string): string {
+ // 本 rewriter usedIds 已见, 或共享缓存(别的并发流)已见 → 碰撞路径改名。
+ if (!this.usedIds.has(id) && !(this.sharedSeen ? this.sharedSeen(id) : false)) {
+ this.usedIds.add(id);
+ this.onObserved?.(id);
+ return id;
+ }
+ let k = 2;
+ let candidate = `${id}_dup${k}`;
+ while (this.usedIds.has(candidate) || (this.sharedSeen ? this.sharedSeen(candidate) : false)) {
+ k += 1;
+ candidate = `${id}_dup${k}`;
+ }
+ this.usedIds.add(candidate);
+ this.renameCount += 1;
+ this.onRename?.(id, candidate);
+ this.onObserved?.(candidate);
+ return candidate;
+ }
+
+ /**
+ * 处理一行 SSE 字节(含或不含行尾换行),返回改写后的行(无改动返回原 Buffer)。
+ * 只对 `data:` 开头、前缀窗口内含 `"content_block_start"` 的行做 JSON 解析;
+ * 其它行字节透传。JSON 解析失败 / 结构不符 → fail-open 返回原行。
+ */
+ rewriteSseLine(line: Buffer): Buffer {
+ // 行尾剥离(保留用于复原),容忍 \n / \r\n / 无尾行。
+ let end = line.length;
+ let newline = '';
+ if (line[end - 1] === 0x0a /* \n */) {
+ end -= 1;
+ newline = '\n';
+ if (line[end - 1] === 0x0d /* \r */) {
+ end -= 1;
+ newline = '\r\n';
+ }
+ }
+ // `data:` + 任意空白 + `{`;JSON 序列化风格(空格/键序)不做假设。
+ // 字节级比较,热路径不为每行分配字符串。
+ if (
+ end <= SSE_DATA_PREFIX.length ||
+ line[0] !== 0x64 /* d */ ||
+ line[1] !== 0x61 /* a */ ||
+ line[2] !== 0x74 /* t */ ||
+ line[3] !== 0x61 /* a */ ||
+ line[4] !== 0x3a /* : */
+ ) {
+ return line;
+ }
+ let jsonStart = 5;
+ while (jsonStart < end && (line[jsonStart] === 0x20 || line[jsonStart] === 0x09)) jsonStart += 1;
+ // UTF-8 BOM(\xEF\xBB\xBF):上游可能在最前面插入 BOM 前缀;跳过 BOM 后 { 才是 JSON 开头
+ if (
+ jsonStart + 2 < end &&
+ line[jsonStart] === 0xef &&
+ line[jsonStart + 1] === 0xbb &&
+ line[jsonStart + 2] === 0xbf
+ ) {
+ jsonStart += 3;
+ }
+ if (jsonStart >= end || line[jsonStart] !== 0x7b /* { */) return line;
+ // 扫描本身限界在窗口内(不是先全行扫再判窗口 —— 那种写法既付全行成本
+ // 又留漏命中,两头不占,Fable-5 复核指出)。
+ const markerAt = line
+ .subarray(jsonStart, Math.min(end, jsonStart + CONTENT_BLOCK_START_SCAN_WINDOW))
+ .indexOf('"content_block_start"');
+ if (markerAt === -1) return line; // ← 廉价门:非 start 帧(text delta / input delta)不透
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(line.toString('utf8', jsonStart, end));
+ } catch {
+ return line;
+ }
+ if (!isRecord(parsed)) return line;
+ const block = parsed.content_block;
+ if (!isRecord(block) || block.type !== 'tool_use' || typeof block.id !== 'string') return line;
+ const next = this.resolve(block.id);
+ if (next === block.id) return line;
+ block.id = next;
+ return Buffer.from(`${SSE_DATA_PREFIX}${JSON.stringify(parsed)}${newline}`, 'utf8');
+ }
+}
+
+/**
+ * SSE 字节流改写 Transform:按 `\n` 切行,不完整行缓冲到下一 chunk / flush;
+ * 缓冲超 MAX_PENDING_LINE_BYTES 时原样放行该行并继续(病态长行不拖垮内存)。
+ * 只重写命中的 data 行,其余字节原样通过(事件边界、注释、心跳行零干预)。
+ */
+export class ToolUseIdRewriteTransform extends Transform {
+ private pending: Buffer = Buffer.alloc(0);
+
+ constructor(private readonly rewriter: ToolUseIdDedupeRewriter) {
+ super();
+ }
+
+ override _transform(chunk: Buffer, _encoding: string, callback: TransformCallback): void {
+ try {
+ const buf = this.pending.length === 0 ? chunk : Buffer.concat([this.pending, chunk]);
+ let start = 0;
+ let nl = buf.indexOf(0x0a, start);
+ while (nl !== -1) {
+ this.push(this.rewriter.rewriteSseLine(buf.subarray(start, nl + 1)));
+ start = nl + 1;
+ nl = buf.indexOf(0x0a, start);
+ }
+ const rest = buf.subarray(start);
+ if (rest.length > MAX_PENDING_LINE_BYTES) {
+ // 病态超长行(无 \n):不做改写直接放行,防止 pending 无限增长。
+ this.push(rest);
+ this.pending = Buffer.alloc(0);
+ } else {
+ this.pending = rest;
+ }
+ callback();
+ } catch (err) {
+ callback(err as Error);
+ }
+ }
+
+ override _flush(callback: TransformCallback): void {
+ try {
+ if (this.pending.length > 0) {
+ this.push(this.rewriter.rewriteSseLine(this.pending));
+ this.pending = Buffer.alloc(0);
+ }
+ callback();
+ } catch (err) {
+ callback(err as Error);
+ }
+ }
+}
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/fork-jsonl-repair.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/fork-jsonl-repair.test.ts
index b3b15a8266..f113aeb874 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/fork-jsonl-repair.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/fork-jsonl-repair.test.ts
@@ -360,3 +360,44 @@ describe('repairForkedClaudeSessionJsonl', () => {
expect(result.clearedInvalidPreservedSegmentRefCount).toBe(3);
});
});
+
+describe('repairForkedClaudeSessionJsonl 权限保留(Copilot review)', () => {
+ it('备份沿用源转录 mode,0600 不被放宽为 0644', async () => {
+ const fsPromises = await import('node:fs/promises');
+ const projectsRoot = await makeTempDir();
+ const workingDir = path.join(projectsRoot, 'repo');
+ const projectDir = path.join(projectsRoot, workingDir.replace(/[^a-zA-Z0-9]/g, '-'));
+ const sessionId = '99999999-9999-4999-8999-999999999998';
+ const jsonlPath = path.join(projectDir, `${sessionId}.jsonl`);
+ await fs.mkdir(projectDir, { recursive: true });
+ // 构造一个带 compact boundary 需要修复的转录
+ const oldUuid = '11111111-1111-4111-8111-111111111112';
+ const newUuid = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa8';
+ await fs.writeFile(
+ jsonlPath,
+ [
+ JSON.stringify({
+ type: 'system',
+ subtype: 'compact_boundary',
+ uuid: newUuid,
+ sessionId,
+ compactMetadata: {
+ postTokens: 100,
+ preservedSegment: { headUuid: oldUuid, anchorUuid: oldUuid, tailUuid: oldUuid },
+ },
+ }),
+ line({ type: 'user', uuid: newUuid, sessionId }),
+ ].join('\n') + '\n',
+ { encoding: 'utf8', mode: 0o600 },
+ );
+ const beforeMode = (await fsPromises.stat(jsonlPath)).mode & 0o777;
+
+ const result = await repairForkedClaudeSessionJsonl({ sessionId, workingDir, projectsRoot });
+ expect(result.changed).toBe(true);
+ expect(result.backupPath).toBeDefined();
+ // 不变量:备份与修复后文件权限与原文一致(Windows 恒 0o666 → 恒等;
+ // POSIX 0600 不被放宽)。
+ const bakMode = (await fsPromises.stat(result.backupPath!)).mode & 0o777;
+ expect(bakMode).toBe(beforeMode);
+ });
+});
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/jsonl-tool-id-normalize.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/jsonl-tool-id-normalize.test.ts
new file mode 100644
index 0000000000..2872476631
--- /dev/null
+++ b/packages/maker-core/src/agents/claude-code/__tests__/jsonl-tool-id-normalize.test.ts
@@ -0,0 +1,1023 @@
+import { mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ normalizeClaudeJsonlToolIdsText,
+ normalizeClaudeSessionJsonlToolIds,
+} from '../jsonl-tool-id-normalize.js';
+
+// ── 测试夹具:按 CC 转录形态构造 jsonl 行 ────────────────────────────────
+
+function assistantEntry(uuid: string, blocks: unknown[], parentUuid?: string): string {
+ return JSON.stringify({
+ type: 'assistant',
+ uuid,
+ ...(parentUuid ? { parentUuid } : {}),
+ message: { role: 'assistant', content: blocks },
+ });
+}
+
+function userEntry(uuid: string, blocks: unknown[], parentUuid?: string): string {
+ return JSON.stringify({
+ type: 'user',
+ uuid,
+ ...(parentUuid ? { parentUuid } : {}),
+ message: { role: 'user', content: blocks },
+ });
+}
+
+function toolUse(id: string, name = 'Bash'): Record<string, unknown> {
+ return { type: 'tool_use', id, name, input: {} };
+}
+
+function toolResult(toolUseId: string, text = 'ok'): Record<string, unknown> {
+ return { type: 'tool_result', tool_use_id: toolUseId, content: text };
+}
+
+function parseEntries(text: string): Array<Record<string, unknown>> {
+ return text
+ .trim()
+ .split('\n')
+ .map((line) => JSON.parse(line) as Record<string, unknown>);
+}
+
+function contentOf(entry: Record<string, unknown>): Array<Record<string, unknown>> {
+ return (entry.message as Record<string, unknown>).content as Array<Record<string, unknown>>;
+}
+
+/** 所有 tool_use(call)id —— exchange 的唯一性按 call 判定(result 与 call 共享 id)。 */
+function allCallIds(text: string): string[] {
+ const ids: string[] = [];
+ for (const entry of parseEntries(text)) {
+ for (const b of contentOf(entry)) {
+ if (b.type === 'tool_use') ids.push(b.id as string);
+ }
+ }
+ return ids;
+}
+
+// ── 文本级归一化 ────────────────────────────────────────────────────────
+
+describe('normalizeClaudeJsonlToolIdsText', () => {
+ it('无 tool_use 的会话原样返回(同引用)', () => {
+ const text = [
+ userEntry('u1', [{ type: 'text', text: '你好' }]),
+ assistantEntry('a1', [{ type: 'text', text: '你好!' }]),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.changed).toBe(false);
+ expect(result.skipped).toBe(true);
+ expect(result.text).toBe(text);
+ });
+
+ it('Anthropic 原生 toolu_* id 不受影响(预扫不命中)', () => {
+ const text = [
+ assistantEntry('a1', [toolUse('toolu_01Jx4AbC')]),
+ userEntry('u1', [toolResult('toolu_01Jx4AbC')]),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.changed).toBe(false);
+ expect(result.skipped).toBe(true);
+ expect(result.text).toBe(text);
+ });
+
+ it('kimi 铸造 id 无重复时只做铸造空间偏移,配对保持', () => {
+ const text = [
+ assistantEntry('a1', [{ type: 'thinking', thinking: '想', signature: '' }, toolUse('Bash_210')]),
+ userEntry('u1', [toolResult('Bash_210')]),
+ assistantEntry('a2', [toolUse('TaskCreate_35', 'TaskCreate')]),
+ userEntry('u2', [toolResult('TaskCreate_35')]),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.changed).toBe(true);
+ expect(result.dedupedBlockCount).toBe(0);
+ expect(result.offsetBlockCount).toBe(4);
+ const entries = parseEntries(result.text);
+ const [call1] = contentOf(entries[0]).filter((b) => b.type === 'tool_use');
+ const [res1] = contentOf(entries[1]);
+ expect(call1.id).toBe('Bash_x210');
+ expect(res1.tool_use_id).toBe('Bash_x210');
+ expect(contentOf(entries[2])[0].id).toBe('TaskCreate_x35');
+ expect(contentOf(entries[3])[0].tool_use_id).toBe('TaskCreate_x35');
+ });
+
+ it('幂等: 归一化结果再过一遍零改写', () => {
+ const text = [
+ assistantEntry('a1', [toolUse('Bash_210')]),
+ userEntry('u1', [toolResult('Bash_210')]),
+ assistantEntry('a2', [toolUse('Bash_210')]),
+ userEntry('u2', [toolResult('Bash_210')]),
+ ].join('\n') + '\n';
+ const once = normalizeClaudeJsonlToolIdsText(text);
+ expect(once.changed).toBe(true);
+ const twice = normalizeClaudeJsonlToolIdsText(once.text);
+ expect(twice.changed).toBe(false);
+ expect(twice.text).toBe(once.text);
+ });
+
+ it('重复 id: 第 N 次出现去重为 _dupN,result 位置配对取同一终 id', () => {
+ // 复刻事故形态: 同一 Bash_210 被铸造两次(两个 exchange)
+ const text = [
+ assistantEntry('a1', [toolUse('Bash_210')]),
+ userEntry('u1', [toolResult('Bash_210', '第一次结果')]),
+ assistantEntry('a2', [{ type: 'text', text: '继续' }, toolUse('Bash_210')]),
+ userEntry('u2', [toolResult('Bash_210', '第二次结果')]),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.changed).toBe(true);
+ expect(result.duplicateIdCount).toBe(1);
+ expect(result.dedupedBlockCount).toBe(2); // 第二次 call + 第二个 result
+
+ const entries = parseEntries(result.text);
+ // 首现保持原 id(再被偏移); 第二次出现去重为 _dup2(不再匹配偏移规则)
+ expect(contentOf(entries[0])[0].id).toBe('Bash_x210');
+ expect(contentOf(entries[1])[0].tool_use_id).toBe('Bash_x210');
+ const a2Blocks = contentOf(entries[2]);
+ expect(a2Blocks[a2Blocks.length - 1].id).toBe('Bash_210_dup2');
+ expect(contentOf(entries[3])[0].tool_use_id).toBe('Bash_210_dup2');
+ });
+
+ it('同批 parallel 同 id call: result 按内容顺序配对,不 swap(codex-connector P2)', () => {
+ // 同一 assistant 消息内两个同 id tool_use(病态但存在), 后随 user 消息的
+ // tool_result 按调用顺序: 修复前 LIFO pop 会倒配(第一个 result 配第二个
+ // call, 输出 swap)。同批内必须按出现序(FIFO)配对。
+ const text = [
+ assistantEntry('a1', [toolUse('Bash_5'), toolUse('Bash_5')]), // 同批 parallel
+ userEntry('u1', [toolResult('Bash_5', '第一个结果'), toolResult('Bash_5', '第二个结果')]),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ const entries = parseEntries(result.text);
+ // 第一个 call 保持首现(偏移), 第二个 call 去重为 _dup2
+ expect(contentOf(entries[0])[0].id).toBe('Bash_x5');
+ expect(contentOf(entries[0])[1].id).toBe('Bash_5_dup2');
+ // 第一个 result 配第一个 call(顺序), 第二个 result 配第二个 call —— 不 swap
+ expect(contentOf(entries[1])[0].tool_use_id).toBe('Bash_x5');
+ expect(contentOf(entries[1])[1].tool_use_id).toBe('Bash_5_dup2');
+ });
+
+ it('并发 subagent 同 minted id: result 按 parent 身份配对,不 swap(P2: Key subagent tool results by parent)', () => {
+ // subagent A 和 B 各自 mint Bash_1(不同 parent)。若 result 只按全局 lastAssistantBatch
+ // 配对, A 的 assistant 行被 B 顶掉后, A 的 result 会错配给 B 的调用 → swap。
+ // 用 parent 身份(顶层 parentUuid)隔离配对。
+ const text = [
+ assistantEntry('aA', [toolUse('Bash_1')], 'parent-A'), // subagent A 的调用
+ assistantEntry('aB', [toolUse('Bash_1')], 'parent-B'), // subagent B 的调用
+ userEntry('uA', [toolResult('Bash_1', 'A 的结果')], 'parent-A'), // A 的 result(先到)
+ userEntry('uB', [toolResult('Bash_1', 'B 的结果')], 'parent-B'), // B 的 result
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ const entries = parseEntries(result.text);
+ // 两个调用分别定终
+ expect(contentOf(entries[0])[0].id).toBe('Bash_x1');
+ expect(contentOf(entries[1])[0].id).toBe('Bash_1_dup2');
+ // A 的 result 配 A 的调用(Bash_x1), B 的 result 配 B 的调用(Bash_1_dup2) —— 不 swap
+ expect(contentOf(entries[2])[0].tool_use_id).toBe('Bash_x1');
+ expect(contentOf(entries[3])[0].tool_use_id).toBe('Bash_1_dup2');
+ });
+
+ it('并发 subagent 同重铸 parent id: 同批并行 child 调用,result 按 parent 配对不 swap(P2: Key subagent tool results by parent)', () => {
+ // 两个 subagent 的 parent_tool_use_id 都是重铸的 Task_1(父 Agent/Task 调用重铸两次),
+ // 它们的 child 调用在同一 assistant 行(同批并行)。若 result 只按全局 batch 配对会
+ // 错配; 用 parent 身份隔离, 同批内按出现序 FIFO。
+ const text = [
+ assistantEntry('aParent1', [toolUse('Task_1')], 'parent-task'), // 父调用 1 → Task_x1
+ assistantEntry('aParent2', [toolUse('Task_1')], 'parent-task'), // 父调用 2 → Task_1_dup2
+ // A、B 的 child 调用同批并行(同一 assistant 行, 各自 parent 原始 Task_1)
+ assistantEntry('aChild', [toolUse('Bash_1'), toolUse('Bash_1')], 'Task_1'),
+ // A 的 result 先到 → 配 A 的调用(第一个 Bash_1)
+ userEntry('uA', [toolResult('Bash_1', 'A 的结果')], 'Task_1'),
+ // B 的 result → 配 B 的调用(第二个 Bash_1)
+ userEntry('uB', [toolResult('Bash_1', 'B 的结果')], 'Task_1'),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ const entries = parseEntries(result.text);
+ // 父调用定终
+ expect(contentOf(entries[0])[0].id).toBe('Task_x1');
+ expect(contentOf(entries[1])[0].id).toBe('Task_1_dup2');
+ // 子调用定终
+ expect(contentOf(entries[2]).map((b) => b.id)).toEqual(['Bash_x1', 'Bash_1_dup2']);
+ // A 的 result 配 A 的调用(Bash_x1), B 的配 B 的(Bash_1_dup2) —— 不 swap
+ expect(contentOf(entries[3])[0].tool_use_id).toBe('Bash_x1');
+ expect(contentOf(entries[4])[0].tool_use_id).toBe('Bash_1_dup2');
+ });
+
+ it('同 parent 孤儿 call + 重铸 call: result 配最新 retry,非 stale 孤儿(P1: Keep same-parent orphan retries on the newest call)', () => {
+ // 同一 parent 下, 孤儿 Bash_5(中断无 result) + 重铸 Bash_5(真实执行)。
+ // 跨批时 result 属于最新 retry(重铸 call) —— 恒取 sameParent[0](孤儿)会改写为
+ // stale 孤儿 id, 真实重铸 call 失配。
+ const text = [
+ assistantEntry('aOrphan', [toolUse('Bash_5')], 'parent-X'), // 孤儿(中断)
+ assistantEntry('aRetry', [toolUse('Bash_5')], 'parent-X'), // 重铸(真实执行)
+ userEntry('u1', [toolResult('Bash_5', '真实结果')], 'parent-X'),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ const entries = parseEntries(result.text);
+ expect(contentOf(entries[0])[0].id).toBe('Bash_x5'); // 孤儿
+ expect(contentOf(entries[1])[0].id).toBe('Bash_5_dup2'); // 重铸
+ // result 配最新 retry(重铸 Bash_5_dup2), 不配孤儿 Bash_x5
+ expect(contentOf(entries[2])[0].tool_use_id).toBe('Bash_5_dup2');
+ });
+
+ it('位置配对: 孤儿 call + 重铸 call 并存时 result 配给真实执行的那次', () => {
+ // 孤儿 Bash_5(无 result,中断残留) + 重铸 Bash_5(有 result):
+ // 出现序配对会把 result 错配给孤儿,位置配对必须配给重铸 call。
+ const text = [
+ assistantEntry('a1', [toolUse('Bash_5')]), // 孤儿(中断,无 result)
+ assistantEntry('a2', [toolUse('Bash_5')]), // 重铸(真实执行)
+ userEntry('u1', [toolResult('Bash_5', '真实结果')]),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ const entries = parseEntries(result.text);
+ expect(contentOf(entries[0])[0].id).toBe('Bash_x5'); // 孤儿保持首现 → 偏移
+ expect(contentOf(entries[1])[0].id).toBe('Bash_5_dup2'); // 重铸去重
+ expect(contentOf(entries[2])[0].tool_use_id).toBe('Bash_5_dup2'); // result 配给重铸 call
+ });
+
+ it('超编 result(无未配对 call)保持原 id 不动,但随铸造空间偏移', () => {
+ // 一个 call、两个 result(病态残留): 第二个 result 无 call 可配 → 不改名
+ const text = [
+ assistantEntry('a1', [toolUse('Bash_210')]),
+ userEntry('u1', [toolResult('Bash_210'), toolResult('Bash_210')]),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ const entries = parseEntries(result.text);
+ const results = contentOf(entries[1]);
+ expect(results[0].tool_use_id).toBe('Bash_x210');
+ expect(results[1].tool_use_id).toBe('Bash_x210'); // 超编不去重,但偏移保持与 call 一致
+ expect(result.dedupedBlockCount).toBe(0);
+ });
+
+ it('P1-C: 既有 _dup2 产物时,新重复去重顺延到 _dup3', () => {
+ // 转录里已有上一轮改名产物 Bash_210_dup2,又出现 Bash_210×2:
+ // 第二次出现若还改 Bash_210_dup2 就撞上既有 id(修复本身复发事故)。
+ const text = [
+ assistantEntry('a0', [toolUse('Bash_210_dup2')]),
+ userEntry('u0', [toolResult('Bash_210_dup2')]),
+ assistantEntry('a1', [toolUse('Bash_210')]),
+ userEntry('u1', [toolResult('Bash_210')]),
+ assistantEntry('a2', [toolUse('Bash_210')]),
+ userEntry('u2', [toolResult('Bash_210')]),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ const entries = parseEntries(result.text);
+ expect(contentOf(entries[0])[0].id).toBe('Bash_210_dup2'); // 既有产物不动
+ expect(contentOf(entries[2])[0].id).toBe('Bash_x210');
+ expect(contentOf(entries[4])[0].id).toBe('Bash_210_dup3'); // 顺延,不撞既有 _dup2
+ expect(contentOf(entries[5])[0].tool_use_id).toBe('Bash_210_dup3');
+ // 全文件 call id 唯一(result 与配对 call 共享 id,不纳入唯一性判定)
+ expect(new Set(allCallIds(result.text)).size).toBe(allCallIds(result.text).length);
+ });
+
+ it('P1-B: 既有 _x 偏移产物时,新同号 id 偏移顺延为 _xx', () => {
+ // 上轮归一化产物 Bash_x210 + resume 后 kimi 重铸的 Bash_210:
+ // 偏移若还改 Bash_x210 即撞车。
+ const text = [
+ assistantEntry('a0', [toolUse('Bash_x210')]),
+ userEntry('u0', [toolResult('Bash_x210')]),
+ assistantEntry('a1', [toolUse('Bash_210')]),
+ userEntry('u1', [toolResult('Bash_210')]),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ const entries = parseEntries(result.text);
+ expect(contentOf(entries[0])[0].id).toBe('Bash_x210'); // 既有产物不动
+ expect(contentOf(entries[2])[0].id).toBe('Bash_xx210'); // 顺延
+ expect(contentOf(entries[3])[0].tool_use_id).toBe('Bash_xx210');
+ expect(new Set(allCallIds(result.text)).size).toBe(allCallIds(result.text).length);
+ // 顺延结果幂等:二次运行零改写
+ expect(normalizeClaudeJsonlToolIdsText(result.text).changed).toBe(false);
+ });
+
+ it('MCP 下划线工具名的铸造 id 同样处理(P1-E)', () => {
+ const text = [
+ assistantEntry('a1', [toolUse('mcp__cindy_memory__call_tool_5', 'mcp__cindy_memory__call_tool')]),
+ userEntry('u1', [toolResult('mcp__cindy_memory__call_tool_5')]),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.changed).toBe(true);
+ const entries = parseEntries(result.text);
+ expect(contentOf(entries[0])[0].id).toBe('mcp__cindy_memory__call_tool_x5');
+ expect(contentOf(entries[1])[0].tool_use_id).toBe('mcp__cindy_memory__call_tool_x5');
+ });
+
+ it('带连字符的 MCP 工具名(id 含 -)同样处理(codex-connector P1)', () => {
+ // Claude MCP 前缀保留连字符(capability-routing.ts): mcp__feishu-delegate__...
+ const text = [
+ assistantEntry('a1', [
+ toolUse('mcp__feishu-delegate__feishu_read_messages_5', 'mcp__feishu-delegate__feishu_read_messages'),
+ ]),
+ userEntry('u1', [toolResult('mcp__feishu-delegate__feishu_read_messages_5')]),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.changed).toBe(true);
+ const entries = parseEntries(result.text);
+ expect(contentOf(entries[0])[0].id).toBe('mcp__feishu-delegate__feishu_read_messages_x5');
+ expect(contentOf(entries[1])[0].tool_use_id).toBe('mcp__feishu-delegate__feishu_read_messages_x5');
+ });
+
+ it('不触碰非 message 条目与 tool input 里的同名字符串', () => {
+ const queueOp = JSON.stringify({
+ type: 'queue-operation',
+ operation: 'enqueue',
+ content: '<tool-use-id>Bash_210</tool-use-id>',
+ });
+ const withInput = assistantEntry('a1', [
+ { type: 'tool_use', id: 'Bash_210', name: 'Bash', input: { command: 'echo Bash_210' } },
+ ]);
+ const text = [queueOp, withInput, userEntry('u1', [toolResult('Bash_210')])].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ const lines = result.text.trim().split('\n');
+ // queue-operation 行保持原始字节
+ expect(lines[0]).toBe(queueOp);
+ // tool_use.id 被偏移, input.command 里的字符串不动
+ const call = contentOf(parseEntries(result.text)[1])[0];
+ expect(call.id).toBe('Bash_x210');
+ expect((call.input as Record<string, unknown>).command).toBe('echo Bash_210');
+ });
+
+ it('subagent 记录顶层 parent_tool_use_id 跟随 tool_use 改名(codex-connector P2)', () => {
+ // Claude subagent 记录在顶层带 parent_tool_use_id 引用父 agent 的 tool_use id,
+ // 归一化改名后必须同步, 否则 subagent 关联断裂(translator 用其作 parentToolUseId)。
+ const text = [
+ assistantEntry('a1', [toolUse('Bash_210')]),
+ userEntry('u1', [toolResult('Bash_210')]),
+ JSON.stringify({
+ type: 'stream_event',
+ uuid: 'stream-1',
+ parent_tool_use_id: 'Bash_210',
+ event: { type: 'message_start', message: { model: 'kimi-k3', usage: {} } },
+ }),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.changed).toBe(true);
+ const entries = parseEntries(result.text);
+ // tool_use 被偏移为 Bash_x210
+ expect(contentOf(entries[0])[0].id).toBe('Bash_x210');
+ // 顶层 parent_tool_use_id 同步为 Bash_x210
+ expect((entries[2] as Record<string, unknown>).parent_tool_use_id).toBe('Bash_x210');
+ });
+
+ it('同 id 重铸多次时 subagent 顶层字段按**行作用域**配对(codex-connector P2)', () => {
+ // 单一 last mapping 会把所有 subagent 记录挂到最后一个 duplicate; 这里验证
+ // 位置配对: 每个 stream_event 引用「它所在位置之前最近的同名 call」的终 id。
+ const text = [
+ // 首次调用 → Bash_x210
+ assistantEntry('a1', [toolUse('Bash_210')]),
+ // 紧随首次调用的 subagent 记录 → 应挂 Bash_x210
+ JSON.stringify({
+ type: 'stream_event',
+ uuid: 'stream-1',
+ parent_tool_use_id: 'Bash_210',
+ tool_use_id: 'Bash_210',
+ event: { type: 'message_start', message: { model: 'kimi-k3', usage: {} } },
+ }),
+ userEntry('u1', [toolResult('Bash_210')]),
+ // 重铸的第二次调用 → Bash_210_dup2
+ assistantEntry('a2', [toolUse('Bash_210')]),
+ // 紧随重铸调用的 subagent 记录 → 应挂 Bash_210_dup2
+ JSON.stringify({
+ type: 'stream_event',
+ uuid: 'stream-2',
+ parent_tool_use_id: 'Bash_210',
+ tool_use_id: 'Bash_210',
+ event: { type: 'message_start', message: { model: 'kimi-k3', usage: {} } },
+ }),
+ userEntry('u2', [toolResult('Bash_210')]),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.changed).toBe(true);
+ const entries = parseEntries(result.text);
+ // 两次调用分别定终
+ expect(contentOf(entries[0])[0].id).toBe('Bash_x210');
+ expect(contentOf(entries[3])[0].id).toBe('Bash_210_dup2');
+ // 行作用域: 第一次调用后的 subagent 挂首次终 id
+ expect((entries[1] as Record<string, unknown>).parent_tool_use_id).toBe('Bash_x210');
+ expect((entries[1] as Record<string, unknown>).tool_use_id).toBe('Bash_x210');
+ // 第二次调用后的 subagent 挂重铸终 id —— 不误挂到首个
+ expect((entries[4] as Record<string, unknown>).parent_tool_use_id).toBe('Bash_210_dup2');
+ expect((entries[4] as Record<string, unknown>).tool_use_id).toBe('Bash_210_dup2');
+ });
+
+ it('tool_use_summary 顶层 preceding_tool_use_ids 数组跟随改名(codex-connector P2)', () => {
+ // translator 把 preceding_tool_use_ids 转发为 tool_result.data.toolUseIds, 归一化
+ // 改名后数组必须同步, 否则 summary 事件挂不上归一化后的 tool 卡片。
+ const text = [
+ assistantEntry('a1', [toolUse('Bash_210')]),
+ userEntry('u1', [toolResult('Bash_210')]),
+ JSON.stringify({
+ type: 'tool_use_summary',
+ summary: 'ran a command',
+ preceding_tool_use_ids: ['Bash_210'],
+ }),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.changed).toBe(true);
+ const entries = parseEntries(result.text);
+ // tool_use 被偏移为 Bash_x210
+ expect(contentOf(entries[0])[0].id).toBe('Bash_x210');
+ // summary 数组项同步为 Bash_x210
+ expect((entries[2] as Record<string, unknown>).preceding_tool_use_ids).toEqual(['Bash_x210']);
+ });
+
+ it('preceding_tool_use_ids 数组重复 id 独立消费 occurrence, 不缓存复用(P2: Resolve repeated summary IDs independently)', () => {
+ // 同行两个重复 Bash_5 调用 → Bash_x5 + Bash_5_dup2。summary 数组 ['Bash_5','Bash_5']
+ // 若走 entry 缓存会变成 ['Bash_x5','Bash_x5'](第二次复用首次结果), 第二个 summary
+ // 挂到错误的 tool card。数组项必须各自消费 occurrence: 第一项 Bash_x5, 第二项 Bash_5_dup2。
+ const text = [
+ assistantEntry('a1', [toolUse('Bash_5'), toolUse('Bash_5')]),
+ userEntry('u1', [toolResult('Bash_5'), toolResult('Bash_5')]),
+ JSON.stringify({
+ type: 'tool_use_summary',
+ summary: 'ran commands',
+ preceding_tool_use_ids: ['Bash_5', 'Bash_5'],
+ }),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.changed).toBe(true);
+ const entries = parseEntries(result.text);
+ expect(contentOf(entries[0]).map((b) => b.id)).toEqual(['Bash_x5', 'Bash_5_dup2']);
+ // 数组重复项各自消费: 第一项首个调用, 第二项第二个调用
+ expect((entries[2] as Record<string, unknown>).preceding_tool_use_ids).toEqual(['Bash_x5', 'Bash_5_dup2']);
+ });
+
+ it('child/task 记录先消费 occPtr 后, summary 数组仍按调用顺序(P2: Keep summary occurrence cursors independent)', () => {
+ // 两个重复 Task_1 调用后, 先有 child/task 记录(推进共享 occPtr), 再出现 summary
+ // 数组 ['Task_1','Task_1']。若数组用共享 occPtr, 起点被 child 改写推到第二个
+ // occurrence, 变成 ['Task_1_dup2','Task_1_dup2'] 而非 [首个, 第二个]。数组必须
+ // 用独立游标, 不受标量/child 消费污染。
+ const text = [
+ assistantEntry('a1', [toolUse('Task_1'), toolUse('Task_1')]),
+ JSON.stringify({
+ type: 'task_progress',
+ subtype: 'task_progress',
+ task_id: 'task-1',
+ tool_use_id: 'Task_1',
+ status: 'running',
+ }),
+ JSON.stringify({
+ type: 'tool_use_summary',
+ summary: 'ran tasks',
+ preceding_tool_use_ids: ['Task_1', 'Task_1'],
+ }),
+ userEntry('u1', [toolResult('Task_1'), toolResult('Task_1')]),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.changed).toBe(true);
+ const entries = parseEntries(result.text);
+ expect(contentOf(entries[0]).map((b) => b.id)).toEqual(['Task_x1', 'Task_1_dup2']);
+ // child 记录挂首个调用(childRef 复用)
+ expect((entries[1] as Record<string, unknown>).tool_use_id).toBe('Task_x1');
+ // summary 数组独立游标: 不受 child 消费污染, 按调用顺序 [首个, 第二个]
+ expect((entries[2] as Record<string, unknown>).preceding_tool_use_ids).toEqual(['Task_x1', 'Task_1_dup2']);
+ });
+
+ it('单 item summary 指向实际产生 summary 的调用(该行之前最近的)(P2: Map summary IDs from the summary row)', () => {
+ // 只总结第二个调用(第一个 result 短没 summary)时, summary 数组单个 item 应指向
+ // 第二个 occurrence(Bash_5_dup2), 而非全局计数从 occurrence 0 开始指向首个。
+ // 数组按该 summary 行之前的 occurrences 行作用域解析。
+ const text = [
+ assistantEntry('a1', [toolUse('Bash_5'), toolUse('Bash_5')]),
+ userEntry('u1', [toolResult('Bash_5'), toolResult('Bash_5')]),
+ JSON.stringify({
+ type: 'tool_use_summary',
+ summary: 'ran the second command',
+ preceding_tool_use_ids: ['Bash_5'],
+ }),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.changed).toBe(true);
+ const entries = parseEntries(result.text);
+ expect(contentOf(entries[0]).map((b) => b.id)).toEqual(['Bash_x5', 'Bash_5_dup2']);
+ // 行作用域 + per-summary 游标: 单 item 从该行之前 occurrences 的【最近】匹配
+ expect((entries[2] as Record<string, unknown>).preceding_tool_use_ids).toEqual(['Bash_5_dup2']);
+ });
+
+ it('同一 assistant 行内同 id 并行调用: 子记录按内容顺序 FIFO 各挂各次(codex-connector P2)', () => {
+ // 同一条 assistant 消息含两个 Bash_210(并行) → Bash_x210 + Bash_210_dup2。
+ // 两条 subagent 记录引用 Bash_210: 第一条应挂第一个调用(Bash_x210),
+ // 第二条挂第二个(Bash_210_dup2) —— 同行块不能折叠成单一 last mapping。
+ const text = [
+ assistantEntry('a1', [toolUse('Bash_210'), toolUse('Bash_210')]),
+ JSON.stringify({
+ type: 'stream_event',
+ uuid: 'stream-1',
+ parent_tool_use_id: 'Bash_210',
+ event: { type: 'message_start', message: { model: 'kimi-k3', usage: {} } },
+ }),
+ JSON.stringify({
+ type: 'stream_event',
+ uuid: 'stream-2',
+ parent_tool_use_id: 'Bash_210',
+ event: { type: 'message_start', message: { model: 'kimi-k3', usage: {} } },
+ }),
+ userEntry('u1', [toolResult('Bash_210'), toolResult('Bash_210')]),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.changed).toBe(true);
+ const entries = parseEntries(result.text);
+ // 同行两个并行调用分别定终: 第一个偏移, 第二个去重
+ const callIds = contentOf(entries[0]).map((b) => b.id);
+ expect(callIds[0]).toBe('Bash_x210');
+ expect(callIds[1]).toBe('Bash_210_dup2');
+ // 两条子记录按内容顺序 FIFO: 第一条挂首个调用, 第二条挂第二个
+ expect((entries[1] as Record<string, unknown>).parent_tool_use_id).toBe('Bash_x210');
+ expect((entries[2] as Record<string, unknown>).parent_tool_use_id).toBe('Bash_210_dup2');
+ });
+
+ it('同一 child(共享 uuid)的多条 stream_event 复用同一终 id, 不拆散到多卡片(codex-connector P2)', () => {
+ // 同行两个 Bash_210(并行) → Bash_x210 + Bash_210_dup2。
+ // 同一 uuid 的 child 发多条 stream_event(都引用 Bash_210): 必须全部挂同一终 id
+ // (Bash_x210), 而不是每条事件消费一个 occurrence(否则第一条挂 Bash_x210、
+ // 第二条被重新映射到 Bash_210_dup2, 同一 subagent 流被拆散到两张卡片)。
+ const childEvent = (uuid: string): string =>
+ JSON.stringify({
+ type: 'stream_event',
+ uuid,
+ parent_tool_use_id: 'Bash_210',
+ event: { type: 'message_start', message: { model: 'kimi-k3', usage: {} } },
+ });
+ const text = [
+ assistantEntry('a1', [toolUse('Bash_210'), toolUse('Bash_210')]),
+ childEvent('stream-child-1'),
+ childEvent('stream-child-1'), // 同一 child 的第二条事件
+ childEvent('stream-child-1'), // 第三条
+ childEvent('stream-child-2'), // 另一 child → 挂第二个调用
+ userEntry('u1', [toolResult('Bash_210'), toolResult('Bash_210')]),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.changed).toBe(true);
+ const entries = parseEntries(result.text);
+ // 同行两个并行调用分别定终
+ expect(contentOf(entries[0]).map((b) => b.id)).toEqual(['Bash_x210', 'Bash_210_dup2']);
+ // 同一 child 的三条事件全部挂 Bash_x210(首次解析, 不按条推进)
+ expect((entries[1] as Record<string, unknown>).parent_tool_use_id).toBe('Bash_x210');
+ expect((entries[2] as Record<string, unknown>).parent_tool_use_id).toBe('Bash_x210');
+ expect((entries[3] as Record<string, unknown>).parent_tool_use_id).toBe('Bash_x210');
+ // 另一 child 挂第二个调用(各 child 独立消费)
+ expect((entries[4] as Record<string, unknown>).parent_tool_use_id).toBe('Bash_210_dup2');
+ });
+
+ it('stream_event 的 event.content_block.id 跟随归一化改名(P2: Rewrite stream-event tool IDs too)', () => {
+ // handleStreamEvent 用 event.content_block.id 驱动 tool-use start 状态; 归一化后
+ // 若仍留旧 id, replay/import 会以旧 id 发 tool card, 与 tool_result/summary 指向
+ // 不一致。验证嵌套的 event.content_block.id 也被改写。
+ const text = [
+ assistantEntry('a1', [toolUse('Bash_210')]),
+ JSON.stringify({
+ type: 'stream_event',
+ uuid: 'stream-1',
+ parent_tool_use_id: 'Bash_210',
+ event: {
+ type: 'content_block_start',
+ content_block: { type: 'tool_use', id: 'Bash_210', name: 'Bash', input: {} },
+ },
+ }),
+ userEntry('u1', [toolResult('Bash_210')]),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.changed).toBe(true);
+ const entries = parseEntries(result.text);
+ expect(contentOf(entries[0])[0].id).toBe('Bash_x210');
+ const evt = (entries[1] as Record<string, unknown>).event as Record<string, unknown>;
+ expect((evt.content_block as Record<string, unknown>).id).toBe('Bash_x210');
+ });
+
+ it('stream_event 先于 assistant 行到达时 content_block.id 前瞻匹配(P2: Handle stream events before assistant rows)', () => {
+ // SDK 允许 stream_event 的 content_block_start 先于同 tool call 的 assistant 消息
+ // 到达。后顾解析(只看 line < index)在此顺序下找不到 occurrence, content_block.id
+ // 会保持旧值 Bash_210, 与后续归一化的 assistant/tool_result(Bash_x210)不一致。
+ // 前瞻解析必须匹配「即将出现」的 occurrence。
+ const text = [
+ JSON.stringify({
+ type: 'stream_event',
+ uuid: 'stream-1',
+ parent_tool_use_id: 'Bash_210',
+ event: {
+ type: 'content_block_start',
+ content_block: { type: 'tool_use', id: 'Bash_210', name: 'Bash', input: {} },
+ },
+ }),
+ assistantEntry('a1', [toolUse('Bash_210')]),
+ userEntry('u1', [toolResult('Bash_210')]),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.changed).toBe(true);
+ const entries = parseEntries(result.text);
+ // stream_event 在 line 0, assistant 在 line 1: content_block.id 前瞻匹配到 Bash_x210
+ const evt = (entries[0] as Record<string, unknown>).event as Record<string, unknown>;
+ expect((evt.content_block as Record<string, unknown>).id).toBe('Bash_x210');
+ // 顶层 parent_tool_use_id 同样前瞻改写(P1: Forward-map pre-assistant top-level
+ // tool refs) —— handleStreamEvent 用它作 parentToolUseId, 必须与 card id 一致
+ expect((entries[0] as Record<string, unknown>).parent_tool_use_id).toBe('Bash_x210');
+ // 后续 assistant / tool_result 也一致
+ expect(contentOf(entries[1])[0].id).toBe('Bash_x210');
+ });
+
+ it('两个重复 content_block_start 先于 assistant 时前瞻 FIFO 各匹配各次(P2: Map pre-assistant stream starts by occurrence)', () => {
+ // 两个同 id 的 content_block_start 先于 assistant 行到达。若前瞻都取第一个
+ // future occurrence, 两条 stream start 都指向 Bash_x5, 而 assistant/tool_result
+ // 把 duplicate 分配到 Bash_x5 + Bash_5_dup2 —— 第二个 tool card 以错 id 创建。
+ // 前瞻必须按内容顺序 FIFO: 第一条 start → Bash_x5, 第二条 → Bash_5_dup2。
+ const startEvent = (id: string): string =>
+ JSON.stringify({
+ type: 'stream_event',
+ uuid: `stream-${id}`,
+ event: {
+ type: 'content_block_start',
+ content_block: { type: 'tool_use', id: 'Bash_5', name: 'Bash', input: {} },
+ },
+ });
+ const text = [
+ startEvent('s1'), // 第一个 start
+ startEvent('s2'), // 第二个 start
+ assistantEntry('a1', [toolUse('Bash_5'), toolUse('Bash_5')]),
+ userEntry('u1', [toolResult('Bash_5'), toolResult('Bash_5')]),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.changed).toBe(true);
+ const entries = parseEntries(result.text);
+ const evt1 = (entries[0] as Record<string, unknown>).event as Record<string, unknown>;
+ const evt2 = (entries[1] as Record<string, unknown>).event as Record<string, unknown>;
+ // 两条 start 前瞻 FIFO: 第一条挂首个调用, 第二条挂第二个调用
+ expect((evt1.content_block as Record<string, unknown>).id).toBe('Bash_x5');
+ expect((evt2.content_block as Record<string, unknown>).id).toBe('Bash_5_dup2');
+ // assistant 两个调用分别定终
+ expect(contentOf(entries[2]).map((b) => b.id)).toEqual(['Bash_x5', 'Bash_5_dup2']);
+ });
+
+ it('content_block_start 在 assistant 之后时 fallback 按内容顺序消费(P2: Consume post-assistant stream starts by occurrence)', () => {
+ // 两个同 id 的 content_block_start 记录在 assistant 行之后。无 future occurrence
+ // 时 fallback 若总返回最后一个(occs[last] = Bash_5_dup2), 两条 start 都指向
+ // 第二个调用, 首张 tool card 以错 id 创建/更新。fallback 必须按内容顺序:
+ // 第一条 → Bash_x5, 第二条 → Bash_5_dup2。
+ const startEvent = (uuid: string): string =>
+ JSON.stringify({
+ type: 'stream_event',
+ uuid,
+ event: {
+ type: 'content_block_start',
+ content_block: { type: 'tool_use', id: 'Bash_5', name: 'Bash', input: {} },
+ },
+ });
+ const text = [
+ assistantEntry('a1', [toolUse('Bash_5'), toolUse('Bash_5')]),
+ userEntry('u1', [toolResult('Bash_5'), toolResult('Bash_5')]),
+ startEvent('stream-1'), // assistant 之后的第一个 start
+ startEvent('stream-2'), // assistant 之后的第二个 start
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.changed).toBe(true);
+ const entries = parseEntries(result.text);
+ const evt1 = (entries[2] as Record<string, unknown>).event as Record<string, unknown>;
+ const evt2 = (entries[3] as Record<string, unknown>).event as Record<string, unknown>;
+ // fallback 按内容顺序: 第一条挂首个调用, 第二条挂第二个调用
+ expect((evt1.content_block as Record<string, unknown>).id).toBe('Bash_x5');
+ expect((evt2.content_block as Record<string, unknown>).id).toBe('Bash_5_dup2');
+ // assistant 两个调用分别定终
+ expect(contentOf(entries[0]).map((b) => b.id)).toEqual(['Bash_x5', 'Bash_5_dup2']);
+ });
+
+ it('task 记录(task_started/progress/notification)按 task_id 复用同一终 id, 不拆散到多卡片(P2: Reuse task_id)', () => {
+ // task 系统记录用 task_id + tool_use_id 标识 child, 通常无 uuid。若按条消费
+ // occurrence, 同一条 task 的 progress/notification 会被重映射到下一个 occurrence。
+ const taskRow = (taskId: string, subtype: string, status = 'running'): string =>
+ JSON.stringify({
+ type: 'task_progress',
+ subtype,
+ task_id: taskId,
+ tool_use_id: 'Bash_210',
+ status,
+ });
+ const text = [
+ assistantEntry('a1', [toolUse('Bash_210'), toolUse('Bash_210')]),
+ taskRow('task-1', 'task_started'),
+ taskRow('task-1', 'task_progress'),
+ taskRow('task-1', 'task_notification', 'completed'),
+ taskRow('task-2', 'task_started'),
+ taskRow('task-2', 'task_notification', 'completed'),
+ userEntry('u1', [toolResult('Bash_210'), toolResult('Bash_210')]),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.changed).toBe(true);
+ const entries = parseEntries(result.text);
+ expect(contentOf(entries[0]).map((b) => b.id)).toEqual(['Bash_x210', 'Bash_210_dup2']);
+ // task-1 的三条记录全部挂 Bash_x210(task_id 复用, 不按条推进)
+ expect((entries[1] as Record<string, unknown>).tool_use_id).toBe('Bash_x210');
+ expect((entries[2] as Record<string, unknown>).tool_use_id).toBe('Bash_x210');
+ expect((entries[3] as Record<string, unknown>).tool_use_id).toBe('Bash_x210');
+ // task-2 挂第二个调用(各 task 独立消费)
+ expect((entries[4] as Record<string, unknown>).tool_use_id).toBe('Bash_210_dup2');
+ expect((entries[5] as Record<string, unknown>).tool_use_id).toBe('Bash_210_dup2');
+ });
+
+ it('task 记录同时带 task_id + uuid 时优先 task_id 复用(P2: Prefer task IDs before per-row UUIDs)', () => {
+ // task 系统记录可能同时带稳定 task_id 和 per-row uuid。若 child 身份优先取 uuid,
+ // 同一 task 的多条记录(uuid 各不相同)不共享 task 级映射, 各自消费下一个 duplicate
+ // occurrence, 把单个 task 拆散到多张卡片。task_id 必须优先。
+ const taskRow = (taskId: string, uuid: string): string =>
+ JSON.stringify({
+ type: 'task_progress',
+ subtype: 'task_progress',
+ task_id: taskId,
+ uuid,
+ tool_use_id: 'Bash_5',
+ status: 'running',
+ });
+ const text = [
+ assistantEntry('a1', [toolUse('Bash_5'), toolUse('Bash_5')]),
+ taskRow('task-1', 'row-uuid-1'), // 同一 task 两条记录, uuid 各不相同
+ taskRow('task-1', 'row-uuid-2'),
+ taskRow('task-2', 'row-uuid-3'),
+ userEntry('u1', [toolResult('Bash_5'), toolResult('Bash_5')]),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.changed).toBe(true);
+ const entries = parseEntries(result.text);
+ expect(contentOf(entries[0]).map((b) => b.id)).toEqual(['Bash_x5', 'Bash_5_dup2']);
+ // task-1 两条记录(uuid 不同)因 task_id 复用全部挂 Bash_x5
+ expect((entries[1] as Record<string, unknown>).tool_use_id).toBe('Bash_x5');
+ expect((entries[2] as Record<string, unknown>).tool_use_id).toBe('Bash_x5');
+ // task-2 挂第二个调用
+ expect((entries[3] as Record<string, unknown>).tool_use_id).toBe('Bash_5_dup2');
+ });
+
+ it('content_block.id 独立解析, 不复用父的 entryRef 映射(P1: Resolve nested stream IDs independently)', () => {
+ // 父调用 Task_1 与子自己启动的首个 Task_1 字符串相同但指向不同 occurrence。
+ // 若 content_block.id 走 resolveField 复用标量缓存的父映射, replay/import 把子
+ // tool 挂到父 id 下。content_block.id 必须独立消费 occurrence。
+ const text = [
+ JSON.stringify({
+ type: 'stream_event',
+ uuid: 'child-stream',
+ parent_tool_use_id: 'Task_1',
+ event: {
+ type: 'content_block_start',
+ content_block: { type: 'tool_use', id: 'Task_1', name: 'Task', input: {} },
+ },
+ }),
+ assistantEntry('a1', [toolUse('Task_1')]), // 父调用(第一个 Task_1)
+ userEntry('u1', [toolResult('Task_1')]),
+ assistantEntry('a2', [toolUse('Task_1')]), // 子调用(第二个 Task_1)
+ userEntry('u2', [toolResult('Task_1')]),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.changed).toBe(true);
+ const entries = parseEntries(result.text);
+ expect(contentOf(entries[1]).map((b) => b.id)).toEqual(['Task_x1']);
+ expect(contentOf(entries[3]).map((b) => b.id)).toEqual(['Task_1_dup2']);
+ // 标量 parent_tool_use_id(父调用)→ 前瞻匹配第一个 Task_1 → Task_x1
+ expect((entries[0] as Record<string, unknown>).parent_tool_use_id).toBe('Task_x1');
+ // content_block.id(子调用)→ 独立解析匹配第二个 Task_1 → Task_1_dup2,
+ // 不复用父映射
+ const evt = (entries[0] as Record<string, unknown>).event as Record<string, unknown>;
+ expect((evt.content_block).id).toBe('Task_1_dup2');
+ });
+
+ it('child content_block_start 在 assistant 后且父同 id 时匹配子 occurrence(P1: Map post-assistant stream starts to the child occurrence)', () => {
+ // 父 Agent/Task 调用 Task_1(line 0), 子 assistant 的 tool 也 Task_1(line 2, 重铸)。
+ // child 的 content_block_start(带 parent_tool_use_id)在 assistant 之后(line 3),
+ // 无 future occurrence —— 若 fallback 到最早之前会命中父(Task_x1), 但应命中子
+ // occurrence(Task_1_dup2), 否则 replay/import 以父 id 启动子 tool card。
+ const text = [
+ assistantEntry('aParent', [toolUse('Task_1')]), // 父调用 → Task_x1
+ userEntry('uParent', [toolResult('Task_1')]),
+ assistantEntry('aChild', [toolUse('Task_1')]), // 子 tool → Task_1_dup2
+ JSON.stringify({
+ type: 'stream_event',
+ uuid: 'child-stream',
+ parent_tool_use_id: 'Task_1',
+ event: {
+ type: 'content_block_start',
+ content_block: { type: 'tool_use', id: 'Task_1', name: 'Task', input: {} },
+ },
+ }),
+ userEntry('uChild', [toolResult('Task_1')]),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.changed).toBe(true);
+ const entries = parseEntries(result.text);
+ expect(contentOf(entries[0])[0].id).toBe('Task_x1');
+ expect(contentOf(entries[2])[0].id).toBe('Task_1_dup2');
+ // content_block_start(assistant 后, 带 parent)匹配子 occurrence(Task_1_dup2), 非父
+ const evt = (entries[3] as Record<string, unknown>).event as Record<string, unknown>;
+ expect((evt.content_block as Record<string, unknown>).id).toBe('Task_1_dup2');
+ });
+
+ it('重铸后新调用的 content_block_start 前瞻匹配新调用, 不后顾命中旧调用(P2: Map pre-assistant duplicate stream IDs forward)', () => {
+ // 旧调用 Bash_5(line 0)已存在, 之后重铸新调用(line 3)。content_block_start(line 2)
+ // 预告的是新调用 —— 后顾优先会命中旧 Bash_x5, 但语义上应前瞻匹配 Bash_5_dup2。
+ const text = [
+ assistantEntry('a1', [toolUse('Bash_5')]),
+ userEntry('u1', [toolResult('Bash_5')]),
+ JSON.stringify({
+ type: 'stream_event',
+ uuid: 'stream-1',
+ event: {
+ type: 'content_block_start',
+ content_block: { type: 'tool_use', id: 'Bash_5', name: 'Bash', input: {} },
+ },
+ }),
+ assistantEntry('a2', [toolUse('Bash_5')]),
+ userEntry('u2', [toolResult('Bash_5')]),
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.changed).toBe(true);
+ const entries = parseEntries(result.text);
+ // 旧调用 → Bash_x5, 重铸新调用 → Bash_5_dup2
+ expect(contentOf(entries[0])[0].id).toBe('Bash_x5');
+ expect(contentOf(entries[3])[0].id).toBe('Bash_5_dup2');
+ // content_block_start 前瞻匹配新调用(不是旧调用)
+ const evt = (entries[2] as Record<string, unknown>).event as Record<string, unknown>;
+ expect((evt.content_block as Record<string, unknown>).id).toBe('Bash_5_dup2');
+ });
+
+ it('未改动行保持原始字节(不重新序列化)', () => {
+ const unchangedLine = userEntry('u1', [{ type: 'text', text: '含 unicode 与 空格' }]);
+ const changedLine = assistantEntry('a1', [toolUse('Bash_210')]);
+ const text = [unchangedLine, changedLine].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.text.trim().split('\n')[0]).toBe(unchangedLine);
+ });
+
+ it('尾部畸形残行原样保留并继续归一化(CLI 崩溃截断常态)', () => {
+ const malformedTail = '{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","id":"Bas';
+ const text = [
+ assistantEntry('a1', [toolUse('Bash_210')]),
+ userEntry('u1', [toolResult('Bash_210')]),
+ malformedTail,
+ ].join('\n') + '\n';
+ const result = normalizeClaudeJsonlToolIdsText(text);
+ expect(result.changed).toBe(true);
+ expect(result.keptMalformedTailLine).toBe(true);
+ const lines = result.text.trim().split('\n');
+ expect(lines[2]).toBe(malformedTail);
+ const firstEntry = JSON.parse(lines[0]) as Record<string, unknown>;
+ expect(contentOf(firstEntry)[0].id).toBe('Bash_x210');
+ });
+
+ it('中间行畸形仍抛错(调用方 best-effort 兜底)', () => {
+ const text = [
+ '{"type":"assistant",broken',
+ assistantEntry('a1', [toolUse('Bash_210')]),
+ ].join('\n') + '\n';
+ expect(() => normalizeClaudeJsonlToolIdsText(text)).toThrow(/JSONL parse error at line 1/);
+ });
+
+ it('空文件 / 无尾换行都能处理', () => {
+ expect(normalizeClaudeJsonlToolIdsText('').changed).toBe(false);
+ const noNewline = assistantEntry('a1', [toolUse('Bash_210')]);
+ const result = normalizeClaudeJsonlToolIdsText(noNewline);
+ expect(result.changed).toBe(true);
+ expect(result.text.endsWith('\n')).toBe(false);
+ });
+});
+
+// ── 文件级归一化 ────────────────────────────────────────────────────────
+
+describe('normalizeClaudeSessionJsonlToolIds', () => {
+ let tmpDir: string | undefined;
+
+ afterEach(async () => {
+ if (tmpDir) {
+ await rm(tmpDir, { recursive: true, force: true });
+ tmpDir = undefined;
+ }
+ });
+
+ it('有改动时先备份再原子重写; 无改动不动文件', async () => {
+ tmpDir = await mkdtemp(path.join(os.tmpdir(), 'jsonl-normalize-'));
+ const filePath = path.join(tmpDir, 'session.jsonl');
+ const original = [
+ assistantEntry('a1', [toolUse('Bash_210')]),
+ userEntry('u1', [toolResult('Bash_210')]),
+ assistantEntry('a2', [toolUse('Bash_210')]),
+ userEntry('u2', [toolResult('Bash_210')]),
+ ].join('\n') + '\n';
+ await writeFile(filePath, original, 'utf8');
+
+ const result = await normalizeClaudeSessionJsonlToolIds(filePath);
+ expect(result.changed).toBe(true);
+ expect(result.backupPath).toBeDefined();
+ // 备份保留原文
+ expect(await readFile(result.backupPath!, 'utf8')).toBe(original);
+ // 文件已归一化,无 tmp 残留
+ const rewritten = await readFile(filePath, 'utf8');
+ expect(rewritten).toContain('Bash_x210');
+ expect(rewritten).toContain('Bash_210_dup2');
+ expect((await readdir(tmpDir)).filter((f) => f.endsWith('.tmp'))).toHaveLength(0);
+
+ // 第二次运行: 幂等 → 无改动、不再产生新备份
+ const again = await normalizeClaudeSessionJsonlToolIds(filePath);
+ expect(again.changed).toBe(false);
+ expect(again.backupPath).toBeUndefined();
+ const backups = (await readdir(tmpDir)).filter((f) => f.includes('.bak.'));
+ expect(backups).toHaveLength(1);
+ });
+
+ it('纯 Anthropic 会话: 预扫跳过, 不读写文件内容', async () => {
+ tmpDir = await mkdtemp(path.join(os.tmpdir(), 'jsonl-normalize-'));
+ const filePath = path.join(tmpDir, 'session.jsonl');
+ const original = [
+ assistantEntry('a1', [toolUse('toolu_01Jx4AbC')]),
+ userEntry('u1', [toolResult('toolu_01Jx4AbC')]),
+ ].join('\n') + '\n';
+ await writeFile(filePath, original, 'utf8');
+ const result = await normalizeClaudeSessionJsonlToolIds(filePath);
+ expect(result.changed).toBe(false);
+ expect(result.skipped).toBe(true);
+ expect(await readFile(filePath, 'utf8')).toBe(original);
+ expect((await readdir(tmpDir)).filter((f) => f.includes('.bak.'))).toHaveLength(0);
+ });
+
+ it('权限保留: 重写文件与 .bak 备份沿用原文件权限(不默认 0644 放宽)', async () => {
+ const fsPromises = await import('node:fs/promises');
+ tmpDir = await mkdtemp(path.join(os.tmpdir(), 'jsonl-normalize-'));
+ const filePath = path.join(tmpDir, 'session.jsonl');
+ const original = [
+ assistantEntry('a1', [toolUse('Bash_210')]),
+ userEntry('u1', [toolResult('Bash_210')]),
+ ].join('\n') + '\n';
+ await writeFile(filePath, original, { encoding: 'utf8', mode: 0o600 });
+ const beforeMode = (await fsPromises.stat(filePath)).mode & 0o777;
+
+ const result = await normalizeClaudeSessionJsonlToolIds(filePath);
+ expect(result.changed).toBe(true);
+
+ // 不变量: 归一化后权限与归一化前一致(Windows 恒 0o666 → 恒等;
+ // POSIX 上 0600 转录不得被 tmp 默认 0644 放宽)。
+ const afterMode = (await fsPromises.stat(filePath)).mode & 0o777;
+ expect(afterMode).toBe(beforeMode);
+ const bakMode = (await fsPromises.stat(result.backupPath!)).mode & 0o777;
+ expect(bakMode).toBe(beforeMode);
+ });
+
+ it('Windows rename 覆盖目标抛 EEXIST 时降级为删除+rename 重试(copilot review)', async () => {
+ tmpDir = await mkdtemp(path.join(os.tmpdir(), 'jsonl-normalize-'));
+ const filePath = path.join(tmpDir, 'session.jsonl');
+ const original = [
+ assistantEntry('a1', [toolUse('Bash_210')]),
+ userEntry('u1', [toolResult('Bash_210')]),
+ ].join('\n') + '\n';
+ await writeFile(filePath, original, 'utf8');
+
+ const fsMod = await import('node:fs');
+ const realRename = fsMod.promises.rename.bind(fsMod.promises);
+ // 第一次 rename 模拟 Windows/exFAT 拒绝覆盖已存在目标; 第二次(删除后)成功。
+ const renameSpy = vi
+ .spyOn(fsMod.promises, 'rename')
+ .mockImplementation(async (oldPath: any, newPath: any) => {
+ if (renameSpy.mock.calls.length === 1) {
+ const err = new Error('EEXIST: file already exists') as NodeJS.ErrnoException;
+ err.code = 'EEXIST';
+ throw err;
+ }
+ return realRename(oldPath, newPath);
+ });
+
+ try {
+ const result = await normalizeClaudeSessionJsonlToolIds(filePath);
+ expect(result.changed).toBe(true);
+ // 降级成功: rename 被调用两次(首次失败 + 删除后重试)
+ expect(renameSpy).toHaveBeenCalledTimes(2);
+ // 归一化已生效,无 tmp 残留
+ const rewritten = await readFile(filePath, 'utf8');
+ expect(rewritten).toContain('Bash_x210');
+ expect((await readdir(tmpDir)).filter((f) => f.endsWith('.tmp'))).toHaveLength(0);
+ } finally {
+ renameSpy.mockRestore();
+ }
+ });
+
+ it('rename 降级失败时从 .bak 备份恢复,转录不丢且不抛错(copilot review)', async () => {
+ tmpDir = await mkdtemp(path.join(os.tmpdir(), 'jsonl-normalize-'));
+ const filePath = path.join(tmpDir, 'session.jsonl');
+ const original = [
+ assistantEntry('a1', [toolUse('Bash_210')]),
+ userEntry('u1', [toolResult('Bash_210')]),
+ ].join('\n') + '\n';
+ await writeFile(filePath, original, 'utf8');
+
+ const fsMod = await import('node:fs');
+ const renameSpy = vi
+ .spyOn(fsMod.promises, 'rename')
+ .mockImplementation(async () => {
+ const err = new Error('EPERM: operation not permitted') as NodeJS.ErrnoException;
+ err.code = 'EPERM';
+ throw err;
+ });
+
+ try {
+ // rename 全失败:降级路径删除目标后从 .bak 备份恢复 → 不抛错,转录仍在
+ const result = await normalizeClaudeSessionJsonlToolIds(filePath);
+ expect(result.backupPath).toBeDefined();
+ // tmp 被清理
+ expect((await readdir(tmpDir)).filter((f) => f.endsWith('.tmp'))).toHaveLength(0);
+ // 原文件从备份恢复,内容为原文(归一化未生效但转录可被 resume 读取)
+ expect(await readFile(filePath, 'utf8')).toBe(original);
+ } finally {
+ renameSpy.mockRestore();
+ }
+ });
+});
diff --git a/packages/maker-core/src/agents/claude-code/fork-jsonl-repair.ts b/packages/maker-core/src/agents/claude-code/fork-jsonl-repair.ts
index b5a243f5e7..7245d6a1e3 100644
--- a/packages/maker-core/src/agents/claude-code/fork-jsonl-repair.ts
+++ b/packages/maker-core/src/agents/claude-code/fork-jsonl-repair.ts
@@ -34,7 +34,7 @@ export interface CompactMetadataRepair {
removedPreservedMessages: boolean;
}
-function isRecord(value: unknown): value is JsonObject {
+export function isRecord(value: unknown): value is JsonObject {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
@@ -298,12 +298,28 @@ function backupTimestamp(): string {
return new Date().toISOString().replace(/[-:.]/g, '').replace('T', '-').replace('Z', '');
}
-async function createJsonlBackup(filePath: string, original: string): Promise<string> {
+/**
+ * 为会话 jsonl 创建 `.bak.<timestamp>` 备份(写不进就换个后缀重试)。
+ * fork 修复与 jsonl-tool-id-normalize 共用同一份备份语义。
+ */
+export async function createClaudeJsonlBackup(
+ filePath: string,
+ original: string,
+ mode?: number,
+): Promise<string> {
for (let attempt = 0; attempt < 100; attempt += 1) {
const suffix = `${backupTimestamp()}${attempt === 0 ? '' : `-${attempt}`}`;
const backupPath = `${filePath}.bak.${suffix}`;
try {
- await fs.writeFile(backupPath, original, { encoding: 'utf8', flag: 'wx' });
+ // mode 沿用源文件权限(转录可能 0600,备份不应变 0644 暴露给同机用户)。
+ await fs.writeFile(backupPath, original, {
+ encoding: 'utf8',
+ flag: 'wx',
+ ...(mode !== undefined ? { mode } : {}),
+ });
+ // writeFile 的 mode 受进程 umask 影响,创建后 chmod 才能真正还原权限
+ // (codex-connector review: Apply chmod after creating transcript copies)。
+ if (mode !== undefined) await fs.chmod(backupPath, mode).catch(() => undefined);
return backupPath;
} catch (error) {
if (isRecord(error) && error.code === 'EEXIST') continue;
@@ -326,7 +342,9 @@ export async function repairForkedClaudeSessionJsonl(
let backupPath: string | undefined;
if (repaired.changed) {
- backupPath = await createJsonlBackup(filePath, original);
+ // 备份沿用源转录权限: 0600 转录不得被备份成 0644(Copilot review)。
+ const originalMode = (await fs.stat(filePath)).mode & 0o777;
+ backupPath = await createClaudeJsonlBackup(filePath, original, originalMode);
await fs.writeFile(filePath, repaired.text, 'utf8');
}
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index 0a6cd3805c..1fa73c31a5 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -120,6 +120,8 @@ import {
} from '../credential-mode.js';
import { repairForkedClaudeSessionJsonl, type RepairForkedClaudeJsonlResult } from './fork-jsonl-repair.js';
import { ensureClaudeTranscriptInWorkingDir } from './transcript-relocation.js';
+import { findClaudeSessionJsonl } from './claude-projects-fs.js';
+import { normalizeClaudeSessionJsonlToolIds } from './jsonl-tool-id-normalize.js';
import { isClaudeResumeSessionNotFound } from './invalid-resume.js';
import { translateSdkMessage, newRuntimeState, type TurnState, type RuntimeState } from './translator.js';
import type { Effort, PermissionMode } from '../../types/common.js';
@@ -2208,6 +2210,18 @@ export class ClaudeCodeAgent extends BaseAgent {
remoteHostId: opts.remoteHostId,
sessionId: opts.sessionId,
});
+ // 已知覆盖缺口(codex-connector review P1):远端会话的转录在远端 daemon
+ // 磁盘、CLI 流量直连远端 endpoint(remoteEnv.ANTHROPIC_BASE_URL),本地
+ // jsonl 归一化钩子与本地 compat-proxy 响应流改写都拦不到。remote cc 是
+ // MVP(rewind/fork 均 throw,撞车主触发路径在远端不可用),但远端 kimi
+ // 会话一旦撞车(如中断后可见数回落)将无法自愈,持续腐蚀到会话结束。
+ // 修复需扩展 cc-mgr wire protocol + 跨包共享归一化逻辑,列为 follow-up。
+ if (resumeSdkSid) {
+ log.warn(
+ 'claude-code: remote cc session not covered by kimi tool-id normalize/rewrite defenses (transcript on remote daemon, CLI bypasses local proxy); a kimi mint collision on this session cannot self-heal',
+ { remoteHostId: opts.remoteHostId, sessionId: opts.sessionId, resumeSdkSid },
+ );
+ }
// 网关路径(remoteRoute 为 null,即会话有效路由是 XD 网关)才依赖
// runtimeConfig.remoteEndpoint:host 定义了该字段但值为空 = 网关凭据尚未就绪 /
// 已失效,env-builder 会回落到本地 endpoint(下面 loopback guard 虽能拦,但错误
@@ -2643,7 +2657,36 @@ export class ClaudeCodeAgent extends BaseAgent {
resumeSdkSid,
workingDir: opts.workingDir,
});
- } else if (outcome === 'missing') {
+ }
+ // kimi 系 tool_call id 归一化: moonshot 按可见历史铸造 `${name}_${index}`
+ // id, rewind/中断造成的可见数回落会让新铸 id 与历史撞车, CLI 的
+ // ensureToolResultPairing 随即将重复 id 的 tool exchange 整段丢弃并以
+ // "(no content)" 占位 user 消息 —— 模型看到"自己的工具调用被阻止 +
+ // 用户连发空消息"进入空转(2026-07-31 kimi-k3 实测)。转录就位后、spawn
+ // 前做一次幂等归一化(重复 id 去重 + 数字后缀移出铸造空间), 纯 Anthropic
+ // 会话预扫不命中、零解析开销。详见 jsonl-tool-id-normalize.ts 头注。
+ // 'target-key-inexact' 时 relocation 无法定位 CLI 转码目录, 但全局扫描
+ // 找到的最新副本大概率正是 CLI 要读的转录, 归一化它同样是正收益。
+ if (outcome !== 'missing' && resumeSdkSid) {
+ const transcriptFile = await findClaudeSessionJsonl(
+ resumeSdkSid,
+ opts.workingDir,
+ path.join(claudeConfigDir, 'projects'),
+ );
+ if (transcriptFile) {
+ const normalized = await normalizeClaudeSessionJsonlToolIds(transcriptFile);
+ if (normalized.changed) {
+ log.info('resume transcript tool ids normalized', {
+ resumeSdkSid,
+ dedupedBlocks: normalized.dedupedBlockCount,
+ offsetBlocks: normalized.offsetBlockCount,
+ duplicateIds: normalized.duplicateIdCount,
+ backupPath: normalized.backupPath,
+ });
+ }
+ }
+ }
+ if (outcome === 'missing') {
const cleared = await clearInvalidResumeSession(resumeSdkSid, 'transcript_preflight');
if (cleared) {
// 本地 CLI 没有转录就不可能恢复。spawn 前转 fresh,当前用户消息尚未
diff --git a/packages/maker-core/src/agents/claude-code/jsonl-tool-id-normalize.ts b/packages/maker-core/src/agents/claude-code/jsonl-tool-id-normalize.ts
new file mode 100644
index 0000000000..4f421ad39c
--- /dev/null
+++ b/packages/maker-core/src/agents/claude-code/jsonl-tool-id-normalize.ts
@@ -0,0 +1,706 @@
+/**
+ * Claude Code 会话转录(jsonl)的 tool_use id 归一化 —— resume 前修复
+ * kimi 系 tool_call id 与 CLI ensureToolResultPairing 冲突导致的上下文腐蚀。
+ *
+ * 背景(2026-07-31 moonshot/kimi-k3 实测事故,顺藤摸到的完整因果链):
+ * 1. kimi 模型按「当前上下文可见的 tool 调用数」生成递增序号的 tool_call id
+ * (原生 `functions.{name}:{idx}`,经 LiteLLM 清洗为 `${ToolName}_${index}`)。
+ * 2. 会话 rewind / 中断轮被 CLI 投影排除后,可见调用数 < 历史已用 id 上界,
+ * resume 后重铸出**与历史重复**的 id(实测:Bash_210 被铸 9 次、
+ * Bash_212 被铸 27 次)。
+ * 3. CC CLI(2.1.219 起)的 ensureToolResultPairing 用全局 Set 去重:后出现的
+ * 重复 id tool_use 块连同其 tool_result 一起从请求里丢弃;被掏空的 user
+ * 消息以字面量 "(no content)" 占位进请求。模型于是看到自己的工具调用
+ * 「被阻止」、用户不断「发空消息」,进入空转循环(inc-4977 同族)。
+ *
+ * 修复策略(resume/spawn 前对转录做一次性归一化,幂等):
+ * a. 去重:同一 id 的第 N 次出现改写为 `${id}_dup${N}`(后缀对**全量既有 id**
+ * 查占用顺延;tool_result 按「最近未配对的同名 call」位置配对同步改写 ——
+ * 孤儿 call + 重铸 call 并存时,result 属于真实执行的那次,Fable-5 review
+ * 指出的出现序配对张冠李戴由此避免)。
+ * b. 移出铸造空间:所有末段纯数字 id 改写为 `${name}_x${digits}`(占用时追加
+ * x 顺延)。kimi 铸造器只产 `_数字` 后缀,改写后历史 id 与未来新铸 id 永不
+ * 撞车;`_x` 形态不再匹配本规则 → 幂等,二次运行零改写。
+ * 后缀一律查占用的原因(Fable-5 review P1-B/C):转录里可能已存在上一轮
+ * 归一化/proxy 改名的产物(`_x210`/`_dup2`),不查占用会把新改写撞上去,
+ * 「修复本身复发事故」。
+ *
+ * id 对模型与 API 均为不透明字符串,配对关系保持 → 改写不改变会话语义。
+ * 未改动的行保持原始字节(与 fork-jsonl-repair 同约定);改写整文件前先备份,
+ * 写入走 tmp+rename 原子替换(见 normalizeClaudeSessionJsonlToolIds)。
+ */
+
+import { promises as fs } from 'node:fs';
+
+import { createClaudeJsonlBackup, isRecord } from './fork-jsonl-repair.js';
+
+type JsonObject = Record<string, unknown>;
+
+/**
+ * kimi 铸造器形态的 id:末段为纯数字。MCP 工具名带下划线
+ * (`mcp__cindy_memory__call_tool_5`),实测 MCP id 当前为 `call_<random>` 无撞车
+ * 风险,此处按威胁面放宽防御(Fable-5 review P1-E)。
+ */
+const MINTED_ID_RE = /^[A-Za-z][A-Za-z0-9_-]*_(\d+)$/;
+
+/** 廉价预扫:文件里是否存在疑似铸造 id 的 tool_use / tool_result,无命中则跳过全量解析。 */
+const SUSPECT_ID_RE = /"(?:id|tool_use_id)"\s*:\s*"[A-Za-z][A-Za-z0-9_-]*_\d+"/;
+
+export interface NormalizeClaudeJsonlToolIdsResult {
+ /** 归一化后的完整文本(changed=false 时与输入同引用)。 */
+ text: string;
+ changed: boolean;
+ lineCount: number;
+ /** 预扫未命中而跳过时为 true(此时 changed=false,未做解析)。 */
+ skipped: boolean;
+ /** 去重改写的块数(tool_use + tool_result 合计)。 */
+ dedupedBlockCount: number;
+ /** 移出铸造空间改写的块数(tool_use + tool_result 合计)。 */
+ offsetBlockCount: number;
+ /** 参与去重判定的重复 id 个数(诊断用)。 */
+ duplicateIdCount: number;
+ /** 尾部畸形残行被原样保留时为 true(诊断用)。 */
+ keptMalformedTailLine: boolean;
+}
+
+function isToolUseBlock(block: unknown): block is JsonObject & { id: string } {
+ return (
+ isRecord(block) &&
+ block.type === 'tool_use' &&
+ typeof block.id === 'string' &&
+ block.id.length > 0
+ );
+}
+
+function isToolResultBlock(block: unknown): block is JsonObject & { tool_use_id: string } {
+ return (
+ isRecord(block) &&
+ block.type === 'tool_result' &&
+ typeof block.tool_use_id === 'string' &&
+ block.tool_use_id.length > 0
+ );
+}
+
+function messageContentBlocks(entry: JsonObject): JsonObject[] | null {
+ const message = entry.message;
+ if (!isRecord(message)) return null;
+ const content = message.content;
+ if (!Array.isArray(content)) return null;
+ return content as JsonObject[];
+}
+
+function messageRole(entry: JsonObject): unknown {
+ return isRecord(entry.message) ? entry.message.role : undefined;
+}
+
+/** `${id}_dup${k}` 查占用顺延,返回未占用的最小 k ≥ 2 候选。 */
+function freeDupSuffix(id: string, used: ReadonlySet<string>): string {
+ let k = 2;
+ let candidate = `${id}_dup${k}`;
+ while (used.has(candidate)) {
+ k += 1;
+ candidate = `${id}_dup${k}`;
+ }
+ return candidate;
+}
+
+/**
+ * `${name}_x${digits}` 移出铸造空间;目标被占用时追加 x 顺延
+ * (`_xx` / `_xxx` … 均不再匹配铸造规则,保持幂等)。非铸造形态返回 null。
+ */
+function offsetMintedId(id: string, used: ReadonlySet<string>): string | null {
+ const match = MINTED_ID_RE.exec(id);
+ if (!match) return null;
+ const digits = match[1];
+ const name = id.slice(0, id.length - digits.length - 1);
+ let xCount = 1;
+ let candidate = `${name}_${'x'.repeat(xCount)}${digits}`;
+ while (used.has(candidate)) {
+ xCount += 1;
+ candidate = `${name}_${'x'.repeat(xCount)}${digits}`;
+ }
+ return candidate;
+}
+
+/**
+ * 文本级归一化:解析 → 去重(位置配对)→ 移出铸造空间 → 仅重写有改动的行。
+ *
+ * 预扫未命中(纯 Anthropic toolu_* / OpenAI call_<random> 会话)直接返回原文,
+ * 不做 JSON 解析 —— spawn 前路径上对绝大多数会话零成本。
+ *
+ * 畸形行容忍:仅**最后一行**允许解析失败(CLI 崩溃截断尾行是常态,这类会话
+ * 恰恰最需要归一化),原样保留;中间行解析失败仍抛错,由调用方 best-effort
+ * 兜底(放弃归一化也不阻断 resume)。
+ */
+export function normalizeClaudeJsonlToolIdsText(text: string): NormalizeClaudeJsonlToolIdsResult {
+ const hadTrailingNewline = text.endsWith('\n');
+ const rawLines = text.split('\n');
+ if (hadTrailingNewline) rawLines.pop();
+ const lineCount = rawLines.length;
+ if (!SUSPECT_ID_RE.test(text)) {
+ return {
+ text,
+ changed: false,
+ lineCount,
+ skipped: true,
+ dedupedBlockCount: 0,
+ offsetBlockCount: 0,
+ duplicateIdCount: 0,
+ keptMalformedTailLine: false,
+ };
+ }
+ const entries: JsonObject[] = [];
+ let keptMalformedTailLine = false;
+ rawLines.forEach((line, index) => {
+ try {
+ entries.push(JSON.parse(line) as JsonObject);
+ } catch (err) {
+ if (index === rawLines.length - 1) {
+ keptMalformedTailLine = true;
+ entries.push({ __malformedTailLine: line });
+ return;
+ }
+ // 错误信息不含原始行内容: 转录可能含用户粘贴的密钥/敏感信息, 拼进 error
+ // message 会被调用方写入日志, 属数据暴露(Copilot review)。只留行号与长度。
+ throw new Error(
+ `tool id normalize: JSONL parse error at line ${index + 1} (length ${line.length})`,
+ { cause: err },
+ );
+ }
+ });
+
+ // pass 0: 全量既有 id 集合(占用判定的基准;含 tool_result 引用,同一命名空间)。
+ const usedIds = new Set<string>();
+ for (const entry of entries) {
+ for (const block of messageContentBlocks(entry) ?? []) {
+ if (isToolUseBlock(block)) usedIds.add(block.id);
+ else if (isToolResultBlock(block)) usedIds.add(block.tool_use_id);
+ }
+ }
+
+ // pass 1: 定终 id —— 按文件序遍历,call occurrence 依次定终(首现保留原 id
+ // 后偏移;第 N 次 _dupN 查占用),result 与配对 call 共享同一终 id:
+ // - 位置配对:result 配「最近未配对的同名 call」(孤儿 call + 重铸 call 并存
+ // 时,result 属于真实执行的那次,Fable-5 review 指出的出现序配对张冠李戴
+ // 由此避免)。已知盲区(记录备查,均不阻断):同一条 assistant 消息内同 id
+ // 并行调用且 result 按调用序到达时 LIFO 会倒配 —— kimi 自回归铸号在同
+ // 响应内天然递增,该形态需要模型故障,概率远低于它修掉的孤儿场景;
+ // result 先于 call 的文件序倒挂会分叉断配(CC 转录追加序下构造不出)。
+ // - 超编 result(无未配对 call):指向首现 call 的终 id(与 compat-proxy
+ // dedupe 语义一致);全文件无同名 call 时按独立原 id 走偏移。
+ // 占用判定 usedIds = 全量原 id ∪ 已产出终 id;配对 exchange 共享终 id 不算占用。
+ const changedLineIndexes = new Set<number>();
+ let dedupedBlockCount = 0;
+ let offsetBlockCount = 0;
+ let duplicateIdCount = 0;
+ const callSeen = new Map<string, number>();
+ // 提取条目所属 subagent/child 身份(顶层 parentUuid 或 parent_tool_use_id):
+ // 并发 subagent 可能 mint 相同 tool id, result 需按 parent 配对避免 swap
+ // (codex-connector P2: Key subagent tool results by parent)。
+ // 用**原始** parent id 做配对 key: result 行的原始 parent 与对应 child call 的
+ // 原始 parent 相同(即使该 parent 是重铸的 Kimi id, 两个 subagent 都带 Task_1),
+ // 按「同 rawParent 的 FIFO」配对 —— 而不是终 id(终 id 化后 Task_x1 / Task_1_dup2
+ // 反而无法用原始 Task_1 关联), 也不是全局 batch(交错时 lastAssistantBatch 错配)。
+ const parentKeyOf = (entry: JsonObject): string | undefined => {
+ const p = entry.parent_tool_use_id ?? entry.parentUuid;
+ return typeof p === 'string' && p ? p : undefined;
+ };
+ // openCalls[originalId] = 该 id 尚未配对的 call,按出现顺序;每项带所在
+ // assistant 消息 index(batch)与 parent 身份,用于「同批同 parent 内顺序配对」。
+ const openCalls = new Map<string, Array<{ originalId: string; finalId: string; batch: number; parentKey?: string }>>();
+ // 最近一次 assistant 消息的 index —— result 的「同批」= 紧跟的那个 assistant 批。
+ let lastAssistantBatch = -1;
+ const firstFinalByOriginal = new Map<string, string>();
+ // 每个原始 id 按文件序出现的 (行号, 终 id) —— 供 subagent 记录顶层字段做
+ // **行作用域配对**(与 tool_result 同语义): 映射到「本记录之前最近的同名 call」的
+ // 终 id。同一原始 id 重铸多次时, 首个 subagent 记录挂首次调用、后续各挂各自
+ // 最近调用, 而不是全部挂最后一个 duplicate —— 单一 last mapping 会把第一个
+ // subagent 的消息错误挂到后面的 Agent/Task 卡片上(codex-connector review P2)。
+ const occurrenceByOriginal = new Map<string, Array<{ line: number; finalId: string }>>();
+ entries.forEach((entry, index) => {
+ const blocks = messageContentBlocks(entry);
+ if (!blocks) return;
+ const role = messageRole(entry);
+ let lineChanged = false;
+ for (const block of blocks) {
+ if (role === 'assistant' && isToolUseBlock(block)) {
+ lastAssistantBatch = index;
+ const originalId = block.id;
+ const n = (callSeen.get(originalId) ?? 0) + 1;
+ callSeen.set(originalId, n);
+ if (n === 2) duplicateIdCount += 1;
+ let finalId = originalId;
+ if (n >= 2) {
+ finalId = freeDupSuffix(originalId, usedIds);
+ usedIds.add(finalId);
+ block.id = finalId;
+ dedupedBlockCount += 1;
+ lineChanged = true;
+ }
+ const offset = offsetMintedId(finalId, usedIds);
+ if (offset !== null) {
+ usedIds.add(offset);
+ block.id = offset;
+ finalId = offset;
+ offsetBlockCount += 1;
+ lineChanged = true;
+ }
+ if (!firstFinalByOriginal.has(originalId)) firstFinalByOriginal.set(originalId, finalId);
+ let occ = occurrenceByOriginal.get(originalId);
+ if (!occ) {
+ occ = [];
+ occurrenceByOriginal.set(originalId, occ);
+ }
+ occ.push({ line: index, finalId });
+ let stack = openCalls.get(originalId);
+ if (!stack) {
+ stack = [];
+ openCalls.set(originalId, stack);
+ }
+ stack.push({ originalId, finalId, batch: index, parentKey: parentKeyOf(entry) });
+ } else if (role === 'user' && isToolResultBlock(block)) {
+ const originalId = block.tool_use_id;
+ // 配对顺序(同批 FIFO, 跨批 LIFO):
+ // - 同一 assistant 消息内的 parallel calls 同时发出,result 按调用顺序
+ // 回来 → 应配同批内按出现序最前的未配对 call(内容顺序,避免 LIFO
+ // 倒配 swap 输出,codex-connector review P2)。「同批」= 最近一个
+ // assistant 消息(index === lastAssistantBatch)里的 call。
+ // - 跨批(孤儿 call + 重铸 call)时,重铸 call 在孤儿之后,result 属于
+ // 最近发出的那个 → 配数组尾部(最近)。先找同批最前,找不到回退最近。
+ const stack = openCalls.get(originalId);
+ let matched: { originalId: string; finalId: string; batch: number; parentKey?: string } | undefined;
+ if (stack) {
+ // 优先配「同 rawParent 的 FIFO」: 并发 subagent mint 相同 tool id 时, result
+ // 属于哪个 subagent 由 parent 身份决定 —— 用原始 parent id 分组, 组内按
+ // 出现序 FIFO 配对(第一个 result 配第一个同 parent 调用)。
+ // 不能用全局 lastAssistantBatch(交错时 A 的 assistant 行被 B 顶掉, A 的
+ // result 错配给 B), 也不能用终 id 化 parent(同原始 Task_1 归一化后变成
+ // Task_x1 / Task_1_dup2, 无法用原始 Task_1 关联回)。
+ // (codex-connector P2: Key subagent tool results by parent / Use normalized
+ // parent IDs)。
+ // **同批 FIFO, 跨批取最新**: 并发 subagent 的同批 parallel calls 按出现序
+ // FIFO(各配各次); 孤儿 + 重铸(跨批)时 result 属于**最新 retry**(重铸 call),
+ // 而非最早的孤儿 —— 恒取 sameParent[0] 会把 result 改写为 stale 孤儿 id,
+ // 真实重铸 call 反而失配(codex-connector P1: Keep same-parent orphan
+ // retries on the newest call)。同批判断用「最近 assistant 批」(即该 result
+ // 紧跟的 child 批)。
+ const resultParent = parentKeyOf(entry);
+ const sameParent = resultParent !== undefined
+ ? stack.filter((c) => c.parentKey === resultParent)
+ : stack;
+ const candidates = sameParent.length > 0 ? sameParent : stack;
+ if (resultParent !== undefined && sameParent.length > 0) {
+ const sameBatch = sameParent.filter((c) => c.batch === lastAssistantBatch);
+ matched = sameBatch.length > 0 ? sameBatch[0] : sameParent[sameParent.length - 1];
+ } else {
+ const batchMatch = candidates.find((c) => c.batch === lastAssistantBatch);
+ matched = batchMatch ?? candidates[candidates.length - 1];
+ }
+ stack.splice(stack.indexOf(matched), 1);
+ }
+ const inherited = matched?.finalId ?? firstFinalByOriginal.get(originalId);
+ if (inherited !== undefined) {
+ if (inherited !== originalId) {
+ block.tool_use_id = inherited;
+ if (matched && matched.finalId !== matched.originalId && matched.finalId.includes('_dup')) {
+ dedupedBlockCount += 1;
+ } else {
+ offsetBlockCount += 1;
+ }
+ lineChanged = true;
+ }
+ } else {
+ // 全文件无同名 call 的孤儿 result:按独立原 id 走铸造空间偏移。
+ const offset = offsetMintedId(originalId, usedIds);
+ if (offset !== null) {
+ usedIds.add(offset);
+ block.tool_use_id = offset;
+ offsetBlockCount += 1;
+ lineChanged = true;
+ }
+ }
+ }
+ }
+ if (lineChanged) changedLineIndexes.add(index);
+ });
+
+ // 顶层引用字段跟随 tool_use 改名: Claude subagent/task-notification 条目在顶层带
+ // parent_tool_use_id / tool_use_id 引用父 agent 的调用 id(translator 用它们作
+ // parentToolUseId 挂载);tool_use_summary 条目在顶层带 preceding_tool_use_ids 数组
+ // (translator 转发为 tool_result.data.toolUseIds)。归一化改名后必须同步, 否则
+ // 关联断裂 / summary 挂不上归一化后的卡片。
+ //
+ // 配对必须**按行作用域 + 同行 FIFO + 同 child 复用**: 每个引用记录指向「它所在位置
+ // 之前最近的同名 call」的终 id —— 同一原始 id 重铸多次时, 第 N 个 subagent/summary 挂
+ // 第 N 次调用, 而非全部挂最后一个 duplicate(单一 last mapping 会把首个记录错误挂到
+ // 后面的卡片上, codex-connector P2)。同一 assistant 行内同 id 并行调用(同行多
+ // occurrence)时, 多条子记录按**内容顺序**各挂各次调用, 与 tool_result 的同批 FIFO
+ // 配对一致(否则同行块被折叠成单一 latest line mapping, 首个子记录错挂到块内最后一个
+ // 调用)。**同一 child(共享 uuid)的多条 stream_event 记录必须复用首次解析的终 id**,
+ // 不按条推进 occPtr —— 否则同一条 subagent 流的每条事件都会消费一个 occurrence,
+ // 把同一个 subagent 拆散到多张 Agent/Task 卡片(codex-connector P2: Keep repeated
+ // subagent events on one occurrence)。
+ if (occurrenceByOriginal.size > 0) {
+ // occPtr[id] = 已消费到 occurrenceByOriginal[id] 的哪个下标。初始 -1。
+ const occPtr = new Map<string, number>();
+ // childRef[childKey][origId] = 该 child 首次解析出的终 id。同一 child 的多条
+ // 记录(共享 child 身份)引用同一 parent id 时全部复用, 不再推进 occPtr。
+ // child 身份: stream_event 用 uuid; task_started/task_progress/task_notification
+ // 等 task 记录用 task_id(通常无 uuid, translator 以 task_id 为 child 标识,
+ // codex-connector P2: Reuse task_id when remapping task records)。用前缀区分
+ // 两类命名空间, 避免 uuid 与 task_id 值相同串扰。
+ const childRef = new Map<string, Map<string, string>>();
+ // 提取记录所属 child 身份(无 child 身份时返回 undefined → 走独立逐条解析)。
+ // task 记录(task_started/progress/notification)的稳定标识是 task_id, per-row 的
+ // uuid 只是临时记录 id —— 若 uuid 优先, 同一 task 的多条记录(uuid 各不相同)
+ // 不共享 task 级映射, 各自消费下一个 duplicate occurrence, 把单个 task 拆散到
+ // 多张 Agent/Task 卡片。task_id 存在时优先, uuid 仅作 fallback
+ // (codex-connector P2: Prefer task IDs before per-row UUIDs)。
+ const childKeyOf = (entry: JsonObject): string | undefined => {
+ if (typeof entry.task_id === 'string' && entry.task_id) return `task:${entry.task_id}`;
+ if (typeof entry.uuid === 'string' && entry.uuid) return `uuid:${entry.uuid}`;
+ return undefined;
+ };
+ // 单个原始 id → 终 id 的行作用域解析。推进规则:
+ // - 同行块内继续(当前 ptr 所在块行 < index 且块内还有下一个): 消费下一个
+ // (FIFO —— 同一条 assistant 消息内同 id 并行调用, 多条子记录按内容顺序);
+ // - 否则: 跳到「最近的行 < index 的块」的**块首**(块内按出现序, 首个即内容
+ // 顺序第一个)。跨行(重铸在更早的行)整体跳过, 引用取最近那次调用。
+ // 该行之前无同名 call 时返回 undefined。
+ const resolveOccurrence = (val: string, index: number): string | undefined => {
+ const occs = occurrenceByOriginal.get(val);
+ if (!occs || occs.length === 0) return undefined;
+ let ptr = occPtr.get(val) ?? -1;
+ if (
+ ptr >= 0 &&
+ ptr + 1 < occs.length &&
+ occs[ptr].line === occs[ptr + 1].line &&
+ occs[ptr + 1].line < index
+ ) {
+ ptr += 1;
+ } else {
+ let next = ptr + 1;
+ while (next < occs.length && occs[next].line < index) {
+ ptr = next; // 块首(内容顺序第一个)
+ while (next + 1 < occs.length && occs[next + 1].line === occs[next].line) next += 1;
+ next += 1;
+ }
+ }
+ occPtr.set(val, ptr);
+ return ptr < 0 ? undefined : occs[ptr].finalId;
+ };
+ // 前瞻解析(content_block_start 专用): 匹配**即将出现**的 tool call —— SDK 允许
+ // stream_event 先于 assistant 消息到达(handleStreamEvent 显式支持该顺序), 后顾
+ // 解析在此顺序下找不到 occurrence、id 保持旧值, 与后续归一化的 assistant/
+ // tool_result 指向不一致(codex-connector P2: Handle stream events before
+ // assistant rows)。
+ // **按内容顺序 FIFO 消费**: 两个重复的 content_block_start(同 id)先于 assistant
+ // 时, 若都取第一个 future occurrence, 两条 stream start 都指向首个调用, 而
+ // assistant/tool_result 把 duplicate 分配到 Bash_x5 + Bash_5_dup2 —— 第二个
+ // tool card 会以错 id 创建/更新。aheadPtr 按 val 记录前瞻已消费到的下标, 每条
+ // content_block_start 取「上一个已消费之后、line >= index 的第一个」occurrence。
+ // 无前瞻命中(stream_event 记录在 assistant 之后)时, fallback **同样按内容顺序**
+ // 消费**之前**的 occurrence —— 而不是总返回最后一个: 两个重复 start 落在
+ // assistant 行之后时, 第一条应指向首个调用(Bash_x5), 第二条指向第二个
+ // (Bash_5_dup2), 都返回最后一个会让首张 tool card 以错 id 创建/更新
+ // (codex-connector P2: Consume post-assistant stream starts by occurrence)。
+ // fallback 超出 occurrence 数(stream start 数 > 调用数, 异常)时取最后一个兜底。
+ const aheadPtr = new Map<string, number>();
+ const resolveAhead = (val: string, index: number): string | undefined => {
+ const occs = occurrenceByOriginal.get(val);
+ if (!occs || occs.length === 0) return undefined;
+ const start = (aheadPtr.get(val) ?? -1) + 1;
+ for (let i = start; i < occs.length; i += 1) {
+ if (occs[i].line >= index) {
+ aheadPtr.set(val, i);
+ return occs[i].finalId;
+ }
+ }
+ // 无 future occurrence: fallback 按内容顺序消费之前未消费的 occurrence。
+ if (start < occs.length) {
+ aheadPtr.set(val, start);
+ return occs[start].finalId;
+ }
+ return occs[occs.length - 1].finalId;
+ };
+ // 带 parent 的 content_block_start 专用: 匹配「最近的 future occurrence」——
+ // 父 Agent/Task 与子 tool 同原始 id 时, 子调用通常是更晚的 future(父先出现),
+ // content_block_start 应指向子; 单 occurrence 时匹配唯一。无 future(assistant 后
+ // 的 child start)时 fallback 最近之前 —— 子 occurrence 仍在父之后, 命中子而非父
+ // (codex-connector P1: Map post-assistant stream starts to the child occurrence)。
+ // 不推进 aheadPtr(不与其他无 parent 的 start FIFO 共享)。
+ const resolveLastFuture = (val: string, index: number): string | undefined => {
+ const occs = occurrenceByOriginal.get(val);
+ if (!occs || occs.length === 0) return undefined;
+ // 带 parent 的 content_block_start 描述子/新调用: 匹配**最后一个** line >= index
+ // 的 future occurrence(父 Agent/Task 与子 tool 同 id 时, 子调用是更晚的 future,
+ // 取最后一个而非最近的那个 —— 「Resolve nested」场景 line 0 的 start 应匹配
+ // 子 Task_1_dup2 而非父 Task_x1)。扫全量 future(不是遇到 line < index 就 break,
+ // 否则等价于总取 occs 末尾, 把较早的 start 错挂到更晚的重铸调用,
+ // copilot P1-A / codex-connector P1: Map child stream starts to the nearest
+ // occurrence)。
+ let lastFuture: { line: number; finalId: string } | undefined;
+ for (let i = 0; i < occs.length; i += 1) {
+ if (occs[i].line >= index) lastFuture = occs[i];
+ }
+ if (lastFuture) return lastFuture.finalId;
+ // 无 future(assistant 后的 child start): 取最近的过去 —— 最后一个 line < index
+ // 的 occurrence(子 occurrence 仍在父之后, 命中子而非父)。
+ return occs[occs.length - 1].finalId;
+ };
+ // 带 child 身份(顶层 uuid / task_id)的记录: 同一 child 复用已解析终 id(首次解析
+ // 后缓存), 不按条消费 occurrence —— 同一条 subagent 流 / task 的后续事件不会被
+ // 重映射到下一个 occurrence 拆散。
+ // 解析顺序: **后顾优先**(引用「之前最近的同名 call」)。标量 parent_tool_use_id /
+ // tool_use_id 引用**已启动的父 Agent/Task 调用** —— subagent/task 记录出现在其父
+ // 调用之后, 后顾语义正确(如两个并行 Agent/Task 调用, subagent-1 挂首次、subagent-2
+ // 挂重铸)。前瞻优先会把这些「引用已完成调用」的记录错配到未来的重铸调用。
+ // content_block_start 的 id 才是「预告未来 tool card」, 独立走 resolveAhead(前瞻)。
+ // 后顾 miss(记录先于一切同名调用)时 fallback 前瞻, 覆盖重铸新 child 先于其
+ // assistant 的场景。
+ const resolveForEntry = (entry: JsonObject, val: string, index: number): string | undefined => {
+ const key = childKeyOf(entry);
+ if (key !== undefined) {
+ let m = childRef.get(key);
+ if (m) {
+ const cached = m.get(val);
+ if (cached !== undefined) return cached;
+ }
+ const mapped = resolveOccurrence(val, index) ?? resolveAhead(val, index);
+ if (mapped !== undefined) {
+ if (!m) {
+ m = new Map();
+ childRef.set(key, m);
+ }
+ m.set(val, mapped);
+ }
+ return mapped;
+ }
+ return resolveOccurrence(val, index) ?? resolveAhead(val, index);
+ };
+ // summary 数组独立游标: preceding_tool_use_ids 的每一项映射到「该 summary 行之前
+ // 的 occurrences 的**尾部**」 —— 数组长度 N 覆盖最近 N 个调用(内容顺序)。
+ // **不共享 occPtr / aheadPtr / childRef**: 标量/child 字段的改写会推进共享指针,
+ // 若数组项用同一 occPtr, 前面 child 记录先消费后, 数组起点错位 —— 如
+ // ['Task_1','Task_1'] 在 task/stream 行之后会归一化成 ['Task_1_dup2','Task_1_dup2']
+ // 而非 [首个, 第二个], 挂错 tool card(codex-connector P2: Keep summary occurrence
+ // cursors independent)。
+ // **尾部映射而非全局计数**: 只总结第二个调用时, 单个 summary item ['Bash_5'] 应
+ // 指向最近那个调用(Bash_5_dup2)而非全局计数从 occurrence 0 开始指向首个 ——
+ // summary 覆盖「实际产生 summary 的最近 N 个调用」(codex-connector P2: Map summary
+ // IDs from the summary row)。
+ const resolveSummaryItems = (arr: unknown[], index: number): Array<string | undefined> => {
+ // 统计数组内每个 id 的出现次数 —— 决定该 id 在 eligible 中的尾部偏移。
+ const arrCount = new Map<string, number>();
+ for (const item of arr) {
+ if (typeof item !== 'string') continue;
+ arrCount.set(item, (arrCount.get(item) ?? 0) + 1);
+ }
+ const consumed = new Map<string, number>();
+ const out: Array<string | undefined> = [];
+ for (const item of arr) {
+ if (typeof item !== 'string') {
+ out.push(undefined);
+ continue;
+ }
+ const occs = occurrenceByOriginal.get(item);
+ if (!occs || occs.length === 0) {
+ out.push(undefined);
+ continue;
+ }
+ // 行作用域: 只取该行之前的同名 occurrences。
+ const eligible = occs.filter((o) => o.line < index);
+ if (eligible.length === 0) {
+ out.push(undefined);
+ continue;
+ }
+ const totalForId = arrCount.get(item) ?? 0;
+ const k = consumed.get(item) ?? 0;
+ consumed.set(item, k + 1);
+ const offset = eligible.length - totalForId; // 尾部偏移: 覆盖最近 totalForId 个
+ const idx = offset + k;
+ out.push(idx >= 0 && idx < eligible.length ? eligible[idx].finalId : eligible[eligible.length - 1].finalId);
+ }
+ return out;
+ };
+ entries.forEach((entry, index) => {
+ let entryChanged = false;
+ // entry 级缓存: 同一条记录内多个字段引用同一 id 时共享解析结果 —— 否则标量
+ // (parent_tool_use_id / tool_use_id)与嵌套 content_block.id 各自消费前瞻/后顾
+ // 指针, 同 id 可能映射到不同终 id, 一条 stream_event 内 self-inconsistent
+ // (codex-connector P1 引出的协调)。
+ const entryRef = new Map<string, string>();
+ const resolveField = (val: string): string | undefined => {
+ const cached = entryRef.get(val);
+ if (cached !== undefined) return cached;
+ const mapped = resolveForEntry(entry, val, index);
+ if (mapped !== undefined) entryRef.set(val, mapped);
+ return mapped;
+ };
+ for (const field of ['parent_tool_use_id', 'tool_use_id'] as const) {
+ const val = entry[field];
+ if (typeof val !== 'string') continue;
+ const mapped = resolveField(val);
+ if (mapped !== undefined && mapped !== val) {
+ entry[field] = mapped;
+ entryChanged = true;
+ }
+ }
+ // tool_use_summary 的 preceding_tool_use_ids 数组: 逐项按调用顺序消费 occurrence。
+ // 数组项**绕过 entryRef / childRef 缓存**: 每一项对应一个独立的 tool call,
+ // 同一 id 重复出现是两个重复调用, 需各自消费 occurrence —— 若走 resolveField,
+ // 同 entry 内同 id 的缓存会让 ['Bash_5','Bash_5'] 变成 ['Bash_x5','Bash_x5'],
+ // 而不是消费第二个 occurrence 得 Bash_5_dup2, resume/import 把第二个 summary
+ // 挂到错误的 tool card 上(codex-connector P2: Resolve repeated summary IDs
+ // independently)。用独立游标 resolveSummaryItem(见上), 不受标量/child 改写的
+ // 共享 occPtr 污染(codex-connector P2: Keep summary occurrence cursors
+ // independent)。
+ const arr = entry.preceding_tool_use_ids;
+ if (Array.isArray(arr) && arr.length > 0) {
+ const mappedItems = resolveSummaryItems(arr, index);
+ for (let i = 0; i < arr.length; i += 1) {
+ const mapped = mappedItems[i];
+ const item = arr[i];
+ if (typeof item !== 'string' || mapped === undefined || mapped === item) continue;
+ arr[i] = mapped;
+ entryChanged = true;
+ }
+ }
+ // stream_event 的 event.content_block.id(content_block_start 的 tool_use)也要
+ // 改写: handleStreamEvent 用它驱动 tool-use start / tool-name 状态, replay/import
+ // 会以旧 id 发 tool card, 与归一化后的 tool_result / summary 指向不一致
+ // (codex-connector P2: Rewrite stream-event tool IDs too)。
+ // **独立解析, 绕过 entryRef**: content_block.id 是「当前正在流的 tool 调用」,
+ // 与顶层 parent_tool_use_id(父 agent 调用)语义不同 —— 即使字符串相同
+ // (如父 Task_1 与子自己启动的首个 Task_1), 也指向不同 occurrence。若走
+ // resolveField, 父的映射被缓存后嵌套复用, replay/import 把子 tool 挂到父 id 下
+ // (codex-connector P1: Resolve nested stream IDs independently)。
+ // **归属区分**: 带顶层 parent_tool_use_id 的 content_block_start 属于某 child,
+ // 走 resolveForEntry(后顾优先, 匹配该 child 的最近 occurrence —— 即使 start 落
+ // 在 child assistant 之后, fallback 也命中子 occurrence 而非父 occurrence,
+ // codex-connector P1: Map post-assistant stream starts to the child occurrence);
+ // 不带 parent 的主流程 tool 预告走 resolveAhead(前瞻, 匹配即将出现的调用,
+ // codex-connector P2: Map pre-assistant duplicate stream IDs forward)。
+ const evt = entry.event;
+ if (isRecord(evt) && evt.type === 'content_block_start') {
+ const cb = evt.content_block;
+ if (isRecord(cb) && cb.type === 'tool_use' && typeof cb.id === 'string' && cb.id.length > 0) {
+ const mapped = typeof entry.parent_tool_use_id === 'string' && entry.parent_tool_use_id
+ ? resolveLastFuture(cb.id, index)
+ : resolveAhead(cb.id, index);
+ if (mapped !== undefined && mapped !== cb.id) {
+ cb.id = mapped;
+ entryChanged = true;
+ }
+ }
+ }
+ if (entryChanged) changedLineIndexes.add(index);
+ });
+ }
+
+ const changed = changedLineIndexes.size > 0;
+ const nextText = changed
+ ? `${entries
+ .map((entry, index) => (changedLineIndexes.has(index) ? JSON.stringify(entry) : rawLines[index]))
+ .join('\n')}${hadTrailingNewline ? '\n' : ''}`
+ : text;
+
+ return {
+ text: nextText,
+ changed,
+ lineCount: entries.length,
+ skipped: false,
+ dedupedBlockCount,
+ offsetBlockCount,
+ duplicateIdCount,
+ keptMalformedTailLine,
+ };
+}
+
+export interface NormalizeClaudeSessionJsonlToolIdsResult
+ extends Omit<NormalizeClaudeJsonlToolIdsResult, 'text'> {
+ filePath: string;
+ backupPath?: string;
+}
+
+/**
+ * 文件级归一化:有改动时先备份(`.bak.<timestamp>`)再 tmp+rename 原子替换;
+ * 无改动 / 预扫跳过时不触碰文件(连备份也不留)。
+ */
+export async function normalizeClaudeSessionJsonlToolIds(
+ filePath: string,
+): Promise<NormalizeClaudeSessionJsonlToolIdsResult> {
+ const original = await fs.readFile(filePath, 'utf8');
+ const normalized = normalizeClaudeJsonlToolIdsText(original);
+ let backupPath: string | undefined;
+ // rename 降级失败时从 .bak 备份恢复成功 → 归一化未生效但转录仍在(见下)。
+ let recoveredFromBackup = false;
+ if (normalized.changed) {
+ // 保留原文件权限:转录可能含用户敏感内容,若原文件是 0600,重写后(tmp 默认
+ // 0666 & umask)会把提示词/工具输出/粘贴的密钥暴露给同机其它用户
+ // (codex-connector review: Preserve transcript file permissions)。stat 拿到
+ // 原 mode 应用到 tmp;createClaudeJsonlBackup 生成的 .bak 也沿用。
+ // writeFile 的 mode 受进程 umask 影响,创建后必须再 chmod 一次才能真正
+ // 还原权限(codex-connector review: Apply chmod after creating transcript
+ // copies —— 否则更严格的 umask 会让重写文件比原文件更严格)。
+ const originalMode = (await fs.stat(filePath)).mode & 0o777;
+ backupPath = await createClaudeJsonlBackup(filePath, original, originalMode);
+ // tmp+rename 原子替换:写一半崩溃不会留下半截转录(备份仍在,tmp 残留无害)。
+ // Windows 上 rename 覆盖已存在目标的行为依文件系统而异(exFAT 等个别系统抛
+ // EEXIST/EPERM,仓内 blobStore.ts:130 有同源注释);若 rename 失败,降级为
+ // 「删除旧文件再 rename」——.bak 备份已就位,失败也可回滚,尽量让归一化生效
+ // (copilot review)。降级也失败才抛错,由调用方 best-effort 兜底继续 resume。
+ const tmpPath = `${filePath}.normalize-${process.pid}-${Math.random().toString(36).slice(2, 10)}.tmp`;
+ await fs.writeFile(tmpPath, normalized.text, { encoding: 'utf8', mode: originalMode });
+ await fs.chmod(tmpPath, originalMode).catch(() => undefined);
+ try {
+ await fs.rename(tmpPath, filePath);
+ } catch (renameErr) {
+ // 目标已存在且 rename 拒绝覆盖:先删除目标再重试(有 .bak 兜底)。降级再失败
+ // 时,先把原内容写回 file(删除目标可能已让原文件消失 —— 绝不能让归一化
+ // 把 resume 需要的转录弄丢,宁可不生效也要保持原文件可用),tmp 清理后抛错
+ // 由调用方 best-effort 兜底继续(copilot review)。
+ const code = (renameErr as NodeJS.ErrnoException)?.code;
+ if (code === 'EEXIST' || code === 'EPERM' || code === 'EACCES') {
+ try {
+ await fs.rm(filePath, { force: true });
+ await fs.rename(tmpPath, filePath);
+ } catch (fallbackErr) {
+ // writeFile 写回失败不能静默吞掉 —— 原文件已被删除、转录缺失会阻断
+ // resume。备份 .bak 已就位:优先从备份恢复(copyFile),保证 filePath 仍可
+ // 被 resume 读取(copilot review);备份恢复也失败时,保留 writeFile 尝试
+ // 并暴露 fallbackErr(调用方 best-effort 兜底继续)。
+ await fs.rm(tmpPath, { force: true }).catch(() => undefined);
+ if (backupPath) {
+ try {
+ await fs.copyFile(backupPath, filePath);
+ await fs.chmod(filePath, originalMode).catch(() => undefined);
+ recoveredFromBackup = true; // 备份恢复成功 → 归一化未生效但转录仍在
+ } catch {
+ // 备份恢复失败:落 writeFile 兜底(也失败则抛 fallbackErr)。
+ }
+ }
+ if (!recoveredFromBackup) {
+ await fs
+ .writeFile(filePath, original, { encoding: 'utf8', mode: originalMode })
+ .catch(() => undefined);
+ await fs.chmod(filePath, originalMode).catch(() => undefined);
+ throw fallbackErr;
+ }
+ }
+ } else {
+ await fs.rm(tmpPath, { force: true }).catch(() => undefined);
+ throw renameErr;
+ }
+ }
+ }
+ if (recoveredFromBackup) {
+ // 归一化未生效(rename 降级失败,从备份恢复原文):复用 normalized 的全部统计
+ // 字段, 仅把 changed 覆盖为 false —— 不误导调用方以为已归一化, 也满足返回
+ // 类型的必填字段(lineCount / skipped / dedupedBlockCount 等, copilot review)。
+ const { text: _, ...rest } = normalized;
+ return { filePath, ...rest, changed: false, ...(backupPath ? { backupPath } : {}) };
+ }
+ const { text: _, ...rest } = normalized;
+ return { filePath, ...rest, ...(backupPath ? { backupPath } : {}) };
+}