@librechat/agents 4.2.13 → 4.2.15

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 (147) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +75 -19
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/graphs/Graph.cjs +52 -6
  4. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  5. package/dist/cjs/harness/providerText.cjs +1 -0
  6. package/dist/cjs/harness/providerText.cjs.map +1 -1
  7. package/dist/cjs/llm/google/utils/signatures.cjs +22 -14
  8. package/dist/cjs/llm/google/utils/signatures.cjs.map +1 -1
  9. package/dist/cjs/llm/invoke.cjs +122 -13
  10. package/dist/cjs/llm/invoke.cjs.map +1 -1
  11. package/dist/cjs/llm/openai/index.cjs +8 -2
  12. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  13. package/dist/cjs/llm/openai/typedContent.cjs +94 -0
  14. package/dist/cjs/llm/openai/typedContent.cjs.map +1 -0
  15. package/dist/cjs/llm/prepareProviderRequest.cjs +102 -7
  16. package/dist/cjs/llm/prepareProviderRequest.cjs.map +1 -1
  17. package/dist/cjs/llm/providerTextBatch.cjs +128 -0
  18. package/dist/cjs/llm/providerTextBatch.cjs.map +1 -0
  19. package/dist/cjs/llm/providerTextBoundary.cjs +81 -12
  20. package/dist/cjs/llm/providerTextBoundary.cjs.map +1 -1
  21. package/dist/cjs/main.cjs +3 -0
  22. package/dist/cjs/messages/content.cjs +3 -3
  23. package/dist/cjs/messages/content.cjs.map +1 -1
  24. package/dist/cjs/messages/vision.cjs +77 -0
  25. package/dist/cjs/messages/vision.cjs.map +1 -0
  26. package/dist/cjs/protection/providerText.cjs +56 -6
  27. package/dist/cjs/protection/providerText.cjs.map +1 -1
  28. package/dist/cjs/protection/providerTextAdmission.cjs +5 -0
  29. package/dist/cjs/protection/providerTextAdmission.cjs.map +1 -1
  30. package/dist/cjs/run.cjs +7 -2
  31. package/dist/cjs/run.cjs.map +1 -1
  32. package/dist/cjs/runtime/client.cjs +2 -0
  33. package/dist/cjs/runtime/client.cjs.map +1 -1
  34. package/dist/cjs/stream.cjs +9 -2
  35. package/dist/cjs/stream.cjs.map +1 -1
  36. package/dist/cjs/summarization/node.cjs +6 -2
  37. package/dist/cjs/summarization/node.cjs.map +1 -1
  38. package/dist/cjs/tools/handlers.cjs +47 -1
  39. package/dist/cjs/tools/handlers.cjs.map +1 -1
  40. package/dist/cjs/tools/search/citations.cjs +194 -0
  41. package/dist/cjs/tools/search/citations.cjs.map +1 -0
  42. package/dist/cjs/tools/search/firecrawl.cjs +4 -9
  43. package/dist/cjs/tools/search/firecrawl.cjs.map +1 -1
  44. package/dist/cjs/tools/search/google.cjs +68 -0
  45. package/dist/cjs/tools/search/google.cjs.map +1 -0
  46. package/dist/cjs/tools/search/openai.cjs +80 -0
  47. package/dist/cjs/tools/search/openai.cjs.map +1 -0
  48. package/dist/cjs/utils/tokens.cjs +6 -0
  49. package/dist/cjs/utils/tokens.cjs.map +1 -1
  50. package/dist/esm/agents/AgentContext.mjs +76 -20
  51. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  52. package/dist/esm/graphs/Graph.mjs +53 -7
  53. package/dist/esm/graphs/Graph.mjs.map +1 -1
  54. package/dist/esm/harness/providerText.mjs +1 -0
  55. package/dist/esm/harness/providerText.mjs.map +1 -1
  56. package/dist/esm/llm/google/utils/signatures.mjs +22 -14
  57. package/dist/esm/llm/google/utils/signatures.mjs.map +1 -1
  58. package/dist/esm/llm/invoke.mjs +124 -15
  59. package/dist/esm/llm/invoke.mjs.map +1 -1
  60. package/dist/esm/llm/openai/index.mjs +8 -2
  61. package/dist/esm/llm/openai/index.mjs.map +1 -1
  62. package/dist/esm/llm/openai/typedContent.mjs +93 -0
  63. package/dist/esm/llm/openai/typedContent.mjs.map +1 -0
  64. package/dist/esm/llm/prepareProviderRequest.mjs +102 -7
  65. package/dist/esm/llm/prepareProviderRequest.mjs.map +1 -1
  66. package/dist/esm/llm/providerTextBatch.mjs +128 -0
  67. package/dist/esm/llm/providerTextBatch.mjs.map +1 -0
  68. package/dist/esm/llm/providerTextBoundary.mjs +81 -12
  69. package/dist/esm/llm/providerTextBoundary.mjs.map +1 -1
  70. package/dist/esm/main.mjs +4 -4
  71. package/dist/esm/messages/content.mjs +3 -3
  72. package/dist/esm/messages/content.mjs.map +1 -1
  73. package/dist/esm/messages/vision.mjs +73 -0
  74. package/dist/esm/messages/vision.mjs.map +1 -0
  75. package/dist/esm/protection/providerText.mjs +55 -7
  76. package/dist/esm/protection/providerText.mjs.map +1 -1
  77. package/dist/esm/protection/providerTextAdmission.mjs +5 -0
  78. package/dist/esm/protection/providerTextAdmission.mjs.map +1 -1
  79. package/dist/esm/run.mjs +7 -2
  80. package/dist/esm/run.mjs.map +1 -1
  81. package/dist/esm/runtime/client.mjs +2 -0
  82. package/dist/esm/runtime/client.mjs.map +1 -1
  83. package/dist/esm/stream.mjs +9 -2
  84. package/dist/esm/stream.mjs.map +1 -1
  85. package/dist/esm/summarization/node.mjs +6 -2
  86. package/dist/esm/summarization/node.mjs.map +1 -1
  87. package/dist/esm/tools/handlers.mjs +47 -2
  88. package/dist/esm/tools/handlers.mjs.map +1 -1
  89. package/dist/esm/tools/search/citations.mjs +190 -0
  90. package/dist/esm/tools/search/citations.mjs.map +1 -0
  91. package/dist/esm/tools/search/firecrawl.mjs +4 -9
  92. package/dist/esm/tools/search/firecrawl.mjs.map +1 -1
  93. package/dist/esm/tools/search/google.mjs +67 -0
  94. package/dist/esm/tools/search/google.mjs.map +1 -0
  95. package/dist/esm/tools/search/openai.mjs +80 -0
  96. package/dist/esm/tools/search/openai.mjs.map +1 -0
  97. package/dist/esm/utils/tokens.mjs +6 -1
  98. package/dist/esm/utils/tokens.mjs.map +1 -1
  99. package/dist/types/agents/AgentContext.d.ts +20 -1
  100. package/dist/types/graphs/Graph.d.ts +14 -0
  101. package/dist/types/index.d.ts +2 -2
  102. package/dist/types/llm/openai/typedContent.d.ts +14 -0
  103. package/dist/types/llm/prepareProviderRequest.d.ts +7 -1
  104. package/dist/types/llm/providerTextBatch.d.ts +26 -0
  105. package/dist/types/llm/providerTextBoundary.d.ts +7 -1
  106. package/dist/types/messages/content.d.ts +2 -1
  107. package/dist/types/messages/vision.d.ts +20 -0
  108. package/dist/types/protection/providerText.d.ts +29 -1
  109. package/dist/types/protection/providerTextAdmission.d.ts +1 -0
  110. package/dist/types/tools/handlers.d.ts +13 -0
  111. package/dist/types/tools/search/citations.d.ts +88 -0
  112. package/dist/types/tools/search/firecrawl.d.ts +3 -1
  113. package/dist/types/tools/search/google.d.ts +11 -0
  114. package/dist/types/tools/search/openai.d.ts +3 -0
  115. package/dist/types/tools/search/types.d.ts +24 -0
  116. package/dist/types/types/graph.d.ts +8 -0
  117. package/dist/types/types/stream.d.ts +12 -0
  118. package/dist/types/utils/tokens.d.ts +3 -0
  119. package/package.json +1 -1
  120. package/src/agents/AgentContext.ts +188 -78
  121. package/src/graphs/Graph.ts +117 -8
  122. package/src/harness/providerText.ts +1 -0
  123. package/src/index.ts +2 -0
  124. package/src/llm/google/utils/signatures.ts +52 -36
  125. package/src/llm/invoke.ts +160 -16
  126. package/src/llm/openai/index.ts +18 -5
  127. package/src/llm/openai/typedContent.ts +110 -0
  128. package/src/llm/prepareProviderRequest.ts +206 -7
  129. package/src/llm/providerTextBatch.ts +158 -0
  130. package/src/llm/providerTextBoundary.ts +119 -13
  131. package/src/messages/content.ts +10 -4
  132. package/src/messages/vision.ts +109 -0
  133. package/src/protection/providerText.ts +95 -6
  134. package/src/protection/providerTextAdmission.ts +6 -0
  135. package/src/run.ts +22 -1
  136. package/src/runtime/client.ts +3 -0
  137. package/src/stream.ts +18 -2
  138. package/src/summarization/node.ts +4 -0
  139. package/src/tools/handlers.ts +110 -5
  140. package/src/tools/search/citations.ts +375 -0
  141. package/src/tools/search/firecrawl.ts +13 -16
  142. package/src/tools/search/google.ts +122 -0
  143. package/src/tools/search/openai.ts +118 -0
  144. package/src/tools/search/types.ts +21 -0
  145. package/src/types/graph.ts +8 -0
  146. package/src/types/stream.ts +9 -0
  147. package/src/utils/tokens.ts +13 -1
