@cloudflare/ai-chat 0.1.3 → 0.1.5

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.
package/dist/react.d.ts CHANGED
@@ -13,13 +13,16 @@ type JSONSchemaType = JSONSchema7;
13
13
  * Definition for a tool that can be executed on the client.
14
14
  * Tools with an `execute` function are automatically registered with the server.
15
15
  *
16
- * Note: Uses `parameters` (JSONSchema7) rather than AI SDK's `inputSchema` (FlexibleSchema)
17
- * because client tools must be serializable for the wire format. Zod schemas cannot be
18
- * serialized, so we require raw JSON Schema here.
16
+ * **For most apps**, define tools on the server with `tool()` from `"ai"` —
17
+ * you get full Zod type safety and simpler code. Use `onToolCall` in
18
+ * `useAgentChat` for tools that need browser-side execution.
19
19
  *
20
- * @deprecated Use AI SDK's native tool pattern instead. Define tools on the server with
21
- * `tool()` from "ai", and handle client-side execution via the `onToolCall` callback
22
- * in `useAgentChat`. For tools requiring user approval, use `needsApproval` on the server.
20
+ * **For SDKs and platforms** where the tool surface is determined dynamically
21
+ * by the embedding application at runtime, this type lets the client register
22
+ * tools the server does not know about at deploy time.
23
+ *
24
+ * Note: Uses `parameters` (JSONSchema7) because client tools must be
25
+ * serializable for the wire format. Zod schemas cannot be serialized.
23
26
  */
