@cloudflare/ai-chat 0.1.3 → 0.1.5
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/CHANGELOG.md +51 -0
- package/dist/index.d.ts +62 -39
- package/dist/index.js +176 -77
- package/dist/index.js.map +1 -1
- package/dist/react.d.ts +40 -25
- package/dist/react.js +48 -35
- package/dist/react.js.map +1 -1
- package/dist/types.d.ts +5 -1
- package/dist/types.js.map +1 -1
- package/package.json +3 -3
- package/src/index.ts +402 -184
- package/src/react-tests/vitest.config.ts +1 -0
- package/src/react.tsx +98 -57
- package/src/tests/cancel-request.test.ts +280 -0
- package/src/tests/client-tool-duplicate-message.test.ts +666 -9
- package/src/tests/get-messages-endpoint.test.ts +74 -0
- package/src/tests/merge-server-state.test.ts +237 -0
- package/src/tests/request-id.test.ts +312 -0
- package/src/tests/sanitize-messages.test.ts +110 -0
- package/src/tests/vitest.config.ts +1 -0
- package/src/tests/worker.ts +113 -1
- package/src/tests/wrangler.jsonc +24 -0
- package/src/tests/ws-transport-abort.test.ts +198 -0
- package/src/types.ts +4 -0
- package/src/ws-chat-transport.ts +50 -26
package/dist/index.js
CHANGED
|
@@ -312,52 +312,29 @@ function isValidMessageStructure(msg) {
|
|
|
312
312
|
return true;
|
|
313
313
|
}
|
|
314
314
|
/**
|
|
315
|
-
* One-shot deprecation warnings (warns once per key per session).
|
|
316
|
-
*/
|
|
317
|
-
const _deprecationWarnings = /* @__PURE__ */ new Set();
|
|
318
|
-
function warnDeprecated(id, message) {
|
|
319
|
-
if (!_deprecationWarnings.has(id)) {
|
|
320
|
-
_deprecationWarnings.add(id);
|
|
321
|
-
console.warn(`[@cloudflare/ai-chat] Deprecated: ${message}`);
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
/**
|
|
325
315
|
* Converts client tool schemas to AI SDK tool format.
|
|
326
316
|
*
|
|
327
|
-
* These tools have no `execute` function
|
|
317
|
+
* These tools have no `execute` function — when the AI model calls them,
|
|
328
318
|
* the tool call is sent back to the client for execution.
|
|
329
319
|
*
|
|
320
|
+
* **For most apps**, define tools on the server with `tool()` from `"ai"`
|
|
321
|
+
* for full Zod type safety. This helper is intended for SDK/platform use
|
|
322
|
+
* cases where the tool surface is determined dynamically by the client.
|
|
323
|
+
*
|
|
330
324
|
* @param clientTools - Array of tool schemas from the client
|
|
331
325
|
* @returns Record of AI SDK tools that can be spread into your tools object
|
|
332
326
|
*
|
|
333
|
-
* @deprecated Define tools on the server using `tool()` from "ai" instead.
|
|
334
|
-
* For tools that need client-side execution, omit the `execute` function
|
|
335
|
-
* and handle them via the `onToolCall` callback in `useAgentChat`.
|
|
336
|
-
*
|
|
337
327
|
* @example
|
|
338
328
|
* ```typescript
|
|
339
|
-
* //
|
|
329
|
+
* // In onChatMessage:
|
|
340
330
|
* const tools = {
|
|
341
|
-
*
|
|
342
|
-
*
|
|
343
|
-
*
|
|
344
|
-
* // No execute = client must handle
|
|
345
|
-
* })
|
|
331
|
+
* ...createToolsFromClientSchemas(options.clientTools),
|
|
332
|
+
* // server-defined tools with execute:
|
|
333
|
+
* myServerTool: tool({ ... }),
|
|
346
334
|
* };
|
|
347
|
-
*
|
|
348
|
-
* // Client: Handle in onToolCall
|
|
349
|
-
* useAgentChat({
|
|
350
|
-
* onToolCall: async ({ toolCall, addToolOutput }) => {
|
|
351
|
-
* if (toolCall.toolName === 'getLocation') {
|
|
352
|
-
* const pos = await navigator.geolocation.getCurrentPosition();
|
|
353
|
-
* addToolOutput({ toolCallId: toolCall.toolCallId, output: pos });
|
|
354
|
-
* }
|
|
355
|
-
* }
|
|
356
|
-
* });
|
|
357
335
|
* ```
|
|
358
336
|
*/
|
|
359
337
|
function createToolsFromClientSchemas(clientTools) {
|
|
360
|
-
warnDeprecated("createToolsFromClientSchemas", "createToolsFromClientSchemas() is deprecated. Define tools on the server using tool() from 'ai' and handle client execution via onToolCall in useAgentChat. Will be removed in the next major version.");
|
|
361
338
|
if (!clientTools || clientTools.length === 0) return {};
|
|
362
339
|
const seenNames = /* @__PURE__ */ new Set();
|
|
363
340
|
for (const t of clientTools) {
|
|
@@ -416,6 +393,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
416
393
|
};
|
|
417
394
|
const _onMessage = this.onMessage.bind(this);
|
|
418
395
|
this.onMessage = async (connection, message) => {
|
|
396
|
+
await this.mcp.ensureJsonSchema();
|
|
419
397
|
if (typeof message === "string") {
|
|
420
398
|
let data;
|
|
421
399
|
try {
|
|
@@ -463,6 +441,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
463
441
|
email: void 0
|
|
464
442
|
}, async () => {
|
|
465
443
|
const response = await this.onChatMessage(async (_finishResult) => {}, {
|
|
444
|
+
requestId: chatMessageId,
|
|
466
445
|
abortSignal,
|
|
467
446
|
clientTools,
|
|
468
447
|
body: this._lastBody
|
|
@@ -512,12 +491,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
512
491
|
return;
|
|
513
492
|
}
|
|
514
493
|
if (data.type === MessageType.CF_AGENT_TOOL_RESULT) {
|
|
515
|
-
const { toolCallId, toolName, output, autoContinue, clientTools } = data;
|
|
494
|
+
const { toolCallId, toolName, output, state, errorText, autoContinue, clientTools } = data;
|
|
516
495
|
if (clientTools?.length) {
|
|
517
496
|
this._lastClientTools = clientTools;
|
|
518
497
|
this._persistRequestContext();
|
|
519
498
|
}
|
|
520
|
-
|
|
499
|
+
const overrideState = state === "output-error" ? "output-error" : void 0;
|
|
500
|
+
this._applyToolResult(toolCallId, toolName, output, overrideState, errorText).then((applied) => {
|
|
521
501
|
if (applied && autoContinue) {
|
|
522
502
|
const waitForStream = async () => {
|
|
523
503
|
if (this._streamCompletionPromise) await this._streamCompletionPromise;
|
|
@@ -534,6 +514,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
534
514
|
email: void 0
|
|
535
515
|
}, async () => {
|
|
536
516
|
const response = await this.onChatMessage(async (_finishResult) => {}, {
|
|
517
|
+
requestId: continuationId,
|
|
537
518
|
abortSignal,
|
|
538
519
|
clientTools: clientTools ?? this._lastClientTools,
|
|
539
520
|
body: this._lastBody
|
|
@@ -554,7 +535,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
554
535
|
if (data.type === MessageType.CF_AGENT_TOOL_APPROVAL) {
|
|
555
536
|
const { toolCallId, approved, autoContinue } = data;
|
|
556
537
|
this._applyToolApproval(toolCallId, approved).then((applied) => {
|
|
557
|
-
if (applied &&
|
|
538
|
+
if (applied && autoContinue) {
|
|
558
539
|
const waitForStream = async () => {
|
|
559
540
|
if (this._streamCompletionPromise) await this._streamCompletionPromise;
|
|
560
541
|
else await new Promise((resolve) => setTimeout(resolve, 500));
|
|
@@ -570,6 +551,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
570
551
|
email: void 0
|
|
571
552
|
}, async () => {
|
|
572
553
|
const response = await this.onChatMessage(async (_finishResult) => {}, {
|
|
554
|
+
requestId: continuationId,
|
|
573
555
|
abortSignal,
|
|
574
556
|
clientTools: this._lastClientTools,
|
|
575
557
|
body: this._lastBody
|
|
@@ -590,6 +572,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
590
572
|
}
|
|
591
573
|
return _onMessage(connection, message);
|
|
592
574
|
};
|
|
575
|
+
const _onRequest = this.onRequest.bind(this);
|
|
576
|
+
this.onRequest = async (request) => {
|
|
577
|
+
return this._tryCatchChat(async () => {
|
|
578
|
+
if (new URL(request.url).pathname.split("/").pop() === "get-messages") return Response.json(this._loadMessagesFromDb());
|
|
579
|
+
return _onRequest(request);
|
|
580
|
+
});
|
|
581
|
+
};
|
|
593
582
|
}
|
|
594
583
|
/**
|
|
595
584
|
* Notify a connection about an active stream that can be resumed.
|
|
@@ -710,15 +699,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
710
699
|
}
|
|
711
700
|
}).filter((msg) => msg !== null);
|
|
712
701
|
}
|
|
713
|
-
async onRequest(request) {
|
|
714
|
-
return this._tryCatchChat(async () => {
|
|
715
|
-
if (new URL(request.url).pathname.endsWith("/get-messages")) {
|
|
716
|
-
const messages = this._loadMessagesFromDb();
|
|
717
|
-
return Response.json(messages);
|
|
718
|
-
}
|
|
719
|
-
return super.onRequest(request);
|
|
720
|
-
});
|
|
721
|
-
}
|
|
722
702
|
async _tryCatchChat(fn) {
|
|
723
703
|
try {
|
|
724
704
|
return await fn();
|
|
@@ -742,8 +722,15 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
742
722
|
async saveMessages(messages) {
|
|
743
723
|
await this.persistMessages(messages);
|
|
744
724
|
await this._tryCatchChat(async () => {
|
|
745
|
-
const
|
|
746
|
-
|
|
725
|
+
const requestId = nanoid();
|
|
726
|
+
const abortSignal = this._getAbortSignal(requestId);
|
|
727
|
+
const response = await this.onChatMessage(() => {}, {
|
|
728
|
+
requestId,
|
|
729
|
+
abortSignal,
|
|
730
|
+
clientTools: this._lastClientTools,
|
|
731
|
+
body: this._lastBody
|
|
732
|
+
});
|
|
733
|
+
if (response) this._reply(requestId, response);
|
|
747
734
|
});
|
|
748
735
|
}
|
|
749
736
|
async persistMessages(messages, excludeBroadcastIds = []) {
|
|
@@ -782,8 +769,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
782
769
|
if (msg.role !== "assistant") continue;
|
|
783
770
|
for (const part of msg.parts) if ("toolCallId" in part && "state" in part && part.state === "output-available" && "output" in part) serverToolOutputs.set(part.toolCallId, part.output);
|
|
784
771
|
}
|
|
785
|
-
|
|
786
|
-
return incomingMessages.map((msg) => {
|
|
772
|
+
const withMergedToolOutputs = serverToolOutputs.size === 0 ? incomingMessages : incomingMessages.map((msg) => {
|
|
787
773
|
if (msg.role !== "assistant") return msg;
|
|
788
774
|
let hasChanges = false;
|
|
789
775
|
const updatedParts = msg.parts.map((part) => {
|
|
@@ -802,6 +788,50 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
802
788
|
parts: updatedParts
|
|
803
789
|
} : msg;
|
|
804
790
|
});
|
|
791
|
+
return this._reconcileAssistantIdsWithServerState(withMergedToolOutputs);
|
|
792
|
+
}
|
|
793
|
+
/**
|
|
794
|
+
* Reconciles assistant message IDs between incoming client state and server state.
|
|
795
|
+
*
|
|
796
|
+
* The client can keep a different local ID for an assistant message than the one
|
|
797
|
+
* persisted on the server (e.g. optimistic/local IDs). When that full history is
|
|
798
|
+
* sent back, persisting by ID alone creates duplicate assistant rows. To prevent
|
|
799
|
+
* this, we reuse the server ID for assistant messages that match by content and
|
|
800
|
+
* order, while leaving tool-call messages to _resolveMessageForToolMerge.
|
|
801
|
+
*/
|
|
802
|
+
_reconcileAssistantIdsWithServerState(incomingMessages) {
|
|
803
|
+
if (this.messages.length === 0) return incomingMessages;
|
|
804
|
+
let serverCursor = 0;
|
|
805
|
+
return incomingMessages.map((incomingMessage) => {
|
|
806
|
+
const exactMatchIndex = this.messages.findIndex((serverMessage, index) => index >= serverCursor && serverMessage.id === incomingMessage.id);
|
|
807
|
+
if (exactMatchIndex !== -1) {
|
|
808
|
+
serverCursor = exactMatchIndex + 1;
|
|
809
|
+
return incomingMessage;
|
|
810
|
+
}
|
|
811
|
+
if (incomingMessage.role !== "assistant" || this._hasToolCallPart(incomingMessage)) return incomingMessage;
|
|
812
|
+
const incomingKey = this._assistantMessageContentKey(incomingMessage);
|
|
813
|
+
if (!incomingKey) return incomingMessage;
|
|
814
|
+
for (let i = serverCursor; i < this.messages.length; i++) {
|
|
815
|
+
const serverMessage = this.messages[i];
|
|
816
|
+
if (serverMessage.role !== "assistant" || this._hasToolCallPart(serverMessage)) continue;
|
|
817
|
+
if (this._assistantMessageContentKey(serverMessage) === incomingKey) {
|
|
818
|
+
serverCursor = i + 1;
|
|
819
|
+
return {
|
|
820
|
+
...incomingMessage,
|
|
821
|
+
id: serverMessage.id
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
return incomingMessage;
|
|
826
|
+
});
|
|
827
|
+
}
|
|
828
|
+
_hasToolCallPart(message) {
|
|
829
|
+
return message.parts.some((part) => "toolCallId" in part);
|
|
830
|
+
}
|
|
831
|
+
_assistantMessageContentKey(message) {
|
|
832
|
+
if (message.role !== "assistant") return;
|
|
833
|
+
const sanitized = this._sanitizeMessageForPersistence(message);
|
|
834
|
+
return JSON.stringify(sanitized.parts);
|
|
805
835
|
}
|
|
806
836
|
/**
|
|
807
837
|
* Resolves a message for persistence, handling tool result merging.
|
|
@@ -815,7 +845,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
815
845
|
*/
|
|
816
846
|
_resolveMessageForToolMerge(message) {
|
|
817
847
|
if (message.role !== "assistant") return message;
|
|
818
|
-
for (const part of message.parts) if ("toolCallId" in part && "state" in part && (part.state === "output-available" || part.state === "approval-responded" || part.state === "approval-requested")) {
|
|
848
|
+
for (const part of message.parts) if ("toolCallId" in part && "state" in part && (part.state === "output-available" || part.state === "output-error" || part.state === "approval-responded" || part.state === "approval-requested")) {
|
|
819
849
|
const toolCallId = part.toolCallId;
|
|
820
850
|
const existingMessage = this._findMessageByToolCallId(toolCallId);
|
|
821
851
|
if (existingMessage && existingMessage.id !== message.id) return {
|
|
@@ -843,32 +873,37 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
843
873
|
* Sanitizes a message for persistence by removing ephemeral provider-specific
|
|
844
874
|
* data that should not be stored or sent back in subsequent requests.
|
|
845
875
|
*
|
|
846
|
-
*
|
|
876
|
+
* Two-step process:
|
|
847
877
|
*
|
|
848
|
-
* 1. **
|
|
849
|
-
* defaults to using OpenAI's Responses API which assigns unique
|
|
850
|
-
* to
|
|
851
|
-
* OpenAI rejects
|
|
878
|
+
* 1. **Strip OpenAI ephemeral fields**: The AI SDK's @ai-sdk/openai provider
|
|
879
|
+
* (v2.0.x+) defaults to using OpenAI's Responses API which assigns unique
|
|
880
|
+
* itemIds and reasoningEncryptedContent to message parts. When persisted
|
|
881
|
+
* and sent back, OpenAI rejects duplicate itemIds.
|
|
852
882
|
*
|
|
853
|
-
* 2. **
|
|
854
|
-
* text and
|
|
855
|
-
*
|
|
883
|
+
* 2. **Filter truly empty reasoning parts**: After stripping, reasoning parts
|
|
884
|
+
* with no text and no remaining providerMetadata are removed. Parts that
|
|
885
|
+
* still carry providerMetadata (e.g. Anthropic's redacted_thinking blocks
|
|
886
|
+
* with providerMetadata.anthropic.redactedData) are preserved, as they
|
|
887
|
+
* contain data required for round-tripping with the provider API.
|
|
856
888
|
*
|
|
857
889
|
* @param message - The message to sanitize
|
|
858
890
|
* @returns A new message with ephemeral provider data removed
|
|
859
891
|
*/
|
|
860
892
|
_sanitizeMessageForPersistence(message) {
|
|
861
|
-
const sanitizedParts = message.parts.
|
|
862
|
-
if (part.type === "reasoning") {
|
|
863
|
-
const reasoningPart = part;
|
|
864
|
-
if (!reasoningPart.text || reasoningPart.text.trim() === "") return false;
|
|
865
|
-
}
|
|
866
|
-
return true;
|
|
867
|
-
}).map((part) => {
|
|
893
|
+
const sanitizedParts = message.parts.map((part) => {
|
|
868
894
|
let sanitizedPart = part;
|
|
869
895
|
if ("providerMetadata" in sanitizedPart && sanitizedPart.providerMetadata && typeof sanitizedPart.providerMetadata === "object" && "openai" in sanitizedPart.providerMetadata) sanitizedPart = this._stripOpenAIMetadata(sanitizedPart, "providerMetadata");
|
|
870
896
|
if ("callProviderMetadata" in sanitizedPart && sanitizedPart.callProviderMetadata && typeof sanitizedPart.callProviderMetadata === "object" && "openai" in sanitizedPart.callProviderMetadata) sanitizedPart = this._stripOpenAIMetadata(sanitizedPart, "callProviderMetadata");
|
|
871
897
|
return sanitizedPart;
|
|
898
|
+
}).filter((part) => {
|
|
899
|
+
if (part.type === "reasoning") {
|
|
900
|
+
const reasoningPart = part;
|
|
901
|
+
if (!reasoningPart.text || reasoningPart.text.trim() === "") {
|
|
902
|
+
if ("providerMetadata" in reasoningPart && reasoningPart.providerMetadata && typeof reasoningPart.providerMetadata === "object" && Object.keys(reasoningPart.providerMetadata).length > 0) return true;
|
|
903
|
+
return false;
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
return true;
|
|
872
907
|
});
|
|
873
908
|
return {
|
|
874
909
|
...message,
|
|
@@ -1097,20 +1132,41 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1097
1132
|
* @param toolCallId - The tool call ID this result is for
|
|
1098
1133
|
* @param _toolName - The name of the tool (unused, kept for API compat)
|
|
1099
1134
|
* @param output - The output from the tool execution
|
|
1135
|
+
* @param overrideState - Optional state override ("output-error" to signal denial/failure)
|
|
1136
|
+
* @param errorText - Error message when overrideState is "output-error"
|
|
1100
1137
|
* @returns true if the result was applied, false if the message was not found
|
|
1101
1138
|
*/
|
|
1102
|
-
async _applyToolResult(toolCallId, _toolName, output) {
|
|
1103
|
-
return this._findAndUpdateToolPart(toolCallId, "_applyToolResult", [
|
|
1139
|
+
async _applyToolResult(toolCallId, _toolName, output, overrideState, errorText) {
|
|
1140
|
+
return this._findAndUpdateToolPart(toolCallId, "_applyToolResult", [
|
|
1141
|
+
"input-available",
|
|
1142
|
+
"approval-requested",
|
|
1143
|
+
"approval-responded"
|
|
1144
|
+
], (part) => ({
|
|
1104
1145
|
...part,
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1146
|
+
...overrideState === "output-error" ? {
|
|
1147
|
+
state: "output-error",
|
|
1148
|
+
errorText: errorText ?? "Tool execution denied by user"
|
|
1149
|
+
} : {
|
|
1150
|
+
state: "output-available",
|
|
1151
|
+
output,
|
|
1152
|
+
preliminary: false
|
|
1153
|
+
}
|
|
1108
1154
|
}));
|
|
1109
1155
|
}
|
|
1110
|
-
async _streamSSEReply(id, streamId, reader, message, streamCompleted, continuation = false) {
|
|
1156
|
+
async _streamSSEReply(id, streamId, reader, message, streamCompleted, continuation = false, abortSignal) {
|
|
1111
1157
|
streamCompleted.value = false;
|
|
1158
|
+
if (abortSignal && !abortSignal.aborted) abortSignal.addEventListener("abort", () => {
|
|
1159
|
+
reader.cancel().catch(() => {});
|
|
1160
|
+
}, { once: true });
|
|
1112
1161
|
while (true) {
|
|
1113
|
-
|
|
1162
|
+
if (abortSignal?.aborted) break;
|
|
1163
|
+
let readResult;
|
|
1164
|
+
try {
|
|
1165
|
+
readResult = await reader.read();
|
|
1166
|
+
} catch {
|
|
1167
|
+
break;
|
|
1168
|
+
}
|
|
1169
|
+
const { done, value } = readResult;
|
|
1114
1170
|
if (done) {
|
|
1115
1171
|
this._completeStream(streamId);
|
|
1116
1172
|
streamCompleted.value = true;
|
|
@@ -1210,8 +1266,20 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1210
1266
|
});
|
|
1211
1267
|
} catch (_error) {}
|
|
1212
1268
|
}
|
|
1269
|
+
if (!streamCompleted.value) {
|
|
1270
|
+
console.warn("[AIChatAgent] Stream was still active when cancel was received. Pass options.abortSignal to streamText() in your onChatMessage() to cancel the upstream LLM call and avoid wasted work.");
|
|
1271
|
+
this._completeStream(streamId);
|
|
1272
|
+
streamCompleted.value = true;
|
|
1273
|
+
this._broadcastChatMessage({
|
|
1274
|
+
body: "",
|
|
1275
|
+
done: true,
|
|
1276
|
+
id,
|
|
1277
|
+
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
|
|
1278
|
+
...continuation && { continuation: true }
|
|
1279
|
+
});
|
|
1280
|
+
}
|
|
1213
1281
|
}
|
|
1214
|
-
async _sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation = false) {
|
|
1282
|
+
async _sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation = false, abortSignal) {
|
|
1215
1283
|
this._broadcastTextEvent(streamId, {
|
|
1216
1284
|
type: "text-start",
|
|
1217
1285
|
id
|
|
@@ -1222,8 +1290,18 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1222
1290
|
state: "streaming"
|
|
1223
1291
|
};
|
|
1224
1292
|
message.parts.push(textPart);
|
|
1293
|
+
if (abortSignal && !abortSignal.aborted) abortSignal.addEventListener("abort", () => {
|
|
1294
|
+
reader.cancel().catch(() => {});
|
|
1295
|
+
}, { once: true });
|
|
1225
1296
|
while (true) {
|
|
1226
|
-
|
|
1297
|
+
if (abortSignal?.aborted) break;
|
|
1298
|
+
let readResult;
|
|
1299
|
+
try {
|
|
1300
|
+
readResult = await reader.read();
|
|
1301
|
+
} catch {
|
|
1302
|
+
break;
|
|
1303
|
+
}
|
|
1304
|
+
const { done, value } = readResult;
|
|
1227
1305
|
if (done) {
|
|
1228
1306
|
textPart.state = "done";
|
|
1229
1307
|
this._broadcastTextEvent(streamId, {
|
|
@@ -1251,11 +1329,31 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1251
1329
|
}, continuation);
|
|
1252
1330
|
}
|
|
1253
1331
|
}
|
|
1332
|
+
if (!streamCompleted.value) {
|
|
1333
|
+
console.warn("[AIChatAgent] Stream was still active when cancel was received. Pass options.abortSignal to streamText() in your onChatMessage() to cancel the upstream LLM call and avoid wasted work.");
|
|
1334
|
+
textPart.state = "done";
|
|
1335
|
+
this._broadcastTextEvent(streamId, {
|
|
1336
|
+
type: "text-end",
|
|
1337
|
+
id
|
|
1338
|
+
}, continuation);
|
|
1339
|
+
this._completeStream(streamId);
|
|
1340
|
+
streamCompleted.value = true;
|
|
1341
|
+
this._broadcastChatMessage({
|
|
1342
|
+
body: "",
|
|
1343
|
+
done: true,
|
|
1344
|
+
id,
|
|
1345
|
+
type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
|
|
1346
|
+
...continuation && { continuation: true }
|
|
1347
|
+
});
|
|
1348
|
+
}
|
|
1254
1349
|
}
|
|
1255
1350
|
/**
|
|
1256
1351
|
* Applies a tool approval response from the client, updating the persisted message.
|
|
1257
1352
|
* This is called when the client sends CF_AGENT_TOOL_APPROVAL for tools with needsApproval.
|
|
1258
|
-
*
|
|
1353
|
+
*
|
|
1354
|
+
* - approved=true transitions to approval-responded
|
|
1355
|
+
* - approved=false transitions to output-denied so convertToModelMessages
|
|
1356
|
+
* emits a tool_result for providers (e.g. Anthropic) that require it.
|
|
1259
1357
|
*
|
|
1260
1358
|
* @param toolCallId - The tool call ID this approval is for
|
|
1261
1359
|
* @param approved - Whether the tool execution was approved
|
|
@@ -1264,7 +1362,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1264
1362
|
async _applyToolApproval(toolCallId, approved) {
|
|
1265
1363
|
return this._findAndUpdateToolPart(toolCallId, "_applyToolApproval", ["input-available", "approval-requested"], (part) => ({
|
|
1266
1364
|
...part,
|
|
1267
|
-
state: "approval-responded",
|
|
1365
|
+
state: approved ? "approval-responded" : "output-denied",
|
|
1268
1366
|
approval: {
|
|
1269
1367
|
...part.approval,
|
|
1270
1368
|
approved
|
|
@@ -1273,6 +1371,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1273
1371
|
}
|
|
1274
1372
|
async _reply(id, response, excludeBroadcastIds = [], options = {}) {
|
|
1275
1373
|
const { continuation = false, chatMessageId } = options;
|
|
1374
|
+
const abortSignal = chatMessageId ? this._chatMessageAbortControllers.get(chatMessageId)?.signal : void 0;
|
|
1276
1375
|
return this._tryCatchChat(async () => {
|
|
1277
1376
|
if (!response.body) {
|
|
1278
1377
|
this._broadcastChatMessage({
|
|
@@ -1299,8 +1398,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
|
|
|
1299
1398
|
const streamCompleted = { value: false };
|
|
1300
1399
|
let earlyPersistedId = null;
|
|
1301
1400
|
try {
|
|
1302
|
-
if (isSSE) await this._streamSSEReply(id, streamId, reader, message, streamCompleted, continuation);
|
|
1303
|
-
else await this._sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation);
|
|
1401
|
+
if (isSSE) await this._streamSSEReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
|
|
1402
|
+
else await this._sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
|
|
1304
1403
|
} catch (error) {
|
|
1305
1404
|
if (!streamCompleted.value) {
|
|
1306
1405
|
this._markStreamError(streamId);
|