@cloudflare/think 0.17.0 → 0.19.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,174 @@ import {
94
113
  } from "chat";
95
114
  import { ChatSdkStateAdapterOptions, ChatSdkStateAgent } from "agents/chat-sdk";
96
115
  import { RpcTarget } from "cloudflare:workers";
116
+ import { Streams } from "agents/streams";
97
117
 
118
+ //#region src/session.d.ts
119
+ /** Options for a block declared through `withContext()` / `addContext()`. */
120
+ type SessionContextOptions = Omit<ContextConfig, "label">;
121
+ /** Receives an error thrown by the registered compaction function. */
122
+ type CompactionErrorHandler = (error: unknown) => void | Promise<void>;
123
+ /**
124
+ * @deprecated `compactAfter()` gates on the token estimate Sessions stamps on
125
+ * each row; a custom counter is no longer consulted. Accepted so existing
126
+ * calls compile.
127
+ */
128
+ interface CompactAfterOptions {
129
+ tokenCounter?: unknown;
130
+ }
131
+ declare class ThinkSession {
132
+ #private;
133
+ /** @internal Constructed by Think during `onStart`. */
134
+ constructor(handle: Session, context: () => ContextBlocks);
135
+ get sessionId(): string;
136
+ /** @internal Blocks declared through `withContext()` during configuration. */
137
+ internal_takePendingContext(): ContextConfig[];
138
+ /** @internal A custom frozen-prompt store passed to `withCachedPrompt()`. */
139
+ internal_promptStore(): WritableContextProvider | undefined;
140
+ /**
141
+ * Declare a prompt context block.
142
+ *
143
+ * @deprecated Return the block from `configureContext()` instead. Only
144
+ * callable inside `configureSession()`; after startup use
145
+ * `this.context.addBlock()`.
146
+ */
147
+ withContext(label: string, options?: SessionContextOptions): this;
148
+ /**
149
+ * Persist the frozen system prompt.
150
+ *
151
+ * @deprecated The frozen prompt is always persisted now, so this is a
152
+ * no-op. A custom `provider` is still honoured as the prompt store.
153
+ */
154
+ withCachedPrompt(provider?: WritableContextProvider): this;
155
+ /** Register the function `compact()` calls to summarize a branch. */
156
+ onCompaction(fn: CompactionFunction): this;
157
+ /**
158
+ * Auto-compact after an append once the stamped token estimate crosses the
159
+ * threshold. Requires `onCompaction()`.
160
+ */
161
+ compactAfter(tokenThreshold: number, _options?: CompactAfterOptions): this;
162
+ /**
163
+ * Observe compaction failures. When set, a failing compaction function
164
+ * calls the handler and the compaction is skipped; without one the failure
165
+ * is reported through the `session:error` capability event.
166
+ */
167
+ onCompactionError(handler: CompactionErrorHandler): this;
168
+ history(
169
+ options?: HistoryReadOptions
170
+ ): AsyncGenerator<SessionMessage, void, undefined>;
171
+ historyBatches(
172
+ options?: HistoryBatchReadOptions
173
+ ): AsyncGenerator<SessionMessage[], void, undefined>;
174
+ /**
175
+ * Materialize the whole selected path. Accepts a leaf id positionally, as
176
+ * the pre-Sessions API did, or a read-options object.
177
+ */
178
+ getHistory(
179
+ leafIdOrOptions?: string | null | HistoryReadOptions
180
+ ): Promise<SessionMessage[]>;
181
+ /**
182
+ * Byte-budgeted read of the most recent messages on the active path. The
183
+ * pre-Sessions `minRecentMessages` argument is accepted and ignored: the
184
+ * budget is a hard ceiling, and the newest message is always returned.
185
+ */
186
+ getRecentHistory(
187
+ maxContentBytes: number,
188
+ optionsOrMinRecentMessages?: number | Pick<HistoryReadOptions, "leafId">
189
+ ): Promise<RecentHistoryResult>;
190
+ getHistoryRowStats(leafId?: string | null): Promise<SessionRowStat[]>;
191
+ /** @deprecated Read `getHistoryRowStats()` and take its length. */
192
+ getPathLength(leafId?: string | null): Promise<number>;
193
+ getMessage(id: string): Promise<SessionMessage | null>;
194
+ getLatestLeaf(): Promise<SessionMessage | null>;
195
+ getBranches(messageId: string): Promise<SessionMessage[]>;
196
+ search(
197
+ query: string,
198
+ options?: {
199
+ limit?: number;
200
+ }
201
+ ): Promise<SearchResult[]>;
202
+ /**
203
+ * Append one message. Accepts the parent id positionally, as the
204
+ * pre-Sessions API did, or an options object.
205
+ */
206
+ appendMessage(
207
+ message: SessionMessage,
208
+ parentIdOrOptions?: string | null | AppendOptions
209
+ ): Promise<AppendResult>;
210
+ updateMessage(
211
+ message: SessionMessage,
212
+ options?: WriteOptions
213
+ ): Promise<SessionMessage | null>;
214
+ upsertMessage(
215
+ message: SessionMessage,
216
+ parentIdOrOptions?: string | null | AppendOptions
217
+ ): Promise<AppendResult>;
218
+ importMessage(
219
+ message: SessionMessage,
220
+ options: {
221
+ parentId: string | null;
222
+ createdAt: number;
223
+ }
224
+ ): Promise<void>;
225
+ deleteMessages(messageIds: string[]): Promise<void>;
226
+ clearMessages(): Promise<void>;
227
+ addCompaction(
228
+ summary: string,
229
+ fromMessageId: string,
230
+ toMessageId: string
231
+ ): Promise<StoredCompaction>;
232
+ getCompactions(): Promise<StoredCompaction[]>;
233
+ compact(leafId?: string | null): Promise<CompactResult | null>;
234
+ /** @deprecated Use `this.context.addBlock({ label, ...options })`. */
235
+ addContext(
236
+ label: string,
237
+ options?: SessionContextOptions
238
+ ): Promise<ContextBlock>;
239
+ /** @deprecated Use `this.context.removeBlock(label)`. */
240
+ removeContext(label: string): boolean;
241
+ /** @deprecated Use `this.context.getBlock(label)`. */
242
+ getContextBlock(label: string): ContextBlock | null;
243
+ /** @deprecated Use `this.context.getBlocks()`. */
244
+ getContextBlocks(): ContextBlock[];
245
+ /** @deprecated Use `this.context.setBlock(label, content)`. */
246
+ replaceContextBlock(label: string, content: string): Promise<ContextBlock>;
247
+ /** @deprecated Use `this.context.appendToBlock(label, content)`. */
248
+ appendContextBlock(label: string, content: string): Promise<ContextBlock>;
249
+ /** @deprecated Use `this.context.freezeSystemPrompt()`. */
250
+ freezeSystemPrompt(): Promise<string>;
251
+ /** @deprecated Use `this.context.refreshSystemPrompt()`. */
252
+ refreshSystemPrompt(): Promise<string>;
253
+ /** @deprecated Use `this.context.tools()`. */
254
+ tools(): Promise<ToolSet>;
255
+ }
256
+ //#endregion
98
257
  //#region src/media-eviction.d.ts
99
258
  interface MediaEvictionConfig {
100
259
  /**
101
260
  * 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.
261
+ * Think clamps this to at least the read-time window the model replays at
262
+ * full fidelity, so a misconfigured low value can never strip content the
263
+ * model still sees.
106
264
  * @default 8
107
265
  */
108
266
  keepRecentMessages?: number;
109
267
  /**
110
- * Minimum serialized size (in characters; base64 is ASCII so this equals
111
- * bytes for media) of a single part value to evict.
268
+ * Minimum decoded payload size, in bytes, for a value to be evicted.
112
269
  * @default 32 * 1024
113
270
  */
114
271
  minPartBytes?: number;
115
272
  /**
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.
273
+ * Maximum stored rows processed per pass. Bounds how long a single pass
274
+ * can take; remaining rows are picked up by the next pass.
125
275
  * @default 64
126
276
  */
127
277
  maxRowsPerPass?: number;
278
+ /**
279
+ * @deprecated Ignored. Evicted bytes are always preserved in the Workspace
280
+ * under `/attachments/evicted/`; there is no drop-the-bytes mode. Accepted
281
+ * so existing configurations keep compiling.
282
+ */
283
+ externalizeToWorkspace?: boolean;
128
284
  }