package/src/stream.ts CHANGED
@@ -63,8 +63,10 @@ import { resolveToolOutcome, outcomeFieldsFromResult } from '@/tools/intentArg';
63
63
  import { snapshotValidatedModelChunk } from '@/graphs/acceptedModelResponse';
64
64
  import { ProviderTextProtectionError } from '@/protection/providerText';
65
65
  import { TOOL_OUTPUT_REF_PATTERN } from '@/tools/toolOutputReferences';
66
+ import { getGoogleGroundingMetadata } from '@/tools/search/google';
66
67
  import { formatToolErrorContent } from '@/tools/toolErrorContent';
67
68
  import { PreparedSubagentError } from '@/tools/preparedSubagents';
69
+ import { applyTextEdits } from '@/tools/search/citations';
68
70
  import { isReasoningContentBlock } from '@/messages/core';
69
71
  import { composeAbortSignals } from '@/utils/misc';
70
72
  import { isGoogleLike } from '@/utils/llm';
@@ -1816,6 +1818,12 @@ export class ChatModelStreamHandler implements t.EventHandler {
1816
1818
  if (metadata?.summarization === true) return;
1817
1819
 
1818
1820
  const agentContext = graph.getAgentContext(metadata);
1821
+ const grounding = isGoogleLike(agentContext.provider)
1822
+ ? getGoogleGroundingMetadata(chunk)
1823
+ : undefined;
1824
+ if (grounding != null) {
1825
+ graph.groundSearchCitations(metadata, grounding);
1826
+ }
1819
1827
 
1820
1828
  const content = getChunkContent({
1821
1829
  chunk,
@@ -2503,16 +2511,24 @@ export function createContentAggregator(): t.ContentAggregatorResult {
2503
2511
  citations?: t.MessageDeltaUpdate['citations'];
2504
2512
  };
2505
2513
  const incomingCitations = Array.isArray(citations) ? citations : undefined;
2514
+ const { edits } = contentPart as { edits?: t.MessageDeltaUpdate['edits'] };
2515
+ const incomingEdits = Array.isArray(edits) ? edits : undefined;
2506
2516
 
2507
2517
  if (
2508
2518
  partType.startsWith(ContentTypes.TEXT) &&
2509
- (incomingText !== undefined || incomingCitations !== undefined)
2519
+ (incomingText !== undefined ||
2520
+ incomingCitations !== undefined ||
2521
+ incomingEdits !== undefined)
2510
2522
  ) {
2511
2523
  // TODO: update this!!
2512
2524
  const currentContent = contentParts[index] as t.MessageDeltaUpdate;
2525
+ const text = (currentContent.text || '') + (incomingText ?? '');
2513
2526
  const update: t.MessageDeltaUpdate = {
2514
2527
  type: ContentTypes.TEXT,
2515
- text: (currentContent.text || '') + (incomingText ?? ''),
2528
+ text:
2529
+ incomingEdits === undefined
2530
+ ? text
2531
+ : applyTextEdits(text, incomingEdits),
2516
2532
  };
2517
2533
 
2518
2534
  if (contentPart.tool_call_ids) {
@@ -1238,6 +1238,8 @@ async function runSummarizationAttempts(
1238
1238
  provider,
1239
1239
  context: graph,
1240
1240
  config,
1241
+ vision: agentContext.vision,
1242
+ useLegacyContent: agentContext.useLegacyContent,
1241
1243
  });
1242
1244
  fallbackIdentity = {
1243
1245
  provider,
@@ -2554,6 +2556,8 @@ async function summarizeWithCacheHit({
2554
2556
  provider,
2555
2557
  context: graph,
2556
2558
  config: signalConfig,
2559
+ vision: agentContext.vision,
2560
+ useLegacyContent: agentContext.useLegacyContent,
2557
2561
  });
2558
2562
  result = await attemptInvoke(
2559
2563
  {
@@ -3,21 +3,30 @@
3
3
  import { nanoid } from 'nanoid';
4
4
  import { ToolMessage } from '@langchain/core/messages';
5
5
  import type { ToolCall, ToolCallChunk } from '@langchain/core/messages/tool';
6
+ import type {
7
+ NativeSearchResults,
8
+ NativeSearchCall,
9
+ } from '@/tools/search/citations';
6
10
  import type { AnthropicWebSearchResultBlockParam } from '@/llm/anthropic/types';
7
11
  import type { Graph, MultiAgentGraph, StandardGraph } from '@/graphs';
12
+ import type { SearchResultData } from '@/tools/search/types';
8
13
  import type { AgentContext } from '@/agents/AgentContext';
9
14
  import type * as t from '@/types';
10
- import {
11
- coerceAnthropicSearchResults,
12
- isAnthropicWebSearchResult,
13
- } from '@/tools/search/anthropic';
14
15
  import {
15
16
  ToolCallTypes,
17
+ ContentTypes,
16
18
  GraphEvents,
17
19
  StepTypes,
18
20
  Providers,
19
21
  Constants,
20
22
  } from '@/common';
23
+ import {
24
+ coerceAnthropicSearchResults,
25
+ isAnthropicWebSearchResult,
26
+ } from '@/tools/search/anthropic';
27
+ import { coerceGoogleGroundingResults } from '@/tools/search/google';
28
+ import { coerceOpenAICitationResults } from '@/tools/search/openai';
29
+ import { formatSearchAnchors } from '@/tools/search/citations';
21
30
  import { formatResultsForLLM } from '@/tools/search/format';
22
31
  import { getMessageId } from '@/messages';
23
32
 
@@ -353,11 +362,14 @@ async function handleAnthropicSearchResults({
353
362
  return;
354
363
  }
355
364
 
356
- const turn = graph.invokedToolIds?.size ?? 0;
365
+ const turn = graph.searchCitations.turn(graph.invokedToolIds?.size ?? 0);
357
366
  const searchResultData = coerceAnthropicSearchResults({
358
367
  turn,
359
368
  results: contentPart.content as AnthropicWebSearchResultBlockParam[],
360
369
  });
370
+ if (!bindsSearchTool(graph)) {
371
+ graph.searchCitations.register(searchResultData);
372
+ }
361
373
 
362
374
  const name = toolCall.name;
363
375
  const input = toolCall.args ?? {};
@@ -388,3 +400,96 @@ async function handleAnthropicSearchResults({
388
400
 
389
401
  graph.invokedToolIds.add(toolCall.id!);
390
402
  }
403
+
404
+ /**
405
+ * The SDK's own search tool numbers its turns per agent and tool, apart from
406
+ * native searches, so a run where any agent binds it keeps provider citations
407
+ * as they are rather than risk two results sharing a turn. Provider server
408
+ * tools (`{ type: 'web_search_20250305', name: 'web_search' }`) carry a
409
+ * `type`; the SDK tool and its definitions never do.
410
+ */
411
+ function bindsSearchTool(graph: StandardGraph | MultiAgentGraph): boolean {
412
+ for (const context of graph.agentContexts.values()) {
413
+ if (
414
+ context.toolDefinitions?.some(
415
+ ({ name }) => name === Constants.WEB_SEARCH
416
+ ) === true ||
417
+ context.tools?.some(
418
+ (tool) =>
419
+ 'name' in tool &&
420
+ tool.name === Constants.WEB_SEARCH &&
421
+ !('type' in tool)
422
+ ) === true
423
+ ) {
424
+ return true;
425
+ }
426
+ }
427
+ return false;
428
+ }
429
+
430
+ function getNativeSearchResults(
431
+ graph: StandardGraph | MultiAgentGraph,
432
+ call: NativeSearchCall
433
+ ): NativeSearchResults | undefined {
434
+ if (bindsSearchTool(graph)) {
435
+ return undefined;
436
+ }
437
+ if (call.grounding != null) {
438
+ return coerceGoogleGroundingResults(call.grounding, call.text);
439
+ }
440
+ return call.citations.length > 0
441
+ ? coerceOpenAICitationResults(call.citations, call.text, call.blocks)
442
+ : undefined;
443
+ }
444
+
445
+ /**
446
+ * Settles the web search citations Gemini grounding and OpenAI `url_citation`
447
+ * attach to a finished model call. They arrive after the text they cite has
448
+ * streamed, so the sources reach TOOL_END handlers as one `web_search` turn
449
+ * (as Anthropic results do) and the cited spans are rewritten into
450
+ * `turnNsearchM` anchors through `edits` on the steps that hold the text.
451
+ */
452
+ export async function handleNativeSearchCitations({
453
+ graph,
454
+ call,
455
+ metadata,
456
+ }: {
457
+ graph: StandardGraph | MultiAgentGraph;
458
+ call: NativeSearchCall;
459
+ metadata?: Record<string, unknown>;
460
+ }): Promise<void> {
461
+ const results = getNativeSearchResults(graph, call);
462
+ const stepId = call.steps.at(0)?.id;
463
+ if (results == null || stepId == null) {
464
+ return;
465
+ }
466
+ const turn = graph.searchCitations.claimTurn(graph.invokedToolIds?.size ?? 0);
467
+ const data: SearchResultData = { turn, organic: results.organic };
468
+ const output = new ToolMessage({
469
+ name: Constants.WEB_SEARCH,
470
+ artifact: { [Constants.WEB_SEARCH]: data },
471
+ content: formatResultsForLLM(turn, data).output,
472
+ tool_call_id: `${Constants.WEB_SEARCH}_${stepId}`,
473
+ });
474
+ await graph.handlerRegistry
475
+ ?.getHandler(GraphEvents.TOOL_END)
476
+ ?.handle(
477
+ GraphEvents.TOOL_END,
478
+ { input: { queries: results.queries ?? [] }, output },
479
+ metadata,
480
+ graph
481
+ );
482
+
483
+ const edits = results.spans.map(({ start, end, sources }) => ({
484
+ start,
485
+ end,
486
+ text: formatSearchAnchors(sources.map((index) => ({ turn, index }))),
487
+ }));
488
+ for (const [id, stepEdits] of graph.searchCitations.locate(call, edits)) {
489
+ await graph.dispatchMessageDelta(
490
+ id,
491
+ { content: [{ type: ContentTypes.TEXT, edits: stepEdits }] },
492
+ metadata
493
+ );
494
+ }
495
+ }
@@ -0,0 +1,375 @@
1
+ import type {
2
+ GoogleGroundingMetadata,
3
+ SearchResultData,
4
+ ProcessedOrganic,
5
+ } from './types';
6
+ import type * as t from '@/types';
7
+ import { ContentTypes } from '@/common/enum';
8
+
9
+ /**
10
+ * LibreChat's citation markers. They are private-use code points, while a
11
+ * model following the web search prompt writes the escaped `\ue202` text, so
12
+ * markers in these forms were inserted here.
13
+ */
14
+ const ANCHOR = '\ue202';
15
+ const GROUP_START = '\ue200';
16
+ const GROUP_END = '\ue201';
17
+ const INSERTED_MARKERS = /\ue200|\ue201|\ue202turn\d+search\d+/g;
18
+
19
+ export type SearchRef = { turn: number; index: number };
20
+
21
+ /** A span of a model call's text that cites `sources` (organic indices). */
22
+ export type CitationSpan = { start: number; end: number; sources: number[] };
23
+
24
+ export type NativeSearchResults = {
25
+ organic: ProcessedOrganic[];
26
+ spans: CitationSpan[];
27
+ queries?: string[];
28
+ };
29
+
30
+ export type UrlCitation = {
31
+ block?: number;
32
+ url: string;
33
+ title?: string;
34
+ start?: number;
35
+ end?: number;
36
+ };
37
+
38
+ export type NativeSearchCall = {
39
+ text: string;
40
+ /** Where each step's text starts, in `text` and in the step's content part. */
41
+ steps: { id: string; start: number; base: number }[];
42
+ /** Offset in `text` where each provider text block starts. */
43
+ blocks: Map<number, number>;
44
+ citations: UrlCitation[];
45
+ grounding?: GoogleGroundingMetadata;
46
+ metadata?: Record<string, unknown>;
47
+ };
48
+
49
+ type PendingAnchors = {
50
+ block?: number;
51
+ refs: SearchRef[];
52
+ metadata?: Record<string, unknown>;
53
+ };
54
+
55
+ type CitedPart = {
56
+ type?: string;
57
+ text?: unknown;
58
+ index?: unknown;
59
+ citations?: unknown;
60
+ annotations?: unknown;
61
+ };
62
+
63
+ export function formatSearchAnchors(refs: readonly SearchRef[]): string {
64
+ const anchors = refs
65
+ .map(({ turn, index }) => `${ANCHOR}turn${turn}search${index}`)
66
+ .join('');
67
+ return refs.length > 1 ? `${GROUP_START}${anchors}${GROUP_END}` : anchors;
68
+ }
69
+
70
+ /** Removes the markers {@link formatSearchAnchors} writes, so replayed text matches what the provider sent. */
71
+ export function stripSearchAnchors(text: string): string {
72
+ return text.replace(INSERTED_MARKERS, '');
73
+ }
74
+
75
+ /** Applies non-overlapping edits by position; an edit outside the text or over an earlier one is skipped. */
76
+ export function applyTextEdits(
77
+ text: string,
78
+ edits: readonly t.TextEdit[]
79
+ ): string {
80
+ const valid = edits
81
+ .filter(
82
+ ({ start, end }) =>
83
+ Number.isSafeInteger(start) &&
84
+ Number.isSafeInteger(end) &&
85
+ start >= 0 &&
86
+ start <= end &&
87
+ end <= text.length
88
+ )
89
+ .sort((a, b) => a.start - b.start || a.end - b.end);
90
+ let result = '';
91
+ let cursor = 0;
92
+ for (const edit of valid) {
93
+ if (edit.start < cursor) {
94
+ continue;
95
+ }
96
+ result += text.slice(cursor, edit.start) + edit.text;
97
+ cursor = edit.end;
98
+ }
99
+ return result + text.slice(cursor);
100
+ }
101
+
102
+ function getUtf8Length(code: number): number {
103
+ if (code < 0x80) {
104
+ return 1;
105
+ }
106
+ if (code < 0x800) {
107
+ return 2;
108
+ }
109
+ return code < 0x10000 ? 3 : 4;
110
+ }
111
+
112
+ /** Converts a UTF-8 byte offset into a UTF-16 index of `text`; undefined when it falls inside a character. */
113
+ export function byteToCharOffset(
114
+ text: string,
115
+ bytes: number
116
+ ): number | undefined {
117
+ let consumed = 0;
118
+ let index = 0;
119
+ while (consumed < bytes && index < text.length) {
120
+ const code = text.codePointAt(index) ?? 0;
121
+ consumed += getUtf8Length(code);
122
+ index += code > 0xffff ? 2 : 1;
123
+ }
124
+ return consumed === bytes ? index : undefined;
125
+ }
126
+
127
+ function getUrlCitations(part: CitedPart): UrlCitation[] {
128
+ if (!Array.isArray(part.annotations)) {
129
+ return [];
130
+ }
131
+ const block = typeof part.index === 'number' ? part.index : undefined;
132
+ const citations: UrlCitation[] = [];
133
+ for (const annotation of part.annotations as Record<string, unknown>[]) {
134
+ const isUrlCitation =
135
+ annotation.source === 'url_citation' ||
136
+ annotation.type === 'url_citation';
137
+ if (!isUrlCitation || typeof annotation.url !== 'string') {
138
+ continue;
139
+ }
140
+ const start = annotation.startIndex ?? annotation.start_index;
141
+ const end = annotation.endIndex ?? annotation.end_index;
142
+ citations.push({
143
+ block,
144
+ url: annotation.url,
145
+ title:
146
+ typeof annotation.title === 'string' ? annotation.title : undefined,
147
+ start: typeof start === 'number' ? start : undefined,
148
+ end: typeof end === 'number' ? end : undefined,
149
+ });
150
+ }
151
+ return citations;
152
+ }
153
+
154
+ /**
155
+ * Run-scoped state that turns provider-native web search citations into the
156
+ * `turnNsearchM` anchors hosts already render for the SDK's own search tool.
157
+ */
158
+ export class SearchCitations {
159
+ /** Organic results by link, so a cited URL resolves to its turn and index. */
160
+ private sources = new Map<string, SearchRef>();
161
+ /** Anchors for a cited block, written once the block ends. */
162
+ private pending = new Map<string, PendingAnchors>();
163
+ /** Text and citation data of a model call still streaming, by agent lane. */
164
+ private calls = new Map<string, NativeSearchCall>();
165
+ /** Text length dispatched to each tracked step, to place late edits. */
166
+ private lengths = new Map<string, number>();
167
+ /** Turns claimed by searches that never produce a tool call id. */
168
+ private claimed = 0;
169
+
170
+ register(data: SearchResultData): void {
171
+ const turn = data.turn ?? 0;
172
+ data.organic?.forEach((result, index) => {
173
+ if (result.link) {
174
+ this.sources.set(result.link, { turn, index });
175
+ }
176
+ });
177
+ }
178
+
179
+ /** The turn for a search identified by a tool call id that joins `invokedToolIds`. */
180
+ turn(invoked: number): number {
181
+ return invoked + this.claimed;
182
+ }
183
+
184
+ /** Claims a turn for a search with no tool call id of its own. */
185
+ claimTurn(invoked: number): number {
186
+ const turn = this.turn(invoked);
187
+ this.claimed += 1;
188
+ return turn;
189
+ }
190
+
191
+ /**
192
+ * Adds the anchors of a cited block before the first delta of the next
193
+ * block. Anthropic sends a block's citations before or after its text, and
194
+ * the anchor belongs after the text, so it waits for the block to end.
195
+ * Returns undefined when the content needs no change.
196
+ */
197
+ anchor(
198
+ stepId: string,
199
+ content: t.MessageContentComplex[],
200
+ metadata?: Record<string, unknown>
201
+ ): t.MessageContentComplex[] | undefined {
202
+ let result: t.MessageContentComplex[] | undefined;
203
+ for (let i = 0; i < content.length; i++) {
204
+ const part = content[i] as CitedPart;
205
+ const pending = this.pending.get(stepId);
206
+ if (
207
+ pending != null &&
208
+ part.type === ContentTypes.TEXT &&
209
+ part.index !== pending.block
210
+ ) {
211
+ result ??= content.slice(0, i);
212
+ result.push({
213
+ type: ContentTypes.TEXT,
214
+ text: formatSearchAnchors(pending.refs),
215
+ });
216
+ this.pending.delete(stepId);
217
+ }
218
+ result?.push(content[i]);
219
+ const refs = this.resolve(part);
220
+ if (refs.length === 0) {
221
+ continue;
222
+ }
223
+ const current = this.pending.get(stepId) ?? {
224
+ block: typeof part.index === 'number' ? part.index : undefined,
225
+ refs: [],
226
+ metadata,
227
+ };
228
+ for (const ref of refs) {
229
+ if (
230
+ !current.refs.some(
231
+ ({ turn, index }) => turn === ref.turn && index === ref.index
232
+ )
233
+ ) {
234
+ current.refs.push(ref);
235
+ }
236
+ }
237
+ this.pending.set(stepId, current);
238
+ }
239
+ return result;
240
+ }
241
+
242
+ /** Anchors still waiting on a step that is closing. */
243
+ release(
244
+ stepId: string
245
+ ): { text: string; metadata?: Record<string, unknown> } | undefined {
246
+ const pending = this.pending.get(stepId);
247
+ if (pending == null) {
248
+ return undefined;
249
+ }
250
+ this.pending.delete(stepId);
251
+ return {
252
+ text: formatSearchAnchors(pending.refs),
253
+ metadata: pending.metadata,
254
+ };
255
+ }
256
+
257
+ /** Records a step's streamed text and url citations for edits made when the model call ends. */
258
+ track(
259
+ lane: string,
260
+ stepId: string,
261
+ content: t.MessageContentComplex[],
262
+ metadata?: Record<string, unknown>
263
+ ): void {
264
+ for (const item of content) {
265
+ const part = item as CitedPart;
266
+ if (part.type !== ContentTypes.TEXT) {
267
+ continue;
268
+ }
269
+ const text = typeof part.text === 'string' ? part.text : '';
270
+ const citations = getUrlCitations(part);
271
+ if (text === '' && citations.length === 0) {
272
+ continue;
273
+ }
274
+ const call = this.open(lane, metadata);
275
+ call.citations.push(...citations);
276
+ if (text === '') {
277
+ continue;
278
+ }
279
+ const base = this.lengths.get(stepId) ?? 0;
280
+ if (call.steps.at(-1)?.id !== stepId) {
281
+ call.steps.push({ id: stepId, start: call.text.length, base });
282
+ }
283
+ if (typeof part.index === 'number' && !call.blocks.has(part.index)) {
284
+ call.blocks.set(part.index, call.text.length);
285
+ }
286
+ call.text += text;
287
+ this.lengths.set(stepId, base + text.length);
288
+ }
289
+ }
290
+
291
+ /** Keeps the latest grounding payload of a model call. */
292
+ ground(
293
+ lane: string,
294
+ grounding: GoogleGroundingMetadata,
295
+ metadata?: Record<string, unknown>
296
+ ): void {
297
+ this.open(lane, metadata).grounding = grounding;
298
+ }
299
+
300
+ /** Hands over the finished model call of a lane. */
301
+ take(lane: string): NativeSearchCall | undefined {
302
+ const call = this.calls.get(lane);
303
+ this.calls.delete(lane);
304
+ return call;
305
+ }
306
+
307
+ /** Splits call-relative edits by the step that holds their text, in that step's offsets. */
308
+ locate(
309
+ call: NativeSearchCall,
310
+ edits: readonly t.TextEdit[]
311
+ ): Map<string, t.TextEdit[]> {
312
+ const byStep = new Map<string, t.TextEdit[]>();
313
+ for (const edit of edits) {
314
+ const step = call.steps.findLast(
315
+ ({ start }) => start < edit.end || (start === 0 && edit.end === 0)
316
+ );
317
+ if (step == null || edit.start < step.start) {
318
+ continue;
319
+ }
320
+ const offset = step.base - step.start;
321
+ const stepEdits = byStep.get(step.id) ?? [];
322
+ stepEdits.push({
323
+ start: edit.start + offset,
324
+ end: edit.end + offset,
325
+ text: edit.text,
326
+ });
327
+ byStep.set(step.id, stepEdits);
328
+ this.lengths.set(
329
+ step.id,
330
+ (this.lengths.get(step.id) ?? 0) +
331
+ edit.text.length -
332
+ (edit.end - edit.start)
333
+ );
334
+ }
335
+ return byStep;
336
+ }
337
+
338
+ private open(
339
+ lane: string,
340
+ metadata?: Record<string, unknown>
341
+ ): NativeSearchCall {
342
+ let call = this.calls.get(lane);
343
+ if (call == null) {
344
+ call = {
345
+ text: '',
346
+ steps: [],
347
+ blocks: new Map(),
348
+ citations: [],
349
+ metadata,
350
+ };
351
+ this.calls.set(lane, call);
352
+ }
353
+ return call;
354
+ }
355
+
356
+ private resolve(part: CitedPart): SearchRef[] {
357
+ if (part.type !== ContentTypes.TEXT || !Array.isArray(part.citations)) {
358
+ return [];
359
+ }
360
+ const refs: SearchRef[] = [];
361
+ for (const citation of part.citations as Record<string, unknown>[]) {
362
+ if (
363
+ citation.type !== 'web_search_result_location' ||
364
+ typeof citation.url !== 'string'
365
+ ) {
366
+ continue;
367
+ }
368
+ const ref = this.sources.get(citation.url);
369
+ if (ref != null) {
370
+ refs.push(ref);
371
+ }
372
+ }
373
+ return refs;
374
+ }
375
+ }
@@ -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,