@cloudflare/ai-chat 0.2.5 → 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();
@@ -742,6 +793,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
742
793
  /** @internal Delegate to _resumableStream */
743
794
  _markStreamError(streamId) {
744
795
  this._resumableStream.markError(streamId);
796
+ this._pendingResumeConnections.clear();
745
797
  }
746
798
  /**
747
799
  * Reconstruct and persist a partial assistant message from an orphaned
@@ -865,6 +917,176 @@ var AIChatAgent = class AIChatAgent extends Agent {
865
917
  await queue;
866
918
  } while (this._chatTurnQueue !== queue);
867
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
+ }
868
1090
  /** `true` when an assistant message is waiting on a client tool result or approval. */
869
1091
  hasPendingInteraction() {
870
1092
  if (this._streamingMessage && this._messageHasPendingInteraction(this._streamingMessage)) return true;
@@ -906,12 +1128,15 @@ var AIChatAgent = class AIChatAgent extends Agent {
906
1128
  * the built-in handler calls it automatically.
907
1129
  */
908
1130
  resetTurnState() {
1131
+ this._mergeQueuedUserStartIndexByEpoch.delete(this._chatEpoch);
909
1132
  this._chatEpoch++;
910
1133
  this._destroyAbortControllers();
1134
+ this._cancelActiveDebounce();
911
1135
  this._pendingInteractionPromise = null;
912
1136
  this._activeAutoContinuationRequestId = null;
913
1137
  this._activeAutoContinuationConnectionId = null;
914
1138
  this._clearAllAutoContinuationState(true);
1139
+ this._pendingChatResponseResults.length = 0;
915
1140
  }
916
1141
  async _awaitWithDeadline(promise, deadline) {
917
1142
  if (deadline == null) return promise;
@@ -930,9 +1155,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
930
1155
  * Run a chat turn exclusively so `_reply()` never overlaps with another
931
1156
  * streaming turn.
932
1157
  */
933
- async _runExclusiveChatTurn(requestId, fn) {
1158
+ async _runExclusiveChatTurn(requestId, fn, options) {
934
1159
  const previousTurn = this._chatTurnQueue;
935
1160
  let releaseTurn = () => {};
1161
+ const epoch = options?.epoch ?? this._chatEpoch;
1162
+ this._queuedChatTurnCountsByEpoch.set(epoch, (this._queuedChatTurnCountsByEpoch.get(epoch) ?? 0) + 1);
936
1163
  this._chatTurnQueue = new Promise((resolve) => {
937
1164
  releaseTurn = resolve;
938
1165
  });
@@ -942,7 +1169,29 @@ var AIChatAgent = class AIChatAgent extends Agent {
942
1169
  return await fn();
943
1170
  } finally {
944
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);
945
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
+ }
946
1195
  }
947
1196
  }
948
1197
  _enqueueAutoContinuation(connection, clientTools, body, errorPrefix, prerequisite) {
@@ -1032,12 +1281,32 @@ var AIChatAgent = class AIChatAgent extends Agent {
1032
1281
  } finally {
1033
1282
  dispose();
1034
1283
  }
1035
- }).catch((error) => {
1284
+ }, { epoch }).catch((error) => {
1036
1285
  const errorPrefix = this._pendingAutoContinuationErrorPrefix ?? "[AIChatAgent] Auto-continuation failed:";
1037
1286
  this._clearAllAutoContinuationState(true);
1038
1287
  console.error(errorPrefix, error);
1039
1288
  });
1040
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
+ }
1041
1310
  /**
1042
1311
  * Handle incoming chat messages and generate a response
1043
1312
  * @param onFinish Callback to be called when the response is finished
@@ -1048,6 +1317,33 @@ var AIChatAgent = class AIChatAgent extends Agent {
1048
1317
  throw new Error("received a chat message, override onChatMessage and return a Response to send to the client");
1049
1318
  }
1050
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
+ /**
1051
1347
  * Override this method to apply custom transformations to messages before
1052
1348
  * they are persisted to storage. This hook runs **after** the built-in
1053
1349
  * sanitization (OpenAI metadata stripping, Anthropic provider-executed tool
@@ -1082,28 +1378,51 @@ var AIChatAgent = class AIChatAgent extends Agent {
1082
1378
  return message;
1083
1379
  }
1084
1380
  /**
1085
- * Save messages on the server side
1086
- * @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"`).
1087
1398
  */
