@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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@librechat/agents",
3
- "version": "4.2.13",
3
+ "version": "4.2.15",
4
4
  "reova": {
5
5
  "enabled": true,
6
6
  "endpoint": "https://telemetry.reo.dev/data"
@@ -1,6 +1,7 @@
1
1
  /* eslint-disable no-console */
2
2
  import { RunnableLambda } from '@langchain/core/runnables';
3
3
  import {
4
+ ToolMessage,
4
5
  HumanMessage,
5
6
  SystemMessage,
6
7
  coerceMessageLikeToMessage,
@@ -10,6 +11,7 @@ import type {
10
11
  BaseMessage,
11
12
  BaseMessageFields,
12
13
  BaseMessageLike,
14
+ MessageContentComplex,
13
15
  } from '@langchain/core/messages';
14
16
  import type { RunnableConfig, Runnable } from '@langchain/core/runnables';
15
17
  import type { ExactTokenCountCache } from '@/llm/contextPressureMeter';
@@ -56,11 +58,17 @@ import {
56
58
  Constants,
57
59
  Providers,
58
60
  } from '@/common';
61
+ import {
62
+ hasComputerCallOutputMarker,
63
+ cloneToolMessageWithContent,
64
+ } from '@/utils/toolContent';
59
65
  import { isTokenCounterCacheCompatible } from '@/llm/tokenCounterCacheCompatibility';
60
66
  import { normalizeToBashIdentifier } from '@/tools/BashProgrammaticToolCalling';
61
67
  import { snapshotCompactionSemanticIndex } from '@/summarization/semanticIndex';
68
+ import { flattenLegacyContent, isLegacyConvertible } from '@/messages/content';
62
69
  import { normalizeToPythonIdentifier } from '@/tools/ProgrammaticToolCalling';
63
70
  import { createExactTokenCountCache } from '@/llm/contextPressureMeter';
71
+ import { omitImageBlocks, omitArtifactImages } from '@/messages/vision';
64
72
  import { markProviderTextInput } from '@/protection/providerTextInput';
65
73
  import { buildSummaryCarrierText } from '@/summarization/shared';
66
74
  import { createSchemaOnlyTools } from '@/tools/schema';
@@ -127,6 +135,7 @@ export class AgentContext {
127
135
  maxContextTokens,
128
136
  reasoningKey,
129
137
  useLegacyContent,
138
+ vision,
130
139
  discoveredTools,
131
140
  summarizationEnabled,
132
141
  summarizeOnly,
@@ -163,6 +172,7 @@ export class AgentContext {
163
172
  instructionTokens: 0,
164
173
  tokenCounter,
165
174
  useLegacyContent,
175
+ vision,
166
176
  discoveredTools,
167
177
  summarizationEnabled,
168
178
  summarizeOnly,
@@ -323,6 +333,8 @@ export class AgentContext {
323
333
  private providerProjectedMessages?: BaseMessage[];
324
334
  /** Canonical object identities corresponding to the projected slots. */
325
335
  private providerProjectionSources?: BaseMessage[];
336
+ /** Without image input, the image-free history the pruner rewrites the projection from. */
337
+ private providerProjectionCanonical?: BaseMessage[];
326
338
  /** Canonical messages by ID, used to distinguish identity replay from replacement. */
327
339
  private providerProjectionSourcesById?: Map<string, BaseMessage>;
328
340
  /** Conservative counts retained by canonical identity across a rebuild. */
@@ -414,6 +426,8 @@ export class AgentContext {
414
426
  tokenCalculationPromise?: Promise<void>;
415
427
  /** Format content blocks as strings (for legacy compatibility) */
416
428
  useLegacyContent: boolean = false;
429
+ /** `false` when this agent's model cannot read images (see `AgentInputs.vision`) */
430
+ vision?: boolean;
417
431
  /** Enables graph-level summarization for this agent */
418
432
  summarizationEnabled?: boolean;
419
433
  /** Summarize-only run: request a summary on the first model step and end after it */
@@ -478,7 +492,11 @@ export class AgentContext {
478
492
  private correctedContextBudgetMode?: t.ContextBudgetMode;
479
493
 
480
494
  get summarizationBudgetMode(): t.ContextBudgetMode {
481
- return this.correctedContextBudgetMode ?? this.summarizationConfig?.contextBudgetMode ?? 'input';
495
+ return (
496
+ this.correctedContextBudgetMode ??
497
+ this.summarizationConfig?.contextBudgetMode ??
498
+ 'input'
499
+ );
482
500
  }
483
501
  /**
484
502
  * Prompt size, normalized into the local counter's uncalibrated units, at
@@ -520,6 +538,7 @@ export class AgentContext {
520
538
  toolEnd,
521
539
  instructionTokens,
522
540
  useLegacyContent,
541
+ vision,
523
542
  discoveredTools,
524
543
  summarizationEnabled,
525
544
  summarizeOnly,
@@ -549,6 +568,7 @@ export class AgentContext {
549
568
  toolEnd?: boolean;
550
569
  instructionTokens?: number;
551
570
  useLegacyContent?: boolean;
571
+ vision?: boolean;
552
572
  discoveredTools?: string[];
553
573
  summarizationEnabled?: boolean;
554
574
  summarizeOnly?: boolean;
@@ -595,6 +615,7 @@ export class AgentContext {
595
615
  }
596
616
 
597
617
  this.useLegacyContent = useLegacyContent ?? false;
618
+ this.vision = vision;
598
619
  this.summarizationEnabled = summarizationEnabled;
599
620
  this.summarizeOnly = summarizeOnly;
600
621
  this.summarizationConfig = summarizationConfig;
@@ -1061,45 +1082,47 @@ export class AgentContext {
1061
1082
  : 0;
1062
1083
  }
1063
1084
 
1064
- return markProviderTextInput(RunnableLambda.from((messages: BaseMessage[]) => {
1065
- const prefix: BaseMessage[] = systemMessage ? [systemMessage] : [];
1066
-
1067
- // Build the non-system portion (summary + conversation), then apply
1068
- // cache markers separately so addCacheControl doesn't strip the
1069
- // SystemMessage's own cache_control breakpoint set above.
1070
- const hasSummaryBody =
1071
- this._summaryLocation === 'user_message' &&
1072
- this.summaryText != null &&
1073
- this.summaryText !== '';
1074
-
1075
- const bodyWithSummary =
1076
- hasSummaryBody && promptCacheProvider == null
1077
- ? [this.buildSummaryHumanMessage(promptCacheProvider), ...messages]
1078
- : messages;
1079
- const dynamicTail = this.buildPromptCacheDynamicTail({
1080
- dynamicInstructions,
1081
- hasSummaryBody,
1082
- promptCacheProvider,
1083
- shouldMoveDynamicInstructions,
1084
- });
1085
- let body = this.buildBodyWithPromptCacheDynamicTail(
1086
- bodyWithSummary,
1087
- dynamicTail,
1088
- promptCacheProvider
1089
- );
1090
-
1091
- if (
1092
- promptCacheProvider != null &&
1093
- dynamicTail.length === 0 &&
1094
- body.length >= 2
1095
- ) {
1096
- body = addTailCacheControl(
1097
- body,
1098
- this.getPromptCacheTtl(promptCacheProvider)
1085
+ return markProviderTextInput(
1086
+ RunnableLambda.from((messages: BaseMessage[]) => {
1087
+ const prefix: BaseMessage[] = systemMessage ? [systemMessage] : [];
1088
+
1089
+ // Build the non-system portion (summary + conversation), then apply
1090
+ // cache markers separately so addCacheControl doesn't strip the
1091
+ // SystemMessage's own cache_control breakpoint set above.
1092
+ const hasSummaryBody =
1093
+ this._summaryLocation === 'user_message' &&
1094
+ this.summaryText != null &&
1095
+ this.summaryText !== '';
1096
+
1097
+ const bodyWithSummary =
1098
+ hasSummaryBody && promptCacheProvider == null
1099
+ ? [this.buildSummaryHumanMessage(promptCacheProvider), ...messages]
1100
+ : messages;
1101
+ const dynamicTail = this.buildPromptCacheDynamicTail({
1102
+ dynamicInstructions,
1103
+ hasSummaryBody,
1104
+ promptCacheProvider,
1105
+ shouldMoveDynamicInstructions,
1106
+ });
1107
+ let body = this.buildBodyWithPromptCacheDynamicTail(
1108
+ bodyWithSummary,
1109
+ dynamicTail,
1110
+ promptCacheProvider
1099
1111
  );
1100
- }
1101
- return [...prefix, ...body];
1102
- })).withConfig({ runName: 'prompt' });
1112
+
1113
+ if (
1114
+ promptCacheProvider != null &&
1115
+ dynamicTail.length === 0 &&
1116
+ body.length >= 2
1117
+ ) {
1118
+ body = addTailCacheControl(
1119
+ body,
1120
+ this.getPromptCacheTtl(promptCacheProvider)
1121
+ );
1122
+ }
1123
+ return [...prefix, ...body];
1124
+ })
1125
+ ).withConfig({ runName: 'prompt' });
1103
1126
  }
1104
1127
 
1105
1128
  private buildSummaryHumanMessage(
@@ -1881,31 +1904,50 @@ export class AgentContext {
1881
1904
  this.pendingOriginalToolContent = undefined;
1882
1905
  this.prepareProviderProjectionRecount(sources);
1883
1906
  }
1884
- projection = messages.map((message) =>
1885
- Array.isArray(message.content)
1886
- ? cloneMessage(message, [...message.content])
1887
- : message
1888
- );
1889
- this.providerProjectedMessages = projection;
1890
- this.providerProjectionSources = [...messages];
1891
- this.providerProjectionSourcesById = new Map(
1892
- messages.flatMap((message) =>
1893
- message.id == null ? [] : [[message.id, message] as const]
1894
- )
1895
- );
1896
- if (this.providerProjectionRequiresRecount && this.tokenCounter != null) {
1897
- const recounted: Record<string, number> = {};
1898
- for (let i = 0; i < messages.length; i++) {
1899
- const localCount = this.tokenCounter(messages[i]);
1900
- const conservativeFloor = this.providerProjectionRecountFloors?.get(
1901
- messages[i]
1902
- );
1903
- recounted[i] =
1907
+ const counter = this.tokenCounter;
1908
+ const recount = this.providerProjectionRequiresRecount && counter != null;
1909
+ const floors = this.providerProjectionRecountFloors;
1910
+ const hostCounts = this.indexTokenCountMap;
1911
+ /** A rewrite recounts every message; otherwise host counts stand, and the first replaced image copies them so other agents' maps stay intact. */
1912
+ let counts: Record<string, number | undefined> = recount
1913
+ ? {}
1914
+ : hostCounts;
1915
+ const canonical: BaseMessage[] | undefined =
1916
+ this.vision === false ? [] : undefined;
1917
+ const nextSources: BaseMessage[] = [];
1918
+ const sourcesById = new Map<string, BaseMessage>();
1919
+ projection = messages.map((message, index) => {
1920
+ nextSources.push(message);
1921
+ if (message.id != null) {
1922
+ sourcesById.set(message.id, message);
1923
+ }
1924
+ const projected = this.projectMessage(message);
1925
+ canonical?.push(projected.canonical);
1926
+ if (counter == null) {
1927
+ return projected.message;
1928
+ }
1929
+ if (projected.omittedImages) {
1930
+ if (counts === hostCounts) {
1931
+ counts = { ...hostCounts };
1932
+ }
1933
+ /** Priced as the marker its request sends, never as the image a host count or floor remembers. */
1934
+ counts[index] = counter(projected.message);
1935
+ } else if (recount) {
1936
+ const localCount = counter(message);
1937
+ const conservativeFloor = floors?.get(message);
1938
+ counts[index] =
1904
1939
  conservativeFloor == null
1905
1940
  ? localCount
1906
1941
  : Math.max(localCount, conservativeFloor);
1907
1942
  }
1908
- this.indexTokenCountMap = recounted;
1943
+ return projected.message;
1944
+ });
1945
+ this.providerProjectedMessages = projection;
1946
+ this.providerProjectionCanonical = canonical;
1947
+ this.providerProjectionSources = nextSources;
1948
+ this.providerProjectionSourcesById = sourcesById;
1949
+ this.indexTokenCountMap = counts;
1950
+ if (recount) {
1909
1951
  this.providerProjectionRequiresRecount = false;
1910
1952
  this.providerProjectionRecountFloors = undefined;
1911
1953
  }
@@ -1918,15 +1960,75 @@ export class AgentContext {
1918
1960
  if (message.id != null) {
1919
1961
  this.providerProjectionSourcesById?.set(message.id, message);
1920
1962
  }
1921
- projection.push(
1922
- Array.isArray(message.content)
1923
- ? cloneMessage(message, [...message.content])
1924
- : message
1925
- );
1963
+ const projected = this.projectMessage(message);
1964
+ projection.push(projected.message);
1965
+ this.providerProjectionCanonical?.push(projected.canonical);
1926
1966
  }
1927
1967
  return projection;
1928
1968
  }
1929
1969
 
1970
+ /**
1971
+ * The canonical history the pruner rewrites the projection from: for a model
1972
+ * without image input, the messages last given to
1973
+ * `getProviderProjectedMessages` with each image as its marker, so fading,
1974
+ * masking and input caps never bring an image back; otherwise `messages`.
1975
+ */
1976
+ getProviderCanonicalMessages(messages: BaseMessage[]): BaseMessage[] {
1977
+ return this.providerProjectionCanonical ?? messages;
1978
+ }
1979
+
1980
+ /**
1981
+ * The projection's copy of `message` and the canonical message it is
1982
+ * rewritten from; without image input, both read each image as its marker,
1983
+ * also in a tool artifact the request expands later. `omittedImages` marks a
1984
+ * content change that needs a new count.
1985
+ */
1986
+ private projectMessage(message: BaseMessage): {
1987
+ message: BaseMessage;
1988
+ canonical: BaseMessage;
1989
+ omittedImages: boolean;
1990
+ } {
1991
+ const content = Array.isArray(message.content)
1992
+ ? (message.content as MessageContentComplex[])
1993
+ : undefined;
1994
+ const omits =
1995
+ this.vision === false && !hasComputerCallOutputMarker(message);
1996
+ const omitted =
1997
+ omits && content != null ? omitImageBlocks(content) : undefined;
1998
+ const artifact =
1999
+ omits && message instanceof ToolMessage
2000
+ ? omitArtifactImages(message.artifact)
2001
+ : undefined;
2002
+ if (omitted == null && artifact == null) {
2003
+ return {
2004
+ message:
2005
+ content == null ? message : cloneMessage(message, [...content]),
2006
+ canonical: message,
2007
+ omittedImages: false,
2008
+ };
2009
+ }
2010
+ let readable = message.content as string | MessageContentComplex[];
2011
+ if (omitted != null) {
2012
+ readable =
2013
+ this.useLegacyContent && isLegacyConvertible(message, omitted)
2014
+ ? flattenLegacyContent(omitted)
2015
+ : omitted;
2016
+ }
2017
+ const copy = (value: string | MessageContentComplex[]): BaseMessage =>
2018
+ artifact == null
2019
+ ? cloneMessage(message, value)
2020
+ : cloneToolMessageWithContent(
2021
+ message as ToolMessage,
2022
+ value as BaseMessage['content'],
2023
+ artifact
2024
+ );
2025
+ return {
2026
+ message: copy(typeof readable === 'string' ? readable : [...readable]),
2027
+ canonical: copy(readable),
2028
+ omittedImages: omitted != null,
2029
+ };
2030
+ }
2031
+
1930
2032
  /**
1931
2033
  * Invalidates the provider projection when a graph reducer update rewrites
1932
2034
  * canonical history. Reducer updates expose replacements and removals before
@@ -1978,6 +2080,7 @@ export class AgentContext {
1978
2080
  this.providerProjectedMessages = undefined;
1979
2081
  this.providerProjectionSources = undefined;
1980
2082
  this.providerProjectionSourcesById = undefined;
2083
+ this.providerProjectionCanonical = undefined;
1981
2084
  }
1982
2085
 
1983
2086
  private prepareProviderProjectionRecount(
@@ -2189,19 +2292,26 @@ export class AgentContext {
2189
2292
  /** Refresh stale system overhead (handoff/summary changes) so instruction
2190
2293
  * tokens match the prompt a real call would send. */
2191
2294
  this.initializeSystemRunnable();
2192
- /** Clone array-content messages: the pruner unshifts reasoning blocks into
2193
- * AI content arrays in place, which would otherwise corrupt the caller's
2194
- * history. (Slot replacements land on the mapped array, not the caller's.) */
2195
- const projected = messages.map((message) =>
2196
- Array.isArray(message.content)
2197
- ? cloneMessage(message, [...message.content])
2198
- : message
2199
- );
2200
- let indexTokenCountMap = opts?.indexTokenCountMap;
2201
- if (indexTokenCountMap == null) {
2202
- indexTokenCountMap = {};
2203
- for (let i = 0; i < messages.length; i++) {
2204
- indexTokenCountMap[String(i)] = tokenCounter(messages[i]);
2295
+ /** The projection's copies: the pruner unshifts reasoning blocks into AI
2296
+ * content arrays in place, which would otherwise corrupt the caller's
2297
+ * history, and a model without image input reads each image as its
2298
+ * marker. (Slot replacements land on the mapped array, not the caller's.) */
2299
+ const supplied = opts?.indexTokenCountMap;
2300
+ let indexTokenCountMap: Record<string, number | undefined> = supplied ?? {};
2301
+ const projected: BaseMessage[] = [];
2302
+ for (let i = 0; i < messages.length; i++) {
2303
+ const { message, omittedImages } = this.projectMessage(messages[i]);
2304
+ projected.push(message);
2305
+ if (supplied == null) {
2306
+ indexTokenCountMap[String(i)] = tokenCounter(
2307
+ omittedImages ? message : messages[i]
2308
+ );
2309
+ } else if (omittedImages) {
2310
+ /** A supplied count priced the image the marker replaces; the copy keeps the caller's map intact. */
2311
+ if (indexTokenCountMap === supplied) {
2312
+ indexTokenCountMap = { ...supplied };
2313
+ }
2314
+ indexTokenCountMap[String(i)] = tokenCounter(message);
2205
2315
  }
2206
2316
  }
2207
2317
  const prune = createPruneMessages({
@@ -37,6 +37,7 @@ import type {
37
37
  GraphFactoryRequest,
38
38
  } from '@/graphs/graphFactory';
39
39
  import type { OverflowRecoveryPlan } from '@/llm/contextOverflowRecovery';
40
+ import type { GoogleGroundingMetadata } from '@/tools/search/types';
40
41
  import type { FallbackErrorContext } from '@/llm/invoke';
41
42
  import type { HandoffRouting } from './handoff';
42
43
  import type { HookRegistry } from '@/hooks';
@@ -184,6 +185,7 @@ import {
184
185
  isThinkingEnabled,
185
186
  getConfiguredCompletionTokens,
186
187
  } from '@/llm/request';
188
+ import { handleNativeSearchCitations, handleToolCalls } from '@/tools/handlers';
187
189
  import { createToolHistoryPreparation } from '@/messages/toolHistoryProjection';
188
190
  import { ToolNode as CustomToolNode, toolsCondition } from '@/tools/ToolNode';
189
191
  import { shouldTraceToolNodeForLangfuse } from '@/langfuseToolOutputTracing';
@@ -203,11 +205,11 @@ import { isRunStepResumeState } from '@/tools/runStepResume';
203
205
  import { resolveLocalToolsForBinding } from '@/tools/local';
204
206
  import { createSummarizeNode } from '@/summarization/node';
205
207
  import { getTruncationStopReason } from '@/llm/truncation';
208
+ import { SearchCitations } from '@/tools/search/citations';
206
209
  import { createSchemaOnlyTools } from '@/tools/schema';
207
210
  import { AgentContext } from '@/agents/AgentContext';
208
211
  import { createFakeStreamingLLM } from '@/llm/fake';
209
212
  import { handoffStateAnnotation } from './handoff';
210
- import { handleToolCalls } from '@/tools/handlers';
211
213
  import { resolveMaxSeals } from '@/llm/preempt';
212
214
  import { initializeModel } from '@/llm/init';
213
215
  import { HandlerRegistry } from '@/events';
@@ -847,6 +849,8 @@ export abstract class Graph<
847
849
  callerSignal?: AbortSignal;
848
850
  /** Set of invoked tool call IDs from non-message run steps completed mid-run, if any */
849
851
  invokedToolIds?: Set<string>;
852
+ /** Provider-native web search sources and the anchors still owed to their citations. */
853
+ searchCitations = new SearchCitations();
850
854
  /** Explicit host policy. Never inferred from missing ToolNode claims. */
851
855
  clientDelegatedToolNames?: ReadonlySet<string>;
852
856
  handlerRegistry: HandlerRegistry | undefined;
@@ -955,6 +959,7 @@ export abstract class Graph<
955
959
  this.messageStepHasToolCalls = new Map();
956
960
  this.prelimMessageIdsByStepKey = new Map();
957
961
  this.invokedToolIds = undefined;
962
+ this.searchCitations = new SearchCitations();
958
963
  this.handlerRegistry = undefined;
959
964
  this.parentToolHandlerRegistry = undefined;
960
965
  this.hookRegistry = undefined;
@@ -1661,6 +1666,25 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
1661
1666
  this.streamLimits = resolveStreamLimits(streamLimits);
1662
1667
  if (providerTextProtection != null)
1663
1668
  validateProviderTextProtection(providerTextProtection);
1669
+ if (providerTextProtection?.batching != null) {
1670
+ const agent = agents[0];
1671
+ if (
1672
+ this.isMultiAgentGraph() ||
1673
+ agents.length !== 1 ||
1674
+ preemption != null ||
1675
+ (clientDelegatedToolNames?.length ?? 0) > 0 ||
1676
+ (agent.tools?.length ?? 0) > 0 ||
1677
+ (agent.graphTools?.length ?? 0) > 0 ||
1678
+ (agent.toolDefinitions?.length ?? 0) > 0 ||
1679
+ (agent.toolRegistry?.size ?? 0) > 0 ||
1680
+ (agent.subagentConfigs?.length ?? 0) > 0 ||
1681
+ agent.summarizationEnabled === true ||
1682
+ agent.summarizeOnly === true ||
1683
+ agent.initialSummary != null
1684
+ ) {
1685
+ throw new ProviderTextProtectionError('unsupported');
1686
+ }
1687
+ }
1664
1688
  this.providerTextProtection = providerTextProtection;
1665
1689
  const toolResultGate =
1666
1690
  toolResultProtection == null
@@ -1854,6 +1878,7 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
1854
1878
  new Map()
1855
1879
  );
1856
1880
  this.invokedToolIds = resetIfNotEmpty(this.invokedToolIds, undefined);
1881
+ this.searchCitations = new SearchCitations();
1857
1882
  this.resetPreemptTurnState();
1858
1883
  this.resetPreemptTotals();
1859
1884
  const hasScopedCheckpoint =
@@ -2356,6 +2381,15 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
2356
2381
  return false;
2357
2382
  }
2358
2383
 
2384
+ const anchors = this.searchCitations.release(stepId);
2385
+ if (anchors != null && this.config != null) {
2386
+ await this.dispatchMessageDelta(
2387
+ stepId,
2388
+ { content: [{ type: ContentTypes.TEXT, text: anchors.text }] },
2389
+ anchors.metadata ?? options?.metadata
2390
+ );
2391
+ }
2392
+
2359
2393
  const closedAt = options?.at ?? Date.now();
2360
2394
  runStep.status = status;
2361
2395
  if (status === 'completed') {
@@ -2484,6 +2518,54 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
2484
2518
  await this.closeRunStep(stepId, 'completed', { metadata, at: closeAt });
2485
2519
  }
2486
2520
 
2521
+ /** Gemini grounding and OpenAI url_citation arrive after the text they cite. */
2522
+ private tracksSearchText(metadata?: Record<string, unknown>): boolean {
2523
+ if (metadata == null) {
2524
+ return false;
2525
+ }
2526
+ try {
2527
+ const { provider } = this.getAgentContext(metadata);
2528
+ return (
2529
+ isGoogleLike(provider) ||
2530
+ provider === Providers.OPENAI ||
2531
+ provider === Providers.AZURE
2532
+ );
2533
+ } catch (_e) {
2534
+ return false;
2535
+ }
2536
+ }
2537
+
2538
+ /** Keeps a Gemini chunk's grounding for the lane's model call. */
2539
+ groundSearchCitations(
2540
+ metadata: Record<string, unknown> | undefined,
2541
+ grounding: GoogleGroundingMetadata
2542
+ ): void {
2543
+ this.searchCitations.ground(
2544
+ this.getStepAgentKey(metadata),
2545
+ grounding,
2546
+ metadata
2547
+ );
2548
+ }
2549
+
2550
+ /**
2551
+ * Turns the web search citations a finished agent model call carried into
2552
+ * a `web_search` result and anchors in its text. Model calls outside an
2553
+ * agent node (summaries, tool internals) never own the lane's text.
2554
+ */
2555
+ async settleSearchCitations(
2556
+ metadata?: Record<string, unknown>
2557
+ ): Promise<void> {
2558
+ const node = metadata?.langgraph_node;
2559
+ if (typeof node !== 'string' || !node.startsWith(AGENT)) {
2560
+ return;
2561
+ }
2562
+ const call = this.searchCitations.take(this.getStepAgentKey(metadata));
2563
+ if (call == null) {
2564
+ return;
2565
+ }
2566
+ await handleNativeSearchCitations({ graph: this, call, metadata });
2567
+ }
2568
+
2487
2569
  /**
2488
2570
  * Closes the tracked open MESSAGE_CREATION step for the event's agent lane.
2489
2571
  * Fires on every model end, so the empty-map check short-circuits ahead of
@@ -3434,7 +3516,6 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
3434
3516
  }
3435
3517
  this.config = config;
3436
3518
 
3437
- let messagesToUse = messages;
3438
3519
  let contextUsage: t.ContextUsageEvent | null = null;
3439
3520
  /**
3440
3521
  * Held outside the prune block so overflow recovery — which detours to
@@ -3445,9 +3526,14 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
3445
3526
  const canProjectContext =
3446
3527
  agentContext.tokenCounter != null &&
3447
3528
  agentContext.maxContextTokens != null;
3448
- const providerMessages = canProjectContext
3449
- ? agentContext.getProviderProjectedMessages(messages)
3450
- : messages;
3529
+ /** A model without image input reads history through the projection even
3530
+ * without a pruner, so no later transform (tool folding included) sees
3531
+ * image bytes before the request replaces them. */
3532
+ const providerMessages =
3533
+ canProjectContext || agentContext.vision === false
3534
+ ? agentContext.getProviderProjectedMessages(messages)
3535
+ : messages;
3536
+ let messagesToUse = providerMessages;
3451
3537
  if (
3452
3538
  !agentContext.pruneMessages &&
3453
3539
  agentContext.tokenCounter &&
@@ -3494,7 +3580,8 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
3494
3580
  effectiveInstructionTokens,
3495
3581
  } = agentContext.pruneMessages({
3496
3582
  messages: providerMessages,
3497
- canonicalMessages: messages,
3583
+ canonicalMessages:
3584
+ agentContext.getProviderCanonicalMessages(messages),
3498
3585
  canonicalPrefixStable: true,
3499
3586
  usageMetadata: agentContext.currentUsage,
3500
3587
  lastCallUsage: agentContext.lastCallUsage,
@@ -4253,6 +4340,8 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
4253
4340
  config,
4254
4341
  maxToolResultChars: maxProviderToolResultChars,
4255
4342
  toolHistory,
4343
+ vision: agentContext.vision,
4344
+ useLegacyContent: agentContext.useLegacyContent,
4256
4345
  measure: (preparedMessages) =>
4257
4346
  measureProviderPayload(
4258
4347
  trackProviderMessageOrigins(
@@ -4814,6 +4903,8 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
4814
4903
  config: fallbackConfig,
4815
4904
  maxToolResultChars: fallbackToolResultChars,
4816
4905
  toolHistory: fallbackToolHistory,
4906
+ vision: agentContext.vision,
4907
+ useLegacyContent: agentContext.useLegacyContent,
4817
4908
  measure: (prepared) => {
4818
4909
  projection = measureFallback(
4819
4910
  trackProviderMessageOrigins(cached, prepared)
@@ -5951,6 +6042,12 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
5951
6042
 
5952
6043
  createWorkflow(): t.CompiledStateWorkflow {
5953
6044
  this.hasCompiledCheckpointer = this.compileOptions?.checkpointer != null;
6045
+ if (
6046
+ this.hasCompiledCheckpointer &&
6047
+ this.providerTextProtection?.batching != null
6048
+ ) {
6049
+ throw new ProviderTextProtectionError('unsupported');
6050
+ }
5954
6051
  const agentNode = this.createAgentNode(this.defaultAgentId);
5955
6052
  const StateAnnotation = Annotation.Root({
5956
6053
  messages: Annotation<BaseMessage[]>({
@@ -6318,11 +6415,23 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
6318
6415
  if (!this.config) {
6319
6416
  throw new Error('No config provided');
6320
6417
  }
6418
+ const content = Array.isArray(delta.content)
6419
+ ? (this.searchCitations.anchor(id, delta.content, metadata) ??
6420
+ delta.content)
6421
+ : delta.content;
6321
6422
  const messageDelta: t.MessageDeltaEvent = {
6322
6423
  id,
6323
- delta,
6424
+ delta: content === delta.content ? delta : { ...delta, content },
6324
6425
  };
6325
- if (hasTextDeltaContent(delta.content)) {
6426
+ if (content != null && this.tracksSearchText(metadata)) {
6427
+ this.searchCitations.track(
6428
+ this.getStepAgentKey(metadata),
6429
+ id,
6430
+ content,
6431
+ metadata
6432
+ );
6433
+ }
6434
+ if (hasTextDeltaContent(content)) {
6326
6435
  this.messageStepHasTextDeltas.add(id);
6327
6436
  }
6328
6437
  const handler = this.handlerRegistry?.getHandler(
@@ -66,6 +66,7 @@ export function createHostProviderTextService(options: {
66
66
  const identity = boundIdentity(options.identity);
67
67
  const policy = options.policy;
68
68
  validateProviderTextProtection(policy);
69
+ if (policy.batching != null) throw new ProviderTextProtectionError('unsupported');
69
70
  const { admission, inspectionTimeoutMs } = options;
70
71
  if (inspectionTimeoutMs !== undefined)
71
72
  validateProviderTextTimeout(inspectionTimeoutMs);
package/src/index.ts CHANGED
@@ -125,11 +125,13 @@ export * from './rerank';
125
125
 
126
126
  export {
127
127
  PROVIDER_TEXT_PROTECTION_VERSION,
128
+ PROVIDER_TEXT_BATCHING_VERSION,
128
129
  ProviderTextProtectionError,
129
130
  serializeProviderTextProtectionError,
130
131
  deserializeProviderTextProtectionError,
131
132
  } from './protection/providerText';
132
133
  export type {
134
+ ProviderTextBatching,
133
135
  ProviderTextProtection,
134
136
  ProviderTextProtectionResult,
135
137
  ProviderTextProtectionErrorCode,