@cloudflare/ai-chat 0.1.9 → 0.2.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.js CHANGED
@@ -14,11 +14,25 @@ var WebSocketChatTransport = class {
14
14
  constructor(options) {
15
15
  this._resumeResolver = null;
16
16
  this._resumeNoneResolver = null;
17
+ this._expectToolContinuation = false;
17
18
  this.agent = options.agent;
18
19
  this.prepareBody = options.prepareBody;
19
20
  this.activeRequestIds = options.activeRequestIds;
20
21
  }
21
22
  /**
23
+ * Mark that the next reconnectToStream() call should attach to a
24
+ * server-initiated tool continuation rather than a page-load resume.
25
+ */
26
+ expectToolContinuation() {
27
+ this._expectToolContinuation = true;
28
+ }
29
+ /**
30
+ * True when the transport is waiting for a resume handshake.
31
+ */
32
+ isAwaitingResume() {
33
+ return this._resumeResolver !== null || this._resumeNoneResolver !== null;
34
+ }
35
+ /**
22
36
  * Called by onAgentMessage when it receives CF_AGENT_STREAM_RESUMING.
23
37
  * If reconnectToStream is waiting, this handles the resume handshake
24
38
  * (ACK + stream creation) and returns true. Otherwise returns false
@@ -61,13 +75,13 @@ var WebSocketChatTransport = class {
61
75
  this.activeRequestIds?.add(requestId);
62
76
  const agent = this.agent;
63
77
  const activeIds = this.activeRequestIds;
64
- const finish = (action) => {
78
+ const finish = (action, keepId = false) => {
65
79
  if (completed) return;
66
80
  completed = true;
67
81
  try {
68
82
  action();
69
83
  } catch {}
70
- activeIds?.delete(requestId);
84
+ if (!keepId) activeIds?.delete(requestId);
71
85
  abortController.abort();
72
86
  };
73
87
  const abortError = /* @__PURE__ */ new Error("Aborted");
@@ -80,7 +94,7 @@ var WebSocketChatTransport = class {
80
94
  type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL
81
95
  }));
82
96
  } catch {}
83
- finish(() => streamController.error(abortError));
97
+ finish(() => streamController.error(abortError), true);
84
98
  };
85
99
  let streamController;
