@cloudflare/think 0.7.3 → 0.8.1

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,11 @@
1
- import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-BP1jgEfY.js";
1
+ import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-D_obpP6O.js";
2
2
  import { createWorkspaceTools } from "./tools/workspace.js";
3
- import { convertToModelMessages, stepCountIs, streamText } from "ai";
3
+ import { t as ThinkMessengerRuntime } from "./chat-sdk-Bb93yaZh.js";
4
+ import { Output, convertToModelMessages, jsonSchema, stepCountIs, streamText } from "ai";
5
+ import * as skills from "agents/skills";
6
+ import { SkillRegistry } from "agents/skills";
4
7
  import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
5
- import { AbortRegistry, CHAT_MESSAGE_TYPES, ContinuationState, ResumableStream, StreamAccumulator, SubmitConcurrencyController, TurnQueue, applyChunkToParts, applyToolUpdate, createChatFiberSnapshot, createToolsFromClientSchemas, enforceRowSizeLimit, parseProtocolMessage, reconcileMessages, resolveToolMergeId, sanitizeMessage, toolApprovalUpdate, toolResultUpdate, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
8
+ import { AbortRegistry, CHAT_MESSAGE_TYPES, ContinuationState, ResumableStream, StreamAccumulator, SubmitConcurrencyController, TurnQueue, applyChunkToParts, applyToolUpdate, createChatFiberSnapshot, createToolsFromClientSchemas, crossMessageToolResultUpdate, enforceRowSizeLimit, normalizeToolInput, parseProtocolMessage, reconcileMessages, resolveToolMergeId, sanitizeMessage, toolApprovalUpdate, toolResultUpdate, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
6
9
  import { Session, Session as Session$1 } from "agents/experimental/memory/session";
7
10
  import { truncateOlderMessages } from "agents/experimental/memory/utils";
8
11
  import { Workspace, Workspace as Workspace$1 } from "@cloudflare/shell";
@@ -14,6 +17,7 @@ const MSG_CHAT_CLEAR = CHAT_MESSAGE_TYPES.CHAT_CLEAR;
14
17
  const MSG_STREAM_RESUMING = CHAT_MESSAGE_TYPES.STREAM_RESUMING;
15
18
  const MSG_STREAM_RESUME_NONE = CHAT_MESSAGE_TYPES.STREAM_RESUME_NONE;
16
19
  const MSG_MESSAGE_UPDATED = CHAT_MESSAGE_TYPES.MESSAGE_UPDATED;
20
+ const MSG_CHAT_RECOVERING = CHAT_MESSAGE_TYPES.CHAT_RECOVERING;
17
21
  function sendIfOpen(connection, message) {
18
22
  try {
19
23
  connection.send(message);
@@ -29,6 +33,299 @@ function isWebSocketClosedSendError(error) {
29
33
  function shouldMarkSkippedAfterGenerationChange(status) {
30
34
  return status === "completed";
31
35
  }
36
+ function stableStringify(value) {
37
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
38
+ if (Array.isArray(value)) return `[${value.map((item) => stableStringify(item)).join(",")}]`;
39
+ const record = value;
40
+ return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`).join(",")}}`;
41
+ }
42
+ function stableHash(value) {
43
+ const input = stableStringify(value);
44
+ let h1 = 1779033703;
45
+ let h2 = 3144134277;
46
+ let h3 = 1013904242;
47
+ let h4 = 2773480762;
48
+ for (let i = 0; i < input.length; i++) {
49
+ const code = input.charCodeAt(i);
50
+ h1 = h2 ^ Math.imul(h1 ^ code, 597399067);
51
+ h2 = h3 ^ Math.imul(h2 ^ code, 2869860233);
52
+ h3 = h4 ^ Math.imul(h3 ^ code, 951274213);
53
+ h4 = h1 ^ Math.imul(h4 ^ code, 2716044179);
54
+ }
55
+ h1 = Math.imul(h3 ^ h1 >>> 18, 597399067);
56
+ h2 = Math.imul(h4 ^ h2 >>> 22, 2869860233);
57
+ h3 = Math.imul(h1 ^ h3 >>> 17, 951274213);
58
+ h4 = Math.imul(h2 ^ h4 >>> 19, 2716044179);
59
+ return [
60
+ h1,
61
+ h2,
62
+ h3,
63
+ h4
64
+ ].map((part) => (part >>> 0).toString(16).padStart(8, "0")).join("");
65
+ }
66
+ function validateTimezone(timezone) {
67
+ try {
68
+ return new Intl.DateTimeFormat("en-US", { timeZone: timezone }).resolvedOptions().timeZone;
69
+ } catch {
70
+ throw new Error(`Invalid timezone "${timezone}"`);
71
+ }
72
+ }
73
+ function parseTime(value) {
74
+ const match = /^([01]\d|2[0-3]):([0-5]\d)$/.exec(value);
75
+ if (!match) throw new Error(`Invalid schedule time "${value}"; expected HH:mm`);
76
+ return {
77
+ hour: Number(match[1]),
78
+ minute: Number(match[2])
79
+ };
80
+ }
81
+ const declaredScheduleDayNumbers = {
82
+ sun: 0,
83
+ sunday: 0,
84
+ mon: 1,
85
+ monday: 1,
86
+ tue: 2,
87
+ tuesday: 2,
88
+ wed: 3,
89
+ wednesday: 3,
90
+ thu: 4,
91
+ thursday: 4,
92
+ fri: 5,
93
+ friday: 5,
94
+ sat: 6,
95
+ saturday: 6
96
+ };
97
+ function parseDeclaredTaskSchedule(rawSchedule, taskTimezone, defaultTimezone) {
98
+ const result = tryParseDeclaredTaskSchedule(rawSchedule, taskTimezone, defaultTimezone);
99
+ if (!result.ok) throw new Error(result.error);
100
+ return result.schedule;
101
+ }
102
+ function tryParseDeclaredTaskSchedule(rawSchedule, taskTimezone, defaultTimezone) {
103
+ try {
104
+ return {
105
+ ok: true,
106
+ schedule: parseDeclaredTaskScheduleUnchecked(rawSchedule, taskTimezone, defaultTimezone)
107
+ };
108
+ } catch (error) {
109
+ return {
110
+ ok: false,
111
+ error: error instanceof Error ? error.message : String(error)
112
+ };
113
+ }
114
+ }
115
+ function parseDeclaredTaskScheduleUnchecked(rawSchedule, taskTimezone, defaultTimezone) {
116
+ const trimmed = rawSchedule.trim().replace(/\s+/g, " ").toLowerCase();
117
+ const inlineTimezoneMatch = /^(.*) in ([A-Za-z_][A-Za-z0-9_+\-/]*)$/.exec(trimmed);
118
+ const schedule = inlineTimezoneMatch?.[1] ?? trimmed;
119
+ const inlineTimezone = inlineTimezoneMatch?.[2];
120
+ if (inlineTimezone && taskTimezone && validateTimezone(inlineTimezone) !== validateTimezone(taskTimezone)) throw new Error(`Schedule timezone "${inlineTimezone}" does not match task timezone "${taskTimezone}"`);
121
+ const intervalMatch = /^every ([1-9]\d*) (minute|minutes|hour|hours)$/.exec(schedule);
122
+ if (intervalMatch) {
123
+ if (inlineTimezone || taskTimezone) throw new Error("Interval schedules cannot specify a timezone");
124
+ const count = Number(intervalMatch[1]);
125
+ const unit = intervalMatch[2];
126
+ if (count === 1 && unit.endsWith("s")) throw new Error(`Use singular unit for "${rawSchedule}"`);
127
+ if (count !== 1 && !unit.endsWith("s")) throw new Error(`Use plural unit for "${rawSchedule}"`);
128
+ return {
129
+ kind: "interval",
130
+ intervalMs: count * (unit.startsWith("hour") ? 60 * 6e4 : 6e4),
131
+ normalizedSchedule: `every ${count} ${unit}`
132
+ };
133
+ }
134
+ const timezone = inlineTimezone ?? taskTimezone ?? defaultTimezone;
135
+ if (!timezone) throw new Error(`Wall-clock schedule "${rawSchedule}" requires a timezone or getDefaultTimezone()`);
136
+ const resolvedTimezone = validateTimezone(timezone);
137
+ const dailyMatch = /^every day at ([0-2]\d:[0-5]\d)$/.exec(schedule);
138
+ if (dailyMatch) {
139
+ const { hour, minute } = parseTime(dailyMatch[1]);
140
+ return {
141
+ kind: "wall-clock",
142
+ normalizedSchedule: `every day at ${dailyMatch[1]}`,
143
+ timezone: resolvedTimezone,
144
+ hour,
145
+ minute,
146
+ days: "daily"
147
+ };
148
+ }
149
+ const weekdayMatch = /^every weekday at ([0-2]\d:[0-5]\d)$/.exec(schedule);
150
+ if (weekdayMatch) {
151
+ const { hour, minute } = parseTime(weekdayMatch[1]);
152
+ return {
153
+ kind: "wall-clock",
154
+ normalizedSchedule: `every weekday at ${weekdayMatch[1]}`,
155
+ timezone: resolvedTimezone,
156
+ hour,
157
+ minute,
158
+ days: "weekday"
159
+ };
160
+ }
161
+ const weeklyMatch = /^every week on ([a-z,\s]+) at ([0-2]\d:[0-5]\d)$/.exec(schedule);
162
+ if (weeklyMatch) {
163
+ const seen = /* @__PURE__ */ new Set();
164
+ const days = weeklyMatch[1].split(",").map((day) => {
165
+ const normalized = day.trim();
166
+ const dayNumber = declaredScheduleDayNumbers[normalized];
167
+ if (dayNumber === void 0) throw new Error(`Invalid schedule day "${normalized}"`);
168
+ if (seen.has(dayNumber)) throw new Error(`Duplicate schedule day "${normalized}"`);
169
+ seen.add(dayNumber);
170
+ return dayNumber;
171
+ });
172
+ if (days.length === 0) throw new Error("Weekly schedule requires at least one day");
173
+ const { hour, minute } = parseTime(weeklyMatch[2]);
174
+ return {
175
+ kind: "wall-clock",
176
+ normalizedSchedule: `every week on ${weeklyMatch[1].split(",").map((day) => day.trim()).join(",")} at ${weeklyMatch[2]}`,
177
+ timezone: resolvedTimezone,
178
+ hour,
179
+ minute,
180
+ days
181
+ };
182
+ }
183
+ throw new Error(`Unsupported schedule DSL "${rawSchedule}"`);
184
+ }
185
+ function getZonedParts(date, timezone) {
186
+ const parts = new Intl.DateTimeFormat("en-US", {
187
+ timeZone: timezone,
188
+ calendar: "iso8601",
189
+ numberingSystem: "latn",
190
+ weekday: "short",
191
+ year: "numeric",
192
+ month: "2-digit",
193
+ day: "2-digit",
194
+ hour: "2-digit",
195
+ minute: "2-digit",
196
+ second: "2-digit",
197
+ hourCycle: "h23"
198
+ }).formatToParts(date);
199
+ const part = (type) => parts.find((entry) => entry.type === type)?.value ?? "";
200
+ return {
201
+ year: Number(part("year")),
202
+ month: Number(part("month")),
203
+ day: Number(part("day")),
204
+ hour: Number(part("hour")),
205
+ minute: Number(part("minute")),
206
+ second: Number(part("second")),
207
+ weekday: [
208
+ "Sun",
209
+ "Mon",
210
+ "Tue",
211
+ "Wed",
212
+ "Thu",
213
+ "Fri",
214
+ "Sat"
215
+ ].indexOf(part("weekday"))
216
+ };
217
+ }
218
+ function compareLocalParts(left, right) {
219
+ for (const field of [
220
+ "year",
221
+ "month",
222
+ "day",
223
+ "hour",
224
+ "minute"
225
+ ]) {
226
+ const diff = left[field] - right[field];
227
+ if (diff !== 0) return diff;
228
+ }
229
+ return 0;
230
+ }
231
+ function findZonedInstant(target, timezone) {
232
+ const approximate = Date.UTC(target.year, target.month - 1, target.day, target.hour, target.minute);
233
+ const start = approximate - 840 * 6e4;
234
+ const end = approximate + 840 * 6e4;
235
+ for (let time = start; time <= end; time += 6e4) {
236
+ const candidate = new Date(time);
237
+ if (compareLocalParts(getZonedParts(candidate, timezone), target) === 0) return candidate;
238
+ }
239
+ for (let time = start; time <= end; time += 6e4) {
240
+ const candidate = new Date(time);
241
+ if (compareLocalParts(getZonedParts(candidate, timezone), target) > 0) return candidate;
242
+ }
243
+ throw new Error(`Unable to resolve local time in timezone "${timezone}"`);
244
+ }
245
+ function addLocalDays(parts, days) {
246
+ const date = new Date(Date.UTC(parts.year, parts.month - 1, parts.day + days));
247
+ return {
248
+ year: date.getUTCFullYear(),
249
+ month: date.getUTCMonth() + 1,
250
+ day: date.getUTCDate()
251
+ };
252
+ }
253
+ function isAllowedWallClockDay(weekday, days) {
254
+ if (days.days === "daily") return true;
255
+ if (days.days === "weekday") return weekday >= 1 && weekday <= 5;
256
+ return days.days.includes(weekday);
257
+ }
258
+ function nextDeclaredScheduleTime(schedule, now, previousScheduledFor) {
259
+ if (schedule.kind === "interval") {
260
+ let next = previousScheduledFor === void 0 ? now.getTime() + schedule.intervalMs : previousScheduledFor + schedule.intervalMs;
261
+ while (next <= now.getTime()) next += schedule.intervalMs;
262
+ return new Date(next);
263
+ }
264
+ const nowParts = getZonedParts(now, schedule.timezone);
265
+ for (let offset = 0; offset < 370; offset++) {
266
+ const candidate = findZonedInstant({
267
+ ...addLocalDays(nowParts, offset),
268
+ hour: schedule.hour,
269
+ minute: schedule.minute
270
+ }, schedule.timezone);
271
+ const weekday = getZonedParts(candidate, schedule.timezone).weekday;
272
+ if (!isAllowedWallClockDay(weekday, schedule)) continue;
273
+ if (candidate.getTime() > now.getTime()) return candidate;
274
+ }
275
+ throw new Error("Unable to compute next scheduled task occurrence");
276
+ }
277
+ /**
278
+ * Thrown by `_iterateWithStallWatchdog` when the inactivity watchdog fires
279
+ * (a model/transport stream that parks without ever throwing). Distinct from
280
+ * in-band model/stream errors so the read-loop catch can route a stall into
281
+ * bounded recovery (#1626) — a transient hang is retried within the existing
282
+ * recovery budget — while genuine errors stay terminal.
283
+ */
284
+ var ChatStreamStalledError = class extends Error {
285
+ constructor(message) {
286
+ super(message);
287
+ this.isChatStreamStall = true;
288
+ this.name = "ChatStreamStalledError";
289
+ }
290
+ };
291
+ const CHAT_RECOVERY_INCIDENT_KEY_PREFIX = "cf:chat-recovery:incident:";
292
+ const CHAT_RECOVERY_PROGRESS_KEY = "cf:chat-recovery:progress";
293
+ const DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS = 10;
294
+ const DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS = 1e4;
295
+ const AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS = 6e4;
296
+ const CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS = 3;
297
+ const DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE = "The assistant was interrupted and could not recover. Please try again.";
298
+ const CHAT_RECOVERY_INCIDENT_TTL_MS = 3600 * 1e3;
299
+ const CHAT_RECOVERY_NO_PROGRESS_WINDOW_MS = 300 * 1e3;
300
+ const CHAT_RECOVERY_ALARM_DEBOUNCE_MS = 30 * 1e3;
301
+ const CHAT_RECOVERY_MAX_WINDOW_MS = 900 * 1e3;
302
+ const AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS = 5e3;
303
+ const CONTINUE_CHECKPOINT_PROMPT = "Continue your previous response from exactly where it left off. Do not repeat any of it.";
304
+ /**
305
+ * Ensure a model request does not end in an assistant message.
306
+ *
307
+ * Continuing a partial assistant turn (e.g. after a deploy interrupts a stream)
308
+ * replays a transcript whose final message is that partial assistant message —
309
+ * an "assistant prefill". Modern chat models reject this: Anthropic Claude 4.6+
310
+ * returns a 400 ("This model does not support assistant message prefill. The
311
+ * conversation must end with a user message."). To reach a valid continue
312
+ * checkpoint across providers we append an ephemeral user message. This shapes
313
+ * only the model request; it is never persisted to the transcript.
314
+ */
315
+ function ensureValidContinueCheckpoint(messages) {
316
+ if (messages.length === 0) return messages;
317
+ if (messages[messages.length - 1]?.role !== "assistant") return messages;
318
+ return [...messages, {
319
+ role: "user",
320
+ content: CONTINUE_CHECKPOINT_PROMPT
321
+ }];
322
+ }
323
+ const CHAT_LAST_TERMINAL_KEY = "cf:chat:last-terminal";
324
+ const CHAT_RECOVERING_KEY = "cf:chat:recovering";
325
+ function defineScheduledTasks(tasks) {
326
+ return tasks;
327
+ }
328
+ const THINK_WORKFLOW_PROMPT_METADATA_KEY = "__thinkWorkflowPrompt";
32
329
  const TIMED_OUT = Symbol("timed-out");
33
330
  var _configCache = /* @__PURE__ */ new WeakMap();
34
331
  var _configTableReady = /* @__PURE__ */ new WeakMap();
@@ -41,17 +338,23 @@ var Think = class Think extends Agent {
41
338
  constructor(ctx, env) {
42
339
  super(ctx, env);
43
340
  this.waitForMcpConnections = false;
341
+ this._skillRegistry = null;
342
+ this._loggedSkillWarnings = /* @__PURE__ */ new Set();
44
343
  this.messageConcurrency = "queue";
45
344
  this.chatRecovery = true;
46
345
  this._cachedMessages = [];
346
+ this.workspaceBash = true;
47
347
  this._aborts = new AbortRegistry();
48
348
  this._turnQueue = new TurnQueue();
49
349
  this._pendingResumeConnections = /* @__PURE__ */ new Set();
50
350
  this._continuation = new ContinuationState();
51
351
  this._continuationTimer = null;
352
+ this._continuationBarrierActive = false;
52
353
  this._insideResponseHook = false;
53
354
  this._insideInferenceLoop = false;
54
355
  this._pendingInteractionPromise = null;
356
+ this._interactionApplyTail = Promise.resolve();
357
+ this._streamingAssistant = null;
55
358
  this._submitConcurrency = new SubmitConcurrencyController({ defaultDebounceMs: Think.MESSAGE_DEBOUNCE_MS });
56
359
  this._agentToolForwarders = /* @__PURE__ */ new Map();
57
360
  this._agentToolClosers = /* @__PURE__ */ new Map();
@@ -60,14 +363,19 @@ var Think = class Think extends Agent {
60
363
  this._agentToolPreTurnAssistantIds = /* @__PURE__ */ new Map();
61
364
  this._agentToolLiveSequences = /* @__PURE__ */ new Map();
62
365
  this._submissionTableEnsured = false;
366
+ this._workflowNotificationTableEnsured = false;
367
+ this._declaredScheduledTasksTableEnsured = false;
63
368
  this._drainingSubmissions = false;
369
+ this._drainingWorkflowNotifications = false;
64
370
  this._submissionAbortControllers = /* @__PURE__ */ new Map();
65
371
  this._programmaticStreamErrors = /* @__PURE__ */ new Map();
66
372
  _classPrivateFieldInitSpec(this, _configCache, null);
67
373
  _classPrivateFieldInitSpec(this, _configTableReady, false);
68
374
  this.maxSteps = 10;
69
375
  this.sendReasoning = true;
376
+ this.chatStreamStallTimeoutMs = 0;
70
377
  this.hookTimeout = 5e3;
378
+ this._lastAgentToolStreamProgressAt = 0;
71
379
  const _onStart = this.onStart.bind(this);
72
380
  this.onStart = async () => {
73
381
  if (!this.workspace) this.workspace = new Workspace$1({
@@ -94,15 +402,20 @@ var Think = class Think extends Agent {
94
402
  break;
95
403
  }
96
404
  });
405
+ await this._initializeSkills();
97
406
  await this._syncMessages();
98
407
  if (this.extensionLoader) await this._initializeExtensions();
99
408
  this._resumableStream = new ResumableStream(this.sql.bind(this));
100
409
  this._restoreClientTools();
101
410
  this._restoreBody();
102
411
  this._setupProtocolHandlers();
412
+ this._initializeMessengers();
103
413
  await _onStart();
414
+ await this._reconcileDeclaredScheduledTasks();
104
415
  await this._recoverSubmissionsOnStart();
105
- this._startSubmissionDrain();
416
+ this._recoverWorkflowNotifications();
417
+ if (this._hasPendingSubmissions()) this._startSubmissionDrain();
418
+ if (this._hasPendingWorkflowNotifications()) this._startWorkflowNotificationDrain();
106
419
  };
107
420
  }
108
421
  /**
@@ -120,6 +433,161 @@ var Think = class Think extends Agent {
120
433
  async _readMessagesFromStorage() {
121
434
  return await this.session.getHistory();
122
435
  }
436
+ /**
437
+ * Normalize a tool part's `input` into something the provider will accept.
438
+ *
439
+ * Malformed shapes 400 modern providers and persist forever once written:
440
+ * a stringified-JSON `input` (e.g. `'{"prompt":"a cat"}'` instead of the
441
+ * object), and any non-object `input` — `null`, `undefined`, `""`, an array,
442
+ * or a primitive — on a settled or interrupted tool call (Anthropic rejects
443
+ * a `tool_use` block whose `input` is not an object). We parse the former and
444
+ * default the latter to an empty object so the tool-call/tool-result pair
445
+ * stays valid. Delegates to the shared `normalizeToolInput` so the read-side
446
+ * repair and the write-side accumulator guard enforce the same invariant.
447
+ */
448
+ _normalizeToolInput(record) {
449
+ return normalizeToolInput("input" in record ? record.input : void 0);
450
+ }
451
+ /**
452
+ * Whether a tool part already has a settled result the provider accepts, so
453
+ * it must NOT be re-repaired into an errored result.
454
+ *
455
+ * Single source of truth for the terminal tool states, shared by the repair
456
+ * pass and the backstop detector so they cannot drift. Mirror the AI SDK's
457
+ * terminal states: `convertToModelMessages` emits a `tool-result` for
458
+ * `output-available`, `output-error`, AND `output-denied` (a user-denied
459
+ * approval — its denial reason becomes the tool-result). Omitting any of
460
+ * these makes repair re-flip the part every turn — clobbering a real
461
+ * `errorText`/denial with the generic "interrupted" message — and makes the
462
+ * backstop falsely drop a valid call.
463
+ */
464
+ _toolPartHasSettledResult(record) {
465
+ if ("output" in record || "result" in record) return true;
466
+ const state = typeof record.state === "string" ? record.state : "";
467
+ return state === "output-available" || state === "output-error" || state === "output-denied";
468
+ }
469
+ /**
470
+ * Tool-call ids that still have no recorded result. After repair this should
471
+ * be empty; a non-empty result means the backstop (`ignoreIncompleteToolCalls`)
472
+ * will drop those calls — i.e. repair missed a shape and should be extended.
473
+ *
474
+ * `approval-responded` is deliberately excluded: an approved server tool has
475
+ * no result *yet*, but it is not incomplete or abandoned — it is waiting for
476
+ * its continuation to run `execute()`. `convertToModelMessages` keeps that
477
+ * call (and the SDK executes it), so flagging it here would log a misleading
478
+ * "repair gap" warning and emit a spurious `chat:transcript:repaired` event
479
+ * on every approval continuation.
480
+ */
481
+ _incompleteToolCallIds(messages) {
482
+ const ids = [];
483
+ for (const message of messages) for (const part of message.parts) {
484
+ const record = part;
485
+ const toolCallId = typeof record.toolCallId === "string" ? record.toolCallId : void 0;
486
+ if (!(typeof record.type === "string" && (record.type.startsWith("tool-") || record.type === "dynamic-tool") && toolCallId)) continue;
487
+ if (record.state === "approval-responded") continue;
488
+ if (!this._toolPartHasSettledResult(record)) ids.push(toolCallId);
489
+ }
490
+ return ids;
491
+ }
492
+ /**
493
+ * Repair a single interrupted tool call — a tool part with no settled result,
494
+ * left behind when a stream was cut off mid-flight. Returns the replacement
495
+ * part that takes its place in the transcript. `input` has already been
496
+ * normalized to a valid object.
497
+ *
498
+ * The default flips it to an errored tool result so the record survives (no
499
+ * "disappearing" tool call) and `convertToModelMessages` still gets a
500
+ * tool-result for it (avoiding `AI_MissingToolResultsError`).
501
+ *
502
+ * Override to customize the repaired shape for client-resolved tools — e.g.
503
+ * convert an interrupted `ask_user` (a question with no server `execute`,
504
+ * normally answered by the user's next message) into a plain text part
505
+ * carrying the question prose, so the model sees it as ordinary conversation
506
+ * rather than a tool error and compaction keeps the question verbatim. This
507
+ * runs DURING transcript repair — before the repaired transcript is persisted
508
+ * and sent to the model — so the conversion shapes the current turn, not just
509
+ * the next one. A returned tool part MUST carry a settled result
510
+ * (`output-available` / `output-error` / `output-denied` or an
511
+ * `output`/`result` field); returning a non-tool part (e.g. text) is fine.
512
+ */
513
+ repairInterruptedToolPart(part) {
514
+ return {
515
+ ...part,
516
+ state: "output-error",
517
+ errorText: "The tool call was interrupted before a result was recorded."
518
+ };
519
+ }
520
+ _repairToolTranscriptParts(messages) {
521
+ let removedToolCalls = 0;
522
+ let normalizedInputs = 0;
523
+ const toolCallIds = [];
524
+ const repaired = [];
525
+ for (const message of messages) {
526
+ const parts = [];
527
+ let messageChanged = false;
528
+ for (const part of message.parts) {
529
+ const record = part;
530
+ const toolCallId = typeof record.toolCallId === "string" ? record.toolCallId : void 0;
531
+ if (!(typeof record.type === "string" && (record.type.startsWith("tool-") || record.type === "dynamic-tool") && toolCallId)) {
532
+ parts.push(part);
533
+ continue;
534
+ }
535
+ if (!this._toolPartHasSettledResult(record)) {
536
+ if ((typeof record.state === "string" ? record.state : "") === "approval-responded") {
537
+ parts.push(part);
538
+ continue;
539
+ }
540
+ const normalized = this._normalizeToolInput(record);
541
+ parts.push(this.repairInterruptedToolPart({
542
+ ...part,
543
+ input: normalized.input
544
+ }));
545
+ if (normalized.changed) normalizedInputs++;
546
+ removedToolCalls++;
547
+ messageChanged = true;
548
+ toolCallIds.push(toolCallId);
549
+ continue;
550
+ }
551
+ const normalized = this._normalizeToolInput(record);
552
+ if (normalized.changed) {
553
+ parts.push({
554
+ ...part,
555
+ input: normalized.input
556
+ });
557
+ normalizedInputs++;
558
+ messageChanged = true;
559
+ continue;
560
+ }
561
+ parts.push(part);
562
+ }
563
+ repaired.push(messageChanged ? {
564
+ ...message,
565
+ parts
566
+ } : message);
567
+ }
568
+ return {
569
+ messages: repaired,
570
+ removedToolCalls,
571
+ normalizedInputs,
572
+ toolCallIds
573
+ };
574
+ }
575
+ async _repairTranscriptForProvider(messages) {
576
+ const repair = this._repairToolTranscriptParts(messages);
577
+ if (repair.removedToolCalls === 0 && repair.normalizedInputs === 0) return messages;
578
+ for (const message of repair.messages) {
579
+ const original = messages.find((candidate) => candidate.id === message.id);
580
+ if (original && original.parts !== message.parts) await this.session.updateMessage(sanitizeMessage(message));
581
+ }
582
+ this._replaceCachedMessages(repair.messages);
583
+ this._broadcastMessages();
584
+ this._emit("chat:transcript:repaired", {
585
+ removedToolCalls: repair.removedToolCalls,
586
+ normalizedInputs: repair.normalizedInputs,
587
+ toolCallIds: repair.toolCallIds
588
+ });
589
+ return repair.messages;
590
+ }
123
591
  /** Replace the live cache with a durable storage snapshot. */
124
592
  _replaceCachedMessages(messages) {
125
593
  this._cachedMessages = messages;
@@ -189,6 +657,10 @@ var Think = class Think extends Agent {
189
657
  } catch {}
190
658
  super.broadcast(msg, without);
191
659
  }
660
+ async alarm() {
661
+ await super.alarm();
662
+ this._startWorkflowNotificationDrain();
663
+ }
192
664
  /**
193
665
  * Persist an arbitrary JSON-serializable configuration object for this
194
666
  * agent instance. Stored in the Think-private `think_config` table —
@@ -298,10 +770,52 @@ var Think = class Think extends Agent {
298
770
  getTools() {
299
771
  return {};
300
772
  }
773
+ /** Return messenger integrations that should be routed through this Think agent. */
774
+ getMessengers() {
775
+ return {};
776
+ }
777
+ getMessengerContext() {
778
+ if (this._activeMessengerContext) return this._activeMessengerContext;
779
+ return this.messages.at(-1)?.metadata?.messenger;
780
+ }
781
+ async chatWithMessengerContext(userMessage, callback, context, options) {
782
+ const previous = this._activeMessengerContext;
783
+ this._activeMessengerContext = context;
784
+ try {
785
+ await this.chat(userMessage, callback, options);
786
+ } finally {
787
+ this._activeMessengerContext = previous;
788
+ }
789
+ }
790
+ _initializeMessengers() {
791
+ if (this.parentPath.length > 0) return;
792
+ const messengers = this.getMessengers();
793
+ if (Object.keys(messengers).length === 0) return;
794
+ this._messengerRuntime = new ThinkMessengerRuntime(messengers, this);
795
+ this._messengerRuntime.initialize();
796
+ }
797
+ /** Return code-declared scheduled tasks for this agent. */
798
+ getScheduledTasks() {
799
+ return {};
800
+ }
801
+ /**
802
+ * Reconcile code-declared scheduled tasks immediately.
803
+ * Static declarations are reconciled on startup automatically; call this
804
+ * after changing app-owned data that `getScheduledTasks()` reads.
805
+ */
806
+ async internal_reconcileScheduledTasks() {
807
+ await this._reconcileDeclaredScheduledTasks();
808
+ }
809
+ /**
810
+ * Return the default timezone for wall-clock scheduled tasks.
811
+ * Task-local timezone declarations take precedence.
812
+ */
813
+ getDefaultTimezone() {}
301
814
  async _runChatRecoveryFiber(requestId, continuation, fn) {
302
815
  const snapshot = createChatFiberSnapshot({
303
816
  kind: "think-chat-turn",
304
817
  requestId,
818
+ recoveryRootRequestId: this._activeChatRecoveryRootRequestId ?? requestId,
305
819
  continuation,
306
820
  messages: this.messages,
307
821
  lastBody: this._lastBody,
@@ -364,6 +878,75 @@ var Think = class Think extends Agent {
364
878
  return session;
365
879
  }
366
880
  /**
881
+ * Return Agent Skills sources for this Think agent.
882
+ *
883
+ * Bundled skills are typically imported with the Agents Vite plugin:
884
+ *
885
+ * ```typescript
886
+ * import productSkills from "agents:skills"; // -> ./skills next to this file
887
+ * ```
888
+ *
889
+ * Sources are applied in order; the first source to register a skill name
890
+ * wins, and later collisions are skipped with a logged warning.
891
+ */
892
+ getSkills() {
893
+ return [];
894
+ }
895
+ async _initializeSkills() {
896
+ try {
897
+ const sources = await this.getSkills();
898
+ if (sources.length === 0) return;
899
+ const registry = new SkillRegistry(sources, this.getSkillScriptRunner());
900
+ await registry.load();
901
+ this._logSkillWarnings(registry);
902
+ this._skillRegistry = registry;
903
+ await this.session.addContext(registry.contextLabel, {
904
+ description: "Think skills: available skill catalog",
905
+ provider: { get: () => registry.systemPrompt() }
906
+ });
907
+ if (this._configGet("skillsFingerprint") !== registry.fingerprint) {
908
+ await this.session.refreshSystemPrompt();
909
+ this._configSet("skillsFingerprint", registry.fingerprint);
910
+ }
911
+ } catch (error) {
912
+ console.warn(`[think] Failed to initialize skills; continuing without them: ${error instanceof Error ? error.message : String(error)}`);
913
+ }
914
+ }
915
+ /**
916
+ * Log registry diagnostics (duplicate names, sources that failed to list),
917
+ * deduped by message so a new collision after a deploy still surfaces while
918
+ * the same warning is not repeated on every turn.
919
+ */
920
+ _logSkillWarnings(registry) {
921
+ for (const warning of registry.warnings) {
922
+ if (this._loggedSkillWarnings.has(warning)) continue;
923
+ this._loggedSkillWarnings.add(warning);
924
+ console.warn(`[think] ${warning}`);
925
+ }
926
+ }
927
+ /**
928
+ * Return an optional runner that enables the `run_skill_script` tool.
929
+ *
930
+ * @experimental Skill script execution is experimental and may change
931
+ * before stabilizing.
932
+ */
933
+ getSkillScriptRunner() {
934
+ return null;
935
+ }
936
+ async _refreshSkillsIfChanged() {
937
+ if (!this._skillRegistry) return;
938
+ try {
939
+ await this._skillRegistry.refresh();
940
+ this._logSkillWarnings(this._skillRegistry);
941
+ if (this._configGet("skillsFingerprint") !== this._skillRegistry.fingerprint) {
942
+ await this.session.refreshSystemPrompt();
943
+ this._configSet("skillsFingerprint", this._skillRegistry.fingerprint);
944
+ }
945
+ } catch (error) {
946
+ console.warn(`[think] Failed to refresh skills; using last known catalog: ${error instanceof Error ? error.message : String(error)}`);
947
+ }
948
+ }
949
+ /**
367
950
  * Return sandboxed extension configurations. Defines load order,
368
951
  * which determines hook execution order.
369
952
  * Requires `extensionLoader` to be set.
@@ -525,12 +1108,12 @@ var Think = class Think extends Agent {
525
1108
  * Handle an error that occurred during a chat turn.
526
1109
  * Override to customize error handling (e.g. logging, metrics).
527
1110
  */
528
- onChatError(error) {
1111
+ onChatError(error, _ctx) {
529
1112
  return error;
530
1113
  }
531
1114
  async _initializeExtensions() {
532
- const { ExtensionManager } = await import("./manager-px912SoZ.js").then((n) => n.n);
533
- const { sanitizeName } = await import("./manager-px912SoZ.js").then((n) => n.n);
1115
+ const { ExtensionManager } = await import("./manager-DnCkoyVo.js").then((n) => n.n);
1116
+ const { sanitizeName } = await import("./manager-DnCkoyVo.js").then((n) => n.n);
534
1117
  const agentClassName = this.constructor.name;
535
1118
  const agentId = this.ctx.id.toString();
536
1119
  const ctxExports = this.ctx.exports;
@@ -571,27 +1154,43 @@ var Think = class Think extends Agent {
571
1154
  * for interception, and calls streamText.
572
1155
  */
573
1156
  async _runInferenceLoop(input) {
1157
+ this._activeStallTimeoutMs = void 0;
574
1158
  if (this.waitForMcpConnections) {
575
1159
  const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : 1e4;
576
1160
  await this.mcp.waitForConnections({ timeout });
577
1161
  }
578
- const workspaceTools = createWorkspaceTools(this.workspace);
1162
+ const workspaceTools = createWorkspaceTools(this.workspace, { bash: this.workspaceBash });
579
1163
  const baseTools = this.getTools();
580
1164
  const extensionTools = this.extensionManager?.getTools() ?? {};
1165
+ await this._refreshSkillsIfChanged();
581
1166
  const contextTools = await this.session.tools();
1167
+ const skillTools = this._skillRegistry?.tools() ?? {};
582
1168
  const clientToolSet = createToolsFromClientSchemas(input.clientTools);
583
1169
  const tools = {
584
1170
  ...workspaceTools,
585
1171
  ...baseTools,
586
1172
  ...extensionTools,
587
1173
  ...contextTools,
1174
+ ...skillTools,
588
1175
  ...this.mcp?.getAITools?.() ?? {},
589
1176
  ...clientToolSet
590
1177
  };
591
1178
  const baseSystem = await this.session.freezeSystemPrompt() || this.getSystemPrompt();
592
1179
  const system = this._systemPromptForTurn(baseSystem, tools);
593
- const history = this.messages;
594
- const messages = await convertToModelMessages(truncateOlderMessages(history), { tools });
1180
+ const truncated = truncateOlderMessages(await this._repairTranscriptForProvider(this.messages));
1181
+ const incompleteAfterRepair = this._incompleteToolCallIds(truncated);
1182
+ if (incompleteAfterRepair.length > 0) {
1183
+ console.warn(`[Think] ${incompleteAfterRepair.length} incomplete tool call(s) survived transcript repair and will be dropped by ignoreIncompleteToolCalls: ${incompleteAfterRepair.join(", ")}. This indicates a gap in _repairToolTranscriptParts.`);
1184
+ this._emit("chat:transcript:repaired", {
1185
+ removedToolCalls: incompleteAfterRepair.length,
1186
+ normalizedInputs: 0,
1187
+ toolCallIds: incompleteAfterRepair
1188
+ });
1189
+ }
1190
+ const messages = await convertToModelMessages(truncated, {
1191
+ tools,
1192
+ ignoreIncompleteToolCalls: true
1193
+ });
595
1194
  if (messages.length === 0) throw new Error("No messages to send to the model. This usually means the chat request arrived before any messages were persisted.");
596
1195
  const model = this.getModel();
597
1196
  const ctx = {
@@ -604,12 +1203,14 @@ var Think = class Think extends Agent {
604
1203
  };
605
1204
  const subclassConfig = await this.beforeTurn(ctx) ?? {};
606
1205
  const config = await this._pipelineExtensionBeforeTurn(ctx, subclassConfig);
1206
+ const workflowPrompt = input.workflowPrompt;
1207
+ const workflowOutput = workflowPrompt?.output ? Output.object({ schema: jsonSchema(workflowPrompt.output.schema) }) : void 0;
607
1208
  const finalModel = config.model ?? model;
608
1209
  const finalSystem = config.system ?? this._systemPromptForTurn(baseSystem, config.tools ? {
609
1210
  ...tools,
610
1211
  ...config.tools
611
1212
  } : tools);
612
- const finalMessages = config.messages ?? messages;
1213
+ const finalMessages = ensureValidContinueCheckpoint(config.messages ?? messages);
613
1214
  const mergedTools = config.tools ? {
614
1215
  ...tools,
615
1216
  ...config.tools
@@ -617,6 +1218,8 @@ var Think = class Think extends Agent {
617
1218
  const finalTools = this._wrapToolsWithDecision(mergedTools);
618
1219
  const finalMaxSteps = config.maxSteps ?? this.maxSteps;
619
1220
  const finalSendReasoning = config.sendReasoning ?? this.sendReasoning;
1221
+ this._activeStallTimeoutMs = config.chatStreamStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
1222
+ const finalOutput = workflowOutput ?? config.output;
620
1223
  const finalStopWhen = [stepCountIs(finalMaxSteps), ...Array.isArray(config.stopWhen) ? config.stopWhen : config.stopWhen ? [config.stopWhen] : []];
621
1224
  const result = streamText({
622
1225
  model: finalModel,
@@ -639,7 +1242,7 @@ var Think = class Think extends Agent {
639
1242
  stopWhen: finalStopWhen,
640
1243
  providerOptions: config.providerOptions,
641
1244
  experimental_telemetry: config.experimental_telemetry,
642
- output: config.output,
1245
+ output: finalOutput,
643
1246
  abortSignal: input.signal,
644
1247
  prepareStep: (async (event) => {
645
1248
  const result = await this.beforeStep(event);
@@ -673,7 +1276,13 @@ var Think = class Think extends Agent {
673
1276
  await this._pipelineExtensionToolCallFinish(event);
674
1277
  })
675
1278
  });
676
- return this._transformInferenceResult({ toUIMessageStream: () => result.toUIMessageStream({ sendReasoning: finalSendReasoning }) });
1279
+ const outputPromise = finalOutput && result.output ? Promise.resolve(result.output) : void 0;
1280
+ if (outputPromise) outputPromise.catch(() => {});
1281
+ const streamResult = {
1282
+ toUIMessageStream: () => result.toUIMessageStream({ sendReasoning: finalSendReasoning }),
1283
+ output: outputPromise
1284
+ };
1285
+ return this._transformInferenceResult(streamResult);
677
1286
  }
678
1287
  /** @internal Test seam — override in test agents to wrap the stream (e.g. error injection). */
679
1288
  _transformInferenceResult(result) {
@@ -690,7 +1299,7 @@ var Think = class Think extends Agent {
690
1299
  if (!this.extensionManager) return subclassConfig;
691
1300
  const subscribers = this.extensionManager.getHookSubscribers("beforeTurn");
692
1301
  if (subscribers.length === 0) return subclassConfig;
693
- const { createTurnContextSnapshot, parseHookResult } = await import("./hook-proxy-5248W-ea.js");
1302
+ const { createTurnContextSnapshot, parseHookResult } = await import("./hook-proxy-CkF0EhRO.js");
694
1303
  let snapshot = createTurnContextSnapshot(ctx);
695
1304
  let accumulated = { ...subclassConfig };
696
1305
  if (accumulated.system !== void 0) snapshot.system = accumulated.system;
@@ -861,25 +1470,25 @@ var Think = class Think extends Agent {
861
1470
  async _pipelineExtensionToolCallStart(event) {
862
1471
  if (!this.extensionManager) return;
863
1472
  if (this.extensionManager.getHookSubscribers("beforeToolCall").length === 0) return;
864
- const { createToolCallStartSnapshot } = await import("./hook-proxy-5248W-ea.js");
1473
+ const { createToolCallStartSnapshot } = await import("./hook-proxy-CkF0EhRO.js");
865
1474
  await this._dispatchExtensionObservation("beforeToolCall", createToolCallStartSnapshot(event));
866
1475
  }
867
1476
  async _pipelineExtensionToolCallFinish(event) {
868
1477
  if (!this.extensionManager) return;
869
1478
  if (this.extensionManager.getHookSubscribers("afterToolCall").length === 0) return;
870
- const { createToolCallFinishSnapshot } = await import("./hook-proxy-5248W-ea.js");
1479
+ const { createToolCallFinishSnapshot } = await import("./hook-proxy-CkF0EhRO.js");
871
1480
  await this._dispatchExtensionObservation("afterToolCall", createToolCallFinishSnapshot(event));
872
1481
  }
873
1482
  async _pipelineExtensionStepFinish(event) {
874
1483
  if (!this.extensionManager) return;
875
1484
  if (this.extensionManager.getHookSubscribers("onStepFinish").length === 0) return;
876
- const { createStepFinishSnapshot } = await import("./hook-proxy-5248W-ea.js");
1485
+ const { createStepFinishSnapshot } = await import("./hook-proxy-CkF0EhRO.js");
877
1486
  await this._dispatchExtensionObservation("onStepFinish", createStepFinishSnapshot(event));
878
1487
  }
879
1488
  async _pipelineExtensionChunk(event) {
880
1489
  if (!this.extensionManager) return;
881
1490
  if (this.extensionManager.getHookSubscribers("onChunk").length === 0) return;
882
- const { createChunkSnapshot } = await import("./hook-proxy-5248W-ea.js");
1491
+ const { createChunkSnapshot } = await import("./hook-proxy-CkF0EhRO.js");
883
1492
  await this._dispatchExtensionObservation("onChunk", createChunkSnapshot(event));
884
1493
  }
885
1494
  async _hostReadFile(path) {
@@ -948,7 +1557,7 @@ var Think = class Think extends Agent {
948
1557
  const ignoredTools = options?.tools;
949
1558
  if (ignoredTools != null && typeof ignoredTools === "object" && Object.keys(ignoredTools).length > 0) console.warn("[Think] chat() no longer accepts options.tools. Define durable tools on the child agent with getTools(), or use runAgentTool()/agentTool() for parent-child orchestration.");
950
1559
  try {
951
- await callback.onStart?.({ requestId });
1560
+ await callback.onStart({ requestId });
952
1561
  await this.keepAliveWhile(async () => {
953
1562
  await this._turnQueue.enqueue(requestId, async () => {
954
1563
  const userMsg = typeof userMessage === "string" ? {
@@ -974,13 +1583,18 @@ var Think = class Think extends Agent {
974
1583
  continuation: false
975
1584
  }));
976
1585
  } catch (error) {
977
- const wrapped = this.onChatError(error);
1586
+ const wrapped = this.onChatError(error, {
1587
+ stage: "turn",
1588
+ messagesPersisted: true
1589
+ });
978
1590
  const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
979
- if (callback.onError) {
980
- await callback.onError(errorMessage);
981
- return;
982
- }
983
- throw wrapped;
1591
+ this._emit("chat:request:failed", {
1592
+ stage: "turn",
1593
+ messagesPersisted: true,
1594
+ error: errorMessage
1595
+ });
1596
+ await callback.onError(errorMessage);
1597
+ return;
984
1598
  }
985
1599
  await this._streamResultToRpcCallback(requestId, result, callback, abortSignal);
986
1600
  };
@@ -1151,9 +1765,78 @@ var Think = class Think extends Agent {
1151
1765
  AND status NOT IN ('completed', 'error', 'aborted')
1152
1766
  `;
1153
1767
  }
1768
+ /**
1769
+ * Classify any in-flight chat-recovery on this child facet (#1630). A child
1770
+ * facet is dedicated to a single agent-tool run, so any recovery incident is
1771
+ * that run's. `detected`/`scheduled`/`attempting` mean recovery is still
1772
+ * resolving the interrupted turn; `exhausted`/`failed` mean it gave up; a
1773
+ * completed recovery deletes its incident.
1774
+ */
1775
+ async _classifyAgentToolChildRecovery() {
1776
+ const entries = await this.ctx.storage.list({ prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX });
1777
+ let failed = false;
1778
+ for (const incident of entries.values()) {
1779
+ if (incident.status === "detected" || incident.status === "scheduled" || incident.status === "attempting") return "in-progress";
1780
+ if (incident.status === "exhausted" || incident.status === "failed") failed = true;
1781
+ }
1782
+ return failed ? "failed" : "none";
1783
+ }
1154
1784
  async inspectAgentToolRun(runId) {
1155
- const row = this._readAgentToolChildRun(runId);
1156
- return row ? this._inspectionFromChildRow(row, this.getAgentToolOutput(runId)) : null;
1785
+ let row = this._readAgentToolChildRun(runId);
1786
+ if (!row) return null;
1787
+ if (this._isStaleAgentToolChildRun(row)) {
1788
+ await this._reconcileStaleAgentToolChildRun(runId);
1789
+ row = this._readAgentToolChildRun(runId) ?? row;
1790
+ }
1791
+ return this._inspectionFromChildRow(row, this.getAgentToolOutput(runId));
1792
+ }
1793
+ _isStaleAgentToolChildRun(row) {
1794
+ return (row.status === "running" || row.status === "starting") && row.completed_at === null && !this._agentToolAbortControllers.has(row.run_id);
1795
+ }
1796
+ /**
1797
+ * Reconcile a stale (post-eviction) child run row from the child's own
1798
+ * durable recovery (#1630). The child facet self-heals its interrupted turn
1799
+ * via `chatRecovery`, but that path never writes the run row, so without this
1800
+ * the row strands `running` and the parent can only collect `interrupted`.
1801
+ *
1802
+ * Persisting the terminal here (rather than only computing it) is intentional:
1803
+ * it's a lazy materialization of the run's true terminal that also lets a
1804
+ * tailing parent's stream close promptly and makes subsequent inspects cheap.
1805
+ * While recovery is still resolving (active stream or in-progress incident)
1806
+ * the row is left `running` so the parent's bounded re-attach keeps waiting.
1807
+ */
1808
+ async _reconcileStaleAgentToolChildRun(runId) {
1809
+ const recovery = await this._classifyAgentToolChildRecovery();
1810
+ if (recovery === "in-progress" || this._resumableStream.hasActiveStream()) return;
1811
+ if (recovery !== "failed" && this._hasRecoveredAgentToolAssistantTurn(runId)) {
1812
+ const output = this.getAgentToolOutput(runId);
1813
+ const summary = this.getAgentToolSummary(runId, output);
1814
+ this.sql`
1815
+ UPDATE cf_agent_tool_child_runs
1816
+ SET status = 'completed',
1817
+ summary = ${summary},
1818
+ output_json = ${Think._stringifyAgentToolOutput(output)},
1819
+ error_message = null,
1820
+ completed_at = ${Date.now()}
1821
+ WHERE run_id = ${runId} AND completed_at IS NULL
1822
+ `;
1823
+ } else this.sql`
1824
+ UPDATE cf_agent_tool_child_runs
1825
+ SET status = 'error',
1826
+ error_message = ${"Agent tool run was interrupted before the child could finish."},
1827
+ completed_at = ${Date.now()}
1828
+ WHERE run_id = ${runId} AND completed_at IS NULL
1829
+ `;
1830
+ this._finalizeAgentToolChildRunTailers(runId);
1831
+ }
1832
+ /** Release a re-attached run's live tail + per-run streaming bookkeeping. */
1833
+ _finalizeAgentToolChildRunTailers(runId) {
1834
+ for (const close of this._agentToolClosers.get(runId) ?? []) close();
1835
+ this._agentToolClosers.delete(runId);
1836
+ this._agentToolForwarders.delete(runId);
1837
+ this._agentToolLiveSequences.delete(runId);
1838
+ this._agentToolLastErrors.delete(runId);
1839
+ this._agentToolPreTurnAssistantIds.delete(runId);
1157
1840
  }
1158
1841
  async getAgentToolChunks(runId, options) {
1159
1842
  const row = this._readAgentToolChildRun(runId);
@@ -1166,24 +1849,50 @@ var Think = class Think extends Agent {
1166
1849
  }
1167
1850
  async tailAgentToolRun(runId, options) {
1168
1851
  const self = this;
1852
+ const signal = options?.signal;
1853
+ let closed = false;
1854
+ let forward;
1855
+ const detach = () => {
1856
+ if (forward) {
1857
+ self._agentToolForwarders.get(runId)?.delete(forward);
1858
+ forward = void 0;
1859
+ }
1860
+ };
1169
1861
  return new ReadableStream({
1170
1862
  async start(controller) {
1863
+ const close = () => {
1864
+ if (closed) return;
1865
+ closed = true;
1866
+ detach();
1867
+ try {
1868
+ controller.close();
1869
+ } catch {}
1870
+ };
1871
+ if (signal?.aborted) {
1872
+ close();
1873
+ return;
1874
+ }
1875
+ signal?.addEventListener("abort", close, { once: true });
1171
1876
  const replayed = await self.getAgentToolChunks(runId, options);
1172
- for (const chunk of replayed) controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
1877
+ for (const chunk of replayed) {
1878
+ if (closed) return;
1879
+ controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
1880
+ }
1173
1881
  const lastReplay = replayed[replayed.length - 1]?.sequence;
1174
1882
  if (lastReplay !== void 0) self._agentToolLiveSequences.set(runId, lastReplay + 1);
1175
1883
  const row = self._readAgentToolChildRun(runId);
1176
1884
  if (!row || row.completed_at !== null) {
1177
- controller.close();
1885
+ close();
1178
1886
  return;
1179
1887
  }
1180
- const forward = (chunk) => {
1181
- if (chunk.sequence > (options?.afterSequence ?? -1)) controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
1182
- };
1183
- const close = () => {
1888
+ forward = (chunk) => {
1889
+ if (closed || chunk.sequence <= (options?.afterSequence ?? -1)) return;
1184
1890
  try {
1185
- controller.close();
1186
- } catch {}
1891
+ controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
1892
+ } catch {
1893
+ closed = true;
1894
+ detach();
1895
+ }
1187
1896
  };
1188
1897
  const forwarders = self._agentToolForwarders.get(runId) ?? /* @__PURE__ */ new Set();
1189
1898
  forwarders.add(forward);
@@ -1192,8 +1901,9 @@ var Think = class Think extends Agent {
1192
1901
  closers.add(close);
1193
1902
  self._agentToolClosers.set(runId, closers);
1194
1903
  },
1195
- cancel(reason) {
1196
- self.cancelAgentToolRun(runId, reason);
1904
+ cancel() {
1905
+ closed = true;
1906
+ detach();
1197
1907
  }
1198
1908
  });
1199
1909
  }
@@ -1213,9 +1923,18 @@ var Think = class Think extends Agent {
1213
1923
  return;
1214
1924
  }
1215
1925
  }
1926
+ /**
1927
+ * Whether the run produced an assistant turn (text or tool-only). Used by the
1928
+ * post-eviction reconcile to mark a settled run `completed` even when it ended
1929
+ * without final text. A dedicated child facet starts with no assistant
1930
+ * messages, so a missing in-memory pre-turn snapshot is treated as empty.
1931
+ */
1932
+ _hasRecoveredAgentToolAssistantTurn(runId) {
1933
+ const before = this._agentToolPreTurnAssistantIds.get(runId) ?? /* @__PURE__ */ new Set();
1934
+ return this.messages.some((msg) => msg.role === "assistant" && !before.has(msg.id));
1935
+ }
1216
1936
  _getAgentToolFinalText(runId) {
1217
- const before = this._agentToolPreTurnAssistantIds.get(runId);
1218
- if (!before) return null;
1937
+ const before = this._agentToolPreTurnAssistantIds.get(runId) ?? /* @__PURE__ */ new Set();
1219
1938
  for (const msg of this.messages) {
1220
1939
  if (msg.role !== "assistant" || before.has(msg.id)) continue;
1221
1940
  const text = msg.parts.map((part) => part.type === "text" ? part.text : "").filter((part) => part.length > 0).join("\n");
@@ -1223,6 +1942,255 @@ var Think = class Think extends Agent {
1223
1942
  }
1224
1943
  return null;
1225
1944
  }
1945
+ _ensureDeclaredScheduledTasksTable() {
1946
+ if (this._declaredScheduledTasksTableEnsured) return;
1947
+ this.sql`
1948
+ CREATE TABLE IF NOT EXISTS cf_think_scheduled_tasks (
1949
+ owner_key TEXT NOT NULL,
1950
+ task_id TEXT NOT NULL,
1951
+ schedule_hash TEXT NOT NULL,
1952
+ task_hash TEXT NOT NULL,
1953
+ schedule_id TEXT,
1954
+ next_run_at INTEGER,
1955
+ created_at INTEGER NOT NULL,
1956
+ updated_at INTEGER NOT NULL,
1957
+ PRIMARY KEY (owner_key, task_id)
1958
+ )
1959
+ `;
1960
+ this._declaredScheduledTasksTableEnsured = true;
1961
+ }
1962
+ _readDeclaredScheduledTaskRow(taskId) {
1963
+ this._ensureDeclaredScheduledTasksTable();
1964
+ const ownerKey = this._declaredScheduleOwnerKey();
1965
+ return this.sql`
1966
+ SELECT owner_key, task_id, schedule_hash, task_hash, schedule_id,
1967
+ next_run_at, created_at, updated_at
1968
+ FROM cf_think_scheduled_tasks
1969
+ WHERE task_id = ${taskId}
1970
+ AND owner_key = ${ownerKey}
1971
+ LIMIT 1
1972
+ `[0] ?? null;
1973
+ }
1974
+ _listDeclaredScheduledTaskRows() {
1975
+ this._ensureDeclaredScheduledTasksTable();
1976
+ const ownerKey = this._declaredScheduleOwnerKey();
1977
+ return this.sql`
1978
+ SELECT owner_key, task_id, schedule_hash, task_hash, schedule_id,
1979
+ next_run_at, created_at, updated_at
1980
+ FROM cf_think_scheduled_tasks
1981
+ WHERE owner_key = ${ownerKey}
1982
+ ORDER BY task_id ASC
1983
+ `;
1984
+ }
1985
+ _updateDeclaredScheduledTaskSchedule(task, ownerKey, scheduled, updatedAt = Date.now()) {
1986
+ this.sql`
1987
+ UPDATE cf_think_scheduled_tasks
1988
+ SET schedule_hash = ${task.scheduleHash},
1989
+ task_hash = ${task.taskHash},
1990
+ schedule_id = ${scheduled.scheduleId},
1991
+ next_run_at = ${scheduled.scheduledFor},
1992
+ updated_at = ${updatedAt}
1993
+ WHERE owner_key = ${ownerKey}
1994
+ AND task_id = ${task.taskId}
1995
+ `;
1996
+ }
1997
+ async _normalizeDeclaredScheduledTasks(tasks, defaultTimezone) {
1998
+ const normalized = /* @__PURE__ */ new Map();
1999
+ for (const [taskId, task] of Object.entries(tasks)) {
2000
+ if (!/^[A-Za-z0-9_-]+$/.test(taskId)) throw new Error(`Invalid scheduled task id "${taskId}"; use letters, numbers, "_" or "-"`);
2001
+ const schedule = parseDeclaredTaskSchedule(task.schedule, task.timezone, defaultTimezone);
2002
+ const hasPrompt = "prompt" in task && task.prompt !== void 0;
2003
+ const hasHandler = "handler" in task && task.handler !== void 0;
2004
+ if (hasPrompt === hasHandler) throw new Error(`Scheduled task "${taskId}" must define exactly one of prompt or handler`);
2005
+ const scheduleHash = stableHash({
2006
+ schedule,
2007
+ retry: task.retry
2008
+ });
2009
+ const taskHash = stableHash({
2010
+ scheduleHash,
2011
+ action: hasPrompt ? {
2012
+ type: "prompt",
2013
+ value: typeof task.prompt === "string" ? task.prompt : "<function>"
2014
+ } : { type: "handler" },
2015
+ metadata: task.metadata
2016
+ });
2017
+ normalized.set(taskId, {
2018
+ taskId,
2019
+ ...hasPrompt ? { prompt: task.prompt } : {},
2020
+ ...hasHandler ? { handler: task.handler } : {},
2021
+ schedule,
2022
+ retry: task.retry,
2023
+ metadata: task.metadata,
2024
+ scheduleHash,
2025
+ taskHash
2026
+ });
2027
+ }
2028
+ return normalized;
2029
+ }
2030
+ async _declaredScheduledTasksForNow() {
2031
+ const defaultTimezone = await this.getDefaultTimezone();
2032
+ const resolvedDefaultTimezone = defaultTimezone === void 0 ? void 0 : validateTimezone(defaultTimezone);
2033
+ return this._normalizeDeclaredScheduledTasks(await this.getScheduledTasks(), resolvedDefaultTimezone);
2034
+ }
2035
+ _declaredScheduleOwnerKey() {
2036
+ return stableHash(this.selfPath);
2037
+ }
2038
+ _declaredScheduleValidationError(rawSchedule, taskTimezone, defaultTimezone) {
2039
+ const result = tryParseDeclaredTaskSchedule(rawSchedule, taskTimezone, defaultTimezone === void 0 ? void 0 : validateTimezone(defaultTimezone));
2040
+ return result.ok ? null : result.error;
2041
+ }
2042
+ _nextDeclaredScheduleTimeForConfig(rawSchedule, now, options = {}) {
2043
+ const resolvedDefaultTimezone = options.defaultTimezone === void 0 ? void 0 : validateTimezone(options.defaultTimezone);
2044
+ return nextDeclaredScheduleTime(parseDeclaredTaskSchedule(rawSchedule, options.taskTimezone, resolvedDefaultTimezone), now, options.previousScheduledFor);
2045
+ }
2046
+ async _reconcileDeclaredScheduledTasks() {
2047
+ const tasks = await this._declaredScheduledTasksForNow();
2048
+ this._ensureDeclaredScheduledTasksTable();
2049
+ const ownerKey = this._declaredScheduleOwnerKey();
2050
+ const now = Date.now();
2051
+ const existing = this._listDeclaredScheduledTaskRows();
2052
+ const seen = /* @__PURE__ */ new Set();
2053
+ for (const [taskId, task] of tasks) {
2054
+ seen.add(taskId);
2055
+ const row = existing.find((candidate) => candidate.task_id === taskId);
2056
+ if (!row) {
2057
+ this.sql`
2058
+ INSERT INTO cf_think_scheduled_tasks (
2059
+ owner_key, task_id, schedule_hash, task_hash, schedule_id,
2060
+ next_run_at, created_at, updated_at
2061
+ )
2062
+ VALUES (
2063
+ ${ownerKey}, ${taskId}, ${task.scheduleHash}, ${task.taskHash},
2064
+ NULL, NULL, ${now}, ${now}
2065
+ )
2066
+ `;
2067
+ const scheduled = await this._scheduleDeclaredTaskOccurrence(task, new Date(now));
2068
+ this._updateDeclaredScheduledTaskSchedule(task, ownerKey, scheduled, now);
2069
+ continue;
2070
+ }
2071
+ if (row.schedule_hash !== task.scheduleHash) {
2072
+ if (row.schedule_id) await this.cancelSchedule(row.schedule_id);
2073
+ this.sql`
2074
+ UPDATE cf_think_scheduled_tasks
2075
+ SET schedule_hash = ${task.scheduleHash},
2076
+ task_hash = ${task.taskHash},
2077
+ schedule_id = NULL,
2078
+ next_run_at = NULL,
2079
+ updated_at = ${now}
2080
+ WHERE owner_key = ${ownerKey}
2081
+ AND task_id = ${taskId}
2082
+ `;
2083
+ const scheduled = await this._scheduleDeclaredTaskOccurrence(task, new Date(now));
2084
+ this._updateDeclaredScheduledTaskSchedule(task, ownerKey, scheduled, now);
2085
+ continue;
2086
+ }
2087
+ if (!row.schedule_id) {
2088
+ const scheduled = row.next_run_at === null ? await this._scheduleDeclaredTaskOccurrence(task, new Date(now)) : await this._scheduleDeclaredTaskOccurrenceAt(task, row.next_run_at);
2089
+ this._updateDeclaredScheduledTaskSchedule(task, ownerKey, scheduled, now);
2090
+ continue;
2091
+ }
2092
+ if (row.schedule_id) {
2093
+ if (!await this.getScheduleById(row.schedule_id)) {
2094
+ const scheduled = row.next_run_at === null ? await this._scheduleDeclaredTaskOccurrence(task, new Date(now)) : await this._scheduleDeclaredTaskOccurrenceAt(task, row.next_run_at);
2095
+ this._updateDeclaredScheduledTaskSchedule(task, ownerKey, scheduled, now);
2096
+ continue;
2097
+ }
2098
+ }
2099
+ if (row.task_hash !== task.taskHash) this.sql`
2100
+ UPDATE cf_think_scheduled_tasks
2101
+ SET task_hash = ${task.taskHash}, updated_at = ${now}
2102
+ WHERE owner_key = ${ownerKey}
2103
+ AND task_id = ${taskId}
2104
+ `;
2105
+ }
2106
+ for (const row of existing) {
2107
+ if (seen.has(row.task_id)) continue;
2108
+ if (row.schedule_id) await this.cancelSchedule(row.schedule_id);
2109
+ this.sql`
2110
+ DELETE FROM cf_think_scheduled_tasks
2111
+ WHERE owner_key = ${ownerKey}
2112
+ AND task_id = ${row.task_id}
2113
+ `;
2114
+ }
2115
+ }
2116
+ async _scheduleDeclaredTaskOccurrence(task, now, previousScheduledFor) {
2117
+ const next = nextDeclaredScheduleTime(task.schedule, now, previousScheduledFor);
2118
+ return this._scheduleDeclaredTaskOccurrenceAt(task, next.getTime());
2119
+ }
2120
+ async _scheduleDeclaredTaskOccurrenceAt(task, scheduledFor) {
2121
+ return {
2122
+ scheduleId: (await this.schedule(new Date(scheduledFor), "_runDeclaredScheduledTask", {
2123
+ taskId: task.taskId,
2124
+ scheduleHash: task.scheduleHash,
2125
+ scheduledFor
2126
+ }, { idempotent: true })).id,
2127
+ scheduledFor
2128
+ };
2129
+ }
2130
+ async _advanceDeclaredScheduledTask(task, payload, ownerKey) {
2131
+ const scheduled = await this._scheduleDeclaredTaskOccurrence(task, /* @__PURE__ */ new Date(), payload.scheduledFor);
2132
+ this._updateDeclaredScheduledTaskSchedule(task, ownerKey, scheduled);
2133
+ }
2134
+ _declaredScheduledTaskContext(task, payload, ownerKey) {
2135
+ const occurrenceKey = `${payload.taskId}:${payload.scheduledFor}`;
2136
+ return {
2137
+ taskId: payload.taskId,
2138
+ scheduledFor: payload.scheduledFor,
2139
+ scheduledForDate: new Date(payload.scheduledFor),
2140
+ occurrenceKey,
2141
+ idempotencyKey: `think-schedule:${ownerKey}:${occurrenceKey}`,
2142
+ schedule: task.schedule.normalizedSchedule,
2143
+ scheduleKind: task.schedule.kind,
2144
+ ...task.schedule.kind === "wall-clock" && { timezone: task.schedule.timezone },
2145
+ ...task.metadata !== void 0 && { metadata: task.metadata }
2146
+ };
2147
+ }
2148
+ async _runDeclaredScheduledTask(payload) {
2149
+ if (!payload || typeof payload.taskId !== "string" || typeof payload.scheduleHash !== "string" || typeof payload.scheduledFor !== "number") throw new Error("Invalid declared scheduled task payload");
2150
+ const row = this._readDeclaredScheduledTaskRow(payload.taskId);
2151
+ if (!row || row.schedule_hash !== payload.scheduleHash) return;
2152
+ if (row.next_run_at !== null && row.next_run_at > payload.scheduledFor) return;
2153
+ const task = (await this._declaredScheduledTasksForNow()).get(payload.taskId);
2154
+ if (!task || task.scheduleHash !== payload.scheduleHash) return;
2155
+ const ownerKey = this._declaredScheduleOwnerKey();
2156
+ const context = this._declaredScheduledTaskContext(task, payload, ownerKey);
2157
+ let actionError;
2158
+ try {
2159
+ await this.retry(async () => {
2160
+ if (task.prompt !== void 0) {
2161
+ const prompt = typeof task.prompt === "function" ? await task.prompt() : task.prompt;
2162
+ await this.submitMessages([{
2163
+ id: crypto.randomUUID(),
2164
+ role: "user",
2165
+ parts: [{
2166
+ type: "text",
2167
+ text: prompt
2168
+ }]
2169
+ }], {
2170
+ idempotencyKey: context.idempotencyKey,
2171
+ metadata: {
2172
+ ...task.metadata,
2173
+ source: "scheduled-task",
2174
+ ownerKey,
2175
+ taskId: payload.taskId,
2176
+ scheduledFor: payload.scheduledFor,
2177
+ schedule: task.schedule.normalizedSchedule
2178
+ }
2179
+ });
2180
+ } else await task.handler?.(context);
2181
+ }, task.retry);
2182
+ } catch (error) {
2183
+ actionError = error;
2184
+ } finally {
2185
+ await this._advanceDeclaredScheduledTask(task, payload, ownerKey);
2186
+ }
2187
+ if (actionError !== void 0) {
2188
+ console.error(`[Think] Scheduled task "${payload.taskId}" failed; next occurrence was still scheduled`, actionError);
2189
+ try {
2190
+ await this.onError(actionError);
2191
+ } catch {}
2192
+ }
2193
+ }
1226
2194
  _ensureSubmissionTable() {
1227
2195
  if (this._submissionTableEnsured) return;
1228
2196
  this.sql`
@@ -1255,6 +2223,34 @@ var Think = class Think extends Agent {
1255
2223
  `;
1256
2224
  this._submissionTableEnsured = true;
1257
2225
  }
2226
+ _ensureWorkflowNotificationTable() {
2227
+ if (this._workflowNotificationTableEnsured) return;
2228
+ this.sql`
2229
+ CREATE TABLE IF NOT EXISTS cf_think_workflow_notifications (
2230
+ notification_id TEXT PRIMARY KEY,
2231
+ submission_id TEXT NOT NULL,
2232
+ workflow_name TEXT NOT NULL,
2233
+ workflow_id TEXT NOT NULL,
2234
+ event_type TEXT NOT NULL,
2235
+ payload_json TEXT NOT NULL,
2236
+ attempts INTEGER NOT NULL DEFAULT 0,
2237
+ last_error TEXT,
2238
+ created_at INTEGER NOT NULL,
2239
+ updated_at INTEGER NOT NULL,
2240
+ delivered_at INTEGER
2241
+ )
2242
+ `;
2243
+ try {
2244
+ this.ctx.storage.sql.exec("ALTER TABLE cf_think_workflow_notifications ADD COLUMN delivered_at INTEGER");
2245
+ } catch (error) {
2246
+ if (!(error instanceof Error ? error.message : String(error)).toLowerCase().includes("duplicate column")) throw error;
2247
+ }
2248
+ this.sql`
2249
+ CREATE INDEX IF NOT EXISTS cf_think_workflow_notifications_created_idx
2250
+ ON cf_think_workflow_notifications (delivered_at, created_at, notification_id)
2251
+ `;
2252
+ this._workflowNotificationTableEnsured = true;
2253
+ }
1258
2254
  _readSubmission(submissionId) {
1259
2255
  this._ensureSubmissionTable();
1260
2256
  return this.sql`
@@ -1339,7 +2335,28 @@ var Think = class Think extends Agent {
1339
2335
  _serializeMetadata(metadata) {
1340
2336
  return metadata === void 0 ? null : JSON.stringify(metadata);
1341
2337
  }
1342
- async _emitSubmissionStatus(row) {
2338
+ _readWorkflowPromptContext(metadata) {
2339
+ const workflowPromptValue = metadata?.[THINK_WORKFLOW_PROMPT_METADATA_KEY];
2340
+ if (workflowPromptValue === null || typeof workflowPromptValue !== "object" || Array.isArray(workflowPromptValue)) return null;
2341
+ const workflowPrompt = workflowPromptValue;
2342
+ const workflowValue = workflowPrompt.workflow;
2343
+ if (workflowValue === null || typeof workflowValue !== "object" || Array.isArray(workflowValue)) return null;
2344
+ const workflowRecord = workflowValue;
2345
+ if (typeof workflowRecord.name !== "string" || typeof workflowRecord.id !== "string" || typeof workflowRecord.stepName !== "string" || typeof workflowRecord.eventType !== "string") return null;
2346
+ const output = workflowPrompt.output;
2347
+ const outputRecord = output !== null && typeof output === "object" && !Array.isArray(output) ? output : null;
2348
+ return {
2349
+ workflow: {
2350
+ name: workflowRecord.name,
2351
+ id: workflowRecord.id,
2352
+ stepName: workflowRecord.stepName,
2353
+ eventType: workflowRecord.eventType
2354
+ },
2355
+ ...outputRecord ? { output: { schema: outputRecord.schema } } : {},
2356
+ ...typeof workflowPrompt.fingerprint === "string" && { fingerprint: workflowPrompt.fingerprint }
2357
+ };
2358
+ }
2359
+ async _emitSubmissionStatus(row, output) {
1343
2360
  const inspection = this._inspectionFromSubmissionRow(row);
1344
2361
  this._emit("submission:status", {
1345
2362
  submissionId: inspection.submissionId,
@@ -1351,6 +2368,7 @@ var Think = class Think extends Agent {
1351
2368
  requestId: inspection.requestId,
1352
2369
  error: inspection.error
1353
2370
  });
2371
+ if (this._isTerminalSubmissionStatus(inspection.status)) await this._enqueueWorkflowNotification(inspection, output);
1354
2372
  await this.keepAliveWhile(async () => {
1355
2373
  try {
1356
2374
  await this.onSubmissionStatus(inspection);
@@ -1360,12 +2378,151 @@ var Think = class Think extends Agent {
1360
2378
  });
1361
2379
  }
1362
2380
  onSubmissionStatus(_submission) {}
1363
- async inspectSubmission(submissionId) {
1364
- const row = this._readSubmission(submissionId);
1365
- return row ? this._inspectionFromSubmissionRow(row) : null;
1366
- }
1367
- async listSubmissions(options) {
1368
- return this._listSubmissionRows(options).map((row) => this._inspectionFromSubmissionRow(row));
2381
+ async _enqueueWorkflowNotification(submission, output) {
2382
+ this._insertWorkflowNotification(submission, output);
2383
+ this._startWorkflowNotificationDrain();
2384
+ }
2385
+ _insertWorkflowNotification(submission, output, override) {
2386
+ const workflowPrompt = this._readWorkflowPromptContext(submission.metadata ?? null);
2387
+ if (!workflowPrompt) return false;
2388
+ this._ensureWorkflowNotificationTable();
2389
+ const now = Date.now();
2390
+ const status = override?.status ?? submission.status;
2391
+ const error = override?.error ?? submission.error;
2392
+ const payload = {
2393
+ submissionId: submission.submissionId,
2394
+ status,
2395
+ ...status === "completed" && { output },
2396
+ ...error && { error }
2397
+ };
2398
+ this.sql`
2399
+ INSERT OR IGNORE INTO cf_think_workflow_notifications (
2400
+ notification_id, submission_id, workflow_name, workflow_id, event_type,
2401
+ payload_json, attempts, last_error, created_at, updated_at, delivered_at
2402
+ )
2403
+ VALUES (
2404
+ ${`${submission.submissionId}:${workflowPrompt.workflow.eventType}`},
2405
+ ${submission.submissionId},
2406
+ ${workflowPrompt.workflow.name},
2407
+ ${workflowPrompt.workflow.id},
2408
+ ${workflowPrompt.workflow.eventType},
2409
+ ${JSON.stringify(payload)},
2410
+ 0,
2411
+ NULL,
2412
+ ${now},
2413
+ ${now},
2414
+ NULL
2415
+ )
2416
+ `;
2417
+ return true;
2418
+ }
2419
+ _recoverWorkflowNotifications() {
2420
+ this._ensureSubmissionTable();
2421
+ this._ensureWorkflowNotificationTable();
2422
+ const terminalRows = this.sql`
2423
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
2424
+ messages_json, metadata_json, error_message, created_at,
2425
+ messages_applied_at, started_at, completed_at
2426
+ FROM cf_think_submissions
2427
+ WHERE status IN ('aborted', 'skipped', 'error')
2428
+ ORDER BY completed_at DESC, created_at DESC
2429
+ LIMIT 100
2430
+ `;
2431
+ let recovered = false;
2432
+ for (const row of terminalRows) {
2433
+ const inspection = this._inspectionFromSubmissionRow(row);
2434
+ const workflowPrompt = this._readWorkflowPromptContext(inspection.metadata ?? null);
2435
+ if (!workflowPrompt) continue;
2436
+ const notificationId = `${inspection.submissionId}:${workflowPrompt.workflow.eventType}`;
2437
+ if (this.sql`
2438
+ SELECT notification_id
2439
+ FROM cf_think_workflow_notifications
2440
+ WHERE notification_id = ${notificationId}
2441
+ LIMIT 1
2442
+ `[0]) continue;
2443
+ recovered = this._insertWorkflowNotification(inspection) || recovered;
2444
+ }
2445
+ if (recovered) this._startWorkflowNotificationDrain();
2446
+ }
2447
+ _startWorkflowNotificationDrain() {
2448
+ this.keepAliveWhile(() => this._drainWorkflowNotifications()).catch((error) => {
2449
+ console.error("[Think] Failed to drain workflow notifications", error);
2450
+ this._scheduleWorkflowNotificationAlarm();
2451
+ });
2452
+ }
2453
+ _hasPendingWorkflowNotifications() {
2454
+ this._ensureWorkflowNotificationTable();
2455
+ return this.sql`
2456
+ SELECT notification_id
2457
+ FROM cf_think_workflow_notifications
2458
+ WHERE delivered_at IS NULL
2459
+ LIMIT 1
2460
+ `.length > 0;
2461
+ }
2462
+ async _drainWorkflowNotifications() {
2463
+ if (this._drainingWorkflowNotifications) return;
2464
+ this._ensureWorkflowNotificationTable();
2465
+ this._drainingWorkflowNotifications = true;
2466
+ try {
2467
+ const rows = this.sql`
2468
+ SELECT notification_id, submission_id, workflow_name, workflow_id,
2469
+ event_type, payload_json, attempts, last_error, created_at,
2470
+ updated_at, delivered_at
2471
+ FROM cf_think_workflow_notifications
2472
+ WHERE delivered_at IS NULL
2473
+ ORDER BY created_at ASC, notification_id ASC
2474
+ LIMIT 25
2475
+ `;
2476
+ for (const row of rows) try {
2477
+ const payload = JSON.parse(row.payload_json);
2478
+ await this.sendWorkflowEvent(row.workflow_name, row.workflow_id, {
2479
+ type: row.event_type,
2480
+ payload
2481
+ });
2482
+ this.sql`
2483
+ UPDATE cf_think_workflow_notifications
2484
+ SET payload_json = '{}',
2485
+ last_error = NULL,
2486
+ updated_at = ${Date.now()},
2487
+ delivered_at = ${Date.now()}
2488
+ WHERE notification_id = ${row.notification_id}
2489
+ AND delivered_at IS NULL
2490
+ `;
2491
+ } catch (error) {
2492
+ this.sql`
2493
+ UPDATE cf_think_workflow_notifications
2494
+ SET attempts = attempts + 1,
2495
+ last_error = ${error instanceof Error ? error.message : String(error)},
2496
+ updated_at = ${Date.now()}
2497
+ WHERE notification_id = ${row.notification_id}
2498
+ `;
2499
+ }
2500
+ } finally {
2501
+ this._drainingWorkflowNotifications = false;
2502
+ }
2503
+ await this._scheduleWorkflowNotificationAlarm();
2504
+ }
2505
+ async _scheduleWorkflowNotificationAlarm() {
2506
+ this._ensureWorkflowNotificationTable();
2507
+ const pending = this.sql`
2508
+ SELECT attempts
2509
+ FROM cf_think_workflow_notifications
2510
+ WHERE delivered_at IS NULL
2511
+ ORDER BY created_at ASC, notification_id ASC
2512
+ LIMIT 1
2513
+ `;
2514
+ if (!pending[0]) return;
2515
+ const delayMs = Math.min(300 * 1e3, 1e3 * 2 ** Math.min(pending[0].attempts, 8));
2516
+ const nextAlarm = Date.now() + delayMs;
2517
+ const existingAlarm = await this.ctx.storage.getAlarm();
2518
+ if (existingAlarm === null || existingAlarm > nextAlarm) await this.ctx.storage.setAlarm(nextAlarm);
2519
+ }
2520
+ async inspectSubmission(submissionId) {
2521
+ const row = this._readSubmission(submissionId);
2522
+ return row ? this._inspectionFromSubmissionRow(row) : null;
2523
+ }
2524
+ async listSubmissions(options) {
2525
+ return this._listSubmissionRows(options).map((row) => this._inspectionFromSubmissionRow(row));
1369
2526
  }
1370
2527
  async deleteSubmission(submissionId) {
1371
2528
  const row = this._readSubmission(submissionId);
@@ -1502,6 +2659,15 @@ var Think = class Think extends Agent {
1502
2659
  console.error("[Think] Failed to drain submissions", error);
1503
2660
  });
1504
2661
  }
2662
+ _hasPendingSubmissions() {
2663
+ this._ensureSubmissionTable();
2664
+ return this.sql`
2665
+ SELECT submission_id
2666
+ FROM cf_think_submissions
2667
+ WHERE status = 'pending'
2668
+ LIMIT 1
2669
+ `.length > 0;
2670
+ }
1505
2671
  async _drainThinkSubmissions() {
1506
2672
  await this._drainSubmissions();
1507
2673
  }
@@ -1543,11 +2709,16 @@ var Think = class Think extends Agent {
1543
2709
  await this._emitSubmissionStatus(claimed);
1544
2710
  const controller = new AbortController();
1545
2711
  this._submissionAbortControllers.set(row.submission_id, controller);
2712
+ let output;
1546
2713
  try {
1547
2714
  const messages = this._parseSubmissionMessages(row.messages_json);
2715
+ const metadata = this._parseJsonObject(row.metadata_json);
2716
+ const workflowPrompt = this._readWorkflowPromptContext(metadata);
1548
2717
  const result = await this._runProgrammaticMessagesTurn(requestId, messages, {
1549
2718
  signal: controller.signal,
1550
2719
  captureProgrammaticStreamError: true,
2720
+ captureOutput: Boolean(workflowPrompt?.output),
2721
+ workflowPrompt: workflowPrompt ?? void 0,
1551
2722
  onMessagesApplied: () => {
1552
2723
  this.sql`
1553
2724
  UPDATE cf_think_submissions
@@ -1558,34 +2729,55 @@ var Think = class Think extends Agent {
1558
2729
  `;
1559
2730
  }
1560
2731
  });
2732
+ output = result.output;
1561
2733
  const streamId = this._resumableStream.getAllStreamMetadata().find((metadata) => metadata.request_id === result.requestId)?.id ?? null;
1562
2734
  const streamError = this._programmaticStreamErrors.get(result.requestId);
1563
2735
  const finalStatus = this._getSubmissionFinalStatus(result.status, result.error ?? streamError);
1564
2736
  const errorMessage = result.error ?? streamError ?? null;
1565
- this.sql`
1566
- UPDATE cf_think_submissions
1567
- SET status = ${finalStatus},
1568
- request_id = ${result.requestId},
1569
- stream_id = ${streamId},
1570
- error_message = ${finalStatus === "error" ? errorMessage : null},
1571
- completed_at = ${Date.now()}
1572
- WHERE submission_id = ${row.submission_id}
1573
- AND status = 'running'
1574
- `;
2737
+ const completedAt = Date.now();
2738
+ this.ctx.storage.transactionSync(() => {
2739
+ this.sql`
2740
+ UPDATE cf_think_submissions
2741
+ SET status = ${finalStatus},
2742
+ request_id = ${result.requestId},
2743
+ stream_id = ${streamId},
2744
+ error_message = ${finalStatus === "error" ? errorMessage : null},
2745
+ completed_at = ${completedAt}
2746
+ WHERE submission_id = ${row.submission_id}
2747
+ AND status = 'running'
2748
+ `;
2749
+ this._insertWorkflowNotification({
2750
+ ...this._inspectionFromSubmissionRow(claimed),
2751
+ requestId: result.requestId,
2752
+ status: finalStatus,
2753
+ error: finalStatus === "error" ? errorMessage ?? void 0 : void 0,
2754
+ completedAt
2755
+ }, output);
2756
+ });
1575
2757
  } catch (error) {
1576
- this.sql`
1577
- UPDATE cf_think_submissions
1578
- SET status = 'error',
1579
- error_message = ${error instanceof Error ? error.message : String(error)},
1580
- completed_at = ${Date.now()}
1581
- WHERE submission_id = ${row.submission_id}
1582
- AND status = 'running'
1583
- `;
2758
+ const errorMessage = error instanceof Error ? error.message : String(error);
2759
+ const completedAt = Date.now();
2760
+ this.ctx.storage.transactionSync(() => {
2761
+ this.sql`
2762
+ UPDATE cf_think_submissions
2763
+ SET status = 'error',
2764
+ error_message = ${errorMessage},
2765
+ completed_at = ${completedAt}
2766
+ WHERE submission_id = ${row.submission_id}
2767
+ AND status = 'running'
2768
+ `;
2769
+ this._insertWorkflowNotification({
2770
+ ...this._inspectionFromSubmissionRow(claimed),
2771
+ status: "error",
2772
+ error: errorMessage,
2773
+ completedAt
2774
+ });
2775
+ });
1584
2776
  } finally {
1585
2777
  this._programmaticStreamErrors.delete(requestId);
1586
2778
  this._submissionAbortControllers.delete(row.submission_id);
1587
2779
  const updated = this._readSubmission(row.submission_id);
1588
- if (updated && this._isTerminalSubmissionStatus(updated.status)) await this._emitSubmissionStatus(updated);
2780
+ if (updated && this._isTerminalSubmissionStatus(updated.status)) await this._emitSubmissionStatus(updated, output);
1589
2781
  }
1590
2782
  }
1591
2783
  _getSubmissionFinalStatus(resultStatus, streamError) {
@@ -1781,10 +2973,11 @@ var Think = class Think extends Agent {
1781
2973
  }
1782
2974
  async _runProgrammaticMessagesTurn(requestId, messages, options) {
1783
2975
  const clientTools = this._lastClientTools;
1784
- const body = this._lastBody;
2976
+ const body = options?.body ?? this._lastBody;
1785
2977
  const epoch = this._turnQueue.generation;
1786
2978
  let status = "completed";
1787
2979
  let error;
2980
+ let output;
1788
2981
  let wasAborted = false;
1789
2982
  await this.keepAliveWhile(async () => {
1790
2983
  await this._turnQueue.enqueue(requestId, async () => {
@@ -1813,12 +3006,17 @@ var Think = class Think extends Agent {
1813
3006
  signal: abortSignal,
1814
3007
  clientTools,
1815
3008
  body,
3009
+ workflowPrompt: options?.workflowPrompt,
1816
3010
  continuation: false
1817
3011
  }));
1818
3012
  if (result) {
1819
- const streamResult = await this._streamResult(requestId, result, abortSignal, { captureProgrammaticStreamError: options?.captureProgrammaticStreamError });
3013
+ const streamResult = await this._streamResult(requestId, result, abortSignal, {
3014
+ captureProgrammaticStreamError: options?.captureProgrammaticStreamError,
3015
+ captureOutput: options?.captureOutput
3016
+ });
1820
3017
  status = streamResult.status;
1821
3018
  error = streamResult.error;
3019
+ output = streamResult.output;
1822
3020
  }
1823
3021
  };
1824
3022
  if (this.chatRecovery) await this._runChatRecoveryFiber(requestId, false, programmaticBody);
@@ -1835,7 +3033,8 @@ var Think = class Think extends Agent {
1835
3033
  return {
1836
3034
  requestId,
1837
3035
  status,
1838
- ...error !== void 0 && { error }
3036
+ ...error !== void 0 && { error },
3037
+ ...output !== void 0 && { output }
1839
3038
  };
1840
3039
  }
1841
3040
  /**
@@ -1972,18 +3171,13 @@ var Think = class Think extends Agent {
1972
3171
  this.onConnect = async (connection, ctx) => {
1973
3172
  if (this._cf_requestTargetsSubAgent(ctx.request)) return _onConnect(connection, ctx);
1974
3173
  if (this._resumableStream.hasActiveStream()) this._notifyStreamResuming(connection);
1975
- else connection.send(JSON.stringify({
1976
- type: MSG_CHAT_MESSAGES,
1977
- messages: this.messages
1978
- }));
3174
+ else for (const message of await this._buildIdleConnectMessages()) connection.send(JSON.stringify(message));
1979
3175
  return _onConnect(connection, ctx);
1980
3176
  };
1981
3177
  const _onClose = this.onClose.bind(this);
1982
3178
  this.onClose = async (connection, code, reason, wasClean) => {
1983
3179
  this._pendingResumeConnections.delete(connection.id);
1984
- this._continuation.awaitingConnections.delete(connection.id);
1985
- if (this._continuation.pending?.connectionId === connection.id) this._continuation.pending = null;
1986
- if (this._continuation.activeConnectionId === connection.id) this._continuation.activeConnectionId = null;
3180
+ this._continuation.releaseConnection(connection.id);
1987
3181
  return _onClose(connection, code, reason, wasClean);
1988
3182
  };
1989
3183
  const _onMessage = this.onMessage.bind(this);
@@ -2002,6 +3196,8 @@ var Think = class Think extends Agent {
2002
3196
  this.onRequest = async (request) => {
2003
3197
  const url = new URL(request.url);
2004
3198
  if (url.pathname === "/get-messages" || url.pathname.endsWith("/get-messages")) return Response.json(this.messages);
3199
+ const messengerResponse = await this._messengerRuntime?.handleRequest(request);
3200
+ if (messengerResponse) return messengerResponse;
2005
3201
  return _onRequest(request);
2006
3202
  };
2007
3203
  }
@@ -2016,34 +3212,18 @@ var Think = class Think extends Agent {
2016
3212
  case "chat-request":
2017
3213
  if (event.init?.method === "POST") await this._handleChatRequest(connection, event);
2018
3214
  break;
2019
- case "tool-result": {
3215
+ case "tool-result":
2020
3216
  if (event.clientTools && Array.isArray(event.clientTools) && event.clientTools.length > 0) {
2021
3217
  this._lastClientTools = event.clientTools;
2022
3218
  this._persistClientTools();
2023
3219
  }
2024
- const resultPromise = Promise.resolve().then(async () => {
2025
- await this._applyToolResult(event.toolCallId, event.output, event.state, event.errorText);
2026
- return true;
2027
- });
2028
- this._pendingInteractionPromise = resultPromise;
2029
- resultPromise.finally(() => {
2030
- if (this._pendingInteractionPromise === resultPromise) this._pendingInteractionPromise = null;
2031
- }).catch(() => {});
3220
+ this._enqueueInteractionApply(() => this._applyToolResult(event.toolCallId, event.output, event.state, event.errorText));
2032
3221
  if (event.autoContinue) this._scheduleAutoContinuation(connection);
2033
3222
  break;
2034
- }
2035
- case "tool-approval": {
2036
- const approvalPromise = Promise.resolve().then(async () => {
2037
- await this._applyToolApproval(event.toolCallId, event.approved);
2038
- return true;
2039
- });
2040
- this._pendingInteractionPromise = approvalPromise;
2041
- approvalPromise.finally(() => {
2042
- if (this._pendingInteractionPromise === approvalPromise) this._pendingInteractionPromise = null;
2043
- }).catch(() => {});
3223
+ case "tool-approval":
3224
+ this._enqueueInteractionApply(() => this._applyToolApproval(event.toolCallId, event.approved));
2044
3225
  if (event.autoContinue) this._scheduleAutoContinuation(connection);
2045
3226
  break;
2046
- }
2047
3227
  case "clear":
2048
3228
  await this._handleClear(connection);
2049
3229
  break;
@@ -2056,7 +3236,7 @@ var Think = class Think extends Agent {
2056
3236
  _handleStreamResumeRequest(connection) {
2057
3237
  if (this._resumableStream.hasActiveStream()) if (this._continuation.activeRequestId === this._resumableStream.activeRequestId && this._continuation.activeConnectionId !== null && this._continuation.activeConnectionId !== connection.id) sendIfOpen(connection, JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
2058
3238
  else this._notifyStreamResuming(connection);
2059
- else if (this._continuation.pending !== null && this._continuation.pending.connectionId === connection.id) this._continuation.awaitingConnections.set(connection.id, connection);
3239
+ else if (this._continuation.pending !== null && (this._continuation.pending.connectionId === null || this._continuation.pending.connectionId === connection.id)) this._continuation.awaitingConnections.set(connection.id, connection);
2060
3240
  else sendIfOpen(connection, JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
2061
3241
  }
2062
3242
  async _handleStreamResumeAck(connection, requestId) {
@@ -2077,7 +3257,18 @@ var Think = class Think extends Agent {
2077
3257
  let rawParsed;
2078
3258
  try {
2079
3259
  rawParsed = JSON.parse(event.init.body);
2080
- } catch {
3260
+ } catch (error) {
3261
+ const wrapped = this.onChatError(error, {
3262
+ requestId: event.id,
3263
+ stage: "parse",
3264
+ messagesPersisted: false
3265
+ });
3266
+ this._emit("chat:request:failed", {
3267
+ requestId: event.id,
3268
+ stage: "parse",
3269
+ messagesPersisted: false,
3270
+ error: wrapped instanceof Error ? wrapped.message : String(wrapped)
3271
+ });
2081
3272
  return;
2082
3273
  }
2083
3274
  const { messages: incomingMessages, clientTools: rawClientTools, trigger: rawTrigger, ...customBody } = rawParsed;
@@ -2085,6 +3276,8 @@ var Think = class Think extends Agent {
2085
3276
  const isRegeneration = rawTrigger === "regenerate-message";
2086
3277
  const isSubmitMessage = !isRegeneration;
2087
3278
  const requestId = event.id;
3279
+ let messagesPersisted = false;
3280
+ let failureStage = "persist";
2088
3281
  const concurrencyDecision = this._getSubmitConcurrencyDecision(isSubmitMessage);
2089
3282
  if (concurrencyDecision.action === "drop") {
2090
3283
  this._rollbackDroppedSubmit(connection);
@@ -2134,6 +3327,8 @@ var Think = class Think extends Agent {
2134
3327
  }
2135
3328
  await this._syncMessages();
2136
3329
  this._broadcastMessages([connection.id]);
3330
+ messagesPersisted = true;
3331
+ failureStage = "turn";
2137
3332
  const abortSignal = this._aborts.getSignal(requestId);
2138
3333
  await this.keepAliveWhile(async () => {
2139
3334
  const turnPromise = this._turnQueue.enqueue(requestId, async () => {
@@ -2184,10 +3379,23 @@ var Think = class Think extends Agent {
2184
3379
  });
2185
3380
  });
2186
3381
  } catch (error) {
3382
+ const wrapped = this.onChatError(error, {
3383
+ requestId,
3384
+ stage: failureStage,
3385
+ messagesPersisted
3386
+ });
3387
+ const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
3388
+ this._emit("chat:request:failed", {
3389
+ requestId,
3390
+ stage: failureStage,
3391
+ messagesPersisted,
3392
+ error: errorMessage
3393
+ });
3394
+ await this._recordTerminalChatStatus("error", requestId, errorMessage);
2187
3395
  this._broadcastChat({
2188
3396
  type: MSG_CHAT_RESPONSE,
2189
3397
  id: requestId,
2190
- body: error instanceof Error ? error.message : "Error",
3398
+ body: errorMessage,
2191
3399
  done: true,
2192
3400
  error: true
2193
3401
  });
@@ -2219,6 +3427,9 @@ var Think = class Think extends Agent {
2219
3427
  }
2220
3428
  this._submitConcurrency.reset();
2221
3429
  this._pendingInteractionPromise = null;
3430
+ this._interactionApplyTail = Promise.resolve();
3431
+ this._streamingAssistant = null;
3432
+ this._continuationBarrierActive = false;
2222
3433
  this._continuation.sendResumeNone();
2223
3434
  this._continuation.clearAll();
2224
3435
  }
@@ -2281,18 +3492,29 @@ var Think = class Think extends Agent {
2281
3492
  async _streamResultToRpcCallback(requestId, result, callback, abortSignal) {
2282
3493
  const streamId = this._resumableStream.start(requestId);
2283
3494
  const accumulator = new StreamAccumulator({ messageId: crypto.randomUUID() });
3495
+ this._streamingAssistant = accumulator;
2284
3496
  let streamFinalized = false;
2285
3497
  let assistantMsg = null;
2286
3498
  let aborted = false;
2287
3499
  let doneSent = false;
2288
3500
  let streamError;
2289
3501
  let pendingRpcError;
3502
+ const stallTimeoutMs = this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
2290
3503
  try {
2291
3504
  this._insideInferenceLoop = true;
2292
- let chunksSinceFlush = 0;
2293
- let hasFlushedContent = false;
3505
+ const flushState = {
3506
+ chunksSinceFlush: 0,
3507
+ hasFlushedContent: false
3508
+ };
2294
3509
  try {
2295
- for await (const chunk of result.toUIMessageStream()) {
3510
+ const guardedStream = this._iterateWithStallWatchdog(result.toUIMessageStream(), stallTimeoutMs, () => {
3511
+ this._emit("chat:stream:stalled", {
3512
+ requestId,
3513
+ timeoutMs: stallTimeoutMs
3514
+ });
3515
+ this.abortRequest(requestId, /* @__PURE__ */ new Error("chat stream stalled: inactivity watchdog fired"));
3516
+ });
3517
+ for await (const chunk of guardedStream) {
2296
3518
  if (abortSignal?.aborted) {
2297
3519
  aborted = true;
2298
3520
  break;
@@ -2302,6 +3524,12 @@ var Think = class Think extends Agent {
2302
3524
  if (action?.type === "error") {
2303
3525
  streamError = action.error;
2304
3526
  this._emit("message:error", { error: streamError });
3527
+ this._emit("chat:request:failed", {
3528
+ requestId,
3529
+ stage: "stream",
3530
+ messagesPersisted: true,
3531
+ error: streamError
3532
+ });
2305
3533
  this._broadcastChat({
2306
3534
  type: MSG_CHAT_RESPONSE,
2307
3535
  id: requestId,
@@ -2312,13 +3540,7 @@ var Think = class Think extends Agent {
2312
3540
  break;
2313
3541
  }
2314
3542
  const chunkBody = JSON.stringify(chunk);
2315
- this._resumableStream.storeChunk(streamId, chunkBody);
2316
- chunksSinceFlush++;
2317
- if (this._shouldFlushRpcStreamChunk(streamChunk, chunksSinceFlush, hasFlushedContent)) {
2318
- this._resumableStream.flushBuffer();
2319
- chunksSinceFlush = 0;
2320
- hasFlushedContent = true;
2321
- }
3543
+ await this._storeChunkDurably(streamId, streamChunk, chunkBody, flushState);
2322
3544
  this._broadcastChat({
2323
3545
  type: MSG_CHAT_RESPONSE,
2324
3546
  id: requestId,
@@ -2369,6 +3591,45 @@ var Think = class Think extends Agent {
2369
3591
  status: "aborted"
2370
3592
  });
2371
3593
  } catch (error) {
3594
+ if (error instanceof ChatStreamStalledError) {
3595
+ if (!assistantMsg && accumulator.parts.length > 0) {
3596
+ assistantMsg = accumulator.toMessage();
3597
+ await this._persistAssistantMessage(assistantMsg);
3598
+ this._broadcastMessages();
3599
+ }
3600
+ const outcome = await this._routeStallToBoundedRecovery({
3601
+ requestId,
3602
+ streamId,
3603
+ partialParts: (assistantMsg ?? accumulator.toMessage()).parts,
3604
+ targetAssistantId: assistantMsg?.id
3605
+ });
3606
+ if (outcome === "scheduled") {
3607
+ if (!streamFinalized) {
3608
+ this._resumableStream.complete(streamId);
3609
+ streamFinalized = true;
3610
+ }
3611
+ if (!doneSent) {
3612
+ this._broadcastChat({
3613
+ type: MSG_CHAT_RESPONSE,
3614
+ id: requestId,
3615
+ body: "",
3616
+ done: true
3617
+ });
3618
+ doneSent = true;
3619
+ }
3620
+ await callback.onInterrupted?.();
3621
+ return;
3622
+ }
3623
+ if (outcome === "exhausted") {
3624
+ if (!streamFinalized) {
3625
+ this._resumableStream.markError(streamId);
3626
+ streamFinalized = true;
3627
+ }
3628
+ doneSent = true;
3629
+ await callback.onInterrupted?.();
3630
+ return;
3631
+ }
3632
+ }
2372
3633
  if (!streamFinalized) {
2373
3634
  this._resumableStream.markError(streamId);
2374
3635
  streamFinalized = true;
@@ -2389,8 +3650,18 @@ var Think = class Think extends Agent {
2389
3650
  await this._persistAssistantMessage(assistantMsg);
2390
3651
  this._broadcastMessages();
2391
3652
  }
2392
- const wrapped = this.onChatError(error);
3653
+ const wrapped = this.onChatError(error, {
3654
+ requestId,
3655
+ stage: "stream",
3656
+ messagesPersisted: true
3657
+ });
2393
3658
  const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
3659
+ this._emit("chat:request:failed", {
3660
+ requestId,
3661
+ stage: "stream",
3662
+ messagesPersisted: true,
3663
+ error: errorMessage
3664
+ });
2394
3665
  if (assistantMsg) await this._fireResponseHook({
2395
3666
  message: assistantMsg,
2396
3667
  requestId,
@@ -2398,14 +3669,89 @@ var Think = class Think extends Agent {
2398
3669
  status: "error",
2399
3670
  error: errorMessage
2400
3671
  });
2401
- if (callback.onError) await callback.onError(errorMessage);
2402
- else throw wrapped;
3672
+ await callback.onError(errorMessage);
3673
+ } finally {
3674
+ this._streamingAssistant = null;
2403
3675
  }
2404
- if (pendingRpcError) if (callback.onError) await callback.onError(pendingRpcError);
2405
- else throw new Error(pendingRpcError);
3676
+ if (pendingRpcError) await callback.onError(pendingRpcError);
2406
3677
  }
2407
- _shouldFlushRpcStreamChunk(chunk, chunksSinceFlush, hasFlushedContent) {
2408
- return (chunk.type === "text-delta" || chunk.type === "reasoning-delta" || chunk.type === "tool-input-available" || chunk.type === "tool-output-available" || chunk.type === "tool-output-error") && (!hasFlushedContent || chunksSinceFlush >= 10);
3678
+ /**
3679
+ * Whether storing this chunk should immediately flush the resumable-stream
3680
+ * buffer to SQLite.
3681
+ *
3682
+ * A settled tool result (`tool-output-available` / `tool-output-error` /
3683
+ * `tool-output-denied`) captures a completed, often non-idempotent side
3684
+ * effect — or, for a denial, a user decision — so it is flushed
3685
+ * **immediately**. An isolate eviction (deploy) before the next batch flush
3686
+ * would otherwise lose it, and recovery would re-anchor without it and re-run
3687
+ * the already-completed tool call (or drop the denial). Frequent recoverable
3688
+ * content (text / reasoning / tool-input streaming) is throttled to avoid
3689
+ * write amplification.
3690
+ */
3691
+ _shouldFlushRecoverableChunk(chunk, chunksSinceFlush, hasFlushedContent) {
3692
+ if (chunk.type === "tool-output-available" || chunk.type === "tool-output-error" || chunk.type === "tool-output-denied") return true;
3693
+ return (chunk.type === "text-delta" || chunk.type === "reasoning-delta" || chunk.type === "tool-input-available") && (!hasFlushedContent || chunksSinceFlush >= 10);
3694
+ }
3695
+ /**
3696
+ * Store a stream chunk, flushing settled tool results durably and promptly.
3697
+ * Shared by the WebSocket and sub-agent RPC streaming paths so both get
3698
+ * tool-call-level recovery durability (recovery loses at most the in-flight
3699
+ * step, never an already-completed tool call).
3700
+ */
3701
+ async _storeChunkDurably(streamId, chunk, chunkBody, state) {
3702
+ this._resumableStream.storeChunk(streamId, chunkBody);
3703
+ state.chunksSinceFlush++;
3704
+ if (this._shouldFlushRecoverableChunk(chunk, state.chunksSinceFlush, state.hasFlushedContent)) {
3705
+ this._resumableStream.flushBuffer();
3706
+ state.chunksSinceFlush = 0;
3707
+ state.hasFlushedContent = true;
3708
+ await this._bumpChatRecoveryProgress();
3709
+ }
3710
+ }
3711
+ /**
3712
+ * Wrap a UI-message stream with an inactivity watchdog. If no chunk arrives
3713
+ * within `timeoutMs`, `onStall` runs (aborting the upstream model stream) and
3714
+ * the iterator throws, so the consumer loop exits with a terminal error
3715
+ * instead of parking forever on a hung provider/transport. `timeoutMs <= 0`
3716
+ * passes the source through untouched.
3717
+ */
3718
+ async *_iterateWithStallWatchdog(source, timeoutMs, onStall) {
3719
+ if (!(timeoutMs > 0)) {
3720
+ yield* source;
3721
+ return;
3722
+ }
3723
+ const iterator = source[Symbol.asyncIterator]();
3724
+ let selfAborted = false;
3725
+ try {
3726
+ while (true) {
3727
+ let timer;
3728
+ let stalled = false;
3729
+ const stall = new Promise((_, reject) => {
3730
+ timer = setTimeout(() => {
3731
+ stalled = true;
3732
+ reject(new ChatStreamStalledError(`Chat stream stalled: no activity for ${timeoutMs}ms; the turn was aborted by the stall watchdog.`));
3733
+ }, timeoutMs);
3734
+ });
3735
+ const nextPromise = iterator.next();
3736
+ nextPromise.catch(() => {});
3737
+ let next;
3738
+ try {
3739
+ next = await Promise.race([nextPromise, stall]);
3740
+ } catch (err) {
3741
+ if (stalled) {
3742
+ selfAborted = true;
3743
+ onStall();
3744
+ }
3745
+ throw err;
3746
+ } finally {
3747
+ if (timer !== void 0) clearTimeout(timer);
3748
+ }
3749
+ if (next.done) return;
3750
+ yield next.value;
3751
+ }
3752
+ } finally {
3753
+ if (!selfAborted) await iterator.return?.(void 0).catch(() => {});
3754
+ }
2409
3755
  }
2410
3756
  async _streamResult(requestId, result, abortSignal, options) {
2411
3757
  const clearGen = this._turnQueue.generation;
@@ -2417,38 +3763,62 @@ var Think = class Think extends Agent {
2417
3763
  this._continuation.flushAwaitingConnections((c) => this._notifyStreamResuming(c));
2418
3764
  }
2419
3765
  const accumulator = new StreamAccumulator({ messageId: crypto.randomUUID() });
3766
+ this._streamingAssistant = accumulator;
2420
3767
  let doneSent = false;
2421
3768
  let streamAborted = false;
2422
3769
  let streamError;
3770
+ let output;
3771
+ const flushState = {
3772
+ chunksSinceFlush: 0,
3773
+ hasFlushedContent: false
3774
+ };
3775
+ const stallTimeoutMs = this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
2423
3776
  try {
2424
3777
  this._insideInferenceLoop = true;
2425
3778
  try {
2426
- for await (const chunk of result.toUIMessageStream()) {
3779
+ const guardedStream = this._iterateWithStallWatchdog(result.toUIMessageStream(), stallTimeoutMs, () => {
3780
+ this._emit("chat:stream:stalled", {
3781
+ requestId,
3782
+ timeoutMs: stallTimeoutMs
3783
+ });
3784
+ this.abortRequest(requestId, /* @__PURE__ */ new Error("chat stream stalled: inactivity watchdog fired"));
3785
+ });
3786
+ for await (const chunk of guardedStream) {
2427
3787
  if (abortSignal?.aborted) {
2428
3788
  streamAborted = true;
2429
3789
  break;
2430
3790
  }
2431
- const { action } = accumulator.applyChunk(chunk);
3791
+ const streamChunk = chunk;
3792
+ const { action } = accumulator.applyChunk(streamChunk);
3793
+ if (action?.type === "cross-message-tool-update") await this._applyToolUpdateToMessages(crossMessageToolResultUpdate(action.toolCallId, action.updateType, action.output, action.errorText, action.preliminary));
2432
3794
  if (action?.type === "error") {
2433
3795
  streamError = action.error;
2434
3796
  if (options?.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
2435
3797
  this._emit("message:error", { error: streamError });
3798
+ this._emit("chat:request:failed", {
3799
+ requestId,
3800
+ stage: "stream",
3801
+ messagesPersisted: true,
3802
+ error: streamError
3803
+ });
2436
3804
  this._broadcastChat({
2437
3805
  type: MSG_CHAT_RESPONSE,
2438
3806
  id: requestId,
2439
3807
  body: action.error,
2440
3808
  done: false,
2441
- error: true
3809
+ error: true,
3810
+ ...continuation && { continuation: true }
2442
3811
  });
2443
3812
  break;
2444
3813
  }
2445
3814
  const chunkBody = JSON.stringify(chunk);
2446
- this._resumableStream.storeChunk(streamId, chunkBody);
3815
+ await this._storeChunkDurably(streamId, streamChunk, chunkBody, flushState);
2447
3816
  this._broadcastChat({
2448
3817
  type: MSG_CHAT_RESPONSE,
2449
3818
  id: requestId,
2450
3819
  body: chunkBody,
2451
- done: false
3820
+ done: false,
3821
+ ...continuation && { continuation: true }
2452
3822
  });
2453
3823
  }
2454
3824
  } finally {
@@ -2461,10 +3831,49 @@ var Think = class Think extends Agent {
2461
3831
  type: MSG_CHAT_RESPONSE,
2462
3832
  id: requestId,
2463
3833
  body: "",
2464
- done: true
3834
+ done: true,
3835
+ ...continuation && { continuation: true }
2465
3836
  });
2466
3837
  doneSent = true;
2467
3838
  } catch (error) {
3839
+ if (error instanceof ChatStreamStalledError) {
3840
+ let targetAssistantId;
3841
+ const partialMsg = accumulator.toMessage();
3842
+ if (this._turnQueue.generation === clearGen && accumulator.parts.length > 0) {
3843
+ await this._persistAssistantMessage(partialMsg, parentId);
3844
+ this._broadcastMessages();
3845
+ targetAssistantId = partialMsg.id;
3846
+ }
3847
+ const outcome = await this._routeStallToBoundedRecovery({
3848
+ requestId,
3849
+ streamId,
3850
+ partialParts: partialMsg.parts,
3851
+ targetAssistantId
3852
+ });
3853
+ if (outcome === "scheduled") {
3854
+ this._resumableStream.complete(streamId);
3855
+ this._pendingResumeConnections.clear();
3856
+ if (!doneSent) {
3857
+ this._broadcastChat({
3858
+ type: MSG_CHAT_RESPONSE,
3859
+ id: requestId,
3860
+ body: "",
3861
+ done: true,
3862
+ ...continuation && { continuation: true }
3863
+ });
3864
+ doneSent = true;
3865
+ }
3866
+ this._streamingAssistant = null;
3867
+ return { status: "aborted" };
3868
+ }
3869
+ if (outcome === "exhausted") {
3870
+ this._resumableStream.markError(streamId);
3871
+ this._pendingResumeConnections.clear();
3872
+ doneSent = true;
3873
+ this._streamingAssistant = null;
3874
+ return { status: "aborted" };
3875
+ }
3876
+ }
2468
3877
  streamError = error instanceof Error ? error.message : "Stream error";
2469
3878
  if (options?.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
2470
3879
  this._resumableStream.markError(streamId);
@@ -2475,7 +3884,8 @@ var Think = class Think extends Agent {
2475
3884
  id: requestId,
2476
3885
  body: streamError,
2477
3886
  done: true,
2478
- error: true
3887
+ error: true,
3888
+ ...continuation && { continuation: true }
2479
3889
  });
2480
3890
  doneSent = true;
2481
3891
  }
@@ -2487,10 +3897,17 @@ var Think = class Think extends Agent {
2487
3897
  type: MSG_CHAT_RESPONSE,
2488
3898
  id: requestId,
2489
3899
  body: "",
2490
- done: true
3900
+ done: true,
3901
+ ...continuation && { continuation: true }
2491
3902
  });
2492
3903
  }
2493
3904
  }
3905
+ if (options?.captureOutput && result.output && !streamError && !streamAborted) try {
3906
+ output = await result.output;
3907
+ } catch (error) {
3908
+ streamError = error instanceof Error ? error.message : "Structured output error";
3909
+ if (options.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
3910
+ }
2494
3911
  if (this._turnQueue.generation === clearGen) try {
2495
3912
  const assistantMsg = accumulator.toMessage();
2496
3913
  if (accumulator.parts.length > 0) {
@@ -2507,10 +3924,14 @@ var Think = class Think extends Agent {
2507
3924
  } catch (e) {
2508
3925
  console.error("Failed to persist assistant message:", e);
2509
3926
  }
3927
+ this._streamingAssistant = null;
2510
3928
  return streamError ? {
2511
3929
  status: "error",
2512
3930
  error: streamError
2513
- } : { status: streamAborted ? "aborted" : "completed" };
3931
+ } : {
3932
+ status: streamAborted ? "aborted" : "completed",
3933
+ ...output !== void 0 && { output }
3934
+ };
2514
3935
  }
2515
3936
  async _persistAssistantMessage(msg, parentId) {
2516
3937
  await this._upsertMessageInHistory(msg, parentId);
@@ -2549,6 +3970,37 @@ var Think = class Think extends Agent {
2549
3970
  this._lastBody = void 0;
2550
3971
  }
2551
3972
  }
3973
+ /**
3974
+ * Serialize a client-tool result/approval apply behind any in-flight apply
3975
+ * (#1649). Parallel tool results arrive as independent WebSocket messages,
3976
+ * and each apply is a read-modify-write of the full message in durable
3977
+ * storage. Running them concurrently means every apply reads the same
3978
+ * snapshot (all siblings still `input-available`), patches only its own part,
3979
+ * and writes the whole message back — so the last write clobbers the others
3980
+ * back to `input-available`, and the auto-continuation barrier later times
3981
+ * out and the transcript-repair backstop errors the lost siblings.
3982
+ *
3983
+ * Chaining each apply off `_interactionApplyTail` makes the read-modify-write
3984
+ * atomic per result and in arrival order. `_pendingInteractionPromise` is set
3985
+ * to the newest link so the barrier's single-slot wake-up still observes the
3986
+ * latest apply; because the chain is serial, awaiting it transitively waits
3987
+ * for every predecessor.
3988
+ *
3989
+ * @internal
3990
+ */
3991
+ _enqueueInteractionApply(apply) {
3992
+ const run = async () => {
3993
+ await apply();
3994
+ return true;
3995
+ };
3996
+ const resultPromise = this._interactionApplyTail.then(run, run);
3997
+ this._interactionApplyTail = resultPromise.then(() => void 0, () => void 0);
3998
+ this._pendingInteractionPromise = resultPromise;
3999
+ resultPromise.finally(() => {
4000
+ if (this._pendingInteractionPromise === resultPromise) this._pendingInteractionPromise = null;
4001
+ }).catch(() => {});
4002
+ return resultPromise;
4003
+ }
2552
4004
  async _applyToolResult(toolCallId, output, overrideState, errorText) {
2553
4005
  const update = toolResultUpdate(toolCallId, output, overrideState, errorText);
2554
4006
  await this._applyToolUpdateToMessages(update);
@@ -2558,26 +4010,41 @@ var Think = class Think extends Agent {
2558
4010
  await this._applyToolUpdateToMessages(update);
2559
4011
  }
2560
4012
  async _applyToolUpdateToMessages(update) {
4013
+ let broadcastMessage;
4014
+ const streaming = this._streamingAssistant;
4015
+ if (streaming) {
4016
+ const accParts = streaming.parts;
4017
+ const result = applyToolUpdate(accParts, update);
4018
+ if (result && result.parts[result.index] !== accParts[result.index]) {
4019
+ accParts[result.index] = result.parts[result.index];
4020
+ broadcastMessage = streaming.toMessage();
4021
+ }
4022
+ }
2561
4023
  const history = await this._readMessagesFromStorage();
2562
4024
  for (let i = 0; i < history.length; i++) {
2563
4025
  const msg = history[i];
2564
- const result = applyToolUpdate(msg.parts, update);
4026
+ const msgParts = msg.parts;
4027
+ const result = applyToolUpdate(msgParts, update);
2565
4028
  if (result) {
4029
+ if (result.parts[result.index] === msgParts[result.index]) break;
2566
4030
  const updatedMsg = {
2567
4031
  ...msg,
2568
4032
  parts: result.parts
2569
4033
  };
2570
4034
  const safe = await this._updateMessageInHistory(updatedMsg);
2571
- this._broadcast({
2572
- type: MSG_MESSAGE_UPDATED,
2573
- message: safe
2574
- });
2575
- return;
4035
+ this._patchCachedMessage(safe);
4036
+ broadcastMessage = safe;
4037
+ break;
2576
4038
  }
2577
4039
  }
4040
+ if (broadcastMessage) this._broadcast({
4041
+ type: MSG_MESSAGE_UPDATED,
4042
+ message: broadcastMessage
4043
+ });
2578
4044
  }
2579
4045
  hasPendingInteraction() {
2580
- return this.messages.some((message) => message.role === "assistant" && this._messageHasPendingInteraction(message));
4046
+ const clientResolvable = this._clientResolvableToolNames();
4047
+ return this.messages.some((message) => message.role === "assistant" && this._messageHasPendingInteraction(message, clientResolvable));
2581
4048
  }
2582
4049
  async waitUntilStable(options) {
2583
4050
  const deadline = options?.timeout != null ? Date.now() + options.timeout : null;
@@ -2606,10 +4073,286 @@ var Think = class Think extends Agent {
2606
4073
  clearTimeout(timer);
2607
4074
  return result;
2608
4075
  }
2609
- _messageHasPendingInteraction(message) {
2610
- return message.parts.some((part) => "state" in part && (part.state === "input-available" || part.state === "approval-requested"));
4076
+ _messageHasPendingInteraction(message, clientResolvable) {
4077
+ return message.parts.some((part) => this._partAwaitsClientInteraction(part, clientResolvable));
4078
+ }
4079
+ /**
4080
+ * Names of the tools whose interrupted `input-available` part can still be
4081
+ * resolved by the CLIENT after a restart — i.e. the client tools (no server
4082
+ * `execute`) from the last request, which the SPA answers by replaying a
4083
+ * `tool-result` over the WebSocket. A server tool is intentionally absent:
4084
+ * its `execute()` promise died with the evicted isolate, so nothing will
4085
+ * ever post its result.
4086
+ */
4087
+ _clientResolvableToolNames() {
4088
+ const names = /* @__PURE__ */ new Set();
4089
+ for (const tool of this._lastClientTools ?? []) if (tool?.name) names.add(tool.name);
4090
+ return names;
4091
+ }
4092
+ /** Extract a tool part's name from its `tool-<name>` / `dynamic-tool` shape. */
4093
+ _toolPartName(record) {
4094
+ const type = typeof record.type === "string" ? record.type : "";
4095
+ if (type === "dynamic-tool") return typeof record.toolName === "string" ? record.toolName : void 0;
4096
+ if (type.startsWith("tool-")) return type.slice(5);
4097
+ }
4098
+ /**
4099
+ * Whether a part is still awaiting a CLIENT interaction that can genuinely
4100
+ * arrive after a restart, so `waitUntilStable` must keep waiting for it:
4101
+ * - `approval-requested`: a reconnecting client can replay the approval.
4102
+ * - `input-available` for a CLIENT tool: the SPA can replay the
4103
+ * `tool-result` (this is why client-tool recovery works — see the
4104
+ * `tool-result` handler, which sets `_pendingInteractionPromise`).
4105
+ *
4106
+ * A SERVER tool's `input-available` is deliberately NOT pending. After an
4107
+ * eviction its `execute()` promise is gone and no interaction will ever
4108
+ * resolve it, so treating it as pending wedges `waitUntilStable` forever:
4109
+ * the recovery continuation times out every attempt, burns the attempt
4110
+ * budget on a wait that can never converge, and — if any transient
4111
+ * storage/schedule error throws on the way — the one-shot recovery alarm row
4112
+ * is swallowed and deleted with no terminal `onExhausted` (the half-finished
4113
+ * message wedges silently). Excluding it lets `waitUntilStable` converge so
4114
+ * `continueLastTurn` runs, where the existing transcript-repair pass
4115
+ * (`_repairTranscriptForProvider`) flips the orphan to an errored result and
4116
+ * the model proceeds.
4117
+ */
4118
+ _partAwaitsClientInteraction(part, clientResolvable) {
4119
+ if (!("state" in part)) return false;
4120
+ const record = part;
4121
+ const state = record.state;
4122
+ if (state === "approval-requested") return true;
4123
+ if (state !== "input-available") return false;
4124
+ const toolName = this._toolPartName(record);
4125
+ return toolName != null && clientResolvable.has(toolName);
4126
+ }
4127
+ _resolveChatRecoveryConfig() {
4128
+ const raw = this.chatRecovery;
4129
+ const custom = typeof raw === "object" ? raw : void 0;
4130
+ return {
4131
+ enabled: raw !== false,
4132
+ maxAttempts: Math.max(1, Math.floor(custom?.maxAttempts ?? DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS)),
4133
+ stableTimeoutMs: Math.max(0, Math.floor(custom?.stableTimeoutMs ?? DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS)),
4134
+ terminalMessage: custom?.terminalMessage ?? DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE,
4135
+ ...custom?.onExhausted ? { onExhausted: custom.onExhausted } : {}
4136
+ };
4137
+ }
4138
+ _chatRecoveryIncidentId(input) {
4139
+ return [input.recoveryRootRequestId ?? input.requestId, input.latestUserMessageId ?? ""].join(":");
4140
+ }
4141
+ _chatRecoveryIncidentKey(incidentId) {
4142
+ return `${CHAT_RECOVERY_INCIDENT_KEY_PREFIX}${encodeURIComponent(incidentId)}`;
4143
+ }
4144
+ /**
4145
+ * Monotonic forward-progress signal for recovery budget resets.
4146
+ *
4147
+ * This used to count assistant messages in `this.messages`, but that is
4148
+ * recomputed from the live, mutable transcript. Compaction collapses older
4149
+ * assistant messages into a summary, lowering the count — so a turn that had
4150
+ * genuinely advanced could read as "no progress" between attempts and exhaust
4151
+ * its budget prematurely (#1628). Instead we read a durably-persisted counter
4152
+ * that only ever increments — bumped at production time when new content is
4153
+ * durably flushed (see `_storeChunkDurably`), which is genuine forward
4154
+ * progress and is immune to client reconnects / recovery re-persists — so
4155
+ * compaction can never lower it and a reconnect can't fake it (#1637).
4156
+ */
4157
+ async _chatRecoveryProgressMarker() {
4158
+ return await this.ctx.storage.get(CHAT_RECOVERY_PROGRESS_KEY) ?? 0;
4159
+ }
4160
+ /** Advance the durable recovery-progress counter. Called from
4161
+ * `_storeChunkDurably` when new content is durably flushed (real, reconnect-
4162
+ * immune forward progress). */
4163
+ async _bumpChatRecoveryProgress() {
4164
+ const current = await this.ctx.storage.get(CHAT_RECOVERY_PROGRESS_KEY) ?? 0;
4165
+ await this.ctx.storage.put(CHAT_RECOVERY_PROGRESS_KEY, current + 1);
4166
+ }
4167
+ /**
4168
+ * N9: forwarding a sub-agent's chunks IS forward progress for this parent
4169
+ * turn, so credit the parent's recovery progress marker — otherwise a parent
4170
+ * whose turn merely `await`s a child banks no progress of its own and its
4171
+ * no-progress window exhausts while the child is healthily streaming. Only
4172
+ * invoked after a child actually produced output (see
4173
+ * `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.
4174
+ * Throttled (and reset per isolate) so we never write storage per token.
4175
+ */
4176
+ async _onAgentToolStreamProgress() {
4177
+ const now = Date.now();
4178
+ if (now - this._lastAgentToolStreamProgressAt < AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS) return;
4179
+ this._lastAgentToolStreamProgressAt = now;
4180
+ await this._bumpChatRecoveryProgress();
4181
+ }
4182
+ /** Sweep recovery incidents that have been inactive past the TTL. */
4183
+ async _sweepStaleChatRecoveryIncidents(now) {
4184
+ const entries = await this.ctx.storage.list({ prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX });
4185
+ const staleKeys = [];
4186
+ for (const [key, incident] of entries) if (now - (incident?.lastAttemptAt ?? incident?.firstSeenAt ?? 0) > CHAT_RECOVERY_INCIDENT_TTL_MS) staleKeys.push(key);
4187
+ for (const key of staleKeys) await this.ctx.storage.delete(key);
4188
+ }
4189
+ async _beginChatRecoveryIncident(input) {
4190
+ const config = this._resolveChatRecoveryConfig();
4191
+ const incidentId = this._chatRecoveryIncidentId(input);
4192
+ const key = this._chatRecoveryIncidentKey(incidentId);
4193
+ const now = input.nowMs ?? Date.now();
4194
+ await this._sweepStaleChatRecoveryIncidents(now);
4195
+ const existing = await this.ctx.storage.get(key);
4196
+ const prevProgress = existing?.progress ?? 0;
4197
+ const currentProgress = await this._chatRecoveryProgressMarker();
4198
+ const madeProgress = existing != null && currentProgress > prevProgress;
4199
+ const lastProgressAt = madeProgress ? now : existing?.lastProgressAt ?? existing?.firstSeenAt ?? now;
4200
+ const noProgressExceeded = existing != null && now - lastProgressAt > CHAT_RECOVERY_NO_PROGRESS_WINDOW_MS;
4201
+ const incidentAgeExceeded = existing != null && now - existing.firstSeenAt > CHAT_RECOVERY_MAX_WINDOW_MS;
4202
+ const debounced = existing != null && !madeProgress && now - existing.lastAttemptAt < CHAT_RECOVERY_ALARM_DEBOUNCE_MS;
4203
+ const attempt = madeProgress ? 1 : debounced ? existing?.attempt ?? 1 : (existing?.attempt ?? 0) + 1;
4204
+ const exhausted = noProgressExceeded || incidentAgeExceeded || attempt > config.maxAttempts;
4205
+ const incident = {
4206
+ incidentId,
4207
+ requestId: input.requestId,
4208
+ recoveryRootRequestId: input.recoveryRootRequestId ?? input.requestId,
4209
+ recoveryKind: input.recoveryKind,
4210
+ attempt,
4211
+ maxAttempts: config.maxAttempts,
4212
+ status: exhausted ? "exhausted" : "attempting",
4213
+ firstSeenAt: existing?.firstSeenAt ?? now,
4214
+ lastAttemptAt: now,
4215
+ lastProgressAt,
4216
+ progress: Math.max(prevProgress, currentProgress),
4217
+ ...exhausted ? { reason: incidentAgeExceeded ? "max_recovery_window_exceeded" : noProgressExceeded ? "no_progress_timeout" : "max_attempts_exceeded" } : {}
4218
+ };
4219
+ await this.ctx.storage.put(key, incident);
4220
+ if (!existing) this._emit("chat:recovery:detected", {
4221
+ incidentId,
4222
+ requestId: input.requestId,
4223
+ attempt,
4224
+ maxAttempts: config.maxAttempts,
4225
+ recoveryKind: input.recoveryKind
4226
+ });
4227
+ this._emit("chat:recovery:attempt", {
4228
+ incidentId,
4229
+ requestId: input.requestId,
4230
+ attempt,
4231
+ maxAttempts: config.maxAttempts,
4232
+ recoveryKind: input.recoveryKind
4233
+ });
4234
+ return {
4235
+ incident,
4236
+ config,
4237
+ exhausted
4238
+ };
4239
+ }
4240
+ async _updateChatRecoveryIncident(incidentId, status, reason) {
4241
+ if (!incidentId) return;
4242
+ const key = this._chatRecoveryIncidentKey(incidentId);
4243
+ const incident = await this.ctx.storage.get(key);
4244
+ if (!incident) return;
4245
+ if (status === "completed") await this.ctx.storage.delete(key);
4246
+ else await this.ctx.storage.put(key, {
4247
+ ...incident,
4248
+ status,
4249
+ ...reason ? { reason } : {}
4250
+ });
4251
+ const eventType = status === "completed" ? "chat:recovery:completed" : status === "skipped" ? "chat:recovery:skipped" : status === "failed" ? "chat:recovery:failed" : void 0;
4252
+ if (eventType) this._emit(eventType, {
4253
+ incidentId,
4254
+ requestId: incident.requestId,
4255
+ attempt: incident.attempt,
4256
+ maxAttempts: incident.maxAttempts,
4257
+ recoveryKind: incident.recoveryKind,
4258
+ ...reason ? { reason } : {}
4259
+ });
4260
+ if (status === "scheduled") await this._setChatRecovering(true, incident.recoveryRootRequestId ?? incident.requestId);
4261
+ else if (status === "completed" || status === "skipped" || status === "failed") await this._setChatRecovering(false);
4262
+ }
4263
+ async _exhaustChatRecovery(incident, config, partial, streamId, createdAt) {
4264
+ const ctx = {
4265
+ incidentId: incident.incidentId,
4266
+ requestId: incident.requestId,
4267
+ recoveryRootRequestId: incident.recoveryRootRequestId ?? incident.requestId,
4268
+ attempt: incident.attempt,
4269
+ maxAttempts: incident.maxAttempts,
4270
+ recoveryKind: incident.recoveryKind,
4271
+ streamId,
4272
+ createdAt,
4273
+ partialText: partial.text,
4274
+ partialParts: partial.parts,
4275
+ reason: incident.reason ?? "max_attempts_exceeded",
4276
+ terminalMessage: config.terminalMessage
4277
+ };
4278
+ this._emit("chat:recovery:exhausted", ctx);
4279
+ try {
4280
+ await config.onExhausted?.(ctx);
4281
+ } catch (error) {
4282
+ console.error("[Think] chatRecovery onExhausted hook threw", error);
4283
+ }
4284
+ this._broadcastChat({
4285
+ type: MSG_CHAT_RESPONSE,
4286
+ id: incident.requestId,
4287
+ body: config.terminalMessage,
4288
+ done: true,
4289
+ error: true
4290
+ });
4291
+ await this._markRecoveredSubmissionInterrupted(incident.recoveryRootRequestId ?? incident.requestId, config.terminalMessage);
4292
+ await this._recordTerminalChatStatus("interrupted", incident.requestId, config.terminalMessage);
4293
+ }
4294
+ /**
4295
+ * Route a stream-stall watchdog abort into bounded recovery instead of a
4296
+ * terminal error (#1626). A stall happens inside a LIVE isolate (no DO
4297
+ * restart), so the normal restart-detected recovery path never runs — we
4298
+ * open/advance a recovery incident here and schedule a continuation, reusing
4299
+ * the SAME budget (`maxAttempts` + wall-clock window + progress-aware reset)
4300
+ * as deploy/eviction recovery. A transient hang recovers; a persistently
4301
+ * hanging provider exhausts the budget. Idempotency matches deploy recovery:
4302
+ * settled tool results are durable and won't re-run, but a tool that was
4303
+ * mid-execution when the stall fired re-runs on the continuation.
4304
+ *
4305
+ * Returns:
4306
+ * - `"scheduled"` — a continuation was scheduled; the caller suppresses the
4307
+ * terminal error and closes the stream cleanly.
4308
+ * - `"exhausted"` — the budget is spent; this routes through the SAME
4309
+ * `_exhaustChatRecovery` path as deploy recovery (fires `onExhausted`,
4310
+ * emits `chat:recovery:exhausted`, marks the submission interrupted, and
4311
+ * delivers the configured `terminalMessage`). The caller must NOT run the
4312
+ * generic terminal path — the terminal UX is already delivered.
4313
+ * - `"disabled"` — chat recovery is off; the caller falls through to the
4314
+ * generic terminal error (the watchdog's original "kill the spinner"
4315
+ * behavior, unchanged).
4316
+ */
4317
+ async _routeStallToBoundedRecovery(input) {
4318
+ if (!this._resolveChatRecoveryConfig().enabled) return "disabled";
4319
+ const recoveryRootRequestId = this._activeChatRecoveryRootRequestId ?? input.requestId;
4320
+ const latestUserMessageId = [...this.messages].reverse().find((m) => m.role === "user")?.id ?? null;
4321
+ const { incident, config, exhausted } = await this._beginChatRecoveryIncident({
4322
+ requestId: input.requestId,
4323
+ recoveryRootRequestId,
4324
+ latestUserMessageId,
4325
+ recoveryKind: "continue"
4326
+ });
4327
+ if (exhausted) {
4328
+ const partialText = input.partialParts.filter((p) => p.type === "text").map((p) => p.text).join("");
4329
+ await this._exhaustChatRecovery(incident, config, {
4330
+ text: partialText,
4331
+ parts: input.partialParts
4332
+ }, input.streamId, incident.firstSeenAt);
4333
+ return "exhausted";
4334
+ }
4335
+ await this._updateChatRecoveryIncident(incident.incidentId, "scheduled");
4336
+ this._emit("chat:recovery:scheduled", {
4337
+ incidentId: incident.incidentId,
4338
+ requestId: input.requestId,
4339
+ attempt: incident.attempt,
4340
+ maxAttempts: incident.maxAttempts,
4341
+ recoveryKind: "continue"
4342
+ });
4343
+ const recoveredRequestId = this._hasRunningSubmission(recoveryRootRequestId) ? recoveryRootRequestId : void 0;
4344
+ await this.schedule(0, "_chatRecoveryContinue", {
4345
+ ...input.targetAssistantId ? { targetAssistantId: input.targetAssistantId } : {},
4346
+ originalRequestId: recoveryRootRequestId,
4347
+ incidentId: incident.incidentId,
4348
+ lastBody: this._lastBody ?? null,
4349
+ lastClientTools: this._lastClientTools ?? null,
4350
+ ...recoveredRequestId ? { recoveredRequestId } : {}
4351
+ }, { idempotent: true });
4352
+ return "scheduled";
2611
4353
  }
2612
4354
  async _handleInternalFiberRecovery(ctx) {
4355
+ if (await this._messengerRuntime?.handleFiberRecovery(ctx)) return true;
2613
4356
  const chatPrefix = this.constructor.CHAT_FIBER_NAME + ":";
2614
4357
  if (!ctx.name.startsWith(chatPrefix)) return false;
2615
4358
  const requestId = ctx.name.slice(chatPrefix.length);
@@ -2635,80 +4378,353 @@ var Think = class Think extends Agent {
2635
4378
  text: "",
2636
4379
  parts: []
2637
4380
  };
2638
- const options = await this.onChatRecovery({
2639
- streamId: streamId ?? "",
2640
- requestId,
2641
- partialText: partial.text,
2642
- partialParts: partial.parts,
2643
- recoveryData,
2644
- messages: [...this.messages],
2645
- lastBody: recoverySnapshot?.lastBody ?? this._lastBody,
2646
- lastClientTools: recoverySnapshot?.lastClientTools ?? this._lastClientTools,
2647
- createdAt: ctx.createdAt
2648
- }) ?? {};
2649
4381
  const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
2650
4382
  const streamIsTerminal = streamStatus === "completed" || streamStatus === "error";
2651
- if (options.persist !== false && streamId && (streamStillActive || streamIsTerminal)) await this._persistOrphanedStream(streamId);
2652
- if (streamStillActive) this._resumableStream.complete(streamId);
2653
4383
  const retryTargetUserId = await this._recoverablePreStreamUserId(recoverySnapshot, streamId ?? "", partial);
2654
- const shouldRetry = retryTargetUserId !== null && options.continue !== false && !streamIsTerminal;
2655
- const canContinue = !shouldRetry && options.continue !== false && !streamIsTerminal;
2656
- const hasRunningSubmission = this._hasRunningSubmission(requestId);
2657
- if (streamIsTerminal && hasRunningSubmission) await this._completeRecoveredSubmission(requestId, streamStatus === "completed" ? "completed" : "error", requestId, streamStatus === "completed" ? null : "Recovered chat stream had already errored.");
2658
- const recoveredRequestId = (canContinue || shouldRetry) && hasRunningSubmission ? requestId : void 0;
2659
- if (shouldRetry) await this.schedule(0, "_chatRecoveryRetry", {
2660
- targetUserId: retryTargetUserId,
2661
- originalRequestId: requestId,
2662
- lastBody: recoverySnapshot?.lastBody ?? null,
2663
- lastClientTools: recoverySnapshot?.lastClientTools ?? null,
2664
- ...recoveredRequestId ? { recoveredRequestId } : {}
2665
- }, { idempotent: true });
2666
- else if (canContinue) {
2667
- const lastLeaf = await this.session.getLatestLeaf();
2668
- const targetId = lastLeaf?.role === "assistant" ? lastLeaf.id : void 0;
2669
- await this.schedule(0, "_chatRecoveryContinue", {
2670
- ...targetId ? { targetAssistantId: targetId } : {},
2671
- originalRequestId: requestId,
2672
- ...recoverySnapshot ? {
2673
- lastBody: recoverySnapshot.lastBody ?? null,
2674
- lastClientTools: recoverySnapshot.lastClientTools ?? null
2675
- } : {},
2676
- ...recoveredRequestId ? { recoveredRequestId } : {}
2677
- }, { idempotent: true });
2678
- } else if (options.continue === false && !streamIsTerminal) await this._markRecoveredSubmissionInterrupted(requestId, "Submission was interrupted and chat recovery was disabled.");
2679
- return true;
4384
+ const recoveryKind = retryTargetUserId !== null && !streamIsTerminal ? "retry" : "continue";
4385
+ const recoveryRootRequestId = recoverySnapshot?.recoveryRootRequestId ?? requestId;
4386
+ const { incident, config, exhausted } = await this._beginChatRecoveryIncident({
4387
+ requestId,
4388
+ recoveryRootRequestId,
4389
+ latestUserMessageId: recoverySnapshot?.latestUserMessageId,
4390
+ recoveryKind
4391
+ });
4392
+ if (exhausted) {
4393
+ if (await this._shouldPersistOrphanedPartial(streamId, {
4394
+ streamStillActive: Boolean(streamStillActive),
4395
+ streamIsTerminal,
4396
+ snapshot: recoverySnapshot
4397
+ })) await this._persistOrphanedStream(streamId);
4398
+ await this._exhaustChatRecovery(incident, config, partial, streamId ?? "", ctx.createdAt);
4399
+ return true;
4400
+ }
4401
+ try {
4402
+ const options = await this.onChatRecovery({
4403
+ incidentId: incident.incidentId,
4404
+ recoveryRootRequestId,
4405
+ attempt: incident.attempt,
4406
+ maxAttempts: incident.maxAttempts,
4407
+ recoveryKind,
4408
+ streamId: streamId ?? "",
4409
+ requestId,
4410
+ partialText: partial.text,
4411
+ partialParts: partial.parts,
4412
+ recoveryData,
4413
+ messages: [...this.messages],
4414
+ lastBody: recoverySnapshot?.lastBody ?? this._lastBody,
4415
+ lastClientTools: recoverySnapshot?.lastClientTools ?? this._lastClientTools,
4416
+ createdAt: ctx.createdAt
4417
+ }) ?? {};
4418
+ if (await this._shouldPersistOrphanedPartial(streamId, {
4419
+ streamStillActive: Boolean(streamStillActive),
4420
+ streamIsTerminal,
4421
+ snapshot: recoverySnapshot
4422
+ }) && (options.persist !== false || this._partialHasSettledToolResults(partial.parts))) await this._persistOrphanedStream(streamId);
4423
+ if (streamStillActive) this._resumableStream.complete(streamId);
4424
+ const shouldRetry = retryTargetUserId !== null && options.continue !== false && !streamIsTerminal;
4425
+ const lastLeaf = shouldRetry ? null : await this.session.getLatestLeaf();
4426
+ const targetId = lastLeaf?.role === "assistant" && !streamIsTerminal ? lastLeaf.id : void 0;
4427
+ const canContinue = !shouldRetry && options.continue !== false && !streamIsTerminal;
4428
+ const hasRunningSubmission = this._hasRunningSubmission(recoveryRootRequestId);
4429
+ if (streamIsTerminal && hasRunningSubmission) await this._completeRecoveredSubmission(recoveryRootRequestId, streamStatus === "completed" ? "completed" : "error", requestId, streamStatus === "completed" ? null : "Recovered chat stream had already errored.");
4430
+ const recoveredRequestId = (canContinue || shouldRetry) && hasRunningSubmission ? recoveryRootRequestId : void 0;
4431
+ if (shouldRetry) {
4432
+ await this._updateChatRecoveryIncident(incident.incidentId, "scheduled");
4433
+ this._emit("chat:recovery:scheduled", {
4434
+ incidentId: incident.incidentId,
4435
+ requestId,
4436
+ attempt: incident.attempt,
4437
+ maxAttempts: incident.maxAttempts,
4438
+ recoveryKind
4439
+ });
4440
+ await this.schedule(0, "_chatRecoveryRetry", {
4441
+ targetUserId: retryTargetUserId,
4442
+ originalRequestId: recoveryRootRequestId,
4443
+ incidentId: incident.incidentId,
4444
+ lastBody: recoverySnapshot?.lastBody ?? null,
4445
+ lastClientTools: recoverySnapshot?.lastClientTools ?? null,
4446
+ ...recoveredRequestId ? { recoveredRequestId } : {}
4447
+ }, { idempotent: true });
4448
+ } else if (canContinue) {
4449
+ await this._updateChatRecoveryIncident(incident.incidentId, "scheduled");
4450
+ this._emit("chat:recovery:scheduled", {
4451
+ incidentId: incident.incidentId,
4452
+ requestId,
4453
+ attempt: incident.attempt,
4454
+ maxAttempts: incident.maxAttempts,
4455
+ recoveryKind
4456
+ });
4457
+ await this.schedule(0, "_chatRecoveryContinue", {
4458
+ ...targetId ? { targetAssistantId: targetId } : {},
4459
+ originalRequestId: recoveryRootRequestId,
4460
+ incidentId: incident.incidentId,
4461
+ ...recoverySnapshot ? {
4462
+ lastBody: recoverySnapshot.lastBody ?? null,
4463
+ lastClientTools: recoverySnapshot.lastClientTools ?? null
4464
+ } : {},
4465
+ ...recoveredRequestId ? { recoveredRequestId } : {}
4466
+ }, { idempotent: true });
4467
+ } else if (options.continue === false && !streamIsTerminal) {
4468
+ await this._updateChatRecoveryIncident(incident.incidentId, "skipped", "continue_disabled");
4469
+ const disabledMessage = "Submission was interrupted and chat recovery was disabled.";
4470
+ await this._markRecoveredSubmissionInterrupted(recoveryRootRequestId, disabledMessage);
4471
+ await this._recordTerminalChatStatus("interrupted", requestId, disabledMessage);
4472
+ this._broadcastChat({
4473
+ type: MSG_CHAT_RESPONSE,
4474
+ id: requestId,
4475
+ body: disabledMessage,
4476
+ done: true,
4477
+ error: true
4478
+ });
4479
+ } else await this._updateChatRecoveryIncident(incident.incidentId, "skipped", streamIsTerminal ? "stream_terminal" : "not_recoverable");
4480
+ return true;
4481
+ } catch (error) {
4482
+ await this._updateChatRecoveryIncident(incident.incidentId, "failed", error instanceof Error ? error.message : String(error));
4483
+ throw error;
4484
+ }
2680
4485
  }
2681
4486
  async _recoverablePreStreamUserId(snapshot, streamId, partial) {
2682
4487
  if (!snapshot || snapshot.continuation || !snapshot.latestUserMessageId || streamId || partial.text || partial.parts.length > 0) return null;
2683
4488
  const lastLeaf = await this.session.getLatestLeaf();
2684
4489
  return lastLeaf?.role === "user" && lastLeaf.id === snapshot.latestUserMessageId ? snapshot.latestUserMessageId : null;
2685
4490
  }
4491
+ async _hasPersistedRecoveredAssistant(snapshot) {
4492
+ const lastLeaf = await this.session.getLatestLeaf();
4493
+ return lastLeaf?.role === "assistant" && lastLeaf.id !== snapshot?.latestMessageId;
4494
+ }
4495
+ /**
4496
+ * Whether the orphaned stream's partial should be materialized into an
4497
+ * assistant message: there is a stream, and it is either still active or
4498
+ * terminal-but-not-yet-persisted. Shared by the normal recovery path AND the
4499
+ * exhaustion path so neither discards settled work nor duplicates a partial
4500
+ * an earlier attempt already saved.
4501
+ */
4502
+ async _shouldPersistOrphanedPartial(streamId, opts) {
4503
+ if (!streamId) return false;
4504
+ const alreadyPersisted = opts.streamIsTerminal && await this._hasPersistedRecoveredAssistant(opts.snapshot);
4505
+ return opts.streamStillActive || opts.streamIsTerminal && !alreadyPersisted;
4506
+ }
4507
+ /** Whether a reconstructed partial carries any settled (provider-accepted)
4508
+ * tool result — the completed, often non-idempotent work that a
4509
+ * `{ persist: false }` recovery return would silently discard. */
4510
+ _partialHasSettledToolResults(parts) {
4511
+ return parts.some((part) => {
4512
+ const record = part;
4513
+ const type = typeof record.type === "string" ? record.type : "";
4514
+ return (type.startsWith("tool-") || type === "dynamic-tool") && this._toolPartHasSettledResult(record);
4515
+ });
4516
+ }
4517
+ /**
4518
+ * Reschedule a recovery callback that timed out waiting for stable state,
4519
+ * consuming one attempt. Returns `true` if rescheduled, `false` if the
4520
+ * attempt budget is exhausted (the caller then fails the turn terminally).
4521
+ *
4522
+ * Shared by `_chatRecoveryRetry` and `_chatRecoveryContinue` so the
4523
+ * non-idempotent scheduling invariant lives in exactly one place — a fix to
4524
+ * one path can't silently diverge from the other. Mirrors the same helper in
4525
+ * `@cloudflare/ai-chat`.
4526
+ */
4527
+ async _rescheduleRecoveryAfterStableTimeout(callback, data, maxAttempts) {
4528
+ const incidentKey = data?.incidentId ? this._chatRecoveryIncidentKey(data.incidentId) : null;
4529
+ const incident = incidentKey ? await this.ctx.storage.get(incidentKey) : null;
4530
+ if (!incident || !incidentKey) return false;
4531
+ const attempt = incident.attempt ?? 0;
4532
+ if (attempt >= (incident.maxAttempts ?? maxAttempts)) return false;
4533
+ await this.ctx.storage.put(incidentKey, {
4534
+ ...incident,
4535
+ attempt: attempt + 1,
4536
+ status: "scheduled",
4537
+ lastAttemptAt: Date.now(),
4538
+ reason: "stable_timeout_retry"
4539
+ });
4540
+ await this.schedule(CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS, callback, data ?? {}, { idempotent: false });
4541
+ return true;
4542
+ }
4543
+ /**
4544
+ * Resolve the stream id for a recovery turn so the give-up terminalization
4545
+ * can surface whatever partial the turn produced. Prefers the durable stream
4546
+ * row keyed by the recovery-root request id; falls back to the live active
4547
+ * stream. Returns `""` when neither is available (the terminal banner still
4548
+ * fires — `_exhaustChatRecovery` does not require a stream).
4549
+ */
4550
+ _resolveRecoveryStreamId(requestId) {
4551
+ if (requestId) {
4552
+ const fromMetadata = this._resumableStream.getAllStreamMetadata().find((metadata) => metadata.request_id === requestId)?.id;
4553
+ if (fromMetadata) return fromMetadata;
4554
+ }
4555
+ return this._resumableStream.hasActiveStream() ? this._resumableStream.activeStreamId ?? "" : "";
4556
+ }
4557
+ /**
4558
+ * Terminalize a recovery turn that is giving up — whether because the
4559
+ * stable-state-timeout retry budget drained, or because the recovery
4560
+ * continuation threw a non-recoverable error — by routing through the SAME
4561
+ * `_exhaustChatRecovery` path as deploy-recovery and stall exhaustion
4562
+ * (#1626/#1631). It fires `onExhausted`, emits `chat:recovery:exhausted`,
4563
+ * marks the durable submission interrupted, records the terminal chat status,
4564
+ * and delivers the configured `terminalMessage`. `reason` carries the cause
4565
+ * (`stable_timeout` for a budget give-up, `recovery_error` for a thrown
4566
+ * error) through to `onExhausted` / `chat:recovery:exhausted`.
4567
+ *
4568
+ * This replaces the older give-up that only set the incident to `failed` and
4569
+ * completed the recovered submission as `error`, which bypassed
4570
+ * `_exhaustChatRecovery` entirely — so an app relying on `onExhausted` for the
4571
+ * terminal banner regressed to an eternal spinner when recovery gave up under
4572
+ * extreme churn. The error path matters just as much: a non-reset throw in a
4573
+ * recovery callback is SWALLOWED by `Agent._executeScheduleCallback` (only a
4574
+ * code-update reset is re-thrown to preserve the one-shot row), so without
4575
+ * routing it here the alarm row is deleted with no terminal UX at all — the
4576
+ * half-finished message wedges silently. Shared by `_chatRecoveryRetry` and
4577
+ * `_chatRecoveryContinue`.
4578
+ *
4579
+ * Exactly-once terminalization is defended by two independent guards:
4580
+ * 1. The `stored?.status === "exhausted"` re-entry guard below — once an
4581
+ * incident is sealed, a duplicate stale alarm (or retried callback)
4582
+ * returns before re-firing. The sealed incident is re-persisted even when
4583
+ * the record was found missing, so a swept record is re-armed for the
4584
+ * guard on the next alarm.
4585
+ * 2. The durable-submission paths additionally short-circuit earlier at the
4586
+ * `submission_not_running` check (the submission is already `error` after
4587
+ * the first give-up). This is the ONLY guard `@cloudflare/ai-chat` lacks
4588
+ * (no submission layer), so guard #1 carries it there.
4589
+ *
4590
+ * Two residual at-least-once edges, both deliberately accepted as "deliver a
4591
+ * second banner" ≫ "silently drop the turn":
4592
+ * • No `incidentId` at all in the payload (only reachable via a direct/test
4593
+ * invocation — every production scheduler carries one): the synthesized
4594
+ * incident can't be persisted (no key), so guard #1 can't arm.
4595
+ * • The record is swept AGAIN between two alarms (guard #1 re-persists on the
4596
+ * first, so this needs a second independent sweep) — vanishingly unlikely.
4597
+ */
4598
+ async _exhaustRecoveryGiveUp(callback, data, reason) {
4599
+ const config = this._resolveChatRecoveryConfig();
4600
+ const incidentKey = data?.incidentId ? this._chatRecoveryIncidentKey(data.incidentId) : null;
4601
+ let stored = null;
4602
+ if (incidentKey) try {
4603
+ stored = await this.ctx.storage.get(incidentKey) ?? null;
4604
+ } catch (readError) {
4605
+ console.error("[Think] failed to read recovery incident during give-up; synthesizing", readError);
4606
+ }
4607
+ if (stored?.status === "exhausted") return;
4608
+ const rootRequestId = data?.originalRequestId ?? data?.recoveredRequestId ?? this._activeChatRecoveryRootRequestId ?? stored?.recoveryRootRequestId ?? stored?.requestId ?? "";
4609
+ const incident = stored ? {
4610
+ ...stored,
4611
+ status: "exhausted",
4612
+ reason
4613
+ } : {
4614
+ incidentId: data?.incidentId ?? crypto.randomUUID(),
4615
+ requestId: rootRequestId,
4616
+ recoveryRootRequestId: rootRequestId,
4617
+ recoveryKind: callback === "_chatRecoveryRetry" ? "retry" : "continue",
4618
+ attempt: config.maxAttempts,
4619
+ maxAttempts: config.maxAttempts,
4620
+ status: "exhausted",
4621
+ firstSeenAt: Date.now(),
4622
+ lastAttemptAt: Date.now(),
4623
+ reason
4624
+ };
4625
+ if (incidentKey) try {
4626
+ await this.ctx.storage.put(incidentKey, incident);
4627
+ } catch (writeError) {
4628
+ console.error("[Think] failed to persist sealed recovery incident during give-up", writeError);
4629
+ }
4630
+ const streamId = this._resolveRecoveryStreamId(incident.recoveryRootRequestId ?? incident.requestId);
4631
+ const partial = streamId ? this._getPartialStreamText(streamId) : {
4632
+ text: "",
4633
+ parts: []
4634
+ };
4635
+ await this._exhaustChatRecovery(incident, config, partial, streamId, incident.firstSeenAt);
4636
+ }
4637
+ /**
4638
+ * Give-up after the stable-state-timeout retry budget drained. Thin wrapper
4639
+ * over `_exhaustRecoveryGiveUp` so the give-up cause is recorded as
4640
+ * `stable_timeout`.
4641
+ */
4642
+ _exhaustRecoveryAfterStableTimeout(callback, data) {
4643
+ return this._exhaustRecoveryGiveUp(callback, data, "stable_timeout");
4644
+ }
4645
+ /**
4646
+ * Whether an error is a transient "superseded isolate" failure — a deploy /
4647
+ * code update replaced the isolate mid-invocation. Mirrors the base `Agent`
4648
+ * check (`isDurableObjectCodeUpdateReset`) and MUST stay in lockstep with it:
4649
+ * the base `_executeScheduleCallback` re-throws this class for a one-shot row
4650
+ * (preserving it so the platform re-runs on the new code), so a recovery
4651
+ * callback must also re-throw — NOT terminalize — since recovery will re-run
4652
+ * and succeed on the fresh isolate. The matched family (kept identical to the
4653
+ * base):
4654
+ * - "Durable Object reset because its code was updated." (deploy bounce)
4655
+ * - "This script has been upgraded. Please send a new request to connect to
4656
+ * the new version." (a stub/connection to a superseded script)
4657
+ * "Network connection lost." is intentionally excluded (a connection error,
4658
+ * not an isolate replacement — see the base helper's note). The match stays
4659
+ * close to the verbatim platform strings so an ordinary error mentioning
4660
+ * those words isn't misclassified as a supersede.
4661
+ */
4662
+ _isDeployCodeUpdateReset(error) {
4663
+ const message = error instanceof Error ? error.message : typeof error === "string" ? error : "";
4664
+ return /reset because its code was updated|this script has been upgraded/i.test(message);
4665
+ }
4666
+ /**
4667
+ * Handle an error thrown by `_chatRecoveryContinue` / `_chatRecoveryRetry`
4668
+ * after the incident was opened.
4669
+ *
4670
+ * - A deploy code-update reset is re-thrown (after marking the incident
4671
+ * `failed` for observability) so `Agent._executeScheduleCallback` preserves
4672
+ * the one-shot alarm row and the platform re-runs recovery on the fresh
4673
+ * isolate — the turn can still recover, so it must NOT terminalize.
4674
+ * - Any OTHER error is terminalized through the give-up path
4675
+ * (`onExhausted` + the `terminalMessage` banner) and NOT re-thrown. This is
4676
+ * the fix for the silent-seal failure mode: `_executeScheduleCallback`
4677
+ * swallows a non-reset throw and then `alarm()` deletes the one-shot row, so
4678
+ * without terminalizing here the half-finished turn is dropped with no
4679
+ * terminal event and no banner (the user stares at a frozen message until
4680
+ * they send something new).
4681
+ */
4682
+ async _handleRecoveryCallbackError(callback, data, error) {
4683
+ if (this._isDeployCodeUpdateReset(error)) {
4684
+ const message = error instanceof Error ? error.message : String(error);
4685
+ await this._updateChatRecoveryIncident(data?.incidentId, "failed", message);
4686
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, message);
4687
+ throw error;
4688
+ }
4689
+ console.error(`[Think] ${callback} threw during recovery; terminalizing instead of leaving the turn wedged`, error);
4690
+ await this._exhaustRecoveryGiveUp(callback, data, "recovery_error");
4691
+ }
2686
4692
  async _chatRecoveryRetry(data) {
2687
4693
  const recoveredSubmission = data?.recoveredRequestId ? this._readRunningSubmissionByRequestId(data.recoveredRequestId) : null;
2688
- if (data?.recoveredRequestId && !recoveredSubmission) return;
4694
+ if (data?.recoveredRequestId && !recoveredSubmission) {
4695
+ await this._updateChatRecoveryIncident(data.incidentId, "skipped", "submission_not_running");
4696
+ return;
4697
+ }
4698
+ const previousRootRequestId = this._activeChatRecoveryRootRequestId;
4699
+ this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
2689
4700
  const controller = recoveredSubmission ? new AbortController() : null;
2690
4701
  if (recoveredSubmission && controller) this._submissionAbortControllers.set(recoveredSubmission.submission_id, controller);
2691
4702
  try {
2692
- if (!await this.waitUntilStable({ timeout: 1e4 })) {
2693
- if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, "Recovered chat retry timed out waiting for stable state.");
4703
+ const recoveryConfig = this._resolveChatRecoveryConfig();
4704
+ if (!await this.waitUntilStable({ timeout: recoveryConfig.stableTimeoutMs })) {
4705
+ if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryRetry", data, recoveryConfig.maxAttempts)) return;
4706
+ await this._exhaustRecoveryAfterStableTimeout("_chatRecoveryRetry", data);
2694
4707
  return;
2695
4708
  }
2696
4709
  const lastLeaf = await this.session.getLatestLeaf();
2697
4710
  if (!lastLeaf || lastLeaf.role !== "user") {
2698
- if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, "Recovered chat retry was skipped because there is no unanswered user message.");
4711
+ await this._updateChatRecoveryIncident(data?.incidentId, "skipped", "no_unanswered_user_message");
4712
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "skipped", null, null);
2699
4713
  return;
2700
4714
  }
2701
4715
  if (data?.targetUserId && lastLeaf.id !== data.targetUserId) {
2702
- if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, "Recovered chat retry was skipped because the conversation changed.");
4716
+ await this._updateChatRecoveryIncident(data?.incidentId, "skipped", "conversation_changed");
4717
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "skipped", null, null);
2703
4718
  return;
2704
4719
  }
2705
4720
  this._applyRecoveredRequestContext(data);
2706
4721
  const result = await this._retryLastUserTurn(this._lastClientTools, this._lastBody, controller ? { signal: controller.signal } : void 0);
4722
+ await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
2707
4723
  if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : result.error ?? `Recovery retry ${result.status}.`);
2708
4724
  } catch (error) {
2709
- if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, error instanceof Error ? error.message : String(error));
2710
- throw error;
4725
+ await this._handleRecoveryCallbackError("_chatRecoveryRetry", data, error);
2711
4726
  } finally {
4727
+ this._activeChatRecoveryRootRequestId = previousRootRequestId;
2712
4728
  if (recoveredSubmission) this._submissionAbortControllers.delete(recoveredSubmission.submission_id);
2713
4729
  }
2714
4730
  }
@@ -2780,28 +4796,38 @@ var Think = class Think extends Agent {
2780
4796
  }
2781
4797
  async _chatRecoveryContinue(data) {
2782
4798
  const recoveredSubmission = data?.recoveredRequestId ? this._readRunningSubmissionByRequestId(data.recoveredRequestId) : null;
2783
- if (data?.recoveredRequestId && !recoveredSubmission) return;
4799
+ if (data?.recoveredRequestId && !recoveredSubmission) {
4800
+ await this._updateChatRecoveryIncident(data.incidentId, "skipped", "submission_not_running");
4801
+ return;
4802
+ }
4803
+ const previousRootRequestId = this._activeChatRecoveryRootRequestId;
4804
+ this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
2784
4805
  const controller = recoveredSubmission ? new AbortController() : null;
2785
4806
  if (recoveredSubmission && controller) this._submissionAbortControllers.set(recoveredSubmission.submission_id, controller);
2786
4807
  try {
2787
- if (!await this.waitUntilStable({ timeout: 1e4 })) {
2788
- console.warn("[Think] _chatRecoveryContinue timed out waiting for stable state, skipping continuation");
2789
- if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, "Recovered chat continuation timed out waiting for stable state.");
4808
+ const recoveryConfig = this._resolveChatRecoveryConfig();
4809
+ if (!await this.waitUntilStable({ timeout: recoveryConfig.stableTimeoutMs })) {
4810
+ console.warn("[Think] _chatRecoveryContinue timed out waiting for stable state");
4811
+ if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryContinue", data, recoveryConfig.maxAttempts)) return;
4812
+ await this._exhaustRecoveryAfterStableTimeout("_chatRecoveryContinue", data);
2790
4813
  return;
2791
4814
  }
2792
4815
  const targetId = data?.targetAssistantId;
2793
4816
  const lastLeaf = await this.session.getLatestLeaf();
2794
4817
  if (targetId && lastLeaf?.id !== targetId) {
2795
- if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, "Recovered chat continuation was skipped because the conversation changed.");
4818
+ const supersededByNewerUserTurn = lastLeaf?.role === "user";
4819
+ await this._updateChatRecoveryIncident(data?.incidentId, "skipped", "conversation_changed");
4820
+ if (data?.recoveredRequestId && supersededByNewerUserTurn) await this._completeRecoveredSubmission(data.recoveredRequestId, "skipped", null, null);
2796
4821
  return;
2797
4822
  }
2798
4823
  this._applyRecoveredRequestContext(data);
2799
4824
  const result = await this.continueLastTurn(void 0, controller ? { signal: controller.signal } : void 0);
4825
+ await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
2800
4826
  if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : result.error ?? `Recovery ${result.status}.`);
2801
4827
  } catch (error) {
2802
- if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, error instanceof Error ? error.message : String(error));
2803
- throw error;
4828
+ await this._handleRecoveryCallbackError("_chatRecoveryContinue", data, error);
2804
4829
  } finally {
4830
+ this._activeChatRecoveryRootRequestId = previousRootRequestId;
2805
4831
  if (recoveredSubmission) this._submissionAbortControllers.delete(recoveredSubmission.submission_id);
2806
4832
  }
2807
4833
  }
@@ -2865,30 +4891,116 @@ var Think = class Think extends Agent {
2865
4891
  this._continuation.pending.connectionId = connection.id;
2866
4892
  this._continuation.pending.clientTools = this._lastClientTools;
2867
4893
  this._continuation.awaitingConnections.set(connection.id, connection);
4894
+ this._resetAutoContinuationTimer();
2868
4895
  return;
2869
4896
  }
4897
+ this._continuation.pending = {
4898
+ connection,
4899
+ connectionId: connection.id,
4900
+ requestId: crypto.randomUUID(),
4901
+ clientTools: this._lastClientTools,
4902
+ body: void 0,
4903
+ errorPrefix: "[Think] Auto-continuation failed:",
4904
+ prerequisite: null,
4905
+ pastCoalesce: false
4906
+ };
4907
+ this._continuation.awaitingConnections.set(connection.id, connection);
4908
+ this._resetAutoContinuationTimer();
4909
+ }
4910
+ _resetAutoContinuationTimer() {
2870
4911
  if (this._continuationTimer) clearTimeout(this._continuationTimer);
2871
4912
  this._continuationTimer = setTimeout(() => {
2872
4913
  this._continuationTimer = null;
2873
- this._fireAutoContinuation(connection);
4914
+ const pending = this._continuation.pending;
4915
+ if (!pending) return;
4916
+ this._fireAutoContinuationWhenStable(pending.connection);
2874
4917
  }, 50);
2875
4918
  }
4919
+ /**
4920
+ * Fire an auto-continuation, but only once the model's parallel tool-call
4921
+ * batch is fully answered (#1649). When the model emits several tool calls in
4922
+ * one step the client answers each independently, so the first `autoContinue`
4923
+ * arrives while slower siblings are still `input-available`. Continuing then
4924
+ * would feed the provider an incomplete tool-result set
4925
+ * (`MissingToolResultsError`) or, via the transcript-repair backstop, silently
4926
+ * error the in-flight sibling and run a spurious extra continuation. We hold
4927
+ * the continuation on a barrier until the batch settles. The wait is bounded
4928
+ * (`AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS`) so a genuinely orphaned tool
4929
+ * call — e.g. the client disconnected mid-batch — still falls through to the
4930
+ * repair backstop rather than pinning the continuation open forever.
4931
+ */
4932
+ _fireAutoContinuationWhenStable(connection) {
4933
+ if (!this._continuation.pending) return;
4934
+ if (this._continuation.pending.pastCoalesce) return;
4935
+ if (this._continuationBarrierActive) return;
4936
+ if (!this._pendingInteractionPromise && !this._hasIncompleteToolBatch()) {
4937
+ this._fireAutoContinuation(connection);
4938
+ return;
4939
+ }
4940
+ this._continuationBarrierActive = true;
4941
+ this.keepAliveWhile(() => this._awaitToolBatch()).catch(() => {}).finally(() => {
4942
+ this._continuationBarrierActive = false;
4943
+ const pending = this._continuation.pending;
4944
+ if (pending) this._fireAutoContinuation(pending.connection);
4945
+ });
4946
+ }
4947
+ /**
4948
+ * Block until the latest assistant step's parallel tool batch is fully
4949
+ * answered, or `AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS` elapses. Awaits the
4950
+ * in-flight tool-result apply when one exists (so a sibling that lands
4951
+ * mid-wait is observed promptly) and polls otherwise.
4952
+ */
4953
+ async _awaitToolBatch() {
4954
+ const deadline = Date.now() + AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS;
4955
+ while (Date.now() < deadline) {
4956
+ if (!this._continuation.pending) return;
4957
+ const pending = this._pendingInteractionPromise;
4958
+ if (pending) {
4959
+ try {
4960
+ await pending;
4961
+ } catch {}
4962
+ continue;
4963
+ }
4964
+ if (!this._hasIncompleteToolBatch()) return;
4965
+ await new Promise((resolve) => setTimeout(resolve, 100));
4966
+ }
4967
+ console.warn(`[Think] Auto-continuation proceeding after waiting ${AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS}ms for unanswered parallel tool result(s) (#1649).`);
4968
+ }
4969
+ /**
4970
+ * `true` when the latest assistant message is mid-batch: it carries at least
4971
+ * one settled tool result AND at least one tool call/approval still awaiting a
4972
+ * client result. That is the #1649 signature — the model fanned out parallel
4973
+ * tool calls and only some have been answered. Scoped to the leaf (the step
4974
+ * the continuation answers) so an unrelated dangling tool in an earlier
4975
+ * message doesn't block a legitimate follow-up continuation.
4976
+ */
4977
+ _hasIncompleteToolBatch() {
4978
+ const messages = this.messages;
4979
+ let leaf;
4980
+ for (let i = messages.length - 1; i >= 0; i--) if (messages[i].role === "assistant") {
4981
+ leaf = messages[i];
4982
+ break;
4983
+ }
4984
+ if (!leaf) return false;
4985
+ let hasPending = false;
4986
+ let hasSettled = false;
4987
+ for (const part of leaf.parts) {
4988
+ const record = part;
4989
+ const state = record.state;
4990
+ if (state === "input-available" || state === "approval-requested") hasPending = true;
4991
+ else if (typeof record.type === "string" && (record.type.startsWith("tool-") || record.type === "dynamic-tool") && (state === "output-available" || state === "output-error" || state === "output-denied" || state === "approval-responded")) hasSettled = true;
4992
+ if (hasPending && hasSettled) return true;
4993
+ }
4994
+ return false;
4995
+ }
2876
4996
  _fireAutoContinuation(connection) {
2877
- if (!this._continuation.pending) {
2878
- const requestId = crypto.randomUUID();
2879
- this._continuation.pending = {
2880
- connection,
2881
- connectionId: connection.id,
2882
- requestId,
2883
- clientTools: this._lastClientTools,
2884
- body: void 0,
2885
- errorPrefix: "[Think] Auto-continuation failed:",
2886
- prerequisite: null,
2887
- pastCoalesce: false
2888
- };
2889
- this._continuation.awaitingConnections.set(connection.id, connection);
4997
+ const pending = this._continuation.pending;
4998
+ if (!pending) return;
4999
+ if (this._continuationTimer) {
5000
+ clearTimeout(this._continuationTimer);
5001
+ this._continuationTimer = null;
2890
5002
  }
2891
- const { requestId, clientTools } = this._continuation.pending;
5003
+ const { requestId, clientTools } = pending;
2892
5004
  const abortSignal = this._aborts.getSignal(requestId);
2893
5005
  this.keepAliveWhile(async () => {
2894
5006
  await this._turnQueue.enqueue(requestId, async () => {
@@ -2929,9 +5041,10 @@ var Think = class Think extends Agent {
2929
5041
  _activateDeferredContinuation() {
2930
5042
  const pending = this._continuation.activateDeferred(() => crypto.randomUUID());
2931
5043
  if (!pending) return;
2932
- this._fireAutoContinuation(pending.connection);
5044
+ this._fireAutoContinuationWhenStable(pending.connection);
2933
5045
  }
2934
5046
  async _fireResponseHook(result) {
5047
+ await this._recordTerminalChatStatus(result.status, result.requestId, result.error ?? "The assistant was interrupted.");
2935
5048
  if (this._insideResponseHook) return;
2936
5049
  this._insideResponseHook = true;
2937
5050
  try {
@@ -2942,6 +5055,79 @@ var Think = class Think extends Agent {
2942
5055
  this._insideResponseHook = false;
2943
5056
  }
2944
5057
  }
5058
+ /**
5059
+ * Persist (on `error`) or clear (on `completed`/`aborted`) a durable record of
5060
+ * the last terminal turn so it can be replayed to clients on connect. A
5061
+ * `completed`/`aborted` turn is conveyed by the persisted messages, so the
5062
+ * record is cleared; an `error`/`interrupted` turn has no durable trace
5063
+ * otherwise, so it is kept until a later turn resolves.
5064
+ */
5065
+ async _recordTerminalChatStatus(status, requestId, body) {
5066
+ if (status === "error" || status === "interrupted") await this.ctx.storage.put(CHAT_LAST_TERMINAL_KEY, {
5067
+ requestId,
5068
+ body
5069
+ });
5070
+ else await this.ctx.storage.delete(CHAT_LAST_TERMINAL_KEY);
5071
+ await this._setChatRecovering(false);
5072
+ }
5073
+ async _pendingTerminalChatResponse() {
5074
+ return await this.ctx.storage.get(CHAT_LAST_TERMINAL_KEY) ?? null;
5075
+ }
5076
+ /**
5077
+ * Set or clear the live "recovering…" status for a durable chat turn (#1620).
5078
+ * Persists a durable record (replayed on connect via `_buildIdleConnectMessages`)
5079
+ * and broadcasts a `MSG_CHAT_RECOVERING` frame — but only on a genuine
5080
+ * transition, so a deploy/reconnect storm (which re-detects recovery many
5081
+ * times) doesn't spam the wire. Cleared on every terminal outcome so the
5082
+ * indicator can't spin forever.
5083
+ */
5084
+ async _setChatRecovering(active, requestId) {
5085
+ const existing = await this.ctx.storage.get(CHAT_RECOVERING_KEY);
5086
+ const activeExisting = existing && Date.now() - (existing.at ?? 0) < CHAT_RECOVERY_MAX_WINDOW_MS;
5087
+ if (active) {
5088
+ if (activeExisting) return;
5089
+ await this.ctx.storage.put(CHAT_RECOVERING_KEY, {
5090
+ ...requestId ? { requestId } : {},
5091
+ at: Date.now()
5092
+ });
5093
+ } else {
5094
+ if (!existing) return;
5095
+ await this.ctx.storage.delete(CHAT_RECOVERING_KEY);
5096
+ requestId = requestId ?? existing.requestId;
5097
+ }
5098
+ this._broadcastChat({
5099
+ type: MSG_CHAT_RECOVERING,
5100
+ recovering: active,
5101
+ ...requestId ? { id: requestId } : {}
5102
+ });
5103
+ }
5104
+ /**
5105
+ * Messages sent to a client on connect when no stream is active: the current
5106
+ * transcript, plus a replay of the last terminal error (if any) so a turn
5107
+ * that failed while the client was disconnected is surfaced rather than
5108
+ * silently frozen.
5109
+ */
5110
+ async _buildIdleConnectMessages() {
5111
+ const messages = [{
5112
+ type: MSG_CHAT_MESSAGES,
5113
+ messages: this.messages
5114
+ }];
5115
+ const pending = await this._pendingTerminalChatResponse();
5116
+ if (pending) messages.push({
5117
+ type: MSG_CHAT_RESPONSE,
5118
+ id: pending.requestId,
5119
+ body: pending.body,
5120
+ done: true,
5121
+ error: true
5122
+ });
5123
+ const recovering = await this.ctx.storage.get(CHAT_RECOVERING_KEY);
5124
+ if (recovering && Date.now() - (recovering.at ?? 0) < CHAT_RECOVERY_MAX_WINDOW_MS) messages.push({
5125
+ type: MSG_CHAT_RECOVERING,
5126
+ recovering: true,
5127
+ ...recovering.requestId ? { id: recovering.requestId } : {}
5128
+ });
5129
+ return messages;
5130
+ }
2945
5131
  _notifyStreamResuming(connection) {
2946
5132
  if (!this._resumableStream.hasActiveStream()) return;
2947
5133
  if (sendIfOpen(connection, JSON.stringify({
@@ -2979,12 +5165,13 @@ var Think = class Think extends Agent {
2979
5165
  Think.CONFIG_KEYS = [
2980
5166
  "_think_config",
2981
5167
  "lastClientTools",
2982
- "lastBody"
5168
+ "lastBody",
5169
+ "skillsFingerprint"
2983
5170
  ];
2984
5171
  Think.CHAT_FIBER_NAME = "__cf_internal_chat_turn";
2985
5172
  Think.MESSAGE_DEBOUNCE_MS = 750;
2986
5173
  Think.submissionRecoveryStaleMs = 900 * 1e3;
2987
5174
  //#endregion
2988
- export { Session, Think, Workspace };
5175
+ export { Session, Think, Workspace, defineScheduledTasks, skills };
2989
5176
 
2990
5177
  //# sourceMappingURL=think.js.map