@cloudflare/ai-chat 0.3.2 → 0.4.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
@@ -54,6 +54,87 @@ type AITool<Input = unknown, Output = unknown> = {
54
54
  declare function extractClientToolSchemas(
55
55
  tools?: Record<string, AITool<unknown, unknown>>
56
56
  ): ClientToolSchema$1[] | undefined;
57
+ /**
58
+ * Map internal tool part states to simplified UI-relevant states.
59
+ *
60
+ * @example
61
+ * ```tsx
62
+ * import { isToolUIPart } from "ai";
63
+ * import { getToolPartState } from "@cloudflare/ai-chat/react";
64
+ *
65
+ * if (isToolUIPart(part)) {
66
+ * const state = getToolPartState(part);
67
+ * if (state === "complete") { ... }
68
+ * if (state === "waiting-approval") { ... }
69
+ * }
70
+ * ```
71
+ */
72
+ declare function getToolPartState(
73
+ part: UIMessage["parts"][number]
74
+ ):
75
+ | "loading"
76
+ | "streaming"
77
+ | "waiting-approval"
78
+ | "approved"
79
+ | "complete"
80
+ | "error"
81
+ | "denied";
82
+ /** Get the tool call ID from a tool UI part. */
83
+ declare function getToolCallId(part: UIMessage["parts"][number]): string;
84
+ /** Get the tool input from a tool UI part (if available). */
85
+ declare function getToolInput(
86
+ part: UIMessage["parts"][number]
87
+ ): unknown | undefined;
88
+ /** Get the tool output from a tool UI part (if available). */
89
+ declare function getToolOutput(
90
+ part: UIMessage["parts"][number]
91
+ ): unknown | undefined;
92
+ /** Get the approval info from a tool UI part (if in approval state). */
93
+ declare function getToolApproval(part: UIMessage["parts"][number]):
94
+ | {
95
+ id: string;
96
+ approved?: boolean;
97
+ }
98
+ | undefined;
99
+ /**
100
+ * Fetch messages from an agent's `/get-messages` HTTP endpoint.
101
+ *
102
+ * Use in framework route loaders to prefetch messages before the component
103
+ * tree mounts, or anywhere you need messages outside a React hook.
104
+ *
105
+ * @example Standard routing
106
+ * ```typescript
107
+ * import { getAgentMessages } from "@cloudflare/ai-chat/react";
108
+ *
109
+ * const messages = await getAgentMessages({
110
+ * host: "https://my-app.workers.dev",
111
+ * agent: "ChatAgent",
112
+ * name: "session-123"
113
+ * });
114
+ * ```
115
+ *
116
+ * @example With basePath (custom URL)
117
+ * ```typescript
118
+ * const messages = await getAgentMessages({
119
+ * url: "https://my-app.workers.dev/custom/path/get-messages"
120
+ * });
121
+ * ```
122
+ */
123
+ declare function getAgentMessages<M extends UIMessage = UIMessage>(
124
+ options:
125
+ | {
126
+ host: string;
127
+ agent: string;
128
+ name: string;
129
+ credentials?: RequestCredentials;
130
+ headers?: HeadersInit;
131
+ }
132
+ | {
133
+ url: string;
134
+ credentials?: RequestCredentials;
135
+ headers?: HeadersInit;
136
+ }
137
+ ): Promise<M[]>;
57
138
  type GetInitialMessagesOptions = {
58
139
  agent: string;
59
140
  name: string;
@@ -293,6 +374,12 @@ export {
293
374
  PrepareSendMessagesRequestResult,
294
375
  detectToolsRequiringConfirmation,
295
376
  extractClientToolSchemas,
377
+ getAgentMessages,
378
+ getToolApproval,
379
+ getToolCallId,
380
+ getToolInput,
381
+ getToolOutput,
382
+ getToolPartState,
296
383
  useAgentChat
297
384
  };
298
385
  //# 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