86
100
  const stream = new ReadableStream({
@@ -123,6 +137,10 @@ var WebSocketChatTransport = class {
123
137
  return stream;
124
138
  }
125
139
  async reconnectToStream(_options) {
140
+ if (this._expectToolContinuation) {
141
+ this._expectToolContinuation = false;
142
+ return this._createToolContinuationStream();
143
+ }
126
144
  const activeIds = this.activeRequestIds;
127
145
  return new Promise((resolve) => {
128
146
  let resolved = false;
@@ -152,6 +170,86 @@ var WebSocketChatTransport = class {
152
170
  });
153
171
  }
154
172
  /**
173
+ * Creates a deferred ReadableStream for client-side tool continuations.
174
+ * The stream is returned immediately so AI SDK status becomes "submitted"
175
+ * right after addToolOutput()/addToolApprovalResponse(), then it waits for
176
+ * the server to announce the continuation via STREAM_RESUMING.
177
+ */
178
+ _createToolContinuationStream() {
179
+ const agent = this.agent;
180
+ const activeIds = this.activeRequestIds;
181
+ const streamController = new AbortController();
182
+ let completed = false;
183
+ let requestId = null;
184
+ const clearHandshakeResolvers = (resumeResolver, resumeNoneResolver) => {
185
+ if (resumeResolver === void 0 && resumeNoneResolver === void 0) {
186
+ this._resumeResolver = null;
187
+ this._resumeNoneResolver = null;
188
+ return;
189
+ }
190
+ if (resumeResolver && this._resumeResolver === resumeResolver) this._resumeResolver = null;
191
+ if (resumeNoneResolver && this._resumeNoneResolver === resumeNoneResolver) this._resumeNoneResolver = null;
192
+ };
193
+ const finish = (action, resumeResolver, resumeNoneResolver) => {
194
+ if (completed) return;
195
+ completed = true;
196
+ clearHandshakeResolvers(resumeResolver, resumeNoneResolver);
197
+ try {
198
+ action();
199
+ } catch {}
200
+ if (requestId) activeIds?.delete(requestId);
201
+ streamController.abort();
202
+ };
203
+ const transport = this;
204
+ return new ReadableStream({
205
+ start(controller) {
206
+ let timeout;
207
+ const onResumeNone = () => {
208
+ if (timeout) clearTimeout(timeout);
209
+ finish(() => controller.close(), onResume, onResumeNone);
210
+ };
211
+ const onResume = (data) => {
212
+ if (requestId) return;
213
+ requestId = data.id;
214
+ activeIds?.add(requestId);
215
+ clearHandshakeResolvers(onResume, onResumeNone);
216
+ if (timeout) clearTimeout(timeout);
217
+ agent.send(JSON.stringify({
218
+ type: MessageType.CF_AGENT_STREAM_RESUME_ACK,
219
+ id: requestId
220
+ }));
221
+ };
222
+ timeout = setTimeout(() => finish(() => controller.close(), onResume, onResumeNone), 5e3);
223
+ transport._resumeResolver = onResume;
224
+ transport._resumeNoneResolver = onResumeNone;
225
+ const onMessage = (event) => {
226
+ try {
227
+ const data = JSON.parse(event.data);
228
+ if (data.type !== MessageType.CF_AGENT_USE_CHAT_RESPONSE || requestId == null || data.id !== requestId) return;
229
+ if (data.error) {
230
+ finish(() => controller.error(new Error(data.body || "Stream error")), onResume, onResumeNone);
231
+ return;
232
+ }
233
+ if (data.body?.trim()) try {
234
+ const chunk = JSON.parse(data.body);
235
+ controller.enqueue(chunk);
236
+ } catch {}
237
+ if (data.done) finish(() => controller.close(), onResume, onResumeNone);
238
+ } catch {}
239
+ };
240
+ agent.addEventListener("message", onMessage, { signal: streamController.signal });
241
+ try {
242
+ agent.send(JSON.stringify({ type: MessageType.CF_AGENT_STREAM_RESUME_REQUEST }));
243
+ } catch {
244
+ finish(() => controller.close());
245
+ }
246
+ },
247
+ cancel() {
248
+ finish(() => {});
249
+ }
250
+ });
251
+ }
252
+ /**
155
253
  * Creates a ReadableStream that receives resumed stream chunks
156
254
  * and forwards them to useChat as UIMessageChunk objects.
157
255
  */
@@ -359,7 +457,20 @@ function useAgentChat(options) {
359
457
  id: initialMessagesCacheKey,
360
458
  resume
361
459
  });
362
- const { messages: chatMessages, setMessages, addToolResult, addToolApprovalResponse, sendMessage } = useChatHelpers;
460
+ const { messages: chatMessages, setMessages, addToolResult, addToolApprovalResponse, sendMessage, resumeStream } = useChatHelpers;
461
+ const resumingToolContinuationRef = useRef(false);
462
+ const startToolContinuation = useCallback(() => {
463
+ if (!autoContinueAfterToolResult || resumingToolContinuationRef.current) return;
464
+ resumingToolContinuationRef.current = true;
465
+ customTransport.expectToolContinuation();
466
+ resumeStream().finally(() => {
467
+ resumingToolContinuationRef.current = false;
468
+ });
469
+ }, [
470
+ autoContinueAfterToolResult,
471
+ customTransport,
472
+ resumeStream
473
+ ]);
363
474
  const processedToolCalls = useRef(/* @__PURE__ */ new Set());
364
475
  const isResolvingToolsRef = useRef(false);
365
476
  const [toolResolutionTrigger, setToolResolutionTrigger] = useState(0);
@@ -431,6 +542,7 @@ function useAgentChat(options) {
431
542
  for (const result of toolResults) newMap.set(result.toolCallId, result.output);
432
543
  return newMap;
433
544
  });
545
+ startToolContinuation();
434
546
  }
435
547
  } finally {
436
548
  isResolvingToolsRef.current = false;
@@ -445,9 +557,11 @@ function useAgentChat(options) {
445
557
  addToolResult,
446
558
  toolsRequiringConfirmation,
447
559
  autoContinueAfterToolResult,
560
+ startToolContinuation,
448
561
  toolResolutionTrigger
449
562
  ]);
