@cloudflare/ai-chat 0.3.1 → 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
@@ -1,5 +1,9 @@
1
- import { ChatInit, JSONSchema7, Tool, UIMessage } from "ai";
1
+ import {
2
+ ClientToolSchema,
3
+ ClientToolSchema as ClientToolSchema$1
4
+ } from "agents/chat";
2
5
  import { UseChatOptions, useChat } from "@ai-sdk/react";
6
+ import { ChatInit, JSONSchema7, Tool, UIMessage } from "ai";
3
7
  import { useAgent } from "agents/react";
4
8
 
5
9
  //#region src/react.d.ts
@@ -37,19 +41,6 @@ type AITool<Input = unknown, Output = unknown> = {
37
41
  */
38
42
  execute?: (input: Input) => Output | Promise<Output>;
39
43
  };
40
- /**
41
- * Schema for a client tool sent to the server.
42
- * This is the wire format — what gets sent in the request body.
43
- * Must match the server-side ClientToolSchema type.
44
- *
45
- * Most apps do not need this directly — it is used internally when the
46
- * `tools` option on `useAgentChat` contains tools with `execute` functions.
47
- */
48
- type ClientToolSchema = {
49
- /** Unique name for the tool */ name: string /** Human-readable description of what the tool does */;
50
- description?: Tool["description"] /** JSON Schema defining the tool's input parameters */;
51
- parameters?: JSONSchema7;
52
- };
53
44
  /**
54
45
  * Extracts tool schemas from tools that have client-side execute functions.
55
46
  * These schemas are automatically sent to the server with each request.
@@ -62,7 +53,88 @@ type ClientToolSchema = {
62
53
  */
