@librechat/agents 4.2.17 → 4.2.19

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 (64) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +63 -2
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/graphs/Graph.cjs +160 -10
  4. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  5. package/dist/cjs/llm/truncation.cjs +4 -0
  6. package/dist/cjs/llm/truncation.cjs.map +1 -1
  7. package/dist/cjs/main.cjs +2 -1
  8. package/dist/cjs/messages/cache.cjs +1 -0
  9. package/dist/cjs/messages/cache.cjs.map +1 -1
  10. package/dist/cjs/messages/core.cjs +20 -5
  11. package/dist/cjs/messages/core.cjs.map +1 -1
  12. package/dist/cjs/run.cjs +4 -0
  13. package/dist/cjs/run.cjs.map +1 -1
  14. package/dist/cjs/summarization/node.cjs +56 -30
  15. package/dist/cjs/summarization/node.cjs.map +1 -1
  16. package/dist/cjs/tools/ToolNode.cjs +20 -2
  17. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  18. package/dist/cjs/utils/toolContent.cjs +32 -16
  19. package/dist/cjs/utils/toolContent.cjs.map +1 -1
  20. package/dist/esm/agents/AgentContext.mjs +64 -3
  21. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  22. package/dist/esm/graphs/Graph.mjs +161 -11
  23. package/dist/esm/graphs/Graph.mjs.map +1 -1
  24. package/dist/esm/llm/truncation.mjs +4 -1
  25. package/dist/esm/llm/truncation.mjs.map +1 -1
  26. package/dist/esm/main.mjs +3 -3
  27. package/dist/esm/messages/cache.mjs +1 -1
  28. package/dist/esm/messages/cache.mjs.map +1 -1
  29. package/dist/esm/messages/core.mjs +22 -7
  30. package/dist/esm/messages/core.mjs.map +1 -1
  31. package/dist/esm/run.mjs +4 -0
  32. package/dist/esm/run.mjs.map +1 -1
  33. package/dist/esm/summarization/node.mjs +56 -31
  34. package/dist/esm/summarization/node.mjs.map +1 -1
  35. package/dist/esm/tools/ToolNode.mjs +20 -2
  36. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  37. package/dist/esm/utils/toolContent.mjs +32 -17
  38. package/dist/esm/utils/toolContent.mjs.map +1 -1
  39. package/dist/types/agents/AgentContext.d.ts +15 -0
  40. package/dist/types/graphs/Graph.d.ts +12 -2
  41. package/dist/types/llm/truncation.d.ts +8 -0
  42. package/dist/types/messages/cache.d.ts +9 -0
  43. package/dist/types/run.d.ts +2 -0
  44. package/dist/types/summarization/node.d.ts +5 -0
  45. package/dist/types/types/graph.d.ts +11 -1
  46. package/dist/types/types/run.d.ts +2 -0
  47. package/dist/types/types/stream.d.ts +2 -0
  48. package/dist/types/types/summarize.d.ts +7 -2
  49. package/dist/types/utils/toolContent.d.ts +6 -0
  50. package/package.json +1 -1
  51. package/src/agents/AgentContext.ts +137 -1
  52. package/src/graphs/Graph.ts +488 -180
  53. package/src/llm/truncation.ts +16 -0
  54. package/src/messages/cache.ts +1 -1
  55. package/src/messages/core.ts +37 -5
  56. package/src/run.ts +8 -0
  57. package/src/summarization/node.ts +75 -33
  58. package/src/tools/ToolNode.ts +67 -8
  59. package/src/types/graph.ts +11 -0
  60. package/src/types/run.ts +2 -0
  61. package/src/types/stream.ts +2 -0
  62. package/src/types/summarize.ts +11 -2
  63. package/src/utils/llmConfig.ts +1 -1
  64. package/src/utils/toolContent.ts +72 -21
@@ -5,12 +5,19 @@ import { tool } from '@langchain/core/tools';
5
5
  import { ToolNode } from '@langchain/langgraph/prebuilt';
6
6
  import { ContextOverflowError } from '@langchain/core/errors';
7
7
  import { Runnable, RunnableConfig } from '@langchain/core/runnables';
8
- import { START, END, StateGraph, Annotation } from '@langchain/langgraph';
9
8
  import {
10
9
  ToolMessage,
11
10
  HumanMessage,
12
11
  AIMessageChunk,
13
12
  } from '@langchain/core/messages';
