@librechat/agents 4.2.19 → 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 (33) 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 +14 -1
  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/tools/ToolNode.cjs +67 -6
  8. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  9. package/dist/cjs/tools/ToolSearch.cjs +88 -12
  10. package/dist/cjs/tools/ToolSearch.cjs.map +1 -1
  11. package/dist/cjs/tools/search/keenable-scraper.cjs +27 -7
  12. package/dist/cjs/tools/search/keenable-scraper.cjs.map +1 -1
  13. package/dist/esm/agents/AgentContext.mjs +2 -6
  14. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  15. package/dist/esm/graphs/Graph.mjs +14 -1
  16. package/dist/esm/graphs/Graph.mjs.map +1 -1
  17. package/dist/esm/llm/vertexai/index.mjs +89 -38
  18. package/dist/esm/llm/vertexai/index.mjs.map +1 -1
  19. package/dist/esm/tools/ToolNode.mjs +67 -6
  20. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  21. package/dist/esm/tools/ToolSearch.mjs +88 -12
  22. package/dist/esm/tools/ToolSearch.mjs.map +1 -1
  23. package/dist/esm/tools/search/keenable-scraper.mjs +27 -7
  24. package/dist/esm/tools/search/keenable-scraper.mjs.map +1 -1
  25. package/dist/types/tools/ToolNode.d.ts +7 -0
  26. package/dist/types/tools/search/keenable-scraper.d.ts +6 -0
  27. package/package.json +1 -1
  28. package/src/agents/AgentContext.ts +7 -11
  29. package/src/graphs/Graph.ts +19 -1
  30. package/src/llm/vertexai/index.ts +193 -67
  31. package/src/tools/ToolNode.ts +133 -11
  32. package/src/tools/ToolSearch.ts +161 -12
  33. package/src/tools/search/keenable-scraper.ts +62 -7
