@librechat/agents 4.2.13 → 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 (121) hide show
  1. package/dist/cjs/graphs/Graph.cjs +45 -3
  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/google/utils/signatures.cjs +22 -14
  6. package/dist/cjs/llm/google/utils/signatures.cjs.map +1 -1
  7. package/dist/cjs/llm/invoke.cjs +122 -13
  8. package/dist/cjs/llm/invoke.cjs.map +1 -1
  9. package/dist/cjs/llm/openai/index.cjs +8 -2
  10. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  11. package/dist/cjs/llm/openai/typedContent.cjs +94 -0
  12. package/dist/cjs/llm/openai/typedContent.cjs.map +1 -0
  13. package/dist/cjs/llm/prepareProviderRequest.cjs +80 -3
  14. package/dist/cjs/llm/prepareProviderRequest.cjs.map +1 -1
  15. package/dist/cjs/llm/providerTextBatch.cjs +128 -0
  16. package/dist/cjs/llm/providerTextBatch.cjs.map +1 -0
  17. package/dist/cjs/llm/providerTextBoundary.cjs +81 -12
  18. package/dist/cjs/llm/providerTextBoundary.cjs.map +1 -1
  19. package/dist/cjs/main.cjs +2 -0
  20. package/dist/cjs/protection/providerText.cjs +56 -6
  21. package/dist/cjs/protection/providerText.cjs.map +1 -1
  22. package/dist/cjs/protection/providerTextAdmission.cjs +5 -0
  23. package/dist/cjs/protection/providerTextAdmission.cjs.map +1 -1
  24. package/dist/cjs/run.cjs +7 -2
  25. package/dist/cjs/run.cjs.map +1 -1
  26. package/dist/cjs/runtime/client.cjs +2 -0
  27. package/dist/cjs/runtime/client.cjs.map +1 -1
  28. package/dist/cjs/stream.cjs +9 -2
  29. package/dist/cjs/stream.cjs.map +1 -1
  30. package/dist/cjs/tools/handlers.cjs +47 -1
  31. package/dist/cjs/tools/handlers.cjs.map +1 -1
  32. package/dist/cjs/tools/search/citations.cjs +194 -0
  33. package/dist/cjs/tools/search/citations.cjs.map +1 -0
  34. package/dist/cjs/tools/search/firecrawl.cjs +4 -9
  35. package/dist/cjs/tools/search/firecrawl.cjs.map +1 -1
  36. package/dist/cjs/tools/search/google.cjs +68 -0
  37. package/dist/cjs/tools/search/google.cjs.map +1 -0
  38. package/dist/cjs/tools/search/openai.cjs +80 -0
  39. package/dist/cjs/tools/search/openai.cjs.map +1 -0
  40. package/dist/cjs/utils/tokens.cjs +5 -0
  41. package/dist/cjs/utils/tokens.cjs.map +1 -1
  42. package/dist/esm/graphs/Graph.mjs +46 -4
  43. package/dist/esm/graphs/Graph.mjs.map +1 -1
  44. package/dist/esm/harness/providerText.mjs +1 -0
  45. package/dist/esm/harness/providerText.mjs.map +1 -1
  46. package/dist/esm/llm/google/utils/signatures.mjs +22 -14
  47. package/dist/esm/llm/google/utils/signatures.mjs.map +1 -1
  48. package/dist/esm/llm/invoke.mjs +124 -15
  49. package/dist/esm/llm/invoke.mjs.map +1 -1
  50. package/dist/esm/llm/openai/index.mjs +8 -2
  51. package/dist/esm/llm/openai/index.mjs.map +1 -1
  52. package/dist/esm/llm/openai/typedContent.mjs +93 -0
  53. package/dist/esm/llm/openai/typedContent.mjs.map +1 -0
  54. package/dist/esm/llm/prepareProviderRequest.mjs +80 -3
  55. package/dist/esm/llm/prepareProviderRequest.mjs.map +1 -1
  56. package/dist/esm/llm/providerTextBatch.mjs +128 -0
  57. package/dist/esm/llm/providerTextBatch.mjs.map +1 -0
  58. package/dist/esm/llm/providerTextBoundary.mjs +81 -12
  59. package/dist/esm/llm/providerTextBoundary.mjs.map +1 -1
  60. package/dist/esm/main.mjs +3 -3
  61. package/dist/esm/protection/providerText.mjs +55 -7
  62. package/dist/esm/protection/providerText.mjs.map +1 -1
  63. package/dist/esm/protection/providerTextAdmission.mjs +5 -0
  64. package/dist/esm/protection/providerTextAdmission.mjs.map +1 -1
  65. package/dist/esm/run.mjs +7 -2
  66. package/dist/esm/run.mjs.map +1 -1
  67. package/dist/esm/runtime/client.mjs +2 -0
  68. package/dist/esm/runtime/client.mjs.map +1 -1
  69. package/dist/esm/stream.mjs +9 -2
  70. package/dist/esm/stream.mjs.map +1 -1
  71. package/dist/esm/tools/handlers.mjs +47 -2
  72. package/dist/esm/tools/handlers.mjs.map +1 -1
  73. package/dist/esm/tools/search/citations.mjs +190 -0
  74. package/dist/esm/tools/search/citations.mjs.map +1 -0
  75. package/dist/esm/tools/search/firecrawl.mjs +4 -9
  76. package/dist/esm/tools/search/firecrawl.mjs.map +1 -1
  77. package/dist/esm/tools/search/google.mjs +67 -0
  78. package/dist/esm/tools/search/google.mjs.map +1 -0
  79. package/dist/esm/tools/search/openai.mjs +80 -0
  80. package/dist/esm/tools/search/openai.mjs.map +1 -0
  81. package/dist/esm/utils/tokens.mjs +5 -0
  82. package/dist/esm/utils/tokens.mjs.map +1 -1
  83. package/dist/types/graphs/Graph.d.ts +14 -0
  84. package/dist/types/index.d.ts +2 -2
  85. package/dist/types/llm/openai/typedContent.d.ts +14 -0
  86. package/dist/types/llm/providerTextBatch.d.ts +26 -0
  87. package/dist/types/llm/providerTextBoundary.d.ts +7 -1
  88. package/dist/types/protection/providerText.d.ts +29 -1
  89. package/dist/types/protection/providerTextAdmission.d.ts +1 -0
  90. package/dist/types/tools/handlers.d.ts +13 -0
  91. package/dist/types/tools/search/citations.d.ts +88 -0
  92. package/dist/types/tools/search/firecrawl.d.ts +3 -1
  93. package/dist/types/tools/search/google.d.ts +11 -0
  94. package/dist/types/tools/search/openai.d.ts +3 -0
  95. package/dist/types/tools/search/types.d.ts +24 -0
  96. package/dist/types/types/stream.d.ts +12 -0
  97. package/dist/types/utils/tokens.d.ts +1 -0
  98. package/package.json +1 -1
  99. package/src/graphs/Graph.ts +103 -3
  100. package/src/harness/providerText.ts +1 -0
  101. package/src/index.ts +2 -0
  102. package/src/llm/google/utils/signatures.ts +52 -36
  103. package/src/llm/invoke.ts +160 -16
  104. package/src/llm/openai/index.ts +18 -5
  105. package/src/llm/openai/typedContent.ts +110 -0
  106. package/src/llm/prepareProviderRequest.ts +154 -4
  107. package/src/llm/providerTextBatch.ts +158 -0
  108. package/src/llm/providerTextBoundary.ts +119 -13
  109. package/src/protection/providerText.ts +95 -6
  110. package/src/protection/providerTextAdmission.ts +6 -0
  111. package/src/run.ts +22 -1
  112. package/src/runtime/client.ts +3 -0
  113. package/src/stream.ts +18 -2
  114. package/src/tools/handlers.ts +110 -5
  115. package/src/tools/search/citations.ts +375 -0
  116. package/src/tools/search/firecrawl.ts +13 -16
  117. package/src/tools/search/google.ts +122 -0
  118. package/src/tools/search/openai.ts +118 -0
  119. package/src/tools/search/types.ts +21 -0
  120. package/src/types/stream.ts +9 -0
  121. package/src/utils/tokens.ts +9 -0
