@illuma-ai/agents 1.1.21 → 1.1.22

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 (241) hide show
  1. package/dist/cjs/graphs/Graph.cjs +12 -1
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/graphs/MultiAgentGraph.cjs +85 -1
  4. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  5. package/dist/cjs/run.cjs +20 -9
  6. package/dist/cjs/run.cjs.map +1 -1
  7. package/dist/esm/graphs/Graph.mjs +12 -1
  8. package/dist/esm/graphs/Graph.mjs.map +1 -1
  9. package/dist/esm/graphs/MultiAgentGraph.mjs +85 -1
  10. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  11. package/dist/esm/run.mjs +20 -9
  12. package/dist/esm/run.mjs.map +1 -1
  13. package/dist/types/graphs/MultiAgentGraph.d.ts +17 -0
  14. package/package.json +1 -1
  15. package/src/graphs/Graph.ts +12 -1
  16. package/src/graphs/MultiAgentGraph.ts +105 -1
  17. package/src/graphs/__tests__/multi-agent-delegate.test.ts +191 -0
  18. package/src/run.ts +20 -11
  19. package/src/scripts/test-bedrock-handoff-autonomous.ts +231 -0
  20. package/src/agents/AgentContext.js +0 -782
  21. package/src/agents/AgentContext.test.js +0 -421
  22. package/src/agents/__tests__/AgentContext.test.js +0 -678
  23. package/src/agents/__tests__/resolveStructuredOutputMode.test.js +0 -117
  24. package/src/common/enum.js +0 -192
  25. package/src/common/index.js +0 -3
  26. package/src/events.js +0 -166
  27. package/src/graphs/Graph.js +0 -1857
  28. package/src/graphs/MultiAgentGraph.js +0 -1092
  29. package/src/graphs/__tests__/structured-output.integration.test.js +0 -624
  30. package/src/graphs/__tests__/structured-output.test.js +0 -144
  31. package/src/graphs/contextManagement.e2e.test.js +0 -718
  32. package/src/graphs/contextManagement.test.js +0 -485
  33. package/src/graphs/handoffValidation.test.js +0 -276
  34. package/src/graphs/index.js +0 -3
  35. package/src/index.js +0 -28
  36. package/src/instrumentation.js +0 -21
  37. package/src/llm/anthropic/index.js +0 -319
  38. package/src/llm/anthropic/types.js +0 -46
  39. package/src/llm/anthropic/utils/message_inputs.js +0 -627
  40. package/src/llm/anthropic/utils/message_outputs.js +0 -290
  41. package/src/llm/anthropic/utils/output_parsers.js +0 -89
  42. package/src/llm/anthropic/utils/tools.js +0 -25
  43. package/src/llm/bedrock/__tests__/bedrock-caching.test.js +0 -392
  44. package/src/llm/bedrock/index.js +0 -303
  45. package/src/llm/bedrock/types.js +0 -2
  46. package/src/llm/bedrock/utils/index.js +0 -6
  47. package/src/llm/bedrock/utils/message_inputs.js +0 -463
  48. package/src/llm/bedrock/utils/message_outputs.js +0 -269
  49. package/src/llm/fake.js +0 -92
  50. package/src/llm/google/index.js +0 -215
  51. package/src/llm/google/types.js +0 -12
  52. package/src/llm/google/utils/common.js +0 -670
  53. package/src/llm/google/utils/tools.js +0 -111
  54. package/src/llm/google/utils/zod_to_genai_parameters.js +0 -47
  55. package/src/llm/openai/index.js +0 -1033
  56. package/src/llm/openai/types.js +0 -2
  57. package/src/llm/openai/utils/index.js +0 -756
  58. package/src/llm/openai/utils/isReasoningModel.test.js +0 -79
  59. package/src/llm/openrouter/index.js +0 -261
  60. package/src/llm/openrouter/reasoning.test.js +0 -181
  61. package/src/llm/providers.js +0 -36
  62. package/src/llm/text.js +0 -65
  63. package/src/llm/vertexai/index.js +0 -402
  64. package/src/messages/__tests__/tools.test.js +0 -392
  65. package/src/messages/cache.js +0 -404
  66. package/src/messages/cache.test.js +0 -1167
  67. package/src/messages/content.js +0 -48
  68. package/src/messages/content.test.js +0 -314
  69. package/src/messages/core.js +0 -359
  70. package/src/messages/ensureThinkingBlock.test.js +0 -997
  71. package/src/messages/format.js +0 -973
  72. package/src/messages/formatAgentMessages.test.js +0 -2278
  73. package/src/messages/formatAgentMessages.tools.test.js +0 -362
  74. package/src/messages/formatMessage.test.js +0 -608
  75. package/src/messages/ids.js +0 -18
  76. package/src/messages/index.js +0 -9
  77. package/src/messages/labelContentByAgent.test.js +0 -725
  78. package/src/messages/prune.js +0 -438
  79. package/src/messages/reducer.js +0 -60
  80. package/src/messages/shiftIndexTokenCountMap.test.js +0 -63
  81. package/src/messages/summarize.js +0 -146
  82. package/src/messages/summarize.test.js +0 -332
  83. package/src/messages/tools.js +0 -90
  84. package/src/mockStream.js +0 -81
  85. package/src/prompts/collab.js +0 -7
  86. package/src/prompts/index.js +0 -3
  87. package/src/prompts/taskmanager.js +0 -58
  88. package/src/run.js +0 -427
  89. package/src/schemas/index.js +0 -3
  90. package/src/schemas/schema-preparation.test.js +0 -370
  91. package/src/schemas/validate.js +0 -314
  92. package/src/schemas/validate.test.js +0 -264
  93. package/src/scripts/abort.js +0 -127
  94. package/src/scripts/ant_web_search.js +0 -130
  95. package/src/scripts/ant_web_search_edge_case.js +0 -133
  96. package/src/scripts/ant_web_search_error_edge_case.js +0 -119
  97. package/src/scripts/args.js +0 -41
  98. package/src/scripts/bedrock-cache-debug.js +0 -186
  99. package/src/scripts/bedrock-content-aggregation-test.js +0 -195
  100. package/src/scripts/bedrock-merge-test.js +0 -80
  101. package/src/scripts/bedrock-parallel-tools-test.js +0 -150
  102. package/src/scripts/caching.js +0 -106
  103. package/src/scripts/cli.js +0 -152
  104. package/src/scripts/cli2.js +0 -119
  105. package/src/scripts/cli3.js +0 -163
  106. package/src/scripts/cli4.js +0 -165
  107. package/src/scripts/cli5.js +0 -165
  108. package/src/scripts/code_exec.js +0 -171
  109. package/src/scripts/code_exec_files.js +0 -180
  110. package/src/scripts/code_exec_multi_session.js +0 -185
  111. package/src/scripts/code_exec_ptc.js +0 -265
  112. package/src/scripts/code_exec_session.js +0 -217
  113. package/src/scripts/code_exec_simple.js +0 -120
  114. package/src/scripts/content.js +0 -111
  115. package/src/scripts/empty_input.js +0 -125
  116. package/src/scripts/handoff-test.js +0 -96
  117. package/src/scripts/image.js +0 -138
  118. package/src/scripts/memory.js +0 -83
  119. package/src/scripts/multi-agent-chain.js +0 -271
  120. package/src/scripts/multi-agent-conditional.js +0 -185
  121. package/src/scripts/multi-agent-document-review-chain.js +0 -171
  122. package/src/scripts/multi-agent-hybrid-flow.js +0 -264
  123. package/src/scripts/multi-agent-parallel-start.js +0 -214
  124. package/src/scripts/multi-agent-parallel.js +0 -346
  125. package/src/scripts/multi-agent-sequence.js +0 -184
  126. package/src/scripts/multi-agent-supervisor.js +0 -324
  127. package/src/scripts/multi-agent-test.js +0 -147
  128. package/src/scripts/parallel-asymmetric-tools-test.js +0 -202
  129. package/src/scripts/parallel-full-metadata-test.js +0 -176
  130. package/src/scripts/parallel-tools-test.js +0 -256
  131. package/src/scripts/programmatic_exec.js +0 -277
  132. package/src/scripts/programmatic_exec_agent.js +0 -168
  133. package/src/scripts/search.js +0 -118
  134. package/src/scripts/sequential-full-metadata-test.js +0 -143
  135. package/src/scripts/simple.js +0 -174
  136. package/src/scripts/single-agent-metadata-test.js +0 -152
  137. package/src/scripts/stream.js +0 -113
  138. package/src/scripts/test-custom-prompt-key.js +0 -132
  139. package/src/scripts/test-handoff-input.js +0 -143
  140. package/src/scripts/test-handoff-preamble.js +0 -227
  141. package/src/scripts/test-handoff-steering.js +0 -353
  142. package/src/scripts/test-multi-agent-list-handoff.js +0 -318
  143. package/src/scripts/test-parallel-agent-labeling.js +0 -253
  144. package/src/scripts/test-parallel-handoffs.js +0 -229
  145. package/src/scripts/test-thinking-handoff-bedrock.js +0 -132
  146. package/src/scripts/test-thinking-handoff.js +0 -132
  147. package/src/scripts/test-thinking-to-thinking-handoff-bedrock.js +0 -140
  148. package/src/scripts/test-tool-before-handoff-role-order.js +0 -223
  149. package/src/scripts/test-tools-before-handoff.js +0 -187
  150. package/src/scripts/test_code_api.js +0 -263
  151. package/src/scripts/thinking-bedrock.js +0 -128
  152. package/src/scripts/thinking-vertexai.js +0 -130
  153. package/src/scripts/thinking.js +0 -134
  154. package/src/scripts/tool_search.js +0 -114
  155. package/src/scripts/tools.js +0 -125
  156. package/src/specs/agent-handoffs-bedrock.integration.test.js +0 -280
  157. package/src/specs/agent-handoffs.test.js +0 -924
  158. package/src/specs/anthropic.simple.test.js +0 -287
  159. package/src/specs/azure.simple.test.js +0 -381
  160. package/src/specs/cache.simple.test.js +0 -282
  161. package/src/specs/custom-event-await.test.js +0 -148
  162. package/src/specs/deepseek.simple.test.js +0 -189
  163. package/src/specs/emergency-prune.test.js +0 -308
  164. package/src/specs/moonshot.simple.test.js +0 -237
  165. package/src/specs/observability.integration.test.js +0 -1337
  166. package/src/specs/openai.simple.test.js +0 -233
  167. package/src/specs/openrouter.simple.test.js +0 -202
  168. package/src/specs/prune.test.js +0 -733
  169. package/src/specs/reasoning.test.js +0 -144
  170. package/src/specs/spec.utils.js +0 -4
  171. package/src/specs/thinking-handoff.test.js +0 -486
  172. package/src/specs/thinking-prune.test.js +0 -600
  173. package/src/specs/token-distribution-edge-case.test.js +0 -246
  174. package/src/specs/token-memoization.test.js +0 -32
  175. package/src/specs/tokens.test.js +0 -49
  176. package/src/specs/tool-error.test.js +0 -139
  177. package/src/splitStream.js +0 -204
  178. package/src/splitStream.test.js +0 -504
  179. package/src/stream.js +0 -650
  180. package/src/stream.test.js +0 -225
  181. package/src/test/mockTools.js +0 -340
  182. package/src/tools/BrowserTools.js +0 -245
  183. package/src/tools/Calculator.js +0 -38
  184. package/src/tools/Calculator.test.js +0 -225
  185. package/src/tools/CodeExecutor.js +0 -233
  186. package/src/tools/ProgrammaticToolCalling.js +0 -602
  187. package/src/tools/StreamingToolCallBuffer.js +0 -179
  188. package/src/tools/ToolNode.js +0 -930
  189. package/src/tools/ToolSearch.js +0 -904
  190. package/src/tools/__tests__/BrowserTools.test.js +0 -306
  191. package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.js +0 -276
  192. package/src/tools/__tests__/ProgrammaticToolCalling.test.js +0 -807
  193. package/src/tools/__tests__/StreamingToolCallBuffer.test.js +0 -175
  194. package/src/tools/__tests__/ToolApproval.test.js +0 -675
  195. package/src/tools/__tests__/ToolNode.recovery.test.js +0 -200
  196. package/src/tools/__tests__/ToolNode.session.test.js +0 -319
  197. package/src/tools/__tests__/ToolSearch.integration.test.js +0 -125
  198. package/src/tools/__tests__/ToolSearch.test.js +0 -812
  199. package/src/tools/__tests__/handlers.test.js +0 -799
  200. package/src/tools/__tests__/truncation-recovery.integration.test.js +0 -362
  201. package/src/tools/handlers.js +0 -306
  202. package/src/tools/schema.js +0 -25
  203. package/src/tools/search/anthropic.js +0 -34
  204. package/src/tools/search/content.js +0 -116
  205. package/src/tools/search/content.test.js +0 -133
  206. package/src/tools/search/firecrawl.js +0 -173
  207. package/src/tools/search/format.js +0 -198
  208. package/src/tools/search/highlights.js +0 -241
  209. package/src/tools/search/index.js +0 -3
  210. package/src/tools/search/jina-reranker.test.js +0 -106
  211. package/src/tools/search/rerankers.js +0 -165
  212. package/src/tools/search/schema.js +0 -102
  213. package/src/tools/search/search.js +0 -561
  214. package/src/tools/search/serper-scraper.js +0 -126
  215. package/src/tools/search/test.js +0 -129
  216. package/src/tools/search/tool.js +0 -453
  217. package/src/tools/search/types.js +0 -2
  218. package/src/tools/search/utils.js +0 -59
  219. package/src/types/graph.js +0 -24
  220. package/src/types/graph.test.js +0 -192
  221. package/src/types/index.js +0 -7
  222. package/src/types/llm.js +0 -2
  223. package/src/types/messages.js +0 -2
  224. package/src/types/run.js +0 -2
  225. package/src/types/stream.js +0 -2
  226. package/src/types/tools.js +0 -2
  227. package/src/utils/contextAnalytics.js +0 -79
  228. package/src/utils/contextAnalytics.test.js +0 -166
  229. package/src/utils/events.js +0 -26
  230. package/src/utils/graph.js +0 -11
  231. package/src/utils/handlers.js +0 -65
  232. package/src/utils/index.js +0 -10
  233. package/src/utils/llm.js +0 -21
  234. package/src/utils/llmConfig.js +0 -205
  235. package/src/utils/logging.js +0 -37
  236. package/src/utils/misc.js +0 -51
  237. package/src/utils/run.js +0 -69
  238. package/src/utils/schema.js +0 -21
  239. package/src/utils/title.js +0 -119
  240. package/src/utils/tokens.js +0 -92
  241. package/src/utils/toonFormat.js +0 -379