1088
1399
  async saveMessages(messages) {
1089
1400
  const requestId = nanoid();
1090
1401
  const clientTools = this._lastClientTools;
1091
1402
  const body = this._lastBody;
1092
1403
  const epoch = this._chatEpoch;
1404
+ let status = "completed";
1093
1405
  await this._runExclusiveChatTurn(requestId, async () => {
1094
- if (this._chatEpoch !== epoch) return;
1095
- await this.persistMessages(messages);
1096
- await this._tryCatchChat(async () => {
1097
- const abortSignal = this._getAbortSignal(requestId);
1098
- const response = await this.onChatMessage(() => {}, {
1099
- requestId,
1100
- abortSignal,
1101
- clientTools,
1102
- body
1103
- });
1104
- if (response) await this._reply(requestId, response, [], { chatMessageId: requestId });
1105
- });
1106
- });
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
+ };
1107
1426
  }
1108
1427
  async persistMessages(messages, excludeBroadcastIds = [], options) {
1109
1428
  const mergedMessages = this._mergeIncomingWithServerState(messages);
@@ -1646,11 +1965,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
1646
1965
  let readResult;
1647
1966
  try {
1648
1967
  readResult = await reader.read();
1649
- } catch {
1650
- break;
1968
+ } catch (readError) {
1969
+ if (abortSignal?.aborted) break;
1970
+ throw readError;
1651
1971
  }
1652
1972
  const { done, value } = readResult;
1653
1973
  if (done) {
1974
+ if (abortSignal?.aborted) break;
1654
1975
  this._completeStream(streamId);
1655
1976
  streamCompleted.value = true;
1656
1977
  this._broadcastChatMessage({
@@ -1660,7 +1981,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1660
1981
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1661
1982
  ...continuation && { continuation: true }
1662
1983
  });
1663
- break;
1984
+ return "completed";
1664
1985
  }
1665
1986
  const lines = decoder.decode(value).split("\n");
1666
1987
  for (const line of lines) if (line.startsWith("data: ") && line !== "data: [DONE]") try {
@@ -1760,7 +2081,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
1760
2081
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1761
2082
  ...continuation && { continuation: true }
1762
2083
  });
2084
+ return "aborted";
1763
2085
  }
2086
+ return "completed";
1764
2087
  }
1765
2088
  async _sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation = false, abortSignal) {
1766
2089
  this._broadcastTextEvent(streamId, {
@@ -1781,11 +2104,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
1781
2104
  let readResult;
1782
2105
  try {
1783
2106
  readResult = await reader.read();
1784
- } catch {
1785
- break;
2107
+ } catch (readError) {
2108
+ if (abortSignal?.aborted) break;
2109
+ throw readError;
1786
2110
  }
1787
2111
  const { done, value } = readResult;
1788
2112
  if (done) {
2113
+ if (abortSignal?.aborted) break;
1789
2114
  textPart.state = "done";
1790
2115
  this._broadcastTextEvent(streamId, {
1791
2116
  type: "text-end",
@@ -1800,7 +2125,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1800
2125
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1801
2126
  ...continuation && { continuation: true }
1802
2127
  });
1803
- break;
2128
+ return "completed";
1804
2129
  }
1805
2130
  const chunk = decoder.decode(value);
1806
2131
  if (chunk.length > 0) {
@@ -1828,7 +2153,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
1828
2153
  type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
1829
2154
  ...continuation && { continuation: true }
1830
2155
  });
2156
+ return "aborted";
1831
2157
  }
2158
+ return "completed";
1832
2159
  }
1833
2160
  /**
1834
2161
  * Applies a tool approval response from the client, updating the persisted message.
@@ -1874,10 +2201,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
1874
2201
  this._streamingMessage = message;
1875
2202
  const isSSE = (response.headers.get("content-type") || "").includes("text/event-stream");
1876
2203
  const streamCompleted = { value: false };
2204
+ let streamEndStatus = "completed";
1877
2205
  let earlyPersistedId = null;
1878
2206
  try {
1879
- if (isSSE) await this._streamSSEReply(id, streamId, reader, message, streamCompleted, continuation, abortSignal);
1880
- 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);
1881
2209
  } catch (error) {
1882
2210
  if (!streamCompleted.value) {
1883
2211
  this._markStreamError(streamId);
@@ -1890,6 +2218,13 @@ var AIChatAgent = class AIChatAgent extends Agent {
1890
2218
  ...continuation && { continuation: true }
1891
2219
  });
1892
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
+ });
1893
2228
  }
1894
2229
  throw error;
1895
2230
  } finally {
@@ -1920,6 +2255,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
1920
2255
  await this.persistMessages(updatedMessages, excludeBroadcastIds);
1921
2256
  } else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
1922
2257
  } else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
2258
+ this._pendingChatResponseResults.push({
2259
+ message,
2260
+ requestId: id,
2261
+ continuation,
2262
+ status: streamEndStatus
2263
+ });
1923
2264
  }));
1924
2265
  }
1925
2266
  /**