@cloudflare/ai-chat 0.10.2 → 0.12.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
@@ -1,7 +1,8 @@
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, __DO_NOT_USE_WILL_BREAK__withInvocationScope, isDurableObjectMemoryLimitReset } from "agents";
4
- import { AbortRegistry, AgentToolProgressEmitter, AgentToolStreamProgressThrottle, AutoContinuationController, ChatRecoveryEngine, ChatStreamStalledError, ContinuationState, MAX_BOUND_PARAMS, PreStreamTurns, ResumableStream, ResumeHandshake, STREAM_CLEANUP_DELAY_SECONDS, StreamProgressCreditThrottle, SubmitConcurrencyController, TIMED_OUT, TurnQueue, aiSdkRecoveryCodec, applyChunkToParts, awaitWithDeadline, buildChatRecoveringFrame, buildInClauseStrings, bumpChatRecoveryProgress, chatRecoverySchedulePolicy, classifyAgentToolChildRecovery, cleanupStreamBuffers, clearChatTerminal, clientResolvableToolNames, createChatFiberSnapshot, createToolsFromClientSchemas, drainInteractionApplies, enforceRowSizeLimit, hasIncompleteToolBatch, interceptAgentToolBroadcast, isReplayChunk, iterateWithStallWatchdog, listActiveChatRecoveryIncidents, parseProtocolMessage, partAwaitsClientInteraction, pendingChatTerminal, persistReconstructedOrphan, readChatRecoveryProgress, reconcileMessages, reconcileOrphanPartial, recordChatTerminal, repairInterruptedToolParts, resolveChatRecoveryConfig, resolveToolMergeId, runChatRecoveryExhaustion, sanitizeMessage, sendIfOpen, setChatRecovering, shouldCreditStreamProgress, sweepStaleChatRecoveryIncidents, toolApprovalUpdate, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
4
+ import { AbortRegistry, AgentToolProgressEmitter, AgentToolStreamProgressThrottle, AutoContinuationController, CHAT_RECOVERY_PROGRESS_KEY, CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS, CHAT_RECOVERY_TASK_NAME, ChatRecoveryEngine, ChatStreamStalledError, ContinuationState, PreStreamTurns, ResumableStream, ResumeHandshake, SubmitConcurrencyController, TIMED_OUT, TurnQueue, aiSdkRecoveryCodec, applyChunkToParts, awaitWithDeadline, buildChatRecoveringFrame, chatRecoveryTaskRunOptions, classifyAgentToolChildRecovery, clearChatTerminal, clientResolvableToolNames, createChatFiberSnapshot, createChatRecoveryTaskDefinition, createChatStreams, createChatTurnTaskDefinition, createToolsFromClientSchemas, dispatchChatRecoveryToHandoff, drainInteractionApplies, hasIncompleteToolBatch, interceptAgentToolBroadcast, isReplayChunk, iterateWithStallWatchdog, listActiveChatRecoveryIncidents, parseProtocolMessage, partAwaitsClientInteraction, pendingChatTerminal, persistReconstructedOrphan, readChatRecoveryProgress, reconcileMessages, reconcileOrphanPartial, recordChatTerminal, repairInterruptedToolParts, resolveChatRecoveryConfig, resolveToolMergeId, runChatRecoveryExhaustion, sendIfOpen, setChatRecovering, sweepStaleChatRecoveryIncidents, toolApprovalUpdate, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
5
+ import { Sessions } from "agents/sessions";
5
6
  import { nanoid } from "nanoid";
6
7
  //#region src/index.ts
7
8
  function withAgentSpan(host, operation, storagePhase, attributes, run) {
@@ -43,10 +44,67 @@ const agentToolChunkEncoder = new TextEncoder();
43
44
  * Extension of Agent with built-in chat capabilities
44
45
  * @template Env Environment type containing bindings
45
46
  */
47
+ /** Bounds for one window of the legacy lift: rows and their summed bytes. */
48
+ const LEGACY_LIFT_WINDOW_ROWS = 25;
49
+ const LEGACY_LIFT_WINDOW_BYTES = 4 * 1024 * 1024;
46
50
  var AIChatAgent = class AIChatAgent extends Agent {
51
+ /** The default linear conversation handle. */
52
+ #session;
47
53
  static {
48
54
  this.MESSAGE_DEBOUNCE_MS = 750;
49
55
  }
56
+ /**
57
+ * Register the shared chat-turn Task definition (see
58
+ * `agents/chat` `createChatTurnTaskDefinition` for the turn logic): the
59
+ * host wires its protected internals through the hooks.
60
+ */
61
+ _registerChatTurnTaskDefinition() {
62
+ const chatFiberName = this.constructor.CHAT_FIBER_NAME;
63
+ this.tasks.register(chatFiberName, createChatTurnTaskDefinition({
64
+ definitionName: chatFiberName,
65
+ storage: this.ctx.storage,
66
+ getRunCreatedAt: async (runId) => (await this.tasks.get(runId))?.createdAt ?? null,
67
+ getLiveClosure: (nonce) => this._liveChatTurnClosures.get(nonce),
68
+ keepAliveWhile: (fn) => this.keepAliveWhile(fn),
69
+ withStash: (context, fn) => this._withFiberStash(context, fn),
70
+ handleRecovery: (ctx) => this._handleInternalFiberRecovery(ctx)
71
+ }));
72
+ }
73
+ /** Register the shared Tasks transport for recovery continuations. */
74
+ _registerChatRecoveryTaskDefinition() {
75
+ this.tasks.register(CHAT_RECOVERY_TASK_NAME, createChatRecoveryTaskDefinition({
76
+ _chatRecoveryContinue: (data) => this._chatRecoveryContinue(data),
77
+ _chatRecoveryRetry: (data) => this._chatRecoveryRetry(data)
78
+ }));
79
+ }
80
+ /**
81
+ * Run a queue-driven recovery callback to its model handoff and return;
82
+ * the turn continues as tracked alarm work, and a detached platform
83
+ * failure enqueues one replacement attempt through the same transport.
84
+ */
85
+ _dispatchChatRecovery(callback, data, detached) {
86
+ return dispatchChatRecoveryToHandoff({
87
+ detached,
88
+ track: (turn) => this.lifecycle.trackAlarmWork(turn),
89
+ redefer: (dedupeKey) => this._enqueueChatRecovery(callback, data ?? {}, "redefer", CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS, dedupeKey),
90
+ onDetachedError: (error) => console.error(`[AIChatAgent] ${callback} dispatch failed`, error)
91
+ });
92
+ }
93
+ /**
94
+ * Enqueue one recovery attempt on the shared Tasks transport. Tasks
95
+ * mirrors a routed dynamic agent's wake to the root's alarm; the run
96
+ * itself, and this continuation's replay, still execute here. `dedupeKey`
97
+ * keys a retried enqueue so it joins its own prior attempt instead of
98
+ * duplicating it — see {@link chatRecoveryTaskRunOptions}.
99
+ */
100
+ async _enqueueChatRecovery(callback, data, reason, delaySeconds, dedupeKey) {
101
+ const input = {
102
+ callback,
103
+ data,
104
+ delaySeconds
105
+ };
106
+ await this.tasks.__DO_NOT_USE_WILL_BREAK__enqueue(CHAT_RECOVERY_TASK_NAME, input, chatRecoveryTaskRunOptions(input, reason, dedupeKey));
107
+ }
50
108
  async _runChatRecoveryFiber(requestId, continuation, fn) {
51
109
  const snapshot = createChatFiberSnapshot({
52
110
  kind: "ai-chat-turn",
@@ -57,10 +115,43 @@ var AIChatAgent = class AIChatAgent extends Agent {
57
115
  lastBody: this._lastBody,
58
116
  lastClientTools: this._lastClientTools
59
117
  });
60
- return this._runFiberWithStashWrapper(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => fn(), {
61
- initialSnapshot: wrapChatFiberSnapshot("__cfAIChatFiberSnapshot", snapshot, null),
62
- wrapStash: (data) => wrapChatFiberSnapshot("__cfAIChatFiberSnapshot", snapshot, data)
118
+ const wrap = (data) => wrapChatFiberSnapshot("__cfAIChatFiberSnapshot", snapshot, data);
119
+ if (this.parentPath.length > 0) return this._runFiberWithStashWrapper(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => fn(), {
120
+ initialSnapshot: wrap(null),
121
+ wrapStash: wrap
122
+ });
123
+ const nonce = nanoid();
124
+ let resolveOutcome;
125
+ let rejectOutcome;
126
+ const outcome = new Promise((resolve, reject) => {
127
+ resolveOutcome = resolve;
128
+ rejectOutcome = reject;
129
+ });
130
+ outcome.catch(() => {});
131
+ const ambient = __DO_NOT_USE_WILL_BREAK__agentContext.getStore();
132
+ this._liveChatTurnClosures.set(nonce, {
133
+ initial: wrap(null),
134
+ wrap,
135
+ run: ambient ? () => __DO_NOT_USE_WILL_BREAK__agentContext.run(ambient, fn) : fn,
136
+ settle: {
137
+ resolve: resolveOutcome,
138
+ reject: rejectOutcome
139
+ }
63
140
  });
141
+ try {
142
+ await this.tasks.__DO_NOT_USE_WILL_BREAK__runAttached(this.constructor.CHAT_FIBER_NAME, {
143
+ requestId,
144
+ continuation,
145
+ nonce
146
+ }, {
147
+ runId: `chat_${nonce}`,
148
+ retain: false,
149
+ metadata: { requestId }
150
+ });
151
+ return await outcome;
152
+ } finally {
153
+ this._liveChatTurnClosures.delete(nonce);
154
+ }
64
155
  }
65
156
  broadcast(msg, without) {
66
157
  if (this._agentToolForwarders.size > 0 || this._agentToolLiveSequences.size > 0) interceptAgentToolBroadcast(msg, {
@@ -139,6 +230,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
139
230
  }
140
231
  constructor(ctx, env) {
141
232
  super(ctx, env);
233
+ this.sessions = new Sessions();
234
+ this.hydrationByteBudget = 32 * 1024 * 1024;
235
+ this.#session = this.sessions.session();
236
+ this.streams = createChatStreams();
142
237
  this._streamingMessage = null;
143
238
  this._pendingChatResponseResults = [];
144
239
  this._insideResponseHook = false;
@@ -146,7 +241,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
146
241
  this._interactionApplyTail = Promise.resolve();
147
242
  this._approvalPersistedMessageId = null;
148
243
  this._turnQueue = new TurnQueue();
149
- this.chatRecovery = false;
244
+ this.chatRecovery = true;
150
245
  this.chatStreamStallTimeoutMs = 0;
151
246
  this._mergeQueuedUserStartIndexByEpoch = /* @__PURE__ */ new Map();
152
247
  this._submitConcurrency = new SubmitConcurrencyController({ defaultDebounceMs: AIChatAgent.MESSAGE_DEBOUNCE_MS });
@@ -161,7 +256,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
161
256
  this._agentToolPreTurnAssistantIds = /* @__PURE__ */ new Map();
162
257
  this._agentToolLiveSequences = /* @__PURE__ */ new Map();
163
258
  this._agentToolRunsByRequestId = /* @__PURE__ */ new Map();
164
- this._persistedMessageCache = /* @__PURE__ */ new Map();
165
259
  this._autoContinuation = new AutoContinuationController({
166
260
  continuation: this._continuation,
167
261
  generateRequestId: () => nanoid(),
@@ -176,19 +270,20 @@ var AIChatAgent = class AIChatAgent extends Agent {
176
270
  this.maxPersistedMessages = void 0;
177
271
  this.messageConcurrency = "queue";
178
272
  this.waitForMcpConnections = { timeout: 1e4 };
273
+ this._liveChatTurnClosures = /* @__PURE__ */ new Map();
179
274
  this.messages = [];
180
- this._streamProgressCredit = new StreamProgressCreditThrottle();
181
275
  this._agentToolProgressEmitterInstance = null;
182
276
  this._inSerializedDetachedDeliverySlot = false;
183
277
  this._inFlightDetachedNotifications = /* @__PURE__ */ new Set();
278
+ this._progressSeed = null;
184
279
  this._agentToolStreamProgress = new AgentToolStreamProgressThrottle();
280
+ this.#pendingCutover = null;
281
+ this.lifecycle.use(this.sessions);
282
+ this.lifecycle.use(this.streams);
283
+ this._registerChatTurnTaskDefinition();
284
+ this._registerChatRecoveryTaskDefinition();
185
285
  withAgentSpan(this, "chat_initialization", "initialization", { "cloudflare.agents.component": "ai_chat" }, (update) => {
186
286
  withAgentSpan(this, "initialize_chat_storage", "initialization", { "cloudflare.agents.component": "ai_chat" }, () => {
187
- this.sql`create table if not exists cf_ai_chat_agent_messages (
188
- id text primary key,
189
- message text not null,
190
- created_at datetime default current_timestamp
191
- )`;
192
287
  this.sql`create table if not exists cf_ai_chat_request_context (
193
288
  key text primary key,
194
289
  value text not null
@@ -197,15 +292,22 @@ var AIChatAgent = class AIChatAgent extends Agent {
197
292
  });
198
293
  withAgentSpan(this, "restore_chat_request_context", "initialization", { "cloudflare.agents.component": "ai_chat" }, () => this._restoreRequestContext());
199
294
  withAgentSpan(this, "initialize_resumable_stream", "initialization", { "cloudflare.agents.component": "ai_chat" }, () => {
200
- this._resumableStream = new ResumableStream(this.sql.bind(this));
201
- });
202
- const rawMessages = withAgentSpan(this, "load_chat_messages", "initialization", { "cloudflare.agents.component": "ai_chat" }, () => this._loadMessagesFromDb());
203
- this.messages = autoTransformMessages(rawMessages);
204
- update({
205
- "cloudflare.agents.chat.messages.loaded": rawMessages.length,
206
- "cloudflare.agents.chat.active_stream.restored": this._resumableStream.hasActiveStream()
295
+ this._resumableStream = new ResumableStream(this.streams, this.sql.bind(this), { onProgress: (durable) => {
296
+ this.ctx.storage.put(CHAT_RECOVERY_PROGRESS_KEY, durable).catch(() => {});
297
+ } });
207
298
  });
299
+ update({ "cloudflare.agents.chat.active_stream.restored": this._resumableStream.hasActiveStream() });
208
300
  });
301
+ this.#subscribeToSessionChanges();
302
+ const _onStart = this.onStart.bind(this);
303
+ this.onStart = async (props) => {
304
+ await withAgentSpan(this, "load_chat_messages", "startup", { "cloudflare.agents.component": "ai_chat" }, async (update) => {
305
+ await this._migrateLegacyMessages();
306
+ await this._hydrateMessages();
307
+ update({ "cloudflare.agents.chat.messages.loaded": this.messages.length });
308
+ });
309
+ return _onStart(props);
310
+ };
209
311
  this._abortRegistry = new AbortRegistry();
210
312
  const _onConnect = this.onConnect.bind(this);
211
313
  this.onConnect = async (connection, ctx) => {
@@ -372,8 +474,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
372
474
  this._settlePreStreamTurn(chatMessageId);
373
475
  }
374
476
  };
375
- if (this.chatRecovery) await this._runChatRecoveryFiber(chatMessageId, false, chatTurnBody);
376
- else await chatTurnBody();
477
+ await this._runChatRecoveryFiber(chatMessageId, false, chatTurnBody);
377
478
  });
378
479
  });
379
480
  }, {
@@ -387,7 +488,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
387
488
  }
388
489
  if (event.type === "clear") {
389
490
  this.resetTurnState();
390
- this.sql`delete from cf_ai_chat_agent_messages`;
491
+ await this.#session.clearMessages();
391
492
  await this._clearChatTerminal();
392
493
  this._resumableStream.clearAll();
393
494
  this._pendingResumeConnections.clear();
@@ -396,8 +497,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
396
497
  this._lastClientTools = void 0;
397
498
  this._lastBody = void 0;
398
499
  this._persistRequestContext();
399
- this._persistedMessageCache.clear();
400
- this.messages = [];
401
500
  this._broadcastChatMessage({ type: MessageType.CF_AGENT_CHAT_CLEAR }, [connection.id]);
402
501
  this._emit("message:clear");
403
502
  return;
@@ -461,7 +560,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
461
560
  const _onRequest = this.onRequest.bind(this);
462
561
  this.onRequest = async (request) => {
463
562
  return this._tryCatchChat(async () => {
464
- if (new URL(request.url).pathname.split("/").pop() === "get-messages") return Response.json(this._loadMessagesFromDb());
563
+ if (new URL(request.url).pathname.split("/").pop() === "get-messages") return new Response(this.#streamMessagesAsJson(), { headers: { "content-type": "application/json" } });
465
564
  return _onRequest(request);
466
565
  });
467
566
  };
@@ -591,70 +690,60 @@ var AIChatAgent = class AIChatAgent extends Agent {
591
690
  this._flushAwaitingStreamStartConnections();
592
691
  this._activateDeferredAutoContinuation();
593
692
  }
594
- this._ensureStreamCleanupScheduled();
595
693
  return streamId;
596
694
  }
597
695
  /** @internal Delegate to _resumableStream */
598
696
  _completeStream(streamId) {
599
697
  const completedRequestId = this._resumableStream.activeRequestId;
600
698
  this._resumableStream.complete(streamId);
699
+ this._afterStreamFinished(completedRequestId);
700
+ }
701
+ /**
702
+ * @internal The producer finished; leave the row for the cutover that
703
+ * persists the message (`persistMessages` via `#pendingCutover`). `_reply`'s
704
+ * finally settles it if no persist follows.
705
+ */
706
+ _finishStream(streamId) {
707
+ const finishedRequestId = this._resumableStream.activeRequestId;
708
+ this._resumableStream.finish(streamId);
709
+ this._afterStreamFinished(finishedRequestId);
710
+ }
711
+ _afterStreamFinished(requestId) {
601
712
  this._pendingResumeConnections.clear();
602
- if (completedRequestId === this._continuation.activeRequestId) {
713
+ if (requestId === this._continuation.activeRequestId) {
603
714
  this._continuation.activeRequestId = null;
604
715
  this._continuation.activeConnectionId = null;
605
716
  }
606
- this._ensureStreamCleanupScheduled();
607
717
  }
608
718
  /**
609
- * Ensure a single cleanup alarm is pending for this DO's resumable-stream
610
- * buffers. Armed whenever a stream finishes (completes or errors) so that
611
- * idle/one-off chat DOs still reclaim their buffers — the lazy sweep in
612
- * {@link ResumableStream} only fires when a *subsequent* stream completes,
613
- * which never happens for a chat that receives a single turn (#1706).
614
- *
615
- * `idempotent` dedupes on (callback, payload, owner) so repeated finishes
616
- * collapse onto one pending alarm rather than stacking.
719
+ * @deprecated Streams are reclaimed at cutover and on the next stream
720
+ * start; no alarm is armed any more. Kept so a cleanup alarm persisted
721
+ * by an earlier version still resolves to a callback when it fires.
617
722
  * @internal
618
723
  */
619
- async _ensureStreamCleanupScheduled({ idempotent = true } = {}) {
620
- await this.schedule(STREAM_CLEANUP_DELAY_SECONDS, "_cleanupStreamBuffers", void 0, { idempotent });
724
+ async _cleanupStreamBuffers() {
725
+ this._resumableStream.reclaim();
621
726
  }
622
727
  /**
623
- * Alarm callback: sweep aged stream buffers, re-arming while rows remain (see
624
- * the shared {@link cleanupStreamBuffers}). Public so it is reachable as a
625
- * schedule callback.
626
- * @internal
728
+ * @internal Delegate to _resumableStream.
729
+ *
730
+ * A settled tool result (`tool-output-available` / `-error` / `-denied`)
731
+ * is flushed to SQLite immediately rather than waiting for the packed
732
+ * segment to fill: it captures a completed, often non-idempotent side
733
+ * effect (or a user's denial), and an isolate eviction before the next
734
+ * batch flush would lose it — recovery would re-anchor without it and
735
+ * re-run the tool. The flush is also what the recovery progress marker is
736
+ * derived from (`_chatRecoveryProgressMarker`), so a settled result counts
737
+ * as forward progress the moment it lands, as it did under the old
738
+ * per-chunk counter. Streaming deltas keep the buffer's own packing.
627
739
  */
628
- async _cleanupStreamBuffers() {
629
- await cleanupStreamBuffers(this._resumableStream, () => this._ensureStreamCleanupScheduled({ idempotent: false }));
630
- }
631
- /** @internal Delegate to _resumableStream. Also advances the recovery
632
- * progress counter at production time (see `_maybeBumpRecoveryProgress`). */
633
740
  async _storeStreamChunk(streamId, body) {
634
741
  this._resumableStream.storeChunk(streamId, body);
635
742
  let type;
636
743
  try {
637
744
  type = JSON.parse(body).type;
638
745
  } catch {}
639
- await this._maybeBumpRecoveryProgress(type);
640
- }
641
- /** Advance the recovery-progress counter when a chunk represents genuinely
642
- * new produced content. Uses the shared host-agnostic rule
643
- * ({@link shouldCreditStreamProgress}): a milestone (started segment / settled
644
- * tool) always credits, and a long single segment's streaming deltas credit
645
- * through a time throttle so the no-progress window doesn't false-fire while
646
- * content streams across crashes. Bumped at production time, so it reflects
647
- * real forward progress and is immune to client reconnects / recovery
648
- * re-persists (which replay or re-materialize stored chunks rather than flow
649
- * through here). This is what the recovery no-progress window keys off
650
- * (#1637), and stays compaction-proof (#1628). */
651
- async _maybeBumpRecoveryProgress(type) {
652
- if (shouldCreditStreamProgress({
653
- codec: aiSdkRecoveryCodec,
654
- type,
655
- throttle: this._streamProgressCredit,
656
- now: Date.now()
657
- })) await this._bumpChatRecoveryProgress();
746
+ if (type === "tool-output-available" || type === "tool-output-error" || type === "tool-output-denied") this._resumableStream.flushBuffer();
658
747
  }
659
748
  /** @internal Delegate to _resumableStream */
660
749
  _flushChunkBuffer() {
@@ -673,7 +762,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
673
762
  this._continuation.activeRequestId = null;
674
763
  this._continuation.activeConnectionId = null;
675
764
  }
676
- this._ensureStreamCleanupScheduled();
677
765
  }
678
766
  /**
679
767
  * Reconstruct and persist a partial assistant message from an orphaned
@@ -687,9 +775,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
687
775
  * `Think` and the client reducer use), replacing a hand-rolled chunk
688
776
  * switch; it owns the `start` / `finish` / `message-metadata` handling;
689
777
  * - (b) {@link _resolveOrphanTargetId} — the id to persist under (#1691);
690
- * - (c)+(d) upsert-by-id over the flat array, the `SessionProvider`-subset
691
- * store-write shape (`getMessage` → `updateMessage` / `appendMessage`)
692
- * that `Think._upsertMessageInHistory` implements over a Session tree.
778
+ * - (c)+(d) upsert-by-id through the shared `OrphanPersistStore` shape
779
+ * (`getMessage` → `updateMessage` / `appendMessage`).
693
780
  * When a row already owns the id, the shared `reconcileOrphanPartial`
694
781
  * merge preserves an in-place tool result rather than letting a replayed
695
782
  * chunk re-advance it (ai-chat has an early tool-approval persist; hosts
@@ -738,9 +825,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
738
825
  return reconstructedId;
739
826
  }
740
827
  /**
741
- * The orphan-persist store adapter — orphan-persist steps **(c)/(d)** route
742
- * their write through this shared `OrphanPersistStore` seam (the
743
- * `SessionProvider` write-subset). Backed by ai-chat's flat `this.messages`
828
+ * The orphan-persist store adapter. Orphan-persist steps **(c)/(d)** route
829
+ * through the shared `OrphanPersistStore` seam, backed by ai-chat's
830
+ * `this.messages`
744
831
  * array + the existing `persistMessages` whole-array write path, so
745
832
  * reconcile/sanitize/row-size/broadcast all stay intact. Each mutating call
746
833
  * is exactly one `persistMessages` invocation; `parentId` is unused (a flat
@@ -796,8 +883,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
796
883
  * framework can't repair "inside" it the way Think does; it repairs
797
884
  * `this.messages` at each point right before handing control to
798
885
  * `onChatMessage` instead. This reaches the cases the recovery-only repair
799
- * missed: a mixed client+server orphan whose client replay drives an
800
- * auto-continuation, and any agent running with `chatRecovery` disabled.
886
+ * missed, including a mixed client+server orphan whose client replay drives
887
+ * an auto-continuation.
801
888
  *
802
889
  * Scope: repair only ever flips a DEAD SERVER orphan (an interrupted tool with
803
890
  * no settled result whose `execute()` died with the evicted isolate). A part
@@ -880,24 +967,172 @@ var AIChatAgent = class AIChatAgent extends Agent {
880
967
  ...continuation && { continuation: true }
881
968
  });
882
969
  }
883
- _loadMessagesFromDb() {
884
- const rows = this.sql`select * from cf_ai_chat_agent_messages order by created_at` || [];
885
- this._persistedMessageCache.clear();
886
- return rows.map((row) => {
887
- try {
888
- const messageStr = row.message;
889
- const parsed = JSON.parse(messageStr);
890
- if (!isValidMessageStructure(parsed)) {
891
- console.warn(`[AIChatAgent] Skipping invalid message ${row.id}: missing or malformed id, role, or parts`);
892
- return null;
970
+ /**
971
+ * Lift ai-chat's legacy flat table into the default Sessions chain.
972
+ *
973
+ * Runs in `onStart` (before hydration), not in the constructor: the lift is
974
+ * an async import through Sessions, and the constructor does no session
975
+ * storage work at all.
976
+ *
977
+ * Order is read first as ids alone, then message bodies are fetched in
978
+ * windows bounded by row count and bytes, so a large transcript never sits
979
+ * in the isolate at once. Once every readable row has a copy the legacy
980
+ * table is DROPPED rather than renamed: keeping it would leave the object
981
+ * holding its history twice.
982
+ */
983
+ async _migrateLegacyMessages() {
984
+ if (!(this.ctx.storage.sql.exec(`SELECT name FROM sqlite_master
985
+ WHERE type = 'table' AND name = 'cf_ai_chat_agent_messages'`).toArray().length > 0)) return;
986
+ const order = this.sql`
987
+ SELECT id, LENGTH(CAST(message AS BLOB)) AS bytes, created_at
988
+ FROM cf_ai_chat_agent_messages
989
+ ORDER BY created_at ASC, rowid ASC
990
+ `;
991
+ let parentId = null;
992
+ let imported = 0;
993
+ let skipped = 0;
994
+ let index = 0;
995
+ while (index < order.length) {
996
+ const window = [];
997
+ let bytes = 0;
998
+ while (index < order.length && window.length < LEGACY_LIFT_WINDOW_ROWS && (window.length === 0 || bytes + order[index].bytes <= LEGACY_LIFT_WINDOW_BYTES)) {
999
+ bytes += order[index].bytes;
1000
+ window.push(order[index]);
1001
+ index++;
1002
+ }
1003
+ const ids = JSON.stringify(window.map((row) => row.id));
1004
+ const bodies = new Map(this.sql`
1005
+ SELECT id, message FROM cf_ai_chat_agent_messages
1006
+ WHERE id IN (SELECT value FROM json_each(${ids}))
1007
+ `.map((row) => [row.id, row.message]));
1008
+ for (const row of window) {
1009
+ const body = bodies.get(row.id);
1010
+ if (body === void 0) {
1011
+ skipped++;
1012
+ continue;
1013
+ }
1014
+ try {
1015
+ const message = autoTransformMessages([JSON.parse(body)])[0];
1016
+ if (!message || !isValidMessageStructure(message)) {
1017
+ console.warn(`[AIChatAgent] Skipping invalid legacy message ${row.id}: missing or malformed id, role, or parts`);
1018
+ skipped++;
1019
+ continue;
1020
+ }
1021
+ const parsedTime = typeof row.created_at === "number" ? row.created_at : Date.parse(String(row.created_at ?? ""));
1022
+ await this.#session.importMessage(message, {
1023
+ parentId,
1024
+ createdAt: Number.isFinite(parsedTime) ? parsedTime : imported
1025
+ });
1026
+ parentId = message.id;
1027
+ imported++;
1028
+ } catch (error) {
1029
+ console.error(`Failed to migrate message ${row.id}:`, error);
1030
+ skipped++;
893
1031
  }
894
- this._persistedMessageCache.set(parsed.id, messageStr);
895
- return parsed;
896
- } catch (error) {
897
- console.error(`Failed to parse message ${row.id}:`, error);
898
- return null;
899
1032
  }
900
- }).filter((msg) => msg !== null);
1033
+ }
1034
+ if (skipped === 0 && imported === order.length) {
1035
+ this.ctx.storage.sql.exec("DROP TABLE cf_ai_chat_agent_messages");
1036
+ return;
1037
+ }
1038
+ console.error(`[AIChatAgent] Legacy lift imported ${imported} of ${order.length} rows (${skipped} skipped); leaving cf_ai_chat_agent_messages in place so they remain recoverable.`);
1039
+ }
1040
+ /**
1041
+ * Hydrate `this.messages` once per wake, bounded by
1042
+ * {@link hydrationByteBudget}. This is the only transcript read on the
1043
+ * startup path; every later change arrives through the Sessions change
1044
+ * feed.
1045
+ */
1046
+ async _hydrateMessages() {
1047
+ const budget = this.hydrationByteBudget;
1048
+ const stored = Number.isFinite(budget) && budget > 0 ? (await this.#session.getRecentHistory(budget)).messages : await this.#session.getHistory();
1049
+ const messages = [];
1050
+ for (const message of stored) {
1051
+ if (!isValidMessageStructure(message)) {
1052
+ console.warn(`[AIChatAgent] Skipping invalid message ${message?.id}: missing or malformed id, role, or parts`);
1053
+ continue;
1054
+ }
1055
+ messages.push(message);
1056
+ }
1057
+ this.messages = autoTransformMessages(messages);
1058
+ }
1059
+ /**
1060
+ * Mirror `this.messages` from the Sessions change feed. Every durable write
1061
+ * dispatches here synchronously, so write sites never hand-patch the
1062
+ * cache.
1063
+ */
1064
+ #subscribeToSessionChanges() {
1065
+ this.sessions.subscribe(async (event) => {
1066
+ if (event.sessionId !== this.#session.sessionId) return;
1067
+ switch (event.type) {
1068
+ case "append": {
1069
+ if (!event.inserted) return;
1070
+ const message = this.#messageForCache(event.message);
1071
+ const index = this.messages.findIndex((m) => m.id === message.id);
1072
+ if (index === -1) this.messages.push(message);
1073
+ else this.messages[index] = message;
1074
+ return;
1075
+ }
1076
+ case "update": {
1077
+ const index = this.messages.findIndex((m) => m.id === event.message.id);
1078
+ if (index === -1) return;
1079
+ this.messages[index] = this.#messageForCache(event.message);
1080
+ return;
1081
+ }
1082
+ case "delete": {
1083
+ const removed = new Set(event.messageIds);
1084
+ this.messages = this.messages.filter((m) => !removed.has(m.id));
1085
+ return;
1086
+ }
1087
+ case "clear":
1088
+ this.messages = [];
1089
+ return;
1090
+ default: return;
1091
+ }
1092
+ });
1093
+ }
1094
+ /**
1095
+ * Turn a stored row into its in-memory form. A stored row is exactly what
1096
+ * the write returned, so this never costs a re-read.
1097
+ */
1098
+ #messageForCache(message) {
1099
+ const stored = message;
1100
+ return autoTransformMessages([stored])[0] ?? stored;
1101
+ }
1102
+ /**
1103
+ * Serialize the whole transcript as a JSON array of messages without ever
1104
+ * holding it in one string: `historyBatches()` yields bounded batches and
1105
+ * each batch is encoded straight into the response body.
1106
+ */
1107
+ #streamMessagesAsJson() {
1108
+ const encoder = new TextEncoder();
1109
+ const batches = this.#session.historyBatches();
1110
+ let opened = false;
1111
+ let first = true;
1112
+ return new ReadableStream({
1113
+ pull: async (controller) => {
1114
+ if (!opened) {
1115
+ opened = true;
1116
+ controller.enqueue(encoder.encode("["));
1117
+ return;
1118
+ }
1119
+ const next = await batches.next();
1120
+ if (next.done) {
1121
+ controller.enqueue(encoder.encode("]"));
1122
+ controller.close();
1123
+ return;
1124
+ }
1125
+ let chunk = "";
1126
+ for (const message of autoTransformMessages(next.value)) {
1127
+ chunk += `${first ? "" : ","}${JSON.stringify(message)}`;
1128
+ first = false;
1129
+ }
1130
+ if (chunk.length > 0) controller.enqueue(encoder.encode(chunk));
1131
+ },
1132
+ cancel: async () => {
1133
+ await batches.return?.(void 0);
1134
+ }
1135
+ });
901
1136
  }
902
1137
  async _tryCatchChat(fn) {
903
1138
  try {
@@ -1372,8 +1607,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1372
1607
  this._abortRegistry.remove(requestId);
1373
1608
  }
1374
1609
  };
1375
- if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, true, autoContinuationBody);
1376
- else await autoContinuationBody();
1610
+ await this._runChatRecoveryFiber(requestId, true, autoContinuationBody);
1377
1611
  });
1378
1612
  });
1379
1613
  } finally {
@@ -1416,8 +1650,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
1416
1650
  });
1417
1651
  if (response) status = await this._reply(requestId, response, [], { chatMessageId: requestId });
1418
1652
  };
1419
- if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, false, programmaticBody);
1420
- else await programmaticBody();
1653
+ await this._runChatRecoveryFiber(requestId, false, programmaticBody);
1421
1654
  } finally {
1422
1655
  if (abortSignal?.aborted) wasAborted = true;
1423
1656
  detachExternal();
@@ -2097,13 +2330,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2097
2330
  `[0] ?? null;
2098
2331
  }
2099
2332
  _getAgentToolStreamId(requestId) {
2100
- return this.sql`
2101
- select id, status, request_id
2102
- from cf_ai_chat_stream_metadata
2103
- where request_id = ${requestId}
2104
- order by rowid desc
2105
- limit 1
2106
- `[0]?.id;
2333
+ return this._resumableStream.latestStreamInfoForRequest(requestId)?.id;
2107
2334
  }
2108
2335
  _getAgentToolStoredChunks(requestId, afterSequence = -1) {
2109
2336
  const streamId = this._getAgentToolStreamId(requestId);
@@ -2268,8 +2495,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2268
2495
  });
2269
2496
  });
2270
2497
  };
2271
- if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, true, turnBody);
2272
- else await turnBody();
2498
+ await this._runChatRecoveryFiber(requestId, true, turnBody);
2273
2499
  }, { epoch });
2274
2500
  if (this._turnQueue.generation !== epoch && status === "completed") status = "skipped";
2275
2501
  else if (wasAborted && status === "completed") status = "aborted";
@@ -2324,34 +2550,38 @@ var AIChatAgent = class AIChatAgent extends Agent {
2324
2550
  * recomputed from the live, mutable transcript. Compaction collapses older
2325
2551
  * assistant messages into a summary, lowering the count — so a turn that had
2326
2552
  * genuinely advanced could read as "no progress" between attempts and exhaust
2327
- * its budget prematurely (#1628). Instead we read a durably-persisted counter
2328
- * that only ever increments — bumped at production time when new content is
2329
- * streamed (see `_storeStreamChunk` / `_maybeBumpRecoveryProgress`), which is
2330
- * genuine forward progress and is immune to client reconnects / recovery
2331
- * re-persists — so compaction can never lower it and a reconnect can't fake
2332
- * it (#1637).
2553
+ * its budget prematurely (#1628). It then became a KV counter bumped per
2554
+ * credited chunk. It is now derived from the stream log the chunks were
2555
+ * already flushed to (`ResumableStream.progressMarker`): the log only grows
2556
+ * when new content lands durably, a reconnect replay or a recovery
2557
+ * re-persist reads it without appending (#1637), and compaction rewrites
2558
+ * the transcript, not the log. Nothing is written per chunk.
2559
+ *
2560
+ * The pre-derivation KV counter is folded in once per isolate, so a marker
2561
+ * an in-flight incident already recorded is never read lower after the
2562
+ * upgrade.
2333
2563
  */
2334
2564
  async _chatRecoveryProgressMarker() {
2335
- return readChatRecoveryProgress(this.ctx.storage);
2336
- }
2337
- /** Advance the durable recovery-progress counter. Called from
2338
- * `_maybeBumpRecoveryProgress` when new content is streamed (real,
2339
- * reconnect-immune forward progress). The increment lives in the shared
2340
- * engine (agents/chat); this is the package binding. */
2341
- async _bumpChatRecoveryProgress() {
2342
- return bumpChatRecoveryProgress(this.ctx.storage);
2565
+ this._progressSeed ??= readChatRecoveryProgress(this.ctx.storage).then((legacy) => this._resumableStream.seedProgress(legacy), (error) => {
2566
+ this._progressSeed = null;
2567
+ throw error;
2568
+ });
2569
+ await this._progressSeed;
2570
+ return this._resumableStream.progressMarker();
2343
2571
  }
2344
2572
  /**
2345
2573
  * N9: forwarding a sub-agent's chunks IS forward progress for this parent
2346
2574
  * turn, so credit the parent's recovery progress marker — otherwise a parent
2347
2575
  * whose turn merely `await`s a child banks no progress of its own and its
2348
- * no-progress window exhausts while the child is healthily streaming. Only
2576
+ * no-progress window exhausts while the child is healthily streaming. The
2577
+ * child's output goes to clients, not to this object's stream log, so the
2578
+ * derived marker cannot see it; this is the one explicit credit left. Only
2349
2579
  * invoked after a child actually produced output (see
2350
2580
  * `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.
2351
2581
  * Throttled (and reset per isolate) so we never write storage per token.
2352
2582
  */
2353
2583
  async _onAgentToolStreamProgress() {
2354
- if (this._agentToolStreamProgress.shouldCredit(Date.now())) await this._bumpChatRecoveryProgress();
2584
+ if (this._agentToolStreamProgress.shouldCredit(Date.now())) this._resumableStream.creditProgress();
2355
2585
  }
2356
2586
  _chatRecoveryEngine() {
2357
2587
  return this._chatRecoveryEngineInstance ??= new ChatRecoveryEngine({
@@ -2373,9 +2603,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2373
2603
  recoveryKind: event.recoveryKind,
2374
2604
  ...event.reason ? { reason: event.reason } : {}
2375
2605
  }),
2376
- scheduleRecovery: async (callback, data, reason, delaySeconds) => {
2377
- await this.schedule(delaySeconds, callback, data, chatRecoverySchedulePolicy(reason));
2378
- },
2606
+ scheduleRecovery: (callback, data, reason, delaySeconds) => this._enqueueChatRecovery(callback, data, reason, delaySeconds),
2379
2607
  setRecovering: (active, requestId) => this._setChatRecovering(active, requestId),
2380
2608
  onShouldKeepRecoveringError: (error) => console.error("[AIChatAgent] chatRecovery shouldKeepRecovering hook threw", error),
2381
2609
  exhaustChatRecovery: (incident, config, partial, streamId, createdAt) => this._exhaustChatRecovery(incident, config, partial, streamId, createdAt),
@@ -2490,7 +2718,6 @@ var AIChatAgent = class AIChatAgent extends Agent {
2490
2718
  persistOrphanedStream: (streamId) => this._persistOrphanedStream(streamId),
2491
2719
  completeRecoveredStream: (streamId) => {
2492
2720
  this._resumableStream.complete(streamId);
2493
- this._ensureStreamCleanupScheduled();
2494
2721
  },
2495
2722
  dispatchRecoveredTurn: (input) => this._dispatchRecoveredChatTurn(input)
2496
2723
  });
@@ -2507,14 +2734,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2507
2734
  */
2508
2735
  _resolveAIChatRecoveryStream(requestId) {
2509
2736
  let streamId = "";
2510
- if (requestId) {
2511
- const rows = this.sql`
2512
- SELECT id FROM cf_ai_chat_stream_metadata
2513
- WHERE request_id = ${requestId}
2514
- ORDER BY created_at DESC LIMIT 1
2515
- `;
2516
- if (rows.length > 0) streamId = rows[0].id;
2517
- }
2737
+ if (requestId) streamId = this._resumableStream.latestStreamInfoForRequest(requestId)?.id ?? "";
2518
2738
  if (!streamId && this._resumableStream.hasActiveStream()) streamId = this._resumableStream.activeStreamId ?? "";
2519
2739
  const streamStillActive = Boolean(streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId);
2520
2740
  return {
@@ -2610,6 +2830,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
2610
2830
  return {};
2611
2831
  }
2612
2832
  async _chatRecoveryContinue(data) {
2833
+ await this._dispatchChatRecovery("_chatRecoveryContinue", data, (onTurnStarted) => this._chatRecoveryContinueDetached(data, onTurnStarted));
2834
+ }
2835
+ async _chatRecoveryContinueDetached(data, onTurnStarted) {
2613
2836
  const previousRootRequestId = this._activeChatRecoveryRootRequestId;
2614
2837
  this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
2615
2838
  try {
@@ -2630,6 +2853,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2630
2853
  return;
2631
2854
  }
2632
2855
  this._applyRecoveredRequestContext(data);
2856
+ onTurnStarted?.();
2633
2857
  const result = await this.continueLastTurn();
2634
2858
  await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
2635
2859
  } catch (error) {
@@ -2656,13 +2880,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
2656
2880
  * Unlike Think there is no durable-submission layer to complete here, so the
2657
2881
  * schedule payload carries no `recoveredRequestId`.
2658
2882
  *
2659
- * Returns `"disabled"` when chat recovery is off (the caller then surfaces the
2660
- * stall as a terminal stream error — the watchdog's "kill the spinner"
2661
- * guarantee), `"exhausted"` when the budget was spent (terminal UX already
2883
+ * Returns `"exhausted"` when the budget was spent (terminal UX already
2662
2884
  * delivered), or `"scheduled"` when a continuation was queued.
2663
2885
  */
2664
2886
  async _routeStallToBoundedRecovery(input) {
2665
- if (!this._resolveChatRecoveryConfig().enabled) return "disabled";
2666
2887
  const recoveryRootRequestId = this._activeChatRecoveryRootRequestId ?? input.requestId;
2667
2888
  const latestUserMessageId = [...this.messages].reverse().find((m) => m.role === "user")?.id ?? null;
2668
2889
  const { incident, config, exhausted } = await this._beginChatRecoveryIncident({
@@ -2761,25 +2982,32 @@ var AIChatAgent = class AIChatAgent extends Agent {
2761
2982
  * Two residual at-least-once edges, both deliberately accepted as "deliver a
2762
2983
  * second banner" ≫ "silently drop the turn":
2763
2984
  * • No `incidentId` at all in the payload (only reachable via a direct/test
2764
- * invocation — every production scheduler carries one): the synthesized
2765
- * incident can't be persisted (no key), so the guard can't arm.
2985
+ * invocation — every production recovery enqueue carries one): the
2986
+ * synthesized incident can't be persisted (no key), so the guard can't
2987
+ * arm.
2766
2988
  * • The record is swept AGAIN between two alarms (the guard re-persists on
2767
2989
  * the first, so this needs a second independent sweep) — vanishingly
2768
2990
  * unlikely.
2769
2991
  */
2770
2992
  /**
2771
- * Recovery continuation callbacks the alarm-boundary OOM circuit breaker may
2772
- * back off / purge (#1825). See `Agent._cf_handleAlarmMemoryLimitReset`.
2993
+ * Host memory-limit policy hook (#1825), dispatched structurally by
2994
+ * Lifecycle's circuit breaker — protected because it is framework
2995
+ * machinery, not part of the public chat API. Tasks applies the breaker to
2996
+ * root recovery runs; the routed dynamic-agent fallback applies it to
2997
+ * `recoveryLoop` schedule rows (see `RecoveryLoopScheduleOptions`). At the
2998
+ * strike budget this hook seals active incidents via
2999
+ * {@link _cf_sealMemoryLimitedRecovery}.
2773
3000
  */
2774
- _cf_recoveryAlarmCallbacks() {
2775
- return ["_chatRecoveryContinue", "_chatRecoveryRetry"];
3001
+ async onAlarmMemoryLimit(context) {
3002
+ if (!context.sealed) return;
3003
+ await this._cf_sealMemoryLimitedRecovery();
2776
3004
  }
2777
3005
  /**
2778
- * Seal any still-live recovery incident as an out-of-memory exhaustion when
2779
- * the alarm circuit breaker trips at its strike budget (#1825). Runs at the
2780
- * outermost alarm frame (post-unwind), so the terminal banner / `onExhausted`
2781
- * and the sealed-incident write can land where mid-turn writes OOMed. Reuses
2782
- * the shared give-up spine via the recovery engine.
3006
+ * Seal any still-live recovery incident as an out-of-memory exhaustion
3007
+ * when the alarm circuit breaker trips at its strike budget (#1825). Runs
3008
+ * at the outermost alarm frame (post-unwind), so the terminal banner /
3009
+ * `onExhausted` and the sealed-incident write can land where mid-turn
3010
+ * writes OOMed. Reuses the shared give-up spine via the recovery engine.
2783
3011
  */
2784
3012
  async _cf_sealMemoryLimitedRecovery() {
2785
3013
  const active = await listActiveChatRecoveryIncidents(this.ctx.storage);
@@ -2847,6 +3075,9 @@ var AIChatAgent = class AIChatAgent extends Agent {
2847
3075
  return lastMessage?.role === "user" && lastMessage.id === snapshot.latestUserMessageId;
2848
3076
  }
2849
3077
  async _chatRecoveryRetry(data) {
3078
+ await this._dispatchChatRecovery("_chatRecoveryRetry", data, (onTurnStarted) => this._chatRecoveryRetryDetached(data, onTurnStarted));
3079
+ }
3080
+ async _chatRecoveryRetryDetached(data, onTurnStarted) {
2850
3081
  const previousRootRequestId = this._activeChatRecoveryRootRequestId;
2851
3082
  this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
2852
3083
  try {
@@ -2871,6 +3102,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
2871
3102
  return;
2872
3103
  }
2873
3104
  this._applyRecoveredRequestContext(data);
3105
+ onTurnStarted?.();
2874
3106
  const result = await this._retryLastUserTurn(this._lastClientTools, this._lastBody);
2875
3107
  await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
2876
3108
  } catch (error) {
@@ -2887,33 +3119,53 @@ var AIChatAgent = class AIChatAgent extends Agent {
2887
3119
  _getPartialStreamText(streamId) {
2888
3120
  return aiSdkRecoveryCodec.toRecoveryPartial(this._resumableStream.getStreamChunks(streamId).map((chunk) => chunk.body));
2889
3121
  }
3122
+ /**
3123
+ * The turn whose finished stream is waiting for its message write: the
3124
+ * cutover rides on the instance, not on an argument, so a subclass that
3125
+ * overrides {@link persistMessages} and calls `super` with only the
3126
+ * messages still lands the message, the stream's settlement and the
3127
+ * deletion of its rows in one transaction. Consumed by the first persist
3128
+ * that carries the turn's message; cleared when the turn ends.
3129
+ */
3130
+ #pendingCutover;
2890
3131
  async persistMessages(messages, excludeBroadcastIds = [], options) {
2891
- const mergedMessages = reconcileMessages(messages, this.messages, (msg) => this._sanitizeMessageForPersistence(msg));
3132
+ const priorMessages = [...this.messages];
3133
+ const priorById = new Map(priorMessages.map((m) => [m.id, m]));
3134
+ const mergedMessages = reconcileMessages(messages, priorMessages, (msg) => this._sanitizeMessageForPersistence(msg));
3135
+ const toWrite = [];
2892
3136
  for (const message of mergedMessages) {
2893
- const resolved = resolveToolMergeId(this._sanitizeMessageForPersistence(message), this.messages);
2894
- const safe = this._enforceRowSizeLimit(resolved);
2895
- const json = JSON.stringify(safe);
2896
- if (this._persistedMessageCache.get(safe.id) === json) continue;
2897
- this.sql`
2898
- insert into cf_ai_chat_agent_messages (id, message)
2899
- values (${safe.id}, ${json})
2900
- on conflict(id) do update set message = excluded.message
2901
- `;
2902
- this._persistedMessageCache.set(safe.id, json);
3137
+ const resolved = resolveToolMergeId(this._sanitizeMessageForPersistence(message), priorMessages);
3138
+ const prior = priorById.get(resolved.id);
3139
+ if (prior && JSON.stringify(prior) === JSON.stringify(resolved)) continue;
3140
+ toWrite.push(resolved);
2903
3141
  }
3142
+ const cutover = this.#pendingCutover;
3143
+ if (cutover && mergedMessages.some((message) => message.id === cutover.messageId)) {
3144
+ this.#pendingCutover = null;
3145
+ const sync = this.#session.__DO_NOT_USE_WILL_BREAK__sync();
3146
+ const afters = [];
3147
+ try {
3148
+ this._resumableStream.cutover(cutover.streamId, () => {
3149
+ for (const message of toWrite) afters.push(sync.upsert(message).after);
3150
+ }, { discard: cutover.discard });
3151
+ } catch (error) {
3152
+ sync.abandon();
3153
+ throw error;
3154
+ }
3155
+ for (const after of afters) await after();
3156
+ } else for (const message of toWrite) await this.#session.upsertMessage(message);
2904
3157
  if (options?._deleteStaleRows) {
2905
- const serverIds = new Set(this.messages.map((m) => m.id));
2906
- if (mergedMessages.every((m) => serverIds.has(m.id))) {
2907
- const keepIds = new Set(mergedMessages.map((m) => m.id));
2908
- const staleIds = (this.sql`
2909
- select id from cf_ai_chat_agent_messages
2910
- ` || []).map((row) => row.id).filter((id) => !keepIds.has(id));
2911
- this._deleteMessagesByIds(staleIds);
3158
+ const serverIds = new Set(priorMessages.map((message) => message.id));
3159
+ if (mergedMessages.every((message) => serverIds.has(message.id))) {
3160
+ const keepIds = new Set(mergedMessages.map((message) => message.id));
3161
+ await this._deleteMessagesByIds(this.messages.map((message) => message.id).filter((id) => !keepIds.has(id)));
2912
3162
  }
2913
3163
  }
2914
- if (this.maxPersistedMessages != null) this._enforceMaxPersistedMessages();
2915
- const persisted = this._loadMessagesFromDb();
2916
- this.messages = autoTransformMessages(persisted);
3164
+ if (this.maxPersistedMessages != null) {
3165
+ const stored = await this.#session.getHistoryRowStats();
3166
+ const excess = stored.length - this.maxPersistedMessages;
3167
+ if (excess > 0) await this._deleteMessagesByIds(stored.slice(0, excess).map((row) => row.id));
3168
+ }
2917
3169
  this._broadcastChatMessage({
2918
3170
  messages: mergedMessages,
2919
3171
  type: MessageType.CF_AGENT_CHAT_MESSAGES
@@ -2948,38 +3200,29 @@ var AIChatAgent = class AIChatAgent extends Agent {
2948
3200
  };
2949
3201
  }
2950
3202
  /**
2951
- * Sanitizes a message for persistence by removing ephemeral provider-specific
2952
- * data that should not be stored or sent back in subsequent requests.
3203
+ * Applies the ai-chat-specific normalization Sessions does not do.
2953
3204
  *
2954
- * Pipeline:
3205
+ * Sessions already strips OpenAI ephemeral fields (itemId,
3206
+ * reasoningEncryptedContent) and drops truly empty reasoning parts on every
3207
+ * write, so those steps are not repeated here.
2955
3208
  *
2956
- * 1. **Strip OpenAI ephemeral fields**: The AI SDK's @ai-sdk/openai provider
2957
- * (v2.0.x+) defaults to using OpenAI's Responses API which assigns unique
2958
- * itemIds and reasoningEncryptedContent to message parts. When persisted
2959
- * and sent back, OpenAI rejects duplicate itemIds.
3209
+ * Pipeline:
2960
3210
  *
2961
- * 2. **Truncate provider-executed tool payloads**: Server-side tool
3211
+ * 1. **Truncate provider-executed tool payloads**: Server-side tool
2962
3212
  * executions (e.g. Anthropic code_execution, text_editor) can produce
2963
3213
  * 200KB+ payloads in `input` and `output`. These are truncated since the
2964
3214
  * model has already consumed the results.
2965
3215
  *
2966
- * 3. **Filter truly empty reasoning parts**: After stripping, reasoning parts
2967
- * with no text and no remaining providerMetadata are removed. Parts that
2968
- * still carry providerMetadata (e.g. Anthropic's redacted_thinking blocks
2969
- * with providerMetadata.anthropic.redactedData) are preserved, as they
2970
- * contain data required for round-tripping with the provider API.
2971
- *
2972
- * 4. **User hook**: Calls the overridable `sanitizeMessageForPersistence()`
3216
+ * 2. **User hook**: Calls the overridable `sanitizeMessageForPersistence()`
2973
3217
  * method, allowing subclasses to apply custom transformations.
2974
3218
  *
2975
3219
  * @param message - The message to sanitize
2976
- * @returns A new message with ephemeral provider data removed
3220
+ * @returns A new message with ai-chat's normalization applied
2977
3221
  */
2978
3222
  _sanitizeMessageForPersistence(message) {
2979
- const baseSanitized = sanitizeMessage(message);
2980
- const parts = baseSanitized.parts.map((part) => AIChatAgent._truncateProviderExecutedToolPayloads(part));
3223
+ const parts = message.parts.map((part) => AIChatAgent._truncateProviderExecutedToolPayloads(part));
2981
3224
  return this.sanitizeMessageForPersistence({
2982
- ...baseSanitized,
3225
+ ...message,
2983
3226
  parts
2984
3227
  });
2985
3228
  }
@@ -3040,54 +3283,12 @@ var AIChatAgent = class AIChatAgent extends Agent {
3040
3283
  return key.startsWith(PROVIDER_TOOL_OPAQUE_STRING_KEY_PREFIX);
3041
3284
  }
3042
3285
  /**
3043
- * Delete the given message rows from SQLite in batched `IN (...)` queries
3044
- * and evict them from the persistence cache. Batches stay within the SQLite
3045
- * 100 bound-parameter limit. No-op for an empty list.
3046
- * @internal
3286
+ * Delete message rows through Sessions. The change feed removes them from
3287
+ * `this.messages`.
3047
3288
  */
3048
- _deleteMessagesByIds(ids) {
3049
- for (let i = 0; i < ids.length; i += MAX_BOUND_PARAMS) {
3050
- const batch = ids.slice(i, i + MAX_BOUND_PARAMS);
3051
- const strings = buildInClauseStrings("delete from cf_ai_chat_agent_messages where id in ", batch.length);
3052
- this.sql(strings, ...batch);
3053
- for (const id of batch) this._persistedMessageCache.delete(id);
3054
- }
3055
- }
3056
- /**
3057
- * Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.
3058
- * Called after each persist to keep storage bounded.
3059
- */
3060
- _enforceMaxPersistedMessages() {
3061
- if (this.maxPersistedMessages == null) return;
3062
- const count = this.sql`
3063
- select count(*) as cnt from cf_ai_chat_agent_messages
3064
- `?.[0]?.cnt ?? 0;
3065
- if (count <= this.maxPersistedMessages) return;
3066
- const excess = count - this.maxPersistedMessages;
3067
- const toDelete = this.sql`
3068
- select id from cf_ai_chat_agent_messages
3069
- order by created_at asc
3070
- limit ${excess}
3071
- `;
3072
- if (toDelete && toDelete.length > 0) this._deleteMessagesByIds(toDelete.map((row) => row.id));
3073
- }
3074
- /**
3075
- * Enforces SQLite row size limits by compacting tool outputs and text parts
3076
- * when a serialized message exceeds the safety threshold (1.8MB).
3077
- *
3078
- * Only fires in pathological cases (extremely large tool outputs or text).
3079
- * Returns the message unchanged if it fits within limits.
3080
- *
3081
- * Compaction strategy:
3082
- * 1. Compact tool outputs over 1KB (replace with LLM-friendly summary)
3083
- * 2. If still too big, truncate text parts from oldest to newest
3084
- * 3. Add metadata so clients can detect compaction
3085
- *
3086
- * @param message - The message to check
3087
- * @returns The message, compacted if necessary
3088
- */
3089
- _enforceRowSizeLimit(message) {
3090
- return enforceRowSizeLimit(message, { warn: (m) => console.warn(`[AIChatAgent] ${m}`) });
3289
+ async _deleteMessagesByIds(ids) {
3290
+ if (ids.length === 0) return;
3291
+ await this.#session.deleteMessages(ids);
3091
3292
  }
3092
3293
  /**
3093
3294
  * Shared helper for finding a tool part by toolCallId and applying an update.
@@ -3155,16 +3356,10 @@ var AIChatAgent = class AIChatAgent extends Agent {
3155
3356
  ...message,
3156
3357
  parts: updatedParts
3157
3358
  });
3158
- const safe = this._enforceRowSizeLimit(updatedMessage);
3159
- const json = JSON.stringify(safe);
3160
- this.sql`
3161
- update cf_ai_chat_agent_messages
3162
- set message = ${json}
3163
- where id = ${message.id}
3164
- `;
3165
- this._persistedMessageCache.set(message.id, json);
3166
- const persisted = this._loadMessagesFromDb();
3167
- this.messages = autoTransformMessages(persisted);
3359
+ if (!await this.#session.updateMessage(updatedMessage)) {
3360
+ const index = this.messages.findIndex((candidate) => candidate.id === updatedMessage.id);
3361
+ if (index !== -1) this.messages[index] = autoTransformMessages([updatedMessage])[0];
3362
+ }
3168
3363
  }
3169
3364
  }
3170
3365
  if (!wasFound) {
@@ -3326,7 +3521,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3326
3521
  const { done, value } = readResult;
3327
3522
  if (done) {
3328
3523
  if (abortSignal?.aborted) break;
3329
- this._completeStream(streamId);
3524
+ this._finishStream(streamId);
3330
3525
  streamCompleted.value = true;
3331
3526
  this._broadcastChatMessage({
3332
3527
  body: "",
@@ -3375,13 +3570,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
3375
3570
  parts: [...this._streamingMessage.parts]
3376
3571
  };
3377
3572
  const sanitized = this._sanitizeMessageForPersistence(snapshot);
3378
- const json = JSON.stringify(sanitized);
3379
- this.sql`
3380
- INSERT INTO cf_ai_chat_agent_messages (id, message)
3381
- VALUES (${sanitized.id}, ${json})
3382
- ON CONFLICT(id) DO UPDATE SET message = excluded.message
3383
- `;
3384
- this._approvalPersistedMessageId = sanitized.id;
3573
+ const stored = await this.#session.upsertMessage(sanitized);
3574
+ this._approvalPersistedMessageId = stored.message.id;
3385
3575
  }
3386
3576
  if ((data.type === "tool-output-available" || data.type === "tool-output-error") && data.toolCallId) {
3387
3577
  if (!message.parts.some((p) => "toolCallId" in p && p.toolCallId === data.toolCallId)) if (data.type === "tool-output-available") this._findAndUpdateToolPart(data.toolCallId, "_streamSSEReply", [
@@ -3494,7 +3684,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3494
3684
  } catch (_error) {}
3495
3685
  }
3496
3686
  if (!streamCompleted.value) {
3497
- this._completeStream(streamId);
3687
+ this._finishStream(streamId);
3498
3688
  streamCompleted.value = true;
3499
3689
  this._broadcastChatMessage({
3500
3690
  body: "",
@@ -3548,7 +3738,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3548
3738
  type: "text-end",
3549
3739
  id
3550
3740
  }, continuation);
3551
- this._completeStream(streamId);
3741
+ this._finishStream(streamId);
3552
3742
  streamCompleted.value = true;
3553
3743
  this._broadcastChatMessage({
3554
3744
  body: "",
@@ -3575,7 +3765,7 @@ var AIChatAgent = class AIChatAgent extends Agent {
3575
3765
  type: "text-end",
3576
3766
  id
3577
3767
  }, continuation);
3578
- this._completeStream(streamId);
3768
+ this._finishStream(streamId);
3579
3769
  streamCompleted.value = true;
3580
3770
  this._broadcastChatMessage({
3581
3771
  body: "",
@@ -3695,6 +3885,11 @@ var AIChatAgent = class AIChatAgent extends Agent {
3695
3885
  if (streamCompleted.value && streamResult.status !== "error" && !stallRouted) this._emit("message:response");
3696
3886
  }
3697
3887
  }
3888
+ this.#pendingCutover = this._resumableStream.pendingCutoverId === streamId ? {
3889
+ streamId,
3890
+ messageId: earlyPersistedId ?? message.id,
3891
+ discard: !this._agentToolRunsByRequestId.get(id)
3892
+ } : null;
3698
3893
  if (message.parts.length > 0) if (earlyPersistedId) {
3699
3894
  const persistedMessage = {
3700
3895
  ...message,
@@ -3713,6 +3908,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
3713
3908
  await this.persistMessages(updatedMessages, excludeBroadcastIds);
3714
3909
  } else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
3715
3910
  } else await this.persistMessages([...this.messages, message], excludeBroadcastIds);
3911
+ this.#pendingCutover = null;
3912
+ this._resumableStream.finalizePending();
3716
3913
  this._pendingChatResponseResults.push({
3717
3914
  message,
3718
3915
  requestId: id,
@@ -3722,6 +3919,8 @@ var AIChatAgent = class AIChatAgent extends Agent {
3722
3919
  });
3723
3920
  return streamResult;
3724
3921
  } finally {
3922
+ this.#pendingCutover = null;
3923
+ this._resumableStream.finalizePending();
3725
3924
  this._onStreamingTurnFinalized();
3726
3925
  }
3727
3926
  }));