450
563
  const sendToolOutputToServer = useCallback((toolCallId, toolName, output, state, errorText) => {
564
+ const shouldAutoContinue = state === "output-error" ? false : autoContinueAfterToolResult;
451
565
  agentRef.current.send(JSON.stringify({
452
566
  type: MessageType.CF_AGENT_TOOL_RESULT,
453
567
  toolCallId,
@@ -455,11 +569,12 @@ function useAgentChat(options) {
455
569
  output,
456
570
  ...state ? { state } : {},
457
571
  ...errorText !== void 0 ? { errorText } : {},
458
- autoContinue: state === "output-error" ? false : autoContinueAfterToolResult,
572
+ autoContinue: shouldAutoContinue,
459
573
  clientTools: toolsRef.current ? extractClientToolSchemas(toolsRef.current) : void 0
460
574
  }));
461
575
  if (state !== "output-error") setClientToolResults((prev) => new Map(prev).set(toolCallId, output));
462
- }, [autoContinueAfterToolResult]);
576
+ if (shouldAutoContinue) startToolContinuation();
577
+ }, [autoContinueAfterToolResult, startToolContinuation]);
463
578
  const sendToolApprovalToServer = useCallback((toolCallId, approved) => {
464
579
  agentRef.current.send(JSON.stringify({
465
580
  type: MessageType.CF_AGENT_TOOL_APPROVAL,
@@ -467,7 +582,8 @@ function useAgentChat(options) {
467
582
  approved,
468
583
  autoContinue: autoContinueAfterToolResult
469
584
  }));
470
- }, [autoContinueAfterToolResult]);
585
+ if (autoContinueAfterToolResult) startToolContinuation();
586
+ }, [autoContinueAfterToolResult, startToolContinuation]);
471
587
  useEffect(() => {
472
588
  const currentOnToolCall = onToolCallRef.current;
473
589
  if (!currentOnToolCall) return;
@@ -571,14 +687,14 @@ function useAgentChat(options) {
571
687
  };
572
688
  return updated;
573
689
  }
574
- return [...prevMessages, updatedMessage];
690
+ return prevMessages;
575
691
  });
576
692
  break;
577
693
  case MessageType.CF_AGENT_STREAM_RESUME_NONE:
578
694
  customTransport.handleStreamResumeNone();
579
695
  break;
580
696
  case MessageType.CF_AGENT_STREAM_RESUMING:
581
- if (!resume) return;
697
+ if (!resume && !customTransport.isAwaitingResume()) return;
582
698
  if (customTransport.handleStreamResuming(data)) return;
583
699
  if (localRequestIdsRef.current.has(data.id)) return;
584
700
  activeStreamRef.current = null;
@@ -594,7 +710,10 @@ function useAgentChat(options) {
594
710
  }));
595
711
  break;
596
712
  case MessageType.CF_AGENT_USE_CHAT_RESPONSE: {
597
- if (localRequestIdsRef.current.has(data.id)) return;
713
+ if (localRequestIdsRef.current.has(data.id)) {
714
+ if (data.done) localRequestIdsRef.current.delete(data.id);
715
+ return;
716
+ }
598
717
  const isContinuation = data.continuation === true;
599
718
  if (!activeStreamRef.current || activeStreamRef.current.id !== data.id) {
600
719
  let messageId = nanoid();
@@ -668,6 +787,7 @@ function useAgentChat(options) {
668
787
  }));
669
788
  setClientToolResults((prev) => new Map(prev).set(toolCallId, output));
670
789
  addToolResult(args);
790
+ if (autoContinueAfterToolResult) startToolContinuation();
671
791
  if (!autoContinueAfterToolResult) {
672
792
  if (!autoSendAfterAllConfirmationsResolved) {
673
793
  sendMessage();
@@ -746,6 +866,7 @@ function useAgentChat(options) {
746
866
  clearHistory: () => {
747
867
  setMessages([]);
748
868
  setClientToolResults(/* @__PURE__ */ new Map());
869
+ resumingToolContinuationRef.current = false;
749
870
  processedToolCalls.current.clear();
750
871
  agent.send(JSON.stringify({ type: MessageType.CF_AGENT_CHAT_CLEAR }));
751
872
  },