@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.
package/dist/think.js CHANGED
@@ -1,8 +1,9 @@
1
- import { a as _classPrivateFieldSet2, i as _classPrivateFieldGet2, n as sanitizeName, s as _classPrivateFieldInitSpec, t as ExtensionManager } from "./manager-CSk5htym.js";
1
+ import { a as _assertClassBrand, i as _classPrivateFieldGet2, n as sanitizeName, o as _classPrivateFieldInitSpec, r as _classPrivateFieldSet2, s as _classPrivateMethodInitSpec, t as ExtensionManager } from "./manager-Cb3DNZgp.js";
2
2
  import { createWorkspaceTools } from "./tools/workspace.js";
3
3
  import { createFetchTools } from "./tools/fetch.js";
4
4
  import { truncatePausedExecutionOutput } from "./tools/execute.js";
5
- import { t as ThinkMessengerRuntime } from "./chat-sdk-C8BvREXn.js";
5
+ import { g as MESSENGER_REPLY_FIBER_NAME, t as ThinkMessengerRuntime } from "./chat-sdk-B77QwYuj.js";
6
+ import "./messengers/index.js";
6
7
  import { AsyncLocalStorage } from "node:async_hooks";
7
8
  import * as aiSdk from "ai";
8
9
  import { convertToModelMessages, hasToolCall, jsonSchema, stepCountIs, tool } from "ai";
@@ -13,64 +14,284 @@ import { openai } from "workers-ai-provider/openai";
13
14
  import * as skills from "agents/skills";
14
15
  import { SkillRegistry } from "agents/skills";
15
16
  import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext, __DO_NOT_USE_WILL_BREAK__withInvocationScope, callable, getCurrentAgent, isDurableObjectMemoryLimitReset, isPlatformTransientError } from "agents";
