@illuma-ai/agents 1.0.98 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +6 -2
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/common/constants.cjs +53 -0
  4. package/dist/cjs/common/constants.cjs.map +1 -1
  5. package/dist/cjs/graphs/Graph.cjs +167 -31
  6. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  7. package/dist/cjs/main.cjs +14 -0
  8. package/dist/cjs/main.cjs.map +1 -1
  9. package/dist/cjs/messages/dedup.cjs +95 -0
  10. package/dist/cjs/messages/dedup.cjs.map +1 -0
  11. package/dist/cjs/tools/CodeExecutor.cjs +22 -3
  12. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  13. package/dist/cjs/types/graph.cjs.map +1 -1
  14. package/dist/cjs/utils/pruneCalibration.cjs +78 -0
  15. package/dist/cjs/utils/pruneCalibration.cjs.map +1 -0
  16. package/dist/cjs/utils/run.cjs.map +1 -1
  17. package/dist/cjs/utils/tokens.cjs.map +1 -1
  18. package/dist/cjs/utils/toolDiscoveryCache.cjs +127 -0
  19. package/dist/cjs/utils/toolDiscoveryCache.cjs.map +1 -0
  20. package/dist/esm/agents/AgentContext.mjs +6 -2
  21. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  22. package/dist/esm/common/constants.mjs +48 -1
  23. package/dist/esm/common/constants.mjs.map +1 -1
  24. package/dist/esm/graphs/Graph.mjs +168 -32
  25. package/dist/esm/graphs/Graph.mjs.map +1 -1
  26. package/dist/esm/main.mjs +4 -1
  27. package/dist/esm/main.mjs.map +1 -1
  28. package/dist/esm/messages/dedup.mjs +93 -0
  29. package/dist/esm/messages/dedup.mjs.map +1 -0
  30. package/dist/esm/tools/CodeExecutor.mjs +22 -3
  31. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  32. package/dist/esm/types/graph.mjs.map +1 -1
  33. package/dist/esm/utils/pruneCalibration.mjs +74 -0
  34. package/dist/esm/utils/pruneCalibration.mjs.map +1 -0
  35. package/dist/esm/utils/run.mjs.map +1 -1
  36. package/dist/esm/utils/tokens.mjs.map +1 -1
  37. package/dist/esm/utils/toolDiscoveryCache.mjs +125 -0
  38. package/dist/esm/utils/toolDiscoveryCache.mjs.map +1 -0
  39. package/dist/types/agents/AgentContext.d.ts +4 -1
  40. package/dist/types/common/constants.d.ts +35 -0
  41. package/dist/types/graphs/Graph.d.ts +25 -0
  42. package/dist/types/messages/dedup.d.ts +25 -0
  43. package/dist/types/messages/index.d.ts +1 -0
  44. package/dist/types/types/graph.d.ts +63 -0
  45. package/dist/types/utils/index.d.ts +2 -0
  46. package/dist/types/utils/pruneCalibration.d.ts +43 -0
  47. package/dist/types/utils/toolDiscoveryCache.d.ts +77 -0
  48. package/package.json +1 -1
  49. package/src/agents/AgentContext.ts +7 -0
  50. package/src/common/constants.ts +56 -0
  51. package/src/graphs/Graph.ts +220 -50
  52. package/src/graphs/gapFeatures.test.ts +520 -0
  53. package/src/graphs/nonBlockingSummarization.test.ts +307 -0
  54. package/src/messages/__tests__/dedup.test.ts +166 -0
  55. package/src/messages/dedup.ts +104 -0
  56. package/src/messages/index.ts +1 -0
  57. package/src/tools/CodeExecutor.ts +22 -3
  58. package/src/types/graph.ts +73 -0
  59. package/src/utils/__tests__/pruneCalibration.test.ts +148 -0
  60. package/src/utils/__tests__/toolDiscoveryCache.test.ts +214 -0
  61. package/src/utils/contextPressure.test.ts +24 -9
  62. package/src/utils/index.ts +2 -0
  63. package/src/utils/pruneCalibration.ts +92 -0
  64. package/src/utils/run.ts +108 -108
  65. package/src/utils/tokens.ts +118 -118
  66. package/src/utils/toolDiscoveryCache.ts +150 -0