24
27
  type AITool<Input = unknown, Output = unknown> = {
25
28
  /** Human-readable description of what the tool does */ description?: Tool["description"] /** JSON Schema defining the tool's input parameters */;
@@ -36,10 +39,11 @@ type AITool<Input = unknown, Output = unknown> = {
36
39
  };
37
40
  /**
38
41
  * Schema for a client tool sent to the server.
39
- * This is the wire format - what gets sent in the request body.
40
- * Must match the server-side ClientToolSchema type in ai-chat-agent.ts.
42
+ * This is the wire format — what gets sent in the request body.
43
+ * Must match the server-side ClientToolSchema type.
41
44
  *
42
- * @deprecated Use AI SDK's native tool pattern instead. Define tools on the server.
45
+ * Most apps do not need this directly — it is used internally when the
46
+ * `tools` option on `useAgentChat` contains tools with `execute` functions.
43
47
  */
44
48
  type ClientToolSchema = {
45
49
  /** Unique name for the tool */ name: string /** Human-readable description of what the tool does */;
@@ -49,11 +53,12 @@ type ClientToolSchema = {
49
53
  /**
50
54
  * Extracts tool schemas from tools that have client-side execute functions.
51
55
  * These schemas are automatically sent to the server with each request.
56
+ *
57
+ * Called internally by `useAgentChat` when `tools` are provided.
58
+ * Most apps do not need to call this directly.
59
+ *
52
60
  * @param tools - Record of tool name to tool definition
53
61
  * @returns Array of tool schemas to send to server, or undefined if none
54
- *
55
- * @deprecated Use AI SDK's native tool pattern instead. Define tools on the server
56
- * and use `onToolCall` callback for client-side execution.
57
62
  */
58
63
  declare function extractClientToolSchemas(
59
64
  tools?: Record<string, AITool<unknown, unknown>>
@@ -95,6 +100,18 @@ type PrepareSendMessagesRequestResult = {
95
100
  credentials?: RequestCredentials /** Custom API endpoint */;
96
101
  api?: string;
97
102
  };
103
+ /**
104
+ * Options for addToolOutput function
105
+ */
106
+ type AddToolOutputOptions = {
107
+ /** The ID of the tool call to provide output for */ toolCallId: string /** The name of the tool (optional, for type safety) */;
108
+ toolName?: string /** The output to provide */;
109
+ output?: unknown /** Override the tool part state (e.g. "output-error" for custom denial) */;
110
+ state?:
111
+ | "output-available"
112
+ | "output-error" /** Error message when state is "output-error" */;
113
+ errorText?: string;
114
+ };
98
115
  /**
99
116
  * Callback for handling client-side tool execution.
100
117
  * Called when a tool without server-side execute is invoked.
@@ -104,8 +121,8 @@ type OnToolCallCallback = (options: {
104
121
  toolCallId: string;
105
122
  toolName: string;
106
123
  input: unknown;
107
- } /** Function to provide the tool output */;
108
- addToolOutput: (options: { toolCallId: string; output: unknown }) => void;
124
+ } /** Function to provide the tool output (or signal an error/denial) */;
125
+ addToolOutput: (options: Omit<AddToolOutputOptions, "toolName">) => void;
109
126
  }) => void | Promise<void>;
110
127
  /**
111
128
  * Options for the useAgentChat hook
@@ -155,10 +172,16 @@ type UseAgentChatOptions<
155
172
  */
156
173
  experimental_automaticToolResolution?: boolean;
157
174
  /**
158
- * @deprecated Use `onToolCall` callback instead. Define tools on the server
159
- * and handle client-side execution via `onToolCall`.
175
+ * Tools that can be executed on the client. Tool schemas are automatically
176
+ * sent to the server and tool calls are routed back for client execution.
177
+ *
178
+ * **For most apps**, define tools on the server with `tool()` from `"ai"`
179
+ * and handle client-side execution via `onToolCall`. This gives you full
180
+ * Zod type safety and keeps tool definitions in one place.
160
181
  *
161
- * Tools that can be executed on the client.
182
+ * **For SDKs and platforms** where tools are defined dynamically by the
183
+ * embedding application at runtime, this option lets the client register
184
+ * tools the server does not know about at deploy time.
162
185
  */
163
186
  tools?: Record<string, AITool<unknown, unknown>>;
164
187
  /**
@@ -243,14 +266,6 @@ type UseAgentChatOptions<
243
266
  declare function detectToolsRequiringConfirmation(
244
267
  tools?: Record<string, AITool<unknown, unknown>>
245
268
  ): string[];
246
- /**
247
- * Return type for addToolOutput function
248
- */
249
- type AddToolOutputOptions = {
250
- /** The ID of the tool call to provide output for */ toolCallId: string /** The name of the tool (optional, for type safety) */;
251
- toolName?: string /** The output to provide */;
252
- output: unknown;
253
- };
254
269
  declare function useAgentChat<
255
270
  State = unknown,
256
271
  ChatMessage extends UIMessage = UIMessage
package/dist/react.js CHANGED
@@ -36,51 +36,59 @@ var WebSocketChatTransport = class {
36
36
  ...extraBody
37
37
  });
38
38
  this.activeRequestIds?.add(requestId);
39
- options.abortSignal?.addEventListener("abort", () => {
40
- if (completed) return;
41
- this.agent.send(JSON.stringify({
42
- id: requestId,
43
- type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL
44
- }));
45
- this.activeRequestIds?.delete(requestId);
46
- abortController.abort();
47
- });
48
39
  const agent = this.agent;
49
40
  const activeIds = this.activeRequestIds;