129
285
  //#endregion
130
286
  //#region src/channels/index.d.ts
@@ -713,6 +869,17 @@ type DeleteSubmissionsOptions = {
713
869
  completedBefore?: Date;
714
870
  limit?: number;
715
871
  };
872
+ /** Payload of one queued workflow notification. */
873
+ type WorkflowNotificationPayload = {
874
+ workflowName: string;
875
+ workflowId: string;
876
+ event: {
877
+ type: string;
878
+ payload: unknown;
879
+ } /** Failed deliveries so far; drives the retry backoff. */;
880
+ attempts?: number /** Epoch ms of the first failed delivery; bounds the retry window. */;
881
+ firstFailedAt?: number;
882
+ };
716
883
  /**
717
884
  * A chat turn request. Built automatically by each entry path
718
885
  * (WebSocket, chat(), saveMessages, auto-continuation) and passed
@@ -1295,6 +1462,15 @@ declare class Think<
1295
1462
  storeMessages: boolean;
1296
1463
  /** Store tool input/output on `execute_tool` spans. */
1297
1464
  storeTools: boolean;
1465
+ /**
1466
+ * Project `getSkills()` into the active workspace so the agent can read
1467
+ * and edit skills as files. Computer workspaces use
1468
+ * `/workspace/.agents/skills`; legacy Shell uses `/.agents/skills`.
1469
+ * Existing edits are preserved. Off by default: skills load from their
1470
+ * sources and nothing is written to the Workspace, as before. Set `{}` to
1471
+ * project with the defaults.
1472
+ */
1473
+ skillWorkspace: false | SkillWorkspaceSeedOptions;
1298
1474
  private _skillRegistry;
1299
1475
  private _loggedSkillWarnings;
1300
1476
  private _loggedProtocolWarnings;
@@ -1326,41 +1502,39 @@ declare class Think<
1326
1502
  * truncated at read time before each turn, and the hydration floor
1327
1503
  * guarantees the full-fidelity span is always present.
1328
1504
  *
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.
1505
+ * The budget counts what hydration actually costs: a row's stored bytes
1506
+ * plus the attachment bytes its pointers inflate back when reconstructed
1507
+ * inline. A pointer row is therefore charged its payload, not its ~100
1508
+ * stored bytes, so the ceiling bounds isolate memory rather than the
1509
+ * on-disk footprint. Set to `Number.POSITIVE_INFINITY` (or any
1510
+ * non-positive value) to disable windowing and always hydrate the full
1511
+ * transcript.
1333
1512
  *
1334
- * @default 24 * 1024 * 1024
1513
+ * @default 32 * 1024 * 1024
1335
1514
  */
1336
1515
  hydrationByteBudget: number;
1337
1516
  /**
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.
1517
+ * Aged-media eviction — a CONTEXT-WINDOW technique, not a storage setting.
1518
+ *
1519
+ * Once media has aged past `keepRecentMessages` on the active path, Think
1520
+ * removes it from the conversation so the model stops re-reading a large
1521
+ * image on every turn, and leaves a marker naming a Workspace file under
1522
+ * `/attachments/evicted/`. The bytes are written raw with their real mime
1523
+ * type, so the agent can read the picture back with the workspace `read`
1524
+ * tool when it deliberately needs it again. Visible to the model and lossy
1525
+ * on purpose.
1341
1526
  *
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.
1527
+ * This is separate from Sessions attachment storage, which is invisible
1528
+ * and lossless: a large payload may be held as an `attachment:sha256:`
1529
+ * pointer whether eviction is on or off.
1348
1530
  *
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.
1531
+ * `false` keeps aged media in the conversation, so the model keeps seeing
1532
+ * it. It does NOT change where Sessions keeps the bytes.
1355
1533
  *
1356
1534
  * `keepRecentMessages` is clamped to at least the recent window the model
1357
1535
  * replays at full fidelity (4 messages), so eviction can never rewrite
1358
1536
  * content the model still sees.
1359
1537
  *
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
1538
  * @default true
1365
1539
  */
1366
1540
  mediaEviction: MediaEvictionConfig | boolean;
@@ -1377,16 +1551,21 @@ declare class Think<
1377
1551
  */
1378
1552
  chatRecovery: ChatRecoveryConfig;
1379
1553
  static readonly CHAT_FIBER_NAME = "__cf_internal_chat_turn";
1554
+ /** Durable conversation history installed on this Agent's Lifecycle. */
1555
+ readonly sessions: Sessions;
1380
1556
  /**
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.
1557
+ * The default conversation handle configured by `configureSession()`.
1558
+ * Storage lives on the `agents/sessions` handle it wraps; the context
1559
+ * methods it still carries forward to {@link Think.context}.
1560
+ */
1561
+ session: ThinkSession;
1562
+ /**
1563
+ * The agent's context blocks. Available once the Lifecycle has started.
1386
1564
  */
1387
- session: Session;
1388
- /** Cached messages — kept in sync with session storage. */
1565
+ protected get context(): ContextBlocks;
1566
+ /** Cached messages, kept in sync with session storage. */
1389
1567
  private _cachedMessages;
1568
+ private _unsubscribeSessionChanges;
1390
1569
  /**
1391
1570
  * Internal onStart steps that failed on this wake and were skipped so the
1392
1571
  * agent could still come up.
@@ -1504,11 +1683,12 @@ declare class Think<
1504
1683
  *
1505
1684
  * Intentionally UNBUDGETED — unlike the cache refresh in `_syncMessages`,
1506
1685
  * 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.
1686
+ * returns the full active path. Its caller, message reconciliation, must see
1687
+ * every message: it diffs incoming client messages against the complete
1688
+ * server transcript, so a windowed read would drop rows and corrupt the
1689
+ * result. It is reached only when the live cache does not already cover the
1690
+ * path (`_serverTranscriptForReconcile`); tool-update application resolves
1691
+ * its one target row without it (`_resolveToolCallOwner`).
1512
1692
  *
1513
1693
  * These full reads are not the unbounded boot-time hydration that bricked the
1514
1694
  * DO in #1710: they run during a live turn (never in `onStart`), so an
@@ -1583,49 +1763,78 @@ declare class Think<
1583
1763
  */
1584
1764
  private _runBestEffortOnStartStep;
1585
1765
  private _mediaEvictionRunning;
1586
- private _mediaEvictionScheduled;
1587
- private _mediaEvictionObservedOversized;
1588
1766
  /**
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.
1767
+ * A request that arrived while a pass was running. That pass read its
1768
+ * candidates before the request's append landed, so the request is kept
1769
+ * and re-evaluated once the pass ends rather than dropped.
1593
1770
  */
1594
- private _scheduleMediaEvictionPass;
1595
- private _scheduleMediaEvictionAfterAppend;
1596
- private _refreshMediaEvictionSignalFromCache;
1597
- private _messageMayNeedMediaEviction;
1771
+ private _mediaEvictionPending;
1772
+ /**
1773
+ * Linear appends that landed while a pass was running. The pass read its
1774
+ * candidates before them, so a fruitless result records them as appends
1775
+ * since — not zero — and the request they left pending can pass the gate.
1776
+ */
1777
+ private _mediaEvictionAppendsDuringPass;
1598
1778
  private _warnedEvictionUnsupported;
