@librechat/agents 3.3.0 → 3.3.1

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 (129) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +116 -2
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/common/enum.cjs +2 -0
  4. package/dist/cjs/common/enum.cjs.map +1 -1
  5. package/dist/cjs/graphs/Graph.cjs +229 -48
  6. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  7. package/dist/cjs/graphs/MultiAgentGraph.cjs +102 -27
  8. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  9. package/dist/cjs/llm/bedrock/index.cjs +11 -2
  10. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  11. package/dist/cjs/llm/contextOverflowRecovery.cjs +132 -0
  12. package/dist/cjs/llm/contextOverflowRecovery.cjs.map +1 -0
  13. package/dist/cjs/llm/google/index.cjs +1 -1
  14. package/dist/cjs/llm/invoke.cjs +60 -3
  15. package/dist/cjs/llm/invoke.cjs.map +1 -1
  16. package/dist/cjs/main.cjs +20 -7
  17. package/dist/cjs/messages/prune.cjs +16 -5
  18. package/dist/cjs/messages/prune.cjs.map +1 -1
  19. package/dist/cjs/messages/recency.cjs +2 -0
  20. package/dist/cjs/messages/recency.cjs.map +1 -1
  21. package/dist/cjs/run.cjs +15 -2
  22. package/dist/cjs/run.cjs.map +1 -1
  23. package/dist/cjs/stream.cjs +205 -49
  24. package/dist/cjs/stream.cjs.map +1 -1
  25. package/dist/cjs/summarization/node.cjs +55 -7
  26. package/dist/cjs/summarization/node.cjs.map +1 -1
  27. package/dist/cjs/tools/BashExecutor.cjs +2 -2
  28. package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
  29. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +2 -2
  30. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -1
  31. package/dist/cjs/tools/CodeExecutor.cjs +69 -8
  32. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  33. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +19 -15
  34. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  35. package/dist/cjs/tools/ToolNode.cjs +32 -3
  36. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  37. package/dist/cjs/utils/errors.cjs +317 -52
  38. package/dist/cjs/utils/errors.cjs.map +1 -1
  39. package/dist/esm/agents/AgentContext.mjs +117 -3
  40. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  41. package/dist/esm/common/enum.mjs +2 -0
  42. package/dist/esm/common/enum.mjs.map +1 -1
  43. package/dist/esm/graphs/Graph.mjs +227 -46
  44. package/dist/esm/graphs/Graph.mjs.map +1 -1
  45. package/dist/esm/graphs/MultiAgentGraph.mjs +102 -27
  46. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  47. package/dist/esm/llm/bedrock/index.mjs +11 -2
  48. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  49. package/dist/esm/llm/contextOverflowRecovery.mjs +130 -0
  50. package/dist/esm/llm/contextOverflowRecovery.mjs.map +1 -0
  51. package/dist/esm/llm/google/index.mjs +1 -1
  52. package/dist/esm/llm/invoke.mjs +59 -4
  53. package/dist/esm/llm/invoke.mjs.map +1 -1
  54. package/dist/esm/main.mjs +9 -9
  55. package/dist/esm/messages/prune.mjs +14 -6
  56. package/dist/esm/messages/prune.mjs.map +1 -1
  57. package/dist/esm/messages/recency.mjs +2 -1
  58. package/dist/esm/messages/recency.mjs.map +1 -1
  59. package/dist/esm/run.mjs +15 -2
  60. package/dist/esm/run.mjs.map +1 -1
  61. package/dist/esm/stream.mjs +205 -49
  62. package/dist/esm/stream.mjs.map +1 -1
  63. package/dist/esm/summarization/node.mjs +55 -7
  64. package/dist/esm/summarization/node.mjs.map +1 -1
  65. package/dist/esm/tools/BashExecutor.mjs +3 -3
  66. package/dist/esm/tools/BashExecutor.mjs.map +1 -1
  67. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +3 -3
  68. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -1
  69. package/dist/esm/tools/CodeExecutor.mjs +62 -9
  70. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  71. package/dist/esm/tools/ProgrammaticToolCalling.mjs +20 -16
  72. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  73. package/dist/esm/tools/ToolNode.mjs +32 -3
  74. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  75. package/dist/esm/utils/errors.mjs +317 -53
  76. package/dist/esm/utils/errors.mjs.map +1 -1
  77. package/dist/types/agents/AgentContext.d.ts +62 -3
  78. package/dist/types/common/enum.d.ts +2 -0
  79. package/dist/types/graphs/Graph.d.ts +16 -2
  80. package/dist/types/graphs/MultiAgentGraph.d.ts +1 -0
  81. package/dist/types/llm/contextOverflowRecovery.d.ts +85 -0
  82. package/dist/types/llm/invoke.d.ts +35 -6
  83. package/dist/types/messages/prune.d.ts +10 -2
  84. package/dist/types/messages/recency.d.ts +1 -0
  85. package/dist/types/run.d.ts +2 -0
  86. package/dist/types/tools/CodeExecutor.d.ts +14 -1
  87. package/dist/types/types/llm.d.ts +7 -4
  88. package/dist/types/types/stream.d.ts +5 -4
  89. package/dist/types/types/summarize.d.ts +22 -0
  90. package/dist/types/utils/__tests__/fixtures/contextOverflowSignatures.d.ts +40 -0
  91. package/dist/types/utils/errors.d.ts +65 -16
  92. package/dist/types/utils/redactSecrets.d.ts +3 -0
  93. package/package.json +7 -8
  94. package/src/agents/AgentContext.ts +188 -7
  95. package/src/agents/__tests__/AgentContext.overflow.test.ts +205 -0
  96. package/src/common/enum.ts +2 -0
  97. package/src/graphs/Graph.ts +389 -58
  98. package/src/graphs/MultiAgentGraph.ts +184 -46
  99. package/src/graphs/__tests__/Graph.contextOverflow.test.ts +631 -0
  100. package/src/llm/__tests__/contextOverflowRecovery.test.ts +401 -0
  101. package/src/llm/__tests__/fallbackOverflow.test.ts +287 -0
  102. package/src/llm/bedrock/index.ts +25 -12
  103. package/src/llm/contextOverflowRecovery.ts +292 -0
  104. package/src/llm/invoke.ts +119 -4
  105. package/src/messages/prune.ts +24 -11
  106. package/src/messages/recency.ts +3 -1
  107. package/src/run.ts +24 -1
  108. package/src/scripts/context-overflow-probe.ts +997 -0
  109. package/src/specs/agent-handoffs.test.ts +903 -1
  110. package/src/specs/context-overflow-recovery.live.test.ts +213 -0
  111. package/src/splitStream.test.ts +882 -0
  112. package/src/stream.ts +315 -51
  113. package/src/summarization/__tests__/aggregator.test.ts +83 -0
  114. package/src/summarization/__tests__/node.test.ts +139 -0
  115. package/src/summarization/node.ts +99 -14
  116. package/src/tools/BashExecutor.ts +4 -2
  117. package/src/tools/BashProgrammaticToolCalling.ts +4 -7
  118. package/src/tools/CodeExecutor.ts +119 -8
  119. package/src/tools/ProgrammaticToolCalling.ts +29 -27
  120. package/src/tools/ToolNode.ts +50 -8
  121. package/src/tools/__tests__/CodeApiAuthHeaders.test.ts +297 -3
  122. package/src/types/llm.ts +8 -1
  123. package/src/types/stream.ts +5 -4
  124. package/src/types/summarize.ts +22 -0
  125. package/src/utils/__tests__/errors.test.ts +270 -0
  126. package/src/utils/__tests__/fixtures/contextOverflowSignatures.ts +336 -0
  127. package/src/utils/__tests__/redactSecrets.test.ts +56 -0
  128. package/src/utils/errors.ts +484 -66
  129. package/src/utils/redactSecrets.ts +61 -0
