@cloudflare/think 0.8.0 → 0.8.2

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.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"think.js","names":["Workspace","Session","agentContext"],"sources":["../src/think.ts"],"sourcesContent":["/**\n * Think — an opinionated chat agent base class.\n *\n * Works as both a **top-level agent** (speaking the `cf_agent_chat_*`\n * WebSocket protocol to browser clients) and a **sub-agent** (called\n * via `chat()` over RPC from a parent agent).\n *\n * Each instance gets its own SQLite storage backed by Session — providing\n * tree-structured messages, context blocks, compaction, FTS5 search, and\n * multi-session support.\n *\n * Configuration overrides:\n * - getModel() — return the LanguageModel to use\n * - getSystemPrompt() — return the system prompt (fallback when no context blocks)\n * - getTools() — return the ToolSet for the agentic loop\n * - maxSteps — max tool-call rounds per turn (default: 10)\n * - configureSession() — add context blocks, compaction, search, skills\n *\n * Lifecycle hooks:\n * - beforeTurn() — inspect/override context, tools, model before inference\n * - beforeStep() — per-step callback to override model, messages, tool selection\n * - beforeToolCall() — intercept tool calls (block, modify args, substitute result)\n * - afterToolCall() — inspect tool results after execution\n * - onStepFinish() — per-step callback (logging, analytics)\n * - onChunk() — per-chunk callback (streaming analytics)\n * - onChatResponse() — post-turn lifecycle hook (logging, chaining, analytics)\n * - onChatError() — customize error handling\n *\n * Production features:\n * - WebSocket chat protocol (compatible with useAgentChat / useChat)\n * - Sub-agent RPC streaming via StreamCallback\n * - Session-backed storage with tree-structured messages\n * - Context blocks with LLM-writable persistent memory\n * - Non-destructive compaction (summaries replace ranges at read time)\n * - FTS5 full-text search across conversation history\n * - Abort/cancel support via AbortRegistry\n * - Error handling with partial message persistence\n * - Message sanitization (strips OpenAI ephemeral metadata)\n * - Row size enforcement (compacts large tool outputs)\n * - Resumable streams (replay on reconnect)\n *\n * @experimental The API surface may change before stabilizing.\n *\n * @example\n * ```typescript\n * import { Think } from \"@cloudflare/think\";\n * import { createWorkersAI } from \"workers-ai-provider\";\n *\n * export class MyAgent extends Think<Env> {\n * getModel() {\n * return createWorkersAI({ binding: this.env.AI })(\"@cf/moonshotai/kimi-k2.6\");\n * }\n *\n * getSystemPrompt() {\n * return \"You are a helpful coding assistant.\";\n * }\n * }\n * ```\n *\n * @example With context blocks and self-updating memory\n * ```typescript\n * import { Think } from \"@cloudflare/think\";\n * import type { Session } from \"@cloudflare/think\";\n *\n * export class MemoryAgent extends Think<Env> {\n * getModel() { ... }\n *\n * configureSession(session: Session) {\n * return session\n * .withContext(\"soul\", {\n * provider: { get: async () => \"You are a helpful coding assistant.\" }\n * })\n * .withContext(\"memory\", {\n * description: \"Important facts learned during conversation.\",\n * maxTokens: 2000\n * })\n * .withCachedPrompt();\n * }\n * }\n * ```\n */\n\nimport type {\n LanguageModel,\n ModelMessage,\n PrepareStepFunction,\n PrepareStepResult,\n StreamTextOnChunkCallback,\n StreamTextOnStepFinishCallback,\n StreamTextOnToolCallFinishCallback,\n StopCondition,\n ToolSet,\n TypedToolCall,\n UIMessage\n} from \"ai\";\nimport {\n convertToModelMessages,\n jsonSchema,\n Output,\n stepCountIs,\n streamText\n} from \"ai\";\nimport * as skills from \"agents/skills\";\nimport { SkillRegistry } from \"agents/skills\";\nimport type { SkillScriptRunner, SkillSource } from \"agents/skills\";\n\n// Re-export AI SDK types that appear on Think's public lifecycle hooks\n// so users can import them from a single place.\nexport type {\n PrepareStepFunction,\n PrepareStepResult,\n StepResult,\n StopCondition,\n TextStreamPart,\n TypedToolCall,\n TypedToolResult\n} from \"ai\";\nexport { skills };\nexport type { SkillRunContext, SkillSource } from \"agents/skills\";\nimport {\n Agent,\n __DO_NOT_USE_WILL_BREAK__agentContext as agentContext\n} from \"agents\";\n\nconst agentToolChunkEncoder = new TextEncoder();\nimport type {\n Connection,\n FiberRecoveryContext,\n RetryOptions,\n WSMessage\n} from \"agents\";\nimport {\n sanitizeMessage,\n enforceRowSizeLimit,\n StreamAccumulator,\n CHAT_MESSAGE_TYPES,\n TurnQueue,\n ResumableStream,\n ContinuationState,\n SubmitConcurrencyController,\n createToolsFromClientSchemas,\n AbortRegistry,\n applyToolUpdate,\n toolResultUpdate,\n crossMessageToolResultUpdate,\n toolApprovalUpdate,\n parseProtocolMessage,\n applyChunkToParts,\n reconcileMessages,\n resolveToolMergeId,\n createChatFiberSnapshot,\n unwrapChatFiberSnapshot,\n wrapChatFiberSnapshot\n} from \"agents/chat\";\nimport type {\n StreamChunkData,\n ClientToolSchema,\n MessagePart,\n SubmitConcurrencyDecision,\n ChatFiberSnapshot\n} from \"agents/chat\";\nimport { Session } from \"agents/experimental/memory/session\";\nimport { truncateOlderMessages } from \"agents/experimental/memory/utils\";\nimport { Workspace } from \"@cloudflare/shell\";\nimport { createWorkspaceTools } from \"./tools/workspace\";\nimport { ThinkMessengerRuntime } from \"./messengers/chat-sdk\";\nimport type {\n MessengerContext,\n ThinkMessengers,\n MessengerThinkHost\n} from \"./messengers\";\n\nexport { Session } from \"agents/experimental/memory/session\";\nexport { Workspace } from \"@cloudflare/shell\";\nexport type { FiberContext, FiberRecoveryContext } from \"agents\";\nexport type { WorkspaceLike } from \"./tools/workspace\";\nimport type { WorkspaceLike } from \"./tools/workspace\";\n\n// ── Wire protocol constants ────────────────────────────────────────\nconst MSG_CHAT_MESSAGES = CHAT_MESSAGE_TYPES.CHAT_MESSAGES;\nconst MSG_CHAT_RESPONSE = CHAT_MESSAGE_TYPES.USE_CHAT_RESPONSE;\nconst MSG_CHAT_CLEAR = CHAT_MESSAGE_TYPES.CHAT_CLEAR;\nconst MSG_STREAM_RESUMING = CHAT_MESSAGE_TYPES.STREAM_RESUMING;\nconst MSG_STREAM_RESUME_NONE = CHAT_MESSAGE_TYPES.STREAM_RESUME_NONE;\nconst MSG_MESSAGE_UPDATED = CHAT_MESSAGE_TYPES.MESSAGE_UPDATED;\nconst MSG_CHAT_RECOVERING = CHAT_MESSAGE_TYPES.CHAT_RECOVERING;\n\nfunction sendIfOpen(connection: Connection, message: string): boolean {\n try {\n connection.send(message);\n return true;\n } catch (error) {\n if (isWebSocketClosedSendError(error)) return false;\n throw error;\n }\n}\n\nfunction isWebSocketClosedSendError(error: unknown): boolean {\n return (\n error instanceof TypeError &&\n error.message.includes(\"WebSocket send() after close\")\n );\n}\n\nfunction shouldMarkSkippedAfterGenerationChange(\n status: SaveMessagesResult[\"status\"]\n): boolean {\n return status === \"completed\";\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== \"object\") {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return `[${value.map((item) => stableStringify(item)).join(\",\")}]`;\n }\n const record = value as Record<string, unknown>;\n return `{${Object.keys(record)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`)\n .join(\",\")}}`;\n}\n\nfunction stableHash(value: unknown): string {\n const input = stableStringify(value);\n let h1 = 1779033703;\n let h2 = 3144134277;\n let h3 = 1013904242;\n let h4 = 2773480762;\n for (let i = 0; i < input.length; i++) {\n const code = input.charCodeAt(i);\n h1 = h2 ^ Math.imul(h1 ^ code, 597399067);\n h2 = h3 ^ Math.imul(h2 ^ code, 2869860233);\n h3 = h4 ^ Math.imul(h3 ^ code, 951274213);\n h4 = h1 ^ Math.imul(h4 ^ code, 2716044179);\n }\n h1 = Math.imul(h3 ^ (h1 >>> 18), 597399067);\n h2 = Math.imul(h4 ^ (h2 >>> 22), 2869860233);\n h3 = Math.imul(h1 ^ (h3 >>> 17), 951274213);\n h4 = Math.imul(h2 ^ (h4 >>> 19), 2716044179);\n return [h1, h2, h3, h4]\n .map((part) => (part >>> 0).toString(16).padStart(8, \"0\"))\n .join(\"\");\n}\n\nfunction validateTimezone(timezone: string): string {\n try {\n const formatter = new Intl.DateTimeFormat(\"en-US\", { timeZone: timezone });\n return formatter.resolvedOptions().timeZone;\n } catch {\n throw new Error(`Invalid timezone \"${timezone}\"`);\n }\n}\n\nfunction parseTime(value: string): { hour: number; minute: number } {\n const match = /^([01]\\d|2[0-3]):([0-5]\\d)$/.exec(value);\n if (!match) {\n throw new Error(`Invalid schedule time \"${value}\"; expected HH:mm`);\n }\n return { hour: Number(match[1]), minute: Number(match[2]) };\n}\n\nconst declaredScheduleDayNumbers: Record<string, number> = {\n sun: 0,\n sunday: 0,\n mon: 1,\n monday: 1,\n tue: 2,\n tuesday: 2,\n wed: 3,\n wednesday: 3,\n thu: 4,\n thursday: 4,\n fri: 5,\n friday: 5,\n sat: 6,\n saturday: 6\n};\n\nfunction parseDeclaredTaskSchedule(\n rawSchedule: string,\n taskTimezone: string | undefined,\n defaultTimezone: string | undefined\n): ParsedDeclaredSchedule {\n const result = tryParseDeclaredTaskSchedule(\n rawSchedule,\n taskTimezone,\n defaultTimezone\n );\n if (!result.ok) throw new Error(result.error);\n return result.schedule;\n}\n\nfunction tryParseDeclaredTaskSchedule(\n rawSchedule: string,\n taskTimezone: string | undefined,\n defaultTimezone: string | undefined\n): ParseDeclaredScheduleResult {\n try {\n return {\n ok: true,\n schedule: parseDeclaredTaskScheduleUnchecked(\n rawSchedule,\n taskTimezone,\n defaultTimezone\n )\n };\n } catch (error) {\n return {\n ok: false,\n error: error instanceof Error ? error.message : String(error)\n };\n }\n}\n\nfunction parseDeclaredTaskScheduleUnchecked(\n rawSchedule: string,\n taskTimezone: string | undefined,\n defaultTimezone: string | undefined\n): ParsedDeclaredSchedule {\n const trimmed = rawSchedule.trim().replace(/\\s+/g, \" \").toLowerCase();\n const inlineTimezoneMatch = /^(.*) in ([A-Za-z_][A-Za-z0-9_+\\-/]*)$/.exec(\n trimmed\n );\n const schedule = inlineTimezoneMatch?.[1] ?? trimmed;\n const inlineTimezone = inlineTimezoneMatch?.[2];\n if (\n inlineTimezone &&\n taskTimezone &&\n validateTimezone(inlineTimezone) !== validateTimezone(taskTimezone)\n ) {\n throw new Error(\n `Schedule timezone \"${inlineTimezone}\" does not match task timezone \"${taskTimezone}\"`\n );\n }\n\n const intervalMatch = /^every ([1-9]\\d*) (minute|minutes|hour|hours)$/.exec(\n schedule\n );\n if (intervalMatch) {\n if (inlineTimezone || taskTimezone) {\n throw new Error(\"Interval schedules cannot specify a timezone\");\n }\n const count = Number(intervalMatch[1]);\n const unit = intervalMatch[2];\n if (count === 1 && unit.endsWith(\"s\")) {\n throw new Error(`Use singular unit for \"${rawSchedule}\"`);\n }\n if (count !== 1 && !unit.endsWith(\"s\")) {\n throw new Error(`Use plural unit for \"${rawSchedule}\"`);\n }\n return {\n kind: \"interval\",\n intervalMs: count * (unit.startsWith(\"hour\") ? 60 * 60_000 : 60_000),\n normalizedSchedule: `every ${count} ${unit}`\n };\n }\n\n const timezone = inlineTimezone ?? taskTimezone ?? defaultTimezone;\n if (!timezone) {\n throw new Error(\n `Wall-clock schedule \"${rawSchedule}\" requires a timezone or getDefaultTimezone()`\n );\n }\n const resolvedTimezone = validateTimezone(timezone);\n\n const dailyMatch = /^every day at ([0-2]\\d:[0-5]\\d)$/.exec(schedule);\n if (dailyMatch) {\n const { hour, minute } = parseTime(dailyMatch[1]);\n return {\n kind: \"wall-clock\",\n normalizedSchedule: `every day at ${dailyMatch[1]}`,\n timezone: resolvedTimezone,\n hour,\n minute,\n days: \"daily\"\n };\n }\n\n const weekdayMatch = /^every weekday at ([0-2]\\d:[0-5]\\d)$/.exec(schedule);\n if (weekdayMatch) {\n const { hour, minute } = parseTime(weekdayMatch[1]);\n return {\n kind: \"wall-clock\",\n normalizedSchedule: `every weekday at ${weekdayMatch[1]}`,\n timezone: resolvedTimezone,\n hour,\n minute,\n days: \"weekday\"\n };\n }\n\n const weeklyMatch = /^every week on ([a-z,\\s]+) at ([0-2]\\d:[0-5]\\d)$/.exec(\n schedule\n );\n if (weeklyMatch) {\n const seen = new Set<number>();\n const days = weeklyMatch[1].split(\",\").map((day) => {\n const normalized = day.trim();\n const dayNumber = declaredScheduleDayNumbers[normalized];\n if (dayNumber === undefined) {\n throw new Error(`Invalid schedule day \"${normalized}\"`);\n }\n if (seen.has(dayNumber)) {\n throw new Error(`Duplicate schedule day \"${normalized}\"`);\n }\n seen.add(dayNumber);\n return dayNumber;\n });\n if (days.length === 0) {\n throw new Error(\"Weekly schedule requires at least one day\");\n }\n const { hour, minute } = parseTime(weeklyMatch[2]);\n return {\n kind: \"wall-clock\",\n normalizedSchedule: `every week on ${weeklyMatch[1]\n .split(\",\")\n .map((day) => day.trim())\n .join(\",\")} at ${weeklyMatch[2]}`,\n timezone: resolvedTimezone,\n hour,\n minute,\n days\n };\n }\n\n throw new Error(`Unsupported schedule DSL \"${rawSchedule}\"`);\n}\n\nfunction getZonedParts(date: Date, timezone: string): ZonedParts {\n const parts = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: timezone,\n calendar: \"iso8601\",\n numberingSystem: \"latn\",\n weekday: \"short\",\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hourCycle: \"h23\"\n }).formatToParts(date);\n const part = (type: Intl.DateTimeFormatPartTypes) =>\n parts.find((entry) => entry.type === type)?.value ?? \"\";\n return {\n year: Number(part(\"year\")),\n month: Number(part(\"month\")),\n day: Number(part(\"day\")),\n hour: Number(part(\"hour\")),\n minute: Number(part(\"minute\")),\n second: Number(part(\"second\")),\n weekday: [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"].indexOf(\n part(\"weekday\")\n )\n };\n}\n\nfunction compareLocalParts(\n left: Pick<ZonedParts, \"year\" | \"month\" | \"day\" | \"hour\" | \"minute\">,\n right: Pick<ZonedParts, \"year\" | \"month\" | \"day\" | \"hour\" | \"minute\">\n): number {\n const fields = [\"year\", \"month\", \"day\", \"hour\", \"minute\"] as const;\n for (const field of fields) {\n const diff = left[field] - right[field];\n if (diff !== 0) return diff;\n }\n return 0;\n}\n\nfunction findZonedInstant(\n target: Pick<ZonedParts, \"year\" | \"month\" | \"day\" | \"hour\" | \"minute\">,\n timezone: string\n): Date {\n const approximate = Date.UTC(\n target.year,\n target.month - 1,\n target.day,\n target.hour,\n target.minute\n );\n const start = approximate - 14 * 60 * 60_000;\n const end = approximate + 14 * 60 * 60_000;\n for (let time = start; time <= end; time += 60_000) {\n const candidate = new Date(time);\n const parts = getZonedParts(candidate, timezone);\n if (compareLocalParts(parts, target) === 0) return candidate;\n }\n for (let time = start; time <= end; time += 60_000) {\n const candidate = new Date(time);\n const parts = getZonedParts(candidate, timezone);\n if (compareLocalParts(parts, target) > 0) return candidate;\n }\n throw new Error(`Unable to resolve local time in timezone \"${timezone}\"`);\n}\n\nfunction addLocalDays(\n parts: Pick<ZonedParts, \"year\" | \"month\" | \"day\">,\n days: number\n): Pick<ZonedParts, \"year\" | \"month\" | \"day\"> {\n const date = new Date(\n Date.UTC(parts.year, parts.month - 1, parts.day + days)\n );\n return {\n year: date.getUTCFullYear(),\n month: date.getUTCMonth() + 1,\n day: date.getUTCDate()\n };\n}\n\nfunction isAllowedWallClockDay(\n weekday: number,\n days: ParsedDeclaredSchedule & { kind: \"wall-clock\" }\n): boolean {\n if (days.days === \"daily\") return true;\n if (days.days === \"weekday\") return weekday >= 1 && weekday <= 5;\n return days.days.includes(weekday);\n}\n\nfunction nextDeclaredScheduleTime(\n schedule: ParsedDeclaredSchedule,\n now: Date,\n previousScheduledFor?: number\n): Date {\n if (schedule.kind === \"interval\") {\n let next =\n previousScheduledFor === undefined\n ? now.getTime() + schedule.intervalMs\n : previousScheduledFor + schedule.intervalMs;\n while (next <= now.getTime()) next += schedule.intervalMs;\n return new Date(next);\n }\n\n const nowParts = getZonedParts(now, schedule.timezone);\n for (let offset = 0; offset < 370; offset++) {\n const localDate = addLocalDays(nowParts, offset);\n const candidate = findZonedInstant(\n {\n ...localDate,\n hour: schedule.hour,\n minute: schedule.minute\n },\n schedule.timezone\n );\n const weekday = getZonedParts(candidate, schedule.timezone).weekday;\n if (!isAllowedWallClockDay(weekday, schedule)) continue;\n if (candidate.getTime() > now.getTime()) return candidate;\n }\n throw new Error(\"Unable to compute next scheduled task occurrence\");\n}\n\ntype StreamResultStatus = {\n status: Exclude<SaveMessagesResult[\"status\"], \"skipped\">;\n error?: string;\n output?: unknown;\n};\n\ntype ProgrammaticMessagesResult = SaveMessagesResult & {\n output?: unknown;\n};\n\ntype ChatRecoveryRetryData = {\n targetUserId?: string;\n originalRequestId?: string;\n incidentId?: string;\n lastBody?: Record<string, unknown> | null;\n lastClientTools?: ClientToolSchema[] | null;\n recoveredRequestId?: string;\n};\n\ntype ChatRecoveryContinueData = {\n targetAssistantId?: string;\n originalRequestId?: string;\n incidentId?: string;\n lastBody?: Record<string, unknown> | null;\n lastClientTools?: ClientToolSchema[] | null;\n recoveredRequestId?: string;\n};\n\n/**\n * Thrown by `_iterateWithStallWatchdog` when the inactivity watchdog fires\n * (a model/transport stream that parks without ever throwing). Distinct from\n * in-band model/stream errors so the read-loop catch can route a stall into\n * bounded recovery (#1626) — a transient hang is retried within the existing\n * recovery budget — while genuine errors stay terminal.\n */\nclass ChatStreamStalledError extends Error {\n readonly isChatStreamStall = true;\n constructor(message: string) {\n super(message);\n this.name = \"ChatStreamStalledError\";\n }\n}\n\ntype ChatRecoveryKind = \"retry\" | \"continue\";\n\ntype ChatRecoveryIncident = {\n incidentId: string;\n requestId: string;\n /**\n * Stable root requestId for the whole continuation chain. The durable\n * submission is keyed by this (not the per-attempt `requestId`, which is\n * overwritten each continuation), so terminal paths must use it to mark the\n * submission. Optional for backward-compat with incidents persisted before\n * this field existed — fall back to `requestId`.\n */\n recoveryRootRequestId?: string;\n recoveryKind: ChatRecoveryKind;\n attempt: number;\n maxAttempts: number;\n status:\n | \"detected\"\n | \"scheduled\"\n | \"attempting\"\n | \"completed\"\n | \"skipped\"\n | \"exhausted\"\n | \"failed\";\n firstSeenAt: number;\n lastAttemptAt: number;\n /**\n * Epoch ms of the last attempt that observed forward progress. The recovery\n * budget is keyed to this (`now - lastProgressAt > NO_PROGRESS_WINDOW`), so a\n * turn that keeps producing content survives churn indefinitely while a\n * genuinely stuck turn is sealed within the window (#1637). Optional for\n * backward-compat — falls back to `firstSeenAt`.\n */\n lastProgressAt?: number;\n reason?: string;\n /**\n * High-water mark of the durable, monotonic recovery-progress counter (see\n * `_chatRecoveryProgressMarker`) observed for this incident. Used to\n * distinguish a turn that is making forward progress but keeps getting\n * interrupted by isolate resets (deploys) — which should NOT exhaust the\n * budget — from one that genuinely fails to advance. Sourced from a persisted\n * counter rather than the live transcript so compaction cannot lower it\n * (#1628).\n */\n progress?: number;\n};\n\nconst CHAT_RECOVERY_INCIDENT_KEY_PREFIX = \"cf:chat-recovery:incident:\";\n// Durable, monotonic forward-progress counter for recovery budget resets.\n// Bumped on each durable content flush (`_storeChunkDurably`) — production time,\n// so it reflects genuinely new content and is immune to reconnects/re-persists;\n// never recomputed from the (compactable) transcript. See\n// `_chatRecoveryProgressMarker`.\nconst CHAT_RECOVERY_PROGRESS_KEY = \"cf:chat-recovery:progress\";\n// Secondary backstop only. The primary recovery bound is the no-progress\n// wall clock below; with alarm debounce this cap rarely binds (it catches a\n// pathological tight alarm-loop). Kept high so the no-progress window seals\n// first under normal deploy cadence (#1637).\nconst DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS = 10;\nconst DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS = 10_000;\n// Auto-continuation barrier (#1649): when the model emits parallel tool calls,\n// the client answers each one independently and sends a `tool-result` with\n// `autoContinue` per result. A fast tool's result must NOT trigger inference\n// while a slower sibling is still `input-available` — doing so feeds the\n// provider an incomplete tool-result set (MissingToolResultsError) or, with the\n// transcript-repair backstop, silently flips the in-flight sibling to errored\n// and runs a spurious extra continuation. So we hold the continuation until the\n// step's batch settles (no `input-available`/`approval-requested` siblings),\n// bounded by this timeout so a genuinely orphaned tool call (e.g. the client\n// disconnected mid-batch) still falls through to the repair backstop instead of\n// pinning the continuation open forever.\nconst AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS = 60_000;\n// Delay before retrying a continuation that timed out waiting for stable state.\n// Gives an actively-churning isolate (e.g. a deploy in flight) time to settle.\nconst CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS = 3;\nconst DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE =\n \"The assistant was interrupted and could not recover. Please try again.\";\n// Incidents that have not seen a new attempt within this window are assumed\n// abandoned and swept so durable storage does not grow without bound.\nconst CHAT_RECOVERY_INCIDENT_TTL_MS = 60 * 60 * 1000;\n// PRIMARY recovery bound (#1637): seal an incident that has made no forward\n// progress for this long. Keyed to `lastProgressAt`, which resets on every\n// progress-bearing attempt — so a turn that keeps producing content survives\n// deploy churn indefinitely, while a genuinely stuck turn dies within 5 min.\nconst CHAT_RECOVERY_NO_PROGRESS_WINDOW_MS = 5 * 60 * 1000;\n// Alarm debounce: recovery alarms bunched within this window collapse into a\n// single attempt. A deploy rollout drops/reconnects the socket several times\n// over ~11–22s; without this, one logical deploy would burn several attempts.\nconst CHAT_RECOVERY_ALARM_DEBOUNCE_MS = 30 * 1000;\n// ABSOLUTE ceiling for a single recovery incident, keyed to `firstSeenAt` and\n// NEVER reset by progress — the final hard stop so even a degenerate\n// slowly-progressing loop cannot run forever.\nconst CHAT_RECOVERY_MAX_WINDOW_MS = 15 * 60 * 1000;\n// N9: while a parent re-attaches to and forwards a sub-agent's stream, credit\n// the parent's recovery progress at most this often. The marker only needs to\n// advance ≥once between recovery attempts (the no-progress window is minutes),\n// so this caps storage writes during high-rate child streaming. The throttle\n// state is in-memory (reset per isolate), so the first forwarded chunk after\n// ANY restart always bumps — guaranteeing every recovery attempt that observes\n// child output registers forward progress.\nconst AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS = 5_000;\n\n// Ephemeral user message appended when a model request would otherwise end in\n// an assistant message (see `ensureValidContinueCheckpoint`).\nconst CONTINUE_CHECKPOINT_PROMPT =\n \"Continue your previous response from exactly where it left off. Do not repeat any of it.\";\n\n/**\n * Ensure a model request does not end in an assistant message.\n *\n * Continuing a partial assistant turn (e.g. after a deploy interrupts a stream)\n * replays a transcript whose final message is that partial assistant message —\n * an \"assistant prefill\". Modern chat models reject this: Anthropic Claude 4.6+\n * returns a 400 (\"This model does not support assistant message prefill. The\n * conversation must end with a user message.\"). To reach a valid continue\n * checkpoint across providers we append an ephemeral user message. This shapes\n * only the model request; it is never persisted to the transcript.\n */\nfunction ensureValidContinueCheckpoint(\n messages: ModelMessage[]\n): ModelMessage[] {\n if (messages.length === 0) return messages;\n if (messages[messages.length - 1]?.role !== \"assistant\") return messages;\n return [...messages, { role: \"user\", content: CONTINUE_CHECKPOINT_PROMPT }];\n}\n\n// Durable record of the last turn that ended in a terminal error / abandoned\n// recovery. Replayed to clients on connect so a turn that failed while they\n// were disconnected (e.g. during a deploy/WS reconnect storm) is not silently\n// frozen — the terminal `MSG_CHAT_RESPONSE` broadcast is otherwise transient.\nconst CHAT_LAST_TERMINAL_KEY = \"cf:chat:last-terminal\";\n\n// Durable record of an in-progress durable recovery, so a \"recovering…\" status\n// can be broadcast live AND replayed to a client that connects mid-recovery\n// (#1620). Set when a recovery continuation/retry is scheduled; cleared on every\n// terminal outcome (completed/skipped/failed/exhausted) so the indicator can't\n// spin forever.\nconst CHAT_RECOVERING_KEY = \"cf:chat:recovering\";\n\n/**\n * Callback interface for streaming chat events from a Think sub-agent.\n *\n * Designed to work across the sub-agent RPC boundary — implement as\n * an RpcTarget in the parent agent and pass to `chat()`.\n */\nexport interface ChatStartEvent {\n requestId: string;\n}\n\nexport interface StreamCallback {\n onStart(event: ChatStartEvent): void | Promise<void>;\n onEvent(json: string): void | Promise<void>;\n onDone(): void | Promise<void>;\n onError(error: string): void | Promise<void>;\n /**\n * The current attempt was interrupted (a stream-stall watchdog abort routed\n * into bounded recovery, #1626) and its final outcome will NOT arrive through\n * this callback. One of two things is true:\n * - a scheduled continuation — running in a LATER isolate invocation, without\n * this callback — will produce the answer (delivered to other channels,\n * e.g. WebSocket connections), OR\n * - the recovery budget was exhausted, so the turn was already terminalized\n * out-of-band (the configured `terminalMessage` + `onExhausted`) and is\n * terminally over — there is NO continuation to come.\n *\n * This is NOT `onDone` (this attempt did not complete) and NOT `onError` (the\n * raw stall is not surfaced as a terminal error here); without it the contract\n * `onStart → onEvent* → (onDone | onError)` is silently abandoned and a\n * consumer that treats the clean resolve as success finalizes a truncated\n * partial.\n *\n * Consumers should AVOID finalizing the partial on this signal — surface a\n * \"recovering…\" / \"interrupted, please retry\" state, or re-attach via a\n * durable channel — but must ALSO NOT block indefinitely waiting for a\n * continuation: per the exhausted case above, one may never come. Optional →\n * defaults to a no-op, so this is fully backward-compatible.\n *\n * Note: a deploy/eviction interruption kills the isolate (and this callback)\n * before this can fire — the caller observes a transport break instead. This\n * fires only for an in-isolate interruption (the stall→recovery path).\n */\n onInterrupted?(): void | Promise<void>;\n}\n\n/**\n * Minimal interface for the result of the inference loop.\n * The AI SDK's `streamText()` result satisfies this interface.\n */\nexport interface StreamableResult {\n toUIMessageStream(options?: {\n sendReasoning?: boolean;\n }): AsyncIterable<unknown>;\n output?: PromiseLike<unknown>;\n}\n\n/**\n * Options for a chat turn (sub-agent RPC entry point).\n */\nexport interface ChatOptions {\n signal?: AbortSignal;\n}\n\ntype AgentToolChildRunStatus =\n | \"starting\"\n | \"running\"\n | \"completed\"\n | \"error\"\n | \"aborted\";\n\ntype AgentToolChildRunRow = {\n run_id: string;\n request_id: string | null;\n stream_id: string | null;\n status: AgentToolChildRunStatus;\n summary: string | null;\n output_json: string | null;\n error_message: string | null;\n started_at: number;\n completed_at: number | null;\n};\n\ntype AgentToolRunInspection<Output = unknown> = {\n runId: string;\n status: AgentToolChildRunStatus;\n requestId?: string;\n streamId?: string;\n output?: Output;\n summary?: string;\n error?: string;\n startedAt: number;\n completedAt?: number;\n};\n\ntype Digit = \"0\" | \"1\" | \"2\" | \"3\" | \"4\" | \"5\" | \"6\" | \"7\" | \"8\" | \"9\";\ntype Hour = `0${Digit}` | `1${Digit}` | \"20\" | \"21\" | \"22\" | \"23\";\ntype Minute = `${\"0\" | \"1\" | \"2\" | \"3\" | \"4\" | \"5\"}${Digit}`;\nexport type ThinkTime = `${Hour}:${Minute}`;\nexport type ThinkIntervalSchedule =\n | `every ${number} minute${\"\" | \"s\"}`\n | `every ${number} hour${\"\" | \"s\"}`;\nexport type ThinkWallClockSchedule =\n | `every day at ${ThinkTime}`\n | `every weekday at ${ThinkTime}`\n | `every week on ${string} at ${ThinkTime}`;\nexport type ThinkScheduledTaskSchedule =\n | ThinkIntervalSchedule\n | ThinkWallClockSchedule\n | `${ThinkWallClockSchedule} in ${string}`;\n\nexport type ThinkScheduledTaskContext = {\n taskId: string;\n scheduledFor: number;\n scheduledForDate: Date;\n occurrenceKey: string;\n idempotencyKey: string;\n schedule: string;\n scheduleKind: \"interval\" | \"wall-clock\";\n timezone?: string;\n metadata?: Record<string, unknown>;\n};\n\ntype ThinkScheduledTaskPromptAction = {\n prompt: string | (() => string | Promise<string>);\n handler?: never;\n};\n\ntype ThinkScheduledTaskHandlerAction = {\n handler: (ctx: ThinkScheduledTaskContext) => void | Promise<void>;\n prompt?: never;\n};\n\ntype ThinkScheduledTaskBase = (\n | ThinkScheduledTaskPromptAction\n | ThinkScheduledTaskHandlerAction\n) & {\n retry?: RetryOptions;\n metadata?: Record<string, unknown>;\n};\n\nexport type ThinkScheduledTask =\n | (ThinkScheduledTaskBase & {\n schedule: ThinkIntervalSchedule;\n timezone?: never;\n })\n | (ThinkScheduledTaskBase & {\n schedule: ThinkWallClockSchedule;\n timezone?: string;\n })\n | (ThinkScheduledTaskBase & {\n schedule: `${ThinkWallClockSchedule} in ${string}`;\n timezone?: string;\n });\n\nexport type ThinkScheduledTasks = Record<string, ThinkScheduledTask>;\n\nexport function defineScheduledTasks<const T extends ThinkScheduledTasks>(\n tasks: T\n): T {\n return tasks;\n}\n\ntype ParsedDeclaredSchedule =\n | {\n kind: \"interval\";\n intervalMs: number;\n normalizedSchedule: string;\n }\n | {\n kind: \"wall-clock\";\n normalizedSchedule: string;\n timezone: string;\n hour: number;\n minute: number;\n days: \"daily\" | \"weekday\" | number[];\n };\n\ntype ParseDeclaredScheduleResult =\n | { ok: true; schedule: ParsedDeclaredSchedule }\n | { ok: false; error: string };\n\ntype NormalizedDeclaredTask = {\n taskId: string;\n prompt?: ThinkScheduledTaskPromptAction[\"prompt\"];\n handler?: ThinkScheduledTaskHandlerAction[\"handler\"];\n schedule: ParsedDeclaredSchedule;\n retry?: RetryOptions;\n metadata?: Record<string, unknown>;\n scheduleHash: string;\n taskHash: string;\n};\n\ntype DeclaredScheduledTaskRow = {\n owner_key: string;\n task_id: string;\n schedule_hash: string;\n task_hash: string;\n schedule_id: string | null;\n next_run_at: number | null;\n created_at: number;\n updated_at: number;\n};\n\ntype DeclaredScheduledTaskPayload = {\n taskId: string;\n scheduleHash: string;\n scheduledFor: number;\n};\n\ntype ZonedParts = {\n year: number;\n month: number;\n day: number;\n hour: number;\n minute: number;\n second: number;\n weekday: number;\n};\n\ntype AgentToolStoredChunk = {\n sequence: number;\n body: string;\n};\n\nexport type ThinkSubmissionStatus =\n | \"pending\"\n | \"running\"\n | \"completed\"\n | \"aborted\"\n | \"skipped\"\n | \"error\";\n\nexport type SubmitMessagesOptions = {\n submissionId?: string;\n idempotencyKey?: string;\n metadata?: Record<string, unknown>;\n};\n\ntype ThinkWorkflowPromptContext = {\n workflow: {\n name: string;\n id: string;\n stepName: string;\n eventType: string;\n };\n output?: {\n schema: unknown;\n };\n fingerprint?: string;\n};\n\nconst THINK_WORKFLOW_PROMPT_METADATA_KEY = \"__thinkWorkflowPrompt\";\n\nexport type ThinkSubmissionInspection = {\n submissionId: string;\n idempotencyKey?: string;\n requestId?: string;\n status: ThinkSubmissionStatus;\n error?: string;\n metadata?: Record<string, unknown>;\n createdAt: number;\n startedAt?: number;\n completedAt?: number;\n};\n\nexport type SubmitMessagesResult = ThinkSubmissionInspection & {\n accepted: boolean;\n};\n\nexport type ListSubmissionsOptions = {\n status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];\n limit?: number;\n};\n\nexport type DeleteSubmissionsOptions = {\n status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];\n completedBefore?: Date;\n limit?: number;\n};\n\ntype ThinkSubmissionRow = {\n submission_id: string;\n idempotency_key: string | null;\n request_id: string | null;\n stream_id: string | null;\n status: ThinkSubmissionStatus;\n messages_json: string;\n metadata_json: string | null;\n error_message: string | null;\n created_at: number;\n messages_applied_at: number | null;\n started_at: number | null;\n completed_at: number | null;\n};\n\ntype ThinkWorkflowNotificationRow = {\n notification_id: string;\n submission_id: string;\n workflow_name: string;\n workflow_id: string;\n event_type: string;\n payload_json: string;\n attempts: number;\n last_error: string | null;\n created_at: number;\n updated_at: number;\n delivered_at: number | null;\n};\n\n// Lifecycle / result types are shared with `@cloudflare/ai-chat` via\n// `agents/chat`. Re-exported from Think so subclasses can import them\n// from `@cloudflare/think` directly.\nexport type {\n ChatResponseResult,\n ChatRecoveryConfig,\n ChatRecoveryContext,\n ChatRecoveryExhaustedContext,\n ChatRecoveryOptions,\n MessageConcurrency,\n ResolvedChatRecoveryConfig,\n SaveMessagesOptions,\n SaveMessagesResult\n} from \"agents/chat\";\nimport type {\n ChatResponseResult,\n ChatRecoveryConfig,\n ChatRecoveryContext,\n ChatRecoveryExhaustedContext,\n ChatRecoveryOptions,\n MessageConcurrency,\n ResolvedChatRecoveryConfig,\n SaveMessagesOptions,\n SaveMessagesResult\n} from \"agents/chat\";\n\n// ── Lifecycle hook types ────────────────────────────────────────\n\n/**\n * A chat turn request. Built automatically by each entry path\n * (WebSocket, chat(), saveMessages, auto-continuation) and passed\n * to Think's inference loop.\n */\nexport interface TurnInput {\n signal?: AbortSignal;\n /** Client-provided tool schemas for dynamic tool registration. */\n clientTools?: ClientToolSchema[];\n /** Custom body fields from the client request. */\n body?: Record<string, unknown>;\n /** Internal workflow prompt configuration, never sourced from client body. */\n workflowPrompt?: ThinkWorkflowPromptContext;\n /** Whether this is a continuation turn (auto-continue after tool result, recovery). */\n continuation: boolean;\n}\n\n/**\n * Context passed to the `beforeTurn` hook.\n * Contains everything Think assembled — the hook can inspect and override.\n */\nexport interface TurnContext {\n /** Assembled system prompt (from context blocks or getSystemPrompt fallback). */\n system: string;\n /** Assembled model messages (truncated, pruned). */\n messages: ModelMessage[];\n /** Merged tool set (workspace + getTools + session + MCP + client + caller). */\n tools: ToolSet;\n /** The language model from getModel(). */\n model: LanguageModel;\n /** Whether this is a continuation turn. */\n continuation: boolean;\n /** Custom body fields from the client request. */\n body?: Record<string, unknown>;\n}\n\n/**\n * Configuration returned by the `beforeTurn` hook to override defaults.\n * All fields are optional — return only what you want to change.\n */\nexport interface TurnConfig {\n /** Override the model for this turn (e.g. cheap model for continuations). */\n model?: LanguageModel;\n /** Override the assembled system prompt. */\n system?: string;\n /** Override the assembled messages. */\n messages?: ModelMessage[];\n /** Extra tools to merge (additive — spread on top of existing tools). */\n tools?: ToolSet;\n /** Limit which tools the model can call (AI SDK activeTools). */\n activeTools?: string[];\n /** Force a specific tool call (AI SDK toolChoice). */\n toolChoice?: Parameters<typeof streamText>[0][\"toolChoice\"];\n /** Override maxSteps for this turn. */\n maxSteps?: number;\n /**\n * Additional AI SDK stop conditions for ending the turn early.\n * Think always keeps its `maxSteps` stop condition as a safety bound.\n */\n stopWhen?: StopCondition<ToolSet> | Array<StopCondition<ToolSet>>;\n /**\n * Controls whether reasoning chunks are included in the UI message stream\n * for this turn. Defaults to the instance-level `sendReasoning` setting.\n */\n sendReasoning?: boolean;\n /**\n * Override the stream-stall inactivity watchdog timeout for THIS turn only\n * (ms; `0` disables it for this turn). Defaults to the instance-level\n * `chatStreamStallTimeoutMs`. Because the watchdog measures the gap between\n * UI-message-stream chunks — which includes server-side tool execution — a\n * turn known to invoke a slow tool can raise (or disable) the timeout for\n * just that turn instead of permanently widening the global window. Auto-\n * resets after the turn.\n */\n chatStreamStallTimeoutMs?: number;\n /** Maximum number of tokens to generate for this turn. */\n maxOutputTokens?: Parameters<typeof streamText>[0][\"maxOutputTokens\"];\n /** Temperature setting for this turn. */\n temperature?: Parameters<typeof streamText>[0][\"temperature\"];\n /** Nucleus sampling setting for this turn. */\n topP?: Parameters<typeof streamText>[0][\"topP\"];\n /** Top-K sampling setting for this turn. */\n topK?: Parameters<typeof streamText>[0][\"topK\"];\n /** Presence penalty setting for this turn. */\n presencePenalty?: Parameters<typeof streamText>[0][\"presencePenalty\"];\n /** Frequency penalty setting for this turn. */\n frequencyPenalty?: Parameters<typeof streamText>[0][\"frequencyPenalty\"];\n /** Stop sequences for this turn. */\n stopSequences?: Parameters<typeof streamText>[0][\"stopSequences\"];\n /** Seed for deterministic sampling when supported by the model. */\n seed?: Parameters<typeof streamText>[0][\"seed\"];\n /** Maximum number of retries for this turn. Set to 0 to disable retries. */\n maxRetries?: Parameters<typeof streamText>[0][\"maxRetries\"];\n /** Timeout configuration for this turn. */\n timeout?: Parameters<typeof streamText>[0][\"timeout\"];\n /** Additional HTTP headers for provider requests on this turn. */\n headers?: Parameters<typeof streamText>[0][\"headers\"];\n /** Provider-specific options (AI SDK providerOptions). */\n providerOptions?: Record<string, unknown>;\n /** Optional AI SDK telemetry configuration for this turn. */\n experimental_telemetry?: Parameters<\n typeof streamText\n >[0][\"experimental_telemetry\"];\n /**\n * Optional structured-output specification (AI SDK `output`).\n * Forwarded to `streamText` so the model's final response is parsed\n * against the supplied schema. Use the AI SDK's `Output.object({ schema })`\n * / `Output.text()` helpers. Combine with `activeTools: []` on the\n * terminal turn if your provider strips tools when structured output\n * is active (e.g. workers-ai-provider).\n */\n output?: Parameters<typeof streamText>[0][\"output\"];\n}\n\nexport interface ChatErrorContext {\n requestId?: string;\n stage: \"parse\" | \"persist\" | \"turn\" | \"stream\" | \"recovery\" | \"transcript\";\n messagesPersisted?: boolean;\n}\n\n/**\n * Context passed to the `beforeStep` hook before each AI SDK step in\n * the agentic loop. Backed by the AI SDK's `PrepareStepFunction<TOOLS>`\n * parameter — exposes the previous `steps`, the zero-based `stepNumber`,\n * the currently selected `model`, the `messages` about to be sent, and\n * `experimental_context`.\n *\n * Pass an explicit `TOOLS` generic for typed previous tool calls / results.\n *\n * Limitations (AI SDK boundary, not Think):\n * - No `abortSignal` is exposed in the context. If you do remote work\n * inside `beforeStep`, it cannot be cancelled by turn-level abort.\n * - `experimental_context` is typed `unknown`; users must narrow it.\n * - `output` cannot be overridden per-step — set it at the turn level\n * via `TurnConfig.output` (returned from `beforeTurn`).\n */\nexport type PrepareStepContext<TOOLS extends ToolSet = ToolSet> = Parameters<\n PrepareStepFunction<TOOLS>\n>[0];\n\n/**\n * Configuration returned by `beforeStep` to override defaults for the\n * current AI SDK step. This is the AI SDK's `PrepareStepResult<TOOLS>` —\n * return only the fields you want to override (`model`, `toolChoice`,\n * `activeTools`, `system`, `messages`, `experimental_context`,\n * `providerOptions`).\n */\nexport type StepConfig<TOOLS extends ToolSet = ToolSet> =\n PrepareStepResult<TOOLS>;\n\n/**\n * Context passed to the `beforeToolCall` hook **before** the tool's\n * `execute` function runs.\n *\n * Backed by the AI SDK's `OnToolCallStartEvent` (the parameter of\n * `experimental_onToolCallStart`). The full `TypedToolCall<TOOLS>`\n * fields (`toolName`, `toolCallId`, `input`, `providerMetadata`, the\n * dynamic/invalid/error discriminators) are spread at the top level for\n * convenience, with the per-call event extras attached:\n *\n * - `stepNumber` — index of the current step\n * - `messages` — conversation messages visible at tool execution time\n * - `abortSignal` — signal that aborts if the turn is cancelled\n *\n * Pass an explicit `TOOLS` generic for full input typing:\n *\n * ```ts\n * import type { ToolCallContext } from \"@cloudflare/think\";\n * import type { tools } from \"./my-tools\";\n *\n * beforeToolCall(ctx: ToolCallContext<typeof tools>) {\n * if (ctx.toolName === \"search\") {\n * ctx.input.query; // typed\n * }\n * }\n * ```\n */\nexport type ToolCallContext<TOOLS extends ToolSet = ToolSet> =\n TypedToolCall<TOOLS> & {\n /** Zero-based index of the current step where this tool call occurs. */\n readonly stepNumber: number | undefined;\n /** The conversation messages available at tool execution time. */\n readonly messages: ReadonlyArray<ModelMessage>;\n /** Signal for cancelling the operation. */\n readonly abortSignal: AbortSignal | undefined;\n };\n\n/**\n * Decision returned by `beforeToolCall` to control tool execution.\n * Return void/undefined to allow execution with original input.\n *\n * Discriminated union — each action has a clear, non-overlapping meaning:\n * - `allow` — execute the tool (optionally with modified input)\n * - `block` — don't execute; return `reason` as the tool result so the model can adjust\n * - `substitute` — don't execute; return `output` as the tool result (afterToolCall still fires)\n */\nexport type ToolCallDecision =\n | {\n action: \"allow\";\n /** Modified input — tool executes with this instead of the original. */\n input?: Record<string, unknown>;\n }\n | {\n action: \"block\";\n /** Returned as the tool result so the model can adjust. */\n reason?: string;\n }\n | {\n action: \"substitute\";\n /** The substitute tool output — model sees this instead of real execution. */\n output: unknown;\n /** Optional input attribution for the afterToolCall log. */\n input?: Record<string, unknown>;\n };\n\n/**\n * Context passed to the `afterToolCall` hook after a tool executes.\n *\n * Backed by the AI SDK's `OnToolCallFinishEvent` (the parameter of\n * `experimental_onToolCallFinish`). The full `TypedToolCall<TOOLS>`\n * fields (`toolName`, `toolCallId`, `input`, …) are spread at the top\n * level, plus the per-call event extras:\n *\n * - `stepNumber` — index of the current step\n * - `messages` — conversation messages visible at tool execution time\n * - `durationMs` — wall-clock execution time in milliseconds\n * - `success`/`output`/`error` — discriminated outcome:\n * - on success: `success: true`, `output: unknown`\n * - on failure: `success: false`, `error: unknown`\n *\n * Pass an explicit `TOOLS` generic for full input typing:\n *\n * ```ts\n * import type { ToolCallResultContext } from \"@cloudflare/think\";\n * import type { tools } from \"./my-tools\";\n *\n * afterToolCall(ctx: ToolCallResultContext<typeof tools>) {\n * if (ctx.success) {\n * console.log(`${ctx.toolName} took ${ctx.durationMs}ms`, ctx.output);\n * } else {\n * console.error(`${ctx.toolName} failed:`, ctx.error);\n * }\n * }\n * ```\n */\nexport type ToolCallResultContext<TOOLS extends ToolSet = ToolSet> =\n TypedToolCall<TOOLS> & {\n readonly stepNumber: number | undefined;\n readonly messages: ReadonlyArray<ModelMessage>;\n /** Wall-clock execution time in milliseconds. */\n readonly durationMs: number;\n } & (\n | {\n readonly success: true;\n readonly output: unknown;\n readonly error?: never;\n }\n | {\n readonly success: false;\n readonly output?: never;\n readonly error: unknown;\n }\n );\n\n/**\n * Context passed to the `onStepFinish` hook after each step completes.\n *\n * This is the AI SDK's `StepResult<TOOLS>` (= `OnStepFinishEvent<TOOLS>`) —\n * the full step record including `text`, `reasoning`, `toolCalls`,\n * `toolResults`, `files`, `sources`, `usage` (with `cachedInputTokens`,\n * `reasoningTokens`, `totalTokens`), `finishReason`, `warnings`, `request`,\n * `response`, and `providerMetadata` (where provider-specific cache\n * accounting like `cacheCreationInputTokens` lives).\n *\n * Pass an explicit `TOOLS` generic for typed `toolCalls`/`toolResults`.\n */\nexport type StepContext<TOOLS extends ToolSet = ToolSet> = Parameters<\n StreamTextOnStepFinishCallback<TOOLS>\n>[0];\n\n/**\n * Context passed to the `onChunk` hook for each streaming chunk.\n *\n * This is the AI SDK's `StreamTextOnChunkCallback` event — `{ chunk }`\n * where `chunk` is a discriminated union of `TextStreamPart` variants\n * (text-delta, reasoning-delta, source, tool-call, tool-input-start,\n * tool-input-delta, tool-result, raw).\n */\nexport type ChunkContext<TOOLS extends ToolSet = ToolSet> = Parameters<\n StreamTextOnChunkCallback<TOOLS>\n>[0];\n\n/**\n * @internal Re-export of the chunk variant union for consumers that need\n * to narrow on `chunk.type` without importing `TextStreamPart` directly.\n */\nexport type ChunkPart<TOOLS extends ToolSet = ToolSet> =\n ChunkContext<TOOLS>[\"chunk\"];\n\n/**\n * Configuration for a sandboxed extension, returned by getExtensions().\n */\nexport interface ExtensionConfig {\n /** Extension manifest (name, version, permissions, contributions). */\n manifest: import(\"./extensions/types\").ExtensionManifest;\n /** JavaScript source code defining the extension's tools. */\n source: string;\n}\n\nconst TIMED_OUT = Symbol(\"timed-out\");\n\n/**\n * An opinionated chat agent base class.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class Think<\n Env extends Cloudflare.Env = Cloudflare.Env,\n State = unknown,\n Props extends Record<string, unknown> = Record<string, unknown>\n> extends Agent<Env, State, Props> {\n // Root requestId of the in-flight recovery chain, threaded into each\n // continuation's snapshot so chained continuations keep owning the original\n // submission. This is a single instance field, NOT per-incident: it is only\n // safe because turns (and recovery fibers) are serialized by the turn queue,\n // so at most one recovery chain is active at a time. The `try/finally`\n // restore in `_chatRecoveryRetry` / `_chatRecoveryContinue` returns it to the\n // prior value once a continuation settles. If turns ever run concurrently,\n // this must move to per-incident storage.\n private _activeChatRecoveryRootRequestId: string | undefined;\n\n private static readonly CONFIG_KEYS = [\n \"_think_config\",\n \"lastClientTools\",\n \"lastBody\",\n \"skillsFingerprint\"\n ] as const;\n /**\n * Wait for MCP server connections to be ready before the inference\n * loop. MCP tools are auto-merged into the tool set.\n *\n * Set to `true` for a default 10s timeout, or `{ timeout: ms }`\n * for a custom timeout. Defaults to `false` (no waiting).\n */\n waitForMcpConnections: boolean | { timeout: number } = false;\n\n private _skillRegistry: SkillRegistry | null = null;\n private _loggedSkillWarnings = new Set<string>();\n\n /**\n * Controls how overlapping user submit requests behave while another\n * chat turn is already active or queued.\n *\n * @default \"queue\"\n */\n messageConcurrency: MessageConcurrency = \"queue\";\n\n /**\n * When true, chat turns are wrapped in `runFiber` for durable execution.\n * Enables `onChatRecovery` hook and `this.stash()` during streaming.\n */\n chatRecovery: ChatRecoveryConfig = true;\n\n static readonly CHAT_FIBER_NAME = \"__cf_internal_chat_turn\";\n\n /**\n * The conversation session — messages, context, compaction, search.\n *\n * Direct message writes are observed and mirrored into Think's live cache.\n * Prefer the history helpers below when writing UI messages from subclasses;\n * they sanitize content and enforce row-size limits before delegating here.\n */\n session!: Session;\n\n /** Cached messages — kept in sync with session storage. */\n private _cachedMessages: UIMessage[] = [];\n\n private _activeMessengerContext?: MessengerContext;\n\n private _messengerRuntime?: ThinkMessengerRuntime;\n\n /**\n * WorkerLoader binding for sandboxed extensions.\n * Set this to enable `getExtensions()` and dynamic extension loading.\n */\n extensionLoader?: WorkerLoader;\n\n /**\n * Extension manager — created automatically when `extensionLoader` is set.\n * Use for dynamic `load()` / `unload()` at runtime.\n */\n extensionManager?: import(\"./extensions/manager\").ExtensionManager;\n\n /**\n * Workspace filesystem available in `getTools()` and lifecycle hooks.\n * Defaults to a full `Workspace` backed by the DO's SQLite storage.\n *\n * Typed as `WorkspaceLike` rather than `Workspace` so subclasses can\n * replace it with anything that satisfies the interface — e.g. a proxy\n * that forwards to a shared workspace owned by a parent DO. Override as\n * a class field to skip the default init entirely:\n *\n * ```typescript\n * // Default init with R2 spillover for large files.\n * override workspace = new Workspace({\n * sql: this.ctx.storage.sql,\n * r2: this.env.R2,\n * name: () => this.name\n * });\n *\n * // Or a custom WorkspaceLike — e.g. a parent-owned shared workspace.\n * override workspace: WorkspaceLike = new SharedWorkspace(this);\n * ```\n */\n workspace!: WorkspaceLike;\n\n /**\n * Include the default workspace Bash tool. Enabled by default so models can\n * run shell-style multi-file workflows against the workspace. Set to `false`\n * to omit it from the built-in workspace tools.\n */\n workspaceBash:\n | boolean\n | NonNullable<Parameters<typeof createWorkspaceTools>[1]>[\"bash\"] = true;\n\n constructor(ctx: DurableObjectState, env: Env) {\n super(ctx, env);\n\n const _onStart = this.onStart.bind(this);\n this.onStart = async () => {\n // 1. Workspace initialization\n if (!this.workspace) {\n this.workspace = new Workspace({\n sql: this.ctx.storage.sql,\n name: () => this.name\n });\n }\n\n // 2. Session configuration (builder phase — context blocks, compaction, skills)\n const baseSession = Session.create(this);\n this.session = await this.configureSession(baseSession);\n this.session.internal_onMessagesChanged(async (event) => {\n switch (event.type) {\n case \"append\":\n if (!event.inserted || event.parentId !== undefined) {\n await this._syncMessages();\n } else {\n this._upsertCachedMessage(event.message as UIMessage);\n }\n break;\n case \"update\":\n this._patchCachedMessage(event.message as UIMessage);\n break;\n case \"clear\":\n this._replaceCachedMessages([]);\n break;\n case \"delete\":\n case \"compact\":\n await this._syncMessages();\n break;\n }\n });\n\n await this._initializeSkills();\n\n // Force Session to initialize its tables (assistant_messages,\n // assistant_compactions, assistant_config, etc.) so that subsequent\n // config reads work.\n await this._syncMessages();\n\n // 3-6. Extension initialization (if extensionLoader is set)\n if (this.extensionLoader) {\n await this._initializeExtensions();\n }\n\n // 7. Protocol handlers\n this._resumableStream = new ResumableStream(this.sql.bind(this));\n this._restoreClientTools();\n this._restoreBody();\n this._setupProtocolHandlers();\n this._initializeMessengers();\n\n // 8. User's onStart\n await _onStart();\n\n // 9. Declarative scheduled tasks are code-defined and should reconcile\n // before draining any recovered programmatic work they may enqueue.\n await this._reconcileDeclaredScheduledTasks();\n\n // 10. Durable submissions may run user-defined model/hooks, so start them\n // after subclass initialization has completed.\n await this._recoverSubmissionsOnStart();\n this._recoverWorkflowNotifications();\n this._startSubmissionDrain();\n this._startWorkflowNotificationDrain();\n };\n }\n\n /**\n * Conversation history as Think's live in-memory view.\n *\n * Storage remains the durable source of truth, but runtime logic should read\n * through this cache so in-flight turns, tool updates, and recovery state all\n * observe the same message list. Use `_syncMessages()` only at safe\n * boundaries where a full storage reread cannot drop in-flight state.\n */\n get messages(): UIMessage[] {\n return this._cachedMessages;\n }\n\n /** Read the durable message path from session storage. */\n private async _readMessagesFromStorage(): Promise<UIMessage[]> {\n return (await this.session.getHistory()) as UIMessage[];\n }\n\n /**\n * Normalize a tool part's `input` into something the provider will accept.\n *\n * Two malformed shapes 400 modern providers (and persist forever once\n * written): a stringified-JSON `input` (e.g. `'{\"prompt\":\"a cat\"}'` instead\n * of the object) and a missing/`null` `input` on a settled or interrupted\n * tool call (Anthropic rejects a `tool_use` block whose `input` is absent).\n * We parse the former and default the latter to an empty object so the\n * tool-call/tool-result pair stays valid. Any other value is left untouched.\n */\n private _normalizeToolInput(record: Record<string, unknown>): {\n input: unknown;\n changed: boolean;\n } {\n const raw = \"input\" in record ? record.input : undefined;\n if (typeof raw === \"string\") {\n const trimmed = raw.trim();\n // Stringified JSON object or array — parse back into structured input.\n if (trimmed.startsWith(\"{\") || trimmed.startsWith(\"[\")) {\n try {\n return { input: JSON.parse(raw) as unknown, changed: true };\n } catch {\n return { input: raw, changed: false };\n }\n }\n }\n if (raw === undefined || raw === null) {\n return { input: {}, changed: true };\n }\n return { input: raw, changed: false };\n }\n\n /**\n * Whether a tool part already has a settled result the provider accepts, so\n * it must NOT be re-repaired into an errored result.\n *\n * Single source of truth for the terminal tool states, shared by the repair\n * pass and the backstop detector so they cannot drift. Mirror the AI SDK's\n * terminal states: `convertToModelMessages` emits a `tool-result` for\n * `output-available`, `output-error`, AND `output-denied` (a user-denied\n * approval — its denial reason becomes the tool-result). Omitting any of\n * these makes repair re-flip the part every turn — clobbering a real\n * `errorText`/denial with the generic \"interrupted\" message — and makes the\n * backstop falsely drop a valid call.\n */\n private _toolPartHasSettledResult(record: Record<string, unknown>): boolean {\n if (\"output\" in record || \"result\" in record) return true;\n const state = typeof record.state === \"string\" ? record.state : \"\";\n return (\n state === \"output-available\" ||\n state === \"output-error\" ||\n state === \"output-denied\"\n );\n }\n\n /**\n * Tool-call ids that still have no recorded result. After repair this should\n * be empty; a non-empty result means the backstop (`ignoreIncompleteToolCalls`)\n * will drop those calls — i.e. repair missed a shape and should be extended.\n *\n * `approval-responded` is deliberately excluded: an approved server tool has\n * no result *yet*, but it is not incomplete or abandoned — it is waiting for\n * its continuation to run `execute()`. `convertToModelMessages` keeps that\n * call (and the SDK executes it), so flagging it here would log a misleading\n * \"repair gap\" warning and emit a spurious `chat:transcript:repaired` event\n * on every approval continuation.\n */\n private _incompleteToolCallIds(messages: UIMessage[]): string[] {\n const ids: string[] = [];\n for (const message of messages) {\n for (const part of message.parts) {\n const record = part as Record<string, unknown>;\n const toolCallId =\n typeof record.toolCallId === \"string\" ? record.toolCallId : undefined;\n const isToolPart =\n typeof record.type === \"string\" &&\n (record.type.startsWith(\"tool-\") || record.type === \"dynamic-tool\") &&\n toolCallId;\n if (!isToolPart) continue;\n if (record.state === \"approval-responded\") continue;\n if (!this._toolPartHasSettledResult(record)) ids.push(toolCallId);\n }\n }\n return ids;\n }\n\n /**\n * Repair a single interrupted tool call — a tool part with no settled result,\n * left behind when a stream was cut off mid-flight. Returns the replacement\n * part that takes its place in the transcript. `input` has already been\n * normalized to a valid object.\n *\n * The default flips it to an errored tool result so the record survives (no\n * \"disappearing\" tool call) and `convertToModelMessages` still gets a\n * tool-result for it (avoiding `AI_MissingToolResultsError`).\n *\n * Override to customize the repaired shape for client-resolved tools — e.g.\n * convert an interrupted `ask_user` (a question with no server `execute`,\n * normally answered by the user's next message) into a plain text part\n * carrying the question prose, so the model sees it as ordinary conversation\n * rather than a tool error and compaction keeps the question verbatim. This\n * runs DURING transcript repair — before the repaired transcript is persisted\n * and sent to the model — so the conversion shapes the current turn, not just\n * the next one. A returned tool part MUST carry a settled result\n * (`output-available` / `output-error` / `output-denied` or an\n * `output`/`result` field); returning a non-tool part (e.g. text) is fine.\n */\n protected repairInterruptedToolPart(\n part: UIMessage[\"parts\"][number]\n ): UIMessage[\"parts\"][number] {\n return {\n ...part,\n state: \"output-error\",\n errorText: \"The tool call was interrupted before a result was recorded.\"\n } as UIMessage[\"parts\"][number];\n }\n\n private _repairToolTranscriptParts(messages: UIMessage[]): {\n messages: UIMessage[];\n removedToolCalls: number;\n normalizedInputs: number;\n toolCallIds: string[];\n } {\n let removedToolCalls = 0;\n let normalizedInputs = 0;\n const toolCallIds: string[] = [];\n const repaired: UIMessage[] = [];\n\n for (const message of messages) {\n const parts: UIMessage[\"parts\"] = [];\n let messageChanged = false;\n for (const part of message.parts) {\n const record = part as Record<string, unknown>;\n const toolCallId =\n typeof record.toolCallId === \"string\" ? record.toolCallId : undefined;\n const isToolPart =\n typeof record.type === \"string\" &&\n (record.type.startsWith(\"tool-\") || record.type === \"dynamic-tool\") &&\n toolCallId;\n if (!isToolPart) {\n parts.push(part);\n continue;\n }\n\n if (!this._toolPartHasSettledResult(record)) {\n const state = typeof record.state === \"string\" ? record.state : \"\";\n // An approved server tool waits at `approval-responded` until its\n // scheduled continuation runs `execute()`. It is not abandoned, so\n // preserve it verbatim — flipping it to an error (or removing it)\n // would strand the approval and prevent the real result from ever\n // being produced by the continuation.\n if (state === \"approval-responded\") {\n parts.push(part);\n continue;\n }\n // Preserve the interrupted/abandoned tool call instead of deleting\n // it. Deleting makes the call \"disappear\" from the (broadcast)\n // transcript and lets the model silently re-run it. `input` is\n // normalized to a valid object first, then `repairInterruptedToolPart`\n // decides the replacement shape (default: an errored result, so\n // conversion still gets a tool-result and the provider doesn't 400\n // with AI_MissingToolResultsError). Subclasses can override it to\n // preserve client-resolved tools (e.g. `ask_user`) as text.\n const normalized = this._normalizeToolInput(record);\n parts.push(\n this.repairInterruptedToolPart({\n ...part,\n input: normalized.input\n } as UIMessage[\"parts\"][number])\n );\n if (normalized.changed) normalizedInputs++;\n removedToolCalls++;\n messageChanged = true;\n toolCallIds.push(toolCallId);\n continue;\n }\n\n const normalized = this._normalizeToolInput(record);\n if (normalized.changed) {\n parts.push({\n ...part,\n input: normalized.input\n } as UIMessage[\"parts\"][number]);\n normalizedInputs++;\n messageChanged = true;\n continue;\n }\n\n parts.push(part);\n }\n\n repaired.push(messageChanged ? { ...message, parts } : message);\n }\n\n return {\n messages: repaired,\n removedToolCalls,\n normalizedInputs,\n toolCallIds\n };\n }\n\n private async _repairTranscriptForProvider(\n messages: UIMessage[]\n ): Promise<UIMessage[]> {\n const repair = this._repairToolTranscriptParts(messages);\n if (repair.removedToolCalls === 0 && repair.normalizedInputs === 0) {\n return messages;\n }\n\n // Repair preserves every message (orphans are flipped to errored in place,\n // never deleted), so there are no removed rows to delete — only updates.\n for (const message of repair.messages) {\n const original = messages.find(\n (candidate) => candidate.id === message.id\n );\n if (original && original.parts !== message.parts) {\n await this.session.updateMessage(sanitizeMessage(message));\n }\n }\n\n this._replaceCachedMessages(repair.messages);\n this._broadcastMessages();\n this._emit(\"chat:transcript:repaired\", {\n removedToolCalls: repair.removedToolCalls,\n normalizedInputs: repair.normalizedInputs,\n toolCallIds: repair.toolCallIds\n });\n return repair.messages;\n }\n\n /** Replace the live cache with a durable storage snapshot. */\n private _replaceCachedMessages(messages: UIMessage[]): UIMessage[] {\n this._cachedMessages = messages;\n return this._cachedMessages;\n }\n\n /** Refresh the live cache from durable storage at a safe boundary. */\n private async _syncMessages(): Promise<UIMessage[]> {\n return this._replaceCachedMessages(await this._readMessagesFromStorage());\n }\n\n /** Patch or append one message in the live cache after a durable write. */\n private _upsertCachedMessage(message: UIMessage): void {\n const index = this._cachedMessages.findIndex((m) => m.id === message.id);\n if (index === -1) {\n this._cachedMessages.push(message);\n } else {\n this._cachedMessages[index] = message;\n }\n }\n\n /** Patch a message that is already present in the live cache. */\n private _patchCachedMessage(message: UIMessage): void {\n const index = this._cachedMessages.findIndex((m) => m.id === message.id);\n if (index !== -1) {\n this._cachedMessages[index] = message;\n }\n }\n\n private async _appendMessageToHistory(\n message: UIMessage,\n parentId?: string | null\n ): Promise<UIMessage> {\n const safe = enforceRowSizeLimit(sanitizeMessage(message));\n await this.session.appendMessage(safe, parentId);\n return safe;\n }\n\n private async _updateMessageInHistory(\n message: UIMessage\n ): Promise<UIMessage> {\n const safe = enforceRowSizeLimit(sanitizeMessage(message));\n await this.session.updateMessage(safe);\n return safe;\n }\n\n private async _upsertMessageInHistory(\n message: UIMessage,\n parentId?: string | null\n ): Promise<UIMessage> {\n const safe = enforceRowSizeLimit(sanitizeMessage(message));\n const existing = await this.session.getMessage(safe.id);\n if (existing) {\n await this.session.updateMessage(safe);\n } else {\n await this.session.appendMessage(safe, parentId);\n }\n return safe;\n }\n\n private async _clearHistory(): Promise<void> {\n await this.session.clearMessages();\n }\n\n /** Append a message while keeping Think's live message cache coherent. */\n protected appendMessageToHistory(\n message: UIMessage,\n parentId?: string | null\n ): Promise<UIMessage> {\n return this._appendMessageToHistory(message, parentId);\n }\n\n /** Update a message while keeping Think's live message cache coherent. */\n protected updateMessageInHistory(message: UIMessage): Promise<UIMessage> {\n return this._updateMessageInHistory(message);\n }\n\n /** Refresh Think's live message cache from the durable session path. */\n protected async syncMessagesFromStorage(): Promise<UIMessage[]> {\n return (await this._syncMessages()).slice();\n }\n\n private _aborts = new AbortRegistry();\n private _turnQueue = new TurnQueue();\n protected _resumableStream!: ResumableStream;\n private _pendingResumeConnections: Set<string> = new Set();\n private _lastClientTools: ClientToolSchema[] | undefined;\n private _lastBody: Record<string, unknown> | undefined;\n private _continuation = new ContinuationState<Connection>();\n private _continuationTimer: ReturnType<typeof setTimeout> | null = null;\n // True while a continuation is parked on the parallel-tool-batch barrier\n // (#1649) waiting for in-flight tool results/approvals to settle. Prevents a\n // second barrier wait (and a double-fire) when more results arrive mid-wait.\n private _continuationBarrierActive = false;\n private _insideResponseHook = false;\n private _insideInferenceLoop = false;\n private _pendingInteractionPromise: Promise<boolean> | null = null;\n private _submitConcurrency = new SubmitConcurrencyController({\n defaultDebounceMs: Think.MESSAGE_DEBOUNCE_MS\n });\n private static MESSAGE_DEBOUNCE_MS = 750;\n private _agentToolForwarders = new Map<\n string,\n Set<(chunk: AgentToolStoredChunk) => void>\n >();\n private _agentToolClosers = new Map<string, Set<() => void>>();\n private _agentToolAbortControllers = new Map<string, AbortController>();\n private _agentToolLastErrors = new Map<string, string>();\n private _agentToolPreTurnAssistantIds = new Map<string, Set<string>>();\n private _agentToolLiveSequences = new Map<string, number>();\n private _submissionTableEnsured = false;\n private _workflowNotificationTableEnsured = false;\n private _declaredScheduledTasksTableEnsured = false;\n private _drainingSubmissions = false;\n private _drainingWorkflowNotifications = false;\n private _submissionAbortControllers = new Map<string, AbortController>();\n private _programmaticStreamErrors = new Map<string, string>();\n protected static submissionRecoveryStaleMs = 15 * 60 * 1000;\n\n override broadcast(\n msg: string | ArrayBuffer | ArrayBufferView,\n without?: string[]\n ): void {\n if (this._agentToolForwarders.size > 0 && typeof msg === \"string\") {\n try {\n const parsed = JSON.parse(msg) as {\n type?: unknown;\n body?: unknown;\n error?: unknown;\n };\n if (parsed.type === MSG_CHAT_RESPONSE) {\n if (parsed.error === true && typeof parsed.body === \"string\") {\n for (const runId of this._agentToolForwarders.keys()) {\n this._agentToolLastErrors.set(runId, parsed.body);\n }\n } else if (\n typeof parsed.body === \"string\" &&\n parsed.body.length > 0\n ) {\n for (const [runId, forwarders] of this._agentToolForwarders) {\n const sequence = this._agentToolLiveSequences.get(runId) ?? 0;\n this._agentToolLiveSequences.set(runId, sequence + 1);\n const chunk = { sequence, body: parsed.body };\n for (const forward of forwarders) forward(chunk);\n }\n }\n }\n } catch {\n // Non-chat frames pass through unchanged.\n }\n }\n super.broadcast(msg, without);\n }\n\n override async alarm(): Promise<void> {\n await super.alarm();\n this._startWorkflowNotificationDrain();\n }\n\n // ── Dynamic config ──────────────────────────────────────────────\n\n #configCache: unknown = null;\n\n /**\n * Persist an arbitrary JSON-serializable configuration object for this\n * agent instance. Stored in the Think-private `think_config` table —\n * survives\n * restarts and hibernation. Pass the config shape as a method generic\n * for typed call sites:\n *\n * ```ts\n * this.configure<MyConfig>({ modelTier: \"fast\" });\n * ```\n *\n * Prefer `state` / `setState` from `Agent` when you want the value\n * broadcast to connected clients. Use `configure` for private\n * per-instance config that should stay server-side.\n */\n configure<T = Record<string, unknown>>(config: T): void {\n const json = JSON.stringify(config);\n this._configSet(\"_think_config\", json);\n this.#configCache = config;\n }\n\n /**\n * Read the persisted configuration, or null if never configured.\n * Pass the config shape as a method generic for a typed result:\n *\n * ```ts\n * const cfg = this.getConfig<MyConfig>();\n * ```\n */\n getConfig<T = Record<string, unknown>>(): T | null {\n if (this.#configCache !== null) return this.#configCache as T;\n const raw = this._configGet(\"_think_config\");\n if (raw !== undefined) {\n this.#configCache = JSON.parse(raw);\n return this.#configCache as T;\n }\n return null;\n }\n\n // ── Config storage helpers (think_config table) ─────────────────\n\n #configTableReady = false;\n\n protected _migrateLegacyConfigToThinkTable(): void {\n const rows = this.ctx.storage.sql\n .exec(\n \"SELECT sql FROM sqlite_master WHERE type='table' AND name='assistant_config'\"\n )\n .toArray() as Array<{ sql?: unknown }>;\n if (rows.length === 0) return;\n\n const ddl = String(rows[0].sql ?? \"\");\n if (!ddl.includes(\"session_id\")) return;\n\n // Older Think builds stored private config in Session's shared\n // `assistant_config(session_id, key, value)` table, even though\n // Think always used the empty session id. Copy only the Think-owned\n // keys into the dedicated `think_config` table and leave the shared\n // Session table untouched.\n for (const key of Think.CONFIG_KEYS) {\n const legacyRows = this.sql<{ value: string }>`\n SELECT value FROM assistant_config\n WHERE session_id = '' AND key = ${key}\n `;\n const value = legacyRows[0]?.value;\n if (value !== undefined) {\n this.sql`\n INSERT OR IGNORE INTO think_config (key, value)\n VALUES (${key}, ${value})\n `;\n }\n }\n }\n\n private _ensureConfigTable(): void {\n if (this.#configTableReady) return;\n this.sql`\n CREATE TABLE IF NOT EXISTS think_config (\n key TEXT NOT NULL,\n value TEXT NOT NULL,\n PRIMARY KEY (key)\n )\n `;\n this._migrateLegacyConfigToThinkTable();\n this.#configTableReady = true;\n }\n\n private _configSet(key: string, value: string): void {\n this._ensureConfigTable();\n this.sql`\n INSERT OR REPLACE INTO think_config (key, value)\n VALUES (${key}, ${value})\n `;\n }\n\n private _configGet(key: string): string | undefined {\n this._ensureConfigTable();\n const rows = this.sql<{ value: string }>`\n SELECT value FROM think_config\n WHERE key = ${key}\n `;\n return rows[0]?.value;\n }\n\n private _configDelete(key: string): void {\n this._ensureConfigTable();\n this.sql`\n DELETE FROM think_config\n WHERE key = ${key}\n `;\n }\n\n // ── Configuration overrides ─────────────────────────────────────\n\n /**\n * Return the language model to use for inference.\n * Must be overridden by subclasses.\n */\n getModel(): LanguageModel {\n throw new Error(\"Override getModel() to return a LanguageModel.\");\n }\n\n /**\n * Return the system prompt for the assistant.\n * Used as fallback when no context blocks are configured via `configureSession`.\n */\n getSystemPrompt(): string {\n return [\n \"You are a careful, capable assistant helping the user complete their task.\",\n \"Use available tools when they materially improve accuracy or let you act on the user's request. Before changing code, understand the relevant context: existing patterns, dependencies, tests, and nearby conventions.\",\n \"Keep changes focused on the user's request. Prefer small, idiomatic edits over broad rewrites or new abstractions. Do not introduce new dependencies, secrets, destructive actions, or persistent side effects unless the user clearly asks or approves.\",\n \"When the task is complex, briefly state your approach and keep the user informed with concise progress updates. If you modify code, verify with the smallest relevant test, build, typecheck, lint, or runtime check available, and report any checks you could not run.\",\n \"Be direct and useful in your final response: summarize the outcome, mention important files or commands, and call out real blockers or risks.\"\n ].join(\"\\n\\n\");\n }\n\n /** Return the tools available to the assistant. */\n getTools(): ToolSet {\n return {};\n }\n\n /** Return messenger integrations that should be routed through this Think agent. */\n getMessengers(): ThinkMessengers {\n return {};\n }\n\n getMessengerContext(): MessengerContext | undefined {\n if (this._activeMessengerContext) {\n return this._activeMessengerContext;\n }\n\n const message = this.messages.at(-1) as\n | (UIMessage & { metadata?: { messenger?: MessengerContext } })\n | undefined;\n return message?.metadata?.messenger;\n }\n\n async chatWithMessengerContext(\n userMessage: string | UIMessage,\n callback: StreamCallback,\n context: MessengerContext,\n options?: ChatOptions\n ): Promise<void> {\n const previous = this._activeMessengerContext;\n this._activeMessengerContext = context;\n try {\n await this.chat(userMessage, callback, options);\n } finally {\n this._activeMessengerContext = previous;\n }\n }\n\n private _initializeMessengers(): void {\n if (this.parentPath.length > 0) {\n return;\n }\n\n const messengers = this.getMessengers();\n if (Object.keys(messengers).length === 0) {\n return;\n }\n\n this._messengerRuntime = new ThinkMessengerRuntime(\n messengers,\n this as unknown as MessengerThinkHost\n );\n this._messengerRuntime.initialize();\n }\n\n /** Return code-declared scheduled tasks for this agent. */\n getScheduledTasks(): ThinkScheduledTasks | Promise<ThinkScheduledTasks> {\n return {};\n }\n\n /**\n * Reconcile code-declared scheduled tasks immediately.\n * Static declarations are reconciled on startup automatically; call this\n * after changing app-owned data that `getScheduledTasks()` reads.\n */\n async internal_reconcileScheduledTasks(): Promise<void> {\n await this._reconcileDeclaredScheduledTasks();\n }\n\n /**\n * Return the default timezone for wall-clock scheduled tasks.\n * Task-local timezone declarations take precedence.\n */\n getDefaultTimezone(): string | undefined | Promise<string | undefined> {\n return undefined;\n }\n\n private async _runChatRecoveryFiber<T>(\n requestId: string,\n continuation: boolean,\n fn: () => Promise<T>\n ): Promise<T> {\n const snapshot = createChatFiberSnapshot({\n kind: \"think-chat-turn\",\n requestId,\n recoveryRootRequestId: this._activeChatRecoveryRootRequestId ?? requestId,\n continuation,\n messages: this.messages,\n lastBody: this._lastBody,\n lastClientTools: this._lastClientTools\n });\n\n return this._runFiberWithStashWrapper(\n `${(this.constructor as typeof Think).CHAT_FIBER_NAME}:${requestId}`,\n async () => fn(),\n {\n initialSnapshot: wrapChatFiberSnapshot(\n \"__cfThinkChatFiberSnapshot\",\n snapshot,\n null\n ),\n wrapStash: (data) =>\n wrapChatFiberSnapshot(\"__cfThinkChatFiberSnapshot\", snapshot, data)\n }\n );\n }\n\n private _systemPromptForTurn(baseSystem: string, tools: ToolSet): string {\n if (baseSystem.includes(\"You are running inside a Think agent.\")) {\n return baseSystem;\n }\n\n return `${baseSystem.trimEnd()}\\n\\n${this._buildThinkCapabilityBlock(tools)}`;\n }\n\n private _buildThinkCapabilityBlock(tools: ToolSet): string {\n const toolNames = new Set(Object.keys(tools));\n const hasTools = toolNames.size > 0;\n const hasWorkspaceTools = [\n \"read\",\n \"write\",\n \"edit\",\n \"list\",\n \"find\",\n \"grep\",\n \"delete\"\n ].some((toolName) => toolNames.has(toolName));\n const hasContextTools =\n toolNames.has(\"load_context\") || toolNames.has(\"unload_context\");\n const hasExtensionTools =\n toolNames.has(\"load_extension\") || toolNames.has(\"list_extensions\");\n const hasExecuteTool = toolNames.has(\"execute\");\n\n const lines = [\n \"You are running inside a Think agent.\",\n \"\",\n \"Capabilities available in this turn:\"\n ];\n\n if (hasWorkspaceTools) {\n lines.push(\n \"- You can inspect and edit the agent workspace using the available file tools.\"\n );\n }\n\n if (hasTools) {\n lines.push(\n \"- Use the tools exposed in this turn when they materially improve accuracy or let you act on the user's request. Treat tool descriptions and schemas as the source of truth.\"\n );\n lines.push(\n \"- Some tools may call server code, browser/client code, MCP servers, extensions, or delegated agents. Use them according to their descriptions.\"\n );\n }\n\n if (hasContextTools) {\n lines.push(\n \"- If context-loading tools are available, use them to load relevant memory, skills, or project context before acting on incomplete information.\"\n );\n }\n\n if (hasExtensionTools) {\n lines.push(\n \"- If extension tools are available, use them only when loading or inspecting extensions directly helps with the task.\"\n );\n }\n\n if (hasExecuteTool) {\n lines.push(\n \"- If sandboxed execution is available, prefer it for safe, bounded checks or coordinated multi-step operations.\"\n );\n }\n\n lines.push(\n \"- Do not claim access to capabilities that are not exposed as tools in this turn.\"\n );\n\n return lines.join(\"\\n\");\n }\n\n /** Maximum number of tool-call steps per turn. Override via property or per-turn via TurnConfig. */\n maxSteps = 10;\n\n /**\n * Whether reasoning chunks are sent to chat clients by default. Override\n * per turn by returning `sendReasoning` from `beforeTurn`.\n */\n sendReasoning = true;\n\n /**\n * Inactivity watchdog for the streaming read loop, in milliseconds.\n *\n * If a turn's model stream produces no chunk for this long, the watchdog\n * aborts the turn and surfaces a terminal stream error instead of letting the\n * loop park forever on a hung provider/transport (the \"infinite spinner\"\n * failure: the stream never throws, so no error and no `done` ever arrives).\n * A `chat:stream:stalled` observability event is emitted when it fires.\n *\n * This measures the gap *between UI-message-stream chunks*, which includes\n * time spent executing server-side tools (no chunks flow while a tool runs).\n * Set it comfortably above your slowest expected model time-to-first-token\n * and your slowest tool execution, or you will abort healthy long turns.\n *\n * Default `0` (disabled) — opt in by setting a value (e.g. `120_000`).\n *\n * Can be overridden per-turn via `TurnConfig.chatStreamStallTimeoutMs`\n * (returned from `beforeTurn`) for turns with known-slow tools.\n */\n chatStreamStallTimeoutMs = 0;\n\n /**\n * Per-turn stall-watchdog timeout resolved from `TurnConfig` in\n * `_runInferenceLoop`, read by the stream loop when arming the watchdog.\n * `undefined` falls back to the instance-level `chatStreamStallTimeoutMs`.\n * Turns are serialized, so a single active value is safe; it is reset at the\n * top of every `_runInferenceLoop`.\n */\n private _activeStallTimeoutMs: number | undefined;\n\n /**\n * Configure the session. Called once during `onStart`.\n * Override to add context blocks, compaction, search, skills.\n *\n * @example\n * ```typescript\n * configureSession(session: Session) {\n * return session\n * .withContext(\"memory\", { description: \"Learned facts\", maxTokens: 2000 })\n * .withCachedPrompt();\n * }\n * ```\n */\n configureSession(session: Session): Session | Promise<Session> {\n return session;\n }\n\n /**\n * Return Agent Skills sources for this Think agent.\n *\n * Bundled skills are typically imported with the Agents Vite plugin:\n *\n * ```typescript\n * import productSkills from \"agents:skills\"; // -> ./skills next to this file\n * ```\n *\n * Sources are applied in order; the first source to register a skill name\n * wins, and later collisions are skipped with a logged warning.\n */\n getSkills(): SkillSource[] | Promise<SkillSource[]> {\n return [];\n }\n\n private async _initializeSkills(): Promise<void> {\n // A misconfigured or failing skill source must never prevent the agent\n // from starting. Any error here is logged and skills stay disabled.\n try {\n const sources = await this.getSkills();\n if (sources.length === 0) return;\n\n const registry = new SkillRegistry(sources, this.getSkillScriptRunner());\n await registry.load();\n this._logSkillWarnings(registry);\n this._skillRegistry = registry;\n\n await this.session.addContext(registry.contextLabel, {\n description: \"Think skills: available skill catalog\",\n provider: {\n get: () => registry.systemPrompt()\n }\n });\n\n const previous = this._configGet(\"skillsFingerprint\");\n if (previous !== registry.fingerprint) {\n await this.session.refreshSystemPrompt();\n this._configSet(\"skillsFingerprint\", registry.fingerprint);\n }\n } catch (error) {\n console.warn(\n `[think] Failed to initialize skills; continuing without them: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n /**\n * Log registry diagnostics (duplicate names, sources that failed to list),\n * deduped by message so a new collision after a deploy still surfaces while\n * the same warning is not repeated on every turn.\n */\n private _logSkillWarnings(registry: SkillRegistry): void {\n for (const warning of registry.warnings) {\n if (this._loggedSkillWarnings.has(warning)) continue;\n this._loggedSkillWarnings.add(warning);\n console.warn(`[think] ${warning}`);\n }\n }\n\n /**\n * Return an optional runner that enables the `run_skill_script` tool.\n *\n * @experimental Skill script execution is experimental and may change\n * before stabilizing.\n */\n getSkillScriptRunner(): SkillScriptRunner | null {\n return null;\n }\n\n private async _refreshSkillsIfChanged(): Promise<void> {\n if (!this._skillRegistry) return;\n\n // Refreshing pulls from live sources (e.g. R2); a transient failure must\n // not break the turn. Keep the last good catalog on error.\n try {\n await this._skillRegistry.refresh();\n this._logSkillWarnings(this._skillRegistry);\n const previous = this._configGet(\"skillsFingerprint\");\n if (previous !== this._skillRegistry.fingerprint) {\n await this.session.refreshSystemPrompt();\n this._configSet(\"skillsFingerprint\", this._skillRegistry.fingerprint);\n }\n } catch (error) {\n console.warn(\n `[think] Failed to refresh skills; using last known catalog: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n /**\n * Return sandboxed extension configurations. Defines load order,\n * which determines hook execution order.\n * Requires `extensionLoader` to be set.\n */\n getExtensions(): ExtensionConfig[] {\n return [];\n }\n\n // ── Lifecycle hooks ───────────────────────────────────────────\n\n /**\n * Called before `streamText` — inspect the assembled context and\n * return overrides. Think assembles tools, system prompt, and messages\n * internally; this hook sees the result and can override any part.\n *\n * Return `void` to accept all defaults.\n *\n * @example Switch model for continuations\n * ```typescript\n * beforeTurn(ctx: TurnContext) {\n * if (ctx.continuation) return { model: this.cheapModel };\n * }\n * ```\n *\n * @example Restrict active tools\n * ```typescript\n * beforeTurn(ctx: TurnContext) {\n * return { activeTools: [\"read\", \"write\"] };\n * }\n * ```\n */\n beforeTurn(\n _ctx: TurnContext\n ): TurnConfig | void | Promise<TurnConfig | void> {}\n\n /**\n * Called before each AI SDK step in the agentic loop. Backed by\n * `streamText({ prepareStep })`.\n *\n * Return `void` to accept the current step defaults, or return a\n * `StepConfig` to override the model, tool choice, active tools,\n * system prompt, messages, experimental context, or provider options\n * for this step. Use `beforeTurn` for turn-wide assembly and\n * `beforeStep` when the decision depends on the step number or\n * previous step results.\n *\n * @example Force search on the first step\n * ```typescript\n * beforeStep(ctx: PrepareStepContext) {\n * if (ctx.stepNumber === 0) {\n * return {\n * activeTools: [\"search\"],\n * toolChoice: { type: \"tool\", toolName: \"search\" }\n * };\n * }\n * }\n * ```\n *\n * @example Switch to a cheaper model after tool results land\n * ```typescript\n * beforeStep(ctx: PrepareStepContext) {\n * // assumes a `fastSummaryModel` field on your Think subclass\n * if (ctx.steps.some((s) => s.toolResults.length > 0)) {\n * return { model: this.fastSummaryModel };\n * }\n * }\n * ```\n */\n beforeStep(\n _ctx: PrepareStepContext\n ): StepConfig | void | Promise<StepConfig | void> {}\n\n /**\n * Called **before** the tool's `execute` function runs. Think wraps\n * every tool's `execute` so it can consult this hook and act on the\n * returned `ToolCallDecision`:\n *\n * - `void` (or `{ action: \"allow\" }` with no `input`) — run the\n * original `execute` with the original input.\n * - `{ action: \"allow\", input }` — run the original `execute` with\n * the substituted input.\n * - `{ action: \"block\", reason }` — skip `execute`; the model sees\n * `reason` as the tool's output.\n * - `{ action: \"substitute\", output }` — skip `execute`; the model\n * sees `output` as the tool's output.\n *\n * Only fires for server-side tools (tools with `execute`). Client\n * tools are handled on the client — Think can't intercept them.\n *\n * `afterToolCall` always fires after this hook (or after the original\n * `execute` when `allow`). For `block`/`substitute`, the substituted\n * value flows through `afterToolCall` as `success: true, output: ...`.\n *\n * @example Log tool calls\n * ```typescript\n * beforeToolCall(ctx: ToolCallContext) {\n * console.log(`Tool called: ${ctx.toolName}`, ctx.input);\n * }\n * ```\n *\n * @example Block a tool the model shouldn't be calling here\n * ```typescript\n * beforeToolCall(ctx: ToolCallContext): ToolCallDecision | void {\n * if (ctx.toolName === \"delete\" && this.isReadOnlyMode) {\n * return { action: \"block\", reason: \"delete is disabled in read-only mode\" };\n * }\n * }\n * ```\n *\n * @example Substitute a cached result\n * ```typescript\n * async beforeToolCall(ctx: ToolCallContext): Promise<ToolCallDecision | void> {\n * if (ctx.toolName === \"weather\") {\n * const cached = await this.cache.get(JSON.stringify(ctx.input));\n * if (cached) return { action: \"substitute\", output: cached };\n * }\n * }\n * ```\n */\n beforeToolCall(\n _ctx: ToolCallContext\n ): ToolCallDecision | void | Promise<ToolCallDecision | void> {}\n\n /**\n * Called **after** a tool's outcome is known — for real executions, for\n * `block` (carries the `reason` as `output`), and for `substitute`\n * (carries the substituted `output`). Backed by the AI SDK's\n * `experimental_onToolCallFinish`, so `durationMs` and the discriminated\n * `success`/`output`/`error` outcome reflect what the model actually\n * sees: a thrown error from the original `execute` becomes\n * `success: false, error: ...`; everything else (including blocked /\n * substituted calls) is `success: true, output: ...`.\n *\n * Override for logging, metrics, or result inspection.\n *\n * @example\n * ```typescript\n * afterToolCall(ctx: ToolCallResultContext) {\n * if (ctx.success) {\n * console.log(`${ctx.toolName} ok in ${ctx.durationMs}ms`);\n * } else {\n * console.error(`${ctx.toolName} failed:`, ctx.error);\n * }\n * }\n * ```\n */\n afterToolCall(_ctx: ToolCallResultContext): void | Promise<void> {}\n\n /**\n * Called after each step completes (initial, continue, tool-result).\n * Override for step-level logging or analytics.\n */\n onStepFinish(_ctx: StepContext): void | Promise<void> {}\n\n /**\n * Called for each streaming chunk. High-frequency — fires per token.\n * Override for streaming analytics, progress indicators, or token counting.\n * Observational only (void return).\n */\n onChunk(_ctx: ChunkContext): void | Promise<void> {}\n\n /**\n * Called after a chat turn completes and the assistant message has been\n * persisted. The turn lock is released before this hook runs, so it is\n * safe to call other methods from inside.\n *\n * Fires for all turn completion paths: WebSocket chat requests,\n * sub-agent RPC, and auto-continuation.\n *\n * Override for logging, chaining, analytics, usage tracking.\n */\n onChatResponse(_result: ChatResponseResult): void | Promise<void> {}\n\n /**\n * Handle an error that occurred during a chat turn.\n * Override to customize error handling (e.g. logging, metrics).\n */\n onChatError(error: unknown, _ctx?: ChatErrorContext): unknown {\n return error;\n }\n\n // ── Extension initialization ───────────────────────────────────\n\n private async _initializeExtensions(): Promise<void> {\n const { ExtensionManager } = await import(\"./extensions/manager\");\n const { sanitizeName } = await import(\"./extensions/manager\");\n\n // 3. Create ExtensionManager with host binding if HostBridgeLoopback\n // is re-exported from the worker entry point.\n const agentClassName = this.constructor.name;\n const agentId = this.ctx.id.toString();\n const ctxExports = (this.ctx as unknown as Record<string, unknown>)\n .exports as Record<string, unknown> | undefined;\n const hasBridge =\n ctxExports && typeof ctxExports.HostBridgeLoopback === \"function\";\n\n this.extensionManager = new ExtensionManager({\n loader: this.extensionLoader!,\n storage: this.ctx.storage,\n ...(hasBridge\n ? {\n createHostBinding: (\n permissions: import(\"./extensions/types\").ExtensionPermissions,\n ownContextLabels: string[]\n ) =>\n (\n ctxExports.HostBridgeLoopback as (opts: {\n props: Record<string, unknown>;\n }) => Fetcher\n )({\n props: {\n agentClassName,\n agentId,\n permissions,\n ownContextLabels\n }\n })\n }\n : {})\n });\n\n // 4. Load static extensions from getExtensions()\n const configs = this.getExtensions();\n for (const config of configs) {\n await this.extensionManager.load(config.manifest, config.source);\n }\n\n // 5. Restore dynamic extensions from DO storage\n await this.extensionManager.restore();\n\n // 6. Register extension context blocks in Session (mutation phase).\n // Context blocks use SQLite-backed AgentContextProvider (no bridge\n // delegation to the extension Worker). Extensions write to their\n // blocks via host.setContext() (Phase 3). Bridge providers that\n // delegate to extension Worker RPC methods are Phase 4.\n for (const ext of this.extensionManager.list()) {\n const manifest = this.extensionManager.getManifest(ext.name);\n if (!manifest?.context) continue;\n\n const prefix = sanitizeName(ext.name);\n for (const ctxDef of manifest.context) {\n const namespacedLabel = `${prefix}_${ctxDef.label}`;\n await this.session.addContext(namespacedLabel, {\n description: ctxDef.description,\n maxTokens: ctxDef.maxTokens\n });\n }\n }\n\n // Wire unload callback to clean up context blocks\n this.extensionManager.onUnload(async (_name, contextLabels) => {\n for (const label of contextLabels) {\n this.session.removeContext(label);\n }\n await this.session.refreshSystemPrompt();\n });\n }\n\n // ── Inference loop (Think owns this) ──────────────────────────\n\n /**\n * The single convergence point for all chat turn entry paths.\n * Merges tools, assembles context, fires lifecycle hooks, wraps tools\n * for interception, and calls streamText.\n */\n private async _runInferenceLoop(input: TurnInput): Promise<StreamableResult> {\n // Reset the per-turn watchdog override; `beforeTurn` may set it below. A\n // turn that doesn't override falls back to the instance-level value.\n this._activeStallTimeoutMs = undefined;\n if (this.waitForMcpConnections) {\n const timeout =\n typeof this.waitForMcpConnections === \"object\"\n ? this.waitForMcpConnections.timeout\n : 10_000;\n await this.mcp.waitForConnections({ timeout });\n }\n\n const workspaceTools = createWorkspaceTools(this.workspace, {\n bash: this.workspaceBash\n });\n const baseTools = this.getTools();\n const extensionTools = this.extensionManager?.getTools() ?? {};\n await this._refreshSkillsIfChanged();\n const contextTools = await this.session.tools();\n const skillTools = this._skillRegistry?.tools() ?? {};\n const clientToolSet = createToolsFromClientSchemas(input.clientTools);\n const tools: ToolSet = {\n ...workspaceTools,\n ...baseTools,\n ...extensionTools,\n ...contextTools,\n ...skillTools,\n ...(this.mcp?.getAITools?.() ?? {}),\n ...clientToolSet\n };\n\n const frozenPrompt = await this.session.freezeSystemPrompt();\n const baseSystem = frozenPrompt || this.getSystemPrompt();\n const system = this._systemPromptForTurn(baseSystem, tools);\n\n const history = await this._repairTranscriptForProvider(this.messages);\n const truncated = truncateOlderMessages(history) as UIMessage[];\n // `_repairTranscriptForProvider` above already heals orphan tool calls\n // (flipping them to errored results, preserving the record). This is the\n // last-line backstop: if any incomplete tool call still slips through\n // (compaction edge, addToolOutput race, an unrecognized part shape), drop it\n // here rather than letting the provider 400 with AI_MissingToolResultsError.\n //\n // The backstop drops silently. Repair should have left nothing incomplete,\n // so a non-empty set here means repair missed a shape — surface it (rather\n // than masking a repair bug) without breaking the turn.\n const incompleteAfterRepair = this._incompleteToolCallIds(truncated);\n if (incompleteAfterRepair.length > 0) {\n console.warn(\n `[Think] ${incompleteAfterRepair.length} incomplete tool call(s) survived transcript repair and will be dropped by ignoreIncompleteToolCalls: ${incompleteAfterRepair.join(\", \")}. This indicates a gap in _repairToolTranscriptParts.`\n );\n this._emit(\"chat:transcript:repaired\", {\n removedToolCalls: incompleteAfterRepair.length,\n normalizedInputs: 0,\n toolCallIds: incompleteAfterRepair\n });\n }\n const messages = await convertToModelMessages(truncated, {\n tools,\n ignoreIncompleteToolCalls: true\n });\n\n if (messages.length === 0) {\n throw new Error(\n \"No messages to send to the model. This usually means the chat request \" +\n \"arrived before any messages were persisted.\"\n );\n }\n\n const model = this.getModel();\n const ctx: TurnContext = {\n system,\n messages,\n tools,\n model,\n continuation: input.continuation,\n body: input.body\n };\n\n const subclassConfig = (await this.beforeTurn(ctx)) ?? {};\n const config = await this._pipelineExtensionBeforeTurn(ctx, subclassConfig);\n const workflowPrompt = input.workflowPrompt;\n const workflowOutput = workflowPrompt?.output\n ? Output.object({\n schema: jsonSchema(workflowPrompt.output.schema as never)\n })\n : undefined;\n\n const finalModel = config.model ?? model;\n const finalSystem =\n config.system ??\n this._systemPromptForTurn(\n baseSystem,\n config.tools ? { ...tools, ...config.tools } : tools\n );\n const finalMessages = ensureValidContinueCheckpoint(\n config.messages ?? messages\n );\n const mergedTools: ToolSet = config.tools\n ? { ...tools, ...config.tools }\n : tools;\n // Wrap each tool's `execute` so `beforeToolCall` is consulted before\n // the tool actually runs. The wrapped `execute` honors the returned\n // `ToolCallDecision` — `block` short-circuits with `reason`,\n // `substitute` returns `output` directly, `allow` runs the original\n // (optionally with modified `input`).\n const finalTools: ToolSet = this._wrapToolsWithDecision(mergedTools);\n const finalMaxSteps = config.maxSteps ?? this.maxSteps;\n const finalSendReasoning = config.sendReasoning ?? this.sendReasoning;\n // Resolve the per-turn stall-watchdog override (explicit `0` = off for this\n // turn). Read by `_streamResult` / `_streamResultToRpcCallback` when arming\n // the watchdog. `??` so a `0` override is honored, not treated as \"unset\".\n this._activeStallTimeoutMs =\n config.chatStreamStallTimeoutMs ?? this.chatStreamStallTimeoutMs;\n const finalOutput = workflowOutput ?? config.output;\n const finalStopWhen = [\n stepCountIs(finalMaxSteps),\n ...(Array.isArray(config.stopWhen)\n ? config.stopWhen\n : config.stopWhen\n ? [config.stopWhen]\n : [])\n ];\n\n const result = streamText({\n model: finalModel,\n system: finalSystem,\n messages: finalMessages,\n tools: finalTools,\n activeTools: config.activeTools,\n toolChoice: config.toolChoice,\n maxOutputTokens: config.maxOutputTokens,\n temperature: config.temperature,\n topP: config.topP,\n topK: config.topK,\n presencePenalty: config.presencePenalty,\n frequencyPenalty: config.frequencyPenalty,\n stopSequences: config.stopSequences,\n seed: config.seed,\n maxRetries: config.maxRetries,\n timeout: config.timeout,\n headers: config.headers,\n stopWhen: finalStopWhen,\n providerOptions: config.providerOptions as\n | Parameters<typeof streamText>[0][\"providerOptions\"]\n | undefined,\n experimental_telemetry: config.experimental_telemetry,\n // Forward the per-turn structured-output spec from TurnConfig so\n // callers can use AI SDK `Output.object({ schema })` / `Output.text()`\n // on the terminal turn without dropping tools at model construction.\n output: finalOutput,\n abortSignal: input.signal,\n // Forward the AI SDK's `prepareStep` callback unchanged so subclasses\n // can make per-step decisions from the previous steps, current\n // messages, model, and experimental context.\n //\n // Subclass-only by design: extension dispatch is intentionally not\n // wired here. The prepareStep event includes a live `LanguageModel`\n // instance which is not JSON-serializable, and a returned override\n // can include the same — there's no useful \"snapshot, override\"\n // contract we could give to sandboxed extensions. If we expose\n // observation-only later it should go through a separate,\n // serialized event surface.\n //\n // `beforeStep` returning `void`/`undefined`/`null` is normalized to\n // `{}` so the AI SDK falls back to top-level settings (it accepts\n // `undefined` per docs but the typed return is non-null).\n prepareStep: (async (event) => {\n const result = await this.beforeStep(event);\n return result == null ? {} : result;\n }) satisfies PrepareStepFunction<ToolSet>,\n onChunk: async (event) => {\n // Pass the AI SDK's chunk event through unchanged — gives users\n // access to the discriminated `TextStreamPart` chunk with all\n // provider metadata.\n await this.onChunk(event);\n await this._pipelineExtensionChunk(event);\n },\n onStepFinish: async (event) => {\n // Pass the full StepResult through — gives users access to\n // reasoning, sources, files, providerMetadata (cache tokens),\n // request/response, warnings, and the full LanguageModelUsage\n // that the AI SDK provides.\n await this.onStepFinish(event);\n await this._pipelineExtensionStepFinish(event);\n },\n // `beforeToolCall` is dispatched from the wrapped `execute` (see\n // `_wrapToolsWithDecision` above) so the returned `ToolCallDecision`\n // can actually intercept the call. `afterToolCall` is wired through\n // the AI SDK's `experimental_onToolCallFinish` callback so we get\n // accurate `durationMs` and the discriminated `success`/`error`\n // outcome — including failures that propagate out of `execute`.\n experimental_onToolCallFinish: (async (event) => {\n const base = {\n ...event.toolCall,\n stepNumber: event.stepNumber,\n messages: event.messages,\n durationMs: event.durationMs\n };\n const ctx = (\n event.success\n ? { ...base, success: true as const, output: event.output }\n : { ...base, success: false as const, error: event.error }\n ) as ToolCallResultContext;\n await this.afterToolCall(ctx);\n await this._pipelineExtensionToolCallFinish(event);\n }) satisfies StreamTextOnToolCallFinishCallback<ToolSet>\n });\n\n const outputPromise =\n finalOutput && result.output ? Promise.resolve(result.output) : undefined;\n if (outputPromise) {\n // Attach a rejection observer immediately. `_streamResult()` will still\n // await this promise when captureOutput is enabled, but aborted streams can\n // reject before the stream consumer reaches that point.\n void outputPromise.catch(() => {});\n }\n\n const streamResult = {\n toUIMessageStream: () =>\n result.toUIMessageStream({ sendReasoning: finalSendReasoning }),\n output: outputPromise\n } satisfies StreamableResult;\n\n return this._transformInferenceResult(streamResult);\n }\n\n /** @internal Test seam — override in test agents to wrap the stream (e.g. error injection). */\n protected _transformInferenceResult(\n result: StreamableResult\n ): StreamableResult {\n return result;\n }\n\n /** Default hook timeout in milliseconds. */\n hookTimeout = 5000;\n\n /**\n * Pipeline beforeTurn through sandboxed extensions in load order.\n * Each extension sees the accumulated state from prior extensions\n * (snapshot is rebuilt after each extension's modifications).\n * Results are merged with last-write-wins for scalar fields.\n * Extensions that don't subscribe to beforeTurn are skipped.\n */\n private async _pipelineExtensionBeforeTurn(\n ctx: TurnContext,\n subclassConfig: TurnConfig\n ): Promise<TurnConfig> {\n if (!this.extensionManager) return subclassConfig;\n\n const subscribers = this.extensionManager.getHookSubscribers(\"beforeTurn\");\n if (subscribers.length === 0) return subclassConfig;\n\n const { createTurnContextSnapshot, parseHookResult } =\n await import(\"./extensions/hook-proxy\");\n\n let snapshot = createTurnContextSnapshot(ctx);\n let accumulated = { ...subclassConfig };\n\n // Apply subclass config to the initial snapshot so extensions\n // see the subclass overrides\n if (accumulated.system !== undefined) snapshot.system = accumulated.system;\n if (accumulated.maxSteps !== undefined)\n snapshot.messageCount = ctx.messages.length;\n\n for (const sub of subscribers) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const resultJson = await Promise.race([\n sub.entrypoint.hook(\"beforeTurn\", snapshot),\n new Promise<string>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(`Hook timeout: ${sub.name}`)),\n this.hookTimeout\n );\n })\n ]);\n\n const parsed = parseHookResult(resultJson);\n if (\"config\" in parsed) {\n // Merge serializable scalars only. model and tools are skipped —\n // sandboxed extensions can't return LanguageModel or AI SDK Tool\n // objects (not serializable across RPC). Use activeTools to\n // control which tools the model can call.\n if (parsed.config.system !== undefined)\n accumulated.system = parsed.config.system;\n if (parsed.config.messages !== undefined)\n accumulated.messages = parsed.config.messages;\n if (parsed.config.activeTools !== undefined)\n accumulated.activeTools = parsed.config.activeTools;\n if (parsed.config.toolChoice !== undefined)\n accumulated.toolChoice = parsed.config.toolChoice;\n if (parsed.config.maxSteps !== undefined)\n accumulated.maxSteps = parsed.config.maxSteps;\n if (parsed.config.sendReasoning !== undefined)\n accumulated.sendReasoning = parsed.config.sendReasoning;\n if (parsed.config.maxOutputTokens !== undefined)\n accumulated.maxOutputTokens = parsed.config.maxOutputTokens;\n if (parsed.config.temperature !== undefined)\n accumulated.temperature = parsed.config.temperature;\n if (parsed.config.topP !== undefined)\n accumulated.topP = parsed.config.topP;\n if (parsed.config.topK !== undefined)\n accumulated.topK = parsed.config.topK;\n if (parsed.config.presencePenalty !== undefined)\n accumulated.presencePenalty = parsed.config.presencePenalty;\n if (parsed.config.frequencyPenalty !== undefined)\n accumulated.frequencyPenalty = parsed.config.frequencyPenalty;\n if (parsed.config.stopSequences !== undefined)\n accumulated.stopSequences = parsed.config.stopSequences;\n if (parsed.config.seed !== undefined)\n accumulated.seed = parsed.config.seed;\n if (parsed.config.maxRetries !== undefined)\n accumulated.maxRetries = parsed.config.maxRetries;\n if (parsed.config.timeout !== undefined)\n accumulated.timeout = parsed.config.timeout;\n if (parsed.config.headers !== undefined) {\n accumulated.headers = {\n ...(accumulated.headers ?? {}),\n ...parsed.config.headers\n };\n }\n if (parsed.config.providerOptions !== undefined) {\n accumulated.providerOptions = {\n ...(accumulated.providerOptions ?? {}),\n ...parsed.config.providerOptions\n };\n }\n // Update snapshot so next extension sees this extension's changes\n if (accumulated.system !== undefined)\n snapshot = { ...snapshot, system: accumulated.system };\n if (accumulated.activeTools !== undefined)\n snapshot = { ...snapshot, toolNames: accumulated.activeTools };\n } else if (\"error\" in parsed) {\n console.warn(\n `[Think] Extension \"${sub.name}\" beforeTurn error:`,\n parsed.error\n );\n }\n } catch (err) {\n console.warn(\n `[Think] Extension \"${sub.name}\" beforeTurn failed:`,\n err instanceof Error ? err.message : err\n );\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n\n return accumulated;\n }\n\n /**\n * Dispatch an observation hook to all extensions that subscribe to it.\n *\n * Used by `_pipelineExtensionToolCallStart`, `_pipelineExtensionToolCallFinish`,\n * `_pipelineExtensionStepFinish`, and `_pipelineExtensionChunk`. Unlike\n * `beforeTurn`, these hooks are observation-only — extensions can't\n * influence the turn — so we ignore return values, log errors, and\n * apply a per-extension timeout.\n *\n * `onChunk` is high-frequency (per token) — extensions that subscribe\n * to it pay an RPC cost per chunk and should be used sparingly.\n */\n private async _dispatchExtensionObservation(\n hookName: \"beforeToolCall\" | \"afterToolCall\" | \"onStepFinish\" | \"onChunk\",\n snapshot: unknown\n ): Promise<void> {\n if (!this.extensionManager) return;\n const subscribers = this.extensionManager.getHookSubscribers(hookName);\n if (subscribers.length === 0) return;\n\n for (const sub of subscribers) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n sub.entrypoint.hook(hookName, snapshot),\n new Promise<string>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(`Hook timeout: ${sub.name}`)),\n this.hookTimeout\n );\n })\n ]);\n } catch (err) {\n console.warn(\n `[Think] Extension \"${sub.name}\" ${hookName} failed:`,\n err instanceof Error ? err.message : err\n );\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n }\n\n /**\n * Wrap each tool's `execute` function so the agent's `beforeToolCall`\n * hook is consulted before the tool runs. The hook can return a\n * `ToolCallDecision` to:\n *\n * - `allow` (default if `void` is returned) — run the original\n * `execute`, optionally with a substituted `input`.\n * - `block` — skip `execute` and return `reason` (or a default string)\n * as the tool result. The model sees this as the tool's output.\n * - `substitute` — skip `execute` and return `output` directly. The\n * model sees this as the tool's output.\n *\n * The wrapped `execute` also dispatches the `beforeToolCall`\n * observation snapshot to subscribed extensions. `afterToolCall` is\n * still wired through the AI SDK's `experimental_onToolCallFinish`\n * callback so we get accurate `durationMs` and proper success/error\n * discrimination — `block` and `substitute` outcomes show up as\n * `success: true` with the substituted output; uncaught throws from\n * the original `execute` show up as `success: false` with the error.\n *\n * Tools without an `execute` (output-schema-only tools, client tools\n * routed via `needsApproval`) are left untouched.\n *\n * **Streaming tools (AsyncIterable):** the AI SDK supports tools whose\n * `execute` returns `AsyncIterable<output>` to emit preliminary\n * results before a final value. This works whether the iterator is\n * returned directly (sync function, `async function*`) or wrapped in\n * a Promise (`async function execute(...) { return makeIter(); }`).\n * Because the wrapper must `await beforeToolCall` first, preliminary\n * chunks are collapsed — only the *final* yielded value reaches the\n * model. If you need true preliminary streaming, override\n * `getTools()` to provide such tools and avoid using `beforeToolCall`\n * for them (or accept the collapse).\n */\n private _wrapToolsWithDecision(tools: ToolSet): ToolSet {\n const wrapped: ToolSet = {};\n for (const [toolName, originalTool] of Object.entries(tools)) {\n const t = originalTool as Record<string, unknown>;\n const originalExecute = t.execute as\n | ((input: unknown, options: unknown) => unknown | Promise<unknown>)\n | undefined;\n if (typeof originalExecute !== \"function\") {\n wrapped[toolName] = originalTool;\n continue;\n }\n\n const isDynamic = t.type === \"dynamic\";\n\n const wrappedExecute = async (\n input: unknown,\n options: {\n toolCallId: string;\n messages: ModelMessage[];\n abortSignal?: AbortSignal;\n experimental_context?: unknown;\n }\n ): Promise<unknown> => {\n // Build the discriminated `TypedToolCall`-shaped context.\n const toolCallBase = {\n type: \"tool-call\" as const,\n toolCallId: options.toolCallId,\n toolName,\n input,\n ...(isDynamic ? { dynamic: true as const } : {})\n };\n\n const ctx = {\n ...toolCallBase,\n stepNumber: undefined,\n messages: options.messages,\n abortSignal: options.abortSignal\n } as ToolCallContext;\n\n // Subclass decision first.\n const decision = await this.beforeToolCall(ctx);\n\n // Extension observation dispatch — runs after the subclass so\n // extensions see whatever effect the subclass had on the\n // decision shape (input substitution shows up in the snapshot).\n const dispatchInput =\n decision && decision.action === \"allow\" && decision.input\n ? decision.input\n : input;\n await this._pipelineExtensionToolCallStart({\n toolCall: {\n ...toolCallBase,\n input: dispatchInput\n } as TypedToolCall<ToolSet>,\n stepNumber: undefined\n });\n\n // Resolve the decision.\n if (!decision || decision.action === \"allow\") {\n const finalInput = decision?.input ?? input;\n // Await before inspecting so we detect AsyncIterable returns\n // whether the original `execute` returned them directly (sync\n // function or `async function*`) or wrapped in a Promise (a\n // plain async function that returns an iterator). Without the\n // await, `Symbol.asyncIterator in result` would be false for\n // any `Promise<AsyncIterable>`, the collapse below would be\n // skipped, and the AI SDK would treat the iterator instance\n // itself as the final output value (broken).\n const result = await originalExecute(finalInput, options);\n // If the resolved value is an AsyncIterable (streaming tool\n // emitting preliminary outputs), collapse to the last yielded\n // value. We trade preliminary streaming for `beforeToolCall`\n // interception support.\n if (\n result != null &&\n typeof result === \"object\" &&\n Symbol.asyncIterator in (result as object)\n ) {\n let last: unknown;\n for await (const part of result as AsyncIterable<unknown>) {\n last = part;\n }\n return last;\n }\n return result;\n }\n if (decision.action === \"block\") {\n return (\n decision.reason ??\n `Tool \"${toolName}\" was blocked by beforeToolCall.`\n );\n }\n // substitute\n return decision.output;\n };\n\n wrapped[toolName] = {\n ...(originalTool as object),\n execute: wrappedExecute\n } as ToolSet[string];\n }\n return wrapped;\n }\n\n private async _pipelineExtensionToolCallStart(event: {\n toolCall: TypedToolCall<ToolSet>;\n stepNumber: number | undefined;\n }): Promise<void> {\n if (!this.extensionManager) return;\n if (this.extensionManager.getHookSubscribers(\"beforeToolCall\").length === 0)\n return;\n const { createToolCallStartSnapshot } =\n await import(\"./extensions/hook-proxy\");\n await this._dispatchExtensionObservation(\n \"beforeToolCall\",\n createToolCallStartSnapshot(event)\n );\n }\n\n private async _pipelineExtensionToolCallFinish(event: {\n toolCall: TypedToolCall<ToolSet>;\n stepNumber: number | undefined;\n durationMs: number;\n success: boolean;\n output?: unknown;\n error?: unknown;\n }): Promise<void> {\n if (!this.extensionManager) return;\n if (this.extensionManager.getHookSubscribers(\"afterToolCall\").length === 0)\n return;\n const { createToolCallFinishSnapshot } =\n await import(\"./extensions/hook-proxy\");\n await this._dispatchExtensionObservation(\n \"afterToolCall\",\n createToolCallFinishSnapshot(event)\n );\n }\n\n private async _pipelineExtensionStepFinish(\n event: StepContext\n ): Promise<void> {\n if (!this.extensionManager) return;\n if (this.extensionManager.getHookSubscribers(\"onStepFinish\").length === 0)\n return;\n const { createStepFinishSnapshot } =\n await import(\"./extensions/hook-proxy\");\n await this._dispatchExtensionObservation(\n \"onStepFinish\",\n createStepFinishSnapshot(event)\n );\n }\n\n private async _pipelineExtensionChunk(event: ChunkContext): Promise<void> {\n if (!this.extensionManager) return;\n if (this.extensionManager.getHookSubscribers(\"onChunk\").length === 0)\n return;\n const { createChunkSnapshot } = await import(\"./extensions/hook-proxy\");\n await this._dispatchExtensionObservation(\n \"onChunk\",\n createChunkSnapshot(event as { chunk: { type: string } })\n );\n }\n\n // ── Host bridge methods (called by HostBridgeLoopback via DO RPC) ──\n\n async _hostReadFile(path: string): Promise<string | null> {\n return (await this.workspace.readFile(path)) ?? null;\n }\n\n async _hostWriteFile(path: string, content: string): Promise<void> {\n await this.workspace.writeFile(path, content);\n }\n\n async _hostDeleteFile(path: string): Promise<boolean> {\n try {\n await this.workspace.rm(path);\n return true;\n } catch {\n return false;\n }\n }\n\n async _hostListFiles(\n dir: string\n ): Promise<\n Array<{ name: string; type: string; size: number; path: string }>\n > {\n const entries = await this.workspace.readDir(dir);\n return entries.map((e) => ({\n name: e.name,\n type: e.type,\n size: e.size ?? 0,\n path: e.path ?? `${dir}/${e.name}`\n }));\n }\n\n async _hostGetContext(label: string): Promise<string | null> {\n const block = this.session.getContextBlock(label);\n return block?.content ?? null;\n }\n\n async _hostSetContext(label: string, content: string): Promise<void> {\n await this.session.replaceContextBlock(label, content);\n }\n\n async _hostGetMessages(\n limit?: number\n ): Promise<Array<{ id: string; role: string; content: string }>> {\n const history = this.messages;\n const sliced =\n limit !== undefined && limit !== null\n ? limit <= 0\n ? []\n : history.slice(-limit)\n : history;\n return sliced.map((m) => ({\n id: m.id,\n role: m.role,\n content: m.parts\n .filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n .map((p) => p.text)\n .join(\"\")\n }));\n }\n\n async _hostSendMessage(content: string): Promise<void> {\n const msg = {\n id: crypto.randomUUID(),\n role: \"user\" as const,\n parts: [{ type: \"text\" as const, text: content }]\n };\n // Append directly to session — do NOT route through saveMessages,\n // which enqueues a full turn via TurnQueue and would deadlock if\n // called during an active turn (tool execution → host.sendMessage\n // → saveMessages → TurnQueue.enqueue → awaits current turn → deadlock).\n // The injected message is visible in the next turn's history.\n await this._appendMessageToHistory(msg);\n }\n\n async _hostGetSessionInfo(): Promise<{\n messageCount: number;\n }> {\n return {\n messageCount: this.messages.length\n };\n }\n\n // ── Sub-agent RPC entry point ───────────────────────────────────\n\n /**\n * Run a chat turn: persist the user message, run the agentic loop,\n * stream UIMessageChunk events via callback, and persist the\n * assistant's response.\n *\n * @param userMessage The user's message (string or UIMessage)\n * @param callback Streaming callback (typically an RpcTarget from the parent)\n * @param options Optional chat options (e.g. AbortSignal)\n */\n async chat(\n userMessage: string | UIMessage,\n callback: StreamCallback,\n options?: ChatOptions\n ): Promise<void> {\n const requestId = crypto.randomUUID();\n const abortSignal = this._aborts.getSignal(requestId);\n const detachExternal = this._aborts.linkExternal(\n requestId,\n options?.signal\n );\n const ignoredTools = (options as { tools?: unknown } | undefined)?.tools;\n if (\n ignoredTools != null &&\n typeof ignoredTools === \"object\" &&\n Object.keys(ignoredTools).length > 0\n ) {\n console.warn(\n \"[Think] chat() no longer accepts options.tools. Define durable tools on the child agent with getTools(), or use runAgentTool()/agentTool() for parent-child orchestration.\"\n );\n }\n\n try {\n await callback.onStart({ requestId });\n await this.keepAliveWhile(async () => {\n await this._turnQueue.enqueue(requestId, async () => {\n const userMsg: UIMessage =\n typeof userMessage === \"string\"\n ? {\n id: crypto.randomUUID(),\n role: \"user\",\n parts: [{ type: \"text\", text: userMessage }]\n }\n : userMessage;\n\n await this._appendMessageToHistory(userMsg);\n this._broadcastMessages();\n\n const chatBody = async () => {\n let result: StreamableResult;\n try {\n result = await agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n continuation: false\n })\n );\n } catch (error) {\n const wrapped = this.onChatError(error, {\n stage: \"turn\",\n messagesPersisted: true\n });\n const errorMessage =\n wrapped instanceof Error ? wrapped.message : String(wrapped);\n this._emit(\"chat:request:failed\", {\n stage: \"turn\",\n messagesPersisted: true,\n error: errorMessage\n });\n await callback.onError(errorMessage);\n return;\n }\n\n await this._streamResultToRpcCallback(\n requestId,\n result,\n callback,\n abortSignal\n );\n };\n\n if (this.chatRecovery) {\n await this._runChatRecoveryFiber(requestId, false, chatBody);\n } else {\n await chatBody();\n }\n });\n });\n } finally {\n detachExternal();\n this._aborts.remove(requestId);\n }\n }\n\n // ── Message access ──────────────────────────────────────────────\n\n /** Get the conversation history as UIMessage[]. */\n async getMessages(): Promise<UIMessage[]> {\n return this.messages.slice();\n }\n\n /** Clear all messages from storage. */\n async clearMessages(): Promise<void> {\n this.resetTurnState();\n await this._clearHistory();\n this._broadcast({ type: MSG_CHAT_CLEAR });\n }\n\n private _ensureAgentToolChildRunTable(): void {\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_agent_tool_child_runs (\n run_id TEXT PRIMARY KEY,\n request_id TEXT,\n stream_id TEXT,\n status TEXT NOT NULL,\n summary TEXT,\n output_json TEXT,\n error_message TEXT,\n started_at INTEGER NOT NULL,\n completed_at INTEGER\n )\n `;\n\n this._addAgentToolChildRunColumnIfMissing(\n \"ALTER TABLE cf_agent_tool_child_runs ADD COLUMN output_json TEXT\"\n );\n }\n\n private _addAgentToolChildRunColumnIfMissing(sql: string): void {\n try {\n this.ctx.storage.sql.exec(sql);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (!message.toLowerCase().includes(\"duplicate column\")) {\n throw error;\n }\n }\n }\n\n private _readAgentToolChildRun(runId: string): AgentToolChildRunRow | null {\n this._ensureAgentToolChildRunTable();\n const rows = this.sql<AgentToolChildRunRow>`\n SELECT run_id, request_id, stream_id, status, summary, output_json,\n error_message, started_at, completed_at\n FROM cf_agent_tool_child_runs\n WHERE run_id = ${runId}\n LIMIT 1\n `;\n return rows[0] ?? null;\n }\n\n private _inspectionFromChildRow<Output>(\n row: AgentToolChildRunRow,\n output?: Output\n ): AgentToolRunInspection<Output> {\n const storedOutput =\n row.output_json === null\n ? output\n : (Think._parseAgentToolOutput(row.output_json) as Output);\n\n return {\n runId: row.run_id,\n status: row.status,\n requestId: row.request_id ?? undefined,\n streamId: row.stream_id ?? undefined,\n output: storedOutput,\n summary: row.summary ?? undefined,\n error: row.error_message ?? undefined,\n startedAt: row.started_at,\n completedAt: row.completed_at ?? undefined\n };\n }\n\n protected formatAgentToolInput(input: unknown): UIMessage {\n const text =\n typeof input === \"string\" ? input : JSON.stringify(input, null, 2);\n return {\n id: crypto.randomUUID(),\n role: \"user\",\n parts: [{ type: \"text\", text }]\n };\n }\n\n protected getAgentToolOutput(_runId: string): unknown {\n return undefined;\n }\n\n protected getAgentToolSummary(runId: string, output: unknown): string {\n const text = this._getAgentToolFinalText(runId);\n if (text) return text;\n if (typeof output === \"string\") return output;\n if (output !== undefined) {\n try {\n return JSON.stringify(output);\n } catch {\n return String(output);\n }\n }\n return \"\";\n }\n\n async startAgentToolRun(\n input: unknown,\n options: { runId: string }\n ): Promise<AgentToolRunInspection> {\n const existing = this._readAgentToolChildRun(options.runId);\n if (existing) return this._inspectionFromChildRow(existing);\n\n const startedAt = Date.now();\n this.sql`\n INSERT INTO cf_agent_tool_child_runs (run_id, status, started_at)\n VALUES (${options.runId}, 'starting', ${startedAt})\n `;\n\n const controller = new AbortController();\n this._agentToolAbortControllers.set(options.runId, controller);\n this._agentToolLiveSequences.set(options.runId, 0);\n this._agentToolPreTurnAssistantIds.set(\n options.runId,\n new Set(\n this.messages.filter((m) => m.role === \"assistant\").map((m) => m.id)\n )\n );\n\n const epoch = this._turnQueue.generation;\n void this.keepAliveWhile(async () => {\n try {\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET status = 'running'\n WHERE run_id = ${options.runId} AND status = 'starting'\n `;\n const result = await this.saveMessages(\n [this.formatAgentToolInput(input)],\n {\n signal: controller.signal\n }\n );\n const streamId =\n this._resumableStream\n .getAllStreamMetadata()\n .find((m) => m.request_id === result.requestId)?.id ?? null;\n const output = this.getAgentToolOutput(options.runId);\n const summary = this.getAgentToolSummary(options.runId, output);\n const streamError =\n result.error ?? this._agentToolLastErrors.get(options.runId);\n const skipped =\n result.status === \"skipped\" ||\n (result.status === \"aborted\" && this._turnQueue.generation !== epoch);\n const status: AgentToolChildRunStatus =\n result.status === \"error\" || skipped || streamError\n ? \"error\"\n : result.status === \"aborted\"\n ? \"aborted\"\n : \"completed\";\n const error: string | null =\n status === \"error\"\n ? (streamError ??\n \"Agent tool run was skipped before the child could finish.\")\n : null;\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET request_id = ${result.requestId},\n stream_id = ${streamId},\n status = ${status},\n summary = ${summary},\n output_json = ${Think._stringifyAgentToolOutput(output)},\n error_message = ${error},\n completed_at = ${Date.now()}\n WHERE run_id = ${options.runId}\n AND completed_at IS NULL\n `;\n } catch (error) {\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET status = 'error',\n error_message = ${error instanceof Error ? error.message : String(error)},\n completed_at = ${Date.now()}\n WHERE run_id = ${options.runId}\n AND completed_at IS NULL\n `;\n } finally {\n this._agentToolAbortControllers.delete(options.runId);\n this._agentToolForwarders.delete(options.runId);\n this._agentToolLiveSequences.delete(options.runId);\n this._agentToolLastErrors.delete(options.runId);\n this._agentToolPreTurnAssistantIds.delete(options.runId);\n for (const close of this._agentToolClosers.get(options.runId) ?? []) {\n close();\n }\n this._agentToolClosers.delete(options.runId);\n }\n });\n\n return {\n runId: options.runId,\n status: \"running\",\n startedAt\n };\n }\n\n async cancelAgentToolRun(runId: string, reason?: unknown): Promise<void> {\n const row = this._readAgentToolChildRun(runId);\n if (!row || row.completed_at !== null) return;\n this._agentToolAbortControllers.get(runId)?.abort(reason);\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET status = 'aborted',\n error_message = ${reason instanceof Error ? reason.message : reason === undefined ? null : String(reason)},\n completed_at = ${Date.now()}\n WHERE run_id = ${runId}\n AND status NOT IN ('completed', 'error', 'aborted')\n `;\n }\n\n /**\n * Classify any in-flight chat-recovery on this child facet (#1630). A child\n * facet is dedicated to a single agent-tool run, so any recovery incident is\n * that run's. `detected`/`scheduled`/`attempting` mean recovery is still\n * resolving the interrupted turn; `exhausted`/`failed` mean it gave up; a\n * completed recovery deletes its incident.\n */\n private async _classifyAgentToolChildRecovery(): Promise<\n \"in-progress\" | \"failed\" | \"none\"\n > {\n const entries = await this.ctx.storage.list<ChatRecoveryIncident>({\n prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX\n });\n let failed = false;\n for (const incident of entries.values()) {\n if (\n incident.status === \"detected\" ||\n incident.status === \"scheduled\" ||\n incident.status === \"attempting\"\n ) {\n return \"in-progress\";\n }\n if (incident.status === \"exhausted\" || incident.status === \"failed\") {\n failed = true;\n }\n }\n return failed ? \"failed\" : \"none\";\n }\n\n async inspectAgentToolRun(\n runId: string\n ): Promise<AgentToolRunInspection | null> {\n let row = this._readAgentToolChildRun(runId);\n if (!row) return null;\n // A `running`/`starting` row with no live abort controller means the\n // original in-isolate run is gone (e.g. the parent was evicted while this\n // child run was in flight, #1630) — lazily reconcile it from the child's\n // own durable recovery before reporting.\n if (this._isStaleAgentToolChildRun(row)) {\n await this._reconcileStaleAgentToolChildRun(runId);\n row = this._readAgentToolChildRun(runId) ?? row;\n }\n return this._inspectionFromChildRow(row, this.getAgentToolOutput(runId));\n }\n\n private _isStaleAgentToolChildRun(row: AgentToolChildRunRow): boolean {\n return (\n (row.status === \"running\" || row.status === \"starting\") &&\n row.completed_at === null &&\n !this._agentToolAbortControllers.has(row.run_id)\n );\n }\n\n /**\n * Reconcile a stale (post-eviction) child run row from the child's own\n * durable recovery (#1630). The child facet self-heals its interrupted turn\n * via `chatRecovery`, but that path never writes the run row, so without this\n * the row strands `running` and the parent can only collect `interrupted`.\n *\n * Persisting the terminal here (rather than only computing it) is intentional:\n * it's a lazy materialization of the run's true terminal that also lets a\n * tailing parent's stream close promptly and makes subsequent inspects cheap.\n * While recovery is still resolving (active stream or in-progress incident)\n * the row is left `running` so the parent's bounded re-attach keeps waiting.\n */\n private async _reconcileStaleAgentToolChildRun(runId: string): Promise<void> {\n const recovery = await this._classifyAgentToolChildRecovery();\n if (recovery === \"in-progress\" || this._resumableStream.hasActiveStream()) {\n return;\n }\n // A settled recovery that produced an assistant turn is `completed`, even if\n // that turn ended on a tool result with no final text — keying off text\n // alone would mis-seal a legitimately-finished (but text-less) run as\n // `error`. `getAgentToolSummary` already falls back to \"\" when there is no\n // final text.\n const recoveredTurn =\n recovery !== \"failed\" && this._hasRecoveredAgentToolAssistantTurn(runId);\n if (recoveredTurn) {\n const output = this.getAgentToolOutput(runId);\n const summary = this.getAgentToolSummary(runId, output);\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET status = 'completed',\n summary = ${summary},\n output_json = ${Think._stringifyAgentToolOutput(output)},\n error_message = null,\n completed_at = ${Date.now()}\n WHERE run_id = ${runId} AND completed_at IS NULL\n `;\n } else {\n const error =\n \"Agent tool run was interrupted before the child could finish.\";\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET status = 'error',\n error_message = ${error},\n completed_at = ${Date.now()}\n WHERE run_id = ${runId} AND completed_at IS NULL\n `;\n }\n this._finalizeAgentToolChildRunTailers(runId);\n }\n\n /** Release a re-attached run's live tail + per-run streaming bookkeeping. */\n private _finalizeAgentToolChildRunTailers(runId: string): void {\n for (const close of this._agentToolClosers.get(runId) ?? []) {\n close();\n }\n this._agentToolClosers.delete(runId);\n this._agentToolForwarders.delete(runId);\n this._agentToolLiveSequences.delete(runId);\n this._agentToolLastErrors.delete(runId);\n this._agentToolPreTurnAssistantIds.delete(runId);\n }\n\n async getAgentToolChunks(\n runId: string,\n options?: { afterSequence?: number }\n ): Promise<AgentToolStoredChunk[]> {\n const row = this._readAgentToolChildRun(runId);\n if (!row?.stream_id) return [];\n this._resumableStream.flushBuffer();\n return this._resumableStream\n .getStreamChunks(row.stream_id)\n .filter((chunk) => chunk.chunk_index > (options?.afterSequence ?? -1))\n .map((chunk) => ({ sequence: chunk.chunk_index, body: chunk.body }));\n }\n\n async tailAgentToolRun(\n runId: string,\n options?: { afterSequence?: number; signal?: AbortSignal }\n ): Promise<ReadableStream<AgentToolStoredChunk>> {\n const self = this;\n const signal = options?.signal;\n let closed = false;\n let forward: ((chunk: AgentToolStoredChunk) => void) | undefined;\n const detach = () => {\n if (forward) {\n self._agentToolForwarders.get(runId)?.delete(forward);\n forward = undefined;\n }\n };\n const stream = new ReadableStream<Uint8Array>({\n async start(controller) {\n const close = () => {\n if (closed) return;\n closed = true;\n detach();\n try {\n controller.close();\n } catch {\n // Already closed.\n }\n };\n // Honor an external abort (e.g. a bounded re-attach budget) so a parent\n // tailing a still-running child can stop waiting without cancelling the\n // child itself — closing the stream unblocks the parent's forwarder.\n if (signal?.aborted) {\n close();\n return;\n }\n signal?.addEventListener(\"abort\", close, { once: true });\n\n const replayed = await self.getAgentToolChunks(runId, options);\n for (const chunk of replayed) {\n if (closed) return;\n controller.enqueue(\n agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\\n`)\n );\n }\n const lastReplay = replayed[replayed.length - 1]?.sequence;\n if (lastReplay !== undefined) {\n self._agentToolLiveSequences.set(runId, lastReplay + 1);\n }\n const row = self._readAgentToolChildRun(runId);\n if (!row || row.completed_at !== null) {\n close();\n return;\n }\n forward = (chunk: AgentToolStoredChunk) => {\n if (closed || chunk.sequence <= (options?.afterSequence ?? -1)) {\n return;\n }\n try {\n controller.enqueue(\n agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\\n`)\n );\n } catch {\n // The consumer detached (e.g. a parent's re-attach budget expired\n // and cancelled the reader) between the RPC cancel arriving and our\n // `cancel`/`close` running. Drop the chunk instead of surfacing a\n // \"Stream was cancelled\" rejection; the child run is unaffected.\n closed = true;\n detach();\n }\n };\n const forwarders = self._agentToolForwarders.get(runId) ?? new Set();\n forwarders.add(forward);\n self._agentToolForwarders.set(runId, forwarders);\n const closers = self._agentToolClosers.get(runId) ?? new Set();\n closers.add(close);\n self._agentToolClosers.set(runId, closers);\n },\n cancel() {\n // A consumer detaching from the tail (e.g. a parent's bounded re-attach\n // budget expiring, via reader.cancel()) is read-only — it must NOT\n // cancel the child run. Explicit cancellation flows through\n // cancelAgentToolRun. Mirrors @cloudflare/ai-chat's read-only tail.\n closed = true;\n detach();\n }\n });\n return stream as unknown as ReadableStream<AgentToolStoredChunk>;\n }\n\n private static _stringifyAgentToolOutput(output: unknown): string | null {\n if (output === undefined) return null;\n try {\n return JSON.stringify(output);\n } catch {\n return JSON.stringify(String(output));\n }\n }\n\n private static _parseAgentToolOutput(value: string | null): unknown {\n if (value === null) return undefined;\n try {\n return JSON.parse(value);\n } catch {\n return undefined;\n }\n }\n\n /**\n * Whether the run produced an assistant turn (text or tool-only). Used by the\n * post-eviction reconcile to mark a settled run `completed` even when it ended\n * without final text. A dedicated child facet starts with no assistant\n * messages, so a missing in-memory pre-turn snapshot is treated as empty.\n */\n private _hasRecoveredAgentToolAssistantTurn(runId: string): boolean {\n const before =\n this._agentToolPreTurnAssistantIds.get(runId) ?? new Set<string>();\n return this.messages.some(\n (msg) => msg.role === \"assistant\" && !before.has(msg.id)\n );\n }\n\n private _getAgentToolFinalText(runId: string): string | null {\n // A child facet is dedicated to a single agent-tool run, so any assistant\n // message it holds is that run's output. When the pre-turn snapshot is\n // missing — e.g. reconciling after a real eviction, where the in-memory\n // snapshot died with the original isolate (#1630) — treat it as empty so\n // the recovered transcript's assistant text is still surfaced as the\n // summary instead of being lost.\n const before =\n this._agentToolPreTurnAssistantIds.get(runId) ?? new Set<string>();\n for (const msg of this.messages) {\n if (msg.role !== \"assistant\" || before.has(msg.id)) continue;\n const text = msg.parts\n .map((part) => (part.type === \"text\" ? part.text : \"\"))\n .filter((part) => part.length > 0)\n .join(\"\\n\");\n if (text.length > 0) return text;\n }\n return null;\n }\n\n // ── Declarative scheduled tasks ─────────────────────────────────\n\n private _ensureDeclaredScheduledTasksTable(): void {\n if (this._declaredScheduledTasksTableEnsured) return;\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_think_scheduled_tasks (\n owner_key TEXT NOT NULL,\n task_id TEXT NOT NULL,\n schedule_hash TEXT NOT NULL,\n task_hash TEXT NOT NULL,\n schedule_id TEXT,\n next_run_at INTEGER,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n PRIMARY KEY (owner_key, task_id)\n )\n `;\n this._declaredScheduledTasksTableEnsured = true;\n }\n\n private _readDeclaredScheduledTaskRow(\n taskId: string\n ): DeclaredScheduledTaskRow | null {\n this._ensureDeclaredScheduledTasksTable();\n const ownerKey = this._declaredScheduleOwnerKey();\n const rows = this.sql<DeclaredScheduledTaskRow>`\n SELECT owner_key, task_id, schedule_hash, task_hash, schedule_id,\n next_run_at, created_at, updated_at\n FROM cf_think_scheduled_tasks\n WHERE task_id = ${taskId}\n AND owner_key = ${ownerKey}\n LIMIT 1\n `;\n return rows[0] ?? null;\n }\n\n private _listDeclaredScheduledTaskRows(): DeclaredScheduledTaskRow[] {\n this._ensureDeclaredScheduledTasksTable();\n const ownerKey = this._declaredScheduleOwnerKey();\n return this.sql<DeclaredScheduledTaskRow>`\n SELECT owner_key, task_id, schedule_hash, task_hash, schedule_id,\n next_run_at, created_at, updated_at\n FROM cf_think_scheduled_tasks\n WHERE owner_key = ${ownerKey}\n ORDER BY task_id ASC\n `;\n }\n\n private _updateDeclaredScheduledTaskSchedule(\n task: NormalizedDeclaredTask,\n ownerKey: string,\n scheduled: { scheduleId: string; scheduledFor: number },\n updatedAt = Date.now()\n ): void {\n this.sql`\n UPDATE cf_think_scheduled_tasks\n SET schedule_hash = ${task.scheduleHash},\n task_hash = ${task.taskHash},\n schedule_id = ${scheduled.scheduleId},\n next_run_at = ${scheduled.scheduledFor},\n updated_at = ${updatedAt}\n WHERE owner_key = ${ownerKey}\n AND task_id = ${task.taskId}\n `;\n }\n\n private async _normalizeDeclaredScheduledTasks(\n tasks: ThinkScheduledTasks,\n defaultTimezone: string | undefined\n ): Promise<Map<string, NormalizedDeclaredTask>> {\n const normalized = new Map<string, NormalizedDeclaredTask>();\n for (const [taskId, task] of Object.entries(tasks)) {\n if (!/^[A-Za-z0-9_-]+$/.test(taskId)) {\n throw new Error(\n `Invalid scheduled task id \"${taskId}\"; use letters, numbers, \"_\" or \"-\"`\n );\n }\n const schedule = parseDeclaredTaskSchedule(\n task.schedule,\n task.timezone,\n defaultTimezone\n );\n const hasPrompt = \"prompt\" in task && task.prompt !== undefined;\n const hasHandler = \"handler\" in task && task.handler !== undefined;\n if (hasPrompt === hasHandler) {\n throw new Error(\n `Scheduled task \"${taskId}\" must define exactly one of prompt or handler`\n );\n }\n const scheduleHash = stableHash({\n schedule,\n retry: task.retry\n });\n const actionHash = hasPrompt\n ? {\n type: \"prompt\",\n value: typeof task.prompt === \"string\" ? task.prompt : \"<function>\"\n }\n : { type: \"handler\" };\n const taskHash = stableHash({\n scheduleHash,\n action: actionHash,\n metadata: task.metadata\n });\n normalized.set(taskId, {\n taskId,\n ...(hasPrompt ? { prompt: task.prompt } : {}),\n ...(hasHandler ? { handler: task.handler } : {}),\n schedule,\n retry: task.retry,\n metadata: task.metadata,\n scheduleHash,\n taskHash\n });\n }\n return normalized;\n }\n\n private async _declaredScheduledTasksForNow(): Promise<\n Map<string, NormalizedDeclaredTask>\n > {\n const defaultTimezone = await this.getDefaultTimezone();\n const resolvedDefaultTimezone =\n defaultTimezone === undefined\n ? undefined\n : validateTimezone(defaultTimezone);\n return this._normalizeDeclaredScheduledTasks(\n await this.getScheduledTasks(),\n resolvedDefaultTimezone\n );\n }\n\n private _declaredScheduleOwnerKey(): string {\n return stableHash(this.selfPath);\n }\n\n private _declaredScheduleValidationError(\n rawSchedule: string,\n taskTimezone?: string,\n defaultTimezone?: string\n ): string | null {\n const resolvedDefaultTimezone =\n defaultTimezone === undefined\n ? undefined\n : validateTimezone(defaultTimezone);\n const result = tryParseDeclaredTaskSchedule(\n rawSchedule,\n taskTimezone,\n resolvedDefaultTimezone\n );\n return result.ok ? null : result.error;\n }\n\n private _nextDeclaredScheduleTimeForConfig(\n rawSchedule: string,\n now: Date,\n options: {\n taskTimezone?: string;\n defaultTimezone?: string;\n previousScheduledFor?: number;\n } = {}\n ): Date {\n const resolvedDefaultTimezone =\n options.defaultTimezone === undefined\n ? undefined\n : validateTimezone(options.defaultTimezone);\n return nextDeclaredScheduleTime(\n parseDeclaredTaskSchedule(\n rawSchedule,\n options.taskTimezone,\n resolvedDefaultTimezone\n ),\n now,\n options.previousScheduledFor\n );\n }\n\n private async _reconcileDeclaredScheduledTasks(): Promise<void> {\n const tasks = await this._declaredScheduledTasksForNow();\n this._ensureDeclaredScheduledTasksTable();\n const ownerKey = this._declaredScheduleOwnerKey();\n const now = Date.now();\n const existing = this._listDeclaredScheduledTaskRows();\n const seen = new Set<string>();\n\n for (const [taskId, task] of tasks) {\n seen.add(taskId);\n const row = existing.find((candidate) => candidate.task_id === taskId);\n if (!row) {\n this.sql`\n INSERT INTO cf_think_scheduled_tasks (\n owner_key, task_id, schedule_hash, task_hash, schedule_id,\n next_run_at, created_at, updated_at\n )\n VALUES (\n ${ownerKey}, ${taskId}, ${task.scheduleHash}, ${task.taskHash},\n NULL, NULL, ${now}, ${now}\n )\n `;\n const scheduled = await this._scheduleDeclaredTaskOccurrence(\n task,\n new Date(now)\n );\n this._updateDeclaredScheduledTaskSchedule(\n task,\n ownerKey,\n scheduled,\n now\n );\n continue;\n }\n\n if (row.schedule_hash !== task.scheduleHash) {\n if (row.schedule_id) await this.cancelSchedule(row.schedule_id);\n this.sql`\n UPDATE cf_think_scheduled_tasks\n SET schedule_hash = ${task.scheduleHash},\n task_hash = ${task.taskHash},\n schedule_id = NULL,\n next_run_at = NULL,\n updated_at = ${now}\n WHERE owner_key = ${ownerKey}\n AND task_id = ${taskId}\n `;\n const scheduled = await this._scheduleDeclaredTaskOccurrence(\n task,\n new Date(now)\n );\n this._updateDeclaredScheduledTaskSchedule(\n task,\n ownerKey,\n scheduled,\n now\n );\n continue;\n }\n\n if (!row.schedule_id) {\n const scheduled =\n row.next_run_at === null\n ? await this._scheduleDeclaredTaskOccurrence(task, new Date(now))\n : await this._scheduleDeclaredTaskOccurrenceAt(\n task,\n row.next_run_at\n );\n this._updateDeclaredScheduledTaskSchedule(\n task,\n ownerKey,\n scheduled,\n now\n );\n continue;\n }\n\n if (row.schedule_id) {\n const schedule = await this.getScheduleById(row.schedule_id);\n if (!schedule) {\n const scheduled =\n row.next_run_at === null\n ? await this._scheduleDeclaredTaskOccurrence(task, new Date(now))\n : await this._scheduleDeclaredTaskOccurrenceAt(\n task,\n row.next_run_at\n );\n this._updateDeclaredScheduledTaskSchedule(\n task,\n ownerKey,\n scheduled,\n now\n );\n continue;\n }\n }\n\n if (row.task_hash !== task.taskHash) {\n this.sql`\n UPDATE cf_think_scheduled_tasks\n SET task_hash = ${task.taskHash}, updated_at = ${now}\n WHERE owner_key = ${ownerKey}\n AND task_id = ${taskId}\n `;\n }\n }\n\n for (const row of existing) {\n if (seen.has(row.task_id)) continue;\n if (row.schedule_id) await this.cancelSchedule(row.schedule_id);\n this.sql`\n DELETE FROM cf_think_scheduled_tasks\n WHERE owner_key = ${ownerKey}\n AND task_id = ${row.task_id}\n `;\n }\n }\n\n private async _scheduleDeclaredTaskOccurrence(\n task: NormalizedDeclaredTask,\n now: Date,\n previousScheduledFor?: number\n ): Promise<{ scheduleId: string; scheduledFor: number }> {\n const next = nextDeclaredScheduleTime(\n task.schedule,\n now,\n previousScheduledFor\n );\n return this._scheduleDeclaredTaskOccurrenceAt(task, next.getTime());\n }\n\n private async _scheduleDeclaredTaskOccurrenceAt(\n task: NormalizedDeclaredTask,\n scheduledFor: number\n ): Promise<{ scheduleId: string; scheduledFor: number }> {\n const schedule = await this.schedule<DeclaredScheduledTaskPayload>(\n new Date(scheduledFor),\n \"_runDeclaredScheduledTask\",\n {\n taskId: task.taskId,\n scheduleHash: task.scheduleHash,\n scheduledFor\n },\n { idempotent: true }\n );\n return { scheduleId: schedule.id, scheduledFor };\n }\n\n private async _advanceDeclaredScheduledTask(\n task: NormalizedDeclaredTask,\n payload: DeclaredScheduledTaskPayload,\n ownerKey: string\n ): Promise<void> {\n const scheduled = await this._scheduleDeclaredTaskOccurrence(\n task,\n new Date(),\n payload.scheduledFor\n );\n this._updateDeclaredScheduledTaskSchedule(task, ownerKey, scheduled);\n }\n\n private _declaredScheduledTaskContext(\n task: NormalizedDeclaredTask,\n payload: DeclaredScheduledTaskPayload,\n ownerKey: string\n ): ThinkScheduledTaskContext {\n const occurrenceKey = `${payload.taskId}:${payload.scheduledFor}`;\n return {\n taskId: payload.taskId,\n scheduledFor: payload.scheduledFor,\n scheduledForDate: new Date(payload.scheduledFor),\n occurrenceKey,\n idempotencyKey: `think-schedule:${ownerKey}:${occurrenceKey}`,\n schedule: task.schedule.normalizedSchedule,\n scheduleKind: task.schedule.kind,\n ...(task.schedule.kind === \"wall-clock\" && {\n timezone: task.schedule.timezone\n }),\n ...(task.metadata !== undefined && { metadata: task.metadata })\n };\n }\n\n async _runDeclaredScheduledTask(\n payload: DeclaredScheduledTaskPayload\n ): Promise<void> {\n if (\n !payload ||\n typeof payload.taskId !== \"string\" ||\n typeof payload.scheduleHash !== \"string\" ||\n typeof payload.scheduledFor !== \"number\"\n ) {\n throw new Error(\"Invalid declared scheduled task payload\");\n }\n\n const row = this._readDeclaredScheduledTaskRow(payload.taskId);\n if (!row || row.schedule_hash !== payload.scheduleHash) return;\n if (row.next_run_at !== null && row.next_run_at > payload.scheduledFor) {\n return;\n }\n\n const tasks = await this._declaredScheduledTasksForNow();\n const task = tasks.get(payload.taskId);\n if (!task || task.scheduleHash !== payload.scheduleHash) return;\n\n const ownerKey = this._declaredScheduleOwnerKey();\n const context = this._declaredScheduledTaskContext(task, payload, ownerKey);\n\n let actionError: unknown;\n try {\n await this.retry(async () => {\n if (task.prompt !== undefined) {\n const prompt =\n typeof task.prompt === \"function\"\n ? await task.prompt()\n : task.prompt;\n await this.submitMessages(\n [\n {\n id: crypto.randomUUID(),\n role: \"user\",\n parts: [{ type: \"text\", text: prompt }]\n }\n ],\n {\n idempotencyKey: context.idempotencyKey,\n metadata: {\n ...task.metadata,\n source: \"scheduled-task\",\n ownerKey,\n taskId: payload.taskId,\n scheduledFor: payload.scheduledFor,\n schedule: task.schedule.normalizedSchedule\n }\n }\n );\n } else {\n await task.handler?.(context);\n }\n }, task.retry);\n } catch (error) {\n actionError = error;\n } finally {\n await this._advanceDeclaredScheduledTask(task, payload, ownerKey);\n }\n\n if (actionError !== undefined) {\n console.error(\n `[Think] Scheduled task \"${payload.taskId}\" failed; next occurrence was still scheduled`,\n actionError\n );\n try {\n await this.onError(actionError);\n } catch {\n // Preserve recurrence even if user error handling fails.\n }\n }\n }\n\n // ── Durable programmatic submissions ───────────────────────────\n\n private _ensureSubmissionTable(): void {\n if (this._submissionTableEnsured) return;\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_think_submissions (\n submission_id TEXT PRIMARY KEY,\n idempotency_key TEXT UNIQUE,\n request_id TEXT,\n stream_id TEXT,\n status TEXT NOT NULL,\n messages_json TEXT NOT NULL,\n metadata_json TEXT,\n error_message TEXT,\n created_at INTEGER NOT NULL,\n messages_applied_at INTEGER,\n started_at INTEGER,\n completed_at INTEGER\n )\n `;\n this.sql`\n CREATE INDEX IF NOT EXISTS cf_think_submissions_status_created_idx\n ON cf_think_submissions (status, created_at, submission_id)\n `;\n this.sql`\n CREATE INDEX IF NOT EXISTS cf_think_submissions_request_status_idx\n ON cf_think_submissions (request_id, status)\n `;\n this.sql`\n CREATE INDEX IF NOT EXISTS cf_think_submissions_status_completed_idx\n ON cf_think_submissions (status, completed_at, created_at)\n `;\n this._submissionTableEnsured = true;\n }\n\n private _ensureWorkflowNotificationTable(): void {\n if (this._workflowNotificationTableEnsured) return;\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_think_workflow_notifications (\n notification_id TEXT PRIMARY KEY,\n submission_id TEXT NOT NULL,\n workflow_name TEXT NOT NULL,\n workflow_id TEXT NOT NULL,\n event_type TEXT NOT NULL,\n payload_json TEXT NOT NULL,\n attempts INTEGER NOT NULL DEFAULT 0,\n last_error TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n delivered_at INTEGER\n )\n `;\n try {\n this.ctx.storage.sql.exec(\n \"ALTER TABLE cf_think_workflow_notifications ADD COLUMN delivered_at INTEGER\"\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (!message.toLowerCase().includes(\"duplicate column\")) {\n throw error;\n }\n }\n this.sql`\n CREATE INDEX IF NOT EXISTS cf_think_workflow_notifications_created_idx\n ON cf_think_workflow_notifications (delivered_at, created_at, notification_id)\n `;\n this._workflowNotificationTableEnsured = true;\n }\n\n private _readSubmission(submissionId: string): ThinkSubmissionRow | null {\n this._ensureSubmissionTable();\n const rows = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE submission_id = ${submissionId}\n LIMIT 1\n `;\n return rows[0] ?? null;\n }\n\n private _readSubmissionByIdempotencyKey(\n idempotencyKey: string\n ): ThinkSubmissionRow | null {\n this._ensureSubmissionTable();\n const rows = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE idempotency_key = ${idempotencyKey}\n LIMIT 1\n `;\n return rows[0] ?? null;\n }\n\n private _normalizeStatusFilter(\n status?: ThinkSubmissionStatus | ThinkSubmissionStatus[]\n ): Set<ThinkSubmissionStatus> | null {\n if (!status) return null;\n return new Set(Array.isArray(status) ? status : [status]);\n }\n\n private _listSubmissionRows(\n options?: ListSubmissionsOptions\n ): ThinkSubmissionRow[] {\n this._ensureSubmissionTable();\n const limit = Math.min(Math.max(options?.limit ?? 50, 1), 100);\n const statuses = this._normalizeStatusFilter(options?.status);\n if (statuses) {\n return [...statuses]\n .flatMap((status) => this._listSubmissionRowsByStatus(status, limit))\n .sort((a, b) =>\n b.created_at === a.created_at\n ? b.submission_id.localeCompare(a.submission_id)\n : b.created_at - a.created_at\n )\n .slice(0, limit);\n }\n\n const rows = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n ORDER BY created_at DESC, submission_id DESC\n LIMIT ${limit}\n `;\n return rows;\n }\n\n private _listSubmissionRowsByStatus(\n status: ThinkSubmissionStatus,\n limit: number\n ): ThinkSubmissionRow[] {\n return this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE status = ${status}\n ORDER BY created_at DESC, submission_id DESC\n LIMIT ${limit}\n `;\n }\n\n private _inspectionFromSubmissionRow(\n row: ThinkSubmissionRow\n ): ThinkSubmissionInspection {\n const metadata = this._parseJsonObject(row.metadata_json);\n return {\n submissionId: row.submission_id,\n idempotencyKey: row.idempotency_key ?? undefined,\n requestId: row.request_id ?? undefined,\n status: row.status,\n error: row.error_message ?? undefined,\n metadata: metadata ?? undefined,\n createdAt: row.created_at,\n startedAt: row.started_at ?? undefined,\n completedAt: row.completed_at ?? undefined\n };\n }\n\n private _parseJsonObject(\n value: string | null\n ): Record<string, unknown> | null {\n if (value === null) return null;\n try {\n const parsed = JSON.parse(value) as unknown;\n if (\n parsed !== null &&\n typeof parsed === \"object\" &&\n !Array.isArray(parsed)\n ) {\n return parsed as Record<string, unknown>;\n }\n } catch {\n // Invalid metadata should not prevent inspection.\n }\n return null;\n }\n\n private _parseSubmissionMessages(value: string): UIMessage[] {\n const parsed = JSON.parse(value) as unknown;\n if (!Array.isArray(parsed)) {\n throw new Error(\"Stored submission messages are invalid\");\n }\n return parsed as UIMessage[];\n }\n\n private _serializeSubmissionMessages(messages: UIMessage[]): string {\n return JSON.stringify(\n messages.map((message) => enforceRowSizeLimit(sanitizeMessage(message)))\n );\n }\n\n private _serializeMetadata(\n metadata: Record<string, unknown> | undefined\n ): string | null {\n return metadata === undefined ? null : JSON.stringify(metadata);\n }\n\n private _readWorkflowPromptContext(\n metadata: Record<string, unknown> | null\n ): ThinkWorkflowPromptContext | null {\n const workflowPromptValue = metadata?.[THINK_WORKFLOW_PROMPT_METADATA_KEY];\n if (\n workflowPromptValue === null ||\n typeof workflowPromptValue !== \"object\" ||\n Array.isArray(workflowPromptValue)\n ) {\n return null;\n }\n const workflowPrompt = workflowPromptValue as Record<string, unknown>;\n const workflowValue = workflowPrompt.workflow;\n if (\n workflowValue === null ||\n typeof workflowValue !== \"object\" ||\n Array.isArray(workflowValue)\n ) {\n return null;\n }\n const workflowRecord = workflowValue as Record<string, unknown>;\n if (\n typeof workflowRecord.name !== \"string\" ||\n typeof workflowRecord.id !== \"string\" ||\n typeof workflowRecord.stepName !== \"string\" ||\n typeof workflowRecord.eventType !== \"string\"\n ) {\n return null;\n }\n const output = workflowPrompt.output;\n const outputRecord =\n output !== null && typeof output === \"object\" && !Array.isArray(output)\n ? (output as Record<string, unknown>)\n : null;\n return {\n workflow: {\n name: workflowRecord.name,\n id: workflowRecord.id,\n stepName: workflowRecord.stepName,\n eventType: workflowRecord.eventType\n },\n ...(outputRecord\n ? {\n output: {\n schema: outputRecord.schema\n }\n }\n : {}),\n ...(typeof workflowPrompt.fingerprint === \"string\" && {\n fingerprint: workflowPrompt.fingerprint\n })\n };\n }\n\n private async _emitSubmissionStatus(\n row: ThinkSubmissionRow,\n output?: unknown\n ): Promise<void> {\n const inspection = this._inspectionFromSubmissionRow(row);\n this._emit(\"submission:status\", {\n submissionId: inspection.submissionId,\n requestId: inspection.requestId,\n status: inspection.status\n });\n if (inspection.status === \"error\" && inspection.error) {\n this._emit(\"submission:error\", {\n submissionId: inspection.submissionId,\n requestId: inspection.requestId,\n error: inspection.error\n });\n }\n if (this._isTerminalSubmissionStatus(inspection.status)) {\n await this._enqueueWorkflowNotification(inspection, output);\n }\n await this.keepAliveWhile(async () => {\n try {\n await this.onSubmissionStatus(inspection);\n } catch (error) {\n console.error(\"[Think] onSubmissionStatus failed\", error);\n }\n });\n }\n\n protected onSubmissionStatus(\n _submission: ThinkSubmissionInspection\n ): void | Promise<void> {}\n\n private async _enqueueWorkflowNotification(\n submission: ThinkSubmissionInspection,\n output?: unknown\n ): Promise<void> {\n this._insertWorkflowNotification(submission, output);\n this._startWorkflowNotificationDrain();\n }\n\n private _insertWorkflowNotification(\n submission: ThinkSubmissionInspection,\n output?: unknown,\n override?: { status: ThinkSubmissionStatus; error: string }\n ): boolean {\n const workflowPrompt = this._readWorkflowPromptContext(\n submission.metadata ?? null\n );\n if (!workflowPrompt) return false;\n\n this._ensureWorkflowNotificationTable();\n const now = Date.now();\n const status = override?.status ?? submission.status;\n const error = override?.error ?? submission.error;\n const payload = {\n submissionId: submission.submissionId,\n status,\n ...(status === \"completed\" && { output }),\n ...(error && { error })\n };\n this.sql`\n INSERT OR IGNORE INTO cf_think_workflow_notifications (\n notification_id, submission_id, workflow_name, workflow_id, event_type,\n payload_json, attempts, last_error, created_at, updated_at, delivered_at\n )\n VALUES (\n ${`${submission.submissionId}:${workflowPrompt.workflow.eventType}`},\n ${submission.submissionId},\n ${workflowPrompt.workflow.name},\n ${workflowPrompt.workflow.id},\n ${workflowPrompt.workflow.eventType},\n ${JSON.stringify(payload)},\n 0,\n NULL,\n ${now},\n ${now},\n NULL\n )\n `;\n return true;\n }\n\n private _recoverWorkflowNotifications(): void {\n this._ensureSubmissionTable();\n this._ensureWorkflowNotificationTable();\n const terminalRows = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE status IN ('aborted', 'skipped', 'error')\n ORDER BY completed_at DESC, created_at DESC\n LIMIT 100\n `;\n\n let recovered = false;\n for (const row of terminalRows) {\n const inspection = this._inspectionFromSubmissionRow(row);\n const workflowPrompt = this._readWorkflowPromptContext(\n inspection.metadata ?? null\n );\n if (!workflowPrompt) continue;\n const notificationId = `${inspection.submissionId}:${workflowPrompt.workflow.eventType}`;\n const existing = this.sql<{ notification_id: string }>`\n SELECT notification_id\n FROM cf_think_workflow_notifications\n WHERE notification_id = ${notificationId}\n LIMIT 1\n `;\n if (existing[0]) continue;\n\n recovered = this._insertWorkflowNotification(inspection) || recovered;\n }\n if (recovered) this._startWorkflowNotificationDrain();\n }\n\n private _startWorkflowNotificationDrain(): void {\n void this.keepAliveWhile(() => this._drainWorkflowNotifications()).catch(\n (error) => {\n console.error(\"[Think] Failed to drain workflow notifications\", error);\n void this._scheduleWorkflowNotificationAlarm();\n }\n );\n }\n\n private async _drainWorkflowNotifications(): Promise<void> {\n if (this._drainingWorkflowNotifications) return;\n this._ensureWorkflowNotificationTable();\n this._drainingWorkflowNotifications = true;\n try {\n const rows = this.sql<ThinkWorkflowNotificationRow>`\n SELECT notification_id, submission_id, workflow_name, workflow_id,\n event_type, payload_json, attempts, last_error, created_at,\n updated_at, delivered_at\n FROM cf_think_workflow_notifications\n WHERE delivered_at IS NULL\n ORDER BY created_at ASC, notification_id ASC\n LIMIT 25\n `;\n for (const row of rows) {\n try {\n const payload = JSON.parse(row.payload_json) as unknown;\n await this.sendWorkflowEvent(\n row.workflow_name as string & {},\n row.workflow_id,\n {\n type: row.event_type,\n payload\n }\n );\n this.sql`\n UPDATE cf_think_workflow_notifications\n SET payload_json = '{}',\n last_error = NULL,\n updated_at = ${Date.now()},\n delivered_at = ${Date.now()}\n WHERE notification_id = ${row.notification_id}\n AND delivered_at IS NULL\n `;\n } catch (error) {\n this.sql`\n UPDATE cf_think_workflow_notifications\n SET attempts = attempts + 1,\n last_error = ${error instanceof Error ? error.message : String(error)},\n updated_at = ${Date.now()}\n WHERE notification_id = ${row.notification_id}\n `;\n }\n }\n } finally {\n this._drainingWorkflowNotifications = false;\n }\n await this._scheduleWorkflowNotificationAlarm();\n }\n\n private async _scheduleWorkflowNotificationAlarm(): Promise<void> {\n this._ensureWorkflowNotificationTable();\n const pending = this.sql<{ attempts: number }>`\n SELECT attempts\n FROM cf_think_workflow_notifications\n WHERE delivered_at IS NULL\n ORDER BY created_at ASC, notification_id ASC\n LIMIT 1\n `;\n if (!pending[0]) return;\n const delayMs = Math.min(\n 5 * 60 * 1000,\n 1000 * 2 ** Math.min(pending[0].attempts, 8)\n );\n const nextAlarm = Date.now() + delayMs;\n const existingAlarm = await this.ctx.storage.getAlarm();\n if (existingAlarm === null || existingAlarm > nextAlarm) {\n await this.ctx.storage.setAlarm(nextAlarm);\n }\n }\n\n async inspectSubmission(\n submissionId: string\n ): Promise<ThinkSubmissionInspection | null> {\n const row = this._readSubmission(submissionId);\n return row ? this._inspectionFromSubmissionRow(row) : null;\n }\n\n async listSubmissions(\n options?: ListSubmissionsOptions\n ): Promise<ThinkSubmissionInspection[]> {\n return this._listSubmissionRows(options).map((row) =>\n this._inspectionFromSubmissionRow(row)\n );\n }\n\n async deleteSubmission(submissionId: string): Promise<boolean> {\n const row = this._readSubmission(submissionId);\n if (!row || !this._isTerminalSubmissionStatus(row.status)) return false;\n this.sql`\n DELETE FROM cf_think_submissions\n WHERE submission_id = ${submissionId}\n AND status IN ('completed', 'aborted', 'skipped', 'error')\n `;\n return true;\n }\n\n async deleteSubmissions(options?: DeleteSubmissionsOptions): Promise<number> {\n this._ensureSubmissionTable();\n const statuses =\n this._normalizeStatusFilter(options?.status) ??\n new Set<ThinkSubmissionStatus>([\n \"completed\",\n \"aborted\",\n \"skipped\",\n \"error\"\n ]);\n const limit = Math.min(Math.max(options?.limit ?? 100, 1), 500);\n const completedBefore = options?.completedBefore?.getTime();\n const rows = [...statuses]\n .flatMap((status) =>\n this._listTerminalSubmissionRowsForDelete(\n status,\n limit,\n completedBefore\n )\n )\n .sort((a, b) =>\n (a.completed_at ?? a.created_at) === (b.completed_at ?? b.created_at)\n ? a.created_at - b.created_at\n : (a.completed_at ?? a.created_at) - (b.completed_at ?? b.created_at)\n )\n .slice(0, limit);\n\n let deleted = 0;\n for (const row of rows) {\n if (!this._isTerminalSubmissionStatus(row.status)) continue;\n this.sql`\n DELETE FROM cf_think_submissions\n WHERE submission_id = ${row.submission_id}\n AND status IN ('completed', 'aborted', 'skipped', 'error')\n `;\n deleted++;\n }\n return deleted;\n }\n\n private _listTerminalSubmissionRowsForDelete(\n status: ThinkSubmissionStatus,\n limit: number,\n completedBefore: number | undefined\n ): ThinkSubmissionRow[] {\n if (completedBefore === undefined) {\n return this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE status = ${status}\n ORDER BY completed_at ASC, created_at ASC\n LIMIT ${limit}\n `;\n }\n\n return this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE status = ${status}\n AND completed_at IS NOT NULL\n AND completed_at < ${completedBefore}\n ORDER BY completed_at ASC, created_at ASC\n LIMIT ${limit}\n `;\n }\n\n private _isTerminalSubmissionStatus(status: ThinkSubmissionStatus): boolean {\n return (\n status === \"completed\" ||\n status === \"aborted\" ||\n status === \"skipped\" ||\n status === \"error\"\n );\n }\n\n async cancelSubmission(\n submissionId: string,\n reason?: unknown\n ): Promise<void> {\n const row = this._readSubmission(submissionId);\n if (!row || this._isTerminalSubmissionStatus(row.status)) return;\n\n const completedAt = Date.now();\n const errorMessage =\n reason === undefined\n ? null\n : reason instanceof Error\n ? reason.message\n : String(reason);\n this._submissionAbortControllers.get(submissionId)?.abort(reason);\n if (row.request_id) {\n this.abortRequest(row.request_id, reason);\n }\n\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'aborted',\n error_message = ${errorMessage},\n completed_at = ${completedAt}\n WHERE submission_id = ${submissionId}\n AND status IN ('pending', 'running')\n `;\n\n const updated = this._readSubmission(submissionId);\n if (updated?.status === \"aborted\") {\n await this._emitSubmissionStatus(updated);\n }\n }\n\n async submitMessages(\n messages: UIMessage[],\n options?: SubmitMessagesOptions\n ): Promise<SubmitMessagesResult> {\n this._ensureSubmissionTable();\n if (messages.length === 0) {\n throw new Error(\"submitMessages requires at least one message\");\n }\n\n const existingById = options?.submissionId\n ? this._readSubmission(options.submissionId)\n : null;\n const existingByKey = options?.idempotencyKey\n ? this._readSubmissionByIdempotencyKey(options.idempotencyKey)\n : null;\n\n if (\n existingById &&\n existingByKey &&\n existingById.submission_id !== existingByKey.submission_id\n ) {\n throw new Error(\n \"submissionId and idempotencyKey refer to different submissions\"\n );\n }\n if (\n existingByKey &&\n options?.submissionId &&\n existingByKey.submission_id !== options.submissionId\n ) {\n throw new Error(\n \"submissionId and idempotencyKey refer to different submissions\"\n );\n }\n if (\n existingById &&\n options?.idempotencyKey &&\n existingById.idempotency_key !== null &&\n existingById.idempotency_key !== options.idempotencyKey\n ) {\n throw new Error(\n \"submissionId and idempotencyKey refer to different submissions\"\n );\n }\n\n const existing = existingById ?? existingByKey;\n if (existing) {\n if (existing.status === \"pending\") {\n await this._scheduleSubmissionDrain();\n this._startSubmissionDrain();\n }\n return {\n ...this._inspectionFromSubmissionRow(existing),\n accepted: false\n };\n }\n\n const submissionId = options?.submissionId ?? crypto.randomUUID();\n const requestId = submissionId;\n const now = Date.now();\n const messagesJson = this._serializeSubmissionMessages(messages);\n const metadataJson = this._serializeMetadata(options?.metadata);\n\n this.sql`\n INSERT INTO cf_think_submissions (\n submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n )\n VALUES (\n ${submissionId}, ${options?.idempotencyKey ?? null}, ${requestId},\n NULL, 'pending', ${messagesJson}, ${metadataJson}, NULL, ${now},\n NULL, NULL, NULL\n )\n `;\n\n const row = this._readSubmission(submissionId);\n if (!row) {\n throw new Error(\"Failed to persist submission\");\n }\n\n this._emit(\"submission:create\", {\n submissionId: row.submission_id,\n requestId: row.request_id ?? undefined,\n idempotencyKey: row.idempotency_key ?? undefined\n });\n await this._emitSubmissionStatus(row);\n await this._scheduleSubmissionDrain();\n this._startSubmissionDrain();\n\n return {\n ...this._inspectionFromSubmissionRow(row),\n accepted: true\n };\n }\n\n private async _scheduleSubmissionDrain(): Promise<void> {\n await this.schedule(0, \"_drainThinkSubmissions\", undefined, {\n idempotent: true\n });\n }\n\n private _startSubmissionDrain(): void {\n void this.keepAliveWhile(() => this._drainSubmissions()).catch((error) => {\n console.error(\"[Think] Failed to drain submissions\", error);\n });\n }\n\n async _drainThinkSubmissions(): Promise<void> {\n await this._drainSubmissions();\n }\n\n private async _drainSubmissions(): Promise<void> {\n this._ensureSubmissionTable();\n if (this._drainingSubmissions) return;\n this._drainingSubmissions = true;\n try {\n while (true) {\n const rows = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE status = 'pending'\n ORDER BY created_at ASC, submission_id ASC\n LIMIT 1\n `;\n const row = rows[0];\n if (!row) break;\n await this._runSubmission(row);\n }\n } finally {\n this._drainingSubmissions = false;\n }\n }\n\n private async _runSubmission(row: ThinkSubmissionRow): Promise<void> {\n const requestId = row.request_id ?? row.submission_id;\n const startedAt = Date.now();\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'running',\n request_id = ${requestId},\n started_at = ${startedAt}\n WHERE submission_id = ${row.submission_id}\n AND status = 'pending'\n `;\n\n const claimed = this._readSubmission(row.submission_id);\n if (!claimed || claimed.status !== \"running\") return;\n await this._emitSubmissionStatus(claimed);\n\n const controller = new AbortController();\n this._submissionAbortControllers.set(row.submission_id, controller);\n let output: unknown;\n try {\n const messages = this._parseSubmissionMessages(row.messages_json);\n const metadata = this._parseJsonObject(row.metadata_json);\n const workflowPrompt = this._readWorkflowPromptContext(metadata);\n const result = await this._runProgrammaticMessagesTurn(\n requestId,\n messages,\n {\n signal: controller.signal,\n captureProgrammaticStreamError: true,\n captureOutput: Boolean(workflowPrompt?.output),\n workflowPrompt: workflowPrompt ?? undefined,\n onMessagesApplied: () => {\n this.sql`\n UPDATE cf_think_submissions\n SET messages_applied_at = ${Date.now()}\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n AND messages_applied_at IS NULL\n `;\n }\n }\n );\n output = result.output;\n const streamId =\n this._resumableStream\n .getAllStreamMetadata()\n .find((metadata) => metadata.request_id === result.requestId)?.id ??\n null;\n const streamError = this._programmaticStreamErrors.get(result.requestId);\n const finalStatus = this._getSubmissionFinalStatus(\n result.status,\n result.error ?? streamError\n );\n const errorMessage = result.error ?? streamError ?? null;\n const completedAt = Date.now();\n this.ctx.storage.transactionSync(() => {\n this.sql`\n UPDATE cf_think_submissions\n SET status = ${finalStatus},\n request_id = ${result.requestId},\n stream_id = ${streamId},\n error_message = ${finalStatus === \"error\" ? errorMessage : null},\n completed_at = ${completedAt}\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n `;\n this._insertWorkflowNotification(\n {\n ...this._inspectionFromSubmissionRow(claimed),\n requestId: result.requestId,\n status: finalStatus,\n error:\n finalStatus === \"error\" ? (errorMessage ?? undefined) : undefined,\n completedAt\n },\n output\n );\n });\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n const completedAt = Date.now();\n this.ctx.storage.transactionSync(() => {\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'error',\n error_message = ${errorMessage},\n completed_at = ${completedAt}\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n `;\n this._insertWorkflowNotification({\n ...this._inspectionFromSubmissionRow(claimed),\n status: \"error\",\n error: errorMessage,\n completedAt\n });\n });\n } finally {\n this._programmaticStreamErrors.delete(requestId);\n this._submissionAbortControllers.delete(row.submission_id);\n const updated = this._readSubmission(row.submission_id);\n if (updated && this._isTerminalSubmissionStatus(updated.status)) {\n await this._emitSubmissionStatus(updated, output);\n }\n }\n }\n\n private _getSubmissionFinalStatus(\n resultStatus: SaveMessagesResult[\"status\"],\n streamError: string | undefined\n ): ThinkSubmissionStatus {\n return resultStatus === \"completed\" && streamError ? \"error\" : resultStatus;\n }\n\n private _markPendingSubmissionsSkipped(): ThinkSubmissionRow[] {\n this._ensureSubmissionTable();\n const pending = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE status = 'pending'\n `;\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'skipped',\n error_message = 'Submission was skipped by turn reset.',\n completed_at = ${Date.now()}\n WHERE status = 'pending'\n `;\n return pending;\n }\n\n private async _emitSkippedSubmissions(\n skipped: ThinkSubmissionRow[]\n ): Promise<void> {\n for (const row of skipped) {\n const updated = this._readSubmission(row.submission_id);\n if (updated?.status === \"skipped\") {\n await this._emitSubmissionStatus(updated);\n }\n }\n }\n\n private async _recoverSubmissionsOnStart(): Promise<void> {\n this._ensureSubmissionTable();\n\n const running = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE status = 'running'\n `;\n\n for (const row of running) {\n if (row.messages_applied_at === null) {\n let appliedState: \"none\" | \"partial\" | \"all\";\n try {\n appliedState = await this._getSubmissionMessagesAppliedState(row);\n } catch (error) {\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'error',\n error_message = ${error instanceof Error ? error.message : String(error)},\n completed_at = ${Date.now()}\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n `;\n const updated = this._readSubmission(row.submission_id);\n if (updated?.status === \"error\") {\n await this._emitSubmissionStatus(updated);\n }\n continue;\n }\n if (appliedState !== \"none\") {\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'error',\n error_message = ${appliedState === \"all\" ? \"Submission was interrupted after messages were applied.\" : \"Submission was interrupted after messages were partially applied.\"},\n completed_at = ${Date.now()}\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n `;\n const updated = this._readSubmission(row.submission_id);\n if (updated?.status === \"error\") {\n await this._emitSubmissionStatus(updated);\n }\n continue;\n }\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'pending',\n started_at = NULL\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n `;\n const updated = this._readSubmission(row.submission_id);\n if (updated?.status === \"pending\") {\n await this._emitSubmissionStatus(updated);\n }\n continue;\n }\n\n if (\n row.request_id &&\n ((this._hasRecoverableChatTurn(row.request_id) &&\n this._hasFreshRecoverableSubmissionEvidence(row)) ||\n this._hasScheduledRecoveredContinuation(row.request_id))\n ) {\n continue;\n }\n\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'error',\n error_message = 'Submission was interrupted after messages were applied.',\n completed_at = ${Date.now()}\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n `;\n const updated = this._readSubmission(row.submission_id);\n if (updated?.status === \"error\") {\n await this._emitSubmissionStatus(updated);\n }\n }\n }\n\n private async _getSubmissionMessagesAppliedState(\n row: ThinkSubmissionRow\n ): Promise<\"none\" | \"partial\" | \"all\"> {\n const messages = this._parseSubmissionMessages(row.messages_json);\n if (messages.length === 0) return \"all\";\n\n let applied = 0;\n for (const message of messages) {\n if (await this.session.getMessage(message.id)) applied++;\n }\n\n if (applied === 0) return \"none\";\n return applied === messages.length ? \"all\" : \"partial\";\n }\n\n private _hasRecoverableChatTurn(requestId: string): boolean {\n const fiberRows = this.sql<{ id: string }>`\n SELECT id FROM cf_agents_runs\n WHERE name = ${(this.constructor as typeof Think).CHAT_FIBER_NAME + \":\" + requestId}\n LIMIT 1\n `;\n if (fiberRows.length > 0) return true;\n\n const streamRows = this.sql<{ id: string }>`\n SELECT id FROM cf_ai_chat_stream_metadata\n WHERE request_id = ${requestId}\n AND status = 'streaming'\n LIMIT 1\n `;\n return streamRows.length > 0;\n }\n\n private _hasFreshRecoverableSubmissionEvidence(row: ThinkSubmissionRow) {\n if (!row.request_id) return false;\n const cutoff =\n Date.now() - (this.constructor as typeof Think).submissionRecoveryStaleMs;\n\n const fiberRows = this.sql<{ created_at: number }>`\n SELECT created_at FROM cf_agents_runs\n WHERE name = ${(this.constructor as typeof Think).CHAT_FIBER_NAME + \":\" + row.request_id}\n LIMIT 1\n `;\n if (fiberRows[0] && fiberRows[0].created_at >= cutoff) return true;\n\n const streamRows = this.sql<{ created_at: number }>`\n SELECT created_at FROM cf_ai_chat_stream_metadata\n WHERE request_id = ${row.request_id}\n AND status = 'streaming'\n ORDER BY created_at DESC\n LIMIT 1\n `;\n return streamRows[0] ? streamRows[0].created_at >= cutoff : false;\n }\n\n private _hasScheduledRecoveredContinuation(requestId: string): boolean {\n const rows = this.sql<{ payload: string | null }>`\n SELECT payload FROM cf_agents_schedules\n WHERE callback = '_chatRecoveryContinue'\n `;\n return rows.some((row) => {\n if (!row.payload) return false;\n try {\n const payload = JSON.parse(row.payload) as unknown;\n return (\n payload !== null &&\n typeof payload === \"object\" &&\n \"recoveredRequestId\" in payload &&\n (payload as { recoveredRequestId?: unknown }).recoveredRequestId ===\n requestId\n );\n } catch {\n return false;\n }\n });\n }\n\n // ── Programmatic API ───────────────────────────────────────────\n\n /**\n * Inject messages and trigger a model turn — without a WebSocket request.\n *\n * Use for scheduled responses, webhook-triggered turns, proactive agents,\n * or chaining from `onChatResponse`.\n *\n * Accepts static messages or a callback that derives messages from the\n * current state (useful when multiple calls queue up — the callback runs\n * with the latest messages when the turn actually starts).\n *\n * Pass `options.signal` to cancel the turn from outside without knowing\n * the internally-generated request id. The signal is linked to the\n * registry's controller for this turn — when it aborts, the inference\n * loop's signal aborts and the result reports `status: \"aborted\"`.\n * Pre-aborted signals short-circuit before any model work runs. See\n * {@link SaveMessagesOptions} for the integration point.\n *\n * @example Scheduled follow-up\n * ```typescript\n * async onScheduled() {\n * await this.saveMessages([{\n * id: crypto.randomUUID(),\n * role: \"user\",\n * parts: [{ type: \"text\", text: \"Time for your daily summary.\" }]\n * }]);\n * }\n * ```\n *\n * @example Function form\n * ```typescript\n * await this.saveMessages((current) => [\n * ...current,\n * { id: crypto.randomUUID(), role: \"user\", parts: [{ type: \"text\", text: \"Continue.\" }] }\n * ]);\n * ```\n *\n * @example External cancellation (helper-as-sub-agent)\n * ```typescript\n * // Inside a parent agent's tool execute — forward the AI SDK's\n * // abortSignal so a parent stop / tab close cancels the helper.\n * await helper.saveMessages([userMsg], { signal: abortSignal });\n * ```\n */\n async saveMessages(\n messages:\n | UIMessage[]\n | ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>),\n options?: SaveMessagesOptions\n ): Promise<SaveMessagesResult> {\n const requestId = crypto.randomUUID();\n return this._runProgrammaticMessagesTurn(requestId, messages, options);\n }\n\n private async _runProgrammaticMessagesTurn(\n requestId: string,\n messages:\n | UIMessage[]\n | ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>),\n options?: SaveMessagesOptions & {\n onMessagesApplied?: () => void;\n captureProgrammaticStreamError?: boolean;\n captureOutput?: boolean;\n body?: Record<string, unknown>;\n workflowPrompt?: ThinkWorkflowPromptContext;\n }\n ): Promise<ProgrammaticMessagesResult> {\n const clientTools = this._lastClientTools;\n const body = options?.body ?? this._lastBody;\n const epoch = this._turnQueue.generation;\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n let error: string | undefined;\n let output: unknown;\n let wasAborted = false;\n\n await this.keepAliveWhile(async () => {\n await this._turnQueue.enqueue(requestId, async () => {\n const resolved =\n typeof messages === \"function\"\n ? await messages(this.messages)\n : messages;\n\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n for (const msg of resolved) {\n await this._appendMessageToHistory(msg);\n }\n options?.onMessagesApplied?.();\n this._broadcastMessages();\n\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n const abortSignal = this._aborts.getSignal(requestId);\n // Wire the optional external signal to the registry's controller\n // for this request. Detacher MUST run in `finally` to avoid\n // leaking listeners on a long-lived parent signal that drives\n // many helper turns.\n const detachExternal = this._aborts.linkExternal(\n requestId,\n options?.signal\n );\n try {\n const programmaticBody = async () => {\n const result = await agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n clientTools,\n body,\n workflowPrompt: options?.workflowPrompt,\n continuation: false\n })\n );\n\n if (result) {\n const streamResult = await this._streamResult(\n requestId,\n result,\n abortSignal,\n {\n captureProgrammaticStreamError:\n options?.captureProgrammaticStreamError,\n captureOutput: options?.captureOutput\n }\n );\n status = streamResult.status;\n error = streamResult.error;\n output = streamResult.output;\n }\n };\n\n if (this.chatRecovery) {\n await this._runChatRecoveryFiber(\n requestId,\n false,\n programmaticBody\n );\n } else {\n await programmaticBody();\n }\n } finally {\n if (abortSignal?.aborted) wasAborted = true;\n detachExternal();\n this._aborts.remove(requestId);\n }\n });\n });\n\n if (\n this._turnQueue.generation !== epoch &&\n shouldMarkSkippedAfterGenerationChange(status)\n ) {\n status = \"skipped\";\n } else if (wasAborted && status === \"completed\") {\n status = \"aborted\";\n }\n\n return {\n requestId,\n status,\n ...(error !== undefined && { error }),\n ...(output !== undefined && { output })\n };\n }\n\n /**\n * Run a new LLM call following the last assistant message.\n *\n * The model sees the full conversation (including the last assistant\n * response) and generates a new response. The new response is persisted\n * as a separate assistant message. Building block for chat recovery\n * (Phase 4), \"generate more\" buttons, and self-correction.\n *\n * Note: this creates a new message, not an append to the existing one.\n * True continuation-as-append (chunk rewriting) is planned for Phase 4.\n *\n * Returns early with `status: \"skipped\"` if there is no assistant message\n * to continue from.\n *\n * Pass `options.signal` to cancel the continuation from outside —\n * matches the {@link saveMessages} contract.\n */\n protected async continueLastTurn(\n body?: Record<string, unknown>,\n options?: SaveMessagesOptions\n ): Promise<SaveMessagesResult> {\n const lastLeaf = await this.session.getLatestLeaf();\n if (!lastLeaf || lastLeaf.role !== \"assistant\") {\n return { requestId: \"\", status: \"skipped\" };\n }\n\n const requestId = crypto.randomUUID();\n const clientTools = this._lastClientTools;\n const resolvedBody = body ?? this._lastBody;\n const epoch = this._turnQueue.generation;\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n let error: string | undefined;\n let wasAborted = false;\n\n await this.keepAliveWhile(async () => {\n await this._turnQueue.enqueue(requestId, async () => {\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n const abortSignal = this._aborts.getSignal(requestId);\n const detachExternal = this._aborts.linkExternal(\n requestId,\n options?.signal\n );\n try {\n const continueTurnBody = async () => {\n const result = await agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n clientTools,\n body: resolvedBody,\n continuation: true\n })\n );\n\n if (result) {\n const streamResult = await this._streamResult(\n requestId,\n result,\n abortSignal,\n {\n continuation: true\n }\n );\n status = streamResult.status;\n error = streamResult.error;\n }\n };\n\n if (this.chatRecovery) {\n await this._runChatRecoveryFiber(requestId, true, continueTurnBody);\n } else {\n await continueTurnBody();\n }\n } finally {\n if (abortSignal?.aborted) wasAborted = true;\n detachExternal();\n this._aborts.remove(requestId);\n }\n });\n });\n\n if (\n this._turnQueue.generation !== epoch &&\n shouldMarkSkippedAfterGenerationChange(status)\n ) {\n status = \"skipped\";\n } else if (wasAborted && status === \"completed\") {\n status = \"aborted\";\n }\n\n return { requestId, status, ...(error !== undefined && { error }) };\n }\n\n private async _retryLastUserTurn(\n clientTools?: ClientToolSchema[],\n body?: Record<string, unknown>,\n options?: SaveMessagesOptions\n ): Promise<SaveMessagesResult> {\n const lastLeaf = await this.session.getLatestLeaf();\n if (!lastLeaf || lastLeaf.role !== \"user\") {\n return { requestId: \"\", status: \"skipped\" };\n }\n\n const requestId = crypto.randomUUID();\n const epoch = this._turnQueue.generation;\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n let error: string | undefined;\n let wasAborted = false;\n\n await this.keepAliveWhile(async () => {\n await this._turnQueue.enqueue(requestId, async () => {\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n const abortSignal = this._aborts.getSignal(requestId);\n const detachExternal = this._aborts.linkExternal(\n requestId,\n options?.signal\n );\n try {\n const retryTurnBody = async () => {\n const result = await agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n clientTools,\n body,\n continuation: false\n })\n );\n\n if (result) {\n const streamResult = await this._streamResult(\n requestId,\n result,\n abortSignal\n );\n status = streamResult.status;\n error = streamResult.error;\n }\n };\n\n if (this.chatRecovery) {\n await this._runChatRecoveryFiber(requestId, false, retryTurnBody);\n } else {\n await retryTurnBody();\n }\n } finally {\n if (abortSignal?.aborted) wasAborted = true;\n detachExternal();\n this._aborts.remove(requestId);\n }\n });\n });\n\n if (\n this._turnQueue.generation !== epoch &&\n shouldMarkSkippedAfterGenerationChange(status)\n ) {\n status = \"skipped\";\n } else if (wasAborted && status === \"completed\") {\n status = \"aborted\";\n }\n\n return { requestId, status, ...(error !== undefined && { error }) };\n }\n\n // ── WebSocket protocol ──────────────────────────────────────────\n\n private _setupProtocolHandlers() {\n const _onConnect = this.onConnect.bind(this);\n this.onConnect = async (\n connection: Connection,\n ctx: { request: Request }\n ) => {\n const requestTargetsSubAgent = this._cf_requestTargetsSubAgent(\n ctx.request\n );\n if (requestTargetsSubAgent) {\n return _onConnect(connection, ctx);\n }\n\n if (this._resumableStream.hasActiveStream()) {\n // A stream is still in flight. The resume flow is the\n // authoritative source of state: `_notifyStreamResuming` tells\n // the client to send `STREAM_RESUME_ACK`, after which the\n // server replays buffered chunks and delivers a final\n // `MSG_CHAT_MESSAGES` broadcast once the turn completes.\n //\n // Sending `MSG_CHAT_MESSAGES` here would clobber the in-progress\n // assistant the client rebuilds from the replayed chunks,\n // because `this.messages` at this point still only contains\n // the user message — the assistant message is not persisted\n // until the stream finishes.\n this._notifyStreamResuming(connection);\n } else {\n for (const message of await this._buildIdleConnectMessages()) {\n connection.send(JSON.stringify(message));\n }\n }\n return _onConnect(connection, ctx);\n };\n\n const _onClose = this.onClose.bind(this);\n this.onClose = async (\n connection: Connection,\n code: number,\n reason: string,\n wasClean: boolean\n ) => {\n this._pendingResumeConnections.delete(connection.id);\n this._continuation.releaseConnection(connection.id);\n return _onClose(connection, code, reason, wasClean);\n };\n\n const _onMessage = this.onMessage.bind(this);\n this.onMessage = async (connection: Connection, message: WSMessage) => {\n const connectionTargetsSubAgent =\n this._cf_connectionTargetsSubAgent(connection);\n if (connectionTargetsSubAgent) {\n return _onMessage(connection, message);\n }\n\n if (typeof message === \"string\") {\n const event = parseProtocolMessage(message);\n if (event) {\n await this._handleProtocolEvent(connection, event);\n return;\n }\n }\n return _onMessage(connection, message);\n };\n\n const _onRequest = this.onRequest.bind(this);\n this.onRequest = async (request: Request) => {\n const url = new URL(request.url);\n if (\n url.pathname === \"/get-messages\" ||\n url.pathname.endsWith(\"/get-messages\")\n ) {\n return Response.json(this.messages);\n }\n const messengerResponse =\n await this._messengerRuntime?.handleRequest(request);\n if (messengerResponse) {\n return messengerResponse;\n }\n return _onRequest(request);\n };\n }\n\n private async _handleProtocolEvent(\n connection: Connection,\n event: NonNullable<ReturnType<typeof parseProtocolMessage>>\n ): Promise<void> {\n switch (event.type) {\n case \"stream-resume-request\":\n this._handleStreamResumeRequest(connection);\n break;\n\n case \"stream-resume-ack\":\n await this._handleStreamResumeAck(connection, event.id);\n break;\n\n case \"chat-request\":\n if (event.init?.method === \"POST\") {\n await this._handleChatRequest(connection, event);\n }\n break;\n\n case \"tool-result\": {\n if (\n event.clientTools &&\n Array.isArray(event.clientTools) &&\n event.clientTools.length > 0\n ) {\n this._lastClientTools = event.clientTools as ClientToolSchema[];\n this._persistClientTools();\n }\n const resultPromise = Promise.resolve().then(async () => {\n await this._applyToolResult(\n event.toolCallId,\n event.output,\n event.state as \"output-error\" | undefined,\n event.errorText\n );\n return true;\n });\n this._pendingInteractionPromise = resultPromise;\n resultPromise\n .finally(() => {\n if (this._pendingInteractionPromise === resultPromise) {\n this._pendingInteractionPromise = null;\n }\n })\n .catch(() => {});\n if (event.autoContinue) {\n this._scheduleAutoContinuation(connection);\n }\n break;\n }\n\n case \"tool-approval\": {\n const approvalPromise = Promise.resolve().then(async () => {\n await this._applyToolApproval(event.toolCallId, event.approved);\n return true;\n });\n this._pendingInteractionPromise = approvalPromise;\n approvalPromise\n .finally(() => {\n if (this._pendingInteractionPromise === approvalPromise) {\n this._pendingInteractionPromise = null;\n }\n })\n .catch(() => {});\n if (event.autoContinue) {\n this._scheduleAutoContinuation(connection);\n }\n break;\n }\n\n case \"clear\":\n await this._handleClear(connection);\n break;\n\n case \"cancel\":\n this._aborts.cancel(event.id);\n break;\n\n case \"messages\":\n break;\n }\n }\n\n private _handleStreamResumeRequest(connection: Connection): void {\n if (this._resumableStream.hasActiveStream()) {\n if (\n this._continuation.activeRequestId ===\n this._resumableStream.activeRequestId &&\n this._continuation.activeConnectionId !== null &&\n this._continuation.activeConnectionId !== connection.id\n ) {\n sendIfOpen(\n connection,\n JSON.stringify({ type: MSG_STREAM_RESUME_NONE })\n );\n } else {\n this._notifyStreamResuming(connection);\n }\n } else if (\n this._continuation.pending !== null &&\n (this._continuation.pending.connectionId === null ||\n this._continuation.pending.connectionId === connection.id)\n ) {\n this._continuation.awaitingConnections.set(connection.id, connection);\n } else {\n sendIfOpen(connection, JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));\n }\n }\n\n private async _handleStreamResumeAck(\n connection: Connection,\n requestId: string\n ): Promise<void> {\n this._pendingResumeConnections.delete(connection.id);\n if (\n this._resumableStream.hasActiveStream() &&\n this._resumableStream.activeRequestId === requestId\n ) {\n const orphanedStreamId = this._resumableStream.replayChunks(\n connection,\n this._resumableStream.activeRequestId\n );\n if (orphanedStreamId) {\n await this._persistOrphanedStream(orphanedStreamId);\n }\n } else if (this._resumableStream.hasActiveStream()) {\n // Ignore ACKs for a different active stream request id.\n } else if (\n !this._resumableStream.replayCompletedChunksByRequestId(\n connection,\n requestId\n )\n ) {\n sendIfOpen(\n connection,\n JSON.stringify({\n body: \"\",\n done: true,\n id: requestId,\n type: MSG_CHAT_RESPONSE,\n replay: true\n })\n );\n }\n }\n\n private async _handleChatRequest(\n connection: Connection,\n event: Extract<\n NonNullable<ReturnType<typeof parseProtocolMessage>>,\n { type: \"chat-request\" }\n >\n ) {\n if (!event.init?.body) return;\n\n let rawParsed: Record<string, unknown>;\n try {\n rawParsed = JSON.parse(event.init.body) as Record<string, unknown>;\n } catch (error) {\n const wrapped = this.onChatError(error, {\n requestId: event.id,\n stage: \"parse\",\n messagesPersisted: false\n });\n this._emit(\"chat:request:failed\", {\n requestId: event.id,\n stage: \"parse\",\n messagesPersisted: false,\n error: wrapped instanceof Error ? wrapped.message : String(wrapped)\n });\n return;\n }\n\n const {\n messages: incomingMessages,\n clientTools: rawClientTools,\n trigger: rawTrigger,\n ...customBody\n } = rawParsed as {\n messages?: UIMessage[];\n clientTools?: ClientToolSchema[];\n trigger?: string;\n [key: string]: unknown;\n };\n if (!Array.isArray(incomingMessages)) return;\n\n const isRegeneration = rawTrigger === \"regenerate-message\";\n const isSubmitMessage = !isRegeneration;\n const requestId = event.id;\n let messagesPersisted = false;\n let failureStage: ChatErrorContext[\"stage\"] = \"persist\";\n\n // ── Concurrency decision (before persisting anything) ────────\n const concurrencyDecision =\n this._getSubmitConcurrencyDecision(isSubmitMessage);\n\n if (concurrencyDecision.action === \"drop\") {\n this._rollbackDroppedSubmit(connection);\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n\n const releasePendingEnqueue = this._submitConcurrency.beginEnqueue();\n let pendingEnqueue = true;\n const epoch = this._turnQueue.generation;\n const releaseIfPending = () => {\n if (!pendingEnqueue) return;\n pendingEnqueue = false;\n releasePendingEnqueue();\n };\n\n try {\n // ── Persist client tools and body (only for accepted requests) ──\n const requestClientTools =\n rawClientTools && rawClientTools.length > 0\n ? rawClientTools\n : undefined;\n if (requestClientTools) {\n this._lastClientTools = requestClientTools;\n this._persistClientTools();\n } else if (rawClientTools !== undefined) {\n this._lastClientTools = undefined;\n this._persistClientTools();\n }\n\n const requestBody =\n Object.keys(customBody).length > 0 ? customBody : undefined;\n this._lastBody = requestBody;\n this._persistBody();\n\n // ── Reconcile, persist, and broadcast user messages ──────────\n //\n // The client may post an in-flight assistant snapshot it minted\n // optimistically (e.g. while a previous tool call is still\n // streaming). Reconcile against the server's current active path\n // so client IDs map onto server IDs and stale client states pick\n // up the server's tool outputs. Without this, Session's\n // INSERT-OR-IGNORE-by-ID would persist a duplicate orphan\n // assistant row alongside the real server-generated one.\n const clientToolsForTurn = this._lastClientTools;\n const bodyForTurn = this._lastBody;\n\n const serverMessages = await this._readMessagesFromStorage();\n const reconciled = reconcileMessages(\n incomingMessages,\n serverMessages,\n sanitizeMessage\n );\n\n let branchParentId: string | undefined;\n if (isRegeneration && reconciled.length > 0) {\n branchParentId = reconciled[reconciled.length - 1].id;\n }\n\n if (this._turnQueue.generation !== epoch) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n\n for (const msg of reconciled) {\n if (this._turnQueue.generation !== epoch) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n\n await this._persistIncomingMessage(msg, serverMessages);\n }\n\n if (this._turnQueue.generation !== epoch) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n\n await this._syncMessages();\n this._broadcastMessages([connection.id]);\n messagesPersisted = true;\n\n // ── Enter turn queue ────────────────────────────────────────\n failureStage = \"turn\";\n const abortSignal = this._aborts.getSignal(requestId);\n\n await this.keepAliveWhile(async () => {\n const turnPromise = this._turnQueue.enqueue(\n requestId,\n async () => {\n // Superseded by a later overlapping submit (latest/merge/debounce)\n if (\n this._submitConcurrency.isSuperseded(\n concurrencyDecision.submitSequence\n )\n ) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n\n // Debounce: wait for quiet period\n if (concurrencyDecision.debounceUntilMs !== null) {\n await this._submitConcurrency.waitForTimestamp(\n concurrencyDecision.debounceUntilMs\n );\n\n if (this._turnQueue.generation !== epoch) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n if (\n this._submitConcurrency.isSuperseded(\n concurrencyDecision.submitSequence\n )\n ) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n }\n\n const chatTurnBody = async () => {\n const result = await agentContext.run(\n {\n agent: this,\n connection,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n clientTools: clientToolsForTurn,\n body: bodyForTurn,\n continuation: false\n })\n );\n\n if (result) {\n await this._streamResult(requestId, result, abortSignal, {\n parentId: branchParentId\n });\n } else {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"No response was generated.\",\n done: true\n });\n }\n };\n\n if (this.chatRecovery) {\n await this._runChatRecoveryFiber(requestId, false, chatTurnBody);\n } else {\n await chatTurnBody();\n }\n },\n {\n generation: epoch\n }\n );\n releaseIfPending();\n\n const turnResult = await turnPromise;\n\n if (turnResult.status === \"stale\") {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n });\n }\n });\n } catch (error) {\n const wrapped = this.onChatError(error, {\n requestId,\n stage: failureStage,\n messagesPersisted\n });\n const errorMessage =\n wrapped instanceof Error ? wrapped.message : String(wrapped);\n this._emit(\"chat:request:failed\", {\n requestId,\n stage: failureStage,\n messagesPersisted,\n error: errorMessage\n });\n // Persist the terminal error before broadcasting it: the broadcast is\n // transient, so a client disconnected at this moment (a pre-stream\n // failure like message reconciliation) would otherwise never learn the\n // turn failed and stay frozen on reconnect (see `_buildIdleConnectMessages`).\n await this._recordTerminalChatStatus(\"error\", requestId, errorMessage);\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: errorMessage,\n done: true,\n error: true\n });\n } finally {\n releaseIfPending();\n this._aborts.remove(requestId);\n }\n }\n\n /**\n * Abort the active turn, invalidate queued turns, and reset\n * concurrency/continuation state. Call this when intercepting\n * clear events or implementing custom reset logic.\n *\n * Does NOT clear messages, streams, or persisted state —\n * only turn execution state.\n */\n protected resetTurnState(): void {\n this._turnQueue.reset();\n this._aborts.destroyAll();\n for (const controller of this._submissionAbortControllers.values()) {\n controller.abort(new Error(\"Turn state reset\"));\n }\n this._submissionAbortControllers.clear();\n const skippedSubmissions = this._markPendingSubmissionsSkipped();\n void this.keepAliveWhile(() =>\n this._emitSkippedSubmissions(skippedSubmissions)\n ).catch((error) => {\n console.error(\"[Think] Failed to skip pending submissions\", error);\n });\n if (this._continuationTimer) {\n clearTimeout(this._continuationTimer);\n this._continuationTimer = null;\n }\n this._submitConcurrency.reset();\n this._pendingInteractionPromise = null;\n this._continuationBarrierActive = false;\n this._continuation.sendResumeNone();\n this._continuation.clearAll();\n }\n\n /**\n * Abort a single in-flight chat turn by request id.\n *\n * Equivalent to the cancel path that fires when a client sends a\n * `chat-request-cancel` WebSocket message — the inference loop's\n * signal aborts, partial chunks already streamed are still\n * persisted, and the turn's `ChatResponseResult` reports\n * `status: \"aborted\"`.\n *\n * No-op if no controller exists for `requestId` (the turn already\n * completed, was never started, or used a different id).\n *\n * `chat()` callers can read the request id from\n * {@link StreamCallback.onStart} and later pass it here from another\n * RPC call.\n *\n * Prefer {@link SaveMessagesOptions.signal} when driving a turn\n * programmatically — it threads the abort intent in from the start\n * without requiring the caller to know the id.\n */\n cancelChat(requestId: string, reason?: string): void {\n this._aborts.cancel(requestId, reason);\n }\n\n /** Abort every in-flight chat turn on this agent. */\n cancelAllChats(): void {\n this._aborts.destroyAll();\n }\n\n protected abortRequest(requestId: string, reason?: unknown): void {\n this._aborts.cancel(requestId, reason);\n }\n\n /**\n * Abort every in-flight chat turn on this agent.\n *\n * Aborts all controllers in the registry and clears it. Used by\n * subclasses that drive single-purpose turns (e.g. a sub-agent\n * helper that runs one turn at a time over RPC) and want a coarse\n * \"cancel whatever is running\" handle without tracking request ids.\n *\n * Does NOT reset queued turns, continuation timers, or submit\n * concurrency state — use {@link resetTurnState} for the full\n * teardown that runs on `chat-clear`.\n */\n protected abortAllRequests(): void {\n this._aborts.destroyAll();\n }\n\n private async _handleClear(connection?: Connection) {\n this.resetTurnState();\n\n this._resumableStream.clearAll();\n this._pendingResumeConnections.clear();\n this._lastClientTools = undefined;\n this._persistClientTools();\n this._lastBody = undefined;\n this._persistBody();\n await this._clearHistory();\n this._broadcast(\n { type: MSG_CHAT_CLEAR },\n connection ? [connection.id] : undefined\n );\n }\n\n private async _streamResultToRpcCallback(\n requestId: string,\n result: StreamableResult,\n callback: StreamCallback,\n abortSignal?: AbortSignal\n ): Promise<void> {\n const streamId = this._resumableStream.start(requestId);\n const accumulator = new StreamAccumulator({\n messageId: crypto.randomUUID()\n });\n\n let streamFinalized = false;\n let assistantMsg: UIMessage | null = null;\n let aborted = false;\n let doneSent = false;\n let streamError: string | undefined;\n let pendingRpcError: string | undefined;\n\n const stallTimeoutMs =\n this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;\n try {\n this._insideInferenceLoop = true;\n const flushState = { chunksSinceFlush: 0, hasFlushedContent: false };\n try {\n const guardedStream = this._iterateWithStallWatchdog(\n result.toUIMessageStream(),\n stallTimeoutMs,\n () => {\n this._emit(\"chat:stream:stalled\", {\n requestId,\n timeoutMs: stallTimeoutMs\n });\n this.abortRequest(\n requestId,\n new Error(\"chat stream stalled: inactivity watchdog fired\")\n );\n }\n );\n for await (const chunk of guardedStream) {\n if (abortSignal?.aborted) {\n aborted = true;\n break;\n }\n\n // RPC callbacks receive serialized UIMessage chunks directly; unlike\n // the WebSocket protocol, there is no wrapper frame to rewrite for\n // accumulator actions such as `error`.\n const streamChunk = chunk as unknown as StreamChunkData;\n const { action } = accumulator.applyChunk(streamChunk);\n\n if (action?.type === \"error\") {\n streamError = action.error;\n this._emit(\"message:error\", { error: streamError });\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: action.error,\n done: false,\n error: true\n });\n break;\n }\n\n const chunkBody = JSON.stringify(chunk);\n await this._storeChunkDurably(\n streamId,\n streamChunk,\n chunkBody,\n flushState\n );\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: chunkBody,\n done: false\n });\n await callback.onEvent(chunkBody);\n }\n } finally {\n this._insideInferenceLoop = false;\n }\n\n if (streamError) {\n this._resumableStream.markError(streamId);\n } else {\n this._resumableStream.complete(streamId);\n }\n streamFinalized = true;\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n });\n doneSent = true;\n\n assistantMsg = accumulator.toMessage();\n if (accumulator.parts.length > 0) {\n await this._persistAssistantMessage(assistantMsg);\n this._broadcastMessages();\n }\n\n if (streamError) {\n await this._fireResponseHook({\n message: assistantMsg,\n requestId,\n continuation: false,\n status: \"error\",\n error: streamError\n });\n pendingRpcError = streamError;\n } else if (!aborted) {\n await callback.onDone();\n await this._fireResponseHook({\n message: assistantMsg,\n requestId,\n continuation: false,\n status: \"completed\"\n });\n } else {\n await this._fireResponseHook({\n message: assistantMsg,\n requestId,\n continuation: false,\n status: \"aborted\"\n });\n }\n } catch (error) {\n // #1626: a stream-stall watchdog abort is a recoverable interruption, not\n // a terminal error. Persist the settled partial (re-anchor), route into\n // bounded recovery, and suppress the terminal error when a continuation is\n // scheduled; fall through to terminal only once the budget is exhausted.\n if (error instanceof ChatStreamStalledError) {\n if (!assistantMsg && accumulator.parts.length > 0) {\n assistantMsg = accumulator.toMessage();\n await this._persistAssistantMessage(assistantMsg);\n this._broadcastMessages();\n }\n const outcome = await this._routeStallToBoundedRecovery({\n requestId,\n streamId,\n partialParts: (assistantMsg ?? accumulator.toMessage()).parts,\n targetAssistantId: assistantMsg?.id\n });\n if (outcome === \"scheduled\") {\n if (!streamFinalized) {\n this._resumableStream.complete(streamId);\n streamFinalized = true;\n }\n if (!doneSent) {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n });\n doneSent = true;\n }\n // The scheduled continuation (a later isolate invocation, without this\n // callback) owns the real terminal outcome. Signal the interruption so\n // the caller doesn't read this clean resolve as success and finalize a\n // truncated partial (#1644); NOT onDone/onError — see `onInterrupted`.\n await callback.onInterrupted?.();\n return;\n }\n if (outcome === \"exhausted\") {\n // `_routeStallToBoundedRecovery` already delivered the terminal UX\n // (configured `terminalMessage` + done/error frame + `onExhausted` +\n // submission interrupted), identical to deploy-recovery exhaustion.\n // Finalize the stream and return WITHOUT the generic terminal path,\n // which would otherwise re-broadcast the raw stall error.\n if (!streamFinalized) {\n this._resumableStream.markError(streamId);\n streamFinalized = true;\n }\n doneSent = true;\n // Exhaustion is terminal for the turn, but it was delivered out-of-band\n // by `_exhaustChatRecovery` (banner/`onExhausted`), NOT through this\n // callback's `onError`. Signal the interruption so a `chat()` consumer\n // doesn't mis-read the clean resolve as a successful completion (#1644).\n await callback.onInterrupted?.();\n return;\n }\n // outcome === \"disabled\" (chat recovery off): fall through to the\n // generic terminal path below (unchanged watchdog behavior).\n }\n if (!streamFinalized) {\n this._resumableStream.markError(streamId);\n streamFinalized = true;\n }\n if (!doneSent) {\n const streamError =\n error instanceof Error ? error.message : \"Stream error\";\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: streamError,\n done: true,\n error: true\n });\n doneSent = true;\n }\n\n if (!assistantMsg && accumulator.parts.length > 0) {\n assistantMsg = accumulator.toMessage();\n await this._persistAssistantMessage(assistantMsg);\n this._broadcastMessages();\n }\n\n const wrapped = this.onChatError(error, {\n requestId,\n stage: \"stream\",\n messagesPersisted: true\n });\n const errorMessage =\n wrapped instanceof Error ? wrapped.message : String(wrapped);\n this._emit(\"chat:request:failed\", {\n requestId,\n stage: \"stream\",\n messagesPersisted: true,\n error: errorMessage\n });\n\n if (assistantMsg) {\n await this._fireResponseHook({\n message: assistantMsg,\n requestId,\n continuation: false,\n status: \"error\",\n error: errorMessage\n });\n }\n\n await callback.onError(errorMessage);\n }\n\n if (pendingRpcError) {\n await callback.onError(pendingRpcError);\n }\n }\n\n /**\n * Whether storing this chunk should immediately flush the resumable-stream\n * buffer to SQLite.\n *\n * A settled tool result (`tool-output-available` / `tool-output-error` /\n * `tool-output-denied`) captures a completed, often non-idempotent side\n * effect — or, for a denial, a user decision — so it is flushed\n * **immediately**. An isolate eviction (deploy) before the next batch flush\n * would otherwise lose it, and recovery would re-anchor without it and re-run\n * the already-completed tool call (or drop the denial). Frequent recoverable\n * content (text / reasoning / tool-input streaming) is throttled to avoid\n * write amplification.\n */\n private _shouldFlushRecoverableChunk(\n chunk: StreamChunkData,\n chunksSinceFlush: number,\n hasFlushedContent: boolean\n ): boolean {\n if (\n chunk.type === \"tool-output-available\" ||\n chunk.type === \"tool-output-error\" ||\n chunk.type === \"tool-output-denied\"\n ) {\n return true;\n }\n const isThrottledRecoverable =\n chunk.type === \"text-delta\" ||\n chunk.type === \"reasoning-delta\" ||\n chunk.type === \"tool-input-available\";\n return (\n isThrottledRecoverable && (!hasFlushedContent || chunksSinceFlush >= 10)\n );\n }\n\n /**\n * Store a stream chunk, flushing settled tool results durably and promptly.\n * Shared by the WebSocket and sub-agent RPC streaming paths so both get\n * tool-call-level recovery durability (recovery loses at most the in-flight\n * step, never an already-completed tool call).\n */\n private async _storeChunkDurably(\n streamId: string,\n chunk: StreamChunkData,\n chunkBody: string,\n state: { chunksSinceFlush: number; hasFlushedContent: boolean }\n ): Promise<void> {\n this._resumableStream.storeChunk(streamId, chunkBody);\n state.chunksSinceFlush++;\n if (\n this._shouldFlushRecoverableChunk(\n chunk,\n state.chunksSinceFlush,\n state.hasFlushedContent\n )\n ) {\n this._resumableStream.flushBuffer();\n state.chunksSinceFlush = 0;\n state.hasFlushedContent = true;\n // Forward progress: new durable content was just flushed. Advance the\n // monotonic, compaction-immune progress counter HERE (production time)\n // rather than in `_persistOrphanedStream` — so it bumps only on genuinely\n // new content and is immune to client reconnects / recovery re-persists\n // (which don't flow through this path). This is what the recovery\n // no-progress window keys off (#1637), and stays compaction-proof (#1628).\n await this._bumpChatRecoveryProgress();\n }\n }\n\n /**\n * Wrap a UI-message stream with an inactivity watchdog. If no chunk arrives\n * within `timeoutMs`, `onStall` runs (aborting the upstream model stream) and\n * the iterator throws, so the consumer loop exits with a terminal error\n * instead of parking forever on a hung provider/transport. `timeoutMs <= 0`\n * passes the source through untouched.\n */\n private async *_iterateWithStallWatchdog<T>(\n source: AsyncIterable<T>,\n timeoutMs: number,\n onStall: () => void\n ): AsyncGenerator<T> {\n if (!(timeoutMs > 0)) {\n yield* source;\n return;\n }\n const iterator = source[Symbol.asyncIterator]();\n // Tracks whether the watchdog itself aborted the upstream. In that case we\n // must NOT also `iterator.return()` it: cancelling the readable after the\n // abort makes the AI SDK pipeline write to an already-cancelled readable\n // (\"readable side is no longer readable\"). Letting the abort error the\n // stream is the clean path.\n let selfAborted = false;\n try {\n while (true) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n let stalled = false;\n const stall = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n stalled = true;\n reject(\n new ChatStreamStalledError(\n `Chat stream stalled: no activity for ${timeoutMs}ms; the turn was aborted by the stall watchdog.`\n )\n );\n }, timeoutMs);\n });\n const nextPromise = iterator.next();\n // If the watchdog wins the race we abandon this read; aborting the\n // upstream stream makes it reject later, so pre-attach a no-op catch to\n // keep that abandoned rejection from surfacing as an unhandled rejection.\n nextPromise.catch(() => {});\n let next: IteratorResult<T>;\n try {\n next = await Promise.race([nextPromise, stall]);\n } catch (err) {\n if (stalled) {\n selfAborted = true;\n onStall();\n }\n throw err;\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n if (next.done) return;\n yield next.value;\n }\n } finally {\n // Forward early termination (consumer `break`/`throw`, e.g. an in-band\n // stream error where the abort signal is NOT set) to the source so its\n // reader is cancelled — otherwise the wrapped source would leak when the\n // consumer stops reading mid-stream. Skipped after a watchdog stall, which\n // already aborted the upstream (see `selfAborted` above).\n if (!selfAborted) {\n await iterator.return?.(undefined as never).catch(() => {});\n }\n }\n }\n\n private async _streamResult(\n requestId: string,\n result: StreamableResult,\n abortSignal?: AbortSignal,\n options?: {\n continuation?: boolean;\n parentId?: string;\n captureProgrammaticStreamError?: boolean;\n captureOutput?: boolean;\n }\n ): Promise<StreamResultStatus> {\n const clearGen = this._turnQueue.generation;\n const streamId = this._resumableStream.start(requestId);\n const continuation = options?.continuation ?? false;\n const parentId = options?.parentId;\n\n if (this._continuation.pending?.requestId === requestId) {\n this._continuation.activatePending();\n this._continuation.flushAwaitingConnections((c) =>\n this._notifyStreamResuming(c)\n );\n }\n\n const accumulator = new StreamAccumulator({\n messageId: crypto.randomUUID()\n });\n\n let doneSent = false;\n let streamAborted = false;\n let streamError: string | undefined;\n let output: unknown;\n const flushState = { chunksSinceFlush: 0, hasFlushedContent: false };\n\n const stallTimeoutMs =\n this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;\n try {\n this._insideInferenceLoop = true;\n try {\n const guardedStream = this._iterateWithStallWatchdog(\n result.toUIMessageStream(),\n stallTimeoutMs,\n () => {\n this._emit(\"chat:stream:stalled\", {\n requestId,\n timeoutMs: stallTimeoutMs\n });\n // Tear down the upstream model stream so a hung provider/transport\n // is released; the watchdog's throw drives the terminal error below.\n this.abortRequest(\n requestId,\n new Error(\"chat stream stalled: inactivity watchdog fired\")\n );\n }\n );\n for await (const chunk of guardedStream) {\n if (abortSignal?.aborted) {\n streamAborted = true;\n break;\n }\n\n const streamChunk = chunk as unknown as StreamChunkData;\n const { action } = accumulator.applyChunk(streamChunk);\n\n // Approved server tools execute during a continuation stream, but\n // their original tool part lives in an earlier assistant message.\n // The accumulator can only own this turn's new content, so it\n // surfaces a terminal result for a prior message as a\n // `cross-message-tool-update`. Persist + broadcast it directly so\n // the approved result reaches clients and durable storage. The\n // update builder is first-write-wins (replay-safe) and preserves a\n // streamed `preliminary` flag; `_applyToolUpdateToMessages` skips\n // the write/broadcast when the matched part is already settled.\n if (action?.type === \"cross-message-tool-update\") {\n await this._applyToolUpdateToMessages(\n crossMessageToolResultUpdate(\n action.toolCallId,\n action.updateType,\n action.output,\n action.errorText,\n action.preliminary\n )\n );\n }\n\n if (action?.type === \"error\") {\n streamError = action.error;\n if (options?.captureProgrammaticStreamError) {\n this._programmaticStreamErrors.set(requestId, streamError);\n }\n this._emit(\"message:error\", { error: streamError });\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: action.error,\n done: false,\n error: true,\n ...(continuation && { continuation: true })\n });\n break;\n }\n\n const chunkBody = JSON.stringify(chunk);\n await this._storeChunkDurably(\n streamId,\n streamChunk,\n chunkBody,\n flushState\n );\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: chunkBody,\n done: false,\n ...(continuation && { continuation: true })\n });\n }\n } finally {\n this._insideInferenceLoop = false;\n }\n\n if (streamError) {\n this._resumableStream.markError(streamId);\n } else {\n this._resumableStream.complete(streamId);\n }\n this._pendingResumeConnections.clear();\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true,\n ...(continuation && { continuation: true })\n });\n doneSent = true;\n } catch (error) {\n // #1626: a stream-stall watchdog abort is a recoverable interruption, not\n // a terminal error. Persist the settled partial (so the continuation\n // re-anchors without re-running completed tool calls), then route into\n // bounded recovery; only fall through to the terminal path below once the\n // budget is exhausted.\n if (error instanceof ChatStreamStalledError) {\n let targetAssistantId: string | undefined;\n const partialMsg = accumulator.toMessage();\n if (\n this._turnQueue.generation === clearGen &&\n accumulator.parts.length > 0\n ) {\n await this._persistAssistantMessage(partialMsg, parentId);\n this._broadcastMessages();\n targetAssistantId = partialMsg.id;\n }\n const outcome = await this._routeStallToBoundedRecovery({\n requestId,\n streamId,\n partialParts: partialMsg.parts,\n targetAssistantId\n });\n if (outcome === \"scheduled\") {\n // Recovering: close the stream cleanly (no terminal error frame); the\n // scheduled continuation drives the turn to completion. Report\n // `aborted` so the caller does not terminalize the turn.\n this._resumableStream.complete(streamId);\n this._pendingResumeConnections.clear();\n if (!doneSent) {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true,\n ...(continuation && { continuation: true })\n });\n doneSent = true;\n }\n // `aborted` (not `error`): this attempt was aborted by the watchdog;\n // the scheduled continuation owns the real terminal outcome. No\n // response hook fires here (the continuation fires it), mirroring how\n // a deploy-interrupted attempt is superseded by its continuation.\n return { status: \"aborted\" };\n }\n if (outcome === \"exhausted\") {\n // `_routeStallToBoundedRecovery` already delivered the terminal UX\n // (configured `terminalMessage` + done/error frame + `onExhausted` +\n // submission interrupted), identical to deploy-recovery exhaustion.\n // Finalize the stream and report `aborted` (not `error`) so the caller\n // does not re-run the generic terminal path on top of it.\n this._resumableStream.markError(streamId);\n this._pendingResumeConnections.clear();\n doneSent = true;\n return { status: \"aborted\" };\n }\n // outcome === \"disabled\" (chat recovery off): fall through to the\n // generic terminal path (the watchdog's original \"kill the spinner\"\n // guarantee, unchanged).\n }\n streamError = error instanceof Error ? error.message : \"Stream error\";\n if (options?.captureProgrammaticStreamError) {\n this._programmaticStreamErrors.set(requestId, streamError);\n }\n this._resumableStream.markError(streamId);\n this._pendingResumeConnections.clear();\n if (!doneSent) {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: streamError,\n done: true,\n error: true,\n ...(continuation && { continuation: true })\n });\n doneSent = true;\n }\n } finally {\n if (!doneSent) {\n this._resumableStream.markError(streamId);\n this._pendingResumeConnections.clear();\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true,\n ...(continuation && { continuation: true })\n });\n }\n }\n\n if (\n options?.captureOutput &&\n result.output &&\n !streamError &&\n !streamAborted\n ) {\n try {\n output = await result.output;\n } catch (error) {\n streamError =\n error instanceof Error ? error.message : \"Structured output error\";\n if (options.captureProgrammaticStreamError) {\n this._programmaticStreamErrors.set(requestId, streamError);\n }\n }\n }\n\n if (this._turnQueue.generation === clearGen) {\n try {\n const assistantMsg = accumulator.toMessage();\n\n if (accumulator.parts.length > 0) {\n await this._persistAssistantMessage(assistantMsg, parentId);\n this._broadcastMessages();\n }\n\n await this._fireResponseHook({\n message: assistantMsg,\n requestId,\n continuation,\n status: streamError\n ? \"error\"\n : streamAborted\n ? \"aborted\"\n : \"completed\",\n error: streamError\n });\n } catch (e) {\n console.error(\"Failed to persist assistant message:\", e);\n }\n }\n\n return streamError\n ? { status: \"error\", error: streamError }\n : {\n status: streamAborted ? \"aborted\" : \"completed\",\n ...(output !== undefined && { output })\n };\n }\n\n // ── Session-backed persistence ──────────────────────────────────\n\n private async _persistAssistantMessage(\n msg: UIMessage,\n parentId?: string\n ): Promise<void> {\n await this._upsertMessageInHistory(msg, parentId);\n }\n\n /**\n * Persist an incoming message after reconciliation. For assistant\n * messages, also resolve their ID against any server-side row that\n * already owns the same `toolCallId` so we update the existing row\n * instead of inserting an orphan duplicate.\n */\n private async _persistIncomingMessage(\n msg: UIMessage,\n serverMessages: readonly UIMessage[]\n ): Promise<void> {\n const resolved =\n msg.role === \"assistant\" ? resolveToolMergeId(msg, serverMessages) : msg;\n await this._upsertMessageInHistory(resolved);\n }\n\n private _persistClientTools(): void {\n if (this._lastClientTools) {\n this._configSet(\"lastClientTools\", JSON.stringify(this._lastClientTools));\n } else {\n this._configDelete(\"lastClientTools\");\n }\n }\n\n private _restoreClientTools(): void {\n const raw = this._configGet(\"lastClientTools\");\n if (raw) {\n try {\n this._lastClientTools = JSON.parse(raw);\n } catch {\n this._lastClientTools = undefined;\n }\n }\n }\n\n private _persistBody(): void {\n if (this._lastBody) {\n this._configSet(\"lastBody\", JSON.stringify(this._lastBody));\n } else {\n this._configDelete(\"lastBody\");\n }\n }\n\n private _restoreBody(): void {\n const raw = this._configGet(\"lastBody\");\n if (raw) {\n try {\n this._lastBody = JSON.parse(raw);\n } catch {\n this._lastBody = undefined;\n }\n }\n }\n\n // ── Tool state updates (shared primitives from agents/chat) ─────\n\n private async _applyToolResult(\n toolCallId: string,\n output: unknown,\n overrideState?: \"output-error\",\n errorText?: string\n ): Promise<void> {\n const update = toolResultUpdate(\n toolCallId,\n output,\n overrideState,\n errorText\n );\n await this._applyToolUpdateToMessages(update);\n }\n\n private async _applyToolApproval(\n toolCallId: string,\n approved: boolean\n ): Promise<void> {\n const update = toolApprovalUpdate(toolCallId, approved);\n await this._applyToolUpdateToMessages(update);\n }\n\n private async _applyToolUpdateToMessages(update: {\n toolCallId: string;\n matchStates: string[];\n apply: (part: Record<string, unknown>) => Record<string, unknown>;\n }): Promise<void> {\n const history = await this._readMessagesFromStorage();\n for (let i = 0; i < history.length; i++) {\n const msg = history[i];\n const msgParts = msg.parts as Array<Record<string, unknown>>;\n const result = applyToolUpdate(msgParts, update);\n if (result) {\n // First-write-wins / idempotent re-apply: when `apply` leaves the\n // matched part untouched (same reference) — e.g. a provider replay of\n // an already-settled cross-message tool result (#1404) — there is\n // nothing to persist. Skip the durable write and the redundant\n // `MESSAGE_UPDATED` broadcast so clients don't churn on a no-op.\n if (result.parts[result.index] === msgParts[result.index]) {\n return;\n }\n const updatedMsg = {\n ...msg,\n parts: result.parts as UIMessage[\"parts\"]\n };\n const safe = await this._updateMessageInHistory(updatedMsg);\n // Session change callbacks may run after an immediately scheduled\n // continuation begins. Keep its input cache coherent synchronously.\n this._patchCachedMessage(safe);\n // Patch the live cache in place instead of doing a full\n // `_syncMessages()` round-trip.\n // A full re-read during a streaming turn drops in-flight messages\n // whose parent chain hasn't been persisted yet (see commits\n // 3f615a24 \"revert _syncMessages in _applyToolUpdateToMessages\"\n // and 6e76bd49 \"update cached messages in-place\"). The cache is\n // the source of truth during a turn; we only reconcile it here to\n // reflect the tool update that was just written to storage.\n this._broadcast({ type: MSG_MESSAGE_UPDATED, message: safe });\n return;\n }\n }\n }\n\n // ── Stability + pending interactions ─────────────────────────────\n\n protected hasPendingInteraction(): boolean {\n return this.messages.some(\n (message) =>\n message.role === \"assistant\" &&\n this._messageHasPendingInteraction(message)\n );\n }\n\n protected async waitUntilStable(options?: {\n timeout?: number;\n }): Promise<boolean> {\n const deadline =\n options?.timeout != null ? Date.now() + options.timeout : null;\n\n while (true) {\n if (\n (await this._awaitWithDeadline(\n this._submitConcurrency.waitForIdle(() =>\n this._turnQueue.waitForIdle()\n ),\n deadline\n )) === TIMED_OUT\n ) {\n return false;\n }\n\n if (!this.hasPendingInteraction()) {\n return true;\n }\n\n const pending = this._pendingInteractionPromise;\n if (pending) {\n let result: boolean | typeof TIMED_OUT;\n try {\n result = await this._awaitWithDeadline(pending, deadline);\n } catch {\n continue;\n }\n if (result === TIMED_OUT) {\n return false;\n }\n } else {\n if (\n (await this._awaitWithDeadline(\n new Promise<void>((resolve) => setTimeout(resolve, 100)),\n deadline\n )) === TIMED_OUT\n ) {\n return false;\n }\n }\n }\n }\n\n private async _awaitWithDeadline<T>(\n promise: Promise<T>,\n deadline: number | null\n ): Promise<T | typeof TIMED_OUT> {\n if (deadline == null) {\n return promise;\n }\n const remainingMs = Math.max(0, deadline - Date.now());\n let timer: ReturnType<typeof setTimeout>;\n const result = await Promise.race([\n promise,\n new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(() => resolve(TIMED_OUT), remainingMs);\n })\n ]);\n clearTimeout(timer!);\n return result;\n }\n\n private _messageHasPendingInteraction(message: UIMessage): boolean {\n return message.parts.some(\n (part) =>\n \"state\" in part &&\n ((part as Record<string, unknown>).state === \"input-available\" ||\n (part as Record<string, unknown>).state === \"approval-requested\")\n );\n }\n\n // ── Chat recovery via fibers ───────────────────────────────────\n\n private _resolveChatRecoveryConfig(): ResolvedChatRecoveryConfig {\n const raw = this.chatRecovery;\n const custom = typeof raw === \"object\" ? raw : undefined;\n return {\n enabled: raw !== false,\n maxAttempts: Math.max(\n 1,\n Math.floor(custom?.maxAttempts ?? DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS)\n ),\n stableTimeoutMs: Math.max(\n 0,\n Math.floor(\n custom?.stableTimeoutMs ?? DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS\n )\n ),\n terminalMessage:\n custom?.terminalMessage ?? DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE,\n ...(custom?.onExhausted ? { onExhausted: custom.onExhausted } : {})\n };\n }\n\n private _chatRecoveryIncidentId(input: {\n requestId: string;\n recoveryRootRequestId?: string | null;\n latestUserMessageId?: string | null;\n targetAssistantId?: string | null;\n recoveryKind: ChatRecoveryKind;\n }): string {\n // `recoveryKind` is intentionally NOT part of the identity: a single\n // interrupted turn can flip between \"retry\" (no chunks persisted) and\n // \"continue\" (partial chunks exist) across restarts, and the attempt\n // budget must be shared so recovery stays bounded by `maxAttempts`.\n return [\n input.recoveryRootRequestId ?? input.requestId,\n input.latestUserMessageId ?? \"\"\n ].join(\":\");\n }\n\n private _chatRecoveryIncidentKey(incidentId: string): string {\n return `${CHAT_RECOVERY_INCIDENT_KEY_PREFIX}${encodeURIComponent(incidentId)}`;\n }\n\n /**\n * Monotonic forward-progress signal for recovery budget resets.\n *\n * This used to count assistant messages in `this.messages`, but that is\n * recomputed from the live, mutable transcript. Compaction collapses older\n * assistant messages into a summary, lowering the count — so a turn that had\n * genuinely advanced could read as \"no progress\" between attempts and exhaust\n * its budget prematurely (#1628). Instead we read a durably-persisted counter\n * that only ever increments — bumped at production time when new content is\n * durably flushed (see `_storeChunkDurably`), which is genuine forward\n * progress and is immune to client reconnects / recovery re-persists — so\n * compaction can never lower it and a reconnect can't fake it (#1637).\n */\n private async _chatRecoveryProgressMarker(): Promise<number> {\n return (\n (await this.ctx.storage.get<number>(CHAT_RECOVERY_PROGRESS_KEY)) ?? 0\n );\n }\n\n /** Advance the durable recovery-progress counter. Called from\n * `_storeChunkDurably` when new content is durably flushed (real, reconnect-\n * immune forward progress). */\n private async _bumpChatRecoveryProgress(): Promise<void> {\n const current =\n (await this.ctx.storage.get<number>(CHAT_RECOVERY_PROGRESS_KEY)) ?? 0;\n await this.ctx.storage.put(CHAT_RECOVERY_PROGRESS_KEY, current + 1);\n }\n\n /** In-memory wall-clock of the last N9 child-stream progress bump (reset per\n * isolate so the first forwarded chunk after a restart always credits). */\n private _lastAgentToolStreamProgressAt = 0;\n\n /**\n * N9: forwarding a sub-agent's chunks IS forward progress for this parent\n * turn, so credit the parent's recovery progress marker — otherwise a parent\n * whose turn merely `await`s a child banks no progress of its own and its\n * no-progress window exhausts while the child is healthily streaming. Only\n * invoked after a child actually produced output (see\n * `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.\n * Throttled (and reset per isolate) so we never write storage per token.\n */\n protected override async _onAgentToolStreamProgress(): Promise<void> {\n const now = Date.now();\n if (\n now - this._lastAgentToolStreamProgressAt <\n AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS\n ) {\n return;\n }\n this._lastAgentToolStreamProgressAt = now;\n await this._bumpChatRecoveryProgress();\n }\n\n /** Sweep recovery incidents that have been inactive past the TTL. */\n private async _sweepStaleChatRecoveryIncidents(now: number): Promise<void> {\n const entries = await this.ctx.storage.list<ChatRecoveryIncident>({\n prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX\n });\n const staleKeys: string[] = [];\n for (const [key, incident] of entries) {\n const lastActive = incident?.lastAttemptAt ?? incident?.firstSeenAt ?? 0;\n if (now - lastActive > CHAT_RECOVERY_INCIDENT_TTL_MS) {\n staleKeys.push(key);\n }\n }\n for (const key of staleKeys) {\n await this.ctx.storage.delete(key);\n }\n }\n\n private async _beginChatRecoveryIncident(input: {\n requestId: string;\n recoveryRootRequestId?: string | null;\n latestUserMessageId?: string | null;\n targetAssistantId?: string | null;\n recoveryKind: ChatRecoveryKind;\n /** Test-only clock injection for deterministic debounce/window timing. */\n nowMs?: number;\n }): Promise<{\n incident: ChatRecoveryIncident;\n config: ResolvedChatRecoveryConfig;\n exhausted: boolean;\n }> {\n const config = this._resolveChatRecoveryConfig();\n const incidentId = this._chatRecoveryIncidentId(input);\n const key = this._chatRecoveryIncidentKey(incidentId);\n const now = input.nowMs ?? Date.now();\n await this._sweepStaleChatRecoveryIncidents(now);\n const existing = await this.ctx.storage.get<ChatRecoveryIncident>(key);\n\n // Forward-progress detection. A mid-turn deploy resets the Durable Object\n // (\"code was updated\"); the interrupted continuation is re-detected on the\n // next wake. A turn that followed real progress (more durably-produced\n // content than the last attempt saw) is environmental churn, not a poison\n // turn.\n const prevProgress = existing?.progress ?? 0;\n const currentProgress = await this._chatRecoveryProgressMarker();\n const madeProgress = existing != null && currentProgress > prevProgress;\n\n // Wall-clock-keyed-to-progress budget (#1637). The raw attempt count is the\n // wrong primary bound under deploy churn: one rollout drops/reconnects the\n // socket several times (~11–22s), each firing an alarm, so a count inflates\n // far faster than the real interruption rate and seals a healthy turn.\n // • PRIMARY — no-progress window: `lastProgressAt` resets on every\n // progress-bearing attempt, so a turn that keeps producing content\n // survives churn indefinitely; a stuck turn is sealed after 5 min.\n // • DEBOUNCE — alarms bunched within `ALARM_DEBOUNCE_MS` collapse into one\n // attempt, so a single rollout's reconnect storm isn't N attempts.\n // • SECONDARY — the attempt cap is a high backstop (resets on progress).\n // • ABSOLUTE — the 15-min incident-age ceiling never resets (final stop).\n const lastProgressAt = madeProgress\n ? now\n : (existing?.lastProgressAt ?? existing?.firstSeenAt ?? now);\n const noProgressExceeded =\n existing != null &&\n now - lastProgressAt > CHAT_RECOVERY_NO_PROGRESS_WINDOW_MS;\n const incidentAgeExceeded =\n existing != null &&\n now - existing.firstSeenAt > CHAT_RECOVERY_MAX_WINDOW_MS;\n const debounced =\n existing != null &&\n !madeProgress &&\n now - existing.lastAttemptAt < CHAT_RECOVERY_ALARM_DEBOUNCE_MS;\n\n const attempt = madeProgress\n ? 1\n : debounced\n ? (existing?.attempt ?? 1)\n : (existing?.attempt ?? 0) + 1;\n const exhausted =\n noProgressExceeded || incidentAgeExceeded || attempt > config.maxAttempts;\n const incident: ChatRecoveryIncident = {\n incidentId,\n requestId: input.requestId,\n recoveryRootRequestId: input.recoveryRootRequestId ?? input.requestId,\n recoveryKind: input.recoveryKind,\n attempt,\n maxAttempts: config.maxAttempts,\n status: exhausted ? \"exhausted\" : \"attempting\",\n firstSeenAt: existing?.firstSeenAt ?? now,\n lastAttemptAt: now,\n lastProgressAt,\n progress: Math.max(prevProgress, currentProgress),\n ...(exhausted\n ? {\n reason: incidentAgeExceeded\n ? \"max_recovery_window_exceeded\"\n : noProgressExceeded\n ? \"no_progress_timeout\"\n : \"max_attempts_exceeded\"\n }\n : {})\n };\n await this.ctx.storage.put(key, incident);\n\n if (!existing) {\n this._emit(\"chat:recovery:detected\", {\n incidentId,\n requestId: input.requestId,\n attempt,\n maxAttempts: config.maxAttempts,\n recoveryKind: input.recoveryKind\n });\n }\n this._emit(\"chat:recovery:attempt\", {\n incidentId,\n requestId: input.requestId,\n attempt,\n maxAttempts: config.maxAttempts,\n recoveryKind: input.recoveryKind\n });\n\n return { incident, config, exhausted };\n }\n\n private async _updateChatRecoveryIncident(\n incidentId: string | undefined,\n status: ChatRecoveryIncident[\"status\"],\n reason?: string\n ): Promise<void> {\n if (!incidentId) return;\n const key = this._chatRecoveryIncidentKey(incidentId);\n const incident = await this.ctx.storage.get<ChatRecoveryIncident>(key);\n if (!incident) return;\n // A completed recovery is terminal and will not be retried, so drop the\n // record instead of leaving it in storage forever. Non-completed states\n // (scheduled/skipped/failed) are retained so the attempt budget survives\n // across restarts; the TTL sweep eventually reclaims abandoned ones.\n if (status === \"completed\") {\n await this.ctx.storage.delete(key);\n } else {\n await this.ctx.storage.put(key, {\n ...incident,\n status,\n ...(reason ? { reason } : {})\n } satisfies ChatRecoveryIncident);\n }\n\n const eventType =\n status === \"completed\"\n ? \"chat:recovery:completed\"\n : status === \"skipped\"\n ? \"chat:recovery:skipped\"\n : status === \"failed\"\n ? \"chat:recovery:failed\"\n : undefined;\n if (eventType) {\n this._emit(eventType, {\n incidentId,\n requestId: incident.requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind: incident.recoveryKind,\n ...(reason ? { reason } : {})\n });\n }\n\n // Live \"recovering…\" status (#1620): a scheduled continuation/retry means\n // recovery is in progress; a terminal incident state resolves it. Keyed by\n // the recovery-root request id so it lines up with the turn the client is\n // watching. (Exhaustion + normal completion also clear via\n // `_recordTerminalChatStatus`; this covers the benign-skip / failed paths\n // that never reach a turn-level terminal.)\n if (status === \"scheduled\") {\n await this._setChatRecovering(\n true,\n incident.recoveryRootRequestId ?? incident.requestId\n );\n } else if (\n status === \"completed\" ||\n status === \"skipped\" ||\n status === \"failed\"\n ) {\n await this._setChatRecovering(false);\n }\n }\n\n private async _exhaustChatRecovery(\n incident: ChatRecoveryIncident,\n config: ResolvedChatRecoveryConfig,\n partial: { text: string; parts: MessagePart[] },\n streamId: string,\n createdAt: number\n ): Promise<void> {\n const ctx: ChatRecoveryExhaustedContext = {\n incidentId: incident.incidentId,\n requestId: incident.requestId,\n recoveryRootRequestId:\n incident.recoveryRootRequestId ?? incident.requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind: incident.recoveryKind,\n streamId,\n createdAt,\n partialText: partial.text,\n partialParts: partial.parts,\n reason: incident.reason ?? \"max_attempts_exceeded\",\n terminalMessage: config.terminalMessage\n };\n this._emit(\"chat:recovery:exhausted\", ctx);\n // A throwing onExhausted hook must not prevent the terminal UX from being\n // delivered, otherwise the turn wedges with no user-visible resolution.\n try {\n await config.onExhausted?.(ctx);\n } catch (error) {\n console.error(\"[Think] chatRecovery onExhausted hook threw\", error);\n }\n // The submission is keyed by the recovery ROOT request id; `incident.requestId`\n // is the latest per-continuation id and won't match a chained submission.\n await this._markRecoveredSubmissionInterrupted(\n incident.recoveryRootRequestId ?? incident.requestId,\n config.terminalMessage\n );\n await this._recordTerminalChatStatus(\n \"interrupted\",\n incident.requestId,\n config.terminalMessage\n );\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: incident.requestId,\n body: config.terminalMessage,\n done: true,\n error: true\n });\n // The exhausted record is retained for inspection and reclaimed later by\n // the TTL sweep; only successful (completed) incidents are deleted eagerly.\n }\n\n /**\n * Route a stream-stall watchdog abort into bounded recovery instead of a\n * terminal error (#1626). A stall happens inside a LIVE isolate (no DO\n * restart), so the normal restart-detected recovery path never runs — we\n * open/advance a recovery incident here and schedule a continuation, reusing\n * the SAME budget (`maxAttempts` + wall-clock window + progress-aware reset)\n * as deploy/eviction recovery. A transient hang recovers; a persistently\n * hanging provider exhausts the budget. Idempotency matches deploy recovery:\n * settled tool results are durable and won't re-run, but a tool that was\n * mid-execution when the stall fired re-runs on the continuation.\n *\n * Returns:\n * - `\"scheduled\"` — a continuation was scheduled; the caller suppresses the\n * terminal error and closes the stream cleanly.\n * - `\"exhausted\"` — the budget is spent; this routes through the SAME\n * `_exhaustChatRecovery` path as deploy recovery (fires `onExhausted`,\n * emits `chat:recovery:exhausted`, marks the submission interrupted, and\n * delivers the configured `terminalMessage`). The caller must NOT run the\n * generic terminal path — the terminal UX is already delivered.\n * - `\"disabled\"` — chat recovery is off; the caller falls through to the\n * generic terminal error (the watchdog's original \"kill the spinner\"\n * behavior, unchanged).\n */\n private async _routeStallToBoundedRecovery(input: {\n requestId: string;\n streamId: string;\n partialParts: MessagePart[];\n targetAssistantId?: string;\n }): Promise<\"scheduled\" | \"exhausted\" | \"disabled\"> {\n // Stall-recovery is automatic only when chat recovery is enabled (the\n // default for Think). With recovery off, a stall stays terminal — there is\n // no budget/continuation machinery to route into.\n if (!this._resolveChatRecoveryConfig().enabled) return \"disabled\";\n const recoveryRootRequestId =\n this._activeChatRecoveryRootRequestId ?? input.requestId;\n const latestUserMessageId =\n [...this.messages].reverse().find((m) => m.role === \"user\")?.id ?? null;\n const { incident, config, exhausted } =\n await this._beginChatRecoveryIncident({\n requestId: input.requestId,\n recoveryRootRequestId,\n latestUserMessageId,\n recoveryKind: \"continue\"\n });\n if (exhausted) {\n // Budget spent: deliver the SAME terminal UX as deploy-recovery\n // exhaustion (terminalMessage + onExhausted + chat:recovery:exhausted +\n // submission interrupted) instead of letting the raw stall error leak\n // out. `firstSeenAt` is the closest available turn-start proxy here.\n const partialText = input.partialParts\n .filter(\n (p): p is { type: \"text\"; text: string } =>\n (p as { type?: string }).type === \"text\"\n )\n .map((p) => p.text)\n .join(\"\");\n await this._exhaustChatRecovery(\n incident,\n config,\n { text: partialText, parts: input.partialParts },\n input.streamId,\n incident.firstSeenAt\n );\n return \"exhausted\";\n }\n await this._updateChatRecoveryIncident(incident.incidentId, \"scheduled\");\n this._emit(\"chat:recovery:scheduled\", {\n incidentId: incident.incidentId,\n requestId: input.requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind: \"continue\"\n });\n // If a durable submission is running for this turn, the continuation must\n // complete it (otherwise the submission hangs) — same as deploy recovery.\n const recoveredRequestId = this._hasRunningSubmission(recoveryRootRequestId)\n ? recoveryRootRequestId\n : undefined;\n await this.schedule(\n 0,\n \"_chatRecoveryContinue\",\n {\n ...(input.targetAssistantId\n ? { targetAssistantId: input.targetAssistantId }\n : {}),\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n lastBody: this._lastBody ?? null,\n lastClientTools: this._lastClientTools ?? null,\n ...(recoveredRequestId ? { recoveredRequestId } : {})\n },\n { idempotent: true }\n );\n return \"scheduled\";\n }\n\n protected override async _handleInternalFiberRecovery(\n ctx: FiberRecoveryContext\n ): Promise<boolean> {\n if (await this._messengerRuntime?.handleFiberRecovery(ctx)) {\n return true;\n }\n\n const chatPrefix = (this.constructor as typeof Think).CHAT_FIBER_NAME + \":\";\n if (!ctx.name.startsWith(chatPrefix)) {\n return false;\n }\n\n const requestId = ctx.name.slice(chatPrefix.length);\n const { snapshot: recoverySnapshot, user: recoveryData } =\n unwrapChatFiberSnapshot<\"think-chat-turn\">(\n \"__cfThinkChatFiberSnapshot\",\n ctx.snapshot,\n \"think-chat-turn\"\n );\n\n let streamId = \"\";\n let streamStatus: \"streaming\" | \"completed\" | \"error\" | undefined;\n if (requestId) {\n const rows = this.sql<{\n id: string;\n status: \"streaming\" | \"completed\" | \"error\";\n }>`\n SELECT id, status FROM cf_ai_chat_stream_metadata\n WHERE request_id = ${requestId}\n ORDER BY created_at DESC LIMIT 1\n `;\n if (rows.length > 0) {\n streamId = rows[0].id;\n streamStatus = rows[0].status;\n }\n }\n if (!streamId && this._resumableStream.hasActiveStream()) {\n streamId = this._resumableStream.activeStreamId ?? \"\";\n streamStatus = \"streaming\";\n }\n\n const partial = streamId\n ? this._getPartialStreamText(streamId)\n : { text: \"\", parts: [] as MessagePart[] };\n\n const streamStillActive =\n streamId &&\n this._resumableStream.hasActiveStream() &&\n this._resumableStream.activeStreamId === streamId;\n\n const streamIsTerminal =\n streamStatus === \"completed\" || streamStatus === \"error\";\n\n const retryTargetUserId = await this._recoverablePreStreamUserId(\n recoverySnapshot,\n streamId ?? \"\",\n partial\n );\n const shouldRetryBase = retryTargetUserId !== null && !streamIsTerminal;\n const recoveryKind: ChatRecoveryKind = shouldRetryBase\n ? \"retry\"\n : \"continue\";\n const recoveryRootRequestId =\n recoverySnapshot?.recoveryRootRequestId ?? requestId;\n const { incident, config, exhausted } =\n await this._beginChatRecoveryIncident({\n requestId,\n recoveryRootRequestId,\n latestUserMessageId: recoverySnapshot?.latestUserMessageId,\n recoveryKind\n });\n\n if (exhausted) {\n // Preserve the settled partial before sealing the turn. Exhaustion is\n // decided BEFORE `onChatRecovery` is consulted, so without this the\n // settled (often non-idempotent) tool results the turn already produced\n // are discarded and the model re-runs them on the next message (#1631).\n // Same gating as the normal path below so an already-persisted partial is\n // never duplicated.\n if (\n await this._shouldPersistOrphanedPartial(streamId, {\n streamStillActive: Boolean(streamStillActive),\n streamIsTerminal,\n snapshot: recoverySnapshot\n })\n ) {\n await this._persistOrphanedStream(streamId);\n }\n await this._exhaustChatRecovery(\n incident,\n config,\n partial,\n streamId ?? \"\",\n ctx.createdAt\n );\n return true;\n }\n\n // Any throw after the incident is opened (user `onChatRecovery`, orphan\n // persistence, scheduling) must flip the incident to a terminal `failed`\n // state and emit, otherwise it leaks in `attempting` and is never\n // observable as a stuck turn.\n try {\n const options =\n (await this.onChatRecovery({\n incidentId: incident.incidentId,\n recoveryRootRequestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind,\n streamId: streamId ?? \"\",\n requestId,\n partialText: partial.text,\n partialParts: partial.parts,\n recoveryData,\n messages: [...this.messages],\n lastBody: recoverySnapshot?.lastBody ?? this._lastBody,\n lastClientTools:\n recoverySnapshot?.lastClientTools ?? this._lastClientTools,\n createdAt: ctx.createdAt\n })) ?? {};\n\n const shouldPersist = await this._shouldPersistOrphanedPartial(streamId, {\n streamStillActive: Boolean(streamStillActive),\n streamIsTerminal,\n snapshot: recoverySnapshot\n });\n\n // Settled work — completed, often non-idempotent tool results — is NEVER\n // dropped by recovery. `persist: false` only suppresses persistence of a\n // partial that has nothing settled to lose; a partial carrying settled\n // tool results is persisted regardless, so an app can never accidentally\n // discard completed work (and never needs `{ persist: true }` just to be\n // safe). A safe default beats a warning about an unsafe one (#1631).\n if (\n shouldPersist &&\n (options.persist !== false ||\n this._partialHasSettledToolResults(partial.parts))\n ) {\n await this._persistOrphanedStream(streamId);\n }\n\n if (streamStillActive) {\n this._resumableStream.complete(streamId);\n }\n\n const shouldRetry =\n retryTargetUserId !== null &&\n options.continue !== false &&\n !streamIsTerminal;\n const lastLeaf = shouldRetry ? null : await this.session.getLatestLeaf();\n const targetId =\n lastLeaf?.role === \"assistant\" && !streamIsTerminal\n ? lastLeaf.id\n : undefined;\n const canContinue =\n !shouldRetry && options.continue !== false && !streamIsTerminal;\n // The durable submission is keyed by the recovery ROOT request id (stable\n // across the whole continuation chain), not this turn's per-continuation\n // requestId. Keying off `requestId` loses the link on every chained\n // continuation, so the continuation that finally completes the turn can no\n // longer mark the submission done (see investigate/recovery-* findings).\n const hasRunningSubmission = this._hasRunningSubmission(\n recoveryRootRequestId\n );\n\n if (streamIsTerminal && hasRunningSubmission) {\n await this._completeRecoveredSubmission(\n recoveryRootRequestId,\n streamStatus === \"completed\" ? \"completed\" : \"error\",\n requestId,\n streamStatus === \"completed\"\n ? null\n : \"Recovered chat stream had already errored.\"\n );\n }\n\n const recoveredRequestId =\n (canContinue || shouldRetry) && hasRunningSubmission\n ? recoveryRootRequestId\n : undefined;\n\n if (shouldRetry) {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"scheduled\"\n );\n this._emit(\"chat:recovery:scheduled\", {\n incidentId: incident.incidentId,\n requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind\n });\n await this.schedule(\n 0,\n \"_chatRecoveryRetry\",\n {\n targetUserId: retryTargetUserId,\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n lastBody: recoverySnapshot?.lastBody ?? null,\n lastClientTools: recoverySnapshot?.lastClientTools ?? null,\n ...(recoveredRequestId ? { recoveredRequestId } : {})\n },\n { idempotent: true }\n );\n } else if (canContinue) {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"scheduled\"\n );\n this._emit(\"chat:recovery:scheduled\", {\n incidentId: incident.incidentId,\n requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind\n });\n await this.schedule(\n 0,\n \"_chatRecoveryContinue\",\n {\n ...(targetId ? { targetAssistantId: targetId } : {}),\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n ...(recoverySnapshot\n ? {\n lastBody: recoverySnapshot.lastBody ?? null,\n lastClientTools: recoverySnapshot.lastClientTools ?? null\n }\n : {}),\n ...(recoveredRequestId ? { recoveredRequestId } : {})\n },\n { idempotent: true }\n );\n } else if (options.continue === false && !streamIsTerminal) {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"skipped\",\n \"continue_disabled\"\n );\n const disabledMessage =\n \"Submission was interrupted and chat recovery was disabled.\";\n // Key off the recovery ROOT, not this continuation's `requestId` — a\n // chained submission's row still carries the root id, so passing the\n // per-continuation id would miss it and leave it stuck `running`.\n await this._markRecoveredSubmissionInterrupted(\n recoveryRootRequestId,\n disabledMessage\n );\n // Unlike `conversation_changed` (a newer turn owns the UI, so silence\n // is correct), disabling recovery abandons the turn with no superseding\n // turn. Surface it like exhaustion so a reconnecting client isn't frozen.\n await this._recordTerminalChatStatus(\n \"interrupted\",\n requestId,\n disabledMessage\n );\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: disabledMessage,\n done: true,\n error: true\n });\n } else {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"skipped\",\n streamIsTerminal ? \"stream_terminal\" : \"not_recoverable\"\n );\n }\n\n return true;\n } catch (error) {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"failed\",\n error instanceof Error ? error.message : String(error)\n );\n throw error;\n }\n }\n\n private async _recoverablePreStreamUserId(\n snapshot: ChatFiberSnapshot<\"think-chat-turn\"> | null,\n streamId: string,\n partial: { text: string; parts: MessagePart[] }\n ): Promise<string | null> {\n if (\n !snapshot ||\n snapshot.continuation ||\n !snapshot.latestUserMessageId ||\n streamId ||\n partial.text ||\n partial.parts.length > 0\n ) {\n return null;\n }\n\n const lastLeaf = await this.session.getLatestLeaf();\n return lastLeaf?.role === \"user\" &&\n lastLeaf.id === snapshot.latestUserMessageId\n ? snapshot.latestUserMessageId\n : null;\n }\n\n private async _hasPersistedRecoveredAssistant(\n snapshot: ChatFiberSnapshot<\"think-chat-turn\"> | null\n ): Promise<boolean> {\n const lastLeaf = await this.session.getLatestLeaf();\n return (\n lastLeaf?.role === \"assistant\" &&\n lastLeaf.id !== snapshot?.latestMessageId\n );\n }\n\n /**\n * Whether the orphaned stream's partial should be materialized into an\n * assistant message: there is a stream, and it is either still active or\n * terminal-but-not-yet-persisted. Shared by the normal recovery path AND the\n * exhaustion path so neither discards settled work nor duplicates a partial\n * an earlier attempt already saved.\n */\n private async _shouldPersistOrphanedPartial(\n streamId: string,\n opts: {\n streamStillActive: boolean;\n streamIsTerminal: boolean;\n snapshot: ChatFiberSnapshot<\"think-chat-turn\"> | null;\n }\n ): Promise<boolean> {\n if (!streamId) return false;\n const alreadyPersisted =\n opts.streamIsTerminal &&\n (await this._hasPersistedRecoveredAssistant(opts.snapshot));\n return (\n opts.streamStillActive || (opts.streamIsTerminal && !alreadyPersisted)\n );\n }\n\n /** Whether a reconstructed partial carries any settled (provider-accepted)\n * tool result — the completed, often non-idempotent work that a\n * `{ persist: false }` recovery return would silently discard. */\n private _partialHasSettledToolResults(parts: MessagePart[]): boolean {\n return parts.some((part) => {\n const record = part as Record<string, unknown>;\n const type = typeof record.type === \"string\" ? record.type : \"\";\n return (\n (type.startsWith(\"tool-\") || type === \"dynamic-tool\") &&\n this._toolPartHasSettledResult(record)\n );\n });\n }\n\n /**\n * Reschedule a recovery callback that timed out waiting for stable state,\n * consuming one attempt. Returns `true` if rescheduled, `false` if the\n * attempt budget is exhausted (the caller then fails the turn terminally).\n *\n * Shared by `_chatRecoveryRetry` and `_chatRecoveryContinue` so the\n * non-idempotent scheduling invariant lives in exactly one place — a fix to\n * one path can't silently diverge from the other. Mirrors the same helper in\n * `@cloudflare/ai-chat`.\n */\n private async _rescheduleRecoveryAfterStableTimeout(\n callback: \"_chatRecoveryContinue\" | \"_chatRecoveryRetry\",\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined,\n maxAttempts: number\n ): Promise<boolean> {\n const incidentKey = data?.incidentId\n ? this._chatRecoveryIncidentKey(data.incidentId)\n : null;\n const incident = incidentKey\n ? await this.ctx.storage.get<ChatRecoveryIncident>(incidentKey)\n : null;\n if (!incident || !incidentKey) return false;\n const attempt = incident.attempt ?? 0;\n if (attempt >= (incident.maxAttempts ?? maxAttempts)) return false;\n await this.ctx.storage.put(incidentKey, {\n ...incident,\n attempt: attempt + 1,\n status: \"scheduled\",\n lastAttemptAt: Date.now(),\n reason: \"stable_timeout_retry\"\n });\n // Must NOT be idempotent: this runs INSIDE the currently-executing one-shot\n // schedule row (which `alarm()` deletes only after we return). An idempotent\n // reschedule would dedup onto that row and then be deleted with it — the\n // retry would silently never fire, stalling the turn. A fresh delayed row\n // survives the deletion.\n await this.schedule(\n CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS,\n callback,\n data ?? {},\n { idempotent: false }\n );\n return true;\n }\n\n /**\n * Resolve the stream id for a recovery turn so the give-up terminalization\n * can surface whatever partial the turn produced. Prefers the durable stream\n * row keyed by the recovery-root request id; falls back to the live active\n * stream. Returns `\"\"` when neither is available (the terminal banner still\n * fires — `_exhaustChatRecovery` does not require a stream).\n */\n private _resolveRecoveryStreamId(requestId: string): string {\n if (requestId) {\n const fromMetadata = this._resumableStream\n .getAllStreamMetadata()\n .find((metadata) => metadata.request_id === requestId)?.id;\n if (fromMetadata) return fromMetadata;\n }\n return this._resumableStream.hasActiveStream()\n ? (this._resumableStream.activeStreamId ?? \"\")\n : \"\";\n }\n\n /**\n * Terminalize a recovery turn that has run out of stable-state-timeout retry\n * budget — or whose incident record has vanished — by routing through the\n * SAME `_exhaustChatRecovery` path as deploy-recovery and stall exhaustion\n * (#1626/#1631). It fires `onExhausted`, emits `chat:recovery:exhausted`,\n * marks the durable submission interrupted, records the terminal chat status,\n * and delivers the configured `terminalMessage`.\n *\n * This replaces the older give-up that only set the incident to `failed` and\n * completed the recovered submission as `error`, which bypassed\n * `_exhaustChatRecovery` entirely — so an app relying on `onExhausted` for the\n * terminal banner regressed to an eternal spinner when recovery gave up under\n * extreme churn (the stable-state wait timing out every attempt until the\n * budget drained). Shared by `_chatRecoveryRetry` and `_chatRecoveryContinue`.\n *\n * Exactly-once terminalization is defended by two independent guards:\n * 1. The `stored?.status === \"exhausted\"` re-entry guard below — once an\n * incident is sealed, a duplicate stale alarm (or retried callback)\n * returns before re-firing. The sealed incident is re-persisted even when\n * the record was found missing, so a swept record is re-armed for the\n * guard on the next alarm.\n * 2. The durable-submission paths additionally short-circuit earlier at the\n * `submission_not_running` check (the submission is already `error` after\n * the first give-up). This is the ONLY guard `@cloudflare/ai-chat` lacks\n * (no submission layer), so guard #1 carries it there.\n *\n * Two residual at-least-once edges, both deliberately accepted as \"deliver a\n * second banner\" ≫ \"silently drop the turn\":\n * • No `incidentId` at all in the payload (only reachable via a direct/test\n * invocation — every production scheduler carries one): the synthesized\n * incident can't be persisted (no key), so guard #1 can't arm.\n * • The record is swept AGAIN between two alarms (guard #1 re-persists on the\n * first, so this needs a second independent sweep) — vanishingly unlikely.\n */\n private async _exhaustRecoveryAfterStableTimeout(\n callback: \"_chatRecoveryContinue\" | \"_chatRecoveryRetry\",\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined\n ): Promise<void> {\n const config = this._resolveChatRecoveryConfig();\n const incidentKey = data?.incidentId\n ? this._chatRecoveryIncidentKey(data.incidentId)\n : null;\n const stored = incidentKey\n ? await this.ctx.storage.get<ChatRecoveryIncident>(incidentKey)\n : null;\n\n // Re-entry guard #1 (see method doc): a sealed incident means\n // terminalization already happened, so a duplicate stale alarm must not\n // re-fire `onExhausted` / re-broadcast the banner.\n if (stored?.status === \"exhausted\") return;\n\n const rootRequestId =\n data?.originalRequestId ??\n data?.recoveredRequestId ??\n this._activeChatRecoveryRootRequestId ??\n stored?.recoveryRootRequestId ??\n stored?.requestId ??\n \"\";\n\n // `stable_timeout` distinguishes a give-up driven by repeated stable-state\n // timeouts from the generic max-attempts / no-progress exhaustion reasons.\n const incident: ChatRecoveryIncident = stored\n ? { ...stored, status: \"exhausted\", reason: \"stable_timeout\" }\n : {\n // Silent-drop guard: the incident record is gone (no `incidentId`, or\n // it was swept/deleted before this stale alarm fired). Synthesize a\n // minimal incident so the turn STILL terminalizes through\n // `onExhausted` instead of being dropped with no terminal UX — the\n // exact \"eternal spinner\" failure mode this fix closes.\n incidentId: data?.incidentId ?? crypto.randomUUID(),\n requestId: rootRequestId,\n recoveryRootRequestId: rootRequestId,\n recoveryKind:\n callback === \"_chatRecoveryRetry\" ? \"retry\" : \"continue\",\n attempt: config.maxAttempts,\n maxAttempts: config.maxAttempts,\n status: \"exhausted\",\n firstSeenAt: Date.now(),\n lastAttemptAt: Date.now(),\n reason: \"stable_timeout\"\n };\n\n // Persist the sealed incident (retained for inspection / TTL sweep) so the\n // re-entry guard above sees `exhausted` if a duplicate stale alarm fires.\n if (incidentKey) {\n await this.ctx.storage.put(incidentKey, incident);\n }\n\n const streamId = this._resolveRecoveryStreamId(\n incident.recoveryRootRequestId ?? incident.requestId\n );\n const partial = streamId\n ? this._getPartialStreamText(streamId)\n : { text: \"\", parts: [] as MessagePart[] };\n\n await this._exhaustChatRecovery(\n incident,\n config,\n partial,\n streamId,\n incident.firstSeenAt\n );\n }\n\n async _chatRecoveryRetry(data?: ChatRecoveryRetryData): Promise<void> {\n const recoveredSubmission = data?.recoveredRequestId\n ? this._readRunningSubmissionByRequestId(data.recoveredRequestId)\n : null;\n if (data?.recoveredRequestId && !recoveredSubmission) {\n await this._updateChatRecoveryIncident(\n data.incidentId,\n \"skipped\",\n \"submission_not_running\"\n );\n return;\n }\n\n const previousRootRequestId = this._activeChatRecoveryRootRequestId;\n this._activeChatRecoveryRootRequestId =\n data?.originalRequestId ?? previousRootRequestId;\n const controller = recoveredSubmission ? new AbortController() : null;\n if (recoveredSubmission && controller) {\n this._submissionAbortControllers.set(\n recoveredSubmission.submission_id,\n controller\n );\n }\n\n try {\n const recoveryConfig = this._resolveChatRecoveryConfig();\n const ready = await this.waitUntilStable({\n timeout: recoveryConfig.stableTimeoutMs\n });\n if (!ready) {\n // Transient under churn — reschedule within the attempt budget rather\n // than terminally failing the turn (see _chatRecoveryContinue).\n if (\n await this._rescheduleRecoveryAfterStableTimeout(\n \"_chatRecoveryRetry\",\n data,\n recoveryConfig.maxAttempts\n )\n ) {\n return;\n }\n // Budget spent: terminalize through the SAME exhaustion path as deploy\n // recovery (fires `onExhausted`, delivers the `terminalMessage` banner,\n // marks the submission interrupted) instead of silently dropping the\n // turn — otherwise an app relying on `onExhausted` sees an eternal\n // spinner.\n await this._exhaustRecoveryAfterStableTimeout(\n \"_chatRecoveryRetry\",\n data\n );\n return;\n }\n\n const lastLeaf = await this.session.getLatestLeaf();\n if (!lastLeaf || lastLeaf.role !== \"user\") {\n // The user turn is no longer the leaf — it was already answered (an\n // assistant message now follows) or the conversation moved on. This is\n // a benign skip, not an error: a completing turn marks the submission\n // `completed`; otherwise it is terminally `skipped`, never `error`.\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"skipped\",\n \"no_unanswered_user_message\"\n );\n if (data?.recoveredRequestId) {\n await this._completeRecoveredSubmission(\n data.recoveredRequestId,\n \"skipped\",\n null,\n null\n );\n }\n return;\n }\n\n if (data?.targetUserId && lastLeaf.id !== data.targetUserId) {\n // Superseded by a genuinely newer user turn — terminal `skipped`, not an\n // error (recovery being superseded is benign).\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"skipped\",\n \"conversation_changed\"\n );\n if (data?.recoveredRequestId) {\n await this._completeRecoveredSubmission(\n data.recoveredRequestId,\n \"skipped\",\n null,\n null\n );\n }\n return;\n }\n\n this._applyRecoveredRequestContext(data);\n const result = await this._retryLastUserTurn(\n this._lastClientTools,\n this._lastBody,\n controller ? { signal: controller.signal } : undefined\n );\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n result.status === \"completed\"\n ? \"completed\"\n : result.status === \"skipped\"\n ? \"skipped\"\n : \"failed\",\n result.error\n );\n if (data?.recoveredRequestId) {\n await this._completeRecoveredSubmission(\n data.recoveredRequestId,\n result.status,\n result.requestId || null,\n result.status === \"completed\"\n ? null\n : (result.error ?? `Recovery retry ${result.status}.`)\n );\n }\n } catch (error) {\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"failed\",\n error instanceof Error ? error.message : String(error)\n );\n if (data?.recoveredRequestId) {\n await this._completeRecoveredSubmission(\n data.recoveredRequestId,\n \"error\",\n null,\n error instanceof Error ? error.message : String(error)\n );\n }\n throw error;\n } finally {\n this._activeChatRecoveryRootRequestId = previousRootRequestId;\n if (recoveredSubmission) {\n this._submissionAbortControllers.delete(\n recoveredSubmission.submission_id\n );\n }\n }\n }\n\n private _hasRunningSubmission(requestId: string): boolean {\n return this._readRunningSubmissionByRequestId(requestId) !== null;\n }\n\n private _readRunningSubmissionByRequestId(\n requestId: string\n ): ThinkSubmissionRow | null {\n this._ensureSubmissionTable();\n const rows = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE request_id = ${requestId}\n AND status = 'running'\n LIMIT 1\n `;\n return rows[0] ?? null;\n }\n\n private async _markRecoveredSubmissionInterrupted(\n requestId: string,\n message: string\n ): Promise<void> {\n this._ensureSubmissionTable();\n const rows = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE request_id = ${requestId}\n AND status = 'running'\n LIMIT 1\n `;\n const row = rows[0];\n if (!row) return;\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'error',\n error_message = ${message},\n completed_at = ${Date.now()}\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n `;\n const updated = this._readSubmission(row.submission_id);\n if (updated) await this._emitSubmissionStatus(updated);\n }\n\n private async _completeRecoveredSubmission(\n originalRequestId: string,\n status: ThinkSubmissionStatus,\n requestId: string | null,\n errorMessage: string | null\n ): Promise<void> {\n this._ensureSubmissionTable();\n const completedAt = Date.now();\n const streamId = requestId\n ? (this._resumableStream\n .getAllStreamMetadata()\n .find((metadata) => metadata.request_id === requestId)?.id ?? null)\n : null;\n this.sql`\n UPDATE cf_think_submissions\n SET status = ${status},\n request_id = COALESCE(${requestId}, request_id),\n stream_id = COALESCE(${streamId}, stream_id),\n error_message = ${errorMessage},\n completed_at = ${completedAt}\n WHERE request_id = ${originalRequestId}\n AND status = 'running'\n `;\n const rows = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE request_id = COALESCE(${requestId}, ${originalRequestId})\n ORDER BY completed_at DESC\n LIMIT 1\n `;\n const updated = rows[0];\n if (updated && this._isTerminalSubmissionStatus(updated.status)) {\n await this._emitSubmissionStatus(updated);\n }\n }\n\n protected async onChatRecovery(\n _ctx: ChatRecoveryContext\n ): Promise<ChatRecoveryOptions | void> {\n return {};\n }\n\n async _chatRecoveryContinue(data?: ChatRecoveryContinueData): Promise<void> {\n const recoveredSubmission = data?.recoveredRequestId\n ? this._readRunningSubmissionByRequestId(data.recoveredRequestId)\n : null;\n if (data?.recoveredRequestId && !recoveredSubmission) {\n await this._updateChatRecoveryIncident(\n data.incidentId,\n \"skipped\",\n \"submission_not_running\"\n );\n return;\n }\n\n const previousRootRequestId = this._activeChatRecoveryRootRequestId;\n this._activeChatRecoveryRootRequestId =\n data?.originalRequestId ?? previousRootRequestId;\n const controller = recoveredSubmission ? new AbortController() : null;\n if (recoveredSubmission && controller) {\n this._submissionAbortControllers.set(\n recoveredSubmission.submission_id,\n controller\n );\n }\n\n try {\n const recoveryConfig = this._resolveChatRecoveryConfig();\n const ready = await this.waitUntilStable({\n timeout: recoveryConfig.stableTimeoutMs\n });\n if (!ready) {\n console.warn(\n \"[Think] _chatRecoveryContinue timed out waiting for stable state\"\n );\n // A stable-state timeout under deploy churn is usually transient (the\n // isolate is still settling / another deploy is in flight). Reschedule\n // within the attempt budget instead of terminally failing the turn at\n // attempt 1; only give up once the budget is genuinely exhausted.\n if (\n await this._rescheduleRecoveryAfterStableTimeout(\n \"_chatRecoveryContinue\",\n data,\n recoveryConfig.maxAttempts\n )\n ) {\n return;\n }\n // Budget spent: terminalize through the SAME exhaustion path as deploy\n // recovery (fires `onExhausted`, delivers the `terminalMessage` banner,\n // marks the submission interrupted) instead of silently dropping the\n // turn — otherwise an app relying on `onExhausted` sees an eternal\n // spinner.\n await this._exhaustRecoveryAfterStableTimeout(\n \"_chatRecoveryContinue\",\n data\n );\n return;\n }\n\n const targetId = data?.targetAssistantId;\n const lastLeaf = await this.session.getLatestLeaf();\n if (targetId && lastLeaf?.id !== targetId) {\n // The target assistant message is no longer the leaf. This is NOT an\n // error and must never clobber the submission to `error`:\n // - leaf is an ASSISTANT message → recovery's OWN later continuation\n // advanced (or already completed) this turn. This continuation is\n // stale/superseded; skip benignly and leave the submission alone so\n // the active continuation marks the real outcome (`completed`).\n // - leaf is a USER message → a genuinely newer turn superseded this\n // one; mark the submission `skipped` (terminal, non-error) so it\n // doesn't hang waiting on a turn nobody will finish.\n const supersededByNewerUserTurn = lastLeaf?.role === \"user\";\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"skipped\",\n \"conversation_changed\"\n );\n if (data?.recoveredRequestId && supersededByNewerUserTurn) {\n await this._completeRecoveredSubmission(\n data.recoveredRequestId,\n \"skipped\",\n null,\n null\n );\n }\n return;\n }\n\n this._applyRecoveredRequestContext(data);\n const result = await this.continueLastTurn(\n undefined,\n controller ? { signal: controller.signal } : undefined\n );\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n result.status === \"completed\"\n ? \"completed\"\n : result.status === \"skipped\"\n ? \"skipped\"\n : \"failed\",\n result.error\n );\n if (data?.recoveredRequestId) {\n await this._completeRecoveredSubmission(\n data.recoveredRequestId,\n result.status,\n result.requestId || null,\n result.status === \"completed\"\n ? null\n : (result.error ?? `Recovery ${result.status}.`)\n );\n }\n } catch (error) {\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"failed\",\n error instanceof Error ? error.message : String(error)\n );\n if (data?.recoveredRequestId) {\n await this._completeRecoveredSubmission(\n data.recoveredRequestId,\n \"error\",\n null,\n error instanceof Error ? error.message : String(error)\n );\n }\n throw error;\n } finally {\n this._activeChatRecoveryRootRequestId = previousRootRequestId;\n if (recoveredSubmission) {\n this._submissionAbortControllers.delete(\n recoveredSubmission.submission_id\n );\n }\n }\n }\n\n private _applyRecoveredRequestContext(\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined\n ): void {\n if (!data) return;\n if (\"lastClientTools\" in data) {\n this._lastClientTools = data.lastClientTools ?? undefined;\n this._persistClientTools();\n }\n if (\"lastBody\" in data) {\n this._lastBody = data.lastBody ?? undefined;\n this._persistBody();\n }\n }\n\n private _getPartialStreamText(streamId: string): {\n text: string;\n parts: MessagePart[];\n } {\n const chunks = this._resumableStream.getStreamChunks(streamId);\n const parts: MessagePart[] = [];\n\n for (const chunk of chunks) {\n try {\n const data = JSON.parse(chunk.body);\n applyChunkToParts(parts, data);\n } catch {\n // skip malformed chunks\n }\n }\n\n const text = parts\n .filter(\n (p): p is MessagePart & { type: \"text\"; text: string } =>\n p.type === \"text\" && \"text\" in p\n )\n .map((p) => p.text)\n .join(\"\");\n\n return { text, parts };\n }\n\n // ── Concurrency strategies ──────────────────────────────────────\n\n private _getSubmitConcurrencyDecision(\n isSubmitMessage: boolean\n ): SubmitConcurrencyDecision {\n return this._submitConcurrency.decide({\n concurrency: this.messageConcurrency,\n isSubmitMessage,\n queuedTurns: this._turnQueue.queuedCount()\n });\n }\n\n private _completeSkippedRequest(\n connection: Connection,\n requestId: string\n ): void {\n connection.send(\n JSON.stringify({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n })\n );\n }\n\n private _rollbackDroppedSubmit(connection: Connection): void {\n connection.send(\n JSON.stringify({\n type: MSG_CHAT_MESSAGES,\n messages: this.messages\n })\n );\n }\n\n // ── Auto-continuation ──────────────────────────────────────────\n\n private _scheduleAutoContinuation(connection: Connection): void {\n if (this._continuation.pending?.pastCoalesce) {\n this._continuation.deferred = {\n connection,\n connectionId: connection.id,\n clientTools: this._lastClientTools,\n body: undefined,\n errorPrefix: \"[Think] Auto-continuation failed:\",\n prerequisite: null\n };\n return;\n }\n\n if (this._continuation.pending) {\n this._continuation.pending.connection = connection;\n this._continuation.pending.connectionId = connection.id;\n this._continuation.pending.clientTools = this._lastClientTools;\n this._continuation.awaitingConnections.set(connection.id, connection);\n this._resetAutoContinuationTimer();\n return;\n }\n\n this._continuation.pending = {\n connection,\n connectionId: connection.id,\n requestId: crypto.randomUUID(),\n clientTools: this._lastClientTools,\n body: undefined,\n errorPrefix: \"[Think] Auto-continuation failed:\",\n prerequisite: null,\n pastCoalesce: false\n };\n this._continuation.awaitingConnections.set(connection.id, connection);\n this._resetAutoContinuationTimer();\n }\n\n private _resetAutoContinuationTimer(): void {\n if (this._continuationTimer) {\n clearTimeout(this._continuationTimer);\n }\n this._continuationTimer = setTimeout(() => {\n this._continuationTimer = null;\n const pending = this._continuation.pending;\n if (!pending) return;\n this._fireAutoContinuationWhenStable(pending.connection);\n }, 50);\n }\n\n /**\n * Fire an auto-continuation, but only once the model's parallel tool-call\n * batch is fully answered (#1649). When the model emits several tool calls in\n * one step the client answers each independently, so the first `autoContinue`\n * arrives while slower siblings are still `input-available`. Continuing then\n * would feed the provider an incomplete tool-result set\n * (`MissingToolResultsError`) or, via the transcript-repair backstop, silently\n * error the in-flight sibling and run a spurious extra continuation. We hold\n * the continuation on a barrier until the batch settles. The wait is bounded\n * (`AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS`) so a genuinely orphaned tool\n * call — e.g. the client disconnected mid-batch — still falls through to the\n * repair backstop rather than pinning the continuation open forever.\n */\n private _fireAutoContinuationWhenStable(connection: Connection): void {\n if (!this._continuation.pending) return;\n // The continuation is already running (a sibling result re-armed the timer\n // after it started). New results coalesce/defer into it — don't double-fire.\n if (this._continuation.pending.pastCoalesce) return;\n // A barrier wait is already in progress; it will fire once stable. Each\n // newly-arrived result re-arms the 50ms timer, but only one wait must run.\n if (this._continuationBarrierActive) return;\n // Fast path: no apply in flight and the leaf step is not mid-batch.\n if (!this._pendingInteractionPromise && !this._hasIncompleteToolBatch()) {\n this._fireAutoContinuation(connection);\n return;\n }\n this._continuationBarrierActive = true;\n // keepAlive so the isolate stays up while the (typically sub-second)\n // remainder of the tool batch lands — the pending-continuation state is\n // in-memory, so hibernating mid-wait would drop it.\n this.keepAliveWhile(() => this._awaitToolBatch())\n .catch(() => {})\n .finally(() => {\n this._continuationBarrierActive = false;\n // Fire whether the batch settled or the wait timed out: on timeout the\n // transcript-repair backstop handles the genuine orphan exactly as it\n // did before this barrier existed.\n const pending = this._continuation.pending;\n if (pending) this._fireAutoContinuation(pending.connection);\n });\n }\n\n /**\n * Block until the latest assistant step's parallel tool batch is fully\n * answered, or `AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS` elapses. Awaits the\n * in-flight tool-result apply when one exists (so a sibling that lands\n * mid-wait is observed promptly) and polls otherwise.\n */\n private async _awaitToolBatch(): Promise<void> {\n const deadline = Date.now() + AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS;\n while (Date.now() < deadline) {\n // The pending continuation was cleared (chat clear / turn reset) — nothing\n // to wait for; bail so the isolate isn't held by a stale wait.\n if (!this._continuation.pending) return;\n const pending = this._pendingInteractionPromise;\n if (pending) {\n // `_pendingInteractionPromise` is a single slot — awaiting it is only a\n // \"wake up as soon as an apply lands\" optimization, NOT the correctness\n // gate. If sibling results arrive together one overwrites the other, but\n // each apply still patches the message cache; the real gate is\n // `_hasIncompleteToolBatch()` re-checked on the next loop. A rejected\n // apply is likewise irrelevant — we just re-check.\n try {\n await pending;\n } catch {\n // Ignore — re-evaluate the batch below.\n }\n continue;\n }\n if (!this._hasIncompleteToolBatch()) return;\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n // Timed out with the batch still incomplete: a sibling tool result never\n // arrived (e.g. the client disconnected mid-batch). Proceed anyway — the\n // transcript-repair backstop errors the unanswered call rather than\n // pinning the continuation open forever.\n console.warn(\n `[Think] Auto-continuation proceeding after waiting ${AUTO_CONTINUATION_PENDING_TOOL_TIMEOUT_MS}ms for unanswered parallel tool result(s) (#1649).`\n );\n }\n\n /**\n * `true` when the latest assistant message is mid-batch: it carries at least\n * one settled tool result AND at least one tool call/approval still awaiting a\n * client result. That is the #1649 signature — the model fanned out parallel\n * tool calls and only some have been answered. Scoped to the leaf (the step\n * the continuation answers) so an unrelated dangling tool in an earlier\n * message doesn't block a legitimate follow-up continuation.\n */\n private _hasIncompleteToolBatch(): boolean {\n // Zero-allocation backward scan for the latest assistant message — this\n // runs on every barrier poll tick, and `this.messages` can be large.\n const messages = this.messages;\n let leaf: (typeof messages)[number] | undefined;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === \"assistant\") {\n leaf = messages[i];\n break;\n }\n }\n if (!leaf) return false;\n let hasPending = false;\n let hasSettled = false;\n for (const part of leaf.parts) {\n const record = part as Record<string, unknown>;\n const state = record.state;\n if (state === \"input-available\" || state === \"approval-requested\") {\n hasPending = true;\n } else if (\n typeof record.type === \"string\" &&\n (record.type.startsWith(\"tool-\") || record.type === \"dynamic-tool\") &&\n (state === \"output-available\" ||\n state === \"output-error\" ||\n state === \"output-denied\" ||\n state === \"approval-responded\")\n ) {\n hasSettled = true;\n }\n if (hasPending && hasSettled) return true;\n }\n return false;\n }\n\n private _fireAutoContinuation(connection: Connection): void {\n const pending = this._continuation.pending;\n if (!pending) return;\n\n // Cancel any still-armed coalesce timer so a sibling result that re-armed\n // it during a barrier wait can't fire a duplicate continuation after this\n // one starts (#1649).\n if (this._continuationTimer) {\n clearTimeout(this._continuationTimer);\n this._continuationTimer = null;\n }\n\n const { requestId, clientTools } = pending;\n const abortSignal = this._aborts.getSignal(requestId);\n\n this.keepAliveWhile(async () => {\n await this._turnQueue.enqueue(requestId, async () => {\n if (this._continuation.pending) {\n this._continuation.pending.pastCoalesce = true;\n }\n let streamed = false;\n try {\n const continuationBody = async () => {\n const result = await agentContext.run(\n {\n agent: this,\n connection,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n clientTools,\n body: this._lastBody,\n continuation: true\n })\n );\n if (result) {\n await this._streamResult(requestId, result, abortSignal, {\n continuation: true\n });\n streamed = true;\n }\n };\n\n if (this.chatRecovery) {\n await this._runChatRecoveryFiber(requestId, true, continuationBody);\n } else {\n await continuationBody();\n }\n } finally {\n this._aborts.remove(requestId);\n if (!streamed) {\n this._continuation.sendResumeNone();\n }\n this._continuation.clearPending();\n this._activateDeferredContinuation();\n }\n });\n }).catch((error) => {\n console.error(\"[Think] Auto-continuation failed:\", error);\n this._aborts.remove(requestId);\n });\n }\n\n private _activateDeferredContinuation(): void {\n const pending = this._continuation.activateDeferred(() =>\n crypto.randomUUID()\n );\n if (!pending) return;\n\n this._fireAutoContinuationWhenStable(pending.connection);\n }\n\n // ── Response hook ──────────────────────────────────────────────\n\n private async _fireResponseHook(result: ChatResponseResult): Promise<void> {\n // Record the terminal status durably so a client connecting after the turn\n // ended still learns its outcome (see `_buildIdleConnectMessages`).\n await this._recordTerminalChatStatus(\n result.status,\n result.requestId,\n result.error ?? \"The assistant was interrupted.\"\n );\n if (this._insideResponseHook) return;\n this._insideResponseHook = true;\n try {\n await this.onChatResponse(result);\n } catch (err) {\n console.error(\"[Think] onChatResponse error:\", err);\n } finally {\n this._insideResponseHook = false;\n }\n }\n\n /**\n * Persist (on `error`) or clear (on `completed`/`aborted`) a durable record of\n * the last terminal turn so it can be replayed to clients on connect. A\n * `completed`/`aborted` turn is conveyed by the persisted messages, so the\n * record is cleared; an `error`/`interrupted` turn has no durable trace\n * otherwise, so it is kept until a later turn resolves.\n */\n private async _recordTerminalChatStatus(\n status: ChatResponseResult[\"status\"] | \"interrupted\",\n requestId: string,\n body: string\n ): Promise<void> {\n if (status === \"error\" || status === \"interrupted\") {\n await this.ctx.storage.put(CHAT_LAST_TERMINAL_KEY, { requestId, body });\n } else {\n await this.ctx.storage.delete(CHAT_LAST_TERMINAL_KEY);\n }\n // Any terminal turn outcome resolves an in-progress recovery (#1620): a\n // recovered turn that completes, errors, or is exhausted must clear the\n // \"recovering…\" indicator so it never spins forever.\n await this._setChatRecovering(false);\n }\n\n private async _pendingTerminalChatResponse(): Promise<{\n requestId: string;\n body: string;\n } | null> {\n return (\n (await this.ctx.storage.get<{ requestId: string; body: string }>(\n CHAT_LAST_TERMINAL_KEY\n )) ?? null\n );\n }\n\n /**\n * Set or clear the live \"recovering…\" status for a durable chat turn (#1620).\n * Persists a durable record (replayed on connect via `_buildIdleConnectMessages`)\n * and broadcasts a `MSG_CHAT_RECOVERING` frame — but only on a genuine\n * transition, so a deploy/reconnect storm (which re-detects recovery many\n * times) doesn't spam the wire. Cleared on every terminal outcome so the\n * indicator can't spin forever.\n */\n private async _setChatRecovering(\n active: boolean,\n requestId?: string\n ): Promise<void> {\n const existing = await this.ctx.storage.get<{\n requestId?: string;\n at?: number;\n }>(CHAT_RECOVERING_KEY);\n // A record older than the max recovery window is stale: the owning incident\n // was abandoned without ever reaching a terminal (e.g. the DO went idle\n // before recovery could exhaust), so its terminal-clear never ran. Treat it\n // as not-recovering so a stuck record can neither pin the indicator \"on\"\n // forever nor suppress a genuinely-new recovering signal.\n const activeExisting =\n existing && Date.now() - (existing.at ?? 0) < CHAT_RECOVERY_MAX_WINDOW_MS;\n if (active) {\n if (activeExisting) return; // already recovering — idempotent, no re-broadcast\n await this.ctx.storage.put(CHAT_RECOVERING_KEY, {\n ...(requestId ? { requestId } : {}),\n at: Date.now()\n });\n } else {\n if (!existing) return; // not recovering — nothing to clear\n await this.ctx.storage.delete(CHAT_RECOVERING_KEY);\n requestId = requestId ?? existing.requestId;\n }\n this._broadcastChat({\n type: MSG_CHAT_RECOVERING,\n recovering: active,\n ...(requestId ? { id: requestId } : {})\n });\n }\n\n /**\n * Messages sent to a client on connect when no stream is active: the current\n * transcript, plus a replay of the last terminal error (if any) so a turn\n * that failed while the client was disconnected is surfaced rather than\n * silently frozen.\n */\n private async _buildIdleConnectMessages(): Promise<\n Array<Record<string, unknown>>\n > {\n const messages: Array<Record<string, unknown>> = [\n { type: MSG_CHAT_MESSAGES, messages: this.messages }\n ];\n const pending = await this._pendingTerminalChatResponse();\n if (pending) {\n messages.push({\n type: MSG_CHAT_RESPONSE,\n id: pending.requestId,\n body: pending.body,\n done: true,\n error: true\n });\n }\n // Replay an in-progress \"recovering…\" status so a client that connects\n // mid-recovery reads the turn as working rather than frozen (#1620). It's\n // mutually exclusive with `pending` (a terminal outcome clears recovering).\n // Skip a stale record (older than the max recovery window) so a turn whose\n // recovery was abandoned without a terminal can't show \"recovering…\"\n // forever on reconnect.\n const recovering = await this.ctx.storage.get<{\n requestId?: string;\n at?: number;\n }>(CHAT_RECOVERING_KEY);\n if (\n recovering &&\n Date.now() - (recovering.at ?? 0) < CHAT_RECOVERY_MAX_WINDOW_MS\n ) {\n messages.push({\n type: MSG_CHAT_RECOVERING,\n recovering: true,\n ...(recovering.requestId ? { id: recovering.requestId } : {})\n });\n }\n return messages;\n }\n\n // ── Resume helpers ──────────────────────────────────────────────\n\n private _notifyStreamResuming(connection: Connection): void {\n if (!this._resumableStream.hasActiveStream()) return;\n const sent = sendIfOpen(\n connection,\n JSON.stringify({\n type: MSG_STREAM_RESUMING,\n id: this._resumableStream.activeRequestId\n })\n );\n if (sent) {\n this._pendingResumeConnections.add(connection.id);\n }\n }\n\n private async _persistOrphanedStream(streamId: string): Promise<void> {\n this._resumableStream.flushBuffer();\n const chunks = this._resumableStream.getStreamChunks(streamId);\n if (chunks.length === 0) return;\n\n const accumulator = new StreamAccumulator({\n messageId: crypto.randomUUID()\n });\n for (const chunk of chunks) {\n try {\n accumulator.applyChunk(JSON.parse(chunk.body) as StreamChunkData);\n } catch {\n // skip malformed chunks\n }\n }\n\n if (accumulator.parts.length > 0) {\n await this._persistAssistantMessage(accumulator.toMessage());\n // NOTE: progress is bumped at production/flush time in `_storeChunkDurably`\n // (#1637), NOT here — persisting on recovery or a client reconnect must\n // not be miscounted as new forward progress.\n this._broadcastMessages();\n }\n }\n\n private _broadcastChat(message: Record<string, unknown>, exclude?: string[]) {\n const allExclusions = [\n ...(exclude || []),\n ...this._pendingResumeConnections\n ];\n this.broadcast(JSON.stringify(message), allExclusions);\n }\n\n private _broadcast(message: Record<string, unknown>, exclude?: string[]) {\n this.broadcast(JSON.stringify(message), exclude);\n }\n\n private _broadcastMessages(exclude?: string[]) {\n this._broadcast(\n { type: MSG_CHAT_MESSAGES, messages: this.messages },\n exclude\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;AA4HA,MAAM,wBAAwB,IAAI,YAAY;AAuD9C,MAAM,oBAAoB,mBAAmB;AAC7C,MAAM,oBAAoB,mBAAmB;AAC7C,MAAM,iBAAiB,mBAAmB;AAC1C,MAAM,sBAAsB,mBAAmB;AAC/C,MAAM,yBAAy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D;CAEA,MAAc,uBAAuB,UAAiC;EACpE,KAAK,iBAAiB,YAAY;EAClC,MAAM,SAAS,KAAK,iBAAiB,gBAAgB,QAAQ;EAC7D,IAAI,OAAO,WAAW,GAAG;EAEzB,MAAM,cAAc,IAAI,kBAAkB,EACxC,WAAW,OAAO,WAAW,EAC/B,CAAC;EACD,KAAK,MAAM,SAAS,QAClB,IAAI;GACF,YAAY,WAAW,KAAK,MAAM,MAAM,IAAI,CAAoB;EAClE,QAAQ,CAER;EAGF,IAAI,YAAY,MAAM,SAAS,GAAG;GAChC,MAAM,KAAK,yBAAyB,YAAY,UAAU,CAAC;GAI3D,KAAK,mBAAmB;EAC1B;CACF;CAEA,eAAuB,SAAkC,SAAoB;EAC3E,MAAM,gBAAgB,CACpB,GAAI,WAAW,CAAC,GAChB,GAAG,KAAK,yBACV;EACA,KAAK,UAAU,KAAK,UAAU,OAAO,GAAG,aAAa;CACvD;CAEA,WAAmB,SAAkC,SAAoB;EACvE,KAAK,UAAU,KAAK,UAAU,OAAO,GAAG,OAAO;CACjD;CAEA,mBAA2B,SAAoB;EAC7C,KAAK,WACH;GAAE,MAAM;GAAmB,UAAU,KAAK;EAAS,GACnD,OACF;CACF;AACF;AAjhPE,MAAwB,cAAc;CACpC;CACA;CACA;CACA;AACF;AA2BA,MAAgB,kBAAkB;AAmelC,MAAe,sBAAsB;AAiBrC,MAAiB,4BAA4B,MAAU"}
1
+ {"version":3,"file":"think.js","names":["Workspace","Session","agentContext"],"sources":["../src/think.ts"],"sourcesContent":["/**\n * Think — an opinionated chat agent base class.\n *\n * Works as both a **top-level agent** (speaking the `cf_agent_chat_*`\n * WebSocket protocol to browser clients) and a **sub-agent** (called\n * via `chat()` over RPC from a parent agent).\n *\n * Each instance gets its own SQLite storage backed by Session — providing\n * tree-structured messages, context blocks, compaction, FTS5 search, and\n * multi-session support.\n *\n * Configuration overrides:\n * - getModel() — return the LanguageModel to use\n * - getSystemPrompt() — return the system prompt (fallback when no context blocks)\n * - getTools() — return the ToolSet for the agentic loop\n * - maxSteps — max tool-call rounds per turn (default: 10)\n * - configureSession() — add context blocks, compaction, search, skills\n *\n * Lifecycle hooks:\n * - beforeTurn() — inspect/override context, tools, model before inference\n * - beforeStep() — per-step callback to override model, messages, tool selection\n * - beforeToolCall() — intercept tool calls (block, modify args, substitute result)\n * - afterToolCall() — inspect tool results after execution\n * - onStepFinish() — per-step callback (logging, analytics)\n * - onChunk() — per-chunk callback (streaming analytics)\n * - onChatResponse() — post-turn lifecycle hook (logging, chaining, analytics)\n * - onChatError() — customize error handling\n *\n * Production features:\n * - WebSocket chat protocol (compatible with useAgentChat / useChat)\n * - Sub-agent RPC streaming via StreamCallback\n * - Session-backed storage with tree-structured messages\n * - Context blocks with LLM-writable persistent memory\n * - Non-destructive compaction (summaries replace ranges at read time)\n * - FTS5 full-text search across conversation history\n * - Abort/cancel support via AbortRegistry\n * - Error handling with partial message persistence\n * - Message sanitization (strips OpenAI ephemeral metadata)\n * - Row size enforcement (compacts large tool outputs)\n * - Resumable streams (replay on reconnect)\n *\n * @experimental The API surface may change before stabilizing.\n *\n * @example\n * ```typescript\n * import { Think } from \"@cloudflare/think\";\n * import { createWorkersAI } from \"workers-ai-provider\";\n *\n * export class MyAgent extends Think<Env> {\n * getModel() {\n * return createWorkersAI({ binding: this.env.AI })(\"@cf/moonshotai/kimi-k2.6\");\n * }\n *\n * getSystemPrompt() {\n * return \"You are a helpful coding assistant.\";\n * }\n * }\n * ```\n *\n * @example With context blocks and self-updating memory\n * ```typescript\n * import { Think } from \"@cloudflare/think\";\n * import type { Session } from \"@cloudflare/think\";\n *\n * export class MemoryAgent extends Think<Env> {\n * getModel() { ... }\n *\n * configureSession(session: Session) {\n * return session\n * .withContext(\"soul\", {\n * provider: { get: async () => \"You are a helpful coding assistant.\" }\n * })\n * .withContext(\"memory\", {\n * description: \"Important facts learned during conversation.\",\n * maxTokens: 2000\n * })\n * .withCachedPrompt();\n * }\n * }\n * ```\n */\n\nimport type {\n LanguageModel,\n ModelMessage,\n PrepareStepFunction,\n PrepareStepResult,\n StreamTextOnChunkCallback,\n StreamTextOnStepFinishCallback,\n StreamTextOnToolCallFinishCallback,\n StopCondition,\n ToolSet,\n TypedToolCall,\n UIMessage\n} from \"ai\";\nimport {\n convertToModelMessages,\n jsonSchema,\n Output,\n stepCountIs,\n streamText\n} from \"ai\";\nimport * as skills from \"agents/skills\";\nimport { SkillRegistry } from \"agents/skills\";\nimport type { SkillScriptRunner, SkillSource } from \"agents/skills\";\n\n// Re-export AI SDK types that appear on Think's public lifecycle hooks\n// so users can import them from a single place.\nexport type {\n PrepareStepFunction,\n PrepareStepResult,\n StepResult,\n StopCondition,\n TextStreamPart,\n TypedToolCall,\n TypedToolResult\n} from \"ai\";\nexport { skills };\nexport type { SkillRunContext, SkillSource } from \"agents/skills\";\nimport {\n Agent,\n __DO_NOT_USE_WILL_BREAK__agentContext as agentContext\n} from \"agents\";\n\nconst agentToolChunkEncoder = new TextEncoder();\nimport type {\n Connection,\n FiberRecoveryContext,\n RetryOptions,\n WSMessage\n} from \"agents\";\nimport {\n sanitizeMessage,\n enforceRowSizeLimit,\n StreamAccumulator,\n CHAT_MESSAGE_TYPES,\n TurnQueue,\n ResumableStream,\n ContinuationState,\n SubmitConcurrencyController,\n createToolsFromClientSchemas,\n AbortRegistry,\n applyToolUpdate,\n toolResultUpdate,\n crossMessageToolResultUpdate,\n toolApprovalUpdate,\n parseProtocolMessage,\n applyChunkToParts,\n normalizeToolInput,\n reconcileMessages,\n resolveToolMergeId,\n createChatFiberSnapshot,\n unwrapChatFiberSnapshot,\n wrapChatFiberSnapshot\n} from \"agents/chat\";\nimport type {\n StreamChunkData,\n ClientToolSchema,\n MessagePart,\n SubmitConcurrencyDecision,\n ChatFiberSnapshot\n} from \"agents/chat\";\nimport { Session } from \"agents/experimental/memory/session\";\nimport { truncateOlderMessages } from \"agents/experimental/memory/utils\";\nimport { Workspace } from \"@cloudflare/shell\";\nimport { createWorkspaceTools } from \"./tools/workspace\";\nimport { ThinkMessengerRuntime } from \"./messengers/chat-sdk\";\nimport type {\n MessengerContext,\n ThinkMessengers,\n MessengerThinkHost\n} from \"./messengers\";\n\nexport { Session } from \"agents/experimental/memory/session\";\nexport { Workspace } from \"@cloudflare/shell\";\nexport type { FiberContext, FiberRecoveryContext } from \"agents\";\nexport type { WorkspaceLike } from \"./tools/workspace\";\nimport type { WorkspaceLike } from \"./tools/workspace\";\n\n// ── Wire protocol constants ────────────────────────────────────────\nconst MSG_CHAT_MESSAGES = CHAT_MESSAGE_TYPES.CHAT_MESSAGES;\nconst MSG_CHAT_RESPONSE = CHAT_MESSAGE_TYPES.USE_CHAT_RESPONSE;\nconst MSG_CHAT_CLEAR = CHAT_MESSAGE_TYPES.CHAT_CLEAR;\nconst MSG_STREAM_RESUMING = CHAT_MESSAGE_TYPES.STREAM_RESUMING;\nconst MSG_STREAM_RESUME_NONE = CHAT_MESSAGE_TYPES.STREAM_RESUME_NONE;\nconst MSG_MESSAGE_UPDATED = CHAT_MESSAGE_TYPES.MESSAGE_UPDATED;\nconst MSG_CHAT_RECOVERING = CHAT_MESSAGE_TYPES.CHAT_RECOVERING;\n\nfunction sendIfOpen(connection: Connection, message: string): boolean {\n try {\n connection.send(message);\n return true;\n } catch (error) {\n if (isWebSocketClosedSendError(error)) return false;\n throw error;\n }\n}\n\nfunction isWebSocketClosedSendError(error: unknown): boolean {\n return (\n error instanceof TypeError &&\n error.message.includes(\"WebSocket send() after close\")\n );\n}\n\nfunction shouldMarkSkippedAfterGenerationChange(\n status: SaveMessagesResult[\"status\"]\n): boolean {\n return status === \"completed\";\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== \"object\") {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return `[${value.map((item) => stableStringify(item)).join(\",\")}]`;\n }\n const record = value as Record<string, unknown>;\n return `{${Object.keys(record)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`)\n .join(\",\")}}`;\n}\n\nfunction stableHash(value: unknown): string {\n const input = stableStringify(value);\n let h1 = 1779033703;\n let h2 = 3144134277;\n let h3 = 1013904242;\n let h4 = 2773480762;\n for (let i = 0; i < input.length; i++) {\n const code = input.charCodeAt(i);\n h1 = h2 ^ Math.imul(h1 ^ code, 597399067);\n h2 = h3 ^ Math.imul(h2 ^ code, 2869860233);\n h3 = h4 ^ Math.imul(h3 ^ code, 951274213);\n h4 = h1 ^ Math.imul(h4 ^ code, 2716044179);\n }\n h1 = Math.imul(h3 ^ (h1 >>> 18), 597399067);\n h2 = Math.imul(h4 ^ (h2 >>> 22), 2869860233);\n h3 = Math.imul(h1 ^ (h3 >>> 17), 951274213);\n h4 = Math.imul(h2 ^ (h4 >>> 19), 2716044179);\n return [h1, h2, h3, h4]\n .map((part) => (part >>> 0).toString(16).padStart(8, \"0\"))\n .join(\"\");\n}\n\nfunction validateTimezone(timezone: string): string {\n try {\n const formatter = new Intl.DateTimeFormat(\"en-US\", { timeZone: timezone });\n return formatter.resolvedOptions().timeZone;\n } catch {\n throw new Error(`Invalid timezone \"${timezone}\"`);\n }\n}\n\nfunction parseTime(value: string): { hour: number; minute: number } {\n const match = /^([01]\\d|2[0-3]):([0-5]\\d)$/.exec(value);\n if (!match) {\n throw new Error(`Invalid schedule time \"${value}\"; expected HH:mm`);\n }\n return { hour: Number(match[1]), minute: Number(match[2]) };\n}\n\nconst declaredScheduleDayNumbers: Record<string, number> = {\n sun: 0,\n sunday: 0,\n mon: 1,\n monday: 1,\n tue: 2,\n tuesday: 2,\n wed: 3,\n wednesday: 3,\n thu: 4,\n thursday: 4,\n fri: 5,\n friday: 5,\n sat: 6,\n saturday: 6\n};\n\nfunction parseDeclaredTaskSchedule(\n rawSchedule: string,\n taskTimezone: string | undefined,\n defaultTimezone: string | undefined\n): ParsedDeclaredSchedule {\n const result = tryParseDeclaredTaskSchedule(\n rawSchedule,\n taskTimezone,\n defaultTimezone\n );\n if (!result.ok) throw new Error(result.error);\n return result.schedule;\n}\n\nfunction tryParseDeclaredTaskSchedule(\n rawSchedule: string,\n taskTimezone: string | undefined,\n defaultTimezone: string | undefined\n): ParseDeclaredScheduleResult {\n try {\n return {\n ok: true,\n schedule: parseDeclaredTaskScheduleUnchecked(\n rawSchedule,\n taskTimezone,\n defaultTimezone\n )\n };\n } catch (error) {\n return {\n ok: false,\n error: error instanceof Error ? error.message : String(error)\n };\n }\n}\n\nfunction parseDeclaredTaskScheduleUnchecked(\n rawSchedule: string,\n taskTimezone: string | undefined,\n defaultTimezone: string | undefined\n): ParsedDeclaredSchedule {\n const trimmed = rawSchedule.trim().replace(/\\s+/g, \" \").toLowerCase();\n const inlineTimezoneMatch = /^(.*) in ([A-Za-z_][A-Za-z0-9_+\\-/]*)$/.exec(\n trimmed\n );\n const schedule = inlineTimezoneMatch?.[1] ?? trimmed;\n const inlineTimezone = inlineTimezoneMatch?.[2];\n if (\n inlineTimezone &&\n taskTimezone &&\n validateTimezone(inlineTimezone) !== validateTimezone(taskTimezone)\n ) {\n throw new Error(\n `Schedule timezone \"${inlineTimezone}\" does not match task timezone \"${taskTimezone}\"`\n );\n }\n\n const intervalMatch = /^every ([1-9]\\d*) (minute|minutes|hour|hours)$/.exec(\n schedule\n );\n if (intervalMatch) {\n if (inlineTimezone || taskTimezone) {\n throw new Error(\"Interval schedules cannot specify a timezone\");\n }\n const count = Number(intervalMatch[1]);\n const unit = intervalMatch[2];\n if (count === 1 && unit.endsWith(\"s\")) {\n throw new Error(`Use singular unit for \"${rawSchedule}\"`);\n }\n if (count !== 1 && !unit.endsWith(\"s\")) {\n throw new Error(`Use plural unit for \"${rawSchedule}\"`);\n }\n return {\n kind: \"interval\",\n intervalMs: count * (unit.startsWith(\"hour\") ? 60 * 60_000 : 60_000),\n normalizedSchedule: `every ${count} ${unit}`\n };\n }\n\n const timezone = inlineTimezone ?? taskTimezone ?? defaultTimezone;\n if (!timezone) {\n throw new Error(\n `Wall-clock schedule \"${rawSchedule}\" requires a timezone or getDefaultTimezone()`\n );\n }\n const resolvedTimezone = validateTimezone(timezone);\n\n const dailyMatch = /^every day at ([0-2]\\d:[0-5]\\d)$/.exec(schedule);\n if (dailyMatch) {\n const { hour, minute } = parseTime(dailyMatch[1]);\n return {\n kind: \"wall-clock\",\n normalizedSchedule: `every day at ${dailyMatch[1]}`,\n timezone: resolvedTimezone,\n hour,\n minute,\n days: \"daily\"\n };\n }\n\n const weekdayMatch = /^every weekday at ([0-2]\\d:[0-5]\\d)$/.exec(schedule);\n if (weekdayMatch) {\n const { hour, minute } = parseTime(weekdayMatch[1]);\n return {\n kind: \"wall-clock\",\n normalizedSchedule: `every weekday at ${weekdayMatch[1]}`,\n timezone: resolvedTimezone,\n hour,\n minute,\n days: \"weekday\"\n };\n }\n\n const weeklyMatch = /^every week on ([a-z,\\s]+) at ([0-2]\\d:[0-5]\\d)$/.exec(\n schedule\n );\n if (weeklyMatch) {\n const seen = new Set<number>();\n const days = weeklyMatch[1].split(\",\").map((day) => {\n const normalized = day.trim();\n const dayNumber = declaredScheduleDayNumbers[normalized];\n if (dayNumber === undefined) {\n throw new Error(`Invalid schedule day \"${normalized}\"`);\n }\n if (seen.has(dayNumber)) {\n throw new Error(`Duplicate schedule day \"${normalized}\"`);\n }\n seen.add(dayNumber);\n return dayNumber;\n });\n if (days.length === 0) {\n throw new Error(\"Weekly schedule requires at least one day\");\n }\n const { hour, minute } = parseTime(weeklyMatch[2]);\n return {\n kind: \"wall-clock\",\n normalizedSchedule: `every week on ${weeklyMatch[1]\n .split(\",\")\n .map((day) => day.trim())\n .join(\",\")} at ${weeklyMatch[2]}`,\n timezone: resolvedTimezone,\n hour,\n minute,\n days\n };\n }\n\n throw new Error(`Unsupported schedule DSL \"${rawSchedule}\"`);\n}\n\nfunction getZonedParts(date: Date, timezone: string): ZonedParts {\n const parts = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: timezone,\n calendar: \"iso8601\",\n numberingSystem: \"latn\",\n weekday: \"short\",\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hourCycle: \"h23\"\n }).formatToParts(date);\n const part = (type: Intl.DateTimeFormatPartTypes) =>\n parts.find((entry) => entry.type === type)?.value ?? \"\";\n return {\n year: Number(part(\"year\")),\n month: Number(part(\"month\")),\n day: Number(part(\"day\")),\n hour: Number(part(\"hour\")),\n minute: Number(part(\"minute\")),\n second: Number(part(\"second\")),\n weekday: [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"].indexOf(\n part(\"weekday\")\n )\n };\n}\n\nfunction compareLocalParts(\n left: Pick<ZonedParts, \"year\" | \"month\" | \"day\" | \"hour\" | \"minute\">,\n right: Pick<ZonedParts, \"year\" | \"month\" | \"day\" | \"hour\" | \"minute\">\n): number {\n const fields = [\"year\", \"month\", \"day\", \"hour\", \"minute\"] as const;\n for (const field of fields) {\n const diff = left[field] - right[field];\n if (diff !== 0) return diff;\n }\n return 0;\n}\n\nfunction findZonedInstant(\n target: Pick<ZonedParts, \"year\" | \"month\" | \"day\" | \"hour\" | \"minute\">,\n timezone: string\n): Date {\n const approximate = Date.UTC(\n target.year,\n target.month - 1,\n target.day,\n target.hour,\n target.minute\n );\n const start = approximate - 14 * 60 * 60_000;\n const end = approximate + 14 * 60 * 60_000;\n for (let time = start; time <= end; time += 60_000) {\n const candidate = new Date(time);\n const parts = getZonedParts(candidate, timezone);\n if (compareLocalParts(parts, target) === 0) return candidate;\n }\n for (let time = start; time <= end; time += 60_000) {\n const candidate = new Date(time);\n const parts = getZonedParts(candidate, timezone);\n if (compareLocalParts(parts, target) > 0) return candidate;\n }\n throw new Error(`Unable to resolve local time in timezone \"${timezone}\"`);\n}\n\nfunction addLocalDays(\n parts: Pick<ZonedParts, \"year\" | \"month\" | \"day\">,\n days: number\n): Pick<ZonedParts, \"year\" | \"month\" | \"day\"> {\n const date = new Date(\n Date.UTC(parts.year, parts.month - 1, parts.day + days)\n );\n return {\n year: date.getUTCFullYear(),\n month: date.getUTCMonth() + 1,\n day: date.getUTCDate()\n };\n}\n\nfunction isAllowedWallClockDay(\n weekday: number,\n days: ParsedDeclaredSchedule & { kind: \"wall-clock\" }\n): boolean {\n if (days.days === \"daily\") return true;\n if (days.days === \"weekday\") return weekday >= 1 && weekday <= 5;\n return days.days.includes(weekday);\n}\n\nfunction nextDeclaredScheduleTime(\n schedule: ParsedDeclaredSchedule,\n now: Date,\n previousScheduledFor?: number\n): Date {\n if (schedule.kind === \"interval\") {\n let next =\n previousScheduledFor === undefined\n ? now.getTime() + schedule.intervalMs\n : previousScheduledFor + schedule.intervalMs;\n while (next <= now.getTime()) next += schedule.intervalMs;\n return new Date(next);\n }\n\n const nowParts = getZonedParts(now, schedule.timezone);\n for (let offset = 0; offset < 370; offset++) {\n const localDate = addLocalDays(nowParts, offset);\n const candidate = findZonedInstant(\n {\n ...localDate,\n hour: schedule.hour,\n minute: schedule.minute\n },\n schedule.timezone\n );\n const weekday = getZonedParts(candidate, schedule.timezone).weekday;\n if (!isAllowedWallClockDay(weekday, schedule)) continue;\n if (candidate.getTime() > now.getTime()) return candidate;\n }\n throw new Error(\"Unable to compute next scheduled task occurrence\");\n}\n\ntype StreamResultStatus = {\n status: Exclude<SaveMessagesResult[\"status\"], \"skipped\">;\n error?: string;\n output?: unknown;\n};\n\ntype ProgrammaticMessagesResult = SaveMessagesResult & {\n output?: unknown;\n};\n\ntype ChatRecoveryRetryData = {\n targetUserId?: string;\n originalRequestId?: string;\n incidentId?: string;\n lastBody?: Record<string, unknown> | null;\n lastClientTools?: ClientToolSchema[] | null;\n recoveredRequestId?: string;\n};\n\ntype ChatRecoveryContinueData = {\n targetAssistantId?: string;\n originalRequestId?: string;\n incidentId?: string;\n lastBody?: Record<string, unknown> | null;\n lastClientTools?: ClientToolSchema[] | null;\n recoveredRequestId?: string;\n};\n\n/**\n * Thrown by `_iterateWithStallWatchdog` when the inactivity watchdog fires\n * (a model/transport stream that parks without ever throwing). Distinct from\n * in-band model/stream errors so the read-loop catch can route a stall into\n * bounded recovery (#1626) — a transient hang is retried within the existing\n * recovery budget — while genuine errors stay terminal.\n */\nclass ChatStreamStalledError extends Error {\n readonly isChatStreamStall = true;\n constructor(message: string) {\n super(message);\n this.name = \"ChatStreamStalledError\";\n }\n}\n\ntype ChatRecoveryKind = \"retry\" | \"continue\";\n\ntype ChatRecoveryIncident = {\n incidentId: string;\n requestId: string;\n /**\n * Stable root requestId for the whole continuation chain. The durable\n * submission is keyed by this (not the per-attempt `requestId`, which is\n * overwritten each continuation), so terminal paths must use it to mark the\n * submission. Optional for backward-compat with incidents persisted before\n * this field existed — fall back to `requestId`.\n */\n recoveryRootRequestId?: string;\n recoveryKind: ChatRecoveryKind;\n attempt: number;\n maxAttempts: number;\n status:\n | \"detected\"\n | \"scheduled\"\n | \"attempting\"\n | \"completed\"\n | \"skipped\"\n | \"exhausted\"\n | \"failed\";\n firstSeenAt: number;\n lastAttemptAt: number;\n /**\n * Epoch ms of the last attempt that observed forward progress. The recovery\n * budget is keyed to this (`now - lastProgressAt > NO_PROGRESS_WINDOW`), so a\n * turn that keeps producing content survives churn indefinitely while a\n * genuinely stuck turn is sealed within the window (#1637). Optional for\n * backward-compat — falls back to `firstSeenAt`.\n */\n lastProgressAt?: number;\n reason?: string;\n /**\n * High-water mark of the durable, monotonic recovery-progress counter (see\n * `_chatRecoveryProgressMarker`) observed for this incident. Used to\n * distinguish a turn that is making forward progress but keeps getting\n * interrupted by isolate resets (deploys) — which should NOT exhaust the\n * budget — from one that genuinely fails to advance. Sourced from a persisted\n * counter rather than the live transcript so compaction cannot lower it\n * (#1628).\n */\n progress?: number;\n};\n\nconst CHAT_RECOVERY_INCIDENT_KEY_PREFIX = \"cf:chat-recovery:incident:\";\n// Durable, monotonic forward-progress counter for recovery budget resets.\n// Bumped on each durable content flush (`_storeChunkDurably`) — production time,\n// so it reflects genuinely new content and is immune to reconnects/re-persists;\n// never recomputed from the (compactable) transcript. See\n// `_chatRecoveryProgressMarker`.\nconst CHAT_RECOVERY_PROGRESS_KEY = \"cf:chat-recovery:progress\";\n// Secondary backstop only. The primary recovery bound is the no-progress\n// wall clock below; with alarm debounce this cap rarely binds (it catches a\n// pathological tight alarm-loop). Kept high so the no-progress window seals\n// first under normal deploy cadence (#1637).\nconst DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS = 10;\nconst DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS = 10_000;\n// Auto-continuation barrier (#1649 / #1650): when the model emits parallel tool\n// calls, the client answers each one independently and sends a `tool-result`\n// with `autoContinue` per result. A fast tool's result must NOT trigger\n// inference while a slower sibling is still `input-available` — doing so feeds\n// the provider an incomplete tool-result set (MissingToolResultsError) or, with\n// the transcript-repair backstop, silently flips the in-flight sibling to\n// errored and runs a spurious extra continuation. So we hold the continuation\n// until the step's batch settles (no `input-available`/`approval-requested`\n// siblings).\n//\n// The barrier is event-driven (#1650): auto-continuation is only ever triggered\n// by a tool-result/approval event, so instead of waiting on a fixed timer we\n// drain the in-flight applies, re-check, and — if a sibling is still unanswered\n// — simply return, leaving the pending continuation in place. The next sibling's\n// result re-arms the coalesce timer (or, after eviction, re-creates the pending\n// state from the persisted transcript) and re-runs the check; the continuation\n// fires once the final sibling lands. This means a legitimately slow answer (a\n// human-in-the-loop tool with no `execute`, an unbounded RPC) never fires\n// through to a spurious error, and a true orphan (a sibling that never arrives)\n// simply never auto-continues — the isolate is not pinned waiting for it.\n// Delay before retrying a continuation that timed out waiting for stable state.\n// Gives an actively-churning isolate (e.g. a deploy in flight) time to settle.\nconst CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS = 3;\nconst DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE =\n \"The assistant was interrupted and could not recover. Please try again.\";\n// Incidents that have not seen a new attempt within this window are assumed\n// abandoned and swept so durable storage does not grow without bound.\nconst CHAT_RECOVERY_INCIDENT_TTL_MS = 60 * 60 * 1000;\n// PRIMARY recovery bound (#1637): seal an incident that has made no forward\n// progress for this long. Keyed to `lastProgressAt`, which resets on every\n// progress-bearing attempt — so a turn that keeps producing content survives\n// deploy churn indefinitely, while a genuinely stuck turn dies within 5 min.\nconst CHAT_RECOVERY_NO_PROGRESS_WINDOW_MS = 5 * 60 * 1000;\n// Alarm debounce: recovery alarms bunched within this window collapse into a\n// single attempt. A deploy rollout drops/reconnects the socket several times\n// over ~11–22s; without this, one logical deploy would burn several attempts.\nconst CHAT_RECOVERY_ALARM_DEBOUNCE_MS = 30 * 1000;\n// ABSOLUTE ceiling for a single recovery incident, keyed to `firstSeenAt` and\n// NEVER reset by progress — the final hard stop so even a degenerate\n// slowly-progressing loop cannot run forever.\nconst CHAT_RECOVERY_MAX_WINDOW_MS = 15 * 60 * 1000;\n// N9: while a parent re-attaches to and forwards a sub-agent's stream, credit\n// the parent's recovery progress at most this often. The marker only needs to\n// advance ≥once between recovery attempts (the no-progress window is minutes),\n// so this caps storage writes during high-rate child streaming. The throttle\n// state is in-memory (reset per isolate), so the first forwarded chunk after\n// ANY restart always bumps — guaranteeing every recovery attempt that observes\n// child output registers forward progress.\nconst AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS = 5_000;\n\n// Ephemeral user message appended when a model request would otherwise end in\n// an assistant message (see `ensureValidContinueCheckpoint`).\nconst CONTINUE_CHECKPOINT_PROMPT =\n \"Continue your previous response from exactly where it left off. Do not repeat any of it.\";\n\n/**\n * Ensure a model request does not end in an assistant message.\n *\n * Continuing a partial assistant turn (e.g. after a deploy interrupts a stream)\n * replays a transcript whose final message is that partial assistant message —\n * an \"assistant prefill\". Modern chat models reject this: Anthropic Claude 4.6+\n * returns a 400 (\"This model does not support assistant message prefill. The\n * conversation must end with a user message.\"). To reach a valid continue\n * checkpoint across providers we append an ephemeral user message. This shapes\n * only the model request; it is never persisted to the transcript.\n */\nfunction ensureValidContinueCheckpoint(\n messages: ModelMessage[]\n): ModelMessage[] {\n if (messages.length === 0) return messages;\n if (messages[messages.length - 1]?.role !== \"assistant\") return messages;\n return [...messages, { role: \"user\", content: CONTINUE_CHECKPOINT_PROMPT }];\n}\n\n// Durable record of the last turn that ended in a terminal error / abandoned\n// recovery. Replayed to clients on connect so a turn that failed while they\n// were disconnected (e.g. during a deploy/WS reconnect storm) is not silently\n// frozen — the terminal `MSG_CHAT_RESPONSE` broadcast is otherwise transient.\nconst CHAT_LAST_TERMINAL_KEY = \"cf:chat:last-terminal\";\n\n// Durable record of an in-progress durable recovery, so a \"recovering…\" status\n// can be broadcast live AND replayed to a client that connects mid-recovery\n// (#1620). Set when a recovery continuation/retry is scheduled; cleared on every\n// terminal outcome (completed/skipped/failed/exhausted) so the indicator can't\n// spin forever.\nconst CHAT_RECOVERING_KEY = \"cf:chat:recovering\";\n\n/**\n * Callback interface for streaming chat events from a Think sub-agent.\n *\n * Designed to work across the sub-agent RPC boundary — implement as\n * an RpcTarget in the parent agent and pass to `chat()`.\n */\nexport interface ChatStartEvent {\n requestId: string;\n}\n\nexport interface StreamCallback {\n onStart(event: ChatStartEvent): void | Promise<void>;\n onEvent(json: string): void | Promise<void>;\n onDone(): void | Promise<void>;\n onError(error: string): void | Promise<void>;\n /**\n * The current attempt was interrupted (a stream-stall watchdog abort routed\n * into bounded recovery, #1626) and its final outcome will NOT arrive through\n * this callback. One of two things is true:\n * - a scheduled continuation — running in a LATER isolate invocation, without\n * this callback — will produce the answer (delivered to other channels,\n * e.g. WebSocket connections), OR\n * - the recovery budget was exhausted, so the turn was already terminalized\n * out-of-band (the configured `terminalMessage` + `onExhausted`) and is\n * terminally over — there is NO continuation to come.\n *\n * This is NOT `onDone` (this attempt did not complete) and NOT `onError` (the\n * raw stall is not surfaced as a terminal error here); without it the contract\n * `onStart → onEvent* → (onDone | onError)` is silently abandoned and a\n * consumer that treats the clean resolve as success finalizes a truncated\n * partial.\n *\n * Consumers should AVOID finalizing the partial on this signal — surface a\n * \"recovering…\" / \"interrupted, please retry\" state, or re-attach via a\n * durable channel — but must ALSO NOT block indefinitely waiting for a\n * continuation: per the exhausted case above, one may never come. Optional →\n * defaults to a no-op, so this is fully backward-compatible.\n *\n * Note: a deploy/eviction interruption kills the isolate (and this callback)\n * before this can fire — the caller observes a transport break instead. This\n * fires only for an in-isolate interruption (the stall→recovery path).\n */\n onInterrupted?(): void | Promise<void>;\n}\n\n/**\n * Minimal interface for the result of the inference loop.\n * The AI SDK's `streamText()` result satisfies this interface.\n */\nexport interface StreamableResult {\n toUIMessageStream(options?: {\n sendReasoning?: boolean;\n }): AsyncIterable<unknown>;\n output?: PromiseLike<unknown>;\n}\n\n/**\n * Options for a chat turn (sub-agent RPC entry point).\n */\nexport interface ChatOptions {\n signal?: AbortSignal;\n}\n\ntype AgentToolChildRunStatus =\n | \"starting\"\n | \"running\"\n | \"completed\"\n | \"error\"\n | \"aborted\";\n\ntype AgentToolChildRunRow = {\n run_id: string;\n request_id: string | null;\n stream_id: string | null;\n status: AgentToolChildRunStatus;\n summary: string | null;\n output_json: string | null;\n error_message: string | null;\n started_at: number;\n completed_at: number | null;\n};\n\ntype AgentToolRunInspection<Output = unknown> = {\n runId: string;\n status: AgentToolChildRunStatus;\n requestId?: string;\n streamId?: string;\n output?: Output;\n summary?: string;\n error?: string;\n startedAt: number;\n completedAt?: number;\n};\n\ntype Digit = \"0\" | \"1\" | \"2\" | \"3\" | \"4\" | \"5\" | \"6\" | \"7\" | \"8\" | \"9\";\ntype Hour = `0${Digit}` | `1${Digit}` | \"20\" | \"21\" | \"22\" | \"23\";\ntype Minute = `${\"0\" | \"1\" | \"2\" | \"3\" | \"4\" | \"5\"}${Digit}`;\nexport type ThinkTime = `${Hour}:${Minute}`;\nexport type ThinkIntervalSchedule =\n | `every ${number} minute${\"\" | \"s\"}`\n | `every ${number} hour${\"\" | \"s\"}`;\nexport type ThinkWallClockSchedule =\n | `every day at ${ThinkTime}`\n | `every weekday at ${ThinkTime}`\n | `every week on ${string} at ${ThinkTime}`;\nexport type ThinkScheduledTaskSchedule =\n | ThinkIntervalSchedule\n | ThinkWallClockSchedule\n | `${ThinkWallClockSchedule} in ${string}`;\n\nexport type ThinkScheduledTaskContext = {\n taskId: string;\n scheduledFor: number;\n scheduledForDate: Date;\n occurrenceKey: string;\n idempotencyKey: string;\n schedule: string;\n scheduleKind: \"interval\" | \"wall-clock\";\n timezone?: string;\n metadata?: Record<string, unknown>;\n};\n\ntype ThinkScheduledTaskPromptAction = {\n prompt: string | (() => string | Promise<string>);\n handler?: never;\n};\n\ntype ThinkScheduledTaskHandlerAction = {\n handler: (ctx: ThinkScheduledTaskContext) => void | Promise<void>;\n prompt?: never;\n};\n\ntype ThinkScheduledTaskBase = (\n | ThinkScheduledTaskPromptAction\n | ThinkScheduledTaskHandlerAction\n) & {\n retry?: RetryOptions;\n metadata?: Record<string, unknown>;\n};\n\nexport type ThinkScheduledTask =\n | (ThinkScheduledTaskBase & {\n schedule: ThinkIntervalSchedule;\n timezone?: never;\n })\n | (ThinkScheduledTaskBase & {\n schedule: ThinkWallClockSchedule;\n timezone?: string;\n })\n | (ThinkScheduledTaskBase & {\n schedule: `${ThinkWallClockSchedule} in ${string}`;\n timezone?: string;\n });\n\nexport type ThinkScheduledTasks = Record<string, ThinkScheduledTask>;\n\nexport function defineScheduledTasks<const T extends ThinkScheduledTasks>(\n tasks: T\n): T {\n return tasks;\n}\n\ntype ParsedDeclaredSchedule =\n | {\n kind: \"interval\";\n intervalMs: number;\n normalizedSchedule: string;\n }\n | {\n kind: \"wall-clock\";\n normalizedSchedule: string;\n timezone: string;\n hour: number;\n minute: number;\n days: \"daily\" | \"weekday\" | number[];\n };\n\ntype ParseDeclaredScheduleResult =\n | { ok: true; schedule: ParsedDeclaredSchedule }\n | { ok: false; error: string };\n\ntype NormalizedDeclaredTask = {\n taskId: string;\n prompt?: ThinkScheduledTaskPromptAction[\"prompt\"];\n handler?: ThinkScheduledTaskHandlerAction[\"handler\"];\n schedule: ParsedDeclaredSchedule;\n retry?: RetryOptions;\n metadata?: Record<string, unknown>;\n scheduleHash: string;\n taskHash: string;\n};\n\ntype DeclaredScheduledTaskRow = {\n owner_key: string;\n task_id: string;\n schedule_hash: string;\n task_hash: string;\n schedule_id: string | null;\n next_run_at: number | null;\n created_at: number;\n updated_at: number;\n};\n\ntype DeclaredScheduledTaskPayload = {\n taskId: string;\n scheduleHash: string;\n scheduledFor: number;\n};\n\ntype ZonedParts = {\n year: number;\n month: number;\n day: number;\n hour: number;\n minute: number;\n second: number;\n weekday: number;\n};\n\ntype AgentToolStoredChunk = {\n sequence: number;\n body: string;\n};\n\nexport type ThinkSubmissionStatus =\n | \"pending\"\n | \"running\"\n | \"completed\"\n | \"aborted\"\n | \"skipped\"\n | \"error\";\n\nexport type SubmitMessagesOptions = {\n submissionId?: string;\n idempotencyKey?: string;\n metadata?: Record<string, unknown>;\n};\n\ntype ThinkWorkflowPromptContext = {\n workflow: {\n name: string;\n id: string;\n stepName: string;\n eventType: string;\n };\n output?: {\n schema: unknown;\n };\n fingerprint?: string;\n};\n\nconst THINK_WORKFLOW_PROMPT_METADATA_KEY = \"__thinkWorkflowPrompt\";\n\nexport type ThinkSubmissionInspection = {\n submissionId: string;\n idempotencyKey?: string;\n requestId?: string;\n status: ThinkSubmissionStatus;\n error?: string;\n metadata?: Record<string, unknown>;\n createdAt: number;\n startedAt?: number;\n completedAt?: number;\n};\n\nexport type SubmitMessagesResult = ThinkSubmissionInspection & {\n accepted: boolean;\n};\n\nexport type ListSubmissionsOptions = {\n status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];\n limit?: number;\n};\n\nexport type DeleteSubmissionsOptions = {\n status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];\n completedBefore?: Date;\n limit?: number;\n};\n\ntype ThinkSubmissionRow = {\n submission_id: string;\n idempotency_key: string | null;\n request_id: string | null;\n stream_id: string | null;\n status: ThinkSubmissionStatus;\n messages_json: string;\n metadata_json: string | null;\n error_message: string | null;\n created_at: number;\n messages_applied_at: number | null;\n started_at: number | null;\n completed_at: number | null;\n};\n\ntype ThinkWorkflowNotificationRow = {\n notification_id: string;\n submission_id: string;\n workflow_name: string;\n workflow_id: string;\n event_type: string;\n payload_json: string;\n attempts: number;\n last_error: string | null;\n created_at: number;\n updated_at: number;\n delivered_at: number | null;\n};\n\n// Lifecycle / result types are shared with `@cloudflare/ai-chat` via\n// `agents/chat`. Re-exported from Think so subclasses can import them\n// from `@cloudflare/think` directly.\nexport type {\n ChatResponseResult,\n ChatRecoveryConfig,\n ChatRecoveryContext,\n ChatRecoveryExhaustedContext,\n ChatRecoveryOptions,\n MessageConcurrency,\n ResolvedChatRecoveryConfig,\n SaveMessagesOptions,\n SaveMessagesResult\n} from \"agents/chat\";\nimport type {\n ChatResponseResult,\n ChatRecoveryConfig,\n ChatRecoveryContext,\n ChatRecoveryExhaustedContext,\n ChatRecoveryOptions,\n MessageConcurrency,\n ResolvedChatRecoveryConfig,\n SaveMessagesOptions,\n SaveMessagesResult\n} from \"agents/chat\";\n\n// ── Lifecycle hook types ────────────────────────────────────────\n\n/**\n * A chat turn request. Built automatically by each entry path\n * (WebSocket, chat(), saveMessages, auto-continuation) and passed\n * to Think's inference loop.\n */\nexport interface TurnInput {\n signal?: AbortSignal;\n /** Client-provided tool schemas for dynamic tool registration. */\n clientTools?: ClientToolSchema[];\n /** Custom body fields from the client request. */\n body?: Record<string, unknown>;\n /** Internal workflow prompt configuration, never sourced from client body. */\n workflowPrompt?: ThinkWorkflowPromptContext;\n /** Whether this is a continuation turn (auto-continue after tool result, recovery). */\n continuation: boolean;\n}\n\n/**\n * Context passed to the `beforeTurn` hook.\n * Contains everything Think assembled — the hook can inspect and override.\n */\nexport interface TurnContext {\n /** Assembled system prompt (from context blocks or getSystemPrompt fallback). */\n system: string;\n /** Assembled model messages (truncated, pruned). */\n messages: ModelMessage[];\n /** Merged tool set (workspace + getTools + session + MCP + client + caller). */\n tools: ToolSet;\n /** The language model from getModel(). */\n model: LanguageModel;\n /** Whether this is a continuation turn. */\n continuation: boolean;\n /** Custom body fields from the client request. */\n body?: Record<string, unknown>;\n}\n\n/**\n * Configuration returned by the `beforeTurn` hook to override defaults.\n * All fields are optional — return only what you want to change.\n */\nexport interface TurnConfig {\n /** Override the model for this turn (e.g. cheap model for continuations). */\n model?: LanguageModel;\n /** Override the assembled system prompt. */\n system?: string;\n /** Override the assembled messages. */\n messages?: ModelMessage[];\n /** Extra tools to merge (additive — spread on top of existing tools). */\n tools?: ToolSet;\n /** Limit which tools the model can call (AI SDK activeTools). */\n activeTools?: string[];\n /** Force a specific tool call (AI SDK toolChoice). */\n toolChoice?: Parameters<typeof streamText>[0][\"toolChoice\"];\n /** Override maxSteps for this turn. */\n maxSteps?: number;\n /**\n * Additional AI SDK stop conditions for ending the turn early.\n * Think always keeps its `maxSteps` stop condition as a safety bound.\n */\n stopWhen?: StopCondition<ToolSet> | Array<StopCondition<ToolSet>>;\n /**\n * Controls whether reasoning chunks are included in the UI message stream\n * for this turn. Defaults to the instance-level `sendReasoning` setting.\n */\n sendReasoning?: boolean;\n /**\n * Override the stream-stall inactivity watchdog timeout for THIS turn only\n * (ms; `0` disables it for this turn). Defaults to the instance-level\n * `chatStreamStallTimeoutMs`. Because the watchdog measures the gap between\n * UI-message-stream chunks — which includes server-side tool execution — a\n * turn known to invoke a slow tool can raise (or disable) the timeout for\n * just that turn instead of permanently widening the global window. Auto-\n * resets after the turn.\n */\n chatStreamStallTimeoutMs?: number;\n /** Maximum number of tokens to generate for this turn. */\n maxOutputTokens?: Parameters<typeof streamText>[0][\"maxOutputTokens\"];\n /** Temperature setting for this turn. */\n temperature?: Parameters<typeof streamText>[0][\"temperature\"];\n /** Nucleus sampling setting for this turn. */\n topP?: Parameters<typeof streamText>[0][\"topP\"];\n /** Top-K sampling setting for this turn. */\n topK?: Parameters<typeof streamText>[0][\"topK\"];\n /** Presence penalty setting for this turn. */\n presencePenalty?: Parameters<typeof streamText>[0][\"presencePenalty\"];\n /** Frequency penalty setting for this turn. */\n frequencyPenalty?: Parameters<typeof streamText>[0][\"frequencyPenalty\"];\n /** Stop sequences for this turn. */\n stopSequences?: Parameters<typeof streamText>[0][\"stopSequences\"];\n /** Seed for deterministic sampling when supported by the model. */\n seed?: Parameters<typeof streamText>[0][\"seed\"];\n /** Maximum number of retries for this turn. Set to 0 to disable retries. */\n maxRetries?: Parameters<typeof streamText>[0][\"maxRetries\"];\n /** Timeout configuration for this turn. */\n timeout?: Parameters<typeof streamText>[0][\"timeout\"];\n /** Additional HTTP headers for provider requests on this turn. */\n headers?: Parameters<typeof streamText>[0][\"headers\"];\n /** Provider-specific options (AI SDK providerOptions). */\n providerOptions?: Record<string, unknown>;\n /** Optional AI SDK telemetry configuration for this turn. */\n experimental_telemetry?: Parameters<\n typeof streamText\n >[0][\"experimental_telemetry\"];\n /**\n * Optional structured-output specification (AI SDK `output`).\n * Forwarded to `streamText` so the model's final response is parsed\n * against the supplied schema. Use the AI SDK's `Output.object({ schema })`\n * / `Output.text()` helpers. Combine with `activeTools: []` on the\n * terminal turn if your provider strips tools when structured output\n * is active (e.g. workers-ai-provider).\n */\n output?: Parameters<typeof streamText>[0][\"output\"];\n}\n\nexport interface ChatErrorContext {\n requestId?: string;\n stage: \"parse\" | \"persist\" | \"turn\" | \"stream\" | \"recovery\" | \"transcript\";\n messagesPersisted?: boolean;\n}\n\n/**\n * Context passed to the `beforeStep` hook before each AI SDK step in\n * the agentic loop. Backed by the AI SDK's `PrepareStepFunction<TOOLS>`\n * parameter — exposes the previous `steps`, the zero-based `stepNumber`,\n * the currently selected `model`, the `messages` about to be sent, and\n * `experimental_context`.\n *\n * Pass an explicit `TOOLS` generic for typed previous tool calls / results.\n *\n * Limitations (AI SDK boundary, not Think):\n * - No `abortSignal` is exposed in the context. If you do remote work\n * inside `beforeStep`, it cannot be cancelled by turn-level abort.\n * - `experimental_context` is typed `unknown`; users must narrow it.\n * - `output` cannot be overridden per-step — set it at the turn level\n * via `TurnConfig.output` (returned from `beforeTurn`).\n */\nexport type PrepareStepContext<TOOLS extends ToolSet = ToolSet> = Parameters<\n PrepareStepFunction<TOOLS>\n>[0];\n\n/**\n * Configuration returned by `beforeStep` to override defaults for the\n * current AI SDK step. This is the AI SDK's `PrepareStepResult<TOOLS>` —\n * return only the fields you want to override (`model`, `toolChoice`,\n * `activeTools`, `system`, `messages`, `experimental_context`,\n * `providerOptions`).\n */\nexport type StepConfig<TOOLS extends ToolSet = ToolSet> =\n PrepareStepResult<TOOLS>;\n\n/**\n * Context passed to the `beforeToolCall` hook **before** the tool's\n * `execute` function runs.\n *\n * Backed by the AI SDK's `OnToolCallStartEvent` (the parameter of\n * `experimental_onToolCallStart`). The full `TypedToolCall<TOOLS>`\n * fields (`toolName`, `toolCallId`, `input`, `providerMetadata`, the\n * dynamic/invalid/error discriminators) are spread at the top level for\n * convenience, with the per-call event extras attached:\n *\n * - `stepNumber` — index of the current step\n * - `messages` — conversation messages visible at tool execution time\n * - `abortSignal` — signal that aborts if the turn is cancelled\n *\n * Pass an explicit `TOOLS` generic for full input typing:\n *\n * ```ts\n * import type { ToolCallContext } from \"@cloudflare/think\";\n * import type { tools } from \"./my-tools\";\n *\n * beforeToolCall(ctx: ToolCallContext<typeof tools>) {\n * if (ctx.toolName === \"search\") {\n * ctx.input.query; // typed\n * }\n * }\n * ```\n */\nexport type ToolCallContext<TOOLS extends ToolSet = ToolSet> =\n TypedToolCall<TOOLS> & {\n /** Zero-based index of the current step where this tool call occurs. */\n readonly stepNumber: number | undefined;\n /** The conversation messages available at tool execution time. */\n readonly messages: ReadonlyArray<ModelMessage>;\n /** Signal for cancelling the operation. */\n readonly abortSignal: AbortSignal | undefined;\n };\n\n/**\n * Decision returned by `beforeToolCall` to control tool execution.\n * Return void/undefined to allow execution with original input.\n *\n * Discriminated union — each action has a clear, non-overlapping meaning:\n * - `allow` — execute the tool (optionally with modified input)\n * - `block` — don't execute; return `reason` as the tool result so the model can adjust\n * - `substitute` — don't execute; return `output` as the tool result (afterToolCall still fires)\n */\nexport type ToolCallDecision =\n | {\n action: \"allow\";\n /** Modified input — tool executes with this instead of the original. */\n input?: Record<string, unknown>;\n }\n | {\n action: \"block\";\n /** Returned as the tool result so the model can adjust. */\n reason?: string;\n }\n | {\n action: \"substitute\";\n /** The substitute tool output — model sees this instead of real execution. */\n output: unknown;\n /** Optional input attribution for the afterToolCall log. */\n input?: Record<string, unknown>;\n };\n\n/**\n * Context passed to the `afterToolCall` hook after a tool executes.\n *\n * Backed by the AI SDK's `OnToolCallFinishEvent` (the parameter of\n * `experimental_onToolCallFinish`). The full `TypedToolCall<TOOLS>`\n * fields (`toolName`, `toolCallId`, `input`, …) are spread at the top\n * level, plus the per-call event extras:\n *\n * - `stepNumber` — index of the current step\n * - `messages` — conversation messages visible at tool execution time\n * - `durationMs` — wall-clock execution time in milliseconds\n * - `success`/`output`/`error` — discriminated outcome:\n * - on success: `success: true`, `output: unknown`\n * - on failure: `success: false`, `error: unknown`\n *\n * Pass an explicit `TOOLS` generic for full input typing:\n *\n * ```ts\n * import type { ToolCallResultContext } from \"@cloudflare/think\";\n * import type { tools } from \"./my-tools\";\n *\n * afterToolCall(ctx: ToolCallResultContext<typeof tools>) {\n * if (ctx.success) {\n * console.log(`${ctx.toolName} took ${ctx.durationMs}ms`, ctx.output);\n * } else {\n * console.error(`${ctx.toolName} failed:`, ctx.error);\n * }\n * }\n * ```\n */\nexport type ToolCallResultContext<TOOLS extends ToolSet = ToolSet> =\n TypedToolCall<TOOLS> & {\n readonly stepNumber: number | undefined;\n readonly messages: ReadonlyArray<ModelMessage>;\n /** Wall-clock execution time in milliseconds. */\n readonly durationMs: number;\n } & (\n | {\n readonly success: true;\n readonly output: unknown;\n readonly error?: never;\n }\n | {\n readonly success: false;\n readonly output?: never;\n readonly error: unknown;\n }\n );\n\n/**\n * Context passed to the `onStepFinish` hook after each step completes.\n *\n * This is the AI SDK's `StepResult<TOOLS>` (= `OnStepFinishEvent<TOOLS>`) —\n * the full step record including `text`, `reasoning`, `toolCalls`,\n * `toolResults`, `files`, `sources`, `usage` (with `cachedInputTokens`,\n * `reasoningTokens`, `totalTokens`), `finishReason`, `warnings`, `request`,\n * `response`, and `providerMetadata` (where provider-specific cache\n * accounting like `cacheCreationInputTokens` lives).\n *\n * Pass an explicit `TOOLS` generic for typed `toolCalls`/`toolResults`.\n */\nexport type StepContext<TOOLS extends ToolSet = ToolSet> = Parameters<\n StreamTextOnStepFinishCallback<TOOLS>\n>[0];\n\n/**\n * Context passed to the `onChunk` hook for each streaming chunk.\n *\n * This is the AI SDK's `StreamTextOnChunkCallback` event — `{ chunk }`\n * where `chunk` is a discriminated union of `TextStreamPart` variants\n * (text-delta, reasoning-delta, source, tool-call, tool-input-start,\n * tool-input-delta, tool-result, raw).\n */\nexport type ChunkContext<TOOLS extends ToolSet = ToolSet> = Parameters<\n StreamTextOnChunkCallback<TOOLS>\n>[0];\n\n/**\n * @internal Re-export of the chunk variant union for consumers that need\n * to narrow on `chunk.type` without importing `TextStreamPart` directly.\n */\nexport type ChunkPart<TOOLS extends ToolSet = ToolSet> =\n ChunkContext<TOOLS>[\"chunk\"];\n\n/**\n * Configuration for a sandboxed extension, returned by getExtensions().\n */\nexport interface ExtensionConfig {\n /** Extension manifest (name, version, permissions, contributions). */\n manifest: import(\"./extensions/types\").ExtensionManifest;\n /** JavaScript source code defining the extension's tools. */\n source: string;\n}\n\nconst TIMED_OUT = Symbol(\"timed-out\");\n\n/**\n * An opinionated chat agent base class.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class Think<\n Env extends Cloudflare.Env = Cloudflare.Env,\n State = unknown,\n Props extends Record<string, unknown> = Record<string, unknown>\n> extends Agent<Env, State, Props> {\n // Root requestId of the in-flight recovery chain, threaded into each\n // continuation's snapshot so chained continuations keep owning the original\n // submission. This is a single instance field, NOT per-incident: it is only\n // safe because turns (and recovery fibers) are serialized by the turn queue,\n // so at most one recovery chain is active at a time. The `try/finally`\n // restore in `_chatRecoveryRetry` / `_chatRecoveryContinue` returns it to the\n // prior value once a continuation settles. If turns ever run concurrently,\n // this must move to per-incident storage.\n private _activeChatRecoveryRootRequestId: string | undefined;\n\n private static readonly CONFIG_KEYS = [\n \"_think_config\",\n \"lastClientTools\",\n \"lastBody\",\n \"skillsFingerprint\"\n ] as const;\n /**\n * Wait for MCP server connections to be ready before the inference\n * loop. MCP tools are auto-merged into the tool set.\n *\n * Set to `true` for a default 10s timeout, or `{ timeout: ms }`\n * for a custom timeout. Defaults to `false` (no waiting).\n */\n waitForMcpConnections: boolean | { timeout: number } = false;\n\n private _skillRegistry: SkillRegistry | null = null;\n private _loggedSkillWarnings = new Set<string>();\n\n /**\n * Controls how overlapping user submit requests behave while another\n * chat turn is already active or queued.\n *\n * @default \"queue\"\n */\n messageConcurrency: MessageConcurrency = \"queue\";\n\n /**\n * When true, chat turns are wrapped in `runFiber` for durable execution.\n * Enables `onChatRecovery` hook and `this.stash()` during streaming.\n */\n chatRecovery: ChatRecoveryConfig = true;\n\n static readonly CHAT_FIBER_NAME = \"__cf_internal_chat_turn\";\n\n /**\n * The conversation session — messages, context, compaction, search.\n *\n * Direct message writes are observed and mirrored into Think's live cache.\n * Prefer the history helpers below when writing UI messages from subclasses;\n * they sanitize content and enforce row-size limits before delegating here.\n */\n session!: Session;\n\n /** Cached messages — kept in sync with session storage. */\n private _cachedMessages: UIMessage[] = [];\n\n private _activeMessengerContext?: MessengerContext;\n\n private _messengerRuntime?: ThinkMessengerRuntime;\n\n /**\n * WorkerLoader binding for sandboxed extensions.\n * Set this to enable `getExtensions()` and dynamic extension loading.\n */\n extensionLoader?: WorkerLoader;\n\n /**\n * Extension manager — created automatically when `extensionLoader` is set.\n * Use for dynamic `load()` / `unload()` at runtime.\n */\n extensionManager?: import(\"./extensions/manager\").ExtensionManager;\n\n /**\n * Workspace filesystem available in `getTools()` and lifecycle hooks.\n * Defaults to a full `Workspace` backed by the DO's SQLite storage.\n *\n * Typed as `WorkspaceLike` rather than `Workspace` so subclasses can\n * replace it with anything that satisfies the interface — e.g. a proxy\n * that forwards to a shared workspace owned by a parent DO. Override as\n * a class field to skip the default init entirely:\n *\n * ```typescript\n * // Default init with R2 spillover for large files.\n * override workspace = new Workspace({\n * sql: this.ctx.storage.sql,\n * r2: this.env.R2,\n * name: () => this.name\n * });\n *\n * // Or a custom WorkspaceLike — e.g. a parent-owned shared workspace.\n * override workspace: WorkspaceLike = new SharedWorkspace(this);\n * ```\n */\n workspace!: WorkspaceLike;\n\n /**\n * Include the default workspace Bash tool. Enabled by default so models can\n * run shell-style multi-file workflows against the workspace. Set to `false`\n * to omit it from the built-in workspace tools.\n */\n workspaceBash:\n | boolean\n | NonNullable<Parameters<typeof createWorkspaceTools>[1]>[\"bash\"] = true;\n\n constructor(ctx: DurableObjectState, env: Env) {\n super(ctx, env);\n\n const _onStart = this.onStart.bind(this);\n this.onStart = async () => {\n // 1. Workspace initialization\n if (!this.workspace) {\n this.workspace = new Workspace({\n sql: this.ctx.storage.sql,\n name: () => this.name\n });\n }\n\n // 2. Session configuration (builder phase — context blocks, compaction, skills)\n const baseSession = Session.create(this);\n this.session = await this.configureSession(baseSession);\n this.session.internal_onMessagesChanged(async (event) => {\n switch (event.type) {\n case \"append\":\n if (!event.inserted || event.parentId !== undefined) {\n await this._syncMessages();\n } else {\n this._upsertCachedMessage(event.message as UIMessage);\n }\n break;\n case \"update\":\n this._patchCachedMessage(event.message as UIMessage);\n break;\n case \"clear\":\n this._replaceCachedMessages([]);\n break;\n case \"delete\":\n case \"compact\":\n await this._syncMessages();\n break;\n }\n });\n\n await this._initializeSkills();\n\n // Force Session to initialize its tables (assistant_messages,\n // assistant_compactions, assistant_config, etc.) so that subsequent\n // config reads work.\n await this._syncMessages();\n\n // 3-6. Extension initialization (if extensionLoader is set)\n if (this.extensionLoader) {\n await this._initializeExtensions();\n }\n\n // 7. Protocol handlers\n this._resumableStream = new ResumableStream(this.sql.bind(this));\n this._restoreClientTools();\n this._restoreBody();\n this._setupProtocolHandlers();\n this._initializeMessengers();\n\n // 8. User's onStart\n await _onStart();\n\n // 9. Declarative scheduled tasks are code-defined and should reconcile\n // before draining any recovered programmatic work they may enqueue.\n await this._reconcileDeclaredScheduledTasks();\n\n // 10. Durable submissions may run user-defined model/hooks, so start them\n // after subclass initialization has completed.\n await this._recoverSubmissionsOnStart();\n this._recoverWorkflowNotifications();\n if (this._hasPendingSubmissions()) {\n this._startSubmissionDrain();\n }\n if (this._hasPendingWorkflowNotifications()) {\n this._startWorkflowNotificationDrain();\n }\n };\n }\n\n /**\n * Conversation history as Think's live in-memory view.\n *\n * Storage remains the durable source of truth, but runtime logic should read\n * through this cache so in-flight turns, tool updates, and recovery state all\n * observe the same message list. Use `_syncMessages()` only at safe\n * boundaries where a full storage reread cannot drop in-flight state.\n */\n get messages(): UIMessage[] {\n return this._cachedMessages;\n }\n\n /** Read the durable message path from session storage. */\n private async _readMessagesFromStorage(): Promise<UIMessage[]> {\n return (await this.session.getHistory()) as UIMessage[];\n }\n\n /**\n * Normalize a tool part's `input` into something the provider will accept.\n *\n * Malformed shapes 400 modern providers and persist forever once written:\n * a stringified-JSON `input` (e.g. `'{\"prompt\":\"a cat\"}'` instead of the\n * object), and any non-object `input` — `null`, `undefined`, `\"\"`, an array,\n * or a primitive — on a settled or interrupted tool call (Anthropic rejects\n * a `tool_use` block whose `input` is not an object). We parse the former and\n * default the latter to an empty object so the tool-call/tool-result pair\n * stays valid. Delegates to the shared `normalizeToolInput` so the read-side\n * repair and the write-side accumulator guard enforce the same invariant.\n */\n private _normalizeToolInput(record: Record<string, unknown>): {\n input: unknown;\n changed: boolean;\n } {\n return normalizeToolInput(\"input\" in record ? record.input : undefined);\n }\n\n /**\n * Whether a tool part already has a settled result the provider accepts, so\n * it must NOT be re-repaired into an errored result.\n *\n * Single source of truth for the terminal tool states, shared by the repair\n * pass and the backstop detector so they cannot drift. Mirror the AI SDK's\n * terminal states: `convertToModelMessages` emits a `tool-result` for\n * `output-available`, `output-error`, AND `output-denied` (a user-denied\n * approval — its denial reason becomes the tool-result). Omitting any of\n * these makes repair re-flip the part every turn — clobbering a real\n * `errorText`/denial with the generic \"interrupted\" message — and makes the\n * backstop falsely drop a valid call.\n */\n private _toolPartHasSettledResult(record: Record<string, unknown>): boolean {\n if (\"output\" in record || \"result\" in record) return true;\n const state = typeof record.state === \"string\" ? record.state : \"\";\n return (\n state === \"output-available\" ||\n state === \"output-error\" ||\n state === \"output-denied\"\n );\n }\n\n /**\n * Tool-call ids that still have no recorded result. After repair this should\n * be empty; a non-empty result means the backstop (`ignoreIncompleteToolCalls`)\n * will drop those calls — i.e. repair missed a shape and should be extended.\n *\n * `approval-responded` is deliberately excluded: an approved server tool has\n * no result *yet*, but it is not incomplete or abandoned — it is waiting for\n * its continuation to run `execute()`. `convertToModelMessages` keeps that\n * call (and the SDK executes it), so flagging it here would log a misleading\n * \"repair gap\" warning and emit a spurious `chat:transcript:repaired` event\n * on every approval continuation.\n */\n private _incompleteToolCallIds(messages: UIMessage[]): string[] {\n const ids: string[] = [];\n for (const message of messages) {\n for (const part of message.parts) {\n const record = part as Record<string, unknown>;\n const toolCallId =\n typeof record.toolCallId === \"string\" ? record.toolCallId : undefined;\n const isToolPart =\n typeof record.type === \"string\" &&\n (record.type.startsWith(\"tool-\") || record.type === \"dynamic-tool\") &&\n toolCallId;\n if (!isToolPart) continue;\n if (record.state === \"approval-responded\") continue;\n if (!this._toolPartHasSettledResult(record)) ids.push(toolCallId);\n }\n }\n return ids;\n }\n\n /**\n * Repair a single interrupted tool call — a tool part with no settled result,\n * left behind when a stream was cut off mid-flight. Returns the replacement\n * part that takes its place in the transcript. `input` has already been\n * normalized to a valid object.\n *\n * The default flips it to an errored tool result so the record survives (no\n * \"disappearing\" tool call) and `convertToModelMessages` still gets a\n * tool-result for it (avoiding `AI_MissingToolResultsError`).\n *\n * Override to customize the repaired shape for client-resolved tools — e.g.\n * convert an interrupted `ask_user` (a question with no server `execute`,\n * normally answered by the user's next message) into a plain text part\n * carrying the question prose, so the model sees it as ordinary conversation\n * rather than a tool error and compaction keeps the question verbatim. This\n * runs DURING transcript repair — before the repaired transcript is persisted\n * and sent to the model — so the conversion shapes the current turn, not just\n * the next one. A returned tool part MUST carry a settled result\n * (`output-available` / `output-error` / `output-denied` or an\n * `output`/`result` field); returning a non-tool part (e.g. text) is fine.\n */\n protected repairInterruptedToolPart(\n part: UIMessage[\"parts\"][number]\n ): UIMessage[\"parts\"][number] {\n return {\n ...part,\n state: \"output-error\",\n errorText: \"The tool call was interrupted before a result was recorded.\"\n } as UIMessage[\"parts\"][number];\n }\n\n private _repairToolTranscriptParts(messages: UIMessage[]): {\n messages: UIMessage[];\n removedToolCalls: number;\n normalizedInputs: number;\n toolCallIds: string[];\n } {\n let removedToolCalls = 0;\n let normalizedInputs = 0;\n const toolCallIds: string[] = [];\n const repaired: UIMessage[] = [];\n\n for (const message of messages) {\n const parts: UIMessage[\"parts\"] = [];\n let messageChanged = false;\n for (const part of message.parts) {\n const record = part as Record<string, unknown>;\n const toolCallId =\n typeof record.toolCallId === \"string\" ? record.toolCallId : undefined;\n const isToolPart =\n typeof record.type === \"string\" &&\n (record.type.startsWith(\"tool-\") || record.type === \"dynamic-tool\") &&\n toolCallId;\n if (!isToolPart) {\n parts.push(part);\n continue;\n }\n\n if (!this._toolPartHasSettledResult(record)) {\n const state = typeof record.state === \"string\" ? record.state : \"\";\n // An approved server tool waits at `approval-responded` until its\n // scheduled continuation runs `execute()`. It is not abandoned, so\n // preserve it verbatim — flipping it to an error (or removing it)\n // would strand the approval and prevent the real result from ever\n // being produced by the continuation.\n if (state === \"approval-responded\") {\n parts.push(part);\n continue;\n }\n // Preserve the interrupted/abandoned tool call instead of deleting\n // it. Deleting makes the call \"disappear\" from the (broadcast)\n // transcript and lets the model silently re-run it. `input` is\n // normalized to a valid object first, then `repairInterruptedToolPart`\n // decides the replacement shape (default: an errored result, so\n // conversion still gets a tool-result and the provider doesn't 400\n // with AI_MissingToolResultsError). Subclasses can override it to\n // preserve client-resolved tools (e.g. `ask_user`) as text.\n const normalized = this._normalizeToolInput(record);\n parts.push(\n this.repairInterruptedToolPart({\n ...part,\n input: normalized.input\n } as UIMessage[\"parts\"][number])\n );\n if (normalized.changed) normalizedInputs++;\n removedToolCalls++;\n messageChanged = true;\n toolCallIds.push(toolCallId);\n continue;\n }\n\n const normalized = this._normalizeToolInput(record);\n if (normalized.changed) {\n parts.push({\n ...part,\n input: normalized.input\n } as UIMessage[\"parts\"][number]);\n normalizedInputs++;\n messageChanged = true;\n continue;\n }\n\n parts.push(part);\n }\n\n repaired.push(messageChanged ? { ...message, parts } : message);\n }\n\n return {\n messages: repaired,\n removedToolCalls,\n normalizedInputs,\n toolCallIds\n };\n }\n\n private async _repairTranscriptForProvider(\n messages: UIMessage[]\n ): Promise<UIMessage[]> {\n const repair = this._repairToolTranscriptParts(messages);\n if (repair.removedToolCalls === 0 && repair.normalizedInputs === 0) {\n return messages;\n }\n\n // Repair preserves every message (orphans are flipped to errored in place,\n // never deleted), so there are no removed rows to delete — only updates.\n for (const message of repair.messages) {\n const original = messages.find(\n (candidate) => candidate.id === message.id\n );\n if (original && original.parts !== message.parts) {\n await this.session.updateMessage(sanitizeMessage(message));\n }\n }\n\n this._replaceCachedMessages(repair.messages);\n this._broadcastMessages();\n this._emit(\"chat:transcript:repaired\", {\n removedToolCalls: repair.removedToolCalls,\n normalizedInputs: repair.normalizedInputs,\n toolCallIds: repair.toolCallIds\n });\n return repair.messages;\n }\n\n /** Replace the live cache with a durable storage snapshot. */\n private _replaceCachedMessages(messages: UIMessage[]): UIMessage[] {\n this._cachedMessages = messages;\n return this._cachedMessages;\n }\n\n /** Refresh the live cache from durable storage at a safe boundary. */\n private async _syncMessages(): Promise<UIMessage[]> {\n return this._replaceCachedMessages(await this._readMessagesFromStorage());\n }\n\n /** Patch or append one message in the live cache after a durable write. */\n private _upsertCachedMessage(message: UIMessage): void {\n const index = this._cachedMessages.findIndex((m) => m.id === message.id);\n if (index === -1) {\n this._cachedMessages.push(message);\n } else {\n this._cachedMessages[index] = message;\n }\n }\n\n /** Patch a message that is already present in the live cache. */\n private _patchCachedMessage(message: UIMessage): void {\n const index = this._cachedMessages.findIndex((m) => m.id === message.id);\n if (index !== -1) {\n this._cachedMessages[index] = message;\n }\n }\n\n private async _appendMessageToHistory(\n message: UIMessage,\n parentId?: string | null\n ): Promise<UIMessage> {\n const safe = enforceRowSizeLimit(sanitizeMessage(message));\n await this.session.appendMessage(safe, parentId);\n return safe;\n }\n\n private async _updateMessageInHistory(\n message: UIMessage\n ): Promise<UIMessage> {\n const safe = enforceRowSizeLimit(sanitizeMessage(message));\n await this.session.updateMessage(safe);\n return safe;\n }\n\n private async _upsertMessageInHistory(\n message: UIMessage,\n parentId?: string | null\n ): Promise<UIMessage> {\n const safe = enforceRowSizeLimit(sanitizeMessage(message));\n const existing = await this.session.getMessage(safe.id);\n if (existing) {\n await this.session.updateMessage(safe);\n } else {\n await this.session.appendMessage(safe, parentId);\n }\n return safe;\n }\n\n private async _clearHistory(): Promise<void> {\n await this.session.clearMessages();\n }\n\n /** Append a message while keeping Think's live message cache coherent. */\n protected appendMessageToHistory(\n message: UIMessage,\n parentId?: string | null\n ): Promise<UIMessage> {\n return this._appendMessageToHistory(message, parentId);\n }\n\n /** Update a message while keeping Think's live message cache coherent. */\n protected updateMessageInHistory(message: UIMessage): Promise<UIMessage> {\n return this._updateMessageInHistory(message);\n }\n\n /** Refresh Think's live message cache from the durable session path. */\n protected async syncMessagesFromStorage(): Promise<UIMessage[]> {\n return (await this._syncMessages()).slice();\n }\n\n private _aborts = new AbortRegistry();\n private _turnQueue = new TurnQueue();\n protected _resumableStream!: ResumableStream;\n private _pendingResumeConnections: Set<string> = new Set();\n private _lastClientTools: ClientToolSchema[] | undefined;\n private _lastBody: Record<string, unknown> | undefined;\n private _continuation = new ContinuationState<Connection>();\n private _continuationTimer: ReturnType<typeof setTimeout> | null = null;\n // True while a continuation is draining the in-flight tool-result/approval\n // applies on the parallel-tool-batch barrier (#1649 / #1650). Prevents a\n // second drain (and a double-fire) when more results arrive mid-drain — a\n // sibling that re-arms the coalesce timer during a drain is absorbed by the\n // in-progress drain rather than starting its own.\n private _continuationBarrierActive = false;\n private _insideResponseHook = false;\n private _insideInferenceLoop = false;\n private _pendingInteractionPromise: Promise<boolean> | null = null;\n // Serialization tail for client-tool result/approval applies (#1649). Each\n // apply is a read-modify-write of the full message; running siblings from a\n // parallel tool batch concurrently lets last-write-wins clobber the others\n // back to `input-available`. Chaining every apply off this tail makes them\n // commit atomically in arrival order.\n private _interactionApplyTail: Promise<void> = Promise.resolve();\n // The in-flight assistant message for the active streaming turn. Until\n // `_persistAssistantMessage` writes it at a turn boundary, the message lives\n // ONLY in this accumulator — not in storage and not in `this.messages`. A\n // client tool result can arrive over the WebSocket before that write (the\n // tool-call chunk was already broadcast), so a storage-only lookup in\n // `_applyToolUpdateToMessages` would miss the message and the part would\n // later be repaired as \"interrupted\" (#1649). Exposing the accumulator here\n // lets the apply write the result in place so it rides into the eventual\n // persist. Null when no stream is active. Mirrors `@cloudflare/ai-chat`'s\n // `_streamingMessage` handling.\n private _streamingAssistant: StreamAccumulator | null = null;\n private _submitConcurrency = new SubmitConcurrencyController({\n defaultDebounceMs: Think.MESSAGE_DEBOUNCE_MS\n });\n private static MESSAGE_DEBOUNCE_MS = 750;\n private _agentToolForwarders = new Map<\n string,\n Set<(chunk: AgentToolStoredChunk) => void>\n >();\n private _agentToolClosers = new Map<string, Set<() => void>>();\n private _agentToolAbortControllers = new Map<string, AbortController>();\n private _agentToolLastErrors = new Map<string, string>();\n private _agentToolPreTurnAssistantIds = new Map<string, Set<string>>();\n private _agentToolLiveSequences = new Map<string, number>();\n private _submissionTableEnsured = false;\n private _workflowNotificationTableEnsured = false;\n private _declaredScheduledTasksTableEnsured = false;\n private _drainingSubmissions = false;\n private _drainingWorkflowNotifications = false;\n private _submissionAbortControllers = new Map<string, AbortController>();\n private _programmaticStreamErrors = new Map<string, string>();\n protected static submissionRecoveryStaleMs = 15 * 60 * 1000;\n\n override broadcast(\n msg: string | ArrayBuffer | ArrayBufferView,\n without?: string[]\n ): void {\n if (this._agentToolForwarders.size > 0 && typeof msg === \"string\") {\n try {\n const parsed = JSON.parse(msg) as {\n type?: unknown;\n body?: unknown;\n error?: unknown;\n };\n if (parsed.type === MSG_CHAT_RESPONSE) {\n if (parsed.error === true && typeof parsed.body === \"string\") {\n for (const runId of this._agentToolForwarders.keys()) {\n this._agentToolLastErrors.set(runId, parsed.body);\n }\n } else if (\n typeof parsed.body === \"string\" &&\n parsed.body.length > 0\n ) {\n for (const [runId, forwarders] of this._agentToolForwarders) {\n const sequence = this._agentToolLiveSequences.get(runId) ?? 0;\n this._agentToolLiveSequences.set(runId, sequence + 1);\n const chunk = { sequence, body: parsed.body };\n for (const forward of forwarders) forward(chunk);\n }\n }\n }\n } catch {\n // Non-chat frames pass through unchanged.\n }\n }\n super.broadcast(msg, without);\n }\n\n override async alarm(): Promise<void> {\n await super.alarm();\n this._startWorkflowNotificationDrain();\n }\n\n // ── Dynamic config ──────────────────────────────────────────────\n\n #configCache: unknown = null;\n\n /**\n * Persist an arbitrary JSON-serializable configuration object for this\n * agent instance. Stored in the Think-private `think_config` table —\n * survives\n * restarts and hibernation. Pass the config shape as a method generic\n * for typed call sites:\n *\n * ```ts\n * this.configure<MyConfig>({ modelTier: \"fast\" });\n * ```\n *\n * Prefer `state` / `setState` from `Agent` when you want the value\n * broadcast to connected clients. Use `configure` for private\n * per-instance config that should stay server-side.\n */\n configure<T = Record<string, unknown>>(config: T): void {\n const json = JSON.stringify(config);\n this._configSet(\"_think_config\", json);\n this.#configCache = config;\n }\n\n /**\n * Read the persisted configuration, or null if never configured.\n * Pass the config shape as a method generic for a typed result:\n *\n * ```ts\n * const cfg = this.getConfig<MyConfig>();\n * ```\n */\n getConfig<T = Record<string, unknown>>(): T | null {\n if (this.#configCache !== null) return this.#configCache as T;\n const raw = this._configGet(\"_think_config\");\n if (raw !== undefined) {\n this.#configCache = JSON.parse(raw);\n return this.#configCache as T;\n }\n return null;\n }\n\n // ── Config storage helpers (think_config table) ─────────────────\n\n #configTableReady = false;\n\n protected _migrateLegacyConfigToThinkTable(): void {\n const rows = this.ctx.storage.sql\n .exec(\n \"SELECT sql FROM sqlite_master WHERE type='table' AND name='assistant_config'\"\n )\n .toArray() as Array<{ sql?: unknown }>;\n if (rows.length === 0) return;\n\n const ddl = String(rows[0].sql ?? \"\");\n if (!ddl.includes(\"session_id\")) return;\n\n // Older Think builds stored private config in Session's shared\n // `assistant_config(session_id, key, value)` table, even though\n // Think always used the empty session id. Copy only the Think-owned\n // keys into the dedicated `think_config` table and leave the shared\n // Session table untouched.\n for (const key of Think.CONFIG_KEYS) {\n const legacyRows = this.sql<{ value: string }>`\n SELECT value FROM assistant_config\n WHERE session_id = '' AND key = ${key}\n `;\n const value = legacyRows[0]?.value;\n if (value !== undefined) {\n this.sql`\n INSERT OR IGNORE INTO think_config (key, value)\n VALUES (${key}, ${value})\n `;\n }\n }\n }\n\n private _ensureConfigTable(): void {\n if (this.#configTableReady) return;\n this.sql`\n CREATE TABLE IF NOT EXISTS think_config (\n key TEXT NOT NULL,\n value TEXT NOT NULL,\n PRIMARY KEY (key)\n )\n `;\n this._migrateLegacyConfigToThinkTable();\n this.#configTableReady = true;\n }\n\n private _configSet(key: string, value: string): void {\n this._ensureConfigTable();\n this.sql`\n INSERT OR REPLACE INTO think_config (key, value)\n VALUES (${key}, ${value})\n `;\n }\n\n private _configGet(key: string): string | undefined {\n this._ensureConfigTable();\n const rows = this.sql<{ value: string }>`\n SELECT value FROM think_config\n WHERE key = ${key}\n `;\n return rows[0]?.value;\n }\n\n private _configDelete(key: string): void {\n this._ensureConfigTable();\n this.sql`\n DELETE FROM think_config\n WHERE key = ${key}\n `;\n }\n\n // ── Configuration overrides ─────────────────────────────────────\n\n /**\n * Return the language model to use for inference.\n * Must be overridden by subclasses.\n */\n getModel(): LanguageModel {\n throw new Error(\"Override getModel() to return a LanguageModel.\");\n }\n\n /**\n * Return the system prompt for the assistant.\n * Used as fallback when no context blocks are configured via `configureSession`.\n */\n getSystemPrompt(): string {\n return [\n \"You are a careful, capable assistant helping the user complete their task.\",\n \"Use available tools when they materially improve accuracy or let you act on the user's request. Before changing code, understand the relevant context: existing patterns, dependencies, tests, and nearby conventions.\",\n \"Keep changes focused on the user's request. Prefer small, idiomatic edits over broad rewrites or new abstractions. Do not introduce new dependencies, secrets, destructive actions, or persistent side effects unless the user clearly asks or approves.\",\n \"When the task is complex, briefly state your approach and keep the user informed with concise progress updates. If you modify code, verify with the smallest relevant test, build, typecheck, lint, or runtime check available, and report any checks you could not run.\",\n \"Be direct and useful in your final response: summarize the outcome, mention important files or commands, and call out real blockers or risks.\"\n ].join(\"\\n\\n\");\n }\n\n /** Return the tools available to the assistant. */\n getTools(): ToolSet {\n return {};\n }\n\n /** Return messenger integrations that should be routed through this Think agent. */\n getMessengers(): ThinkMessengers {\n return {};\n }\n\n getMessengerContext(): MessengerContext | undefined {\n if (this._activeMessengerContext) {\n return this._activeMessengerContext;\n }\n\n const message = this.messages.at(-1) as\n | (UIMessage & { metadata?: { messenger?: MessengerContext } })\n | undefined;\n return message?.metadata?.messenger;\n }\n\n async chatWithMessengerContext(\n userMessage: string | UIMessage,\n callback: StreamCallback,\n context: MessengerContext,\n options?: ChatOptions\n ): Promise<void> {\n const previous = this._activeMessengerContext;\n this._activeMessengerContext = context;\n try {\n await this.chat(userMessage, callback, options);\n } finally {\n this._activeMessengerContext = previous;\n }\n }\n\n private _initializeMessengers(): void {\n if (this.parentPath.length > 0) {\n return;\n }\n\n const messengers = this.getMessengers();\n if (Object.keys(messengers).length === 0) {\n return;\n }\n\n this._messengerRuntime = new ThinkMessengerRuntime(\n messengers,\n this as unknown as MessengerThinkHost\n );\n this._messengerRuntime.initialize();\n }\n\n /** Return code-declared scheduled tasks for this agent. */\n getScheduledTasks(): ThinkScheduledTasks | Promise<ThinkScheduledTasks> {\n return {};\n }\n\n /**\n * Reconcile code-declared scheduled tasks immediately.\n * Static declarations are reconciled on startup automatically; call this\n * after changing app-owned data that `getScheduledTasks()` reads.\n */\n async internal_reconcileScheduledTasks(): Promise<void> {\n await this._reconcileDeclaredScheduledTasks();\n }\n\n /**\n * Return the default timezone for wall-clock scheduled tasks.\n * Task-local timezone declarations take precedence.\n */\n getDefaultTimezone(): string | undefined | Promise<string | undefined> {\n return undefined;\n }\n\n private async _runChatRecoveryFiber<T>(\n requestId: string,\n continuation: boolean,\n fn: () => Promise<T>\n ): Promise<T> {\n const snapshot = createChatFiberSnapshot({\n kind: \"think-chat-turn\",\n requestId,\n recoveryRootRequestId: this._activeChatRecoveryRootRequestId ?? requestId,\n continuation,\n messages: this.messages,\n lastBody: this._lastBody,\n lastClientTools: this._lastClientTools\n });\n\n return this._runFiberWithStashWrapper(\n `${(this.constructor as typeof Think).CHAT_FIBER_NAME}:${requestId}`,\n async () => fn(),\n {\n initialSnapshot: wrapChatFiberSnapshot(\n \"__cfThinkChatFiberSnapshot\",\n snapshot,\n null\n ),\n wrapStash: (data) =>\n wrapChatFiberSnapshot(\"__cfThinkChatFiberSnapshot\", snapshot, data)\n }\n );\n }\n\n private _systemPromptForTurn(baseSystem: string, tools: ToolSet): string {\n if (baseSystem.includes(\"You are running inside a Think agent.\")) {\n return baseSystem;\n }\n\n return `${baseSystem.trimEnd()}\\n\\n${this._buildThinkCapabilityBlock(tools)}`;\n }\n\n private _buildThinkCapabilityBlock(tools: ToolSet): string {\n const toolNames = new Set(Object.keys(tools));\n const hasTools = toolNames.size > 0;\n const hasWorkspaceTools = [\n \"read\",\n \"write\",\n \"edit\",\n \"list\",\n \"find\",\n \"grep\",\n \"delete\"\n ].some((toolName) => toolNames.has(toolName));\n const hasContextTools =\n toolNames.has(\"load_context\") || toolNames.has(\"unload_context\");\n const hasExtensionTools =\n toolNames.has(\"load_extension\") || toolNames.has(\"list_extensions\");\n const hasExecuteTool = toolNames.has(\"execute\");\n\n const lines = [\n \"You are running inside a Think agent.\",\n \"\",\n \"Capabilities available in this turn:\"\n ];\n\n if (hasWorkspaceTools) {\n lines.push(\n \"- You can inspect and edit the agent workspace using the available file tools.\"\n );\n }\n\n if (hasTools) {\n lines.push(\n \"- Use the tools exposed in this turn when they materially improve accuracy or let you act on the user's request. Treat tool descriptions and schemas as the source of truth.\"\n );\n lines.push(\n \"- Some tools may call server code, browser/client code, MCP servers, extensions, or delegated agents. Use them according to their descriptions.\"\n );\n }\n\n if (hasContextTools) {\n lines.push(\n \"- If context-loading tools are available, use them to load relevant memory, skills, or project context before acting on incomplete information.\"\n );\n }\n\n if (hasExtensionTools) {\n lines.push(\n \"- If extension tools are available, use them only when loading or inspecting extensions directly helps with the task.\"\n );\n }\n\n if (hasExecuteTool) {\n lines.push(\n \"- If sandboxed execution is available, prefer it for safe, bounded checks or coordinated multi-step operations.\"\n );\n }\n\n lines.push(\n \"- Do not claim access to capabilities that are not exposed as tools in this turn.\"\n );\n\n return lines.join(\"\\n\");\n }\n\n /** Maximum number of tool-call steps per turn. Override via property or per-turn via TurnConfig. */\n maxSteps = 10;\n\n /**\n * Whether reasoning chunks are sent to chat clients by default. Override\n * per turn by returning `sendReasoning` from `beforeTurn`.\n */\n sendReasoning = true;\n\n /**\n * Inactivity watchdog for the streaming read loop, in milliseconds.\n *\n * If a turn's model stream produces no chunk for this long, the watchdog\n * aborts the turn and surfaces a terminal stream error instead of letting the\n * loop park forever on a hung provider/transport (the \"infinite spinner\"\n * failure: the stream never throws, so no error and no `done` ever arrives).\n * A `chat:stream:stalled` observability event is emitted when it fires.\n *\n * This measures the gap *between UI-message-stream chunks*, which includes\n * time spent executing server-side tools (no chunks flow while a tool runs).\n * Set it comfortably above your slowest expected model time-to-first-token\n * and your slowest tool execution, or you will abort healthy long turns.\n *\n * Default `0` (disabled) — opt in by setting a value (e.g. `120_000`).\n *\n * Can be overridden per-turn via `TurnConfig.chatStreamStallTimeoutMs`\n * (returned from `beforeTurn`) for turns with known-slow tools.\n */\n chatStreamStallTimeoutMs = 0;\n\n /**\n * Per-turn stall-watchdog timeout resolved from `TurnConfig` in\n * `_runInferenceLoop`, read by the stream loop when arming the watchdog.\n * `undefined` falls back to the instance-level `chatStreamStallTimeoutMs`.\n * Turns are serialized, so a single active value is safe; it is reset at the\n * top of every `_runInferenceLoop`.\n */\n private _activeStallTimeoutMs: number | undefined;\n\n /**\n * Configure the session. Called once during `onStart`.\n * Override to add context blocks, compaction, search, skills.\n *\n * @example\n * ```typescript\n * configureSession(session: Session) {\n * return session\n * .withContext(\"memory\", { description: \"Learned facts\", maxTokens: 2000 })\n * .withCachedPrompt();\n * }\n * ```\n */\n configureSession(session: Session): Session | Promise<Session> {\n return session;\n }\n\n /**\n * Return Agent Skills sources for this Think agent.\n *\n * Bundled skills are typically imported with the Agents Vite plugin:\n *\n * ```typescript\n * import productSkills from \"agents:skills\"; // -> ./skills next to this file\n * ```\n *\n * Sources are applied in order; the first source to register a skill name\n * wins, and later collisions are skipped with a logged warning.\n */\n getSkills(): SkillSource[] | Promise<SkillSource[]> {\n return [];\n }\n\n private async _initializeSkills(): Promise<void> {\n // A misconfigured or failing skill source must never prevent the agent\n // from starting. Any error here is logged and skills stay disabled.\n try {\n const sources = await this.getSkills();\n if (sources.length === 0) return;\n\n const registry = new SkillRegistry(sources, this.getSkillScriptRunner());\n await registry.load();\n this._logSkillWarnings(registry);\n this._skillRegistry = registry;\n\n await this.session.addContext(registry.contextLabel, {\n description: \"Think skills: available skill catalog\",\n provider: {\n get: () => registry.systemPrompt()\n }\n });\n\n const previous = this._configGet(\"skillsFingerprint\");\n if (previous !== registry.fingerprint) {\n await this.session.refreshSystemPrompt();\n this._configSet(\"skillsFingerprint\", registry.fingerprint);\n }\n } catch (error) {\n console.warn(\n `[think] Failed to initialize skills; continuing without them: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n /**\n * Log registry diagnostics (duplicate names, sources that failed to list),\n * deduped by message so a new collision after a deploy still surfaces while\n * the same warning is not repeated on every turn.\n */\n private _logSkillWarnings(registry: SkillRegistry): void {\n for (const warning of registry.warnings) {\n if (this._loggedSkillWarnings.has(warning)) continue;\n this._loggedSkillWarnings.add(warning);\n console.warn(`[think] ${warning}`);\n }\n }\n\n /**\n * Return an optional runner that enables the `run_skill_script` tool.\n *\n * @experimental Skill script execution is experimental and may change\n * before stabilizing.\n */\n getSkillScriptRunner(): SkillScriptRunner | null {\n return null;\n }\n\n private async _refreshSkillsIfChanged(): Promise<void> {\n if (!this._skillRegistry) return;\n\n // Refreshing pulls from live sources (e.g. R2); a transient failure must\n // not break the turn. Keep the last good catalog on error.\n try {\n await this._skillRegistry.refresh();\n this._logSkillWarnings(this._skillRegistry);\n const previous = this._configGet(\"skillsFingerprint\");\n if (previous !== this._skillRegistry.fingerprint) {\n await this.session.refreshSystemPrompt();\n this._configSet(\"skillsFingerprint\", this._skillRegistry.fingerprint);\n }\n } catch (error) {\n console.warn(\n `[think] Failed to refresh skills; using last known catalog: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n /**\n * Return sandboxed extension configurations. Defines load order,\n * which determines hook execution order.\n * Requires `extensionLoader` to be set.\n */\n getExtensions(): ExtensionConfig[] {\n return [];\n }\n\n // ── Lifecycle hooks ───────────────────────────────────────────\n\n /**\n * Called before `streamText` — inspect the assembled context and\n * return overrides. Think assembles tools, system prompt, and messages\n * internally; this hook sees the result and can override any part.\n *\n * Return `void` to accept all defaults.\n *\n * @example Switch model for continuations\n * ```typescript\n * beforeTurn(ctx: TurnContext) {\n * if (ctx.continuation) return { model: this.cheapModel };\n * }\n * ```\n *\n * @example Restrict active tools\n * ```typescript\n * beforeTurn(ctx: TurnContext) {\n * return { activeTools: [\"read\", \"write\"] };\n * }\n * ```\n */\n beforeTurn(\n _ctx: TurnContext\n ): TurnConfig | void | Promise<TurnConfig | void> {}\n\n /**\n * Called before each AI SDK step in the agentic loop. Backed by\n * `streamText({ prepareStep })`.\n *\n * Return `void` to accept the current step defaults, or return a\n * `StepConfig` to override the model, tool choice, active tools,\n * system prompt, messages, experimental context, or provider options\n * for this step. Use `beforeTurn` for turn-wide assembly and\n * `beforeStep` when the decision depends on the step number or\n * previous step results.\n *\n * @example Force search on the first step\n * ```typescript\n * beforeStep(ctx: PrepareStepContext) {\n * if (ctx.stepNumber === 0) {\n * return {\n * activeTools: [\"search\"],\n * toolChoice: { type: \"tool\", toolName: \"search\" }\n * };\n * }\n * }\n * ```\n *\n * @example Switch to a cheaper model after tool results land\n * ```typescript\n * beforeStep(ctx: PrepareStepContext) {\n * // assumes a `fastSummaryModel` field on your Think subclass\n * if (ctx.steps.some((s) => s.toolResults.length > 0)) {\n * return { model: this.fastSummaryModel };\n * }\n * }\n * ```\n */\n beforeStep(\n _ctx: PrepareStepContext\n ): StepConfig | void | Promise<StepConfig | void> {}\n\n /**\n * Called **before** the tool's `execute` function runs. Think wraps\n * every tool's `execute` so it can consult this hook and act on the\n * returned `ToolCallDecision`:\n *\n * - `void` (or `{ action: \"allow\" }` with no `input`) — run the\n * original `execute` with the original input.\n * - `{ action: \"allow\", input }` — run the original `execute` with\n * the substituted input.\n * - `{ action: \"block\", reason }` — skip `execute`; the model sees\n * `reason` as the tool's output.\n * - `{ action: \"substitute\", output }` — skip `execute`; the model\n * sees `output` as the tool's output.\n *\n * Only fires for server-side tools (tools with `execute`). Client\n * tools are handled on the client — Think can't intercept them.\n *\n * `afterToolCall` always fires after this hook (or after the original\n * `execute` when `allow`). For `block`/`substitute`, the substituted\n * value flows through `afterToolCall` as `success: true, output: ...`.\n *\n * @example Log tool calls\n * ```typescript\n * beforeToolCall(ctx: ToolCallContext) {\n * console.log(`Tool called: ${ctx.toolName}`, ctx.input);\n * }\n * ```\n *\n * @example Block a tool the model shouldn't be calling here\n * ```typescript\n * beforeToolCall(ctx: ToolCallContext): ToolCallDecision | void {\n * if (ctx.toolName === \"delete\" && this.isReadOnlyMode) {\n * return { action: \"block\", reason: \"delete is disabled in read-only mode\" };\n * }\n * }\n * ```\n *\n * @example Substitute a cached result\n * ```typescript\n * async beforeToolCall(ctx: ToolCallContext): Promise<ToolCallDecision | void> {\n * if (ctx.toolName === \"weather\") {\n * const cached = await this.cache.get(JSON.stringify(ctx.input));\n * if (cached) return { action: \"substitute\", output: cached };\n * }\n * }\n * ```\n */\n beforeToolCall(\n _ctx: ToolCallContext\n ): ToolCallDecision | void | Promise<ToolCallDecision | void> {}\n\n /**\n * Called **after** a tool's outcome is known — for real executions, for\n * `block` (carries the `reason` as `output`), and for `substitute`\n * (carries the substituted `output`). Backed by the AI SDK's\n * `experimental_onToolCallFinish`, so `durationMs` and the discriminated\n * `success`/`output`/`error` outcome reflect what the model actually\n * sees: a thrown error from the original `execute` becomes\n * `success: false, error: ...`; everything else (including blocked /\n * substituted calls) is `success: true, output: ...`.\n *\n * Override for logging, metrics, or result inspection.\n *\n * @example\n * ```typescript\n * afterToolCall(ctx: ToolCallResultContext) {\n * if (ctx.success) {\n * console.log(`${ctx.toolName} ok in ${ctx.durationMs}ms`);\n * } else {\n * console.error(`${ctx.toolName} failed:`, ctx.error);\n * }\n * }\n * ```\n */\n afterToolCall(_ctx: ToolCallResultContext): void | Promise<void> {}\n\n /**\n * Called after each step completes (initial, continue, tool-result).\n * Override for step-level logging or analytics.\n */\n onStepFinish(_ctx: StepContext): void | Promise<void> {}\n\n /**\n * Called for each streaming chunk. High-frequency — fires per token.\n * Override for streaming analytics, progress indicators, or token counting.\n * Observational only (void return).\n */\n onChunk(_ctx: ChunkContext): void | Promise<void> {}\n\n /**\n * Called after a chat turn completes and the assistant message has been\n * persisted. The turn lock is released before this hook runs, so it is\n * safe to call other methods from inside.\n *\n * Fires for all turn completion paths: WebSocket chat requests,\n * sub-agent RPC, and auto-continuation.\n *\n * Override for logging, chaining, analytics, usage tracking.\n */\n onChatResponse(_result: ChatResponseResult): void | Promise<void> {}\n\n /**\n * Handle an error that occurred during a chat turn.\n * Override to customize error handling (e.g. logging, metrics).\n */\n onChatError(error: unknown, _ctx?: ChatErrorContext): unknown {\n return error;\n }\n\n // ── Extension initialization ───────────────────────────────────\n\n private async _initializeExtensions(): Promise<void> {\n const { ExtensionManager } = await import(\"./extensions/manager\");\n const { sanitizeName } = await import(\"./extensions/manager\");\n\n // 3. Create ExtensionManager with host binding if HostBridgeLoopback\n // is re-exported from the worker entry point.\n const agentClassName = this.constructor.name;\n const agentId = this.ctx.id.toString();\n const ctxExports = (this.ctx as unknown as Record<string, unknown>)\n .exports as Record<string, unknown> | undefined;\n const hasBridge =\n ctxExports && typeof ctxExports.HostBridgeLoopback === \"function\";\n\n this.extensionManager = new ExtensionManager({\n loader: this.extensionLoader!,\n storage: this.ctx.storage,\n ...(hasBridge\n ? {\n createHostBinding: (\n permissions: import(\"./extensions/types\").ExtensionPermissions,\n ownContextLabels: string[]\n ) =>\n (\n ctxExports.HostBridgeLoopback as (opts: {\n props: Record<string, unknown>;\n }) => Fetcher\n )({\n props: {\n agentClassName,\n agentId,\n permissions,\n ownContextLabels\n }\n })\n }\n : {})\n });\n\n // 4. Load static extensions from getExtensions()\n const configs = this.getExtensions();\n for (const config of configs) {\n await this.extensionManager.load(config.manifest, config.source);\n }\n\n // 5. Restore dynamic extensions from DO storage\n await this.extensionManager.restore();\n\n // 6. Register extension context blocks in Session (mutation phase).\n // Context blocks use SQLite-backed AgentContextProvider (no bridge\n // delegation to the extension Worker). Extensions write to their\n // blocks via host.setContext() (Phase 3). Bridge providers that\n // delegate to extension Worker RPC methods are Phase 4.\n for (const ext of this.extensionManager.list()) {\n const manifest = this.extensionManager.getManifest(ext.name);\n if (!manifest?.context) continue;\n\n const prefix = sanitizeName(ext.name);\n for (const ctxDef of manifest.context) {\n const namespacedLabel = `${prefix}_${ctxDef.label}`;\n await this.session.addContext(namespacedLabel, {\n description: ctxDef.description,\n maxTokens: ctxDef.maxTokens\n });\n }\n }\n\n // Wire unload callback to clean up context blocks\n this.extensionManager.onUnload(async (_name, contextLabels) => {\n for (const label of contextLabels) {\n this.session.removeContext(label);\n }\n await this.session.refreshSystemPrompt();\n });\n }\n\n // ── Inference loop (Think owns this) ──────────────────────────\n\n /**\n * The single convergence point for all chat turn entry paths.\n * Merges tools, assembles context, fires lifecycle hooks, wraps tools\n * for interception, and calls streamText.\n */\n private async _runInferenceLoop(input: TurnInput): Promise<StreamableResult> {\n // Reset the per-turn watchdog override; `beforeTurn` may set it below. A\n // turn that doesn't override falls back to the instance-level value.\n this._activeStallTimeoutMs = undefined;\n if (this.waitForMcpConnections) {\n const timeout =\n typeof this.waitForMcpConnections === \"object\"\n ? this.waitForMcpConnections.timeout\n : 10_000;\n await this.mcp.waitForConnections({ timeout });\n }\n\n const workspaceTools = createWorkspaceTools(this.workspace, {\n bash: this.workspaceBash\n });\n const baseTools = this.getTools();\n const extensionTools = this.extensionManager?.getTools() ?? {};\n await this._refreshSkillsIfChanged();\n const contextTools = await this.session.tools();\n const skillTools = this._skillRegistry?.tools() ?? {};\n const clientToolSet = createToolsFromClientSchemas(input.clientTools);\n const tools: ToolSet = {\n ...workspaceTools,\n ...baseTools,\n ...extensionTools,\n ...contextTools,\n ...skillTools,\n ...(this.mcp?.getAITools?.() ?? {}),\n ...clientToolSet\n };\n\n const frozenPrompt = await this.session.freezeSystemPrompt();\n const baseSystem = frozenPrompt || this.getSystemPrompt();\n const system = this._systemPromptForTurn(baseSystem, tools);\n\n const history = await this._repairTranscriptForProvider(this.messages);\n const truncated = truncateOlderMessages(history) as UIMessage[];\n // `_repairTranscriptForProvider` above already heals orphan tool calls\n // (flipping them to errored results, preserving the record). This is the\n // last-line backstop: if any incomplete tool call still slips through\n // (compaction edge, addToolOutput race, an unrecognized part shape), drop it\n // here rather than letting the provider 400 with AI_MissingToolResultsError.\n //\n // The backstop drops silently. Repair should have left nothing incomplete,\n // so a non-empty set here means repair missed a shape — surface it (rather\n // than masking a repair bug) without breaking the turn.\n const incompleteAfterRepair = this._incompleteToolCallIds(truncated);\n if (incompleteAfterRepair.length > 0) {\n console.warn(\n `[Think] ${incompleteAfterRepair.length} incomplete tool call(s) survived transcript repair and will be dropped by ignoreIncompleteToolCalls: ${incompleteAfterRepair.join(\", \")}. This indicates a gap in _repairToolTranscriptParts.`\n );\n this._emit(\"chat:transcript:repaired\", {\n removedToolCalls: incompleteAfterRepair.length,\n normalizedInputs: 0,\n toolCallIds: incompleteAfterRepair\n });\n }\n const messages = await convertToModelMessages(truncated, {\n tools,\n ignoreIncompleteToolCalls: true\n });\n\n if (messages.length === 0) {\n throw new Error(\n \"No messages to send to the model. This usually means the chat request \" +\n \"arrived before any messages were persisted.\"\n );\n }\n\n const model = this.getModel();\n const ctx: TurnContext = {\n system,\n messages,\n tools,\n model,\n continuation: input.continuation,\n body: input.body\n };\n\n const subclassConfig = (await this.beforeTurn(ctx)) ?? {};\n const config = await this._pipelineExtensionBeforeTurn(ctx, subclassConfig);\n const workflowPrompt = input.workflowPrompt;\n const workflowOutput = workflowPrompt?.output\n ? Output.object({\n schema: jsonSchema(workflowPrompt.output.schema as never)\n })\n : undefined;\n\n const finalModel = config.model ?? model;\n const finalSystem =\n config.system ??\n this._systemPromptForTurn(\n baseSystem,\n config.tools ? { ...tools, ...config.tools } : tools\n );\n const finalMessages = ensureValidContinueCheckpoint(\n config.messages ?? messages\n );\n const mergedTools: ToolSet = config.tools\n ? { ...tools, ...config.tools }\n : tools;\n // Wrap each tool's `execute` so `beforeToolCall` is consulted before\n // the tool actually runs. The wrapped `execute` honors the returned\n // `ToolCallDecision` — `block` short-circuits with `reason`,\n // `substitute` returns `output` directly, `allow` runs the original\n // (optionally with modified `input`).\n const finalTools: ToolSet = this._wrapToolsWithDecision(mergedTools);\n const finalMaxSteps = config.maxSteps ?? this.maxSteps;\n const finalSendReasoning = config.sendReasoning ?? this.sendReasoning;\n // Resolve the per-turn stall-watchdog override (explicit `0` = off for this\n // turn). Read by `_streamResult` / `_streamResultToRpcCallback` when arming\n // the watchdog. `??` so a `0` override is honored, not treated as \"unset\".\n this._activeStallTimeoutMs =\n config.chatStreamStallTimeoutMs ?? this.chatStreamStallTimeoutMs;\n const finalOutput = workflowOutput ?? config.output;\n const finalStopWhen = [\n stepCountIs(finalMaxSteps),\n ...(Array.isArray(config.stopWhen)\n ? config.stopWhen\n : config.stopWhen\n ? [config.stopWhen]\n : [])\n ];\n\n const result = streamText({\n model: finalModel,\n system: finalSystem,\n messages: finalMessages,\n tools: finalTools,\n activeTools: config.activeTools,\n toolChoice: config.toolChoice,\n maxOutputTokens: config.maxOutputTokens,\n temperature: config.temperature,\n topP: config.topP,\n topK: config.topK,\n presencePenalty: config.presencePenalty,\n frequencyPenalty: config.frequencyPenalty,\n stopSequences: config.stopSequences,\n seed: config.seed,\n maxRetries: config.maxRetries,\n timeout: config.timeout,\n headers: config.headers,\n stopWhen: finalStopWhen,\n providerOptions: config.providerOptions as\n | Parameters<typeof streamText>[0][\"providerOptions\"]\n | undefined,\n experimental_telemetry: config.experimental_telemetry,\n // Forward the per-turn structured-output spec from TurnConfig so\n // callers can use AI SDK `Output.object({ schema })` / `Output.text()`\n // on the terminal turn without dropping tools at model construction.\n output: finalOutput,\n abortSignal: input.signal,\n // Forward the AI SDK's `prepareStep` callback unchanged so subclasses\n // can make per-step decisions from the previous steps, current\n // messages, model, and experimental context.\n //\n // Subclass-only by design: extension dispatch is intentionally not\n // wired here. The prepareStep event includes a live `LanguageModel`\n // instance which is not JSON-serializable, and a returned override\n // can include the same — there's no useful \"snapshot, override\"\n // contract we could give to sandboxed extensions. If we expose\n // observation-only later it should go through a separate,\n // serialized event surface.\n //\n // `beforeStep` returning `void`/`undefined`/`null` is normalized to\n // `{}` so the AI SDK falls back to top-level settings (it accepts\n // `undefined` per docs but the typed return is non-null).\n prepareStep: (async (event) => {\n const result = await this.beforeStep(event);\n return result == null ? {} : result;\n }) satisfies PrepareStepFunction<ToolSet>,\n onChunk: async (event) => {\n // Pass the AI SDK's chunk event through unchanged — gives users\n // access to the discriminated `TextStreamPart` chunk with all\n // provider metadata.\n await this.onChunk(event);\n await this._pipelineExtensionChunk(event);\n },\n onStepFinish: async (event) => {\n // Pass the full StepResult through — gives users access to\n // reasoning, sources, files, providerMetadata (cache tokens),\n // request/response, warnings, and the full LanguageModelUsage\n // that the AI SDK provides.\n await this.onStepFinish(event);\n await this._pipelineExtensionStepFinish(event);\n },\n // `beforeToolCall` is dispatched from the wrapped `execute` (see\n // `_wrapToolsWithDecision` above) so the returned `ToolCallDecision`\n // can actually intercept the call. `afterToolCall` is wired through\n // the AI SDK's `experimental_onToolCallFinish` callback so we get\n // accurate `durationMs` and the discriminated `success`/`error`\n // outcome — including failures that propagate out of `execute`.\n experimental_onToolCallFinish: (async (event) => {\n const base = {\n ...event.toolCall,\n stepNumber: event.stepNumber,\n messages: event.messages,\n durationMs: event.durationMs\n };\n const ctx = (\n event.success\n ? { ...base, success: true as const, output: event.output }\n : { ...base, success: false as const, error: event.error }\n ) as ToolCallResultContext;\n await this.afterToolCall(ctx);\n await this._pipelineExtensionToolCallFinish(event);\n }) satisfies StreamTextOnToolCallFinishCallback<ToolSet>\n });\n\n const outputPromise =\n finalOutput && result.output ? Promise.resolve(result.output) : undefined;\n if (outputPromise) {\n // Attach a rejection observer immediately. `_streamResult()` will still\n // await this promise when captureOutput is enabled, but aborted streams can\n // reject before the stream consumer reaches that point.\n void outputPromise.catch(() => {});\n }\n\n const streamResult = {\n toUIMessageStream: () =>\n result.toUIMessageStream({ sendReasoning: finalSendReasoning }),\n output: outputPromise\n } satisfies StreamableResult;\n\n return this._transformInferenceResult(streamResult);\n }\n\n /** @internal Test seam — override in test agents to wrap the stream (e.g. error injection). */\n protected _transformInferenceResult(\n result: StreamableResult\n ): StreamableResult {\n return result;\n }\n\n /** Default hook timeout in milliseconds. */\n hookTimeout = 5000;\n\n /**\n * Pipeline beforeTurn through sandboxed extensions in load order.\n * Each extension sees the accumulated state from prior extensions\n * (snapshot is rebuilt after each extension's modifications).\n * Results are merged with last-write-wins for scalar fields.\n * Extensions that don't subscribe to beforeTurn are skipped.\n */\n private async _pipelineExtensionBeforeTurn(\n ctx: TurnContext,\n subclassConfig: TurnConfig\n ): Promise<TurnConfig> {\n if (!this.extensionManager) return subclassConfig;\n\n const subscribers = this.extensionManager.getHookSubscribers(\"beforeTurn\");\n if (subscribers.length === 0) return subclassConfig;\n\n const { createTurnContextSnapshot, parseHookResult } =\n await import(\"./extensions/hook-proxy\");\n\n let snapshot = createTurnContextSnapshot(ctx);\n let accumulated = { ...subclassConfig };\n\n // Apply subclass config to the initial snapshot so extensions\n // see the subclass overrides\n if (accumulated.system !== undefined) snapshot.system = accumulated.system;\n if (accumulated.maxSteps !== undefined)\n snapshot.messageCount = ctx.messages.length;\n\n for (const sub of subscribers) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const resultJson = await Promise.race([\n sub.entrypoint.hook(\"beforeTurn\", snapshot),\n new Promise<string>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(`Hook timeout: ${sub.name}`)),\n this.hookTimeout\n );\n })\n ]);\n\n const parsed = parseHookResult(resultJson);\n if (\"config\" in parsed) {\n // Merge serializable scalars only. model and tools are skipped —\n // sandboxed extensions can't return LanguageModel or AI SDK Tool\n // objects (not serializable across RPC). Use activeTools to\n // control which tools the model can call.\n if (parsed.config.system !== undefined)\n accumulated.system = parsed.config.system;\n if (parsed.config.messages !== undefined)\n accumulated.messages = parsed.config.messages;\n if (parsed.config.activeTools !== undefined)\n accumulated.activeTools = parsed.config.activeTools;\n if (parsed.config.toolChoice !== undefined)\n accumulated.toolChoice = parsed.config.toolChoice;\n if (parsed.config.maxSteps !== undefined)\n accumulated.maxSteps = parsed.config.maxSteps;\n if (parsed.config.sendReasoning !== undefined)\n accumulated.sendReasoning = parsed.config.sendReasoning;\n if (parsed.config.maxOutputTokens !== undefined)\n accumulated.maxOutputTokens = parsed.config.maxOutputTokens;\n if (parsed.config.temperature !== undefined)\n accumulated.temperature = parsed.config.temperature;\n if (parsed.config.topP !== undefined)\n accumulated.topP = parsed.config.topP;\n if (parsed.config.topK !== undefined)\n accumulated.topK = parsed.config.topK;\n if (parsed.config.presencePenalty !== undefined)\n accumulated.presencePenalty = parsed.config.presencePenalty;\n if (parsed.config.frequencyPenalty !== undefined)\n accumulated.frequencyPenalty = parsed.config.frequencyPenalty;\n if (parsed.config.stopSequences !== undefined)\n accumulated.stopSequences = parsed.config.stopSequences;\n if (parsed.config.seed !== undefined)\n accumulated.seed = parsed.config.seed;\n if (parsed.config.maxRetries !== undefined)\n accumulated.maxRetries = parsed.config.maxRetries;\n if (parsed.config.timeout !== undefined)\n accumulated.timeout = parsed.config.timeout;\n if (parsed.config.headers !== undefined) {\n accumulated.headers = {\n ...(accumulated.headers ?? {}),\n ...parsed.config.headers\n };\n }\n if (parsed.config.providerOptions !== undefined) {\n accumulated.providerOptions = {\n ...(accumulated.providerOptions ?? {}),\n ...parsed.config.providerOptions\n };\n }\n // Update snapshot so next extension sees this extension's changes\n if (accumulated.system !== undefined)\n snapshot = { ...snapshot, system: accumulated.system };\n if (accumulated.activeTools !== undefined)\n snapshot = { ...snapshot, toolNames: accumulated.activeTools };\n } else if (\"error\" in parsed) {\n console.warn(\n `[Think] Extension \"${sub.name}\" beforeTurn error:`,\n parsed.error\n );\n }\n } catch (err) {\n console.warn(\n `[Think] Extension \"${sub.name}\" beforeTurn failed:`,\n err instanceof Error ? err.message : err\n );\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n\n return accumulated;\n }\n\n /**\n * Dispatch an observation hook to all extensions that subscribe to it.\n *\n * Used by `_pipelineExtensionToolCallStart`, `_pipelineExtensionToolCallFinish`,\n * `_pipelineExtensionStepFinish`, and `_pipelineExtensionChunk`. Unlike\n * `beforeTurn`, these hooks are observation-only — extensions can't\n * influence the turn — so we ignore return values, log errors, and\n * apply a per-extension timeout.\n *\n * `onChunk` is high-frequency (per token) — extensions that subscribe\n * to it pay an RPC cost per chunk and should be used sparingly.\n */\n private async _dispatchExtensionObservation(\n hookName: \"beforeToolCall\" | \"afterToolCall\" | \"onStepFinish\" | \"onChunk\",\n snapshot: unknown\n ): Promise<void> {\n if (!this.extensionManager) return;\n const subscribers = this.extensionManager.getHookSubscribers(hookName);\n if (subscribers.length === 0) return;\n\n for (const sub of subscribers) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n sub.entrypoint.hook(hookName, snapshot),\n new Promise<string>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(`Hook timeout: ${sub.name}`)),\n this.hookTimeout\n );\n })\n ]);\n } catch (err) {\n console.warn(\n `[Think] Extension \"${sub.name}\" ${hookName} failed:`,\n err instanceof Error ? err.message : err\n );\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n }\n\n /**\n * Wrap each tool's `execute` function so the agent's `beforeToolCall`\n * hook is consulted before the tool runs. The hook can return a\n * `ToolCallDecision` to:\n *\n * - `allow` (default if `void` is returned) — run the original\n * `execute`, optionally with a substituted `input`.\n * - `block` — skip `execute` and return `reason` (or a default string)\n * as the tool result. The model sees this as the tool's output.\n * - `substitute` — skip `execute` and return `output` directly. The\n * model sees this as the tool's output.\n *\n * The wrapped `execute` also dispatches the `beforeToolCall`\n * observation snapshot to subscribed extensions. `afterToolCall` is\n * still wired through the AI SDK's `experimental_onToolCallFinish`\n * callback so we get accurate `durationMs` and proper success/error\n * discrimination — `block` and `substitute` outcomes show up as\n * `success: true` with the substituted output; uncaught throws from\n * the original `execute` show up as `success: false` with the error.\n *\n * Tools without an `execute` (output-schema-only tools, client tools\n * routed via `needsApproval`) are left untouched.\n *\n * **Streaming tools (AsyncIterable):** the AI SDK supports tools whose\n * `execute` returns `AsyncIterable<output>` to emit preliminary\n * results before a final value. This works whether the iterator is\n * returned directly (sync function, `async function*`) or wrapped in\n * a Promise (`async function execute(...) { return makeIter(); }`).\n * Because the wrapper must `await beforeToolCall` first, preliminary\n * chunks are collapsed — only the *final* yielded value reaches the\n * model. If you need true preliminary streaming, override\n * `getTools()` to provide such tools and avoid using `beforeToolCall`\n * for them (or accept the collapse).\n */\n private _wrapToolsWithDecision(tools: ToolSet): ToolSet {\n const wrapped: ToolSet = {};\n for (const [toolName, originalTool] of Object.entries(tools)) {\n const t = originalTool as Record<string, unknown>;\n const originalExecute = t.execute as\n | ((input: unknown, options: unknown) => unknown | Promise<unknown>)\n | undefined;\n if (typeof originalExecute !== \"function\") {\n wrapped[toolName] = originalTool;\n continue;\n }\n\n const isDynamic = t.type === \"dynamic\";\n\n const wrappedExecute = async (\n input: unknown,\n options: {\n toolCallId: string;\n messages: ModelMessage[];\n abortSignal?: AbortSignal;\n experimental_context?: unknown;\n }\n ): Promise<unknown> => {\n // Build the discriminated `TypedToolCall`-shaped context.\n const toolCallBase = {\n type: \"tool-call\" as const,\n toolCallId: options.toolCallId,\n toolName,\n input,\n ...(isDynamic ? { dynamic: true as const } : {})\n };\n\n const ctx = {\n ...toolCallBase,\n stepNumber: undefined,\n messages: options.messages,\n abortSignal: options.abortSignal\n } as ToolCallContext;\n\n // Subclass decision first.\n const decision = await this.beforeToolCall(ctx);\n\n // Extension observation dispatch — runs after the subclass so\n // extensions see whatever effect the subclass had on the\n // decision shape (input substitution shows up in the snapshot).\n const dispatchInput =\n decision && decision.action === \"allow\" && decision.input\n ? decision.input\n : input;\n await this._pipelineExtensionToolCallStart({\n toolCall: {\n ...toolCallBase,\n input: dispatchInput\n } as TypedToolCall<ToolSet>,\n stepNumber: undefined\n });\n\n // Resolve the decision.\n if (!decision || decision.action === \"allow\") {\n const finalInput = decision?.input ?? input;\n // Await before inspecting so we detect AsyncIterable returns\n // whether the original `execute` returned them directly (sync\n // function or `async function*`) or wrapped in a Promise (a\n // plain async function that returns an iterator). Without the\n // await, `Symbol.asyncIterator in result` would be false for\n // any `Promise<AsyncIterable>`, the collapse below would be\n // skipped, and the AI SDK would treat the iterator instance\n // itself as the final output value (broken).\n const result = await originalExecute(finalInput, options);\n // If the resolved value is an AsyncIterable (streaming tool\n // emitting preliminary outputs), collapse to the last yielded\n // value. We trade preliminary streaming for `beforeToolCall`\n // interception support.\n if (\n result != null &&\n typeof result === \"object\" &&\n Symbol.asyncIterator in (result as object)\n ) {\n let last: unknown;\n for await (const part of result as AsyncIterable<unknown>) {\n last = part;\n }\n return last;\n }\n return result;\n }\n if (decision.action === \"block\") {\n return (\n decision.reason ??\n `Tool \"${toolName}\" was blocked by beforeToolCall.`\n );\n }\n // substitute\n return decision.output;\n };\n\n wrapped[toolName] = {\n ...(originalTool as object),\n execute: wrappedExecute\n } as ToolSet[string];\n }\n return wrapped;\n }\n\n private async _pipelineExtensionToolCallStart(event: {\n toolCall: TypedToolCall<ToolSet>;\n stepNumber: number | undefined;\n }): Promise<void> {\n if (!this.extensionManager) return;\n if (this.extensionManager.getHookSubscribers(\"beforeToolCall\").length === 0)\n return;\n const { createToolCallStartSnapshot } =\n await import(\"./extensions/hook-proxy\");\n await this._dispatchExtensionObservation(\n \"beforeToolCall\",\n createToolCallStartSnapshot(event)\n );\n }\n\n private async _pipelineExtensionToolCallFinish(event: {\n toolCall: TypedToolCall<ToolSet>;\n stepNumber: number | undefined;\n durationMs: number;\n success: boolean;\n output?: unknown;\n error?: unknown;\n }): Promise<void> {\n if (!this.extensionManager) return;\n if (this.extensionManager.getHookSubscribers(\"afterToolCall\").length === 0)\n return;\n const { createToolCallFinishSnapshot } =\n await import(\"./extensions/hook-proxy\");\n await this._dispatchExtensionObservation(\n \"afterToolCall\",\n createToolCallFinishSnapshot(event)\n );\n }\n\n private async _pipelineExtensionStepFinish(\n event: StepContext\n ): Promise<void> {\n if (!this.extensionManager) return;\n if (this.extensionManager.getHookSubscribers(\"onStepFinish\").length === 0)\n return;\n const { createStepFinishSnapshot } =\n await import(\"./extensions/hook-proxy\");\n await this._dispatchExtensionObservation(\n \"onStepFinish\",\n createStepFinishSnapshot(event)\n );\n }\n\n private async _pipelineExtensionChunk(event: ChunkContext): Promise<void> {\n if (!this.extensionManager) return;\n if (this.extensionManager.getHookSubscribers(\"onChunk\").length === 0)\n return;\n const { createChunkSnapshot } = await import(\"./extensions/hook-proxy\");\n await this._dispatchExtensionObservation(\n \"onChunk\",\n createChunkSnapshot(event as { chunk: { type: string } })\n );\n }\n\n // ── Host bridge methods (called by HostBridgeLoopback via DO RPC) ──\n\n async _hostReadFile(path: string): Promise<string | null> {\n return (await this.workspace.readFile(path)) ?? null;\n }\n\n async _hostWriteFile(path: string, content: string): Promise<void> {\n await this.workspace.writeFile(path, content);\n }\n\n async _hostDeleteFile(path: string): Promise<boolean> {\n try {\n await this.workspace.rm(path);\n return true;\n } catch {\n return false;\n }\n }\n\n async _hostListFiles(\n dir: string\n ): Promise<\n Array<{ name: string; type: string; size: number; path: string }>\n > {\n const entries = await this.workspace.readDir(dir);\n return entries.map((e) => ({\n name: e.name,\n type: e.type,\n size: e.size ?? 0,\n path: e.path ?? `${dir}/${e.name}`\n }));\n }\n\n async _hostGetContext(label: string): Promise<string | null> {\n const block = this.session.getContextBlock(label);\n return block?.content ?? null;\n }\n\n async _hostSetContext(label: string, content: string): Promise<void> {\n await this.session.replaceContextBlock(label, content);\n }\n\n async _hostGetMessages(\n limit?: number\n ): Promise<Array<{ id: string; role: string; content: string }>> {\n const history = this.messages;\n const sliced =\n limit !== undefined && limit !== null\n ? limit <= 0\n ? []\n : history.slice(-limit)\n : history;\n return sliced.map((m) => ({\n id: m.id,\n role: m.role,\n content: m.parts\n .filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n .map((p) => p.text)\n .join(\"\")\n }));\n }\n\n async _hostSendMessage(content: string): Promise<void> {\n const msg = {\n id: crypto.randomUUID(),\n role: \"user\" as const,\n parts: [{ type: \"text\" as const, text: content }]\n };\n // Append directly to session — do NOT route through saveMessages,\n // which enqueues a full turn via TurnQueue and would deadlock if\n // called during an active turn (tool execution → host.sendMessage\n // → saveMessages → TurnQueue.enqueue → awaits current turn → deadlock).\n // The injected message is visible in the next turn's history.\n await this._appendMessageToHistory(msg);\n }\n\n async _hostGetSessionInfo(): Promise<{\n messageCount: number;\n }> {\n return {\n messageCount: this.messages.length\n };\n }\n\n // ── Sub-agent RPC entry point ───────────────────────────────────\n\n /**\n * Run a chat turn: persist the user message, run the agentic loop,\n * stream UIMessageChunk events via callback, and persist the\n * assistant's response.\n *\n * @param userMessage The user's message (string or UIMessage)\n * @param callback Streaming callback (typically an RpcTarget from the parent)\n * @param options Optional chat options (e.g. AbortSignal)\n */\n async chat(\n userMessage: string | UIMessage,\n callback: StreamCallback,\n options?: ChatOptions\n ): Promise<void> {\n const requestId = crypto.randomUUID();\n const abortSignal = this._aborts.getSignal(requestId);\n const detachExternal = this._aborts.linkExternal(\n requestId,\n options?.signal\n );\n const ignoredTools = (options as { tools?: unknown } | undefined)?.tools;\n if (\n ignoredTools != null &&\n typeof ignoredTools === \"object\" &&\n Object.keys(ignoredTools).length > 0\n ) {\n console.warn(\n \"[Think] chat() no longer accepts options.tools. Define durable tools on the child agent with getTools(), or use runAgentTool()/agentTool() for parent-child orchestration.\"\n );\n }\n\n try {\n await callback.onStart({ requestId });\n await this.keepAliveWhile(async () => {\n await this._turnQueue.enqueue(requestId, async () => {\n const userMsg: UIMessage =\n typeof userMessage === \"string\"\n ? {\n id: crypto.randomUUID(),\n role: \"user\",\n parts: [{ type: \"text\", text: userMessage }]\n }\n : userMessage;\n\n await this._appendMessageToHistory(userMsg);\n this._broadcastMessages();\n\n const chatBody = async () => {\n let result: StreamableResult;\n try {\n result = await agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n continuation: false\n })\n );\n } catch (error) {\n const wrapped = this.onChatError(error, {\n stage: \"turn\",\n messagesPersisted: true\n });\n const errorMessage =\n wrapped instanceof Error ? wrapped.message : String(wrapped);\n this._emit(\"chat:request:failed\", {\n stage: \"turn\",\n messagesPersisted: true,\n error: errorMessage\n });\n await callback.onError(errorMessage);\n return;\n }\n\n await this._streamResultToRpcCallback(\n requestId,\n result,\n callback,\n abortSignal\n );\n };\n\n if (this.chatRecovery) {\n await this._runChatRecoveryFiber(requestId, false, chatBody);\n } else {\n await chatBody();\n }\n });\n });\n } finally {\n detachExternal();\n this._aborts.remove(requestId);\n }\n }\n\n // ── Message access ──────────────────────────────────────────────\n\n /** Get the conversation history as UIMessage[]. */\n async getMessages(): Promise<UIMessage[]> {\n return this.messages.slice();\n }\n\n /** Clear all messages from storage. */\n async clearMessages(): Promise<void> {\n this.resetTurnState();\n await this._clearHistory();\n this._broadcast({ type: MSG_CHAT_CLEAR });\n }\n\n private _ensureAgentToolChildRunTable(): void {\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_agent_tool_child_runs (\n run_id TEXT PRIMARY KEY,\n request_id TEXT,\n stream_id TEXT,\n status TEXT NOT NULL,\n summary TEXT,\n output_json TEXT,\n error_message TEXT,\n started_at INTEGER NOT NULL,\n completed_at INTEGER\n )\n `;\n\n this._addAgentToolChildRunColumnIfMissing(\n \"ALTER TABLE cf_agent_tool_child_runs ADD COLUMN output_json TEXT\"\n );\n }\n\n private _addAgentToolChildRunColumnIfMissing(sql: string): void {\n try {\n this.ctx.storage.sql.exec(sql);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (!message.toLowerCase().includes(\"duplicate column\")) {\n throw error;\n }\n }\n }\n\n private _readAgentToolChildRun(runId: string): AgentToolChildRunRow | null {\n this._ensureAgentToolChildRunTable();\n const rows = this.sql<AgentToolChildRunRow>`\n SELECT run_id, request_id, stream_id, status, summary, output_json,\n error_message, started_at, completed_at\n FROM cf_agent_tool_child_runs\n WHERE run_id = ${runId}\n LIMIT 1\n `;\n return rows[0] ?? null;\n }\n\n private _inspectionFromChildRow<Output>(\n row: AgentToolChildRunRow,\n output?: Output\n ): AgentToolRunInspection<Output> {\n const storedOutput =\n row.output_json === null\n ? output\n : (Think._parseAgentToolOutput(row.output_json) as Output);\n\n return {\n runId: row.run_id,\n status: row.status,\n requestId: row.request_id ?? undefined,\n streamId: row.stream_id ?? undefined,\n output: storedOutput,\n summary: row.summary ?? undefined,\n error: row.error_message ?? undefined,\n startedAt: row.started_at,\n completedAt: row.completed_at ?? undefined\n };\n }\n\n protected formatAgentToolInput(input: unknown): UIMessage {\n const text =\n typeof input === \"string\" ? input : JSON.stringify(input, null, 2);\n return {\n id: crypto.randomUUID(),\n role: \"user\",\n parts: [{ type: \"text\", text }]\n };\n }\n\n protected getAgentToolOutput(_runId: string): unknown {\n return undefined;\n }\n\n protected getAgentToolSummary(runId: string, output: unknown): string {\n const text = this._getAgentToolFinalText(runId);\n if (text) return text;\n if (typeof output === \"string\") return output;\n if (output !== undefined) {\n try {\n return JSON.stringify(output);\n } catch {\n return String(output);\n }\n }\n return \"\";\n }\n\n async startAgentToolRun(\n input: unknown,\n options: { runId: string }\n ): Promise<AgentToolRunInspection> {\n const existing = this._readAgentToolChildRun(options.runId);\n if (existing) return this._inspectionFromChildRow(existing);\n\n const startedAt = Date.now();\n this.sql`\n INSERT INTO cf_agent_tool_child_runs (run_id, status, started_at)\n VALUES (${options.runId}, 'starting', ${startedAt})\n `;\n\n const controller = new AbortController();\n this._agentToolAbortControllers.set(options.runId, controller);\n this._agentToolLiveSequences.set(options.runId, 0);\n this._agentToolPreTurnAssistantIds.set(\n options.runId,\n new Set(\n this.messages.filter((m) => m.role === \"assistant\").map((m) => m.id)\n )\n );\n\n const epoch = this._turnQueue.generation;\n void this.keepAliveWhile(async () => {\n try {\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET status = 'running'\n WHERE run_id = ${options.runId} AND status = 'starting'\n `;\n const result = await this.saveMessages(\n [this.formatAgentToolInput(input)],\n {\n signal: controller.signal\n }\n );\n const streamId =\n this._resumableStream\n .getAllStreamMetadata()\n .find((m) => m.request_id === result.requestId)?.id ?? null;\n const output = this.getAgentToolOutput(options.runId);\n const summary = this.getAgentToolSummary(options.runId, output);\n const streamError =\n result.error ?? this._agentToolLastErrors.get(options.runId);\n const skipped =\n result.status === \"skipped\" ||\n (result.status === \"aborted\" && this._turnQueue.generation !== epoch);\n const status: AgentToolChildRunStatus =\n result.status === \"error\" || skipped || streamError\n ? \"error\"\n : result.status === \"aborted\"\n ? \"aborted\"\n : \"completed\";\n const error: string | null =\n status === \"error\"\n ? (streamError ??\n \"Agent tool run was skipped before the child could finish.\")\n : null;\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET request_id = ${result.requestId},\n stream_id = ${streamId},\n status = ${status},\n summary = ${summary},\n output_json = ${Think._stringifyAgentToolOutput(output)},\n error_message = ${error},\n completed_at = ${Date.now()}\n WHERE run_id = ${options.runId}\n AND completed_at IS NULL\n `;\n } catch (error) {\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET status = 'error',\n error_message = ${error instanceof Error ? error.message : String(error)},\n completed_at = ${Date.now()}\n WHERE run_id = ${options.runId}\n AND completed_at IS NULL\n `;\n } finally {\n this._agentToolAbortControllers.delete(options.runId);\n this._agentToolForwarders.delete(options.runId);\n this._agentToolLiveSequences.delete(options.runId);\n this._agentToolLastErrors.delete(options.runId);\n this._agentToolPreTurnAssistantIds.delete(options.runId);\n for (const close of this._agentToolClosers.get(options.runId) ?? []) {\n close();\n }\n this._agentToolClosers.delete(options.runId);\n }\n });\n\n return {\n runId: options.runId,\n status: \"running\",\n startedAt\n };\n }\n\n async cancelAgentToolRun(runId: string, reason?: unknown): Promise<void> {\n const row = this._readAgentToolChildRun(runId);\n if (!row || row.completed_at !== null) return;\n this._agentToolAbortControllers.get(runId)?.abort(reason);\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET status = 'aborted',\n error_message = ${reason instanceof Error ? reason.message : reason === undefined ? null : String(reason)},\n completed_at = ${Date.now()}\n WHERE run_id = ${runId}\n AND status NOT IN ('completed', 'error', 'aborted')\n `;\n }\n\n /**\n * Classify any in-flight chat-recovery on this child facet (#1630). A child\n * facet is dedicated to a single agent-tool run, so any recovery incident is\n * that run's. `detected`/`scheduled`/`attempting` mean recovery is still\n * resolving the interrupted turn; `exhausted`/`failed` mean it gave up; a\n * completed recovery deletes its incident.\n */\n private async _classifyAgentToolChildRecovery(): Promise<\n \"in-progress\" | \"failed\" | \"none\"\n > {\n const entries = await this.ctx.storage.list<ChatRecoveryIncident>({\n prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX\n });\n let failed = false;\n for (const incident of entries.values()) {\n if (\n incident.status === \"detected\" ||\n incident.status === \"scheduled\" ||\n incident.status === \"attempting\"\n ) {\n return \"in-progress\";\n }\n if (incident.status === \"exhausted\" || incident.status === \"failed\") {\n failed = true;\n }\n }\n return failed ? \"failed\" : \"none\";\n }\n\n async inspectAgentToolRun(\n runId: string\n ): Promise<AgentToolRunInspection | null> {\n let row = this._readAgentToolChildRun(runId);\n if (!row) return null;\n // A `running`/`starting` row with no live abort controller means the\n // original in-isolate run is gone (e.g. the parent was evicted while this\n // child run was in flight, #1630) — lazily reconcile it from the child's\n // own durable recovery before reporting.\n if (this._isStaleAgentToolChildRun(row)) {\n await this._reconcileStaleAgentToolChildRun(runId);\n row = this._readAgentToolChildRun(runId) ?? row;\n }\n return this._inspectionFromChildRow(row, this.getAgentToolOutput(runId));\n }\n\n private _isStaleAgentToolChildRun(row: AgentToolChildRunRow): boolean {\n return (\n (row.status === \"running\" || row.status === \"starting\") &&\n row.completed_at === null &&\n !this._agentToolAbortControllers.has(row.run_id)\n );\n }\n\n /**\n * Reconcile a stale (post-eviction) child run row from the child's own\n * durable recovery (#1630). The child facet self-heals its interrupted turn\n * via `chatRecovery`, but that path never writes the run row, so without this\n * the row strands `running` and the parent can only collect `interrupted`.\n *\n * Persisting the terminal here (rather than only computing it) is intentional:\n * it's a lazy materialization of the run's true terminal that also lets a\n * tailing parent's stream close promptly and makes subsequent inspects cheap.\n * While recovery is still resolving (active stream or in-progress incident)\n * the row is left `running` so the parent's bounded re-attach keeps waiting.\n */\n private async _reconcileStaleAgentToolChildRun(runId: string): Promise<void> {\n const recovery = await this._classifyAgentToolChildRecovery();\n if (recovery === \"in-progress\" || this._resumableStream.hasActiveStream()) {\n return;\n }\n // A settled recovery that produced an assistant turn is `completed`, even if\n // that turn ended on a tool result with no final text — keying off text\n // alone would mis-seal a legitimately-finished (but text-less) run as\n // `error`. `getAgentToolSummary` already falls back to \"\" when there is no\n // final text.\n const recoveredTurn =\n recovery !== \"failed\" && this._hasRecoveredAgentToolAssistantTurn(runId);\n if (recoveredTurn) {\n const output = this.getAgentToolOutput(runId);\n const summary = this.getAgentToolSummary(runId, output);\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET status = 'completed',\n summary = ${summary},\n output_json = ${Think._stringifyAgentToolOutput(output)},\n error_message = null,\n completed_at = ${Date.now()}\n WHERE run_id = ${runId} AND completed_at IS NULL\n `;\n } else {\n const error =\n \"Agent tool run was interrupted before the child could finish.\";\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET status = 'error',\n error_message = ${error},\n completed_at = ${Date.now()}\n WHERE run_id = ${runId} AND completed_at IS NULL\n `;\n }\n this._finalizeAgentToolChildRunTailers(runId);\n }\n\n /** Release a re-attached run's live tail + per-run streaming bookkeeping. */\n private _finalizeAgentToolChildRunTailers(runId: string): void {\n for (const close of this._agentToolClosers.get(runId) ?? []) {\n close();\n }\n this._agentToolClosers.delete(runId);\n this._agentToolForwarders.delete(runId);\n this._agentToolLiveSequences.delete(runId);\n this._agentToolLastErrors.delete(runId);\n this._agentToolPreTurnAssistantIds.delete(runId);\n }\n\n async getAgentToolChunks(\n runId: string,\n options?: { afterSequence?: number }\n ): Promise<AgentToolStoredChunk[]> {\n const row = this._readAgentToolChildRun(runId);\n if (!row?.stream_id) return [];\n this._resumableStream.flushBuffer();\n return this._resumableStream\n .getStreamChunks(row.stream_id)\n .filter((chunk) => chunk.chunk_index > (options?.afterSequence ?? -1))\n .map((chunk) => ({ sequence: chunk.chunk_index, body: chunk.body }));\n }\n\n async tailAgentToolRun(\n runId: string,\n options?: { afterSequence?: number; signal?: AbortSignal }\n ): Promise<ReadableStream<AgentToolStoredChunk>> {\n const self = this;\n const signal = options?.signal;\n let closed = false;\n let forward: ((chunk: AgentToolStoredChunk) => void) | undefined;\n const detach = () => {\n if (forward) {\n self._agentToolForwarders.get(runId)?.delete(forward);\n forward = undefined;\n }\n };\n const stream = new ReadableStream<Uint8Array>({\n async start(controller) {\n const close = () => {\n if (closed) return;\n closed = true;\n detach();\n try {\n controller.close();\n } catch {\n // Already closed.\n }\n };\n // Honor an external abort (e.g. a bounded re-attach budget) so a parent\n // tailing a still-running child can stop waiting without cancelling the\n // child itself — closing the stream unblocks the parent's forwarder.\n if (signal?.aborted) {\n close();\n return;\n }\n signal?.addEventListener(\"abort\", close, { once: true });\n\n const replayed = await self.getAgentToolChunks(runId, options);\n for (const chunk of replayed) {\n if (closed) return;\n controller.enqueue(\n agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\\n`)\n );\n }\n const lastReplay = replayed[replayed.length - 1]?.sequence;\n if (lastReplay !== undefined) {\n self._agentToolLiveSequences.set(runId, lastReplay + 1);\n }\n const row = self._readAgentToolChildRun(runId);\n if (!row || row.completed_at !== null) {\n close();\n return;\n }\n forward = (chunk: AgentToolStoredChunk) => {\n if (closed || chunk.sequence <= (options?.afterSequence ?? -1)) {\n return;\n }\n try {\n controller.enqueue(\n agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\\n`)\n );\n } catch {\n // The consumer detached (e.g. a parent's re-attach budget expired\n // and cancelled the reader) between the RPC cancel arriving and our\n // `cancel`/`close` running. Drop the chunk instead of surfacing a\n // \"Stream was cancelled\" rejection; the child run is unaffected.\n closed = true;\n detach();\n }\n };\n const forwarders = self._agentToolForwarders.get(runId) ?? new Set();\n forwarders.add(forward);\n self._agentToolForwarders.set(runId, forwarders);\n const closers = self._agentToolClosers.get(runId) ?? new Set();\n closers.add(close);\n self._agentToolClosers.set(runId, closers);\n },\n cancel() {\n // A consumer detaching from the tail (e.g. a parent's bounded re-attach\n // budget expiring, via reader.cancel()) is read-only — it must NOT\n // cancel the child run. Explicit cancellation flows through\n // cancelAgentToolRun. Mirrors @cloudflare/ai-chat's read-only tail.\n closed = true;\n detach();\n }\n });\n return stream as unknown as ReadableStream<AgentToolStoredChunk>;\n }\n\n private static _stringifyAgentToolOutput(output: unknown): string | null {\n if (output === undefined) return null;\n try {\n return JSON.stringify(output);\n } catch {\n return JSON.stringify(String(output));\n }\n }\n\n private static _parseAgentToolOutput(value: string | null): unknown {\n if (value === null) return undefined;\n try {\n return JSON.parse(value);\n } catch {\n return undefined;\n }\n }\n\n /**\n * Whether the run produced an assistant turn (text or tool-only). Used by the\n * post-eviction reconcile to mark a settled run `completed` even when it ended\n * without final text. A dedicated child facet starts with no assistant\n * messages, so a missing in-memory pre-turn snapshot is treated as empty.\n */\n private _hasRecoveredAgentToolAssistantTurn(runId: string): boolean {\n const before =\n this._agentToolPreTurnAssistantIds.get(runId) ?? new Set<string>();\n return this.messages.some(\n (msg) => msg.role === \"assistant\" && !before.has(msg.id)\n );\n }\n\n private _getAgentToolFinalText(runId: string): string | null {\n // A child facet is dedicated to a single agent-tool run, so any assistant\n // message it holds is that run's output. When the pre-turn snapshot is\n // missing — e.g. reconciling after a real eviction, where the in-memory\n // snapshot died with the original isolate (#1630) — treat it as empty so\n // the recovered transcript's assistant text is still surfaced as the\n // summary instead of being lost.\n const before =\n this._agentToolPreTurnAssistantIds.get(runId) ?? new Set<string>();\n for (const msg of this.messages) {\n if (msg.role !== \"assistant\" || before.has(msg.id)) continue;\n const text = msg.parts\n .map((part) => (part.type === \"text\" ? part.text : \"\"))\n .filter((part) => part.length > 0)\n .join(\"\\n\");\n if (text.length > 0) return text;\n }\n return null;\n }\n\n // ── Declarative scheduled tasks ─────────────────────────────────\n\n private _ensureDeclaredScheduledTasksTable(): void {\n if (this._declaredScheduledTasksTableEnsured) return;\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_think_scheduled_tasks (\n owner_key TEXT NOT NULL,\n task_id TEXT NOT NULL,\n schedule_hash TEXT NOT NULL,\n task_hash TEXT NOT NULL,\n schedule_id TEXT,\n next_run_at INTEGER,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n PRIMARY KEY (owner_key, task_id)\n )\n `;\n this._declaredScheduledTasksTableEnsured = true;\n }\n\n private _readDeclaredScheduledTaskRow(\n taskId: string\n ): DeclaredScheduledTaskRow | null {\n this._ensureDeclaredScheduledTasksTable();\n const ownerKey = this._declaredScheduleOwnerKey();\n const rows = this.sql<DeclaredScheduledTaskRow>`\n SELECT owner_key, task_id, schedule_hash, task_hash, schedule_id,\n next_run_at, created_at, updated_at\n FROM cf_think_scheduled_tasks\n WHERE task_id = ${taskId}\n AND owner_key = ${ownerKey}\n LIMIT 1\n `;\n return rows[0] ?? null;\n }\n\n private _listDeclaredScheduledTaskRows(): DeclaredScheduledTaskRow[] {\n this._ensureDeclaredScheduledTasksTable();\n const ownerKey = this._declaredScheduleOwnerKey();\n return this.sql<DeclaredScheduledTaskRow>`\n SELECT owner_key, task_id, schedule_hash, task_hash, schedule_id,\n next_run_at, created_at, updated_at\n FROM cf_think_scheduled_tasks\n WHERE owner_key = ${ownerKey}\n ORDER BY task_id ASC\n `;\n }\n\n private _updateDeclaredScheduledTaskSchedule(\n task: NormalizedDeclaredTask,\n ownerKey: string,\n scheduled: { scheduleId: string; scheduledFor: number },\n updatedAt = Date.now()\n ): void {\n this.sql`\n UPDATE cf_think_scheduled_tasks\n SET schedule_hash = ${task.scheduleHash},\n task_hash = ${task.taskHash},\n schedule_id = ${scheduled.scheduleId},\n next_run_at = ${scheduled.scheduledFor},\n updated_at = ${updatedAt}\n WHERE owner_key = ${ownerKey}\n AND task_id = ${task.taskId}\n `;\n }\n\n private async _normalizeDeclaredScheduledTasks(\n tasks: ThinkScheduledTasks,\n defaultTimezone: string | undefined\n ): Promise<Map<string, NormalizedDeclaredTask>> {\n const normalized = new Map<string, NormalizedDeclaredTask>();\n for (const [taskId, task] of Object.entries(tasks)) {\n if (!/^[A-Za-z0-9_-]+$/.test(taskId)) {\n throw new Error(\n `Invalid scheduled task id \"${taskId}\"; use letters, numbers, \"_\" or \"-\"`\n );\n }\n const schedule = parseDeclaredTaskSchedule(\n task.schedule,\n task.timezone,\n defaultTimezone\n );\n const hasPrompt = \"prompt\" in task && task.prompt !== undefined;\n const hasHandler = \"handler\" in task && task.handler !== undefined;\n if (hasPrompt === hasHandler) {\n throw new Error(\n `Scheduled task \"${taskId}\" must define exactly one of prompt or handler`\n );\n }\n const scheduleHash = stableHash({\n schedule,\n retry: task.retry\n });\n const actionHash = hasPrompt\n ? {\n type: \"prompt\",\n value: typeof task.prompt === \"string\" ? task.prompt : \"<function>\"\n }\n : { type: \"handler\" };\n const taskHash = stableHash({\n scheduleHash,\n action: actionHash,\n metadata: task.metadata\n });\n normalized.set(taskId, {\n taskId,\n ...(hasPrompt ? { prompt: task.prompt } : {}),\n ...(hasHandler ? { handler: task.handler } : {}),\n schedule,\n retry: task.retry,\n metadata: task.metadata,\n scheduleHash,\n taskHash\n });\n }\n return normalized;\n }\n\n private async _declaredScheduledTasksForNow(): Promise<\n Map<string, NormalizedDeclaredTask>\n > {\n const defaultTimezone = await this.getDefaultTimezone();\n const resolvedDefaultTimezone =\n defaultTimezone === undefined\n ? undefined\n : validateTimezone(defaultTimezone);\n return this._normalizeDeclaredScheduledTasks(\n await this.getScheduledTasks(),\n resolvedDefaultTimezone\n );\n }\n\n private _declaredScheduleOwnerKey(): string {\n return stableHash(this.selfPath);\n }\n\n private _declaredScheduleValidationError(\n rawSchedule: string,\n taskTimezone?: string,\n defaultTimezone?: string\n ): string | null {\n const resolvedDefaultTimezone =\n defaultTimezone === undefined\n ? undefined\n : validateTimezone(defaultTimezone);\n const result = tryParseDeclaredTaskSchedule(\n rawSchedule,\n taskTimezone,\n resolvedDefaultTimezone\n );\n return result.ok ? null : result.error;\n }\n\n private _nextDeclaredScheduleTimeForConfig(\n rawSchedule: string,\n now: Date,\n options: {\n taskTimezone?: string;\n defaultTimezone?: string;\n previousScheduledFor?: number;\n } = {}\n ): Date {\n const resolvedDefaultTimezone =\n options.defaultTimezone === undefined\n ? undefined\n : validateTimezone(options.defaultTimezone);\n return nextDeclaredScheduleTime(\n parseDeclaredTaskSchedule(\n rawSchedule,\n options.taskTimezone,\n resolvedDefaultTimezone\n ),\n now,\n options.previousScheduledFor\n );\n }\n\n private async _reconcileDeclaredScheduledTasks(): Promise<void> {\n const tasks = await this._declaredScheduledTasksForNow();\n this._ensureDeclaredScheduledTasksTable();\n const ownerKey = this._declaredScheduleOwnerKey();\n const now = Date.now();\n const existing = this._listDeclaredScheduledTaskRows();\n const seen = new Set<string>();\n\n for (const [taskId, task] of tasks) {\n seen.add(taskId);\n const row = existing.find((candidate) => candidate.task_id === taskId);\n if (!row) {\n this.sql`\n INSERT INTO cf_think_scheduled_tasks (\n owner_key, task_id, schedule_hash, task_hash, schedule_id,\n next_run_at, created_at, updated_at\n )\n VALUES (\n ${ownerKey}, ${taskId}, ${task.scheduleHash}, ${task.taskHash},\n NULL, NULL, ${now}, ${now}\n )\n `;\n const scheduled = await this._scheduleDeclaredTaskOccurrence(\n task,\n new Date(now)\n );\n this._updateDeclaredScheduledTaskSchedule(\n task,\n ownerKey,\n scheduled,\n now\n );\n continue;\n }\n\n if (row.schedule_hash !== task.scheduleHash) {\n if (row.schedule_id) await this.cancelSchedule(row.schedule_id);\n this.sql`\n UPDATE cf_think_scheduled_tasks\n SET schedule_hash = ${task.scheduleHash},\n task_hash = ${task.taskHash},\n schedule_id = NULL,\n next_run_at = NULL,\n updated_at = ${now}\n WHERE owner_key = ${ownerKey}\n AND task_id = ${taskId}\n `;\n const scheduled = await this._scheduleDeclaredTaskOccurrence(\n task,\n new Date(now)\n );\n this._updateDeclaredScheduledTaskSchedule(\n task,\n ownerKey,\n scheduled,\n now\n );\n continue;\n }\n\n if (!row.schedule_id) {\n const scheduled =\n row.next_run_at === null\n ? await this._scheduleDeclaredTaskOccurrence(task, new Date(now))\n : await this._scheduleDeclaredTaskOccurrenceAt(\n task,\n row.next_run_at\n );\n this._updateDeclaredScheduledTaskSchedule(\n task,\n ownerKey,\n scheduled,\n now\n );\n continue;\n }\n\n if (row.schedule_id) {\n const schedule = await this.getScheduleById(row.schedule_id);\n if (!schedule) {\n const scheduled =\n row.next_run_at === null\n ? await this._scheduleDeclaredTaskOccurrence(task, new Date(now))\n : await this._scheduleDeclaredTaskOccurrenceAt(\n task,\n row.next_run_at\n );\n this._updateDeclaredScheduledTaskSchedule(\n task,\n ownerKey,\n scheduled,\n now\n );\n continue;\n }\n }\n\n if (row.task_hash !== task.taskHash) {\n this.sql`\n UPDATE cf_think_scheduled_tasks\n SET task_hash = ${task.taskHash}, updated_at = ${now}\n WHERE owner_key = ${ownerKey}\n AND task_id = ${taskId}\n `;\n }\n }\n\n for (const row of existing) {\n if (seen.has(row.task_id)) continue;\n if (row.schedule_id) await this.cancelSchedule(row.schedule_id);\n this.sql`\n DELETE FROM cf_think_scheduled_tasks\n WHERE owner_key = ${ownerKey}\n AND task_id = ${row.task_id}\n `;\n }\n }\n\n private async _scheduleDeclaredTaskOccurrence(\n task: NormalizedDeclaredTask,\n now: Date,\n previousScheduledFor?: number\n ): Promise<{ scheduleId: string; scheduledFor: number }> {\n const next = nextDeclaredScheduleTime(\n task.schedule,\n now,\n previousScheduledFor\n );\n return this._scheduleDeclaredTaskOccurrenceAt(task, next.getTime());\n }\n\n private async _scheduleDeclaredTaskOccurrenceAt(\n task: NormalizedDeclaredTask,\n scheduledFor: number\n ): Promise<{ scheduleId: string; scheduledFor: number }> {\n const schedule = await this.schedule<DeclaredScheduledTaskPayload>(\n new Date(scheduledFor),\n \"_runDeclaredScheduledTask\",\n {\n taskId: task.taskId,\n scheduleHash: task.scheduleHash,\n scheduledFor\n },\n { idempotent: true }\n );\n return { scheduleId: schedule.id, scheduledFor };\n }\n\n private async _advanceDeclaredScheduledTask(\n task: NormalizedDeclaredTask,\n payload: DeclaredScheduledTaskPayload,\n ownerKey: string\n ): Promise<void> {\n const scheduled = await this._scheduleDeclaredTaskOccurrence(\n task,\n new Date(),\n payload.scheduledFor\n );\n this._updateDeclaredScheduledTaskSchedule(task, ownerKey, scheduled);\n }\n\n private _declaredScheduledTaskContext(\n task: NormalizedDeclaredTask,\n payload: DeclaredScheduledTaskPayload,\n ownerKey: string\n ): ThinkScheduledTaskContext {\n const occurrenceKey = `${payload.taskId}:${payload.scheduledFor}`;\n return {\n taskId: payload.taskId,\n scheduledFor: payload.scheduledFor,\n scheduledForDate: new Date(payload.scheduledFor),\n occurrenceKey,\n idempotencyKey: `think-schedule:${ownerKey}:${occurrenceKey}`,\n schedule: task.schedule.normalizedSchedule,\n scheduleKind: task.schedule.kind,\n ...(task.schedule.kind === \"wall-clock\" && {\n timezone: task.schedule.timezone\n }),\n ...(task.metadata !== undefined && { metadata: task.metadata })\n };\n }\n\n async _runDeclaredScheduledTask(\n payload: DeclaredScheduledTaskPayload\n ): Promise<void> {\n if (\n !payload ||\n typeof payload.taskId !== \"string\" ||\n typeof payload.scheduleHash !== \"string\" ||\n typeof payload.scheduledFor !== \"number\"\n ) {\n throw new Error(\"Invalid declared scheduled task payload\");\n }\n\n const row = this._readDeclaredScheduledTaskRow(payload.taskId);\n if (!row || row.schedule_hash !== payload.scheduleHash) return;\n if (row.next_run_at !== null && row.next_run_at > payload.scheduledFor) {\n return;\n }\n\n const tasks = await this._declaredScheduledTasksForNow();\n const task = tasks.get(payload.taskId);\n if (!task || task.scheduleHash !== payload.scheduleHash) return;\n\n const ownerKey = this._declaredScheduleOwnerKey();\n const context = this._declaredScheduledTaskContext(task, payload, ownerKey);\n\n let actionError: unknown;\n try {\n await this.retry(async () => {\n if (task.prompt !== undefined) {\n const prompt =\n typeof task.prompt === \"function\"\n ? await task.prompt()\n : task.prompt;\n await this.submitMessages(\n [\n {\n id: crypto.randomUUID(),\n role: \"user\",\n parts: [{ type: \"text\", text: prompt }]\n }\n ],\n {\n idempotencyKey: context.idempotencyKey,\n metadata: {\n ...task.metadata,\n source: \"scheduled-task\",\n ownerKey,\n taskId: payload.taskId,\n scheduledFor: payload.scheduledFor,\n schedule: task.schedule.normalizedSchedule\n }\n }\n );\n } else {\n await task.handler?.(context);\n }\n }, task.retry);\n } catch (error) {\n actionError = error;\n } finally {\n await this._advanceDeclaredScheduledTask(task, payload, ownerKey);\n }\n\n if (actionError !== undefined) {\n console.error(\n `[Think] Scheduled task \"${payload.taskId}\" failed; next occurrence was still scheduled`,\n actionError\n );\n try {\n await this.onError(actionError);\n } catch {\n // Preserve recurrence even if user error handling fails.\n }\n }\n }\n\n // ── Durable programmatic submissions ───────────────────────────\n\n private _ensureSubmissionTable(): void {\n if (this._submissionTableEnsured) return;\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_think_submissions (\n submission_id TEXT PRIMARY KEY,\n idempotency_key TEXT UNIQUE,\n request_id TEXT,\n stream_id TEXT,\n status TEXT NOT NULL,\n messages_json TEXT NOT NULL,\n metadata_json TEXT,\n error_message TEXT,\n created_at INTEGER NOT NULL,\n messages_applied_at INTEGER,\n started_at INTEGER,\n completed_at INTEGER\n )\n `;\n this.sql`\n CREATE INDEX IF NOT EXISTS cf_think_submissions_status_created_idx\n ON cf_think_submissions (status, created_at, submission_id)\n `;\n this.sql`\n CREATE INDEX IF NOT EXISTS cf_think_submissions_request_status_idx\n ON cf_think_submissions (request_id, status)\n `;\n this.sql`\n CREATE INDEX IF NOT EXISTS cf_think_submissions_status_completed_idx\n ON cf_think_submissions (status, completed_at, created_at)\n `;\n this._submissionTableEnsured = true;\n }\n\n private _ensureWorkflowNotificationTable(): void {\n if (this._workflowNotificationTableEnsured) return;\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_think_workflow_notifications (\n notification_id TEXT PRIMARY KEY,\n submission_id TEXT NOT NULL,\n workflow_name TEXT NOT NULL,\n workflow_id TEXT NOT NULL,\n event_type TEXT NOT NULL,\n payload_json TEXT NOT NULL,\n attempts INTEGER NOT NULL DEFAULT 0,\n last_error TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n delivered_at INTEGER\n )\n `;\n try {\n this.ctx.storage.sql.exec(\n \"ALTER TABLE cf_think_workflow_notifications ADD COLUMN delivered_at INTEGER\"\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (!message.toLowerCase().includes(\"duplicate column\")) {\n throw error;\n }\n }\n this.sql`\n CREATE INDEX IF NOT EXISTS cf_think_workflow_notifications_created_idx\n ON cf_think_workflow_notifications (delivered_at, created_at, notification_id)\n `;\n this._workflowNotificationTableEnsured = true;\n }\n\n private _readSubmission(submissionId: string): ThinkSubmissionRow | null {\n this._ensureSubmissionTable();\n const rows = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE submission_id = ${submissionId}\n LIMIT 1\n `;\n return rows[0] ?? null;\n }\n\n private _readSubmissionByIdempotencyKey(\n idempotencyKey: string\n ): ThinkSubmissionRow | null {\n this._ensureSubmissionTable();\n const rows = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE idempotency_key = ${idempotencyKey}\n LIMIT 1\n `;\n return rows[0] ?? null;\n }\n\n private _normalizeStatusFilter(\n status?: ThinkSubmissionStatus | ThinkSubmissionStatus[]\n ): Set<ThinkSubmissionStatus> | null {\n if (!status) return null;\n return new Set(Array.isArray(status) ? status : [status]);\n }\n\n private _listSubmissionRows(\n options?: ListSubmissionsOptions\n ): ThinkSubmissionRow[] {\n this._ensureSubmissionTable();\n const limit = Math.min(Math.max(options?.limit ?? 50, 1), 100);\n const statuses = this._normalizeStatusFilter(options?.status);\n if (statuses) {\n return [...statuses]\n .flatMap((status) => this._listSubmissionRowsByStatus(status, limit))\n .sort((a, b) =>\n b.created_at === a.created_at\n ? b.submission_id.localeCompare(a.submission_id)\n : b.created_at - a.created_at\n )\n .slice(0, limit);\n }\n\n const rows = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n ORDER BY created_at DESC, submission_id DESC\n LIMIT ${limit}\n `;\n return rows;\n }\n\n private _listSubmissionRowsByStatus(\n status: ThinkSubmissionStatus,\n limit: number\n ): ThinkSubmissionRow[] {\n return this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE status = ${status}\n ORDER BY created_at DESC, submission_id DESC\n LIMIT ${limit}\n `;\n }\n\n private _inspectionFromSubmissionRow(\n row: ThinkSubmissionRow\n ): ThinkSubmissionInspection {\n const metadata = this._parseJsonObject(row.metadata_json);\n return {\n submissionId: row.submission_id,\n idempotencyKey: row.idempotency_key ?? undefined,\n requestId: row.request_id ?? undefined,\n status: row.status,\n error: row.error_message ?? undefined,\n metadata: metadata ?? undefined,\n createdAt: row.created_at,\n startedAt: row.started_at ?? undefined,\n completedAt: row.completed_at ?? undefined\n };\n }\n\n private _parseJsonObject(\n value: string | null\n ): Record<string, unknown> | null {\n if (value === null) return null;\n try {\n const parsed = JSON.parse(value) as unknown;\n if (\n parsed !== null &&\n typeof parsed === \"object\" &&\n !Array.isArray(parsed)\n ) {\n return parsed as Record<string, unknown>;\n }\n } catch {\n // Invalid metadata should not prevent inspection.\n }\n return null;\n }\n\n private _parseSubmissionMessages(value: string): UIMessage[] {\n const parsed = JSON.parse(value) as unknown;\n if (!Array.isArray(parsed)) {\n throw new Error(\"Stored submission messages are invalid\");\n }\n return parsed as UIMessage[];\n }\n\n private _serializeSubmissionMessages(messages: UIMessage[]): string {\n return JSON.stringify(\n messages.map((message) => enforceRowSizeLimit(sanitizeMessage(message)))\n );\n }\n\n private _serializeMetadata(\n metadata: Record<string, unknown> | undefined\n ): string | null {\n return metadata === undefined ? null : JSON.stringify(metadata);\n }\n\n private _readWorkflowPromptContext(\n metadata: Record<string, unknown> | null\n ): ThinkWorkflowPromptContext | null {\n const workflowPromptValue = metadata?.[THINK_WORKFLOW_PROMPT_METADATA_KEY];\n if (\n workflowPromptValue === null ||\n typeof workflowPromptValue !== \"object\" ||\n Array.isArray(workflowPromptValue)\n ) {\n return null;\n }\n const workflowPrompt = workflowPromptValue as Record<string, unknown>;\n const workflowValue = workflowPrompt.workflow;\n if (\n workflowValue === null ||\n typeof workflowValue !== \"object\" ||\n Array.isArray(workflowValue)\n ) {\n return null;\n }\n const workflowRecord = workflowValue as Record<string, unknown>;\n if (\n typeof workflowRecord.name !== \"string\" ||\n typeof workflowRecord.id !== \"string\" ||\n typeof workflowRecord.stepName !== \"string\" ||\n typeof workflowRecord.eventType !== \"string\"\n ) {\n return null;\n }\n const output = workflowPrompt.output;\n const outputRecord =\n output !== null && typeof output === \"object\" && !Array.isArray(output)\n ? (output as Record<string, unknown>)\n : null;\n return {\n workflow: {\n name: workflowRecord.name,\n id: workflowRecord.id,\n stepName: workflowRecord.stepName,\n eventType: workflowRecord.eventType\n },\n ...(outputRecord\n ? {\n output: {\n schema: outputRecord.schema\n }\n }\n : {}),\n ...(typeof workflowPrompt.fingerprint === \"string\" && {\n fingerprint: workflowPrompt.fingerprint\n })\n };\n }\n\n private async _emitSubmissionStatus(\n row: ThinkSubmissionRow,\n output?: unknown\n ): Promise<void> {\n const inspection = this._inspectionFromSubmissionRow(row);\n this._emit(\"submission:status\", {\n submissionId: inspection.submissionId,\n requestId: inspection.requestId,\n status: inspection.status\n });\n if (inspection.status === \"error\" && inspection.error) {\n this._emit(\"submission:error\", {\n submissionId: inspection.submissionId,\n requestId: inspection.requestId,\n error: inspection.error\n });\n }\n if (this._isTerminalSubmissionStatus(inspection.status)) {\n await this._enqueueWorkflowNotification(inspection, output);\n }\n await this.keepAliveWhile(async () => {\n try {\n await this.onSubmissionStatus(inspection);\n } catch (error) {\n console.error(\"[Think] onSubmissionStatus failed\", error);\n }\n });\n }\n\n protected onSubmissionStatus(\n _submission: ThinkSubmissionInspection\n ): void | Promise<void> {}\n\n private async _enqueueWorkflowNotification(\n submission: ThinkSubmissionInspection,\n output?: unknown\n ): Promise<void> {\n this._insertWorkflowNotification(submission, output);\n this._startWorkflowNotificationDrain();\n }\n\n private _insertWorkflowNotification(\n submission: ThinkSubmissionInspection,\n output?: unknown,\n override?: { status: ThinkSubmissionStatus; error: string }\n ): boolean {\n const workflowPrompt = this._readWorkflowPromptContext(\n submission.metadata ?? null\n );\n if (!workflowPrompt) return false;\n\n this._ensureWorkflowNotificationTable();\n const now = Date.now();\n const status = override?.status ?? submission.status;\n const error = override?.error ?? submission.error;\n const payload = {\n submissionId: submission.submissionId,\n status,\n ...(status === \"completed\" && { output }),\n ...(error && { error })\n };\n this.sql`\n INSERT OR IGNORE INTO cf_think_workflow_notifications (\n notification_id, submission_id, workflow_name, workflow_id, event_type,\n payload_json, attempts, last_error, created_at, updated_at, delivered_at\n )\n VALUES (\n ${`${submission.submissionId}:${workflowPrompt.workflow.eventType}`},\n ${submission.submissionId},\n ${workflowPrompt.workflow.name},\n ${workflowPrompt.workflow.id},\n ${workflowPrompt.workflow.eventType},\n ${JSON.stringify(payload)},\n 0,\n NULL,\n ${now},\n ${now},\n NULL\n )\n `;\n return true;\n }\n\n private _recoverWorkflowNotifications(): void {\n this._ensureSubmissionTable();\n this._ensureWorkflowNotificationTable();\n const terminalRows = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE status IN ('aborted', 'skipped', 'error')\n ORDER BY completed_at DESC, created_at DESC\n LIMIT 100\n `;\n\n let recovered = false;\n for (const row of terminalRows) {\n const inspection = this._inspectionFromSubmissionRow(row);\n const workflowPrompt = this._readWorkflowPromptContext(\n inspection.metadata ?? null\n );\n if (!workflowPrompt) continue;\n const notificationId = `${inspection.submissionId}:${workflowPrompt.workflow.eventType}`;\n const existing = this.sql<{ notification_id: string }>`\n SELECT notification_id\n FROM cf_think_workflow_notifications\n WHERE notification_id = ${notificationId}\n LIMIT 1\n `;\n if (existing[0]) continue;\n\n recovered = this._insertWorkflowNotification(inspection) || recovered;\n }\n if (recovered) this._startWorkflowNotificationDrain();\n }\n\n private _startWorkflowNotificationDrain(): void {\n void this.keepAliveWhile(() => this._drainWorkflowNotifications()).catch(\n (error) => {\n console.error(\"[Think] Failed to drain workflow notifications\", error);\n void this._scheduleWorkflowNotificationAlarm();\n }\n );\n }\n\n private _hasPendingWorkflowNotifications(): boolean {\n this._ensureWorkflowNotificationTable();\n const pending = this.sql<{ notification_id: string }>`\n SELECT notification_id\n FROM cf_think_workflow_notifications\n WHERE delivered_at IS NULL\n LIMIT 1\n `;\n return pending.length > 0;\n }\n\n private async _drainWorkflowNotifications(): Promise<void> {\n if (this._drainingWorkflowNotifications) return;\n this._ensureWorkflowNotificationTable();\n this._drainingWorkflowNotifications = true;\n try {\n const rows = this.sql<ThinkWorkflowNotificationRow>`\n SELECT notification_id, submission_id, workflow_name, workflow_id,\n event_type, payload_json, attempts, last_error, created_at,\n updated_at, delivered_at\n FROM cf_think_workflow_notifications\n WHERE delivered_at IS NULL\n ORDER BY created_at ASC, notification_id ASC\n LIMIT 25\n `;\n for (const row of rows) {\n try {\n const payload = JSON.parse(row.payload_json) as unknown;\n await this.sendWorkflowEvent(\n row.workflow_name as string & {},\n row.workflow_id,\n {\n type: row.event_type,\n payload\n }\n );\n this.sql`\n UPDATE cf_think_workflow_notifications\n SET payload_json = '{}',\n last_error = NULL,\n updated_at = ${Date.now()},\n delivered_at = ${Date.now()}\n WHERE notification_id = ${row.notification_id}\n AND delivered_at IS NULL\n `;\n } catch (error) {\n this.sql`\n UPDATE cf_think_workflow_notifications\n SET attempts = attempts + 1,\n last_error = ${error instanceof Error ? error.message : String(error)},\n updated_at = ${Date.now()}\n WHERE notification_id = ${row.notification_id}\n `;\n }\n }\n } finally {\n this._drainingWorkflowNotifications = false;\n }\n await this._scheduleWorkflowNotificationAlarm();\n }\n\n private async _scheduleWorkflowNotificationAlarm(): Promise<void> {\n this._ensureWorkflowNotificationTable();\n const pending = this.sql<{ attempts: number }>`\n SELECT attempts\n FROM cf_think_workflow_notifications\n WHERE delivered_at IS NULL\n ORDER BY created_at ASC, notification_id ASC\n LIMIT 1\n `;\n if (!pending[0]) return;\n const delayMs = Math.min(\n 5 * 60 * 1000,\n 1000 * 2 ** Math.min(pending[0].attempts, 8)\n );\n const nextAlarm = Date.now() + delayMs;\n const existingAlarm = await this.ctx.storage.getAlarm();\n if (existingAlarm === null || existingAlarm > nextAlarm) {\n await this.ctx.storage.setAlarm(nextAlarm);\n }\n }\n\n async inspectSubmission(\n submissionId: string\n ): Promise<ThinkSubmissionInspection | null> {\n const row = this._readSubmission(submissionId);\n return row ? this._inspectionFromSubmissionRow(row) : null;\n }\n\n async listSubmissions(\n options?: ListSubmissionsOptions\n ): Promise<ThinkSubmissionInspection[]> {\n return this._listSubmissionRows(options).map((row) =>\n this._inspectionFromSubmissionRow(row)\n );\n }\n\n async deleteSubmission(submissionId: string): Promise<boolean> {\n const row = this._readSubmission(submissionId);\n if (!row || !this._isTerminalSubmissionStatus(row.status)) return false;\n this.sql`\n DELETE FROM cf_think_submissions\n WHERE submission_id = ${submissionId}\n AND status IN ('completed', 'aborted', 'skipped', 'error')\n `;\n return true;\n }\n\n async deleteSubmissions(options?: DeleteSubmissionsOptions): Promise<number> {\n this._ensureSubmissionTable();\n const statuses =\n this._normalizeStatusFilter(options?.status) ??\n new Set<ThinkSubmissionStatus>([\n \"completed\",\n \"aborted\",\n \"skipped\",\n \"error\"\n ]);\n const limit = Math.min(Math.max(options?.limit ?? 100, 1), 500);\n const completedBefore = options?.completedBefore?.getTime();\n const rows = [...statuses]\n .flatMap((status) =>\n this._listTerminalSubmissionRowsForDelete(\n status,\n limit,\n completedBefore\n )\n )\n .sort((a, b) =>\n (a.completed_at ?? a.created_at) === (b.completed_at ?? b.created_at)\n ? a.created_at - b.created_at\n : (a.completed_at ?? a.created_at) - (b.completed_at ?? b.created_at)\n )\n .slice(0, limit);\n\n let deleted = 0;\n for (const row of rows) {\n if (!this._isTerminalSubmissionStatus(row.status)) continue;\n this.sql`\n DELETE FROM cf_think_submissions\n WHERE submission_id = ${row.submission_id}\n AND status IN ('completed', 'aborted', 'skipped', 'error')\n `;\n deleted++;\n }\n return deleted;\n }\n\n private _listTerminalSubmissionRowsForDelete(\n status: ThinkSubmissionStatus,\n limit: number,\n completedBefore: number | undefined\n ): ThinkSubmissionRow[] {\n if (completedBefore === undefined) {\n return this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE status = ${status}\n ORDER BY completed_at ASC, created_at ASC\n LIMIT ${limit}\n `;\n }\n\n return this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE status = ${status}\n AND completed_at IS NOT NULL\n AND completed_at < ${completedBefore}\n ORDER BY completed_at ASC, created_at ASC\n LIMIT ${limit}\n `;\n }\n\n private _isTerminalSubmissionStatus(status: ThinkSubmissionStatus): boolean {\n return (\n status === \"completed\" ||\n status === \"aborted\" ||\n status === \"skipped\" ||\n status === \"error\"\n );\n }\n\n async cancelSubmission(\n submissionId: string,\n reason?: unknown\n ): Promise<void> {\n const row = this._readSubmission(submissionId);\n if (!row || this._isTerminalSubmissionStatus(row.status)) return;\n\n const completedAt = Date.now();\n const errorMessage =\n reason === undefined\n ? null\n : reason instanceof Error\n ? reason.message\n : String(reason);\n this._submissionAbortControllers.get(submissionId)?.abort(reason);\n if (row.request_id) {\n this.abortRequest(row.request_id, reason);\n }\n\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'aborted',\n error_message = ${errorMessage},\n completed_at = ${completedAt}\n WHERE submission_id = ${submissionId}\n AND status IN ('pending', 'running')\n `;\n\n const updated = this._readSubmission(submissionId);\n if (updated?.status === \"aborted\") {\n await this._emitSubmissionStatus(updated);\n }\n }\n\n async submitMessages(\n messages: UIMessage[],\n options?: SubmitMessagesOptions\n ): Promise<SubmitMessagesResult> {\n this._ensureSubmissionTable();\n if (messages.length === 0) {\n throw new Error(\"submitMessages requires at least one message\");\n }\n\n const existingById = options?.submissionId\n ? this._readSubmission(options.submissionId)\n : null;\n const existingByKey = options?.idempotencyKey\n ? this._readSubmissionByIdempotencyKey(options.idempotencyKey)\n : null;\n\n if (\n existingById &&\n existingByKey &&\n existingById.submission_id !== existingByKey.submission_id\n ) {\n throw new Error(\n \"submissionId and idempotencyKey refer to different submissions\"\n );\n }\n if (\n existingByKey &&\n options?.submissionId &&\n existingByKey.submission_id !== options.submissionId\n ) {\n throw new Error(\n \"submissionId and idempotencyKey refer to different submissions\"\n );\n }\n if (\n existingById &&\n options?.idempotencyKey &&\n existingById.idempotency_key !== null &&\n existingById.idempotency_key !== options.idempotencyKey\n ) {\n throw new Error(\n \"submissionId and idempotencyKey refer to different submissions\"\n );\n }\n\n const existing = existingById ?? existingByKey;\n if (existing) {\n if (existing.status === \"pending\") {\n await this._scheduleSubmissionDrain();\n this._startSubmissionDrain();\n }\n return {\n ...this._inspectionFromSubmissionRow(existing),\n accepted: false\n };\n }\n\n const submissionId = options?.submissionId ?? crypto.randomUUID();\n const requestId = submissionId;\n const now = Date.now();\n const messagesJson = this._serializeSubmissionMessages(messages);\n const metadataJson = this._serializeMetadata(options?.metadata);\n\n this.sql`\n INSERT INTO cf_think_submissions (\n submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n )\n VALUES (\n ${submissionId}, ${options?.idempotencyKey ?? null}, ${requestId},\n NULL, 'pending', ${messagesJson}, ${metadataJson}, NULL, ${now},\n NULL, NULL, NULL\n )\n `;\n\n const row = this._readSubmission(submissionId);\n if (!row) {\n throw new Error(\"Failed to persist submission\");\n }\n\n this._emit(\"submission:create\", {\n submissionId: row.submission_id,\n requestId: row.request_id ?? undefined,\n idempotencyKey: row.idempotency_key ?? undefined\n });\n await this._emitSubmissionStatus(row);\n await this._scheduleSubmissionDrain();\n this._startSubmissionDrain();\n\n return {\n ...this._inspectionFromSubmissionRow(row),\n accepted: true\n };\n }\n\n private async _scheduleSubmissionDrain(): Promise<void> {\n await this.schedule(0, \"_drainThinkSubmissions\", undefined, {\n idempotent: true\n });\n }\n\n private _startSubmissionDrain(): void {\n void this.keepAliveWhile(() => this._drainSubmissions()).catch((error) => {\n console.error(\"[Think] Failed to drain submissions\", error);\n });\n }\n\n private _hasPendingSubmissions(): boolean {\n this._ensureSubmissionTable();\n const pending = this.sql<{ submission_id: string }>`\n SELECT submission_id\n FROM cf_think_submissions\n WHERE status = 'pending'\n LIMIT 1\n `;\n return pending.length > 0;\n }\n\n async _drainThinkSubmissions(): Promise<void> {\n await this._drainSubmissions();\n }\n\n private async _drainSubmissions(): Promise<void> {\n this._ensureSubmissionTable();\n if (this._drainingSubmissions) return;\n this._drainingSubmissions = true;\n try {\n while (true) {\n const rows = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE status = 'pending'\n ORDER BY created_at ASC, submission_id ASC\n LIMIT 1\n `;\n const row = rows[0];\n if (!row) break;\n await this._runSubmission(row);\n }\n } finally {\n this._drainingSubmissions = false;\n }\n }\n\n private async _runSubmission(row: ThinkSubmissionRow): Promise<void> {\n const requestId = row.request_id ?? row.submission_id;\n const startedAt = Date.now();\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'running',\n request_id = ${requestId},\n started_at = ${startedAt}\n WHERE submission_id = ${row.submission_id}\n AND status = 'pending'\n `;\n\n const claimed = this._readSubmission(row.submission_id);\n if (!claimed || claimed.status !== \"running\") return;\n await this._emitSubmissionStatus(claimed);\n\n const controller = new AbortController();\n this._submissionAbortControllers.set(row.submission_id, controller);\n let output: unknown;\n try {\n const messages = this._parseSubmissionMessages(row.messages_json);\n const metadata = this._parseJsonObject(row.metadata_json);\n const workflowPrompt = this._readWorkflowPromptContext(metadata);\n const result = await this._runProgrammaticMessagesTurn(\n requestId,\n messages,\n {\n signal: controller.signal,\n captureProgrammaticStreamError: true,\n captureOutput: Boolean(workflowPrompt?.output),\n workflowPrompt: workflowPrompt ?? undefined,\n onMessagesApplied: () => {\n this.sql`\n UPDATE cf_think_submissions\n SET messages_applied_at = ${Date.now()}\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n AND messages_applied_at IS NULL\n `;\n }\n }\n );\n output = result.output;\n const streamId =\n this._resumableStream\n .getAllStreamMetadata()\n .find((metadata) => metadata.request_id === result.requestId)?.id ??\n null;\n const streamError = this._programmaticStreamErrors.get(result.requestId);\n const finalStatus = this._getSubmissionFinalStatus(\n result.status,\n result.error ?? streamError\n );\n const errorMessage = result.error ?? streamError ?? null;\n const completedAt = Date.now();\n this.ctx.storage.transactionSync(() => {\n this.sql`\n UPDATE cf_think_submissions\n SET status = ${finalStatus},\n request_id = ${result.requestId},\n stream_id = ${streamId},\n error_message = ${finalStatus === \"error\" ? errorMessage : null},\n completed_at = ${completedAt}\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n `;\n this._insertWorkflowNotification(\n {\n ...this._inspectionFromSubmissionRow(claimed),\n requestId: result.requestId,\n status: finalStatus,\n error:\n finalStatus === \"error\" ? (errorMessage ?? undefined) : undefined,\n completedAt\n },\n output\n );\n });\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n const completedAt = Date.now();\n this.ctx.storage.transactionSync(() => {\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'error',\n error_message = ${errorMessage},\n completed_at = ${completedAt}\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n `;\n this._insertWorkflowNotification({\n ...this._inspectionFromSubmissionRow(claimed),\n status: \"error\",\n error: errorMessage,\n completedAt\n });\n });\n } finally {\n this._programmaticStreamErrors.delete(requestId);\n this._submissionAbortControllers.delete(row.submission_id);\n const updated = this._readSubmission(row.submission_id);\n if (updated && this._isTerminalSubmissionStatus(updated.status)) {\n await this._emitSubmissionStatus(updated, output);\n }\n }\n }\n\n private _getSubmissionFinalStatus(\n resultStatus: SaveMessagesResult[\"status\"],\n streamError: string | undefined\n ): ThinkSubmissionStatus {\n return resultStatus === \"completed\" && streamError ? \"error\" : resultStatus;\n }\n\n private _markPendingSubmissionsSkipped(): ThinkSubmissionRow[] {\n this._ensureSubmissionTable();\n const pending = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE status = 'pending'\n `;\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'skipped',\n error_message = 'Submission was skipped by turn reset.',\n completed_at = ${Date.now()}\n WHERE status = 'pending'\n `;\n return pending;\n }\n\n private async _emitSkippedSubmissions(\n skipped: ThinkSubmissionRow[]\n ): Promise<void> {\n for (const row of skipped) {\n const updated = this._readSubmission(row.submission_id);\n if (updated?.status === \"skipped\") {\n await this._emitSubmissionStatus(updated);\n }\n }\n }\n\n private async _recoverSubmissionsOnStart(): Promise<void> {\n this._ensureSubmissionTable();\n\n const running = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE status = 'running'\n `;\n\n for (const row of running) {\n if (row.messages_applied_at === null) {\n let appliedState: \"none\" | \"partial\" | \"all\";\n try {\n appliedState = await this._getSubmissionMessagesAppliedState(row);\n } catch (error) {\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'error',\n error_message = ${error instanceof Error ? error.message : String(error)},\n completed_at = ${Date.now()}\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n `;\n const updated = this._readSubmission(row.submission_id);\n if (updated?.status === \"error\") {\n await this._emitSubmissionStatus(updated);\n }\n continue;\n }\n if (appliedState !== \"none\") {\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'error',\n error_message = ${appliedState === \"all\" ? \"Submission was interrupted after messages were applied.\" : \"Submission was interrupted after messages were partially applied.\"},\n completed_at = ${Date.now()}\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n `;\n const updated = this._readSubmission(row.submission_id);\n if (updated?.status === \"error\") {\n await this._emitSubmissionStatus(updated);\n }\n continue;\n }\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'pending',\n started_at = NULL\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n `;\n const updated = this._readSubmission(row.submission_id);\n if (updated?.status === \"pending\") {\n await this._emitSubmissionStatus(updated);\n }\n continue;\n }\n\n if (\n row.request_id &&\n ((this._hasRecoverableChatTurn(row.request_id) &&\n this._hasFreshRecoverableSubmissionEvidence(row)) ||\n this._hasScheduledRecoveredContinuation(row.request_id))\n ) {\n continue;\n }\n\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'error',\n error_message = 'Submission was interrupted after messages were applied.',\n completed_at = ${Date.now()}\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n `;\n const updated = this._readSubmission(row.submission_id);\n if (updated?.status === \"error\") {\n await this._emitSubmissionStatus(updated);\n }\n }\n }\n\n private async _getSubmissionMessagesAppliedState(\n row: ThinkSubmissionRow\n ): Promise<\"none\" | \"partial\" | \"all\"> {\n const messages = this._parseSubmissionMessages(row.messages_json);\n if (messages.length === 0) return \"all\";\n\n let applied = 0;\n for (const message of messages) {\n if (await this.session.getMessage(message.id)) applied++;\n }\n\n if (applied === 0) return \"none\";\n return applied === messages.length ? \"all\" : \"partial\";\n }\n\n private _hasRecoverableChatTurn(requestId: string): boolean {\n const fiberRows = this.sql<{ id: string }>`\n SELECT id FROM cf_agents_runs\n WHERE name = ${(this.constructor as typeof Think).CHAT_FIBER_NAME + \":\" + requestId}\n LIMIT 1\n `;\n if (fiberRows.length > 0) return true;\n\n const streamRows = this.sql<{ id: string }>`\n SELECT id FROM cf_ai_chat_stream_metadata\n WHERE request_id = ${requestId}\n AND status = 'streaming'\n LIMIT 1\n `;\n return streamRows.length > 0;\n }\n\n private _hasFreshRecoverableSubmissionEvidence(row: ThinkSubmissionRow) {\n if (!row.request_id) return false;\n const cutoff =\n Date.now() - (this.constructor as typeof Think).submissionRecoveryStaleMs;\n\n const fiberRows = this.sql<{ created_at: number }>`\n SELECT created_at FROM cf_agents_runs\n WHERE name = ${(this.constructor as typeof Think).CHAT_FIBER_NAME + \":\" + row.request_id}\n LIMIT 1\n `;\n if (fiberRows[0] && fiberRows[0].created_at >= cutoff) return true;\n\n const streamRows = this.sql<{ created_at: number }>`\n SELECT created_at FROM cf_ai_chat_stream_metadata\n WHERE request_id = ${row.request_id}\n AND status = 'streaming'\n ORDER BY created_at DESC\n LIMIT 1\n `;\n return streamRows[0] ? streamRows[0].created_at >= cutoff : false;\n }\n\n private _hasScheduledRecoveredContinuation(requestId: string): boolean {\n const rows = this.sql<{ payload: string | null }>`\n SELECT payload FROM cf_agents_schedules\n WHERE callback = '_chatRecoveryContinue'\n `;\n return rows.some((row) => {\n if (!row.payload) return false;\n try {\n const payload = JSON.parse(row.payload) as unknown;\n return (\n payload !== null &&\n typeof payload === \"object\" &&\n \"recoveredRequestId\" in payload &&\n (payload as { recoveredRequestId?: unknown }).recoveredRequestId ===\n requestId\n );\n } catch {\n return false;\n }\n });\n }\n\n // ── Programmatic API ───────────────────────────────────────────\n\n /**\n * Inject messages and trigger a model turn — without a WebSocket request.\n *\n * Use for scheduled responses, webhook-triggered turns, proactive agents,\n * or chaining from `onChatResponse`.\n *\n * Accepts static messages or a callback that derives messages from the\n * current state (useful when multiple calls queue up — the callback runs\n * with the latest messages when the turn actually starts).\n *\n * Pass `options.signal` to cancel the turn from outside without knowing\n * the internally-generated request id. The signal is linked to the\n * registry's controller for this turn — when it aborts, the inference\n * loop's signal aborts and the result reports `status: \"aborted\"`.\n * Pre-aborted signals short-circuit before any model work runs. See\n * {@link SaveMessagesOptions} for the integration point.\n *\n * @example Scheduled follow-up\n * ```typescript\n * async onScheduled() {\n * await this.saveMessages([{\n * id: crypto.randomUUID(),\n * role: \"user\",\n * parts: [{ type: \"text\", text: \"Time for your daily summary.\" }]\n * }]);\n * }\n * ```\n *\n * @example Function form\n * ```typescript\n * await this.saveMessages((current) => [\n * ...current,\n * { id: crypto.randomUUID(), role: \"user\", parts: [{ type: \"text\", text: \"Continue.\" }] }\n * ]);\n * ```\n *\n * @example External cancellation (helper-as-sub-agent)\n * ```typescript\n * // Inside a parent agent's tool execute — forward the AI SDK's\n * // abortSignal so a parent stop / tab close cancels the helper.\n * await helper.saveMessages([userMsg], { signal: abortSignal });\n * ```\n */\n async saveMessages(\n messages:\n | UIMessage[]\n | ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>),\n options?: SaveMessagesOptions\n ): Promise<SaveMessagesResult> {\n const requestId = crypto.randomUUID();\n return this._runProgrammaticMessagesTurn(requestId, messages, options);\n }\n\n private async _runProgrammaticMessagesTurn(\n requestId: string,\n messages:\n | UIMessage[]\n | ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>),\n options?: SaveMessagesOptions & {\n onMessagesApplied?: () => void;\n captureProgrammaticStreamError?: boolean;\n captureOutput?: boolean;\n body?: Record<string, unknown>;\n workflowPrompt?: ThinkWorkflowPromptContext;\n }\n ): Promise<ProgrammaticMessagesResult> {\n const clientTools = this._lastClientTools;\n const body = options?.body ?? this._lastBody;\n const epoch = this._turnQueue.generation;\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n let error: string | undefined;\n let output: unknown;\n let wasAborted = false;\n\n await this.keepAliveWhile(async () => {\n await this._turnQueue.enqueue(requestId, async () => {\n const resolved =\n typeof messages === \"function\"\n ? await messages(this.messages)\n : messages;\n\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n for (const msg of resolved) {\n await this._appendMessageToHistory(msg);\n }\n options?.onMessagesApplied?.();\n this._broadcastMessages();\n\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n const abortSignal = this._aborts.getSignal(requestId);\n // Wire the optional external signal to the registry's controller\n // for this request. Detacher MUST run in `finally` to avoid\n // leaking listeners on a long-lived parent signal that drives\n // many helper turns.\n const detachExternal = this._aborts.linkExternal(\n requestId,\n options?.signal\n );\n try {\n const programmaticBody = async () => {\n const result = await agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n clientTools,\n body,\n workflowPrompt: options?.workflowPrompt,\n continuation: false\n })\n );\n\n if (result) {\n const streamResult = await this._streamResult(\n requestId,\n result,\n abortSignal,\n {\n captureProgrammaticStreamError:\n options?.captureProgrammaticStreamError,\n captureOutput: options?.captureOutput\n }\n );\n status = streamResult.status;\n error = streamResult.error;\n output = streamResult.output;\n }\n };\n\n if (this.chatRecovery) {\n await this._runChatRecoveryFiber(\n requestId,\n false,\n programmaticBody\n );\n } else {\n await programmaticBody();\n }\n } finally {\n if (abortSignal?.aborted) wasAborted = true;\n detachExternal();\n this._aborts.remove(requestId);\n }\n });\n });\n\n if (\n this._turnQueue.generation !== epoch &&\n shouldMarkSkippedAfterGenerationChange(status)\n ) {\n status = \"skipped\";\n } else if (wasAborted && status === \"completed\") {\n status = \"aborted\";\n }\n\n return {\n requestId,\n status,\n ...(error !== undefined && { error }),\n ...(output !== undefined && { output })\n };\n }\n\n /**\n * Run a new LLM call following the last assistant message.\n *\n * The model sees the full conversation (including the last assistant\n * response) and generates a new response. The new response is persisted\n * as a separate assistant message. Building block for chat recovery\n * (Phase 4), \"generate more\" buttons, and self-correction.\n *\n * Note: this creates a new message, not an append to the existing one.\n * True continuation-as-append (chunk rewriting) is planned for Phase 4.\n *\n * Returns early with `status: \"skipped\"` if there is no assistant message\n * to continue from.\n *\n * Pass `options.signal` to cancel the continuation from outside —\n * matches the {@link saveMessages} contract.\n */\n protected async continueLastTurn(\n body?: Record<string, unknown>,\n options?: SaveMessagesOptions\n ): Promise<SaveMessagesResult> {\n const lastLeaf = await this.session.getLatestLeaf();\n if (!lastLeaf || lastLeaf.role !== \"assistant\") {\n return { requestId: \"\", status: \"skipped\" };\n }\n\n const requestId = crypto.randomUUID();\n const clientTools = this._lastClientTools;\n const resolvedBody = body ?? this._lastBody;\n const epoch = this._turnQueue.generation;\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n let error: string | undefined;\n let wasAborted = false;\n\n await this.keepAliveWhile(async () => {\n await this._turnQueue.enqueue(requestId, async () => {\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n const abortSignal = this._aborts.getSignal(requestId);\n const detachExternal = this._aborts.linkExternal(\n requestId,\n options?.signal\n );\n try {\n const continueTurnBody = async () => {\n const result = await agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n clientTools,\n body: resolvedBody,\n continuation: true\n })\n );\n\n if (result) {\n const streamResult = await this._streamResult(\n requestId,\n result,\n abortSignal,\n {\n continuation: true\n }\n );\n status = streamResult.status;\n error = streamResult.error;\n }\n };\n\n if (this.chatRecovery) {\n await this._runChatRecoveryFiber(requestId, true, continueTurnBody);\n } else {\n await continueTurnBody();\n }\n } finally {\n if (abortSignal?.aborted) wasAborted = true;\n detachExternal();\n this._aborts.remove(requestId);\n }\n });\n });\n\n if (\n this._turnQueue.generation !== epoch &&\n shouldMarkSkippedAfterGenerationChange(status)\n ) {\n status = \"skipped\";\n } else if (wasAborted && status === \"completed\") {\n status = \"aborted\";\n }\n\n return { requestId, status, ...(error !== undefined && { error }) };\n }\n\n private async _retryLastUserTurn(\n clientTools?: ClientToolSchema[],\n body?: Record<string, unknown>,\n options?: SaveMessagesOptions\n ): Promise<SaveMessagesResult> {\n const lastLeaf = await this.session.getLatestLeaf();\n if (!lastLeaf || lastLeaf.role !== \"user\") {\n return { requestId: \"\", status: \"skipped\" };\n }\n\n const requestId = crypto.randomUUID();\n const epoch = this._turnQueue.generation;\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n let error: string | undefined;\n let wasAborted = false;\n\n await this.keepAliveWhile(async () => {\n await this._turnQueue.enqueue(requestId, async () => {\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n const abortSignal = this._aborts.getSignal(requestId);\n const detachExternal = this._aborts.linkExternal(\n requestId,\n options?.signal\n );\n try {\n const retryTurnBody = async () => {\n const result = await agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n clientTools,\n body,\n continuation: false\n })\n );\n\n if (result) {\n const streamResult = await this._streamResult(\n requestId,\n result,\n abortSignal\n );\n status = streamResult.status;\n error = streamResult.error;\n }\n };\n\n if (this.chatRecovery) {\n await this._runChatRecoveryFiber(requestId, false, retryTurnBody);\n } else {\n await retryTurnBody();\n }\n } finally {\n if (abortSignal?.aborted) wasAborted = true;\n detachExternal();\n this._aborts.remove(requestId);\n }\n });\n });\n\n if (\n this._turnQueue.generation !== epoch &&\n shouldMarkSkippedAfterGenerationChange(status)\n ) {\n status = \"skipped\";\n } else if (wasAborted && status === \"completed\") {\n status = \"aborted\";\n }\n\n return { requestId, status, ...(error !== undefined && { error }) };\n }\n\n // ── WebSocket protocol ──────────────────────────────────────────\n\n private _setupProtocolHandlers() {\n const _onConnect = this.onConnect.bind(this);\n this.onConnect = async (\n connection: Connection,\n ctx: { request: Request }\n ) => {\n const requestTargetsSubAgent = this._cf_requestTargetsSubAgent(\n ctx.request\n );\n if (requestTargetsSubAgent) {\n return _onConnect(connection, ctx);\n }\n\n if (this._resumableStream.hasActiveStream()) {\n // A stream is still in flight. The resume flow is the\n // authoritative source of state: `_notifyStreamResuming` tells\n // the client to send `STREAM_RESUME_ACK`, after which the\n // server replays buffered chunks and delivers a final\n // `MSG_CHAT_MESSAGES` broadcast once the turn completes.\n //\n // Sending `MSG_CHAT_MESSAGES` here would clobber the in-progress\n // assistant the client rebuilds from the replayed chunks,\n // because `this.messages` at this point still only contains\n // the user message — the assistant message is not persisted\n // until the stream finishes.\n this._notifyStreamResuming(connection);\n } else {\n for (const message of await this._buildIdleConnectMessages()) {\n connection.send(JSON.stringify(message));\n }\n }\n return _onConnect(connection, ctx);\n };\n\n const _onClose = this.onClose.bind(this);\n this.onClose = async (\n connection: Connection,\n code: number,\n reason: string,\n wasClean: boolean\n ) => {\n this._pendingResumeConnections.delete(connection.id);\n this._continuation.releaseConnection(connection.id);\n return _onClose(connection, code, reason, wasClean);\n };\n\n const _onMessage = this.onMessage.bind(this);\n this.onMessage = async (connection: Connection, message: WSMessage) => {\n const connectionTargetsSubAgent =\n this._cf_connectionTargetsSubAgent(connection);\n if (connectionTargetsSubAgent) {\n return _onMessage(connection, message);\n }\n\n if (typeof message === \"string\") {\n const event = parseProtocolMessage(message);\n if (event) {\n await this._handleProtocolEvent(connection, event);\n return;\n }\n }\n return _onMessage(connection, message);\n };\n\n const _onRequest = this.onRequest.bind(this);\n this.onRequest = async (request: Request) => {\n const url = new URL(request.url);\n if (\n url.pathname === \"/get-messages\" ||\n url.pathname.endsWith(\"/get-messages\")\n ) {\n return Response.json(this.messages);\n }\n const messengerResponse =\n await this._messengerRuntime?.handleRequest(request);\n if (messengerResponse) {\n return messengerResponse;\n }\n return _onRequest(request);\n };\n }\n\n private async _handleProtocolEvent(\n connection: Connection,\n event: NonNullable<ReturnType<typeof parseProtocolMessage>>\n ): Promise<void> {\n switch (event.type) {\n case \"stream-resume-request\":\n this._handleStreamResumeRequest(connection);\n break;\n\n case \"stream-resume-ack\":\n await this._handleStreamResumeAck(connection, event.id);\n break;\n\n case \"chat-request\":\n if (event.init?.method === \"POST\") {\n await this._handleChatRequest(connection, event);\n }\n break;\n\n case \"tool-result\": {\n if (\n event.clientTools &&\n Array.isArray(event.clientTools) &&\n event.clientTools.length > 0\n ) {\n this._lastClientTools = event.clientTools as ClientToolSchema[];\n this._persistClientTools();\n }\n this._enqueueInteractionApply(() =>\n this._applyToolResult(\n event.toolCallId,\n event.output,\n event.state as \"output-error\" | undefined,\n event.errorText\n )\n );\n if (event.autoContinue) {\n this._scheduleAutoContinuation(connection);\n } else {\n this._rearmPendingAutoContinuationForBatch();\n }\n break;\n }\n\n case \"tool-approval\": {\n this._enqueueInteractionApply(() =>\n this._applyToolApproval(event.toolCallId, event.approved)\n );\n if (event.autoContinue) {\n this._scheduleAutoContinuation(connection);\n } else {\n this._rearmPendingAutoContinuationForBatch();\n }\n break;\n }\n\n case \"clear\":\n await this._handleClear(connection);\n break;\n\n case \"cancel\":\n this._aborts.cancel(event.id);\n break;\n\n case \"messages\":\n break;\n }\n }\n\n private _handleStreamResumeRequest(connection: Connection): void {\n if (this._resumableStream.hasActiveStream()) {\n if (\n this._continuation.activeRequestId ===\n this._resumableStream.activeRequestId &&\n this._continuation.activeConnectionId !== null &&\n this._continuation.activeConnectionId !== connection.id\n ) {\n sendIfOpen(\n connection,\n JSON.stringify({ type: MSG_STREAM_RESUME_NONE })\n );\n } else {\n this._notifyStreamResuming(connection);\n }\n } else if (\n this._continuation.pending !== null &&\n (this._continuation.pending.connectionId === null ||\n this._continuation.pending.connectionId === connection.id)\n ) {\n this._continuation.awaitingConnections.set(connection.id, connection);\n } else {\n sendIfOpen(connection, JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));\n }\n }\n\n private async _handleStreamResumeAck(\n connection: Connection,\n requestId: string\n ): Promise<void> {\n this._pendingResumeConnections.delete(connection.id);\n if (\n this._resumableStream.hasActiveStream() &&\n this._resumableStream.activeRequestId === requestId\n ) {\n const orphanedStreamId = this._resumableStream.replayChunks(\n connection,\n this._resumableStream.activeRequestId\n );\n if (orphanedStreamId) {\n await this._persistOrphanedStream(orphanedStreamId);\n }\n } else if (this._resumableStream.hasActiveStream()) {\n // Ignore ACKs for a different active stream request id.\n } else if (\n !this._resumableStream.replayCompletedChunksByRequestId(\n connection,\n requestId\n )\n ) {\n sendIfOpen(\n connection,\n JSON.stringify({\n body: \"\",\n done: true,\n id: requestId,\n type: MSG_CHAT_RESPONSE,\n replay: true\n })\n );\n }\n }\n\n private async _handleChatRequest(\n connection: Connection,\n event: Extract<\n NonNullable<ReturnType<typeof parseProtocolMessage>>,\n { type: \"chat-request\" }\n >\n ) {\n if (!event.init?.body) return;\n\n let rawParsed: Record<string, unknown>;\n try {\n rawParsed = JSON.parse(event.init.body) as Record<string, unknown>;\n } catch (error) {\n const wrapped = this.onChatError(error, {\n requestId: event.id,\n stage: \"parse\",\n messagesPersisted: false\n });\n this._emit(\"chat:request:failed\", {\n requestId: event.id,\n stage: \"parse\",\n messagesPersisted: false,\n error: wrapped instanceof Error ? wrapped.message : String(wrapped)\n });\n return;\n }\n\n const {\n messages: incomingMessages,\n clientTools: rawClientTools,\n trigger: rawTrigger,\n ...customBody\n } = rawParsed as {\n messages?: UIMessage[];\n clientTools?: ClientToolSchema[];\n trigger?: string;\n [key: string]: unknown;\n };\n if (!Array.isArray(incomingMessages)) return;\n\n const isRegeneration = rawTrigger === \"regenerate-message\";\n const isSubmitMessage = !isRegeneration;\n const requestId = event.id;\n let messagesPersisted = false;\n let failureStage: ChatErrorContext[\"stage\"] = \"persist\";\n\n // ── Concurrency decision (before persisting anything) ────────\n const concurrencyDecision =\n this._getSubmitConcurrencyDecision(isSubmitMessage);\n\n if (concurrencyDecision.action === \"drop\") {\n this._rollbackDroppedSubmit(connection);\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n\n const releasePendingEnqueue = this._submitConcurrency.beginEnqueue();\n let pendingEnqueue = true;\n const epoch = this._turnQueue.generation;\n const releaseIfPending = () => {\n if (!pendingEnqueue) return;\n pendingEnqueue = false;\n releasePendingEnqueue();\n };\n\n try {\n // ── Persist client tools and body (only for accepted requests) ──\n const requestClientTools =\n rawClientTools && rawClientTools.length > 0\n ? rawClientTools\n : undefined;\n if (requestClientTools) {\n this._lastClientTools = requestClientTools;\n this._persistClientTools();\n } else if (rawClientTools !== undefined) {\n this._lastClientTools = undefined;\n this._persistClientTools();\n }\n\n const requestBody =\n Object.keys(customBody).length > 0 ? customBody : undefined;\n this._lastBody = requestBody;\n this._persistBody();\n\n // ── Reconcile, persist, and broadcast user messages ──────────\n //\n // The client may post an in-flight assistant snapshot it minted\n // optimistically (e.g. while a previous tool call is still\n // streaming). Reconcile against the server's current active path\n // so client IDs map onto server IDs and stale client states pick\n // up the server's tool outputs. Without this, Session's\n // INSERT-OR-IGNORE-by-ID would persist a duplicate orphan\n // assistant row alongside the real server-generated one.\n const clientToolsForTurn = this._lastClientTools;\n const bodyForTurn = this._lastBody;\n\n const serverMessages = await this._readMessagesFromStorage();\n const reconciled = reconcileMessages(\n incomingMessages,\n serverMessages,\n sanitizeMessage\n );\n\n let branchParentId: string | undefined;\n if (isRegeneration && reconciled.length > 0) {\n branchParentId = reconciled[reconciled.length - 1].id;\n }\n\n if (this._turnQueue.generation !== epoch) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n\n for (const msg of reconciled) {\n if (this._turnQueue.generation !== epoch) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n\n await this._persistIncomingMessage(msg, serverMessages);\n }\n\n if (this._turnQueue.generation !== epoch) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n\n await this._syncMessages();\n this._broadcastMessages([connection.id]);\n messagesPersisted = true;\n\n // ── Enter turn queue ────────────────────────────────────────\n failureStage = \"turn\";\n const abortSignal = this._aborts.getSignal(requestId);\n\n await this.keepAliveWhile(async () => {\n const turnPromise = this._turnQueue.enqueue(\n requestId,\n async () => {\n // Superseded by a later overlapping submit (latest/merge/debounce)\n if (\n this._submitConcurrency.isSuperseded(\n concurrencyDecision.submitSequence\n )\n ) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n\n // Debounce: wait for quiet period\n if (concurrencyDecision.debounceUntilMs !== null) {\n await this._submitConcurrency.waitForTimestamp(\n concurrencyDecision.debounceUntilMs\n );\n\n if (this._turnQueue.generation !== epoch) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n if (\n this._submitConcurrency.isSuperseded(\n concurrencyDecision.submitSequence\n )\n ) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n }\n\n const chatTurnBody = async () => {\n const result = await agentContext.run(\n {\n agent: this,\n connection,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n clientTools: clientToolsForTurn,\n body: bodyForTurn,\n continuation: false\n })\n );\n\n if (result) {\n await this._streamResult(requestId, result, abortSignal, {\n parentId: branchParentId\n });\n } else {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"No response was generated.\",\n done: true\n });\n }\n };\n\n if (this.chatRecovery) {\n await this._runChatRecoveryFiber(requestId, false, chatTurnBody);\n } else {\n await chatTurnBody();\n }\n },\n {\n generation: epoch\n }\n );\n releaseIfPending();\n\n const turnResult = await turnPromise;\n\n if (turnResult.status === \"stale\") {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n });\n }\n });\n } catch (error) {\n const wrapped = this.onChatError(error, {\n requestId,\n stage: failureStage,\n messagesPersisted\n });\n const errorMessage =\n wrapped instanceof Error ? wrapped.message : String(wrapped);\n this._emit(\"chat:request:failed\", {\n requestId,\n stage: failureStage,\n messagesPersisted,\n error: errorMessage\n });\n // Persist the terminal error before broadcasting it: the broadcast is\n // transient, so a client disconnected at this moment (a pre-stream\n // failure like message reconciliation) would otherwise never learn the\n // turn failed and stay frozen on reconnect (see `_buildIdleConnectMessages`).\n await this._recordTerminalChatStatus(\"error\", requestId, errorMessage);\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: errorMessage,\n done: true,\n error: true\n });\n } finally {\n releaseIfPending();\n this._aborts.remove(requestId);\n }\n }\n\n /**\n * Abort the active turn, invalidate queued turns, and reset\n * concurrency/continuation state. Call this when intercepting\n * clear events or implementing custom reset logic.\n *\n * Does NOT clear messages, streams, or persisted state —\n * only turn execution state.\n */\n protected resetTurnState(): void {\n this._turnQueue.reset();\n this._aborts.destroyAll();\n for (const controller of this._submissionAbortControllers.values()) {\n controller.abort(new Error(\"Turn state reset\"));\n }\n this._submissionAbortControllers.clear();\n const skippedSubmissions = this._markPendingSubmissionsSkipped();\n void this.keepAliveWhile(() =>\n this._emitSkippedSubmissions(skippedSubmissions)\n ).catch((error) => {\n console.error(\"[Think] Failed to skip pending submissions\", error);\n });\n if (this._continuationTimer) {\n clearTimeout(this._continuationTimer);\n this._continuationTimer = null;\n }\n this._submitConcurrency.reset();\n this._pendingInteractionPromise = null;\n // Drop the apply chain so new interactions don't serialize behind a stale\n // (possibly hung) apply from the turn we just reset (#1649).\n this._interactionApplyTail = Promise.resolve();\n // The streaming turn (if any) is being torn down; stop exposing its\n // accumulator so a late tool result doesn't apply to an abandoned message.\n this._streamingAssistant = null;\n this._continuationBarrierActive = false;\n this._continuation.sendResumeNone();\n this._continuation.clearAll();\n }\n\n /**\n * Abort a single in-flight chat turn by request id.\n *\n * Equivalent to the cancel path that fires when a client sends a\n * `chat-request-cancel` WebSocket message — the inference loop's\n * signal aborts, partial chunks already streamed are still\n * persisted, and the turn's `ChatResponseResult` reports\n * `status: \"aborted\"`.\n *\n * No-op if no controller exists for `requestId` (the turn already\n * completed, was never started, or used a different id).\n *\n * `chat()` callers can read the request id from\n * {@link StreamCallback.onStart} and later pass it here from another\n * RPC call.\n *\n * Prefer {@link SaveMessagesOptions.signal} when driving a turn\n * programmatically — it threads the abort intent in from the start\n * without requiring the caller to know the id.\n */\n cancelChat(requestId: string, reason?: string): void {\n this._aborts.cancel(requestId, reason);\n }\n\n /** Abort every in-flight chat turn on this agent. */\n cancelAllChats(): void {\n this._aborts.destroyAll();\n }\n\n protected abortRequest(requestId: string, reason?: unknown): void {\n this._aborts.cancel(requestId, reason);\n }\n\n /**\n * Abort every in-flight chat turn on this agent.\n *\n * Aborts all controllers in the registry and clears it. Used by\n * subclasses that drive single-purpose turns (e.g. a sub-agent\n * helper that runs one turn at a time over RPC) and want a coarse\n * \"cancel whatever is running\" handle without tracking request ids.\n *\n * Does NOT reset queued turns, continuation timers, or submit\n * concurrency state — use {@link resetTurnState} for the full\n * teardown that runs on `chat-clear`.\n */\n protected abortAllRequests(): void {\n this._aborts.destroyAll();\n }\n\n private async _handleClear(connection?: Connection) {\n this.resetTurnState();\n\n this._resumableStream.clearAll();\n this._pendingResumeConnections.clear();\n this._lastClientTools = undefined;\n this._persistClientTools();\n this._lastBody = undefined;\n this._persistBody();\n await this._clearHistory();\n this._broadcast(\n { type: MSG_CHAT_CLEAR },\n connection ? [connection.id] : undefined\n );\n }\n\n private async _streamResultToRpcCallback(\n requestId: string,\n result: StreamableResult,\n callback: StreamCallback,\n abortSignal?: AbortSignal\n ): Promise<void> {\n const streamId = this._resumableStream.start(requestId);\n const accumulator = new StreamAccumulator({\n messageId: crypto.randomUUID()\n });\n // Expose the in-flight message so a client tool result arriving before the\n // end-of-stream persist lands on the accumulator instead of being dropped\n // (#1649). Cleared in the `finally` below.\n this._streamingAssistant = accumulator;\n\n let streamFinalized = false;\n let assistantMsg: UIMessage | null = null;\n let aborted = false;\n let doneSent = false;\n let streamError: string | undefined;\n let pendingRpcError: string | undefined;\n // When a stall-recovery early-return schedules a continuation, the\n // continuation re-runs the turn and its own stream finalize re-triggers the\n // held barrier. Re-arming here too would let the 50ms coalesce timer fire a\n // SECOND continuation alongside the scheduled recovery one — a spurious\n // double model invocation. Mirror the WebSocket `_streamResult` recovery\n // paths and clear `_streamingAssistant` WITHOUT re-arming in that case.\n let skipFinalizeRearm = false;\n\n const stallTimeoutMs =\n this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;\n try {\n this._insideInferenceLoop = true;\n const flushState = { chunksSinceFlush: 0, hasFlushedContent: false };\n try {\n const guardedStream = this._iterateWithStallWatchdog(\n result.toUIMessageStream(),\n stallTimeoutMs,\n () => {\n this._emit(\"chat:stream:stalled\", {\n requestId,\n timeoutMs: stallTimeoutMs\n });\n this.abortRequest(\n requestId,\n new Error(\"chat stream stalled: inactivity watchdog fired\")\n );\n }\n );\n for await (const chunk of guardedStream) {\n if (abortSignal?.aborted) {\n aborted = true;\n break;\n }\n\n // RPC callbacks receive serialized UIMessage chunks directly; unlike\n // the WebSocket protocol, there is no wrapper frame to rewrite for\n // accumulator actions such as `error`.\n const streamChunk = chunk as unknown as StreamChunkData;\n const { action } = accumulator.applyChunk(streamChunk);\n\n if (action?.type === \"error\") {\n streamError = action.error;\n this._emit(\"message:error\", { error: streamError });\n // An AI-SDK error surfaces as a stream error part (not a thrown\n // exception), so it lands here rather than in the `catch` below.\n // Bridge it to `chat:request:failed` too — observers shouldn't have\n // to know whether the failure threw or arrived as a chunk (the\n // post-`beforeTurn`, in-stream provider 400 class), and turn-count\n // telemetry needs the failed signal to balance `turn.started`.\n this._emit(\"chat:request:failed\", {\n requestId,\n stage: \"stream\",\n messagesPersisted: true,\n error: streamError\n });\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: action.error,\n done: false,\n error: true\n });\n break;\n }\n\n const chunkBody = JSON.stringify(chunk);\n await this._storeChunkDurably(\n streamId,\n streamChunk,\n chunkBody,\n flushState\n );\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: chunkBody,\n done: false\n });\n await callback.onEvent(chunkBody);\n }\n } finally {\n this._insideInferenceLoop = false;\n }\n\n if (streamError) {\n this._resumableStream.markError(streamId);\n } else {\n this._resumableStream.complete(streamId);\n }\n streamFinalized = true;\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n });\n doneSent = true;\n\n assistantMsg = accumulator.toMessage();\n if (accumulator.parts.length > 0) {\n await this._persistAssistantMessage(assistantMsg);\n this._broadcastMessages();\n }\n\n if (streamError) {\n await this._fireResponseHook({\n message: assistantMsg,\n requestId,\n continuation: false,\n status: \"error\",\n error: streamError\n });\n pendingRpcError = streamError;\n } else if (!aborted) {\n await callback.onDone();\n await this._fireResponseHook({\n message: assistantMsg,\n requestId,\n continuation: false,\n status: \"completed\"\n });\n } else {\n await this._fireResponseHook({\n message: assistantMsg,\n requestId,\n continuation: false,\n status: \"aborted\"\n });\n }\n } catch (error) {\n // #1626: a stream-stall watchdog abort is a recoverable interruption, not\n // a terminal error. Persist the settled partial (re-anchor), route into\n // bounded recovery, and suppress the terminal error when a continuation is\n // scheduled; fall through to terminal only once the budget is exhausted.\n if (error instanceof ChatStreamStalledError) {\n if (!assistantMsg && accumulator.parts.length > 0) {\n assistantMsg = accumulator.toMessage();\n await this._persistAssistantMessage(assistantMsg);\n this._broadcastMessages();\n }\n const outcome = await this._routeStallToBoundedRecovery({\n requestId,\n streamId,\n partialParts: (assistantMsg ?? accumulator.toMessage()).parts,\n targetAssistantId: assistantMsg?.id\n });\n if (outcome === \"scheduled\") {\n if (!streamFinalized) {\n this._resumableStream.complete(streamId);\n streamFinalized = true;\n }\n if (!doneSent) {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n });\n doneSent = true;\n }\n // The scheduled continuation (a later isolate invocation, without this\n // callback) owns the real terminal outcome. Signal the interruption so\n // the caller doesn't read this clean resolve as success and finalize a\n // truncated partial (#1644); NOT onDone/onError — see `onInterrupted`.\n skipFinalizeRearm = true;\n await callback.onInterrupted?.();\n return;\n }\n if (outcome === \"exhausted\") {\n // `_routeStallToBoundedRecovery` already delivered the terminal UX\n // (configured `terminalMessage` + done/error frame + `onExhausted` +\n // submission interrupted), identical to deploy-recovery exhaustion.\n // Finalize the stream and return WITHOUT the generic terminal path,\n // which would otherwise re-broadcast the raw stall error.\n if (!streamFinalized) {\n this._resumableStream.markError(streamId);\n streamFinalized = true;\n }\n doneSent = true;\n // Exhaustion is terminal for the turn, but it was delivered out-of-band\n // by `_exhaustChatRecovery` (banner/`onExhausted`), NOT through this\n // callback's `onError`. Signal the interruption so a `chat()` consumer\n // doesn't mis-read the clean resolve as a successful completion (#1644).\n skipFinalizeRearm = true;\n await callback.onInterrupted?.();\n return;\n }\n // outcome === \"disabled\" (chat recovery off): fall through to the\n // generic terminal path below (unchanged watchdog behavior).\n }\n if (!streamFinalized) {\n this._resumableStream.markError(streamId);\n streamFinalized = true;\n }\n if (!doneSent) {\n const streamError =\n error instanceof Error ? error.message : \"Stream error\";\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: streamError,\n done: true,\n error: true\n });\n doneSent = true;\n }\n\n if (!assistantMsg && accumulator.parts.length > 0) {\n assistantMsg = accumulator.toMessage();\n await this._persistAssistantMessage(assistantMsg);\n this._broadcastMessages();\n }\n\n const wrapped = this.onChatError(error, {\n requestId,\n stage: \"stream\",\n messagesPersisted: true\n });\n const errorMessage =\n wrapped instanceof Error ? wrapped.message : String(wrapped);\n this._emit(\"chat:request:failed\", {\n requestId,\n stage: \"stream\",\n messagesPersisted: true,\n error: errorMessage\n });\n\n if (assistantMsg) {\n await this._fireResponseHook({\n message: assistantMsg,\n requestId,\n continuation: false,\n status: \"error\",\n error: errorMessage\n });\n }\n\n await callback.onError(errorMessage);\n } finally {\n // The message is now durably persisted (success, error, or recovery\n // path), so subsequent tool results resolve against storage; stop\n // exposing the sealed accumulator (#1649) and re-check any continuation\n // the stream-active barrier held (#1650). A stall-recovery early-return\n // does a plain clear instead (no re-arm): its scheduled continuation\n // re-runs the turn and that finalize re-triggers the held barrier, so\n // re-arming here would double-fire alongside the recovery continuation.\n if (skipFinalizeRearm) {\n this._streamingAssistant = null;\n } else {\n this._onStreamingTurnFinalized();\n }\n }\n\n if (pendingRpcError) {\n await callback.onError(pendingRpcError);\n }\n }\n\n /**\n * Whether storing this chunk should immediately flush the resumable-stream\n * buffer to SQLite.\n *\n * A settled tool result (`tool-output-available` / `tool-output-error` /\n * `tool-output-denied`) captures a completed, often non-idempotent side\n * effect — or, for a denial, a user decision — so it is flushed\n * **immediately**. An isolate eviction (deploy) before the next batch flush\n * would otherwise lose it, and recovery would re-anchor without it and re-run\n * the already-completed tool call (or drop the denial). Frequent recoverable\n * content (text / reasoning / tool-input streaming) is throttled to avoid\n * write amplification.\n */\n private _shouldFlushRecoverableChunk(\n chunk: StreamChunkData,\n chunksSinceFlush: number,\n hasFlushedContent: boolean\n ): boolean {\n if (\n chunk.type === \"tool-output-available\" ||\n chunk.type === \"tool-output-error\" ||\n chunk.type === \"tool-output-denied\"\n ) {\n return true;\n }\n const isThrottledRecoverable =\n chunk.type === \"text-delta\" ||\n chunk.type === \"reasoning-delta\" ||\n chunk.type === \"tool-input-available\";\n return (\n isThrottledRecoverable && (!hasFlushedContent || chunksSinceFlush >= 10)\n );\n }\n\n /**\n * Store a stream chunk, flushing settled tool results durably and promptly.\n * Shared by the WebSocket and sub-agent RPC streaming paths so both get\n * tool-call-level recovery durability (recovery loses at most the in-flight\n * step, never an already-completed tool call).\n */\n private async _storeChunkDurably(\n streamId: string,\n chunk: StreamChunkData,\n chunkBody: string,\n state: { chunksSinceFlush: number; hasFlushedContent: boolean }\n ): Promise<void> {\n this._resumableStream.storeChunk(streamId, chunkBody);\n state.chunksSinceFlush++;\n if (\n this._shouldFlushRecoverableChunk(\n chunk,\n state.chunksSinceFlush,\n state.hasFlushedContent\n )\n ) {\n this._resumableStream.flushBuffer();\n state.chunksSinceFlush = 0;\n state.hasFlushedContent = true;\n // Forward progress: new durable content was just flushed. Advance the\n // monotonic, compaction-immune progress counter HERE (production time)\n // rather than in `_persistOrphanedStream` — so it bumps only on genuinely\n // new content and is immune to client reconnects / recovery re-persists\n // (which don't flow through this path). This is what the recovery\n // no-progress window keys off (#1637), and stays compaction-proof (#1628).\n await this._bumpChatRecoveryProgress();\n }\n }\n\n /**\n * Wrap a UI-message stream with an inactivity watchdog. If no chunk arrives\n * within `timeoutMs`, `onStall` runs (aborting the upstream model stream) and\n * the iterator throws, so the consumer loop exits with a terminal error\n * instead of parking forever on a hung provider/transport. `timeoutMs <= 0`\n * passes the source through untouched.\n */\n private async *_iterateWithStallWatchdog<T>(\n source: AsyncIterable<T>,\n timeoutMs: number,\n onStall: () => void\n ): AsyncGenerator<T> {\n if (!(timeoutMs > 0)) {\n yield* source;\n return;\n }\n const iterator = source[Symbol.asyncIterator]();\n // Tracks whether the watchdog itself aborted the upstream. In that case we\n // must NOT also `iterator.return()` it: cancelling the readable after the\n // abort makes the AI SDK pipeline write to an already-cancelled readable\n // (\"readable side is no longer readable\"). Letting the abort error the\n // stream is the clean path.\n let selfAborted = false;\n try {\n while (true) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n let stalled = false;\n const stall = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n stalled = true;\n reject(\n new ChatStreamStalledError(\n `Chat stream stalled: no activity for ${timeoutMs}ms; the turn was aborted by the stall watchdog.`\n )\n );\n }, timeoutMs);\n });\n const nextPromise = iterator.next();\n // If the watchdog wins the race we abandon this read; aborting the\n // upstream stream makes it reject later, so pre-attach a no-op catch to\n // keep that abandoned rejection from surfacing as an unhandled rejection.\n nextPromise.catch(() => {});\n let next: IteratorResult<T>;\n try {\n next = await Promise.race([nextPromise, stall]);\n } catch (err) {\n if (stalled) {\n selfAborted = true;\n onStall();\n }\n throw err;\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n if (next.done) return;\n yield next.value;\n }\n } finally {\n // Forward early termination (consumer `break`/`throw`, e.g. an in-band\n // stream error where the abort signal is NOT set) to the source so its\n // reader is cancelled — otherwise the wrapped source would leak when the\n // consumer stops reading mid-stream. Skipped after a watchdog stall, which\n // already aborted the upstream (see `selfAborted` above).\n if (!selfAborted) {\n await iterator.return?.(undefined as never).catch(() => {});\n }\n }\n }\n\n private async _streamResult(\n requestId: string,\n result: StreamableResult,\n abortSignal?: AbortSignal,\n options?: {\n continuation?: boolean;\n parentId?: string;\n captureProgrammaticStreamError?: boolean;\n captureOutput?: boolean;\n }\n ): Promise<StreamResultStatus> {\n const clearGen = this._turnQueue.generation;\n const streamId = this._resumableStream.start(requestId);\n const continuation = options?.continuation ?? false;\n const parentId = options?.parentId;\n\n if (this._continuation.pending?.requestId === requestId) {\n this._continuation.activatePending();\n this._continuation.flushAwaitingConnections((c) =>\n this._notifyStreamResuming(c)\n );\n }\n\n const accumulator = new StreamAccumulator({\n messageId: crypto.randomUUID()\n });\n // Expose the in-flight message so a client tool result arriving before the\n // end-of-stream persist lands on the accumulator instead of being dropped\n // (#1649). Cleared before every return path below.\n this._streamingAssistant = accumulator;\n\n let doneSent = false;\n let streamAborted = false;\n let streamError: string | undefined;\n let output: unknown;\n const flushState = { chunksSinceFlush: 0, hasFlushedContent: false };\n\n const stallTimeoutMs =\n this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;\n try {\n this._insideInferenceLoop = true;\n try {\n const guardedStream = this._iterateWithStallWatchdog(\n result.toUIMessageStream(),\n stallTimeoutMs,\n () => {\n this._emit(\"chat:stream:stalled\", {\n requestId,\n timeoutMs: stallTimeoutMs\n });\n // Tear down the upstream model stream so a hung provider/transport\n // is released; the watchdog's throw drives the terminal error below.\n this.abortRequest(\n requestId,\n new Error(\"chat stream stalled: inactivity watchdog fired\")\n );\n }\n );\n for await (const chunk of guardedStream) {\n if (abortSignal?.aborted) {\n streamAborted = true;\n break;\n }\n\n const streamChunk = chunk as unknown as StreamChunkData;\n const { action } = accumulator.applyChunk(streamChunk);\n\n // Approved server tools execute during a continuation stream, but\n // their original tool part lives in an earlier assistant message.\n // The accumulator can only own this turn's new content, so it\n // surfaces a terminal result for a prior message as a\n // `cross-message-tool-update`. Persist + broadcast it directly so\n // the approved result reaches clients and durable storage. The\n // update builder is first-write-wins (replay-safe) and preserves a\n // streamed `preliminary` flag; `_applyToolUpdateToMessages` skips\n // the write/broadcast when the matched part is already settled.\n if (action?.type === \"cross-message-tool-update\") {\n await this._applyToolUpdateToMessages(\n crossMessageToolResultUpdate(\n action.toolCallId,\n action.updateType,\n action.output,\n action.errorText,\n action.preliminary\n )\n );\n }\n\n if (action?.type === \"error\") {\n streamError = action.error;\n if (options?.captureProgrammaticStreamError) {\n this._programmaticStreamErrors.set(requestId, streamError);\n }\n this._emit(\"message:error\", { error: streamError });\n // An AI-SDK error surfaces as a stream error part (not a thrown\n // exception), so it lands here rather than in the `catch` below.\n // Bridge it to `chat:request:failed` too — observers shouldn't have\n // to know whether the failure threw or arrived as a chunk (the\n // post-`beforeTurn`, in-stream provider 400 class), and turn-count\n // telemetry needs the failed signal to balance `turn.started`.\n this._emit(\"chat:request:failed\", {\n requestId,\n stage: \"stream\",\n messagesPersisted: true,\n error: streamError\n });\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: action.error,\n done: false,\n error: true,\n ...(continuation && { continuation: true })\n });\n break;\n }\n\n const chunkBody = JSON.stringify(chunk);\n await this._storeChunkDurably(\n streamId,\n streamChunk,\n chunkBody,\n flushState\n );\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: chunkBody,\n done: false,\n ...(continuation && { continuation: true })\n });\n }\n } finally {\n this._insideInferenceLoop = false;\n }\n\n if (streamError) {\n this._resumableStream.markError(streamId);\n } else {\n this._resumableStream.complete(streamId);\n }\n this._pendingResumeConnections.clear();\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true,\n ...(continuation && { continuation: true })\n });\n doneSent = true;\n } catch (error) {\n // #1626: a stream-stall watchdog abort is a recoverable interruption, not\n // a terminal error. Persist the settled partial (so the continuation\n // re-anchors without re-running completed tool calls), then route into\n // bounded recovery; only fall through to the terminal path below once the\n // budget is exhausted.\n if (error instanceof ChatStreamStalledError) {\n let targetAssistantId: string | undefined;\n const partialMsg = accumulator.toMessage();\n if (\n this._turnQueue.generation === clearGen &&\n accumulator.parts.length > 0\n ) {\n await this._persistAssistantMessage(partialMsg, parentId);\n this._broadcastMessages();\n targetAssistantId = partialMsg.id;\n }\n const outcome = await this._routeStallToBoundedRecovery({\n requestId,\n streamId,\n partialParts: partialMsg.parts,\n targetAssistantId\n });\n if (outcome === \"scheduled\") {\n // Recovering: close the stream cleanly (no terminal error frame); the\n // scheduled continuation drives the turn to completion. Report\n // `aborted` so the caller does not terminalize the turn.\n this._resumableStream.complete(streamId);\n this._pendingResumeConnections.clear();\n if (!doneSent) {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true,\n ...(continuation && { continuation: true })\n });\n doneSent = true;\n }\n // `aborted` (not `error`): this attempt was aborted by the watchdog;\n // the scheduled continuation owns the real terminal outcome. No\n // response hook fires here (the continuation fires it), mirroring how\n // a deploy-interrupted attempt is superseded by its continuation.\n // Plain clear (no auto-continuation re-check): recovery re-runs the\n // turn and its own stream finalize re-triggers the held barrier.\n this._streamingAssistant = null;\n return { status: \"aborted\" };\n }\n if (outcome === \"exhausted\") {\n // `_routeStallToBoundedRecovery` already delivered the terminal UX\n // (configured `terminalMessage` + done/error frame + `onExhausted` +\n // submission interrupted), identical to deploy-recovery exhaustion.\n // Finalize the stream and report `aborted` (not `error`) so the caller\n // does not re-run the generic terminal path on top of it.\n this._resumableStream.markError(streamId);\n this._pendingResumeConnections.clear();\n doneSent = true;\n this._streamingAssistant = null;\n return { status: \"aborted\" };\n }\n // outcome === \"disabled\" (chat recovery off): fall through to the\n // generic terminal path (the watchdog's original \"kill the spinner\"\n // guarantee, unchanged).\n }\n streamError = error instanceof Error ? error.message : \"Stream error\";\n if (options?.captureProgrammaticStreamError) {\n this._programmaticStreamErrors.set(requestId, streamError);\n }\n this._resumableStream.markError(streamId);\n this._pendingResumeConnections.clear();\n if (!doneSent) {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: streamError,\n done: true,\n error: true,\n ...(continuation && { continuation: true })\n });\n doneSent = true;\n }\n } finally {\n if (!doneSent) {\n this._resumableStream.markError(streamId);\n this._pendingResumeConnections.clear();\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true,\n ...(continuation && { continuation: true })\n });\n }\n }\n\n if (\n options?.captureOutput &&\n result.output &&\n !streamError &&\n !streamAborted\n ) {\n try {\n output = await result.output;\n } catch (error) {\n streamError =\n error instanceof Error ? error.message : \"Structured output error\";\n if (options.captureProgrammaticStreamError) {\n this._programmaticStreamErrors.set(requestId, streamError);\n }\n }\n }\n\n if (this._turnQueue.generation === clearGen) {\n try {\n const assistantMsg = accumulator.toMessage();\n\n if (accumulator.parts.length > 0) {\n await this._persistAssistantMessage(assistantMsg, parentId);\n this._broadcastMessages();\n }\n\n await this._fireResponseHook({\n message: assistantMsg,\n requestId,\n continuation,\n status: streamError\n ? \"error\"\n : streamAborted\n ? \"aborted\"\n : \"completed\",\n error: streamError\n });\n } catch (e) {\n console.error(\"Failed to persist assistant message:\", e);\n }\n }\n\n // The message is now persisted (or the turn was cleared), so subsequent\n // tool results resolve against storage; stop exposing the accumulator and\n // re-check any continuation the stream-active barrier held (#1650).\n this._onStreamingTurnFinalized();\n\n return streamError\n ? { status: \"error\", error: streamError }\n : {\n status: streamAborted ? \"aborted\" : \"completed\",\n ...(output !== undefined && { output })\n };\n }\n\n // ── Session-backed persistence ──────────────────────────────────\n\n private async _persistAssistantMessage(\n msg: UIMessage,\n parentId?: string\n ): Promise<void> {\n await this._upsertMessageInHistory(msg, parentId);\n }\n\n /**\n * Persist an incoming message after reconciliation. For assistant\n * messages, also resolve their ID against any server-side row that\n * already owns the same `toolCallId` so we update the existing row\n * instead of inserting an orphan duplicate.\n */\n private async _persistIncomingMessage(\n msg: UIMessage,\n serverMessages: readonly UIMessage[]\n ): Promise<void> {\n const resolved =\n msg.role === \"assistant\" ? resolveToolMergeId(msg, serverMessages) : msg;\n await this._upsertMessageInHistory(resolved);\n }\n\n private _persistClientTools(): void {\n if (this._lastClientTools) {\n this._configSet(\"lastClientTools\", JSON.stringify(this._lastClientTools));\n } else {\n this._configDelete(\"lastClientTools\");\n }\n }\n\n private _restoreClientTools(): void {\n const raw = this._configGet(\"lastClientTools\");\n if (raw) {\n try {\n this._lastClientTools = JSON.parse(raw);\n } catch {\n this._lastClientTools = undefined;\n }\n }\n }\n\n private _persistBody(): void {\n if (this._lastBody) {\n this._configSet(\"lastBody\", JSON.stringify(this._lastBody));\n } else {\n this._configDelete(\"lastBody\");\n }\n }\n\n private _restoreBody(): void {\n const raw = this._configGet(\"lastBody\");\n if (raw) {\n try {\n this._lastBody = JSON.parse(raw);\n } catch {\n this._lastBody = undefined;\n }\n }\n }\n\n // ── Tool state updates (shared primitives from agents/chat) ─────\n\n /**\n * Serialize a client-tool result/approval apply behind any in-flight apply\n * (#1649). Parallel tool results arrive as independent WebSocket messages,\n * and each apply is a read-modify-write of the full message in durable\n * storage. Running them concurrently means every apply reads the same\n * snapshot (all siblings still `input-available`), patches only its own part,\n * and writes the whole message back — so the last write clobbers the others\n * back to `input-available`, and the auto-continuation barrier later times\n * out and the transcript-repair backstop errors the lost siblings.\n *\n * Chaining each apply off `_interactionApplyTail` makes the read-modify-write\n * atomic per result and in arrival order. `_pendingInteractionPromise` is set\n * to the newest link so the barrier's single-slot wake-up still observes the\n * latest apply; because the chain is serial, awaiting it transitively waits\n * for every predecessor.\n *\n * @internal\n */\n protected _enqueueInteractionApply(\n apply: () => Promise<void>\n ): Promise<boolean> {\n const run = async (): Promise<boolean> => {\n await apply();\n return true;\n };\n // `.then(run, run)` runs regardless of a predecessor's outcome so one\n // rejected apply can't poison the rest of the batch.\n const resultPromise = this._interactionApplyTail.then(run, run);\n this._interactionApplyTail = resultPromise.then(\n () => undefined,\n () => undefined\n );\n this._pendingInteractionPromise = resultPromise;\n resultPromise\n .finally(() => {\n if (this._pendingInteractionPromise === resultPromise) {\n this._pendingInteractionPromise = null;\n }\n })\n .catch(() => {});\n return resultPromise;\n }\n\n private async _applyToolResult(\n toolCallId: string,\n output: unknown,\n overrideState?: \"output-error\",\n errorText?: string\n ): Promise<void> {\n const update = toolResultUpdate(\n toolCallId,\n output,\n overrideState,\n errorText\n );\n await this._applyToolUpdateToMessages(update);\n }\n\n private async _applyToolApproval(\n toolCallId: string,\n approved: boolean\n ): Promise<void> {\n const update = toolApprovalUpdate(toolCallId, approved);\n await this._applyToolUpdateToMessages(update);\n }\n\n private async _applyToolUpdateToMessages(update: {\n toolCallId: string;\n matchStates: string[];\n apply: (part: Record<string, unknown>) => Record<string, unknown>;\n }): Promise<void> {\n // The message to update can live in two places. During a streaming turn\n // the assistant message exists ONLY in the in-flight accumulator until\n // `_persistAssistantMessage` writes it at a turn boundary; a parallel-\n // batch sibling can also have been persisted already by stall recovery.\n // Apply to BOTH so the result is correct regardless of where the message\n // currently is and survives the eventual `accumulator.toMessage()` persist\n // (which would otherwise downgrade an applied result back to\n // `input-available` — #1649). Mirrors `@cloudflare/ai-chat`'s streaming-\n // message handling, generalized to also cover the post-persist case.\n let broadcastMessage: UIMessage | undefined;\n\n // (1) In-flight accumulator. A client tool result that arrives over the\n // WebSocket before the end-of-stream persist would be missed by a\n // storage-only lookup and later repaired as \"interrupted\". Writing it in\n // place lets it ride into the persist.\n const streaming = this._streamingAssistant;\n if (streaming) {\n const accParts = streaming.parts as unknown as Array<\n Record<string, unknown>\n >;\n const result = applyToolUpdate(accParts, update);\n if (result && result.parts[result.index] !== accParts[result.index]) {\n // `accParts` is a typed alias of the accumulator's live array, so this\n // in-place write is reflected by `streaming.toMessage()` and the\n // eventual end-of-stream persist.\n accParts[result.index] = result.parts[result.index];\n broadcastMessage = streaming.toMessage();\n }\n }\n\n // (2) Durable storage. Handles messages already persisted — including\n // partials written mid-stream by stall recovery and cross-message tool\n // results that target an earlier message than this turn's.\n const history = await this._readMessagesFromStorage();\n for (let i = 0; i < history.length; i++) {\n const msg = history[i];\n const msgParts = msg.parts as Array<Record<string, unknown>>;\n const result = applyToolUpdate(msgParts, update);\n if (result) {\n // First-write-wins / idempotent re-apply: when `apply` leaves the\n // matched part untouched (same reference) — e.g. a provider replay of\n // an already-settled cross-message tool result (#1404) — there is\n // nothing to persist. Skip the durable write and the redundant\n // `MESSAGE_UPDATED` broadcast so clients don't churn on a no-op.\n if (result.parts[result.index] === msgParts[result.index]) {\n break;\n }\n const updatedMsg = {\n ...msg,\n parts: result.parts as UIMessage[\"parts\"]\n };\n const safe = await this._updateMessageInHistory(updatedMsg);\n // Session change callbacks may run after an immediately scheduled\n // continuation begins. Keep its input cache coherent synchronously.\n this._patchCachedMessage(safe);\n // Patch the live cache in place instead of doing a full\n // `_syncMessages()` round-trip.\n // A full re-read during a streaming turn drops in-flight messages\n // whose parent chain hasn't been persisted yet (see commits\n // 3f615a24 \"revert _syncMessages in _applyToolUpdateToMessages\"\n // and 6e76bd49 \"update cached messages in-place\"). The cache is\n // the source of truth during a turn; we only reconcile it here to\n // reflect the tool update that was just written to storage.\n broadcastMessage = safe;\n break;\n }\n }\n\n if (broadcastMessage) {\n this._broadcast({\n type: MSG_MESSAGE_UPDATED,\n message: broadcastMessage\n });\n }\n }\n\n // ── Stability + pending interactions ─────────────────────────────\n\n protected hasPendingInteraction(): boolean {\n const clientResolvable = this._clientResolvableToolNames();\n return this.messages.some(\n (message) =>\n message.role === \"assistant\" &&\n this._messageHasPendingInteraction(message, clientResolvable)\n );\n }\n\n protected async waitUntilStable(options?: {\n timeout?: number;\n }): Promise<boolean> {\n const deadline =\n options?.timeout != null ? Date.now() + options.timeout : null;\n\n while (true) {\n if (\n (await this._awaitWithDeadline(\n this._submitConcurrency.waitForIdle(() =>\n this._turnQueue.waitForIdle()\n ),\n deadline\n )) === TIMED_OUT\n ) {\n return false;\n }\n\n if (!this.hasPendingInteraction()) {\n return true;\n }\n\n const pending = this._pendingInteractionPromise;\n if (pending) {\n let result: boolean | typeof TIMED_OUT;\n try {\n result = await this._awaitWithDeadline(pending, deadline);\n } catch {\n continue;\n }\n if (result === TIMED_OUT) {\n return false;\n }\n } else {\n if (\n (await this._awaitWithDeadline(\n new Promise<void>((resolve) => setTimeout(resolve, 100)),\n deadline\n )) === TIMED_OUT\n ) {\n return false;\n }\n }\n }\n }\n\n private async _awaitWithDeadline<T>(\n promise: Promise<T>,\n deadline: number | null\n ): Promise<T | typeof TIMED_OUT> {\n if (deadline == null) {\n return promise;\n }\n const remainingMs = Math.max(0, deadline - Date.now());\n let timer: ReturnType<typeof setTimeout>;\n const result = await Promise.race([\n promise,\n new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(() => resolve(TIMED_OUT), remainingMs);\n })\n ]);\n clearTimeout(timer!);\n return result;\n }\n\n private _messageHasPendingInteraction(\n message: UIMessage,\n clientResolvable: Set<string>\n ): boolean {\n return message.parts.some((part) =>\n this._partAwaitsClientInteraction(part, clientResolvable)\n );\n }\n\n /**\n * Names of the tools whose interrupted `input-available` part can still be\n * resolved by the CLIENT after a restart — i.e. the client tools (no server\n * `execute`) from the last request, which the SPA answers by replaying a\n * `tool-result` over the WebSocket. A server tool is intentionally absent:\n * its `execute()` promise died with the evicted isolate, so nothing will\n * ever post its result.\n */\n private _clientResolvableToolNames(): Set<string> {\n const names = new Set<string>();\n for (const tool of this._lastClientTools ?? []) {\n if (tool?.name) names.add(tool.name);\n }\n return names;\n }\n\n /** Extract a tool part's name from its `tool-<name>` / `dynamic-tool` shape. */\n private _toolPartName(record: Record<string, unknown>): string | undefined {\n const type = typeof record.type === \"string\" ? record.type : \"\";\n if (type === \"dynamic-tool\") {\n return typeof record.toolName === \"string\" ? record.toolName : undefined;\n }\n if (type.startsWith(\"tool-\")) {\n return type.slice(\"tool-\".length);\n }\n return undefined;\n }\n\n /**\n * Whether a part is still awaiting a CLIENT interaction that can genuinely\n * arrive after a restart, so `waitUntilStable` must keep waiting for it:\n * - `approval-requested`: a reconnecting client can replay the approval.\n * - `input-available` for a CLIENT tool: the SPA can replay the\n * `tool-result` (this is why client-tool recovery works — see the\n * `tool-result` handler, which sets `_pendingInteractionPromise`).\n *\n * A SERVER tool's `input-available` is deliberately NOT pending. After an\n * eviction its `execute()` promise is gone and no interaction will ever\n * resolve it, so treating it as pending wedges `waitUntilStable` forever:\n * the recovery continuation times out every attempt, burns the attempt\n * budget on a wait that can never converge, and — if any transient\n * storage/schedule error throws on the way — the one-shot recovery alarm row\n * is swallowed and deleted with no terminal `onExhausted` (the half-finished\n * message wedges silently). Excluding it lets `waitUntilStable` converge so\n * `continueLastTurn` runs, where the existing transcript-repair pass\n * (`_repairTranscriptForProvider`) flips the orphan to an errored result and\n * the model proceeds.\n */\n private _partAwaitsClientInteraction(\n part: UIMessage[\"parts\"][number],\n clientResolvable: Set<string>\n ): boolean {\n if (!(\"state\" in part)) return false;\n const record = part as Record<string, unknown>;\n const state = record.state;\n if (state === \"approval-requested\") return true;\n if (state !== \"input-available\") return false;\n const toolName = this._toolPartName(record);\n return toolName != null && clientResolvable.has(toolName);\n }\n\n // ── Chat recovery via fibers ───────────────────────────────────\n\n private _resolveChatRecoveryConfig(): ResolvedChatRecoveryConfig {\n const raw = this.chatRecovery;\n const custom = typeof raw === \"object\" ? raw : undefined;\n return {\n enabled: raw !== false,\n maxAttempts: Math.max(\n 1,\n Math.floor(custom?.maxAttempts ?? DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS)\n ),\n stableTimeoutMs: Math.max(\n 0,\n Math.floor(\n custom?.stableTimeoutMs ?? DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS\n )\n ),\n terminalMessage:\n custom?.terminalMessage ?? DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE,\n ...(custom?.onExhausted ? { onExhausted: custom.onExhausted } : {})\n };\n }\n\n private _chatRecoveryIncidentId(input: {\n requestId: string;\n recoveryRootRequestId?: string | null;\n latestUserMessageId?: string | null;\n targetAssistantId?: string | null;\n recoveryKind: ChatRecoveryKind;\n }): string {\n // `recoveryKind` is intentionally NOT part of the identity: a single\n // interrupted turn can flip between \"retry\" (no chunks persisted) and\n // \"continue\" (partial chunks exist) across restarts, and the attempt\n // budget must be shared so recovery stays bounded by `maxAttempts`.\n return [\n input.recoveryRootRequestId ?? input.requestId,\n input.latestUserMessageId ?? \"\"\n ].join(\":\");\n }\n\n private _chatRecoveryIncidentKey(incidentId: string): string {\n return `${CHAT_RECOVERY_INCIDENT_KEY_PREFIX}${encodeURIComponent(incidentId)}`;\n }\n\n /**\n * Monotonic forward-progress signal for recovery budget resets.\n *\n * This used to count assistant messages in `this.messages`, but that is\n * recomputed from the live, mutable transcript. Compaction collapses older\n * assistant messages into a summary, lowering the count — so a turn that had\n * genuinely advanced could read as \"no progress\" between attempts and exhaust\n * its budget prematurely (#1628). Instead we read a durably-persisted counter\n * that only ever increments — bumped at production time when new content is\n * durably flushed (see `_storeChunkDurably`), which is genuine forward\n * progress and is immune to client reconnects / recovery re-persists — so\n * compaction can never lower it and a reconnect can't fake it (#1637).\n */\n private async _chatRecoveryProgressMarker(): Promise<number> {\n return (\n (await this.ctx.storage.get<number>(CHAT_RECOVERY_PROGRESS_KEY)) ?? 0\n );\n }\n\n /** Advance the durable recovery-progress counter. Called from\n * `_storeChunkDurably` when new content is durably flushed (real, reconnect-\n * immune forward progress). */\n private async _bumpChatRecoveryProgress(): Promise<void> {\n const current =\n (await this.ctx.storage.get<number>(CHAT_RECOVERY_PROGRESS_KEY)) ?? 0;\n await this.ctx.storage.put(CHAT_RECOVERY_PROGRESS_KEY, current + 1);\n }\n\n /** In-memory wall-clock of the last N9 child-stream progress bump (reset per\n * isolate so the first forwarded chunk after a restart always credits). */\n private _lastAgentToolStreamProgressAt = 0;\n\n /**\n * N9: forwarding a sub-agent's chunks IS forward progress for this parent\n * turn, so credit the parent's recovery progress marker — otherwise a parent\n * whose turn merely `await`s a child banks no progress of its own and its\n * no-progress window exhausts while the child is healthily streaming. Only\n * invoked after a child actually produced output (see\n * `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.\n * Throttled (and reset per isolate) so we never write storage per token.\n */\n protected override async _onAgentToolStreamProgress(): Promise<void> {\n const now = Date.now();\n if (\n now - this._lastAgentToolStreamProgressAt <\n AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS\n ) {\n return;\n }\n this._lastAgentToolStreamProgressAt = now;\n await this._bumpChatRecoveryProgress();\n }\n\n /** Sweep recovery incidents that have been inactive past the TTL. */\n private async _sweepStaleChatRecoveryIncidents(now: number): Promise<void> {\n const entries = await this.ctx.storage.list<ChatRecoveryIncident>({\n prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX\n });\n const staleKeys: string[] = [];\n for (const [key, incident] of entries) {\n const lastActive = incident?.lastAttemptAt ?? incident?.firstSeenAt ?? 0;\n if (now - lastActive > CHAT_RECOVERY_INCIDENT_TTL_MS) {\n staleKeys.push(key);\n }\n }\n for (const key of staleKeys) {\n await this.ctx.storage.delete(key);\n }\n }\n\n private async _beginChatRecoveryIncident(input: {\n requestId: string;\n recoveryRootRequestId?: string | null;\n latestUserMessageId?: string | null;\n targetAssistantId?: string | null;\n recoveryKind: ChatRecoveryKind;\n /** Test-only clock injection for deterministic debounce/window timing. */\n nowMs?: number;\n }): Promise<{\n incident: ChatRecoveryIncident;\n config: ResolvedChatRecoveryConfig;\n exhausted: boolean;\n }> {\n const config = this._resolveChatRecoveryConfig();\n const incidentId = this._chatRecoveryIncidentId(input);\n const key = this._chatRecoveryIncidentKey(incidentId);\n const now = input.nowMs ?? Date.now();\n await this._sweepStaleChatRecoveryIncidents(now);\n const existing = await this.ctx.storage.get<ChatRecoveryIncident>(key);\n\n // Forward-progress detection. A mid-turn deploy resets the Durable Object\n // (\"code was updated\"); the interrupted continuation is re-detected on the\n // next wake. A turn that followed real progress (more durably-produced\n // content than the last attempt saw) is environmental churn, not a poison\n // turn.\n const prevProgress = existing?.progress ?? 0;\n const currentProgress = await this._chatRecoveryProgressMarker();\n const madeProgress = existing != null && currentProgress > prevProgress;\n\n // Wall-clock-keyed-to-progress budget (#1637). The raw attempt count is the\n // wrong primary bound under deploy churn: one rollout drops/reconnects the\n // socket several times (~11–22s), each firing an alarm, so a count inflates\n // far faster than the real interruption rate and seals a healthy turn.\n // • PRIMARY — no-progress window: `lastProgressAt` resets on every\n // progress-bearing attempt, so a turn that keeps producing content\n // survives churn indefinitely; a stuck turn is sealed after 5 min.\n // • DEBOUNCE — alarms bunched within `ALARM_DEBOUNCE_MS` collapse into one\n // attempt, so a single rollout's reconnect storm isn't N attempts.\n // • SECONDARY — the attempt cap is a high backstop (resets on progress).\n // • ABSOLUTE — the 15-min incident-age ceiling never resets (final stop).\n const lastProgressAt = madeProgress\n ? now\n : (existing?.lastProgressAt ?? existing?.firstSeenAt ?? now);\n const noProgressExceeded =\n existing != null &&\n now - lastProgressAt > CHAT_RECOVERY_NO_PROGRESS_WINDOW_MS;\n const incidentAgeExceeded =\n existing != null &&\n now - existing.firstSeenAt > CHAT_RECOVERY_MAX_WINDOW_MS;\n const debounced =\n existing != null &&\n !madeProgress &&\n now - existing.lastAttemptAt < CHAT_RECOVERY_ALARM_DEBOUNCE_MS;\n\n const attempt = madeProgress\n ? 1\n : debounced\n ? (existing?.attempt ?? 1)\n : (existing?.attempt ?? 0) + 1;\n const exhausted =\n noProgressExceeded || incidentAgeExceeded || attempt > config.maxAttempts;\n const incident: ChatRecoveryIncident = {\n incidentId,\n requestId: input.requestId,\n recoveryRootRequestId: input.recoveryRootRequestId ?? input.requestId,\n recoveryKind: input.recoveryKind,\n attempt,\n maxAttempts: config.maxAttempts,\n status: exhausted ? \"exhausted\" : \"attempting\",\n firstSeenAt: existing?.firstSeenAt ?? now,\n lastAttemptAt: now,\n lastProgressAt,\n progress: Math.max(prevProgress, currentProgress),\n ...(exhausted\n ? {\n reason: incidentAgeExceeded\n ? \"max_recovery_window_exceeded\"\n : noProgressExceeded\n ? \"no_progress_timeout\"\n : \"max_attempts_exceeded\"\n }\n : {})\n };\n await this.ctx.storage.put(key, incident);\n\n if (!existing) {\n this._emit(\"chat:recovery:detected\", {\n incidentId,\n requestId: input.requestId,\n attempt,\n maxAttempts: config.maxAttempts,\n recoveryKind: input.recoveryKind\n });\n }\n this._emit(\"chat:recovery:attempt\", {\n incidentId,\n requestId: input.requestId,\n attempt,\n maxAttempts: config.maxAttempts,\n recoveryKind: input.recoveryKind\n });\n\n return { incident, config, exhausted };\n }\n\n private async _updateChatRecoveryIncident(\n incidentId: string | undefined,\n status: ChatRecoveryIncident[\"status\"],\n reason?: string\n ): Promise<void> {\n if (!incidentId) return;\n const key = this._chatRecoveryIncidentKey(incidentId);\n const incident = await this.ctx.storage.get<ChatRecoveryIncident>(key);\n if (!incident) return;\n // A completed recovery is terminal and will not be retried, so drop the\n // record instead of leaving it in storage forever. Non-completed states\n // (scheduled/skipped/failed) are retained so the attempt budget survives\n // across restarts; the TTL sweep eventually reclaims abandoned ones.\n if (status === \"completed\") {\n await this.ctx.storage.delete(key);\n } else {\n await this.ctx.storage.put(key, {\n ...incident,\n status,\n ...(reason ? { reason } : {})\n } satisfies ChatRecoveryIncident);\n }\n\n const eventType =\n status === \"completed\"\n ? \"chat:recovery:completed\"\n : status === \"skipped\"\n ? \"chat:recovery:skipped\"\n : status === \"failed\"\n ? \"chat:recovery:failed\"\n : undefined;\n if (eventType) {\n this._emit(eventType, {\n incidentId,\n requestId: incident.requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind: incident.recoveryKind,\n ...(reason ? { reason } : {})\n });\n }\n\n // Live \"recovering…\" status (#1620): a scheduled continuation/retry means\n // recovery is in progress; a terminal incident state resolves it. Keyed by\n // the recovery-root request id so it lines up with the turn the client is\n // watching. (Exhaustion + normal completion also clear via\n // `_recordTerminalChatStatus`; this covers the benign-skip / failed paths\n // that never reach a turn-level terminal.)\n if (status === \"scheduled\") {\n await this._setChatRecovering(\n true,\n incident.recoveryRootRequestId ?? incident.requestId\n );\n } else if (\n status === \"completed\" ||\n status === \"skipped\" ||\n status === \"failed\"\n ) {\n await this._setChatRecovering(false);\n }\n }\n\n private async _exhaustChatRecovery(\n incident: ChatRecoveryIncident,\n config: ResolvedChatRecoveryConfig,\n partial: { text: string; parts: MessagePart[] },\n streamId: string,\n createdAt: number\n ): Promise<void> {\n const ctx: ChatRecoveryExhaustedContext = {\n incidentId: incident.incidentId,\n requestId: incident.requestId,\n recoveryRootRequestId:\n incident.recoveryRootRequestId ?? incident.requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind: incident.recoveryKind,\n streamId,\n createdAt,\n partialText: partial.text,\n partialParts: partial.parts,\n reason: incident.reason ?? \"max_attempts_exceeded\",\n terminalMessage: config.terminalMessage\n };\n this._emit(\"chat:recovery:exhausted\", ctx);\n // A throwing onExhausted hook must not prevent the terminal UX from being\n // delivered, otherwise the turn wedges with no user-visible resolution.\n try {\n await config.onExhausted?.(ctx);\n } catch (error) {\n console.error(\"[Think] chatRecovery onExhausted hook threw\", error);\n }\n // Deliver the user-visible terminal banner BEFORE the bookkeeping storage\n // writes below. A `ctx.storage` write can reject mid-deploy (the exact\n // window recovery exhausts in), and if it threw before this broadcast the\n // user would be left staring at a half-finished message with no terminal\n // resolution. The broadcast itself touches no storage, so ordering it first\n // makes the banner resilient to a failing `_markRecoveredSubmissionInterrupted`\n // / `_recordTerminalChatStatus`.\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: incident.requestId,\n body: config.terminalMessage,\n done: true,\n error: true\n });\n // The submission is keyed by the recovery ROOT request id; `incident.requestId`\n // is the latest per-continuation id and won't match a chained submission.\n await this._markRecoveredSubmissionInterrupted(\n incident.recoveryRootRequestId ?? incident.requestId,\n config.terminalMessage\n );\n await this._recordTerminalChatStatus(\n \"interrupted\",\n incident.requestId,\n config.terminalMessage\n );\n // The exhausted record is retained for inspection and reclaimed later by\n // the TTL sweep; only successful (completed) incidents are deleted eagerly.\n }\n\n /**\n * Route a stream-stall watchdog abort into bounded recovery instead of a\n * terminal error (#1626). A stall happens inside a LIVE isolate (no DO\n * restart), so the normal restart-detected recovery path never runs — we\n * open/advance a recovery incident here and schedule a continuation, reusing\n * the SAME budget (`maxAttempts` + wall-clock window + progress-aware reset)\n * as deploy/eviction recovery. A transient hang recovers; a persistently\n * hanging provider exhausts the budget. Idempotency matches deploy recovery:\n * settled tool results are durable and won't re-run, but a tool that was\n * mid-execution when the stall fired re-runs on the continuation.\n *\n * Returns:\n * - `\"scheduled\"` — a continuation was scheduled; the caller suppresses the\n * terminal error and closes the stream cleanly.\n * - `\"exhausted\"` — the budget is spent; this routes through the SAME\n * `_exhaustChatRecovery` path as deploy recovery (fires `onExhausted`,\n * emits `chat:recovery:exhausted`, marks the submission interrupted, and\n * delivers the configured `terminalMessage`). The caller must NOT run the\n * generic terminal path — the terminal UX is already delivered.\n * - `\"disabled\"` — chat recovery is off; the caller falls through to the\n * generic terminal error (the watchdog's original \"kill the spinner\"\n * behavior, unchanged).\n */\n private async _routeStallToBoundedRecovery(input: {\n requestId: string;\n streamId: string;\n partialParts: MessagePart[];\n targetAssistantId?: string;\n }): Promise<\"scheduled\" | \"exhausted\" | \"disabled\"> {\n // Stall-recovery is automatic only when chat recovery is enabled (the\n // default for Think). With recovery off, a stall stays terminal — there is\n // no budget/continuation machinery to route into.\n if (!this._resolveChatRecoveryConfig().enabled) return \"disabled\";\n const recoveryRootRequestId =\n this._activeChatRecoveryRootRequestId ?? input.requestId;\n const latestUserMessageId =\n [...this.messages].reverse().find((m) => m.role === \"user\")?.id ?? null;\n const { incident, config, exhausted } =\n await this._beginChatRecoveryIncident({\n requestId: input.requestId,\n recoveryRootRequestId,\n latestUserMessageId,\n recoveryKind: \"continue\"\n });\n if (exhausted) {\n // Budget spent: deliver the SAME terminal UX as deploy-recovery\n // exhaustion (terminalMessage + onExhausted + chat:recovery:exhausted +\n // submission interrupted) instead of letting the raw stall error leak\n // out. `firstSeenAt` is the closest available turn-start proxy here.\n const partialText = input.partialParts\n .filter(\n (p): p is { type: \"text\"; text: string } =>\n (p as { type?: string }).type === \"text\"\n )\n .map((p) => p.text)\n .join(\"\");\n await this._exhaustChatRecovery(\n incident,\n config,\n { text: partialText, parts: input.partialParts },\n input.streamId,\n incident.firstSeenAt\n );\n return \"exhausted\";\n }\n await this._updateChatRecoveryIncident(incident.incidentId, \"scheduled\");\n this._emit(\"chat:recovery:scheduled\", {\n incidentId: incident.incidentId,\n requestId: input.requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind: \"continue\"\n });\n // If a durable submission is running for this turn, the continuation must\n // complete it (otherwise the submission hangs) — same as deploy recovery.\n const recoveredRequestId = this._hasRunningSubmission(recoveryRootRequestId)\n ? recoveryRootRequestId\n : undefined;\n await this.schedule(\n 0,\n \"_chatRecoveryContinue\",\n {\n ...(input.targetAssistantId\n ? { targetAssistantId: input.targetAssistantId }\n : {}),\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n lastBody: this._lastBody ?? null,\n lastClientTools: this._lastClientTools ?? null,\n ...(recoveredRequestId ? { recoveredRequestId } : {})\n },\n { idempotent: true }\n );\n return \"scheduled\";\n }\n\n protected override async _handleInternalFiberRecovery(\n ctx: FiberRecoveryContext\n ): Promise<boolean> {\n if (await this._messengerRuntime?.handleFiberRecovery(ctx)) {\n return true;\n }\n\n const chatPrefix = (this.constructor as typeof Think).CHAT_FIBER_NAME + \":\";\n if (!ctx.name.startsWith(chatPrefix)) {\n return false;\n }\n\n const requestId = ctx.name.slice(chatPrefix.length);\n const { snapshot: recoverySnapshot, user: recoveryData } =\n unwrapChatFiberSnapshot<\"think-chat-turn\">(\n \"__cfThinkChatFiberSnapshot\",\n ctx.snapshot,\n \"think-chat-turn\"\n );\n\n let streamId = \"\";\n let streamStatus: \"streaming\" | \"completed\" | \"error\" | undefined;\n if (requestId) {\n const rows = this.sql<{\n id: string;\n status: \"streaming\" | \"completed\" | \"error\";\n }>`\n SELECT id, status FROM cf_ai_chat_stream_metadata\n WHERE request_id = ${requestId}\n ORDER BY created_at DESC LIMIT 1\n `;\n if (rows.length > 0) {\n streamId = rows[0].id;\n streamStatus = rows[0].status;\n }\n }\n if (!streamId && this._resumableStream.hasActiveStream()) {\n streamId = this._resumableStream.activeStreamId ?? \"\";\n streamStatus = \"streaming\";\n }\n\n const partial = streamId\n ? this._getPartialStreamText(streamId)\n : { text: \"\", parts: [] as MessagePart[] };\n\n const streamStillActive =\n streamId &&\n this._resumableStream.hasActiveStream() &&\n this._resumableStream.activeStreamId === streamId;\n\n const streamIsTerminal =\n streamStatus === \"completed\" || streamStatus === \"error\";\n\n const retryTargetUserId = await this._recoverablePreStreamUserId(\n recoverySnapshot,\n streamId ?? \"\",\n partial\n );\n const shouldRetryBase = retryTargetUserId !== null && !streamIsTerminal;\n const recoveryKind: ChatRecoveryKind = shouldRetryBase\n ? \"retry\"\n : \"continue\";\n const recoveryRootRequestId =\n recoverySnapshot?.recoveryRootRequestId ?? requestId;\n const { incident, config, exhausted } =\n await this._beginChatRecoveryIncident({\n requestId,\n recoveryRootRequestId,\n latestUserMessageId: recoverySnapshot?.latestUserMessageId,\n recoveryKind\n });\n\n if (exhausted) {\n // Preserve the settled partial before sealing the turn. Exhaustion is\n // decided BEFORE `onChatRecovery` is consulted, so without this the\n // settled (often non-idempotent) tool results the turn already produced\n // are discarded and the model re-runs them on the next message (#1631).\n // Same gating as the normal path below so an already-persisted partial is\n // never duplicated.\n if (\n await this._shouldPersistOrphanedPartial(streamId, {\n streamStillActive: Boolean(streamStillActive),\n streamIsTerminal,\n snapshot: recoverySnapshot\n })\n ) {\n await this._persistOrphanedStream(streamId);\n }\n await this._exhaustChatRecovery(\n incident,\n config,\n partial,\n streamId ?? \"\",\n ctx.createdAt\n );\n return true;\n }\n\n // Any throw after the incident is opened (user `onChatRecovery`, orphan\n // persistence, scheduling) must flip the incident to a terminal `failed`\n // state and emit, otherwise it leaks in `attempting` and is never\n // observable as a stuck turn.\n try {\n const options =\n (await this.onChatRecovery({\n incidentId: incident.incidentId,\n recoveryRootRequestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind,\n streamId: streamId ?? \"\",\n requestId,\n partialText: partial.text,\n partialParts: partial.parts,\n recoveryData,\n messages: [...this.messages],\n lastBody: recoverySnapshot?.lastBody ?? this._lastBody,\n lastClientTools:\n recoverySnapshot?.lastClientTools ?? this._lastClientTools,\n createdAt: ctx.createdAt\n })) ?? {};\n\n const shouldPersist = await this._shouldPersistOrphanedPartial(streamId, {\n streamStillActive: Boolean(streamStillActive),\n streamIsTerminal,\n snapshot: recoverySnapshot\n });\n\n // Settled work — completed, often non-idempotent tool results — is NEVER\n // dropped by recovery. `persist: false` only suppresses persistence of a\n // partial that has nothing settled to lose; a partial carrying settled\n // tool results is persisted regardless, so an app can never accidentally\n // discard completed work (and never needs `{ persist: true }` just to be\n // safe). A safe default beats a warning about an unsafe one (#1631).\n if (\n shouldPersist &&\n (options.persist !== false ||\n this._partialHasSettledToolResults(partial.parts))\n ) {\n await this._persistOrphanedStream(streamId);\n }\n\n if (streamStillActive) {\n this._resumableStream.complete(streamId);\n }\n\n const shouldRetry =\n retryTargetUserId !== null &&\n options.continue !== false &&\n !streamIsTerminal;\n const lastLeaf = shouldRetry ? null : await this.session.getLatestLeaf();\n const targetId =\n lastLeaf?.role === \"assistant\" && !streamIsTerminal\n ? lastLeaf.id\n : undefined;\n const canContinue =\n !shouldRetry && options.continue !== false && !streamIsTerminal;\n // The durable submission is keyed by the recovery ROOT request id (stable\n // across the whole continuation chain), not this turn's per-continuation\n // requestId. Keying off `requestId` loses the link on every chained\n // continuation, so the continuation that finally completes the turn can no\n // longer mark the submission done (see investigate/recovery-* findings).\n const hasRunningSubmission = this._hasRunningSubmission(\n recoveryRootRequestId\n );\n\n if (streamIsTerminal && hasRunningSubmission) {\n await this._completeRecoveredSubmission(\n recoveryRootRequestId,\n streamStatus === \"completed\" ? \"completed\" : \"error\",\n requestId,\n streamStatus === \"completed\"\n ? null\n : \"Recovered chat stream had already errored.\"\n );\n }\n\n const recoveredRequestId =\n (canContinue || shouldRetry) && hasRunningSubmission\n ? recoveryRootRequestId\n : undefined;\n\n if (shouldRetry) {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"scheduled\"\n );\n this._emit(\"chat:recovery:scheduled\", {\n incidentId: incident.incidentId,\n requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind\n });\n await this.schedule(\n 0,\n \"_chatRecoveryRetry\",\n {\n targetUserId: retryTargetUserId,\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n lastBody: recoverySnapshot?.lastBody ?? null,\n lastClientTools: recoverySnapshot?.lastClientTools ?? null,\n ...(recoveredRequestId ? { recoveredRequestId } : {})\n },\n { idempotent: true }\n );\n } else if (canContinue) {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"scheduled\"\n );\n this._emit(\"chat:recovery:scheduled\", {\n incidentId: incident.incidentId,\n requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind\n });\n await this.schedule(\n 0,\n \"_chatRecoveryContinue\",\n {\n ...(targetId ? { targetAssistantId: targetId } : {}),\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n ...(recoverySnapshot\n ? {\n lastBody: recoverySnapshot.lastBody ?? null,\n lastClientTools: recoverySnapshot.lastClientTools ?? null\n }\n : {}),\n ...(recoveredRequestId ? { recoveredRequestId } : {})\n },\n { idempotent: true }\n );\n } else if (options.continue === false && !streamIsTerminal) {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"skipped\",\n \"continue_disabled\"\n );\n const disabledMessage =\n \"Submission was interrupted and chat recovery was disabled.\";\n // Key off the recovery ROOT, not this continuation's `requestId` — a\n // chained submission's row still carries the root id, so passing the\n // per-continuation id would miss it and leave it stuck `running`.\n await this._markRecoveredSubmissionInterrupted(\n recoveryRootRequestId,\n disabledMessage\n );\n // Unlike `conversation_changed` (a newer turn owns the UI, so silence\n // is correct), disabling recovery abandons the turn with no superseding\n // turn. Surface it like exhaustion so a reconnecting client isn't frozen.\n await this._recordTerminalChatStatus(\n \"interrupted\",\n requestId,\n disabledMessage\n );\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: disabledMessage,\n done: true,\n error: true\n });\n } else {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"skipped\",\n streamIsTerminal ? \"stream_terminal\" : \"not_recoverable\"\n );\n }\n\n return true;\n } catch (error) {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"failed\",\n error instanceof Error ? error.message : String(error)\n );\n throw error;\n }\n }\n\n private async _recoverablePreStreamUserId(\n snapshot: ChatFiberSnapshot<\"think-chat-turn\"> | null,\n streamId: string,\n partial: { text: string; parts: MessagePart[] }\n ): Promise<string | null> {\n if (\n !snapshot ||\n snapshot.continuation ||\n !snapshot.latestUserMessageId ||\n streamId ||\n partial.text ||\n partial.parts.length > 0\n ) {\n return null;\n }\n\n const lastLeaf = await this.session.getLatestLeaf();\n return lastLeaf?.role === \"user\" &&\n lastLeaf.id === snapshot.latestUserMessageId\n ? snapshot.latestUserMessageId\n : null;\n }\n\n private async _hasPersistedRecoveredAssistant(\n snapshot: ChatFiberSnapshot<\"think-chat-turn\"> | null\n ): Promise<boolean> {\n const lastLeaf = await this.session.getLatestLeaf();\n return (\n lastLeaf?.role === \"assistant\" &&\n lastLeaf.id !== snapshot?.latestMessageId\n );\n }\n\n /**\n * Whether the orphaned stream's partial should be materialized into an\n * assistant message: there is a stream, and it is either still active or\n * terminal-but-not-yet-persisted. Shared by the normal recovery path AND the\n * exhaustion path so neither discards settled work nor duplicates a partial\n * an earlier attempt already saved.\n */\n private async _shouldPersistOrphanedPartial(\n streamId: string,\n opts: {\n streamStillActive: boolean;\n streamIsTerminal: boolean;\n snapshot: ChatFiberSnapshot<\"think-chat-turn\"> | null;\n }\n ): Promise<boolean> {\n if (!streamId) return false;\n const alreadyPersisted =\n opts.streamIsTerminal &&\n (await this._hasPersistedRecoveredAssistant(opts.snapshot));\n return (\n opts.streamStillActive || (opts.streamIsTerminal && !alreadyPersisted)\n );\n }\n\n /** Whether a reconstructed partial carries any settled (provider-accepted)\n * tool result — the completed, often non-idempotent work that a\n * `{ persist: false }` recovery return would silently discard. */\n private _partialHasSettledToolResults(parts: MessagePart[]): boolean {\n return parts.some((part) => {\n const record = part as Record<string, unknown>;\n const type = typeof record.type === \"string\" ? record.type : \"\";\n return (\n (type.startsWith(\"tool-\") || type === \"dynamic-tool\") &&\n this._toolPartHasSettledResult(record)\n );\n });\n }\n\n /**\n * Reschedule a recovery callback that timed out waiting for stable state,\n * consuming one attempt. Returns `true` if rescheduled, `false` if the\n * attempt budget is exhausted (the caller then fails the turn terminally).\n *\n * Shared by `_chatRecoveryRetry` and `_chatRecoveryContinue` so the\n * non-idempotent scheduling invariant lives in exactly one place — a fix to\n * one path can't silently diverge from the other. Mirrors the same helper in\n * `@cloudflare/ai-chat`.\n */\n private async _rescheduleRecoveryAfterStableTimeout(\n callback: \"_chatRecoveryContinue\" | \"_chatRecoveryRetry\",\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined,\n maxAttempts: number\n ): Promise<boolean> {\n const incidentKey = data?.incidentId\n ? this._chatRecoveryIncidentKey(data.incidentId)\n : null;\n const incident = incidentKey\n ? await this.ctx.storage.get<ChatRecoveryIncident>(incidentKey)\n : null;\n if (!incident || !incidentKey) return false;\n const attempt = incident.attempt ?? 0;\n if (attempt >= (incident.maxAttempts ?? maxAttempts)) return false;\n await this.ctx.storage.put(incidentKey, {\n ...incident,\n attempt: attempt + 1,\n status: \"scheduled\",\n lastAttemptAt: Date.now(),\n reason: \"stable_timeout_retry\"\n });\n // Must NOT be idempotent: this runs INSIDE the currently-executing one-shot\n // schedule row (which `alarm()` deletes only after we return). An idempotent\n // reschedule would dedup onto that row and then be deleted with it — the\n // retry would silently never fire, stalling the turn. A fresh delayed row\n // survives the deletion.\n await this.schedule(\n CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS,\n callback,\n data ?? {},\n { idempotent: false }\n );\n return true;\n }\n\n /**\n * Resolve the stream id for a recovery turn so the give-up terminalization\n * can surface whatever partial the turn produced. Prefers the durable stream\n * row keyed by the recovery-root request id; falls back to the live active\n * stream. Returns `\"\"` when neither is available (the terminal banner still\n * fires — `_exhaustChatRecovery` does not require a stream).\n */\n private _resolveRecoveryStreamId(requestId: string): string {\n if (requestId) {\n const fromMetadata = this._resumableStream\n .getAllStreamMetadata()\n .find((metadata) => metadata.request_id === requestId)?.id;\n if (fromMetadata) return fromMetadata;\n }\n return this._resumableStream.hasActiveStream()\n ? (this._resumableStream.activeStreamId ?? \"\")\n : \"\";\n }\n\n /**\n * Terminalize a recovery turn that is giving up — whether because the\n * stable-state-timeout retry budget drained, or because the recovery\n * continuation threw a non-recoverable error — by routing through the SAME\n * `_exhaustChatRecovery` path as deploy-recovery and stall exhaustion\n * (#1626/#1631). It fires `onExhausted`, emits `chat:recovery:exhausted`,\n * marks the durable submission interrupted, records the terminal chat status,\n * and delivers the configured `terminalMessage`. `reason` carries the cause\n * (`stable_timeout` for a budget give-up, `recovery_error` for a thrown\n * error) through to `onExhausted` / `chat:recovery:exhausted`.\n *\n * This replaces the older give-up that only set the incident to `failed` and\n * completed the recovered submission as `error`, which bypassed\n * `_exhaustChatRecovery` entirely — so an app relying on `onExhausted` for the\n * terminal banner regressed to an eternal spinner when recovery gave up under\n * extreme churn. The error path matters just as much: a non-reset throw in a\n * recovery callback is SWALLOWED by `Agent._executeScheduleCallback` (only a\n * code-update reset is re-thrown to preserve the one-shot row), so without\n * routing it here the alarm row is deleted with no terminal UX at all — the\n * half-finished message wedges silently. Shared by `_chatRecoveryRetry` and\n * `_chatRecoveryContinue`.\n *\n * Exactly-once terminalization is defended by two independent guards:\n * 1. The `stored?.status === \"exhausted\"` re-entry guard below — once an\n * incident is sealed, a duplicate stale alarm (or retried callback)\n * returns before re-firing. The sealed incident is re-persisted even when\n * the record was found missing, so a swept record is re-armed for the\n * guard on the next alarm.\n * 2. The durable-submission paths additionally short-circuit earlier at the\n * `submission_not_running` check (the submission is already `error` after\n * the first give-up). This is the ONLY guard `@cloudflare/ai-chat` lacks\n * (no submission layer), so guard #1 carries it there.\n *\n * Two residual at-least-once edges, both deliberately accepted as \"deliver a\n * second banner\" ≫ \"silently drop the turn\":\n * • No `incidentId` at all in the payload (only reachable via a direct/test\n * invocation — every production scheduler carries one): the synthesized\n * incident can't be persisted (no key), so guard #1 can't arm.\n * • The record is swept AGAIN between two alarms (guard #1 re-persists on the\n * first, so this needs a second independent sweep) — vanishingly unlikely.\n */\n private async _exhaustRecoveryGiveUp(\n callback: \"_chatRecoveryContinue\" | \"_chatRecoveryRetry\",\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined,\n reason: string\n ): Promise<void> {\n const config = this._resolveChatRecoveryConfig();\n const incidentKey = data?.incidentId\n ? this._chatRecoveryIncidentKey(data.incidentId)\n : null;\n // The incident read/write below are best-effort: they back the re-entry\n // guard, not the terminal UX. Under deploy storage stress they can reject,\n // but terminalization MUST still fire — a failed bookkeeping op here is\n // exactly what used to drop the turn silently. So tolerate a failed read\n // (synthesize the incident) and a failed write (accept a possible second\n // banner) rather than letting either abort `_exhaustChatRecovery`.\n let stored: ChatRecoveryIncident | null = null;\n if (incidentKey) {\n try {\n stored =\n (await this.ctx.storage.get<ChatRecoveryIncident>(incidentKey)) ??\n null;\n } catch (readError) {\n console.error(\n \"[Think] failed to read recovery incident during give-up; synthesizing\",\n readError\n );\n }\n }\n\n // Re-entry guard #1 (see method doc): a sealed incident means\n // terminalization already happened, so a duplicate stale alarm must not\n // re-fire `onExhausted` / re-broadcast the banner.\n if (stored?.status === \"exhausted\") return;\n\n const rootRequestId =\n data?.originalRequestId ??\n data?.recoveredRequestId ??\n this._activeChatRecoveryRootRequestId ??\n stored?.recoveryRootRequestId ??\n stored?.requestId ??\n \"\";\n\n const incident: ChatRecoveryIncident = stored\n ? { ...stored, status: \"exhausted\", reason }\n : {\n // Silent-drop guard: the incident record is gone (no `incidentId`, or\n // it was swept/deleted before this stale alarm fired). Synthesize a\n // minimal incident so the turn STILL terminalizes through\n // `onExhausted` instead of being dropped with no terminal UX — the\n // exact \"eternal spinner\" failure mode this fix closes.\n incidentId: data?.incidentId ?? crypto.randomUUID(),\n requestId: rootRequestId,\n recoveryRootRequestId: rootRequestId,\n recoveryKind:\n callback === \"_chatRecoveryRetry\" ? \"retry\" : \"continue\",\n attempt: config.maxAttempts,\n maxAttempts: config.maxAttempts,\n status: \"exhausted\",\n firstSeenAt: Date.now(),\n lastAttemptAt: Date.now(),\n reason\n };\n\n // Persist the sealed incident (retained for inspection / TTL sweep) so the\n // re-entry guard above sees `exhausted` if a duplicate stale alarm fires.\n // Best-effort: a failed persist must not block terminalization below.\n if (incidentKey) {\n try {\n await this.ctx.storage.put(incidentKey, incident);\n } catch (writeError) {\n console.error(\n \"[Think] failed to persist sealed recovery incident during give-up\",\n writeError\n );\n }\n }\n\n const streamId = this._resolveRecoveryStreamId(\n incident.recoveryRootRequestId ?? incident.requestId\n );\n const partial = streamId\n ? this._getPartialStreamText(streamId)\n : { text: \"\", parts: [] as MessagePart[] };\n\n await this._exhaustChatRecovery(\n incident,\n config,\n partial,\n streamId,\n incident.firstSeenAt\n );\n }\n\n /**\n * Give-up after the stable-state-timeout retry budget drained. Thin wrapper\n * over `_exhaustRecoveryGiveUp` so the give-up cause is recorded as\n * `stable_timeout`.\n */\n private _exhaustRecoveryAfterStableTimeout(\n callback: \"_chatRecoveryContinue\" | \"_chatRecoveryRetry\",\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined\n ): Promise<void> {\n return this._exhaustRecoveryGiveUp(callback, data, \"stable_timeout\");\n }\n\n /**\n * Whether an error is a transient \"superseded isolate\" failure — a deploy /\n * code update replaced the isolate mid-invocation. Mirrors the base `Agent`\n * check (`isDurableObjectCodeUpdateReset`) and MUST stay in lockstep with it:\n * the base `_executeScheduleCallback` re-throws this class for a one-shot row\n * (preserving it so the platform re-runs on the new code), so a recovery\n * callback must also re-throw — NOT terminalize — since recovery will re-run\n * and succeed on the fresh isolate. The matched family (kept identical to the\n * base):\n * - \"Durable Object reset because its code was updated.\" (deploy bounce)\n * - \"This script has been upgraded. Please send a new request to connect to\n * the new version.\" (a stub/connection to a superseded script)\n * \"Network connection lost.\" is intentionally excluded (a connection error,\n * not an isolate replacement — see the base helper's note). The match stays\n * close to the verbatim platform strings so an ordinary error mentioning\n * those words isn't misclassified as a supersede.\n */\n private _isDeployCodeUpdateReset(error: unknown): boolean {\n const message =\n error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : \"\";\n return /reset because its code was updated|this script has been upgraded/i.test(\n message\n );\n }\n\n /**\n * Handle an error thrown by `_chatRecoveryContinue` / `_chatRecoveryRetry`\n * after the incident was opened.\n *\n * - A deploy code-update reset is re-thrown (after marking the incident\n * `failed` for observability) so `Agent._executeScheduleCallback` preserves\n * the one-shot alarm row and the platform re-runs recovery on the fresh\n * isolate — the turn can still recover, so it must NOT terminalize.\n * - Any OTHER error is terminalized through the give-up path\n * (`onExhausted` + the `terminalMessage` banner) and NOT re-thrown. This is\n * the fix for the silent-seal failure mode: `_executeScheduleCallback`\n * swallows a non-reset throw and then `alarm()` deletes the one-shot row, so\n * without terminalizing here the half-finished turn is dropped with no\n * terminal event and no banner (the user stares at a frozen message until\n * they send something new).\n */\n private async _handleRecoveryCallbackError(\n callback: \"_chatRecoveryContinue\" | \"_chatRecoveryRetry\",\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined,\n error: unknown\n ): Promise<void> {\n if (this._isDeployCodeUpdateReset(error)) {\n const message = error instanceof Error ? error.message : String(error);\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"failed\",\n message\n );\n if (data?.recoveredRequestId) {\n await this._completeRecoveredSubmission(\n data.recoveredRequestId,\n \"error\",\n null,\n message\n );\n }\n throw error;\n }\n // Preserve the underlying error for operators — the give-up path records\n // only the `recovery_error` category on the incident / `onExhausted` ctx,\n // so without this log the actual cause (e.g. a transient storage reject)\n // would be lost. Mirrors `Agent._executeScheduleCallback`'s own logging.\n console.error(\n `[Think] ${callback} threw during recovery; terminalizing instead of leaving the turn wedged`,\n error\n );\n // `_exhaustRecoveryGiveUp` marks the submission interrupted + records the\n // terminal chat status itself (via `_exhaustChatRecovery`), so it fully\n // replaces the old mark-failed + complete-as-error bookkeeping here.\n await this._exhaustRecoveryGiveUp(callback, data, \"recovery_error\");\n }\n\n async _chatRecoveryRetry(data?: ChatRecoveryRetryData): Promise<void> {\n const recoveredSubmission = data?.recoveredRequestId\n ? this._readRunningSubmissionByRequestId(data.recoveredRequestId)\n : null;\n if (data?.recoveredRequestId && !recoveredSubmission) {\n await this._updateChatRecoveryIncident(\n data.incidentId,\n \"skipped\",\n \"submission_not_running\"\n );\n return;\n }\n\n const previousRootRequestId = this._activeChatRecoveryRootRequestId;\n this._activeChatRecoveryRootRequestId =\n data?.originalRequestId ?? previousRootRequestId;\n const controller = recoveredSubmission ? new AbortController() : null;\n if (recoveredSubmission && controller) {\n this._submissionAbortControllers.set(\n recoveredSubmission.submission_id,\n controller\n );\n }\n\n try {\n const recoveryConfig = this._resolveChatRecoveryConfig();\n const ready = await this.waitUntilStable({\n timeout: recoveryConfig.stableTimeoutMs\n });\n if (!ready) {\n // Transient under churn — reschedule within the attempt budget rather\n // than terminally failing the turn (see _chatRecoveryContinue).\n if (\n await this._rescheduleRecoveryAfterStableTimeout(\n \"_chatRecoveryRetry\",\n data,\n recoveryConfig.maxAttempts\n )\n ) {\n return;\n }\n // Budget spent: terminalize through the SAME exhaustion path as deploy\n // recovery (fires `onExhausted`, delivers the `terminalMessage` banner,\n // marks the submission interrupted) instead of silently dropping the\n // turn — otherwise an app relying on `onExhausted` sees an eternal\n // spinner.\n await this._exhaustRecoveryAfterStableTimeout(\n \"_chatRecoveryRetry\",\n data\n );\n return;\n }\n\n const lastLeaf = await this.session.getLatestLeaf();\n if (!lastLeaf || lastLeaf.role !== \"user\") {\n // The user turn is no longer the leaf — it was already answered (an\n // assistant message now follows) or the conversation moved on. This is\n // a benign skip, not an error: a completing turn marks the submission\n // `completed`; otherwise it is terminally `skipped`, never `error`.\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"skipped\",\n \"no_unanswered_user_message\"\n );\n if (data?.recoveredRequestId) {\n await this._completeRecoveredSubmission(\n data.recoveredRequestId,\n \"skipped\",\n null,\n null\n );\n }\n return;\n }\n\n if (data?.targetUserId && lastLeaf.id !== data.targetUserId) {\n // Superseded by a genuinely newer user turn — terminal `skipped`, not an\n // error (recovery being superseded is benign).\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"skipped\",\n \"conversation_changed\"\n );\n if (data?.recoveredRequestId) {\n await this._completeRecoveredSubmission(\n data.recoveredRequestId,\n \"skipped\",\n null,\n null\n );\n }\n return;\n }\n\n this._applyRecoveredRequestContext(data);\n const result = await this._retryLastUserTurn(\n this._lastClientTools,\n this._lastBody,\n controller ? { signal: controller.signal } : undefined\n );\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n result.status === \"completed\"\n ? \"completed\"\n : result.status === \"skipped\"\n ? \"skipped\"\n : \"failed\",\n result.error\n );\n if (data?.recoveredRequestId) {\n await this._completeRecoveredSubmission(\n data.recoveredRequestId,\n result.status,\n result.requestId || null,\n result.status === \"completed\"\n ? null\n : (result.error ?? `Recovery retry ${result.status}.`)\n );\n }\n } catch (error) {\n await this._handleRecoveryCallbackError(\n \"_chatRecoveryRetry\",\n data,\n error\n );\n } finally {\n this._activeChatRecoveryRootRequestId = previousRootRequestId;\n if (recoveredSubmission) {\n this._submissionAbortControllers.delete(\n recoveredSubmission.submission_id\n );\n }\n }\n }\n\n private _hasRunningSubmission(requestId: string): boolean {\n return this._readRunningSubmissionByRequestId(requestId) !== null;\n }\n\n private _readRunningSubmissionByRequestId(\n requestId: string\n ): ThinkSubmissionRow | null {\n this._ensureSubmissionTable();\n const rows = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE request_id = ${requestId}\n AND status = 'running'\n LIMIT 1\n `;\n return rows[0] ?? null;\n }\n\n private async _markRecoveredSubmissionInterrupted(\n requestId: string,\n message: string\n ): Promise<void> {\n this._ensureSubmissionTable();\n const rows = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE request_id = ${requestId}\n AND status = 'running'\n LIMIT 1\n `;\n const row = rows[0];\n if (!row) return;\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'error',\n error_message = ${message},\n completed_at = ${Date.now()}\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n `;\n const updated = this._readSubmission(row.submission_id);\n if (updated) await this._emitSubmissionStatus(updated);\n }\n\n private async _completeRecoveredSubmission(\n originalRequestId: string,\n status: ThinkSubmissionStatus,\n requestId: string | null,\n errorMessage: string | null\n ): Promise<void> {\n this._ensureSubmissionTable();\n const completedAt = Date.now();\n const streamId = requestId\n ? (this._resumableStream\n .getAllStreamMetadata()\n .find((metadata) => metadata.request_id === requestId)?.id ?? null)\n : null;\n this.sql`\n UPDATE cf_think_submissions\n SET status = ${status},\n request_id = COALESCE(${requestId}, request_id),\n stream_id = COALESCE(${streamId}, stream_id),\n error_message = ${errorMessage},\n completed_at = ${completedAt}\n WHERE request_id = ${originalRequestId}\n AND status = 'running'\n `;\n const rows = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE request_id = COALESCE(${requestId}, ${originalRequestId})\n ORDER BY completed_at DESC\n LIMIT 1\n `;\n const updated = rows[0];\n if (updated && this._isTerminalSubmissionStatus(updated.status)) {\n await this._emitSubmissionStatus(updated);\n }\n }\n\n protected async onChatRecovery(\n _ctx: ChatRecoveryContext\n ): Promise<ChatRecoveryOptions | void> {\n return {};\n }\n\n async _chatRecoveryContinue(data?: ChatRecoveryContinueData): Promise<void> {\n const recoveredSubmission = data?.recoveredRequestId\n ? this._readRunningSubmissionByRequestId(data.recoveredRequestId)\n : null;\n if (data?.recoveredRequestId && !recoveredSubmission) {\n await this._updateChatRecoveryIncident(\n data.incidentId,\n \"skipped\",\n \"submission_not_running\"\n );\n return;\n }\n\n const previousRootRequestId = this._activeChatRecoveryRootRequestId;\n this._activeChatRecoveryRootRequestId =\n data?.originalRequestId ?? previousRootRequestId;\n const controller = recoveredSubmission ? new AbortController() : null;\n if (recoveredSubmission && controller) {\n this._submissionAbortControllers.set(\n recoveredSubmission.submission_id,\n controller\n );\n }\n\n try {\n const recoveryConfig = this._resolveChatRecoveryConfig();\n const ready = await this.waitUntilStable({\n timeout: recoveryConfig.stableTimeoutMs\n });\n if (!ready) {\n console.warn(\n \"[Think] _chatRecoveryContinue timed out waiting for stable state\"\n );\n // A stable-state timeout under deploy churn is usually transient (the\n // isolate is still settling / another deploy is in flight). Reschedule\n // within the attempt budget instead of terminally failing the turn at\n // attempt 1; only give up once the budget is genuinely exhausted.\n if (\n await this._rescheduleRecoveryAfterStableTimeout(\n \"_chatRecoveryContinue\",\n data,\n recoveryConfig.maxAttempts\n )\n ) {\n return;\n }\n // Budget spent: terminalize through the SAME exhaustion path as deploy\n // recovery (fires `onExhausted`, delivers the `terminalMessage` banner,\n // marks the submission interrupted) instead of silently dropping the\n // turn — otherwise an app relying on `onExhausted` sees an eternal\n // spinner.\n await this._exhaustRecoveryAfterStableTimeout(\n \"_chatRecoveryContinue\",\n data\n );\n return;\n }\n\n const targetId = data?.targetAssistantId;\n const lastLeaf = await this.session.getLatestLeaf();\n if (targetId && lastLeaf?.id !== targetId) {\n // The target assistant message is no longer the leaf. This is NOT an\n // error and must never clobber the submission to `error`:\n // - leaf is an ASSISTANT message → recovery's OWN later continuation\n // advanced (or already completed) this turn. This continuation is\n // stale/superseded; skip benignly and leave the submission alone so\n // the active continuation marks the real outcome (`completed`).\n // - leaf is a USER message → a genuinely newer turn superseded this\n // one; mark the submission `skipped` (terminal, non-error) so it\n // doesn't hang waiting on a turn nobody will finish.\n const supersededByNewerUserTurn = lastLeaf?.role === \"user\";\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"skipped\",\n \"conversation_changed\"\n );\n if (data?.recoveredRequestId && supersededByNewerUserTurn) {\n await this._completeRecoveredSubmission(\n data.recoveredRequestId,\n \"skipped\",\n null,\n null\n );\n }\n return;\n }\n\n this._applyRecoveredRequestContext(data);\n const result = await this.continueLastTurn(\n undefined,\n controller ? { signal: controller.signal } : undefined\n );\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n result.status === \"completed\"\n ? \"completed\"\n : result.status === \"skipped\"\n ? \"skipped\"\n : \"failed\",\n result.error\n );\n if (data?.recoveredRequestId) {\n await this._completeRecoveredSubmission(\n data.recoveredRequestId,\n result.status,\n result.requestId || null,\n result.status === \"completed\"\n ? null\n : (result.error ?? `Recovery ${result.status}.`)\n );\n }\n } catch (error) {\n await this._handleRecoveryCallbackError(\n \"_chatRecoveryContinue\",\n data,\n error\n );\n } finally {\n this._activeChatRecoveryRootRequestId = previousRootRequestId;\n if (recoveredSubmission) {\n this._submissionAbortControllers.delete(\n recoveredSubmission.submission_id\n );\n }\n }\n }\n\n private _applyRecoveredRequestContext(\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined\n ): void {\n if (!data) return;\n if (\"lastClientTools\" in data) {\n this._lastClientTools = data.lastClientTools ?? undefined;\n this._persistClientTools();\n }\n if (\"lastBody\" in data) {\n this._lastBody = data.lastBody ?? undefined;\n this._persistBody();\n }\n }\n\n private _getPartialStreamText(streamId: string): {\n text: string;\n parts: MessagePart[];\n } {\n const chunks = this._resumableStream.getStreamChunks(streamId);\n const parts: MessagePart[] = [];\n\n for (const chunk of chunks) {\n try {\n const data = JSON.parse(chunk.body);\n applyChunkToParts(parts, data);\n } catch {\n // skip malformed chunks\n }\n }\n\n const text = parts\n .filter(\n (p): p is MessagePart & { type: \"text\"; text: string } =>\n p.type === \"text\" && \"text\" in p\n )\n .map((p) => p.text)\n .join(\"\");\n\n return { text, parts };\n }\n\n // ── Concurrency strategies ──────────────────────────────────────\n\n private _getSubmitConcurrencyDecision(\n isSubmitMessage: boolean\n ): SubmitConcurrencyDecision {\n return this._submitConcurrency.decide({\n concurrency: this.messageConcurrency,\n isSubmitMessage,\n queuedTurns: this._turnQueue.queuedCount()\n });\n }\n\n private _completeSkippedRequest(\n connection: Connection,\n requestId: string\n ): void {\n connection.send(\n JSON.stringify({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n })\n );\n }\n\n private _rollbackDroppedSubmit(connection: Connection): void {\n connection.send(\n JSON.stringify({\n type: MSG_CHAT_MESSAGES,\n messages: this.messages\n })\n );\n }\n\n // ── Auto-continuation ──────────────────────────────────────────\n\n private _scheduleAutoContinuation(connection: Connection): void {\n if (this._continuation.pending?.pastCoalesce) {\n this._continuation.deferred = {\n connection,\n connectionId: connection.id,\n clientTools: this._lastClientTools,\n body: undefined,\n errorPrefix: \"[Think] Auto-continuation failed:\",\n prerequisite: null\n };\n return;\n }\n\n if (this._continuation.pending) {\n this._continuation.pending.connection = connection;\n this._continuation.pending.connectionId = connection.id;\n this._continuation.pending.clientTools = this._lastClientTools;\n this._continuation.awaitingConnections.set(connection.id, connection);\n this._resetAutoContinuationTimer();\n return;\n }\n\n this._continuation.pending = {\n connection,\n connectionId: connection.id,\n requestId: crypto.randomUUID(),\n clientTools: this._lastClientTools,\n body: undefined,\n errorPrefix: \"[Think] Auto-continuation failed:\",\n prerequisite: null,\n pastCoalesce: false\n };\n this._continuation.awaitingConnections.set(connection.id, connection);\n this._resetAutoContinuationTimer();\n }\n\n /**\n * Re-arm the barrier for a tool result/approval that arrived WITHOUT\n * `autoContinue` (#1650). The client sends `autoContinue: false` for an\n * errored tool result (it declines to auto-continue a standalone error), but\n * in a parallel batch a SIBLING may already have requested continuation — and\n * this result can be the one that completes the batch. In that case we must\n * re-run the barrier check so the continuation the sibling requested still\n * fires once the batch is whole.\n *\n * Unlike `_scheduleAutoContinuation` this never CREATES a pending\n * continuation: a standalone errored tool (no opted-in sibling, so no pending)\n * must not auto-continue. It also no-ops once the continuation is running\n * (`pastCoalesce`) — a late result then defers/applies through the normal\n * path rather than re-arming.\n */\n private _rearmPendingAutoContinuationForBatch(): void {\n const pending = this._continuation.pending;\n if (!pending || pending.pastCoalesce) return;\n this._resetAutoContinuationTimer();\n }\n\n /**\n * Called when a streaming assistant turn finalizes (its message, with ALL\n * tool parts, is now persisted). Clears the in-flight accumulator and re-runs\n * the auto-continuation barrier for a continuation the stream-active gate held\n * (#1650). This is essential for an all-fast parallel batch whose every result\n * landed mid-stream: once the stream ends there is no further tool-result\n * event to re-arm the barrier, so without this re-check the held continuation\n * would never fire. A slow batch is also re-checked here and simply continues\n * to hold (event-driven) until its remaining siblings answer.\n */\n private _onStreamingTurnFinalized(): void {\n this._streamingAssistant = null;\n this._rearmPendingAutoContinuationForBatch();\n }\n\n private _resetAutoContinuationTimer(): void {\n if (this._continuationTimer) {\n clearTimeout(this._continuationTimer);\n }\n this._continuationTimer = setTimeout(() => {\n this._continuationTimer = null;\n const pending = this._continuation.pending;\n if (!pending) return;\n this._fireAutoContinuationWhenStable(pending.connection);\n }, 50);\n }\n\n /**\n * Fire an auto-continuation, but only once the model's parallel tool-call\n * batch is fully answered (#1649). When the model emits several tool calls in\n * one step the client answers each independently, so the first `autoContinue`\n * arrives while slower siblings are still `input-available`. Continuing then\n * would feed the provider an incomplete tool-result set\n * (`MissingToolResultsError`) or, via the transcript-repair backstop, silently\n * error the in-flight sibling and run a spurious extra continuation.\n *\n * The barrier is event-driven (#1650). Auto-continuation is only ever\n * triggered by a tool-result/approval event, so rather than wait on a fixed\n * timer we drain the in-flight applies, re-check, and — if the batch is still\n * incomplete — return WITHOUT firing and WITHOUT holding the isolate, leaving\n * `_continuation.pending` in place. The next sibling's result re-arms the\n * coalesce timer (`_scheduleAutoContinuation`) and re-runs this check; the\n * continuation fires once the final sibling lands. If the in-memory pending\n * state is lost to eviction between siblings, the final result re-creates it\n * from the persisted transcript and fires with a complete batch — self-healing.\n * A true orphan (a sibling that never arrives) simply never auto-continues,\n * which is correct: there is nothing valid to continue, and a later user turn\n * / chat recovery repairs the transcript.\n *\n * The barrier also holds while the assistant turn is still streaming (the\n * stream-active gate below): mid-stream the batch can still grow with tool\n * calls the model hasn't emitted yet, so no completeness check is meaningful.\n * `_onStreamingTurnFinalized` re-runs the check once the stream ends.\n */\n private _fireAutoContinuationWhenStable(connection: Connection): void {\n if (!this._continuation.pending) return;\n // The continuation is already running (a sibling result re-armed the timer\n // after it started). New results coalesce/defer into it — don't double-fire.\n if (this._continuation.pending.pastCoalesce) return;\n // A drain is already in progress; the sibling that re-armed the timer is\n // absorbed by it. Only one drain must run, and it re-checks on completion.\n if (this._continuationBarrierActive) return;\n // Stream-active gate (#1650, #1649). While the model is still streaming the\n // assistant turn we CANNOT know the parallel tool batch is complete: the\n // model emits tool calls sequentially, so a fast client tool can resolve\n // before its slower siblings have even been streamed. At that point the\n // siblings exist nowhere — not in `this.messages`, not in the in-flight\n // `_streamingAssistant` accumulator — so no batch check can see them, and\n // firing now would enqueue a continuation that repairs the (later\n // materialized, still-pending) siblings to errored. The only signal that\n // \"more tool calls may still arrive\" is that the stream is open, so we hold\n // without firing. `_onStreamingTurnFinalized` re-runs this check once the\n // stream ends and the batch is fully materialized, and any later sibling\n // result re-arms it via `_scheduleAutoContinuation`.\n if (this._streamingAssistant) return;\n // Fast path: no apply in flight and the leaf step is not mid-batch.\n if (!this._pendingInteractionPromise && !this._hasIncompleteToolBatch()) {\n this._fireAutoContinuation(connection);\n return;\n }\n this._continuationBarrierActive = true;\n // keepAlive only for the bounded drain — the duration of the applies that\n // have ALREADY arrived, not an open-ended wait for siblings that haven't.\n // The pending-continuation state is in-memory, so we must not hibernate\n // mid-apply; once the drain returns we release and let the isolate idle.\n this.keepAliveWhile(() => this._drainInteractionApplies())\n .catch(() => {})\n .finally(() => {\n // Clear the flag and re-check synchronously — no `await` between here\n // and the fire/return decision, so a sibling-armed coalesce timer (a\n // macrotask) cannot interleave and double-fire. `_fireAutoContinuation`\n // cancels that timer; the incomplete-return path leaves it armed so the\n // sibling that armed it re-runs this check when it fires.\n this._continuationBarrierActive = false;\n const pending = this._continuation.pending;\n if (!pending || pending.pastCoalesce) return;\n // A stream (re)started during the drain — hold; the finalize re-trigger\n // will re-check once the batch is fully materialized.\n if (this._streamingAssistant) return;\n // Still waiting on an unanswered sibling — return without firing. The\n // result that completes the batch re-triggers this check via its own\n // `_scheduleAutoContinuation`; we do not pin the isolate in the interim.\n if (this._hasIncompleteToolBatch()) return;\n this._fireAutoContinuation(pending.connection);\n });\n }\n\n /**\n * Drain every in-flight tool-result/approval apply, including any enqueued\n * while we wait, so the subsequent `_hasIncompleteToolBatch()` re-check sees\n * every result that has ALREADY arrived. Bounded by real apply activity (a\n * storage write each), never by a fixed timer: a batch with no further\n * results drains in the time its pending applies take and then returns. The\n * loop re-reads `_interactionApplyTail` after each await because a sibling can\n * extend the tail mid-drain; we stop once the tail stops advancing.\n */\n private async _drainInteractionApplies(): Promise<void> {\n let tail = this._interactionApplyTail;\n // Bounded: each iteration only continues if a NEW apply was chained during\n // the await, and applies are not self-perpetuating (only an inbound result\n // enqueues one), so the tail necessarily stabilizes.\n for (;;) {\n // The pending continuation was cleared (chat clear / turn reset) — nothing\n // to drain for; bail so the isolate isn't held by a stale drain.\n if (!this._continuation.pending) return;\n try {\n await tail;\n } catch {\n // A rejected apply is irrelevant to completeness — re-read and re-check.\n }\n if (this._interactionApplyTail === tail) return;\n tail = this._interactionApplyTail;\n }\n }\n\n /**\n * `true` when the latest assistant message is mid-batch: it carries at least\n * one settled tool result AND at least one tool call/approval still awaiting a\n * client result. That is the #1649 signature — the model fanned out parallel\n * tool calls and only some have been answered. Scoped to the leaf (the step\n * the continuation answers) so an unrelated dangling tool in an earlier\n * message doesn't block a legitimate follow-up continuation.\n */\n private _hasIncompleteToolBatch(): boolean {\n // Zero-allocation backward scan for the latest assistant message — this\n // runs on every barrier poll tick, and `this.messages` can be large.\n const messages = this.messages;\n let leaf: (typeof messages)[number] | undefined;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === \"assistant\") {\n leaf = messages[i];\n break;\n }\n }\n if (!leaf) return false;\n let hasPending = false;\n let hasSettled = false;\n for (const part of leaf.parts) {\n const record = part as Record<string, unknown>;\n const state = record.state;\n if (state === \"input-available\" || state === \"approval-requested\") {\n hasPending = true;\n } else if (\n typeof record.type === \"string\" &&\n (record.type.startsWith(\"tool-\") || record.type === \"dynamic-tool\") &&\n (state === \"output-available\" ||\n state === \"output-error\" ||\n state === \"output-denied\" ||\n state === \"approval-responded\")\n ) {\n hasSettled = true;\n }\n if (hasPending && hasSettled) return true;\n }\n return false;\n }\n\n private _fireAutoContinuation(connection: Connection): void {\n const pending = this._continuation.pending;\n if (!pending) return;\n\n // Cancel any still-armed coalesce timer so a sibling result that re-armed\n // it during a barrier wait can't fire a duplicate continuation after this\n // one starts (#1649).\n if (this._continuationTimer) {\n clearTimeout(this._continuationTimer);\n this._continuationTimer = null;\n }\n\n const { requestId, clientTools } = pending;\n const abortSignal = this._aborts.getSignal(requestId);\n\n this.keepAliveWhile(async () => {\n await this._turnQueue.enqueue(requestId, async () => {\n if (this._continuation.pending) {\n this._continuation.pending.pastCoalesce = true;\n }\n let streamed = false;\n try {\n const continuationBody = async () => {\n const result = await agentContext.run(\n {\n agent: this,\n connection,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n clientTools,\n body: this._lastBody,\n continuation: true\n })\n );\n if (result) {\n await this._streamResult(requestId, result, abortSignal, {\n continuation: true\n });\n streamed = true;\n }\n };\n\n if (this.chatRecovery) {\n await this._runChatRecoveryFiber(requestId, true, continuationBody);\n } else {\n await continuationBody();\n }\n } finally {\n this._aborts.remove(requestId);\n if (!streamed) {\n this._continuation.sendResumeNone();\n }\n this._continuation.clearPending();\n this._activateDeferredContinuation();\n }\n });\n }).catch((error) => {\n console.error(\"[Think] Auto-continuation failed:\", error);\n this._aborts.remove(requestId);\n });\n }\n\n private _activateDeferredContinuation(): void {\n const pending = this._continuation.activateDeferred(() =>\n crypto.randomUUID()\n );\n if (!pending) return;\n\n this._fireAutoContinuationWhenStable(pending.connection);\n }\n\n // ── Response hook ──────────────────────────────────────────────\n\n private async _fireResponseHook(result: ChatResponseResult): Promise<void> {\n // Record the terminal status durably so a client connecting after the turn\n // ended still learns its outcome (see `_buildIdleConnectMessages`).\n await this._recordTerminalChatStatus(\n result.status,\n result.requestId,\n result.error ?? \"The assistant was interrupted.\"\n );\n if (this._insideResponseHook) return;\n this._insideResponseHook = true;\n try {\n await this.onChatResponse(result);\n } catch (err) {\n console.error(\"[Think] onChatResponse error:\", err);\n } finally {\n this._insideResponseHook = false;\n }\n }\n\n /**\n * Persist (on `error`) or clear (on `completed`/`aborted`) a durable record of\n * the last terminal turn so it can be replayed to clients on connect. A\n * `completed`/`aborted` turn is conveyed by the persisted messages, so the\n * record is cleared; an `error`/`interrupted` turn has no durable trace\n * otherwise, so it is kept until a later turn resolves.\n */\n private async _recordTerminalChatStatus(\n status: ChatResponseResult[\"status\"] | \"interrupted\",\n requestId: string,\n body: string\n ): Promise<void> {\n if (status === \"error\" || status === \"interrupted\") {\n await this.ctx.storage.put(CHAT_LAST_TERMINAL_KEY, { requestId, body });\n } else {\n await this.ctx.storage.delete(CHAT_LAST_TERMINAL_KEY);\n }\n // Any terminal turn outcome resolves an in-progress recovery (#1620): a\n // recovered turn that completes, errors, or is exhausted must clear the\n // \"recovering…\" indicator so it never spins forever.\n await this._setChatRecovering(false);\n }\n\n private async _pendingTerminalChatResponse(): Promise<{\n requestId: string;\n body: string;\n } | null> {\n return (\n (await this.ctx.storage.get<{ requestId: string; body: string }>(\n CHAT_LAST_TERMINAL_KEY\n )) ?? null\n );\n }\n\n /**\n * Set or clear the live \"recovering…\" status for a durable chat turn (#1620).\n * Persists a durable record (replayed on connect via `_buildIdleConnectMessages`)\n * and broadcasts a `MSG_CHAT_RECOVERING` frame — but only on a genuine\n * transition, so a deploy/reconnect storm (which re-detects recovery many\n * times) doesn't spam the wire. Cleared on every terminal outcome so the\n * indicator can't spin forever.\n */\n private async _setChatRecovering(\n active: boolean,\n requestId?: string\n ): Promise<void> {\n const existing = await this.ctx.storage.get<{\n requestId?: string;\n at?: number;\n }>(CHAT_RECOVERING_KEY);\n // A record older than the max recovery window is stale: the owning incident\n // was abandoned without ever reaching a terminal (e.g. the DO went idle\n // before recovery could exhaust), so its terminal-clear never ran. Treat it\n // as not-recovering so a stuck record can neither pin the indicator \"on\"\n // forever nor suppress a genuinely-new recovering signal.\n const activeExisting =\n existing && Date.now() - (existing.at ?? 0) < CHAT_RECOVERY_MAX_WINDOW_MS;\n if (active) {\n if (activeExisting) return; // already recovering — idempotent, no re-broadcast\n await this.ctx.storage.put(CHAT_RECOVERING_KEY, {\n ...(requestId ? { requestId } : {}),\n at: Date.now()\n });\n } else {\n if (!existing) return; // not recovering — nothing to clear\n await this.ctx.storage.delete(CHAT_RECOVERING_KEY);\n requestId = requestId ?? existing.requestId;\n }\n this._broadcastChat({\n type: MSG_CHAT_RECOVERING,\n recovering: active,\n ...(requestId ? { id: requestId } : {})\n });\n }\n\n /**\n * Messages sent to a client on connect when no stream is active: the current\n * transcript, plus a replay of the last terminal error (if any) so a turn\n * that failed while the client was disconnected is surfaced rather than\n * silently frozen.\n */\n private async _buildIdleConnectMessages(): Promise<\n Array<Record<string, unknown>>\n > {\n const messages: Array<Record<string, unknown>> = [\n { type: MSG_CHAT_MESSAGES, messages: this.messages }\n ];\n const pending = await this._pendingTerminalChatResponse();\n if (pending) {\n messages.push({\n type: MSG_CHAT_RESPONSE,\n id: pending.requestId,\n body: pending.body,\n done: true,\n error: true\n });\n }\n // Replay an in-progress \"recovering…\" status so a client that connects\n // mid-recovery reads the turn as working rather than frozen (#1620). It's\n // mutually exclusive with `pending` (a terminal outcome clears recovering).\n // Skip a stale record (older than the max recovery window) so a turn whose\n // recovery was abandoned without a terminal can't show \"recovering…\"\n // forever on reconnect.\n const recovering = await this.ctx.storage.get<{\n requestId?: string;\n at?: number;\n }>(CHAT_RECOVERING_KEY);\n if (\n recovering &&\n Date.now() - (recovering.at ?? 0) < CHAT_RECOVERY_MAX_WINDOW_MS\n ) {\n messages.push({\n type: MSG_CHAT_RECOVERING,\n recovering: true,\n ...(recovering.requestId ? { id: recovering.requestId } : {})\n });\n }\n return messages;\n }\n\n // ── Resume helpers ──────────────────────────────────────────────\n\n private _notifyStreamResuming(connection: Connection): void {\n if (!this._resumableStream.hasActiveStream()) return;\n const sent = sendIfOpen(\n connection,\n JSON.stringify({\n type: MSG_STREAM_RESUMING,\n id: this._resumableStream.activeRequestId\n })\n );\n if (sent) {\n this._pendingResumeConnections.add(connection.id);\n }\n }\n\n private async _persistOrphanedStream(streamId: string): Promise<void> {\n this._resumableStream.flushBuffer();\n const chunks = this._resumableStream.getStreamChunks(streamId);\n if (chunks.length === 0) return;\n\n const accumulator = new StreamAccumulator({\n messageId: crypto.randomUUID()\n });\n for (const chunk of chunks) {\n try {\n accumulator.applyChunk(JSON.parse(chunk.body) as StreamChunkData);\n } catch {\n // skip malformed chunks\n }\n }\n\n if (accumulator.parts.length > 0) {\n await this._persistAssistantMessage(accumulator.toMessage());\n // NOTE: progress is bumped at production/flush time in `_storeChunkDurably`\n // (#1637), NOT here — persisting on recovery or a client reconnect must\n // not be miscounted as new forward progress.\n this._broadcastMessages();\n }\n }\n\n private _broadcastChat(message: Record<string, unknown>, exclude?: string[]) {\n const allExclusions = [\n ...(exclude || []),\n ...this._pendingResumeConnections\n ];\n this.broadcast(JSON.stringify(message), allExclusions);\n }\n\n private _broadcast(message: Record<string, unknown>, exclude?: string[]) {\n this.broadcast(JSON.stringify(message), exclude);\n }\n\n private _broadcastMessages(exclude?: string[]) {\n this._broadcast(\n { type: MSG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