@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
package/e2e/worker.ts ADDED
@@ -0,0 +1,176 @@
1
+ import {
2
+ AIChatAgent,
3
+ type OnChatMessageOptions,
4
+ createToolsFromClientSchemas
5
+ } from "../src/index";
6
+ import { streamText, tool, convertToModelMessages, stepCountIs } from "ai";
7
+ import { createWorkersAI } from "workers-ai-provider";
8
+ import { createOpenAI } from "@ai-sdk/openai";
9
+ import { z } from "zod/v4";
10
+ import { routeAgentRequest } from "agents";
11
+
12
+ export type Env = {
13
+ ChatAgent: DurableObjectNamespace<ChatAgent>;
14
+ LlmChatAgent: DurableObjectNamespace<LlmChatAgent>;
15
+ ClientToolAgent: DurableObjectNamespace<ClientToolAgent>;
16
+ SlowAgent: DurableObjectNamespace<SlowAgent>;
17
+ BadKeyAgent: DurableObjectNamespace<BadKeyAgent>;
18
+ AI: Ai;
19
+ OPENAI_API_KEY: string;
20
+ };
21
+
22
+ /**
23
+ * Simple agent that returns plain text — used by the basic protocol tests.
24
+ */
25
+ export class ChatAgent extends AIChatAgent<Env> {
26
+ observability = undefined;
27
+
28
+ async onChatMessage() {
29
+ return new Response("Hello from e2e agent!", {
30
+ headers: { "Content-Type": "text/plain" }
31
+ });
32
+ }
33
+ }
34
+
35
+ /**
36
+ * LLM-backed agent using Workers AI with streamText.
37
+ * Used by the LLM e2e tests that verify real SSE streaming, tool calls, etc.
38
+ */
39
+ export class LlmChatAgent extends AIChatAgent<Env> {
40
+ observability = undefined;
41
+
42
+ async onChatMessage(_onFinish?: unknown, options?: OnChatMessageOptions) {
43
+ const workersai = createWorkersAI({ binding: this.env.AI });
44
+
45
+ const tools = {
46
+ getWeather: tool({
47
+ description: "Get the current weather for a city",
48
+ inputSchema: z.object({
49
+ city: z.string().describe("The city name")
50
+ }),
51
+ execute: async ({ city }) => ({
52
+ city,
53
+ temperature: 22,
54
+ condition: "Sunny"
55
+ })
56
+ }),
57
+ addNumbers: tool({
58
+ description: "Add two numbers together",
59
+ inputSchema: z.object({
60
+ a: z.number().describe("First number"),
61
+ b: z.number().describe("Second number")
62
+ }),
63
+ execute: async ({ a, b }) => ({
64
+ result: a + b
65
+ })
66
+ }),
67
+ ...createToolsFromClientSchemas(options?.clientTools)
68
+ };
69
+
70
+ const result = streamText({
71
+ // @ts-expect-error — model not yet in workers-ai-provider types
72
+ model: workersai("@cf/zai-org/glm-4.7-flash"),
73
+ system:
74
+ "You are a helpful test assistant. Keep responses very short (1-2 sentences max). " +
75
+ "When asked about the weather, use the getWeather tool. " +
76
+ "When asked to add numbers, use the addNumbers tool.",
77
+ messages: await convertToModelMessages(this.messages),
78
+ tools,
79
+ stopWhen: stepCountIs(3)
80
+ });
81
+
82
+ return result.toUIMessageStreamResponse();
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Agent with a client-side tool (no execute function).
88
+ * The LLM calls the tool, the stream pauses at tool-input-available,
89
+ * and the test must send CF_AGENT_TOOL_RESULT to continue.
90
+ */
91
+ export class ClientToolAgent extends AIChatAgent<Env> {
92
+ observability = undefined;
93
+
94
+ async onChatMessage() {
95
+ const workersai = createWorkersAI({ binding: this.env.AI });
96
+
97
+ const result = streamText({
98
+ // @ts-expect-error — model not yet in workers-ai-provider types
99
+ model: workersai("@cf/zai-org/glm-4.7-flash"),
100
+ system:
101
+ "You are a test assistant. Always use the getUserLocation tool when asked about location.",
102
+ messages: await convertToModelMessages(this.messages),
103
+ tools: {
104
+ getUserLocation: tool({
105
+ description: "Get the user's current location from the browser",
106
+ inputSchema: z.object({})
107
+ // No execute — client must handle via CF_AGENT_TOOL_RESULT
108
+ })
109
+ },
110
+ stopWhen: stepCountIs(3)
111
+ });
112
+
113
+ return result.toUIMessageStreamResponse();
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Agent that returns a slow, multi-chunk plain text response.
119
+ * Used to test stream resumption by disconnecting mid-stream.
120
+ */
121
+ export class SlowAgent extends AIChatAgent<Env> {
122
+ observability = undefined;
123
+
124
+ async onChatMessage() {
125
+ // Create a stream that sends chunks with delays
126
+ const encoder = new TextEncoder();
127
+ const stream = new ReadableStream({
128
+ async start(controller) {
129
+ const chunks = [
130
+ "chunk-1 ",
131
+ "chunk-2 ",
132
+ "chunk-3 ",
133
+ "chunk-4 ",
134
+ "chunk-5"
135
+ ];
136
+ for (const chunk of chunks) {
137
+ controller.enqueue(encoder.encode(chunk));
138
+ await new Promise((r) => setTimeout(r, 400));
139
+ }
140
+ controller.close();
141
+ }
142
+ });
143
+
144
+ return new Response(stream, {
145
+ headers: { "Content-Type": "text/plain" }
146
+ });
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Agent configured with a bad API key to test error handling.
152
+ */
153
+ export class BadKeyAgent extends AIChatAgent<Env> {
154
+ observability = undefined;
155
+
156
+ async onChatMessage() {
157
+ const openai = createOpenAI({ apiKey: "sk-invalid-key-for-testing" });
158
+
159
+ const result = streamText({
160
+ model: openai.chat("gpt-4o-mini"),
161
+ system: "You are a test assistant.",
162
+ messages: await convertToModelMessages(this.messages)
163
+ });
164
+
165
+ return result.toUIMessageStreamResponse();
166
+ }
167
+ }
168
+
169
+ export default {
170
+ async fetch(request: Request, env: Env, _ctx: ExecutionContext) {
171
+ return (
172
+ (await routeAgentRequest(request, env)) ||
173
+ new Response("Not found", { status: 404 })
174
+ );
175
+ }
176
+ };
@@ -0,0 +1,23 @@
1
+ {
2
+ "ai": { "binding": "AI" },
3
+ "compatibility_date": "2026-01-28",
4
+ "compatibility_flags": ["nodejs_compat"],
5
+ "durable_objects": {
6
+ "bindings": [
7
+ { "class_name": "ChatAgent", "name": "ChatAgent" },
8
+ { "class_name": "LlmChatAgent", "name": "LlmChatAgent" },
9
+ { "class_name": "ClientToolAgent", "name": "ClientToolAgent" },
10
+ { "class_name": "SlowAgent", "name": "SlowAgent" },
11
+ { "class_name": "BadKeyAgent", "name": "BadKeyAgent" }
12
+ ]
13
+ },
14
+ "main": "worker.ts",
15
+ "migrations": [
16
+ { "new_sqlite_classes": ["ChatAgent"], "tag": "v1" },
17
+ { "new_sqlite_classes": ["LlmChatAgent"], "tag": "v2" },
18
+ {
19
+ "new_sqlite_classes": ["ClientToolAgent", "SlowAgent", "BadKeyAgent"],
20
+ "tag": "v3"
21
+ }
22
+ ]
23
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/ai-chat",
3
- "version": "0.0.7",
3
+ "version": "0.1.0",
4
4
  "description": "Cloudflare Agents (x) AI SDK Chat",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -19,14 +19,15 @@
19
19
  "url": "https://github.com/cloudflare/agents/issues"
20
20
  },
21
21
  "devDependencies": {
22
- "@types/react": "^19.2.13",
23
- "ai": "^6.0.77",
22
+ "@playwright/test": "^1.58.2",
23
+ "@types/react": "^19.2.14",
24
+ "ai": "^6.0.86",
24
25
  "react": "^19.2.4",
25
26
  "vitest-browser-react": "^1.0.1",
26
27
  "zod": "^4.3.6"
27
28
  },
28
29
  "peerDependencies": {
29
- "agents": "^0.4.0",
30
+ "agents": "^0.5.0",
30
31
  "ai": "^6.0.0",
31
32
  "react": "^19.0.0",
32
33
  "zod": "^3.25.0 || ^4.0.0"
@@ -51,6 +52,11 @@
51
52
  "types": "./dist/ai-chat-v5-migration.d.ts",
52
53
  "import": "./dist/ai-chat-v5-migration.js",
53
54
  "require": "./dist/ai-chat-v5-migration.js"
55
+ },
56
+ "./experimental/forever": {
57
+ "types": "./dist/experimental/forever.d.ts",
58
+ "import": "./dist/experimental/forever.js",
59
+ "require": "./dist/experimental/forever.js"
54
60
  }
55
61
  },
56
62
  "author": "Cloudflare Inc.",
@@ -59,6 +65,7 @@
59
65
  "build": "tsx ./scripts/build.ts",
60
66
  "test": "vitest --run",
61
67
  "test:react": "vitest --project react",
62
- "test:workers": "vitest --project workers"
68
+ "test:workers": "vitest --project workers",
69
+ "test:e2e": "npx playwright test --config e2e/playwright.config.ts"
63
70
  }
64
71
  }
package/scripts/build.ts CHANGED
@@ -9,7 +9,8 @@ async function main() {
9
9
  "src/index.ts",
10
10
  "src/react.tsx",
11
11
  "src/types.ts",
12
- "src/ai-chat-v5-migration.ts"
12
+ "src/ai-chat-v5-migration.ts",
13
+ "src/experimental/forever.ts"
13
14
  ],
14
15
  skipNodeModulesBundle: true,
15
16
  external: ["cloudflare:workers", "cloudflare:email"],
@@ -5,6 +5,17 @@ import type { UIMessage } from "ai";
5
5
  * Using exact types from the official AI SDK documentation
6
6
  */
7
7
 
8
+ /**
9
+ * One-shot deprecation warnings (warns once per key per session).
10
+ */
11
+ const _deprecationWarnings = new Set<string>();
12
+ function warnDeprecated(id: string, message: string) {
13
+ if (!_deprecationWarnings.has(id)) {
14
+ _deprecationWarnings.add(id);
15
+ console.warn(`[@cloudflare/ai-chat] Deprecated: ${message}`);
16
+ }
17
+ }
18
+
8
19
  /**
9
20
  * AI SDK v5 Message Part types reference (from official AI SDK documentation)
10
21
  *
@@ -168,7 +179,7 @@ type InputMessage = {
168
179
  * @returns UIMessage in v5 format
169
180
  */
170
181
  export function autoTransformMessage(
171
- message: InputMessage,
182
+ message: UIMessage | InputMessage,
172
183
  index = 0
173
184
  ): UIMessage {
174
185
  // Already in v5 format
@@ -268,9 +279,14 @@ export function autoTransformMessage(
268
279
  }
269
280
 
270
281
  /**
271
- * Legacy single message migration for backward compatibility
282
+ * Legacy single message migration for backward compatibility.
283
+ * @deprecated Use `autoTransformMessage` instead. Will be removed in the next major version.
272
284
  */
273
285
  export function migrateToUIMessage(message: MigratableMessage): UIMessage {
286
+ warnDeprecated(
287
+ "migrateToUIMessage",
288
+ "migrateToUIMessage() is deprecated. Use autoTransformMessage() instead. It will be removed in the next major version."
289
+ );
274
290
  return autoTransformMessage(message as InputMessage);
275
291
  }
276
292
 
@@ -284,22 +300,32 @@ export function autoTransformMessages(messages: unknown[]): UIMessage[] {
284
300
  }
285
301
 
286
302
  /**
287
- * Migrates an array of messages to UIMessage format (legacy compatibility)
303
+ * Migrates an array of messages to UIMessage format (legacy compatibility).
288
304
  * @param messages - Array of messages in old or new format
289
305
  * @returns Array of UIMessages in the new format
306
+ * @deprecated Use `autoTransformMessages` instead. Will be removed in the next major version.
290
307
  */
291
308
  export function migrateMessagesToUIFormat(
292
309
  messages: MigratableMessage[]
293
310
  ): UIMessage[] {
311
+ warnDeprecated(
312
+ "migrateMessagesToUIFormat",
313
+ "migrateMessagesToUIFormat() is deprecated. Use autoTransformMessages() instead. It will be removed in the next major version."
314
+ );
294
315
  return autoTransformMessages(messages as InputMessage[]);
295
316
  }
296
317
 
297
318
  /**
298
- * Checks if any messages in an array need migration
319
+ * Checks if any messages in an array need migration.
299
320
  * @param messages - Array of messages to check
300
321
  * @returns true if any messages are not in proper UIMessage format
322
+ * @deprecated Migration is now automatic via `autoTransformMessages`. Will be removed in the next major version.
301
323
  */
302
324
  export function needsMigration(messages: unknown[]): boolean {
325
+ warnDeprecated(
326
+ "needsMigration",
327
+ "needsMigration() is deprecated. Migration is automatic via autoTransformMessages(). It will be removed in the next major version."
328
+ );
303
329
  return messages.some((message) => {
304
330
  // If it's already a UIMessage, no migration needed
305
331
  if (isUIMessage(message)) {
@@ -322,9 +348,10 @@ export function needsMigration(messages: unknown[]): boolean {
322
348
  }
323
349
 
324
350
  /**
325
- * Analyzes the corruption types in a message array for debugging
351
+ * Analyzes the corruption types in a message array for debugging.
326
352
  * @param messages - Array of messages to analyze
327
353
  * @returns Statistics about corruption types found
354
+ * @deprecated Migration is now automatic. Use this only for debugging legacy data. Will be removed in the next major version.
328
355
  */
329
356
  export function analyzeCorruption(messages: unknown[]): {
330
357
  total: number;
@@ -0,0 +1,66 @@
1
+ /**
2
+ * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
3
+ * !! WARNING: EXPERIMENTAL — DO NOT USE IN PRODUCTION !!
4
+ * !! !!
5
+ * !! This API is under active development and WILL break between !!
6
+ * !! releases. Method names, types, behavior, and the mixin signature !!
7
+ * !! are all subject to change without notice. !!
8
+ * !! !!
9
+ * !! If you use this, pin your @cloudflare/ai-chat version and expect !!
10
+ * !! to rewrite your code when upgrading. !!
11
+ * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
12
+ *
13
+ * Experimental mixin for durable chat streaming.
14
+ *
15
+ * Usage:
16
+ * import { AIChatAgent } from "@cloudflare/ai-chat";
17
+ * import { withDurableChat } from "@cloudflare/ai-chat/experimental/forever";
18
+ *
19
+ * class MyAgent extends withDurableChat(AIChatAgent)<Env, State> {
20
+ * async onChatMessage(onFinish, options) { ... }
21
+ * }
22
+ *
23
+ * This mixin adds:
24
+ * - keepAlive during streaming — DO stays alive while LLM generates
25
+ * - (planned) getPartialStreamText() — extract partial response from chunks
26
+ * - (planned) onStreamInterrupted() — hook for recovery after eviction
27
+ *
28
+ * @experimental This API is not yet stable and may change.
29
+ */
30
+ import { keepAlive } from "agents/experimental/forever";
31
+ import type { AIChatAgent } from "../index";
32
+
33
+ console.warn(
34
+ "[@cloudflare/ai-chat/experimental/forever] WARNING: You are using an experimental API that WILL break between releases. Do not use in production."
35
+ );
36
+
37
+ // ── Mixin ─────────────────────────────────────────────────────────────
38
+
39
+ // oxlint-disable-next-line @typescript-eslint/no-explicit-any -- mixin constructor constraint
40
+ type Constructor<T = object> = new (...args: any[]) => T;
41
+
42
+ type AIChatAgentLike = Constructor<
43
+ Pick<AIChatAgent, "scheduleEvery" | "cancelSchedule">
44
+ >;
45
+
46
+ export function withDurableChat<TBase extends AIChatAgentLike>(Base: TBase) {
47
+ class DurableChatAgent extends Base {
48
+ /**
49
+ * No-op heartbeat callback. The schedule itself keeps the DO alive;
50
+ * the callback doesn't need to do anything.
51
+ * @internal
52
+ */
53
+ // oxlint-disable-next-line @typescript-eslint/no-empty-function
54
+ _cf_streamKeepAlive() {}
55
+
56
+ /**
57
+ * Keep the DO alive during streaming.
58
+ * Returns a disposer that cancels the heartbeat schedule.
59
+ */
60
+ async keepAlive(): Promise<() => void> {
61
+ return keepAlive(this, "_cf_streamKeepAlive");
62
+ }
63
+ }
64
+
65
+ return DurableChatAgent;
66
+ }