@librechat/agents 3.1.65 → 3.1.66

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.
@@ -491,6 +491,13 @@ class AgentContext {
491
491
  updateTokenMapWithInstructions(baseTokenMap) {
492
492
  this.indexTokenCountMap = { ...baseTokenMap };
493
493
  }
494
+ /** Active tool definitions for token accounting (excludes deferred-and-undiscovered entries). */
495
+ getActiveToolDefinitions() {
496
+ if (!this.toolDefinitions) {
497
+ return [];
498
+ }
499
+ return this.toolDefinitions.filter((def) => def.defer_loading !== true || this.discoveredToolNames.has(def.name));
500
+ }
494
501
  /**
495
502
  * Calculate tool tokens and add to instruction tokens
496
503
  * Note: System message tokens are calculated during systemRunnable creation
@@ -512,21 +519,19 @@ class AgentContext {
512
519
  }
513
520
  }
514
521
  }
515
- if (this.toolDefinitions && this.toolDefinitions.length > 0) {
516
- for (const def of this.toolDefinitions) {
517
- if (countedToolNames.has(def.name)) {
518
- continue;
519
- }
520
- const schema = {
521
- type: 'function',
522
- function: {
523
- name: def.name,
524
- description: def.description ?? '',
525
- parameters: def.parameters ?? {},
526
- },
527
- };
528
- toolTokens += tokenCounter(new messages.SystemMessage(JSON.stringify(schema)));
522
+ for (const def of this.getActiveToolDefinitions()) {
523
+ if (countedToolNames.has(def.name)) {
524
+ continue;
529
525
  }
526
+ const schema = {
527
+ type: 'function',
528
+ function: {
529
+ name: def.name,
530
+ description: def.description ?? '',
531
+ parameters: def.parameters ?? {},
532
+ },
533
+ };
534
+ toolTokens += tokenCounter(new messages.SystemMessage(JSON.stringify(schema)));
530
535
  }
531
536
  const isAnthropic = this.provider !== _enum.Providers.BEDROCK &&
532
537
  (this.provider === _enum.Providers.ANTHROPIC ||
@@ -650,10 +655,14 @@ class AgentContext {
650
655
  /**
651
656
  * Returns a structured breakdown of how the context token budget is consumed.
652
657
  * Useful for diagnostics when context overflow or pruning issues occur.
658
+ *
659
+ * Note: `toolCount` reflects discoveries immediately, but `toolSchemaTokens`
660
+ * is a snapshot taken during `calculateInstructionTokens` and is not
661
+ * recomputed when `markToolsAsDiscovered` is called mid-run.
653
662
  */
654
663
  getTokenBudgetBreakdown(messages) {
655
664
  const maxContextTokens = this.maxContextTokens ?? 0;
656
- const toolCount = (this.tools?.length ?? 0) + (this.toolDefinitions?.length ?? 0);
665
+ const toolCount = (this.tools?.length ?? 0) + this.getActiveToolDefinitions().length;
657
666
  const messageCount = messages?.length ?? 0;
658
667
  let messageTokens = 0;
659
668
  if (messages != null) {
@@ -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 } = 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 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 /** 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 /**\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 if (this.tools && this.tools.length > 0) {\n for (const tool of this.tools) {\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 if (this.toolDefinitions && this.toolDefinitions.length > 0) {\n for (const def of this.toolDefinitions) {\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\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 getTokenBudgetBreakdown(messages?: BaseMessage[]): t.TokenBudgetBreakdown {\n const maxContextTokens = this.maxContextTokens ?? 0;\n const toolCount =\n (this.tools?.length ?? 0) + (this.toolDefinitions?.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 =\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":["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,uBAAuB,EACvB,YAAY,EACZ,gBAAgB,EAChB,YAAY,EACZ,gBAAgB,EAChB,eAAe,EACf,oBAAoB,EACpB,mBAAmB,EACnB,cAAc,EACd,oBAAoB,EACpB,kBAAkB,EAClB,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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C,GAAG,IAAI,CAAC,UAAU,CAAC;QACnC;AAEA,QAAA,IAAI,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE;YACvC,QAAQ,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC;QAC9B;AAEA,QAAA,OAAO,QAAQ;IACjB;;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\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 } = 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 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 /** 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 if (this.tools && this.tools.length > 0) {\n for (const tool of this.tools) {\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":["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,uBAAuB,EACvB,YAAY,EACZ,gBAAgB,EAChB,YAAY,EACZ,gBAAgB,EAChB,eAAe,EACf,oBAAoB,EACpB,mBAAmB,EACnB,cAAc,EACd,oBAAoB,EACpB,kBAAkB,EAClB,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,IAAI,cAAc,EAAE,IAAI,IAAI,IAAI,IAAI,cAAc,CAAC,IAAI,KAAK,EAAE,EAAE;YAC9D,YAAY,CAAC,iBAAiB,CAC5B,cAAc,CAAC,IAAI,EACnB,cAAc,CAAC,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AI,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC;QAC9B;AAEA,QAAA,OAAO,QAAQ;IACjB;;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;;;;"}
@@ -489,6 +489,13 @@ class AgentContext {
489
489
  updateTokenMapWithInstructions(baseTokenMap) {
490
490
  this.indexTokenCountMap = { ...baseTokenMap };
491
491
  }
492
+ /** Active tool definitions for token accounting (excludes deferred-and-undiscovered entries). */
493
+ getActiveToolDefinitions() {
494
+ if (!this.toolDefinitions) {
495
+ return [];
496
+ }
497
+ return this.toolDefinitions.filter((def) => def.defer_loading !== true || this.discoveredToolNames.has(def.name));
498
+ }
492
499
  /**
493
500
  * Calculate tool tokens and add to instruction tokens
494
501
  * Note: System message tokens are calculated during systemRunnable creation
@@ -510,21 +517,19 @@ class AgentContext {
510
517
  }
511
518
  }
512
519
  }
513
- if (this.toolDefinitions && this.toolDefinitions.length > 0) {
514
- for (const def of this.toolDefinitions) {
515
- if (countedToolNames.has(def.name)) {
516
- continue;
517
- }
518
- const schema = {
519
- type: 'function',
520
- function: {
521
- name: def.name,
522
- description: def.description ?? '',
523
- parameters: def.parameters ?? {},
524
- },
525
- };
526
- toolTokens += tokenCounter(new SystemMessage(JSON.stringify(schema)));
520
+ for (const def of this.getActiveToolDefinitions()) {
521
+ if (countedToolNames.has(def.name)) {
522
+ continue;
527
523
  }
524
+ const schema = {
525
+ type: 'function',
526
+ function: {
527
+ name: def.name,
528
+ description: def.description ?? '',
529
+ parameters: def.parameters ?? {},
530
+ },
531
+ };
532
+ toolTokens += tokenCounter(new SystemMessage(JSON.stringify(schema)));
528
533
  }
529
534
  const isAnthropic = this.provider !== Providers.BEDROCK &&
530
535
  (this.provider === Providers.ANTHROPIC ||
@@ -648,10 +653,14 @@ class AgentContext {
648
653
  /**
649
654
  * Returns a structured breakdown of how the context token budget is consumed.
650
655
  * Useful for diagnostics when context overflow or pruning issues occur.
656
+ *
657
+ * Note: `toolCount` reflects discoveries immediately, but `toolSchemaTokens`
658
+ * is a snapshot taken during `calculateInstructionTokens` and is not
659
+ * recomputed when `markToolsAsDiscovered` is called mid-run.
651
660
  */
652
661
  getTokenBudgetBreakdown(messages) {
653
662
  const maxContextTokens = this.maxContextTokens ?? 0;
654
- const toolCount = (this.tools?.length ?? 0) + (this.toolDefinitions?.length ?? 0);
663
+ const toolCount = (this.tools?.length ?? 0) + this.getActiveToolDefinitions().length;
655
664
  const messageCount = messages?.length ?? 0;
656
665
  let messageTokens = 0;
657
666
  if (messages != null) {
@@ -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 } = 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 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 /** 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 /**\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 if (this.tools && this.tools.length > 0) {\n for (const tool of this.tools) {\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 if (this.toolDefinitions && this.toolDefinitions.length > 0) {\n for (const def of this.toolDefinitions) {\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\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 getTokenBudgetBreakdown(messages?: BaseMessage[]): t.TokenBudgetBreakdown {\n const maxContextTokens = this.maxContextTokens ?? 0;\n const toolCount =\n (this.tools?.length ?? 0) + (this.toolDefinitions?.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 =\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,EA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D,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.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 } = 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 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 /** 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 if (this.tools && this.tools.length > 0) {\n for (const tool of this.tools) {\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,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,EAA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record<string, number>): void;
233
+ /** Active tool definitions for token accounting (excludes deferred-and-undiscovered entries). */
234
+ private getActiveToolDefinitions;
233
235
  /**
234
236
  * Calculate tool tokens and add to instruction tokens
235
237
  * Note: System message tokens are calculated during systemRunnable creation
@@ -284,6 +286,10 @@ export declare class AgentContext {
284
286
  /**
285
287
  * Returns a structured breakdown of how the context token budget is consumed.
286
288
  * Useful for diagnostics when context overflow or pruning issues occur.
289
+ *
290
+ * Note: `toolCount` reflects discoveries immediately, but `toolSchemaTokens`
291
+ * is a snapshot taken during `calculateInstructionTokens` and is not
292
+ * recomputed when `markToolsAsDiscovered` is called mid-run.
287
293
  */
288
294
  getTokenBudgetBreakdown(messages?: BaseMessage[]): t.TokenBudgetBreakdown;
289
295
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@librechat/agents",
3
- "version": "3.1.65",
3
+ "version": "3.1.66",
4
4
  "main": "./dist/cjs/main.cjs",
5
5
  "module": "./dist/esm/main.mjs",
6
6
  "types": "./dist/types/index.d.ts",
@@ -664,6 +664,17 @@ export class AgentContext {
664
664
  this.indexTokenCountMap = { ...baseTokenMap };
665
665
  }
666
666
 
667
+ /** Active tool definitions for token accounting (excludes deferred-and-undiscovered entries). */
668
+ private getActiveToolDefinitions(): t.LCTool[] {
669
+ if (!this.toolDefinitions) {
670
+ return [];
671
+ }
672
+ return this.toolDefinitions.filter(
673
+ (def) =>
674
+ def.defer_loading !== true || this.discoveredToolNames.has(def.name)
675
+ );
676
+ }
677
+
667
678
  /**
668
679
  * Calculate tool tokens and add to instruction tokens
669
680
  * Note: System message tokens are calculated during systemRunnable creation
@@ -697,21 +708,19 @@ export class AgentContext {
697
708
  }
698
709
  }
699
710
 
700
- if (this.toolDefinitions && this.toolDefinitions.length > 0) {
701
- for (const def of this.toolDefinitions) {
702
- if (countedToolNames.has(def.name)) {
703
- continue;
704
- }
705
- const schema = {
706
- type: 'function',
707
- function: {
708
- name: def.name,
709
- description: def.description ?? '',
710
- parameters: def.parameters ?? {},
711
- },
712
- };
713
- toolTokens += tokenCounter(new SystemMessage(JSON.stringify(schema)));
711
+ for (const def of this.getActiveToolDefinitions()) {
712
+ if (countedToolNames.has(def.name)) {
713
+ continue;
714
714
  }
715
+ const schema = {
716
+ type: 'function',
717
+ function: {
718
+ name: def.name,
719
+ description: def.description ?? '',
720
+ parameters: def.parameters ?? {},
721
+ },
722
+ };
723
+ toolTokens += tokenCounter(new SystemMessage(JSON.stringify(schema)));
715
724
  }
716
725
 
717
726
  const isAnthropic =
@@ -860,11 +869,15 @@ export class AgentContext {
860
869
  /**
861
870
  * Returns a structured breakdown of how the context token budget is consumed.
862
871
  * Useful for diagnostics when context overflow or pruning issues occur.
872
+ *
873
+ * Note: `toolCount` reflects discoveries immediately, but `toolSchemaTokens`
874
+ * is a snapshot taken during `calculateInstructionTokens` and is not
875
+ * recomputed when `markToolsAsDiscovered` is called mid-run.
863
876
  */
864
877
  getTokenBudgetBreakdown(messages?: BaseMessage[]): t.TokenBudgetBreakdown {
865
878
  const maxContextTokens = this.maxContextTokens ?? 0;
866
879
  const toolCount =
867
- (this.tools?.length ?? 0) + (this.toolDefinitions?.length ?? 0);
880
+ (this.tools?.length ?? 0) + this.getActiveToolDefinitions().length;
868
881
  const messageCount = messages?.length ?? 0;
869
882
 
870
883
  let messageTokens = 0;
@@ -375,6 +375,116 @@ describe('AgentContext', () => {
375
375
 
376
376
  expect(ctx.instructionTokens).toBeGreaterThan(initialTokens);
377
377
  });
378
+
379
+ it('excludes deferred-undiscovered toolDefinitions from toolSchemaTokens', async () => {
380
+ const activeDef: t.LCTool = {
381
+ name: 'active_tool',
382
+ description: 'Always loaded',
383
+ parameters: { type: 'object', properties: {} },
384
+ };
385
+ const deferredDef: t.LCTool = {
386
+ name: 'deferred_tool',
387
+ description: 'Loaded via tool search',
388
+ parameters: { type: 'object', properties: {} },
389
+ defer_loading: true,
390
+ };
391
+
392
+ const ctxBase = createBasicContext({
393
+ agentConfig: { toolDefinitions: [activeDef] },
394
+ tokenCounter: mockTokenCounter,
395
+ });
396
+ const ctxWithDeferred = createBasicContext({
397
+ agentConfig: { toolDefinitions: [activeDef, deferredDef] },
398
+ tokenCounter: mockTokenCounter,
399
+ });
400
+
401
+ await ctxBase.tokenCalculationPromise;
402
+ await ctxWithDeferred.tokenCalculationPromise;
403
+
404
+ expect(ctxWithDeferred.toolSchemaTokens).toBe(ctxBase.toolSchemaTokens);
405
+ });
406
+
407
+ it('includes deferred toolDefinitions once discovered via discoveredTools input', async () => {
408
+ const toolDefinitions: t.LCTool[] = [
409
+ {
410
+ name: 'deferred_tool',
411
+ description: 'Loaded via tool search',
412
+ parameters: { type: 'object', properties: {} },
413
+ defer_loading: true,
414
+ },
415
+ ];
416
+
417
+ const ctxUndiscovered = createBasicContext({
418
+ agentConfig: { toolDefinitions },
419
+ tokenCounter: mockTokenCounter,
420
+ });
421
+ const ctxDiscovered = createBasicContext({
422
+ agentConfig: { toolDefinitions, discoveredTools: ['deferred_tool'] },
423
+ tokenCounter: mockTokenCounter,
424
+ });
425
+
426
+ await ctxUndiscovered.tokenCalculationPromise;
427
+ await ctxDiscovered.tokenCalculationPromise;
428
+
429
+ expect(ctxUndiscovered.toolSchemaTokens).toBe(0);
430
+ expect(ctxDiscovered.toolSchemaTokens).toBeGreaterThan(0);
431
+ });
432
+
433
+ it('getTokenBudgetBreakdown toolCount excludes deferred-undiscovered toolDefinitions', () => {
434
+ const toolDefinitions: t.LCTool[] = [
435
+ {
436
+ name: 'active',
437
+ parameters: { type: 'object', properties: {} },
438
+ },
439
+ {
440
+ name: 'deferred',
441
+ defer_loading: true,
442
+ parameters: { type: 'object', properties: {} },
443
+ },
444
+ ];
445
+
446
+ const ctx = createBasicContext({ agentConfig: { toolDefinitions } });
447
+
448
+ expect(ctx.getTokenBudgetBreakdown().toolCount).toBe(1);
449
+ });
450
+
451
+ it('getTokenBudgetBreakdown toolCount reflects newly discovered deferred tools', () => {
452
+ const toolDefinitions: t.LCTool[] = [
453
+ {
454
+ name: 'deferred',
455
+ defer_loading: true,
456
+ parameters: { type: 'object', properties: {} },
457
+ },
458
+ ];
459
+
460
+ const ctx = createBasicContext({ agentConfig: { toolDefinitions } });
461
+
462
+ expect(ctx.getTokenBudgetBreakdown().toolCount).toBe(0);
463
+ ctx.markToolsAsDiscovered(['deferred']);
464
+ expect(ctx.getTokenBudgetBreakdown().toolCount).toBe(1);
465
+ });
466
+
467
+ it('toolSchemaTokens snapshot does not auto-update after markToolsAsDiscovered', async () => {
468
+ const toolDefinitions: t.LCTool[] = [
469
+ {
470
+ name: 'deferred',
471
+ description: 'Loaded via tool search',
472
+ parameters: { type: 'object', properties: {} },
473
+ defer_loading: true,
474
+ },
475
+ ];
476
+
477
+ const ctx = createBasicContext({
478
+ agentConfig: { toolDefinitions },
479
+ tokenCounter: mockTokenCounter,
480
+ });
481
+
482
+ await ctx.tokenCalculationPromise;
483
+ expect(ctx.toolSchemaTokens).toBe(0);
484
+
485
+ ctx.markToolsAsDiscovered(['deferred']);
486
+ expect(ctx.toolSchemaTokens).toBe(0);
487
+ });
378
488
  });
379
489
 
380
490
  describe('reset()', () => {