@cloudflare/think 0.7.3 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/think.js CHANGED
@@ -1,8 +1,11 @@
1
1
  import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-BP1jgEfY.js";
2
2
  import { createWorkspaceTools } from "./tools/workspace.js";
3
- import { convertToModelMessages, stepCountIs, streamText } from "ai";
3
+ import { t as ThinkMessengerRuntime } from "./chat-sdk-CJwYlbp9.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, 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,14 +338,18 @@ 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;
@@ -60,14 +361,19 @@ var Think = class Think extends Agent {
60
361
  this._agentToolPreTurnAssistantIds = /* @__PURE__ */ new Map();
61
362
  this._agentToolLiveSequences = /* @__PURE__ */ new Map();
62
363
  this._submissionTableEnsured = false;
364
+ this._workflowNotificationTableEnsured = false;
365
+ this._declaredScheduledTasksTableEnsured = false;
63
366
  this._drainingSubmissions = false;
367
+ this._drainingWorkflowNotifications = false;
64
368
  this._submissionAbortControllers = /* @__PURE__ */ new Map();
65
369
  this._programmaticStreamErrors = /* @__PURE__ */ new Map();
66
370
  _classPrivateFieldInitSpec(this, _configCache, null);
67
371
  _classPrivateFieldInitSpec(this, _configTableReady, false);
68
372
  this.maxSteps = 10;
69
373
  this.sendReasoning = true;
374
+ this.chatStreamStallTimeoutMs = 0;
70
375
  this.hookTimeout = 5e3;
376
+ this._lastAgentToolStreamProgressAt = 0;
71
377
  const _onStart = this.onStart.bind(this);
72
378
  this.onStart = async () => {
73
379
  if (!this.workspace) this.workspace = new Workspace$1({
@@ -94,15 +400,20 @@ var Think = class Think extends Agent {
94
400
  break;
95
401
  }
96
402
  });
403
+ await this._initializeSkills();
97
404
  await this._syncMessages();
98
405
  if (this.extensionLoader) await this._initializeExtensions();
99
406
  this._resumableStream = new ResumableStream(this.sql.bind(this));
100
407
  this._restoreClientTools();
101
408
  this._restoreBody();
102
409
  this._setupProtocolHandlers();
410
+ this._initializeMessengers();
103
411
  await _onStart();
412
+ await this._reconcileDeclaredScheduledTasks();
104
413
  await this._recoverSubmissionsOnStart();
414
+ this._recoverWorkflowNotifications();
105
415
  this._startSubmissionDrain();
416
+ this._startWorkflowNotificationDrain();
106
417
  };
107
418
  }
108
419
  /**
@@ -120,6 +431,181 @@ var Think = class Think extends Agent {
120
431
  async _readMessagesFromStorage() {
121
432
  return await this.session.getHistory();
122
433
  }
434
+ /**
435
+ * Normalize a tool part's `input` into something the provider will accept.
436
+ *
437
+ * Two malformed shapes 400 modern providers (and persist forever once
438
+ * written): a stringified-JSON `input` (e.g. `'{"prompt":"a cat"}'` instead
439
+ * of the object) and a missing/`null` `input` on a settled or interrupted
440
+ * tool call (Anthropic rejects a `tool_use` block whose `input` is absent).
441
+ * We parse the former and default the latter to an empty object so the
442
+ * tool-call/tool-result pair stays valid. Any other value is left untouched.
443
+ */
444
+ _normalizeToolInput(record) {
445
+ const raw = "input" in record ? record.input : void 0;
446
+ if (typeof raw === "string") {
447
+ const trimmed = raw.trim();
448
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) try {
449
+ return {
450
+ input: JSON.parse(raw),
451
+ changed: true
452
+ };
453
+ } catch {
454
+ return {
455
+ input: raw,
456
+ changed: false
457
+ };
458
+ }
459
+ }
460
+ if (raw === void 0 || raw === null) return {
461
+ input: {},
462
+ changed: true
463
+ };
464
+ return {
465
+ input: raw,
466
+ changed: false
467
+ };
468
+ }
469
+ /**
470
+ * Whether a tool part already has a settled result the provider accepts, so
471
+ * it must NOT be re-repaired into an errored result.
472
+ *
473
+ * Single source of truth for the terminal tool states, shared by the repair
474
+ * pass and the backstop detector so they cannot drift. Mirror the AI SDK's
475
+ * terminal states: `convertToModelMessages` emits a `tool-result` for
476
+ * `output-available`, `output-error`, AND `output-denied` (a user-denied
477
+ * approval — its denial reason becomes the tool-result). Omitting any of
478
+ * these makes repair re-flip the part every turn — clobbering a real
479
+ * `errorText`/denial with the generic "interrupted" message — and makes the
480
+ * backstop falsely drop a valid call.
481
+ */
482
+ _toolPartHasSettledResult(record) {
483
+ if ("output" in record || "result" in record) return true;
484
+ const state = typeof record.state === "string" ? record.state : "";
485
+ return state === "output-available" || state === "output-error" || state === "output-denied";
486
+ }
487
+ /**
488
+ * Tool-call ids that still have no recorded result. After repair this should
489
+ * be empty; a non-empty result means the backstop (`ignoreIncompleteToolCalls`)
490
+ * will drop those calls — i.e. repair missed a shape and should be extended.
491
+ *
492
+ * `approval-responded` is deliberately excluded: an approved server tool has
493
+ * no result *yet*, but it is not incomplete or abandoned — it is waiting for
494
+ * its continuation to run `execute()`. `convertToModelMessages` keeps that
495
+ * call (and the SDK executes it), so flagging it here would log a misleading
496
+ * "repair gap" warning and emit a spurious `chat:transcript:repaired` event
497
+ * on every approval continuation.
498
+ */
499
+ _incompleteToolCallIds(messages) {
500
+ const ids = [];
501
+ for (const message of messages) for (const part of message.parts) {
502
+ const record = part;
503
+ const toolCallId = typeof record.toolCallId === "string" ? record.toolCallId : void 0;
504
+ if (!(typeof record.type === "string" && (record.type.startsWith("tool-") || record.type === "dynamic-tool") && toolCallId)) continue;
505
+ if (record.state === "approval-responded") continue;
506
+ if (!this._toolPartHasSettledResult(record)) ids.push(toolCallId);
507
+ }
508
+ return ids;
509
+ }
510
+ /**
511
+ * Repair a single interrupted tool call — a tool part with no settled result,
512
+ * left behind when a stream was cut off mid-flight. Returns the replacement
513
+ * part that takes its place in the transcript. `input` has already been
514
+ * normalized to a valid object.
515
+ *
516
+ * The default flips it to an errored tool result so the record survives (no
517
+ * "disappearing" tool call) and `convertToModelMessages` still gets a
518
+ * tool-result for it (avoiding `AI_MissingToolResultsError`).
519
+ *
520
+ * Override to customize the repaired shape for client-resolved tools — e.g.
521
+ * convert an interrupted `ask_user` (a question with no server `execute`,
522
+ * normally answered by the user's next message) into a plain text part
523
+ * carrying the question prose, so the model sees it as ordinary conversation
524
+ * rather than a tool error and compaction keeps the question verbatim. This
525
+ * runs DURING transcript repair — before the repaired transcript is persisted
526
+ * and sent to the model — so the conversion shapes the current turn, not just
527
+ * the next one. A returned tool part MUST carry a settled result
528
+ * (`output-available` / `output-error` / `output-denied` or an
529
+ * `output`/`result` field); returning a non-tool part (e.g. text) is fine.
530
+ */
531
+ repairInterruptedToolPart(part) {
532
+ return {
533
+ ...part,
534
+ state: "output-error",
535
+ errorText: "The tool call was interrupted before a result was recorded."
536
+ };
537
+ }
538
+ _repairToolTranscriptParts(messages) {
539
+ let removedToolCalls = 0;
540
+ let normalizedInputs = 0;
541
+ const toolCallIds = [];
542
+ const repaired = [];
543
+ for (const message of messages) {
544
+ const parts = [];
545
+ let messageChanged = false;
546
+ for (const part of message.parts) {
547
+ const record = part;
548
+ const toolCallId = typeof record.toolCallId === "string" ? record.toolCallId : void 0;
549
+ if (!(typeof record.type === "string" && (record.type.startsWith("tool-") || record.type === "dynamic-tool") && toolCallId)) {
550
+ parts.push(part);
551
+ continue;
552
+ }
553
+ if (!this._toolPartHasSettledResult(record)) {
554
+ if ((typeof record.state === "string" ? record.state : "") === "approval-responded") {
555
+ parts.push(part);
556
+ continue;
557
+ }
558
+ const normalized = this._normalizeToolInput(record);
559
+ parts.push(this.repairInterruptedToolPart({
560
+ ...part,
561
+ input: normalized.input
562
+ }));
563
+ if (normalized.changed) normalizedInputs++;
564
+ removedToolCalls++;
565
+ messageChanged = true;
566
+ toolCallIds.push(toolCallId);
567
+ continue;
568
+ }
569
+ const normalized = this._normalizeToolInput(record);
570
+ if (normalized.changed) {
571
+ parts.push({
572
+ ...part,
573
+ input: normalized.input
574
+ });
575
+ normalizedInputs++;
576
+ messageChanged = true;
577
+ continue;
578
+ }
579
+ parts.push(part);
580
+ }
581
+ repaired.push(messageChanged ? {
582
+ ...message,
583
+ parts
584
+ } : message);
585
+ }
586
+ return {
587
+ messages: repaired,
588
+ removedToolCalls,
589
+ normalizedInputs,
590
+ toolCallIds
591
+ };
592
+ }
593
+ async _repairTranscriptForProvider(messages) {
594
+ const repair = this._repairToolTranscriptParts(messages);
595
+ if (repair.removedToolCalls === 0 && repair.normalizedInputs === 0) return messages;
596
+ for (const message of repair.messages) {
597
+ const original = messages.find((candidate) => candidate.id === message.id);
598
+ if (original && original.parts !== message.parts) await this.session.updateMessage(sanitizeMessage(message));
599
+ }
600
+ this._replaceCachedMessages(repair.messages);
601
+ this._broadcastMessages();
602
+ this._emit("chat:transcript:repaired", {
603
+ removedToolCalls: repair.removedToolCalls,
604
+ normalizedInputs: repair.normalizedInputs,
605
+ toolCallIds: repair.toolCallIds
606
+ });
607
+ return repair.messages;
608
+ }
123
609
  /** Replace the live cache with a durable storage snapshot. */
124
610
  _replaceCachedMessages(messages) {
125
611
  this._cachedMessages = messages;
@@ -189,6 +675,10 @@ var Think = class Think extends Agent {
189
675
  } catch {}
190
676
  super.broadcast(msg, without);
191
677
  }