63
54
  declare function extractClientToolSchemas(
64
55
  tools?: Record<string, AITool<unknown, unknown>>
65
- ): ClientToolSchema[] | undefined;
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[]>;
66
138
  type GetInitialMessagesOptions = {
67
139
  agent: string;
68
140
  name: string;
@@ -295,13 +367,19 @@ declare function useAgentChat<
295
367
  //#endregion
296
368
  export {
297
369
  AITool,
298
- ClientToolSchema,
370
+ type ClientToolSchema,
299
371
  JSONSchemaType,
300
372
  OnToolCallCallback,
301
373
  PrepareSendMessagesRequestOptions,
302
374
  PrepareSendMessagesRequestResult,
303
375
  detectToolsRequiringConfirmation,
304
376
  extractClientToolSchemas,
377
+ getAgentMessages,
378
+ getToolApproval,
379
+ getToolCallId,
380
+ getToolInput,
381
+ getToolOutput,
382
+ getToolPartState,
305
383
  useAgentChat
306
384
  };
307
385
  //# sourceMappingURL=react.d.ts.map
package/dist/react.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { MessageType } from "./types.js";
2
- import { t as applyChunkToParts } from "./message-builder-BAgcFJMf.js";
3
- import { getToolName, isToolUIPart } from "ai";
2
+ import { broadcastTransition } from "agents/chat";
4
3
  import { nanoid } from "nanoid";
5
4
  import { useChat } from "@ai-sdk/react";
5
+ import { getToolName, isToolUIPart } from "ai";
6
6
  import { use, useCallback, useEffect, useMemo, useRef, useState } from "react";
7
7
  //#region src/ws-chat-transport.ts
8
8
  /**
@@ -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 ?? ""}`;
@@ -722,42 +818,8 @@ function useAgentChat(options) {
722
818
  sendToolOutputToServer,
723
819
  addToolResult
724
820
  ]);
725
- /**
726
- * Contains the request ID, accumulated message parts, metadata, and a unique message ID.
727
- * Used for both resumed streams and real-time broadcasts from other tabs.
728
- * Metadata is captured from start/finish/message-metadata stream chunks
729
- * so that it's included when the partial message is flushed to React state.
730
- */
731
- const activeStreamRef = useRef(null);
821
+ const streamStateRef = useRef({ status: "idle" });
732
822
  const [isServerStreaming, setIsServerStreaming] = useState(false);
733
- /**
734
- * Flush the active stream's accumulated parts into React state.
735
- * Extracted as a helper so it can be called both during live streaming
736
- * (per-chunk) and after replay completes (once, at done).
737
- */
738
- const flushActiveStreamToMessages = useCallback((activeMsg) => {
739
- setMessages((prevMessages) => {
740
- let existingIdx = prevMessages.findIndex((m) => m.id === activeMsg.messageId);
741
- if (existingIdx < 0 && activeMsg.continuation) {
742
- for (let i = prevMessages.length - 1; i >= 0; i--) if (prevMessages[i].role === "assistant") {
743
- existingIdx = i;
744
- break;
745
- }
746
- }
747
- const partialMessage = {
748
- id: existingIdx >= 0 ? prevMessages[existingIdx].id : activeMsg.messageId,
749
- role: "assistant",
750
- parts: [...activeMsg.parts],
751
- ...activeMsg.metadata != null && { metadata: activeMsg.metadata }
752
- };
753
- if (existingIdx >= 0) {
754
- const updated = [...prevMessages];
755
- updated[existingIdx] = partialMessage;
756
- return updated;
757
- }
758
- return [...prevMessages, partialMessage];
759
- });
760
- }, [setMessages]);
761
823
  useEffect(() => {
762
824
  const localResponseIds = localResponseMessageIdsRef.current;
763
825
  /**
@@ -776,6 +838,8 @@ function useAgentChat(options) {
776
838
  case MessageType.CF_AGENT_CHAT_CLEAR:
777
839
  localResponseIds.clear();
778
840
  protectedStreamingAssistantRef.current = null;
841
+ streamStateRef.current = broadcastTransition(streamStateRef.current, { type: "clear" }).state;
842
+ setIsServerStreaming(false);
779
843
  setMessages([]);
780
844
  break;
781
845
  case MessageType.CF_AGENT_CHAT_MESSAGES:
@@ -807,13 +871,11 @@ function useAgentChat(options) {
807
871
  if (!resume && !customTransport.isAwaitingResume()) return;
808
872
  if (customTransport.handleStreamResuming(data)) return;
809
873
  if (localRequestIdsRef.current.has(data.id)) return;
810
- activeStreamRef.current = null;
811
- activeStreamRef.current = {
812
- id: data.id,
813
- messageId: nanoid(),
814
- continuation: false,
815
- parts: []
816
- };
874
+ streamStateRef.current = broadcastTransition(streamStateRef.current, {
875
+ type: "resume-fallback",
876
+ streamId: data.id,
877
+ messageId: nanoid()
878
+ }).state;
817
879
  setIsServerStreaming(true);
818
880
  agentRef.current.send(JSON.stringify({
819
881
  type: MessageType.CF_AGENT_STREAM_RESUME_ACK,
@@ -833,51 +895,28 @@ function useAgentChat(options) {
833
895
  }
834
896
  return;
835
897
  }
836
- const isContinuation = data.continuation === true;
837
- if (!activeStreamRef.current || activeStreamRef.current.id !== data.id) {
838
- let messageId = nanoid();
839
- let existingParts = [];
840
- let existingMetadata;
841
- if (isContinuation) {
842
- const currentMessages = messagesRef.current;
843
- for (let i = currentMessages.length - 1; i >= 0; i--) if (currentMessages[i].role === "assistant") {
844
- messageId = currentMessages[i].id;
845
- existingParts = [...currentMessages[i].parts];
846
- if (currentMessages[i].metadata != null) existingMetadata = { ...currentMessages[i].metadata };
847
- break;
848
- }
849
- }
850
- activeStreamRef.current = {
851
- id: data.id,
852
- messageId,
853
- continuation: isContinuation,
854
- parts: existingParts,
855
- metadata: existingMetadata
856
- };
857
- setIsServerStreaming(true);
858
- }
859
- const activeMsg = activeStreamRef.current;
860
- const isReplay = data.replay === true;
898
+ let chunkData;
861
899
  if (data.body?.trim()) try {
862
- const chunkData = JSON.parse(data.body);
863
- const handled = applyChunkToParts(activeMsg.parts, chunkData);
900
+ chunkData = JSON.parse(data.body);
864
901
  if (typeof chunkData.type === "string" && chunkData.type.startsWith("data-") && onDataRef.current) onDataRef.current(chunkData);
865
- if (!handled && (chunkData.type === "start" || chunkData.type === "finish" || chunkData.type === "message-metadata")) {
866
- if (chunkData.messageId != null && chunkData.type === "start" && !isContinuation) activeMsg.messageId = chunkData.messageId;
867
- if (chunkData.messageMetadata != null) activeMsg.metadata = activeMsg.metadata ? {
868
- ...activeMsg.metadata,
869
- ...chunkData.messageMetadata
870
- } : { ...chunkData.messageMetadata };
871
- }
872
- if (!isReplay) flushActiveStreamToMessages(activeMsg);
873
902
  } catch (parseError) {
874
903
  console.warn("[useAgentChat] Failed to parse stream chunk:", parseError instanceof Error ? parseError.message : parseError, "body:", data.body?.slice(0, 100));
875
904
  }
876
- if (data.done || data.error) {
877
- if (isReplay && activeMsg) flushActiveStreamToMessages(activeMsg);
878
- activeStreamRef.current = null;
879
- setIsServerStreaming(false);
880
- } else if (data.replayComplete && activeMsg) flushActiveStreamToMessages(activeMsg);
905
+ const result = broadcastTransition(streamStateRef.current, {
906
+ type: "response",
907
+ streamId: data.id,
908
+ messageId: nanoid(),
909
+ chunkData,
910
+ done: data.done,
911
+ error: data.error,
912
+ replay: data.replay,
913
+ replayComplete: data.replayComplete,
914
+ continuation: data.continuation,
915
+ currentMessages: data.continuation ? messagesRef.current : void 0
916
+ });
917
+ streamStateRef.current = result.state;
918
+ if (result.messagesUpdate) setMessages(result.messagesUpdate);
919
+ setIsServerStreaming(result.isStreaming);
881
920
  break;
882
921
  }
883
922
  }
@@ -885,7 +924,7 @@ function useAgentChat(options) {
885
924
  agent.addEventListener("message", onAgentMessage);
886
925
  return () => {
887
926
  agent.removeEventListener("message", onAgentMessage);
888
- activeStreamRef.current = null;
927
+ streamStateRef.current = { status: "idle" };
889
928
  setIsServerStreaming(false);
890
929
  protectedStreamingAssistantRef.current = null;
891
930
  localResponseIds.clear();
@@ -894,7 +933,6 @@ function useAgentChat(options) {
894
933
  agent,
895
934
  setMessages,
896
935
  resume,
897
- flushActiveStreamToMessages,
898
936
  customTransport,
899
937
  preserveProtectedStreamingAssistant,
900
938
  restoreProtectedStreamingAssistant
@@ -1016,6 +1054,6 @@ function useAgentChat(options) {
1016
1054
  };
1017
1055
  }
1018
1056
  //#endregion
1019
- export { detectToolsRequiringConfirmation, extractClientToolSchemas, useAgentChat };
1057
+ export { detectToolsRequiringConfirmation, extractClientToolSchemas, getAgentMessages, getToolApproval, getToolCallId, getToolInput, getToolOutput, getToolPartState, useAgentChat };
1020
1058
 
1021
1059
  //# sourceMappingURL=react.js.map