@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/README.md CHANGED
@@ -254,11 +254,11 @@ Streams automatically resume on disconnect/reconnect. No configuration needed.
254
254
 
255
255
  When a client disconnects mid-stream, chunks are buffered in SQLite. On reconnect, the client receives all buffered chunks and continues receiving the live stream.
256
256
 
257
- This handles browser disconnects, navigation, and React cleanup while the Durable Object keeps running. To recover after the Durable Object itself is evicted during a model call, opt in to `chatRecovery`.
257
+ This handles browser disconnects, navigation, and React cleanup while the Durable Object keeps running. Durable chat recovery separately handles the Durable Object itself being evicted during a model call.
258
258
 
259
259
  ## Durable Chat Recovery
260
260
 
261
- `AIChatAgent` defaults `chatRecovery` to `false`. Enable it when you want chat turns to survive Worker deploys, Durable Object eviction, or process restarts:
261
+ Every `AIChatAgent` turn runs in a durable recovery fiber, so turns can survive Worker deploys, Durable Object eviction, or process restarts. Assign a `chatRecovery` object only when you need to tune budgets or terminal behavior:
262
262
 
263
263
  ```typescript
264
264
  import type {
@@ -281,7 +281,9 @@ export class ChatAgent extends AIChatAgent<Env> {
281
281
  }
282
282
  ```
283
283
 
