Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
refactor(hook-control): 出站附件引用解析收敛到 @cindy/im xdtRefs 单一实现 (#1856)
Chris Zhangc40070c56305
diff --git a/apps/desktop/src/main/hook-control/__tests__/outbound.test.ts b/apps/desktop/src/main/hook-control/__tests__/outbound.test.tsindex 8b58b67420..18c3a3c2ff 100644--- a/apps/desktop/src/main/hook-control/__tests__/outbound.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/outbound.test.ts@@ -129,6 +129,34 @@ describe('collectOutboundAttachments', () => {expect(r.skipped).toBe(0);});+ it('未闭合 file 引用在前仍收集后续合法图片(#1856 review P2:共享解析器畸形恢复)', async () => {+ // 修复前: 畸形候选把 good.png 的右括号当自己的结尾, 图整个不收集,+ // 正文变换还会把含合法引用的整段错误改写成失败文件标签。+ const text = '[bad](xdt-file://unterminated  完事';+ const r = await collectOutboundAttachments(+ text,+ [],+ deps({ '/cache/good.png': Buffer.from('png-good') }),+ );+ expect(r.attachments.map((a) => a.name)).toEqual(['good.png']);+ expect(r.text).toContain('🖼️ _good(已作为附件发送)_');+ expect(r.text).toContain('[bad](xdt-file://unterminated');+ expect(r.text).not.toContain('xdt-image://');+ expect(r.skipped).toBe(0);+ });++ it('方括号文件名附件走全流程被收集(#1856 review P1:畸形恢复判据不能误伤合法 URL)', async () => {+ const text = '详见 [报告](xdt-file:///out/report[final].pdf) 收工';+ const r = await collectOutboundAttachments(+ text,+ [],+ deps({ '/out/report[final].pdf': Buffer.from('%PDF-1.4') }, { allowedFileRoots: ['/out'] }),+ );+ expect(r.attachments.map((a) => a.name)).toEqual(['report[final].pdf']);+ expect(r.text).not.toContain('xdt-file://');+ expect(r.skipped).toBe(0);+ });+it('cindy-media 图片引用同样收集(媒体总仓双协议;只认 xdt-image 会让 hook Slack 拿不到生成图)', async () => {const hash = 'b'.repeat(64);const text = `画好了 `;diff --git a/apps/desktop/src/main/hook-control/outbound.ts b/apps/desktop/src/main/hook-control/outbound.tsindex ff8f921be9..f994c1dd6e 100644--- a/apps/desktop/src/main/hook-control/outbound.ts+++ b/apps/desktop/src/main/hook-control/outbound.ts@@ -8,8 +8,10 @@* 引用语义与 IM 渠道收口(@cindy/im slack/streamingText.doFinalize)一致:* - 图片引用 `` → 附件, 正文替换成"已作为附件发送"提示* - 文件引用 `[name](xdt-file:///abs/path)` → 附件, 正文整体剥离- * (正则与 packages/lizi-im/src/xdtRefs.ts 对齐 —— 该包未导出这些工具,- * 这里维护精简副本, 改动语义时两处同步。)+ * 引用解析与正文变换直接消费 @cindy/im/xdtRefs 的前向解析器(单一实现,+ * #1855 收敛;旧版此处维护正则副本, 语义靠注释两处同步)。xdt-file 的+ * URL→路径转换是唯一的本地保留项: hook 会拿它自动读盘, 必须 fail-closed+ * (非法编码 / 相对路径 / null byte 一律拒绝), 严格版见 xdtFileUrlToAbsPath。** 限额(protocol 单帧 48MiB 的安全水位): 单图 5MiB(与入站一致)、单文件* 10MiB、总数 8、总字节 30MiB(base64 膨胀 4/3 后约 40MiB)。xdt-file@@ -23,10 +25,12 @@ import path from 'node:path';import { promises as fsp } from 'node:fs';import type { TaskAttachment } from '@cindy/slack-hook-protocol';--// 双协议:老 xdt-image + 新 cindy-media(媒体总仓),与 @cindy/im/xdtRefs.ts 对齐-const XDT_IMAGE_REGEX = /!\[([^\]]*)\]\(((?:xdt-image|cindy-media):\/\/[^)]+)\)/g;-const XDT_FILE_REGEX = /\[([^\]]*)\]\((xdt-file:\/\/[^)]+)\)/g;+import {+ collectXdtFileRefs,+ collectXdtImageRefs,+ normalizeXdtAbsPath,+ transformXdtRefs,+} from '@cindy/im';const MAX_OUT_IMAGE_BYTES = 5 * 1024 * 1024;const MAX_OUT_FILE_BYTES = 10 * 1024 * 1024;@@ -116,13 +120,10 @@ export function xdtFileUrlToAbsPath(url: string): string {throw new Error('not an xdt-file URL');}const raw = url.slice('xdt-file://'.length);+ // 与 @cindy/im 宽松版(解码失败回退原串)刻意不同: hook 会拿这个路径自动+ // 读盘, 非法编码必须拒绝(fail-closed), 让调用方按坏链接计 skipped。const decoded = decodeURIComponent(raw);- // 约定写法 xdt-file:///<绝对路径>:Unix 下剥掉协议后的首个 `/` 就是根;- // Windows 盘符路径剥完协议剩 `/C:\...`(或 /C:/...),多余的前导 `/` 会让- // allowedFileRoots 比对必失败 → 附件静默丢失(2026-07-16 实踩,规则 15),- // 这里剥掉。hook 会把该路径用于自动读盘,因而比只做文案重写的- // @cindy/im/xdtRefs.ts 多一道“必须是绝对路径”的安全约束。- const absPath = decoded.replace(/^\/+([A-Za-z]:[\\/])/, '$1');+ const absPath = normalizeXdtAbsPath(decoded);const isWindowsAbsolute = /^[A-Za-z]:[\\/]/.test(absPath) || /^\\\\[^\\]/.test(absPath);if (absPath.includes('\0') || (!path.isAbsolute(absPath) && !isWindowsAbsolute)) {throw new Error('xdt-file URL must contain an absolute path');@@ -177,7 +178,7 @@ export interface OutboundResult {/** 文本里是否存在任何托管媒体出站引用(快速前置判断, 避免无谓的收集开销)。 */export function hasOutboundRefs(text: string): boolean {- // 双协议:老 xdt-image + 媒体总仓 cindy-media(XDT_IMAGE_REGEX 同口径)——+ // 双协议:老 xdt-image + 媒体总仓 cindy-media(与 @cindy/im 解析器同口径)——// 漏了 cindy-media 会让只含总仓图的回帖跳过附件收集,图静默丢失。return (text.includes('xdt-image://') || text.includes('cindy-media://') || text.includes('xdt-file://')@@ -274,10 +275,10 @@ export async function collectOutboundAttachments(// 1. 图片: 文本引用 + tool_result 旁路, 按 absPath 去重(模型常重复引用)const imageAbsPaths: string[] = [];const seenImage = new Set<string>();- for (const m of refScanText.matchAll(XDT_IMAGE_REGEX)) {+ for (const ref of collectXdtImageRefs(refScanText)) {try {- const { absPath } = deps.resolveImageUrl(m[2]);- imageAbsPathByUrl.set(m[2], absPath);+ const { absPath } = deps.resolveImageUrl(ref.url);+ imageAbsPathByUrl.set(ref.url, absPath);if (!seenImage.has(absPath)) {seenImage.add(absPath);imageAbsPaths.push(absPath);@@ -285,7 +286,7 @@ export async function collectOutboundAttachments(} catch (err) {skipped += 1;deps.log.warn(- `resolve xdt-image failed (${m[2]}): ${err instanceof Error ? err.message : String(err)}`,+ `resolve xdt-image failed (${ref.url}): ${err instanceof Error ? err.message : String(err)}`,);}}@@ -301,8 +302,8 @@ export async function collectOutboundAttachments(// 2. 文件引用(去重同上)const seenFile = new Set<string>();- for (const m of refScanText.matchAll(XDT_FILE_REGEX)) {- const url = m[2];+ for (const ref of collectXdtFileRefs(refScanText)) {+ const url = ref.url;if (fileAbsPathByUrl.has(url)) continue;let absPath: string;try {@@ -325,20 +326,19 @@ export async function collectOutboundAttachments(// 3. 正文变换: 只有确实收集成功的引用才声称已发送。失败项保留可读标签,// 并在末尾附加显式警告,避免“正文剥掉了、附件也没到”的静默丢失。- const transformed = finalText- .replace(XDT_IMAGE_REGEX, (_m, alt: string, url: string) => {+ const transformed = transformXdtRefs(finalText, {+ image: ({ alt, url }) => {const absPath = imageAbsPathByUrl.get(url);if (absPath !== undefined && sentImageAbsPaths.has(absPath)) {return alt ? `🖼️ _${alt}(已作为附件发送)_` : '';}return alt ? `🖼️ _${alt}_` : '';- })- .replace(XDT_FILE_REGEX, (_m, label: string, url: string) => {+ },+ file: ({ alt, url }) => {const absPath = fileAbsPathByUrl.get(url);- return absPath !== null && absPath !== undefined && sentFileAbsPaths.has(absPath)- ? ''- : label;- });+ return absPath !== null && absPath !== undefined && sentFileAbsPaths.has(absPath) ? '' : alt;+ },+ });const warning =skipped > 0? `⚠️ Attachment delivery incomplete: ${skipped} item${skipped === 1 ? '' : 's'} could not be sent.`diff --git a/packages/lizi-im/src/__tests__/xdtRefs.test.ts b/packages/lizi-im/src/__tests__/xdtRefs.test.tsindex f04e167a89..0b28cb4470 100644--- a/packages/lizi-im/src/__tests__/xdtRefs.test.ts+++ b/packages/lizi-im/src/__tests__/xdtRefs.test.ts@@ -9,11 +9,14 @@ import { describe, it, expect } from 'vitest';import {classifyXdtOnly,collectXdtFileLinks,+ collectXdtFileRefs,collectXdtImageRefs,collectXdtImageUrls,+ normalizeXdtAbsPath,stripXdtFileLinks,stripXdtForStreaming,stripXdtImageLinks,+ transformXdtRefs,xdtFileUrlToAbsPath,} from '../xdtRefs.js';@@ -79,10 +82,125 @@ describe('linear managed-media parser', () => {expect(stripXdtForStreaming(nearUrl)).toBe(nearUrl);});+ it('大量嵌套未闭合候选 + 单个尾括号仍是线性(#1856 review 第三轮: 畸形恢复曾退化成 Θ(n²))', () => {+ // 每次恢复把 cursor 挪到下一个 '[', 无缓存实现让 N 个候选各自重扫同一个+ // 尾括号。实测(本机, N=200k / 3.2MB): 平方实现 ~4.8s, 线性实现 ~31ms ——+ // 靠本用例 2s 的超时预算把回归钉死, 而不是脆弱的墙钟断言。+ const nested = '[a](xdt-file://x'.repeat(200_000) + ')';++ expect(collectXdtFileRefs(nested)).toEqual([+ {+ alt: 'a',+ url: 'xdt-file://x',+ start: nested.lastIndexOf('['),+ end: nested.length,+ },+ ]);+ expect(stripXdtForStreaming(nested).endsWith('[📎 a · 准备发送...]')).toBe(true);+ }, 2_000);++ it('URL 段密集非起点方括号 + 单个尾括号: 照常收下, 不逐个重扫', () => {+ const url = `xdt-file://${'[x]'.repeat(30_000)}`;+ const dense = `[a](${url})`;++ expect(collectXdtFileRefs(dense)).toEqual([{ alt: 'a', url, start: 0, end: dense.length }]);+ expect(stripXdtForStreaming(dense)).toBe('[📎 a · 准备发送...]');+ });+it('still finds a valid ref after malformed Markdown', () => {const text = `broken [ prefix `;expect(collectXdtImageUrls(text)).toEqual([BLOB]);expect(stripXdtImageLinks(text)).toBe('broken [ prefix ');});++ it('未闭合 file 引用在前不吞后续合法 image(#1856 review P2 回归)', () => {+ // 畸形候选一路扫到 image 的右括号, 修复前 good 图整段被吞:+ // 收集为 0、transform 把含合法引用的整段错误改写。+ const text = `[bad](xdt-file://unterminated  尾巴`;++ expect(collectXdtImageUrls(text)).toEqual([BLOB]);+ expect(collectXdtFileRefs(text)).toEqual([]);+ expect(stripXdtImageLinks(text)).toBe('[bad](xdt-file://unterminated 尾巴');+ expect(transformXdtRefs(text, { image: ({ alt }) => `<${alt}>` })).toBe(+ '[bad](xdt-file://unterminated <good> 尾巴',+ );+ });++ it('未闭合 image 引用在前不吞后续合法 file(同根因对称面)', () => {+ const file = 'xdt-file:///tmp/r.txt';+ const text = ``;++ expect(collectXdtImageUrls(text)).toEqual([]);+ expect(collectXdtFileLinks(text)).toEqual([{ alt: 'report', absPath: '/tmp/r.txt' }]);+ expect(stripXdtFileLinks(text)).toBe(';+ });++ it('URL 里的方括号文件名保留(#1856 review P1: 畸形恢复判据收窄到"真引用起点")', () => {+ // 早先"URL 段出现任意 '[' 即放弃"过宽, 把这类合法文件名静默丢掉。+ expect(collectXdtFileLinks('[f](xdt-file:///tmp/a[1].txt)')).toEqual([+ { alt: 'f', absPath: '/tmp/a[1].txt' },+ ]);+ // %5B 编码写法继续可用。+ expect(collectXdtFileLinks('[f](xdt-file:///tmp/a%5B1%5D.txt)')).toEqual([+ { alt: 'f', absPath: '/tmp/a[1].txt' },+ ]);+ });++ it('方括号文件名的中文 alt 引用同样收集(Codex 原例)', () => {+ expect(collectXdtFileLinks('[报告](xdt-file:///tmp/report[final].pdf)')).toEqual([+ { alt: '报告', absPath: '/tmp/report[final].pdf' },+ ]);+ });++ it('image URL 含方括号也保留(两类引用同一判据)', () => {+ expect(collectXdtImageUrls('')).toEqual(['xdt-image://x[1].png']);+ });++ it('URL 段先出现非起点方括号、后跟真引用: 仍在真起点处恢复', () => {+ // 两类边界不互相回归: 非起点的 '[note]' 不触发放弃, 真引用起点仍要救回来。+ const text = `[bad](xdt-file://unterminated [note] `;++ expect(collectXdtImageUrls(text)).toEqual([BLOB]);+ expect(collectXdtFileRefs(text)).toEqual([]);+ expect(stripXdtImageLinks(text)).toBe('[bad](xdt-file://unterminated [note] ');+ });+});++describe('collectXdtFileRefs(hook 出站收敛,#1855)', () => {+ it('按源顺序返回未解码 URL,不去重(URL 维度记账由调用方做)', () => {+ const file = 'xdt-file:///tmp/a%20b.txt';+ const text = `一份 [报告](${file}) 再引一次 [同一份](${file})`;+ const refs = collectXdtFileRefs(text);+ expect(refs.map((r) => r.url)).toEqual([file, file]);+ expect(refs.map((r) => r.alt)).toEqual(['报告', '同一份']);+ expect(refs[0].start).toBe(text.indexOf('[报告]'));+ });++ it('图片语法 + xdt-file 协议不算文件引用(与个人渠道收口同口径)', () => {+ expect(collectXdtFileRefs('')).toEqual([]);+ });+});++describe('transformXdtRefs(收口正文改写共享原语)', () => {+ it('图片/文件各自按引用逐个替换,缺省的类别原样保留', () => {+ const file = 'xdt-file:///tmp/r.txt';+ const text = `头  中 [报告](${file}) 尾`;+ expect(+ transformXdtRefs(text, {+ image: ({ alt }) => `<img:${alt}>`,+ file: ({ alt }) => `<file:${alt}>`,+ }),+ ).toBe('头 <img:猫> 中 <file:报告> 尾');+ expect(transformXdtRefs(text, { image: () => '' })).toBe(`头 中 [报告](${file}) 尾`);+ expect(transformXdtRefs(text, {})).toBe(text);+ });+});++describe('normalizeXdtAbsPath(Windows 前缀归一化唯一实现)', () => {+ it('剥掉盘符路径前导斜杠,Unix 绝对路径不动', () => {+ expect(normalizeXdtAbsPath('/C:\\Users\\x\\f.txt')).toBe('C:\\Users\\x\\f.txt');+ expect(normalizeXdtAbsPath('//C:/Users/x/f.txt')).toBe('C:/Users/x/f.txt');+ expect(normalizeXdtAbsPath('/home/u/f.txt')).toBe('/home/u/f.txt');+ });});diff --git a/packages/lizi-im/src/index.ts b/packages/lizi-im/src/index.tsindex e8f0f28910..f8977e12f8 100644--- a/packages/lizi-im/src/index.ts+++ b/packages/lizi-im/src/index.ts@@ -53,7 +53,15 @@ export {chunkWecomMarkdown,escapeWecomMarkdown,} from './wecom/codec.js';-export { stripXdtFileLinks, stripXdtImageLinks } from './xdtRefs.js';+export {+ collectXdtFileRefs,+ collectXdtImageRefs,+ normalizeXdtAbsPath,+ stripXdtFileLinks,+ stripXdtImageLinks,+ transformXdtRefs,+} from './xdtRefs.js';+export type { XdtFileRef, XdtImageRef, XdtRefTransform } from './xdtRefs.js';export {decodeLaneUserId as decodeTelegramLaneUserId,encodeLaneUserId as encodeTelegramLaneUserId,diff --git a/packages/lizi-im/src/xdtRefs.ts b/packages/lizi-im/src/xdtRefs.tsindex 9d8127e6e7..1c3e157f04 100644--- a/packages/lizi-im/src/xdtRefs.ts+++ b/packages/lizi-im/src/xdtRefs.ts@@ -25,6 +25,32 @@ interface ParsedXdtRef extends XdtImageRef {kind: 'image' | 'file';}+/**+ * 判定 text[openBracket] 处是否**直接**开始一个 managed-media 引用。判据与+ * parseXdtRefs 主循环逐条同语义(前一字符 '!' 决定 image、alt 扫描遇 '[' 即+ * 放弃、']( ' 收尾、按 image 与否认 scheme), 只读、无副作用。+ *+ * "直接"很关键: alt 里再出现 '[' 时返回 false —— 那个更内层的 '[' 才可能是+ * 起点, 外层的恢复循环会继续迭代到它。+ */+function refStartsAt(text: string, openBracket: number): boolean {+ const image = openBracket > 0 && text[openBracket - 1] === '!';+ let altEnd = openBracket + 1;+ while (+ altEnd < text.length &&+ text[altEnd] !== '[' &&+ !(text[altEnd] === ']' && text[altEnd + 1] === '(')+ ) {+ altEnd += 1;+ }+ if (altEnd >= text.length || text[altEnd] === '[') return false;++ const urlStart = altEnd + 2;+ return image+ ? text.startsWith('xdt-image://', urlStart) || text.startsWith('cindy-media://', urlStart)+ : text.startsWith('xdt-file://', urlStart);+}+/*** Parse managed-media Markdown in one forward pass. Model output is* uncontrolled input, so this deliberately avoids the former global regexes:@@ -33,6 +59,19 @@ interface ParsedXdtRef extends XdtImageRef {function parseXdtRefs(text: string): ParsedXdtRef[] {const refs: ParsedXdtRef[] = [];let cursor = 0;+ // ')' 查找的单调缓存。搜索起点跨候选严格递增(scheme 不匹配的路径根本不查+ // 括号; 恢复后新候选的 urlStart 在恢复点之后; 收下引用后 cursor = endParen+ // + 1 > 上次命中), 且 [上次起点, 上次命中) 区间内必无 ')' —— 所以起点仍+ // ≤ 上次命中时可直接复用, 与每次重新 indexOf 等价, 每个文本位置至多被扫+ // 一次。没有它, 形如 '[a](xdt-file://x'.repeat(N) + ')' 的对抗输入会让 N 个+ // 候选各自重扫同一个尾括号, 退化成 Θ(n²)(#1856 review 第三轮: 这条平方+ // 向量是畸形恢复引入的, 收敛前的解析器一次扫到 ')' 就整体跳过)。+ let cachedParen = -2; // -2 = 尚无缓存+ const nextParen = (from: number): number => {+ if (cachedParen >= from) return cachedParen;+ cachedParen = text.indexOf(')', from);+ return cachedParen;+ };while (cursor < text.length) {const openBracket = text.indexOf('[', cursor);@@ -73,8 +112,36 @@ function parseXdtRefs(text: string): ParsedXdtRef[] {continue;}- const endParen = text.indexOf(')', urlStart + scheme.length);+ const endParen = nextParen(urlStart + scheme.length);if (endParen === -1) break;+ // 畸形恢复(#1856 review P2): 未闭合引用会让本候选一路扫到**下一个**引用+ // 的右括号, 把后续合法引用整段吞进自己的 URL —— 收集丢附件, transform 还会+ // 把整段错误改写。判据是 URL 段里出现**构成引用起点**的 '['(#1856 review+ // P1 收窄: 早先"出现任意 '[' 就放弃"过宽, 把合法方括号文件名如+ // `[f](xdt-file:///tmp/report[final].pdf)` 静默丢掉 —— 旧正则实现与收敛前+ // 的解析器都接受这类 URL)。命中即放弃本候选、从那个 '[' 恢复前向扫描;+ // 一个都不命中就照常收下, URL 里的 '['/']' 原样保留。+ //+ // cursor 仍严格前进: recovery ≥ urlStart + scheme.length > openBracket。+ // 恢复判定本身是线性(本解析器防 ReDoS/防回扫的前提): refStartsAt 的 alt+ // 扫描天然停在下一个 '[', 一段里相邻 '[' 的间距之和 ≤ 段长; 且恢复点是本段+ // 第一个引用起点, 下一候选的 URL 段从它之后才开始, 各候选扫过的区间互不+ // 重叠。恢复带来的 ')' 重复定位由上面的 nextParen 单调缓存兜住。+ let recovery = -1;+ for (+ let bracket = text.indexOf('[', urlStart + scheme.length);+ bracket !== -1 && bracket < endParen;+ bracket = text.indexOf('[', bracket + 1)+ ) {+ if (refStartsAt(text, bracket)) {+ recovery = bracket;+ break;+ }+ }+ if (recovery !== -1) {+ cursor = recovery;+ continue;+ }if (endParen > urlStart + scheme.length) {refs.push({kind: image ? 'image' : 'file',@@ -106,6 +173,19 @@ function replaceXdtRefs(return parts.join('');}+/**+ * 剥掉 Windows 盘符路径解码后残留的多余前导斜杠。+ *+ * 约定写法 xdt-file:///<绝对路径>:Unix 下剥协议后的首个 `/` 就是根;+ * Windows 盘符路径剥完剩 `/C:\...`(或 /C:/...),多余前导 `/` 会让下游+ * 存在性检查 / 目录白名单比对失败 → 文件静默丢失(2026-07-16 hook 渠道+ * 实踩)。这里是该归一化的唯一实现 —— hook-control/outbound.ts 的严格版+ * 解析(fail-closed 读盘校验)也消费它, 不再各持副本。+ */+export function normalizeXdtAbsPath(decoded: string): string {+ return decoded.replace(/^\/+([A-Za-z]:[\\/])/, '$1');+}+/** xdt-file://<absPath> → absPath (URL-decoded). */export function xdtFileUrlToAbsPath(url: string): string {const raw = url.replace(/^xdt-file:\/\//, '');@@ -115,11 +195,7 @@ export function xdtFileUrlToAbsPath(url: string): string {} catch {decoded = raw;}- // 约定写法 xdt-file:///<绝对路径>:Unix 下剥协议后的首个 `/` 就是根;- // Windows 盘符路径剥完剩 `/C:\...`(或 /C:/...),多余前导 `/` 会让下游- // 存在性检查 / 目录白名单比对失败 → 文件静默丢失(2026-07-16 hook 渠道- // 实踩)。与 hook-control/outbound.ts 的副本同步修改。- return decoded.replace(/^\/+([A-Za-z]:[\\/])/, '$1');+ return normalizeXdtAbsPath(decoded);}/** Replace xdt-* refs with placeholder text suitable for intermediate frames. */@@ -183,6 +259,43 @@ export function collectXdtImageRefs(text: string): XdtImageRef[] {.map(({ alt, url, start, end }) => ({ alt, url, start, end }));}+/** 文件引用(与 XdtImageRef 同形, url 未解码 —— 调用方自行决定解码与校验策略)。 */+export type XdtFileRef = XdtImageRef;++/**+ * Collect xdt-file refs in source order, including the raw URL. 与+ * collectXdtFileLinks 的差异: 不解码路径、不去重 —— 给需要按 URL 维度+ * 记账 / 自带严格路径校验的调用方(hook-control/outbound)用。+ */+export function collectXdtFileRefs(text: string): XdtFileRef[] {+ return parseXdtRefs(text)+ .filter((ref) => ref.kind === 'file')+ .map(({ alt, url, start, end }) => ({ alt, url, start, end }));+}++export interface XdtRefTransform {+ /** 图片引用替换文本; 缺省 = 该类引用原样保留。 */+ image?: (ref: XdtImageRef) => string;+ /** 文件引用替换文本; 缺省 = 该类引用原样保留。 */+ file?: (ref: XdtFileRef) => string;+}++/**+ * 单遍变换文本里的托管媒体引用(收口正文改写的共享原语)。+ * 与 strip 系列的差异: 替换文案由调用方按引用逐个决定(如"已作为附件+ * 发送" vs 保留可读标签), 而不是固定剥离。+ */+export function transformXdtRefs(text: string, transform: XdtRefTransform): string {+ const refs = parseXdtRefs(text).filter((ref) =>+ ref.kind === 'image' ? transform.image !== undefined : transform.file !== undefined,+ );+ return replaceXdtRefs(text, refs, (ref) =>+ ref.kind === 'image'+ ? transform.image!({ alt: ref.alt, url: ref.url, start: ref.start, end: ref.end })+ : transform.file!({ alt: ref.alt, url: ref.url, start: ref.start, end: ref.end }),+ );+}+/** Collect unique xdt-image URLs from text. */export function collectXdtImageUrls(text: string): string[] {const set = new Set<string>();