@@ -7,6 +7,21 @@ import { PreparedSubagentError } from '@/tools/preparedSubagents';
7
7
  import { StreamLimitExceededError } from '@/llm/streamLimits';
8
8
 
9
9
  export const PROVIDER_TEXT_PROTECTION_VERSION = 1;
10
+ export const PROVIDER_TEXT_BATCHING_VERSION = 1;
11
+ export const BATCHED_PROVIDER_EVENT_OWNER = 'librechat:batched-provider-event-owner';
12
+
13
+ /**
14
+ * Opt in only when every rule is substring-local with a certified maximum match width.
15
+ * No anchors, surrounding-context assertions, or partial rewrites. Classification and
16
+ * inspection must be valid over overlapping UTF-16 windows. Omit this option to inspect
17
+ * the whole reply without releasing any prose early.
18
+ */
19
+ export interface ProviderTextBatching {
20
+ readonly version: 1;
21
+ readonly batchBytes: number;
22
+ readonly flushMs: number;
23
+ readonly maxMatchChars: number;
24
+ }
10
25
 
11
26
  export type ProviderTextProtectionErrorCode =
12
27
  | 'blocked'
@@ -43,6 +58,7 @@ export interface ProviderTextProtection {
43
58
  readonly maxAttemptBytes: number;
44
59
  /** Shared across all attempts using this policy, including child graphs. */
45
60
  readonly maxBufferedBytes: number;
61
+ readonly batching?: ProviderTextBatching;
46
62
  readonly classify: (content: string) => 'prose' | 'unsupported';
47
63
  readonly inspect: (input: {
48
64
  readonly version: 1;
@@ -214,6 +230,25 @@ export function validateProviderTextProtection(
214
230
  ) {
215
231
  throw new ProviderTextProtectionError('incompatible');
216
232
  }
233
+ const batch = policy.batching as
234
+ | (Omit<ProviderTextBatching, 'version'> & { version: number })
235
+ | null
236
+ | undefined;
237
+ if (
238
+ batch !== undefined &&
239
+ (batch == null ||
240
+ batch.version !== 1 ||
241
+ !Number.isSafeInteger(batch.batchBytes) ||
242
+ batch.batchBytes < 2 ||
243
+ !Number.isSafeInteger(batch.maxMatchChars) ||
244
+ batch.maxMatchChars < 1 ||
245
+ (batch.maxMatchChars - 1) * 2 > batch.batchBytes ||
246
+ batch.batchBytes > policy.maxAttemptBytes ||
247
+ !Number.isSafeInteger(batch.flushMs) ||
248
+ batch.flushMs < 1 ||
249
+ batch.flushMs > policy.timeoutMs)
250
+ )
251
+ throw new ProviderTextProtectionError('incompatible');
217
252
  }
218
253
 
219
254
  export interface ProviderTextAttemptOptions {
@@ -233,6 +268,9 @@ export class ProviderTextAttempt {
233
268
  private readonly timer: ReturnType<typeof setTimeout>;
234
269
  private readonly abort: () => void;
235
270
  private finished = false;
271
+ private publishedText = false;
272
+ private finishHeld = false;
273
+ private finishPending = false;
236
274
  private readonly admission?: ProviderTextAdmissionLease;
237
275
 
238
276
  constructor(
@@ -285,6 +323,25 @@ export class ProviderTextAttempt {
285
323
  return this.controller.signal;
286
324
  }
287
325
 
326
+ followSignal(signal?: AbortSignal): (() => void) | undefined {
327
+ if (signal == null || signal === this.signal || signal === this.parent) return;
328
+ const abort = (): void => this.controller.abort(protectionAbortError(signal));
329
+ if (signal.aborted) {
330
+ abort();
331
+ this.check();
332
+ }
333
+ signal.addEventListener('abort', abort, { once: true });
334
+ return (): void => signal.removeEventListener('abort', abort);
335
+ }
336
+
337
+ get hasPublishedText(): boolean {
338
+ return this.publishedText;
339
+ }
340
+
341
+ markTextPublished(): void {
342
+ this.publishedText = true;
343
+ }
344
+
288
345
  check(): void {
289
346
  if (this.finished) throw new ProviderTextProtectionError('incompatible');
290
347
  if (this.signal.aborted) throw this.signal.reason;
@@ -347,13 +404,25 @@ export class ProviderTextAttempt {
347
404
  this.charge(bytes);
348
405
  }
349
406
 
407
+ /** Release staged window charges after its raw references and inspector have settled. */
408
+ releaseWindow(bytes: number): void {
409
+ this.admission?.uncharge(bytes);
410
+ this.bytes -= bytes;
411
+ this.budget.bytes -= bytes;
412
+ }
413
+
414
+ stop(error: ProviderTextProtectionError): void {
415
+ this.controller.abort(error);
416
+ }
417
+
350
418
  observeChunk(): void {
351
419
  this.check();
352
420
  this.charge(128);
353
421
  }
354
422
 
355
- async wait<T>(work: Promise<T>): Promise<T> {
356
- this.pending.add(work);
423
+ /** Approved-text callbacks can stop blocking cleanup without retaining raw capacity. */
424
+ async wait<T>(work: Promise<T>, retain = true): Promise<T> {
425
+ if (retain) this.pending.add(work);
357
426
  return new Promise<T>((resolve, reject) => {
358
427
  const abort = (): void => {
359
428
  this.signal.removeEventListener('abort', abort);
@@ -363,7 +432,7 @@ export class ProviderTextAttempt {
363
432
  if (this.signal.aborted) abort();
364
433
  const settle = (): void => {
365
434
  this.signal.removeEventListener('abort', abort);
366
- this.pending.delete(work);
435
+ if (retain) this.pending.delete(work);
367
436
  };
368
437
  void work.then(
369
438
  (value) => {
@@ -378,9 +447,8 @@ export class ProviderTextAttempt {
378
447
  });
379
448
  }
380
449
 
381
- async release(): Promise<string> {
450
+ async inspect(content: string): Promise<string> {
382
451
  this.check();
383
- const content = this.fragments.join('');
384
452
  if (!content) return '';
385
453
  let result: ProviderTextProtectionResult;
386
454
  try {
@@ -409,12 +477,33 @@ export class ProviderTextAttempt {
409
477
  this.check();
410
478
  const canonical = validateResult(result);
411
479
  this.check();
412
- this.charge(canonical.length * 2);
413
480
  return canonical;
414
481
  }
415
482
 
483
+ async release(): Promise<string> {
484
+ this.check();
485
+ const content = this.fragments.join('');
486
+ if (!content) return '';
487
+ const canonical = await this.inspect(content);
488
+ this.retain(canonical.length * 2);
489
+ return canonical;
490
+ }
491
+
492
+ /** Native prefetch can end the iterator while the invocation still dispatches its final chunk. */
493
+ holdFinish(): () => void {
494
+ this.finishHeld = true;
495
+ return (): void => {
496
+ this.finishHeld = false;
497
+ if (this.finishPending) this.finish();
498
+ };
499
+ }
500
+
416
501
  finish(): void {
417
502
  if (this.finished) return;
503
+ if (this.finishHeld) {
504
+ this.finishPending = true;
505
+ return;
506
+ }
418
507
  this.finished = true;
419
508
  clearTimeout(this.timer);
420
509
  try {
@@ -16,6 +16,7 @@ export interface ProviderTextAdmissionSnapshot {
16
16
  /** Internal ownership lease; only the attempt that acquires it may release it. */
17
17
  export interface ProviderTextAdmissionLease {
18
18
  charge(bytes: number): void;
19
+ uncharge(bytes: number): void;
19
20
  retain(): void;
20
21
  release(): void;
21
22
  }
@@ -66,6 +67,11 @@ export class ProviderTextAdmission {
66
67
  bytes += amount;
67
68
  if (retained) this.retainedBytes += amount;
68
69
  },
70
+ uncharge: (amount): void => {
71
+ this.bufferedBytes -= amount;
72
+ bytes -= amount;
73
+ if (retained) this.retainedBytes -= amount;
74
+ },
69
75
  retain: (): void => {
70
76
  if (retained || released) return;
71
77
  retained = true;
package/src/run.ts CHANGED
@@ -95,6 +95,10 @@ import {
95
95
  findCallback,
96
96
  type CallbackEntry,
97
97
  } from '@/utils/callbacks';
98
+ import {
99
+ BATCHED_PROVIDER_EVENT_OWNER,
100
+ ProviderTextProtectionError,
101
+ } from '@/protection/providerText';
98
102
  import {
99
103
  resolveLangfuseRuntimeScope,
100
104
  withLangfuseRuntimeScope,
@@ -108,7 +112,6 @@ import {
108
112
  createTitleRunnable,
109
113
  } from '@/utils/title';
110
114
  import { applyGraphRuntimeConfig } from '@/graphs/applyGraphRuntimeConfig';
111
- import { ProviderTextProtectionError } from '@/protection/providerText';
112
115
  import { LANGFUSE_OPERATION_METADATA_KEY } from '@/langfuseOperation';
113
116
  import { createTokenCounter, encodingForModel } from '@/utils/tokens';
114
117
  import { stampSyntheticProviderMessage } from '@/messages/provenance';
@@ -635,6 +638,15 @@ export class Run<_T extends t.BaseGraphState> {
635
638
  throw new ToolResultProtectionError('incompatible');
636
639
  }
637
640
 
641
+ if (
642
+ this.providerTextProtection?.batching != null &&
643
+ (config.humanInTheLoop?.enabled === true ||
644
+ ('agents' in config.graphConfig &&
645
+ config.graphConfig.agents.length !== 1))
646
+ ) {
647
+ throw new ProviderTextProtectionError('unsupported');
648
+ }
649
+
638
650
  /** Handle different graph types */
639
651
  if (config.graphConfig.type === 'multi-agent') {
640
652
  if (
@@ -1628,6 +1640,14 @@ export class Run<_T extends t.BaseGraphState> {
1628
1640
  for await (const event of stream) {
1629
1641
  const { data, metadata, ...info } = event;
1630
1642
  const eventName: t.EventName = info.event;
1643
+ // The batched attempt owns start and delta delivery and their deadline.
1644
+ if (
1645
+ this.providerTextProtection?.batching != null &&
1646
+ (eventName === GraphEvents.CHAT_MODEL_START ||
1647
+ eventName === GraphEvents.CHAT_MODEL_STREAM) &&
1648
+ metadata[BATCHED_PROVIDER_EVENT_OWNER] === true
1649
+ )
1650
+ continue;
1631
1651
 
1632
1652
  if (CUSTOM_GRAPH_EVENTS.has(eventName)) {
1633
1653
  continue;
@@ -1672,6 +1692,7 @@ export class Run<_T extends t.BaseGraphState> {
1672
1692
  }
1673
1693
 
1674
1694
  if (eventName === GraphEvents.CHAT_MODEL_END && this.Graph != null) {
1695
+ await this.Graph.settleSearchCitations(metadata);
1675
1696
  await this.Graph.closeOpenMessageStep(metadata, modelEndAt);
1676
1697
  }
1677
1698
 
@@ -28,6 +28,7 @@ import type { SdkAgentIdentity } from './identity';
28
28
  import {
29
29
  Run,
30
30
  ToolResultProtectionError,
31
+ ProviderTextProtectionError,
31
32
  executeHooks,
32
33
  GraphEvents,
33
34
  HOOK_EVENTS,
@@ -67,6 +68,8 @@ export async function createRemoteSdkRun({
67
68
  );
68
69
  if (config.toolResultProtection != null)
69
70
  throw new ToolResultProtectionError('unsupported');
71
+ if (config.providerTextProtection?.batching != null)
72
+ throw new ProviderTextProtectionError('unsupported');
70
73
  if (config.providerTextProtection && !hostServices?.providerText)
71
74
  throw new Error(
72
75
  'Remote SDK provider protection requires a supported policy adapter'
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) {
@@ -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
+ }