1599
1779
  /**
1600
- * Evict oversized inline media from aged stored messages (#1710).
1780
+ * The last pass that found nothing to evict while aged rows were hidden
1781
+ * from the cache: the stored size it saw, and how many linear appends have
1782
+ * landed since. Until either changes enough, another pass would scan the
1783
+ * same rows to the same answer. A refresh that measures a different size
1784
+ * re-arms it, and so do `keepRecentMessages` appends: that is what it takes
1785
+ * for a row the pass had to protect to age into a candidate. An update
1786
+ * that grows a cached row clears it outright (`_patchCachedMessage`).
1787
+ */
1788
+ private _mediaEvictionFruitless;
1789
+ /**
1790
+ * Whether the cache can stand in for the stored path when deciding if an
1791
+ * eviction pass is worth running. It cannot when the hydration is a window
1792
+ * of the path, or when a compaction overlay collapses rows the pass would
1793
+ * still read and rewrite.
1794
+ */
1795
+ private _agedRowsHiddenFromCache;
1796
+ /**
1797
+ * Queue a bounded media-eviction pass (see `mediaEviction`).
1798
+ *
1799
+ * The pass is one queue item with a stable id, so repeated requests
1800
+ * coalesce and the pass runs from the alarm loop, never inside the
1801
+ * request or the `blockConcurrencyWhile` cache refresh that asked for it.
1802
+ * A request that lands while a pass is running is re-evaluated once the
1803
+ * pass ends, so media aged by an append during the pass is not left until
1804
+ * the next one. `_evictAgedMediaBestEffort` swallows its own failures, so
1805
+ * a bad pass can never brick the object.
1806
+ */
1807
+ private _scheduleMediaEvictionPass;
1808
+ /**
1809
+ * Run one media-eviction pass.
1810
+ * @internal Queue callback.
1811
+ */
1812
+ _cfEvictAgedMedia(): Promise<void>;
1813
+ /**
1814
+ * Remove aged media from the conversation, leaving a Workspace pointer the
1815
+ * agent can read back.
1601
1816
  *
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.
1817
+ * Memory-bounded by design: candidate sizes come from `getHistoryRowStats()`
1818
+ * (no content loaded), only rows big enough to hold an evictable payload are
1819
+ * read, and they are processed one at a time. Bytes are written to the
1820
+ * Workspace BEFORE the row is rewritten, so a failed pass never loses data;
1821
+ * once the rewritten row is stored, its Sessions attachment reference is
1822
+ * gone and the blob is reaped, so the bytes live in exactly one place.
1610
1823
  *
1611
1824
  * 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.
1614
- *
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.
1825
+ * `MODEL_RECENT_WINDOW`: messages the model still replays at full fidelity
1826
+ * are never rewritten, whatever the configuration says.
1620
1827
  *
1621
- * Returns the pass totals, or `null` when eviction is disabled, already
1622
- * running, or the provider cannot enumerate row sizes (warned once).
1828
+ * Best-effort: failures are logged and the next pass retries. When a pass
1829
+ * stops at `maxRowsPerPass` having made progress, the next one is scheduled
1830
+ * so a backlog drains on its own; a pass that changed nothing does not
1831
+ * reschedule, which is what guarantees termination.
1623
1832
  */
1624
1833
  protected _evictAgedMediaBestEffort(): Promise<{
1625
1834
  messages: number;
1626
1835
  parts: number;
1627
1836
  bytes: number;
1628
- externalizedBytes: number;
1837
+ backlogRemains: boolean;
1629
1838
  } | null>;
1630
1839
  /** Replace the live cache with a durable storage snapshot. */
1631
1840
  private _replaceCachedMessages;
@@ -1640,6 +1849,26 @@ declare class Think<
1640
1849
  hydratedMessages: number;
1641
1850
  } | null;
1642
1851
  private _warnedHydrationWindowed;
1852
+ /**
1853
+ * `true` while `this.messages` holds every message on the active path.
1854
+ * That is the common case: the default `hydrationByteBudget` admits whole
1855
+ * transcripts, and the Sessions change feed patches the cache after every
1856
+ * durable write. Set by `_syncMessages()`; `false` when the last refresh
1857
+ * was windowed, failed, or has not run yet. Readers that need the complete
1858
+ * path — reconciliation, tool-update lookups — consult it to decide whether
1859
+ * the cache can answer or storage must be read.
1860
+ */
1861
+ private _cacheCoversActivePath;
1862
+ /**
1863
+ * Serialized bytes the cache has grown by since the last refresh — new
1864
+ * messages and updates that enlarged existing ones, measured as UTF-8 the
1865
+ * way the budget is. The hydration budget was measured at that refresh;
1866
+ * once the growth since would carry the cache past it, the cache stops
1867
+ * claiming to cover the path, so the next boundary re-reads storage and
1868
+ * re-windows (#1710).
1869
+ */
1870
+ private _cachedBytesSinceSync;
1871
+ private _noteCachedGrowth;
1643
1872
  /**
1644
1873
  * Snapshot of the last `chat:hydration:windowed` emit, used to emit on
1645
1874
  * CHANGE rather than on every safe-boundary sync — a chronically
@@ -1652,29 +1881,26 @@ declare class Think<
1652
1881
  *
1653
1882
  * Bounded by `hydrationByteBudget`: oversized transcripts hydrate as a
1654
1883
  * 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).
1884
+ * budget is a hard ceiling with no message-count floor beneath it — a floor
1885
+ * that admitted rows regardless of size would defeat the bound it sits
1886
+ * under. A window of unusually large messages can therefore be shorter than
1887
+ * `MODEL_RECENT_WINDOW`; `getHistory()` still reads the full path.
1658
1888
  */
1659
1889
  private _syncMessages;
1660
1890
  /** Patch or append one message in the live cache after a durable write. */
1661
1891
  private _upsertCachedMessage;
1662
- /** Patch a message that is already present in the live cache. */
1892
+ /**
1893
+ * Patch a message that is already present in the live cache. An update
1894
+ * that enlarges the message (a tool result landing on it) grows the cache
1895
+ * exactly as an append does, so it is charged against the hydration
1896
+ * budget the same way; and it may have put an inline payload on an aged
1897
+ * row, so a fruitless eviction pass no longer stands.
1898
+ */
1663
1899
  private _patchCachedMessage;
1664
- /** Sanitize + row-size-compact a message before it touches storage. */
1665
- private _rowSafe;
1666
1900
  private _appendMessageToHistory;
1667
1901
  private _updateMessageInHistory;
1668
1902
  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
- */
1903
+ /** Session-backed orphan persistence with Think's default branch. */
1678
1904
  protected _orphanStore(): OrphanPersistStore;
1679
1905
  private _clearHistory;
1680
1906
  /** Append a message while keeping Think's live message cache coherent. */
@@ -1688,6 +1914,12 @@ declare class Think<
1688
1914
  protected syncMessagesFromStorage(): Promise<UIMessage[]>;
1689
1915
  private _aborts;
1690
1916
  private _turnQueue;
1917
+ /**
1918
+ * The Streams capability backing `_resumableStream`: chat's in-flight
1919
+ * output lives in the shared durable chunk log, readable by any
1920
+ * `streams.read()` consumer on this Durable Object.
1921
+ */
1922
+ readonly streams: Streams;
1691
1923
  protected _resumableStream: ResumableStream;
1692
1924
  private _pendingResumeConnections;
1693
1925
  /** Lazily-built shared resume-handshake driver (Tier-2). */
@@ -1731,12 +1963,9 @@ declare class Think<
1731
1963
  */
1732
1964
  private _agentToolRunsByRequestId;
1733
1965
  private _submissionTableEnsured;
1734
- private _workflowNotificationTableEnsured;
1735
1966
  private _declaredScheduledTasksTableEnsured;
1736
1967
  private _actionLedgerTableEnsured;
1737
1968
  private _actionPendingTableEnsured;
1738
- private _drainingSubmissions;
1739
- private _drainingWorkflowNotifications;
1740
1969
  private _submissionAbortControllers;
