@librechat/agents 3.3.4 → 3.3.5

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 (159) hide show
  1. package/dist/cjs/common/constants.cjs +21 -0
  2. package/dist/cjs/common/constants.cjs.map +1 -1
  3. package/dist/cjs/events.cjs +10 -1
  4. package/dist/cjs/events.cjs.map +1 -1
  5. package/dist/cjs/graphs/Graph.cjs +456 -7
  6. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  7. package/dist/cjs/hooks/HookRegistry.cjs +25 -0
  8. package/dist/cjs/hooks/HookRegistry.cjs.map +1 -1
  9. package/dist/cjs/hooks/index.cjs +12 -0
  10. package/dist/cjs/hooks/index.cjs.map +1 -1
  11. package/dist/cjs/hooks/types.cjs +1 -0
  12. package/dist/cjs/hooks/types.cjs.map +1 -1
  13. package/dist/cjs/langfuse.cjs +8 -0
  14. package/dist/cjs/langfuse.cjs.map +1 -1
  15. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +1 -3
  16. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -1
  17. package/dist/cjs/llm/invoke.cjs +268 -3
  18. package/dist/cjs/llm/invoke.cjs.map +1 -1
  19. package/dist/cjs/llm/preempt.cjs +132 -0
  20. package/dist/cjs/llm/preempt.cjs.map +1 -0
  21. package/dist/cjs/main.cjs +17 -3
  22. package/dist/cjs/messages/alternation.cjs +92 -0
  23. package/dist/cjs/messages/alternation.cjs.map +1 -0
  24. package/dist/cjs/messages/format.cjs +72 -0
  25. package/dist/cjs/messages/format.cjs.map +1 -1
  26. package/dist/cjs/messages/handoffCue.cjs +63 -0
  27. package/dist/cjs/messages/handoffCue.cjs.map +1 -0
  28. package/dist/cjs/messages/index.cjs +3 -0
  29. package/dist/cjs/messages/injected.cjs +60 -0
  30. package/dist/cjs/messages/injected.cjs.map +1 -0
  31. package/dist/cjs/run.cjs +80 -7
  32. package/dist/cjs/run.cjs.map +1 -1
  33. package/dist/cjs/session/handlers.cjs +18 -9
  34. package/dist/cjs/session/handlers.cjs.map +1 -1
  35. package/dist/cjs/stream.cjs +28 -7
  36. package/dist/cjs/stream.cjs.map +1 -1
  37. package/dist/cjs/tools/ToolNode.cjs +3 -23
  38. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  39. package/dist/cjs/tools/search/keenable-scraper.cjs +90 -0
  40. package/dist/cjs/tools/search/keenable-scraper.cjs.map +1 -0
  41. package/dist/cjs/tools/search/tool.cjs +9 -1
  42. package/dist/cjs/tools/search/tool.cjs.map +1 -1
  43. package/dist/esm/common/constants.mjs +19 -1
  44. package/dist/esm/common/constants.mjs.map +1 -1
  45. package/dist/esm/events.mjs +10 -1
  46. package/dist/esm/events.mjs.map +1 -1
  47. package/dist/esm/graphs/Graph.mjs +455 -6
  48. package/dist/esm/graphs/Graph.mjs.map +1 -1
  49. package/dist/esm/hooks/HookRegistry.mjs +25 -0
  50. package/dist/esm/hooks/HookRegistry.mjs.map +1 -1
  51. package/dist/esm/hooks/index.mjs +12 -1
  52. package/dist/esm/hooks/index.mjs.map +1 -1
  53. package/dist/esm/hooks/types.mjs +1 -0
  54. package/dist/esm/hooks/types.mjs.map +1 -1
  55. package/dist/esm/langfuse.mjs +9 -1
  56. package/dist/esm/langfuse.mjs.map +1 -1
  57. package/dist/esm/llm/bedrock/utils/message_inputs.mjs +1 -3
  58. package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -1
  59. package/dist/esm/llm/invoke.mjs +270 -6
  60. package/dist/esm/llm/invoke.mjs.map +1 -1
  61. package/dist/esm/llm/preempt.mjs +131 -0
  62. package/dist/esm/llm/preempt.mjs.map +1 -0
  63. package/dist/esm/main.mjs +8 -5
  64. package/dist/esm/messages/alternation.mjs +91 -0
  65. package/dist/esm/messages/alternation.mjs.map +1 -0
  66. package/dist/esm/messages/format.mjs +72 -0
  67. package/dist/esm/messages/format.mjs.map +1 -1
  68. package/dist/esm/messages/handoffCue.mjs +61 -0
  69. package/dist/esm/messages/handoffCue.mjs.map +1 -0
  70. package/dist/esm/messages/index.mjs +3 -0
  71. package/dist/esm/messages/injected.mjs +60 -0
  72. package/dist/esm/messages/injected.mjs.map +1 -0
  73. package/dist/esm/run.mjs +80 -7
  74. package/dist/esm/run.mjs.map +1 -1
  75. package/dist/esm/session/handlers.mjs +19 -10
  76. package/dist/esm/session/handlers.mjs.map +1 -1
  77. package/dist/esm/stream.mjs +27 -8
  78. package/dist/esm/stream.mjs.map +1 -1
  79. package/dist/esm/tools/ToolNode.mjs +3 -23
  80. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  81. package/dist/esm/tools/search/keenable-scraper.mjs +88 -0
  82. package/dist/esm/tools/search/keenable-scraper.mjs.map +1 -0
  83. package/dist/esm/tools/search/tool.mjs +9 -1
  84. package/dist/esm/tools/search/tool.mjs.map +1 -1
  85. package/dist/types/common/constants.d.ts +18 -0
  86. package/dist/types/graphs/Graph.d.ts +138 -1
  87. package/dist/types/hooks/HookRegistry.d.ts +15 -0
  88. package/dist/types/hooks/index.d.ts +12 -1
  89. package/dist/types/hooks/types.d.ts +45 -6
  90. package/dist/types/index.d.ts +1 -1
  91. package/dist/types/llm/invoke.d.ts +7 -0
  92. package/dist/types/llm/preempt.d.ts +40 -0
  93. package/dist/types/messages/alternation.d.ts +23 -0
  94. package/dist/types/messages/handoffCue.d.ts +40 -0
  95. package/dist/types/messages/index.d.ts +3 -0
  96. package/dist/types/messages/injected.d.ts +3 -0
  97. package/dist/types/run.d.ts +7 -0
  98. package/dist/types/stream.d.ts +14 -0
  99. package/dist/types/tools/ToolNode.d.ts +0 -7
  100. package/dist/types/tools/search/keenable-scraper.d.ts +15 -0
  101. package/dist/types/tools/search/types.d.ts +31 -2
  102. package/dist/types/types/graph.d.ts +8 -1
  103. package/dist/types/types/run.d.ts +65 -0
  104. package/dist/types/types/stream.d.ts +0 -25
  105. package/package.json +1 -1
  106. package/src/{splitStream.test.ts → aggregator.test.ts} +59 -666
  107. package/src/common/constants.ts +21 -0
  108. package/src/events.ts +15 -1
  109. package/src/graphs/Graph.ts +568 -3
  110. package/src/graphs/__tests__/Graph.contextOverflow.test.ts +18 -7
  111. package/src/graphs/__tests__/Graph.preemptSignal.test.ts +126 -0
  112. package/src/hooks/HookRegistry.ts +40 -0
  113. package/src/hooks/__tests__/preemptBoundary.test.ts +152 -0
  114. package/src/hooks/index.ts +16 -2
  115. package/src/hooks/types.ts +47 -3
  116. package/src/index.ts +1 -1
  117. package/src/langfuse.ts +26 -1
  118. package/src/llm/bedrock/utils/message_inputs.test.ts +82 -0
  119. package/src/llm/bedrock/utils/message_inputs.ts +14 -11
  120. package/src/llm/bedrock/utils/toolResultCachePoint.test.ts +15 -0
  121. package/src/llm/invoke.alternation.test.ts +87 -0
  122. package/src/llm/invoke.handoffCue.test.ts +112 -0
  123. package/src/llm/invoke.ts +417 -8
  124. package/src/llm/preempt.test.ts +323 -0
  125. package/src/llm/preempt.ts +178 -0
  126. package/src/messages/alternation.test.ts +212 -0
  127. package/src/messages/alternation.ts +112 -0
  128. package/src/messages/format.ts +91 -0
  129. package/src/messages/formatAgentMessages.steer.test.ts +267 -0
  130. package/src/messages/handoffCue.test.ts +96 -0
  131. package/src/messages/handoffCue.ts +78 -0
  132. package/src/messages/index.ts +3 -0
  133. package/src/messages/injected.test.ts +90 -0
  134. package/src/messages/injected.ts +74 -0
  135. package/src/run.ts +91 -6
  136. package/src/scripts/preempt-probe.ts +330 -0
  137. package/src/scripts/preempt-scenarios.ts +388 -0
  138. package/src/session/handlers.ts +32 -12
  139. package/src/specs/handoffCue.test.ts +165 -0
  140. package/src/specs/langfuse-callbacks.test.ts +352 -2
  141. package/src/specs/preemptSeal.test.ts +309 -0
  142. package/src/stream.dispatch.test.ts +63 -0
  143. package/src/stream.ts +36 -8
  144. package/src/tools/ToolNode.ts +3 -31
  145. package/src/tools/search/keenable-scraper.test.ts +153 -0
  146. package/src/tools/search/keenable-scraper.ts +137 -0
  147. package/src/tools/search/tool.ts +13 -2
  148. package/src/tools/search/types.ts +50 -3
  149. package/src/types/graph.ts +12 -1
  150. package/src/types/run.ts +67 -0
  151. package/src/types/stream.ts +0 -41
  152. package/dist/cjs/splitStream.cjs +0 -151
  153. package/dist/cjs/splitStream.cjs.map +0 -1
  154. package/dist/esm/splitStream.mjs +0 -150
  155. package/dist/esm/splitStream.mjs.map +0 -1
  156. package/dist/types/mockStream.d.ts +0 -32
  157. package/dist/types/splitStream.d.ts +0 -37
  158. package/src/mockStream.ts +0 -99
  159. package/src/splitStream.ts +0 -234
