@librechat/agents 3.1.74 → 3.1.75
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 +84 -37
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +4 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
- package/dist/cjs/messages/cache.cjs +37 -3
- package/dist/cjs/messages/cache.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +85 -38
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs +4 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
- package/dist/esm/messages/cache.mjs +37 -3
- package/dist/esm/messages/cache.mjs.map +1 -1
- package/dist/types/agents/AgentContext.d.ts +14 -4
- package/dist/types/agents/__tests__/promptCacheLiveHelpers.d.ts +46 -0
- package/dist/types/types/graph.d.ts +3 -1
- package/dist/types/types/run.d.ts +2 -0
- package/package.json +1 -1
- package/src/agents/AgentContext.ts +123 -44
- 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 +155 -2
- package/src/agents/__tests__/promptCacheLiveHelpers.ts +165 -0
- package/src/llm/anthropic/utils/message_inputs.ts +6 -1
- package/src/llm/anthropic/utils/server-tool-inputs.test.ts +77 -0
- package/src/messages/cache.test.ts +104 -3
- package/src/messages/cache.ts +54 -3
- package/src/specs/anthropic.simple.test.ts +61 -0
- package/src/specs/summarization.test.ts +7 -3
- package/src/types/graph.ts +3 -1
- package/src/types/run.ts +2 -0
package/README.md
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# @librechat/agents
|
|
2
|
+
|
|
3
|
+
TypeScript utilities for building LibreChat agent workflows. The package provides graph orchestration, streaming event handling, tool execution, provider adapters, and message formatting for single-agent and multi-agent runs.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- LangGraph-based single-agent and multi-agent workflows
|
|
8
|
+
- Streaming content aggregation and run-step event handlers
|
|
9
|
+
- Tool calling, tool search, subagent handoffs, and programmatic tool execution
|
|
10
|
+
- Provider adapters for Anthropic, Bedrock, Vertex AI, OpenAI-compatible providers, Google, Mistral, DeepSeek, and xAI
|
|
11
|
+
- Message formatting, context pruning, summarization, and cache-control helpers
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install @librechat/agents
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
## Basic Usage
|
|
20
|
+
|
|
21
|
+
```typescript
|
|
22
|
+
import { HumanMessage } from '@langchain/core/messages';
|
|
23
|
+
import { Providers, Run } from '@librechat/agents';
|
|
24
|
+
|
|
25
|
+
const run = await Run.create({
|
|
26
|
+
runId: crypto.randomUUID(),
|
|
27
|
+
graphConfig: {
|
|
28
|
+
type: 'standard',
|
|
29
|
+
instructions: 'You are a helpful assistant.',
|
|
30
|
+
llmConfig: {
|
|
31
|
+
provider: Providers.OPENAI,
|
|
32
|
+
model: 'gpt-4o-mini',
|
|
33
|
+
apiKey: process.env.OPENAI_API_KEY,
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
returnContent: true,
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
const content = await run.processStream(
|
|
40
|
+
{ messages: [new HumanMessage('Hello')] },
|
|
41
|
+
{
|
|
42
|
+
runId: crypto.randomUUID(),
|
|
43
|
+
streamMode: 'values',
|
|
44
|
+
version: 'v2',
|
|
45
|
+
}
|
|
46
|
+
);
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Development
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
npm ci
|
|
53
|
+
npm run build
|
|
54
|
+
npm test
|
|
55
|
+
npx tsc --noEmit
|
|
56
|
+
npx eslint src/
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Documentation
|
|
60
|
+
|
|
61
|
+
- [Multi-agent patterns](./docs/multi-agent-patterns.md)
|
|
62
|
+
- [Summarization behavior](./docs/summarization-behavior.md)
|
|
63
|
+
|
|
64
|
+
## License
|
|
65
|
+
|
|
66
|
+
MIT
|
|
@@ -192,7 +192,7 @@ class AgentContext {
|
|
|
192
192
|
summaryTokenCount = 0;
|
|
193
193
|
/**
|
|
194
194
|
* Where the summary should be injected:
|
|
195
|
-
* - `'system_prompt'`: cross-run summary, included in
|
|
195
|
+
* - `'system_prompt'`: cross-run summary, included in the dynamic system tail
|
|
196
196
|
* - `'user_message'`: mid-run compaction, injected as HumanMessage on clean slate
|
|
197
197
|
* - `'none'`: no summary present
|
|
198
198
|
*/
|
|
@@ -298,15 +298,18 @@ class AgentContext {
|
|
|
298
298
|
}
|
|
299
299
|
/**
|
|
300
300
|
* Gets the system runnable, creating it lazily if needed.
|
|
301
|
-
* Includes instructions, additional instructions, and
|
|
301
|
+
* Includes stable instructions, dynamic additional instructions, and
|
|
302
|
+
* programmatic-only tools documentation.
|
|
302
303
|
* Only rebuilds when marked stale (via markToolsAsDiscovered).
|
|
303
304
|
*/
|
|
304
305
|
get systemRunnable() {
|
|
305
306
|
if (!this.systemRunnableStale && this.cachedSystemRunnable !== undefined) {
|
|
306
307
|
return this.cachedSystemRunnable;
|
|
307
308
|
}
|
|
308
|
-
|
|
309
|
-
|
|
309
|
+
this.cachedSystemRunnable = this.buildSystemRunnable({
|
|
310
|
+
stableInstructions: this.buildStableInstructionsString(),
|
|
311
|
+
dynamicInstructions: this.buildDynamicInstructionsString(),
|
|
312
|
+
});
|
|
310
313
|
this.systemRunnableStale = false;
|
|
311
314
|
return this.cachedSystemRunnable;
|
|
312
315
|
}
|
|
@@ -316,16 +319,18 @@ class AgentContext {
|
|
|
316
319
|
*/
|
|
317
320
|
initializeSystemRunnable() {
|
|
318
321
|
if (this.systemRunnableStale || this.cachedSystemRunnable === undefined) {
|
|
319
|
-
|
|
320
|
-
|
|
322
|
+
this.cachedSystemRunnable = this.buildSystemRunnable({
|
|
323
|
+
stableInstructions: this.buildStableInstructionsString(),
|
|
324
|
+
dynamicInstructions: this.buildDynamicInstructionsString(),
|
|
325
|
+
});
|
|
321
326
|
this.systemRunnableStale = false;
|
|
322
327
|
}
|
|
323
328
|
}
|
|
324
329
|
/**
|
|
325
|
-
* Builds the
|
|
330
|
+
* Builds the cacheable instructions string (without creating SystemMessage).
|
|
326
331
|
* Includes agent identity preamble and handoff context when available.
|
|
327
332
|
*/
|
|
328
|
-
|
|
333
|
+
buildStableInstructionsString() {
|
|
329
334
|
const parts = [];
|
|
330
335
|
const identityPreamble = this.buildIdentityPreamble();
|
|
331
336
|
if (identityPreamble) {
|
|
@@ -334,17 +339,27 @@ class AgentContext {
|
|
|
334
339
|
if (this.instructions != null && this.instructions !== '') {
|
|
335
340
|
parts.push(this.instructions);
|
|
336
341
|
}
|
|
337
|
-
if (this.additionalInstructions != null &&
|
|
338
|
-
this.additionalInstructions !== '') {
|
|
339
|
-
parts.push(this.additionalInstructions);
|
|
340
|
-
}
|
|
341
342
|
const programmaticToolsDoc = this.buildProgrammaticOnlyToolsInstructions();
|
|
342
343
|
if (programmaticToolsDoc) {
|
|
343
344
|
parts.push(programmaticToolsDoc);
|
|
344
345
|
}
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
346
|
+
return parts.join('\n\n');
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Builds the dynamic system-tail string (without creating SystemMessage).
|
|
350
|
+
* Keep this out of prompt-cache-marked content so volatile context does not
|
|
351
|
+
* invalidate the stable prefix.
|
|
352
|
+
*/
|
|
353
|
+
buildDynamicInstructionsString() {
|
|
354
|
+
const parts = [];
|
|
355
|
+
if (this.additionalInstructions != null &&
|
|
356
|
+
this.additionalInstructions !== '') {
|
|
357
|
+
parts.push(this.additionalInstructions);
|
|
358
|
+
}
|
|
359
|
+
// Cross-run summary: include in the system tail so the model has context
|
|
360
|
+
// from the prior run without invalidating the cacheable prefix. Mid-run
|
|
361
|
+
// summaries are injected as a HumanMessage on the post-compaction clean
|
|
362
|
+
// slate instead (see buildSystemRunnable).
|
|
348
363
|
if (this._summaryLocation === 'system_prompt' &&
|
|
349
364
|
this.summaryText != null &&
|
|
350
365
|
this.summaryText !== '') {
|
|
@@ -375,34 +390,20 @@ class AgentContext {
|
|
|
375
390
|
* Build system runnable from pre-built instructions string.
|
|
376
391
|
* Only called when content has actually changed.
|
|
377
392
|
*/
|
|
378
|
-
buildSystemRunnable(
|
|
393
|
+
buildSystemRunnable({ stableInstructions, dynamicInstructions, }) {
|
|
379
394
|
const hasMidRunSummary = this._summaryLocation === 'user_message' &&
|
|
380
395
|
this.summaryText != null &&
|
|
381
396
|
this.summaryText !== '';
|
|
382
|
-
if (!
|
|
397
|
+
if (!stableInstructions && !dynamicInstructions && !hasMidRunSummary) {
|
|
383
398
|
this.systemMessageTokens = 0;
|
|
384
399
|
return undefined;
|
|
385
400
|
}
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
finalInstructions = {
|
|
393
|
-
content: [
|
|
394
|
-
{
|
|
395
|
-
type: 'text',
|
|
396
|
-
text: instructionsString,
|
|
397
|
-
cache_control: { type: 'ephemeral' },
|
|
398
|
-
},
|
|
399
|
-
],
|
|
400
|
-
};
|
|
401
|
-
}
|
|
402
|
-
}
|
|
403
|
-
const systemMessage = instructionsString
|
|
404
|
-
? new messages.SystemMessage(finalInstructions)
|
|
405
|
-
: undefined;
|
|
401
|
+
const usePromptCache = this.hasAnthropicPromptCache();
|
|
402
|
+
const systemMessage = this.buildSystemMessage({
|
|
403
|
+
stableInstructions,
|
|
404
|
+
dynamicInstructions,
|
|
405
|
+
usePromptCache,
|
|
406
|
+
});
|
|
406
407
|
if (this.tokenCounter) {
|
|
407
408
|
this.systemMessageTokens = systemMessage
|
|
408
409
|
? this.tokenCounter(systemMessage)
|
|
@@ -444,6 +445,52 @@ class AgentContext {
|
|
|
444
445
|
return [...prefix, ...body];
|
|
445
446
|
}).withConfig({ runName: 'prompt' });
|
|
446
447
|
}
|
|
448
|
+
hasAnthropicPromptCache() {
|
|
449
|
+
if (this.provider !== _enum.Providers.ANTHROPIC) {
|
|
450
|
+
return false;
|
|
451
|
+
}
|
|
452
|
+
const anthropicOptions = this.clientOptions;
|
|
453
|
+
return anthropicOptions?.promptCache === true;
|
|
454
|
+
}
|
|
455
|
+
hasBedrockPromptCache() {
|
|
456
|
+
if (this.provider !== _enum.Providers.BEDROCK) {
|
|
457
|
+
return false;
|
|
458
|
+
}
|
|
459
|
+
const bedrockOptions = this.clientOptions;
|
|
460
|
+
return bedrockOptions?.promptCache === true;
|
|
461
|
+
}
|
|
462
|
+
buildSystemMessage({ stableInstructions, dynamicInstructions, usePromptCache, }) {
|
|
463
|
+
if (!stableInstructions && !dynamicInstructions) {
|
|
464
|
+
return undefined;
|
|
465
|
+
}
|
|
466
|
+
if (usePromptCache) {
|
|
467
|
+
const content = [];
|
|
468
|
+
if (stableInstructions) {
|
|
469
|
+
content.push({
|
|
470
|
+
type: 'text',
|
|
471
|
+
text: stableInstructions,
|
|
472
|
+
cache_control: { type: 'ephemeral' },
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
if (dynamicInstructions) {
|
|
476
|
+
content.push({ type: 'text', text: dynamicInstructions });
|
|
477
|
+
}
|
|
478
|
+
return new messages.SystemMessage({ content });
|
|
479
|
+
}
|
|
480
|
+
if (this.hasBedrockPromptCache() && stableInstructions) {
|
|
481
|
+
const content = [
|
|
482
|
+
{ type: 'text', text: stableInstructions },
|
|
483
|
+
{ cachePoint: { type: 'default' } },
|
|
484
|
+
];
|
|
485
|
+
if (dynamicInstructions) {
|
|
486
|
+
content.push({ type: 'text', text: dynamicInstructions });
|
|
487
|
+
}
|
|
488
|
+
return new messages.SystemMessage({ content });
|
|
489
|
+
}
|
|
490
|
+
return new messages.SystemMessage([stableInstructions, dynamicInstructions]
|
|
491
|
+
.filter((part) => part !== '')
|
|
492
|
+
.join('\n\n'));
|
|
493
|
+
}
|
|
447
494
|
/**
|
|
448
495
|
* Reset context for a new run
|
|
449
496
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AgentContext.cjs","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 /**\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":["ContentTypes","Providers","SystemMessage","RunnableLambda","messages","HumanMessage","addCacheControl","toJsonSchema","ANTHROPIC_TOOL_TOKEN_MULTIPLIER","DEFAULT_TOOL_TOKEN_MULTIPLIER","DEFAULT_RESERVE_RATIO","createSchemaOnlyTools"],"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,uBA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ACjB;;AAGQ,IAAA,qBAAqB,CAAC,KAAmB,EAAA;AAC/C,QAAA,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,KAAI;AAC3B,YAAA,IAAI,EAAE,MAAM,IAAI,IAAI,CAAC,EAAE;AACrB,gBAAA,OAAO,IAAI;YACb;AAEA,YAAA,MAAM,OAAO,GAAG,IAAI,CAAC,YAAY,EAAE,GAAG,CAAC,IAAI,CAAC,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;;;;"}
|
|
1
|
+
{"version":3,"file":"AgentContext.cjs","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\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":["ContentTypes","RunnableLambda","messages","HumanMessage","addCacheControl","Providers","SystemMessage","toJsonSchema","ANTHROPIC_TOOL_TOKEN_MULTIPLIER","DEFAULT_TOOL_TOKEN_MULTIPLIER","DEFAULT_RESERVE_RATIO","createSchemaOnlyTools"],"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;YACpB,kBAAkB;AACnB,SAAA,CAAC;AAEF,QAAA,YAAY,CAAC,aAAa,GAAG,WAAW;AACxC,QAAA,YAAY,CAAC,eAAe,GAAG,eAAe;AAC9C,QAAA,YAAY,CAAC,gBAAgB,GAAG,gBAAgB;AAEhD,QAAA,IAAI,cAAc,EAAE,IAAI,IAAI,IAAI,IAAI,cA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O,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;;;;"}
|
|
@@ -519,7 +519,10 @@ function _formatContent(message) {
|
|
|
519
519
|
}
|
|
520
520
|
});
|
|
521
521
|
return contentBlocks.filter((block) => block !== null &&
|
|
522
|
-
!(block.type === 'text' &&
|
|
522
|
+
!(block.type === 'text' &&
|
|
523
|
+
'text' in block &&
|
|
524
|
+
typeof block.text === 'string' &&
|
|
525
|
+
block.text.trim() === ''));
|
|
523
526
|
}
|
|
524
527
|
}
|
|
525
528
|
/**
|