16
- import { AbortRegistry, AgentToolProgressEmitter, AgentToolStreamProgressThrottle, AutoContinuationController, CHAT_MESSAGE_TYPES, ChatRecoveryEngine, ChatStreamStalledError, ContinuationState, MAX_BOUND_PARAMS, PreStreamTurns, ResumableStream, ResumeHandshake, STREAM_CLEANUP_DELAY_SECONDS, StreamAccumulator, StreamProgressCreditThrottle, SubmitConcurrencyController, TIMED_OUT, TurnQueue, aiSdkRecoveryCodec, applyToolUpdate, awaitWithDeadline, buildChatRecoveringFrame, buildInClauseStrings, bumpChatRecoveryProgress, chatRecoverySchedulePolicy, classifyAgentToolChildRecovery, cleanupStreamBuffers, clearChatTerminal, clientResolvableToolNames, createChatFiberSnapshot, createToolsFromClientSchemas, crossMessageToolResultUpdate, drainInteractionApplies, enforceRowSizeLimit, hasIncompleteToolBatch, interceptAgentToolBroadcast, iterateWithStallWatchdog, listActiveChatRecoveryIncidents, normalizeToolInput, parseProtocolMessage, partAwaitsClientInteraction, pausedExecutionUpdate, pendingChatTerminal, persistReconstructedOrphan, readChatRecoveryProgress, reconcileMessages, recordChatTerminal, repairInterruptedToolParts, resolveChatRecoveryConfig, resolveToolMergeId, runChatRecoveryExhaustion, sanitizeMessage, setChatRecovering, shouldCreditStreamProgress, sweepStaleChatRecoveryIncidents, toolApprovalUpdate, toolPartHasSettledResult, toolResultUpdate, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
17
- import { Session, Session as Session$1 } from "agents/experimental/memory/session";
18
- import { truncateOlderMessages } from "agents/experimental/memory/utils";
17
+ import { AbortRegistry, AgentToolProgressEmitter, AgentToolStreamProgressThrottle, AutoContinuationController, CHAT_MESSAGE_TYPES, CHAT_RECOVERY_PROGRESS_KEY, CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS, CHAT_RECOVERY_TASK_NAME, ChatRecoveryEngine, ChatStreamStalledError, ContinuationState, MAX_BOUND_PARAMS, PreStreamTurns, ResumableStream, ResumeHandshake, StreamAccumulator, SubmitConcurrencyController, TIMED_OUT, TurnQueue, aiSdkRecoveryCodec, applyToolUpdate, awaitWithDeadline, buildChatRecoveringFrame, buildInClauseStrings, chatRecoveryTaskRunOptions, classifyAgentToolChildRecovery, clearChatTerminal, clientResolvableToolNames, createChatFiberSnapshot, createChatRecoveryTaskDefinition, createChatStreams, createChatTurnTaskDefinition, createToolsFromClientSchemas, crossMessageToolResultUpdate, dispatchChatRecoveryToHandoff, drainInteractionApplies, enforceRowSizeLimit, hasIncompleteToolBatch, interceptAgentToolBroadcast, iterateWithStallWatchdog, listActiveChatRecoveryIncidents, normalizeToolInput, parseProtocolMessage, partAwaitsClientInteraction, pausedExecutionUpdate, pendingChatTerminal, persistReconstructedOrphan, readChatRecoveryProgress, reconcileMessages, recordChatTerminal, repairInterruptedToolParts, resolveChatRecoveryConfig, resolveToolMergeId, runChatRecoveryExhaustion, sanitizeMessage, setChatRecovering, sweepStaleChatRecoveryIncidents, toolApprovalUpdate, toolPartHasSettledResult, toolResultUpdate, truncateOlderMessages, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
18
+ import { Sessions, isCompactionMessage } from "agents/sessions";
19
+ import { AgentContextProvider, ContextBlocks } from "agents/context";
19
20
  import { Workspace, Workspace as Workspace$1 } from "@cloudflare/shell";
21
+ //#region src/session.ts
22
+ var _handle = /* @__PURE__ */ new WeakMap();
23
+ var _context = /* @__PURE__ */ new WeakMap();
24
+ var _pendingContext = /* @__PURE__ */ new WeakMap();
25
+ var _promptStore = /* @__PURE__ */ new WeakMap();
26
+ var _compactionErrorHandler = /* @__PURE__ */ new WeakMap();
27
+ var ThinkSession = class {
28
+ /** @internal Constructed by Think during `onStart`. */
29
+ constructor(handle, context) {
30
+ _classPrivateFieldInitSpec(this, _handle, void 0);
31
+ _classPrivateFieldInitSpec(this, _context, void 0);
32
+ _classPrivateFieldInitSpec(this, _pendingContext, []);
33
+ _classPrivateFieldInitSpec(this, _promptStore, void 0);
34
+ _classPrivateFieldInitSpec(this, _compactionErrorHandler, null);
35
+ _classPrivateFieldSet2(_handle, this, handle);
36
+ _classPrivateFieldSet2(_context, this, context);
37
+ }
38
+ get sessionId() {
39
+ return _classPrivateFieldGet2(_handle, this).sessionId;
40
+ }
41
+ /** @internal Blocks declared through `withContext()` during configuration. */
42
+ internal_takePendingContext() {
43
+ const pending = _classPrivateFieldGet2(_pendingContext, this) ?? [];
44
+ _classPrivateFieldSet2(_pendingContext, this, null);
45
+ return pending;
46
+ }
47
+ /** @internal A custom frozen-prompt store passed to `withCachedPrompt()`. */
48
+ internal_promptStore() {
49
+ return _classPrivateFieldGet2(_promptStore, this);
50
+ }
51
+ /**
52
+ * Declare a prompt context block.
53
+ *
54
+ * @deprecated Return the block from `configureContext()` instead. Only
55
+ * callable inside `configureSession()`; after startup use
56
+ * `this.context.addBlock()`.
57
+ */
58
+ withContext(label, options = {}) {
59
+ if (!_classPrivateFieldGet2(_pendingContext, this)) throw new Error("withContext() is only available inside configureSession(). After startup, add a block with this.context.addBlock().");
60
+ _classPrivateFieldGet2(_pendingContext, this).push({
61
+ label,
62
+ ...options
63
+ });
64
+ return this;
65
+ }
66
+ /**
67
+ * Persist the frozen system prompt.
68
+ *
69
+ * @deprecated The frozen prompt is always persisted now, so this is a
70
+ * no-op. A custom `provider` is still honoured as the prompt store.
71
+ */
72
+ withCachedPrompt(provider) {
73
+ if (provider) _classPrivateFieldSet2(_promptStore, this, provider);
74
+ return this;
75
+ }
76
+ /** Register the function `compact()` calls to summarize a branch. */
77
+ onCompaction(fn) {
78
+ _classPrivateFieldGet2(_handle, this).onCompaction(async (messages) => {
79
+ try {
80
+ return await fn(messages);
81
+ } catch (error) {
82
+ const handler = _classPrivateFieldGet2(_compactionErrorHandler, this);
83
+ if (!handler) throw error;
84
+ await handler(error);
85
+ return null;
86
+ }
87
+ });
88
+ return this;
89
+ }
90
+ /**
91
+ * Auto-compact after an append once the stamped token estimate crosses the
92
+ * threshold. Requires `onCompaction()`.
93
+ */
94
+ compactAfter(tokenThreshold, _options) {
95
+ _classPrivateFieldGet2(_handle, this).compactAfter(tokenThreshold);
96
+ return this;
97
+ }
98
+ /**
99
+ * Observe compaction failures. When set, a failing compaction function
100
+ * calls the handler and the compaction is skipped; without one the failure
101
+ * is reported through the `session:error` capability event.
102
+ */
103
+ onCompactionError(handler) {
104
+ _classPrivateFieldSet2(_compactionErrorHandler, this, handler);
105
+ return this;
106
+ }
107
+ history(options) {
108
+ return _classPrivateFieldGet2(_handle, this).history(options);
109
+ }
110
+ historyBatches(options) {
111
+ return _classPrivateFieldGet2(_handle, this).historyBatches(options);
112
+ }
113
+ /**
114
+ * Materialize the whole selected path. Accepts a leaf id positionally, as
115
+ * the pre-Sessions API did, or a read-options object.
116
+ */
117
+ getHistory(leafIdOrOptions) {
118
+ return _classPrivateFieldGet2(_handle, this).getHistory(readOptions(leafIdOrOptions));
119
+ }
120
+ /**
121
+ * Byte-budgeted read of the most recent messages on the active path. The
122
+ * pre-Sessions `minRecentMessages` argument is accepted and ignored: the
123
+ * budget is a hard ceiling, and the newest message is always returned.
124
+ */
125
+ getRecentHistory(maxContentBytes, optionsOrMinRecentMessages) {
126
+ const options = typeof optionsOrMinRecentMessages === "object" ? optionsOrMinRecentMessages : void 0;
127
+ return _classPrivateFieldGet2(_handle, this).getRecentHistory(maxContentBytes, options);
128
+ }
129
+ getHistoryRowStats(leafId) {
130
+ return _classPrivateFieldGet2(_handle, this).getHistoryRowStats(leafId);
131
+ }
132
+ /** @deprecated Read `getHistoryRowStats()` and take its length. */
133
+ async getPathLength(leafId) {
134
+ return (await _classPrivateFieldGet2(_handle, this).getHistoryRowStats(leafId)).length;
135
+ }
136
+ getMessage(id) {
137
+ return _classPrivateFieldGet2(_handle, this).getMessage(id);
138
+ }
139
+ getLatestLeaf() {
140
+ return _classPrivateFieldGet2(_handle, this).getLatestLeaf();
141
+ }
142
+ getBranches(messageId) {
143
+ return _classPrivateFieldGet2(_handle, this).getBranches(messageId);
144
+ }
145
+ search(query, options) {
146
+ return _classPrivateFieldGet2(_handle, this).search(query, options);
147
+ }
148
+ /**
149
+ * Append one message. Accepts the parent id positionally, as the
150
+ * pre-Sessions API did, or an options object.
151
+ */
152
+ appendMessage(message, parentIdOrOptions) {
153
+ return _classPrivateFieldGet2(_handle, this).appendMessage(message, appendOptions(parentIdOrOptions));
154
+ }
155
+ updateMessage(message, options) {
156
+ return _classPrivateFieldGet2(_handle, this).updateMessage(message, options);
157
+ }
158
+ upsertMessage(message, parentIdOrOptions) {
159
+ return _classPrivateFieldGet2(_handle, this).upsertMessage(message, appendOptions(parentIdOrOptions));
160
+ }
161
+ importMessage(message, options) {
162
+ return _classPrivateFieldGet2(_handle, this).importMessage(message, options);
163
+ }
164
+ deleteMessages(messageIds) {
165
+ return _classPrivateFieldGet2(_handle, this).deleteMessages(messageIds);
166
+ }
167
+ clearMessages() {
168
+ return _classPrivateFieldGet2(_handle, this).clearMessages();
169
+ }
170
+ addCompaction(summary, fromMessageId, toMessageId) {
171
+ return _classPrivateFieldGet2(_handle, this).addCompaction(summary, fromMessageId, toMessageId);
172
+ }
173
+ getCompactions() {
174
+ return _classPrivateFieldGet2(_handle, this).getCompactions();
175
+ }
176
+ compact(leafId) {
177
+ return _classPrivateFieldGet2(_handle, this).compact(leafId);
178
+ }
179
+ /** @deprecated Use `this.context.addBlock({ label, ...options })`. */
180
+ addContext(label, options = {}) {
181
+ return _classPrivateFieldGet2(_context, this).call(this).addBlock({
182
+ label,
183
+ ...options
184
+ });
185
+ }
186
+ /** @deprecated Use `this.context.removeBlock(label)`. */
187
+ removeContext(label) {
188
+ return _classPrivateFieldGet2(_context, this).call(this).removeBlock(label);
189
+ }
190
+ /** @deprecated Use `this.context.getBlock(label)`. */
191
+ getContextBlock(label) {
192
+ return _classPrivateFieldGet2(_context, this).call(this).getBlock(label);
193
+ }
194
+ /** @deprecated Use `this.context.getBlocks()`. */
195
+ getContextBlocks() {
196
+ return _classPrivateFieldGet2(_context, this).call(this).getBlocks();
197
+ }
198
+ /** @deprecated Use `this.context.setBlock(label, content)`. */
199
+ replaceContextBlock(label, content) {
200
+ return _classPrivateFieldGet2(_context, this).call(this).setBlock(label, content);
201
+ }
202
+ /** @deprecated Use `this.context.appendToBlock(label, content)`. */
203
+ appendContextBlock(label, content) {
204
+ return _classPrivateFieldGet2(_context, this).call(this).appendToBlock(label, content);
205
+ }
206
+ /** @deprecated Use `this.context.freezeSystemPrompt()`. */
207
+ freezeSystemPrompt() {
208
+ return _classPrivateFieldGet2(_context, this).call(this).freezeSystemPrompt();
209
+ }
210
+ /** @deprecated Use `this.context.refreshSystemPrompt()`. */
211
+ refreshSystemPrompt() {
212
+ return _classPrivateFieldGet2(_context, this).call(this).refreshSystemPrompt();
213
+ }
214
+ /** @deprecated Use `this.context.tools()`. */
215
+ tools() {
216
+ return _classPrivateFieldGet2(_context, this).call(this).tools();
217
+ }
218
+ };
219
+ function readOptions(leafIdOrOptions) {
220
+ if (leafIdOrOptions === void 0) return void 0;
221
+ if (leafIdOrOptions === null || typeof leafIdOrOptions === "string") return { leafId: leafIdOrOptions };
222
+ return leafIdOrOptions;
223
+ }
224
+ function appendOptions(parentIdOrOptions) {
225
+ if (parentIdOrOptions === void 0) return void 0;
226
+ if (parentIdOrOptions === null || typeof parentIdOrOptions === "string") return { parentId: parentIdOrOptions };
227
+ return parentIdOrOptions;
228
+ }
229
+ //#endregion
20
230
  //#region src/media-eviction.ts
231
+ /** Nested tool-output walks stop here so hostile output cannot recurse forever. */
232
+ const MAX_WALK_DEPTH = 8;
21
233
  function resolveMediaEvictionConfig(config) {
22
234
  if (config === false) return null;
23
235
  const base = config === true ? {} : config;
24
236
  return {
25
237
  keepRecentMessages: base.keepRecentMessages ?? 8,
26
238
  minPartBytes: base.minPartBytes ?? 32 * 1024,
27
- externalizeToWorkspace: base.externalizeToWorkspace ?? true,
28
239
  maxRowsPerPass: base.maxRowsPerPass ?? 64
29
240
  };
30
241
  }
31
- const MAX_WALK_DEPTH = 8;
32
242
  /**
33
- * Replace oversized media values in a message with markers.
34
- * Returns a new message — the input is not mutated.
243
+ * The exact marker Think has always written. Old and new markers are
244
+ * byte-identical, so a transcript evicted before and after the Sessions
245
+ * replatform reads the same and old markers keep resolving.
35
246
  */
36
- function evictLargeMediaFromMessage(message, options) {
247
+ function evictionMarker(bytes, path, mediaType) {
248
+ return `[evicted ${mediaType ? `${mediaType}, ` : ""}${bytes} bytes; preserved at ${path}]`;
249
+ }
250
+ /**
251
+ * Replace aged oversized media in one message with markers, writing the
252
+ * bytes to the Workspace first. Returns a new message — the input is never
253
+ * mutated, and nothing is written when nothing qualifies.
254
+ */
255
+ async function evictMediaFromMessage(message, options) {
37
256
  const state = {
38
257
  options,
258
+ index: 0,
39
259
  parts: 0,
40
- bytes: 0,
41
- blobs: []
260
+ bytes: 0
42
261
  };
43
262
  let changed = false;
44
- const parts = message.parts.map((part) => {
263
+ const parts = [];
264
+ for (const part of message.parts) {
45
265
  if (part.type === "file" && "url" in part) {
46
- const url = part.url;
47
- if (typeof url === "string" && url.startsWith("data:") && url.length >= options.minPartBytes) {
266
+ const marker = await evictUrl(state, part.url, part.mediaType);
267
+ if (marker !== null) {
48
268
  changed = true;
49
- const mediaType = part.mediaType ?? dataUrlMediaType(url);
50
- const path = extractBlob(state, url, mediaType);
51
- return {
269
+ parts.push({
52
270
  type: "text",
53
- text: evictionMarker(url.length, path, mediaType)
54
- };
271
+ text: marker
272
+ });
273
+ continue;
55
274
  }
56
- return part;
275
+ parts.push(part);
276
+ continue;
57
277
  }
58
278
  if ((part.type.startsWith("tool-") || part.type === "dynamic-tool") && "output" in part) {
59
279
  const output = part.output;
60
280
  if (output !== void 0) {
61
281
  const before = state.parts;
62
- const evicted = walkAndEvict(state, output, 0);
282
+ const rewritten = await walkAndEvict(state, output, 0);
63
283
  if (state.parts > before) {
64
284
  changed = true;
65
- return {
285
+ parts.push({
66
286
  ...part,
67
- output: evicted
68
- };
287
+ output: rewritten
288
+ });
289
+ continue;
69
290
  }
70
291
  }
71
292
  }
72
- return part;
73
- });
293
+ parts.push(part);
294
+ }
74
295
  return {
75
296
  message: changed ? {
76
297
  ...message,
@@ -78,60 +299,117 @@ function evictLargeMediaFromMessage(message, options) {
78
299
  } : message,
79
300
  changed,
80
301
  parts: state.parts,
81
- bytes: state.bytes,
82
- blobs: state.blobs
302
+ bytes: state.bytes
83
303
  };
84
304
  }
85
- function walkAndEvict(state, value, depth) {
86
- if (typeof value === "string") {
87
- if (value.length < state.options.minPartBytes) return value;
88
- const mediaType = value.startsWith("data:") ? dataUrlMediaType(value) : void 0;
89
- const path = extractBlob(state, value, mediaType);
90
- return evictionMarker(value.length, path, mediaType);
91
- }
305
+ /**
306
+ * Evict one stored payload locator. Returns its marker, or `null` when the
307
+ * value is not an evictable payload or is below the size threshold.
308
+ */
309
+ async function evictUrl(state, url, fallbackMediaType) {
310
+ if (typeof url !== "string") return null;
311
+ const payload = resolvePayload(state, url);
312
+ if (!payload) return null;
313
+ const mediaType = payload.mediaType ?? fallbackMediaType;
314
+ const path = await state.options.write(state.index, payload.bytes, mediaType);
315
+ state.index++;
316
+ state.parts++;
317
+ state.bytes += payload.bytes.byteLength;
318
+ return evictionMarker(payload.bytes.byteLength, path, mediaType);
319
+ }
320
+ /**
321
+ * A stored payload is always an inline `data:` URL now, so eviction decodes
322
+ * it directly.
323
+ */
324
+ function resolvePayload(state, url) {
325
+ const { minPartBytes } = state.options;
326
+ if (!url.startsWith("data:")) return null;
327
+ if (url.length < minPartBytes) return null;
328
+ const decoded = decodeDataUrl(url);
329
+ if (!decoded || decoded.bytes.byteLength < minPartBytes) return null;
330
+ return decoded;
331
+ }
332
+ async function walkAndEvict(state, value, depth) {
333
+ if (typeof value === "string") return await evictUrl(state, value) ?? value;
92
334
  if (value === null || typeof value !== "object" || depth >= MAX_WALK_DEPTH) return value;
93
335
  if (Array.isArray(value)) {
94
336
  let changed = false;
95
- const result = value.map((item) => {
96
- const next = walkAndEvict(state, item, depth + 1);
337
+ const result = [];
338
+ for (const item of value) {
339
+ const next = await walkAndEvict(state, item, depth + 1);
97
340
  if (next !== item) changed = true;
98
- return next;
99
- });
341
+ result.push(next);
342
+ }
100
343
  return changed ? result : value;
101
344
  }
102
345
  let changed = false;
103
346
  const result = {};
104
347
  for (const [key, entry] of Object.entries(value)) {
105
- const next = walkAndEvict(state, entry, depth + 1);
348
+ const next = await walkAndEvict(state, entry, depth + 1);
106
349
  if (next !== entry) changed = true;
107
350
  result[key] = next;
108
351
  }
109
352
  return changed ? result : value;
110
353
  }
111
- /** Record an evicted value; returns its workspace path or null when dropped. */
112
- function extractBlob(state, data, mediaType) {
113
- state.parts++;
114
- state.bytes += data.length;
115
- if (!state.options.externalize) return null;
116
- const path = state.options.pathFor(state.blobs.length, extensionFor(mediaType));
117
- state.blobs.push({
118
- path,
119
- data,
120
- mediaType
121
- });
122
- return path;
123
- }
124
- function evictionMarker(bytes, path, mediaType) {
125
- const media = mediaType ? `${mediaType}, ` : "";
126
- return path ? `[evicted ${media}${bytes} bytes; preserved at ${path}]` : `[evicted ${media}${bytes} bytes]`;
354
+ /**
355
+ * Whether a pass over `message` could evict anything: a file part or a tool
356
+ * output holding a `data:` URL at least `minPartBytes` long. Decodes nothing —
357
+ * this is the in-memory gate that decides whether a pass is worth scheduling,
358
+ * so a decoded payload that turns out smaller than the threshold is merely a
359
+ * pass that changes nothing.
360
+ */
361
+ function hasEvictableMedia(message, minPartBytes) {
362
+ const isCandidate = (value) => typeof value === "string" && value.length >= minPartBytes && value.startsWith("data:");
363
+ const walk = (value, depth) => {
364
+ if (isCandidate(value)) return true;
365
+ if (value === null || typeof value !== "object" || depth >= MAX_WALK_DEPTH) return false;
366
+ return (Array.isArray(value) ? value : Object.values(value)).some((entry) => walk(entry, depth + 1));
367
+ };
368
+ for (const part of message.parts) {
369
+ if (part.type === "file" && "url" in part) {
370
+ if (isCandidate(part.url)) return true;
371
+ continue;
372
+ }
373
+ if ((part.type.startsWith("tool-") || part.type === "dynamic-tool") && "output" in part && walk(part.output, 0)) return true;
374
+ }
375
+ return false;
127
376
  }
128
- function dataUrlMediaType(url) {
129
- return /^data:([^;,]+)/.exec(url)?.[1] || void 0;
377
+ /** Decode a `data:` URL into raw bytes. Returns null when it is malformed. */
378
+ function decodeDataUrl(url) {
379
+ const comma = url.indexOf(",");
380
+ if (comma === -1) return null;
381
+ const header = url.slice(5, comma);
382
+ const base64 = /;base64$/i.test(header);
383
+ const mediaType = header.replace(/;base64$/i, "").split(";")[0]?.trim() || void 0;
384
+ const payload = url.slice(comma + 1);
385
+ try {
386
+ if (base64) {
387
+ const binary = atob(payload);
388
+ const bytes = new Uint8Array(binary.length);
389
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
390
+ return mediaType === void 0 ? { bytes } : {
391
+ bytes,
392
+ mediaType
393
+ };
394
+ }
395
+ const bytes = new TextEncoder().encode(decodeURIComponent(payload));
396
+ return mediaType === void 0 ? { bytes } : {
397
+ bytes,
398
+ mediaType
399
+ };
400
+ } catch {
401
+ return null;
402
+ }
130
403
  }
404
+ /** File extension for an evicted payload, derived from its media type. */
131
405
  function extensionFor(mediaType) {
132
406
  if (!mediaType) return "txt";
133
407
  return mediaType.split("/")[1]?.replace(/[^a-zA-Z0-9]/g, "") || "bin";
134
408
  }
409
+ /** Workspace path for the n-th value evicted from a message. */
410
+ function evictedFilePath(messageId, index, mediaType) {
411
+ return `/attachments/evicted/${messageId}-${index}.${extensionFor(mediaType)}`;
412
+ }
135
413
  //#endregion
136
414
  //#region src/channels/index.ts
137
415
  /** Wrap a {@link MessengerDefinition} as a `kind: "messenger"` channel. */
@@ -229,7 +507,8 @@ function resolveChannels(configured, messengers) {
229
507
  * - getSystemPrompt() — return the legacy fallback system prompt
230
508
  * - getTools() — return the ToolSet for the agentic loop
231
509
  * - maxSteps — max tool-call rounds per turn (default: 10)
232
- * - configureSession() — add context blocks, compaction, search, skills
510
+ * - configureSession() — compaction and search policy
511
+ * - configureContext() — declare prompt context blocks
233
512
  *
234
513
  * Lifecycle hooks:
235
514
  * - beforeTurn() — inspect/override context, tools, model before inference
@@ -277,21 +556,23 @@ function resolveChannels(configured, messengers) {
277
556
  * @example With context blocks and self-updating memory
278
557
  * ```typescript
279
558
  * import { Think } from "@cloudflare/think";
280
- * import type { Session } from "@cloudflare/think";
559
+ * import type { ContextConfig } from "agents/context";
281
560
  *
282
561
  * export class MemoryAgent extends Think<Env> {
283
562
  * getModel() { ... }
284
563
  *
285
- * configureSession(session: Session) {
286
- * return session
287
- * .withContext("soul", {
564
+ * configureContext(): ContextConfig[] {
565
+ * return [
566
+ * {
567
+ * label: "soul",
288
568
  * provider: { get: async () => "You are a helpful coding assistant." }
289
- * })
290
- * .withContext("memory", {
569
+ * },
570
+ * {
571
+ * label: "memory",
291
572
  * description: "Important facts learned during conversation.",
292
573
  * maxTokens: 2000
293
- * })
294
- * .withCachedPrompt();
574
+ * }
575
+ * ];
295
576
  * }
296
577
  * }
297
578
  * ```
@@ -304,15 +585,19 @@ const usesAISDKV7Telemetry = "registerTelemetry" in aiSdk;
304
585
  * `truncateOlderMessages`' default `keepRecent` (see `_assembleModelMessages`).
305
586
  *
306
587
  * Both memory bounds are anchored to this window (#1710):
307
- * - budgeted hydration never shrinks `this.messages` below it (the floor
308
- * passed to `session.getRecentHistory`), so windowing cannot starve the
309
- * model's context;
588
+ * - budgeted hydration (`hydrationByteBudget`) is a hard byte ceiling, so a
589
+ * window of unusually large messages can be shorter than this; the model
590
+ * then sees what fits rather than exhausting isolate memory;
310
591
  * - media eviction never rewrites messages inside it (the
311
- * `keepRecentMessages` clamp), so content the model still replays at full
312
- * fidelity is never replaced with markers.
592
+ * `keepRecentMessages` clamp), so the rows the model replays at full
593
+ * fidelity are never stripped.
313
594
  */
314
595
  const MODEL_RECENT_WINDOW = 4;
315
596
  const DEFAULT_ACTION_TIMEOUT_MS = 3e4;
597
+ /** Whether a workspace can receive raw bytes, which skills projection needs. */
598
+ function hasWriteFileBytes(workspace) {
599
+ return typeof workspace.writeFileBytes === "function";
600
+ }
316
601
  const ACTION_OUTPUT_MAX_CHARS = 2e4;
317
602
  const MAX_REPLY_ATTACHMENTS_PER_TURN = 32;
318
603
  const ACTION_LEDGER_SWEEP_INTERVAL_MS = 3600 * 1e3;
@@ -797,14 +1082,75 @@ function isAction(value) {
797
1082
  return typeof value === "object" && value !== null && value[ACTION_BRAND] === true;
798
1083
  }
799
1084
  const admittedTurnContext = new AsyncLocalStorage();
1085
+ const recoveredTurnAcceptanceContext = new AsyncLocalStorage();
800
1086
  const inferenceStreamFinalizers = /* @__PURE__ */ new WeakMap();
801
1087
  const THINK_WORKFLOW_PROMPT_METADATA_KEY = "__thinkWorkflowPrompt";
1088
+ /** Queue callback that delivers one terminal-submission workflow event. */
1089
+ const WORKFLOW_NOTIFICATION_CALLBACK = "_cfDeliverWorkflowNotification";
1090
+ /**
1091
+ * A workflow notification never retries in-process: a failed delivery
1092
+ * schedules its own retry with backoff (see `_cfDeliverWorkflowNotification`)
1093
+ * so the alarm loop is not held while a workflow is unreachable.
1094
+ */
1095
+ const WORKFLOW_NOTIFICATION_RETRY = { maxAttempts: 1 };
1096
+ /** Longest wait between two delivery attempts of one workflow notification. */
1097
+ const WORKFLOW_NOTIFICATION_MAX_BACKOFF_SECONDS = 600;
1098
+ /**
1099
+ * How long delivery of one workflow notification keeps being retried after
1100
+ * its first failure. Long enough to ride out an outage of the workflow
1101
+ * binding; a target still failing after this is treated as permanently
1102
+ * unreachable rather than waking the object every ten minutes forever.
1103
+ */
1104
+ const WORKFLOW_NOTIFICATION_GIVE_UP_MS = 720 * 60 * 1e3;
1105
+ /** Queue callback that runs one connection-less continuation turn. */
1106
+ const CONNECTIONLESS_CONTINUATION_CALLBACK = "_cfRunConnectionlessContinuation";
1107
+ /** Queue callback that runs one media-eviction pass. */
1108
+ const MEDIA_EVICTION_CALLBACK = "_cfEvictAgedMedia";
1109
+ /** Queue callback that runs one pending submission. */
1110
+ const SUBMISSION_RUN_CALLBACK = "_cfRunSubmission";
1111
+ function workflowNotificationItemId(submissionId, eventType) {
1112
+ return `workflow-notification:${submissionId}:${eventType}`;
1113
+ }
1114
+ function submissionRunItemId(submissionId) {
1115
+ return `submission:${submissionId}`;
1116
+ }
802
1117
  /**
803
1118
  * Message-metadata keys that are server-written turn context (stamped by
804
1119
  * `_stampChannel`) and trusted by hooks and recovery. They are stripped from
805
1120
  * client-supplied messages at intake so a client can never forge them.
806
1121
  */
807
1122
  const RESERVED_MESSAGE_METADATA_KEYS = ["channel", "turnMetadata"];
1123
+ const cachedMessageEncoder = new TextEncoder();
1124
+ /**
1125
+ * A cached message's size in the unit the hydration budget is measured in:
1126
+ * UTF-8 bytes of its serialized form, not UTF-16 code units.
1127
+ */
1128
+ function cachedMessageBytes(message) {
1129
+ return cachedMessageEncoder.encode(JSON.stringify(message)).byteLength;
1130
+ }
1131
+ /**
1132
+ * The stored form of a client-sourced message's metadata: Sessions drops the
1133
+ * reserved keys on every client write, so a compare against a stored row has
1134
+ * to drop them too. Mirrors `SessionCore.stripReservedMetadata` for the keys
1135
+ * Think registers.
1136
+ */
1137
+ function stripReservedMetadata(message) {
1138
+ const metadata = message.metadata;
1139
+ if (typeof metadata !== "object" || metadata === null || Array.isArray(metadata)) return message;
1140
+ const remaining = { ...metadata };
1141
+ let changed = false;
1142
+ for (const key of RESERVED_MESSAGE_METADATA_KEYS) if (key in remaining) {
1143
+ delete remaining[key];
1144
+ changed = true;
1145
+ }
1146
+ if (!changed) return message;
1147
+ if (Object.keys(remaining).length > 0) return {
1148
+ ...message,
1149
+ metadata: remaining
1150
+ };
1151
+ const { metadata: _dropped, ...withoutMetadata } = message;
1152
+ return withoutMetadata;
1153
+ }
808
1154
  /** Stable id prefix for fallback notes that preserve orphaned execution outcomes. */
809
1155
  const EXECUTION_OUTCOME_MESSAGE_PREFIX = "exec-outcome-";
810
1156
  /**
@@ -909,9 +1255,27 @@ function defaultContextOverflowClassifier(error) {
909
1255
  }
910
1256
  return CONTEXT_OVERFLOW_PATTERN.test(text) ? "context_overflow" : void 0;
911
1257
  }
1258
+ /**
1259
+ * Definition name for messenger reply runs on the Tasks capability. The
1260
+ * reserved prefix keeps it outside the public `fibers.run()` surface; the
1261
+ * recovery context still carries the historical `MESSENGER_REPLY_FIBER_NAME`
1262
+ * so the messenger runtime's recovery gate is unchanged.
1263
+ */
1264
+ const MESSENGER_REPLY_TASK_DEFINITION = "__cf_internal_messenger_reply";
1265
+ var _contextBlocks = /* @__PURE__ */ new WeakMap();
1266
+ var _Think_brand = /* @__PURE__ */ new WeakSet();
912
1267
  var _configCache = /* @__PURE__ */ new WeakMap();
913
1268
  var _configTableReady = /* @__PURE__ */ new WeakMap();
1269
+ var _configMemo = /* @__PURE__ */ new WeakMap();
1270
+ var _agentToolChildRunTableReady = /* @__PURE__ */ new WeakMap();
914
1271
  var Think = class Think extends Agent {
1272
+ /**
1273
+ * The agent's context blocks. Available once the Lifecycle has started.
1274
+ */
1275
+ get context() {
1276
+ if (!_classPrivateFieldGet2(_contextBlocks, this)) throw new Error("Context is not initialized yet; it is available after onStart().");
1277
+ return _classPrivateFieldGet2(_contextBlocks, this);
1278
+ }
915
1279
  /**
916
1280
  * Internal onStart steps that failed on this wake and were skipped so the
917
1281
  * agent could still come up (see {@link OnStartDegradation}). Empty when
@@ -923,30 +1287,38 @@ var Think = class Think extends Agent {
923
1287
  }
924
1288
  constructor(ctx, env) {
925
1289
  super(ctx, env);
1290
+ _classPrivateMethodInitSpec(this, _Think_brand);
926
1291
  this.includeMcpTools = true;
927
1292
  this.waitForMcpConnections = false;
928
1293
  this.storeMessages = false;
929
1294
  this.storeTools = false;
1295
+ this.skillWorkspace = false;
930
1296
  this._skillRegistry = null;
931
1297
  this._loggedSkillWarnings = /* @__PURE__ */ new Set();
932
1298
  this._loggedProtocolWarnings = /* @__PURE__ */ new Set();
933
1299
  this.messageConcurrency = "queue";
934
- this.hydrationByteBudget = 24 * 1024 * 1024;
1300
+ this.hydrationByteBudget = 32 * 1024 * 1024;
935
1301
  this.mediaEviction = true;
936
1302
  this.chatRecovery = true;
1303
+ this.sessions = new Sessions({ reservedMetadataKeys: RESERVED_MESSAGE_METADATA_KEYS });
1304
+ _classPrivateFieldInitSpec(this, _contextBlocks, void 0);
937
1305
  this._cachedMessages = [];
938
1306
  this._onStartDegradations = [];
939
1307
  this.workspaceBash = true;
940
1308
  this.fetchTools = false;
941
1309
  this._mediaEvictionRunning = false;
942
- this._mediaEvictionScheduled = false;
943
- this._mediaEvictionObservedOversized = false;
1310
+ this._mediaEvictionPending = false;
1311
+ this._mediaEvictionAppendsDuringPass = 0;
944
1312
  this._warnedEvictionUnsupported = false;
1313
+ this._mediaEvictionFruitless = null;
945
1314
  this._lastHydration = null;
946
1315
  this._warnedHydrationWindowed = false;
1316
+ this._cacheCoversActivePath = false;
1317
+ this._cachedBytesSinceSync = 0;
947
1318
  this._lastWindowedEmit = null;
948
1319
  this._aborts = new AbortRegistry();
949
1320
  this._turnQueue = new TurnQueue();
1321
+ this.streams = createChatStreams();
950
1322
  this._pendingResumeConnections = /* @__PURE__ */ new Set();
951
1323
  this._resumeHandshakeInstance = null;
952
1324
  this._continuation = new ContinuationState();
@@ -975,16 +1347,15 @@ var Think = class Think extends Agent {
975
1347
  this._agentToolLiveSequences = /* @__PURE__ */ new Map();
976
1348
  this._agentToolRunsByRequestId = /* @__PURE__ */ new Map();
977
1349
  this._submissionTableEnsured = false;
978
- this._workflowNotificationTableEnsured = false;
979
1350
  this._declaredScheduledTasksTableEnsured = false;
980
1351
  this._actionLedgerTableEnsured = false;
981
1352
  this._actionPendingTableEnsured = false;
982
- this._drainingSubmissions = false;
983
- this._drainingWorkflowNotifications = false;
984
1353
  this._submissionAbortControllers = /* @__PURE__ */ new Map();
985
1354
  this._programmaticStreamErrors = /* @__PURE__ */ new Map();
986
1355
  _classPrivateFieldInitSpec(this, _configCache, null);
987
1356
  _classPrivateFieldInitSpec(this, _configTableReady, false);
1357
+ _classPrivateFieldInitSpec(this, _configMemo, /* @__PURE__ */ new Map());
1358
+ this._liveChatTurnClosures = /* @__PURE__ */ new Map();
988
1359
  this.maxSteps = 10;
989
1360
  this.actionLedgerRetention = {
990
1361
  settledMs: 720 * 60 * 60 * 1e3,
@@ -1006,9 +1377,16 @@ var Think = class Think extends Agent {
1006
1377
  this._proactiveCompactionsThisRun = 0;
1007
1378
  this._warnedMissingClassifier = false;
1008
1379
  this.hookTimeout = 5e3;
1380
+ _classPrivateFieldInitSpec(this, _agentToolChildRunTableReady, false);
1009
1381
  this._agentToolProgressEmitterInstance = null;
1010
- this._streamProgressCredit = new StreamProgressCreditThrottle();
1382
+ this._persistedRequestContext = {};
1383
+ this._progressSeed = null;
1011
1384
  this._agentToolStreamProgress = new AgentToolStreamProgressThrottle();
1385
+ this.lifecycle.use(this.sessions);
1386
+ this.lifecycle.use(this.streams);
1387
+ this._registerChatTurnTaskDefinition();
1388
+ this._registerChatRecoveryTaskDefinition();
1389
+ this._registerMessengerReplyTaskDefinition();
1012
1390
  const _onStart = this.onStart.bind(this);
1013
1391
  const startThink = async (props, update) => {
1014
1392
  await withAgentSpan(this, "initialize_think_session", "startup", { "cloudflare.agents.component": "think" }, async () => {
@@ -1016,24 +1394,42 @@ var Think = class Think extends Agent {
1016
1394
  sql: this.ctx.storage.sql,
1017
1395
  name: () => this.name
1018
1396
  });
1019
- const baseSession = Session$1.create(this);
1020
- this.session = await this.configureSession(baseSession);
1021
- this.session.internal_onMessagesChanged(async (event) => {
1397
+ this.session = await this.configureSession(new ThinkSession(this.sessions.session(), () => this.context));
1398
+ _classPrivateFieldSet2(_contextBlocks, this, new ContextBlocks([...await this.configureContext(), ...this.session.internal_takePendingContext()], this.session.internal_promptStore() ?? _assertClassBrand(_Think_brand, this, _contextProvider).call(this, "_system_prompt"), (label) => _assertClassBrand(_Think_brand, this, _contextProvider).call(this, label)));
1399
+ await _classPrivateFieldGet2(_contextBlocks, this).load();
1400
+ this._unsubscribeSessionChanges?.();
1401
+ this._unsubscribeSessionChanges = this.sessions.subscribe(async (event) => {
1402
+ if (event.sessionId !== this.session.sessionId) return;
1022
1403
  switch (event.type) {
1023
1404
  case "append":
1024
1405
  if (!event.inserted || event.parentId !== void 0) await this._syncMessages();
1025
- else this._upsertCachedMessage(event.message);
1026
- this._scheduleMediaEvictionAfterAppend(event.message);
1406
+ else {
1407
+ this._upsertCachedMessage(event.message);
1408
+ this._noteCachedGrowth(cachedMessageBytes(event.message));
1409
+ if (this._mediaEvictionFruitless) this._mediaEvictionFruitless.appendsSince++;
1410
+ if (this._mediaEvictionRunning) this._mediaEvictionAppendsDuringPass++;
1411
+ this._scheduleMediaEvictionPass();
1412
+ }
1413
+ break;
1414
+ case "import":
1415
+ this._cacheCoversActivePath = false;
1416
+ break;
1417
+ case "compaction":
1418
+ await this._syncMessages();
1027
1419
  break;
1028
1420
  case "update":
1029
- this._patchCachedMessage(event.message);
1421
+ if (this._cachedMessages.some((message) => message.id === event.message.id)) this._patchCachedMessage(event.message);
1030
1422
  break;
1031
1423
  case "clear":
1032
1424
  this._replaceCachedMessages([]);
1425
+ this._cacheCoversActivePath = true;
1033
1426
  break;
1034
1427
  case "delete":
1428
+ await this._syncMessages();
1429
+ break;
1035
1430
  case "compact":
1036
1431
  await this._syncMessages();
1432
+ await _classPrivateFieldGet2(_contextBlocks, this)?.refreshSystemPrompt();
1037
1433
  break;
1038
1434
  }
1039
1435
  });
@@ -1042,11 +1438,12 @@ var Think = class Think extends Agent {
1042
1438
  this._onStartDegradations = [];
1043
1439
  await withAgentSpan(this, "hydrate_think_session", "startup", { "cloudflare.agents.component": "think" }, async () => {
1044
1440
  if (!await this._runBestEffortOnStartStep("transcript-hydration", () => this._syncMessages(), "The agent is starting with an empty in-memory message view; persisted history is untouched. If the error is SQLITE_NOMEM, the stored transcript is too large to hydrate (often inline base64 media in tool results) — compact or clear the session to recover.")) this._replaceCachedMessages([]);
1045
- this._refreshMediaEvictionSignalFromCache();
1046
1441
  });
1047
1442
  if (this.extensionLoader) await withAgentSpan(this, "initialize_think_extensions", "startup", { "cloudflare.agents.component": "think" }, () => this._initializeExtensions());
1048
1443
  await withAgentSpan(this, "initialize_think_chat", "startup", { "cloudflare.agents.component": "think" }, async () => {
1049
- this._resumableStream = new ResumableStream(this.sql.bind(this));
1444
+ this._resumableStream = new ResumableStream(this.streams, this.sql.bind(this), { onProgress: (durable) => {
1445
+ this.ctx.storage.put(CHAT_RECOVERY_PROGRESS_KEY, durable).catch(() => {});
1446
+ } });
1050
1447
  this._restoreClientTools();
1051
1448
  this._restoreBody();
1052
1449
  this._setupProtocolHandlers();
@@ -1057,12 +1454,9 @@ var Think = class Think extends Agent {
1057
1454
  await withAgentSpan(this, "recover_think_durable_work", "startup", { "cloudflare.agents.component": "think" }, () => this._runBestEffortOnStartStep("durable-work-recovery", async () => {
1058
1455
  await this._sweepActionLedger();
1059
1456
  await this._sweepActionPendingApprovals();
1457
+ await this._migrateLegacyWorkflowNotifications();
1060
1458
  await this._recoverSubmissionsOnStart();
1061
- this._recoverWorkflowNotifications();
1062
- if (this._hasPendingSubmissions()) await this._scheduleSubmissionDrain();
1063
- if (this._hasPendingWorkflowNotifications()) this._startWorkflowNotificationDrain();
1064
1459
  }, "Pending submissions / workflow notifications were not recovered on this wake; the next successful wake will recover them."));
1065
- if (this._lastHydration?.truncated) this._scheduleMediaEvictionPass({ force: true });
1066
1460
  update({
1067
1461
  "cloudflare.agents.hydration.messages": this._lastHydration?.hydratedMessages,
1068
1462
  "cloudflare.agents.hydration.content_bytes": this._lastHydration?.totalContentBytes,
@@ -1092,11 +1486,12 @@ var Think = class Think extends Agent {
1092
1486
  *
1093
1487
  * Intentionally UNBUDGETED — unlike the cache refresh in `_syncMessages`,
1094
1488
  * which routes through `session.getRecentHistory(hydrationByteBudget)`, this
1095
- * returns the full active path. Callers (message reconciliation, tool-update
1096
- * application) must see every message: reconciliation diffs incoming client
1097
- * messages against the complete server transcript, and a tool result can
1098
- * target any message on the path, so a windowed read would drop rows and
1099
- * corrupt the result.
1489
+ * returns the full active path. Its caller, message reconciliation, must see
1490
+ * every message: it diffs incoming client messages against the complete
1491
+ * server transcript, so a windowed read would drop rows and corrupt the
1492
+ * result. It is reached only when the live cache does not already cover the
1493
+ * path (`_serverTranscriptForReconcile`); tool-update application resolves
1494
+ * its one target row without it (`_resolveToolCallOwner`).
1100
1495
  *
1101
1496
  * These full reads are not the unbounded boot-time hydration that bricked the
1102
1497
  * DO in #1710: they run during a live turn (never in `onStart`), so an
@@ -1183,7 +1578,7 @@ var Think = class Think extends Agent {
1183
1578
  if (repair.removedToolCalls === 0 && repair.normalizedInputs === 0) return messages;
1184
1579
  for (const message of repair.messages) {
1185
1580
  const original = messages.find((candidate) => candidate.id === message.id);
1186
- if (original && original.parts !== message.parts) await this.session.updateMessage(sanitizeMessage(message));
1581
+ if (original && original.parts !== message.parts) await this.session.updateMessage(message);
1187
1582
  }
1188
1583
  this._replaceCachedMessages(repair.messages);
1189
1584
  this._broadcastMessages();
@@ -1226,121 +1621,139 @@ var Think = class Think extends Agent {
1226
1621
  }
1227
1622
  }
1228
1623
  /**
1229
- * Schedule a background media-eviction pass (see `mediaEviction`).
1230
- * Coalesces repeated requests; the timer fires after the current
1231
- * event-loop work (and after `onStart`'s `blockConcurrencyWhile`), so
1232
- * boot and turn latency are unaffected.
1624
+ * Whether the cache can stand in for the stored path when deciding if an
1625
+ * eviction pass is worth running. It cannot when the hydration is a window
1626
+ * of the path, or when a compaction overlay collapses rows the pass would
1627
+ * still read and rewrite.
1233
1628
  */
1234
- _scheduleMediaEvictionPass(options) {
1235
- if (this._mediaEvictionScheduled || this._mediaEvictionRunning) return;
1236
- if (!resolveMediaEvictionConfig(this.mediaEviction)) return;
1237
- if (!options?.force && !this._mediaEvictionObservedOversized) return;
1238
- this._mediaEvictionScheduled = true;
1239
- setTimeout(() => {
1240
- this._mediaEvictionScheduled = false;
1241
- this._evictAgedMediaBestEffort();
1242
- }, 0);
1629
+ _agedRowsHiddenFromCache() {
1630
+ return this._lastHydration?.truncated === true || this._cachedMessages.some((message) => isCompactionMessage(message));
1243
1631
  }
1244
- _scheduleMediaEvictionAfterAppend(message) {
1632
+ /**
1633
+ * Queue a bounded media-eviction pass (see `mediaEviction`).
1634
+ *
1635
+ * The pass is one queue item with a stable id, so repeated requests
1636
+ * coalesce and the pass runs from the alarm loop, never inside the
1637
+ * request or the `blockConcurrencyWhile` cache refresh that asked for it.
1638
+ * A request that lands while a pass is running is re-evaluated once the
1639
+ * pass ends, so media aged by an append during the pass is not left until
1640
+ * the next one. `_evictAgedMediaBestEffort` swallows its own failures, so
1641
+ * a bad pass can never brick the object.
1642
+ */
1643
+ _scheduleMediaEvictionPass() {
1644
+ if (this._mediaEvictionRunning) {
1645
+ this._mediaEvictionPending = true;
1646
+ return;
1647
+ }
1245
1648
  const config = resolveMediaEvictionConfig(this.mediaEviction);
1246
1649
  if (!config) return;
1247
- if (!this._mediaEvictionObservedOversized) this._mediaEvictionObservedOversized = this._messageMayNeedMediaEviction(message, config);
1248
- if (!this._mediaEvictionObservedOversized) return;
1249
1650
  const keepRecent = Math.max(config.keepRecentMessages, MODEL_RECENT_WINDOW);
1250
- if (this._cachedMessages.length > keepRecent) this._scheduleMediaEvictionPass({ force: true });
1251
- }
1252
- _refreshMediaEvictionSignalFromCache() {
1253
- const config = resolveMediaEvictionConfig(this.mediaEviction);
1254
- if (!config) {
1255
- this._mediaEvictionObservedOversized = false;
1256
- return;
1257
- }
1258
- this._mediaEvictionObservedOversized = this._cachedMessages.some((message) => this._messageMayNeedMediaEviction(message, config));
1651
+ if (this._agedRowsHiddenFromCache()) {
1652
+ const fruitless = this._mediaEvictionFruitless;
1653
+ if (fruitless !== null && this._lastHydration !== null && fruitless.storedBytes === this._lastHydration.totalContentBytes && fruitless.appendsSince < keepRecent) return;
1654
+ } else if (!this._cachedMessages.slice(0, Math.max(0, this._cachedMessages.length - keepRecent)).some((message) => hasEvictableMedia(message, config.minPartBytes))) return;
1655
+ this.queue(MEDIA_EVICTION_CALLBACK, void 0, { id: "media-eviction" }).catch((error) => {
1656
+ console.error("[Think] Failed to queue media eviction pass", error);
1657
+ });
1259
1658
  }
1260
- _messageMayNeedMediaEviction(message, config) {
1261
- return JSON.stringify(message).length >= config.minPartBytes;
1659
+ /**
1660
+ * Run one media-eviction pass.
1661
+ * @internal Queue callback.
1662
+ */
1663
+ async _cfEvictAgedMedia() {
1664
+ await this._evictAgedMediaBestEffort();
1262
1665
  }
1263
1666
  /**
1264
- * Evict oversized inline media from aged stored messages (#1710).
1667
+ * Remove aged media from the conversation, leaving a Workspace pointer the
1668
+ * agent can read back.
1265
1669
  *
1266
- * Memory-bounded by design: row sizes come from `getHistoryRowStats()`
1267
- * (no content loaded), only rows large enough to contain an evictable
1268
- * part are parsed, and they are processed one at a time via
1269
- * `session.internal_rewriteMessage` — the maintenance write path that
1270
- * skips the full-history token-estimate broadcast a public
1271
- * `updateMessage` performs per row. Evicted values are written to the
1272
- * workspace BEFORE the row is rewritten, so a failed pass never loses
1273
- * data. Best-effort: failures are logged and the next pass retries.
1670
+ * Memory-bounded by design: candidate sizes come from `getHistoryRowStats()`
1671
+ * (no content loaded), only rows big enough to hold an evictable payload are
1672
+ * read, and they are processed one at a time. Bytes are written to the
1673
+ * Workspace BEFORE the row is rewritten, so a failed pass never loses data;
1674
+ * once the rewritten row is stored, its Sessions attachment reference is
1675
+ * gone and the blob is reaped, so the bytes live in exactly one place.
1274
1676
  *
1275
1677
  * The aged cutoff is `keepRecentMessages` clamped to at least
1276
- * `MODEL_RECENT_WINDOW`: messages the model still replays at full
1277
- * fidelity each turn are never rewritten, regardless of configuration.
1278
- *
1279
- * When a pass stops at `maxRowsPerPass` with eligible rows remaining,
1280
- * another pass is scheduled automatically so a large backlog drains
1281
- * without waiting for new appends. Termination is guaranteed: every
1282
- * rewritten row drops below `minPartBytes` and is skipped by later
1283
- * passes, so the eligible set strictly shrinks.
1678
+ * `MODEL_RECENT_WINDOW`: messages the model still replays at full fidelity
1679
+ * are never rewritten, whatever the configuration says.
1284
1680
  *
1285
- * Returns the pass totals, or `null` when eviction is disabled, already
1286
- * running, or the provider cannot enumerate row sizes (warned once).
1681
+ * Best-effort: failures are logged and the next pass retries. When a pass
1682
+ * stops at `maxRowsPerPass` having made progress, the next one is scheduled
1683
+ * so a backlog drains on its own; a pass that changed nothing does not
1684
+ * reschedule, which is what guarantees termination.
1287
1685
  */
1288
1686
  async _evictAgedMediaBestEffort() {
1289
1687
  if (this._mediaEvictionRunning) return null;
1290
1688
  const config = resolveMediaEvictionConfig(this.mediaEviction);
1291
1689
  if (!config) return null;
1292
1690
  this._mediaEvictionRunning = true;
1293
- let backlogRemains = false;
1691
+ this._mediaEvictionAppendsDuringPass = 0;
1692
+ const totals = {
1693
+ messages: 0,
1694
+ parts: 0,
1695
+ bytes: 0,
1696
+ backlogRemains: false
1697
+ };
1294
1698
  try {
1295
- const stats = await this.session.getHistoryRowStats();
1296
- if (!stats) {
1699
+ const writeFileBytes = this.workspace.writeFileBytes?.bind(this.workspace);
1700
+ if (!writeFileBytes) {
1297
1701
  if (!this._warnedEvictionUnsupported) {
1298
1702
  this._warnedEvictionUnsupported = true;
1299
- console.warn("[Think] mediaEviction is enabled but the configured SessionProvider does not implement getHistoryRowStats; media eviction is a no-op for this agent.");
1703
+ console.warn("[Think] mediaEviction is enabled but the configured workspace does not implement writeFileBytes; media eviction is a no-op for this agent.");
1300
1704
  }
1301
1705
  return null;
1302
1706
  }
1707
+ const stats = await this.session.getHistoryRowStats();
1303
1708
  const keepRecent = Math.max(config.keepRecentMessages, MODEL_RECENT_WINDOW);
1304
1709
  const aged = stats.slice(0, Math.max(0, stats.length - keepRecent));
1305
1710
  let processed = 0;
1306
- const totals = {
1307
- messages: 0,
1308
- parts: 0,
1309
- bytes: 0,
1310
- externalizedBytes: 0
1311
- };
1312
1711
  for (const row of aged) {
1313
1712
  if (row.bytes < config.minPartBytes) continue;
1314
1713
  if (processed >= config.maxRowsPerPass) {
1315
- backlogRemains = true;
1714
+ totals.backlogRemains = true;
1316
1715
  break;
1317
1716
  }
1318
1717
  processed++;
1319
1718
  const message = await this.session.getMessage(row.id);
1320
1719
  if (!message) continue;
1321
- const result = evictLargeMediaFromMessage(message, {
1720
+ const result = await evictMediaFromMessage(message, {
1322
1721
  minPartBytes: config.minPartBytes,
1323
- externalize: config.externalizeToWorkspace,
1324
- pathFor: (index, extension) => `/attachments/evicted/${message.id}-${index}.${extension}`
1722
+ write: async (index, bytes, mediaType) => {
1723
+ const path = evictedFilePath(message.id, index, mediaType);
1724
+ await writeFileBytes(path, bytes, mediaType ?? "application/octet-stream");
1725
+ return path;
1726
+ }
1325
1727
  });
1326
1728
  if (!result.changed) continue;
1327
- for (const blob of result.blobs) {
1328
- await this.workspace.writeFile(blob.path, blob.data);
1329
- totals.externalizedBytes += blob.data.length;
1330
- }
1331
- await this.session.internal_rewriteMessage(sanitizeMessage(result.message));
1729
+ await this._updateMessageInHistory(result.message);
1332
1730
  totals.messages++;
1333
1731
  totals.parts += result.parts;
1334
1732
  totals.bytes += result.bytes;
1335
1733
  }
1336
- if (totals.messages > 0) this._emit("chat:media:evicted", totals);
1734
+ if (totals.messages > 0) {
1735
+ this._mediaEvictionFruitless = null;
1736
+ this._emit("chat:media:evicted", {
1737
+ messages: totals.messages,
1738
+ parts: totals.parts,
1739
+ bytes: totals.bytes,
1740
+ externalizedBytes: totals.bytes
1741
+ });
1742
+ } else if (this._agedRowsHiddenFromCache() && this._lastHydration) this._mediaEvictionFruitless = {
1743
+ storedBytes: this._lastHydration.totalContentBytes,
1744
+ appendsSince: this._mediaEvictionAppendsDuringPass
1745
+ };
1337
1746
  return totals;
1338
1747
  } catch (error) {
1339
1748
  console.error("[Think] media eviction pass failed; a later pass will retry.", error);
1340
1749
  return null;
1341
1750
  } finally {
1342
1751
  this._mediaEvictionRunning = false;
1343
- if (backlogRemains) this._scheduleMediaEvictionPass({ force: true });
1752
+ if (totals.backlogRemains && totals.messages > 0) this._scheduleMediaEvictionPass();
1753
+ if (this._mediaEvictionPending) {
1754
+ this._mediaEvictionPending = false;
1755
+ this._scheduleMediaEvictionPass();
1756
+ }
1344
1757
  }
1345
1758
  }
1346
1759
  /** Replace the live cache with a durable storage snapshot. */
@@ -1348,23 +1761,35 @@ var Think = class Think extends Agent {
1348
1761
  this._cachedMessages = messages;
1349
1762
  return this._cachedMessages;
1350
1763
  }
1764
+ _noteCachedGrowth(bytes) {
1765
+ const budget = this.hydrationByteBudget;
1766
+ if (bytes <= 0 || !Number.isFinite(budget) || budget <= 0 || !this._lastHydration) return;
1767
+ this._cachedBytesSinceSync += bytes;
1768
+ if (this._lastHydration.totalContentBytes + this._cachedBytesSinceSync > budget) this._cacheCoversActivePath = false;
1769
+ }
1351
1770
  /**
1352
1771
  * Refresh the live cache from durable storage at a safe boundary.
1353
1772
  *
1354
1773
  * Bounded by `hydrationByteBudget`: oversized transcripts hydrate as a
1355
1774
  * recent window instead of exhausting the isolate's memory (#1710). The
1356
- * window never shrinks below `MODEL_RECENT_WINDOW` messages, so budgeted
1357
- * hydration cannot starve the model-facing context assembly (which keeps
1358
- * that many recent messages at full fidelity).
1775
+ * budget is a hard ceiling with no message-count floor beneath it — a floor
1776
+ * that admitted rows regardless of size would defeat the bound it sits
1777
+ * under. A window of unusually large messages can therefore be shorter than
1778
+ * `MODEL_RECENT_WINDOW`; `getHistory()` still reads the full path.
1359
1779
  */
1360
1780
  async _syncMessages() {
1781
+ this._cacheCoversActivePath = false;
1782
+ this._cachedBytesSinceSync = 0;
1361
1783
  const budget = this.hydrationByteBudget;
1362
1784
  if (!Number.isFinite(budget) || budget <= 0) {
1363
1785
  this._lastHydration = null;
1364
1786
  this._lastWindowedEmit = null;
1365
- return this._replaceCachedMessages(await this._readMessagesFromStorage());
1787
+ const full = this._replaceCachedMessages(await this._readMessagesFromStorage());
1788
+ this._cacheCoversActivePath = true;
1789
+ this._scheduleMediaEvictionPass();
1790
+ return full;
1366
1791
  }
1367
- const recent = await this.session.getRecentHistory(budget, MODEL_RECENT_WINDOW);
1792
+ const recent = await this.session.getRecentHistory(budget);
1368
1793
  this._lastHydration = {
1369
1794
  truncated: recent.truncated,
1370
1795
  totalContentBytes: recent.totalContentBytes,
@@ -1387,7 +1812,10 @@ var Think = class Think extends Agent {
1387
1812
  });
1388
1813
  }
1389
1814
  } else this._lastWindowedEmit = null;
1390
- return this._replaceCachedMessages(recent.messages);
1815
+ const hydrated = this._replaceCachedMessages(recent.messages);
1816
+ this._cacheCoversActivePath = !recent.truncated;
1817
+ this._scheduleMediaEvictionPass();
1818
+ return hydrated;
1391
1819
  }
1392
1820
  /** Patch or append one message in the live cache after a durable write. */
1393
1821
  _upsertCachedMessage(message) {
@@ -1395,49 +1823,50 @@ var Think = class Think extends Agent {
1395
1823
  if (index === -1) this._cachedMessages.push(message);
1396
1824
  else this._cachedMessages[index] = message;
1397
1825
  }
1398
- /** Patch a message that is already present in the live cache. */
1826
+ /**
1827
+ * Patch a message that is already present in the live cache. An update
1828
+ * that enlarges the message (a tool result landing on it) grows the cache
1829
+ * exactly as an append does, so it is charged against the hydration
1830
+ * budget the same way; and it may have put an inline payload on an aged
1831
+ * row, so a fruitless eviction pass no longer stands.
1832
+ */
1399
1833
  _patchCachedMessage(message) {
1400
1834
  const index = this._cachedMessages.findIndex((m) => m.id === message.id);
1401
- if (index !== -1) this._cachedMessages[index] = message;
1402
- }
1403
- /** Sanitize + row-size-compact a message before it touches storage. */
1404
- _rowSafe(message) {
1405
- return enforceRowSizeLimit(sanitizeMessage(message), { warn: (m) => console.warn(`[Think] ${m}`) });
1835
+ if (index === -1) return;
1836
+ const grew = cachedMessageBytes(message) - cachedMessageBytes(this._cachedMessages[index]);
1837
+ this._cachedMessages[index] = message;
1838
+ if (grew > 0) {
1839
+ this._noteCachedGrowth(grew);
1840
+ this._mediaEvictionFruitless = null;
1841
+ }
1406
1842
  }
1407
1843
  async _appendMessageToHistory(message, parentId) {
1408
- const safe = this._rowSafe(message);
1409
- await this.session.appendMessage(safe, parentId);
1410
- return safe;
1844
+ return (await this.session.appendMessage(message, { parentId })).message;
1411
1845
  }
1412
1846
  async _updateMessageInHistory(message) {
1413
- const safe = this._rowSafe(message);
1414
- await this.session.updateMessage(safe);
1415
- return safe;
1416
- }
1417
- async _upsertMessageInHistory(message, parentId) {
1418
- const safe = this._rowSafe(message);
1419
- if (await this.session.getMessage(safe.id)) await this.session.updateMessage(safe);
1420
- else await this.session.appendMessage(safe, parentId);
1421
- return safe;
1422
- }
1423
- /**
1424
- * The orphan-persist store adapter — orphan-persist steps **(c)/(d)** route
1425
- * their write through this shared `OrphanPersistStore` seam (the
1426
- * `SessionProvider` write-subset). Delegates to `this.session` with `_rowSafe`
1427
- * applied at the write boundary (sanitize + row-size cap), exactly as Think's
1428
- * other Session call sites do. The `SessionMessage → UIMessage` read cast is
1429
- * confined here, matching those call sites.
1430
- * @internal
1431
- */
1847
+ return await this.session.updateMessage(message) ?? message;
1848
+ }
1849
+ async _upsertMessageInHistory(message, parentId, source = "server") {
1850
+ return (await this.session.upsertMessage(message, {
1851
+ parentId,
1852
+ source
1853
+ })).message;
1854
+ }
1855
+ /** Session-backed orphan persistence with Think's default branch. */
1432
1856
  _orphanStore() {
1433
1857
  return {
1434
1858
  getMessage: async (id) => await this.session.getMessage(id),
1435
- appendMessage: (message, parentId) => this.session.appendMessage(this._rowSafe(message), parentId),
1436
- updateMessage: (message) => this.session.updateMessage(this._rowSafe(message))
1859
+ appendMessage: async (message, parentId) => {
1860
+ await this.session.appendMessage(message, { parentId });
1861
+ },
1862
+ updateMessage: async (message) => {
1863
+ await this.session.updateMessage(message);
1864
+ }
1437
1865
  };
1438
1866
  }
1439
1867
  async _clearHistory() {
1440
1868
  await this.session.clearMessages();
1869
+ await _classPrivateFieldGet2(_contextBlocks, this)?.refreshSystemPrompt();
1441
1870
  await this._clearChatTerminal();
1442
1871
  }
1443
1872
  /** Append a message while keeping Think's live message cache coherent. */
@@ -1530,10 +1959,6 @@ var Think = class Think extends Agent {
1530
1959
  WHERE run_id = ${runId}
1531
1960
  `;
1532
1961
  }
1533
- async alarm() {
1534
- await super.alarm();
1535
- this._startWorkflowNotificationDrain();
1536
- }
1537
1962
  /**
1538
1963
  * Persist an arbitrary JSON-serializable configuration object for this
1539
1964
  * agent instance. Stored in the Think-private `think_config` table —
@@ -1572,19 +1997,25 @@ var Think = class Think extends Agent {
1572
1997
  return null;
1573
1998
  }
1574
1999
  _migrateLegacyConfigToThinkTable() {
1575
- const rows = this.ctx.storage.sql.exec("SELECT sql FROM sqlite_master WHERE type='table' AND name='assistant_config'").toArray();
1576
- if (rows.length === 0) return;
1577
- if (!String(rows[0].sql ?? "").includes("session_id")) return;
2000
+ const legacy = this.ctx.storage.sql.exec(`SELECT name FROM sqlite_master
2001
+ WHERE type = 'table'
2002
+ AND name IN ('assistant_config', 'assistant_config__lifted_v1')`).toArray().map((row) => String(row.name));
2003
+ const source = legacy.includes("assistant_config") ? "assistant_config" : legacy.includes("assistant_config__lifted_v1") ? "assistant_config__lifted_v1" : null;
2004
+ if (!source) return;
1578
2005
  for (const key of Think.CONFIG_KEYS) {
1579
- const value = this.sql`
1580
- SELECT value FROM assistant_config
1581
- WHERE session_id = '' AND key = ${key}
1582
- `[0]?.value;
2006
+ const value = (source === "assistant_config" ? this.sql`
2007
+ SELECT value FROM assistant_config
2008
+ WHERE session_id = '' AND key = ${key}
2009
+ ` : this.sql`
2010
+ SELECT value FROM assistant_config__lifted_v1
2011
+ WHERE session_id = '' AND key = ${key}
2012
+ `)[0]?.value;
1583
2013
  if (value !== void 0) this.sql`
1584
2014
  INSERT OR IGNORE INTO think_config (key, value)
1585
2015
  VALUES (${key}, ${value})
1586
2016
  `;
1587
2017
  }
2018
+ this.ctx.storage.sql.exec(`DROP TABLE ${source}`);
1588
2019
  }
1589
2020
  _ensureConfigTable() {
1590
2021
  if (_classPrivateFieldGet2(_configTableReady, this)) return;
@@ -1600,24 +2031,30 @@ var Think = class Think extends Agent {
1600
2031
  }
1601
2032
  _configSet(key, value) {
1602
2033
  this._ensureConfigTable();
2034
+ if (_classPrivateFieldGet2(_configMemo, this).get(key) === value) return;
1603
2035
  this.sql`
1604
2036
  INSERT OR REPLACE INTO think_config (key, value)
1605
2037
  VALUES (${key}, ${value})
1606
2038
  `;
2039
+ _classPrivateFieldGet2(_configMemo, this).set(key, value);
1607
2040
  }
1608
2041
  _configGet(key) {
1609
2042
  this._ensureConfigTable();
1610
- return this.sql`
2043
+ const value = this.sql`
1611
2044
  SELECT value FROM think_config
1612
2045
  WHERE key = ${key}
1613
2046
  `[0]?.value;
2047
+ _classPrivateFieldGet2(_configMemo, this).set(key, value);
2048
+ return value;
1614
2049
  }
1615
2050
  _configDelete(key) {
1616
2051
  this._ensureConfigTable();
2052
+ if (_classPrivateFieldGet2(_configMemo, this).has(key) && _classPrivateFieldGet2(_configMemo, this).get(key) === void 0) return;
1617
2053
  this.sql`
1618
2054
  DELETE FROM think_config
1619
2055
  WHERE key = ${key}
1620
2056
  `;
2057
+ _classPrivateFieldGet2(_configMemo, this).set(key, void 0);
1621
2058
  }
1622
2059
  /**
1623
2060
  * Return the model to use for inference. Must be overridden by subclasses.
@@ -1688,9 +2125,8 @@ var Think = class Think extends Agent {
1688
2125
  }
1689
2126
  /**
1690
2127
  * Return the fallback system prompt for the assistant.
1691
- * Ignored when Session context blocks are configured. Use
1692
- * `configureSession().withContext()` for always-on instructions that should
1693
- * coexist with context blocks or skills.
2128
+ * Ignored when context blocks are configured. Use `configureContext()` for
2129
+ * always-on instructions that should coexist with context blocks or skills.
1694
2130
  */
1695
2131
  getSystemPrompt() {
1696
2132
  return [
@@ -1944,6 +2380,117 @@ var Think = class Think extends Agent {
1944
2380
  * Task-local timezone declarations take precedence.
1945
2381
  */
1946
2382
  getDefaultTimezone() {}
2383
+ /**
2384
+ * Register the shared chat-turn Task definition (see
2385
+ * `agents/chat` `createChatTurnTaskDefinition` for the turn logic): the
2386
+ * host wires its protected internals through the hooks.
2387
+ */
2388
+ _registerChatTurnTaskDefinition() {
2389
+ const chatFiberName = this.constructor.CHAT_FIBER_NAME;
2390
+ this.tasks.register(chatFiberName, createChatTurnTaskDefinition({
2391
+ definitionName: chatFiberName,
2392
+ storage: this.ctx.storage,
2393
+ getRunCreatedAt: async (runId) => (await this.tasks.get(runId))?.createdAt ?? null,
2394
+ getLiveClosure: (nonce) => this._liveChatTurnClosures.get(nonce),
2395
+ keepAliveWhile: (fn) => this.keepAliveWhile(fn),
2396
+ withStash: (context, fn) => this._withFiberStash(context, fn),
2397
+ handleRecovery: (ctx) => this._handleInternalFiberRecovery(ctx)
2398
+ }));
2399
+ }
2400
+ /** Register the shared Tasks transport for recovery continuations. */
2401
+ _registerChatRecoveryTaskDefinition() {
2402
+ this.tasks.register(CHAT_RECOVERY_TASK_NAME, createChatRecoveryTaskDefinition({
2403
+ _chatRecoveryContinue: (data) => this._chatRecoveryContinue(data),
2404
+ _chatRecoveryRetry: (data) => this._chatRecoveryRetry(data)
2405
+ }));
2406
+ }
2407
+ /**
2408
+ * Run a queue-driven recovery callback to its model handoff and return;
2409
+ * the turn continues as tracked alarm work, and a detached platform
2410
+ * failure enqueues one replacement attempt through the same transport.
2411
+ */
2412
+ _dispatchChatRecovery(callback, data, detached) {
2413
+ return dispatchChatRecoveryToHandoff({
2414
+ detached,
2415
+ track: (turn) => this.lifecycle.trackAlarmWork(turn),
2416
+ redefer: (dedupeKey) => this._enqueueChatRecovery(callback, data ?? {}, "redefer", CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS, dedupeKey),
2417
+ onDetachedError: (error) => console.error(`[Think] ${callback} dispatch failed`, error)
2418
+ });
2419
+ }
2420
+ /**
2421
+ * Enqueue one recovery attempt on the shared Tasks transport. Tasks
2422
+ * mirrors a routed dynamic agent's wake to the root's alarm; the run
2423
+ * itself, and this continuation's replay, still execute here. `dedupeKey`
2424
+ * keys a retried enqueue so it joins its own prior attempt instead of
2425
+ * duplicating it — see {@link chatRecoveryTaskRunOptions}.
2426
+ */
2427
+ async _enqueueChatRecovery(callback, data, reason, delaySeconds, dedupeKey) {
2428
+ const input = {
2429
+ callback,
2430
+ data,
2431
+ delaySeconds
2432
+ };
2433
+ await this.tasks.__DO_NOT_USE_WILL_BREAK__enqueue(CHAT_RECOVERY_TASK_NAME, input, chatRecoveryTaskRunOptions(input, reason, dedupeKey));
2434
+ }
2435
+ /**
2436
+ * The messenger-reply Task definition. A live webhook reply executes as
2437
+ * one journaled step through the runtime's closure registry, persisting
2438
+ * its re-entry snapshot in host storage; a replay whose closure is gone
2439
+ * is recovered on wake by the same
2440
+ * `ThinkMessengerRuntime.handleFiberRecovery` the legacy scan used.
2441
+ */
2442
+ _registerMessengerReplyTaskDefinition() {
2443
+ this.tasks.register(MESSENGER_REPLY_TASK_DEFINITION, async (input, step) => {
2444
+ const { nonce } = input;
2445
+ await step.do("deliver", {
2446
+ retries: { limit: 1 },
2447
+ timeout: "1 day"
2448
+ }, async ({ signal }) => {
2449
+ const runtime = this._messengerRuntime;
2450
+ if (!runtime) throw new Error("Messenger runtime is unavailable");
2451
+ const runId = `msgr_${nonce}`;
2452
+ const persistKey = `__cf_messenger_recovery:${runId}`;
2453
+ if (!runtime.hasLiveReply(nonce)) {
2454
+ const persisted = await this.ctx.storage.get(persistKey);
2455
+ const createdAt = (await this.tasks.get(runId))?.createdAt ?? Date.now();
2456
+ const ctx = {
2457
+ id: runId,
2458
+ name: MESSENGER_REPLY_FIBER_NAME,
2459
+ snapshot: persisted ?? null,
2460
+ createdAt,
2461
+ recoveryReason: "interrupted"
2462
+ };
2463
+ await runtime.handleFiberRecovery(ctx, { persistRecoverySnapshot: async (snapshot) => {
2464
+ await this.ctx.storage.put(persistKey, snapshot);
2465
+ } });
2466
+ await this.ctx.storage.delete(persistKey);
2467
+ return;
2468
+ }
2469
+ const initial = runtime.initialReplySnapshot(nonce);
2470
+ if (initial !== void 0) await this.ctx.storage.put(persistKey, initial);
2471
+ await runtime.executeLiveReply(nonce, {
2472
+ id: runId,
2473
+ signal,
2474
+ stash: (data) => void this.ctx.storage.put(persistKey, data).catch(() => {}),
2475
+ snapshot: null
2476
+ });
2477
+ await this.ctx.storage.delete(persistKey);
2478
+ });
2479
+ });
2480
+ }
2481
+ /**
2482
+ * Host seam for {@link ThinkMessengerRuntime}: durably accept one reply
2483
+ * run on the Tasks capability and execute it inline while this isolate
2484
+ * lives.
2485
+ * @internal
2486
+ */
2487
+ async _runMessengerReplyTask(input) {
2488
+ return { accepted: (await this.tasks.__DO_NOT_USE_WILL_BREAK__runAttached(MESSENGER_REPLY_TASK_DEFINITION, { nonce: input.nonce }, {
2489
+ runId: `msgr_${input.nonce}`,
2490
+ idempotencyKey: input.idempotencyKey,
2491
+ metadata: input.metadata
2492
+ })).accepted };
2493
+ }
1947
2494
  async _runChatRecoveryFiber(requestId, continuation, fn) {
1948
2495
  const snapshot = createChatFiberSnapshot({
1949
2496
  kind: "think-chat-turn",
@@ -1954,10 +2501,52 @@ var Think = class Think extends Agent {
1954
2501
  lastBody: this._lastBody,
1955
2502
  lastClientTools: this._lastClientTools
1956
2503
  });
1957
- return this._runFiberWithStashWrapper(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => fn(), {
1958
- initialSnapshot: wrapChatFiberSnapshot("__cfThinkChatFiberSnapshot", snapshot, null),
1959
- wrapStash: (data) => wrapChatFiberSnapshot("__cfThinkChatFiberSnapshot", snapshot, data)
2504
+ const wrap = (data) => wrapChatFiberSnapshot("__cfThinkChatFiberSnapshot", snapshot, data);
2505
+ const acceptance = recoveredTurnAcceptanceContext.getStore();
2506
+ const onAccepted = acceptance?.agent === this ? acceptance.onAccepted : void 0;
2507
+ if (this.parentPath.length > 0) return this._runFiberWithStashWrapper(`${this.constructor.CHAT_FIBER_NAME}:${requestId}`, async () => {
2508
+ onAccepted?.(requestId);
2509
+ return fn();
2510
+ }, {
2511
+ initialSnapshot: wrap(null),
2512
+ wrapStash: wrap
2513
+ });
2514
+ const nonce = crypto.randomUUID();
2515
+ let resolveOutcome;
2516
+ let rejectOutcome;
2517
+ const outcome = new Promise((resolve, reject) => {
2518
+ resolveOutcome = resolve;
2519
+ rejectOutcome = reject;
2520
+ });
2521
+ outcome.catch(() => {});
2522
+ const ambient = __DO_NOT_USE_WILL_BREAK__agentContext.getStore();
2523
+ const run = () => {
2524
+ onAccepted?.(requestId);
2525
+ return ambient ? __DO_NOT_USE_WILL_BREAK__agentContext.run(ambient, fn) : fn();
2526
+ };
2527
+ this._liveChatTurnClosures.set(nonce, {
2528
+ initial: wrap(null),
2529
+ wrap,
2530
+ run,
2531
+ settle: {
2532
+ resolve: resolveOutcome,
2533
+ reject: rejectOutcome
2534
+ }
1960
2535
  });
2536
+ try {
2537
+ await this.tasks.__DO_NOT_USE_WILL_BREAK__runAttached(this.constructor.CHAT_FIBER_NAME, {
2538
+ requestId,
2539
+ continuation,
2540
+ nonce
2541
+ }, {
2542
+ runId: `chat_${nonce}`,
2543
+ retain: false,
2544
+ metadata: { requestId }
2545
+ });
2546
+ return await outcome;
2547
+ } finally {
2548
+ this._liveChatTurnClosures.delete(nonce);
2549
+ }
1961
2550
  }
1962
2551
  _systemPromptForTurn(baseSystem, tools) {
1963
2552
  if (baseSystem.includes("You are running inside a Think agent.")) return baseSystem;
@@ -1975,7 +2564,6 @@ var Think = class Think extends Agent {
1975
2564
  "grep",
1976
2565
  "delete"
1977
2566
  ].some((toolName) => toolNames.has(toolName));
1978
- const hasContextTools = toolNames.has("load_context") || toolNames.has("unload_context");
1979
2567
  const hasExtensionTools = toolNames.has("load_extension") || toolNames.has("list_extensions");
1980
2568
  const hasExecuteTool = toolNames.has("execute");
1981
2569
  const hasFetchTools = [...toolNames].some((name) => name.startsWith("fetch_"));
@@ -1989,7 +2577,6 @@ var Think = class Think extends Agent {
1989
2577
  lines.push("- Use the tools exposed in this turn when they materially improve accuracy or let you act on the user's request. Treat tool descriptions and schemas as the source of truth.");
1990
2578
  lines.push("- Some tools may call server code, browser/client code, MCP servers, extensions, or delegated agents. Use them according to their descriptions.");
1991
2579
  }
1992
- if (hasContextTools) lines.push("- If context-loading tools are available, use them to load relevant memory, skills, or project context before acting on incomplete information.");
1993
2580
  if (hasExtensionTools) lines.push("- If extension tools are available, use them only when loading or inspecting extensions directly helps with the task.");
1994
2581
  if (hasExecuteTool) lines.push("- If sandboxed execution is available, prefer it for safe, bounded checks or coordinated multi-step operations.");
1995
2582
  if (hasFetchTools) lines.push("- If fetch tools are available, use them to read allowlisted HTTP resources (documentation, APIs). They are read-only and bounded; respect their allowlist and do not assume access to other URLs.");
@@ -2013,15 +2600,20 @@ var Think = class Think extends Agent {
2013
2600
  return Math.max(1, this.contextOverflow?.proactive?.maxCompactions ?? 1);
2014
2601
  }
2015
2602
  /**
2016
- * Configure the session. Called once during `onStart`.
2017
- * Override to add context blocks, compaction, search, skills.
2603
+ * Configure conversation storage. Called once during `onStart`. Override to
2604
+ * set the compaction policy; prompt context is declared by
2605
+ * {@link Think.configureContext} instead.
2606
+ *
2607
+ * The handle still accepts the pre-Sessions `withContext()` and
2608
+ * `withCachedPrompt()` chain, so an existing override keeps working; those
2609
+ * blocks are appended after the ones `configureContext()` returns.
2018
2610
  *
2019
2611
  * @example
2020
2612
  * ```typescript
2021
2613
  * configureSession(session: Session) {
2022
2614
  * return session
2023
- * .withContext("memory", { description: "Learned facts", maxTokens: 2000 })
2024
- * .withCachedPrompt();
2615
+ * .onCompaction(createCompactFunction({ summarize }))
2616
+ * .compactAfter(80_000);
2025
2617
  * }
2026
2618
  * ```
2027
2619
  */
@@ -2029,6 +2621,26 @@ var Think = class Think extends Agent {
2029
2621
  return session;
2030
2622
  }
2031
2623
  /**
2624
+ * Declare the prompt context blocks for this agent.
2625
+ *
2626
+ * Blocks render into the system prompt and, when their provider is
2627
+ * writable, give the model `set_context` to update them. A block declared
2628
+ * without a provider is auto-wired to durable per-agent SQLite storage.
2629
+ *
2630
+ * @example
2631
+ * ```typescript
2632
+ * configureContext(): ContextConfig[] {
2633
+ * return [
2634
+ * { label: "soul", provider: { get: async () => "You are helpful." } },
2635
+ * { label: "memory", description: "Learned facts", maxTokens: 2000 }
2636
+ * ];
2637
+ * }
2638
+ * ```
2639
+ */
2640
+ configureContext() {
2641
+ return [];
2642
+ }
2643
+ /**
2032
2644
  * Return Agent Skills sources for this Think agent.
2033
2645
  *
2034
2646
  * Bundled skills are typically imported with the Agents Vite plugin:
@@ -2048,7 +2660,7 @@ var Think = class Think extends Agent {
2048
2660
  const sources = await this.getSkills();
2049
2661
  if (sources.length === 0) return;
2050
2662
  if (this.getSystemPrompt !== Think.prototype.getSystemPrompt) {
2051
- const warning = "getSystemPrompt() is only used as a fallback when no Session context blocks are configured. getSkills() registers a skills context block, so move always-on instructions into configureSession().withContext(...) instead.";
2663
+ const warning = "getSystemPrompt() is only used as a fallback when no context blocks are configured. getSkills() registers a skills context block, so move always-on instructions into configureContext() instead.";
2052
2664
  if (!this._loggedSkillWarnings.has(warning)) {
2053
2665
  this._loggedSkillWarnings.add(warning);
2054
2666
  console.warn(`[think] ${warning}`);
@@ -2058,18 +2670,49 @@ var Think = class Think extends Agent {
2058
2670
  await registry.load();
2059
2671
  this._logSkillWarnings(registry);
2060
2672
  this._skillRegistry = registry;
2061
- await this.session.addContext(registry.contextLabel, {
2673
+ await this._configureSkillWorkspace(registry);
2674
+ await this.context.addBlock({
2675
+ label: registry.contextLabel,
2062
2676
  description: "Think skills: available skill catalog",
2063
2677
  provider: { get: () => registry.systemPrompt() }
2064
2678
  });
2065
- if (this._configGet("skillsFingerprint") !== registry.fingerprint) {
2066
- await this.session.refreshSystemPrompt();
2679
+ if ((this._skillsFingerprint ??= this._configGet("skillsFingerprint") ?? null) !== registry.fingerprint) {
2680
+ await this.context.refreshSystemPrompt();
2067
2681
  this._configSet("skillsFingerprint", registry.fingerprint);
2682
+ this._skillsFingerprint = registry.fingerprint;
2068
2683
  }
2069
2684
  } catch (error) {
2070
2685
  console.warn(`[think] Failed to initialize skills; continuing without them: ${error instanceof Error ? error.message : String(error)}`);
2071
2686
  }
2072
2687
  }
2688
+ async _configureSkillWorkspace(registry) {
2689
+ if (this.skillWorkspace === false) return;
2690
+ const workspace = this.workspace;
2691
+ if (!hasWriteFileBytes(workspace)) {
2692
+ const warning = "skillWorkspace is enabled but the configured workspace does not implement writeFileBytes; skills stay source-backed.";
2693
+ if (!this._loggedSkillWarnings.has(warning)) {
2694
+ this._loggedSkillWarnings.add(warning);
2695
+ console.warn(`[think] ${warning}`);
2696
+ }
2697
+ return;
2698
+ }
2699
+ try {
2700
+ const key = "skillsWorkspaceFingerprint";
2701
+ if (this._configGet(key) === registry.fingerprint) {
2702
+ await registry.useWorkspace(workspace, this.skillWorkspace);
2703
+ return;
2704
+ }
2705
+ const seeded = await registry.seedWorkspace(workspace, this.skillWorkspace);
2706
+ for (const warning of seeded.warnings) {
2707
+ if (this._loggedSkillWarnings.has(warning)) continue;
2708
+ this._loggedSkillWarnings.add(warning);
2709
+ console.warn(`[think] ${warning}`);
2710
+ }
2711
+ if (seeded.skipped === 0) this._configSet(key, registry.fingerprint);
2712
+ } catch (error) {
2713
+ console.warn(`[think] Failed to seed skills into the workspace; source-backed skill tools remain available: ${error instanceof Error ? error.message : String(error)}`);
2714
+ }
2715
+ }
2073
2716
  /**
2074
2717
  * Log registry diagnostics (duplicate names, sources that failed to list),
2075
2718
  * deduped by message so a new collision after a deploy still surfaces while
@@ -2096,9 +2739,11 @@ var Think = class Think extends Agent {
2096
2739
  try {
2097
2740
  await this._skillRegistry.refresh();
2098
2741
  this._logSkillWarnings(this._skillRegistry);
2099
- if (this._configGet("skillsFingerprint") !== this._skillRegistry.fingerprint) {
2100
- await this.session.refreshSystemPrompt();
2742
+ await this._configureSkillWorkspace(this._skillRegistry);
2743
+ if ((this._skillsFingerprint ??= this._configGet("skillsFingerprint") ?? null) !== this._skillRegistry.fingerprint) {
2744
+ await this.context.refreshSystemPrompt();
2101
2745
  this._configSet("skillsFingerprint", this._skillRegistry.fingerprint);
2746
+ this._skillsFingerprint = this._skillRegistry.fingerprint;
2102
2747
  }
2103
2748
  } catch (error) {
2104
2749
  console.warn(`[think] Failed to refresh skills; using last known catalog: ${error instanceof Error ? error.message : String(error)}`);
@@ -2457,15 +3102,16 @@ var Think = class Think extends Agent {
2457
3102
  const prefix = sanitizeName(ext.name);
2458
3103
  for (const ctxDef of manifest.context) {
2459
3104
  const namespacedLabel = `${prefix}_${ctxDef.label}`;
2460
- await this.session.addContext(namespacedLabel, {
3105
+ await this.context.addBlock({
3106
+ label: namespacedLabel,
2461
3107
  description: ctxDef.description,
2462
3108
  maxTokens: ctxDef.maxTokens
2463
3109
  });
2464
3110
  }
2465
3111
  }
2466
3112
  this.extensionManager.onUnload(async (_name, contextLabels) => {
2467
- for (const label of contextLabels) this.session.removeContext(label);
2468
- await this.session.refreshSystemPrompt();
3113
+ for (const label of contextLabels) this.context.removeBlock(label);
3114
+ await this.context.refreshSystemPrompt();
2469
3115
  });
2470
3116
  }
2471
3117
  /**
@@ -2653,7 +3299,7 @@ var Think = class Think extends Agent {
2653
3299
  const actionTools = await this._compileActionTools();
2654
3300
  const extensionTools = this.extensionManager?.getTools() ?? {};
2655
3301
  await this._refreshSkillsIfChanged();
2656
- const contextTools = await this.session.tools();
3302
+ const contextTools = await this.context.tools();
2657
3303
  const skillTools = this._skillRegistry?.tools() ?? {};
2658
3304
  const clientToolSet = createToolsFromClientSchemas(input.clientTools, input.clientToolExecutor ? { execute: input.clientToolExecutor } : void 0);
2659
3305
  let tools = {
@@ -2671,7 +3317,7 @@ var Think = class Think extends Agent {
2671
3317
  const channelDefinition = channelContext ? this._channels?.get(channelContext.channelId) : void 0;
2672
3318
  if (channelDefinition?.tools) tools = channelDefinition.tools(tools);
2673
3319
  const channelInstructions = channelDefinition?.instructions && channelContext ? typeof channelDefinition.instructions === "function" ? await channelDefinition.instructions(channelContext) : channelDefinition.instructions : void 0;
2674
- const rawBaseSystem = await this.session.freezeSystemPrompt() || this.getSystemPrompt();
3320
+ const rawBaseSystem = await this.context.freezeSystemPrompt() || this.getSystemPrompt();
2675
3321
  const baseSystem = channelInstructions ? `${channelInstructions}\n\n${rawBaseSystem}` : rawBaseSystem;
2676
3322
  const system = this._systemPromptForTurn(baseSystem, tools);
2677
3323
  const messages = await this._assembleModelMessages(tools);
@@ -2764,7 +3410,10 @@ var Think = class Think extends Agent {
2764
3410
  abortSignal: input.signal,
2765
3411
  prepareStep: (async (event) => {
2766
3412
  const guarded = await this._maybeProactiveContextCompact(event);
2767
- const result = await this.beforeStep(event);
3413
+ const result = await this.beforeStep(guarded ? {
3414
+ ...event,
3415
+ messages: guarded
3416
+ } : event);
2768
3417
  const base = result == null ? {} : result;
2769
3418
  const baseMessages = base.messages;
2770
3419
  const withMessages = guarded && baseMessages === void 0 ? {
@@ -3514,10 +4163,10 @@ var Think = class Think extends Agent {
3514
4163
  }));
3515
4164
  }
3516
4165
  async _hostGetContext(label) {
3517
- return this.session.getContextBlock(label)?.content ?? null;
4166
+ return this.context.getBlock(label)?.content ?? null;
3518
4167
  }
3519
4168
  async _hostSetContext(label, content) {
3520
- await this.session.replaceContextBlock(label, content);
4169
+ await this.context.setBlock(label, content);
3521
4170
  }
3522
4171
  async _hostGetMessages(limit) {
3523
4172
  const history = this.messages;
@@ -3839,6 +4488,7 @@ var Think = class Think extends Agent {
3839
4488
  this._broadcast({ type: MSG_CHAT_CLEAR });
3840
4489
  }
3841
4490
  _ensureAgentToolChildRunTable() {
4491
+ if (_classPrivateFieldGet2(_agentToolChildRunTableReady, this)) return;
3842
4492
  this.sql`
3843
4493
  CREATE TABLE IF NOT EXISTS cf_agent_tool_child_runs (
3844
4494
  run_id TEXT PRIMARY KEY,
@@ -3865,6 +4515,7 @@ var Think = class Think extends Agent {
3865
4515
  PRIMARY KEY (run_id, sequence)
3866
4516
  )
3867
4517
  `;
4518
+ _classPrivateFieldSet2(_agentToolChildRunTableReady, this, true);
3868
4519
  }
3869
4520
  _persistAgentToolMilestone(runId, name, data, at) {
3870
4521
  this._ensureAgentToolChildRunTable();
@@ -5041,9 +5692,18 @@ var Think = class Think extends Agent {
5041
5692
  created_at INTEGER NOT NULL,
5042
5693
  messages_applied_at INTEGER,
5043
5694
  started_at INTEGER,
5044
- completed_at INTEGER
5695
+ completed_at INTEGER,
5696
+ -- Closed vocabulary: 'completed' | 'aborted' | 'retry'. NULL is legacy
5697
+ -- or an unsettled attempt; 'retry' is NOT terminal completion evidence.
5698
+ result_status TEXT,
5699
+ output_json TEXT
5045
5700
  )
5046
5701
  `;
5702
+ for (const statement of ["ALTER TABLE cf_think_submissions ADD COLUMN result_status TEXT", "ALTER TABLE cf_think_submissions ADD COLUMN output_json TEXT"]) try {
5703
+ this.ctx.storage.sql.exec(statement);
5704
+ } catch (error) {
5705
+ if (!(error instanceof Error ? error.message : String(error)).toLowerCase().includes("duplicate column")) throw error;
5706
+ }
5047
5707
  this.sql`
5048
5708
  CREATE INDEX IF NOT EXISTS cf_think_submissions_status_created_idx
5049
5709
  ON cf_think_submissions (status, created_at, submission_id)
@@ -5058,40 +5718,12 @@ var Think = class Think extends Agent {
5058
5718
  `;
5059
5719
  this._submissionTableEnsured = true;
5060
5720
  }
5061
- _ensureWorkflowNotificationTable() {
5062
- if (this._workflowNotificationTableEnsured) return;
5063
- this.sql`
5064
- CREATE TABLE IF NOT EXISTS cf_think_workflow_notifications (
5065
- notification_id TEXT PRIMARY KEY,
5066
- submission_id TEXT NOT NULL,
5067
- workflow_name TEXT NOT NULL,
5068
- workflow_id TEXT NOT NULL,
5069
- event_type TEXT NOT NULL,
5070
- payload_json TEXT NOT NULL,
5071
- attempts INTEGER NOT NULL DEFAULT 0,
5072
- last_error TEXT,
5073
- created_at INTEGER NOT NULL,
5074
- updated_at INTEGER NOT NULL,
5075
- delivered_at INTEGER
5076
- )
5077
- `;
5078
- try {
5079
- this.ctx.storage.sql.exec("ALTER TABLE cf_think_workflow_notifications ADD COLUMN delivered_at INTEGER");
5080
- } catch (error) {
5081
- if (!(error instanceof Error ? error.message : String(error)).toLowerCase().includes("duplicate column")) throw error;
5082
- }
5083
- this.sql`
5084
- CREATE INDEX IF NOT EXISTS cf_think_workflow_notifications_created_idx
5085
- ON cf_think_workflow_notifications (delivered_at, created_at, notification_id)
5086
- `;
5087
- this._workflowNotificationTableEnsured = true;
5088
- }
5089
5721
  _readSubmission(submissionId) {
5090
5722
  this._ensureSubmissionTable();
5091
5723
  return this.sql`
5092
5724
  SELECT submission_id, idempotency_key, request_id, stream_id, status,
5093
5725
  messages_json, metadata_json, error_message, created_at,
5094
- messages_applied_at, started_at, completed_at
5726
+ messages_applied_at, started_at, completed_at, result_status, output_json
5095
5727
  FROM cf_think_submissions
5096
5728
  WHERE submission_id = ${submissionId}
5097
5729
  LIMIT 1
@@ -5102,7 +5734,7 @@ var Think = class Think extends Agent {
5102
5734
  return this.sql`
5103
5735
  SELECT submission_id, idempotency_key, request_id, stream_id, status,
5104
5736
  messages_json, metadata_json, error_message, created_at,
5105
- messages_applied_at, started_at, completed_at
5737
+ messages_applied_at, started_at, completed_at, result_status, output_json
5106
5738
  FROM cf_think_submissions
5107
5739
  WHERE idempotency_key = ${idempotencyKey}
5108
5740
  LIMIT 1
@@ -5120,7 +5752,7 @@ var Think = class Think extends Agent {
5120
5752
  return this.sql`
5121
5753
  SELECT submission_id, idempotency_key, request_id, stream_id, status,
5122
5754
  messages_json, metadata_json, error_message, created_at,
5123
- messages_applied_at, started_at, completed_at
5755
+ messages_applied_at, started_at, completed_at, result_status, output_json
5124
5756
  FROM cf_think_submissions
5125
5757
  ORDER BY created_at DESC, submission_id DESC
5126
5758
  LIMIT ${limit}
@@ -5130,7 +5762,7 @@ var Think = class Think extends Agent {
5130
5762
  return this.sql`
5131
5763
  SELECT submission_id, idempotency_key, request_id, stream_id, status,
5132
5764
  messages_json, metadata_json, error_message, created_at,
5133
- messages_applied_at, started_at, completed_at
5765
+ messages_applied_at, started_at, completed_at, result_status, output_json
5134
5766
  FROM cf_think_submissions
5135
5767
  WHERE status = ${status}
5136
5768
  ORDER BY created_at DESC, submission_id DESC
@@ -5165,7 +5797,7 @@ var Think = class Think extends Agent {
5165
5797
  return parsed;
5166
5798
  }
5167
5799
  _serializeSubmissionMessages(messages) {
5168
- return JSON.stringify(messages.map((message) => this._rowSafe(message)));
5800
+ return JSON.stringify(messages.map((message) => enforceRowSizeLimit(sanitizeMessage(message), { warn: (warning) => console.warn(`[Think] ${warning}`) })));
5169
5801
  }
5170
5802
  _serializeMetadata(metadata) {
5171
5803
  return metadata === void 0 ? null : JSON.stringify(metadata);
@@ -5191,7 +5823,7 @@ var Think = class Think extends Agent {
5191
5823
  ...typeof workflowPrompt.fingerprint === "string" && { fingerprint: workflowPrompt.fingerprint }
5192
5824
  };
5193
5825
  }
5194
- async _emitSubmissionStatus(row, output) {
5826
+ async _emitSubmissionStatus(row) {
5195
5827
  const inspection = this._inspectionFromSubmissionRow(row);
5196
5828
  this._emit("submission:status", {
5197
5829
  submissionId: inspection.submissionId,
@@ -5212,7 +5844,6 @@ var Think = class Think extends Agent {
5212
5844
  error: inspection.error
5213
5845
  });
5214
5846
  }
5215
- if (this._isTerminalSubmissionStatus(inspection.status)) await this._enqueueWorkflowNotification(inspection, output);
5216
5847
  await this.keepAliveWhile(async () => {
5217
5848
  try {
5218
5849
  await this.onSubmissionStatus(inspection);
@@ -5222,149 +5853,112 @@ var Think = class Think extends Agent {
5222
5853
  });
5223
5854
  }
5224
5855
  onSubmissionStatus(_submission) {}
5225
- async _enqueueWorkflowNotification(submission, output) {
5226
- this._insertWorkflowNotification(submission, output);
5227
- this._startWorkflowNotificationDrain();
5228
- }
5229
- _insertWorkflowNotification(submission, output, override) {
5856
+ /**
5857
+ * Queue the workflow event for a submission that just went terminal.
5858
+ *
5859
+ * The item is written synchronously (the Lifecycle has started whenever a
5860
+ * submission transitions), so call this in the same synchronous block as
5861
+ * the terminal status write: the two commit together and no recovery scan
5862
+ * is needed. A repeated push for the same submission and event type
5863
+ * replaces the pending item rather than duplicating it.
5864
+ */
5865
+ _insertWorkflowNotification(submission, output) {
5230
5866
  const workflowPrompt = this._readWorkflowPromptContext(submission.metadata ?? null);
5231
5867
  if (!workflowPrompt) return false;
5232
- this._ensureWorkflowNotificationTable();
5233
- const now = Date.now();
5234
- const status = override?.status ?? submission.status;
5235
- const error = override?.error ?? submission.error;
5868
+ const { status, error } = submission;
5236
5869
  const payload = {
5237
5870
  submissionId: submission.submissionId,
5238
5871
  status,
5239
5872
  ...status === "completed" && { output },
5240
5873
  ...error && { error }
5241
5874
  };
5242
- this.sql`
5243
- INSERT OR IGNORE INTO cf_think_workflow_notifications (
5244
- notification_id, submission_id, workflow_name, workflow_id, event_type,
5245
- payload_json, attempts, last_error, created_at, updated_at, delivered_at
5246
- )
5247
- VALUES (
5248
- ${`${submission.submissionId}:${workflowPrompt.workflow.eventType}`},
5249
- ${submission.submissionId},
5250
- ${workflowPrompt.workflow.name},
5251
- ${workflowPrompt.workflow.id},
5252
- ${workflowPrompt.workflow.eventType},
5253
- ${JSON.stringify(payload)},
5254
- 0,
5255
- NULL,
5256
- ${now},
5257
- ${now},
5258
- NULL
5259
- )
5260
- `;
5875
+ this.queue(WORKFLOW_NOTIFICATION_CALLBACK, {
5876
+ workflowName: workflowPrompt.workflow.name,
5877
+ workflowId: workflowPrompt.workflow.id,
5878
+ event: {
5879
+ type: workflowPrompt.workflow.eventType,
5880
+ payload
5881
+ }
5882
+ }, {
5883
+ id: workflowNotificationItemId(submission.submissionId, workflowPrompt.workflow.eventType),
5884
+ retry: WORKFLOW_NOTIFICATION_RETRY
5885
+ }).catch((error) => {
5886
+ console.error("[Think] Failed to queue workflow notification", error);
5887
+ });
5261
5888
  return true;
5262
5889
  }
5263
- _recoverWorkflowNotifications() {
5264
- this._ensureSubmissionTable();
5265
- this._ensureWorkflowNotificationTable();
5266
- const terminalRows = this.sql`
5267
- SELECT submission_id, idempotency_key, request_id, stream_id, status,
5268
- messages_json, metadata_json, error_message, created_at,
5269
- messages_applied_at, started_at, completed_at
5270
- FROM cf_think_submissions
5271
- WHERE status IN ('aborted', 'skipped', 'error')
5272
- ORDER BY completed_at DESC, created_at DESC
5273
- LIMIT 100
5274
- `;
5275
- let recovered = false;
5276
- for (const row of terminalRows) {
5277
- const inspection = this._inspectionFromSubmissionRow(row);
5278
- const workflowPrompt = this._readWorkflowPromptContext(inspection.metadata ?? null);
5279
- if (!workflowPrompt) continue;
5280
- const notificationId = `${inspection.submissionId}:${workflowPrompt.workflow.eventType}`;
5281
- if (this.sql`
5282
- SELECT notification_id
5283
- FROM cf_think_workflow_notifications
5284
- WHERE notification_id = ${notificationId}
5285
- LIMIT 1
5286
- `[0]) continue;
5287
- recovered = this._insertWorkflowNotification(inspection) || recovered;
5288
- }
5289
- if (recovered) this._startWorkflowNotificationDrain();
5290
- }
5291
- _startWorkflowNotificationDrain() {
5292
- if (!this._hasPendingWorkflowNotifications()) return;
5293
- this.keepAliveWhile(() => this._drainWorkflowNotifications()).catch((error) => {
5294
- console.error("[Think] Failed to drain workflow notifications", error);
5295
- this._rearmWorkflowNotificationAlarm();
5296
- });
5890
+ /** Queue the workflow event for a row that a caller just made terminal. */
5891
+ _enqueueTerminalWorkflowNotification(row, output) {
5892
+ if (!row || !this._isTerminalSubmissionStatus(row.status)) return;
5893
+ this._insertWorkflowNotification(this._inspectionFromSubmissionRow(row), output);
5297
5894
  }
5298
- _hasPendingWorkflowNotifications() {
5299
- this._ensureWorkflowNotificationTable();
5300
- return this.sql`
5301
- SELECT notification_id
5302
- FROM cf_think_workflow_notifications
5303
- WHERE delivered_at IS NULL
5304
- LIMIT 1
5305
- `.length > 0;
5306
- }
5307
- async _drainWorkflowNotifications() {
5308
- if (this._drainingWorkflowNotifications) return;
5309
- this._ensureWorkflowNotificationTable();
5310
- this._drainingWorkflowNotifications = true;
5895
+ /**
5896
+ * Deliver one workflow notification. Runs from the queue on first
5897
+ * delivery; a failed delivery schedules this same callback again with
5898
+ * exponential backoff (2s doubling, capped at ten minutes) so a
5899
+ * temporarily unreachable workflow still gets its terminal event. Once
5900
+ * the first failure is twelve hours old delivery gives up by throwing:
5901
+ * the dispatching capability reports it through its error event and the
5902
+ * Agent's `onError`.
5903
+ * @internal Queue and schedule callback.
5904
+ */
5905
+ async _cfDeliverWorkflowNotification(payload) {
5311
5906
  try {
5312
- const rows = this.sql`
5313
- SELECT notification_id, submission_id, workflow_name, workflow_id,
5314
- event_type, payload_json, attempts, last_error, created_at,
5315
- updated_at, delivered_at
5316
- FROM cf_think_workflow_notifications
5317
- WHERE delivered_at IS NULL
5318
- ORDER BY created_at ASC, notification_id ASC
5319
- LIMIT 25
5320
- `;
5321
- for (const row of rows) try {
5322
- const payload = JSON.parse(row.payload_json);
5323
- await this.sendWorkflowEvent(row.workflow_name, row.workflow_id, {
5324
- type: row.event_type,
5325
- payload
5326
- });
5327
- this.sql`
5328
- UPDATE cf_think_workflow_notifications
5329
- SET payload_json = '{}',
5330
- last_error = NULL,
5331
- updated_at = ${Date.now()},
5332
- delivered_at = ${Date.now()}
5333
- WHERE notification_id = ${row.notification_id}
5334
- AND delivered_at IS NULL
5335
- `;
5336
- } catch (error) {
5337
- this.sql`
5338
- UPDATE cf_think_workflow_notifications
5339
- SET attempts = attempts + 1,
5340
- last_error = ${error instanceof Error ? error.message : String(error)},
5341
- updated_at = ${Date.now()}
5342
- WHERE notification_id = ${row.notification_id}
5343
- `;
5907
+ await this.sendWorkflowEvent(payload.workflowName, payload.workflowId, payload.event);
5908
+ } catch (error) {
5909
+ const attempts = (payload.attempts ?? 0) + 1;
5910
+ const firstFailedAt = payload.firstFailedAt ?? Date.now();
5911
+ if (Date.now() - firstFailedAt >= WORKFLOW_NOTIFICATION_GIVE_UP_MS) {
5912
+ const summary = `Workflow notification for submission ${JSON.stringify(payload.event.payload?.submissionId)} (${payload.workflowName}/${payload.workflowId}, ${payload.event.type}) could not be delivered after ${attempts} attempts over 12h; giving up`;
5913
+ console.error(`[Think] ${summary}`, error);
5914
+ throw new Error(summary);
5344
5915
  }
5345
- } finally {
5346
- this._drainingWorkflowNotifications = false;
5916
+ const delaySeconds = Math.min(WORKFLOW_NOTIFICATION_MAX_BACKOFF_SECONDS, 2 ** Math.min(attempts, 20));
5917
+ console.error(`[Think] Workflow notification delivery failed (attempt ${attempts}); retrying in ${delaySeconds}s`, error);
5918
+ await this.schedule(delaySeconds, WORKFLOW_NOTIFICATION_CALLBACK, {
5919
+ ...payload,
5920
+ attempts,
5921
+ firstFailedAt
5922
+ });
5347
5923
  }
5348
- await this._rearmWorkflowNotificationAlarm();
5349
5924
  }
5350
- _nextWorkflowNotificationAlarm() {
5351
- this._ensureWorkflowNotificationTable();
5352
- const pending = this.sql`
5353
- SELECT attempts, updated_at
5925
+ /**
5926
+ * Move undelivered rows of the retired `cf_think_workflow_notifications`
5927
+ * outbox into the queue and drop the table. Idempotent: a missing table
5928
+ * means a fresh object or a completed migration.
5929
+ *
5930
+ * TEMPORARY: one-shot upgrade path for objects that were mid-delivery when
5931
+ * this release landed. Remove in the next minor release, once every
5932
+ * deployed object has started on this version and migrated.
5933
+ */
5934
+ async _migrateLegacyWorkflowNotifications() {
5935
+ if (this.ctx.storage.sql.exec("SELECT name FROM sqlite_master WHERE type='table' AND name='cf_think_workflow_notifications'").toArray().length === 0) return;
5936
+ const rows = this.sql`
5937
+ SELECT submission_id, workflow_name, workflow_id, event_type, payload_json
5354
5938
  FROM cf_think_workflow_notifications
5355
5939
  WHERE delivered_at IS NULL
5356
5940
  ORDER BY created_at ASC, notification_id ASC
5357
- LIMIT 1
5358
5941
  `;
5359
- if (!pending[0]) return null;
5360
- const delayMs = Math.min(300 * 1e3, 1e3 * 2 ** Math.min(pending[0].attempts, 8));
5361
- return Math.max(pending[0].updated_at + delayMs, Date.now() + 1);
5362
- }
5363
- _getExtensionAlarm() {
5364
- return this._nextWorkflowNotificationAlarm();
5365
- }
5366
- _rearmWorkflowNotificationAlarm() {
5367
- return this.lifecycle.rearmAlarm();
5942
+ for (const row of rows) {
5943
+ let payload;
5944
+ try {
5945
+ payload = JSON.parse(row.payload_json);
5946
+ } catch {
5947
+ continue;
5948
+ }
5949
+ await this.queue(WORKFLOW_NOTIFICATION_CALLBACK, {
5950
+ workflowName: row.workflow_name,
5951
+ workflowId: row.workflow_id,
5952
+ event: {
5953
+ type: row.event_type,
5954
+ payload
5955
+ }
5956
+ }, {
5957
+ id: workflowNotificationItemId(row.submission_id, row.event_type),
5958
+ retry: WORKFLOW_NOTIFICATION_RETRY
5959
+ });
5960
+ }
5961
+ this.sql`DROP TABLE cf_think_workflow_notifications`;
5368
5962
  }
5369
5963
  async inspectSubmission(submissionId) {
5370
5964
  const row = this._readSubmission(submissionId);
@@ -5407,7 +6001,7 @@ var Think = class Think extends Agent {
5407
6001
  if (completedBefore === void 0) return this.sql`
5408
6002
  SELECT submission_id, idempotency_key, request_id, stream_id, status,
5409
6003
  messages_json, metadata_json, error_message, created_at,
5410
- messages_applied_at, started_at, completed_at
6004
+ messages_applied_at, started_at, completed_at, result_status, output_json
5411
6005
  FROM cf_think_submissions
5412
6006
  WHERE status = ${status}
5413
6007
  ORDER BY completed_at ASC, created_at ASC
@@ -5416,7 +6010,7 @@ var Think = class Think extends Agent {
5416
6010
  return this.sql`
5417
6011
  SELECT submission_id, idempotency_key, request_id, stream_id, status,
5418
6012
  messages_json, metadata_json, error_message, created_at,
5419
- messages_applied_at, started_at, completed_at
6013
+ messages_applied_at, started_at, completed_at, result_status, output_json
5420
6014
  FROM cf_think_submissions
5421
6015
  WHERE status = ${status}
5422
6016
  AND completed_at IS NOT NULL
@@ -5439,12 +6033,18 @@ var Think = class Think extends Agent {
5439
6033
  UPDATE cf_think_submissions
5440
6034
  SET status = 'aborted',
5441
6035
  error_message = ${errorMessage},
5442
- completed_at = ${completedAt}
6036
+ completed_at = ${completedAt},
6037
+ result_status = NULL,
6038
+ output_json = NULL
5443
6039
  WHERE submission_id = ${submissionId}
5444
6040
  AND status IN ('pending', 'running')
5445
6041
  `;
5446
6042
  const updated = this._readSubmission(submissionId);
5447
- if (updated?.status === "aborted") await this._emitSubmissionStatus(updated);
6043
+ if (updated?.status === "aborted") {
6044
+ this._enqueueTerminalWorkflowNotification(updated);
6045
+ await this.dequeue(submissionRunItemId(submissionId));
6046
+ await this._emitSubmissionStatus(updated);
6047
+ }
5448
6048
  }
5449
6049
  async submitMessages(messages, options) {
5450
6050
  messages = this._stampChannel(messages, options?.channel);
@@ -5461,7 +6061,7 @@ var Think = class Think extends Agent {
5461
6061
  if (existingById && options?.idempotencyKey && existingById.idempotency_key !== null && existingById.idempotency_key !== options.idempotencyKey) throw new Error("submissionId and idempotencyKey refer to different submissions");
5462
6062
  const existing = existingById ?? existingByKey;
5463
6063
  if (existing) {
5464
- if (existing.status === "pending") await this._scheduleSubmissionDrain();
6064
+ if (existing.status === "pending") await this._queueSubmissionRun(existing.submission_id);
5465
6065
  return {
5466
6066
  ...this._inspectionFromSubmissionRow(existing),
5467
6067
  accepted: false
@@ -5492,7 +6092,7 @@ var Think = class Think extends Agent {
5492
6092
  idempotencyKey: row.idempotency_key ?? void 0
5493
6093
  });
5494
6094
  await this._emitSubmissionStatus(row);
5495
- await this._scheduleSubmissionDrain();
6095
+ await this._queueSubmissionRun(submissionId);
5496
6096
  return {
5497
6097
  ...this._inspectionFromSubmissionRow(row),
5498
6098
  accepted: true
@@ -5500,44 +6100,36 @@ var Think = class Think extends Agent {
5500
6100
  }
5501
6101
  });
5502
6102
  }
5503
- async _scheduleSubmissionDrain() {
5504
- await this.schedule(0, "_drainThinkSubmissions", void 0, { idempotent: true });
6103
+ /**
6104
+ * Queue the run of one pending submission. Idempotent: the stable id
6105
+ * replaces an item already queued for the submission in place, keeping
6106
+ * its FIFO slot, and re-arms the physical alarm so a lost alarm recovers.
6107
+ */
6108
+ async _queueSubmissionRun(submissionId) {
6109
+ await this.queue(SUBMISSION_RUN_CALLBACK, { submissionId }, { id: submissionRunItemId(submissionId) });
5505
6110
  }
5506
- _hasPendingSubmissions() {
6111
+ /** Queue a run for every pending submission that has none. */
6112
+ async _queuePendingSubmissionRuns() {
5507
6113
  this._ensureSubmissionTable();
5508
- return this.sql`
6114
+ const pending = this.sql`
5509
6115
  SELECT submission_id
5510
6116
  FROM cf_think_submissions
5511
6117
  WHERE status = 'pending'
5512
- LIMIT 1
5513
- `.length > 0;
5514
- }
5515
- async _drainThinkSubmissions() {
5516
- await this._drainSubmissions();
6118
+ ORDER BY created_at ASC, submission_id ASC
6119
+ `;
6120
+ for (const row of pending) await this._queueSubmissionRun(row.submission_id);
5517
6121
  }
5518
- async _drainSubmissions() {
6122
+ /**
6123
+ * Run one pending submission. Runs on the Lifecycle alarm loop through the
6124
+ * Queue capability, one item at a time in submission order; a row that is
6125
+ * no longer pending (cancelled, skipped, or claimed by an overlapping
6126
+ * dispatch) is a no-op.
6127
+ * @internal Queue callback.
6128
+ */
6129
+ async _cfRunSubmission(payload) {
5519
6130
  this._ensureSubmissionTable();
5520
- if (this._drainingSubmissions) return;
5521
- this._drainingSubmissions = true;
5522
- try {
5523
- while (true) {
5524
- const row = this.sql`
5525
- SELECT submission_id, idempotency_key, request_id, stream_id, status,
5526
- messages_json, metadata_json, error_message, created_at,
5527
- messages_applied_at, started_at, completed_at
5528
- FROM cf_think_submissions
5529
- WHERE status = 'pending'
5530
- ORDER BY created_at ASC, submission_id ASC
5531
- LIMIT 1
5532
- `[0];
5533
- if (!row) break;
5534
- await this._runSubmission(row);
5535
- }
5536
- } finally {
5537
- this._drainingSubmissions = false;
5538
- }
5539
- }
5540
- async _runSubmission(row) {
6131
+ const row = this._readSubmission(payload.submissionId);
6132
+ if (!row || row.status !== "pending") return;
5541
6133
  await this._admitTurn({
5542
6134
  admission: "execute-submission",
5543
6135
  trigger: "submission",
@@ -5596,7 +6188,9 @@ var Think = class Think extends Agent {
5596
6188
  request_id = ${result.requestId},
5597
6189
  stream_id = ${streamId},
5598
6190
  error_message = ${finalStatus === "error" ? errorMessage : null},
5599
- completed_at = ${completedAt}
6191
+ completed_at = ${completedAt},
6192
+ result_status = NULL,
6193
+ output_json = NULL
5600
6194
  WHERE submission_id = ${row.submission_id}
5601
6195
  AND status = 'running'
5602
6196
  `;
@@ -5611,7 +6205,9 @@ var Think = class Think extends Agent {
5611
6205
  UPDATE cf_think_submissions
5612
6206
  SET status = 'error',
5613
6207
  error_message = ${errorMessage},
5614
- completed_at = ${completedAt}
6208
+ completed_at = ${completedAt},
6209
+ result_status = NULL,
6210
+ output_json = NULL
5615
6211
  WHERE submission_id = ${row.submission_id}
5616
6212
  AND status = 'running'
5617
6213
  `;
@@ -5622,7 +6218,7 @@ var Think = class Think extends Agent {
5622
6218
  this._programmaticStreamErrors.delete(requestId);
5623
6219
  this._submissionAbortControllers.delete(row.submission_id);
5624
6220
  const updated = this._readSubmission(row.submission_id);
5625
- if (updated && this._isTerminalSubmissionStatus(updated.status)) await this._emitSubmissionStatus(updated, output);
6221
+ if (updated && this._isTerminalSubmissionStatus(updated.status)) await this._emitSubmissionStatus(updated);
5626
6222
  }
5627
6223
  }
5628
6224
  _getSubmissionFinalStatus(resultStatus, streamError) {
@@ -5633,7 +6229,7 @@ var Think = class Think extends Agent {
5633
6229
  const pending = this.sql`
5634
6230
  SELECT submission_id, idempotency_key, request_id, stream_id, status,
5635
6231
  messages_json, metadata_json, error_message, created_at,
5636
- messages_applied_at, started_at, completed_at
6232
+ messages_applied_at, started_at, completed_at, result_status, output_json
5637
6233
  FROM cf_think_submissions
5638
6234
  WHERE status = 'pending'
5639
6235
  `;
@@ -5644,6 +6240,12 @@ var Think = class Think extends Agent {
5644
6240
  completed_at = ${Date.now()}
5645
6241
  WHERE status = 'pending'
5646
6242
  `;
6243
+ for (const row of pending) {
6244
+ this._enqueueTerminalWorkflowNotification(this._readSubmission(row.submission_id));
6245
+ this.dequeue(submissionRunItemId(row.submission_id)).catch((error) => {
6246
+ console.error("[Think] Failed to dequeue skipped submission", error);
6247
+ });
6248
+ }
5647
6249
  return pending;
5648
6250
  }
5649
6251
  async _emitSkippedSubmissions(skipped) {
@@ -5657,11 +6259,15 @@ var Think = class Think extends Agent {
5657
6259
  const running = this.sql`
5658
6260
  SELECT submission_id, idempotency_key, request_id, stream_id, status,
5659
6261
  messages_json, metadata_json, error_message, created_at,
5660
- messages_applied_at, started_at, completed_at
6262
+ messages_applied_at, started_at, completed_at, result_status, output_json
5661
6263
  FROM cf_think_submissions
5662
6264
  WHERE status = 'running'
5663
6265
  `;
5664
6266
  for (const row of running) {
6267
+ if (row.result_status === "completed" || row.result_status === "aborted") {
6268
+ await this._completeRecoveredSubmission(row, row.result_status, row.request_id, null);
6269
+ continue;
6270
+ }
5665
6271
  if (row.messages_applied_at === null) {
5666
6272
  let appliedState;
5667
6273
  try {
@@ -5676,7 +6282,10 @@ var Think = class Think extends Agent {
5676
6282
  AND status = 'running'
5677
6283
  `;
5678
6284
  const updated = this._readSubmission(row.submission_id);
5679
- if (updated?.status === "error") await this._emitSubmissionStatus(updated);
6285
+ if (updated?.status === "error") {
6286
+ this._enqueueTerminalWorkflowNotification(updated);
6287
+ await this._emitSubmissionStatus(updated);
6288
+ }
5680
6289
  continue;
5681
6290
  }
5682
6291
  if (appliedState !== "none") {
@@ -5689,7 +6298,10 @@ var Think = class Think extends Agent {
5689
6298
  AND status = 'running'
5690
6299
  `;
5691
6300
  const updated = this._readSubmission(row.submission_id);
5692
- if (updated?.status === "error") await this._emitSubmissionStatus(updated);
6301
+ if (updated?.status === "error") {
6302
+ this._enqueueTerminalWorkflowNotification(updated);
6303
+ await this._emitSubmissionStatus(updated);
6304
+ }
5693
6305
  continue;
5694
6306
  }
5695
6307
  this.sql`
@@ -5703,7 +6315,13 @@ var Think = class Think extends Agent {
5703
6315
  if (updated?.status === "pending") await this._emitSubmissionStatus(updated);
5704
6316
  continue;
5705
6317
  }
5706
- if (row.request_id && (this._hasRecoverableChatTurn(row.request_id) && this._hasFreshRecoverableSubmissionEvidence(row) || this._hasScheduledRecoveredContinuation(row.request_id))) continue;
6318
+ if (row.request_id && (this._hasRecoverableChatTurn(row.request_id) && this._hasFreshRecoverableSubmissionEvidence(row) || await this._hasScheduledChatRecovery(row))) continue;
6319
+ const terminalStream = row.request_id ? this._resumableStream.latestStreamInfoForRequest(row.request_id) : null;
6320
+ const errored = row.result_status === "error" || terminalStream?.status === "error";
6321
+ if (errored || terminalStream?.status === "completed" && row.result_status !== "retry") {
6322
+ await this._completeRecoveredSubmission(row, errored ? "error" : "completed", row.request_id, errored ? "Recovered chat stream had already errored." : null);
6323
+ continue;
6324
+ }
5707
6325
  this.sql`
5708
6326
  UPDATE cf_think_submissions
5709
6327
  SET status = 'error',
@@ -5713,8 +6331,12 @@ var Think = class Think extends Agent {
5713
6331
  AND status = 'running'
5714
6332
  `;
5715
6333
  const updated = this._readSubmission(row.submission_id);
5716
- if (updated?.status === "error") await this._emitSubmissionStatus(updated);
6334
+ if (updated?.status === "error") {
6335
+ this._enqueueTerminalWorkflowNotification(updated);
6336
+ await this._emitSubmissionStatus(updated);
6337
+ }
5717
6338
  }
6339
+ await this._queuePendingSubmissionRuns();
5718
6340
  }
5719
6341
  async _getSubmissionMessagesAppliedState(row) {
5720
6342
  const messages = this._parseSubmissionMessages(row.messages_json);
@@ -5724,18 +6346,28 @@ var Think = class Think extends Agent {
5724
6346
  if (applied === 0) return "none";
5725
6347
  return applied === messages.length ? "all" : "partial";
5726
6348
  }
6349
+ /**
6350
+ * Wall-clock creation time of a non-terminal chat-turn run on the Tasks
6351
+ * capability, or null. The metadata column holds the exact JSON the chat
6352
+ * wrapper wrote, so string equality matches the requestId.
6353
+ */
6354
+ _recoverableChatTurnTaskCreatedAt(requestId) {
6355
+ return this.sql`
6356
+ SELECT created_at FROM cf_agents_task_runs
6357
+ WHERE definition = ${this.constructor.CHAT_FIBER_NAME}
6358
+ AND state IN ('pending', 'running', 'waiting', 'recovering')
6359
+ AND metadata = ${JSON.stringify({ requestId })}
6360
+ LIMIT 1
6361
+ `[0]?.created_at ?? null;
6362
+ }
5727
6363
  _hasRecoverableChatTurn(requestId) {
5728
6364
  if (this.sql`
5729
6365
  SELECT id FROM cf_agents_runs
5730
6366
  WHERE name = ${this.constructor.CHAT_FIBER_NAME + ":" + requestId}
5731
6367
  LIMIT 1
5732
6368
  `.length > 0) return true;
5733
- return this.sql`
5734
- SELECT id FROM cf_ai_chat_stream_metadata
5735
- WHERE request_id = ${requestId}
5736
- AND status = 'streaming'
5737
- LIMIT 1
5738
- `.length > 0;
6369
+ if (this._recoverableChatTurnTaskCreatedAt(requestId) !== null) return true;
6370
+ return this._resumableStream.latestActiveStreamInfoForRequest(requestId) !== null;
5739
6371
  }
5740
6372
  _hasFreshRecoverableSubmissionEvidence(row) {
5741
6373
  if (!row.request_id) return false;
@@ -5746,27 +6378,27 @@ var Think = class Think extends Agent {
5746
6378
  LIMIT 1
5747
6379
  `;
5748
6380
  if (fiberRows[0] && fiberRows[0].created_at >= cutoff) return true;
5749
- const streamRows = this.sql`
5750
- SELECT created_at FROM cf_ai_chat_stream_metadata
5751
- WHERE request_id = ${row.request_id}
5752
- AND status = 'streaming'
5753
- ORDER BY created_at DESC
5754
- LIMIT 1
5755
- `;
5756
- return streamRows[0] ? streamRows[0].created_at >= cutoff : false;
5757
- }
5758
- _hasScheduledRecoveredContinuation(requestId) {
5759
- return this.sql`
5760
- SELECT payload FROM cf_agents_schedules
5761
- WHERE callback = '_chatRecoveryContinue'
5762
- `.some((row) => {
5763
- if (!row.payload) return false;
5764
- try {
5765
- const payload = JSON.parse(row.payload);
5766
- return payload !== null && typeof payload === "object" && "recoveredRequestId" in payload && payload.recoveredRequestId === requestId;
5767
- } catch {
5768
- return false;
5769
- }
6381
+ const capabilityCreatedAt = this._recoverableChatTurnTaskCreatedAt(row.request_id);
6382
+ if (capabilityCreatedAt !== null && capabilityCreatedAt >= cutoff) return true;
6383
+ const streamInfo = this._resumableStream.latestActiveStreamInfoForRequest(row.request_id);
6384
+ return streamInfo ? streamInfo.createdAt >= cutoff : false;
6385
+ }
6386
+ async _hasScheduledChatRecovery(submission) {
6387
+ const isChatRecoveryCallback = (callback) => callback === "_chatRecoveryContinue" || callback === "_chatRecoveryRetry";
6388
+ const matchesSubmission = (recoveredRequestId) => typeof recoveredRequestId === "string" && this._readRunningSubmissionForRecovery(recoveredRequestId)?.submission_id === submission.submission_id;
6389
+ if ((await this.tasks.list({
6390
+ definition: CHAT_RECOVERY_TASK_NAME,
6391
+ status: [
6392
+ "pending",
6393
+ "running",
6394
+ "waiting"
6395
+ ],
6396
+ limit: Number.MAX_SAFE_INTEGER
6397
+ })).some((run) => isChatRecoveryCallback(run.metadata?.callback) && matchesSubmission(run.metadata.recoveredRequestId))) return true;
6398
+ return (await this.listSchedules()).some((schedule) => {
6399
+ if (!isChatRecoveryCallback(schedule.callback)) return false;
6400
+ const payload = schedule.payload;
6401
+ return payload !== null && typeof payload === "object" && "recoveredRequestId" in payload && matchesSubmission(payload.recoveredRequestId);
5770
6402
  });
5771
6403
  }
5772
6404
  /**
@@ -6267,31 +6899,16 @@ var Think = class Think extends Agent {
6267
6899
  });
6268
6900
  const clientToolsForTurn = this._lastClientTools;
6269
6901
  const bodyForTurn = this._lastBody;
6270
- const serverMessages = await withAgentSpan(this, "load_chat_history", "interaction", {
6271
- "cloudflare.agents.component": "think",
6272
- "cloudflare.agents.turn.request_id": requestId,
6273
- "cloudflare.agents.turn.trigger": "ws-chat"
6274
- }, () => this._readMessagesFromStorage());
6275
- const reconciled = reconcileMessages(incomingMessages, serverMessages, sanitizeMessage);
6276
- let branchParentId;
6277
- if (isRegeneration && reconciled.length > 0) branchParentId = reconciled[reconciled.length - 1].id;
6278
- if (!await withAgentSpan(this, "persist_incoming_messages", "interaction", {
6279
- "cloudflare.agents.component": "think",
6280
- "cloudflare.agents.turn.request_id": requestId,
6281
- "cloudflare.agents.turn.trigger": "ws-chat"
6282
- }, async () => {
6283
- if (this._turnQueue.generation !== epoch) return false;
6284
- for (const msg of reconciled) {
6285
- if (this._turnQueue.generation !== epoch) return false;
6286
- await this._persistIncomingMessage(msg, serverMessages);
6287
- }
6288
- if (this._turnQueue.generation !== epoch) return false;
6289
- await this._syncMessages();
6290
- return true;
6291
- })) {
6902
+ const reconciledTurn = await this._reconcileAndPersistIncoming(incomingMessages, {
6903
+ requestId,
6904
+ isRegeneration,
6905
+ isCurrent: () => this._turnQueue.generation === epoch
6906
+ });
6907
+ if (!reconciledTurn) {
6292
6908
  this._completeSkippedRequest(connection, requestId);
6293
6909
  return;
6294
6910
  }
6911
+ const { branchParentId } = reconciledTurn;
6295
6912
  this._broadcastMessages([connection.id]);
6296
6913
  messagesPersisted = true;
6297
6914
  failureStage = "turn";
@@ -6711,15 +7328,15 @@ var Think = class Think extends Agent {
6711
7328
  if (!streamDrainedNaturally) this._drainInferenceStream(result);
6712
7329
  }
6713
7330
  if (overflowRetry) {
6714
- this._completeResumableStream(streamId);
7331
+ this._completeSubmissionRetryStream(streamId, requestId);
6715
7332
  streamFinalized = true;
6716
7333
  return {
6717
7334
  status: "overflow_retry",
6718
7335
  error: streamError
6719
7336
  };
6720
7337
  }
6721
- if (streamError) this._errorResumableStream(streamId);
6722
- else this._completeResumableStream(streamId);
7338
+ if (streamError) this._errorResumableStream(streamId, requestId);
7339
+ else this._finishResumableStream(streamId);
6723
7340
  streamFinalized = true;
6724
7341
  this._broadcastChat({
6725
7342
  type: MSG_CHAT_RESPONSE,
@@ -6730,9 +7347,13 @@ var Think = class Think extends Agent {
6730
7347
  doneSent = true;
6731
7348
  assistantMsg = accumulator.toMessage();
6732
7349
  if (accumulator.parts.length > 0) {
6733
- await this._persistAssistantMessage(assistantMsg);
7350
+ await this._persistAssistantMessageWithCutover(streamId, assistantMsg, void 0, this._streamCutoverOptions(requestId), {
7351
+ requestId,
7352
+ result: { status: aborted ? "aborted" : "completed" }
7353
+ });
6734
7354
  this._broadcastMessages();
6735
7355
  }
7356
+ this._finalizeSubmissionStream(requestId, { status: aborted ? "aborted" : "completed" });
6736
7357
  if (streamError) {
6737
7358
  await this._fireResponseHook({
6738
7359
  message: assistantMsg,
@@ -6789,7 +7410,7 @@ var Think = class Think extends Agent {
6789
7410
  }
6790
7411
  if (outcome === "exhausted") {
6791
7412
  if (!streamFinalized) {
6792
- this._errorResumableStream(streamId);
7413
+ this._errorResumableStream(streamId, requestId);
6793
7414
  streamFinalized = true;
6794
7415
  }
6795
7416
  doneSent = true;
@@ -6799,7 +7420,7 @@ var Think = class Think extends Agent {
6799
7420
  }
6800
7421
  }
6801
7422
  if (!streamFinalized) {
6802
- this._errorResumableStream(streamId);
7423
+ this._errorResumableStream(streamId, requestId);
6803
7424
  streamFinalized = true;
6804
7425
  }
6805
7426
  if (!doneSent) {
@@ -6876,12 +7497,6 @@ var Think = class Think extends Agent {
6876
7497
  state.chunksSinceFlush = 0;
6877
7498
  state.hasFlushedContent = true;
6878
7499
  }
6879
- if (shouldCreditStreamProgress({
6880
- codec: aiSdkRecoveryCodec,
6881
- type: chunk.type,
6882
- throttle: this._streamProgressCredit,
6883
- now: Date.now()
6884
- })) await this._bumpChatRecoveryProgress();
6885
7500
  }
6886
7501
  async _streamResult(requestId, result, abortSignal, options) {
6887
7502
  const clearGen = this._turnQueue.generation;
@@ -6966,15 +7581,15 @@ var Think = class Think extends Agent {
6966
7581
  if (!streamDrainedNaturally) this._drainInferenceStream(result);
6967
7582
  }
6968
7583
  if (overflowRetry && options?.overflowRecovery) {
6969
- this._completeResumableStream(streamId);
7584
+ this._completeSubmissionRetryStream(streamId, requestId);
6970
7585
  this._pendingResumeConnections.clear();
6971
7586
  doneSent = true;
6972
7587
  options.overflowRecovery.onRetry(streamError);
6973
7588
  this._streamingAssistant = null;
6974
7589
  return { status: "aborted" };
6975
7590
  }
6976
- if (streamError) this._errorResumableStream(streamId);
6977
- else this._completeResumableStream(streamId);
7591
+ if (streamError) this._errorResumableStream(streamId, requestId);
7592
+ else this._finishResumableStream(streamId);
6978
7593
  this._pendingResumeConnections.clear();
6979
7594
  this._broadcastChat({
6980
7595
  type: MSG_CHAT_RESPONSE,
@@ -7016,7 +7631,7 @@ var Think = class Think extends Agent {
7016
7631
  return { status: "aborted" };
7017
7632
  }
7018
7633
  if (outcome === "exhausted") {
7019
- this._errorResumableStream(streamId);
7634
+ this._errorResumableStream(streamId, requestId);
7020
7635
  this._pendingResumeConnections.clear();
7021
7636
  doneSent = true;
7022
7637
  this._streamingAssistant = null;
@@ -7025,7 +7640,7 @@ var Think = class Think extends Agent {
7025
7640
  }
7026
7641
  streamError = error instanceof Error ? error.message : "Stream error";
7027
7642
  if (options?.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
7028
- this._errorResumableStream(streamId);
7643
+ this._errorResumableStream(streamId, requestId);
7029
7644
  this._pendingResumeConnections.clear();
7030
7645
  if (!doneSent) {
7031
7646
  this._broadcastChat({
@@ -7040,7 +7655,7 @@ var Think = class Think extends Agent {
7040
7655
  }
7041
7656
  } finally {
7042
7657
  if (!doneSent) {
7043
- this._errorResumableStream(streamId);
7658
+ this._errorResumableStream(streamId, requestId);
7044
7659
  this._pendingResumeConnections.clear();
7045
7660
  this._broadcastChat({
7046
7661
  type: MSG_CHAT_RESPONSE,
@@ -7056,13 +7671,22 @@ var Think = class Think extends Agent {
7056
7671
  } catch (error) {
7057
7672
  streamError = error instanceof Error ? error.message : "Structured output error";
7058
7673
  if (options.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
7674
+ this._errorResumableStream(streamId, requestId);
7059
7675
  }
7676
+ const submissionResult = streamAborted ? { status: "aborted" } : {
7677
+ status: "completed",
7678
+ output
7679
+ };
7060
7680
  if (this._turnQueue.generation === clearGen) try {
7061
7681
  const assistantMsg = accumulator.toMessage();
7062
7682
  if (accumulator.parts.length > 0) {
7063
- await this._persistAssistantMessage(assistantMsg, parentId);
7683
+ await this._persistAssistantMessageWithCutover(streamId, assistantMsg, parentId, this._streamCutoverOptions(requestId), {
7684
+ requestId,
7685
+ result: submissionResult
7686
+ });
7064
7687
  this._broadcastMessages();
7065
7688
  }
7689
+ this._finalizeSubmissionStream(requestId, submissionResult);
7066
7690
  await this._fireResponseHook({
7067
7691
  message: assistantMsg,
7068
7692
  requestId,
@@ -7072,7 +7696,10 @@ var Think = class Think extends Agent {
7072
7696
  });
7073
7697
  } catch (e) {
7074
7698
  console.error("Failed to persist assistant message:", e);
7699
+ streamError = e instanceof Error ? e.message : "Assistant message persistence failed";
7700
+ this._errorResumableStream(streamId, requestId);
7075
7701
  }
7702
+ this._finalizeSubmissionStream(requestId, submissionResult);
7076
7703
  this._onStreamingTurnFinalized();
7077
7704
  return streamError ? {
7078
7705
  status: "error",
@@ -7103,6 +7730,73 @@ var Think = class Think extends Agent {
7103
7730
  await this._upsertMessageInHistory(toPersist, parentId);
7104
7731
  }
7105
7732
  /**
7733
+ * The cutover: persist the finished turn's assistant message, settle its
7734
+ * resumable stream and delete the stream's rows in ONE SQLite transaction,
7735
+ * so a crash leaves either the live stream (recovery rebuilds the message
7736
+ * from it) or the message — never neither, never both. The session
7737
+ * change feed and auto-compaction run once the transaction has committed.
7738
+ */
7739
+ async _persistAssistantMessageWithCutover(streamId, msg, parentId, options = {}, submission) {
7740
+ const toPersist = this._strippedForPersist(msg);
7741
+ if (toPersist === null) return;
7742
+ if (this._resumableStream.pendingCutoverId !== streamId) {
7743
+ await this._upsertMessageInHistory(toPersist, parentId);
7744
+ return;
7745
+ }
7746
+ const sync = this.sessions.session().__DO_NOT_USE_WILL_BREAK__sync();
7747
+ let after;
7748
+ try {
7749
+ this._resumableStream.cutover(streamId, () => {
7750
+ after = sync.upsert(toPersist, {
7751
+ parentId,
7752
+ source: "server"
7753
+ }).after;
7754
+ if (submission) this._recordSubmissionTurnResult(submission.requestId, submission.result);
7755
+ }, options);
7756
+ } catch (error) {
7757
+ sync.abandon();
7758
+ throw error;
7759
+ }
7760
+ await after?.();
7761
+ }
7762
+ /**
7763
+ * Whether this turn's stream rows can go with its cutover. An agent-tool
7764
+ * child turn keeps them: the parent tails the stored chunks after the
7765
+ * child completes (`getAgentToolChunks`), so the rows are reclaimed by
7766
+ * the child's next `start()` instead, as `AIChatAgent` does. A running
7767
+ * submission needs no stream evidence: its durable outcome stamp commits
7768
+ * in the same transaction as this cutover.
7769
+ */
7770
+ _streamCutoverOptions(requestId) {
7771
+ return { discard: !this._agentToolRunsByRequestId.get(requestId) };
7772
+ }
7773
+ /** Write only inside the transaction that settles this exact request's stream. */
7774
+ _recordSubmissionTurnResult(requestId, result) {
7775
+ const row = this._readRunningSubmissionForRecovery(requestId);
7776
+ if (!row || row.request_id !== requestId) return;
7777
+ this.sql`
7778
+ UPDATE cf_think_submissions
7779
+ SET result_status = ${result.status},
7780
+ output_json = ${result.status === "completed" && result.output !== void 0 ? JSON.stringify(result.output) : null}
7781
+ WHERE submission_id = ${row.submission_id} AND status = 'running'
7782
+ `;
7783
+ }
7784
+ /** Empty/stripped messages have the same atomic outcome cutover as messages. */
7785
+ _finalizeSubmissionStream(requestId, result) {
7786
+ if (this._resumableStream.pendingCutoverId === null) return;
7787
+ this.ctx.storage.transactionSync(() => {
7788
+ this._resumableStream.finalizePending();
7789
+ this._recordSubmissionTurnResult(requestId, result);
7790
+ });
7791
+ }
7792
+ /** Keep overflow chunks for consumers, but never call that segment an answer. */
7793
+ _completeSubmissionRetryStream(streamId, requestId) {
7794
+ this.ctx.storage.transactionSync(() => {
7795
+ this._completeResumableStream(streamId);
7796
+ this._recordSubmissionTurnResult(requestId, { status: "retry" });
7797
+ });
7798
+ }
7799
+ /**
7106
7800
  * Remove parts belonging to Think's internal structured-output final-answer
7107
7801
  * tool (`think_final_answer`, or a collision-suffixed variant) from a UI
7108
7802
  * message so the internal call/result never enters the persisted conversation
@@ -7124,38 +7818,83 @@ var Think = class Think extends Agent {
7124
7818
  };
7125
7819
  }
7126
7820
  /**
7127
- * Persist an incoming message after reconciliation. For assistant
7128
- * messages, also resolve their ID against any server-side row that
7129
- * already owns the same `toolCallId` so we update the existing row
7130
- * instead of inserting an orphan duplicate.
7821
+ * Turn-start persistence of the client's transcript: reconcile the posted
7822
+ * messages against the server's active path, write only what changed, and
7823
+ * leave the live cache current. Returns `null` when a newer request
7824
+ * superseded this one part-way through (`isCurrent` turned false).
7825
+ *
7826
+ * Storage traffic here is independent of transcript length: the server
7827
+ * transcript comes from the live cache when it covers the path, unchanged
7828
+ * echoed messages are skipped before Sessions is asked, and the cache is
7829
+ * re-read only when it is windowed.
7131
7830
  */
7132
- async _persistIncomingMessage(msg, serverMessages) {
7133
- const sanitized = this._stripReservedMessageMetadata(msg);
7134
- const resolved = sanitized.role === "assistant" ? resolveToolMergeId(sanitized, serverMessages) : sanitized;
7135
- await this._upsertMessageInHistory(resolved);
7831
+ async _reconcileAndPersistIncoming(incomingMessages, options) {
7832
+ const spanAttributes = {
7833
+ "cloudflare.agents.component": "think",
7834
+ "cloudflare.agents.turn.request_id": options.requestId,
7835
+ "cloudflare.agents.turn.trigger": "ws-chat"
7836
+ };
7837
+ const serverMessages = await withAgentSpan(this, "load_chat_history", "interaction", spanAttributes, () => this._serverTranscriptForReconcile());
7838
+ const serverMessagesById = new Map(serverMessages.map((message) => [message.id, message]));
7839
+ const reconciled = reconcileMessages(incomingMessages, serverMessages, sanitizeMessage);
7840
+ let branchParentId;
7841
+ if (options.isRegeneration && reconciled.length > 0) branchParentId = reconciled[reconciled.length - 1].id;
7842
+ return await withAgentSpan(this, "persist_incoming_messages", "interaction", spanAttributes, async () => {
7843
+ if (!options.isCurrent()) return false;
7844
+ for (const msg of reconciled) {
7845
+ if (!options.isCurrent()) return false;
7846
+ await this._persistIncomingMessage(msg, serverMessages, serverMessagesById);
7847
+ }
7848
+ if (!options.isCurrent()) return false;
7849
+ if (!this._cacheCoversActivePath) await this._syncMessages();
7850
+ return true;
7851
+ }) ? { branchParentId } : null;
7136
7852
  }
7137
7853
  /**
7138
- * Strip {@link RESERVED_MESSAGE_METADATA_KEYS} from a client-supplied message
7139
- * at intake. Those keys are server-written turn context (stamped by
7140
- * `_stampChannel`) that hooks and recovery re-resolve and trust, so a client
7141
- * must never be able to forge them.
7854
+ * The server transcript that reconciliation diffs client messages against.
7855
+ * The live cache answers when it holds the whole active path — the common
7856
+ * case, kept current by the change feed after every durable write. A
7857
+ * windowed or unhydrated cache falls back to the full storage read, since
7858
+ * reconciliation must see every message (`_readMessagesFromStorage`).
7859
+ *
7860
+ * Returns a snapshot: the writes that follow patch the cache through the
7861
+ * change feed while the caller is still iterating.
7142
7862
  */
7143
- _stripReservedMessageMetadata(msg) {
7144
- const metadata = msg.metadata;
7145
- if (!metadata || !RESERVED_MESSAGE_METADATA_KEYS.some((key) => key in metadata)) return msg;
7146
- const rest = { ...metadata };
7147
- for (const key of RESERVED_MESSAGE_METADATA_KEYS) delete rest[key];
7148
- return {
7149
- ...msg,
7150
- metadata: rest
7151
- };
7863
+ async _serverTranscriptForReconcile() {
7864
+ if (this._cacheCoversActivePath) return [...this._cachedMessages];
7865
+ return this._readMessagesFromStorage();
7866
+ }
7867
+ /**
7868
+ * Persist an incoming message after reconciliation. For assistant
7869
+ * messages, also resolve their ID against any server-side row that
7870
+ * already owns the same `toolCallId` so we update the existing row
7871
+ * instead of inserting an orphan duplicate.
7872
+ *
7873
+ * A message whose stored form is what the server already holds is skipped
7874
+ * outright. The client posts its whole transcript on every request, so
7875
+ * without this every prior message would cost Sessions an existence read
7876
+ * plus a full-row compare (and, for media, a decode and hash of every
7877
+ * payload) per turn — reads spent discovering nothing changed.
7878
+ */
7879
+ async _persistIncomingMessage(msg, serverMessages, serverMessagesById) {
7880
+ const resolved = msg.role === "assistant" ? resolveToolMergeId(msg, serverMessages) : msg;
7881
+ const prior = serverMessagesById?.get(resolved.id);
7882
+ if (prior && JSON.stringify(prior) === JSON.stringify(stripReservedMetadata(sanitizeMessage(resolved)))) return;
7883
+ await this._upsertMessageInHistory(resolved, void 0, "client");
7884
+ }
7885
+ _persistRequestContextKey(key, value) {
7886
+ const json = value ? JSON.stringify(value) : void 0;
7887
+ if (this._persistedRequestContext[key] === json) return;
7888
+ if (json === void 0) this._configDelete(key);
7889
+ else this._configSet(key, json);
7890
+ this._persistedRequestContext[key] = json;
7152
7891
  }
7153
7892
  _persistClientTools() {
7154
- if (this._lastClientTools) this._configSet("lastClientTools", JSON.stringify(this._lastClientTools));
7155
- else this._configDelete("lastClientTools");
7893
+ this._persistRequestContextKey("lastClientTools", this._lastClientTools);
7156
7894
  }
7157
7895
  _restoreClientTools() {
7158
7896
  const raw = this._configGet("lastClientTools");
7897
+ this._persistedRequestContext.lastClientTools = raw;
7159
7898
  if (raw) try {
7160
7899
  this._lastClientTools = JSON.parse(raw);
7161
7900
  } catch {
@@ -7163,11 +7902,11 @@ var Think = class Think extends Agent {
7163
7902
  }
7164
7903
  }
7165
7904
  _persistBody() {
7166
- if (this._lastBody) this._configSet("lastBody", JSON.stringify(this._lastBody));
7167
- else this._configDelete("lastBody");
7905
+ this._persistRequestContextKey("lastBody", this._lastBody);
7168
7906
  }
7169
7907
  _restoreBody() {
7170
7908
  const raw = this._configGet("lastBody");
7909
+ this._persistedRequestContext.lastBody = raw;
7171
7910
  if (raw) try {
7172
7911
  this._lastBody = JSON.parse(raw);
7173
7912
  } catch {
@@ -7520,7 +8259,7 @@ var Think = class Think extends Agent {
7520
8259
  break;
7521
8260
  }
7522
8261
  if (target) this._scheduleAutoContinuation(target);
7523
- else this._runConnectionlessContinuation();
8262
+ else await this._queueConnectionlessContinuation();
7524
8263
  return true;
7525
8264
  }
7526
8265
  /**
@@ -7559,29 +8298,30 @@ var Think = class Think extends Agent {
7559
8298
  async _applyToolUpdateToMessages(update) {
7560
8299
  let broadcastMessage;
7561
8300
  const streaming = this._streamingAssistant;
8301
+ let accumulatorOwnsCall = false;
7562
8302
  if (streaming) {
7563
8303
  const accParts = streaming.parts;
7564
8304
  const result = applyToolUpdate(accParts, update);
7565
- if (result && result.parts[result.index] !== accParts[result.index]) {
7566
- accParts[result.index] = result.parts[result.index];
7567
- broadcastMessage = streaming.toMessage();
8305
+ if (result) {
8306
+ accumulatorOwnsCall = true;
8307
+ if (result.parts[result.index] !== accParts[result.index]) {
8308
+ accParts[result.index] = result.parts[result.index];
8309
+ broadcastMessage = streaming.toMessage();
8310
+ }
7568
8311
  }
7569
8312
  }
7570
- const history = await this._readMessagesFromStorage();
7571
- for (let i = 0; i < history.length; i++) {
7572
- const msg = history[i];
7573
- const msgParts = msg.parts;
7574
- const result = applyToolUpdate(msgParts, update);
7575
- if (result) {
7576
- if (result.parts[result.index] === msgParts[result.index]) break;
8313
+ const owner = await this._resolveToolCallOwner(update.toolCallId, accumulatorOwnsCall && streaming ? streaming.messageId : void 0);
8314
+ if (owner) {
8315
+ const ownerParts = owner.parts;
8316
+ const result = applyToolUpdate(ownerParts, update);
8317
+ if (result && result.parts[result.index] !== ownerParts[result.index]) {
7577
8318
  const updatedMsg = {
7578
- ...msg,
8319
+ ...owner,
7579
8320
  parts: result.parts
7580
8321
  };
7581
8322
  const safe = await this._updateMessageInHistory(updatedMsg);
7582
8323
  this._patchCachedMessage(safe);
7583
8324
  broadcastMessage = safe;
7584
- break;
7585
8325
  }
7586
8326
  }
7587
8327
  if (broadcastMessage) this._broadcast({
@@ -7589,6 +8329,55 @@ var Think = class Think extends Agent {
7589
8329
  message: broadcastMessage
7590
8330
  });
7591
8331
  }
8332
+ /**
8333
+ * The persisted message that owns `toolCallId`, read as one row — or
8334
+ * `null` when no persisted row owns it.
8335
+ *
8336
+ * Lookup order, cheapest first:
8337
+ *
8338
+ * 1. `liveMessageId`, when the in-flight accumulator owns the call. A row
8339
+ * under that id exists only when stall recovery persisted a partial
8340
+ * mid-stream. When it does not, the call is not on its own row — but a
8341
+ * provider can replay a prior tool round-trip into a fresh continuation
8342
+ * accumulator (#1404), so the persisted owner may still be an earlier
8343
+ * message; the cache is checked for that before concluding there is
8344
+ * nothing durable to update. Storage is never walked for a call the
8345
+ * live turn owns: every row it could target is on the cached path.
8346
+ * 2. The live cache, for the id only. Whatever names the row, the returned
8347
+ * message is always the STORED form: the apply must compare against
8348
+ * what storage holds, and the cache may be patched ahead of it.
8349
+ * 3. Storage, newest first, stopping at the first owner. Reached only when
8350
+ * the cache does not cover the active path (a windowed hydration, a
8351
+ * boot whose hydration failed, or rows imported behind the cache): a
8352
+ * cross-message result can target a row older than the window, and the
8353
+ * path is read from the leaf so a recent hit costs the rows it passed,
8354
+ * not the transcript.
8355
+ *
8356
+ * This is what keeps a long turn's tool updates independent of transcript
8357
+ * length: the previous shape re-read the whole path per update.
8358
+ */
8359
+ async _resolveToolCallOwner(toolCallId, liveMessageId) {
8360
+ const owns = (message) => message.parts.some((part) => part.toolCallId === toolCallId);
8361
+ const stored = async (id) => {
8362
+ const row = await this.session.getMessage(id);
8363
+ return row && owns(row) ? row : null;
8364
+ };
8365
+ const cachedOwnerId = () => {
8366
+ for (let i = this._cachedMessages.length - 1; i >= 0; i--) if (owns(this._cachedMessages[i])) return this._cachedMessages[i].id;
8367
+ return null;
8368
+ };
8369
+ if (liveMessageId !== void 0) {
8370
+ const live = await stored(liveMessageId);
8371
+ if (live) return live;
8372
+ const cachedId = cachedOwnerId();
8373
+ return cachedId === null ? null : stored(cachedId);
8374
+ }
8375
+ const cachedId = cachedOwnerId();
8376
+ if (cachedId !== null) return stored(cachedId);
8377
+ if (this._cacheCoversActivePath) return null;
8378
+ for await (const message of this.session.history({ newestFirst: true })) if (owns(message)) return message;
8379
+ return null;
8380
+ }
7592
8381
  hasPendingInteraction() {
7593
8382
  const clientResolvable = this._clientResolvableToolNames();
7594
8383
  const streaming = this._streamingAssistant;
@@ -7677,33 +8466,38 @@ var Think = class Think extends Agent {
7677
8466
  * recomputed from the live, mutable transcript. Compaction collapses older
7678
8467
  * assistant messages into a summary, lowering the count — so a turn that had
7679
8468
  * genuinely advanced could read as "no progress" between attempts and exhaust
7680
- * its budget prematurely (#1628). Instead we read a durably-persisted counter
7681
- * that only ever increments — bumped at production time when new content is
7682
- * durably flushed (see `_storeChunkDurably`), which is genuine forward
7683
- * progress and is immune to client reconnects / recovery re-persists — so
7684
- * compaction can never lower it and a reconnect can't fake it (#1637).
8469
+ * its budget prematurely (#1628). It then became a KV counter bumped per
8470
+ * credited chunk. It is now derived from the stream log the chunks were
8471
+ * already flushed to (`ResumableStream.progressMarker`): the log only grows
8472
+ * when new content lands durably, a reconnect replay or a recovery
8473
+ * re-persist reads it without appending (#1637), and compaction rewrites
8474
+ * the transcript, not the log. Nothing is written per chunk.
8475
+ *
8476
+ * The pre-derivation KV counter is folded in once per isolate, so a marker
8477
+ * an in-flight incident already recorded is never read lower after the
8478
+ * upgrade.
7685
8479
  */
7686
8480
  async _chatRecoveryProgressMarker() {
7687
- return readChatRecoveryProgress(this.ctx.storage);
7688
- }
7689
- /** Advance the durable recovery-progress counter. Called from
7690
- * `_storeChunkDurably` when a stored chunk credits forward progress under the
7691
- * shared rule (real, reconnect-immune forward progress). The increment lives
7692
- * in the shared engine (agents/chat); this is the package binding. */
7693
- async _bumpChatRecoveryProgress() {
7694
- return bumpChatRecoveryProgress(this.ctx.storage);
8481
+ this._progressSeed ??= readChatRecoveryProgress(this.ctx.storage).then((legacy) => this._resumableStream.seedProgress(legacy), (error) => {
8482
+ this._progressSeed = null;
8483
+ throw error;
8484
+ });
8485
+ await this._progressSeed;
8486
+ return this._resumableStream.progressMarker();
7695
8487
  }
7696
8488
  /**
7697
8489
  * N9: forwarding a sub-agent's chunks IS forward progress for this parent
7698
8490
  * turn, so credit the parent's recovery progress marker — otherwise a parent
7699
8491
  * whose turn merely `await`s a child banks no progress of its own and its
7700
- * no-progress window exhausts while the child is healthily streaming. Only
8492
+ * no-progress window exhausts while the child is healthily streaming. The
8493
+ * child's output goes to clients, not to this object's stream log, so the
8494
+ * derived marker cannot see it; this is the one explicit credit left. Only
7701
8495
  * invoked after a child actually produced output (see
7702
8496
  * `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.
7703
8497
  * Throttled (and reset per isolate) so we never write storage per token.
7704
8498
  */
7705
8499
  async _onAgentToolStreamProgress() {
7706
- if (this._agentToolStreamProgress.shouldCredit(Date.now())) await this._bumpChatRecoveryProgress();
8500
+ if (this._agentToolStreamProgress.shouldCredit(Date.now())) this._resumableStream.creditProgress();
7707
8501
  }
7708
8502
  async _beginChatRecoveryIncident(input) {
7709
8503
  return this._chatRecoveryEngine().beginIncident(input);
@@ -7732,9 +8526,7 @@ var Think = class Think extends Agent {
7732
8526
  recoveryKind: event.recoveryKind,
7733
8527
  ...event.reason ? { reason: event.reason } : {}
7734
8528
  }),
7735
- scheduleRecovery: async (callback, data, reason, delaySeconds) => {
7736
- await this.schedule(delaySeconds, callback, data, chatRecoverySchedulePolicy(reason));
7737
- },
8529
+ scheduleRecovery: (callback, data, reason, delaySeconds) => this._enqueueChatRecovery(callback, data, reason, delaySeconds),
7738
8530
  setRecovering: (active, requestId) => this._setChatRecovering(active, requestId),
7739
8531
  onShouldKeepRecoveringError: (error) => console.error("[Think] chatRecovery shouldKeepRecovering hook threw", error),
7740
8532
  exhaustChatRecovery: (incident, config, partial, streamId, createdAt) => this._exhaustChatRecovery(incident, config, partial, streamId, createdAt),
@@ -7809,7 +8601,7 @@ var Think = class Think extends Agent {
7809
8601
  }, input.streamId, incident.firstSeenAt);
7810
8602
  return "exhausted";
7811
8603
  }
7812
- const recoveredRequestId = this._hasRunningSubmission(recoveryRootRequestId) ? recoveryRootRequestId : void 0;
8604
+ const recoveredRequestId = this._readRunningSubmissionForRecovery(recoveryRootRequestId)?.submission_id;
7813
8605
  await this._chatRecoveryEngine().scheduleRecovery({
7814
8606
  incident,
7815
8607
  recoveryKind: "continue",
@@ -7874,14 +8666,10 @@ var Think = class Think extends Agent {
7874
8666
  let streamId = "";
7875
8667
  let streamStatus;
7876
8668
  if (requestId) {
7877
- const rows = this.sql`
7878
- SELECT id, status FROM cf_ai_chat_stream_metadata
7879
- WHERE request_id = ${requestId}
7880
- ORDER BY created_at DESC LIMIT 1
7881
- `;
7882
- if (rows.length > 0) {
7883
- streamId = rows[0].id;
7884
- streamStatus = rows[0].status;
8669
+ const info = this._resumableStream.latestStreamInfoForRequest(requestId);
8670
+ if (info) {
8671
+ streamId = info.id;
8672
+ streamStatus = info.status;
7885
8673
  }
7886
8674
  }
7887
8675
  if (!streamId && this._resumableStream.hasActiveStream()) {
@@ -7896,14 +8684,20 @@ var Think = class Think extends Agent {
7896
8684
  };
7897
8685
  }
7898
8686
  /**
7899
- * Classify a recovered turn as `retry` or `continue`. A pre-stream turn with no
7900
- * partial re-runs its user message (`retryTargetUserId`), unless the stream is
7901
- * already terminal — a terminal stream is never retried (it completed), only
7902
- * its submission is reconciled in dispatch.
8687
+ * Classify a recovered turn as `retry` or `continue`. A turn that left no
8688
+ * persisted partial re-runs its user message (`retryTargetUserId`), unless
8689
+ * the stream is already terminal — a terminal stream is never retried (it
8690
+ * completed), only its submission is reconciled in dispatch.
8691
+ *
8692
+ * The stream row is opened before inference, so an interrupted turn can
8693
+ * have a stream id and still nothing to continue from; what decides retry is
8694
+ * the absence of persisted content and a leaf that is still the turn's user
8695
+ * message. Mirrors `AIChatAgent`'s empty-partial new-turn rule (#1691): a
8696
+ * `continue` here would find no assistant message and skip the turn.
7903
8697
  */
7904
8698
  async _classifyRecoveredThinkTurn(input) {
7905
8699
  const streamIsTerminal = input.streamStatus === "completed" || input.streamStatus === "error";
7906
- const retryTargetUserId = await this._recoverablePreStreamUserId(input.snapshot, input.streamId, input.partial);
8700
+ const retryTargetUserId = await this._recoverablePreStreamUserId(input.snapshot, input.partial);
7907
8701
  return {
7908
8702
  recoveryKind: retryTargetUserId !== null && !streamIsTerminal ? "retry" : "continue",
7909
8703
  detail: { retryTargetUserId }
@@ -7925,9 +8719,9 @@ var Think = class Think extends Agent {
7925
8719
  const lastLeaf = shouldRetry ? null : await this.session.getLatestLeaf();
7926
8720
  const targetId = lastLeaf?.role === "assistant" && !streamIsTerminal ? lastLeaf.id : void 0;
7927
8721
  const canContinue = !shouldRetry && options.continue !== false && !streamIsTerminal;
7928
- const hasRunningSubmission = this._hasRunningSubmission(recoveryRootRequestId);
7929
- if (streamIsTerminal && hasRunningSubmission) await this._completeRecoveredSubmission(recoveryRootRequestId, streamStatus === "completed" ? "completed" : "error", requestId, streamStatus === "completed" ? null : "Recovered chat stream had already errored.");
7930
- const recoveredRequestId = (canContinue || shouldRetry) && hasRunningSubmission ? recoveryRootRequestId : void 0;
8722
+ const recoveredSubmission = this._readRunningSubmissionForRecovery(recoveryRootRequestId);
8723
+ if (streamIsTerminal && recoveredSubmission) await this._completeRecoveredSubmission(recoveryRootRequestId, streamStatus === "completed" ? "completed" : "error", requestId, streamStatus === "completed" ? null : "Recovered chat stream had already errored.");
8724
+ const recoveredRequestId = (canContinue || shouldRetry) && recoveredSubmission ? recoveredSubmission.submission_id : void 0;
7931
8725
  if (shouldRetry) await this._chatRecoveryEngine().scheduleRecovery({
7932
8726
  incident,
7933
8727
  recoveryKind: input.recoveryKind,
@@ -7970,8 +8764,8 @@ var Think = class Think extends Agent {
7970
8764
  });
7971
8765
  } else await this._updateChatRecoveryIncident(incident.incidentId, "skipped", streamIsTerminal ? "stream_terminal" : "not_recoverable");
7972
8766
  }
7973
- async _recoverablePreStreamUserId(snapshot, streamId, partial) {
7974
- if (!snapshot || snapshot.continuation || !snapshot.latestUserMessageId || streamId || partial.text || partial.parts.length > 0) return null;
8767
+ async _recoverablePreStreamUserId(snapshot, partial) {
8768
+ if (!snapshot || snapshot.continuation || !snapshot.latestUserMessageId || partial.text || partial.parts.length > 0) return null;
7975
8769
  const lastLeaf = await this.session.getLatestLeaf();
7976
8770
  return lastLeaf?.role === "user" && lastLeaf.id === snapshot.latestUserMessageId ? snapshot.latestUserMessageId : null;
7977
8771
  }
@@ -8069,10 +8863,10 @@ var Think = class Think extends Agent {
8069
8863
  * `_exhaustChatRecovery` entirely — so an app relying on `onExhausted` for the
8070
8864
  * terminal banner regressed to an eternal spinner when recovery gave up under
8071
8865
  * extreme churn. The error path matters just as much: a non-transient throw
8072
- * in a recovery callback is SWALLOWED by `Agent._executeScheduleCallback`
8073
- * (only a platform transient is re-thrown to preserve the one-shot row), so
8074
- * without routing it here the alarm row is deleted with no terminal UX at
8075
- * all — the half-finished message wedges silently. Shared by
8866
+ * in a recovery callback is SWALLOWED by the driving Task attempt (or the
8867
+ * routed one-shot schedule row) — only a platform transient is re-thrown to
8868
+ * preserve it — so without routing it here the run/row settles with no
8869
+ * terminal UX at all — the half-finished message wedges silently. Shared by
8076
8870
  * `_chatRecoveryRetry` and `_chatRecoveryContinue`.
8077
8871
  *
8078
8872
  * Exactly-once terminalization is defended by two independent guards:
@@ -8090,8 +8884,9 @@ var Think = class Think extends Agent {
8090
8884
  * Residual at-least-once edges, all deliberately accepted as "deliver a
8091
8885
  * second banner" ≫ "silently drop the turn":
8092
8886
  * • No `incidentId` at all in the payload (only reachable via a direct/test
8093
- * invocation — every production scheduler carries one): the synthesized
8094
- * incident can't be persisted (no key), so guard #1 can't arm.
8887
+ * invocation — every production recovery enqueue carries one): the
8888
+ * synthesized incident can't be persisted (no key), so guard #1 can't
8889
+ * arm.
8095
8890
  * • The record is swept AGAIN between two alarms (guard #1 re-persists on the
8096
8891
  * first, so this needs a second independent sweep) — vanishingly unlikely.
8097
8892
  * • A platform transient interrupts `_exhaustChatRecovery` after the banner
@@ -8099,18 +8894,25 @@ var Think = class Think extends Agent {
8099
8894
  * (the terminal writes themselves are idempotent).
8100
8895
  */
8101
8896
  /**
8102
- * Recovery continuation callbacks the alarm-boundary OOM circuit breaker may
8103
- * back off / purge (#1825). See `Agent._cf_handleAlarmMemoryLimitReset`.
8897
+ * Host memory-limit policy hook (#1825), dispatched structurally by
8898
+ * Lifecycle's circuit breaker — protected because it is framework
8899
+ * machinery, not part of the public Think API. Tasks applies the breaker to
8900
+ * root recovery runs; the routed dynamic-agent fallback applies it to
8901
+ * `recoveryLoop` schedule rows (see `RecoveryLoopScheduleOptions`). At the
8902
+ * strike budget this hook seals active incidents via
8903
+ * {@link _cf_sealMemoryLimitedRecovery}.
8104
8904
  */
8105
- _cf_recoveryAlarmCallbacks() {
8106
- return ["_chatRecoveryContinue", "_chatRecoveryRetry"];
8905
+ async onAlarmMemoryLimit(context) {
8906
+ if (!context.sealed) return;
8907
+ await this._cf_sealMemoryLimitedRecovery();
8107
8908
  }
8108
8909
  /**
8109
- * Seal any still-live recovery incident as an out-of-memory exhaustion when
8110
- * the alarm circuit breaker trips at its strike budget (#1825). Runs at the
8111
- * outermost alarm frame (post-unwind), so the terminal banner / `onExhausted`
8112
- * and the sealed-incident write can land where the mid-turn give-up's writes
8113
- * OOMed. Reuses the shared give-up spine via `_exhaustRecoveryGiveUp`.
8910
+ * Seal any still-live recovery incident as an out-of-memory exhaustion
8911
+ * when the alarm circuit breaker trips at its strike budget (#1825). Runs
8912
+ * at the outermost alarm frame (post-unwind), so the terminal banner /
8913
+ * `onExhausted` and the sealed-incident write can land where the mid-turn
8914
+ * give-up's writes OOMed. Reuses the shared give-up spine via
8915
+ * `_exhaustRecoveryGiveUp`.
8114
8916
  */
8115
8917
  async _cf_sealMemoryLimitedRecovery() {
8116
8918
  const active = await listActiveChatRecoveryIncidents(this.ctx.storage);
@@ -8182,24 +8984,24 @@ var Think = class Think extends Agent {
8182
8984
  * deploy code-update reset / script supersede, a `retryable`-flagged
8183
8985
  * platform error, or "Network connection lost.", looking through wrappers
8184
8986
  * like `SqlError` via the `cause` chain) is re-thrown (after best-effort
8185
- * marking the incident `failed` for observability) so
8186
- * `Agent._executeScheduleCallback` preserves the one-shot alarm row and
8187
- * the platform re-runs recovery once it is healthy again — the turn can
8987
+ * marking the incident `failed` for observability) so the current
8988
+ * attempt (the driving Task run, or the routed one-shot schedule row) is
8989
+ * preserved and the platform re-runs recovery once it is healthy again — the turn can
8188
8990
  * still recover, so it must NOT terminalize. Terminalizing here was the
8189
8991
  * #1730 freeze: the give-up's own seal needs the very storage that is
8190
8992
  * down, so it throws too, burns the in-process retry budget inside the
8191
8993
  * same reset window, and the row is consumed milliseconds before storage
8192
8994
  * recovers. The submission is deliberately left `running` — the deferred
8193
- * re-run reads it via `_readRunningSubmissionByRequestId`, so marking it
8995
+ * re-run reads it via `_readRunningSubmissionForRecovery`, so marking it
8194
8996
  * terminal here would turn the preserved row into a guaranteed
8195
8997
  * `submission_not_running` no-op skip (a self-defeating defer).
8196
8998
  * - Any OTHER (application) error is terminalized through the give-up path
8197
8999
  * (`onExhausted` + the `terminalMessage` banner) and NOT re-thrown. This is
8198
- * the fix for the silent-seal failure mode: `_executeScheduleCallback`
8199
- * swallows a non-transient throw and then `alarm()` deletes the one-shot
8200
- * row, so without terminalizing here the half-finished turn is dropped
8201
- * with no terminal event and no banner (the user stares at a frozen
8202
- * message until they send something new).
9000
+ * the fix for the silent-seal failure mode: the driving attempt swallows
9001
+ * a non-transient throw and settles without terminalizing, so without
9002
+ * terminalizing here the half-finished turn is dropped with no terminal
9003
+ * event and no banner (the user stares at a frozen message until they
9004
+ * send something new).
8203
9005
  */
8204
9006
  async _handleRecoveryCallbackError(callback, data, error) {
8205
9007
  if (await this._handleRecoveryOom(callback, data, error)) return;
@@ -8215,8 +9017,36 @@ var Think = class Think extends Agent {
8215
9017
  console.error(`[Think] ${callback} threw during recovery; terminalizing instead of leaving the turn wedged`, error);
8216
9018
  await this._exhaustRecoveryGiveUp(callback, data, "recovery_error");
8217
9019
  }
9020
+ /**
9021
+ * Keep the recovery callback as owner until a chat Task or facet fiber is durably
9022
+ * accepted. At acceptance, move the running submission to the successor's
9023
+ * request identity before signaling handoff. If an override never starts a
9024
+ * durable successor, the signal stays inert and the callback owns the work
9025
+ * until the override returns.
9026
+ */
9027
+ async _runRecoveredTurnAfterAcceptance(recoveredSubmission, onTurnStarted, run) {
9028
+ let signaled = false;
9029
+ const onAccepted = (successorRequestId) => {
9030
+ if (signaled) return;
9031
+ signaled = true;
9032
+ if (recoveredSubmission) this.sql`
9033
+ UPDATE cf_think_submissions
9034
+ SET request_id = ${successorRequestId}
9035
+ WHERE submission_id = ${recoveredSubmission.submission_id}
9036
+ AND status = 'running'
9037
+ `;
9038
+ onTurnStarted?.();
9039
+ };
9040
+ return recoveredTurnAcceptanceContext.run({
9041
+ agent: this,
9042
+ onAccepted
9043
+ }, run);
9044
+ }
8218
9045
  async _chatRecoveryRetry(data) {
8219
- const recoveredSubmission = data?.recoveredRequestId ? this._readRunningSubmissionByRequestId(data.recoveredRequestId) : null;
9046
+ await this._dispatchChatRecovery("_chatRecoveryRetry", data, (onTurnStarted) => this._chatRecoveryRetryDetached(data, onTurnStarted));
9047
+ }
9048
+ async _chatRecoveryRetryDetached(data, onTurnStarted) {
9049
+ const recoveredSubmission = data?.recoveredRequestId ? this._readRunningSubmissionForRecovery(data.recoveredRequestId) : null;
8220
9050
  if (data?.recoveredRequestId && !recoveredSubmission) {
8221
9051
  await this._updateChatRecoveryIncident(data.incidentId, "skipped", "submission_not_running");
8222
9052
  return;
@@ -8245,12 +9075,12 @@ var Think = class Think extends Agent {
8245
9075
  return;
8246
9076
  }
8247
9077
  this._applyRecoveredRequestContext(data);
8248
- const result = await this._retryLastUserTurn(this._lastClientTools, this._lastBody, controller ? {
9078
+ const result = await this._runRecoveredTurnAfterAcceptance(recoveredSubmission, onTurnStarted, () => this._retryLastUserTurn(this._lastClientTools, this._lastBody, controller ? {
8249
9079
  signal: controller.signal,
8250
9080
  trigger: "recovery-retry"
8251
- } : { trigger: "recovery-retry" });
9081
+ } : { trigger: "recovery-retry" }));
8252
9082
  await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
8253
- if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : result.error ?? `Recovery retry ${result.status}.`);
9083
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(recoveredSubmission ?? data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : result.error ?? `Recovery retry ${result.status}.`);
8254
9084
  } catch (error) {
8255
9085
  await this._handleRecoveryCallbackError("_chatRecoveryRetry", data, error);
8256
9086
  } finally {
@@ -8259,74 +9089,90 @@ var Think = class Think extends Agent {
8259
9089
  await this._reconcileOwnStaleAgentToolChildRuns();
8260
9090
  }
8261
9091
  }
8262
- _hasRunningSubmission(requestId) {
8263
- return this._readRunningSubmissionByRequestId(requestId) !== null;
8264
- }
8265
- _readRunningSubmissionByRequestId(requestId) {
9092
+ /**
9093
+ * Recovery payloads retain the original submission/root identity while
9094
+ * request_id follows the accepted successor. Match both so released payloads,
9095
+ * redeferred callbacks, and exhaustion can still locate the running row.
9096
+ * Exact submission identity wins even when terminal: a redelivery must not
9097
+ * fall through to another submission whose successor request collides.
9098
+ */
9099
+ _readRunningSubmissionForRecovery(recoveredRequestId) {
8266
9100
  this._ensureSubmissionTable();
8267
- return this.sql`
9101
+ const rows = this.sql`
8268
9102
  SELECT submission_id, idempotency_key, request_id, stream_id, status,
8269
9103
  messages_json, metadata_json, error_message, created_at,
8270
- messages_applied_at, started_at, completed_at
9104
+ messages_applied_at, started_at, completed_at, result_status, output_json
8271
9105
  FROM cf_think_submissions
8272
- WHERE request_id = ${requestId}
8273
- AND status = 'running'
9106
+ WHERE submission_id = ${recoveredRequestId}
9107
+ OR (request_id = ${recoveredRequestId} AND status = 'running')
9108
+ ORDER BY (submission_id = ${recoveredRequestId}) DESC
8274
9109
  LIMIT 1
8275
- `[0] ?? null;
9110
+ `;
9111
+ return rows[0]?.status === "running" ? rows[0] : null;
8276
9112
  }
8277
- async _markRecoveredSubmissionInterrupted(requestId, message) {
8278
- this._ensureSubmissionTable();
8279
- const row = this.sql`
8280
- SELECT submission_id, idempotency_key, request_id, stream_id, status,
8281
- messages_json, metadata_json, error_message, created_at,
8282
- messages_applied_at, started_at, completed_at
8283
- FROM cf_think_submissions
8284
- WHERE request_id = ${requestId}
8285
- AND status = 'running'
8286
- LIMIT 1
8287
- `[0];
9113
+ async _markRecoveredSubmissionInterrupted(recoveredRequestId, message) {
9114
+ const row = this._readRunningSubmissionForRecovery(recoveredRequestId);
8288
9115
  if (!row) return;
8289
9116
  this.sql`
8290
9117
  UPDATE cf_think_submissions
8291
9118
  SET status = 'error',
8292
9119
  error_message = ${message},
8293
- completed_at = ${Date.now()}
9120
+ completed_at = ${Date.now()},
9121
+ result_status = NULL,
9122
+ output_json = NULL
8294
9123
  WHERE submission_id = ${row.submission_id}
8295
9124
  AND status = 'running'
8296
9125
  `;
8297
9126
  const updated = this._readSubmission(row.submission_id);
8298
- if (updated) await this._emitSubmissionStatus(updated);
9127
+ if (updated?.status === "error") {
9128
+ this._enqueueTerminalWorkflowNotification(updated);
9129
+ await this._emitSubmissionStatus(updated);
9130
+ }
8299
9131
  }
8300
- async _completeRecoveredSubmission(originalRequestId, status, requestId, errorMessage) {
8301
- this._ensureSubmissionTable();
9132
+ async _completeRecoveredSubmission(recoveredSubmission, status, requestId, errorMessage) {
9133
+ const row = typeof recoveredSubmission === "string" ? this._readRunningSubmissionForRecovery(recoveredSubmission) : this._readSubmission(recoveredSubmission.submission_id);
9134
+ if (row?.status !== "running") return;
9135
+ let output;
9136
+ if (row.result_status === "completed" || row.result_status === "aborted") {
9137
+ status = row.result_status;
9138
+ errorMessage = null;
9139
+ if (status === "completed" && row.output_json !== null) output = JSON.parse(row.output_json);
9140
+ } else if (row.result_status === "error" && status === "completed") {
9141
+ status = "error";
9142
+ errorMessage = "Recovered chat stream had already errored.";
9143
+ } else if (row.result_status === "retry" && status === "completed") {
9144
+ if (row.request_id && this._hasRecoverableChatTurn(row.request_id) && this._hasFreshRecoverableSubmissionEvidence(row) || await this._hasScheduledChatRecovery(row)) return;
9145
+ await this._markRecoveredSubmissionInterrupted(row.submission_id, "Submission was interrupted after messages were applied.");
9146
+ return;
9147
+ }
8302
9148
  const completedAt = Date.now();
8303
- const streamId = requestId ? this._resumableStream.getAllStreamMetadata().find((metadata) => metadata.request_id === requestId)?.id ?? null : null;
8304
- this.sql`
8305
- UPDATE cf_think_submissions
8306
- SET status = ${status},
8307
- request_id = COALESCE(${requestId}, request_id),
8308
- stream_id = COALESCE(${streamId}, stream_id),
8309
- error_message = ${errorMessage},
8310
- completed_at = ${completedAt}
8311
- WHERE request_id = ${originalRequestId}
8312
- AND status = 'running'
8313
- `;
8314
- const updated = this.sql`
8315
- SELECT submission_id, idempotency_key, request_id, stream_id, status,
8316
- messages_json, metadata_json, error_message, created_at,
8317
- messages_applied_at, started_at, completed_at
8318
- FROM cf_think_submissions
8319
- WHERE request_id = COALESCE(${requestId}, ${originalRequestId})
8320
- ORDER BY completed_at DESC
8321
- LIMIT 1
8322
- `[0];
9149
+ const streamId = requestId ? this._resumableStream.latestStreamInfoForRequest(requestId)?.id ?? null : null;
9150
+ this.ctx.storage.transactionSync(() => {
9151
+ this.sql`
9152
+ UPDATE cf_think_submissions
9153
+ SET status = ${status},
9154
+ request_id = COALESCE(${requestId}, request_id),
9155
+ stream_id = COALESCE(${streamId}, stream_id),
9156
+ error_message = ${errorMessage},
9157
+ completed_at = ${completedAt},
9158
+ result_status = NULL,
9159
+ output_json = NULL
9160
+ WHERE submission_id = ${row.submission_id}
9161
+ AND status = 'running'
9162
+ `;
9163
+ this._enqueueTerminalWorkflowNotification(this._readSubmission(row.submission_id), output);
9164
+ });
9165
+ const updated = this._readSubmission(row.submission_id);
8323
9166
  if (updated && this._isTerminalSubmissionStatus(updated.status)) await this._emitSubmissionStatus(updated);
8324
9167
  }
8325
9168
  async onChatRecovery(_ctx) {
8326
9169
  return {};
8327
9170
  }
8328
9171
  async _chatRecoveryContinue(data) {
8329
- const recoveredSubmission = data?.recoveredRequestId ? this._readRunningSubmissionByRequestId(data.recoveredRequestId) : null;
9172
+ await this._dispatchChatRecovery("_chatRecoveryContinue", data, (onTurnStarted) => this._chatRecoveryContinueDetached(data, onTurnStarted));
9173
+ }
9174
+ async _chatRecoveryContinueDetached(data, onTurnStarted) {
9175
+ const recoveredSubmission = data?.recoveredRequestId ? this._readRunningSubmissionForRecovery(data.recoveredRequestId) : null;
8330
9176
  if (data?.recoveredRequestId && !recoveredSubmission) {
8331
9177
  await this._updateChatRecoveryIncident(data.incidentId, "skipped", "submission_not_running");
8332
9178
  return;
@@ -8353,12 +9199,12 @@ var Think = class Think extends Agent {
8353
9199
  return;
8354
9200
  }
8355
9201
  this._applyRecoveredRequestContext(data);
8356
- const result = await this.continueLastTurn(void 0, controller ? {
9202
+ const result = await this._runRecoveredTurnAfterAcceptance(recoveredSubmission, onTurnStarted, () => this.continueLastTurn(void 0, controller ? {
8357
9203
  signal: controller.signal,
8358
9204
  trigger: "recovery-continue"
8359
- } : { trigger: "recovery-continue" });
9205
+ } : { trigger: "recovery-continue" }));
8360
9206
  await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
8361
- if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : result.error ?? `Recovery ${result.status}.`);
9207
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(recoveredSubmission ?? data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : result.error ?? `Recovery ${result.status}.`);
8362
9208
  } catch (error) {
8363
9209
  await this._handleRecoveryCallbackError("_chatRecoveryContinue", data, error);
8364
9210
  } finally {
@@ -8527,54 +9373,59 @@ var Think = class Think extends Agent {
8527
9373
  this._autoContinuation.activateDeferredAndReschedule();
8528
9374
  }
8529
9375
  /**
8530
- * Run a continuation turn that does NOT require a live client connection.
9376
+ * Queue a continuation turn that does NOT require a live client connection.
8531
9377
  *
8532
9378
  * Used when a durable approval (a paused action or codemode execution) is
8533
9379
  * resolved via RPC from a surface with no open chat socket — e.g. an ops
8534
9380
  * dashboard, a webhook, or a voice backend approving hours/days later. The
8535
- * connection-bound auto-continuation barrier (`_fireAutoContinuation`) cannot
8536
- * fire without a `Connection`, so this mirrors its turn body but streams via
8537
- * `broadcast` (a no-op when nobody is attached) and always persists, so a
8538
- * client that reconnects later resumes the continued turn from history.
8539
- *
8540
- * Wrapped in `keepAliveWhile` because the resolving RPC returns before the
8541
- * continuation finishes (mirrors the submission-drain pattern).
9381
+ * item is durable, so the turn still runs if the object leaves memory
9382
+ * before the alarm fires; the last request body and client tools it needs
9383
+ * are persisted config, restored on start. Approvals landing while one
9384
+ * continuation is pending or running coalesce onto the single item.
8542
9385
  */
8543
- _runConnectionlessContinuation() {
8544
- this.keepAliveWhile(async () => {
8545
- const requestId = crypto.randomUUID();
8546
- const abortSignal = this._aborts.getSignal(requestId);
8547
- try {
8548
- await this._admitTurn({
8549
- admission: "queue",
8550
- trigger: "auto-continuation",
8551
- requestId,
8552
- continuation: true,
8553
- allowNested: true,
8554
- execute: async () => {
8555
- const continuationBody = async () => {
8556
- const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
8557
- agent: this,
8558
- connection: void 0,
8559
- request: void 0,
8560
- email: void 0
8561
- }, () => this._runInferenceLoop({
8562
- signal: abortSignal,
8563
- clientTools: this._lastClientTools,
8564
- body: this._lastBody,
8565
- continuation: true
8566
- }));
8567
- if (result) await this._streamResult(requestId, result, abortSignal, { continuation: true });
8568
- };
8569
- await this._runChatRecoveryFiber(requestId, true, continuationBody);
8570
- }
8571
- });
8572
- } catch (error) {
8573
- console.error("[Think] Connection-less continuation failed:", error);
8574
- } finally {
8575
- this._aborts.remove(requestId);
8576
- }
8577
- });
9386
+ async _queueConnectionlessContinuation() {
9387
+ await this.queue(CONNECTIONLESS_CONTINUATION_CALLBACK, void 0, { id: "connectionless-continuation" });
9388
+ }
9389
+ /**
9390
+ * Run one connection-less continuation turn. Mirrors the connection-bound
9391
+ * auto-continuation turn body but streams via `broadcast` (a no-op when
9392
+ * nobody is attached) and always persists, so a client that reconnects
9393
+ * later resumes the continued turn from history.
9394
+ * @internal Queue callback.
9395
+ */
9396
+ async _cfRunConnectionlessContinuation() {
9397
+ const requestId = crypto.randomUUID();
9398
+ const abortSignal = this._aborts.getSignal(requestId);
9399
+ try {
9400
+ await this._admitTurn({
9401
+ admission: "queue",
9402
+ trigger: "auto-continuation",
9403
+ requestId,
9404
+ continuation: true,
9405
+ allowNested: true,
9406
+ execute: async () => {
9407
+ const continuationBody = async () => {
9408
+ const result = await __DO_NOT_USE_WILL_BREAK__agentContext.run({
9409
+ agent: this,
9410
+ connection: void 0,
9411
+ request: void 0,
9412
+ email: void 0
9413
+ }, () => this._runInferenceLoop({
9414
+ signal: abortSignal,
9415
+ clientTools: this._lastClientTools,
9416
+ body: this._lastBody,
9417
+ continuation: true
9418
+ }));
9419
+ if (result) await this._streamResult(requestId, result, abortSignal, { continuation: true });
9420
+ };
9421
+ await this._runChatRecoveryFiber(requestId, true, continuationBody);
9422
+ }
9423
+ });
9424
+ } catch (error) {
9425
+ console.error("[Think] Connection-less continuation failed:", error);
9426
+ } finally {
9427
+ this._aborts.remove(requestId);
9428
+ }
8578
9429
  }
8579
9430
  /**
8580
9431
  * Render a reply attachment ({@link ReplyAttachment}) for delivery to the
@@ -8755,45 +9606,34 @@ var Think = class Think extends Agent {
8755
9606
  _startResumableStream(requestId, options) {
8756
9607
  const streamId = this._resumableStream.start(requestId, options);
8757
9608
  this._preStream.flushOnStreamStart((c) => this._notifyStreamResuming(c));
8758
- this._ensureStreamCleanupScheduled();
8759
9609
  return streamId;
8760
9610
  }
8761
- /**
8762
- * Mark a resumable stream completed and arm buffer cleanup. Wrapper around
8763
- * `ResumableStream.complete` so every stream-finish path also schedules the
8764
- * cleanup alarm (#1706).
8765
- */
9611
+ /** Mark a resumable stream completed (settled now, rows kept until reclaim). */
8766
9612
  _completeResumableStream(streamId) {
8767
9613
  this._resumableStream.complete(streamId);
8768
- this._ensureStreamCleanupScheduled();
8769
9614
  }
8770
9615
  /**
8771
- * Mark a resumable stream errored and arm buffer cleanup. Wrapper around
8772
- * `ResumableStream.markError` — see {@link _completeResumableStream}.
9616
+ * The producer finished; leave the row for the cutover that persists the
9617
+ * assistant message (`_persistAssistantMessageWithCutover`). Every path
9618
+ * that calls this must end in that cutover or `finalizePending()`.
8773
9619
  */
8774
- _errorResumableStream(streamId) {
8775
- this._resumableStream.markError(streamId);
8776
- this._ensureStreamCleanupScheduled();
9620
+ _finishResumableStream(streamId) {
9621
+ this._resumableStream.finish(streamId);
8777
9622
  }
8778
- /**
8779
- * Ensure a single cleanup alarm is pending for this DO's resumable-stream
8780
- * buffers. Armed whenever a stream finishes so that idle/one-off chat DOs
8781
- * still reclaim their buffers — the lazy sweep in {@link ResumableStream}
8782
- * only fires when a *subsequent* stream completes, which never happens for a
8783
- * chat that receives a single turn (#1706).
8784
- *
8785
- * `idempotent` dedupes on (callback, payload, owner) so repeated finishes
8786
- * collapse onto one pending alarm rather than stacking.
8787
- */
8788
- async _ensureStreamCleanupScheduled({ idempotent = true } = {}) {
8789
- await this.schedule(STREAM_CLEANUP_DELAY_SECONDS, "_cleanupStreamBuffers", void 0, { idempotent });
9623
+ /** Mark a resumable stream errored. */
9624
+ _errorResumableStream(streamId, requestId) {
9625
+ this.ctx.storage.transactionSync(() => {
9626
+ this._resumableStream.markError(streamId);
9627
+ if (requestId) this._recordSubmissionTurnResult(requestId, { status: "error" });
9628
+ });
8790
9629
  }
8791
9630
  /**
8792
- * Alarm callback: sweep aged stream buffers, re-arming while rows remain (see
8793
- * the shared {@link cleanupStreamBuffers}).
9631
+ * @deprecated Streams are reclaimed at cutover and on the next stream
9632
+ * start; no alarm is armed any more. Kept so a cleanup alarm persisted by
9633
+ * an earlier version still resolves to a callback when it fires.
8794
9634
  */
8795
9635
  async _cleanupStreamBuffers() {
8796
- await cleanupStreamBuffers(this._resumableStream, () => this._ensureStreamCleanupScheduled({ idempotent: false }));
9636
+ this._resumableStream.reclaim();
8797
9637
  }
8798
9638
  async _persistOrphanedStream(streamId) {
8799
9639
  this._resumableStream.flushBuffer();
@@ -8820,6 +9660,11 @@ var Think = class Think extends Agent {
8820
9660
  }, exclude);
8821
9661
  }
8822
9662
  };
9663
+ /** Durable SQLite storage for one context block of this agent. */
9664
+ function _contextProvider(label) {
9665
+ const sessionId = this.session?.sessionId ?? "";
9666
+ return new AgentContextProvider(this, sessionId ? `${label}_${sessionId}` : label);
9667
+ }
8823
9668
  Think.CONFIG_KEYS = [
8824
9669
  "_think_config",
8825
9670
  "lastClientTools",
@@ -8836,6 +9681,6 @@ for (const method of [
8836
9681
  Think.prototype.rejectExecution
8837
9682
  ]) callable()(method, void 0);
8838
9683
  //#endregion
8839
- export { Session, Think, Workspace, action, defaultContextOverflowClassifier, isAction, messengerChannel, skills };
9684
+ export { ThinkSession as Session, ThinkSession, Think, Workspace, action, defaultContextOverflowClassifier, isAction, messengerChannel, skills };
8840
9685
 
8841
9686
  //# sourceMappingURL=think.js.map