@@ -47,6 +47,11 @@ import {
47
47
  partitionAndMarkAnthropicToolCache,
48
48
  DEFAULT_RETAIN_RECENT_TURNS,
49
49
  splitAtRecencyBoundary,
50
+ convertInjectedMessages,
51
+ coalesceAdjacentUserTurns,
52
+ strictAlternationProviders,
53
+ appendPredecessorHandoffCue,
54
+ removePredecessorHandoffCue,
50
55
  } from '@/messages';
51
56
  import {
52
57
  resetIfNotEmpty,
@@ -64,7 +69,9 @@ import {
64
69
  getFallbackErrorContext,
65
70
  getFallbackOverflowCandidates,
66
71
  projectMessagesForProvider,
72
+ resolveServingModelId,
67
73
  } from '@/llm/invoke';
74
+ import { v4 } from 'uuid';
68
75
  import {
69
76
  createLangfuseHandler,
70
77
  createLangfuseTraceMetadata,
@@ -81,6 +88,7 @@ import {
81
88
  getToolContentCharLength,
82
89
  serializeToolContentBounded,
83
90
  } from '@/utils/toolContent';
91
+ import { resolveMaxSeals } from '@/llm/preempt';
84
92
  import {
85
93
  Constants,
86
94
  GraphNodeKeys,
@@ -88,6 +96,7 @@ import {
88
96
  GraphEvents,
89
97
  Providers,
90
98
  StepTypes,
99
+ PREEMPT_BOUNDARY_HOOK_TIMEOUT_MS,
91
100
  } from '@/common';
92
101
  import {
93
102
  annotateMessagesForLLM,
@@ -125,9 +134,41 @@ import { isThinkingEnabled } from '@/llm/request';
125
134
  import { initializeModel } from '@/llm/init';
126
135
  import { HandlerRegistry } from '@/events';
127
136
  import { ChatOpenAI } from '@/llm/openai';
137
+ import { executeHooks } from '@/hooks';
128
138
 
129
139
  const { AGENT, TOOLS, SUMMARIZE } = GraphNodeKeys;
130
140
 
141
+ /** What a `PreemptBoundary` drain resolved to. */
142
+ type PreemptBoundaryResult = {
143
+ messages: BaseMessage[];
144
+ /** A hook asked for no further model turn; the seal must not self-loop. */
145
+ preventContinuation: boolean;
146
+ };
147
+
148
+ const EMPTY_PREEMPT_BOUNDARY: PreemptBoundaryResult = {
149
+ messages: [],
150
+ preventContinuation: false,
151
+ };
152
+
153
+ /**
154
+ * One signal that fires when either input fires. `AbortSignal.any` is skipped
155
+ * when the inputs collapse to a single signal — the composite is a fresh
156
+ * object per call, and the common cases (one channel, or the host reusing the
157
+ * same controller for both) don't need one.
158
+ */
159
+ function composeAbortSignals(
160
+ a: AbortSignal | undefined,
161
+ b: AbortSignal | undefined
162
+ ): AbortSignal | undefined {
163
+ if (a == null || a === b) {
164
+ return b;
165
+ }
166
+ if (b == null) {
167
+ return a;
168
+ }
169
+ return AbortSignal.any([a, b]);
170
+ }
171
+
131
172
  /** Minimum relative variance before calibrated toolSchemaTokens overrides current value. */
132
173
  const CALIBRATION_VARIANCE_THRESHOLD = 0.15;
133
174
 
@@ -655,6 +696,20 @@ export abstract class Graph<
655
696
  reasoningStepHasDeltas: Set<string> = new Set();
656
697
  protected handlerDispatchedEventCounts: Map<string, number> = new Map();
657
698
  signal?: AbortSignal;
699
+ /**
700
+ * The abort signal the CALLER handed to the current `processStream` call,
701
+ * assigned unconditionally — including back to `undefined` — on every call.
702
+ *
703
+ * Kept separate from {@link signal} on purpose. That field is construction
704
+ * state with its own consumers (model-call config, subagent parentSignal),
705
+ * so adopting a per-call signal into it would leak one call's controller
706
+ * into the next — `clearHeavyState()` is skipped on HITL interrupts, so a
707
+ * host that aborts a finished request's controller would poison the resumed
708
+ * run's model calls and boundary drains with an already-aborted signal.
709
+ * Boundary dispatch composes the two instead; see
710
+ * `StandardGraph.dispatchPreemptBoundary`.
711
+ */
712
+ callerSignal?: AbortSignal;
658
713
  /** Set of invoked tool call IDs from non-message run steps completed mid-run, if any */
659
714
  invokedToolIds?: Set<string>;
660
715
  handlerRegistry: HandlerRegistry | undefined;
@@ -734,6 +789,7 @@ export abstract class Graph<
734
789
  clearHeavyState(): void {
735
790
  this.config = undefined;
736
791
  this.signal = undefined;
792
+ this.callerSignal = undefined;
737
793
  this.contentData = [];
738
794
  this.contentIndexMap = new Map();
739
795
  this.stepKeyIds = new Map();
@@ -936,6 +992,8 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
936
992
  messages: BaseMessage[] = [];
937
993
  /** Cached run messages preserved before clearHeavyState() so getRunMessages() works after cleanup. */
938
994
  private cachedRunMessages?: BaseMessage[];
995
+ /** Ids of AI turns the agent node returned THIS run; see isRunProducedMessage. */
996
+ protected runProducedAiMessageIds = new Set<string>();
939
997
  /** Checkpoint scope whose messages match index-keyed tool snapshots. */
940
998
  private originalToolContentCheckpointScope?: string;
941
999
  runId: string | undefined;
@@ -961,6 +1019,53 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
961
1019
  subagentUsageSink?: t.SubagentUsageSink;
962
1020
  /** See {@link t.StandardGraphInput.subagentScope}. */
963
1021
  subagentScope: boolean;
1022
+ /** See {@link t.StandardGraphInput.preemption}. */
1023
+ preemption?: t.StreamPreemption;
1024
+ /**
1025
+ * Seals charged against `preemption.maxSeals`. Per-turn: cleared by both
1026
+ * reset paths so a fresh turn gets a fresh budget, while a HITL resume —
1027
+ * which skips `resetValues` — keeps what it had left.
1028
+ */
1029
+ private preemptSealBudgetUsed = 0;
1030
+ /**
1031
+ * Seals honored over the graph's lifetime. Reported by
1032
+ * {@link getPreemptStats}, so it deliberately SURVIVES `clearHeavyState()`
1033
+ * — a host reads it after `processStream` returns, which is strictly after
1034
+ * cleanup runs.
1035
+ */
1036
+ preemptSealCount = 0;
1037
+ /** Boundaries that produced nothing to inject, so the turn stopped early. */
1038
+ preemptEmptyBoundaries = 0;
1039
+ /**
1040
+ * Set between claiming a seal and resolving its boundary. `MultiAgentGraph`
1041
+ * fans parallel agents through this one instance against a single host
1042
+ * request, so without a one-at-a-time gate several streams would each seal
1043
+ * for the same queued message and every loser would take the
1044
+ * nothing-to-inject path and cut its answer short.
1045
+ */
1046
+ private preemptSealInFlight = false;
1047
+ /**
1048
+ * True when a seal ended the turn without a resume. The assistant turn is
1049
+ * real and kept, but it is not the answer the model intended to finish —
1050
+ * hosts persist it as unfinished rather than complete.
1051
+ */
1052
+ preemptIncomplete = false;
1053
+ /**
1054
+ * `stopReason` from a `PreemptBoundary` hook that halted the turn.
1055
+ *
1056
+ * Clearing the registry halt is what keeps the sealed turn alive, but the
1057
+ * registry held the only copy of the reason — so it is captured here first.
1058
+ * Without it `getHaltReason()` returns undefined and a host records a
1059
+ * hook-halted turn as an ordinary completion.
1060
+ */
1061
+ preemptHaltReason: string | undefined;
1062
+ /**
1063
+ * Agent IDs whose next superstep must return to the agent node. Keyed by
1064
+ * agent because `MultiAgentGraph` routes every parallel agent through this
1065
+ * same instance, and a single field would let one agent's boundary resume
1066
+ * another's turn.
1067
+ */
1068
+ pendingPreemptReturn = new Set<string>();
964
1069
 
965
1070
  constructor({
966
1071
  runId,
@@ -972,6 +1077,7 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
972
1077
  calibrationRatio,
973
1078
  subagentUsageSink,
974
1079
  subagentScope,
1080
+ preemption,
975
1081
  }: t.StandardGraphInput) {
976
1082
  super();
977
1083
  this.runId = runId;
@@ -979,6 +1085,7 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
979
1085
  this.langfuse = langfuse;
980
1086
  this.subagentUsageSink = subagentUsageSink;
981
1087
  this.subagentScope = subagentScope === true;
1088
+ this.preemption = preemption;
982
1089
 
983
1090
  if (agents.length === 0) {
984
1091
  throw new Error('At least one agent configuration is required');
@@ -1018,6 +1125,7 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
1018
1125
  * a stale reference on 2nd+ processStream calls.
1019
1126
  */
1020
1127
  this.toolCallStepIds.clear();
1128
+ this.runProducedAiMessageIds.clear();
1021
1129
  this.eagerEventToolExecutions.clear();
1022
1130
  this.clearEagerEventToolUsageCounts();
1023
1131
  this.eagerEventToolCallChunks.clear();
@@ -1050,6 +1158,8 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
1050
1158
  new Map()
1051
1159
  );
1052
1160
  this.invokedToolIds = resetIfNotEmpty(this.invokedToolIds, undefined);
1161
+ this.resetPreemptTurnState();
1162
+ this.resetPreemptTotals();
1053
1163
  const hasScopedCheckpoint =
1054
1164
  this.hasCompiledCheckpointer &&
1055
1165
  checkpointScope != null &&
@@ -1070,6 +1180,12 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
1070
1180
  super.clearHeavyState();
1071
1181
  this.messages = [];
1072
1182
  this.overrideModel = undefined;
1183
+ /**
1184
+ * Turn state only. The reported totals must outlive cleanup — this runs
1185
+ * in `processStream`'s `finally`, and the host reads `getPreemptStats()`
1186
+ * after that returns.
1187
+ */
1188
+ this.resetPreemptTurnState();
1073
1189
  const preserveOriginalToolContent =
1074
1190
  this.hasCompiledCheckpointer &&
1075
1191
  this.originalToolContentCheckpointScope != null;
@@ -1078,6 +1194,120 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
1078
1194
  }
1079
1195
  }
1080
1196
 
1197
+ /**
1198
+ * Per-turn seal budget and routing markers. Cleared by both reset paths so
1199
+ * a new turn starts with a full budget and no stale resume marker.
1200
+ *
1201
+ * The REPORTED counters are deliberately not touched here — see
1202
+ * {@link resetPreemptTotals}.
1203
+ */
1204
+ private resetPreemptTurnState(): void {
1205
+ this.preemptSealBudgetUsed = 0;
1206
+ this.preemptSealInFlight = false;
1207
+ this.pendingPreemptReturn.clear();
1208
+ }
1209
+
1210
+ /**
1211
+ * Lifetime seal totals, cleared only when a genuinely new run starts.
1212
+ * `clearHeavyState()` must NOT call this: it runs in `processStream`'s
1213
+ * `finally`, so zeroing here would make {@link getPreemptStats} and
1214
+ * `preemptIncomplete` unreadable for every caller of the method that just
1215
+ * produced them.
1216
+ */
1217
+ private resetPreemptTotals(): void {
1218
+ this.preemptSealCount = 0;
1219
+ this.preemptEmptyBoundaries = 0;
1220
+ this.preemptIncomplete = false;
1221
+ this.preemptHaltReason = undefined;
1222
+ }
1223
+
1224
+ /**
1225
+ * True when the host has requested a cooperative seal AND this graph may
1226
+ * honor it. Read once per streamed chunk, so it stays property reads plus
1227
+ * one host callback — no I/O, no allocation.
1228
+ *
1229
+ * Non-mutating: a true result only means a seal is worth evaluating. The
1230
+ * budget is taken by {@link claimPreemptSeal} once the accumulated chunk is
1231
+ * known to be safe, so a chunk that cannot seal never spends budget.
1232
+ *
1233
+ * Subagent scopes never seal: a steer targets the top-level conversation,
1234
+ * and a child run must finish so its parent sees a complete result.
1235
+ */
1236
+ /** Internal seal preconditions only — no host callback, no side effects. */
1237
+ private canClaimPreemptSeal(): boolean {
1238
+ /**
1239
+ * Resolved and required here with the same rule `dispatchPreemptBoundary`
1240
+ * uses. Without it a direct `StandardGraph` consumer that supplies no
1241
+ * `runId` could claim a seal on the strength of a global matcher, then hit
1242
+ * the boundary's own null-runId guard and get nothing back — truncating
1243
+ * the answer for a drain that provably could not run.
1244
+ */
1245
+ const runId =
1246
+ (this.config?.configurable?.run_id as string | undefined) ?? this.runId;
1247
+ return (
1248
+ !this.subagentScope &&
1249
+ this.preemption != null &&
1250
+ !this.preemptSealInFlight &&
1251
+ this.preemptSealBudgetUsed < resolveMaxSeals(this.preemption.maxSeals) &&
1252
+ runId != null &&
1253
+ /**
1254
+ * A seal only buys room for an injection. With no `PreemptBoundary`
1255
+ * matcher live — never registered, or a `once` matcher already
1256
+ * consumed — the boundary provably returns nothing and the answer is
1257
+ * cut short for no gain, so refuse the seal instead. Failing closed
1258
+ * lands on the documented no-preemption behavior: the model finishes
1259
+ * and the message waits for the next tool boundary.
1260
+ *
1261
+ * Same session resolution as `dispatchPreemptBoundary`, or a
1262
+ * session-scoped matcher would be visible at one site and not the other.
1263
+ */
1264
+ this.hookRegistry?.hasDispatchableHookFor('PreemptBoundary', runId) ===
1265
+ true
1266
+ );
1267
+ }
1268
+
1269
+ shouldPreemptStream(): boolean {
1270
+ return (
1271
+ this.canClaimPreemptSeal() && this.preemption?.shouldPreempt() === true
1272
+ );
1273
+ }
1274
+
1275
+ /**
1276
+ * Takes the seal slot, or returns false if another stream already holds it.
1277
+ *
1278
+ * Assumes the caller already polled `shouldPreemptStream()` for THIS chunk,
1279
+ * and deliberately does not poll the host again — `StreamPreemption`
1280
+ * documents `shouldPreempt` as once per chunk, and a host that consumes a
1281
+ * pending flag on read would lose the request to a second call.
1282
+ *
1283
+ * The guard and both mutations remain one synchronous body, which is what
1284
+ * makes this safe under a parallel `MultiAgentGraph`: several agents share
1285
+ * one graph and can each see the poll as true, but no `await` can split the
1286
+ * claim, so only one takes the slot. The loser keeps streaming normally
1287
+ * rather than sealing for a message it would never receive.
1288
+ */
1289
+ claimPreemptSeal(): boolean {
1290
+ if (!this.canClaimPreemptSeal()) {
1291
+ return false;
1292
+ }
1293
+ this.preemptSealInFlight = true;
1294
+ this.preemptSealBudgetUsed += 1;
1295
+ this.preemptSealCount += 1;
1296
+ return true;
1297
+ }
1298
+
1299
+ /** Releases the seal slot once its boundary has resolved, win or lose. */
1300
+ releasePreemptSeal(): void {
1301
+ this.preemptSealInFlight = false;
1302
+ }
1303
+
1304
+ getPreemptStats(): t.PreemptStats {
1305
+ return {
1306
+ seals: this.preemptSealCount,
1307
+ emptyBoundaries: this.preemptEmptyBoundaries,
1308
+ };
1309
+ }
1310
+
1081
1311
  /* Run Step Processing */
1082
1312
 
1083
1313
  getRunStep(stepId: string): t.RunStep | undefined {
@@ -1241,6 +1471,25 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
1241
1471
  return this.messages.slice(this.startIndex);
1242
1472
  }
1243
1473
 
1474
+ /**
1475
+ * True when THIS RUN produced `message` — the provenance the handoff cue
1476
+ * gate needs. Tracked as an id set rather than inferred from `startIndex`
1477
+ * arithmetic: summarization's remove-all compaction rewrites the live
1478
+ * array and leaves `startIndex` stale, so index-based run/host
1479
+ * discrimination silently breaks right after a mid-run summarize. Ids
1480
+ * survive compaction (retained messages keep theirs), host-supplied
1481
+ * prefill messages are never in the set, and membership is O(1) per
1482
+ * model call.
1483
+ */
1484
+ isRunProducedMessage(message: BaseMessage): boolean {
1485
+ const id = message.id;
1486
+ return (
1487
+ typeof id === 'string' &&
1488
+ id !== '' &&
1489
+ this.runProducedAiMessageIds.has(id)
1490
+ );
1491
+ }
1492
+
1244
1493
  getContentParts(): t.MessageContentComplex[] | undefined {
1245
1494
  // `messages` can be null/undefined on a graph that has been disposed
1246
1495
  // (clearHeavyState) but is still reachable via a cache (e.g. RedisJobStore's
@@ -1621,6 +1870,23 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
1621
1870
  throw new Error('No config provided');
1622
1871
  }
1623
1872
 
1873
+ /**
1874
+ * A `PreemptBoundary` hook halted this run and the sealed commit is
1875
+ * already in state. Enforced at every model node's ENTRY because that
1876
+ * is the only site that covers all of `MultiAgentGraph`'s onward
1877
+ * routing at once — static direct edges, Command fan-out, fan-in
1878
+ * wrappers, and parallel siblings' subsequent inner-loop turns — none
1879
+ * of which consult the halt (the registry signal was deliberately
1880
+ * cleared to keep the stream-cancel from destroying the sealed turn).
1881
+ * Declining the model call turns every routed-to successor into a
1882
+ * no-op, so the outer workflow drains to END without new turns or tool
1883
+ * side effects. Reset per turn in `resetPreemptTotals`, so the next
1884
+ * `processStream` call starts clean.
1885
+ */
1886
+ if (this.preemptHaltReason != null) {
1887
+ return { messages: [] };
1888
+ }
1889
+
1624
1890
  const { messages } = state;
1625
1891
 
1626
1892
  const discoveredNames = extractToolDiscoveries(messages);
@@ -2277,6 +2543,29 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
2277
2543
  );
2278
2544
  }
2279
2545
  }
2546
+ /**
2547
+ * Applied HERE for the primary so the cue is part of the MEASURED
2548
+ * payload — the pre-invoke projection and overflow guard run on this
2549
+ * stage's output, and a post-measure append could push a just-fits
2550
+ * prompt over budget unreported (#346 round 2). The attemptInvoke
2551
+ * funnel re-keys per SERVING provider: it strips this cue for a
2552
+ * tolerant fallback and adds it for a Claude fallback behind a
2553
+ * tolerant primary.
2554
+ */
2555
+ if (
2556
+ isAnthropicLike(
2557
+ agentContext.provider,
2558
+ agentContext.clientOptions as { model?: string }
2559
+ )
2560
+ ) {
2561
+ const before = transformed;
2562
+ transformed = trackProviderMessageOrigins(
2563
+ before,
2564
+ appendPredecessorHandoffCue(before, (message) =>
2565
+ this.isRunProducedMessage(message)
2566
+ )
2567
+ );
2568
+ }
2280
2569
  return transformed;
2281
2570
  };
