@illuma-ai/agents 1.1.20 → 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 (246) 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/llm/bedrock/index.cjs +14 -0
  6. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  7. package/dist/cjs/run.cjs +20 -9
  8. package/dist/cjs/run.cjs.map +1 -1
  9. package/dist/esm/graphs/Graph.mjs +12 -1
  10. package/dist/esm/graphs/Graph.mjs.map +1 -1
  11. package/dist/esm/graphs/MultiAgentGraph.mjs +85 -1
  12. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  13. package/dist/esm/llm/bedrock/index.mjs +14 -0
  14. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  15. package/dist/esm/run.mjs +20 -9
  16. package/dist/esm/run.mjs.map +1 -1
  17. package/dist/types/graphs/MultiAgentGraph.d.ts +17 -0
  18. package/package.json +1 -1
  19. package/src/graphs/Graph.ts +12 -1
  20. package/src/graphs/MultiAgentGraph.ts +105 -1
  21. package/src/graphs/__tests__/multi-agent-delegate.test.ts +191 -0
  22. package/src/llm/bedrock/index.ts +17 -0
  23. package/src/run.ts +20 -11
  24. package/src/scripts/test-bedrock-handoff-autonomous.ts +231 -0
  25. package/src/agents/AgentContext.js +0 -782
  26. package/src/agents/AgentContext.test.js +0 -421
  27. package/src/agents/__tests__/AgentContext.test.js +0 -678
  28. package/src/agents/__tests__/resolveStructuredOutputMode.test.js +0 -117
  29. package/src/common/enum.js +0 -192
  30. package/src/common/index.js +0 -3
  31. package/src/events.js +0 -166
  32. package/src/graphs/Graph.js +0 -1857
  33. package/src/graphs/MultiAgentGraph.js +0 -1092
  34. package/src/graphs/__tests__/structured-output.integration.test.js +0 -624
  35. package/src/graphs/__tests__/structured-output.test.js +0 -144
  36. package/src/graphs/contextManagement.e2e.test.js +0 -718
  37. package/src/graphs/contextManagement.test.js +0 -485
  38. package/src/graphs/handoffValidation.test.js +0 -276
  39. package/src/graphs/index.js +0 -3
  40. package/src/index.js +0 -28
  41. package/src/instrumentation.js +0 -21
  42. package/src/llm/anthropic/index.js +0 -319
  43. package/src/llm/anthropic/types.js +0 -46
  44. package/src/llm/anthropic/utils/message_inputs.js +0 -627
  45. package/src/llm/anthropic/utils/message_outputs.js +0 -290
  46. package/src/llm/anthropic/utils/output_parsers.js +0 -89
  47. package/src/llm/anthropic/utils/tools.js +0 -25
  48. package/src/llm/bedrock/__tests__/bedrock-caching.test.js +0 -392
  49. package/src/llm/bedrock/index.js +0 -303
  50. package/src/llm/bedrock/types.js +0 -2
  51. package/src/llm/bedrock/utils/index.js +0 -6
  52. package/src/llm/bedrock/utils/message_inputs.js +0 -463
  53. package/src/llm/bedrock/utils/message_outputs.js +0 -269
  54. package/src/llm/fake.js +0 -92
  55. package/src/llm/google/index.js +0 -215
  56. package/src/llm/google/types.js +0 -12
  57. package/src/llm/google/utils/common.js +0 -670
  58. package/src/llm/google/utils/tools.js +0 -111
  59. package/src/llm/google/utils/zod_to_genai_parameters.js +0 -47
  60. package/src/llm/openai/index.js +0 -1033
  61. package/src/llm/openai/types.js +0 -2
  62. package/src/llm/openai/utils/index.js +0 -756
  63. package/src/llm/openai/utils/isReasoningModel.test.js +0 -79
  64. package/src/llm/openrouter/index.js +0 -261
  65. package/src/llm/openrouter/reasoning.test.js +0 -181
  66. package/src/llm/providers.js +0 -36
  67. package/src/llm/text.js +0 -65
  68. package/src/llm/vertexai/index.js +0 -402
  69. package/src/messages/__tests__/tools.test.js +0 -392
  70. package/src/messages/cache.js +0 -404
  71. package/src/messages/cache.test.js +0 -1167
  72. package/src/messages/content.js +0 -48
  73. package/src/messages/content.test.js +0 -314
  74. package/src/messages/core.js +0 -359
  75. package/src/messages/ensureThinkingBlock.test.js +0 -997
  76. package/src/messages/format.js +0 -973
  77. package/src/messages/formatAgentMessages.test.js +0 -2278
  78. package/src/messages/formatAgentMessages.tools.test.js +0 -362
  79. package/src/messages/formatMessage.test.js +0 -608
  80. package/src/messages/ids.js +0 -18
  81. package/src/messages/index.js +0 -9
  82. package/src/messages/labelContentByAgent.test.js +0 -725
  83. package/src/messages/prune.js +0 -438
  84. package/src/messages/reducer.js +0 -60
  85. package/src/messages/shiftIndexTokenCountMap.test.js +0 -63
  86. package/src/messages/summarize.js +0 -146
  87. package/src/messages/summarize.test.js +0 -332
  88. package/src/messages/tools.js +0 -90
  89. package/src/mockStream.js +0 -81
  90. package/src/prompts/collab.js +0 -7
  91. package/src/prompts/index.js +0 -3
  92. package/src/prompts/taskmanager.js +0 -58
  93. package/src/run.js +0 -427
  94. package/src/schemas/index.js +0 -3
  95. package/src/schemas/schema-preparation.test.js +0 -370
  96. package/src/schemas/validate.js +0 -314
  97. package/src/schemas/validate.test.js +0 -264
  98. package/src/scripts/abort.js +0 -127
  99. package/src/scripts/ant_web_search.js +0 -130
  100. package/src/scripts/ant_web_search_edge_case.js +0 -133
  101. package/src/scripts/ant_web_search_error_edge_case.js +0 -119
  102. package/src/scripts/args.js +0 -41
  103. package/src/scripts/bedrock-cache-debug.js +0 -186
  104. package/src/scripts/bedrock-content-aggregation-test.js +0 -195
  105. package/src/scripts/bedrock-merge-test.js +0 -80
  106. package/src/scripts/bedrock-parallel-tools-test.js +0 -150
  107. package/src/scripts/caching.js +0 -106
  108. package/src/scripts/cli.js +0 -152
  109. package/src/scripts/cli2.js +0 -119
  110. package/src/scripts/cli3.js +0 -163
  111. package/src/scripts/cli4.js +0 -165
  112. package/src/scripts/cli5.js +0 -165
  113. package/src/scripts/code_exec.js +0 -171
  114. package/src/scripts/code_exec_files.js +0 -180
  115. package/src/scripts/code_exec_multi_session.js +0 -185
  116. package/src/scripts/code_exec_ptc.js +0 -265
  117. package/src/scripts/code_exec_session.js +0 -217
  118. package/src/scripts/code_exec_simple.js +0 -120
  119. package/src/scripts/content.js +0 -111
  120. package/src/scripts/empty_input.js +0 -125
  121. package/src/scripts/handoff-test.js +0 -96
  122. package/src/scripts/image.js +0 -138
  123. package/src/scripts/memory.js +0 -83
  124. package/src/scripts/multi-agent-chain.js +0 -271
  125. package/src/scripts/multi-agent-conditional.js +0 -185
  126. package/src/scripts/multi-agent-document-review-chain.js +0 -171
  127. package/src/scripts/multi-agent-hybrid-flow.js +0 -264
  128. package/src/scripts/multi-agent-parallel-start.js +0 -214
  129. package/src/scripts/multi-agent-parallel.js +0 -346
  130. package/src/scripts/multi-agent-sequence.js +0 -184
  131. package/src/scripts/multi-agent-supervisor.js +0 -324
  132. package/src/scripts/multi-agent-test.js +0 -147
  133. package/src/scripts/parallel-asymmetric-tools-test.js +0 -202
  134. package/src/scripts/parallel-full-metadata-test.js +0 -176
  135. package/src/scripts/parallel-tools-test.js +0 -256
  136. package/src/scripts/programmatic_exec.js +0 -277
  137. package/src/scripts/programmatic_exec_agent.js +0 -168
  138. package/src/scripts/search.js +0 -118
  139. package/src/scripts/sequential-full-metadata-test.js +0 -143
  140. package/src/scripts/simple.js +0 -174
  141. package/src/scripts/single-agent-metadata-test.js +0 -152
  142. package/src/scripts/stream.js +0 -113
  143. package/src/scripts/test-custom-prompt-key.js +0 -132
  144. package/src/scripts/test-handoff-input.js +0 -143
  145. package/src/scripts/test-handoff-preamble.js +0 -227
  146. package/src/scripts/test-handoff-steering.js +0 -353
  147. package/src/scripts/test-multi-agent-list-handoff.js +0 -318
  148. package/src/scripts/test-parallel-agent-labeling.js +0 -253
  149. package/src/scripts/test-parallel-handoffs.js +0 -229
  150. package/src/scripts/test-thinking-handoff-bedrock.js +0 -132
  151. package/src/scripts/test-thinking-handoff.js +0 -132
  152. package/src/scripts/test-thinking-to-thinking-handoff-bedrock.js +0 -140
  153. package/src/scripts/test-tool-before-handoff-role-order.js +0 -223
  154. package/src/scripts/test-tools-before-handoff.js +0 -187
  155. package/src/scripts/test_code_api.js +0 -263
  156. package/src/scripts/thinking-bedrock.js +0 -128
  157. package/src/scripts/thinking-vertexai.js +0 -130
  158. package/src/scripts/thinking.js +0 -134
  159. package/src/scripts/tool_search.js +0 -114
  160. package/src/scripts/tools.js +0 -125
  161. package/src/specs/agent-handoffs-bedrock.integration.test.js +0 -280
  162. package/src/specs/agent-handoffs.test.js +0 -924
  163. package/src/specs/anthropic.simple.test.js +0 -287
  164. package/src/specs/azure.simple.test.js +0 -381
  165. package/src/specs/cache.simple.test.js +0 -282
  166. package/src/specs/custom-event-await.test.js +0 -148
  167. package/src/specs/deepseek.simple.test.js +0 -189
  168. package/src/specs/emergency-prune.test.js +0 -308
  169. package/src/specs/moonshot.simple.test.js +0 -237
  170. package/src/specs/observability.integration.test.js +0 -1337
  171. package/src/specs/openai.simple.test.js +0 -233
  172. package/src/specs/openrouter.simple.test.js +0 -202
  173. package/src/specs/prune.test.js +0 -733
  174. package/src/specs/reasoning.test.js +0 -144
  175. package/src/specs/spec.utils.js +0 -4
  176. package/src/specs/thinking-handoff.test.js +0 -486
  177. package/src/specs/thinking-prune.test.js +0 -600
  178. package/src/specs/token-distribution-edge-case.test.js +0 -246
  179. package/src/specs/token-memoization.test.js +0 -32
  180. package/src/specs/tokens.test.js +0 -49
  181. package/src/specs/tool-error.test.js +0 -139
  182. package/src/splitStream.js +0 -204
  183. package/src/splitStream.test.js +0 -504
  184. package/src/stream.js +0 -650
  185. package/src/stream.test.js +0 -225
  186. package/src/test/mockTools.js +0 -340
  187. package/src/tools/BrowserTools.js +0 -245
  188. package/src/tools/Calculator.js +0 -38
  189. package/src/tools/Calculator.test.js +0 -225
  190. package/src/tools/CodeExecutor.js +0 -233
  191. package/src/tools/ProgrammaticToolCalling.js +0 -602
  192. package/src/tools/StreamingToolCallBuffer.js +0 -179
  193. package/src/tools/ToolNode.js +0 -930
  194. package/src/tools/ToolSearch.js +0 -904
  195. package/src/tools/__tests__/BrowserTools.test.js +0 -306
  196. package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.js +0 -276
  197. package/src/tools/__tests__/ProgrammaticToolCalling.test.js +0 -807
  198. package/src/tools/__tests__/StreamingToolCallBuffer.test.js +0 -175
  199. package/src/tools/__tests__/ToolApproval.test.js +0 -675
  200. package/src/tools/__tests__/ToolNode.recovery.test.js +0 -200
  201. package/src/tools/__tests__/ToolNode.session.test.js +0 -319
  202. package/src/tools/__tests__/ToolSearch.integration.test.js +0 -125
  203. package/src/tools/__tests__/ToolSearch.test.js +0 -812
  204. package/src/tools/__tests__/handlers.test.js +0 -799
  205. package/src/tools/__tests__/truncation-recovery.integration.test.js +0 -362
  206. package/src/tools/handlers.js +0 -306
  207. package/src/tools/schema.js +0 -25
  208. package/src/tools/search/anthropic.js +0 -34
  209. package/src/tools/search/content.js +0 -116
  210. package/src/tools/search/content.test.js +0 -133
  211. package/src/tools/search/firecrawl.js +0 -173
  212. package/src/tools/search/format.js +0 -198
  213. package/src/tools/search/highlights.js +0 -241
  214. package/src/tools/search/index.js +0 -3
  215. package/src/tools/search/jina-reranker.test.js +0 -106
  216. package/src/tools/search/rerankers.js +0 -165
  217. package/src/tools/search/schema.js +0 -102
  218. package/src/tools/search/search.js +0 -561
  219. package/src/tools/search/serper-scraper.js +0 -126
  220. package/src/tools/search/test.js +0 -129
  221. package/src/tools/search/tool.js +0 -453
  222. package/src/tools/search/types.js +0 -2
  223. package/src/tools/search/utils.js +0 -59
  224. package/src/types/graph.js +0 -24
  225. package/src/types/graph.test.js +0 -192
  226. package/src/types/index.js +0 -7
  227. package/src/types/llm.js +0 -2
  228. package/src/types/messages.js +0 -2
  229. package/src/types/run.js +0 -2
  230. package/src/types/stream.js +0 -2
  231. package/src/types/tools.js +0 -2
  232. package/src/utils/contextAnalytics.js +0 -79
  233. package/src/utils/contextAnalytics.test.js +0 -166
  234. package/src/utils/events.js +0 -26
  235. package/src/utils/graph.js +0 -11
  236. package/src/utils/handlers.js +0 -65
  237. package/src/utils/index.js +0 -10
  238. package/src/utils/llm.js +0 -21
  239. package/src/utils/llmConfig.js +0 -205
  240. package/src/utils/logging.js +0 -37
  241. package/src/utils/misc.js +0 -51
  242. package/src/utils/run.js +0 -69
  243. package/src/utils/schema.js +0 -21
  244. package/src/utils/title.js +0 -119
  245. package/src/utils/tokens.js +0 -92
  246. package/src/utils/toonFormat.js +0 -379
