@librechat/agents 4.2.12 → 4.2.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (357) hide show
  1. package/dist/cjs/graphs/Graph.cjs +56 -6
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/harness/providerText.cjs +1 -0
  4. package/dist/cjs/harness/providerText.cjs.map +1 -1
  5. package/dist/cjs/llm/anthropic/index.cjs +4 -3
  6. package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
  7. package/dist/cjs/llm/anthropic/utils/container.cjs +37 -0
  8. package/dist/cjs/llm/anthropic/utils/container.cjs.map +1 -0
  9. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +25 -23
  10. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  11. package/dist/cjs/llm/anthropic/utils/message_outputs.cjs +15 -21
  12. package/dist/cjs/llm/anthropic/utils/message_outputs.cjs.map +1 -1
  13. package/dist/cjs/llm/anthropic/utils/stream_events.cjs +16 -14
  14. package/dist/cjs/llm/anthropic/utils/stream_events.cjs.map +1 -1
  15. package/dist/cjs/llm/bedrock/index.cjs +1 -1
  16. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  17. package/dist/cjs/llm/bedrock/toolCache.cjs +1 -1
  18. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +19 -13
  19. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -1
  20. package/dist/cjs/llm/google/utils/common.cjs +59 -13
  21. package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
  22. package/dist/cjs/llm/google/utils/signatures.cjs +22 -14
  23. package/dist/cjs/llm/google/utils/signatures.cjs.map +1 -1
  24. package/dist/cjs/llm/init.cjs +12 -2
  25. package/dist/cjs/llm/init.cjs.map +1 -1
  26. package/dist/cjs/llm/invoke.cjs +122 -13
  27. package/dist/cjs/llm/invoke.cjs.map +1 -1
  28. package/dist/cjs/llm/openai/index.cjs +9 -3
  29. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  30. package/dist/cjs/llm/openai/typedContent.cjs +94 -0
  31. package/dist/cjs/llm/openai/typedContent.cjs.map +1 -0
  32. package/dist/cjs/llm/openrouter/toolCache.cjs +1 -1
  33. package/dist/cjs/llm/prepareProviderRequest.cjs +81 -4
  34. package/dist/cjs/llm/prepareProviderRequest.cjs.map +1 -1
  35. package/dist/cjs/llm/providerTextBatch.cjs +128 -0
  36. package/dist/cjs/llm/providerTextBatch.cjs.map +1 -0
  37. package/dist/cjs/llm/providerTextBoundary.cjs +81 -12
  38. package/dist/cjs/llm/providerTextBoundary.cjs.map +1 -1
  39. package/dist/cjs/main.cjs +8 -3
  40. package/dist/cjs/messages/alternation.cjs +1 -1
  41. package/dist/cjs/messages/anthropicServerTools.cjs +20 -0
  42. package/dist/cjs/messages/anthropicServerTools.cjs.map +1 -0
  43. package/dist/cjs/messages/budget.cjs +1 -1
  44. package/dist/cjs/messages/core.cjs +3 -2
  45. package/dist/cjs/messages/core.cjs.map +1 -1
  46. package/dist/cjs/messages/format.cjs +2 -2
  47. package/dist/cjs/messages/index.cjs +1 -1
  48. package/dist/cjs/messages/prune.cjs +1 -1
  49. package/dist/cjs/messages/recency.cjs +1 -1
  50. package/dist/cjs/messages/toolResultTypes.cjs +21 -45
  51. package/dist/cjs/messages/toolResultTypes.cjs.map +1 -1
  52. package/dist/cjs/protection/providerText.cjs +60 -6
  53. package/dist/cjs/protection/providerText.cjs.map +1 -1
  54. package/dist/cjs/protection/providerTextAdmission.cjs +5 -0
  55. package/dist/cjs/protection/providerTextAdmission.cjs.map +1 -1
  56. package/dist/cjs/protection/toolResult.cjs +119 -0
  57. package/dist/cjs/protection/toolResult.cjs.map +1 -0
  58. package/dist/cjs/run.cjs +14 -3
  59. package/dist/cjs/run.cjs.map +1 -1
  60. package/dist/cjs/runtime/client.cjs +4 -0
  61. package/dist/cjs/runtime/client.cjs.map +1 -1
  62. package/dist/cjs/stream.cjs +10 -2
  63. package/dist/cjs/stream.cjs.map +1 -1
  64. package/dist/cjs/summarization/node.cjs +1 -1
  65. package/dist/cjs/tools/ToolNode.cjs +46 -13
  66. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  67. package/dist/cjs/tools/handlers.cjs +47 -1
  68. package/dist/cjs/tools/handlers.cjs.map +1 -1
  69. package/dist/cjs/tools/search/citations.cjs +194 -0
  70. package/dist/cjs/tools/search/citations.cjs.map +1 -0
  71. package/dist/cjs/tools/search/content.cjs +163 -42
  72. package/dist/cjs/tools/search/content.cjs.map +1 -1
  73. package/dist/cjs/tools/search/firecrawl.cjs +4 -9
  74. package/dist/cjs/tools/search/firecrawl.cjs.map +1 -1
  75. package/dist/cjs/tools/search/google.cjs +68 -0
  76. package/dist/cjs/tools/search/google.cjs.map +1 -0
  77. package/dist/cjs/tools/search/openai.cjs +80 -0
  78. package/dist/cjs/tools/search/openai.cjs.map +1 -0
  79. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +4 -0
  80. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
  81. package/dist/cjs/utils/tokens.cjs +12 -2
  82. package/dist/cjs/utils/tokens.cjs.map +1 -1
  83. package/dist/esm/graphs/Graph.mjs +57 -7
  84. package/dist/esm/graphs/Graph.mjs.map +1 -1
  85. package/dist/esm/harness/providerText.mjs +1 -0
  86. package/dist/esm/harness/providerText.mjs.map +1 -1
  87. package/dist/esm/llm/anthropic/index.mjs +4 -3
  88. package/dist/esm/llm/anthropic/index.mjs.map +1 -1
  89. package/dist/esm/llm/anthropic/utils/container.mjs +37 -0
  90. package/dist/esm/llm/anthropic/utils/container.mjs.map +1 -0
  91. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +25 -23
  92. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  93. package/dist/esm/llm/anthropic/utils/message_outputs.mjs +15 -21
  94. package/dist/esm/llm/anthropic/utils/message_outputs.mjs.map +1 -1
  95. package/dist/esm/llm/anthropic/utils/stream_events.mjs +16 -14
  96. package/dist/esm/llm/anthropic/utils/stream_events.mjs.map +1 -1
  97. package/dist/esm/llm/bedrock/index.mjs +2 -2
  98. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  99. package/dist/esm/llm/bedrock/toolCache.mjs +1 -1
  100. package/dist/esm/llm/bedrock/utils/message_inputs.mjs +19 -14
  101. package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -1
  102. package/dist/esm/llm/google/utils/common.mjs +59 -13
  103. package/dist/esm/llm/google/utils/common.mjs.map +1 -1
  104. package/dist/esm/llm/google/utils/signatures.mjs +22 -14
  105. package/dist/esm/llm/google/utils/signatures.mjs.map +1 -1
  106. package/dist/esm/llm/init.mjs +12 -2
  107. package/dist/esm/llm/init.mjs.map +1 -1
  108. package/dist/esm/llm/invoke.mjs +124 -15
  109. package/dist/esm/llm/invoke.mjs.map +1 -1
  110. package/dist/esm/llm/openai/index.mjs +9 -3
  111. package/dist/esm/llm/openai/index.mjs.map +1 -1
  112. package/dist/esm/llm/openai/typedContent.mjs +93 -0
  113. package/dist/esm/llm/openai/typedContent.mjs.map +1 -0
  114. package/dist/esm/llm/openrouter/toolCache.mjs +1 -1
  115. package/dist/esm/llm/prepareProviderRequest.mjs +81 -4
  116. package/dist/esm/llm/prepareProviderRequest.mjs.map +1 -1
  117. package/dist/esm/llm/providerTextBatch.mjs +128 -0
  118. package/dist/esm/llm/providerTextBatch.mjs.map +1 -0
  119. package/dist/esm/llm/providerTextBoundary.mjs +81 -12
  120. package/dist/esm/llm/providerTextBoundary.mjs.map +1 -1
  121. package/dist/esm/main.mjs +7 -6
  122. package/dist/esm/messages/alternation.mjs +1 -1
  123. package/dist/esm/messages/anthropicServerTools.mjs +18 -0
  124. package/dist/esm/messages/anthropicServerTools.mjs.map +1 -0
  125. package/dist/esm/messages/budget.mjs +1 -1
  126. package/dist/esm/messages/core.mjs +3 -2
  127. package/dist/esm/messages/core.mjs.map +1 -1
  128. package/dist/esm/messages/format.mjs +2 -2
  129. package/dist/esm/messages/index.mjs +1 -1
  130. package/dist/esm/messages/prune.mjs +1 -1
  131. package/dist/esm/messages/recency.mjs +1 -1
  132. package/dist/esm/messages/toolResultTypes.mjs +21 -45
  133. package/dist/esm/messages/toolResultTypes.mjs.map +1 -1
  134. package/dist/esm/protection/providerText.mjs +58 -7
  135. package/dist/esm/protection/providerText.mjs.map +1 -1
  136. package/dist/esm/protection/providerTextAdmission.mjs +5 -0
  137. package/dist/esm/protection/providerTextAdmission.mjs.map +1 -1
  138. package/dist/esm/protection/toolResult.mjs +114 -0
  139. package/dist/esm/protection/toolResult.mjs.map +1 -0
  140. package/dist/esm/run.mjs +14 -3
  141. package/dist/esm/run.mjs.map +1 -1
  142. package/dist/esm/runtime/client.mjs +4 -0
  143. package/dist/esm/runtime/client.mjs.map +1 -1
  144. package/dist/esm/stream.mjs +10 -2
  145. package/dist/esm/stream.mjs.map +1 -1
  146. package/dist/esm/summarization/node.mjs +1 -1
  147. package/dist/esm/tools/ToolNode.mjs +46 -13
  148. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  149. package/dist/esm/tools/handlers.mjs +47 -2
  150. package/dist/esm/tools/handlers.mjs.map +1 -1
  151. package/dist/esm/tools/search/citations.mjs +190 -0
  152. package/dist/esm/tools/search/citations.mjs.map +1 -0
  153. package/dist/esm/tools/search/content.mjs +163 -42
  154. package/dist/esm/tools/search/content.mjs.map +1 -1
  155. package/dist/esm/tools/search/firecrawl.mjs +4 -9
  156. package/dist/esm/tools/search/firecrawl.mjs.map +1 -1
  157. package/dist/esm/tools/search/google.mjs +67 -0
  158. package/dist/esm/tools/search/google.mjs.map +1 -0
  159. package/dist/esm/tools/search/openai.mjs +80 -0
  160. package/dist/esm/tools/search/openai.mjs.map +1 -0
  161. package/dist/esm/tools/subagent/SubagentExecutor.mjs +4 -0
  162. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
  163. package/dist/esm/utils/tokens.mjs +12 -2
  164. package/dist/esm/utils/tokens.mjs.map +1 -1
  165. package/dist/types/common/index.d.ts +2 -2
  166. package/dist/types/decisions/breaker.d.ts +2 -2
  167. package/dist/types/decisions/core.d.ts +13 -13
  168. package/dist/types/decisions/dialect.d.ts +1 -1
  169. package/dist/types/decisions/http.d.ts +2 -2
  170. package/dist/types/decisions/index.d.ts +5 -5
  171. package/dist/types/decisions/node.d.ts +2 -2
  172. package/dist/types/decisions/presets.d.ts +2 -2
  173. package/dist/types/decisions/probe.d.ts +1 -1
  174. package/dist/types/decisions/questions.d.ts +1 -1
  175. package/dist/types/decisions/structuredChat.d.ts +2 -2
  176. package/dist/types/decisions/transport.d.ts +1 -1
  177. package/dist/types/eventActor/EventActorExecutor.d.ts +1 -1
  178. package/dist/types/eventActor/index.d.ts +2 -2
  179. package/dist/types/graphs/Graph.d.ts +18 -2
  180. package/dist/types/graphs/MultiAgentGraph.d.ts +1 -1
  181. package/dist/types/graphs/applyGraphRuntimeConfig.d.ts +1 -1
  182. package/dist/types/graphs/graphFactory.d.ts +1 -1
  183. package/dist/types/graphs/index.d.ts +5 -5
  184. package/dist/types/harness/fileBindings.d.ts +2 -2
  185. package/dist/types/harness/fileService.d.ts +2 -2
  186. package/dist/types/harness/fileStream.d.ts +1 -1
  187. package/dist/types/harness/index.d.ts +15 -15
  188. package/dist/types/harness/model.d.ts +1 -1
  189. package/dist/types/harness/modelService.d.ts +2 -2
  190. package/dist/types/harness/modelStreamCallbacks.d.ts +1 -1
  191. package/dist/types/harness/providerText.d.ts +1 -1
  192. package/dist/types/hitl/index.d.ts +3 -3
  193. package/dist/types/hooks/HookRegistry.d.ts +1 -1
  194. package/dist/types/hooks/createToolPolicyHook.d.ts +1 -1
  195. package/dist/types/hooks/createWorkspacePolicyHook.d.ts +1 -1
  196. package/dist/types/hooks/executeHooks.d.ts +2 -2
  197. package/dist/types/hooks/index.d.ts +11 -11
  198. package/dist/types/index.d.ts +62 -60
  199. package/dist/types/langchain/index.d.ts +8 -8
  200. package/dist/types/llm/anthropic/utils/container.d.ts +4 -0
  201. package/dist/types/llm/anthropic/utils/message_inputs.d.ts +1 -1
  202. package/dist/types/llm/anthropic/utils/message_outputs.d.ts +1 -1
  203. package/dist/types/llm/anthropic/utils/stream_events.d.ts +1 -1
  204. package/dist/types/llm/bedrock/index.d.ts +2 -3
  205. package/dist/types/llm/bedrock/utils/harmony.d.ts +1 -1
  206. package/dist/types/llm/bedrock/utils/index.d.ts +2 -2
  207. package/dist/types/llm/bedrock/utils/message_inputs.d.ts +3 -12
  208. package/dist/types/llm/bedrock/utils/message_outputs.d.ts +1 -1
  209. package/dist/types/llm/google/index.d.ts +2 -2
  210. package/dist/types/llm/google/utils/common.d.ts +1 -1
  211. package/dist/types/llm/google/utils/tools.d.ts +1 -1
  212. package/dist/types/llm/openai/index.d.ts +1 -1
  213. package/dist/types/llm/openai/typedContent.d.ts +14 -0
  214. package/dist/types/llm/providerRegistry.d.ts +1 -1
  215. package/dist/types/llm/providerTextBatch.d.ts +26 -0
  216. package/dist/types/llm/providerTextBoundary.d.ts +7 -1
  217. package/dist/types/llm/providers.d.ts +1 -1
  218. package/dist/types/messages/anthropicServerTools.d.ts +13 -0
  219. package/dist/types/messages/contextPruning.d.ts +1 -1
  220. package/dist/types/messages/core.d.ts +4 -4
  221. package/dist/types/messages/format.d.ts +1 -1
  222. package/dist/types/messages/index.d.ts +21 -21
  223. package/dist/types/messages/prune.d.ts +1 -1
  224. package/dist/types/openai/index.d.ts +2 -2
  225. package/dist/types/openai/toolProjection.d.ts +1 -1
  226. package/dist/types/prompts/index.d.ts +2 -2
  227. package/dist/types/protection/providerText.d.ts +32 -2
  228. package/dist/types/protection/providerTextAdmission.d.ts +1 -0
  229. package/dist/types/protection/toolResult.d.ts +69 -0
  230. package/dist/types/provider-registration.d.ts +1 -1
  231. package/dist/types/rerank/bm25.d.ts +1 -1
  232. package/dist/types/rerank/core.d.ts +17 -17
  233. package/dist/types/rerank/crossEncoder.d.ts +3 -3
  234. package/dist/types/rerank/fallback.d.ts +1 -1
  235. package/dist/types/rerank/index.d.ts +2 -2
  236. package/dist/types/rerank/outcome.d.ts +2 -2
  237. package/dist/types/rerank/pin.d.ts +2 -2
  238. package/dist/types/rerank/search.d.ts +1 -1
  239. package/dist/types/rerank/systemone.d.ts +4 -4
  240. package/dist/types/rerank/types.d.ts +1 -1
  241. package/dist/types/run.d.ts +1 -0
  242. package/dist/types/runtime/admission.d.ts +1 -1
  243. package/dist/types/runtime/checkpoint.d.ts +1 -1
  244. package/dist/types/runtime/client.d.ts +2 -2
  245. package/dist/types/runtime/files.d.ts +3 -3
  246. package/dist/types/runtime/hostTools.d.ts +2 -2
  247. package/dist/types/runtime/index.d.ts +12 -12
  248. package/dist/types/runtime/model.d.ts +5 -5
  249. package/dist/types/runtime/policy.d.ts +3 -3
  250. package/dist/types/runtime/recovery/client.d.ts +3 -3
  251. package/dist/types/runtime/recovery/log.d.ts +2 -2
  252. package/dist/types/runtime/recovery/redis.d.ts +1 -1
  253. package/dist/types/runtime/recovery/server.d.ts +3 -3
  254. package/dist/types/runtime/resume.d.ts +1 -1
  255. package/dist/types/runtime/server.d.ts +3 -3
  256. package/dist/types/runtime/snapshot.d.ts +1 -1
  257. package/dist/types/runtime/types.d.ts +2 -2
  258. package/dist/types/session/AgentSession.d.ts +2 -2
  259. package/dist/types/session/JsonlSessionStore.d.ts +1 -1
  260. package/dist/types/session/deriveMessages.d.ts +1 -1
  261. package/dist/types/session/handlers.d.ts +1 -1
  262. package/dist/types/session/index.d.ts +7 -7
  263. package/dist/types/session/messageSerialization.d.ts +1 -1
  264. package/dist/types/session/sessionProjection.d.ts +3 -3
  265. package/dist/types/summarization/index.d.ts +2 -2
  266. package/dist/types/tools/BashProgrammaticToolCalling.d.ts +1 -1
  267. package/dist/types/tools/GitHubCompare.d.ts +6 -6
  268. package/dist/types/tools/ProgrammaticToolCalling.d.ts +1 -1
  269. package/dist/types/tools/ReadFile.d.ts +6 -6
  270. package/dist/types/tools/SkillTool.d.ts +6 -6
  271. package/dist/types/tools/ToolNode.d.ts +5 -1
  272. package/dist/types/tools/cloudflare/index.d.ts +4 -4
  273. package/dist/types/tools/handlers.d.ts +13 -0
  274. package/dist/types/tools/local/FileCheckpointer.d.ts +1 -1
  275. package/dist/types/tools/local/LocalExecutionEngine.d.ts +1 -1
  276. package/dist/types/tools/local/attachments.d.ts +1 -1
  277. package/dist/types/tools/local/index.d.ts +12 -12
  278. package/dist/types/tools/search/anthropic.d.ts +1 -1
  279. package/dist/types/tools/search/citations.d.ts +88 -0
  280. package/dist/types/tools/search/content.d.ts +38 -1
  281. package/dist/types/tools/search/crw-scraper.d.ts +1 -1
  282. package/dist/types/tools/search/crw-search.d.ts +1 -1
  283. package/dist/types/tools/search/firecrawl.d.ts +4 -2
  284. package/dist/types/tools/search/format.d.ts +1 -1
  285. package/dist/types/tools/search/google.d.ts +11 -0
  286. package/dist/types/tools/search/highlights.d.ts +1 -1
  287. package/dist/types/tools/search/index.d.ts +3 -3
  288. package/dist/types/tools/search/keenable-scraper.d.ts +1 -1
  289. package/dist/types/tools/search/keenable-search.d.ts +1 -1
  290. package/dist/types/tools/search/metrics.d.ts +1 -1
  291. package/dist/types/tools/search/openai.d.ts +3 -0
  292. package/dist/types/tools/search/rerankers.d.ts +1 -1
  293. package/dist/types/tools/search/schema.d.ts +6 -6
  294. package/dist/types/tools/search/search.d.ts +1 -1
  295. package/dist/types/tools/search/serper-scraper.d.ts +1 -1
  296. package/dist/types/tools/search/tavily-scraper.d.ts +1 -1
  297. package/dist/types/tools/search/tavily-search.d.ts +1 -1
  298. package/dist/types/tools/search/tool.d.ts +3 -3
  299. package/dist/types/tools/search/types.d.ts +26 -2
  300. package/dist/types/tools/search/utils.d.ts +3 -3
  301. package/dist/types/tools/subagent/SubagentExecutionRegistry.d.ts +1 -1
  302. package/dist/types/tools/subagent/SubagentExecutor.d.ts +6 -3
  303. package/dist/types/tools/subagent/diagnostics.d.ts +1 -1
  304. package/dist/types/tools/subagent/index.d.ts +7 -7
  305. package/dist/types/types/attachments.d.ts +1 -1
  306. package/dist/types/types/graph.d.ts +4 -1
  307. package/dist/types/types/index.d.ts +14 -14
  308. package/dist/types/types/llm.d.ts +2 -2
  309. package/dist/types/types/run.d.ts +3 -1
  310. package/dist/types/types/stream.d.ts +12 -0
  311. package/dist/types/types/subagentTasks.d.ts +2 -2
  312. package/dist/types/types/tools.d.ts +6 -3
  313. package/dist/types/utils/index.d.ts +10 -10
  314. package/dist/types/utils/tokens.d.ts +2 -0
  315. package/package.json +3 -2
  316. package/src/graphs/Graph.ts +125 -3
  317. package/src/harness/providerText.ts +1 -0
  318. package/src/index.ts +10 -0
  319. package/src/llm/anthropic/index.ts +11 -3
  320. package/src/llm/anthropic/utils/container.ts +63 -0
  321. package/src/llm/anthropic/utils/message_inputs.ts +57 -51
  322. package/src/llm/anthropic/utils/message_outputs.ts +12 -39
  323. package/src/llm/anthropic/utils/stream_events.ts +17 -12
  324. package/src/llm/bedrock/index.ts +7 -5
  325. package/src/llm/bedrock/utils/message_inputs.ts +28 -35
  326. package/src/llm/google/utils/common.ts +88 -36
  327. package/src/llm/google/utils/signatures.ts +52 -36
  328. package/src/llm/init.ts +35 -3
  329. package/src/llm/invoke.ts +160 -16
  330. package/src/llm/openai/index.ts +18 -5
  331. package/src/llm/openai/typedContent.ts +110 -0
  332. package/src/llm/prepareProviderRequest.ts +154 -4
  333. package/src/llm/providerTextBatch.ts +158 -0
  334. package/src/llm/providerTextBoundary.ts +119 -13
  335. package/src/messages/anthropicServerTools.ts +24 -0
  336. package/src/messages/core.ts +12 -11
  337. package/src/messages/toolResultTypes.ts +80 -88
  338. package/src/protection/providerText.ts +222 -46
  339. package/src/protection/providerTextAdmission.ts +6 -0
  340. package/src/protection/toolResult.ts +272 -0
  341. package/src/run.ts +37 -5
  342. package/src/runtime/client.ts +6 -0
  343. package/src/stream.ts +23 -2
  344. package/src/tools/ToolNode.ts +112 -17
  345. package/src/tools/handlers.ts +110 -5
  346. package/src/tools/search/citations.ts +375 -0
  347. package/src/tools/search/content.ts +282 -62
  348. package/src/tools/search/firecrawl.ts +13 -16
  349. package/src/tools/search/google.ts +122 -0
  350. package/src/tools/search/openai.ts +118 -0
  351. package/src/tools/search/types.ts +21 -0
  352. package/src/tools/subagent/SubagentExecutor.ts +6 -0
  353. package/src/types/graph.ts +3 -0
  354. package/src/types/run.ts +3 -0
  355. package/src/types/stream.ts +9 -0
  356. package/src/types/tools.ts +3 -0
  357. package/src/utils/tokens.ts +37 -2
