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(maker-core): codex 内部 citation 标记归一化为可读文件路径 (#839)

fico-hub8442e8cc7fae
diff --git a/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts b/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts
index 5bb9831d36..e13ca427e8 100644
--- a/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts
+++ b/apps/desktop/src/main/__tests__/codexLocalSessions.test.ts
@@ -1025,6 +1025,96 @@ describe('importExternalCodexMessagesForSession', () => {
expect(rows.map((r) => JSON.parse(r.content))).toEqual(['first', 'third']);
});
+ it('normalizes codex file citations in imported assistant messages (#785)', async () => {
+ const dbPath = createStateDb(externalHome);
+ const rolloutPath = path.join(externalHome, 'sessions', `rollout-2026-05-13-${threadId}.jsonl`);
+ fs.mkdirSync(path.dirname(rolloutPath), { recursive: true });
+ fs.writeFileSync(
+ rolloutPath,
+ [
+ rolloutLine('m1', 'user', 'save it', '2026-05-13T00:00:01.000Z'),
+ rolloutLine(
+ 'm2',
+ 'assistant',
+ '已保存::codex-file-citation{path="/tmp/报告.docx" purpose="output"},请查收。',
+ '2026-05-13T00:00:02.000Z',
+ ),
+ '',
+ ].join('\n'),
+ );
+ insertThread(dbPath, threadId, rolloutPath, { updatedAt: 1_000 });
+
+ currentTestDb()
+ .prepare(
+ `
+ INSERT INTO sessions (
+ id, title, working_dir, model, effort, permission_mode, status,
+ sdk_session_id, total_token_usage, total_cost_usd, context_tokens,
+ context_window, fast_mode, cleared_at, pinned_at, user_send_at,
+ agent_kind, parent_session_id, forked_at_message_id, worktree_path,
+ source, feishu_open_id, feishu_bot_app_id, used_project_context,
+ extra_dirs, created_at, updated_at
+ )
+ VALUES (
+ ?, 'Imported', '/tmp/project', 'gpt-5.5', 'high', 'ask', 'active',
+ ?, 0, 0, 0, 0, 0, NULL, NULL, 1,
+ 'codex', NULL, NULL, NULL, 'desktop', NULL, NULL, 0, '[]', 1, 1
+ )
+ `,
+ )
+ .run(`codex-${threadId}`, threadId);
+
+ await importExternalCodexMessagesForSession(`codex-${threadId}`);
+
+ const rows = currentTestDb()
+ .prepare('SELECT role, content FROM messages ORDER BY id')
+ .all() as Array<{ role: string; content: string }>;
+ // 导入路径与流式路径同口径:入库的 assistant 正文不含内部 citation 语法。
+ expect(rows.map((r) => r.role)).toEqual(['user', 'assistant']);
+ expect(JSON.parse(rows[1].content)).toBe('已保存:`/tmp/报告.docx`,请查收。');
+ });
+
+ it('strips unfinished citation tails from imported assistant messages (#785 review 反馈)', async () => {
+ const dbPath = createStateDb(externalHome);
+ const rolloutPath = path.join(externalHome, 'sessions', `rollout-2026-05-13-${threadId}.jsonl`);
+ fs.mkdirSync(path.dirname(rolloutPath), { recursive: true });
+ // 生成中断的会话:assistant 正文停在标记中间(rollout 里就是这样存的)。
+ fs.writeFileSync(
+ rolloutPath,
+ `${rolloutLine('m1', 'assistant', '结果在 :codex-file-citation{path="/tmp/x', '2026-05-13T00:00:01.000Z')}\n`,
+ );
+ insertThread(dbPath, threadId, rolloutPath, { updatedAt: 1_000 });
+
+ currentTestDb()
+ .prepare(
+ `
+ INSERT INTO sessions (
+ id, title, working_dir, model, effort, permission_mode, status,
+ sdk_session_id, total_token_usage, total_cost_usd, context_tokens,
+ context_window, fast_mode, cleared_at, pinned_at, user_send_at,
+ agent_kind, parent_session_id, forked_at_message_id, worktree_path,
+ source, feishu_open_id, feishu_bot_app_id, used_project_context,
+ extra_dirs, created_at, updated_at
+ )
+ VALUES (
+ ?, 'Imported', '/tmp/project', 'gpt-5.5', 'high', 'ask', 'active',
+ ?, 0, 0, 0, 0, 0, NULL, NULL, 1,
+ 'codex', NULL, NULL, NULL, 'desktop', NULL, NULL, 0, '[]', 1, 1
+ )
+ `,
+ )
+ .run(`codex-${threadId}`, threadId);
+
+ await importExternalCodexMessagesForSession(`codex-${threadId}`);
+
+ const rows = currentTestDb()
+ .prepare('SELECT role, content FROM messages ORDER BY id')
+ .all() as Array<{ role: string; content: string }>;
+ // 与流式 completed 同口径:确定的截断残尾从入库文本剥掉,不漏内部语法。
+ expect(rows).toHaveLength(1);
+ expect(JSON.parse(rows[0].content)).toBe('结果在');
+ });
+
it('keeps importing linked Codex rollout messages after local app messages without duplicating them', async () => {
const dbPath = createStateDb(externalHome);
const rolloutPath = path.join(externalHome, 'sessions', `rollout-2026-05-13-${threadId}.jsonl`);
diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
index a930cd8a80..13cbeeba5f 100644
--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
@@ -1198,11 +1198,69 @@ function readExistingMessageFingerprints(readyDb, sessionId, importClientIdPrefi
function isLikelyLocalDuplicate(existing, row) {
const next = messageFingerprint(row.role, row.text, row.createdAt);
- return existing.some((prev) => prev.role === next.role && prev.text === next.text && Math.abs(prev.createdAt - next.createdAt) <= LOCAL_DUPLICATE_WINDOW_MS);
+ // 普通消息原文精确比较;canon 有损比较只在「至少一侧含原始标记字面量」时启用
+ // (升级前旧标记行 vs 已归一化导入行),避免仅 Markdown 格式不同的正常回复被
+ // 误判成重复。口径同 opHandlers/tx.ts。
+ return existing.some((prev) => prev.role === next.role
+ && Math.abs(prev.createdAt - next.createdAt) <= LOCAL_DUPLICATE_WINDOW_MS
+ && (prev.plain === next.plain
+ || (prev.canonical !== undefined && next.canonical !== undefined
+ && (prev.hasMarker || next.hasMarker)
+ && prev.canonical === next.canonical)));
}
function messageFingerprint(role, text, createdAt) {
- return { role, text: normalizeFingerprintText(text), createdAt };
+ const plain = normalizeFingerprintText(text);
+ const hasMarker = role === 'assistant' && text.includes(CODEX_CITATION_OPEN);
+ const canonical = role === 'assistant'
+ ? normalizeFingerprintText(canonicalizeCodexCitations(text))
+ : undefined;
+ const out = { role, plain, hasMarker, createdAt };
+ if (canonical !== undefined) out.canonical = canonical;
+ return out;
+}
+
+// 与 opHandlers/tx.ts 的指纹规范形同构;SSoT 注释见该文件,口径变更需同步。
+const CODEX_CITATION_RE = /:codex-file-citation\\{((?:[^"{}]|"(?:[^"\\\\]|\\\\.)*")*)\\}/g;
+const CODEX_CITATION_OPEN = ':codex-file-citation{';
+
+function codexCitationClose(text, attrsStart) {
+ let inQuote = false;
+ for (let i = attrsStart; i < text.length; i += 1) {
+ const ch = text[i];
+ if (inQuote && ch === '\\\\') i += 1;
+ else if (ch === '"') inQuote = !inQuote;
+ else if (!inQuote && ch === '}') return i;
+ else if (!inQuote && ch === '{') return -2;
+ }
+ return -1;
+}
+
+function decodeCitationPathForFingerprint(attrs) {
+ const m = /(?:^|\\s)path="((?:[^"\\\\]|\\\\.)*)"/.exec(attrs);
+ if (!m) return '';
+ const raw = m[1];
+ const nativeUnc = raw.startsWith('\\\\\\\\') && raw[2] !== '\\\\';
+ const head = nativeUnc ? '\\\\\\\\' : '';
+ return head + (nativeUnc ? raw.slice(2) : raw).replace(/\\\\([\\\\"])/g, '$1');
+}
+
+function canonicalizeCodexCitations(text) {
+ let out = text;
+ let from = 0;
+ for (;;) {
+ const open = out.indexOf(CODEX_CITATION_OPEN, from);
+ if (open === -1) break;
+ const close = codexCitationClose(out, open + CODEX_CITATION_OPEN.length);
+ if (close === -1) { out = out.slice(0, open); break; }
+ from = close === -2 ? open + CODEX_CITATION_OPEN.length : close + 1;
+ }
+ for (let i = 0; i < 5; i += 1) {
+ const next = out.replace(CODEX_CITATION_RE, (_all, attrs) => decodeCitationPathForFingerprint(attrs));
+ if (next === out) break;
+ out = next;
+ }
+ return out.replace(/\`+/g, '').replace(/\\s+/g, ' ');
}
function normalizeStoredMessageText(raw) {
diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
index 58673d3d33..11f7d2214b 100644
--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
@@ -195,6 +195,152 @@ describe('db worker tx handlers', () => {
});
});
+ it('codex.importMessages dedupes pre-upgrade local rows that still carry raw citation markers', async () => {
+ await withClient(async (client) => {
+ await seedSession(client, 's1');
+ // 升级前经流式路径落库的本地 assistant 行:正文仍是原始 citation 标记。
+ await client.exec(
+ 'INSERT INTO messages (id, client_id, session_id, role, content, created_at) VALUES (?, ?, ?, ?, ?, ?)',
+ [
+ 'local-1',
+ 'local-1',
+ 's1',
+ 'assistant',
+ JSON.stringify('已保存::codex-file-citation{path="/tmp/报告.docx" purpose="output"},请查收。'),
+ 1000,
+ ],
+ );
+
+ // 升级后再导入同一条回复:导入侧文本已归一化。两侧指纹统一规范化后应判定为
+ // 同一条,不插入第二份(review 反馈)。
+ const result = await client.tx('codex.importMessages', {
+ sessionId: 's1',
+ importClientIdPrefix: 'codex-import:',
+ sdkSessionId: 'thread-1',
+ model: 'gpt-5',
+ rows: [
+ {
+ lineNo: 1,
+ role: 'assistant',
+ text: '已保存:`/tmp/报告.docx`,请查收。',
+ content: '已保存:`/tmp/报告.docx`,请查收。',
+ createdAt: 1001,
+ },
+ ],
+ });
+
+ expect(result).toEqual({ changed: 0 });
+ await expect(
+ client.query('SELECT client_id FROM messages WHERE session_id = ?', ['s1']),
+ ).resolves.toEqual([{ client_id: 'local-1' }]);
+ });
+ });
+
+ it('codex.importMessages keeps distinct replies that differ only by Markdown formatting', async () => {
+ await withClient(async (client) => {
+ await seedSession(client, 's1');
+ // 仅 Markdown 格式不同的两条**不同**回复:canon 有损比较只在「至少一侧含
+ // 原始标记字面量」时启用,这里两侧都不含 → 原文精确比较,不得误判成重复
+ // (review 反馈:无条件去反引号会把 `Use \`foo\`` 与 `Use foo` 判成同一条)。
+ await client.exec(
+ 'INSERT INTO messages (id, client_id, session_id, role, content, created_at) VALUES (?, ?, ?, ?, ?, ?)',
+ ['local-1', 'local-1', 's1', 'assistant', JSON.stringify('Use `foo`'), 1000],
+ );
+
+ const result = await client.tx('codex.importMessages', {
+ sessionId: 's1',
+ importClientIdPrefix: 'codex-import:',
+ sdkSessionId: 'thread-1',
+ model: 'gpt-5',
+ rows: [
+ { lineNo: 1, role: 'assistant', text: 'Use foo', content: 'Use foo', createdAt: 1001 },
+ ],
+ });
+
+ expect(result).toEqual({ changed: 1 });
+ await expect(
+ client.query('SELECT client_id FROM messages WHERE session_id = ? ORDER BY client_id', [
+ 's1',
+ ]),
+ ).resolves.toEqual([{ client_id: 'codex-import:1' }, { client_id: 'local-1' }]);
+ });
+ });
+
+ it('codex.importMessages dedupes unfinished-marker rows against finalized plain text', async () => {
+ await withClient(async (client) => {
+ await seedSession(client, 's1');
+ // 升级前落库的残尾行:生成被打断,正文停在未闭合标记。导入侧同一条回复
+ // finalize 后是**不含标记/反引号的纯文本**——纯文本也要有规范形候选指纹,
+ // 否则永远配不上残尾行的规范形(review 反馈)。
+ await client.exec(
+ 'INSERT INTO messages (id, client_id, session_id, role, content, created_at) VALUES (?, ?, ?, ?, ?, ?)',
+ [
+ 'local-1',
+ 'local-1',
+ 's1',
+ 'assistant',
+ JSON.stringify('Result :codex-file-citation{path="/tmp/x'),
+ 1000,
+ ],
+ );
+
+ const result = await client.tx('codex.importMessages', {
+ sessionId: 's1',
+ importClientIdPrefix: 'codex-import:',
+ sdkSessionId: 'thread-1',
+ model: 'gpt-5',
+ rows: [
+ { lineNo: 1, role: 'assistant', text: 'Result', content: 'Result', createdAt: 1001 },
+ ],
+ });
+
+ expect(result).toEqual({ changed: 0 });
+ await expect(
+ client.query('SELECT client_id FROM messages WHERE session_id = ?', ['s1']),
+ ).resolves.toEqual([{ client_id: 'local-1' }]);
+ });
+ });
+
+ it('codex.importMessages dedupes marker-literal filenames (指纹不动点规范形)', async () => {
+ await withClient(async (client) => {
+ await seedSession(client, 's1');
+ // 极端文件名:路径解码后本身是完整标记字面量。展示形二次处理不幂等,指纹
+ // 用不动点规范形让原始行与展示形行收敛到同一形。
+ await client.exec(
+ 'INSERT INTO messages (id, client_id, session_id, role, content, created_at) VALUES (?, ?, ?, ?, ?, ?)',
+ [
+ 'local-1',
+ 'local-1',
+ 's1',
+ 'assistant',
+ JSON.stringify('保存 :codex-file-citation{path="/tmp/a:codex-file-citation{path=\\"/b\\"}.md"} 完成'),
+ 1000,
+ ],
+ );
+
+ const result = await client.tx('codex.importMessages', {
+ sessionId: 's1',
+ importClientIdPrefix: 'codex-import:',
+ sdkSessionId: 'thread-1',
+ model: 'gpt-5',
+ rows: [
+ {
+ lineNo: 1,
+ role: 'assistant',
+ text: '保存 `/tmp/a:codex-file-citation{path="/b"}.md` 完成',
+ content: '保存 `/tmp/a:codex-file-citation{path="/b"}.md` 完成',
+ createdAt: 1001,
+ },
+ ],
+ });
+
+ expect(result).toEqual({ changed: 0 });
+ await expect(
+ client.query('SELECT client_id FROM messages WHERE session_id = ?', ['s1']),
+ ).resolves.toEqual([{ client_id: 'local-1' }]);
+ });
+ });
+
it('codex.importMessages does not rewrite tombstoned imported messages', async () => {
await withClient(async (client) => {
await seedSession(client, 's1');
diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
index e3aa175184..17004df17e 100644
--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
@@ -1202,7 +1202,16 @@ function readExistingImportedClientIds(
interface MessageFingerprint {
role: 'user' | 'assistant';
- text: string;
+ /** 原文指纹(仅换行归一 + trim),普通消息只用它精确比较。 */
+ plain: string;
+ /**
+ * citation 规范形指纹(有损:标记→路径、去反引号、折叠空白)。只在 canon 比较
+ * 门放行时参与(见 isLikelyLocalDuplicate),避免「仅 Markdown 格式不同」的两条
+ * 正常回复被误判成重复(review 反馈)。
+ */
+ canonical?: string;
+ /** 原文是否含原始标记字面量——canon 比较的门:至少一侧为真才启用有损比较。 */
+ hasMarker: boolean;
createdAt: number;
}
@@ -1237,10 +1246,18 @@ function isLikelyLocalDuplicate(
row: { role: 'user' | 'assistant'; text: string; createdAt: number },
): boolean {
const next = messageFingerprint(row.role, row.text, row.createdAt);
- return existing.some((prev) =>
- prev.role === next.role &&
- prev.text === next.text &&
- Math.abs(prev.createdAt - next.createdAt) <= LOCAL_DUPLICATE_WINDOW_MS,
+ return existing.some(
+ (prev) =>
+ prev.role === next.role &&
+ Math.abs(prev.createdAt - next.createdAt) <= LOCAL_DUPLICATE_WINDOW_MS &&
+ // 普通消息:原文精确比较。canon 有损比较只在「至少一侧含原始标记字面量」时
+ // 启用——即升级前的旧标记行 vs 已归一化的导入行;两条都不含标记的正常回复
+ // (如 `Use \`foo\`` vs `Use foo`)绝不走有损比较(review 反馈)。
+ (prev.plain === next.plain ||
+ (prev.canonical !== undefined &&
+ next.canonical !== undefined &&
+ (prev.hasMarker || next.hasMarker) &&
+ prev.canonical === next.canonical)),
);
}
@@ -1249,7 +1266,76 @@ function messageFingerprint(
text: string,
createdAt: number,
): MessageFingerprint {
- return { role, text: normalizeFingerprintText(text), createdAt };
+ // 升级前落库的旧行仍带原始 `:codex-file-citation{...}` 标记,导入侧新文本已
+ // 归一化(标记换成 code span,截断残尾则被整段剥掉——此时是**不含任何标记/
+ // 反引号的纯文本**)。因此 assistant 一律算出规范形候选指纹,是否参与比较由
+ // isLikelyLocalDuplicate 的标记门决定(review 反馈:残尾行的规范形是纯文本,
+ // 导入侧若不给纯文本算规范形就永远配不上)。只影响比较,不改落库内容。
+ const plain = normalizeFingerprintText(text);
+ const hasMarker = role === 'assistant' && text.includes(CODEX_CITATION_OPEN);
+ const canonical =
+ role === 'assistant' ? normalizeFingerprintText(canonicalizeCodexCitations(text)) : undefined;
+ return { role, plain, ...(canonical !== undefined ? { canonical } : {}), hasMarker, createdAt };
+}
+
+// 指纹专用规范形——与展示形(maker-core finalizeCodexCitationText)**刻意不同**:
+// 标记替换为解码路径本体(无 code span 围栏/空格垫),循环到不动点,再去掉全部
+// 反引号并折叠空白。这样「升级前的原始标记行」与「已归一化的展示形文本」两侧
+// 都收敛到同一规范形——路径本身解码出完整标记字面量的极端文件名也一致(review
+// 反馈:展示形二次处理不幂等,不能拿来当指纹)。只用于去重比较,不落库。
+// eval-fallback worker(WorkerThreadTransport WORKER_CODE)无法 import,两份 worker
+// 各内联一份,口径变更需同步(tx.test 用真实标记 fixture 钉行为)。
+const CODEX_CITATION_RE = /:codex-file-citation\{((?:[^"{}]|"(?:[^"\\]|\\.)*")*)\}/g;
+const CODEX_CITATION_OPEN = ':codex-file-citation{';
+
+function codexCitationClose(text: string, attrsStart: number): number {
+ let inQuote = false;
+ for (let i = attrsStart; i < text.length; i += 1) {
+ const ch = text[i];
+ if (inQuote && ch === '\\') i += 1;
+ else if (ch === '"') inQuote = !inQuote;
+ else if (!inQuote && ch === '}') return i;
+ else if (!inQuote && ch === '{') return -2; // 裸 { = 畸形标记,原样透出
+ }
+ return -1; // 扫描到末尾未闭合 = 截断残尾
+}
+
+// path 属性解码(与 translator extractCitationPath 同口径:完整属性名边界、
+// \"/\\ 转义、开头恰好两个反斜杠 = 原生 UNC 整体保留)。
+function decodeCitationPathForFingerprint(attrs: string): string {
+ const raw = /(?:^|\s)path="((?:[^"\\]|\\.)*)"/.exec(attrs)?.[1];
+ if (raw === undefined) return '';
+ const nativeUnc = raw.startsWith('\\\\') && raw[2] !== '\\';
+ const head = nativeUnc ? '\\\\' : '';
+ return head + (nativeUnc ? raw.slice(2) : raw).replace(/\\([\\"])/g, '$1');
+}
+
+function canonicalizeCodexCitations(text: string): string {
+ // 无早退:纯文本也要走末尾的空白折叠,否则「残尾行规范形(折叠过)」与「导入侧
+ // 纯文本规范形(未折叠)」会因内部空白差异配不上。
+ // 截断残尾剥除(与展示口径一致:只剥「扫描到文本末尾仍未闭合」的标记)。
+ let out = text;
+ let from = 0;
+ for (;;) {
+ const open = out.indexOf(CODEX_CITATION_OPEN, from);
+ if (open === -1) break;
+ const close = codexCitationClose(out, open + CODEX_CITATION_OPEN.length);
+ if (close === -1) {
+ out = out.slice(0, open);
+ break;
+ }
+ from = close === -2 ? open + CODEX_CITATION_OPEN.length : close + 1;
+ }
+ // 标记 → 解码路径,循环到不动点(路径解码可能暴露新的完整标记字面量;有界防御)。
+ for (let i = 0; i < 5; i += 1) {
+ const next = out.replace(CODEX_CITATION_RE, (_all, attrs: string) =>
+ decodeCitationPathForFingerprint(attrs),
+ );
+ if (next === out) break;
+ out = next;
+ }
+ // 展示形的围栏/空格垫与换行渲染差异不参与指纹比较。
+ return out.replace(/`+/g, '').replace(/\s+/g, ' ');
}
function normalizeStoredMessageText(raw: string): string {
diff --git a/apps/desktop/src/main/maker-host/codex-local-sessions.ts b/apps/desktop/src/main/maker-host/codex-local-sessions.ts
index bf32394426..4dff78778e 100644
--- a/apps/desktop/src/main/maker-host/codex-local-sessions.ts
+++ b/apps/desktop/src/main/maker-host/codex-local-sessions.ts
@@ -22,6 +22,8 @@ import {
} from '@cindy/maker-shared/brand-identity';
import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
+import { finalizeCodexCitationText } from '@cindy/maker-core';
+
import { getCurrentDbClientUserId, getDbClient } from '../localDb/client/current.js';
import { createBetterSqliteDatabase } from '../localDb/betterSqliteFactory.js';
import { createLogger } from '../logger.js';
@@ -1951,7 +1953,14 @@ export function parseCodexRolloutMessageLine(
const role = payload.role === 'assistant' ? 'assistant' : payload.role === 'user' ? 'user' : null;
if (!role) return null;
const rawText = extractContentText(payload.content);
- const text = (role === 'user' ? stripCompleteIdeOpenedFileBlocks(rawText) : rawText).trim();
+ // assistant 正文与流式 completed 同口径:剥截断残尾 + citation 归一化——rollout
+ // 存的是含 `:codex-file-citation{...}` 内部语法的原文(生成被打断时还带未闭合
+ // 残尾),直接入库会把它漏给用户(#785)。
+ const text = (
+ role === 'user'
+ ? stripCompleteIdeOpenedFileBlocks(rawText)
+ : finalizeCodexCitationText(rawText)
+ ).trim();
if (!text) return null;
return {
lineNo,
@@ -1982,7 +1991,14 @@ async function parseCodexRolloutMessageLineForImport(
if (!role) return null;
const rawText = extractContentText(payload.content);
- const text = (role === 'user' ? stripCompleteIdeOpenedFileBlocks(rawText) : rawText).trim();
+ // assistant 正文与流式 completed 同口径:剥截断残尾 + citation 归一化——rollout
+ // 存的是含 `:codex-file-citation{...}` 内部语法的原文(生成被打断时还带未闭合
+ // 残尾),直接入库会把它漏给用户(#785)。
+ const text = (
+ role === 'user'
+ ? stripCompleteIdeOpenedFileBlocks(rawText)
+ : finalizeCodexCitationText(rawText)
+ ).trim();
const images = role === 'user'
? await extractCodexUserImages(payload.content, sessionId, lineNo)
: [];
diff --git a/packages/maker-core/src/agents/codex/translator.test.ts b/packages/maker-core/src/agents/codex/translator.test.ts
index 282529040c..7d9eccdc94 100644
--- a/packages/maker-core/src/agents/codex/translator.test.ts
+++ b/packages/maker-core/src/agents/codex/translator.test.ts
@@ -1231,3 +1231,263 @@ describe('extractRolloutUpdatePlanFunctionCallEvent', () => {
expect(parsed).toBeNull();
});
});
+
+describe('codex file citation 归一化 (#785)', () => {
+ it('normalizeCodexFileCitations 把标记换成行内代码路径,畸形标记整个剥掉', async () => {
+ const { normalizeCodexFileCitations } = await import('./translator.js');
+ expect(
+ normalizeCodexFileCitations(
+ '文档已生成::codex-file-citation{path="/tmp/报告.docx" purpose="output"},请查收。',
+ ),
+ ).toBe('文档已生成:`/tmp/报告.docx`,请查收。');
+ expect(normalizeCodexFileCitations('bad :codex-file-citation{purpose="output"} end')).toBe(
+ 'bad end',
+ );
+ expect(normalizeCodexFileCitations('no marker here')).toBe('no marker here');
+ // 路径含花括号(引号串内):标记仍完整匹配,不把内部语法漏给用户。
+ expect(
+ normalizeCodexFileCitations(':codex-file-citation{path="/tmp/a{b}.md" purpose="output"}'),
+ ).toBe('`/tmp/a{b}.md`');
+ // 路径含反引号:围栏升级为双反引号,code span 不被撑破。
+ expect(
+ normalizeCodexFileCitations(':codex-file-citation{path="/tmp/a`b.md" purpose="output"}'),
+ ).toBe('``/tmp/a`b.md``');
+ // 路径以反引号结尾:按 CommonMark 两侧补空格。
+ expect(
+ normalizeCodexFileCitations(':codex-file-citation{path="/tmp/ab`" purpose="output"}'),
+ ).toBe('`` /tmp/ab` ``');
+ // 路径含转义引号(\"):解出真实文件名(review 反馈)。
+ expect(
+ normalizeCodexFileCitations(':codex-file-citation{path="/tmp/a\\"b.md" purpose="output"}'),
+ ).toBe('`/tmp/a"b.md`');
+ // Windows 原生路径:反斜杠不是转义前缀,原样保留(review 反馈——全量 \(.) 反
+ // 转义会把 C:\Users\Ada\out.docx 毁成 C:UsersAdaout.docx)。
+ expect(
+ normalizeCodexFileCitations(
+ ':codex-file-citation{path="C:\\Users\\Ada\\out.docx" purpose="output"}',
+ ),
+ ).toBe('`C:\\Users\\Ada\\out.docx`');
+ // 显式转义的 \\ 仍解为单个反斜杠。
+ expect(
+ normalizeCodexFileCitations(':codex-file-citation{path="C:\\\\tmp\\\\a.md" purpose="output"}'),
+ ).toBe('`C:\\tmp\\a.md`');
+ // UNC 原生路径:开头的 \\ 是路径本体(网络共享前缀),不当作转义对(review 反馈)。
+ expect(
+ normalizeCodexFileCitations(
+ ':codex-file-citation{path="\\\\server\\share\\out.docx" purpose="output"}',
+ ),
+ ).toBe('`\\\\server\\share\\out.docx`');
+ // 转义形态的 UNC(\\\\server\\share):按转义对解码,解出恰好两个分隔符(review 反馈)。
+ expect(
+ normalizeCodexFileCitations(
+ ':codex-file-citation{path="\\\\\\\\server\\\\share\\\\out.docx" purpose="output"}',
+ ),
+ ).toBe('`\\\\server\\share\\out.docx`');
+ // 属性名完整边界:display_path 不是 path,畸形标记(无真 path)整个剥掉;
+ // 有真 path 时不被前面的 *_path 别名遮蔽(review 反馈)。
+ expect(
+ normalizeCodexFileCitations(
+ 'bad :codex-file-citation{display_path="/tmp/preview.docx"} end',
+ ),
+ ).toBe('bad end');
+ expect(
+ normalizeCodexFileCitations(
+ ':codex-file-citation{display_path="/tmp/preview.docx" path="/tmp/real.docx"}',
+ ),
+ ).toBe('`/tmp/real.docx`');
+ // 文件名首尾空白保留,不 trim(悄悄改写会指向另一个文件)。
+ expect(
+ normalizeCodexFileCitations(':codex-file-citation{path="/tmp/ab.md " purpose="output"}'),
+ ).toBe('`/tmp/ab.md `');
+ // 首尾都是空格:CommonMark 渲染器会对这种 code span 各剥一个空格,补空格垫让
+ // 展示串回到真实路径(review 反馈);单侧空格渲染器不剥,不垫。
+ expect(
+ normalizeCodexFileCitations(':codex-file-citation{path=" ab.md " purpose="output"}'),
+ ).toBe('` ab.md `');
+ // 全空格路径:CommonMark 规定剥空格仅当「首尾是空格且**非全空格**」——全空格
+ // code span 原样保留,因此**不垫**才是无损的;垫了反而多出两个永远不被剥的空格。
+ expect(normalizeCodexFileCitations(':codex-file-citation{path=" " purpose="output"}')).toBe(
+ '` `',
+ );
+ });
+
+ it('finalizeCodexCitationText:剥截断残尾 + 归一化,幂等(#785 导入口径)', async () => {
+ const { finalizeCodexCitationText } = await import('./translator.js');
+ // 截断残尾剥除,与流式 completed 同口径。
+ expect(finalizeCodexCitationText('文件在 :codex-file-citation{path="/tmp/x')).toBe('文件在 ');
+ // 完整标记归一化。
+ expect(
+ finalizeCodexCitationText('done :codex-file-citation{path="/a/b.md" purpose="output"}'),
+ ).toBe('done `/a/b.md`');
+ // 对已归一化文本幂等。
+ expect(finalizeCodexCitationText('done `/a/b.md`')).toBe('done `/a/b.md`');
+ });
+
+ it('stableCitationBoundary 按住未写完的标记尾巴', async () => {
+ const { stableCitationBoundary } = await import('./translator.js');
+ expect(stableCitationBoundary('plain text')).toBe('plain text'.length);
+ const partialOpen = 'abc :codex-file-citation{path="/x';
+ expect(stableCitationBoundary(partialOpen)).toBe(4);
+ const partialPrefix = 'abc :codex-fi';
+ expect(stableCitationBoundary(partialPrefix)).toBe(4);
+ const complete = 'abc :codex-file-citation{path="/x"}';
+ expect(stableCitationBoundary(complete)).toBe(complete.length);
+ // 引号串内的 } 不是闭合边界:标记未写完仍要按住(review 反馈的花括号路径场景)。
+ const braceInQuote = 'abc :codex-file-citation{path="/tmp/a{b}';
+ expect(stableCitationBoundary(braceInQuote)).toBe(4);
+ const braceComplete = 'abc :codex-file-citation{path="/tmp/a{b}.md"}';
+ expect(stableCitationBoundary(braceComplete)).toBe(braceComplete.length);
+ });
+
+ it('路径本身含标记开头字面量:完整标记结构化消费,不被误认成新的未闭合开头', async () => {
+ const { normalizeCodexFileCitations, stableCitationBoundary } = await import('./translator.js');
+ // macOS/POSIX 文件名允许 `:` 与 `{`——路径里可以出现完整的 OPEN 字面量。
+ // 按「最后一个裸字面量」定位会从路径中间起扫、引号状态错位,把完整标记判成
+ // 未完成(review 反馈);结构化扫描把完整标记整体跳过。
+ const marker =
+ ':codex-file-citation{path="/tmp/a:codex-file-citation{b.md" purpose="output"}';
+ expect(stableCitationBoundary(`abc ${marker}`)).toBe(`abc ${marker}`.length);
+ expect(normalizeCodexFileCitations(`abc ${marker}`)).toBe(
+ 'abc `/tmp/a:codex-file-citation{b.md`',
+ );
+ // 完整标记之后的真实截断尾巴仍要按住,且按住点在外层标记的真实开头。
+ const tail = ' 然后 :codex-file-citation{path="/x';
+ expect(stableCitationBoundary(`abc ${marker}${tail}`)).toBe(`abc ${marker} 然后 `.length);
+ });
+
+ it('completed:路径含 OPEN 字面量的完整标记不再被误剥,只剥真实截断尾巴', async () => {
+ const { newCodexRuntimeState } = await import('./translator.js');
+ const marker =
+ ':codex-file-citation{path="/tmp/a:codex-file-citation{b.md" purpose="output"}';
+ const rt = newCodexRuntimeState();
+ const q = createAsyncQueue<AgentEvent>();
+ translateItemNotification(
+ 'completed',
+ {
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ item: {
+ type: 'agentMessage',
+ id: 'msg-embed',
+ text: `保存到 ${marker} 之后 :codex-file-citation{path="/x`,
+ },
+ },
+ q,
+ makeCtx(rt),
+ );
+ const events = await collect(q);
+ expect((events[0].data as { text: string }).text).toBe(
+ '保存到 `/tmp/a:codex-file-citation{b.md` 之后 ',
+ );
+ });
+
+ it('裸 { 的畸形标记原样透出:不按住流式边界,也不吞它后面的正文', async () => {
+ const { stableCitationBoundary } = await import('./translator.js');
+ // 属性区出现裸 { 后正则永不匹配,追加文本也救不回来——不是「尚未写完」,按住
+ // 或剥除都会误吞后续正文,原样透出交给用户可见性兜底。
+ const poisoned = 'abc :codex-file-citation{oops{ 后面是正文';
+ expect(stableCitationBoundary(poisoned)).toBe(poisoned.length);
+ });
+
+ it('agentMessage 流式:标记跨 update 分段到达,delta 流与 final 全文一致且无内部语法', async () => {
+ const { newCodexRuntimeState } = await import('./translator.js');
+ const rt = newCodexRuntimeState();
+ const q = createAsyncQueue<AgentEvent>();
+ const push = (phase: 'started' | 'updated' | 'completed', text: string): void => {
+ translateItemNotification(
+ phase,
+ {
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ item: { type: 'agentMessage', id: 'msg-1', text },
+ },
+ q,
+ makeCtx(rt),
+ );
+ };
+ push('started', '文件已保存:');
+ push('updated', '文件已保存::codex-file-cit');
+ push('updated', '文件已保存::codex-file-citation{path="/tmp/out');
+ push('updated', '文件已保存::codex-file-citation{path="/tmp/out.docx" purpose="output"} 完成');
+ push('completed', '文件已保存::codex-file-citation{path="/tmp/out.docx" purpose="output"} 完成。');
+
+ const events = await collect(q);
+ const finalText = '文件已保存:`/tmp/out.docx` 完成。';
+ const deltas = events
+ .filter((e) => e.type === 'text' && (e.data as { isFinal: boolean }).isFinal === false)
+ .map((e) => (e.data as { text: string }).text);
+ // 既有契约:completed 只出 final、不补 delta——completed 才首次出现的「。」不进
+ // delta 流,由 final 全文兜底。delta 累积必须是 final 的前缀且不含内部语法。
+ expect(deltas.join('')).toBe('文件已保存:`/tmp/out.docx` 完成');
+ expect(finalText.startsWith(deltas.join(''))).toBe(true);
+ const finals = events.filter(
+ (e) => e.type === 'text' && (e.data as { isFinal: boolean }).isFinal === true,
+ );
+ expect(finals).toHaveLength(1);
+ expect((finals[0].data as { text: string }).text).toBe(finalText);
+ for (const d of deltas) expect(d).not.toContain(':codex-file-citation{');
+ });
+
+ it('completed 文本截断在标记中间:确定的未完成标记从 final 剥掉,疑似前缀保留', async () => {
+ const { newCodexRuntimeState } = await import('./translator.js');
+ const rt = newCodexRuntimeState();
+ const q = createAsyncQueue<AgentEvent>();
+ translateItemNotification(
+ 'completed',
+ {
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ item: {
+ type: 'agentMessage',
+ id: 'msg-cut',
+ text: '文件在 :codex-file-citation{path="/tmp/x',
+ },
+ },
+ q,
+ makeCtx(rt),
+ );
+ const rt2 = newCodexRuntimeState();
+ const q2 = createAsyncQueue<AgentEvent>();
+ translateItemNotification(
+ 'completed',
+ {
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ item: { type: 'agentMessage', id: 'msg-prefix', text: '正文以 :codex 结尾' },
+ },
+ q2,
+ makeCtx(rt2),
+ );
+ const events = await collect(q);
+ expect((events[0].data as { text: string }).text).toBe('文件在 ');
+ const events2 = await collect(q2);
+ expect((events2[0].data as { text: string }).text).toBe('正文以 :codex 结尾');
+ });
+
+ it('agentMessage 非流式(直接 completed):final 文本已归一化', async () => {
+ const { newCodexRuntimeState } = await import('./translator.js');
+ const rt = newCodexRuntimeState();
+ const q = createAsyncQueue<AgentEvent>();
+ translateItemNotification(
+ 'completed',
+ {
+ threadId: 'thread-1',
+ turnId: 'turn-1',
+ item: {
+ type: 'agentMessage',
+ id: 'msg-2',
+ text: 'done :codex-file-citation{path="/a/b.md" purpose="output"}',
+ },
+ },
+ q,
+ makeCtx(rt),
+ );
+ const events = await collect(q);
+ expect(events).toEqual([
+ expect.objectContaining({
+ type: 'text',
+ data: { text: 'done `/a/b.md`', isFinal: true },
+ }),
+ ]);
+ });
+});
diff --git a/packages/maker-core/src/agents/codex/translator.ts b/packages/maker-core/src/agents/codex/translator.ts
index da2f375324..abf7461912 100644
--- a/packages/maker-core/src/agents/codex/translator.ts
+++ b/packages/maker-core/src/agents/codex/translator.ts
@@ -61,7 +61,7 @@ export interface CodexRuntimeState {
reasoningStartedAt: Map<string, number>;
/** item.id → reasoning 已 emit 文本字符长度 (上次 join 后总长)。 */
reasoningTextLen: Map<string, number>;
- /** item.id → agentMessage 已 emit 文本字符长度。 */
+ /** item.id → agentMessage 已 emit 文本字符长度(citation 归一化后的空间,见 handleAgentMessage)。 */
itemTextLen: Map<string, number>;
/** 已经 emit 过 tool_use 的 item.id (避免 started + 第一次 updated 重复)。 */
emittedToolUse: Set<string>;
@@ -627,27 +627,168 @@ interface ContextCompactionItem {
// item.started / item.updated 出 delta (isFinal=false), item.completed 出 final 全文。
// Phase 1 没订阅 item/agentMessage/delta, 增量靠 item.updated 的 text 全量字段算 diff。
+/**
+ * Codex 正文里的内部文件引用标记 `:codex-file-citation{path="..." ...}`——对用户
+ * 是不可读的内部语法,归一化成行内代码的文件路径。没有 path 属性的畸形标记整个
+ * 剥掉,不把内部语法漏给用户。
+ */
+// 属性区 = 「非引号非花括号字符 或 双引号串」的序列:双引号串内允许出现 { } ,
+// 且支持反斜杠转义(\" 表示文件名里的引号)——路径含花括号 / 引号都不会让标记
+// 匹配失败而把内部语法漏给用户。
+const CODEX_FILE_CITATION_RE = /:codex-file-citation\{((?:[^"{}]|"(?:[^"\\]|\\.)*")*)\}/g;
+const CODEX_FILE_CITATION_OPEN = ':codex-file-citation{';
+
+/**
+ * 路径包成 Markdown 行内代码:围栏取「比路径内最长反引号连跑多一个」的反引号数,
+ * 路径以反引号开头/结尾时按 CommonMark 规则两侧补空格——路径自身含反引号也不会
+ * 把 code span 撑破。
+ */
+function inlineCodePath(path: string): string {
+ const longestRun = path.match(/`+/g)?.reduce((max, run) => Math.max(max, run.length), 0) ?? 0;
+ const fence = '`'.repeat(longestRun + 1);
+ // 补空格垫的两种情形:路径以反引号开头/结尾(隔开围栏),或首尾都是空格且非全空格
+ // (CommonMark 渲染器对这种 code span 会各剥一个空格,不垫会把真实路径的首尾空白
+ // 剥掉指向别的文件;单侧空格渲染器不剥,不垫)。
+ const symmetricSpace = path.startsWith(' ') && path.endsWith(' ') && path.trim().length > 0;
+ const pad = path.startsWith('`') || path.endsWith('`') || symmetricSpace ? ' ' : '';
+ return `${fence}${pad}${path}${pad}${fence}`;
+}
+
+export function normalizeCodexFileCitations(text: string): string {
+ if (!text.includes(CODEX_FILE_CITATION_OPEN)) return text;
+ return text.replace(CODEX_FILE_CITATION_RE, (_all, attrs: string) => {
+ const path = extractCitationPath(attrs);
+ return path ? inlineCodePath(path) : '';
+ });
+}
+
+/**
+ * 属性区取 path 值并解码。
+ * - 属性名要求完整边界(串首或空白后的 `path=`):`display_path=` 这类「以 path 结尾」
+ * 的别名不当作 path,也不遮蔽其后真正的 path 属性(review 反馈)。
+ * - 只解 \" 与 \\ 两种转义——Windows 原生路径(C:\Users\...)里的反斜杠不是转义
+ * 前缀,全量 \\(.) 反转义会把路径毁成 C:Users...(review 反馈)。
+ * - UNC 前缀:开头**恰好两个**反斜杠视为原生 UNC 本体整体保留(\\server\share);
+ * 更长的开头连跑(如转义形态 \\\\server)与其余位置按转义对解码,转义 UNC 解出
+ * 恰好两个分隔符(review 反馈)。
+ * - 取出后不做 trim——文件名首尾空白是路径的一部分,悄悄改写会指向另一个文件。
+ */
+function extractCitationPath(attrs: string): string | undefined {
+ const raw = /(?:^|\s)path="((?:[^"\\]|\\.)*)"/.exec(attrs)?.[1];
+ if (raw === undefined) return undefined;
+ const nativeUnc = raw.startsWith('\\\\') && raw[2] !== '\\';
+ const head = nativeUnc ? '\\\\' : '';
+ const tail = (nativeUnc ? raw.slice(2) : raw).replace(/\\([\\"])/g, '$1');
+ return head + tail;
+}
+
+// 闭合扫描的两种「未找到」:UNFINISHED = 扫描到文本末尾仍未闭合(可能是尚未写完、
+// 会被后续 update 补全的截断尾巴);POISONED = 属性区出现裸 `{`,正则永不匹配,该
+// 标记已确定畸形且追加文本也不会改变这一判定。
+const CITATION_UNFINISHED = -1;
+const CITATION_POISONED = -2;
+
+/**
+ * 属性区闭合 `}` 的位置(与 CODEX_FILE_CITATION_RE 同一口径:双引号串内的花括号
+ * 不算边界);找不到时区分 CITATION_UNFINISHED 与 CITATION_POISONED。
+ */
+function findCitationClose(text: string, attrsStart: number): number {
+ let inQuote = false;
+ for (let i = attrsStart; i < text.length; i += 1) {
+ const ch = text[i];
+ if (inQuote && ch === '\\') {
+ i += 1; // 引号串内的转义对(如 \")整体跳过,与正则同口径。
+ } else if (ch === '"') {
+ inQuote = !inQuote;
+ } else if (!inQuote && ch === '}') {
+ return i;
+ } else if (!inQuote && ch === '{') {
+ return CITATION_POISONED;
+ }
+ }
+ return CITATION_UNFINISHED;
+}
+
+/**
+ * 从左到右结构化扫描,返回第一个「扫描到文本末尾仍未闭合」的标记开头;没有 → -1。
+ * 完整标记整体跳过——路径引号串里出现的 OPEN 字面量属于已消费标记的内部,不会被
+ * 误认成新的开头(review 反馈:文件名本身含 `:codex-file-citation{` 时,按最后一个
+ * 裸字面量定位会带着错误的引号状态把完整标记判成未完成)。裸 `{` 的畸形标记(正则
+ * 永不匹配、追加文本也救不回来)原样透出:只跳过开头字面量继续扫,不吞它后面的正文。
+ */
+function findUnfinishedCitationOpen(text: string): number {
+ let from = 0;
+ for (;;) {
+ const open = text.indexOf(CODEX_FILE_CITATION_OPEN, from);
+ if (open === -1) return -1;
+ const close = findCitationClose(text, open + CODEX_FILE_CITATION_OPEN.length);
+ if (close === CITATION_UNFINISHED) return open;
+ from = close === CITATION_POISONED ? open + CODEX_FILE_CITATION_OPEN.length : close + 1;
+ }
+}
+
+/**
+ * 流式安全边界:全量文本尾部可能是一个尚未写完的 citation 标记(标记会被后续
+ * update 补全),归一化后的文本对这段尾巴不是 append-only。返回可安全发出的原文
+ * 前缀长度,未写完的尾巴按住等下一轮;completed 时全量补发,不丢内容。
+ */
+/**
+ * final 文本统一口径(流式 completed 与历史 rollout 导入共用):先剥「扫描到文本
+ * 末尾仍未闭合」的确定截断残尾(它之后没有正文可吞),再做 citation 归一化。
+ * 契约:只做 raw→final 的**单次**转换(两个调用点都满足)。无标记文本原样返回,
+ * 但展示形不承诺严格幂等——路径本身解码出完整标记字面量的极端文件名,二次处理
+ * 会把生成的 code span 内容再替换;去重指纹因此不复用展示形,走独立的不动点
+ * 规范形(见 localDb worker 的 canonicalizeCodexCitations)。
+ */
+export function finalizeCodexCitationText(text: string): string {
+ const openAt = findUnfinishedCitationOpen(text);
+ return normalizeCodexFileCitations(openAt === -1 ? text : text.slice(0, openAt));
+}
+
+export function stableCitationBoundary(text: string): number {
+ const open = findUnfinishedCitationOpen(text);
+ if (open !== -1) {
+ return open;
+ }
+ const maxProbe = Math.min(text.length, CODEX_FILE_CITATION_OPEN.length - 1);
+ for (let k = maxProbe; k > 0; k -= 1) {
+ if (text.endsWith(CODEX_FILE_CITATION_OPEN.slice(0, k))) return text.length - k;
+ }
+ return text.length;
+}
+
function handleAgentMessage(
phase: ItemPhase,
item: AgentMessageItem,
queue: AsyncQueue<AgentEvent>,
ctx: CodexTranslateContext,
): void {
- const currentText = item.text ?? '';
+ const rawText = item.text ?? '';
+ // itemTextLen 记录的是**归一化后已发出**的长度:citation 替换会改变文本长度,
+ // diff 必须在归一化空间里做,不能混用原文长度。
+ const prevLen = ctx.rt.itemTextLen.get(item.id) ?? 0;
if (phase === 'completed') {
ctx.rt.itemTextLen.delete(item.id);
+ // 既有契约:completed 只出 final 全文、不补 delta(desktop codexTranslator.test
+ // 钉死 3 事件形状)。boundary 按住的尾段与「completed 才首次出现的文本」同一待遇:
+ // 不进 delta 流,由 final 全文兜底(main 落库层 onAssistantTextEvent 的 isFinal
+ // 分支以更长 final 覆盖 delta 累积,不丢内容)。
+ // 输出被截断在标记中间(有明确的 open、永远等不到 close)时,把残尾剥掉——
+ // 内部语法不该漏给用户;只剥「扫描到文本末尾仍未闭合」的确定截断残尾(它之后
+ // 没有正文可吞),疑似前缀(不足完整 open 字面量)可能是真实正文,保留。
+ // finalizeCodexCitationText 是与历史导入共用的统一口径。
queue.push({
type: 'text',
- data: { text: currentText, isFinal: true },
+ data: { text: finalizeCodexCitationText(rawText), isFinal: true },
source: 'codex',
});
return;
}
- const prevLen = ctx.rt.itemTextLen.get(item.id) ?? 0;
- const delta = currentText.slice(prevLen);
- ctx.rt.itemTextLen.set(item.id, currentText.length);
+ const emitted = normalizeCodexFileCitations(rawText.slice(0, stableCitationBoundary(rawText)));
+ const delta = emitted.slice(prevLen);
+ ctx.rt.itemTextLen.set(item.id, emitted.length);
if (delta.length === 0) return;
queue.push({
type: 'text',
diff --git a/packages/maker-core/src/agents/index.ts b/packages/maker-core/src/agents/index.ts
index c677ac93ef..fd66277371 100644
--- a/packages/maker-core/src/agents/index.ts
+++ b/packages/maker-core/src/agents/index.ts
@@ -3,6 +3,10 @@ export * from './base-agent.js';
// (claude-haiku-4-5 → claude-haiku-4-5-20251001),复用 SSoT 映射,避免在 host 硬编码 dated id。
export { ClaudeCodeAgent, toSdkModelString, setClaudeSupportedModelsListener } from './claude-code/index.js';
export { CodexAgent } from './codex/index.js';
+// host 导入本地 Codex rollout 历史时也要做 citation 归一化(流式路径在 translator
+// 内部做,导入路径拿到的是 rollout 原文),复用同一实现避免口径分叉。
+// finalizeCodexCitationText = 剥截断残尾 + 归一化(与流式 completed 完全同口径)。
+export { finalizeCodexCitationText, normalizeCodexFileCitations } from './codex/translator.js';
export {
canReuseCodexHostForCredentialMode,
canReuseHostForCredentialMode,