@tambo-ai/client 0.0.1

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 (235) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +100 -0
  3. package/dist/index.d.ts +43 -0
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/index.js +78 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/mcp/elicitation.d.ts +59 -0
  8. package/dist/mcp/elicitation.d.ts.map +1 -0
  9. package/dist/mcp/elicitation.js +27 -0
  10. package/dist/mcp/elicitation.js.map +1 -0
  11. package/dist/mcp/index.d.ts +6 -0
  12. package/dist/mcp/index.d.ts.map +1 -0
  13. package/dist/mcp/index.js +14 -0
  14. package/dist/mcp/index.js.map +1 -0
  15. package/dist/mcp/mcp-client.d.ts +185 -0
  16. package/dist/mcp/mcp-client.d.ts.map +1 -0
  17. package/dist/mcp/mcp-client.js +219 -0
  18. package/dist/mcp/mcp-client.js.map +1 -0
  19. package/dist/mcp/mcp-constants.d.ts +19 -0
  20. package/dist/mcp/mcp-constants.d.ts.map +1 -0
  21. package/dist/mcp/mcp-constants.js +21 -0
  22. package/dist/mcp/mcp-constants.js.map +1 -0
  23. package/dist/model/component-metadata.d.ts +390 -0
  24. package/dist/model/component-metadata.d.ts.map +1 -0
  25. package/dist/model/component-metadata.js +3 -0
  26. package/dist/model/component-metadata.js.map +1 -0
  27. package/dist/model/mcp-server-info.d.ts +72 -0
  28. package/dist/model/mcp-server-info.d.ts.map +1 -0
  29. package/dist/model/mcp-server-info.js +29 -0
  30. package/dist/model/mcp-server-info.js.map +1 -0
  31. package/dist/schema/index.d.ts +5 -0
  32. package/dist/schema/index.d.ts.map +1 -0
  33. package/dist/schema/index.js +15 -0
  34. package/dist/schema/index.js.map +1 -0
  35. package/dist/schema/json-schema.d.ts +42 -0
  36. package/dist/schema/json-schema.d.ts.map +1 -0
  37. package/dist/schema/json-schema.js +114 -0
  38. package/dist/schema/json-schema.js.map +1 -0
  39. package/dist/schema/schema.d.ts +49 -0
  40. package/dist/schema/schema.d.ts.map +1 -0
  41. package/dist/schema/schema.js +129 -0
  42. package/dist/schema/schema.js.map +1 -0
  43. package/dist/schema/standard-schema.d.ts +22 -0
  44. package/dist/schema/standard-schema.d.ts.map +1 -0
  45. package/dist/schema/standard-schema.js +42 -0
  46. package/dist/schema/standard-schema.js.map +1 -0
  47. package/dist/schema/validate.d.ts +14 -0
  48. package/dist/schema/validate.d.ts.map +1 -0
  49. package/dist/schema/validate.js +148 -0
  50. package/dist/schema/validate.js.map +1 -0
  51. package/dist/tambo-client.d.ts +292 -0
  52. package/dist/tambo-client.d.ts.map +1 -0
  53. package/dist/tambo-client.js +508 -0
  54. package/dist/tambo-client.js.map +1 -0
  55. package/dist/tambo-stream.d.ts +112 -0
  56. package/dist/tambo-stream.d.ts.map +1 -0
  57. package/dist/tambo-stream.js +345 -0
  58. package/dist/tambo-stream.js.map +1 -0
  59. package/dist/types/auth.d.ts +24 -0
  60. package/dist/types/auth.d.ts.map +1 -0
  61. package/dist/types/auth.js +3 -0
  62. package/dist/types/auth.js.map +1 -0
  63. package/dist/types/event.d.ts +89 -0
  64. package/dist/types/event.d.ts.map +1 -0
  65. package/dist/types/event.js +57 -0
  66. package/dist/types/event.js.map +1 -0
  67. package/dist/types/message.d.ts +122 -0
  68. package/dist/types/message.d.ts.map +1 -0
  69. package/dist/types/message.js +10 -0
  70. package/dist/types/message.js.map +1 -0
  71. package/dist/types/thread.d.ts +58 -0
  72. package/dist/types/thread.d.ts.map +1 -0
  73. package/dist/types/thread.js +9 -0
  74. package/dist/types/thread.js.map +1 -0
  75. package/dist/types/tool-choice.d.ts +8 -0
  76. package/dist/types/tool-choice.d.ts.map +1 -0
  77. package/dist/types/tool-choice.js +3 -0
  78. package/dist/types/tool-choice.js.map +1 -0
  79. package/dist/utils/event-accumulator.d.ts +165 -0
  80. package/dist/utils/event-accumulator.d.ts.map +1 -0
  81. package/dist/utils/event-accumulator.js +1278 -0
  82. package/dist/utils/event-accumulator.js.map +1 -0
  83. package/dist/utils/json-patch.d.ts +18 -0
  84. package/dist/utils/json-patch.d.ts.map +1 -0
  85. package/dist/utils/json-patch.js +35 -0
  86. package/dist/utils/json-patch.js.map +1 -0
  87. package/dist/utils/keyed-throttle.d.ts +42 -0
  88. package/dist/utils/keyed-throttle.d.ts.map +1 -0
  89. package/dist/utils/keyed-throttle.js +86 -0
  90. package/dist/utils/keyed-throttle.js.map +1 -0
  91. package/dist/utils/registry-conversion.d.ts +53 -0
  92. package/dist/utils/registry-conversion.d.ts.map +1 -0
  93. package/dist/utils/registry-conversion.js +115 -0
  94. package/dist/utils/registry-conversion.js.map +1 -0
  95. package/dist/utils/send-message.d.ts +140 -0
  96. package/dist/utils/send-message.d.ts.map +1 -0
  97. package/dist/utils/send-message.js +183 -0
  98. package/dist/utils/send-message.js.map +1 -0
  99. package/dist/utils/stream-handler.d.ts +45 -0
  100. package/dist/utils/stream-handler.d.ts.map +1 -0
  101. package/dist/utils/stream-handler.js +47 -0
  102. package/dist/utils/stream-handler.js.map +1 -0
  103. package/dist/utils/thread-utils.d.ts +16 -0
  104. package/dist/utils/thread-utils.d.ts.map +1 -0
  105. package/dist/utils/thread-utils.js +34 -0
  106. package/dist/utils/thread-utils.js.map +1 -0
  107. package/dist/utils/tool-call-tracker.d.ts +74 -0
  108. package/dist/utils/tool-call-tracker.d.ts.map +1 -0
  109. package/dist/utils/tool-call-tracker.js +181 -0
  110. package/dist/utils/tool-call-tracker.js.map +1 -0
  111. package/dist/utils/tool-executor.d.ts +67 -0
  112. package/dist/utils/tool-executor.d.ts.map +1 -0
  113. package/dist/utils/tool-executor.js +160 -0
  114. package/dist/utils/tool-executor.js.map +1 -0
  115. package/dist/utils/unstrictify.d.ts +32 -0
  116. package/dist/utils/unstrictify.d.ts.map +1 -0
  117. package/dist/utils/unstrictify.js +160 -0
  118. package/dist/utils/unstrictify.js.map +1 -0
  119. package/esm/index.d.ts +43 -0
  120. package/esm/index.d.ts.map +1 -0
  121. package/esm/index.js +78 -0
  122. package/esm/index.js.map +1 -0
  123. package/esm/mcp/elicitation.d.ts +59 -0
  124. package/esm/mcp/elicitation.d.ts.map +1 -0
  125. package/esm/mcp/elicitation.js +27 -0
  126. package/esm/mcp/elicitation.js.map +1 -0
  127. package/esm/mcp/index.d.ts +6 -0
  128. package/esm/mcp/index.d.ts.map +1 -0
  129. package/esm/mcp/index.js +14 -0
  130. package/esm/mcp/index.js.map +1 -0
  131. package/esm/mcp/mcp-client.d.ts +185 -0
  132. package/esm/mcp/mcp-client.d.ts.map +1 -0
  133. package/esm/mcp/mcp-client.js +219 -0
  134. package/esm/mcp/mcp-client.js.map +1 -0
  135. package/esm/mcp/mcp-constants.d.ts +19 -0
  136. package/esm/mcp/mcp-constants.d.ts.map +1 -0
  137. package/esm/mcp/mcp-constants.js +21 -0
  138. package/esm/mcp/mcp-constants.js.map +1 -0
  139. package/esm/model/component-metadata.d.ts +390 -0
  140. package/esm/model/component-metadata.d.ts.map +1 -0
  141. package/esm/model/component-metadata.js +3 -0
  142. package/esm/model/component-metadata.js.map +1 -0
  143. package/esm/model/mcp-server-info.d.ts +72 -0
  144. package/esm/model/mcp-server-info.d.ts.map +1 -0
  145. package/esm/model/mcp-server-info.js +29 -0
  146. package/esm/model/mcp-server-info.js.map +1 -0
  147. package/esm/schema/index.d.ts +5 -0
  148. package/esm/schema/index.d.ts.map +1 -0
  149. package/esm/schema/index.js +15 -0
  150. package/esm/schema/index.js.map +1 -0
  151. package/esm/schema/json-schema.d.ts +42 -0
  152. package/esm/schema/json-schema.d.ts.map +1 -0
  153. package/esm/schema/json-schema.js +114 -0
  154. package/esm/schema/json-schema.js.map +1 -0
  155. package/esm/schema/schema.d.ts +49 -0
  156. package/esm/schema/schema.d.ts.map +1 -0
  157. package/esm/schema/schema.js +129 -0
  158. package/esm/schema/schema.js.map +1 -0
  159. package/esm/schema/standard-schema.d.ts +22 -0
  160. package/esm/schema/standard-schema.d.ts.map +1 -0
  161. package/esm/schema/standard-schema.js +42 -0
  162. package/esm/schema/standard-schema.js.map +1 -0
  163. package/esm/schema/validate.d.ts +14 -0
  164. package/esm/schema/validate.d.ts.map +1 -0
  165. package/esm/schema/validate.js +148 -0
  166. package/esm/schema/validate.js.map +1 -0
  167. package/esm/tambo-client.d.ts +292 -0
  168. package/esm/tambo-client.d.ts.map +1 -0
  169. package/esm/tambo-client.js +508 -0
  170. package/esm/tambo-client.js.map +1 -0
  171. package/esm/tambo-stream.d.ts +112 -0
  172. package/esm/tambo-stream.d.ts.map +1 -0
  173. package/esm/tambo-stream.js +345 -0
  174. package/esm/tambo-stream.js.map +1 -0
  175. package/esm/types/auth.d.ts +24 -0
  176. package/esm/types/auth.d.ts.map +1 -0
  177. package/esm/types/auth.js +3 -0
  178. package/esm/types/auth.js.map +1 -0
  179. package/esm/types/event.d.ts +89 -0
  180. package/esm/types/event.d.ts.map +1 -0
  181. package/esm/types/event.js +57 -0
  182. package/esm/types/event.js.map +1 -0
  183. package/esm/types/message.d.ts +122 -0
  184. package/esm/types/message.d.ts.map +1 -0
  185. package/esm/types/message.js +10 -0
  186. package/esm/types/message.js.map +1 -0
  187. package/esm/types/thread.d.ts +58 -0
  188. package/esm/types/thread.d.ts.map +1 -0
  189. package/esm/types/thread.js +9 -0
  190. package/esm/types/thread.js.map +1 -0
  191. package/esm/types/tool-choice.d.ts +8 -0
  192. package/esm/types/tool-choice.d.ts.map +1 -0
  193. package/esm/types/tool-choice.js +3 -0
  194. package/esm/types/tool-choice.js.map +1 -0
  195. package/esm/utils/event-accumulator.d.ts +165 -0
  196. package/esm/utils/event-accumulator.d.ts.map +1 -0
  197. package/esm/utils/event-accumulator.js +1278 -0
  198. package/esm/utils/event-accumulator.js.map +1 -0
  199. package/esm/utils/json-patch.d.ts +18 -0
  200. package/esm/utils/json-patch.d.ts.map +1 -0
  201. package/esm/utils/json-patch.js +35 -0
  202. package/esm/utils/json-patch.js.map +1 -0
  203. package/esm/utils/keyed-throttle.d.ts +42 -0
  204. package/esm/utils/keyed-throttle.d.ts.map +1 -0
  205. package/esm/utils/keyed-throttle.js +86 -0
  206. package/esm/utils/keyed-throttle.js.map +1 -0
  207. package/esm/utils/registry-conversion.d.ts +53 -0
  208. package/esm/utils/registry-conversion.d.ts.map +1 -0
  209. package/esm/utils/registry-conversion.js +115 -0
  210. package/esm/utils/registry-conversion.js.map +1 -0
  211. package/esm/utils/send-message.d.ts +140 -0
  212. package/esm/utils/send-message.d.ts.map +1 -0
  213. package/esm/utils/send-message.js +183 -0
  214. package/esm/utils/send-message.js.map +1 -0
  215. package/esm/utils/stream-handler.d.ts +45 -0
  216. package/esm/utils/stream-handler.d.ts.map +1 -0
  217. package/esm/utils/stream-handler.js +47 -0
  218. package/esm/utils/stream-handler.js.map +1 -0
  219. package/esm/utils/thread-utils.d.ts +16 -0
  220. package/esm/utils/thread-utils.d.ts.map +1 -0
  221. package/esm/utils/thread-utils.js +34 -0
  222. package/esm/utils/thread-utils.js.map +1 -0
  223. package/esm/utils/tool-call-tracker.d.ts +74 -0
  224. package/esm/utils/tool-call-tracker.d.ts.map +1 -0
  225. package/esm/utils/tool-call-tracker.js +181 -0
  226. package/esm/utils/tool-call-tracker.js.map +1 -0
  227. package/esm/utils/tool-executor.d.ts +67 -0
  228. package/esm/utils/tool-executor.d.ts.map +1 -0
  229. package/esm/utils/tool-executor.js +160 -0
  230. package/esm/utils/tool-executor.js.map +1 -0
  231. package/esm/utils/unstrictify.d.ts +32 -0
  232. package/esm/utils/unstrictify.d.ts.map +1 -0
  233. package/esm/utils/unstrictify.js +160 -0
  234. package/esm/utils/unstrictify.js.map +1 -0
  235. package/package.json +90 -0
