@cloudflare/ai-chat 0.6.1 → 0.7.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 +29 -10
- package/dist/ai-chat-v5-migration.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +31 -12
- package/dist/index.js.map +1 -1
- package/dist/react.d.ts +9 -0
- package/dist/react.js +117 -13
- package/dist/react.js.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +9 -6
package/dist/react.d.ts
CHANGED
|
@@ -316,6 +316,15 @@ type UseAgentChatOptions<
|
|
|
316
316
|
* @default true
|
|
317
317
|
*/
|
|
318
318
|
resume?: boolean;
|
|
319
|
+
/**
|
|
320
|
+
* Whether generic client-side stream abort/cleanup should cancel the server
|
|
321
|
+
* turn. By default, client cleanup is local-only so the server turn can
|
|
322
|
+
* continue and be resumed on reconnect. Explicit stop() always cancels the
|
|
323
|
+
* server turn.
|
|
324
|
+
*
|
|
325
|
+
* @default false
|
|
326
|
+
*/
|
|
327
|
+
cancelOnClientAbort?: boolean;
|
|
319
328
|
/**
|
|
320
329
|
* Custom data to include in every chat request body.
|
|
321
330
|
* Accepts a static object or a function that returns one (for dynamic values).
|
package/dist/react.js
CHANGED
|
@@ -16,9 +16,50 @@ var WebSocketChatTransport = class {
|
|
|
16
16
|
this._resumeNoneResolver = null;
|
|
17
17
|
this._expectToolContinuation = false;
|
|
18
18
|
this._abortToolContinuation = null;
|
|
19
|
+
this._activeServerTurnId = null;
|
|
20
|
+
this._cancelAttachedStream = null;
|
|
19
21
|
this.agent = options.agent;
|
|
20
22
|
this.prepareBody = options.prepareBody;
|
|
21
23
|
this.activeRequestIds = options.activeRequestIds;
|
|
24
|
+
this.cancelOnClientAbort = options.cancelOnClientAbort ?? false;
|
|
25
|
+
}
|
|
26
|
+
setCancelOnClientAbort(cancelOnClientAbort) {
|
|
27
|
+
this.cancelOnClientAbort = cancelOnClientAbort;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Explicitly cancel the active server turn, if any.
|
|
31
|
+
* This is separate from generic client-side abort/cancel lifecycle so
|
|
32
|
+
* clients can detach locally without stopping server work.
|
|
33
|
+
*/
|
|
34
|
+
cancelActiveServerTurn() {
|
|
35
|
+
const requestId = this._activeServerTurnId;
|
|
36
|
+
let cancelledRequest = false;
|
|
37
|
+
if (requestId) {
|
|
38
|
+
this.sendCancelFrame(requestId);
|
|
39
|
+
this._cancelAttachedStream?.();
|
|
40
|
+
this.clearActiveServerTurn(requestId);
|
|
41
|
+
cancelledRequest = true;
|
|
42
|
+
}
|
|
43
|
+
const cancelledToolContinuation = this.abortActiveToolContinuation();
|
|
44
|
+
return cancelledRequest || cancelledToolContinuation;
|
|
45
|
+
}
|
|
46
|
+
sendCancelFrame(requestId) {
|
|
47
|
+
try {
|
|
48
|
+
this.agent.send(JSON.stringify({
|
|
49
|
+
id: requestId,
|
|
50
|
+
type: "cf_agent_chat_request_cancel"
|
|
51
|
+
}));
|
|
52
|
+
} catch {}
|
|
53
|
+
}
|
|
54
|
+
setActiveServerTurn(requestId, cancelAttachedStream) {
|
|
55
|
+
this._activeServerTurnId = requestId;
|
|
56
|
+
this._cancelAttachedStream = cancelAttachedStream;
|
|
57
|
+
}
|
|
58
|
+
clearActiveServerTurn(requestId) {
|
|
59
|
+
if (this._activeServerTurnId === requestId) {
|
|
60
|
+
this._activeServerTurnId = null;
|
|
61
|
+
this._cancelAttachedStream = null;
|
|
62
|
+
}
|
|
22
63
|
}
|
|
23
64
|
/**
|
|
24
65
|
* Mark that the next reconnectToStream() call should attach to a
|
|
@@ -61,10 +102,26 @@ var WebSocketChatTransport = class {
|
|
|
61
102
|
this._resumeNoneResolver();
|
|
62
103
|
return true;
|
|
63
104
|
}
|
|
105
|
+
/**
|
|
106
|
+
* Called by the hook's shared message handler when a server turn finishes
|
|
107
|
+
* outside the currently attached transport stream, such as after local-only
|
|
108
|
+
* client cleanup.
|
|
109
|
+
*/
|
|
110
|
+
handleServerTurnCompleted(requestId) {
|
|
111
|
+
this.clearActiveServerTurn(requestId);
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Register a server turn that is being rendered outside a transport-owned
|
|
115
|
+
* stream, such as the hook's fallback cross-tab/resume observer path.
|
|
116
|
+
*/
|
|
117
|
+
observeServerTurn(requestId) {
|
|
118
|
+
this.setActiveServerTurn(requestId, null);
|
|
119
|
+
}
|
|
64
120
|
async sendMessages(options) {
|
|
65
121
|
const requestId = nanoid(8);
|
|
66
122
|
const abortController = new AbortController();
|
|
67
123
|
let completed = false;
|
|
124
|
+
let requestSent = false;
|
|
68
125
|
let extraBody = {};
|
|
69
126
|
if (this.prepareBody) extraBody = await this.prepareBody({
|
|
70
127
|
messages: options.messages,
|
|
@@ -83,9 +140,10 @@ var WebSocketChatTransport = class {
|
|
|
83
140
|
this.activeRequestIds?.add(requestId);
|
|
84
141
|
const agent = this.agent;
|
|
85
142
|
const activeIds = this.activeRequestIds;
|
|
86
|
-
const finish = (action, keepId = false) => {
|
|
143
|
+
const finish = (action, keepId = false, clearServerTurn = true) => {
|
|
87
144
|
if (completed) return;
|
|
88
145
|
completed = true;
|
|
146
|
+
if (clearServerTurn) this.clearActiveServerTurn(requestId);
|
|
89
147
|
try {
|
|
90
148
|
action();
|
|
91
149
|
} catch {}
|
|
@@ -94,15 +152,18 @@ var WebSocketChatTransport = class {
|
|
|
94
152
|
};
|
|
95
153
|
const abortError = /* @__PURE__ */ new Error("Aborted");
|
|
96
154
|
abortError.name = "AbortError";
|
|
155
|
+
const cancelActiveRequest = () => {
|
|
156
|
+
if (completed) return false;
|
|
157
|
+
finish(() => streamController.error(abortError), true);
|
|
158
|
+
return true;
|
|
159
|
+
};
|
|
160
|
+
this.setActiveServerTurn(requestId, cancelActiveRequest);
|
|
97
161
|
const onAbort = () => {
|
|
98
162
|
if (completed) return;
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
}));
|
|
104
|
-
} catch {}
|
|
105
|
-
finish(() => streamController.error(abortError), true);
|
|
163
|
+
if (this.cancelOnClientAbort) {
|
|
164
|
+
if (requestSent) this.sendCancelFrame(requestId);
|
|
165
|
+
finish(() => streamController.error(abortError), requestSent);
|
|
166
|
+
} else finish(() => streamController.error(abortError), false, !requestSent);
|
|
106
167
|
};
|
|
107
168
|
let streamController;
|
|
108
169
|
const stream = new ReadableStream({
|
|
@@ -124,7 +185,11 @@ var WebSocketChatTransport = class {
|
|
|
124
185
|
if (data.done) finish(() => controller.close());
|
|
125
186
|
} catch {}
|
|
126
187
|
};
|
|
188
|
+
const onClose = () => {
|
|
189
|
+
finish(() => controller.close(), false, false);
|
|
190
|
+
};
|
|
127
191
|
agent.addEventListener("message", onMessage, { signal: abortController.signal });
|
|
192
|
+
agent.addEventListener("close", onClose, { signal: abortController.signal });
|
|
128
193
|
},
|
|
129
194
|
cancel() {
|
|
130
195
|
onAbort();
|
|
@@ -134,6 +199,8 @@ var WebSocketChatTransport = class {
|
|
|
134
199
|
options.abortSignal.addEventListener("abort", onAbort, { once: true });
|
|
135
200
|
if (options.abortSignal.aborted) onAbort();
|
|
136
201
|
}
|
|
202
|
+
if (completed) return stream;
|
|
203
|
+
requestSent = true;
|
|
137
204
|
agent.send(JSON.stringify({
|
|
138
205
|
id: requestId,
|
|
139
206
|
init: {
|
|
@@ -270,7 +337,12 @@ var WebSocketChatTransport = class {
|
|
|
270
337
|
if (data.done) finish(() => controller.close(), onResume, onResumeNone);
|
|
271
338
|
} catch {}
|
|
272
339
|
};
|
|
340
|
+
const onClose = () => {
|
|
341
|
+
if (timeout) clearTimeout(timeout);
|
|
342
|
+
finish(() => controller.close(), onResume, onResumeNone);
|
|
343
|
+
};
|
|
273
344
|
agent.addEventListener("message", onMessage, { signal: streamController.signal });
|
|
345
|
+
agent.addEventListener("close", onClose, { signal: streamController.signal });
|
|
274
346
|
try {
|
|
275
347
|
agent.send(JSON.stringify({ type: "cf_agent_stream_resume_request" }));
|
|
276
348
|
} catch {
|
|
@@ -278,7 +350,10 @@ var WebSocketChatTransport = class {
|
|
|
278
350
|
}
|
|
279
351
|
},
|
|
280
352
|
cancel() {
|
|
281
|
-
|
|
353
|
+
if (requestId && transport.cancelOnClientAbort) {
|
|
354
|
+
transport.sendCancelFrame(requestId);
|
|
355
|
+
finish(() => {}, onResumeRef, onResumeNoneRef, true);
|
|
356
|
+
} else finish(() => {}, onResumeRef, onResumeNoneRef);
|
|
282
357
|
}
|
|
283
358
|
});
|
|
284
359
|
}
|
|
@@ -290,18 +365,30 @@ var WebSocketChatTransport = class {
|
|
|
290
365
|
const agent = this.agent;
|
|
291
366
|
const activeIds = this.activeRequestIds;
|
|
292
367
|
const chunkController = new AbortController();
|
|
368
|
+
const abortError = /* @__PURE__ */ new Error("Aborted");
|
|
369
|
+
abortError.name = "AbortError";
|
|
293
370
|
let completed = false;
|
|
294
|
-
const finish = (action) => {
|
|
371
|
+
const finish = (action, keepId = false, clearServerTurn = true) => {
|
|
295
372
|
if (completed) return;
|
|
296
373
|
completed = true;
|
|
374
|
+
if (clearServerTurn) this.clearActiveServerTurn(requestId);
|
|
297
375
|
try {
|
|
298
376
|
action();
|
|
299
377
|
} catch {}
|
|
300
|
-
activeIds?.delete(requestId);
|
|
378
|
+
if (!keepId) activeIds?.delete(requestId);
|
|
301
379
|
chunkController.abort();
|
|
302
380
|
};
|
|
381
|
+
const cancelActiveRequest = () => {
|
|
382
|
+
if (completed) return false;
|
|
383
|
+
finish(() => streamController.error(abortError), true);
|
|
384
|
+
return true;
|
|
385
|
+
};
|
|
386
|
+
this.setActiveServerTurn(requestId, cancelActiveRequest);
|
|
387
|
+
let streamController;
|
|
388
|
+
const transport = this;
|
|
303
389
|
return new ReadableStream({
|
|
304
390
|
start(controller) {
|
|
391
|
+
streamController = controller;
|
|
305
392
|
const onMessage = (event) => {
|
|
306
393
|
try {
|
|
307
394
|
const data = JSON.parse(event.data);
|
|
@@ -318,10 +405,17 @@ var WebSocketChatTransport = class {
|
|
|
318
405
|
if (data.done) finish(() => controller.close());
|
|
319
406
|
} catch {}
|
|
320
407
|
};
|
|
408
|
+
const onClose = () => {
|
|
409
|
+
finish(() => controller.close(), false, false);
|
|
410
|
+
};
|
|
321
411
|
agent.addEventListener("message", onMessage, { signal: chunkController.signal });
|
|
412
|
+
agent.addEventListener("close", onClose, { signal: chunkController.signal });
|
|
322
413
|
},
|
|
323
414
|
cancel() {
|
|
324
|
-
|
|
415
|
+
if (transport.cancelOnClientAbort) {
|
|
416
|
+
transport.sendCancelFrame(requestId);
|
|
417
|
+
finish(() => {}, true);
|
|
418
|
+
} else finish(() => {}, false, false);
|
|
325
419
|
}
|
|
326
420
|
});
|
|
327
421
|
}
|
|
@@ -501,7 +595,7 @@ function detectToolsRequiringConfirmation(tools) {
|
|
|
501
595
|
return Object.entries(tools).filter(([_name, tool]) => !tool.execute).map(([name]) => name);
|
|
502
596
|
}
|
|
503
597
|
function useAgentChat(options) {
|
|
504
|
-
const { agent, getInitialMessages, messages: optionsInitialMessages, onToolCall, onData, experimental_automaticToolResolution, tools, toolsRequiringConfirmation: manualToolsRequiringConfirmation, autoContinueAfterToolResult = true, autoSendAfterAllConfirmationsResolved = true, resume = true, body: bodyOption, prepareSendMessagesRequest, ...rest } = options;
|
|
598
|
+
const { agent, getInitialMessages, messages: optionsInitialMessages, onToolCall, onData, experimental_automaticToolResolution, tools, toolsRequiringConfirmation: manualToolsRequiringConfirmation, autoContinueAfterToolResult = true, autoSendAfterAllConfirmationsResolved = true, resume = true, cancelOnClientAbort = false, body: bodyOption, prepareSendMessagesRequest, ...rest } = options;
|
|
505
599
|
if (manualToolsRequiringConfirmation) warnDeprecated("useAgentChat.toolsRequiringConfirmation", "The 'toolsRequiringConfirmation' option is deprecated. Use needsApproval on server-side tools instead. Will be removed in the next major version.");
|
|
506
600
|
if (experimental_automaticToolResolution) warnDeprecated("useAgentChat.experimental_automaticToolResolution", "The 'experimental_automaticToolResolution' option is deprecated. Use the onToolCall callback instead. Will be removed in the next major version.");
|
|
507
601
|
if (options.autoSendAfterAllConfirmationsResolved !== void 0) warnDeprecated("useAgentChat.autoSendAfterAllConfirmationsResolved", "The 'autoSendAfterAllConfirmationsResolved' option is deprecated. Use sendAutomaticallyWhen from AI SDK instead. Will be removed in the next major version.");
|
|
@@ -591,6 +685,7 @@ function useAgentChat(options) {
|
|
|
591
685
|
if (customTransportRef.current === null) customTransportRef.current = new WebSocketChatTransport({
|
|
592
686
|
agent: agentRef.current,
|
|
593
687
|
activeRequestIds: localRequestIdsRef.current,
|
|
688
|
+
cancelOnClientAbort,
|
|
594
689
|
prepareBody: async ({ messages: msgs, trigger, messageId }) => {
|
|
595
690
|
let extraBody = {};
|
|
596
691
|
const currentBody = bodyOptionRef.current;
|
|
@@ -612,6 +707,7 @@ function useAgentChat(options) {
|
|
|
612
707
|
}
|
|
613
708
|
});
|
|
614
709
|
customTransportRef.current.agent = agentRef.current;
|
|
710
|
+
customTransportRef.current.setCancelOnClientAbort(cancelOnClientAbort);
|
|
615
711
|
const customTransport = customTransportRef.current;
|
|
616
712
|
const useChatHelpers = useChat({
|
|
617
713
|
...rest,
|
|
@@ -650,6 +746,7 @@ function useAgentChat(options) {
|
|
|
650
746
|
]);
|
|
651
747
|
const stopWithToolContinuationAbort = useCallback(async () => {
|
|
652
748
|
try {
|
|
749
|
+
customTransport.cancelActiveServerTurn();
|
|
653
750
|
await stop();
|
|
654
751
|
} finally {
|
|
655
752
|
customTransport.abortActiveToolContinuation();
|
|
@@ -987,6 +1084,7 @@ function useAgentChat(options) {
|
|
|
987
1084
|
streamId: data.id,
|
|
988
1085
|
messageId: nanoid()
|
|
989
1086
|
}).state;
|
|
1087
|
+
customTransport.observeServerTurn(data.id);
|
|
990
1088
|
setIsServerStreaming(true);
|
|
991
1089
|
agentRef.current.send(JSON.stringify({
|
|
992
1090
|
type: "cf_agent_stream_resume_ack",
|
|
@@ -1007,6 +1105,11 @@ function useAgentChat(options) {
|
|
|
1007
1105
|
} catch {}
|
|
1008
1106
|
if (data.done || data.replayComplete) pendingReplayResumeRequestIdsRef.current.delete(data.id);
|
|
1009
1107
|
if (data.done) {
|
|
1108
|
+
if (streamStateRef.current.status === "observing" && streamStateRef.current.streamId === data.id) {
|
|
1109
|
+
streamStateRef.current = { status: "idle" };
|
|
1110
|
+
setIsServerStreaming(false);
|
|
1111
|
+
}
|
|
1112
|
+
customTransport.handleServerTurnCompleted(data.id);
|
|
1010
1113
|
restoreProtectedStreamingAssistant(localResponseIds.get(data.id));
|
|
1011
1114
|
localResponseIds.delete(data.id);
|
|
1012
1115
|
localRequestIdsRef.current.delete(data.id);
|
|
@@ -1026,6 +1129,7 @@ function useAgentChat(options) {
|
|
|
1026
1129
|
console.warn("[useAgentChat] Failed to parse stream chunk:", parseError instanceof Error ? parseError.message : parseError, "body:", data.body?.slice(0, 100));
|
|
1027
1130
|
}
|
|
1028
1131
|
if (data.done || data.replayComplete) pendingReplayResumeRequestIdsRef.current.delete(data.id);
|
|
1132
|
+
if (data.done) customTransport.handleServerTurnCompleted(data.id);
|
|
1029
1133
|
const result = broadcastTransition(streamStateRef.current, {
|
|
1030
1134
|
type: "response",
|
|
1031
1135
|
streamId: data.id,
|