@cloudflare/ai-chat 0.2.6 → 0.3.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/dist/index.js CHANGED
@@ -413,6 +413,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
413
413
  static {
414
414
  this.AUTO_CONTINUATION_COALESCE_MS = 10;
415
415
  }
416
+ static {
417
+ this.MESSAGE_DEBOUNCE_MS = 750;
418
+ }
416
419
  /** Measure UTF-8 byte length of a string (accurate for SQLite row limits). */
417
420
  static _byteLength(s) {
418
421
  return textEncoder.encode(s).byteLength;
@@ -420,11 +423,19 @@ var AIChatAgent = class AIChatAgent extends Agent {
420
423
  constructor(ctx, env) {
421
424
  super(ctx, env);
422
425
  this._streamingMessage = null;
426
+ this._pendingChatResponseResults = [];
427
+ this._insideResponseHook = false;
423
428
  this._pendingInteractionPromise = null;
424
429
  this._approvalPersistedMessageId = null;
425
430
  this._chatTurnQueue = Promise.resolve();
426
431
  this._activeChatTurnRequestId = null;
427
432
  this._chatEpoch = 0;
433
+ this._queuedChatTurnCountsByEpoch = /* @__PURE__ */ new Map();
434
+ this._mergeQueuedUserStartIndexByEpoch = /* @__PURE__ */ new Map();
435
+ this._submitSequence = 0;
436
+ this._latestOverlappingSubmitSequence = 0;
437
+ this._activeDebounceTimer = null;
438
+ this._activeDebounceResolve = null;
428
439
  this._pendingResumeConnections = /* @__PURE__ */ new Set();
429
440
  this._awaitingStreamStartConnections = /* @__PURE__ */ new Map();
430
441
  this._pendingAutoContinuation = false;
@@ -439,6 +450,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
439
450
  this._deferredAutoContinuation = null;
440
451
  this._persistedMessageCache = /* @__PURE__ */ new Map();
441
452
  this.maxPersistedMessages = void 0;
453
+ this.messageConcurrency = "queue";
442
454
  this.waitForMcpConnections = { timeout: 1e4 };
443
455
  this.sql`create table if not exists cf_ai_chat_agent_messages (
444
456
  id text primary key,
@@ -490,20 +502,59 @@ var AIChatAgent = class AIChatAgent extends Agent {
490
502
  }
491
503
  const { messages, clientTools, trigger: _trigger, ...customBody } = parsed;
492
504
  const chatMessageId = data.id;
505
+ const transformedMessages = autoTransformMessages(messages);
506
+ const requestTrigger = _trigger === "regenerate-message" ? "regenerate-message" : "submit-message";
507
+ const requestClientTools = clientTools?.length ? clientTools : void 0;
508
+ const requestBody = Object.keys(customBody).length > 0 ? customBody : void 0;
509
+ const epoch = this._chatEpoch;
510
+ const concurrencyDecision = this._getSubmitConcurrencyDecision(requestTrigger);
511
+ if (concurrencyDecision.action === "drop") {
512
+ this._rollbackDroppedSubmit(connection);
513
+ this._completeSkippedRequest(connection, chatMessageId);
514
+ return;
515
+ }
516
+ this._broadcastChatMessage({
517
+ messages: transformedMessages,
518
+ type: MessageType.CF_AGENT_CHAT_MESSAGES
519
+ }, [connection.id]);
520
+ await this.persistMessages(transformedMessages, [connection.id], { _deleteStaleRows: true });
521
+ if (concurrencyDecision.mergeQueuedMessages) await this._mergeQueuedUserMessages(epoch);
493
522
  return this._runExclusiveChatTurn(chatMessageId, async () => {
523
+ if (this._chatEpoch !== epoch) {
524
+ this._completeSkippedRequest(connection, chatMessageId);
525
+ return;
526
+ }
527
+ if (this._isSupersededSubmit(concurrencyDecision.submitSequence)) {
528
+ this._completeSkippedRequest(connection, chatMessageId);
529
+ return;
530
+ }
531
+ if (concurrencyDecision.debounceUntilMs !== null) {
532
+ await this._waitForTimestamp(concurrencyDecision.debounceUntilMs);
533
+ if (this._chatEpoch !== epoch) {
534
+ this._completeSkippedRequest(connection, chatMessageId);
535
+ return;
536
+ }
537
+ if (this._isSupersededSubmit(concurrencyDecision.submitSequence)) {
538
+ this._completeSkippedRequest(connection, chatMessageId);
539
+ return;
540
+ }
541
+ }
542
+ if (concurrencyDecision.mergeQueuedMessages) {
543
+ await this._mergeQueuedUserMessages(epoch);
544
+ if (this._chatEpoch !== epoch) {
545
+ this._completeSkippedRequest(connection, chatMessageId);
546
+ return;
547
+ }
548
+ if (this._isSupersededSubmit(concurrencyDecision.submitSequence)) {
549
+ this._completeSkippedRequest(connection, chatMessageId);
550
+ return;
551
+ }
552
+ }
494
553
  if (this.waitForMcpConnections) {
495
554
  const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : void 0;
496
555
  await this.mcp.waitForConnections(timeout != null ? { timeout } : void 0);
497
556
  }
498
- this._lastClientTools = clientTools?.length ? clientTools : void 0;
499
- this._lastBody = Object.keys(customBody).length > 0 ? customBody : void 0;
500
- this._persistRequestContext();
501
- const transformedMessages = autoTransformMessages(messages);
502
- this._broadcastChatMessage({
503
- messages: transformedMessages,
504
- type: MessageType.CF_AGENT_CHAT_MESSAGES
505
- }, [connection.id]);
506
- await this.persistMessages(transformedMessages, [connection.id], { _deleteStaleRows: true });
557
+ this._setRequestContext(requestClientTools, requestBody);
507
558
  this._emit("message:request");
508
559
  const abortSignal = this._getAbortSignal(chatMessageId);
509
560
  return this._tryCatchChat(async () => {
@@ -516,8 +567,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
516
567
  const response = await this.onChatMessage(async (_finishResult) => {}, {
517
568
  requestId: chatMessageId,
518
569
  abortSignal,
519
- clientTools,
520
- body: this._lastBody
570
+ clientTools: requestClientTools,
571
+ body: requestBody
521
572
  });
522
573
  if (response) await this._reply(chatMessageId, response, [connection.id], { chatMessageId });
523
574
  else {
@@ -531,7 +582,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
531
582
  }
532
583
  });
533
584
  });
534
- });
585
+ }, { epoch });
535
586
  }
536
587
  if (data.type === MessageType.CF_AGENT_CHAT_CLEAR) {
537
588
  this.resetTurnState();
@@ -866,6 +917,176 @@ var AIChatAgent = class AIChatAgent extends Agent {
866
917
  await queue;
867
918
  } while (this._chatTurnQueue !== queue);
868
919
  }
920
+ _normalizeMessageConcurrency() {
921
+ if (typeof this.messageConcurrency === "string") return this.messageConcurrency;
922
+ const debounceMs = this.messageConcurrency.debounceMs;
923
+ return {
924
+ strategy: "debounce",
925
+ debounceMs: typeof debounceMs === "number" && Number.isFinite(debounceMs) && debounceMs >= 0 ? debounceMs : AIChatAgent.MESSAGE_DEBOUNCE_MS
926
+ };
927
+ }
928
+ _getSubmitConcurrencyDecision(trigger) {
929
+ const queuedTurnsInCurrentEpoch = this._queuedChatTurnCountsByEpoch.get(this._chatEpoch) ?? 0;
930
+ if (trigger !== "submit-message" || queuedTurnsInCurrentEpoch === 0) return {
931
+ action: "execute",
932
+ submitSequence: null,
933
+ debounceUntilMs: null,
934
+ mergeQueuedMessages: false
935
+ };
936
+ const concurrency = this._normalizeMessageConcurrency();
937
+ if (concurrency === "drop") return {
938
+ action: "drop",
939
+ submitSequence: null,
940
+ debounceUntilMs: null,
941
+ mergeQueuedMessages: false
942
+ };
943
+ if (concurrency === "queue") return {
944
+ action: "execute",
945
+ submitSequence: null,
946
+ debounceUntilMs: null,
947
+ mergeQueuedMessages: false
948
+ };
949
+ const submitSequence = ++this._submitSequence;
950
+ this._latestOverlappingSubmitSequence = submitSequence;
951
+ if (concurrency === "latest") return {
952
+ action: "execute",
953
+ submitSequence,
954
+ debounceUntilMs: null,
955
+ mergeQueuedMessages: false
956
+ };
957
+ if (concurrency === "merge") {
958
+ if (!this._mergeQueuedUserStartIndexByEpoch.has(this._chatEpoch)) this._mergeQueuedUserStartIndexByEpoch.set(this._chatEpoch, this.messages.length);
959
+ return {
960
+ action: "execute",
961
+ submitSequence,
962
+ debounceUntilMs: null,
963
+ mergeQueuedMessages: true
964
+ };
965
+ }
966
+ return {
967
+ action: "execute",
968
+ submitSequence,
969
+ debounceUntilMs: Date.now() + concurrency.debounceMs,
970
+ mergeQueuedMessages: false
971
+ };
972
+ }
973
+ _isSupersededSubmit(submitSequence) {
974
+ return submitSequence !== null && submitSequence < this._latestOverlappingSubmitSequence;
975
+ }
976
+ async _waitForTimestamp(timestampMs) {
977
+ const remainingMs = timestampMs - Date.now();
978
+ if (remainingMs <= 0) return;
979
+ await new Promise((resolve) => {
980
+ this._activeDebounceResolve = resolve;
981
+ this._activeDebounceTimer = setTimeout(() => {
982
+ this._activeDebounceTimer = null;
983
+ this._activeDebounceResolve = null;
984
+ resolve();
985
+ }, remainingMs);
986
+ });
987
+ }
988
+ _cancelActiveDebounce() {
989
+ if (this._activeDebounceTimer !== null) {
990
+ clearTimeout(this._activeDebounceTimer);
991
+ this._activeDebounceTimer = null;
992
+ }
993
+ if (this._activeDebounceResolve !== null) {
994
+ this._activeDebounceResolve();
995
+ this._activeDebounceResolve = null;
996
+ }
997
+ }
998
+ async _mergeQueuedUserMessages(epoch = this._chatEpoch) {
999
+ const mergedMessages = this._getMergedQueuedUserMessages(epoch);
1000
+ if (!mergedMessages) return;
1001
+ await this.persistMessages(mergedMessages, [], { _deleteStaleRows: true });
1002
+ }
1003
+ _getMergedQueuedUserMessages(epoch) {
1004
+ const queuedUserStart = this._mergeQueuedUserStartIndexByEpoch.get(epoch);
1005
+ if (queuedUserStart === void 0) return null;
1006
+ let queuedUserEnd = queuedUserStart;
1007
+ while (this.messages[queuedUserEnd]?.role === "user") queuedUserEnd++;
1008
+ if (queuedUserEnd === queuedUserStart && queuedUserStart < this.messages.length) console.warn(`[AIChatAgent] merge: expected user messages at index ${queuedUserStart} but found role="${this.messages[queuedUserStart]?.role}"; skipping merge`);
1009
+ const queuedUserMessages = this.messages.slice(queuedUserStart, queuedUserEnd);
1010
+ if (queuedUserMessages.length < 2) return null;
1011
+ return [
1012
+ ...this.messages.slice(0, queuedUserStart),
1013
+ AIChatAgent._mergeUserMessages(queuedUserMessages),
1014
+ ...this.messages.slice(queuedUserEnd)
1015
+ ];
1016
+ }
1017
+ static _mergeUserMessages(messages) {
1018
+ const [firstMessage, ...remainingMessages] = messages;
1019
+ if (!firstMessage) throw new Error("cannot merge an empty message list");
1020
+ let mergedParts = AIChatAgent._cloneMessageParts(firstMessage.parts);
1021
+ for (const message of remainingMessages) {
1022
+ AIChatAgent._appendMergedText(mergedParts, "\n\n");
1023
+ mergedParts = AIChatAgent._mergeMessageParts(mergedParts, message.parts);
1024
+ }
1025
+ return {
1026
+ ...messages[messages.length - 1] ?? firstMessage,
1027
+ parts: mergedParts
1028
+ };
1029
+ }
1030
+ static _mergeMessageParts(currentParts, nextParts) {
1031
+ const mergedParts = AIChatAgent._cloneMessageParts(currentParts);
1032
+ for (const part of nextParts) {
1033
+ if (part.type === "text") {
1034
+ AIChatAgent._appendMergedText(mergedParts, part.text);
1035
+ continue;
1036
+ }
1037
+ mergedParts.push(part);
1038
+ }
1039
+ return mergedParts;
1040
+ }
1041
+ static _cloneMessageParts(parts) {
1042
+ return [...parts];
1043
+ }
1044
+ static _appendMergedText(parts, text) {
1045
+ if (text.length === 0) return;
1046
+ const lastPart = parts[parts.length - 1];
1047
+ if (lastPart?.type === "text") {
1048
+ parts[parts.length - 1] = {
1049
+ ...lastPart,
1050
+ text: lastPart.text + text
1051
+ };
1052
+ return;
1053
+ }
1054
+ const textPart = {
1055
+ type: "text",
1056
+ text
1057
+ };
1058
+ parts.push(textPart);
1059
+ }
1060
+ _setRequestContext(clientTools, body) {
1061
+ this._lastClientTools = clientTools?.length ? clientTools : void 0;
1062
+ this._lastBody = body && Object.keys(body).length > 0 ? body : void 0;
1063
+ this._persistRequestContext();
1064
+ }
1065
+ _messagesForClientSync() {
1066
+ if (!this._streamingMessage || this._streamingMessage.parts.length === 0) return this.messages;
1067
+ const existingIdx = this.messages.findIndex((message) => message.id === this._streamingMessage?.id);
1068
+ if (existingIdx >= 0) return this.messages.map((message, idx) => idx === existingIdx && this._streamingMessage ? this._streamingMessage : message);
1069
+ return [...this.messages, this._streamingMessage];
1070
+ }
1071
+ _sendDirectMessage(connection, message) {
1072
+ try {
1073
+ connection.send(JSON.stringify(message));
1074
+ } catch {}
1075
+ }
1076
+ _completeSkippedRequest(connection, requestId) {
1077
+ this._sendDirectMessage(connection, {
1078
+ body: "",
1079
+ done: true,
1080
+ id: requestId,
1081
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
1082
+ });
1083
+ }
1084
+ _rollbackDroppedSubmit(connection) {
1085
+ this._sendDirectMessage(connection, {
1086
+ messages: this._messagesForClientSync(),
1087
+ type: MessageType.CF_AGENT_CHAT_MESSAGES
1088
+ });
1089
+ }
869
1090
  /** `true` when an assistant message is waiting on a client tool result or approval. */
870
1091
  hasPendingInteraction() {
871
1092
  if (this._streamingMessage && this._messageHasPendingInteraction(this._streamingMessage)) return true;
@@ -907,12 +1128,15 @@ var AIChatAgent = class AIChatAgent extends Agent {
907
1128
  * the built-in handler calls it automatically.
908
1129
  */
909
1130
  resetTurnState() {
1131
+ this._mergeQueuedUserStartIndexByEpoch.delete(this._chatEpoch);
910
1132
  this._chatEpoch++;
911
1133
  this._destroyAbortControllers();
1134
+ this._cancelActiveDebounce();
912
1135
  this._pendingInteractionPromise = null;
913
1136
  this._activeAutoContinuationRequestId = null;
914
1137
  this._activeAutoContinuationConnectionId = null;
915
1138
  this._clearAllAutoContinuationState(true);
1139
+ this._pendingChatResponseResults.length = 0;
916
1140
  }
917
1141
  async _awaitWithDeadline(promise, deadline) {
918
1142
  if (deadline == null) return promise;
@@ -931,9 +1155,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
931
1155
  * Run a chat turn exclusively so `_reply()` never overlaps with another
932
1156
  * streaming turn.
933
1157
  */
934
- async _runExclusiveChatTurn(requestId, fn) {
1158
+ async _runExclusiveChatTurn(requestId, fn, options) {
935
1159
  const previousTurn = this._chatTurnQueue;
936
1160
  let releaseTurn = () => {};
1161
+ const epoch = options?.epoch ?? this._chatEpoch;
1162
+ this._queuedChatTurnCountsByEpoch.set(epoch, (this._queuedChatTurnCountsByEpoch.get(epoch) ?? 0) + 1);
937
1163
  this._chatTurnQueue = new Promise((resolve) => {
938
1164
  releaseTurn = resolve;
939
1165
  });
@@ -943,7 +1169,29 @@ var AIChatAgent = class AIChatAgent extends Agent {
943
1169
  return await fn();
944
1170
  } finally {
945
1171
  this._activeChatTurnRequestId = null;
1172
+ const nextCount = (this._queuedChatTurnCountsByEpoch.get(epoch) ?? 1) - 1;
1173
+ if (nextCount <= 0) {
1174
+ this._queuedChatTurnCountsByEpoch.delete(epoch);
1175
+ this._mergeQueuedUserStartIndexByEpoch.delete(epoch);
1176
+ } else this._queuedChatTurnCountsByEpoch.set(epoch, nextCount);
946
1177
  releaseTurn();
1178
+ if (this._pendingChatResponseResults.length > 0 && !this._insideResponseHook) {
1179
+ this._insideResponseHook = true;
1180
+ try {
1181
+ await this.keepAliveWhile(async () => {
1182
+ while (this._pendingChatResponseResults.length > 0) {
1183
+ const result = this._pendingChatResponseResults.shift();
1184
+ try {
1185
+ await this.onChatResponse(result);
1186
+ } catch (hookError) {
1187
+ console.error("[AIChatAgent] onChatResponse threw:", hookError);
1188
+ }
1189
+ }
1190
+ });
1191
+ } finally {
1192
+ this._insideResponseHook = false;
1193
+ }
1194
+ }
947
1195
  }
948
1196
  }
949
1197
  _enqueueAutoContinuation(connection, clientTools, body, errorPrefix, prerequisite) {
@@ -1033,12 +1281,32 @@ var AIChatAgent = class AIChatAgent extends Agent {
1033
1281
  } finally {
1034
1282
  dispose();
1035
1283
  }
1036
- }).catch((error) => {
1284
+ }, { epoch }).catch((error) => {
1037
1285
  const errorPrefix = this._pendingAutoContinuationErrorPrefix ?? "[AIChatAgent] Auto-continuation failed:";
1038
1286
  this._clearAllAutoContinuationState(true);
1039
1287
  console.error(errorPrefix, error);
1040
1288
  });
1041
1289
  }
1290
+ async _runProgrammaticChatTurn(requestId, clientTools, body) {
1291
+ this._setRequestContext(clientTools, body);
1292
+ await this._tryCatchChat(async () => {
1293
+ return __DO_NOT_USE_WILL_BREAK__agentContext.run({
1294
+ agent: this,
1295
+ connection: void 0,
1296
+ request: void 0,
1297
+ email: void 0
1298
+ }, async () => {
1299
+ const abortSignal = this._getAbortSignal(requestId);
1300
+ const response = await this.onChatMessage(() => {}, {
1301
+ requestId,
1302
+ abortSignal,
1303
+ clientTools,
1304
+ body
1305
+ });
1306
+ if (response) await this._reply(requestId, response, [], { chatMessageId: requestId });
1307
+ });
1308
+ });
1309
+ }
1042
1310
  /**
1043
1311
  * Handle incoming chat messages and generate a response
1044
1312
  * @param onFinish Callback to be called when the response is finished
@@ -1049,6 +1317,33 @@ var AIChatAgent = class AIChatAgent extends Agent {
1049
1317
  throw new Error("received a chat message, override onChatMessage and return a Response to send to the client");
1050
1318
  }
1051
1319
  /**
1320
+ * Called after a chat turn completes and the assistant message has been
1321
+ * persisted. The turn lock is released before this hook runs, so it is
1322
+ * safe to call `saveMessages` from inside.
1323
+ *
1324
+ * Fires for all turn completion paths: WebSocket chat requests,
1325
+ * `saveMessages`, and auto-continuation.
1326
+ *
1327
+ * Responses triggered from inside `onChatResponse` (e.g. via `saveMessages`)
1328
+ * do not fire `onChatResponse` recursively.
1329
+ *
1330
+ * The default implementation is a no-op.
1331
+ *
1332
+ * @param result - Information about the completed turn
1333
+ *
1334
+ * @example
1335
+ * ```ts
1336
+ * class MyAgent extends AIChatAgent<Env> {
1337
+ * protected async onChatResponse(result: ChatResponseResult) {
1338
+ * if (result.status === "completed") {
1339
+ * this.broadcast(JSON.stringify({ streaming: false }));
1340
+ * }
1341
+ * }
1342
+ * }
1343
+ * ```
1344
+ */
1345
+ onChatResponse(_result) {}
1346
+ /**
1052
1347
  * Override this method to apply custom transformations to messages before
1053
1348
  * they are persisted to storage. This hook runs **after** the built-in
1054
1349
  * sanitization (OpenAI metadata stripping, Anthropic provider-executed tool
@@ -1083,28 +1378,51 @@ var AIChatAgent = class AIChatAgent extends Agent {
1083
1378
  return message;
1084
1379
  }
1085
1380
  /**
1086
- * Save messages on the server side
1087
- * @param messages Chat messages to save
1381
+ * Persist messages and trigger `onChatMessage()` for a new response.
1382
+ *
1383
+ * Waits for any active chat turn to finish before starting, so scheduled
1384
+ * or programmatic messages never overlap an in-flight stream.
1385
+ *
1386
+ * Pass a function to derive the next message list from the latest
1387
+ * persisted `this.messages` when the turn actually starts. This avoids
1388
+ * stale baselines when multiple `saveMessages()` calls queue up behind
1389
+ * active work:
1390
+ *
1391
+ * ```ts
1392
+ * await this.saveMessages((messages) => [...messages, syntheticMessage]);
1393
+ * ```
1394
+ *
1395
+ * Returns `{ requestId, status }` so callers can detect whether the turn
1396
+ * ran (`"completed"`) or was skipped because the chat was cleared
1397
+ * (`"skipped"`).
1088
1398
  */
1089
1399
  async saveMessages(messages) {
1090
1400
  const requestId = nanoid();
1091
1401
  const clientTools = this._lastClientTools;
1092
1402
  const body = this._lastBody;
1093
1403
  const epoch = this._chatEpoch;
1404
+ let status = "completed";
1094
1405
  await this._runExclusiveChatTurn(requestId, async () => {
1095
- if (this._chatEpoch !== epoch) return;
1096
- await this.persistMessages(messages);
1097
- await this._tryCatchChat(async () => {
1098
- const abortSignal = this._getAbortSignal(requestId);
1099
- const response = await this.onChatMessage(() => {}, {
1100
- requestId,
1101
- abortSignal,
1102
- clientTools,
1103
- body
1104
- });
1105
- if (response) await this._reply(requestId, response, [], { chatMessageId: requestId });
1106
- });
1107
- });
1406
+ if (this._chatEpoch !== epoch) {
1407
+ status = "skipped";
1408
+ return;
1409
+ }
1410
+ const resolvedMessages = typeof messages === "function" ? await messages(this.messages) : messages;
1411
+ if (this._chatEpoch !== epoch) {
1412
+ status = "skipped";
1413
+ return;
1414
+ }
1415
+ await this.persistMessages(resolvedMessages);
1416
+ if (this._chatEpoch !== epoch) {
1417
+ status = "skipped";
1418
+ return;
1419
+ }
1420
+ await this._runProgrammaticChatTurn(requestId, clientTools, body);
1421
+ }, { epoch });
1422
+ return {
1423
+ requestId,
1424
+ status
1425
+ };
1108
1426
  }
1109
1427
  async persistMessages(messages, excludeBroadcastIds = [], options) {
1110
1428
  const mergedMessages = this._mergeIncomingWithServerState(messages);
@@ -1647,11 +1965,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
1647
1965
  let readResult;
1648
1966
  try {
1649
1967
  readResult = await reader.read();
1650
- } catch {
1651
- break;
1968
+ } catch (readError) {
1969
+ if (abortSignal?.aborted) break;
1970
+ throw readError;
1652
1971
  }
1653
1972
  const { done, value } = readResult;
1654
1973
  if (done) {
1974
+ if (abortSignal?.aborted) break;
1655
1975
  this._completeStream(streamId);
1656
1976
  streamCompleted.value = true;
1657
1977
  this._broadcastChatMessage({
@@ -1661,7 +1981,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1661
1981
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1662
1982
  ...continuation && { continuation: true }
1663
1983
  });
1664
- break;
1984
+ return "completed";
1665
1985
  }
1666
1986
  const lines = decoder.decode(value).split("\n");
1667
1987
  for (const line of lines) if (line.startsWith("data: ") && line !== "data: [DONE]") try {
@@ -1761,7 +2081,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
1761
2081
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1762
2082
  ...continuation && { continuation: true }
1763
2083
  });
2084
+ return "aborted";
1764
2085
  }
2086
+ return "completed";
1765
2087
  }
1766
2088
  async _sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation = false, abortSignal) {
1767
2089
  this._broadcastTextEvent(streamId, {
@@ -1782,11 +2104,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
1782
2104
  let readResult;
1783
2105
  try {
1784
2106
  readResult = await reader.read();
1785
- } catch {
1786
- break;
2107
+ } catch (readError) {
2108
+ if (abortSignal?.aborted) break;
2109
+ throw readError;
1787
2110
  }
1788
2111
  const { done, value } = readResult;
1789
2112
  if (done) {
2113
+ if (abortSignal?.aborted) break;
1790
2114
  textPart.state = "done";
1791
2115
  this._broadcastTextEvent(streamId, {
1792
2116
  type: "text-end",
@@ -1801,7 +2125,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1801
2125
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1802
2126
  ...continuation && { continuation: true }
1803
2127
  });
1804
- break;
2128
+ return "completed";
1805
2129
  }
1806
2130
  const chunk = decoder.decode(value);
1807
2131
  if (chunk.length > 0) {
@@ -1829,7 +2153,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
1829
2153
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1830
2154
  ...continuation && { continuation: true }
1831
2155
  });
2156
+ return "aborted";
1832
2157
  }
2158
+ return "completed";
1833
2159
  }
1834
2160
  /**
1835
2161
  * Applies a tool approval response from the client, updating the persisted message.
@@ -1875,10 +2201,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
1875
2201
  this._streamingMessage = message;
1876
2202
  const isSSE = (response.headers.get("content-type") || "").includes("text/event-stream");
1877
2203
  const streamCompleted = { value: false };
2204
+ let streamEndStatus = "completed";
1878
2205
  let earlyPersistedId = null;
1879
2206
  try {
1880
- if (isSSE) await this._streamSSEReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
1881
- else await this._sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
2207
+ if (isSSE) streamEndStatus = await this._streamSSEReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
2208
+ else streamEndStatus = await this._sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
1882
2209
  } catch (error) {
1883
2210
  if (!streamCompleted.value) {
1884
2211
  this._markStreamError(streamId);
@@ -1891,6 +2218,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
1891
2218
  ...continuation && { continuation: true }
1892
2219
  });
1893
2220
  this._emit("message:error", { error: error instanceof Error ? error.message : String(error) });
2221
+ this._pendingChatResponseResults.push({
2222
+ message,
2223
+ requestId: id,
2224
+ continuation,
2225
+ status: "error",
2226
+ error: error instanceof Error ? error.message : String(error)
2227
+ });
1894
2228
  }
1895
2229
  throw error;
1896
2230
  } finally {
@@ -1921,6 +2255,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
1921
2255
  await this.persistMessages(updatedMessages, excludeBroadcastIds);
1922
2256
  } else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
1923
2257
  } else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
2258
+ this._pendingChatResponseResults.push({
2259
+ message,
2260
+ requestId: id,
2261
+ continuation,
2262
+ status: streamEndStatus
2263
+ });
1924
2264
  }));
1925
2265
  }
1926
2266
  /**