@@ -0,0 +1,127 @@
1
+ 'use strict';
2
+
3
+ var _enum = require('../common/enum.cjs');
4
+ var constants = require('../common/constants.cjs');
5
+
6
+ /**
7
+ * ToolDiscoveryCache provides a run-scoped cache of tool search results.
8
+ *
9
+ * Problem: Without caching, every LLM iteration re-parses the full message
10
+ * history via extractToolDiscoveries() to find tool_search results. In long
11
+ * conversations with many tool iterations, this is redundant work.
12
+ *
13
+ * Solution: Cache discovered tool names by message index. On each iteration,
14
+ * only scan messages AFTER the last scanned index. Already-seen discoveries
15
+ * are returned from cache instantly.
16
+ *
17
+ * This mirrors the pattern used by VS Code Copilot Chat where tool search
18
+ * results from prior turns are cached to avoid re-discovery.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * const cache = new ToolDiscoveryCache();
23
+ *
24
+ * // First call: scans all messages
25
+ * const newTools = cache.getNewDiscoveries(messages);
26
+ * // Returns: ['web_search', 'file_read']
27
+ *
28
+ * // Second call (3 new messages added): only scans new messages
29
+ * const moreTools = cache.getNewDiscoveries(messages);
30
+ * // Returns: ['code_exec'] (only newly discovered)
31
+ * ```
32
+ */
33
+ class ToolDiscoveryCache {
34
+ /** Set of all discovered tool names (deduped) */
35
+ _discoveredTools = new Set();
36
+ /** Last message index that was scanned */
37
+ _lastScannedIndex = -1;
38
+ /**
39
+ * Scan messages for new tool_search results since the last scan.
40
+ * Only processes messages after `_lastScannedIndex` to avoid redundant work.
41
+ *
42
+ * @param messages - Full conversation message array
43
+ * @returns Array of newly discovered tool names (not previously cached)
44
+ */
45
+ getNewDiscoveries(messages) {
46
+ if (messages.length === 0) {
47
+ return [];
48
+ }
49
+ const startIndex = this._lastScannedIndex + 1;
50
+ if (startIndex >= messages.length) {
51
+ return [];
52
+ }
53
+ const newDiscoveries = [];
54
+ for (let i = startIndex; i < messages.length; i++) {
55
+ const msg = messages[i];
56
+ if (msg.getType() !== _enum.MessageTypes.TOOL) {
57
+ continue;
58
+ }
59
+ // Check if this is a tool_search result
60
+ if (msg.name !== _enum.Constants.TOOL_SEARCH) {
61
+ continue;
62
+ }
63
+ // Extract tool references from artifact
64
+ const artifact = msg.artifact;
65
+ if (typeof artifact === 'object' && artifact != null) {
66
+ const refs = artifact.tool_references;
67
+ if (refs && refs.length > 0) {
68
+ for (const ref of refs) {
69
+ if (!this._discoveredTools.has(ref.tool_name)) {
70
+ // Enforce cache size limit
71
+ if (this._discoveredTools.size >= constants.TOOL_DISCOVERY_CACHE_MAX_SIZE) {
72
+ break;
73
+ }
74
+ this._discoveredTools.add(ref.tool_name);
75
+ newDiscoveries.push(ref.tool_name);
76
+ }
77
+ }
78
+ }
79
+ }
80
+ }
81
+ this._lastScannedIndex = messages.length - 1;
82
+ return newDiscoveries;
83
+ }
84
+ /**
85
+ * Returns all tool names discovered so far (across all scans).
86
+ */
87
+ getAllDiscoveredTools() {
88
+ return [...this._discoveredTools];
89
+ }
90
+ /**
91
+ * Check if a specific tool has been discovered.
92
+ */
93
+ has(toolName) {
94
+ return this._discoveredTools.has(toolName);
95
+ }
96
+ /**
97
+ * Number of unique tools discovered.
98
+ */
99
+ get size() {
100
+ return this._discoveredTools.size;
101
+ }
102
+ /**
103
+ * Reset the cache (e.g., on graph reset).
104
+ */
105
+ reset() {
106
+ this._discoveredTools.clear();
107
+ this._lastScannedIndex = -1;
108
+ }
109
+ /**
110
+ * Seed the cache with previously known tool names (e.g., from prior conversation turns).
111
+ * Does not affect _lastScannedIndex — the next getNewDiscoveries call will still
112
+ * scan all messages from the beginning.
113
+ *
114
+ * @param toolNames - Tool names to pre-seed into the cache
115
+ */
116
+ seed(toolNames) {
117
+ for (const name of toolNames) {
118
+ if (this._discoveredTools.size >= constants.TOOL_DISCOVERY_CACHE_MAX_SIZE) {
119
+ break;
120
+ }
121
+ this._discoveredTools.add(name);
122
+ }
123
+ }
124
+ }
125
+
126
+ exports.ToolDiscoveryCache = ToolDiscoveryCache;
127
+ //# sourceMappingURL=toolDiscoveryCache.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"toolDiscoveryCache.cjs","sources":["../../../src/utils/toolDiscoveryCache.ts"],"sourcesContent":["// src/utils/toolDiscoveryCache.ts\nimport type { BaseMessage } from '@langchain/core/messages';\nimport { Constants, MessageTypes } from '@/common';\nimport { TOOL_DISCOVERY_CACHE_MAX_SIZE } from '@/common/constants';\n\n/**\n * Cached tool discovery entry.\n * Stores the tool name and the message index where it was discovered,\n * enabling efficient lookups without re-parsing conversation history.\n */\nexport interface ToolDiscoveryEntry {\n /** The tool name that was discovered */\n toolName: string;\n /** Message index in conversation history where discovery occurred */\n discoveredAtIndex: number;\n}\n\n/**\n * ToolDiscoveryCache provides a run-scoped cache of tool search results.\n *\n * Problem: Without caching, every LLM iteration re-parses the full message\n * history via extractToolDiscoveries() to find tool_search results. In long\n * conversations with many tool iterations, this is redundant work.\n *\n * Solution: Cache discovered tool names by message index. On each iteration,\n * only scan messages AFTER the last scanned index. Already-seen discoveries\n * are returned from cache instantly.\n *\n * This mirrors the pattern used by VS Code Copilot Chat where tool search\n * results from prior turns are cached to avoid re-discovery.\n *\n * @example\n * ```ts\n * const cache = new ToolDiscoveryCache();\n *\n * // First call: scans all messages\n * const newTools = cache.getNewDiscoveries(messages);\n * // Returns: ['web_search', 'file_read']\n *\n * // Second call (3 new messages added): only scans new messages\n * const moreTools = cache.getNewDiscoveries(messages);\n * // Returns: ['code_exec'] (only newly discovered)\n * ```\n */\nexport class ToolDiscoveryCache {\n /** Set of all discovered tool names (deduped) */\n private _discoveredTools: Set<string> = new Set();\n /** Last message index that was scanned */\n private _lastScannedIndex: number = -1;\n\n /**\n * Scan messages for new tool_search results since the last scan.\n * Only processes messages after `_lastScannedIndex` to avoid redundant work.\n *\n * @param messages - Full conversation message array\n * @returns Array of newly discovered tool names (not previously cached)\n */\n getNewDiscoveries(messages: BaseMessage[]): string[] {\n if (messages.length === 0) {\n return [];\n }\n\n const startIndex = this._lastScannedIndex + 1;\n if (startIndex >= messages.length) {\n return [];\n }\n\n const newDiscoveries: string[] = [];\n\n for (let i = startIndex; i < messages.length; i++) {\n const msg = messages[i];\n if (msg.getType() !== MessageTypes.TOOL) {\n continue;\n }\n\n // Check if this is a tool_search result\n if ((msg as { name?: string }).name !== Constants.TOOL_SEARCH) {\n continue;\n }\n\n // Extract tool references from artifact\n const artifact = (msg as { artifact?: unknown }).artifact;\n if (typeof artifact === 'object' && artifact != null) {\n const refs = (\n artifact as { tool_references?: Array<{ tool_name: string }> }\n ).tool_references;\n if (refs && refs.length > 0) {\n for (const ref of refs) {\n if (!this._discoveredTools.has(ref.tool_name)) {\n // Enforce cache size limit\n if (this._discoveredTools.size >= TOOL_DISCOVERY_CACHE_MAX_SIZE) {\n break;\n }\n this._discoveredTools.add(ref.tool_name);\n newDiscoveries.push(ref.tool_name);\n }\n }\n }\n }\n }\n\n this._lastScannedIndex = messages.length - 1;\n return newDiscoveries;\n }\n\n /**\n * Returns all tool names discovered so far (across all scans).\n */\n getAllDiscoveredTools(): string[] {\n return [...this._discoveredTools];\n }\n\n /**\n * Check if a specific tool has been discovered.\n */\n has(toolName: string): boolean {\n return this._discoveredTools.has(toolName);\n }\n\n /**\n * Number of unique tools discovered.\n */\n get size(): number {\n return this._discoveredTools.size;\n }\n\n /**\n * Reset the cache (e.g., on graph reset).\n */\n reset(): void {\n this._discoveredTools.clear();\n this._lastScannedIndex = -1;\n }\n\n /**\n * Seed the cache with previously known tool names (e.g., from prior conversation turns).\n * Does not affect _lastScannedIndex — the next getNewDiscoveries call will still\n * scan all messages from the beginning.\n *\n * @param toolNames - Tool names to pre-seed into the cache\n */\n seed(toolNames: string[]): void {\n for (const name of toolNames) {\n if (this._discoveredTools.size >= TOOL_DISCOVERY_CACHE_MAX_SIZE) {\n break;\n }\n this._discoveredTools.add(name);\n }\n }\n}\n"],"names":["MessageTypes","Constants","TOOL_DISCOVERY_CACHE_MAX_SIZE"],"mappings":";;;;;AAiBA;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BG;MACU,kBAAkB,CAAA;;AAErB,IAAA,gBAAgB,GAAgB,IAAI,GAAG,EAAE;;IAEzC,iBAAiB,GAAW,EAAE;AAEtC;;;;;;AAMG;AACH,IAAA,iBAAiB,CAAC,QAAuB,EAA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,QAAQ,CAAC,MAAM,GAAG,CAAC;AAC5C,QAAA,OAAO,cAAc;IACvB;AAEA;;AAEG;IACH,qBAAqB,GAAA;AACnB,QAAA,OAAO,CAAC,GAAG,IAAI,CAAC,gBAAgB,CAAC;IACnC;AAEA;;AAEG;AACH,IAAA,GAAG,CAAC,QAAgB,EAAA;QAClB,OAAO,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,QAAQ,CAAC;IAC5C;AAEA;;AAEG;AACH,IAAA,IAAI,IAAI,GAAA;AACN,QAAA,OAAO,IAAI,CAAC,gBAAgB,CAAC,IAAI;IACnC;AAEA;;AAEG;IACH,KAAK,GAAA;AACH,QAAA,IAAI,CAAC,gBAAgB,CAAC,KAAK,EAAE;AAC7B,QAAA,IAAI,CAAC,iBAAiB,GAAG,EAAE;IAC7B;AAEA;;;;;;AAMG;AACH,IAAA,IAAI,CAAC,SAAmB,EAAA;AACtB,QAAA,KAAK,MAAM,IAAI,IAAI,SAAS,EAAE;YAC5B,IAAI,IAAI,CAAC,gBAAgB,CAAC,IAAI,IAAIA,uCAA6B,EAAE;gBAC/D;YACF;AACA,YAAA,IAAI,CAAC,gBAAgB,CAAC,GAAG,CAAC,IAAI,CAAC;QACjC;IACF;AACD;;;;"}
@@ -14,7 +14,7 @@ class AgentContext {
14
14
  * Create an AgentContext from configuration with token accounting initialization
15
15
  */
16
16
  static fromConfig(agentConfig, tokenCounter, indexTokenCountMap) {
17
- const { agentId, name, description, provider, clientOptions, tools, toolMap, toolEnd, toolRegistry, toolDefinitions, instructions, additional_instructions, streamBuffer, maxContextTokens, reasoningKey, useLegacyContent, dynamicContext, structuredOutput: structuredOutputCamel, structured_output: structuredOutputSnake, discoveredTools, summarizeCallback, persistedSummary, } = agentConfig;
17
+ const { agentId, name, description, provider, clientOptions, tools, toolMap, toolEnd, toolRegistry, toolDefinitions, instructions, additional_instructions, streamBuffer, maxContextTokens, reasoningKey, useLegacyContent, dynamicContext, structuredOutput: structuredOutputCamel, structured_output: structuredOutputSnake, discoveredTools, summarizeCallback, persistedSummary, summarizationConfig, } = agentConfig;
18
18
  // Normalize structured output: support both camelCase and snake_case inputs
19
19
  // Priority: structuredOutput (camelCase) > structured_output (snake_case with enabled check)
20
20
  let structuredOutput;
@@ -56,6 +56,7 @@ class AgentContext {
56
56
  discoveredTools,
57
57
  summarizeCallback,
58
58
  persistedSummary,
59
+ summarizationConfig,
59
60
  });
60
61
  if (tokenCounter) {
61
62
  // Initialize system runnable BEFORE async tool token calculation
@@ -187,7 +188,9 @@ class AgentContext {
187
188
  summarizeCallback;
188
189
  /** Pre-existing summary loaded from persistent storage, injected into context on new turns */
189
190
  persistedSummary;
190
- constructor({ agentId, name, description, provider, clientOptions, maxContextTokens, streamBuffer, tokenCounter, tools, toolMap, toolRegistry, toolDefinitions, instructions, additionalInstructions, dynamicContext, reasoningKey, toolEnd, instructionTokens, useLegacyContent, structuredOutput, discoveredTools, summarizeCallback, persistedSummary, }) {
191
+ /** Summarization configuration controlling trigger strategy, reserve ratio, and EMA calibration */
192
+ summarizationConfig;
193
+ constructor({ agentId, name, description, provider, clientOptions, maxContextTokens, streamBuffer, tokenCounter, tools, toolMap, toolRegistry, toolDefinitions, instructions, additionalInstructions, dynamicContext, reasoningKey, toolEnd, instructionTokens, useLegacyContent, structuredOutput, discoveredTools, summarizeCallback, persistedSummary, summarizationConfig, }) {
191
194
  this.agentId = agentId;
192
195
  this.name = name;
193
196
  this.description = description;
@@ -206,6 +209,7 @@ class AgentContext {
206
209
  this.structuredOutput = structuredOutput;
207
210
  this.summarizeCallback = summarizeCallback;
208
211
  this.persistedSummary = persistedSummary;
212
+ this.summarizationConfig = summarizationConfig;
209
213
  if (reasoningKey) {
210
214
  this.reasoningKey = reasoningKey;
211
215
  }
@@ -1 +1 @@
1
- {"version":3,"file":"AgentContext.mjs","sources":["../../../src/agents/AgentContext.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/agents/AgentContext.ts\nimport { 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 * as t from '@/types';\nimport type { createPruneMessages } from '@/messages';\nimport { createSchemaOnlyTools } from '@/tools/schema';\nimport { ContentTypes, Providers } from '@/common';\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 description,\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 dynamicContext,\n structuredOutput: structuredOutputCamel,\n\n structured_output: structuredOutputSnake,\n discoveredTools,\n summarizeCallback,\n persistedSummary,\n } = agentConfig;\n\n // Normalize structured output: support both camelCase and snake_case inputs\n // Priority: structuredOutput (camelCase) > structured_output (snake_case with enabled check)\n let structuredOutput: t.StructuredOutputConfig | undefined;\n if (structuredOutputCamel) {\n structuredOutput = structuredOutputCamel;\n } else if (\n structuredOutputSnake?.enabled === true &&\n structuredOutputSnake.schema != null\n ) {\n // Convert snake_case input to StructuredOutputConfig\n structuredOutput = {\n schema: structuredOutputSnake.schema,\n name: structuredOutputSnake.name,\n description: structuredOutputSnake.description,\n mode: structuredOutputSnake.mode,\n strict: structuredOutputSnake.strict,\n };\n }\n\n const agentContext = new AgentContext({\n agentId,\n name: name ?? agentId,\n description,\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 dynamicContext,\n structuredOutput,\n discoveredTools,\n summarizeCallback,\n persistedSummary,\n });\n\n if (tokenCounter) {\n // Initialize system runnable BEFORE async tool token calculation\n // This ensures system message tokens are in instructionTokens before\n // updateTokenMapWithInstructions is called\n agentContext.initializeSystemRunnable();\n\n const tokenMap = indexTokenCountMap || {};\n agentContext.baseIndexTokenCountMap = { ...tokenMap };\n agentContext.indexTokenCountMap = tokenMap;\n agentContext.tokenCalculationPromise = agentContext\n .calculateInstructionTokens(tokenCounter)\n .then(() => {\n // Update token map with instruction tokens (includes system + tool tokens)\n agentContext.updateTokenMapWithInstructions(tokenMap);\n })\n .catch((err) => {\n console.error('Error calculating instruction tokens:', err);\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 /** Description of what this agent does (used to enrich handoff tool descriptions). */\n description?: 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 /** Prune messages function configured for this agent */\n pruneMessages?: ReturnType<typeof createPruneMessages>;\n /** Token counter function for this agent */\n tokenCounter?: t.TokenCounter;\n /** Instructions/system message token count */\n instructionTokens: number = 0;\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 /**\n * Dynamic context that changes per-request (e.g., current time, user info).\n * This is NOT included in the system message to preserve cache.\n * Instead, it's injected as a user message at the start of the conversation.\n */\n dynamicContext?: 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 /** Cached system message token count (separate from tool tokens) */\n private systemMessageTokens: number = 0;\n /** Promise for token calculation initialization */\n tokenCalculationPromise?: Promise<void>;\n /** Format content blocks as strings (for legacy compatibility) */\n useLegacyContent: boolean = false;\n /** Detailed per-tool token breakdown for admin tracking */\n private toolsDetail: Array<{ name: string; tokens: number }> = [];\n /** Total tool tokens (sum of all toolsDetail) */\n private toolTokensTotal: number = 0;\n /** Per-prompt token breakdown for detailed admin reporting */\n private promptBreakdown: {\n branding: number;\n toolRouting: number;\n agentInstructions: number;\n mcpInstructions: number;\n artifacts: number;\n memory: number;\n } = {\n branding: 0,\n toolRouting: 0,\n agentInstructions: 0,\n mcpInstructions: 0,\n artifacts: 0,\n memory: 0,\n };\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 * Structured output configuration.\n * When set, the agent will return a validated JSON response\n * instead of streaming text.\n */\n structuredOutput?: t.StructuredOutputConfig;\n /** Optional callback to summarize discarded messages during context pruning */\n summarizeCallback?: (messages: BaseMessage[]) => Promise<string | undefined>;\n /** Pre-existing summary loaded from persistent storage, injected into context on new turns */\n persistedSummary?: string;\n\n constructor({\n agentId,\n name,\n description,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tokenCounter,\n tools,\n toolMap,\n toolRegistry,\n toolDefinitions,\n instructions,\n additionalInstructions,\n dynamicContext,\n reasoningKey,\n toolEnd,\n instructionTokens,\n useLegacyContent,\n structuredOutput,\n discoveredTools,\n summarizeCallback,\n persistedSummary,\n }: {\n agentId: string;\n name?: string;\n description?: 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 dynamicContext?: string;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n toolEnd?: boolean;\n instructionTokens?: number;\n useLegacyContent?: boolean;\n structuredOutput?: t.StructuredOutputConfig;\n discoveredTools?: string[];\n summarizeCallback?: (\n messages: BaseMessage[]\n ) => Promise<string | undefined>;\n persistedSummary?: string;\n }) {\n this.agentId = agentId;\n this.name = name;\n this.description = description;\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 this.dynamicContext = dynamicContext;\n this.structuredOutput = structuredOutput;\n this.summarizeCallback = summarizeCallback;\n this.persistedSummary = persistedSummary;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (toolEnd !== undefined) {\n this.toolEnd = toolEnd;\n }\n if (instructionTokens !== undefined) {\n this.instructionTokens = instructionTokens;\n }\n\n this.useLegacyContent = useLegacyContent ?? false;\n\n if (discoveredTools && discoveredTools.length > 0) {\n for (const toolName of discoveredTools) {\n this.discoveredToolNames.add(toolName);\n }\n }\n }\n\n /**\n * Checks if structured output mode is enabled for this agent.\n * When enabled, the agent will use model.invoke() instead of streaming\n * and return a validated JSON response.\n */\n get isStructuredOutputMode(): boolean {\n // Runtime safety: schema can be null/undefined via API despite type saying required\n return (\n this.structuredOutput != null &&\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n this.structuredOutput.schema != null\n );\n }\n\n /**\n * Gets the structured output schema with normalized defaults.\n * Returns undefined if structured output is not configured.\n */\n getStructuredOutputSchema(): Record<string, unknown> | undefined {\n if (!this.structuredOutput?.schema) {\n return undefined;\n }\n\n const schema = { ...this.structuredOutput.schema };\n\n // Ensure type is set\n if (schema.type == null && schema.properties != null) {\n schema.type = 'object';\n }\n\n // Add title from config name\n if (\n this.structuredOutput.name != null &&\n this.structuredOutput.name !== '' &&\n schema.title == null\n ) {\n schema.title = this.structuredOutput.name;\n }\n\n // Add description from config\n if (\n this.structuredOutput.description != null &&\n this.structuredOutput.description !== '' &&\n schema.description == null\n ) {\n schema.description = this.structuredOutput.description;\n }\n\n // Enable strict mode by default\n if (this.structuredOutput.strict !== false && schema.type === 'object') {\n schema.additionalProperties = schema.additionalProperties ?? false;\n }\n\n return schema;\n }\n\n /**\n * Resolves the structured output mode to a concrete method based on provider capabilities.\n *\n * Resolution logic:\n * - 'native' or 'auto' + supported provider → native constrained decoding\n * - 'native' + unsupported provider → fallback to 'functionCalling' with warning\n * - 'provider' → LangChain's jsonMode (existing behavior)\n * - 'tool' → function calling trick (existing behavior)\n * - 'auto' + unsupported provider → 'functionCalling'\n *\n * @returns The resolved method for withStructuredOutput, or 'native' for direct API usage\n */\n resolveStructuredOutputMode(): {\n method: t.ResolvedStructuredOutputMethod;\n warnings: string[];\n } {\n const mode = this.structuredOutput?.mode ?? 'auto';\n const warnings: string[] = [];\n\n // Providers that support native constrained decoding via LangChain\n const nativeProviders = new Set([\n Providers.ANTHROPIC,\n Providers.OPENAI,\n Providers.AZURE,\n ]);\n\n // Providers where LangChain supports jsonMode\n const jsonModeProviders = new Set([\n Providers.ANTHROPIC,\n Providers.OPENAI,\n Providers.AZURE,\n ]);\n\n switch (mode) {\n case 'native': {\n if (nativeProviders.has(this.provider)) {\n if (this.provider === Providers.ANTHROPIC) {\n return { method: 'jsonSchema', warnings };\n }\n // OpenAI/Azure\n return { method: 'jsonSchema', warnings };\n }\n // Fallback for unsupported providers\n warnings.push(\n `Native structured output is not supported for provider '${this.provider}'. Falling back to function calling.`\n );\n return { method: 'functionCalling', warnings };\n }\n\n case 'auto': {\n if (nativeProviders.has(this.provider)) {\n if (this.provider === Providers.ANTHROPIC) {\n return { method: 'jsonSchema', warnings };\n }\n // OpenAI/Azure\n return { method: 'jsonSchema', warnings };\n }\n // Default to function calling for all other providers\n return { method: undefined, warnings };\n }\n\n case 'provider': {\n if (this.provider === Providers.BEDROCK) {\n // Bedrock doesn't support jsonMode, fall back to functionCalling\n return { method: 'functionCalling', warnings };\n }\n if (jsonModeProviders.has(this.provider)) {\n return { method: 'jsonMode', warnings };\n }\n return { method: 'jsonMode', warnings };\n }\n\n case 'tool': {\n return { method: 'functionCalling', warnings };\n }\n\n default: {\n return { method: undefined, warnings };\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 // Include if: not deferred OR deferred but discovered\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 // Return cached if not stale\n if (!this.systemRunnableStale && this.cachedSystemRunnable !== undefined) {\n return this.cachedSystemRunnable;\n }\n\n // Stale or first access - rebuild\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 /** Build agent identity and handoff context preamble */\n const identityPreamble = this.buildIdentityPreamble();\n if (identityPreamble) {\n parts.push(identityPreamble);\n }\n\n /** Add main instructions */\n if (this.instructions != null && this.instructions !== '') {\n parts.push(this.instructions);\n }\n\n /** Add additional instructions */\n if (\n this.additionalInstructions != null &&\n this.additionalInstructions !== ''\n ) {\n parts.push(this.additionalInstructions);\n }\n\n /** Add programmatic tools documentation */\n const programmaticToolsDoc = this.buildProgrammaticOnlyToolsInstructions();\n if (programmaticToolsDoc) {\n parts.push(programmaticToolsDoc);\n }\n\n return parts.join('\\n\\n');\n }\n\n /**\n * Builds the 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 if (!instructionsString) {\n // Remove previous tokens if we had a system message before\n this.instructionTokens -= this.systemMessageTokens;\n this.systemMessageTokens = 0;\n return undefined;\n }\n\n let finalInstructions: string | BaseMessageFields = instructionsString;\n\n // Handle Anthropic prompt caching (Direct API)\n if (this.provider === Providers.ANTHROPIC) {\n const anthropicOptions = this.clientOptions as\n | t.AnthropicClientOptions\n | undefined;\n if (anthropicOptions?.promptCache === 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 = new SystemMessage(finalInstructions);\n\n // Update token counts (subtract old, add new)\n if (this.tokenCounter) {\n this.instructionTokens -= this.systemMessageTokens;\n this.systemMessageTokens = this.tokenCounter(systemMessage);\n this.instructionTokens += this.systemMessageTokens;\n }\n\n return RunnableLambda.from((messages: BaseMessage[]) => {\n return [systemMessage, ...messages];\n }).withConfig({ runName: 'prompt' });\n }\n\n /**\n * Reset context for a new run\n */\n reset(): void {\n this.instructionTokens = 0;\n this.systemMessageTokens = 0;\n this.toolsDetail = [];\n this.toolTokensTotal = 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 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 with instruction tokens\n */\n updateTokenMapWithInstructions(baseTokenMap: Record<string, number>): void {\n if (this.instructionTokens > 0) {\n // Shift all indices by the instruction token count\n const shiftedMap: Record<string, number> = {};\n for (const [key, value] of Object.entries(baseTokenMap)) {\n const index = parseInt(key, 10);\n if (!isNaN(index)) {\n shiftedMap[String(index)] =\n value + (index === 0 ? this.instructionTokens : 0);\n }\n }\n this.indexTokenCountMap = shiftedMap;\n } else {\n this.indexTokenCountMap = { ...baseTokenMap };\n }\n }\n\n /**\n * Calculate tool tokens and add to instruction tokens\n * Note: System message tokens are calculated during systemRunnable creation\n * Also tracks per-tool token breakdown for admin reporting\n */\n async calculateInstructionTokens(\n tokenCounter: t.TokenCounter\n ): Promise<void> {\n let toolTokens = 0;\n // Track names to avoid double-counting when a tool appears in both\n // this.tools (bound StructuredTool instances) and this.toolDefinitions\n // (MCP / event-driven schemas).\n const countedToolNames = new Set<string>();\n\n // Reset per-tool breakdown\n this.toolsDetail = [];\n\n // Count tokens for bound tools (StructuredTool instances with .schema)\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 const tokens = tokenCounter(\n new SystemMessage(JSON.stringify(jsonSchema))\n );\n if (toolName) {\n countedToolNames.add(toolName);\n }\n\n // Track per-tool breakdown\n this.toolsDetail.push({ name: toolName || 'unknown', tokens });\n toolTokens += tokens;\n }\n }\n }\n\n // Count tokens for tool definitions (MCP / event-driven tools).\n // These are sent to the provider API as tool schemas alongside bound tools.\n // Both can be populated simultaneously (graph tools + MCP tools).\n if (this.toolDefinitions && this.toolDefinitions.length > 0) {\n for (const def of this.toolDefinitions) {\n if (countedToolNames.has(def.name)) {\n continue; // Already counted via this.tools\n }\n const schema = {\n name: def.name,\n description: def.description ?? '',\n parameters: def.parameters ?? {},\n };\n const defTokens = tokenCounter(\n new SystemMessage(JSON.stringify(schema))\n );\n this.toolsDetail.push({\n name: def.name || 'unknown',\n tokens: defTokens,\n });\n toolTokens += defTokens;\n }\n }\n\n // Store total tool tokens for breakdown reporting\n this.toolTokensTotal = toolTokens;\n\n // Add tool tokens to existing instruction tokens (which may already include system message tokens)\n this.instructionTokens += toolTokens;\n }\n\n /**\n * Set the per-prompt token breakdown for detailed admin tracking.\n * Called by the client after assembling all prompt components.\n * @param breakdown - Object with token counts per prompt component\n */\n setPromptBreakdown(breakdown: {\n branding?: number;\n toolRouting?: number;\n agentInstructions?: number;\n mcpInstructions?: number;\n artifacts?: number;\n memory?: number;\n }): void {\n if (breakdown.branding !== undefined)\n this.promptBreakdown.branding = breakdown.branding;\n if (breakdown.toolRouting !== undefined)\n this.promptBreakdown.toolRouting = breakdown.toolRouting;\n if (breakdown.agentInstructions !== undefined)\n this.promptBreakdown.agentInstructions = breakdown.agentInstructions;\n if (breakdown.mcpInstructions !== undefined)\n this.promptBreakdown.mcpInstructions = breakdown.mcpInstructions;\n if (breakdown.artifacts !== undefined)\n this.promptBreakdown.artifacts = breakdown.artifacts;\n if (breakdown.memory !== undefined)\n this.promptBreakdown.memory = breakdown.memory;\n }\n\n /**\n * Get a detailed breakdown of context tokens for admin reporting.\n * This provides visibility into what's consuming the input token budget.\n * @returns ContextBreakdown object with per-component token counts\n */\n getContextBreakdown(): {\n instructions: number;\n artifacts: number;\n tools: number;\n toolCount: number;\n toolContext: number;\n total: number;\n toolsDetail: Array<{ name: string; tokens: number }>;\n toolContextDetail: Array<{ name: string; tokens: number }>;\n prompts?: {\n branding: number;\n toolRouting: number;\n agentInstructions: number;\n mcpInstructions: number;\n artifacts: number;\n memory: number;\n };\n } {\n // Calculate sum of prompt components\n const promptsTotal =\n this.promptBreakdown.branding +\n this.promptBreakdown.toolRouting +\n this.promptBreakdown.agentInstructions +\n this.promptBreakdown.mcpInstructions +\n this.promptBreakdown.artifacts +\n this.promptBreakdown.memory;\n\n return {\n // System message tokens (instructions + additional_instructions)\n instructions: this.systemMessageTokens,\n // Artifacts prompt tokens\n artifacts: this.promptBreakdown.artifacts,\n // Total tool definition tokens\n tools: this.toolTokensTotal,\n // Number of tools\n toolCount: this.toolsDetail.length,\n // Tool context/usage instructions (currently embedded in system message)\n toolContext: 0,\n // Total tracked context tokens\n total: this.instructionTokens,\n // Per-tool token breakdown\n toolsDetail: [...this.toolsDetail],\n // Tool context detail (currently not tracked separately)\n toolContextDetail: [],\n // Per-prompt breakdown (only include if any prompts were tracked)\n prompts: promptsTotal > 0 ? { ...this.promptBreakdown } : undefined,\n };\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 /**\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 /** Event-driven mode: create schema-only tools from definitions */\n if (this.toolDefinitions && this.toolDefinitions.length > 0) {\n return this.getEventDrivenToolsForBinding();\n }\n\n /** Traditional mode: filter actual tool instances */\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;AACA;AAeA;;AAEG;MACU,YAAY,CAAA;AACvB;;AAEG;AACH,IAAA,OAAO,UAAU,CACf,WAA0B,EAC1B,YAA6B,EAC7B,kBAA2C,EAAA;QAE3C,MAAM,EACJ,OAAO,EACP,IAAI,EACJ,WAAW,EACX,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,cAAc,EACd,gBAAgB,EAAE,qBAAqB,EAEvC,iBAAiB,EAAE,qBAAqB,EACxC,eAAe,EACf,iBAAiB,EACjB,gBAAgB,GACjB,GAAG,WAAW;;;AAIf,QAAA,IAAI,gBAAsD;QAC1D,IAAI,qBAAqB,EAAE;YACzB,gBAAgB,GAAG,qBAAqB;QAC1C;AAAO,aAAA,IACL,qBAAqB,EAAE,OAAO,KAAK,IAAI;AACvC,YAAA,qBAAqB,CAAC,MAAM,IAAI,IAAI,EACpC;;AAEA,YAAA,gBAAgB,GAAG;gBACjB,MAAM,EAAE,qBAAqB,CAAC,MAAM;gBACpC,IAAI,EAAE,qBAAqB,CAAC,IAAI;gBAChC,WAAW,EAAE,qBAAqB,CAAC,WAAW;gBAC9C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CAAC,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.mjs","sources":["../../../src/agents/AgentContext.ts"],"sourcesContent":["/* eslint-disable no-console */\n// src/agents/AgentContext.ts\nimport { 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 * as t from '@/types';\nimport type { createPruneMessages } from '@/messages';\nimport { createSchemaOnlyTools } from '@/tools/schema';\nimport { ContentTypes, Providers } from '@/common';\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 description,\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 dynamicContext,\n structuredOutput: structuredOutputCamel,\n\n structured_output: structuredOutputSnake,\n discoveredTools,\n summarizeCallback,\n persistedSummary,\n summarizationConfig,\n } = agentConfig;\n\n // Normalize structured output: support both camelCase and snake_case inputs\n // Priority: structuredOutput (camelCase) > structured_output (snake_case with enabled check)\n let structuredOutput: t.StructuredOutputConfig | undefined;\n if (structuredOutputCamel) {\n structuredOutput = structuredOutputCamel;\n } else if (\n structuredOutputSnake?.enabled === true &&\n structuredOutputSnake.schema != null\n ) {\n // Convert snake_case input to StructuredOutputConfig\n structuredOutput = {\n schema: structuredOutputSnake.schema,\n name: structuredOutputSnake.name,\n description: structuredOutputSnake.description,\n mode: structuredOutputSnake.mode,\n strict: structuredOutputSnake.strict,\n };\n }\n\n const agentContext = new AgentContext({\n agentId,\n name: name ?? agentId,\n description,\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 dynamicContext,\n structuredOutput,\n discoveredTools,\n summarizeCallback,\n persistedSummary,\n summarizationConfig,\n });\n\n if (tokenCounter) {\n // Initialize system runnable BEFORE async tool token calculation\n // This ensures system message tokens are in instructionTokens before\n // updateTokenMapWithInstructions is called\n agentContext.initializeSystemRunnable();\n\n const tokenMap = indexTokenCountMap || {};\n agentContext.baseIndexTokenCountMap = { ...tokenMap };\n agentContext.indexTokenCountMap = tokenMap;\n agentContext.tokenCalculationPromise = agentContext\n .calculateInstructionTokens(tokenCounter)\n .then(() => {\n // Update token map with instruction tokens (includes system + tool tokens)\n agentContext.updateTokenMapWithInstructions(tokenMap);\n })\n .catch((err) => {\n console.error('Error calculating instruction tokens:', err);\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 /** Description of what this agent does (used to enrich handoff tool descriptions). */\n description?: 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 /** Prune messages function configured for this agent */\n pruneMessages?: ReturnType<typeof createPruneMessages>;\n /** Token counter function for this agent */\n tokenCounter?: t.TokenCounter;\n /** Instructions/system message token count */\n instructionTokens: number = 0;\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 /**\n * Dynamic context that changes per-request (e.g., current time, user info).\n * This is NOT included in the system message to preserve cache.\n * Instead, it's injected as a user message at the start of the conversation.\n */\n dynamicContext?: 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 /** Cached system message token count (separate from tool tokens) */\n private systemMessageTokens: number = 0;\n /** Promise for token calculation initialization */\n tokenCalculationPromise?: Promise<void>;\n /** Format content blocks as strings (for legacy compatibility) */\n useLegacyContent: boolean = false;\n /** Detailed per-tool token breakdown for admin tracking */\n private toolsDetail: Array<{ name: string; tokens: number }> = [];\n /** Total tool tokens (sum of all toolsDetail) */\n private toolTokensTotal: number = 0;\n /** Per-prompt token breakdown for detailed admin reporting */\n private promptBreakdown: {\n branding: number;\n toolRouting: number;\n agentInstructions: number;\n mcpInstructions: number;\n artifacts: number;\n memory: number;\n } = {\n branding: 0,\n toolRouting: 0,\n agentInstructions: 0,\n mcpInstructions: 0,\n artifacts: 0,\n memory: 0,\n };\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 * Structured output configuration.\n * When set, the agent will return a validated JSON response\n * instead of streaming text.\n */\n structuredOutput?: t.StructuredOutputConfig;\n /** Optional callback to summarize discarded messages during context pruning */\n summarizeCallback?: (messages: BaseMessage[]) => Promise<string | undefined>;\n /** Pre-existing summary loaded from persistent storage, injected into context on new turns */\n persistedSummary?: string;\n /** Summarization configuration controlling trigger strategy, reserve ratio, and EMA calibration */\n summarizationConfig?: t.SummarizationConfig;\n\n constructor({\n agentId,\n name,\n description,\n provider,\n clientOptions,\n maxContextTokens,\n streamBuffer,\n tokenCounter,\n tools,\n toolMap,\n toolRegistry,\n toolDefinitions,\n instructions,\n additionalInstructions,\n dynamicContext,\n reasoningKey,\n toolEnd,\n instructionTokens,\n useLegacyContent,\n structuredOutput,\n discoveredTools,\n summarizeCallback,\n persistedSummary,\n summarizationConfig,\n }: {\n agentId: string;\n name?: string;\n description?: 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 dynamicContext?: string;\n reasoningKey?: 'reasoning_content' | 'reasoning';\n toolEnd?: boolean;\n instructionTokens?: number;\n useLegacyContent?: boolean;\n structuredOutput?: t.StructuredOutputConfig;\n discoveredTools?: string[];\n summarizeCallback?: (\n messages: BaseMessage[]\n ) => Promise<string | undefined>;\n persistedSummary?: string;\n summarizationConfig?: t.SummarizationConfig;\n }) {\n this.agentId = agentId;\n this.name = name;\n this.description = description;\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 this.dynamicContext = dynamicContext;\n this.structuredOutput = structuredOutput;\n this.summarizeCallback = summarizeCallback;\n this.persistedSummary = persistedSummary;\n this.summarizationConfig = summarizationConfig;\n if (reasoningKey) {\n this.reasoningKey = reasoningKey;\n }\n if (toolEnd !== undefined) {\n this.toolEnd = toolEnd;\n }\n if (instructionTokens !== undefined) {\n this.instructionTokens = instructionTokens;\n }\n\n this.useLegacyContent = useLegacyContent ?? false;\n\n if (discoveredTools && discoveredTools.length > 0) {\n for (const toolName of discoveredTools) {\n this.discoveredToolNames.add(toolName);\n }\n }\n }\n\n /**\n * Checks if structured output mode is enabled for this agent.\n * When enabled, the agent will use model.invoke() instead of streaming\n * and return a validated JSON response.\n */\n get isStructuredOutputMode(): boolean {\n // Runtime safety: schema can be null/undefined via API despite type saying required\n return (\n this.structuredOutput != null &&\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n this.structuredOutput.schema != null\n );\n }\n\n /**\n * Gets the structured output schema with normalized defaults.\n * Returns undefined if structured output is not configured.\n */\n getStructuredOutputSchema(): Record<string, unknown> | undefined {\n if (!this.structuredOutput?.schema) {\n return undefined;\n }\n\n const schema = { ...this.structuredOutput.schema };\n\n // Ensure type is set\n if (schema.type == null && schema.properties != null) {\n schema.type = 'object';\n }\n\n // Add title from config name\n if (\n this.structuredOutput.name != null &&\n this.structuredOutput.name !== '' &&\n schema.title == null\n ) {\n schema.title = this.structuredOutput.name;\n }\n\n // Add description from config\n if (\n this.structuredOutput.description != null &&\n this.structuredOutput.description !== '' &&\n schema.description == null\n ) {\n schema.description = this.structuredOutput.description;\n }\n\n // Enable strict mode by default\n if (this.structuredOutput.strict !== false && schema.type === 'object') {\n schema.additionalProperties = schema.additionalProperties ?? false;\n }\n\n return schema;\n }\n\n /**\n * Resolves the structured output mode to a concrete method based on provider capabilities.\n *\n * Resolution logic:\n * - 'native' or 'auto' + supported provider → native constrained decoding\n * - 'native' + unsupported provider → fallback to 'functionCalling' with warning\n * - 'provider' → LangChain's jsonMode (existing behavior)\n * - 'tool' → function calling trick (existing behavior)\n * - 'auto' + unsupported provider → 'functionCalling'\n *\n * @returns The resolved method for withStructuredOutput, or 'native' for direct API usage\n */\n resolveStructuredOutputMode(): {\n method: t.ResolvedStructuredOutputMethod;\n warnings: string[];\n } {\n const mode = this.structuredOutput?.mode ?? 'auto';\n const warnings: string[] = [];\n\n // Providers that support native constrained decoding via LangChain\n const nativeProviders = new Set([\n Providers.ANTHROPIC,\n Providers.OPENAI,\n Providers.AZURE,\n ]);\n\n // Providers where LangChain supports jsonMode\n const jsonModeProviders = new Set([\n Providers.ANTHROPIC,\n Providers.OPENAI,\n Providers.AZURE,\n ]);\n\n switch (mode) {\n case 'native': {\n if (nativeProviders.has(this.provider)) {\n if (this.provider === Providers.ANTHROPIC) {\n return { method: 'jsonSchema', warnings };\n }\n // OpenAI/Azure\n return { method: 'jsonSchema', warnings };\n }\n // Fallback for unsupported providers\n warnings.push(\n `Native structured output is not supported for provider '${this.provider}'. Falling back to function calling.`\n );\n return { method: 'functionCalling', warnings };\n }\n\n case 'auto': {\n if (nativeProviders.has(this.provider)) {\n if (this.provider === Providers.ANTHROPIC) {\n return { method: 'jsonSchema', warnings };\n }\n // OpenAI/Azure\n return { method: 'jsonSchema', warnings };\n }\n // Default to function calling for all other providers\n return { method: undefined, warnings };\n }\n\n case 'provider': {\n if (this.provider === Providers.BEDROCK) {\n // Bedrock doesn't support jsonMode, fall back to functionCalling\n return { method: 'functionCalling', warnings };\n }\n if (jsonModeProviders.has(this.provider)) {\n return { method: 'jsonMode', warnings };\n }\n return { method: 'jsonMode', warnings };\n }\n\n case 'tool': {\n return { method: 'functionCalling', warnings };\n }\n\n default: {\n return { method: undefined, warnings };\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 // Include if: not deferred OR deferred but discovered\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 // Return cached if not stale\n if (!this.systemRunnableStale && this.cachedSystemRunnable !== undefined) {\n return this.cachedSystemRunnable;\n }\n\n // Stale or first access - rebuild\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 /** Build agent identity and handoff context preamble */\n const identityPreamble = this.buildIdentityPreamble();\n if (identityPreamble) {\n parts.push(identityPreamble);\n }\n\n /** Add main instructions */\n if (this.instructions != null && this.instructions !== '') {\n parts.push(this.instructions);\n }\n\n /** Add additional instructions */\n if (\n this.additionalInstructions != null &&\n this.additionalInstructions !== ''\n ) {\n parts.push(this.additionalInstructions);\n }\n\n /** Add programmatic tools documentation */\n const programmaticToolsDoc = this.buildProgrammaticOnlyToolsInstructions();\n if (programmaticToolsDoc) {\n parts.push(programmaticToolsDoc);\n }\n\n return parts.join('\\n\\n');\n }\n\n /**\n * Builds the 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 if (!instructionsString) {\n // Remove previous tokens if we had a system message before\n this.instructionTokens -= this.systemMessageTokens;\n this.systemMessageTokens = 0;\n return undefined;\n }\n\n let finalInstructions: string | BaseMessageFields = instructionsString;\n\n // Handle Anthropic prompt caching (Direct API)\n if (this.provider === Providers.ANTHROPIC) {\n const anthropicOptions = this.clientOptions as\n | t.AnthropicClientOptions\n | undefined;\n if (anthropicOptions?.promptCache === 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 = new SystemMessage(finalInstructions);\n\n // Update token counts (subtract old, add new)\n if (this.tokenCounter) {\n this.instructionTokens -= this.systemMessageTokens;\n this.systemMessageTokens = this.tokenCounter(systemMessage);\n this.instructionTokens += this.systemMessageTokens;\n }\n\n return RunnableLambda.from((messages: BaseMessage[]) => {\n return [systemMessage, ...messages];\n }).withConfig({ runName: 'prompt' });\n }\n\n /**\n * Reset context for a new run\n */\n reset(): void {\n this.instructionTokens = 0;\n this.systemMessageTokens = 0;\n this.toolsDetail = [];\n this.toolTokensTotal = 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 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 with instruction tokens\n */\n updateTokenMapWithInstructions(baseTokenMap: Record<string, number>): void {\n if (this.instructionTokens > 0) {\n // Shift all indices by the instruction token count\n const shiftedMap: Record<string, number> = {};\n for (const [key, value] of Object.entries(baseTokenMap)) {\n const index = parseInt(key, 10);\n if (!isNaN(index)) {\n shiftedMap[String(index)] =\n value + (index === 0 ? this.instructionTokens : 0);\n }\n }\n this.indexTokenCountMap = shiftedMap;\n } else {\n this.indexTokenCountMap = { ...baseTokenMap };\n }\n }\n\n /**\n * Calculate tool tokens and add to instruction tokens\n * Note: System message tokens are calculated during systemRunnable creation\n * Also tracks per-tool token breakdown for admin reporting\n */\n async calculateInstructionTokens(\n tokenCounter: t.TokenCounter\n ): Promise<void> {\n let toolTokens = 0;\n // Track names to avoid double-counting when a tool appears in both\n // this.tools (bound StructuredTool instances) and this.toolDefinitions\n // (MCP / event-driven schemas).\n const countedToolNames = new Set<string>();\n\n // Reset per-tool breakdown\n this.toolsDetail = [];\n\n // Count tokens for bound tools (StructuredTool instances with .schema)\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 const tokens = tokenCounter(\n new SystemMessage(JSON.stringify(jsonSchema))\n );\n if (toolName) {\n countedToolNames.add(toolName);\n }\n\n // Track per-tool breakdown\n this.toolsDetail.push({ name: toolName || 'unknown', tokens });\n toolTokens += tokens;\n }\n }\n }\n\n // Count tokens for tool definitions (MCP / event-driven tools).\n // These are sent to the provider API as tool schemas alongside bound tools.\n // Both can be populated simultaneously (graph tools + MCP tools).\n if (this.toolDefinitions && this.toolDefinitions.length > 0) {\n for (const def of this.toolDefinitions) {\n if (countedToolNames.has(def.name)) {\n continue; // Already counted via this.tools\n }\n const schema = {\n name: def.name,\n description: def.description ?? '',\n parameters: def.parameters ?? {},\n };\n const defTokens = tokenCounter(\n new SystemMessage(JSON.stringify(schema))\n );\n this.toolsDetail.push({\n name: def.name || 'unknown',\n tokens: defTokens,\n });\n toolTokens += defTokens;\n }\n }\n\n // Store total tool tokens for breakdown reporting\n this.toolTokensTotal = toolTokens;\n\n // Add tool tokens to existing instruction tokens (which may already include system message tokens)\n this.instructionTokens += toolTokens;\n }\n\n /**\n * Set the per-prompt token breakdown for detailed admin tracking.\n * Called by the client after assembling all prompt components.\n * @param breakdown - Object with token counts per prompt component\n */\n setPromptBreakdown(breakdown: {\n branding?: number;\n toolRouting?: number;\n agentInstructions?: number;\n mcpInstructions?: number;\n artifacts?: number;\n memory?: number;\n }): void {\n if (breakdown.branding !== undefined)\n this.promptBreakdown.branding = breakdown.branding;\n if (breakdown.toolRouting !== undefined)\n this.promptBreakdown.toolRouting = breakdown.toolRouting;\n if (breakdown.agentInstructions !== undefined)\n this.promptBreakdown.agentInstructions = breakdown.agentInstructions;\n if (breakdown.mcpInstructions !== undefined)\n this.promptBreakdown.mcpInstructions = breakdown.mcpInstructions;\n if (breakdown.artifacts !== undefined)\n this.promptBreakdown.artifacts = breakdown.artifacts;\n if (breakdown.memory !== undefined)\n this.promptBreakdown.memory = breakdown.memory;\n }\n\n /**\n * Get a detailed breakdown of context tokens for admin reporting.\n * This provides visibility into what's consuming the input token budget.\n * @returns ContextBreakdown object with per-component token counts\n */\n getContextBreakdown(): {\n instructions: number;\n artifacts: number;\n tools: number;\n toolCount: number;\n toolContext: number;\n total: number;\n toolsDetail: Array<{ name: string; tokens: number }>;\n toolContextDetail: Array<{ name: string; tokens: number }>;\n prompts?: {\n branding: number;\n toolRouting: number;\n agentInstructions: number;\n mcpInstructions: number;\n artifacts: number;\n memory: number;\n };\n } {\n // Calculate sum of prompt components\n const promptsTotal =\n this.promptBreakdown.branding +\n this.promptBreakdown.toolRouting +\n this.promptBreakdown.agentInstructions +\n this.promptBreakdown.mcpInstructions +\n this.promptBreakdown.artifacts +\n this.promptBreakdown.memory;\n\n return {\n // System message tokens (instructions + additional_instructions)\n instructions: this.systemMessageTokens,\n // Artifacts prompt tokens\n artifacts: this.promptBreakdown.artifacts,\n // Total tool definition tokens\n tools: this.toolTokensTotal,\n // Number of tools\n toolCount: this.toolsDetail.length,\n // Tool context/usage instructions (currently embedded in system message)\n toolContext: 0,\n // Total tracked context tokens\n total: this.instructionTokens,\n // Per-tool token breakdown\n toolsDetail: [...this.toolsDetail],\n // Tool context detail (currently not tracked separately)\n toolContextDetail: [],\n // Per-prompt breakdown (only include if any prompts were tracked)\n prompts: promptsTotal > 0 ? { ...this.promptBreakdown } : undefined,\n };\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 /**\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 /** Event-driven mode: create schema-only tools from definitions */\n if (this.toolDefinitions && this.toolDefinitions.length > 0) {\n return this.getEventDrivenToolsForBinding();\n }\n\n /** Traditional mode: filter actual tool instances */\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;AACA;AAeA;;AAEG;MACU,YAAY,CAAA;AACvB;;AAEG;AACH,IAAA,OAAO,UAAU,CACf,WAA0B,EAC1B,YAA6B,EAC7B,kBAA2C,EAAA;QAE3C,MAAM,EACJ,OAAO,EACP,IAAI,EACJ,WAAW,EACX,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,cAAc,EACd,gBAAgB,EAAE,qBAAqB,EAEvC,iBAAiB,EAAE,qBAAqB,EACxC,eAAe,EACf,iBAAiB,EACjB,gBAAgB,EAChB,mBAAmB,GACpB,GAAG,WAAW;;;AAIf,QAAA,IAAI,gBAAsD;QAC1D,IAAI,qBAAqB,EAAE;YACzB,gBAAgB,GAAG,qBAAqB;QAC1C;AAAO,aAAA,IACL,qBAAqB,EAAE,OAAO,KAAK,IAAI;AACvC,YAAA,qBAAqB,CAAC,MAAM,IAAI,IAAI,EACpC;;AAEA,YAAA,gBAAgB,GAAG;gBACjB,MAAM,EAAE,qBAAqB,CAAC,MAAM;gBACpC,IAAI,EAAE,qBAAqB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41
  */
42
42
  const CONTEXT_SAFETY_BUFFER = 0.9;
43
+ // ============================================================================
44
+ // SUMMARIZATION CONFIGURATION DEFAULTS
45
+ //
46
+ // These constants provide sensible defaults for the SummarizationConfig.
47
+ // They can be overridden per-agent via AgentInputs.summarizationConfig.
48
+ // ============================================================================
49
+ /**
50
+ * Default context utilization percentage (0-100) at which summarization triggers.
51
+ * When the context window is ≥80% full, pruning + summarization activates.
52
+ */
53
+ const SUMMARIZATION_CONTEXT_THRESHOLD = 80;
54
+ /**
55
+ * Default reserve ratio (0-1) — fraction of context window to preserve as recent messages.
56
+ * 0.3 means 30% of the context budget is reserved for the most recent messages,
57
+ * ensuring the model always has immediate conversation history even after aggressive pruning.
58
+ */
59
+ const SUMMARIZATION_RESERVE_RATIO = 0.3;
60
+ /**
61
+ * Default EMA (Exponential Moving Average) alpha for pruning calibration.
62
+ * Controls how quickly the calibration adapts to new token counts.
63
+ * Higher α = faster adaptation (more responsive to recent changes).
64
+ * Lower α = smoother adaptation (more stable across iterations).
65
+ * 0.3 provides a balance between responsiveness and stability.
66
+ */
67
+ const PRUNING_EMA_ALPHA = 0.3;
68
+ /**
69
+ * Default initial calibration ratio for EMA pruning.
70
+ * 1.0 means no adjustment on the first iteration (trust the raw token counts).
71
+ * Subsequent iterations will adjust based on actual vs. estimated token usage.
72
+ */
73
+ const PRUNING_INITIAL_CALIBRATION = 1.0;
74
+ // ============================================================================
75
+ // TOOL DISCOVERY CACHING
76
+ // ============================================================================
77
+ /**
78
+ * Maximum number of tool discovery entries to cache per conversation.
79
+ * Prevents unbounded memory growth in very long conversations.
80
+ */
81
+ const TOOL_DISCOVERY_CACHE_MAX_SIZE = 200;
82
+ // ============================================================================
83
+ // MESSAGE DEDUPLICATION
84
+ // ============================================================================
85
+ /**
86
+ * Maximum length of system message content to hash for deduplication.
87
+ * Messages longer than this are always considered unique (hashing would be expensive).
88
+ */
89
+ const DEDUP_MAX_CONTENT_LENGTH = 10000;
43
90
 
44
- export { CONTEXT_SAFETY_BUFFER, MIN_THINKING_BUDGET, MULTI_DOCUMENT_THRESHOLD, TOOL_TURN_THINKING_BUDGET };
91
+ export { CONTEXT_SAFETY_BUFFER, DEDUP_MAX_CONTENT_LENGTH, MIN_THINKING_BUDGET, MULTI_DOCUMENT_THRESHOLD, PRUNING_EMA_ALPHA, PRUNING_INITIAL_CALIBRATION, SUMMARIZATION_CONTEXT_THRESHOLD, SUMMARIZATION_RESERVE_RATIO, TOOL_DISCOVERY_CACHE_MAX_SIZE, TOOL_TURN_THINKING_BUDGET };
45
92
  //# sourceMappingURL=constants.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.mjs","sources":["../../../src/common/constants.ts"],"sourcesContent":["// src/common/constants.ts\n\n/**\n * Minimum thinking budget allowed by the Anthropic API.\n * Extended thinking requires at least 1024 budget_tokens.\n * @see https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking\n */\nexport const MIN_THINKING_BUDGET = 1024;\n\n/**\n * Reduced thinking budget for subsequent ReAct iterations (tool-result turns).\n *\n * In a ReAct agent loop, the first LLM call processes the user's query and\n * may need deep reasoning. Subsequent iterations (after tool results return)\n * typically only need to decide \"call next tool\" or \"generate final response\"\n * — 1024 tokens is sufficient for this routing logic.\n *\n * This reduces wall-clock time per iteration from ~20-30s to ~5-10s,\n * compounding across multi-tool conversations (e.g., 10 tool calls).\n */\nexport const TOOL_TURN_THINKING_BUDGET = 1024;\n\n// ============================================================================\n// CONTEXT OVERFLOW MANAGEMENT\n//\n// Context overflow is handled mechanically — no token budget numbers are\n// exposed to the LLM. The system uses: pruning (Graph), summarization\n// (summarizeCallback), and auto-continuation (client.js max_tokens detection).\n//\n// See: docs/context-overflow-architecture.md\n// ============================================================================\n\n/**\n * Minimum number of attached documents before the multi-document delegation\n * hint is injected. Below this threshold, the agent processes documents\n * directly within its own context.\n */\nexport const MULTI_DOCUMENT_THRESHOLD = 3;\n\n/**\n * Context utilization safety buffer multiplier (0-1).\n * Applied as: effectiveMax = (maxContextTokens - maxOutputTokens) * CONTEXT_SAFETY_BUFFER\n *\n * Reserves headroom so the LLM doesn't hit hard token limits mid-generation.\n * 0.9 = 10% reserved for safety.\n */\nexport const CONTEXT_SAFETY_BUFFER = 0.9;\n"],"names":[],"mappings":"AAAA;AAEA;;;;AAIG;AACI,MAAM,mBAAmB,GAAG;AAEnC;;;;;;;;;;AAUG;AACI,MAAM,yBAAyB,GAAG;AAEzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;;;;AAIG;AACI,MAAM,wBAAwB,GAAG;AAExC;;;;;;AAMG;AACI,MAAM,qBAAqB,GAAG;;;;"}
1
+ {"version":3,"file":"constants.mjs","sources":["../../../src/common/constants.ts"],"sourcesContent":["// src/common/constants.ts\n\n/**\n * Minimum thinking budget allowed by the Anthropic API.\n * Extended thinking requires at least 1024 budget_tokens.\n * @see https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking\n */\nexport const MIN_THINKING_BUDGET = 1024;\n\n/**\n * Reduced thinking budget for subsequent ReAct iterations (tool-result turns).\n *\n * In a ReAct agent loop, the first LLM call processes the user's query and\n * may need deep reasoning. Subsequent iterations (after tool results return)\n * typically only need to decide \"call next tool\" or \"generate final response\"\n * — 1024 tokens is sufficient for this routing logic.\n *\n * This reduces wall-clock time per iteration from ~20-30s to ~5-10s,\n * compounding across multi-tool conversations (e.g., 10 tool calls).\n */\nexport const TOOL_TURN_THINKING_BUDGET = 1024;\n\n// ============================================================================\n// CONTEXT OVERFLOW MANAGEMENT\n//\n// Context overflow is handled mechanically — no token budget numbers are\n// exposed to the LLM. The system uses: pruning (Graph), summarization\n// (summarizeCallback), and auto-continuation (client.js max_tokens detection).\n//\n// See: docs/context-overflow-architecture.md\n// ============================================================================\n\n/**\n * Minimum number of attached documents before the multi-document delegation\n * hint is injected. Below this threshold, the agent processes documents\n * directly within its own context.\n */\nexport const MULTI_DOCUMENT_THRESHOLD = 3;\n\n/**\n * Context utilization safety buffer multiplier (0-1).\n * Applied as: effectiveMax = (maxContextTokens - maxOutputTokens) * CONTEXT_SAFETY_BUFFER\n *\n * Reserves headroom so the LLM doesn't hit hard token limits mid-generation.\n * 0.9 = 10% reserved for safety.\n */\nexport const CONTEXT_SAFETY_BUFFER = 0.9;\n\n// ============================================================================\n// SUMMARIZATION CONFIGURATION DEFAULTS\n//\n// These constants provide sensible defaults for the SummarizationConfig.\n// They can be overridden per-agent via AgentInputs.summarizationConfig.\n// ============================================================================\n\n/**\n * Default context utilization percentage (0-100) at which summarization triggers.\n * When the context window is ≥80% full, pruning + summarization activates.\n */\nexport const SUMMARIZATION_CONTEXT_THRESHOLD = 80;\n\n/**\n * Default reserve ratio (0-1) — fraction of context window to preserve as recent messages.\n * 0.3 means 30% of the context budget is reserved for the most recent messages,\n * ensuring the model always has immediate conversation history even after aggressive pruning.\n */\nexport const SUMMARIZATION_RESERVE_RATIO = 0.3;\n\n/**\n * Default EMA (Exponential Moving Average) alpha for pruning calibration.\n * Controls how quickly the calibration adapts to new token counts.\n * Higher α = faster adaptation (more responsive to recent changes).\n * Lower α = smoother adaptation (more stable across iterations).\n * 0.3 provides a balance between responsiveness and stability.\n */\nexport const PRUNING_EMA_ALPHA = 0.3;\n\n/**\n * Default initial calibration ratio for EMA pruning.\n * 1.0 means no adjustment on the first iteration (trust the raw token counts).\n * Subsequent iterations will adjust based on actual vs. estimated token usage.\n */\nexport const PRUNING_INITIAL_CALIBRATION = 1.0;\n\n// ============================================================================\n// TOOL DISCOVERY CACHING\n// ============================================================================\n\n/**\n * Maximum number of tool discovery entries to cache per conversation.\n * Prevents unbounded memory growth in very long conversations.\n */\nexport const TOOL_DISCOVERY_CACHE_MAX_SIZE = 200;\n\n// ============================================================================\n// MESSAGE DEDUPLICATION\n// ============================================================================\n\n/**\n * Maximum length of system message content to hash for deduplication.\n * Messages longer than this are always considered unique (hashing would be expensive).\n */\nexport const DEDUP_MAX_CONTENT_LENGTH = 10000;\n"],"names":[],"mappings":"AAAA;AAEA;;;;AAIG;AACI,MAAM,mBAAmB,GAAG;AAEnC;;;;;;;;;;AAUG;AACI,MAAM,yBAAyB,GAAG;AAEzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;;;;AAIG;AACI,MAAM,wBAAwB,GAAG;AAExC;;;;;;AAMG;AACI,MAAM,qBAAqB,GAAG;AAErC;AACA;AACA;AACA;AACA;AACA;AAEA;;;AAGG;AACI,MAAM,+BAA+B,GAAG;AAE/C;;;;AAIG;AACI,MAAM,2BAA2B,GAAG;AAE3C;;;;;;AAMG;AACI,MAAM,iBAAiB,GAAG;AAEjC;;;;AAIG;AACI,MAAM,2BAA2B,GAAG;AAE3C;AACA;AACA;AAEA;;;AAGG;AACI,MAAM,6BAA6B,GAAG;AAE7C;AACA;AACA;AAEA;;;AAGG;AACI,MAAM,wBAAwB,GAAG;;;;"}