41
+ const finish = (action) => {
42
+ if (completed) return;
43
+ completed = true;
44
+ try {
45
+ action();
46
+ } catch {}
47
+ activeIds?.delete(requestId);
48
+ abortController.abort();
49
+ };
50
+ const abortError = /* @__PURE__ */ new Error("Aborted");
51
+ abortError.name = "AbortError";
52
+ const onAbort = () => {
53
+ if (completed) return;
54
+ try {
55
+ agent.send(JSON.stringify({
56
+ id: requestId,
57
+ type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL
58
+ }));
59
+ } catch {}
60
+ finish(() => streamController.error(abortError));
61
+ };
62
+ let streamController;
50
63
  const stream = new ReadableStream({
51
64
  start(controller) {
65
+ streamController = controller;
52
66
  const onMessage = (event) => {
53
67
  try {
54
68
  const data = JSON.parse(event.data);
55
69
  if (data.type !== MessageType.CF_AGENT_USE_CHAT_RESPONSE) return;
56
70
  if (data.id !== requestId) return;
57
71
  if (data.error) {
58
- completed = true;
59
- controller.error(new Error(data.body));
60
- activeIds?.delete(requestId);
61
- abortController.abort();
72
+ finish(() => controller.error(new Error(data.body)));
62
73
  return;
63
74
  }
64
75
  if (data.body?.trim()) try {
65
76
  const chunk = JSON.parse(data.body);
66
77
  controller.enqueue(chunk);
67
78
  } catch {}
68
- if (data.done) {
69
- completed = true;
70
- try {
71
- controller.close();
72
- } catch {}
73
- activeIds?.delete(requestId);
74
- abortController.abort();
75
- }
79
+ if (data.done) finish(() => controller.close());
76
80
  } catch {}
77
81
  };
78
82
  agent.addEventListener("message", onMessage, { signal: abortController.signal });
79
83
  },
80
84
  cancel() {
81
- abortController.abort();
85
+ onAbort();
82
86
  }
83
87
  });
