@cloudflare/ai-chat 0.3.2 → 0.4.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.d.ts CHANGED
@@ -1,13 +1,38 @@
1
- import { Agent, AgentContext } from "agents";
1
+ import { Agent, AgentContext, FiberRecoveryContext } from "agents";
2
2
  import {
3
3
  ClientToolSchema,
4
4
  ClientToolSchema as ClientToolSchema$1,
5
+ MessagePart,
5
6
  ResumableStream,
6
7
  createToolsFromClientSchemas
7
8
  } from "agents/chat";
8
9
  import { StreamTextOnFinishCallback, ToolSet, UIMessage } from "ai";
9
10
 
10
11
  //#region src/index.d.ts
12
+ /**
13
+ * Context passed to `onChatRecovery` when an interrupted chat stream
14
+ * is detected after DO restart.
15
+ */
16
+ type ChatRecoveryContext = {
17
+ /** Stream ID from the interrupted stream. */ streamId: string /** Request ID from the interrupted stream. */;
18
+ requestId: string /** Partial text extracted from stored chunks. */;
19
+ partialText: string /** Partial message parts reconstructed from chunks. */;
20
+ partialParts: MessagePart[] /** Checkpoint data from `this.stash()` during the interrupted stream. */;
21
+ recoveryData: unknown | null /** Current persisted messages. */;
22
+ messages: UIMessage[] /** Custom body from the last chat request. */;
23
+ lastBody?: Record<
24
+ string,
25
+ unknown
26
+ > /** Client tool schemas from the last chat request. */;
27
+ lastClientTools?: ClientToolSchema$1[];
28
+ };
29
+ /**
30
+ * Options returned from `onChatRecovery` to control recovery behavior.
31
+ */
32
+ type ChatRecoveryOptions = {
33
+ /** Save the partial response from stored chunks. Default: true. */ persist?: boolean /** Schedule a continuation via continueLastTurn(). Default: true. */;
34
+ continue?: boolean;
35
+ };
11
36
  type MessageConcurrency =
12
37
  | "queue"
13
38
  | "latest"
@@ -70,6 +95,14 @@ type OnChatMessageOptions = {
70
95
  * chat is cleared via `CF_AGENT_CHAT_CLEAR`.
71
96
  */
72
97
  body?: Record<string, unknown>;
98
+ /**
99
+ * Whether this turn is a continuation of a previous assistant message
100
+ * (auto-continue after tool result, `continueLastTurn`, or recovery).
101
+ *
102
+ * Use this to adjust system prompts, select different models, skip
103
+ * expensive context assembly, or log differently for continuations.
104
+ */
105
+ continuation?: boolean;
73
106
  };
74
107
  /**
75
108
  * Result returned by `saveMessages()`.
@@ -87,10 +120,10 @@ declare class AIChatAgent<
87
120
  State = unknown
88
121
  > extends Agent<Env, State> {
89
122
  /**
90
- * Map of message `id`s to `AbortController`s
91
- * useful to propagate request cancellation signals for any external calls made by the agent
123
+ * Registry of per-request AbortControllers.
124
+ * Used to propagate cancellation signals for any external calls made by the agent.
92
125
  */
93
- private _chatMessageAbortControllers;
126
+ private _abortRegistry;
94
127
  /**
95
128
  * Resumable stream manager -- handles chunk buffering, persistence, and replay.
96
129
  * @internal Protected for testing purposes.
@@ -133,6 +166,12 @@ declare class AIChatAgent<
133
166
  * generation-based invalidation on clear, and active-request tracking.
134
167
  */
135
168
  private _turnQueue;
169
+ /**
170
+ * When true, chat turns are wrapped in `runFiber` for durable execution.
171
+ * Enables `onChatRecovery` hook and `this.stash()` during streaming.
172
+ * Set to `true` in subclasses to enable durable streaming.
173
+ */
174
+ unstable_chatRecovery: boolean;
136
175
  /** First queued overlap message index for merge strategy, keyed by epoch. */