1741
1970
  private _programmaticStreamErrors;
1742
1971
  protected static submissionRecoveryStaleMs: number;
@@ -1783,7 +2012,6 @@ declare class Think<
1783
2012
  * invariant note there).
1784
2013
  */
1785
2014
  private _rebindAgentToolChildRunRequestId;
1786
- alarm(): Promise<void>;
1787
2015
  /**
1788
2016
  * Persist an arbitrary JSON-serializable configuration object for this
1789
2017
  * agent instance. Stored in the Think-private `think_config` table —
@@ -1880,9 +2108,8 @@ declare class Think<
1880
2108
  resolveModel(model?: ThinkModel): LanguageModel;
1881
2109
  /**
1882
2110
  * 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.
2111
+ * Ignored when context blocks are configured. Use `configureContext()` for
2112
+ * always-on instructions that should coexist with context blocks or skills.
1886
2113
  */
1887
2114
  getSystemPrompt(): string;
1888
2115
  /** Return the tools available to the assistant. */
@@ -1992,6 +2219,56 @@ declare class Think<
1992
2219
  * Task-local timezone declarations take precedence.
1993
2220
  */
1994
2221
  getDefaultTimezone(): string | undefined | Promise<string | undefined>;
2222
+ /**
2223
+ * Live chat-turn closures keyed by run nonce. A closure exists only in the
2224
+ * isolate that accepted the turn; recovery after interruption never re-runs
2225
+ * it — the definition's `recover` callback hands the interruption to the
2226
+ * shared ChatRecoveryEngine instead.
2227
+ */
2228
+ private readonly _liveChatTurnClosures;
2229
+ /**
2230
+ * Register the shared chat-turn Task definition (see
2231
+ * `agents/chat` `createChatTurnTaskDefinition` for the turn logic): the
2232
+ * host wires its protected internals through the hooks.
2233
+ */
2234
+ private _registerChatTurnTaskDefinition;
2235
+ /** Register the shared Tasks transport for recovery continuations. */
2236
+ private _registerChatRecoveryTaskDefinition;
2237
+ /**
2238
+ * Run a queue-driven recovery callback to its model handoff and return;
2239
+ * the turn continues as tracked alarm work, and a detached platform
2240
+ * failure enqueues one replacement attempt through the same transport.
2241
+ */
2242
+ private _dispatchChatRecovery;
2243
+ /**
2244
+ * Enqueue one recovery attempt on the shared Tasks transport. Tasks
2245
+ * mirrors a routed dynamic agent's wake to the root's alarm; the run
2246
+ * itself, and this continuation's replay, still execute here. `dedupeKey`
2247
+ * keys a retried enqueue so it joins its own prior attempt instead of
2248
+ * duplicating it — see {@link chatRecoveryTaskRunOptions}.
2249
+ */
2250
+ private _enqueueChatRecovery;
2251
+ /**
2252
+ * The messenger-reply Task definition. A live webhook reply executes as
2253
+ * one journaled step through the runtime's closure registry, persisting
2254
+ * its re-entry snapshot in host storage; a replay whose closure is gone
2255
+ * is recovered on wake by the same
2256
+ * `ThinkMessengerRuntime.handleFiberRecovery` the legacy scan used.
2257
+ */
2258
+ private _registerMessengerReplyTaskDefinition;
2259
+ /**
2260
+ * Host seam for {@link ThinkMessengerRuntime}: durably accept one reply
2261
+ * run on the Tasks capability and execute it inline while this isolate
2262
+ * lives.
2263
+ * @internal
2264
+ */
2265
+ _runMessengerReplyTask(input: {
2266
+ nonce: string;
2267
+ idempotencyKey: string;
2268
+ metadata: Record<string, unknown>;
2269
+ }): Promise<{
2270
+ accepted: boolean;
2271
+ }>;
1995
2272
  private _runChatRecoveryFiber;
1996
2273
  private _systemPromptForTurn;
1997
2274
  private _buildThinkCapabilityBlock;
@@ -2122,19 +2399,42 @@ declare class Think<
2122
2399
  /** One-time guard for the "recovery enabled but no classifier" DX warning. */
2123
2400
  private _warnedMissingClassifier;
2124
2401
  /**
2125
- * Configure the session. Called once during `onStart`.
2126
- * Override to add context blocks, compaction, search, skills.
2402
+ * Configure conversation storage. Called once during `onStart`. Override to
2403
+ * set the compaction policy; prompt context is declared by
2404
+ * {@link Think.configureContext} instead.
2405
+ *
2406
+ * The handle still accepts the pre-Sessions `withContext()` and
2407
+ * `withCachedPrompt()` chain, so an existing override keeps working; those
2408
+ * blocks are appended after the ones `configureContext()` returns.
2127
2409
  *
2128
2410
  * @example
2129
2411
  * ```typescript
2130
2412
  * configureSession(session: Session) {
2131
2413
  * return session
2132
- * .withContext("memory", { description: "Learned facts", maxTokens: 2000 })
2133
- * .withCachedPrompt();
2414
+ * .onCompaction(createCompactFunction({ summarize }))
2415
+ * .compactAfter(80_000);
2416
+ * }
2417
+ * ```
2418
+ */
2419
+ configureSession(session: ThinkSession): ThinkSession | Promise<ThinkSession>;
2420
+ /**
2421
+ * Declare the prompt context blocks for this agent.
2422
+ *
2423
+ * Blocks render into the system prompt and, when their provider is
2424
+ * writable, give the model `set_context` to update them. A block declared
2425
+ * without a provider is auto-wired to durable per-agent SQLite storage.
2426
+ *
2427
+ * @example
2428
+ * ```typescript
2429
+ * configureContext(): ContextConfig[] {
2430
+ * return [
2431
+ * { label: "soul", provider: { get: async () => "You are helpful." } },
2432
+ * { label: "memory", description: "Learned facts", maxTokens: 2000 }
2433
+ * ];
2134
2434
  * }
2135
2435
  * ```
2136
2436
  */
2137
- configureSession(session: Session): Session | Promise<Session>;
2437
+ configureContext(): ContextConfig[] | Promise<ContextConfig[]>;
2138
2438
  /**
2139
2439
  * Return Agent Skills sources for this Think agent.
2140
2440
  *
@@ -2149,6 +2449,7 @@ declare class Think<
2149
2449
  */
2150
2450
  getSkills(): SkillSource[] | Promise<SkillSource[]>;
2151
2451
  private _initializeSkills;
2452
+ private _configureSkillWorkspace;
2152
2453
  /**
2153
2454
  * Log registry diagnostics (duplicate names, sources that failed to list),
2154
2455
  * deduped by message so a new collision after a deploy still surfaces while
@@ -2162,6 +2463,11 @@ declare class Think<
2162
2463
  * before stabilizing.
2163
2464
  */
2164
2465
  getSkillScriptRunner(): SkillScriptRunner | null;
2466
+ /**
2467
+ * The persisted skills fingerprint, read from `think_config` once per
2468
+ * object lifetime; `null` once read and absent. Saves the per-turn probe.
2469
+ */
2470
+ private _skillsFingerprint;
2165
2471
  private _refreshSkillsIfChanged;
2166
2472
  /**
2167
2473
  * Return sandboxed extension configurations. Defines load order,
@@ -2920,7 +3226,6 @@ declare class Think<
2920
3226
  payload: DeclaredScheduledTaskPayload
2921
3227
  ): Promise<void>;
2922
3228
  private _ensureSubmissionTable;
2923
- private _ensureWorkflowNotificationTable;
2924
3229
  private _readSubmission;
2925
3230
  private _readSubmissionByIdempotencyKey;
2926
3231
  private _normalizeStatusFilter;
@@ -2936,15 +3241,41 @@ declare class Think<
2936
3241
  protected onSubmissionStatus(
2937
3242
  _submission: ThinkSubmissionInspection
2938
3243
  ): void | Promise<void>;
2939
- private _enqueueWorkflowNotification;
3244
+ /**
3245
+ * Queue the workflow event for a submission that just went terminal.
3246
+ *
3247
+ * The item is written synchronously (the Lifecycle has started whenever a
3248
+ * submission transitions), so call this in the same synchronous block as
3249
+ * the terminal status write: the two commit together and no recovery scan
3250
+ * is needed. A repeated push for the same submission and event type
3251
+ * replaces the pending item rather than duplicating it.
3252
+ */
2940
3253
  private _insertWorkflowNotification;