@@ -0,0 +1,1278 @@
1
+ "use strict";
2
+ /**
3
+ * Event Accumulation Logic for Streaming API
4
+ *
5
+ * Implements a reducer that transforms AG-UI event streams into React state.
6
+ * Used with useReducer to accumulate events into thread state.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.PLACEHOLDER_THREAD_ID = exports.UnreachableCaseError = void 0;
10
+ exports.createInitialThreadState = createInitialThreadState;
11
+ exports.isPlaceholderThreadId = isPlaceholderThreadId;
12
+ exports.createInitialState = createInitialState;
13
+ exports.createInitialStateWithMessages = createInitialStateWithMessages;
14
+ exports.streamReducer = streamReducer;
15
+ const core_1 = require("@ag-ui/core");
16
+ const event_1 = require("../types/event");
17
+ const partial_json_1 = require("partial-json");
18
+ const json_patch_1 = require("./json-patch");
19
+ const unstrictify_1 = require("./unstrictify");
20
+ /**
21
+ * Error thrown when an unreachable case is reached in a switch statement.
22
+ * This indicates a programming error where not all cases were handled.
23
+ */
24
+ class UnreachableCaseError extends Error {
25
+ constructor(value) {
26
+ super(`Unreachable case: ${JSON.stringify(value)}`);
27
+ this.name = "UnreachableCaseError";
28
+ }
29
+ }
30
+ exports.UnreachableCaseError = UnreachableCaseError;
31
+ /**
32
+ * Initial streaming state.
33
+ */
34
+ const initialStreamingState = {
35
+ status: "idle",
36
+ };
37
+ /**
38
+ * Create initial thread state for a new thread.
39
+ * @param threadId - Unique thread identifier
40
+ * @returns Initial thread state
41
+ */
42
+ function createInitialThreadState(threadId) {
43
+ const now = new Date().toISOString();
44
+ return {
45
+ thread: {
46
+ id: threadId,
47
+ messages: [],
48
+ status: "idle",
49
+ createdAt: now,
50
+ updatedAt: now,
51
+ lastRunCancelled: false,
52
+ },
53
+ streaming: initialStreamingState,
54
+ accumulatingToolArgs: {},
55
+ };
56
+ }
57
+ /**
58
+ * Placeholder thread ID used for new threads before they get a real ID from the server.
59
+ * This allows optimistic UI updates (showing user messages immediately) before the
60
+ * server responds with the actual thread ID.
61
+ */
62
+ exports.PLACEHOLDER_THREAD_ID = "placeholder";
63
+ /**
64
+ * Check if a thread ID is a placeholder (not a real API thread ID).
65
+ * @param threadId - Thread ID to check
66
+ * @returns True if this is a placeholder thread ID
67
+ */
68
+ function isPlaceholderThreadId(threadId) {
69
+ return threadId === exports.PLACEHOLDER_THREAD_ID;
70
+ }
71
+ /**
72
+ * Create initial stream state with placeholder thread.
73
+ * @returns Initial stream state
74
+ */
75
+ function createInitialState() {
76
+ return {
77
+ threadMap: {
78
+ [exports.PLACEHOLDER_THREAD_ID]: createInitialThreadState(exports.PLACEHOLDER_THREAD_ID),
79
+ },
80
+ currentThreadId: exports.PLACEHOLDER_THREAD_ID,
81
+ };
82
+ }
83
+ /**
84
+ * Create initial stream state with placeholder thread seeded with initial messages.
85
+ * The messages are converted from InputMessage format to TamboThreadMessage format
86
+ * for immediate UI display before any API call.
87
+ * @param initialMessages - Messages to seed the placeholder thread with
88
+ * @returns Initial stream state with messages in the placeholder thread
89
+ */
90
+ function createInitialStateWithMessages(initialMessages) {
91
+ const placeholderState = createInitialThreadState(exports.PLACEHOLDER_THREAD_ID);
92
+ const messages = initialMessages.map((msg) => ({
93
+ id: `initial_${crypto.randomUUID()}`,
94
+ role: msg.role,
95
+ content: msg.content.map((c) => {
96
+ if (c.type === "text") {
97
+ return { type: "text", text: c.text };
98
+ }
99
+ return c;
100
+ }),
101
+ }));
102
+ return {
103
+ threadMap: {
104
+ [exports.PLACEHOLDER_THREAD_ID]: {
105
+ ...placeholderState,
106
+ thread: {
107
+ ...placeholderState.thread,
108
+ messages,
109
+ },
110
+ },
111
+ },
112
+ currentThreadId: exports.PLACEHOLDER_THREAD_ID,
113
+ };
114
+ }
115
+ /**
116
+ * Replace a message at a specific index immutably.
117
+ * @param messages - Current messages array
118
+ * @param index - Index of message to replace
119
+ * @param updatedMessage - New message to insert
120
+ * @returns New messages array with the message replaced
121
+ */
122
+ function updateMessageAtIndex(messages, index, updatedMessage) {
123
+ return [
124
+ ...messages.slice(0, index),
125
+ updatedMessage,
126
+ ...messages.slice(index + 1),
127
+ ];
128
+ }
129
+ /**
130
+ * Replace a content block at a specific index within a message's content immutably.
131
+ * @param content - Current content array
132
+ * @param index - Index of content to replace
133
+ * @param updatedContent - New content to insert
134
+ * @returns New content array with the content replaced
135
+ */
136
+ function updateContentAtIndex(content, index, updatedContent) {
137
+ return [
138
+ ...content.slice(0, index),
139
+ updatedContent,
140
+ ...content.slice(index + 1),
141
+ ];
142
+ }
143
+ /**
144
+ * Find a content block by ID across all messages, searching from most recent.
145
+ *
146
+ * TODO: This is O(n*m) where n = messages and m = content blocks per message.
147
+ * For high-frequency streaming with many messages, consider maintaining an
148
+ * index map of contentId -> {messageIndex, contentIndex} that gets updated
149
+ * when content blocks are created.
150
+ * @param messages - Messages to search
151
+ * @param contentType - Type of content to find ("component" or "tool_use")
152
+ * @param contentId - ID of the content block
153
+ * @param eventName - Name of the event (for error messages)
154
+ * @returns Location of the content block
155
+ * @throws {Error} If content not found
156
+ */
157
+ function findContentById(messages, contentType, contentId, eventName) {
158
+ for (let i = messages.length - 1; i >= 0; i--) {
159
+ const idx = messages[i].content.findIndex((c) => c.type === contentType && c.id === contentId);
160
+ if (idx !== -1) {
161
+ return { messageIndex: i, contentIndex: idx };
162
+ }
163
+ }
164
+ throw new Error(`${contentType} ${contentId} not found for ${eventName}`);
165
+ }
166
+ /**
167
+ * Create updated thread state with new messages.
168
+ * @param threadState - Current thread state
169
+ * @param messages - New messages array
170
+ * @returns Updated thread state
171
+ */
172
+ function updateThreadMessages(threadState, messages) {
173
+ return {
174
+ ...threadState,
175
+ thread: {
176
+ ...threadState.thread,
177
+ messages,
178
+ updatedAt: new Date().toISOString(),
179
+ },
180
+ };
181
+ }
182
+ /**
183
+ * Stream reducer that accumulates events into thread state.
184
+ *
185
+ * This reducer handles all AG-UI events and Tambo custom events,
186
+ * transforming them into immutable state updates per thread.
187
+ * @param state - Current stream state
188
+ * @param action - Action to process
189
+ * @returns Updated stream state
190
+ */
191
+ function streamReducer(state, action) {
192
+ // Handle non-event actions first
193
+ switch (action.type) {
194
+ case "INIT_THREAD": {
195
+ const { threadId, initialThread } = action;
196
+ // Don't overwrite existing thread
197
+ if (state.threadMap[threadId]) {
198
+ return state;
199
+ }
200
+ const baseState = createInitialThreadState(threadId);
201
+ const threadState = initialThread
202
+ ? {
203
+ ...baseState,
204
+ thread: {
205
+ ...baseState.thread,
206
+ ...initialThread,
207
+ id: threadId,
208
+ },
209
+ }
210
+ : baseState;
211
+ return {
212
+ ...state,
213
+ threadMap: {
214
+ ...state.threadMap,
215
+ [threadId]: threadState,
216
+ },
217
+ };
218
+ }
219
+ case "SET_CURRENT_THREAD": {
220
+ return {
221
+ ...state,
222
+ currentThreadId: action.threadId,
223
+ };
224
+ }
225
+ case "START_NEW_THREAD": {
226
+ // Atomic action: initialize thread AND set as current in one reducer pass.
227
+ // Always overwrites any existing thread state for this ID — the whole
228
+ // point of START_NEW_THREAD is to reset and start fresh (e.g. the
229
+ // placeholder thread must be wiped clean on every new conversation).
230
+ const { threadId, initialThread } = action;
231
+ const baseState = createInitialThreadState(threadId);
232
+ const threadState = initialThread
233
+ ? {
234
+ ...baseState,
235
+ thread: {
236
+ ...baseState.thread,
237
+ ...initialThread,
238
+ id: threadId,
239
+ },
240
+ }
241
+ : baseState;
242
+ return {
243
+ ...state,
244
+ threadMap: {
245
+ ...state.threadMap,
246
+ [threadId]: threadState,
247
+ },
248
+ currentThreadId: threadId,
249
+ };
250
+ }
251
+ case "LOAD_THREAD_MESSAGES": {
252
+ return handleLoadThreadMessages(state, action);
253
+ }
254
+ case "SET_LAST_COMPLETED_RUN_ID": {
255
+ const threadState = state.threadMap[action.threadId] ??
256
+ createInitialThreadState(action.threadId);
257
+ return {
258
+ ...state,
259
+ threadMap: {
260
+ ...state.threadMap,
261
+ [action.threadId]: {
262
+ ...threadState,
263
+ lastCompletedRunId: action.lastCompletedRunId,
264
+ },
265
+ },
266
+ };
267
+ }
268
+ case "UPDATE_THREAD_NAME": {
269
+ const threadState = state.threadMap[action.threadId];
270
+ if (!threadState) {
271
+ return state;
272
+ }
273
+ return {
274
+ ...state,
275
+ threadMap: {
276
+ ...state.threadMap,
277
+ [action.threadId]: {
278
+ ...threadState,
279
+ thread: {
280
+ ...threadState.thread,
281
+ name: action.name,
282
+ },
283
+ },
284
+ },
285
+ };
286
+ }
287
+ case "EVENT":
288
+ // Fall through to event handling below
289
+ break;
290
+ }
291
+ // Handle EVENT action
292
+ const { event, threadId } = action;
293
+ const effectiveThreadId = event.type === core_1.EventType.RUN_STARTED ? event.threadId : threadId;
294
+ // Get the current thread state, auto-initializing if needed
295
+ // Auto-initialization handles the case where events arrive before explicit thread init
296
+ // (e.g., when creating a new thread and RUN_STARTED is the first event)
297
+ let threadState = state.threadMap[effectiveThreadId];
298
+ let updatedState = state;
299
+ if (!threadState) {
300
+ // Auto-initialize the thread to avoid dropping events
301
+ threadState = createInitialThreadState(effectiveThreadId);
302
+ updatedState = {
303
+ ...state,
304
+ threadMap: {
305
+ ...state.threadMap,
306
+ [effectiveThreadId]: threadState,
307
+ },
308
+ };
309
+ }
310
+ // Handle placeholder thread migration for RUN_STARTED events
311
+ // When a new thread is created, messages may have been added to the placeholder thread
312
+ // for immediate UI feedback. Now that we have the real threadId, migrate those messages.
313
+ if (event.type === core_1.EventType.RUN_STARTED &&
314
+ effectiveThreadId !== exports.PLACEHOLDER_THREAD_ID) {
315
+ const placeholderState = updatedState.threadMap[exports.PLACEHOLDER_THREAD_ID];
316
+ if (placeholderState?.thread.messages.length) {
317
+ // Prepend placeholder thread messages to the real thread
318
+ threadState = {
319
+ ...threadState,
320
+ thread: {
321
+ ...threadState.thread,
322
+ messages: [
323
+ ...placeholderState.thread.messages,
324
+ ...threadState.thread.messages,
325
+ ],
326
+ },
327
+ };
328
+ // Reset placeholder thread to empty state
329
+ const resetPlaceholder = createInitialThreadState(exports.PLACEHOLDER_THREAD_ID);
330
+ updatedState = {
331
+ ...updatedState,
332
+ threadMap: {
333
+ ...updatedState.threadMap,
334
+ [exports.PLACEHOLDER_THREAD_ID]: resetPlaceholder,
335
+ [effectiveThreadId]: threadState,
336
+ },
337
+ // Only switch selection if the user is currently on the placeholder thread
338
+ currentThreadId: isPlaceholderThreadId(updatedState.currentThreadId)
339
+ ? effectiveThreadId
340
+ : updatedState.currentThreadId,
341
+ };
342
+ }
343
+ }
344
+ // Process the event for this specific thread
345
+ let updatedThreadState;
346
+ // Switch on event.type - AGUIEvent is a discriminated union so TypeScript
347
+ // automatically narrows the type in each case branch
348
+ switch (event.type) {
349
+ case core_1.EventType.RUN_STARTED:
350
+ updatedThreadState = handleRunStarted(threadState, event);
351
+ break;
352
+ case core_1.EventType.RUN_FINISHED:
353
+ updatedThreadState = handleRunFinished(threadState, event);
354
+ break;
355
+ case core_1.EventType.RUN_ERROR:
356
+ updatedThreadState = handleRunError(threadState, event);
357
+ break;
358
+ case core_1.EventType.TEXT_MESSAGE_START:
359
+ updatedThreadState = handleTextMessageStart(threadState, event);
360
+ break;
361
+ case core_1.EventType.TEXT_MESSAGE_CONTENT:
362
+ updatedThreadState = handleTextMessageContent(threadState, event);
363
+ break;
364
+ case core_1.EventType.TEXT_MESSAGE_END:
365
+ updatedThreadState = handleTextMessageEnd(threadState, event);
366
+ break;
367
+ case core_1.EventType.TOOL_CALL_START:
368
+ updatedThreadState = handleToolCallStart(threadState, event);
369
+ break;
370
+ case core_1.EventType.TOOL_CALL_ARGS:
371
+ updatedThreadState = handleToolCallArgs(threadState, event, action.parsedToolArgs, action.toolSchemas);
372
+ break;
373
+ case core_1.EventType.TOOL_CALL_END:
374
+ updatedThreadState = handleToolCallEnd(threadState, event, action.toolSchemas);
375
+ break;
376
+ case core_1.EventType.TOOL_CALL_RESULT:
377
+ updatedThreadState = handleToolCallResult(threadState, event);
378
+ break;
379
+ case core_1.EventType.CUSTOM:
380
+ updatedThreadState = handleCustomEvent(threadState, event);
381
+ break;
382
+ case core_1.EventType.THINKING_TEXT_MESSAGE_START:
383
+ updatedThreadState = handleThinkingTextMessageStart(threadState, event);
384
+ break;
385
+ case core_1.EventType.THINKING_TEXT_MESSAGE_CONTENT:
386
+ updatedThreadState = handleThinkingTextMessageContent(threadState, event);
387
+ break;
388
+ case core_1.EventType.THINKING_TEXT_MESSAGE_END:
389
+ updatedThreadState = handleThinkingTextMessageEnd(threadState, event);
390
+ break;
391
+ // Unsupported AG-UI event types - may be added in future phases
392
+ case core_1.EventType.TEXT_MESSAGE_CHUNK:
393
+ case core_1.EventType.TOOL_CALL_CHUNK:
394
+ case core_1.EventType.THINKING_START:
395
+ case core_1.EventType.THINKING_END:
396
+ case core_1.EventType.STATE_SNAPSHOT:
397
+ case core_1.EventType.STATE_DELTA:
398
+ case core_1.EventType.MESSAGES_SNAPSHOT:
399
+ case core_1.EventType.ACTIVITY_SNAPSHOT:
400
+ case core_1.EventType.ACTIVITY_DELTA:
401
+ case core_1.EventType.RAW:
402
+ case core_1.EventType.STEP_STARTED:
403
+ case core_1.EventType.STEP_FINISHED:
404
+ // Log warning - these events are being ignored
405
+ console.warn(`[StreamReducer] Received unsupported event type: ${event.type}. ` +
406
+ `This event will be ignored.`);
407
+ return updatedState;
408
+ default: {
409
+ // Exhaustiveness check: if a new event type is added to AGUIEvent
410
+ // and not handled above, TypeScript will error here
411
+ const _exhaustiveCheck = event;
412
+ throw new UnreachableCaseError(_exhaustiveCheck);
413
+ }
414
+ }
415
+ // Return updated state with modified thread
416
+ return {
417
+ ...updatedState,
418
+ threadMap: {
419
+ ...updatedState.threadMap,
420
+ [effectiveThreadId]: updatedThreadState,
421
+ },
422
+ };
423
+ }
424
+ /**
425
+ * Handle RUN_STARTED event.
426
+ * @param threadState - Current thread state
427
+ * @param event - Run started event
428
+ * @returns Updated thread state
429
+ */
430
+ function handleRunStarted(threadState, event) {
431
+ return {
432
+ ...threadState,
433
+ thread: {
434
+ ...threadState.thread,
435
+ status: "streaming",
436
+ updatedAt: new Date().toISOString(),
437
+ // Reset lastRunCancelled when a new run starts
438
+ lastRunCancelled: false,
439
+ },
440
+ streaming: {
441
+ status: "streaming",
442
+ runId: event.runId,
443
+ startTime: event.timestamp ?? Date.now(),
444
+ },
445
+ };
446
+ }
447
+ /**
448
+ * Handle RUN_FINISHED event.
449
+ * @param threadState - Current thread state
450
+ * @param event - Run finished event containing the completed run's ID
451
+ * @returns Updated thread state
452
+ */
453
+ function handleRunFinished(threadState, event) {
454
+ return {
455
+ ...threadState,
456
+ lastCompletedRunId: event.runId ??
457
+ threadState.streaming.runId ??
458
+ threadState.lastCompletedRunId,
459
+ thread: {
460
+ ...threadState.thread,
461
+ status: "idle",
462
+ updatedAt: new Date().toISOString(),
463
+ },
464
+ streaming: {
465
+ ...threadState.streaming,
466
+ status: "idle",
467
+ },
468
+ };
469
+ }
470
+ /**
471
+ * Handle RUN_ERROR event.
472
+ * Sets lastRunCancelled if the error code is "CANCELLED".
473
+ * @param threadState - Current thread state
474
+ * @param event - Run error event
475
+ * @returns Updated thread state
476
+ */
477
+ function handleRunError(threadState, event) {
478
+ const isCancelled = event.code === "CANCELLED";
479
+ return {
480
+ ...threadState,
481
+ thread: {
482
+ ...threadState.thread,
483
+ status: "idle",
484
+ updatedAt: new Date().toISOString(),
485
+ lastRunCancelled: isCancelled,
486
+ },
487
+ streaming: {
488
+ ...threadState.streaming,
489
+ status: "idle",
490
+ error: isCancelled
491
+ ? undefined
492
+ : {
493
+ message: event.message,
494
+ code: event.code,
495
+ },
496
+ },
497
+ };
498
+ }
499
+ /**
500
+ * Handle TEXT_MESSAGE_START event.
501
+ * Creates a new message or reuses an ephemeral reasoning message.
502
+ * @param threadState - Current thread state
503
+ * @param event - Text message start event
504
+ * @returns Updated thread state
505
+ */
506
+ function handleTextMessageStart(threadState, event) {
507
+ const isAssistant = event.role !== "user";
508
+ const messages = threadState.thread.messages;
509
+ // For assistant messages, check if there's an ephemeral message with reasoning
510
+ // that we should merge into instead of creating a new message.
511
+ if (isAssistant) {
512
+ const ephemeralIndex = messages.findIndex((m) => m.role === "assistant" &&
513
+ m.id.startsWith("ephemeral_") &&
514
+ m.reasoning &&
515
+ m.reasoning.length > 0);
516
+ if (ephemeralIndex !== -1) {
517
+ // Update the ephemeral message with the real ID
518
+ const ephemeralMessage = messages[ephemeralIndex];
519
+ const updatedMessages = [...messages];
520
+ updatedMessages[ephemeralIndex] = {
521
+ ...ephemeralMessage,
522
+ id: event.messageId,
523
+ };
524
+ return {
525
+ ...threadState,
526
+ thread: {
527
+ ...threadState.thread,
528
+ messages: updatedMessages,
529
+ updatedAt: new Date().toISOString(),
530
+ },
531
+ streaming: {
532
+ ...threadState.streaming,
533
+ messageId: event.messageId,
534
+ },
535
+ };
536
+ }
537
+ }
538
+ // Check if a message with this ID already exists (e.g., created by
539
+ // handleMessageParent). If so, just update streaming state to track it.
540
+ const existingIndex = messages.findIndex((m) => m.id === event.messageId);
541
+ if (existingIndex !== -1) {
542
+ return {
543
+ ...threadState,
544
+ thread: {
545
+ ...threadState.thread,
546
+ updatedAt: new Date().toISOString(),
547
+ },
548
+ streaming: {
549
+ ...threadState.streaming,
550
+ messageId: event.messageId,
551
+ },
552
+ };
553
+ }
554
+ // No existing message to reuse - create a new message
555
+ const newMessage = {
556
+ id: event.messageId,
557
+ role: isAssistant ? "assistant" : "user",
558
+ content: [],
559
+ createdAt: new Date().toISOString(),
560
+ };
561
+ return {
562
+ ...threadState,
563
+ thread: {
564
+ ...threadState.thread,
565
+ messages: [...messages, newMessage],
566
+ updatedAt: new Date().toISOString(),
567
+ },
568
+ streaming: {
569
+ ...threadState.streaming,
570
+ messageId: event.messageId,
571
+ },
572
+ };
573
+ }
574
+ /**
575
+ * Handle TEXT_MESSAGE_CONTENT event.
576
+ * Appends text content to the current message.
577
+ * @param threadState - Current thread state
578
+ * @param event - Text message content event
579
+ * @returns Updated thread state
580
+ */
581
+ function handleTextMessageContent(threadState, event) {
582
+ const messageId = event.messageId;
583
+ const messages = threadState.thread.messages;
584
+ // Find the message to update
585
+ const messageIndex = messages.findIndex((m) => m.id === messageId);
586
+ if (messageIndex === -1) {
587
+ throw new Error(`Message ${messageId} not found for TEXT_MESSAGE_CONTENT event`);
588
+ }
589
+ const message = messages[messageIndex];
590
+ const content = message.content;
591
+ // Find or create text content block
592
+ const lastContent = content[content.length - 1];
593
+ const isTextBlock = lastContent?.type === "text";
594
+ const updatedContent = isTextBlock
595
+ ? [
596
+ ...content.slice(0, -1),
597
+ {
598
+ ...lastContent,
599
+ text: lastContent.text + event.delta,
600
+ },
601
+ ]
602
+ : [
603
+ ...content,
604
+ {
605
+ type: "text",
606
+ text: event.delta,
607
+ },
608
+ ];
609
+ const updatedMessage = {
610
+ ...message,
611
+ content: updatedContent,
612
+ };
613
+ return updateThreadMessages(threadState, updateMessageAtIndex(messages, messageIndex, updatedMessage));
614
+ }
615
+ /**
616
+ * Handle TEXT_MESSAGE_END event.
617
+ * Marks the message as complete.
618
+ * @param threadState - Current thread state
619
+ * @param event - Text message end event
620
+ * @returns Updated thread state
621
+ */
622
+ function handleTextMessageEnd(threadState, event) {
623
+ const activeMessageId = threadState.streaming.messageId;
624
+ if (activeMessageId && event.messageId !== activeMessageId) {
625
+ throw new Error(`TEXT_MESSAGE_END messageId mismatch (thread ${threadState.thread.id}): expected ${activeMessageId}, got ${event.messageId}`);
626
+ }
627
+ return {
628
+ ...threadState,
629
+ streaming: {
630
+ ...threadState.streaming,
631
+ messageId: undefined,
632
+ },
633
+ };
634
+ }
635
+ /**
636
+ * Handle TOOL_CALL_START event.
637
+ * Adds a tool use content block to the current message.
638
+ * If no message exists, creates a synthetic assistant message to hold the tool call.
639
+ * @param threadState - Current thread state
640
+ * @param event - Tool call start event
641
+ * @returns Updated thread state
642
+ */
643
+ function handleToolCallStart(threadState, event) {
644
+ const messageId = event.parentMessageId;
645
+ const messages = threadState.thread.messages;
646
+ // Find the parent message for this tool call.
647
+ // If parentMessageId is provided, look it up directly.
648
+ // Otherwise fall back to the last message, but only if it's an assistant message.
649
+ // If the last message isn't assistant (e.g. it's the user message and the LLM
650
+ // didn't produce any text before the tool call), we'll create a synthetic
651
+ // assistant message below.
652
+ let messageIndex;
653
+ if (messageId) {
654
+ messageIndex = messages.findIndex((m) => m.id === messageId);
655
+ }
656
+ else {
657
+ const lastIndex = messages.length - 1;
658
+ messageIndex =
659
+ lastIndex >= 0 && messages[lastIndex].role === "assistant"
660
+ ? lastIndex
661
+ : -1;
662
+ }
663
+ const newContent = {
664
+ type: "tool_use",
665
+ id: event.toolCallId,
666
+ name: event.toolCallName,
667
+ input: {},
668
+ };
669
+ // If no suitable assistant message found, create a synthetic one for the tool call
670
+ if (messageIndex === -1) {
671
+ const syntheticMessageId = messageId ?? `msg_tool_${event.toolCallId}`;
672
+ const syntheticMessage = {
673
+ id: syntheticMessageId,
674
+ role: "assistant",
675
+ content: [newContent],
676
+ createdAt: new Date().toISOString(),
677
+ };
678
+ return {
679
+ ...threadState,
680
+ thread: {
681
+ ...threadState.thread,
682
+ messages: [...messages, syntheticMessage],
683
+ updatedAt: new Date().toISOString(),
684
+ },
685
+ streaming: {
686
+ ...threadState.streaming,
687
+ messageId: syntheticMessageId,
688
+ },
689
+ };
690
+ }
691
+ const message = messages[messageIndex];
692
+ const updatedMessage = {
693
+ ...message,
694
+ content: [...message.content, newContent],
695
+ };
696
+ return updateThreadMessages(threadState, updateMessageAtIndex(messages, messageIndex, updatedMessage));
697
+ }
698
+ /**
699
+ * Handle TOOL_CALL_ARGS event.
700
+ * Accumulates JSON string deltas for tool call arguments and optimistically
701
+ * parses the partial JSON to update the tool_use content block in real-time.
702
+ * When toolSchemas is provided, the parsed args are unstrictified so the
703
+ * reducer always emits schema-valid values during streaming.
704
+ * The final authoritative parse still happens at TOOL_CALL_END.
705
+ * @param threadState - Current thread state
706
+ * @param event - Tool call args event
707
+ * @param parsedToolArgs - Pre-parsed args from the hook (already unstrictified)
708
+ * @param toolSchemas - Original tool schemas for unstrictification
709
+ * @returns Updated thread state
710
+ */
711
+ function handleToolCallArgs(threadState, event, parsedToolArgs, toolSchemas) {
712
+ const toolCallId = event.toolCallId;
713
+ // Accumulate the JSON string delta
714
+ const accumulatedArgs = threadState.accumulatingToolArgs;
715
+ const existingArgs = accumulatedArgs[toolCallId] ?? "";
716
+ const newAccumulatedJson = existingArgs + event.delta;
717
+ const newAccumulatedArgs = { ...accumulatedArgs };
718
+ newAccumulatedArgs[toolCallId] = newAccumulatedJson;
719
+ // Use pre-parsed args if provided, otherwise parse partial JSON ourselves
720
+ let parsedInput = parsedToolArgs;
721
+ if (!parsedInput) {
722
+ try {
723
+ const parsed = (0, partial_json_1.parse)(newAccumulatedJson);
724
+ if (typeof parsed === "object" &&
725
+ parsed !== null &&
726
+ !Array.isArray(parsed)) {
727
+ parsedInput = parsed;
728
+ }
729
+ }
730
+ catch {
731
+ // Partial JSON not parseable yet — leave input unchanged
732
+ }
733
+ }
734
+ if (!parsedInput) {
735
+ return {
736
+ ...threadState,
737
+ accumulatingToolArgs: newAccumulatedArgs,
738
+ };
739
+ }
740
+ // Update the tool_use content block with partially parsed input
741
+ const messages = threadState.thread.messages;
742
+ const { messageIndex, contentIndex } = findContentById(messages, "tool_use", toolCallId, "TOOL_CALL_ARGS event");
743
+ const message = messages[messageIndex];
744
+ const toolUseContent = message.content[contentIndex];
745
+ if (toolUseContent.type !== "tool_use") {
746
+ throw new Error(`Content at index ${contentIndex} is not a tool_use block for TOOL_CALL_ARGS event`);
747
+ }
748
+ // Unstrictify if we have the original schema for this tool
749
+ if (toolSchemas) {
750
+ const schema = toolSchemas.get(toolUseContent.name);
751
+ if (schema) {
752
+ parsedInput = (0, unstrictify_1.unstrictifyToolCallParamsFromSchema)(schema, parsedInput);
753
+ }
754
+ }
755
+ const updatedContent = {
756
+ ...toolUseContent,
757
+ input: parsedInput,
758
+ };
759
+ const updatedMessage = {
760
+ ...message,
761
+ content: updateContentAtIndex(message.content, contentIndex, updatedContent),
762
+ };
763
+ return {
764
+ ...updateThreadMessages(threadState, updateMessageAtIndex(messages, messageIndex, updatedMessage)),
765
+ accumulatingToolArgs: newAccumulatedArgs,
766
+ };
767
+ }
768
+ /**
769
+ * Handle TOOL_CALL_END event.
770
+ * Parses the accumulated JSON arguments, unstrictifies them if possible,
771
+ * and updates the tool_use content block.
772
+ * @param threadState - Current thread state
773
+ * @param event - Tool call end event
774
+ * @param toolSchemas - Original tool schemas for unstrictification
775
+ * @returns Updated thread state
776
+ */
777
+ function handleToolCallEnd(threadState, event, toolSchemas) {
778
+ const toolCallId = event.toolCallId;
779
+ const messages = threadState.thread.messages;
780
+ // Get accumulated JSON args string
781
+ const accumulatedJson = threadState.accumulatingToolArgs[toolCallId];
782
+ if (!accumulatedJson) {
783
+ // No args accumulated - tool call has empty input
784
+ return threadState;
785
+ }
786
+ // Parse the accumulated JSON - tool inputs are always objects
787
+ let parsedInput;
788
+ try {
789
+ parsedInput = JSON.parse(accumulatedJson);
790
+ }
791
+ catch (error) {
792
+ throw new Error(`Failed to parse tool call arguments for ${toolCallId}: ${error instanceof Error ? error.message : String(error)}. JSON: ${accumulatedJson}`);
793
+ }
794
+ // Find the tool_use content block
795
+ const { messageIndex, contentIndex } = findContentById(messages, "tool_use", toolCallId, "TOOL_CALL_END event");
796
+ const message = messages[messageIndex];
797
+ const toolUseContent = message.content[contentIndex];
798
+ if (toolUseContent.type !== "tool_use") {
799
+ throw new Error(`Content at index ${contentIndex} is not a tool_use block for TOOL_CALL_END event`);
800
+ }
801
+ // Unstrictify parsed input if we have the original schema
802
+ if (toolSchemas) {
803
+ const schema = toolSchemas.get(toolUseContent.name);
804
+ if (schema) {
805
+ parsedInput = (0, unstrictify_1.unstrictifyToolCallParamsFromSchema)(schema, parsedInput);
806
+ }
807
+ }
808
+ // Update the tool_use content with parsed input
809
+ const updatedContent = {
810
+ ...toolUseContent,
811
+ input: parsedInput,
812
+ };
813
+ const updatedMessage = {
814
+ ...message,
815
+ content: updateContentAtIndex(message.content, contentIndex, updatedContent),
816
+ };
817
+ // Clear accumulated args for this tool call
818
+ const newAccumulatingToolArgs = { ...threadState.accumulatingToolArgs };
819
+ delete newAccumulatingToolArgs[toolCallId];
820
+ return {
821
+ ...updateThreadMessages(threadState, updateMessageAtIndex(messages, messageIndex, updatedMessage)),
822
+ accumulatingToolArgs: newAccumulatingToolArgs,
823
+ };
824
+ }
825
+ /**
826
+ * Handle TOOL_CALL_RESULT event.
827
+ * Adds tool result to the specified message.
828
+ * @param threadState - Current thread state
829
+ * @param event - Tool call result event
830
+ * @returns Updated thread state
831
+ */
832
+ function handleToolCallResult(threadState, event) {
833
+ const messageId = event.messageId;
834
+ const messages = threadState.thread.messages;
835
+ // Find the message
836
+ const messageIndex = messages.findIndex((m) => m.id === messageId);
837
+ if (messageIndex === -1) {
838
+ throw new Error(`Message ${messageId} not found for TOOL_CALL_RESULT event`);
839
+ }
840
+ const message = messages[messageIndex];
841
+ // Add tool result content
842
+ const newContent = {
843
+ type: "tool_result",
844
+ toolUseId: event.toolCallId,
845
+ content: [
846
+ {
847
+ type: "text",
848
+ text: event.content,
849
+ },
850
+ ],
851
+ };
852
+ const updatedMessage = {
853
+ ...message,
854
+ content: [...message.content, newContent],
855
+ };
856
+ return updateThreadMessages(threadState, updateMessageAtIndex(messages, messageIndex, updatedMessage));
857
+ }
858
+ /**
859
+ * Handle custom events (Tambo-specific).
860
+ * @param threadState - Current thread state
861
+ * @param event - Custom event (already narrowed from AGUIEvent)
862
+ * @returns Updated thread state
863
+ */
864
+ function handleCustomEvent(threadState, event) {
865
+ // Use centralized casting function to get properly typed Tambo event
866
+ const customEvent = (0, event_1.asTamboCustomEvent)(event);
867
+ if (!customEvent) {
868
+ // Unknown custom event - log and return unchanged
869
+ console.warn(`[StreamReducer] Unknown custom event name: ${event.name}`);
870
+ return threadState;
871
+ }
872
+ switch (customEvent.name) {
873
+ case "tambo.component.start":
874
+ return handleComponentStart(threadState, customEvent);
875
+ case "tambo.component.props_delta":
876
+ return handleComponentDelta(threadState, customEvent, "props");
877
+ case "tambo.component.state_delta":
878
+ return handleComponentDelta(threadState, customEvent, "state");
879
+ case "tambo.component.end":
880
+ return handleComponentEnd(threadState, customEvent);
881
+ case "tambo.run.awaiting_input":
882
+ return handleRunAwaitingInput(threadState, customEvent);
883
+ case "tambo.message.parent":
884
+ return handleMessageParent(threadState, customEvent);
885
+ default: {
886
+ // Exhaustiveness check: if a new event type is added to TamboCustomEvent
887
+ // and not handled here, TypeScript will error
888
+ const _exhaustiveCheck = customEvent;
889
+ throw new UnreachableCaseError(_exhaustiveCheck);
890
+ }
891
+ }
892
+ }
893
+ /**
894
+ * Handle tambo.component.start event.
895
+ * Adds a component content block to the message with 'started' streaming state.
896
+ * @param threadState - Current thread state
897
+ * @param event - Component start event
898
+ * @returns Updated thread state
899
+ */
900
+ function handleComponentStart(threadState, event) {
901
+ const messageId = event.value.messageId;
902
+ let messages = threadState.thread.messages;
903
+ // Find the message, or create it if it doesn't exist.
904
+ // The backend may emit component events before TEXT_MESSAGE_START when
905
+ // the LLM outputs a component tool call without preceding text.
906
+ let messageIndex = messages.findIndex((m) => m.id === messageId);
907
+ if (messageIndex === -1) {
908
+ // Create a new assistant message for this component
909
+ const newMessage = {
910
+ id: messageId,
911
+ role: "assistant",
912
+ content: [],
913
+ createdAt: new Date().toISOString(),
914
+ };
915
+ messages = [...messages, newMessage];
916
+ messageIndex = messages.length - 1;
917
+ // Update thread state with the new message before adding the component
918
+ threadState = updateThreadMessages(threadState, messages);
919
+ }
920
+ const message = messages[messageIndex];
921
+ // Add component content block with 'started' streaming state
922
+ const newContent = {
923
+ type: "component",
924
+ id: event.value.componentId,
925
+ name: event.value.componentName,
926
+ props: {},
927
+ streamingState: "started",
928
+ };
929
+ const updatedMessage = {
930
+ ...message,
931
+ content: [...message.content, newContent],
932
+ };
933
+ return updateThreadMessages(threadState, updateMessageAtIndex(messages, messageIndex, updatedMessage));
934
+ }
935
+ /**
936
+ * Handle component delta events (both props_delta and state_delta).
937
+ * Applies JSON Patch to the specified field and sets streamingState to 'streaming'.
938
+ * @param threadState - Current thread state
939
+ * @param event - Component delta event (props or state)
940
+ * @param field - Which field to update ('props' or 'state')
941
+ * @returns Updated thread state
942
+ */
943
+ function handleComponentDelta(threadState, event, field) {
944
+ const componentId = event.value.componentId;
945
+ const operations = event.value.operations;
946
+ const messages = threadState.thread.messages;
947
+ const eventName = `tambo.component.${field}_delta`;
948
+ // Find the component content block
949
+ const { messageIndex, contentIndex } = findContentById(messages, "component", componentId, `${eventName} event`);
950
+ const message = messages[messageIndex];
951
+ const componentContent = message.content[contentIndex];
952
+ if (componentContent.type !== "component") {
953
+ throw new Error(`Content at index ${contentIndex} is not a component block for ${eventName} event`);
954
+ }
955
+ // Get current value (state defaults to {} if undefined)
956
+ const currentValue = field === "props"
957
+ ? componentContent.props
958
+ : (componentContent.state ?? {});
959
+ // Apply JSON Patch
960
+ const updatedValue = (0, json_patch_1.applyJsonPatch)(currentValue, operations);
961
+ // Update field and set streaming state to 'streaming'
962
+ const updatedContent = {
963
+ ...componentContent,
964
+ [field]: updatedValue,
965
+ streamingState: "streaming",
966
+ };
967
+ const updatedMessage = {
968
+ ...message,
969
+ content: updateContentAtIndex(message.content, contentIndex, updatedContent),
970
+ };
971
+ return updateThreadMessages(threadState, updateMessageAtIndex(messages, messageIndex, updatedMessage));
972
+ }
973
+ /**
974
+ * Handle tambo.component.end event.
975
+ * Sets component streaming state to 'done'.
976
+ * @param threadState - Current thread state
977
+ * @param event - Component end event
978
+ * @returns Updated thread state
979
+ */
980
+ function handleComponentEnd(threadState, event) {
981
+ const componentId = event.value.componentId;
982
+ const messages = threadState.thread.messages;
983
+ // Find the component content block
984
+ const { messageIndex, contentIndex } = findContentById(messages, "component", componentId, "tambo.component.end event");
985
+ const message = messages[messageIndex];
986
+ const componentContent = message.content[contentIndex];
987
+ if (componentContent.type !== "component") {
988
+ throw new Error(`Content at index ${contentIndex} is not a component block for tambo.component.end event`);
989
+ }
990
+ // Set streaming state to 'done'
991
+ const updatedContent = {
992
+ ...componentContent,
993
+ streamingState: "done",
994
+ };
995
+ const updatedMessage = {
996
+ ...message,
997
+ content: updateContentAtIndex(message.content, contentIndex, updatedContent),
998
+ };
999
+ return updateThreadMessages(threadState, updateMessageAtIndex(messages, messageIndex, updatedMessage));
1000
+ }
1001
+ /**
1002
+ * Handle tambo.run.awaiting_input event.
1003
+ * Sets thread status to waiting for client-side tool execution.
1004
+ * @param threadState - Current thread state
1005
+ * @param _event - Run awaiting input event (unused)
1006
+ * @returns Updated thread state
1007
+ */
1008
+ function handleRunAwaitingInput(threadState, _event) {
1009
+ return {
1010
+ ...threadState,
1011
+ thread: {
1012
+ ...threadState.thread,
1013
+ status: "waiting",
1014
+ updatedAt: new Date().toISOString(),
1015
+ },
1016
+ streaming: {
1017
+ ...threadState.streaming,
1018
+ status: "waiting",
1019
+ },
1020
+ };
1021
+ }
1022
+ /**
1023
+ * Handle tambo.message.parent event.
1024
+ * Sets parentMessageId on the target message, creating a new empty assistant
1025
+ * message if one doesn't already exist with the given ID.
1026
+ *
1027
+ * This event fires BEFORE TEXT_MESSAGE_START, so when handleTextMessageStart
1028
+ * later finds/creates the message with the same ID, the parentMessageId will
1029
+ * already be set.
1030
+ * @param threadState - Current thread state
1031
+ * @param event - Message parent event
1032
+ * @returns Updated thread state
1033
+ */
1034
+ function handleMessageParent(threadState, event) {
1035
+ const { messageId, parentMessageId } = event.value;
1036
+ const messages = threadState.thread.messages;
1037
+ // Find existing message or create a new empty assistant message
1038
+ const messageIndex = messages.findIndex((m) => m.id === messageId);
1039
+ if (messageIndex !== -1) {
1040
+ // Message already exists - set parentMessageId on it
1041
+ const message = messages[messageIndex];
1042
+ const updatedMessage = {
1043
+ ...message,
1044
+ parentMessageId,
1045
+ };
1046
+ return updateThreadMessages(threadState, updateMessageAtIndex(messages, messageIndex, updatedMessage));
1047
+ }
1048
+ // Message doesn't exist yet - create a new empty assistant message
1049
+ const newMessage = {
1050
+ id: messageId,
1051
+ role: "assistant",
1052
+ content: [],
1053
+ createdAt: new Date().toISOString(),
1054
+ parentMessageId,
1055
+ };
1056
+ return updateThreadMessages(threadState, [...messages, newMessage]);
1057
+ }
1058
+ // ============================================================================
1059
+ // Reasoning Event Handlers (currently mapped from THINKING_TEXT_MESSAGE_* events)
1060
+ // ============================================================================
1061
+ /**
1062
+ * Generate an ephemeral message ID for reasoning messages that arrive before TEXT_MESSAGE_START.
1063
+ * Uses crypto.randomUUID() which is available in Node.js 19+ and modern browsers.
1064
+ * @returns A unique ephemeral message ID string.
1065
+ */
1066
+ function generateEphemeralMessageId() {
1067
+ return `ephemeral_${crypto.randomUUID()}`;
1068
+ }
1069
+ /**
1070
+ * Find or create an assistant message for reasoning events.
1071
+ * Reasoning should only be attached to assistant messages.
1072
+ * If no suitable assistant message exists, creates an ephemeral one.
1073
+ * @param threadState - Current thread state
1074
+ * @returns Object with messageIndex, messages array, and updated threadState
1075
+ */
1076
+ function findOrCreateMessageForReasoning(threadState) {
1077
+ const messageId = threadState.streaming.messageId;
1078
+ let messages = threadState.thread.messages;
1079
+ // If we have an active streaming messageId, try to find it
1080
+ if (messageId) {
1081
+ const messageIndex = messages.findIndex((m) => m.id === messageId);
1082
+ if (messageIndex !== -1 && messages[messageIndex].role === "assistant") {
1083
+ return { messageIndex, messages, threadState };
1084
+ }
1085
+ }
1086
+ // Look for the last assistant message
1087
+ const lastAssistantIndex = messages.findLastIndex((m) => m.role === "assistant");
1088
+ // If there's an assistant message and it's the most recent message, use it
1089
+ // (Don't attach reasoning to an old assistant message if user message came after)
1090
+ if (lastAssistantIndex !== -1 && lastAssistantIndex === messages.length - 1) {
1091
+ return { messageIndex: lastAssistantIndex, messages, threadState };
1092
+ }
1093
+ // No suitable assistant message - create an ephemeral one
1094
+ const ephemeralId = generateEphemeralMessageId();
1095
+ const newMessage = {
1096
+ id: ephemeralId,
1097
+ role: "assistant",
1098
+ content: [],
1099
+ createdAt: new Date().toISOString(),
1100
+ };
1101
+ messages = [...messages, newMessage];
1102
+ const messageIndex = messages.length - 1;
1103
+ // Update thread state with new message
1104
+ threadState = {
1105
+ ...threadState,
1106
+ thread: {
1107
+ ...threadState.thread,
1108
+ messages,
1109
+ updatedAt: new Date().toISOString(),
1110
+ },
1111
+ streaming: {
1112
+ ...threadState.streaming,
1113
+ messageId: ephemeralId,
1114
+ },
1115
+ };
1116
+ return { messageIndex, messages, threadState };
1117
+ }
1118
+ /**
1119
+ * Handle THINKING_TEXT_MESSAGE_START event (will become REASONING_MESSAGE_START).
1120
+ * Starts a new reasoning chunk by appending an empty string to the message's reasoning array.
1121
+ * Records the start time for duration calculation.
1122
+ * @param threadState - Current thread state
1123
+ * @param event - Thinking text message start event
1124
+ * @returns Updated thread state
1125
+ */
1126
+ function handleThinkingTextMessageStart(threadState, event) {
1127
+ const { messageIndex, messages, threadState: updatedThreadState, } = findOrCreateMessageForReasoning(threadState);
1128
+ threadState = updatedThreadState;
1129
+ const message = messages[messageIndex];
1130
+ const existingReasoning = message.reasoning ?? [];
1131
+ const updatedMessage = {
1132
+ ...message,
1133
+ reasoning: [...existingReasoning, ""],
1134
+ };
1135
+ // Record reasoning start time if this is the first reasoning chunk
1136
+ const reasoningStartTime = threadState.streaming.reasoningStartTime ?? event.timestamp ?? Date.now();
1137
+ return {
1138
+ ...updateThreadMessages(threadState, updateMessageAtIndex(messages, messageIndex, updatedMessage)),
1139
+ streaming: {
1140
+ ...threadState.streaming,
1141
+ reasoningStartTime,
1142
+ },
1143
+ };
1144
+ }
1145
+ /**
1146
+ * Handle THINKING_TEXT_MESSAGE_CONTENT event (will become REASONING_MESSAGE_CONTENT).
1147
+ * Appends delta text to the last reasoning chunk.
1148
+ * @param threadState - Current thread state
1149
+ * @param event - Thinking text message content event
1150
+ * @returns Updated thread state
1151
+ */
1152
+ function handleThinkingTextMessageContent(threadState, event) {
1153
+ const { messageIndex, messages, threadState: updatedThreadState, } = findOrCreateMessageForReasoning(threadState);
1154
+ threadState = updatedThreadState;
1155
+ const message = messages[messageIndex];
1156
+ const existingReasoning = message.reasoning ?? [];
1157
+ if (existingReasoning.length === 0) {
1158
+ // No reasoning chunk started - start one implicitly
1159
+ const updatedMessage = {
1160
+ ...message,
1161
+ reasoning: [event.delta],
1162
+ };
1163
+ return {
1164
+ ...updateThreadMessages(threadState, updateMessageAtIndex(messages, messageIndex, updatedMessage)),
1165
+ streaming: {
1166
+ ...threadState.streaming,
1167
+ reasoningStartTime: threadState.streaming.reasoningStartTime ??
1168
+ event.timestamp ??
1169
+ Date.now(),
1170
+ },
1171
+ };
1172
+ }
1173
+ // Append to the last reasoning chunk
1174
+ const updatedReasoning = [
1175
+ ...existingReasoning.slice(0, -1),
1176
+ existingReasoning[existingReasoning.length - 1] + event.delta,
1177
+ ];
1178
+ const updatedMessage = {
1179
+ ...message,
1180
+ reasoning: updatedReasoning,
1181
+ };
1182
+ return updateThreadMessages(threadState, updateMessageAtIndex(messages, messageIndex, updatedMessage));
1183
+ }
1184
+ /**
1185
+ * Handle THINKING_TEXT_MESSAGE_END event (will become REASONING_MESSAGE_END).
1186
+ * Calculates and stores the reasoning duration.
1187
+ * @param threadState - Current thread state
1188
+ * @param event - Thinking text message end event
1189
+ * @returns Updated thread state
1190
+ */
1191
+ function handleThinkingTextMessageEnd(threadState, event) {
1192
+ const { messageIndex, messages, threadState: updatedThreadState, } = findOrCreateMessageForReasoning(threadState);
1193
+ threadState = updatedThreadState;
1194
+ const message = messages[messageIndex];
1195
+ // Calculate duration if we have a start time
1196
+ const reasoningStartTime = threadState.streaming.reasoningStartTime;
1197
+ const endTime = event.timestamp ?? Date.now();
1198
+ const reasoningDurationMS = reasoningStartTime
1199
+ ? endTime - reasoningStartTime
1200
+ : undefined;
1201
+ const updatedMessage = {
1202
+ ...message,
1203
+ reasoningDurationMS: reasoningDurationMS ?? message.reasoningDurationMS ?? undefined,
1204
+ };
1205
+ return updateThreadMessages(threadState, updateMessageAtIndex(messages, messageIndex, updatedMessage));
1206
+ }
1207
+ /**
1208
+ * Handle LOAD_THREAD_MESSAGES action.
1209
+ * Loads messages from API into stream state for an existing thread.
1210
+ * Deduplicates by message ID, keeping existing messages (they may have in-flight updates).
1211
+ * Sorts merged messages by createdAt to ensure chronological order.
1212
+ * @param state - Current stream state
1213
+ * @param action - Load thread messages action
1214
+ * @returns Updated stream state
1215
+ */
1216
+ function handleLoadThreadMessages(state, action) {
1217
+ const { threadId, messages, skipIfStreaming } = action;
1218
+ // Get or create thread state
1219
+ let threadState = state.threadMap[threadId];
1220
+ if (!threadState) {
1221
+ threadState = createInitialThreadState(threadId);
1222
+ }
1223
+ // Skip if streaming and skipIfStreaming is true
1224
+ if (skipIfStreaming && threadState.streaming.status === "streaming") {
1225
+ return state;
1226
+ }
1227
+ const existingMessages = threadState.thread.messages;
1228
+ // Build a set of existing message IDs for fast lookup
1229
+ const existingIds = new Set(existingMessages.map((m) => m.id));
1230
+ // Filter out messages that already exist (keep existing, add new).
1231
+ // API-loaded messages are by definition fully complete, so stamp
1232
+ // streamingState: "done" on all component content blocks. This is
1233
+ // required by downstream hooks (usePropsStreamingStatus) which check
1234
+ // streamingState === "done" to report isSuccess: true.
1235
+ const newMessages = messages
1236
+ .filter((m) => !existingIds.has(m.id))
1237
+ .map((m) => ({
1238
+ ...m,
1239
+ content: m.content.map((block) => {
1240
+ if (block.type !== "component")
1241
+ return block;
1242
+ if (block.streamingState !== undefined &&
1243
+ block.streamingState !== "done") {
1244
+ console.warn(`LOAD_THREAD_MESSAGES: component "${block.id}" has unexpected ` +
1245
+ `streamingState "${block.streamingState}". API-loaded messages ` +
1246
+ `should not have in-flight streaming state.`);
1247
+ }
1248
+ return { ...block, streamingState: "done" };
1249
+ }),
1250
+ }));
1251
+ // Merge and sort by createdAt
1252
+ const mergedMessages = [...existingMessages, ...newMessages].toSorted((a, b) => {
1253
+ // Messages without createdAt go to the end
1254
+ if (!a.createdAt && !b.createdAt)
1255
+ return 0;
1256
+ if (!a.createdAt)
1257
+ return 1;
1258
+ if (!b.createdAt)
1259
+ return -1;
1260
+ return a.createdAt.localeCompare(b.createdAt);
1261
+ });
1262
+ const updatedThreadState = {
1263
+ ...threadState,
1264
+ thread: {
1265
+ ...threadState.thread,
1266
+ messages: mergedMessages,
1267
+ updatedAt: new Date().toISOString(),
1268
+ },
1269
+ };
1270
+ return {
1271
+ ...state,
1272
+ threadMap: {
1273
+ ...state.threadMap,
1274
+ [threadId]: updatedThreadState,
1275
+ },
1276
+ };
1277
+ }
1278
+ //# sourceMappingURL=event-accumulator.js.map