678
+ async alarm() {
679
+ await super.alarm();
680
+ this._startWorkflowNotificationDrain();
681
+ }
192
682
  /**
193
683
  * Persist an arbitrary JSON-serializable configuration object for this
194
684
  * agent instance. Stored in the Think-private `think_config` table —
@@ -298,10 +788,52 @@ var Think = class Think extends Agent {
298
788
  getTools() {
299
789
  return {};
300
790
  }
791
+ /** Return messenger integrations that should be routed through this Think agent. */
792
+ getMessengers() {
793
+ return {};
794
+ }
795
+ getMessengerContext() {
796
+ if (this._activeMessengerContext) return this._activeMessengerContext;
797
+ return this.messages.at(-1)?.metadata?.messenger;
798
+ }
799
+ async chatWithMessengerContext(userMessage, callback, context, options) {
800
+ const previous = this._activeMessengerContext;
801
+ this._activeMessengerContext = context;
802
+ try {
803
+ await this.chat(userMessage, callback, options);
804
+ } finally {
805
+ this._activeMessengerContext = previous;
806
+ }
807
+ }
808
+ _initializeMessengers() {
809
+ if (this.parentPath.length > 0) return;
810
+ const messengers = this.getMessengers();
811
+ if (Object.keys(messengers).length === 0) return;
812
+ this._messengerRuntime = new ThinkMessengerRuntime(messengers, this);
813
+ this._messengerRuntime.initialize();
814
+ }
815
+ /** Return code-declared scheduled tasks for this agent. */
816
+ getScheduledTasks() {
817
+ return {};
818
+ }
819
+ /**
820
+ * Reconcile code-declared scheduled tasks immediately.
821
+ * Static declarations are reconciled on startup automatically; call this
822
+ * after changing app-owned data that `getScheduledTasks()` reads.
823
+ */
824
+ async internal_reconcileScheduledTasks() {
825
+ await this._reconcileDeclaredScheduledTasks();
826
+ }
827
+ /**
828
+ * Return the default timezone for wall-clock scheduled tasks.
829
+ * Task-local timezone declarations take precedence.
830
+ */
831
+ getDefaultTimezone() {}
301
832
  async _runChatRecoveryFiber(requestId, continuation, fn) {
302
833
  const snapshot = createChatFiberSnapshot({
303
834
  kind: "think-chat-turn",
304
835
  requestId,
836
+ recoveryRootRequestId: this._activeChatRecoveryRootRequestId ?? requestId,
305
837
  continuation,
306
838
  messages: this.messages,
307
839
  lastBody: this._lastBody,
@@ -364,6 +896,75 @@ var Think = class Think extends Agent {
364
896
  return session;
365
897
  }
366
898
  /**
899
+ * Return Agent Skills sources for this Think agent.
900
+ *
901
+ * Bundled skills are typically imported with the Agents Vite plugin:
902
+ *
903
+ * ```typescript
904
+ * import productSkills from "agents:skills"; // -> ./skills next to this file
905
+ * ```
906
+ *
907
+ * Sources are applied in order; the first source to register a skill name
908
+ * wins, and later collisions are skipped with a logged warning.
909
+ */
910
+ getSkills() {
911
+ return [];
912
+ }
913
+ async _initializeSkills() {
914
+ try {
915
+ const sources = await this.getSkills();
916
+ if (sources.length === 0) return;
917
+ const registry = new SkillRegistry(sources, this.getSkillScriptRunner());
918
+ await registry.load();
919
+ this._logSkillWarnings(registry);
920
+ this._skillRegistry = registry;
921
+ await this.session.addContext(registry.contextLabel, {
922
+ description: "Think skills: available skill catalog",
923
+ provider: { get: () => registry.systemPrompt() }
924
+ });
925
+ if (this._configGet("skillsFingerprint") !== registry.fingerprint) {
926
+ await this.session.refreshSystemPrompt();
927
+ this._configSet("skillsFingerprint", registry.fingerprint);
928
+ }
929
+ } catch (error) {
930
+ console.warn(`[think] Failed to initialize skills; continuing without them: ${error instanceof Error ? error.message : String(error)}`);
931
+ }
932
+ }
933
+ /**
934
+ * Log registry diagnostics (duplicate names, sources that failed to list),
935
+ * deduped by message so a new collision after a deploy still surfaces while
936
+ * the same warning is not repeated on every turn.
937
+ */
938
+ _logSkillWarnings(registry) {
939
+ for (const warning of registry.warnings) {
940
+ if (this._loggedSkillWarnings.has(warning)) continue;
941
+ this._loggedSkillWarnings.add(warning);
942
+ console.warn(`[think] ${warning}`);
943
+ }
944
+ }
945
+ /**
946
+ * Return an optional runner that enables the `run_skill_script` tool.
947
+ *
948
+ * @experimental Skill script execution is experimental and may change
949
+ * before stabilizing.
950
+ */
951
+ getSkillScriptRunner() {
952
+ return null;
953
+ }
954
+ async _refreshSkillsIfChanged() {
955
+ if (!this._skillRegistry) return;
956
+ try {
957
+ await this._skillRegistry.refresh();
958
+ this._logSkillWarnings(this._skillRegistry);
959
+ if (this._configGet("skillsFingerprint") !== this._skillRegistry.fingerprint) {
960
+ await this.session.refreshSystemPrompt();
961
+ this._configSet("skillsFingerprint", this._skillRegistry.fingerprint);
962
+ }
963
+ } catch (error) {
964
+ console.warn(`[think] Failed to refresh skills; using last known catalog: ${error instanceof Error ? error.message : String(error)}`);
965
+ }
966
+ }
967
+ /**
367
968
  * Return sandboxed extension configurations. Defines load order,
368
969
  * which determines hook execution order.
369
970
  * Requires `extensionLoader` to be set.
@@ -525,7 +1126,7 @@ var Think = class Think extends Agent {
525
1126
  * Handle an error that occurred during a chat turn.
526
1127
  * Override to customize error handling (e.g. logging, metrics).
527
1128
  */
528
- onChatError(error) {
1129
+ onChatError(error, _ctx) {
529
1130
  return error;
530
1131
  }
531
1132
  async _initializeExtensions() {
@@ -571,27 +1172,43 @@ var Think = class Think extends Agent {
571
1172
  * for interception, and calls streamText.
572
1173
  */
573
1174
  async _runInferenceLoop(input) {
1175
+ this._activeStallTimeoutMs = void 0;
574
1176
  if (this.waitForMcpConnections) {
575
1177
  const timeout = typeof this.waitForMcpConnections === "object" ? this.waitForMcpConnections.timeout : 1e4;
576
1178
  await this.mcp.waitForConnections({ timeout });
577
1179
  }
578
- const workspaceTools = createWorkspaceTools(this.workspace);
1180
+ const workspaceTools = createWorkspaceTools(this.workspace, { bash: this.workspaceBash });
579
1181
  const baseTools = this.getTools();
580
1182
  const extensionTools = this.extensionManager?.getTools() ?? {};
1183
+ await this._refreshSkillsIfChanged();
581
1184
  const contextTools = await this.session.tools();
1185
+ const skillTools = this._skillRegistry?.tools() ?? {};
582
1186
  const clientToolSet = createToolsFromClientSchemas(input.clientTools);
583
1187
  const tools = {
584
1188
  ...workspaceTools,
585
1189
  ...baseTools,
586
1190
  ...extensionTools,
587
1191
  ...contextTools,
1192
+ ...skillTools,
588
1193
  ...this.mcp?.getAITools?.() ?? {},
589
1194
  ...clientToolSet
590
1195
  };
591
1196
  const baseSystem = await this.session.freezeSystemPrompt() || this.getSystemPrompt();
592
1197
  const system = this._systemPromptForTurn(baseSystem, tools);
593
- const history = this.messages;
594
- const messages = await convertToModelMessages(truncateOlderMessages(history), { tools });
1198
+ const truncated = truncateOlderMessages(await this._repairTranscriptForProvider(this.messages));
1199
+ const incompleteAfterRepair = this._incompleteToolCallIds(truncated);
1200
+ if (incompleteAfterRepair.length > 0) {
1201
+ 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.`);
1202
+ this._emit("chat:transcript:repaired", {
1203
+ removedToolCalls: incompleteAfterRepair.length,
1204
+ normalizedInputs: 0,
1205
+ toolCallIds: incompleteAfterRepair
1206
+ });
1207
+ }
1208
+ const messages = await convertToModelMessages(truncated, {
1209
+ tools,
1210
+ ignoreIncompleteToolCalls: true
1211
+ });
595
1212
  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
1213
  const model = this.getModel();
597
1214
  const ctx = {
@@ -604,12 +1221,14 @@ var Think = class Think extends Agent {
604
1221
  };
605
1222
  const subclassConfig = await this.beforeTurn(ctx) ?? {};
606
1223
  const config = await this._pipelineExtensionBeforeTurn(ctx, subclassConfig);
1224
+ const workflowPrompt = input.workflowPrompt;
1225
+ const workflowOutput = workflowPrompt?.output ? Output.object({ schema: jsonSchema(workflowPrompt.output.schema) }) : void 0;
607
1226
  const finalModel = config.model ?? model;
608
1227
  const finalSystem = config.system ?? this._systemPromptForTurn(baseSystem, config.tools ? {
609
1228
  ...tools,
610
1229
  ...config.tools
611
1230
  } : tools);
612
- const finalMessages = config.messages ?? messages;
1231
+ const finalMessages = ensureValidContinueCheckpoint(config.messages ?? messages);
613
1232
  const mergedTools = config.tools ? {
614
1233
  ...tools,
615
1234
  ...config.tools
@@ -617,6 +1236,8 @@ var Think = class Think extends Agent {
617
1236
  const finalTools = this._wrapToolsWithDecision(mergedTools);
618
1237
  const finalMaxSteps = config.maxSteps ?? this.maxSteps;
619
1238
  const finalSendReasoning = config.sendReasoning ?? this.sendReasoning;
1239
+ this._activeStallTimeoutMs = config.chatStreamStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
1240
+ const finalOutput = workflowOutput ?? config.output;
620
1241
  const finalStopWhen = [stepCountIs(finalMaxSteps), ...Array.isArray(config.stopWhen) ? config.stopWhen : config.stopWhen ? [config.stopWhen] : []];
621
1242
  const result = streamText({
622
1243
  model: finalModel,
@@ -639,7 +1260,7 @@ var Think = class Think extends Agent {
639
1260
  stopWhen: finalStopWhen,
640
1261
  providerOptions: config.providerOptions,
641
1262
  experimental_telemetry: config.experimental_telemetry,
642
- output: config.output,
1263
+ output: finalOutput,
643
1264
  abortSignal: input.signal,
644
1265
  prepareStep: (async (event) => {
645
1266
  const result = await this.beforeStep(event);
@@ -673,7 +1294,13 @@ var Think = class Think extends Agent {
673
1294
  await this._pipelineExtensionToolCallFinish(event);
674
1295
  })
675
1296
  });
676
- return this._transformInferenceResult({ toUIMessageStream: () => result.toUIMessageStream({ sendReasoning: finalSendReasoning }) });
1297
+ const outputPromise = finalOutput && result.output ? Promise.resolve(result.output) : void 0;
1298
+ if (outputPromise) outputPromise.catch(() => {});
1299
+ const streamResult = {
1300
+ toUIMessageStream: () => result.toUIMessageStream({ sendReasoning: finalSendReasoning }),
1301
+ output: outputPromise
1302
+ };
1303
+ return this._transformInferenceResult(streamResult);
677
1304
  }
678
1305
  /** @internal Test seam — override in test agents to wrap the stream (e.g. error injection). */
679
1306
  _transformInferenceResult(result) {
@@ -690,7 +1317,7 @@ var Think = class Think extends Agent {
690
1317
  if (!this.extensionManager) return subclassConfig;
691
1318
  const subscribers = this.extensionManager.getHookSubscribers("beforeTurn");
692
1319
  if (subscribers.length === 0) return subclassConfig;
693
- const { createTurnContextSnapshot, parseHookResult } = await import("./hook-proxy-5248W-ea.js");
1320
+ const { createTurnContextSnapshot, parseHookResult } = await import("./hook-proxy-DHwqL8MV.js");
694
1321
  let snapshot = createTurnContextSnapshot(ctx);
695
1322
  let accumulated = { ...subclassConfig };
696
1323
  if (accumulated.system !== void 0) snapshot.system = accumulated.system;
@@ -861,25 +1488,25 @@ var Think = class Think extends Agent {
861
1488
  async _pipelineExtensionToolCallStart(event) {
862
1489
  if (!this.extensionManager) return;
863
1490
  if (this.extensionManager.getHookSubscribers("beforeToolCall").length === 0) return;
864
- const { createToolCallStartSnapshot } = await import("./hook-proxy-5248W-ea.js");
1491
+ const { createToolCallStartSnapshot } = await import("./hook-proxy-DHwqL8MV.js");
865
1492
  await this._dispatchExtensionObservation("beforeToolCall", createToolCallStartSnapshot(event));
866
1493
  }
867
1494
  async _pipelineExtensionToolCallFinish(event) {
868
1495
  if (!this.extensionManager) return;
869
1496
  if (this.extensionManager.getHookSubscribers("afterToolCall").length === 0) return;
870
- const { createToolCallFinishSnapshot } = await import("./hook-proxy-5248W-ea.js");
1497
+ const { createToolCallFinishSnapshot } = await import("./hook-proxy-DHwqL8MV.js");
871
1498
  await this._dispatchExtensionObservation("afterToolCall", createToolCallFinishSnapshot(event));
872
1499
  }
873
1500
  async _pipelineExtensionStepFinish(event) {
874
1501
  if (!this.extensionManager) return;
875
1502
  if (this.extensionManager.getHookSubscribers("onStepFinish").length === 0) return;
876
- const { createStepFinishSnapshot } = await import("./hook-proxy-5248W-ea.js");
1503
+ const { createStepFinishSnapshot } = await import("./hook-proxy-DHwqL8MV.js");
877
1504
  await this._dispatchExtensionObservation("onStepFinish", createStepFinishSnapshot(event));
878
1505
  }
879
1506
  async _pipelineExtensionChunk(event) {
880
1507
  if (!this.extensionManager) return;
881
1508
  if (this.extensionManager.getHookSubscribers("onChunk").length === 0) return;
882
- const { createChunkSnapshot } = await import("./hook-proxy-5248W-ea.js");
1509
+ const { createChunkSnapshot } = await import("./hook-proxy-DHwqL8MV.js");
883
1510
  await this._dispatchExtensionObservation("onChunk", createChunkSnapshot(event));
884
1511
  }
885
1512
  async _hostReadFile(path) {
@@ -948,7 +1575,7 @@ var Think = class Think extends Agent {
948
1575
  const ignoredTools = options?.tools;
949
1576
  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
1577
  try {
951
- await callback.onStart?.({ requestId });
1578
+ await callback.onStart({ requestId });
952
1579
  await this.keepAliveWhile(async () => {
953
1580
  await this._turnQueue.enqueue(requestId, async () => {
954
1581
  const userMsg = typeof userMessage === "string" ? {
@@ -974,13 +1601,18 @@ var Think = class Think extends Agent {
974
1601
  continuation: false
975
1602
  }));
976
1603
  } catch (error) {
977
- const wrapped = this.onChatError(error);
1604
+ const wrapped = this.onChatError(error, {
1605
+ stage: "turn",
1606
+ messagesPersisted: true
1607
+ });
978
1608
  const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
979
- if (callback.onError) {
980
- await callback.onError(errorMessage);
981
- return;
982
- }
983
- throw wrapped;
1609
+ this._emit("chat:request:failed", {
1610
+ stage: "turn",
1611
+ messagesPersisted: true,
1612
+ error: errorMessage
1613
+ });
1614
+ await callback.onError(errorMessage);
1615
+ return;
984
1616
  }
985
1617
  await this._streamResultToRpcCallback(requestId, result, callback, abortSignal);
986
1618
  };
@@ -1151,9 +1783,78 @@ var Think = class Think extends Agent {
1151
1783
  AND status NOT IN ('completed', 'error', 'aborted')
1152
1784
  `;
1153
1785
  }
1786
+ /**
1787
+ * Classify any in-flight chat-recovery on this child facet (#1630). A child
1788
+ * facet is dedicated to a single agent-tool run, so any recovery incident is
1789
+ * that run's. `detected`/`scheduled`/`attempting` mean recovery is still
1790
+ * resolving the interrupted turn; `exhausted`/`failed` mean it gave up; a
1791
+ * completed recovery deletes its incident.
1792
+ */
1793
+ async _classifyAgentToolChildRecovery() {
1794
+ const entries = await this.ctx.storage.list({ prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX });
1795
+ let failed = false;
1796
+ for (const incident of entries.values()) {
1797
+ if (incident.status === "detected" || incident.status === "scheduled" || incident.status === "attempting") return "in-progress";
1798
+ if (incident.status === "exhausted" || incident.status === "failed") failed = true;
1799
+ }
1800
+ return failed ? "failed" : "none";
1801
+ }
1154
1802
  async inspectAgentToolRun(runId) {
1155
- const row = this._readAgentToolChildRun(runId);
1156
- return row ? this._inspectionFromChildRow(row, this.getAgentToolOutput(runId)) : null;
1803
+ let row = this._readAgentToolChildRun(runId);
1804
+ if (!row) return null;
1805
+ if (this._isStaleAgentToolChildRun(row)) {
1806
+ await this._reconcileStaleAgentToolChildRun(runId);
1807
+ row = this._readAgentToolChildRun(runId) ?? row;
1808
+ }
1809
+ return this._inspectionFromChildRow(row, this.getAgentToolOutput(runId));
1810
+ }
1811
+ _isStaleAgentToolChildRun(row) {
1812
+ return (row.status === "running" || row.status === "starting") && row.completed_at === null && !this._agentToolAbortControllers.has(row.run_id);
1813
+ }
1814
+ /**
1815
+ * Reconcile a stale (post-eviction) child run row from the child's own
1816
+ * durable recovery (#1630). The child facet self-heals its interrupted turn
1817
+ * via `chatRecovery`, but that path never writes the run row, so without this
1818
+ * the row strands `running` and the parent can only collect `interrupted`.
1819
+ *
1820
+ * Persisting the terminal here (rather than only computing it) is intentional:
1821
+ * it's a lazy materialization of the run's true terminal that also lets a
1822
+ * tailing parent's stream close promptly and makes subsequent inspects cheap.
1823
+ * While recovery is still resolving (active stream or in-progress incident)
1824
+ * the row is left `running` so the parent's bounded re-attach keeps waiting.
1825
+ */
1826
+ async _reconcileStaleAgentToolChildRun(runId) {
1827
+ const recovery = await this._classifyAgentToolChildRecovery();
1828
+ if (recovery === "in-progress" || this._resumableStream.hasActiveStream()) return;
1829
+ if (recovery !== "failed" && this._hasRecoveredAgentToolAssistantTurn(runId)) {
1830
+ const output = this.getAgentToolOutput(runId);
1831
+ const summary = this.getAgentToolSummary(runId, output);
1832
+ this.sql`
1833
+ UPDATE cf_agent_tool_child_runs
1834
+ SET status = 'completed',
1835
+ summary = ${summary},
1836
+ output_json = ${Think._stringifyAgentToolOutput(output)},
1837
+ error_message = null,
1838
+ completed_at = ${Date.now()}
1839
+ WHERE run_id = ${runId} AND completed_at IS NULL
1840
+ `;
1841
+ } else this.sql`
1842
+ UPDATE cf_agent_tool_child_runs
1843
+ SET status = 'error',
1844
+ error_message = ${"Agent tool run was interrupted before the child could finish."},
1845
+ completed_at = ${Date.now()}
1846
+ WHERE run_id = ${runId} AND completed_at IS NULL
1847
+ `;
1848
+ this._finalizeAgentToolChildRunTailers(runId);
1849
+ }
1850
+ /** Release a re-attached run's live tail + per-run streaming bookkeeping. */
1851
+ _finalizeAgentToolChildRunTailers(runId) {
1852
+ for (const close of this._agentToolClosers.get(runId) ?? []) close();
1853
+ this._agentToolClosers.delete(runId);
1854
+ this._agentToolForwarders.delete(runId);
1855
+ this._agentToolLiveSequences.delete(runId);
1856
+ this._agentToolLastErrors.delete(runId);
1857
+ this._agentToolPreTurnAssistantIds.delete(runId);
1157
1858
  }
1158
1859
  async getAgentToolChunks(runId, options) {
1159
1860
  const row = this._readAgentToolChildRun(runId);
@@ -1166,24 +1867,50 @@ var Think = class Think extends Agent {
1166
1867
  }
1167
1868
  async tailAgentToolRun(runId, options) {
1168
1869
  const self = this;
1870
+ const signal = options?.signal;
1871
+ let closed = false;
1872
+ let forward;
1873
+ const detach = () => {
1874
+ if (forward) {
1875
+ self._agentToolForwarders.get(runId)?.delete(forward);
1876
+ forward = void 0;
1877
+ }
1878
+ };
1169
1879
  return new ReadableStream({
1170
1880
  async start(controller) {
1881
+ const close = () => {
1882
+ if (closed) return;
1883
+ closed = true;
1884
+ detach();
1885
+ try {
1886
+ controller.close();
1887
+ } catch {}
1888
+ };
1889
+ if (signal?.aborted) {
1890
+ close();
1891
+ return;
1892
+ }
1893
+ signal?.addEventListener("abort", close, { once: true });
1171
1894
  const replayed = await self.getAgentToolChunks(runId, options);
1172
- for (const chunk of replayed) controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
1895
+ for (const chunk of replayed) {
1896
+ if (closed) return;
1897
+ controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
1898
+ }
1173
1899
  const lastReplay = replayed[replayed.length - 1]?.sequence;
1174
1900
  if (lastReplay !== void 0) self._agentToolLiveSequences.set(runId, lastReplay + 1);
1175
1901
  const row = self._readAgentToolChildRun(runId);
1176
1902
  if (!row || row.completed_at !== null) {
1177
- controller.close();
1903
+ close();
1178
1904
  return;
1179
1905
  }
1180
- const forward = (chunk) => {
1181
- if (chunk.sequence > (options?.afterSequence ?? -1)) controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
1182
- };
1183
- const close = () => {
1906
+ forward = (chunk) => {
1907
+ if (closed || chunk.sequence <= (options?.afterSequence ?? -1)) return;
1184
1908
  try {
1185
- controller.close();
1186
- } catch {}
1909
+ controller.enqueue(agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\n`));
1910
+ } catch {
1911
+ closed = true;
1912
+ detach();
1913
+ }
1187
1914
  };
1188
1915
  const forwarders = self._agentToolForwarders.get(runId) ?? /* @__PURE__ */ new Set();
1189
1916
  forwarders.add(forward);
@@ -1192,8 +1919,9 @@ var Think = class Think extends Agent {
1192
1919
  closers.add(close);
1193
1920
  self._agentToolClosers.set(runId, closers);
1194
1921
  },
1195
- cancel(reason) {
1196
- self.cancelAgentToolRun(runId, reason);
1922
+ cancel() {
1923
+ closed = true;
1924
+ detach();
1197
1925
  }
1198
1926
  });
1199
1927
  }
@@ -1213,9 +1941,18 @@ var Think = class Think extends Agent {
1213
1941
  return;
1214
1942
  }
1215
1943
  }
1944
+ /**
1945
+ * Whether the run produced an assistant turn (text or tool-only). Used by the
1946
+ * post-eviction reconcile to mark a settled run `completed` even when it ended
1947
+ * without final text. A dedicated child facet starts with no assistant
1948
+ * messages, so a missing in-memory pre-turn snapshot is treated as empty.
1949
+ */
1950
+ _hasRecoveredAgentToolAssistantTurn(runId) {
1951
+ const before = this._agentToolPreTurnAssistantIds.get(runId) ?? /* @__PURE__ */ new Set();
1952
+ return this.messages.some((msg) => msg.role === "assistant" && !before.has(msg.id));
1953
+ }
1216
1954
  _getAgentToolFinalText(runId) {
1217
- const before = this._agentToolPreTurnAssistantIds.get(runId);
1218
- if (!before) return null;
1955
+ const before = this._agentToolPreTurnAssistantIds.get(runId) ?? /* @__PURE__ */ new Set();
1219
1956
  for (const msg of this.messages) {
1220
1957
  if (msg.role !== "assistant" || before.has(msg.id)) continue;
1221
1958
  const text = msg.parts.map((part) => part.type === "text" ? part.text : "").filter((part) => part.length > 0).join("\n");
@@ -1223,6 +1960,255 @@ var Think = class Think extends Agent {
1223
1960
  }
1224
1961
  return null;
1225
1962
  }
1963
+ _ensureDeclaredScheduledTasksTable() {
1964
+ if (this._declaredScheduledTasksTableEnsured) return;
1965
+ this.sql`
1966
+ CREATE TABLE IF NOT EXISTS cf_think_scheduled_tasks (
1967
+ owner_key TEXT NOT NULL,
1968
+ task_id TEXT NOT NULL,
1969
+ schedule_hash TEXT NOT NULL,
1970
+ task_hash TEXT NOT NULL,
1971
+ schedule_id TEXT,
1972
+ next_run_at INTEGER,
1973
+ created_at INTEGER NOT NULL,
1974
+ updated_at INTEGER NOT NULL,
1975
+ PRIMARY KEY (owner_key, task_id)
1976
+ )
1977
+ `;
1978
+ this._declaredScheduledTasksTableEnsured = true;
1979
+ }
1980
+ _readDeclaredScheduledTaskRow(taskId) {
1981
+ this._ensureDeclaredScheduledTasksTable();
1982
+ const ownerKey = this._declaredScheduleOwnerKey();
1983
+ return this.sql`
1984
+ SELECT owner_key, task_id, schedule_hash, task_hash, schedule_id,
1985
+ next_run_at, created_at, updated_at
1986
+ FROM cf_think_scheduled_tasks
1987
+ WHERE task_id = ${taskId}
1988
+ AND owner_key = ${ownerKey}
1989
+ LIMIT 1
1990
+ `[0] ?? null;
1991
+ }
1992
+ _listDeclaredScheduledTaskRows() {
1993
+ this._ensureDeclaredScheduledTasksTable();
1994
+ const ownerKey = this._declaredScheduleOwnerKey();
1995
+ return this.sql`
1996
+ SELECT owner_key, task_id, schedule_hash, task_hash, schedule_id,
1997
+ next_run_at, created_at, updated_at
1998
+ FROM cf_think_scheduled_tasks
1999
+ WHERE owner_key = ${ownerKey}
2000
+ ORDER BY task_id ASC
2001
+ `;
2002
+ }
2003
+ _updateDeclaredScheduledTaskSchedule(task, ownerKey, scheduled, updatedAt = Date.now()) {
2004
+ this.sql`
2005
+ UPDATE cf_think_scheduled_tasks
2006
+ SET schedule_hash = ${task.scheduleHash},
2007
+ task_hash = ${task.taskHash},
2008
+ schedule_id = ${scheduled.scheduleId},
2009
+ next_run_at = ${scheduled.scheduledFor},
2010
+ updated_at = ${updatedAt}
2011
+ WHERE owner_key = ${ownerKey}
2012
+ AND task_id = ${task.taskId}
2013
+ `;
2014
+ }
2015
+ async _normalizeDeclaredScheduledTasks(tasks, defaultTimezone) {
2016
+ const normalized = /* @__PURE__ */ new Map();
2017
+ for (const [taskId, task] of Object.entries(tasks)) {
2018
+ if (!/^[A-Za-z0-9_-]+$/.test(taskId)) throw new Error(`Invalid scheduled task id "${taskId}"; use letters, numbers, "_" or "-"`);
2019
+ const schedule = parseDeclaredTaskSchedule(task.schedule, task.timezone, defaultTimezone);
2020
+ const hasPrompt = "prompt" in task && task.prompt !== void 0;
2021
+ const hasHandler = "handler" in task && task.handler !== void 0;
2022
+ if (hasPrompt === hasHandler) throw new Error(`Scheduled task "${taskId}" must define exactly one of prompt or handler`);
2023
+ const scheduleHash = stableHash({
2024
+ schedule,
2025
+ retry: task.retry
2026
+ });
2027
+ const taskHash = stableHash({
2028
+ scheduleHash,
2029
+ action: hasPrompt ? {
2030
+ type: "prompt",
2031
+ value: typeof task.prompt === "string" ? task.prompt : "<function>"
2032
+ } : { type: "handler" },
2033
+ metadata: task.metadata
2034
+ });
2035
+ normalized.set(taskId, {
2036
+ taskId,
2037
+ ...hasPrompt ? { prompt: task.prompt } : {},
2038
+ ...hasHandler ? { handler: task.handler } : {},
2039
+ schedule,
2040
+ retry: task.retry,
2041
+ metadata: task.metadata,
2042
+ scheduleHash,
2043
+ taskHash
2044
+ });
2045
+ }
2046
+ return normalized;
2047
+ }
2048
+ async _declaredScheduledTasksForNow() {
2049
+ const defaultTimezone = await this.getDefaultTimezone();
2050
+ const resolvedDefaultTimezone = defaultTimezone === void 0 ? void 0 : validateTimezone(defaultTimezone);
2051
+ return this._normalizeDeclaredScheduledTasks(await this.getScheduledTasks(), resolvedDefaultTimezone);
2052
+ }
2053
+ _declaredScheduleOwnerKey() {
2054
+ return stableHash(this.selfPath);
2055
+ }
2056
+ _declaredScheduleValidationError(rawSchedule, taskTimezone, defaultTimezone) {
2057
+ const result = tryParseDeclaredTaskSchedule(rawSchedule, taskTimezone, defaultTimezone === void 0 ? void 0 : validateTimezone(defaultTimezone));
2058
+ return result.ok ? null : result.error;
2059
+ }
2060
+ _nextDeclaredScheduleTimeForConfig(rawSchedule, now, options = {}) {
2061
+ const resolvedDefaultTimezone = options.defaultTimezone === void 0 ? void 0 : validateTimezone(options.defaultTimezone);
2062
+ return nextDeclaredScheduleTime(parseDeclaredTaskSchedule(rawSchedule, options.taskTimezone, resolvedDefaultTimezone), now, options.previousScheduledFor);
2063
+ }
2064
+ async _reconcileDeclaredScheduledTasks() {
2065
+ const tasks = await this._declaredScheduledTasksForNow();
2066
+ this._ensureDeclaredScheduledTasksTable();
2067
+ const ownerKey = this._declaredScheduleOwnerKey();
2068
+ const now = Date.now();
2069
+ const existing = this._listDeclaredScheduledTaskRows();
2070
+ const seen = /* @__PURE__ */ new Set();
2071
+ for (const [taskId, task] of tasks) {
2072
+ seen.add(taskId);
2073
+ const row = existing.find((candidate) => candidate.task_id === taskId);
2074
+ if (!row) {
2075
+ this.sql`
2076
+ INSERT INTO cf_think_scheduled_tasks (
2077
+ owner_key, task_id, schedule_hash, task_hash, schedule_id,
2078
+ next_run_at, created_at, updated_at
2079
+ )
2080
+ VALUES (
2081
+ ${ownerKey}, ${taskId}, ${task.scheduleHash}, ${task.taskHash},
2082
+ NULL, NULL, ${now}, ${now}
2083
+ )
2084
+ `;
2085
+ const scheduled = await this._scheduleDeclaredTaskOccurrence(task, new Date(now));
2086
+ this._updateDeclaredScheduledTaskSchedule(task, ownerKey, scheduled, now);
2087
+ continue;
2088
+ }
2089
+ if (row.schedule_hash !== task.scheduleHash) {
2090
+ if (row.schedule_id) await this.cancelSchedule(row.schedule_id);
2091
+ this.sql`
2092
+ UPDATE cf_think_scheduled_tasks
2093
+ SET schedule_hash = ${task.scheduleHash},
2094
+ task_hash = ${task.taskHash},
2095
+ schedule_id = NULL,
2096
+ next_run_at = NULL,
2097
+ updated_at = ${now}
2098
+ WHERE owner_key = ${ownerKey}
2099
+ AND task_id = ${taskId}
2100
+ `;
2101
+ const scheduled = await this._scheduleDeclaredTaskOccurrence(task, new Date(now));
2102
+ this._updateDeclaredScheduledTaskSchedule(task, ownerKey, scheduled, now);
2103
+ continue;
2104
+ }
2105
+ if (!row.schedule_id) {
2106
+ const scheduled = row.next_run_at === null ? await this._scheduleDeclaredTaskOccurrence(task, new Date(now)) : await this._scheduleDeclaredTaskOccurrenceAt(task, row.next_run_at);
2107
+ this._updateDeclaredScheduledTaskSchedule(task, ownerKey, scheduled, now);
2108
+ continue;
2109
+ }
2110
+ if (row.schedule_id) {
2111
+ if (!await this.getScheduleById(row.schedule_id)) {
2112
+ const scheduled = row.next_run_at === null ? await this._scheduleDeclaredTaskOccurrence(task, new Date(now)) : await this._scheduleDeclaredTaskOccurrenceAt(task, row.next_run_at);
2113
+ this._updateDeclaredScheduledTaskSchedule(task, ownerKey, scheduled, now);
2114
+ continue;
2115
+ }
2116
+ }
2117
+ if (row.task_hash !== task.taskHash) this.sql`
2118
+ UPDATE cf_think_scheduled_tasks
2119
+ SET task_hash = ${task.taskHash}, updated_at = ${now}
2120
+ WHERE owner_key = ${ownerKey}
2121
+ AND task_id = ${taskId}
2122
+ `;
2123
+ }
2124
+ for (const row of existing) {
2125
+ if (seen.has(row.task_id)) continue;
2126
+ if (row.schedule_id) await this.cancelSchedule(row.schedule_id);
2127
+ this.sql`
2128
+ DELETE FROM cf_think_scheduled_tasks
2129
+ WHERE owner_key = ${ownerKey}
2130
+ AND task_id = ${row.task_id}
2131
+ `;
2132
+ }
2133
+ }
2134
+ async _scheduleDeclaredTaskOccurrence(task, now, previousScheduledFor) {
2135
+ const next = nextDeclaredScheduleTime(task.schedule, now, previousScheduledFor);
2136
+ return this._scheduleDeclaredTaskOccurrenceAt(task, next.getTime());
2137
+ }
2138
+ async _scheduleDeclaredTaskOccurrenceAt(task, scheduledFor) {
2139
+ return {
2140
+ scheduleId: (await this.schedule(new Date(scheduledFor), "_runDeclaredScheduledTask", {
2141
+ taskId: task.taskId,
2142
+ scheduleHash: task.scheduleHash,
2143
+ scheduledFor
2144
+ }, { idempotent: true })).id,
2145
+ scheduledFor
2146
+ };
2147
+ }
2148
+ async _advanceDeclaredScheduledTask(task, payload, ownerKey) {
2149
+ const scheduled = await this._scheduleDeclaredTaskOccurrence(task, /* @__PURE__ */ new Date(), payload.scheduledFor);
2150
+ this._updateDeclaredScheduledTaskSchedule(task, ownerKey, scheduled);
2151
+ }
2152
+ _declaredScheduledTaskContext(task, payload, ownerKey) {
2153
+ const occurrenceKey = `${payload.taskId}:${payload.scheduledFor}`;
2154
+ return {
2155
+ taskId: payload.taskId,
2156
+ scheduledFor: payload.scheduledFor,
2157
+ scheduledForDate: new Date(payload.scheduledFor),
2158
+ occurrenceKey,
2159
+ idempotencyKey: `think-schedule:${ownerKey}:${occurrenceKey}`,
2160
+ schedule: task.schedule.normalizedSchedule,
2161
+ scheduleKind: task.schedule.kind,
2162
+ ...task.schedule.kind === "wall-clock" && { timezone: task.schedule.timezone },
2163
+ ...task.metadata !== void 0 && { metadata: task.metadata }
2164
+ };
2165
+ }
2166
+ async _runDeclaredScheduledTask(payload) {
2167
+ if (!payload || typeof payload.taskId !== "string" || typeof payload.scheduleHash !== "string" || typeof payload.scheduledFor !== "number") throw new Error("Invalid declared scheduled task payload");
2168
+ const row = this._readDeclaredScheduledTaskRow(payload.taskId);
2169
+ if (!row || row.schedule_hash !== payload.scheduleHash) return;
2170
+ if (row.next_run_at !== null && row.next_run_at > payload.scheduledFor) return;
2171
+ const task = (await this._declaredScheduledTasksForNow()).get(payload.taskId);
2172
+ if (!task || task.scheduleHash !== payload.scheduleHash) return;
2173
+ const ownerKey = this._declaredScheduleOwnerKey();
2174
+ const context = this._declaredScheduledTaskContext(task, payload, ownerKey);
2175
+ let actionError;
2176
+ try {
2177
+ await this.retry(async () => {
2178
+ if (task.prompt !== void 0) {
2179
+ const prompt = typeof task.prompt === "function" ? await task.prompt() : task.prompt;
2180
+ await this.submitMessages([{
2181
+ id: crypto.randomUUID(),
2182
+ role: "user",
2183
+ parts: [{
2184
+ type: "text",
2185
+ text: prompt
2186
+ }]
2187
+ }], {
2188
+ idempotencyKey: context.idempotencyKey,
2189
+ metadata: {
2190
+ ...task.metadata,
2191
+ source: "scheduled-task",
2192
+ ownerKey,
2193
+ taskId: payload.taskId,
2194
+ scheduledFor: payload.scheduledFor,
2195
+ schedule: task.schedule.normalizedSchedule
2196
+ }
2197
+ });
2198
+ } else await task.handler?.(context);
2199
+ }, task.retry);
2200
+ } catch (error) {
2201
+ actionError = error;
2202
+ } finally {
2203
+ await this._advanceDeclaredScheduledTask(task, payload, ownerKey);
2204
+ }
2205
+ if (actionError !== void 0) {
2206
+ console.error(`[Think] Scheduled task "${payload.taskId}" failed; next occurrence was still scheduled`, actionError);
2207
+ try {
2208
+ await this.onError(actionError);
2209
+ } catch {}
2210
+ }
2211
+ }
1226
2212
  _ensureSubmissionTable() {
1227
2213
  if (this._submissionTableEnsured) return;
1228
2214
  this.sql`
@@ -1255,6 +2241,34 @@ var Think = class Think extends Agent {
1255
2241
  `;
1256
2242
  this._submissionTableEnsured = true;
1257
2243
  }
2244
+ _ensureWorkflowNotificationTable() {
2245
+ if (this._workflowNotificationTableEnsured) return;
2246
+ this.sql`
2247
+ CREATE TABLE IF NOT EXISTS cf_think_workflow_notifications (
2248
+ notification_id TEXT PRIMARY KEY,
2249
+ submission_id TEXT NOT NULL,
2250
+ workflow_name TEXT NOT NULL,
2251
+ workflow_id TEXT NOT NULL,
2252
+ event_type TEXT NOT NULL,
2253
+ payload_json TEXT NOT NULL,
2254
+ attempts INTEGER NOT NULL DEFAULT 0,
2255
+ last_error TEXT,
2256
+ created_at INTEGER NOT NULL,
2257
+ updated_at INTEGER NOT NULL,
2258
+ delivered_at INTEGER
2259
+ )
2260
+ `;
2261
+ try {
2262
+ this.ctx.storage.sql.exec("ALTER TABLE cf_think_workflow_notifications ADD COLUMN delivered_at INTEGER");
2263
+ } catch (error) {
2264
+ if (!(error instanceof Error ? error.message : String(error)).toLowerCase().includes("duplicate column")) throw error;
2265
+ }
2266
+ this.sql`
2267
+ CREATE INDEX IF NOT EXISTS cf_think_workflow_notifications_created_idx
2268
+ ON cf_think_workflow_notifications (delivered_at, created_at, notification_id)
2269
+ `;
2270
+ this._workflowNotificationTableEnsured = true;
2271
+ }
1258
2272
  _readSubmission(submissionId) {
1259
2273
  this._ensureSubmissionTable();
1260
2274
  return this.sql`
@@ -1339,9 +2353,30 @@ var Think = class Think extends Agent {
1339
2353
  _serializeMetadata(metadata) {
1340
2354
  return metadata === void 0 ? null : JSON.stringify(metadata);
1341
2355
  }
1342
- async _emitSubmissionStatus(row) {
1343
- const inspection = this._inspectionFromSubmissionRow(row);
1344
- this._emit("submission:status", {
2356
+ _readWorkflowPromptContext(metadata) {
2357
+ const workflowPromptValue = metadata?.[THINK_WORKFLOW_PROMPT_METADATA_KEY];
2358
+ if (workflowPromptValue === null || typeof workflowPromptValue !== "object" || Array.isArray(workflowPromptValue)) return null;
2359
+ const workflowPrompt = workflowPromptValue;
2360
+ const workflowValue = workflowPrompt.workflow;
2361
+ if (workflowValue === null || typeof workflowValue !== "object" || Array.isArray(workflowValue)) return null;
2362
+ const workflowRecord = workflowValue;
2363
+ if (typeof workflowRecord.name !== "string" || typeof workflowRecord.id !== "string" || typeof workflowRecord.stepName !== "string" || typeof workflowRecord.eventType !== "string") return null;
2364
+ const output = workflowPrompt.output;
2365
+ const outputRecord = output !== null && typeof output === "object" && !Array.isArray(output) ? output : null;
2366
+ return {
2367
+ workflow: {
2368
+ name: workflowRecord.name,
2369
+ id: workflowRecord.id,
2370
+ stepName: workflowRecord.stepName,
2371
+ eventType: workflowRecord.eventType
2372
+ },
2373
+ ...outputRecord ? { output: { schema: outputRecord.schema } } : {},
2374
+ ...typeof workflowPrompt.fingerprint === "string" && { fingerprint: workflowPrompt.fingerprint }
2375
+ };
2376
+ }
2377
+ async _emitSubmissionStatus(row, output) {
2378
+ const inspection = this._inspectionFromSubmissionRow(row);
2379
+ this._emit("submission:status", {
1345
2380
  submissionId: inspection.submissionId,
1346
2381
  requestId: inspection.requestId,
1347
2382
  status: inspection.status
@@ -1351,6 +2386,7 @@ var Think = class Think extends Agent {
1351
2386
  requestId: inspection.requestId,
1352
2387
  error: inspection.error
1353
2388
  });
2389
+ if (this._isTerminalSubmissionStatus(inspection.status)) await this._enqueueWorkflowNotification(inspection, output);
1354
2390
  await this.keepAliveWhile(async () => {
1355
2391
  try {
1356
2392
  await this.onSubmissionStatus(inspection);
@@ -1360,6 +2396,136 @@ var Think = class Think extends Agent {
1360
2396
  });
1361
2397
  }
1362
2398
  onSubmissionStatus(_submission) {}
2399
+ async _enqueueWorkflowNotification(submission, output) {
2400
+ this._insertWorkflowNotification(submission, output);
2401
+ this._startWorkflowNotificationDrain();
2402
+ }
2403
+ _insertWorkflowNotification(submission, output, override) {
2404
+ const workflowPrompt = this._readWorkflowPromptContext(submission.metadata ?? null);
2405
+ if (!workflowPrompt) return false;
2406
+ this._ensureWorkflowNotificationTable();
2407
+ const now = Date.now();
2408
+ const status = override?.status ?? submission.status;
2409
+ const error = override?.error ?? submission.error;
2410
+ const payload = {
2411
+ submissionId: submission.submissionId,
2412
+ status,
2413
+ ...status === "completed" && { output },
2414
+ ...error && { error }
2415
+ };
2416
+ this.sql`
2417
+ INSERT OR IGNORE INTO cf_think_workflow_notifications (
2418
+ notification_id, submission_id, workflow_name, workflow_id, event_type,
2419
+ payload_json, attempts, last_error, created_at, updated_at, delivered_at
2420
+ )
2421
+ VALUES (
2422
+ ${`${submission.submissionId}:${workflowPrompt.workflow.eventType}`},
2423
+ ${submission.submissionId},
2424
+ ${workflowPrompt.workflow.name},
2425
+ ${workflowPrompt.workflow.id},
2426
+ ${workflowPrompt.workflow.eventType},
2427
+ ${JSON.stringify(payload)},
2428
+ 0,
2429
+ NULL,
2430
+ ${now},
2431
+ ${now},
2432
+ NULL
2433
+ )
2434
+ `;
2435
+ return true;
2436
+ }
2437
+ _recoverWorkflowNotifications() {
2438
+ this._ensureSubmissionTable();
2439
+ this._ensureWorkflowNotificationTable();
2440
+ const terminalRows = this.sql`
2441
+ SELECT submission_id, idempotency_key, request_id, stream_id, status,
2442
+ messages_json, metadata_json, error_message, created_at,
2443
+ messages_applied_at, started_at, completed_at
2444
+ FROM cf_think_submissions
2445
+ WHERE status IN ('aborted', 'skipped', 'error')
2446
+ ORDER BY completed_at DESC, created_at DESC
2447
+ LIMIT 100
2448
+ `;
2449
+ let recovered = false;
2450
+ for (const row of terminalRows) {
2451
+ const inspection = this._inspectionFromSubmissionRow(row);
2452
+ const workflowPrompt = this._readWorkflowPromptContext(inspection.metadata ?? null);
2453
+ if (!workflowPrompt) continue;
2454
+ const notificationId = `${inspection.submissionId}:${workflowPrompt.workflow.eventType}`;
2455
+ if (this.sql`
2456
+ SELECT notification_id
2457
+ FROM cf_think_workflow_notifications
2458
+ WHERE notification_id = ${notificationId}
2459
+ LIMIT 1
2460
+ `[0]) continue;
2461
+ recovered = this._insertWorkflowNotification(inspection) || recovered;
2462
+ }
2463
+ if (recovered) this._startWorkflowNotificationDrain();
2464
+ }
2465
+ _startWorkflowNotificationDrain() {
2466
+ this.keepAliveWhile(() => this._drainWorkflowNotifications()).catch((error) => {
2467
+ console.error("[Think] Failed to drain workflow notifications", error);
2468
+ this._scheduleWorkflowNotificationAlarm();
2469
+ });
2470
+ }
2471
+ async _drainWorkflowNotifications() {
2472
+ if (this._drainingWorkflowNotifications) return;
2473
+ this._ensureWorkflowNotificationTable();
2474
+ this._drainingWorkflowNotifications = true;
2475
+ try {
2476
+ const rows = this.sql`
2477
+ SELECT notification_id, submission_id, workflow_name, workflow_id,
2478
+ event_type, payload_json, attempts, last_error, created_at,
2479
+ updated_at, delivered_at
2480
+ FROM cf_think_workflow_notifications
2481
+ WHERE delivered_at IS NULL
2482
+ ORDER BY created_at ASC, notification_id ASC
2483
+ LIMIT 25
2484
+ `;
2485
+ for (const row of rows) try {
2486
+ const payload = JSON.parse(row.payload_json);
2487
+ await this.sendWorkflowEvent(row.workflow_name, row.workflow_id, {
2488
+ type: row.event_type,
2489
+ payload
2490
+ });
2491
+ this.sql`
2492
+ UPDATE cf_think_workflow_notifications
2493
+ SET payload_json = '{}',
2494
+ last_error = NULL,
2495
+ updated_at = ${Date.now()},
2496
+ delivered_at = ${Date.now()}
2497
+ WHERE notification_id = ${row.notification_id}
2498
+ AND delivered_at IS NULL
2499
+ `;
2500
+ } catch (error) {
2501
+ this.sql`
2502
+ UPDATE cf_think_workflow_notifications
2503
+ SET attempts = attempts + 1,
2504
+ last_error = ${error instanceof Error ? error.message : String(error)},
2505
+ updated_at = ${Date.now()}
2506
+ WHERE notification_id = ${row.notification_id}
2507
+ `;
2508
+ }
2509
+ } finally {
2510
+ this._drainingWorkflowNotifications = false;
2511
+ }
2512
+ await this._scheduleWorkflowNotificationAlarm();
2513
+ }
2514
+ async _scheduleWorkflowNotificationAlarm() {
2515
+ this._ensureWorkflowNotificationTable();
2516
+ const pending = this.sql`
2517
+ SELECT attempts
2518
+ FROM cf_think_workflow_notifications
2519
+ WHERE delivered_at IS NULL
2520
+ ORDER BY created_at ASC, notification_id ASC
2521
+ LIMIT 1
2522
+ `;
2523
+ if (!pending[0]) return;
2524
+ const delayMs = Math.min(300 * 1e3, 1e3 * 2 ** Math.min(pending[0].attempts, 8));
2525
+ const nextAlarm = Date.now() + delayMs;
2526
+ const existingAlarm = await this.ctx.storage.getAlarm();
2527
+ if (existingAlarm === null || existingAlarm > nextAlarm) await this.ctx.storage.setAlarm(nextAlarm);
2528
+ }
1363
2529
  async inspectSubmission(submissionId) {
1364
2530
  const row = this._readSubmission(submissionId);
1365
2531
  return row ? this._inspectionFromSubmissionRow(row) : null;
@@ -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
  }
@@ -2056,7 +3252,7 @@ var Think = class Think extends Agent {
2056
3252
  _handleStreamResumeRequest(connection) {
2057
3253
  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
3254
  else this._notifyStreamResuming(connection);
2059
- else if (this._continuation.pending !== null && this._continuation.pending.connectionId === connection.id) this._continuation.awaitingConnections.set(connection.id, connection);
3255
+ 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
3256
  else sendIfOpen(connection, JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));
2061
3257
  }
2062
3258
  async _handleStreamResumeAck(connection, requestId) {
@@ -2077,7 +3273,18 @@ var Think = class Think extends Agent {
2077
3273
  let rawParsed;
2078
3274
  try {
2079
3275
  rawParsed = JSON.parse(event.init.body);
2080
- } catch {
3276
+ } catch (error) {
3277
+ const wrapped = this.onChatError(error, {
3278
+ requestId: event.id,
3279
+ stage: "parse",
3280
+ messagesPersisted: false
3281
+ });
3282
+ this._emit("chat:request:failed", {
3283
+ requestId: event.id,
3284
+ stage: "parse",
3285
+ messagesPersisted: false,
3286
+ error: wrapped instanceof Error ? wrapped.message : String(wrapped)
3287
+ });
2081
3288
  return;
2082
3289
  }
2083
3290
  const { messages: incomingMessages, clientTools: rawClientTools, trigger: rawTrigger, ...customBody } = rawParsed;
@@ -2085,6 +3292,8 @@ var Think = class Think extends Agent {
2085
3292
  const isRegeneration = rawTrigger === "regenerate-message";
2086
3293
  const isSubmitMessage = !isRegeneration;
2087
3294
  const requestId = event.id;
3295
+ let messagesPersisted = false;
3296
+ let failureStage = "persist";
2088
3297
  const concurrencyDecision = this._getSubmitConcurrencyDecision(isSubmitMessage);
2089
3298
  if (concurrencyDecision.action === "drop") {
2090
3299
  this._rollbackDroppedSubmit(connection);
@@ -2134,6 +3343,8 @@ var Think = class Think extends Agent {
2134
3343
  }
2135
3344
  await this._syncMessages();
2136
3345
  this._broadcastMessages([connection.id]);
3346
+ messagesPersisted = true;
3347
+ failureStage = "turn";
2137
3348
  const abortSignal = this._aborts.getSignal(requestId);
2138
3349
  await this.keepAliveWhile(async () => {
2139
3350
  const turnPromise = this._turnQueue.enqueue(requestId, async () => {
@@ -2184,10 +3395,23 @@ var Think = class Think extends Agent {
2184
3395
  });
2185
3396
  });
2186
3397
  } catch (error) {
3398
+ const wrapped = this.onChatError(error, {
3399
+ requestId,
3400
+ stage: failureStage,
3401
+ messagesPersisted
3402
+ });
3403
+ const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
3404
+ this._emit("chat:request:failed", {
3405
+ requestId,
3406
+ stage: failureStage,
3407
+ messagesPersisted,
3408
+ error: errorMessage
3409
+ });
3410
+ await this._recordTerminalChatStatus("error", requestId, errorMessage);
2187
3411
  this._broadcastChat({
2188
3412
  type: MSG_CHAT_RESPONSE,
2189
3413
  id: requestId,
2190
- body: error instanceof Error ? error.message : "Error",
3414
+ body: errorMessage,
2191
3415
  done: true,
2192
3416
  error: true
2193
3417
  });
@@ -2219,6 +3443,7 @@ var Think = class Think extends Agent {
2219
3443
  }
2220
3444
  this._submitConcurrency.reset();
2221
3445
  this._pendingInteractionPromise = null;
3446
+ this._continuationBarrierActive = false;
2222
3447
  this._continuation.sendResumeNone();
2223
3448
  this._continuation.clearAll();
2224
3449
  }
@@ -2287,12 +3512,22 @@ var Think = class Think extends Agent {
2287
3512
  let doneSent = false;
2288
3513
  let streamError;
2289
3514
  let pendingRpcError;
3515
+ const stallTimeoutMs = this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
2290
3516
  try {
2291
3517
  this._insideInferenceLoop = true;
2292
- let chunksSinceFlush = 0;
2293
- let hasFlushedContent = false;
3518
+ const flushState = {
3519
+ chunksSinceFlush: 0,
3520
+ hasFlushedContent: false
3521
+ };
2294
3522
  try {
2295
- for await (const chunk of result.toUIMessageStream()) {
3523
+ const guardedStream = this._iterateWithStallWatchdog(result.toUIMessageStream(), stallTimeoutMs, () => {
3524
+ this._emit("chat:stream:stalled", {
3525
+ requestId,
3526
+ timeoutMs: stallTimeoutMs
3527
+ });
3528
+ this.abortRequest(requestId, /* @__PURE__ */ new Error("chat stream stalled: inactivity watchdog fired"));
3529
+ });
3530
+ for await (const chunk of guardedStream) {
2296
3531
  if (abortSignal?.aborted) {
2297
3532
  aborted = true;
2298
3533
  break;
@@ -2312,13 +3547,7 @@ var Think = class Think extends Agent {
2312
3547
  break;
2313
3548
  }
2314
3549
  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
- }
3550
+ await this._storeChunkDurably(streamId, streamChunk, chunkBody, flushState);
2322
3551
  this._broadcastChat({
2323
3552
  type: MSG_CHAT_RESPONSE,
2324
3553
  id: requestId,
@@ -2369,6 +3598,45 @@ var Think = class Think extends Agent {
2369
3598
  status: "aborted"
2370
3599
  });
2371
3600
  } catch (error) {
3601
+ if (error instanceof ChatStreamStalledError) {
3602
+ if (!assistantMsg && accumulator.parts.length > 0) {
3603
+ assistantMsg = accumulator.toMessage();
3604
+ await this._persistAssistantMessage(assistantMsg);
3605
+ this._broadcastMessages();
3606
+ }
3607
+ const outcome = await this._routeStallToBoundedRecovery({
3608
+ requestId,
3609
+ streamId,
3610
+ partialParts: (assistantMsg ?? accumulator.toMessage()).parts,
3611
+ targetAssistantId: assistantMsg?.id
3612
+ });
3613
+ if (outcome === "scheduled") {
3614
+ if (!streamFinalized) {
3615
+ this._resumableStream.complete(streamId);
3616
+ streamFinalized = true;
3617
+ }
3618
+ if (!doneSent) {
3619
+ this._broadcastChat({
3620
+ type: MSG_CHAT_RESPONSE,
3621
+ id: requestId,
3622
+ body: "",
3623
+ done: true
3624
+ });
3625
+ doneSent = true;
3626
+ }
3627
+ await callback.onInterrupted?.();
3628
+ return;
3629
+ }
3630
+ if (outcome === "exhausted") {
3631
+ if (!streamFinalized) {
3632
+ this._resumableStream.markError(streamId);
3633
+ streamFinalized = true;
3634
+ }
3635
+ doneSent = true;
3636
+ await callback.onInterrupted?.();
3637
+ return;
3638
+ }
3639
+ }
2372
3640
  if (!streamFinalized) {
2373
3641
  this._resumableStream.markError(streamId);
2374
3642
  streamFinalized = true;
@@ -2389,8 +3657,18 @@ var Think = class Think extends Agent {
2389
3657
  await this._persistAssistantMessage(assistantMsg);
2390
3658
  this._broadcastMessages();
2391
3659
  }
2392
- const wrapped = this.onChatError(error);
3660
+ const wrapped = this.onChatError(error, {
3661
+ requestId,
3662
+ stage: "stream",
3663
+ messagesPersisted: true
3664
+ });
2393
3665
  const errorMessage = wrapped instanceof Error ? wrapped.message : String(wrapped);
3666
+ this._emit("chat:request:failed", {
3667
+ requestId,
3668
+ stage: "stream",
3669
+ messagesPersisted: true,
3670
+ error: errorMessage
3671
+ });
2394
3672
  if (assistantMsg) await this._fireResponseHook({
2395
3673
  message: assistantMsg,
2396
3674
  requestId,
@@ -2398,14 +3676,87 @@ var Think = class Think extends Agent {
2398
3676
  status: "error",
2399
3677
  error: errorMessage
2400
3678
  });
2401
- if (callback.onError) await callback.onError(errorMessage);
2402
- else throw wrapped;
3679
+ await callback.onError(errorMessage);
2403
3680
  }
2404
- if (pendingRpcError) if (callback.onError) await callback.onError(pendingRpcError);
2405
- else throw new Error(pendingRpcError);
3681
+ if (pendingRpcError) await callback.onError(pendingRpcError);
3682
+ }
3683
+ /**
3684
+ * Whether storing this chunk should immediately flush the resumable-stream
3685
+ * buffer to SQLite.
3686
+ *
3687
+ * A settled tool result (`tool-output-available` / `tool-output-error` /
3688
+ * `tool-output-denied`) captures a completed, often non-idempotent side
3689
+ * effect — or, for a denial, a user decision — so it is flushed
3690
+ * **immediately**. An isolate eviction (deploy) before the next batch flush
3691
+ * would otherwise lose it, and recovery would re-anchor without it and re-run
3692
+ * the already-completed tool call (or drop the denial). Frequent recoverable
3693
+ * content (text / reasoning / tool-input streaming) is throttled to avoid
3694
+ * write amplification.
3695
+ */
3696
+ _shouldFlushRecoverableChunk(chunk, chunksSinceFlush, hasFlushedContent) {
3697
+ if (chunk.type === "tool-output-available" || chunk.type === "tool-output-error" || chunk.type === "tool-output-denied") return true;
3698
+ return (chunk.type === "text-delta" || chunk.type === "reasoning-delta" || chunk.type === "tool-input-available") && (!hasFlushedContent || chunksSinceFlush >= 10);
2406
3699
  }
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);
3700
+ /**
3701
+ * Store a stream chunk, flushing settled tool results durably and promptly.
3702
+ * Shared by the WebSocket and sub-agent RPC streaming paths so both get
3703
+ * tool-call-level recovery durability (recovery loses at most the in-flight
3704
+ * step, never an already-completed tool call).
3705
+ */
3706
+ async _storeChunkDurably(streamId, chunk, chunkBody, state) {
3707
+ this._resumableStream.storeChunk(streamId, chunkBody);
3708
+ state.chunksSinceFlush++;
3709
+ if (this._shouldFlushRecoverableChunk(chunk, state.chunksSinceFlush, state.hasFlushedContent)) {
3710
+ this._resumableStream.flushBuffer();
3711
+ state.chunksSinceFlush = 0;
3712
+ state.hasFlushedContent = true;
3713
+ await this._bumpChatRecoveryProgress();
3714
+ }
3715
+ }
3716
+ /**
3717
+ * Wrap a UI-message stream with an inactivity watchdog. If no chunk arrives
3718
+ * within `timeoutMs`, `onStall` runs (aborting the upstream model stream) and
3719
+ * the iterator throws, so the consumer loop exits with a terminal error
3720
+ * instead of parking forever on a hung provider/transport. `timeoutMs <= 0`
3721
+ * passes the source through untouched.
3722
+ */
3723
+ async *_iterateWithStallWatchdog(source, timeoutMs, onStall) {
3724
+ if (!(timeoutMs > 0)) {
3725
+ yield* source;
3726
+ return;
3727
+ }
3728
+ const iterator = source[Symbol.asyncIterator]();
3729
+ let selfAborted = false;
3730
+ try {
3731
+ while (true) {
3732
+ let timer;
3733
+ let stalled = false;
3734
+ const stall = new Promise((_, reject) => {
3735
+ timer = setTimeout(() => {
3736
+ stalled = true;
3737
+ reject(new ChatStreamStalledError(`Chat stream stalled: no activity for ${timeoutMs}ms; the turn was aborted by the stall watchdog.`));
3738
+ }, timeoutMs);
3739
+ });
3740
+ const nextPromise = iterator.next();
3741
+ nextPromise.catch(() => {});
3742
+ let next;
3743
+ try {
3744
+ next = await Promise.race([nextPromise, stall]);
3745
+ } catch (err) {
3746
+ if (stalled) {
3747
+ selfAborted = true;
3748
+ onStall();
3749
+ }
3750
+ throw err;
3751
+ } finally {
3752
+ if (timer !== void 0) clearTimeout(timer);
3753
+ }
3754
+ if (next.done) return;
3755
+ yield next.value;
3756
+ }
3757
+ } finally {
3758
+ if (!selfAborted) await iterator.return?.(void 0).catch(() => {});
3759
+ }
2409
3760
  }
2410
3761
  async _streamResult(requestId, result, abortSignal, options) {
2411
3762
  const clearGen = this._turnQueue.generation;
@@ -2420,15 +3771,30 @@ var Think = class Think extends Agent {
2420
3771
  let doneSent = false;
2421
3772
  let streamAborted = false;
2422
3773
  let streamError;
3774
+ let output;
3775
+ const flushState = {
3776
+ chunksSinceFlush: 0,
3777
+ hasFlushedContent: false
3778
+ };
3779
+ const stallTimeoutMs = this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;
2423
3780
  try {
2424
3781
  this._insideInferenceLoop = true;
2425
3782
  try {
2426
- for await (const chunk of result.toUIMessageStream()) {
3783
+ const guardedStream = this._iterateWithStallWatchdog(result.toUIMessageStream(), stallTimeoutMs, () => {
3784
+ this._emit("chat:stream:stalled", {
3785
+ requestId,
3786
+ timeoutMs: stallTimeoutMs
3787
+ });
3788
+ this.abortRequest(requestId, /* @__PURE__ */ new Error("chat stream stalled: inactivity watchdog fired"));
3789
+ });
3790
+ for await (const chunk of guardedStream) {
2427
3791
  if (abortSignal?.aborted) {
2428
3792
  streamAborted = true;
2429
3793
  break;
2430
3794
  }
2431
- const { action } = accumulator.applyChunk(chunk);
3795
+ const streamChunk = chunk;
3796
+ const { action } = accumulator.applyChunk(streamChunk);
3797
+ if (action?.type === "cross-message-tool-update") await this._applyToolUpdateToMessages(crossMessageToolResultUpdate(action.toolCallId, action.updateType, action.output, action.errorText, action.preliminary));
2432
3798
  if (action?.type === "error") {
2433
3799
  streamError = action.error;
2434
3800
  if (options?.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
@@ -2438,17 +3804,19 @@ var Think = class Think extends Agent {
2438
3804
  id: requestId,
2439
3805
  body: action.error,
2440
3806
  done: false,
2441
- error: true
3807
+ error: true,
3808
+ ...continuation && { continuation: true }
2442
3809
  });
2443
3810
  break;
2444
3811
  }
2445
3812
  const chunkBody = JSON.stringify(chunk);
2446
- this._resumableStream.storeChunk(streamId, chunkBody);
3813
+ await this._storeChunkDurably(streamId, streamChunk, chunkBody, flushState);
2447
3814
  this._broadcastChat({
2448
3815
  type: MSG_CHAT_RESPONSE,
2449
3816
  id: requestId,
2450
3817
  body: chunkBody,
2451
- done: false
3818
+ done: false,
3819
+ ...continuation && { continuation: true }
2452
3820
  });
2453
3821
  }
2454
3822
  } finally {
@@ -2461,10 +3829,47 @@ var Think = class Think extends Agent {
2461
3829
  type: MSG_CHAT_RESPONSE,
2462
3830
  id: requestId,
2463
3831
  body: "",
2464
- done: true
3832
+ done: true,
3833
+ ...continuation && { continuation: true }
2465
3834
  });
2466
3835
  doneSent = true;
2467
3836
  } catch (error) {
3837
+ if (error instanceof ChatStreamStalledError) {
3838
+ let targetAssistantId;
3839
+ const partialMsg = accumulator.toMessage();
3840
+ if (this._turnQueue.generation === clearGen && accumulator.parts.length > 0) {
3841
+ await this._persistAssistantMessage(partialMsg, parentId);
3842
+ this._broadcastMessages();
3843
+ targetAssistantId = partialMsg.id;
3844
+ }
3845
+ const outcome = await this._routeStallToBoundedRecovery({
3846
+ requestId,
3847
+ streamId,
3848
+ partialParts: partialMsg.parts,
3849
+ targetAssistantId
3850
+ });
3851
+ if (outcome === "scheduled") {
3852
+ this._resumableStream.complete(streamId);
3853
+ this._pendingResumeConnections.clear();
3854
+ if (!doneSent) {
3855
+ this._broadcastChat({
3856
+ type: MSG_CHAT_RESPONSE,
3857
+ id: requestId,
3858
+ body: "",
3859
+ done: true,
3860
+ ...continuation && { continuation: true }
3861
+ });
3862
+ doneSent = true;
3863
+ }
3864
+ return { status: "aborted" };
3865
+ }
3866
+ if (outcome === "exhausted") {
3867
+ this._resumableStream.markError(streamId);
3868
+ this._pendingResumeConnections.clear();
3869
+ doneSent = true;
3870
+ return { status: "aborted" };
3871
+ }
3872
+ }
2468
3873
  streamError = error instanceof Error ? error.message : "Stream error";
2469
3874
  if (options?.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
2470
3875
  this._resumableStream.markError(streamId);
@@ -2475,7 +3880,8 @@ var Think = class Think extends Agent {
2475
3880
  id: requestId,
2476
3881
  body: streamError,
2477
3882
  done: true,
2478
- error: true
3883
+ error: true,
3884
+ ...continuation && { continuation: true }
2479
3885
  });
2480
3886
  doneSent = true;
2481
3887
  }
@@ -2487,10 +3893,17 @@ var Think = class Think extends Agent {
2487
3893
  type: MSG_CHAT_RESPONSE,
2488
3894
  id: requestId,
2489
3895
  body: "",
2490
- done: true
3896
+ done: true,
3897
+ ...continuation && { continuation: true }
2491
3898
  });
2492
3899
  }
2493
3900
  }
3901
+ if (options?.captureOutput && result.output && !streamError && !streamAborted) try {
3902
+ output = await result.output;
3903
+ } catch (error) {
3904
+ streamError = error instanceof Error ? error.message : "Structured output error";
3905
+ if (options.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
3906
+ }
2494
3907
  if (this._turnQueue.generation === clearGen) try {
2495
3908
  const assistantMsg = accumulator.toMessage();
2496
3909
  if (accumulator.parts.length > 0) {
@@ -2510,7 +3923,10 @@ var Think = class Think extends Agent {
2510
3923
  return streamError ? {
2511
3924
  status: "error",
2512
3925
  error: streamError
2513
- } : { status: streamAborted ? "aborted" : "completed" };
3926
+ } : {
3927
+ status: streamAborted ? "aborted" : "completed",
3928
+ ...output !== void 0 && { output }
3929
+ };
2514
3930
  }
2515
3931
  async _persistAssistantMessage(msg, parentId) {
2516
3932
  await this._upsertMessageInHistory(msg, parentId);
@@ -2561,13 +3977,16 @@ var Think = class Think extends Agent {
2561
3977
  const history = await this._readMessagesFromStorage();
2562
3978
  for (let i = 0; i < history.length; i++) {
2563
3979
  const msg = history[i];
2564
- const result = applyToolUpdate(msg.parts, update);
3980
+ const msgParts = msg.parts;
3981
+ const result = applyToolUpdate(msgParts, update);
2565
3982
  if (result) {
3983
+ if (result.parts[result.index] === msgParts[result.index]) return;
2566
3984
  const updatedMsg = {
2567
3985
  ...msg,
2568
3986
  parts: result.parts
2569
3987
  };
2570
3988
  const safe = await this._updateMessageInHistory(updatedMsg);
3989
+ this._patchCachedMessage(safe);
2571
3990
  this._broadcast({
2572
3991
  type: MSG_MESSAGE_UPDATED,
2573
3992
  message: safe
@@ -2609,7 +4028,235 @@ var Think = class Think extends Agent {
2609
4028
  _messageHasPendingInteraction(message) {
2610
4029
  return message.parts.some((part) => "state" in part && (part.state === "input-available" || part.state === "approval-requested"));
2611
4030
  }
4031
+ _resolveChatRecoveryConfig() {
4032
+ const raw = this.chatRecovery;
4033
+ const custom = typeof raw === "object" ? raw : void 0;
4034
+ return {
4035
+ enabled: raw !== false,
4036
+ maxAttempts: Math.max(1, Math.floor(custom?.maxAttempts ?? DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS)),
4037
+ stableTimeoutMs: Math.max(0, Math.floor(custom?.stableTimeoutMs ?? DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS)),
4038
+ terminalMessage: custom?.terminalMessage ?? DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE,
4039
+ ...custom?.onExhausted ? { onExhausted: custom.onExhausted } : {}
4040
+ };
4041
+ }
4042
+ _chatRecoveryIncidentId(input) {
4043
+ return [input.recoveryRootRequestId ?? input.requestId, input.latestUserMessageId ?? ""].join(":");
4044
+ }
4045
+ _chatRecoveryIncidentKey(incidentId) {
4046
+ return `${CHAT_RECOVERY_INCIDENT_KEY_PREFIX}${encodeURIComponent(incidentId)}`;
4047
+ }
4048
+ /**
4049
+ * Monotonic forward-progress signal for recovery budget resets.
4050
+ *
4051
+ * This used to count assistant messages in `this.messages`, but that is
4052
+ * recomputed from the live, mutable transcript. Compaction collapses older
4053
+ * assistant messages into a summary, lowering the count — so a turn that had
4054
+ * genuinely advanced could read as "no progress" between attempts and exhaust
4055
+ * its budget prematurely (#1628). Instead we read a durably-persisted counter
4056
+ * that only ever increments — bumped at production time when new content is
4057
+ * durably flushed (see `_storeChunkDurably`), which is genuine forward
4058
+ * progress and is immune to client reconnects / recovery re-persists — so
4059
+ * compaction can never lower it and a reconnect can't fake it (#1637).
4060
+ */
4061
+ async _chatRecoveryProgressMarker() {
4062
+ return await this.ctx.storage.get(CHAT_RECOVERY_PROGRESS_KEY) ?? 0;
4063
+ }
4064
+ /** Advance the durable recovery-progress counter. Called from
4065
+ * `_storeChunkDurably` when new content is durably flushed (real, reconnect-
4066
+ * immune forward progress). */
4067
+ async _bumpChatRecoveryProgress() {
4068
+ const current = await this.ctx.storage.get(CHAT_RECOVERY_PROGRESS_KEY) ?? 0;
4069
+ await this.ctx.storage.put(CHAT_RECOVERY_PROGRESS_KEY, current + 1);
4070
+ }
4071
+ /**
4072
+ * N9: forwarding a sub-agent's chunks IS forward progress for this parent
4073
+ * turn, so credit the parent's recovery progress marker — otherwise a parent
4074
+ * whose turn merely `await`s a child banks no progress of its own and its
4075
+ * no-progress window exhausts while the child is healthily streaming. Only
4076
+ * invoked after a child actually produced output (see
4077
+ * `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.
4078
+ * Throttled (and reset per isolate) so we never write storage per token.
4079
+ */
4080
+ async _onAgentToolStreamProgress() {
4081
+ const now = Date.now();
4082
+ if (now - this._lastAgentToolStreamProgressAt < AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS) return;
4083
+ this._lastAgentToolStreamProgressAt = now;
4084
+ await this._bumpChatRecoveryProgress();
4085
+ }
4086
+ /** Sweep recovery incidents that have been inactive past the TTL. */
4087
+ async _sweepStaleChatRecoveryIncidents(now) {
4088
+ const entries = await this.ctx.storage.list({ prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX });
4089
+ const staleKeys = [];
4090
+ for (const [key, incident] of entries) if (now - (incident?.lastAttemptAt ?? incident?.firstSeenAt ?? 0) > CHAT_RECOVERY_INCIDENT_TTL_MS) staleKeys.push(key);
4091
+ for (const key of staleKeys) await this.ctx.storage.delete(key);
4092
+ }
4093
+ async _beginChatRecoveryIncident(input) {
4094
+ const config = this._resolveChatRecoveryConfig();
4095
+ const incidentId = this._chatRecoveryIncidentId(input);
4096
+ const key = this._chatRecoveryIncidentKey(incidentId);
4097
+ const now = input.nowMs ?? Date.now();
4098
+ await this._sweepStaleChatRecoveryIncidents(now);
4099
+ const existing = await this.ctx.storage.get(key);
4100
+ const prevProgress = existing?.progress ?? 0;
4101
+ const currentProgress = await this._chatRecoveryProgressMarker();
4102
+ const madeProgress = existing != null && currentProgress > prevProgress;
4103
+ const lastProgressAt = madeProgress ? now : existing?.lastProgressAt ?? existing?.firstSeenAt ?? now;
4104
+ const noProgressExceeded = existing != null && now - lastProgressAt > CHAT_RECOVERY_NO_PROGRESS_WINDOW_MS;
4105
+ const incidentAgeExceeded = existing != null && now - existing.firstSeenAt > CHAT_RECOVERY_MAX_WINDOW_MS;
4106
+ const debounced = existing != null && !madeProgress && now - existing.lastAttemptAt < CHAT_RECOVERY_ALARM_DEBOUNCE_MS;
4107
+ const attempt = madeProgress ? 1 : debounced ? existing?.attempt ?? 1 : (existing?.attempt ?? 0) + 1;
4108
+ const exhausted = noProgressExceeded || incidentAgeExceeded || attempt > config.maxAttempts;
4109
+ const incident = {
4110
+ incidentId,
4111
+ requestId: input.requestId,
4112
+ recoveryRootRequestId: input.recoveryRootRequestId ?? input.requestId,
4113
+ recoveryKind: input.recoveryKind,
4114
+ attempt,
4115
+ maxAttempts: config.maxAttempts,
4116
+ status: exhausted ? "exhausted" : "attempting",
4117
+ firstSeenAt: existing?.firstSeenAt ?? now,
4118
+ lastAttemptAt: now,
4119
+ lastProgressAt,
4120
+ progress: Math.max(prevProgress, currentProgress),
4121
+ ...exhausted ? { reason: incidentAgeExceeded ? "max_recovery_window_exceeded" : noProgressExceeded ? "no_progress_timeout" : "max_attempts_exceeded" } : {}
4122
+ };
4123
+ await this.ctx.storage.put(key, incident);
4124
+ if (!existing) this._emit("chat:recovery:detected", {
4125
+ incidentId,
4126
+ requestId: input.requestId,
4127
+ attempt,
4128
+ maxAttempts: config.maxAttempts,
4129
+ recoveryKind: input.recoveryKind
4130
+ });
4131
+ this._emit("chat:recovery:attempt", {
4132
+ incidentId,
4133
+ requestId: input.requestId,
4134
+ attempt,
4135
+ maxAttempts: config.maxAttempts,
4136
+ recoveryKind: input.recoveryKind
4137
+ });
4138
+ return {
4139
+ incident,
4140
+ config,
4141
+ exhausted
4142
+ };
4143
+ }
4144
+ async _updateChatRecoveryIncident(incidentId, status, reason) {
4145
+ if (!incidentId) return;
4146
+ const key = this._chatRecoveryIncidentKey(incidentId);
4147
+ const incident = await this.ctx.storage.get(key);
4148
+ if (!incident) return;
4149
+ if (status === "completed") await this.ctx.storage.delete(key);
4150
+ else await this.ctx.storage.put(key, {
4151
+ ...incident,
4152
+ status,
4153
+ ...reason ? { reason } : {}
4154
+ });
4155
+ const eventType = status === "completed" ? "chat:recovery:completed" : status === "skipped" ? "chat:recovery:skipped" : status === "failed" ? "chat:recovery:failed" : void 0;
4156
+ if (eventType) this._emit(eventType, {
4157
+ incidentId,
4158
+ requestId: incident.requestId,
4159
+ attempt: incident.attempt,
4160
+ maxAttempts: incident.maxAttempts,
4161
+ recoveryKind: incident.recoveryKind,
4162
+ ...reason ? { reason } : {}
4163
+ });
4164
+ if (status === "scheduled") await this._setChatRecovering(true, incident.recoveryRootRequestId ?? incident.requestId);
4165
+ else if (status === "completed" || status === "skipped" || status === "failed") await this._setChatRecovering(false);
4166
+ }
4167
+ async _exhaustChatRecovery(incident, config, partial, streamId, createdAt) {
4168
+ const ctx = {
4169
+ incidentId: incident.incidentId,
4170
+ requestId: incident.requestId,
4171
+ recoveryRootRequestId: incident.recoveryRootRequestId ?? incident.requestId,
4172
+ attempt: incident.attempt,
4173
+ maxAttempts: incident.maxAttempts,
4174
+ recoveryKind: incident.recoveryKind,
4175
+ streamId,
4176
+ createdAt,
4177
+ partialText: partial.text,
4178
+ partialParts: partial.parts,
4179
+ reason: incident.reason ?? "max_attempts_exceeded",
4180
+ terminalMessage: config.terminalMessage
4181
+ };
4182
+ this._emit("chat:recovery:exhausted", ctx);
4183
+ try {
4184
+ await config.onExhausted?.(ctx);
4185
+ } catch (error) {
4186
+ console.error("[Think] chatRecovery onExhausted hook threw", error);
4187
+ }
4188
+ await this._markRecoveredSubmissionInterrupted(incident.recoveryRootRequestId ?? incident.requestId, config.terminalMessage);
4189
+ await this._recordTerminalChatStatus("interrupted", incident.requestId, config.terminalMessage);
4190
+ this._broadcastChat({
4191
+ type: MSG_CHAT_RESPONSE,
4192
+ id: incident.requestId,
4193
+ body: config.terminalMessage,
4194
+ done: true,
4195
+ error: true
4196
+ });
4197
+ }
4198
+ /**
4199
+ * Route a stream-stall watchdog abort into bounded recovery instead of a
4200
+ * terminal error (#1626). A stall happens inside a LIVE isolate (no DO
4201
+ * restart), so the normal restart-detected recovery path never runs — we
4202
+ * open/advance a recovery incident here and schedule a continuation, reusing
4203
+ * the SAME budget (`maxAttempts` + wall-clock window + progress-aware reset)
4204
+ * as deploy/eviction recovery. A transient hang recovers; a persistently
4205
+ * hanging provider exhausts the budget. Idempotency matches deploy recovery:
4206
+ * settled tool results are durable and won't re-run, but a tool that was
4207
+ * mid-execution when the stall fired re-runs on the continuation.
4208
+ *
4209
+ * Returns:
4210
+ * - `"scheduled"` — a continuation was scheduled; the caller suppresses the
4211
+ * terminal error and closes the stream cleanly.
4212
+ * - `"exhausted"` — the budget is spent; this routes through the SAME
4213
+ * `_exhaustChatRecovery` path as deploy recovery (fires `onExhausted`,
4214
+ * emits `chat:recovery:exhausted`, marks the submission interrupted, and
4215
+ * delivers the configured `terminalMessage`). The caller must NOT run the
4216
+ * generic terminal path — the terminal UX is already delivered.
4217
+ * - `"disabled"` — chat recovery is off; the caller falls through to the
4218
+ * generic terminal error (the watchdog's original "kill the spinner"
4219
+ * behavior, unchanged).
4220
+ */
4221
+ async _routeStallToBoundedRecovery(input) {
4222
+ if (!this._resolveChatRecoveryConfig().enabled) return "disabled";
4223
+ const recoveryRootRequestId = this._activeChatRecoveryRootRequestId ?? input.requestId;
4224
+ const latestUserMessageId = [...this.messages].reverse().find((m) => m.role === "user")?.id ?? null;
4225
+ const { incident, config, exhausted } = await this._beginChatRecoveryIncident({
4226
+ requestId: input.requestId,
4227
+ recoveryRootRequestId,
4228
+ latestUserMessageId,
4229
+ recoveryKind: "continue"
4230
+ });
4231
+ if (exhausted) {
4232
+ const partialText = input.partialParts.filter((p) => p.type === "text").map((p) => p.text).join("");
4233
+ await this._exhaustChatRecovery(incident, config, {
4234
+ text: partialText,
4235
+ parts: input.partialParts
4236
+ }, input.streamId, incident.firstSeenAt);
4237
+ return "exhausted";
4238
+ }
4239
+ await this._updateChatRecoveryIncident(incident.incidentId, "scheduled");
4240
+ this._emit("chat:recovery:scheduled", {
4241
+ incidentId: incident.incidentId,
4242
+ requestId: input.requestId,
4243
+ attempt: incident.attempt,
4244
+ maxAttempts: incident.maxAttempts,
4245
+ recoveryKind: "continue"
4246
+ });
4247
+ const recoveredRequestId = this._hasRunningSubmission(recoveryRootRequestId) ? recoveryRootRequestId : void 0;
4248
+ await this.schedule(0, "_chatRecoveryContinue", {
4249
+ ...input.targetAssistantId ? { targetAssistantId: input.targetAssistantId } : {},
4250
+ originalRequestId: recoveryRootRequestId,
4251
+ incidentId: incident.incidentId,
4252
+ lastBody: this._lastBody ?? null,
4253
+ lastClientTools: this._lastClientTools ?? null,
4254
+ ...recoveredRequestId ? { recoveredRequestId } : {}
4255
+ }, { idempotent: true });
4256
+ return "scheduled";
4257
+ }
2612
4258
  async _handleInternalFiberRecovery(ctx) {
4259
+ if (await this._messengerRuntime?.handleFiberRecovery(ctx)) return true;
2613
4260
  const chatPrefix = this.constructor.CHAT_FIBER_NAME + ":";
2614
4261
  if (!ctx.name.startsWith(chatPrefix)) return false;
2615
4262
  const requestId = ctx.name.slice(chatPrefix.length);
@@ -2635,80 +4282,284 @@ var Think = class Think extends Agent {
2635
4282
  text: "",
2636
4283
  parts: []
2637
4284
  };
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
4285
  const streamStillActive = streamId && this._resumableStream.hasActiveStream() && this._resumableStream.activeStreamId === streamId;
2650
4286
  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
4287
  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;
4288
+ const recoveryKind = retryTargetUserId !== null && !streamIsTerminal ? "retry" : "continue";
4289
+ const recoveryRootRequestId = recoverySnapshot?.recoveryRootRequestId ?? requestId;
4290
+ const { incident, config, exhausted } = await this._beginChatRecoveryIncident({
4291
+ requestId,
4292
+ recoveryRootRequestId,
4293
+ latestUserMessageId: recoverySnapshot?.latestUserMessageId,
4294
+ recoveryKind
4295
+ });
4296
+ if (exhausted) {
4297
+ if (await this._shouldPersistOrphanedPartial(streamId, {
4298
+ streamStillActive: Boolean(streamStillActive),
4299
+ streamIsTerminal,
4300
+ snapshot: recoverySnapshot
4301
+ })) await this._persistOrphanedStream(streamId);
4302
+ await this._exhaustChatRecovery(incident, config, partial, streamId ?? "", ctx.createdAt);
4303
+ return true;
4304
+ }
4305
+ try {
4306
+ const options = await this.onChatRecovery({
4307
+ incidentId: incident.incidentId,
4308
+ recoveryRootRequestId,
4309
+ attempt: incident.attempt,
4310
+ maxAttempts: incident.maxAttempts,
4311
+ recoveryKind,
4312
+ streamId: streamId ?? "",
4313
+ requestId,
4314
+ partialText: partial.text,
4315
+ partialParts: partial.parts,
4316
+ recoveryData,
4317
+ messages: [...this.messages],
4318
+ lastBody: recoverySnapshot?.lastBody ?? this._lastBody,
4319
+ lastClientTools: recoverySnapshot?.lastClientTools ?? this._lastClientTools,
4320
+ createdAt: ctx.createdAt
4321
+ }) ?? {};
4322
+ if (await this._shouldPersistOrphanedPartial(streamId, {
4323
+ streamStillActive: Boolean(streamStillActive),
4324
+ streamIsTerminal,
4325
+ snapshot: recoverySnapshot
4326
+ }) && (options.persist !== false || this._partialHasSettledToolResults(partial.parts))) await this._persistOrphanedStream(streamId);
4327
+ if (streamStillActive) this._resumableStream.complete(streamId);
4328
+ const shouldRetry = retryTargetUserId !== null && options.continue !== false && !streamIsTerminal;
4329
+ const lastLeaf = shouldRetry ? null : await this.session.getLatestLeaf();
4330
+ const targetId = lastLeaf?.role === "assistant" && !streamIsTerminal ? lastLeaf.id : void 0;
4331
+ const canContinue = !shouldRetry && options.continue !== false && !streamIsTerminal;
4332
+ const hasRunningSubmission = this._hasRunningSubmission(recoveryRootRequestId);
4333
+ if (streamIsTerminal && hasRunningSubmission) await this._completeRecoveredSubmission(recoveryRootRequestId, streamStatus === "completed" ? "completed" : "error", requestId, streamStatus === "completed" ? null : "Recovered chat stream had already errored.");
4334
+ const recoveredRequestId = (canContinue || shouldRetry) && hasRunningSubmission ? recoveryRootRequestId : void 0;
4335
+ if (shouldRetry) {
4336
+ await this._updateChatRecoveryIncident(incident.incidentId, "scheduled");
4337
+ this._emit("chat:recovery:scheduled", {
4338
+ incidentId: incident.incidentId,
4339
+ requestId,
4340
+ attempt: incident.attempt,
4341
+ maxAttempts: incident.maxAttempts,
4342
+ recoveryKind
4343
+ });
4344
+ await this.schedule(0, "_chatRecoveryRetry", {
4345
+ targetUserId: retryTargetUserId,
4346
+ originalRequestId: recoveryRootRequestId,
4347
+ incidentId: incident.incidentId,
4348
+ lastBody: recoverySnapshot?.lastBody ?? null,
4349
+ lastClientTools: recoverySnapshot?.lastClientTools ?? null,
4350
+ ...recoveredRequestId ? { recoveredRequestId } : {}
4351
+ }, { idempotent: true });
4352
+ } else if (canContinue) {
4353
+ await this._updateChatRecoveryIncident(incident.incidentId, "scheduled");
4354
+ this._emit("chat:recovery:scheduled", {
4355
+ incidentId: incident.incidentId,
4356
+ requestId,
4357
+ attempt: incident.attempt,
4358
+ maxAttempts: incident.maxAttempts,
4359
+ recoveryKind
4360
+ });
4361
+ await this.schedule(0, "_chatRecoveryContinue", {
4362
+ ...targetId ? { targetAssistantId: targetId } : {},
4363
+ originalRequestId: recoveryRootRequestId,
4364
+ incidentId: incident.incidentId,
4365
+ ...recoverySnapshot ? {
4366
+ lastBody: recoverySnapshot.lastBody ?? null,
4367
+ lastClientTools: recoverySnapshot.lastClientTools ?? null
4368
+ } : {},
4369
+ ...recoveredRequestId ? { recoveredRequestId } : {}
4370
+ }, { idempotent: true });
4371
+ } else if (options.continue === false && !streamIsTerminal) {
4372
+ await this._updateChatRecoveryIncident(incident.incidentId, "skipped", "continue_disabled");
4373
+ const disabledMessage = "Submission was interrupted and chat recovery was disabled.";
4374
+ await this._markRecoveredSubmissionInterrupted(recoveryRootRequestId, disabledMessage);
4375
+ await this._recordTerminalChatStatus("interrupted", requestId, disabledMessage);
4376
+ this._broadcastChat({
4377
+ type: MSG_CHAT_RESPONSE,
4378
+ id: requestId,
4379
+ body: disabledMessage,
4380
+ done: true,
4381
+ error: true
4382
+ });
4383
+ } else await this._updateChatRecoveryIncident(incident.incidentId, "skipped", streamIsTerminal ? "stream_terminal" : "not_recoverable");
4384
+ return true;
4385
+ } catch (error) {
4386
+ await this._updateChatRecoveryIncident(incident.incidentId, "failed", error instanceof Error ? error.message : String(error));
4387
+ throw error;
4388
+ }
2680
4389
  }
2681
4390
  async _recoverablePreStreamUserId(snapshot, streamId, partial) {
2682
4391
  if (!snapshot || snapshot.continuation || !snapshot.latestUserMessageId || streamId || partial.text || partial.parts.length > 0) return null;
2683
4392
  const lastLeaf = await this.session.getLatestLeaf();
2684
4393
  return lastLeaf?.role === "user" && lastLeaf.id === snapshot.latestUserMessageId ? snapshot.latestUserMessageId : null;
2685
4394
  }
4395
+ async _hasPersistedRecoveredAssistant(snapshot) {
4396
+ const lastLeaf = await this.session.getLatestLeaf();
4397
+ return lastLeaf?.role === "assistant" && lastLeaf.id !== snapshot?.latestMessageId;
4398
+ }
4399
+ /**
4400
+ * Whether the orphaned stream's partial should be materialized into an
4401
+ * assistant message: there is a stream, and it is either still active or
4402
+ * terminal-but-not-yet-persisted. Shared by the normal recovery path AND the
4403
+ * exhaustion path so neither discards settled work nor duplicates a partial
4404
+ * an earlier attempt already saved.
4405
+ */
4406
+ async _shouldPersistOrphanedPartial(streamId, opts) {
4407
+ if (!streamId) return false;
4408
+ const alreadyPersisted = opts.streamIsTerminal && await this._hasPersistedRecoveredAssistant(opts.snapshot);
4409
+ return opts.streamStillActive || opts.streamIsTerminal && !alreadyPersisted;
4410
+ }
4411
+ /** Whether a reconstructed partial carries any settled (provider-accepted)
4412
+ * tool result — the completed, often non-idempotent work that a
4413
+ * `{ persist: false }` recovery return would silently discard. */
4414
+ _partialHasSettledToolResults(parts) {
4415
+ return parts.some((part) => {
4416
+ const record = part;
4417
+ const type = typeof record.type === "string" ? record.type : "";
4418
+ return (type.startsWith("tool-") || type === "dynamic-tool") && this._toolPartHasSettledResult(record);
4419
+ });
4420
+ }
4421
+ /**
4422
+ * Reschedule a recovery callback that timed out waiting for stable state,
4423
+ * consuming one attempt. Returns `true` if rescheduled, `false` if the
4424
+ * attempt budget is exhausted (the caller then fails the turn terminally).
4425
+ *
4426
+ * Shared by `_chatRecoveryRetry` and `_chatRecoveryContinue` so the
4427
+ * non-idempotent scheduling invariant lives in exactly one place — a fix to
4428
+ * one path can't silently diverge from the other. Mirrors the same helper in
4429
+ * `@cloudflare/ai-chat`.
4430
+ */
4431
+ async _rescheduleRecoveryAfterStableTimeout(callback, data, maxAttempts) {
4432
+ const incidentKey = data?.incidentId ? this._chatRecoveryIncidentKey(data.incidentId) : null;
4433
+ const incident = incidentKey ? await this.ctx.storage.get(incidentKey) : null;
4434
+ if (!incident || !incidentKey) return false;
4435
+ const attempt = incident.attempt ?? 0;
4436
+ if (attempt >= (incident.maxAttempts ?? maxAttempts)) return false;
4437
+ await this.ctx.storage.put(incidentKey, {
4438
+ ...incident,
4439
+ attempt: attempt + 1,
4440
+ status: "scheduled",
4441
+ lastAttemptAt: Date.now(),
4442
+ reason: "stable_timeout_retry"
4443
+ });
4444
+ await this.schedule(CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS, callback, data ?? {}, { idempotent: false });
4445
+ return true;
4446
+ }
4447
+ /**
4448
+ * Resolve the stream id for a recovery turn so the give-up terminalization
4449
+ * can surface whatever partial the turn produced. Prefers the durable stream
4450
+ * row keyed by the recovery-root request id; falls back to the live active
4451
+ * stream. Returns `""` when neither is available (the terminal banner still
4452
+ * fires — `_exhaustChatRecovery` does not require a stream).
4453
+ */
4454
+ _resolveRecoveryStreamId(requestId) {
4455
+ if (requestId) {
4456
+ const fromMetadata = this._resumableStream.getAllStreamMetadata().find((metadata) => metadata.request_id === requestId)?.id;
4457
+ if (fromMetadata) return fromMetadata;
4458
+ }
4459
+ return this._resumableStream.hasActiveStream() ? this._resumableStream.activeStreamId ?? "" : "";
4460
+ }
4461
+ /**
4462
+ * Terminalize a recovery turn that has run out of stable-state-timeout retry
4463
+ * budget — or whose incident record has vanished — by routing through the
4464
+ * SAME `_exhaustChatRecovery` path as deploy-recovery and stall exhaustion
4465
+ * (#1626/#1631). It fires `onExhausted`, emits `chat:recovery:exhausted`,
4466
+ * marks the durable submission interrupted, records the terminal chat status,
4467
+ * and delivers the configured `terminalMessage`.
4468
+ *
4469
+ * This replaces the older give-up that only set the incident to `failed` and
4470
+ * completed the recovered submission as `error`, which bypassed
4471
+ * `_exhaustChatRecovery` entirely — so an app relying on `onExhausted` for the
4472
+ * terminal banner regressed to an eternal spinner when recovery gave up under
4473
+ * extreme churn (the stable-state wait timing out every attempt until the
4474
+ * budget drained). Shared by `_chatRecoveryRetry` and `_chatRecoveryContinue`.
4475
+ *
4476
+ * Exactly-once terminalization is defended by two independent guards:
4477
+ * 1. The `stored?.status === "exhausted"` re-entry guard below — once an
4478
+ * incident is sealed, a duplicate stale alarm (or retried callback)
4479
+ * returns before re-firing. The sealed incident is re-persisted even when
4480
+ * the record was found missing, so a swept record is re-armed for the
4481
+ * guard on the next alarm.
4482
+ * 2. The durable-submission paths additionally short-circuit earlier at the
4483
+ * `submission_not_running` check (the submission is already `error` after
4484
+ * the first give-up). This is the ONLY guard `@cloudflare/ai-chat` lacks
4485
+ * (no submission layer), so guard #1 carries it there.
4486
+ *
4487
+ * Two residual at-least-once edges, both deliberately accepted as "deliver a
4488
+ * second banner" ≫ "silently drop the turn":
4489
+ * • No `incidentId` at all in the payload (only reachable via a direct/test
4490
+ * invocation — every production scheduler carries one): the synthesized
4491
+ * incident can't be persisted (no key), so guard #1 can't arm.
4492
+ * • The record is swept AGAIN between two alarms (guard #1 re-persists on the
4493
+ * first, so this needs a second independent sweep) — vanishingly unlikely.
4494
+ */
4495
+ async _exhaustRecoveryAfterStableTimeout(callback, data) {
4496
+ const config = this._resolveChatRecoveryConfig();
4497
+ const incidentKey = data?.incidentId ? this._chatRecoveryIncidentKey(data.incidentId) : null;
4498
+ const stored = incidentKey ? await this.ctx.storage.get(incidentKey) : null;
4499
+ if (stored?.status === "exhausted") return;
4500
+ const rootRequestId = data?.originalRequestId ?? data?.recoveredRequestId ?? this._activeChatRecoveryRootRequestId ?? stored?.recoveryRootRequestId ?? stored?.requestId ?? "";
4501
+ const incident = stored ? {
4502
+ ...stored,
4503
+ status: "exhausted",
4504
+ reason: "stable_timeout"
4505
+ } : {
4506
+ incidentId: data?.incidentId ?? crypto.randomUUID(),
4507
+ requestId: rootRequestId,
4508
+ recoveryRootRequestId: rootRequestId,
4509
+ recoveryKind: callback === "_chatRecoveryRetry" ? "retry" : "continue",
4510
+ attempt: config.maxAttempts,
4511
+ maxAttempts: config.maxAttempts,
4512
+ status: "exhausted",
4513
+ firstSeenAt: Date.now(),
4514
+ lastAttemptAt: Date.now(),
4515
+ reason: "stable_timeout"
4516
+ };
4517
+ if (incidentKey) await this.ctx.storage.put(incidentKey, incident);
4518
+ const streamId = this._resolveRecoveryStreamId(incident.recoveryRootRequestId ?? incident.requestId);
4519
+ const partial = streamId ? this._getPartialStreamText(streamId) : {
4520
+ text: "",
4521
+ parts: []
4522
+ };
4523
+ await this._exhaustChatRecovery(incident, config, partial, streamId, incident.firstSeenAt);
4524
+ }
2686
4525
  async _chatRecoveryRetry(data) {
2687
4526
  const recoveredSubmission = data?.recoveredRequestId ? this._readRunningSubmissionByRequestId(data.recoveredRequestId) : null;
2688
- if (data?.recoveredRequestId && !recoveredSubmission) return;
4527
+ if (data?.recoveredRequestId && !recoveredSubmission) {
4528
+ await this._updateChatRecoveryIncident(data.incidentId, "skipped", "submission_not_running");
4529
+ return;
4530
+ }
4531
+ const previousRootRequestId = this._activeChatRecoveryRootRequestId;
4532
+ this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
2689
4533
  const controller = recoveredSubmission ? new AbortController() : null;
2690
4534
  if (recoveredSubmission && controller) this._submissionAbortControllers.set(recoveredSubmission.submission_id, controller);
2691
4535
  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.");
4536
+ const recoveryConfig = this._resolveChatRecoveryConfig();
4537
+ if (!await this.waitUntilStable({ timeout: recoveryConfig.stableTimeoutMs })) {
4538
+ if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryRetry", data, recoveryConfig.maxAttempts)) return;
4539
+ await this._exhaustRecoveryAfterStableTimeout("_chatRecoveryRetry", data);
2694
4540
  return;
2695
4541
  }
2696
4542
  const lastLeaf = await this.session.getLatestLeaf();
2697
4543
  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.");
4544
+ await this._updateChatRecoveryIncident(data?.incidentId, "skipped", "no_unanswered_user_message");
4545
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "skipped", null, null);
2699
4546
  return;
2700
4547
  }
2701
4548
  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.");
4549
+ await this._updateChatRecoveryIncident(data?.incidentId, "skipped", "conversation_changed");
4550
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "skipped", null, null);
2703
4551
  return;
2704
4552
  }
2705
4553
  this._applyRecoveredRequestContext(data);
2706
4554
  const result = await this._retryLastUserTurn(this._lastClientTools, this._lastBody, controller ? { signal: controller.signal } : void 0);
4555
+ await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
2707
4556
  if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : result.error ?? `Recovery retry ${result.status}.`);
2708
4557
  } catch (error) {
4558
+ await this._updateChatRecoveryIncident(data?.incidentId, "failed", error instanceof Error ? error.message : String(error));
2709
4559
  if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, error instanceof Error ? error.message : String(error));
2710
4560
  throw error;
2711
4561
  } finally {
4562
+ this._activeChatRecoveryRootRequestId = previousRootRequestId;
2712
4563
  if (recoveredSubmission) this._submissionAbortControllers.delete(recoveredSubmission.submission_id);
2713
4564
  }
2714
4565
  }
@@ -2780,28 +4631,40 @@ var Think = class Think extends Agent {
2780
4631
  }
2781
4632
  async _chatRecoveryContinue(data) {
2782
4633
  const recoveredSubmission = data?.recoveredRequestId ? this._readRunningSubmissionByRequestId(data.recoveredRequestId) : null;
2783
- if (data?.recoveredRequestId && !recoveredSubmission) return;
4634
+ if (data?.recoveredRequestId && !recoveredSubmission) {
4635
+ await this._updateChatRecoveryIncident(data.incidentId, "skipped", "submission_not_running");
4636
+ return;
4637
+ }
4638
+ const previousRootRequestId = this._activeChatRecoveryRootRequestId;
4639
+ this._activeChatRecoveryRootRequestId = data?.originalRequestId ?? previousRootRequestId;
2784
4640
  const controller = recoveredSubmission ? new AbortController() : null;
2785
4641
  if (recoveredSubmission && controller) this._submissionAbortControllers.set(recoveredSubmission.submission_id, controller);
2786
4642
  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.");
4643
+ const recoveryConfig = this._resolveChatRecoveryConfig();
4644
+ if (!await this.waitUntilStable({ timeout: recoveryConfig.stableTimeoutMs })) {
4645
+ console.warn("[Think] _chatRecoveryContinue timed out waiting for stable state");
4646
+ if (await this._rescheduleRecoveryAfterStableTimeout("_chatRecoveryContinue", data, recoveryConfig.maxAttempts)) return;
4647
+ await this._exhaustRecoveryAfterStableTimeout("_chatRecoveryContinue", data);
2790
4648
  return;
2791
4649
  }
2792
4650
  const targetId = data?.targetAssistantId;
2793
4651
  const lastLeaf = await this.session.getLatestLeaf();
2794
4652
  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.");
4653
+ const supersededByNewerUserTurn = lastLeaf?.role === "user";
4654
+ await this._updateChatRecoveryIncident(data?.incidentId, "skipped", "conversation_changed");
4655
+ if (data?.recoveredRequestId && supersededByNewerUserTurn) await this._completeRecoveredSubmission(data.recoveredRequestId, "skipped", null, null);
2796
4656
  return;
2797
4657
  }
2798
4658
  this._applyRecoveredRequestContext(data);
2799
4659
  const result = await this.continueLastTurn(void 0, controller ? { signal: controller.signal } : void 0);
4660
+ await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
2800
4661
  if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : result.error ?? `Recovery ${result.status}.`);
2801
4662
  } catch (error) {
4663
+ await this._updateChatRecoveryIncident(data?.incidentId, "failed", error instanceof Error ? error.message : String(error));
2802
4664
  if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, error instanceof Error ? error.message : String(error));
2803
4665
  throw error;
2804
4666
  } finally {
4667
+ this._activeChatRecoveryRootRequestId = previousRootRequestId;
2805
4668
  if (recoveredSubmission) this._submissionAbortControllers.delete(recoveredSubmission.submission_id);
2806
4669
  }
2807
4670
  }
@@ -2865,30 +4728,116 @@ var Think = class Think extends Agent {
2865
4728
  this._continuation.pending.connectionId = connection.id;
2866
4729
  this._continuation.pending.clientTools = this._lastClientTools;
2867
4730
  this._continuation.awaitingConnections.set(connection.id, connection);
4731
+ this._resetAutoContinuationTimer();
2868
4732
  return;
2869
4733
  }
4734
+ this._continuation.pending = {
4735
+ connection,
4736
+ connectionId: connection.id,
4737
+ requestId: crypto.randomUUID(),
4738
+ clientTools: this._lastClientTools,
4739
+ body: void 0,
4740
+ errorPrefix: "[Think] Auto-continuation failed:",
4741
+ prerequisite: null,
4742
+ pastCoalesce: false
4743
+ };
4744
+ this._continuation.awaitingConnections.set(connection.id, connection);
4745
+ this._resetAutoContinuationTimer();
4746
+ }
4747
+ _resetAutoContinuationTimer() {
2870
4748
  if (this._continuationTimer) clearTimeout(this._continuationTimer);
2871
4749
  this._continuationTimer = setTimeout(() => {
2872
4750
  this._continuationTimer = null;
2873
- this._fireAutoContinuation(connection);
4751
+ const pending = this._continuation.pending;
4752
+ if (!pending) return;
4753
+ this._fireAutoContinuationWhenStable(pending.connection);
2874
4754
  }, 50);
2875
4755
  }
4756
+ /**
4757
+ * Fire an auto-continuation, but only once the model's parallel tool-call
4758
+ * batch is fully answered (#1649). When the model emits several tool calls in
4759
+ * one step the client answers each independently, so the first `autoContinue`
4760
+ * arrives while slower siblings are still `input-available`. Continuing then
4761
+ * would feed the provider an incomplete tool-result set
4762
+ * (`MissingToolResultsError`) or, via the transcript-repair backstop, silently
4763
+ * error the in-flight sibling and run a spurious extra continuation. We hold
4764
+ * the continuation on a barrier until the batch settles. The wait is bounded
4765
+ * (`AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS`) so a genuinely orphaned tool
4766
+ * call — e.g. the client disconnected mid-batch — still falls through to the
4767
+ * repair backstop rather than pinning the continuation open forever.
4768
+ */
4769
+ _fireAutoContinuationWhenStable(connection) {
4770
+ if (!this._continuation.pending) return;
4771
+ if (this._continuation.pending.pastCoalesce) return;
4772
+ if (this._continuationBarrierActive) return;
4773
+ if (!this._pendingInteractionPromise && !this._hasIncompleteToolBatch()) {
4774
+ this._fireAutoContinuation(connection);
4775
+ return;
4776
+ }
4777
+ this._continuationBarrierActive = true;
4778
+ this.keepAliveWhile(() => this._awaitToolBatch()).catch(() => {}).finally(() => {
4779
+ this._continuationBarrierActive = false;
4780
+ const pending = this._continuation.pending;
4781
+ if (pending) this._fireAutoContinuation(pending.connection);
4782
+ });
4783
+ }
4784
+ /**
4785
+ * Block until the latest assistant step's parallel tool batch is fully
4786
+ * answered, or `AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS` elapses. Awaits the
4787
+ * in-flight tool-result apply when one exists (so a sibling that lands
4788
+ * mid-wait is observed promptly) and polls otherwise.
4789
+ */
4790
+ async _awaitToolBatch() {
4791
+ const deadline = Date.now() + AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS;
4792
+ while (Date.now() < deadline) {
4793
+ if (!this._continuation.pending) return;
4794
+ const pending = this._pendingInteractionPromise;
4795
+ if (pending) {
4796
+ try {
4797
+ await pending;
4798
+ } catch {}
4799
+ continue;
4800
+ }
4801
+ if (!this._hasIncompleteToolBatch()) return;
4802
+ await new Promise((resolve) => setTimeout(resolve, 100));
4803
+ }
4804
+ console.warn(`[Think] Auto-continuation proceeding after waiting ${AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS}ms for unanswered parallel tool result(s) (#1649).`);
4805
+ }
4806
+ /**
4807
+ * `true` when the latest assistant message is mid-batch: it carries at least
4808
+ * one settled tool result AND at least one tool call/approval still awaiting a
4809
+ * client result. That is the #1649 signature — the model fanned out parallel
4810
+ * tool calls and only some have been answered. Scoped to the leaf (the step
4811
+ * the continuation answers) so an unrelated dangling tool in an earlier
4812
+ * message doesn't block a legitimate follow-up continuation.
4813
+ */
4814
+ _hasIncompleteToolBatch() {
4815
+ const messages = this.messages;
4816
+ let leaf;
4817
+ for (let i = messages.length - 1; i >= 0; i--) if (messages[i].role === "assistant") {
4818
+ leaf = messages[i];
4819
+ break;
4820
+ }
4821
+ if (!leaf) return false;
4822
+ let hasPending = false;
4823
+ let hasSettled = false;
4824
+ for (const part of leaf.parts) {
4825
+ const record = part;
4826
+ const state = record.state;
4827
+ if (state === "input-available" || state === "approval-requested") hasPending = true;
4828
+ 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;
4829
+ if (hasPending && hasSettled) return true;
4830
+ }
4831
+ return false;
4832
+ }
2876
4833
  _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);
4834
+ const pending = this._continuation.pending;
4835
+ if (!pending) return;
4836
+ if (this._continuationTimer) {
4837
+ clearTimeout(this._continuationTimer);
4838
+ this._continuationTimer = null;
2890
4839
  }
2891
- const { requestId, clientTools } = this._continuation.pending;
4840
+ const { requestId, clientTools } = pending;
2892
4841
  const abortSignal = this._aborts.getSignal(requestId);
2893
4842
  this.keepAliveWhile(async () => {
2894
4843
  await this._turnQueue.enqueue(requestId, async () => {
@@ -2929,9 +4878,10 @@ var Think = class Think extends Agent {
2929
4878
  _activateDeferredContinuation() {
2930
4879
  const pending = this._continuation.activateDeferred(() => crypto.randomUUID());
2931
4880
  if (!pending) return;
2932
- this._fireAutoContinuation(pending.connection);
4881
+ this._fireAutoContinuationWhenStable(pending.connection);
2933
4882
  }
2934
4883
  async _fireResponseHook(result) {
4884
+ await this._recordTerminalChatStatus(result.status, result.requestId, result.error ?? "The assistant was interrupted.");
2935
4885
  if (this._insideResponseHook) return;
2936
4886
  this._insideResponseHook = true;
2937
4887
  try {
@@ -2942,6 +4892,79 @@ var Think = class Think extends Agent {
2942
4892
  this._insideResponseHook = false;
2943
4893
  }
2944
4894
  }
4895
+ /**
4896
+ * Persist (on `error`) or clear (on `completed`/`aborted`) a durable record of
4897
+ * the last terminal turn so it can be replayed to clients on connect. A
4898
+ * `completed`/`aborted` turn is conveyed by the persisted messages, so the
4899
+ * record is cleared; an `error`/`interrupted` turn has no durable trace
4900
+ * otherwise, so it is kept until a later turn resolves.
4901
+ */
4902
+ async _recordTerminalChatStatus(status, requestId, body) {
4903
+ if (status === "error" || status === "interrupted") await this.ctx.storage.put(CHAT_LAST_TERMINAL_KEY, {
4904
+ requestId,
4905
+ body
4906
+ });
4907
+ else await this.ctx.storage.delete(CHAT_LAST_TERMINAL_KEY);
4908
+ await this._setChatRecovering(false);
4909
+ }
4910
+ async _pendingTerminalChatResponse() {
4911
+ return await this.ctx.storage.get(CHAT_LAST_TERMINAL_KEY) ?? null;
4912
+ }
4913
+ /**
4914
+ * Set or clear the live "recovering…" status for a durable chat turn (#1620).
4915
+ * Persists a durable record (replayed on connect via `_buildIdleConnectMessages`)
4916
+ * and broadcasts a `MSG_CHAT_RECOVERING` frame — but only on a genuine
4917
+ * transition, so a deploy/reconnect storm (which re-detects recovery many
4918
+ * times) doesn't spam the wire. Cleared on every terminal outcome so the
4919
+ * indicator can't spin forever.
4920
+ */
4921
+ async _setChatRecovering(active, requestId) {
4922
+ const existing = await this.ctx.storage.get(CHAT_RECOVERING_KEY);
4923
+ const activeExisting = existing && Date.now() - (existing.at ?? 0) < CHAT_RECOVERY_MAX_WINDOW_MS;
4924
+ if (active) {
4925
+ if (activeExisting) return;
4926
+ await this.ctx.storage.put(CHAT_RECOVERING_KEY, {
4927
+ ...requestId ? { requestId } : {},
4928
+ at: Date.now()
4929
+ });
4930
+ } else {
4931
+ if (!existing) return;
4932
+ await this.ctx.storage.delete(CHAT_RECOVERING_KEY);
4933
+ requestId = requestId ?? existing.requestId;
4934
+ }
4935
+ this._broadcastChat({
4936
+ type: MSG_CHAT_RECOVERING,
4937
+ recovering: active,
4938
+ ...requestId ? { id: requestId } : {}
4939
+ });
4940
+ }
4941
+ /**
4942
+ * Messages sent to a client on connect when no stream is active: the current
4943
+ * transcript, plus a replay of the last terminal error (if any) so a turn
4944
+ * that failed while the client was disconnected is surfaced rather than
4945
+ * silently frozen.
4946
+ */
4947
+ async _buildIdleConnectMessages() {
4948
+ const messages = [{
4949
+ type: MSG_CHAT_MESSAGES,
4950
+ messages: this.messages
4951
+ }];
4952
+ const pending = await this._pendingTerminalChatResponse();
4953
+ if (pending) messages.push({
4954
+ type: MSG_CHAT_RESPONSE,
4955
+ id: pending.requestId,
4956
+ body: pending.body,
4957
+ done: true,
4958
+ error: true
4959
+ });
4960
+ const recovering = await this.ctx.storage.get(CHAT_RECOVERING_KEY);
4961
+ if (recovering && Date.now() - (recovering.at ?? 0) < CHAT_RECOVERY_MAX_WINDOW_MS) messages.push({
4962
+ type: MSG_CHAT_RECOVERING,
4963
+ recovering: true,
4964
+ ...recovering.requestId ? { id: recovering.requestId } : {}
4965
+ });
4966
+ return messages;
4967
+ }
2945
4968
  _notifyStreamResuming(connection) {
2946
4969
  if (!this._resumableStream.hasActiveStream()) return;
2947
4970
  if (sendIfOpen(connection, JSON.stringify({
@@ -2979,12 +5002,13 @@ var Think = class Think extends Agent {
2979
5002
  Think.CONFIG_KEYS = [
2980
5003
  "_think_config",
2981
5004
  "lastClientTools",
2982
- "lastBody"
5005
+ "lastBody",
5006
+ "skillsFingerprint"
2983
5007
  ];
2984
5008
  Think.CHAT_FIBER_NAME = "__cf_internal_chat_turn";
2985
5009
  Think.MESSAGE_DEBOUNCE_MS = 750;
2986
5010
  Think.submissionRecoveryStaleMs = 900 * 1e3;
2987
5011
  //#endregion
2988
- export { Session, Think, Workspace };
5012
+ export { Session, Think, Workspace, defineScheduledTasks, skills };
2989
5013
 
2990
5014
  //# sourceMappingURL=think.js.map