@librechat/agents 4.2.16 → 4.2.18

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 (73) 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 +152 -10
  4. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  5. package/dist/cjs/graphs/acceptedModelResponse.cjs +24 -15
  6. package/dist/cjs/graphs/acceptedModelResponse.cjs.map +1 -1
  7. package/dist/cjs/llm/truncation.cjs +4 -0
  8. package/dist/cjs/llm/truncation.cjs.map +1 -1
  9. package/dist/cjs/llm/vertexai/index.cjs +2 -3
  10. package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
  11. package/dist/cjs/main.cjs +2 -1
  12. package/dist/cjs/messages/cache.cjs +1 -0
  13. package/dist/cjs/messages/cache.cjs.map +1 -1
  14. package/dist/cjs/messages/core.cjs +20 -5
  15. package/dist/cjs/messages/core.cjs.map +1 -1
  16. package/dist/cjs/run.cjs +4 -0
  17. package/dist/cjs/run.cjs.map +1 -1
  18. package/dist/cjs/summarization/node.cjs +55 -30
  19. package/dist/cjs/summarization/node.cjs.map +1 -1
  20. package/dist/cjs/tools/ToolNode.cjs +20 -2
  21. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  22. package/dist/cjs/utils/toolContent.cjs +32 -16
  23. package/dist/cjs/utils/toolContent.cjs.map +1 -1
  24. package/dist/esm/agents/AgentContext.mjs +64 -3
  25. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  26. package/dist/esm/graphs/Graph.mjs +153 -11
  27. package/dist/esm/graphs/Graph.mjs.map +1 -1
  28. package/dist/esm/graphs/acceptedModelResponse.mjs +24 -15
  29. package/dist/esm/graphs/acceptedModelResponse.mjs.map +1 -1
  30. package/dist/esm/llm/truncation.mjs +4 -1
  31. package/dist/esm/llm/truncation.mjs.map +1 -1
  32. package/dist/esm/llm/vertexai/index.mjs +2 -3
  33. package/dist/esm/llm/vertexai/index.mjs.map +1 -1
  34. package/dist/esm/main.mjs +3 -3
  35. package/dist/esm/messages/cache.mjs +1 -1
  36. package/dist/esm/messages/cache.mjs.map +1 -1
  37. package/dist/esm/messages/core.mjs +22 -7
  38. package/dist/esm/messages/core.mjs.map +1 -1
  39. package/dist/esm/run.mjs +4 -0
  40. package/dist/esm/run.mjs.map +1 -1
  41. package/dist/esm/summarization/node.mjs +55 -31
  42. package/dist/esm/summarization/node.mjs.map +1 -1
  43. package/dist/esm/tools/ToolNode.mjs +20 -2
  44. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  45. package/dist/esm/utils/toolContent.mjs +32 -17
  46. package/dist/esm/utils/toolContent.mjs.map +1 -1
  47. package/dist/types/agents/AgentContext.d.ts +15 -0
  48. package/dist/types/graphs/Graph.d.ts +12 -2
  49. package/dist/types/llm/truncation.d.ts +8 -0
  50. package/dist/types/messages/cache.d.ts +9 -0
  51. package/dist/types/run.d.ts +2 -0
  52. package/dist/types/summarization/node.d.ts +5 -0
  53. package/dist/types/types/graph.d.ts +9 -1
  54. package/dist/types/types/run.d.ts +2 -0
  55. package/dist/types/types/stream.d.ts +2 -0
  56. package/dist/types/types/summarize.d.ts +7 -2
  57. package/dist/types/utils/toolContent.d.ts +6 -0
  58. package/package.json +1 -1
  59. package/src/agents/AgentContext.ts +137 -1
  60. package/src/graphs/Graph.ts +468 -180
  61. package/src/graphs/acceptedModelResponse.ts +31 -24
  62. package/src/llm/truncation.ts +16 -0
  63. package/src/llm/vertexai/index.ts +5 -4
  64. package/src/messages/cache.ts +1 -1
  65. package/src/messages/core.ts +37 -5
  66. package/src/run.ts +8 -0
  67. package/src/summarization/node.ts +74 -33
  68. package/src/tools/ToolNode.ts +67 -8
  69. package/src/types/graph.ts +9 -0
  70. package/src/types/run.ts +2 -0
  71. package/src/types/stream.ts +2 -0
  72. package/src/types/summarize.ts +11 -2
  73. 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';
