@cloudflare/ai-chat 0.8.5 → 0.9.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.
package/dist/react.d.ts CHANGED
@@ -1,442 +1,29 @@
1
1
  import {
2
- ClientToolSchema,
3
- ClientToolSchema as ClientToolSchema$1
4
- } from "agents/chat";
5
- import { UseChatOptions, useChat } from "@ai-sdk/react";
6
- import { ChatInit, JSONSchema7, Tool, UIMessage } from "ai";
7
-
8
- //#region src/ws-chat-transport.d.ts
9
- /**
10
- * Agent-like interface for sending/receiving WebSocket messages.
11
- * Matches the shape returned by useAgent from agents/react.
12
- */
13
- interface AgentConnection {
14
- send: (data: string) => void;
15
- addEventListener: (
16
- type: string,
17
- listener: (event: MessageEvent) => void,
18
- options?: {
19
- signal?: AbortSignal;
20
- }
21
- ) => void;
22
- removeEventListener: (
23
- type: string,
24
- listener: (event: MessageEvent) => void
25
- ) => void;
26
- }
27
- //#endregion
28
- //#region src/react.d.ts
29
- /**
30
- * JSON Schema type for tool parameters.
31
- * Re-exported from the AI SDK for convenience.
32
- * @deprecated Import JSONSchema7 directly from "ai" instead. Will be removed in the next major version.
33
- */
34
- type JSONSchemaType = JSONSchema7;
35
- /**
36
- * Definition for a tool that can be executed on the client.
37
- * Tools with an `execute` function are automatically registered with the server.
38
- *
39
- * **For most apps**, define tools on the server with `tool()` from `"ai"` —
40
- * you get full Zod type safety and simpler code. Use `onToolCall` in
41
- * `useAgentChat` for tools that need browser-side execution.
42
- *
43
- * **For SDKs and platforms** where the tool surface is determined dynamically
44
- * by the embedding application at runtime, this type lets the client register
45
- * tools the server does not know about at deploy time.
46
- *
47
- * Note: Uses `parameters` (JSONSchema7) because client tools must be
48
- * serializable for the wire format. Zod schemas cannot be serialized.
49
- */
50
- type AITool<Input = unknown, Output = unknown> = {
51
- /** Human-readable description of what the tool does */ description?: Tool["description"] /** JSON Schema defining the tool's input parameters */;
52
- parameters?: JSONSchema7;
53
- /**
54
- * @deprecated Use `parameters` instead. Will be removed in a future version.
55
- */
56
- inputSchema?: JSONSchema7;
57
- /**
58
- * Function to execute the tool on the client.
59
- * If provided, the tool schema is automatically sent to the server.
60
- */
61
- execute?: (input: Input) => Output | Promise<Output>;
62
- };
63
- /**
64
- * Extracts tool schemas from tools that have client-side execute functions.
65
- * These schemas are automatically sent to the server with each request.
66
- *
67
- * Called internally by `useAgentChat` when `tools` are provided.
68
- * Most apps do not need to call this directly.
69
- *
70
- * @param tools - Record of tool name to tool definition
71
- * @returns Array of tool schemas to send to server, or undefined if none
72
- */
73
- declare function extractClientToolSchemas(
74
- tools?: Record<string, AITool<unknown, unknown>>
75
- ): ClientToolSchema$1[] | undefined;
76
- /**
77
- * Map internal tool part states to simplified UI-relevant states.
78
- *
79
- * @example
80
- * ```tsx
81
- * import { isToolUIPart } from "ai";
82
- * import { getToolPartState } from "@cloudflare/ai-chat/react";
83
- *
84
- * if (isToolUIPart(part)) {
85
- * const state = getToolPartState(part);
86
- * if (state === "complete") { ... }
87
- * if (state === "waiting-approval") { ... }
88
- * }
89
- * ```
90
- */
91
- declare function getToolPartState(
92
- part: UIMessage["parts"][number]
93
- ):
94
- | "loading"
95
- | "streaming"
96
- | "waiting-approval"
97
- | "approved"
98
- | "complete"
99
- | "error"
100
- | "denied";
101
- /** Get the tool call ID from a tool UI part. */
102
- declare function getToolCallId(part: UIMessage["parts"][number]): string;
103
- /** Get the tool input from a tool UI part (if available). */
104
- declare function getToolInput(
105
- part: UIMessage["parts"][number]
106
- ): unknown | undefined;
107
- /** Get the tool output from a tool UI part (if available). */
108
- declare function getToolOutput(
109
- part: UIMessage["parts"][number]
110
- ): unknown | undefined;
111
- /** Get the approval info from a tool UI part (if in approval state). */
112
- declare function getToolApproval(part: UIMessage["parts"][number]):
113
- | {
114
- id: string;
115
- approved?: boolean;
116
- }
117
- | undefined;
118
- /**
119
- * Fetch messages from an agent's `/get-messages` HTTP endpoint.
120
- *
121
- * Use in framework route loaders to prefetch messages before the component
122
- * tree mounts, or anywhere you need messages outside a React hook.
123
- *
124
- * @example Standard routing
125
- * ```typescript
126
- * import { getAgentMessages } from "@cloudflare/ai-chat/react";
127
- *
128
- * const messages = await getAgentMessages({
129
- * host: "https://my-app.workers.dev",
130
- * agent: "ChatAgent",
131
- * name: "session-123"
132
- * });
133
- * ```
134
- *
135
- * @example With basePath (custom URL)
136
- * ```typescript
137
- * const messages = await getAgentMessages({
138
- * url: "https://my-app.workers.dev/custom/path/get-messages"
139
- * });
140
- * ```
141
- */
142
- declare function getAgentMessages<M extends UIMessage = UIMessage>(
143
- options:
144
- | {
145
- host: string;
146
- agent: string;
147
- name: string;
148
- credentials?: RequestCredentials;
149
- headers?: HeadersInit;
150
- }
151
- | {
152
- url: string;
153
- credentials?: RequestCredentials;
154
- headers?: HeadersInit;
155
- }
156
- ): Promise<M[]>;
157
- type GetInitialMessagesOptions = {
158
- agent: string;
159
- name: string;
160
- url?: string;
161
- };
162
- type UseChatParams<M extends UIMessage = UIMessage> = ChatInit<M> &
163
- UseChatOptions<M>;
164
- /**
165
- * Options for preparing the send messages request.
166
- * Used by prepareSendMessagesRequest callback.
167
- */
168
- type PrepareSendMessagesRequestOptions<
169
- ChatMessage extends UIMessage = UIMessage
170
- > = {
171
- /** The chat ID */ id: string /** Messages to send */;
172
- messages: ChatMessage[] /** What triggered this request */;
173
- trigger:
174
- | "submit-message"
175
- | "regenerate-message" /** ID of the message being sent (if applicable) */;
176
- messageId?: string /** Request metadata */;
177
- requestMetadata?: unknown /** Current body (if any) */;
178
- body?: Record<string, unknown> /** Current credentials (if any) */;
179
- credentials?: RequestCredentials /** Current headers (if any) */;
180
- headers?: HeadersInit /** API endpoint */;
181
- api?: string;
182
- };
183
- /**
184
- * Return type for prepareSendMessagesRequest callback.
185
- * Allows customizing headers, body, and credentials for each request.
186
- * All fields are optional; only specify what you need to customize.
187
- */
188
- type PrepareSendMessagesRequestResult = {
189
- /** Custom headers to send with the request */ headers?: HeadersInit /** Custom body data to merge with the request */;
190
- body?: Record<string, unknown> /** Custom credentials option */;
191
- credentials?: RequestCredentials /** Custom API endpoint */;
192
- api?: string;
193
- };
194
- /**
195
- * Options for addToolOutput function
196
- */
197
- type AddToolOutputOptions = {
198
- /** The ID of the tool call to provide output for */ toolCallId: string /** The name of the tool (optional, for type safety) */;
199
- toolName?: string /** The output to provide */;
200
- output?: unknown /** Override the tool part state (e.g. "output-error" for custom denial) */;
201
- state?:
202
- | "output-available"
203
- | "output-error" /** Error message when state is "output-error" */;
204
- errorText?: string;
205
- };
206
- /**
207
- * Callback for handling client-side tool execution.
208
- * Called when a tool without server-side execute is invoked.
209
- */
210
- type OnToolCallCallback = (options: {
211
- /** The tool call that needs to be handled */ toolCall: {
212
- toolCallId: string;
213
- toolName: string;
214
- input: unknown;
215
- } /** Function to provide the tool output (or signal an error/denial) */;
216
- addToolOutput: (options: Omit<AddToolOutputOptions, "toolName">) => void;
217
- }) => void | Promise<void>;
218
- /**
219
- * Options for the useAgentChat hook
220
- */
221
- type UseAgentChatOptions<
222
- State = unknown,
223
- ChatMessage extends UIMessage = UIMessage
224
- > = Omit<UseChatParams<ChatMessage>, "fetch" | "onToolCall"> & {
225
- /** Agent connection from useAgent (accepts both typed and untyped agents) */ agent: AgentConnection & {
226
- agent: string;
227
- name: string;
228
- path?: ReadonlyArray<{
229
- agent: string;
230
- name: string;
231
- }>;
232
- getHttpUrl: () => string;
233
- };
234
- getInitialMessages?:
235
- | undefined
236
- | null
237
- | ((
238
- options: GetInitialMessagesOptions
239
- ) => Promise<ChatMessage[]>) /** Request credentials */;
240
- credentials?: RequestCredentials /** Request headers */;
241
- headers?: HeadersInit;
242
- /**
243
- * Callback for handling client-side tool execution.
244
- * Called when a tool without server-side `execute` is invoked by the LLM.
245
- *
246
- * Use this for:
247
- * - Tools that need browser APIs (geolocation, camera, etc.)
248
- * - Tools that need user interaction before providing a result
249
- * - Tools requiring approval before execution
250
- *
251
- * @example
252
- * ```typescript
253
- * onToolCall: async ({ toolCall, addToolOutput }) => {
254
- * if (toolCall.toolName === 'getLocation') {
255
- * const position = await navigator.geolocation.getCurrentPosition();
256
- * addToolOutput({
257
- * toolCallId: toolCall.toolCallId,
258
- * output: { lat: position.coords.latitude, lng: position.coords.longitude }
259
- * });
260
- * }
261
- * }
262
- * ```
263
- */
264
- onToolCall?: OnToolCallCallback;
265
- /**
266
- * @deprecated Use `onToolCall` callback instead for automatic tool execution.
267
- * @description Whether to automatically resolve tool calls that do not require human interaction.
268
- * @experimental
269
- */
270
- experimental_automaticToolResolution?: boolean;
271
- /**
272
- * Tools that can be executed on the client. Tool schemas are automatically
273
- * sent to the server and tool calls are routed back for client execution.
274
- *
275
- * **For most apps**, define tools on the server with `tool()` from `"ai"`
276
- * and handle client-side execution via `onToolCall`. This gives you full
277
- * Zod type safety and keeps tool definitions in one place.
278
- *
279
- * **For SDKs and platforms** where tools are defined dynamically by the
280
- * embedding application at runtime, this option lets the client register
281
- * tools the server does not know about at deploy time.
282
- */
283
- tools?: Record<string, AITool<unknown, unknown>>;
284
- /**
285
- * @deprecated Use `needsApproval` on server-side tools instead.
286
- * @description Manual override for tools requiring confirmation.
287
- * If not provided, will auto-detect from tools object (tools without execute require confirmation).
288
- */
289
- toolsRequiringConfirmation?: string[];
290
- /**
291
- * When true (default), the server automatically continues the conversation
292
- * after receiving client-side tool results or approvals, similar to how
293
- * server-executed tools work with maxSteps in streamText. The continuation
294
- * is merged into the same assistant message.
295
- *
296
- * When false, the client must call sendMessage() after tool results
297
- * to continue the conversation, which creates a new assistant message.
298
- *
299
- * @default true
300
- */
301
- autoContinueAfterToolResult?: boolean;
302
- /**
303
- * @deprecated Use `sendAutomaticallyWhen` from AI SDK instead.
304
- *
305
- * When true (default), automatically sends the next message only after
306
- * all pending confirmation-required tool calls have been resolved.
307
- * When false, sends immediately after each tool result.
308
- *
309
- * Only applies when `autoContinueAfterToolResult` is false.
310
- *
311
- * @default true
312
- */
313
- autoSendAfterAllConfirmationsResolved?: boolean;
314
- /**
315
- * Set to false to disable automatic stream resumption.
316
- * @default true
317
- */
318
- resume?: boolean;
319
- /**
320
- * Whether generic client-side stream abort/cleanup should cancel the server
321
- * turn. By default, client cleanup is local-only so the server turn can
322
- * continue and be resumed on reconnect. Explicit stop() always cancels the
323
- * server turn.
324
- *
325
- * @default false
326
- */
327
- cancelOnClientAbort?: boolean;
328
- /**
329
- * Custom data to include in every chat request body.
330
- * Accepts a static object or a function that returns one (for dynamic values).
331
- * These fields are available in `onChatMessage` via `options.body`.
332
- *
333
- * @example
334
- * ```typescript
335
- * // Static
336
- * body: { timezone: "America/New_York", userId: "abc" }
337
- *
338
- * // Dynamic (called on each send)
339
- * body: () => ({ token: getAuthToken(), timestamp: Date.now() })
340
- * ```
341
- */
342
- body?:
343
- | Record<string, unknown>
344
- | (() => Record<string, unknown> | Promise<Record<string, unknown>>);
345
- /**
346
- * Callback to customize the request before sending messages.
347
- * For most cases, use the `body` option instead.
348
- * Use this for advanced scenarios that need access to the messages or trigger type.
349
- *
350
- * Note: Client tool schemas are automatically sent when tools have `execute` functions.
351
- * This callback can add additional data alongside the auto-extracted schemas.
352
- */
353
- prepareSendMessagesRequest?: (
354
- options: PrepareSendMessagesRequestOptions<ChatMessage>
355
- ) =>
356
- | PrepareSendMessagesRequestResult
357
- | Promise<PrepareSendMessagesRequestResult>;
358
- };
359
- /**
360
- * React hook for building AI chat interfaces using an Agent
361
- * @param options Chat options including the agent connection
362
- * @returns Chat interface controls and state with added clearHistory method
363
- */
364
- /**
365
- * Automatically detects which tools require confirmation based on their configuration.
366
- * Tools require confirmation if they have no execute function AND are not server-executed.
367
- * @param tools - Record of tool name to tool definition
368
- * @returns Array of tool names that require confirmation
369
- *
370
- * @deprecated Use `needsApproval` on server-side tools instead.
371
- */
372
- declare function detectToolsRequiringConfirmation(
373
- tools?: Record<string, AITool<unknown, unknown>>
374
- ): string[];
375
- declare function useAgentChat<
376
- State = unknown,
377
- ChatMessage extends UIMessage = UIMessage
378
- >(
379
- options: UseAgentChatOptions<State, ChatMessage>
380
- ): Omit<ReturnType<typeof useChat<ChatMessage>>, "addToolOutput"> & {
381
- clearHistory: () => void;
382
- /**
383
- * Provide output for a tool call. Use this for tools that require user interaction
384
- * or client-side execution.
385
- */
386
- addToolOutput: (opts: AddToolOutputOptions) => void;
387
- /**
388
- * Whether a server-initiated stream (e.g. from `saveMessages`,
389
- * auto-continuation, or another tab) is currently active, OR a
390
- * client-side tool call is awaiting resolution via `onToolCall`.
391
- * Covers the full "turn-in-progress" window from the consumer's
392
- * perspective, including the gap between the model emitting a
393
- * client-tool call and the server pushing a continuation after
394
- * `addToolOutput`. This is independent of the AI SDK's `status`
395
- * which only tracks client-initiated request/response cycles.
396
- */
397
- isServerStreaming: boolean;
398
- /**
399
- * Convenience flag: `true` when either the client-initiated stream
400
- * (`status === "streaming"`) or a server-initiated stream is active.
401
- * Use this for showing a universal streaming indicator.
402
- */
403
- isStreaming: boolean;
404
- /**
405
- * `true` while a durable chat turn is being recovered (interrupted by a
406
- * deploy/eviction or a stream-stall watchdog abort and now resuming, #1620).
407
- * Distinct from `isStreaming` — a recovering turn isn't producing tokens yet,
408
- * so a client can show a "recovering…" hint instead of looking frozen. Most
409
- * UIs treat `isStreaming || isRecovering` as "busy". Driven by the server's
410
- * `CF_AGENT_CHAT_RECOVERING` frames (also replayed on connect for
411
- * `@cloudflare/think`); cleared automatically on the next stream or terminal.
412
- */
413
- isRecovering: boolean;
414
- /**
415
- * `true` when the current `status`/`isServerStreaming` activity is
416
- * driven by a server-pushed tool continuation (i.e. the server is
417
- * auto-continuing the conversation after `addToolOutput` or
418
- * `addToolApprovalResponse`) rather than a fresh user submission.
419
- *
420
- * Use this to disambiguate "user just sent a new message, awaiting
421
- * first token" from "mid-turn tool round-trip" — e.g. when you want
422
- * a typing indicator only for the former:
423
- *
424
- * ```tsx
425
- * const showTypingIndicator = status === "submitted" && !isToolContinuation;
426
- * ```
427
- *
428
- * See issue #1365.
429
- */
430
- isToolContinuation: boolean;
431
- };
432
- //#endregion
433
- export {
434
2
  AITool,
435
- type ClientToolSchema,
3
+ ClientToolSchema,
436
4
  JSONSchemaType,
437
5
  OnToolCallCallback,
438
6
  PrepareSendMessagesRequestOptions,
439
7
  PrepareSendMessagesRequestResult,
8
+ UseAgentChatOptions,
9
+ detectToolsRequiringConfirmation,
10
+ extractClientToolSchemas,
11
+ getAgentMessages,
12
+ getToolApproval,
13
+ getToolCallId,
14
+ getToolInput,
15
+ getToolOutput,
16
+ getToolPartState,
17
+ useAgentChat
18
+ } from "agents/chat/react";
19
+ export {
20
+ type AITool,
21
+ type ClientToolSchema,
22
+ type JSONSchemaType,
23
+ type OnToolCallCallback,
24
+ type PrepareSendMessagesRequestOptions,
25
+ type PrepareSendMessagesRequestResult,
26
+ type UseAgentChatOptions,
440
27
  detectToolsRequiringConfirmation,
441
28
  extractClientToolSchemas,
442
29
  getAgentMessages,
@@ -447,4 +34,3 @@ export {
447
34
  getToolPartState,
448
35
  useAgentChat
449
36
  };
450
- //# sourceMappingURL=react.d.ts.map