@cloudflare/think 0.8.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/think.js CHANGED
@@ -1,11 +1,11 @@
1
- import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-BP1jgEfY.js";
1
+ import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-D_obpP6O.js";
2
2
  import { createWorkspaceTools } from "./tools/workspace.js";
3
- import { t as ThinkMessengerRuntime } from "./chat-sdk-CJwYlbp9.js";
3
+ import { t as ThinkMessengerRuntime } from "./chat-sdk-Bb93yaZh.js";
4
4
  import { Output, convertToModelMessages, jsonSchema, stepCountIs, streamText } from "ai";
5
5
  import * as skills from "agents/skills";
6
6
  import { SkillRegistry } from "agents/skills";
7
7
  import { Agent, __DO_NOT_USE_WILL_BREAK__agentContext } from "agents";
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";
8
+ import { AbortRegistry, CHAT_MESSAGE_TYPES, ContinuationState, ResumableStream, StreamAccumulator, SubmitConcurrencyController, TurnQueue, applyChunkToParts, applyToolUpdate, createChatFiberSnapshot, createToolsFromClientSchemas, crossMessageToolResultUpdate, enforceRowSizeLimit, normalizeToolInput, parseProtocolMessage, reconcileMessages, resolveToolMergeId, sanitizeMessage, toolApprovalUpdate, toolResultUpdate, unwrapChatFiberSnapshot, wrapChatFiberSnapshot } from "agents/chat";
9
9
  import { Session, Session as Session$1 } from "agents/experimental/memory/session";
10
10
  import { truncateOlderMessages } from "agents/experimental/memory/utils";
11
11
  import { Workspace, Workspace as Workspace$1 } from "@cloudflare/shell";
@@ -353,6 +353,8 @@ var Think = class Think extends Agent {
353
353
  this._insideResponseHook = false;
354
354
  this._insideInferenceLoop = false;
355
355
  this._pendingInteractionPromise = null;
356
+ this._interactionApplyTail = Promise.resolve();
357
+ this._streamingAssistant = null;
356
358
  this._submitConcurrency = new SubmitConcurrencyController({ defaultDebounceMs: Think.MESSAGE_DEBOUNCE_MS });
357
359
  this._agentToolForwarders = /* @__PURE__ */ new Map();
358
360
  this._agentToolClosers = /* @__PURE__ */ new Map();
@@ -412,8 +414,8 @@ var Think = class Think extends Agent {
412
414
  await this._reconcileDeclaredScheduledTasks();
413
415
  await this._recoverSubmissionsOnStart();
414
416
  this._recoverWorkflowNotifications();
415
- this._startSubmissionDrain();
416
- this._startWorkflowNotificationDrain();
417
+ if (this._hasPendingSubmissions()) this._startSubmissionDrain();
418
+ if (this._hasPendingWorkflowNotifications()) this._startWorkflowNotificationDrain();
417
419
  };
418
420
  }
419
421
  /**
@@ -434,37 +436,17 @@ var Think = class Think extends Agent {
434
436
  /**
435
437
  * Normalize a tool part's `input` into something the provider will accept.
436
438
  *
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.
439
+ * Malformed shapes 400 modern providers and persist forever once written:
440
+ * a stringified-JSON `input` (e.g. `'{"prompt":"a cat"}'` instead of the
441
+ * object), and any non-object `input` — `null`, `undefined`, `""`, an array,
442
+ * or a primitive — on a settled or interrupted tool call (Anthropic rejects
443
+ * a `tool_use` block whose `input` is not an object). We parse the former and
444
+ * default the latter to an empty object so the tool-call/tool-result pair
445
+ * stays valid. Delegates to the shared `normalizeToolInput` so the read-side
446
+ * repair and the write-side accumulator guard enforce the same invariant.
443
447
  */
444
448
  _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
- };
449
+ return normalizeToolInput("input" in record ? record.input : void 0);
468
450
  }