@@ -1447,6 +1457,11 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
1447
1457
  * these on every streamed chunk event.
1448
1458
  */
1449
1459
  streamLimits: ResolvedStreamLimits;
1460
+ /** A single compaction claim per logical run, including Stop continuations. */
1461
+ private readonly claimQueuedCompaction?: t.ClaimQueuedCompaction;
1462
+ private queuedCompactionClaimed = false;
1463
+ private queuedCompactionSummaryRestored = false;
1464
+ private queuedCompactionDeferredCount: number | null = null;
1450
1465
  /** Default-off mandatory provider prose release. */
1451
1466
  providerTextProtection?: t.StandardGraphInput['providerTextProtection'];
1452
1467
  /** Default-off host inspection of selected tools' result text. */
@@ -1631,6 +1646,7 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
1631
1646
  subagentContext,
1632
1647
  onSubagentResolutionFailure,
1633
1648
  preemption,
1649
+ claimQueuedCompaction,
1634
1650
  streamLimits,
1635
1651
  providerTextProtection,
1636
1652
  toolResultProtection,
@@ -1663,6 +1679,14 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
1663
1679
  this.subagentContext = subagentContext;
1664
1680
  this.onSubagentResolutionFailure = onSubagentResolutionFailure;
1665
1681
  this.preemption = preemption;
1682
+ if (
1683
+ !this.subagentScope &&
1684
+ !this.isMultiAgentGraph() &&
1685
+ providerTextProtection == null &&
1686
+ (clientDelegatedToolNames?.length ?? 0) === 0
1687
+ ) {
1688
+ this.claimQueuedCompaction = claimQueuedCompaction;
1689
+ }
1666
1690
  this.streamLimits = resolveStreamLimits(streamLimits);
1667
1691
  if (providerTextProtection != null)
1668
1692
  validateProviderTextProtection(providerTextProtection);
@@ -1787,6 +1811,9 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
1787
1811
  /* Init */
1788
1812
 
1789
1813
  resetValues(keepContent?: boolean, checkpointScope?: string): void {
1814
+ this.queuedCompactionClaimed = false;
1815
+ this.queuedCompactionSummaryRestored = false;
1816
+ this.queuedCompactionDeferredCount = null;
1790
1817
  this.preparedSubagents.clear();
1791
1818
  this.resetSubagentCheckpointThreadIds();
1792
1819
  this.messages = [];
@@ -3451,6 +3478,70 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
3451
3478
  return { messages: [] };
3452
3479
  }
3453
3480
 
