@librechat/agents 4.2.18 → 4.2.20

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 (41) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +2 -6
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/graphs/Graph.cjs +36 -15
  4. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  5. package/dist/cjs/llm/vertexai/index.cjs +89 -38
  6. package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
  7. package/dist/cjs/summarization/node.cjs +2 -1
  8. package/dist/cjs/summarization/node.cjs.map +1 -1
  9. package/dist/cjs/tools/ToolNode.cjs +67 -6
  10. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  11. package/dist/cjs/tools/ToolSearch.cjs +88 -12
  12. package/dist/cjs/tools/ToolSearch.cjs.map +1 -1
  13. package/dist/cjs/tools/search/keenable-scraper.cjs +27 -7
  14. package/dist/cjs/tools/search/keenable-scraper.cjs.map +1 -1
  15. package/dist/esm/agents/AgentContext.mjs +2 -6
  16. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  17. package/dist/esm/graphs/Graph.mjs +36 -15
  18. package/dist/esm/graphs/Graph.mjs.map +1 -1
  19. package/dist/esm/llm/vertexai/index.mjs +89 -38
  20. package/dist/esm/llm/vertexai/index.mjs.map +1 -1
  21. package/dist/esm/summarization/node.mjs +2 -1
  22. package/dist/esm/summarization/node.mjs.map +1 -1
  23. package/dist/esm/tools/ToolNode.mjs +67 -6
  24. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  25. package/dist/esm/tools/ToolSearch.mjs +88 -12
  26. package/dist/esm/tools/ToolSearch.mjs.map +1 -1
  27. package/dist/esm/tools/search/keenable-scraper.mjs +27 -7
  28. package/dist/esm/tools/search/keenable-scraper.mjs.map +1 -1
  29. package/dist/types/tools/ToolNode.d.ts +7 -0
  30. package/dist/types/tools/search/keenable-scraper.d.ts +6 -0
  31. package/dist/types/types/graph.d.ts +2 -0
  32. package/package.json +1 -1
  33. package/src/agents/AgentContext.ts +7 -11
  34. package/src/graphs/Graph.ts +56 -18
  35. package/src/llm/vertexai/index.ts +193 -67
  36. package/src/summarization/node.ts +1 -0
  37. package/src/tools/ToolNode.ts +133 -11
  38. package/src/tools/ToolSearch.ts +161 -12
  39. package/src/tools/search/keenable-scraper.ts +62 -7
  40. package/src/types/graph.ts +2 -0
  41. package/src/utils/llmConfig.ts +1 -1
@@ -1,6 +1,10 @@
1
1
  import { ChatGoogle } from '@langchain/google-gauth';
2
2
  import { ChatConnection } from '@langchain/google-common';