package/src/stream.js DELETED
@@ -1,650 +0,0 @@
1
- import { ToolCallTypes, ContentTypes, GraphEvents, StepTypes, Providers, } from '@/common';
2
- import { handleServerToolResult, handleToolCallChunks, handleToolCalls, } from '@/tools/handlers';
3
- import { getMessageId } from '@/messages';
4
- /**
5
- * Parses content to extract thinking sections enclosed in <think> tags using string operations
6
- * @param content The content to parse
7
- * @returns An object with separated text and thinking content
8
- */
9
- function parseThinkingContent(content) {
10
- // If no think tags, return the original content as text
11
- if (!content.includes('<think>')) {
12
- return { text: content, thinking: '' };
13
- }
14
- let textResult = '';
15
- const thinkingResult = [];
16
- let position = 0;
17
- while (position < content.length) {
18
- const thinkStart = content.indexOf('<think>', position);
19
- if (thinkStart === -1) {
20
- // No more think tags, add the rest and break
21
- textResult += content.slice(position);
22
- break;
23
- }
24
- // Add text before the think tag
25
- textResult += content.slice(position, thinkStart);
26
- const thinkEnd = content.indexOf('</think>', thinkStart);
27
- if (thinkEnd === -1) {
28
- // Malformed input, no closing tag
29
- textResult += content.slice(thinkStart);
30
- break;
31
- }
32
- // Add the thinking content
33
- const thinkContent = content.slice(thinkStart + 7, thinkEnd);
34
- thinkingResult.push(thinkContent);
35
- // Move position to after the think tag
36
- position = thinkEnd + 8; // 8 is the length of '</think>'
37
- }
38
- return {
39
- text: textResult.trim(),
40
- thinking: thinkingResult.join('\n').trim(),
41
- };
42
- }
43
- function getNonEmptyValue(possibleValues) {
44
- for (const value of possibleValues) {
45
- if (value && value.trim() !== '') {
46
- return value;
47
- }
48
- }
49
- return undefined;
50
- }
51
- export function getChunkContent({ chunk, provider, reasoningKey, }) {
52
- if ((provider === Providers.OPENAI || provider === Providers.AZURE) &&
53
- chunk?.additional_kwargs?.reasoning?.summary?.[0]?.text != null &&
54
- (chunk?.additional_kwargs?.reasoning?.summary?.[0]?.text?.length ?? 0) > 0) {
55
- return chunk?.additional_kwargs?.reasoning?.summary?.[0]?.text;
56
- }
57
- /**
58
- * For OpenRouter, reasoning is stored in additional_kwargs.reasoning (not reasoning_content).
59
- * NOTE: We intentionally do NOT extract text from reasoning_details here.
60
- * The reasoning_details array contains the FULL accumulated reasoning text (set only on final chunk),
61
- * but individual reasoning tokens are already streamed via additional_kwargs.reasoning.
62
- * Extracting from reasoning_details would cause duplication.
63
- * The reasoning_details is only used for:
64
- * 1. Detecting reasoning mode in handleReasoning()
65
- * 2. Final message storage (for thought signatures)
66
- */
67
- if (provider === Providers.OPENROUTER) {
68
- // Content presence signals end of reasoning phase - prefer content over reasoning
69
- // This handles transitional chunks that may have both reasoning and content
70
- if (typeof chunk?.content === 'string' && chunk.content !== '') {
71
- return chunk.content;
72
- }
73
- const reasoning = chunk?.additional_kwargs?.reasoning;
74
- if (reasoning != null && reasoning !== '') {
75
- return reasoning;
76
- }
77
- return chunk?.content;
78
- }
79
- return ((chunk?.additional_kwargs?.[reasoningKey] ?? '') ||
80
- chunk?.content);
81
- }
82
- export class ChatModelStreamHandler {
83
- async handle(event, data, metadata, graph) {
84
- if (!graph) {
85
- throw new Error('Graph not found');
86
- }
87
- if (!graph.config) {
88
- throw new Error('Config not found in graph');
89
- }
90
- if (!data.chunk) {
91
- console.warn(`No chunk found in ${event} event`);
92
- return;
93
- }
94
- const agentContext = graph.getAgentContext(metadata);
95
- const chunk = data.chunk;
96
- const content = getChunkContent({
97
- chunk,
98
- reasoningKey: agentContext.reasoningKey,
99
- provider: agentContext.provider,
100
- });
101
- const skipHandling = await handleServerToolResult({
102
- graph,
103
- content,
104
- metadata,
105
- agentContext,
106
- });
107
- if (skipHandling) {
108
- return;
109
- }
110
- this.handleReasoning(chunk, agentContext);
111
- let hasToolCalls = false;
112
- if (chunk.tool_calls &&
113
- chunk.tool_calls.length > 0 &&
114
- chunk.tool_calls.every((tc) => tc.id != null &&
115
- tc.id !== '' &&
116
- tc.name != null &&
117
- tc.name !== '')) {
118
- hasToolCalls = true;
119
- await handleToolCalls(chunk.tool_calls, metadata, graph);
120
- }
121
- const hasToolCallChunks = (chunk.tool_call_chunks && chunk.tool_call_chunks.length > 0) ?? false;
122
- const isEmptyContent = typeof content === 'undefined' ||
123
- !content.length ||
124
- (typeof content === 'string' && !content);
125
- /** Set a preliminary message ID if found in empty chunk */
126
- const isEmptyChunk = isEmptyContent && !hasToolCallChunks;
127
- if (isEmptyChunk &&
128
- (chunk.id ?? '') !== '' &&
129
- !graph.prelimMessageIdsByStepKey.has(chunk.id ?? '')) {
130
- const stepKey = graph.getStepKey(metadata);
131
- graph.prelimMessageIdsByStepKey.set(stepKey, chunk.id ?? '');
132
- }
133
- else if (isEmptyChunk) {
134
- return;
135
- }
136
- const stepKey = graph.getStepKey(metadata);
137
- if (hasToolCallChunks &&
138
- chunk.tool_call_chunks &&
139
- chunk.tool_call_chunks.length &&
140
- typeof chunk.tool_call_chunks[0]?.index === 'number') {
141
- await handleToolCallChunks({
142
- graph,
143
- stepKey,
144
- toolCallChunks: chunk.tool_call_chunks,
145
- metadata,
146
- });
147
- }
148
- if (isEmptyContent) {
149
- return;
150
- }
151
- const message_id = getMessageId(stepKey, graph) ?? '';
152
- if (message_id) {
153
- await graph.dispatchRunStep(stepKey, {
154
- type: StepTypes.MESSAGE_CREATION,
155
- message_creation: {
156
- message_id,
157
- },
158
- }, metadata);
159
- }
160
- const stepId = graph.getStepIdByKey(stepKey);
161
- const runStep = graph.getRunStep(stepId);
162
- if (!runStep) {
163
- console.warn(`\n
164
- ==============================================================
165
-
166
-
167
- Run step for ${stepId} does not exist, cannot dispatch delta event.
168
-
169
- event: ${event}
170
- stepId: ${stepId}
171
- stepKey: ${stepKey}
172
- message_id: ${message_id}
173
- hasToolCalls: ${hasToolCalls}
174
- hasToolCallChunks: ${hasToolCallChunks}
175
-
176
- ==============================================================
177
- \n`);
178
- return;
179
- }
180
- /* Note: tool call chunks may have non-empty content that matches the current tool chunk generation */
181
- if (typeof content === 'string' && runStep.type === StepTypes.TOOL_CALLS) {
182
- return;
183
- }
184
- else if (hasToolCallChunks &&
185
- (chunk.tool_call_chunks?.some((tc) => tc.args === content) ?? false)) {
186
- return;
187
- }
188
- else if (typeof content === 'string') {
189
- if (agentContext.currentTokenType === ContentTypes.TEXT) {
190
- await graph.dispatchMessageDelta(stepId, {
191
- content: [
192
- {
193
- type: ContentTypes.TEXT,
194
- text: content,
195
- },
196
- ],
197
- });
198
- }
199
- else if (agentContext.currentTokenType === 'think_and_text') {
200
- const { text, thinking } = parseThinkingContent(content);
201
- if (thinking) {
202
- await graph.dispatchReasoningDelta(stepId, {
203
- content: [
204
- {
205
- type: ContentTypes.THINK,
206
- think: thinking,
207
- },
208
- ],
209
- });
210
- }
211
- if (text) {
212
- agentContext.currentTokenType = ContentTypes.TEXT;
213
- agentContext.tokenTypeSwitch = 'content';
214
- const newStepKey = graph.getStepKey(metadata);
215
- const message_id = getMessageId(newStepKey, graph) ?? '';
216
- await graph.dispatchRunStep(newStepKey, {
217
- type: StepTypes.MESSAGE_CREATION,
218
- message_creation: {
219
- message_id,
220
- },
221
- }, metadata);
222
- const newStepId = graph.getStepIdByKey(newStepKey);
223
- await graph.dispatchMessageDelta(newStepId, {
224
- content: [
225
- {
226
- type: ContentTypes.TEXT,
227
- text: text,
228
- },
229
- ],
230
- });
231
- }
232
- }
233
- else {
234
- await graph.dispatchReasoningDelta(stepId, {
235
- content: [
236
- {
237
- type: ContentTypes.THINK,
238
- think: content,
239
- },
240
- ],
241
- });
242
- }
243
- }
244
- else if (content.every((c) => c.type?.startsWith(ContentTypes.TEXT) ?? false)) {
245
- await graph.dispatchMessageDelta(stepId, {
246
- content,
247
- });
248
- }
249
- else if (content.every((c) => (c.type?.startsWith(ContentTypes.THINKING) ?? false) ||
250
- (c.type?.startsWith(ContentTypes.REASONING) ?? false) ||
251
- (c.type?.startsWith(ContentTypes.REASONING_CONTENT) ?? false) ||
252
- c.type === 'redacted_thinking')) {
253
- await graph.dispatchReasoningDelta(stepId, {
254
- content: content.map((c) => ({
255
- type: ContentTypes.THINK,
256
- think: c.thinking ??
257
- c.reasoning ??
258
- c.reasoningText?.text ??
259
- '',
260
- })),
261
- });
262
- }
263
- }
264
- handleReasoning(chunk, agentContext) {
265
- let reasoning_content = chunk.additional_kwargs?.[agentContext.reasoningKey];
266
- if (Array.isArray(chunk.content) &&
267
- (chunk.content[0]?.type === ContentTypes.THINKING ||
268
- chunk.content[0]?.type === ContentTypes.REASONING ||
269
- chunk.content[0]?.type === ContentTypes.REASONING_CONTENT ||
270
- chunk.content[0]?.type === 'redacted_thinking')) {
271
- reasoning_content = 'valid';
272
- }
273
- else if ((agentContext.provider === Providers.OPENAI ||
274
- agentContext.provider === Providers.AZURE) &&
275
- reasoning_content != null &&
276
- typeof reasoning_content !== 'string' &&
277
- reasoning_content.summary?.[0]?.text != null &&
278
- reasoning_content.summary[0].text) {
279
- reasoning_content = 'valid';
280
- }
281
- else if (agentContext.provider === Providers.OPENROUTER &&
282
- // Only set reasoning as valid if content is NOT present (content signals end of reasoning)
283
- (chunk.content == null || chunk.content === '') &&
284
- // Check for reasoning_details (final chunk) OR reasoning string (intermediate chunks)
285
- ((chunk.additional_kwargs?.reasoning_details != null &&
286
- Array.isArray(chunk.additional_kwargs.reasoning_details) &&
287
- chunk.additional_kwargs.reasoning_details.length > 0) ||
288
- (typeof chunk.additional_kwargs?.reasoning === 'string' &&
289
- chunk.additional_kwargs.reasoning !== ''))) {
290
- reasoning_content = 'valid';
291
- }
292
- if (reasoning_content != null &&
293
- reasoning_content !== '' &&
294
- (chunk.content == null ||
295
- chunk.content === '' ||
296
- reasoning_content === 'valid')) {
297
- agentContext.currentTokenType = ContentTypes.THINK;
298
- agentContext.tokenTypeSwitch = 'reasoning';
299
- return;
300
- }
301
- else if (agentContext.tokenTypeSwitch === 'reasoning' &&
302
- agentContext.currentTokenType !== ContentTypes.TEXT &&
303
- ((chunk.content != null && chunk.content !== '') ||
304
- (chunk.tool_calls?.length ?? 0) > 0 ||
305
- (chunk.tool_call_chunks?.length ?? 0) > 0)) {
306
- agentContext.currentTokenType = ContentTypes.TEXT;
307
- agentContext.tokenTypeSwitch = 'content';
308
- agentContext.reasoningTransitionCount++;
309
- }
310
- else if (chunk.content != null &&
311
- typeof chunk.content === 'string' &&
312
- chunk.content.includes('<think>') &&
313
- chunk.content.includes('</think>')) {
314
- agentContext.currentTokenType = 'think_and_text';
315
- agentContext.tokenTypeSwitch = 'content';
316
- }
317
- else if (chunk.content != null &&
318
- typeof chunk.content === 'string' &&
319
- chunk.content.includes('<think>')) {
320
- agentContext.currentTokenType = ContentTypes.THINK;
321
- agentContext.tokenTypeSwitch = 'content';
322
- }
323
- else if (agentContext.lastToken != null &&
324
- agentContext.lastToken.includes('</think>')) {
325
- agentContext.currentTokenType = ContentTypes.TEXT;
326
- agentContext.tokenTypeSwitch = 'content';
327
- }
328
- if (typeof chunk.content !== 'string') {
329
- return;
330
- }
331
- agentContext.lastToken = chunk.content;
332
- }
333
- }
334
- export function createContentAggregator() {
335
- const contentParts = [];
336
- const stepMap = new Map();
337
- const toolCallIdMap = new Map();
338
- // Track step IDs for structured output tool calls that should be skipped
339
- const skippedStructuredOutputSteps = new Set();
340
- // Track agentId and groupId for each content index (applied to content parts)
341
- const contentMetaMap = new Map();
342
- const updateContent = (index, contentPart, finalUpdate = false) => {
343
- if (!contentPart) {
344
- console.warn('No content part found in \'updateContent\'');
345
- return;
346
- }
347
- const partType = contentPart.type ?? '';
348
- if (!partType) {
349
- console.warn('No content type found in content part');
350
- return;
351
- }
352
- if (!contentParts[index] && partType !== ContentTypes.TOOL_CALL) {
353
- contentParts[index] = { type: partType };
354
- }
355
- if (!partType.startsWith(contentParts[index]?.type ?? '')) {
356
- console.warn('Content type mismatch');
357
- return;
358
- }
359
- if (partType.startsWith(ContentTypes.TEXT) &&
360
- ContentTypes.TEXT in contentPart &&
361
- typeof contentPart.text === 'string') {
362
- // TODO: update this!!
363
- const currentContent = contentParts[index];
364
- const update = {
365
- type: ContentTypes.TEXT,
366
- text: (currentContent.text || '') + contentPart.text,
367
- };
368
- if (contentPart.tool_call_ids) {
369
- update.tool_call_ids = contentPart.tool_call_ids;
370
- }
371
- contentParts[index] = update;
372
- }
373
- else if (partType.startsWith(ContentTypes.THINK) &&
374
- ContentTypes.THINK in contentPart &&
375
- typeof contentPart.think === 'string') {
376
- const currentContent = contentParts[index];
377
- const update = {
378
- type: ContentTypes.THINK,
379
- think: (currentContent.think || '') + contentPart.think,
380
- };
381
- contentParts[index] = update;
382
- }
383
- else if (partType.startsWith(ContentTypes.AGENT_UPDATE) &&
384
- ContentTypes.AGENT_UPDATE in contentPart &&
385
- contentPart.agent_update != null) {
386
- const update = {
387
- type: ContentTypes.AGENT_UPDATE,
388
- agent_update: contentPart.agent_update,
389
- };
390
- contentParts[index] = update;
391
- }
392
- else if (partType === ContentTypes.IMAGE_URL &&
393
- 'image_url' in contentPart) {
394
- const currentContent = contentParts[index];
395
- contentParts[index] = {
396
- ...currentContent,
397
- };
398
- }
399
- else if (partType === ContentTypes.TOOL_CALL &&
400
- 'tool_call' in contentPart) {
401
- const incomingName = contentPart.tool_call.name;
402
- const incomingId = contentPart.tool_call.id;
403
- const toolCallArgs = contentPart.tool_call.args;
404
- // When we receive a tool call with a name, it's the complete tool call
405
- // Consolidate with any previously accumulated args from chunks
406
- const hasValidName = incomingName != null && incomingName !== '';
407
- const existingContent = contentParts[index];
408
- // Allow processing if:
409
- // 1. Incoming has a valid name (initial tool call setup), OR
410
- // 2. It's a final update (ON_RUN_STEP_COMPLETED), OR
411
- // 3. Existing content already has a name (delta streaming — grows args progressively)
412
- const existingHasName = existingContent?.tool_call?.name != null &&
413
- existingContent.tool_call.name !== '';
414
- if (!hasValidName && !finalUpdate && !existingHasName) {
415
- return;
416
- }
417
- /** Concatenate string args for progressive streaming; replace when object (complete).
418
- * When incoming delta has a valid name, treat as a complete replacement —
419
- * this handles the Bedrock case where handleToolCalls sends complete args
420
- * as a delta to an existing step that already has partial args from chunks. */
421
- const existingArgs = existingContent?.tool_call?.args;
422
- const existingIsEmptyObj = typeof existingArgs === 'object' &&
423
- Object.keys(existingArgs).length === 0;
424
- const existingIsString = typeof existingArgs === 'string' || existingIsEmptyObj;
425
- let args = finalUpdate ||
426
- hasValidName ||
427
- (!existingIsString && typeof existingArgs === 'object') ||
428
- typeof toolCallArgs === 'object'
429
- ? contentPart.tool_call.args
430
- : ((existingIsEmptyObj ? '' : existingArgs) ?? '') +
431
- (toolCallArgs ?? '');
432
- if (finalUpdate &&
433
- args == null &&
434
- existingContent?.tool_call?.args != null) {
435
- args = existingContent.tool_call.args;
436
- }
437
- const id = getNonEmptyValue([incomingId, existingContent?.tool_call?.id]) ?? '';
438
- const name = getNonEmptyValue([incomingName, existingContent?.tool_call?.name]) ??
439
- '';
440
- const newToolCall = {
441
- id,
442
- name,
443
- args,
444
- type: ToolCallTypes.TOOL_CALL,
445
- };
446
- if (finalUpdate) {
447
- newToolCall.progress = 1;
448
- newToolCall.output = contentPart.tool_call.output;
449
- }
450
- contentParts[index] = {
451
- type: ContentTypes.TOOL_CALL,
452
- tool_call: newToolCall,
453
- };
454
- }
455
- // Apply agentId (for MultiAgentGraph) and groupId (for parallel execution) to content parts
456
- // - agentId present → MultiAgentGraph (show agent labels)
457
- // - groupId present → parallel execution (render columns)
458
- const meta = contentMetaMap.get(index);
459
- if (meta?.agentId != null) {
460
- contentParts[index].agentId = meta.agentId;
461
- }
462
- if (meta?.groupId != null) {
463
- contentParts[index].groupId = meta.groupId;
464
- }
465
- };
466
- const aggregateContent = ({ event, data, }) => {
467
- // Handle structured output - add the JSON response as a text content part
468
- if (event === GraphEvents.ON_STRUCTURED_OUTPUT) {
469
- const structuredData = data;
470
- const contentPart = {
471
- type: ContentTypes.TEXT,
472
- text: JSON.stringify(structuredData.structuredResponse, null, 2),
473
- };
474
- // Use the next available index
475
- const nextIndex = contentParts.length;
476
- updateContent(nextIndex, contentPart);
477
- return;
478
- }
479
- if (event === GraphEvents.ON_RUN_STEP) {
480
- const runStep = data;
481
- stepMap.set(runStep.id, runStep);
482
- // Track agentId (MultiAgentGraph) and groupId (parallel execution) separately
483
- // - agentId: present for all MultiAgentGraph runs (enables agent labels in UI)
484
- // - groupId: present only for parallel execution (enables column rendering)
485
- const hasAgentId = runStep.agentId != null && runStep.agentId !== '';
486
- const hasGroupId = runStep.groupId != null;
487
- if (hasAgentId || hasGroupId) {
488
- const existingMeta = contentMetaMap.get(runStep.index) ?? {};
489
- if (hasAgentId) {
490
- existingMeta.agentId = runStep.agentId;
491
- }
492
- if (hasGroupId) {
493
- existingMeta.groupId = runStep.groupId;
494
- }
495
- contentMetaMap.set(runStep.index, existingMeta);
496
- }
497
- // Store tool call IDs if present
498
- if (runStep.stepDetails.type === StepTypes.TOOL_CALLS &&
499
- runStep.stepDetails.tool_calls) {
500
- // Check if ALL tool calls are structured output tool calls
501
- const toolCalls = runStep.stepDetails.tool_calls;
502
- const allAreStructuredOutput = toolCalls.length > 0 &&
503
- toolCalls.every((toolCall) => {
504
- const toolName = toolCall.name.toLowerCase();
505
- return (toolName === 'response' ||
506
- toolName === 'structuredresponse' ||
507
- toolName === 'structured_response');
508
- });
509
- // If all tool calls are structured output, skip this entire step
510
- if (allAreStructuredOutput) {
511
- skippedStructuredOutputSteps.add(runStep.id);
512
- return;
513
- }
514
- // When tool_calls is empty (Bedrock sends name/args only at model end),
515
- // initialize a placeholder so contentParts[index] is not null.
516
- // ON_RUN_STEP_COMPLETED or ON_RUN_STEP_DELTA will fill in the real data.
517
- if (toolCalls.length === 0) {
518
- contentParts[runStep.index] = {
519
- type: ContentTypes.TOOL_CALL,
520
- tool_call: {
521
- args: '',
522
- name: '',
523
- id: '',
524
- type: ToolCallTypes.TOOL_CALL,
525
- },
526
- };
527
- }
528
- toolCalls.forEach((toolCall) => {
529
- // Skip structured output tool calls - these are synthetic tool calls
530
- // used by withStructuredOutput() to extract JSON, not real tools
531
- const toolName = toolCall.name.toLowerCase();
532
- if (toolName === 'response' ||
533
- toolName === 'structuredresponse' ||
534
- toolName === 'structured_response') {
535
- return;
536
- }
537
- const toolCallId = toolCall.id ?? '';
538
- if ('id' in toolCall && toolCallId) {
539
- toolCallIdMap.set(runStep.id, toolCallId);
540
- }
541
- const contentPart = {
542
- type: ContentTypes.TOOL_CALL,
543
- tool_call: {
544
- args: toolCall.args,
545
- name: toolCall.name,
546
- id: toolCallId,
547
- },
548
- };
549
- updateContent(runStep.index, contentPart);
550
- });
551
- }
552
- }
553
- else if (event === GraphEvents.ON_MESSAGE_DELTA) {
554
- const messageDelta = data;
555
- const runStep = stepMap.get(messageDelta.id);
556
- if (!runStep) {
557
- console.warn('No run step or runId found for message delta event');
558
- return;
559
- }
560
- if (messageDelta.delta.content) {
561
- const contentPart = Array.isArray(messageDelta.delta.content)
562
- ? messageDelta.delta.content[0]
563
- : messageDelta.delta.content;
564
- updateContent(runStep.index, contentPart);
565
- }
566
- }
567
- else if (event === GraphEvents.ON_AGENT_UPDATE &&
568
- data?.agent_update) {
569
- const contentPart = data;
570
- if (!contentPart) {
571
- return;
572
- }
573
- updateContent(contentPart.agent_update.index, contentPart);
574
- }
575
- else if (event === GraphEvents.ON_REASONING_DELTA) {
576
- const reasoningDelta = data;
577
- const runStep = stepMap.get(reasoningDelta.id);
578
- if (!runStep) {
579
- console.warn('No run step or runId found for reasoning delta event');
580
- return;
581
- }
582
- if (reasoningDelta.delta.content) {
583
- const contentPart = Array.isArray(reasoningDelta.delta.content)
584
- ? reasoningDelta.delta.content[0]
585
- : reasoningDelta.delta.content;
586
- updateContent(runStep.index, contentPart);
587
- }
588
- }
589
- else if (event === GraphEvents.ON_RUN_STEP_DELTA) {
590
- const runStepDelta = data;
591
- // Skip deltas for structured output tool calls
592
- if (skippedStructuredOutputSteps.has(runStepDelta.id)) {
593
- return;
594
- }
595
- const runStep = stepMap.get(runStepDelta.id);
596
- if (!runStep) {
597
- console.warn('No run step or runId found for run step delta event');
598
- return;
599
- }
600
- if (runStepDelta.delta.type === StepTypes.TOOL_CALLS &&
601
- runStepDelta.delta.tool_calls) {
602
- runStepDelta.delta.tool_calls.forEach((toolCallDelta) => {
603
- /** Use toolCallIdMap first; fall back to the delta's own id
604
- * (Bedrock sends complete tool call data as a delta via handleToolCalls,
605
- * which includes the id, but the map was never populated because
606
- * the initial on_run_step had tool_calls: []) */
607
- const toolCallId = toolCallIdMap.get(runStepDelta.id) ??
608
- (toolCallDelta.id != null && toolCallDelta.id !== ''
609
- ? toolCallDelta.id
610
- : undefined);
611
- // Store the mapping for future lookups (e.g. on_run_step_completed)
612
- if (toolCallId != null &&
613
- toolCallId !== '' &&
614
- !toolCallIdMap.has(runStepDelta.id)) {
615
- toolCallIdMap.set(runStepDelta.id, toolCallId);
616
- }
617
- const contentPart = {
618
- type: ContentTypes.TOOL_CALL,
619
- tool_call: {
620
- args: toolCallDelta.args ?? '',
621
- name: toolCallDelta.name,
622
- id: toolCallId,
623
- },
624
- };
625
- updateContent(runStep.index, contentPart);
626
- });
627
- }
628
- }
629
- else if (event === GraphEvents.ON_RUN_STEP_COMPLETED) {
630
- const { result } = data;
631
- const { id: stepId } = result;
632
- // Skip completion events for structured output tool calls
633
- if (skippedStructuredOutputSteps.has(stepId)) {
634
- return;
635
- }
636
- const runStep = stepMap.get(stepId);
637
- if (!runStep) {
638
- console.warn('No run step or runId found for completed tool call event');
639
- return;
640
- }
641
- const contentPart = {
642
- type: ContentTypes.TOOL_CALL,
643
- tool_call: result.tool_call,
644
- };
645
- updateContent(runStep.index, contentPart, true);
646
- }
647
- };
648
- return { contentParts, aggregateContent, stepMap };
649
- }
650
- //# sourceMappingURL=stream.js.map