@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,314 @@
1
+ import { env } from "cloudflare:test";
2
+ import { describe, it, expect } from "vitest";
3
+ import { MessageType } from "../types";
4
+ import type { UIMessage as ChatMessage } from "ai";
5
+ import { connectChatWS } from "./test-utils";
6
+ import { getAgentByName } from "agents";
7
+
8
+ describe("Client tools continuation", () => {
9
+ it("should pass client tools to onChatMessage during auto-continuation", async () => {
10
+ const room = crypto.randomUUID();
11
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
12
+
13
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
14
+ await agentStub.clearCapturedContext();
15
+
16
+ // Step 1: Send initial chat request WITH client tools to store them
17
+ let resolvePromise: (value: boolean) => void;
18
+ let donePromise = new Promise<boolean>((res) => {
19
+ resolvePromise = res;
20
+ });
21
+
22
+ let timeout = setTimeout(() => resolvePromise(false), 2000);
23
+
24
+ ws.addEventListener("message", function handler(e: MessageEvent) {
25
+ const data = JSON.parse(e.data as string);
26
+ if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && data.done) {
27
+ clearTimeout(timeout);
28
+ resolvePromise(true);
29
+ ws.removeEventListener("message", handler);
30
+ }
31
+ });
32
+
33
+ const userMessage: ChatMessage = {
34
+ id: "msg1",
35
+ role: "user",
36
+ parts: [{ type: "text", text: "Hello" }]
37
+ };
38
+
39
+ const clientTools = [
40
+ {
41
+ name: "changeBackgroundColor",
42
+ description: "Changes the background color",
43
+ parameters: {
44
+ type: "object",
45
+ properties: { color: { type: "string" } }
46
+ }
47
+ },
48
+ {
49
+ name: "changeTextColor",
50
+ description: "Changes the text color",
51
+ parameters: {
52
+ type: "object",
53
+ properties: { color: { type: "string" } }
54
+ }
55
+ }
56
+ ];
57
+
58
+ ws.send(
59
+ JSON.stringify({
60
+ type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
61
+ id: "req1",
62
+ init: {
63
+ method: "POST",
64
+ body: JSON.stringify({ messages: [userMessage], clientTools })
65
+ }
66
+ })
67
+ );
68
+
69
+ let done = await donePromise;
70
+ expect(done).toBe(true);
71
+
72
+ // Verify initial request received client tools
73
+ await new Promise((resolve) => setTimeout(resolve, 100));
74
+ const initialClientTools = await agentStub.getCapturedClientTools();
75
+ expect(initialClientTools).toBeDefined();
76
+ expect(initialClientTools).toHaveLength(2);
77
+
78
+ // Step 2: Persist a tool call in input-available state
79
+ const toolCallId = "call_continuation_test";
80
+ await agentStub.persistMessages([
81
+ userMessage,
82
+ {
83
+ id: "assistant-1",
84
+ role: "assistant",
85
+ parts: [
86
+ {
87
+ type: "tool-changeBackgroundColor",
88
+ toolCallId,
89
+ state: "input-available",
90
+ input: { color: "green" }
91
+ }
92
+ ] as ChatMessage["parts"]
93
+ }
94
+ ]);
95
+
96
+ // Step 3: Clear captured state before continuation
97
+ await agentStub.clearCapturedContext();
98
+
99
+ // Step 4: Send tool result with autoContinue to trigger continuation
100
+ ws.send(
101
+ JSON.stringify({
102
+ type: "cf_agent_tool_result",
103
+ toolCallId,
104
+ toolName: "changeBackgroundColor",
105
+ output: { success: true },
106
+ autoContinue: true
107
+ })
108
+ );
109
+
110
+ // Wait for continuation (500ms stream wait + processing)
111
+ await new Promise((resolve) => setTimeout(resolve, 1000));
112
+
113
+ // Step 5: Verify continuation received client tools
114
+ const continuationClientTools = await agentStub.getCapturedClientTools();
115
+ expect(continuationClientTools).toBeDefined();
116
+ expect(continuationClientTools).toHaveLength(2);
117
+ expect(continuationClientTools).toEqual(clientTools);
118
+
119
+ ws.close(1000);
120
+ });
121
+
122
+ it("should clear stored client tools when chat is cleared", async () => {
123
+ const room = crypto.randomUUID();
124
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
125
+
126
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
127
+
128
+ // Send initial request with client tools to store them
129
+ let resolvePromise: (value: boolean) => void;
130
+ const donePromise = new Promise<boolean>((res) => {
131
+ resolvePromise = res;
132
+ });
133
+
134
+ const timeout = setTimeout(() => resolvePromise(false), 2000);
135
+
136
+ ws.addEventListener("message", function handler(e: MessageEvent) {
137
+ const data = JSON.parse(e.data as string);
138
+ if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && data.done) {
139
+ clearTimeout(timeout);
140
+ resolvePromise(true);
141
+ ws.removeEventListener("message", handler);
142
+ }
143
+ });
144
+
145
+ ws.send(
146
+ JSON.stringify({
147
+ type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
148
+ id: "req1",
149
+ init: {
150
+ method: "POST",
151
+ body: JSON.stringify({
152
+ messages: [
153
+ {
154
+ id: "msg1",
155
+ role: "user",
156
+ parts: [{ type: "text", text: "Hi" }]
157
+ }
158
+ ],
159
+ clientTools: [{ name: "testTool", description: "Test" }]
160
+ })
161
+ }
162
+ })
163
+ );
164
+
165
+ const done = await donePromise;
166
+ expect(done).toBe(true);
167
+
168
+ // Clear chat
169
+ ws.send(JSON.stringify({ type: MessageType.CF_AGENT_CHAT_CLEAR }));
170
+ await new Promise((resolve) => setTimeout(resolve, 200));
171
+
172
+ // Persist a tool call and trigger continuation
173
+ await agentStub.persistMessages([
174
+ {
175
+ id: "user-1",
176
+ role: "user",
177
+ parts: [{ type: "text", text: "Execute tool" }]
178
+ },
179
+ {
180
+ id: "assistant-1",
181
+ role: "assistant",
182
+ parts: [
183
+ {
184
+ type: "tool-testTool",
185
+ toolCallId: "call_after_clear",
186
+ state: "input-available",
187
+ input: {}
188
+ }
189
+ ] as ChatMessage["parts"]
190
+ }
191
+ ]);
192
+
193
+ await agentStub.clearCapturedContext();
194
+
195
+ ws.send(
196
+ JSON.stringify({
197
+ type: "cf_agent_tool_result",
198
+ toolCallId: "call_after_clear",
199
+ toolName: "testTool",
200
+ output: { success: true },
201
+ autoContinue: true
202
+ })
203
+ );
204
+
205
+ await new Promise((resolve) => setTimeout(resolve, 1000));
206
+
207
+ // Client tools should be undefined after chat clear
208
+ const continuationClientTools = await agentStub.getCapturedClientTools();
209
+ expect(continuationClientTools).toBeUndefined();
210
+
211
+ ws.close(1000);
212
+ });
213
+
214
+ it("should clear stored client tools when new request has no client tools", async () => {
215
+ const room = crypto.randomUUID();
216
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
217
+
218
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
219
+
220
+ // Send first request WITH client tools
221
+ let resolvePromise: (value: boolean) => void;
222
+ let donePromise = new Promise<boolean>((res) => {
223
+ resolvePromise = res;
224
+ });
225
+ let timeout = setTimeout(() => resolvePromise(false), 2000);
226
+
227
+ const handler1 = (e: MessageEvent) => {
228
+ const data = JSON.parse(e.data as string);
229
+ if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && data.done) {
230
+ clearTimeout(timeout);
231
+ resolvePromise(true);
232
+ }
233
+ };
234
+ ws.addEventListener("message", handler1);
235
+
236
+ ws.send(
237
+ JSON.stringify({
238
+ type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
239
+ id: "req1",
240
+ init: {
241
+ method: "POST",
242
+ body: JSON.stringify({
243
+ messages: [
244
+ {
245
+ id: "msg1",
246
+ role: "user",
247
+ parts: [{ type: "text", text: "Hi" }]
248
+ }
249
+ ],
250
+ clientTools: [{ name: "testTool", description: "Test" }]
251
+ })
252
+ }
253
+ })
254
+ );
255
+
256
+ let done = await donePromise;
257
+ expect(done).toBe(true);
258
+ ws.removeEventListener("message", handler1);
259
+
260
+ await new Promise((resolve) => setTimeout(resolve, 100));
261
+ let capturedTools = await agentStub.getCapturedClientTools();
262
+ expect(capturedTools).toHaveLength(1);
263
+
264
+ // Send second request WITHOUT client tools
265
+ donePromise = new Promise<boolean>((res) => {
266
+ resolvePromise = res;
267
+ });
268
+ timeout = setTimeout(() => resolvePromise(false), 2000);
269
+
270
+ const handler2 = (e: MessageEvent) => {
271
+ const data = JSON.parse(e.data as string);
272
+ if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && data.done) {
273
+ clearTimeout(timeout);
274
+ resolvePromise(true);
275
+ }
276
+ };
277
+ ws.addEventListener("message", handler2);
278
+
279
+ ws.send(
280
+ JSON.stringify({
281
+ type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
282
+ id: "req2",
283
+ init: {
284
+ method: "POST",
285
+ body: JSON.stringify({
286
+ messages: [
287
+ {
288
+ id: "msg1",
289
+ role: "user",
290
+ parts: [{ type: "text", text: "Hi" }]
291
+ },
292
+ {
293
+ id: "msg2",
294
+ role: "user",
295
+ parts: [{ type: "text", text: "Again" }]
296
+ }
297
+ ]
298
+ // No clientTools
299
+ })
300
+ }
301
+ })
302
+ );
303
+
304
+ done = await donePromise;
305
+ expect(done).toBe(true);
306
+ ws.removeEventListener("message", handler2);
307
+
308
+ await new Promise((resolve) => setTimeout(resolve, 100));
309
+ capturedTools = await agentStub.getCapturedClientTools();
310
+ expect(capturedTools).toBeUndefined();
311
+
312
+ ws.close(1000);
313
+ });
314
+ });
@@ -0,0 +1,143 @@
1
+ import { env } from "cloudflare:test";
2
+ import { describe, it, expect } from "vitest";
3
+ import { MessageType } from "../types";
4
+ import type { UIMessage as ChatMessage } from "ai";
5
+ import { connectChatWS } from "./test-utils";
6
+ import { getAgentByName } from "agents";
7
+
8
+ describe("Client tools after reconnect", () => {
9
+ it("should use client tools from CF_AGENT_TOOL_RESULT for continuation", async () => {
10
+ const room = crypto.randomUUID();
11
+
12
+ // Step 1: Set up a conversation with a pending tool call (simulates state before refresh)
13
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
14
+
15
+ const userMessage: ChatMessage = {
16
+ id: "msg1",
17
+ role: "user",
18
+ parts: [{ type: "text", text: "Change the background" }]
19
+ };
20
+
21
+ const toolCallId = "call_reconnect_test";
22
+ const assistantMessage: ChatMessage = {
23
+ id: "assistant-1",
24
+ role: "assistant",
25
+ parts: [
26
+ {
27
+ type: "tool-changeBackgroundColor",
28
+ toolCallId,
29
+ state: "input-available",
30
+ input: { color: "blue" }
31
+ }
32
+ ] as ChatMessage["parts"]
33
+ };
34
+
35
+ // Persist messages directly (simulates state loaded from SQLite after DO restart)
36
+ await agentStub.persistMessages([userMessage, assistantMessage]);
37
+
38
+ // Step 2: Connect (simulates reconnect after refresh)
39
+ // Note: We intentionally do NOT send a CF_AGENT_USE_CHAT_REQUEST first,
40
+ // so _lastClientTools is never set — this simulates DO restart.
41
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
42
+
43
+ // Wait for connection to be established
44
+ await new Promise((resolve) => setTimeout(resolve, 200));
45
+
46
+ // Clear any captured context from connection setup
47
+ await agentStub.clearCapturedContext();
48
+
49
+ // Step 3: Send tool result WITH clientTools (simulates client approval after reconnect)
50
+ const clientTools = [
51
+ {
52
+ name: "changeBackgroundColor",
53
+ description: "Changes the background color",
54
+ parameters: {
55
+ type: "object",
56
+ properties: { color: { type: "string" } }
57
+ }
58
+ },
59
+ {
60
+ name: "changeTextColor",
61
+ description: "Changes the text color",
62
+ parameters: {
63
+ type: "object",
64
+ properties: { color: { type: "string" } }
65
+ }
66
+ }
67
+ ];
68
+
69
+ ws.send(
70
+ JSON.stringify({
71
+ type: MessageType.CF_AGENT_TOOL_RESULT,
72
+ toolCallId,
73
+ toolName: "changeBackgroundColor",
74
+ output: { success: true },
75
+ autoContinue: true,
76
+ clientTools
77
+ })
78
+ );
79
+
80
+ // Wait for tool result to be applied + 500ms stream wait + continuation
81
+ await new Promise((resolve) => setTimeout(resolve, 1500));
82
+
83
+ // Step 4: Verify continuation received client tools
84
+ const capturedClientTools = await agentStub.getCapturedClientTools();
85
+ expect(capturedClientTools).toBeDefined();
86
+ expect(capturedClientTools).toHaveLength(2);
87
+ expect(capturedClientTools![0].name).toBe("changeBackgroundColor");
88
+ expect(capturedClientTools![1].name).toBe("changeTextColor");
89
+
90
+ ws.close(1000);
91
+ });
92
+
93
+ it("should work without clientTools in CF_AGENT_TOOL_RESULT (backwards compat)", async () => {
94
+ const room = crypto.randomUUID();
95
+
96
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
97
+
98
+ // Persist a conversation with a pending tool call
99
+ await agentStub.persistMessages([
100
+ {
101
+ id: "msg1",
102
+ role: "user",
103
+ parts: [{ type: "text", text: "Do something" }]
104
+ },
105
+ {
106
+ id: "assistant-1",
107
+ role: "assistant",
108
+ parts: [
109
+ {
110
+ type: "tool-testTool",
111
+ toolCallId: "call_compat_test",
112
+ state: "input-available",
113
+ input: {}
114
+ }
115
+ ] as ChatMessage["parts"]
116
+ }
117
+ ]);
118
+
119
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
120
+ await new Promise((resolve) => setTimeout(resolve, 200));
121
+ await agentStub.clearCapturedContext();
122
+
123
+ // Send tool result WITHOUT clientTools (old client behavior)
124
+ ws.send(
125
+ JSON.stringify({
126
+ type: MessageType.CF_AGENT_TOOL_RESULT,
127
+ toolCallId: "call_compat_test",
128
+ toolName: "testTool",
129
+ output: { success: true },
130
+ autoContinue: true
131
+ // No clientTools field
132
+ })
133
+ );
134
+
135
+ await new Promise((resolve) => setTimeout(resolve, 1500));
136
+
137
+ // Continuation should still fire, just without client tools
138
+ const capturedClientTools = await agentStub.getCapturedClientTools();
139
+ expect(capturedClientTools).toBeUndefined();
140
+
141
+ ws.close(1000);
142
+ });
143
+ });