@cloudflare/ai-chat 0.3.2 → 0.4.1

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
@@ -4,8 +4,27 @@ import {
4
4
  } from "agents/chat";
5
5
  import { UseChatOptions, useChat } from "@ai-sdk/react";
6
6
  import { ChatInit, JSONSchema7, Tool, UIMessage } from "ai";
7
- import { useAgent } from "agents/react";
8
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
9
28
  //#region src/react.d.ts
10
29
  /**
11
30
  * JSON Schema type for tool parameters.
@@ -54,6 +73,87 @@ type AITool<Input = unknown, Output = unknown> = {
54
73
  declare function extractClientToolSchemas(
55
74
  tools?: Record<string, AITool<unknown, unknown>>
56
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[]>;
57
157
  type GetInitialMessagesOptions = {
58
158
  agent: string;
59
159
  name: string;
@@ -119,12 +219,14 @@ type OnToolCallCallback = (options: {
119
219
  * Options for the useAgentChat hook
120
220
  */
121
221
  type UseAgentChatOptions<
122
- State,
222
+ State = unknown,
123
223
  ChatMessage extends UIMessage = UIMessage
124
224
  > = Omit<UseChatParams<ChatMessage>, "fetch" | "onToolCall"> & {
125
- /** Agent connection from useAgent */ agent: ReturnType<
126
- typeof useAgent<State>
127
- >;
225
+ /** Agent connection from useAgent (accepts both typed and untyped agents) */ agent: AgentConnection & {
226
+ agent: string;
227
+ name: string;
228
+ getHttpUrl: () => string;
229
+ };
128
230
  getInitialMessages?:
129
231
  | undefined
130
232
  | null
@@ -293,6 +395,12 @@ export {
293
395
  PrepareSendMessagesRequestResult,
294
396
  detectToolsRequiringConfirmation,
295
397
  extractClientToolSchemas,
398
+ getAgentMessages,
399
+ getToolApproval,
400
+ getToolCallId,
401
+ getToolInput,
402
+ getToolOutput,
403
+ getToolPartState,
296
404
  useAgentChat
297
405
  };
298
406
  //# sourceMappingURL=react.d.ts.map
package/dist/react.js CHANGED
@@ -360,6 +360,102 @@ function extractClientToolSchemas(tools) {
360
360
  return schemas.length > 0 ? schemas : void 0;
361
361
  }
362
362
  /**
363
+ * Map internal tool part states to simplified UI-relevant states.
364
+ *
365
+ * @example
366
+ * ```tsx
367
+ * import { isToolUIPart } from "ai";
368
+ * import { getToolPartState } from "@cloudflare/ai-chat/react";
369
+ *
370
+ * if (isToolUIPart(part)) {
371
+ * const state = getToolPartState(part);
372
+ * if (state === "complete") { ... }
373
+ * if (state === "waiting-approval") { ... }
374
+ * }
375
+ * ```
376
+ */
377
+ function getToolPartState(part) {
378
+ switch (part.state) {
379
+ case "input-streaming": return "streaming";
380
+ case "approval-requested": return "waiting-approval";
381
+ case "approval-responded": return "approved";
382
+ case "output-available": return "complete";
383
+ case "output-error": return "error";
384
+ case "output-denied": return "denied";
385
+ default: return "loading";
386
+ }
387
+ }
388
+ /** Get the tool call ID from a tool UI part. */
389
+ function getToolCallId(part) {
390
+ return part.toolCallId;
391
+ }
392
+ /** Get the tool input from a tool UI part (if available). */
393
+ function getToolInput(part) {
394
+ return part.input;
395
+ }
396
+ /** Get the tool output from a tool UI part (if available). */
397
+ function getToolOutput(part) {
398
+ return part.output;
399
+ }
400
+ /** Get the approval info from a tool UI part (if in approval state). */
401
+ function getToolApproval(part) {
402
+ return part.approval;
403
+ }
404
+ function agentNameToKebab(name) {
405
+ if (name === name.toUpperCase() && name !== name.toLowerCase()) return name.toLowerCase().replace(/_/g, "-");
406
+ let result = name.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
407
+ result = result.startsWith("-") ? result.slice(1) : result;
408
+ return result.replace(/_/g, "-").replace(/-$/, "");
409
+ }
410
+ /**
411
+ * Fetch messages from an agent's `/get-messages` HTTP endpoint.
412
+ *
413
+ * Use in framework route loaders to prefetch messages before the component
414
+ * tree mounts, or anywhere you need messages outside a React hook.
415
+ *
416
+ * @example Standard routing
417
+ * ```typescript
418
+ * import { getAgentMessages } from "@cloudflare/ai-chat/react";
419
+ *
420
+ * const messages = await getAgentMessages({
421
+ * host: "https://my-app.workers.dev",
422
+ * agent: "ChatAgent",
423
+ * name: "session-123"
424
+ * });
425
+ * ```
426
+ *
427
+ * @example With basePath (custom URL)
428
+ * ```typescript
429
+ * const messages = await getAgentMessages({
430
+ * url: "https://my-app.workers.dev/custom/path/get-messages"
431
+ * });
432
+ * ```
433
+ */
434
+ async function getAgentMessages(options) {
435
+ let messagesUrl;
436
+ if ("url" in options) messagesUrl = options.url;
437
+ else {
438
+ const agentSlug = agentNameToKebab(options.agent);
439
+ messagesUrl = `${options.host.endsWith("/") ? options.host.slice(0, -1) : options.host}/agents/${agentSlug}/${options.name}/get-messages`;
440
+ }
441
+ try {
442
+ const response = await fetch(messagesUrl, {
443
+ credentials: options.credentials,
444
+ headers: options.headers
445
+ });
446
+ if (!response.ok) {
447
+ console.warn(`[getAgentMessages] Failed to fetch: ${response.status} ${response.statusText}`);
448
+ return [];
449
+ }
450
+ const text = await response.text();
451
+ if (!text.trim()) return [];
452
+ return JSON.parse(text);
453
+ } catch (error) {
454
+ console.warn("[getAgentMessages] Fetch error:", error);
455
+ return [];
456
+ }
457
+ }
458
+ /**
363
459
  * Module-level cache for initial message fetches. Intentionally shared across
364
460
  * all useAgentChat instances to deduplicate requests during React Strict Mode
365
461
  * double-renders and re-renders. Cache keys include the agent URL, agent type,
@@ -417,7 +513,7 @@ function useAgentChat(options) {
417
513
  onToolCallRef.current = onToolCall;
418
514
  const onDataRef = useRef(onData);
419
515
  onDataRef.current = onData;
420
- const agentUrl = new URL(`${(agent._url || agent._pkurl)?.replace("ws://", "http://").replace("wss://", "https://")}`);
516
+ const agentUrl = new URL(agent.getHttpUrl());
421
517
  agentUrl.searchParams.delete("_pk");
422
518
  const agentUrlString = agentUrl.toString();
423
519
  const initialMessagesCacheKey = `${agentUrl.origin}${agentUrl.pathname}|${agent.agent ?? ""}|${agent.name ?? ""}`;
@@ -958,6 +1054,6 @@ function useAgentChat(options) {
958
1054
  };
959
1055
  }
960
1056
  //#endregion
961
- export { detectToolsRequiringConfirmation, extractClientToolSchemas, useAgentChat };
1057
+ export { detectToolsRequiringConfirmation, extractClientToolSchemas, getAgentMessages, getToolApproval, getToolCallId, getToolInput, getToolOutput, getToolPartState, useAgentChat };
962
1058
 
963
1059
  //# sourceMappingURL=react.js.map