2941
- private _recoverWorkflowNotifications;
2942
- private _startWorkflowNotificationDrain;
2943
- private _hasPendingWorkflowNotifications;
2944
- private _drainWorkflowNotifications;
2945
- private _nextWorkflowNotificationAlarm;
2946
- protected _getExtensionAlarm(): number | null;
2947
- private _rearmWorkflowNotificationAlarm;
3254
+ /** Queue the workflow event for a row that a caller just made terminal. */
3255
+ private _enqueueTerminalWorkflowNotification;
3256
+ /**
3257
+ * Deliver one workflow notification. Runs from the queue on first
3258
+ * delivery; a failed delivery schedules this same callback again with
3259
+ * exponential backoff (2s doubling, capped at ten minutes) so a
3260
+ * temporarily unreachable workflow still gets its terminal event. Once
3261
+ * the first failure is twelve hours old delivery gives up by throwing:
3262
+ * the dispatching capability reports it through its error event and the
3263
+ * Agent's `onError`.
3264
+ * @internal Queue and schedule callback.
3265
+ */
3266
+ _cfDeliverWorkflowNotification(
3267
+ payload: WorkflowNotificationPayload
3268
+ ): Promise<void>;
3269
+ /**
3270
+ * Move undelivered rows of the retired `cf_think_workflow_notifications`
3271
+ * outbox into the queue and drop the table. Idempotent: a missing table
3272
+ * means a fresh object or a completed migration.
3273
+ *
3274
+ * TEMPORARY: one-shot upgrade path for objects that were mid-delivery when
3275
+ * this release landed. Remove in the next minor release, once every
3276
+ * deployed object has started on this version and migrated.
3277
+ */
3278
+ private _migrateLegacyWorkflowNotifications;
2948
3279
  inspectSubmission(
2949
3280
  submissionId: string
2950
3281
  ): Promise<ThinkSubmissionInspection | null>;
@@ -2960,20 +3291,37 @@ declare class Think<
2960
3291
  messages: UIMessage[],
2961
3292
  options?: SubmitMessagesOptions
2962
3293
  ): Promise<SubmitMessagesResult>;
2963
- private _scheduleSubmissionDrain;
2964
- private _hasPendingSubmissions;
2965
- _drainThinkSubmissions(): Promise<void>;
2966
- private _drainSubmissions;
2967
- private _runSubmission;
3294
+ /**
3295
+ * Queue the run of one pending submission. Idempotent: the stable id
3296
+ * replaces an item already queued for the submission in place, keeping
3297
+ * its FIFO slot, and re-arms the physical alarm so a lost alarm recovers.
3298
+ */
3299
+ private _queueSubmissionRun;
3300
+ /** Queue a run for every pending submission that has none. */
3301
+ private _queuePendingSubmissionRuns;
3302
+ /**
3303
+ * Run one pending submission. Runs on the Lifecycle alarm loop through the
3304
+ * Queue capability, one item at a time in submission order; a row that is
3305
+ * no longer pending (cancelled, skipped, or claimed by an overlapping
3306
+ * dispatch) is a no-op.
3307
+ * @internal Queue callback.
3308
+ */
3309
+ _cfRunSubmission(payload: { submissionId: string }): Promise<void>;
2968
3310
  private _executeSubmission;
2969
3311
  private _getSubmissionFinalStatus;
2970
3312
  private _markPendingSubmissionsSkipped;
2971
3313
  private _emitSkippedSubmissions;
2972
3314
  private _recoverSubmissionsOnStart;
2973
3315
  private _getSubmissionMessagesAppliedState;
3316
+ /**
3317
+ * Wall-clock creation time of a non-terminal chat-turn run on the Tasks
3318
+ * capability, or null. The metadata column holds the exact JSON the chat
3319
+ * wrapper wrote, so string equality matches the requestId.
3320
+ */
3321
+ private _recoverableChatTurnTaskCreatedAt;
2974
3322
  private _hasRecoverableChatTurn;
2975
3323
  private _hasFreshRecoverableSubmissionEvidence;
2976
- private _hasScheduledRecoveredContinuation;
3324
+ private _hasScheduledChatRecovery;
2977
3325
  /**
2978
3326
  * Inject messages and trigger a model turn — without a WebSocket request.
2979
3327
  *
@@ -3183,10 +3531,6 @@ declare class Think<
3183
3531
  * step, never an already-completed tool call).
3184
3532
  */
3185
3533
  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
3534
  private _streamResult;
3191
3535
  /**
3192
3536
  * Single source of Think's strip + empty-skip persistence rule. Strips the
@@ -3200,6 +3544,29 @@ declare class Think<
3200
3544
  */
3201
3545
  private _strippedForPersist;
3202
3546
  private _persistAssistantMessage;
3547
+ /**
3548
+ * The cutover: persist the finished turn's assistant message, settle its
3549
+ * resumable stream and delete the stream's rows in ONE SQLite transaction,
3550
+ * so a crash leaves either the live stream (recovery rebuilds the message
3551
+ * from it) or the message — never neither, never both. The session
3552
+ * change feed and auto-compaction run once the transaction has committed.
3553
+ */
3554
+ private _persistAssistantMessageWithCutover;
3555
+ /**
3556
+ * Whether this turn's stream rows can go with its cutover. An agent-tool
3557
+ * child turn keeps them: the parent tails the stored chunks after the
3558
+ * child completes (`getAgentToolChunks`), so the rows are reclaimed by
3559
+ * the child's next `start()` instead, as `AIChatAgent` does. A running
3560
+ * submission needs no stream evidence: its durable outcome stamp commits
3561
+ * in the same transaction as this cutover.
3562
+ */
3563
+ private _streamCutoverOptions;
3564
+ /** Write only inside the transaction that settles this exact request's stream. */
3565
+ private _recordSubmissionTurnResult;
3566
+ /** Empty/stripped messages have the same atomic outcome cutover as messages. */
3567
+ private _finalizeSubmissionStream;
3568
+ /** Keep overflow chunks for consumers, but never call that segment an answer. */
3569
+ private _completeSubmissionRetryStream;
3203
3570
  /**
3204
3571
  * Remove parts belonging to Think's internal structured-output final-answer
3205
3572
  * tool (`think_final_answer`, or a collision-suffixed variant) from a UI
@@ -3210,20 +3577,50 @@ declare class Think<
3210
3577
  * SDK can emit.
3211
3578
  */
3212
3579
  private _stripInternalFinalAnswerParts;