@@ -1,6 +1,280 @@
1
1
  import * as cheerio from 'cheerio';
2
2
  import type { References, MediaReference } from './types';
3
3
 
4
+ type ReferenceType = 'image' | 'video' | 'iframe' | 'link';
5
+
6
+ interface ReferenceTarget {
7
+ type: ReferenceType;
8
+ idx: number;
9
+ }
10
+
11
+ interface ReferenceEntry extends ReferenceTarget {
12
+ url: string;
13
+ }
14
+
15
+ /**
16
+ * Aho-Corasick automaton over `(` followed by every referenced URL, held in
17
+ * typed arrays: 18 bytes per node and no object per node. Nodes are numbered
18
+ * breadth first, so the children of `node` are the nodes from
19
+ * `firstChild[node]` up to `firstChild[node + 1]`, sorted by `code`.
20
+ */
21
+ export interface ReferenceMatcher {
22
+ firstChild: Int32Array;
23
+ code: Uint16Array;
24
+ depth: Int32Array;
25
+ fail: Int32Array;
26
+ /** Nearest node on the fail chain, itself included, that ends a URL, or -1. */
27
+ output: Int32Array;
28
+ targets: Map<number, ReferenceTarget>;
29
+ }
30
+
31
+ interface ReferenceClose {
32
+ end: number;
33
+ title?: string;
34
+ }
35
+
36
+ /**
37
+ * Largest automaton built for one page. Nodes are the distinct URL prefixes, at
38
+ * most the URL characters on the page: 2^21 of them measured 36 MiB and 0.15 s
39
+ * to build, about 100 times a long Wikipedia article. A page above the cap
40
+ * keeps its markdown as is.
41
+ */
42
+ export const MAX_MATCHER_NODES = 1 << 21;
43
+ const OPEN_PAREN = 0x28;
44
+ const CLOSE_PAREN = 0x29;
45
+ const QUOTE = 0x22;
46
+ const WHITESPACE = /\s/;
47
+
48
+ function compareUrls(a: ReferenceEntry, b: ReferenceEntry): number {
49
+ if (a.url === b.url) {
50
+ return 0;
51
+ }
52
+ return a.url < b.url ? -1 : 1;
53
+ }
54
+
55
+ function sharedPrefixLength(a: string, b: string): number {
56
+ const limit = Math.min(a.length, b.length);
57
+ let length = 0;
58
+ while (length < limit && a.charCodeAt(length) === b.charCodeAt(length)) {
59
+ length++;
60
+ }
61
+ return length;
62
+ }
63
+
64
+ /**
65
+ * Indexes every referenced URL once, or returns `undefined` when the automaton
66
+ * would exceed `MAX_MATCHER_NODES`. A URL listed under several types keeps the
67
+ * first, in image, video, iframe, link order, which is the order the replacement
68
+ * has always preferred. Sorting the URLs gives the exact node count before
69
+ * anything is allocated, and lets each node take its children from one
70
+ * contiguous run of URLs.
71
+ */
72
+ export function buildMatcher(
73
+ groups: ReadonlyArray<[ReferenceType, Map<string, MediaReference>]>
74
+ ): ReferenceMatcher | undefined {
75
+ const entries: ReferenceEntry[] = [];
76
+ for (const [type, references] of groups) {
77
+ let idx = 0;
78
+ for (const url of references.keys()) {
79
+ entries.push({ url, type, idx: ++idx });
80
+ }
81
+ }
82
+ entries.sort(compareUrls);
83
+ let size = 2;
84
+ for (let i = 0; i < entries.length; i++) {
85
+ const { url } = entries[i];
86
+ size +=
87
+ url.length - (i === 0 ? 0 : sharedPrefixLength(entries[i - 1].url, url));
88
+ }
89
+ if (size > MAX_MATCHER_NODES) {
90
+ return undefined;
91
+ }
92
+
93
+ const matcher: ReferenceMatcher = {
94
+ firstChild: new Int32Array(size + 1),
95
+ code: new Uint16Array(size),
96
+ depth: new Int32Array(size),
97
+ fail: new Int32Array(size),
98
+ output: new Int32Array(size).fill(-1),
99
+ targets: new Map<number, ReferenceTarget>(),
100
+ };
101
+ const { firstChild, code, depth, fail, output, targets } = matcher;
102
+ /** Nodes awaiting their children span two trie levels, each at most one node per URL. */
103
+ const pending = 2 * entries.length + 2;
104
+ const from = new Int32Array(pending);
105
+ const to = new Int32Array(pending);
106
+ firstChild[0] = 1;
107
+ code[1] = OPEN_PAREN;
108
+ depth[1] = 1;
109
+ to[1] = entries.length;
110
+ let next = 2;
111
+ for (let node = 1; node < next; node++) {
112
+ const consumed = depth[node] - 1;
113
+ const end = to[node % pending];
114
+ let i = from[node % pending];
115
+ const endsUrl = i < end && entries[i].url.length === consumed;
116
+ if (endsUrl) {
117
+ targets.set(node, entries[i]);
118
+ }
119
+ while (i < end && entries[i].url.length === consumed) {
120
+ i++;
121
+ }
122
+ output[node] = endsUrl ? node : output[fail[node]];
123
+ firstChild[node] = next;
124
+ while (i < end) {
125
+ const charCode = entries[i].url.charCodeAt(consumed);
126
+ code[next] = charCode;
127
+ depth[next] = consumed + 2;
128
+ fail[next] = transition(matcher, fail[node], charCode);
129
+ from[next % pending] = i;
130
+ do {
131
+ i++;
132
+ } while (i < end && entries[i].url.charCodeAt(consumed) === charCode);
133
+ to[next % pending] = i;
134
+ next++;
135
+ }
136
+ }
137
+ firstChild[next] = next;
138
+ return matcher;
139
+ }
140
+
141
+ function childOf(
142
+ matcher: ReferenceMatcher,
143
+ node: number,
144
+ charCode: number
145
+ ): number {
146
+ const { firstChild, code } = matcher;
147
+ const end = firstChild[node + 1];
148
+ let low = firstChild[node];
149
+ let high = end;
150
+ while (low < high) {
151
+ const middle = (low + high) >>> 1;
152
+ if (code[middle] < charCode) {
153
+ low = middle + 1;
154
+ } else {
155
+ high = middle;
156
+ }
157
+ }
158
+ return low < end && code[low] === charCode ? low : -1;
159
+ }
160
+
161
+ function transition(
162
+ matcher: ReferenceMatcher,
163
+ from: number,
164
+ charCode: number
165
+ ): number {
166
+ let state = from;
167
+ let next = childOf(matcher, state, charCode);
168
+ while (next === -1 && state !== 0) {
169
+ state = matcher.fail[state];
170
+ next = childOf(matcher, state, charCode);
171
+ }
172
+ return next === -1 ? 0 : next;
173
+ }
174
+
175
+ /**
176
+ * Closes a reference whose URL ends just before `urlEnd` with `)` or
177
+ * ` "title")`. Whitespace runs and quote pairs are resolved once each and
178
+ * cached, so checking many URL ends never rescans the same text.
179
+ */
180
+ function createCloser(
181
+ markdown: string
182
+ ): (urlEnd: number) => ReferenceClose | undefined {
183
+ const closingQuote = new Map<number, number>();
184
+ let nonSpaceFrom: Int32Array | undefined;
185
+ const firstNonSpace = (index: number): number => {
186
+ if (nonSpaceFrom == null) {
187
+ nonSpaceFrom = new Int32Array(markdown.length + 1);
188
+ nonSpaceFrom[markdown.length] = markdown.length;
189
+ for (let i = markdown.length - 1; i >= 0; i--) {
190
+ nonSpaceFrom[i] = WHITESPACE.test(markdown[i])
191
+ ? nonSpaceFrom[i + 1]
192
+ : i;
193
+ }
194
+ }
195
+ return nonSpaceFrom[index];
196
+ };
197
+ return (urlEnd) => {
198
+ const next = markdown.charCodeAt(urlEnd);
199
+ if (next === CLOSE_PAREN) {
200
+ return { end: urlEnd + 1 };
201
+ }
202
+ if (!WHITESPACE.test(markdown[urlEnd] ?? '')) {
203
+ return undefined;
204
+ }
205
+ const open = firstNonSpace(urlEnd);
206
+ if (markdown.charCodeAt(open) !== QUOTE) {
207
+ return undefined;
208
+ }
209
+ let close = closingQuote.get(open);
210
+ if (close == null) {
211
+ close = markdown.indexOf('"', open + 1);
212
+ closingQuote.set(open, close);
213
+ }
214
+ if (close === -1 || markdown.charCodeAt(close + 1) !== CLOSE_PAREN) {
215
+ return undefined;
216
+ }
217
+ return { end: close + 2, title: markdown.slice(open + 1, close) };
218
+ };
219
+ }
220
+
221
+ /**
222
+ * Rewrites every markdown reference to a known URL. One scan finds each
223
+ * `(url` occurrence that is closed as a reference; the longest at each opening
224
+ * parenthesis is applied left to right. The work is linear in the markdown
225
+ * plus the occurrences found, where one regex per URL over the whole page grew
226
+ * with links times page size and blocked the event loop for seconds.
227
+ * Occurrences exceed the markdown length only when URLs are suffixes of one
228
+ * another; n such URLs need about n * n characters of HTML, so the worst case
229
+ * stays near the input size to the power 1.5.
230
+ */
231
+ function replaceReferences(
232
+ markdown: string,
233
+ matcher: ReferenceMatcher
234
+ ): string {
235
+ if (matcher.targets.size === 0) {
236
+ return markdown;
237
+ }
238
+ const { depth, fail, output, targets } = matcher;
239
+ const closeAt = createCloser(markdown);
240
+ const longest = new Map<number, { node: number; close: ReferenceClose }>();
241
+ let state = 0;
242
+ for (let i = 0; i < markdown.length; i++) {
243
+ state = transition(matcher, state, markdown.charCodeAt(i));
244
+ let node = output[state];
245
+ if (node === -1) {
246
+ continue;
247
+ }
248
+ const close = closeAt(i + 1);
249
+ if (close == null) {
250
+ continue;
251
+ }
252
+ for (; node !== -1; node = output[fail[node]]) {
253
+ const start = i - depth[node] + 1;
254
+ const current = longest.get(start);
255
+ if (current == null || depth[current.node] < depth[node]) {
256
+ longest.set(start, { node, close });
257
+ }
258
+ }
259
+ }
260
+
261
+ let result = '';
262
+ let copied = 0;
263
+ const ordered = Array.from(longest.entries()).sort((a, b) => a[0] - b[0]);
264
+ for (const [start, { node, close }] of ordered) {
265
+ const target = targets.get(node);
266
+ if (start < copied || target == null) {
267
+ continue;
268
+ }
269
+ const label = `${target.type}#${target.idx}`;
270
+ const text =
271
+ close.title == null ? `(${label})` : `(${label} "${close.title}")`;
272
+ result += markdown.slice(copied, start) + text;
273
+ copied = close.end;
274
+ }
275
+ return result + markdown.slice(copied);
276
+ }
277
+
4
278
  export function processContent(
5
279
  html: string,
6
280
  markdown: string
@@ -67,68 +341,14 @@ export function processContent(
67
341
  }
68
342
  });
