@cloudflare/ai-chat 0.0.8 → 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 +89 -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 +114 -76
  10. package/dist/index.js +745 -629
  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 +244 -258
  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 +831 -1137
  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 +385 -461
  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 +3 -3
  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 +3 -3
  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 +59 -24
  59. package/src/types.ts +17 -1
  60. package/src/ws-chat-transport.ts +203 -0
@@ -0,0 +1,269 @@
1
+ import { createExecutionContext, env } from "cloudflare:test";
2
+ import { describe, it, expect } from "vitest";
3
+ import worker from "./worker";
4
+ import type { UIMessage as ChatMessage } from "ai";
5
+ import { getAgentByName } from "agents";
6
+
7
+ describe("Message Structural Validation", () => {
8
+ async function setupAgent(room: string) {
9
+ const ctx = createExecutionContext();
10
+ const req = new Request(
11
+ `http://example.com/agents/test-chat-agent/${room}`,
12
+ { headers: { Upgrade: "websocket" } }
13
+ );
14
+ const res = await worker.fetch(req, env, ctx);
15
+ expect(res.status).toBe(101);
16
+ const ws = res.webSocket as WebSocket;
17
+ ws.accept();
18
+ await ctx.waitUntil(Promise.resolve());
19
+
20
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
21
+ return { ws, agentStub };
22
+ }
23
+
24
+ /**
25
+ * Fetch messages via the /get-messages HTTP endpoint, which goes through
26
+ * _loadMessagesFromDb() and applies structural validation.
27
+ */
28
+ async function getValidatedMessages(room: string): Promise<ChatMessage[]> {
29
+ const getMessagesReq = new Request(
30
+ `http://example.com/agents/test-chat-agent/${room}/get-messages`
31
+ );
32
+ const getMessagesRes = await worker.fetch(
33
+ getMessagesReq,
34
+ env,
35
+ createExecutionContext()
36
+ );
37
+ expect(getMessagesRes.status).toBe(200);
38
+ return (await getMessagesRes.json()) as ChatMessage[];
39
+ }
40
+
41
+ it("loads valid messages without filtering", async () => {
42
+ const room = crypto.randomUUID();
43
+ const { ws, agentStub } = await setupAgent(room);
44
+
45
+ const messages: ChatMessage[] = [
46
+ { id: "msg1", role: "user", parts: [{ type: "text", text: "Hello" }] },
47
+ {
48
+ id: "msg2",
49
+ role: "assistant",
50
+ parts: [{ type: "text", text: "Hi!" }]
51
+ }
52
+ ];
53
+
54
+ await agentStub.persistMessages(messages);
55
+
56
+ const persisted = await getValidatedMessages(room);
57
+ expect(persisted.length).toBe(2);
58
+ expect(persisted[0].id).toBe("msg1");
59
+ expect(persisted[1].id).toBe("msg2");
60
+
61
+ ws.close(1000);
62
+ });
63
+
64
+ it("filters out messages with missing id", async () => {
65
+ const room = crypto.randomUUID();
66
+ const { ws, agentStub } = await setupAgent(room);
67
+
68
+ await agentStub.persistMessages([
69
+ { id: "valid1", role: "user", parts: [{ type: "text", text: "Hello" }] }
70
+ ]);
71
+
72
+ // Manually insert a malformed message (no id field)
73
+ agentStub.insertRawMessage(
74
+ "bad-no-id",
75
+ JSON.stringify({
76
+ role: "user",
77
+ parts: [{ type: "text", text: "bad" }]
78
+ })
79
+ );
80
+
81
+ const persisted = await getValidatedMessages(room);
82
+ expect(persisted.length).toBe(1);
83
+ expect(persisted[0].id).toBe("valid1");
84
+
85
+ ws.close(1000);
86
+ });
87
+
88
+ it("filters out messages with invalid role", async () => {
89
+ const room = crypto.randomUUID();
90
+ const { ws, agentStub } = await setupAgent(room);
91
+
92
+ await agentStub.persistMessages([
93
+ { id: "valid1", role: "user", parts: [{ type: "text", text: "Hello" }] }
94
+ ]);
95
+
96
+ agentStub.insertRawMessage(
97
+ "bad-role",
98
+ JSON.stringify({
99
+ id: "bad-role",
100
+ role: "invalid-role",
101
+ parts: [{ type: "text", text: "bad" }]
102
+ })
103
+ );
104
+
105
+ const persisted = await getValidatedMessages(room);
106
+ expect(persisted.length).toBe(1);
107
+ expect(persisted[0].id).toBe("valid1");
108
+
109
+ ws.close(1000);
110
+ });
111
+
112
+ it("filters out messages with non-array parts", async () => {
113
+ const room = crypto.randomUUID();
114
+ const { ws, agentStub } = await setupAgent(room);
115
+
116
+ await agentStub.persistMessages([
117
+ { id: "valid1", role: "user", parts: [{ type: "text", text: "Hello" }] }
118
+ ]);
119
+
120
+ agentStub.insertRawMessage(
121
+ "bad-parts",
122
+ JSON.stringify({
123
+ id: "bad-parts",
124
+ role: "user",
125
+ parts: "not an array"
126
+ })
127
+ );
128
+
129
+ const persisted = await getValidatedMessages(room);
130
+ expect(persisted.length).toBe(1);
131
+ expect(persisted[0].id).toBe("valid1");
132
+
133
+ ws.close(1000);
134
+ });
135
+
136
+ it("filters out messages with empty id", async () => {
137
+ const room = crypto.randomUUID();
138
+ const { ws, agentStub } = await setupAgent(room);
139
+
140
+ await agentStub.persistMessages([
141
+ { id: "valid1", role: "user", parts: [{ type: "text", text: "Hello" }] }
142
+ ]);
143
+
144
+ agentStub.insertRawMessage(
145
+ "bad-empty-id",
146
+ JSON.stringify({
147
+ id: "",
148
+ role: "user",
149
+ parts: [{ type: "text", text: "bad" }]
150
+ })
151
+ );
152
+
153
+ const persisted = await getValidatedMessages(room);
154
+ expect(persisted.length).toBe(1);
155
+ expect(persisted[0].id).toBe("valid1");
156
+
157
+ ws.close(1000);
158
+ });
159
+
160
+ it("keeps messages with empty parts array (lenient)", async () => {
161
+ const room = crypto.randomUUID();
162
+ const { ws, agentStub } = await setupAgent(room);
163
+
164
+ await agentStub.persistMessages([
165
+ { id: "empty-parts", role: "assistant", parts: [] }
166
+ ]);
167
+
168
+ const persisted = await getValidatedMessages(room);
169
+ expect(persisted.length).toBe(1);
170
+ expect(persisted[0].id).toBe("empty-parts");
171
+ expect(persisted[0].parts).toEqual([]);
172
+
173
+ ws.close(1000);
174
+ });
175
+
176
+ it("filters out non-object values stored as messages", async () => {
177
+ const room = crypto.randomUUID();
178
+ const { ws, agentStub } = await setupAgent(room);
179
+
180
+ await agentStub.persistMessages([
181
+ { id: "valid1", role: "user", parts: [{ type: "text", text: "Hello" }] }
182
+ ]);
183
+
184
+ // Raw string value (not a JSON object)
185
+ agentStub.insertRawMessage("bad-string", JSON.stringify("just a string"));
186
+
187
+ // null value
188
+ agentStub.insertRawMessage("bad-null", "null");
189
+
190
+ const persisted = await getValidatedMessages(room);
191
+ expect(persisted.length).toBe(1);
192
+ expect(persisted[0].id).toBe("valid1");
193
+
194
+ ws.close(1000);
195
+ });
196
+
197
+ it("preserves messages with metadata", async () => {
198
+ const room = crypto.randomUUID();
199
+ const { ws, agentStub } = await setupAgent(room);
200
+
201
+ const messageWithMeta: ChatMessage = {
202
+ id: "meta1",
203
+ role: "assistant",
204
+ parts: [{ type: "text", text: "Response" }],
205
+ metadata: { model: "gpt-4o", totalTokens: 150 }
206
+ };
207
+
208
+ await agentStub.persistMessages([messageWithMeta]);
209
+
210
+ const persisted = await getValidatedMessages(room);
211
+ expect(persisted.length).toBe(1);
212
+ expect(persisted[0].id).toBe("meta1");
213
+ expect(persisted[0].metadata).toEqual({
214
+ model: "gpt-4o",
215
+ totalTokens: 150
216
+ });
217
+
218
+ ws.close(1000);
219
+ });
220
+
221
+ it("filters out completely unparseable JSON", async () => {
222
+ const room = crypto.randomUUID();
223
+ const { ws, agentStub } = await setupAgent(room);
224
+
225
+ await agentStub.persistMessages([
226
+ { id: "valid1", role: "user", parts: [{ type: "text", text: "Hello" }] }
227
+ ]);
228
+
229
+ // Insert raw broken JSON that will fail JSON.parse
230
+ agentStub.insertRawMessage("bad-json", "{broken json!!!");
231
+
232
+ const persisted = await getValidatedMessages(room);
233
+ expect(persisted.length).toBe(1);
234
+ expect(persisted[0].id).toBe("valid1");
235
+
236
+ ws.close(1000);
237
+ });
238
+
239
+ it("accepts all valid roles: user, assistant, system", async () => {
240
+ const room = crypto.randomUUID();
241
+ const { ws, agentStub } = await setupAgent(room);
242
+
243
+ const messages: ChatMessage[] = [
244
+ {
245
+ id: "sys1",
246
+ role: "system",
247
+ parts: [{ type: "text", text: "You are helpful" }]
248
+ },
249
+ { id: "usr1", role: "user", parts: [{ type: "text", text: "Hello" }] },
250
+ {
251
+ id: "ast1",
252
+ role: "assistant",
253
+ parts: [{ type: "text", text: "Hi!" }]
254
+ }
255
+ ];
256
+
257
+ await agentStub.persistMessages(messages);
258
+
259
+ const persisted = await getValidatedMessages(room);
260
+ expect(persisted.length).toBe(3);
261
+ expect(persisted.map((m) => m.role)).toEqual([
262
+ "system",
263
+ "user",
264
+ "assistant"
265
+ ]);
266
+
267
+ ws.close(1000);
268
+ });
269
+ });
@@ -4,8 +4,9 @@ import type {
4
4
  StreamTextOnFinishCallback,
5
5
  ToolSet
6
6
  } from "ai";