88
+ if (options.abortSignal) {
89
+ options.abortSignal.addEventListener("abort", onAbort, { once: true });
90
+ if (options.abortSignal.aborted) onAbort();
91
+ }
84
92
  agent.send(JSON.stringify({
85
93
  id: requestId,
86
94
  init: {
@@ -111,14 +119,14 @@ function warnDeprecated(id, message) {
111
119
  /**
112
120
  * Extracts tool schemas from tools that have client-side execute functions.
113
121
  * These schemas are automatically sent to the server with each request.
122
+ *
123
+ * Called internally by `useAgentChat` when `tools` are provided.
124
+ * Most apps do not need to call this directly.
125
+ *
114
126
  * @param tools - Record of tool name to tool definition
115
127
  * @returns Array of tool schemas to send to server, or undefined if none
116
- *
117
- * @deprecated Use AI SDK's native tool pattern instead. Define tools on the server
118
- * and use `onToolCall` callback for client-side execution.
119
128
  */
120
129
  function extractClientToolSchemas(tools) {
121
- warnDeprecated("extractClientToolSchemas", "extractClientToolSchemas() is deprecated. Define tools on the server and use onToolCall for client execution. Will be removed in the next major version.");
122
130
  if (!tools) return void 0;
123
131
  const schemas = Object.entries(tools).filter(([_, tool]) => tool.execute).map(([name, tool]) => {
124
132
  if (tool.inputSchema && !tool.parameters) console.warn(`[useAgentChat] Tool "${name}" uses deprecated 'inputSchema'. Please migrate to 'parameters'.`);
@@ -157,11 +165,14 @@ function detectToolsRequiringConfirmation(tools) {
157
165
  }
158
166
  function useAgentChat(options) {
159
167
  const { agent, getInitialMessages, messages: optionsInitialMessages, onToolCall, onData, experimental_automaticToolResolution, tools, toolsRequiringConfirmation: manualToolsRequiringConfirmation, autoContinueAfterToolResult = true, autoSendAfterAllConfirmationsResolved = true, resume = true, body: bodyOption, prepareSendMessagesRequest, ...rest } = options;
160
- if (tools) warnDeprecated("useAgentChat.tools", "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.");
161
168
  if (manualToolsRequiringConfirmation) warnDeprecated("useAgentChat.toolsRequiringConfirmation", "The 'toolsRequiringConfirmation' option is deprecated. Use needsApproval on server-side tools instead. Will be removed in the next major version.");
162
169
  if (experimental_automaticToolResolution) warnDeprecated("useAgentChat.experimental_automaticToolResolution", "The 'experimental_automaticToolResolution' option is deprecated. Use the onToolCall callback instead. Will be removed in the next major version.");
163
170
  if (options.autoSendAfterAllConfirmationsResolved !== void 0) warnDeprecated("useAgentChat.autoSendAfterAllConfirmationsResolved", "The 'autoSendAfterAllConfirmationsResolved' option is deprecated. Use sendAutomaticallyWhen from AI SDK instead. Will be removed in the next major version.");
164
- const toolsRequiringConfirmation = useMemo(() => manualToolsRequiringConfirmation ?? (tools ? detectToolsRequiringConfirmation(tools) : []), [manualToolsRequiringConfirmation, tools]);
171
+ const toolsRequiringConfirmation = useMemo(() => {
172
+ if (manualToolsRequiringConfirmation) return manualToolsRequiringConfirmation;
173
+ if (!tools) return [];
174
+ return Object.entries(tools).filter(([_name, tool]) => !tool.execute).map(([name]) => name);
175
+ }, [manualToolsRequiringConfirmation, tools]);
165
176
  const onToolCallRef = useRef(onToolCall);
166
177
  onToolCallRef.current = onToolCall;
167
178
  const onDataRef = useRef(onData);
@@ -341,16 +352,18 @@ function useAgentChat(options) {
341
352
  autoContinueAfterToolResult,
342
353
  toolResolutionTrigger
343
354
  ]);
344
- const sendToolOutputToServer = useCallback((toolCallId, toolName, output) => {
355
+ const sendToolOutputToServer = useCallback((toolCallId, toolName, output, state, errorText) => {
345
356
  agentRef.current.send(JSON.stringify({
346
357
  type: MessageType.CF_AGENT_TOOL_RESULT,
347
358
  toolCallId,
348
359
  toolName,
349
360
  output,
350
- autoContinue: autoContinueAfterToolResult,
361
+ ...state ? { state } : {},
362
+ ...errorText !== void 0 ? { errorText } : {},
363
+ autoContinue: state === "output-error" ? false : autoContinueAfterToolResult,
351
364
  clientTools: toolsRef.current ? extractClientToolSchemas(toolsRef.current) : void 0
352
365
  }));
353
- setClientToolResults((prev) => new Map(prev).set(toolCallId, output));
366
+ if (state !== "output-error") setClientToolResults((prev) => new Map(prev).set(toolCallId, output));
354
367
  }, [autoContinueAfterToolResult]);
355
368
  const sendToolApprovalToServer = useCallback((toolCallId, approved) => {
356
369
  agentRef.current.send(JSON.stringify({
@@ -371,11 +384,11 @@ function useAgentChat(options) {
371
384
  const toolName = getToolName(part);
372
385
  processedToolCalls.current.add(toolCallId);
373
386
  const addToolOutput = (opts) => {
374
- sendToolOutputToServer(opts.toolCallId, toolName, opts.output);
387
+ sendToolOutputToServer(opts.toolCallId, toolName, opts.output, opts.state, opts.errorText);
375
388
  addToolResult({
376
389
  tool: toolName,
377
390
  toolCallId: opts.toolCallId,
378
- output: opts.output
391
+ output: opts.state === "output-error" ? opts.errorText ?? "Tool execution denied by user" : opts.output
379
392
  });
380
393
  };
381
394
  currentOnToolCall({
@@ -609,11 +622,11 @@ function useAgentChat(options) {
609
622
  }, [chatMessages]);
610
623
  const addToolOutput = useCallback((opts) => {
611
624
  const toolName = opts.toolName ?? "";
612
- sendToolOutputToServer(opts.toolCallId, toolName, opts.output);
625
+ sendToolOutputToServer(opts.toolCallId, toolName, opts.output, opts.state, opts.errorText);
613
626
  addToolResult({
614
627
  tool: toolName,
615
628
  toolCallId: opts.toolCallId,
616
- output: opts.output
629
+ output: opts.state === "output-error" ? opts.errorText ?? "Tool execution denied by user" : opts.output
617
630
  });
618
631
  }, [sendToolOutputToServer, addToolResult]);
619
632
  return {