13
+ import {
14
+ START,
15
+ END,
16
+ task,
17
+ getConfig,
18
+ StateGraph,
19
+ Annotation,
20
+ } from '@langchain/langgraph';
14
21
  import type {
15
22
  UsageMetadata,
16
23
  BaseMessage,
@@ -168,6 +175,10 @@ import {
168
175
  createToolResultGate,
169
176
  ToolResultProtectionError,
170
177
  } from '@/protection/toolResult';
178
+ import {
179
+ createSummarizeNode,
180
+ resolveSummaryRecencyWindow,
181
+ } from '@/summarization/node';
171
182
  import {
172
183
  appendCallbacks,
173
184
  findCallback,
@@ -203,7 +214,6 @@ import { buildSubagentToolParams } from '@/tools/SubagentTool';
203
214
  import { initializeLangfuseTracing } from '@/instrumentation';
204
215
  import { isRunStepResumeState } from '@/tools/runStepResume';
205
216
  import { resolveLocalToolsForBinding } from '@/tools/local';
206
- import { createSummarizeNode } from '@/summarization/node';
207
217
  import { getTruncationStopReason } from '@/llm/truncation';
208
218
  import { SearchCitations } from '@/tools/search/citations';
209
219
  import { createSchemaOnlyTools } from '@/tools/schema';
@@ -1376,6 +1386,15 @@ export abstract class Graph<
1376
1386
  }
1377
1387
  }
1378
1388
 
1389
+ type SummarizeNodeResult = Awaited<
1390
+ ReturnType<ReturnType<typeof createSummarizeNode>>
1391
+ >;
1392
+ type CheckpointedCompaction = {
1393
+ result?: SummarizeNodeResult;
1394
+ deferred: number | null;
1395
+ nextContentIndex?: number;
1396
+ };
1397
+
1379
1398
  export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
1380
1399
  readonly runName: string = STANDARD_GRAPH_RUN_NAME;
1381
1400
  overrideModel?: t.ChatModel;
@@ -1447,6 +1466,11 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
1447
1466
  * these on every streamed chunk event.
1448
1467
  */
1449
1468
  streamLimits: ResolvedStreamLimits;
1469
+ /** A single compaction claim per logical run, including Stop continuations. */
1470
+ private readonly claimQueuedCompaction?: t.ClaimQueuedCompaction;
1471
+ private queuedCompactionClaimed = false;
1472
+ private queuedCompactionSummaryRestored = false;
1473
+ private queuedCompactionDeferredCount: number | null = null;
1450
1474
  /** Default-off mandatory provider prose release. */
1451
1475
  providerTextProtection?: t.StandardGraphInput['providerTextProtection'];
1452
1476
  /** Default-off host inspection of selected tools' result text. */
@@ -1631,6 +1655,7 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
1631
1655
  subagentContext,
1632
1656
  onSubagentResolutionFailure,
1633
1657
  preemption,
1658
+ claimQueuedCompaction,
1634
1659
  streamLimits,
1635
1660
  providerTextProtection,
1636
1661
  toolResultProtection,
@@ -1663,6 +1688,14 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
1663
1688
  this.subagentContext = subagentContext;
1664
1689
  this.onSubagentResolutionFailure = onSubagentResolutionFailure;
1665
1690
  this.preemption = preemption;
1691
+ if (
1692
+ !this.subagentScope &&
1693
+ !this.isMultiAgentGraph() &&
1694
+ providerTextProtection == null &&
1695
+ (clientDelegatedToolNames?.length ?? 0) === 0
1696
+ ) {
1697
+ this.claimQueuedCompaction = claimQueuedCompaction;
1698
+ }
1666
1699
  this.streamLimits = resolveStreamLimits(streamLimits);
1667
1700
  if (providerTextProtection != null)
1668
1701
  validateProviderTextProtection(providerTextProtection);
@@ -1787,6 +1820,9 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
1787
1820
  /* Init */
1788
1821
 
1789
1822
  resetValues(keepContent?: boolean, checkpointScope?: string): void {
1823
+ this.queuedCompactionClaimed = false;
1824
+ this.queuedCompactionSummaryRestored = false;
1825
+ this.queuedCompactionDeferredCount = null;
1790
1826
  this.preparedSubagents.clear();
1791
1827
  this.resetSubagentCheckpointThreadIds();
1792
1828
  this.messages = [];
@@ -3451,6 +3487,70 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
3451
3487
  return { messages: [] };
3452
3488
  }
3453
3489
 
