illuma-agents 1.0.7 → 1.0.9

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 (237) hide show
  1. package/LICENSE +1 -5
  2. package/dist/cjs/common/enum.cjs +1 -2
  3. package/dist/cjs/common/enum.cjs.map +1 -1
  4. package/dist/cjs/instrumentation.cjs.map +1 -1
  5. package/dist/cjs/llm/anthropic/types.cjs.map +1 -1
  6. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +79 -2
  7. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  8. package/dist/cjs/llm/anthropic/utils/tools.cjs.map +1 -1
  9. package/dist/cjs/llm/bedrock/index.cjs +99 -0
  10. package/dist/cjs/llm/bedrock/index.cjs.map +1 -0
  11. package/dist/cjs/llm/fake.cjs.map +1 -1
  12. package/dist/cjs/llm/google/index.cjs +78 -9
  13. package/dist/cjs/llm/google/index.cjs.map +1 -1
  14. package/dist/cjs/llm/google/utils/common.cjs +185 -28
  15. package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
  16. package/dist/cjs/llm/providers.cjs +13 -16
  17. package/dist/cjs/llm/providers.cjs.map +1 -1
  18. package/dist/cjs/llm/text.cjs.map +1 -1
  19. package/dist/cjs/messages/core.cjs +14 -14
  20. package/dist/cjs/messages/core.cjs.map +1 -1
  21. package/dist/cjs/messages/ids.cjs.map +1 -1
  22. package/dist/cjs/messages/prune.cjs.map +1 -1
  23. package/dist/cjs/run.cjs +10 -1
  24. package/dist/cjs/run.cjs.map +1 -1
  25. package/dist/cjs/splitStream.cjs.map +1 -1
  26. package/dist/cjs/stream.cjs +4 -1
  27. package/dist/cjs/stream.cjs.map +1 -1
  28. package/dist/cjs/tools/ToolNode.cjs +163 -55
  29. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  30. package/dist/cjs/tools/handlers.cjs +29 -25
  31. package/dist/cjs/tools/handlers.cjs.map +1 -1
  32. package/dist/cjs/tools/search/anthropic.cjs.map +1 -1
  33. package/dist/cjs/tools/search/content.cjs.map +1 -1
  34. package/dist/cjs/tools/search/firecrawl.cjs.map +1 -1
  35. package/dist/cjs/tools/search/format.cjs.map +1 -1
  36. package/dist/cjs/tools/search/highlights.cjs.map +1 -1
  37. package/dist/cjs/tools/search/rerankers.cjs.map +1 -1
  38. package/dist/cjs/tools/search/schema.cjs +25 -25
  39. package/dist/cjs/tools/search/schema.cjs.map +1 -1
  40. package/dist/cjs/tools/search/search.cjs +6 -1
  41. package/dist/cjs/tools/search/search.cjs.map +1 -1
  42. package/dist/cjs/tools/search/serper-scraper.cjs.map +1 -1
  43. package/dist/cjs/tools/search/tool.cjs +162 -35
  44. package/dist/cjs/tools/search/tool.cjs.map +1 -1
  45. package/dist/cjs/tools/search/utils.cjs.map +1 -1
  46. package/dist/cjs/utils/graph.cjs.map +1 -1
  47. package/dist/cjs/utils/llm.cjs +0 -1
  48. package/dist/cjs/utils/llm.cjs.map +1 -1
  49. package/dist/cjs/utils/misc.cjs.map +1 -1
  50. package/dist/cjs/utils/run.cjs.map +1 -1
  51. package/dist/cjs/utils/title.cjs +7 -7
  52. package/dist/cjs/utils/title.cjs.map +1 -1
  53. package/dist/esm/common/enum.mjs +1 -2
  54. package/dist/esm/common/enum.mjs.map +1 -1
  55. package/dist/esm/instrumentation.mjs.map +1 -1
  56. package/dist/esm/llm/anthropic/types.mjs.map +1 -1
  57. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +79 -2
  58. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  59. package/dist/esm/llm/anthropic/utils/tools.mjs.map +1 -1
  60. package/dist/esm/llm/bedrock/index.mjs +97 -0
  61. package/dist/esm/llm/bedrock/index.mjs.map +1 -0
  62. package/dist/esm/llm/fake.mjs.map +1 -1
  63. package/dist/esm/llm/google/index.mjs +79 -10
  64. package/dist/esm/llm/google/index.mjs.map +1 -1
  65. package/dist/esm/llm/google/utils/common.mjs +184 -30
  66. package/dist/esm/llm/google/utils/common.mjs.map +1 -1
  67. package/dist/esm/llm/providers.mjs +2 -5
  68. package/dist/esm/llm/providers.mjs.map +1 -1
  69. package/dist/esm/llm/text.mjs.map +1 -1
  70. package/dist/esm/messages/core.mjs +14 -14
  71. package/dist/esm/messages/core.mjs.map +1 -1
  72. package/dist/esm/messages/ids.mjs.map +1 -1
  73. package/dist/esm/messages/prune.mjs.map +1 -1
  74. package/dist/esm/run.mjs +10 -1
  75. package/dist/esm/run.mjs.map +1 -1
  76. package/dist/esm/splitStream.mjs.map +1 -1
  77. package/dist/esm/stream.mjs +4 -1
  78. package/dist/esm/stream.mjs.map +1 -1
  79. package/dist/esm/tools/ToolNode.mjs +164 -56
  80. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  81. package/dist/esm/tools/handlers.mjs +30 -26
  82. package/dist/esm/tools/handlers.mjs.map +1 -1
  83. package/dist/esm/tools/search/anthropic.mjs.map +1 -1
  84. package/dist/esm/tools/search/content.mjs.map +1 -1
  85. package/dist/esm/tools/search/firecrawl.mjs.map +1 -1
  86. package/dist/esm/tools/search/format.mjs.map +1 -1
  87. package/dist/esm/tools/search/highlights.mjs.map +1 -1
  88. package/dist/esm/tools/search/rerankers.mjs.map +1 -1
  89. package/dist/esm/tools/search/schema.mjs +25 -25
  90. package/dist/esm/tools/search/schema.mjs.map +1 -1
  91. package/dist/esm/tools/search/search.mjs +6 -1
  92. package/dist/esm/tools/search/search.mjs.map +1 -1
  93. package/dist/esm/tools/search/serper-scraper.mjs.map +1 -1
  94. package/dist/esm/tools/search/tool.mjs +162 -35
  95. package/dist/esm/tools/search/tool.mjs.map +1 -1
  96. package/dist/esm/tools/search/utils.mjs.map +1 -1
  97. package/dist/esm/utils/graph.mjs.map +1 -1
  98. package/dist/esm/utils/llm.mjs +0 -1
  99. package/dist/esm/utils/llm.mjs.map +1 -1
  100. package/dist/esm/utils/misc.mjs.map +1 -1
  101. package/dist/esm/utils/run.mjs.map +1 -1
  102. package/dist/esm/utils/title.mjs +7 -7
  103. package/dist/esm/utils/title.mjs.map +1 -1
  104. package/dist/types/common/enum.d.ts +1 -2
  105. package/dist/types/llm/bedrock/index.d.ts +36 -0
  106. package/dist/types/llm/google/index.d.ts +10 -0
  107. package/dist/types/llm/google/types.d.ts +11 -1
  108. package/dist/types/llm/google/utils/common.d.ts +17 -2
  109. package/dist/types/tools/ToolNode.d.ts +9 -1
  110. package/dist/types/tools/search/types.d.ts +2 -0
  111. package/dist/types/types/llm.d.ts +3 -8
  112. package/dist/types/types/tools.d.ts +1 -1
  113. package/package.json +15 -11
  114. package/src/common/enum.ts +1 -2
  115. package/src/common/index.ts +1 -1
  116. package/src/instrumentation.ts +22 -22
  117. package/src/llm/anthropic/llm.spec.ts +1442 -1442
  118. package/src/llm/anthropic/types.ts +140 -140
  119. package/src/llm/anthropic/utils/message_inputs.ts +757 -660
  120. package/src/llm/anthropic/utils/output_parsers.ts +133 -133
  121. package/src/llm/anthropic/utils/tools.ts +29 -29
  122. package/src/llm/bedrock/index.ts +128 -0
  123. package/src/llm/fake.ts +133 -133
  124. package/src/llm/google/data/gettysburg10.wav +0 -0
  125. package/src/llm/google/data/hotdog.jpg +0 -0
  126. package/src/llm/google/index.ts +129 -14
  127. package/src/llm/google/llm.spec.ts +932 -0
  128. package/src/llm/google/types.ts +56 -43
  129. package/src/llm/google/utils/common.ts +873 -660
  130. package/src/llm/google/utils/tools.ts +160 -160
  131. package/src/llm/openai/types.ts +24 -24
  132. package/src/llm/openai/utils/isReasoningModel.test.ts +90 -90
  133. package/src/llm/providers.ts +2 -7
  134. package/src/llm/text.ts +94 -94
  135. package/src/messages/core.ts +463 -463
  136. package/src/messages/formatAgentMessages.tools.test.ts +400 -400
  137. package/src/messages/formatMessage.test.ts +693 -693
  138. package/src/messages/ids.ts +26 -26
  139. package/src/messages/prune.ts +567 -567
  140. package/src/messages/shiftIndexTokenCountMap.test.ts +81 -81
  141. package/src/mockStream.ts +98 -98
  142. package/src/prompts/collab.ts +5 -5
  143. package/src/prompts/index.ts +1 -1
  144. package/src/prompts/taskmanager.ts +61 -61
  145. package/src/run.ts +13 -4
  146. package/src/scripts/ant_web_search_edge_case.ts +162 -0
  147. package/src/scripts/ant_web_search_error_edge_case.ts +148 -0
  148. package/src/scripts/args.ts +48 -48
  149. package/src/scripts/caching.ts +123 -123
  150. package/src/scripts/code_exec_files.ts +193 -193
  151. package/src/scripts/empty_input.ts +137 -137
  152. package/src/scripts/image.ts +178 -178
  153. package/src/scripts/memory.ts +97 -97
  154. package/src/scripts/thinking.ts +149 -149
  155. package/src/specs/anthropic.simple.test.ts +67 -0
  156. package/src/specs/spec.utils.ts +3 -3
  157. package/src/specs/token-distribution-edge-case.test.ts +316 -316
  158. package/src/specs/tool-error.test.ts +193 -193
  159. package/src/splitStream.test.ts +691 -691
  160. package/src/splitStream.ts +234 -234
  161. package/src/stream.test.ts +94 -94
  162. package/src/stream.ts +4 -1
  163. package/src/tools/ToolNode.ts +206 -64
  164. package/src/tools/handlers.ts +32 -28
  165. package/src/tools/search/anthropic.ts +51 -51
  166. package/src/tools/search/content.test.ts +173 -173
  167. package/src/tools/search/content.ts +147 -147
  168. package/src/tools/search/direct-url.test.ts +530 -0
  169. package/src/tools/search/firecrawl.ts +210 -210
  170. package/src/tools/search/format.ts +250 -250
  171. package/src/tools/search/highlights.ts +320 -320
  172. package/src/tools/search/index.ts +2 -2
  173. package/src/tools/search/jina-reranker.test.ts +126 -126
  174. package/src/tools/search/output.md +2775 -2775
  175. package/src/tools/search/rerankers.ts +242 -242
  176. package/src/tools/search/schema.ts +63 -63
  177. package/src/tools/search/search.ts +766 -759
  178. package/src/tools/search/serper-scraper.ts +155 -155
  179. package/src/tools/search/test.html +883 -883
  180. package/src/tools/search/test.md +642 -642
  181. package/src/tools/search/test.ts +159 -159
  182. package/src/tools/search/tool.ts +619 -471
  183. package/src/tools/search/types.ts +689 -687
  184. package/src/tools/search/utils.ts +79 -79
  185. package/src/types/index.ts +6 -6
  186. package/src/types/llm.ts +2 -8
  187. package/src/types/tools.ts +80 -80
  188. package/src/utils/graph.ts +10 -10
  189. package/src/utils/llm.ts +26 -27
  190. package/src/utils/llmConfig.ts +5 -3
  191. package/src/utils/logging.ts +48 -48
  192. package/src/utils/misc.ts +57 -57
  193. package/src/utils/run.ts +100 -100
  194. package/src/utils/title.ts +165 -165
  195. package/dist/cjs/llm/ollama/index.cjs +0 -70
  196. package/dist/cjs/llm/ollama/index.cjs.map +0 -1
  197. package/dist/cjs/llm/ollama/utils.cjs +0 -158
  198. package/dist/cjs/llm/ollama/utils.cjs.map +0 -1
  199. package/dist/esm/llm/ollama/index.mjs +0 -68
  200. package/dist/esm/llm/ollama/index.mjs.map +0 -1
  201. package/dist/esm/llm/ollama/utils.mjs +0 -155
  202. package/dist/esm/llm/ollama/utils.mjs.map +0 -1
  203. package/dist/types/llm/ollama/index.d.ts +0 -8
  204. package/dist/types/llm/ollama/utils.d.ts +0 -7
  205. package/src/llm/ollama/index.ts +0 -92
  206. package/src/llm/ollama/utils.ts +0 -193
  207. package/src/proto/CollabGraph.ts +0 -269
  208. package/src/proto/TaskManager.ts +0 -243
  209. package/src/proto/collab.ts +0 -200
  210. package/src/proto/collab_design.ts +0 -184
  211. package/src/proto/collab_design_v2.ts +0 -224
  212. package/src/proto/collab_design_v3.ts +0 -255
  213. package/src/proto/collab_design_v4.ts +0 -220
  214. package/src/proto/collab_design_v5.ts +0 -251
  215. package/src/proto/collab_graph.ts +0 -181
  216. package/src/proto/collab_original.ts +0 -123
  217. package/src/proto/example.ts +0 -93
  218. package/src/proto/example_new.ts +0 -68
  219. package/src/proto/example_old.ts +0 -201
  220. package/src/proto/example_test.ts +0 -152
  221. package/src/proto/example_test_anthropic.ts +0 -100
  222. package/src/proto/log_stream.ts +0 -202
  223. package/src/proto/main_collab_community_event.ts +0 -133
  224. package/src/proto/main_collab_design_v2.ts +0 -96
  225. package/src/proto/main_collab_design_v4.ts +0 -100
  226. package/src/proto/main_collab_design_v5.ts +0 -135
  227. package/src/proto/main_collab_global_analysis.ts +0 -122
  228. package/src/proto/main_collab_hackathon_event.ts +0 -153
  229. package/src/proto/main_collab_space_mission.ts +0 -153
  230. package/src/proto/main_philosophy.ts +0 -210
  231. package/src/proto/original_script.ts +0 -126
  232. package/src/proto/standard.ts +0 -100
  233. package/src/proto/stream.ts +0 -56
  234. package/src/proto/tasks.ts +0 -118
  235. package/src/proto/tools/global_analysis_tools.ts +0 -86
  236. package/src/proto/tools/space_mission_tools.ts +0 -60
  237. package/src/proto/vertexai.ts +0 -54
