@cloudflare/ai-chat 0.1.3 → 0.1.4

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.
@@ -3,6 +3,7 @@ import { defineConfig } from "vitest/config";
3
3
  export default defineConfig({
4
4
  test: {
5
5
  name: "react",
6
+ include: ["**/*.test.{ts,tsx}"],
6
7
  browser: {
7
8
  enabled: true,
8
9
  instances: [
package/src/react.tsx CHANGED
@@ -42,13 +42,16 @@ export type JSONSchemaType = JSONSchema7;
42
42
  * Definition for a tool that can be executed on the client.
43
43
  * Tools with an `execute` function are automatically registered with the server.
44
44
  *
45
- * Note: Uses `parameters` (JSONSchema7) rather than AI SDK's `inputSchema` (FlexibleSchema)
46
- * because client tools must be serializable for the wire format. Zod schemas cannot be
47
- * serialized, so we require raw JSON Schema here.
45
+ * **For most apps**, define tools on the server with `tool()` from `"ai"` —
46
+ * you get full Zod type safety and simpler code. Use `onToolCall` in
47
+ * `useAgentChat` for tools that need browser-side execution.
48
48
  *
49
- * @deprecated Use AI SDK's native tool pattern instead. Define tools on the server with
50
- * `tool()` from "ai", and handle client-side execution via the `onToolCall` callback
51
- * in `useAgentChat`. For tools requiring user approval, use `needsApproval` on the server.
49
+ * **For SDKs and platforms** where the tool surface is determined dynamically
50
+ * by the embedding application at runtime, this type lets the client register
51
+ * tools the server does not know about at deploy time.
52
+ *
53
+ * Note: Uses `parameters` (JSONSchema7) because client tools must be
54
+ * serializable for the wire format. Zod schemas cannot be serialized.
52
55
  */
53
56
  export type AITool<Input = unknown, Output = unknown> = {
54
57
  /** Human-readable description of what the tool does */
@@ -68,10 +71,11 @@ export type AITool<Input = unknown, Output = unknown> = {
68
71
 
69
72
  /**
70
73
  * Schema for a client tool sent to the server.
71
- * This is the wire format - what gets sent in the request body.
72
- * Must match the server-side ClientToolSchema type in ai-chat-agent.ts.
74
+ * This is the wire format — what gets sent in the request body.
75
+ * Must match the server-side ClientToolSchema type.
73
76
  *
74
- * @deprecated Use AI SDK's native tool pattern instead. Define tools on the server.
77
+ * Most apps do not need this directly — it is used internally when the
78
+ * `tools` option on `useAgentChat` contains tools with `execute` functions.
75
79
  */
76
80
  export type ClientToolSchema = {
77
81
  /** Unique name for the tool */
@@ -85,19 +89,16 @@ export type ClientToolSchema = {
85
89
  /**
86
90
  * Extracts tool schemas from tools that have client-side execute functions.
87
91
  * These schemas are automatically sent to the server with each request.
92
+ *
93
+ * Called internally by `useAgentChat` when `tools` are provided.
94
+ * Most apps do not need to call this directly.
95
+ *
88
96
  * @param tools - Record of tool name to tool definition
89
97
  * @returns Array of tool schemas to send to server, or undefined if none
90
- *
91
- * @deprecated Use AI SDK's native tool pattern instead. Define tools on the server
92
- * and use `onToolCall` callback for client-side execution.
93
98
  */
94
99
  export function extractClientToolSchemas(
95
100
  tools?: Record<string, AITool<unknown, unknown>>
96
101
  ): ClientToolSchema[] | undefined {
97
- warnDeprecated(
98
- "extractClientToolSchemas",
99
- "extractClientToolSchemas() is deprecated. Define tools on the server and use onToolCall for client execution. Will be removed in the next major version."
100
- );
101
102
  if (!tools) return undefined;
102
103
 
103
104
  const schemas: ClientToolSchema[] = Object.entries(tools)
@@ -173,6 +174,22 @@ export type PrepareSendMessagesRequestResult = {
173
174
  api?: string;
174
175
  };
175
176
 
177
+ /**
178
+ * Options for addToolOutput function
179
+ */
180
+ type AddToolOutputOptions = {
181
+ /** The ID of the tool call to provide output for */
182
+ toolCallId: string;
183
+ /** The name of the tool (optional, for type safety) */
184
+ toolName?: string;
185
+ /** The output to provide */
186
+ output?: unknown;
187
+ /** Override the tool part state (e.g. "output-error" for custom denial) */
188
+ state?: "output-available" | "output-error";
189
+ /** Error message when state is "output-error" */
190
+ errorText?: string;
191
+ };
192
+
176
193
  /**
177
194
  * Callback for handling client-side tool execution.
178
195
  * Called when a tool without server-side execute is invoked.
@@ -184,8 +201,8 @@ export type OnToolCallCallback = (options: {
184
201
  toolName: string;
185
202
  input: unknown;
186
203
  };
187
- /** Function to provide the tool output */
188
- addToolOutput: (options: { toolCallId: string; output: unknown }) => void;
204
+ /** Function to provide the tool output (or signal an error/denial) */
205
+ addToolOutput: (options: Omit<AddToolOutputOptions, "toolName">) => void;
189
206
  }) => void | Promise<void>;
190
207
 
191
208
  /**
@@ -235,10 +252,16 @@ type UseAgentChatOptions<
235
252
  */
236
253
  experimental_automaticToolResolution?: boolean;
237
254
  /**
238
- * @deprecated Use `onToolCall` callback instead. Define tools on the server
239
- * and handle client-side execution via `onToolCall`.
255
+ * Tools that can be executed on the client. Tool schemas are automatically
256
+ * sent to the server and tool calls are routed back for client execution.
257
+ *
258
+ * **For most apps**, define tools on the server with `tool()` from `"ai"`
259
+ * and handle client-side execution via `onToolCall`. This gives you full
260
+ * Zod type safety and keeps tool definitions in one place.
240
261
  *
241
- * Tools that can be executed on the client.
262
+ * **For SDKs and platforms** where tools are defined dynamically by the
263
+ * embedding application at runtime, this option lets the client register
264
+ * tools the server does not know about at deploy time.
242
265
  */
243
266
  tools?: Record<string, AITool<unknown, unknown>>;
244
267
  /**
@@ -343,18 +366,6 @@ export function detectToolsRequiringConfirmation(
343
366
  .map(([name]) => name);
344
367
  }
345
368
 
346
- /**
347
- * Return type for addToolOutput function
348
- */
349
- type AddToolOutputOptions = {
350
- /** The ID of the tool call to provide output for */
351
- toolCallId: string;
352
- /** The name of the tool (optional, for type safety) */
353
- toolName?: string;
354
- /** The output to provide */
355
- output: unknown;
356
- };
357
-
358
369
  export function useAgentChat<
359
370
  State = unknown,
360
371
  ChatMessage extends UIMessage = UIMessage
@@ -386,12 +397,6 @@ export function useAgentChat<
386
397
  } = options;
387
398
 
388
399
  // Emit deprecation warnings for deprecated options (once per session)
389
- if (tools) {
390
- warnDeprecated(
391
- "useAgentChat.tools",
392
- "The 'tools' option in useAgentChat is deprecated. Define tools on the server using tool() from 'ai' and handle client execution via the onToolCall callback. Will be removed in the next major version."
393
- );
394
- }
395
400
  if (manualToolsRequiringConfirmation) {
396
401
  warnDeprecated(
397
402
  "useAgentChat.toolsRequiringConfirmation",
@@ -414,12 +419,18 @@ export function useAgentChat<
414
419
  // ── DEPRECATED: client-side tool confirmation ──────────────────────
415
420
  // This block will be removed when toolsRequiringConfirmation is removed.
416
421
  // Only call the deprecated function when deprecated options are actually used.
417
- const toolsRequiringConfirmation = useMemo(
418
- () =>
419
- manualToolsRequiringConfirmation ??
420
- (tools ? detectToolsRequiringConfirmation(tools) : []),
421
- [manualToolsRequiringConfirmation, tools]
422
- );
422
+ const toolsRequiringConfirmation = useMemo(() => {
423
+ if (manualToolsRequiringConfirmation) {
424
+ return manualToolsRequiringConfirmation;
425
+ }
426
+ // Inline the logic from detectToolsRequiringConfirmation to avoid
427
+ // emitting a deprecation warning when tools are provided via the
428
+ // non-deprecated `tools` option.
429
+ if (!tools) return [];
430
+ return Object.entries(tools)
431
+ .filter(([_name, tool]) => !tool.execute)
432
+ .map(([name]) => name);
433
+ }, [manualToolsRequiringConfirmation, tools]);
423
434
 
424
435
  // Keep refs to always point to the latest callbacks
425
436
  const onToolCallRef = useRef(onToolCall);
@@ -788,21 +799,36 @@ export function useAgentChat<
788
799
 
789
800
  // Helper function to send tool output to server
790
801
  const sendToolOutputToServer = useCallback(
791
- (toolCallId: string, toolName: string, output: unknown) => {
802
+ (
803
+ toolCallId: string,
804
+ toolName: string,
805
+ output: unknown,
806
+ state?: "output-available" | "output-error",
807
+ errorText?: string
808
+ ) => {
792
809
  agentRef.current.send(
793
810
  JSON.stringify({
794
811
  type: MessageType.CF_AGENT_TOOL_RESULT,
795
812
  toolCallId,
796
813
  toolName,
797
814
  output,
798
- autoContinue: autoContinueAfterToolResult,
815
+ ...(state ? { state } : {}),
816
+ ...(errorText !== undefined ? { errorText } : {}),
817
+ // output-error is a deliberate client action — don't auto-continue.
818
+ // This differs from addToolApprovalResponse (which auto-continues for
819
+ // both approvals and rejections). To have the LLM respond to the error,
820
+ // call sendMessage() after addToolOutput.
821
+ autoContinue:
822
+ state === "output-error" ? false : autoContinueAfterToolResult,
799
823
  clientTools: toolsRef.current
800
824
  ? extractClientToolSchemas(toolsRef.current)
801
825
  : undefined
802
826
  })
803
827
  );
804
828
 
805
- setClientToolResults((prev) => new Map(prev).set(toolCallId, output));
829
+ if (state !== "output-error") {
830
+ setClientToolResults((prev) => new Map(prev).set(toolCallId, output));
831
+ }
806
832
  },
807
833
  [autoContinueAfterToolResult]
808
834
  );
@@ -852,17 +878,23 @@ export function useAgentChat<
852
878
  processedToolCalls.current.add(toolCallId);
853
879
 
854
880
  // Create addToolOutput function for this specific tool call
855
- const addToolOutput = (opts: {
856
- toolCallId: string;
857
- output: unknown;
858
- }) => {
859
- sendToolOutputToServer(opts.toolCallId, toolName, opts.output);
881
+ const addToolOutput = (opts: AddToolOutputOptions) => {
882
+ sendToolOutputToServer(
883
+ opts.toolCallId,
884
+ toolName,
885
+ opts.output,
886
+ opts.state,
887
+ opts.errorText
888
+ );
860
889
 
861
890
  // Update local state via AI SDK
862
891
  addToolResult({
863
892
  tool: toolName,
864
893
  toolCallId: opts.toolCallId,
865
- output: opts.output
894
+ output:
895
+ opts.state === "output-error"
896
+ ? (opts.errorText ?? "Tool execution denied by user")
897
+ : opts.output
866
898
  });
867
899
  };
868
900
 
@@ -1341,15 +1373,24 @@ export function useAgentChat<
1341
1373
 
1342
1374
  // Create addToolOutput function for external use
1343
1375
  const addToolOutput = useCallback(
1344
- (opts: { toolCallId: string; toolName?: string; output: unknown }) => {
1376
+ (opts: AddToolOutputOptions) => {
1345
1377
  const toolName = opts.toolName ?? "";
1346
- sendToolOutputToServer(opts.toolCallId, toolName, opts.output);
1378
+ sendToolOutputToServer(
1379
+ opts.toolCallId,
1380
+ toolName,
1381
+ opts.output,
1382
+ opts.state,
1383
+ opts.errorText
1384
+ );
1347
1385
 
1348
1386
  // Update local state via AI SDK
1349
1387
  addToolResult({
1350
1388
  tool: toolName,
1351
1389
  toolCallId: opts.toolCallId,
1352
- output: opts.output
1390
+ output:
1391
+ opts.state === "output-error"
1392
+ ? (opts.errorText ?? "Tool execution denied by user")
1393
+ : opts.output
1353
1394
  });
1354
1395
  },
1355
1396
  [sendToolOutputToServer, addToolResult]
@@ -0,0 +1,280 @@
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, isUseChatResponseMessage } from "./test-utils";
6
+ import { getAgentByName } from "agents";
7
+
8
+ /**
9
+ * Helper: connect to the SlowStreamAgent
10
+ */
11
+ function connectSlowStream(room: string) {
12
+ return connectChatWS(`/agents/slow-stream-agent/${room}`);
13
+ }
14
+
15
+ /**
16
+ * Helper: send a chat request with custom body fields
17
+ */
18
+ function sendChatRequest(
19
+ ws: WebSocket,
20
+ requestId: string,
21
+ messages: ChatMessage[],
22
+ extraBody?: Record<string, unknown>
23
+ ) {
24
+ ws.send(
25
+ JSON.stringify({
26
+ type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
27
+ id: requestId,
28
+ init: {
29
+ method: "POST",
30
+ body: JSON.stringify({ messages, ...extraBody })
31
+ }
32
+ })
33
+ );
34
+ }
35
+
36
+ /**
37
+ * Helper: send a cancel request
38
+ */
39
+ function sendCancel(ws: WebSocket, requestId: string) {
40
+ ws.send(
41
+ JSON.stringify({
42
+ type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL,
43
+ id: requestId
44
+ })
45
+ );
46
+ }
47
+
48
+ /**
49
+ * Helper: collect messages from a WebSocket until a done message arrives or timeout
50
+ */
51
+ function collectMessages(
52
+ ws: WebSocket,
53
+ timeoutMs = 5000
54
+ ): Promise<{ messages: unknown[]; timedOut: boolean }> {
55
+ const messages: unknown[] = [];
56
+ let resolve: (value: { messages: unknown[]; timedOut: boolean }) => void;
57
+ const promise = new Promise<{ messages: unknown[]; timedOut: boolean }>(
58
+ (r) => {
59
+ resolve = r;
60
+ }
61
+ );
62
+
63
+ const timeout = setTimeout(() => {
64
+ ws.removeEventListener("message", handler);
65
+ resolve({ messages, timedOut: true });
66
+ }, timeoutMs);
67
+
68
+ function handler(e: MessageEvent) {
69
+ const data = JSON.parse(e.data as string);
70
+ messages.push(data);
71
+ if (isUseChatResponseMessage(data) && data.done) {
72
+ clearTimeout(timeout);
73
+ ws.removeEventListener("message", handler);
74
+ resolve({ messages, timedOut: false });
75
+ }
76
+ }
77
+
78
+ ws.addEventListener("message", handler);
79
+ return promise;
80
+ }
81
+
82
+ const userMessage: ChatMessage = {
83
+ id: "msg1",
84
+ role: "user",
85
+ parts: [{ type: "text", text: "Hello" }]
86
+ };
87
+
88
+ describe("Cancel request", () => {
89
+ it("cancel during plaintext streaming sends done and stops chunks", async () => {
90
+ const room = crypto.randomUUID();
91
+ const { ws } = await connectSlowStream(room);
92
+ await new Promise((r) => setTimeout(r, 50));
93
+
94
+ const requestId = "req-cancel-plain";
95
+
96
+ // Start collecting messages
97
+ const collecting = collectMessages(ws);
98
+
99
+ // Send a slow plaintext streaming request (20 chunks × 50ms = ~1s total)
100
+ sendChatRequest(ws, requestId, [userMessage], {
101
+ format: "plaintext",
102
+ chunkCount: 20,
103
+ chunkDelayMs: 50
104
+ });
105
+
106
+ // Wait for a couple of chunks to arrive, then cancel
107
+ await new Promise((r) => setTimeout(r, 200));
108
+ sendCancel(ws, requestId);
109
+
110
+ const { messages, timedOut } = await collecting;
111
+ expect(timedOut).toBe(false);
112
+
113
+ // Should have received a done message
114
+ const chatResponses = messages.filter(isUseChatResponseMessage);
115
+ const doneMsg = chatResponses.find((m) => m.done === true);
116
+ expect(doneMsg).toBeDefined();
117
+
118
+ // Should NOT have received all 20 chunks worth of text-delta events
119
+ // (we cancelled after ~200ms, which is ~4 chunks at 50ms each)
120
+ const textDeltas = chatResponses.filter((m) => {
121
+ if (!m.body || typeof m.body !== "string" || m.body.length === 0)
122
+ return false;
123
+ try {
124
+ const parsed = JSON.parse(m.body);
125
+ return parsed.type === "text-delta";
126
+ } catch {
127
+ return false;
128
+ }
129
+ });
130
+ expect(textDeltas.length).toBeLessThan(20);
131
+
132
+ ws.close(1000);
133
+ });
134
+
135
+ it("cancel during SSE streaming sends done and stops chunks", async () => {
136
+ const room = crypto.randomUUID();
137
+ const { ws } = await connectSlowStream(room);
138
+ await new Promise((r) => setTimeout(r, 50));
139
+
140
+ const requestId = "req-cancel-sse";
141
+
142
+ const collecting = collectMessages(ws);
143
+
144
+ sendChatRequest(ws, requestId, [userMessage], {
145
+ format: "sse",
146
+ chunkCount: 20,
147
+ chunkDelayMs: 50
148
+ });
149
+
150
+ // Wait for some chunks then cancel
151
+ await new Promise((r) => setTimeout(r, 200));
152
+ sendCancel(ws, requestId);
153
+
154
+ const { messages, timedOut } = await collecting;
155
+ expect(timedOut).toBe(false);
156
+
157
+ // Should have received a done message
158
+ const chatResponses = messages.filter(isUseChatResponseMessage);
159
+ const doneMsg = chatResponses.find((m) => m.done === true);
160
+ expect(doneMsg).toBeDefined();
161
+
162
+ // Should have fewer chunks than a full stream
163
+ const dataChunks = chatResponses.filter(
164
+ (m) => m.body && typeof m.body === "string" && m.body.length > 0
165
+ );
166
+ expect(dataChunks.length).toBeLessThan(20);
167
+
168
+ ws.close(1000);
169
+ });
170
+
171
+ it("abort controller is cleaned up after cancel", async () => {
172
+ const room = crypto.randomUUID();
173
+ const { ws } = await connectSlowStream(room);
174
+ await new Promise((r) => setTimeout(r, 50));
175
+
176
+ const agentStub = await getAgentByName(env.SlowStreamAgent, room);
177
+
178
+ const requestId = "req-cancel-cleanup";
179
+ const collecting = collectMessages(ws);
180
+
181
+ sendChatRequest(ws, requestId, [userMessage], {
182
+ format: "plaintext",
183
+ chunkCount: 20,
184
+ chunkDelayMs: 50
185
+ });
186
+
187
+ await new Promise((r) => setTimeout(r, 200));
188
+ sendCancel(ws, requestId);
189
+
190
+ await collecting;
191
+
192
+ // Allow cleanup to complete
193
+ await new Promise((r) => setTimeout(r, 200));
194
+
195
+ const count = await agentStub.getAbortControllerCount();
196
+ expect(count).toBe(0);
197
+
198
+ ws.close(1000);
199
+ });
200
+
201
+ it("cancel with abortSignal wired to stream stops faster", async () => {
202
+ const room = crypto.randomUUID();
203
+ const { ws } = await connectSlowStream(room);
204
+ await new Promise((r) => setTimeout(r, 50));
205
+
206
+ const requestId = "req-cancel-with-signal";
207
+ const collecting = collectMessages(ws);
208
+
209
+ sendChatRequest(ws, requestId, [userMessage], {
210
+ format: "plaintext",
211
+ useAbortSignal: true,
212
+ chunkCount: 20,
213
+ chunkDelayMs: 50
214
+ });
215
+
216
+ await new Promise((r) => setTimeout(r, 200));
217
+ sendCancel(ws, requestId);
218
+
219
+ const { messages, timedOut } = await collecting;
220
+ expect(timedOut).toBe(false);
221
+
222
+ // Should have received done
223
+ const chatResponses = messages.filter(isUseChatResponseMessage);
224
+ const doneMsg = chatResponses.find((m) => m.done === true);
225
+ expect(doneMsg).toBeDefined();
226
+
227
+ // Abort controller should be cleaned up
228
+ await new Promise((r) => setTimeout(r, 200));
229
+ const agentStub = await getAgentByName(env.SlowStreamAgent, room);
230
+ const count = await agentStub.getAbortControllerCount();
231
+ expect(count).toBe(0);
232
+
233
+ ws.close(1000);
234
+ });
235
+
236
+ it("completing a full stream without cancel produces no abort-related issues", async () => {
237
+ const room = crypto.randomUUID();
238
+ const { ws } = await connectSlowStream(room);
239
+ await new Promise((r) => setTimeout(r, 50));
240
+
241
+ const requestId = "req-no-cancel";
242
+ const collecting = collectMessages(ws);
243
+
244
+ // Send a fast request that completes naturally
245
+ sendChatRequest(ws, requestId, [userMessage], {
246
+ format: "plaintext",
247
+ chunkCount: 3,
248
+ chunkDelayMs: 10
249
+ });
250
+
251
+ const { messages, timedOut } = await collecting;
252
+ expect(timedOut).toBe(false);
253
+
254
+ // Should have received all chunks + done
255
+ const chatResponses = messages.filter(isUseChatResponseMessage);
256
+ const doneMsg = chatResponses.find((m) => m.done === true);
257
+ expect(doneMsg).toBeDefined();
258
+
259
+ // Should have all 3 text-delta events
260
+ const textDeltas = chatResponses.filter((m) => {
261
+ if (!m.body || typeof m.body !== "string" || m.body.length === 0)
262
+ return false;
263
+ try {
264
+ const parsed = JSON.parse(m.body);
265
+ return parsed.type === "text-delta";
266
+ } catch {
267
+ return false;
268
+ }
269
+ });
270
+ expect(textDeltas.length).toBe(3);
271
+
272
+ // Abort controller should be cleaned up
273
+ await new Promise((r) => setTimeout(r, 100));
274
+ const agentStub = await getAgentByName(env.SlowStreamAgent, room);
275
+ const count = await agentStub.getAbortControllerCount();
276
+ expect(count).toBe(0);
277
+
278
+ ws.close(1000);
279
+ });
280
+ });