3481
+ private async takeQueuedCompaction(
3482
+ boundary: 'model' | 'terminal',
3483
+ agentContext: AgentContext,
3484
+ state: t.AgentSubgraphState,
3485
+ config?: RunnableConfig
3486
+ ): Promise<t.SummarizationNodeInput | undefined> {
3487
+ const claim = this.claimQueuedCompaction;
3488
+ const signal = config?.signal ?? this.signal;
3489
+ const deferred =
3490
+ state.queuedCompactionDeferredCount === undefined
3491
+ ? this.queuedCompactionDeferredCount
3492
+ : state.queuedCompactionDeferredCount;
3493
+ this.queuedCompactionDeferredCount = deferred;
3494
+ if (
3495
+ claim == null ||
3496
+ (this.queuedCompactionClaimed && deferred == null) ||
3497
+ agentContext.summarizeOnly === true ||
3498
+ agentContext.summarizationEnabled !== true ||
3499
+ this.preemptHaltReason != null ||
3500
+ this.preemptIncomplete ||
3501
+ this.outputTruncatedIncomplete ||
3502
+ signal?.aborted === true
3503
+ ) {
3504
+ return;
3505
+ }
3506
+ if (deferred === state.messages.length) return;
3507
+ try {
3508
+ if (deferred == null && !(await claim(boundary, signal))) return;
3509
+ } catch {
3510
+ emitAgentLog(
3511
+ config,
3512
+ 'warn',
3513
+ 'graph',
3514
+ 'Could not read the queued compaction request'
3515
+ );
3516
+ return;
3517
+ }
3518
+ signal?.throwIfAborted();
3519
+ this.queuedCompactionClaimed = true;
3520
+ if (agentContext.tokenCalculationPromise != null)
3521
+ await agentContext.tokenCalculationPromise;
3522
+ const windowMessages = agentContext.getProviderProjectedMessages(
3523
+ state.messages
3524
+ );
3525
+ const split = await resolveSummaryRecencyWindow(
3526
+ agentContext,
3527
+ windowMessages,
3528
+ true
3529
+ );
3530
+ signal?.throwIfAborted();
3531
+ if (split.head.length === 0 || split.tail.length === 0) {
3532
+ this.queuedCompactionDeferredCount = state.messages.length;
3533
+ return;
3534
+ }
3535
+ this.queuedCompactionDeferredCount = null;
3536
+ return {
3537
+ agentId: agentContext.agentId,
3538
+ remainingContextTokens: 0,
3539
+ reason: 'queued',
3540
+ windowMessages,
3541
+ queuedTailStartIndex: split.tailStartIndex,
3542
+ };
3543
+ }
3544
+
3454
3545
  createCallModel(agentId = 'default') {
3455
3546
  return async (
3456
3547
  state: t.AgentSubgraphState,
@@ -5443,8 +5534,10 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
5443
5534
  return buildRunStepStateAnnotation();
5444
5535
  }
5445
5536
 
5446
- createAgentNode(agentId: string): t.CompiledAgentWorfklow {
5447
- const getConfig = (): RunnableConfig | undefined => this.config;
5537
+ createAgentNode(
5538
+ agentId: string,
5539
+ summarizer?: ReturnType<typeof createSummarizeNode>
5540
+ ): t.CompiledAgentWorfklow {
5448
5541
  const agentContext = this.agentContexts.get(agentId);
5449
5542
  if (!agentContext) {
5450
5543
  throw new Error(`Agent context not found for agentId: ${agentId}`);
@@ -5751,6 +5844,11 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
5751
5844
  state.manualSummary.length > 0;
5752
5845
  return {
5753
5846
  ...result,
5847
+ ...(this.claimQueuedCompaction == null
5848
+ ? {}
5849
+ : {
5850
+ queuedCompactionDeferredCount: this.queuedCompactionDeferredCount,
5851
+ }),
5754
5852
  ...(clearsManualSummary ? { manualSummary: '' } : {}),
5755
5853
  runStepState: this.createRunStepResumeState(),
5756
5854
  };
@@ -5832,6 +5930,10 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
5832
5930
  },
5833
5931
  default: () => [],
5834
5932
  }),
5933
+ queuedCompactionApplied: Annotation<boolean | undefined>(),
5934
+ queuedCompactionSummary:
5935
+ Annotation<t.AgentSubgraphState['queuedCompactionSummary']>(),
5936
+ queuedCompactionDeferredCount: Annotation<number | null>(),
5835
5937
  summarizationRequest: Annotation<t.SummarizationNodeInput | undefined>({
5836
5938
  reducer: (
5837
5939
  _: t.SummarizationNodeInput | undefined,
@@ -5847,6 +5949,116 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
5847
5949
  handoffState: handoffStateAnnotation(),
5848
5950
  });
5849
5951
 
5952
+ const summarize = summarizer ?? this.createGraphSummarizer(agentContext);
5953
+ const checkpointedCompaction =
5954
+ this.hasCompiledCheckpointer && this.claimQueuedCompaction != null
5955
+ ? task('queued_compaction', async (state: t.AgentSubgraphState) => {
5956
+ const result = await this.compactAtBoundary(
5957
+ 'model',
5958
+ state,
5959
+ agentContext,
5960
+ summarize,
5961
+ getConfig(),
5962
+ true
5963
+ );
5964
+ return {
5965
+ result,
5966
+ deferred: this.queuedCompactionDeferredCount,
5967
+ nextContentIndex:
5968
+ result == null ? undefined : this.nextContentIndex,
5969
+ };
5970
+ })
5971
+ : undefined;
5972
+ const restoreSummary = (
5973
+ summary: t.AgentSubgraphState['queuedCompactionSummary'],
5974
+ count: number
5975
+ ): void => {
5976
+ if (summary == null || this.queuedCompactionSummaryRestored) return;
5977
+ this.queuedCompactionClaimed = true;
5978
+ this.queuedCompactionSummaryRestored = true;
5979
+ if (
5980
+ agentContext.getSummaryText() !== summary.text ||
5981
+ !agentContext.hasPendingCompactionSummary()
5982
+ ) {
5983
+ agentContext.setSummary(summary.text, summary.tokenCount, {
5984
+ precedesMessages: summary.precedesMessages,
5985
+ });
5986
+ agentContext.rebuildTokenMapAfterSummarization({});
5987
+ agentContext.markSummarizationTriggered(count);
5988
+ }
5989
+ };
5990
+ const invokeModel = async (
5991
+ state: t.AgentSubgraphState,
5992
+ config?: RunnableConfig
5993
+ ): Promise<Partial<t.AgentSubgraphState>> => {
5994
+ if (this.claimQueuedCompaction == null) return callModel(state, config);
5995
+ restoreSummary(state.queuedCompactionSummary, state.messages.length);
5996
+ let compacted;
5997
+ if (
5998
+ checkpointedCompaction != null &&
5999
+ state.queuedCompactionSummary == null
6000
+ ) {
6001
+ /** Pregel saves the task result even when its enclosing answer call fails. */
6002
+ const { result, deferred, nextContentIndex } =
6003
+ await checkpointedCompaction(state);
6004
+ if (nextContentIndex != null) {
6005
+ this.nextContentIndex = Math.max(
6006
+ this.nextContentIndex,
6007
+ nextContentIndex
6008
+ );
6009
+ }
6010
+ this.queuedCompactionDeferredCount = deferred;
6011
+ if (deferred != null) this.queuedCompactionClaimed = true;
6012
+ compacted = result;
6013
+ } else {
6014
+ compacted = await this.compactAtBoundary(
6015
+ 'model',
6016
+ state,
6017
+ agentContext,
6018
+ summarize,
6019
+ config
6020
+ );
6021
+ }
6022
+ if (compacted?.messages == null) return callModel(state, config);
6023
+ restoreSummary(
6024
+ compacted.queuedCompactionSummary,
6025
+ compacted.messages.length - 1
6026
+ );
6027
+
6028
+ const messages = compacted.messages.slice(1);
6029
+ agentContext.invalidateProviderProjectionForMessageUpdates(
6030
+ compacted.messages
6031
+ );
6032
+ const result = await callModel({ ...state, messages }, config);
6033
+ return {
6034
+ ...compacted,
6035
+ ...result,
6036
+ messages:
6037
+ result.messages == null
6038
+ ? compacted.messages
6039
+ : [
6040
+ compacted.messages[0],
6041
+ ...messagesStateReducer(messages, result.messages),
6042
+ ],
6043
+ };
6044
+ };
6045
+ return new StateGraph(StateAnnotation)
6046
+ .addNode(agentNode, (state, config) =>
6047
+ invokeWithRunStepState(state, config, () => invokeModel(state, config))
6048
+ )
6049
+ .addNode(toolNode, callTools)
6050
+ .addNode(summarizeNode, summarize)
6051
+ .addEdge(START, agentNode)
6052
+ .addConditionalEdges(agentNode, routeMessage)
6053
+ .addEdge(summarizeNode, agentNode)
6054
+ .addEdge(toolNode, agentContext.toolEnd ? END : agentNode)
6055
+ .compile({ name: STANDARD_GRAPH_RUN_NAME });
6056
+ }
6057
+
6058
+ private createGraphSummarizer(
6059
+ agentContext: AgentContext
6060
+ ): ReturnType<typeof createSummarizeNode> {
6061
+ const getConfig = (): RunnableConfig | undefined => this.config;
5850
6062
  const readChargeCredits = ():
5851
6063
  | WeakMap<object, Map<string, number>>
5852
6064
  | undefined => this.streamLimitChargeCredits;
@@ -5862,182 +6074,209 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
5862
6074
  this.streamLimitChargeCredits = value;
5863
6075
  };
5864
6076
 
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
- );
6077
+ return createSummarizeNode({
6078
+ agentContext,
6079
+ graph: {
6080
+ contentData: this.contentData,
6081
+ contentIndexMap: this.contentIndexMap,
6082
+ get config() {
6083
+ return getConfig();
6084
+ },
6085
+ runId: this.runId,
6086
+ resolveAttachment: this.resolveAttachment,
6087
+ isMultiAgent: this.isMultiAgentGraph(),
6088
+ getSubagentExecutionContext: () => this.subagentExecutionContext,
6089
+ hookRegistry: this.hookRegistry,
6090
+ getToolsForBinding: (
6091
+ provider: t.ProviderName,
6092
+ clientOptions: t.ClientOptions | undefined
6093
+ ): t.GraphTools | undefined =>
6094
+ this.getPreparedToolsForBinding(
6095
+ agentContext,
6096
+ provider,
6097
+ clientOptions
6098
+ ),
6099
+ /**
6100
+ * Live references (both maps are cleared in place, never
6101
+ * replaced), so summarization streams share the run's event
6102
+ * budget accounting under their own generation key.
6103
+ */
6104
+ streamLimits: this.streamLimits,
6105
+ streamDeltaEventCounts: this.streamDeltaEventCounts,
6106
+ streamedToolCallArgTallies: this.streamedToolCallArgTallies,
6107
+ /** Accessor pair, not a value copy: unlike the two maps above,
6108
+ * the credit map is REPLACED by graph resets rather than cleared
6109
+ * in place, and the guards' lazy `??=` must install onto the
6110
+ * graph — a copy held here would survive resets and grow one
6111
+ * attempt-stamped entry per compaction for a retained reused
6112
+ * chunk object. */
6113
+ get streamLimitChargeCredits() {
6114
+ return readChargeCredits();
6115
+ },
6116
+ set streamLimitChargeCredits(
6117
+ value: WeakMap<object, Map<string, number>> | undefined
6118
+ ) {
6119
+ writeChargeCredits(value);
6120
+ },
6121
+ /** Live epoch, so summary tallies are creation-tagged and the
6122
+ * resetValues grace sweep treats them like model-attempt
6123
+ * entries. */
6124
+ get breakerEpoch(): number {
6125
+ return readBreakerEpoch();
6126
+ },
6127
+ /** Accessor pair like the charge credits: summary attempts
6128
+ * lease their generations on the GRAPH's active set, and the
6129
+ * lazy `??=` in the lease helper must install there. */
6130
+ get activeStreamLimitGenerations(): Set<string> | undefined {
6131
+ return readActiveGenerations();
6132
+ },
6133
+ set activeStreamLimitGenerations(value: Set<string> | undefined) {
6134
+ writeActiveGenerations(value);
6135
+ },
6136
+ /** Read per attempt: a sibling branch tripping the run breaker
6137
+ * must also cancel in-flight summarization model calls. */
6138
+ getBreakerSignal: (): AbortSignal => this.breakerAbort.signal,
6139
+ /** The node captures this at entry so its own chunk handler's
6140
+ * breach trips the run that STARTED the summarization, not a
6141
+ * controller installed by a later reset. */
6142
+ getBreakerController: (): AbortController => this.breakerAbort,
6143
+ /** Captured at node entry and stamped into the summary attempt
6144
+ * metadata, so the wire consumer epoch-gates old-run summary
6145
+ * chunks exactly like model-attempt chunks. */
6146
+ getBreakerEpoch: (): number => this.breakerEpoch,
6147
+ dispatchRunStep: async (runStep, nodeConfig) => {
6148
+ const resolvedConfig = nodeConfig ?? this.config;
6149
+ if (runStep.agentId != null) {
6150
+ const groupId = this.resolveParallelGroupId(
6151
+ runStep.agentId,
6152
+ resolvedConfig?.metadata
6153
+ );
6154
+ if (groupId != null) {
6155
+ runStep.groupId = groupId;
6156
+ }
6157
+ }
6158
+ runStep.status ??= 'in_progress';
6159
+ await this.trackDispatchedRunStep(
6160
+ runStep,
6161
+ resolvedConfig?.metadata,
6162
+ false
6163
+ );
5959
6164
 
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
- }
6165
+ const handler = this.handlerRegistry?.getHandler(
6166
+ GraphEvents.ON_RUN_STEP
6167
+ );
6168
+ if (handler) {
6169
+ await handler.handle(
6170
+ GraphEvents.ON_RUN_STEP,
6171
+ runStep,
6172
+ resolvedConfig?.configurable,
6173
+ this
6174
+ );
6175
+ this.handlerDispatchedStepIds.add(runStep.id);
6176
+ }
5972
6177
 
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
6178
+ const unmarkHandlerDispatchedEvent = handler
6179
+ ? this.markHandlerDispatchedEvent(
6180
+ GraphEvents.ON_RUN_STEP,
6181
+ runStep.id
6182
+ )
6183
+ : undefined;
6184
+ try {
6185
+ if (resolvedConfig) {
6186
+ await safeDispatchCustomEvent(
6187
+ GraphEvents.ON_RUN_STEP,
6188
+ runStep,
6189
+ resolvedConfig
6010
6190
  );
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);
6191
+ }
6192
+ } finally {
6193
+ unmarkHandlerDispatchedEvent?.();
6194
+ }
6195
+ },
6196
+ closeRunStep: async (
6197
+ stepId: string,
6198
+ status: Exclude<t.RunStepStatus, 'in_progress'>,
6199
+ nodeConfig?: RunnableConfig
6200
+ ) => {
6201
+ await this.closeRunStep(stepId, status, {
6202
+ metadata: (nodeConfig ?? this.config)?.metadata,
6203
+ });
6204
+ },
6205
+ dispatchRunStepCompleted: async (
6206
+ stepId: string,
6207
+ result: t.StepCompleted,
6208
+ nodeConfig?: RunnableConfig
6209
+ ) => {
6210
+ const resolvedConfig = nodeConfig ?? this.config;
6211
+ const completedAt = Date.now();
6212
+ const runStep = this.getRunStep(stepId);
6213
+ const handler = this.handlerRegistry?.getHandler(
6214
+ GraphEvents.ON_RUN_STEP_COMPLETED
6215
+ );
6216
+ if (handler) {
6217
+ await handler.handle(
6218
+ GraphEvents.ON_RUN_STEP_COMPLETED,
6219
+ {
6220
+ result: {
6221
+ ...result,
6222
+ id: stepId,
6223
+ index: runStep?.index ?? 0,
6224
+ completed_at: completedAt,
6225
+ },
6226
+ },
6227
+ resolvedConfig?.configurable,
6228
+ this
6229
+ );
6230
+ }
6231
+ await this.recordStepCompletion(stepId, {
6232
+ metadata: resolvedConfig?.metadata,
6233
+ at: completedAt,
6234
+ });
6235
+ },
6236
+ },
6237
+ generateStepId: (stepKey: string) => this.generateStepId(stepKey),
6238
+ });
6239
+ }
6039
6240
 
