@cloudflare/think 0.8.8 → 0.9.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.
@@ -56,6 +56,7 @@ import {
56
56
  ChatRecoveryProgressContext,
57
57
  ChatResponseResult,
58
58
  ChatResponseResult as ChatResponseResult$1,
59
+ ClientToolExecutor,
59
60
  ClientToolSchema,
60
61
  MessageConcurrency,
61
62
  MessageConcurrency as MessageConcurrency$1,
@@ -82,6 +83,38 @@ import {
82
83
  import { ChatSdkStateAdapterOptions, ChatSdkStateAgent } from "agents/chat-sdk";
83
84
  import { RpcTarget } from "cloudflare:workers";
84
85
 
86
+ //#region src/media-eviction.d.ts
87
+ interface MediaEvictionConfig {
88
+ /**
89
+ * Messages at the tail of the active path that are never evicted.
90
+ * Think clamps this to at least the read-time truncation window
91
+ * (4 messages — the recent span the model replays at full fidelity),
92
+ * so a misconfigured low value can never strip content the model
93
+ * still sees.
94
+ * @default 8
95
+ */
96
+ keepRecentMessages?: number;
97
+ /**
98
+ * Minimum serialized size (in characters; base64 is ASCII so this equals
99
+ * bytes for media) of a single part value to evict.
100
+ * @default 32 * 1024
101
+ */
102
+ minPartBytes?: number;
103
+ /**
104
+ * Preserve evicted values as workspace files under
105
+ * `/attachments/evicted/` instead of dropping them. The marker records
106
+ * the file path.
107
+ * @default true
108
+ */
109
+ externalizeToWorkspace?: boolean;
110
+ /**
111
+ * Maximum oversized stored rows processed per pass. Bounds how long a
112
+ * single pass can take; remaining rows are picked up by later passes.
113
+ * @default 64
114
+ */
115
+ maxRowsPerPass?: number;
116
+ }
117
+ //#endregion
85
118
  //#region src/messengers/events.d.ts
86
119
  type MessengerEventKind =
87
120
  | "direct-message"
@@ -447,6 +480,26 @@ type ChatRecoveryContinueData = {
447
480
  lastClientTools?: ClientToolSchema[] | null;
448
481
  recoveredRequestId?: string;
449
482
  };
483
+ /**
484
+ * A best-effort internal `onStart` step that failed on this wake and was
485
+ * skipped so the agent could still come up (#1710).
486
+ *
487
+ * - `transcript-hydration` — reading the persisted conversation into the
488
+ * in-memory message cache failed (e.g. `SQLITE_NOMEM` on an oversized,
489
+ * media-heavy transcript). The agent starts with an empty in-memory view;
490
+ * persisted history is untouched and the next safe-boundary sync retries.
491
+ * - `scheduled-task-reconcile` — declarative scheduled tasks were not
492
+ * reconciled on this wake; the next successful wake reconciles them.
493
+ * - `durable-work-recovery` — pending submissions / workflow notifications
494
+ * were not recovered or drained on this wake.
495
+ */
496
+ interface OnStartDegradation {
497
+ step:
498
+ | "transcript-hydration"
499
+ | "scheduled-task-reconcile"
500
+ | "durable-work-recovery";
501
+ error: unknown;
502
+ }
450
503
  /**
451
504
  * Callback interface for streaming chat events from a Think sub-agent.
452
505
  *
@@ -505,6 +558,28 @@ interface StreamableResult {
505
558
  */
506
559
  interface ChatOptions {
507
560
  signal?: AbortSignal;
561
+ /**
562
+ * Client-defined tool schemas to expose to the model for this turn, mirroring
563
+ * the `clientTools` carried over the WebSocket chat protocol. Use this when a
564
+ * parent agent delegates to a Think sub-agent over RPC but the sub-agent still
565
+ * needs access to tools the client (or parent) defines at runtime.
566
+ *
567
+ * On their own these are execute-less — the model's call surfaces as a tool
568
+ * call through the stream callback. Provide {@link ChatOptions.onClientToolCall}
569
+ * to also resolve those calls inline so the turn can continue to completion.
570
+ */
571
+ clientTools?: ClientToolSchema[];
572
+ /**
573
+ * Executes a client tool call and returns its output, completing the
574
+ * round trip for {@link ChatOptions.clientTools} within the same turn.
575
+ *
576
+ * Without this, a client-tool call has no result and the turn ends with a
577
+ * dangling tool call (the RPC stream callback has no inbound result channel).
578
+ * With it, the model can call a client tool, receive the result, and keep
579
+ * going — the same multi-step behavior the WebSocket path gets from
580
+ * `cf_agent_tool_result` messages.
581
+ */
582
+ onClientToolCall?: ClientToolExecutor;
508
583
  }
509
584
  type AgentToolChildRunStatus =
510
585
  | "starting"
@@ -646,6 +721,13 @@ interface TurnInput {
646
721
  signal?: AbortSignal;
647
722
  /** Client-provided tool schemas for dynamic tool registration. */
648
723
  clientTools?: ClientToolSchema[];
724
+ /**
725
+ * Executor that resolves client-tool calls inline (RPC `chat()` path). When
726
+ * present, `clientTools` are built WITH an `execute` that delegates to it, so
727
+ * the turn completes the tool round trip itself instead of surfacing a
728
+ * dangling tool call. Not persisted — recovery cannot replay a live executor.
729
+ */
730
+ clientToolExecutor?: ClientToolExecutor;
649
731
  /** Custom body fields from the client request. */
650
732
  body?: Record<string, unknown>;
651
733
  /** Internal workflow prompt configuration, never sourced from client body. */
@@ -738,6 +820,16 @@ interface TurnConfig {
738
820
  experimental_telemetry?: Parameters<
739
821
  typeof streamText
740
822
  >[0]["experimental_telemetry"];
823
+ /**
824
+ * Optional AI SDK stream transform(s) for this turn (`experimental_transform`).
825
+ * Forwarded to `streamText` so callers can inspect/rewrite the stream — e.g.
826
+ * detecting tool results that carry `{ content, sources }` and enqueuing
827
+ * additional `source` parts via the transform's controller. Accepts a single
828
+ * transform or an array applied in order.
829
+ */
830
+ experimental_transform?: Parameters<
831
+ typeof streamText
832
+ >[0]["experimental_transform"];
741
833
  /**
742
834
  * Optional structured-output specification (AI SDK `output`).
743
835
  * Forwarded to `streamText` so the model's final response is parsed
@@ -1074,6 +1166,65 @@ declare class Think<
1074
1166
  * @default "queue"
1075
1167
  */
1076
1168
  messageConcurrency: MessageConcurrency;
1169
+ /**
1170
+ * Byte budget for hydrating the persisted transcript into the in-memory
1171
+ * message cache (`this.messages`).
1172
+ *
1173
+ * Hydration runs on every wake (and at safe boundaries during a session).
1174
+ * Without a budget it materializes the ENTIRE stored conversation — for
1175
+ * long-lived, media-heavy sessions that footprint approaches the isolate's
1176
+ * 128MB memory budget and the next SQLite allocation fails with
1177
+ * `SQLITE_NOMEM`, permanently bricking the DO (#1710).
1178
+ *
1179
+ * When the stored path exceeds the budget, only the most recent messages
1180
+ * that fit are hydrated — never fewer than the recent window the model
1181
+ * sees at full fidelity (the `truncateOlderMessages` default of 4), even
1182
+ * when those messages alone exceed the budget — a
1183
+ * `chat:hydration:windowed` observability event is emitted, and
1184
+ * `this.messages` exposes the bounded window. Durable storage is never
1185
+ * truncated by this — `session.getHistory()` still reads the full path.
1186
+ * The model-facing context is unaffected: older content is already
1187
+ * truncated at read time before each turn, and the hydration floor
1188
+ * guarantees the full-fidelity span is always present.
1189
+ *
1190
+ * The default (24MB) leaves headroom for the ~2-3x amplification between
1191
+ * stored JSON and parsed in-memory messages. Set to
1192
+ * `Number.POSITIVE_INFINITY` (or any non-positive value) to disable
1193
+ * windowing and always hydrate the full transcript.
1194
+ *
1195
+ * @default 24 * 1024 * 1024
1196
+ */
1197
+ hydrationByteBudget: number;
1198
+ /**
1199
+ * Bound the PERSISTED transcript footprint by evicting oversized inline
1200
+ * media (base64 data-URL attachments, large strings inside tool outputs)
1201
+ * from messages that have aged out of the recent window.
1202
+ *
1203
+ * Read-time truncation already hides aged media from the model, but the
1204
+ * bytes stay in storage forever and are rehydrated on every wake — the
1205
+ * boot footprint grows with every image a session ever produced until
1206
+ * SQLite's allocator fails with `SQLITE_NOMEM` (#1710). Eviction passes
1207
+ * run in the background after the agent starts and as the conversation
1208
+ * grows; each pass processes a bounded number of oversized rows.
1209
+ *
1210
+ * By default evicted values are preserved as workspace files under
1211
+ * `/attachments/evicted/` (same Durable Object storage, but outside the
1212
+ * hydration path) and the in-message marker records the file path.
1213
+ * Pass a {@link MediaEvictionConfig} with `externalizeToWorkspace: false`
1214
+ * to drop the bytes instead of preserving them. Set this field to
1215
+ * `false` to disable eviction entirely.
1216
+ *
1217
+ * `keepRecentMessages` is clamped to at least the recent window the model
1218
+ * replays at full fidelity (4 messages), so eviction can never rewrite
1219
+ * content the model still sees.
1220
+ *
1221
+ * Requires a SessionProvider that implements `getHistoryRowStats`
1222
+ * (the default DO SQLite provider does); otherwise eviction is a no-op
1223
+ * and a warning is logged once.
1224
+ *
1225
+ * @default true
1226
+ */
1227
+ mediaEviction: MediaEvictionConfig | boolean;
1077
1228
  /**
1078
1229
  * When true, chat turns are wrapped in `runFiber` for durable execution.
1079
1230
  * Enables `onChatRecovery` hook and `this.stash()` during streaming.
@@ -1096,6 +1247,24 @@ declare class Think<
1096
1247
  session: Session;
1097
1248
  /** Cached messages — kept in sync with session storage. */
1098
1249
  private _cachedMessages;
1250
+ /**
1251
+ * Internal onStart steps that failed on this wake and were skipped so the
1252
+ * agent could still come up.
1253
+ *
1254
+ * onStart failures are terminal: partyserver resets its init state and
1255
+ * rethrows, so every subsequent wake — including platform alarm retries —
1256
+ * re-runs the failing onStart. A data-driven failure (e.g. SQLITE_NOMEM
1257
+ * hydrating an oversized transcript) would otherwise permanently brick the
1258
+ * DO and drive an unbounded alarm-retry loop (#1710).
1259
+ */
1260
+ protected _onStartDegradations: OnStartDegradation[];
1261
+ /**
1262
+ * Internal onStart steps that failed on this wake and were skipped so the
1263
+ * agent could still come up (see {@link OnStartDegradation}). Empty when
1264
+ * boot was clean. Lets hosts and operators surface degraded boots —
1265
+ * e.g. via a health RPC — without subclassing.
1266
+ */
1267
+ getOnStartDegradations(): ReadonlyArray<OnStartDegradation>;
1099
1268
  private _activeMessengerContext?;
1100
1269
  private _messengerRuntime?;
1101
1270
  /**
@@ -1130,6 +1299,14 @@ declare class Think<
1130
1299
  * ```
1131
1300
  */
1132
1301
  workspace: WorkspaceLike;
1302
+ /**
1303
+ * The codemode runtime behind the execute tool, when one has been created
1304
+ * via `createExecuteRuntime(this)` / `createExecuteTool(this)` (from
1305
+ * `@cloudflare/think/tools/execute`). Gives callables and lifecycle hooks
1306
+ * access to approvals (`approve`/`reject`/`pending`), the audit trail
1307
+ * (`executions`), `expirePaused`, and snippets.
1308
+ */
1309
+ codemode?: import("@cloudflare/codemode").CodemodeRuntimeHandle;
1133
1310
  /**
1134
1311
  * Include the default workspace Bash tool. Enabled by default so models can
1135
1312
  * run shell-style multi-file workflows against the workspace. Set to `false`
@@ -1146,9 +1323,32 @@ declare class Think<
1146
1323
  * through this cache so in-flight turns, tool updates, and recovery state all
1147
1324
  * observe the same message list. Use `_syncMessages()` only at safe
1148
1325
  * boundaries where a full storage reread cannot drop in-flight state.
1326
+ *
1327
+ * When the stored transcript exceeds `hydrationByteBudget`, this view is a
1328
+ * bounded window of the most recent messages (see `_lastHydration`); the
1329
+ * full history remains readable via `session.getHistory()`.
1149
1330
  */
1150
1331
  get messages(): UIMessage[];
1151
- /** Read the durable message path from session storage. */
1332
+ /**
1333
+ * Read the durable message path from session storage.
1334
+ *
1335
+ * Intentionally UNBUDGETED — unlike the cache refresh in `_syncMessages`,
1336
+ * which routes through `session.getRecentHistory(hydrationByteBudget)`, this
1337
+ * returns the full active path. Callers (message reconciliation, tool-update
1338
+ * application) must see every message: reconciliation diffs incoming client
1339
+ * messages against the complete server transcript, and a tool result can
1340
+ * target any message on the path, so a windowed read would drop rows and
1341
+ * corrupt the result.
1342
+ *
1343
+ * These full reads are not the unbounded boot-time hydration that bricked the
1344
+ * DO in #1710: they run during a live turn (never in `onStart`), so an
1345
+ * `SQLITE_NOMEM` here surfaces as a recoverable turn-level error rather than a
1346
+ * partyserver init-reset/alarm-retry loop. They also inherit step 1's
1347
+ * mitigation — `session.getHistory()` now fetches content in bounded chunks
1348
+ * (`messagesByPathIds`) instead of carrying blobs through the recursive CTE
1349
+ * and its `ORDER BY` sorter — and background media eviction shrinks the stored
1350
+ * footprint over time, so the steady-state read size converges down.
1351
+ */
1152
1352
  private _readMessagesFromStorage;
1153
1353
  /**
1154
1354
  * Normalize a tool part's `input` into something the provider will accept.
@@ -1216,9 +1416,91 @@ declare class Think<
1216
1416
  ): UIMessage["parts"][number];
1217
1417
  private _repairToolTranscriptParts;
1218
1418
  private _repairTranscriptForProvider;
1419
+ /**
1420
+ * Run a best-effort internal onStart step, degrading on failure instead of
1421
+ * throwing.
1422
+ *
1423
+ * Throwing out of `onStart` is terminal: partyserver resets its init state
1424
+ * and rethrows, so every wake — including platform alarm retries — re-runs
1425
+ * the failing `onStart` and fails again. A data-driven failure (oversized
1426
+ * transcript, bad declared-task config) would permanently brick the DO and
1427
+ * drive an unbounded alarm-retry loop (#1710). Instead, record the
1428
+ * degradation, emit `chat:onstart:degraded`, and let the agent come up so
1429
+ * it stays reachable for remediation (compaction, clearing, redeploy).
1430
+ *
1431
+ * Returns `true` when the step succeeded.
1432
+ */
1433
+ private _runBestEffortOnStartStep;
1434
+ private _mediaEvictionRunning;
1435
+ private _mediaEvictionScheduled;
1436
+ /**
1437
+ * Schedule a background media-eviction pass (see `mediaEviction`).
1438
+ * Coalesces repeated requests; the timer fires after the current
1439
+ * event-loop work (and after `onStart`'s `blockConcurrencyWhile`), so
1440
+ * boot and turn latency are unaffected.
1441
+ */
1442
+ private _scheduleMediaEvictionPass;
1443
+ private _warnedEvictionUnsupported;
1444
+ /**
1445
+ * Evict oversized inline media from aged stored messages (#1710).
1446
+ *
1447
+ * Memory-bounded by design: row sizes come from `getHistoryRowStats()`
1448
+ * (no content loaded), only rows large enough to contain an evictable
1449
+ * part are parsed, and they are processed one at a time via
1450
+ * `session.internal_rewriteMessage` — the maintenance write path that
1451
+ * skips the full-history token-estimate broadcast a public
1452
+ * `updateMessage` performs per row. Evicted values are written to the
1453
+ * workspace BEFORE the row is rewritten, so a failed pass never loses
1454
+ * data. Best-effort: failures are logged and the next pass retries.
1455
+ *
1456
+ * The aged cutoff is `keepRecentMessages` clamped to at least
1457
+ * `MODEL_RECENT_WINDOW`: messages the model still replays at full
1458
+ * fidelity each turn are never rewritten, regardless of configuration.
1459
+ *
1460
+ * When a pass stops at `maxRowsPerPass` with eligible rows remaining,
1461
+ * another pass is scheduled automatically so a large backlog drains
1462
+ * without waiting for new appends. Termination is guaranteed: every
1463
+ * rewritten row drops below `minPartBytes` and is skipped by later
1464
+ * passes, so the eligible set strictly shrinks.
1465
+ *
1466
+ * Returns the pass totals, or `null` when eviction is disabled, already
1467
+ * running, or the provider cannot enumerate row sizes (warned once).
1468
+ */
1469
+ protected _evictAgedMediaBestEffort(): Promise<{
1470
+ messages: number;
1471
+ parts: number;
1472
+ bytes: number;
1473
+ externalizedBytes: number;
1474
+ } | null>;
1219
1475
  /** Replace the live cache with a durable storage snapshot. */
1220
1476
  private _replaceCachedMessages;
1221
- /** Refresh the live cache from durable storage at a safe boundary. */
1477
+ /**
1478
+ * Result of the most recent cache refresh when `hydrationByteBudget` is
1479
+ * active. `truncated` means `this.messages` is a bounded recent window of
1480
+ * a larger stored transcript.
1481
+ */
1482
+ protected _lastHydration: {
1483
+ truncated: boolean;
1484
+ totalContentBytes: number;
1485
+ hydratedMessages: number;
1486
+ } | null;
1487
+ private _warnedHydrationWindowed;
1488
+ /**
1489
+ * Snapshot of the last `chat:hydration:windowed` emit, used to emit on
1490
+ * CHANGE rather than on every safe-boundary sync — a chronically
1491
+ * oversized session syncs many times per turn and would otherwise spam
1492
+ * identical events.
1493
+ */
1494
+ private _lastWindowedEmit;
1495
+ /**
1496
+ * Refresh the live cache from durable storage at a safe boundary.
1497
+ *
1498
+ * Bounded by `hydrationByteBudget`: oversized transcripts hydrate as a
1499
+ * recent window instead of exhausting the isolate's memory (#1710). The
1500
+ * window never shrinks below `MODEL_RECENT_WINDOW` messages, so budgeted
1501
+ * hydration cannot starve the model-facing context assembly (which keeps
1502
+ * that many recent messages at full fidelity).
1503
+ */
1222
1504
  private _syncMessages;
1223
1505
  /** Patch or append one message in the live cache after a durable write. */
1224
1506
  private _upsertCachedMessage;
@@ -1259,6 +1541,15 @@ declare class Think<
1259
1541
  private _agentToolLastErrors;
1260
1542
  private _agentToolPreTurnAssistantIds;
1261
1543
  private _agentToolLiveSequences;
1544
+ /**
1545
+ * Request id → run id for in-flight agent-tool turns (null = resolved as
1546
+ * not an agent-tool turn, cached so unrelated turns don't re-query SQLite
1547
+ * per frame). Drives frame attribution in {@link broadcast}: a frame
1548
+ * belongs to a run iff it carries that run's turn request id, so an error
1549
+ * in an unrelated turn or a concurrent run can never leak into another
1550
+ * run's state (#1575).
1551
+ */
1552
+ private _agentToolRunsByRequestId;
1262
1553
  private _submissionTableEnsured;
1263
1554
  private _workflowNotificationTableEnsured;
1264
1555
  private _declaredScheduledTasksTableEnsured;
@@ -1271,6 +1562,14 @@ declare class Think<
1271
1562
  msg: string | ArrayBuffer | ArrayBufferView,
1272
1563
  without?: string[]
1273
1564
  ): void;
1565
+ /**
1566
+ * Resolve the agent-tool run whose turn owns a request id, or null when the
1567
+ * request is not an agent-tool turn. Falls back to the persisted child-run
1568
+ * row (whose `request_id` is written when the run's turn is bound, see
1569
+ * `startAgentToolRun`) so attribution survives a DO restart mid-run; either
1570
+ * outcome is cached.
1571
+ */
1572
+ private _agentToolRunForRequest;
1274
1573
  alarm(): Promise<void>;
1275
1574
  /**
1276
1575
  * Persist an arbitrary JSON-serializable configuration object for this
@@ -2188,6 +2487,74 @@ declare class Think<
2188
2487
  ): Promise<boolean>;
2189
2488
  private _applyToolResult;
2190
2489
  private _applyToolApproval;
2490
+ /**
2491
+ * The codemode runtime handle behind the execute tool. `this.codemode` is
2492
+ * assigned when `createExecuteRuntime(this)` / `createExecuteTool(this)`
2493
+ * runs (normally at turn start, via `getTools()`); after a DO restart no
2494
+ * turn may have run yet, so fall back to building the tools once.
2495
+ */
2496
+ private _codemodeRuntime;
2497
+ /**
2498
+ * Pending (awaiting-approval) actions across paused executions of the
2499
+ * execute tool's codemode runtime — `{ executionId, seq, connector,
2500
+ * method, args }` each, with FULL args (the transcript copy is truncated).
2501
+ * Clients reconcile approval cards against this on load.
2502
+ *
2503
+ * Client-callable (registered below — see the `callable()` calls after the
2504
+ * class body).
2505
+ */
2506
+ pendingExecutions(
2507
+ executionId?: string
2508
+ ): Promise<import("@cloudflare/codemode").PendingAction[]>;
2509
+ /**
2510
+ * Approve a paused execution and resume it. The run continues from where
2511
+ * it stopped (replaying logged work, executing the approved call); the
2512
+ * outcome — completed, errored, or paused again on the NEXT gated call —
2513
+ * replaces the paused tool output in the transcript and the chat
2514
+ * auto-continues so the model can act on it.
2515
+ *
2516
+ * Approving an execution that is no longer pending (already settled,
2517
+ * expired, or unknown) returns `{ status: "error" }` with an explanatory
2518
+ * message — it never throws.
2519
+ *
2520
+ * Client-callable.
2521
+ */
2522
+ approveExecution(executionId: string): Promise<unknown>;
2523
+ /**
2524
+ * Reject a paused execution's pending action, ending the run. The
2525
+ * transcript's paused output is replaced with
2526
+ * `{ status: "rejected", executionId, reason }` and the chat
2527
+ * auto-continues so the model can adapt (or explain) instead of erroring.
2528
+ *
2529
+ * Client-callable.
2530
+ */
2531
+ rejectExecution(executionId: string, reason?: string): Promise<unknown>;
2532
+ /**
2533
+ * Replace a paused execute-tool output in the transcript with the
2534
+ * execution's new outcome and kick the auto-continuation so the model sees
2535
+ * it.
2536
+ *
2537
+ * When no paused part carries `executionId` — the output was already
2538
+ * replaced from another tab, or compaction summarized the part away — the
2539
+ * runtime has still durably applied the approval/rejection, so the outcome
2540
+ * must not be dropped: it is appended as a system note instead, and the
2541
+ * continuation still fires so the model can act on it.
2542
+ */
2543
+ private _applyExecutionOutcome;
2544
+ /**
2545
+ * Find the tool part holding the paused output of `executionId` — in the
2546
+ * in-flight streaming accumulator first (an approval can land while a new
2547
+ * turn streams), then the persisted transcript, newest message first.
2548
+ */
2549
+ private _findPausedExecutionToolCall;
2550
+ /**
2551
+ * Find the tool part carrying `executionId` in its output. With
2552
+ * `pausedOnly`, only a still-paused output matches — used to locate the
2553
+ * part an approval outcome should replace. Without it, any settled output
2554
+ * matches — used to distinguish "already resolved elsewhere" from "the
2555
+ * part is gone from the transcript" (e.g. compacted away).
2556
+ */
2557
+ private _findExecutionToolCall;
2191
2558
  private _applyToolUpdateToMessages;
2192
2559
  protected hasPendingInteraction(): boolean;
2193
2560
  protected waitUntilStable(options?: { timeout?: number }): Promise<boolean>;
@@ -2378,31 +2745,35 @@ declare class Think<
2378
2745
  * completed the recovered submission as `error`, which bypassed
2379
2746
  * `_exhaustChatRecovery` entirely — so an app relying on `onExhausted` for the
2380
2747
  * terminal banner regressed to an eternal spinner when recovery gave up under
2381
- * extreme churn. The error path matters just as much: a non-reset throw in a
2382
- * recovery callback is SWALLOWED by `Agent._executeScheduleCallback` (only a
2383
- * code-update reset is re-thrown to preserve the one-shot row), so without
2384
- * routing it here the alarm row is deleted with no terminal UX at all — the
2385
- * half-finished message wedges silently. Shared by `_chatRecoveryRetry` and
2386
- * `_chatRecoveryContinue`.
2748
+ * extreme churn. The error path matters just as much: a non-transient throw
2749
+ * in a recovery callback is SWALLOWED by `Agent._executeScheduleCallback`
2750
+ * (only a platform transient is re-thrown to preserve the one-shot row), so
2751
+ * without routing it here the alarm row is deleted with no terminal UX at
2752
+ * all — the half-finished message wedges silently. Shared by
2753
+ * `_chatRecoveryRetry` and `_chatRecoveryContinue`.
2387
2754
  *
2388
2755
  * Exactly-once terminalization is defended by two independent guards:
2389
2756
  * 1. The `stored?.status === "exhausted"` re-entry guard below — once an
2390
2757
  * incident is sealed, a duplicate stale alarm (or retried callback)
2391
- * returns before re-firing. The sealed incident is re-persisted even when
2392
- * the record was found missing, so a swept record is re-armed for the
2393
- * guard on the next alarm.
2758
+ * returns before re-firing. The seal is persisted only AFTER the
2759
+ * terminal writes in `_exhaustChatRecovery` succeed (see the ordering
2760
+ * note at the call below), so a give-up interrupted by a platform
2761
+ * transient re-runs in full instead of being half-sealed.
2394
2762
  * 2. The durable-submission paths additionally short-circuit earlier at the
2395
2763
  * `submission_not_running` check (the submission is already `error` after
2396
2764
  * the first give-up). This is the ONLY guard `@cloudflare/ai-chat` lacks
2397
2765
  * (no submission layer), so guard #1 carries it there.
2398
2766
  *
2399
- * Two residual at-least-once edges, both deliberately accepted as "deliver a
2767
+ * Residual at-least-once edges, all deliberately accepted as "deliver a
2400
2768
  * second banner" ≫ "silently drop the turn":
2401
2769
  * • No `incidentId` at all in the payload (only reachable via a direct/test
2402
2770
  * invocation — every production scheduler carries one): the synthesized
2403
2771
  * incident can't be persisted (no key), so guard #1 can't arm.
2404
2772
  * • The record is swept AGAIN between two alarms (guard #1 re-persists on the
2405
2773
  * first, so this needs a second independent sweep) — vanishingly unlikely.
2774
+ * • A platform transient interrupts `_exhaustChatRecovery` after the banner
2775
+ * broadcast — the deferred re-run re-fires `onExhausted` + the banner
2776
+ * (the terminal writes themselves are idempotent).
2406
2777
  */
2407
2778
  private _exhaustRecoveryGiveUp;
2408
2779
  /**
@@ -2411,39 +2782,32 @@ declare class Think<
2411
2782
  * `stable_timeout`.
2412
2783
  */
2413
2784
  private _exhaustRecoveryAfterStableTimeout;
2414
- /**
2415
- * Whether an error is a transient "superseded isolate" failure — a deploy /
2416
- * code update replaced the isolate mid-invocation. Mirrors the base `Agent`
2417
- * check (`isDurableObjectCodeUpdateReset`) and MUST stay in lockstep with it:
2418
- * the base `_executeScheduleCallback` re-throws this class for a one-shot row
2419
- * (preserving it so the platform re-runs on the new code), so a recovery
2420
- * callback must also re-throw — NOT terminalize — since recovery will re-run
2421
- * and succeed on the fresh isolate. The matched family (kept identical to the
2422
- * base):
2423
- * - "Durable Object reset because its code was updated." (deploy bounce)
2424
- * - "This script has been upgraded. Please send a new request to connect to
2425
- * the new version." (a stub/connection to a superseded script)
2426
- * "Network connection lost." is intentionally excluded (a connection error,
2427
- * not an isolate replacement — see the base helper's note). The match stays
2428
- * close to the verbatim platform strings so an ordinary error mentioning
2429
- * those words isn't misclassified as a supersede.
2430
- */
2431
- private _isDeployCodeUpdateReset;
2432
2785
  /**
2433
2786
  * Handle an error thrown by `_chatRecoveryContinue` / `_chatRecoveryRetry`
2434
2787
  * after the incident was opened.
2435
2788
  *
2436
- * - A deploy code-update reset is re-thrown (after marking the incident
2437
- * `failed` for observability) so `Agent._executeScheduleCallback` preserves
2438
- * the one-shot alarm row and the platform re-runs recovery on the fresh
2439
- * isolate — the turn can still recover, so it must NOT terminalize.
2440
- * - Any OTHER error is terminalized through the give-up path
2789
+ * - A platform transient (`isPlatformTransientError` from `agents` — a
2790
+ * deploy code-update reset / script supersede, a `retryable`-flagged
2791
+ * platform error, or "Network connection lost.", looking through wrappers
2792
+ * like `SqlError` via the `cause` chain) is re-thrown (after best-effort
2793
+ * marking the incident `failed` for observability) so
2794
+ * `Agent._executeScheduleCallback` preserves the one-shot alarm row and
2795
+ * the platform re-runs recovery once it is healthy again — the turn can
2796
+ * still recover, so it must NOT terminalize. Terminalizing here was the
2797
+ * #1730 freeze: the give-up's own seal needs the very storage that is
2798
+ * down, so it throws too, burns the in-process retry budget inside the
2799
+ * same reset window, and the row is consumed milliseconds before storage
2800
+ * recovers. The submission is deliberately left `running` — the deferred
2801
+ * re-run reads it via `_readRunningSubmissionByRequestId`, so marking it
2802
+ * terminal here would turn the preserved row into a guaranteed
2803
+ * `submission_not_running` no-op skip (a self-defeating defer).
2804
+ * - Any OTHER (application) error is terminalized through the give-up path
2441
2805
  * (`onExhausted` + the `terminalMessage` banner) and NOT re-thrown. This is
2442
2806
  * the fix for the silent-seal failure mode: `_executeScheduleCallback`
2443
- * swallows a non-reset throw and then `alarm()` deletes the one-shot row, so
2444
- * without terminalizing here the half-finished turn is dropped with no
2445
- * terminal event and no banner (the user stares at a frozen message until
2446
- * they send something new).
2807
+ * swallows a non-transient throw and then `alarm()` deletes the one-shot
2808
+ * row, so without terminalizing here the half-finished turn is dropped
2809
+ * with no terminal event and no banner (the user stares at a frozen
2810
+ * message until they send something new).
2447
2811
  */
2448
2812
  private _handleRecoveryCallbackError;
2449
2813
  _chatRecoveryRetry(data?: ChatRecoveryRetryData): Promise<void>;
@@ -2601,6 +2965,57 @@ declare class Think<
2601
2965
  */
2602
2966
  private _buildIdleConnectMessages;
2603
2967
  private _notifyStreamResuming;
2968
+ /**
2969
+ * Start a resumable stream and arm buffer cleanup. Wrapper around
2970
+ * `ResumableStream.start`: arming on START as well as finish guarantees a
2971
+ * stream whose DO is evicted mid-flight and never reaches a finish still gets
2972
+ * a future sweep instead of leaking its buffer.
2973
+ *
2974
+ * When a turn runs inside `runFiber` (durable recovery), the DO already
2975
+ * self-heals: `runFiber` holds `keepAlive`, which leaves a durable alarm in
2976
+ * storage that survives eviction, fires within ~keepAliveIntervalMs, and runs
2977
+ * the fiber-recovery scan — finalizing the stream (which arms cleanup) without
2978
+ * any client reconnect. Arming here is the safety net for any non-fiber stream
2979
+ * path, where no such alarm exists. The last-activity sweep threshold prevents
2980
+ * an actively streaming run from being reclaimed before it goes quiet (#1706).
2981
+ */
2982
+ protected _startResumableStream(
2983
+ requestId: string,
2984
+ options?: {
2985
+ messageId?: string;
2986
+ }
2987
+ ): string;
2988
+ /**
2989
+ * Mark a resumable stream completed and arm buffer cleanup. Wrapper around
2990
+ * `ResumableStream.complete` so every stream-finish path also schedules the
2991
+ * cleanup alarm (#1706).
2992
+ */
2993
+ protected _completeResumableStream(streamId: string): void;
2994
+ /**
2995
+ * Mark a resumable stream errored and arm buffer cleanup. Wrapper around
2996
+ * `ResumableStream.markError` — see {@link _completeResumableStream}.
2997
+ */
2998
+ protected _errorResumableStream(streamId: string): void;
2999
+ /**
3000
+ * Ensure a single cleanup alarm is pending for this DO's resumable-stream
3001
+ * buffers. Armed whenever a stream finishes so that idle/one-off chat DOs
3002
+ * still reclaim their buffers — the lazy sweep in {@link ResumableStream}
3003
+ * only fires when a *subsequent* stream completes, which never happens for a
3004
+ * chat that receives a single turn (#1706).
3005
+ *
3006
+ * `idempotent` dedupes on (callback, payload, owner) so repeated finishes
3007
+ * collapse onto one pending alarm rather than stacking.
3008
+ */
3009
+ protected _ensureStreamCleanupScheduled({
3010
+ idempotent
3011
+ }?: {
3012
+ idempotent?: boolean;
3013
+ }): Promise<void>;
3014
+ /**
3015
+ * Alarm callback: sweep aged stream buffers, then re-arm only while rows
3016
+ * remain so a fully-swept DO stops waking itself.
3017
+ */
3018
+ _cleanupStreamBuffers(): Promise<void>;
2604
3019
  private _persistOrphanedStream;
2605
3020
  private _broadcastChat;
2606
3021
  private _broadcast;
@@ -2608,117 +3023,119 @@ declare class Think<
2608
3023
  }
2609
3024
  //#endregion
2610
3025
  export {
2611
- TurnInput as $,
2612
- MessengerEventKind as $t,
2613
- StepContext as A,
2614
- EMPTY_MESSENGER_RESPONSE as At,
2615
- ThinkScheduledTask as B,
2616
- TextStreamCallbackOptions as Bt,
2617
- ResolvedChatRecoveryConfig as C,
2618
- idempotencyKeyForEvent as Ct,
2619
- SkillRunContext as D,
2620
- toMessengerMessage as Dt,
2621
- Session$1 as E,
2622
- toMessengerAuthor as Et,
2623
- SubmitMessagesOptions as F,
2624
- MessengerDeliverySurface as Ft,
2625
- ThinkSubmissionStatus as G,
2626
- parseMessengerReplySnapshot as Gt,
2627
- ThinkScheduledTaskSchedule as H,
2628
- messengerReplyFailureMode as Ht,
2629
- SubmitMessagesResult as I,
2630
- MessengerDeliveryTarget as It,
2631
- ToolCallContext as J,
2632
- MessengerAttachment as Jt,
2633
- ThinkTime as K,
2634
- textDeltaFromStreamChunk as Kt,
2635
- TextStreamPart as L,
2636
- MessengerReplySnapshot as Lt,
2637
- StopCondition$1 as M,
2638
- INTERRUPTED_MESSENGER_RESPONSE as Mt,
2639
- StreamCallback as N,
2640
- MESSENGER_REPLY_FIBER_NAME as Nt,
2641
- SkillSource$1 as O,
2642
- toMessengerThread as Ot,
2643
- StreamableResult as P,
2644
- MessengerDeliveryPolicy as Pt,
2645
- TurnContext as Q,
2646
- MessengerEvent as Qt,
2647
- Think as R,
2648
- MessengerReplyStage as Rt,
2649
- PrepareStepResult$1 as S,
2650
- defineMessengers as St,
2651
- SaveMessagesResult$1 as T,
2652
- toMessengerAttachment as Tt,
2653
- ThinkScheduledTasks as U,
2654
- messengerReplyRecoveryMode as Ut,
2655
- ThinkScheduledTaskContext as V,
2656
- deliverMessengerReply as Vt,
2657
- ThinkSubmissionInspection as W,
2658
- messengerReplySnapshot as Wt,
2659
- ToolCallResultContext as X,
2660
- MessengerCapabilities as Xt,
2661
- ToolCallDecision as Y,
2662
- MessengerAuthor as Yt,
2663
- TurnConfig as Z,
2664
- MessengerContext as Zt,
3026
+ TurnContext as $,
3027
+ MessengerEvent as $t,
3028
+ StepConfig as A,
3029
+ DeliverMessengerReplyOptions as At,
3030
+ ThinkIntervalSchedule as B,
3031
+ TextStreamCallback as Bt,
3032
+ PrepareStepResult$1 as C,
3033
+ defineMessengers as Ct,
3034
+ Session$1 as D,
3035
+ toMessengerAuthor as Dt,
3036
+ SaveMessagesResult$1 as E,
3037
+ toMessengerAttachment as Et,
3038
+ StreamableResult as F,
3039
+ MessengerDeliveryPolicy as Ft,
3040
+ ThinkSubmissionInspection as G,
3041
+ messengerReplySnapshot as Gt,
3042
+ ThinkScheduledTaskContext as H,
3043
+ deliverMessengerReply as Ht,
3044
+ SubmitMessagesOptions as I,
3045
+ MessengerDeliverySurface as It,
3046
+ ThinkWallClockSchedule as J,
3047
+ MessengerAction as Jt,
3048
+ ThinkSubmissionStatus as K,
3049
+ parseMessengerReplySnapshot as Kt,
3050
+ SubmitMessagesResult as L,
3051
+ MessengerDeliveryTarget as Lt,
3052
+ StepResult as M,
3053
+ ERROR_MESSENGER_RESPONSE as Mt,
3054
+ StopCondition$1 as N,
3055
+ INTERRUPTED_MESSENGER_RESPONSE as Nt,
3056
+ SkillRunContext as O,
3057
+ toMessengerMessage as Ot,
3058
+ StreamCallback as P,
3059
+ MESSENGER_REPLY_FIBER_NAME as Pt,
3060
+ TurnConfig as Q,
3061
+ MessengerContext as Qt,
3062
+ TextStreamPart as R,
3063
+ MessengerReplySnapshot as Rt,
3064
+ PrepareStepFunction$1 as S,
3065
+ defaultConversationName as St,
3066
+ SaveMessagesOptions$1 as T,
3067
+ normalizeMessengers as Tt,
3068
+ ThinkScheduledTaskSchedule as U,
3069
+ messengerReplyFailureMode as Ut,
3070
+ ThinkScheduledTask as V,
3071
+ TextStreamCallbackOptions as Vt,
3072
+ ThinkScheduledTasks as W,
3073
+ messengerReplyRecoveryMode as Wt,
3074
+ ToolCallDecision as X,
3075
+ MessengerAuthor as Xt,
3076
+ ToolCallContext as Y,
3077
+ MessengerAttachment as Yt,
3078
+ ToolCallResultContext as Z,
3079
+ MessengerCapabilities as Zt,
2665
3080
  FiberRecoveryContext$1 as _,
2666
- ThinkMessengerStateAgent as _t,
3081
+ ThinkMessengerRuntime as _t,
2667
3082
  ChatRecoveryContext$1 as a,
2668
- skills as at,
2669
- PrepareStepContext as b,
2670
- defaultChatSdkEvent as bt,
3083
+ toMessengerUserMessage as an,
3084
+ defineScheduledTasks as at,
3085
+ OnStartDegradation as b,
3086
+ chatSdkMessenger as bt,
2671
3087
  ChatRecoveryProgressContext as c,
2672
- MessengerConversationMode as ct,
3088
+ ChatSdkMessengerOptions as ct,
2673
3089
  ChunkContext as d,
2674
- MessengerDefinition as dt,
2675
- MessengerMessage as en,
2676
- TypedToolCall$1 as et,
3090
+ MessengerConversationTarget as dt,
3091
+ MessengerEventKind as en,
3092
+ TurnInput as et,
2677
3093
  ChunkPart as f,
2678
- MessengerRespondTo as ft,
3094
+ MessengerDefinition as ft,
2679
3095
  FiberContext$1 as g,
2680
- ThinkMessengerRuntime as gt,
3096
+ NormalizedMessengerDefinition as gt,
2681
3097
  ExtensionConfig as h,
2682
- NormalizedMessengerDefinition as ht,
3098
+ MessengerThinkTarget as ht,
2683
3099
  ChatRecoveryConfig$1 as i,
2684
- toMessengerUserMessage as in,
2685
- defineScheduledTasks as it,
2686
- StepResult as j,
2687
- ERROR_MESSENGER_RESPONSE as jt,
2688
- StepConfig as k,
2689
- DeliverMessengerReplyOptions as kt,
3100
+ serializableMessengerEvent as in,
3101
+ defaultContextOverflowClassifier as it,
3102
+ StepContext as j,
3103
+ EMPTY_MESSENGER_RESPONSE as jt,
3104
+ SkillSource$1 as k,
3105
+ toMessengerThread as kt,
2690
3106
  ChatResponseResult$1 as l,
2691
- MessengerConversationResolver as lt,
3107
+ MessengerConversationMode as lt,
2692
3108
  DeleteSubmissionsOptions as m,
2693
- MessengerThinkTarget as mt,
3109
+ MessengerThinkHost as mt,
2694
3110
  ChatErrorContext as n,
2695
- messengerContextFromEvent as nn,
2696
- Workspace$1 as nt,
3111
+ MessengerThread as nn,
3112
+ TypedToolResult as nt,
2697
3113
  ChatRecoveryExhaustedContext as o,
2698
- ChatSdkMessengerEventInput as ot,
3114
+ MediaEvictionConfig as on,
3115
+ skills as ot,
2699
3116
  ContextOverflowConfig as p,
2700
- MessengerThinkHost as pt,
2701
- ThinkWallClockSchedule as q,
2702
- MessengerAction as qt,
3117
+ MessengerRespondTo as pt,
3118
+ ThinkTime as q,
3119
+ textDeltaFromStreamChunk as qt,
2703
3120
  ChatOptions as r,
2704
- serializableMessengerEvent as rn,
2705
- defaultContextOverflowClassifier as rt,
3121
+ messengerContextFromEvent as rn,
3122
+ Workspace$1 as rt,
2706
3123
  ChatRecoveryOptions$1 as s,
2707
- ChatSdkMessengerOptions as st,
3124
+ ChatSdkMessengerEventInput as st,
2708
3125
  ChatErrorClassification as t,
2709
- MessengerThread as tn,
2710
- TypedToolResult as tt,
3126
+ MessengerMessage as tn,
3127
+ TypedToolCall$1 as tt,
2711
3128
  ChatStartEvent as u,
2712
- MessengerConversationTarget as ut,
3129
+ MessengerConversationResolver as ut,
2713
3130
  ListSubmissionsOptions as v,
2714
- ThinkMessengers as vt,
2715
- SaveMessagesOptions$1 as w,
2716
- normalizeMessengers as wt,
2717
- PrepareStepFunction$1 as x,
2718
- defaultConversationName as xt,
3131
+ ThinkMessengerStateAgent as vt,
3132
+ ResolvedChatRecoveryConfig as w,
3133
+ idempotencyKeyForEvent as wt,
3134
+ PrepareStepContext as x,
3135
+ defaultChatSdkEvent as xt,
2719
3136
  MessageConcurrency$1 as y,
2720
- chatSdkMessenger as yt,
2721
- ThinkIntervalSchedule as z,
2722
- TextStreamCallback as zt
3137
+ ThinkMessengers as yt,
3138
+ Think as z,
3139
+ MessengerReplyStage as zt
2723
3140
  };
2724
- //# sourceMappingURL=think-8jik2oZ5.d.ts.map
3141
+ //# sourceMappingURL=think-Cike7VBF.d.ts.map