illuma-agents 1.0.8 → 1.0.10

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 (250) 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/events.cjs +11 -0
  5. package/dist/cjs/events.cjs.map +1 -1
  6. package/dist/cjs/graphs/Graph.cjs +2 -1
  7. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  8. package/dist/cjs/instrumentation.cjs +3 -1
  9. package/dist/cjs/instrumentation.cjs.map +1 -1
  10. package/dist/cjs/llm/anthropic/types.cjs.map +1 -1
  11. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +79 -2
  12. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  13. package/dist/cjs/llm/anthropic/utils/tools.cjs.map +1 -1
  14. package/dist/cjs/llm/bedrock/index.cjs +99 -0
  15. package/dist/cjs/llm/bedrock/index.cjs.map +1 -0
  16. package/dist/cjs/llm/fake.cjs.map +1 -1
  17. package/dist/cjs/llm/openai/index.cjs +102 -0
  18. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  19. package/dist/cjs/llm/openai/utils/index.cjs +87 -1
  20. package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
  21. package/dist/cjs/llm/openrouter/index.cjs +175 -1
  22. package/dist/cjs/llm/openrouter/index.cjs.map +1 -1
  23. package/dist/cjs/llm/providers.cjs +13 -16
  24. package/dist/cjs/llm/providers.cjs.map +1 -1
  25. package/dist/cjs/llm/text.cjs.map +1 -1
  26. package/dist/cjs/messages/core.cjs +14 -14
  27. package/dist/cjs/messages/core.cjs.map +1 -1
  28. package/dist/cjs/messages/ids.cjs.map +1 -1
  29. package/dist/cjs/messages/prune.cjs.map +1 -1
  30. package/dist/cjs/run.cjs +18 -1
  31. package/dist/cjs/run.cjs.map +1 -1
  32. package/dist/cjs/splitStream.cjs.map +1 -1
  33. package/dist/cjs/stream.cjs +24 -1
  34. package/dist/cjs/stream.cjs.map +1 -1
  35. package/dist/cjs/tools/ToolNode.cjs +20 -1
  36. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  37. package/dist/cjs/tools/handlers.cjs +29 -25
  38. package/dist/cjs/tools/handlers.cjs.map +1 -1
  39. package/dist/cjs/tools/search/anthropic.cjs.map +1 -1
  40. package/dist/cjs/tools/search/content.cjs.map +1 -1
  41. package/dist/cjs/tools/search/firecrawl.cjs.map +1 -1
  42. package/dist/cjs/tools/search/format.cjs.map +1 -1
  43. package/dist/cjs/tools/search/highlights.cjs.map +1 -1
  44. package/dist/cjs/tools/search/rerankers.cjs.map +1 -1
  45. package/dist/cjs/tools/search/schema.cjs +27 -25
  46. package/dist/cjs/tools/search/schema.cjs.map +1 -1
  47. package/dist/cjs/tools/search/search.cjs +6 -1
  48. package/dist/cjs/tools/search/search.cjs.map +1 -1
  49. package/dist/cjs/tools/search/serper-scraper.cjs.map +1 -1
  50. package/dist/cjs/tools/search/tool.cjs +182 -35
  51. package/dist/cjs/tools/search/tool.cjs.map +1 -1
  52. package/dist/cjs/tools/search/utils.cjs.map +1 -1
  53. package/dist/cjs/utils/graph.cjs.map +1 -1
  54. package/dist/cjs/utils/llm.cjs +0 -1
  55. package/dist/cjs/utils/llm.cjs.map +1 -1
  56. package/dist/cjs/utils/misc.cjs.map +1 -1
  57. package/dist/cjs/utils/run.cjs.map +1 -1
  58. package/dist/cjs/utils/title.cjs +7 -7
  59. package/dist/cjs/utils/title.cjs.map +1 -1
  60. package/dist/esm/common/enum.mjs +1 -2
  61. package/dist/esm/common/enum.mjs.map +1 -1
  62. package/dist/esm/events.mjs +11 -0
  63. package/dist/esm/events.mjs.map +1 -1
  64. package/dist/esm/graphs/Graph.mjs +2 -1
  65. package/dist/esm/graphs/Graph.mjs.map +1 -1
  66. package/dist/esm/instrumentation.mjs +3 -1
  67. package/dist/esm/instrumentation.mjs.map +1 -1
  68. package/dist/esm/llm/anthropic/types.mjs.map +1 -1
  69. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +79 -2
  70. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  71. package/dist/esm/llm/anthropic/utils/tools.mjs.map +1 -1
  72. package/dist/esm/llm/bedrock/index.mjs +97 -0
  73. package/dist/esm/llm/bedrock/index.mjs.map +1 -0
  74. package/dist/esm/llm/fake.mjs.map +1 -1
  75. package/dist/esm/llm/openai/index.mjs +103 -1
  76. package/dist/esm/llm/openai/index.mjs.map +1 -1
  77. package/dist/esm/llm/openai/utils/index.mjs +88 -2
  78. package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
  79. package/dist/esm/llm/openrouter/index.mjs +175 -1
  80. package/dist/esm/llm/openrouter/index.mjs.map +1 -1
  81. package/dist/esm/llm/providers.mjs +2 -5
  82. package/dist/esm/llm/providers.mjs.map +1 -1
  83. package/dist/esm/llm/text.mjs.map +1 -1
  84. package/dist/esm/messages/core.mjs +14 -14
  85. package/dist/esm/messages/core.mjs.map +1 -1
  86. package/dist/esm/messages/ids.mjs.map +1 -1
  87. package/dist/esm/messages/prune.mjs.map +1 -1
  88. package/dist/esm/run.mjs +18 -1
  89. package/dist/esm/run.mjs.map +1 -1
  90. package/dist/esm/splitStream.mjs.map +1 -1
  91. package/dist/esm/stream.mjs +24 -1
  92. package/dist/esm/stream.mjs.map +1 -1
  93. package/dist/esm/tools/ToolNode.mjs +20 -1
  94. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  95. package/dist/esm/tools/handlers.mjs +30 -26
  96. package/dist/esm/tools/handlers.mjs.map +1 -1
  97. package/dist/esm/tools/search/anthropic.mjs.map +1 -1
  98. package/dist/esm/tools/search/content.mjs.map +1 -1
  99. package/dist/esm/tools/search/firecrawl.mjs.map +1 -1
  100. package/dist/esm/tools/search/format.mjs.map +1 -1
  101. package/dist/esm/tools/search/highlights.mjs.map +1 -1
  102. package/dist/esm/tools/search/rerankers.mjs.map +1 -1
  103. package/dist/esm/tools/search/schema.mjs +27 -25
  104. package/dist/esm/tools/search/schema.mjs.map +1 -1
  105. package/dist/esm/tools/search/search.mjs +6 -1
  106. package/dist/esm/tools/search/search.mjs.map +1 -1
  107. package/dist/esm/tools/search/serper-scraper.mjs.map +1 -1
  108. package/dist/esm/tools/search/tool.mjs +182 -35
  109. package/dist/esm/tools/search/tool.mjs.map +1 -1
  110. package/dist/esm/tools/search/utils.mjs.map +1 -1
  111. package/dist/esm/utils/graph.mjs.map +1 -1
  112. package/dist/esm/utils/llm.mjs +0 -1
  113. package/dist/esm/utils/llm.mjs.map +1 -1
  114. package/dist/esm/utils/misc.mjs.map +1 -1
  115. package/dist/esm/utils/run.mjs.map +1 -1
  116. package/dist/esm/utils/title.mjs +7 -7
  117. package/dist/esm/utils/title.mjs.map +1 -1
  118. package/dist/types/common/enum.d.ts +1 -2
  119. package/dist/types/llm/bedrock/index.d.ts +36 -0
  120. package/dist/types/llm/openai/index.d.ts +1 -0
  121. package/dist/types/llm/openai/utils/index.d.ts +10 -1
  122. package/dist/types/llm/openrouter/index.d.ts +4 -1
  123. package/dist/types/tools/search/types.d.ts +2 -0
  124. package/dist/types/types/llm.d.ts +3 -8
  125. package/package.json +16 -12
  126. package/src/common/enum.ts +1 -2
  127. package/src/common/index.ts +1 -1
  128. package/src/events.ts +11 -0
  129. package/src/graphs/Graph.ts +2 -1
  130. package/src/instrumentation.ts +25 -22
  131. package/src/llm/anthropic/llm.spec.ts +1442 -1442
  132. package/src/llm/anthropic/types.ts +140 -140
  133. package/src/llm/anthropic/utils/message_inputs.ts +757 -660
  134. package/src/llm/anthropic/utils/output_parsers.ts +133 -133
  135. package/src/llm/anthropic/utils/tools.ts +29 -29
  136. package/src/llm/bedrock/index.ts +128 -0
  137. package/src/llm/fake.ts +133 -133
  138. package/src/llm/google/llm.spec.ts +3 -1
  139. package/src/llm/google/utils/tools.ts +160 -160
  140. package/src/llm/openai/index.ts +126 -0
  141. package/src/llm/openai/types.ts +24 -24
  142. package/src/llm/openai/utils/index.ts +116 -1
  143. package/src/llm/openai/utils/isReasoningModel.test.ts +90 -90
  144. package/src/llm/openrouter/index.ts +222 -1
  145. package/src/llm/providers.ts +2 -7
  146. package/src/llm/text.ts +94 -94
  147. package/src/messages/core.ts +463 -463
  148. package/src/messages/formatAgentMessages.tools.test.ts +400 -400
  149. package/src/messages/formatMessage.test.ts +693 -693
  150. package/src/messages/ids.ts +26 -26
  151. package/src/messages/prune.ts +567 -567
  152. package/src/messages/shiftIndexTokenCountMap.test.ts +81 -81
  153. package/src/mockStream.ts +98 -98
  154. package/src/prompts/collab.ts +5 -5
  155. package/src/prompts/index.ts +1 -1
  156. package/src/prompts/taskmanager.ts +61 -61
  157. package/src/run.ts +22 -4
  158. package/src/scripts/ant_web_search_edge_case.ts +162 -0
  159. package/src/scripts/ant_web_search_error_edge_case.ts +148 -0
  160. package/src/scripts/args.ts +48 -48
  161. package/src/scripts/caching.ts +123 -123
  162. package/src/scripts/code_exec_files.ts +193 -193
  163. package/src/scripts/empty_input.ts +137 -137
  164. package/src/scripts/memory.ts +97 -97
  165. package/src/scripts/test-tools-before-handoff.ts +1 -5
  166. package/src/scripts/thinking.ts +149 -149
  167. package/src/scripts/tools.ts +1 -4
  168. package/src/specs/anthropic.simple.test.ts +67 -0
  169. package/src/specs/spec.utils.ts +3 -3
  170. package/src/specs/token-distribution-edge-case.test.ts +316 -316
  171. package/src/specs/tool-error.test.ts +193 -193
  172. package/src/splitStream.test.ts +691 -691
  173. package/src/splitStream.ts +234 -234
  174. package/src/stream.test.ts +94 -94
  175. package/src/stream.ts +30 -1
  176. package/src/tools/ToolNode.ts +24 -1
  177. package/src/tools/handlers.ts +32 -28
  178. package/src/tools/search/anthropic.ts +51 -51
  179. package/src/tools/search/content.test.ts +173 -173
  180. package/src/tools/search/content.ts +147 -147
  181. package/src/tools/search/direct-url.test.ts +530 -0
  182. package/src/tools/search/firecrawl.ts +210 -210
  183. package/src/tools/search/format.ts +250 -250
  184. package/src/tools/search/highlights.ts +320 -320
  185. package/src/tools/search/index.ts +2 -2
  186. package/src/tools/search/jina-reranker.test.ts +126 -126
  187. package/src/tools/search/output.md +2775 -2775
  188. package/src/tools/search/rerankers.ts +242 -242
  189. package/src/tools/search/schema.ts +65 -63
  190. package/src/tools/search/search.ts +766 -759
  191. package/src/tools/search/serper-scraper.ts +155 -155
  192. package/src/tools/search/test.html +883 -883
  193. package/src/tools/search/test.md +642 -642
  194. package/src/tools/search/test.ts +159 -159
  195. package/src/tools/search/tool.ts +641 -471
  196. package/src/tools/search/types.ts +689 -687
  197. package/src/tools/search/utils.ts +79 -79
  198. package/src/types/index.ts +6 -6
  199. package/src/types/llm.ts +2 -8
  200. package/src/utils/graph.ts +10 -10
  201. package/src/utils/llm.ts +26 -27
  202. package/src/utils/llmConfig.ts +13 -5
  203. package/src/utils/logging.ts +48 -48
  204. package/src/utils/misc.ts +57 -57
  205. package/src/utils/run.ts +100 -100
  206. package/src/utils/title.ts +165 -165
  207. package/dist/cjs/llm/ollama/index.cjs +0 -70
  208. package/dist/cjs/llm/ollama/index.cjs.map +0 -1
  209. package/dist/cjs/llm/ollama/utils.cjs +0 -158
  210. package/dist/cjs/llm/ollama/utils.cjs.map +0 -1
  211. package/dist/esm/llm/ollama/index.mjs +0 -68
  212. package/dist/esm/llm/ollama/index.mjs.map +0 -1
  213. package/dist/esm/llm/ollama/utils.mjs +0 -155
  214. package/dist/esm/llm/ollama/utils.mjs.map +0 -1
  215. package/dist/types/llm/ollama/index.d.ts +0 -8
  216. package/dist/types/llm/ollama/utils.d.ts +0 -7
  217. package/src/llm/ollama/index.ts +0 -92
  218. package/src/llm/ollama/utils.ts +0 -193
  219. package/src/proto/CollabGraph.ts +0 -269
  220. package/src/proto/TaskManager.ts +0 -243
  221. package/src/proto/collab.ts +0 -200
  222. package/src/proto/collab_design.ts +0 -184
  223. package/src/proto/collab_design_v2.ts +0 -224
  224. package/src/proto/collab_design_v3.ts +0 -255
  225. package/src/proto/collab_design_v4.ts +0 -220
  226. package/src/proto/collab_design_v5.ts +0 -251
  227. package/src/proto/collab_graph.ts +0 -181
  228. package/src/proto/collab_original.ts +0 -123
  229. package/src/proto/example.ts +0 -93
  230. package/src/proto/example_new.ts +0 -68
  231. package/src/proto/example_old.ts +0 -201
  232. package/src/proto/example_test.ts +0 -152
  233. package/src/proto/example_test_anthropic.ts +0 -100
  234. package/src/proto/log_stream.ts +0 -202
  235. package/src/proto/main_collab_community_event.ts +0 -133
  236. package/src/proto/main_collab_design_v2.ts +0 -96
  237. package/src/proto/main_collab_design_v4.ts +0 -100
  238. package/src/proto/main_collab_design_v5.ts +0 -135
  239. package/src/proto/main_collab_global_analysis.ts +0 -122
  240. package/src/proto/main_collab_hackathon_event.ts +0 -153
  241. package/src/proto/main_collab_space_mission.ts +0 -153
  242. package/src/proto/main_philosophy.ts +0 -210
  243. package/src/proto/original_script.ts +0 -126
  244. package/src/proto/standard.ts +0 -100
  245. package/src/proto/stream.ts +0 -56
  246. package/src/proto/tasks.ts +0 -118
  247. package/src/proto/tools/global_analysis_tools.ts +0 -86
  248. package/src/proto/tools/space_mission_tools.ts +0 -60
  249. package/src/proto/vertexai.ts +0 -54
  250. package/src/scripts/image.ts +0 -178
@@ -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
+ });