@cloudflare/ai-chat 0.0.7 → 0.1.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.
Files changed (60) hide show
  1. package/CHANGELOG.md +105 -0
  2. package/README.md +225 -459
  3. package/dist/ai-chat-v5-migration.d.ts +9 -9
  4. package/dist/ai-chat-v5-migration.js +25 -4
  5. package/dist/ai-chat-v5-migration.js.map +1 -1
  6. package/dist/experimental/forever.d.ts +29 -0
  7. package/dist/experimental/forever.js +55 -0
  8. package/dist/experimental/forever.js.map +1 -0
  9. package/dist/index.d.ts +126 -74
  10. package/dist/index.js +753 -632
  11. package/dist/index.js.map +1 -1
  12. package/dist/message-builder-Bwc_Umye.js +231 -0
  13. package/dist/message-builder-Bwc_Umye.js.map +1 -0
  14. package/dist/react.d.ts +27 -9
  15. package/dist/react.js +248 -259
  16. package/dist/react.js.map +1 -1
  17. package/dist/resumable-stream-DqXxQVjf.d.ts +103 -0
  18. package/dist/types.d.ts +16 -4
  19. package/dist/types.js +2 -0
  20. package/dist/types.js.map +1 -1
  21. package/e2e/chat.spec.ts +1703 -0
  22. package/e2e/client-tools.spec.ts +504 -0
  23. package/e2e/llm.spec.ts +637 -0
  24. package/e2e/playwright.config.ts +24 -0
  25. package/e2e/worker.ts +176 -0
  26. package/e2e/wrangler.jsonc +23 -0
  27. package/package.json +12 -5
  28. package/scripts/build.ts +2 -1
  29. package/src/ai-chat-v5-migration.ts +32 -5
  30. package/src/experimental/forever.ts +66 -0
  31. package/src/index.ts +850 -1132
  32. package/src/message-builder.ts +384 -0
  33. package/src/react-tests/use-agent-chat.test.tsx +738 -2
  34. package/src/react.tsx +396 -462
  35. package/src/resumable-stream.ts +441 -0
  36. package/src/tests/chat-context.test.ts +1 -1
  37. package/src/tests/chat-persistence.test.ts +5 -5
  38. package/src/tests/clear-history.test.ts +132 -0
  39. package/src/tests/client-tool-duplicate-message.test.ts +457 -14
  40. package/src/tests/client-tools-broadcast.test.ts +2 -2
  41. package/src/tests/client-tools-continuation.test.ts +314 -0
  42. package/src/tests/client-tools-reconnect.test.ts +143 -0
  43. package/src/tests/custom-body-continuation.test.ts +309 -0
  44. package/src/tests/custom-body.test.ts +186 -0
  45. package/src/tests/destroy.test.ts +57 -0
  46. package/src/tests/get-messages-endpoint.test.ts +79 -0
  47. package/src/tests/max-persisted-messages.test.ts +201 -0
  48. package/src/tests/merge-server-state.test.ts +106 -0
  49. package/src/tests/message-builder.test.ts +808 -0
  50. package/src/tests/migration.test.ts +282 -0
  51. package/src/tests/non-sse-response.test.ts +2 -2
  52. package/src/tests/onfinish-cleanup.test.ts +362 -0
  53. package/src/tests/plaintext-response.test.ts +87 -0
  54. package/src/tests/resumable-streaming.test.ts +220 -14
  55. package/src/tests/row-size-guard.test.ts +374 -0
  56. package/src/tests/sanitize-messages.test.ts +215 -0
  57. package/src/tests/validate-messages.test.ts +269 -0
  58. package/src/tests/worker.ts +85 -23
  59. package/src/types.ts +17 -1
  60. package/src/ws-chat-transport.ts +203 -0
