@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
@@ -1,504 +0,0 @@
1
- import { nanoid } from 'nanoid';
2
- import { GraphEvents, StepTypes, ContentTypes } from '@/common';
3
- import { createContentAggregator } from './stream';
4
- import { SplitStreamHandler } from './splitStream';
5
- import { createMockStream } from './mockStream';
6
- // Mock sleep to speed up tests
7
- jest.mock('@/utils', () => ({
8
- sleep: () => Promise.resolve(),
9
- }));
10
- describe('Stream Generation and Handling', () => {
11
- let mockHandlers;
12
- beforeEach(() => {
13
- mockHandlers = {
14
- [GraphEvents.ON_RUN_STEP]: jest.fn(),
15
- [GraphEvents.ON_MESSAGE_DELTA]: jest.fn(),
16
- };
17
- });
18
- it('should properly stream tokens including spaces', async () => {
19
- const stream = createMockStream({
20
- text: 'Hello world!',
21
- streamRate: 0,
22
- })();
23
- const tokens = [];
24
- for await (const chunk of stream) {
25
- const content = chunk.choices?.[0]?.delta.content ?? '';
26
- if (content)
27
- tokens.push(content);
28
- }
29
- expect(tokens).toEqual(['Hello', ' ', 'world!']);
30
- });
31
- it('should handle code blocks without splitting them', async () => {
32
- const runId = nanoid();
33
- const handler = new SplitStreamHandler({
34
- runId,
35
- blockThreshold: 10,
36
- handlers: mockHandlers,
37
- });
38
- const codeText = `Code:
39
- \`\`\`
40
- const x = 1;
41
- const y = 2;
42
- const z = 2;
43
- const a = 2;
44
- const b = 2;
45
- const c = 2;
46
- const d = 2;
47
- const e = 2;
48
- const f = 2;
49
- const g = 2;
50
- const h = 2;
51
- \`\`\`
52
- End code.`;
53
- const stream = createMockStream({
54
- text: codeText,
55
- streamRate: 0,
56
- })();
57
- for await (const chunk of stream) {
58
- handler.handle(chunk);
59
- }
60
- // Verify that only one message block was created for the code section
61
- const runSteps = mockHandlers[GraphEvents.ON_RUN_STEP].mock.calls;
62
- expect(runSteps.length).toBe(2); // Should only create one message block
63
- });
64
- it('should split content when exceeding threshold', async () => {
65
- const runId = nanoid();
66
- const handler = new SplitStreamHandler({
67
- runId,
68
- handlers: mockHandlers,
69
- // Set a very low threshold for testing
70
- blockThreshold: 10,
71
- });
72
- // Make the text longer and ensure it has clear breaking points
73
- const longText = 'This is the first sentence. And here is another sentence. And yet another one here. Finally one more.';
74
- const stream = createMockStream({
75
- text: longText,
76
- streamRate: 0,
77
- })();
78
- // For debugging
79
- // let totalLength = 0;
80
- for await (const chunk of stream) {
81
- handler.handle(chunk);
82
- // For debugging
83
- // const content = chunk.choices?.[0]?.delta.content;
84
- // if (content) {
85
- // totalLength += content.length;
86
- // console.log(`Current length: ${totalLength}, Content: "${content}"`);
87
- // }
88
- }
89
- // Verify multiple message blocks were created
90
- const runSteps = mockHandlers[GraphEvents.ON_RUN_STEP].mock.calls;
91
- // console.log('Number of run steps:', runSteps.length);
92
- expect(runSteps.length).toEqual(handler.currentIndex + 1);
93
- });
94
- it('should handle reasoning text separately', async () => {
95
- const runId = nanoid();
96
- new SplitStreamHandler({
97
- runId,
98
- handlers: mockHandlers,
99
- });
100
- const stream = createMockStream({
101
- text: 'Main content',
102
- reasoningText: 'Reasoning text',
103
- streamRate: 0,
104
- })();
105
- const reasoningTokens = [];
106
- const contentTokens = [];
107
- for await (const chunk of stream) {
108
- const reasoning = chunk.choices?.[0]?.delta.reasoning_content ?? '';
109
- const content = chunk.choices?.[0]?.delta.content ?? '';
110
- if (reasoning)
111
- reasoningTokens.push(reasoning);
112
- if (content)
113
- contentTokens.push(content);
114
- }
115
- expect(reasoningTokens.length).toBeGreaterThan(0);
116
- expect(contentTokens.length).toBeGreaterThan(0);
117
- });
118
- it('should preserve empty strings and whitespace', async () => {
119
- const stream = createMockStream({
120
- text: 'Hello world', // Note double space
121
- streamRate: 0,
122
- })();
123
- const tokens = [];
124
- for await (const chunk of stream) {
125
- const content = chunk.choices?.[0]?.delta.content ?? '';
126
- if (!content) {
127
- return;
128
- }
129
- tokens.push(content);
130
- }
131
- expect(tokens).toContain(' ');
132
- expect(tokens.join('')).toBe('Hello world');
133
- });
134
- });
135
- describe('ContentAggregator with SplitStreamHandler', () => {
136
- it('should aggregate content from multiple message blocks', async () => {
137
- const runId = nanoid();
138
- const { contentParts, aggregateContent } = createContentAggregator();
139
- const handler = new SplitStreamHandler({
140
- runId,
141
- handlers: {
142
- [GraphEvents.ON_RUN_STEP]: aggregateContent,
143
- [GraphEvents.ON_MESSAGE_DELTA]: aggregateContent,
144
- },
145
- blockThreshold: 5,
146
- });
147
- const text = 'First sentence. Second sentence. Third sentence.';
148
- const stream = createMockStream({ text, streamRate: 0 })();
149
- for await (const chunk of stream) {
150
- handler.handle(chunk);
151
- }
152
- expect(contentParts.length).toBeGreaterThan(0);
153
- contentParts.forEach((part) => {
154
- expect(part?.type).toBe(ContentTypes.TEXT);
155
- if (part?.type === ContentTypes.TEXT) {
156
- expect(typeof part.text).toBe('string');
157
- expect(part.text.length).toBeGreaterThan(0);
158
- }
159
- });
160
- const fullText = contentParts
161
- .filter((part) => part?.type === ContentTypes.TEXT)
162
- .map((part) => (part?.type === ContentTypes.TEXT ? part.text : ''))
163
- .join('');
164
- expect(fullText).toBe(text);
165
- });
166
- it('should maintain content order across splits', async () => {
167
- const runId = nanoid();
168
- const { contentParts, aggregateContent } = createContentAggregator();
169
- const handler = new SplitStreamHandler({
170
- runId,
171
- handlers: {
172
- [GraphEvents.ON_RUN_STEP]: aggregateContent,
173
- [GraphEvents.ON_MESSAGE_DELTA]: aggregateContent,
174
- },
175
- blockThreshold: 15,
176
- });
177
- const text = 'First part. Second part. Third part.';
178
- const stream = createMockStream({ text, streamRate: 0 })();
179
- for await (const chunk of stream) {
180
- handler.handle(chunk);
181
- }
182
- const texts = contentParts
183
- .filter((part) => part?.type === ContentTypes.TEXT)
184
- .map((part) => (part?.type === ContentTypes.TEXT ? part.text : ''));
185
- expect(texts[0]).toContain('First');
186
- expect(texts[texts.length - 1]).toContain('Third');
187
- });
188
- it('should handle code blocks as single content parts', async () => {
189
- const runId = nanoid();
190
- const { contentParts, aggregateContent } = createContentAggregator();
191
- const handler = new SplitStreamHandler({
192
- runId,
193
- handlers: {
194
- [GraphEvents.ON_RUN_STEP]: aggregateContent,
195
- [GraphEvents.ON_MESSAGE_DELTA]: aggregateContent,
196
- },
197
- blockThreshold: 10,
198
- });
199
- const text = `Before code.
200
- \`\`\`python
201
- def test():
202
- return True
203
- \`\`\`
204
- After code.`;
205
- const stream = createMockStream({ text, streamRate: 0 })();
206
- for await (const chunk of stream) {
207
- handler.handle(chunk);
208
- }
209
- const codeBlockPart = contentParts.find((part) => part?.type === ContentTypes.TEXT && part.text.includes('```python'));
210
- expect(codeBlockPart).toBeDefined();
211
- if (codeBlockPart?.type === ContentTypes.TEXT) {
212
- expect(codeBlockPart.text).toContain('def test()');
213
- expect(codeBlockPart.text).toContain('return True');
214
- }
215
- });
216
- it('should properly map steps to their content', async () => {
217
- const runId = nanoid();
218
- const { contentParts, aggregateContent, stepMap } = createContentAggregator();
219
- const handler = new SplitStreamHandler({
220
- runId,
221
- handlers: {
222
- [GraphEvents.ON_RUN_STEP]: aggregateContent,
223
- [GraphEvents.ON_MESSAGE_DELTA]: aggregateContent,
224
- },
225
- blockThreshold: 5,
226
- });
227
- const text = 'Hi. Ok. Yes.';
228
- const stream = createMockStream({ text, streamRate: 0 })();
229
- for await (const chunk of stream) {
230
- handler.handle(chunk);
231
- }
232
- Array.from(stepMap.entries()).forEach(([_stepId, step]) => {
233
- expect(step?.type).toBe(StepTypes.MESSAGE_CREATION);
234
- const currentIndex = step?.index ?? -1;
235
- const stepContent = contentParts[currentIndex];
236
- if (!stepContent && currentIndex > 0) {
237
- const prevStepContent = contentParts[currentIndex - 1];
238
- expect(prevStepContent?.text).toEqual(text);
239
- }
240
- else if (stepContent?.type === ContentTypes.TEXT) {
241
- expect(stepContent.text.length).toBeGreaterThan(0);
242
- }
243
- });
244
- contentParts.forEach((part, index) => {
245
- const hasMatchingStep = Array.from(stepMap.values()).some((step) => step?.index === index);
246
- expect(hasMatchingStep).toBe(true);
247
- });
248
- });
249
- it('should aggregate content across multiple splits while preserving order', async () => {
250
- const runId = nanoid();
251
- const { contentParts, aggregateContent } = createContentAggregator();
252
- const handler = new SplitStreamHandler({
253
- runId,
254
- handlers: {
255
- [GraphEvents.ON_RUN_STEP]: aggregateContent,
256
- [GraphEvents.ON_MESSAGE_DELTA]: aggregateContent,
257
- },
258
- blockThreshold: 10,
259
- });
260
- const text = 'A. B. C. D. E. F.';
261
- const stream = createMockStream({ text, streamRate: 0 })();
262
- for await (const chunk of stream) {
263
- handler.handle(chunk);
264
- }
265
- const letters = ['A', 'B', 'C', 'D', 'E', 'F'];
266
- let letterIndex = 0;
267
- contentParts.forEach((part) => {
268
- if (part?.type === ContentTypes.TEXT) {
269
- while (letterIndex < letters.length &&
270
- part.text.includes(letters[letterIndex]) === true) {
271
- letterIndex++;
272
- }
273
- }
274
- });
275
- expect(letterIndex).toBe(letters.length);
276
- });
277
- });
278
- describe('SplitStreamHandler with Reasoning Tokens', () => {
279
- it('should apply same splitting rules to both content types', async () => {
280
- const runId = nanoid();
281
- const mockHandlers = {
282
- [GraphEvents.ON_RUN_STEP]: jest.fn(),
283
- [GraphEvents.ON_MESSAGE_DELTA]: jest.fn(),
284
- [GraphEvents.ON_REASONING_DELTA]: jest.fn(),
285
- };
286
- const handler = new SplitStreamHandler({
287
- runId,
288
- handlers: mockHandlers,
289
- blockThreshold: 3,
290
- });
291
- const stream = createMockStream({
292
- text: 'First text. Second text. Third text.',
293
- reasoningText: 'First thought. Second thought. Third thought.',
294
- streamRate: 0,
295
- })();
296
- for await (const chunk of stream) {
297
- handler.handle(chunk);
298
- }
299
- const runSteps = mockHandlers[GraphEvents.ON_RUN_STEP].mock
300
- .calls;
301
- const reasoningDeltas = mockHandlers[GraphEvents.ON_REASONING_DELTA].mock.calls;
302
- const messageDeltas = mockHandlers[GraphEvents.ON_MESSAGE_DELTA].mock.calls;
303
- // Both content types should create multiple blocks
304
- expect(runSteps.length).toBeGreaterThan(1);
305
- expect(reasoningDeltas.length).toBeGreaterThan(0);
306
- expect(messageDeltas.length).toBeGreaterThan(0);
307
- // Verify splitting behavior for both types
308
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
309
- const getStepTypes = (calls) => calls
310
- .map(([{ data }]) => data.stepDetails?.type === StepTypes.MESSAGE_CREATION
311
- ? data.stepDetails.message_creation.message_id
312
- : null)
313
- .filter(Boolean);
314
- const messageSteps = getStepTypes(runSteps);
315
- expect(new Set(messageSteps).size).toBeGreaterThan(1);
316
- });
317
- it('should properly map steps to their reasoning content', async () => {
318
- const runId = nanoid();
319
- const { contentParts, aggregateContent, stepMap } = createContentAggregator();
320
- const handler = new SplitStreamHandler({
321
- runId,
322
- handlers: {
323
- [GraphEvents.ON_RUN_STEP]: aggregateContent,
324
- [GraphEvents.ON_MESSAGE_DELTA]: aggregateContent,
325
- [GraphEvents.ON_REASONING_DELTA]: aggregateContent,
326
- },
327
- blockThreshold: 5,
328
- });
329
- const text = 'Main content.';
330
- const reasoningText = 'First thought. Second thought. Third thought.';
331
- const stream = createMockStream({
332
- text,
333
- reasoningText,
334
- streamRate: 0,
335
- })();
336
- for await (const chunk of stream) {
337
- handler.handle(chunk);
338
- }
339
- Array.from(stepMap.entries()).forEach(([_stepId, step]) => {
340
- expect(step?.type).toBe(StepTypes.MESSAGE_CREATION);
341
- const currentIndex = step?.index ?? -1;
342
- const stepContent = contentParts[currentIndex];
343
- if (stepContent?.type === ContentTypes.THINK) {
344
- // Verify reasoning content structure
345
- expect(stepContent).toHaveProperty('think');
346
- expect(typeof stepContent.think).toBe('string');
347
- expect(stepContent.think.length).toBeGreaterThan(0);
348
- }
349
- });
350
- // Verify at least one reasoning content part exists
351
- const reasoningParts = contentParts.filter((part) => part?.type === ContentTypes.THINK);
352
- expect(reasoningParts.length).toBeGreaterThan(0);
353
- // Verify the content order (reasoning should come before main content)
354
- const contentTypes = contentParts
355
- .filter((part) => part !== undefined)
356
- .map((part) => part.type);
357
- expect(contentTypes).toContain(ContentTypes.THINK);
358
- expect(contentTypes).toContain(ContentTypes.TEXT);
359
- // Verify the complete reasoning content is preserved
360
- const fullReasoningText = reasoningParts
361
- .map((part) => (part?.type === ContentTypes.THINK ? part.think : ''))
362
- .join('');
363
- expect(fullReasoningText).toBe(reasoningText);
364
- });
365
- });
366
- describe('SplitStreamHandler', () => {
367
- it('should handle think blocks correctly', async () => {
368
- const runId = nanoid();
369
- const messageDeltaEvents = [];
370
- const reasoningDeltaEvents = [];
371
- const streamHandler = new SplitStreamHandler({
372
- runId,
373
- handlers: {
374
- [GraphEvents.ON_MESSAGE_DELTA]: ({ data }) => {
375
- messageDeltaEvents.push(data);
376
- },
377
- [GraphEvents.ON_REASONING_DELTA]: ({ data }) => {
378
- reasoningDeltaEvents.push(data);
379
- },
380
- },
381
- });
382
- const content = 'Here\'s some regular text. <think>Now I\'m thinking deeply about something important. This should all be reasoning.</think> Back to regular text.';
383
- const stream = createMockStream({
384
- text: content,
385
- streamRate: 5,
386
- })();
387
- for await (const chunk of stream) {
388
- streamHandler.handle(chunk);
389
- }
390
- // Check that content before <think> was handled as regular text
391
- expect(messageDeltaEvents.some((event) => event.delta.content?.[0]?.text.includes('Here\'s'))).toBe(true);
392
- // Check that <think> tag was handled as reasoning
393
- expect(reasoningDeltaEvents.some((event) => event.delta.content?.[0]?.think.includes('<think>'))).toBe(true);
394
- // Check that content inside <think> tags was handled as reasoning
395
- expect(reasoningDeltaEvents.some((event) => event.delta.content?.[0]?.think.includes('thinking'))).toBe(true);
396
- // Check that </think> tag was handled as reasoning
397
- expect(reasoningDeltaEvents.some((event) => event.delta.content?.[0]?.think.includes('</think>'))).toBe(true);
398
- // Check that content after </think> was handled as regular text
399
- expect(messageDeltaEvents.some((event) => event.delta.content?.[0]?.text.includes('Back'))).toBe(true);
400
- });
401
- it('should ignore think tags inside code blocks', async () => {
402
- const runId = nanoid();
403
- const messageDeltaEvents = [];
404
- const reasoningDeltaEvents = [];
405
- const streamHandler = new SplitStreamHandler({
406
- runId,
407
- handlers: {
408
- [GraphEvents.ON_MESSAGE_DELTA]: ({ data }) => {
409
- messageDeltaEvents.push(data);
410
- },
411
- [GraphEvents.ON_REASONING_DELTA]: ({ data }) => {
412
- reasoningDeltaEvents.push(data);
413
- },
414
- },
415
- });
416
- const content = 'Regular text. ```<think>This should stay as code</think>``` More text.';
417
- const stream = createMockStream({
418
- text: content,
419
- streamRate: 5,
420
- })();
421
- for await (const chunk of stream) {
422
- streamHandler.handle(chunk);
423
- }
424
- // Check that think tags inside code blocks were treated as regular text
425
- expect(messageDeltaEvents.some((event) => event.delta.content?.[0]?.text.includes('Regular'))).toBe(true);
426
- // Verify no reasoning events were generated
427
- expect(reasoningDeltaEvents.length).toBe(0);
428
- });
429
- it('should properly split content with think tags while maintaining context', async () => {
430
- const runId = nanoid();
431
- const messageDeltaEvents = [];
432
- const reasoningDeltaEvents = [];
433
- const runStepEvents = [];
434
- const { contentParts, aggregateContent } = createContentAggregator();
435
- const streamHandler = new SplitStreamHandler({
436
- runId,
437
- blockThreshold: 20, // Small threshold to force splits
438
- handlers: {
439
- [GraphEvents.ON_MESSAGE_DELTA]: (event) => {
440
- messageDeltaEvents.push(event.data);
441
- aggregateContent(event);
442
- },
443
- [GraphEvents.ON_REASONING_DELTA]: (event) => {
444
- reasoningDeltaEvents.push(event.data);
445
- aggregateContent(event);
446
- },
447
- [GraphEvents.ON_RUN_STEP]: (event) => {
448
- runStepEvents.push(event.data);
449
- aggregateContent(event);
450
- },
451
- },
452
- });
453
- const content = 'Here\'s some regular text. <think>Now I\'m thinking deeply about something important. This is a long thought that should be split into multiple parts. We want to ensure the splitting works correctly.</think> Back to regular text after thinking.';
454
- const stream = createMockStream({
455
- text: content,
456
- streamRate: 5,
457
- })();
458
- for await (const chunk of stream) {
459
- streamHandler.handle(chunk);
460
- }
461
- // Verify that multiple message blocks were created
462
- expect(runStepEvents.length).toBeGreaterThan(2);
463
- // Check that content before <think> was handled as regular text
464
- expect(messageDeltaEvents.some((event) => event.delta.content?.[0]?.text.includes('regular'))).toBe(true);
465
- // Verify that reasoning content was split into multiple parts
466
- const reasoningParts = reasoningDeltaEvents
467
- .map((event) => event.delta.content?.[0]
468
- ?.think)
469
- .filter(Boolean);
470
- expect(reasoningParts.length).toBeGreaterThan(1);
471
- // Verify that the complete reasoning content is preserved when joined
472
- const fullReasoningContent = reasoningParts.join('');
473
- expect(fullReasoningContent).toContain('thinking');
474
- expect(fullReasoningContent).toContain('should');
475
- expect(fullReasoningContent).toContain('be');
476
- expect(fullReasoningContent).toContain('split');
477
- // Check that each reasoning part maintains proper think context
478
- let seenThinkOpen = false;
479
- let seenThinkClose = false;
480
- reasoningParts.forEach((part) => {
481
- if (part == null)
482
- return;
483
- if (part.includes('<think>')) {
484
- seenThinkOpen = true;
485
- }
486
- if (part.includes('</think>')) {
487
- seenThinkClose = true;
488
- }
489
- // Middle parts should be handled as reasoning even without explicit think tags
490
- if (!part.includes('<think>') && !part.includes('</think>')) {
491
- expect(reasoningDeltaEvents.some((event) => event.delta.content?.[0]
492
- ?.think === part)).toBe(true);
493
- }
494
- });
495
- expect(seenThinkOpen).toBe(true);
496
- expect(seenThinkClose).toBe(true);
497
- // Check that content after </think> was handled as regular text
498
- expect(messageDeltaEvents.some((event) => event.delta.content?.[0]?.text.includes('Back'))).toBe(true);
499
- const thinkingBlocks = contentParts.filter((part) => part?.type === ContentTypes.THINK);
500
- expect(thinkingBlocks.length).toBeGreaterThan(0);
501
- expect(thinkingBlocks[0].think.startsWith('<think>')).toBeTruthy();
502
- });
503
- });
504
- //# sourceMappingURL=splitStream.test.js.map