6040
- return workflow.compile({ name: STANDARD_GRAPH_RUN_NAME });
6241
+ /** A manual request shares the existing node's step budget, but keeps summary event identity. */
6242
+ private async compactAtBoundary(
6243
+ boundary: 'model' | 'terminal',
6244
+ state: t.AgentSubgraphState,
6245
+ agentContext: AgentContext,
6246
+ summarize: ReturnType<typeof createSummarizeNode>,
6247
+ config?: RunnableConfig,
6248
+ replayableTask = false
6249
+ ): Promise<
6250
+ Awaited<ReturnType<ReturnType<typeof createSummarizeNode>>> | undefined
6251
+ > {
6252
+ const request = await this.takeQueuedCompaction(
6253
+ boundary,
6254
+ agentContext,
6255
+ state,
6256
+ config
6257
+ );
6258
+ if (request == null) return;
6259
+ let callbacks = config?.callbacks;
6260
+ if (replayableTask && callbacks != null && !Array.isArray(callbacks)) {
6261
+ /** Nested task dispatch can inherit the same handlers twice. */
6262
+ callbacks = callbacks.copy();
6263
+ callbacks.handlers = [...new Set(callbacks.handlers)];
6264
+ callbacks.inheritableHandlers = [
6265
+ ...new Set(callbacks.inheritableHandlers),
6266
+ ];
6267
+ }
6268
+ return summarize(
6269
+ { messages: state.messages, summarizationRequest: request },
6270
+ {
6271
+ ...config,
6272
+ callbacks,
6273
+ signal: config?.signal ?? this.signal,
6274
+ metadata: {
6275
+ ...config?.metadata,
6276
+ langgraph_node: `${SUMMARIZE}${agentContext.agentId}`,
6277
+ },
6278
+ }
6279
+ );
6041
6280
  }