@@ -1,691 +1,691 @@
1
- import { nanoid } from 'nanoid';
2
- import { MessageContentText } from '@langchain/core/messages';
3
- import type * as t from '@/types';
4
- import { GraphEvents, StepTypes, ContentTypes } from '@/common';
5
- import { createContentAggregator } from './stream';
6
- import { SplitStreamHandler } from './splitStream';
7
- import { createMockStream } from './mockStream';
8
-
9
- // Mock sleep to speed up tests
10
- jest.mock('@/utils', () => ({
11
- sleep: (): Promise<void> => Promise.resolve(),
12
- }));
13
-
14
- describe('Stream Generation and Handling', () => {
15
- let mockHandlers: {
16
- [GraphEvents.ON_RUN_STEP]: jest.Mock;
17
- [GraphEvents.ON_MESSAGE_DELTA]: jest.Mock;
18
- };
19
-
20
- beforeEach(() => {
21
- mockHandlers = {
22
- [GraphEvents.ON_RUN_STEP]: jest.fn(),
23
- [GraphEvents.ON_MESSAGE_DELTA]: jest.fn(),
24
- };
25
- });
26
-
27
- it('should properly stream tokens including spaces', async () => {
28
- const stream = createMockStream({
29
- text: 'Hello world!',
30
- streamRate: 0,
31
- })();
32
-
33
- const tokens: string[] = [];
34
- for await (const chunk of stream) {
35
- const content = chunk.choices?.[0]?.delta.content ?? '';
36
- if (content) tokens.push(content);
37
- }
38
-
39
- expect(tokens).toEqual(['Hello', ' ', 'world!']);
40
- });
41
-
42
- it('should handle code blocks without splitting them', async () => {
43
- const runId = nanoid();
44
- const handler = new SplitStreamHandler({
45
- runId,
46
- blockThreshold: 10,
47
- handlers: mockHandlers,
48
- });
49
-
50
- const codeText = `Code:
51
- \`\`\`
52
- const x = 1;
53
- const y = 2;
54
- const z = 2;
55
- const a = 2;
56
- const b = 2;
57
- const c = 2;
58
- const d = 2;
59
- const e = 2;
60
- const f = 2;
61
- const g = 2;
62
- const h = 2;
63
- \`\`\`
64
- End code.`;
65
-
66
- const stream = createMockStream({
67
- text: codeText,
68
- streamRate: 0,
69
- })();
70
-
71
- for await (const chunk of stream) {
72
- handler.handle(chunk);
73
- }
74
-
75
- // Verify that only one message block was created for the code section
76
- const runSteps = mockHandlers[GraphEvents.ON_RUN_STEP].mock.calls;
77
- expect(runSteps.length).toBe(2); // Should only create one message block
78
- });
79
-
80
- it('should split content when exceeding threshold', async () => {
81
- const runId = nanoid();
82
- const handler = new SplitStreamHandler({
83
- runId,
84
- handlers: mockHandlers,
85
- // Set a very low threshold for testing
86
- blockThreshold: 10,
87
- });
88
-
89
- // Make the text longer and ensure it has clear breaking points
90
- const longText =
91
- 'This is the first sentence. And here is another sentence. And yet another one here. Finally one more.';
92
-
93
- const stream = createMockStream({
94
- text: longText,
95
- streamRate: 0,
96
- })();
97
-
98
- // For debugging
99
- // let totalLength = 0;
100
- for await (const chunk of stream) {
101
- handler.handle(chunk);
102
- // For debugging
103
- // const content = chunk.choices?.[0]?.delta.content;
104
- // if (content) {
105
- // totalLength += content.length;
106
- // console.log(`Current length: ${totalLength}, Content: "${content}"`);
107
- // }
108
- }
109
-
110
- // Verify multiple message blocks were created
111
- const runSteps = mockHandlers[GraphEvents.ON_RUN_STEP].mock.calls;
112
- // console.log('Number of run steps:', runSteps.length);
113
- expect(runSteps.length).toEqual(handler.currentIndex + 1);
114
- });
115
-
116
- it('should handle reasoning text separately', async () => {
117
- const runId = nanoid();
118
- new SplitStreamHandler({
119
- runId,
120
- handlers: mockHandlers,
121
- });
122
-
123
- const stream = createMockStream({
124
- text: 'Main content',
125
- reasoningText: 'Reasoning text',
126
- streamRate: 0,
127
- })();
128
-
129
- const reasoningTokens: string[] = [];
130
- const contentTokens: string[] = [];
131
-
132
- for await (const chunk of stream) {
133
- const reasoning = chunk.choices?.[0]?.delta.reasoning_content ?? '';
134
- const content = chunk.choices?.[0]?.delta.content ?? '';
135
-
136
- if (reasoning) reasoningTokens.push(reasoning);
137
- if (content) contentTokens.push(content);
138
- }
139
-
140
- expect(reasoningTokens.length).toBeGreaterThan(0);
141
- expect(contentTokens.length).toBeGreaterThan(0);
142
- });
143
-
144
- it('should preserve empty strings and whitespace', async () => {
145
- const stream = createMockStream({
146
- text: 'Hello world', // Note double space
147
- streamRate: 0,
148
- })();
149
-
150
- const tokens: string[] = [];
151
- for await (const chunk of stream) {
152
- const content = chunk.choices?.[0]?.delta.content ?? '';
153
- if (!content) {
154
- return;
155
- }
156
- tokens.push(content);
157
- }
158
-
159
- expect(tokens).toContain(' ');
160
- expect(tokens.join('')).toBe('Hello world');
161
- });
162
- });
163
-
164
- describe('ContentAggregator with SplitStreamHandler', () => {
165
- it('should aggregate content from multiple message blocks', async () => {
166
- const runId = nanoid();
167
- const { contentParts, aggregateContent } = createContentAggregator();
168
-
169
- const handler = new SplitStreamHandler({
170
- runId,
171
- handlers: {
172
- [GraphEvents.ON_RUN_STEP]: aggregateContent,
173
- [GraphEvents.ON_MESSAGE_DELTA]: aggregateContent,
174
- },
175
- blockThreshold: 5,
176
- });
177
-
178
- const text = 'First sentence. Second sentence. Third sentence.';
179
- const stream = createMockStream({ text, streamRate: 0 })();
180
-
181
- for await (const chunk of stream) {
182
- handler.handle(chunk);
183
- }
184
-
185
- expect(contentParts.length).toBeGreaterThan(0);
186
- contentParts.forEach((part) => {
187
- expect(part?.type).toBe(ContentTypes.TEXT);
188
- if (part?.type === ContentTypes.TEXT) {
189
- expect(typeof part.text).toBe('string');
190
- expect(part.text.length).toBeGreaterThan(0);
191
- }
192
- });
193
-
194
- const fullText = contentParts
195
- .filter((part) => part?.type === ContentTypes.TEXT)
196
- .map((part) => (part?.type === ContentTypes.TEXT ? part.text : ''))
197
- .join('');
198
- expect(fullText).toBe(text);
199
- });
200
-
201
- it('should maintain content order across splits', async () => {
202
- const runId = nanoid();
203
- const { contentParts, aggregateContent } = createContentAggregator();
204
-
205
- const handler = new SplitStreamHandler({
206
- runId,
207
- handlers: {
208
- [GraphEvents.ON_RUN_STEP]: aggregateContent,
209
- [GraphEvents.ON_MESSAGE_DELTA]: aggregateContent,
210
- },
211
- blockThreshold: 15,
212
- });
213
-
214
- const text = 'First part. Second part. Third part.';
215
- const stream = createMockStream({ text, streamRate: 0 })();
216
-
217
- for await (const chunk of stream) {
218
- handler.handle(chunk);
219
- }
220
-
221
- const texts = contentParts
222
- .filter((part) => part?.type === ContentTypes.TEXT)
223
- .map((part) => (part?.type === ContentTypes.TEXT ? part.text : ''));
224
-
225
- expect(texts[0]).toContain('First');
226
- expect(texts[texts.length - 1]).toContain('Third');
227
- });
228
-
229
- it('should handle code blocks as single content parts', async () => {
230
- const runId = nanoid();
231
- const { contentParts, aggregateContent } = createContentAggregator();
232
-
233
- const handler = new SplitStreamHandler({
234
- runId,
235
- handlers: {
236
- [GraphEvents.ON_RUN_STEP]: aggregateContent,
237
- [GraphEvents.ON_MESSAGE_DELTA]: aggregateContent,
238
- },
239
- blockThreshold: 10,
240
- });
241
-
242
- const text = `Before code.
243
- \`\`\`python
244
- def test():
245
- return True
246
- \`\`\`
247
- After code.`;
248
-
249
- const stream = createMockStream({ text, streamRate: 0 })();
250
-
251
- for await (const chunk of stream) {
252
- handler.handle(chunk);
253
- }
254
-
255
- const codeBlockPart = contentParts.find(
256
- (part) =>
257
- part?.type === ContentTypes.TEXT && part.text.includes('```python')
258
- );
259
-
260
- expect(codeBlockPart).toBeDefined();
261
- if (codeBlockPart?.type === ContentTypes.TEXT) {
262
- expect(codeBlockPart.text).toContain('def test()');
263
- expect(codeBlockPart.text).toContain('return True');
264
- }
265
- });
266
-
267
- it('should properly map steps to their content', async () => {
268
- const runId = nanoid();
269
- const { contentParts, aggregateContent, stepMap } =
270
- createContentAggregator();
271
-
272
- const handler = new SplitStreamHandler({
273
- runId,
274
- handlers: {
275
- [GraphEvents.ON_RUN_STEP]: aggregateContent,
276
- [GraphEvents.ON_MESSAGE_DELTA]: aggregateContent,
277
- },
278
- blockThreshold: 5,
279
- });
280
-
281
- const text = 'Hi. Ok. Yes.';
282
- const stream = createMockStream({ text, streamRate: 0 })();
283
-
284
- for await (const chunk of stream) {
285
- handler.handle(chunk);
286
- }
287
-
288
- Array.from(stepMap.entries()).forEach(([_stepId, step]) => {
289
- expect(step?.type).toBe(StepTypes.MESSAGE_CREATION);
290
- const currentIndex = step?.index ?? -1;
291
- const stepContent = contentParts[currentIndex];
292
- if (!stepContent && currentIndex > 0) {
293
- const prevStepContent = contentParts[currentIndex - 1];
294
- expect(
295
- (prevStepContent as MessageContentText | undefined)?.text
296
- ).toEqual(text);
297
- } else if (stepContent?.type === ContentTypes.TEXT) {
298
- expect(stepContent.text.length).toBeGreaterThan(0);
299
- }
300
- });
301
-
302
- contentParts.forEach((part, index) => {
303
- const hasMatchingStep = Array.from(stepMap.values()).some(
304
- (step) => step?.index === index
305
- );
306
- expect(hasMatchingStep).toBe(true);
307
- });
308
- });
309
-
310
- it('should aggregate content across multiple splits while preserving order', async () => {
311
- const runId = nanoid();
312
- const { contentParts, aggregateContent } = createContentAggregator();
313
-
314
- const handler = new SplitStreamHandler({
315
- runId,
316
- handlers: {
317
- [GraphEvents.ON_RUN_STEP]: aggregateContent,
318
- [GraphEvents.ON_MESSAGE_DELTA]: aggregateContent,
319
- },
320
- blockThreshold: 10,
321
- });
322
-
323
- const text = 'A. B. C. D. E. F.';
324
- const stream = createMockStream({ text, streamRate: 0 })();
325
-
326
- for await (const chunk of stream) {
327
- handler.handle(chunk);
328
- }
329
-
330
- const letters = ['A', 'B', 'C', 'D', 'E', 'F'];
331
- let letterIndex = 0;
332
-
333
- contentParts.forEach((part) => {
334
- if (part?.type === ContentTypes.TEXT) {
335
- while (
336
- letterIndex < letters.length &&
337
- part.text.includes(letters[letterIndex]) === true
338
- ) {
339
- letterIndex++;
340
- }
341
- }
342
- });
343
-
344
- expect(letterIndex).toBe(letters.length);
345
- });
346
- });
347
-
348
- describe('SplitStreamHandler with Reasoning Tokens', () => {
349
- it('should apply same splitting rules to both content types', async () => {
350
- const runId = nanoid();
351
- const mockHandlers: t.SplitStreamHandlers = {
352
- [GraphEvents.ON_RUN_STEP]: jest.fn(),
353
- [GraphEvents.ON_MESSAGE_DELTA]: jest.fn(),
354
- [GraphEvents.ON_REASONING_DELTA]: jest.fn(),
355
- };
356
-
357
- const handler = new SplitStreamHandler({
358
- runId,
359
- handlers: mockHandlers,
360
- blockThreshold: 3,
361
- });
362
-
363
- const stream = createMockStream({
364
- text: 'First text. Second text. Third text.',
365
- reasoningText: 'First thought. Second thought. Third thought.',
366
- streamRate: 0,
367
- })();
368
-
369
- for await (const chunk of stream) {
370
- handler.handle(chunk);
371
- }
372
-
373
- const runSteps = (mockHandlers[GraphEvents.ON_RUN_STEP] as jest.Mock).mock
374
- .calls;
375
- const reasoningDeltas = (
376
- mockHandlers[GraphEvents.ON_REASONING_DELTA] as jest.Mock
377
- ).mock.calls;
378
- const messageDeltas = (
379
- mockHandlers[GraphEvents.ON_MESSAGE_DELTA] as jest.Mock
380
- ).mock.calls;
381
-
382
- // Both content types should create multiple blocks
383
- expect(runSteps.length).toBeGreaterThan(1);
384
- expect(reasoningDeltas.length).toBeGreaterThan(0);
385
- expect(messageDeltas.length).toBeGreaterThan(0);
386
-
387
- // Verify splitting behavior for both types
388
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
389
- const getStepTypes = (calls: any[]): string[] =>
390
- calls
391
- .map(([{ data }]) =>
392
- data.stepDetails?.type === StepTypes.MESSAGE_CREATION
393
- ? data.stepDetails.message_creation.message_id
394
- : null
395
- )
396
- .filter(Boolean);
397
-
398
- const messageSteps = getStepTypes(runSteps);
399
- expect(new Set(messageSteps).size).toBeGreaterThan(1);
400
- });
401
-
402
- it('should properly map steps to their reasoning content', async () => {
403
- const runId = nanoid();
404
- const { contentParts, aggregateContent, stepMap } =
405
- createContentAggregator();
406
-
407
- const handler = new SplitStreamHandler({
408
- runId,
409
- handlers: {
410
- [GraphEvents.ON_RUN_STEP]: aggregateContent,
411
- [GraphEvents.ON_MESSAGE_DELTA]: aggregateContent,
412
- [GraphEvents.ON_REASONING_DELTA]: aggregateContent,
413
- },
414
- blockThreshold: 5,
415
- });
416
-
417
- const text = 'Main content.';
418
- const reasoningText = 'First thought. Second thought. Third thought.';
419
- const stream = createMockStream({
420
- text,
421
- reasoningText,
422
- streamRate: 0,
423
- })();
424
-
425
- for await (const chunk of stream) {
426
- handler.handle(chunk);
427
- }
428
-
429
- Array.from(stepMap.entries()).forEach(([_stepId, step]) => {
430
- expect(step?.type).toBe(StepTypes.MESSAGE_CREATION);
431
- const currentIndex = step?.index ?? -1;
432
- const stepContent = contentParts[currentIndex];
433
-
434
- if (stepContent?.type === ContentTypes.THINK) {
435
- // Verify reasoning content structure
436
- expect(stepContent).toHaveProperty('think');
437
- expect(typeof stepContent.think).toBe('string');
438
- expect(stepContent.think.length).toBeGreaterThan(0);
439
- }
440
- });
441
-
442
- // Verify at least one reasoning content part exists
443
- const reasoningParts = contentParts.filter(
444
- (part) => part?.type === ContentTypes.THINK
445
- );
446
- expect(reasoningParts.length).toBeGreaterThan(0);
447
-
448
- // Verify the content order (reasoning should come before main content)
449
- const contentTypes = contentParts
450
- .filter((part) => part !== undefined)
451
- .map((part) => part.type);
452
-
453
- expect(contentTypes).toContain(ContentTypes.THINK);
454
- expect(contentTypes).toContain(ContentTypes.TEXT);
455
-
456
- // Verify the complete reasoning content is preserved
457
- const fullReasoningText = reasoningParts
458
- .map((part) => (part?.type === ContentTypes.THINK ? part.think : ''))
459
- .join('');
460
- expect(fullReasoningText).toBe(reasoningText);
461
- });
462
- });
463
-
464
- describe('SplitStreamHandler', () => {
465
- it('should handle think blocks correctly', async () => {
466
- const runId = nanoid();
467
- const messageDeltaEvents: t.MessageDeltaEvent[] = [];
468
- const reasoningDeltaEvents: t.ReasoningDeltaEvent[] = [];
469
-
470
- const streamHandler = new SplitStreamHandler({
471
- runId,
472
- handlers: {
473
- [GraphEvents.ON_MESSAGE_DELTA]: ({ data }): void => {
474
- messageDeltaEvents.push(data);
475
- },
476
- [GraphEvents.ON_REASONING_DELTA]: ({ data }): void => {
477
- reasoningDeltaEvents.push(data);
478
- },
479
- },
480
- });
481
-
482
- const content =
483
- 'Here\'s some regular text. <think>Now I\'m thinking deeply about something important. This should all be reasoning.</think> Back to regular text.';
484
-
485
- const stream = createMockStream({
486
- text: content,
487
- streamRate: 5,
488
- })();
489
-
490
- for await (const chunk of stream) {
491
- streamHandler.handle(chunk);
492
- }
493
-
494
- // Check that content before <think> was handled as regular text
495
- expect(
496
- messageDeltaEvents.some((event) =>
497
- (
498
- event.delta.content?.[0] as t.MessageDeltaUpdate | undefined
499
- )?.text.includes('Here\'s')
500
- )
501
- ).toBe(true);
502
-
503
- // Check that <think> tag was handled as reasoning
504
- expect(
505
- reasoningDeltaEvents.some((event) =>
506
- (
507
- event.delta.content?.[0] as t.ReasoningDeltaUpdate | undefined
508
- )?.think.includes('<think>')
509
- )
510
- ).toBe(true);
511
-
512
- // Check that content inside <think> tags was handled as reasoning
513
- expect(
514
- reasoningDeltaEvents.some((event) =>
515
- (
516
- event.delta.content?.[0] as t.ReasoningDeltaUpdate | undefined
517
- )?.think.includes('thinking')
518
- )
519
- ).toBe(true);
520
-
521
- // Check that </think> tag was handled as reasoning
522
- expect(
523
- reasoningDeltaEvents.some((event) =>
524
- (
525
- event.delta.content?.[0] as t.ReasoningDeltaUpdate | undefined
526
- )?.think.includes('</think>')
527
- )
528
- ).toBe(true);
529
-
530
- // Check that content after </think> was handled as regular text
531
- expect(
532
- messageDeltaEvents.some((event) =>
533
- (
534
- event.delta.content?.[0] as t.MessageDeltaUpdate | undefined
535
- )?.text.includes('Back')
536
- )
537
- ).toBe(true);
538
- });
539
-
540
- it('should ignore think tags inside code blocks', async () => {
541
- const runId = nanoid();
542
- const messageDeltaEvents: t.MessageDeltaEvent[] = [];
543
- const reasoningDeltaEvents: t.ReasoningDeltaEvent[] = [];
544
-
545
- const streamHandler = new SplitStreamHandler({
546
- runId,
547
- handlers: {
548
- [GraphEvents.ON_MESSAGE_DELTA]: ({ data }): void => {
549
- messageDeltaEvents.push(data);
550
- },
551
- [GraphEvents.ON_REASONING_DELTA]: ({ data }): void => {
552
- reasoningDeltaEvents.push(data);
553
- },
554
- },
555
- });
556
-
557
- const content =
558
- 'Regular text. ```<think>This should stay as code</think>``` More text.';
559
-
560
- const stream = createMockStream({
561
- text: content,
562
- streamRate: 5,
563
- })();
564
-
565
- for await (const chunk of stream) {
566
- streamHandler.handle(chunk);
567
- }
568
-
569
- // Check that think tags inside code blocks were treated as regular text
570
- expect(
571
- messageDeltaEvents.some((event) =>
572
- (
573
- event.delta.content?.[0] as t.MessageDeltaUpdate | undefined
574
- )?.text.includes('Regular')
575
- )
576
- ).toBe(true);
577
-
578
- // Verify no reasoning events were generated
579
- expect(reasoningDeltaEvents.length).toBe(0);
580
- });
581
-
582
- it('should properly split content with think tags while maintaining context', async () => {
583
- const runId = nanoid();
584
- const messageDeltaEvents: t.MessageDeltaEvent[] = [];
585
- const reasoningDeltaEvents: t.ReasoningDeltaEvent[] = [];
586
- const runStepEvents: t.RunStep[] = [];
587
- const { contentParts, aggregateContent } = createContentAggregator();
588
-
589
- const streamHandler = new SplitStreamHandler({
590
- runId,
591
- blockThreshold: 20, // Small threshold to force splits
592
- handlers: {
593
- [GraphEvents.ON_MESSAGE_DELTA]: (event): void => {
594
- messageDeltaEvents.push(event.data);
595
- aggregateContent(event);
596
- },
597
- [GraphEvents.ON_REASONING_DELTA]: (event): void => {
598
- reasoningDeltaEvents.push(event.data);
599
- aggregateContent(event);
600
- },
601
- [GraphEvents.ON_RUN_STEP]: (event): void => {
602
- runStepEvents.push(event.data);
603
- aggregateContent(event);
604
- },
605
- },
606
- });
607
-
608
- const content =
609
- '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.';
610
-
611
- const stream = createMockStream({
612
- text: content,
613
- streamRate: 5,
614
- })();
615
-
616
- for await (const chunk of stream) {
617
- streamHandler.handle(chunk);
618
- }
619
-
620
- // Verify that multiple message blocks were created
621
- expect(runStepEvents.length).toBeGreaterThan(2);
622
-
623
- // Check that content before <think> was handled as regular text
624
- expect(
625
- messageDeltaEvents.some((event) =>
626
- (
627
- event.delta.content?.[0] as t.MessageDeltaUpdate | undefined
628
- )?.text.includes('regular')
629
- )
630
- ).toBe(true);
631
-
632
- // Verify that reasoning content was split into multiple parts
633
- const reasoningParts = reasoningDeltaEvents
634
- .map(
635
- (event) =>
636
- (event.delta.content?.[0] as t.ReasoningDeltaUpdate | undefined)
637
- ?.think
638
- )
639
- .filter(Boolean);
640
- expect(reasoningParts.length).toBeGreaterThan(1);
641
-
642
- // Verify that the complete reasoning content is preserved when joined
643
- const fullReasoningContent = reasoningParts.join('');
644
- expect(fullReasoningContent).toContain('thinking');
645
- expect(fullReasoningContent).toContain('should');
646
- expect(fullReasoningContent).toContain('be');
647
- expect(fullReasoningContent).toContain('split');
648
-
649
- // Check that each reasoning part maintains proper think context
650
- let seenThinkOpen = false;
651
- let seenThinkClose = false;
652
- reasoningParts.forEach((part) => {
653
- if (part == null) return;
654
- if (part.includes('<think>')) {
655
- seenThinkOpen = true;
656
- }
657
- if (part.includes('</think>')) {
658
- seenThinkClose = true;
659
- }
660
- // Middle parts should be handled as reasoning even without explicit think tags
661
- if (!part.includes('<think>') && !part.includes('</think>')) {
662
- expect(
663
- reasoningDeltaEvents.some(
664
- (event) =>
665
- (event.delta.content?.[0] as t.ReasoningDeltaUpdate | undefined)
666
- ?.think === part
667
- )
668
- ).toBe(true);
669
- }
670
- });
671
- expect(seenThinkOpen).toBe(true);
672
- expect(seenThinkClose).toBe(true);
673
-
674
- // Check that content after </think> was handled as regular text
675
- expect(
676
- messageDeltaEvents.some((event) =>
677
- (
678
- event.delta.content?.[0] as t.MessageDeltaUpdate | undefined
679
- )?.text.includes('Back')
680
- )
681
- ).toBe(true);
682
-
683
- const thinkingBlocks = contentParts.filter(
684
- (part) => part?.type === ContentTypes.THINK
685
- );
686
- expect(thinkingBlocks.length).toBeGreaterThan(0);
687
- expect(
688
- (thinkingBlocks[0] as t.ReasoningContentText).think.startsWith('<think>')
689
- ).toBeTruthy();
690
- });
691
- });
1
+ import { nanoid } from 'nanoid';
2
+ import { MessageContentText } from '@langchain/core/messages';
3
+ import type * as t from '@/types';
4
+ import { GraphEvents, StepTypes, ContentTypes } from '@/common';
5
+ import { createContentAggregator } from './stream';
6
+ import { SplitStreamHandler } from './splitStream';
7
+ import { createMockStream } from './mockStream';
8
+
9
+ // Mock sleep to speed up tests
10
+ jest.mock('@/utils', () => ({
11
+ sleep: (): Promise<void> => Promise.resolve(),
12
+ }));
13
+
14
+ describe('Stream Generation and Handling', () => {
15
+ let mockHandlers: {
16
+ [GraphEvents.ON_RUN_STEP]: jest.Mock;
17
+ [GraphEvents.ON_MESSAGE_DELTA]: jest.Mock;
18
+ };
19
+
20
+ beforeEach(() => {
21
+ mockHandlers = {
22
+ [GraphEvents.ON_RUN_STEP]: jest.fn(),
23
+ [GraphEvents.ON_MESSAGE_DELTA]: jest.fn(),
24
+ };
25
+ });
26
+
27
+ it('should properly stream tokens including spaces', async () => {
28
+ const stream = createMockStream({
29
+ text: 'Hello world!',
30
+ streamRate: 0,
31
+ })();
32
+
33
+ const tokens: string[] = [];
34
+ for await (const chunk of stream) {
35
+ const content = chunk.choices?.[0]?.delta.content ?? '';
36
+ if (content) tokens.push(content);
37
+ }
38
+
39
+ expect(tokens).toEqual(['Hello', ' ', 'world!']);
40
+ });
41
+
42
+ it('should handle code blocks without splitting them', async () => {
43
+ const runId = nanoid();
44
+ const handler = new SplitStreamHandler({
45
+ runId,
46
+ blockThreshold: 10,
47
+ handlers: mockHandlers,
48
+ });
49
+
50
+ const codeText = `Code:
51
+ \`\`\`
52
+ const x = 1;
53
+ const y = 2;
54
+ const z = 2;
55
+ const a = 2;
56
+ const b = 2;
57
+ const c = 2;
58
+ const d = 2;
59
+ const e = 2;
60
+ const f = 2;
61
+ const g = 2;
62
+ const h = 2;
63
+ \`\`\`
64
+ End code.`;
65
+
66
+ const stream = createMockStream({
67
+ text: codeText,
68
+ streamRate: 0,
69
+ })();
70
+
71
+ for await (const chunk of stream) {
72
+ handler.handle(chunk);
73
+ }
74
+
75
+ // Verify that only one message block was created for the code section
76
+ const runSteps = mockHandlers[GraphEvents.ON_RUN_STEP].mock.calls;
77
+ expect(runSteps.length).toBe(2); // Should only create one message block
78
+ });
79
+
80
+ it('should split content when exceeding threshold', async () => {
81
+ const runId = nanoid();
82
+ const handler = new SplitStreamHandler({
83
+ runId,
84
+ handlers: mockHandlers,
85
+ // Set a very low threshold for testing
86
+ blockThreshold: 10,
87
+ });
88
+
89
+ // Make the text longer and ensure it has clear breaking points
90
+ const longText =
91
+ 'This is the first sentence. And here is another sentence. And yet another one here. Finally one more.';
92
+
93
+ const stream = createMockStream({
94
+ text: longText,
95
+ streamRate: 0,
96
+ })();
97
+
98
+ // For debugging
99
+ // let totalLength = 0;
100
+ for await (const chunk of stream) {
101
+ handler.handle(chunk);
102
+ // For debugging
103
+ // const content = chunk.choices?.[0]?.delta.content;
104
+ // if (content) {
105
+ // totalLength += content.length;
106
+ // console.log(`Current length: ${totalLength}, Content: "${content}"`);
107
+ // }
108
+ }
109
+
110
+ // Verify multiple message blocks were created
111
+ const runSteps = mockHandlers[GraphEvents.ON_RUN_STEP].mock.calls;
112
+ // console.log('Number of run steps:', runSteps.length);
113
+ expect(runSteps.length).toEqual(handler.currentIndex + 1);
114
+ });
115
+
116
+ it('should handle reasoning text separately', async () => {
117
+ const runId = nanoid();
118
+ new SplitStreamHandler({
119
+ runId,
120
+ handlers: mockHandlers,
121
+ });
122
+
123
+ const stream = createMockStream({
124
+ text: 'Main content',
125
+ reasoningText: 'Reasoning text',
126
+ streamRate: 0,
127
+ })();
128
+
129
+ const reasoningTokens: string[] = [];
130
+ const contentTokens: string[] = [];
131
+
132
+ for await (const chunk of stream) {
133
+ const reasoning = chunk.choices?.[0]?.delta.reasoning_content ?? '';
134
+ const content = chunk.choices?.[0]?.delta.content ?? '';
135
+
136
+ if (reasoning) reasoningTokens.push(reasoning);
137
+ if (content) contentTokens.push(content);
138
+ }
139
+
140
+ expect(reasoningTokens.length).toBeGreaterThan(0);
141
+ expect(contentTokens.length).toBeGreaterThan(0);
142
+ });
143
+
144
+ it('should preserve empty strings and whitespace', async () => {
145
+ const stream = createMockStream({
146
+ text: 'Hello world', // Note double space
147
+ streamRate: 0,
148
+ })();
149
+
150
+ const tokens: string[] = [];
151
+ for await (const chunk of stream) {
152
+ const content = chunk.choices?.[0]?.delta.content ?? '';
153
+ if (!content) {
154
+ return;
155
+ }
156
+ tokens.push(content);
157
+ }
158
+
159
+ expect(tokens).toContain(' ');
160
+ expect(tokens.join('')).toBe('Hello world');
161
+ });
162
+ });
163
+
164
+ describe('ContentAggregator with SplitStreamHandler', () => {
165
+ it('should aggregate content from multiple message blocks', async () => {
166
+ const runId = nanoid();
167
+ const { contentParts, aggregateContent } = createContentAggregator();
168
+
169
+ const handler = new SplitStreamHandler({
170
+ runId,
171
+ handlers: {
172
+ [GraphEvents.ON_RUN_STEP]: aggregateContent,
173
+ [GraphEvents.ON_MESSAGE_DELTA]: aggregateContent,
174
+ },
175
+ blockThreshold: 5,
176
+ });
177
+
178
+ const text = 'First sentence. Second sentence. Third sentence.';
179
+ const stream = createMockStream({ text, streamRate: 0 })();
180
+
181
+ for await (const chunk of stream) {
182
+ handler.handle(chunk);
183
+ }
184
+
185
+ expect(contentParts.length).toBeGreaterThan(0);
186
+ contentParts.forEach((part) => {
187
+ expect(part?.type).toBe(ContentTypes.TEXT);
188
+ if (part?.type === ContentTypes.TEXT) {
189
+ expect(typeof part.text).toBe('string');
190
+ expect(part.text.length).toBeGreaterThan(0);
191
+ }
192
+ });
193
+
194
+ const fullText = contentParts
195
+ .filter((part) => part?.type === ContentTypes.TEXT)
196
+ .map((part) => (part?.type === ContentTypes.TEXT ? part.text : ''))
197
+ .join('');
198
+ expect(fullText).toBe(text);
199
+ });
200
+
201
+ it('should maintain content order across splits', async () => {
202
+ const runId = nanoid();
203
+ const { contentParts, aggregateContent } = createContentAggregator();
204
+
205
+ const handler = new SplitStreamHandler({
206
+ runId,
207
+ handlers: {
208
+ [GraphEvents.ON_RUN_STEP]: aggregateContent,
209
+ [GraphEvents.ON_MESSAGE_DELTA]: aggregateContent,
210
+ },
211
+ blockThreshold: 15,
212
+ });
213
+
214
+ const text = 'First part. Second part. Third part.';
215
+ const stream = createMockStream({ text, streamRate: 0 })();
216
+
217
+ for await (const chunk of stream) {
218
+ handler.handle(chunk);
219
+ }
220
+
221
+ const texts = contentParts
222
+ .filter((part) => part?.type === ContentTypes.TEXT)
223
+ .map((part) => (part?.type === ContentTypes.TEXT ? part.text : ''));
224
+
225
+ expect(texts[0]).toContain('First');
226
+ expect(texts[texts.length - 1]).toContain('Third');
227
+ });
228
+
229
+ it('should handle code blocks as single content parts', async () => {
230
+ const runId = nanoid();
231
+ const { contentParts, aggregateContent } = createContentAggregator();
232
+
233
+ const handler = new SplitStreamHandler({
234
+ runId,
235
+ handlers: {
236
+ [GraphEvents.ON_RUN_STEP]: aggregateContent,
237
+ [GraphEvents.ON_MESSAGE_DELTA]: aggregateContent,
238
+ },
239
+ blockThreshold: 10,
240
+ });
241
+
242
+ const text = `Before code.
243
+ \`\`\`python
244
+ def test():
245
+ return True
246
+ \`\`\`
247
+ After code.`;
248
+
249
+ const stream = createMockStream({ text, streamRate: 0 })();
250
+
251
+ for await (const chunk of stream) {
252
+ handler.handle(chunk);
253
+ }
254
+
255
+ const codeBlockPart = contentParts.find(
256
+ (part) =>
257
+ part?.type === ContentTypes.TEXT && part.text.includes('```python')
258
+ );
259
+
260
+ expect(codeBlockPart).toBeDefined();
261
+ if (codeBlockPart?.type === ContentTypes.TEXT) {
262
+ expect(codeBlockPart.text).toContain('def test()');
263
+ expect(codeBlockPart.text).toContain('return True');
264
+ }
265
+ });
266
+
267
+ it('should properly map steps to their content', async () => {
268
+ const runId = nanoid();
269
+ const { contentParts, aggregateContent, stepMap } =
270
+ createContentAggregator();
271
+
272
+ const handler = new SplitStreamHandler({
273
+ runId,
274
+ handlers: {
275
+ [GraphEvents.ON_RUN_STEP]: aggregateContent,
276
+ [GraphEvents.ON_MESSAGE_DELTA]: aggregateContent,
277
+ },
278
+ blockThreshold: 5,
279
+ });
280
+
281
+ const text = 'Hi. Ok. Yes.';
282
+ const stream = createMockStream({ text, streamRate: 0 })();
283
+
284
+ for await (const chunk of stream) {
285
+ handler.handle(chunk);
286
+ }
287
+
288
+ Array.from(stepMap.entries()).forEach(([_stepId, step]) => {
289
+ expect(step?.type).toBe(StepTypes.MESSAGE_CREATION);
290
+ const currentIndex = step?.index ?? -1;
291
+ const stepContent = contentParts[currentIndex];
292
+ if (!stepContent && currentIndex > 0) {
293
+ const prevStepContent = contentParts[currentIndex - 1];
294
+ expect(
295
+ (prevStepContent as MessageContentText | undefined)?.text
296
+ ).toEqual(text);
297
+ } else if (stepContent?.type === ContentTypes.TEXT) {
298
+ expect(stepContent.text.length).toBeGreaterThan(0);
299
+ }
300
+ });
301
+
302
+ contentParts.forEach((part, index) => {
303
+ const hasMatchingStep = Array.from(stepMap.values()).some(
304
+ (step) => step?.index === index
305
+ );
306
+ expect(hasMatchingStep).toBe(true);
307
+ });
308
+ });
309
+
310
+ it('should aggregate content across multiple splits while preserving order', async () => {
311
+ const runId = nanoid();
312
+ const { contentParts, aggregateContent } = createContentAggregator();
313
+
314
+ const handler = new SplitStreamHandler({
315
+ runId,
316
+ handlers: {
317
+ [GraphEvents.ON_RUN_STEP]: aggregateContent,
318
+ [GraphEvents.ON_MESSAGE_DELTA]: aggregateContent,
319
+ },
320
+ blockThreshold: 10,
321
+ });
322
+
323
+ const text = 'A. B. C. D. E. F.';
324
+ const stream = createMockStream({ text, streamRate: 0 })();
325
+
326
+ for await (const chunk of stream) {
327
+ handler.handle(chunk);
328
+ }
329
+
330
+ const letters = ['A', 'B', 'C', 'D', 'E', 'F'];
331
+ let letterIndex = 0;
332
+
333
+ contentParts.forEach((part) => {
334
+ if (part?.type === ContentTypes.TEXT) {
335
+ while (
336
+ letterIndex < letters.length &&
337
+ part.text.includes(letters[letterIndex]) === true
338
+ ) {
339
+ letterIndex++;
340
+ }
341
+ }
342
+ });
343
+
344
+ expect(letterIndex).toBe(letters.length);
345
+ });
346
+ });
347
+
348
+ describe('SplitStreamHandler with Reasoning Tokens', () => {
349
+ it('should apply same splitting rules to both content types', async () => {
350
+ const runId = nanoid();
351
+ const mockHandlers: t.SplitStreamHandlers = {
352
+ [GraphEvents.ON_RUN_STEP]: jest.fn(),
353
+ [GraphEvents.ON_MESSAGE_DELTA]: jest.fn(),
354
+ [GraphEvents.ON_REASONING_DELTA]: jest.fn(),
355
+ };
356
+
357
+ const handler = new SplitStreamHandler({
358
+ runId,
359
+ handlers: mockHandlers,
360
+ blockThreshold: 3,
361
+ });
362
+
363
+ const stream = createMockStream({
364
+ text: 'First text. Second text. Third text.',
365
+ reasoningText: 'First thought. Second thought. Third thought.',
366
+ streamRate: 0,
367
+ })();
368
+
369
+ for await (const chunk of stream) {
370
+ handler.handle(chunk);
371
+ }
372
+
373
+ const runSteps = (mockHandlers[GraphEvents.ON_RUN_STEP] as jest.Mock).mock
374
+ .calls;
375
+ const reasoningDeltas = (
376
+ mockHandlers[GraphEvents.ON_REASONING_DELTA] as jest.Mock
377
+ ).mock.calls;
378
+ const messageDeltas = (
379
+ mockHandlers[GraphEvents.ON_MESSAGE_DELTA] as jest.Mock
380
+ ).mock.calls;
381
+
382
+ // Both content types should create multiple blocks
383
+ expect(runSteps.length).toBeGreaterThan(1);
384
+ expect(reasoningDeltas.length).toBeGreaterThan(0);
385
+ expect(messageDeltas.length).toBeGreaterThan(0);
386
+
387
+ // Verify splitting behavior for both types
388
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
389
+ const getStepTypes = (calls: any[]): string[] =>
390
+ calls
391
+ .map(([{ data }]) =>
392
+ data.stepDetails?.type === StepTypes.MESSAGE_CREATION
393
+ ? data.stepDetails.message_creation.message_id
394
+ : null
395
+ )
396
+ .filter(Boolean);
397
+
398
+ const messageSteps = getStepTypes(runSteps);
399
+ expect(new Set(messageSteps).size).toBeGreaterThan(1);
400
+ });
401
+
402
+ it('should properly map steps to their reasoning content', async () => {
403
+ const runId = nanoid();
404
+ const { contentParts, aggregateContent, stepMap } =
405
+ createContentAggregator();
406
+
407
+ const handler = new SplitStreamHandler({
408
+ runId,
409
+ handlers: {
410
+ [GraphEvents.ON_RUN_STEP]: aggregateContent,
411
+ [GraphEvents.ON_MESSAGE_DELTA]: aggregateContent,
412
+ [GraphEvents.ON_REASONING_DELTA]: aggregateContent,
413
+ },
414
+ blockThreshold: 5,
415
+ });
416
+
417
+ const text = 'Main content.';
418
+ const reasoningText = 'First thought. Second thought. Third thought.';
419
+ const stream = createMockStream({
420
+ text,
421
+ reasoningText,
422
+ streamRate: 0,
423
+ })();
424
+
425
+ for await (const chunk of stream) {
426
+ handler.handle(chunk);
427
+ }
428
+
429
+ Array.from(stepMap.entries()).forEach(([_stepId, step]) => {
430
+ expect(step?.type).toBe(StepTypes.MESSAGE_CREATION);
431
+ const currentIndex = step?.index ?? -1;
432
+ const stepContent = contentParts[currentIndex];
433
+
434
+ if (stepContent?.type === ContentTypes.THINK) {
435
+ // Verify reasoning content structure
436
+ expect(stepContent).toHaveProperty('think');
437
+ expect(typeof stepContent.think).toBe('string');
438
+ expect(stepContent.think.length).toBeGreaterThan(0);
439
+ }
440
+ });
441
+
442
+ // Verify at least one reasoning content part exists
443
+ const reasoningParts = contentParts.filter(
444
+ (part) => part?.type === ContentTypes.THINK
445
+ );
446
+ expect(reasoningParts.length).toBeGreaterThan(0);
447
+
448
+ // Verify the content order (reasoning should come before main content)
449
+ const contentTypes = contentParts
450
+ .filter((part) => part !== undefined)
451
+ .map((part) => part.type);
452
+
453
+ expect(contentTypes).toContain(ContentTypes.THINK);
454
+ expect(contentTypes).toContain(ContentTypes.TEXT);
455
+
456
+ // Verify the complete reasoning content is preserved
457
+ const fullReasoningText = reasoningParts
458
+ .map((part) => (part?.type === ContentTypes.THINK ? part.think : ''))
459
+ .join('');
460
+ expect(fullReasoningText).toBe(reasoningText);
461
+ });
462
+ });
463
+
464
+ describe('SplitStreamHandler', () => {
465
+ it('should handle think blocks correctly', async () => {
466
+ const runId = nanoid();
467
+ const messageDeltaEvents: t.MessageDeltaEvent[] = [];
468
+ const reasoningDeltaEvents: t.ReasoningDeltaEvent[] = [];
469
+
470
+ const streamHandler = new SplitStreamHandler({
471
+ runId,
472
+ handlers: {
473
+ [GraphEvents.ON_MESSAGE_DELTA]: ({ data }): void => {
474
+ messageDeltaEvents.push(data);
475
+ },
476
+ [GraphEvents.ON_REASONING_DELTA]: ({ data }): void => {
477
+ reasoningDeltaEvents.push(data);
478
+ },
479
+ },
480
+ });
481
+
482
+ const content =
483
+ 'Here\'s some regular text. <think>Now I\'m thinking deeply about something important. This should all be reasoning.</think> Back to regular text.';
484
+
485
+ const stream = createMockStream({
486
+ text: content,
487
+ streamRate: 5,
488
+ })();
489
+
490
+ for await (const chunk of stream) {
491
+ streamHandler.handle(chunk);
492
+ }
493
+
494
+ // Check that content before <think> was handled as regular text
495
+ expect(
496
+ messageDeltaEvents.some((event) =>
497
+ (
498
+ event.delta.content?.[0] as t.MessageDeltaUpdate | undefined
499
+ )?.text.includes('Here\'s')
500
+ )
501
+ ).toBe(true);
502
+
503
+ // Check that <think> tag was handled as reasoning
504
+ expect(
505
+ reasoningDeltaEvents.some((event) =>
506
+ (
507
+ event.delta.content?.[0] as t.ReasoningDeltaUpdate | undefined
508
+ )?.think.includes('<think>')
509
+ )
510
+ ).toBe(true);
511
+
512
+ // Check that content inside <think> tags was handled as reasoning
513
+ expect(
514
+ reasoningDeltaEvents.some((event) =>
515
+ (
516
+ event.delta.content?.[0] as t.ReasoningDeltaUpdate | undefined
517
+ )?.think.includes('thinking')
518
+ )
519
+ ).toBe(true);
520
+
521
+ // Check that </think> tag was handled as reasoning
522
+ expect(
523
+ reasoningDeltaEvents.some((event) =>
524
+ (
525
+ event.delta.content?.[0] as t.ReasoningDeltaUpdate | undefined
526
+ )?.think.includes('</think>')
527
+ )
528
+ ).toBe(true);
529
+
530
+ // Check that content after </think> was handled as regular text
531
+ expect(
532
+ messageDeltaEvents.some((event) =>
533
+ (
534
+ event.delta.content?.[0] as t.MessageDeltaUpdate | undefined
535
+ )?.text.includes('Back')
536
+ )
537
+ ).toBe(true);
538
+ });
539
+
540
+ it('should ignore think tags inside code blocks', async () => {
541
+ const runId = nanoid();
542
+ const messageDeltaEvents: t.MessageDeltaEvent[] = [];
543
+ const reasoningDeltaEvents: t.ReasoningDeltaEvent[] = [];
544
+
545
+ const streamHandler = new SplitStreamHandler({
546
+ runId,
547
+ handlers: {
548
+ [GraphEvents.ON_MESSAGE_DELTA]: ({ data }): void => {
549
+ messageDeltaEvents.push(data);
550
+ },
551
+ [GraphEvents.ON_REASONING_DELTA]: ({ data }): void => {
552
+ reasoningDeltaEvents.push(data);
553
+ },
554
+ },
555
+ });
556
+
557
+ const content =
558
+ 'Regular text. ```<think>This should stay as code</think>``` More text.';
559
+
560
+ const stream = createMockStream({
561
+ text: content,
562
+ streamRate: 5,
563
+ })();
564
+
565
+ for await (const chunk of stream) {
566
+ streamHandler.handle(chunk);
567
+ }
568
+
569
+ // Check that think tags inside code blocks were treated as regular text
570
+ expect(
571
+ messageDeltaEvents.some((event) =>
572
+ (
573
+ event.delta.content?.[0] as t.MessageDeltaUpdate | undefined
574
+ )?.text.includes('Regular')
575
+ )
576
+ ).toBe(true);
577
+
578
+ // Verify no reasoning events were generated
579
+ expect(reasoningDeltaEvents.length).toBe(0);
580
+ });
581
+
582
+ it('should properly split content with think tags while maintaining context', async () => {
583
+ const runId = nanoid();
584
+ const messageDeltaEvents: t.MessageDeltaEvent[] = [];
585
+ const reasoningDeltaEvents: t.ReasoningDeltaEvent[] = [];
586
+ const runStepEvents: t.RunStep[] = [];
587
+ const { contentParts, aggregateContent } = createContentAggregator();
588
+
589
+ const streamHandler = new SplitStreamHandler({
590
+ runId,
591
+ blockThreshold: 20, // Small threshold to force splits
592
+ handlers: {
593
+ [GraphEvents.ON_MESSAGE_DELTA]: (event): void => {
594
+ messageDeltaEvents.push(event.data);
595
+ aggregateContent(event);
596
+ },
597
+ [GraphEvents.ON_REASONING_DELTA]: (event): void => {
598
+ reasoningDeltaEvents.push(event.data);
599
+ aggregateContent(event);
600
+ },
601
+ [GraphEvents.ON_RUN_STEP]: (event): void => {
602
+ runStepEvents.push(event.data);
603
+ aggregateContent(event);
604
+ },
605
+ },
606
+ });
607
+
608
+ const content =
609
+ '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.';
610
+
611
+ const stream = createMockStream({
612
+ text: content,
613
+ streamRate: 5,
614
+ })();
615
+
616
+ for await (const chunk of stream) {
617
+ streamHandler.handle(chunk);
618
+ }
619
+
620
+ // Verify that multiple message blocks were created
621
+ expect(runStepEvents.length).toBeGreaterThan(2);
622
+
623
+ // Check that content before <think> was handled as regular text
624
+ expect(
625
+ messageDeltaEvents.some((event) =>
626
+ (
627
+ event.delta.content?.[0] as t.MessageDeltaUpdate | undefined
628
+ )?.text.includes('regular')
629
+ )
630
+ ).toBe(true);
631
+
632
+ // Verify that reasoning content was split into multiple parts
633
+ const reasoningParts = reasoningDeltaEvents
634
+ .map(
635
+ (event) =>
636
+ (event.delta.content?.[0] as t.ReasoningDeltaUpdate | undefined)
637
+ ?.think
638
+ )
639
+ .filter(Boolean);
640
+ expect(reasoningParts.length).toBeGreaterThan(1);
641
+
642
+ // Verify that the complete reasoning content is preserved when joined
643
+ const fullReasoningContent = reasoningParts.join('');
644
+ expect(fullReasoningContent).toContain('thinking');
645
+ expect(fullReasoningContent).toContain('should');
646
+ expect(fullReasoningContent).toContain('be');
647
+ expect(fullReasoningContent).toContain('split');
648
+
649
+ // Check that each reasoning part maintains proper think context
650
+ let seenThinkOpen = false;
651
+ let seenThinkClose = false;
652
+ reasoningParts.forEach((part) => {
653
+ if (part == null) return;
654
+ if (part.includes('<think>')) {
655
+ seenThinkOpen = true;
656
+ }
657
+ if (part.includes('</think>')) {
658
+ seenThinkClose = true;
659
+ }
660
+ // Middle parts should be handled as reasoning even without explicit think tags
661
+ if (!part.includes('<think>') && !part.includes('</think>')) {
662
+ expect(
663
+ reasoningDeltaEvents.some(
664
+ (event) =>
665
+ (event.delta.content?.[0] as t.ReasoningDeltaUpdate | undefined)
666
+ ?.think === part
667
+ )
668
+ ).toBe(true);
669
+ }
670
+ });
671
+ expect(seenThinkOpen).toBe(true);
672
+ expect(seenThinkClose).toBe(true);
673
+
674
+ // Check that content after </think> was handled as regular text
675
+ expect(
676
+ messageDeltaEvents.some((event) =>
677
+ (
678
+ event.delta.content?.[0] as t.MessageDeltaUpdate | undefined
679
+ )?.text.includes('Back')
680
+ )
681
+ ).toBe(true);
682
+
683
+ const thinkingBlocks = contentParts.filter(
684
+ (part) => part?.type === ContentTypes.THINK
685
+ );
686
+ expect(thinkingBlocks.length).toBeGreaterThan(0);
687
+ expect(
688
+ (thinkingBlocks[0] as t.ReasoningContentText).think.startsWith('<think>')
689
+ ).toBeTruthy();
690
+ });
691
+ });