@@ -1,782 +0,0 @@
1
- /* eslint-disable no-console */
2
- // src/agents/AgentContext.ts
3
- import { SystemMessage } from '@langchain/core/messages';
4
- import { RunnableLambda } from '@langchain/core/runnables';
5
- import { createSchemaOnlyTools } from '@/tools/schema';
6
- import { ContentTypes, Providers } from '@/common';
7
- import { toJsonSchema } from '@/utils/schema';
8
- /**
9
- * Encapsulates agent-specific state that can vary between agents in a multi-agent system
10
- */
11
- export class AgentContext {
12
- /**
13
- * Create an AgentContext from configuration with token accounting initialization
14
- */
15
- static fromConfig(agentConfig, tokenCounter, indexTokenCountMap) {
16
- 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
- // Normalize structured output: support both camelCase and snake_case inputs
18
- // Priority: structuredOutput (camelCase) > structured_output (snake_case with enabled check)
19
- let structuredOutput;
20
- if (structuredOutputCamel) {
21
- structuredOutput = structuredOutputCamel;
22
- }
23
- else if (structuredOutputSnake?.enabled === true &&
24
- structuredOutputSnake.schema != null) {
25
- // Convert snake_case input to StructuredOutputConfig
26
- structuredOutput = {
27
- schema: structuredOutputSnake.schema,
28
- name: structuredOutputSnake.name,
29
- description: structuredOutputSnake.description,
30
- mode: structuredOutputSnake.mode,
31
- strict: structuredOutputSnake.strict,
32
- };
33
- }
34
- const agentContext = new AgentContext({
35
- agentId,
36
- name: name ?? agentId,
37
- description,
38
- provider,
39
- clientOptions,
40
- maxContextTokens,
41
- streamBuffer,
42
- tools,
43
- toolMap,
44
- toolRegistry,
45
- toolDefinitions,
46
- instructions,
47
- additionalInstructions: additional_instructions,
48
- reasoningKey,
49
- toolEnd,
50
- instructionTokens: 0,
51
- tokenCounter,
52
- useLegacyContent,
53
- dynamicContext,
54
- structuredOutput,
55
- discoveredTools,
56
- summarizeCallback,
57
- persistedSummary,
58
- });
59
- if (tokenCounter) {
60
- // Initialize system runnable BEFORE async tool token calculation
61
- // This ensures system message tokens are in instructionTokens before
62
- // updateTokenMapWithInstructions is called
63
- agentContext.initializeSystemRunnable();
64
- const tokenMap = indexTokenCountMap || {};
65
- agentContext.baseIndexTokenCountMap = { ...tokenMap };
66
- agentContext.indexTokenCountMap = tokenMap;
67
- agentContext.tokenCalculationPromise = agentContext
68
- .calculateInstructionTokens(tokenCounter)
69
- .then(() => {
70
- // Update token map with instruction tokens (includes system + tool tokens)
71
- agentContext.updateTokenMapWithInstructions(tokenMap);
72
- })
73
- .catch((err) => {
74
- console.error('Error calculating instruction tokens:', err);
75
- });
76
- }
77
- else if (indexTokenCountMap) {
78
- agentContext.baseIndexTokenCountMap = { ...indexTokenCountMap };
79
- agentContext.indexTokenCountMap = indexTokenCountMap;
80
- }
81
- return agentContext;
82
- }
83
- /** Agent identifier */
84
- agentId;
85
- /** Human-readable name for this agent (used in handoff context). Falls back to agentId if not provided. */
86
- name;
87
- /** Description of what this agent does (used to enrich handoff tool descriptions). */
88
- description;
89
- /** Provider for this specific agent */
90
- provider;
91
- /** Client options for this agent */
92
- clientOptions;
93
- /** Token count map indexed by message position */
94
- indexTokenCountMap = {};
95
- /** Canonical pre-run token map used to restore token accounting on reset */
96
- baseIndexTokenCountMap = {};
97
- /** Maximum context tokens for this agent */
98
- maxContextTokens;
99
- /** Current usage metadata for this agent */
100
- currentUsage;
101
- /** Prune messages function configured for this agent */
102
- pruneMessages;
103
- /** Token counter function for this agent */
104
- tokenCounter;
105
- /** Instructions/system message token count */
106
- instructionTokens = 0;
107
- /** The amount of time that should pass before another consecutive API call */
108
- streamBuffer;
109
- /** Last stream call timestamp for rate limiting */
110
- lastStreamCall;
111
- /** Tools available to this agent */
112
- tools;
113
- /** Graph-managed tools (e.g., handoff tools created by MultiAgentGraph) that bypass event-driven dispatch */
114
- graphTools;
115
- /** Tool map for this agent */
116
- toolMap;
117
- /**
118
- * Tool definitions registry (includes deferred and programmatic tool metadata).
119
- * Used for tool search and programmatic tool calling.
120
- */
121
- toolRegistry;
122
- /**
123
- * Serializable tool definitions for event-driven execution.
124
- * When provided, ToolNode operates in event-driven mode.
125
- */
126
- toolDefinitions;
127
- /** Set of tool names discovered via tool search (to be loaded) */
128
- discoveredToolNames = new Set();
129
- /** Instructions for this agent */
130
- instructions;
131
- /** Additional instructions for this agent */
132
- additionalInstructions;
133
- /**
134
- * Dynamic context that changes per-request (e.g., current time, user info).
135
- * This is NOT included in the system message to preserve cache.
136
- * Instead, it's injected as a user message at the start of the conversation.
137
- */
138
- dynamicContext;
139
- /** Reasoning key for this agent */
140
- reasoningKey = 'reasoning_content';
141
- /** Last token for reasoning detection */
142
- lastToken;
143
- /** Token type switch state */
144
- tokenTypeSwitch;
145
- /** Tracks how many reasoning→text transitions have occurred (ensures unique post-reasoning step keys) */
146
- reasoningTransitionCount = 0;
147
- /** Current token type being processed */
148
- currentTokenType = ContentTypes.TEXT;
149
- /** Whether tools should end the workflow */
150
- toolEnd = false;
151
- /** Cached system runnable (created lazily) */
152
- cachedSystemRunnable;
153
- /** Whether system runnable needs rebuild (set when discovered tools change) */
154
- systemRunnableStale = true;
155
- /** Cached system message token count (separate from tool tokens) */
156
- systemMessageTokens = 0;
157
- /** Promise for token calculation initialization */
158
- tokenCalculationPromise;
159
- /** Format content blocks as strings (for legacy compatibility) */
160
- useLegacyContent = false;
161
- /** Detailed per-tool token breakdown for admin tracking */
162
- toolsDetail = [];
163
- /** Total tool tokens (sum of all toolsDetail) */
164
- toolTokensTotal = 0;
165
- /** Per-prompt token breakdown for detailed admin reporting */
166
- promptBreakdown = {
167
- branding: 0,
168
- toolRouting: 0,
169
- agentInstructions: 0,
170
- mcpInstructions: 0,
171
- artifacts: 0,
172
- memory: 0,
173
- };
174
- /**
175
- * Handoff context when this agent receives control via handoff.
176
- * Contains source and parallel execution info for system message context.
177
- */
178
- handoffContext;
179
- /**
180
- * Structured output configuration.
181
- * When set, the agent will return a validated JSON response
182
- * instead of streaming text.
183
- */
184
- structuredOutput;
185
- /** Optional callback to summarize discarded messages during context pruning */
186
- summarizeCallback;
187
- /** Pre-existing summary loaded from persistent storage, injected into context on new turns */
188
- persistedSummary;
189
- constructor({ agentId, name, description, provider, clientOptions, maxContextTokens, streamBuffer, tokenCounter, tools, toolMap, toolRegistry, toolDefinitions, instructions, additionalInstructions, dynamicContext, reasoningKey, toolEnd, instructionTokens, useLegacyContent, structuredOutput, discoveredTools, summarizeCallback, persistedSummary, }) {
190
- this.agentId = agentId;
191
- this.name = name;
192
- this.description = description;
193
- this.provider = provider;
194
- this.clientOptions = clientOptions;
195
- this.maxContextTokens = maxContextTokens;
196
- this.streamBuffer = streamBuffer;
197
- this.tokenCounter = tokenCounter;
198
- this.tools = tools;
199
- this.toolMap = toolMap;
200
- this.toolRegistry = toolRegistry;
201
- this.toolDefinitions = toolDefinitions;
202
- this.instructions = instructions;
203
- this.additionalInstructions = additionalInstructions;
204
- this.dynamicContext = dynamicContext;
205
- this.structuredOutput = structuredOutput;
206
- this.summarizeCallback = summarizeCallback;
207
- this.persistedSummary = persistedSummary;
208
- if (reasoningKey) {
209
- this.reasoningKey = reasoningKey;
210
- }
211
- if (toolEnd !== undefined) {
212
- this.toolEnd = toolEnd;
213
- }
214
- if (instructionTokens !== undefined) {
215
- this.instructionTokens = instructionTokens;
216
- }
217
- this.useLegacyContent = useLegacyContent ?? false;
218
- if (discoveredTools && discoveredTools.length > 0) {
219
- for (const toolName of discoveredTools) {
220
- this.discoveredToolNames.add(toolName);
221
- }
222
- }
223
- }
224
- /**
225
- * Checks if structured output mode is enabled for this agent.
226
- * When enabled, the agent will use model.invoke() instead of streaming
227
- * and return a validated JSON response.
228
- */
229
- get isStructuredOutputMode() {
230
- // Runtime safety: schema can be null/undefined via API despite type saying required
231
- return (this.structuredOutput != null &&
232
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
233
- this.structuredOutput.schema != null);
234
- }
235
- /**
236
- * Gets the structured output schema with normalized defaults.
237
- * Returns undefined if structured output is not configured.
238
- */
239
- getStructuredOutputSchema() {
240
- if (!this.structuredOutput?.schema) {
241
- return undefined;
242
- }
243
- const schema = { ...this.structuredOutput.schema };
244
- // Ensure type is set
245
- if (schema.type == null && schema.properties != null) {
246
- schema.type = 'object';
247
- }
248
- // Add title from config name
249
- if (this.structuredOutput.name != null &&
250
- this.structuredOutput.name !== '' &&
251
- schema.title == null) {
252
- schema.title = this.structuredOutput.name;
253
- }
254
- // Add description from config
255
- if (this.structuredOutput.description != null &&
256
- this.structuredOutput.description !== '' &&
257
- schema.description == null) {
258
- schema.description = this.structuredOutput.description;
259
- }
260
- // Enable strict mode by default
261
- if (this.structuredOutput.strict !== false && schema.type === 'object') {
262
- schema.additionalProperties = schema.additionalProperties ?? false;
263
- }
264
- return schema;
265
- }
266
- /**
267
- * Resolves the structured output mode to a concrete method based on provider capabilities.
268
- *
269
- * Resolution logic:
270
- * - 'native' or 'auto' + supported provider → native constrained decoding
271
- * - 'native' + unsupported provider → fallback to 'functionCalling' with warning
272
- * - 'provider' → LangChain's jsonMode (existing behavior)
273
- * - 'tool' → function calling trick (existing behavior)
274
- * - 'auto' + unsupported provider → 'functionCalling'
275
- *
276
- * @returns The resolved method for withStructuredOutput, or 'native' for direct API usage
277
- */
278
- resolveStructuredOutputMode() {
279
- const mode = this.structuredOutput?.mode ?? 'auto';
280
- const warnings = [];
281
- // Providers that support native constrained decoding via LangChain
282
- const nativeProviders = new Set([
283
- Providers.ANTHROPIC,
284
- Providers.OPENAI,
285
- Providers.AZURE,
286
- ]);
287
- // Providers where LangChain supports jsonMode
288
- const jsonModeProviders = new Set([
289
- Providers.ANTHROPIC,
290
- Providers.OPENAI,
291
- Providers.AZURE,
292
- ]);
293
- switch (mode) {
294
- case 'native': {
295
- if (nativeProviders.has(this.provider)) {
296
- if (this.provider === Providers.ANTHROPIC) {
297
- return { method: 'jsonSchema', warnings };
298
- }
299
- // OpenAI/Azure
300
- return { method: 'jsonSchema', warnings };
301
- }
302
- // Fallback for unsupported providers
303
- warnings.push(`Native structured output is not supported for provider '${this.provider}'. Falling back to function calling.`);
304
- return { method: 'functionCalling', warnings };
305
- }
306
- case 'auto': {
307
- if (nativeProviders.has(this.provider)) {
308
- if (this.provider === Providers.ANTHROPIC) {
309
- return { method: 'jsonSchema', warnings };
310
- }
311
- // OpenAI/Azure
312
- return { method: 'jsonSchema', warnings };
313
- }
314
- // Default to function calling for all other providers
315
- return { method: undefined, warnings };
316
- }
317
- case 'provider': {
318
- if (this.provider === Providers.BEDROCK) {
319
- // Bedrock doesn't support jsonMode, fall back to functionCalling
320
- return { method: 'functionCalling', warnings };
321
- }
322
- if (jsonModeProviders.has(this.provider)) {
323
- return { method: 'jsonMode', warnings };
324
- }
325
- return { method: 'jsonMode', warnings };
326
- }
327
- case 'tool': {
328
- return { method: 'functionCalling', warnings };
329
- }
330
- default: {
331
- return { method: undefined, warnings };
332
- }
333
- }
334
- }
335
- /**
336
- * Builds instructions text for tools that are ONLY callable via programmatic code execution.
337
- * These tools cannot be called directly by the LLM but are available through the
338
- * run_tools_with_code tool.
339
- *
340
- * Includes:
341
- * - Code_execution-only tools that are NOT deferred
342
- * - Code_execution-only tools that ARE deferred but have been discovered via tool search
343
- */
344
- buildProgrammaticOnlyToolsInstructions() {
345
- if (!this.toolRegistry)
346
- return '';
347
- const programmaticOnlyTools = [];
348
- for (const [name, toolDef] of this.toolRegistry) {
349
- const allowedCallers = toolDef.allowed_callers ?? ['direct'];
350
- const isCodeExecutionOnly = allowedCallers.includes('code_execution') &&
351
- !allowedCallers.includes('direct');
352
- if (!isCodeExecutionOnly)
353
- continue;
354
- // Include if: not deferred OR deferred but discovered
355
- const isDeferred = toolDef.defer_loading === true;
356
- const isDiscovered = this.discoveredToolNames.has(name);
357
- if (!isDeferred || isDiscovered) {
358
- programmaticOnlyTools.push(toolDef);
359
- }
360
- }
361
- if (programmaticOnlyTools.length === 0)
362
- return '';
363
- const toolDescriptions = programmaticOnlyTools
364
- .map((tool) => {
365
- let desc = `- **${tool.name}**`;
366
- if (tool.description != null && tool.description !== '') {
367
- desc += `: ${tool.description}`;
368
- }
369
- if (tool.parameters) {
370
- desc += `\n Parameters: ${JSON.stringify(tool.parameters, null, 2).replace(/\n/g, '\n ')}`;
371
- }
372
- return desc;
373
- })
374
- .join('\n\n');
375
- return ('\n\n## Programmatic-Only Tools\n\n' +
376
- 'The following tools are available exclusively through the `run_tools_with_code` tool. ' +
377
- 'You cannot call these tools directly; instead, use `run_tools_with_code` with Python code that invokes them.\n\n' +
378
- toolDescriptions);
379
- }
380
- /**
381
- * Gets the system runnable, creating it lazily if needed.
382
- * Includes instructions, additional instructions, and programmatic-only tools documentation.
383
- * Only rebuilds when marked stale (via markToolsAsDiscovered).
384
- */
385
- get systemRunnable() {
386
- // Return cached if not stale
387
- if (!this.systemRunnableStale && this.cachedSystemRunnable !== undefined) {
388
- return this.cachedSystemRunnable;
389
- }
390
- // Stale or first access - rebuild
391
- const instructionsString = this.buildInstructionsString();
392
- this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);
393
- this.systemRunnableStale = false;
394
- return this.cachedSystemRunnable;
395
- }
396
- /**
397
- * Explicitly initializes the system runnable.
398
- * Call this before async token calculation to ensure system message tokens are counted first.
399
- */
400
- initializeSystemRunnable() {
401
- if (this.systemRunnableStale || this.cachedSystemRunnable === undefined) {
402
- const instructionsString = this.buildInstructionsString();
403
- this.cachedSystemRunnable = this.buildSystemRunnable(instructionsString);
404
- this.systemRunnableStale = false;
405
- }
406
- }
407
- /**
408
- * Builds the raw instructions string (without creating SystemMessage).
409
- * Includes agent identity preamble and handoff context when available.
410
- */
411
- buildInstructionsString() {
412
- const parts = [];
413
- /** Build agent identity and handoff context preamble */
414
- const identityPreamble = this.buildIdentityPreamble();
415
- if (identityPreamble) {
416
- parts.push(identityPreamble);
417
- }
418
- /** Add main instructions */
419
- if (this.instructions != null && this.instructions !== '') {
420
- parts.push(this.instructions);
421
- }
422
- /** Add additional instructions */
423
- if (this.additionalInstructions != null &&
424
- this.additionalInstructions !== '') {
425
- parts.push(this.additionalInstructions);
426
- }
427
- /** Add programmatic tools documentation */
428
- const programmaticToolsDoc = this.buildProgrammaticOnlyToolsInstructions();
429
- if (programmaticToolsDoc) {
430
- parts.push(programmaticToolsDoc);
431
- }
432
- return parts.join('\n\n');
433
- }
434
- /**
435
- * Builds the agent identity preamble including handoff context if present.
436
- * This helps the agent understand its role in the multi-agent workflow.
437
- */
438
- buildIdentityPreamble() {
439
- if (!this.handoffContext)
440
- return '';
441
- const displayName = this.name ?? this.agentId;
442
- const { sourceAgentName, parallelSiblings } = this.handoffContext;
443
- const isParallel = parallelSiblings.length > 0;
444
- const lines = [];
445
- lines.push('## Multi-Agent Workflow');
446
- lines.push(`You are "${displayName}", transferred from "${sourceAgentName}".`);
447
- if (isParallel) {
448
- lines.push(`Running in parallel with: ${parallelSiblings.join(', ')}.`);
449
- }
450
- lines.push('Execute only tasks relevant to your role. Routing is already handled if requested, unless you can route further.');
451
- return lines.join('\n');
452
- }
453
- /**
454
- * Build system runnable from pre-built instructions string.
455
- * Only called when content has actually changed.
456
- */
457
- buildSystemRunnable(instructionsString) {
458
- if (!instructionsString) {
459
- // Remove previous tokens if we had a system message before
460
- this.instructionTokens -= this.systemMessageTokens;
461
- this.systemMessageTokens = 0;
462
- return undefined;
463
- }
464
- let finalInstructions = instructionsString;
465
- // Handle Anthropic prompt caching (Direct API)
466
- if (this.provider === Providers.ANTHROPIC) {
467
- const anthropicOptions = this.clientOptions;
468
- if (anthropicOptions?.promptCache === true) {
469
- finalInstructions = {
470
- content: [
471
- {
472
- type: 'text',
473
- text: instructionsString,
474
- cache_control: { type: 'ephemeral' },
475
- },
476
- ],
477
- };
478
- }
479
- }
480
- const systemMessage = new SystemMessage(finalInstructions);
481
- // Update token counts (subtract old, add new)
482
- if (this.tokenCounter) {
483
- this.instructionTokens -= this.systemMessageTokens;
484
- this.systemMessageTokens = this.tokenCounter(systemMessage);
485
- this.instructionTokens += this.systemMessageTokens;
486
- }
487
- return RunnableLambda.from((messages) => {
488
- return [systemMessage, ...messages];
489
- }).withConfig({ runName: 'prompt' });
490
- }
491
- /**
492
- * Reset context for a new run
493
- */
494
- reset() {
495
- this.instructionTokens = 0;
496
- this.systemMessageTokens = 0;
497
- this.toolsDetail = [];
498
- this.toolTokensTotal = 0;
499
- this.cachedSystemRunnable = undefined;
500
- this.systemRunnableStale = true;
501
- this.lastToken = undefined;
502
- this.indexTokenCountMap = { ...this.baseIndexTokenCountMap };
503
- this.currentUsage = undefined;
504
- this.pruneMessages = undefined;
505
- this.lastStreamCall = undefined;
506
- this.tokenTypeSwitch = undefined;
507
- this.reasoningTransitionCount = 0;
508
- this.currentTokenType = ContentTypes.TEXT;
509
- this.discoveredToolNames.clear();
510
- this.handoffContext = undefined;
511
- if (this.tokenCounter) {
512
- this.initializeSystemRunnable();
513
- const baseTokenMap = { ...this.baseIndexTokenCountMap };
514
- this.indexTokenCountMap = baseTokenMap;
515
- this.tokenCalculationPromise = this.calculateInstructionTokens(this.tokenCounter)
516
- .then(() => {
517
- this.updateTokenMapWithInstructions(baseTokenMap);
518
- })
519
- .catch((err) => {
520
- console.error('Error calculating instruction tokens:', err);
521
- });
522
- }
523
- else {
524
- this.tokenCalculationPromise = undefined;
525
- }
526
- }
527
- /**
528
- * Update the token count map with instruction tokens
529
- */
530
- updateTokenMapWithInstructions(baseTokenMap) {
531
- if (this.instructionTokens > 0) {
532
- // Shift all indices by the instruction token count
533
- const shiftedMap = {};
534
- for (const [key, value] of Object.entries(baseTokenMap)) {
535
- const index = parseInt(key, 10);
536
- if (!isNaN(index)) {
537
- shiftedMap[String(index)] =
538
- value + (index === 0 ? this.instructionTokens : 0);
539
- }
540
- }
541
- this.indexTokenCountMap = shiftedMap;
542
- }
543
- else {
544
- this.indexTokenCountMap = { ...baseTokenMap };
545
- }
546
- }
547
- /**
548
- * Calculate tool tokens and add to instruction tokens
549
- * Note: System message tokens are calculated during systemRunnable creation
550
- * Also tracks per-tool token breakdown for admin reporting
551
- */
552
- async calculateInstructionTokens(tokenCounter) {
553
- let toolTokens = 0;
554
- // Track names to avoid double-counting when a tool appears in both
555
- // this.tools (bound StructuredTool instances) and this.toolDefinitions
556
- // (MCP / event-driven schemas).
557
- const countedToolNames = new Set();
558
- // Reset per-tool breakdown
559
- this.toolsDetail = [];
560
- // Count tokens for bound tools (StructuredTool instances with .schema)
561
- if (this.tools && this.tools.length > 0) {
562
- for (const tool of this.tools) {
563
- const genericTool = tool;
564
- if (genericTool.schema != null &&
565
- typeof genericTool.schema === 'object') {
566
- const toolName = genericTool.name ?? '';
567
- const jsonSchema = toJsonSchema(genericTool.schema, toolName, genericTool.description ?? '');
568
- const tokens = tokenCounter(new SystemMessage(JSON.stringify(jsonSchema)));
569
- if (toolName) {
570
- countedToolNames.add(toolName);
571
- }
572
- // Track per-tool breakdown
573
- this.toolsDetail.push({ name: toolName || 'unknown', tokens });
574
- toolTokens += tokens;
575
- }
576
- }
577
- }
578
- // Count tokens for tool definitions (MCP / event-driven tools).
579
- // These are sent to the provider API as tool schemas alongside bound tools.
580
- // Both can be populated simultaneously (graph tools + MCP tools).
581
- if (this.toolDefinitions && this.toolDefinitions.length > 0) {
582
- for (const def of this.toolDefinitions) {
583
- if (countedToolNames.has(def.name)) {
584
- continue; // Already counted via this.tools
585
- }
586
- const schema = {
587
- name: def.name,
588
- description: def.description ?? '',
589
- parameters: def.parameters ?? {},
590
- };
591
- const defTokens = tokenCounter(new SystemMessage(JSON.stringify(schema)));
592
- this.toolsDetail.push({
593
- name: def.name || 'unknown',
594
- tokens: defTokens,
595
- });
596
- toolTokens += defTokens;
597
- }
598
- }
599
- // Store total tool tokens for breakdown reporting
600
- this.toolTokensTotal = toolTokens;
601
- // Add tool tokens to existing instruction tokens (which may already include system message tokens)
602
- this.instructionTokens += toolTokens;
603
- }
604
- /**
605
- * Set the per-prompt token breakdown for detailed admin tracking.
606
- * Called by the client after assembling all prompt components.
607
- * @param breakdown - Object with token counts per prompt component
608
- */
609
- setPromptBreakdown(breakdown) {
610
- if (breakdown.branding !== undefined)
611
- this.promptBreakdown.branding = breakdown.branding;
612
- if (breakdown.toolRouting !== undefined)
613
- this.promptBreakdown.toolRouting = breakdown.toolRouting;
614
- if (breakdown.agentInstructions !== undefined)
615
- this.promptBreakdown.agentInstructions = breakdown.agentInstructions;
616
- if (breakdown.mcpInstructions !== undefined)
617
- this.promptBreakdown.mcpInstructions = breakdown.mcpInstructions;
618
- if (breakdown.artifacts !== undefined)
619
- this.promptBreakdown.artifacts = breakdown.artifacts;
620
- if (breakdown.memory !== undefined)
621
- this.promptBreakdown.memory = breakdown.memory;
622
- }
623
- /**
624
- * Get a detailed breakdown of context tokens for admin reporting.
625
- * This provides visibility into what's consuming the input token budget.
626
- * @returns ContextBreakdown object with per-component token counts
627
- */
628
- getContextBreakdown() {
629
- // Calculate sum of prompt components
630
- const promptsTotal = this.promptBreakdown.branding +
631
- this.promptBreakdown.toolRouting +
632
- this.promptBreakdown.agentInstructions +
633
- this.promptBreakdown.mcpInstructions +
634
- this.promptBreakdown.artifacts +
635
- this.promptBreakdown.memory;
636
- return {
637
- // System message tokens (instructions + additional_instructions)
638
- instructions: this.systemMessageTokens,
639
- // Artifacts prompt tokens
640
- artifacts: this.promptBreakdown.artifacts,
641
- // Total tool definition tokens
642
- tools: this.toolTokensTotal,
643
- // Number of tools
644
- toolCount: this.toolsDetail.length,
645
- // Tool context/usage instructions (currently embedded in system message)
646
- toolContext: 0,
647
- // Total tracked context tokens
648
- total: this.instructionTokens,
649
- // Per-tool token breakdown
650
- toolsDetail: [...this.toolsDetail],
651
- // Tool context detail (currently not tracked separately)
652
- toolContextDetail: [],
653
- // Per-prompt breakdown (only include if any prompts were tracked)
654
- prompts: promptsTotal > 0 ? { ...this.promptBreakdown } : undefined,
655
- };
656
- }
657
- /**
658
- * Gets the tool registry for deferred tools (for tool search).
659
- * @param onlyDeferred If true, only returns tools with defer_loading=true
660
- * @returns LCToolRegistry with tool definitions
661
- */
662
- getDeferredToolRegistry(onlyDeferred = true) {
663
- const registry = new Map();
664
- if (!this.toolRegistry) {
665
- return registry;
666
- }
667
- for (const [name, toolDef] of this.toolRegistry) {
668
- if (!onlyDeferred || toolDef.defer_loading === true) {
669
- registry.set(name, toolDef);
670
- }
671
- }
672
- return registry;
673
- }
674
- /**
675
- * Sets the handoff context for this agent.
676
- * Call this when the agent receives control via handoff from another agent.
677
- * Marks system runnable as stale to include handoff context in system message.
678
- * @param sourceAgentName - Name of the agent that transferred control
679
- * @param parallelSiblings - Names of other agents executing in parallel with this one
680
- */
681
- setHandoffContext(sourceAgentName, parallelSiblings) {
682
- this.handoffContext = { sourceAgentName, parallelSiblings };
683
- this.systemRunnableStale = true;
684
- }
685
- /**
686
- * Clears any handoff context.
687
- * Call this when resetting the agent or when handoff context is no longer relevant.
688
- */
689
- clearHandoffContext() {
690
- if (this.handoffContext) {
691
- this.handoffContext = undefined;
692
- this.systemRunnableStale = true;
693
- }
694
- }
695
- /**
696
- * Marks tools as discovered via tool search.
697
- * Discovered tools will be included in the next model binding.
698
- * Only marks system runnable stale if NEW tools were actually added.
699
- * @param toolNames - Array of discovered tool names
700
- * @returns true if any new tools were discovered
701
- */
702
- markToolsAsDiscovered(toolNames) {
703
- let hasNewDiscoveries = false;
704
- for (const name of toolNames) {
705
- if (!this.discoveredToolNames.has(name)) {
706
- this.discoveredToolNames.add(name);
707
- hasNewDiscoveries = true;
708
- }
709
- }
710
- if (hasNewDiscoveries) {
711
- this.systemRunnableStale = true;
712
- }
713
- return hasNewDiscoveries;
714
- }
715
- /**
716
- * Gets tools that should be bound to the LLM.
717
- * In event-driven mode (toolDefinitions present, tools empty), creates schema-only tools.
718
- * Otherwise filters tool instances based on:
719
- * 1. Non-deferred tools with allowed_callers: ['direct']
720
- * 2. Discovered tools (from tool search)
721
- * @returns Array of tools to bind to model
722
- */
723
- getToolsForBinding() {
724
- /** Event-driven mode: create schema-only tools from definitions */
725
- if (this.toolDefinitions && this.toolDefinitions.length > 0) {
726
- return this.getEventDrivenToolsForBinding();
727
- }
728
- /** Traditional mode: filter actual tool instances */
729
- const filtered = !this.tools || !this.toolRegistry
730
- ? this.tools
731
- : this.filterToolsForBinding(this.tools);
732
- if (this.graphTools && this.graphTools.length > 0) {
733
- return [...(filtered ?? []), ...this.graphTools];
734
- }
735
- return filtered;
736
- }
737
- /** Creates schema-only tools from toolDefinitions for event-driven mode, merged with native tools */
738
- getEventDrivenToolsForBinding() {
739
- if (!this.toolDefinitions) {
740
- return this.graphTools ?? [];
741
- }
742
- const defsToInclude = this.toolDefinitions.filter((def) => {
743
- const allowedCallers = def.allowed_callers ?? ['direct'];
744
- if (!allowedCallers.includes('direct')) {
745
- return false;
746
- }
747
- if (def.defer_loading === true &&
748
- !this.discoveredToolNames.has(def.name)) {
749
- return false;
750
- }
751
- return true;
752
- });
753
- const schemaTools = createSchemaOnlyTools(defsToInclude);
754
- const allTools = [...schemaTools];
755
- if (this.graphTools && this.graphTools.length > 0) {
756
- allTools.push(...this.graphTools);
757
- }
758
- if (this.tools && this.tools.length > 0) {
759
- allTools.push(...this.tools);
760
- }
761
- return allTools;
762
- }
763
- /** Filters tool instances for binding based on registry config */
764
- filterToolsForBinding(tools) {
765
- return tools.filter((tool) => {
766
- if (!('name' in tool)) {
767
- return true;
768
- }
769
- const toolDef = this.toolRegistry?.get(tool.name);
770
- if (!toolDef) {
771
- return true;
772
- }
773
- if (this.discoveredToolNames.has(tool.name)) {
774
- const allowedCallers = toolDef.allowed_callers ?? ['direct'];
775
- return allowedCallers.includes('direct');
776
- }
777
- const allowedCallers = toolDef.allowed_callers ?? ['direct'];
778
- return (allowedCallers.includes('direct') && toolDef.defer_loading !== true);
779
- });
780
- }
781
- }
782
- //# sourceMappingURL=AgentContext.js.map