7
- import { callable, getCurrentAgent, routeAgentRequest } from "agents";
7
+ import { getCurrentAgent, routeAgentRequest } from "agents";
8
8
  import { MessageType, type OutgoingMessage } from "../types";
9
+ import type { ClientToolSchema } from "../";
9
10
 
10
11
  // Type helper for tool call parts - extracts from ChatMessage parts
11
12
  type TestToolCallPart = Extract<
@@ -34,7 +35,7 @@ export class TestChatAgent extends AIChatAgent<Env> {
34
35
  // Store captured body from onChatMessage options for testing
35
36
  private _capturedBody: Record<string, unknown> | undefined = undefined;
36
37
  // Store captured clientTools from onChatMessage options for testing
37
- private _capturedClientTools: unknown[] | undefined = undefined;
38
+ private _capturedClientTools: ClientToolSchema[] | undefined = undefined;
38
39
 
39
40
  async onChatMessage(
40
41
  _onFinish: StreamTextOnFinishCallback<ToolSet>,
@@ -76,7 +77,6 @@ export class TestChatAgent extends AIChatAgent<Env> {
76
77
  };
77
78
  }
78
79
 
79
- @callable()
80
80
  getCapturedContext(): {
81
81
  hasAgent: boolean;
82
82
  hasConnection: boolean;
@@ -85,7 +85,6 @@ export class TestChatAgent extends AIChatAgent<Env> {
85
85
  return this._capturedContext;
86
86
  }
87
87
 
88
- @callable()
89
88
  getNestedContext(): {
90
89
  hasAgent: boolean;
91
90
  hasConnection: boolean;
@@ -94,7 +93,6 @@ export class TestChatAgent extends AIChatAgent<Env> {
94
93
  return this._nestedContext;
95
94
  }
96
95
 
97
- @callable()
98
96
  clearCapturedContext(): void {
99
97
  this._capturedContext = null;
100
98
  this._nestedContext = null;
@@ -102,17 +100,14 @@ export class TestChatAgent extends AIChatAgent<Env> {
102
100
  this._capturedClientTools = undefined;
103
101
  }
104
102
 
105
- @callable()
106
103
  getCapturedBody(): Record<string, unknown> | undefined {
107
104
  return this._capturedBody;
108
105
  }
109
106
 
110
- @callable()
111
- getCapturedClientTools(): unknown[] | undefined {
107
+ getCapturedClientTools(): ClientToolSchema[] | undefined {
112
108
  return this._capturedClientTools;
113
109
  }
114
110
 
115
- @callable()
116
111
  getPersistedMessages(): ChatMessage[] {
117
112
  const rawMessages = (
118
113
  this.sql`select * from cf_ai_chat_agent_messages order by created_at` ||
@@ -123,7 +118,6 @@ export class TestChatAgent extends AIChatAgent<Env> {
123
118
  return rawMessages;
124
119
  }
125
120
 
126
- @callable()
127
121
  async testPersistToolCall(messageId: string, toolName: string) {
128
122
  const toolCallPart: TestToolCallPart = {
129
123
  type: `tool-${toolName}`,
@@ -141,7 +135,6 @@ export class TestChatAgent extends AIChatAgent<Env> {
141
135
  return messageWithToolCall;
142
136
  }
143
137
 
144
- @callable()
145
138
  async testPersistToolResult(
146
139
  messageId: string,
147
140
  toolName: string,
@@ -166,17 +159,14 @@ export class TestChatAgent extends AIChatAgent<Env> {
166
159
 
167
160
  // Resumable streaming test helpers
168
161
 
169
- @callable()
170
162
  testStartStream(requestId: string): string {
171
163
  return this._startStream(requestId);
172
164
  }
173
165
 
174
- @callable()
175
166
  testStoreStreamChunk(streamId: string, body: string): void {
176
167
  this._storeStreamChunk(streamId, body);
177
168
  }
178
169
 
179
- @callable()
180
170
  testBroadcastLiveChunk(
181
171
  requestId: string,
182
172
  streamId: string,
@@ -199,32 +189,26 @@ export class TestChatAgent extends AIChatAgent<Env> {
199
189
  )._broadcastChatMessage(message);
200
190
  }
201
191
 
202
- @callable()
203
192
  testFlushChunkBuffer(): void {
204
193
  this._flushChunkBuffer();
205
194
  }
206
195
 
207
- @callable()
208
196
  testCompleteStream(streamId: string): void {
209
197
  this._completeStream(streamId);
210
198
  }
211
199
 
212
- @callable()
213
200
  testMarkStreamError(streamId: string): void {
214
201
  this._markStreamError(streamId);
215
202
  }
216
203
 
217
- @callable()
218
204
  getActiveStreamId(): string | null {
219
205
  return this._activeStreamId;
220
206
  }
221
207
 
222
- @callable()
223
208
  getActiveRequestId(): string | null {
224
209
  return this._activeRequestId;
225
210
  }
226
211
 
227
- @callable()
228
212
  getStreamChunks(
229
213
  streamId: string
230
214
  ): Array<{ body: string; chunk_index: number }> {
@@ -237,7 +221,6 @@ export class TestChatAgent extends AIChatAgent<Env> {
237
221
  );
238
222
  }
239
223
 
240
- @callable()
241
224
  getStreamMetadata(
242
225
  streamId: string
243
226
  ): { status: string; request_id: string } | null {
@@ -248,7 +231,6 @@ export class TestChatAgent extends AIChatAgent<Env> {
248
231
  return result && result.length > 0 ? result[0] : null;
249
232
  }
250
233
 
251
- @callable()
252
234
  getAllStreamMetadata(): Array<{
253
235
  id: string;
254
236
  status: string;
@@ -266,7 +248,6 @@ export class TestChatAgent extends AIChatAgent<Env> {
266
248
  );
267
249
  }
268
250
 
269
- @callable()
270
251
  testInsertStaleStream(
271
252
  streamId: string,
272
253
  requestId: string,
@@ -279,10 +260,64 @@ export class TestChatAgent extends AIChatAgent<Env> {
279
260
  `;
280
261
  }
281
262
 
282
- @callable()
263
+ testInsertOldErroredStream(
264
+ streamId: string,
265
+ requestId: string,
266
+ ageMs: number
267
+ ): void {
268
+ const createdAt = Date.now() - ageMs;
269
+ const completedAt = createdAt + 1000;
270
+ this.sql`
271
+ insert into cf_ai_chat_stream_metadata (id, request_id, status, created_at, completed_at)
272
+ values (${streamId}, ${requestId}, 'error', ${createdAt}, ${completedAt})
273
+ `;
274
+ }
275
+
283
276
  testRestoreActiveStream(): void {
284
277
  this._restoreActiveStream();
285
278
  }
279
+
280
+ testTriggerStreamCleanup(): void {
281
+ // Force the cleanup interval to 0 so the next completeStream triggers it
282
+ // We do this by starting and immediately completing a dummy stream
283
+ const dummyId = this._startStream("cleanup-trigger");
284
+ this._completeStream(dummyId);
285
+ }
286
+
287
+ /**
288
+ * Insert a raw JSON string as a message directly into SQLite.
289
+ * Used to test validation of malformed/corrupt messages.
290
+ */
291
+ insertRawMessage(rowId: string, rawJson: string): void {
292
+ this.sql`
293
+ insert into cf_ai_chat_agent_messages (id, message)
294
+ values (${rowId}, ${rawJson})
295
+ `;
296
+ }
297
+
298
+ setMaxPersistedMessages(max: number | null): void {
299
+ this.maxPersistedMessages = max ?? undefined;
300
+ }
301
+
302
+ getMessageCount(): number {
303
+ const result = this.sql<{ cnt: number }>`
304
+ select count(*) as cnt from cf_ai_chat_agent_messages
305
+ `;
306
+ return result?.[0]?.cnt ?? 0;
307
+ }
308
+
309
+ /**
310
+ * Returns the number of active abort controllers.
311
+ * Used to verify that cleanup happens after stream completion.
312
+ * If controllers leak, this count grows with each request.
313
+ */
314
+ getAbortControllerCount(): number {
315
+ return (
316
+ this as unknown as {
317
+ _chatMessageAbortControllers: Map<string, unknown>;
318
+ }
319
+ )._chatMessageAbortControllers.size;
320
+ }
286
321
  }
287
322
 
288
323
  export default {
package/src/types.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { UIMessage } from "ai";
1
+ import type { JSONSchema7, UIMessage } from "ai";
2
2
 
3
3
  /**
4
4
  * Enum for message types to improve type safety and maintainability
@@ -14,6 +14,8 @@ export enum MessageType {
14
14
  CF_AGENT_STREAM_RESUMING = "cf_agent_stream_resuming",
15
15
  /** Sent by client to acknowledge stream resuming notification and request chunks */
16
16
  CF_AGENT_STREAM_RESUME_ACK = "cf_agent_stream_resume_ack",
17
+ /** Sent by client after message handler is ready, requesting stream resume check */
18
+ CF_AGENT_STREAM_RESUME_REQUEST = "cf_agent_stream_resume_request",
17
19
 
18
20
  /** Client sends tool result to server (for client-side tools) */
19
21
  CF_AGENT_TOOL_RESULT = "cf_agent_tool_result",
@@ -50,6 +52,8 @@ export type OutgoingMessage<ChatMessage extends UIMessage = UIMessage> =
50
52
  error?: boolean;
51
53
  /** Whether this is a continuation (append to last assistant message) */
52
54
  continuation?: boolean;
55
+ /** Whether this chunk is being replayed from storage (stream resumption) */
56
+ replay?: boolean;
53
57
  }
54
58
  | {
55
59
  /** Indicates the server is resuming an active stream */
@@ -110,6 +114,10 @@ export type IncomingMessage<ChatMessage extends UIMessage = UIMessage> =
110
114
  /** The request ID of the stream being resumed */
111
115
  id: string;
112
116
  }
117
+ | {
118
+ /** Client requests stream resume check after message handler is registered */
119
+ type: MessageType.CF_AGENT_STREAM_RESUME_REQUEST;
120
+ }
113
121
  | {
114
122
  /** Client sends tool result to server (for client-side tools) */
115
123
  type: MessageType.CF_AGENT_TOOL_RESULT;
@@ -121,6 +129,12 @@ export type IncomingMessage<ChatMessage extends UIMessage = UIMessage> =
121
129
  output: unknown;
122
130
  /** Whether server should auto-continue the conversation after applying result */
123
131
  autoContinue?: boolean;
132
+ /** Client tool schemas for continuation (client is source of truth) */
133
+ clientTools?: Array<{
134
+ name: string;
135
+ description?: string;
136
+ parameters?: JSONSchema7;
137
+ }>;
124
138
  }
125
139
  | {
126
140
  /** Client sends tool approval response to server (for tools with needsApproval) */
@@ -129,4 +143,6 @@ export type IncomingMessage<ChatMessage extends UIMessage = UIMessage> =
129
143
  toolCallId: string;
130
144
  /** Whether the tool execution was approved */
131
145
  approved: boolean;
146
+ /** Whether server should auto-continue the conversation after applying approval */
147
+ autoContinue?: boolean;
132
148
  };