69
343
 
70
- // Create lookup maps with indices
71
- const linkIndexMap = new Map<string, number>();
72
- const imageIndexMap = new Map<string, number>();
73
- const videoIndexMap = new Map<string, number>();
74
- const iframeIndexMap = new Map<string, number>();
75
-
76
- Array.from(linkMap.keys()).forEach((url, i) => linkIndexMap.set(url, i + 1));
77
- Array.from(imageMap.keys()).forEach((url, i) =>
78
- imageIndexMap.set(url, i + 1)
79
- );
80
- Array.from(videoMap.keys()).forEach((url, i) =>
81
- videoIndexMap.set(url, i + 1)
82
- );
83
- Array.from(iframeMap.keys()).forEach((url, i) =>
84
- iframeIndexMap.set(url, i + 1)
85
- );
86
-
87
- // Process the markdown
88
- let result = markdown;
89
-
90
- // Replace each URL one by one, starting with the longest URLs first to avoid partial matches
91
- const allUrls = [
92
- ...Array.from(imageMap.keys()).map((url) => ({
93
- url,
94
- type: 'image',
95
- idx: imageIndexMap.get(url),
96
- })),
97
- ...Array.from(videoMap.keys()).map((url) => ({
98
- url,
99
- type: 'video',
100
- idx: videoIndexMap.get(url),
101
- })),
102
- ...Array.from(iframeMap.keys()).map((url) => ({
103
- url,
104
- type: 'iframe',
105
- idx: iframeIndexMap.get(url),
106
- })),
107
- ...Array.from(linkMap.keys()).map((url) => ({
108
- url,
109
- type: 'link',
110
- idx: linkIndexMap.get(url),
111
- })),
112
- ].sort((a, b) => b.url.length - a.url.length);
113
-
114
- // Create a function to escape special characters in URLs for regex
115
- function escapeRegex(string: string): string {
116
- return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
117
- }
118
-
119
- // Replace each URL in the markdown
120
- for (const { url, type, idx } of allUrls) {
121
- // Create a regex that captures URLs in markdown links
122
- const regex = new RegExp(`\\(${escapeRegex(url)}(?:\\s+"[^"]*")?\\)`, 'g');
123
-
124
- result = result.replace(regex, (match) => {
125
- // Keep any title attribute that might exist
126
- const titleMatch = match.match(/\s+"([^"]*)"/);
127
- const titlePart = titleMatch ? ` "${titleMatch[1]}"` : '';
128
-
129
- return `(${type}#${idx}${titlePart})`;
130
- });
131
- }
344
+ const matcher = buildMatcher([
345
+ ['image', imageMap],
346
+ ['video', videoMap],
347
+ ['iframe', iframeMap],
348
+ ['link', linkMap],
349
+ ]);
350
+ const result =
351
+ matcher == null ? markdown : replaceReferences(markdown, matcher);
132
352
 