284
- See [`docs/agents/chat-agents.md`](../../docs/agents/chat-agents.md#stream-recovery) for provider-specific recovery strategies and observability events.
284
+ `chatRecovery = false` is no longer supported. Previously compiled JavaScript that still supplies `false` receives the default durable configuration. If automatic continuation is unsafe, return `{ continue: false }` from `onChatRecovery()`; use durable state for cancellation or side-effect guards, and configure recovery budgets for cost control.
285
+
286
+ See [`docs/agents/chat-agents.md`](../../docs/agents/chat-agents.md#stream-recovery) for migration guidance, provider-specific recovery strategies, and observability events.
285
287
 
286
288
  Generic client stream abort/cleanup is local-only by default: the server turn continues and can be resumed later. An explicit `stop()` still cancels the server turn:
287
289
 
@@ -466,11 +468,11 @@ Extends `Agent` from the `agents` package.
466
468
  | Property / Method | Type | Description |
467
469
  | ------------------------------------ | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
468
470
  | `messages` | `ChatMessage[]` | Current conversation messages (loaded from SQLite) |
469
- | `chatRecovery` | `ChatRecoveryConfig` | Opt-in Durable Object eviction recovery for chat turns. Default: `false` |
471
+ | `chatRecovery` | `ChatRecoveryConfig` | Always-on durable recovery configuration. Assign an object to tune budgets and terminal behavior |
470
472
  | `maxPersistedMessages` | `number \| undefined` | Max messages to keep in SQLite. Default: unlimited |
471
473
  | `messageConcurrency` | `MessageConcurrency` | Concurrency strategy for `sendMessage()` submits. Default: `"queue"` |
472
474
  | `onChatMessage(onFinish?, options?)` | Override | Handle incoming chat messages. Return a `Response`. `onFinish` is optional. |
473
- | `onChatRecovery(ctx)` | Override | Customize recovery after a chat turn is interrupted while `chatRecovery` is enabled |
475
+ | `onChatRecovery(ctx)` | Override | Customize recovery after a chat turn is interrupted |
474
476
  | `onChatResponse(result)` | Override | Called after a chat turn completes. `result` has `message`, `requestId`, `status`, `continuation` |
475
477
  | `persistMessages(messages)` | `Promise<void>` | Manually persist messages (usually automatic) |
476
478
  | `saveMessages(messages, options?)` | `Promise<SaveMessagesResult>` | Persist messages and trigger `onChatMessage`. Accepts array or function. `options.signal` cancels the turn externally. |
package/dist/index.d.ts CHANGED
@@ -33,7 +33,9 @@ import {
33
33
  SaveMessagesResult as SaveMessagesResult$1,
34
34
  createToolsFromClientSchemas
35
35
  } from "agents/chat";
36
+ import { Sessions } from "agents/sessions";
36
37
  import { GenerateTextOnFinishCallback, ToolSet, UIMessage } from "ai";
38
+ import { Streams } from "agents/streams";
37
39
 
38
40
  //#region src/index.d.ts
39
41
  type ChatRecoveryRetryData = {
@@ -100,21 +102,43 @@ type OnChatMessageOptions = {
100
102
  */
101
103
  continuation?: boolean;
102
104
  };
103
- /**
104
- * Extension of Agent with built-in chat capabilities
105
- * @template Env Environment type containing bindings
106
- */
107
105
  declare class AIChatAgent<
108
106
  Env extends Cloudflare.Env = Cloudflare.Env,
109
107
  State = unknown,
110
108
  Props extends Record<string, unknown> = Record<string, unknown>
111
109
  > extends Agent<Env, State, Props> {
110
+ #private;
112
111
  private _activeChatRecoveryRootRequestId;
113
112
  /**
114
113
  * Registry of per-request AbortControllers.
115
114
  * Used to propagate cancellation signals for any external calls made by the agent.
116
115
  */
117
116
  private _abortRegistry;
117
+ /** Durable chat history for this Agent. */
118
+ readonly sessions: Sessions;
119
+ /**
120
+ * Byte budget for wake-time transcript hydration into {@link messages}.
121
+ *
122
+ * `onStart` hydrates through `session.getRecentHistory(budget, …)`. The
123
+ * budget counts each stored row plus the continuation rows it was split
124
+ * across, so it bounds isolate memory: an oversized transcript hydrates
125
+ * as a bounded recent window
126
+ * instead of exhausting the isolate. Durable storage is never truncated by
127
+ * this — `sessions.session().getHistory()` still reads the full path, and
128
+ * the streamed `get-messages` route still serves every message.
129
+ *
130
+ * Set to `Number.POSITIVE_INFINITY` (or any non-positive value) to disable
131
+ * windowing and always hydrate the whole transcript.
132
+ *
133
+ * @default 32 * 1024 * 1024
134
+ */
135
+ hydrationByteBudget: number;
136
+ /**
137
+ * The Streams capability backing `_resumableStream`: chat's in-flight
138
+ * output lives in the shared durable chunk log, readable by any
139
+ * `streams.read()` consumer on this Durable Object.
140
+ */
141
+ readonly streams: Streams;
118
142
  /**
119
143
  * Resumable stream manager -- handles chunk buffering, persistence, and replay.
120
144
  * @internal Protected for testing purposes.
@@ -166,9 +190,9 @@ declare class AIChatAgent<
166
190
  */
167
191
  private _turnQueue;
168
192
  /**
169
- * When true, chat turns are wrapped in `runFiber` for durable execution.
170
- * Enables `onChatRecovery` hook and `this.stash()` during streaming.
171
- * Set to `true` in subclasses to enable durable streaming.
193
+ * Durable chat recovery configuration. Every chat turn runs in `runFiber`,
194
+ * enabling `onChatRecovery` and `this.stash()` during streaming. Assign an
195
+ * object to tune recovery budgets and terminal behavior.
172
196
  *
173
197
  * Assign this as a class field or in the constructor — NOT in `onStart()`.
174
198
  * On every wake the SDK evaluates recovery budgets (and may seal an
@@ -180,10 +204,9 @@ declare class AIChatAgent<
180
204
  /**
181
205
  * Inactivity watchdog for the live model/transport stream, in milliseconds.
182
206
  * If more than this many ms elapse between stream chunks, the turn is aborted
183
- * and — when {@link chatRecovery} is enabled — routed into bounded recovery
184
- * (the same continuation machinery as a deploy/eviction interruption, #1626)
185
- * rather than parking forever on a hung provider. With recovery disabled, a
186
- * stall instead surfaces as a terminal stream error (kills the spinner).
207
+ * and routed into bounded recovery (the same continuation machinery as a
208
+ * deploy or eviction interruption, #1626) rather than parking forever on a
209
+ * hung provider.
187
210
  *
188
211
  * Default `0` disables the watchdog (opt-in), matching `@cloudflare/think`.
189
212
  * A value such as `60_000` (60s) is a reasonable starting point; tune it
@@ -256,13 +279,6 @@ declare class AIChatAgent<
256
279
  * @internal
257
280
  */
258
281
  protected _lastBody: Record<string, unknown> | undefined;
259
- /**
260
- * Cache of last-persisted JSON for each message ID.
261
- * Used for incremental persistence: skip SQL writes for unchanged messages.
262
- * Lost on hibernation, repopulated from SQLite on wake.
263
- * @internal
264
- */
265
- private _persistedMessageCache;
266
282
  /**
267
283
  * Shared auto-continuation barrier (#1649 / #1650): owns the coalesce timer
268
284
  * and the double-fire guard. Parameterized by this agent's stream-active
@@ -346,6 +362,35 @@ declare class AIChatAgent<
346
362
  | {
347
363
  timeout: number;
348
364
  };
365
+ /**
366
+ * Live chat-turn closures keyed by run nonce. A closure exists only in the
367
+ * isolate that accepted the turn; recovery after interruption never re-runs
368
+ * it — the definition's `recover` callback hands the interruption to the
369
+ * shared ChatRecoveryEngine instead.
370
+ */
371
+ private readonly _liveChatTurnClosures;
372
+ /**
373
+ * Register the shared chat-turn Task definition (see
374
+ * `agents/chat` `createChatTurnTaskDefinition` for the turn logic): the
375
+ * host wires its protected internals through the hooks.
376
+ */
377
+ private _registerChatTurnTaskDefinition;
378
+ /** Register the shared Tasks transport for recovery continuations. */
379
+ private _registerChatRecoveryTaskDefinition;
380
+ /**
381
+ * Run a queue-driven recovery callback to its model handoff and return;
382
+ * the turn continues as tracked alarm work, and a detached platform
383
+ * failure enqueues one replacement attempt through the same transport.
384
+ */
385
+ private _dispatchChatRecovery;
386
+ /**
387
+ * Enqueue one recovery attempt on the shared Tasks transport. Tasks
388
+ * mirrors a routed dynamic agent's wake to the root's alarm; the run
389
+ * itself, and this continuation's replay, still execute here. `dedupeKey`
390
+ * keys a retried enqueue so it joins its own prior attempt instead of
391
+ * duplicating it — see {@link chatRecoveryTaskRunOptions}.
392
+ */
393
+ private _enqueueChatRecovery;
349
394
  private _runChatRecoveryFiber;
350
395
  /**
351
396
  * Array of chat messages for the current conversation.
@@ -433,46 +478,33 @@ declare class AIChatAgent<
433
478
  /** @internal Delegate to _resumableStream */
434
479
  protected _completeStream(streamId: string): void;
435
480
  /**
436
- * Ensure a single cleanup alarm is pending for this DO's resumable-stream
437
- * buffers. Armed whenever a stream finishes (completes or errors) so that
438
- * idle/one-off chat DOs still reclaim their buffers — the lazy sweep in
439
- * {@link ResumableStream} only fires when a *subsequent* stream completes,
440
- * which never happens for a chat that receives a single turn (#1706).
441
- *
442
- * `idempotent` dedupes on (callback, payload, owner) so repeated finishes
443
- * collapse onto one pending alarm rather than stacking.
444
- * @internal
481
+ * @internal The producer finished; leave the row for the cutover that
482
+ * persists the message (`persistMessages` via `#pendingCutover`). `_reply`'s
483
+ * finally settles it if no persist follows.
445
484
  */
446
- protected _ensureStreamCleanupScheduled({
447
- idempotent
448
- }?: {
449
- idempotent?: boolean;
450
- }): Promise<void>;
485
+ protected _finishStream(streamId: string): void;
486
+ private _afterStreamFinished;
451
487
  /**
452
- * Alarm callback: sweep aged stream buffers, re-arming while rows remain (see
453
- * the shared {@link cleanupStreamBuffers}). Public so it is reachable as a
454
- * schedule callback.
488
+ * @deprecated Streams are reclaimed at cutover and on the next stream
489
+ * start; no alarm is armed any more. Kept so a cleanup alarm persisted
490
+ * by an earlier version still resolves to a callback when it fires.
455
491
  * @internal
456
492
  */
457
493
  _cleanupStreamBuffers(): Promise<void>;
458
- /** @internal Delegate to _resumableStream. Also advances the recovery
459
- * progress counter at production time (see `_maybeBumpRecoveryProgress`). */
494
+ /**
495
+ * @internal Delegate to _resumableStream.
496
+ *
497
+ * A settled tool result (`tool-output-available` / `-error` / `-denied`)
498
+ * is flushed to SQLite immediately rather than waiting for the packed
499
+ * segment to fill: it captures a completed, often non-idempotent side
500
+ * effect (or a user's denial), and an isolate eviction before the next
501
+ * batch flush would lose it — recovery would re-anchor without it and
502
+ * re-run the tool. The flush is also what the recovery progress marker is
503
+ * derived from (`_chatRecoveryProgressMarker`), so a settled result counts
504
+ * as forward progress the moment it lands, as it did under the old
505
+ * per-chunk counter. Streaming deltas keep the buffer's own packing.
506
+ */
460
507
  protected _storeStreamChunk(streamId: string, body: string): Promise<void>;
461
- /** Per-isolate throttle for crediting recovery progress from mid-segment
462
- * streaming-content deltas (the shared `agents/chat` rule); reset per isolate
463
- * so the first delta after a restart always credits. */
464
- private _streamProgressCredit;
465
- /** Advance the recovery-progress counter when a chunk represents genuinely
466
- * new produced content. Uses the shared host-agnostic rule
467
- * ({@link shouldCreditStreamProgress}): a milestone (started segment / settled
468
- * tool) always credits, and a long single segment's streaming deltas credit
469
- * through a time throttle so the no-progress window doesn't false-fire while
470
- * content streams across crashes. Bumped at production time, so it reflects
471
- * real forward progress and is immune to client reconnects / recovery
472
- * re-persists (which replay or re-materialize stored chunks rather than flow
473
- * through here). This is what the recovery no-progress window keys off
474
- * (#1637), and stays compaction-proof (#1628). */
475
- private _maybeBumpRecoveryProgress;
476
508
  /** @internal Delegate to _resumableStream */
477
509
  protected _flushChunkBuffer(): void;
478
510
  /** @internal Delegate to _resumableStream */
@@ -491,9 +523,8 @@ declare class AIChatAgent<
491
523
  * `Think` and the client reducer use), replacing a hand-rolled chunk
492
524
  * switch; it owns the `start` / `finish` / `message-metadata` handling;
493
525
  * - (b) {@link _resolveOrphanTargetId} — the id to persist under (#1691);
494
- * - (c)+(d) upsert-by-id over the flat array, the `SessionProvider`-subset
495
- * store-write shape (`getMessage` → `updateMessage` / `appendMessage`)
496
- * that `Think._upsertMessageInHistory` implements over a Session tree.
526
+ * - (c)+(d) upsert-by-id through the shared `OrphanPersistStore` shape
527
+ * (`getMessage` → `updateMessage` / `appendMessage`).
497
528
  * When a row already owns the id, the shared `reconcileOrphanPartial`
498
529
  * merge preserves an in-place tool result rather than letting a replayed
499
530
  * chunk re-advance it (ai-chat has an early tool-approval persist; hosts
@@ -527,9 +558,9 @@ declare class AIChatAgent<
527
558
  fallbackId: string
528
559
  ): string;
529
560
  /**
530
- * The orphan-persist store adapter — orphan-persist steps **(c)/(d)** route
531
- * their write through this shared `OrphanPersistStore` seam (the
532
- * `SessionProvider` write-subset). Backed by ai-chat's flat `this.messages`
561
+ * The orphan-persist store adapter. Orphan-persist steps **(c)/(d)** route
562
+ * through the shared `OrphanPersistStore` seam, backed by ai-chat's
563
+ * `this.messages`
533
564
  * array + the existing `persistMessages` whole-array write path, so
534
565
  * reconcile/sanitize/row-size/broadcast all stay intact. Each mutating call
535
566
  * is exactly one `persistMessages` invocation; `parentId` is unused (a flat
@@ -575,8 +606,8 @@ declare class AIChatAgent<
575
606
  * framework can't repair "inside" it the way Think does; it repairs
576
607
  * `this.messages` at each point right before handing control to
577
608
  * `onChatMessage` instead. This reaches the cases the recovery-only repair
578
- * missed: a mixed client+server orphan whose client replay drives an
579
- * auto-continuation, and any agent running with `chatRecovery` disabled.
609
+ * missed, including a mixed client+server orphan whose client replay drives
610
+ * an auto-continuation.
580
611
  *
581
612
  * Scope: repair only ever flips a DEAD SERVER orphan (an interrupted tool with
582
613
  * no settled result whose `execute()` died with the evicted isolate). A part
@@ -619,7 +650,27 @@ declare class AIChatAgent<
619
650
  * @param continuation - Whether this is a continuation of a previous stream
620
651
  */
621
652
  private _broadcastTextEvent;
622
- private _loadMessagesFromDb;
653
+ /**
654
+ * Lift ai-chat's legacy flat table into the default Sessions chain.
655
+ *
656
+ * Runs in `onStart` (before hydration), not in the constructor: the lift is
657
+ * an async import through Sessions, and the constructor does no session
658
+ * storage work at all.
659
+ *
660
+ * Order is read first as ids alone, then message bodies are fetched in
661
+ * windows bounded by row count and bytes, so a large transcript never sits
662
+ * in the isolate at once. Once every readable row has a copy the legacy
663
+ * table is DROPPED rather than renamed: keeping it would leave the object
664
+ * holding its history twice.
665
+ */
666
+ private _migrateLegacyMessages;
667
+ /**
668
+ * Hydrate `this.messages` once per wake, bounded by
669
+ * {@link hydrationByteBudget}. This is the only transcript read on the
670
+ * startup path; every later change arrives through the Sessions change
671
+ * feed.
672
+ */
673
+ private _hydrateMessages;
623
674
  private _tryCatchChat;
624
675
  private isChatTurnActive;
625
676
  /**
@@ -1169,19 +1220,19 @@ declare class AIChatAgent<
1169
1220
  * recomputed from the live, mutable transcript. Compaction collapses older
1170
1221
  * assistant messages into a summary, lowering the count — so a turn that had
1171
1222
  * genuinely advanced could read as "no progress" between attempts and exhaust
1172
- * its budget prematurely (#1628). Instead we read a durably-persisted counter
1173
- * that only ever increments — bumped at production time when new content is
1174
- * streamed (see `_storeStreamChunk` / `_maybeBumpRecoveryProgress`), which is
1175
- * genuine forward progress and is immune to client reconnects / recovery
1176
- * re-persists — so compaction can never lower it and a reconnect can't fake
1177
- * it (#1637).
1223
+ * its budget prematurely (#1628). It then became a KV counter bumped per
1224
+ * credited chunk. It is now derived from the stream log the chunks were
1225
+ * already flushed to (`ResumableStream.progressMarker`): the log only grows
1226
+ * when new content lands durably, a reconnect replay or a recovery
1227
+ * re-persist reads it without appending (#1637), and compaction rewrites
1228
+ * the transcript, not the log. Nothing is written per chunk.
1229
+ *
1230
+ * The pre-derivation KV counter is folded in once per isolate, so a marker
1231
+ * an in-flight incident already recorded is never read lower after the
1232
+ * upgrade.
1178
1233
  */
1179
1234
  private _chatRecoveryProgressMarker;
1180
- /** Advance the durable recovery-progress counter. Called from
1181
- * `_maybeBumpRecoveryProgress` when new content is streamed (real,
1182
- * reconnect-immune forward progress). The increment lives in the shared
1183
- * engine (agents/chat); this is the package binding. */
1184
- private _bumpChatRecoveryProgress;
1235
+ private _progressSeed;
1185
1236
  /** Per-isolate N9 throttle gate (shared `agents/chat` helper); reset per
1186
1237
  * isolate so the first forwarded chunk after a restart always credits. */
1187
1238
  private _agentToolStreamProgress;
@@ -1189,7 +1240,9 @@ declare class AIChatAgent<
1189
1240
  * N9: forwarding a sub-agent's chunks IS forward progress for this parent
1190
1241
  * turn, so credit the parent's recovery progress marker — otherwise a parent
1191
1242
  * whose turn merely `await`s a child banks no progress of its own and its
1192
- * no-progress window exhausts while the child is healthily streaming. Only
1243
+ * no-progress window exhausts while the child is healthily streaming. The
1244
+ * child's output goes to clients, not to this object's stream log, so the
1245
+ * derived marker cannot see it; this is the one explicit credit left. Only
1193
1246
  * invoked after a child actually produced output (see
1194
1247
  * `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.
1195
1248
  * Throttled (and reset per isolate) so we never write storage per token.
@@ -1284,6 +1337,10 @@ declare class AIChatAgent<
1284
1337
  _ctx: ChatRecoveryContext$1
1285
1338
  ): Promise<ChatRecoveryOptions$1 | void>;
1286
1339
  _chatRecoveryContinue(data?: ChatRecoveryContinueData): Promise<void>;
1340
+ protected _chatRecoveryContinueDetached(
1341
+ data?: ChatRecoveryContinueData,
1342
+ onTurnStarted?: () => void
1343
+ ): Promise<void>;
1287
1344
  private _applyRecoveredRequestContext;
1288
1345
  /**
1289
1346
  * Route a live stream stall (the {@link chatStreamStallTimeoutMs} watchdog
@@ -1295,9 +1352,7 @@ declare class AIChatAgent<
1295
1352
  * Unlike Think there is no durable-submission layer to complete here, so the
1296
1353
  * schedule payload carries no `recoveredRequestId`.
1297
1354
  *
1298
- * Returns `"disabled"` when chat recovery is off (the caller then surfaces the
1299
- * stall as a terminal stream error — the watchdog's "kill the spinner"
1300
- * guarantee), `"exhausted"` when the budget was spent (terminal UX already
1355
+ * Returns `"exhausted"` when the budget was spent (terminal UX already
1301
1356
  * delivered), or `"scheduled"` when a continuation was queued.
1302
1357
  */
1303
1358
  private _routeStallToBoundedRecovery;
@@ -1358,25 +1413,33 @@ declare class AIChatAgent<
1358
1413
  * Two residual at-least-once edges, both deliberately accepted as "deliver a
1359
1414
  * second banner" ≫ "silently drop the turn":
1360
1415
  * • No `incidentId` at all in the payload (only reachable via a direct/test
1361
- * invocation — every production scheduler carries one): the synthesized
1362
- * incident can't be persisted (no key), so the guard can't arm.
1416
+ * invocation — every production recovery enqueue carries one): the
1417
+ * synthesized incident can't be persisted (no key), so the guard can't
1418
+ * arm.
1363
1419
  * • The record is swept AGAIN between two alarms (the guard re-persists on
1364
1420
  * the first, so this needs a second independent sweep) — vanishingly
1365
1421
  * unlikely.
1366
1422
  */
1367
1423
  /**
1368
- * Recovery continuation callbacks the alarm-boundary OOM circuit breaker may
1369
- * back off / purge (#1825). See `Agent._cf_handleAlarmMemoryLimitReset`.
1424
+ * Host memory-limit policy hook (#1825), dispatched structurally by
1425
+ * Lifecycle's circuit breaker — protected because it is framework
1426
+ * machinery, not part of the public chat API. Tasks applies the breaker to
1427
+ * root recovery runs; the routed dynamic-agent fallback applies it to
1428
+ * `recoveryLoop` schedule rows (see `RecoveryLoopScheduleOptions`). At the
1429
+ * strike budget this hook seals active incidents via
1430
+ * {@link _cf_sealMemoryLimitedRecovery}.
1370
1431
  */
1371
- protected _cf_recoveryAlarmCallbacks(): string[];
1432
+ protected onAlarmMemoryLimit(context: {
1433
+ readonly sealed: boolean;
1434
+ }): Promise<void>;
1372
1435
  /**
1373
- * Seal any still-live recovery incident as an out-of-memory exhaustion when
1374
- * the alarm circuit breaker trips at its strike budget (#1825). Runs at the
1375
- * outermost alarm frame (post-unwind), so the terminal banner / `onExhausted`
1376
- * and the sealed-incident write can land where mid-turn writes OOMed. Reuses
1377
- * the shared give-up spine via the recovery engine.
1436
+ * Seal any still-live recovery incident as an out-of-memory exhaustion
1437
+ * when the alarm circuit breaker trips at its strike budget (#1825). Runs
1438
+ * at the outermost alarm frame (post-unwind), so the terminal banner /
1439
+ * `onExhausted` and the sealed-incident write can land where mid-turn
1440
+ * writes OOMed. Reuses the shared give-up spine via the recovery engine.
1378
1441
  */
1379
- protected _cf_sealMemoryLimitedRecovery(): Promise<void>;
1442
+ private _cf_sealMemoryLimitedRecovery;
1380
1443
  private _exhaustRecoveryAfterStableTimeout;
1381
1444
  /**
1382
1445
  * Apply the tight OOM-retry budget to a recovery error (#1825). Symmetric with
@@ -1402,6 +1465,10 @@ declare class AIChatAgent<
1402
1465
  private _handleRecoveryOom;
1403
1466
  private _shouldRetryRecoveredPreStreamTurn;
1404
1467
  _chatRecoveryRetry(data?: ChatRecoveryRetryData): Promise<void>;
1468
+ protected _chatRecoveryRetryDetached(
1469
+ data?: ChatRecoveryRetryData,
1470
+ onTurnStarted?: () => void
1471
+ ): Promise<void>;
1405
1472
  /**
1406
1473
  * Extract partial text and parts from stored stream chunks.
1407
1474
  */
@@ -1425,32 +1492,24 @@ declare class AIChatAgent<
1425
1492
  private _findLastAssistantMessage;
1426
1493
  private _createStreamingAssistantMessage;
1427
1494
  /**
1428
- * Sanitizes a message for persistence by removing ephemeral provider-specific
1429
- * data that should not be stored or sent back in subsequent requests.
1495
+ * Applies the ai-chat-specific normalization Sessions does not do.
1430
1496
  *
1431
- * Pipeline:
1497
+ * Sessions already strips OpenAI ephemeral fields (itemId,
1498
+ * reasoningEncryptedContent) and drops truly empty reasoning parts on every
1499
+ * write, so those steps are not repeated here.
1432
1500
  *
1433
- * 1. **Strip OpenAI ephemeral fields**: The AI SDK's @ai-sdk/openai provider
1434
- * (v2.0.x+) defaults to using OpenAI's Responses API which assigns unique
1435
- * itemIds and reasoningEncryptedContent to message parts. When persisted
1436
- * and sent back, OpenAI rejects duplicate itemIds.
1501
+ * Pipeline:
1437
1502
  *
1438
- * 2. **Truncate provider-executed tool payloads**: Server-side tool
1503
+ * 1. **Truncate provider-executed tool payloads**: Server-side tool
1439
1504
  * executions (e.g. Anthropic code_execution, text_editor) can produce
1440
1505
  * 200KB+ payloads in `input` and `output`. These are truncated since the
1441
1506
  * model has already consumed the results.
1442
1507
  *
1443
- * 3. **Filter truly empty reasoning parts**: After stripping, reasoning parts
1444
- * with no text and no remaining providerMetadata are removed. Parts that
1445
- * still carry providerMetadata (e.g. Anthropic's redacted_thinking blocks
1446
- * with providerMetadata.anthropic.redactedData) are preserved, as they
1447
- * contain data required for round-tripping with the provider API.
1448
- *
1449
- * 4. **User hook**: Calls the overridable `sanitizeMessageForPersistence()`
1508
+ * 2. **User hook**: Calls the overridable `sanitizeMessageForPersistence()`
1450
1509
  * method, allowing subclasses to apply custom transformations.
1451
1510
  *
1452
1511
  * @param message - The message to sanitize
1453
- * @returns A new message with ephemeral provider data removed
1512
+ * @returns A new message with ai-chat's normalization applied
1454
1513
  */
1455
1514
  private _sanitizeMessageForPersistence;
1456
1515
  /**
@@ -1477,33 +1536,10 @@ declare class AIChatAgent<
1477
1536
  private static _getToolNameFromPart;
1478
1537
  private static _isOpaqueReplayFieldKey;
1479
1538
  /**
1480
- * Delete the given message rows from SQLite in batched `IN (...)` queries
1481
- * and evict them from the persistence cache. Batches stay within the SQLite
1482
- * 100 bound-parameter limit. No-op for an empty list.
1483
- * @internal
1539
+ * Delete message rows through Sessions. The change feed removes them from
1540
+ * `this.messages`.
1484
1541
  */
1485
1542
  private _deleteMessagesByIds;
1486
- /**
1487
- * Deletes oldest messages from SQLite when the count exceeds maxPersistedMessages.
1488
- * Called after each persist to keep storage bounded.
1489
- */
1490
- private _enforceMaxPersistedMessages;
1491
- /**
1492
- * Enforces SQLite row size limits by compacting tool outputs and text parts
1493
- * when a serialized message exceeds the safety threshold (1.8MB).
1494
- *
1495
- * Only fires in pathological cases (extremely large tool outputs or text).
1496
- * Returns the message unchanged if it fits within limits.
1497
- *
1498
- * Compaction strategy:
1499
- * 1. Compact tool outputs over 1KB (replace with LLM-friendly summary)
1500
- * 2. If still too big, truncate text parts from oldest to newest
1501
- * 3. Add metadata so clients can detect compaction
1502
- *
1503
- * @param message - The message to check
1504
- * @returns The message, compacted if necessary
1505
- */
1506
- private _enforceRowSizeLimit;
1507
1543
  /**
1508
1544
  * Shared helper for finding a tool part by toolCallId and applying an update.
1509
1545
  * Handles both streaming (in-memory) and persisted (SQLite) messages.