markdown-source-citation.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. export interface ContextualWebCitation {
  2. readonly name: string;
  3. readonly url: string;
  4. readonly favicon?: string;
  5. readonly evidence?: string;
  6. }
  7. const MAX_EVIDENCE_CHARS = 200_000;
  8. const MAX_SOURCE_PARSE_DEPTH = 8;
  9. const MAX_COLLECTED_SOURCES = 100;
  10. const SOURCE_SCALAR_KEYS = new Set([
  11. 'url',
  12. 'href',
  13. 'link',
  14. 'source_url',
  15. 'sourceUrl',
  16. 'favicon',
  17. 'favicon_url',
  18. 'faviconUrl',
  19. 'site_icon',
  20. 'siteIcon',
  21. 'icon',
  22. ]);
  23. /**
  24. * Extracts WebSearch-style source records from nested/JSON-string tool output.
  25. * It intentionally only recognizes explicit HTTP(S) fields, so page text that
  26. * merely mentions a URL does not become provenance by accident.
  27. */
  28. export function collectWebSourceCitations(
  29. value: unknown,
  30. options: { includeText?: boolean; requireSourceMetadata?: boolean } = {},
  31. ): ContextualWebCitation[] {
  32. const output: ContextualWebCitation[] = [];
  33. collectWebSourceCitationsInto(value, output, new Set(), 0, options);
  34. const deduped = new Map<string, ContextualWebCitation>();
  35. output.forEach((citation) => {
  36. if (!deduped.has(citation.url)) deduped.set(citation.url, citation);
  37. });
  38. return Array.from(deduped.values());
  39. }
  40. function collectWebSourceCitationsInto(
  41. value: unknown,
  42. output: ContextualWebCitation[],
  43. visited: Set<object>,
  44. depth: number,
  45. options: { includeText?: boolean; requireSourceMetadata?: boolean },
  46. ): void {
  47. if (depth > MAX_SOURCE_PARSE_DEPTH || output.length >= MAX_COLLECTED_SOURCES) return;
  48. const parsed = parseJsonValue(value);
  49. if (typeof parsed === 'string') {
  50. if (options.includeText !== false) collectTextWebCitations(parsed, output);
  51. return;
  52. }
  53. if (Array.isArray(parsed)) {
  54. if (visited.has(parsed)) return;
  55. visited.add(parsed);
  56. parsed.forEach((entry) =>
  57. collectWebSourceCitationsInto(entry, output, visited, depth + 1, options),
  58. );
  59. return;
  60. }
  61. const record = readRecord(parsed);
  62. if (!record || visited.has(record)) return;
  63. visited.add(record);
  64. const url = safeHttpUrl(
  65. readString(record.url) ??
  66. readString(record.href) ??
  67. readString(record.link) ??
  68. readString(record.source_url) ??
  69. readString(record.sourceUrl),
  70. );
  71. const sourceMetadata =
  72. readString(record.title) ??
  73. readString(record.page_title) ??
  74. readString(record.pageTitle) ??
  75. readString(record.snippet) ??
  76. readString(record.description) ??
  77. readString(record.summary) ??
  78. readString(record.text);
  79. if (url && (!options.requireSourceMetadata || sourceMetadata)) {
  80. const name = preferredWebSourceName(
  81. url,
  82. [
  83. readString(record.title),
  84. readString(record.page_title),
  85. readString(record.pageTitle),
  86. readString(record.name),
  87. readString(record.label),
  88. ],
  89. [readWebDocumentTitle(record.content), readWebDocumentTitle(record.text)],
  90. );
  91. const evidence = [
  92. name,
  93. readString(record.snippet),
  94. readString(record.description),
  95. readString(record.summary),
  96. readString(record.text),
  97. readString(record.content)
  98. ?.split(/(?:^|\n)\[(?:附加字段|additional fields?)[^\]]*\]/iu, 1)[0]
  99. ?.trim(),
  100. ]
  101. .filter((entry): entry is string => Boolean(entry))
  102. .join('\n')
  103. .slice(0, MAX_EVIDENCE_CHARS);
  104. const supplementalMetadata = parseSupplementalMetadata(record.content);
  105. const favicon = safeHttpUrl(
  106. readString(record.favicon) ??
  107. readString(record.favicon_url) ??
  108. readString(record.faviconUrl) ??
  109. readString(record.site_icon) ??
  110. readString(record.siteIcon) ??
  111. readString(record.icon) ??
  112. readString(supplementalMetadata?.favicon) ??
  113. readString(supplementalMetadata?.favicon_url) ??
  114. readString(supplementalMetadata?.faviconUrl) ??
  115. readString(supplementalMetadata?.site_icon) ??
  116. readString(supplementalMetadata?.siteIcon) ??
  117. readString(supplementalMetadata?.icon),
  118. );
  119. output.push({
  120. name,
  121. url,
  122. ...(favicon ? { favicon } : {}),
  123. ...(evidence ? { evidence } : {}),
  124. });
  125. // A structured WebSearch result is a provenance leaf. Its `content` may
  126. // contain the fetched page body, including navigation and recommendation
  127. // links that were never returned as search results. Recursing into that
  128. // body would incorrectly offer those outbound links as citation targets.
  129. return;
  130. }
  131. Object.entries(record).forEach(([key, entry]) => {
  132. if (!SOURCE_SCALAR_KEYS.has(key)) {
  133. collectWebSourceCitationsInto(entry, output, visited, depth + 1, options);
  134. }
  135. });
  136. }
  137. /**
  138. * Connector WebSearch implementations may serialize results as Markdown or
  139. * line-oriented text instead of a JSON object. This parser is intentionally
  140. * reached only after the caller has classified the ToolResult as WebSearch,
  141. * so explicit links in that result are source candidates rather than arbitrary
  142. * URLs found in a page body.
  143. */
  144. function collectTextWebCitations(value: string, output: ContextualWebCitation[]): void {
  145. if (!value.trim() || value.length > MAX_EVIDENCE_CHARS) return;
  146. const occupied = new Set<string>();
  147. for (const match of value.matchAll(
  148. /(?<!!)\[([^\]\n]+)\]\(\s*(https?:\/\/[^\s<>"')\],。;:!?]+)(?:\s+(?:"[^"]*"|'[^']*'))?\s*\)/giu,
  149. )) {
  150. const url = safeHttpUrl(match[2]);
  151. if (!url) continue;
  152. occupied.add(url);
  153. const label = match[1]?.trim();
  154. output.push({
  155. name: label && !isFallbackWebSourceTitle(label, url) ? label : url,
  156. url,
  157. evidence: evidenceLine(value, match.index ?? 0),
  158. });
  159. }
  160. for (const match of value.matchAll(/https?:\/\/[^\s<>"')\],。;:!?]+/giu)) {
  161. const url = safeHttpUrl(match[0]);
  162. const line = evidenceLine(value, match.index ?? 0);
  163. if (
  164. !url ||
  165. occupied.has(url) ||
  166. /["']?(?:favicon(?:_url|Url)?|site_(?:icon)|siteIcon|icon)["']?\s*:/iu.test(line)
  167. ) {
  168. continue;
  169. }
  170. output.push({
  171. name: url,
  172. url,
  173. evidence: line,
  174. });
  175. }
  176. }
  177. function readWebDocumentTitle(value: unknown): string | undefined {
  178. if (typeof value !== 'string') return undefined;
  179. const htmlTitle = /<title[^>]*>\s*([^<]{2,120})\s*<\/title>/iu.exec(value)?.[1]?.trim();
  180. if (htmlTitle) return htmlTitle;
  181. return /^#{1,2}\s+(.{2,120})$/mu.exec(value)?.[1]?.trim();
  182. }
  183. function preferredWebSourceName(
  184. url: string,
  185. semanticTitles: readonly (string | undefined)[],
  186. documentTitles: readonly (string | undefined)[],
  187. ): string {
  188. return (
  189. [...semanticTitles, ...documentTitles].find(
  190. (title): title is string =>
  191. typeof title === 'string' && !isFallbackWebSourceTitle(title, url),
  192. ) ?? url
  193. );
  194. }
  195. function isFallbackWebSourceTitle(title: string, url: string): boolean {
  196. if (safeHttpUrl(title) === url) return true;
  197. const hostname = new URL(url).hostname.toLowerCase();
  198. const normalizedTitle = title
  199. .toLowerCase()
  200. .replace(/^https?:\/\//u, '')
  201. .replace(/\/$/u, '');
  202. return normalizedTitle === hostname || normalizedTitle === hostname.replace(/^www\./u, '');
  203. }
  204. function evidenceLine(value: string, index: number): string {
  205. const start = value.lastIndexOf('\n', Math.max(0, index - 1)) + 1;
  206. const endIndex = value.indexOf('\n', index);
  207. const end = endIndex < 0 ? value.length : endIndex;
  208. return value.slice(start, end).trim().slice(0, 500);
  209. }
  210. function parseSupplementalMetadata(value: unknown): Record<string, unknown> | undefined {
  211. if (typeof value !== 'string' || value.length > MAX_EVIDENCE_CHARS) return undefined;
  212. const matches = Array.from(
  213. value.matchAll(/(?:^|\n)\[(?:附加字段|additional fields?)[^\]]*\]\s*/giu),
  214. );
  215. const marker = matches.at(-1);
  216. if (marker?.index === undefined) return undefined;
  217. return readRecord(parseJsonValue(value.slice(marker.index + marker[0].length)));
  218. }
  219. function parseJsonValue(value: unknown): unknown {
  220. if (typeof value !== 'string') return value;
  221. const trimmed = value.trim();
  222. if (
  223. trimmed.length === 0 ||
  224. trimmed.length > MAX_EVIDENCE_CHARS ||
  225. (!trimmed.startsWith('{') && !trimmed.startsWith('['))
  226. ) {
  227. return value;
  228. }
  229. try {
  230. return JSON.parse(trimmed) as unknown;
  231. } catch {
  232. return value;
  233. }
  234. }
  235. function readRecord(value: unknown): Record<string, unknown> | undefined {
  236. return typeof value === 'object' && value !== null && !Array.isArray(value)
  237. ? (value as Record<string, unknown>)
  238. : undefined;
  239. }
  240. function readString(value: unknown): string | undefined {
  241. return typeof value === 'string' && value.trim() ? value.trim() : undefined;
  242. }
  243. function safeHttpUrl(value: string | undefined): string | undefined {
  244. if (!value) return undefined;
  245. try {
  246. const url = new URL(value);
  247. return url.protocol === 'http:' || url.protocol === 'https:' ? url.href : undefined;
  248. } catch {
  249. return undefined;
  250. }
  251. }