3580
+ /**
3581
+ * Turn-start persistence of the client's transcript: reconcile the posted
3582
+ * messages against the server's active path, write only what changed, and
3583
+ * leave the live cache current. Returns `null` when a newer request
3584
+ * superseded this one part-way through (`isCurrent` turned false).
3585
+ *
3586
+ * Storage traffic here is independent of transcript length: the server
3587
+ * transcript comes from the live cache when it covers the path, unchanged
3588
+ * echoed messages are skipped before Sessions is asked, and the cache is
3589
+ * re-read only when it is windowed.
3590
+ */
3591
+ private _reconcileAndPersistIncoming;
3592
+ /**
3593
+ * The server transcript that reconciliation diffs client messages against.
3594
+ * The live cache answers when it holds the whole active path — the common
3595
+ * case, kept current by the change feed after every durable write. A
3596
+ * windowed or unhydrated cache falls back to the full storage read, since
3597
+ * reconciliation must see every message (`_readMessagesFromStorage`).
3598
+ *
3599
+ * Returns a snapshot: the writes that follow patch the cache through the
3600
+ * change feed while the caller is still iterating.
3601
+ */
3602
+ private _serverTranscriptForReconcile;
3213
3603
  /**
3214
3604
  * Persist an incoming message after reconciliation. For assistant
3215
3605
  * messages, also resolve their ID against any server-side row that
3216
3606
  * already owns the same `toolCallId` so we update the existing row
3217
3607
  * instead of inserting an orphan duplicate.
3608
+ *
3609
+ * A message whose stored form is what the server already holds is skipped
3610
+ * outright. The client posts its whole transcript on every request, so
3611
+ * without this every prior message would cost Sessions an existence read
3612
+ * plus a full-row compare (and, for media, a decode and hash of every
3613
+ * payload) per turn — reads spent discovering nothing changed.
3218
3614
  */
3219
3615
  private _persistIncomingMessage;
3220
3616
  /**
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.
3617
+ * The serialized form last written to (or read from) `think_config` for a
3618
+ * request-context key. Every chat request re-sends its client tools and
3619
+ * body; comparing here turns the per-request write into a no-op when
3620
+ * nothing changed. `undefined` means "not persisted" (row absent).
3225
3621
  */
3226
- private _stripReservedMessageMetadata;
3622
+ private _persistedRequestContext;
3623
+ private _persistRequestContextKey;
3227
3624
  private _persistClientTools;
3228
3625
  private _restoreClientTools;
3229
3626
  private _persistBody;
@@ -3360,6 +3757,34 @@ declare class Think<
3360
3757
  */
3361
3758
  private _findExecutionToolCall;
3362
3759
  private _applyToolUpdateToMessages;
3760
+ /**
3761
+ * The persisted message that owns `toolCallId`, read as one row — or
3762
+ * `null` when no persisted row owns it.
3763
+ *
3764
+ * Lookup order, cheapest first:
3765
+ *
3766
+ * 1. `liveMessageId`, when the in-flight accumulator owns the call. A row
3767
+ * under that id exists only when stall recovery persisted a partial
3768
+ * mid-stream. When it does not, the call is not on its own row — but a
3769
+ * provider can replay a prior tool round-trip into a fresh continuation
3770
+ * accumulator (#1404), so the persisted owner may still be an earlier
3771
+ * message; the cache is checked for that before concluding there is
3772
+ * nothing durable to update. Storage is never walked for a call the
3773
+ * live turn owns: every row it could target is on the cached path.
3774
+ * 2. The live cache, for the id only. Whatever names the row, the returned
3775
+ * message is always the STORED form: the apply must compare against
3776
+ * what storage holds, and the cache may be patched ahead of it.
3777
+ * 3. Storage, newest first, stopping at the first owner. Reached only when
3778
+ * the cache does not cover the active path (a windowed hydration, a
3779
+ * boot whose hydration failed, or rows imported behind the cache): a
3780
+ * cross-message result can target a row older than the window, and the
3781
+ * path is read from the leaf so a recent hit costs the rows it passed,
3782
+ * not the transcript.
3783
+ *
3784
+ * This is what keeps a long turn's tool updates independent of transcript
3785
+ * length: the previous shape re-read the whole path per update.
3786
+ */
3787
+ private _resolveToolCallOwner;
3363
3788
  protected hasPendingInteraction(): boolean;
3364
3789
  /**
3365
3790
  * `true` when an auto-continuation is armed but has not yet fired (#1650): a
@@ -3410,18 +3835,19 @@ declare class Think<
3410
3835
  * recomputed from the live, mutable transcript. Compaction collapses older
3411
3836
  * assistant messages into a summary, lowering the count — so a turn that had
3412
3837
  * 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).
3838
+ * its budget prematurely (#1628). It then became a KV counter bumped per
3839
+ * credited chunk. It is now derived from the stream log the chunks were
3840
+ * already flushed to (`ResumableStream.progressMarker`): the log only grows
3841
+ * when new content lands durably, a reconnect replay or a recovery
3842
+ * re-persist reads it without appending (#1637), and compaction rewrites
3843
+ * the transcript, not the log. Nothing is written per chunk.
3844
+ *
3845
+ * The pre-derivation KV counter is folded in once per isolate, so a marker
3846
+ * an in-flight incident already recorded is never read lower after the
3847
+ * upgrade.
3418
3848
  */
3419
3849
  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;
3850
+ private _progressSeed;
3425
3851
  /** Per-isolate N9 throttle gate (shared `agents/chat` helper); reset per
3426
3852
  * isolate so the first forwarded chunk after a restart always credits. */
3427
3853
  private _agentToolStreamProgress;
@@ -3429,7 +3855,9 @@ declare class Think<
3429
3855
  * N9: forwarding a sub-agent's chunks IS forward progress for this parent
3430
3856
  * turn, so credit the parent's recovery progress marker — otherwise a parent
3431
3857
  * 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