2282
2571
 
@@ -2440,6 +2729,50 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
2440
2729
  );
2441
2730
  }
2442
2731
  }
2732
+
2733
+ /**
2734
+ * Mistral rejects consecutive user turns outright; Bedrock's Converse
2735
+ * API documents strict user/assistant alternation across its model
2736
+ * families, with enforcement varying by family (Claude on Converse
2737
+ * currently tolerates the shape — verified live — but the payload is
2738
+ * normalized for all of them rather than betting on leniency). Four
2739
+ * sites can emit them — the `PostToolBatch` and `PreemptBoundary` hook
2740
+ * boundaries (a consolidated context message followed by one
2741
+ * `HumanMessage` per injected entry), a queue drain carrying more than
2742
+ * one steer, and `run.ts`'s pre-stream context push onto a payload that
2743
+ * already ends on a user turn.
2744
+ *
2745
+ * Normalized here, at the last provider-facing hop, rather than at any
2746
+ * one boundary: the boundaries must keep per-message identity, because
2747
+ * `additional_kwargs.source`/`skillName` drive steer rendering and the
2748
+ * trailing-steer anchor downstream. Graph state and the host's
2749
+ * persisted messages are untouched — this shapes only what goes on the
2750
+ * wire, for the providers that actually care.
2751
+ *
2752
+ * Runs AFTER synthetic-context compaction: that pass can rewrite or
2753
+ * drop messages, so coalescing has to see its output, and it is the
2754
+ * last shaping step before the cache breakpoint is chosen.
2755
+ */
2756
+ if (strictAlternationProviders.has(agentContext.provider)) {
2757
+ /**
2758
+ * Wrapped like every other provider transform: the merged message is
2759
+ * a NEW object, and without re-attachment the final pre-invoke
2760
+ * measurement would drop both source turns' calibrated shares and
2761
+ * recharge the merge at full raw estimate — enough to flip a
2762
+ * just-fits payload (the synthetic-context compaction above binary
2763
+ * searches to exactly that) into a spurious pre-invoke overflow. The
2764
+ * merge keeps the first source's id, so the keyed branch re-attaches
2765
+ * that origin; the absorbed turn's tokens are charged as new raw
2766
+ * growth, which only ever under-estimates by less than the old
2767
+ * behavior over-estimated.
2768
+ */
2769
+ const beforeCoalesce = finalMessages;
2770
+ finalMessages = trackProviderMessageOrigins(
2771
+ beforeCoalesce,
2772
+ coalesceAdjacentUserTurns(beforeCoalesce)
2773
+ );
2774
+ }
2775
+
2443
2776
  // Determine the prompt-cache strategy up front. Two distinct facts:
