@cloudflare/think 0.17.0 → 0.18.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.
@@ -5,7 +5,7 @@ import {
5
5
  import {
6
6
  D as createWorkspaceTools,
7
7
  h as WorkspaceLike
8
- } from "./workspace-DxZQSbko.js";
8
+ } from "./workspace-CNeXc2vl.js";
9
9
  import { t as CreateFetchToolsOptions } from "./fetch-By3eIQ-a.js";
10
10
  import {
11
11
  FlexibleSchema,
@@ -35,7 +35,9 @@ import {
35
35
  SkillRunContext,
36
36
  SkillScriptRunner,
37
37
  SkillSource,
38
- SkillSource as SkillSource$1
38
+ SkillSource as SkillSource$1,
39
+ SkillWorkspaceSeedOptions,
40
+ SkillWorkspaceSeedOptions as SkillWorkspaceSeedOptions$1
39
41
  } from "agents/skills";
40
42
  import {
41
43
  Agent,
@@ -78,11 +80,28 @@ import {
78
80
  SaveMessagesResult as SaveMessagesResult$1
79
81
  } from "agents/chat";
80
82
  import {
83
+ AppendOptions,
84
+ AppendResult,
85
+ CompactResult,
86
+ CompactionFunction,
87
+ HistoryBatchReadOptions,
88
+ HistoryReadOptions,
89
+ RecentHistoryResult,
90
+ SearchResult,
81
91
  Session,
82
- Session as Session$1,
83
92
  SessionMessage,
84
- SessionMessage as SessionMessage$1
85
- } from "agents/experimental/memory/session";
93
+ SessionMessage as SessionMessage$1,
94
+ SessionRowStat,
95
+ Sessions,
96
+ StoredCompaction,
97
+ WriteOptions
98
+ } from "agents/sessions";
99
+ import {
100
+ ContextBlock,
101
+ ContextBlocks,
102
+ ContextConfig,
103
+ WritableContextProvider
104
+ } from "agents/context";
86
105
  import { Workspace as Workspace$1 } from "@cloudflare/shell";
87
106
  import {
88
107
  ActionEvent,
@@ -94,37 +113,175 @@ import {
94
113
  } from "chat";
95
114
  import { ChatSdkStateAdapterOptions, ChatSdkStateAgent } from "agents/chat-sdk";
96
115
  import { RpcTarget } from "cloudflare:workers";
116
+ import { LifecycleJobContext, LifecycleJobOutcome } from "agents/lifecycle";
117
+ import { Streams } from "agents/streams";
97
118
 
119
+ //#region src/session.d.ts
120
+ /** Options for a block declared through `withContext()` / `addContext()`. */
121
+ type SessionContextOptions = Omit<ContextConfig, "label">;
122
+ /** Receives an error thrown by the registered compaction function. */
123
+ type CompactionErrorHandler = (error: unknown) => void | Promise<void>;
124
+ /**
125
+ * @deprecated `compactAfter()` gates on the token estimate Sessions stamps on
126
+ * each row; a custom counter is no longer consulted. Accepted so existing
127
+ * calls compile.
128
+ */
129
+ interface CompactAfterOptions {
130
+ tokenCounter?: unknown;
131
+ }
132
+ declare class ThinkSession {
133
+ #private;
134
+ /** @internal Constructed by Think during `onStart`. */
135
+ constructor(handle: Session, context: () => ContextBlocks);
136
+ get sessionId(): string;
137
+ /** @internal Blocks declared through `withContext()` during configuration. */
138
+ internal_takePendingContext(): ContextConfig[];
139
+ /** @internal A custom frozen-prompt store passed to `withCachedPrompt()`. */
140
+ internal_promptStore(): WritableContextProvider | undefined;
141
+ /**
142
+ * Declare a prompt context block.
143
+ *
144
+ * @deprecated Return the block from `configureContext()` instead. Only
145
+ * callable inside `configureSession()`; after startup use
146
+ * `this.context.addBlock()`.
147
+ */
148
+ withContext(label: string, options?: SessionContextOptions): this;
149
+ /**
150
+ * Persist the frozen system prompt.
151
+ *
152
+ * @deprecated The frozen prompt is always persisted now, so this is a
153
+ * no-op. A custom `provider` is still honoured as the prompt store.
154
+ */
155
+ withCachedPrompt(provider?: WritableContextProvider): this;
156
+ /** Register the function `compact()` calls to summarize a branch. */
157
+ onCompaction(fn: CompactionFunction): this;
158
+ /**
159
+ * Auto-compact after an append once the stamped token estimate crosses the
160
+ * threshold. Requires `onCompaction()`.
161
+ */
162
+ compactAfter(tokenThreshold: number, _options?: CompactAfterOptions): this;
163
+ /**
164
+ * Observe compaction failures. When set, a failing compaction function
165
+ * calls the handler and the compaction is skipped; without one the failure
166
+ * is reported through the `session:error` capability event.
167
+ */
168
+ onCompactionError(handler: CompactionErrorHandler): this;
169
+ history(
170
+ options?: HistoryReadOptions
171
+ ): AsyncGenerator<SessionMessage, void, undefined>;
172
+ historyBatches(
173
+ options?: HistoryBatchReadOptions
174
+ ): AsyncGenerator<SessionMessage[], void, undefined>;
175
+ /**
176
+ * Materialize the whole selected path. Accepts a leaf id positionally, as
177
+ * the pre-Sessions API did, or a read-options object.
178
+ */
179
+ getHistory(
180
+ leafIdOrOptions?: string | null | HistoryReadOptions
181
+ ): Promise<SessionMessage[]>;
182
+ /**
183
+ * Byte-budgeted read of the most recent messages on the active path. The
184
+ * pre-Sessions `minRecentMessages` argument is accepted and ignored: the
185
+ * budget is a hard ceiling, and the newest message is always returned.
186
+ */
187
+ getRecentHistory(
188
+ maxContentBytes: number,
189
+ optionsOrMinRecentMessages?: number | Pick<HistoryReadOptions, "leafId">
190
+ ): Promise<RecentHistoryResult>;
191
+ getHistoryRowStats(leafId?: string | null): Promise<SessionRowStat[]>;
192
+ /** @deprecated Read `getHistoryRowStats()` and take its length. */
193
+ getPathLength(leafId?: string | null): Promise<number>;
194
+ getMessage(id: string): Promise<SessionMessage | null>;
195
+ getLatestLeaf(): Promise<SessionMessage | null>;
196
+ getBranches(messageId: string): Promise<SessionMessage[]>;
197
+ search(
198
+ query: string,
199
+ options?: {
200
+ limit?: number;
201
+ }
202
+ ): Promise<SearchResult[]>;
203
+ /**
204
+ * Append one message. Accepts the parent id positionally, as the
205
+ * pre-Sessions API did, or an options object.
206
+ */
207
+ appendMessage(
208
+ message: SessionMessage,
209
+ parentIdOrOptions?: string | null | AppendOptions
210
+ ): Promise<AppendResult>;
211
+ updateMessage(
212
+ message: SessionMessage,
213
+ options?: WriteOptions
214
+ ): Promise<SessionMessage | null>;
215
+ upsertMessage(
216
+ message: SessionMessage,
217
+ parentIdOrOptions?: string | null | AppendOptions
218
+ ): Promise<AppendResult>;
219
+ importMessage(
220
+ message: SessionMessage,
221
+ options: {
222
+ parentId: string | null;
223
+ createdAt: number;
224
+ }
225
+ ): Promise<void>;
226
+ deleteMessages(messageIds: string[]): Promise<void>;
227
+ clearMessages(): Promise<void>;
228
+ addCompaction(
229
+ summary: string,
230
+ fromMessageId: string,
231
+ toMessageId: string
232
+ ): Promise<StoredCompaction>;
233
+ getCompactions(): Promise<StoredCompaction[]>;
234
+ compact(leafId?: string | null): Promise<CompactResult | null>;
235
+ /** @deprecated Use `this.context.addBlock({ label, ...options })`. */
236
+ addContext(
237
+ label: string,
238
+ options?: SessionContextOptions
239
+ ): Promise<ContextBlock>;
240
+ /** @deprecated Use `this.context.removeBlock(label)`. */
241
+ removeContext(label: string): boolean;
242
+ /** @deprecated Use `this.context.getBlock(label)`. */
243
+ getContextBlock(label: string): ContextBlock | null;
244
+ /** @deprecated Use `this.context.getBlocks()`. */
245
+ getContextBlocks(): ContextBlock[];
246
+ /** @deprecated Use `this.context.setBlock(label, content)`. */
247
+ replaceContextBlock(label: string, content: string): Promise<ContextBlock>;
248
+ /** @deprecated Use `this.context.appendToBlock(label, content)`. */
249
+ appendContextBlock(label: string, content: string): Promise<ContextBlock>;
250
+ /** @deprecated Use `this.context.freezeSystemPrompt()`. */
251
+ freezeSystemPrompt(): Promise<string>;
252
+ /** @deprecated Use `this.context.refreshSystemPrompt()`. */
253
+ refreshSystemPrompt(): Promise<string>;
254
+ /** @deprecated Use `this.context.tools()`. */
255
+ tools(): Promise<ToolSet>;
256
+ }
257
+ //#endregion
98
258
  //#region src/media-eviction.d.ts
99
259
  interface MediaEvictionConfig {
100
260
  /**
101
261
  * Messages at the tail of the active path that are never evicted.
102
- * Think clamps this to at least the read-time truncation window
103
- * (4 messages — the recent span the model replays at full fidelity),
104
- * so a misconfigured low value can never strip content the model
105
- * still sees.
262
+ * Think clamps this to at least the read-time window the model replays at
263
+ * full fidelity, so a misconfigured low value can never strip content the
264
+ * model still sees.
106
265
  * @default 8
107
266
  */
108
267
  keepRecentMessages?: number;
109
268
  /**
110
- * Minimum serialized size (in characters; base64 is ASCII so this equals
111
- * bytes for media) of a single part value to evict.
269
+ * Minimum decoded payload size, in bytes, for a value to be evicted.
112
270
  * @default 32 * 1024
113
271
  */
114
272
  minPartBytes?: number;
115
273
  /**
116
- * Preserve evicted values as workspace files under
117
- * `/attachments/evicted/` instead of dropping them. The marker records
118
- * the file path.
119
- * @default true
120
- */
121
- externalizeToWorkspace?: boolean;
122
- /**
123
- * Maximum oversized stored rows processed per pass. Bounds how long a
124
- * single pass can take; remaining rows are picked up by later passes.
274
+ * Maximum stored rows processed per pass. Bounds how long a single pass
275
+ * can take; remaining rows are picked up by the next pass.
125
276
  * @default 64
126
277
  */
127
278
  maxRowsPerPass?: number;
279
+ /**
280
+ * @deprecated Ignored. Evicted bytes are always preserved in the Workspace
281
+ * under `/attachments/evicted/`; there is no drop-the-bytes mode. Accepted
282
+ * so existing configurations keep compiling.
283
+ */
284
+ externalizeToWorkspace?: boolean;
128
285
  }
129
286
  //#endregion
130
287
  //#region src/channels/index.d.ts
@@ -1295,6 +1452,15 @@ declare class Think<
1295
1452
  storeMessages: boolean;
1296
1453
  /** Store tool input/output on `execute_tool` spans. */
1297
1454
  storeTools: boolean;
1455
+ /**
1456
+ * Project `getSkills()` into the active workspace so the agent can read
1457
+ * and edit skills as files. Computer workspaces use
1458
+ * `/workspace/.agents/skills`; legacy Shell uses `/.agents/skills`.
1459
+ * Existing edits are preserved. Off by default: skills load from their
1460
+ * sources and nothing is written to the Workspace, as before. Set `{}` to
1461
+ * project with the defaults.
1462
+ */
1463
+ skillWorkspace: false | SkillWorkspaceSeedOptions;
1298
1464
  private _skillRegistry;
1299
1465
  private _loggedSkillWarnings;
1300
1466
  private _loggedProtocolWarnings;
@@ -1326,41 +1492,39 @@ declare class Think<
1326
1492
  * truncated at read time before each turn, and the hydration floor
1327
1493
  * guarantees the full-fidelity span is always present.
1328
1494
  *
1329
- * The default (24MB) leaves headroom for the ~2-3x amplification between
1330
- * stored JSON and parsed in-memory messages. Set to
1331
- * `Number.POSITIVE_INFINITY` (or any non-positive value) to disable
1332
- * windowing and always hydrate the full transcript.
1495
+ * The budget counts what hydration actually costs: a row's stored bytes
1496
+ * plus the attachment bytes its pointers inflate back when reconstructed
1497
+ * inline. A pointer row is therefore charged its payload, not its ~100
1498
+ * stored bytes, so the ceiling bounds isolate memory rather than the
1499
+ * on-disk footprint. Set to `Number.POSITIVE_INFINITY` (or any
1500
+ * non-positive value) to disable windowing and always hydrate the full
1501
+ * transcript.
1333
1502
  *
1334
- * @default 24 * 1024 * 1024
1503
+ * @default 32 * 1024 * 1024
1335
1504
  */
1336
1505
  hydrationByteBudget: number;
1337
1506
  /**
1338
- * Bound the PERSISTED transcript footprint by evicting oversized inline
1339
- * media (base64 data-URL attachments, large strings inside tool outputs)
1340
- * from messages that have aged out of the recent window.
1507
+ * Aged-media eviction — a CONTEXT-WINDOW technique, not a storage setting.
1341
1508
  *
1342
- * Read-time truncation already hides aged media from the model, but the
1343
- * bytes stay in storage forever and are rehydrated on every wake — the
1344
- * boot footprint grows with every image a session ever produced until
1345
- * SQLite's allocator fails with `SQLITE_NOMEM` (#1710). Eviction passes
1346
- * run in the background after the agent starts and as the conversation
1347
- * grows; each pass processes a bounded number of oversized rows.
1509
+ * Once media has aged past `keepRecentMessages` on the active path, Think
1510
+ * removes it from the conversation so the model stops re-reading a large
1511
+ * image on every turn, and leaves a marker naming a Workspace file under
1512
+ * `/attachments/evicted/`. The bytes are written raw with their real mime
1513
+ * type, so the agent can read the picture back with the workspace `read`
1514
+ * tool when it deliberately needs it again. Visible to the model and lossy
1515
+ * on purpose.
1348
1516
  *
1349
- * By default evicted values are preserved as workspace files under
1350
- * `/attachments/evicted/` (same Durable Object storage, but outside the
1351
- * hydration path) and the in-message marker records the file path.
1352
- * Pass a {@link MediaEvictionConfig} with `externalizeToWorkspace: false`
1353
- * to drop the bytes instead of preserving them. Set this field to
1354
- * `false` to disable eviction entirely.
1517
+ * This is separate from Sessions attachment storage, which is invisible
1518
+ * and lossless: a large payload may be held as an `attachment:sha256:`
1519
+ * pointer whether eviction is on or off.
1520
+ *
1521
+ * `false` keeps aged media in the conversation, so the model keeps seeing
1522
+ * it. It does NOT change where Sessions keeps the bytes.
1355
1523
  *
1356
1524
  * `keepRecentMessages` is clamped to at least the recent window the model
1357
1525
  * replays at full fidelity (4 messages), so eviction can never rewrite
1358
1526
  * content the model still sees.
1359
1527
  *
1360
- * Requires a SessionProvider that implements `getHistoryRowStats`
1361
- * (the default DO SQLite provider does); otherwise eviction is a no-op
1362
- * and a warning is logged once.
1363
- *
1364
1528
  * @default true
1365
1529
  */
1366
1530
  mediaEviction: MediaEvictionConfig | boolean;
@@ -1377,16 +1541,21 @@ declare class Think<
1377
1541
  */
1378
1542
  chatRecovery: ChatRecoveryConfig;
1379
1543
  static readonly CHAT_FIBER_NAME = "__cf_internal_chat_turn";
1544
+ /** Durable conversation history installed on this Agent's Lifecycle. */
1545
+ readonly sessions: Sessions;
1380
1546
  /**
1381
- * The conversation session — messages, context, compaction, search.
1382
- *
1383
- * Direct message writes are observed and mirrored into Think's live cache.
1384
- * Prefer the history helpers below when writing UI messages from subclasses;
1385
- * they sanitize content and enforce row-size limits before delegating here.
1547
+ * The default conversation handle configured by `configureSession()`.
1548
+ * Storage lives on the `agents/sessions` handle it wraps; the context
1549
+ * methods it still carries forward to {@link Think.context}.
1386
1550
  */
1387
- session: Session;
1388
- /** Cached messages — kept in sync with session storage. */
1551
+ session: ThinkSession;
1552
+ /**
1553
+ * The agent's context blocks. Available once the Lifecycle has started.
1554
+ */
1555
+ protected get context(): ContextBlocks;
1556
+ /** Cached messages, kept in sync with session storage. */
1389
1557
  private _cachedMessages;
1558
+ private _unsubscribeSessionChanges;
1390
1559
  /**
1391
1560
  * Internal onStart steps that failed on this wake and were skipped so the
1392
1561
  * agent could still come up.
@@ -1504,11 +1673,12 @@ declare class Think<
1504
1673
  *
1505
1674
  * Intentionally UNBUDGETED — unlike the cache refresh in `_syncMessages`,
1506
1675
  * which routes through `session.getRecentHistory(hydrationByteBudget)`, this
1507
- * returns the full active path. Callers (message reconciliation, tool-update
1508
- * application) must see every message: reconciliation diffs incoming client
1509
- * messages against the complete server transcript, and a tool result can
1510
- * target any message on the path, so a windowed read would drop rows and
1511
- * corrupt the result.
1676
+ * returns the full active path. Its caller, message reconciliation, must see
1677
+ * every message: it diffs incoming client messages against the complete
1678
+ * server transcript, so a windowed read would drop rows and corrupt the
1679
+ * result. It is reached only when the live cache does not already cover the
1680
+ * path (`_serverTranscriptForReconcile`); tool-update application resolves
1681
+ * its one target row without it (`_resolveToolCallOwner`).
1512
1682
  *
1513
1683
  * These full reads are not the unbounded boot-time hydration that bricked the
1514
1684
  * DO in #1710: they run during a live turn (never in `onStart`), so an
@@ -1584,48 +1754,71 @@ declare class Think<
1584
1754
  private _runBestEffortOnStartStep;
1585
1755
  private _mediaEvictionRunning;
1586
1756
  private _mediaEvictionScheduled;
1587
- private _mediaEvictionObservedOversized;
1588
1757
  /**
1589
- * Schedule a background media-eviction pass (see `mediaEviction`).
1590
- * Coalesces repeated requests; the timer fires after the current
1591
- * event-loop work (and after `onStart`'s `blockConcurrencyWhile`), so
1592
- * boot and turn latency are unaffected.
1758
+ * A request that arrived while a pass was running. That pass read its
1759
+ * candidates before the request's append landed, so the request is kept
1760
+ * and re-evaluated once the pass ends rather than dropped.
1593
1761
  */
1594
- private _scheduleMediaEvictionPass;
1595
- private _scheduleMediaEvictionAfterAppend;
1596
- private _refreshMediaEvictionSignalFromCache;
1597
- private _messageMayNeedMediaEviction;
1762
+ private _mediaEvictionPending;
1763
+ /**
1764
+ * Linear appends that landed while a pass was running. The pass read its
1765
+ * candidates before them, so a fruitless result records them as appends
1766
+ * since — not zero — and the request they left pending can pass the gate.
1767
+ */
1768
+ private _mediaEvictionAppendsDuringPass;
1598
1769
  private _warnedEvictionUnsupported;
1599
1770
  /**
1600
- * Evict oversized inline media from aged stored messages (#1710).
1771
+ * The last pass that found nothing to evict while aged rows were hidden
1772
+ * from the cache: the stored size it saw, and how many linear appends have
1773
+ * landed since. Until either changes enough, another pass would scan the
1774
+ * same rows to the same answer. A refresh that measures a different size
1775
+ * re-arms it, and so do `keepRecentMessages` appends: that is what it takes
1776
+ * for a row the pass had to protect to age into a candidate. An update
1777
+ * that grows a cached row clears it outright (`_patchCachedMessage`).
1778
+ */
1779
+ private _mediaEvictionFruitless;
1780
+ /**
1781
+ * Whether the cache can stand in for the stored path when deciding if an
1782
+ * eviction pass is worth running. It cannot when the hydration is a window
1783
+ * of the path, or when a compaction overlay collapses rows the pass would
1784
+ * still read and rewrite.
1785
+ */
1786
+ private _agedRowsHiddenFromCache;
1787
+ /**
1788
+ * Schedule a bounded media-eviction pass (see `mediaEviction`).
1789
+ *
1790
+ * Coalesces repeated requests and defers past the current event-loop work,
1791
+ * so it is safe to call from the cache-refresh path that `onStart` runs
1792
+ * inside `blockConcurrencyWhile`: the pass itself never runs in `onStart`,
1793
+ * and `_evictAgedMediaBestEffort` swallows its own failures, so a bad pass
1794
+ * can never brick the object.
1795
+ */
1796
+ private _scheduleMediaEvictionPass;
1797
+ /**
1798
+ * Remove aged media from the conversation, leaving a Workspace pointer the
1799
+ * agent can read back.
1601
1800
  *
1602
- * Memory-bounded by design: row sizes come from `getHistoryRowStats()`
1603
- * (no content loaded), only rows large enough to contain an evictable
1604
- * part are parsed, and they are processed one at a time via
1605
- * `session.internal_rewriteMessage` — the maintenance write path that
1606
- * skips the full-history token-estimate broadcast a public
1607
- * `updateMessage` performs per row. Evicted values are written to the
1608
- * workspace BEFORE the row is rewritten, so a failed pass never loses
1609
- * data. Best-effort: failures are logged and the next pass retries.
1801
+ * Memory-bounded by design: candidate sizes come from `getHistoryRowStats()`
1802
+ * (no content loaded), only rows big enough to hold an evictable payload are
1803
+ * read, and they are processed one at a time. Bytes are written to the
1804
+ * Workspace BEFORE the row is rewritten, so a failed pass never loses data;
1805
+ * once the rewritten row is stored, its Sessions attachment reference is
1806
+ * gone and the blob is reaped, so the bytes live in exactly one place.
1610
1807
  *
1611
1808
  * The aged cutoff is `keepRecentMessages` clamped to at least
1612
- * `MODEL_RECENT_WINDOW`: messages the model still replays at full
1613
- * fidelity each turn are never rewritten, regardless of configuration.
1809
+ * `MODEL_RECENT_WINDOW`: messages the model still replays at full fidelity
1810
+ * are never rewritten, whatever the configuration says.
1614
1811
  *
1615
- * When a pass stops at `maxRowsPerPass` with eligible rows remaining,
1616
- * another pass is scheduled automatically so a large backlog drains
1617
- * without waiting for new appends. Termination is guaranteed: every
1618
- * rewritten row drops below `minPartBytes` and is skipped by later
1619
- * passes, so the eligible set strictly shrinks.
1620
- *
1621
- * Returns the pass totals, or `null` when eviction is disabled, already
1622
- * running, or the provider cannot enumerate row sizes (warned once).
1812
+ * Best-effort: failures are logged and the next pass retries. When a pass
1813
+ * stops at `maxRowsPerPass` having made progress, the next one is scheduled
1814
+ * so a backlog drains on its own; a pass that changed nothing does not
1815
+ * reschedule, which is what guarantees termination.
1623
1816
  */
1624
1817
  protected _evictAgedMediaBestEffort(): Promise<{
1625
1818
  messages: number;
1626
1819
  parts: number;
1627
1820
  bytes: number;
1628
- externalizedBytes: number;
1821
+ backlogRemains: boolean;
1629
1822
  } | null>;
1630
1823
  /** Replace the live cache with a durable storage snapshot. */
1631
1824
  private _replaceCachedMessages;
@@ -1640,6 +1833,26 @@ declare class Think<
1640
1833
  hydratedMessages: number;
1641
1834
  } | null;
1642
1835
  private _warnedHydrationWindowed;
1836
+ /**
1837
+ * `true` while `this.messages` holds every message on the active path.
1838
+ * That is the common case: the default `hydrationByteBudget` admits whole
1839
+ * transcripts, and the Sessions change feed patches the cache after every
1840
+ * durable write. Set by `_syncMessages()`; `false` when the last refresh
1841
+ * was windowed, failed, or has not run yet. Readers that need the complete
1842
+ * path — reconciliation, tool-update lookups — consult it to decide whether
1843
+ * the cache can answer or storage must be read.
1844
+ */
1845
+ private _cacheCoversActivePath;
1846
+ /**
1847
+ * Serialized bytes the cache has grown by since the last refresh — new
1848
+ * messages and updates that enlarged existing ones, measured as UTF-8 the
1849
+ * way the budget is. The hydration budget was measured at that refresh;
1850
+ * once the growth since would carry the cache past it, the cache stops
1851
+ * claiming to cover the path, so the next boundary re-reads storage and
1852
+ * re-windows (#1710).
1853
+ */
1854
+ private _cachedBytesSinceSync;
1855
+ private _noteCachedGrowth;
1643
1856
  /**
1644
1857
  * Snapshot of the last `chat:hydration:windowed` emit, used to emit on
1645
1858
  * CHANGE rather than on every safe-boundary sync — a chronically
@@ -1652,29 +1865,26 @@ declare class Think<
1652
1865
  *
1653
1866
  * Bounded by `hydrationByteBudget`: oversized transcripts hydrate as a
1654
1867
  * recent window instead of exhausting the isolate's memory (#1710). The
1655
- * window never shrinks below `MODEL_RECENT_WINDOW` messages, so budgeted
1656
- * hydration cannot starve the model-facing context assembly (which keeps
1657
- * that many recent messages at full fidelity).
1868
+ * budget is a hard ceiling with no message-count floor beneath it — a floor
1869
+ * that admitted rows regardless of size would defeat the bound it sits
1870
+ * under. A window of unusually large messages can therefore be shorter than
1871
+ * `MODEL_RECENT_WINDOW`; `getHistory()` still reads the full path.
1658
1872
  */
1659
1873
  private _syncMessages;
1660
1874
  /** Patch or append one message in the live cache after a durable write. */
1661
1875
  private _upsertCachedMessage;
1662
- /** Patch a message that is already present in the live cache. */
1876
+ /**
1877
+ * Patch a message that is already present in the live cache. An update
1878
+ * that enlarges the message (a tool result landing on it) grows the cache
1879
+ * exactly as an append does, so it is charged against the hydration
1880
+ * budget the same way; and it may have put an inline payload on an aged
1881
+ * row, so a fruitless eviction pass no longer stands.
1882
+ */
1663
1883
  private _patchCachedMessage;
1664
- /** Sanitize + row-size-compact a message before it touches storage. */
1665
- private _rowSafe;
1666
1884
  private _appendMessageToHistory;
1667
1885
  private _updateMessageInHistory;
1668
1886
  private _upsertMessageInHistory;
1669
- /**
1670
- * The orphan-persist store adapter — orphan-persist steps **(c)/(d)** route
1671
- * their write through this shared `OrphanPersistStore` seam (the
1672
- * `SessionProvider` write-subset). Delegates to `this.session` with `_rowSafe`
1673
- * applied at the write boundary (sanitize + row-size cap), exactly as Think's
1674
- * other Session call sites do. The `SessionMessage → UIMessage` read cast is
1675
- * confined here, matching those call sites.
1676
- * @internal
1677
- */
1887
+ /** Session-backed orphan persistence with Think's default branch. */
1678
1888
  protected _orphanStore(): OrphanPersistStore;
1679
1889
  private _clearHistory;
1680
1890
  /** Append a message while keeping Think's live message cache coherent. */
@@ -1688,6 +1898,12 @@ declare class Think<
1688
1898
  protected syncMessagesFromStorage(): Promise<UIMessage[]>;
1689
1899
  private _aborts;
1690
1900
  private _turnQueue;
1901
+ /**
1902
+ * The Streams capability backing `_resumableStream`: chat's in-flight
1903
+ * output lives in the shared durable chunk log, readable by any
1904
+ * `streams.read()` consumer on this Durable Object.
1905
+ */
1906
+ readonly streams: Streams;
1691
1907
  protected _resumableStream: ResumableStream;
1692
1908
  private _pendingResumeConnections;
1693
1909
  /** Lazily-built shared resume-handshake driver (Tier-2). */
@@ -1880,9 +2096,8 @@ declare class Think<
1880
2096
  resolveModel(model?: ThinkModel): LanguageModel;
1881
2097
  /**
1882
2098
  * Return the fallback system prompt for the assistant.
1883
- * Ignored when Session context blocks are configured. Use
1884
- * `configureSession().withContext()` for always-on instructions that should
1885
- * coexist with context blocks or skills.
2099
+ * Ignored when context blocks are configured. Use `configureContext()` for
2100
+ * always-on instructions that should coexist with context blocks or skills.
1886
2101
  */
1887
2102
  getSystemPrompt(): string;
1888
2103
  /** Return the tools available to the assistant. */
@@ -1992,6 +2207,56 @@ declare class Think<
1992
2207
  * Task-local timezone declarations take precedence.
1993
2208
  */
1994
2209
  getDefaultTimezone(): string | undefined | Promise<string | undefined>;
2210
+ /**
2211
+ * Live chat-turn closures keyed by run nonce. A closure exists only in the
2212
+ * isolate that accepted the turn; recovery after interruption never re-runs
2213
+ * it — the definition's `recover` callback hands the interruption to the
2214
+ * shared ChatRecoveryEngine instead.
2215
+ */
2216
+ private readonly _liveChatTurnClosures;
2217
+ /**
2218
+ * Register the shared chat-turn Task definition (see
2219
+ * `agents/chat` `createChatTurnTaskDefinition` for the turn logic): the
2220
+ * host wires its protected internals through the hooks.
2221
+ */
2222
+ private _registerChatTurnTaskDefinition;
2223
+ /** Register the shared Tasks transport for recovery continuations. */
2224
+ private _registerChatRecoveryTaskDefinition;
2225
+ /**
2226
+ * Run a queue-driven recovery callback to its model handoff and return;
2227
+ * the turn continues as tracked alarm work, and a detached platform
2228
+ * failure enqueues one replacement attempt through the same transport.
2229
+ */
2230
+ private _dispatchChatRecovery;
2231
+ /**
2232
+ * Enqueue one recovery attempt on the shared Tasks transport. Tasks
2233
+ * mirrors a routed dynamic agent's wake to the root's alarm; the run
2234
+ * itself, and this continuation's replay, still execute here. `dedupeKey`
2235
+ * keys a retried enqueue so it joins its own prior attempt instead of
2236
+ * duplicating it — see {@link chatRecoveryTaskRunOptions}.
2237
+ */
2238
+ private _enqueueChatRecovery;
2239
+ /**
2240
+ * The messenger-reply Task definition. A live webhook reply executes as
2241
+ * one journaled step through the runtime's closure registry, persisting
2242
+ * its re-entry snapshot in host storage; a replay whose closure is gone
2243
+ * is recovered on wake by the same
2244
+ * `ThinkMessengerRuntime.handleFiberRecovery` the legacy scan used.
2245
+ */
2246
+ private _registerMessengerReplyTaskDefinition;
2247
+ /**
2248
+ * Host seam for {@link ThinkMessengerRuntime}: durably accept one reply
2249
+ * run on the Tasks capability and execute it inline while this isolate
2250
+ * lives.
2251
+ * @internal
2252
+ */
2253
+ _runMessengerReplyTask(input: {
2254
+ nonce: string;
2255
+ idempotencyKey: string;
2256
+ metadata: Record<string, unknown>;
2257
+ }): Promise<{
2258
+ accepted: boolean;
2259
+ }>;
1995
2260
  private _runChatRecoveryFiber;
1996
2261
  private _systemPromptForTurn;
1997
2262
  private _buildThinkCapabilityBlock;
@@ -2122,19 +2387,42 @@ declare class Think<
2122
2387
  /** One-time guard for the "recovery enabled but no classifier" DX warning. */
2123
2388
  private _warnedMissingClassifier;
2124
2389
  /**
2125
- * Configure the session. Called once during `onStart`.
2126
- * Override to add context blocks, compaction, search, skills.
2390
+ * Configure conversation storage. Called once during `onStart`. Override to
2391
+ * set the compaction policy; prompt context is declared by
2392
+ * {@link Think.configureContext} instead.
2393
+ *
2394
+ * The handle still accepts the pre-Sessions `withContext()` and
2395
+ * `withCachedPrompt()` chain, so an existing override keeps working; those
2396
+ * blocks are appended after the ones `configureContext()` returns.
2127
2397
  *
2128
2398
  * @example
2129
2399
  * ```typescript
2130
2400
  * configureSession(session: Session) {
2131
2401
  * return session
2132
- * .withContext("memory", { description: "Learned facts", maxTokens: 2000 })
2133
- * .withCachedPrompt();
2402
+ * .onCompaction(createCompactFunction({ summarize }))
2403
+ * .compactAfter(80_000);
2404
+ * }
2405
+ * ```
2406
+ */
2407
+ configureSession(session: ThinkSession): ThinkSession | Promise<ThinkSession>;
2408
+ /**
2409
+ * Declare the prompt context blocks for this agent.
2410
+ *
2411
+ * Blocks render into the system prompt and, when their provider is
2412
+ * writable, give the model `set_context` to update them. A block declared
2413
+ * without a provider is auto-wired to durable per-agent SQLite storage.
2414
+ *
2415
+ * @example
2416
+ * ```typescript
2417
+ * configureContext(): ContextConfig[] {
2418
+ * return [
2419
+ * { label: "soul", provider: { get: async () => "You are helpful." } },
2420
+ * { label: "memory", description: "Learned facts", maxTokens: 2000 }
2421
+ * ];
2134
2422
  * }
2135
2423
  * ```
2136
2424
  */
2137
- configureSession(session: Session): Session | Promise<Session>;
2425
+ configureContext(): ContextConfig[] | Promise<ContextConfig[]>;
2138
2426
  /**
2139
2427
  * Return Agent Skills sources for this Think agent.
2140
2428
  *
@@ -2149,6 +2437,7 @@ declare class Think<
2149
2437
  */
2150
2438
  getSkills(): SkillSource[] | Promise<SkillSource[]>;
2151
2439
  private _initializeSkills;
2440
+ private _configureSkillWorkspace;
2152
2441
  /**
2153
2442
  * Log registry diagnostics (duplicate names, sources that failed to list),
2154
2443
  * deduped by message so a new collision after a deploy still surfaces while
@@ -2162,6 +2451,11 @@ declare class Think<
2162
2451
  * before stabilizing.
2163
2452
  */
2164
2453
  getSkillScriptRunner(): SkillScriptRunner | null;
2454
+ /**
2455
+ * The persisted skills fingerprint, read from `think_config` once per
2456
+ * object lifetime; `null` once read and absent. Saves the per-turn probe.
2457
+ */
2458
+ private _skillsFingerprint;
2165
2459
  private _refreshSkillsIfChanged;
2166
2460
  /**
2167
2461
  * Return sandboxed extension configurations. Defines load order,
@@ -2943,7 +3237,18 @@ declare class Think<
2943
3237
  private _hasPendingWorkflowNotifications;
2944
3238
  private _drainWorkflowNotifications;
2945
3239
  private _nextWorkflowNotificationAlarm;
2946
- protected _getExtensionAlarm(): number | null;
3240
+ /**
3241
+ * Drive the Think-owned workflow-notification host job. Unknown fns
3242
+ * delegate to Agent's dispatch.
3243
+ */
3244
+ protected _onHostJob(
3245
+ fn: string,
3246
+ context: LifecycleJobContext
3247
+ ): LifecycleJobOutcome | void | Promise<LifecycleJobOutcome | void>;
3248
+ /**
3249
+ * Sync the workflow-notification wake job with pending-notification state.
3250
+ * Replaces the pull-based `_getExtensionAlarm()` contribution.
3251
+ */
2947
3252
  private _rearmWorkflowNotificationAlarm;
2948
3253
  inspectSubmission(
2949
3254
  submissionId: string
@@ -2971,6 +3276,12 @@ declare class Think<
2971
3276
  private _emitSkippedSubmissions;
2972
3277
  private _recoverSubmissionsOnStart;
2973
3278
  private _getSubmissionMessagesAppliedState;
3279
+ /**
3280
+ * Wall-clock creation time of a non-terminal chat-turn run on the Tasks
3281
+ * capability, or null. The metadata column holds the exact JSON the chat
3282
+ * wrapper wrote, so string equality matches the requestId.
3283
+ */
3284
+ private _recoverableChatTurnTaskCreatedAt;
2974
3285
  private _hasRecoverableChatTurn;
2975
3286
  private _hasFreshRecoverableSubmissionEvidence;
2976
3287
  private _hasScheduledRecoveredContinuation;
@@ -3183,10 +3494,6 @@ declare class Think<
3183
3494
  * step, never an already-completed tool call).
3184
3495
  */
3185
3496
  private _storeChunkDurably;
3186
- /** Per-isolate throttle for crediting recovery progress from mid-segment
3187
- * streaming-content deltas (the shared `agents/chat` rule); reset per isolate
3188
- * so the first delta after a restart always credits. */
3189
- private _streamProgressCredit;
3190
3497
  private _streamResult;
3191
3498
  /**
3192
3499
  * Single source of Think's strip + empty-skip persistence rule. Strips the
@@ -3200,6 +3507,21 @@ declare class Think<
3200
3507
  */
3201
3508
  private _strippedForPersist;
3202
3509
  private _persistAssistantMessage;
3510
+ /**
3511
+ * The cutover: persist the finished turn's assistant message, settle its
3512
+ * resumable stream and delete the stream's rows in ONE SQLite transaction,
3513
+ * so a crash leaves either the live stream (recovery rebuilds the message
3514
+ * from it) or the message — never neither, never both. The session
3515
+ * change feed and auto-compaction run once the transaction has committed.
3516
+ */
3517
+ private _persistAssistantMessageWithCutover;
3518
+ /**
3519
+ * Whether this turn's stream rows can go with its cutover. An agent-tool
3520
+ * child turn keeps them: the parent tails the stored chunks after the
3521
+ * child completes (`getAgentToolChunks`), so the rows are reclaimed by
3522
+ * the child's next `start()` instead, as `AIChatAgent` does.
3523
+ */
3524
+ private _discardStreamAtCutover;
3203
3525
  /**
3204
3526
  * Remove parts belonging to Think's internal structured-output final-answer
3205
3527
  * tool (`think_final_answer`, or a collision-suffixed variant) from a UI
@@ -3210,20 +3532,50 @@ declare class Think<
3210
3532
  * SDK can emit.
3211
3533
  */
3212
3534
  private _stripInternalFinalAnswerParts;
3535
+ /**
3536
+ * Turn-start persistence of the client's transcript: reconcile the posted
3537
+ * messages against the server's active path, write only what changed, and
3538
+ * leave the live cache current. Returns `null` when a newer request
3539
+ * superseded this one part-way through (`isCurrent` turned false).
3540
+ *
3541
+ * Storage traffic here is independent of transcript length: the server
3542
+ * transcript comes from the live cache when it covers the path, unchanged
3543
+ * echoed messages are skipped before Sessions is asked, and the cache is
3544
+ * re-read only when it is windowed.
3545
+ */
3546
+ private _reconcileAndPersistIncoming;
3547
+ /**
3548
+ * The server transcript that reconciliation diffs client messages against.
3549
+ * The live cache answers when it holds the whole active path — the common
3550
+ * case, kept current by the change feed after every durable write. A
3551
+ * windowed or unhydrated cache falls back to the full storage read, since
3552
+ * reconciliation must see every message (`_readMessagesFromStorage`).
3553
+ *
3554
+ * Returns a snapshot: the writes that follow patch the cache through the
3555
+ * change feed while the caller is still iterating.
3556
+ */
3557
+ private _serverTranscriptForReconcile;
3213
3558
  /**
3214
3559
  * Persist an incoming message after reconciliation. For assistant
3215
3560
  * messages, also resolve their ID against any server-side row that
3216
3561
  * already owns the same `toolCallId` so we update the existing row
3217
3562
  * instead of inserting an orphan duplicate.
3563
+ *
3564
+ * A message whose stored form is what the server already holds is skipped
3565
+ * outright. The client posts its whole transcript on every request, so
3566
+ * without this every prior message would cost Sessions an existence read
3567
+ * plus a full-row compare (and, for media, a decode and hash of every
3568
+ * payload) per turn — reads spent discovering nothing changed.
3218
3569
  */
3219
3570
  private _persistIncomingMessage;
3220
3571
  /**
3221
- * Strip {@link RESERVED_MESSAGE_METADATA_KEYS} from a client-supplied message
3222
- * at intake. Those keys are server-written turn context (stamped by
3223
- * `_stampChannel`) that hooks and recovery re-resolve and trust, so a client
3224
- * must never be able to forge them.
3572
+ * The serialized form last written to (or read from) `think_config` for a
3573
+ * request-context key. Every chat request re-sends its client tools and
3574
+ * body; comparing here turns the per-request write into a no-op when
3575
+ * nothing changed. `undefined` means "not persisted" (row absent).
3225
3576
  */
3226
- private _stripReservedMessageMetadata;
3577
+ private _persistedRequestContext;
3578
+ private _persistRequestContextKey;
3227
3579
  private _persistClientTools;
3228
3580
  private _restoreClientTools;
3229
3581
  private _persistBody;
@@ -3360,6 +3712,34 @@ declare class Think<
3360
3712
  */
3361
3713
  private _findExecutionToolCall;
3362
3714
  private _applyToolUpdateToMessages;
3715
+ /**
3716
+ * The persisted message that owns `toolCallId`, read as one row — or
3717
+ * `null` when no persisted row owns it.
3718
+ *
3719
+ * Lookup order, cheapest first:
3720
+ *
3721
+ * 1. `liveMessageId`, when the in-flight accumulator owns the call. A row
3722
+ * under that id exists only when stall recovery persisted a partial
3723
+ * mid-stream. When it does not, the call is not on its own row — but a
3724
+ * provider can replay a prior tool round-trip into a fresh continuation
3725
+ * accumulator (#1404), so the persisted owner may still be an earlier
3726
+ * message; the cache is checked for that before concluding there is
3727
+ * nothing durable to update. Storage is never walked for a call the
3728
+ * live turn owns: every row it could target is on the cached path.
3729
+ * 2. The live cache, for the id only. Whatever names the row, the returned
3730
+ * message is always the STORED form: the apply must compare against
3731
+ * what storage holds, and the cache may be patched ahead of it.
3732
+ * 3. Storage, newest first, stopping at the first owner. Reached only when
3733
+ * the cache does not cover the active path (a windowed hydration, a
3734
+ * boot whose hydration failed, or rows imported behind the cache): a
3735
+ * cross-message result can target a row older than the window, and the
3736
+ * path is read from the leaf so a recent hit costs the rows it passed,
3737
+ * not the transcript.
3738
+ *
3739
+ * This is what keeps a long turn's tool updates independent of transcript
3740
+ * length: the previous shape re-read the whole path per update.
3741
+ */
3742
+ private _resolveToolCallOwner;
3363
3743
  protected hasPendingInteraction(): boolean;
3364
3744
  /**
3365
3745
  * `true` when an auto-continuation is armed but has not yet fired (#1650): a
@@ -3410,18 +3790,19 @@ declare class Think<
3410
3790
  * recomputed from the live, mutable transcript. Compaction collapses older
3411
3791
  * assistant messages into a summary, lowering the count — so a turn that had
3412
3792
  * genuinely advanced could read as "no progress" between attempts and exhaust
3413
- * its budget prematurely (#1628). Instead we read a durably-persisted counter
3414
- * that only ever increments — bumped at production time when new content is
3415
- * durably flushed (see `_storeChunkDurably`), which is genuine forward
3416
- * progress and is immune to client reconnects / recovery re-persists — so
3417
- * compaction can never lower it and a reconnect can't fake it (#1637).
3793
+ * its budget prematurely (#1628). It then became a KV counter bumped per
3794
+ * credited chunk. It is now derived from the stream log the chunks were
3795
+ * already flushed to (`ResumableStream.progressMarker`): the log only grows
3796
+ * when new content lands durably, a reconnect replay or a recovery
3797
+ * re-persist reads it without appending (#1637), and compaction rewrites
3798
+ * the transcript, not the log. Nothing is written per chunk.
3799
+ *
3800
+ * The pre-derivation KV counter is folded in once per isolate, so a marker
3801
+ * an in-flight incident already recorded is never read lower after the
3802
+ * upgrade.
3418
3803
  */
3419
3804
  private _chatRecoveryProgressMarker;
3420
- /** Advance the durable recovery-progress counter. Called from
3421
- * `_storeChunkDurably` when a stored chunk credits forward progress under the
3422
- * shared rule (real, reconnect-immune forward progress). The increment lives
3423
- * in the shared engine (agents/chat); this is the package binding. */
3424
- private _bumpChatRecoveryProgress;
3805
+ private _progressSeed;
3425
3806
  /** Per-isolate N9 throttle gate (shared `agents/chat` helper); reset per
3426
3807
  * isolate so the first forwarded chunk after a restart always credits. */
3427
3808
  private _agentToolStreamProgress;
@@ -3429,7 +3810,9 @@ declare class Think<
3429
3810
  * N9: forwarding a sub-agent's chunks IS forward progress for this parent
3430
3811
  * turn, so credit the parent's recovery progress marker — otherwise a parent
3431
3812
  * whose turn merely `await`s a child banks no progress of its own and its
3432
- * no-progress window exhausts while the child is healthily streaming. Only
3813
+ * no-progress window exhausts while the child is healthily streaming. The
3814
+ * child's output goes to clients, not to this object's stream log, so the
3815
+ * derived marker cannot see it; this is the one explicit credit left. Only
3433
3816
  * invoked after a child actually produced output (see
3434
3817
  * `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.
3435
3818
  * Throttled (and reset per isolate) so we never write storage per token.
@@ -3570,10 +3953,10 @@ declare class Think<
3570
3953
  * `_exhaustChatRecovery` entirely — so an app relying on `onExhausted` for the
3571
3954
  * terminal banner regressed to an eternal spinner when recovery gave up under
3572
3955
  * extreme churn. The error path matters just as much: a non-transient throw
3573
- * in a recovery callback is SWALLOWED by `Agent._executeScheduleCallback`
3574
- * (only a platform transient is re-thrown to preserve the one-shot row), so
3575
- * without routing it here the alarm row is deleted with no terminal UX at
3576
- * all — the half-finished message wedges silently. Shared by
3956
+ * in a recovery callback is SWALLOWED by the driving Task attempt (or the
3957
+ * routed one-shot schedule row) — only a platform transient is re-thrown to
3958
+ * preserve it — so without routing it here the run/row settles with no
3959
+ * terminal UX at all — the half-finished message wedges silently. Shared by
3577
3960
  * `_chatRecoveryRetry` and `_chatRecoveryContinue`.
3578
3961
  *
3579
3962
  * Exactly-once terminalization is defended by two independent guards:
@@ -3591,8 +3974,9 @@ declare class Think<
3591
3974
  * Residual at-least-once edges, all deliberately accepted as "deliver a
3592
3975
  * second banner" ≫ "silently drop the turn":
3593
3976
  * • No `incidentId` at all in the payload (only reachable via a direct/test
3594
- * invocation — every production scheduler carries one): the synthesized
3595
- * incident can't be persisted (no key), so guard #1 can't arm.
3977
+ * invocation — every production recovery enqueue carries one): the
3978
+ * synthesized incident can't be persisted (no key), so guard #1 can't
3979
+ * arm.
3596
3980
  * • The record is swept AGAIN between two alarms (guard #1 re-persists on the
3597
3981
  * first, so this needs a second independent sweep) — vanishingly unlikely.
3598
3982
  * • A platform transient interrupts `_exhaustChatRecovery` after the banner
@@ -3600,18 +3984,26 @@ declare class Think<
3600
3984
  * (the terminal writes themselves are idempotent).
3601
3985
  */
3602
3986
  /**
3603
- * Recovery continuation callbacks the alarm-boundary OOM circuit breaker may
3604
- * back off / purge (#1825). See `Agent._cf_handleAlarmMemoryLimitReset`.
3987
+ * Host memory-limit policy hook (#1825), dispatched structurally by
3988
+ * Lifecycle's circuit breaker — protected because it is framework
3989
+ * machinery, not part of the public Think API. Tasks applies the breaker to
3990
+ * root recovery runs; the routed dynamic-agent fallback applies it to
3991
+ * `recoveryLoop` schedule rows (see `RecoveryLoopScheduleOptions`). At the
3992
+ * strike budget this hook seals active incidents via
3993
+ * {@link _cf_sealMemoryLimitedRecovery}.
3605
3994
  */
3606
- protected _cf_recoveryAlarmCallbacks(): string[];
3995
+ protected onAlarmMemoryLimit(context: {
3996
+ readonly sealed: boolean;
3997
+ }): Promise<void>;
3607
3998
  /**
3608
- * Seal any still-live recovery incident as an out-of-memory exhaustion when
3609
- * the alarm circuit breaker trips at its strike budget (#1825). Runs at the
3610
- * outermost alarm frame (post-unwind), so the terminal banner / `onExhausted`
3611
- * and the sealed-incident write can land where the mid-turn give-up's writes
3612
- * OOMed. Reuses the shared give-up spine via `_exhaustRecoveryGiveUp`.
3999
+ * Seal any still-live recovery incident as an out-of-memory exhaustion
4000
+ * when the alarm circuit breaker trips at its strike budget (#1825). Runs
4001
+ * at the outermost alarm frame (post-unwind), so the terminal banner /
4002
+ * `onExhausted` and the sealed-incident write can land where the mid-turn
4003
+ * give-up's writes OOMed. Reuses the shared give-up spine via
4004
+ * `_exhaustRecoveryGiveUp`.
3613
4005
  */
3614
- protected _cf_sealMemoryLimitedRecovery(): Promise<void>;
4006
+ private _cf_sealMemoryLimitedRecovery;
3615
4007
  private _exhaustRecoveryGiveUp;
3616
4008
  /**
3617
4009
  * Give-up after the stable-state-timeout retry budget drained. Thin wrapper
@@ -3651,9 +4043,9 @@ declare class Think<
3651
4043
  * deploy code-update reset / script supersede, a `retryable`-flagged
3652
4044
  * platform error, or "Network connection lost.", looking through wrappers
3653
4045
  * like `SqlError` via the `cause` chain) is re-thrown (after best-effort
3654
- * marking the incident `failed` for observability) so
3655
- * `Agent._executeScheduleCallback` preserves the one-shot alarm row and
3656
- * the platform re-runs recovery once it is healthy again — the turn can
4046
+ * marking the incident `failed` for observability) so the current
4047
+ * attempt (the driving Task run, or the routed one-shot schedule row) is
4048
+ * preserved and the platform re-runs recovery once it is healthy again — the turn can
3657
4049
  * still recover, so it must NOT terminalize. Terminalizing here was the
3658
4050
  * #1730 freeze: the give-up's own seal needs the very storage that is
3659
4051
  * down, so it throws too, burns the in-process retry budget inside the
@@ -3664,14 +4056,18 @@ declare class Think<
3664
4056
  * `submission_not_running` no-op skip (a self-defeating defer).
3665
4057
  * - Any OTHER (application) error is terminalized through the give-up path
3666
4058
  * (`onExhausted` + the `terminalMessage` banner) and NOT re-thrown. This is
3667
- * the fix for the silent-seal failure mode: `_executeScheduleCallback`
3668
- * swallows a non-transient throw and then `alarm()` deletes the one-shot
3669
- * row, so without terminalizing here the half-finished turn is dropped
3670
- * with no terminal event and no banner (the user stares at a frozen
3671
- * message until they send something new).
4059
+ * the fix for the silent-seal failure mode: the driving attempt swallows
4060
+ * a non-transient throw and settles without terminalizing, so without
4061
+ * terminalizing here the half-finished turn is dropped with no terminal
4062
+ * event and no banner (the user stares at a frozen message until they
4063
+ * send something new).
3672
4064
  */
3673
4065
  private _handleRecoveryCallbackError;
3674
4066
  _chatRecoveryRetry(data?: ChatRecoveryRetryData): Promise<void>;
4067
+ protected _chatRecoveryRetryDetached(
4068
+ data?: ChatRecoveryRetryData,
4069
+ onTurnStarted?: () => void
4070
+ ): Promise<void>;
3675
4071
  private _hasRunningSubmission;
3676
4072
  private _readRunningSubmissionByRequestId;
3677
4073
  private _markRecoveredSubmissionInterrupted;
@@ -3680,6 +4076,10 @@ declare class Think<
3680
4076
  _ctx: ChatRecoveryContext
3681
4077
  ): Promise<ChatRecoveryOptions | void>;
3682
4078
  _chatRecoveryContinue(data?: ChatRecoveryContinueData): Promise<void>;
4079
+ protected _chatRecoveryContinueDetached(
4080
+ data?: ChatRecoveryContinueData,
4081
+ onTurnStarted?: () => void
4082
+ ): Promise<void>;
3683
4083
  private _applyRecoveredRequestContext;
3684
4084
  private _getPartialStreamText;
3685
4085
  private _getSubmitConcurrencyDecision;
@@ -3855,35 +4255,20 @@ declare class Think<
3855
4255
  messageId?: string;
3856
4256
  }
3857
4257
  ): string;
3858
- /**
3859
- * Mark a resumable stream completed and arm buffer cleanup. Wrapper around
3860
- * `ResumableStream.complete` so every stream-finish path also schedules the
3861
- * cleanup alarm (#1706).
3862
- */
4258
+ /** Mark a resumable stream completed (settled now, rows kept until reclaim). */
3863
4259
  protected _completeResumableStream(streamId: string): void;
3864
4260
  /**
3865
- * Mark a resumable stream errored and arm buffer cleanup. Wrapper around
3866
- * `ResumableStream.markError` — see {@link _completeResumableStream}.
4261
+ * The producer finished; leave the row for the cutover that persists the
4262
+ * assistant message (`_persistAssistantMessageWithCutover`). Every path
4263
+ * that calls this must end in that cutover or `finalizePending()`.
3867
4264
  */
4265
+ protected _finishResumableStream(streamId: string): void;
4266
+ /** Mark a resumable stream errored. */
3868
4267
  protected _errorResumableStream(streamId: string): void;
3869
4268
  /**
3870
- * Ensure a single cleanup alarm is pending for this DO's resumable-stream
3871
- * buffers. Armed whenever a stream finishes so that idle/one-off chat DOs
3872
- * still reclaim their buffers — the lazy sweep in {@link ResumableStream}
3873
- * only fires when a *subsequent* stream completes, which never happens for a
3874
- * chat that receives a single turn (#1706).
3875
- *
3876
- * `idempotent` dedupes on (callback, payload, owner) so repeated finishes
3877
- * collapse onto one pending alarm rather than stacking.
3878
- */
3879
- protected _ensureStreamCleanupScheduled({
3880
- idempotent
3881
- }?: {
3882
- idempotent?: boolean;
3883
- }): Promise<void>;
3884
- /**
3885
- * Alarm callback: sweep aged stream buffers, re-arming while rows remain (see
3886
- * the shared {@link cleanupStreamBuffers}).
4269
+ * @deprecated Streams are reclaimed at cutover and on the next stream
4270
+ * start; no alarm is armed any more. Kept so a cleanup alarm persisted by
4271
+ * an earlier version still resolves to a callback when it fires.
3887
4272
  */
3888
4273
  _cleanupStreamBuffers(): Promise<void>;
3889
4274
  private _persistOrphanedStream;
@@ -4246,6 +4631,18 @@ interface MessengerThinkHost extends MessengerThinkTarget {
4246
4631
  options?: StartFiberOptions
4247
4632
  ): Promise<MessengerFiberStartResult>;
4248
4633
  resolveFiber(id: string, result: FiberRecoveryResult): Promise<boolean>;
4634
+ /**
4635
+ * Durably accept one messenger reply run on the host's Tasks capability
4636
+ * and execute it inline while this isolate lives. The same idempotency key
4637
+ * joins the existing run (`accepted: false`).
4638
+ */
4639
+ _runMessengerReplyTask(input: {
4640
+ nonce: string;
4641
+ idempotencyKey: string;
4642
+ metadata: Record<string, unknown>;
4643
+ }): Promise<{
4644
+ accepted: boolean;
4645
+ }>;
4249
4646
  subAgent<T extends Agent>(
4250
4647
  agentClass: SubAgentClass<T>,
4251
4648
  name: string
@@ -4263,6 +4660,12 @@ declare function chatSdkMessenger(
4263
4660
  declare class ThinkMessengerRuntime {
4264
4661
  private readonly host;
4265
4662
  private chat?;
4663
+ /**
4664
+ * Live reply closures keyed by run nonce. A closure exists only in the
4665
+ * isolate that accepted the webhook; an interrupted reply is recovered on
4666
+ * wake through {@link handleFiberRecovery} from its persisted snapshot.
4667
+ */
4668
+ private readonly liveReplies;
4266
4669
  private readonly definitionsByAdapterName;
4267
4670
  private readonly definitionsById;
4268
4671
  private readonly definitions;
@@ -4270,8 +4673,33 @@ declare class ThinkMessengerRuntime {
4270
4673
  get size(): number;
4271
4674
  initialize(): void;
4272
4675
  handleRequest(request: Request): Promise<Response | undefined>;
4273
- handleFiberRecovery(ctx: FiberRecoveryContext): Promise<boolean>;
4676
+ handleFiberRecovery(
4677
+ ctx: FiberRecoveryContext,
4678
+ options?: {
4679
+ /**
4680
+ * Capability-run recovery: persist re-entry checkpoints here instead
4681
+ * of the legacy managed-fiber ledger, whose row does not exist for
4682
+ * runs on the Tasks capability. Terminal settlement is implied by the
4683
+ * caller's recovery decision, so the legacy `resolveFiber` completion
4684
+ * calls are skipped when this hook is present.
4685
+ */
4686
+ persistRecoverySnapshot?: (
4687
+ snapshot: ReturnType<typeof messengerReplySnapshot>
4688
+ ) => Promise<void> | void;
4689
+ }
4690
+ ): Promise<boolean>;
4274
4691
  private createChat;
4692
+ /** Whether this isolate still holds the live closure for one reply. */
4693
+ hasLiveReply(nonce: string): boolean;
4694
+ /**
4695
+ * The durable "accepted" snapshot for one live reply, when its closure is
4696
+ * still held. The task definition persists this BEFORE delivery begins:
4697
+ * an isolate lost mid-answer recovers through it, and without it replay
4698
+ * could neither deliver nor apologize.
4699
+ */
4700
+ initialReplySnapshot(nonce: string): unknown | undefined;
4701
+ /** Execute one live (same-isolate) reply under the given fiber context. */
4702
+ executeLiveReply(nonce: string, fiber: FiberContext): Promise<void>;
4275
4703
  private enqueueReply;
4276
4704
  private answer;
4277
4705
  /**
@@ -4361,8 +4789,10 @@ export {
4361
4789
  ChannelContext as In,
4362
4790
  PendingApproval as It,
4363
4791
  MessengerCapabilities as J,
4792
+ SessionContextOptions as Jn,
4364
4793
  SaveMessagesResult$1 as Jt,
4365
4794
  MessengerAttachment as K,
4795
+ CompactAfterOptions as Kn,
4366
4796
  RunTurnWait as Kt,
4367
4797
  TextStreamCallbackOptions as L,
4368
4798
  ChannelDefinition as Ln,
@@ -4380,7 +4810,7 @@ export {
4380
4810
  skills as Pn,
4381
4811
  MessageConcurrency$1 as Pt,
4382
4812
  MessengerMessage as Q,
4383
- SkillSource$1 as Qt,
4813
+ SkillWorkspaceSeedOptions$1 as Qt,
4384
4814
  defaultDeliveryTag as R,
4385
4815
  ChannelDeliveryPolicy as Rn,
4386
4816
  PrepareStepFunction$1 as Rt,
@@ -4400,11 +4830,12 @@ export {
4400
4830
  messengerChannel as Wn,
4401
4831
  RunTurnStream as Wt,
4402
4832
  MessengerEvent as X,
4403
- SessionMessage$1 as Xt,
4833
+ SkillRunContext as Xt,
4404
4834
  MessengerContext as Y,
4405
- Session$1 as Yt,
4835
+ ThinkSession as Yn,
4836
+ SessionMessage$1 as Yt,
4406
4837
  MessengerEventKind as Z,
4407
- SkillRunContext as Zt,
4838
+ SkillSource$1 as Zt,
4408
4839
  idempotencyKeyForEvent as _,
4409
4840
  ThinkSubmissionStatus as _n,
4410
4841
  ChatOptions as _t,
@@ -4456,6 +4887,7 @@ export {
4456
4887
  ThinkScheduledTaskContext as pn,
4457
4888
  ActionPermissionSpec as pt,
4458
4889
  MessengerAuthor as q,
4890
+ CompactionErrorHandler as qn,
4459
4891
  SaveMessagesOptions$1 as qt,
4460
4892
  MessengerConversationMode as r,
4461
4893
  StreamCallback as rn,
@@ -4485,4 +4917,4 @@ export {
4485
4917
  ChannelDeliverySurface as zn,
4486
4918
  PrepareStepResult$1 as zt
4487
4919
  };
4488
- //# sourceMappingURL=index-B7zEkBBM.d.ts.map
4920
+ //# sourceMappingURL=index-CJ--4uax.d.ts.map