@@ -0,0 +1,631 @@
1
+ import { MemorySaver } from '@langchain/langgraph';
2
+ import { describe, expect, it } from '@jest/globals';
3
+ import { Runnable } from '@langchain/core/runnables';
4
+ import {
5
+ AIMessageChunk,
6
+ HumanMessage,
7
+ AIMessage,
8
+ } from '@langchain/core/messages';
9
+ import type { BaseMessage } from '@langchain/core/messages';
10
+ import type * as t from '@/types';
11
+ import { OVERFLOW_SIGNATURES } from '@/utils/__tests__/fixtures/contextOverflowSignatures';
12
+ import { GraphEvents, Providers } from '@/common';
13
+ import { Run } from '@/run';
14
+
15
+ /**
16
+ * Every message is claimed to cost the same, so the budget the recovery
17
+ * settles on maps directly onto a message count and the assertions can be
18
+ * about behavior rather than arithmetic.
19
+ */
20
+ const TOKENS_PER_MESSAGE = 40_000;
21
+
22
+ const tokenCounter: t.TokenCounter = () => TOKENS_PER_MESSAGE;
23
+
24
+ function signatureFor(model: string): Record<string, unknown> {
25
+ const signature = OVERFLOW_SIGNATURES.find((s) => s.model === model);
26
+ if (signature == null) {
27
+ throw new Error(`missing fixture for ${model}`);
28
+ }
29
+ return signature.error;
30
+ }
31
+
32
+ /** Rebuilds a thrown provider error from a captured signature. */
33
+ function throwable(fields: Record<string, unknown>): Error {
34
+ const error = new Error(String(fields.message));
35
+ return Object.assign(error, fields);
36
+ }
37
+
38
+ /**
39
+ * Fails the first N calls with a real captured provider rejection, then
40
+ * answers normally — the shape of a run that overflows and then fits after
41
+ * compaction.
42
+ */
43
+ class OverflowThenSucceedModel extends Runnable<BaseMessage[], AIMessageChunk> {
44
+ lc_namespace = ['tests'];
45
+ readonly calls: BaseMessage[][] = [];
46
+
47
+ constructor(
48
+ private readonly error: Record<string, unknown>,
49
+ private readonly failures = 1
50
+ ) {
51
+ super();
52
+ }
53
+
54
+ private record(messages: BaseMessage[]): void {
55
+ this.calls.push(messages);
56
+ if (this.calls.length <= this.failures) {
57
+ throw throwable(this.error);
58
+ }
59
+ }
60
+
61
+ async invoke(messages: BaseMessage[]): Promise<AIMessageChunk> {
62
+ this.record(messages);
63
+ return new AIMessageChunk({ content: 'recovered' });
64
+ }
65
+ }
66
+
67
+ function buildConversation(turns: number): BaseMessage[] {
68
+ const messages: BaseMessage[] = [];
69
+ for (let i = 0; i < turns; i++) {
70
+ messages.push(new HumanMessage(`question ${i}`));
71
+ messages.push(new AIMessage(`answer ${i}`));
72
+ }
73
+ messages.push(new HumanMessage('final question'));
74
+ return messages;
75
+ }
76
+
77
+ async function createRun(options: {
78
+ runId: string;
79
+ maxContextTokens: number;
80
+ checkpointer?: boolean;
81
+ }): Promise<Run<t.IState>> {
82
+ return Run.create<t.IState>({
83
+ runId: options.runId,
84
+ graphConfig: {
85
+ type: 'standard',
86
+ llmConfig: {
87
+ provider: Providers.ANTHROPIC,
88
+ disableStreaming: true,
89
+ streamUsage: false,
90
+ },
91
+ maxContextTokens: options.maxContextTokens,
92
+ compileOptions:
93
+ options.checkpointer === true
94
+ ? { checkpointer: new MemorySaver() }
95
+ : undefined,
96
+ },
97
+ returnContent: true,
98
+ skipCleanup: true,
99
+ tokenCounter,
100
+ });
101
+ }
102
+
103
+ const streamConfig = {
104
+ configurable: { thread_id: 'context-overflow-recovery' },
105
+ streamMode: 'values' as const,
106
+ version: 'v2' as const,
107
+ };
108
+
109
+ describe('context overflow recovery', () => {
110
+ it('preserves masked tool originals while checkpointed messages survive', async () => {
111
+ const run = await createRun({
112
+ runId: 'overflow-originals-checkpoint',
113
+ maxContextTokens: 1_000_000,
114
+ checkpointer: true,
115
+ });
116
+ if (!run.Graph) {
117
+ throw new Error('Expected graph to be initialized');
118
+ }
119
+ const agentContext = run.Graph.agentContexts.get('default');
120
+ if (agentContext == null) {
121
+ throw new Error('Expected default agent context');
122
+ }
123
+ run.Graph.resetValues(undefined, '8:thread-a:');
124
+ agentContext.preserveOriginalToolContent(new Map([[2, 'full output']]));
125
+
126
+ run.Graph.resetValues(undefined, '8:thread-a:');
127
+
128
+ expect(agentContext.pendingOriginalToolContent).toEqual(
129
+ new Map([[2, 'full output']])
130
+ );
131
+ });
132
+
133
+ it('does not share masked tool originals across checkpoint scopes', async () => {
134
+ const run = await createRun({
135
+ runId: 'overflow-originals-isolated',
136
+ maxContextTokens: 1_000_000,
137
+ checkpointer: true,
138
+ });
139
+ if (!run.Graph) {
140
+ throw new Error('Expected graph to be initialized');
141
+ }
142
+ const agentContext = run.Graph.agentContexts.get('default');
143
+ if (agentContext == null) {
144
+ throw new Error('Expected default agent context');
145
+ }
146
+ run.Graph.resetValues(undefined, '8:thread-a:branch');
147
+ agentContext.preserveOriginalToolContent(new Map([[2, 'thread A']]));
148
+
149
+ run.Graph.resetValues(undefined, '8:thread-b:branch');
150
+
151
+ expect(agentContext.pendingOriginalToolContent).toBeUndefined();
152
+ });
153
+
154
+ it('does not share masked tool originals across sibling checkpoint forks', async () => {
155
+ const run = await createRun({
156
+ runId: 'overflow-originals-branch-isolated',
157
+ maxContextTokens: 1_000_000,
158
+ checkpointer: true,
159
+ });
160
+ if (!run.Graph) {
161
+ throw new Error('Expected graph to be initialized');
162
+ }
163
+ const agentContext = run.Graph.agentContexts.get('default');
164
+ if (agentContext == null) {
165
+ throw new Error('Expected default agent context');
166
+ }
167
+ run.Graph.resetValues(
168
+ undefined,
169
+ JSON.stringify(['thread-a', 'namespace', 'checkpoint-a', 1])
170
+ );
171
+ agentContext.preserveOriginalToolContent(new Map([[2, 'branch A']]));
172
+
173
+ run.Graph.resetValues(
174
+ undefined,
175
+ JSON.stringify(['thread-a', 'namespace', 'checkpoint-a', 2])
176
+ );
177
+
178
+ expect(agentContext.pendingOriginalToolContent).toBeUndefined();
179
+ });
180
+
181
+ it('preserves snapshots with the auto-installed HITL checkpointer', async () => {
182
+ const run = await Run.create<t.IState>({
183
+ runId: 'overflow-originals-hitl-checkpointer',
184
+ graphConfig: {
185
+ type: 'standard',
186
+ llmConfig: {
187
+ provider: Providers.ANTHROPIC,
188
+ disableStreaming: true,
189
+ streamUsage: false,
190
+ },
191
+ maxContextTokens: 1_000_000,
192
+ compileOptions: { interruptAfter: [] },
193
+ },
194
+ humanInTheLoop: { enabled: true },
195
+ returnContent: true,
196
+ skipCleanup: true,
197
+ tokenCounter,
198
+ });
199
+ if (!run.Graph) {
200
+ throw new Error('Expected graph to be initialized');
201
+ }
202
+ const agentContext = run.Graph.agentContexts.get('default');
203
+ if (agentContext == null) {
204
+ throw new Error('Expected default agent context');
205
+ }
206
+ expect(run.Graph.compileOptions?.checkpointer).toBeUndefined();
207
+ expect(run.Graph.hasCompiledCheckpointer).toBe(true);
208
+ run.Graph.resetValues(undefined, 'checkpoint-scope');
209
+ agentContext.preserveOriginalToolContent(new Map([[2, 'full output']]));
210
+
211
+ run.Graph.resetValues(undefined, 'checkpoint-scope');
212
+
213
+ expect(agentContext.pendingOriginalToolContent).toEqual(
214
+ new Map([[2, 'full output']])
215
+ );
216
+ });
217
+
218
+ it('compacts and retries instead of surfacing the provider error', async () => {
219
+ const run = await createRun({
220
+ runId: 'overflow-recovery-numbers',
221
+ /** Deliberately wrong: far above the model's real 200k window. */
222
+ maxContextTokens: 1_000_000,
223
+ });
224
+ if (!run.Graph) {
225
+ throw new Error('Expected graph to be initialized');
226
+ }
227
+ const model = new OverflowThenSucceedModel(
228
+ signatureFor('claude-haiku-4-5-20251001')
229
+ );
230
+ run.Graph.overrideModel = model;
231
+
232
+ const content = await run.processStream(
233
+ { messages: buildConversation(8) },
234
+ streamConfig
235
+ );
236
+
237
+ expect(model.calls).toHaveLength(2);
238
+ expect(content).toEqual([{ type: 'text', text: 'recovered' }]);
239
+ });
240
+
241
+ it('retargets the budget to the ceiling the provider reported', async () => {
242
+ const run = await createRun({
243
+ runId: 'overflow-recovery-budget',
244
+ maxContextTokens: 1_000_000,
245
+ });
246
+ if (!run.Graph) {
247
+ throw new Error('Expected graph to be initialized');
248
+ }
249
+ run.Graph.overrideModel = new OverflowThenSucceedModel(
250
+ signatureFor('claude-haiku-4-5-20251001')
251
+ );
252
+
253
+ await run.processStream({ messages: buildConversation(8) }, streamConfig);
254
+
255
+ const agentContext = run.Graph.agentContexts.get('default');
256
+ expect(agentContext?.maxContextTokens).toBeLessThan(1_000_000);
257
+ expect(agentContext?.overflowRecoveryAttempts).toBe(1);
258
+ });
259
+
260
+ it('sends strictly less on the retry', async () => {
261
+ const run = await createRun({
262
+ runId: 'overflow-recovery-shrinks',
263
+ maxContextTokens: 1_000_000,
264
+ });
265
+ if (!run.Graph) {
266
+ throw new Error('Expected graph to be initialized');
267
+ }
268
+ const model = new OverflowThenSucceedModel(
269
+ signatureFor('claude-haiku-4-5-20251001')
270
+ );
271
+ run.Graph.overrideModel = model;
272
+
273
+ await run.processStream({ messages: buildConversation(8) }, streamConfig);
274
+
275
+ expect(model.calls[1].length).toBeLessThan(model.calls[0].length);
276
+ });
277
+
278
+ it('recovers from a rejection that reported no numbers', async () => {
279
+ const run = await createRun({
280
+ runId: 'overflow-recovery-blind',
281
+ maxContextTokens: 600_000,
282
+ });
283
+ if (!run.Graph) {
284
+ throw new Error('Expected graph to be initialized');
285
+ }
286
+ const model = new OverflowThenSucceedModel(
287
+ signatureFor('us.anthropic.claude-sonnet-4-5-20250929-v1:0')
288
+ );
289
+ run.Graph.overrideModel = model;
290
+
291
+ const content = await run.processStream(
292
+ { messages: buildConversation(8) },
293
+ streamConfig
294
+ );
295
+
296
+ expect(model.calls).toHaveLength(2);
297
+ expect(content).toEqual([{ type: 'text', text: 'recovered' }]);
298
+ });
299
+
300
+ it('gives up after the bounded number of recoveries rather than looping', async () => {
301
+ const run = await createRun({
302
+ runId: 'overflow-recovery-bounded',
303
+ maxContextTokens: 600_000,
304
+ });
305
+ if (!run.Graph) {
306
+ throw new Error('Expected graph to be initialized');
307
+ }
308
+ const model = new OverflowThenSucceedModel(
309
+ signatureFor('us.anthropic.claude-sonnet-4-5-20250929-v1:0'),
310
+ Number.MAX_SAFE_INTEGER
311
+ );
312
+ run.Graph.overrideModel = model;
313
+
314
+ await expect(
315
+ run.processStream({ messages: buildConversation(8) }, streamConfig)
316
+ ).rejects.toThrow(/too long/i);
317
+
318
+ /** Initial call plus one retry per allowed recovery. */
319
+ expect(model.calls.length).toBeLessThanOrEqual(4);
320
+ });
321
+
322
+ it('restores the configured budget and allowance for the next run', async () => {
323
+ const run = await createRun({
324
+ runId: 'overflow-recovery-reset',
325
+ maxContextTokens: 1_000_000,
326
+ });
327
+ if (!run.Graph) {
328
+ throw new Error('Expected graph to be initialized');
329
+ }
330
+ run.Graph.overrideModel = new OverflowThenSucceedModel(
331
+ signatureFor('claude-haiku-4-5-20251001')
332
+ );
333
+
334
+ await run.processStream({ messages: buildConversation(8) }, streamConfig);
335
+
336
+ const agentContext = run.Graph.agentContexts.get('default');
337
+ expect(agentContext?.maxContextTokens).toBeLessThan(1_000_000);
338
+ expect(agentContext?.overflowRecoveryAttempts).toBe(1);
339
+
340
+ /** What `processStream` runs at the start of every turn. */
341
+ run.Graph.resetValues();
342
+
343
+ expect(agentContext?.maxContextTokens).toBe(1_000_000);
344
+ expect(agentContext?.overflowRecoveryAttempts).toBe(0);
345
+ });
346
+
347
+ it('recovers again on a later turn of the same run', async () => {
348
+ const run = await createRun({
349
+ runId: 'overflow-recovery-second-turn',
350
+ maxContextTokens: 1_000_000,
351
+ });
352
+ if (!run.Graph) {
353
+ throw new Error('Expected graph to be initialized');
354
+ }
355
+ const signature = signatureFor('claude-haiku-4-5-20251001');
356
+
357
+ for (const turn of [1, 2, 3]) {
358
+ run.Graph.overrideModel = new OverflowThenSucceedModel(signature);
359
+ await run.processStream(
360
+ { messages: buildConversation(8) },
361
+ {
362
+ ...streamConfig,
363
+ configurable: { thread_id: `context-overflow-recovery-${turn}` },
364
+ }
365
+ );
366
+ }
367
+
368
+ const agentContext = run.Graph.agentContexts.get('default');
369
+ /**
370
+ * One recovery per turn, not three accumulated — an allowance that
371
+ * carried across turns would have stopped recovering by turn three.
372
+ */
373
+ expect(agentContext?.overflowRecoveryAttempts).toBe(1);
374
+ });
375
+
376
+ it('does not retry when neither pruning nor summarization can shrink the prompt', async () => {
377
+ /**
378
+ * No token counter means no pruner, and summarization is off, so the
379
+ * summarize node deliberately no-ops — a retry would resend a
380
+ * byte-identical prompt.
381
+ */
382
+ const run = await Run.create<t.IState>({
383
+ runId: 'overflow-recovery-nothing-to-shrink',
384
+ graphConfig: {
385
+ type: 'standard',
386
+ llmConfig: {
387
+ provider: Providers.ANTHROPIC,
388
+ disableStreaming: true,
389
+ streamUsage: false,
390
+ },
391
+ maxContextTokens: 1_000_000,
392
+ },
393
+ returnContent: true,
394
+ skipCleanup: true,
395
+ });
396
+ if (!run.Graph) {
397
+ throw new Error('Expected graph to be initialized');
398
+ }
399
+ const model = new OverflowThenSucceedModel(
400
+ signatureFor('claude-haiku-4-5-20251001'),
401
+ Number.MAX_SAFE_INTEGER
402
+ );
403
+ run.Graph.overrideModel = model;
404
+
405
+ await expect(
406
+ run.processStream({ messages: buildConversation(8) }, streamConfig)
407
+ ).rejects.toThrow(/too long/i);
408
+
409
+ expect(model.calls).toHaveLength(1);
410
+ expect(
411
+ run.Graph.agentContexts.get('default')?.overflowRecoveryAttempts
412
+ ).toBe(0);
413
+ });
414
+
415
+ it('does not retry when recency preserves the entire first turn', async () => {
416
+ const run = await Run.create<t.IState>({
417
+ runId: 'overflow-recovery-recent-first-turn',
418
+ graphConfig: {
419
+ type: 'standard',
420
+ llmConfig: {
421
+ provider: Providers.ANTHROPIC,
422
+ disableStreaming: true,
423
+ streamUsage: false,
424
+ },
425
+ summarizationEnabled: true,
426
+ },
427
+ returnContent: true,
428
+ skipCleanup: true,
429
+ });
430
+ if (!run.Graph) {
431
+ throw new Error('Expected graph to be initialized');
432
+ }
433
+ const model = new OverflowThenSucceedModel(
434
+ signatureFor('us.anthropic.claude-sonnet-4-5-20250929-v1:0'),
435
+ Number.MAX_SAFE_INTEGER
436
+ );
437
+ run.Graph.overrideModel = model;
438
+
439
+ await expect(
440
+ run.processStream(
441
+ { messages: [new HumanMessage('oversized first turn')] },
442
+ streamConfig
443
+ )
444
+ ).rejects.toThrow(/too long/i);
445
+
446
+ expect(model.calls).toHaveLength(1);
447
+ expect(
448
+ run.Graph.agentContexts.get('default')?.overflowRecoveryAttempts
449
+ ).toBe(0);
450
+ });
451
+
452
+ it('does not retry without a configured pruning budget', async () => {
453
+ const run = await Run.create<t.IState>({
454
+ runId: 'overflow-recovery-no-pruning-budget',
455
+ graphConfig: {
456
+ type: 'standard',
457
+ llmConfig: {
458
+ provider: Providers.ANTHROPIC,
459
+ disableStreaming: true,
460
+ streamUsage: false,
461
+ },
462
+ },
463
+ returnContent: true,
464
+ skipCleanup: true,
465
+ tokenCounter,
466
+ });
467
+ if (!run.Graph) {
468
+ throw new Error('Expected graph to be initialized');
469
+ }
470
+ const model = new OverflowThenSucceedModel(
471
+ signatureFor('us.anthropic.claude-sonnet-4-5-20250929-v1:0'),
472
+ Number.MAX_SAFE_INTEGER
473
+ );
474
+ run.Graph.overrideModel = model;
475
+
476
+ await expect(
477
+ run.processStream({ messages: buildConversation(8) }, streamConfig)
478
+ ).rejects.toThrow(/too long/i);
479
+
480
+ expect(model.calls).toHaveLength(1);
481
+ expect(
482
+ run.Graph.agentContexts.get('default')?.overflowRecoveryAttempts
483
+ ).toBe(0);
484
+ });
485
+
486
+ it('summarizes the first numberless overflow without a pruning budget', async () => {
487
+ const summarizeStarts: unknown[] = [];
488
+ const run = await Run.create<t.IState>({
489
+ runId: 'overflow-recovery-summary-without-budget',
490
+ graphConfig: {
491
+ type: 'standard',
492
+ llmConfig: {
493
+ provider: Providers.ANTHROPIC,
494
+ disableStreaming: true,
495
+ streamUsage: false,
496
+ },
497
+ summarizationEnabled: true,
498
+ },
499
+ returnContent: true,
500
+ skipCleanup: true,
501
+ tokenCounter,
502
+ customHandlers: {
503
+ [GraphEvents.ON_SUMMARIZE_START]: {
504
+ handle: (_event: string, data: t.StreamEventData): void => {
505
+ summarizeStarts.push(data);
506
+ },
507
+ },
508
+ },
509
+ });
510
+ if (!run.Graph) {
511
+ throw new Error('Expected graph to be initialized');
512
+ }
513
+ const model = new OverflowThenSucceedModel(
514
+ signatureFor('us.anthropic.claude-sonnet-4-5-20250929-v1:0')
515
+ );
516
+ run.Graph.overrideModel = model;
517
+
518
+ const content = await run.processStream(
519
+ { messages: buildConversation(8) },
520
+ streamConfig
521
+ );
522
+
523
+ expect(content).toEqual([{ type: 'text', text: 'recovered' }]);
524
+ expect(summarizeStarts).toHaveLength(1);
525
+ });
526
+
527
+ it('summarizes conversation messages pruned on the first recovery', async () => {
528
+ /**
529
+ * The initial overflow detour avoids an unconditional summarization call,
530
+ * but the corrected prune must still summarize any conversation messages
531
+ * it moves out of the retained tail.
532
+ */
533
+ const summarizeStarts: unknown[] = [];
534
+ const run = await Run.create<t.IState>({
535
+ runId: 'overflow-recovery-compress-first',
536
+ graphConfig: {
537
+ type: 'standard',
538
+ llmConfig: {
539
+ provider: Providers.ANTHROPIC,
540
+ disableStreaming: true,
541
+ streamUsage: false,
542
+ },
543
+ maxContextTokens: 1_000_000,
544
+ summarizationEnabled: true,
545
+ },
546
+ returnContent: true,
547
+ skipCleanup: true,
548
+ tokenCounter,
549
+ customHandlers: {
550
+ [GraphEvents.ON_SUMMARIZE_START]: {
551
+ handle: (_event: string, data: t.StreamEventData): void => {
552
+ summarizeStarts.push(data);
553
+ },
554
+ },
555
+ },
556
+ });
557
+ if (!run.Graph) {
558
+ throw new Error('Expected graph to be initialized');
559
+ }
560
+ const model = new OverflowThenSucceedModel(
561
+ signatureFor('claude-haiku-4-5-20251001')
562
+ );
563
+ run.Graph.overrideModel = model;
564
+
565
+ const content = await run.processStream(
566
+ { messages: buildConversation(8) },
567
+ streamConfig
568
+ );
569
+
570
+ expect(content).toEqual([{ type: 'text', text: 'recovered' }]);
571
+ expect(model.calls).toHaveLength(2);
572
+ expect(summarizeStarts).toHaveLength(1);
573
+ });
574
+
575
+ it('keeps the corrected budget in provider units and seeds calibration', async () => {
576
+ /**
577
+ * The provider counted 274,468 for a prompt it caps at 200,000 — 1.37×
578
+ * over the provider ceiling. The corrected budget stays in provider units,
579
+ * and the provider/local ratio is installed on the pruner so it is applied
580
+ * exactly once on this retry and later tool-call turns.
581
+ */
582
+ const run = await createRun({
583
+ runId: 'overflow-recovery-proportional',
584
+ maxContextTokens: 1_000_000,
585
+ });
586
+ if (!run.Graph) {
587
+ throw new Error('Expected graph to be initialized');
588
+ }
589
+ const model = new OverflowThenSucceedModel(
590
+ signatureFor('claude-haiku-4-5-20251001')
591
+ );
592
+ run.Graph.overrideModel = model;
593
+
594
+ const messages = buildConversation(8);
595
+ const agentContext = run.Graph.agentContexts.get('default');
596
+ if (agentContext == null) {
597
+ throw new Error('Expected default agent context');
598
+ }
599
+ agentContext.calibrationRatio = 1.5;
600
+ await run.processStream({ messages }, streamConfig);
601
+
602
+ const uncalibratedPrompt = model.calls[0].length * TOKENS_PER_MESSAGE;
603
+ expect(agentContext.maxContextTokens).toBe(Math.floor(200_000 * 0.95));
604
+ expect(274_468 / uncalibratedPrompt).toBeLessThan(0.5);
605
+ expect(agentContext.calibrationRatio).toBe(0.5);
606
+ });
607
+
608
+ it('does not intercept errors compaction cannot fix', async () => {
609
+ const run = await createRun({
610
+ runId: 'overflow-recovery-unrelated',
611
+ maxContextTokens: 600_000,
612
+ });
613
+ if (!run.Graph) {
614
+ throw new Error('Expected graph to be initialized');
615
+ }
616
+ const model = new OverflowThenSucceedModel(
617
+ {
618
+ name: 'AuthenticationError',
619
+ status: 401,
620
+ message: '401 Incorrect API key provided.',
621
+ },
622
+ Number.MAX_SAFE_INTEGER
623
+ );
624
+ run.Graph.overrideModel = model;
625
+
626
+ await expect(
627
+ run.processStream({ messages: buildConversation(2) }, streamConfig)
628
+ ).rejects.toThrow(/Incorrect API key/);
629
+ expect(model.calls).toHaveLength(1);
630
+ });
631
+ });