@@ -1 +1 @@
1
- {"version":3,"file":"keenable-scraper.mjs","names":[],"sources":["../../../../src/tools/search/keenable-scraper.ts"],"mappings":";;;AAIA,MAAM,kCAAkC;AAIxC,MAAM,yBAAyB;AAC/B,MAAM,4BAA4B;AAElC,IAAa,kBAAb,MAAsD;CACpD;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,SAAkC,CAAC,GAAG;EAChD,MAAM,cAAc,OAAO,UAAU,QAAQ,IAAI;EACjD,KAAK,SACH,eAAe,QAAQ,gBAAgB,KAAK,cAAc,KAAA;EAC5D,KAAK,SACH,OAAO,UACP,QAAQ,IAAI,uBACX,KAAK,UAAU,OACZ,yBACA;EACN,KAAK,UAAU,OAAO,WAAW;EACjC,KAAK,mBAAmB,OAAO,oBAAoB;EACnD,KAAK,YAAY,OAAO;EACxB,KAAK,aAAa,OAAO;EACzB,KAAK,SAAS,OAAO,UAAU,oBAAoB;CACrD;CAEA,eAA+C;EAI7C,MAAM,UAAkC,EACtC,oBAAoB,KAAK,iBAC3B;EACA,IAAI,KAAK,UAAU,MACjB,QAAQ,eAAe,KAAK;EAE9B,OAAO;CACT;CAEA,MAAM,UACJ,KACA,UAAmC,CAAC,GACS;EAC7C,IAAI,CAAC,OAAO,CAAC,IAAI,KAAK,GACpB,OAAO,CAAC,KAAK;GAAE,SAAS;GAAO,OAAO;EAAsB,CAAC;EAG/D,IAAI;GASF,MAAM,QAAO,MARU,MAAM,IAA2B,KAAK,QAAQ;IACnE,QAAQ,EAAE,IAAI;IACd,SAAS,KAAK,aAAa;IAC3B,SAAS,QAAQ,WAAW,KAAK;IACjC,WAAW,KAAK;IAChB,YAAY,KAAK;GACnB,CAAC,EAAA,CAEqB;GACtB,MAAM,UAAU,KAAK,WAAW;GAChC,IAAI,CAAC,SACH,OAAO,CACL,KACA;IAAE,SAAS;IAAO,OAAO;GAAqC,CAChE;GAGF,OAAO,CACL,KACA;IACE,SAAS;IACT,MAAM;KACJ;KACA,OAAO,KAAK;KACZ,aAAa,KAAK;KAClB,KAAK,KAAK,OAAO;IACnB;GACF,CACF;EACF,SAAS,OAAO;GAGd,OAAO,CACL,KACA;IACE,SAAS;IACT,OAAO,sCALT,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GAMrD,CACF;EACF;CACF;CAEA,MAAM,WACJ,MACA,UAAmC,CAAC,GACgB;EAEpD,OAAO,QAAQ,IAAI,KAAK,KAAK,QAAQ,KAAK,UAAU,KAAK,OAAO,CAAC,CAAC;CACpE;CAEA,eACE,UACoC;EACpC,IAAI,CAAC,SAAS,WAAW,CAAC,SAAS,MACjC,OAAO,CAAC,IAAI,KAAA,CAAS;EAIvB,OAAO,CAAC,SAAS,KAAK,SAAS,KAAA,CAAS;CAC1C;CAEA,gBAAgB,UAA6D;EAC3E,IAAI,CAAC,SAAS,WAAW,CAAC,SAAS,MACjC,OAAO,CAAC;EAEV,MAAM,WAAoC,CAAC;EAC3C,IAAI,SAAS,KAAK,SAAS,MACzB,SAAS,QAAQ,SAAS,KAAK;EAEjC,IAAI,SAAS,KAAK,eAAe,QAAQ,SAAS,KAAK,gBAAgB,IACrE,SAAS,cAAc,SAAS,KAAK;EAEvC,IAAI,SAAS,KAAK,OAAO,MACvB,SAAS,MAAM,SAAS,KAAK;EAE/B,OAAO;CACT;AACF;AAEA,MAAa,yBACX,SAAkC,CAAC,MACf;CACpB,OAAO,IAAI,gBAAgB,MAAM;AACnC"}
1
+ {"version":3,"file":"keenable-scraper.mjs","names":[],"sources":["../../../../src/tools/search/keenable-scraper.ts"],"mappings":";;;AAKA,MAAM,kCAAkC;AAIxC,MAAM,yBAAyB;AAC/B,MAAM,4BAA4B;AAIlC,MAAM,kCAAkC;AACxC,MAAM,kCAAkC;AACxC,MAAM,8BAA8B;AACpC,MAAM,2BAA2B;AAGjC,MAAM,4BAA4B,UAAuC;CACvE,IAAI,CAAC,MAAM,aAA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ACrE,SAAS,cAAc,SAAS,KAAK;EAEvC,IAAI,SAAS,KAAK,OAAO,MACvB,SAAS,MAAM,SAAS,KAAK;EAE/B,OAAO;CACT;AACF;AAEA,MAAa,yBACX,SAAkC,CAAC,MACf;CACpB,OAAO,IAAI,gBAAgB,MAAM;AACnC"}
@@ -301,6 +301,13 @@ export declare class ToolNode<T = any> extends RunnableCallable<T, T> {
301
301
  * langgraph's prebuilt ToolNode runtime exactly.
302
302
  */
303
303
  private invokeWithRuntime;
304
+ /**
305
+ * Whether a batch may run its code tools before its `read_file` calls, in two phases. Never when
306
+ * an approval could pause between the phases: LangGraph re-runs the whole node on resume and
307
+ * would execute the code again. Nor when result-altering or `PostToolBatch` hooks expect the
308
+ * batch as one unit: each dispatch fires batch hooks on its own partial set.
309
+ */
310
+ private canDeferReadFile;
304
311
  /** Only Graph's built-in subagent binding is allowed to call this seam. */
305
312
  prestartSubagent(call: ToolCall, attempt: string, config: RunnableConfig, capacity: number): void;
306
313
  /**
@@ -9,6 +9,12 @@ export declare class KeenableScraper implements t.BaseScraper {
9
9
  private httpsAgent?;
10
10
  constructor(config?: t.KeenableScraperConfig);
11
11
  private buildHeaders;
12
+ /**
13
+ * Fetches a page, retrying a 429 within the request's own timeout: every attempt and wait share
14
+ * one deadline, so retries never make a fetch outlast the timeout a caller already accepted. A
15
+ * timeout of 0 keeps meaning "no timeout" to axios, and then no deadline applies.
16
+ */
17
+ private fetchPage;
12
18
  scrapeUrl(url: string, options?: t.KeenableScrapeOptions): Promise<[string, t.KeenableScrapeResponse]>;
13
19
  scrapeUrls(urls: string[], options?: t.KeenableScrapeOptions): Promise<Array<[string, t.KeenableScrapeResponse]>>;
14
20
  extractContent(response: t.KeenableScrapeResponse): [string, undefined | t.References];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@librechat/agents",
3
- "version": "4.2.19",
3
+ "version": "4.2.20",
4
4
  "reova": {
5
5
  "enabled": true,
6
6
  "endpoint": "https://telemetry.reo.dev/data"
@@ -1103,10 +1103,10 @@ export class AgentContext {
1103
1103
 
1104
1104
  const promptCacheProvider = this.getPromptCacheProvider();
1105
1105
  const anchorsOnUser = this.anchorsPromptCacheOnUser(promptCacheProvider);
1106
+ /** Moved even without stable instructions: per-turn text left in the system message would sit
1107
+ * ahead of the history and invalidate the cached prefix on every turn. */
1106
1108
  const shouldMoveDynamicInstructions =
1107
- promptCacheProvider != null &&
1108
- (stableInstructions !== '' || anchorsOnUser) &&
1109
- dynamicInstructions !== '';
1109
+ promptCacheProvider != null && dynamicInstructions !== '';
1110
1110
  const systemMessage = this.buildSystemMessage({
1111
1111
  stableInstructions,
1112
1112
  dynamicInstructions,
@@ -1449,7 +1449,10 @@ export class AgentContext {
1449
1449
  promptCacheProvider: PromptCacheProvider | undefined;
1450
1450
  shouldMoveDynamicInstructions: boolean;
1451
1451
  }): SystemMessage | undefined {
1452
- if (!stableInstructions && !dynamicInstructions) {
1452
+ if (
1453
+ !stableInstructions &&
1454
+ (!dynamicInstructions || shouldMoveDynamicInstructions)
1455
+ ) {
1453
1456
  return undefined;
1454
1457
  }
1455
1458
 
@@ -1470,13 +1473,6 @@ export class AgentContext {
1470
1473
  return new SystemMessage({ content } as BaseMessageFields);
1471
1474
  }
1472
1475
 
1473
- if (promptCacheProvider === Providers.OPENROUTER && !stableInstructions) {
1474
- if (shouldMoveDynamicInstructions) {
1475
- return undefined;
1476
- }
1477
- return new SystemMessage(dynamicInstructions);
1478
- }
1479
-
1480
1476
  if (promptCacheProvider === Providers.OPENROUTER) {
1481
1477
  return new SystemMessage({
1482
1478
  content: [
@@ -3293,7 +3293,25 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
3293
3293
  'usage_metadata' in finalMessage &&
3294
3294
  finalMessage.usage_metadata != null
3295
3295
  ) {
3296
- return finalMessage.usage_metadata as Partial<UsageMetadata>;
3296
+ const usage = finalMessage.usage_metadata as Partial<UsageMetadata>;
3297
+ /** Long decode re-prefills each segment for billing, but only the first
3298
+ * prompt describes the conversation context. Cumulative cache details
3299
+ * must not be reused with that smaller input count. */
3300
+ const initial = (
3301
+ finalMessage.response_metadata as {
3302
+ initial_prompt_token_count?: number;
3303
+ }
3304
+ ).initial_prompt_token_count;
3305
+ if (typeof initial === 'number' && Number.isFinite(initial)) {
3306
+ const output = usage.output_tokens ?? 0;
3307
+ return {
3308
+ input_tokens: initial,
3309
+ output_tokens: output,
3310
+ total_tokens: initial + output,
3311
+ output_token_details: usage.output_token_details,
3312
+ };
3313
+ }
3314
+ return usage;
3297
3315
  }
3298
3316
  }
3299
3317
 
@@ -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(
@@ -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,