@librechat/agents 3.1.73 → 3.1.75-dev.0
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.
- package/README.md +66 -0
- package/dist/cjs/agents/AgentContext.cjs +146 -57
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +13 -3
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/index.cjs +145 -52
- package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/types.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +25 -15
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_outputs.cjs +84 -70
- package/dist/cjs/llm/anthropic/utils/message_outputs.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/index.cjs +1 -1
- package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +213 -3
- package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/llm/bedrock/utils/message_outputs.cjs +2 -1
- package/dist/cjs/llm/bedrock/utils/message_outputs.cjs.map +1 -1
- package/dist/cjs/llm/google/utils/common.cjs +5 -4
- package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
- package/dist/cjs/llm/openai/index.cjs +468 -647
- package/dist/cjs/llm/openai/index.cjs.map +1 -1
- package/dist/cjs/llm/openai/utils/index.cjs +1 -448
- package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
- package/dist/cjs/llm/openrouter/index.cjs +57 -175
- package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
- package/dist/cjs/llm/vertexai/index.cjs +5 -3
- package/dist/cjs/llm/vertexai/index.cjs.map +1 -1
- package/dist/cjs/main.cjs +1 -0
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/cache.cjs +39 -4
- package/dist/cjs/messages/cache.cjs.map +1 -1
- package/dist/cjs/messages/core.cjs +7 -6
- package/dist/cjs/messages/core.cjs.map +1 -1
- package/dist/cjs/messages/format.cjs +7 -6
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/messages/langchain.cjs +26 -0
- package/dist/cjs/messages/langchain.cjs.map +1 -0
- package/dist/cjs/messages/prune.cjs +7 -6
- package/dist/cjs/messages/prune.cjs.map +1 -1
- package/dist/cjs/tools/BashExecutor.cjs +21 -11
- package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
- package/dist/cjs/tools/CodeExecutor.cjs +37 -10
- package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs +16 -11
- package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
- package/dist/cjs/tools/ToolNode.cjs +5 -1
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +147 -58
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +13 -3
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/llm/anthropic/index.mjs +146 -54
- package/dist/esm/llm/anthropic/index.mjs.map +1 -1
- package/dist/esm/llm/anthropic/types.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs +25 -15
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_outputs.mjs +84 -71
- package/dist/esm/llm/anthropic/utils/message_outputs.mjs.map +1 -1
- package/dist/esm/llm/bedrock/index.mjs +1 -1
- package/dist/esm/llm/bedrock/index.mjs.map +1 -1
- package/dist/esm/llm/bedrock/utils/message_inputs.mjs +214 -4
- package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/llm/bedrock/utils/message_outputs.mjs +2 -1
- package/dist/esm/llm/bedrock/utils/message_outputs.mjs.map +1 -1
- package/dist/esm/llm/google/utils/common.mjs +5 -4
- package/dist/esm/llm/google/utils/common.mjs.map +1 -1
- package/dist/esm/llm/openai/index.mjs +469 -648
- package/dist/esm/llm/openai/index.mjs.map +1 -1
- package/dist/esm/llm/openai/utils/index.mjs +4 -449
- package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
- package/dist/esm/llm/openrouter/index.mjs +57 -175
- package/dist/esm/llm/openrouter/index.mjs.map +1 -1
- package/dist/esm/llm/vertexai/index.mjs +5 -3
- package/dist/esm/llm/vertexai/index.mjs.map +1 -1
- package/dist/esm/main.mjs +1 -1
- package/dist/esm/messages/cache.mjs +39 -4
- package/dist/esm/messages/cache.mjs.map +1 -1
- package/dist/esm/messages/core.mjs +7 -6
- package/dist/esm/messages/core.mjs.map +1 -1
- package/dist/esm/messages/format.mjs +7 -6
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/messages/langchain.mjs +23 -0
- package/dist/esm/messages/langchain.mjs.map +1 -0
- package/dist/esm/messages/prune.mjs +7 -6
- package/dist/esm/messages/prune.mjs.map +1 -1
- package/dist/esm/tools/BashExecutor.mjs +22 -12
- package/dist/esm/tools/BashExecutor.mjs.map +1 -1
- package/dist/esm/tools/CodeExecutor.mjs +37 -11
- package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
- package/dist/esm/tools/ProgrammaticToolCalling.mjs +17 -12
- package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
- package/dist/esm/tools/ToolNode.mjs +5 -1
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/types/agents/AgentContext.d.ts +29 -4
- package/dist/types/agents/__tests__/promptCacheLiveHelpers.d.ts +46 -0
- package/dist/types/llm/anthropic/index.d.ts +22 -9
- package/dist/types/llm/anthropic/types.d.ts +5 -1
- package/dist/types/llm/anthropic/utils/message_outputs.d.ts +13 -6
- package/dist/types/llm/anthropic/utils/output_parsers.d.ts +1 -1
- package/dist/types/llm/openai/index.d.ts +21 -24
- package/dist/types/llm/openrouter/index.d.ts +11 -9
- package/dist/types/llm/vertexai/index.d.ts +1 -0
- package/dist/types/messages/cache.d.ts +4 -1
- package/dist/types/messages/langchain.d.ts +27 -0
- package/dist/types/tools/CodeExecutor.d.ts +6 -0
- package/dist/types/types/graph.d.ts +26 -38
- package/dist/types/types/llm.d.ts +3 -3
- package/dist/types/types/run.d.ts +2 -0
- package/dist/types/types/stream.d.ts +1 -1
- package/dist/types/types/tools.d.ts +9 -0
- package/package.json +17 -16
- package/src/agents/AgentContext.ts +189 -71
- package/src/agents/__tests__/AgentContext.anthropic.live.test.ts +116 -0
- package/src/agents/__tests__/AgentContext.bedrock.live.test.ts +149 -0
- package/src/agents/__tests__/AgentContext.test.ts +333 -2
- package/src/agents/__tests__/promptCacheLiveHelpers.ts +165 -0
- package/src/graphs/Graph.ts +24 -4
- package/src/graphs/__tests__/composition.smoke.test.ts +188 -0
- package/src/llm/anthropic/index.ts +252 -84
- package/src/llm/anthropic/llm.spec.ts +751 -102
- package/src/llm/anthropic/types.ts +9 -1
- package/src/llm/anthropic/utils/message_inputs.ts +43 -20
- package/src/llm/anthropic/utils/message_outputs.ts +119 -101
- package/src/llm/anthropic/utils/server-tool-inputs.test.ts +77 -0
- package/src/llm/bedrock/index.ts +2 -2
- package/src/llm/bedrock/llm.spec.ts +341 -0
- package/src/llm/bedrock/utils/message_inputs.ts +303 -4
- package/src/llm/bedrock/utils/message_outputs.ts +2 -1
- package/src/llm/custom-chat-models.smoke.test.ts +662 -0
- package/src/llm/google/llm.spec.ts +339 -57
- package/src/llm/google/utils/common.ts +53 -48
- package/src/llm/openai/contentBlocks.test.ts +346 -0
- package/src/llm/openai/index.ts +736 -837
- package/src/llm/openai/utils/index.ts +84 -64
- package/src/llm/openrouter/index.ts +124 -247
- package/src/llm/openrouter/reasoning.test.ts +8 -1
- package/src/llm/vertexai/index.ts +11 -5
- package/src/llm/vertexai/llm.spec.ts +28 -1
- package/src/messages/cache.test.ts +106 -4
- package/src/messages/cache.ts +57 -5
- package/src/messages/core.ts +16 -9
- package/src/messages/format.ts +9 -6
- package/src/messages/langchain.ts +39 -0
- package/src/messages/prune.ts +12 -8
- package/src/scripts/caching.ts +2 -3
- package/src/specs/anthropic.simple.test.ts +61 -0
- package/src/specs/summarization.test.ts +58 -61
- package/src/tools/BashExecutor.ts +37 -13
- package/src/tools/CodeExecutor.ts +55 -11
- package/src/tools/ProgrammaticToolCalling.ts +29 -14
- package/src/tools/ToolNode.ts +5 -1
- package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +60 -0
- package/src/types/graph.ts +35 -88
- package/src/types/llm.ts +3 -3
- package/src/types/run.ts +2 -0
- package/src/types/stream.ts +1 -1
- package/src/types/tools.ts +9 -0
- package/src/utils/llmConfig.ts +1 -6
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { HumanMessage, SystemMessage } from '@langchain/core/messages';
|
|
2
2
|
import { RunnableLambda } from '@langchain/core/runnables';
|
|
3
3
|
import { ANTHROPIC_TOOL_TOKEN_MULTIPLIER, DEFAULT_TOOL_TOKEN_MULTIPLIER } from '../common/constants.mjs';
|
|
4
4
|
import { ContentTypes, Providers } from '../common/enum.mjs';
|
|
@@ -190,7 +190,7 @@ class AgentContext {
|
|
|
190
190
|
summaryTokenCount = 0;
|
|
191
191
|
/**
|
|
192
192
|
* Where the summary should be injected:
|
|
193
|
-
* - `'system_prompt'`: cross-run summary, included in
|
|
193
|
+
* - `'system_prompt'`: cross-run summary, included in the dynamic system tail
|
|
194
194
|
* - `'user_message'`: mid-run compaction, injected as HumanMessage on clean slate
|
|
195
195
|
* - `'none'`: no summary present
|
|
196
196
|
*/
|
|
@@ -296,15 +296,18 @@ class AgentContext {
|
|
|
296
296
|
}
|
|
297
297
|
/**
|
|
298
298
|
* Gets the system runnable, creating it lazily if needed.
|
|
299
|
-
* Includes instructions, additional instructions, and
|
|
299
|
+
* Includes stable instructions, dynamic additional instructions, and
|
|
300
|
+
* programmatic-only tools documentation.
|
|
300
301
|
* Only rebuilds when marked stale (via markToolsAsDiscovered).
|
|
301
302
|
*/
|
|
302
303
|
get systemRunnable() {
|
|
303
304
|
if (!this.systemRunnableStale && this.cachedSystemRunnable !== undefined) {
|
|
304
305
|
return this.cachedSystemRunnable;
|
|
305
306
|
}
|
|
306
|
-
|
|
307
|
-
|
|
307
|
+
this.cachedSystemRunnable = this.buildSystemRunnable({
|
|
308
|
+
stableInstructions: this.buildStableInstructionsString(),
|
|
309
|
+
dynamicInstructions: this.buildDynamicInstructionsString(),
|
|
310
|
+
});
|
|
308
311
|
this.systemRunnableStale = false;
|
|
309
312
|
return this.cachedSystemRunnable;
|
|
310
313
|
}
|
|
@@ -314,16 +317,18 @@ class AgentContext {
|
|
|
314
317
|
*/
|
|
315
318
|
initializeSystemRunnable() {
|
|
316
319
|
if (this.systemRunnableStale || this.cachedSystemRunnable === undefined) {
|
|
317
|
-
|
|
318
|
-
|
|
320
|
+
this.cachedSystemRunnable = this.buildSystemRunnable({
|
|
321
|
+
stableInstructions: this.buildStableInstructionsString(),
|
|
322
|
+
dynamicInstructions: this.buildDynamicInstructionsString(),
|
|
323
|
+
});
|
|
319
324
|
this.systemRunnableStale = false;
|
|
320
325
|
}
|
|
321
326
|
}
|
|
322
327
|
/**
|
|
323
|
-
* Builds the
|
|
328
|
+
* Builds the cacheable instructions string (without creating SystemMessage).
|
|
324
329
|
* Includes agent identity preamble and handoff context when available.
|
|
325
330
|
*/
|
|
326
|
-
|
|
331
|
+
buildStableInstructionsString() {
|
|
327
332
|
const parts = [];
|
|
328
333
|
const identityPreamble = this.buildIdentityPreamble();
|
|
329
334
|
if (identityPreamble) {
|
|
@@ -332,17 +337,27 @@ class AgentContext {
|
|
|
332
337
|
if (this.instructions != null && this.instructions !== '') {
|
|
333
338
|
parts.push(this.instructions);
|
|
334
339
|
}
|
|
335
|
-
if (this.additionalInstructions != null &&
|
|
336
|
-
this.additionalInstructions !== '') {
|
|
337
|
-
parts.push(this.additionalInstructions);
|
|
338
|
-
}
|
|
339
340
|
const programmaticToolsDoc = this.buildProgrammaticOnlyToolsInstructions();
|
|
340
341
|
if (programmaticToolsDoc) {
|
|
341
342
|
parts.push(programmaticToolsDoc);
|
|
342
343
|
}
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
344
|
+
return parts.join('\n\n');
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Builds the dynamic system-tail string (without creating SystemMessage).
|
|
348
|
+
* Keep this out of prompt-cache-marked content so volatile context does not
|
|
349
|
+
* invalidate the stable prefix.
|
|
350
|
+
*/
|
|
351
|
+
buildDynamicInstructionsString() {
|
|
352
|
+
const parts = [];
|
|
353
|
+
if (this.additionalInstructions != null &&
|
|
354
|
+
this.additionalInstructions !== '') {
|
|
355
|
+
parts.push(this.additionalInstructions);
|
|
356
|
+
}
|
|
357
|
+
// Cross-run summary: include in the system tail so the model has context
|
|
358
|
+
// from the prior run without invalidating the cacheable prefix. Mid-run
|
|
359
|
+
// summaries are injected as a HumanMessage on the post-compaction clean
|
|
360
|
+
// slate instead (see buildSystemRunnable).
|
|
346
361
|
if (this._summaryLocation === 'system_prompt' &&
|
|
347
362
|
this.summaryText != null &&
|
|
348
363
|
this.summaryText !== '') {
|
|
@@ -373,34 +388,20 @@ class AgentContext {
|
|
|
373
388
|
* Build system runnable from pre-built instructions string.
|
|
374
389
|
* Only called when content has actually changed.
|
|
375
390
|
*/
|
|
376
|
-
buildSystemRunnable(
|
|
391
|
+
buildSystemRunnable({ stableInstructions, dynamicInstructions, }) {
|
|
377
392
|
const hasMidRunSummary = this._summaryLocation === 'user_message' &&
|
|
378
393
|
this.summaryText != null &&
|
|
379
394
|
this.summaryText !== '';
|
|
380
|
-
if (!
|
|
395
|
+
if (!stableInstructions && !dynamicInstructions && !hasMidRunSummary) {
|
|
381
396
|
this.systemMessageTokens = 0;
|
|
382
397
|
return undefined;
|
|
383
398
|
}
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
finalInstructions = {
|
|
391
|
-
content: [
|
|
392
|
-
{
|
|
393
|
-
type: 'text',
|
|
394
|
-
text: instructionsString,
|
|
395
|
-
cache_control: { type: 'ephemeral' },
|
|
396
|
-
},
|
|
397
|
-
],
|
|
398
|
-
};
|
|
399
|
-
}
|
|
400
|
-
}
|
|
401
|
-
const systemMessage = instructionsString
|
|
402
|
-
? new SystemMessage(finalInstructions)
|
|
403
|
-
: undefined;
|
|
399
|
+
const usePromptCache = this.hasAnthropicPromptCache();
|
|
400
|
+
const systemMessage = this.buildSystemMessage({
|
|
401
|
+
stableInstructions,
|
|
402
|
+
dynamicInstructions,
|
|
403
|
+
usePromptCache,
|
|
404
|
+
});
|
|
404
405
|
if (this.tokenCounter) {
|
|
405
406
|
this.systemMessageTokens = systemMessage
|
|
406
407
|
? this.tokenCounter(systemMessage)
|
|
@@ -442,6 +443,52 @@ class AgentContext {
|
|
|
442
443
|
return [...prefix, ...body];
|
|
443
444
|
}).withConfig({ runName: 'prompt' });
|
|
444
445
|
}
|
|
446
|
+
hasAnthropicPromptCache() {
|
|
447
|
+
if (this.provider !== Providers.ANTHROPIC) {
|
|
448
|
+
return false;
|
|
449
|
+
}
|
|
450
|
+
const anthropicOptions = this.clientOptions;
|
|
451
|
+
return anthropicOptions?.promptCache === true;
|
|
452
|
+
}
|
|
453
|
+
hasBedrockPromptCache() {
|
|
454
|
+
if (this.provider !== Providers.BEDROCK) {
|
|
455
|
+
return false;
|
|
456
|
+
}
|
|
457
|
+
const bedrockOptions = this.clientOptions;
|
|
458
|
+
return bedrockOptions?.promptCache === true;
|
|
459
|
+
}
|
|
460
|
+
buildSystemMessage({ stableInstructions, dynamicInstructions, usePromptCache, }) {
|
|
461
|
+
if (!stableInstructions && !dynamicInstructions) {
|
|
462
|
+
return undefined;
|
|
463
|
+
}
|
|
464
|
+
if (usePromptCache) {
|
|
465
|
+
const content = [];
|
|
466
|
+
if (stableInstructions) {
|
|
467
|
+
content.push({
|
|
468
|
+
type: 'text',
|
|
469
|
+
text: stableInstructions,
|
|
470
|
+
cache_control: { type: 'ephemeral' },
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
if (dynamicInstructions) {
|
|
474
|
+
content.push({ type: 'text', text: dynamicInstructions });
|
|
475
|
+
}
|
|
476
|
+
return new SystemMessage({ content });
|
|
477
|
+
}
|
|
478
|
+
if (this.hasBedrockPromptCache() && stableInstructions) {
|
|
479
|
+
const content = [
|
|
480
|
+
{ type: 'text', text: stableInstructions },
|
|
481
|
+
{ cachePoint: { type: 'default' } },
|
|
482
|
+
];
|
|
483
|
+
if (dynamicInstructions) {
|
|
484
|
+
content.push({ type: 'text', text: dynamicInstructions });
|
|
485
|
+
}
|
|
486
|
+
return new SystemMessage({ content });
|
|
487
|
+
}
|
|
488
|
+
return new SystemMessage([stableInstructions, dynamicInstructions]
|
|
489
|
+
.filter((part) => part !== '')
|
|
490
|
+
.join('\n\n'));
|
|
491
|
+
}
|
|
445
492
|
/**
|
|
446
493
|
* Reset context for a new run
|
|
447
494
|
*/
|
|
@@ -503,7 +550,44 @@ class AgentContext {
|
|
|
503
550
|
if (!this.toolDefinitions) {
|
|
504
551
|
return [];
|
|
505
552
|
}
|
|
506
|
-
|
|
553
|
+
/**
|
|
554
|
+
* Mirror `getEventDrivenToolsForBinding`'s gate: a definition is only
|
|
555
|
+
* bound to the model when its `allowed_callers` include `'direct'` and
|
|
556
|
+
* (if deferred) it has been discovered. Filtering by `defer_loading`
|
|
557
|
+
* alone left programmatic-only definitions counted in
|
|
558
|
+
* `toolSchemaTokens` even though they were never bound.
|
|
559
|
+
*/
|
|
560
|
+
return this.toolDefinitions.filter((def) => {
|
|
561
|
+
const allowedCallers = def.allowed_callers ?? ['direct'];
|
|
562
|
+
if (!allowedCallers.includes('direct')) {
|
|
563
|
+
return false;
|
|
564
|
+
}
|
|
565
|
+
return (def.defer_loading !== true || this.discoveredToolNames.has(def.name));
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* Single source of truth for "which entries of `this.tools` should be
|
|
570
|
+
* treated as actually bound". Callers:
|
|
571
|
+
* - `getToolsForBinding` (non-event-driven branch)
|
|
572
|
+
* - `getEventDrivenToolsForBinding` (appends instance tools alongside
|
|
573
|
+
* schema-only definitions)
|
|
574
|
+
* - `calculateInstructionTokens` (counts schema bytes for accounting)
|
|
575
|
+
*
|
|
576
|
+
* In event-driven mode (`toolDefinitions` present) instance tools are
|
|
577
|
+
* appended unfiltered; outside event-driven mode they pass through
|
|
578
|
+
* `filterToolsForBinding`. Centralizing the decision here prevents the
|
|
579
|
+
* accounting/binding paths from drifting apart, which was the root
|
|
580
|
+
* cause of the original miscount.
|
|
581
|
+
*/
|
|
582
|
+
getEffectiveInstanceTools() {
|
|
583
|
+
if (!this.tools) {
|
|
584
|
+
return undefined;
|
|
585
|
+
}
|
|
586
|
+
const isEventDriven = (this.toolDefinitions?.length ?? 0) > 0;
|
|
587
|
+
if (isEventDriven || !this.toolRegistry) {
|
|
588
|
+
return this.tools;
|
|
589
|
+
}
|
|
590
|
+
return this.filterToolsForBinding(this.tools);
|
|
507
591
|
}
|
|
508
592
|
/**
|
|
509
593
|
* Calculate tool tokens and add to instruction tokens
|
|
@@ -518,9 +602,17 @@ class AgentContext {
|
|
|
518
602
|
* populated after `fromConfig()` kicks off the initial calculation, so
|
|
519
603
|
* callers that mutate `graphTools` must re-trigger this method to
|
|
520
604
|
* refresh `toolSchemaTokens`.
|
|
605
|
+
*
|
|
606
|
+
* Use `getEffectiveInstanceTools()` so accounting reflects exactly the
|
|
607
|
+
* subset that `getToolsForBinding` would emit — preventing the
|
|
608
|
+
* worst-case-ceiling miscount that triggered spurious `empty_messages`
|
|
609
|
+
* preflight rejections at low `maxContextTokens`. Deferred and
|
|
610
|
+
* non-`'direct'` `toolDefinitions` are excluded by
|
|
611
|
+
* `getActiveToolDefinitions()` below.
|
|
521
612
|
*/
|
|
522
613
|
const instanceTools = [
|
|
523
|
-
...(this.
|
|
614
|
+
...(this.getEffectiveInstanceTools() ??
|
|
615
|
+
[]),
|
|
524
616
|
...(this.graphTools ?? []),
|
|
525
617
|
];
|
|
526
618
|
if (instanceTools.length > 0) {
|
|
@@ -680,7 +772,16 @@ class AgentContext {
|
|
|
680
772
|
*/
|
|
681
773
|
getTokenBudgetBreakdown(messages) {
|
|
682
774
|
const maxContextTokens = this.maxContextTokens ?? 0;
|
|
683
|
-
|
|
775
|
+
/**
|
|
776
|
+
* Derive `toolCount` from `getToolsForBinding()` so the diagnostic stays
|
|
777
|
+
* aligned with what is actually bound to the model — and with what
|
|
778
|
+
* `calculateInstructionTokens` counts into `toolSchemaTokens`. Using raw
|
|
779
|
+
* `this.tools.length` would inflate the count whenever the registry
|
|
780
|
+
* marks instance tools as deferred-undiscovered or non-`'direct'`,
|
|
781
|
+
* producing the same misleading "N tools" diagnostic this fix is meant
|
|
782
|
+
* to eliminate.
|
|
783
|
+
*/
|
|
784
|
+
const toolCount = this.getToolsForBinding()?.length ?? 0;
|
|
684
785
|
const messageCount = messages?.length ?? 0;
|
|
685
786
|
let messageTokens = 0;
|
|
686
787
|
if (messages != null) {
|
|
@@ -778,9 +879,7 @@ class AgentContext {
|
|
|
778
879
|
if (this.toolDefinitions && this.toolDefinitions.length > 0) {
|
|
779
880
|
return this.getEventDrivenToolsForBinding();
|
|
780
881
|
}
|
|
781
|
-
const filtered =
|
|
782
|
-
? this.tools
|
|
783
|
-
: this.filterToolsForBinding(this.tools);
|
|
882
|
+
const filtered = this.getEffectiveInstanceTools();
|
|
784
883
|
if (this.graphTools && this.graphTools.length > 0) {
|
|
785
884
|
return [...(filtered ?? []), ...this.graphTools];
|
|
786
885
|
}
|
|
@@ -791,24 +890,14 @@ class AgentContext {
|
|
|
791
890
|
if (!this.toolDefinitions) {
|
|
792
891
|
return this.graphTools ?? [];
|
|
793
892
|
}
|
|
794
|
-
const
|
|
795
|
-
const allowedCallers = def.allowed_callers ?? ['direct'];
|
|
796
|
-
if (!allowedCallers.includes('direct')) {
|
|
797
|
-
return false;
|
|
798
|
-
}
|
|
799
|
-
if (def.defer_loading === true &&
|
|
800
|
-
!this.discoveredToolNames.has(def.name)) {
|
|
801
|
-
return false;
|
|
802
|
-
}
|
|
803
|
-
return true;
|
|
804
|
-
});
|
|
805
|
-
const schemaTools = createSchemaOnlyTools(defsToInclude);
|
|
893
|
+
const schemaTools = createSchemaOnlyTools(this.getActiveToolDefinitions());
|
|
806
894
|
const allTools = [...schemaTools];
|
|
807
895
|
if (this.graphTools && this.graphTools.length > 0) {
|
|
808
896
|
allTools.push(...this.graphTools);
|
|
809
897
|
}
|
|
810
|
-
|
|
811
|
-
|
|
898
|
+
const instanceTools = this.getEffectiveInstanceTools();
|
|
899
|
+
if (instanceTools && instanceTools.length > 0) {
|
|
900
|
+
allTools.push(...instanceTools);
|
|
812
901
|
}
|
|
813
902
|
return allTools;
|
|
814
903
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AgentContext.mjs","sources":["../../../src/agents/AgentContext.ts"],"sourcesContent":["/* eslint-disable no-console */\nimport { HumanMessage, SystemMessage } from '@langchain/core/messages';\nimport { RunnableLambda } from '@langchain/core/runnables';\nimport type {\n UsageMetadata,\n BaseMessage,\n BaseMessageFields,\n} from '@langchain/core/messages';\nimport type { RunnableConfig, Runnable } from '@langchain/core/runnables';\nimport type { createPruneMessages } from '@/messages';\nimport type * as t from '@/types';\nimport {\n ANTHROPIC_TOOL_TOKEN_MULTIPLIER,\n DEFAULT_TOOL_TOKEN_MULTIPLIER,\n ContentTypes,\n Providers,\n} from '@/common';\nimport { createSchemaOnlyTools } from '@/tools/schema';\nimport { addCacheControl } from '@/messages/cache';\nimport { DEFAULT_RESERVE_RATIO } from '@/messages';\nimport { toJsonSchema } from '@/utils/schema';\n\n/**\n * Encapsulates agent-specific state that can vary between agents in a multi-agent system\n */\nexport class AgentContext {\n /**\n * Create an AgentContext from configuration with token accounting initialization\n */\n static fromConfig(\n agentConfig: t.AgentInputs,\n tokenCounter?: t.TokenCounter,\n indexTokenCountMap?: Record<string, number>\n ): AgentContext {\n const {\n agentId,\n name,\n provider,\n clientOptions,\n tools,\n toolMap,\n toolEnd,\n toolRegistry,\n toolDefinitions,\n instructions,\n additional_instructions,\n streamBuffer,\n maxContextTokens,\n reasoningKey,\n useLegacyContent,\n discoveredTools,\n summarizationEnabled,\n summarizationConfig,\n initialSummary,\n contextPruningConfig,\n maxToolResultChars,\n toolSchemaTokens,\n subagentConfigs,\n maxSubagentDepth,\n } = agentConfig;\n\n const agentContext = new AgentContext({\n agentId,\n name: name ?? agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tools,\n toolMap,\n toolRegistry,\n toolDefinitions,\n instructions,\n additionalInstructions: additional_instructions,\n reasoningKey,\n toolEnd,\n instructionTokens: 0,\n tokenCounter,\n useLegacyContent,\n discoveredTools,\n summarizationEnabled,\n summarizationConfig,\n contextPruningConfig,\n maxToolResultChars,\n });\n\n agentContext._sourceInputs = agentConfig;\n agentContext.subagentConfigs = subagentConfigs;\n agentContext.maxSubagentDepth = maxSubagentDepth;\n\n if (initialSummary?.text != null && initialSummary.text !== '') {\n agentContext.setInitialSummary(\n initialSummary.text,\n initialSummary.tokenCount\n );\n }\n\n if (tokenCounter) {\n agentContext.initializeSystemRunnable();\n\n const tokenMap = indexTokenCountMap || {};\n agentContext.baseIndexTokenCountMap = { ...tokenMap };\n agentContext.indexTokenCountMap = tokenMap;\n\n if (toolSchemaTokens != null && toolSchemaTokens > 0) {\n /** Use pre-computed (cached) tool schema tokens — skip calculateInstructionTokens */\n agentContext.toolSchemaTokens = toolSchemaTokens;\n agentContext.tokenCalculationPromise = Promise.resolve();\n agentContext.updateTokenMapWithInstructions(tokenMap);\n } else {\n agentContext.tokenCalculationPromise = agentContext\n .calculateInstructionTokens(tokenCounter)\n .then(() => {\n agentContext.updateTokenMapWithInstructions(tokenMap);\n })\n .catch((err) => {\n console.error('Error calculating instruction tokens:', err);\n });\n }\n } else if (indexTokenCountMap) {\n agentContext.baseIndexTokenCountMap = { ...indexTokenCountMap };\n agentContext.indexTokenCountMap = indexTokenCountMap;\n }\n\n return agentContext;\n }\n\n /** Agent identifier */\n agentId: string;\n /** Human-readable name for this agent (used in handoff context). Falls back to agentId if not provided. */\n name?: string;\n /** Provider for this specific agent */\n provider: Providers;\n /** Client options for this agent */\n clientOptions?: t.ClientOptions;\n /** Token count map indexed by message position */\n indexTokenCountMap: Record<string, number | undefined> = {};\n /** Canonical pre-run token map used to restore token accounting on reset */\n baseIndexTokenCountMap: Record<string, number> = {};\n /** Maximum context tokens for this agent */\n maxContextTokens?: number;\n /** Current usage metadata for this agent */\n currentUsage?: Partial<UsageMetadata>;\n /**\n * Usage from the most recent LLM call only (not accumulated).\n * Used for accurate provider calibration in pruning.\n */\n lastCallUsage?: {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n cacheRead?: number;\n cacheCreation?: number;\n };\n /**\n * Whether totalTokens data is fresh (set true when provider usage arrives,\n * false at the start of each turn before the LLM responds).\n * Prevents stale token data from driving pruning/trigger decisions.\n */\n totalTokensFresh: boolean = false;\n /** Context pruning configuration. */\n contextPruningConfig?: t.ContextPruningConfig;\n maxToolResultChars?: number;\n /** Prune messages function configured for this agent */\n pruneMessages?: ReturnType<typeof createPruneMessages>;\n /** Token counter function for this agent */\n tokenCounter?: t.TokenCounter;\n /** Token count for the system message (instructions text). */\n systemMessageTokens: number = 0;\n /** Token count for tool schemas only. */\n toolSchemaTokens: number = 0;\n /** Running calibration ratio from the pruner — persisted across runs via contextMeta. */\n calibrationRatio: number = 1;\n /** Provider-observed instruction overhead from the pruner's best-variance turn. */\n resolvedInstructionOverhead?: number;\n /** Pre-masking tool content keyed by message index, consumed by the summarize node. */\n pendingOriginalToolContent?: Map<number, string>;\n\n /** Total instruction overhead: system message + tool schemas + pending summary. */\n get instructionTokens(): number {\n const summaryOverhead =\n this._summaryLocation === 'user_message' ? this.summaryTokenCount : 0;\n return this.systemMessageTokens + this.toolSchemaTokens + summaryOverhead;\n }\n /** The amount of time that should pass before another consecutive API call */\n streamBuffer?: number;\n /** Last stream call timestamp for rate limiting */\n lastStreamCall?: number;\n /** Tools available to this agent */\n tools?: t.GraphTools;\n /** Graph-managed tools (e.g., handoff tools created by MultiAgentGraph) that bypass event-driven dispatch */\n graphTools?: t.GraphTools;\n /** Tool map for this agent */\n toolMap?: t.ToolMap;\n /**\n * Tool definitions registry (includes deferred and programmatic tool metadata).\n * Used for tool search and programmatic tool calling.\n */\n toolRegistry?: t.LCToolRegistry;\n /**\n * Serializable tool definitions for event-driven execution.\n * When provided, ToolNode operates in event-driven mode.\n */\n toolDefinitions?: t.LCTool[];\n /** Set of tool names discovered via tool search (to be loaded) */\n discoveredToolNames: Set<string> = new Set();\n /** Original AgentInputs used to create this context — used for self-spawn subagent resolution. */\n _sourceInputs?: t.AgentInputs;\n /** Subagent configurations for hierarchical delegation. */\n subagentConfigs?: t.SubagentConfig[];\n /** Maximum subagent nesting depth. */\n maxSubagentDepth?: number;\n /** Instructions for this agent */\n instructions?: string;\n /** Additional instructions for this agent */\n additionalInstructions?: string;\n /** Reasoning key for this agent */\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n /** Last token for reasoning detection */\n lastToken?: string;\n /** Token type switch state */\n tokenTypeSwitch?: 'reasoning' | 'content';\n /** Tracks how many reasoning→text transitions have occurred (ensures unique post-reasoning step keys) */\n reasoningTransitionCount = 0;\n /** Current token type being processed */\n currentTokenType: ContentTypes.TEXT | ContentTypes.THINK | 'think_and_text' =\n ContentTypes.TEXT;\n /** Whether tools should end the workflow */\n toolEnd: boolean = false;\n /** Cached system runnable (created lazily) */\n private cachedSystemRunnable?: Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >;\n /** Whether system runnable needs rebuild (set when discovered tools change) */\n private systemRunnableStale: boolean = true;\n /** Promise for token calculation initialization */\n tokenCalculationPromise?: Promise<void>;\n /** Format content blocks as strings (for legacy compatibility) */\n useLegacyContent: boolean = false;\n /** Enables graph-level summarization for this agent */\n summarizationEnabled?: boolean;\n /** Summarization runtime settings used by graph pruning hooks */\n summarizationConfig?: t.SummarizationConfig;\n /** Current summary text produced by the summarize node, integrated into system message */\n private summaryText?: string;\n /** Token count of the current summary (tracked for token accounting) */\n private summaryTokenCount: number = 0;\n /**\n * Where the summary should be injected:\n * - `'system_prompt'`: cross-run summary, included in `buildInstructionsString`\n * - `'user_message'`: mid-run compaction, injected as HumanMessage on clean slate\n * - `'none'`: no summary present\n */\n private _summaryLocation: 'system_prompt' | 'user_message' | 'none' = 'none';\n /**\n * Durable summary that survives reset() calls. Set from initialSummary\n * during fromConfig() and updated by setSummary() so that the latest\n * summary (whether cross-run or intra-run) is always restored after\n * processStream's resetValues() cycle.\n */\n private _durableSummaryText?: string;\n private _durableSummaryTokenCount: number = 0;\n /** Number of summarization cycles that have occurred for this agent context */\n private _summaryVersion: number = 0;\n /**\n * Message count at the time summarization was last triggered.\n * Used to prevent re-summarizing the same unchanged message set.\n * Summarization is allowed to fire again only when new messages appear.\n */\n private _lastSummarizationMsgCount: number = 0;\n /**\n * Handoff context when this agent receives control via handoff.\n * Contains source and parallel execution info for system message context.\n */\n handoffContext?: {\n /** Source agent that transferred control */\n sourceAgentName: string;\n /** Names of sibling agents executing in parallel (empty if sequential) */\n parallelSiblings: string[];\n };\n\n constructor({\n agentId,\n name,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tokenCounter,\n tools,\n toolMap,\n toolRegistry,\n toolDefinitions,\n instructions,\n additionalInstructions,\n reasoningKey,\n toolEnd,\n instructionTokens,\n useLegacyContent,\n discoveredTools,\n summarizationEnabled,\n summarizationConfig,\n contextPruningConfig,\n maxToolResultChars,\n }: {\n agentId: string;\n name?: string;\n provider: Providers;\n clientOptions?: t.ClientOptions;\n maxContextTokens?: number;\n streamBuffer?: number;\n tokenCounter?: t.TokenCounter;\n tools?: t.GraphTools;\n toolMap?: t.ToolMap;\n toolRegistry?: t.LCToolRegistry;\n toolDefinitions?: t.LCTool[];\n instructions?: string;\n additionalInstructions?: string;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n toolEnd?: boolean;\n instructionTokens?: number;\n useLegacyContent?: boolean;\n discoveredTools?: string[];\n summarizationEnabled?: boolean;\n summarizationConfig?: t.SummarizationConfig;\n contextPruningConfig?: t.ContextPruningConfig;\n maxToolResultChars?: number;\n }) {\n this.agentId = agentId;\n this.name = name;\n this.provider = provider;\n this.clientOptions = clientOptions;\n this.maxContextTokens = maxContextTokens;\n this.streamBuffer = streamBuffer;\n this.tokenCounter = tokenCounter;\n this.tools = tools;\n this.toolMap = toolMap;\n this.toolRegistry = toolRegistry;\n this.toolDefinitions = toolDefinitions;\n this.instructions = instructions;\n this.additionalInstructions = additionalInstructions;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (toolEnd !== undefined) {\n this.toolEnd = toolEnd;\n }\n if (instructionTokens !== undefined) {\n this.systemMessageTokens = instructionTokens;\n }\n\n this.useLegacyContent = useLegacyContent ?? false;\n this.summarizationEnabled = summarizationEnabled;\n this.summarizationConfig = summarizationConfig;\n this.contextPruningConfig = contextPruningConfig;\n this.maxToolResultChars = maxToolResultChars;\n\n if (discoveredTools && discoveredTools.length > 0) {\n for (const toolName of discoveredTools) {\n this.discoveredToolNames.add(toolName);\n }\n }\n }\n\n /**\n * Builds instructions text for tools that are ONLY callable via programmatic code execution.\n * These tools cannot be called directly by the LLM but are available through the\n * run_tools_with_code tool.\n *\n * Includes:\n * - Code_execution-only tools that are NOT deferred\n * - Code_execution-only tools that ARE deferred but have been discovered via tool search\n */\n private buildProgrammaticOnlyToolsInstructions(): string {\n if (!this.toolRegistry) return '';\n\n const programmaticOnlyTools: t.LCTool[] = [];\n for (const [name, toolDef] of this.toolRegistry) {\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n const isCodeExecutionOnly =\n allowedCallers.includes('code_execution') &&\n !allowedCallers.includes('direct');\n\n if (!isCodeExecutionOnly) continue;\n\n const isDeferred = toolDef.defer_loading === true;\n const isDiscovered = this.discoveredToolNames.has(name);\n if (!isDeferred || isDiscovered) {\n programmaticOnlyTools.push(toolDef);\n }\n }\n\n if (programmaticOnlyTools.length === 0) return '';\n\n const toolDescriptions = programmaticOnlyTools\n .map((tool) => {\n let desc = `- **${tool.name}**`;\n if (tool.description != null && tool.description !== '') {\n desc += `: ${tool.description}`;\n }\n if (tool.parameters) {\n desc += `\\n Parameters: ${JSON.stringify(tool.parameters, null, 2).replace(/\\n/g, '\\n ')}`;\n }\n return desc;\n })\n .join('\\n\\n');\n\n return (\n '\\n\\n## Programmatic-Only Tools\\n\\n' +\n 'The following tools are available exclusively through the `run_tools_with_code` tool. ' +\n 'You cannot call these tools directly; instead, use `run_tools_with_code` with Python code that invokes them.\\n\\n' +\n toolDescriptions\n );\n }\n\n /**\n * Gets the system runnable, creating it lazily if needed.\n * Includes instructions, additional instructions, and programmatic-only tools documentation.\n * Only rebuilds when marked stale (via markToolsAsDiscovered).\n */\n get systemRunnable():\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n if (!this.systemRunnableStale && this.cachedSystemRunnable !== undefined) {\n return this.cachedSystemRunnable;\n }\n\n const instructionsString = this.buildInstructionsString();\n this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);\n this.systemRunnableStale = false;\n return this.cachedSystemRunnable;\n }\n\n /**\n * Explicitly initializes the system runnable.\n * Call this before async token calculation to ensure system message tokens are counted first.\n */\n initializeSystemRunnable(): void {\n if (this.systemRunnableStale || this.cachedSystemRunnable === undefined) {\n const instructionsString = this.buildInstructionsString();\n this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);\n this.systemRunnableStale = false;\n }\n }\n\n /**\n * Builds the raw instructions string (without creating SystemMessage).\n * Includes agent identity preamble and handoff context when available.\n */\n private buildInstructionsString(): string {\n const parts: string[] = [];\n\n const identityPreamble = this.buildIdentityPreamble();\n if (identityPreamble) {\n parts.push(identityPreamble);\n }\n\n if (this.instructions != null && this.instructions !== '') {\n parts.push(this.instructions);\n }\n\n if (\n this.additionalInstructions != null &&\n this.additionalInstructions !== ''\n ) {\n parts.push(this.additionalInstructions);\n }\n\n const programmaticToolsDoc = this.buildProgrammaticOnlyToolsInstructions();\n if (programmaticToolsDoc) {\n parts.push(programmaticToolsDoc);\n }\n\n // Cross-run summary: include in system prompt so the model has context\n // from the prior run. Mid-run summaries are injected as a HumanMessage\n // on the post-compaction clean slate instead (see buildSystemRunnable).\n if (\n this._summaryLocation === 'system_prompt' &&\n this.summaryText != null &&\n this.summaryText !== ''\n ) {\n parts.push('## Conversation Summary\\n\\n' + this.summaryText);\n }\n\n return parts.join('\\n\\n');\n }\n\n /**\n * Builds the agent identity preamble including handoff context if present.\n * This helps the agent understand its role in the multi-agent workflow.\n */\n private buildIdentityPreamble(): string {\n if (!this.handoffContext) return '';\n\n const displayName = this.name ?? this.agentId;\n const { sourceAgentName, parallelSiblings } = this.handoffContext;\n const isParallel = parallelSiblings.length > 0;\n\n const lines: string[] = [];\n lines.push('## Multi-Agent Workflow');\n lines.push(\n `You are \"${displayName}\", transferred from \"${sourceAgentName}\".`\n );\n\n if (isParallel) {\n lines.push(`Running in parallel with: ${parallelSiblings.join(', ')}.`);\n }\n\n lines.push(\n 'Execute only tasks relevant to your role. Routing is already handled if requested, unless you can route further.'\n );\n\n return lines.join('\\n');\n }\n\n /**\n * Build system runnable from pre-built instructions string.\n * Only called when content has actually changed.\n */\n private buildSystemRunnable(\n instructionsString: string\n ):\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n const hasMidRunSummary =\n this._summaryLocation === 'user_message' &&\n this.summaryText != null &&\n this.summaryText !== '';\n\n if (!instructionsString && !hasMidRunSummary) {\n this.systemMessageTokens = 0;\n return undefined;\n }\n\n let finalInstructions: string | BaseMessageFields = instructionsString;\n\n let usePromptCache = false;\n if (this.provider === Providers.ANTHROPIC) {\n const anthropicOptions = this.clientOptions as\n | t.AnthropicClientOptions\n | undefined;\n if (anthropicOptions?.promptCache === true) {\n usePromptCache = true;\n finalInstructions = {\n content: [\n {\n type: 'text',\n text: instructionsString,\n cache_control: { type: 'ephemeral' },\n },\n ],\n };\n }\n }\n\n const systemMessage = instructionsString\n ? new SystemMessage(finalInstructions)\n : undefined;\n\n if (this.tokenCounter) {\n this.systemMessageTokens = systemMessage\n ? this.tokenCounter(systemMessage)\n : 0;\n }\n\n return RunnableLambda.from((messages: BaseMessage[]) => {\n const prefix: BaseMessage[] = systemMessage ? [systemMessage] : [];\n\n // Build the non-system portion (summary + conversation), then apply\n // cache markers separately so addCacheControl doesn't strip the\n // SystemMessage's own cache_control breakpoint set above.\n const hasSummaryBody =\n this._summaryLocation === 'user_message' &&\n this.summaryText != null &&\n this.summaryText !== '';\n\n let body: BaseMessage[];\n if (hasSummaryBody) {\n const wrappedSummary =\n '<summary>\\n' +\n (this.summaryText as string) +\n '\\n</summary>\\n\\n' +\n 'This is your own checkpoint: you wrote it to preserve context after compaction. Pick up where you left off based on the summary above. Do not repeat prior tasks, information or acknowledge this checkpoint message directly.';\n\n const summaryMsg = usePromptCache\n ? new HumanMessage({\n content: [\n {\n type: 'text',\n text: wrappedSummary,\n cache_control: { type: 'ephemeral' },\n },\n ],\n })\n : new HumanMessage(wrappedSummary);\n body = [summaryMsg, ...messages];\n } else {\n body = messages;\n }\n\n if (usePromptCache && body.length >= 2) {\n body = addCacheControl(body);\n }\n return [...prefix, ...body];\n }).withConfig({ runName: 'prompt' });\n }\n\n /**\n * Reset context for a new run\n */\n reset(): void {\n this.systemMessageTokens = 0;\n this.toolSchemaTokens = 0;\n this.cachedSystemRunnable = undefined;\n this.systemRunnableStale = true;\n this.lastToken = undefined;\n this.indexTokenCountMap = { ...this.baseIndexTokenCountMap };\n this.currentUsage = undefined;\n this.pruneMessages = undefined;\n this.lastStreamCall = undefined;\n this.tokenTypeSwitch = undefined;\n this.reasoningTransitionCount = 0;\n this.currentTokenType = ContentTypes.TEXT;\n this.discoveredToolNames.clear();\n this.handoffContext = undefined;\n\n this.summaryText = this._durableSummaryText;\n this.summaryTokenCount = this._durableSummaryTokenCount;\n this._lastSummarizationMsgCount = 0;\n this.lastCallUsage = undefined;\n this.totalTokensFresh = false;\n\n if (this.tokenCounter) {\n this.initializeSystemRunnable();\n const baseTokenMap = { ...this.baseIndexTokenCountMap };\n this.indexTokenCountMap = baseTokenMap;\n this.tokenCalculationPromise = this.calculateInstructionTokens(\n this.tokenCounter\n )\n .then(() => {\n this.updateTokenMapWithInstructions(baseTokenMap);\n })\n .catch((err) => {\n console.error('Error calculating instruction tokens:', err);\n });\n } else {\n this.tokenCalculationPromise = undefined;\n }\n }\n\n /**\n * Update the token count map from a base map.\n *\n * Previously this inflated index 0 with instructionTokens to indirectly\n * reserve budget for the system prompt. That approach was imprecise: with\n * large tool-schema overhead (e.g. 26 MCP tools ~5 000 tokens) the first\n * conversation message appeared enormous and was always pruned, while the\n * real available budget was never explicitly computed.\n *\n * Now instruction tokens are passed to getMessagesWithinTokenLimit via\n * the `getInstructionTokens` factory param so the pruner subtracts them\n * from the budget directly. The token map contains only real per-message\n * token counts.\n */\n updateTokenMapWithInstructions(baseTokenMap: Record<string, number>): void {\n this.indexTokenCountMap = { ...baseTokenMap };\n }\n\n /** Active tool definitions for token accounting (excludes deferred-and-undiscovered entries). */\n private getActiveToolDefinitions(): t.LCTool[] {\n if (!this.toolDefinitions) {\n return [];\n }\n return this.toolDefinitions.filter(\n (def) =>\n def.defer_loading !== true || this.discoveredToolNames.has(def.name)\n );\n }\n\n /**\n * Calculate tool tokens and add to instruction tokens\n * Note: System message tokens are calculated during systemRunnable creation\n */\n async calculateInstructionTokens(\n tokenCounter: t.TokenCounter\n ): Promise<void> {\n let toolTokens = 0;\n const countedToolNames = new Set<string>();\n\n /**\n * Iterate both `tools` (user-provided instance tools) and `graphTools`\n * (graph-managed tools like handoff + subagent). `graphTools` is often\n * populated after `fromConfig()` kicks off the initial calculation, so\n * callers that mutate `graphTools` must re-trigger this method to\n * refresh `toolSchemaTokens`.\n */\n const instanceTools: t.GraphTools = [\n ...((this.tools as t.GenericTool[] | undefined) ?? []),\n ...((this.graphTools as t.GenericTool[] | undefined) ?? []),\n ];\n\n if (instanceTools.length > 0) {\n for (const tool of instanceTools) {\n const genericTool = tool as Record<string, unknown>;\n if (\n genericTool.schema != null &&\n typeof genericTool.schema === 'object'\n ) {\n const toolName = (genericTool.name as string | undefined) ?? '';\n const jsonSchema = toJsonSchema(\n genericTool.schema,\n toolName,\n (genericTool.description as string | undefined) ?? ''\n );\n toolTokens += tokenCounter(\n new SystemMessage(JSON.stringify(jsonSchema))\n );\n if (toolName) {\n countedToolNames.add(toolName);\n }\n }\n }\n }\n\n for (const def of this.getActiveToolDefinitions()) {\n if (countedToolNames.has(def.name)) {\n continue;\n }\n const schema = {\n type: 'function',\n function: {\n name: def.name,\n description: def.description ?? '',\n parameters: def.parameters ?? {},\n },\n };\n toolTokens += tokenCounter(new SystemMessage(JSON.stringify(schema)));\n }\n\n const isAnthropic =\n this.provider !== Providers.BEDROCK &&\n (this.provider === Providers.ANTHROPIC ||\n /anthropic|claude/i.test(\n String(\n (this.clientOptions as { model?: string } | undefined)?.model ?? ''\n )\n ));\n const toolTokenMultiplier = isAnthropic\n ? ANTHROPIC_TOOL_TOKEN_MULTIPLIER\n : DEFAULT_TOOL_TOKEN_MULTIPLIER;\n this.toolSchemaTokens = Math.ceil(toolTokens * toolTokenMultiplier);\n }\n\n /**\n * Gets the tool registry for deferred tools (for tool search).\n * @param onlyDeferred If true, only returns tools with defer_loading=true\n * @returns LCToolRegistry with tool definitions\n */\n getDeferredToolRegistry(onlyDeferred: boolean = true): t.LCToolRegistry {\n const registry: t.LCToolRegistry = new Map();\n\n if (!this.toolRegistry) {\n return registry;\n }\n\n for (const [name, toolDef] of this.toolRegistry) {\n if (!onlyDeferred || toolDef.defer_loading === true) {\n registry.set(name, toolDef);\n }\n }\n\n return registry;\n }\n\n /**\n * Sets the handoff context for this agent.\n * Call this when the agent receives control via handoff from another agent.\n * Marks system runnable as stale to include handoff context in system message.\n * @param sourceAgentName - Name of the agent that transferred control\n * @param parallelSiblings - Names of other agents executing in parallel with this one\n */\n setHandoffContext(sourceAgentName: string, parallelSiblings: string[]): void {\n this.handoffContext = { sourceAgentName, parallelSiblings };\n this.systemRunnableStale = true;\n }\n\n /**\n * Clears any handoff context.\n * Call this when resetting the agent or when handoff context is no longer relevant.\n */\n clearHandoffContext(): void {\n if (this.handoffContext) {\n this.handoffContext = undefined;\n this.systemRunnableStale = true;\n }\n }\n\n setSummary(text: string, tokenCount: number): void {\n this.summaryText = text;\n this.summaryTokenCount = tokenCount;\n this._summaryLocation = 'user_message';\n this._durableSummaryText = text;\n this._durableSummaryTokenCount = tokenCount;\n this._summaryVersion += 1;\n this.systemRunnableStale = true;\n this.pruneMessages = undefined;\n }\n\n /** Sets a cross-run summary that is injected into the system prompt. */\n setInitialSummary(text: string, tokenCount: number): void {\n this.summaryText = text;\n this.summaryTokenCount = tokenCount;\n this._summaryLocation = 'system_prompt';\n this._durableSummaryText = text;\n this._durableSummaryTokenCount = tokenCount;\n this._summaryVersion += 1;\n this.systemRunnableStale = true;\n }\n\n /**\n * Replaces the indexTokenCountMap with a fresh map keyed to the surviving\n * context messages after summarization. Called by the summarize node after\n * it emits RemoveMessage operations that shift message indices.\n */\n rebuildTokenMapAfterSummarization(newTokenMap: Record<string, number>): void {\n this.indexTokenCountMap = newTokenMap;\n this.baseIndexTokenCountMap = { ...newTokenMap };\n this._lastSummarizationMsgCount = Object.keys(newTokenMap).length;\n this.currentUsage = undefined;\n this.lastCallUsage = undefined;\n this.totalTokensFresh = false;\n }\n\n hasSummary(): boolean {\n return this.summaryText != null && this.summaryText !== '';\n }\n\n /** True when a mid-run compaction summary is ready to be injected as a HumanMessage. */\n hasPendingCompactionSummary(): boolean {\n return this._summaryLocation === 'user_message' && this.hasSummary();\n }\n\n getSummaryText(): string | undefined {\n return this.summaryText;\n }\n\n get summaryVersion(): number {\n return this._summaryVersion;\n }\n\n /**\n * Returns true when the message count hasn't changed since the last\n * summarization — re-summarizing would produce an identical result.\n * Oversized individual messages are handled by fit-to-budget truncation\n * in the pruner, which keeps them in context without triggering overflow.\n */\n shouldSkipSummarization(currentMsgCount: number): boolean {\n return (\n this._lastSummarizationMsgCount > 0 &&\n currentMsgCount <= this._lastSummarizationMsgCount\n );\n }\n\n /**\n * Records the message count at which summarization was triggered,\n * so subsequent calls with the same count are suppressed.\n */\n markSummarizationTriggered(msgCount: number): void {\n this._lastSummarizationMsgCount = msgCount;\n }\n\n clearSummary(): void {\n if (this.summaryText != null) {\n this.summaryText = undefined;\n this.summaryTokenCount = 0;\n this._durableSummaryText = undefined;\n this._durableSummaryTokenCount = 0;\n this._summaryLocation = 'none';\n this.systemRunnableStale = true;\n }\n }\n\n /**\n * Returns a structured breakdown of how the context token budget is consumed.\n * Useful for diagnostics when context overflow or pruning issues occur.\n *\n * Note: `toolCount` reflects discoveries immediately, but `toolSchemaTokens`\n * is a snapshot taken during `calculateInstructionTokens` and is not\n * recomputed when `markToolsAsDiscovered` is called mid-run.\n */\n getTokenBudgetBreakdown(messages?: BaseMessage[]): t.TokenBudgetBreakdown {\n const maxContextTokens = this.maxContextTokens ?? 0;\n const toolCount =\n (this.tools?.length ?? 0) + this.getActiveToolDefinitions().length;\n const messageCount = messages?.length ?? 0;\n\n let messageTokens = 0;\n if (messages != null) {\n for (let i = 0; i < messages.length; i++) {\n messageTokens +=\n (this.indexTokenCountMap[i] as number | undefined) ?? 0;\n }\n }\n\n const reserveTokens = Math.round(maxContextTokens * DEFAULT_RESERVE_RATIO);\n const availableForMessages = Math.max(\n 0,\n maxContextTokens - reserveTokens - this.instructionTokens\n );\n\n return {\n maxContextTokens,\n instructionTokens: this.instructionTokens,\n systemMessageTokens: this.systemMessageTokens,\n toolSchemaTokens: this.toolSchemaTokens,\n summaryTokens: this.summaryTokenCount,\n toolCount,\n messageCount,\n messageTokens,\n availableForMessages,\n };\n }\n\n /**\n * Returns a human-readable string of the token budget breakdown\n * for inclusion in error messages and diagnostics.\n */\n formatTokenBudgetBreakdown(messages?: BaseMessage[]): string {\n const b = this.getTokenBudgetBreakdown(messages);\n const lines = [\n 'Token budget breakdown:',\n ` maxContextTokens: ${b.maxContextTokens}`,\n ` instructionTokens: ${b.instructionTokens} (system: ${b.systemMessageTokens}, tools: ${b.toolSchemaTokens} [${b.toolCount} tools])`,\n ` summaryTokens: ${b.summaryTokens}`,\n ` messageTokens: ${b.messageTokens} (${b.messageCount} messages)`,\n ` availableForMessages: ${b.availableForMessages}`,\n ];\n return lines.join('\\n');\n }\n\n /**\n * Updates the last-call usage with data from the most recent LLM response.\n * Unlike `currentUsage` which accumulates, this captures only the single call.\n */\n updateLastCallUsage(usage: Partial<UsageMetadata>): void {\n const baseInputTokens = Number(usage.input_tokens) || 0;\n const cacheCreation =\n Number(usage.input_token_details?.cache_creation) || 0;\n const cacheRead = Number(usage.input_token_details?.cache_read) || 0;\n\n const outputTokens = Number(usage.output_tokens) || 0;\n const cacheSum = cacheCreation + cacheRead;\n const cacheIsAdditive = cacheSum > 0 && cacheSum > baseInputTokens;\n const totalInputTokens = cacheIsAdditive\n ? baseInputTokens + cacheSum\n : baseInputTokens;\n\n this.lastCallUsage = {\n inputTokens: totalInputTokens,\n outputTokens,\n totalTokens: totalInputTokens + outputTokens,\n cacheRead: cacheRead || undefined,\n cacheCreation: cacheCreation || undefined,\n };\n this.totalTokensFresh = true;\n }\n\n /** Marks token data as stale before a new LLM call. */\n markTokensStale(): void {\n this.totalTokensFresh = false;\n }\n\n /**\n * Marks tools as discovered via tool search.\n * Discovered tools will be included in the next model binding.\n * Only marks system runnable stale if NEW tools were actually added.\n * @param toolNames - Array of discovered tool names\n * @returns true if any new tools were discovered\n */\n markToolsAsDiscovered(toolNames: string[]): boolean {\n let hasNewDiscoveries = false;\n for (const name of toolNames) {\n if (!this.discoveredToolNames.has(name)) {\n this.discoveredToolNames.add(name);\n hasNewDiscoveries = true;\n }\n }\n if (hasNewDiscoveries) {\n this.systemRunnableStale = true;\n }\n return hasNewDiscoveries;\n }\n\n /**\n * Gets tools that should be bound to the LLM.\n * In event-driven mode (toolDefinitions present, tools empty), creates schema-only tools.\n * Otherwise filters tool instances based on:\n * 1. Non-deferred tools with allowed_callers: ['direct']\n * 2. Discovered tools (from tool search)\n * @returns Array of tools to bind to model\n */\n getToolsForBinding(): t.GraphTools | undefined {\n if (this.toolDefinitions && this.toolDefinitions.length > 0) {\n return this.getEventDrivenToolsForBinding();\n }\n\n const filtered =\n !this.tools || !this.toolRegistry\n ? this.tools\n : this.filterToolsForBinding(this.tools);\n\n if (this.graphTools && this.graphTools.length > 0) {\n return [...(filtered ?? []), ...this.graphTools];\n }\n\n return filtered;\n }\n\n /** Creates schema-only tools from toolDefinitions for event-driven mode, merged with native tools */\n private getEventDrivenToolsForBinding(): t.GraphTools {\n if (!this.toolDefinitions) {\n return this.graphTools ?? [];\n }\n\n const defsToInclude = this.toolDefinitions.filter((def) => {\n const allowedCallers = def.allowed_callers ?? ['direct'];\n if (!allowedCallers.includes('direct')) {\n return false;\n }\n if (\n def.defer_loading === true &&\n !this.discoveredToolNames.has(def.name)\n ) {\n return false;\n }\n return true;\n });\n\n const schemaTools = createSchemaOnlyTools(defsToInclude) as t.GraphTools;\n\n const allTools = [...schemaTools];\n\n if (this.graphTools && this.graphTools.length > 0) {\n allTools.push(...this.graphTools);\n }\n\n if (this.tools && this.tools.length > 0) {\n allTools.push(...this.tools);\n }\n\n return allTools;\n }\n\n /** Filters tool instances for binding based on registry config */\n private filterToolsForBinding(tools: t.GraphTools): t.GraphTools {\n return tools.filter((tool) => {\n if (!('name' in tool)) {\n return true;\n }\n\n const toolDef = this.toolRegistry?.get(tool.name);\n if (!toolDef) {\n return true;\n }\n\n if (this.discoveredToolNames.has(tool.name)) {\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return allowedCallers.includes('direct');\n }\n\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return (\n allowedCallers.includes('direct') && toolDef.defer_loading !== true\n );\n });\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;AAAA;AAsBA;;AAEG;MACU,YAAY,CAAA;AACvB;;AAEG;AACH,IAAA,OAAO,UAAU,CACf,WAA0B,EAC1B,YAA6B,EAC7B,kBAA2C,EAAA;QAE3C,MAAM,EACJ,OAAO,EACP,IAAI,EACJ,QAAQ,EACR,aAAa,EACb,KAAK,EACL,OAAO,EACP,OAAO,EACP,YAAY,EACZ,eAAe,EACf,YAAY,EACZ,uBAAuB,EACvB,YAAY,EACZ,gBAAgB,EAChB,YAAY,EACZ,gBAAgB,EAChB,eAAe,EACf,oBAAoB,EACpB,mBAAmB,EACnB,cAAc,EACd,oBAAoB,EACpB,kBAAkB,EAClB,gBAAgB,EAChB,eAAe,EACf,gBAAgB,GACjB,GAAG,WAAW;AAEf,QAAA,MAAM,YAAY,GAAG,IAAI,YAAY,CAAC;YACpC,OAAO;YACP,IAAI,EAAE,IAAI,IAAI,OAAO;YACrB,QAAQ;YACR,aAAa;YACb,gBAAgB;YAChB,YAAY;YACZ,KAAK;YACL,OAAO;YACP,YAAY;YACZ,eAAe;YACf,YAAY;AACZ,YAAA,sBAAsB,EAAE,uBAAuB;YAC/C,YAAY;YACZ,OAAO;AACP,YAAA,iBAAiB,EAAE,CAAC;YACpB,YAAY;YACZ,gBAAgB;YAChB,eAAe;YACf,oBAAoB;YACpB,mBAAmB;YACnB,oBAAoB;YACpB,kBAAkB;AACnB,SAAA,CAAC;AAEF,QAAA,YAAY,CAAC,aAAa,GAAG,WAAW;AACxC,QAAA,YAAY,CAAC,eAAe,GAAG,eAAe;AAC9C,QAAA,YAAY,CAAC,gBAAgB,GA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slint-disable no-console */\nimport { HumanMessage, SystemMessage } from '@langchain/core/messages';\nimport { RunnableLambda } from '@langchain/core/runnables';\nimport type {\n UsageMetadata,\n BaseMessage,\n BaseMessageFields,\n} from '@langchain/core/messages';\nimport type { RunnableConfig, Runnable } from '@langchain/core/runnables';\nimport type { createPruneMessages } from '@/messages';\nimport type * as t from '@/types';\nimport {\n ANTHROPIC_TOOL_TOKEN_MULTIPLIER,\n DEFAULT_TOOL_TOKEN_MULTIPLIER,\n ContentTypes,\n Providers,\n} from '@/common';\nimport { createSchemaOnlyTools } from '@/tools/schema';\nimport { addCacheControl } from '@/messages/cache';\nimport { DEFAULT_RESERVE_RATIO } from '@/messages';\nimport { toJsonSchema } from '@/utils/schema';\n\ntype AgentSystemTextBlock = {\n type: 'text';\n text: string;\n cache_control?: { type: 'ephemeral' };\n};\n\ntype AgentSystemContentBlock =\n | AgentSystemTextBlock\n | { cachePoint: { type: 'default' } };\n\n/**\n * Encapsulates agent-specific state that can vary between agents in a multi-agent system\n */\nexport class AgentContext {\n /**\n * Create an AgentContext from configuration with token accounting initialization\n */\n static fromConfig(\n agentConfig: t.AgentInputs,\n tokenCounter?: t.TokenCounter,\n indexTokenCountMap?: Record<string, number>\n ): AgentContext {\n const {\n agentId,\n name,\n provider,\n clientOptions,\n tools,\n toolMap,\n toolEnd,\n toolRegistry,\n toolDefinitions,\n instructions,\n additional_instructions,\n streamBuffer,\n maxContextTokens,\n reasoningKey,\n useLegacyContent,\n discoveredTools,\n summarizationEnabled,\n summarizationConfig,\n initialSummary,\n contextPruningConfig,\n maxToolResultChars,\n toolSchemaTokens,\n subagentConfigs,\n maxSubagentDepth,\n } = agentConfig;\n\n const agentContext = new AgentContext({\n agentId,\n name: name ?? agentId,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tools,\n toolMap,\n toolRegistry,\n toolDefinitions,\n instructions,\n additionalInstructions: additional_instructions,\n reasoningKey,\n toolEnd,\n instructionTokens: 0,\n tokenCounter,\n useLegacyContent,\n discoveredTools,\n summarizationEnabled,\n summarizationConfig,\n contextPruningConfig,\n maxToolResultChars,\n });\n\n agentContext._sourceInputs = agentConfig;\n agentContext.subagentConfigs = subagentConfigs;\n agentContext.maxSubagentDepth = maxSubagentDepth;\n\n if (initialSummary?.text != null && initialSummary.text !== '') {\n agentContext.setInitialSummary(\n initialSummary.text,\n initialSummary.tokenCount\n );\n }\n\n if (tokenCounter) {\n agentContext.initializeSystemRunnable();\n\n const tokenMap = indexTokenCountMap || {};\n agentContext.baseIndexTokenCountMap = { ...tokenMap };\n agentContext.indexTokenCountMap = tokenMap;\n\n if (toolSchemaTokens != null && toolSchemaTokens > 0) {\n /** Use pre-computed (cached) tool schema tokens — skip calculateInstructionTokens */\n agentContext.toolSchemaTokens = toolSchemaTokens;\n agentContext.tokenCalculationPromise = Promise.resolve();\n agentContext.updateTokenMapWithInstructions(tokenMap);\n } else {\n agentContext.tokenCalculationPromise = agentContext\n .calculateInstructionTokens(tokenCounter)\n .then(() => {\n agentContext.updateTokenMapWithInstructions(tokenMap);\n })\n .catch((err) => {\n console.error('Error calculating instruction tokens:', err);\n });\n }\n } else if (indexTokenCountMap) {\n agentContext.baseIndexTokenCountMap = { ...indexTokenCountMap };\n agentContext.indexTokenCountMap = indexTokenCountMap;\n }\n\n return agentContext;\n }\n\n /** Agent identifier */\n agentId: string;\n /** Human-readable name for this agent (used in handoff context). Falls back to agentId if not provided. */\n name?: string;\n /** Provider for this specific agent */\n provider: Providers;\n /** Client options for this agent */\n clientOptions?: t.ClientOptions;\n /** Token count map indexed by message position */\n indexTokenCountMap: Record<string, number | undefined> = {};\n /** Canonical pre-run token map used to restore token accounting on reset */\n baseIndexTokenCountMap: Record<string, number> = {};\n /** Maximum context tokens for this agent */\n maxContextTokens?: number;\n /** Current usage metadata for this agent */\n currentUsage?: Partial<UsageMetadata>;\n /**\n * Usage from the most recent LLM call only (not accumulated).\n * Used for accurate provider calibration in pruning.\n */\n lastCallUsage?: {\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n cacheRead?: number;\n cacheCreation?: number;\n };\n /**\n * Whether totalTokens data is fresh (set true when provider usage arrives,\n * false at the start of each turn before the LLM responds).\n * Prevents stale token data from driving pruning/trigger decisions.\n */\n totalTokensFresh: boolean = false;\n /** Context pruning configuration. */\n contextPruningConfig?: t.ContextPruningConfig;\n maxToolResultChars?: number;\n /** Prune messages function configured for this agent */\n pruneMessages?: ReturnType<typeof createPruneMessages>;\n /** Token counter function for this agent */\n tokenCounter?: t.TokenCounter;\n /** Token count for the system message (instructions text). */\n systemMessageTokens: number = 0;\n /** Token count for tool schemas only. */\n toolSchemaTokens: number = 0;\n /** Running calibration ratio from the pruner — persisted across runs via contextMeta. */\n calibrationRatio: number = 1;\n /** Provider-observed instruction overhead from the pruner's best-variance turn. */\n resolvedInstructionOverhead?: number;\n /** Pre-masking tool content keyed by message index, consumed by the summarize node. */\n pendingOriginalToolContent?: Map<number, string>;\n\n /** Total instruction overhead: system message + tool schemas + pending summary. */\n get instructionTokens(): number {\n const summaryOverhead =\n this._summaryLocation === 'user_message' ? this.summaryTokenCount : 0;\n return this.systemMessageTokens + this.toolSchemaTokens + summaryOverhead;\n }\n /** The amount of time that should pass before another consecutive API call */\n streamBuffer?: number;\n /** Last stream call timestamp for rate limiting */\n lastStreamCall?: number;\n /** Tools available to this agent */\n tools?: t.GraphTools;\n /** Graph-managed tools (e.g., handoff tools created by MultiAgentGraph) that bypass event-driven dispatch */\n graphTools?: t.GraphTools;\n /** Tool map for this agent */\n toolMap?: t.ToolMap;\n /**\n * Tool definitions registry (includes deferred and programmatic tool metadata).\n * Used for tool search and programmatic tool calling.\n */\n toolRegistry?: t.LCToolRegistry;\n /**\n * Serializable tool definitions for event-driven execution.\n * When provided, ToolNode operates in event-driven mode.\n */\n toolDefinitions?: t.LCTool[];\n /** Set of tool names discovered via tool search (to be loaded) */\n discoveredToolNames: Set<string> = new Set();\n /** Original AgentInputs used to create this context — used for self-spawn subagent resolution. */\n _sourceInputs?: t.AgentInputs;\n /** Subagent configurations for hierarchical delegation. */\n subagentConfigs?: t.SubagentConfig[];\n /** Maximum subagent nesting depth. */\n maxSubagentDepth?: number;\n /** Instructions for this agent */\n instructions?: string;\n /** Additional instructions for this agent */\n additionalInstructions?: string;\n /** Reasoning key for this agent */\n reasoningKey: 'reasoning_content' | 'reasoning' = 'reasoning_content';\n /** Last token for reasoning detection */\n lastToken?: string;\n /** Token type switch state */\n tokenTypeSwitch?: 'reasoning' | 'content';\n /** Tracks how many reasoning→text transitions have occurred (ensures unique post-reasoning step keys) */\n reasoningTransitionCount = 0;\n /** Current token type being processed */\n currentTokenType: ContentTypes.TEXT | ContentTypes.THINK | 'think_and_text' =\n ContentTypes.TEXT;\n /** Whether tools should end the workflow */\n toolEnd: boolean = false;\n /** Cached system runnable (created lazily) */\n private cachedSystemRunnable?: Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >;\n /** Whether system runnable needs rebuild (set when discovered tools change) */\n private systemRunnableStale: boolean = true;\n /** Promise for token calculation initialization */\n tokenCalculationPromise?: Promise<void>;\n /** Format content blocks as strings (for legacy compatibility) */\n useLegacyContent: boolean = false;\n /** Enables graph-level summarization for this agent */\n summarizationEnabled?: boolean;\n /** Summarization runtime settings used by graph pruning hooks */\n summarizationConfig?: t.SummarizationConfig;\n /** Current summary text produced by the summarize node, integrated into system message */\n private summaryText?: string;\n /** Token count of the current summary (tracked for token accounting) */\n private summaryTokenCount: number = 0;\n /**\n * Where the summary should be injected:\n * - `'system_prompt'`: cross-run summary, included in the dynamic system tail\n * - `'user_message'`: mid-run compaction, injected as HumanMessage on clean slate\n * - `'none'`: no summary present\n */\n private _summaryLocation: 'system_prompt' | 'user_message' | 'none' = 'none';\n /**\n * Durable summary that survives reset() calls. Set from initialSummary\n * during fromConfig() and updated by setSummary() so that the latest\n * summary (whether cross-run or intra-run) is always restored after\n * processStream's resetValues() cycle.\n */\n private _durableSummaryText?: string;\n private _durableSummaryTokenCount: number = 0;\n /** Number of summarization cycles that have occurred for this agent context */\n private _summaryVersion: number = 0;\n /**\n * Message count at the time summarization was last triggered.\n * Used to prevent re-summarizing the same unchanged message set.\n * Summarization is allowed to fire again only when new messages appear.\n */\n private _lastSummarizationMsgCount: number = 0;\n /**\n * Handoff context when this agent receives control via handoff.\n * Contains source and parallel execution info for system message context.\n */\n handoffContext?: {\n /** Source agent that transferred control */\n sourceAgentName: string;\n /** Names of sibling agents executing in parallel (empty if sequential) */\n parallelSiblings: string[];\n };\n\n constructor({\n agentId,\n name,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tokenCounter,\n tools,\n toolMap,\n toolRegistry,\n toolDefinitions,\n instructions,\n additionalInstructions,\n reasoningKey,\n toolEnd,\n instructionTokens,\n useLegacyContent,\n discoveredTools,\n summarizationEnabled,\n summarizationConfig,\n contextPruningConfig,\n maxToolResultChars,\n }: {\n agentId: string;\n name?: string;\n provider: Providers;\n clientOptions?: t.ClientOptions;\n maxContextTokens?: number;\n streamBuffer?: number;\n tokenCounter?: t.TokenCounter;\n tools?: t.GraphTools;\n toolMap?: t.ToolMap;\n toolRegistry?: t.LCToolRegistry;\n toolDefinitions?: t.LCTool[];\n instructions?: string;\n additionalInstructions?: string;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n toolEnd?: boolean;\n instructionTokens?: number;\n useLegacyContent?: boolean;\n discoveredTools?: string[];\n summarizationEnabled?: boolean;\n summarizationConfig?: t.SummarizationConfig;\n contextPruningConfig?: t.ContextPruningConfig;\n maxToolResultChars?: number;\n }) {\n this.agentId = agentId;\n this.name = name;\n this.provider = provider;\n this.clientOptions = clientOptions;\n this.maxContextTokens = maxContextTokens;\n this.streamBuffer = streamBuffer;\n this.tokenCounter = tokenCounter;\n this.tools = tools;\n this.toolMap = toolMap;\n this.toolRegistry = toolRegistry;\n this.toolDefinitions = toolDefinitions;\n this.instructions = instructions;\n this.additionalInstructions = additionalInstructions;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (toolEnd !== undefined) {\n this.toolEnd = toolEnd;\n }\n if (instructionTokens !== undefined) {\n this.systemMessageTokens = instructionTokens;\n }\n\n this.useLegacyContent = useLegacyContent ?? false;\n this.summarizationEnabled = summarizationEnabled;\n this.summarizationConfig = summarizationConfig;\n this.contextPruningConfig = contextPruningConfig;\n this.maxToolResultChars = maxToolResultChars;\n\n if (discoveredTools && discoveredTools.length > 0) {\n for (const toolName of discoveredTools) {\n this.discoveredToolNames.add(toolName);\n }\n }\n }\n\n /**\n * Builds instructions text for tools that are ONLY callable via programmatic code execution.\n * These tools cannot be called directly by the LLM but are available through the\n * run_tools_with_code tool.\n *\n * Includes:\n * - Code_execution-only tools that are NOT deferred\n * - Code_execution-only tools that ARE deferred but have been discovered via tool search\n */\n private buildProgrammaticOnlyToolsInstructions(): string {\n if (!this.toolRegistry) return '';\n\n const programmaticOnlyTools: t.LCTool[] = [];\n for (const [name, toolDef] of this.toolRegistry) {\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n const isCodeExecutionOnly =\n allowedCallers.includes('code_execution') &&\n !allowedCallers.includes('direct');\n\n if (!isCodeExecutionOnly) continue;\n\n const isDeferred = toolDef.defer_loading === true;\n const isDiscovered = this.discoveredToolNames.has(name);\n if (!isDeferred || isDiscovered) {\n programmaticOnlyTools.push(toolDef);\n }\n }\n\n if (programmaticOnlyTools.length === 0) return '';\n\n const toolDescriptions = programmaticOnlyTools\n .map((tool) => {\n let desc = `- **${tool.name}**`;\n if (tool.description != null && tool.description !== '') {\n desc += `: ${tool.description}`;\n }\n if (tool.parameters) {\n desc += `\\n Parameters: ${JSON.stringify(tool.parameters, null, 2).replace(/\\n/g, '\\n ')}`;\n }\n return desc;\n })\n .join('\\n\\n');\n\n return (\n '\\n\\n## Programmatic-Only Tools\\n\\n' +\n 'The following tools are available exclusively through the `run_tools_with_code` tool. ' +\n 'You cannot call these tools directly; instead, use `run_tools_with_code` with Python code that invokes them.\\n\\n' +\n toolDescriptions\n );\n }\n\n /**\n * Gets the system runnable, creating it lazily if needed.\n * Includes stable instructions, dynamic additional instructions, and\n * programmatic-only tools documentation.\n * Only rebuilds when marked stale (via markToolsAsDiscovered).\n */\n get systemRunnable():\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n if (!this.systemRunnableStale && this.cachedSystemRunnable !== undefined) {\n return this.cachedSystemRunnable;\n }\n\n this.cachedSystemRunnable = this.buildSystemRunnable({\n stableInstructions: this.buildStableInstructionsString(),\n dynamicInstructions: this.buildDynamicInstructionsString(),\n });\n this.systemRunnableStale = false;\n return this.cachedSystemRunnable;\n }\n\n /**\n * Explicitly initializes the system runnable.\n * Call this before async token calculation to ensure system message tokens are counted first.\n */\n initializeSystemRunnable(): void {\n if (this.systemRunnableStale || this.cachedSystemRunnable === undefined) {\n this.cachedSystemRunnable = this.buildSystemRunnable({\n stableInstructions: this.buildStableInstructionsString(),\n dynamicInstructions: this.buildDynamicInstructionsString(),\n });\n this.systemRunnableStale = false;\n }\n }\n\n /**\n * Builds the cacheable instructions string (without creating SystemMessage).\n * Includes agent identity preamble and handoff context when available.\n */\n private buildStableInstructionsString(): string {\n const parts: string[] = [];\n\n const identityPreamble = this.buildIdentityPreamble();\n if (identityPreamble) {\n parts.push(identityPreamble);\n }\n\n if (this.instructions != null && this.instructions !== '') {\n parts.push(this.instructions);\n }\n\n const programmaticToolsDoc = this.buildProgrammaticOnlyToolsInstructions();\n if (programmaticToolsDoc) {\n parts.push(programmaticToolsDoc);\n }\n\n return parts.join('\\n\\n');\n }\n\n /**\n * Builds the dynamic system-tail string (without creating SystemMessage).\n * Keep this out of prompt-cache-marked content so volatile context does not\n * invalidate the stable prefix.\n */\n private buildDynamicInstructionsString(): string {\n const parts: string[] = [];\n\n if (\n this.additionalInstructions != null &&\n this.additionalInstructions !== ''\n ) {\n parts.push(this.additionalInstructions);\n }\n\n // Cross-run summary: include in the system tail so the model has context\n // from the prior run without invalidating the cacheable prefix. Mid-run\n // summaries are injected as a HumanMessage on the post-compaction clean\n // slate instead (see buildSystemRunnable).\n if (\n this._summaryLocation === 'system_prompt' &&\n this.summaryText != null &&\n this.summaryText !== ''\n ) {\n parts.push('## Conversation Summary\\n\\n' + this.summaryText);\n }\n\n return parts.join('\\n\\n');\n }\n\n /**\n * Builds the agent identity preamble including handoff context if present.\n * This helps the agent understand its role in the multi-agent workflow.\n */\n private buildIdentityPreamble(): string {\n if (!this.handoffContext) return '';\n\n const displayName = this.name ?? this.agentId;\n const { sourceAgentName, parallelSiblings } = this.handoffContext;\n const isParallel = parallelSiblings.length > 0;\n\n const lines: string[] = [];\n lines.push('## Multi-Agent Workflow');\n lines.push(\n `You are \"${displayName}\", transferred from \"${sourceAgentName}\".`\n );\n\n if (isParallel) {\n lines.push(`Running in parallel with: ${parallelSiblings.join(', ')}.`);\n }\n\n lines.push(\n 'Execute only tasks relevant to your role. Routing is already handled if requested, unless you can route further.'\n );\n\n return lines.join('\\n');\n }\n\n /**\n * Build system runnable from pre-built instructions string.\n * Only called when content has actually changed.\n */\n private buildSystemRunnable({\n stableInstructions,\n dynamicInstructions,\n }: {\n stableInstructions: string;\n dynamicInstructions: string;\n }):\n | Runnable<\n BaseMessage[],\n (BaseMessage | SystemMessage)[],\n RunnableConfig<Record<string, unknown>>\n >\n | undefined {\n const hasMidRunSummary =\n this._summaryLocation === 'user_message' &&\n this.summaryText != null &&\n this.summaryText !== '';\n\n if (!stableInstructions && !dynamicInstructions && !hasMidRunSummary) {\n this.systemMessageTokens = 0;\n return undefined;\n }\n\n const usePromptCache = this.hasAnthropicPromptCache();\n const systemMessage = this.buildSystemMessage({\n stableInstructions,\n dynamicInstructions,\n usePromptCache,\n });\n\n if (this.tokenCounter) {\n this.systemMessageTokens = systemMessage\n ? this.tokenCounter(systemMessage)\n : 0;\n }\n\n return RunnableLambda.from((messages: BaseMessage[]) => {\n const prefix: BaseMessage[] = systemMessage ? [systemMessage] : [];\n\n // Build the non-system portion (summary + conversation), then apply\n // cache markers separately so addCacheControl doesn't strip the\n // SystemMessage's own cache_control breakpoint set above.\n const hasSummaryBody =\n this._summaryLocation === 'user_message' &&\n this.summaryText != null &&\n this.summaryText !== '';\n\n let body: BaseMessage[];\n if (hasSummaryBody) {\n const wrappedSummary =\n '<summary>\\n' +\n (this.summaryText as string) +\n '\\n</summary>\\n\\n' +\n 'This is your own checkpoint: you wrote it to preserve context after compaction. Pick up where you left off based on the summary above. Do not repeat prior tasks, information or acknowledge this checkpoint message directly.';\n\n const summaryMsg = usePromptCache\n ? new HumanMessage({\n content: [\n {\n type: 'text',\n text: wrappedSummary,\n cache_control: { type: 'ephemeral' },\n },\n ],\n })\n : new HumanMessage(wrappedSummary);\n body = [summaryMsg, ...messages];\n } else {\n body = messages;\n }\n\n if (usePromptCache && body.length >= 2) {\n body = addCacheControl(body);\n }\n return [...prefix, ...body];\n }).withConfig({ runName: 'prompt' });\n }\n\n private hasAnthropicPromptCache(): boolean {\n if (this.provider !== Providers.ANTHROPIC) {\n return false;\n }\n const anthropicOptions = this.clientOptions as\n | t.AnthropicClientOptions\n | undefined;\n return anthropicOptions?.promptCache === true;\n }\n\n private hasBedrockPromptCache(): boolean {\n if (this.provider !== Providers.BEDROCK) {\n return false;\n }\n const bedrockOptions = this.clientOptions as\n | t.BedrockAnthropicClientOptions\n | undefined;\n return bedrockOptions?.promptCache === true;\n }\n\n private buildSystemMessage({\n stableInstructions,\n dynamicInstructions,\n usePromptCache,\n }: {\n stableInstructions: string;\n dynamicInstructions: string;\n usePromptCache: boolean;\n }): SystemMessage | undefined {\n if (!stableInstructions && !dynamicInstructions) {\n return undefined;\n }\n\n if (usePromptCache) {\n const content: AgentSystemContentBlock[] = [];\n if (stableInstructions) {\n content.push({\n type: 'text',\n text: stableInstructions,\n cache_control: { type: 'ephemeral' },\n });\n }\n if (dynamicInstructions) {\n content.push({ type: 'text', text: dynamicInstructions });\n }\n return new SystemMessage({ content } as BaseMessageFields);\n }\n\n if (this.hasBedrockPromptCache() && stableInstructions) {\n const content: AgentSystemContentBlock[] = [\n { type: 'text', text: stableInstructions },\n { cachePoint: { type: 'default' } },\n ];\n if (dynamicInstructions) {\n content.push({ type: 'text', text: dynamicInstructions });\n }\n return new SystemMessage({ content } as BaseMessageFields);\n }\n\n return new SystemMessage(\n [stableInstructions, dynamicInstructions]\n .filter((part) => part !== '')\n .join('\\n\\n')\n );\n }\n\n /**\n * Reset context for a new run\n */\n reset(): void {\n this.systemMessageTokens = 0;\n this.toolSchemaTokens = 0;\n this.cachedSystemRunnable = undefined;\n this.systemRunnableStale = true;\n this.lastToken = undefined;\n this.indexTokenCountMap = { ...this.baseIndexTokenCountMap };\n this.currentUsage = undefined;\n this.pruneMessages = undefined;\n this.lastStreamCall = undefined;\n this.tokenTypeSwitch = undefined;\n this.reasoningTransitionCount = 0;\n this.currentTokenType = ContentTypes.TEXT;\n this.discoveredToolNames.clear();\n this.handoffContext = undefined;\n\n this.summaryText = this._durableSummaryText;\n this.summaryTokenCount = this._durableSummaryTokenCount;\n this._lastSummarizationMsgCount = 0;\n this.lastCallUsage = undefined;\n this.totalTokensFresh = false;\n\n if (this.tokenCounter) {\n this.initializeSystemRunnable();\n const baseTokenMap = { ...this.baseIndexTokenCountMap };\n this.indexTokenCountMap = baseTokenMap;\n this.tokenCalculationPromise = this.calculateInstructionTokens(\n this.tokenCounter\n )\n .then(() => {\n this.updateTokenMapWithInstructions(baseTokenMap);\n })\n .catch((err) => {\n console.error('Error calculating instruction tokens:', err);\n });\n } else {\n this.tokenCalculationPromise = undefined;\n }\n }\n\n /**\n * Update the token count map from a base map.\n *\n * Previously this inflated index 0 with instructionTokens to indirectly\n * reserve budget for the system prompt. That approach was imprecise: with\n * large tool-schema overhead (e.g. 26 MCP tools ~5 000 tokens) the first\n * conversation message appeared enormous and was always pruned, while the\n * real available budget was never explicitly computed.\n *\n * Now instruction tokens are passed to getMessagesWithinTokenLimit via\n * the `getInstructionTokens` factory param so the pruner subtracts them\n * from the budget directly. The token map contains only real per-message\n * token counts.\n */\n updateTokenMapWithInstructions(baseTokenMap: Record<string, number>): void {\n this.indexTokenCountMap = { ...baseTokenMap };\n }\n\n /** Active tool definitions for token accounting (excludes deferred-and-undiscovered entries). */\n private getActiveToolDefinitions(): t.LCTool[] {\n if (!this.toolDefinitions) {\n return [];\n }\n /**\n * Mirror `getEventDrivenToolsForBinding`'s gate: a definition is only\n * bound to the model when its `allowed_callers` include `'direct'` and\n * (if deferred) it has been discovered. Filtering by `defer_loading`\n * alone left programmatic-only definitions counted in\n * `toolSchemaTokens` even though they were never bound.\n */\n return this.toolDefinitions.filter((def) => {\n const allowedCallers = def.allowed_callers ?? ['direct'];\n if (!allowedCallers.includes('direct')) {\n return false;\n }\n return (\n def.defer_loading !== true || this.discoveredToolNames.has(def.name)\n );\n });\n }\n\n /**\n * Single source of truth for \"which entries of `this.tools` should be\n * treated as actually bound\". Callers:\n * - `getToolsForBinding` (non-event-driven branch)\n * - `getEventDrivenToolsForBinding` (appends instance tools alongside\n * schema-only definitions)\n * - `calculateInstructionTokens` (counts schema bytes for accounting)\n *\n * In event-driven mode (`toolDefinitions` present) instance tools are\n * appended unfiltered; outside event-driven mode they pass through\n * `filterToolsForBinding`. Centralizing the decision here prevents the\n * accounting/binding paths from drifting apart, which was the root\n * cause of the original miscount.\n */\n private getEffectiveInstanceTools(): t.GraphTools | undefined {\n if (!this.tools) {\n return undefined;\n }\n const isEventDriven = (this.toolDefinitions?.length ?? 0) > 0;\n if (isEventDriven || !this.toolRegistry) {\n return this.tools;\n }\n return this.filterToolsForBinding(this.tools);\n }\n\n /**\n * Calculate tool tokens and add to instruction tokens\n * Note: System message tokens are calculated during systemRunnable creation\n */\n async calculateInstructionTokens(\n tokenCounter: t.TokenCounter\n ): Promise<void> {\n let toolTokens = 0;\n const countedToolNames = new Set<string>();\n\n /**\n * Iterate both `tools` (user-provided instance tools) and `graphTools`\n * (graph-managed tools like handoff + subagent). `graphTools` is often\n * populated after `fromConfig()` kicks off the initial calculation, so\n * callers that mutate `graphTools` must re-trigger this method to\n * refresh `toolSchemaTokens`.\n *\n * Use `getEffectiveInstanceTools()` so accounting reflects exactly the\n * subset that `getToolsForBinding` would emit — preventing the\n * worst-case-ceiling miscount that triggered spurious `empty_messages`\n * preflight rejections at low `maxContextTokens`. Deferred and\n * non-`'direct'` `toolDefinitions` are excluded by\n * `getActiveToolDefinitions()` below.\n */\n const instanceTools: t.GraphTools = [\n ...((this.getEffectiveInstanceTools() as t.GenericTool[] | undefined) ??\n []),\n ...((this.graphTools as t.GenericTool[] | undefined) ?? []),\n ];\n\n if (instanceTools.length > 0) {\n for (const tool of instanceTools) {\n const genericTool = tool as Record<string, unknown>;\n if (\n genericTool.schema != null &&\n typeof genericTool.schema === 'object'\n ) {\n const toolName = (genericTool.name as string | undefined) ?? '';\n const jsonSchema = toJsonSchema(\n genericTool.schema,\n toolName,\n (genericTool.description as string | undefined) ?? ''\n );\n toolTokens += tokenCounter(\n new SystemMessage(JSON.stringify(jsonSchema))\n );\n if (toolName) {\n countedToolNames.add(toolName);\n }\n }\n }\n }\n\n for (const def of this.getActiveToolDefinitions()) {\n if (countedToolNames.has(def.name)) {\n continue;\n }\n const schema = {\n type: 'function',\n function: {\n name: def.name,\n description: def.description ?? '',\n parameters: def.parameters ?? {},\n },\n };\n toolTokens += tokenCounter(new SystemMessage(JSON.stringify(schema)));\n }\n\n const isAnthropic =\n this.provider !== Providers.BEDROCK &&\n (this.provider === Providers.ANTHROPIC ||\n /anthropic|claude/i.test(\n String(\n (this.clientOptions as { model?: string } | undefined)?.model ?? ''\n )\n ));\n const toolTokenMultiplier = isAnthropic\n ? ANTHROPIC_TOOL_TOKEN_MULTIPLIER\n : DEFAULT_TOOL_TOKEN_MULTIPLIER;\n this.toolSchemaTokens = Math.ceil(toolTokens * toolTokenMultiplier);\n }\n\n /**\n * Gets the tool registry for deferred tools (for tool search).\n * @param onlyDeferred If true, only returns tools with defer_loading=true\n * @returns LCToolRegistry with tool definitions\n */\n getDeferredToolRegistry(onlyDeferred: boolean = true): t.LCToolRegistry {\n const registry: t.LCToolRegistry = new Map();\n\n if (!this.toolRegistry) {\n return registry;\n }\n\n for (const [name, toolDef] of this.toolRegistry) {\n if (!onlyDeferred || toolDef.defer_loading === true) {\n registry.set(name, toolDef);\n }\n }\n\n return registry;\n }\n\n /**\n * Sets the handoff context for this agent.\n * Call this when the agent receives control via handoff from another agent.\n * Marks system runnable as stale to include handoff context in system message.\n * @param sourceAgentName - Name of the agent that transferred control\n * @param parallelSiblings - Names of other agents executing in parallel with this one\n */\n setHandoffContext(sourceAgentName: string, parallelSiblings: string[]): void {\n this.handoffContext = { sourceAgentName, parallelSiblings };\n this.systemRunnableStale = true;\n }\n\n /**\n * Clears any handoff context.\n * Call this when resetting the agent or when handoff context is no longer relevant.\n */\n clearHandoffContext(): void {\n if (this.handoffContext) {\n this.handoffContext = undefined;\n this.systemRunnableStale = true;\n }\n }\n\n setSummary(text: string, tokenCount: number): void {\n this.summaryText = text;\n this.summaryTokenCount = tokenCount;\n this._summaryLocation = 'user_message';\n this._durableSummaryText = text;\n this._durableSummaryTokenCount = tokenCount;\n this._summaryVersion += 1;\n this.systemRunnableStale = true;\n this.pruneMessages = undefined;\n }\n\n /** Sets a cross-run summary that is injected into the system prompt. */\n setInitialSummary(text: string, tokenCount: number): void {\n this.summaryText = text;\n this.summaryTokenCount = tokenCount;\n this._summaryLocation = 'system_prompt';\n this._durableSummaryText = text;\n this._durableSummaryTokenCount = tokenCount;\n this._summaryVersion += 1;\n this.systemRunnableStale = true;\n }\n\n /**\n * Replaces the indexTokenCountMap with a fresh map keyed to the surviving\n * context messages after summarization. Called by the summarize node after\n * it emits RemoveMessage operations that shift message indices.\n */\n rebuildTokenMapAfterSummarization(newTokenMap: Record<string, number>): void {\n this.indexTokenCountMap = newTokenMap;\n this.baseIndexTokenCountMap = { ...newTokenMap };\n this._lastSummarizationMsgCount = Object.keys(newTokenMap).length;\n this.currentUsage = undefined;\n this.lastCallUsage = undefined;\n this.totalTokensFresh = false;\n }\n\n hasSummary(): boolean {\n return this.summaryText != null && this.summaryText !== '';\n }\n\n /** True when a mid-run compaction summary is ready to be injected as a HumanMessage. */\n hasPendingCompactionSummary(): boolean {\n return this._summaryLocation === 'user_message' && this.hasSummary();\n }\n\n getSummaryText(): string | undefined {\n return this.summaryText;\n }\n\n get summaryVersion(): number {\n return this._summaryVersion;\n }\n\n /**\n * Returns true when the message count hasn't changed since the last\n * summarization — re-summarizing would produce an identical result.\n * Oversized individual messages are handled by fit-to-budget truncation\n * in the pruner, which keeps them in context without triggering overflow.\n */\n shouldSkipSummarization(currentMsgCount: number): boolean {\n return (\n this._lastSummarizationMsgCount > 0 &&\n currentMsgCount <= this._lastSummarizationMsgCount\n );\n }\n\n /**\n * Records the message count at which summarization was triggered,\n * so subsequent calls with the same count are suppressed.\n */\n markSummarizationTriggered(msgCount: number): void {\n this._lastSummarizationMsgCount = msgCount;\n }\n\n clearSummary(): void {\n if (this.summaryText != null) {\n this.summaryText = undefined;\n this.summaryTokenCount = 0;\n this._durableSummaryText = undefined;\n this._durableSummaryTokenCount = 0;\n this._summaryLocation = 'none';\n this.systemRunnableStale = true;\n }\n }\n\n /**\n * Returns a structured breakdown of how the context token budget is consumed.\n * Useful for diagnostics when context overflow or pruning issues occur.\n *\n * Note: `toolCount` reflects discoveries immediately, but `toolSchemaTokens`\n * is a snapshot taken during `calculateInstructionTokens` and is not\n * recomputed when `markToolsAsDiscovered` is called mid-run.\n */\n getTokenBudgetBreakdown(messages?: BaseMessage[]): t.TokenBudgetBreakdown {\n const maxContextTokens = this.maxContextTokens ?? 0;\n /**\n * Derive `toolCount` from `getToolsForBinding()` so the diagnostic stays\n * aligned with what is actually bound to the model — and with what\n * `calculateInstructionTokens` counts into `toolSchemaTokens`. Using raw\n * `this.tools.length` would inflate the count whenever the registry\n * marks instance tools as deferred-undiscovered or non-`'direct'`,\n * producing the same misleading \"N tools\" diagnostic this fix is meant\n * to eliminate.\n */\n const toolCount = this.getToolsForBinding()?.length ?? 0;\n const messageCount = messages?.length ?? 0;\n\n let messageTokens = 0;\n if (messages != null) {\n for (let i = 0; i < messages.length; i++) {\n messageTokens +=\n (this.indexTokenCountMap[i] as number | undefined) ?? 0;\n }\n }\n\n const reserveTokens = Math.round(maxContextTokens * DEFAULT_RESERVE_RATIO);\n const availableForMessages = Math.max(\n 0,\n maxContextTokens - reserveTokens - this.instructionTokens\n );\n\n return {\n maxContextTokens,\n instructionTokens: this.instructionTokens,\n systemMessageTokens: this.systemMessageTokens,\n toolSchemaTokens: this.toolSchemaTokens,\n summaryTokens: this.summaryTokenCount,\n toolCount,\n messageCount,\n messageTokens,\n availableForMessages,\n };\n }\n\n /**\n * Returns a human-readable string of the token budget breakdown\n * for inclusion in error messages and diagnostics.\n */\n formatTokenBudgetBreakdown(messages?: BaseMessage[]): string {\n const b = this.getTokenBudgetBreakdown(messages);\n const lines = [\n 'Token budget breakdown:',\n ` maxContextTokens: ${b.maxContextTokens}`,\n ` instructionTokens: ${b.instructionTokens} (system: ${b.systemMessageTokens}, tools: ${b.toolSchemaTokens} [${b.toolCount} tools])`,\n ` summaryTokens: ${b.summaryTokens}`,\n ` messageTokens: ${b.messageTokens} (${b.messageCount} messages)`,\n ` availableForMessages: ${b.availableForMessages}`,\n ];\n return lines.join('\\n');\n }\n\n /**\n * Updates the last-call usage with data from the most recent LLM response.\n * Unlike `currentUsage` which accumulates, this captures only the single call.\n */\n updateLastCallUsage(usage: Partial<UsageMetadata>): void {\n const baseInputTokens = Number(usage.input_tokens) || 0;\n const cacheCreation =\n Number(usage.input_token_details?.cache_creation) || 0;\n const cacheRead = Number(usage.input_token_details?.cache_read) || 0;\n\n const outputTokens = Number(usage.output_tokens) || 0;\n const cacheSum = cacheCreation + cacheRead;\n const cacheIsAdditive = cacheSum > 0 && cacheSum > baseInputTokens;\n const totalInputTokens = cacheIsAdditive\n ? baseInputTokens + cacheSum\n : baseInputTokens;\n\n this.lastCallUsage = {\n inputTokens: totalInputTokens,\n outputTokens,\n totalTokens: totalInputTokens + outputTokens,\n cacheRead: cacheRead || undefined,\n cacheCreation: cacheCreation || undefined,\n };\n this.totalTokensFresh = true;\n }\n\n /** Marks token data as stale before a new LLM call. */\n markTokensStale(): void {\n this.totalTokensFresh = false;\n }\n\n /**\n * Marks tools as discovered via tool search.\n * Discovered tools will be included in the next model binding.\n * Only marks system runnable stale if NEW tools were actually added.\n * @param toolNames - Array of discovered tool names\n * @returns true if any new tools were discovered\n */\n markToolsAsDiscovered(toolNames: string[]): boolean {\n let hasNewDiscoveries = false;\n for (const name of toolNames) {\n if (!this.discoveredToolNames.has(name)) {\n this.discoveredToolNames.add(name);\n hasNewDiscoveries = true;\n }\n }\n if (hasNewDiscoveries) {\n this.systemRunnableStale = true;\n }\n return hasNewDiscoveries;\n }\n\n /**\n * Gets tools that should be bound to the LLM.\n * In event-driven mode (toolDefinitions present, tools empty), creates schema-only tools.\n * Otherwise filters tool instances based on:\n * 1. Non-deferred tools with allowed_callers: ['direct']\n * 2. Discovered tools (from tool search)\n * @returns Array of tools to bind to model\n */\n getToolsForBinding(): t.GraphTools | undefined {\n if (this.toolDefinitions && this.toolDefinitions.length > 0) {\n return this.getEventDrivenToolsForBinding();\n }\n\n const filtered = this.getEffectiveInstanceTools();\n\n if (this.graphTools && this.graphTools.length > 0) {\n return [...(filtered ?? []), ...this.graphTools];\n }\n\n return filtered;\n }\n\n /** Creates schema-only tools from toolDefinitions for event-driven mode, merged with native tools */\n private getEventDrivenToolsForBinding(): t.GraphTools {\n if (!this.toolDefinitions) {\n return this.graphTools ?? [];\n }\n\n const schemaTools = createSchemaOnlyTools(\n this.getActiveToolDefinitions()\n ) as t.GraphTools;\n\n const allTools = [...schemaTools];\n\n if (this.graphTools && this.graphTools.length > 0) {\n allTools.push(...this.graphTools);\n }\n\n const instanceTools = this.getEffectiveInstanceTools();\n if (instanceTools && instanceTools.length > 0) {\n allTools.push(...instanceTools);\n }\n\n return allTools;\n }\n\n /** Filters tool instances for binding based on registry config */\n private filterToolsForBinding(tools: t.GraphTools): t.GraphTools {\n return tools.filter((tool) => {\n if (!('name' in tool)) {\n return true;\n }\n\n const toolDef = this.toolRegistry?.get(tool.name);\n if (!toolDef) {\n return true;\n }\n\n if (this.discoveredToolNames.has(tool.name)) {\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return allowedCallers.includes('direct');\n }\n\n const allowedCallers = toolDef.allowed_callers ?? ['direct'];\n return (\n allowedCallers.includes('direct') && toolDef.defer_loading !== true\n );\n });\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;AAAA;AAgCA;;AAEG;MACU,YAAY,CAAA;AACvB;;AAEG;AACH,IAAA,OAAO,UAAU,CACf,WAA0B,EAC1B,YAA6B,EAC7B,kBAA2C,EAAA;QAE3C,MAAM,EACJ,OAAO,EACP,IAAI,EACJ,QAAQ,EACR,aAAa,EACb,KAAK,EACL,OAAO,EACP,OAAO,EACP,YAAY,EACZ,eAAe,EACf,YAAY,EACZ,uBAAuB,EACvB,YAAY,EACZ,gBAAgB,EAChB,YAAY,EACZ,gBAAgB,EAChB,eAAe,EACf,oBAAoB,EACpB,mBAAmB,EACnB,cAAc,EACd,oBAAoB,EACpB,kBAAkB,EAClB,gBAAgB,EAChB,eAAe,EACf,gBAAgB,GACjB,GAAG,WAAW;AAEf,QAAA,MAAM,YAAY,GAAG,IAAI,YAAY,CAAC;YACpC,OAAO;YACP,IAAI,EAAE,IAAI,IAAI,OAAO;YACrB,QAAQ;YACR,aAAa;YACb,gBAAgB;YAChB,YAAY;YACZ,KAAK;YACL,OAAO;YACP,YAAY;YACZ,eAAe;YACf,YAAY;AACZ,YAAA,sBAAsB,EAAE,uBAAuB;YAC/C,YAAY;YACZ,OAAO;AACP,YAAA,iBAAiB,EAAE,CAAC;YACpB,YAAY;YACZ,gBAAgB;YAChB,eAAe;YACf,oBAAoB;YACpB,mBAAmB;YACnB,oBAAoB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,IAAI,CAAC;YACjD,IAAI,CAAC,OAAO,EAAE;AACZ,gBAAA,OAAO,IAAI;YACb;YAEA,IAAI,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;gBAC3C,MAAM,cAAc,GAAG,OAAO,CAAC,eAAe,IAAI,CAAC,QAAQ,CAAC;AAC5D,gBAAA,OAAO,cAAc,CAAC,QAAQ,CAAC,QAAQ,CAAC;YAC1C;YAEA,MAAM,cAAc,GAAG,OAAO,CAAC,eAAe,IAAI,CAAC,QAAQ,CAAC;AAC5D,YAAA,QACE,cAAc,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,OAAO,CAAC,aAAa,KAAK,IAAI;AAEvE,QAAA,CAAC,CAAC;IACJ;AACD;;;;"}
|
|
@@ -273,12 +273,22 @@ class StandardGraph extends Graph {
|
|
|
273
273
|
getKeyList(metadata) {
|
|
274
274
|
if (!metadata)
|
|
275
275
|
return [];
|
|
276
|
+
const configurable = this.config?.configurable;
|
|
277
|
+
const runId = metadata.run_id ??
|
|
278
|
+
configurable?.run_id ??
|
|
279
|
+
this.runId;
|
|
280
|
+
const threadId = metadata.thread_id ??
|
|
281
|
+
configurable?.thread_id ??
|
|
282
|
+
runId;
|
|
283
|
+
const checkpointNs = metadata.checkpoint_ns ??
|
|
284
|
+
metadata.langgraph_checkpoint_ns ??
|
|
285
|
+
'';
|
|
276
286
|
const keyList = [
|
|
277
|
-
|
|
278
|
-
|
|
287
|
+
runId,
|
|
288
|
+
threadId,
|
|
279
289
|
metadata.langgraph_node,
|
|
280
290
|
metadata.langgraph_step,
|
|
281
|
-
|
|
291
|
+
checkpointNs,
|
|
282
292
|
];
|
|
283
293
|
const agentContext = this.getAgentContext(metadata);
|
|
284
294
|
if (agentContext.currentTokenType === ContentTypes.THINK ||
|