@@ -0,0 +1,384 @@
1
+ /**
2
+ * Shared message builder for reconstructing UIMessage parts from stream chunks.
3
+ *
4
+ * Used by both the server (_streamSSEReply) and client (onAgentMessage in react.tsx)
5
+ * to avoid duplicating the chunk-type switch/case logic. The server handles additional
6
+ * chunk types (tool-input-start, tool-input-delta, etc.) on top of this shared base.
7
+ *
8
+ * Operates on a mutable parts array for performance (avoids allocating new arrays
9
+ * on every chunk during streaming).
10
+ */
11
+
12
+ import type { UIMessage } from "ai";
13
+
14
+ /** The parts array type from UIMessage */
15
+ export type MessageParts = UIMessage["parts"];
16
+
17
+ /** A single part from the UIMessage parts array */
18
+ export type MessagePart = MessageParts[number];
19
+
20
+ /**
21
+ * Parsed chunk data from an AI SDK stream event.
22
+ * This is the JSON-parsed body of a CF_AGENT_USE_CHAT_RESPONSE message,
23
+ * or the `data:` payload of an SSE line.
24
+ */
25
+ export type StreamChunkData = {
26
+ type: string;
27
+ id?: string;
28
+ delta?: string;
29
+ text?: string;
30
+ mediaType?: string;
31
+ url?: string;
32
+ sourceId?: string;
33
+ title?: string;
34
+ filename?: string;
35
+ toolCallId?: string;
36
+ toolName?: string;
37
+ input?: unknown;
38
+ inputTextDelta?: string;
39
+ output?: unknown;
40
+ state?: string;
41
+ errorText?: string;
42
+ /** When true, the output is preliminary (may be updated by a later chunk) */
43
+ preliminary?: boolean;
44
+ /** Approval ID for tools with needsApproval */
45
+ approvalId?: string;
46
+ providerMetadata?: Record<string, unknown>;
47
+ /** Payload for data-* parts (developer-defined typed JSON) */
48
+ data?: unknown;
49
+ /** When true, data parts are ephemeral and not persisted to message.parts */
50
+ transient?: boolean;
51
+ [key: string]: unknown;
52
+ };
53
+
54
+ /**
55
+ * Applies a stream chunk to a mutable parts array, building up the message
56
+ * incrementally. Returns true if the chunk was handled, false if it was
57
+ * an unrecognized type (caller may handle it with additional logic).
58
+ *
59
+ * Handles all common chunk types that both server and client need:
60
+ * - text-start / text-delta / text-end
61
+ * - reasoning-start / reasoning-delta / reasoning-end
62
+ * - file
63
+ * - source-url / source-document
64
+ * - tool-input-start / tool-input-delta / tool-input-available / tool-input-error
65
+ * - tool-output-available / tool-output-error
66
+ * - step-start (aliased from start-step)
67
+ * - data-* (developer-defined typed JSON blobs)
68
+ *
69
+ * @param parts - The mutable parts array to update
70
+ * @param chunk - The parsed stream chunk data
71
+ * @returns true if handled, false if the chunk type is not recognized
72
+ */
73
+ export function applyChunkToParts(
74
+ parts: MessagePart[],
75
+ chunk: StreamChunkData
76
+ ): boolean {
77
+ switch (chunk.type) {
78
+ case "text-start": {
79
+ parts.push({
80
+ type: "text",
81
+ text: "",
82
+ state: "streaming"
83
+ } as MessagePart);
84
+ return true;
85
+ }
86
+
87
+ case "text-delta": {
88
+ const lastTextPart = findLastPartByType(parts, "text");
89
+ if (lastTextPart && lastTextPart.type === "text") {
90
+ (lastTextPart as { text: string }).text += chunk.delta ?? "";
91
+ } else {
92
+ // No text-start received — create a new text part (stream resumption fallback)
93
+ parts.push({
94
+ type: "text",
95
+ text: chunk.delta ?? "",
96
+ state: "streaming"
97
+ } as MessagePart);
98
+ }
99
+ return true;
100
+ }
101
+
102
+ case "text-end": {
103
+ const lastTextPart = findLastPartByType(parts, "text");
104
+ if (lastTextPart && "state" in lastTextPart) {
105
+ (lastTextPart as { state: string }).state = "done";
106
+ }
107
+ return true;
108
+ }
109
+
110
+ case "reasoning-start": {
111
+ parts.push({
112
+ type: "reasoning",
113
+ text: "",
114
+ state: "streaming"
115
+ } as MessagePart);
116
+ return true;
117
+ }
118
+
119
+ case "reasoning-delta": {
120
+ const lastReasoningPart = findLastPartByType(parts, "reasoning");
121
+ if (lastReasoningPart && lastReasoningPart.type === "reasoning") {
122
+ (lastReasoningPart as { text: string }).text += chunk.delta ?? "";
123
+ } else {
124
+ // No reasoning-start received — create a new reasoning part (stream resumption fallback)
125
+ parts.push({
126
+ type: "reasoning",
127
+ text: chunk.delta ?? "",
128
+ state: "streaming"
129
+ } as MessagePart);
130
+ }
131
+ return true;
132
+ }
133
+
134
+ case "reasoning-end": {
135
+ const lastReasoningPart = findLastPartByType(parts, "reasoning");
136
+ if (lastReasoningPart && "state" in lastReasoningPart) {
137
+ (lastReasoningPart as { state: string }).state = "done";
138
+ }
139
+ return true;
140
+ }
141
+
142
+ case "file": {
143
+ parts.push({
144
+ type: "file",
145
+ mediaType: chunk.mediaType,
146
+ url: chunk.url
147
+ } as MessagePart);
148
+ return true;
149
+ }
150
+
151
+ case "source-url": {
152
+ parts.push({
153
+ type: "source-url",
154
+ sourceId: chunk.sourceId,
155
+ url: chunk.url,
156
+ title: chunk.title,
157
+ providerMetadata: chunk.providerMetadata
158
+ } as MessagePart);
159
+ return true;
160
+ }
161
+
162
+ case "source-document": {
163
+ parts.push({
164
+ type: "source-document",
165
+ sourceId: chunk.sourceId,
166
+ mediaType: chunk.mediaType,
167
+ title: chunk.title,
168
+ filename: chunk.filename,
169
+ providerMetadata: chunk.providerMetadata
170
+ } as MessagePart);
171
+ return true;
172
+ }
173
+
174
+ case "tool-input-start": {
175
+ // Create a tool part in input-streaming state with no input yet.
176
+ // Cross-tab clients see the tool appear immediately with "streaming" indicator.
177
+ parts.push({
178
+ type: `tool-${chunk.toolName}`,
179
+ toolCallId: chunk.toolCallId,
180
+ toolName: chunk.toolName,
181
+ state: "input-streaming",
182
+ input: undefined
183
+ } as MessagePart);
184
+ return true;
185
+ }
186
+
187
+ case "tool-input-delta": {
188
+ // Update the existing tool part with partial input as it streams in.
189
+ const toolPart = findToolPartByCallId(parts, chunk.toolCallId);
190
+ if (toolPart) {
191
+ (toolPart as Record<string, unknown>).input = chunk.input;
192
+ }
193
+ return true;
194
+ }
195
+
196
+ case "tool-input-available": {
197
+ // Finalize the tool input. If tool-input-start was received, update
198
+ // the existing part; otherwise create a new one (for non-streaming tools).
199
+ const existing = findToolPartByCallId(parts, chunk.toolCallId);
200
+ if (existing) {
201
+ const p = existing as Record<string, unknown>;
202
+ p.state = "input-available";
203
+ p.input = chunk.input;
204
+ } else {
205
+ parts.push({
206
+ type: `tool-${chunk.toolName}`,
207
+ toolCallId: chunk.toolCallId,
208
+ toolName: chunk.toolName,
209
+ state: "input-available",
210
+ input: chunk.input
211
+ } as MessagePart);
212
+ }
213
+ return true;
214
+ }
215
+
216
+ case "tool-input-error": {
217
+ // Tool input parsing failed. Update existing part or create one.
218
+ const existing = findToolPartByCallId(parts, chunk.toolCallId);
219
+ if (existing) {
220
+ const p = existing as Record<string, unknown>;
221
+ p.state = "output-error";
222
+ p.errorText = chunk.errorText;
223
+ p.input = chunk.input;
224
+ } else {
225
+ parts.push({
226
+ type: `tool-${chunk.toolName}`,
227
+ toolCallId: chunk.toolCallId,
228
+ toolName: chunk.toolName,
229
+ state: "output-error",
230
+ input: chunk.input,
231
+ errorText: chunk.errorText
232
+ } as MessagePart);
233
+ }
234
+ return true;
235
+ }
236
+
237
+ case "tool-approval-request": {
238
+ // Tool requires user approval before executing.
239
+ // Transition the tool part to approval-requested state with the approval ID.
240
+ const toolPart = findToolPartByCallId(parts, chunk.toolCallId);
241
+ if (toolPart) {
242
+ const p = toolPart as Record<string, unknown>;
243
+ p.state = "approval-requested";
244
+ p.approval = { id: chunk.approvalId };
245
+ }
246
+ return true;
247
+ }
248
+
249
+ case "tool-output-denied": {
250
+ // User rejected the tool approval request.
251
+ const toolPart = findToolPartByCallId(parts, chunk.toolCallId);
252
+ if (toolPart) {
253
+ const p = toolPart as Record<string, unknown>;
254
+ p.state = "output-denied";
255
+ }
256
+ return true;
257
+ }
258
+
259
+ case "tool-output-available": {
260
+ // Update existing tool part with output.
261
+ // Supports `preliminary: true` for streaming tool results —
262
+ // the output may be updated by a subsequent chunk.
263
+ const toolPart = findToolPartByCallId(parts, chunk.toolCallId);
264
+ if (toolPart) {
265
+ const p = toolPart as Record<string, unknown>;
266
+ p.state = "output-available";
267
+ p.output = chunk.output;
268
+ if (chunk.preliminary !== undefined) {
269
+ p.preliminary = chunk.preliminary;
270
+ }
271
+ }
272
+ return true;
273
+ }
274
+
275
+ case "tool-output-error": {
276
+ // Tool execution failed. Update the existing tool part.
277
+ const toolPart = findToolPartByCallId(parts, chunk.toolCallId);
278
+ if (toolPart) {
279
+ const p = toolPart as Record<string, unknown>;
280
+ p.state = "output-error";
281
+ p.errorText = chunk.errorText;
282
+ }
283
+ return true;
284
+ }
285
+
286
+ // Both "step-start" (client convention) and "start-step" (server convention)
287
+ case "step-start":
288
+ case "start-step": {
289
+ parts.push({ type: "step-start" } as MessagePart);
290
+ return true;
291
+ }
292
+
293
+ default: {
294
+ // https://ai-sdk.dev/docs/ai-sdk-ui/streaming-data
295
+ if (chunk.type.startsWith("data-")) {
296
+ // Transient parts are ephemeral — the AI SDK client fires an onData
297
+ // callback instead of adding them to message.parts. On the server we
298
+ // still broadcast them (so connected clients see them in real time)
299
+ // but skip persisting them into the stored message parts.
300
+ if (chunk.transient) {
301
+ return true;
302
+ }
303
+
304
+ // Reconciliation: if a part with the same type AND id already exists,
305
+ // update its data in-place instead of appending a duplicate.
306
+ if (chunk.id != null) {
307
+ const existing = findDataPartByTypeAndId(parts, chunk.type, chunk.id);
308
+ if (existing) {
309
+ (existing as Record<string, unknown>).data = chunk.data;
310
+ return true;
311
+ }
312
+ }
313
+
314
+ // Append new data parts to the array directly.
315
+ // Note: `chunk.data` should always be provided — if omitted, the
316
+ // persisted part will have `data: undefined` which JSON.stringify
317
+ // drops, so the part will have no `data` field on reload.
318
+ // The cast is needed because UIMessage["parts"] doesn't include
319
+ // data-* types in its union because they're an open extension point.
320
+ parts.push({
321
+ type: chunk.type,
322
+ ...(chunk.id != null && { id: chunk.id }),
323
+ data: chunk.data
324
+ } as MessagePart);
325
+ return true;
326
+ }
327
+
328
+ return false;
329
+ }
330
+ }
331
+ }
332
+
333
+ /**
334
+ * Finds the last part in the array matching the given type.
335
+ * Searches from the end for efficiency (the part we want is usually recent).
336
+ */
337
+ function findLastPartByType(
338
+ parts: MessagePart[],
339
+ type: string
340
+ ): MessagePart | undefined {
341
+ for (let i = parts.length - 1; i >= 0; i--) {
342
+ if (parts[i].type === type) {
343
+ return parts[i];
344
+ }
345
+ }
346
+ return undefined;
347
+ }
348
+
349
+ /**
350
+ * Finds a tool part by its toolCallId.
351
+ * Searches from the end since the tool part is usually recent.
352
+ */
353
+ function findToolPartByCallId(
354
+ parts: MessagePart[],
355
+ toolCallId: string | undefined
356
+ ): MessagePart | undefined {
357
+ if (!toolCallId) return undefined;
358
+ for (let i = parts.length - 1; i >= 0; i--) {
359
+ const p = parts[i];
360
+ if ("toolCallId" in p && p.toolCallId === toolCallId) {
361
+ return p;
362
+ }
363
+ }
364
+ return undefined;
365
+ }
366
+
367
+ /**
368
+ * Finds a data part by its type and id for reconciliation.
369
+ * Data parts use type+id as a composite key so when the same combination
370
+ * is seen again, the existing part's data is updated in-place.
371
+ */
372
+ function findDataPartByTypeAndId(
373
+ parts: MessagePart[],
374
+ type: string,
375
+ id: string
376
+ ): MessagePart | undefined {
377
+ for (let i = parts.length - 1; i >= 0; i--) {
378
+ const p = parts[i];
379
+ if (p.type === type && "id" in p && (p as { id: string }).id === id) {
380
+ return p;
381
+ }
382
+ }
383
+ return undefined;
384
+ }