3
- import { AIMessageChunk, isAIMessage, isToolMessage } from '@langchain/core/messages';
3
+ import {
4
+ AIMessageChunk,
5
+ isAIMessage,
6
+ isToolMessage,
7
+ } from '@langchain/core/messages';
4
8
  import type {
5
9
  GeminiContent,
6
10
  GoogleAIAPI,
@@ -114,18 +118,24 @@ export function fixThoughtSignatures(
114
118
  modelContents[i].parts = replay;
115
119
  continue;
116
120
  }
117
- if (Object.hasOwn(aiMessages[i].additional_kwargs, GEMINI_PARTS) && aiMessages[i].additional_kwargs[GEMINI_REPLAY_UNSUPPORTED] !== true) {
121
+ if (
122
+ Object.hasOwn(aiMessages[i].additional_kwargs, GEMINI_PARTS) &&
123
+ aiMessages[i].additional_kwargs[GEMINI_REPLAY_UNSUPPORTED] !== true
124
+ ) {
118
125
  for (const part of modelContents[i].parts) delete part.thoughtSignature;
119
126
  continue;
120
127
  }
121
- const signatureMap = aiMessages[i].additional_kwargs[GEMINI_SIGNATURES] as Record<string, string> | undefined;
128
+ const signatureMap = aiMessages[i].additional_kwargs[GEMINI_SIGNATURES] as
129
+ | Record<string, string>
130
+ | undefined;
122
131
  if (signatureMap != null) {
123
132
  let callIndex = 0;
124
133
  for (const part of modelContents[i].parts) {
125
134
  if (!('functionCall' in part)) continue;
126
135
  const id = aiMessages[i].tool_calls?.[callIndex++]?.id;
127
136
  const signature = id != null ? signatureMap[id] : undefined;
128
- if (typeof signature === 'string' && signature !== '') part.thoughtSignature = signature;
137
+ if (typeof signature === 'string' && signature !== '')
138
+ part.thoughtSignature = signature;
129
139
  else delete part.thoughtSignature;
130
140
  }
131
141
  continue;
@@ -137,32 +147,104 @@ export function fixThoughtSignatures(
137
147
  const content = modelContents[i];
138
148
  const callCount = aiMessages[i].tool_calls?.length ?? 0;
139
149
  const mismatchedSlots = signatures.length !== content.parts.length;
140
- if (mismatchedSlots && content.parts.some((part) => 'text' in part)) continue;
141
- if (mismatchedSlots && signatures.slice(callCount).some((signature) => signature != null && signature !== '')) continue;
150
+ if (mismatchedSlots && content.parts.some((part) => 'text' in part))
151
+ continue;
152
+ if (
153
+ mismatchedSlots &&
154
+ signatures
155
+ .slice(callCount)
156
+ .some((signature) => signature != null && signature !== '')
157
+ )
158
+ continue;
142
159
  for (let index = 0; index < content.parts.length; index++) {
143
160
  const part = content.parts[index];
144
161
  const signature = signatures[index];
145
- if ((part.thoughtSignature == null || part.thoughtSignature === '') &&
146
- typeof signature === 'string' && signature !== '') {
162
+ if (
163
+ (part.thoughtSignature == null || part.thoughtSignature === '') &&
164
+ typeof signature === 'string' &&
165
+ signature !== ''
166
+ ) {
147
167
  part.thoughtSignature = signature;
148
168
  }
149
169
  }
150
170
  }
151
171
  }
152
172
 
153
- type VertexResponseData = Omit<Partial<GenerateContentResponseData>, 'candidates'> & {
154
- candidates?: Array<Omit<Partial<GeminiResponseCandidate>, 'content'> & {
155
- /** Vertex can send a candidate's `content` without `parts`, e.g. `{ role: 'model' }`. */
156
- content?: Omit<GeminiResponseCandidate['content'], 'parts'> &
157
- Partial<Pick<GeminiResponseCandidate['content'], 'parts'>>;
158
- }>;
173
+ type VertexResponseData = Omit<
174
+ Partial<GenerateContentResponseData>,
175
+ 'candidates'
176
+ > & {
177
+ candidates?: Array<
178
+ Omit<Partial<GeminiResponseCandidate>, 'content'> & {
179
+ /** Vertex can send a candidate's `content` without `parts`, e.g. `{ role: 'model' }`. */
180
+ content?: Omit<GeminiResponseCandidate['content'], 'parts'> &
181
+ Partial<Pick<GeminiResponseCandidate['content'], 'parts'>>;
182
+ continuationToken?: string;
183
+ }
184
+ >;
185
+ };
186
+
187
+ /** Upper bound on long-decode segments in one response (each up to 65,536 output tokens). */
188
+ const MAX_LONG_DECODE_SEGMENTS = 8;
189
+ type ContinuationParams = { continuationToken?: string };
190
+
191
+ type ContinuationGenerationInfo = {
192
+ continuation_token?: string;
193
+ finish_reason?: string;
194
+ usage_metadata?: UsageMetadata;
159
195
  };
160
196
 
197
+ function withContinuationToken(
198
+ chunk: ChatGenerationChunk | null,
199
+ data: VertexResponseData
200
+ ): ChatGenerationChunk | null {
201
+ const continuationToken = data.candidates?.[0]?.continuationToken;
202
+ if (chunk == null || continuationToken == null) return chunk;
203
+ chunk.generationInfo = {
204
+ ...chunk.generationInfo,
205
+ continuation_token: continuationToken,
206
+ };
207
+ return chunk;
208
+ }
209
+
161
210
  class CustomChatConnection extends ChatConnection<VertexAIClientOptions> {
162
211
  thinkingConfig?: GoogleThinkingConfig;
163
212
 
164
213
  buildGeminiAPI(): GoogleAIAPI {
165
214
  const api = super.buildGeminiAPI();
215
+ const toChatGeneration: GoogleAIAPI['responseToChatGeneration'] = (
216
+ response
217
+ ): ChatGenerationChunk | null => {
218
+ const data = response.data as VertexResponseData;
219
+ const candidate = data.candidates?.[0];
220
+ const parts = candidate?.content?.parts;
221
+ if (candidate?.content == null || parts == null || parts.length === 0)
222
+ return api.responseToChatGeneration(response);
223
+ let combined: ChatGenerationChunk | undefined;
224
+ let generationInfo: ChatGenerationChunk['generationInfo'];
225
+ for (const part of parts) {
226
+ const chunk = api.responseToChatGeneration({
227
+ data: {
228
+ ...data,
229
+ candidates: [
230
+ {
231
+ ...candidate,
232
+ content: { ...candidate.content, parts: [part] },
233
+ },
234
+ ],
235
+ } as GenerateContentResponseData,
236
+ });
237
+ if (chunk != null) {
238
+ generationInfo ??= chunk.generationInfo;
239
+ chunk.generationInfo = undefined;
240
+ combined = combined == null ? chunk : combined.concat(chunk);
241
+ }
242
+ }
243
+ if (combined == null) return null;
244
+ combined.generationInfo = generationInfo;
245
+ captureGeminiReplayParts(combined.message, parts, this.model);
246
+ return combined;
247
+ };
166
248
  return {
167
249
  ...api,
168
250
  responseToChatResult: (response): ChatResult => {
@@ -177,37 +259,11 @@ class CustomChatConnection extends ChatConnection<VertexAIClientOptions> {
177
259
  );
178
260
  return result;
179
261
  },
180
- responseToChatGeneration: (response): ChatGenerationChunk | null => {
181
- const data = response.data as VertexResponseData;
182
- const candidate = data.candidates?.[0];
183
- const parts = candidate?.content?.parts;
184
- if (candidate?.content == null || parts == null || parts.length === 0)
185
- return api.responseToChatGeneration(response);
186
- let combined: ChatGenerationChunk | undefined;
187
- let generationInfo: ChatGenerationChunk['generationInfo'];
188
- for (const part of parts) {
189
- const chunk = api.responseToChatGeneration({
190
- data: {
191
- ...data,
192
- candidates: [
193
- {
194
- ...candidate,
195
- content: { ...candidate.content, parts: [part] },
196
- },
197
- ],
198
- } as GenerateContentResponseData,
199
- });
200
- if (chunk != null) {
201
- generationInfo ??= chunk.generationInfo;
202
- chunk.generationInfo = undefined;
203
- combined = combined == null ? chunk : combined.concat(chunk);
204
- }
205
- }
206
- if (combined == null) return null;
207
- combined.generationInfo = generationInfo;
208
- captureGeminiReplayParts(combined.message, parts, this.model);
209
- return combined;
210
- },
262
+ responseToChatGeneration: (response) =>
263
+ withContinuationToken(
264
+ toChatGeneration(response),
265
+ response.data as VertexResponseData
266
+ ),
211
267
  };
212
268
  }
213
269
 
@@ -261,7 +317,9 @@ class CustomChatConnection extends ChatConnection<VertexAIClientOptions> {
261
317
  if (call.id != null) callNames.set(call.id, call.name);
262
318
  }
263
319
  } else if (isToolMessage(message)) {
264
- functionResponseNames.push(callNames.get(message.tool_call_id) ?? message.name);
320
+ functionResponseNames.push(
321
+ callNames.get(message.tool_call_id) ?? message.name
322
+ );
265
323
  }
266
324
  }
267
325
  let responseIndex = 0;
@@ -277,6 +335,13 @@ class CustomChatConnection extends ChatConnection<VertexAIClientOptions> {
277
335
  }
278
336
  }
279
337
  }
338
+ const continuationToken = (
339
+ parameters as GoogleAIModelRequestParams & ContinuationParams
340
+ ).continuationToken;
341
+ if (continuationToken != null) {
342
+ (formattedData as GeminiRequest & ContinuationParams).continuationToken =
343
+ continuationToken;
344
+ }
280
345
  return formattedData;
281
346
  }
