source-reference-web.ts 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. import {
  2. collectFetchedWebSources,
  3. collectWebSourceCitations,
  4. type ContextualWebCitation,
  5. } from '@mavis/agent-runtime';
  6. import type { ToolSourceAdapterInput, ToolSourceReference } from './source-reference.js';
  7. import {
  8. escapeMarkdownLabel,
  9. invokedToolName,
  10. normalizeToolName,
  11. parseMcpToolName,
  12. readNonEmptyString,
  13. readRecord,
  14. safeHttpUrl,
  15. } from './source-reference-utils.js';
  16. interface WebSourceReferences {
  17. /** All successfully accessed Web sources, persisted for access history. */
  18. readonly references: readonly ContextualWebCitation[];
  19. /** Only context that is absent from the original ToolResult and must reach the model. */
  20. readonly markerReferences: readonly ContextualWebCitation[];
  21. }
  22. export function renderWebFetchSourceMarker(reference: ContextualWebCitation): string {
  23. return `Final URL: [${escapeMarkdownLabel(reference.name)}](${reference.url})`;
  24. }
  25. export function webSourceReferencesForToolResult(
  26. input: ToolSourceAdapterInput,
  27. directReference = webFetchSourceReferenceForToolResult(input),
  28. ): WebSourceReferences {
  29. if (directReference) {
  30. const references = collectFetchedWebSources(directReference, input.result.content);
  31. return { references, markerReferences: references.slice(0, 1) };
  32. }
  33. const isKnownWebSearch = isWebSearchToolCall(input.toolName, input.args);
  34. return {
  35. references: collectWebSourceCitations(
  36. input.result,
  37. isKnownWebSearch ? {} : { includeText: false, requireSourceMetadata: true },
  38. ),
  39. markerReferences: [],
  40. };
  41. }
  42. export function webFetchSourceReferenceForToolResult(
  43. input: ToolSourceAdapterInput,
  44. ): ContextualWebCitation | undefined {
  45. const details = readRecord(input.result.details);
  46. if (details?.ok === false) return undefined;
  47. const args = readRecord(input.args);
  48. const nestedArgs = readRecord(args?.arguments) ?? readRecord(args?.args);
  49. const resultUrl = safeHttpUrl(
  50. readNonEmptyString(details?.final_url) ??
  51. readNonEmptyString(details?.finalUrl) ??
  52. readNonEmptyString(details?.url),
  53. );
  54. const argumentUrl = safeHttpUrl(
  55. readNonEmptyString(args?.url) ??
  56. readNonEmptyString(args?.href) ??
  57. readNonEmptyString(args?.link) ??
  58. readNonEmptyString(nestedArgs?.url) ??
  59. readNonEmptyString(nestedArgs?.href) ??
  60. readNonEmptyString(nestedArgs?.link),
  61. );
  62. const url =
  63. resultUrl ??
  64. (isExplicitWebSourceToolCall(input.toolName, input.args) ? argumentUrl : undefined);
  65. if (!url) return undefined;
  66. return {
  67. name: preferredWebSourceName(
  68. url,
  69. [
  70. readNonEmptyString(args?.title),
  71. readNonEmptyString(args?.name),
  72. readNonEmptyString(args?.label),
  73. readNonEmptyString(nestedArgs?.title),
  74. readNonEmptyString(nestedArgs?.name),
  75. readNonEmptyString(nestedArgs?.label),
  76. readNonEmptyString(details?.source_title),
  77. readNonEmptyString(details?.sourceTitle),
  78. readNonEmptyString(details?.name),
  79. readNonEmptyString(details?.label),
  80. ],
  81. [
  82. readNonEmptyString(details?.title),
  83. readNonEmptyString(details?.page_title),
  84. readNonEmptyString(details?.pageTitle),
  85. readWebDocumentTitle(input.result.content),
  86. ],
  87. ),
  88. url,
  89. };
  90. }
  91. function preferredWebSourceName(
  92. url: string,
  93. semanticTitles: readonly (string | undefined)[],
  94. documentTitles: readonly (string | undefined)[],
  95. ): string {
  96. return (
  97. [...semanticTitles, ...documentTitles].find(
  98. (title): title is string =>
  99. typeof title === 'string' && !isFallbackWebSourceTitle(title, url),
  100. ) ?? url
  101. );
  102. }
  103. function isFallbackWebSourceTitle(title: string, url: string): boolean {
  104. if (safeHttpUrl(title) === url) return true;
  105. const hostname = new URL(url).hostname.toLowerCase();
  106. const normalizedTitle = title
  107. .toLowerCase()
  108. .replace(/^https?:\/\//u, '')
  109. .replace(/\/$/u, '');
  110. return normalizedTitle === hostname || normalizedTitle === hostname.replace(/^www\./u, '');
  111. }
  112. export function persistedWebReference(
  113. input: ToolSourceAdapterInput,
  114. reference: ContextualWebCitation,
  115. ): ToolSourceReference {
  116. return {
  117. version: 1,
  118. type: 'web',
  119. source_id: `web:${Buffer.from(reference.url, 'utf8').toString('base64url')}`,
  120. name: reference.name,
  121. url: reference.url,
  122. ...(reference.favicon ? { icon_url: reference.favicon } : {}),
  123. tool_call_id: input.toolCallId,
  124. tool_name: invokedToolName(input.args) ?? input.toolName,
  125. result_path: '$',
  126. };
  127. }
  128. function isWebSearchToolCall(toolName: string, args: unknown): boolean {
  129. const candidates = [toolName, invokedToolName(args)]
  130. .filter((value): value is string => Boolean(value))
  131. .map(normalizeToolName);
  132. return candidates.some(
  133. (name) => name === 'web' || name === 'web_search' || name.endsWith('__web_search'),
  134. );
  135. }
  136. export function isExplicitWebSourceToolCall(toolName: string, args: unknown): boolean {
  137. return [toolName, invokedToolName(args)]
  138. .filter((value): value is string => Boolean(value))
  139. .map(normalizeToolName)
  140. .some(
  141. (name) =>
  142. name === 'web_search' ||
  143. name === 'web_fetch' ||
  144. name === 'webfetch' ||
  145. name.endsWith('__web_search') ||
  146. name.endsWith('__web_fetch'),
  147. );
  148. }
  149. /**
  150. * A platform WebSearch may include companion App metadata (for example, a
  151. * result-enrichment provider). That metadata must not suppress the distinct
  152. * public Web result sources. Connector-owned `*_web_search` methods remain
  153. * App-only, because their returned homepage or asset URL is not WebSearch
  154. * provenance.
  155. */
  156. export function isPlatformWebSourceToolCall(toolName: string, args: unknown): boolean {
  157. return [toolName, invokedToolName(args)].some((value) => {
  158. if (!value) return false;
  159. const normalized = normalizeToolName(value);
  160. if (normalized === 'web_search' || normalized === 'web_fetch' || normalized === 'webfetch') {
  161. return true;
  162. }
  163. const mcp = parseMcpToolName(value);
  164. return (
  165. normalizeToolName(mcp?.server ?? '') === 'matrix' &&
  166. (normalizeToolName(mcp?.tool ?? '') === 'web_search' ||
  167. normalizeToolName(mcp?.tool ?? '') === 'web_fetch')
  168. );
  169. });
  170. }
  171. export function readToolResultText(content: readonly unknown[]): string {
  172. return content
  173. .map((block) => readRecord(block))
  174. .map((block) => (block?.type === 'text' ? readNonEmptyString(block.text) : undefined))
  175. .filter((value): value is string => Boolean(value))
  176. .join('\n');
  177. }
  178. function readWebDocumentTitle(content: readonly unknown[]): string | undefined {
  179. const text = readToolResultText(content);
  180. const htmlTitle = /<title[^>]*>\s*([^<]{2,120})\s*<\/title>/iu.exec(text)?.[1]?.trim();
  181. if (htmlTitle) return htmlTitle;
  182. const markdownHeading = /^#{1,2}\s+(.{2,120})$/mu.exec(text)?.[1]?.trim();
  183. return markdownHeading || undefined;
  184. }