2444
2777
  //
2445
2778
  // `providerPromptCacheEnabled` — prompt caching is on for this provider
@@ -2949,11 +3282,31 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
2949
3282
  calculateMaxToolResultChars(
2950
3283
  fallbackMaxContextTokens ?? agentContext.maxContextTokens
2951
3284
  );
2952
- const projectedFallbackMessages = trackProviderMessageOrigins(
3285
+ /**
3286
+ * Serving-provider cue shaping BEFORE the fallback payload
3287
+ * is measured: a Claude fallback behind a tolerant primary
3288
+ * gains the cue inside the guarded projection (a prompt
3289
+ * within the cue's cost of the fallback budget must take
3290
+ * the recovery path, not ship oversized), and a tolerant
3291
+ * fallback behind an Anthropic primary sheds the baked cue
3292
+ * before it is measured against the tighter budget. The
3293
+ * attemptInvoke funnel pass then finds nothing to change.
3294
+ */
3295
+ const cueShapedFallbackMessages = trackProviderMessageOrigins(
2953
3296
  fallbackMessages,
3297
+ isAnthropicLike(fallbackProvider, {
3298
+ model: resolveServingModelId(fallbackModel),
3299
+ })
3300
+ ? appendPredecessorHandoffCue(fallbackMessages, (m) =>
3301
+ this.isRunProducedMessage(m)
3302
+ )
3303
+ : removePredecessorHandoffCue(fallbackMessages)
3304
+ );
3305
+ const projectedFallbackMessages = trackProviderMessageOrigins(
3306
+ cueShapedFallbackMessages,
2954
3307
  projectMessagesForProvider({
2955
3308
  model: fallbackModel,
2956
- messages: fallbackMessages,
3309
+ messages: cueShapedFallbackMessages,
2957
3310
  provider: fallbackProvider,
2958
3311
  maxToolResultChars: fallbackToolResultChars,
2959
3312
  callOptions: fallbackConfig,
@@ -3039,6 +3392,25 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
3039
3392
  * handled everything — both paths become no-ops.
3040
3393
  */
3041
3394
  const responseMessage = result.messages?.[0];
3395
+ /**
3396
+ * Provenance for the handoff-cue gate: recorded at the node, where the
3397
+ * produced turn is unambiguous. The public ChatModel contract does not
3398
+ * require implementations to set message ids — the reducer would
3399
+ * assign one AFTER this node returns, which is too late for the set —
3400
+ * so an id is assigned here first, the same way the reducer does it
3401
+ * (`v4()`, mirrored into `lc_kwargs`), and the reducer's
3402
+ * keep-existing-id rule makes the state message match.
3403
+ */
3404
+ if (responseMessage?.getType() === 'ai') {
3405
+ if (
3406
+ typeof responseMessage.id !== 'string' ||
3407
+ responseMessage.id === ''
3408
+ ) {
3409
+ responseMessage.id = v4();
3410
+ responseMessage.lc_kwargs.id = responseMessage.id;
3411
+ }
3412
+ this.runProducedAiMessageIds.add(responseMessage.id);
3413
+ }
3042
3414
  const toolCalls = (responseMessage as AIMessageChunk | undefined)
3043
3415
  ?.tool_calls;
3044
3416
  const hasToolCalls = Array.isArray(toolCalls) && toolCalls.length > 0;
@@ -3126,8 +3498,20 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
3126
3498
 
3127
3499
  const invokeElapsed = ((Date.now() - invokeStart) / 1000).toFixed(2);
3128
3500
  agentContext.currentUsage = this.getUsageMetadata(result.messages?.[0]);
3501
+ /**
3502
+ * Synthetic usage from a sealed turn is an estimate derived from the
3503
+ * host's own counter, so feeding it to calibration would teach a ratio
3504
+ * of exactly 1.0 — self-consistent by construction, and wrong for any
3505
+ * provider whose real ratio differs. It still flows to `currentUsage`
3506
+ * for host billing; it just does not get to move the EMA.
3507
+ */
3508
+ const estimatedUsage =
3509
+ (result.messages?.[0] as AIMessageChunk | undefined)?.response_metadata
3510
+ .estimated_usage === true;
3129
3511
  if (agentContext.currentUsage) {
3130
- agentContext.updateLastCallUsage(agentContext.currentUsage);
3512
+ if (!estimatedUsage) {
3513
+ agentContext.updateLastCallUsage(agentContext.currentUsage);
3514
+ }
3131
3515
  emitAgentLog(
3132
3516
  config,
3133
3517
  'debug',
@@ -3157,11 +3541,184 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
3157
3541
  { force: true }
3158
3542
  );
3159
3543
  }
3544
+ if (
3545
+ (responseMessage as AIMessageChunk | undefined)?.response_metadata
3546
+ .preempted === true
3547
+ ) {
3548
+ const { messages: injected, preventContinuation } =
3549
+ await this.dispatchPreemptBoundary(agentId, config);
3550
+ /**
3551
+ * Release before branching: the slot is held only for the duration of
3552
+ * the drain, and an early return below must not strand it.
3553
+ */
3554
+ this.releasePreemptSeal();
3555
+ if (preventContinuation) {
3556
+ /**
3557
+ * A hook halted at the boundary. Commit the sealed turn and anything
3558
+ * it injected, but do NOT self-loop: `preventContinuation` promises
3559
+ * no further model turn, and the run-loop poll in `processStream`
3560
+ * only sees the halt AFTER the next call would already have started
3561
+ * — direct graph consumers never poll it at all. A trailing injected
3562
+ * HumanMessage carries no tool calls, so `toolsCondition` routes it
3563
+ * to END.
3564
+ */
3565
+ this.preemptIncomplete = true;
3566
+ /**
3567
+ * A halting boundary that ALSO injected nothing is still an empty
3568
+ * boundary by the `getPreemptStats().emptyBoundaries` contract —
3569
+ * hosts use the counter for truncated-seal telemetry, and both
3570
+ * paths end the turn with nothing to resume from.
3571
+ */
3572
+ if (injected.length === 0) {
3573
+ this.preemptEmptyBoundaries += 1;
3574
+ }
3575
+ this.cleanupSignalListener();
3576
+ return injected.length > 0
3577
+ ? { messages: [...(result.messages ?? []), ...injected] }
3578
+ : result;
3579
+ }
3580
+ if (injected.length > 0) {
3581
+ this.pendingPreemptReturn.add(agentId);
3582
+ this.cleanupSignalListener();
3583
+ return { messages: [...(result.messages ?? []), ...injected] };
3584
+ }
3585
+ /**
3586
+ * Nothing to inject — the host cancelled or already drained. Do NOT
3587
+ * self-loop: a trailing model turn with no new input is dropped by
3588
+ * some Gemini models and read as prefill by Anthropic. Do NOT pretend
3589
+ * the turn completed either; the answer really was cut short.
3590
+ */
3591
+ this.preemptEmptyBoundaries += 1;
3592
+ this.preemptIncomplete = true;
3593
+ }
3594
+
3160
3595
  this.cleanupSignalListener();
3161
3596
  return result;
3162
3597
  };
3163
3598
  }
3164
3599
 
3600
+ /**
3601
+ * Fires `PreemptBoundary` after a sealed turn and returns whatever the
3602
+ * hooks asked to inject, converted through the same `convertInjectedMessages`
3603
+ * the tool boundary uses so the two sites cannot emit different shapes.
3604
+ *
3605
+ * Never throws: a drain that fails or times out costs the injection, not the
3606
+ * run. The caller treats an empty result as "nothing to resume with".
3607
+ *
3608
+ * `preventContinuation` is surfaced alongside the messages rather than left
3609
+ * to the registry halt signal, which `processStream` only polls between
3610
+ * stream events — by then the self-loop it was meant to prevent has already
3611
+ * issued another model call, and a direct graph consumer never polls it.
3612
+ */
3613
+ private async dispatchPreemptBoundary(
3614
+ agentId: string,
3615
+ config: RunnableConfig | undefined
3616
+ ): Promise<PreemptBoundaryResult> {
3617
+ if (this.hookRegistry == null) {
3618
+ return EMPTY_PREEMPT_BOUNDARY;
3619
+ }
3620
+ const configurable = config?.configurable;
3621
+ const runId = (configurable?.run_id as string | undefined) ?? this.runId;
3622
+ if (runId == null) {
3623
+ return EMPTY_PREEMPT_BOUNDARY;
3624
+ }
3625
+ const result = await executeHooks({
3626
+ registry: this.hookRegistry,
3627
+ input: {
3628
+ hook_event_name: 'PreemptBoundary',
3629
+ runId,
3630
+ threadId: configurable?.thread_id as string | undefined,
3631
+ agentId: this.subagentScope ? agentId : undefined,
3632
+ executingAgentId: agentId,
3633
+ sealCount: this.preemptSealCount,
3634
+ },
3635
+ sessionId: runId,
3636
+ timeoutMs: PREEMPT_BOUNDARY_HOOK_TIMEOUT_MS,
3637
+ /**
3638
+ * The host's own abort signal(s), deliberately NOT `config.signal` —
3639
+ * inside a node the latter is LangGraph's composed signal, which also
3640
+ * fires when an unrelated sibling in the same superstep throws.
3641
+ * Cancellation already returns control in milliseconds without this;
3642
+ * what it buys is that a drain does not keep running after the run it
3643
+ * belongs to died.
3644
+ *
3645
+ * Composed because the host can cancel through either channel: the
3646
+ * construction signal, or the per-call `callerConfig.signal` — the only
3647
+ * one a multi-agent run has, since `MultiAgentGraphConfig` exposes no
3648
+ * construction signal. When both exist they may be different
3649
+ * controllers, and a drain must stop when EITHER fires.
3650
+ */
3651
+ signal: composeAbortSignals(this.signal, this.callerSignal),
3652
+ }).catch((): undefined => undefined);
3653
+ if (result == null) {
3654
+ return EMPTY_PREEMPT_BOUNDARY;
3655
+ }
3656
+ /**
3657
+ * `executeHooks` raises a registry halt whenever a hook returns
3658
+ * `preventContinuation`. That halt has exactly one consumer — the poll in
3659
+ * `Run.processStream` — and its `break` cancels the stream iterator, which
3660
+ * aborts Pregel. The abort lands BEFORE the outer reducer commits
3661
+ * `StandardGraph.messages`, so honoring the halt here would destroy the
3662
+ * sealed assistant turn: the run returns empty content and the host
3663
+ * persists nothing. Measured deterministically — the commit is several
3664
+ * stream events downstream of the point the halt becomes observable.
3665
+ *
3666
+ * The `preventContinuation` branch in `createCallModel` already enforces
3667
+ * the contract locally by declining to self-loop, and a sealed chunk
3668
+ * provably carries no tool calls, so the turn routes to END after exactly
3669
+ * one model call either way. Clearing the halt therefore costs nothing it
3670
+ * was buying and saves the content the seal exists to preserve.
3671
+ *
3672
+ * Scoped to a halt this event raised, so a halt from an earlier hook in
3673
+ * the same run — `haltRun` is first-write-wins — is left alone.
3674
+ */
3675
+ const halt = this.hookRegistry.getHaltSignal(runId);
3676
+ if (result.preventContinuation === true && halt?.source === 'PreemptBoundary') {
3677
+ this.preemptHaltReason = halt.reason;
3678
+ this.hookRegistry.clearHaltSignal(runId);
3679
+ }
3680
+ const injected: BaseMessage[] = [];
3681
+ /**
3682
+ * `PreemptBoundaryHookOutput` is `BaseHookOutput`, so `additionalContext`
3683
+ * is part of the contract here just as it is at the tool boundary. It has
3684
+ * to be materialized BEFORE the emptiness test, or a hook that returns
3685
+ * context alone would read as "nothing to resume with" and cut the answer
3686
+ * short. Same system-flavored `HumanMessage` convention `ToolNode` uses —
3687
+ * Anthropic and Google reject a mid-conversation `SystemMessage`.
3688
+ */
3689
+ /**
3690
+ * Whitespace-only entries are dropped for the same reason empty
3691
+ * `injectedMessages` are: `executeHooks` keeps them because their raw
3692
+ * length is nonzero, but a blank turn is not something to resume from —
3693
+ * it costs a model call and strict providers reject it outright.
3694
+ */
3695
+ const contexts = result.additionalContexts.filter(
3696
+ (context) => context.trim() !== ''
3697
+ );
3698
+ if (contexts.length > 0) {
3699
+ injected.push(
3700
+ new HumanMessage({
3701
+ content: contexts.join('\n\n'),
3702
+ additional_kwargs: { role: 'system', isMeta: true, source: 'hook' },
3703
+ })
3704
+ );
3705
+ }
3706
+ if (result.injectedMessages.length > 0) {
3707
+ try {
3708
+ injected.push(...convertInjectedMessages(result.injectedMessages));
3709
+ } catch (e) {
3710
+ console.warn(
3711
+ '[StandardGraph] Failed to convert PreemptBoundary injectedMessages:',
3712
+ e instanceof Error ? e.message : e
3713
+ );
3714
+ }
3715
+ }
3716
+ return {
3717
+ messages: injected,
3718
+ preventContinuation: result.preventContinuation === true,
3719
+ };
3720
+ }
3721
+
3165
3722
  createAgentNode(agentId: string): t.CompiledAgentWorfklow {
3166
3723
  const getConfig = (): RunnableConfig | undefined => this.config;
3167
3724
  const agentContext = this.agentContexts.get(agentId);
@@ -3325,6 +3882,14 @@ export class StandardGraph extends Graph<t.BaseGraphState, t.GraphNode> {
3325
3882
  config?: RunnableConfig
3326
3883
  ): string => {
3327
3884
  this.config = config;
3885
+ /**
3886
+ * A sealed turn that injected messages resumes in the SAME pregel run:
3887
+ * back to the agent node as a new superstep, so the model continues in
3888
+ * one assistant message instead of restarting the graph.
3889
+ */
3890
+ if (this.pendingPreemptReturn.delete(agentId)) {
3891
+ return agentNode;
3892
+ }
3328
3893
  if (state.summarizationRequest != null) {
3329
3894
  return summarizeNode;
3330
3895
  }