3858
+ * no-progress window exhausts while the child is healthily streaming. The
3859
+ * child's output goes to clients, not to this object's stream log, so the
3860
+ * derived marker cannot see it; this is the one explicit credit left. Only
3433
3861
  * invoked after a child actually produced output (see
3434
3862
  * `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.
3435
3863
  * Throttled (and reset per isolate) so we never write storage per token.
@@ -3479,10 +3907,16 @@ declare class Think<
3479
3907
  */
3480
3908
  private _resolveThinkRecoveryStream;
3481
3909
  /**
3482
- * Classify a recovered turn as `retry` or `continue`. A pre-stream turn with no
3483
- * partial re-runs its user message (`retryTargetUserId`), unless the stream is
3484
- * already terminal — a terminal stream is never retried (it completed), only
3485
- * its submission is reconciled in dispatch.
3910
+ * Classify a recovered turn as `retry` or `continue`. A turn that left no
3911
+ * persisted partial re-runs its user message (`retryTargetUserId`), unless
3912
+ * the stream is already terminal — a terminal stream is never retried (it
3913
+ * completed), only its submission is reconciled in dispatch.
3914
+ *
3915
+ * The stream row is opened before inference, so an interrupted turn can
3916
+ * have a stream id and still nothing to continue from; what decides retry is
3917
+ * the absence of persisted content and a leaf that is still the turn's user
3918
+ * message. Mirrors `AIChatAgent`'s empty-partial new-turn rule (#1691): a
3919
+ * `continue` here would find no assistant message and skip the turn.
3486
3920
  */
3487
3921
  private _classifyRecoveredThinkTurn;
3488
3922
  /**
@@ -3570,10 +4004,10 @@ declare class Think<
3570
4004
  * `_exhaustChatRecovery` entirely — so an app relying on `onExhausted` for the
3571
4005
  * terminal banner regressed to an eternal spinner when recovery gave up under
3572
4006
  * 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
4007
+ * in a recovery callback is SWALLOWED by the driving Task attempt (or the
4008
+ * routed one-shot schedule row) — only a platform transient is re-thrown to
4009
+ * preserve it — so without routing it here the run/row settles with no
4010
+ * terminal UX at all — the half-finished message wedges silently. Shared by
3577
4011
  * `_chatRecoveryRetry` and `_chatRecoveryContinue`.
3578
4012
  *
3579
4013
  * Exactly-once terminalization is defended by two independent guards:
@@ -3591,8 +4025,9 @@ declare class Think<
3591
4025
  * Residual at-least-once edges, all deliberately accepted as "deliver a
3592
4026
  * second banner" ≫ "silently drop the turn":
3593
4027
  * • 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.
4028
+ * invocation — every production recovery enqueue carries one): the
4029
+ * synthesized incident can't be persisted (no key), so guard #1 can't
4030
+ * arm.
3596
4031
  * • The record is swept AGAIN between two alarms (guard #1 re-persists on the
3597
4032
  * first, so this needs a second independent sweep) — vanishingly unlikely.
3598
4033
  * • A platform transient interrupts `_exhaustChatRecovery` after the banner
@@ -3600,18 +4035,26 @@ declare class Think<
3600
4035
  * (the terminal writes themselves are idempotent).
3601
4036
  */
3602
4037
  /**
3603
- * Recovery continuation callbacks the alarm-boundary OOM circuit breaker may
3604
- * back off / purge (#1825). See `Agent._cf_handleAlarmMemoryLimitReset`.
4038
+ * Host memory-limit policy hook (#1825), dispatched structurally by
4039
+ * Lifecycle's circuit breaker — protected because it is framework
4040
+ * machinery, not part of the public Think API. Tasks applies the breaker to
4041
+ * root recovery runs; the routed dynamic-agent fallback applies it to
4042
+ * `recoveryLoop` schedule rows (see `RecoveryLoopScheduleOptions`). At the
4043
+ * strike budget this hook seals active incidents via
4044
+ * {@link _cf_sealMemoryLimitedRecovery}.
3605
4045
  */
3606
- protected _cf_recoveryAlarmCallbacks(): string[];
4046
+ protected onAlarmMemoryLimit(context: {
4047
+ readonly sealed: boolean;
4048
+ }): Promise<void>;
3607
4049
  /**
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`.
4050
+ * Seal any still-live recovery incident as an out-of-memory exhaustion
4051
+ * when the alarm circuit breaker trips at its strike budget (#1825). Runs
4052
+ * at the outermost alarm frame (post-unwind), so the terminal banner /
4053
+ * `onExhausted` and the sealed-incident write can land where the mid-turn
4054
+ * give-up's writes OOMed. Reuses the shared give-up spine via
4055
+ * `_exhaustRecoveryGiveUp`.
3613
4056
  */
3614
- protected _cf_sealMemoryLimitedRecovery(): Promise<void>;
4057
+ private _cf_sealMemoryLimitedRecovery;
3615
4058
  private _exhaustRecoveryGiveUp;
3616
4059
  /**
3617
4060
  * Give-up after the stable-state-timeout retry budget drained. Thin wrapper
@@ -3651,35 +4094,57 @@ declare class Think<
3651
4094
  * deploy code-update reset / script supersede, a `retryable`-flagged
3652
4095
  * platform error, or "Network connection lost.", looking through wrappers
3653
4096
  * 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
4097
+ * marking the incident `failed` for observability) so the current
4098
+ * attempt (the driving Task run, or the routed one-shot schedule row) is
4099
+ * preserved and the platform re-runs recovery once it is healthy again — the turn can
3657
4100
  * still recover, so it must NOT terminalize. Terminalizing here was the
3658
4101
  * #1730 freeze: the give-up's own seal needs the very storage that is
3659
4102
  * down, so it throws too, burns the in-process retry budget inside the
3660
4103
  * same reset window, and the row is consumed milliseconds before storage
3661
4104
  * recovers. The submission is deliberately left `running` — the deferred
3662
- * re-run reads it via `_readRunningSubmissionByRequestId`, so marking it
4105
+ * re-run reads it via `_readRunningSubmissionForRecovery`, so marking it
3663
4106
  * terminal here would turn the preserved row into a guaranteed
3664
4107
  * `submission_not_running` no-op skip (a self-defeating defer).
3665
4108
  * - Any OTHER (application) error is terminalized through the give-up path
3666
4109
  * (`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).
4110
+ * the fix for the silent-seal failure mode: the driving attempt swallows
4111
+ * a non-transient throw and settles without terminalizing, so without
4112
+ * terminalizing here the half-finished turn is dropped with no terminal
4113
+ * event and no banner (the user stares at a frozen message until they
4114
+ * send something new).
3672
4115
  */
3673
4116
  private _handleRecoveryCallbackError;
4117
+ /**
4118
+ * Keep the recovery callback as owner until a chat Task or facet fiber is durably
4119
+ * accepted. At acceptance, move the running submission to the successor's
4120
+ * request identity before signaling handoff. If an override never starts a
4121
+ * durable successor, the signal stays inert and the callback owns the work
4122
+ * until the override returns.
4123
+ */
4124
+ private _runRecoveredTurnAfterAcceptance;
3674
4125
  _chatRecoveryRetry(data?: ChatRecoveryRetryData): Promise<void>;
3675
- private _hasRunningSubmission;
3676
- private _readRunningSubmissionByRequestId;
4126
+ protected _chatRecoveryRetryDetached(
4127
+ data?: ChatRecoveryRetryData,
4128
+ onTurnStarted?: () => void
4129
+ ): Promise<void>;
4130
+ /**
4131
+ * Recovery payloads retain the original submission/root identity while
4132
+ * request_id follows the accepted successor. Match both so released payloads,
4133
+ * redeferred callbacks, and exhaustion can still locate the running row.
4134
+ * Exact submission identity wins even when terminal: a redelivery must not
4135
+ * fall through to another submission whose successor request collides.
4136
+ */
4137
+ private _readRunningSubmissionForRecovery;
3677
4138
  private _markRecoveredSubmissionInterrupted;
3678
4139
  private _completeRecoveredSubmission;
3679
4140
  protected onChatRecovery(
3680
4141
  _ctx: ChatRecoveryContext
3681
4142
  ): Promise<ChatRecoveryOptions | void>;
3682
4143
  _chatRecoveryContinue(data?: ChatRecoveryContinueData): Promise<void>;
4144
+ protected _chatRecoveryContinueDetached(
4145
+ data?: ChatRecoveryContinueData,
4146
+ onTurnStarted?: () => void
4147
+ ): Promise<void>;
3683
4148
  private _applyRecoveredRequestContext;
3684
4149
  private _getPartialStreamText;
3685
4150
  private _getSubmitConcurrencyDecision;
@@ -3744,20 +4209,25 @@ declare class Think<
3744
4209
  private _fireAutoContinuation;
3745
4210
  private _activateDeferredContinuation;
3746
4211
  /**
3747
- * Run a continuation turn that does NOT require a live client connection.
4212
+ * Queue a continuation turn that does NOT require a live client connection.
3748
4213
  *
3749
4214
  * Used when a durable approval (a paused action or codemode execution) is
3750
4215
  * resolved via RPC from a surface with no open chat socket — e.g. an ops
3751
4216
  * dashboard, a webhook, or a voice backend approving hours/days later. The
3752
- * connection-bound auto-continuation barrier (`_fireAutoContinuation`) cannot
3753
- * fire without a `Connection`, so this mirrors its turn body but streams via
3754
- * `broadcast` (a no-op when nobody is attached) and always persists, so a
3755
- * client that reconnects later resumes the continued turn from history.
3756
- *
3757
- * Wrapped in `keepAliveWhile` because the resolving RPC returns before the
3758
- * continuation finishes (mirrors the submission-drain pattern).
4217
+ * item is durable, so the turn still runs if the object leaves memory
4218
+ * before the alarm fires; the last request body and client tools it needs
4219
+ * are persisted config, restored on start. Approvals landing while one
4220
+ * continuation is pending or running coalesce onto the single item.
4221
+ */
4222
+ private _queueConnectionlessContinuation;
4223
+ /**
4224
+ * Run one connection-less continuation turn. Mirrors the connection-bound
4225
+ * auto-continuation turn body but streams via `broadcast` (a no-op when
4226
+ * nobody is attached) and always persists, so a client that reconnects
4227
+ * later resumes the continued turn from history.
4228
+ * @internal Queue callback.
3759
4229
  */
3760
- private _runConnectionlessContinuation;
4230
+ _cfRunConnectionlessContinuation(): Promise<void>;
3761
4231
  /**
3762
4232
  * Render a reply attachment ({@link ReplyAttachment}) for delivery to the
3763
4233
  * active channel. Returns the text/markdown to post, or `undefined` to skip —
@@ -3855,35 +4325,20 @@ declare class Think<
3855
4325
  messageId?: string;
3856
4326
  }
3857
4327
  ): 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
- */
4328
+ /** Mark a resumable stream completed (settled now, rows kept until reclaim). */
3863
4329
  protected _completeResumableStream(streamId: string): void;
3864
4330
  /**
3865
- * Mark a resumable stream errored and arm buffer cleanup. Wrapper around
3866
- * `ResumableStream.markError` — see {@link _completeResumableStream}.
3867
- */
3868
- protected _errorResumableStream(streamId: string): void;
3869
- /**
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.
4331
+ * The producer finished; leave the row for the cutover that persists the
4332
+ * assistant message (`_persistAssistantMessageWithCutover`). Every path
4333
+ * that calls this must end in that cutover or `finalizePending()`.
3878
4334
  */
3879
- protected _ensureStreamCleanupScheduled({
3880
- idempotent
3881
- }?: {
3882
- idempotent?: boolean;
3883
- }): Promise<void>;
4335
+ protected _finishResumableStream(streamId: string): void;
4336
+ /** Mark a resumable stream errored. */
4337
+ protected _errorResumableStream(streamId: string, requestId?: string): void;
3884
4338
  /**
3885
- * Alarm callback: sweep aged stream buffers, re-arming while rows remain (see
3886
- * the shared {@link cleanupStreamBuffers}).
4339
+ * @deprecated Streams are reclaimed at cutover and on the next stream
4340
+ * start; no alarm is armed any more. Kept so a cleanup alarm persisted by
4341
+ * an earlier version still resolves to a callback when it fires.
3887
4342
  */
3888
4343
  _cleanupStreamBuffers(): Promise<void>;
3889
4344
  private _persistOrphanedStream;
@@ -4246,6 +4701,18 @@ interface MessengerThinkHost extends MessengerThinkTarget {
4246
4701
  options?: StartFiberOptions
4247
4702
  ): Promise<MessengerFiberStartResult>;
4248
4703
  resolveFiber(id: string, result: FiberRecoveryResult): Promise<boolean>;
4704
+ /**
4705
+ * Durably accept one messenger reply run on the host's Tasks capability
4706
+ * and execute it inline while this isolate lives. The same idempotency key
4707
+ * joins the existing run (`accepted: false`).
4708
+ */
4709
+ _runMessengerReplyTask(input: {
4710
+ nonce: string;
4711
+ idempotencyKey: string;
4712
+ metadata: Record<string, unknown>;
4713
+ }): Promise<{
4714
+ accepted: boolean;
4715
+ }>;
4249
4716
  subAgent<T extends Agent>(
4250
4717
  agentClass: SubAgentClass<T>,
4251
4718
  name: string
@@ -4263,6 +4730,12 @@ declare function chatSdkMessenger(
4263
4730
  declare class ThinkMessengerRuntime {
4264
4731
  private readonly host;
4265
4732
  private chat?;
4733
+ /**
4734
+ * Live reply closures keyed by run nonce. A closure exists only in the
4735
+ * isolate that accepted the webhook; an interrupted reply is recovered on
4736
+ * wake through {@link handleFiberRecovery} from its persisted snapshot.
4737
+ */
4738
+ private readonly liveReplies;
4266
4739
  private readonly definitionsByAdapterName;
4267
4740
  private readonly definitionsById;
4268
4741
  private readonly definitions;
@@ -4270,8 +4743,33 @@ declare class ThinkMessengerRuntime {
4270
4743
  get size(): number;
4271
4744
  initialize(): void;
4272
4745
  handleRequest(request: Request): Promise<Response | undefined>;
4273
- handleFiberRecovery(ctx: FiberRecoveryContext): Promise<boolean>;
4746
+ handleFiberRecovery(
4747
+ ctx: FiberRecoveryContext,
4748
+ options?: {
4749
+ /**
4750
+ * Capability-run recovery: persist re-entry checkpoints here instead
4751
+ * of the legacy managed-fiber ledger, whose row does not exist for
4752
+ * runs on the Tasks capability. Terminal settlement is implied by the
4753
+ * caller's recovery decision, so the legacy `resolveFiber` completion
4754
+ * calls are skipped when this hook is present.
4755
+ */
4756
+ persistRecoverySnapshot?: (
4757
+ snapshot: ReturnType<typeof messengerReplySnapshot>
4758
+ ) => Promise<void> | void;
4759
+ }
4760
+ ): Promise<boolean>;
4274
4761
  private createChat;
4762
+ /** Whether this isolate still holds the live closure for one reply. */
4763
+ hasLiveReply(nonce: string): boolean;
4764
+ /**
4765
+ * The durable "accepted" snapshot for one live reply, when its closure is
4766
+ * still held. The task definition persists this BEFORE delivery begins:
4767
+ * an isolate lost mid-answer recovers through it, and without it replay
4768
+ * could neither deliver nor apologize.
4769
+ */
4770
+ initialReplySnapshot(nonce: string): unknown | undefined;
4771
+ /** Execute one live (same-isolate) reply under the given fiber context. */
4772
+ executeLiveReply(nonce: string, fiber: FiberContext): Promise<void>;
4275
4773
  private enqueueReply;
4276
4774
  private answer;
4277
4775
  /**
@@ -4361,8 +4859,10 @@ export {
4361
4859
  ChannelContext as In,
4362
4860
  PendingApproval as It,
4363
4861
  MessengerCapabilities as J,
4862
+ SessionContextOptions as Jn,
4364
4863
  SaveMessagesResult$1 as Jt,
4365
4864
  MessengerAttachment as K,
4865
+ CompactAfterOptions as Kn,
4366
4866
  RunTurnWait as Kt,
4367
4867
  TextStreamCallbackOptions as L,
4368
4868
  ChannelDefinition as Ln,
@@ -4380,7 +4880,7 @@ export {
4380
4880
  skills as Pn,
4381
4881
  MessageConcurrency$1 as Pt,
4382
4882
  MessengerMessage as Q,
4383
- SkillSource$1 as Qt,
4883
+ SkillWorkspaceSeedOptions$1 as Qt,
4384
4884
  defaultDeliveryTag as R,
4385
4885
  ChannelDeliveryPolicy as Rn,
4386
4886
  PrepareStepFunction$1 as Rt,
@@ -4400,11 +4900,12 @@ export {
4400
4900
  messengerChannel as Wn,
4401
4901
  RunTurnStream as Wt,
4402
4902
  MessengerEvent as X,
4403
- SessionMessage$1 as Xt,
4903
+ SkillRunContext as Xt,
4404
4904
  MessengerContext as Y,
4405
- Session$1 as Yt,
4905
+ ThinkSession as Yn,
4906
+ SessionMessage$1 as Yt,
4406
4907
  MessengerEventKind as Z,
4407
- SkillRunContext as Zt,
4908
+ SkillSource$1 as Zt,
4408
4909
  idempotencyKeyForEvent as _,
4409
4910
  ThinkSubmissionStatus as _n,
4410
4911
  ChatOptions as _t,
@@ -4456,6 +4957,7 @@ export {
4456
4957
  ThinkScheduledTaskContext as pn,
4457
4958
  ActionPermissionSpec as pt,
4458
4959
  MessengerAuthor as q,
4960
+ CompactionErrorHandler as qn,
4459
4961
  SaveMessagesOptions$1 as qt,
4460
4962
  MessengerConversationMode as r,
4461
4963
  StreamCallback as rn,
@@ -4485,4 +4987,4 @@ export {
4485
4987
  ChannelDeliverySurface as zn,
4486
4988
  PrepareStepResult$1 as zt
4487
4989
  };
4488
- //# sourceMappingURL=index-B7zEkBBM.d.ts.map
4990
+ //# sourceMappingURL=index-BLkPlEbF.d.ts.map