@cloudflare/ai-chat 0.4.5 → 0.5.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/README.md +12 -12
- package/dist/index.d.ts +48 -75
- package/dist/index.js +57 -34
- package/dist/index.js.map +1 -1
- package/dist/react.d.ts +1 -1
- package/dist/react.js +69 -33
- package/dist/react.js.map +1 -1
- package/dist/types.d.ts +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +2 -2
package/dist/react.d.ts
CHANGED
|
@@ -157,7 +157,7 @@ declare function getAgentMessages<M extends UIMessage = UIMessage>(
|
|
|
157
157
|
type GetInitialMessagesOptions = {
|
|
158
158
|
agent: string;
|
|
159
159
|
name: string;
|
|
160
|
-
url
|
|
160
|
+
url?: string;
|
|
161
161
|
};
|
|
162
162
|
type UseChatParams<M extends UIMessage = UIMessage> = ChatInit<M> &
|
|
163
163
|
UseChatOptions<M>;
|
package/dist/react.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import "./types.js";
|
|
2
2
|
import { broadcastTransition } from "agents/chat";
|
|
3
3
|
import { nanoid } from "nanoid";
|
|
4
4
|
import { useChat } from "@ai-sdk/react";
|
|
@@ -99,7 +99,7 @@ var WebSocketChatTransport = class {
|
|
|
99
99
|
try {
|
|
100
100
|
agent.send(JSON.stringify({
|
|
101
101
|
id: requestId,
|
|
102
|
-
type:
|
|
102
|
+
type: "cf_agent_chat_request_cancel"
|
|
103
103
|
}));
|
|
104
104
|
} catch {}
|
|
105
105
|
finish(() => streamController.error(abortError), true);
|
|
@@ -111,7 +111,7 @@ var WebSocketChatTransport = class {
|
|
|
111
111
|
const onMessage = (event) => {
|
|
112
112
|
try {
|
|
113
113
|
const data = JSON.parse(event.data);
|
|
114
|
-
if (data.type !==
|
|
114
|
+
if (data.type !== "cf_agent_use_chat_response") return;
|
|
115
115
|
if (data.id !== requestId) return;
|
|
116
116
|
if (data.error) {
|
|
117
117
|
finish(() => controller.error(new Error(data.body || "Stream error")));
|
|
@@ -140,7 +140,7 @@ var WebSocketChatTransport = class {
|
|
|
140
140
|
method: "POST",
|
|
141
141
|
body: bodyPayload
|
|
142
142
|
},
|
|
143
|
-
type:
|
|
143
|
+
type: "cf_agent_use_chat_request"
|
|
144
144
|
}));
|
|
145
145
|
return stream;
|
|
146
146
|
}
|
|
@@ -166,13 +166,13 @@ var WebSocketChatTransport = class {
|
|
|
166
166
|
const requestId = data.id;
|
|
167
167
|
activeIds?.add(requestId);
|
|
168
168
|
this.agent.send(JSON.stringify({
|
|
169
|
-
type:
|
|
169
|
+
type: "cf_agent_stream_resume_ack",
|
|
170
170
|
id: requestId
|
|
171
171
|
}));
|
|
172
172
|
done(this._createResumeStream(requestId));
|
|
173
173
|
};
|
|
174
174
|
try {
|
|
175
|
-
this.agent.send(JSON.stringify({ type:
|
|
175
|
+
this.agent.send(JSON.stringify({ type: "cf_agent_stream_resume_request" }));
|
|
176
176
|
} catch {}
|
|
177
177
|
timeout = setTimeout(() => done(null), 5e3);
|
|
178
178
|
});
|
|
@@ -222,7 +222,7 @@ var WebSocketChatTransport = class {
|
|
|
222
222
|
}
|
|
223
223
|
try {
|
|
224
224
|
agent.send(JSON.stringify({
|
|
225
|
-
type:
|
|
225
|
+
type: "cf_agent_chat_request_cancel",
|
|
226
226
|
id: requestId
|
|
227
227
|
}));
|
|
228
228
|
} catch {}
|
|
@@ -245,7 +245,7 @@ var WebSocketChatTransport = class {
|
|
|
245
245
|
clearHandshakeResolvers(onResume, onResumeNone);
|
|
246
246
|
if (timeout) clearTimeout(timeout);
|
|
247
247
|
agent.send(JSON.stringify({
|
|
248
|
-
type:
|
|
248
|
+
type: "cf_agent_stream_resume_ack",
|
|
249
249
|
id: requestId
|
|
250
250
|
}));
|
|
251
251
|
};
|
|
@@ -257,7 +257,7 @@ var WebSocketChatTransport = class {
|
|
|
257
257
|
const onMessage = (event) => {
|
|
258
258
|
try {
|
|
259
259
|
const data = JSON.parse(event.data);
|
|
260
|
-
if (data.type !==
|
|
260
|
+
if (data.type !== "cf_agent_use_chat_response" || requestId == null || data.id !== requestId) return;
|
|
261
261
|
if (data.error) {
|
|
262
262
|
finish(() => controller.error(new Error(data.body || "Stream error")), onResume, onResumeNone);
|
|
263
263
|
return;
|
|
@@ -271,7 +271,7 @@ var WebSocketChatTransport = class {
|
|
|
271
271
|
};
|
|
272
272
|
agent.addEventListener("message", onMessage, { signal: streamController.signal });
|
|
273
273
|
try {
|
|
274
|
-
agent.send(JSON.stringify({ type:
|
|
274
|
+
agent.send(JSON.stringify({ type: "cf_agent_stream_resume_request" }));
|
|
275
275
|
} catch {
|
|
276
276
|
finish(() => controller.close());
|
|
277
277
|
}
|
|
@@ -304,7 +304,7 @@ var WebSocketChatTransport = class {
|
|
|
304
304
|
const onMessage = (event) => {
|
|
305
305
|
try {
|
|
306
306
|
const data = JSON.parse(event.data);
|
|
307
|
-
if (data.type !==
|
|
307
|
+
if (data.type !== "cf_agent_use_chat_response") return;
|
|
308
308
|
if (data.id !== requestId) return;
|
|
309
309
|
if (data.error) {
|
|
310
310
|
finish(() => controller.error(new Error(data.body || "Stream error")));
|
|
@@ -513,13 +513,23 @@ function useAgentChat(options) {
|
|
|
513
513
|
onToolCallRef.current = onToolCall;
|
|
514
514
|
const onDataRef = useRef(onData);
|
|
515
515
|
onDataRef.current = onData;
|
|
516
|
-
const
|
|
517
|
-
agentUrl
|
|
518
|
-
|
|
519
|
-
const
|
|
516
|
+
const rawHttpUrl = agent.getHttpUrl();
|
|
517
|
+
const agentUrl = rawHttpUrl ? new URL(rawHttpUrl) : null;
|
|
518
|
+
if (agentUrl) agentUrl.searchParams.delete("_pk");
|
|
519
|
+
const agentUrlString = agentUrl?.toString() ?? null;
|
|
520
|
+
const agentIdentityKey = `${agent.agent ?? ""}|${agent.name ?? ""}`;
|
|
521
|
+
const resolvedInitialMessagesCacheKey = agentUrl ? `${agentUrl.origin}${agentUrl.pathname}|${agentIdentityKey}` : null;
|
|
522
|
+
const initialMessagesCacheKey = agentIdentityKey;
|
|
523
|
+
const stableChatIdRef = useRef(null);
|
|
524
|
+
const previousChatIdentityKeyRef = useRef(null);
|
|
525
|
+
const fallbackChatId = agentIdentityKey;
|
|
526
|
+
if (stableChatIdRef.current === null || previousChatIdentityKeyRef.current !== agentIdentityKey) stableChatIdRef.current = resolvedInitialMessagesCacheKey ?? fallbackChatId;
|
|
527
|
+
else if (resolvedInitialMessagesCacheKey && stableChatIdRef.current !== fallbackChatId && stableChatIdRef.current !== resolvedInitialMessagesCacheKey) stableChatIdRef.current = resolvedInitialMessagesCacheKey;
|
|
528
|
+
previousChatIdentityKeyRef.current = agentIdentityKey;
|
|
520
529
|
const agentRef = useRef(agent);
|
|
521
530
|
agentRef.current = agent;
|
|
522
531
|
async function defaultGetInitialMessagesFetch({ url }) {
|
|
532
|
+
if (!url) return [];
|
|
523
533
|
const getMessagesUrl = new URL(url);
|
|
524
534
|
getMessagesUrl.pathname += "/get-messages";
|
|
525
535
|
const response = await fetch(getMessagesUrl.toString(), {
|
|
@@ -546,10 +556,10 @@ function useAgentChat(options) {
|
|
|
546
556
|
requestCache.set(cacheKey, promise);
|
|
547
557
|
return promise;
|
|
548
558
|
}
|
|
549
|
-
const initialMessagesPromise = getInitialMessages === null ? null : doGetInitialMessages({
|
|
559
|
+
const initialMessagesPromise = !(getInitialMessages === null ? false : getInitialMessages ? true : !!agentUrlString) ? null : doGetInitialMessages({
|
|
550
560
|
agent: agent.agent,
|
|
551
561
|
name: agent.name,
|
|
552
|
-
url: agentUrlString
|
|
562
|
+
url: agentUrlString ?? void 0
|
|
553
563
|
}, initialMessagesCacheKey);
|
|
554
564
|
const initialMessages = initialMessagesPromise ? use(initialMessagesPromise) : optionsInitialMessages ?? [];
|
|
555
565
|
useEffect(() => {
|
|
@@ -601,7 +611,7 @@ function useAgentChat(options) {
|
|
|
601
611
|
onData,
|
|
602
612
|
messages: initialMessages,
|
|
603
613
|
transport: customTransport,
|
|
604
|
-
id:
|
|
614
|
+
id: stableChatIdRef.current,
|
|
605
615
|
resume
|
|
606
616
|
});
|
|
607
617
|
const { messages: chatMessages, setMessages, addToolResult, addToolApprovalResponse, sendMessage, resumeStream, status, stop } = useChatHelpers;
|
|
@@ -633,13 +643,35 @@ function useAgentChat(options) {
|
|
|
633
643
|
const [clientToolResults, setClientToolResults] = useState(/* @__PURE__ */ new Map());
|
|
634
644
|
const messagesRef = useRef(chatMessages);
|
|
635
645
|
messagesRef.current = chatMessages;
|
|
646
|
+
const initialMessagesRef = useRef(initialMessages);
|
|
647
|
+
initialMessagesRef.current = initialMessages;
|
|
648
|
+
const seededInitialMessagesKeyRef = useRef(null);
|
|
649
|
+
const markInitialMessagesSeeded = useCallback(() => {
|
|
650
|
+
seededInitialMessagesKeyRef.current = initialMessagesCacheKey;
|
|
651
|
+
}, [initialMessagesCacheKey]);
|
|
652
|
+
useEffect(() => {
|
|
653
|
+
if (!initialMessagesPromise) return;
|
|
654
|
+
if (seededInitialMessagesKeyRef.current === initialMessagesCacheKey) return;
|
|
655
|
+
if (chatMessages.length > 0) {
|
|
656
|
+
markInitialMessagesSeeded();
|
|
657
|
+
return;
|
|
658
|
+
}
|
|
659
|
+
markInitialMessagesSeeded();
|
|
660
|
+
setMessages(initialMessagesRef.current);
|
|
661
|
+
}, [
|
|
662
|
+
chatMessages.length,
|
|
663
|
+
initialMessagesCacheKey,
|
|
664
|
+
initialMessagesPromise,
|
|
665
|
+
markInitialMessagesSeeded,
|
|
666
|
+
setMessages
|
|
667
|
+
]);
|
|
636
668
|
const localResponseMessageIdsRef = useRef(/* @__PURE__ */ new Map());
|
|
637
669
|
const protectedStreamingAssistantRef = useRef(null);
|
|
638
670
|
const preserveProtectedStreamingAssistant = useCallback((messages) => {
|
|
639
671
|
const protection = protectedStreamingAssistantRef.current;
|
|
640
|
-
if (!protection) return messages;
|
|
672
|
+
if (!protection) return [...messages];
|
|
641
673
|
const protectedAssistant = messagesRef.current.find((message) => message.id === protection.assistantId) ?? messages.find((message) => message.id === protection.assistantId);
|
|
642
|
-
if (!protectedAssistant) return messages;
|
|
674
|
+
if (!protectedAssistant) return [...messages];
|
|
643
675
|
return [...messages.filter((message) => message.id !== protection.assistantId), protectedAssistant];
|
|
644
676
|
}, []);
|
|
645
677
|
const protectStreamingAssistantTail = useCallback(() => {
|
|
@@ -727,7 +759,7 @@ function useAgentChat(options) {
|
|
|
727
759
|
if (toolResults.length > 0) {
|
|
728
760
|
const clientToolSchemas = extractClientToolSchemas(currentTools);
|
|
729
761
|
for (const result of toolResults) agentRef.current.send(JSON.stringify({
|
|
730
|
-
type:
|
|
762
|
+
type: "cf_agent_tool_result",
|
|
731
763
|
toolCallId: result.toolCallId,
|
|
732
764
|
toolName: result.toolName,
|
|
733
765
|
output: result.output,
|
|
@@ -765,7 +797,7 @@ function useAgentChat(options) {
|
|
|
765
797
|
const sendToolOutputToServer = useCallback((toolCallId, toolName, output, state, errorText) => {
|
|
766
798
|
const shouldAutoContinue = state === "output-error" ? false : autoContinueAfterToolResult;
|
|
767
799
|
agentRef.current.send(JSON.stringify({
|
|
768
|
-
type:
|
|
800
|
+
type: "cf_agent_tool_result",
|
|
769
801
|
toolCallId,
|
|
770
802
|
toolName,
|
|
771
803
|
output,
|
|
@@ -779,7 +811,7 @@ function useAgentChat(options) {
|
|
|
779
811
|
}, [autoContinueAfterToolResult, startToolContinuation]);
|
|
780
812
|
const sendToolApprovalToServer = useCallback((toolCallId, approved) => {
|
|
781
813
|
agentRef.current.send(JSON.stringify({
|
|
782
|
-
type:
|
|
814
|
+
type: "cf_agent_tool_approval",
|
|
783
815
|
toolCallId,
|
|
784
816
|
approved,
|
|
785
817
|
autoContinue: autoContinueAfterToolResult
|
|
@@ -835,17 +867,18 @@ function useAgentChat(options) {
|
|
|
835
867
|
return;
|
|
836
868
|
}
|
|
837
869
|
switch (data.type) {
|
|
838
|
-
case
|
|
870
|
+
case "cf_agent_chat_clear":
|
|
839
871
|
localResponseIds.clear();
|
|
840
872
|
protectedStreamingAssistantRef.current = null;
|
|
841
873
|
streamStateRef.current = broadcastTransition(streamStateRef.current, { type: "clear" }).state;
|
|
842
874
|
setIsServerStreaming(false);
|
|
875
|
+
markInitialMessagesSeeded();
|
|
843
876
|
setMessages([]);
|
|
844
877
|
break;
|
|
845
|
-
case
|
|
878
|
+
case "cf_agent_chat_messages":
|
|
846
879
|
setMessages(preserveProtectedStreamingAssistant(data.messages));
|
|
847
880
|
break;
|
|
848
|
-
case
|
|
881
|
+
case "cf_agent_message_updated":
|
|
849
882
|
setMessages((prevMessages) => {
|
|
850
883
|
const updatedMessage = data.message;
|
|
851
884
|
let idx = prevMessages.findIndex((m) => m.id === updatedMessage.id);
|
|
@@ -864,10 +897,10 @@ function useAgentChat(options) {
|
|
|
864
897
|
return prevMessages;
|
|
865
898
|
});
|
|
866
899
|
break;
|
|
867
|
-
case
|
|
900
|
+
case "cf_agent_stream_resume_none":
|
|
868
901
|
customTransport.handleStreamResumeNone();
|
|
869
902
|
break;
|
|
870
|
-
case
|
|
903
|
+
case "cf_agent_stream_resuming":
|
|
871
904
|
if (!resume && !customTransport.isAwaitingResume()) return;
|
|
872
905
|
if (customTransport.handleStreamResuming(data)) return;
|
|
873
906
|
if (localRequestIdsRef.current.has(data.id)) return;
|
|
@@ -878,11 +911,11 @@ function useAgentChat(options) {
|
|
|
878
911
|
}).state;
|
|
879
912
|
setIsServerStreaming(true);
|
|
880
913
|
agentRef.current.send(JSON.stringify({
|
|
881
|
-
type:
|
|
914
|
+
type: "cf_agent_stream_resume_ack",
|
|
882
915
|
id: data.id
|
|
883
916
|
}));
|
|
884
917
|
break;
|
|
885
|
-
case
|
|
918
|
+
case "cf_agent_use_chat_response": {
|
|
886
919
|
if (localRequestIdsRef.current.has(data.id)) {
|
|
887
920
|
if (data.body?.trim()) try {
|
|
888
921
|
const chunkData = JSON.parse(data.body);
|
|
@@ -934,6 +967,7 @@ function useAgentChat(options) {
|
|
|
934
967
|
setMessages,
|
|
935
968
|
resume,
|
|
936
969
|
customTransport,
|
|
970
|
+
markInitialMessagesSeeded,
|
|
937
971
|
preserveProtectedStreamingAssistant,
|
|
938
972
|
restoreProtectedStreamingAssistant
|
|
939
973
|
]);
|
|
@@ -942,7 +976,7 @@ function useAgentChat(options) {
|
|
|
942
976
|
const toolName = "tool" in args ? args.tool : "";
|
|
943
977
|
const output = "output" in args ? args.output : void 0;
|
|
944
978
|
agentRef.current.send(JSON.stringify({
|
|
945
|
-
type:
|
|
979
|
+
type: "cf_agent_tool_result",
|
|
946
980
|
toolCallId,
|
|
947
981
|
toolName,
|
|
948
982
|
output,
|
|
@@ -1033,22 +1067,24 @@ function useAgentChat(options) {
|
|
|
1033
1067
|
addToolResult: addToolResultAndSendMessage,
|
|
1034
1068
|
addToolApprovalResponse: addToolApprovalResponseAndNotifyServer,
|
|
1035
1069
|
clearHistory: () => {
|
|
1070
|
+
markInitialMessagesSeeded();
|
|
1036
1071
|
setMessages([]);
|
|
1037
1072
|
setClientToolResults(/* @__PURE__ */ new Map());
|
|
1038
1073
|
resumingToolContinuationRef.current = false;
|
|
1039
1074
|
processedToolCalls.current.clear();
|
|
1040
1075
|
localResponseMessageIdsRef.current.clear();
|
|
1041
1076
|
protectedStreamingAssistantRef.current = null;
|
|
1042
|
-
agent.send(JSON.stringify({ type:
|
|
1077
|
+
agent.send(JSON.stringify({ type: "cf_agent_chat_clear" }));
|
|
1043
1078
|
},
|
|
1044
1079
|
setMessages: (messagesOrUpdater) => {
|
|
1045
1080
|
let resolvedMessages;
|
|
1046
1081
|
if (typeof messagesOrUpdater === "function") resolvedMessages = messagesOrUpdater(messagesRef.current);
|
|
1047
1082
|
else resolvedMessages = messagesOrUpdater;
|
|
1083
|
+
if (resolvedMessages.length === 0) markInitialMessagesSeeded();
|
|
1048
1084
|
setMessages(resolvedMessages);
|
|
1049
1085
|
agent.send(JSON.stringify({
|
|
1050
1086
|
messages: resolvedMessages,
|
|
1051
|
-
type:
|
|
1087
|
+
type: "cf_agent_chat_messages"
|
|
1052
1088
|
}));
|
|
1053
1089
|
}
|
|
1054
1090
|
};
|