deepagentsdk 0.13.0 → 0.15.0
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.
- package/dist/adapters/elements/index.cjs +322 -82
- package/dist/adapters/elements/index.cjs.map +1 -1
- package/dist/adapters/elements/index.d.cts +28 -3
- package/dist/adapters/elements/index.d.mts +28 -3
- package/dist/adapters/elements/index.mjs +321 -82
- package/dist/adapters/elements/index.mjs.map +1 -1
- package/dist/{agent-BDM-PIu8.d.mts → agent-DHUp_-Fx.d.mts} +114 -4
- package/dist/{agent-DToEVxs-.d.cts → agent-tfRthBvX.d.cts} +114 -4
- package/dist/{chunk-C5azi7Hr.cjs → chunk-DUZBydyJ.cjs} +7 -0
- package/dist/cli/index.cjs +2 -2
- package/dist/cli/index.mjs +1 -1
- package/dist/{file-saver-Hj5so3dV.mjs → file-saver-CQWTIr8z.mjs} +87 -4
- package/dist/file-saver-CQWTIr8z.mjs.map +1 -0
- package/dist/{file-saver-BYPKakT4.cjs → file-saver-ZDVH1zHI.cjs} +84 -4
- package/dist/file-saver-ZDVH1zHI.cjs.map +1 -0
- package/dist/index.cjs +27508 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +299 -2
- package/dist/index.d.mts +301 -4
- package/dist/index.mjs +27499 -4
- package/dist/index.mjs.map +1 -1
- package/dist/{load-BrRAKlO6.cjs → load-BnaAQyCo.cjs} +4 -4
- package/dist/{load-BrRAKlO6.cjs.map → load-BnaAQyCo.cjs.map} +1 -1
- package/dist/load-CLVcFzo7.cjs +4 -0
- package/dist/{load-BDxe6Cet.mjs → load-DRzSpESX.mjs} +1 -1
- package/dist/{load-BBYEnMwz.mjs → load-FjxJSusX.mjs} +2 -2
- package/dist/{load-BBYEnMwz.mjs.map → load-FjxJSusX.mjs.map} +1 -1
- package/package.json +5 -1
- package/dist/file-saver-BYPKakT4.cjs.map +0 -1
- package/dist/file-saver-Hj5so3dV.mjs.map +0 -1
- package/dist/load-DqllBbDc.cjs +0 -4
|
@@ -5,7 +5,15 @@ import { convertToModelMessages, createUIMessageStream, createUIMessageStreamRes
|
|
|
5
5
|
* Server-side route handler adapter for AI SDK Elements
|
|
6
6
|
*
|
|
7
7
|
* Creates a Next.js/Express-compatible route handler that runs DeepAgent
|
|
8
|
-
* and returns UI Message Stream compatible responses
|
|
8
|
+
* and returns UI Message Stream compatible responses with full event visibility.
|
|
9
|
+
*
|
|
10
|
+
* This handler streams all DeepAgent event types (26+) including:
|
|
11
|
+
* - Text and tool events (standard protocol)
|
|
12
|
+
* - File system operations
|
|
13
|
+
* - Command execution
|
|
14
|
+
* - Web requests and searches
|
|
15
|
+
* - Subagent lifecycle
|
|
16
|
+
* - State changes (todos, checkpoints)
|
|
9
17
|
*
|
|
10
18
|
* @example
|
|
11
19
|
* ```typescript
|
|
@@ -25,13 +33,14 @@ import { convertToModelMessages, createUIMessageStream, createUIMessageStreamRes
|
|
|
25
33
|
*/
|
|
26
34
|
/**
|
|
27
35
|
* Creates a route handler that processes chat requests using DeepAgent
|
|
28
|
-
* and
|
|
36
|
+
* and streams all 26+ event types in UI Message Stream Protocol format.
|
|
29
37
|
*
|
|
30
38
|
* The returned handler:
|
|
31
39
|
* - Accepts POST requests with { messages: UIMessage[] } body
|
|
32
40
|
* - Runs DeepAgent with the conversation history
|
|
33
41
|
* - Streams responses in UI Message Stream Protocol format
|
|
34
42
|
* - Works with useChat hook from @ai-sdk/react
|
|
43
|
+
* - Provides full visibility into agent behavior (file ops, web requests, subagents, etc.)
|
|
35
44
|
*
|
|
36
45
|
* @param options - Configuration options
|
|
37
46
|
* @returns A request handler function compatible with Next.js/Express
|
|
@@ -65,8 +74,8 @@ function createElementsRouteHandler(options) {
|
|
|
65
74
|
headers: { "Content-Type": "application/json" }
|
|
66
75
|
});
|
|
67
76
|
const modelMessages = await convertToModelMessages(messages);
|
|
68
|
-
let currentTextId = null;
|
|
69
77
|
const genId = generateId || (() => crypto.randomUUID());
|
|
78
|
+
let currentTextId = null;
|
|
70
79
|
return createUIMessageStreamResponse({ stream: createUIMessageStream({
|
|
71
80
|
originalMessages: messages,
|
|
72
81
|
generateId: genId,
|
|
@@ -77,84 +86,10 @@ function createElementsRouteHandler(options) {
|
|
|
77
86
|
state: initialState,
|
|
78
87
|
threadId,
|
|
79
88
|
maxSteps
|
|
80
|
-
}))
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
case "step-finish":
|
|
85
|
-
writer.write({ type: "finish-step" });
|
|
86
|
-
break;
|
|
87
|
-
case "text":
|
|
88
|
-
if (!currentTextId) {
|
|
89
|
-
currentTextId = genId();
|
|
90
|
-
writer.write({
|
|
91
|
-
type: "text-start",
|
|
92
|
-
id: currentTextId
|
|
93
|
-
});
|
|
94
|
-
}
|
|
95
|
-
writer.write({
|
|
96
|
-
type: "text-delta",
|
|
97
|
-
id: currentTextId,
|
|
98
|
-
delta: event.text
|
|
99
|
-
});
|
|
100
|
-
break;
|
|
101
|
-
case "tool-call":
|
|
102
|
-
if (currentTextId) {
|
|
103
|
-
writer.write({
|
|
104
|
-
type: "text-end",
|
|
105
|
-
id: currentTextId
|
|
106
|
-
});
|
|
107
|
-
currentTextId = null;
|
|
108
|
-
}
|
|
109
|
-
writer.write({
|
|
110
|
-
type: "tool-input-available",
|
|
111
|
-
toolCallId: event.toolCallId,
|
|
112
|
-
toolName: event.toolName,
|
|
113
|
-
input: event.args
|
|
114
|
-
});
|
|
115
|
-
break;
|
|
116
|
-
case "tool-result":
|
|
117
|
-
if (event.isError) writer.write({
|
|
118
|
-
type: "tool-output-error",
|
|
119
|
-
toolCallId: event.toolCallId,
|
|
120
|
-
errorText: String(event.result)
|
|
121
|
-
});
|
|
122
|
-
else writer.write({
|
|
123
|
-
type: "tool-output-available",
|
|
124
|
-
toolCallId: event.toolCallId,
|
|
125
|
-
output: event.result
|
|
126
|
-
});
|
|
127
|
-
break;
|
|
128
|
-
case "todos-changed":
|
|
129
|
-
writer.write({
|
|
130
|
-
type: "data",
|
|
131
|
-
name: "todos-changed",
|
|
132
|
-
data: { todos: event.todos }
|
|
133
|
-
});
|
|
134
|
-
break;
|
|
135
|
-
case "error":
|
|
136
|
-
if (currentTextId) {
|
|
137
|
-
writer.write({
|
|
138
|
-
type: "text-end",
|
|
139
|
-
id: currentTextId
|
|
140
|
-
});
|
|
141
|
-
currentTextId = null;
|
|
142
|
-
}
|
|
143
|
-
writer.write({
|
|
144
|
-
type: "error",
|
|
145
|
-
errorText: event.error.message
|
|
146
|
-
});
|
|
147
|
-
break;
|
|
148
|
-
case "done":
|
|
149
|
-
if (currentTextId) {
|
|
150
|
-
writer.write({
|
|
151
|
-
type: "text-end",
|
|
152
|
-
id: currentTextId
|
|
153
|
-
});
|
|
154
|
-
currentTextId = null;
|
|
155
|
-
}
|
|
156
|
-
break;
|
|
157
|
-
default: break;
|
|
89
|
+
})) {
|
|
90
|
+
const result = mapEventToProtocol(event, writer, genId, currentTextId);
|
|
91
|
+
if (typeof result === "string") currentTextId = result;
|
|
92
|
+
else if (result === null) currentTextId = null;
|
|
158
93
|
}
|
|
159
94
|
if (currentTextId) writer.write({
|
|
160
95
|
type: "text-end",
|
|
@@ -174,6 +109,310 @@ function createElementsRouteHandler(options) {
|
|
|
174
109
|
}) });
|
|
175
110
|
};
|
|
176
111
|
}
|
|
112
|
+
/**
|
|
113
|
+
* Maps a DeepAgent event to a UI Message Stream Protocol event.
|
|
114
|
+
*
|
|
115
|
+
* This function handles all 26+ DeepAgent event types, mapping:
|
|
116
|
+
* - Standard protocol events (text, tools, steps, errors)
|
|
117
|
+
* - Custom data events (file operations, web requests, subagents, execution)
|
|
118
|
+
*
|
|
119
|
+
* @param event - The DeepAgent event to map
|
|
120
|
+
* @param writer - The UI message stream writer
|
|
121
|
+
* @param genId - ID generator function
|
|
122
|
+
* @param currentTextId - The current text part ID (for tracking streaming text)
|
|
123
|
+
* @returns The new currentTextId value (string | null)
|
|
124
|
+
*
|
|
125
|
+
* @example
|
|
126
|
+
* ```typescript
|
|
127
|
+
* // Handles text streaming with proper ID tracking
|
|
128
|
+
* let textId: string | null = null;
|
|
129
|
+
* textId = mapEventToProtocol({ type: 'text', text: 'Hello' }, writer, genId, textId);
|
|
130
|
+
* // textId is now the ID of the active text part
|
|
131
|
+
* ```
|
|
132
|
+
*/
|
|
133
|
+
function mapEventToProtocol(event, writer, genId, currentTextId) {
|
|
134
|
+
switch (event.type) {
|
|
135
|
+
case "step-start":
|
|
136
|
+
writer.write({ type: "start-step" });
|
|
137
|
+
return currentTextId;
|
|
138
|
+
case "step-finish":
|
|
139
|
+
writer.write({ type: "finish-step" });
|
|
140
|
+
return currentTextId;
|
|
141
|
+
case "text":
|
|
142
|
+
if (!currentTextId) {
|
|
143
|
+
const textId = genId();
|
|
144
|
+
writer.write({
|
|
145
|
+
type: "text-start",
|
|
146
|
+
id: textId
|
|
147
|
+
});
|
|
148
|
+
return textId;
|
|
149
|
+
}
|
|
150
|
+
writer.write({
|
|
151
|
+
type: "text-delta",
|
|
152
|
+
id: currentTextId,
|
|
153
|
+
delta: event.text
|
|
154
|
+
});
|
|
155
|
+
return currentTextId;
|
|
156
|
+
case "tool-call":
|
|
157
|
+
if (currentTextId) {
|
|
158
|
+
writer.write({
|
|
159
|
+
type: "text-end",
|
|
160
|
+
id: currentTextId
|
|
161
|
+
});
|
|
162
|
+
currentTextId = null;
|
|
163
|
+
}
|
|
164
|
+
writer.write({
|
|
165
|
+
type: "tool-input-available",
|
|
166
|
+
toolCallId: event.toolCallId,
|
|
167
|
+
toolName: event.toolName,
|
|
168
|
+
input: event.args
|
|
169
|
+
});
|
|
170
|
+
return null;
|
|
171
|
+
case "tool-result":
|
|
172
|
+
if (event.isError) writer.write({
|
|
173
|
+
type: "tool-output-error",
|
|
174
|
+
toolCallId: event.toolCallId,
|
|
175
|
+
errorText: String(event.result)
|
|
176
|
+
});
|
|
177
|
+
else writer.write({
|
|
178
|
+
type: "tool-output-available",
|
|
179
|
+
toolCallId: event.toolCallId,
|
|
180
|
+
output: event.result
|
|
181
|
+
});
|
|
182
|
+
return currentTextId;
|
|
183
|
+
case "todos-changed":
|
|
184
|
+
writer.write({
|
|
185
|
+
type: "data",
|
|
186
|
+
name: "todos-changed",
|
|
187
|
+
data: { todos: event.todos }
|
|
188
|
+
});
|
|
189
|
+
return currentTextId;
|
|
190
|
+
case "file-write-start":
|
|
191
|
+
writer.write({
|
|
192
|
+
type: "data",
|
|
193
|
+
name: "file-write-start",
|
|
194
|
+
data: {
|
|
195
|
+
path: event.path,
|
|
196
|
+
content: event.content
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
return currentTextId;
|
|
200
|
+
case "file-written":
|
|
201
|
+
writer.write({
|
|
202
|
+
type: "data",
|
|
203
|
+
name: "file-written",
|
|
204
|
+
data: {
|
|
205
|
+
path: event.path,
|
|
206
|
+
content: event.content
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
return currentTextId;
|
|
210
|
+
case "file-edited":
|
|
211
|
+
writer.write({
|
|
212
|
+
type: "data",
|
|
213
|
+
name: "file-edited",
|
|
214
|
+
data: {
|
|
215
|
+
path: event.path,
|
|
216
|
+
occurrences: event.occurrences
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
return currentTextId;
|
|
220
|
+
case "file-read":
|
|
221
|
+
writer.write({
|
|
222
|
+
type: "data",
|
|
223
|
+
name: "file-read",
|
|
224
|
+
data: {
|
|
225
|
+
path: event.path,
|
|
226
|
+
lines: event.lines
|
|
227
|
+
}
|
|
228
|
+
});
|
|
229
|
+
return currentTextId;
|
|
230
|
+
case "ls":
|
|
231
|
+
writer.write({
|
|
232
|
+
type: "data",
|
|
233
|
+
name: "ls",
|
|
234
|
+
data: {
|
|
235
|
+
path: event.path,
|
|
236
|
+
count: event.count
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
return currentTextId;
|
|
240
|
+
case "glob":
|
|
241
|
+
writer.write({
|
|
242
|
+
type: "data",
|
|
243
|
+
name: "glob",
|
|
244
|
+
data: {
|
|
245
|
+
pattern: event.pattern,
|
|
246
|
+
count: event.count
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
return currentTextId;
|
|
250
|
+
case "grep":
|
|
251
|
+
writer.write({
|
|
252
|
+
type: "data",
|
|
253
|
+
name: "grep",
|
|
254
|
+
data: {
|
|
255
|
+
pattern: event.pattern,
|
|
256
|
+
count: event.count
|
|
257
|
+
}
|
|
258
|
+
});
|
|
259
|
+
return currentTextId;
|
|
260
|
+
case "execute-start":
|
|
261
|
+
writer.write({
|
|
262
|
+
type: "data",
|
|
263
|
+
name: "execute-start",
|
|
264
|
+
data: {
|
|
265
|
+
command: event.command,
|
|
266
|
+
sandboxId: event.sandboxId
|
|
267
|
+
}
|
|
268
|
+
});
|
|
269
|
+
return currentTextId;
|
|
270
|
+
case "execute-finish":
|
|
271
|
+
writer.write({
|
|
272
|
+
type: "data",
|
|
273
|
+
name: "execute-finish",
|
|
274
|
+
data: {
|
|
275
|
+
command: event.command,
|
|
276
|
+
exitCode: event.exitCode,
|
|
277
|
+
truncated: event.truncated,
|
|
278
|
+
sandboxId: event.sandboxId
|
|
279
|
+
}
|
|
280
|
+
});
|
|
281
|
+
return currentTextId;
|
|
282
|
+
case "web-search-start":
|
|
283
|
+
writer.write({
|
|
284
|
+
type: "data",
|
|
285
|
+
name: "web-search-start",
|
|
286
|
+
data: { query: event.query }
|
|
287
|
+
});
|
|
288
|
+
return currentTextId;
|
|
289
|
+
case "web-search-finish":
|
|
290
|
+
writer.write({
|
|
291
|
+
type: "data",
|
|
292
|
+
name: "web-search-finish",
|
|
293
|
+
data: {
|
|
294
|
+
query: event.query,
|
|
295
|
+
resultCount: event.resultCount
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
return currentTextId;
|
|
299
|
+
case "http-request-start":
|
|
300
|
+
writer.write({
|
|
301
|
+
type: "data",
|
|
302
|
+
name: "http-request-start",
|
|
303
|
+
data: {
|
|
304
|
+
url: event.url,
|
|
305
|
+
method: event.method
|
|
306
|
+
}
|
|
307
|
+
});
|
|
308
|
+
return currentTextId;
|
|
309
|
+
case "http-request-finish":
|
|
310
|
+
writer.write({
|
|
311
|
+
type: "data",
|
|
312
|
+
name: "http-request-finish",
|
|
313
|
+
data: {
|
|
314
|
+
url: event.url,
|
|
315
|
+
statusCode: event.statusCode
|
|
316
|
+
}
|
|
317
|
+
});
|
|
318
|
+
return currentTextId;
|
|
319
|
+
case "fetch-url-start":
|
|
320
|
+
writer.write({
|
|
321
|
+
type: "data",
|
|
322
|
+
name: "fetch-url-start",
|
|
323
|
+
data: { url: event.url }
|
|
324
|
+
});
|
|
325
|
+
return currentTextId;
|
|
326
|
+
case "fetch-url-finish":
|
|
327
|
+
writer.write({
|
|
328
|
+
type: "data",
|
|
329
|
+
name: "fetch-url-finish",
|
|
330
|
+
data: {
|
|
331
|
+
url: event.url,
|
|
332
|
+
success: event.success
|
|
333
|
+
}
|
|
334
|
+
});
|
|
335
|
+
return currentTextId;
|
|
336
|
+
case "subagent-start":
|
|
337
|
+
writer.write({
|
|
338
|
+
type: "data",
|
|
339
|
+
name: "subagent-start",
|
|
340
|
+
data: {
|
|
341
|
+
name: event.name,
|
|
342
|
+
task: event.task
|
|
343
|
+
}
|
|
344
|
+
});
|
|
345
|
+
return currentTextId;
|
|
346
|
+
case "subagent-finish":
|
|
347
|
+
writer.write({
|
|
348
|
+
type: "data",
|
|
349
|
+
name: "subagent-finish",
|
|
350
|
+
data: {
|
|
351
|
+
name: event.name,
|
|
352
|
+
result: event.result
|
|
353
|
+
}
|
|
354
|
+
});
|
|
355
|
+
return currentTextId;
|
|
356
|
+
case "subagent-step":
|
|
357
|
+
writer.write({
|
|
358
|
+
type: "data",
|
|
359
|
+
name: "subagent-step",
|
|
360
|
+
data: {
|
|
361
|
+
stepIndex: event.stepIndex,
|
|
362
|
+
toolCalls: event.toolCalls
|
|
363
|
+
}
|
|
364
|
+
});
|
|
365
|
+
return currentTextId;
|
|
366
|
+
case "checkpoint-saved":
|
|
367
|
+
writer.write({
|
|
368
|
+
type: "data",
|
|
369
|
+
name: "checkpoint-saved",
|
|
370
|
+
data: {
|
|
371
|
+
threadId: event.threadId,
|
|
372
|
+
step: event.step
|
|
373
|
+
}
|
|
374
|
+
});
|
|
375
|
+
return currentTextId;
|
|
376
|
+
case "checkpoint-loaded":
|
|
377
|
+
writer.write({
|
|
378
|
+
type: "data",
|
|
379
|
+
name: "checkpoint-loaded",
|
|
380
|
+
data: {
|
|
381
|
+
threadId: event.threadId,
|
|
382
|
+
step: event.step,
|
|
383
|
+
messagesCount: event.messagesCount
|
|
384
|
+
}
|
|
385
|
+
});
|
|
386
|
+
return currentTextId;
|
|
387
|
+
case "error":
|
|
388
|
+
if (currentTextId) {
|
|
389
|
+
writer.write({
|
|
390
|
+
type: "text-end",
|
|
391
|
+
id: currentTextId
|
|
392
|
+
});
|
|
393
|
+
currentTextId = null;
|
|
394
|
+
}
|
|
395
|
+
writer.write({
|
|
396
|
+
type: "error",
|
|
397
|
+
errorText: event.error.message
|
|
398
|
+
});
|
|
399
|
+
return null;
|
|
400
|
+
case "done":
|
|
401
|
+
if (currentTextId) {
|
|
402
|
+
writer.write({
|
|
403
|
+
type: "text-end",
|
|
404
|
+
id: currentTextId
|
|
405
|
+
});
|
|
406
|
+
currentTextId = null;
|
|
407
|
+
}
|
|
408
|
+
writer.write({
|
|
409
|
+
type: "finish",
|
|
410
|
+
finishReason: "stop"
|
|
411
|
+
});
|
|
412
|
+
return null;
|
|
413
|
+
default: return currentTextId;
|
|
414
|
+
}
|
|
415
|
+
}
|
|
177
416
|
|
|
178
417
|
//#endregion
|
|
179
418
|
//#region src/adapters/elements/messageConverters.ts
|
|
@@ -264,5 +503,5 @@ function extractTextFromMessage(message) {
|
|
|
264
503
|
}
|
|
265
504
|
|
|
266
505
|
//#endregion
|
|
267
|
-
export { convertUIMessagesToModelMessages, countMessagesByRole, createElementsRouteHandler, extractLastUserMessage, extractTextFromMessage, hasToolParts };
|
|
506
|
+
export { convertUIMessagesToModelMessages, countMessagesByRole, createElementsRouteHandler, extractLastUserMessage, extractTextFromMessage, hasToolParts, mapEventToProtocol };
|
|
268
507
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/adapters/elements/createElementsRouteHandler.ts","../../../src/adapters/elements/messageConverters.ts"],"sourcesContent":["/**\n * Server-side route handler adapter for AI SDK Elements\n *\n * Creates a Next.js/Express-compatible route handler that runs DeepAgent\n * and returns UI Message Stream compatible responses for use with useChat.\n *\n * @example\n * ```typescript\n * // app/api/chat/route.ts (Next.js App Router)\n * import { createDeepAgent } from 'deepagentsdk';\n * import { createElementsRouteHandler } from 'deepagentsdk/adapters/elements';\n * import { anthropic } from '@ai-sdk/anthropic';\n *\n * const agent = createDeepAgent({\n * model: anthropic('claude-sonnet-4-20250514'),\n * });\n *\n * export const POST = createElementsRouteHandler({ agent });\n * ```\n *\n * @see https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol\n */\n\nimport {\n createUIMessageStream,\n createUIMessageStreamResponse,\n convertToModelMessages,\n type UIMessage,\n} from \"ai\";\nimport type { DeepAgent } from \"../../agent\";\nimport type { DeepAgentState, ModelMessage } from \"../../types\";\n\n/**\n * Options for creating an Elements route handler\n */\nexport interface CreateElementsRouteHandlerOptions {\n /**\n * The DeepAgent instance to use for handling requests\n */\n agent: DeepAgent;\n\n /**\n * Optional callback before processing a request.\n * Use for authentication, logging, rate limiting, etc.\n *\n * @example\n * ```typescript\n * onRequest: async (req) => {\n * const token = req.headers.get('Authorization');\n * if (!validateToken(token)) {\n * throw new Error('Unauthorized');\n * }\n * }\n * ```\n */\n onRequest?: (req: Request) => Promise<void> | void;\n\n /**\n * Optional initial state to provide to the agent.\n * If not provided, uses empty state { todos: [], files: {} }\n */\n initialState?: DeepAgentState;\n\n /**\n * Optional thread ID for checkpointing.\n * If provided, enables conversation persistence.\n */\n threadId?: string;\n\n /**\n * Optional maximum number of steps for the agent loop.\n */\n maxSteps?: number;\n\n /**\n * Custom ID generator for message IDs.\n * Defaults to crypto.randomUUID if available.\n */\n generateId?: () => string;\n}\n\n/**\n * Creates a route handler that processes chat requests using DeepAgent\n * and returns UI Message Stream compatible responses.\n *\n * The returned handler:\n * - Accepts POST requests with { messages: UIMessage[] } body\n * - Runs DeepAgent with the conversation history\n * - Streams responses in UI Message Stream Protocol format\n * - Works with useChat hook from @ai-sdk/react\n *\n * @param options - Configuration options\n * @returns A request handler function compatible with Next.js/Express\n */\nexport function createElementsRouteHandler(\n options: CreateElementsRouteHandlerOptions\n): (req: Request) => Promise<Response> {\n const {\n agent,\n onRequest,\n initialState = { todos: [], files: {} },\n threadId,\n maxSteps,\n generateId,\n } = options;\n\n return async (req: Request): Promise<Response> => {\n // Run optional request hook (auth, logging, etc.)\n if (onRequest) {\n try {\n await onRequest(req);\n } catch (error) {\n return new Response(\n JSON.stringify({\n error: error instanceof Error ? error.message : \"Request rejected\",\n }),\n { status: 401, headers: { \"Content-Type\": \"application/json\" } }\n );\n }\n }\n\n // Parse request body\n let requestBody: { messages: UIMessage[] };\n try {\n requestBody = await req.json();\n } catch {\n return new Response(\n JSON.stringify({ error: \"Invalid JSON body\" }),\n { status: 400, headers: { \"Content-Type\": \"application/json\" } }\n );\n }\n\n const { messages } = requestBody;\n\n if (!messages || !Array.isArray(messages)) {\n return new Response(\n JSON.stringify({ error: \"messages array is required\" }),\n { status: 400, headers: { \"Content-Type\": \"application/json\" } }\n );\n }\n\n // Convert UI messages to model messages using AI SDK's converter\n const modelMessages = await convertToModelMessages(messages) as ModelMessage[];\n\n // Track current text part ID for proper text streaming\n let currentTextId: string | null = null;\n const genId = generateId || (() => crypto.randomUUID());\n\n // Create the UI message stream\n const stream = createUIMessageStream({\n originalMessages: messages,\n generateId: genId,\n execute: async ({ writer }) => {\n try {\n for await (const event of agent.streamWithEvents({\n messages: modelMessages,\n state: initialState,\n threadId,\n maxSteps,\n })) {\n switch (event.type) {\n case \"step-start\":\n // Emit step start for UI progress tracking\n writer.write({ type: \"start-step\" });\n break;\n\n case \"step-finish\":\n // Emit step finish\n writer.write({ type: \"finish-step\" });\n break;\n\n case \"text\":\n // Handle text streaming\n if (!currentTextId) {\n // Start a new text part\n currentTextId = genId();\n writer.write({\n type: \"text-start\",\n id: currentTextId,\n });\n }\n // Stream text delta\n writer.write({\n type: \"text-delta\",\n id: currentTextId,\n delta: event.text,\n });\n break;\n\n case \"tool-call\":\n // End any in-progress text before tool call\n if (currentTextId) {\n writer.write({ type: \"text-end\", id: currentTextId });\n currentTextId = null;\n }\n // Emit tool input available\n writer.write({\n type: \"tool-input-available\",\n toolCallId: event.toolCallId,\n toolName: event.toolName,\n input: event.args,\n });\n break;\n\n case \"tool-result\":\n // Emit tool output\n if (event.isError) {\n writer.write({\n type: \"tool-output-error\",\n toolCallId: event.toolCallId,\n errorText: String(event.result),\n });\n } else {\n writer.write({\n type: \"tool-output-available\",\n toolCallId: event.toolCallId,\n output: event.result,\n });\n }\n break;\n\n case \"todos-changed\":\n // Emit as custom data part for UI to handle\n // Note: This requires UI to handle custom data types\n writer.write({\n type: \"data\" as any,\n name: \"todos-changed\",\n data: { todos: event.todos },\n } as any);\n break;\n\n case \"error\":\n // End any in-progress text\n if (currentTextId) {\n writer.write({ type: \"text-end\", id: currentTextId });\n currentTextId = null;\n }\n // Emit error\n writer.write({\n type: \"error\",\n errorText: event.error.message,\n });\n break;\n\n case \"done\":\n // End any in-progress text\n if (currentTextId) {\n writer.write({ type: \"text-end\", id: currentTextId });\n currentTextId = null;\n }\n // Done event is handled automatically by the stream\n break;\n\n // Other events (file operations, subagents, etc.) can be\n // emitted as custom data parts if needed by the UI\n default:\n // Optionally emit other events as data parts\n // writer.write({\n // type: \"data\" as any,\n // name: event.type,\n // data: event,\n // } as any);\n break;\n }\n }\n\n // Ensure text is ended if stream completes\n if (currentTextId) {\n writer.write({ type: \"text-end\", id: currentTextId });\n }\n } catch (error) {\n // End any in-progress text on error\n if (currentTextId) {\n writer.write({ type: \"text-end\", id: currentTextId });\n }\n // Re-throw to let the stream handle the error\n throw error;\n }\n },\n onError: (error) => {\n // Return error message for the stream\n return error instanceof Error ? error.message : \"Unknown error\";\n },\n });\n\n // Return the stream response\n return createUIMessageStreamResponse({ stream });\n };\n}\n\n/**\n * Type for the request handler returned by createElementsRouteHandler\n */\nexport type ElementsRouteHandler = (req: Request) => Promise<Response>;\n","/**\n * Message conversion utilities for AI SDK Elements adapter\n *\n * Provides utilities for converting between UI message formats and model message formats.\n * The primary conversion is handled by AI SDK's `convertToModelMessages`, but these\n * utilities provide additional helpers for DeepAgent-specific needs.\n */\n\nimport {\n convertToModelMessages,\n type UIMessage,\n} from \"ai\";\nimport type { ModelMessage } from \"../../types\";\n\n/**\n * Re-export AI SDK's convertToModelMessages for convenience.\n *\n * This function converts UIMessage[] (from useChat) to ModelMessage[]\n * (for agent consumption), handling:\n * - Role mapping (user/assistant)\n * - Tool call/result parts\n * - Text content extraction\n *\n * @example\n * ```typescript\n * import { convertUIMessagesToModelMessages } from 'deepagentsdk/adapters/elements';\n *\n * const modelMessages = await convertUIMessagesToModelMessages(uiMessages);\n * ```\n */\nexport async function convertUIMessagesToModelMessages(\n messages: UIMessage[]\n): Promise<ModelMessage[]> {\n return await convertToModelMessages(messages) as ModelMessage[];\n}\n\n/**\n * Extract the last user message text from a UIMessage array.\n * Useful for extracting the prompt from a conversation.\n *\n * @param messages - Array of UI messages\n * @returns The text content of the last user message, or undefined if none\n */\nexport function extractLastUserMessage(messages: UIMessage[]): string | undefined {\n // Find the last user message\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg && msg.role === \"user\" && msg.parts) {\n // Extract text parts\n const textParts = msg.parts.filter(\n (p): p is { type: \"text\"; text: string } => p.type === \"text\"\n );\n if (textParts.length > 0) {\n return textParts.map(p => p.text).join(\"\");\n }\n }\n }\n return undefined;\n}\n\n/**\n * Check if the messages contain any tool parts.\n * This is a simplified helper that checks for any tool-related parts.\n *\n * @param messages - Array of UI messages\n * @returns True if there are any tool-related parts in the messages\n */\nexport function hasToolParts(messages: UIMessage[]): boolean {\n for (const msg of messages) {\n if (!msg.parts) continue;\n for (const part of msg.parts) {\n // Tool parts have type starting with \"tool-\" or \"dynamic-tool\"\n if (part.type.startsWith(\"tool-\") || part.type === \"dynamic-tool\") {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Count the number of messages by role.\n *\n * @param messages - Array of UI messages\n * @returns Object with counts by role\n */\nexport function countMessagesByRole(\n messages: UIMessage[]\n): { user: number; assistant: number; system: number } {\n let user = 0;\n let assistant = 0;\n let system = 0;\n\n for (const msg of messages) {\n if (msg.role === \"user\") {\n user++;\n } else if (msg.role === \"assistant\") {\n assistant++;\n } else if (msg.role === \"system\") {\n system++;\n }\n }\n\n return { user, assistant, system };\n}\n\n/**\n * Extract all text content from a message.\n *\n * @param message - A UI message\n * @returns Combined text from all text parts\n */\nexport function extractTextFromMessage(message: UIMessage): string {\n if (!message.parts) return \"\";\n\n return message.parts\n .filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n .map(p => p.text)\n .join(\"\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FA,SAAgB,2BACd,SACqC;CACrC,MAAM,EACJ,OACA,WACA,eAAe;EAAE,OAAO,EAAE;EAAE,OAAO,EAAE;EAAE,EACvC,UACA,UACA,eACE;AAEJ,QAAO,OAAO,QAAoC;AAEhD,MAAI,UACF,KAAI;AACF,SAAM,UAAU,IAAI;WACb,OAAO;AACd,UAAO,IAAI,SACT,KAAK,UAAU,EACb,OAAO,iBAAiB,QAAQ,MAAM,UAAU,oBACjD,CAAC,EACF;IAAE,QAAQ;IAAK,SAAS,EAAE,gBAAgB,oBAAoB;IAAE,CACjE;;EAKL,IAAI;AACJ,MAAI;AACF,iBAAc,MAAM,IAAI,MAAM;UACxB;AACN,UAAO,IAAI,SACT,KAAK,UAAU,E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AAI,MAAO;AAChB,OAAK,MAAM,QAAQ,IAAI,MAErB,KAAI,KAAK,KAAK,WAAW,QAAQ,IAAI,KAAK,SAAS,eACjD,QAAO;;AAIb,QAAO;;;;;;;;AAST,SAAgB,oBACd,UACqD;CACrD,IAAI,OAAO;CACX,IAAI,YAAY;CAChB,IAAI,SAAS;AAEb,MAAK,MAAM,OAAO,SAChB,KAAI,IAAI,SAAS,OACf;UACS,IAAI,SAAS,YACtB;UACS,IAAI,SAAS,SACtB;AAIJ,QAAO;EAAE;EAAM;EAAW;EAAQ;;;;;;;;AASpC,SAAgB,uBAAuB,SAA4B;AACjE,KAAI,CAAC,QAAQ,MAAO,QAAO;AAE3B,QAAO,QAAQ,MACZ,QAAQ,MAA2C,EAAE,SAAS,OAAO,CACrE,KAAI,MAAK,EAAE,KAAK,CAChB,KAAK,GAAG"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../../src/adapters/elements/createElementsRouteHandler.ts","../../../src/adapters/elements/messageConverters.ts"],"sourcesContent":["/**\n * Server-side route handler adapter for AI SDK Elements\n *\n * Creates a Next.js/Express-compatible route handler that runs DeepAgent\n * and returns UI Message Stream compatible responses with full event visibility.\n *\n * This handler streams all DeepAgent event types (26+) including:\n * - Text and tool events (standard protocol)\n * - File system operations\n * - Command execution\n * - Web requests and searches\n * - Subagent lifecycle\n * - State changes (todos, checkpoints)\n *\n * @example\n * ```typescript\n * // app/api/chat/route.ts (Next.js App Router)\n * import { createDeepAgent } from 'deepagentsdk';\n * import { createElementsRouteHandler } from 'deepagentsdk/adapters/elements';\n * import { anthropic } from '@ai-sdk/anthropic';\n *\n * const agent = createDeepAgent({\n * model: anthropic('claude-sonnet-4-20250514'),\n * });\n *\n * export const POST = createElementsRouteHandler({ agent });\n * ```\n *\n * @see https://ai-sdk.dev/docs/ai-sdk-ui/stream-protocol\n */\n\nimport {\n createUIMessageStream,\n createUIMessageStreamResponse,\n convertToModelMessages,\n} from \"ai\";\nimport type { DeepAgent } from \"../../agent\";\nimport type { DeepAgentState, DeepAgentEvent } from \"../../types\";\n\n/**\n * Options for creating an Elements route handler\n */\nexport interface CreateElementsRouteHandlerOptions {\n /**\n * The DeepAgent instance to use for handling requests\n */\n agent: DeepAgent;\n\n /**\n * Optional callback before processing a request.\n * Use for authentication, logging, rate limiting, etc.\n *\n * @example\n * ```typescript\n * onRequest: async (req) => {\n * const token = req.headers.get('Authorization');\n * if (!validateToken(token)) {\n * throw new Error('Unauthorized');\n * }\n * }\n * ```\n */\n onRequest?: (req: Request) => Promise<void> | void;\n\n /**\n * Optional initial state to provide to the agent.\n * If not provided, uses empty state { todos: [], files: {} }\n */\n initialState?: DeepAgentState;\n\n /**\n * Optional thread ID for checkpointing.\n * If provided, enables conversation persistence.\n */\n threadId?: string;\n\n /**\n * Optional maximum number of steps for the agent loop.\n */\n maxSteps?: number;\n\n /**\n * Custom ID generator for message IDs.\n * Defaults to crypto.randomUUID if available.\n */\n generateId?: () => string;\n}\n\n/**\n * Creates a route handler that processes chat requests using DeepAgent\n * and streams all 26+ event types in UI Message Stream Protocol format.\n *\n * The returned handler:\n * - Accepts POST requests with { messages: UIMessage[] } body\n * - Runs DeepAgent with the conversation history\n * - Streams responses in UI Message Stream Protocol format\n * - Works with useChat hook from @ai-sdk/react\n * - Provides full visibility into agent behavior (file ops, web requests, subagents, etc.)\n *\n * @param options - Configuration options\n * @returns A request handler function compatible with Next.js/Express\n */\nexport function createElementsRouteHandler(\n options: CreateElementsRouteHandlerOptions\n): (req: Request) => Promise<Response> {\n const {\n agent,\n onRequest,\n initialState = {\n todos: [],\n files: {}\n },\n threadId,\n maxSteps,\n generateId\n } = options;\n\n return async (req: Request): Promise<Response> => {\n // 1. Handle onRequest hook (auth, logging, rate limiting)\n if (onRequest) {\n try {\n await onRequest(req);\n } catch (error) {\n return new Response(\n JSON.stringify({\n error: error instanceof Error ? error.message : 'Request rejected'\n }),\n {\n status: 401,\n headers: { 'Content-Type': 'application/json' }\n }\n );\n }\n }\n\n // 2. Parse request body\n let requestBody;\n try {\n requestBody = await req.json();\n } catch {\n return new Response(\n JSON.stringify({ error: 'Invalid JSON body' }),\n {\n status: 400,\n headers: { 'Content-Type': 'application/json' }\n }\n );\n }\n\n const { messages } = requestBody;\n if (!messages || !Array.isArray(messages)) {\n return new Response(\n JSON.stringify({ error: 'messages array is required' }),\n {\n status: 400,\n headers: { 'Content-Type': 'application/json' }\n }\n );\n }\n\n // 3. Convert UI messages to model messages\n const modelMessages = await convertToModelMessages(messages);\n\n // 4. Setup ID generator\n const genId = generateId || (() => crypto.randomUUID());\n\n // 5. Track current text ID for text-start/text-end\n let currentTextId: string | null = null;\n\n // 6. Create UI message stream response\n return createUIMessageStreamResponse({\n stream: createUIMessageStream({\n originalMessages: messages,\n generateId: genId,\n execute: async ({ writer }) => {\n try {\n // Stream all events from DeepAgent\n for await (const event of agent.streamWithEvents({\n messages: modelMessages,\n state: initialState,\n threadId,\n maxSteps\n })) {\n // Update currentTextId from the returned value\n const result = mapEventToProtocol(event, writer, genId, currentTextId);\n if (typeof result === 'string') {\n currentTextId = result;\n } else if (result === null) {\n currentTextId = null;\n }\n }\n\n // Ensure text is properly closed\n if (currentTextId) {\n writer.write({\n type: 'text-end',\n id: currentTextId\n });\n }\n } catch (error) {\n // Close text if error occurs mid-stream\n if (currentTextId) {\n writer.write({\n type: 'text-end',\n id: currentTextId\n });\n }\n throw error;\n }\n },\n onError: (error) => {\n return error instanceof Error ? error.message : 'Unknown error';\n }\n })\n });\n };\n}\n\n/**\n * Maps a DeepAgent event to a UI Message Stream Protocol event.\n *\n * This function handles all 26+ DeepAgent event types, mapping:\n * - Standard protocol events (text, tools, steps, errors)\n * - Custom data events (file operations, web requests, subagents, execution)\n *\n * @param event - The DeepAgent event to map\n * @param writer - The UI message stream writer\n * @param genId - ID generator function\n * @param currentTextId - The current text part ID (for tracking streaming text)\n * @returns The new currentTextId value (string | null)\n *\n * @example\n * ```typescript\n * // Handles text streaming with proper ID tracking\n * let textId: string | null = null;\n * textId = mapEventToProtocol({ type: 'text', text: 'Hello' }, writer, genId, textId);\n * // textId is now the ID of the active text part\n * ```\n */\nexport function mapEventToProtocol(\n event: DeepAgentEvent,\n writer: { write: (chunk: any) => void },\n genId: () => string,\n currentTextId: string | null\n): string | null {\n switch (event.type) {\n // ============================================================================\n // TEXT & FLOW EVENTS (Required for compatibility)\n // ============================================================================\n\n case 'step-start':\n writer.write({ type: 'start-step' });\n return currentTextId;\n\n case 'step-finish':\n writer.write({ type: 'finish-step' });\n return currentTextId;\n\n case 'text':\n // Start text if not already started\n if (!currentTextId) {\n const textId = genId();\n writer.write({\n type: 'text-start',\n id: textId\n });\n return textId;\n }\n writer.write({\n type: 'text-delta',\n id: currentTextId,\n delta: event.text\n });\n return currentTextId;\n\n // ============================================================================\n // TOOL EVENTS (Standard protocol events)\n // ============================================================================\n\n case 'tool-call':\n // End text before tool call\n if (currentTextId) {\n writer.write({\n type: 'text-end',\n id: currentTextId\n });\n currentTextId = null;\n }\n writer.write({\n type: 'tool-input-available',\n toolCallId: event.toolCallId,\n toolName: event.toolName,\n input: event.args\n });\n return null;\n\n case 'tool-result':\n if (event.isError) {\n writer.write({\n type: 'tool-output-error',\n toolCallId: event.toolCallId,\n errorText: String(event.result)\n });\n } else {\n writer.write({\n type: 'tool-output-available',\n toolCallId: event.toolCallId,\n output: event.result\n });\n }\n return currentTextId;\n\n // ============================================================================\n // TODO & PLANNING EVENTS\n // ============================================================================\n\n case 'todos-changed':\n writer.write({\n type: 'data',\n name: 'todos-changed',\n data: { todos: event.todos }\n });\n return currentTextId;\n\n // ============================================================================\n // FILE SYSTEM EVENTS (Custom data events)\n // ============================================================================\n\n case 'file-write-start':\n writer.write({\n type: 'data',\n name: 'file-write-start',\n data: {\n path: event.path,\n content: event.content\n }\n });\n return currentTextId;\n\n case 'file-written':\n writer.write({\n type: 'data',\n name: 'file-written',\n data: {\n path: event.path,\n content: event.content\n }\n });\n return currentTextId;\n\n case 'file-edited':\n writer.write({\n type: 'data',\n name: 'file-edited',\n data: {\n path: event.path,\n occurrences: event.occurrences\n }\n });\n return currentTextId;\n\n case 'file-read':\n writer.write({\n type: 'data',\n name: 'file-read',\n data: {\n path: event.path,\n lines: event.lines\n }\n });\n return currentTextId;\n\n case 'ls':\n writer.write({\n type: 'data',\n name: 'ls',\n data: {\n path: event.path,\n count: event.count\n }\n });\n return currentTextId;\n\n case 'glob':\n writer.write({\n type: 'data',\n name: 'glob',\n data: {\n pattern: event.pattern,\n count: event.count\n }\n });\n return currentTextId;\n\n case 'grep':\n writer.write({\n type: 'data',\n name: 'grep',\n data: {\n pattern: event.pattern,\n count: event.count\n }\n });\n return currentTextId;\n\n // ============================================================================\n // EXECUTION EVENTS (Custom data events)\n // ============================================================================\n\n case 'execute-start':\n writer.write({\n type: 'data',\n name: 'execute-start',\n data: {\n command: event.command,\n sandboxId: event.sandboxId\n }\n });\n return currentTextId;\n\n case 'execute-finish':\n writer.write({\n type: 'data',\n name: 'execute-finish',\n data: {\n command: event.command,\n exitCode: event.exitCode,\n truncated: event.truncated,\n sandboxId: event.sandboxId\n }\n });\n return currentTextId;\n\n // ============================================================================\n // WEB EVENTS (Custom data events)\n // ============================================================================\n\n case 'web-search-start':\n writer.write({\n type: 'data',\n name: 'web-search-start',\n data: {\n query: event.query\n }\n });\n return currentTextId;\n\n case 'web-search-finish':\n writer.write({\n type: 'data',\n name: 'web-search-finish',\n data: {\n query: event.query,\n resultCount: event.resultCount\n }\n });\n return currentTextId;\n\n case 'http-request-start':\n writer.write({\n type: 'data',\n name: 'http-request-start',\n data: {\n url: event.url,\n method: event.method\n }\n });\n return currentTextId;\n\n case 'http-request-finish':\n writer.write({\n type: 'data',\n name: 'http-request-finish',\n data: {\n url: event.url,\n statusCode: event.statusCode\n }\n });\n return currentTextId;\n\n case 'fetch-url-start':\n writer.write({\n type: 'data',\n name: 'fetch-url-start',\n data: {\n url: event.url\n }\n });\n return currentTextId;\n\n case 'fetch-url-finish':\n writer.write({\n type: 'data',\n name: 'fetch-url-finish',\n data: {\n url: event.url,\n success: event.success\n }\n });\n return currentTextId;\n\n // ============================================================================\n // SUBAGENT EVENTS (Custom data events)\n // ============================================================================\n\n case 'subagent-start':\n writer.write({\n type: 'data',\n name: 'subagent-start',\n data: {\n name: event.name,\n task: event.task\n }\n });\n return currentTextId;\n\n case 'subagent-finish':\n writer.write({\n type: 'data',\n name: 'subagent-finish',\n data: {\n name: event.name,\n result: event.result\n }\n });\n return currentTextId;\n\n case 'subagent-step':\n writer.write({\n type: 'data',\n name: 'subagent-step',\n data: {\n stepIndex: event.stepIndex,\n toolCalls: event.toolCalls\n }\n });\n return currentTextId;\n\n // ============================================================================\n // CHECKPOINT EVENTS (Custom data events)\n // ============================================================================\n\n case 'checkpoint-saved':\n writer.write({\n type: 'data',\n name: 'checkpoint-saved',\n data: {\n threadId: event.threadId,\n step: event.step\n }\n });\n return currentTextId;\n\n case 'checkpoint-loaded':\n writer.write({\n type: 'data',\n name: 'checkpoint-loaded',\n data: {\n threadId: event.threadId,\n step: event.step,\n messagesCount: event.messagesCount\n }\n });\n return currentTextId;\n\n // ============================================================================\n // CONTROL EVENTS\n // ============================================================================\n\n case 'error':\n // End text before error\n if (currentTextId) {\n writer.write({\n type: 'text-end',\n id: currentTextId\n });\n currentTextId = null;\n }\n writer.write({\n type: 'error',\n errorText: event.error.message\n });\n return null;\n\n case 'done':\n // End text before completion\n if (currentTextId) {\n writer.write({\n type: 'text-end',\n id: currentTextId\n });\n currentTextId = null;\n }\n // The finish event is auto-emitted by createUIMessageStream\n // We explicitly emit it here for clarity\n writer.write({\n type: 'finish',\n finishReason: 'stop',\n });\n return null;\n\n // Ignore unhandled events (text-segment, user-message, approval events)\n default:\n return currentTextId;\n }\n}\n\n/**\n * Type for the request handler returned by createElementsRouteHandler\n */\nexport type ElementsRouteHandler = (req: Request) => Promise<Response>;\n","/**\n * Message conversion utilities for AI SDK Elements adapter\n *\n * Provides utilities for converting between UI message formats and model message formats.\n * The primary conversion is handled by AI SDK's `convertToModelMessages`, but these\n * utilities provide additional helpers for DeepAgent-specific needs.\n */\n\nimport {\n convertToModelMessages,\n type UIMessage,\n} from \"ai\";\nimport type { ModelMessage } from \"../../types\";\n\n/**\n * Re-export AI SDK's convertToModelMessages for convenience.\n *\n * This function converts UIMessage[] (from useChat) to ModelMessage[]\n * (for agent consumption), handling:\n * - Role mapping (user/assistant)\n * - Tool call/result parts\n * - Text content extraction\n *\n * @example\n * ```typescript\n * import { convertUIMessagesToModelMessages } from 'deepagentsdk/adapters/elements';\n *\n * const modelMessages = await convertUIMessagesToModelMessages(uiMessages);\n * ```\n */\nexport async function convertUIMessagesToModelMessages(\n messages: UIMessage[]\n): Promise<ModelMessage[]> {\n return await convertToModelMessages(messages) as ModelMessage[];\n}\n\n/**\n * Extract the last user message text from a UIMessage array.\n * Useful for extracting the prompt from a conversation.\n *\n * @param messages - Array of UI messages\n * @returns The text content of the last user message, or undefined if none\n */\nexport function extractLastUserMessage(messages: UIMessage[]): string | undefined {\n // Find the last user message\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (msg && msg.role === \"user\" && msg.parts) {\n // Extract text parts\n const textParts = msg.parts.filter(\n (p): p is { type: \"text\"; text: string } => p.type === \"text\"\n );\n if (textParts.length > 0) {\n return textParts.map(p => p.text).join(\"\");\n }\n }\n }\n return undefined;\n}\n\n/**\n * Check if the messages contain any tool parts.\n * This is a simplified helper that checks for any tool-related parts.\n *\n * @param messages - Array of UI messages\n * @returns True if there are any tool-related parts in the messages\n */\nexport function hasToolParts(messages: UIMessage[]): boolean {\n for (const msg of messages) {\n if (!msg.parts) continue;\n for (const part of msg.parts) {\n // Tool parts have type starting with \"tool-\" or \"dynamic-tool\"\n if (part.type.startsWith(\"tool-\") || part.type === \"dynamic-tool\") {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Count the number of messages by role.\n *\n * @param messages - Array of UI messages\n * @returns Object with counts by role\n */\nexport function countMessagesByRole(\n messages: UIMessage[]\n): { user: number; assistant: number; system: number } {\n let user = 0;\n let assistant = 0;\n let system = 0;\n\n for (const msg of messages) {\n if (msg.role === \"user\") {\n user++;\n } else if (msg.role === \"assistant\") {\n assistant++;\n } else if (msg.role === \"system\") {\n system++;\n }\n }\n\n return { user, assistant, system };\n}\n\n/**\n * Extract all text content from a message.\n *\n * @param message - A UI message\n * @returns Combined text from all text parts\n */\nexport function extractTextFromMessage(message: UIMessage): string {\n if (!message.parts) return \"\";\n\n return message.parts\n .filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n .map(p => p.text)\n .join(\"\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsGA,SAAgB,2BACd,SACqC;CACrC,MAAM,EACJ,OACA,WACA,eAAe;EACb,OAAO,EAAE;EACT,OAAO,EAAE;EACV,EACD,UACA,UACA,eACE;AAEJ,QAAO,OAAO,QAAoC;AAEhD,MAAI,UACF,KAAI;AACF,SAAM,UAAU,IAAI;WACb,OAAO;AACd,UAAO,IAAI,SACT,KAAK,UAAU,EACb,OAAO,iBAAiB,QAAQ,MAAM,UAAU,oBACjD,CAAC,EACF;IACE,QAAQ;IACR,SAAS,EAAE,gBAAgB,oBAAoB;IAChD,CACF;;EAKL,IAAI;AACJ,MAAI;AACF,iBAAc,MAAM,IAAI,MAAM;UACxB;AACN,UAAO,IAAI,SACT,KAAK,UAAU,EAAE,OAAO,qBAAqB,CAAC,EAC9C;IACE,QAAQ;IACR,SAAS,EAAE,gBAAgB,oBAAoB;IAChD,CACF;;EAGH,MAAM,EAAE,aAAa;AACrB,MAAI,CAAC,YAAY,CAAC,MAAM,QAAQ,SAAS,CACvC,QAAO,IAAI,SACT,KAAK,UAAU,EAAE,OAAO,8BAA8B,CAAC,EACvD;GACE,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAChD,CACF;EAIH,MAAM,gBAAgB,MAAM,uBAAuB,SAAS;EAG5D,MAAM,QAAQ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