3490
+ private async takeQueuedCompaction(
3491
+ boundary: 'model' | 'terminal',
3492
+ agentContext: AgentContext,
3493
+ state: t.AgentSubgraphState,
3494
+ config?: RunnableConfig
3495
+ ): Promise<t.SummarizationNodeInput | undefined> {
3496
+ const claim = this.claimQueuedCompaction;
3497
+ const signal = config?.signal ?? this.signal;
3498
+ const deferred =
3499
+ state.queuedCompactionDeferredCount === undefined
3500
+ ? this.queuedCompactionDeferredCount
3501
+ : state.queuedCompactionDeferredCount;
3502
+ this.queuedCompactionDeferredCount = deferred;
3503
+ if (
3504
+ claim == null ||
3505
+ (this.queuedCompactionClaimed && deferred == null) ||
3506
+ agentContext.summarizeOnly === true ||
3507
+ agentContext.summarizationEnabled !== true ||
3508
+ this.preemptHaltReason != null ||
3509
+ this.preemptIncomplete ||
3510
+ this.outputTruncatedIncomplete ||
3511
+ signal?.aborted === true
3512
+ ) {
3513
+ return;
3514
+ }
3515
+ if (deferred === state.messages.length) return;
3516
+ try {
3517
+ if (deferred == null && !(await claim(boundary, signal))) return;
3518
+ } catch {
3519
+ emitAgentLog(
3520
+ config,
3521
+ 'warn',
3522
+ 'graph',
3523
+ 'Could not read the queued compaction request'
3524
+ );
3525
+ return;
3526
+ }
3527
+ signal?.throwIfAborted();
3528
+ this.queuedCompactionClaimed = true;
3529
+ if (agentContext.tokenCalculationPromise != null)
3530
+ await agentContext.tokenCalculationPromise;
3531
+ const windowMessages = agentContext.getProviderProjectedMessages(
3532
+ state.messages
3533
+ );
3534
+ const split = await resolveSummaryRecencyWindow(
3535
+ agentContext,
3536
+ windowMessages,
3537
+ true
3538
+ );
3539
+ signal?.throwIfAborted();
3540
+ if (split.head.length === 0 || split.tail.length === 0) {
3541
+ this.queuedCompactionDeferredCount = state.messages.length;
3542
+ return;
3543
+ }
3544
+ this.queuedCompactionDeferredCount = null;
3545
+ return {
3546
+ agentId: agentContext.agentId,
3547
+ remainingContextTokens: 0,
3548
+ reason: 'queued',
3549
+ windowMessages,
3550
+ queuedTailStartIndex: split.tailStartIndex,
3551
+ };
3552
+ }
3553
+
3454
3554
  createCallModel(agentId = 'default') {
3455
3555
  return async (
3456
3556
  state: t.AgentSubgraphState,
@@ -5443,8 +5543,10 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
5443
5543
  return buildRunStepStateAnnotation();
5444
5544
  }
5445
5545
 
5446
- createAgentNode(agentId: string): t.CompiledAgentWorfklow {
5447
- const getConfig = (): RunnableConfig | undefined => this.config;
5546
+ createAgentNode(
5547
+ agentId: string,
5548
+ summarizer?: ReturnType<typeof createSummarizeNode>
5549
+ ): t.CompiledAgentWorfklow {
5448
5550
  const agentContext = this.agentContexts.get(agentId);
5449
5551
  if (!agentContext) {
5450
5552
  throw new Error(`Agent context not found for agentId: ${agentId}`);
@@ -5751,6 +5853,11 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
5751
5853
  state.manualSummary.length > 0;
5752
5854
  return {
5753
5855
  ...result,
5856
+ ...(this.claimQueuedCompaction == null
5857
+ ? {}
5858
+ : {
5859
+ queuedCompactionDeferredCount: this.queuedCompactionDeferredCount,
5860
+ }),
5754
5861
  ...(clearsManualSummary ? { manualSummary: '' } : {}),
5755
5862
  runStepState: this.createRunStepResumeState(),
5756
5863
  };
@@ -5832,6 +5939,10 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
5832
5939
  },
5833
5940
  default: () => [],
5834
5941
  }),
5942
+ queuedCompactionApplied: Annotation<boolean | undefined>(),
5943
+ queuedCompactionSummary:
5944
+ Annotation<t.AgentSubgraphState['queuedCompactionSummary']>(),
5945
+ queuedCompactionDeferredCount: Annotation<number | null>(),
5835
5946
  summarizationRequest: Annotation<t.SummarizationNodeInput | undefined>({
5836
5947
  reducer: (
5837
5948
  _: t.SummarizationNodeInput | undefined,
@@ -5847,6 +5958,127 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
5847
5958
  handoffState: handoffStateAnnotation(),
5848
5959
  });
5849
5960
 
5961
+ const summarize = summarizer ?? this.createGraphSummarizer(agentContext);
5962
+ const checkpointedCompaction = async (
5963
+ state: t.AgentSubgraphState
5964
+ ): Promise<CheckpointedCompaction> => {
5965
+ const execution = { ran: false };
5966
+ const compact = task(
5967
+ 'queued_compaction',
5968
+ async (input: t.AgentSubgraphState) => {
5969
+ execution.ran = true;
5970
+ const result = await this.compactAtBoundary(
5971
+ 'model',
5972
+ input,
5973
+ agentContext,
5974
+ summarize,
5975
+ getConfig(),
5976
+ true
5977
+ );
5978
+ return {
5979
+ result,
5980
+ deferred: this.queuedCompactionDeferredCount,
5981
+ nextContentIndex:
5982
+ result == null ? undefined : this.nextContentIndex,
5983
+ };
5984
+ }
5985
+ );
5986
+ for (;;) {
5987
+ const outcome = await compact(state);
5988
+ // A replayed miss is not a claim: check the live queue before calling the model.
5989
+ if (execution.ran || outcome.result != null || outcome.deferred != null)
5990
+ return outcome;
5991
+ }
5992
+ };
5993
+ const restoreSummary = (
5994
+ summary: t.AgentSubgraphState['queuedCompactionSummary']
5995
+ ): void => {
5996
+ if (summary == null || this.queuedCompactionSummaryRestored) return;
5997
+ this.queuedCompactionClaimed = true;
5998
+ this.queuedCompactionSummaryRestored = true;
5999
+ if (
6000
+ agentContext.getSummaryText() !== summary.text ||
6001
+ !agentContext.hasPendingCompactionSummary()
6002
+ ) {
6003
+ agentContext.setSummary(summary.text, summary.tokenCount, {
6004
+ precedesMessages: summary.precedesMessages,
6005
+ });
6006
+ agentContext.rebuildTokenMapAfterSummarization({});
6007
+ if (summary.retainedMessageCount != null) {
6008
+ agentContext.markSummarizationTriggered(summary.retainedMessageCount);
6009
+ }
6010
+ }
6011
+ };
6012
+ const invokeModel = async (
6013
+ state: t.AgentSubgraphState,
6014
+ config?: RunnableConfig
6015
+ ): Promise<Partial<t.AgentSubgraphState>> => {
6016
+ if (this.claimQueuedCompaction == null) return callModel(state, config);
6017
+ restoreSummary(state.queuedCompactionSummary);
6018
+ let compacted;
6019
+ if (
6020
+ this.hasCompiledCheckpointer &&
6021
+ state.queuedCompactionSummary == null
6022
+ ) {
6023
+ /** Pregel saves the task result even when its enclosing answer call fails. */
6024
+ const { result, deferred, nextContentIndex } =
6025
+ await checkpointedCompaction(state);
6026
+ if (nextContentIndex != null) {
6027
+ this.nextContentIndex = Math.max(
6028
+ this.nextContentIndex,
6029
+ nextContentIndex
6030
+ );
6031
+ }
6032
+ this.queuedCompactionDeferredCount = deferred;
6033
+ if (result != null || deferred != null)
6034
+ this.queuedCompactionClaimed = true;
6035
+ compacted = result;
6036
+ } else {
6037
+ compacted = await this.compactAtBoundary(
6038
+ 'model',
6039
+ state,
6040
+ agentContext,
6041
+ summarize,
6042
+ config
6043
+ );
6044
+ }
6045
+ if (compacted?.messages == null) return callModel(state, config);
6046
+ restoreSummary(compacted.queuedCompactionSummary);
6047
+
6048
+ const messages = compacted.messages.slice(1);
6049
+ agentContext.invalidateProviderProjectionForMessageUpdates(
6050
+ compacted.messages
6051
+ );
6052
+ const result = await callModel({ ...state, messages }, config);
6053
+ return {
6054
+ ...compacted,
6055
+ ...result,
6056
+ messages:
6057
+ result.messages == null
6058
+ ? compacted.messages
6059
+ : [
6060
+ compacted.messages[0],
6061
+ ...messagesStateReducer(messages, result.messages),
6062
+ ],
6063
+ };
6064
+ };
6065
+ return new StateGraph(StateAnnotation)
6066
+ .addNode(agentNode, (state, config) =>
6067
+ invokeWithRunStepState(state, config, () => invokeModel(state, config))
6068
+ )
6069
+ .addNode(toolNode, callTools)
6070
+ .addNode(summarizeNode, summarize)
6071
+ .addEdge(START, agentNode)
6072
+ .addConditionalEdges(agentNode, routeMessage)
6073
+ .addEdge(summarizeNode, agentNode)
6074
+ .addEdge(toolNode, agentContext.toolEnd ? END : agentNode)
6075
+ .compile({ name: STANDARD_GRAPH_RUN_NAME });
6076
+ }
6077
+
6078
+ private createGraphSummarizer(
6079
+ agentContext: AgentContext
6080
+ ): ReturnType<typeof createSummarizeNode> {
6081
+ const getConfig = (): RunnableConfig | undefined => this.config;
5850
6082
  const readChargeCredits = ():
5851
6083
  | WeakMap<object, Map<string, number>>
5852
6084
  | undefined => this.streamLimitChargeCredits;
@@ -5862,182 +6094,209 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
5862
6094
  this.streamLimitChargeCredits = value;
5863
6095
  };
5864
6096
 
5865
- const workflow = new StateGraph(StateAnnotation)
5866
- .addNode(agentNode, (state, config) =>
5867
- invokeWithRunStepState(state, config, () => callModel(state, config))
5868
- )
5869
- .addNode(toolNode, callTools)
5870
- .addNode(
5871
- summarizeNode,
5872
- createSummarizeNode({
5873
- agentContext,
5874
- graph: {
5875
- contentData: this.contentData,
5876
- contentIndexMap: this.contentIndexMap,
5877
- get config() {
5878
- return getConfig();
5879
- },
5880
- runId: this.runId,
5881
- resolveAttachment: this.resolveAttachment,
5882
- isMultiAgent: this.isMultiAgentGraph(),
5883
- getSubagentExecutionContext: () => this.subagentExecutionContext,
5884
- hookRegistry: this.hookRegistry,
5885
- getToolsForBinding: (
5886
- provider: t.ProviderName,
5887
- clientOptions: t.ClientOptions | undefined
5888
- ): t.GraphTools | undefined =>
5889
- this.getPreparedToolsForBinding(
5890
- agentContext,
5891
- provider,
5892
- clientOptions
5893
- ),
5894
- /**
5895
- * Live references (both maps are cleared in place, never
5896
- * replaced), so summarization streams share the run's event
5897
- * budget accounting under their own generation key.
5898
- */
5899
- streamLimits: this.streamLimits,
5900
- streamDeltaEventCounts: this.streamDeltaEventCounts,
5901
- streamedToolCallArgTallies: this.streamedToolCallArgTallies,
5902
- /** Accessor pair, not a value copy: unlike the two maps above,
5903
- * the credit map is REPLACED by graph resets rather than cleared
5904
- * in place, and the guards' lazy `??=` must install onto the
5905
- * graph — a copy held here would survive resets and grow one
5906
- * attempt-stamped entry per compaction for a retained reused
5907
- * chunk object. */
5908
- get streamLimitChargeCredits() {
5909
- return readChargeCredits();
5910
- },
5911
- set streamLimitChargeCredits(
5912
- value: WeakMap<object, Map<string, number>> | undefined
5913
- ) {
5914
- writeChargeCredits(value);
5915
- },
5916
- /** Live epoch, so summary tallies are creation-tagged and the
5917
- * resetValues grace sweep treats them like model-attempt
5918
- * entries. */
5919
- get breakerEpoch(): number {
5920
- return readBreakerEpoch();
5921
- },
5922
- /** Accessor pair like the charge credits: summary attempts
5923
- * lease their generations on the GRAPH's active set, and the
5924
- * lazy `??=` in the lease helper must install there. */
5925
- get activeStreamLimitGenerations(): Set<string> | undefined {
5926
- return readActiveGenerations();
5927
- },
5928
- set activeStreamLimitGenerations(value: Set<string> | undefined) {
5929
- writeActiveGenerations(value);
5930
- },
5931
- /** Read per attempt: a sibling branch tripping the run breaker
5932
- * must also cancel in-flight summarization model calls. */
5933
- getBreakerSignal: (): AbortSignal => this.breakerAbort.signal,
5934
- /** The node captures this at entry so its own chunk handler's
5935
- * breach trips the run that STARTED the summarization, not a
5936
- * controller installed by a later reset. */
5937
- getBreakerController: (): AbortController => this.breakerAbort,
5938
- /** Captured at node entry and stamped into the summary attempt
5939
- * metadata, so the wire consumer epoch-gates old-run summary
5940
- * chunks exactly like model-attempt chunks. */
5941
- getBreakerEpoch: (): number => this.breakerEpoch,
5942
- dispatchRunStep: async (runStep, nodeConfig) => {
5943
- const resolvedConfig = nodeConfig ?? this.config;
5944
- if (runStep.agentId != null) {
5945
- const groupId = this.resolveParallelGroupId(
5946
- runStep.agentId,
5947
- resolvedConfig?.metadata
5948
- );
5949
- if (groupId != null) {
5950
- runStep.groupId = groupId;
5951
- }
5952
- }
5953
- runStep.status ??= 'in_progress';
5954
- await this.trackDispatchedRunStep(
5955
- runStep,
5956
- resolvedConfig?.metadata,
5957
- false
5958
- );
6097
+ return createSummarizeNode({
6098
+ agentContext,
6099
+ graph: {
6100
+ contentData: this.contentData,
6101
+ contentIndexMap: this.contentIndexMap,
6102
+ get config() {
6103
+ return getConfig();
6104
+ },
6105
+ runId: this.runId,
6106
+ resolveAttachment: this.resolveAttachment,
6107
+ isMultiAgent: this.isMultiAgentGraph(),
6108
+ getSubagentExecutionContext: () => this.subagentExecutionContext,
6109
+ hookRegistry: this.hookRegistry,
6110
+ getToolsForBinding: (
6111
+ provider: t.ProviderName,
6112
+ clientOptions: t.ClientOptions | undefined
6113
+ ): t.GraphTools | undefined =>
6114
+ this.getPreparedToolsForBinding(
6115
+ agentContext,
6116
+ provider,
6117
+ clientOptions
6118
+ ),
6119
+ /**
6120
+ * Live references (both maps are cleared in place, never
6121
+ * replaced), so summarization streams share the run's event
6122
+ * budget accounting under their own generation key.
6123
+ */
6124
+ streamLimits: this.streamLimits,
6125
+ streamDeltaEventCounts: this.streamDeltaEventCounts,
6126
+ streamedToolCallArgTallies: this.streamedToolCallArgTallies,
6127
+ /** Accessor pair, not a value copy: unlike the two maps above,
6128
+ * the credit map is REPLACED by graph resets rather than cleared
6129
+ * in place, and the guards' lazy `??=` must install onto the
6130
+ * graph — a copy held here would survive resets and grow one
6131
+ * attempt-stamped entry per compaction for a retained reused
6132
+ * chunk object. */
6133
+ get streamLimitChargeCredits() {
6134
+ return readChargeCredits();
6135
+ },
6136
+ set streamLimitChargeCredits(
6137
+ value: WeakMap<object, Map<string, number>> | undefined
6138
+ ) {
6139
+ writeChargeCredits(value);
6140
+ },
6141
+ /** Live epoch, so summary tallies are creation-tagged and the
6142
+ * resetValues grace sweep treats them like model-attempt
6143
+ * entries. */
6144
+ get breakerEpoch(): number {
6145
+ return readBreakerEpoch();
6146
+ },
6147
+ /** Accessor pair like the charge credits: summary attempts
6148
+ * lease their generations on the GRAPH's active set, and the
6149
+ * lazy `??=` in the lease helper must install there. */
6150
+ get activeStreamLimitGenerations(): Set<string> | undefined {
6151
+ return readActiveGenerations();
6152
+ },
6153
+ set activeStreamLimitGenerations(value: Set<string> | undefined) {
6154
+ writeActiveGenerations(value);
6155
+ },
6156
+ /** Read per attempt: a sibling branch tripping the run breaker
6157
+ * must also cancel in-flight summarization model calls. */
6158
+ getBreakerSignal: (): AbortSignal => this.breakerAbort.signal,
6159
+ /** The node captures this at entry so its own chunk handler's
6160
+ * breach trips the run that STARTED the summarization, not a
6161
+ * controller installed by a later reset. */
6162
+ getBreakerController: (): AbortController => this.breakerAbort,
6163
+ /** Captured at node entry and stamped into the summary attempt
6164
+ * metadata, so the wire consumer epoch-gates old-run summary
6165
+ * chunks exactly like model-attempt chunks. */
6166
+ getBreakerEpoch: (): number => this.breakerEpoch,
6167
+ dispatchRunStep: async (runStep, nodeConfig) => {
6168
+ const resolvedConfig = nodeConfig ?? this.config;
6169
+ if (runStep.agentId != null) {
6170
+ const groupId = this.resolveParallelGroupId(
6171
+ runStep.agentId,
6172
+ resolvedConfig?.metadata
6173
+ );
6174
+ if (groupId != null) {
6175
+ runStep.groupId = groupId;
6176
+ }
6177
+ }
6178
+ runStep.status ??= 'in_progress';
6179
+ await this.trackDispatchedRunStep(
6180
+ runStep,
6181
+ resolvedConfig?.metadata,
6182
+ false
6183
+ );
5959
6184
 
5960
- const handler = this.handlerRegistry?.getHandler(
5961
- GraphEvents.ON_RUN_STEP
5962
- );
5963
- if (handler) {
5964
- await handler.handle(
5965
- GraphEvents.ON_RUN_STEP,
5966
- runStep,
5967
- resolvedConfig?.configurable,
5968
- this
5969
- );
5970
- this.handlerDispatchedStepIds.add(runStep.id);
5971
- }
6185
+ const handler = this.handlerRegistry?.getHandler(
6186
+ GraphEvents.ON_RUN_STEP
6187
+ );
6188
+ if (handler) {
6189
+ await handler.handle(
6190
+ GraphEvents.ON_RUN_STEP,
6191
+ runStep,
6192
+ resolvedConfig?.configurable,
6193
+ this
6194
+ );
6195
+ this.handlerDispatchedStepIds.add(runStep.id);
6196
+ }
5972
6197
 
5973
- const unmarkHandlerDispatchedEvent = handler
5974
- ? this.markHandlerDispatchedEvent(
5975
- GraphEvents.ON_RUN_STEP,
5976
- runStep.id
5977
- )
5978
- : undefined;
5979
- try {
5980
- if (resolvedConfig) {
5981
- await safeDispatchCustomEvent(
5982
- GraphEvents.ON_RUN_STEP,
5983
- runStep,
5984
- resolvedConfig
5985
- );
5986
- }
5987
- } finally {
5988
- unmarkHandlerDispatchedEvent?.();
5989
- }
5990
- },
5991
- closeRunStep: async (
5992
- stepId: string,
5993
- status: Exclude<t.RunStepStatus, 'in_progress'>,
5994
- nodeConfig?: RunnableConfig
5995
- ) => {
5996
- await this.closeRunStep(stepId, status, {
5997
- metadata: (nodeConfig ?? this.config)?.metadata,
5998
- });
5999
- },
6000
- dispatchRunStepCompleted: async (
6001
- stepId: string,
6002
- result: t.StepCompleted,
6003
- nodeConfig?: RunnableConfig
6004
- ) => {
6005
- const resolvedConfig = nodeConfig ?? this.config;
6006
- const completedAt = Date.now();
6007
- const runStep = this.getRunStep(stepId);
6008
- const handler = this.handlerRegistry?.getHandler(
6009
- GraphEvents.ON_RUN_STEP_COMPLETED
6198
+ const unmarkHandlerDispatchedEvent = handler
6199
+ ? this.markHandlerDispatchedEvent(
6200
+ GraphEvents.ON_RUN_STEP,
6201
+ runStep.id
6202
+ )
6203
+ : undefined;
6204
+ try {
6205
+ if (resolvedConfig) {
6206
+ await safeDispatchCustomEvent(
6207
+ GraphEvents.ON_RUN_STEP,
6208
+ runStep,
6209
+ resolvedConfig
6010
6210
  );
6011
- if (handler) {
6012
- await handler.handle(
6013
- GraphEvents.ON_RUN_STEP_COMPLETED,
6014
- {
6015
- result: {
6016
- ...result,
6017
- id: stepId,
6018
- index: runStep?.index ?? 0,
6019
- completed_at: completedAt,
6020
- },
6021
- },
6022
- resolvedConfig?.configurable,
6023
- this
6024
- );
6025
- }
6026
- await this.recordStepCompletion(stepId, {
6027
- metadata: resolvedConfig?.metadata,
6028
- at: completedAt,
6029
- });
6030
- },
6031
- },
6032
- generateStepId: (stepKey: string) => this.generateStepId(stepKey),
6033
- })
6034
- )
6035
- .addEdge(START, agentNode)
6036
- .addConditionalEdges(agentNode, routeMessage)
6037
- .addEdge(summarizeNode, agentNode)
6038
- .addEdge(toolNode, agentContext.toolEnd ? END : agentNode);
6211
+ }
6212
+ } finally {
6213
+ unmarkHandlerDispatchedEvent?.();
6214
+ }
6215
+ },
6216
+ closeRunStep: async (
6217
+ stepId: string,
6218
+ status: Exclude<t.RunStepStatus, 'in_progress'>,
6219
+ nodeConfig?: RunnableConfig
6220
+ ) => {
6221
+ await this.closeRunStep(stepId, status, {
6222
+ metadata: (nodeConfig ?? this.config)?.metadata,
6223
+ });
6224
+ },
6225
+ dispatchRunStepCompleted: async (
6226
+ stepId: string,
6227
+ result: t.StepCompleted,
6228
+ nodeConfig?: RunnableConfig
6229
+ ) => {
6230
+ const resolvedConfig = nodeConfig ?? this.config;
6231
+ const completedAt = Date.now();
6232
+ const runStep = this.getRunStep(stepId);
6233
+ const handler = this.handlerRegistry?.getHandler(
6234
+ GraphEvents.ON_RUN_STEP_COMPLETED
6235
+ );
6236
+ if (handler) {
6237
+ await handler.handle(
6238
+ GraphEvents.ON_RUN_STEP_COMPLETED,
6239
+ {
6240
+ result: {
6241
+ ...result,
6242
+ id: stepId,
6243
+ index: runStep?.index ?? 0,
6244
+ completed_at: completedAt,
6245
+ },
6246
+ },
6247
+ resolvedConfig?.configurable,
6248
+ this
6249
+ );
6250
+ }
6251
+ await this.recordStepCompletion(stepId, {
6252
+ metadata: resolvedConfig?.metadata,
6253
+ at: completedAt,
6254
+ });
6255
+ },
6256
+ },
6257
+ generateStepId: (stepKey: string) => this.generateStepId(stepKey),
6258
+ });
6259
+ }
6039
6260
 
6040
- return workflow.compile({ name: STANDARD_GRAPH_RUN_NAME });
6261
+ /** A manual request shares the existing node's step budget, but keeps summary event identity. */
6262
+ private async compactAtBoundary(
6263
+ boundary: 'model' | 'terminal',
6264
+ state: t.AgentSubgraphState,
6265
+ agentContext: AgentContext,
6266
+ summarize: ReturnType<typeof createSummarizeNode>,
6267
+ config?: RunnableConfig,
6268
+ replayableTask = false
6269
+ ): Promise<
6270
+ Awaited<ReturnType<ReturnType<typeof createSummarizeNode>>> | undefined
6271
+ > {
6272
+ const request = await this.takeQueuedCompaction(
6273
+ boundary,
6274
+ agentContext,
6275
+ state,
6276
+ config
6277
+ );
6278
+ if (request == null) return;
6279
+ let callbacks = config?.callbacks;
6280
+ if (replayableTask && callbacks != null && !Array.isArray(callbacks)) {
6281
+ /** Nested task dispatch can inherit the same handlers twice. */
6282
+ callbacks = callbacks.copy();
6283
+ callbacks.handlers = [...new Set(callbacks.handlers)];
6284
+ callbacks.inheritableHandlers = [
6285
+ ...new Set(callbacks.inheritableHandlers),
6286
+ ];
6287
+ }
6288
+ return summarize(
6289
+ { messages: state.messages, summarizationRequest: request },
6290
+ {
6291
+ ...config,
6292
+ callbacks,
6293
+ signal: config?.signal ?? this.signal,
6294
+ metadata: {
6295
+ ...config?.metadata,
6296
+ langgraph_node: `${SUMMARIZE}${agentContext.agentId}`,
6297
+ },
6298
+ }
6299
+ );
6041
6300
  }
6042
6301
 
6043
6302
  createWorkflow(): t.CompiledStateWorkflow {
@@ -6048,7 +6307,13 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
6048
6307
  ) {
6049
6308
  throw new ProviderTextProtectionError('unsupported');
6050
6309
  }
6051
- const agentNode = this.createAgentNode(this.defaultAgentId);
6310
+ const agentContext = this.agentContexts.get(this.defaultAgentId);
6311
+ if (agentContext == null)
6312
+ throw new Error(
6313
+ `Agent context not found for agentId: ${this.defaultAgentId}`
6314
+ );
6315
+ const summarize = this.createGraphSummarizer(agentContext);
6316
+ const agentNode = this.createAgentNode(this.defaultAgentId, summarize);
6052
6317
  const StateAnnotation = Annotation.Root({
6053
6318
  messages: Annotation<BaseMessage[]>({
6054
6319
  reducer: (a, b) => {
@@ -6072,12 +6337,55 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
6072
6337
  const compactingAgentNode = async (
6073
6338
  state: t.AgentSubgraphState,
6074
6339
  config?: RunnableConfig
6075
- ): Promise<Partial<t.AgentSubgraphState>> =>
6076
- this.propagateManualCompaction(await agentNode.invoke(state, config));
6340
+ ): Promise<Partial<t.AgentSubgraphState>> => {
6341
+ let agentConfig = config;
6342
+ if (
6343
+ this.claimQueuedCompaction != null &&
6344
+ config?.configurable != null &&
6345
+ 'checkpoint_id' in config.configurable
6346
+ ) {
6347
+ const { checkpoint_id, ...configurable } = config.configurable;
6348
+ /** LangGraph treats the presence of this key as explicit replay, even when undefined. */
6349
+ if (checkpoint_id === undefined)
6350
+ agentConfig = { ...config, configurable };
6351
+ }
6352
+ let result = await agentNode.invoke(state, agentConfig);
6353
+ if (this.claimQueuedCompaction != null) {
6354
+ const terminal = await this.compactAtBoundary(
6355
+ 'terminal',
6356
+ result,
6357
+ agentContext,
6358
+ summarize,
6359
+ config
6360
+ );
6361
+ if (terminal != null) {
6362
+ result = {
6363
+ ...result,
6364
+ ...terminal,
6365
+ messages: terminal.messages?.slice(1) ?? result.messages,
6366
+ runStepState: this.createRunStepResumeState(),
6367
+ };
6368
+ }
6369
+ }
6370
+ if (result.queuedCompactionApplied !== true) {
6371
+ return this.propagateManualCompaction(result);
6372
+ }
6373
+ /** The retained suffix must replace the outer checkpoint's copy too. */
6374
+ const inputTailId = state.messages[this.startIndex - 1]?.id;
6375
+ this.startIndex =
6376
+ inputTailId == null
6377
+ ? 0
6378
+ : result.messages.findIndex((message) => message.id === inputTailId) +
6379
+ 1;
6380
+ return {
6381
+ ...result,
6382
+ messages: [createRemoveAllMessage(), ...result.messages],
6383
+ };
6384
+ };
6077
6385
  const workflow = new StateGraph(StateAnnotation)
6078
6386
  .addNode(
6079
6387
  this.defaultAgentId,
6080
- this.summarizeOnlyAgentId != null
6388
+ this.summarizeOnlyAgentId != null || this.claimQueuedCompaction != null
6081
6389
  ? compactingAgentNode
6082
6390
  : (agentNode as Runnable<
6083
6391
  t.AgentSubgraphState,