@cloudflare/ai-chat 0.3.0 → 0.3.2
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/experimental/forever.d.ts +1 -1
- package/dist/index.d.ts +623 -9
- package/dist/index.js +221 -683
- package/dist/index.js.map +1 -1
- package/dist/react.d.ts +7 -16
- package/dist/react.js +160 -93
- package/dist/react.js.map +1 -1
- package/package.json +4 -4
- package/dist/index-BZiT3pOq.d.ts +0 -901
- package/dist/message-builder-BAgcFJMf.js +0 -244
- package/dist/message-builder-BAgcFJMf.js.map +0 -1
package/dist/react.d.ts
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
|
-
import {
|
|
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,7 @@ type ClientToolSchema = {
|
|
|
62
53
|
*/
|
|
63
54
|
declare function extractClientToolSchemas(
|
|
64
55
|
tools?: Record<string, AITool<unknown, unknown>>
|
|
65
|
-
): ClientToolSchema[] | undefined;
|
|
56
|
+
): ClientToolSchema$1[] | undefined;
|
|
66
57
|
type GetInitialMessagesOptions = {
|
|
67
58
|
agent: string;
|
|
68
59
|
name: string;
|
|
@@ -295,7 +286,7 @@ declare function useAgentChat<
|
|
|
295
286
|
//#endregion
|
|
296
287
|
export {
|
|
297
288
|
AITool,
|
|
298
|
-
ClientToolSchema,
|
|
289
|
+
type ClientToolSchema,
|
|
299
290
|
JSONSchemaType,
|
|
300
291
|
OnToolCallCallback,
|
|
301
292
|
PrepareSendMessagesRequestOptions,
|
package/dist/react.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { MessageType } from "./types.js";
|
|
2
|
-
import {
|
|
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
|
/**
|
|
@@ -15,6 +15,7 @@ var WebSocketChatTransport = class {
|
|
|
15
15
|
this._resumeResolver = null;
|
|
16
16
|
this._resumeNoneResolver = null;
|
|
17
17
|
this._expectToolContinuation = false;
|
|
18
|
+
this._abortToolContinuation = null;
|
|
18
19
|
this.agent = options.agent;
|
|
19
20
|
this.prepareBody = options.prepareBody;
|
|
20
21
|
this.activeRequestIds = options.activeRequestIds;
|
|
@@ -27,6 +28,13 @@ var WebSocketChatTransport = class {
|
|
|
27
28
|
this._expectToolContinuation = true;
|
|
28
29
|
}
|
|
29
30
|
/**
|
|
31
|
+
* Abort the active client-side tool continuation stream, if one is attached
|
|
32
|
+
* to a server request id.
|
|
33
|
+
*/
|
|
34
|
+
abortActiveToolContinuation() {
|
|
35
|
+
return this._abortToolContinuation?.() ?? false;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
30
38
|
* True when the transport is waiting for a resume handshake.
|
|
31
39
|
*/
|
|
32
40
|
isAwaitingResume() {
|
|
@@ -179,8 +187,13 @@ var WebSocketChatTransport = class {
|
|
|
179
187
|
const agent = this.agent;
|
|
180
188
|
const activeIds = this.activeRequestIds;
|
|
181
189
|
const streamController = new AbortController();
|
|
190
|
+
const abortError = /* @__PURE__ */ new Error("Aborted");
|
|
191
|
+
abortError.name = "AbortError";
|
|
182
192
|
let completed = false;
|
|
183
193
|
let requestId = null;
|
|
194
|
+
let readerController;
|
|
195
|
+
let onResumeRef = null;
|
|
196
|
+
let onResumeNoneRef = null;
|
|
184
197
|
const clearHandshakeResolvers = (resumeResolver, resumeNoneResolver) => {
|
|
185
198
|
if (resumeResolver === void 0 && resumeNoneResolver === void 0) {
|
|
186
199
|
this._resumeResolver = null;
|
|
@@ -190,19 +203,36 @@ var WebSocketChatTransport = class {
|
|
|
190
203
|
if (resumeResolver && this._resumeResolver === resumeResolver) this._resumeResolver = null;
|
|
191
204
|
if (resumeNoneResolver && this._resumeNoneResolver === resumeNoneResolver) this._resumeNoneResolver = null;
|
|
192
205
|
};
|
|
193
|
-
const finish = (action, resumeResolver, resumeNoneResolver) => {
|
|
206
|
+
const finish = (action, resumeResolver, resumeNoneResolver, keepRequestId = false) => {
|
|
194
207
|
if (completed) return;
|
|
195
208
|
completed = true;
|
|
209
|
+
this._abortToolContinuation = null;
|
|
196
210
|
clearHandshakeResolvers(resumeResolver, resumeNoneResolver);
|
|
197
211
|
try {
|
|
198
212
|
action();
|
|
199
213
|
} catch {}
|
|
200
|
-
if (requestId) activeIds?.delete(requestId);
|
|
214
|
+
if (requestId && !keepRequestId) activeIds?.delete(requestId);
|
|
201
215
|
streamController.abort();
|
|
202
216
|
};
|
|
217
|
+
this._abortToolContinuation = () => {
|
|
218
|
+
if (completed) return false;
|
|
219
|
+
if (requestId === null) {
|
|
220
|
+
finish(() => readerController.error(abortError), onResumeRef, onResumeNoneRef);
|
|
221
|
+
return true;
|
|
222
|
+
}
|
|
223
|
+
try {
|
|
224
|
+
agent.send(JSON.stringify({
|
|
225
|
+
type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL,
|
|
226
|
+
id: requestId
|
|
227
|
+
}));
|
|
228
|
+
} catch {}
|
|
229
|
+
finish(() => readerController.error(abortError), onResumeRef, onResumeNoneRef, true);
|
|
230
|
+
return true;
|
|
231
|
+
};
|
|
203
232
|
const transport = this;
|
|
204
233
|
return new ReadableStream({
|
|
205
234
|
start(controller) {
|
|
235
|
+
readerController = controller;
|
|
206
236
|
let timeout;
|
|
207
237
|
const onResumeNone = () => {
|
|
208
238
|
if (timeout) clearTimeout(timeout);
|
|
@@ -219,6 +249,8 @@ var WebSocketChatTransport = class {
|
|
|
219
249
|
id: requestId
|
|
220
250
|
}));
|
|
221
251
|
};
|
|
252
|
+
onResumeRef = onResume;
|
|
253
|
+
onResumeNoneRef = onResumeNone;
|
|
222
254
|
timeout = setTimeout(() => finish(() => controller.close(), onResume, onResumeNone), 5e3);
|
|
223
255
|
transport._resumeResolver = onResume;
|
|
224
256
|
transport._resumeNoneResolver = onResumeNone;
|
|
@@ -334,6 +366,25 @@ function extractClientToolSchemas(tools) {
|
|
|
334
366
|
* and thread name to prevent cross-agent collisions.
|
|
335
367
|
*/
|
|
336
368
|
const requestCache = /* @__PURE__ */ new Map();
|
|
369
|
+
function findLastAssistantMessage(messages) {
|
|
370
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
371
|
+
const message = messages[index];
|
|
372
|
+
if (message.role === "assistant") return {
|
|
373
|
+
index,
|
|
374
|
+
message
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
return null;
|
|
378
|
+
}
|
|
379
|
+
function moveMessageToEnd(messages, messageId) {
|
|
380
|
+
const idx = messages.findIndex((m) => m.id === messageId);
|
|
381
|
+
if (idx < 0 || idx === messages.length - 1) return messages;
|
|
382
|
+
const result = [...messages];
|
|
383
|
+
const [msg] = result.splice(idx, 1);
|
|
384
|
+
if (!msg) return messages;
|
|
385
|
+
result.push(msg);
|
|
386
|
+
return result;
|
|
387
|
+
}
|
|
337
388
|
/**
|
|
338
389
|
* React hook for building AI chat interfaces using an Agent
|
|
339
390
|
* @param options Chat options including the agent connection
|
|
@@ -457,7 +508,9 @@ function useAgentChat(options) {
|
|
|
457
508
|
id: initialMessagesCacheKey,
|
|
458
509
|
resume
|
|
459
510
|
});
|
|
460
|
-
const { messages: chatMessages, setMessages, addToolResult, addToolApprovalResponse, sendMessage, resumeStream } = useChatHelpers;
|
|
511
|
+
const { messages: chatMessages, setMessages, addToolResult, addToolApprovalResponse, sendMessage, resumeStream, status, stop } = useChatHelpers;
|
|
512
|
+
const statusRef = useRef(status);
|
|
513
|
+
statusRef.current = status;
|
|
461
514
|
const resumingToolContinuationRef = useRef(false);
|
|
462
515
|
const startToolContinuation = useCallback(() => {
|
|
463
516
|
if (!autoContinueAfterToolResult || resumingToolContinuationRef.current) return;
|
|
@@ -471,12 +524,65 @@ function useAgentChat(options) {
|
|
|
471
524
|
customTransport,
|
|
472
525
|
resumeStream
|
|
473
526
|
]);
|
|
527
|
+
const stopWithToolContinuationAbort = useCallback(async () => {
|
|
528
|
+
try {
|
|
529
|
+
await stop();
|
|
530
|
+
} finally {
|
|
531
|
+
customTransport.abortActiveToolContinuation();
|
|
532
|
+
}
|
|
533
|
+
}, [stop, customTransport]);
|
|
474
534
|
const processedToolCalls = useRef(/* @__PURE__ */ new Set());
|
|
475
535
|
const isResolvingToolsRef = useRef(false);
|
|
476
536
|
const [toolResolutionTrigger, setToolResolutionTrigger] = useState(0);
|
|
477
537
|
const [clientToolResults, setClientToolResults] = useState(/* @__PURE__ */ new Map());
|
|
478
538
|
const messagesRef = useRef(chatMessages);
|
|
479
539
|
messagesRef.current = chatMessages;
|
|
540
|
+
const localResponseMessageIdsRef = useRef(/* @__PURE__ */ new Map());
|
|
541
|
+
const protectedStreamingAssistantRef = useRef(null);
|
|
542
|
+
const preserveProtectedStreamingAssistant = useCallback((messages) => {
|
|
543
|
+
const protection = protectedStreamingAssistantRef.current;
|
|
544
|
+
if (!protection) return messages;
|
|
545
|
+
const protectedAssistant = messagesRef.current.find((message) => message.id === protection.assistantId) ?? messages.find((message) => message.id === protection.assistantId);
|
|
546
|
+
if (!protectedAssistant) return messages;
|
|
547
|
+
return [...messages.filter((message) => message.id !== protection.assistantId), protectedAssistant];
|
|
548
|
+
}, []);
|
|
549
|
+
const protectStreamingAssistantTail = useCallback(() => {
|
|
550
|
+
if (statusRef.current !== "streaming") return;
|
|
551
|
+
const assistantInfo = findLastAssistantMessage(messagesRef.current);
|
|
552
|
+
if (!assistantInfo) return;
|
|
553
|
+
if (protectedStreamingAssistantRef.current?.assistantId !== assistantInfo.message.id) protectedStreamingAssistantRef.current = {
|
|
554
|
+
assistantId: assistantInfo.message.id,
|
|
555
|
+
anchorMessageId: messagesRef.current[assistantInfo.index - 1]?.id ?? null
|
|
556
|
+
};
|
|
557
|
+
setMessages((prevMessages) => {
|
|
558
|
+
const protection = protectedStreamingAssistantRef.current;
|
|
559
|
+
if (!protection) return prevMessages;
|
|
560
|
+
return moveMessageToEnd(prevMessages, protection.assistantId);
|
|
561
|
+
});
|
|
562
|
+
}, [setMessages]);
|
|
563
|
+
const restoreProtectedStreamingAssistant = useCallback((assistantId) => {
|
|
564
|
+
const protection = protectedStreamingAssistantRef.current;
|
|
565
|
+
if (!protection || assistantId !== void 0 && protection.assistantId !== assistantId) return;
|
|
566
|
+
protectedStreamingAssistantRef.current = null;
|
|
567
|
+
setMessages((prevMessages) => {
|
|
568
|
+
const sourceIdx = prevMessages.findIndex((m) => m.id === protection.assistantId);
|
|
569
|
+
if (sourceIdx < 0) return prevMessages;
|
|
570
|
+
const result = [...prevMessages];
|
|
571
|
+
const [msg] = result.splice(sourceIdx, 1);
|
|
572
|
+
if (!msg) return prevMessages;
|
|
573
|
+
if (protection.anchorMessageId === null) result.unshift(msg);
|
|
574
|
+
else {
|
|
575
|
+
const anchorIdx = result.findIndex((m) => m.id === protection.anchorMessageId);
|
|
576
|
+
result.splice(anchorIdx >= 0 ? anchorIdx + 1 : sourceIdx, 0, msg);
|
|
577
|
+
}
|
|
578
|
+
return result;
|
|
579
|
+
});
|
|
580
|
+
}, [setMessages]);
|
|
581
|
+
const sendMessageWithStreamingProtection = useCallback(async (message, options) => {
|
|
582
|
+
const request = sendMessage(message, options);
|
|
583
|
+
if (message !== void 0 && !(typeof message === "object" && message !== null && "messageId" in message && message.messageId != null)) protectStreamingAssistantTail();
|
|
584
|
+
return request;
|
|
585
|
+
}, [sendMessage, protectStreamingAssistantTail]);
|
|
480
586
|
const lastMessage = chatMessages[chatMessages.length - 1];
|
|
481
587
|
const pendingConfirmations = (() => {
|
|
482
588
|
if (!lastMessage || lastMessage.role !== "assistant") return {
|
|
@@ -616,43 +722,10 @@ function useAgentChat(options) {
|
|
|
616
722
|
sendToolOutputToServer,
|
|
617
723
|
addToolResult
|
|
618
724
|
]);
|
|
619
|
-
|
|
620
|
-
* Contains the request ID, accumulated message parts, metadata, and a unique message ID.
|
|
621
|
-
* Used for both resumed streams and real-time broadcasts from other tabs.
|
|
622
|
-
* Metadata is captured from start/finish/message-metadata stream chunks
|
|
623
|
-
* so that it's included when the partial message is flushed to React state.
|
|
624
|
-
*/
|
|
625
|
-
const activeStreamRef = useRef(null);
|
|
725
|
+
const streamStateRef = useRef({ status: "idle" });
|
|
626
726
|
const [isServerStreaming, setIsServerStreaming] = useState(false);
|
|
627
|
-
/**
|
|
628
|
-
* Flush the active stream's accumulated parts into React state.
|
|
629
|
-
* Extracted as a helper so it can be called both during live streaming
|
|
630
|
-
* (per-chunk) and after replay completes (once, at done).
|
|
631
|
-
*/
|
|
632
|
-
const flushActiveStreamToMessages = useCallback((activeMsg) => {
|
|
633
|
-
setMessages((prevMessages) => {
|
|
634
|
-
let existingIdx = prevMessages.findIndex((m) => m.id === activeMsg.messageId);
|
|
635
|
-
if (existingIdx < 0 && activeMsg.continuation) {
|
|
636
|
-
for (let i = prevMessages.length - 1; i >= 0; i--) if (prevMessages[i].role === "assistant") {
|
|
637
|
-
existingIdx = i;
|
|
638
|
-
break;
|
|
639
|
-
}
|
|
640
|
-
}
|
|
641
|
-
const partialMessage = {
|
|
642
|
-
id: existingIdx >= 0 ? prevMessages[existingIdx].id : activeMsg.messageId,
|
|
643
|
-
role: "assistant",
|
|
644
|
-
parts: [...activeMsg.parts],
|
|
645
|
-
...activeMsg.metadata != null && { metadata: activeMsg.metadata }
|
|
646
|
-
};
|
|
647
|
-
if (existingIdx >= 0) {
|
|
648
|
-
const updated = [...prevMessages];
|
|
649
|
-
updated[existingIdx] = partialMessage;
|
|
650
|
-
return updated;
|
|
651
|
-
}
|
|
652
|
-
return [...prevMessages, partialMessage];
|
|
653
|
-
});
|
|
654
|
-
}, [setMessages]);
|
|
655
727
|
useEffect(() => {
|
|
728
|
+
const localResponseIds = localResponseMessageIdsRef.current;
|
|
656
729
|
/**
|
|
657
730
|
* Unified message handler that parses JSON once and dispatches based on type.
|
|
658
731
|
* Avoids duplicate parsing overhead from separate listeners.
|
|
@@ -667,10 +740,14 @@ function useAgentChat(options) {
|
|
|
667
740
|
}
|
|
668
741
|
switch (data.type) {
|
|
669
742
|
case MessageType.CF_AGENT_CHAT_CLEAR:
|
|
743
|
+
localResponseIds.clear();
|
|
744
|
+
protectedStreamingAssistantRef.current = null;
|
|
745
|
+
streamStateRef.current = broadcastTransition(streamStateRef.current, { type: "clear" }).state;
|
|
746
|
+
setIsServerStreaming(false);
|
|
670
747
|
setMessages([]);
|
|
671
748
|
break;
|
|
672
749
|
case MessageType.CF_AGENT_CHAT_MESSAGES:
|
|
673
|
-
setMessages(data.messages);
|
|
750
|
+
setMessages(preserveProtectedStreamingAssistant(data.messages));
|
|
674
751
|
break;
|
|
675
752
|
case MessageType.CF_AGENT_MESSAGE_UPDATED:
|
|
676
753
|
setMessages((prevMessages) => {
|
|
@@ -698,13 +775,11 @@ function useAgentChat(options) {
|
|
|
698
775
|
if (!resume && !customTransport.isAwaitingResume()) return;
|
|
699
776
|
if (customTransport.handleStreamResuming(data)) return;
|
|
700
777
|
if (localRequestIdsRef.current.has(data.id)) return;
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
messageId: nanoid()
|
|
705
|
-
|
|
706
|
-
parts: []
|
|
707
|
-
};
|
|
778
|
+
streamStateRef.current = broadcastTransition(streamStateRef.current, {
|
|
779
|
+
type: "resume-fallback",
|
|
780
|
+
streamId: data.id,
|
|
781
|
+
messageId: nanoid()
|
|
782
|
+
}).state;
|
|
708
783
|
setIsServerStreaming(true);
|
|
709
784
|
agentRef.current.send(JSON.stringify({
|
|
710
785
|
type: MessageType.CF_AGENT_STREAM_RESUME_ACK,
|
|
@@ -713,54 +788,39 @@ function useAgentChat(options) {
|
|
|
713
788
|
break;
|
|
714
789
|
case MessageType.CF_AGENT_USE_CHAT_RESPONSE: {
|
|
715
790
|
if (localRequestIdsRef.current.has(data.id)) {
|
|
716
|
-
if (data.
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
if (isContinuation) {
|
|
725
|
-
const currentMessages = messagesRef.current;
|
|
726
|
-
for (let i = currentMessages.length - 1; i >= 0; i--) if (currentMessages[i].role === "assistant") {
|
|
727
|
-
messageId = currentMessages[i].id;
|
|
728
|
-
existingParts = [...currentMessages[i].parts];
|
|
729
|
-
if (currentMessages[i].metadata != null) existingMetadata = { ...currentMessages[i].metadata };
|
|
730
|
-
break;
|
|
731
|
-
}
|
|
791
|
+
if (data.body?.trim()) try {
|
|
792
|
+
const chunkData = JSON.parse(data.body);
|
|
793
|
+
if (chunkData.type === "start" && typeof chunkData.messageId === "string") localResponseIds.set(data.id, chunkData.messageId);
|
|
794
|
+
} catch {}
|
|
795
|
+
if (data.done) {
|
|
796
|
+
restoreProtectedStreamingAssistant(localResponseIds.get(data.id));
|
|
797
|
+
localResponseIds.delete(data.id);
|
|
798
|
+
localRequestIdsRef.current.delete(data.id);
|
|
732
799
|
}
|
|
733
|
-
|
|
734
|
-
id: data.id,
|
|
735
|
-
messageId,
|
|
736
|
-
continuation: isContinuation,
|
|
737
|
-
parts: existingParts,
|
|
738
|
-
metadata: existingMetadata
|
|
739
|
-
};
|
|
740
|
-
setIsServerStreaming(true);
|
|
800
|
+
return;
|
|
741
801
|
}
|
|
742
|
-
|
|
743
|
-
const isReplay = data.replay === true;
|
|
802
|
+
let chunkData;
|
|
744
803
|
if (data.body?.trim()) try {
|
|
745
|
-
|
|
746
|
-
const handled = applyChunkToParts(activeMsg.parts, chunkData);
|
|
804
|
+
chunkData = JSON.parse(data.body);
|
|
747
805
|
if (typeof chunkData.type === "string" && chunkData.type.startsWith("data-") && onDataRef.current) onDataRef.current(chunkData);
|
|
748
|
-
if (!handled && (chunkData.type === "start" || chunkData.type === "finish" || chunkData.type === "message-metadata")) {
|
|
749
|
-
if (chunkData.messageId != null && chunkData.type === "start" && !isContinuation) activeMsg.messageId = chunkData.messageId;
|
|
750
|
-
if (chunkData.messageMetadata != null) activeMsg.metadata = activeMsg.metadata ? {
|
|
751
|
-
...activeMsg.metadata,
|
|
752
|
-
...chunkData.messageMetadata
|
|
753
|
-
} : { ...chunkData.messageMetadata };
|
|
754
|
-
}
|
|
755
|
-
if (!isReplay) flushActiveStreamToMessages(activeMsg);
|
|
756
806
|
} catch (parseError) {
|
|
757
807
|
console.warn("[useAgentChat] Failed to parse stream chunk:", parseError instanceof Error ? parseError.message : parseError, "body:", data.body?.slice(0, 100));
|
|
758
808
|
}
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
809
|
+
const result = broadcastTransition(streamStateRef.current, {
|
|
810
|
+
type: "response",
|
|
811
|
+
streamId: data.id,
|
|
812
|
+
messageId: nanoid(),
|
|
813
|
+
chunkData,
|
|
814
|
+
done: data.done,
|
|
815
|
+
error: data.error,
|
|
816
|
+
replay: data.replay,
|
|
817
|
+
replayComplete: data.replayComplete,
|
|
818
|
+
continuation: data.continuation,
|
|
819
|
+
currentMessages: data.continuation ? messagesRef.current : void 0
|
|
820
|
+
});
|
|
821
|
+
streamStateRef.current = result.state;
|
|
822
|
+
if (result.messagesUpdate) setMessages(result.messagesUpdate);
|
|
823
|
+
setIsServerStreaming(result.isStreaming);
|
|
764
824
|
break;
|
|
765
825
|
}
|
|
766
826
|
}
|
|
@@ -768,15 +828,18 @@ function useAgentChat(options) {
|
|
|
768
828
|
agent.addEventListener("message", onAgentMessage);
|
|
769
829
|
return () => {
|
|
770
830
|
agent.removeEventListener("message", onAgentMessage);
|
|
771
|
-
|
|
831
|
+
streamStateRef.current = { status: "idle" };
|
|
772
832
|
setIsServerStreaming(false);
|
|
833
|
+
protectedStreamingAssistantRef.current = null;
|
|
834
|
+
localResponseIds.clear();
|
|
773
835
|
};
|
|
774
836
|
}, [
|
|
775
837
|
agent,
|
|
776
838
|
setMessages,
|
|
777
839
|
resume,
|
|
778
|
-
|
|
779
|
-
|
|
840
|
+
customTransport,
|
|
841
|
+
preserveProtectedStreamingAssistant,
|
|
842
|
+
restoreProtectedStreamingAssistant
|
|
780
843
|
]);
|
|
781
844
|
const addToolResultAndSendMessage = async (args) => {
|
|
782
845
|
const { toolCallId } = args;
|
|
@@ -862,12 +925,14 @@ function useAgentChat(options) {
|
|
|
862
925
|
output: opts.state === "output-error" ? opts.errorText ?? "Tool execution denied by user" : opts.output
|
|
863
926
|
});
|
|
864
927
|
}, [sendToolOutputToServer, addToolResult]);
|
|
865
|
-
const isStreaming =
|
|
928
|
+
const isStreaming = status === "streaming" || isServerStreaming;
|
|
866
929
|
return {
|
|
867
930
|
...useChatHelpers,
|
|
868
931
|
messages: messagesWithToolResults,
|
|
869
932
|
isServerStreaming,
|
|
870
933
|
isStreaming,
|
|
934
|
+
sendMessage: sendMessageWithStreamingProtection,
|
|
935
|
+
stop: stopWithToolContinuationAbort,
|
|
871
936
|
addToolOutput,
|
|
872
937
|
addToolResult: addToolResultAndSendMessage,
|
|
873
938
|
addToolApprovalResponse: addToolApprovalResponseAndNotifyServer,
|
|
@@ -876,6 +941,8 @@ function useAgentChat(options) {
|
|
|
876
941
|
setClientToolResults(/* @__PURE__ */ new Map());
|
|
877
942
|
resumingToolContinuationRef.current = false;
|
|
878
943
|
processedToolCalls.current.clear();
|
|
944
|
+
localResponseMessageIdsRef.current.clear();
|
|
945
|
+
protectedStreamingAssistantRef.current = null;
|
|
879
946
|
agent.send(JSON.stringify({ type: MessageType.CF_AGENT_CHAT_CLEAR }));
|
|
880
947
|
},
|
|
881
948
|
setMessages: (messagesOrUpdater) => {
|