469
451
  /**
470
452
  * Whether a tool part already has a settled result the provider accepts, so
@@ -1130,8 +1112,8 @@ var Think = class Think extends Agent {
1130
1112
  return error;
1131
1113
  }
1132
1114
  async _initializeExtensions() {
1133
- const { ExtensionManager } = await import("./manager-px912SoZ.js").then((n) => n.n);
1134
- const { sanitizeName } = await import("./manager-px912SoZ.js").then((n) => n.n);
1115
+ const { ExtensionManager } = await import("./manager-DnCkoyVo.js").then((n) => n.n);
1116
+ const { sanitizeName } = await import("./manager-DnCkoyVo.js").then((n) => n.n);
1135
1117
  const agentClassName = this.constructor.name;
1136
1118
  const agentId = this.ctx.id.toString();
1137
1119
  const ctxExports = this.ctx.exports;
@@ -1317,7 +1299,7 @@ var Think = class Think extends Agent {
1317
1299
  if (!this.extensionManager) return subclassConfig;
1318
1300
  const subscribers = this.extensionManager.getHookSubscribers("beforeTurn");
1319
1301
  if (subscribers.length === 0) return subclassConfig;
1320
- const { createTurnContextSnapshot, parseHookResult } = await import("./hook-proxy-DHwqL8MV.js");
1302
+ const { createTurnContextSnapshot, parseHookResult } = await import("./hook-proxy-CkF0EhRO.js");
1321
1303
  let snapshot = createTurnContextSnapshot(ctx);
1322
1304
  let accumulated = { ...subclassConfig };
1323
1305
  if (accumulated.system !== void 0) snapshot.system = accumulated.system;
@@ -1488,25 +1470,25 @@ var Think = class Think extends Agent {
1488
1470
  async _pipelineExtensionToolCallStart(event) {
1489
1471
  if (!this.extensionManager) return;
1490
1472
  if (this.extensionManager.getHookSubscribers("beforeToolCall").length === 0) return;
1491
- const { createToolCallStartSnapshot } = await import("./hook-proxy-DHwqL8MV.js");
1473
+ const { createToolCallStartSnapshot } = await import("./hook-proxy-CkF0EhRO.js");
1492
1474
  await this._dispatchExtensionObservation("beforeToolCall", createToolCallStartSnapshot(event));
1493
1475
  }
1494
1476
  async _pipelineExtensionToolCallFinish(event) {
1495
1477
  if (!this.extensionManager) return;
1496
1478
  if (this.extensionManager.getHookSubscribers("afterToolCall").length === 0) return;
1497
- const { createToolCallFinishSnapshot } = await import("./hook-proxy-DHwqL8MV.js");
1479
+ const { createToolCallFinishSnapshot } = await import("./hook-proxy-CkF0EhRO.js");
1498
1480
  await this._dispatchExtensionObservation("afterToolCall", createToolCallFinishSnapshot(event));
1499
1481
  }
1500
1482
  async _pipelineExtensionStepFinish(event) {
1501
1483
  if (!this.extensionManager) return;
1502
1484
  if (this.extensionManager.getHookSubscribers("onStepFinish").length === 0) return;
1503
- const { createStepFinishSnapshot } = await import("./hook-proxy-DHwqL8MV.js");
1485
+ const { createStepFinishSnapshot } = await import("./hook-proxy-CkF0EhRO.js");
1504
1486
  await this._dispatchExtensionObservation("onStepFinish", createStepFinishSnapshot(event));
1505
1487
  }
1506
1488
  async _pipelineExtensionChunk(event) {
1507
1489
  if (!this.extensionManager) return;
1508
1490
  if (this.extensionManager.getHookSubscribers("onChunk").length === 0) return;
1509
- const { createChunkSnapshot } = await import("./hook-proxy-DHwqL8MV.js");
1491
+ const { createChunkSnapshot } = await import("./hook-proxy-CkF0EhRO.js");
1510
1492
  await this._dispatchExtensionObservation("onChunk", createChunkSnapshot(event));
1511
1493
  }
1512
1494
  async _hostReadFile(path) {
@@ -2468,6 +2450,15 @@ var Think = class Think extends Agent {
2468
2450
  this._scheduleWorkflowNotificationAlarm();
2469
2451
  });
2470
2452
  }
2453
+ _hasPendingWorkflowNotifications() {
2454
+ this._ensureWorkflowNotificationTable();
2455
+ return this.sql`
2456
+ SELECT notification_id
2457
+ FROM cf_think_workflow_notifications
2458
+ WHERE delivered_at IS NULL
2459
+ LIMIT 1
2460
+ `.length > 0;
2461
+ }
2471
2462
  async _drainWorkflowNotifications() {
2472
2463
  if (this._drainingWorkflowNotifications) return;
2473
2464
  this._ensureWorkflowNotificationTable();
@@ -2668,6 +2659,15 @@ var Think = class Think extends Agent {
2668
2659
  console.error("[Think] Failed to drain submissions", error);
2669
2660
  });
2670
2661
  }
2662
+ _hasPendingSubmissions() {
2663
+ this._ensureSubmissionTable();
2664
+ return this.sql`
2665
+ SELECT submission_id
2666
+ FROM cf_think_submissions
2667
+ WHERE status = 'pending'
2668
+ LIMIT 1
2669
+ `.length > 0;
2670
+ }
2671
2671
  async _drainThinkSubmissions() {
2672
2672
  await this._drainSubmissions();
2673
2673
  }
@@ -3212,34 +3212,18 @@ var Think = class Think extends Agent {
3212
3212
  case "chat-request":
3213
3213
  if (event.init?.method === "POST") await this._handleChatRequest(connection, event);
3214
3214
  break;
3215
- case "tool-result": {
3215
+ case "tool-result":
3216
3216
  if (event.clientTools && Array.isArray(event.clientTools) && event.clientTools.length > 0) {
3217
3217
  this._lastClientTools = event.clientTools;
3218
3218
  this._persistClientTools();
3219
3219
  }
3220
- const resultPromise = Promise.resolve().then(async () => {
3221
- await this._applyToolResult(event.toolCallId, event.output, event.state, event.errorText);
3222
- return true;
3223
- });
3224
- this._pendingInteractionPromise = resultPromise;
3225
- resultPromise.finally(() => {
3226
- if (this._pendingInteractionPromise === resultPromise) this._pendingInteractionPromise = null;
3227
- }).catch(() => {});
3220
+ this._enqueueInteractionApply(() => this._applyToolResult(event.toolCallId, event.output, event.state, event.errorText));
3228
3221
  if (event.autoContinue) this._scheduleAutoContinuation(connection);
3229
3222
  break;
3230
- }
3231
- case "tool-approval": {
3232
- const approvalPromise = Promise.resolve().then(async () => {
3233
- await this._applyToolApproval(event.toolCallId, event.approved);
3234
- return true;
3235
- });
3236
- this._pendingInteractionPromise = approvalPromise;
3237
- approvalPromise.finally(() => {
3238
- if (this._pendingInteractionPromise === approvalPromise) this._pendingInteractionPromise = null;
3239
- }).catch(() => {});
3223
+ case "tool-approval":
3224
+ this._enqueueInteractionApply(() => this._applyToolApproval(event.toolCallId, event.approved));
3240
3225
  if (event.autoContinue) this._scheduleAutoContinuation(connection);
3241
3226
  break;
3242
- }
3243
3227
  case "clear":
3244
3228
  await this._handleClear(connection);
3245
3229
  break;
@@ -3443,6 +3427,8 @@ var Think = class Think extends Agent {
3443
3427
  }
3444
3428
  this._submitConcurrency.reset();
3445
3429
  this._pendingInteractionPromise = null;
3430
+ this._interactionApplyTail = Promise.resolve();
3431
+ this._streamingAssistant = null;
3446
3432
  this._continuationBarrierActive = false;
3447
3433
  this._continuation.sendResumeNone();
3448
3434
  this._continuation.clearAll();
@@ -3506,6 +3492,7 @@ var Think = class Think extends Agent {
3506
3492
  async _streamResultToRpcCallback(requestId, result, callback, abortSignal) {
3507
3493
  const streamId = this._resumableStream.start(requestId);
3508
3494
  const accumulator = new StreamAccumulator({ messageId: crypto.randomUUID() });
3495
+ this._streamingAssistant = accumulator;
3509
3496
  let streamFinalized = false;
3510
3497
  let assistantMsg = null;
3511
3498
  let aborted = false;
@@ -3537,6 +3524,12 @@ var Think = class Think extends Agent {
3537
3524
  if (action?.type === "error") {
3538
3525
  streamError = action.error;
3539
3526
  this._emit("message:error", { error: streamError });
3527
+ this._emit("chat:request:failed", {
3528
+ requestId,
3529
+ stage: "stream",
3530
+ messagesPersisted: true,
3531
+ error: streamError
3532
+ });
3540
3533
  this._broadcastChat({
3541
3534
  type: MSG_CHAT_RESPONSE,
3542
3535
  id: requestId,
@@ -3677,6 +3670,8 @@ var Think = class Think extends Agent {
3677
3670
  error: errorMessage
3678
3671
  });
3679
3672
  await callback.onError(errorMessage);
3673
+ } finally {
3674
+ this._streamingAssistant = null;
3680
3675
  }
3681
3676
  if (pendingRpcError) await callback.onError(pendingRpcError);
3682
3677
  }
@@ -3768,6 +3763,7 @@ var Think = class Think extends Agent {
3768
3763
  this._continuation.flushAwaitingConnections((c) => this._notifyStreamResuming(c));
3769
3764
  }
3770
3765
  const accumulator = new StreamAccumulator({ messageId: crypto.randomUUID() });
3766
+ this._streamingAssistant = accumulator;
3771
3767
  let doneSent = false;
3772
3768
  let streamAborted = false;
3773
3769
  let streamError;
@@ -3799,6 +3795,12 @@ var Think = class Think extends Agent {
3799
3795
  streamError = action.error;
3800
3796
  if (options?.captureProgrammaticStreamError) this._programmaticStreamErrors.set(requestId, streamError);
3801
3797
  this._emit("message:error", { error: streamError });
3798
+ this._emit("chat:request:failed", {
3799
+ requestId,
3800
+ stage: "stream",
3801
+ messagesPersisted: true,
3802
+ error: streamError
3803
+ });
3802
3804
  this._broadcastChat({
3803
3805
  type: MSG_CHAT_RESPONSE,
3804
3806
  id: requestId,
@@ -3861,12 +3863,14 @@ var Think = class Think extends Agent {
3861
3863
  });
3862
3864
  doneSent = true;
3863
3865
  }
3866
+ this._streamingAssistant = null;
3864
3867
  return { status: "aborted" };
3865
3868
  }
3866
3869
  if (outcome === "exhausted") {
3867
3870
  this._resumableStream.markError(streamId);
3868
3871
  this._pendingResumeConnections.clear();
3869
3872
  doneSent = true;
3873
+ this._streamingAssistant = null;
3870
3874
  return { status: "aborted" };
3871
3875
  }
3872
3876
  }
@@ -3920,6 +3924,7 @@ var Think = class Think extends Agent {
3920
3924
  } catch (e) {
3921
3925
  console.error("Failed to persist assistant message:", e);
3922
3926
  }
3927
+ this._streamingAssistant = null;
3923
3928
  return streamError ? {
3924
3929
  status: "error",
3925
3930
  error: streamError
@@ -3965,6 +3970,37 @@ var Think = class Think extends Agent {
3965
3970
  this._lastBody = void 0;
3966
3971
  }
3967
3972
  }
3973
+ /**
3974
+ * Serialize a client-tool result/approval apply behind any in-flight apply
3975
+ * (#1649). Parallel tool results arrive as independent WebSocket messages,
3976
+ * and each apply is a read-modify-write of the full message in durable
3977
+ * storage. Running them concurrently means every apply reads the same
3978
+ * snapshot (all siblings still `input-available`), patches only its own part,
3979
+ * and writes the whole message back — so the last write clobbers the others
3980
+ * back to `input-available`, and the auto-continuation barrier later times
3981
+ * out and the transcript-repair backstop errors the lost siblings.
3982
+ *
3983
+ * Chaining each apply off `_interactionApplyTail` makes the read-modify-write
3984
+ * atomic per result and in arrival order. `_pendingInteractionPromise` is set
3985
+ * to the newest link so the barrier's single-slot wake-up still observes the
3986
+ * latest apply; because the chain is serial, awaiting it transitively waits
3987
+ * for every predecessor.
3988
+ *
3989
+ * @internal
3990
+ */
3991
+ _enqueueInteractionApply(apply) {
3992
+ const run = async () => {
3993
+ await apply();
3994
+ return true;
3995
+ };
3996
+ const resultPromise = this._interactionApplyTail.then(run, run);
3997
+ this._interactionApplyTail = resultPromise.then(() => void 0, () => void 0);
3998
+ this._pendingInteractionPromise = resultPromise;
3999
+ resultPromise.finally(() => {
4000
+ if (this._pendingInteractionPromise === resultPromise) this._pendingInteractionPromise = null;
4001
+ }).catch(() => {});
4002
+ return resultPromise;
4003
+ }
3968
4004
  async _applyToolResult(toolCallId, output, overrideState, errorText) {
3969
4005
  const update = toolResultUpdate(toolCallId, output, overrideState, errorText);
3970
4006
  await this._applyToolUpdateToMessages(update);
@@ -3974,29 +4010,41 @@ var Think = class Think extends Agent {
3974
4010
  await this._applyToolUpdateToMessages(update);
3975
4011
  }
3976
4012
  async _applyToolUpdateToMessages(update) {
4013
+ let broadcastMessage;
4014
+ const streaming = this._streamingAssistant;
4015
+ if (streaming) {
4016
+ const accParts = streaming.parts;
4017
+ const result = applyToolUpdate(accParts, update);
4018
+ if (result && result.parts[result.index] !== accParts[result.index]) {
4019
+ accParts[result.index] = result.parts[result.index];
4020
+ broadcastMessage = streaming.toMessage();
4021
+ }
4022
+ }
3977
4023
  const history = await this._readMessagesFromStorage();
3978
4024
  for (let i = 0; i < history.length; i++) {
3979
4025
  const msg = history[i];
3980
4026
  const msgParts = msg.parts;
3981
4027
  const result = applyToolUpdate(msgParts, update);
3982
4028
  if (result) {
3983
- if (result.parts[result.index] === msgParts[result.index]) return;
4029
+ if (result.parts[result.index] === msgParts[result.index]) break;
3984
4030
  const updatedMsg = {
3985
4031
  ...msg,
3986
4032
  parts: result.parts
3987
4033
  };
3988
4034
  const safe = await this._updateMessageInHistory(updatedMsg);
3989
4035
  this._patchCachedMessage(safe);
3990
- this._broadcast({
3991
- type: MSG_MESSAGE_UPDATED,
3992
- message: safe
3993
- });
3994
- return;
4036
+ broadcastMessage = safe;
4037
+ break;
3995
4038
  }
3996
4039
  }
4040
+ if (broadcastMessage) this._broadcast({
4041
+ type: MSG_MESSAGE_UPDATED,
4042
+ message: broadcastMessage
4043
+ });
3997
4044
  }
3998
4045
  hasPendingInteraction() {
3999
- return this.messages.some((message) => message.role === "assistant" && this._messageHasPendingInteraction(message));
4046
+ const clientResolvable = this._clientResolvableToolNames();
4047
+ return this.messages.some((message) => message.role === "assistant" && this._messageHasPendingInteraction(message, clientResolvable));
4000
4048
  }
4001
4049
  async waitUntilStable(options) {
4002
4050
  const deadline = options?.timeout != null ? Date.now() + options.timeout : null;
@@ -4025,8 +4073,56 @@ var Think = class Think extends Agent {
4025
4073
  clearTimeout(timer);
4026
4074
  return result;
4027
4075
  }
4028
- _messageHasPendingInteraction(message) {
4029
- return message.parts.some((part) => "state" in part && (part.state === "input-available" || part.state === "approval-requested"));
4076
+ _messageHasPendingInteraction(message, clientResolvable) {
4077
+ return message.parts.some((part) => this._partAwaitsClientInteraction(part, clientResolvable));
4078
+ }
4079
+ /**
4080
+ * Names of the tools whose interrupted `input-available` part can still be
4081
+ * resolved by the CLIENT after a restart — i.e. the client tools (no server
4082
+ * `execute`) from the last request, which the SPA answers by replaying a
4083
+ * `tool-result` over the WebSocket. A server tool is intentionally absent:
4084
+ * its `execute()` promise died with the evicted isolate, so nothing will
4085
+ * ever post its result.
4086
+ */
4087
+ _clientResolvableToolNames() {
4088
+ const names = /* @__PURE__ */ new Set();
4089
+ for (const tool of this._lastClientTools ?? []) if (tool?.name) names.add(tool.name);
4090
+ return names;
4091
+ }
4092
+ /** Extract a tool part's name from its `tool-<name>` / `dynamic-tool` shape. */
4093
+ _toolPartName(record) {
4094
+ const type = typeof record.type === "string" ? record.type : "";
4095
+ if (type === "dynamic-tool") return typeof record.toolName === "string" ? record.toolName : void 0;
4096
+ if (type.startsWith("tool-")) return type.slice(5);
4097
+ }
4098
+ /**
4099
+ * Whether a part is still awaiting a CLIENT interaction that can genuinely
4100
+ * arrive after a restart, so `waitUntilStable` must keep waiting for it:
4101
+ * - `approval-requested`: a reconnecting client can replay the approval.
4102
+ * - `input-available` for a CLIENT tool: the SPA can replay the
4103
+ * `tool-result` (this is why client-tool recovery works — see the
4104
+ * `tool-result` handler, which sets `_pendingInteractionPromise`).
4105
+ *
4106
+ * A SERVER tool's `input-available` is deliberately NOT pending. After an
4107
+ * eviction its `execute()` promise is gone and no interaction will ever
4108
+ * resolve it, so treating it as pending wedges `waitUntilStable` forever:
4109
+ * the recovery continuation times out every attempt, burns the attempt
4110
+ * budget on a wait that can never converge, and — if any transient
4111
+ * storage/schedule error throws on the way — the one-shot recovery alarm row
4112
+ * is swallowed and deleted with no terminal `onExhausted` (the half-finished
4113
+ * message wedges silently). Excluding it lets `waitUntilStable` converge so
4114
+ * `continueLastTurn` runs, where the existing transcript-repair pass
4115
+ * (`_repairTranscriptForProvider`) flips the orphan to an errored result and
4116
+ * the model proceeds.
4117
+ */
4118
+ _partAwaitsClientInteraction(part, clientResolvable) {
4119
+ if (!("state" in part)) return false;
4120
+ const record = part;
4121
+ const state = record.state;
4122
+ if (state === "approval-requested") return true;
4123
+ if (state !== "input-available") return false;
4124
+ const toolName = this._toolPartName(record);
4125
+ return toolName != null && clientResolvable.has(toolName);
4030
4126
  }
4031
4127
  _resolveChatRecoveryConfig() {
4032
4128
  const raw = this.chatRecovery;
@@ -4185,8 +4281,6 @@ var Think = class Think extends Agent {
4185
4281
  } catch (error) {
4186
4282
  console.error("[Think] chatRecovery onExhausted hook threw", error);
4187
4283
  }
4188
- await this._markRecoveredSubmissionInterrupted(incident.recoveryRootRequestId ?? incident.requestId, config.terminalMessage);
4189
- await this._recordTerminalChatStatus("interrupted", incident.requestId, config.terminalMessage);
4190
4284
  this._broadcastChat({
4191
4285
  type: MSG_CHAT_RESPONSE,
4192
4286
  id: incident.requestId,
@@ -4194,6 +4288,8 @@ var Think = class Think extends Agent {
4194
4288
  done: true,
4195
4289
  error: true
4196
4290
  });
4291
+ await this._markRecoveredSubmissionInterrupted(incident.recoveryRootRequestId ?? incident.requestId, config.terminalMessage);
4292
+ await this._recordTerminalChatStatus("interrupted", incident.requestId, config.terminalMessage);
4197
4293
  }
4198
4294
  /**
4199
4295
  * Route a stream-stall watchdog abort into bounded recovery instead of a
@@ -4459,19 +4555,26 @@ var Think = class Think extends Agent {
4459
4555
  return this._resumableStream.hasActiveStream() ? this._resumableStream.activeStreamId ?? "" : "";
4460
4556
  }
4461
4557
  /**
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
4558
+ * Terminalize a recovery turn that is giving up — whether because the
4559
+ * stable-state-timeout retry budget drained, or because the recovery
4560
+ * continuation threw a non-recoverable error — by routing through the SAME
4561
+ * `_exhaustChatRecovery` path as deploy-recovery and stall exhaustion
4465
4562
  * (#1626/#1631). It fires `onExhausted`, emits `chat:recovery:exhausted`,
4466
4563
  * marks the durable submission interrupted, records the terminal chat status,
4467
- * and delivers the configured `terminalMessage`.
4564
+ * and delivers the configured `terminalMessage`. `reason` carries the cause
4565
+ * (`stable_timeout` for a budget give-up, `recovery_error` for a thrown
4566
+ * error) through to `onExhausted` / `chat:recovery:exhausted`.
4468
4567
  *
4469
4568
  * This replaces the older give-up that only set the incident to `failed` and
4470
4569
  * completed the recovered submission as `error`, which bypassed
4471
4570
  * `_exhaustChatRecovery` entirely — so an app relying on `onExhausted` for the
4472
4571
  * 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`.
4572
+ * extreme churn. The error path matters just as much: a non-reset throw in a
4573
+ * recovery callback is SWALLOWED by `Agent._executeScheduleCallback` (only a
4574
+ * code-update reset is re-thrown to preserve the one-shot row), so without
4575
+ * routing it here the alarm row is deleted with no terminal UX at all — the
4576
+ * half-finished message wedges silently. Shared by `_chatRecoveryRetry` and
4577
+ * `_chatRecoveryContinue`.
4475
4578
  *
4476
4579
  * Exactly-once terminalization is defended by two independent guards:
4477
4580
  * 1. The `stored?.status === "exhausted"` re-entry guard below — once an
@@ -4492,16 +4595,21 @@ var Think = class Think extends Agent {
4492
4595
  * • The record is swept AGAIN between two alarms (guard #1 re-persists on the
4493
4596
  * first, so this needs a second independent sweep) — vanishingly unlikely.
4494
4597
  */
4495
- async _exhaustRecoveryAfterStableTimeout(callback, data) {
4598
+ async _exhaustRecoveryGiveUp(callback, data, reason) {
4496
4599
  const config = this._resolveChatRecoveryConfig();
4497
4600
  const incidentKey = data?.incidentId ? this._chatRecoveryIncidentKey(data.incidentId) : null;
4498
- const stored = incidentKey ? await this.ctx.storage.get(incidentKey) : null;
4601
+ let stored = null;
4602
+ if (incidentKey) try {
4603
+ stored = await this.ctx.storage.get(incidentKey) ?? null;
4604
+ } catch (readError) {
4605
+ console.error("[Think] failed to read recovery incident during give-up; synthesizing", readError);
4606
+ }
4499
4607
  if (stored?.status === "exhausted") return;
4500
4608
  const rootRequestId = data?.originalRequestId ?? data?.recoveredRequestId ?? this._activeChatRecoveryRootRequestId ?? stored?.recoveryRootRequestId ?? stored?.requestId ?? "";
4501
4609
  const incident = stored ? {
4502
4610
  ...stored,
4503
4611
  status: "exhausted",
4504
- reason: "stable_timeout"
4612
+ reason
4505
4613
  } : {
4506
4614
  incidentId: data?.incidentId ?? crypto.randomUUID(),
4507
4615
  requestId: rootRequestId,
@@ -4512,9 +4620,13 @@ var Think = class Think extends Agent {
4512
4620
  status: "exhausted",
4513
4621
  firstSeenAt: Date.now(),
4514
4622
  lastAttemptAt: Date.now(),
4515
- reason: "stable_timeout"
4623
+ reason
4516
4624
  };
4517
- if (incidentKey) await this.ctx.storage.put(incidentKey, incident);
4625
+ if (incidentKey) try {
4626
+ await this.ctx.storage.put(incidentKey, incident);
4627
+ } catch (writeError) {
4628
+ console.error("[Think] failed to persist sealed recovery incident during give-up", writeError);
4629
+ }
4518
4630
  const streamId = this._resolveRecoveryStreamId(incident.recoveryRootRequestId ?? incident.requestId);
4519
4631
  const partial = streamId ? this._getPartialStreamText(streamId) : {
4520
4632
  text: "",
@@ -4522,6 +4634,61 @@ var Think = class Think extends Agent {
4522
4634
  };
4523
4635
  await this._exhaustChatRecovery(incident, config, partial, streamId, incident.firstSeenAt);
4524
4636
  }
4637
+ /**
4638
+ * Give-up after the stable-state-timeout retry budget drained. Thin wrapper
4639
+ * over `_exhaustRecoveryGiveUp` so the give-up cause is recorded as
4640
+ * `stable_timeout`.
4641
+ */
4642
+ _exhaustRecoveryAfterStableTimeout(callback, data) {
4643
+ return this._exhaustRecoveryGiveUp(callback, data, "stable_timeout");
4644
+ }
4645
+ /**
4646
+ * Whether an error is a transient "superseded isolate" failure — a deploy /
4647
+ * code update replaced the isolate mid-invocation. Mirrors the base `Agent`
4648
+ * check (`isDurableObjectCodeUpdateReset`) and MUST stay in lockstep with it:
4649
+ * the base `_executeScheduleCallback` re-throws this class for a one-shot row
4650
+ * (preserving it so the platform re-runs on the new code), so a recovery
4651
+ * callback must also re-throw — NOT terminalize — since recovery will re-run
4652
+ * and succeed on the fresh isolate. The matched family (kept identical to the
4653
+ * base):
4654
+ * - "Durable Object reset because its code was updated." (deploy bounce)
4655
+ * - "This script has been upgraded. Please send a new request to connect to
4656
+ * the new version." (a stub/connection to a superseded script)
4657
+ * "Network connection lost." is intentionally excluded (a connection error,
4658
+ * not an isolate replacement — see the base helper's note). The match stays
4659
+ * close to the verbatim platform strings so an ordinary error mentioning
4660
+ * those words isn't misclassified as a supersede.
4661
+ */
4662
+ _isDeployCodeUpdateReset(error) {
4663
+ const message = error instanceof Error ? error.message : typeof error === "string" ? error : "";
4664
+ return /reset because its code was updated|this script has been upgraded/i.test(message);
4665
+ }
4666
+ /**
4667
+ * Handle an error thrown by `_chatRecoveryContinue` / `_chatRecoveryRetry`
4668
+ * after the incident was opened.
4669
+ *
4670
+ * - A deploy code-update reset is re-thrown (after marking the incident
4671
+ * `failed` for observability) so `Agent._executeScheduleCallback` preserves
4672
+ * the one-shot alarm row and the platform re-runs recovery on the fresh
4673
+ * isolate — the turn can still recover, so it must NOT terminalize.
4674
+ * - Any OTHER error is terminalized through the give-up path
4675
+ * (`onExhausted` + the `terminalMessage` banner) and NOT re-thrown. This is
4676
+ * the fix for the silent-seal failure mode: `_executeScheduleCallback`
4677
+ * swallows a non-reset throw and then `alarm()` deletes the one-shot row, so
4678
+ * without terminalizing here the half-finished turn is dropped with no
4679
+ * terminal event and no banner (the user stares at a frozen message until
4680
+ * they send something new).
4681
+ */
4682
+ async _handleRecoveryCallbackError(callback, data, error) {
4683
+ if (this._isDeployCodeUpdateReset(error)) {
4684
+ const message = error instanceof Error ? error.message : String(error);
4685
+ await this._updateChatRecoveryIncident(data?.incidentId, "failed", message);
4686
+ if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, message);
4687
+ throw error;
4688
+ }
4689
+ console.error(`[Think] ${callback} threw during recovery; terminalizing instead of leaving the turn wedged`, error);
4690
+ await this._exhaustRecoveryGiveUp(callback, data, "recovery_error");
4691
+ }
4525
4692
  async _chatRecoveryRetry(data) {
4526
4693
  const recoveredSubmission = data?.recoveredRequestId ? this._readRunningSubmissionByRequestId(data.recoveredRequestId) : null;
4527
4694
  if (data?.recoveredRequestId && !recoveredSubmission) {
@@ -4555,9 +4722,7 @@ var Think = class Think extends Agent {
4555
4722
  await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
4556
4723
  if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : result.error ?? `Recovery retry ${result.status}.`);
4557
4724
  } catch (error) {
4558
- await this._updateChatRecoveryIncident(data?.incidentId, "failed", error instanceof Error ? error.message : String(error));
4559
- if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, error instanceof Error ? error.message : String(error));
4560
- throw error;
4725
+ await this._handleRecoveryCallbackError("_chatRecoveryRetry", data, error);
4561
4726
  } finally {
4562
4727
  this._activeChatRecoveryRootRequestId = previousRootRequestId;
4563
4728
  if (recoveredSubmission) this._submissionAbortControllers.delete(recoveredSubmission.submission_id);
@@ -4660,9 +4825,7 @@ var Think = class Think extends Agent {
4660
4825
  await this._updateChatRecoveryIncident(data?.incidentId, result.status === "completed" ? "completed" : result.status === "skipped" ? "skipped" : "failed", result.error);
4661
4826
  if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, result.status, result.requestId || null, result.status === "completed" ? null : result.error ?? `Recovery ${result.status}.`);
4662
4827
  } catch (error) {
4663
- await this._updateChatRecoveryIncident(data?.incidentId, "failed", error instanceof Error ? error.message : String(error));
4664
- if (data?.recoveredRequestId) await this._completeRecoveredSubmission(data.recoveredRequestId, "error", null, error instanceof Error ? error.message : String(error));
4665
- throw error;
4828
+ await this._handleRecoveryCallbackError("_chatRecoveryContinue", data, error);
4666
4829
  } finally {
4667
4830
  this._activeChatRecoveryRootRequestId = previousRootRequestId;
4668
4831
  if (recoveredSubmission) this._submissionAbortControllers.delete(recoveredSubmission.submission_id);