137
176
  private _mergeQueuedUserStartIndexByEpoch;
138
177
  /** Monotonic sequence for overlapping submit-message requests. */
@@ -160,13 +199,13 @@ declare class AIChatAgent<
160
199
  * Stored so they can be passed to onChatMessage during tool continuations.
161
200
  * @internal
162
201
  */
163
- private _lastClientTools;
202
+ protected _lastClientTools: ClientToolSchema$1[] | undefined;
164
203
  /**
165
204
  * Custom body data from the most recent chat request.
166
205
  * Stored so it can be passed to onChatMessage during tool continuations.
167
206
  * @internal
168
207
  */
169
- private _lastBody;
208
+ protected _lastBody: Record<string, unknown> | undefined;
170
209
  /**
171
210
  * Cache of last-persisted JSON for each message ID.
172
211
  * Used for incremental persistence: skip SQL writes for unchanged messages.
@@ -288,7 +327,7 @@ declare class AIChatAgent<
288
327
  * message parts, then persists the result so it survives further refreshes.
289
328
  * @internal
290
329
  */
291
- private _persistOrphanedStream;
330
+ protected _persistOrphanedStream(streamId: string): void;
292
331
  /**
293
332
  * Restore _lastBody and _lastClientTools from SQLite.
294
333
  * Called in the constructor so these values survive DO hibernation.
@@ -453,6 +492,53 @@ declare class AIChatAgent<
453
492
  | UIMessage[]
454
493
  | ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>)
455
494
  ): Promise<SaveMessagesResult>;
495
+ /**
496
+ * Trigger a continuation of the last assistant message without inserting
497
+ * a new user message. The LLM sees the full conversation (including the
498
+ * partial assistant response) and generates a continuation that appends
499
+ * to the same message.
500
+ *
501
+ * This uses `continuation: true` in `_reply`, which clones the last
502
+ * assistant message and appends new parts to it — the same mechanism
503
+ * used by tool auto-continuation.
504
+ *
505
+ * Returns early if there is no assistant message to continue from.
506
+ */
507
+ protected continueLastTurn(
508
+ body?: Record<string, unknown>
509
+ ): Promise<SaveMessagesResult>;
510
+ /**
511
+ * Context passed to `onChatRecovery` when an interrupted chat stream
512
+ * is detected after DO restart.
513
+ */
514
+ static readonly CHAT_FIBER_NAME = "__cf_internal_chat_turn";
515
+ /**
516
+ * Intercept internal chat fibers before they reach the user's
517
+ * `onFiberRecovered` hook. Maps to `onChatRecovery`.
518
+ * @internal
519
+ */
520
+ protected _handleInternalFiberRecovery(
521
+ ctx: FiberRecoveryContext
522
+ ): Promise<boolean>;
523
+ /**
524
+ * Called when an interrupted chat stream is detected after restart.
525
+ * Return options to control recovery:
526
+ *
527
+ * - `{}` (default): persist partial response + schedule continuation
528
+ * - `{ continue: false }`: persist but don't continue
529
+ * - `{ persist: false, continue: false }`: handle everything yourself
530
+ *
531
+ * `ctx.recoveryData` contains any data checkpointed via `this.stash()`
532
+ * during streaming (e.g., OpenAI `responseId`).
533
+ */
534
+ protected onChatRecovery(
535
+ _ctx: ChatRecoveryContext
536
+ ): Promise<ChatRecoveryOptions>;
537
+ _chatRecoveryContinue(data?: { targetAssistantId?: string }): Promise<void>;
538
+ /**
539
+ * Extract partial text and parts from stored stream chunks.
540
+ */
541
+ private _getPartialStreamText;
456
542
  persistMessages(
457
543
  messages: UIMessage[],
458
544
  excludeBroadcastIds?: string[],
@@ -595,25 +681,6 @@ declare class AIChatAgent<
595
681
  */
596
682
  private _applyToolApproval;
597
683
  private _reply;
598
- /**
599
- * For the given message id, look up its associated AbortController
600
- * If the AbortController does not exist, create and store one in memory
601
- *
602
- * returns the AbortSignal associated with the AbortController
603
- */
604
- private _getAbortSignal;
605
- /**
606
- * Remove an abort controller from the cache of pending message responses
607
- */
608
- private _removeAbortController;
609
- /**
610
- * Propagate an abort signal for any requests associated with the given message id
611
- */
612
- private _cancelChatRequest;
613
- /**
614
- * Abort all pending requests and clear the cache of AbortControllers
615
- */
616
- private _destroyAbortControllers;
617
684
  /**
618
685
  * When the DO is destroyed, cancel all pending requests and clean up resources
619
686
  */
@@ -622,6 +689,8 @@ declare class AIChatAgent<
622
689
  //#endregion
623
690
  export {
624
691
  AIChatAgent,
692
+ ChatRecoveryContext,
693
+ ChatRecoveryOptions,
625
694
  ChatResponseResult,
626
695
  type ClientToolSchema,
627
696
  MessageConcurrency,
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { MessageType } from "./types.js";
2
2
  import { autoTransformMessages } from "./ai-chat-v5-migration.js";
3
3
  import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
4
- import { ContinuationState, ROW_MAX_BYTES, ResumableStream, TurnQueue, applyChunkToParts, byteLength, createToolsFromClientSchemas, sanitizeMessage } from "agents/chat";
4
+ import { AbortRegistry, ContinuationState, ROW_MAX_BYTES, ResumableStream, TurnQueue, applyChunkToParts, byteLength, createToolsFromClientSchemas, sanitizeMessage } from "agents/chat";
5
5
  import { nanoid } from "nanoid";
6
6
  //#region src/message-reconciler.ts
7
7
  /**
@@ -166,6 +166,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
166
166
  this._pendingInteractionPromise = null;
167
167
  this._approvalPersistedMessageId = null;
168
168
  this._turnQueue = new TurnQueue();
169
+ this.unstable_chatRecovery = false;
169
170
  this._mergeQueuedUserStartIndexByEpoch = /* @__PURE__ */ new Map();
170
171
  this._submitSequence = 0;
171
172
  this._latestOverlappingSubmitSequence = 0;
@@ -189,7 +190,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
189
190
  this._restoreRequestContext();
190
191
  this._resumableStream = new ResumableStream(this.sql.bind(this));
191
192
  this.messages = autoTransformMessages(this._loadMessagesFromDb());
192
- this._chatMessageAbortControllers = /* @__PURE__ */ new Map();
193
+ this._abortRegistry = new AbortRegistry();
193
194
  const _onConnect = this.onConnect.bind(this);
194
195
  this.onConnect = async (connection, ctx) => {
195
196
  if (this._resumableStream.hasActiveStream()) this._notifyStreamResuming(connection);
@@ -277,7 +278,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
277
278
  }
278
279
  this._setRequestContext(requestClientTools, requestBody);
279
280
  this._emit("message:request");
280
- const abortSignal = this._getAbortSignal(chatMessageId);
281
+ const abortSignal = this._abortRegistry.getSignal(chatMessageId);
281
282
  return this._tryCatchChat(async () => {
282
283
  return __DO_NOT_USE_WILL_BREAK__agentContext.run({
283
284
  agent: this,
@@ -285,22 +286,33 @@ var AIChatAgent = class AIChatAgent extends Agent {
285
286
  request: void 0,
286
287
  email: void 0
287
288
  }, async () => {
288
- const response = await this.onChatMessage(async (_finishResult) => {}, {
289
- requestId: chatMessageId,
290
- abortSignal,
291
- clientTools: requestClientTools,
292
- body: requestBody
289
+ const chatTurnBody = async () => {
290
+ try {
291
+ const response = await this.onChatMessage(async (_finishResult) => {}, {
292
+ requestId: chatMessageId,
293
+ abortSignal,
294
+ clientTools: requestClientTools,
295
+ body: requestBody,
296
+ continuation: false
297
+ });
298
+ if (response) await this._reply(chatMessageId, response, [connection.id], { chatMessageId });
299
+ else {
300
+ console.warn(`[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`);
301
+ this._broadcastChatMessage({
302
+ body: "No response was generated by the agent.",
303
+ done: true,
304
+ id: chatMessageId,
305
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
306
+ }, [connection.id]);
307
+ }
308
+ } finally {
309
+ this._abortRegistry.remove(chatMessageId);
310
+ }
311
+ };
312
+ if (this.unstable_chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${chatMessageId}`, async () => {
313
+ await chatTurnBody();
293
314
  });
294
- if (response) await this._reply(chatMessageId, response, [connection.id], { chatMessageId });
295
- else {
296
- console.warn(`[AIChatAgent] onChatMessage returned no response for chatMessageId: ${chatMessageId}`);
297
- this._broadcastChatMessage({
298
- body: "No response was generated by the agent.",
299
- done: true,
300
- id: chatMessageId,
301
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
302
- }, [connection.id]);
303
- }
315
+ else await chatTurnBody();
304
316
  });
305
317
  });
306
318
  }, {
@@ -328,7 +340,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
328
340
  return;
329
341
  }
330
342
  if (data.type === MessageType.CF_AGENT_CHAT_REQUEST_CANCEL) {
331
- this._cancelChatRequest(data.id);
343
+ this._abortRegistry.cancel(data.id);
332
344
  this._emit("message:cancel", { requestId: data.id });
333
345
  return;
334
346
  }
@@ -819,7 +831,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
819
831
  }
820
832
  abortActiveTurn() {
821
833
  if (!this._turnQueue.activeRequestId) return false;
822
- this._cancelChatRequest(this._turnQueue.activeRequestId);
834
+ this._abortRegistry.cancel(this._turnQueue.activeRequestId);
823
835
  return true;
824
836
  }
825
837
  /**
@@ -830,7 +842,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
830
842
  resetTurnState() {
831
843
  this._mergeQueuedUserStartIndexByEpoch.delete(this._turnQueue.generation);
832
844
  this._turnQueue.reset();
833
- this._destroyAbortControllers();
845
+ this._abortRegistry.destroyAll();
834
846
  this._cancelActiveDebounce();
835
847
  this._pendingInteractionPromise = null;
836
848
  this._continuation.sendResumeNone();
@@ -941,7 +953,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
941
953
  const clientTools = this._continuation.pending?.clientTools;
942
954
  const body = this._continuation.pending?.body;
943
955
  if (this._continuation.pending) this._continuation.pending.pastCoalesce = true;
944
- const abortSignal = this._getAbortSignal(requestId);
956
+ const abortSignal = this._abortRegistry.getSignal(requestId);
945
957
  return this._tryCatchChat(async () => {
946
958
  return __DO_NOT_USE_WILL_BREAK__agentContext.run({
947
959
  agent: this,
@@ -949,22 +961,33 @@ var AIChatAgent = class AIChatAgent extends Agent {
949
961
  request: void 0,
950
962
  email: void 0
951
963
  }, async () => {
952
- const response = await this.onChatMessage(async (_finishResult) => {}, {
953
- requestId,
954
- abortSignal,
955
- clientTools,
956
- body
964
+ const autoContinuationBody = async () => {
965
+ try {
966
+ const response = await this.onChatMessage(async (_finishResult) => {}, {
967
+ requestId,
968
+ abortSignal,
969
+ clientTools,
970
+ body,
971
+ continuation: true
972
+ });
973
+ if (response) {
974
+ await this._reply(requestId, response, [], {
975
+ continuation: true,
976
+ chatMessageId: requestId
977
+ });
978
+ this._activateDeferredAutoContinuation();
979
+ } else {
980
+ this._clearPendingAutoContinuation(true);
981
+ this._activateDeferredAutoContinuation();
982
+ }
983
+ } finally {
984
+ this._abortRegistry.remove(requestId);
985
+ }
986
+ };
987
+ if (this.unstable_chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
988
+ await autoContinuationBody();
957
989
  });
958
- if (response) {
959
- await this._reply(requestId, response, [], {
960
- continuation: true,
961
- chatMessageId: requestId
962
- });
963
- this._activateDeferredAutoContinuation();
964
- } else {
965
- this._clearPendingAutoContinuation(true);
966
- this._activateDeferredAutoContinuation();
967
- }
990
+ else await autoContinuationBody();
968
991
  });
969
992
  });
970
993
  } finally {
@@ -988,14 +1011,25 @@ var AIChatAgent = class AIChatAgent extends Agent {
988
1011
  request: void 0,
989
1012
  email: void 0
990
1013
  }, async () => {
991
- const abortSignal = this._getAbortSignal(requestId);
992
- const response = await this.onChatMessage(() => {}, {
993
- requestId,
994
- abortSignal,
995
- clientTools,
996
- body
1014
+ const abortSignal = this._abortRegistry.getSignal(requestId);
1015
+ const programmaticBody = async () => {
1016
+ try {
1017
+ const response = await this.onChatMessage(() => {}, {
1018
+ requestId,
1019
+ abortSignal,
1020
+ clientTools,
1021
+ body,
1022
+ continuation: false
1023
+ });
1024
+ if (response) await this._reply(requestId, response, [], { chatMessageId: requestId });
1025
+ } finally {
1026
+ this._abortRegistry.remove(requestId);
1027
+ }
1028
+ };
1029
+ if (this.unstable_chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
1030
+ await programmaticBody();
997
1031
  });
998
- if (response) await this._reply(requestId, response, [], { chatMessageId: requestId });
1032
+ else await programmaticBody();
999
1033
  });
1000
1034
  });
1001
1035
  }
@@ -1113,6 +1147,154 @@ var AIChatAgent = class AIChatAgent extends Agent {
1113
1147
  status
1114
1148
  };
1115
1149
  }
1150
+ /**
1151
+ * Trigger a continuation of the last assistant message without inserting
1152
+ * a new user message. The LLM sees the full conversation (including the
1153
+ * partial assistant response) and generates a continuation that appends
1154
+ * to the same message.
1155
+ *
1156
+ * This uses `continuation: true` in `_reply`, which clones the last
1157
+ * assistant message and appends new parts to it — the same mechanism
1158
+ * used by tool auto-continuation.
1159
+ *
1160
+ * Returns early if there is no assistant message to continue from.
1161
+ */
1162
+ async continueLastTurn(body) {
1163
+ if (!this._findLastAssistantMessage()) return {
1164
+ requestId: "",
1165
+ status: "skipped"
1166
+ };
1167
+ const requestId = nanoid();
1168
+ const clientTools = this._lastClientTools;
1169
+ const resolvedBody = body ?? this._lastBody;
1170
+ const epoch = this._turnQueue.generation;
1171
+ let status = "completed";
1172
+ await this._runExclusiveChatTurn(requestId, async () => {
1173
+ if (this._turnQueue.generation !== epoch) {
1174
+ status = "skipped";
1175
+ return;
1176
+ }
1177
+ this._setRequestContext(clientTools, resolvedBody);
1178
+ const turnBody = async () => {
1179
+ await this._tryCatchChat(async () => {
1180
+ return __DO_NOT_USE_WILL_BREAK__agentContext.run({
1181
+ agent: this,
1182
+ connection: void 0,
1183
+ request: void 0,
1184
+ email: void 0
1185
+ }, async () => {
1186
+ const abortSignal = this._abortRegistry.getSignal(requestId);
1187
+ try {
1188
+ const response = await this.onChatMessage(() => {}, {
1189
+ requestId,
1190
+ abortSignal,
1191
+ clientTools,
1192
+ body: resolvedBody,
1193
+ continuation: true
1194
+ });
1195
+ if (response) await this._reply(requestId, response, [], {
1196
+ continuation: true,
1197
+ chatMessageId: requestId
1198
+ });
1199
+ } finally {
1200
+ this._abortRegistry.remove(requestId);
1201
+ }
1202
+ });
1203
+ });
1204
+ };
1205
+ if (this.unstable_chatRecovery) await this.runFiber(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
1206
+ await turnBody();
1207
+ });
1208
+ else await turnBody();
1209
+ }, { epoch });
1210
+ if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
1211
+ return {
1212
+ requestId,
1213
+ status
1214
+ };
1215
+ }
1216
+ static {
1217
+ this.CHAT_FIBER_NAME = "__cf_internal_chat_turn";
1218
+ }
1219
+ /**
1220
+ * Intercept internal chat fibers before they reach the user's
1221
+ * `onFiberRecovered` hook. Maps to `onChatRecovery`.
1222
+ * @internal
1223
+ */
1224
+ async _handleInternalFiberRecovery(ctx) {
1225
+ const chatPrefix = this.constructor.CHAT_FIBER_NAME + ":";
1226
+ if (!ctx.name.startsWith(chatPrefix)) return false;
1227
+ const requestId = ctx.name.slice(chatPrefix.length);
1228
+ let streamId = "";
1229
+ if (requestId) {
1230
+ const rows = this.sql`
1231
+ SELECT id FROM cf_ai_chat_stream_metadata
1232
+ WHERE request_id = ${requestId}
1233
+ ORDER BY created_at DESC LIMIT 1
1234
+ `;
1235
+ if (rows.length > 0) streamId = rows[0].id;
1236
+ }
1237
+ if (!streamId && this._resumableStream.hasActiveStream()) streamId = this._resumableStream.activeStreamId ?? "";
1238
+ const partial = streamId ? this._getPartialStreamText(streamId) : {
1239
+ text: "",
1240
+ parts: []
1241
+ };
1242
+ const options = await this.onChatRecovery({
1243
+ streamId: streamId ?? "",
1244
+ requestId,
1245
+ partialText: partial.text,
1246
+ partialParts: partial.parts,
1247
+ recoveryData: ctx.snapshot,
1248
+ messages: [...this.messages],
1249
+ lastBody: this._lastBody,
1250
+ lastClientTools: this._lastClientTools
1251
+ });
1252
+ const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
1253
+ if (options.persist !== false && streamStillActive) this._persistOrphanedStream(streamId);
1254
+ if (streamStillActive) this._resumableStream.complete(streamId);
1255
+ if (options.continue !== false) {
1256
+ const targetId = this._findLastAssistantMessage()?.id;
1257
+ await this.schedule(0, "_chatRecoveryContinue", targetId ? { targetAssistantId: targetId } : void 0, { idempotent: true });
1258
+ }
1259
+ return true;
1260
+ }
1261
+ /**
1262
+ * Called when an interrupted chat stream is detected after restart.
1263
+ * Return options to control recovery:
1264
+ *
1265
+ * - `{}` (default): persist partial response + schedule continuation
1266
+ * - `{ continue: false }`: persist but don't continue
1267
+ * - `{ persist: false, continue: false }`: handle everything yourself
1268
+ *
1269
+ * `ctx.recoveryData` contains any data checkpointed via `this.stash()`
1270
+ * during streaming (e.g., OpenAI `responseId`).
1271
+ */
1272
+ async onChatRecovery(_ctx) {
1273
+ return {};
1274
+ }
1275
+ async _chatRecoveryContinue(data) {
1276
+ if (!await this.waitUntilStable({ timeout: 1e4 })) {
1277
+ console.warn("[AIChatAgent] _chatRecoveryContinue timed out waiting for stable state, skipping continuation");
1278
+ return;
1279
+ }
1280
+ const targetId = data?.targetAssistantId;
1281
+ if (targetId && this._findLastAssistantMessage()?.id !== targetId) return;
1282
+ await this.continueLastTurn();
1283
+ }
1284
+ /**
1285
+ * Extract partial text and parts from stored stream chunks.
1286
+ */
1287
+ _getPartialStreamText(streamId) {
1288
+ const chunks = this._resumableStream.getStreamChunks(streamId);
1289
+ const parts = [];
1290
+ for (const chunk of chunks) try {
1291
+ applyChunkToParts(parts, JSON.parse(chunk.body));
1292
+ } catch {}
1293
+ return {
1294
+ text: parts.filter((p) => p.type === "text" && "text" in p).map((p) => p.text).join(""),
1295
+ parts
1296
+ };
1297
+ }
1116
1298
  async persistMessages(messages, excludeBroadcastIds = [], options) {
1117
1299
  const mergedMessages = reconcileMessages(messages, this.messages, (msg) => this._sanitizeMessageForPersistence(msg));
1118
1300
  for (const message of mergedMessages) {
@@ -1491,6 +1673,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
1491
1673
  }
1492
1674
  async _streamSSEReply(id, streamId, reader, message, streamCompleted, continuation = false, abortSignal) {
1493
1675
  streamCompleted.value = false;
1676
+ let continuationTextResumed = false;
1677
+ let continuationReasoningResumed = false;
1494
1678
  if (abortSignal && !abortSignal.aborted) abortSignal.addEventListener("abort", () => {
1495
1679
  reader.cancel().catch(() => {});
1496
1680
  }, { once: true });
@@ -1520,6 +1704,25 @@ var AIChatAgent = class AIChatAgent extends Agent {
1520
1704
  const lines = decoder.decode(value).split("\n");
1521
1705
  for (const line of lines) if (line.startsWith("data: ") && line !== "data: [DONE]") try {
1522
1706
  const data = JSON.parse(line.slice(6));
1707
+ if (continuation) {
1708
+ if (!continuationTextResumed && data.type === "text-start") {
1709
+ for (let k = message.parts.length - 1; k >= 0; k--) {
1710
+ const part = message.parts[k];
1711
+ if (part.type === "text") {
1712
+ if ("state" in part && part.state === "streaming") continuationTextResumed = true;
1713
+ break;
1714
+ }
1715
+ }
1716
+ if (continuationTextResumed) continue;
1717
+ }
1718
+ if (!continuationReasoningResumed && data.type === "reasoning-start") {
1719
+ for (let k = message.parts.length - 1; k >= 0; k--) if (message.parts[k].type === "reasoning") {
1720
+ continuationReasoningResumed = true;
1721
+ break;
1722
+ }
1723
+ if (continuationReasoningResumed) continue;
1724
+ }
1725
+ }
1523
1726
  const handled = applyChunkToParts(message.parts, data);
1524
1727
  if (data.type === "tool-approval-request" && this._streamingMessage) {
1525
1728
  const snapshot = {
@@ -1624,16 +1827,26 @@ var AIChatAgent = class AIChatAgent extends Agent {
1624
1827
  return "completed";
1625
1828
  }
1626
1829
  async _sendPlaintextReply(id, streamId, reader, message, streamCompleted, continuation = false, abortSignal) {
1627
- this._broadcastTextEvent(streamId, {
1628
- type: "text-start",
1629
- id
1630
- }, continuation);
1631
- const textPart = {
1632
- type: "text",
1633
- text: "",
1634
- state: "streaming"
1635
- };
1636
- message.parts.push(textPart);
1830
+ let textPart;
1831
+ if (continuation) for (let k = message.parts.length - 1; k >= 0; k--) {
1832
+ const part = message.parts[k];
1833
+ if (part.type === "text") {
1834
+ if ("state" in part && part.state === "streaming") textPart = part;
1835
+ break;
1836
+ }
1837
+ }
1838
+ if (textPart) {} else {
1839
+ this._broadcastTextEvent(streamId, {
1840
+ type: "text-start",
1841
+ id
1842
+ }, continuation);
1843
+ textPart = {
1844
+ type: "text",
1845
+ text: "",
1846
+ state: "streaming"
1847
+ };
1848
+ message.parts.push(textPart);
1849
+ }
1637
1850
  if (abortSignal && !abortSignal.aborted) abortSignal.addEventListener("abort", () => {
1638
1851
  reader.cancel().catch(() => {});
1639
1852
  }, { once: true });
@@ -1719,7 +1932,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1719
1932
  }
1720
1933
  async _reply(id, response, excludeBroadcastIds = [], options = {}) {
1721
1934
  const { continuation = false, chatMessageId } = options;
1722
- const abortSignal = chatMessageId ? this._chatMessageAbortControllers.get(chatMessageId)?.signal : void 0;
1935
+ const abortSignal = chatMessageId ? this._abortRegistry.getExistingSignal(chatMessageId) : void 0;
1723
1936
  return this.keepAliveWhile(() => this._tryCatchChat(async () => {
1724
1937
  if (!response.body) {
1725
1938
  this._clearPendingAutoContinuation(true);
@@ -1771,7 +1984,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1771
1984
  earlyPersistedId = this._approvalPersistedMessageId;
1772
1985
  this._approvalPersistedMessageId = null;
1773
1986
  if (chatMessageId) {
1774
- this._removeAbortController(chatMessageId);
1987
+ this._abortRegistry.remove(chatMessageId);
1775
1988
  if (streamCompleted.value) this._emit("message:response");
1776
1989
  }
1777
1990
  }
@@ -1802,40 +2015,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
1802
2015
  }));
1803
2016
  }
1804
2017
  /**
1805
- * For the given message id, look up its associated AbortController
1806
- * If the AbortController does not exist, create and store one in memory
1807
- *
1808
- * returns the AbortSignal associated with the AbortController
1809
- */
1810
- _getAbortSignal(id) {
1811
- if (typeof id !== "string") return;
1812
- if (!this._chatMessageAbortControllers.has(id)) this._chatMessageAbortControllers.set(id, new AbortController());
1813
- return this._chatMessageAbortControllers.get(id)?.signal;
1814
- }
1815
- /**
1816
- * Remove an abort controller from the cache of pending message responses
1817
- */
1818
- _removeAbortController(id) {
1819
- this._chatMessageAbortControllers.delete(id);
1820
- }
1821
- /**
1822
- * Propagate an abort signal for any requests associated with the given message id
1823
- */
1824
- _cancelChatRequest(id) {
1825
- if (this._chatMessageAbortControllers.has(id)) this._chatMessageAbortControllers.get(id)?.abort();
1826
- }
1827
- /**
1828
- * Abort all pending requests and clear the cache of AbortControllers
1829
- */
1830
- _destroyAbortControllers() {
1831
- for (const controller of this._chatMessageAbortControllers.values()) controller?.abort();
1832
- this._chatMessageAbortControllers.clear();
1833
- }
1834
- /**
1835
2018
  * When the DO is destroyed, cancel all pending requests and clean up resources
1836
2019
  */
1837
2020
  async destroy() {
1838
- this._destroyAbortControllers();
2021
+ this._abortRegistry.destroyAll();
1839
2022
  this._resumableStream.destroy();
1840
2023
  await super.destroy();
1841
2024
  }