282
347
  }
@@ -584,8 +649,16 @@ export class ChatVertexAI extends ChatGoogle {
584
649
  ? { ...(params ?? {}), model: modelOrFields }
585
650
  : modelOrFields;
586
651
  const dynamicThinkingBudget = fields?.thinkingBudget === -1;
652
+ const model = (fields?.model ?? fields?.modelName)
653
+ ?.toLowerCase()
654
+ .split('/')
655
+ .pop();
656
+ const apiVersion =
657
+ fields?.apiVersion ??
658
+ (model?.startsWith('gemini-4-') === true ? 'v1beta1' : undefined);
587
659
  super({
588
660
  ...fields,
661
+ ...(apiVersion != null ? { apiVersion } : {}),
589
662
  platformType: 'gcp',
590
663
  });
591
664
  this.dynamicThinkingBudget = dynamicThinkingBudget;
@@ -596,6 +669,14 @@ export class ChatVertexAI extends ChatGoogle {
596
669
  options?: this['ParsedCallOptions'] | undefined
597
670
  ): GoogleAIModelRequestParams {
598
671
  const params = super.invocationParams(options);
672
+ const continuationToken = (
673
+ options as (this['ParsedCallOptions'] & ContinuationParams) | undefined
674
+ )?.continuationToken;
675
+ if (continuationToken != null) {
676
+ (
677
+ params as GoogleAIModelRequestParams & ContinuationParams
678
+ ).continuationToken = continuationToken;
679
+ }
599
680
  if (this.dynamicThinkingBudget) {
600
681
  params.maxReasoningTokens = -1;
601
682
  }
@@ -618,29 +699,74 @@ export class ChatVertexAI extends ChatGoogle {
618
699
  messages: BaseMessage[],
619
700
  options: this['ParsedCallOptions']
620
701
  ): AsyncGenerator<ChatGenerationChunk> {
621
- let lastGoodUsage: UsageMetadata | undefined;
622
- for await (const chunk of super._streamResponseChunks(
623
- messages,
624
- options,
625
- undefined
626
- )) {
627
- const genUsage = (
628
- chunk.generationInfo as { usage_metadata?: UsageMetadata } | undefined
629
- )?.usage_metadata;
630
- if (genUsage) {
631
- lastGoodUsage = genUsage;
632
- }
633
- if (chunk.message instanceof AIMessageChunk) {
634
- const repaired = repairStreamUsageMetadata(
635
- chunk.message.usage_metadata,
636
- lastGoodUsage
637
- );
638
- if (repaired !== chunk.message.usage_metadata) {
639
- chunk.message.usage_metadata = repaired;
702
+ type StreamOptions = this['ParsedCallOptions'] & ContinuationParams;
703
+ let nextOptions = options as StreamOptions;
704
+ let initialPromptTokens: number | undefined;
705
+ for (let segment = 0; ; segment++) {
706
+ const continued = nextOptions.continuationToken != null;
707
+ /** The last allowed segment keeps its CONTINUATION finish, so a host sees a cut-off
708
+ * answer instead of a silent end when the provider never stops asking for more. */
709
+ const mayContinue = segment < MAX_LONG_DECODE_SEGMENTS - 1;
710
+ let lastGoodUsage: UsageMetadata | undefined;
711
+ let finishReason: string | undefined;
712
+ let token: string | undefined;
713
+ let shouldContinue = false;
714
+ for await (const chunk of super._streamResponseChunks(
715
+ messages,
716
+ nextOptions,
717
+ undefined
718
+ )) {
719
+ const info = chunk.generationInfo as
720
+ | ContinuationGenerationInfo
721
+ | undefined;
722
+ const genUsage = info?.usage_metadata;
723
+ if (genUsage) {
724
+ lastGoodUsage = genUsage;
725
+ initialPromptTokens ??= genUsage.input_tokens;
640
726
  }
641
- sealCompleteStreamedToolCalls(chunk.message);
727
+ finishReason = info?.finish_reason?.toUpperCase() ?? finishReason;
728
+ token = info?.continuation_token ?? token;
729
+ if (chunk.message instanceof AIMessageChunk) {
730
+ const repaired = repairStreamUsageMetadata(
731
+ chunk.message.usage_metadata,
732
+ lastGoodUsage
733
+ );
734
+ if (repaired !== chunk.message.usage_metadata) {
735
+ chunk.message.usage_metadata = repaired;
736
+ }
737
+ sealCompleteStreamedToolCalls(chunk.message);
738
+ }
739
+ shouldContinue =
740
+ mayContinue && token != null && finishReason === 'CONTINUATION';
741
+ if (
742
+ chunk.generationInfo != null &&
743
+ (info?.continuation_token != null || shouldContinue)
744
+ ) {
745
+ chunk.generationInfo = { ...chunk.generationInfo };
746
+ delete chunk.generationInfo.continuation_token;
747
+ if (shouldContinue) {
748
+ delete chunk.generationInfo.finish_reason;
749
+ delete chunk.generationInfo.finishReason;
750
+ }
751
+ }
752
+ if (
753
+ continued &&
754
+ !shouldContinue &&
755
+ info?.finish_reason != null &&
756
+ initialPromptTokens != null &&
757
+ chunk.message instanceof AIMessageChunk
758
+ ) {
759
+ chunk.message.response_metadata = {
760
+ ...chunk.message.response_metadata,
761
+ initial_prompt_token_count: initialPromptTokens,
762
+ };
763
+ }
764
+ yield chunk;
765
+ }
766
+ if (!shouldContinue || options.signal?.aborted === true) {
767
+ break;
642
768
  }
643
- yield chunk;
769
+ nextOptions = { ...nextOptions, continuationToken: token };
644
770
  }
645
771
  }
646
772
  buildConnection(
@@ -2166,6 +2166,7 @@ export function createSummarizeNode({
2166
2166
  text: summaryText,
2167
2167
  tokenCount,
2168
2168
  precedesMessages: messagesToRetain.length > 0,
2169
+ retainedMessageCount: messagesToRetain.length,
2169
2170
  },
2170
2171
  }
2171
2172
  : {}),
@@ -896,6 +896,29 @@ function retainCodeSessionInputs(
896
896
  });
897
897
  }
898
898
 
899
+ /** Tools that can create files a `read_file` in the same batch is about to read. */
900
+ const CODE_WRITING_TOOL_NAMES = new Set<string>([
901
+ Constants.EXECUTE_CODE,
902
+ 'bash_tool',
903
+ ]);
904
+ const READ_FILE_TOOL_NAME = 'read_file';
905
+
906
+ function hasCodeWriterAndReadFile(calls: ReadonlyArray<ToolCall>): boolean {
907
+ let hasCodeWriter = false;
908
+ let hasReadFile = false;
909
+ for (const call of calls) {
910
+ if (CODE_WRITING_TOOL_NAMES.has(call.name)) {
911
+ hasCodeWriter = true;
912
+ } else if (call.name === READ_FILE_TOOL_NAME) {
913
+ hasReadFile = true;
914
+ }
915
+ if (hasCodeWriter && hasReadFile) {
916
+ return true;
917
+ }
918
+ }
919
+ return false;
920
+ }
921
+
899
922
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
900
923
  export class ToolNode<T = any> extends RunnableCallable<T, T> {
901
924
  private toolMap: Map<string, StructuredToolInterface | RunnableToolLike>;
@@ -1807,6 +1830,27 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
1807
1830
  return tool.invoke(invokeParams, runtime);
1808
1831
  }
1809
1832
 
1833
+ /**
1834
+ * Whether a batch may run its code tools before its `read_file` calls, in two phases. Never when
1835
+ * an approval could pause between the phases: LangGraph re-runs the whole node on resume and
1836
+ * would execute the code again. Nor when result-altering or `PostToolBatch` hooks expect the
1837
+ * batch as one unit: each dispatch fires batch hooks on its own partial set.
1838
+ */
1839
+ private canDeferReadFile(
1840
+ calls: ReadonlyArray<ToolCall>,
1841
+ config: RunnableConfig
1842
+ ): boolean {
1843
+ if (!hasCodeWriterAndReadFile(calls)) {
1844
+ return false;
1845
+ }
1846
+ const runId = (config.configurable?.run_id as string | undefined) ?? '';
1847
+ return (
1848
+ this.humanInTheLoop?.enabled !== true &&
1849
+ this.hookRegistry?.hasResultAlteringHooks(runId) !== true &&
1850
+ this.hookRegistry?.hasHookFor('PostToolBatch', runId) !== true
1851
+ );
1852
+ }
1853
+
1810
1854
  /** Only Graph's built-in subagent binding is allowed to call this seam. */
1811
1855
  prestartSubagent(
1812
1856
  call: ToolCall,
@@ -5515,14 +5559,13 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
5515
5559
  return restoreResult(call, result);
5516
5560
  };
5517
5561
 
5518
- const interrupting = this.interruptingToolNames;
5519
- const hasInterrupting =
5520
- interrupting != null &&
5521
- directCalls.some((call) => interrupting.has(call.name));
5522
-
5523
- if (!hasInterrupting) {
5562
+ /** Runs positions concurrently and returns their outputs in order, preferring a real failure
5563
+ * over a graph interrupt when both are rejected. */
5564
+ const settle = async (
5565
+ positions: number[]
5566
+ ): Promise<(BaseMessage | Command)[]> => {
5524
5567
  const results = await Promise.allSettled(
5525
- directCalls.map((call, i) => runOne(call, i))
5568
+ positions.map((pos) => runOne(directCalls[pos], pos))
5526
5569
  );
5527
5570
  this.throwIfBreakerTripped(config);
5528
5571
  const failed =
@@ -5539,6 +5582,45 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
5539
5582
  }
5540
5583
  return result.value.output;
5541
5584
  });
5585
+ };
5586
+
5587
+ /** Runs a group, with code tools before `read_file` when {@link canDeferReadFile} allows it. */
5588
+ const runPositionsGroup = async (
5589
+ positions: number[]
5590
+ ): Promise<(BaseMessage | Command)[]> => {
5591
+ const groupCalls = positions.map((pos) => directCalls[pos]);
5592
+ if (!this.canDeferReadFile(groupCalls, config)) {
5593
+ return settle(positions);
5594
+ }
5595
+ const primarySlots: number[] = [];
5596
+ const readFileSlots: number[] = [];
5597
+ positions.forEach((pos, slot) => {
5598
+ (directCalls[pos].name === READ_FILE_TOOL_NAME
5599
+ ? readFileSlots
5600
+ : primarySlots
5601
+ ).push(slot);
5602
+ });
5603
+ const groupOutputs: (BaseMessage | Command)[] = new Array(
5604
+ positions.length
5605
+ );
5606
+ for (const phaseSlots of [primarySlots, readFileSlots]) {
5607
+ const phaseOutputs = await settle(
5608
+ phaseSlots.map((slot) => positions[slot])
5609
+ );
5610
+ phaseSlots.forEach((slot, k) => {
5611
+ groupOutputs[slot] = phaseOutputs[k];
5612
+ });
5613
+ }
5614
+ return groupOutputs;
5615
+ };
5616
+
5617
+ const interrupting = this.interruptingToolNames;
5618
+ const hasInterrupting =
5619
+ interrupting != null &&
5620
+ directCalls.some((call) => interrupting.has(call.name));
5621
+
5622
+ if (!hasInterrupting) {
5623
+ return runPositionsGroup(directCalls.map((_, i) => i));
5542
5624
  }
5543
5625
 
5544
5626
  const outputs: (BaseMessage | Command)[] = new Array(directCalls.length);
@@ -5634,11 +5716,9 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
5634
5716
  this.throwIfBreakerTripped(config);
5635
5717
 
5636
5718
  // No interrupting call suspended — safe to run the remaining siblings.
5637
- const regularOutputs = await Promise.all(
5638
- regularPositions.map((i) => runOne(directCalls[i], i))
5639
- );
5719
+ const regularOutputs = await runPositionsGroup(regularPositions);
5640
5720
  regularPositions.forEach((i, k) => {
5641
- outputs[i] = regularOutputs[k].output;
5721
+ outputs[i] = regularOutputs[k];
5642
5722
  });
5643
5723
 
5644
5724
  return outputs;
@@ -5662,6 +5742,48 @@ export class ToolNode<T = any> extends RunnableCallable<T, T> {
5662
5742
  input: any,
5663
5743
  batchContext: DispatchBatchContext = {}
5664
5744
  ): Promise<T> {
5745
+ if (this.canDeferReadFile(toolCalls, config)) {
5746
+ const primaryIndices: number[] = [];
5747
+ const readFileIndices: number[] = [];
5748
+ for (let i = 0; i < toolCalls.length; i++) {
5749
+ if (toolCalls[i].name === READ_FILE_TOOL_NAME) {
5750
+ readFileIndices.push(i);
5751
+ } else {
5752
+ primaryIndices.push(i);
5753
+ }
5754
+ }
5755
+ const sliceBatchContext = (indices: number[]): DispatchBatchContext => ({
5756
+ ...batchContext,
5757
+ ...(batchContext.batchIndices != null && {
5758
+ batchIndices: indices.map((i) => batchContext.batchIndices![i]),
5759
+ }),
5760
+ });
5761
+ const primaryResult = await this.dispatchToolEvents(
5762
+ primaryIndices.map((i) => toolCalls[i]),
5763
+ config,
5764
+ sliceBatchContext(primaryIndices)
5765
+ );
5766
+ this.throwIfBreakerTripped(config);
5767
+ const readFileResult = await this.dispatchToolEvents(
5768
+ readFileIndices.map((i) => toolCalls[i]),
5769
+ config,
5770
+ sliceBatchContext(readFileIndices)
5771
+ );
5772
+ const orderedToolMessages: BaseMessage[] = new Array(toolCalls.length);
5773
+ primaryIndices.forEach((origIdx, k) => {
5774
+ orderedToolMessages[origIdx] = primaryResult.toolMessages[k];
5775
+ });
5776
+ readFileIndices.forEach((origIdx, k) => {
5777
+ orderedToolMessages[origIdx] = readFileResult.toolMessages[k];
5778
+ });
5779
+ const outputs: BaseMessage[] = [
5780
+ ...orderedToolMessages,
5781
+ ...primaryResult.injected,
5782
+ ...readFileResult.injected,
5783
+ ];
5784
+ return (Array.isArray(input) ? outputs : { messages: outputs }) as T;
5785
+ }
5786
+
5665
5787
  const { toolMessages, injected } = await this.dispatchToolEvents(
5666
5788
  toolCalls,
5667
5789
  config,