133
353
  iframeMap.clear();
134
354
  const links = Array.from(linkMap.values());
@@ -5,7 +5,9 @@ import { processContent } from './content';
5
5
 
6
6
  /**
7
7
  * Firecrawl scraper implementation
8
- * Uses the Firecrawl API to scrape web pages
8
+ * Uses the Firecrawl API to scrape web pages. Without an API key, requests go
9
+ * out with no Authorization header, which a self-hosted instance running
10
+ * without authentication accepts.
9
11
  */
10
12
  export class FirecrawlScraper implements t.BaseScraper {
11
13
  private apiKey: string;
@@ -67,7 +69,9 @@ export class FirecrawlScraper implements t.BaseScraper {
67
69
  this.httpsAgent = config.httpsAgent;
68
70
 
69
71
  if (!this.apiKey) {
70
- this.logger.warn('FIRECRAWL_API_KEY is not set. Scraping will not work.');
72
+ this.logger.debug(
73
+ 'FIRECRAWL_API_KEY is not set; Firecrawl requests are sent without an API key'
74
+ );
71
75
  }
72
76
 
73
77
  this.logger.debug(
@@ -85,16 +89,6 @@ export class FirecrawlScraper implements t.BaseScraper {
85
89
  url: string,
86
90
  options: t.FirecrawlScrapeOptions = {}
87
91
  ): Promise<[string, t.FirecrawlScrapeResponse]> {
88
- if (!this.apiKey) {
89
- return [
90
- url,
91
- {
92
- success: false,
93
- error: 'FIRECRAWL_API_KEY is not set',
94
- },
95
- ];
96
- }
97
-
98
92
  try {
99
93
  const payload = omitUndefined({
100
94
  url,
@@ -119,11 +113,14 @@ export class FirecrawlScraper implements t.BaseScraper {
119
113
  changeTrackingOptions:
120
114
  options.changeTrackingOptions ?? this.changeTrackingOptions,
121
115
  });
116
+ const headers: Record<string, string> = {
117
+ 'Content-Type': 'application/json',
118
+ };
119
+ if (this.apiKey) {
120
+ headers.Authorization = `Bearer ${this.apiKey}`;
121
+ }
122
122
  const response = await axios.post(this.apiUrl, payload, {
123
- headers: {
124
- 'Content-Type': 'application/json',
125
- Authorization: `Bearer ${this.apiKey}`,
126
- },
123
+ headers,
127
124
  timeout: this.timeout,
128
125
  httpAgent: this.httpAgent,
129
126
  httpsAgent: this.httpsAgent,
@@ -0,0 +1,122 @@
1
+ import type { GoogleGroundingMetadata, ProcessedOrganic } from './types';
2
+ import type { NativeSearchResults, CitationSpan } from './citations';
3
+ import { byteToCharOffset } from './citations';
4
+ import { getAttribution } from './utils';
5
+
6
+ type GroundedChunk = {
7
+ additional_kwargs?: Record<string, unknown>;
8
+ response_metadata?: Record<string, unknown>;
9
+ };
10
+
11
+ function isGroundingMetadata(value: unknown): value is GoogleGroundingMetadata {
12
+ return (
13
+ value != null &&
14
+ typeof value === 'object' &&
15
+ Array.isArray((value as GoogleGroundingMetadata).groundingChunks)
16
+ );
17
+ }
18
+
19
+ /** Gemini API chunks carry it in `additional_kwargs`, Vertex AI chunks in `response_metadata`. */
20
+ export function getGoogleGroundingMetadata(
21
+ chunk: GroundedChunk
22
+ ): GoogleGroundingMetadata | undefined {
23
+ const candidates = [
24
+ chunk.additional_kwargs?.groundingMetadata,
25
+ chunk.response_metadata?.groundingMetadata,
26
+ chunk.response_metadata?.grounding_metadata,
27
+ ];
28
+ return candidates.find(isGroundingMetadata);
29
+ }
30
+
31
+ /**
32
+ * Finds where a grounded segment ends in the call text. The API measures
33
+ * offsets in UTF-8 bytes of one response part, and streamed text carries no
34
+ * part boundaries, so the byte offset is trusted only for the first part and
35
+ * when the segment text sits right before it. A first-part segment is
36
+ * otherwise searched from the previous segment's end; a later part's segment
37
+ * is placed only when its text occurs once, never at a guessed occurrence.
38
+ */
39
+ function locateSegmentEnd(
40
+ text: string,
41
+ segment: { partIndex?: number; endIndex?: number; text?: string },
42
+ cursor: number
43
+ ): number | undefined {
44
+ const value = segment.text;
45
+ const firstPart = (segment.partIndex ?? 0) === 0;
46
+ const end =
47
+ firstPart && typeof segment.endIndex === 'number'
48
+ ? byteToCharOffset(text, segment.endIndex)
49
+ : undefined;
50
+ if (value == null || value === '') {
51
+ return end;
52
+ }
53
+ if (end != null && text.slice(end - value.length, end) === value) {
54
+ return end;
55
+ }
56
+ if (!firstPart) {
57
+ const index = text.indexOf(value);
58
+ return index !== -1 && text.indexOf(value, index + 1) === -1
59
+ ? index + value.length
60
+ : undefined;
61
+ }
62
+ let index = text.indexOf(value, cursor);
63
+ if (index === -1) {
64
+ index = text.indexOf(value);
65
+ }
66
+ return index === -1 ? undefined : index + value.length;
67
+ }
68
+
69
+ /** Turns Gemini grounding into organic results and the spans each support cites. */
70
+ export function coerceGoogleGroundingResults(
71
+ grounding: GoogleGroundingMetadata,
72
+ text: string
73
+ ): NativeSearchResults | undefined {
74
+ const organic: ProcessedOrganic[] = [];
75
+ const sourceByChunk = new Map<number, number>();
76
+ grounding.groundingChunks?.forEach((chunk, index) => {
77
+ const link = chunk.web?.uri;
78
+ if (link == null || link === '') {
79
+ return;
80
+ }
81
+ sourceByChunk.set(index, organic.length);
82
+ organic.push({
83
+ link,
84
+ position: organic.length + 1,
85
+ title: chunk.web?.title,
86
+ attribution:
87
+ chunk.web?.domain ?? chunk.web?.title ?? getAttribution(link),
88
+ });
89
+ });
90
+ if (organic.length === 0) {
91
+ return undefined;
92
+ }
93
+
94
+ const sourcesByEnd = new Map<number, number[]>();
95
+ let cursor = 0;
96
+ for (const support of grounding.groundingSupports ?? []) {
97
+ const sources = [
98
+ ...new Set(
99
+ (support.groundingChunkIndices ?? []).flatMap(
100
+ (index) => sourceByChunk.get(index) ?? []
101
+ )
102
+ ),
103
+ ];
104
+ if (sources.length === 0 || support.segment == null) {
105
+ continue;
106
+ }
107
+ const end = locateSegmentEnd(text, support.segment, cursor);
108
+ if (end == null) {
109
+ continue;
110
+ }
111
+ cursor = end;
112
+ const cited = sourcesByEnd.get(end) ?? [];
113
+ sourcesByEnd.set(end, [...new Set([...cited, ...sources])]);
114
+ }
115
+
116
+ const spans: CitationSpan[] = [...sourcesByEnd].map(([end, sources]) => ({
117
+ start: end,
118
+ end,
119
+ sources,
120
+ }));
121
+ return { organic, spans, queries: grounding.webSearchQueries };
122
+ }
@@ -0,0 +1,118 @@
1
+ import type {
2
+ NativeSearchResults,
3
+ CitationSpan,
4
+ UrlCitation,
5
+ } from './citations';
6
+ import type { ProcessedOrganic } from './types';
7
+ import { getAttribution, getDomainName } from './utils';
8
+
9
+ /** A markdown link, optionally wrapped in the parentheses OpenAI puts around citations. */
10
+ const MARKDOWN_LINK = /^\(?\[[^\]\n]+\]\((https?:\/\/\S+?)\)\)?$/;
11
+
12
+ function linksTo(span: string, url: string): boolean {
13
+ const target = MARKDOWN_LINK.exec(span)?.[1];
14
+ if (target == null) {
15
+ return false;
16
+ }
17
+ return target === url || getDomainName(target) === getDomainName(url);
18
+ }
19
+
20
+ function matchLink(
21
+ text: string,
22
+ start: number,
23
+ end: number,
24
+ url: string
25
+ ): { start: number; end: number } | undefined {
26
+ for (const close of [end, end + 1]) {
27
+ if (!linksTo(text.slice(start, close), url)) {
28
+ continue;
29
+ }
30
+ const wrapped = text[start - 1] === '(' && text[close] === ')';
31
+ return wrapped
32
+ ? { start: start - 1, end: close + 1 }
33
+ : { start, end: close };
34
+ }
35
+ return undefined;
36
+ }
37
+
38
+ /** UTF-16 index of every code point from `from` to the end of `text`, then the end itself. */
39
+ function getCodePointOffsets(text: string, from: number): number[] {
40
+ const offsets: number[] = [];
41
+ let index = from;
42
+ while (index < text.length) {
43
+ offsets.push(index);
44
+ index += (text.codePointAt(index) ?? 0) > 0xffff ? 2 : 1;
45
+ }
46
+ offsets.push(index);
47
+ return offsets;
48
+ }
49
+
50
+ /**
51
+ * Finds the inline markdown link a `url_citation` covers. Its indices count
52
+ * characters of one output text block; they are read as UTF-16 first, then as
53
+ * code points, and the end is tried as exclusive and inclusive. A span that is
54
+ * not a link to the cited host is left alone.
55
+ */
56
+ function locateLink(
57
+ text: string,
58
+ blockStart: number,
59
+ citation: UrlCitation,
60
+ getOffsets: () => number[]
61
+ ): { start: number; end: number } | undefined {
62
+ const { start, end, url } = citation;
63
+ if (start == null || end == null) {
64
+ return undefined;
65
+ }
66
+ const direct = matchLink(text, blockStart + start, blockStart + end, url);
67
+ if (direct != null) {
68
+ return direct;
69
+ }
70
+ const offsets = getOffsets();
71
+ const from = offsets.at(start);
72
+ const to = offsets.at(end);
73
+ return from == null || to == null
74
+ ? undefined
75
+ : matchLink(text, from, to, url);
76
+ }
77
+
78
+ /** Turns OpenAI `url_citation` annotations into organic results and the links they replace. */
79
+ export function coerceOpenAICitationResults(
80
+ citations: readonly UrlCitation[],
81
+ text: string,
82
+ blocks: ReadonlyMap<number, number>
83
+ ): NativeSearchResults | undefined {
84
+ const organic: ProcessedOrganic[] = [];
85
+ const sourceByUrl = new Map<string, number>();
86
+ const offsetsByBlock = new Map<number, number[]>();
87
+ const spans: CitationSpan[] = [];
88
+ for (const citation of citations) {
89
+ let source = sourceByUrl.get(citation.url);
90
+ if (source == null) {
91
+ source = organic.length;
92
+ sourceByUrl.set(citation.url, source);
93
+ organic.push({
94
+ link: citation.url,
95
+ position: source + 1,
96
+ title: citation.title,
97
+ attribution: getAttribution(citation.url),
98
+ });
99
+ }
100
+ const blockStart =
101
+ citation.block == null ? undefined : blocks.get(citation.block);
102
+ const span =
103
+ blockStart == null
104
+ ? undefined
105
+ : locateLink(text, blockStart, citation, () => {
106
+ let offsets = offsetsByBlock.get(blockStart);
107
+ if (offsets == null) {
108
+ offsets = getCodePointOffsets(text, blockStart);
109
+ offsetsByBlock.set(blockStart, offsets);
110
+ }
111
+ return offsets;
112
+ });
113
+ if (span != null) {
114
+ spans.push({ ...span, sources: [source] });
115
+ }
116
+ }
117
+ return organic.length > 0 ? { organic, spans } : undefined;
118
+ }
@@ -75,6 +75,27 @@ export interface SearchResultData {
75
75
  error?: string;
76
76
  }
77
77
 
78
+ /**
79
+ * Gemini's `groundingMetadata` as the API returns it. The
80
+ * `@google/generative-ai` declarations type `segment` as a string and
81
+ * misspell `groundingChunkIndices`, so they cannot describe it.
82
+ */
83
+ export type GoogleGroundingMetadata = {
84
+ webSearchQueries?: string[];
85
+ groundingChunks?: {
86
+ web?: { uri?: string; title?: string; domain?: string };
87
+ }[];
88
+ groundingSupports?: {
89
+ segment?: {
90
+ partIndex?: number;
91
+ startIndex?: number;
92
+ endIndex?: number;
93
+ text?: string;
94
+ };
95
+ groundingChunkIndices?: number[];
96
+ }[];
97
+ };
98
+
78
99
  export interface SearchResult {
79
100
  data?: SearchResultData;
80
101
  error?: string;