6042
6281
 
6043
6282
  createWorkflow(): t.CompiledStateWorkflow {
@@ -6048,7 +6287,13 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
6048
6287
  ) {
6049
6288
  throw new ProviderTextProtectionError('unsupported');
6050
6289
  }
6051
- const agentNode = this.createAgentNode(this.defaultAgentId);
6290
+ const agentContext = this.agentContexts.get(this.defaultAgentId);
6291
+ if (agentContext == null)
6292
+ throw new Error(
6293
+ `Agent context not found for agentId: ${this.defaultAgentId}`
6294
+ );
6295
+ const summarize = this.createGraphSummarizer(agentContext);
6296
+ const agentNode = this.createAgentNode(this.defaultAgentId, summarize);
6052
6297
  const StateAnnotation = Annotation.Root({
6053
6298
  messages: Annotation<BaseMessage[]>({
6054
6299
  reducer: (a, b) => {
@@ -6072,12 +6317,55 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
6072
6317
  const compactingAgentNode = async (
6073
6318
  state: t.AgentSubgraphState,
6074
6319
  config?: RunnableConfig
6075
- ): Promise<Partial<t.AgentSubgraphState>> =>
6076
- this.propagateManualCompaction(await agentNode.invoke(state, config));
6320
+ ): Promise<Partial<t.AgentSubgraphState>> => {
6321
+ let agentConfig = config;
6322
+ if (
6323
+ this.claimQueuedCompaction != null &&
6324
+ config?.configurable != null &&
6325
+ 'checkpoint_id' in config.configurable
6326
+ ) {
6327
+ const { checkpoint_id, ...configurable } = config.configurable;
6328
+ /** LangGraph treats the presence of this key as explicit replay, even when undefined. */
6329
+ if (checkpoint_id === undefined)
6330
+ agentConfig = { ...config, configurable };
6331
+ }
6332
+ let result = await agentNode.invoke(state, agentConfig);
6333
+ if (this.claimQueuedCompaction != null) {
6334
+ const terminal = await this.compactAtBoundary(
6335
+ 'terminal',
6336
+ result,
6337
+ agentContext,
6338
+ summarize,
6339
+ config
6340
+ );
6341
+ if (terminal != null) {
6342
+ result = {
6343
+ ...result,
6344
+ ...terminal,
6345
+ messages: terminal.messages?.slice(1) ?? result.messages,
6346
+ runStepState: this.createRunStepResumeState(),
6347
+ };
6348
+ }
6349
+ }
6350
+ if (result.queuedCompactionApplied !== true) {
6351
+ return this.propagateManualCompaction(result);
6352
+ }
6353
+ /** The retained suffix must replace the outer checkpoint's copy too. */
6354
+ const inputTailId = state.messages[this.startIndex - 1]?.id;
6355
+ this.startIndex =
6356
+ inputTailId == null
6357
+ ? 0
6358
+ : result.messages.findIndex((message) => message.id === inputTailId) +
6359
+ 1;
6360
+ return {
6361
+ ...result,
6362
+ messages: [createRemoveAllMessage(), ...result.messages],
6363
+ };
6364
+ };
6077
6365
  const workflow = new StateGraph(StateAnnotation)
6078
6366
  .addNode(
6079
6367
  this.defaultAgentId,
6080
- this.summarizeOnlyAgentId != null
6368
+ this.summarizeOnlyAgentId != null || this.claimQueuedCompaction != null
6081
6369
  ? compactingAgentNode
6082
6370
  : (agentNode as Runnable<
6083
6371
  t.AgentSubgraphState,