source-reference.ts 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434
  1. import { createHash } from 'node:crypto';
  2. import nodePath from 'node:path';
  3. import { createSourceReferenceMarkerBlock } from './source-reference-marker.js';
  4. import {
  5. buildToolCallCitationId,
  6. collapseAdjacentDuplicateFileCitations,
  7. collectUsedWebEvidenceIds,
  8. resolveKnownCitationAlias,
  9. } from '@mavis/agent-runtime';
  10. import type {
  11. AfterLlmCallHandler,
  12. AgentExtension,
  13. AfterToolCallHandler,
  14. TurnAssemblyCtx,
  15. } from '@mavis/agent-runtime';
  16. import {
  17. filePathsMatch,
  18. generatedFilePathsForToolCall,
  19. isGeneratedFileReference,
  20. isTemporaryOrInternalFilePath,
  21. knownFileReferencesUsedByShellCommand,
  22. normalizeFilePath,
  23. recordGeneratedFilePaths,
  24. registeredAssetPathsFromShellCommand,
  25. workspaceFilePathsFromShellCommand,
  26. } from './source-reference-files.js';
  27. import {
  28. escapeMarkdownLabel,
  29. invokedToolName,
  30. normalizeToolName,
  31. parseMcpToolName,
  32. readNonEmptyString,
  33. readRecord,
  34. safeHttpUrl,
  35. } from './source-reference-utils.js';
  36. import {
  37. isExplicitWebSourceToolCall,
  38. isPlatformWebSourceToolCall,
  39. persistedWebReference,
  40. readToolResultText,
  41. renderWebFetchSourceMarker,
  42. webFetchSourceReferenceForToolResult,
  43. webSourceReferencesForToolResult,
  44. } from './source-reference-web.js';
  45. export const SOURCE_REFERENCE_DETAILS_KEY = 'source_references';
  46. export const SOURCE_REFERENCE_MARKER_TAG = 'source_reference';
  47. const CODE_FILE_EXTENSION_RE =
  48. /\.(?:astro|bash|bat|c|cc|cjs|clj|cljs|cljc|cmd|cpp|cs|css|cts|cxx|dart|elm|erl|ex|exs|fish|fs|fsi|fsx|go|gradle|groovy|h|handlebars|hbs|hcl|hh|hpp|hrl|htm|html|java|jl|js|json|jsx|kt|kts|less|lua|m|mjs|mm|mts|nim|php|pl|pm|proto|ps1|py|pyi|r|rb|rs|sass|scala|scss|sh|sol|sql|svelte|swift|tf|thrift|toml|ts|tsx|vb|vbs|vue|xml|yaml|yml|zig|zsh)$/iu;
  49. const CODE_FILE_BASENAME_RE =
  50. /(?:^|[\\/])(?:cmakelists\.txt|dockerfile|gemfile|jenkinsfile|makefile|rakefile)$/iu;
  51. export interface ToolSourceReference {
  52. readonly version: 1;
  53. readonly type: string;
  54. readonly source_id: string;
  55. readonly citation_id?: string;
  56. readonly citation_aliases?: readonly string[];
  57. readonly name: string;
  58. readonly tool_call_id: string;
  59. readonly tool_name: string;
  60. readonly result_path?: string;
  61. readonly provider?: string;
  62. readonly icon_url?: string;
  63. readonly url?: string;
  64. readonly path?: string;
  65. readonly citation_mode?: 'implicit';
  66. }
  67. export interface ToolSourceAdapterInput {
  68. readonly toolCallId: string;
  69. readonly toolName: string;
  70. readonly args: unknown;
  71. readonly result: {
  72. readonly content: readonly unknown[];
  73. readonly details?: unknown;
  74. };
  75. readonly isError: boolean;
  76. readonly turn: TurnAssemblyCtx;
  77. }
  78. export interface ToolSourceAdapter {
  79. readonly id: string;
  80. adapt(
  81. input: ToolSourceAdapterInput,
  82. ): ToolSourceReference | readonly ToolSourceReference[] | null | undefined;
  83. }
  84. export interface SourceReferenceExtensionOptions {
  85. readonly adapters?: readonly ToolSourceAdapter[];
  86. readonly id?: string;
  87. readonly description?: string;
  88. readonly resolveFileSourcePath?: FileSourcePathResolver;
  89. }
  90. export interface FileSourcePathResolution {
  91. readonly path: string;
  92. readonly name?: string;
  93. readonly resultPath?: string;
  94. readonly citationMode?: 'implicit';
  95. }
  96. export type FileSourcePathResolver = (input: {
  97. readonly path: string;
  98. readonly toolName: string;
  99. readonly turn: TurnAssemblyCtx;
  100. readonly origin: 'tool-argument' | 'shell-argument' | 'diff-result';
  101. }) => FileSourcePathResolution | undefined;
  102. interface CitationAliasState {
  103. /** Runtime map for model-visible short IDs, scoped to one turn. */
  104. readonly citationAliases: Map<string, string>;
  105. readonly citationIdsByAlias: Map<string, string>;
  106. }
  107. interface TurnSourceState extends CitationAliasState {
  108. readonly references: Map<string, ToolSourceReference>;
  109. readonly evidence: Map<string, string>;
  110. readonly generatedFilePaths: Set<string>;
  111. retryAttempted: boolean;
  112. retryAssetMarkup: readonly string[];
  113. retryDraft: string;
  114. }
  115. const MAX_SOURCE_EVIDENCE_CHARS = 200_000;
  116. const MAX_HISTORICAL_FILE_REFERENCES = 32;
  117. const MAX_HISTORICAL_MESSAGES = 200;
  118. /**
  119. * Standardizes provenance after a tool has completed. The normalized metadata
  120. * stays in ToolResult.details for durable access-history reconstruction. Every
  121. * WebSearch results already contain their exact URLs, so they are persisted
  122. * without duplicating every result into an extra model-visible marker. WebFetch
  123. * alone receives one compact final-URL marker because redirects can make that
  124. * URL unavailable in the original ToolResult. Safe legacy links and malformed
  125. * File tags are normalized deterministically. App/MCP candidates use a
  126. * target-only marker plus a six-character, per-turn hash; the hash is expanded
  127. * back to the canonical ID before validation. If a terminal answer
  128. * demonstrably reuses App/MCP/File/Web evidence but omits its candidate reference,
  129. * one bounded model retry asks for a citation-correct version; unused source
  130. * access remains history only.
  131. */
  132. export function sourceReferenceExtension(
  133. options: SourceReferenceExtensionOptions = {},
  134. ): AgentExtension {
  135. const adapters = options.adapters ?? [
  136. mcpSourceAdapter,
  137. appSourceAdapter,
  138. createFileSourceAdapter(options.resolveFileSourcePath),
  139. ];
  140. const turnSources = new Map<string, TurnSourceState>();
  141. const afterToolCall: AfterToolCallHandler = (toolContext, _signal, turnCtx) => {
  142. if (toolContext.isError) return undefined;
  143. const state = sourceStateFor(turnSources, turnCtx);
  144. const adapterInput: ToolSourceAdapterInput = {
  145. toolCallId: toolContext.toolCall.id,
  146. toolName: toolContext.toolCall.name,
  147. args: toolContext.args,
  148. result: toolContext.result,
  149. isError: toolContext.isError,
  150. turn: turnCtx,
  151. };
  152. recordGeneratedFilePaths(state, generatedFilePathsForToolCall(adapterInput));
  153. const adaptedReferences = adapters.flatMap((adapter) => {
  154. const adapted = adapter.adapt(adapterInput);
  155. const adapterReferences = Array.isArray(adapted) ? adapted : adapted ? [adapted] : [];
  156. return adapterReferences
  157. .map((reference) => withCallCitationId(reference))
  158. .filter((reference) => !isGeneratedFileReference(reference, state.generatedFilePaths));
  159. });
  160. const reusedFileReferences = knownFileReferencesUsedByShellCommand(
  161. adapterInput,
  162. state.references.values(),
  163. ).filter((reference) => !isGeneratedFileReference(reference, state.generatedFilePaths));
  164. const references = Array.from(
  165. new Map(
  166. [...adaptedReferences, ...reusedFileReferences].map((reference) => [
  167. citationIdFor(reference),
  168. reference,
  169. ]),
  170. ).values(),
  171. );
  172. const hasAppReference = references.some((reference) => reference.type === 'app');
  173. // A successful fetch result is identified by the HTTP(S) URL it reports,
  174. // not by a particular runtime/tool wrapper name. Explicit App metadata
  175. // remains authoritative for connector-owned results.
  176. const directWebReference = hasAppReference
  177. ? undefined
  178. : webFetchSourceReferenceForToolResult(adapterInput);
  179. const { references: webReferences, markerReferences: webMarkerReferences } =
  180. directWebReference ||
  181. references.length === 0 ||
  182. (!hasAppReference && isExplicitWebSourceToolCall(adapterInput.toolName, adapterInput.args)) ||
  183. isPlatformWebSourceToolCall(adapterInput.toolName, adapterInput.args)
  184. ? webSourceReferencesForToolResult(adapterInput, directWebReference)
  185. : { references: [], markerReferences: [] };
  186. const persistedWebReferences = webReferences.map((reference) =>
  187. persistedWebReference(adapterInput, reference),
  188. );
  189. if (references.length === 0 && webReferences.length === 0) return undefined;
  190. const modelReferences = references.map((reference) => withModelCitationAlias(reference, state));
  191. const persistedReferences = [...modelReferences, ...persistedWebReferences];
  192. const details =
  193. persistedReferences.length > 0
  194. ? mergeSourceReferenceDetails(toolContext.result.details, persistedReferences)
  195. : toolContext.result.details;
  196. const evidence = readToolResultText(toolContext.result.content);
  197. for (const reference of modelReferences) {
  198. const citationId = citationIdFor(reference);
  199. state.references.set(citationId, reference);
  200. state.evidence.set(citationId, appendEvidence(state.evidence.get(citationId), evidence));
  201. }
  202. persistedWebReferences.forEach((webReference, index) => {
  203. const citationId = citationIdFor(webReference);
  204. const webEvidence = webReferences[index]?.evidence ?? evidence;
  205. state.references.set(citationId, webReference);
  206. state.evidence.set(citationId, appendEvidence(state.evidence.get(citationId), webEvidence));
  207. });
  208. const markerText = [
  209. ...modelReferences.map((reference) => renderSourceReferenceMarker(reference, state)),
  210. ...webMarkerReferences.map(renderWebFetchSourceMarker),
  211. ]
  212. .filter((marker): marker is string => Boolean(marker))
  213. .join('\n');
  214. return {
  215. ...(markerText
  216. ? {
  217. content: [
  218. ...toolContext.result.content,
  219. createSourceReferenceMarkerBlock(`\n${markerText}\n`),
  220. ],
  221. }
  222. : {}),
  223. details,
  224. };
  225. };
  226. const afterLlmCall: AfterLlmCallHandler = (event, turnCtx) => {
  227. if (event.message.stopReason === 'error' || event.message.stopReason === 'aborted') {
  228. return undefined;
  229. }
  230. if (event.message.content.some((block) => block.type === 'toolCall')) return undefined;
  231. const text = readAssistantText(event.message.content);
  232. if (!text.trim()) return undefined;
  233. // Review owns validation/retries and file targets for these protocol documents.
  234. // Citation rewriting must not mutate their attributes or retry a finalized review.
  235. if (/<\s*(?:annotation-result|review-candidates|review-candidate-corrections)(?=[\s/>])/iu.test(text)) {
  236. return undefined;
  237. }
  238. const state = sourceStateFor(turnSources, turnCtx);
  239. if (state?.retryAttempted && isCitationRetryPromptLeak(text)) {
  240. const fallback = restoreMissingAssetMarkup(state.retryDraft, state.retryAssetMarkup);
  241. return fallback === text ? undefined : { type: 'replaceText', text: fallback };
  242. }
  243. const retrySafeText = state?.retryAttempted
  244. ? restoreMissingAssetMarkup(text, state.retryAssetMarkup)
  245. : text;
  246. const safeSourceText = removeDisallowedFileCitations(retrySafeText);
  247. if (!state) {
  248. return safeSourceText === text ? undefined : { type: 'replaceText', text: safeSourceText };
  249. }
  250. const allReferences = Array.from(state.references.values());
  251. const normalizedCitationTags = normalizeMisclassifiedSourceFilePathTags(
  252. normalizeFilePathCitationTags(safeSourceText, allReferences),
  253. allReferences,
  254. state.evidence,
  255. );
  256. const normalizedSourceText = removeUnbackedFileCitations(
  257. normalizeFileCitationLabels(
  258. normalizeBareToolSourceLines(
  259. normalizeExplicitSourceLinks(
  260. normalizedCitationTags,
  261. allReferences.filter(
  262. (reference) => reference.type === 'app' || reference.type === 'mcp',
  263. ),
  264. state.evidence,
  265. state.citationIdsByAlias,
  266. ),
  267. ),
  268. allReferences,
  269. ),
  270. allReferences,
  271. );
  272. const sectionDeduplicatedText = state.retryAttempted
  273. ? collapseRepeatedCitationTargetsByMarkdownSection(normalizedSourceText, allReferences)
  274. : normalizedSourceText;
  275. const projectedSourceText = collapseRepeatedPresentedSourceLists(
  276. sectionDeduplicatedText,
  277. allReferences,
  278. );
  279. const usedWebEvidenceIds = collectUsedWebEvidenceIds(projectedSourceText, state.evidence);
  280. const usedSources = allReferences.filter((reference) => {
  281. const citationId = citationIdFor(reference);
  282. if (reference.type === 'web') return usedWebEvidenceIds.has(citationId);
  283. return answerUsesReferenceEvidence(
  284. reference,
  285. projectedSourceText,
  286. state.evidence.get(citationId) ?? '',
  287. competingEvidenceForReference(reference, allReferences, state.evidence),
  288. allReferences,
  289. );
  290. });
  291. const normalizedText = collapseAdjacentDuplicateFileCitations(
  292. normalizeFileCitationLineAddresses(
  293. localizeMentionedFileCitations(
  294. unwrapSyntheticFileMentionMarkdownLinks(projectedSourceText, usedSources),
  295. usedSources,
  296. ),
  297. usedSources,
  298. ),
  299. );
  300. // Missing citations are repaired only for positively identified usage.
  301. // Returning search candidates does not mean the answer adopted them.
  302. const citationRequiredSources = usedSources;
  303. const missingUsedSources = citationRequiredSources.filter(
  304. (reference) => !answerCitesReference(normalizedText, reference),
  305. );
  306. const webBackfilledText = appendMissingWebSourceSummary(normalizedText, missingUsedSources);
  307. const sourcesStillMissing = citationRequiredSources.filter(
  308. (reference) => !answerCitesReference(webBackfilledText, reference),
  309. );
  310. if (sourcesStillMissing.length > 0 && !state.retryAttempted) {
  311. state.retryAttempted = true;
  312. state.retryAssetMarkup = collectAssetMarkupSegments(webBackfilledText);
  313. state.retryDraft = webBackfilledText;
  314. return {
  315. type: 'retry',
  316. reason: 'missing_source_citation',
  317. prompt: buildCitationRetryPrompt(sourcesStillMissing, webBackfilledText, state),
  318. };
  319. }
  320. return webBackfilledText === text
  321. ? undefined
  322. : { type: 'replaceText', text: webBackfilledText };
  323. };
  324. return {
  325. id: options.id ?? 'source-reference',
  326. description:
  327. options.description ??
  328. 'Standardize source history and validate evidence-backed App/MCP/File/Web citations.',
  329. init(api) {
  330. api.on('after_tool_call', afterToolCall);
  331. api.on('after_llm_call', afterLlmCall);
  332. api.on('turn_end', (_event, turnCtx) => {
  333. turnSources.delete(turnKey(turnCtx));
  334. });
  335. },
  336. };
  337. }
  338. export const mcpSourceAdapter: ToolSourceAdapter = {
  339. id: 'mcp',
  340. adapt(input) {
  341. const details = readRecord(input.result.details);
  342. const invokedName = invokedToolName(input.args);
  343. const parsed =
  344. parseMcpToolName(input.toolName) ?? (invokedName ? parseMcpToolName(invokedName) : undefined);
  345. if (details?.mcp === undefined && !parsed) return null;
  346. const rawServer = readNonEmptyString(details?.server) ?? parsed?.server;
  347. const tool = readNonEmptyString(details?.tool) ?? parsed?.tool ?? invokedToolName(input.args);
  348. if (!rawServer || isWebSearchMcp(rawServer, tool, input.toolName, input.args)) return null;
  349. const server = canonicalMcpServerName(rawServer);
  350. return {
  351. version: 1,
  352. type: 'mcp',
  353. source_id: `mcp:${Buffer.from(server, 'utf8').toString('base64url')}`,
  354. name: server,
  355. ...(rawServer === server ? {} : { provider: rawServer }),
  356. tool_call_id: input.toolCallId,
  357. tool_name: tool ?? input.toolName,
  358. result_path: details?.mcp === undefined ? '$' : 'details.mcp',
  359. };
  360. },
  361. };
  362. export const fileSourceAdapter: ToolSourceAdapter = createFileSourceAdapter();
  363. export const appSourceAdapter: ToolSourceAdapter = {
  364. id: 'app',
  365. adapt(input) {
  366. const details = readRecord(input.result.details);
  367. if (details?.kind === 'skill') return null;
  368. const app = readRecord(details?.app);
  369. const invokedName = invokedToolName(input.args);
  370. const connector =
  371. parseConnectorToolName(input.toolName) ??
  372. (invokedName ? parseConnectorToolName(invokedName) : undefined);
  373. const provider = readNonEmptyString(app?.provider) ?? connector?.provider;
  374. if (!provider) return null;
  375. if (normalizeToolName(provider) === 'matrix') return null;
  376. const name = readNonEmptyString(app?.display_name) ?? provider;
  377. const iconUrl = readNonEmptyString(app?.icon_url);
  378. const tool = readNonEmptyString(app?.tool) ?? connector?.tool ?? input.toolName;
  379. return {
  380. version: 1,
  381. type: 'app',
  382. source_id: `app:${Buffer.from(provider, 'utf8').toString('base64url')}`,
  383. name,
  384. provider,
  385. ...(iconUrl ? { icon_url: iconUrl } : {}),
  386. tool_call_id: input.toolCallId,
  387. tool_name: tool,
  388. result_path: 'content.0.text',
  389. };
  390. },
  391. };
  392. function parseConnectorToolName(value: string): { provider: string; tool: string } | undefined {
  393. const match = /^connector__(.+?)__(.+)$/u.exec(value.trim());
  394. const provider = match?.[1]?.trim();
  395. const tool = match?.[2]?.trim();
  396. return provider && tool ? { provider, tool } : undefined;
  397. }
  398. function mergeSourceReferenceDetails(
  399. details: unknown,
  400. references: readonly ToolSourceReference[],
  401. ): Record<string, unknown> {
  402. const record = readRecord(details);
  403. const base: Record<string, unknown> =
  404. record ?? (details === undefined ? {} : { original_details: details });
  405. const existing = Array.isArray(base[SOURCE_REFERENCE_DETAILS_KEY])
  406. ? base[SOURCE_REFERENCE_DETAILS_KEY]
  407. : [];
  408. return {
  409. ...base,
  410. [SOURCE_REFERENCE_DETAILS_KEY]: [...existing, ...references],
  411. };
  412. }
  413. function renderSourceReferenceMarker(
  414. reference: ToolSourceReference,
  415. citationAliasState: CitationAliasState,
  416. ): string | undefined {
  417. if (reference.type === 'file' && reference.path) {
  418. if (reference.citation_mode === 'implicit') return undefined;
  419. return `Citation candidate: [${escapeMarkdownLabel(reference.name)}](${sourceReferenceHref(citationIdFor(reference))})`;
  420. }
  421. const citationId = citationIdFor(reference);
  422. const modelCitationId =
  423. reference.type === 'app' || reference.type === 'mcp'
  424. ? shortCitationIdFor(citationId, citationAliasState)
  425. : citationId;
  426. return `Citation candidate: #mavis-source=${modelCitationId}`;
  427. }
  428. function withModelCitationAlias(
  429. reference: ToolSourceReference,
  430. citationAliasState: CitationAliasState,
  431. ): ToolSourceReference {
  432. if (reference.type !== 'app' && reference.type !== 'mcp') return reference;
  433. const citationId = citationIdFor(reference);
  434. const alias = shortCitationIdFor(citationId, citationAliasState);
  435. const aliases = Array.from(new Set([...(reference.citation_aliases ?? []), alias]));
  436. for (const existingAlias of reference.citation_aliases ?? []) {
  437. const normalizedAlias = existingAlias.trim().toLowerCase();
  438. if (!normalizedAlias) continue;
  439. if (!citationAliasState.citationIdsByAlias.has(normalizedAlias)) {
  440. citationAliasState.citationIdsByAlias.set(normalizedAlias, citationId);
  441. }
  442. }
  443. return { ...reference, citation_aliases: aliases };
  444. }
  445. const SHORT_CITATION_ID_LENGTH = 6;
  446. /**
  447. * Return a compact, collision-safe ID for the model while retaining the full
  448. * citation ID in the durable source reference and in the rendered answer.
  449. * Aliases are scoped to one turn, so a six-character hash is sufficient for
  450. * the model-facing candidate; the selected alias is also retained in source
  451. * metadata so the UI can resolve a short link after the turn is complete.
  452. */
  453. function shortCitationIdFor(citationId: string, state: CitationAliasState): string {
  454. const existing = state.citationAliases.get(citationId);
  455. if (existing) return existing;
  456. for (let attempt = 0; ; attempt += 1) {
  457. const seed = attempt === 0 ? citationId : `${citationId}\u0000${String(attempt)}`;
  458. const candidate = createHash('sha256')
  459. .update(seed, 'utf8')
  460. .digest('hex')
  461. .slice(0, SHORT_CITATION_ID_LENGTH);
  462. const owner = state.citationIdsByAlias.get(candidate);
  463. if (!owner || owner === citationId) {
  464. state.citationAliases.set(citationId, candidate);
  465. state.citationIdsByAlias.set(candidate, citationId);
  466. return candidate;
  467. }
  468. }
  469. }
  470. function withCallCitationId(reference: ToolSourceReference): ToolSourceReference {
  471. if (reference.citation_id || (reference.type !== 'app' && reference.type !== 'mcp')) {
  472. return reference;
  473. }
  474. return {
  475. ...reference,
  476. citation_id: buildToolCallCitationId(reference.source_id, reference.tool_call_id),
  477. };
  478. }
  479. function citationIdFor(reference: ToolSourceReference): string {
  480. return reference.citation_id ?? reference.source_id;
  481. }
  482. function isWebSearchMcp(
  483. server: string,
  484. tool: string | undefined,
  485. runtimeToolName: string,
  486. args: unknown,
  487. ): boolean {
  488. const invokedName = invokedToolName(args);
  489. const candidates = [server, tool, runtimeToolName, invokedName]
  490. .filter((value): value is string => Boolean(value))
  491. .map(normalizeToolName);
  492. const isWebSearchTool = candidates.some(
  493. (candidate) =>
  494. candidate === 'web_search' ||
  495. candidate.endsWith('__web_search') ||
  496. candidate === 'web_fetch' ||
  497. candidate.endsWith('__web_fetch'),
  498. );
  499. return isWebSearchTool && candidates.some((candidate) => candidate.includes('matrix'));
  500. }
  501. function canonicalMcpServerName(value: string): string {
  502. return value.replace(/_h[0-9a-f]{16,}$/iu, '').replaceAll('_', '-');
  503. }
  504. function isFileReadToolCall(value: string): boolean {
  505. const normalized = normalizeToolName(value);
  506. return normalized === 'read' || normalized === 'read_file';
  507. }
  508. function createFileSourceAdapter(
  509. resolveFileSourcePath?: FileSourcePathResolver,
  510. ): ToolSourceAdapter {
  511. return {
  512. id: 'file',
  513. adapt(input) {
  514. return fileSourcePaths(input, resolveFileSourcePath).map(
  515. ({ path, name, resultPath, citationMode }) => ({
  516. version: 1,
  517. type: 'file',
  518. source_id: `file:${Buffer.from(normalizeFilePath(path), 'utf8').toString('base64url')}`,
  519. name: name ?? fileDisplayName(path),
  520. tool_call_id: input.toolCallId,
  521. tool_name: input.toolName,
  522. result_path: resultPath ?? '$',
  523. path,
  524. ...(citationMode ? { citation_mode: citationMode } : {}),
  525. }),
  526. );
  527. },
  528. };
  529. }
  530. function fileSourcePaths(
  531. input: ToolSourceAdapterInput,
  532. resolveFileSourcePath: FileSourcePathResolver | undefined,
  533. ): FileSourcePathResolution[] {
  534. const args = readRecord(input.args);
  535. const toolName = input.toolName;
  536. const readPath = isFileReadToolCall(toolName)
  537. ? (readNonEmptyString(args?.path) ?? readNonEmptyString(args?.file_path))
  538. : undefined;
  539. const command =
  540. normalizeToolName(toolName) === 'bash' ? (readNonEmptyString(args?.command) ?? '') : '';
  541. const registeredAssetPaths = command ? registeredAssetPathsFromShellCommand(command) : [];
  542. const resolvableShellPaths =
  543. command && resolveFileSourcePath
  544. ? workspaceFilePathsFromShellCommand(command, input.turn.workspaceDir)
  545. : [];
  546. const diffResultPaths =
  547. command && resolveFileSourcePath ? codeFilePathsFromDiffResult(input, command) : [];
  548. const candidates = [
  549. ...(readPath
  550. ? [
  551. {
  552. path: readPath,
  553. requiresResolution: false,
  554. resultPath: '$',
  555. citationMode: undefined,
  556. origin: 'tool-argument' as const,
  557. },
  558. ]
  559. : []),
  560. ...registeredAssetPaths.map((path) => ({
  561. path,
  562. requiresResolution: false,
  563. resultPath: '$',
  564. citationMode: undefined,
  565. origin: 'tool-argument' as const,
  566. })),
  567. ...resolvableShellPaths.map((path) => ({
  568. path,
  569. requiresResolution: true,
  570. resultPath: '$',
  571. citationMode: undefined,
  572. origin: 'shell-argument' as const,
  573. })),
  574. ...diffResultPaths.map((path) => ({
  575. path,
  576. requiresResolution: true,
  577. resultPath: 'content.0.text',
  578. citationMode: 'implicit' as const,
  579. origin: 'diff-result' as const,
  580. })),
  581. ];
  582. const resolved = candidates.flatMap(
  583. ({ path, requiresResolution, resultPath, citationMode, origin }) => {
  584. const resolution = resolveFileSourcePath?.({
  585. path,
  586. toolName,
  587. turn: input.turn,
  588. origin,
  589. });
  590. if (requiresResolution && !resolution) return [];
  591. const source = { ...(resolution ?? { path }), resultPath, citationMode };
  592. return !safeHttpUrl(source.path) && !isTemporaryOrInternalFilePath(source.path)
  593. ? [source]
  594. : [];
  595. },
  596. );
  597. return Array.from(
  598. new Map(resolved.map((source) => [normalizeFilePath(source.path), source] as const)).values(),
  599. );
  600. }
  601. function codeFilePathsFromDiffResult(input: ToolSourceAdapterInput, command: string): string[] {
  602. const text = readToolResultText(input.result.content);
  603. if (!text) return [];
  604. const lines = text.split(/\r?\n/u);
  605. const hasUnifiedDiff = lines.some((line) => /^diff --git\s+/u.test(line));
  606. const normalizedCommand = command.toLocaleLowerCase();
  607. const isGitListing =
  608. /(?:^|[\s;&|])git(?:\s+-C\s+(?:"[^"]+"|'[^']+'|\S+))?\s+(?:-[^\s]+\s+)*(?:diff|show|log)\b/u.test(
  609. normalizedCommand,
  610. );
  611. if (!hasUnifiedDiff && !isGitListing) return [];
  612. const rawPaths: string[] = [];
  613. for (const line of lines) {
  614. const unifiedPath = /^\+\+\+\s+b\/(.+)$/u.exec(line)?.[1];
  615. if (unifiedPath) rawPaths.push(unifiedPath);
  616. const renamedPath = /^rename to\s+(.+)$/u.exec(line)?.[1];
  617. if (renamedPath) rawPaths.push(renamedPath);
  618. if (!isGitListing) continue;
  619. const statPath = /^\s*(.+?)\s+\|\s+\d+/u.exec(line)?.[1];
  620. if (statPath && !statPath.includes('=>')) rawPaths.push(statPath);
  621. const numstatPath = /^\d+\s+\d+\s+(.+)$/u.exec(line)?.[1];
  622. if (numstatPath && !numstatPath.includes('\t')) rawPaths.push(numstatPath);
  623. const nameStatus = /^([ACDMRTUXB])\d*\s+(.+)$/u.exec(line);
  624. if (nameStatus?.[1] && nameStatus[1] !== 'D' && nameStatus[2]) {
  625. const paths = nameStatus[2].split(/\t/u);
  626. rawPaths.push(paths.at(-1) ?? '');
  627. }
  628. if (/--name-only\b/u.test(normalizedCommand) && /^\S.*\.[A-Za-z0-9]{1,16}$/u.test(line)) {
  629. rawPaths.push(line);
  630. }
  631. }
  632. const workspaceDir = input.turn.workspaceDir;
  633. const pathApi = nodePath.win32.isAbsolute(workspaceDir) ? nodePath.win32 : nodePath.posix;
  634. return Array.from(
  635. new Set(
  636. rawPaths
  637. .map((value) => value.trim())
  638. .filter(
  639. (value) =>
  640. value &&
  641. value !== '/dev/null' &&
  642. !value.startsWith('"') &&
  643. !['*', '?', '[', ']', '{', '}', '$'].some((marker) => value.includes(marker)),
  644. )
  645. .map((value) => value.replace(/^[ab]\//u, ''))
  646. .filter(isCodeFilePath)
  647. .map((value) =>
  648. normalizeFilePath(
  649. pathApi.isAbsolute(value) ? value : pathApi.resolve(workspaceDir, value),
  650. ),
  651. ),
  652. ),
  653. );
  654. }
  655. function fileName(value: string): string {
  656. return normalizeFilePath(value).split('/').filter(Boolean).at(-1) ?? value;
  657. }
  658. function fileDisplayName(value: string): string {
  659. const name = fileName(value);
  660. return (
  661. /^\d{2}-\d{2}-\d{2}-\d{3}-asset_\d{8}-\d{6}-\d{3}_[a-f0-9]{12}_[a-f0-9]{8}-(.+)$/iu.exec(
  662. name,
  663. )?.[1] ?? name
  664. );
  665. }
  666. function sourceStateFor(
  667. states: Map<string, TurnSourceState>,
  668. ctx: TurnAssemblyCtx,
  669. ): TurnSourceState {
  670. const key = turnKey(ctx);
  671. const existing = states.get(key);
  672. if (existing) return existing;
  673. const created: TurnSourceState = {
  674. references: new Map(),
  675. evidence: new Map(),
  676. generatedFilePaths: new Set(),
  677. citationAliases: new Map(),
  678. citationIdsByAlias: new Map(),
  679. retryAttempted: false,
  680. retryAssetMarkup: [],
  681. retryDraft: '',
  682. };
  683. seedHistoricalFileReferences(created, ctx.history);
  684. states.set(key, created);
  685. return created;
  686. }
  687. function seedHistoricalFileReferences(
  688. state: TurnSourceState,
  689. history: TurnAssemblyCtx['history'],
  690. ): void {
  691. const recentHistory = history.slice(-MAX_HISTORICAL_MESSAGES);
  692. for (let index = recentHistory.length - 1; index >= 0; index -= 1) {
  693. if (state.references.size >= MAX_HISTORICAL_FILE_REFERENCES) return;
  694. const message = readRecord(recentHistory[index]);
  695. if (message?.role !== 'toolResult') continue;
  696. const details = readRecord(message.details);
  697. const references = Array.isArray(details?.[SOURCE_REFERENCE_DETAILS_KEY])
  698. ? details[SOURCE_REFERENCE_DETAILS_KEY]
  699. : [];
  700. for (const value of references) {
  701. const reference = historicalFileReference(value, message);
  702. if (!reference || state.references.has(reference.source_id)) continue;
  703. state.references.set(reference.source_id, reference);
  704. state.evidence.set(reference.source_id, '');
  705. if (state.references.size >= MAX_HISTORICAL_FILE_REFERENCES) return;
  706. }
  707. }
  708. }
  709. function historicalFileReference(
  710. value: unknown,
  711. message: Record<string, unknown>,
  712. ): ToolSourceReference | undefined {
  713. const reference = readRecord(value);
  714. if (reference?.type !== 'file') return undefined;
  715. const sourceId = readNonEmptyString(reference.source_id);
  716. const name = readNonEmptyString(reference.name);
  717. const path = readNonEmptyString(reference.path);
  718. const toolCallId =
  719. readNonEmptyString(reference.tool_call_id) ?? readNonEmptyString(message.toolCallId);
  720. const toolName = readNonEmptyString(reference.tool_name) ?? readNonEmptyString(message.toolName);
  721. if (!sourceId || !name || !path || !toolCallId || !toolName) return undefined;
  722. return {
  723. version: 1,
  724. type: 'file',
  725. source_id: sourceId,
  726. name,
  727. path,
  728. tool_call_id: toolCallId,
  729. tool_name: toolName,
  730. ...(readNonEmptyString(reference.result_path)
  731. ? { result_path: readNonEmptyString(reference.result_path) }
  732. : {}),
  733. };
  734. }
  735. function turnKey(ctx: Pick<TurnAssemblyCtx, 'sessionId' | 'turnId'>): string {
  736. return `${ctx.sessionId}\u0000${ctx.turnId}`;
  737. }
  738. function appendEvidence(previous: string | undefined, current: string): string {
  739. return `${previous ?? ''}\n${current}`.slice(-MAX_SOURCE_EVIDENCE_CHARS);
  740. }
  741. function readAssistantText(content: readonly unknown[]): string {
  742. return content
  743. .map((block) => readRecord(block))
  744. .map((block) => (block?.type === 'text' ? readNonEmptyString(block.text) : undefined))
  745. .filter((value): value is string => Boolean(value))
  746. .join('\n');
  747. }
  748. function answerUsesEvidence(
  749. answer: string,
  750. evidence: string,
  751. otherEvidence: readonly string[],
  752. ): boolean {
  753. if (answerUsesDistinctiveTextEvidence(answer, evidence, otherEvidence)) return true;
  754. return answerUsesNumericEvidence(answer, evidence, otherEvidence);
  755. }
  756. function answerUsesReferenceEvidence(
  757. reference: ToolSourceReference,
  758. answer: string,
  759. evidence: string,
  760. otherEvidence: readonly string[],
  761. references: readonly ToolSourceReference[],
  762. ): boolean {
  763. if (reference.type === 'file') {
  764. if (reference.citation_mode === 'implicit') {
  765. return answerMentionsFileReference(answer, reference, references);
  766. }
  767. return (
  768. answerMentionsFileReference(answer, reference, references) ||
  769. answerUsesFileEvidence(answer, evidence, otherEvidence)
  770. );
  771. }
  772. return answerUsesEvidence(answer, evidence, otherEvidence);
  773. }
  774. function answerMentionsFileReference(
  775. answer: string,
  776. reference: ToolSourceReference,
  777. references: readonly ToolSourceReference[],
  778. ): boolean {
  779. if (reference.type !== 'file' || !reference.path) return false;
  780. const candidates = fileMentionCandidates(reference, references);
  781. const normalized = normalizeMalformedFileMentionLinks(answer, candidates, reference.path);
  782. return (
  783. answerCitesReference(normalized, reference) ||
  784. hasSemanticFileMention(unwrapSyntheticFileMentionMarkdownLinks(answer, [reference]), candidates)
  785. );
  786. }
  787. function competingEvidenceForReference(
  788. reference: ToolSourceReference,
  789. references: readonly ToolSourceReference[],
  790. evidenceByCitationId: ReadonlyMap<string, string>,
  791. ): string[] {
  792. return references.flatMap((candidate) => {
  793. if (citationIdFor(candidate) === citationIdFor(reference)) return [];
  794. if (
  795. reference.type === 'file' &&
  796. candidate.type === 'file' &&
  797. candidate.tool_call_id === reference.tool_call_id
  798. ) {
  799. return [];
  800. }
  801. if (
  802. (reference.type === 'app' || reference.type === 'mcp') &&
  803. (candidate.type !== reference.type || candidate.source_id !== reference.source_id)
  804. ) {
  805. return [];
  806. }
  807. return [evidenceByCitationId.get(citationIdFor(candidate)) ?? ''];
  808. });
  809. }
  810. function answerUsesFileEvidence(
  811. answer: string,
  812. evidence: string,
  813. otherEvidence: readonly string[],
  814. ): boolean {
  815. const candidates = collectFileEvidenceLines(evidence);
  816. const shared = new Set(otherEvidence.flatMap(collectFileEvidenceLines));
  817. if (candidates.some((candidate) => !shared.has(candidate) && answer.includes(candidate))) {
  818. return true;
  819. }
  820. if (answerUsesFileNumericEvidence(answer, evidence, otherEvidence)) return true;
  821. return answerUsesFileTextSegment(answer, evidence, otherEvidence);
  822. }
  823. function collectFileEvidenceLines(evidence: string): string[] {
  824. return Array.from(
  825. new Set(
  826. evidence
  827. .split(/\r?\n/gu)
  828. .map((line) =>
  829. line
  830. .replace(/^\s*\d+[→\t|:]\s*/u, '')
  831. .replace(/^\s*==\s*Page\s+\d+\s*==\s*$/iu, '')
  832. .trim(),
  833. )
  834. .filter((line) => {
  835. if (!line || /^\[[^\]]*(?:truncated|lines? omitted)[^\]]*\]$/iu.test(line)) {
  836. return false;
  837. }
  838. const compactLength = line.replace(/\s+/gu, '').length;
  839. return compactLength >= (/\p{Script=Han}/u.test(line) ? 8 : 12) && compactLength <= 500;
  840. }),
  841. ),
  842. );
  843. }
  844. function answerUsesFileNumericEvidence(
  845. answer: string,
  846. evidence: string,
  847. otherEvidence: readonly string[],
  848. ): boolean {
  849. const evidenceNumbers = collectComparableNumbers(evidence);
  850. const sharedNumbers = new Set(otherEvidence.flatMap(collectComparableNumbers));
  851. return collectNumberValues(answer).some((value) => {
  852. if (!isDistinctiveFileNumber(value)) return false;
  853. const comparable = comparableNumber(value);
  854. return (
  855. comparable !== undefined &&
  856. evidenceNumbers.includes(comparable) &&
  857. !sharedNumbers.has(comparable)
  858. );
  859. });
  860. }
  861. function answerUsesFileTextSegment(
  862. answer: string,
  863. evidence: string,
  864. otherEvidence: readonly string[],
  865. ): boolean {
  866. const comparableAnswer = comparableFileText(answer);
  867. const comparableOtherEvidence = otherEvidence.map(comparableFileText);
  868. return collectFileEvidenceSegments(evidence).some(
  869. (candidate) =>
  870. comparableAnswer.includes(candidate) &&
  871. !comparableOtherEvidence.some((other) => other.includes(candidate)),
  872. );
  873. }
  874. function collectFileEvidenceSegments(evidence: string): string[] {
  875. return Array.from(
  876. new Set(
  877. evidence
  878. .split(/\r?\n/gu)
  879. .map((line) =>
  880. line
  881. .replace(/^\s*\d+[→\t|:]\s*/u, '')
  882. .replace(/^\s*(?:[-*+]\s+|#{1,6}\s*)/u, '')
  883. .trim(),
  884. )
  885. .filter((line) => line && !/^==\s*Page\s+\d+\s*==$/iu.test(line))
  886. .flatMap((line) => line.split(/[。!?!?;;,,::\t|]+/gu))
  887. .map(comparableFileText)
  888. .filter((value) => {
  889. if (!/\p{L}/u.test(value)) return false;
  890. const minimumLength = /\p{Script=Han}/u.test(value) ? 4 : 8;
  891. return value.length >= minimumLength && value.length <= 500;
  892. }),
  893. ),
  894. );
  895. }
  896. function comparableFileText(value: string): string {
  897. return value.normalize('NFKC').toLocaleLowerCase().replace(/\s+/gu, '');
  898. }
  899. function isDistinctiveFileNumber(value: string): boolean {
  900. const digitCount = (value.match(/\d/gu) ?? []).length;
  901. return digitCount >= 4 || value.includes(',') || value.includes('%') || /\.\d{2,}/u.test(value);
  902. }
  903. function collectNumberValues(value: string): string[] {
  904. return Array.from(
  905. value.matchAll(/[+-]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?%?/gu),
  906. (match) => match[0],
  907. );
  908. }
  909. function collectComparableNumbers(value: string): string[] {
  910. return collectToolNumericTokens(value).flatMap(comparableToolNumericValues);
  911. }
  912. function answerUsesNumericEvidence(
  913. answer: string,
  914. evidence: string,
  915. otherEvidence: readonly string[],
  916. ): boolean {
  917. if (!evidence) return false;
  918. const evidenceNumbers = new Set(collectComparableNumbers(evidence));
  919. const sharedNumbers = new Set(otherEvidence.flatMap(collectComparableNumbers));
  920. return collectToolNumericTokens(answer).some((value) => {
  921. if (!isDistinctiveToolNumber(value)) return false;
  922. return comparableToolNumericValues(value).some(
  923. (comparable) => evidenceNumbers.has(comparable) && !sharedNumbers.has(comparable),
  924. );
  925. });
  926. }
  927. function collectToolNumericTokens(value: string): string[] {
  928. return Array.from(
  929. value.matchAll(/[+-]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?\s*(?:%|万|亿)?/gu),
  930. (match) => match[0].replace(/\s+/gu, ''),
  931. );
  932. }
  933. function comparableToolNumericValues(value: string): string[] {
  934. const unit = /[%万亿]$/u.exec(value)?.[0];
  935. const numeric = Number(value.replaceAll(',', '').replace(/[%万亿]$/u, ''));
  936. if (!Number.isFinite(numeric)) return [];
  937. const values = new Set([String(numeric)]);
  938. if (unit === '%') values.add(String(numeric / 100));
  939. if (unit === '万') values.add(String(numeric * 10_000));
  940. if (unit === '亿') values.add(String(numeric * 100_000_000));
  941. return [...values];
  942. }
  943. function isDistinctiveToolNumber(value: string): boolean {
  944. const digitCount = (value.match(/\d/gu) ?? []).length;
  945. return (
  946. digitCount >= 4 || value.includes(',') || /[%万亿]$/u.test(value) || /\.\d{2,}/u.test(value)
  947. );
  948. }
  949. function answerUsesDistinctiveTextEvidence(
  950. answer: string,
  951. evidence: string,
  952. otherEvidence: readonly string[],
  953. ): boolean {
  954. const candidates = collectEvidenceTextValues(evidence);
  955. const otherValues = new Set(otherEvidence.flatMap(collectEvidenceTextValues));
  956. return candidates.some((candidate) => {
  957. const value = candidate.trim();
  958. const compactLength = value.replace(/\s+/gu, '').length;
  959. const minimumLength = /[\u3400-\u9fff]/u.test(value) ? 4 : 8;
  960. return compactLength >= minimumLength && answer.includes(value) && !otherValues.has(value);
  961. });
  962. }
  963. function collectEvidenceTextValues(evidence: string): string[] {
  964. const values = new Set<string>();
  965. const visit = (value: unknown, depth: number): void => {
  966. if (depth > 6) return;
  967. if (typeof value === 'string') {
  968. const trimmed = value.trim();
  969. if (!trimmed) return;
  970. values.add(trimmed);
  971. if (
  972. (trimmed.startsWith('{') && trimmed.endsWith('}')) ||
  973. (trimmed.startsWith('[') && trimmed.endsWith(']'))
  974. ) {
  975. try {
  976. visit(JSON.parse(trimmed) as unknown, depth + 1);
  977. } catch {
  978. // Keep the original scalar when a JSON-looking string is malformed.
  979. }
  980. }
  981. return;
  982. }
  983. if (Array.isArray(value)) {
  984. value.forEach((entry) => visit(entry, depth + 1));
  985. return;
  986. }
  987. const record = readRecord(value);
  988. if (record) Object.values(record).forEach((entry) => visit(entry, depth + 1));
  989. };
  990. try {
  991. visit(JSON.parse(evidence) as unknown, 0);
  992. } catch {
  993. // Concatenated or prose-wrapped ToolResults still expose JSON string leaves below.
  994. }
  995. for (const match of evidence.matchAll(/:\s*"((?:\\.|[^"\\])+)"/gu)) {
  996. try {
  997. visit(JSON.parse(`"${match[1] ?? ''}"`) as unknown, 0);
  998. } catch {
  999. visit(match[1] ?? '', 0);
  1000. }
  1001. }
  1002. return Array.from(values);
  1003. }
  1004. function comparableNumber(value: string): string | undefined {
  1005. const number = Number(value.replaceAll(',', '').replace(/%$/u, ''));
  1006. return Number.isFinite(number) ? String(number) : undefined;
  1007. }
  1008. function sourceReferenceHref(sourceId: string): string {
  1009. return `#mavis-source=${sourceId}`;
  1010. }
  1011. function answerCitesReference(answer: string, reference: ToolSourceReference): boolean {
  1012. if (reference.type === 'web') {
  1013. return Boolean(reference.url && answer.includes(reference.url));
  1014. }
  1015. if (reference.type === 'app' || reference.type === 'mcp') {
  1016. return (
  1017. answer.includes(sourceReferenceHref(citationIdFor(reference))) ||
  1018. answer.includes(`${sourceReferenceHref(reference.source_id)}:call:`) ||
  1019. answer.includes(`${sourceReferenceHref(reference.source_id)})`)
  1020. );
  1021. }
  1022. if (reference.type !== 'file') {
  1023. return answer.includes(sourceReferenceHref(citationIdFor(reference)));
  1024. }
  1025. return answer.includes(sourceReferenceHref(citationIdFor(reference)));
  1026. }
  1027. /**
  1028. * Web searches already return canonical result URLs. Append any missing links
  1029. * to the completed draft immediately instead of making source visibility
  1030. * depend on a citation-repair LLM call.
  1031. */
  1032. function appendMissingWebSourceSummary(
  1033. text: string,
  1034. missingReferences: readonly ToolSourceReference[],
  1035. ): string {
  1036. const referencesByUrl = new Map<string, ToolSourceReference>();
  1037. for (const reference of missingReferences) {
  1038. if (reference.type !== 'web' || !reference.url || text.includes(reference.url)) continue;
  1039. if (!referencesByUrl.has(reference.url)) referencesByUrl.set(reference.url, reference);
  1040. }
  1041. const citations = Array.from(referencesByUrl.values()).map(
  1042. (reference) => `[${escapeMarkdownLabel(reference.name)}](${reference.url})`,
  1043. );
  1044. if (citations.length === 0) return text;
  1045. const isChinese = /\p{Script=Han}/u.test(text);
  1046. const separator = isChinese ? '、' : ', ';
  1047. const label = isChinese ? '来源:' : 'Sources: ';
  1048. return `${text.trimEnd()}\n\n${label}${citations.join(separator)}`;
  1049. }
  1050. function normalizeFilePathCitationTags(
  1051. text: string,
  1052. references: readonly ToolSourceReference[],
  1053. ): string {
  1054. return text
  1055. .split(/(```[\s\S]*?```|~~~[\s\S]*?~~~)/gu)
  1056. .map((segment, index) => {
  1057. if (index % 2 === 1) return segment;
  1058. return segment
  1059. .split(/(`[^`\n]*`)/gu)
  1060. .map((part, inlineIndex) =>
  1061. inlineIndex % 2 === 1
  1062. ? normalizeInlineOrphanFilePathCitation(part, references)
  1063. : normalizeStandardFilePathCitationTags(part, references),
  1064. )
  1065. .join('');
  1066. })
  1067. .join('');
  1068. }
  1069. function normalizeStandardFilePathCitationTags(
  1070. text: string,
  1071. references: readonly ToolSourceReference[],
  1072. ): string {
  1073. const normalized = normalizeFilePathTagSyntax(text)
  1074. .replace(/<<>\s*(?=[^<\n]+<\/filepath>)/giu, '<filepath>')
  1075. .replace(
  1076. /<filepath\b([^>]*)>\s*(?:data-path|path)\s*=\s*(?:"([^"]*)"|'([^']*)')\s*>\s*([^<]+?)\s*<\/filepath>/giu,
  1077. (
  1078. _tag,
  1079. attributes: string,
  1080. doubleQuotedPath: string,
  1081. singleQuotedPath: string,
  1082. label: string,
  1083. ) =>
  1084. `<filepath${attributes} path="${escapeHtmlAttribute(doubleQuotedPath ?? singleQuotedPath ?? '')}">${label.trim()}</filepath>`,
  1085. )
  1086. .replace(
  1087. /<filepath\b([^>]*)>\s*([^<\n]+?)\s+\((?:line|lines)\s+(\d+)(?:\s*[-–—:]\s*(\d+))?\)\s*<\/filepath>/giu,
  1088. (_tag, attributes: string, path: string, lineStart: string, lineEnd: string) =>
  1089. `<filepath${attributes}>${path.trim()}:${lineStart}${lineEnd ? `:${lineEnd}` : ''}</filepath>`,
  1090. )
  1091. .replace(
  1092. /<((?:(?:[A-Za-z]:[\\/]|\.{0,2}[\\/])[^<>\n]*?|[^<>\s]+)\.[A-Za-z0-9][A-Za-z0-9._-]*)\s+\((?:line|lines)\s+(\d+)(?:\s*[-–—:]\s*(\d+))?\)>?\s*<\/filepath>/giu,
  1093. (_tag, path: string, lineStart: string, lineEnd: string) =>
  1094. `<filepath>${path.trim()}:${lineStart}${lineEnd ? `:${lineEnd}` : ''}</filepath>`,
  1095. )
  1096. .replace(/<filepath\b([^>]*)>([^<\n]+)(?=\n|$)/giu, (_tag, attributes: string, body: string) =>
  1097. normalizeUnclosedFilePathCitation(attributes, body, references),
  1098. );
  1099. return stripOrphanFilePathClosers(
  1100. normalized
  1101. .split(/(<filepath\b[^>]*>[\s\S]*?<\/filepath>)/giu)
  1102. .map((part, index) =>
  1103. index % 2 === 1 ? part : normalizeKnownOrphanFilePathClosers(part, references),
  1104. )
  1105. .join(''),
  1106. );
  1107. }
  1108. function normalizeUnclosedFilePathCitation(
  1109. attributes: string,
  1110. rawBody: string,
  1111. references: readonly ToolSourceReference[],
  1112. ): string {
  1113. const body = rawBody.trim();
  1114. const path = filePathFromCitationTag(attributes, body);
  1115. const isBacked = references.some(
  1116. (reference) =>
  1117. reference.type === 'file' &&
  1118. typeof reference.path === 'string' &&
  1119. filePathsMatch(path, reference.path),
  1120. );
  1121. const isPlausibleFile =
  1122. isBacked ||
  1123. (isMalformedFileCitationPlaceholder(body) &&
  1124. references.filter((reference) => reference.type === 'file' && Boolean(reference.path))
  1125. .length === 1) ||
  1126. isCodeFilePath(path) ||
  1127. /^(?:[A-Za-z]:[\\/]|\.{0,2}[\\/]|[/\\])/u.test(path) ||
  1128. (/[/\\]/u.test(path) && !/\s/u.test(path)) ||
  1129. /(?:^|[\\/])[^\\/]+\.[A-Za-z0-9][A-Za-z0-9._-]*(?::\d+(?::\d+)?)?$/u.test(path);
  1130. if (!isPlausibleFile) return body;
  1131. return `<filepath${attributes}>${body}</filepath>`;
  1132. }
  1133. function normalizeInlineOrphanFilePathCitation(
  1134. text: string,
  1135. references: readonly ToolSourceReference[],
  1136. ): string {
  1137. const body = normalizeFilePathTagSyntax(text.slice(1, -1));
  1138. if (!body.includes('</filepath>')) return text;
  1139. const normalized = normalizeKnownOrphanFilePathClosers(body, references);
  1140. return normalized === body ? body.replaceAll('</filepath>', '') : normalized;
  1141. }
  1142. function normalizeKnownOrphanFilePathClosers(
  1143. text: string,
  1144. references: readonly ToolSourceReference[],
  1145. ): string {
  1146. const fileReferences = references.filter(
  1147. (reference): reference is ToolSourceReference & { readonly path: string } =>
  1148. reference.type === 'file' && Boolean(reference.path),
  1149. );
  1150. let normalized = text;
  1151. fileReferences.forEach((reference) => {
  1152. const aliases = Array.from(
  1153. new Set([reference.path, normalizeFilePath(reference.path), fileName(reference.path)]),
  1154. ).sort((left, right) => right.length - left.length);
  1155. aliases.forEach((alias) => {
  1156. const pattern = new RegExp(
  1157. `(^|[^>])(${escapeRegExp(alias)})(?::(\\d+)(?::(\\d+))?)?(\\s*[((][^<>\\n]{1,120}[))])?\\s*<\\/filepath>`,
  1158. 'giu',
  1159. );
  1160. normalized = normalized.replace(
  1161. pattern,
  1162. (
  1163. _tag,
  1164. prefix: string,
  1165. _alias: string,
  1166. lineStart?: string,
  1167. lineEnd?: string,
  1168. locator?: string,
  1169. ) => {
  1170. const line =
  1171. lineStart && isCodeFilePath(reference.path)
  1172. ? `:${lineStart}${lineEnd ? `:${lineEnd}` : ''}`
  1173. : '';
  1174. return `${prefix}<filepath path="${escapeHtmlAttribute(reference.path)}">${escapeHtmlText(fileName(reference.path))}${line}</filepath>${locator ?? ''}`;
  1175. },
  1176. );
  1177. });
  1178. });
  1179. return normalized;
  1180. }
  1181. function stripOrphanFilePathClosers(text: string): string {
  1182. let openTagCount = 0;
  1183. return text.replace(/<\p{Cf}*filepath\b[^>]*>|<\p{Cf}*\/\p{Cf}*filepath\p{Cf}*\s*>/giu, (tag) => {
  1184. const normalizedTag = normalizeFilePathTagSyntax(tag);
  1185. if (/^<filepath\b/iu.test(normalizedTag)) {
  1186. openTagCount += 1;
  1187. return normalizedTag;
  1188. }
  1189. if (openTagCount === 0) return '';
  1190. openTagCount -= 1;
  1191. return normalizedTag;
  1192. });
  1193. }
  1194. function normalizeFilePathTagSyntax(text: string): string {
  1195. return text
  1196. .replace(/<\p{Cf}*(?=<\p{Cf}*filepath\b)/giu, '')
  1197. .replace(/<\p{Cf}*filepath\b([^>]*)>/giu, '<filepath$1>')
  1198. .replace(/<\p{Cf}*\/\p{Cf}*filepath\p{Cf}*\s*>/giu, '</filepath>')
  1199. .replace(/(<\/filepath>)\p{Cf}*>/giu, '$1')
  1200. .replace(
  1201. /<filepath\b[^<>]*?\bpath\s*=\s*(["'])<filepath\b([^>]*)>([^<]+?)<\/filepath>\1\s*>\s*([^<]+?)<\/filepath>/giu,
  1202. (_tag, _quote: string, innerAttributes: string, innerLabel: string, outerLabel: string) =>
  1203. `<filepath${innerAttributes}>${outerLabel.trim() || innerLabel.trim()}</filepath>`,
  1204. );
  1205. }
  1206. function escapeRegExp(value: string): string {
  1207. return value.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
  1208. }
  1209. function normalizeMisclassifiedSourceFilePathTags(
  1210. text: string,
  1211. references: readonly ToolSourceReference[],
  1212. evidenceByCitationId: ReadonlyMap<string, string>,
  1213. ): string {
  1214. const webReferences = references.filter(
  1215. (reference): reference is ToolSourceReference & { readonly url: string } =>
  1216. reference.type === 'web' && Boolean(reference.url),
  1217. );
  1218. return text
  1219. .split(/(```[\s\S]*?```|~~~[\s\S]*?~~~|`[^`\n]*`)/gu)
  1220. .map((segment, index) => {
  1221. if (index % 2 === 1) return segment;
  1222. return segment.replace(
  1223. /<filepath\b([^>]*)>([^<]+?)<\/filepath>/giu,
  1224. (tag, attributes: string, rawLabel: string, offset: number) => {
  1225. const pathMatch = /\b(?:data-path|path)\s*=\s*(?:"([^"]*)"|'([^']*)')/iu.exec(attributes);
  1226. const candidate = decodeBasicHtmlEntities(pathMatch?.[1] ?? pathMatch?.[2] ?? '').trim();
  1227. const label = decodeBasicHtmlEntities(rawLabel.trim());
  1228. const sourceId = sourceIdFromCandidateHref(candidate);
  1229. if (sourceId) {
  1230. return `[${escapeMarkdownLabel(label)}](${sourceReferenceHref(sourceId)})`;
  1231. }
  1232. const candidateUrl = httpUrlFromMisclassifiedFilePath(candidate);
  1233. if (!candidateUrl) return String(tag);
  1234. const candidateComparable = comparableHttpUrl(candidateUrl);
  1235. const exactReference = webReferences.find(
  1236. (reference) => comparableHttpUrl(reference.url) === candidateComparable,
  1237. );
  1238. const candidateHost = safeHttpUrl(candidateUrl)
  1239. ? new URL(candidateUrl).hostname.toLowerCase()
  1240. : undefined;
  1241. const sameHostReferences = candidateHost
  1242. ? webReferences.filter((reference) => {
  1243. const url = safeHttpUrl(reference.url);
  1244. return url ? new URL(url).hostname.toLowerCase() === candidateHost : false;
  1245. })
  1246. : [];
  1247. const labelAlias = normalizedSourceAlias(label);
  1248. const labelReference = labelAlias
  1249. ? sameHostReferences.find(
  1250. (reference) => normalizedSourceAlias(reference.name) === labelAlias,
  1251. )
  1252. : undefined;
  1253. const contextualReference = contextualReferenceForAlias(
  1254. segment.slice(0, offset),
  1255. sameHostReferences,
  1256. evidenceByCitationId,
  1257. );
  1258. const resolvedUrl =
  1259. exactReference?.url ??
  1260. labelReference?.url ??
  1261. contextualReference?.url ??
  1262. (sameHostReferences.length === 1 ? sameHostReferences[0]?.url : undefined) ??
  1263. candidateUrl;
  1264. return `[${escapeMarkdownLabel(label)}](${resolvedUrl})`;
  1265. },
  1266. );
  1267. })
  1268. .join('');
  1269. }
  1270. function httpUrlFromMisclassifiedFilePath(value: string): string | undefined {
  1271. const existing = safeHttpUrl(value);
  1272. if (existing) return existing;
  1273. const domainPath = /^((?:[a-z0-9-]+\.)+[a-z]{2,63})([:/])(.+)$/iu.exec(value);
  1274. if (!domainPath) return undefined;
  1275. const [, domain, separator, suffix] = domainPath;
  1276. if (!domain || !separator || !suffix) return undefined;
  1277. const address =
  1278. separator === ':' && /^\d+(?:\/|$)/u.test(suffix)
  1279. ? `https://${domain}:${suffix}`
  1280. : `https://${domain}/${suffix.replace(/^\/+/, '')}`;
  1281. return safeHttpUrl(address);
  1282. }
  1283. function comparableHttpUrl(value: string): string | undefined {
  1284. const normalized = safeHttpUrl(value);
  1285. if (!normalized) return undefined;
  1286. const url = new URL(normalized);
  1287. url.hash = '';
  1288. return url.href.replace(/\/$/u, '');
  1289. }
  1290. function removeDisallowedFileCitations(text: string): string {
  1291. return text
  1292. .split(/(```[\s\S]*?```|~~~[\s\S]*?~~~|`[^`\n]*`)/gu)
  1293. .map((segment, index) => {
  1294. if (index % 2 === 1) return segment;
  1295. return segment.replace(
  1296. /<filepath\b([^>]*)>([^<]+?)<\/filepath>([ \t]*[::][ \t]*)?/giu,
  1297. (tag, attributes: string, rawBody: string, separator: string | undefined) => {
  1298. const path = filePathFromCitationTag(attributes, rawBody);
  1299. if (!path || !isTemporaryOrInternalFilePath(path)) return String(tag);
  1300. const label = decodeBasicHtmlEntities(rawBody.trim());
  1301. return isSemanticFileCitationLabel(label, path)
  1302. ? ''
  1303. : `${rawBody.trim()}${separator ?? ''}`;
  1304. },
  1305. );
  1306. })
  1307. .join('');
  1308. }
  1309. function removeUnbackedFileCitations(
  1310. text: string,
  1311. references: readonly ToolSourceReference[],
  1312. ): string {
  1313. const fileReferences = references.filter(
  1314. (reference): reference is ToolSourceReference & { readonly path: string } =>
  1315. reference.type === 'file' && Boolean(reference.path),
  1316. );
  1317. const isBacked = (attributes: string, body: string): boolean => {
  1318. const path = filePathFromCitationTag(attributes, body);
  1319. return fileReferences.some((reference) => filePathsMatch(path, reference.path));
  1320. };
  1321. return text
  1322. .split(/(```[\s\S]*?```|~~~[\s\S]*?~~~|`[^`\n]*`)/gu)
  1323. .map((segment, index) => {
  1324. if (index % 2 === 1) return segment;
  1325. const withoutStandaloneLines = segment.replace(
  1326. /^[ \t]*(?:[-*][ \t]+)?(?:(?:来源[::]|Source:)[ \t]*)?<filepath\b([^>]*)>\s*([^<\n]+?)\s*<\/filepath>[ \t]*$/gimu,
  1327. (line, attributes: string, body: string) =>
  1328. isBacked(attributes, body) ? String(line) : '',
  1329. );
  1330. return withoutStandaloneLines.replace(
  1331. /<filepath\b([^>]*)>([^<]+?)<\/filepath>/giu,
  1332. (tag, attributes: string, body: string) =>
  1333. isBacked(attributes, body) ? String(tag) : body.trim(),
  1334. );
  1335. })
  1336. .join('');
  1337. }
  1338. function normalizeFileCitationLabels(
  1339. text: string,
  1340. references: readonly ToolSourceReference[],
  1341. ): string {
  1342. const fileReferences = references.filter(
  1343. (reference): reference is ToolSourceReference & { readonly path: string } =>
  1344. reference.type === 'file' && Boolean(reference.path),
  1345. );
  1346. if (fileReferences.length === 0) return text;
  1347. return text.replace(
  1348. /<filepath\b([^>]*)>([^<]+?)<\/filepath>/giu,
  1349. (tag, attributes: string, rawBody: string) => {
  1350. const citedPath = filePathFromCitationTag(attributes, rawBody);
  1351. const label = decodeBasicHtmlEntities(rawBody.trim());
  1352. const malformedPlaceholder = isMalformedFileCitationPlaceholder(label);
  1353. const reference =
  1354. fileReferences.find((candidate) => filePathsMatch(citedPath, candidate.path)) ??
  1355. (malformedPlaceholder && fileReferences.length === 1 ? fileReferences[0] : undefined);
  1356. if (!reference) return malformedPlaceholder ? '' : String(tag);
  1357. if (malformedPlaceholder) {
  1358. return renderSemanticFileCitation(reference.path, fileDisplayName(reference.path));
  1359. }
  1360. if (isSemanticFileCitationLabel(label, reference.path)) {
  1361. return renderSemanticFileCitation(reference.path, label);
  1362. }
  1363. const localizedCitation = renderSemanticFileCitation(
  1364. reference.path,
  1365. fileDisplayName(reference.path),
  1366. );
  1367. const separator = /\p{Script=Han}/u.test(label) ? ':' : ': ';
  1368. return `${localizedCitation}${separator}${rawBody.trim()}`;
  1369. },
  1370. );
  1371. }
  1372. function isMalformedFileCitationPlaceholder(value: string): boolean {
  1373. return /^\/?filepath\s*>?$/iu.test(value.trim());
  1374. }
  1375. function isSemanticFileCitationLabel(label: string, path: string): boolean {
  1376. const withoutLineAddress = extractFileLineAddress(label).label;
  1377. const candidates = new Set([
  1378. path,
  1379. normalizeFilePath(path),
  1380. fileName(path),
  1381. fileDisplayName(path),
  1382. ...semanticFileMentionLabels(path),
  1383. ]);
  1384. const comparableLabel = comparableFileText(withoutLineAddress);
  1385. return Array.from(candidates).some(
  1386. (candidate) => comparableFileText(candidate) === comparableLabel,
  1387. );
  1388. }
  1389. function isCodeFilePath(path: string): boolean {
  1390. return CODE_FILE_BASENAME_RE.test(path) || CODE_FILE_EXTENSION_RE.test(fileName(path));
  1391. }
  1392. function localizeMentionedFileCitations(
  1393. text: string,
  1394. references: readonly ToolSourceReference[],
  1395. ): string {
  1396. const fileReferences = references.filter(
  1397. (reference): reference is ToolSourceReference & { readonly path: string } =>
  1398. reference.type === 'file' && Boolean(reference.path),
  1399. );
  1400. return fileReferences.reduce((answer, reference) => {
  1401. const candidates = fileMentionCandidates(reference, fileReferences);
  1402. const normalizedMalformedLinks = normalizeMalformedFileMentionLinks(
  1403. answer,
  1404. candidates,
  1405. reference.path,
  1406. );
  1407. const withoutOldCitations = removeMatchingFileCitations(
  1408. normalizedMalformedLinks,
  1409. reference.path,
  1410. );
  1411. if (!hasSemanticFileMention(withoutOldCitations, candidates)) return normalizedMalformedLinks;
  1412. return replaceSemanticFileMentions(
  1413. normalizeMalformedFileMentionLinks(withoutOldCitations, candidates, reference.path),
  1414. candidates,
  1415. reference.path,
  1416. );
  1417. }, text);
  1418. }
  1419. function fileMentionCandidates(
  1420. reference: ToolSourceReference,
  1421. references: readonly ToolSourceReference[],
  1422. ): string[] {
  1423. if (reference.type !== 'file' || !reference.path) return [];
  1424. const referencePath = reference.path;
  1425. const fileReferencesByPath = new Map<string, ToolSourceReference & { readonly path: string }>();
  1426. references.forEach((candidate) => {
  1427. if (candidate.type !== 'file' || !candidate.path) return;
  1428. fileReferencesByPath.set(comparableFileText(normalizeFilePath(candidate.path)), {
  1429. ...candidate,
  1430. path: candidate.path,
  1431. });
  1432. });
  1433. const ownersByLabel = new Map<string, Set<string>>();
  1434. const labelsByPath = new Map<string, string[]>();
  1435. fileReferencesByPath.forEach((candidate, pathKey) => {
  1436. const extension = fileExtension(candidate.path);
  1437. const labels = Array.from(
  1438. new Set([
  1439. candidate.path,
  1440. normalizeFilePath(candidate.path),
  1441. candidate.name,
  1442. ...semanticFileMentionLabels(candidate.path),
  1443. ...filePathSuffixMentionLabels(candidate.path),
  1444. ...(extension ? fileTypeMentionLabels(extension) : []),
  1445. ]),
  1446. ).filter(Boolean);
  1447. labelsByPath.set(pathKey, labels);
  1448. labels.forEach((label) => {
  1449. const labelKey = comparableFileText(label);
  1450. const owners = ownersByLabel.get(labelKey) ?? new Set<string>();
  1451. owners.add(pathKey);
  1452. ownersByLabel.set(labelKey, owners);
  1453. });
  1454. });
  1455. const referencePathKey = comparableFileText(normalizeFilePath(referencePath));
  1456. return (labelsByPath.get(referencePathKey) ?? [referencePath])
  1457. .filter((label) => ownersByLabel.get(comparableFileText(label))?.size === 1)
  1458. .sort((left, right) => right.length - left.length);
  1459. }
  1460. function removeMatchingFileCitations(text: string, path: string): string {
  1461. const href = sourceReferenceHref(fileSourceId(path));
  1462. const internalLink = new RegExp(`\\[([^\\]\\n]+)\\]\\(\\s*${escapeRegExp(href)}\\s*\\)`, 'giu');
  1463. const withoutStandaloneInternalLinks = text.replace(
  1464. new RegExp(
  1465. `^[ \\t]*(?:[-*][ \\t]+)?(?:(?:来源[::]|Source:)[ \\t]*)?${internalLink.source}[ \\t]*$`,
  1466. 'gimu',
  1467. ),
  1468. '',
  1469. );
  1470. const withoutStandaloneSourceLines = withoutStandaloneInternalLinks.replace(
  1471. /^[ \t]*(?:[-*][ \t]+)?(?:(?:来源[::]|Source:)[ \t]*)?<filepath\b([^>]*)>\s*([^<\n]+?)\s*<\/filepath>[ \t]*$/gimu,
  1472. (line, attributes: string, body: string) =>
  1473. filePathsMatch(filePathFromCitationTag(attributes, body), path) ? '' : String(line),
  1474. );
  1475. return withoutStandaloneSourceLines
  1476. .replace(internalLink, (_link, label: string) => label)
  1477. .replace(
  1478. /<filepath\b([^>]*)>\s*([^<]+?)\s*<\/filepath>/giu,
  1479. (tag, attributes: string, body: string) =>
  1480. filePathsMatch(filePathFromCitationTag(attributes, body), path) ? '' : String(tag),
  1481. );
  1482. }
  1483. function semanticFileMentionLabels(path: string): string[] {
  1484. const name = fileDisplayName(path);
  1485. const extension = /\.([a-z0-9]{1,10})$/iu.exec(name)?.[1];
  1486. const stem = extension ? name.slice(0, -(extension.length + 1)) : name;
  1487. const core = stem
  1488. .replace(/[((【[][^))】\]]*[))】\]]/gu, '')
  1489. .replace(/[\s_-]*\d{4,}[\s_-]*$/u, '')
  1490. .replace(/[\s_-]+$/u, '')
  1491. .trim();
  1492. const spacedCore = core
  1493. .replace(/([a-z0-9])([\u3400-\u9fff])/giu, '$1 $2')
  1494. .replace(/([\u3400-\u9fff])([a-z0-9])/giu, '$1 $2');
  1495. const extensionLabel = extension?.toUpperCase();
  1496. return Array.from(
  1497. new Set(
  1498. [
  1499. name,
  1500. stem,
  1501. core,
  1502. spacedCore,
  1503. ...(extensionLabel
  1504. ? [`${core} ${extensionLabel}`, `${spacedCore} ${extensionLabel}`, `${core}.${extension}`]
  1505. : []),
  1506. ].filter((value) => value.length >= 4),
  1507. ),
  1508. );
  1509. }
  1510. function filePathSuffixMentionLabels(path: string): string[] {
  1511. const segments = normalizeFilePath(path).split('/').filter(Boolean);
  1512. return segments.slice(0, -1).map((_, index) => segments.slice(index).join('/'));
  1513. }
  1514. function fileExtension(path: string): string | undefined {
  1515. return /\.([a-z0-9]{1,16})$/iu.exec(fileName(path))?.[1]?.toLocaleLowerCase();
  1516. }
  1517. function fileTypeMentionLabels(extension: string): string[] {
  1518. const lower = extension.toLocaleLowerCase();
  1519. const upper = extension.toLocaleUpperCase();
  1520. return [`${upper} 文件`, `${upper} 文档`, `${lower} 文件`, `${lower} 文档`];
  1521. }
  1522. function matchesSemanticFileMention(value: string, candidates: readonly string[]): boolean {
  1523. const address = extractFileLineAddress(value.trim());
  1524. const comparableLabel = comparableFileText(address.label);
  1525. return candidates.some((candidate) => comparableFileText(candidate) === comparableLabel);
  1526. }
  1527. function normalizeMalformedFileMentionLinks(
  1528. text: string,
  1529. candidates: readonly string[],
  1530. path: string,
  1531. ): string {
  1532. if (candidates.length === 0) return text;
  1533. // Unwrap only an already-backed File citation with an empty/line-only outer
  1534. // target. A real Web link wrapping a filename remains untouched.
  1535. const normalizedWrappers = text
  1536. .split(/(```[\s\S]*?```|~~~[\s\S]*?~~~|`[^`\n]*`)/gu)
  1537. .map((segment, index) =>
  1538. index % 2 === 1
  1539. ? segment
  1540. : segment.replace(
  1541. /\[(\[[^\]\n]+\]\((#mavis-source=file:[^\s)"'<>]+)\))\]\(((?:[^()\n]|\([^()\n]*\))*)\)/gu,
  1542. (wrapper, citation: string, href: string, outerHref: string) => {
  1543. const target = decodePercentEncodedText(outerHref)
  1544. .replace(/^\((.*)\)$/u, '$1')
  1545. .trim();
  1546. return href === sourceReferenceHref(fileSourceId(path)) &&
  1547. (!target || /^(?:line|lines)\s+\d+(?:\s*[-–—:]\s*\d+)?$/iu.test(target))
  1548. ? citation
  1549. : wrapper;
  1550. },
  1551. ),
  1552. )
  1553. .join('');
  1554. const lineLabelPattern = `(?:line|lines)\\s+${FILE_LINE_LIST_PATTERN}`;
  1555. const pattern = new RegExp(
  1556. `\\[([^\\]\\n]+)\\]\\(((?:[^()\\n]|\\([^()\\n]*\\))*)\\)(?:\\s*\\(\\s*(${lineLabelPattern})\\s*\\))?`,
  1557. 'giu',
  1558. );
  1559. return splitFileCitationSegments(normalizedWrappers)
  1560. .map((segment) => {
  1561. if (
  1562. isFilePathTag(segment) ||
  1563. isFileSourceMarkdownLink(segment) ||
  1564. isAssetMarkup(segment) ||
  1565. isFencedCode(segment) ||
  1566. isInlineCode(segment)
  1567. ) {
  1568. return segment;
  1569. }
  1570. return segment.replace(
  1571. pattern,
  1572. (link, rawLabel: string, rawHref: string, trailingLineLabel?: string) => {
  1573. const label = rawLabel.trim();
  1574. const href = decodePercentEncodedText(decodeBasicHtmlEntities(rawHref.trim()))
  1575. .replace(/^<|>$/gu, '')
  1576. .trim();
  1577. const unwrappedHref = /^\((.*)\)$/u.exec(href)?.[1]?.trim() ?? href;
  1578. const hrefLineLabel = new RegExp(`^${lineLabelPattern}$`, 'iu').exec(unwrappedHref)?.[0];
  1579. const hrefAddress = extractFileLineAddress(href.replace(/^file:\/\//iu, ''));
  1580. const backedLocalPath = Boolean(
  1581. href &&
  1582. !safeHttpUrl(href) &&
  1583. (filePathsMatch(hrefAddress.label, path) ||
  1584. matchesFlattenedFilePathAlias(hrefAddress.label, path)),
  1585. );
  1586. const uniquelyMatchedLabel = matchesSemanticFileMention(label, candidates);
  1587. if (
  1588. !uniquelyMatchedLabel &&
  1589. !(backedLocalPath && isSemanticFileCitationLabel(label, path))
  1590. ) {
  1591. return String(link);
  1592. }
  1593. const emptyOrBackedHref = !href || hrefLineLabel || backedLocalPath;
  1594. if (!emptyOrBackedHref) return String(link);
  1595. const labelAddress = extractFileLineAddress(label);
  1596. const lineLabel =
  1597. labelAddress.lineRanges.length > 0
  1598. ? undefined
  1599. : (hrefLineLabel ??
  1600. trailingLineLabel ??
  1601. (hrefAddress.lineRanges.length > 0
  1602. ? `lines ${hrefAddress.lineRanges.join(', ')}`
  1603. : undefined));
  1604. return renderSemanticFileCitation(path, lineLabel ? `${label}(${lineLabel})` : label);
  1605. },
  1606. );
  1607. })
  1608. .join('');
  1609. }
  1610. function matchesFlattenedFilePathAlias(value: string, path: string): boolean {
  1611. const comparableValue = value
  1612. .normalize('NFKC')
  1613. .toLocaleLowerCase()
  1614. .replace(/^\.\//u, '')
  1615. .replace(/[\\/\s_-]+/gu, '');
  1616. if (!comparableValue) return false;
  1617. return filePathSuffixMentionLabels(path).some(
  1618. (suffix) =>
  1619. suffix
  1620. .normalize('NFKC')
  1621. .toLocaleLowerCase()
  1622. .replace(/[\\/\s_-]+/gu, '') === comparableValue,
  1623. );
  1624. }
  1625. function decodePercentEncodedText(value: string): string {
  1626. try {
  1627. return decodeURIComponent(value);
  1628. } catch {
  1629. return value;
  1630. }
  1631. }
  1632. function hasSemanticFileMention(text: string, candidates: readonly string[]): boolean {
  1633. return splitFileCitationSegments(text).some((segment) => {
  1634. if (
  1635. isFilePathTag(segment) ||
  1636. isFileSourceMarkdownLink(segment) ||
  1637. isFileMentionLink(segment) ||
  1638. isAssetMarkup(segment) ||
  1639. isFencedCode(segment)
  1640. ) {
  1641. return false;
  1642. }
  1643. if (isInlineCode(segment)) {
  1644. const value = segment.slice(1, -1).trim();
  1645. return matchesSemanticFileMention(value, candidates);
  1646. }
  1647. return fileMentionPattern(candidates).test(segment);
  1648. });
  1649. }
  1650. function replaceSemanticFileMentions(
  1651. text: string,
  1652. candidates: readonly string[],
  1653. path: string,
  1654. ): string {
  1655. let replacedNaturalMention = false;
  1656. const replaceAllCodeMentions = isCodeFilePath(path);
  1657. return splitFileCitationSegments(text)
  1658. .map((segment) => {
  1659. if (
  1660. isFilePathTag(segment) ||
  1661. isFileSourceMarkdownLink(segment) ||
  1662. isFileMentionLink(segment) ||
  1663. isAssetMarkup(segment) ||
  1664. isFencedCode(segment)
  1665. ) {
  1666. return segment;
  1667. }
  1668. if (isInlineCode(segment)) {
  1669. const value = segment.slice(1, -1).trim();
  1670. if (!matchesSemanticFileMention(value, candidates)) return segment;
  1671. return renderSemanticFileCitation(path, value);
  1672. }
  1673. if (replacedNaturalMention && !replaceAllCodeMentions) return segment;
  1674. const lineAddress = `(?:${FILE_LINE_ADDRESS_PATTERN})?`;
  1675. const pattern = fileMentionPattern(candidates, lineAddress);
  1676. return segment.replace(pattern, (mention) => {
  1677. if (replacedNaturalMention && !replaceAllCodeMentions) return String(mention);
  1678. replacedNaturalMention = true;
  1679. return renderSemanticFileCitation(path, String(mention));
  1680. });
  1681. })
  1682. .join('');
  1683. }
  1684. // Ordinary links/URLs are syntax boundaries, never file mentions to rewrite.
  1685. function isFileMentionLink(value: string): boolean {
  1686. return /^(?:!?\[|https?:\/\/|<https?:\/\/)/iu.test(value.trimStart());
  1687. }
  1688. function fileMentionPattern(candidates: readonly string[], suffix = ''): RegExp {
  1689. const alternatives = [...candidates]
  1690. .sort((a, b) => b.length - a.length)
  1691. .map(escapeRegExp)
  1692. .join('|');
  1693. return new RegExp(
  1694. `(?<![\\w./\\\\-])(?:${alternatives})${suffix}(?![\\w/\\\\-]|\\.[\\w.])`,
  1695. 'giu',
  1696. );
  1697. }
  1698. function renderSemanticFileCitation(path: string, label: string): string {
  1699. return `[${escapeMarkdownLabel(canonicalFileCitationLabel(path, label))}](${sourceReferenceHref(fileSourceId(path))})`;
  1700. }
  1701. function fileSourceId(path: string): string {
  1702. return `file:${Buffer.from(normalizeFilePath(path), 'utf8').toString('base64url')}`;
  1703. }
  1704. function unwrapSyntheticFileMentionMarkdownLinks(
  1705. text: string,
  1706. references: readonly ToolSourceReference[],
  1707. ): string {
  1708. const fileNames = new Set(
  1709. references.flatMap((reference) =>
  1710. reference.type === 'file' && reference.path ? [fileName(reference.path).toLowerCase()] : [],
  1711. ),
  1712. );
  1713. if (fileNames.size === 0) return text;
  1714. return text.replace(
  1715. /\[([^\]\n]+)\]\(https?:\/\/([^/)\s]+)[^\n)]*\)/giu,
  1716. (link, label: string, rawHost: string) => {
  1717. const host = rawHost.replace(/:\d+$/u, '').toLowerCase();
  1718. return fileNames.has(host) ? label : String(link);
  1719. },
  1720. );
  1721. }
  1722. function canonicalFileCitationLabel(path: string, rawLabel: string): string {
  1723. const label = decodeBasicHtmlEntities(rawLabel.trim());
  1724. const address = extractFileLineAddress(label);
  1725. const baseLabel = isCodeFilePath(path)
  1726. ? fileName(path)
  1727. : address?.label || label || fileDisplayName(path);
  1728. if (!address.lineRanges.length || !isCodeFilePath(path)) return baseLabel;
  1729. return `${baseLabel}(line ${address.lineRanges.join(', ')})`;
  1730. }
  1731. function extractFileLineAddress(value: string): {
  1732. label: string;
  1733. lineRanges: string[];
  1734. } {
  1735. const match = new RegExp(
  1736. `^(.*?)(?::\\s*(${FILE_LINE_LIST_PATTERN})|\\s*\\((?:line|lines)\\s+(${FILE_LINE_LIST_PATTERN})\\))\\s*$`,
  1737. 'iu',
  1738. ).exec(value);
  1739. if (!match) return { label: value.trim(), lineRanges: [] };
  1740. const rawRanges = match[2] ?? match[3] ?? '';
  1741. return {
  1742. label: (match[1] ?? '').trim(),
  1743. lineRanges: rawRanges.split(/\s*[,,]\s*/u).flatMap((range) => {
  1744. const rangeMatch = /^(\d+)(?:\s*[-–—:]\s*(\d+))?$/u.exec(range);
  1745. if (!rangeMatch?.[1]) return [];
  1746. return [rangeMatch[2] ? `${rangeMatch[1]}-${rangeMatch[2]}` : rangeMatch[1]];
  1747. }),
  1748. };
  1749. }
  1750. const FILE_LINE_RANGE_PATTERN = '\\d+(?:\\s*[-–—:]\\s*\\d+)?';
  1751. const FILE_LINE_LIST_PATTERN = `${FILE_LINE_RANGE_PATTERN}(?:\\s*[,,]\\s*${FILE_LINE_RANGE_PATTERN})*`;
  1752. const FILE_LINE_ADDRESS_PATTERN = `(?::\\s*${FILE_LINE_LIST_PATTERN}|\\s*\\((?:line|lines)\\s+${FILE_LINE_LIST_PATTERN}\\))`;
  1753. function normalizeFileCitationLineAddresses(
  1754. text: string,
  1755. references: readonly ToolSourceReference[],
  1756. ): string {
  1757. const fileNamesBySourceHref = new Map(
  1758. references.flatMap((reference) =>
  1759. reference.type === 'file' && reference.path
  1760. ? [[sourceReferenceHref(citationIdFor(reference)), reference.path] as const]
  1761. : [],
  1762. ),
  1763. );
  1764. if (fileNamesBySourceHref.size === 0) return text;
  1765. return text.replace(
  1766. new RegExp(
  1767. `\\[([^\\]\\n]+)\\]\\((#mavis-source=file:[^\\s)"'<>]+)\\)(${FILE_LINE_ADDRESS_PATTERN})`,
  1768. 'giu',
  1769. ),
  1770. (citation, label: string, href: string, lineAddress: string) => {
  1771. const path = fileNamesBySourceHref.get(href);
  1772. if (!path || !lineAddress) return String(citation);
  1773. return renderSemanticFileCitation(path, `${label}${lineAddress}`);
  1774. },
  1775. );
  1776. }
  1777. function filePathFromCitationTag(attributes: string, body: string): string {
  1778. const pathMatch = /\b(?:data-path|path)\s*=\s*(?:"([^"]*)"|'([^']*)')/iu.exec(attributes);
  1779. return decodeBasicHtmlEntities(pathMatch?.[1] ?? pathMatch?.[2] ?? body.trim());
  1780. }
  1781. function escapeHtmlAttribute(value: string): string {
  1782. return value
  1783. .replaceAll('&', '&amp;')
  1784. .replaceAll('"', '&quot;')
  1785. .replaceAll('<', '&lt;')
  1786. .replaceAll('>', '&gt;');
  1787. }
  1788. function escapeHtmlText(value: string): string {
  1789. return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
  1790. }
  1791. function decodeBasicHtmlEntities(value: string): string {
  1792. return value
  1793. .replaceAll('&quot;', '"')
  1794. .replaceAll('&#39;', "'")
  1795. .replaceAll('&lt;', '<')
  1796. .replaceAll('&gt;', '>')
  1797. .replaceAll('&amp;', '&');
  1798. }
  1799. function splitFileCitationSegments(text: string): string[] {
  1800. return text.split(
  1801. /(```[\s\S]*?```|~~~[\s\S]*?~~~|<(?:deliver-assets|deliver_assets)\b[^>]*>[\s\S]*?<\/(?:deliver-assets|deliver_assets)>|<media\b(?:[^>"']|"[^"]*"|'[^']*')*?\/>|<filepath\b[^>]*>[\s\S]*?<\/filepath>|!?\[[^\]\n]+\](?:\((?:[^()\n]|\([^()\n]*\))*\)|\[[^\]\n]*\])|^[ \t]{0,3}\[[^\]\n]+\]:[^\n]*|<https?:\/\/[^>\n]+>|https?:\/\/[^\s<>"`]+|`[^`\n]*`)/gimu,
  1802. );
  1803. }
  1804. function isFilePathTag(value: string): boolean {
  1805. return /^<filepath\b/iu.test(value);
  1806. }
  1807. function isFileSourceMarkdownLink(value: string): boolean {
  1808. return /^\[[^\]\n]+\]\(#mavis-source=file:/iu.test(value);
  1809. }
  1810. function isAssetMarkup(value: string): boolean {
  1811. return /^<(?:deliver-assets|deliver_assets|media)\b/iu.test(value);
  1812. }
  1813. function collectAssetMarkupSegments(text: string): string[] {
  1814. return splitFileCitationSegments(text).filter(isAssetMarkup);
  1815. }
  1816. function restoreMissingAssetMarkup(text: string, preserved: readonly string[]): string {
  1817. if (preserved.length === 0) return text;
  1818. const present = new Set(collectAssetMarkupSegments(text));
  1819. const missing = preserved.filter((segment) => !present.has(segment));
  1820. if (missing.length === 0) return text;
  1821. return `${text.trimEnd()}\n\n${missing.join('\n')}`;
  1822. }
  1823. function isFencedCode(value: string): boolean {
  1824. return value.startsWith('```') || value.startsWith('~~~');
  1825. }
  1826. function isInlineCode(value: string): boolean {
  1827. return value.startsWith('`') && value.endsWith('`');
  1828. }
  1829. function normalizeExplicitSourceLinks(
  1830. text: string,
  1831. references: Iterable<ToolSourceReference>,
  1832. evidenceByCitationId: ReadonlyMap<string, string>,
  1833. citationIdsByAlias: ReadonlyMap<string, string>,
  1834. ): string {
  1835. const sourceById = new Map<string, ToolSourceReference>();
  1836. const sourceByAlias = new Map<string, ToolSourceReference | null>();
  1837. const sourcesByAlias = new Map<string, ToolSourceReference[]>();
  1838. const sourceByGroupId = new Map<string, ToolSourceReference | null>();
  1839. const sourcesByGroupId = new Map<string, ToolSourceReference[]>();
  1840. for (const reference of references) {
  1841. sourceById.set(citationIdFor(reference), reference);
  1842. sourcesByGroupId.set(reference.source_id, [
  1843. ...(sourcesByGroupId.get(reference.source_id) ?? []),
  1844. reference,
  1845. ]);
  1846. const grouped = sourceByGroupId.get(reference.source_id);
  1847. if (!sourceByGroupId.has(reference.source_id)) {
  1848. sourceByGroupId.set(reference.source_id, reference);
  1849. } else if (grouped && citationIdFor(grouped) !== citationIdFor(reference)) {
  1850. sourceByGroupId.set(reference.source_id, null);
  1851. }
  1852. const aliases = new Set(
  1853. [reference.provider, reference.name]
  1854. .map((alias) => normalizedSourceAlias(alias))
  1855. .filter((alias): alias is string => Boolean(alias)),
  1856. );
  1857. for (const normalized of aliases) {
  1858. sourcesByAlias.set(normalized, [...(sourcesByAlias.get(normalized) ?? []), reference]);
  1859. const existing = sourceByAlias.get(normalized);
  1860. if (!sourceByAlias.has(normalized)) {
  1861. sourceByAlias.set(normalized, reference);
  1862. } else if (existing && citationIdFor(existing) !== citationIdFor(reference)) {
  1863. sourceByAlias.set(normalized, null);
  1864. }
  1865. }
  1866. }
  1867. sourceByGroupId.forEach((reference, sourceId) => {
  1868. if (reference) sourceById.set(sourceId, reference);
  1869. });
  1870. return text
  1871. .split(/(```[\s\S]*?```|~~~[\s\S]*?~~~|`[^`\n]*`)/gu)
  1872. .map((segment, index) => {
  1873. if (index % 2 === 1) return segment;
  1874. return segment.replace(
  1875. /\[([^\]\n]+)\]\(\s*([^\s)]+)\s*\)/gu,
  1876. (link, label, href, offset: number) => {
  1877. const hrefText = String(href);
  1878. const rawSourceId = sourceIdFromCandidateHref(hrefText);
  1879. const resolvedSourceId = rawSourceId
  1880. ? resolveKnownCitationAlias(rawSourceId, sourceById.keys(), citationIdsByAlias)
  1881. : undefined;
  1882. const collapsedSourceId = resolvedSourceId
  1883. ? collapseRepeatedCallCitationId(resolvedSourceId)
  1884. : undefined;
  1885. const sourceId =
  1886. collapsedSourceId && sourceById.has(collapsedSourceId)
  1887. ? collapsedSourceId
  1888. : resolvedSourceId;
  1889. const sourceGroupId = sourceId ? sourceGroupIdFromCitationId(sourceId) : undefined;
  1890. const legacyLocator =
  1891. legacyToolSourceLocator(hrefText) ??
  1892. legacySplitToolSourceLocator(String(label), hrefText);
  1893. const alias = normalizedSourceAlias(legacyLocator?.provider ?? hrefText);
  1894. const labelAlias = safeHttpUrl(hrefText)
  1895. ? normalizedSourceAlias(String(label))
  1896. : undefined;
  1897. const aliasReferences = alias ? (sourcesByAlias.get(alias) ?? []) : [];
  1898. const matchingReferences = legacyLocator
  1899. ? aliasReferences.filter(
  1900. (candidate) =>
  1901. normalizedSourceAlias(candidate.tool_name) ===
  1902. normalizedSourceAlias(legacyLocator.toolName),
  1903. )
  1904. : aliasReferences;
  1905. const reference = sourceId
  1906. ? (sourceById.get(sourceId) ??
  1907. contextualReferenceForAlias(
  1908. segment.slice(0, offset),
  1909. sourceGroupId ? (sourcesByGroupId.get(sourceGroupId) ?? []) : [],
  1910. evidenceByCitationId,
  1911. ))
  1912. : ((legacyLocator
  1913. ? matchingReferences.length === 1
  1914. ? matchingReferences[0]
  1915. : undefined
  1916. : (sourceByAlias.get(alias ?? '') ?? sourceByAlias.get(labelAlias ?? ''))) ??
  1917. contextualReferenceForAlias(
  1918. segment.slice(0, offset),
  1919. matchingReferences,
  1920. evidenceByCitationId,
  1921. ) ??
  1922. undefined);
  1923. if (!reference) return link;
  1924. return `[${escapeMarkdownLabel(reference.name)}](${sourceReferenceHref(
  1925. citationIdFor(reference),
  1926. )})`;
  1927. },
  1928. );
  1929. })
  1930. .join('');
  1931. }
  1932. function sourceGroupIdFromCitationId(value: string): string | undefined {
  1933. return /^((?:app|mcp):[^:]+):call:/u.exec(value)?.[1];
  1934. }
  1935. function collapseRepeatedCallCitationId(value: string): string {
  1936. const match = /^((?:app|mcp):[^:]+):call:(.+)$/u.exec(value);
  1937. if (!match?.[1] || !match[2]?.includes(':call:')) return value;
  1938. const finalCallId = match[2].split(':call:').at(-1);
  1939. return finalCallId ? `${match[1]}:call:${finalCallId}` : value;
  1940. }
  1941. function contextualReferenceForAlias(
  1942. precedingText: string,
  1943. references: readonly ToolSourceReference[],
  1944. evidenceByCitationId: ReadonlyMap<string, string>,
  1945. ): ToolSourceReference | undefined {
  1946. if (references.length === 1) return references[0];
  1947. if (references.length === 0) return undefined;
  1948. const context = precedingCitationBlock(precedingText);
  1949. const valuesByReference = new Map(
  1950. references.map((reference) => [
  1951. citationIdFor(reference),
  1952. collectEvidenceTextValues(evidenceByCitationId.get(citationIdFor(reference)) ?? ''),
  1953. ]),
  1954. );
  1955. const scores = references.map((reference) => {
  1956. const citationId = citationIdFor(reference);
  1957. const otherValues = new Set(
  1958. references
  1959. .filter((candidate) => citationIdFor(candidate) !== citationId)
  1960. .flatMap((candidate) => valuesByReference.get(citationIdFor(candidate)) ?? []),
  1961. );
  1962. const score = (valuesByReference.get(citationId) ?? []).reduce((total, value) => {
  1963. const compactLength = value.replace(/\s+/gu, '').length;
  1964. if (compactLength < (/[\u3400-\u9fff]/u.test(value) ? 4 : 8)) return total;
  1965. if (otherValues.has(value) || !context.includes(value)) return total;
  1966. return total + Math.min(compactLength, 80);
  1967. }, 0);
  1968. return { reference, score };
  1969. });
  1970. scores.sort((left, right) => right.score - left.score);
  1971. if ((scores[0]?.score ?? 0) === 0 || scores[0]?.score === scores[1]?.score) return undefined;
  1972. return scores[0]?.reference;
  1973. }
  1974. function precedingCitationBlock(text: string): string {
  1975. const bounded = text.slice(-6_000);
  1976. const boundary = Math.max(bounded.lastIndexOf('\n\n'), bounded.lastIndexOf('\n#'));
  1977. return boundary >= 0 ? bounded.slice(boundary + 2) : bounded;
  1978. }
  1979. /**
  1980. * Citation repair is model-authored, so enforce its block contract before the
  1981. * repaired answer becomes user-visible. A Markdown heading starts a sourced
  1982. * block; only repeats in explicit citation-only summaries may collapse.
  1983. * Descriptive links and file locations retain their text and targets.
  1984. */
  1985. function collapseRepeatedCitationTargetsByMarkdownSection(
  1986. text: string,
  1987. references: readonly ToolSourceReference[],
  1988. ): string {
  1989. const citationIdentityByHref = new Map<string, string>();
  1990. references.forEach((reference) => {
  1991. if (reference.type === 'file') return;
  1992. if (reference.type === 'web') {
  1993. if (reference.url) citationIdentityByHref.set(reference.url, `web:${reference.url}`);
  1994. return;
  1995. }
  1996. const citationId = citationIdFor(reference);
  1997. citationIdentityByHref.set(sourceReferenceHref(citationId), `tool:${citationId}`);
  1998. citationIdentityByHref.set(
  1999. sourceReferenceHref(reference.source_id),
  2000. `tool:${reference.source_id}`,
  2001. );
  2002. });
  2003. if (citationIdentityByHref.size === 0) return text;
  2004. const protectedPattern = /(`[^`\n]*`)/gu;
  2005. const citationPattern = /\[([^\]\n]+)\]\(\s*([^\s)"'<>]+)\s*\)/gu;
  2006. const seen = new Set<string>();
  2007. let fence: { character: '`' | '~'; length: number } | undefined;
  2008. return text
  2009. .split('\n')
  2010. .map((line) => {
  2011. const fenceMatch = /^\s*(`{3,}|~{3,})/u.exec(line);
  2012. if (fence) {
  2013. if (fenceMatch?.[1]?.startsWith(fence.character) && fenceMatch[1].length >= fence.length) {
  2014. fence = undefined;
  2015. }
  2016. return line;
  2017. }
  2018. if (fenceMatch?.[1]) {
  2019. fence = {
  2020. character: fenceMatch[1][0] as '`' | '~',
  2021. length: fenceMatch[1].length,
  2022. };
  2023. return line;
  2024. }
  2025. if (/^\s{0,3}#{1,6}\s+/u.test(line)) seen.clear();
  2026. const sourceOnlyLine = isCitationOnlySummaryLine(line);
  2027. let removedCitation = false;
  2028. const projected = line
  2029. .split(protectedPattern)
  2030. .map((segment, protectedIndex) => {
  2031. if (protectedIndex % 2 === 1) return segment;
  2032. return segment.replace(citationPattern, (link, _label: string, href: string) => {
  2033. const identity = citationIdentityByHref.get(href.trim());
  2034. if (!identity) return link;
  2035. if (!seen.has(identity)) {
  2036. seen.add(identity);
  2037. return link;
  2038. }
  2039. if (!sourceOnlyLine) return link;
  2040. removedCitation = true;
  2041. return '';
  2042. });
  2043. })
  2044. .join('');
  2045. return removedCitation ? cleanRemovedCitationLine(projected) : projected;
  2046. })
  2047. .join('\n');
  2048. }
  2049. /**
  2050. * A source summary may list multiple call-specific links for one provider as
  2051. * `Source A + Source A`. Collapse only delimiter-connected source lists, so
  2052. * separate factual citations remain call-specific and independently usable.
  2053. */
  2054. function collapseRepeatedPresentedSourceLists(
  2055. text: string,
  2056. references: readonly ToolSourceReference[],
  2057. ): string {
  2058. const presentationIdentityByHref = new Map<string, string>();
  2059. references.forEach((reference) => {
  2060. if (reference.type === 'file') return;
  2061. if (reference.type === 'web') {
  2062. if (reference.url) {
  2063. presentationIdentityByHref.set(reference.url, `web:${reference.url}`);
  2064. }
  2065. return;
  2066. }
  2067. const identity = `tool:${reference.source_id}`;
  2068. presentationIdentityByHref.set(sourceReferenceHref(citationIdFor(reference)), identity);
  2069. presentationIdentityByHref.set(sourceReferenceHref(reference.source_id), identity);
  2070. });
  2071. if (presentationIdentityByHref.size === 0) return text;
  2072. const protectedPattern = /(`[^`\n]*`)/gu;
  2073. const citationPattern = /\[([^\]\n]+)\]\(\s*([^\s)"'<>]+)\s*\)/gu;
  2074. const sourceListSeparator = /^\s*[+、,,;;/·•]\s*$/u;
  2075. let fence: { character: '`' | '~'; length: number } | undefined;
  2076. return text
  2077. .split('\n')
  2078. .map((line) => {
  2079. const fenceMatch = /^\s*(`{3,}|~{3,})/u.exec(line);
  2080. if (fence) {
  2081. if (fenceMatch?.[1]?.startsWith(fence.character) && fenceMatch[1].length >= fence.length) {
  2082. fence = undefined;
  2083. }
  2084. return line;
  2085. }
  2086. if (fenceMatch?.[1]) {
  2087. fence = {
  2088. character: fenceMatch[1][0] as '`' | '~',
  2089. length: fenceMatch[1].length,
  2090. };
  2091. return line;
  2092. }
  2093. if (line.includes('|')) return line;
  2094. const trailingSourceList = isCitationOnlySummaryLine(
  2095. line.replace(/^.*?(?=(?:数据来源|来源|Sources?)\s*[::])/iu, ''),
  2096. );
  2097. let removedCitation = false;
  2098. const projected = line
  2099. .split(protectedPattern)
  2100. .map((segment, protectedIndex) => {
  2101. if (protectedIndex % 2 === 1) return segment;
  2102. const seenInList = new Set<string>();
  2103. let previousCitationEnd: number | undefined;
  2104. return segment.replace(
  2105. citationPattern,
  2106. (link, _label: string, href: string, offset: number) => {
  2107. const connectedToPrevious =
  2108. previousCitationEnd !== undefined &&
  2109. sourceListSeparator.test(segment.slice(previousCitationEnd, offset));
  2110. if (!connectedToPrevious) seenInList.clear();
  2111. previousCitationEnd = offset + String(link).length;
  2112. const identity = presentationIdentityByHref.get(href.trim());
  2113. if (!identity) {
  2114. seenInList.clear();
  2115. return link;
  2116. }
  2117. // App-only source lists may follow prose on the same line. Never
  2118. // use URL identity alone to delete a descriptive Web link label.
  2119. if (
  2120. connectedToPrevious &&
  2121. seenInList.has(identity) &&
  2122. identity.startsWith('tool:') &&
  2123. trailingSourceList
  2124. ) {
  2125. removedCitation = true;
  2126. return '';
  2127. }
  2128. seenInList.add(identity);
  2129. return link;
  2130. },
  2131. );
  2132. })
  2133. .join('');
  2134. return removedCitation ? cleanRemovedCitationLine(projected) : projected;
  2135. })
  2136. .join('\n');
  2137. }
  2138. function isCitationOnlySummaryLine(line: string): boolean {
  2139. if (line.includes('|')) return false;
  2140. const withoutLinks = line.replace(/\[[^\]\n]+\]\(\s*[^\s)"'<>]+\s*\)/gu, '');
  2141. return /^\s*(?:>\s*)?(?:[-*+]\s*)?(?:已引用的?来源(?:链接)?|数据来源|来源(?:链接)?|Sources?(?: links?)?)\s*[::][\s+、,,;;/·•()()]*$/iu.test(
  2142. withoutLinks,
  2143. );
  2144. }
  2145. function cleanRemovedCitationLine(line: string): string {
  2146. const sourceSummaryAtStart =
  2147. /^\s*(?:>\s*)?(?:[-*+]\s*)?(?:已引用的?来源(?:链接)?|数据来源|来源(?:链接)?|Sources?(?: links?)?)\s*[::]/iu;
  2148. const remainingMarkdownLink = /\[[^\]\n]+\]\(\s*[^)\n]+\s*\)/u;
  2149. if (sourceSummaryAtStart.test(line) && !remainingMarkdownLink.test(line)) return '';
  2150. const cleaned = line
  2151. .replace(/(?:来源[::]|Source:)\s*(?=$|[+、,,;;/|·•])/giu, '')
  2152. .replace(/([+、,,;;/|·•])(?:\s*[+、,,;;/|·•])+/gu, '$1')
  2153. .replace(/[((]\s*[+、,,;;/|·•\s]+[))]/gu, '')
  2154. .replace(/\s*[+、,,;;/|·•]+\s*$/gu, '')
  2155. .replace(/(?:数据来源|来源(?:链接)?|Source(?: links?)?)\s*[::]\s*$/giu, '')
  2156. .trimEnd();
  2157. return /^\s*(?:>\s*)?(?:[-*+]\s*)?$/u.test(cleaned) ? '' : cleaned;
  2158. }
  2159. function normalizeBareToolSourceLines(text: string): string {
  2160. const label = /[\u3400-\u9fff]/u.test(text) ? '来源:' : 'Source: ';
  2161. return text
  2162. .replace(
  2163. /^([ \t]*)[((]\s*(\[[^\]\n]+\]\(#mavis-source=[^)\n]+\))\s*[))][ \t]*$/gmu,
  2164. (_line, indent: string, citation: string) =>
  2165. `${indent}${indent ? '- ' : ''}${label}${citation}`,
  2166. )
  2167. .replace(
  2168. /^-[ \t]+((?:来源[::]|Source:)[ \t]*\[[^\]\n]+\]\(#mavis-source=[^)\n]+\))[ \t]*$/gmu,
  2169. '$1',
  2170. );
  2171. }
  2172. function sourceIdFromCandidateHref(href: string): string | undefined {
  2173. const marker = '#mavis-source=';
  2174. const schemeMarker = '://mavis-source=';
  2175. let decodedHref = href.trim();
  2176. try {
  2177. decodedHref = decodeURIComponent(decodedHref);
  2178. } catch {
  2179. // Match the original candidate when malformed escaping is present.
  2180. }
  2181. const markerIndex = decodedHref.indexOf(marker);
  2182. const schemeMarkerIndex = decodedHref.indexOf(schemeMarker);
  2183. const sourceId =
  2184. markerIndex >= 0
  2185. ? decodedHref.slice(markerIndex + marker.length)
  2186. : schemeMarkerIndex >= 0
  2187. ? decodedHref.slice(schemeMarkerIndex + schemeMarker.length)
  2188. : decodedHref.startsWith('mavis-source=')
  2189. ? decodedHref.slice('mavis-source='.length)
  2190. : /^(?:app|mcp):/u.test(decodedHref)
  2191. ? decodedHref
  2192. : undefined;
  2193. if (!sourceId) return undefined;
  2194. return sourceId;
  2195. }
  2196. function legacyToolSourceLocator(href: string): { provider: string; toolName: string } | undefined {
  2197. let decodedHref = href.trim();
  2198. try {
  2199. decodedHref = decodeURIComponent(decodedHref);
  2200. } catch {
  2201. // Match the original candidate when malformed escaping is present.
  2202. }
  2203. const match = /^([a-z0-9._-]+)#([a-z0-9._-]+)$/iu.exec(decodedHref);
  2204. if (!match?.[1] || !match[2] || match[2].toLowerCase() === 'mavis-source') return undefined;
  2205. return { provider: match[1], toolName: match[2].toLowerCase() };
  2206. }
  2207. function legacySplitToolSourceLocator(
  2208. label: string,
  2209. href: string,
  2210. ): { provider: string; toolName: string } | undefined {
  2211. const providerMatch = /^(?:来源|Source)\s*[::]\s*([a-z0-9._-]+)$/iu.exec(label.trim());
  2212. const toolName = href.trim();
  2213. if (!providerMatch?.[1] || !/^[a-z0-9._-]+$/iu.test(toolName)) return undefined;
  2214. return { provider: providerMatch[1], toolName: toolName.toLowerCase() };
  2215. }
  2216. function normalizedSourceAlias(value: string | undefined): string | undefined {
  2217. if (!value) return undefined;
  2218. let decoded = value.trim();
  2219. try {
  2220. decoded = decodeURIComponent(decoded);
  2221. } catch {
  2222. // Compare the original value when malformed escaping is present.
  2223. }
  2224. const normalized = canonicalMcpServerName(
  2225. decoded.replace(/^\.\//u, '').replace(/\/$/u, '').trim().toLowerCase(),
  2226. );
  2227. return normalized || undefined;
  2228. }
  2229. /**
  2230. * Citation correction is an internal one-shot rewrite. Some models answer the
  2231. * instruction itself instead of the draft, which must never be accepted as a
  2232. * user-visible assistant message. This check only runs after that retry has
  2233. * been requested, and requires multiple distinctive instruction fragments to
  2234. * avoid treating ordinary source-format discussion as a failed correction.
  2235. */
  2236. function isCitationRetryPromptLeak(text: string): boolean {
  2237. const promptFragments = [
  2238. 'Cite each used source once per sourced block.',
  2239. 'For Markdown tables, remove citations from individual rows/cells',
  2240. 'Web: exact URL.',
  2241. 'App/MCP:',
  2242. 'File: use the exact internal target as a Markdown link.',
  2243. 'Current draft JSON:',
  2244. 'I need to use the format:',
  2245. ];
  2246. return (
  2247. text.includes('Rewrite only the current draft supplied below with localized citations.') ||
  2248. promptFragments.filter((fragment) => text.includes(fragment)).length >= 2
  2249. );
  2250. }
  2251. function buildCitationRetryPrompt(
  2252. references: readonly ToolSourceReference[],
  2253. currentDraft: string,
  2254. citationAliasState: CitationAliasState,
  2255. ): string {
  2256. const candidates = references
  2257. .map((reference) =>
  2258. reference.type === 'file'
  2259. ? `File: [${escapeMarkdownLabel(reference.name)}](${sourceReferenceHref(citationIdFor(reference))})`
  2260. : reference.type === 'web'
  2261. ? `${escapeMarkdownLabel(reference.name)} => ${reference.url ?? ''}`
  2262. : `${escapeMarkdownLabel(reference.name)} (${escapeMarkdownLabel(reference.tool_name)}) => ${sourceReferenceHref(modelCitationIdFor(reference, citationAliasState))}`,
  2263. )
  2264. .join(', ');
  2265. return `Rewrite only the current draft supplied below with localized citations. Do not reuse or rewrite any earlier assistant answer from the conversation. Preserve its content and formatting, including every <deliver-assets>, <deliver_assets>, and <media /> block exactly. Cite each used source once per sourced block. Treat one Markdown heading section as one sourced block; a table and its immediately following explanation belong to that same block. Within that block, cite the same target URL at most once, except that every code-file reference must remain individually sourced. For Markdown tables, remove citations from individual rows/cells and place one source line immediately below the table with each used source once, except code-file references, which stay linked in their cells. Web: exact URL. App/MCP: cite the exact target URL as a Markdown link and always label it with the App/MCP name; the client renders its icon. File: every code filename/path must use its listed exact internal target as a Markdown link; never leave it as inline code or plain text. For code use filename(line N) or filename(lines N-M); for other files use a concise filename/title. Never wrap factual answer text or a sentence/list/table cell. Never invent an HTTP URL for a local file, expose the local path in the link target, or turn an App/MCP tool name, API/interface name, result label, or artifact URL into a File citation. Omit unused targets; never output a bare parenthesized citation, repeat a non-file source within the same block, or list a source/provider name without its target link. Targets: ${candidates}. App/MCP URLs start #mavis-source=. File internal URLs also start #mavis-source=. Current draft JSON: ${JSON.stringify(currentDraft)}`;
  2266. }
  2267. function modelCitationIdFor(reference: ToolSourceReference, state: CitationAliasState): string {
  2268. const citationId = citationIdFor(reference);
  2269. return reference.type === 'app' || reference.type === 'mcp'
  2270. ? shortCitationIdFor(citationId, state)
  2271. : citationId;
  2272. }