@cloudflare/think 0.15.0 → 0.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/think.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"think.js","names":["Workspace","Session","agentContext"],"sources":["../src/media-eviction.ts","../src/channels/index.ts","../src/think.ts"],"sourcesContent":["/**\n * Aged-media eviction (#1710).\n *\n * Long-lived sessions accumulate inline base64 media — screenshot/image\n * tool results, data-URL file attachments — in the persisted transcript.\n * Read-time truncation hides that content from the model, but it stays in\n * storage forever and is rehydrated on every wake, so the boot footprint\n * grows with the number of images a session ever produced until SQLite's\n * allocator fails with `SQLITE_NOMEM`.\n *\n * This module rewrites oversized part values in AGED messages (the recent\n * tail is never touched) with small markers, optionally preserving the\n * original bytes as workspace files. Targets:\n *\n * - `file` parts whose `url` is a large `data:` URL — the part is\n * replaced with a text marker;\n * - large string values nested anywhere inside a tool part's `output` —\n * the string is replaced in place, preserving the container shape so\n * tool-specific `toModelOutput` handlers can still replay the result.\n *\n * Plain `text` parts are intentionally NOT evicted: they are user-visible\n * prose, and the row-size limit already bounds them at write time.\n */\n\nimport type { UIMessage } from \"ai\";\n\nexport interface MediaEvictionConfig {\n /**\n * Messages at the tail of the active path that are never evicted.\n * Think clamps this to at least the read-time truncation window\n * (4 messages — the recent span the model replays at full fidelity),\n * so a misconfigured low value can never strip content the model\n * still sees.\n * @default 8\n */\n keepRecentMessages?: number;\n /**\n * Minimum serialized size (in characters; base64 is ASCII so this equals\n * bytes for media) of a single part value to evict.\n * @default 32 * 1024\n */\n minPartBytes?: number;\n /**\n * Preserve evicted values as workspace files under\n * `/attachments/evicted/` instead of dropping them. The marker records\n * the file path.\n * @default true\n */\n externalizeToWorkspace?: boolean;\n /**\n * Maximum oversized stored rows processed per pass. Bounds how long a\n * single pass can take; remaining rows are picked up by later passes.\n * @default 64\n */\n maxRowsPerPass?: number;\n}\n\nexport interface ResolvedMediaEvictionConfig {\n keepRecentMessages: number;\n minPartBytes: number;\n externalizeToWorkspace: boolean;\n maxRowsPerPass: number;\n}\n\nexport function resolveMediaEvictionConfig(\n config: MediaEvictionConfig | boolean\n): ResolvedMediaEvictionConfig | null {\n if (config === false) return null;\n const base = config === true ? {} : config;\n return {\n keepRecentMessages: base.keepRecentMessages ?? 8,\n minPartBytes: base.minPartBytes ?? 32 * 1024,\n externalizeToWorkspace: base.externalizeToWorkspace ?? true,\n maxRowsPerPass: base.maxRowsPerPass ?? 64\n };\n}\n\n/** An oversized value extracted from a message, to be written to the workspace. */\nexport interface EvictedBlob {\n path: string;\n data: string;\n mediaType?: string;\n}\n\nexport interface EvictMessageResult {\n message: UIMessage;\n changed: boolean;\n /** Individual oversized values evicted. */\n parts: number;\n /** Total characters removed from the serialized message. */\n bytes: number;\n /** Values to persist before the rewritten row is stored (may be empty). */\n blobs: EvictedBlob[];\n}\n\nexport interface EvictMessageOptions {\n minPartBytes: number;\n /** When false, evicted values are dropped and markers record size only. */\n externalize: boolean;\n /** Workspace path for the n-th evicted value of this message. */\n pathFor: (index: number, extension: string) => string;\n}\n\nconst MAX_WALK_DEPTH = 8;\n\n/**\n * Replace oversized media values in a message with markers.\n * Returns a new message — the input is not mutated.\n */\nexport function evictLargeMediaFromMessage(\n message: UIMessage,\n options: EvictMessageOptions\n): EvictMessageResult {\n const state = {\n options,\n parts: 0,\n bytes: 0,\n blobs: [] as EvictedBlob[]\n };\n\n let changed = false;\n const parts = message.parts.map((part) => {\n // Large data-URL file attachments → text marker.\n if (part.type === \"file\" && \"url\" in part) {\n const url = (part as { url: string }).url;\n if (\n typeof url === \"string\" &&\n url.startsWith(\"data:\") &&\n url.length >= options.minPartBytes\n ) {\n changed = true;\n const mediaType =\n (part as { mediaType?: string }).mediaType ?? dataUrlMediaType(url);\n const path = extractBlob(state, url, mediaType);\n return {\n type: \"text\" as const,\n text: evictionMarker(url.length, path, mediaType)\n };\n }\n return part;\n }\n\n // Large strings nested in tool outputs → marker strings in place.\n if (\n (part.type.startsWith(\"tool-\") || part.type === \"dynamic-tool\") &&\n \"output\" in part\n ) {\n const output = (part as { output?: unknown }).output;\n if (output !== undefined) {\n const before = state.parts;\n const evicted = walkAndEvict(state, output, 0);\n if (state.parts > before) {\n changed = true;\n return { ...part, output: evicted };\n }\n }\n }\n\n return part;\n }) as UIMessage[\"parts\"];\n\n return {\n message: changed ? { ...message, parts } : message,\n changed,\n parts: state.parts,\n bytes: state.bytes,\n blobs: state.blobs\n };\n}\n\ntype WalkState = {\n options: EvictMessageOptions;\n parts: number;\n bytes: number;\n blobs: EvictedBlob[];\n};\n\nfunction walkAndEvict(\n state: WalkState,\n value: unknown,\n depth: number\n): unknown {\n if (typeof value === \"string\") {\n if (value.length < state.options.minPartBytes) return value;\n const mediaType = value.startsWith(\"data:\")\n ? dataUrlMediaType(value)\n : undefined;\n const path = extractBlob(state, value, mediaType);\n return evictionMarker(value.length, path, mediaType);\n }\n\n if (value === null || typeof value !== \"object\" || depth >= MAX_WALK_DEPTH) {\n return value;\n }\n\n if (Array.isArray(value)) {\n let changed = false;\n const result = value.map((item) => {\n const next = walkAndEvict(state, item, depth + 1);\n if (next !== item) changed = true;\n return next;\n });\n return changed ? result : value;\n }\n\n let changed = false;\n const result: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n const next = walkAndEvict(state, entry, depth + 1);\n if (next !== entry) changed = true;\n result[key] = next;\n }\n return changed ? result : value;\n}\n\n/** Record an evicted value; returns its workspace path or null when dropped. */\nfunction extractBlob(\n state: WalkState,\n data: string,\n mediaType: string | undefined\n): string | null {\n state.parts++;\n state.bytes += data.length;\n if (!state.options.externalize) return null;\n const path = state.options.pathFor(\n state.blobs.length,\n extensionFor(mediaType)\n );\n state.blobs.push({ path, data, mediaType });\n return path;\n}\n\nfunction evictionMarker(\n bytes: number,\n path: string | null,\n mediaType?: string\n): string {\n const media = mediaType ? `${mediaType}, ` : \"\";\n return path\n ? `[evicted ${media}${bytes} bytes; preserved at ${path}]`\n : `[evicted ${media}${bytes} bytes]`;\n}\n\nfunction dataUrlMediaType(url: string): string | undefined {\n const match = /^data:([^;,]+)/.exec(url);\n return match?.[1] || undefined;\n}\n\nfunction extensionFor(mediaType: string | undefined): string {\n if (!mediaType) return \"txt\";\n const subtype = mediaType.split(\"/\")[1]?.replace(/[^a-zA-Z0-9]/g, \"\");\n return subtype || \"bin\";\n}\n","import type { ToolSet } from \"ai\";\nimport type {\n MessengerCapabilities,\n MessengerContext,\n MessengerConversationMode,\n MessengerConversationResolver,\n MessengerDefinition,\n MessengerDeliveryPolicy,\n MessengerDeliverySurface,\n ThinkMessengers\n} from \"../messengers\";\n\n/** Surface family for a channel. Drives the default ingress/delivery wiring. */\nexport type ChannelKind = \"messenger\" | \"web\" | \"voice\" | \"custom\";\n\n/** A channel's capabilities are the same shape as a messenger's. */\nexport type ChannelCapabilities = MessengerCapabilities;\n\n/** A channel's delivery policy is the same shape as a messenger's. */\nexport type ChannelDeliveryPolicy = MessengerDeliveryPolicy;\n\n/** Where a channel posts replies/notices. */\nexport type ChannelDeliverySurface = MessengerDeliverySurface;\n\n/**\n * How events arrive for a channel. A discriminated union so `web`/`voice` do\n * not have to invent webhook fields they don't use. The `webhook` transport is\n * exactly today's messenger ingress (a full {@link MessengerDefinition}).\n */\nexport type ChannelIngress =\n | ({ transport: \"webhook\" } & MessengerDefinition)\n | { transport: \"websocket\" }\n | { transport: \"voice\" };\n\n/**\n * Turn-scoped context the runtime sets when a turn resolves to a channel. For\n * `kind: \"messenger\"` it wraps the existing {@link MessengerContext}.\n */\nexport interface ChannelContext {\n channelId: string;\n kind: ChannelKind;\n capabilities?: ChannelCapabilities;\n messenger?: MessengerContext;\n thread?: string;\n}\n\n/**\n * The public channel contract — the generalization of a messenger: an ingress,\n * a delivery surface, capabilities, conversation routing, a delivery policy, and\n * (new) per-channel policy.\n */\nexport interface ChannelDefinition {\n kind: ChannelKind;\n capabilities?: ChannelCapabilities;\n conversation?: MessengerConversationMode | MessengerConversationResolver;\n delivery?: ChannelDeliveryPolicy;\n /** Per-channel instructions, prepended to the system prompt for this channel. */\n instructions?: string | ((ctx: ChannelContext) => string | Promise<string>);\n /** Narrow the assembled tool set for this channel. */\n tools?: (all: ToolSet) => ToolSet;\n /** Per-channel cap on model steps for a turn. */\n maxTurns?: number;\n ingress: ChannelIngress;\n}\n\nexport type ThinkChannels = Record<string, ChannelDefinition>;\n\nexport type NormalizedChannelDefinition = ChannelDefinition & { id: string };\n\n/** Wrap a {@link MessengerDefinition} as a `kind: \"messenger\"` channel. */\nexport function messengerChannel(\n definition: MessengerDefinition\n): ChannelDefinition {\n return {\n kind: \"messenger\",\n capabilities: definition.capabilities,\n conversation: definition.conversation,\n delivery: definition.delivery,\n ingress: { transport: \"webhook\", ...definition }\n };\n}\n\nfunction messengerFromChannel(\n definition: ChannelDefinition\n): MessengerDefinition | undefined {\n const ingress = definition.ingress;\n if (ingress.transport !== \"webhook\") {\n return undefined;\n }\n const { transport: _transport, ...messenger } = ingress;\n return messenger;\n}\n\nconst IMPLICIT_WEB_CHANNEL: ChannelDefinition = {\n kind: \"web\",\n capabilities: { canStream: true, canEditMessages: true },\n ingress: { transport: \"websocket\" }\n};\n\nexport interface ResolvedChannels {\n /** Every resolved channel keyed by id (registry for per-channel policy). */\n channels: Map<string, NormalizedChannelDefinition>;\n /** Messenger-kind channels mapped back to the runtime's input shape. */\n messengers: ThinkMessengers;\n}\n\n/**\n * Merge the implicit `web` channel, `configureChannels()` entries, and\n * `getMessengers()` entries into a single channel registry, and extract the\n * messenger definitions that feed the unchanged `ThinkMessengerRuntime`.\n *\n * Resolution order: (1) implicit `web`; (2) `configureChannels()`; (3) each\n * `getMessengers()` entry as a `kind: \"messenger\"` channel. A duplicate id\n * across (2) and (3) throws.\n */\nexport function resolveChannels(\n configured: ThinkChannels,\n messengers: ThinkMessengers\n): ResolvedChannels {\n const channels = new Map<string, NormalizedChannelDefinition>();\n channels.set(\"web\", { ...IMPLICIT_WEB_CHANNEL, id: \"web\" });\n\n for (const [id, definition] of Object.entries(configured)) {\n // `web` is reserved for the built-in WebSocket chat surface. Users may\n // override its *policy* (instructions / tool narrowing / maxTurns) with a\n // `{ kind: \"web\" }` entry, but replacing it with another kind would silently\n // break the native chat ingress/delivery path — reject that footgun loudly.\n if (id === \"web\") {\n if (definition.kind !== \"web\") {\n throw new Error(\n `Channel \"web\" is reserved for the built-in WebSocket chat surface; configureChannels() may override its policy with a { kind: \"web\" } entry but cannot replace it with kind \"${definition.kind}\"`\n );\n }\n // Merge over the implicit web defaults so a policy-only override (e.g.\n // just `instructions`) keeps the built-in capabilities/ingress instead of\n // silently dropping them.\n channels.set(\"web\", {\n ...IMPLICIT_WEB_CHANNEL,\n ...definition,\n id: \"web\"\n });\n continue;\n }\n channels.set(id, { ...definition, id });\n }\n\n const messengerDefs: ThinkMessengers = {};\n\n for (const [id, definition] of Object.entries(configured)) {\n const messenger = messengerFromChannel(definition);\n if (definition.kind === \"messenger\" && messenger) {\n messengerDefs[id] = messenger;\n }\n }\n\n for (const [id, definition] of Object.entries(messengers)) {\n // Same reservation as the configureChannels() path: a messenger named\n // \"web\" would overwrite the built-in WebSocket chat surface with a\n // kind: \"messenger\" channel and break native chat ingress/delivery.\n if (id === \"web\") {\n throw new Error(\n `Channel \"web\" is reserved for the built-in WebSocket chat surface and cannot be declared as a messenger via getMessengers()`\n );\n }\n if (Object.prototype.hasOwnProperty.call(configured, id)) {\n throw new Error(\n `Channel id \"${id}\" is declared by both configureChannels() and getMessengers(); channel ids must be unique`\n );\n }\n channels.set(id, { ...messengerChannel(definition), id });\n messengerDefs[id] = definition;\n }\n\n return { channels, messengers: messengerDefs };\n}\n","/**\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 a model id string (resolved via the\n * built-in workers-ai-provider) or a LanguageModel\n * - getSystemPrompt() — return the legacy fallback system prompt\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 *\n * export class MyAgent extends Think<Env> {\n * getModel() {\n * // A string is resolved via the built-in workers-ai-provider off env.AI.\n * // Use a \"@cf/...\" id for Workers AI, or a \"provider/model\" slug like\n * // \"openai/gpt-5.5\" to route through AI Gateway.\n * return \"@cf/moonshotai/kimi-k2.7-code\";\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 { AsyncLocalStorage } from \"node:async_hooks\";\nimport * as aiSdk from \"ai\";\nimport type {\n FlexibleSchema,\n InferSchema,\n InferToolOutput,\n LanguageModel,\n ModelMessage,\n PrepareStepFunction,\n PrepareStepResult,\n StreamTextOnChunkCallback,\n GenerateTextOnStepFinishCallback,\n StopCondition,\n ToolSet,\n TypedToolCall,\n UIMessage\n} from \"ai\";\nimport {\n convertToModelMessages,\n hasToolCall,\n jsonSchema,\n // `stepCountIs` exists in both AI SDK v6 and v7 (v7 keeps it as an alias of\n // `isStepCount`). Using it keeps Think compatible with both majors.\n stepCountIs,\n streamText,\n tool,\n wrapLanguageModel\n} from \"ai\";\n/**\n * Callback type for the AI SDK tool-execution-finished hook, derived from\n * `streamText`'s options so it resolves under both AI SDK v6 and v7 (the\n * exported `OnToolExecutionEndCallback` type is v7-only).\n */\ntype ToolCallFinishCallback = NonNullable<\n Parameters<typeof streamText>[0][\"experimental_onToolCallFinish\"]\n>;\nimport { createAISDKTelemetry, wrapAISDK } from \"agents/observability/ai\";\nimport { createWorkersAI } from \"workers-ai-provider\";\nimport { anthropic } from \"workers-ai-provider/anthropic\";\nimport { openai } from \"workers-ai-provider/openai\";\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 callable,\n getCurrentAgent,\n isDurableObjectMemoryLimitReset,\n isPlatformTransientError,\n __DO_NOT_USE_WILL_BREAK__agentContext as agentContext\n} from \"agents\";\n\nconst agentToolChunkEncoder = new TextEncoder();\nconst agentsAISDKTelemetryBrand = Symbol.for(\n \"cloudflare.agents.ai-sdk-telemetry\"\n);\nconst usesAISDKV7Telemetry = \"registerTelemetry\" in aiSdk;\nimport type {\n AgentToolLifecycleResult,\n AgentToolMilestone,\n AgentToolProgress,\n AgentToolProgressSnapshot,\n AgentToolRunInfo,\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 cleanupStreamBuffers,\n STREAM_CLEANUP_DELAY_SECONDS,\n ContinuationState,\n PreStreamTurns,\n AutoContinuationController,\n TIMED_OUT,\n awaitWithDeadline,\n drainInteractionApplies,\n interceptAgentToolBroadcast,\n AgentToolProgressEmitter,\n SubmitConcurrencyController,\n createToolsFromClientSchemas,\n AbortRegistry,\n applyToolUpdate,\n toolResultUpdate,\n crossMessageToolResultUpdate,\n toolApprovalUpdate,\n pausedExecutionUpdate,\n hasIncompleteToolBatch,\n partAwaitsClientInteraction,\n clientResolvableToolNames,\n parseProtocolMessage,\n aiSdkRecoveryCodec,\n ResumeHandshake,\n normalizeToolInput,\n repairInterruptedToolParts,\n toolPartHasSettledResult,\n persistReconstructedOrphan,\n reconcileMessages,\n resolveToolMergeId,\n createChatFiberSnapshot,\n unwrapChatFiberSnapshot,\n wrapChatFiberSnapshot,\n MAX_BOUND_PARAMS,\n buildInClauseStrings,\n resolveChatRecoveryConfig,\n chatRecoverySchedulePolicy,\n ChatRecoveryEngine,\n runChatRecoveryExhaustion,\n ChatStreamStalledError,\n iterateWithStallWatchdog,\n sweepStaleChatRecoveryIncidents,\n listActiveChatRecoveryIncidents,\n readChatRecoveryProgress,\n bumpChatRecoveryProgress,\n recordChatTerminal,\n clearChatTerminal,\n pendingChatTerminal,\n buildChatRecoveringFrame,\n setChatRecovering,\n AgentToolStreamProgressThrottle,\n StreamProgressCreditThrottle,\n shouldCreditStreamProgress,\n classifyAgentToolChildRecovery,\n type ChatRecoveryAdapter,\n type ChatFiberWakeHooks,\n type ResolvedRecoveryStream,\n type ClassifyRecoveredTurnInput,\n type DispatchRecoveredTurnInput,\n type ChatRecoveryScheduleCallback,\n type ChatRecoveryIncident,\n type ChatRecoveryKind\n} from \"agents/chat\";\nimport type {\n StreamChunkData,\n ClientToolSchema,\n ClientToolExecutor,\n MessagePart,\n SubmitConcurrencyDecision,\n ChatFiberSnapshot,\n OrphanPersistStore\n} from \"agents/chat\";\nimport { Session } from \"agents/experimental/memory/session\";\nimport type { SessionMessage } from \"agents/experimental/memory/session\";\nimport { truncateOlderMessages } from \"agents/experimental/memory/utils\";\nimport {\n evictLargeMediaFromMessage,\n resolveMediaEvictionConfig,\n type MediaEvictionConfig,\n type ResolvedMediaEvictionConfig\n} from \"./media-eviction\";\n\n/**\n * The recent-message span the model sees at FULL fidelity each turn —\n * `truncateOlderMessages`' default `keepRecent` (see `_assembleModelMessages`).\n *\n * Both memory bounds are anchored to this window (#1710):\n * - budgeted hydration never shrinks `this.messages` below it (the floor\n * passed to `session.getRecentHistory`), so windowing cannot starve the\n * model's context;\n * - media eviction never rewrites messages inside it (the\n * `keepRecentMessages` clamp), so content the model still replays at full\n * fidelity is never replaced with markers.\n */\nconst MODEL_RECENT_WINDOW = 4;\nconst DEFAULT_ACTION_TIMEOUT_MS = 30_000;\nconst ACTION_OUTPUT_MAX_CHARS = 20_000;\nconst MAX_REPLY_ATTACHMENTS_PER_TURN = 32;\nconst ACTION_LEDGER_SWEEP_INTERVAL_MS = 60 * 60 * 1000;\nconst ACTION_LEDGER_LAST_SWEPT_KEY = \"cf_think_action_ledger:last_swept_at\";\nconst ACTION_PENDING_SWEEP_INTERVAL_MS = 60 * 60 * 1000;\nconst ACTION_PENDING_LAST_SWEPT_KEY =\n \"cf_think_action_pending_approvals:last_swept_at\";\n/** Prefix for durable-pause action execution ids (vs codemode execution ids). */\nconst ACTION_PAUSE_ID_PREFIX = \"actpause_\";\nimport { Workspace } from \"@cloudflare/shell\";\nimport { createWorkspaceTools } from \"./tools/workspace\";\nimport { createFetchTools } from \"./tools/fetch\";\nimport type { CreateFetchToolsOptions, FetchToolEvent } from \"./tools/fetch\";\nimport { truncatePausedExecutionOutput } from \"./tools/execute\";\nimport { ExtensionManager, sanitizeName } from \"./extensions/manager\";\nimport { ThinkMessengerRuntime } from \"./messengers/chat-sdk\";\nimport type {\n DeliveryKind,\n MessengerContext,\n MessengerDeliverySurface,\n ThinkMessengers,\n MessengerThinkHost\n} from \"./messengers\";\nimport { resolveChannels } from \"./channels\";\nimport type {\n ChannelContext,\n NormalizedChannelDefinition,\n ThinkChannels\n} from \"./channels\";\n\nexport { messengerChannel } from \"./channels\";\nexport type {\n ChannelCapabilities,\n ChannelContext,\n ChannelDefinition,\n ChannelDeliveryPolicy,\n ChannelDeliverySurface,\n ChannelIngress,\n ChannelKind,\n NormalizedChannelDefinition,\n ThinkChannels\n} from \"./channels\";\nexport type { DeliveryKind, DeliveryTag } from \"./messengers\";\nexport { Session } from \"agents/experimental/memory/session\";\nexport type { SessionMessage } 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\";\nexport type {\n CreateFetchToolsOptions,\n FetchBindingTarget,\n FetchResult,\n FetchToolEvent,\n FetchErrorCode,\n FetchResponseMode,\n FetchRedirectPolicy\n} from \"./tools/fetch\";\n\ntype AgentSpanAttributes = Readonly<\n Record<string, string | number | boolean | undefined>\n>;\n\ntype UpdateAgentSpan = (attributes: AgentSpanAttributes) => void;\n\ntype AgentSpanHost = {\n _withAgentSpan<T>(\n operation: string,\n storagePhase: string,\n attributes: AgentSpanAttributes,\n run: (update: UpdateAgentSpan) => T | Promise<T>\n ): T | Promise<T>;\n};\n\nfunction withAgentSpan<T>(\n host: object,\n operation: string,\n storagePhase: string,\n attributes: AgentSpanAttributes,\n run: (update: UpdateAgentSpan) => Promise<T>\n): Promise<T>;\nfunction withAgentSpan<T>(\n host: object,\n operation: string,\n storagePhase: string,\n attributes: AgentSpanAttributes,\n run: (update: UpdateAgentSpan) => T\n): T;\nfunction withAgentSpan<T>(\n host: object,\n operation: string,\n storagePhase: string,\n attributes: AgentSpanAttributes,\n run: (update: UpdateAgentSpan) => T | Promise<T>\n): T | Promise<T> {\n return (host as AgentSpanHost)._withAgentSpan(\n operation,\n storagePhase,\n attributes,\n run\n );\n}\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_MESSAGE_UPDATED = CHAT_MESSAGE_TYPES.MESSAGE_UPDATED;\nconst MSG_CHAT_RECOVERING = CHAT_MESSAGE_TYPES.CHAT_RECOVERING;\n\nfunction shouldMarkSkippedAfterGenerationChange(\n status: SaveMessagesResult[\"status\"]\n): boolean {\n return status === \"completed\";\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === undefined) return \"undefined\";\n if (typeof value === \"function\" || typeof value === \"symbol\") {\n return String(value);\n }\n if (value === null || typeof value !== \"object\") {\n if (typeof value === \"bigint\") return `${value.toString()}n`;\n return JSON.stringify(value) ?? \"undefined\";\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 stableJsonEqual(left: unknown, right: unknown): boolean {\n return stableStringify(left) === stableStringify(right);\n}\n\nfunction actionErrorEnvelope(error: unknown): {\n error: { name: string; message: string };\n} {\n return {\n error: {\n name: error instanceof Error ? error.name : \"Error\",\n message: error instanceof Error ? error.message : String(error)\n }\n };\n}\n\nfunction streamErrorToString(error: unknown): string {\n if (error instanceof Error) return error.message;\n if (typeof error === \"string\") return error;\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n}\n\n/**\n * Normalizes the AI SDK tool-execution-finished event across major versions.\n *\n * Think registers a single `experimental_onToolCallFinish` callback, which is\n * the native option in AI SDK v6 and a supported alias for `onToolExecutionEnd`\n * in AI SDK v7 (resolved internally — see `ai`'s `streamText`). The two majors\n * hand the callback different event shapes:\n *\n * - v6: `{ toolCall, messages, success, output, error, durationMs, stepNumber }`\n * - v7: `{ toolCall, messages, toolExecutionMs, toolOutput: { type, output|error } }`\n * (no `stepNumber`)\n *\n * This collapses both into one shape so the rest of Think stays version-agnostic.\n */\nfunction normalizeToolFinishEvent(event: unknown): {\n toolCall: TypedToolCall<ToolSet>;\n messages: ModelMessage[];\n toolExecutionMs: number;\n stepNumber: number | undefined;\n success: boolean;\n output: unknown;\n error: unknown;\n} {\n const e = event as {\n toolCall: TypedToolCall<ToolSet>;\n messages: ModelMessage[];\n // v7\n toolExecutionMs?: number;\n toolOutput?: { type: string; output?: unknown; error?: unknown };\n // v6\n durationMs?: number;\n success?: boolean;\n output?: unknown;\n error?: unknown;\n stepNumber?: number;\n };\n const toolExecutionMs = e.toolExecutionMs ?? e.durationMs ?? 0;\n if (e.toolOutput) {\n const success = e.toolOutput.type === \"tool-result\";\n return {\n toolCall: e.toolCall,\n messages: e.messages,\n toolExecutionMs,\n // v7 does not provide a step number on this event.\n stepNumber: undefined,\n success,\n output: success ? e.toolOutput.output : undefined,\n error: success ? undefined : e.toolOutput.error\n };\n }\n const success = e.success ?? false;\n return {\n toolCall: e.toolCall,\n messages: e.messages,\n toolExecutionMs,\n stepNumber: e.stepNumber,\n success,\n output: success ? e.output : undefined,\n error: success ? undefined : e.error\n };\n}\n\nasync function* readableStreamToAsyncIterable<T>(\n stream: ReadableStream<T>\n): AsyncIterable<T> {\n const reader = stream.getReader();\n try {\n while (true) {\n const next = await reader.read();\n if (next.done) return;\n yield next.value;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\nfunction actionAuthorizationErrorEnvelope(\n reason: string | undefined,\n permissions: string[]\n): {\n error: { name: string; message: string; permissions: string[] };\n} {\n return {\n error: {\n name: \"ActionAuthorizationError\",\n message: reason ?? \"Action is not authorized\",\n permissions\n }\n };\n}\n\nfunction actionApprovalInputErrorEnvelope(): {\n error: { name: string; message: string };\n} {\n return {\n error: {\n name: \"ActionApprovalInputError\",\n message: \"Approved action input cannot be changed by beforeToolCall\"\n }\n };\n}\n\nfunction actionPendingErrorEnvelope(): {\n error: { name: string; message: string };\n} {\n return {\n error: {\n name: \"ActionPendingError\",\n message:\n \"A prior attempt of this action is in an unknown state; not re-executed. Manual reconciliation may be required.\"\n }\n };\n}\n\nfunction actionKeyConflictEnvelope(\n actionName: string,\n key: string\n): {\n error: { name: string; message: string };\n} {\n return {\n error: {\n name: \"ActionKeyConflict\",\n message: `Idempotency key \"${key}\" for action \"${actionName}\" was reused with different input. This is a programming error; do not retry.`\n }\n };\n}\n\nfunction encodeActionLedgerOutput(\n output: unknown\n): { ok: true; json: string; value: unknown } | { ok: false } {\n try {\n const json = JSON.stringify({\n valuePresent: output !== undefined,\n value: output\n });\n if (json === undefined) return { ok: false };\n const parsed = JSON.parse(json) as {\n valuePresent: boolean;\n value?: unknown;\n };\n if (output !== undefined && !(\"value\" in parsed)) {\n return { ok: false };\n }\n return {\n ok: true,\n json,\n value: parsed.valuePresent ? parsed.value : undefined\n };\n } catch {\n return { ok: false };\n }\n}\n\nfunction decodeActionLedgerOutput(json: string | null): unknown {\n if (json === null) return undefined;\n const parsed = JSON.parse(json) as {\n valuePresent?: unknown;\n value?: unknown;\n };\n return parsed.valuePresent === true ? parsed.value : undefined;\n}\n\nfunction safeStringifyActionOutput(output: unknown): {\n value?: string;\n lossy: boolean;\n error?: string;\n} {\n const seen = new WeakSet<object>();\n let lossy = false;\n try {\n const value = JSON.stringify(output, (_key, value: unknown) => {\n if (typeof value === \"bigint\") {\n lossy = true;\n return `${value.toString()}n`;\n }\n if (typeof value === \"object\" && value !== null) {\n if (seen.has(value)) {\n lossy = true;\n return \"[Circular]\";\n }\n seen.add(value);\n }\n return value;\n });\n return { value, lossy };\n } catch (error) {\n return {\n lossy: true,\n error: error instanceof Error ? error.message : String(error)\n };\n }\n}\n\nfunction prepareActionOutputForModel(output: unknown): unknown {\n if (typeof output === \"string\") {\n if (output.length <= ACTION_OUTPUT_MAX_CHARS) return output;\n return `${output.slice(0, ACTION_OUTPUT_MAX_CHARS)}\\n\\n[truncated ${output.length - ACTION_OUTPUT_MAX_CHARS} chars]`;\n }\n\n const serialized = safeStringifyActionOutput(output);\n if (serialized.error) {\n return {\n serialized: false,\n error: serialized.error\n };\n }\n if (serialized.value === undefined) return output;\n if (serialized.value.length <= ACTION_OUTPUT_MAX_CHARS) {\n if (!serialized.lossy) return output;\n return JSON.parse(serialized.value) as unknown;\n }\n\n return {\n truncated: true,\n chars: serialized.value.length,\n preview: `${serialized.value.slice(0, ACTION_OUTPUT_MAX_CHARS)}\\n\\n[truncated ${serialized.value.length - ACTION_OUTPUT_MAX_CHARS} chars]`\n };\n}\n\nfunction createActionAbortSignal(\n turnSignal: AbortSignal | undefined,\n timeoutMs: number | undefined\n): { signal: AbortSignal; cleanup: () => void } {\n const controller = new AbortController();\n let timeout: ReturnType<typeof setTimeout> | undefined;\n const abortFromTurn = () => controller.abort(turnSignal?.reason);\n\n if (turnSignal?.aborted) {\n abortFromTurn();\n } else {\n turnSignal?.addEventListener(\"abort\", abortFromTurn, { once: true });\n if (timeoutMs !== undefined && timeoutMs > 0) {\n timeout = setTimeout(() => {\n controller.abort(new Error(`Action timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n }\n }\n\n return {\n signal: controller.signal,\n cleanup: () => {\n if (timeout) clearTimeout(timeout);\n turnSignal?.removeEventListener(\"abort\", abortFromTurn);\n }\n };\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 * `Think`'s `classifyRecoveredTurn` detail (the {@link ChatFiberWakeHooks}\n * generic). `retryTargetUserId` is the pre-stream user message the turn re-runs\n * when it had no partial; the dispatch decision re-derives `streamIsTerminal` from\n * `streamStatus` rather than carrying it here.\n */\ntype ThinkRecoveryClassification = { retryTargetUserId: string | null };\n\n// `ChatRecoveryIncident` / `ChatRecoveryKind` / `CHAT_RECOVERY_INCIDENT_KEY_PREFIX`\n// are the canonical shared symbols from `agents/chat` (imported above); the\n// persisted incident shape and key prefix are owned by the engine package so\n// both consumers round-trip the same record across the deploy that ships them.\n\n// The durable, monotonic forward-progress counter (`CHAT_RECOVERY_PROGRESS_KEY`)\n// and its read/bump helpers now live in the shared engine (agents/chat) —\n// `readChatRecoveryProgress` / `bumpChatRecoveryProgress`. Bumped on each durable\n// content flush (`_storeChunkDurably`) — production time, so it reflects genuinely\n// new content and is immune to reconnects/re-persists; never recomputed from the\n// (compactable) transcript.\n// Recovery budget defaults (maxAttempts, maxRecoveryWork, stableTimeoutMs,\n// terminalMessage, noProgressTimeoutMs, alarm debounce) now live in the shared\n// incident engine (agents/chat) and are applied by `resolveChatRecoveryConfig`\n// / `evaluateChatRecoveryIncident`. See design/rfc-chat-recovery-foundation.md.\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// (Stable-state retry delay `CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS` and the\n// incident sweep — TTL selection, key prefix, and batched delete — now live in\n// agents/chat; the reschedule is owned by the shared engine and the sweep by the\n// shared `sweepStaleChatRecoveryIncidents` helper.)\n// (The recovering-flag key/TTL and the stream-cleanup delay/re-arm loop now live\n// in agents/chat — the durable recovery UX is driven via the shared\n// `setChatRecovering` / `buildChatRecoveringFrame` helpers, and buffer cleanup via\n// `STREAM_CLEANUP_DELAY_SECONDS` / `cleanupStreamBuffers`. The N9 throttle lives\n// there too as `AgentToolStreamProgressThrottle`.)\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// (The terminal-record key and the recovering-flag key now live in agents/chat;\n// the durable terminal/recovering records are driven via the shared\n// `recordChatTerminal` / `clearChatTerminal` / `pendingChatTerminal` /\n// `setChatRecovering` / `buildChatRecoveringFrame` helpers.)\n\n/**\n * A best-effort internal `onStart` step that failed on this wake and was\n * skipped so the agent could still come up (#1710).\n *\n * - `transcript-hydration` — reading the persisted conversation into the\n * in-memory message cache failed (e.g. `SQLITE_NOMEM` on an oversized,\n * media-heavy transcript). The agent starts with an empty in-memory view;\n * persisted history is untouched and the next safe-boundary sync retries.\n * - `scheduled-task-reconcile` — declarative scheduled tasks were not\n * reconciled on this wake; the next successful wake reconciles them.\n * - `durable-work-recovery` — pending submissions / workflow notifications\n * were not recovered or drained on this wake.\n */\nexport interface OnStartDegradation {\n step:\n | \"transcript-hydration\"\n | \"scheduled-task-reconcile\"\n | \"durable-work-recovery\";\n error: unknown;\n}\n\nexport type { MediaEvictionConfig } from \"./media-eviction\";\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 onError?: (error: unknown) => string;\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 * Client-defined tool schemas to expose to the model for this turn, mirroring\n * the `clientTools` carried over the WebSocket chat protocol. Use this when a\n * parent agent delegates to a Think sub-agent over RPC but the sub-agent still\n * needs access to tools the client (or parent) defines at runtime.\n *\n * On their own these are execute-less — the model's call surfaces as a tool\n * call through the stream callback. Provide {@link ChatOptions.onClientToolCall}\n * to also resolve those calls inline so the turn can continue to completion.\n */\n clientTools?: ClientToolSchema[];\n /**\n * Executes a client tool call and returns its output, completing the\n * round trip for {@link ChatOptions.clientTools} within the same turn.\n *\n * Without this, a client-tool call has no result and the turn ends with a\n * dangling tool call (the RPC stream callback has no inbound result channel).\n * With it, the model can call a client tool, receive the result, and keep\n * going — the same multi-step behavior the WebSocket path gets from\n * `cf_agent_tool_result` messages.\n */\n onClientToolCall?: ClientToolExecutor;\n /** Channel id this turn belongs to. See {@link RunTurnBase.channel}. */\n channel?: string;\n /**\n * Server-supplied metadata for this turn. Persisted on the turn's user\n * message alongside {@link ChatOptions.channel} (as `metadata.turnMetadata`)\n * so a recovered/continued turn re-resolves it from durable history, and\n * readable during the turn via {@link Think.activeTurnMetadata}.\n *\n * Trust contract mirrors the channel stamp: only server-side callers can set\n * it — reserved metadata keys on client-supplied messages are stripped at\n * intake. This gives messenger/RPC entry points (e.g.\n * {@link Think.chatWithMessengerContext}) a per-turn, recovery-safe carrier\n * for facts like \"which authenticated principal initiated this turn\" without\n * resorting to mutable agent-wide state.\n */\n metadata?: Record<string, unknown>;\n}\n\n/** Input accepted by {@link Think.runTurn}. */\nexport type TurnInputMessages =\n | string\n | UIMessage\n | UIMessage[]\n | ((current: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>);\n\n/** Shared base for {@link RunTurnOptions}; only `input` is common across modes. */\nexport interface RunTurnBase {\n input?: TurnInputMessages;\n /**\n * Channel id this turn belongs to (resolved against `configureChannels()` /\n * `getMessengers()`). Sets the turn-scoped channel context and is persisted on\n * the user message so a recovered/continued turn re-resolves it. Defaults to\n * the implicit `web` channel.\n */\n channel?: string;\n}\n\n/** Options for {@link Think.runTurn} with `mode: \"wait\"` (the default). */\nexport interface RunTurnWait extends RunTurnBase {\n mode?: \"wait\";\n continuation?: boolean;\n body?: Record<string, unknown>;\n signal?: AbortSignal;\n}\n\n/** Options for {@link Think.runTurn} with `mode: \"submit\"`. */\nexport interface RunTurnSubmit extends RunTurnBase {\n mode: \"submit\";\n submissionId?: string;\n idempotencyKey?: string;\n metadata?: Record<string, unknown>;\n}\n\n/** Options for {@link Think.runTurn} with `mode: \"stream\"`. */\nexport interface RunTurnStream extends RunTurnBase {\n mode: \"stream\";\n callback: StreamCallback;\n clientTools?: ClientToolSchema[];\n onClientToolCall?: ClientToolExecutor;\n signal?: AbortSignal;\n}\n\nexport type RunTurnOptions = RunTurnWait | RunTurnSubmit | RunTurnStream;\n\n/** Result of {@link Think.runTurn} in `mode: \"wait\"`. */\nexport type TurnResult = SaveMessagesResult & {\n message?: SessionMessage;\n continuation: boolean;\n};\n\nconst ACTION_BRAND: unique symbol = Symbol.for(\n \"cf.think.action\"\n) as typeof ACTION_BRAND;\n\nexport type ActionKind =\n | \"server\"\n | \"client\"\n | \"approval-gated\"\n | \"durable-pause\"\n | \"delegated-agent\";\n\nexport interface ActionContext {\n /** The agent instance currently executing the action. */\n agent: Think;\n env: Cloudflare.Env;\n /** Current turn request id. */\n requestId: string;\n toolCallId: string;\n /** Model messages visible to the tool call. */\n messages: ReadonlyArray<ModelMessage>;\n /** Combined action timeout and turn abort signal. */\n signal: AbortSignal;\n /**\n * Record an advisory delivery hint for this turn's final reply (voice note,\n * card, email draft, ...). Does not change the model-visible tool output.\n * No-op for approval/permission/idempotency policy evaluation and for\n * durable-pause approved-action resumes (their reply is delivered by a\n * later continuation turn in v1).\n */\n attachReply(attachment: ReplyAttachment): void;\n}\n\n/**\n * The attachment shape accepted by {@link ActionContext.attachReply}. An open\n * union: the named variants give autocomplete for common channels, and the\n * trailing `{ type: string; [k]: unknown }` keeps it extensible. Advisory only\n * — surfaces that don't recognize a `type` ignore it.\n */\nexport type ReplyAttachment =\n | { type: \"voice_note\" }\n | { type: \"email_draft\"; subject?: string; to?: string[] }\n | { type: \"card\"; payload: unknown }\n | { type: string; [k: string]: unknown };\n\nexport type ActionApprovalPolicy<Input> =\n | boolean\n | ((args: {\n input: Input;\n ctx: ActionContext;\n }) => boolean | Promise<boolean>);\n\nexport type ActionPermissionSpec<Input> =\n | readonly string[]\n | ((args: {\n input: Input;\n ctx: ActionContext;\n }) => readonly string[] | Promise<readonly string[]>);\n\nexport type ActionIdempotencyKey<Input> =\n | string\n | ((args: { input: Input; ctx: ActionContext }) => string | Promise<string>);\n\nexport type ActionAuthorizationDecision =\n | boolean\n | {\n allowed: boolean;\n reason?: string;\n grantedPermissions?: readonly string[];\n };\n\nexport interface ActionAuthorizationContext {\n requestId: string;\n toolCallId: string;\n action: string;\n kind: ActionKind;\n input: unknown;\n requiredPermissions: readonly string[];\n grantedPermissions?: readonly string[];\n messages: ReadonlyArray<ModelMessage>;\n agent: Think;\n env: Cloudflare.Env;\n}\n\nexport interface ActionApprovalDescriptor {\n requestId: string;\n toolCallId: string;\n action: string;\n summary: string;\n input: unknown;\n permissions: string[];\n risk?: \"low\" | \"medium\" | \"high\";\n kind: \"approval-gated\" | \"durable-pause\";\n}\n\n/**\n * A single approval awaiting a human decision, unified across pause backends so\n * dashboards/voice/messenger can list and reconcile everything pending with one\n * call. `source: \"action\"` is a parked `kind: \"durable-pause\"` action;\n * `source: \"codemode\"` is a paused `execute`-tool execution. Both resolve via\n * {@link Think.approveExecution} / {@link Think.rejectExecution}.\n */\nexport interface PendingApproval {\n executionId: string;\n source: \"action\" | \"codemode\";\n descriptor: ActionApprovalDescriptor;\n}\n\nexport interface ActionConfig<\n InputSchema extends FlexibleSchema = FlexibleSchema,\n Output = unknown\n> {\n /** Defaults to the registration key when returned from getActions(). */\n name?: string;\n description: string;\n inputSchema: InputSchema;\n /** Reserved metadata; output validation is not enforced yet. */\n outputSchema?: FlexibleSchema<Output>;\n /**\n * Stable key used to replay settled action results without re-running side\n * effects. Use domain identifiers that survive recovery retries (for example,\n * an order id or inbound event id); avoid request ids, timestamps, and random\n * values.\n */\n idempotencyKey?: ActionIdempotencyKey<InferSchema<InputSchema>>;\n permissions?: ActionPermissionSpec<InferSchema<InputSchema>>;\n approval?: ActionApprovalPolicy<InferSchema<InputSchema>>;\n approvalSummary?: string;\n approvalRisk?: \"low\" | \"medium\" | \"high\";\n timeoutMs?: number;\n kind?: ActionKind;\n execute(\n input: InferSchema<InputSchema>,\n ctx: ActionContext\n ): Promise<Output> | Output;\n}\n\nexport interface Action<\n InputSchema extends FlexibleSchema = FlexibleSchema,\n Output = unknown\n> {\n readonly [ACTION_BRAND]: true;\n readonly config: ActionConfig<InputSchema, Output>;\n}\n\nexport function action<\n const InputSchema extends FlexibleSchema,\n Output = unknown\n>(config: ActionConfig<InputSchema, Output>): Action<InputSchema, Output> {\n if (config.kind === \"durable-pause\" && config.approval === false) {\n throw new Error(\n `Action \"${config.name ?? \"(anonymous)\"}\": kind \"durable-pause\" with ` +\n `approval: false never parks for approval, defeating the purpose. ` +\n `Use kind \"server\" for an inline action, or omit approval (or set a ` +\n `predicate) to gate when it parks.`\n );\n }\n const descriptor: Action<InputSchema, Output> = {\n [ACTION_BRAND]: true,\n config: Object.freeze({ ...config })\n };\n return Object.freeze(descriptor);\n}\n\nexport function isAction(value: unknown): value is Action {\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as { [ACTION_BRAND]?: unknown })[ACTION_BRAND] === true\n );\n}\n\ntype CompiledActionMetadata = {\n actionName: string;\n summary: string;\n permissions?: string[];\n risk?: \"low\" | \"medium\" | \"high\";\n kind: \"approval-gated\" | \"durable-pause\";\n};\n\ntype NormalizedActionAuthorization = {\n allowed: boolean;\n reason?: string;\n grantedPermissions?: readonly string[];\n};\n\ntype TurnTrigger =\n | \"ws-chat\"\n | \"rpc\"\n | \"programmatic\"\n | \"submission\"\n | \"scheduled\"\n | \"agent-tool\"\n | \"auto-continuation\"\n | \"recovery-continue\"\n | \"recovery-retry\";\n\ntype TurnAdmission = \"queue\" | \"submit\" | \"execute-submission\";\n\ntype AdmittedQueueResult<T> =\n | { status: \"completed\"; value: T }\n | { status: \"stale\" };\n\ntype QueueTurnSpec<T> = {\n admission: \"queue\";\n trigger: TurnTrigger;\n requestId: string;\n generation?: number;\n continuation?: boolean;\n allowNested?: boolean;\n channel?: string;\n onQueued?: () => void;\n getStatus?: () => string | undefined;\n execute: () => Promise<T>;\n};\n\ntype NonQueueTurnSpec<T> = {\n admission: Exclude<TurnAdmission, \"queue\">;\n trigger: TurnTrigger;\n channel?: string;\n execute: () => Promise<T>;\n};\n\ntype TurnSpec<T> = QueueTurnSpec<T> | NonQueueTurnSpec<T>;\n\nconst admittedTurnContext = new AsyncLocalStorage<{\n agent: unknown;\n requestId: string;\n trigger: TurnTrigger;\n admission: \"queue\";\n channel?: string | undefined;\n continuation?: boolean | undefined;\n generation?: number | undefined;\n}>();\n\n// Drains the underlying model stream when a drain loop exits early (in-stream\n// error break, stall abort, user abort). The AI SDK tees its base stream, so\n// an abandoned tee branch would otherwise leave the tracing wrapper's\n// operation span open forever. One registration is associated with both the\n// stable pre-transform result and any wrapper returned by the test seam.\ntype InferenceStreamFinalizer = {\n started: boolean;\n run: () => Promise<void>;\n};\nconst inferenceStreamFinalizers = new WeakMap<\n object,\n InferenceStreamFinalizer\n>();\n\n/** Options for {@link Think.addMessages}. */\nexport interface AddMessagesOptions {\n /**\n * Parent to attach the first message under. Omitted (`undefined`) attaches to\n * the latest committed leaf at call time; `null` attaches at the root. An\n * explicit id that does not exist throws (fail fast rather than silently\n * misattaching). Subsequent messages in an array chain under the previous one.\n */\n parentId?: string | null;\n /**\n * `\"append\"` (default) inserts new rows, idempotent by message id.\n * `\"upsert\"` inserts, or updates in place when the id already exists (in which\n * case `parentId` is ignored — re-parenting is not supported).\n *\n * Idempotency is by id against the whole session tree, not just the target\n * path: if a message id already exists *anywhere* in history, `\"append\"` is a\n * no-op for it (no new row, no re-parent) and `\"upsert\"` updates it in place\n * wherever it lives. In both modes the next message in the array chains under\n * that existing id, so passing already-present ids mid-array threads new\n * messages onto the existing branch rather than forking a new one.\n */\n mode?: \"append\" | \"upsert\";\n /**\n * Broadcast the change to connected clients. Default `true`. Has no effect\n * when called from inside an active turn (e.g. a tool `execute`), where the\n * live view is intentionally not touched until the next turn's sync.\n */\n broadcast?: boolean;\n}\n\n/** Options for {@link Think.deliverNotice}. */\nexport interface DeliverNoticeOptions {\n /**\n * Target channel id. Defaults to the active turn's channel, else `\"web\"`.\n */\n channel?: string;\n /**\n * Also record the notice in the model-visible transcript so the next turn\n * knows it was said. Default `false`. For the `web` channel the note is always\n * appended to the transcript (its only render path); `informModel` then only\n * controls the phrasing.\n */\n informModel?: boolean;\n /** Delivery kind for the wire tag. Default `\"notice\"`. */\n kind?: DeliveryKind;\n /**\n * Conversation/thread hint, required for out-of-turn delivery to a\n * multi-thread messenger channel.\n */\n thread?: string;\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 progress_json?: string | null;\n last_signal_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 progress?: AgentToolProgressSnapshot;\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\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 ActionLedgerStatus = \"pending\" | \"settled\";\n\ntype ActionLedgerRow = {\n key: string;\n action_name: string;\n request_id: string | null;\n tool_call_id: string | null;\n input_hash: string;\n status: ActionLedgerStatus;\n result_json: string | null;\n created_at: number;\n updated_at: number;\n};\n\ntype ActionLedgerClaim =\n | { outcome: \"claimed\" }\n | { outcome: \"replay\"; row: ActionLedgerRow }\n | { outcome: \"pending\"; row: ActionLedgerRow }\n | { outcome: \"reclaimed\"; row: ActionLedgerRow }\n | { outcome: \"conflict\"; row: ActionLedgerRow };\n\ntype ActionLedgerRetentionConfig = {\n settledMs: number | false;\n pendingMs: number | false;\n maxSweepRows: number;\n};\n\ntype ActionLedgerSweepStatus = Extract<\n ActionLedgerStatus,\n \"pending\" | \"settled\"\n>;\n\ntype ActionLedgerEvent =\n | {\n type: \"action:ledger:replayed\";\n payload: { action: string; key: string; inputHash: string };\n }\n | {\n type: \"action:ledger:pending\";\n payload: { action: string; key: string; inputHash: string };\n }\n | {\n type: \"action:ledger:conflict\";\n payload: { action: string; key: string; inputHash: string };\n }\n | {\n type: \"action:ledger:serialize_failed\";\n payload: { action: string; key: string };\n }\n | {\n type: \"action:ledger:settled\";\n payload: { action: string; key: string; inputHash: string };\n }\n | {\n type: \"action:ledger:reclaimed\";\n payload: {\n action: string;\n key: string;\n inputHash: string;\n ageMs: number;\n };\n }\n | {\n type: \"action:ledger:swept\";\n payload: { settled: number; pending: number };\n };\n\ntype ChannelEvent =\n | {\n type: \"channel:resolved\";\n payload: { channel: string; kind: string; requestId?: string };\n }\n | {\n type: \"channel:delivered\";\n payload: { channel: string; kind: DeliveryKind; turnEnded: boolean };\n }\n | {\n type: \"notice:delivered\";\n payload: { channel: string; kind: DeliveryKind; informModel: boolean };\n }\n | {\n type: \"notice:failed\";\n payload: { channel: string; error: string };\n };\n\n/**\n * A durably-parked `kind: \"durable-pause\"` action awaiting human approval. The\n * row is the compaction-safe record of everything needed to run `execute` on\n * approve (the transcript part can be summarized away before approval), so it\n * carries the action name, the model's input, and the approval descriptor.\n */\ntype ActionPendingRow = {\n execution_id: string;\n action_name: string;\n tool_call_id: string;\n request_id: string | null;\n input_json: string;\n descriptor_json: string | null;\n created_at: number;\n};\n\ntype ActionPauseEvent =\n | {\n type: \"action:pause:created\";\n payload: { action: string; executionId: string; toolCallId: string };\n }\n | {\n type: \"action:pause:approved\";\n payload: { action: string; executionId: string };\n }\n | {\n type: \"action:pause:rejected\";\n payload: { action: string; executionId: string };\n }\n | {\n type: \"action:pause:swept\";\n payload: { swept: number };\n };\n\ntype ActionReplyEvent = {\n type: \"action:reply-attached\";\n payload: { action?: string; attachmentType: string };\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 /** Channel id this submission belongs to. See {@link RunTurnBase.channel}. */\n channel?: string;\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\n/**\n * Message-metadata keys that are server-written turn context (stamped by\n * `_stampChannel`) and trusted by hooks and recovery. They are stripped from\n * client-supplied messages at intake so a client can never forge them.\n */\nconst RESERVED_MESSAGE_METADATA_KEYS = [\"channel\", \"turnMetadata\"] as const;\n\n/**\n * Reserved name for the synthetic tool a workflow `step.prompt` turn uses to\n * deliver its structured final answer. The agent runs a full multi-step,\n * tool-using turn and ends it by calling this tool with arguments matching the\n * requested schema — exactly the way a sub-agent returns a result.\n *\n * Why a tool instead of the AI SDK `output`/`response_format` path: streaming a\n * JSON Schema `response_format` is rejected by some providers (Workers AI\n * returns `AiError 5023: JSON Schema mode is not supported with stream mode`),\n * whereas plain tool-calling streams on every provider. Capturing the tool\n * call's INPUT as the result keeps Think's single streaming engine intact\n * (persistence, recovery, resumable streams) and works uniformly across\n * Workers AI, OpenAI, and Anthropic.\n *\n * The name is namespaced to avoid clashing with user tools; if a user tool\n * already uses it, the turn picks a suffixed variant (see `_handleTurn`).\n */\nconst THINK_FINAL_ANSWER_TOOL_NAME = \"think_final_answer\";\n\n/**\n * Whether `name` is (or is a collision-suffixed variant of) the reserved\n * structured-output final-answer tool. Used to strip the internal tool's parts\n * from persisted assistant messages regardless of which per-turn name was used.\n */\nfunction isThinkFinalAnswerToolName(name: string): boolean {\n return (\n name === THINK_FINAL_ANSWER_TOOL_NAME ||\n name.startsWith(`${THINK_FINAL_ANSWER_TOOL_NAME}_`)\n );\n}\n\n/**\n * Build the system-prompt instruction that tells the model to terminate a\n * structured workflow turn by calling the given final-answer tool.\n */\nfunction thinkFinalAnswerInstruction(toolName: string): string {\n return (\n \"When you have everything you need to answer, you MUST call the \" +\n `\\`${toolName}\\` tool exactly once with arguments that match the required ` +\n \"schema. Do not write the final answer as plain text — the \" +\n `\\`${toolName}\\` tool call IS the answer and ends the task.`\n );\n}\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 ChatRecoveryProgressContext,\n ChatRecoveryOptions,\n MessageConcurrency,\n ResolvedChatRecoveryConfig,\n SaveMessagesOptions,\n SaveMessagesResult\n} from \"agents/chat\";\nimport type {\n ChatResponseResult,\n ChatRecoveryConfig,\n ChatRecoveryContext,\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 /**\n * Executor that resolves client-tool calls inline (RPC `chat()` path). When\n * present, `clientTools` are built WITH an `execute` that delegates to it, so\n * the turn completes the tool round trip itself instead of surfacing a\n * dangling tool call. Not persisted — recovery cannot replay a live executor.\n */\n clientToolExecutor?: ClientToolExecutor;\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 /**\n * Override the model for this turn (e.g. cheap model for continuations).\n * Accepts a model id string (resolved via the built-in provider, same rules\n * as {@link Think.getModel}) or a `LanguageModel`.\n */\n model?: ThinkModel;\n /** Override the assembled instructions prompt. */\n instructions?: string;\n /** @deprecated Prefer `instructions`. */\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 /**\n * Optional AI SDK telemetry configuration for this turn.\n *\n * Typed via the `experimental_telemetry` key, which exists in both AI SDK v6\n * and v7 (`telemetry` is v7-only), so this type resolves under either major.\n */\n telemetry?: Parameters<typeof streamText>[0][\"experimental_telemetry\"];\n /** @deprecated Prefer `telemetry`. */\n experimental_telemetry?: Parameters<\n typeof streamText\n >[0][\"experimental_telemetry\"];\n /**\n * Optional AI SDK stream transform(s) for this turn (`experimental_transform`).\n * Forwarded to `streamText` so callers can inspect/rewrite the stream — e.g.\n * detecting tool results that carry `{ content, sources }` and enqueuing\n * additional `source` parts via the transform's controller. Accepts a single\n * transform or an array applied in order.\n */\n experimental_transform?: Parameters<\n typeof streamText\n >[0][\"experimental_transform\"];\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\n/**\n * Provider-agnostic semantic classification of a chat-turn error.\n *\n * Think ships **no** provider-specific string/code matching — the app owns\n * that knowledge (it knows which provider/model it talks to), exactly like the\n * `tokenCounter` it already passes to `compactAfter()`. An app teaches Think\n * what an error *means* by overriding `classifyChatError()`; Think then reacts\n * generically (e.g. compact-and-retry on `context_overflow`).\n *\n * - `context_overflow` — the prompt exceeded the model's context window\n * (Anthropic `\"prompt is too long\"`, OpenAI `context_length_exceeded`, …).\n * The only category Think currently acts on (auto-compact + retry).\n * - `rate_limit` / `transient` — reserved for future backoff/retry policies.\n * - `fatal` — unrecoverable; surface terminally.\n * - `unknown` — default; Think applies its existing terminal behavior.\n */\nexport type ChatErrorClassification =\n | \"context_overflow\"\n | \"rate_limit\"\n | \"transient\"\n | \"fatal\"\n | \"unknown\";\n\n/**\n * Opt-in handling for a turn that overflows the model's context window\n * mid-flight. Compaction (`compactAfter()`) is only checked between turns, so a\n * long, tool-heavy turn can grow past the window before the next check; the\n * provider then rejects the request (`\"prompt is too long\"` /\n * `context_length_exceeded`). Both layers reuse the session's compaction\n * function and are provider-agnostic — the app maps the error via\n * {@link Think.classifyChatError}; Think never matches provider strings itself.\n *\n * Set `Think.contextOverflow` to enable. Leaving it unset disables both layers\n * (existing terminal behavior).\n */\nexport interface ContextOverflowConfig {\n /**\n * Reactive backstop. When a turn fails with an error classified as\n * `\"context_overflow\"`, discard the truncated partial, run\n * `session.compact()`, and re-run the turn from the compacted history. The\n * partial is intentionally not persisted: the turn restarts from scratch, so\n * keeping the cut-off assistant message would orphan it beside the recovered\n * answer (and duplicate any tool work the retry re-issues). If compaction\n * cannot shorten history or the retry budget is spent, the overflow surfaces\n * terminally through `onChatError` (classified) — it never loops or ends\n * silently. Default `false`.\n */\n reactive?: boolean;\n\n /**\n * Maximum compact-and-retry attempts for a single overflowing turn (the\n * reactive backstop). Independent of the proactive guard's cap — see\n * {@link proactive.maxCompactions}. Default `1`.\n */\n maxRetries?: number;\n\n /**\n * Proactive guard. Before each step, read the previous step's model-reported\n * `usage.inputTokens` and, if it crosses `maxInputTokens * (headroom ?? 0.9)`,\n * compact in place and feed the recompacted history into the upcoming step —\n * heading off the provider rejection before it happens. Keys off usage (every\n * provider reports it), not provider error strings. Unset disables it.\n *\n * If a provider omits `inputTokens`, the guard falls back to `usage.totalTokens`\n * (input + output) — a safe over-approximation that compacts slightly early\n * rather than missing the threshold. If neither is reported, the guard does\n * nothing that step (the reactive backstop still catches a genuine overflow).\n *\n * `maxCompactions` caps how many times the guard may compact within a single\n * step loop (default `1`, floored at `1`). It is independent of\n * {@link maxRetries} (the reactive budget): a no-op compaction would repeat on\n * every step, so the cap stops the guard from compacting (and emitting\n * `chat:context:compacted`) on each one.\n */\n proactive?: {\n maxInputTokens: number;\n headroom?: number;\n maxCompactions?: number;\n };\n}\n\n/**\n * Matches the context-window-overflow error messages of the common providers.\n * Anthropic (`prompt is too long`), OpenAI (`context_length_exceeded`,\n * `maximum context length`, `reduce the length of …`), Google Gemini (`exceeds\n * the maximum number of tokens`, `input token count`), Bedrock / Mistral /\n * others (`input is too long`, `too many tokens`, `context window`).\n *\n * This default deliberately favors recall over precision: a missed overflow\n * means no recovery (the feature's whole point), whereas a false positive\n * self-heals — the retry hits the same non-overflow error, the budget is spent,\n * and it surfaces terminally anyway. The vaguest fragment (`reduce the length`)\n * is anchored to `of` to match the real OpenAI phrasing without matching\n * unrelated prose. Apps that need stricter matching can wrap this classifier.\n */\nconst CONTEXT_OVERFLOW_PATTERN =\n /prompt is too long|context[_ ]length[_ ]exceeded|maximum context length|exceeds the maximum number of tokens|input token count|reduce the length of|input is too long|too many (?:input )?tokens|context window/i;\n\n/**\n * Opt-in default classifier for {@link Think.classifyChatError}. Matches the\n * context-window-overflow error messages of the common providers (Anthropic,\n * OpenAI, Google, Bedrock, Mistral, …) and returns `\"context_overflow\"`.\n *\n * Think ships this as an explicitly-imported helper rather than wiring it into\n * core, so the framework default stays free of provider strings. Assign it (or\n * delegate to it) when you do not need custom classification:\n *\n * @example\n * ```typescript\n * import { Think, defaultContextOverflowClassifier } from \"@cloudflare/think\";\n *\n * export class MyAgent extends Think<Env> {\n * override contextOverflow = { reactive: true };\n * override classifyChatError = defaultContextOverflowClassifier;\n * }\n * ```\n *\n * Or combine with your own checks:\n *\n * @example\n * ```typescript\n * override classifyChatError(error: unknown): ChatErrorClassification | void {\n * if (isMyRateLimit(error)) return \"rate_limit\";\n * return defaultContextOverflowClassifier(error);\n * }\n * ```\n */\nexport function defaultContextOverflowClassifier(\n error: unknown\n): ChatErrorClassification | undefined {\n let text: string;\n if (error instanceof Error) {\n text = error.message;\n } else if (typeof error === \"string\") {\n text = error;\n } else {\n try {\n text = JSON.stringify(error);\n } catch {\n text = String(error);\n }\n }\n return CONTEXT_OVERFLOW_PATTERN.test(text) ? \"context_overflow\" : undefined;\n}\n\nexport interface ChatErrorContext {\n requestId?: string;\n stage: \"parse\" | \"persist\" | \"turn\" | \"stream\" | \"recovery\" | \"transcript\";\n messagesPersisted?: boolean;\n /**\n * App-provided semantic classification (from `classifyChatError`), when\n * known. Lets `onChatError` overrides and observers distinguish e.g. a\n * context-overflow from a generic provider failure without re-matching\n * provider strings.\n */\n classification?: ChatErrorClassification;\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`, `instructions`, `messages`, `experimental_context`,\n * `providerOptions`). The previous `system` field remains available as a\n * deprecated alias.\n *\n * `model` is widened to {@link ThinkModel}: like {@link Think.getModel}, you\n * can return a model id string (resolved via the built-in provider) instead of\n * a `LanguageModel`. Think resolves it before handing the step to the AI SDK.\n */\nexport type StepConfig<TOOLS extends ToolSet = ToolSet> = Omit<\n PrepareStepResult<TOOLS>,\n \"model\"\n> & {\n model?: ThinkModel;\n};\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. With a concrete\n * tool set, narrowing on `ctx.toolName` narrows `ctx.input` to that tool's\n * input shape:\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 as string\n * }\n * }\n * ```\n */\nexport type ToolCallContext<TOOLS extends ToolSet = ToolSet> =\n PerToolCall<TOOLS> & ToolCallContextExtras;\n\n/** Per-call event extras attached to every {@link ToolCallContext}. */\ntype ToolCallContextExtras = {\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 * The `TypedToolCall<TOOLS>` union, re-keyed so that discriminating on\n * `toolName` narrows `input` per tool.\n *\n * The AI SDK's `TypedToolCall` includes a `DynamicToolCall` arm whose\n * `toolName: string` / `input: unknown` overlaps every static tool name —\n * leaving it in the union collapses `ctx.input` to `unknown` even after a\n * `toolName` check. When an explicit `TOOLS` generic is passed (so the keys\n * are a literal union), we distribute over those keys and drop the dynamic\n * arm so narrowing works. With the default `ToolSet` (keys are `string`) we\n * fall back to the raw union, preserving the prior loose behavior.\n */\ntype PerToolCall<TOOLS extends ToolSet> = string extends keyof TOOLS\n ? TypedToolCall<TOOLS>\n : {\n [K in keyof TOOLS]: Extract<TypedToolCall<TOOLS>, { toolName: K }>;\n }[keyof TOOLS];\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 `OnToolExecutionEndEvent`. The full\n * `TypedToolCall<TOOLS>` fields (`toolName`, `toolCallId`, `input`, …) are\n * spread at the top 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 * - `toolExecutionMs` — wall-clock execution time in milliseconds\n * - `durationMs` — deprecated alias for `toolExecutionMs`\n * - `toolOutput` — AI SDK v7 discriminated outcome\n * - `success`/`output`/`error` — deprecated normalized outcome aliases:\n * - on success: `success: true`, `output` typed per tool\n * - on failure: `success: false`, `error: unknown`\n *\n * Pass an explicit `TOOLS` generic for full input **and** output typing.\n * On the success branch, narrowing on `ctx.toolName` narrows `ctx.output`\n * to that tool's inferred output type (dynamic tools stay `unknown`):\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.toolName === \"search\" && ctx.success) {\n * ctx.output.results; // typed as the `search` tool's output\n * }\n * }\n * ```\n */\nexport type ToolCallResultContext<TOOLS extends ToolSet = ToolSet> =\n string extends keyof TOOLS\n ? TypedToolCall<TOOLS> & ToolCallResultBase & ToolCallOutcome<unknown>\n : {\n [K in keyof TOOLS]: Extract<TypedToolCall<TOOLS>, { toolName: K }> &\n ToolCallResultBase &\n ToolCallOutcome<InferToolOutput<TOOLS[K]>>;\n }[keyof TOOLS];\n\n/** Per-call extras attached to every {@link ToolCallResultContext}. */\ntype ToolCallResultBase = {\n readonly stepNumber: number | undefined;\n readonly messages: ReadonlyArray<ModelMessage>;\n /** Wall-clock execution time in milliseconds. */\n readonly toolExecutionMs: number;\n /** @deprecated Prefer `toolExecutionMs`. */\n readonly durationMs: number;\n};\n\n/**\n * The discriminated success/failure outcome of a tool call. On success the\n * `output` is typed (`O`); on failure the `error` is `unknown`.\n */\ntype ToolCallOutcome<O> =\n | {\n readonly toolOutput: { type: \"tool-result\"; output: O };\n /** @deprecated Prefer `toolOutput.type === \"tool-result\"`. */\n readonly success: true;\n /** @deprecated Prefer `toolOutput.output`. */\n readonly output: O;\n readonly error?: never;\n }\n | {\n readonly toolOutput: { type: \"tool-error\"; error: unknown };\n /** @deprecated Prefer `toolOutput.type === \"tool-error\"`. */\n readonly success: false;\n readonly output?: never;\n /** @deprecated Prefer `toolOutput.error`. */\n readonly error: unknown;\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 GenerateTextOnStepFinishCallback<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\n/**\n * @internal The subset of the AI SDK's `ToolExecuteOptions` that Think's\n * tool wrapper reads when resolving a `beforeToolCall` decision.\n */\ntype ToolDecisionOptions = {\n toolCallId: string;\n messages: ModelMessage[];\n abortSignal?: AbortSignal;\n context?: unknown;\n experimental_context?: unknown; // v6 alias kept for local wrappers if present\n};\n\n/**\n * An opinionated chat agent base class.\n *\n * @experimental The API surface may change before stabilizing.\n */\n/**\n * Keys of the global `AiModels` interface (from `@cloudflare/workers-types`)\n * whose model type extends `T`. Mirrors the derivation `workers-ai-provider`\n * uses, so the set stays in sync with the installed workers-types version.\n */\ntype WorkersAIModelIdsExtending<T> = {\n [K in keyof AiModels]: AiModels[K] extends T ? K : never;\n}[keyof AiModels];\n\n/**\n * A model id accepted by {@link Think.getModel}.\n *\n * Provides editor autocomplete for the Workers AI text-generation catalog\n * (`@cf/...`) while still accepting **any** string — including\n * `\"<provider>/<model>\"` AI Gateway slugs like `\"openai/gpt-5.5\"`, whose\n * validity is only known at runtime (the catalog is server-side and changes\n * independently of these types). The `(string & {})` arm is what keeps\n * arbitrary strings assignable without collapsing the autocomplete union.\n */\nexport type ThinkModelId =\n | Exclude<\n WorkersAIModelIdsExtending<BaseAiTextGeneration>,\n WorkersAIModelIdsExtending<BaseAiTextToImage>\n >\n | (string & {});\n\n/**\n * What {@link Think.getModel} may return: either a fully-constructed AI SDK\n * `LanguageModel`, or a {@link ThinkModelId} string resolved through Think's\n * built-in `workers-ai-provider`. Also the input type of {@link Think.resolveModel}.\n */\nexport type ThinkModel = LanguageModel | ThinkModelId;\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 * Whether Think automatically converts connected MCP tools to AI SDK tools\n * and merges them into each model turn.\n *\n * Set this to `false` when MCP tools are exposed through Code Mode or another\n * mechanism outside Think's automatic tool set. Connections, discovery,\n * `waitForMcpConnections`, raw tool listing and calls, and explicit\n * `this.mcp.getAITools()` calls are unaffected.\n *\n * @default true\n */\n includeMcpTools = true;\n\n /**\n * Wait for MCP server connections to be ready before the inference loop.\n * When {@link includeMcpTools} is enabled, their tools are then auto-merged\n * 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 /** Store model input/output on `chat` spans. */\n storeMessages = false;\n\n /** Store tool input/output on `execute_tool` spans. */\n storeTools = false;\n\n private _skillRegistry: SkillRegistry | null = null;\n private _loggedSkillWarnings = new Set<string>();\n private _loggedProtocolWarnings = 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 * Byte budget for hydrating the persisted transcript into the in-memory\n * message cache (`this.messages`).\n *\n * Hydration runs on every wake (and at safe boundaries during a session).\n * Without a budget it materializes the ENTIRE stored conversation — for\n * long-lived, media-heavy sessions that footprint approaches the isolate's\n * 128MB memory budget and the next SQLite allocation fails with\n * `SQLITE_NOMEM`, permanently bricking the DO (#1710).\n *\n * When the stored path exceeds the budget, only the most recent messages\n * that fit are hydrated — never fewer than the recent window the model\n * sees at full fidelity (the `truncateOlderMessages` default of 4), even\n * when those messages alone exceed the budget — a\n * `chat:hydration:windowed` observability event is emitted, and\n * `this.messages` exposes the bounded window. Durable storage is never\n * truncated by this — `session.getHistory()` still reads the full path.\n * The model-facing context is unaffected: older content is already\n * truncated at read time before each turn, and the hydration floor\n * guarantees the full-fidelity span is always present.\n *\n * The default (24MB) leaves headroom for the ~2-3x amplification between\n * stored JSON and parsed in-memory messages. Set to\n * `Number.POSITIVE_INFINITY` (or any non-positive value) to disable\n * windowing and always hydrate the full transcript.\n *\n * @default 24 * 1024 * 1024\n */\n hydrationByteBudget: number = 24 * 1024 * 1024;\n\n /**\n * Bound the PERSISTED transcript footprint by evicting oversized inline\n * media (base64 data-URL attachments, large strings inside tool outputs)\n * from messages that have aged out of the recent window.\n *\n * Read-time truncation already hides aged media from the model, but the\n * bytes stay in storage forever and are rehydrated on every wake — the\n * boot footprint grows with every image a session ever produced until\n * SQLite's allocator fails with `SQLITE_NOMEM` (#1710). Eviction passes\n * run in the background after the agent starts and as the conversation\n * grows; each pass processes a bounded number of oversized rows.\n *\n * By default evicted values are preserved as workspace files under\n * `/attachments/evicted/` (same Durable Object storage, but outside the\n * hydration path) and the in-message marker records the file path.\n * Pass a {@link MediaEvictionConfig} with `externalizeToWorkspace: false`\n * to drop the bytes instead of preserving them. Set this field to\n * `false` to disable eviction entirely.\n *\n * `keepRecentMessages` is clamped to at least the recent window the model\n * replays at full fidelity (4 messages), so eviction can never rewrite\n * content the model still sees.\n *\n * Requires a SessionProvider that implements `getHistoryRowStats`\n * (the default DO SQLite provider does); otherwise eviction is a no-op\n * and a warning is logged once.\n *\n * @default true\n */\n mediaEviction: MediaEvictionConfig | boolean = true;\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 * Assign this as a class field or in the constructor — NOT in `onStart()`.\n * On every wake the SDK evaluates recovery budgets (and may seal an\n * interrupted turn, firing `onExhausted`) before `onStart()` runs, so a config\n * set in `onStart()` is applied too late and the built-in defaults are used\n * for the recovery that matters. See {@link ChatRecoveryConfig}.\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 /**\n * Internal onStart steps that failed on this wake and were skipped so the\n * agent could still come up.\n *\n * onStart failures are terminal: partyserver resets its init state and\n * rethrows, so every subsequent wake — including platform alarm retries —\n * re-runs the failing onStart. A data-driven failure (e.g. SQLITE_NOMEM\n * hydrating an oversized transcript) would otherwise permanently brick the\n * DO and drive an unbounded alarm-retry loop (#1710).\n */\n protected _onStartDegradations: OnStartDegradation[] = [];\n\n /**\n * Internal onStart steps that failed on this wake and were skipped so the\n * agent could still come up (see {@link OnStartDegradation}). Empty when\n * boot was clean. Lets hosts and operators surface degraded boots —\n * e.g. via a health RPC — without subclassing.\n */\n getOnStartDegradations(): ReadonlyArray<OnStartDegradation> {\n return [...this._onStartDegradations];\n }\n\n private _activeMessengerContext?: MessengerContext;\n\n /**\n * Turn-scoped channel context (superset of `_activeMessengerContext`). Set on\n * both the queue and submit admission paths via `_withChannelContext`, read by\n * `deliverNotice` and per-channel policy. Save/restore keeps nested turns safe.\n */\n private _activeChannelContext?: ChannelContext;\n\n /**\n * Live delivery surface for the active turn, bound by `deliverMessengerReply`\n * so `deliverNotice` can post to the originating channel mid-turn. Save/restore\n * keeps nested turns safe.\n */\n private _activeDeliverySurface?: MessengerDeliverySurface;\n\n private _messengerRuntime?: ThinkMessengerRuntime;\n\n /** Resolved channel registry (implicit web + configureChannels + messengers). */\n private _channels?: Map<string, NormalizedChannelDefinition>;\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 * The codemode runtime behind the execute tool, when one has been created\n * via `createExecuteRuntime(this)` / `createExecuteTool(this)` (from\n * `@cloudflare/think/tools/execute`). Gives callables and lifecycle hooks\n * access to approvals (`approve`/`reject`/`pending`), the audit trail\n * (`executions`), `expirePaused`, and snippets.\n */\n codemode?: import(\"@cloudflare/codemode\").CodemodeRuntimeHandle;\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 /**\n * Opt-in HTTP fetch tools. Disabled by default — set to a config object to\n * register a generic `fetch_url` tool (when `allowlist` is provided) and one\n * `fetch_<name>` tool per `bindings` target. Read-only (GET), allowlisted,\n * and bounded; see {@link createFetchTools}.\n *\n * The workspace and an observability hook are injected automatically, so omit\n * `workspace`/`onEvent` here. This property is evaluated at construction, so\n * use it for static config — for per-tenant/dynamic allowlists call\n * `createFetchTools()` inside `getTools()` instead (it runs every turn).\n *\n * ```ts\n * fetchTools = { allowlist: [\"https://developers.cloudflare.com/**\"] };\n * ```\n */\n fetchTools: false | Omit<CreateFetchToolsOptions, \"workspace\" | \"onEvent\"> =\n false;\n\n constructor(ctx: DurableObjectState, env: Env) {\n super(ctx, env);\n\n const _onStart = this.onStart.bind(this);\n const startThink = async (\n props: Props | undefined,\n update: UpdateAgentSpan\n ) => {\n await withAgentSpan(\n this,\n \"initialize_think_session\",\n \"startup\",\n { \"cloudflare.agents.component\": \"think\" },\n 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 // The conversation grew — older messages may have aged out of\n // the keep-recent window. Only schedule the maintenance scan once\n // this session has actually observed oversized media; otherwise a\n // normal text-only chat would pay a row-stat read after every turn.\n this._scheduleMediaEvictionAfterAppend(\n 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 );\n\n // Force Session to initialize its tables (assistant_messages,\n // assistant_compactions, assistant_config, etc.) so that subsequent\n // config reads work.\n //\n // Hydration is bounded by `hydrationByteBudget` (a byte-budgeted\n // recent window on oversized transcripts), but even the budgeted read\n // can fail — and that failure must not escape onStart, or the DO is\n // bricked (#1710). Degrade to an empty in-memory view; persisted\n // history is untouched and the next safe-boundary `_syncMessages()`\n // retries.\n this._onStartDegradations = [];\n await withAgentSpan(\n this,\n \"hydrate_think_session\",\n \"startup\",\n { \"cloudflare.agents.component\": \"think\" },\n async () => {\n const hydrated = await this._runBestEffortOnStartStep(\n \"transcript-hydration\",\n () => this._syncMessages(),\n \"The agent is starting with an empty in-memory message view; \" +\n \"persisted history is untouched. If the error is SQLITE_NOMEM, \" +\n \"the stored transcript is too large to hydrate (often inline \" +\n \"base64 media in tool results) — compact or clear the session \" +\n \"to recover.\"\n );\n if (!hydrated) {\n this._replaceCachedMessages([]);\n }\n this._refreshMediaEvictionSignalFromCache();\n }\n );\n\n // 3-6. Extension initialization (if extensionLoader is set)\n if (this.extensionLoader) {\n await withAgentSpan(\n this,\n \"initialize_think_extensions\",\n \"startup\",\n { \"cloudflare.agents.component\": \"think\" },\n () => this._initializeExtensions()\n );\n }\n\n // 7. Protocol handlers\n await withAgentSpan(\n this,\n \"initialize_think_chat\",\n \"startup\",\n { \"cloudflare.agents.component\": \"think\" },\n async () => {\n this._resumableStream = new ResumableStream(this.sql.bind(this));\n this._restoreClientTools();\n this._restoreBody();\n this._setupProtocolHandlers();\n await this._initializeChannels();\n }\n );\n\n // 8. User's onStart\n await _onStart(props);\n\n // 9. Declarative scheduled tasks are code-defined and should reconcile\n // before draining any recovered programmatic work they may enqueue.\n // Best-effort: reconcile runs after the agent is otherwise functional,\n // and a failure (user getScheduledTasks() throwing, storage pressure)\n // must not brick the DO (#1710).\n await withAgentSpan(\n this,\n \"reconcile_think_schedules\",\n \"startup\",\n { \"cloudflare.agents.component\": \"think\" },\n () =>\n this._runBestEffortOnStartStep(\n \"scheduled-task-reconcile\",\n () => this._reconcileDeclaredScheduledTasks(),\n \"Declared scheduled tasks were not reconciled on this wake; the \" +\n \"next successful wake will reconcile them.\"\n )\n );\n\n // 10. Durable submissions may run user-defined model/hooks, so start them\n // after subclass initialization has completed. Best-effort for the same\n // reason as step 9.\n await withAgentSpan(\n this,\n \"recover_think_durable_work\",\n \"startup\",\n { \"cloudflare.agents.component\": \"think\" },\n () =>\n this._runBestEffortOnStartStep(\n \"durable-work-recovery\",\n async () => {\n await this._sweepActionLedger();\n await this._sweepActionPendingApprovals();\n await this._recoverSubmissionsOnStart();\n this._recoverWorkflowNotifications();\n if (this._hasPendingSubmissions()) {\n await this._scheduleSubmissionDrain();\n }\n if (this._hasPendingWorkflowNotifications()) {\n this._startWorkflowNotificationDrain();\n }\n },\n \"Pending submissions / workflow notifications were not recovered on \" +\n \"this wake; the next successful wake will recover them.\"\n )\n );\n\n // 11. Background bound on the persisted transcript: if hydration was\n // windowed, evict aged inline media so the footprint can converge down\n // (#1710). Runs after `blockConcurrencyWhile` releases — no boot cost.\n if (this._lastHydration?.truncated) {\n this._scheduleMediaEvictionPass({ force: true });\n }\n\n update({\n \"cloudflare.agents.hydration.messages\":\n this._lastHydration?.hydratedMessages,\n \"cloudflare.agents.hydration.content_bytes\":\n this._lastHydration?.totalContentBytes,\n \"cloudflare.agents.hydration.truncated\": this._lastHydration?.truncated,\n \"cloudflare.agents.start.degradations\": this._onStartDegradations.length\n });\n };\n this.onStart = (props?: Props) =>\n withAgentSpan(\n this,\n \"think_start\",\n \"startup\",\n { \"cloudflare.agents.component\": \"think\" },\n (update) => startThink(props, update)\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 * When the stored transcript exceeds `hydrationByteBudget`, this view is a\n * bounded window of the most recent messages (see `_lastHydration`); the\n * full history remains readable via `session.getHistory()`.\n */\n get messages(): UIMessage[] {\n return this._cachedMessages;\n }\n\n /**\n * Read the durable message path from session storage.\n *\n * Intentionally UNBUDGETED — unlike the cache refresh in `_syncMessages`,\n * which routes through `session.getRecentHistory(hydrationByteBudget)`, this\n * returns the full active path. Callers (message reconciliation, tool-update\n * application) must see every message: reconciliation diffs incoming client\n * messages against the complete server transcript, and a tool result can\n * target any message on the path, so a windowed read would drop rows and\n * corrupt the result.\n *\n * These full reads are not the unbounded boot-time hydration that bricked the\n * DO in #1710: they run during a live turn (never in `onStart`), so an\n * `SQLITE_NOMEM` here surfaces as a recoverable turn-level error rather than a\n * partyserver init-reset/alarm-retry loop. They also inherit step 1's\n * mitigation — `session.getHistory()` now fetches content in bounded chunks\n * (`messagesByPathIds`) instead of carrying blobs through the recursive CTE\n * and its `ORDER BY` sorter — and background media eviction shrinks the stored\n * footprint over time, so the steady-state read size converges down.\n */\n private async _readMessagesFromStorage(): Promise<UIMessage[]> {\n return (await this.session.getHistory()) as UIMessage[];\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. Delegates to the shared\n * `agents/chat` primitive so the repair pass and the backstop detector\n * (`_incompleteToolCallIds`) share the single source of truth for terminal\n * tool states.\n */\n private _toolPartHasSettledResult(record: Record<string, unknown>): boolean {\n return toolPartHasSettledResult(record);\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 // Delegates to the shared `agents/chat` primitive so Think and ai-chat run\n // identical repair logic. The overridable `repairInterruptedToolPart` hook\n // (default: flip to an errored result; subclasses can preserve a\n // client-resolved tool such as `ask_user` as text) is threaded through, and\n // the settled-result / input-normalization helpers are the shared defaults.\n return repairInterruptedToolParts(messages, {\n repairPart: (part) => this.repairInterruptedToolPart(part),\n isSettled: (record) => this._toolPartHasSettledResult(record),\n normalizeInput: (input) => normalizeToolInput(input)\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 /**\n * Run a best-effort internal onStart step, degrading on failure instead of\n * throwing.\n *\n * Throwing out of `onStart` is terminal: partyserver resets its init state\n * and rethrows, so every wake — including platform alarm retries — re-runs\n * the failing `onStart` and fails again. A data-driven failure (oversized\n * transcript, bad declared-task config) would permanently brick the DO and\n * drive an unbounded alarm-retry loop (#1710). Instead, record the\n * degradation, emit `chat:onstart:degraded`, and let the agent come up so\n * it stays reachable for remediation (compaction, clearing, redeploy).\n *\n * Returns `true` when the step succeeded.\n */\n private async _runBestEffortOnStartStep(\n step: OnStartDegradation[\"step\"],\n fn: () => unknown | Promise<unknown>,\n hint: string\n ): Promise<boolean> {\n try {\n await fn();\n return true;\n } catch (error) {\n this._onStartDegradations.push({ step, error });\n console.error(\n `[Think] onStart step \"${step}\" failed; continuing with degraded state. ${hint}`,\n error\n );\n this._emit(\"chat:onstart:degraded\", {\n step,\n error: error instanceof Error ? error.message : String(error)\n });\n return false;\n }\n }\n\n private _mediaEvictionRunning = false;\n private _mediaEvictionScheduled = false;\n private _mediaEvictionObservedOversized = false;\n\n /**\n * Schedule a background media-eviction pass (see `mediaEviction`).\n * Coalesces repeated requests; the timer fires after the current\n * event-loop work (and after `onStart`'s `blockConcurrencyWhile`), so\n * boot and turn latency are unaffected.\n */\n private _scheduleMediaEvictionPass(options?: { force?: boolean }): void {\n if (this._mediaEvictionScheduled || this._mediaEvictionRunning) return;\n const config = resolveMediaEvictionConfig(this.mediaEviction);\n if (!config) return;\n if (!options?.force && !this._mediaEvictionObservedOversized) return;\n this._mediaEvictionScheduled = true;\n setTimeout(() => {\n this._mediaEvictionScheduled = false;\n void this._evictAgedMediaBestEffort();\n }, 0);\n }\n\n private _scheduleMediaEvictionAfterAppend(message: UIMessage): void {\n const config = resolveMediaEvictionConfig(this.mediaEviction);\n if (!config) return;\n if (!this._mediaEvictionObservedOversized) {\n this._mediaEvictionObservedOversized = this._messageMayNeedMediaEviction(\n message,\n config\n );\n }\n if (!this._mediaEvictionObservedOversized) return;\n\n const keepRecent = Math.max(config.keepRecentMessages, MODEL_RECENT_WINDOW);\n if (this._cachedMessages.length > keepRecent) {\n this._scheduleMediaEvictionPass({ force: true });\n }\n }\n\n private _refreshMediaEvictionSignalFromCache(): void {\n const config = resolveMediaEvictionConfig(this.mediaEviction);\n if (!config) {\n this._mediaEvictionObservedOversized = false;\n return;\n }\n this._mediaEvictionObservedOversized = this._cachedMessages.some(\n (message) => this._messageMayNeedMediaEviction(message, config)\n );\n }\n\n private _messageMayNeedMediaEviction(\n message: UIMessage,\n config: ResolvedMediaEvictionConfig\n ): boolean {\n return JSON.stringify(message).length >= config.minPartBytes;\n }\n\n private _warnedEvictionUnsupported = false;\n\n /**\n * Evict oversized inline media from aged stored messages (#1710).\n *\n * Memory-bounded by design: row sizes come from `getHistoryRowStats()`\n * (no content loaded), only rows large enough to contain an evictable\n * part are parsed, and they are processed one at a time via\n * `session.internal_rewriteMessage` — the maintenance write path that\n * skips the full-history token-estimate broadcast a public\n * `updateMessage` performs per row. Evicted values are written to the\n * workspace BEFORE the row is rewritten, so a failed pass never loses\n * data. Best-effort: failures are logged and the next pass retries.\n *\n * The aged cutoff is `keepRecentMessages` clamped to at least\n * `MODEL_RECENT_WINDOW`: messages the model still replays at full\n * fidelity each turn are never rewritten, regardless of configuration.\n *\n * When a pass stops at `maxRowsPerPass` with eligible rows remaining,\n * another pass is scheduled automatically so a large backlog drains\n * without waiting for new appends. Termination is guaranteed: every\n * rewritten row drops below `minPartBytes` and is skipped by later\n * passes, so the eligible set strictly shrinks.\n *\n * Returns the pass totals, or `null` when eviction is disabled, already\n * running, or the provider cannot enumerate row sizes (warned once).\n */\n protected async _evictAgedMediaBestEffort(): Promise<{\n messages: number;\n parts: number;\n bytes: number;\n externalizedBytes: number;\n } | null> {\n if (this._mediaEvictionRunning) return null;\n const config = resolveMediaEvictionConfig(this.mediaEviction);\n if (!config) return null;\n this._mediaEvictionRunning = true;\n let backlogRemains = false;\n try {\n const stats = await this.session.getHistoryRowStats();\n if (!stats) {\n if (!this._warnedEvictionUnsupported) {\n this._warnedEvictionUnsupported = true;\n console.warn(\n \"[Think] mediaEviction is enabled but the configured \" +\n \"SessionProvider does not implement getHistoryRowStats; \" +\n \"media eviction is a no-op for this agent.\"\n );\n }\n return null;\n }\n const keepRecent = Math.max(\n config.keepRecentMessages,\n MODEL_RECENT_WINDOW\n );\n const aged = stats.slice(0, Math.max(0, stats.length - keepRecent));\n\n let processed = 0;\n const totals = { messages: 0, parts: 0, bytes: 0, externalizedBytes: 0 };\n for (const row of aged) {\n // A row smaller than the part threshold cannot contain an\n // evictable value — skip without parsing. Rewritten rows shrink\n // below the threshold, so later passes skip them here too.\n if (row.bytes < config.minPartBytes) continue;\n if (processed >= config.maxRowsPerPass) {\n backlogRemains = true;\n break;\n }\n processed++;\n\n const message = (await this.session.getMessage(\n row.id\n )) as UIMessage | null;\n if (!message) continue;\n\n const result = evictLargeMediaFromMessage(message, {\n minPartBytes: config.minPartBytes,\n externalize: config.externalizeToWorkspace,\n pathFor: (index, extension) =>\n `/attachments/evicted/${message.id}-${index}.${extension}`\n });\n if (!result.changed) continue;\n\n for (const blob of result.blobs) {\n await this.workspace.writeFile(blob.path, blob.data);\n totals.externalizedBytes += blob.data.length;\n }\n await this.session.internal_rewriteMessage(\n sanitizeMessage(result.message)\n );\n totals.messages++;\n totals.parts += result.parts;\n totals.bytes += result.bytes;\n }\n\n if (totals.messages > 0) {\n this._emit(\"chat:media:evicted\", totals);\n }\n return totals;\n } catch (error) {\n console.error(\n \"[Think] media eviction pass failed; a later pass will retry.\",\n error\n );\n return null;\n } finally {\n this._mediaEvictionRunning = false;\n if (backlogRemains) this._scheduleMediaEvictionPass({ force: true });\n }\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 /**\n * Result of the most recent cache refresh when `hydrationByteBudget` is\n * active. `truncated` means `this.messages` is a bounded recent window of\n * a larger stored transcript.\n */\n protected _lastHydration: {\n truncated: boolean;\n totalContentBytes: number;\n hydratedMessages: number;\n } | null = null;\n\n private _warnedHydrationWindowed = false;\n\n /**\n * Snapshot of the last `chat:hydration:windowed` emit, used to emit on\n * CHANGE rather than on every safe-boundary sync — a chronically\n * oversized session syncs many times per turn and would otherwise spam\n * identical events.\n */\n private _lastWindowedEmit: {\n totalContentBytes: number;\n hydratedMessages: number;\n } | null = null;\n\n /**\n * Refresh the live cache from durable storage at a safe boundary.\n *\n * Bounded by `hydrationByteBudget`: oversized transcripts hydrate as a\n * recent window instead of exhausting the isolate's memory (#1710). The\n * window never shrinks below `MODEL_RECENT_WINDOW` messages, so budgeted\n * hydration cannot starve the model-facing context assembly (which keeps\n * that many recent messages at full fidelity).\n */\n private async _syncMessages(): Promise<UIMessage[]> {\n const budget = this.hydrationByteBudget;\n if (!Number.isFinite(budget) || budget <= 0) {\n this._lastHydration = null;\n this._lastWindowedEmit = null;\n return this._replaceCachedMessages(await this._readMessagesFromStorage());\n }\n\n const recent = await this.session.getRecentHistory(\n budget,\n MODEL_RECENT_WINDOW\n );\n this._lastHydration = {\n truncated: recent.truncated,\n totalContentBytes: recent.totalContentBytes,\n hydratedMessages: recent.messages.length\n };\n if (recent.truncated) {\n if (!this._warnedHydrationWindowed) {\n this._warnedHydrationWindowed = true;\n console.warn(\n `[Think] Stored transcript (${recent.totalContentBytes} bytes) ` +\n `exceeds hydrationByteBudget (${budget} bytes); hydrated the ` +\n `most recent ${recent.messages.length} message(s) instead of ` +\n \"the full history. Durable storage is untouched. Compact the \" +\n \"session (or enable media eviction) to shrink it.\"\n );\n }\n const changed =\n this._lastWindowedEmit === null ||\n this._lastWindowedEmit.totalContentBytes !== recent.totalContentBytes ||\n this._lastWindowedEmit.hydratedMessages !== recent.messages.length;\n if (changed) {\n this._lastWindowedEmit = {\n totalContentBytes: recent.totalContentBytes,\n hydratedMessages: recent.messages.length\n };\n this._emit(\"chat:hydration:windowed\", {\n totalContentBytes: recent.totalContentBytes,\n budgetBytes: budget,\n hydratedMessages: recent.messages.length\n });\n }\n } else {\n this._lastWindowedEmit = null;\n }\n return this._replaceCachedMessages(recent.messages as UIMessage[]);\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 /** Sanitize + row-size-compact a message before it touches storage. */\n private _rowSafe(message: UIMessage): UIMessage {\n return enforceRowSizeLimit(sanitizeMessage(message), {\n warn: (m) => console.warn(`[Think] ${m}`)\n });\n }\n\n private async _appendMessageToHistory(\n message: UIMessage,\n parentId?: string | null\n ): Promise<UIMessage> {\n const safe = this._rowSafe(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 = this._rowSafe(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 = this._rowSafe(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 /**\n * The orphan-persist store adapter — orphan-persist steps **(c)/(d)** route\n * their write through this shared `OrphanPersistStore` seam (the\n * `SessionProvider` write-subset). Delegates to `this.session` with `_rowSafe`\n * applied at the write boundary (sanitize + row-size cap), exactly as Think's\n * other Session call sites do. The `SessionMessage → UIMessage` read cast is\n * confined here, matching those call sites.\n * @internal\n */\n protected _orphanStore(): OrphanPersistStore {\n return {\n getMessage: async (id) =>\n (await this.session.getMessage(id)) as UIMessage | null,\n appendMessage: (message, parentId) =>\n this.session.appendMessage(this._rowSafe(message), parentId),\n updateMessage: (message) =>\n this.session.updateMessage(this._rowSafe(message))\n };\n }\n\n private async _clearHistory(): Promise<void> {\n await this.session.clearMessages();\n // Drop any pending terminal record (#1645) so a stale exhaustion can't\n // replay onto a freshly-cleared (empty) conversation on reconnect. Covers\n // both the WS `chat-clear` path and the programmatic `clearMessages()` API.\n await this._clearChatTerminal();\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 /** Lazily-built shared resume-handshake driver (Tier-2). */\n private _resumeHandshakeInstance: ResumeHandshake | null = null;\n private _lastClientTools: ClientToolSchema[] | undefined;\n private _lastBody: Record<string, unknown> | undefined;\n private _continuation = new ContinuationState<Connection>();\n /**\n * Accepted-but-not-yet-streamed turns and the connections parked waiting for\n * one (#1784). See {@link ResumeHandshake} `preStream`.\n *\n * HIBERNATION INVARIANT: in-memory only, NOT persisted. Safe because the\n * pre-stream window cannot overlap hibernation — a turn between `begin()` and\n * stream start is an unresolved `onMessage` handler promise that pins the DO,\n * so eviction only happens once a durable stream exists (resumed via\n * `ResumableStream`) or the turn finished. Breaks if a pre-stream wait is ever\n * moved onto a durable alarm that releases the DO; if so, persist this state.\n */\n private _preStream = new PreStreamTurns<Connection>();\n // Shared auto-continuation barrier (#1649 / #1650): owns the coalesce timer\n // and the double-fire guard. Parameterized by this agent's stream-active\n // signal, apply-drain, and continuation-turn pipeline (`_fireAutoContinuation`).\n private _autoContinuation = new AutoContinuationController<Connection>({\n continuation: this._continuation,\n generateRequestId: () => crypto.randomUUID(),\n isStreamActive: () => this._streamingAssistant !== null,\n hasPendingInteraction: () => this._pendingInteractionPromise !== null,\n hasIncompleteToolBatch: () => this._hasIncompleteToolBatch(),\n drainInteractionApplies: () => this._drainInteractionApplies(),\n keepAliveWhile: <T>(fn: () => Promise<T>) => this.keepAliveWhile(fn),\n fire: () => this._fireAutoContinuation()\n });\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 /**\n * Request id → run id for in-flight agent-tool turns (null = resolved as\n * not an agent-tool turn, cached so unrelated turns don't re-query SQLite\n * per frame). Drives frame attribution in {@link broadcast}: a frame\n * belongs to a run iff it carries that run's turn request id, so an error\n * in an unrelated turn or a concurrent run can never leak into another\n * run's state (#1575).\n */\n private _agentToolRunsByRequestId = new Map<string, string | null>();\n private _submissionTableEnsured = false;\n private _workflowNotificationTableEnsured = false;\n private _declaredScheduledTasksTableEnsured = false;\n private _actionLedgerTableEnsured = false;\n private _actionPendingTableEnsured = 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 // Cheap idle guard so the common (no agent-tool child) broadcast path stays\n // allocation-free — only build the snoop hooks while a run is in flight.\n if (\n this._agentToolForwarders.size > 0 ||\n this._agentToolLiveSequences.size > 0\n ) {\n interceptAgentToolBroadcast(msg, {\n forwarders: this._agentToolForwarders,\n liveSequences: this._agentToolLiveSequences,\n lastErrors: this._agentToolLastErrors,\n responseType: MSG_CHAT_RESPONSE,\n runForRequest: (requestId) => this._agentToolRunForRequest(requestId)\n });\n }\n super.broadcast(msg, without);\n }\n\n /**\n * Resolve the agent-tool run whose turn owns a request id, or null when the\n * request is not an agent-tool turn. Falls back to the persisted child-run\n * row (whose `request_id` is written when the run's turn is bound, see\n * `startAgentToolRun`) so attribution survives a DO restart mid-run; either\n * outcome is cached.\n */\n private _agentToolRunForRequest(requestId: string): string | null {\n const cached = this._agentToolRunsByRequestId.get(requestId);\n if (cached !== undefined) return cached;\n // Active-run predicate: a child run is in flight while `status` is\n // `starting`/`running`; terminal rows set `status` AND `completed_at`\n // together (the lifecycle invariant), so this is equivalent to\n // `completed_at IS NULL` but states the intent. Kept consistent with\n // `_rebindAgentToolChildRunRequestId` and the ai-chat counterpart.\n const rows = this.sql<{ run_id: string }>`\n SELECT run_id FROM cf_agent_tool_child_runs\n WHERE request_id = ${requestId} AND status IN ('starting', 'running')\n LIMIT 1\n `;\n const runId = rows[0]?.run_id ?? null;\n this._agentToolRunsByRequestId.set(requestId, runId);\n return runId;\n }\n\n /**\n * Re-bind this facet's in-flight agent-tool child run to the CURRENT turn's\n * request id.\n *\n * When this facet is itself running as an agent-tool child and its turn is\n * interrupted (e.g. a deploy evicts it mid-run), the recovery continuation\n * (`continueLastTurn` / `_retryLastUserTurn`) mints a NEW request id. The\n * `cf_agent_tool_child_runs.request_id` column — and the in-memory attribution\n * map — still point at the pre-eviction turn, so `broadcast` can no longer\n * attribute the recovered turn's frames to the run. The parent's re-attach\n * tail then sees no forwarded chunks, its no-progress budget elapses, and it\n * abandons a healthy, still-advancing child as `interrupted`\n * (`agentToolReattachNoProgressTimeoutMs`). Re-binding the row to the recovery\n * turn's request id keeps frame attribution alive across recovery so the\n * parent re-attaches and follows the child to its real terminal.\n *\n * Safe to call on EVERY recovery continuation:\n * - Facets that never ran as an agent-tool child have no\n * `cf_agent_tool_child_runs` table → the guarded SELECT throws → no-op.\n * - A facet whose run already settled has no `starting`/`running` row → no-op.\n * - A child DO is addressed by its `runId` (`subAgent(cls, runId)`), so it\n * owns AT MOST ONE child-run row for its whole lifetime and is never reused\n * as a top-level chat agent — the single active row is unambiguously this\n * recovery's run. The `ORDER BY started_at DESC LIMIT 1` is defensive\n * belt-and-suspenders for that invariant.\n *\n * Uses the same `status IN ('starting','running')` active-run predicate as\n * `_agentToolRunForRequest` and the ai-chat counterpart (see the lifecycle\n * invariant note there).\n */\n private _rebindAgentToolChildRunRequestId(requestId: string): void {\n let runId: string | undefined;\n try {\n const rows = this.sql<{ run_id: string }>`\n SELECT run_id FROM cf_agent_tool_child_runs\n WHERE status IN ('starting', 'running')\n ORDER BY started_at DESC\n LIMIT 1\n `;\n runId = rows[0]?.run_id;\n } catch {\n // No child-run table on facets that never ran as an agent tool.\n return;\n }\n if (!runId) return;\n this._agentToolRunsByRequestId.set(requestId, runId);\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET request_id = ${requestId}\n WHERE run_id = ${runId}\n `;\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 model to use for inference. Must be overridden by subclasses.\n *\n * The return value can be either:\n *\n * - A **string** model id, resolved through the built-in\n * {@link https://www.npmjs.com/package/workers-ai-provider | workers-ai-provider}\n * off your `AI` binding (see {@link getAIBinding}). A `@cf/...` id hits\n * Workers AI directly; any other `\"<provider>/<model>\"` slug — e.g.\n * `\"openai/gpt-5.5\"`, `\"anthropic/claude-sonnet-4-5\"`, `\"google/gemini-2.5-pro\"`\n * — is routed through AI Gateway with resumable streaming on by default.\n * This is the common case: no extra package to install, no provider to wire.\n * - A fully-constructed AI SDK `LanguageModel`, for any other provider or for\n * full control over provider/gateway options.\n *\n * @example String (Workers AI)\n * ```typescript\n * getModel() {\n * return \"@cf/moonshotai/kimi-k2.7-code\";\n * }\n * ```\n *\n * @example String (third-party via AI Gateway)\n * ```typescript\n * getModel() {\n * return \"openai/gpt-5.5\";\n * }\n * ```\n *\n * @example Bring your own provider\n * ```typescript\n * import { createOpenAI } from \"@ai-sdk/openai\";\n * getModel() {\n * return createOpenAI({ apiKey: this.env.OPENAI_API_KEY })(\"gpt-5.5\");\n * }\n * ```\n */\n getModel(): ThinkModel {\n throw new Error(\n \"Override getModel() to return a model id string (e.g. \" +\n '\"@cf/moonshotai/kimi-k2.7-code\" or \"openai/gpt-5.5\") or a LanguageModel.'\n );\n }\n\n /**\n * Return the Workers AI binding used by the built-in default provider when\n * {@link getModel} returns a string. Defaults to `this.env.AI`. Override if\n * your binding is named something other than `AI`.\n */\n getAIBinding(): Ai {\n const binding = (this.env as { AI?: Ai }).AI;\n if (!binding) {\n throw new Error(\n \"Think's default model provider needs a Workers AI binding named \" +\n '\"AI\". Add `\"ai\": { \"binding\": \"AI\" }` to wrangler.jsonc, override ' +\n \"getAIBinding() to return your binding, or override getModel() to \" +\n \"return a LanguageModel.\"\n );\n }\n return binding;\n }\n\n /**\n * Lazily-constructed, instance-cached default provider. Bundles the `openai`\n * and `anthropic` wire-format plugins so a `\"<provider>/<model>\"` slug routes\n * through AI Gateway out of the box (covers OpenAI, Anthropic, Google,\n * xAI/Grok, Groq, and the OpenAI-compatible long tail).\n *\n * Cached per instance, which assumes {@link getAIBinding} is stable for the\n * lifetime of the agent (the default `this.env.AI` always is).\n */\n private _defaultProvider?: ReturnType<typeof createWorkersAI>;\n\n /**\n * Resolve a model value into a concrete AI SDK `LanguageModel`.\n *\n * Defaults to resolving {@link getModel}. A `LanguageModel` is returned as-is;\n * a string is built through the bundled default provider (see {@link getModel}\n * for the slug rules). Use this whenever you need a usable model outside the\n * main turn — e.g. a side `generateText` call for summarization/compaction —\n * since `getModel()` may return a bare string.\n */\n resolveModel(model: ThinkModel = this.getModel()): LanguageModel {\n if (typeof model !== \"string\") return model;\n this._defaultProvider ??= createWorkersAI({\n binding: this.getAIBinding(),\n providers: [openai, anthropic]\n });\n // `@cf/...` ids take Workers AI chat settings (sessionAffinity improves\n // prefix-cache hits). Any other slug is a catalog model routed through AI\n // Gateway; we pass no per-call settings, which avoids forcing options a\n // given provider/transport would reject.\n return model.startsWith(\"@cf/\")\n ? this._defaultProvider(model, { sessionAffinity: this.sessionAffinity })\n : this._defaultProvider(model);\n }\n\n /**\n * Return the fallback system prompt for the assistant.\n * Ignored when Session context blocks are configured. Use\n * `configureSession().withContext()` for always-on instructions that should\n * coexist with context blocks or skills.\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 action descriptors compiled into tools for the assistant. */\n getActions(): Record<string, Action> | Promise<Record<string, Action>> {\n return {};\n }\n\n /** Return messenger integrations that should be routed through this Think agent. */\n getMessengers(): ThinkMessengers {\n return {};\n }\n\n /**\n * Return the channels for this agent. Wraps (does not supersede)\n * {@link getMessengers}: the implicit `web` channel is always present, each\n * messenger from `getMessengers()` is absorbed as a `kind: \"messenger\"`\n * channel, and these entries add `web`/`voice`/`custom` surfaces plus\n * per-channel policy. A channel id that collides with a `getMessengers()` id\n * is an error.\n */\n configureChannels(): ThinkChannels | Promise<ThinkChannels> {\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, {\n ...options,\n channel: context.messengerId\n });\n } finally {\n this._activeMessengerContext = previous;\n }\n }\n\n /**\n * Bind the live messenger delivery surface for the active turn so\n * `deliverNotice` can post to the originating channel while a messenger turn\n * is running. Returns a restore function; save/restore keeps nested turns\n * safe. Called by `deliverMessengerReply`.\n */\n bindActiveDeliverySurface(surface: MessengerDeliverySurface): () => void {\n const previous = this._activeDeliverySurface;\n this._activeDeliverySurface = surface;\n return () => {\n this._activeDeliverySurface = previous;\n };\n }\n\n /**\n * The channel context for the active turn, if the turn resolved to a channel.\n * Readable from tools/hooks during a turn (e.g. to branch on `kind`).\n */\n get activeChannel(): ChannelContext | undefined {\n return this._activeChannelContext;\n }\n\n /**\n * The server-supplied metadata stamped on the active turn's user message\n * ({@link ChatOptions.metadata}). Like the channel stamp, it is persisted on\n * the durable user message, so recovered/continued turns re-resolve the same\n * value; client-supplied message metadata can never populate it (reserved\n * keys are stripped at intake). `undefined` when the turn carried none.\n */\n get activeTurnMetadata(): Record<string, unknown> | undefined {\n return this._turnMetadataFromMessages(this.messages);\n }\n\n /** Resolve a channel id to a turn-scoped {@link ChannelContext}, if registered. */\n private _resolveChannelContext(\n channel: string | undefined\n ): ChannelContext | undefined {\n if (!channel) {\n return undefined;\n }\n const definition = this._channels?.get(channel);\n if (!definition) {\n // A channel was requested but is not registered. Don't throw (a recovered\n // turn may name a channel later removed from `configureChannels()`), but\n // warn so a typo'd channel id is visible rather than silently policy-free.\n // `_channels` is undefined for sub-agents (no channel registry), where a\n // missing channel is expected, so only warn once the registry exists.\n if (this._channels) {\n console.warn(\n `[Think] turn requested channel \"${channel}\" which is not registered ` +\n `(configureChannels()/getMessengers()); no per-channel policy applied`\n );\n }\n return undefined;\n }\n this._emitChannelEvent({\n type: \"channel:resolved\",\n payload: {\n channel,\n kind: definition.kind,\n requestId: admittedTurnContext.getStore()?.requestId\n }\n });\n return {\n channelId: channel,\n kind: definition.kind,\n capabilities: definition.capabilities,\n messenger:\n definition.kind === \"messenger\" ? this.getMessengerContext() : undefined\n };\n }\n\n /**\n * Run `fn` with the turn-scoped channel context set for `channel`. No-op (just\n * runs `fn`) when the channel is unset or unregistered. Save/restore keeps\n * nested turns safe — mirrors `chatWithMessengerContext`.\n */\n private async _withChannelContext<T>(\n channel: string | undefined,\n fn: () => Promise<T>\n ): Promise<T> {\n const context = this._resolveChannelContext(channel);\n if (!context) {\n return fn();\n }\n const previous = this._activeChannelContext;\n this._activeChannelContext = context;\n try {\n return await fn();\n } finally {\n this._activeChannelContext = previous;\n }\n }\n\n /**\n * Stamp the channel id — and, when supplied, the caller's turn metadata —\n * onto user messages so a recovered/continued turn can re-resolve both from\n * durable history.\n */\n private _stampChannel(\n messages: UIMessage[],\n channel: string | undefined,\n turnMetadata?: Record<string, unknown>\n ): UIMessage[] {\n if (!channel && !turnMetadata) {\n return messages;\n }\n return messages.map((message) =>\n message.role === \"user\"\n ? {\n ...message,\n metadata: {\n ...(message.metadata as Record<string, unknown> | undefined),\n ...(channel ? { channel } : {}),\n ...(turnMetadata ? { turnMetadata } : {})\n }\n }\n : message\n );\n }\n\n /** Metadata of the latest user message in the given list, if any. */\n private _latestUserMessageMetadata(\n messages: UIMessage[]\n ): Record<string, unknown> | undefined {\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (message.role === \"user\") {\n return message.metadata as Record<string, unknown> | undefined;\n }\n }\n return undefined;\n }\n\n /** The channel stamped on the latest user message in the given list, if any. */\n private _channelFromMessages(messages: UIMessage[]): string | undefined {\n const channel = this._latestUserMessageMetadata(messages)?.channel;\n return typeof channel === \"string\" ? channel : undefined;\n }\n\n /** The turn metadata stamped on the latest user message, if any. */\n private _turnMetadataFromMessages(\n messages: UIMessage[]\n ): Record<string, unknown> | undefined {\n const turnMetadata =\n this._latestUserMessageMetadata(messages)?.turnMetadata;\n return turnMetadata &&\n typeof turnMetadata === \"object\" &&\n !Array.isArray(turnMetadata)\n ? (turnMetadata as Record<string, unknown>)\n : undefined;\n }\n\n /** Re-resolve the channel for a continuation from the latest user message. */\n private _channelFromLatestUserMessage(): string | undefined {\n return this._channelFromMessages(this.messages);\n }\n\n /**\n * Deliver a no-turn, channel-routed message — a deterministic status, fallback,\n * or notice — straight to the channel's delivery surface WITHOUT invoking the\n * model and WITHOUT opening a recovery incident.\n *\n * Routing precedence for the target channel: explicit `options.channel` → the\n * active turn's channel → `\"web\"`. The `web` channel renders via the transcript\n * (its only client render path), so a web notice is always transcript-visible;\n * messenger/voice deliver out of band and only touch the transcript when\n * `informModel: true`.\n *\n * Like `addMessages`, this bypasses the turn queue and is safe to call from\n * inside a tool `execute` without deadlocking.\n */\n async deliverNotice(\n text: string | { markdown: string },\n options?: DeliverNoticeOptions\n ): Promise<void> {\n const informModel = options?.informModel ?? false;\n const kind: DeliveryKind = options?.kind ?? \"notice\";\n const plain = typeof text === \"string\" ? text : text.markdown;\n const annotated = `[Delivered to the user out of band] ${plain}`;\n const channelId = options?.channel ?? this._activeChannelId() ?? \"web\";\n\n try {\n if (channelId === \"web\") {\n await this.addMessages([\n this._noticeMessage(informModel ? annotated : plain, kind)\n ]);\n } else {\n const surface =\n this._activeDeliverySurface ??\n (await this._messengerRuntime?.resolveDeliverySurface(\n channelId,\n options?.thread\n ));\n if (!surface) {\n const kindOf = this._channels?.get(channelId)?.kind;\n let hint: string;\n if (kindOf === undefined) {\n hint = `; channel \"${channelId}\" is not registered`;\n } else if (kindOf === \"messenger\") {\n hint = options?.thread\n ? ` (thread \"${options.thread}\")`\n : \"; pass { thread } for out-of-turn messenger notices\";\n } else {\n hint = `; channel kind \"${kindOf}\" has no out-of-turn delivery surface yet`;\n }\n throw new Error(\n `deliverNotice: cannot resolve a delivery surface for channel \"${channelId}\"${hint}`\n );\n }\n await surface.post(\n typeof text === \"string\" ? text : { markdown: text.markdown }\n );\n if (informModel) {\n await this.addMessages([this._noticeMessage(annotated, kind)]);\n }\n }\n this._emitChannelEvent({\n type: \"notice:delivered\",\n payload: { channel: channelId, kind, informModel }\n });\n } catch (error) {\n this._emitChannelEvent({\n type: \"notice:failed\",\n payload: {\n channel: channelId,\n error: error instanceof Error ? error.message : String(error)\n }\n });\n throw error;\n }\n }\n\n /**\n * The active turn's channel id, if any. Prefers the turn-scoped channel\n * context, then the active messenger turn's id; web turns have none, so\n * `deliverNotice` defaults to `\"web\"`.\n */\n private _activeChannelId(): string | undefined {\n return (\n this._activeChannelContext?.channelId ??\n this._activeMessengerContext?.messengerId\n );\n }\n\n private _noticeMessage(\n text: string,\n kind: DeliveryKind = \"notice\"\n ): UIMessage {\n return {\n id: crypto.randomUUID(),\n role: \"assistant\",\n parts: [{ type: \"text\", text }],\n metadata: { deliveryKind: kind }\n };\n }\n\n private async _initializeChannels(): Promise<void> {\n if (this.parentPath.length > 0) {\n return;\n }\n\n const configured = await this.configureChannels();\n const messengers = this.getMessengers();\n const { channels, messengers: messengerDefs } = resolveChannels(\n configured,\n messengers\n );\n this._channels = channels;\n\n if (Object.keys(messengerDefs).length === 0) {\n return;\n }\n\n this._messengerRuntime = new ThinkMessengerRuntime(\n messengerDefs,\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 const hasFetchTools = [...toolNames].some((name) =>\n name.startsWith(\"fetch_\")\n );\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 if (hasFetchTools) {\n lines.push(\n \"- If fetch tools are available, use them to read allowlisted HTTP resources (documentation, APIs). They are read-only and bounded; respect their allowlist and do not assume access to other URLs.\"\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 * Retention window for settled action ledger rows. Deleting a row ends the\n * idempotency guarantee for that key, so increase these windows for side\n * effects whose downstream idempotency horizon is longer. Set a status to\n * `false` to disable sweeping it.\n */\n actionLedgerRetention: ActionLedgerRetentionConfig = {\n settledMs: 30 * 24 * 60 * 60 * 1000,\n pendingMs: 90 * 24 * 60 * 60 * 1000,\n maxSweepRows: 500\n };\n\n /**\n * Lease window after which a durable `pending` action ledger row is assumed\n * abandoned (its executor isolate died) and may be reclaimed and re-run.\n * Reclaim re-runs `execute`, so it only applies to actions that declare an\n * explicit `idempotencyKey` — that key is the developer's assertion that the\n * keyed side effect is safe to retry. Fallback `tool:${toolCallId}` keys are\n * never reclaimed. Set to `false` to disable stale-pending reclaim entirely\n * (a stale row then blocks forever with `ActionPendingError`, the old\n * behavior). This is a retry lease, not a retention window: retention answers\n * \"when may we delete old rows?\"; the lease answers \"when may we assume the\n * previous executor died and retry safely?\". Keep `actionLedgerRetention.pendingMs`\n * well above this lease so reclaim happens before a sweep deletes the row.\n */\n actionLedgerPendingRetryLeaseMs: number | false = 5 * 60 * 1000;\n\n /**\n * Retention window for abandoned durable-pause approval rows — a\n * `kind: \"durable-pause\"` action that parked but was never approved or\n * rejected. Deleting a row makes that approval permanently unresolvable, so\n * default generously: \"approve days later from a dashboard\" is the use case.\n * Set to `false` to disable sweeping. Rows are deleted promptly on\n * approve/reject regardless; this only bounds truly abandoned pauses.\n */\n actionPendingApprovalTtlMs: number | false = 30 * 24 * 60 * 60 * 1000;\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 // ── Context-overflow handling (opt-in) ────────────────────────────\n //\n // Compaction normally only fires between turns (Session.compactAfter checks\n // the threshold on appendMessage). But a single long, tool-heavy turn grows\n // the prompt step-by-step inside one streamText loop and can exceed the\n // model's context window *mid-turn*, before the next pre-turn check — the\n // provider then 400s (\"prompt is too long\" / context_length_exceeded). The\n // `contextOverflow` config lets Think recover without baking provider\n // knowledge into core: the app classifies the error (`classifyChatError`),\n // Think reacts.\n\n /**\n * Opt-in handling for a turn that overflows the context window mid-flight.\n * See {@link ContextOverflowConfig}. Unset (the default) leaves the existing\n * terminal behavior unchanged.\n *\n * @example\n * ```typescript\n * override contextOverflow = {\n * reactive: true,\n * proactive: { maxInputTokens: 200_000 }\n * };\n * ```\n */\n contextOverflow?: ContextOverflowConfig;\n\n /** Whether the reactive compact-and-retry backstop is enabled. */\n private get _overflowReactiveEnabled(): boolean {\n return this.contextOverflow?.reactive === true;\n }\n\n /** Reactive compact-and-retry budget. */\n private get _overflowMaxRetries(): number {\n return this.contextOverflow?.maxRetries ?? 1;\n }\n\n /** Proactive guard config, when enabled. */\n private get _overflowGuard():\n | { maxInputTokens: number; headroom?: number; maxCompactions?: number }\n | undefined {\n return this.contextOverflow?.proactive;\n }\n\n /** Per-run cap on proactive compactions (independent of the reactive budget). */\n private get _overflowProactiveMaxCompactions(): number {\n return Math.max(1, this.contextOverflow?.proactive?.maxCompactions ?? 1);\n }\n\n /**\n * Count of model messages assembled from history at the start of the current\n * turn (captured in `_runInferenceLoop`). The proactive guard uses it to\n * splice this turn's in-flight steps onto a freshly recompacted head. Turns\n * are serialized, so a single value is safe.\n */\n private _turnModelMessageBaseline = 0;\n\n /**\n * The assembled tool set for the current turn, captured in\n * `_runInferenceLoop`. The proactive guard reuses it to convert the\n * recompacted history through the same `convertToModelMessages` tool schemas.\n * Turns are serialized, so a single value is safe.\n */\n private _activeTurnTools: ToolSet = {};\n private _activeTurnActionMetadata = new Map<string, CompiledActionMetadata>();\n private _activeTurnAuthorization: NormalizedActionAuthorization = {\n allowed: true\n };\n private _activeTurnActionApprovalDescriptors = new Map<\n string,\n ActionApprovalDescriptor\n >();\n private _activeTurnApprovedActionInputs = new Map<string, unknown>();\n private _activeActionLedgerExecutions = new Map<string, Promise<unknown>>();\n /**\n * Advisory reply attachments recorded by actions during the current admitted\n * turn (see `ctx.attachReply`). Single-slot because turns are serialized.\n * Reset at turn start in `_runInsideAdmittedTurnBody`; intentionally not\n * cleared at turn end so `onChatResponse` and `replyAttachments()` can read\n * it — the next turn's reset overwrites it.\n */\n private _activeTurnReplyAttachments: ReplyAttachment[] = [];\n private _activeTurnReplyAttachmentsRequestId: string | undefined;\n\n /**\n * Number of times the proactive guard has compacted within the current\n * `_runInferenceLoop` (reset at the top of each run). Capped at\n * `contextOverflow.proactive.maxCompactions` (default `1`) so a guard that\n * keeps reading over-budget usage can't compact on every step — once the head\n * is summarized, further compaction no-ops anyway, and a genuine remaining\n * overflow falls through to the reactive backstop.\n */\n private _proactiveCompactionsThisRun = 0;\n\n /** One-time guard for the \"recovery enabled but no classifier\" DX warning. */\n private _warnedMissingClassifier = false;\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 if (this.getSystemPrompt !== Think.prototype.getSystemPrompt) {\n const warning =\n \"getSystemPrompt() is only used as a fallback when no Session context blocks are configured. getSkills() registers a skills context block, so move always-on instructions into configureSession().withContext(...) instead.\";\n if (!this._loggedSkillWarnings.has(warning)) {\n this._loggedSkillWarnings.add(warning);\n console.warn(`[think] ${warning}`);\n }\n }\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 * Authorize action permissions for the current turn. Returning `true` grants\n * all action permissions. Returning `grantedPermissions` limits the default\n * `authorizeAction` implementation to that permission set.\n */\n authorizeTurn(\n _ctx: TurnContext\n ): ActionAuthorizationDecision | Promise<ActionAuthorizationDecision> {\n return true;\n }\n\n /**\n * Authorize a single action call after its model input and required\n * permissions are known. Override this for app-specific policy; the default\n * implementation enforces the grant returned from `authorizeTurn`.\n */\n authorizeAction(\n ctx: ActionAuthorizationContext\n ): ActionAuthorizationDecision | Promise<ActionAuthorizationDecision> {\n const turnAuthorization = this._activeTurnAuthorization;\n if (!turnAuthorization.allowed) {\n return {\n allowed: false,\n reason: turnAuthorization.reason\n };\n }\n if (turnAuthorization.grantedPermissions === undefined) {\n return true;\n }\n const granted = new Set(turnAuthorization.grantedPermissions);\n const missing = ctx.requiredPermissions.filter(\n (permission) => !granted.has(permission)\n );\n if (missing.length === 0) return true;\n return {\n allowed: false,\n reason: `Missing required permission: ${missing.join(\", \")}`\n };\n }\n\n /**\n * Enrich the approval descriptor shown in approval UIs for a paused codemode\n * `execute` execution. The default descriptor is derived from the first\n * pending action as `connector.method` with its args as the input; override\n * here to supply a human summary, the permissions it consumes, or a risk\n * level (returned fields are merged over the derived defaults).\n *\n * Not called for `kind: \"durable-pause\"` actions — those carry their own\n * descriptor from the `action()` config. Default returns `undefined` (use the\n * derived descriptor).\n */\n describePausedExecution(\n _pending: import(\"@cloudflare/codemode\").PendingAction[],\n _ctx: { requestId: string; toolCallId: string }\n ): Partial<ActionApprovalDescriptor> | undefined {\n return undefined;\n }\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 onStepEnd(ctx: StepContext): void | Promise<void> {\n return this.onStepFinish(ctx);\n }\n\n /**\n * Called after each step completes (initial, continue, tool-result).\n * Override for step-level logging or analytics.\n * @deprecated Prefer `onStepEnd`.\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 /**\n * Classify a raw chat-turn error into a provider-agnostic category.\n *\n * Think deliberately ships **no** provider-specific matching: it cannot know\n * that Anthropic's `\"prompt is too long\"` or OpenAI's\n * `context_length_exceeded` means \"context overflow\" without baking provider\n * knowledge into core. The app does know its provider/model, so it owns the\n * mapping — the same split Think already uses for `tokenCounter`.\n *\n * Currently this hook drives **only** context-overflow recovery: it is\n * consulted when a turn errors **and** `contextOverflow.reactive` is enabled\n * (if reactive is off, it is not called). Return `\"context_overflow\"` to run\n * the compact-and-retry backstop; if recovery cannot save the turn, that\n * classification is surfaced on the terminal `onChatError` call via\n * {@link ChatErrorContext.classification}. The other categories are reserved\n * for future use — returning one today is a no-op (the turn terminalizes as\n * usual) and it is **not** forwarded to `onChatError`. Returning\n * `void`/`\"unknown\"` keeps the existing terminal behavior.\n *\n * The argument may be an `Error`, an AI SDK `APICallError` (with\n * `statusCode`/`responseBody`), or — for in-stream provider errors that\n * surface as a stream error part rather than a throw — the error message\n * string. Narrow accordingly.\n *\n * The second argument carries a {@link ChatErrorContext}: when consulted for\n * overflow recovery it is `{ stage: \"stream\", requestId }`, so a classifier\n * can correlate the error with the in-flight turn (e.g. to call\n * {@link cancelChat}).\n *\n * @example Anthropic + OpenAI context-overflow\n * ```typescript\n * classifyChatError(error: unknown): ChatErrorClassification | void {\n * const text = error instanceof Error ? error.message : String(error);\n * if (/prompt is too long|context length|context_length_exceeded|maximum context/i.test(text)) {\n * return \"context_overflow\";\n * }\n * }\n * ```\n */\n classifyChatError(\n _error: unknown,\n _ctx?: ChatErrorContext\n ): ChatErrorClassification | void {}\n\n /**\n * Whether an error (thrown or surfaced as an in-stream error string) should\n * trigger the opt-in compact-and-retry backstop. Consults the app's\n * `classifyChatError` and the `contextOverflow.reactive` flag. Centralized\n * so both stream consumers (WebSocket + RPC) classify identically.\n */\n private _isRecoverableContextOverflow(\n error: unknown,\n requestId?: string\n ): boolean {\n if (!this._overflowReactiveEnabled) return false;\n // DX guard: enabling recovery without teaching Think which errors are\n // overflows silently does nothing. Warn once instead of failing quietly.\n if (this.classifyChatError === Think.prototype.classifyChatError) {\n if (!this._warnedMissingClassifier) {\n this._warnedMissingClassifier = true;\n console.warn(\n '[Think] contextOverflow.reactive is enabled but classifyChatError() is not overridden, so no error will ever be treated as a context overflow and recovery will never run. Override classifyChatError() (or assign the exported defaultContextOverflowClassifier) to return \"context_overflow\" for your provider\\'s context-window error (e.g. Anthropic \"prompt is too long\", OpenAI context_length_exceeded).'\n );\n }\n return false;\n }\n let classification: ChatErrorClassification | void;\n try {\n classification = this.classifyChatError(error, {\n stage: \"stream\",\n requestId\n });\n } catch (err) {\n console.warn(\n `[Think] classifyChatError threw; treating as non-overflow: ${err instanceof Error ? err.message : String(err)}`\n );\n return false;\n }\n return classification === \"context_overflow\";\n }\n\n /**\n * Compact the session in response to a context overflow (reactive backstop or\n * proactive guard). Returns whether history was actually shortened — a no-op\n * compaction (returns `null`) means a retry would just overflow again, so the\n * caller should fall through to the terminal error rather than loop.\n *\n * This is the single emit point for `chat:context:compacted`, so callers must\n * NOT emit it again.\n */\n private async _compactForContextOverflow(\n reason: \"reactive\" | \"proactive\",\n extra?: { requestId?: string; attempt?: number }\n ): Promise<boolean> {\n try {\n const result = await this.session.compact();\n const shortened = Boolean(result);\n this._emit(\"chat:context:compacted\", {\n reason,\n shortened,\n ...extra\n });\n return shortened;\n } catch (err) {\n console.warn(\n `[Think] context-overflow compaction failed: ${err instanceof Error ? err.message : String(err)}`\n );\n return false;\n }\n }\n\n /**\n * Finalize a context overflow that recovery could not fix (compaction was a\n * no-op, or the retry budget is spent). Routes the error through\n * `onChatError` with `classification: \"context_overflow\"` and emits\n * `chat:request:failed`, so every overflow terminal — whichever path it took\n * — is reported identically. Returns the (possibly app-reshaped) message for\n * the caller to deliver via its own transport (RPC callback / WS broadcast).\n */\n private _finalizeContextOverflowError(\n requestId: string,\n rawError: string | undefined\n ): string {\n const raw = rawError ?? \"Context window exceeded.\";\n const wrapped = this.onChatError(raw, {\n requestId,\n stage: \"stream\",\n messagesPersisted: true,\n classification: \"context_overflow\"\n });\n const message =\n wrapped instanceof Error ? wrapped.message : String(wrapped);\n this._emit(\"chat:request:failed\", {\n requestId,\n stage: \"stream\",\n messagesPersisted: true,\n error: message\n });\n return message;\n }\n\n // ── Extension initialization ───────────────────────────────────\n\n private async _initializeExtensions(): Promise<void> {\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 * Assemble provider-ready model messages from the current session history:\n * repair the transcript, truncate older messages, drop any still-incomplete\n * tool calls, and convert to `ModelMessage[]`. Shared by the turn entry point\n * and the proactive context guard so a mid-turn recompaction rebuilds the\n * head through the exact same pipeline.\n */\n private async _assembleModelMessages(\n tools: ToolSet\n ): Promise<Awaited<ReturnType<typeof convertToModelMessages>>> {\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 return convertToModelMessages(truncated, {\n tools,\n ignoreIncompleteToolCalls: true\n });\n }\n\n /**\n * Proactive context guard (Layer 1). Runs before each step from the\n * `prepareStep` wrapper. If `contextOverflow.proactive` is set and the *previous*\n * step's model-reported input tokens cross the budget, compact the session in\n * place and return recompacted messages for the upcoming step — heading off a\n * provider context-overflow 400 before it happens.\n *\n * Keys off `usage.inputTokens` (provider-agnostic; every provider reports it)\n * rather than any provider error string, and reuses `_assembleModelMessages`\n * so the recompacted head goes through the same repair/convert pipeline. The\n * current turn's in-flight steps (everything after `_turnModelMessageBaseline`)\n * are spliced back on so no completed work is lost.\n *\n * Best-effort: any failure (no-op compaction, reconciliation that would leave\n * an incomplete tool pair) returns `undefined` so the step proceeds unchanged\n * and the reactive backstop (`contextOverflow.reactive`) can still\n * catch a genuine overflow.\n */\n private async _maybeProactiveContextCompact(\n event: PrepareStepContext\n ): Promise<Awaited<ReturnType<typeof convertToModelMessages>> | undefined> {\n const guard = this._overflowGuard;\n if (!guard || guard.maxInputTokens <= 0) return undefined;\n // Proactive cap is independent of the reactive budget — it has its own\n // `proactive.maxCompactions` (default 1). This lets an app use the proactive\n // guard without the reactive backstop (and vice versa) and tune each freely.\n if (\n this._proactiveCompactionsThisRun >= this._overflowProactiveMaxCompactions\n )\n return undefined;\n\n const prev = event.steps?.at(-1);\n const used = prev?.usage?.inputTokens ?? prev?.usage?.totalTokens;\n if (used == null || !Number.isFinite(used)) return undefined;\n\n const headroom = guard.headroom ?? 0.9;\n if (used < guard.maxInputTokens * headroom) return undefined;\n\n try {\n // Count the ATTEMPT (not just successful shortenings) before compacting.\n // This bounds the guard to `proactiveCap` tries per run regardless of\n // outcome: a no-op compaction (e.g. nothing left to summarize) would be a\n // no-op again on every subsequent step, so consuming the slot here is\n // what stops it from compacting — and emitting `chat:context:compacted` —\n // on every step. A genuine remaining overflow falls through to the\n // reactive backstop. (Locked by the \"no-op\" proactive test.)\n this._proactiveCompactionsThisRun++;\n const shortened = await this._compactForContextOverflow(\"proactive\");\n if (!shortened) return undefined;\n\n // Rebuild the compacted head, then splice this turn's in-flight steps\n // (which are not yet persisted to the session) back onto the tail.\n const head = await this._assembleModelMessages(this._activeTurnTools);\n const tail = event.messages.slice(this._turnModelMessageBaseline);\n const merged = [...head, ...tail];\n // Re-baseline so a second guard fire this turn keeps the new tail. This\n // is correct only if the AI SDK carries our returned `messages` override\n // forward into the next step's `event.messages` (so the next slice sees\n // [recompacted head, ...in-flight steps], not the original uncompacted\n // array). Verified by the \"fires twice in one turn\" test in\n // assistant-agent-loop.test.ts — a clean multi-fire completion proves the\n // override propagates and the splice does not drop/duplicate tool pairs.\n this._turnModelMessageBaseline = head.length;\n return merged;\n } catch (err) {\n console.warn(\n `[Think] proactive context compaction failed; proceeding without it: ${err instanceof Error ? err.message : String(err)}`\n );\n return undefined;\n }\n }\n\n /**\n * Finalizes the traced inference stream after a drain loop exits: drains the\n * abandoned tee branch so the operation span closes even on early exits.\n * Idempotent (the finalizer is removed before it runs); the drain rides\n * `ctx.waitUntil` so it survives turn completion without blocking it.\n */\n private _drainInferenceStream(result: object): void {\n const finalizer = inferenceStreamFinalizers.get(result);\n inferenceStreamFinalizers.delete(result);\n if (!finalizer || finalizer.started) {\n return;\n }\n\n finalizer.started = true;\n // Invoke exactly once: start the drain, then try to extend its lifetime.\n // A missing/throwing waitUntil must not start a second tee consumer.\n const completion = finalizer.run();\n try {\n this.ctx.waitUntil(completion);\n } catch {\n // waitUntil unavailable (tests, exotic contexts): the drain is already\n // running; nothing further to attach it to.\n }\n }\n\n /**\n * Adds default identity and current-turn metadata to the AI SDK telemetry\n * options. The class identifies the logical agent implementation, the named\n * instance identifies the agent resource, and the opaque Durable Object id\n * identifies its one persisted conversation. Caller values override defaults.\n */\n private _turnTelemetry(\n base: Parameters<typeof streamText>[0][\"experimental_telemetry\"]\n ): Parameters<typeof streamText>[0][\"experimental_telemetry\"] {\n const settings = (base ?? {}) as unknown as Record<string, unknown>;\n const metadata =\n typeof settings.metadata === \"object\" && settings.metadata !== null\n ? (settings.metadata as Record<string, unknown>)\n : {};\n const turn = admittedTurnContext.getStore();\n return {\n ...settings,\n // AI SDK maps functionId to gen_ai.agent.name. Use the class name by\n // default while preserving an explicit caller label.\n functionId:\n typeof settings.functionId === \"string\"\n ? settings.functionId\n : this.constructor.name,\n metadata: {\n agentId: this.name,\n conversationId: this.ctx.id.toString(),\n ...(turn?.agent === this\n ? {\n \"cloudflare.agents.turn.request_id\": turn.requestId,\n \"cloudflare.agents.turn.trigger\": turn.trigger,\n \"cloudflare.agents.turn.admission\": turn.admission,\n ...(turn.channel !== undefined && {\n \"cloudflare.agents.turn.channel\": turn.channel\n }),\n ...(turn.continuation !== undefined && {\n \"cloudflare.agents.turn.continuation\": turn.continuation\n }),\n ...(turn.generation !== undefined && {\n \"cloudflare.agents.turn.generation\": turn.generation\n })\n }\n : {}),\n // beforeTurn remains authoritative. metadata.agentName, when supplied,\n // also takes precedence over functionId in the tracing adapter.\n ...metadata\n }\n } as unknown as Parameters<typeof streamText>[0][\"experimental_telemetry\"];\n }\n\n /** Builds the native AI SDK v7 telemetry settings and identity context. */\n private _turnTelemetryV7(\n base: Parameters<typeof streamText>[0][\"experimental_telemetry\"]\n ): {\n options: Record<string, unknown>;\n runtimeContext: Record<string, unknown>;\n } {\n const settings = (base ?? {}) as unknown as Record<string, unknown>;\n const metadata =\n typeof settings.metadata === \"object\" && settings.metadata !== null\n ? (settings.metadata as Record<string, unknown>)\n : {};\n const turn = admittedTurnContext.getStore();\n const runtimeContext: Record<string, unknown> = {\n agentId: this.name,\n conversationId: this.ctx.id.toString(),\n ...(turn?.agent === this\n ? {\n \"cloudflare.agents.turn.request_id\": turn.requestId,\n \"cloudflare.agents.turn.trigger\": turn.trigger,\n \"cloudflare.agents.turn.admission\": turn.admission,\n ...(turn.channel !== undefined && {\n \"cloudflare.agents.turn.channel\": turn.channel\n }),\n ...(turn.continuation !== undefined && {\n \"cloudflare.agents.turn.continuation\": turn.continuation\n }),\n ...(turn.generation !== undefined && {\n \"cloudflare.agents.turn.generation\": turn.generation\n })\n }\n : {}),\n ...metadata\n };\n const includedContext =\n typeof settings.includeRuntimeContext === \"object\" &&\n settings.includeRuntimeContext !== null\n ? (settings.includeRuntimeContext as Record<string, boolean>)\n : {};\n const localIntegrations = settings.integrations;\n const globalIntegrations = (\n globalThis as typeof globalThis & {\n AI_SDK_TELEMETRY_INTEGRATIONS?: unknown[];\n }\n ).AI_SDK_TELEMETRY_INTEGRATIONS;\n const integrations = [\n ...(localIntegrations !== undefined\n ? Array.isArray(localIntegrations)\n ? localIntegrations\n : [localIntegrations]\n : (globalIntegrations ?? []))\n ];\n if (\n !integrations.some(\n (integration) =>\n typeof integration === \"object\" &&\n integration !== null &&\n agentsAISDKTelemetryBrand in integration\n )\n ) {\n integrations.push(\n createAISDKTelemetry({\n storeMessages: this.storeMessages,\n storeTools: this.storeTools\n })\n );\n }\n\n const options: Record<string, unknown> = {\n ...settings,\n functionId:\n typeof settings.functionId === \"string\"\n ? settings.functionId\n : this.constructor.name,\n includeRuntimeContext: {\n ...Object.fromEntries(\n Object.keys(runtimeContext).map((key) => [key, true])\n ),\n ...includedContext\n },\n integrations\n };\n delete options.metadata;\n return { options, runtimeContext };\n }\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 const turn = admittedTurnContext.getStore();\n const invoke = await withAgentSpan(\n this,\n \"prepare_agent\",\n \"turn\",\n {\n \"cloudflare.agents.component\": \"think\",\n ...(turn?.agent === this\n ? {\n \"cloudflare.agents.turn.request_id\": turn.requestId,\n \"cloudflare.agents.turn.trigger\": turn.trigger,\n \"cloudflare.agents.turn.admission\": turn.admission,\n \"cloudflare.agents.turn.channel\": turn.channel,\n \"cloudflare.agents.turn.continuation\": turn.continuation,\n \"cloudflare.agents.turn.generation\": turn.generation\n }\n : {})\n },\n () => this._prepareInferenceInvocation(input)\n );\n return invoke();\n }\n\n private async _prepareInferenceInvocation(\n input: TurnInput\n ): Promise<() => StreamableResult> {\n // Keep one exposure policy for this inference attempt even if subclass\n // code changes the instance property while asynchronous setup is running.\n const includeMcpTools = this.includeMcpTools;\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 this._activeTurnAuthorization = { allowed: true };\n this._activeTurnApprovedActionInputs =\n this._approvedActionInputsFromTranscript();\n // Reset the proactive-compaction cap for this streamText run.\n this._proactiveCompactionsThisRun = 0;\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 fetchToolSet: ToolSet = this.fetchTools\n ? createFetchTools({\n ...this.fetchTools,\n workspace: this.workspace,\n onEvent: (event: FetchToolEvent) => {\n (\n this._emit as unknown as (\n type: string,\n payload: Record<string, unknown>\n ) => void\n ).call(this, \"tool:fetch\", { ...event });\n }\n })\n : {};\n const baseTools = this.getTools();\n const actionTools = await this._compileActionTools();\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(\n input.clientTools,\n input.clientToolExecutor\n ? { execute: input.clientToolExecutor }\n : undefined\n );\n let tools: ToolSet = {\n ...workspaceTools,\n ...fetchToolSet,\n ...baseTools,\n ...actionTools,\n ...extensionTools,\n ...contextTools,\n ...skillTools,\n ...(includeMcpTools ? (this.mcp?.getAITools?.() ?? {}) : {}),\n ...clientToolSet\n };\n\n // Per-channel policy (overridable defaults applied BEFORE `beforeTurn`):\n // narrow the tool set (the `config.tools` seam can only ADD, never remove)\n // and prepend channel instructions to the base system prompt.\n const channelContext = this._activeChannelContext;\n const channelDefinition = channelContext\n ? this._channels?.get(channelContext.channelId)\n : undefined;\n if (channelDefinition?.tools) {\n tools = channelDefinition.tools(tools);\n }\n\n const channelInstructions =\n channelDefinition?.instructions && channelContext\n ? typeof channelDefinition.instructions === \"function\"\n ? await channelDefinition.instructions(channelContext)\n : channelDefinition.instructions\n : undefined;\n\n const frozenPrompt = await this.session.freezeSystemPrompt();\n const rawBaseSystem = frozenPrompt || this.getSystemPrompt();\n const baseSystem = channelInstructions\n ? `${channelInstructions}\\n\\n${rawBaseSystem}`\n : rawBaseSystem;\n const system = this._systemPromptForTurn(baseSystem, tools);\n\n const messages = await this._assembleModelMessages(tools);\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.resolveModel();\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 // Workflow `step.prompt` turns produce their structured result by calling\n // the synthetic `final_answer` tool (see THINK_FINAL_ANSWER_TOOL_NAME) —\n // NOT via the AI SDK `output`/`response_format` path, which some providers\n // reject when streaming. We pre-build the JSON Schema once here.\n const structuredOutputSchema = workflowPrompt?.output\n ? jsonSchema(workflowPrompt.output.schema as never)\n : undefined;\n const wantsStructuredOutput = structuredOutputSchema !== undefined;\n\n const finalModel =\n config.model != null ? this.resolveModel(config.model) : model;\n const finalSystem =\n config.instructions ??\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 const finalTurnContext: TurnContext = {\n ...ctx,\n system: finalSystem,\n messages: finalMessages,\n tools: mergedTools,\n model: finalModel\n };\n this._activeTurnAuthorization = this._normalizeActionAuthorization(\n await this.authorizeTurn(finalTurnContext)\n );\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 // For a structured workflow turn, expose a final-answer tool alongside the\n // agent's real tools. The agent loops with its tools and terminates by\n // calling this one; its arguments are captured as the structured result.\n // Guard against a clash with a user tool of the same name by suffixing.\n let finalAnswerToolName = THINK_FINAL_ANSWER_TOOL_NAME;\n if (structuredOutputSchema) {\n let suffix = 1;\n while (finalAnswerToolName in finalTools) {\n finalAnswerToolName = `${THINK_FINAL_ANSWER_TOOL_NAME}_${suffix++}`;\n }\n finalTools[finalAnswerToolName] = tool({\n description:\n \"Provide your final answer. The arguments MUST match the required \" +\n \"schema. Calling this tool ends the task — call it exactly once when \" +\n \"you have everything you need.\",\n inputSchema: structuredOutputSchema,\n execute: async () => \"Final answer recorded.\"\n });\n }\n\n // Baseline for the proactive context guard: everything the AI SDK appends\n // to the model-message list after the assembled turn messages belongs to\n // this turn's steps, so a mid-turn recompaction can keep that tail and only\n // re-summarize the (now-compacted) head. Captured from the FINAL messages\n // and tools — after `beforeTurn` may have overridden them — so the tail\n // splice stays correct even when the override changes the message count.\n this._turnModelMessageBaseline = finalMessages.length;\n this._activeTurnTools = mergedTools;\n\n // `maxTurns` is an overridable per-channel default: a user `beforeTurn`\n // returning `maxSteps` still wins, then the channel cap, then the instance\n // default.\n const finalMaxSteps =\n config.maxSteps ?? channelDefinition?.maxTurns ?? 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 // `output` (AI SDK structured-output / `response_format`) is reserved for\n // the opt-in chat `TurnConfig.output` API. Workflow prompts use the\n // `final_answer` tool instead (see `wantsStructuredOutput`).\n const finalOutput = config.output;\n // On a structured workflow turn, append the instruction telling the model to\n // finish by calling `final_answer`. `filter(Boolean)` drops an absent system\n // prompt so we never stringify `undefined` into the prompt.\n const turnSystem = wantsStructuredOutput\n ? [finalSystem, thinkFinalAnswerInstruction(finalAnswerToolName)]\n .filter(Boolean)\n .join(\"\\n\\n\")\n : finalSystem;\n // Structured turns must not end with a plain-text answer that skips\n // `final_answer` (some models, e.g. Workers AI llama, otherwise just reply\n // in text and stop). Force tool use: when the agent has real tools, require\n // *a* tool each step so it can do work and then call `final_answer`; with no\n // real tools, pin the choice directly to `final_answer`. A caller-provided\n // `toolChoice` still wins.\n const structuredHasRealTools =\n wantsStructuredOutput &&\n Object.keys(finalTools).some((name) => name !== finalAnswerToolName);\n const finalToolChoice = wantsStructuredOutput\n ? (config.toolChoice ??\n (structuredHasRealTools\n ? \"required\"\n : { type: \"tool\" as const, toolName: finalAnswerToolName }))\n : config.toolChoice;\n const finalStopWhen = [\n stepCountIs(finalMaxSteps),\n // Stop as soon as the model calls `final_answer` so the structured turn\n // terminates at the answer instead of continuing to stream more steps.\n ...(wantsStructuredOutput ? [hasToolCall(finalAnswerToolName)] : []),\n ...(Array.isArray(config.stopWhen)\n ? config.stopWhen\n : config.stopWhen\n ? [config.stopWhen]\n : [])\n ];\n\n const turnTelemetry = config.telemetry ?? config.experimental_telemetry;\n const streamTextOptions = {\n model: finalModel,\n // `system` is accepted by both AI SDK v6 and v7 (v7 also accepts the\n // renamed `instructions`, but v6 does not). Use `system` for cross-major\n // compatibility.\n system: turnSystem,\n messages: finalMessages,\n tools: finalTools,\n // Keep the synthetic final-answer tool callable even when a caller\n // restricts `activeTools` — otherwise a structured turn could never call\n // it and would fail to produce output.\n activeTools:\n wantsStructuredOutput && config.activeTools\n ? [...config.activeTools, finalAnswerToolName]\n : config.activeTools,\n toolChoice: finalToolChoice,\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: usesAISDKV7Telemetry\n ? undefined\n : this._turnTelemetry(turnTelemetry),\n // Forward the per-turn stream transform(s) from TurnConfig so callers\n // can inspect/rewrite the stream (e.g. emit `source` parts derived from\n // tool results) without owning the stream pipeline themselves.\n experimental_transform: config.experimental_transform,\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 // Proactive context guard (Layer 1) runs first so `beforeStep` sees the\n // recompacted messages and can still override them if it wants to.\n const guarded = await this._maybeProactiveContextCompact(event);\n const result = await this.beforeStep(event);\n const base = result == null ? {} : result;\n // Only apply the guard's recompacted messages when the subclass didn't\n // set its own `messages` override for this step.\n const baseMessages = (base as { messages?: unknown }).messages;\n const withMessages =\n guarded && baseMessages === undefined\n ? { ...base, messages: guarded }\n : base;\n // Safety net for structured workflow turns: on the final permitted step,\n // force the model to call `final_answer` so the turn always terminates\n // with a schema-shaped result instead of running out of steps. Respect a\n // `toolChoice` the subclass already set for this step.\n const stepResult =\n wantsStructuredOutput &&\n event.stepNumber >= finalMaxSteps - 1 &&\n (withMessages as { toolChoice?: unknown }).toolChoice === undefined\n ? {\n ...withMessages,\n toolChoice: {\n type: \"tool\" as const,\n toolName: finalAnswerToolName\n },\n activeTools: [finalAnswerToolName]\n }\n : withMessages;\n // `beforeStep` may return a string `model` (StepConfig widens it to\n // ThinkModel); the AI SDK needs a concrete LanguageModel, so resolve it.\n const stepModel = (stepResult as { model?: ThinkModel }).model;\n if (typeof stepModel === \"string\") {\n return {\n ...stepResult,\n model: this.resolveModel(stepModel)\n } as PrepareStepResult<ToolSet>;\n }\n return stepResult as PrepareStepResult<ToolSet>;\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` is the step callback name in both AI SDK v6 and v7 (v7\n // also accepts the renamed `onStepEnd`, but v6 does not). Use the shared\n // name; it still dispatches to Think's `onStepEnd` hook.\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.onStepEnd(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 execution time and the discriminated `success`/`error`\n // outcome — including failures that propagate out of `execute`.\n //\n // We register `experimental_onToolCallFinish` (rather than the v7-only\n // `onToolExecutionEnd`) because it is the native option in AI SDK v6 and\n // a supported alias in v7 — `ai` resolves it to `onToolExecutionEnd`\n // internally and fires it exactly once. `normalizeToolFinishEvent`\n // reconciles the differing event shapes between the two majors.\n experimental_onToolCallFinish: (async (event) => {\n // The synthetic final-answer tool is internal plumbing for structured\n // workflow turns — do not surface it to user `afterToolCall` hooks or\n // extensions.\n const e = normalizeToolFinishEvent(event);\n if (e.toolCall.toolName === finalAnswerToolName) return;\n const { success, output, error } = e;\n const base = {\n ...e.toolCall,\n stepNumber: e.stepNumber,\n messages: e.messages,\n toolExecutionMs: e.toolExecutionMs,\n durationMs: e.toolExecutionMs\n };\n const ctx = (success\n ? {\n ...base,\n toolOutput: { type: \"tool-result\" as const, output },\n success: true as const,\n output\n }\n : {\n ...base,\n toolOutput: { type: \"tool-error\" as const, error },\n success: false as const,\n error\n }) as unknown as ToolCallResultContext;\n await this.afterToolCall(ctx);\n await this._pipelineExtensionToolCallFinish({\n toolCall: e.toolCall,\n stepNumber: e.stepNumber,\n durationMs: e.toolExecutionMs,\n success,\n output,\n error\n });\n }) as ToolCallFinishCallback\n } satisfies Parameters<typeof streamText>[0];\n\n if (usesAISDKV7Telemetry) {\n const { options, runtimeContext } = this._turnTelemetryV7(turnTelemetry);\n const crossMajorOptions = streamTextOptions as unknown as Record<\n string,\n unknown\n >;\n delete crossMajorOptions.experimental_telemetry;\n crossMajorOptions.telemetry = options;\n crossMajorOptions.runtimeContext = runtimeContext;\n }\n\n const inferenceStreamText: typeof streamText = usesAISDKV7Telemetry\n ? streamText\n : wrapAISDK(\n { streamText, wrapLanguageModel },\n { storeMessages: this.storeMessages, storeTools: this.storeTools }\n ).streamText;\n\n return () => {\n const result = inferenceStreamText(streamTextOptions);\n\n const outputPromise = wantsStructuredOutput\n ? // Structured workflow result = the `final_answer` tool call's INPUT\n // (its arguments), captured after the stream finishes. Take the last\n // call in case the model emitted more than one. `result.toolCalls` is a\n // `PromiseLike`, so wrap it to get a real `Promise` (for `.catch` below).\n Promise.resolve(result.toolCalls).then((calls) => {\n const finalCalls = calls.filter(\n (call) => call.toolName === finalAnswerToolName\n );\n const last = finalCalls[finalCalls.length - 1];\n if (!last) {\n throw new Error(\n `Model ended the turn without calling the ${finalAnswerToolName} tool`\n );\n }\n return last.input;\n })\n : finalOutput && result.output\n ? Promise.resolve(result.output)\n : 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: (options) => {\n const sendReasoning = options?.sendReasoning ?? finalSendReasoning;\n const onError = options?.onError ?? streamErrorToString;\n // Use the result's own `toUIMessageStream()` method rather than the\n // standalone `toUIMessageStream({ stream })` helper: the method exists\n // in both AI SDK v6 and v7 (deprecated in v7 but functional), whereas\n // the standalone helper and the `result.stream` property it needs are\n // v7-only.\n const uiStream = (\n result as {\n toUIMessageStream: (o: {\n sendReasoning?: boolean;\n onError?: (error: unknown) => string;\n }) => ReadableStream;\n }\n ).toUIMessageStream({ sendReasoning, onError });\n return readableStreamToAsyncIterable(uiStream);\n },\n output: outputPromise\n } satisfies StreamableResult;\n\n const finalizer: InferenceStreamFinalizer = {\n started: false,\n run: () =>\n // consumeStream never rejects (onError swallows) and is a no-op when\n // the stream already ran to completion.\n Promise.resolve(result.consumeStream({ onError: () => {} }))\n };\n inferenceStreamFinalizers.set(streamResult, finalizer);\n\n const finalized = this._transformInferenceResult(streamResult);\n if (finalized !== streamResult) {\n inferenceStreamFinalizers.set(finalized, finalizer);\n }\n return finalized;\n };\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 private _normalizeActionAuthorization(\n decision: ActionAuthorizationDecision\n ): NormalizedActionAuthorization {\n if (typeof decision === \"boolean\") {\n return { allowed: decision };\n }\n return {\n allowed: decision.allowed,\n ...(decision.reason !== undefined && { reason: decision.reason }),\n ...(decision.grantedPermissions !== undefined && {\n grantedPermissions: [...decision.grantedPermissions]\n })\n };\n }\n\n private _emitActionLedgerEvent(event: ActionLedgerEvent): void {\n const emit = this._emit as unknown as (\n type: string,\n payload: Record<string, unknown>\n ) => void;\n emit.call(this, event.type, event.payload);\n }\n\n private _emitChannelEvent(event: ChannelEvent): void {\n const emit = this._emit as unknown as (\n type: string,\n payload: Record<string, unknown>\n ) => void;\n emit.call(this, event.type, event.payload);\n }\n\n private _approvedActionInputsFromTranscript(): Map<string, unknown> {\n const approved = new Map<string, unknown>();\n for (const message of this.messages) {\n for (const part of message.parts ?? []) {\n if (typeof part !== \"object\" || part === null) continue;\n const record = part as Record<string, unknown>;\n const toolCallId =\n typeof record.toolCallId === \"string\" ? record.toolCallId : undefined;\n if (!toolCallId) continue;\n const approval = record.approval as\n | { approved?: unknown; descriptor?: unknown }\n | undefined;\n if (approval?.approved !== true) continue;\n const descriptor = approval.descriptor as\n | { input?: unknown; action?: unknown }\n | undefined;\n if (typeof descriptor?.action !== \"string\") continue;\n approved.set(\n toolCallId,\n \"input\" in descriptor ? descriptor.input : record.input\n );\n }\n }\n return approved;\n }\n\n private async _resolveActionPermissions(\n spec: ActionPermissionSpec<unknown> | undefined,\n input: unknown,\n ctx: ActionContext\n ): Promise<string[]> {\n if (spec === undefined) return [];\n const policyCtx = this._actionContextWithoutReply(ctx);\n const permissions =\n typeof spec === \"function\" ? await spec({ input, ctx: policyCtx }) : spec;\n return [...permissions];\n }\n\n private _actionContextWithoutReply(ctx: ActionContext): ActionContext {\n return {\n ...ctx,\n attachReply: () => {}\n };\n }\n\n private async _authorizeActionCall(options: {\n actionName: string;\n kind: ActionKind;\n input: unknown;\n ctx: ActionContext;\n permissions?: ActionPermissionSpec<unknown>;\n }): Promise<NormalizedActionAuthorization & { permissions: string[] }> {\n const permissions = await this._resolveActionPermissions(\n options.permissions,\n options.input,\n options.ctx\n );\n const decision = await this.authorizeAction({\n requestId: options.ctx.requestId,\n toolCallId: options.ctx.toolCallId,\n action: options.actionName,\n kind: options.kind,\n input: options.input,\n requiredPermissions: permissions,\n grantedPermissions: this._activeTurnAuthorization.grantedPermissions,\n messages: options.ctx.messages,\n agent: this,\n env: this.env as Cloudflare.Env\n });\n return {\n ...this._normalizeActionAuthorization(decision),\n permissions\n };\n }\n\n private async _compileActionTools(): Promise<ToolSet> {\n const actions = await this.getActions();\n const tools: ToolSet = {};\n this._activeTurnActionMetadata = new Map();\n this._activeTurnActionApprovalDescriptors = new Map();\n for (const [registrationName, descriptor] of Object.entries(actions)) {\n if (!isAction(descriptor)) {\n throw new Error(\n `getActions() entry \"${registrationName}\" must be created with action().`\n );\n }\n const toolName = descriptor.config.name ?? registrationName;\n const kind =\n descriptor.config.kind ??\n (descriptor.config.approval ? \"approval-gated\" : \"server\");\n if (kind === \"approval-gated\" || kind === \"durable-pause\") {\n const staticPermissions = Array.isArray(descriptor.config.permissions)\n ? [...descriptor.config.permissions]\n : undefined;\n this._activeTurnActionMetadata.set(toolName, {\n actionName: toolName,\n summary:\n descriptor.config.approvalSummary ?? descriptor.config.description,\n ...(staticPermissions !== undefined && {\n permissions: staticPermissions\n }),\n ...(descriptor.config.approvalRisk !== undefined && {\n risk: descriptor.config.approvalRisk\n }),\n kind\n });\n }\n tools[toolName] = this._actionToTool(descriptor, toolName, kind);\n }\n return tools;\n }\n\n private _actionToTool(\n descriptor: Action,\n toolName: string,\n kind: ActionKind\n ): ToolSet[string] {\n const config = descriptor.config;\n const executeAction = config.execute as (\n input: unknown,\n ctx: ActionContext\n ) => Promise<unknown> | unknown;\n const approval = config.approval as\n | ActionApprovalPolicy<unknown>\n | undefined;\n const permissions = config.permissions as\n | ActionPermissionSpec<unknown>\n | undefined;\n const idempotencyKey = config.idempotencyKey as\n | ActionIdempotencyKey<unknown>\n | undefined;\n\n return tool({\n description: config.description,\n metadata: {\n cfThinkAction: true,\n cfThinkActionApprovalConfigured:\n approval !== undefined && kind !== \"durable-pause\"\n },\n inputSchema: config.inputSchema as never,\n ...(approval !== undefined && kind !== \"durable-pause\"\n ? {\n needsApproval: async (\n input: unknown,\n options: {\n toolCallId: string;\n messages: ModelMessage[];\n }\n ) => {\n const ctx: ActionContext = {\n agent: this,\n env: this.env as Cloudflare.Env,\n requestId: admittedTurnContext.getStore()?.requestId ?? \"\",\n toolCallId: options.toolCallId,\n messages: options.messages,\n signal: new AbortController().signal,\n // No-op: approval/permission predicates must be pure and may\n // run twice (prompt + resume). Attachments belong to execute.\n attachReply: () => {}\n };\n if (\n this._activeTurnApprovedActionInputs.has(options.toolCallId)\n ) {\n return true;\n }\n const authorization = await this._authorizeActionCall({\n actionName: toolName,\n kind,\n input,\n ctx,\n permissions\n });\n if (!authorization.allowed) return false;\n const needsApproval =\n typeof approval === \"function\"\n ? await approval({ input, ctx })\n : approval;\n if (needsApproval) {\n this._activeTurnActionApprovalDescriptors.set(\n options.toolCallId,\n {\n requestId: ctx.requestId,\n toolCallId: options.toolCallId,\n action: toolName,\n summary: config.approvalSummary ?? config.description,\n input,\n permissions: authorization.permissions,\n ...(config.approvalRisk !== undefined && {\n risk: config.approvalRisk\n }),\n kind: \"approval-gated\"\n }\n );\n }\n return needsApproval;\n }\n }\n : {}),\n execute: async (\n input: unknown,\n options: {\n toolCallId?: string;\n messages?: ModelMessage[];\n abortSignal?: AbortSignal;\n }\n ): Promise<unknown> => {\n const { signal, cleanup } = createActionAbortSignal(\n options.abortSignal,\n config.timeoutMs ?? DEFAULT_ACTION_TIMEOUT_MS\n );\n const requestId = admittedTurnContext.getStore()?.requestId ?? \"\";\n const actionContext: ActionContext = {\n agent: this,\n env: this.env as Cloudflare.Env,\n requestId,\n toolCallId: options.toolCallId ?? \"\",\n messages: options.messages ?? [],\n signal,\n attachReply: (attachment) =>\n this._recordReplyAttachment(requestId, attachment, toolName)\n };\n const abortError = () =>\n signal.reason instanceof Error\n ? signal.reason\n : new Error(\n signal.reason ? String(signal.reason) : \"Action aborted\"\n );\n let onAbort: (() => void) | undefined;\n\n try {\n const authorization = await this._authorizeActionCall({\n actionName: toolName,\n kind,\n input,\n ctx: actionContext,\n permissions\n });\n if (!authorization.allowed) {\n return actionAuthorizationErrorEnvelope(\n authorization.reason,\n authorization.permissions\n );\n }\n if (signal.aborted) throw abortError();\n const abortPromise = new Promise<never>((_, reject) => {\n onAbort = () => reject(abortError());\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n const runAction = async () => {\n const output = await Promise.race([\n Promise.resolve(executeAction(input, actionContext)),\n abortPromise\n ]);\n return prepareActionOutputForModel(output);\n };\n\n if (kind === \"durable-pause\") {\n // The approval predicate gates whether to PARK (not whether an AI\n // SDK approval is needed). Absent → always park; a function may opt\n // a given input out of the human gate and run inline instead.\n const shouldPark =\n approval === undefined\n ? true\n : typeof approval === \"function\"\n ? await approval({\n input,\n ctx: this._actionContextWithoutReply(actionContext)\n })\n : approval;\n if (!shouldPark) {\n return await this._runLedgeredAction({\n toolName,\n idempotencyKey,\n input,\n ctx: actionContext,\n runAction\n });\n }\n return this._parkDurablePauseAction({\n toolName,\n input,\n ctx: actionContext,\n summary: config.approvalSummary ?? config.description,\n permissions: authorization.permissions,\n risk: config.approvalRisk\n });\n }\n\n return await this._runLedgeredAction({\n toolName,\n idempotencyKey,\n input,\n ctx: actionContext,\n runAction\n });\n } catch (error) {\n return actionErrorEnvelope(error);\n } finally {\n if (onAbort) signal.removeEventListener(\"abort\", onAbort);\n cleanup();\n }\n }\n });\n }\n\n /**\n * Run an action's `execute` through the action ledger: same-isolate\n * coalescing, durable claim/replay, settle-on-success, release-on-failure.\n * Shared by the inline server-action path and the durable-pause-on-approve\n * path so an action's side effect is replay-safe regardless of how it is\n * dispatched. `runAction` must already apply timeout/abort and\n * `prepareActionOutputForModel`.\n */\n private async _runLedgeredAction(args: {\n toolName: string;\n idempotencyKey: ActionIdempotencyKey<unknown> | undefined;\n input: unknown;\n ctx: ActionContext;\n runAction: () => Promise<unknown>;\n }): Promise<unknown> {\n const { toolName, idempotencyKey, input, ctx, runAction } = args;\n\n const ledgerKey = await this._resolveActionLedgerKey(\n toolName,\n idempotencyKey,\n input,\n this._actionContextWithoutReply(ctx)\n );\n if (!ledgerKey) {\n const attachmentCount = this._activeTurnReplyAttachments.length;\n try {\n return await runAction();\n } catch (error) {\n this._activeTurnReplyAttachments.length = attachmentCount;\n throw error;\n }\n }\n\n const active = this._activeActionLedgerExecutions.get(ledgerKey);\n if (active) {\n return await active;\n }\n\n const inputHash = this._actionInputHash(input);\n // An explicit `idempotencyKey` is the developer's assertion that retrying\n // the keyed side effect is safe; only those rows are reclaimable when stale.\n // Fallback `tool:${toolCallId}` keys stay conservative.\n const hasExplicitIdempotencyKey = idempotencyKey !== undefined;\n const claim = this._claimActionLedgerRow({\n key: ledgerKey,\n actionName: toolName,\n requestId: ctx.requestId,\n toolCallId: ctx.toolCallId,\n inputHash,\n retryablePending: hasExplicitIdempotencyKey,\n leaseMs: this.actionLedgerPendingRetryLeaseMs\n });\n if (claim.outcome === \"replay\") {\n this._emitActionLedgerEvent({\n type: \"action:ledger:replayed\",\n payload: { action: toolName, key: ledgerKey, inputHash }\n });\n return decodeActionLedgerOutput(claim.row.result_json);\n }\n if (claim.outcome === \"pending\") {\n this._emitActionLedgerEvent({\n type: \"action:ledger:pending\",\n payload: { action: toolName, key: ledgerKey, inputHash }\n });\n return actionPendingErrorEnvelope();\n }\n if (claim.outcome === \"conflict\") {\n this._emitActionLedgerEvent({\n type: \"action:ledger:conflict\",\n payload: { action: toolName, key: ledgerKey, inputHash }\n });\n return actionKeyConflictEnvelope(toolName, ledgerKey);\n }\n // `claimed` (fresh row) and `reclaimed` (stale row re-leased) both fall\n // through to execution below; reclaim just re-runs the keyed side effect.\n if (claim.outcome === \"reclaimed\") {\n this._emitActionLedgerEvent({\n type: \"action:ledger:reclaimed\",\n payload: {\n action: toolName,\n key: ledgerKey,\n inputHash,\n ageMs: Date.now() - claim.row.updated_at\n }\n });\n }\n\n const attachmentCount = this._activeTurnReplyAttachments.length;\n const execution = Promise.resolve().then(async () => {\n try {\n const prepared = await runAction();\n const encoded = encodeActionLedgerOutput(prepared);\n if (!encoded.ok) {\n this._releaseActionLedgerRow(ledgerKey);\n this._emitActionLedgerEvent({\n type: \"action:ledger:serialize_failed\",\n payload: { action: toolName, key: ledgerKey }\n });\n return prepared;\n }\n this._settleActionLedgerRow(ledgerKey, encoded.json);\n this._emitActionLedgerEvent({\n type: \"action:ledger:settled\",\n payload: { action: toolName, key: ledgerKey, inputHash }\n });\n return encoded.value;\n } catch (error) {\n this._activeTurnReplyAttachments.length = attachmentCount;\n throw error;\n }\n });\n this._activeActionLedgerExecutions.set(ledgerKey, execution);\n try {\n return await execution;\n } catch (error) {\n this._releaseActionLedgerRow(ledgerKey);\n return actionErrorEnvelope(error);\n } finally {\n this._activeActionLedgerExecutions.delete(ledgerKey);\n }\n }\n\n /**\n * Park a `kind: \"durable-pause\"` action for human approval. Persists a\n * compaction-safe pending row (action name + model input + approval\n * descriptor) so the approval survives history compaction, deploys, and\n * isolate eviction, then returns the minimal model-visible paused output.\n *\n * The action's `execute` does NOT run here — it runs later in\n * `approveExecution` via `_runLedgeredAction`, so the side effect is gated on\n * human approval AND remains replay-safe. The rich descriptor lives on the\n * row and on the transcript part, never embedded in the model-visible output.\n */\n private _parkDurablePauseAction(args: {\n toolName: string;\n input: unknown;\n ctx: ActionContext;\n summary: string;\n permissions: string[];\n risk?: \"low\" | \"medium\" | \"high\";\n }): {\n status: \"paused\";\n executionId: string;\n action: string;\n message: string;\n } {\n const { toolName, input, ctx, summary, permissions, risk } = args;\n const executionId = `${ACTION_PAUSE_ID_PREFIX}${crypto.randomUUID()}`;\n const descriptor: ActionApprovalDescriptor = {\n requestId: ctx.requestId,\n toolCallId: ctx.toolCallId,\n action: toolName,\n summary,\n input,\n permissions,\n ...(risk !== undefined && { risk }),\n kind: \"durable-pause\"\n };\n this._insertActionPendingRow({\n execution_id: executionId,\n action_name: toolName,\n tool_call_id: ctx.toolCallId,\n request_id: ctx.requestId || null,\n input_json: JSON.stringify(input),\n descriptor_json: JSON.stringify(descriptor),\n created_at: Date.now()\n });\n this._emitActionPauseEvent({\n type: \"action:pause:created\",\n payload: { action: toolName, executionId, toolCallId: ctx.toolCallId }\n });\n return {\n status: \"paused\",\n executionId,\n action: toolName,\n message:\n \"This action is awaiting human approval. Stop and wait for the \" +\n \"approval result before proceeding.\"\n };\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. The canonical form is an async\n * generator (`async function* execute(...)`), where calling `execute`\n * synchronously returns a direct `AsyncIterable`. For that form Think\n * preserves preliminary streaming: the wrapper is itself an async\n * generator that `await`s `beforeToolCall` and then yields every\n * chunk through unchanged. Non-streaming tools keep a scalar wrapper\n * so they never emit a synthetic `preliminary` tool-result chunk.\n *\n * The non-canonical `async function execute(...) { return makeIter(); }`\n * form returns a `Promise<AsyncIterable>`, which does not stream even\n * in the raw AI SDK (it would surface the iterator object as the final\n * output). Think collapses it to the last yielded value instead. If\n * you need preliminary streaming, use an `async function*` `execute`.\n */\n private _wrapToolsWithDecision(tools: ToolSet): ToolSet {\n const wrapped: ToolSet = {};\n // Capture `this` lexically so the streaming wrapper (which must be an\n // async generator function expression, not an arrow) can reach the\n // shared decision helper without a per-tool `.bind`.\n const self = this;\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 const metadata = t.metadata as Record<string, unknown> | undefined;\n const isApprovalConfiguredAction =\n metadata?.cfThinkAction === true &&\n metadata.cfThinkActionApprovalConfigured === true;\n\n // Canonical AI SDK streaming tools use an async generator `execute`\n // (`async function* execute(...)`). Detect that form so we can keep\n // preliminary streaming flowing through `beforeToolCall`. Everything\n // else routes through the scalar wrapper so non-streaming tools never\n // emit a synthetic `preliminary` tool-result.\n const isStreamingExecute =\n (originalExecute as { constructor?: { name?: string } }).constructor\n ?.name === \"AsyncGeneratorFunction\";\n\n const wrappedExecute = isStreamingExecute\n ? (input: unknown, options: ToolDecisionOptions) =>\n // Returning the generator synchronously (via the sync arrow)\n // keeps it a *direct* AsyncIterable so the AI SDK streams the\n // preliminary parts instead of awaiting a Promise<AsyncIterable>.\n (async function* () {\n const resolved = await self._resolveToolCallDecision(\n toolName,\n input,\n options,\n isDynamic,\n isApprovalConfiguredAction\n );\n if (!resolved.execute) {\n // Block/substitute is a scalar outcome, but this wrapper had\n // to commit to an AsyncIterable shape synchronously (before the\n // async decision was known) so the execute path can stream.\n // The AI SDK's `executeTool` turns every yielded value into a\n // `preliminary` tool-result plus a `final`, so this single\n // yield surfaces one synthetic `preliminary` chunk to observers\n // (e.g. onChunk) that the scalar wrapper never emits. The\n // model-visible final output is identical and correct, and this\n // matches how any streaming tool that emits a single value\n // already behaves — so we accept it rather than regress\n // streaming preservation for the (rare) block/substitute case.\n yield resolved.output;\n return;\n }\n const result = await originalExecute(\n resolved.finalInput,\n options\n );\n if (\n result != null &&\n typeof result === \"object\" &&\n Symbol.asyncIterator in (result as object)\n ) {\n // Stream the original tool's preliminary outputs through\n // unchanged — the AI SDK emits each as a `preliminary`\n // tool-result and the last as the final value.\n yield* result as AsyncIterable<unknown>;\n } else {\n yield result;\n }\n })()\n : async (\n input: unknown,\n options: ToolDecisionOptions\n ): Promise<unknown> => {\n const resolved = await self._resolveToolCallDecision(\n toolName,\n input,\n options,\n isDynamic,\n isApprovalConfiguredAction\n );\n if (!resolved.execute) return resolved.output;\n // Await before inspecting so we detect a direct AsyncIterable\n // return even from a non-async-generator `execute` (e.g. a\n // plain function that returns a generator). Such non-canonical\n // streaming shapes are collapsed to their last yielded value.\n const result = await originalExecute(resolved.finalInput, options);\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\n wrapped[toolName] = {\n ...(originalTool as object),\n execute: wrappedExecute\n } as ToolSet[string];\n }\n return wrapped;\n }\n\n /**\n * Shared `beforeToolCall` resolution for both the scalar and streaming\n * tool wrappers (see {@link _wrapToolsWithDecision}). Builds the\n * `ToolCallContext`, consults the subclass `beforeToolCall` hook,\n * dispatches the extension observation snapshot, and resolves the\n * returned `ToolCallDecision` into either \"run `execute` with this\n * input\" or \"short-circuit with this output\".\n */\n private async _resolveToolCallDecision(\n toolName: string,\n input: unknown,\n options: ToolDecisionOptions,\n isDynamic: boolean,\n isApprovalConfiguredAction: boolean\n ): Promise<\n { execute: true; finalInput: unknown } | { execute: false; output: unknown }\n > {\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 decision\n // 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 const approvedInput = isApprovalConfiguredAction\n ? this._activeTurnApprovedActionInputs.get(options.toolCallId)\n : undefined;\n if (\n approvedInput !== undefined &&\n !stableJsonEqual(finalInput, approvedInput)\n ) {\n return { execute: false, output: actionApprovalInputErrorEnvelope() };\n }\n return { execute: true, finalInput };\n }\n if (decision.action === \"block\") {\n return {\n execute: false,\n output:\n decision.reason ?? `Tool \"${toolName}\" was blocked by beforeToolCall.`\n };\n }\n // substitute\n return { execute: false, output: decision.output };\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 private async _admitTurn<T>(\n spec: QueueTurnSpec<T>\n ): Promise<AdmittedQueueResult<T>>;\n private async _admitTurn<T>(spec: NonQueueTurnSpec<T>): Promise<T>;\n private async _admitTurn<T>(\n spec: TurnSpec<T>\n ): Promise<AdmittedQueueResult<T> | T> {\n if (spec.admission !== \"queue\") {\n // The non-queue (submit/execute-submission) path runs `execute()` here\n // directly — it does NOT pass through `_runInsideAdmittedTurnBody`, so the\n // channel context must be set here too.\n return withAgentSpan(\n this,\n \"chat_submission\",\n \"submission\",\n {\n \"cloudflare.agents.component\": \"think\",\n \"cloudflare.agents.turn.trigger\": spec.trigger,\n \"cloudflare.agents.turn.admission\": spec.admission,\n \"cloudflare.agents.turn.channel\": spec.channel\n },\n () =>\n withAgentSpan(\n this,\n spec.admission === \"submit\"\n ? \"accept_chat_submission\"\n : \"execute_chat_submission\",\n \"submission\",\n {\n \"cloudflare.agents.component\": \"think\",\n \"cloudflare.agents.turn.trigger\": spec.trigger,\n \"cloudflare.agents.turn.admission\": spec.admission,\n \"cloudflare.agents.turn.channel\": spec.channel\n },\n () => this._withChannelContext(spec.channel, () => spec.execute())\n )\n );\n }\n\n if (!spec.allowNested) {\n this._assertNotInsideAdmittedTurn(spec.trigger);\n }\n\n return this.keepAliveWhile(async () => {\n const turnPromise = this._turnQueue.enqueue(\n spec.requestId,\n () => this._runInsideAdmittedTurnBody(spec),\n spec.generation === undefined\n ? undefined\n : { generation: spec.generation }\n );\n spec.onQueued?.();\n return turnPromise;\n });\n }\n\n private _assertNotInsideAdmittedTurn(trigger: TurnTrigger): void {\n if (admittedTurnContext.getStore()?.agent !== this) return;\n throw new Error(\n `Think turn admission (${trigger}) cannot be called from inside an active turn; use runTurn({ mode: \"submit\" }) or addMessages() instead`\n );\n }\n\n private async _runInsideAdmittedTurnBody<T>(\n spec: QueueTurnSpec<T>\n ): Promise<T> {\n return withAgentSpan(\n this,\n \"chat_turn\",\n \"turn\",\n {\n \"cloudflare.agents.component\": \"think\",\n \"cloudflare.agents.turn.request_id\": spec.requestId,\n \"cloudflare.agents.turn.trigger\": spec.trigger,\n \"cloudflare.agents.turn.admission\": spec.admission,\n \"cloudflare.agents.turn.channel\": spec.channel,\n \"cloudflare.agents.turn.continuation\": spec.continuation,\n \"cloudflare.agents.turn.generation\": spec.generation\n },\n (update) =>\n admittedTurnContext.run(\n {\n agent: this,\n requestId: spec.requestId,\n trigger: spec.trigger,\n admission: spec.admission,\n channel: spec.channel,\n continuation: spec.continuation,\n generation: spec.generation\n },\n async () => {\n const startedAt = Date.now();\n this._emit(\"chat:turn:start\", {\n requestId: spec.requestId,\n trigger: spec.trigger,\n admission: spec.admission,\n ...(spec.continuation !== undefined && {\n continuation: spec.continuation\n }),\n ...(spec.generation !== undefined && {\n generation: spec.generation\n })\n });\n\n this._activeTurnReplyAttachments = [];\n this._activeTurnReplyAttachmentsRequestId = spec.requestId;\n\n try {\n const value = await this._withChannelContext(spec.channel, () =>\n spec.execute()\n );\n const status = spec.getStatus?.() ?? \"completed\";\n this._emit(\"chat:turn:finish\", {\n requestId: spec.requestId,\n trigger: spec.trigger,\n admission: spec.admission,\n ...(spec.continuation !== undefined && {\n continuation: spec.continuation\n }),\n ...(spec.generation !== undefined && {\n generation: spec.generation\n }),\n status,\n durationMs: Date.now() - startedAt\n });\n update({ \"cloudflare.agents.turn.status\": status });\n return value;\n } catch (error) {\n const message =\n error instanceof Error ? error.message : String(error);\n this._emit(\"chat:turn:finish\", {\n requestId: spec.requestId,\n trigger: spec.trigger,\n admission: spec.admission,\n ...(spec.continuation !== undefined && {\n continuation: spec.continuation\n }),\n ...(spec.generation !== undefined && {\n generation: spec.generation\n }),\n status: \"error\",\n durationMs: Date.now() - startedAt,\n error: message\n });\n update({ \"cloudflare.agents.turn.status\": \"error\" });\n throw error;\n }\n }\n )\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(s), or a callback that derives them\n * from the in-queue transcript.\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: TurnInputMessages,\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 // Client tools supplied by the caller (e.g. a parent agent delegating to\n // this sub-agent). Both the schemas and the `onClientToolCall` executor are\n // forwarded per-turn only — deliberately NOT persisted into\n // `_lastClientTools`. The executor is a live RPC ref that dies with the\n // isolate, so unlike the WebSocket path there is no SPA that could ever\n // replay a `tool-result` after an eviction. Persisting the names would put\n // them in `_clientResolvableToolNames()`, causing recovery to misclassify a\n // dangling `input-available` orphan as a pending human interaction and park\n // forever. Keeping them per-turn lets such an orphan recover like a server\n // tool: `continueLastTurn`'s transcript repair errors it and the model\n // proceeds. `_runInferenceLoop` sources client tools from `input.clientTools`\n // (not `_lastClientTools`), so the live turn is unaffected.\n const clientTools = options?.clientTools?.length\n ? options.clientTools\n : undefined;\n const clientToolExecutor = options?.onClientToolCall;\n\n try {\n await callback.onStart({ requestId });\n await this._admitTurn({\n admission: \"queue\",\n trigger: \"rpc\",\n requestId,\n continuation: false,\n channel: options?.channel,\n execute: async () => {\n const resolved =\n typeof userMessage === \"function\"\n ? await userMessage(this.messages)\n : this._normalizeChatMessages(userMessage);\n\n for (const msg of this._stampChannel(\n resolved,\n options?.channel,\n options?.metadata\n )) {\n await this._appendMessageToHistory(msg);\n }\n this._broadcastMessages();\n\n const chatBody = async () => {\n // Bounded compact-and-retry loop (opt-in via\n // `contextOverflow.reactive`). A turn that overflows the context\n // window mid-flight is compacted and re-run from the persisted\n // partial instead of dying terminally. Every attempt re-runs the\n // SAME user turn from the now-compacted history, so it stays\n // `continuation: false` — an overflow retry is not an\n // auto-continuation, and `beforeTurn` should not treat it as one.\n for (let attempt = 0; ; attempt++) {\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 clientTools,\n clientToolExecutor,\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 // The consumer suppresses a classified overflow whenever recovery\n // is enabled; the driver (here) owns the retry-vs-terminal call so\n // every overflow terminal is reported identically.\n const { status, error } = await this._streamResultToRpcCallback(\n requestId,\n result,\n callback,\n abortSignal,\n { overflowRecovery: this._overflowReactiveEnabled }\n );\n\n if (status === \"overflow_retry\") {\n if (\n attempt < this._overflowMaxRetries &&\n !abortSignal?.aborted\n ) {\n const shortened = await this._compactForContextOverflow(\n \"reactive\",\n { requestId, attempt: attempt + 1 }\n );\n // Compaction shortened history → retry. A no-op compaction\n // can't fix the overflow, so fall through to terminal.\n if (shortened) continue;\n }\n // Budget spent, aborted, or compaction no-op: deliver terminally\n // (through onChatError, classified) so the turn never loops or ends\n // silently with no answer.\n const message = this._finalizeContextOverflowError(\n requestId,\n error\n );\n await callback.onError(message);\n }\n return;\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 /**\n * Unified turn admission API (Turns RFC, step 2).\n *\n * Thin facade over {@link Think.saveMessages}, {@link Think.continueLastTurn},\n * {@link Think.submitMessages}, and {@link Think.chat}. Each `mode` delegates\n * to the matching backing method with a narrowed option surface; the full\n * unified superset lands with `_admitTurn` (step 3).\n *\n * - `mode: \"wait\"` (default) — blocking turn; returns {@link TurnResult}.\n * - `mode: \"submit\"` — durable queued turn; returns {@link SubmitMessagesResult}.\n * - `mode: \"stream\"` — RPC-style streaming; returns `Promise<void>`.\n *\n * **Re-entrancy.** Calling `mode: \"wait\"` or `continuation: true` from inside\n * an active turn (a tool `execute`, a lifecycle hook) deadlocks on the turn\n * queue — identical to calling {@link Think.saveMessages} or\n * {@link Think.continueLastTurn} from there. Prefer `mode: \"submit\"` or\n * {@link Think.addMessages} instead. Precise nested-call detection is deferred\n * to `_admitTurn` (step 3).\n *\n * **Empty input (`wait`).** String, single-message, and array inputs that\n * normalize to an empty list short-circuit to `{ status: \"skipped\" }` without\n * running inference. A function `input` that resolves to `[]` at run time is\n * not pre-checked (the function must see the in-queue transcript); step 3's\n * `_admitTurn` centralizes empty-skip inside the queue.\n *\n * @experimental\n */\n runTurn(options: RunTurnWait): Promise<TurnResult>;\n runTurn(options: RunTurnSubmit): Promise<SubmitMessagesResult>;\n runTurn(options: RunTurnStream): Promise<void>;\n async runTurn(\n options: RunTurnOptions\n ): Promise<TurnResult | SubmitMessagesResult | void> {\n const mode = this._resolveRunTurnMode(options);\n if (mode === \"stream\") {\n return this._runTurnStream(options as RunTurnStream);\n }\n if (mode === \"submit\") {\n return this._runTurnSubmit(options as RunTurnSubmit);\n }\n return this._runTurnWait(options as RunTurnWait);\n }\n\n private _resolveRunTurnMode(\n options: RunTurnOptions\n ): \"wait\" | \"submit\" | \"stream\" {\n if (options === null || typeof options !== \"object\") {\n throw new TypeError(\"runTurn: options must be an object\");\n }\n\n const mode = (options as { mode?: unknown }).mode;\n if (mode === undefined || mode === \"wait\") return \"wait\";\n if (mode === \"submit\" || mode === \"stream\") return mode;\n throw new TypeError('runTurn: mode must be \"wait\", \"submit\", or \"stream\"');\n }\n\n private _validateRunTurnAdmission(\n options: RunTurnOptions,\n mode: \"wait\" | \"submit\" | \"stream\"\n ): void {\n const hasInput = options.input !== undefined;\n const continuation =\n mode === \"wait\" && (options as RunTurnWait).continuation === true;\n\n if (mode !== \"wait\" && (options as RunTurnWait).continuation === true) {\n throw new TypeError(\n 'runTurn: continuation is only supported with mode: \"wait\"'\n );\n }\n\n if (mode === \"stream\" && !(options as RunTurnStream).callback) {\n throw new TypeError('runTurn: mode \"stream\" requires callback');\n }\n\n if (mode === \"wait\") {\n if (hasInput && continuation) {\n throw new TypeError(\n \"runTurn: supply either input or continuation: true, not both\"\n );\n }\n if (!hasInput && !continuation) {\n throw new TypeError(\n \"runTurn: supply either input or continuation: true\"\n );\n }\n return;\n }\n\n if (!hasInput) {\n throw new TypeError(`runTurn: mode \"${mode}\" requires input`);\n }\n }\n\n private _userMessageFromText(text: string): UIMessage {\n return {\n id: crypto.randomUUID(),\n role: \"user\",\n parts: [{ type: \"text\", text }]\n };\n }\n\n private _normalizeRunTurnMessages(\n input: Exclude<\n TurnInputMessages,\n (current: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>\n >\n ): UIMessage[] {\n if (typeof input === \"string\") {\n if (input.length === 0) return [];\n return [this._userMessageFromText(input)];\n }\n if (Array.isArray(input)) {\n return input;\n }\n return [input];\n }\n\n private _normalizeChatMessages(\n input: Exclude<\n TurnInputMessages,\n (current: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>\n >\n ): UIMessage[] {\n if (typeof input === \"string\") {\n return [this._userMessageFromText(input)];\n }\n if (Array.isArray(input)) {\n return input;\n }\n return [input];\n }\n\n private _assertRunTurnSubmitInput(\n input: TurnInputMessages\n ): asserts input is string | UIMessage | UIMessage[] {\n if (typeof input === \"function\") {\n throw new Error(\n 'runTurn({ mode: \"submit\" }) does not support function input until _admitTurn (step 3)'\n );\n }\n }\n\n private async _enrichTurnResult(\n result: SaveMessagesResult,\n continuation: boolean\n ): Promise<TurnResult> {\n let message: SessionMessage | undefined;\n if (result.status === \"completed\") {\n const leaf = await this.session.getLatestLeaf();\n if (leaf?.role === \"assistant\") {\n message = leaf;\n }\n }\n return { ...result, continuation, message };\n }\n\n private async _runTurnWait(options: RunTurnWait): Promise<TurnResult> {\n this._validateRunTurnAdmission(options, \"wait\");\n\n if (options.continuation === true) {\n const result = await this.continueLastTurn(options.body, {\n signal: options.signal,\n channel: options.channel\n });\n return this._enrichTurnResult(result, true);\n }\n\n const input = options.input;\n if (input === undefined) {\n throw new TypeError(\"runTurn: supply either input or continuation: true\");\n }\n\n if (typeof input === \"function\") {\n const result = await this._runProgrammaticMessagesTurn(\n crypto.randomUUID(),\n input,\n { signal: options.signal, channel: options.channel }\n );\n return this._enrichTurnResult(result, false);\n }\n\n const messages = this._normalizeRunTurnMessages(input);\n if (messages.length === 0) {\n return { requestId: \"\", status: \"skipped\", continuation: false };\n }\n\n const result = await this._runProgrammaticMessagesTurn(\n crypto.randomUUID(),\n messages,\n { signal: options.signal, channel: options.channel }\n );\n return this._enrichTurnResult(result, false);\n }\n\n private async _runTurnSubmit(\n options: RunTurnSubmit\n ): Promise<SubmitMessagesResult> {\n this._validateRunTurnAdmission(options, \"submit\");\n\n const input = options.input;\n if (input === undefined) {\n throw new TypeError('runTurn: mode \"submit\" requires input');\n }\n\n this._assertRunTurnSubmitInput(input);\n const messages = this._normalizeRunTurnMessages(input);\n return this.submitMessages(messages, {\n submissionId: options.submissionId,\n idempotencyKey: options.idempotencyKey,\n metadata: options.metadata,\n channel: options.channel\n });\n }\n\n private async _runTurnStream(options: RunTurnStream): Promise<void> {\n this._validateRunTurnAdmission(options, \"stream\");\n\n const input = options.input;\n if (input === undefined) {\n throw new TypeError('runTurn: mode \"stream\" requires input');\n }\n\n if (typeof input !== \"function\") {\n const messages = this._normalizeRunTurnMessages(input);\n if (messages.length === 0) {\n await options.callback.onStart({ requestId: crypto.randomUUID() });\n await options.callback.onDone();\n return;\n }\n }\n\n return this.chat(input, options.callback, {\n signal: options.signal,\n clientTools: options.clientTools,\n onClientToolCall: options.onClientToolCall,\n channel: options.channel\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 // Latest progress snapshot (rfc-detached-agent-tools §progress). Only the\n // most recent `reportProgress` is retained; `last_signal_at` drives the\n // parent's resetting no-progress budget across eviction.\n this._addAgentToolChildRunColumnIfMissing(\n \"ALTER TABLE cf_agent_tool_child_runs ADD COLUMN progress_json TEXT\"\n );\n this._addAgentToolChildRunColumnIfMissing(\n \"ALTER TABLE cf_agent_tool_child_runs ADD COLUMN last_signal_at INTEGER\"\n );\n // Durable milestones (rfc-detached-agent-tools §progress, 4b). One row per\n // milestone; `sequence` is monotonic per run so replay/live races dedupe.\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_agent_tool_milestones (\n run_id TEXT NOT NULL,\n sequence INTEGER NOT NULL,\n name TEXT NOT NULL,\n data_json TEXT,\n at INTEGER NOT NULL,\n PRIMARY KEY (run_id, sequence)\n )\n `;\n }\n\n private _persistAgentToolMilestone(\n runId: string,\n name: string,\n data: unknown,\n at: number\n ): number {\n this._ensureAgentToolChildRunTable();\n const rows = this.sql<{ next: number }>`\n SELECT COALESCE(MAX(sequence), -1) + 1 AS next\n FROM cf_agent_tool_milestones WHERE run_id = ${runId}\n `;\n const sequence = rows[0]?.next ?? 0;\n this.sql`\n INSERT OR IGNORE INTO cf_agent_tool_milestones\n (run_id, sequence, name, data_json, at)\n VALUES (\n ${runId}, ${sequence}, ${name},\n ${data !== undefined ? JSON.stringify(data) : null}, ${at}\n )\n `;\n // A milestone is a progress signal too: advance the no-progress clock.\n this.sql`\n UPDATE cf_agent_tool_child_runs SET last_signal_at = ${at}\n WHERE run_id = ${runId}\n `;\n return sequence;\n }\n\n private _readAgentToolMilestones(runId: string): AgentToolMilestone[] {\n this._ensureAgentToolChildRunTable();\n return this.sql<{\n sequence: number;\n name: string;\n data_json: string | null;\n at: number;\n }>`\n SELECT sequence, name, data_json, at FROM cf_agent_tool_milestones\n WHERE run_id = ${runId} ORDER BY sequence ASC\n `.map((row) => ({\n name: row.name,\n sequence: row.sequence,\n at: row.at,\n ...(row.data_json != null\n ? { data: Think._parseAgentToolOutput(row.data_json) }\n : {})\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, progress_json,\n last_signal_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 const progress = Think._progressSnapshotFromRow(row);\n return progress ? { progress } : {};\n })(),\n ...(() => {\n const milestones = this._readAgentToolMilestones(row.run_id);\n return milestones.length > 0 ? { milestones } : {};\n })()\n };\n }\n\n /**\n * Rebuild the latest progress snapshot persisted by `reportProgress` from a\n * child run row, or `undefined` if the child never reported progress.\n */\n private static _progressSnapshotFromRow(\n row: AgentToolChildRunRow\n ): AgentToolProgressSnapshot | undefined {\n if (row.progress_json == null || row.last_signal_at == null)\n return undefined;\n try {\n const parsed = JSON.parse(row.progress_json) as Partial<\n Omit<AgentToolProgressSnapshot, \"at\">\n >;\n return { ...parsed, at: row.last_signal_at };\n } catch {\n return { at: row.last_signal_at };\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 private _agentToolProgressEmitterInstance: AgentToolProgressEmitter | null =\n null;\n\n private get _agentToolProgressEmitter(): AgentToolProgressEmitter {\n if (!this._agentToolProgressEmitterInstance) {\n this._agentToolProgressEmitterInstance = new AgentToolProgressEmitter({\n resolveActiveRun: () => {\n const requestId = admittedTurnContext.getStore()?.requestId;\n if (!requestId) return null;\n const runId = this._agentToolRunsByRequestId.get(requestId);\n return runId ? { runId, requestId } : null;\n },\n broadcast: (requestId, chunkBody) => {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: chunkBody,\n done: false\n });\n },\n persistSnapshot: (runId, snapshot, at) => {\n this._ensureAgentToolChildRunTable();\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET progress_json = ${JSON.stringify(snapshot)},\n last_signal_at = ${at}\n WHERE run_id = ${runId}\n `;\n },\n persistMilestone: (runId, name, data, at) =>\n this._persistAgentToolMilestone(runId, name, data, at)\n });\n }\n return this._agentToolProgressEmitterInstance;\n }\n\n override async reportProgress<T = unknown>(\n progress: AgentToolProgress<T>,\n options?: { persist?: boolean }\n ): Promise<void> {\n const result = this._agentToolProgressEmitter.report(progress, options);\n if (result === \"inactive\") {\n console.warn(\n \"[think] reportProgress() was called outside of an active agent-tool run; ignoring. Call it from within a turn that is running as a sub-agent.\"\n );\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 /**\n * Format the message injected back into the chat when a `detached:\n * { notify: true }` run finishes. Override to customize the prose (or return\n * an empty string to suppress the notification for a given outcome). The\n * default announces the terminal status and any summary/error so the model\n * has enough context to react.\n */\n protected formatDetachedCompletion(\n run: AgentToolRunInfo,\n result: AgentToolLifecycleResult\n ): string {\n const label = `Background task \"${run.agentType}\" (run ${run.runId})`;\n switch (result.status) {\n case \"completed\":\n return result.summary\n ? `${label} finished:\\n\\n${result.summary}`\n : `${label} finished successfully.`;\n case \"error\":\n return `${label} failed${result.error ? `: ${result.error}` : \".\"}`;\n case \"aborted\":\n return `${label} was cancelled.`;\n case \"interrupted\":\n return result.reason === \"budget-exceeded\"\n ? `${label} ran out of time before completing and was stopped.`\n : `${label} was interrupted before completing${result.error ? `: ${result.error}` : \".\"}`;\n default:\n return `${label} ended (${result.status}).`;\n }\n }\n\n /**\n * Serialize detached terminal delivery against the chat turn queue. A\n * fast-path push or backbone tick can land mid-turn, and an `onFinish` that\n * mutates state (`setState`, `submitMessages`, a follow-up `runAgentTool`)\n * running concurrently with an active LLM turn is a data race. Those paths\n * never run synchronously inside a turn body (they fire from `waitUntil` / a\n * scheduled alarm), so enqueuing on the turn queue runs the delivery strictly\n * between turns without risk of self-deadlock.\n *\n * An explicit `cancelAgentTool` (`serialize` unset) may be invoked from inside\n * the very turn that triggers it, where enqueuing WOULD self-deadlock, so it\n * runs inline in the caller's (or a fresh) `agentContext` instead. The Think\n * `notify` convenience is unaffected either way: it delivers via\n * `submitMessages`, which already serializes FIFO behind any active turn.\n */\n protected override async _runDetachedDelivery(\n invoke: () => Promise<void>,\n options?: { serialize?: boolean }\n ): Promise<void> {\n const inContext = () =>\n agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n invoke\n );\n if (!options?.serialize) {\n if (agentContext.getStore()?.agent === this) {\n await invoke();\n return;\n }\n await inContext();\n return;\n }\n await this.keepAliveWhile(() =>\n this._turnQueue.enqueue(\n `detached-delivery:${crypto.randomUUID()}`,\n inContext\n )\n );\n }\n\n /**\n * Targeted completion hook for `detached: { notify: true }`. Auto-wired by\n * `runAgentTool` (resolved by name so the base Agent stays decoupled from the\n * chat layer). Injects the formatted completion as a programmatic turn so the\n * model reacts to the background result. Idempotent per run + status, so an\n * exactly-once finish — or a soft give-up followed by a real completion —\n * never injects a duplicate, while a give-up and a later real completion are\n * surfaced as two distinct turns.\n */\n async _cfDetachedNotifyFinish(\n run: AgentToolRunInfo,\n result: AgentToolLifecycleResult\n ): Promise<void> {\n const text = this.formatDetachedCompletion(run, result);\n if (!text) return;\n await this.submitMessages(\n [\n {\n id: crypto.randomUUID(),\n role: \"user\",\n parts: [{ type: \"text\", text }]\n }\n ],\n {\n idempotencyKey: `detached-finish:${run.runId}:${result.status}`,\n metadata: {\n source: run.notifySource ?? \"detached-agent-tool\",\n runId: run.runId,\n agentType: run.agentType,\n status: result.status\n }\n }\n );\n }\n\n /**\n * Format the synthetic message injected when a `detached: { onMilestones }`\n * milestone is reached. Override to customize the prose (or return an empty\n * string to suppress a given milestone). The default announces the milestone\n * name and any structured data so the model can react in-conversation before\n * the run finishes.\n */\n protected formatDetachedMilestone(\n run: AgentToolRunInfo,\n milestone: AgentToolMilestone\n ): string {\n const label = `Background task \"${run.agentType}\" (run ${run.runId})`;\n const detail =\n milestone.data !== undefined\n ? `\\n\\n${JSON.stringify(milestone.data, null, 2)}`\n : \"\";\n return `${label} reached milestone \"${milestone.name}\".${detail}`;\n }\n\n /**\n * Targeted milestone hook for `detached: { onMilestones }`. Idempotent per run\n * + milestone NAME (not sequence — a name surfaces at most once even if\n * re-emitted), so the warm tail and the backbone reconcile converge. Fired\n * from both paths.\n *\n * - `\"narrate\"` (default): a synthetic **assistant** message injected directly\n * — no model turn — using a deterministic message id for idempotency\n * (`addMessages` is a no-op for an id already in history).\n * - `\"react\"`: a **user-role** turn so the model responds to the milestone\n * (idempotency via `submitMessages` + UNIQUE idempotency key).\n */\n protected override async _deliverDetachedMilestone(\n run: AgentToolRunInfo,\n milestone: AgentToolMilestone,\n mode: \"react\" | \"narrate\"\n ): Promise<void> {\n const text = this.formatDetachedMilestone(run, milestone);\n if (!text) return;\n const metadata = {\n source: run.notifySource ?? \"detached-agent-tool\",\n runId: run.runId,\n agentType: run.agentType,\n milestone: milestone.name\n };\n if (mode === \"narrate\") {\n await this.addMessages([\n {\n id: `detached-ms:${run.runId}:${milestone.name}`,\n role: \"assistant\",\n parts: [{ type: \"text\", text }],\n metadata\n }\n ]);\n return;\n }\n await this.submitMessages(\n [\n {\n id: crypto.randomUUID(),\n role: \"user\",\n parts: [{ type: \"text\", text }]\n }\n ],\n { idempotencyKey: `detached-ms:${run.runId}:${milestone.name}`, metadata }\n );\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 // Bind the run to its turn's request id BEFORE the turn starts —\n // in memory for live frame attribution in `broadcast`, and on the\n // child-run row so attribution survives a DO restart mid-run\n // (#1575). `saveMessages` would generate the id internally, so call\n // the inner turn runner with a pre-generated one instead.\n const requestId = crypto.randomUUID();\n this._agentToolRunsByRequestId.set(requestId, options.runId);\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET request_id = ${requestId}\n WHERE run_id = ${options.runId}\n `;\n const result = await this._runProgrammaticMessagesTurn(\n requestId,\n [this.formatAgentToolInput(input)],\n {\n signal: controller.signal,\n trigger: \"agent-tool\"\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 // Drop the progress emitter's per-run coalescing state.\n this._agentToolProgressEmitterInstance?.forget(options.runId);\n // Drop this run's request-id mappings. When no runs remain in flight\n // clear the whole map, so negatively-cached (null) entries for\n // unrelated turns can't accumulate for the DO's lifetime — the map is\n // only consulted while a run is active (#1575).\n if (this._agentToolAbortControllers.size === 0) {\n this._agentToolRunsByRequestId.clear();\n } else {\n for (const [reqId, runId] of this._agentToolRunsByRequestId) {\n if (runId === options.runId) {\n this._agentToolRunsByRequestId.delete(reqId);\n }\n }\n }\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 // Stop the original in-isolate run if it's still live...\n this._agentToolAbortControllers.get(runId)?.abort(reason);\n // ...and any in-flight chat-recovery turn driving this child facet after an\n // eviction. A recovered turn re-runs via `_chatRecoveryContinue` outside\n // `startAgentToolRun`, so it has no entry in `_agentToolAbortControllers`; a\n // child facet is dedicated to a single agent-tool run, so aborting its\n // active submissions tears the recovery down instead of letting it keep\n // grinding (and holding a fiber / keep-alive) after the parent gave up on\n // it and sealed `interrupted` (#1630 follow-up).\n for (const controller of this._submissionAbortControllers.values()) {\n controller.abort(reason);\n }\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 // Release any parent live-tail so it stops waiting on this run immediately.\n this._finalizeAgentToolChildRunTailers(runId);\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 _classifyAgentToolChildRecovery(): Promise<\n \"in-progress\" | \"failed\" | \"none\"\n > {\n return classifyAgentToolChildRecovery(this.ctx.storage);\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 /**\n * Eagerly terminalize this child facet's OWN agent-tool run row(s) once a\n * recovered turn has settled. A recovered turn re-runs via either\n * `_chatRecoveryContinue` → `continueLastTurn` or, for a pre-stream eviction,\n * `_chatRecoveryRetry` (a fresh user turn) — neither flows through\n * `startAgentToolRun`'s finalizer, so without this the run row strands\n * `running` and its tailers stay open until a parent inspect lazily\n * reconciles it — forcing a re-attached parent to wait out a full no-progress\n * window before collecting an already-finished result (#1630 follow-up).\n * Reconciling here closes the tail promptly so the parent collects the\n * terminal immediately. No-op on non-child facets (their\n * `cf_agent_tool_child_runs` table is empty) and on rows whose in-memory run\n * is still live (those are finalized by `startAgentToolRun`); the underlying\n * reconcile leaves a row `running` while its recovery is still in progress.\n */\n private async _reconcileOwnStaleAgentToolChildRuns(): Promise<void> {\n let rows: Array<{ run_id: string }>;\n try {\n rows = this.sql<{ run_id: string }>`\n SELECT run_id FROM cf_agent_tool_child_runs\n WHERE completed_at IS NULL\n `;\n } catch {\n // No child-run table on this facet (it never ran as a child) — nothing\n // to reconcile.\n return;\n }\n for (const { run_id } of rows) {\n if (this._agentToolAbortControllers.has(run_id)) continue;\n try {\n await this._reconcileStaleAgentToolChildRun(run_id);\n } catch {\n // Best-effort: a parent inspect still reconciles lazily.\n }\n }\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 const set = self._agentToolForwarders.get(runId);\n set?.delete(forward);\n // Drop the now-empty set so the broadcast idle-guard\n // (`_agentToolForwarders.size`) goes cold again. Otherwise a run that\n // was already terminal at attach — its `_finalizeAgentToolChildRunTailers`\n // already ran and won't run again — leaves an empty set keyed by runId,\n // and every subsequent broadcast on this DO keeps paying the\n // `interceptAgentToolBroadcast` cost forever.\n if (set && set.size === 0) self._agentToolForwarders.delete(runId);\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 // Stored chunk_index and the live forwarder sequence share one\n // monotonic numbering (see `getAgentToolChunks` + the broadcast snoop),\n // so a single high-water mark dedupes the stored-replay → live-\n // forwarding handoff: a chunk that lands in both the drained backlog AND\n // the live buffer (stored + broadcast during the drain) is emitted\n // exactly once, in order.\n let lastEmitted = options?.afterSequence ?? -1;\n const emit = (chunk: AgentToolStoredChunk) => {\n if (closed || chunk.sequence <= lastEmitted) return;\n lastEmitted = chunk.sequence;\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\n // While draining the stored backlog, park live chunks rather than\n // emitting them directly, so ordering/dedupe against the backlog is\n // resolved by `emit` while the forwarder (registered FIRST, below)\n // already catches everything the child produces.\n let draining = true;\n const pending: AgentToolStoredChunk[] = [];\n forward = (chunk: AgentToolStoredChunk) => {\n if (closed) return;\n if (draining) {\n pending.push(chunk);\n return;\n }\n emit(chunk);\n };\n\n // Register the live forwarder BEFORE draining the stored backlog.\n // Previously it was attached only AFTER `getAgentToolChunks` resolved;\n // any chunk the child stored AND broadcast during that `await` advanced\n // the live sequence with no forwarder attached, so it was neither in the\n // drained snapshot nor live-forwarded — silently dropped from the\n // parent's forward stream. A network-paced proxied child stream (a sub-\n // agent returning a remote `toUIMessageStreamResponse()`) hits this\n // window constantly, leaving tool parts stuck at `input-available`\n // (#1589).\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 try {\n const replayed = await self.getAgentToolChunks(runId, options);\n for (const chunk of replayed) {\n if (closed) return;\n emit(chunk);\n }\n\n // Flush chunks that arrived live during the drain, then switch the\n // forwarder to direct emit. No `await` between here and the drain loop\n // means no live chunk can slip past this handoff.\n draining = false;\n for (const chunk of pending) emit(chunk);\n pending.length = 0;\n\n const row = self._readAgentToolChildRun(runId);\n if (!row || row.completed_at !== null) {\n close();\n return;\n }\n\n // Run is still live: realign the live sequence to continue right after\n // the highest emitted chunk (which now includes any captured during the\n // drain). Realigning to `lastEmitted + 1` rather than the backlog's last\n // sequence keeps a post-restart re-attach — where the in-memory counter\n // is cold — from colliding with already-emitted chunks. Gating on the\n // terminal check above also avoids repopulating `_agentToolLiveSequences`\n // for an already-terminal run, which would re-heat the broadcast\n // idle-guard for the DO's lifetime.\n if (lastEmitted > (options?.afterSequence ?? -1)) {\n self._agentToolLiveSequences.set(runId, lastEmitted + 1);\n }\n } catch (error) {\n // A drain/read failure must surface to the consumer; detach first so\n // the forwarder we registered up front doesn't linger on this run.\n closed = true;\n detach();\n try {\n controller.error(error);\n } catch {\n // Stream already torn down.\n }\n }\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 // ── Action ledger ────────────────────────────────────────────────\n\n private _ensureActionLedgerTable(): void {\n if (this._actionLedgerTableEnsured) return;\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_think_action_ledger (\n key TEXT PRIMARY KEY,\n action_name TEXT NOT NULL,\n request_id TEXT,\n tool_call_id TEXT,\n input_hash TEXT NOT NULL,\n status TEXT NOT NULL,\n result_json TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL\n )\n `;\n this.sql`\n CREATE INDEX IF NOT EXISTS cf_think_action_ledger_sweep\n ON cf_think_action_ledger (status, updated_at)\n `;\n this._actionLedgerTableEnsured = true;\n }\n\n private _readActionLedgerRow(key: string): ActionLedgerRow | null {\n this._ensureActionLedgerTable();\n const rows = this.sql<ActionLedgerRow>`\n SELECT key, action_name, request_id, tool_call_id, input_hash, status,\n result_json, created_at, updated_at\n FROM cf_think_action_ledger\n WHERE key = ${key}\n LIMIT 1\n `;\n return rows[0] ?? null;\n }\n\n /**\n * Claim a ledger key for execution. Read-then-write with no `await` between\n * the read and any write, so within the single DO isolate two claims cannot\n * interleave — the same race-free idiom documented on\n * {@link _claimActionPendingRow}. The only way a durable `pending` row\n * outlives its writer is a crashed prior isolate, which has no live writer to\n * race; that is the row a stale reclaim safely re-runs.\n */\n private _claimActionLedgerRow(options: {\n key: string;\n actionName: string;\n requestId: string;\n toolCallId: string;\n inputHash: string;\n retryablePending: boolean;\n leaseMs: number | false;\n now?: number;\n }): ActionLedgerClaim {\n this._ensureActionLedgerTable();\n const now = options.now ?? Date.now();\n const existing = this._readActionLedgerRow(options.key);\n if (existing) {\n if (\n existing.action_name !== options.actionName ||\n existing.input_hash !== options.inputHash\n ) {\n return { outcome: \"conflict\", row: existing };\n }\n if (existing.status === \"settled\") {\n return { outcome: \"replay\", row: existing };\n }\n // `pending` from here. Reclaim only an explicit-key row whose lease has\n // expired; fresh rows, fallback keys, and a disabled lease still block.\n const stale =\n options.retryablePending &&\n options.leaseMs !== false &&\n now - existing.updated_at > options.leaseMs;\n if (!stale) {\n return { outcome: \"pending\", row: existing };\n }\n this.sql`\n UPDATE cf_think_action_ledger\n SET request_id = ${options.requestId || null},\n tool_call_id = ${options.toolCallId || null},\n updated_at = ${now}\n WHERE key = ${options.key} AND status = ${\"pending\"}\n `;\n return { outcome: \"reclaimed\", row: existing };\n }\n\n this.sql`\n INSERT INTO cf_think_action_ledger (\n key, action_name, request_id, tool_call_id, input_hash, status,\n result_json, created_at, updated_at\n )\n VALUES (\n ${options.key}, ${options.actionName}, ${options.requestId || null},\n ${options.toolCallId || null}, ${options.inputHash}, ${\"pending\"},\n ${null}, ${now}, ${now}\n )\n `;\n return { outcome: \"claimed\" };\n }\n\n private _settleActionLedgerRow(key: string, resultJson: string): void {\n this._ensureActionLedgerTable();\n this.sql`\n UPDATE cf_think_action_ledger\n SET status = ${\"settled\"},\n result_json = ${resultJson},\n updated_at = ${Date.now()}\n WHERE key = ${key}\n `;\n }\n\n private _releaseActionLedgerRow(key: string): void {\n this._ensureActionLedgerTable();\n this.sql`\n DELETE FROM cf_think_action_ledger\n WHERE key = ${key}\n `;\n }\n\n private async _resolveActionLedgerKey(\n actionName: string,\n spec: ActionIdempotencyKey<unknown> | undefined,\n input: unknown,\n ctx: ActionContext\n ): Promise<string | null> {\n if (spec !== undefined) {\n const key =\n typeof spec === \"function\" ? await spec({ input, ctx }) : spec;\n if (key.length === 0) {\n throw new Error(\n `Action \"${actionName}\" returned an empty idempotency key`\n );\n }\n return `action:${actionName}:${key}`;\n }\n return ctx.toolCallId ? `tool:${ctx.toolCallId}` : null;\n }\n\n private _actionInputHash(input: unknown): string {\n return stableHash(input);\n }\n\n private _actionLedgerRetentionForStatus(\n status: ActionLedgerSweepStatus\n ): number | false {\n return status === \"settled\"\n ? this.actionLedgerRetention.settledMs\n : this.actionLedgerRetention.pendingMs;\n }\n\n private _deleteActionLedgerRows(keys: string[]): number {\n let deleted = 0;\n for (let i = 0; i < keys.length; i += MAX_BOUND_PARAMS) {\n const batch = keys.slice(i, i + MAX_BOUND_PARAMS);\n const strings = buildInClauseStrings(\n \"DELETE FROM cf_think_action_ledger WHERE key IN \",\n batch.length\n );\n this.sql(strings, ...batch);\n deleted += batch.length;\n }\n return deleted;\n }\n\n private _sweepActionLedgerStatus(\n status: ActionLedgerSweepStatus,\n now: number,\n limit: number\n ): number {\n const retentionMs = this._actionLedgerRetentionForStatus(status);\n if (retentionMs === false || limit <= 0) return 0;\n const cutoff = now - retentionMs;\n const rows = this.sql<{ key: string }>`\n SELECT key\n FROM cf_think_action_ledger\n WHERE status = ${status}\n AND updated_at < ${cutoff}\n ORDER BY updated_at ASC\n LIMIT ${limit}\n `;\n return this._deleteActionLedgerRows(rows.map((row) => row.key));\n }\n\n private async _sweepActionLedger(options?: {\n force?: boolean;\n }): Promise<{ settled: number; pending: number }> {\n this._ensureActionLedgerTable();\n const now = Date.now();\n if (!options?.force) {\n const lastSwept =\n (await this.ctx.storage.get<number>(ACTION_LEDGER_LAST_SWEPT_KEY)) ?? 0;\n if (now - lastSwept < ACTION_LEDGER_SWEEP_INTERVAL_MS) {\n return { settled: 0, pending: 0 };\n }\n }\n\n const maxSweepRows = Math.max(\n 0,\n Math.floor(this.actionLedgerRetention.maxSweepRows)\n );\n const settled = this._sweepActionLedgerStatus(\"settled\", now, maxSweepRows);\n const pending = this._sweepActionLedgerStatus(\n \"pending\",\n now,\n Math.max(0, maxSweepRows - settled)\n );\n await this.ctx.storage.put(ACTION_LEDGER_LAST_SWEPT_KEY, now);\n this._emitActionLedgerEvent({\n type: \"action:ledger:swept\",\n payload: { settled, pending }\n });\n return { settled, pending };\n }\n\n // ── Durable-pause action approvals ──────────────────────────────\n\n private _emitActionReplyEvent(event: ActionReplyEvent): void {\n const emit = this._emit as unknown as (\n type: string,\n payload: Record<string, unknown>\n ) => void;\n emit.call(this, event.type, event.payload);\n }\n\n /**\n * Record an advisory reply attachment for the active turn. Advisory: a\n * non-object, a missing/non-string `type`, or exceeding the per-turn cap is\n * silently ignored. The attachment is JSON-normalized to a safe copy so a\n * later mutation of the caller's object can't corrupt it and downstream\n * persistence/RPC can't choke on bigint/circular values.\n */\n private _recordReplyAttachment(\n requestId: string,\n attachment: unknown,\n actionName?: string\n ): void {\n if (!requestId || requestId !== this._activeTurnReplyAttachmentsRequestId) {\n return;\n }\n if (\n typeof attachment !== \"object\" ||\n attachment === null ||\n Array.isArray(attachment) ||\n typeof (attachment as { type?: unknown }).type !== \"string\"\n ) {\n return;\n }\n if (\n this._activeTurnReplyAttachments.length >= MAX_REPLY_ATTACHMENTS_PER_TURN\n ) {\n return;\n }\n const serialized = safeStringifyActionOutput(attachment);\n if (serialized.error || serialized.value === undefined) {\n return;\n }\n const normalized = JSON.parse(serialized.value) as unknown;\n if (\n typeof normalized !== \"object\" ||\n normalized === null ||\n Array.isArray(normalized) ||\n typeof (normalized as { type?: unknown }).type !== \"string\"\n ) {\n return;\n }\n this._activeTurnReplyAttachments.push(normalized as ReplyAttachment);\n this._emitActionReplyEvent({\n type: \"action:reply-attached\",\n payload: {\n ...(actionName !== undefined && { action: actionName }),\n attachmentType: (normalized as { type: string }).type\n }\n });\n }\n\n private _cloneReplyAttachment(attachment: ReplyAttachment): ReplyAttachment {\n return JSON.parse(JSON.stringify(attachment)) as ReplyAttachment;\n }\n\n /**\n * Advisory reply attachments recorded during a turn via `ctx.attachReply`.\n * Returns deep copies. With no `requestId`, returns the most recent turn's\n * attachments; with a `requestId`, returns them only if they belong to that\n * turn (else `[]`).\n */\n replyAttachments(requestId?: string): ReplyAttachment[] {\n if (\n requestId !== undefined &&\n requestId !== this._activeTurnReplyAttachmentsRequestId\n ) {\n return [];\n }\n return this._activeTurnReplyAttachments.map((attachment) =>\n this._cloneReplyAttachment(attachment)\n );\n }\n\n private _emitActionPauseEvent(event: ActionPauseEvent): void {\n const emit = this._emit as unknown as (\n type: string,\n payload: Record<string, unknown>\n ) => void;\n emit.call(this, event.type, event.payload);\n }\n\n private _ensureActionPendingTable(): void {\n if (this._actionPendingTableEnsured) return;\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_think_action_pending_approvals (\n execution_id TEXT PRIMARY KEY,\n action_name TEXT NOT NULL,\n tool_call_id TEXT NOT NULL,\n request_id TEXT,\n input_json TEXT NOT NULL,\n descriptor_json TEXT,\n created_at INTEGER NOT NULL\n )\n `;\n this.sql`\n CREATE INDEX IF NOT EXISTS cf_think_action_pending_created\n ON cf_think_action_pending_approvals (created_at)\n `;\n this._actionPendingTableEnsured = true;\n }\n\n private _readActionPendingRow(executionId: string): ActionPendingRow | null {\n this._ensureActionPendingTable();\n const rows = this.sql<ActionPendingRow>`\n SELECT execution_id, action_name, tool_call_id, request_id, input_json,\n descriptor_json, created_at\n FROM cf_think_action_pending_approvals\n WHERE execution_id = ${executionId}\n LIMIT 1\n `;\n return rows[0] ?? null;\n }\n\n private _insertActionPendingRow(row: ActionPendingRow): void {\n this._ensureActionPendingTable();\n this.sql`\n INSERT INTO cf_think_action_pending_approvals (\n execution_id, action_name, tool_call_id, request_id, input_json,\n descriptor_json, created_at\n )\n VALUES (\n ${row.execution_id}, ${row.action_name}, ${row.tool_call_id},\n ${row.request_id}, ${row.input_json}, ${row.descriptor_json},\n ${row.created_at}\n )\n `;\n }\n\n /**\n * Atomically claim a pending-approval row for resolution: read it, then\n * delete it. SQLite calls are synchronous and there is no `await` between the\n * read and the delete, so within the single DO isolate this is race-free — a\n * concurrent `approveExecution`/`rejectExecution` for the same id can only run\n * at an await boundary, by which point the row is already gone (it sees\n * `null` → \"already resolved\"). The returned row is the caller's to resolve.\n */\n private _claimActionPendingRow(executionId: string): ActionPendingRow | null {\n this._ensureActionPendingTable();\n const row = this._readActionPendingRow(executionId);\n if (!row) return null;\n this.sql`\n DELETE FROM cf_think_action_pending_approvals\n WHERE execution_id = ${executionId}\n `;\n return row;\n }\n\n private _listActionPendingRows(): ActionPendingRow[] {\n this._ensureActionPendingTable();\n return this.sql<ActionPendingRow>`\n SELECT execution_id, action_name, tool_call_id, request_id, input_json,\n descriptor_json, created_at\n FROM cf_think_action_pending_approvals\n ORDER BY created_at ASC\n `;\n }\n\n private _deleteActionPendingRows(executionIds: string[]): number {\n let deleted = 0;\n for (let i = 0; i < executionIds.length; i += MAX_BOUND_PARAMS) {\n const batch = executionIds.slice(i, i + MAX_BOUND_PARAMS);\n const strings = buildInClauseStrings(\n \"DELETE FROM cf_think_action_pending_approvals WHERE execution_id IN \",\n batch.length\n );\n this.sql(strings, ...batch);\n deleted += batch.length;\n }\n return deleted;\n }\n\n private async _sweepActionPendingApprovals(options?: {\n force?: boolean;\n }): Promise<{ swept: number }> {\n this._ensureActionPendingTable();\n const ttl = this.actionPendingApprovalTtlMs;\n if (ttl === false) return { swept: 0 };\n const now = Date.now();\n if (!options?.force) {\n const lastSwept =\n (await this.ctx.storage.get<number>(ACTION_PENDING_LAST_SWEPT_KEY)) ??\n 0;\n if (now - lastSwept < ACTION_PENDING_SWEEP_INTERVAL_MS) {\n return { swept: 0 };\n }\n }\n const cutoff = now - ttl;\n const rows = this.sql<{ execution_id: string }>`\n SELECT execution_id\n FROM cf_think_action_pending_approvals\n WHERE created_at < ${cutoff}\n ORDER BY created_at ASC\n LIMIT 500\n `;\n const swept = this._deleteActionPendingRows(\n rows.map((row) => row.execution_id)\n );\n await this.ctx.storage.put(ACTION_PENDING_LAST_SWEPT_KEY, now);\n if (swept > 0) {\n this._emitActionPauseEvent({\n type: \"action:pause:swept\",\n payload: { swept }\n });\n }\n return { swept };\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(messages.map((message) => this._rowSafe(message)));\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 console.error(\"[Think] Submission failed\", {\n submissionId: inspection.submissionId,\n requestId: inspection.requestId,\n idempotencyKey: inspection.idempotencyKey,\n metadata: inspection.metadata,\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 if (!this._hasPendingWorkflowNotifications()) return;\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 const idsToDelete = rows\n .filter((row) => this._isTerminalSubmissionStatus(row.status))\n .map((row) => row.submission_id);\n\n // Batch deletes into `IN (...)` queries within the SQLite 100\n // bound-parameter limit to minimize round-trips during cleanup.\n let deleted = 0;\n for (let i = 0; i < idsToDelete.length; i += MAX_BOUND_PARAMS) {\n const batch = idsToDelete.slice(i, i + MAX_BOUND_PARAMS);\n const strings = buildInClauseStrings(\n \"DELETE FROM cf_think_submissions WHERE status IN ('completed', 'aborted', 'skipped', 'error') AND submission_id IN \",\n batch.length\n );\n this.sql(strings, ...batch);\n deleted += batch.length;\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 // Persist the channel on the user messages so the drained turn re-resolves\n // it from history (the model turn runs later in the submission drain).\n messages = this._stampChannel(messages, options?.channel);\n return this._admitTurn({\n admission: \"submit\",\n trigger: \"submission\",\n execute: async () => {\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 }\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\n return {\n ...this._inspectionFromSubmissionRow(row),\n accepted: true\n };\n }\n });\n }\n\n private async _scheduleSubmissionDrain(): Promise<void> {\n await this.schedule(0, \"_drainThinkSubmissions\", undefined, {\n idempotent: true\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 await this._admitTurn({\n admission: \"execute-submission\",\n trigger: \"submission\",\n execute: () => this._executeSubmission(row)\n });\n }\n\n private async _executeSubmission(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 trigger: \"submission\",\n captureProgrammaticStreamError: true,\n captureOutput: Boolean(workflowPrompt?.output),\n // The alarm-owned drain can inherit the ALS of a turn\n // that called `submitMessages` mid-turn (e.g. a detached-finish notify\n // from a `beforeTurn` hook). `allowNested` skips the\n // not-inside-active-turn guard for that case. Safe on every submission\n // path: nothing holding the turn queue ever awaits this turn, so the\n // queued submission simply runs once the parent turn frees the slot —\n // no deadlock, no need to scope this to detached notify.\n allowNested: true,\n workflowPrompt: workflowPrompt ?? undefined,\n shouldApplyMessages: () =>\n this._readSubmission(row.submission_id)?.status === \"running\",\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 const finalized = this._readSubmission(row.submission_id);\n if (finalized && this._isTerminalSubmissionStatus(finalized.status)) {\n this._insertWorkflowNotification(\n this._inspectionFromSubmissionRow(finalized),\n output\n );\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 const finalized = this._readSubmission(row.submission_id);\n if (finalized && this._isTerminalSubmissionStatus(finalized.status)) {\n this._insertWorkflowNotification(\n this._inspectionFromSubmissionRow(finalized)\n );\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 /**\n * Add messages to history WITHOUT starting a model turn.\n *\n * Distinct from {@link Think.saveMessages} (which runs a turn) and from\n * AIChatAgent's `persistMessages()` (which replaces/reconciles a flat array):\n * `addMessages` appends or upserts into the Session tree and never enqueues a\n * turn. Because it bypasses the turn queue, it never deadlocks — including\n * when called from inside a tool `execute` during an active turn.\n *\n * Array entries are appended **linearly**: the first attaches under the\n * resolved parent (the latest committed leaf by default, or `parentId`), and\n * each subsequent message attaches under the previous one, so imported history\n * stays a single path rather than a fan-out of siblings. Appends are\n * idempotent by message id; pass `{ mode: \"upsert\" }` to update an existing\n * message in place instead (upsert never re-parents). Any role may be written;\n * an `assistant` message added this way is inert transcript data (it does not\n * mark a completed turn or trigger auto-continuation).\n *\n * The live message cache stays coherent automatically (the Session keeps it\n * in sync on every write, branches included). Broadcast behaviour depends on\n * whether a turn is running:\n *\n * - **Out of a turn** (the supported pattern — \"add context, then run a\n * turn\"): the new messages are broadcast to connected clients immediately\n * (unless `broadcast: false`).\n * - **Inside a turn** (e.g. from a tool `execute`): no broadcast is sent, so a\n * full snapshot can't clobber the in-progress streamed message; the injected\n * messages ride along on the turn's next broadcast. The write is still\n * durable and visible to the running turn's next sync.\n */\n async addMessages(\n messages:\n | UIMessage[]\n | ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>),\n options?: AddMessagesOptions\n ): Promise<void> {\n const resolved =\n typeof messages === \"function\" ? await messages(this.messages) : messages;\n if (resolved.length === 0) return;\n\n const mode = options?.mode ?? \"append\";\n\n // Validate an explicit parentId up front. The Session provider silently\n // falls back to the root for an unknown parent; fail fast instead so a\n // typo'd id surfaces as an error rather than a misattached message.\n if (typeof options?.parentId === \"string\") {\n const parent = await this.session.getMessage(options.parentId);\n if (!parent) {\n throw new Error(\n `addMessages: parentId \"${options.parentId}\" does not exist in this session`\n );\n }\n }\n\n let parentId = options?.parentId;\n for (const message of resolved) {\n const existing = await this.session.getMessage(message.id);\n if (existing) {\n // Append mode is idempotent by id (existing id → no-op); upsert updates\n // the content in place. Neither path re-parents an existing message.\n if (mode === \"upsert\") await this._updateMessageInHistory(message);\n parentId = message.id;\n } else {\n const stored = await this._appendMessageToHistory(message, parentId);\n parentId = stored.id;\n }\n }\n\n // The live cache is kept coherent automatically by the Session change\n // listener wired in `onStart` (`internal_onMessagesChanged`), which handles\n // both linear appends and branches (an explicit `parentId` triggers a full\n // resync). So `addMessages` only owns the broadcast — and suppresses it\n // mid-turn: pushing a full `MSG_CHAT_MESSAGES` snapshot while a turn streams\n // would clobber the in-progress assistant message on connected clients (the\n // same reason the streaming path defers its snapshot). The injected messages\n // ride along on the turn's next broadcast.\n if (this._insideInferenceLoop) return;\n if (options?.broadcast !== false) {\n this._broadcastMessages();\n }\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 shouldApplyMessages?: () => boolean | Promise<boolean>;\n allowNested?: boolean;\n trigger?: TurnTrigger;\n channel?: string;\n }\n ): Promise<ProgrammaticMessagesResult> {\n const clientTools = this._lastClientTools;\n const body = options?.body ?? this._lastBody;\n const epoch = this._turnQueue.generation;\n // Explicit channel wins; otherwise re-resolve from persisted user-message\n // metadata (covers the submission drain replaying stamped messages).\n const channel =\n options?.channel ??\n (Array.isArray(messages)\n ? this._channelFromMessages(messages)\n : undefined);\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n let error: string | undefined;\n let output: unknown;\n let wasAborted = false;\n\n await this._admitTurn({\n admission: \"queue\",\n trigger: options?.trigger ?? \"programmatic\",\n requestId,\n continuation: false,\n allowNested: options?.allowNested,\n channel,\n getStatus: () => status,\n execute: async () => {\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n if (\n options?.shouldApplyMessages &&\n !(await options.shouldApplyMessages())\n ) {\n status = \"aborted\";\n return;\n }\n\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 if (\n options?.shouldApplyMessages &&\n !(await options.shouldApplyMessages())\n ) {\n status = \"aborted\";\n return;\n }\n\n for (const msg of this._stampChannel(resolved, channel)) {\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 // Bounded compact-and-retry loop (opt-in via\n // `contextOverflow.reactive`), mirroring the WebSocket and chat()\n // paths so programmatic turns (saveMessages / submitMessages /\n // scheduled prompts) recover from a mid-turn overflow too. Each\n // attempt re-runs the same turn (`continuation: false`).\n for (let attempt = 0; ; attempt++) {\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) return;\n\n let overflowError: string | undefined;\n let overflowRequested = false;\n const overflowRecovery = this._overflowReactiveEnabled\n ? {\n onRetry: (err?: string) => {\n overflowRequested = true;\n overflowError = err;\n }\n }\n : undefined;\n\n const streamResult = await this._streamResult(\n requestId,\n result,\n abortSignal,\n {\n captureProgrammaticStreamError:\n options?.captureProgrammaticStreamError,\n captureOutput: options?.captureOutput,\n overflowRecovery\n }\n );\n\n if (overflowRequested) {\n if (\n attempt < this._overflowMaxRetries &&\n !abortSignal?.aborted\n ) {\n const shortened = await this._compactForContextOverflow(\n \"reactive\",\n { requestId, attempt: attempt + 1 }\n );\n if (shortened) continue;\n }\n // Budget spent, aborted, or compaction no-op: surface terminally\n // through onChatError (classified). The caller reads status/error.\n error = this._finalizeContextOverflowError(\n requestId,\n overflowError\n );\n status = \"error\";\n return;\n }\n\n status = streamResult.status;\n error = streamResult.error;\n output = streamResult.output;\n return;\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 & { trigger?: TurnTrigger; channel?: string }\n ): Promise<SaveMessagesResult> {\n const trigger = options?.trigger ?? \"programmatic\";\n this._assertNotInsideAdmittedTurn(trigger);\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 // If this facet is itself an agent-tool child being recovered, re-bind its\n // run row to this turn's request id so the parent's re-attach tail keeps\n // attributing the continued turn's frames (no-op otherwise).\n this._rebindAgentToolChildRunRequestId(requestId);\n const clientTools = this._lastClientTools;\n const resolvedBody = body ?? this._lastBody;\n const epoch = this._turnQueue.generation;\n // Re-resolve the channel from durable history so a continued/recovered turn\n // re-applies per-channel policy.\n const channel = options?.channel ?? this._channelFromLatestUserMessage();\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n let error: string | undefined;\n let wasAborted = false;\n\n await this._admitTurn({\n admission: \"queue\",\n trigger,\n requestId,\n continuation: true,\n channel,\n getStatus: () => status,\n execute: 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 & { trigger?: TurnTrigger; channel?: string }\n ): Promise<SaveMessagesResult> {\n const trigger = options?.trigger ?? \"recovery-retry\";\n this._assertNotInsideAdmittedTurn(trigger);\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 // If this facet is itself an agent-tool child being recovered, re-bind its\n // run row to this turn's request id so the parent's re-attach tail keeps\n // attributing the retried turn's frames (no-op otherwise).\n this._rebindAgentToolChildRunRequestId(requestId);\n const epoch = this._turnQueue.generation;\n // Re-resolve the channel from the persisted user message so a recovered\n // retry re-applies per-channel policy, exactly like `continueLastTurn`. The\n // `metadata.channel` stamp survives the interruption; without this the\n // retried turn would silently fall back to the default policy.\n const channel = options?.channel ?? this._channelFromLatestUserMessage();\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n let error: string | undefined;\n let wasAborted = false;\n\n await this._admitTurn({\n admission: \"queue\",\n trigger,\n requestId,\n continuation: false,\n channel,\n getStatus: () => status,\n execute: 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 // No active stream. If a turn is accepted but its stream hasn't started\n // yet (#1784), park this connection and tell it to keep waiting (`park`\n // sends the keep-waiting frame; no-op otherwise). Either way send the\n // idle-connect transcript so the client renders the user message it\n // just submitted while it waits for the stream to begin.\n this._preStream.park(connection);\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 this._preStream.release(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 if (event.type === \"chat-request\") {\n await withAgentSpan(\n this,\n \"chat_interaction\",\n \"interaction\",\n {\n \"cloudflare.agents.component\": \"think\",\n \"cloudflare.agents.turn.request_id\": event.id\n },\n () => this._handleProtocolEvent(connection, event)\n );\n } else {\n await this._handleProtocolEvent(connection, event);\n }\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 await this._handleStreamResumeRequest(connection, event.probeId);\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 if (!this._loggedProtocolWarnings.has(\"client-pushed-messages\")) {\n this._loggedProtocolWarnings.add(\"client-pushed-messages\");\n console.warn(\n \"[think] Ignoring client-pushed chat messages; Think is \" +\n \"server-authoritative and does not persist flat transcript \" +\n \"overwrites. Use @cloudflare/think/react so setMessages stays \" +\n \"local-only, and use clearHistory() for persisted clears.\"\n );\n }\n break;\n }\n }\n\n private async _handleStreamResumeRequest(\n connection: Connection,\n probeId?: string\n ): Promise<void> {\n await this._resumeHandshake().handleResumeRequest(connection, probeId);\n }\n\n private async _handleStreamResumeAck(\n connection: Connection,\n requestId: string\n ): Promise<void> {\n await this._resumeHandshake().handleResumeAck(connection, requestId);\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 // A genuinely-new turn supersedes any pending terminal record (#1645) so a\n // stale exhaustion can't replay over the resume handshake to a client that\n // reconnects in the window between accepting this submit and the new turn\n // streaming. Mirrors `@cloudflare/ai-chat`; without it a reconnect in that\n // gap would surface the previous failed turn's error even though the user\n // has already moved on. Completion clears it too, but only once the turn\n // resolves — which leaves the gap open.\n await withAgentSpan(\n this,\n \"clear_previous_chat_state\",\n \"interaction\",\n {\n \"cloudflare.agents.component\": \"think\",\n \"cloudflare.agents.turn.request_id\": requestId,\n \"cloudflare.agents.turn.trigger\": \"ws-chat\"\n },\n () => this._clearChatTerminal()\n );\n\n // Mark this turn as accepted-but-not-yet-streamed (#1784) so a client that\n // reconnects/re-mounts before the stream starts is parked and told to keep\n // waiting (see _resumeHandshake / onConnect), then flushed into\n // STREAM_RESUMING on _startResumableStream or released on settle.\n this._preStream.begin(requestId);\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 const requestBody =\n Object.keys(customBody).length > 0 ? customBody : undefined;\n withAgentSpan(\n this,\n \"persist_chat_request_context\",\n \"interaction\",\n {\n \"cloudflare.agents.component\": \"think\",\n \"cloudflare.agents.turn.request_id\": requestId,\n \"cloudflare.agents.turn.trigger\": \"ws-chat\"\n },\n () => {\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 this._lastBody = requestBody;\n this._persistBody();\n }\n );\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 withAgentSpan(\n this,\n \"load_chat_history\",\n \"interaction\",\n {\n \"cloudflare.agents.component\": \"think\",\n \"cloudflare.agents.turn.request_id\": requestId,\n \"cloudflare.agents.turn.trigger\": \"ws-chat\"\n },\n () => this._readMessagesFromStorage()\n );\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 const persisted = await withAgentSpan(\n this,\n \"persist_incoming_messages\",\n \"interaction\",\n {\n \"cloudflare.agents.component\": \"think\",\n \"cloudflare.agents.turn.request_id\": requestId,\n \"cloudflare.agents.turn.trigger\": \"ws-chat\"\n },\n async () => {\n if (this._turnQueue.generation !== epoch) return false;\n\n for (const msg of reconciled) {\n if (this._turnQueue.generation !== epoch) return false;\n await this._persistIncomingMessage(msg, serverMessages);\n }\n\n if (this._turnQueue.generation !== epoch) return false;\n await this._syncMessages();\n return true;\n }\n );\n if (!persisted) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n\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._admitTurn({\n admission: \"queue\",\n trigger: \"ws-chat\",\n requestId,\n generation: epoch,\n continuation: false,\n onQueued: releaseIfPending,\n execute: 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 // Bounded compact-and-retry loop (opt-in via\n // `contextOverflow.reactive`). A turn that overflows the\n // context window mid-flight is compacted and re-run from the\n // persisted partial instead of dying terminally. Each attempt\n // re-runs the same turn (`continuation: false`) — not an\n // auto-continuation.\n for (let attempt = 0; ; attempt++) {\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 this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"No response was generated.\",\n done: true\n });\n return;\n }\n\n // The consumer suppresses a classified overflow whenever\n // recovery is enabled; the driver (here) owns the\n // retry-vs-terminal call so every overflow terminal is reported\n // identically.\n let overflowError: string | undefined;\n let overflowRequested = false;\n const overflowRecovery = this._overflowReactiveEnabled\n ? {\n onRetry: (error?: string) => {\n overflowRequested = true;\n overflowError = error;\n }\n }\n : undefined;\n\n await withAgentSpan(\n this,\n \"persist_chat_result\",\n \"turn\",\n {\n \"cloudflare.agents.component\": \"think\",\n \"cloudflare.agents.turn.request_id\": requestId,\n \"cloudflare.agents.turn.trigger\": \"ws-chat\",\n \"cloudflare.agents.turn.admission\": \"queue\",\n \"cloudflare.agents.turn.generation\": epoch,\n \"cloudflare.agents.turn.continuation\": false\n },\n () =>\n this._streamResult(requestId, result, abortSignal, {\n parentId: branchParentId,\n overflowRecovery\n })\n );\n\n if (overflowRequested) {\n if (\n attempt < this._overflowMaxRetries &&\n !abortSignal?.aborted\n ) {\n const shortened = await withAgentSpan(\n this,\n \"compact_chat_history\",\n \"turn\",\n {\n \"cloudflare.agents.component\": \"think\",\n \"cloudflare.agents.turn.request_id\": requestId,\n \"cloudflare.agents.turn.trigger\": \"ws-chat\",\n \"cloudflare.agents.turn.admission\": \"queue\",\n \"cloudflare.agents.turn.generation\": epoch,\n \"cloudflare.agents.turn.continuation\": false\n },\n () =>\n this._compactForContextOverflow(\"reactive\", {\n requestId,\n attempt: attempt + 1\n })\n );\n // Compaction shortened history → retry. A no-op compaction\n // can't fix the overflow, so fall through to terminal.\n if (shortened) continue;\n }\n // Budget spent, aborted, or compaction no-op: deliver\n // terminally (through onChatError, classified) so the turn\n // never loops or ends silently with no answer.\n const message = this._finalizeContextOverflowError(\n requestId,\n overflowError\n );\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: message,\n done: true,\n error: true\n });\n }\n return;\n }\n };\n\n if (this.chatRecovery) {\n await this._runChatRecoveryFiber(requestId, false, chatTurnBody);\n } else {\n await chatTurnBody();\n }\n }\n });\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 // Release any pre-stream parked connections (#1784). No-op when the turn\n // streamed (flushed on _startResumableStream); covers the no-response /\n // pre-stream-failure paths.\n this._settlePreStreamTurn(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 // Tear down the event-driven auto-continuation barrier (#1650): cancel the\n // coalesce timer and clear the double-fire guard so a reset mid-park can't\n // leave a stale flag pinning future continuations.\n this._autoContinuation.reset();\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._continuation.sendResumeNone();\n this._continuation.clearAll();\n this._preStream.releaseAwaiting();\n this._preStream.reset();\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 /**\n * Stamp the allocated assistant id onto a new turn's `start` chunk so a chat\n * client builds the live-streamed message under the SAME id this agent\n * persists under. Providers that emit no `start.messageId` (e.g. Workers AI)\n * otherwise leave the client to generate its own id; the live stream and the\n * persisted message broadcast then can't reconcile by id, and the originating\n * tab briefly renders the turn twice before collapsing. Mirrors the fix in\n * `@cloudflare/ai-chat`. Continuations are skipped — they reuse the existing\n * assistant message via the `continuation` frame flag, so the id must not\n * change mid-message. The orphan-recovery path inherits the id from the\n * stored chunk, so it needs no separate stamping.\n */\n private _alignStreamStartId(\n chunk: StreamChunkData,\n action: { type: string; messageId?: string } | undefined,\n accumulator: StreamAccumulator,\n continuation: boolean\n ): void {\n if (action?.type === \"start\" && action.messageId == null && !continuation) {\n (chunk as { messageId?: string }).messageId = accumulator.messageId;\n }\n }\n\n private _annotateActionApprovalChunk(\n requestId: string,\n chunk: StreamChunkData,\n pendingActionCalls: Map<\n string,\n { toolName: string; input: unknown | undefined }\n >,\n parts?: UIMessage[\"parts\"]\n ): StreamChunkData {\n const toolCallId =\n typeof chunk.toolCallId === \"string\"\n ? chunk.toolCallId\n : typeof chunk.id === \"string\"\n ? chunk.id\n : undefined;\n\n if (toolCallId) {\n if (\n (chunk.type === \"tool-input-start\" ||\n chunk.type === \"tool-input-available\" ||\n chunk.type === \"tool-call\") &&\n typeof chunk.toolName === \"string\"\n ) {\n const previous = pendingActionCalls.get(toolCallId);\n pendingActionCalls.set(toolCallId, {\n toolName: chunk.toolName,\n input:\n \"input\" in chunk\n ? normalizeToolInput(chunk.input).input\n : previous?.input\n });\n } else if (\"input\" in chunk) {\n const previous = pendingActionCalls.get(toolCallId);\n if (previous) {\n pendingActionCalls.set(toolCallId, {\n ...previous,\n input: normalizeToolInput(chunk.input).input\n });\n }\n }\n }\n\n // A durable pause (durable-pause action OR codemode execution) surfaces as\n // a `tool-output-available` chunk whose output is `status: \"paused\"`, NOT a\n // `tool-approval-request`. Attach the approval descriptor here so the paused\n // transcript part renders consistently in every approval UI.\n if (chunk.type === \"tool-output-available\" && toolCallId) {\n const descriptor = this._descriptorForPausedOutput(\n requestId,\n toolCallId,\n (chunk as { output?: unknown }).output\n );\n return descriptor ? { ...chunk, approvalDescriptor: descriptor } : chunk;\n }\n\n if (chunk.type !== \"tool-approval-request\" || !toolCallId) return chunk;\n\n const storedDescriptor =\n this._activeTurnActionApprovalDescriptors.get(toolCallId);\n if (storedDescriptor) {\n return {\n ...chunk,\n approvalDescriptor: storedDescriptor\n };\n }\n\n let pending = pendingActionCalls.get(toolCallId);\n if (!pending && parts) {\n const part = parts.find(\n (candidate) =>\n \"toolCallId\" in candidate && candidate.toolCallId === toolCallId\n ) as Record<string, unknown> | undefined;\n if (typeof part?.toolName === \"string\") {\n pending = {\n toolName: part.toolName,\n input: \"input\" in part ? normalizeToolInput(part.input).input : {}\n };\n }\n }\n if (!pending) return chunk;\n\n const metadata = this._activeTurnActionMetadata.get(pending.toolName);\n if (!metadata) return chunk;\n\n const descriptor: ActionApprovalDescriptor = {\n requestId,\n toolCallId,\n action: metadata.actionName,\n summary: metadata.summary,\n input: pending.input ?? {},\n permissions: metadata.permissions ?? [],\n ...(metadata.risk !== undefined && { risk: metadata.risk }),\n kind: metadata.kind\n };\n\n return {\n ...chunk,\n approvalDescriptor: descriptor\n };\n }\n\n /**\n * Build the approval descriptor for a paused tool output, the single source\n * of truth for rendering a pending approval. Durable-pause actions read the\n * descriptor persisted on their pending row (resolved permissions, survives\n * compaction); codemode pauses derive `connector.method` from the first\n * pending action and let {@link describePausedExecution} enrich it. Returns\n * `undefined` for non-paused outputs or when no descriptor can be built.\n */\n private _descriptorForPausedOutput(\n requestId: string,\n toolCallId: string,\n output: unknown\n ): ActionApprovalDescriptor | undefined {\n if (typeof output !== \"object\" || output === null) return undefined;\n const o = output as {\n status?: unknown;\n executionId?: unknown;\n pending?: unknown;\n };\n if (o.status !== \"paused\") return undefined;\n const executionId =\n typeof o.executionId === \"string\" ? o.executionId : undefined;\n\n if (executionId?.startsWith(ACTION_PAUSE_ID_PREFIX)) {\n const row = this._readActionPendingRow(executionId);\n if (!row?.descriptor_json) return undefined;\n try {\n return JSON.parse(row.descriptor_json) as ActionApprovalDescriptor;\n } catch {\n return undefined;\n }\n }\n\n const pending = Array.isArray(o.pending)\n ? (o.pending as import(\"@cloudflare/codemode\").PendingAction[])\n : [];\n const first = pending[0];\n if (!first) return undefined;\n const label = `${first.connector}.${first.method}`;\n const base: ActionApprovalDescriptor = {\n requestId,\n toolCallId,\n action: label,\n summary: label,\n input: first.args,\n permissions: [],\n kind: \"durable-pause\"\n };\n const override = this.describePausedExecution(pending, {\n requestId,\n toolCallId\n });\n if (!override) return base;\n return {\n ...base,\n ...override,\n // Identity fields are ours to set — an override can't retarget the part.\n requestId,\n toolCallId\n };\n }\n\n private _applyActionApprovalDescriptorToParts(\n chunk: StreamChunkData,\n parts: UIMessage[\"parts\"]\n ): void {\n if (\n (chunk.type !== \"tool-approval-request\" &&\n chunk.type !== \"tool-output-available\") ||\n typeof chunk.toolCallId !== \"string\" ||\n chunk.approvalDescriptor === undefined\n ) {\n return;\n }\n const part = parts.find(\n (candidate) =>\n \"toolCallId\" in candidate && candidate.toolCallId === chunk.toolCallId\n ) as Record<string, unknown> | undefined;\n if (!part) return;\n if (chunk.type === \"tool-approval-request\") {\n // A genuine AI SDK approval request: the descriptor rides on the\n // approval object (which also carries the eventual decision).\n part.approval = {\n ...(part.approval as Record<string, unknown> | undefined),\n descriptor: chunk.approvalDescriptor\n };\n return;\n }\n // A durable pause (durable-pause action / codemode) is a SETTLED\n // `output-available` part, not an AI SDK approval. Putting the descriptor\n // on `part.approval` would make `convertToModelMessages` emit a\n // `tool-approval-request` for an already-resolved output on the next turn\n // (an invalid prompt). Use a sibling field conversion ignores instead.\n part.approvalDescriptor = chunk.approvalDescriptor;\n }\n\n private async _streamResultToRpcCallback(\n requestId: string,\n result: StreamableResult,\n callback: StreamCallback,\n abortSignal?: AbortSignal,\n options?: {\n /**\n * When set, an in-stream error the app classifies as `context_overflow`\n * is treated as recoverable: the partial is persisted, the stream is\n * finalized cleanly (no terminal error to the caller), and\n * `{ status: \"overflow_retry\" }` is returned so the driver can compact\n * and re-run. Pass only while the retry budget allows.\n */\n overflowRecovery?: boolean;\n }\n ): Promise<{\n status: \"completed\" | \"error\" | \"aborted\" | \"overflow_retry\";\n error?: string;\n }> {\n const streamId = this._startResumableStream(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 // Set when an in-stream overflow error is recoverable (opt-in): suppresses\n // terminal delivery so the driver can compact and re-run the turn.\n let overflowRetry = false;\n\n const stallTimeoutMs =\n this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;\n // True only when the wrapped stream was pulled to natural exhaustion; a\n // break OR a throw (stall watchdog) leaves it false so the finally drains\n // the abandoned tee branch.\n let streamDrainedNaturally = false;\n try {\n this._insideInferenceLoop = true;\n const flushState = { chunksSinceFlush: 0, hasFlushedContent: false };\n const pendingActionCalls = new Map<\n string,\n { toolName: string; input: unknown | undefined }\n >();\n try {\n const guardedStream = iterateWithStallWatchdog(\n result.toUIMessageStream({ onError: streamErrorToString }),\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 = this._annotateActionApprovalChunk(\n requestId,\n chunk as unknown as StreamChunkData,\n pendingActionCalls,\n accumulator.parts\n );\n const { action } = accumulator.applyChunk(streamChunk);\n this._applyActionApprovalDescriptorToParts(\n streamChunk,\n accumulator.parts\n );\n\n if (action?.type === \"error\") {\n streamError = action.error;\n // Recoverable context overflow (opt-in): don't terminalize. Persist\n // the partial after the loop, then signal the driver to compact and\n // re-run. No `message:error`/`chat:request:failed`/error frame here\n // — the turn isn't over.\n if (\n options?.overflowRecovery &&\n this._isRecoverableContextOverflow(streamError, requestId)\n ) {\n overflowRetry = true;\n break;\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 });\n break;\n }\n\n this._alignStreamStartId(streamChunk, action, accumulator, false);\n\n const chunkBody = JSON.stringify(streamChunk);\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 streamDrainedNaturally = !(\n aborted ||\n overflowRetry ||\n streamError !== undefined\n );\n } finally {\n this._insideInferenceLoop = false;\n // Only early exits leave an abandoned tee branch; a naturally\n // exhausted stream needs no drain (consumeStream is not free — it\n // tees the base stream and traverses the buffered branch). A thrown\n // exit (stall watchdog) never reaches the assignment above, so it\n // drains too.\n if (!streamDrainedNaturally) {\n this._drainInferenceStream(result);\n }\n }\n\n // Recoverable context overflow: discard the partial, close the stream\n // cleanly without a terminal error, and hand control back to the driver.\n // No `onDone`/`onError` and no response hook — the turn is not finished;\n // the retry owns the terminal outcome.\n //\n // The partial is intentionally NOT persisted: the driver re-runs the turn\n // from scratch (`continuation: false`) against the compacted history, so\n // the retry produces a fresh assistant message. Persisting the truncated\n // partial would leave an orphan beside the recovered answer — and any tool\n // work it captured would be re-issued by the retry, duplicating records.\n // The live-streamed chunks already reached clients; the driver's\n // post-retry `_broadcastMessages()` reconciles them to the real answer.\n if (overflowRetry) {\n this._completeResumableStream(streamId);\n streamFinalized = true;\n return { status: \"overflow_retry\", error: streamError };\n }\n\n if (streamError) {\n this._errorResumableStream(streamId);\n } else {\n this._completeResumableStream(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._completeResumableStream(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 { 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 return WITHOUT the generic terminal path,\n // which would otherwise re-broadcast the raw stall error.\n if (!streamFinalized) {\n this._errorResumableStream(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 { status: \"aborted\" };\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._errorResumableStream(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 return {\n status:\n streamError || pendingRpcError\n ? \"error\"\n : aborted\n ? \"aborted\"\n : \"completed\"\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 }\n // Forward progress: advance the monotonic, compaction-immune progress\n // counter HERE (production time) rather than in `_persistOrphanedStream` —\n // so it bumps only on genuinely new content and is immune to client\n // reconnects / recovery re-persists (which don't flow through this path).\n // Decoupled from the flush decision and routed through the shared\n // host-agnostic rule ({@link shouldCreditStreamProgress}) so the bump TIMING\n // matches `AIChatAgent`: a milestone (started segment / settled tool) always\n // credits, and a long single segment's streaming deltas credit through a\n // time throttle. This is what the recovery no-progress window keys off\n // (#1637), and stays compaction-proof (#1628).\n if (\n shouldCreditStreamProgress({\n codec: aiSdkRecoveryCodec,\n type: chunk.type,\n throttle: this._streamProgressCredit,\n now: Date.now()\n })\n ) {\n await this._bumpChatRecoveryProgress();\n }\n }\n\n /** Per-isolate throttle for crediting recovery progress from mid-segment\n * streaming-content deltas (the shared `agents/chat` rule); reset per isolate\n * so the first delta after a restart always credits. */\n private _streamProgressCredit = new StreamProgressCreditThrottle();\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 * When set, an in-stream error the app classifies as `context_overflow`\n * is treated as recoverable: the partial is persisted, the stream is\n * finalized cleanly (no terminal error frame), `onRetry(error)` is invoked\n * so the driver can compact and re-run, and `{ status: \"aborted\" }` is\n * returned. Pass only while the retry budget allows.\n */\n overflowRecovery?: { onRetry: (error?: string) => void };\n }\n ): Promise<StreamResultStatus> {\n const clearGen = this._turnQueue.generation;\n const streamId = this._startResumableStream(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 // Set when an in-stream overflow error is recoverable (opt-in): suppresses\n // terminal delivery so the driver can compact and re-run the turn.\n let overflowRetry = false;\n const flushState = { chunksSinceFlush: 0, hasFlushedContent: false };\n const pendingActionCalls = new Map<\n string,\n { toolName: string; input: unknown | undefined }\n >();\n\n const stallTimeoutMs =\n this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;\n // True only when the wrapped stream was pulled to natural exhaustion; a\n // break OR a throw (stall watchdog) leaves it false so the finally drains\n // the abandoned tee branch.\n let streamDrainedNaturally = false;\n try {\n this._insideInferenceLoop = true;\n try {\n const guardedStream = iterateWithStallWatchdog(\n result.toUIMessageStream({ onError: streamErrorToString }),\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 = this._annotateActionApprovalChunk(\n requestId,\n chunk as unknown as StreamChunkData,\n pendingActionCalls,\n accumulator.parts\n );\n const { action } = accumulator.applyChunk(streamChunk);\n this._applyActionApprovalDescriptorToParts(\n streamChunk,\n accumulator.parts\n );\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 // Recoverable context overflow (opt-in): don't terminalize. Persist\n // the partial after the loop, then signal the driver to compact and\n // re-run. No `message:error`/`chat:request:failed`/error frame here.\n if (\n options?.overflowRecovery &&\n this._isRecoverableContextOverflow(streamError, requestId)\n ) {\n overflowRetry = true;\n break;\n }\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 this._alignStreamStartId(\n streamChunk,\n action,\n accumulator,\n continuation\n );\n\n const chunkBody = JSON.stringify(streamChunk);\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 streamDrainedNaturally = !(\n streamAborted ||\n overflowRetry ||\n streamError !== undefined\n );\n } finally {\n this._insideInferenceLoop = false;\n // Only early exits leave an abandoned tee branch; a naturally\n // exhausted stream needs no drain (consumeStream is not free — it\n // tees the base stream and traverses the buffered branch). A thrown\n // exit (stall watchdog) never reaches the assignment above, so it\n // drains too.\n if (!streamDrainedNaturally) {\n this._drainInferenceStream(result);\n }\n }\n\n // Recoverable context overflow: discard the partial, close this stream\n // segment WITHOUT a terminal frame, and hand control back to the driver\n // via `onRetry`. The inline retry runs in this same invocation and owns\n // the terminal outcome, so we must NOT emit a `done` frame here — and\n // `doneSent = true` keeps the outer `finally` from emitting one (it would\n // otherwise prematurely terminate the client's stream mid-recovery and\n // mark the segment errored).\n //\n // The partial is intentionally NOT persisted: the driver re-runs the turn\n // from scratch (`continuation: false`) against the compacted history, so\n // the retry produces a fresh assistant message. Persisting the truncated\n // partial would leave an orphan beside the recovered answer — and any tool\n // work it captured would be re-issued by the retry, duplicating records.\n // The live-streamed chunks already reached clients; the retry's\n // `_broadcastMessages()` reconciles them to the real answer.\n if (overflowRetry && options?.overflowRecovery) {\n this._completeResumableStream(streamId);\n this._pendingResumeConnections.clear();\n doneSent = true;\n options.overflowRecovery.onRetry(streamError);\n this._streamingAssistant = null;\n return { status: \"aborted\" };\n }\n\n if (streamError) {\n this._errorResumableStream(streamId);\n } else {\n this._completeResumableStream(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._completeResumableStream(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._errorResumableStream(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._errorResumableStream(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._errorResumableStream(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 /**\n * Single source of Think's strip + empty-skip persistence rule. Strips the\n * internal final-answer parts and returns the message to persist (the stripped\n * copy, or the original when nothing was stripped), or `null` when stripping\n * leaves nothing user-facing (only structural `step-start` markers, or\n * nothing) — in which case the caller skips persistence so a structured\n * workflow turn does not leave an empty assistant message in the conversation.\n * Shared by `_persistAssistantMessage` and the orphan-persist path so the rule\n * cannot drift between the live and recovery writes.\n */\n private _strippedForPersist(msg: UIMessage): UIMessage | null {\n const stripped = this._stripInternalFinalAnswerParts(msg);\n if (stripped === msg) return msg;\n const hasMeaningfulParts = stripped.parts.some(\n (part) => (part as { type?: string }).type !== \"step-start\"\n );\n return hasMeaningfulParts ? stripped : null;\n }\n\n private async _persistAssistantMessage(\n msg: UIMessage,\n parentId?: string\n ): Promise<void> {\n const toPersist = this._strippedForPersist(msg);\n if (toPersist === null) return;\n await this._upsertMessageInHistory(toPersist, parentId);\n }\n\n /**\n * Remove parts belonging to Think's internal structured-output final-answer\n * tool (`think_final_answer`, or a collision-suffixed variant) from a UI\n * message so the internal call/result never enters the persisted conversation\n * (and is never re-fed to the model on later turns). Stateless and matched by\n * the reserved name so it also covers recovery re-persist paths. Handles both\n * the static (`tool-<name>`) and dynamic (`dynamic-tool`) part shapes the AI\n * SDK can emit.\n */\n private _stripInternalFinalAnswerParts(msg: UIMessage): UIMessage {\n const parts = msg.parts.filter((part) => {\n const candidate = part as { type?: string; toolName?: string };\n if (\n typeof candidate.type === \"string\" &&\n candidate.type.startsWith(\"tool-\") &&\n isThinkFinalAnswerToolName(candidate.type.slice(\"tool-\".length))\n ) {\n return false;\n }\n if (\n candidate.type === \"dynamic-tool\" &&\n typeof candidate.toolName === \"string\" &&\n isThinkFinalAnswerToolName(candidate.toolName)\n ) {\n return false;\n }\n return true;\n });\n return parts.length === msg.parts.length ? msg : { ...msg, parts };\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 sanitized = this._stripReservedMessageMetadata(msg);\n const resolved =\n sanitized.role === \"assistant\"\n ? resolveToolMergeId(sanitized, serverMessages)\n : sanitized;\n await this._upsertMessageInHistory(resolved);\n }\n\n /**\n * Strip {@link RESERVED_MESSAGE_METADATA_KEYS} from a client-supplied message\n * at intake. Those keys are server-written turn context (stamped by\n * `_stampChannel`) that hooks and recovery re-resolve and trust, so a client\n * must never be able to forge them.\n */\n private _stripReservedMessageMetadata(msg: UIMessage): UIMessage {\n const metadata = msg.metadata as Record<string, unknown> | undefined;\n if (\n !metadata ||\n !RESERVED_MESSAGE_METADATA_KEYS.some((key) => key in metadata)\n ) {\n return msg;\n }\n const rest = { ...metadata };\n for (const key of RESERVED_MESSAGE_METADATA_KEYS) {\n delete rest[key];\n }\n return { ...msg, metadata: rest };\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 // ── Durable execution approvals (codemode HITL) ──────────────────\n //\n // A `requiresApproval` connector call inside the execute tool pauses the\n // run *durably*: the tool returns `{ status: \"paused\", executionId,\n // pending }` as a normal output, the model narrates what it needs, and the\n // turn ends. These callables are the resume path: approve/reject the\n // pending action on the codemode runtime, replace the paused output in the\n // transcript with the new outcome, and auto-continue so the model sees it.\n\n /**\n * The codemode runtime handle behind the execute tool. `this.codemode` is\n * assigned when `createExecuteRuntime(this)` / `createExecuteTool(this)`\n * runs (normally at turn start, via `getTools()`); after a DO restart no\n * turn may have run yet, so fall back to building the tools once.\n */\n private _codemodeRuntime():\n | import(\"@cloudflare/codemode\").CodemodeRuntimeHandle\n | undefined {\n if (!this.codemode) {\n try {\n this.getTools();\n } catch {\n // getTools may require turn-time context; without it there is\n // simply no runtime to resolve.\n }\n }\n return this.codemode;\n }\n\n /**\n * Pending (awaiting-approval) actions across paused executions of the\n * execute tool's codemode runtime — `{ executionId, seq, connector,\n * method, args }` each, with FULL args (the transcript copy is truncated).\n * Clients reconcile approval cards against this on load.\n *\n * Client-callable (registered below — see the `callable()` calls after the\n * class body).\n */\n async pendingExecutions(\n executionId?: string\n ): Promise<import(\"@cloudflare/codemode\").PendingAction[]> {\n const runtime = this._codemodeRuntime();\n if (!runtime) return [];\n return runtime.pending(executionId);\n }\n\n /**\n * List everything awaiting human approval — parked `kind: \"durable-pause\"`\n * actions and paused codemode executions — each carrying its\n * {@link ActionApprovalDescriptor}. The unified, descriptor-first view a\n * dashboard, voice backend, or messenger reconciles against; resolve any of\n * them via {@link approveExecution} / {@link rejectExecution}. Pass an\n * `executionId` to scope to one.\n *\n * Client-callable.\n */\n async pendingApprovals(executionId?: string): Promise<PendingApproval[]> {\n const out: PendingApproval[] = [];\n\n for (const row of this._listActionPendingRows()) {\n if (executionId && row.execution_id !== executionId) continue;\n if (!row.descriptor_json) continue;\n let descriptor: ActionApprovalDescriptor;\n try {\n descriptor = JSON.parse(\n row.descriptor_json\n ) as ActionApprovalDescriptor;\n } catch {\n continue;\n }\n out.push({\n executionId: row.execution_id,\n source: \"action\",\n descriptor\n });\n }\n\n const runtime = this._codemodeRuntime();\n if (runtime) {\n const pending = await runtime.pending(executionId);\n const seen = new Set<string>();\n for (const action of pending) {\n if (seen.has(action.executionId)) continue;\n seen.add(action.executionId);\n const group = pending.filter(\n (candidate) => candidate.executionId === action.executionId\n );\n const toolCallId =\n this._findExecutionToolCall(action.executionId) ?? \"\";\n const descriptor = this._descriptorForPausedOutput(\"\", toolCallId, {\n status: \"paused\",\n executionId: action.executionId,\n pending: group\n });\n if (descriptor) {\n out.push({\n executionId: action.executionId,\n source: \"codemode\",\n descriptor\n });\n }\n }\n }\n\n return out;\n }\n\n /**\n * Approve a paused execution and resume it. The run continues from where\n * it stopped (replaying logged work, executing the approved call); the\n * outcome — completed, errored, or paused again on the NEXT gated call —\n * replaces the paused tool output in the transcript and the chat\n * auto-continues so the model can act on it.\n *\n * Approving an execution that is no longer pending (already settled,\n * expired, or unknown) returns `{ status: \"error\" }` with an explanatory\n * message — it never throws.\n *\n * Client-callable.\n */\n async approveExecution(executionId: string): Promise<unknown> {\n // Durable-pause action approvals own the `actpause_` id space and resolve\n // against the pending-approval store, not the codemode runtime.\n if (executionId.startsWith(ACTION_PAUSE_ID_PREFIX)) {\n return await this._approveActionPause(executionId);\n }\n const runtime = this._codemodeRuntime();\n if (!runtime) {\n return {\n status: \"error\",\n executionId,\n error:\n \"No codemode runtime is configured — the execute tool was never \" +\n \"created on this agent.\"\n };\n }\n const output = truncatePausedExecutionOutput(\n await runtime.approve({ executionId })\n );\n await this._applyExecutionOutcome(executionId, output);\n return output;\n }\n\n /**\n * Approve a parked `kind: \"durable-pause\"` action and run its `execute`.\n *\n * Claim-by-delete makes this idempotent across tabs/recovery: only the caller\n * that removes the row runs the action; a racing approve/reject sees no row\n * and reports \"already resolved\". Authorization happened at PAUSE time — the\n * human approval is the authority now, so we do not re-authorize (the turn\n * context that `authorizeAction` needs is gone). The action runs through the\n * ledger so its side effect stays replay-safe, the outcome replaces the\n * paused transcript part, and the chat continues even with no socket open.\n */\n private async _approveActionPause(executionId: string): Promise<unknown> {\n const row = this._claimActionPendingRow(executionId);\n if (!row) {\n return {\n status: \"error\",\n executionId,\n error: `Execution \"${executionId}\" is no longer pending — it was approved or rejected elsewhere.`\n };\n }\n\n const action = await this._findRegisteredAction(row.action_name);\n if (!action) {\n const output = {\n status: \"error\",\n executionId,\n action: row.action_name,\n error:\n `Action \"${row.action_name}\" is no longer registered, so the ` +\n `approved call cannot run. The approval was consumed.`\n };\n await this._applyExecutionOutcome(executionId, output);\n return output;\n }\n\n let input: unknown;\n try {\n input = JSON.parse(row.input_json);\n } catch {\n input = {};\n }\n\n const output = await this._runApprovedActionPause(action, row, input);\n this._emitActionPauseEvent({\n type: \"action:pause:approved\",\n payload: { action: row.action_name, executionId }\n });\n await this._applyExecutionOutcome(executionId, output);\n return output;\n }\n\n /** Resolve a registered action by its resolved name (config.name ?? key). */\n private async _findRegisteredAction(name: string): Promise<Action | null> {\n const actions = await this.getActions();\n for (const [registrationName, candidate] of Object.entries(actions)) {\n if (!isAction(candidate)) continue;\n const resolved = candidate.config.name ?? registrationName;\n if (resolved === name) return candidate;\n }\n return null;\n }\n\n /**\n * Run a just-approved durable-pause action's `execute` through the ledger.\n * Mirrors the inline `_actionToTool` execute wrapper (timeout, abort race,\n * model-output prep) MINUS authorization — that was settled at pause time.\n */\n private async _runApprovedActionPause(\n action: Action,\n row: ActionPendingRow,\n input: unknown\n ): Promise<unknown> {\n const config = action.config;\n const executeAction = config.execute as (\n input: unknown,\n ctx: ActionContext\n ) => Promise<unknown> | unknown;\n const idempotencyKey = config.idempotencyKey as\n | ActionIdempotencyKey<unknown>\n | undefined;\n const { signal, cleanup } = createActionAbortSignal(\n undefined,\n config.timeoutMs ?? DEFAULT_ACTION_TIMEOUT_MS\n );\n const ctx: ActionContext = {\n agent: this,\n env: this.env as Cloudflare.Env,\n requestId: row.request_id ?? \"\",\n toolCallId: row.tool_call_id,\n messages: [],\n signal,\n // No-op: a durable-pause approved action is delivered by a later\n // continuation turn (different requestId), so a same-turn attachment\n // can't be delivered in v1.\n attachReply: () => {}\n };\n const abortError = () =>\n signal.reason instanceof Error\n ? signal.reason\n : new Error(signal.reason ? String(signal.reason) : \"Action aborted\");\n let onAbort: (() => void) | undefined;\n try {\n if (signal.aborted) throw abortError();\n const abortPromise = new Promise<never>((_, reject) => {\n onAbort = () => reject(abortError());\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n const runAction = async () => {\n const out = await Promise.race([\n Promise.resolve(executeAction(input, ctx)),\n abortPromise\n ]);\n return prepareActionOutputForModel(out);\n };\n return await this._runLedgeredAction({\n toolName: row.action_name,\n idempotencyKey,\n input,\n ctx,\n runAction\n });\n } catch (error) {\n return actionErrorEnvelope(error);\n } finally {\n if (onAbort) signal.removeEventListener(\"abort\", onAbort);\n cleanup();\n }\n }\n\n /**\n * Reject a paused execution's pending action, ending the run. The\n * transcript's paused output is replaced with\n * `{ status: \"rejected\", executionId, reason }` and the chat\n * auto-continues so the model can adapt (or explain) instead of erroring.\n *\n * Client-callable.\n */\n async rejectExecution(\n executionId: string,\n reason?: string\n ): Promise<unknown> {\n if (executionId.startsWith(ACTION_PAUSE_ID_PREFIX)) {\n return await this._rejectActionPause(executionId, reason);\n }\n const runtime = this._codemodeRuntime();\n if (!runtime) {\n return {\n status: \"error\",\n executionId,\n error:\n \"No codemode runtime is configured — the execute tool was never \" +\n \"created on this agent.\"\n };\n }\n const pending = await runtime.pending(executionId);\n if (pending.length === 0) {\n return {\n status: \"error\",\n executionId,\n error: `Execution \"${executionId}\" is no longer pending.`\n };\n }\n // `reject` reports whether it actually terminated the run. A `false`\n // means the action was resolved between our `pending()` check and the\n // reject (approve/reject interleave across facet RPC awaits — input\n // gates only cover storage). Writing \"rejected\" then would clobber a\n // paused part whose real outcome (e.g. an in-flight approval) is still\n // coming, so surface an error instead.\n const terminated = await runtime.reject({\n executionId,\n seq: pending[0].seq\n });\n if (!terminated) {\n return {\n status: \"error\",\n executionId,\n error: `Execution \"${executionId}\" is no longer pending — it was approved or rejected elsewhere.`\n };\n }\n const output = {\n status: \"rejected\",\n executionId,\n reason: reason ?? \"Rejected by user\"\n };\n await this._applyExecutionOutcome(executionId, output);\n return output;\n }\n\n /**\n * Reject a parked `kind: \"durable-pause\"` action. Claim-by-delete consumes\n * the pending row (idempotent across tabs/recovery), the action's `execute`\n * never runs, and the paused transcript part is replaced with a `rejected`\n * outcome so the model can adapt or explain.\n */\n private async _rejectActionPause(\n executionId: string,\n reason?: string\n ): Promise<unknown> {\n const row = this._claimActionPendingRow(executionId);\n if (!row) {\n return {\n status: \"error\",\n executionId,\n error: `Execution \"${executionId}\" is no longer pending — it was approved or rejected elsewhere.`\n };\n }\n const output = {\n status: \"rejected\",\n executionId,\n action: row.action_name,\n reason: reason ?? \"Rejected by user\"\n };\n this._emitActionPauseEvent({\n type: \"action:pause:rejected\",\n payload: { action: row.action_name, executionId }\n });\n await this._applyExecutionOutcome(executionId, output);\n return output;\n }\n\n /**\n * Replace a paused execute-tool output in the transcript with the\n * execution's new outcome and kick the auto-continuation so the model sees\n * it.\n *\n * When no paused part carries `executionId` — the output was already\n * replaced from another tab, or compaction summarized the part away — the\n * runtime has still durably applied the approval/rejection, so the outcome\n * must not be dropped: it is appended as a system note instead, and the\n * continuation still fires so the model can act on it.\n */\n private async _applyExecutionOutcome(\n executionId: string,\n output: unknown\n ): Promise<boolean> {\n const toolCallId = this._findPausedExecutionToolCall(executionId);\n if (!toolCallId) {\n // Already resolved in place (e.g. approved from another tab)? Then the\n // transcript has the outcome and nothing more is needed.\n if (this._findExecutionToolCall(executionId) != null) return false;\n let summary: string;\n try {\n summary = JSON.stringify(output)?.slice(0, 4_000) ?? String(output);\n } catch {\n summary = String(output);\n }\n await this._appendMessageToHistory({\n id: `exec-outcome-${executionId}-${crypto.randomUUID()}`,\n role: \"system\",\n parts: [\n {\n type: \"text\",\n text:\n `[execute tool] The paused execution \"${executionId}\" was ` +\n `resolved, but its tool call is no longer in the transcript ` +\n `(it may have been compacted). Outcome: ${summary}`\n }\n ]\n } as UIMessage);\n } else {\n await this._enqueueInteractionApply(() =>\n this._applyToolUpdateToMessages(\n pausedExecutionUpdate(toolCallId, executionId, output)\n )\n );\n }\n // Continue on the approving connection when there is one (WS callable),\n // else any open connection (DO-stub approval with clients attached). When\n // NO connection is open — an approval arriving via RPC from a dashboard,\n // webhook, or voice backend — fall back to a connection-independent\n // continuation so the model still advances and the result isn't stranded.\n const { connection } = getCurrentAgent();\n let target = connection;\n if (!target) {\n for (const open of this.getConnections()) {\n target = open;\n break;\n }\n }\n if (target) {\n this._scheduleAutoContinuation(target);\n } else {\n this._runConnectionlessContinuation();\n }\n return true;\n }\n\n /**\n * Find the tool part holding the paused output of `executionId` — in the\n * in-flight streaming accumulator first (an approval can land while a new\n * turn streams), then the persisted transcript, newest message first.\n */\n private _findPausedExecutionToolCall(executionId: string): string | null {\n return this._findExecutionToolCall(executionId, true);\n }\n\n /**\n * Find the tool part carrying `executionId` in its output. With\n * `pausedOnly`, only a still-paused output matches — used to locate the\n * part an approval outcome should replace. Without it, any settled output\n * matches — used to distinguish \"already resolved elsewhere\" from \"the\n * part is gone from the transcript\" (e.g. compacted away).\n */\n private _findExecutionToolCall(\n executionId: string,\n pausedOnly = false\n ): string | null {\n const matches = (part: Record<string, unknown>): boolean => {\n if (part.state !== \"output-available\") return false;\n if (typeof part.toolCallId !== \"string\") return false;\n const output = part.output as\n | { status?: unknown; executionId?: unknown }\n | null\n | undefined;\n return (\n output != null &&\n typeof output === \"object\" &&\n (!pausedOnly || output.status === \"paused\") &&\n output.executionId === executionId\n );\n };\n\n const streaming = this._streamingAssistant;\n if (streaming) {\n for (const part of streaming.parts as unknown as Array<\n Record<string, unknown>\n >) {\n if (matches(part)) return part.toolCallId as string;\n }\n }\n\n for (let i = this.messages.length - 1; i >= 0; i--) {\n const message = this.messages[i];\n if (message.role !== \"assistant\") continue;\n for (const part of message.parts as unknown as Array<\n Record<string, unknown>\n >) {\n if (matches(part)) return part.toolCallId as string;\n }\n }\n return null;\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 // Scan the in-flight accumulator first, mirroring `@cloudflare/ai-chat`'s\n // `_streamingMessage` check. A parallel-batch client tool can stream a\n // pending `input-available`/`approval-requested` part into\n // `_streamingAssistant` before the end-of-stream persist writes it to\n // `this.messages`. The hot `waitUntilStable` loop only consults this after\n // `waitForIdle()` (when the streaming turn has drained and the accumulator\n // is null), so the scan is a no-op there. It matters on the same-isolate\n // stall route, where the incident-eval callback runs mid-stream: without\n // it Think would budget a stall that ai-chat treats as \"awaiting client\"\n // (budget-free) — a self-correcting drift once the continuation re-reads\n // persisted state, but a real asymmetry the stall watchdog would expose.\n const streaming = this._streamingAssistant;\n if (\n streaming &&\n this._messageHasPendingInteraction(\n streaming.toMessage(),\n clientResolvable\n )\n ) {\n return true;\n }\n return this.messages.some(\n (message) =>\n message.role === \"assistant\" &&\n this._messageHasPendingInteraction(message, clientResolvable)\n );\n }\n\n /**\n * `true` when an auto-continuation is armed but has not yet fired (#1650): a\n * pending continuation that has not entered its turn (`!pastCoalesce`) whose\n * coalesce timer is still pending or whose completeness drain is in progress.\n * Mirrors `@cloudflare/ai-chat`'s `_hasArmedContinuation`, consuming the shared\n * controller's `isArmed()`.\n */\n private _hasArmedContinuation(): boolean {\n const pending = this._continuation.pending;\n return (\n pending !== null &&\n !pending.pastCoalesce &&\n this._autoContinuation.isArmed()\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 // An auto-continuation may be armed (#1650): the coalesce timer is\n // still pending or its drain is in flight. Report not-stable and wait\n // it out, mirroring `@cloudflare/ai-chat` — otherwise idle eviction /\n // recovery could act in the ~50ms window before the held continuation\n // fires (and the turn it enqueues then drains via the loop top).\n if (!this._hasArmedContinuation()) {\n return true;\n }\n if (\n (await this._awaitWithDeadline(\n new Promise<void>((resolve) =>\n setTimeout(resolve, AutoContinuationController.COALESCE_MS)\n ),\n deadline\n )) === TIMED_OUT\n ) {\n return false;\n }\n continue;\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 _awaitWithDeadline<T>(\n promise: Promise<T>,\n deadline: number | null\n ): Promise<T | typeof TIMED_OUT> {\n return awaitWithDeadline(promise, deadline);\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 return clientResolvableToolNames(this._lastClientTools);\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 return partAwaitsClientInteraction(part, clientResolvable);\n }\n\n // ── Chat recovery via fibers ───────────────────────────────────\n\n private _resolveChatRecoveryConfig(): ResolvedChatRecoveryConfig {\n // Delegates to the shared incident engine (agents/chat) so Think and\n // AIChatAgent resolve recovery config identically. See\n // design/rfc-chat-recovery-foundation.md.\n return resolveChatRecoveryConfig(this.chatRecovery);\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 // Storage read lives in the shared engine (agents/chat); this is the\n // package binding, symmetric with `AIChatAgent`.\n return readChatRecoveryProgress(this.ctx.storage);\n }\n\n /** Advance the durable recovery-progress counter. Called from\n * `_storeChunkDurably` when a stored chunk credits forward progress under the\n * shared rule (real, reconnect-immune forward progress). The increment lives\n * in the shared engine (agents/chat); this is the package binding. */\n private async _bumpChatRecoveryProgress(): Promise<void> {\n return bumpChatRecoveryProgress(this.ctx.storage);\n }\n\n /** Per-isolate N9 throttle gate (shared `agents/chat` helper); reset per\n * isolate so the first forwarded chunk after a restart always credits. */\n private _agentToolStreamProgress = new AgentToolStreamProgressThrottle();\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 if (this._agentToolStreamProgress.shouldCredit(Date.now())) {\n await this._bumpChatRecoveryProgress();\n }\n }\n\n private async _beginChatRecoveryIncident(input: {\n requestId: string;\n recoveryRootRequestId?: string | null;\n latestUserMessageId?: 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 // Incident orchestration (sweep -> read -> rehydrate interaction state ->\n // budget eval -> persist -> emit, with its ordering invariants) lives in the\n // shared ChatRecoveryEngine; this method is the package's adapter binding.\n // See design/rfc-chat-recovery-foundation.md.\n return this._chatRecoveryEngine().beginIncident(input);\n }\n\n /**\n * Lazily-built shared recovery engine. The adapter arrows capture `this`, so a\n * single cached instance is correct across calls (and across future engine\n * methods).\n */\n private _chatRecoveryEngineInstance?: ChatRecoveryEngine;\n private _chatRecoveryEngine(): ChatRecoveryEngine {\n return (this._chatRecoveryEngineInstance ??= new ChatRecoveryEngine({\n resolveConfig: () => this._resolveChatRecoveryConfig(),\n now: () => Date.now(),\n sweepStaleIncidents: (now) =>\n sweepStaleChatRecoveryIncidents(this.ctx.storage, now),\n getIncident: async (key) =>\n (await this.ctx.storage.get<ChatRecoveryIncident>(key)) ?? null,\n // Hibernation ordering guard. The budget decision consults\n // `hasPendingInteraction()` -> `_clientResolvableToolNames()` ->\n // `_lastClientTools` to keep a HITL turn (parked on a client-tool\n // `input-available` orphan) budget-free. On a fresh wake the base Agent\n // runs the boot-recovery path (`_handleInternalFiberRecovery`) BEFORE\n // onStart's `_restoreClientTools()`, so without this the in-memory cache\n // is empty and such a turn is misread as \"stuck\" and wrongly sealed (the\n // slow-human + deploy-churn case). Re-hydrate from the durable\n // `think_config` store — its own table, no Session init required, so the\n // read is safe this early; the guard keeps it idempotent with the later\n // onStart restore and a no-op on the live-isolate stall path where the\n // tools are already loaded. The engine invokes this BEFORE it reads\n // `isAwaitingClientInteraction()`.\n ensureInteractionStateLoaded: () => {\n if (this._lastClientTools === undefined) {\n this._restoreClientTools();\n }\n },\n // Messenger/workflow reply fibers (`think:messenger-reply`) are NOT chat\n // turns; the messenger runtime owns their recovery. The engine dispatches\n // this before the chat-fiber gate so such a fiber is never misread as an\n // orphaned chat turn. `Promise.resolve(false)` when no messenger runtime\n // is initialized (e.g. a child facet).\n tryHandleNonChatFiberRecovery: (ctx) =>\n this._messengerRuntime?.handleFiberRecovery(ctx) ??\n Promise.resolve(false),\n readProgress: () => this._chatRecoveryProgressMarker(),\n // A turn parked on a pending CLIENT interaction is waiting on the human,\n // not stuck, so the engine keeps it budget-free. SERVER-tool orphans are\n // excluded by `hasPendingInteraction` and still recover normally.\n isAwaitingClientInteraction: () => this.hasPendingInteraction(),\n putIncident: (key, incident) => this.ctx.storage.put(key, incident),\n deleteIncident: async (key) => {\n await this.ctx.storage.delete(key);\n },\n emitRecoveryEvent: (event) =>\n this._emit(event.type, {\n incidentId: event.incidentId,\n requestId: event.requestId,\n attempt: event.attempt,\n maxAttempts: event.maxAttempts,\n recoveryKind: event.recoveryKind,\n ...(event.reason ? { reason: event.reason } : {})\n }),\n scheduleRecovery: async (callback, data, reason, delaySeconds) => {\n await this.schedule(\n delaySeconds,\n callback,\n data,\n chatRecoverySchedulePolicy(reason)\n );\n },\n setRecovering: (active, requestId) =>\n this._setChatRecovering(active, requestId),\n onShouldKeepRecoveringError: (error) =>\n console.error(\n \"[Think] chatRecovery shouldKeepRecovering hook threw\",\n error\n ),\n exhaustChatRecovery: (incident, config, partial, streamId, createdAt) =>\n this._exhaustChatRecovery(\n incident,\n config,\n partial,\n streamId,\n createdAt\n ),\n resolveRecoveryStream: (requestId) =>\n this._resolveThinkRecoveryStream(requestId),\n getPartialStreamText: (streamId) => this._getPartialStreamText(streamId),\n activeChatRecoveryRootRequestId: () =>\n this._activeChatRecoveryRootRequestId,\n onGiveUpBookkeepingError: (phase, error) =>\n console.error(\n phase === \"read\"\n ? \"[Think] failed to read recovery incident during give-up; synthesizing\"\n : \"[Think] failed to persist sealed recovery incident during give-up\",\n error\n )\n } satisfies ChatRecoveryAdapter));\n }\n\n private async _updateChatRecoveryIncident(\n incidentId: string | undefined,\n status: ChatRecoveryIncident[\"status\"],\n reason?: string\n ): Promise<void> {\n // Incident state-machine transitions (delete-on-completed vs persist, the\n // completed/skipped/failed event emit, and the #1620 recovering-flag) live\n // in the shared ChatRecoveryEngine; this method is the package's adapter\n // binding, symmetric with `AIChatAgent`. The recovering-flag clear here\n // covers the benign-skip / failed paths that never reach a turn-level\n // terminal (exhaustion + normal completion also clear via\n // `_recordTerminalChatStatus`). See design/rfc-chat-recovery-foundation.md.\n return this._chatRecoveryEngine().updateIncident(\n incidentId,\n status,\n reason\n );\n }\n\n private async _exhaustChatRecovery(\n incident: ChatRecoveryIncident,\n config: ResolvedChatRecoveryConfig,\n // `parts` is the engine's vocabulary-agnostic `unknown[]`; Think owns the AI\n // SDK `UIMessage` vocabulary, so it re-asserts `MessagePart[]` at the\n // user-facing exhausted-context edge below.\n partial: { text: string; parts: unknown[] },\n streamId: string,\n createdAt: number\n ): Promise<void> {\n // Build + notification (event + onExhausted-swallow) and the\n // notify-before-terminalize invariant live in the engine helper; the\n // broadcast/terminal ordering inside `terminalize` is Think's own\n // (broadcast-first; see the note below). See\n // design/rfc-chat-recovery-foundation.md.\n await runChatRecoveryExhaustion(\n {\n incident,\n config,\n partialText: partial.text,\n partialParts: partial.parts as MessagePart[],\n streamId,\n createdAt\n },\n {\n emit: (event) => this._emit(\"chat:recovery:exhausted\", event),\n onExhausted: config.onExhausted,\n onError: (error) =>\n console.error(\"[Think] chatRecovery onExhausted hook threw\", error),\n terminalize: async (ctx) => {\n // Deliver the user-visible terminal banner BEFORE the bookkeeping\n // storage writes below. A `ctx.storage` write can reject mid-deploy\n // (the exact window recovery exhausts in), and if it threw before this\n // broadcast the user would be left staring at a half-finished message\n // with no terminal resolution. The broadcast itself touches no\n // storage, so ordering it first makes the banner resilient to a\n // failing `_recordTerminalChatStatus` / `_markRecoveredSubmissionInterrupted`.\n // `@cloudflare/ai-chat` terminalizes broadcast-first for the same\n // reason; only the set of durable writes below differs (Think also\n // writes a submission row).\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: ctx.requestId,\n body: ctx.terminalMessage,\n done: true,\n error: true\n });\n // Write the durable terminal record (#1645) FIRST among the storage\n // writes: it's the record a disconnected client replays on reconnect,\n // so it must not be skipped if the (independent) submission-row write\n // below throws.\n await this._recordTerminalChatStatus(\n \"interrupted\",\n ctx.requestId,\n ctx.terminalMessage\n );\n // The submission is keyed by the recovery ROOT request id;\n // `ctx.requestId` is the latest per-continuation id and won't match a\n // chained submission.\n await this._markRecoveredSubmissionInterrupted(\n ctx.recoveryRootRequestId ?? ctx.requestId,\n ctx.terminalMessage\n );\n }\n }\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 // 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._chatRecoveryEngine().scheduleRecovery({\n incident,\n recoveryKind: \"continue\",\n callback: \"_chatRecoveryContinue\",\n data: {\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 });\n return \"scheduled\";\n }\n\n protected override async _handleInternalFiberRecovery(\n ctx: FiberRecoveryContext\n ): Promise<boolean> {\n // The wake-recovery lifecycle (non-chat dispatch → chat gate → unwrap →\n // stream/partial → classify → begin-incident → exhausted-branch →\n // onChatRecovery → persist → complete → dispatch → catch→failed) lives in the\n // shared ChatRecoveryEngine; this binds the divergent organs as wake hooks,\n // symmetric with `AIChatAgent`. `Think` tracks terminal stream status and a\n // durable submission layer + session leaf, so its dispatch owns the\n // terminal-skip / submission-completion / interrupted-broadcast branches the\n // engine frame stays out of. See design/rfc-chat-recovery-foundation.md.\n return this._chatRecoveryEngine().handleChatFiberRecovery(ctx, {\n chatFiberPrefix: () =>\n (this.constructor as typeof Think).CHAT_FIBER_NAME + \":\",\n unwrapRecoverySnapshot: (fiber) => {\n const { snapshot, user } = unwrapChatFiberSnapshot<\"think-chat-turn\">(\n \"__cfThinkChatFiberSnapshot\",\n fiber.snapshot,\n \"think-chat-turn\"\n );\n return { snapshot, recoveryData: user };\n },\n classifyRecoveredTurn: (input) => this._classifyRecoveredThinkTurn(input),\n invokeOnChatRecovery: (input) =>\n this.onChatRecovery({\n incidentId: input.incident.incidentId,\n recoveryRootRequestId: input.recoveryRootRequestId,\n attempt: input.incident.attempt,\n maxAttempts: input.incident.maxAttempts,\n recoveryKind: input.recoveryKind,\n streamId: input.streamId,\n requestId: input.requestId,\n partialText: input.partial.text,\n // The engine seam is vocabulary-agnostic (`unknown[]`); Think owns the\n // AI SDK parts vocabulary, so re-assert it for the user-facing context.\n partialParts: input.partial.parts as MessagePart[],\n recoveryData: input.recoveryData,\n messages: [...this.messages],\n lastBody: input.snapshot?.lastBody ?? this._lastBody,\n lastClientTools:\n input.snapshot?.lastClientTools ?? this._lastClientTools,\n createdAt: input.createdAt\n }),\n shouldPersistOrphanedPartial: (input) =>\n this._shouldPersistOrphanedPartial(input.streamId, {\n streamStillActive: input.streamStillActive,\n streamIsTerminal:\n input.streamStatus === \"completed\" ||\n input.streamStatus === \"error\",\n snapshot: input.snapshot\n }),\n persistOrphanedStream: (streamId) =>\n this._persistOrphanedStream(streamId),\n completeRecoveredStream: (streamId) =>\n this._completeResumableStream(streamId),\n dispatchRecoveredTurn: (input) => this._dispatchRecoveredThinkTurn(input)\n } satisfies ChatFiberWakeHooks<ThinkRecoveryClassification>);\n }\n\n /**\n * Resolve the orphaned stream + its terminal status for a recovered chat turn.\n * Drives BOTH the wake path (full result) and the give-up terminalization\n * (which reads only `.streamId`; the terminal banner still fires when\n * `streamId` is `\"\"` — `_exhaustChatRecovery` does not require a stream).\n * Prefers the newest durable stream row keyed by the recovery-root request id;\n * falls back to the live active stream.\n */\n private _resolveThinkRecoveryStream(\n requestId: string\n ): ResolvedRecoveryStream {\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 const streamStillActive = Boolean(\n streamId &&\n this._resumableStream.hasActiveStream() &&\n this._resumableStream.activeStreamId === streamId\n );\n return { streamId, streamStillActive, streamStatus };\n }\n\n /**\n * Classify a recovered turn as `retry` or `continue`. A pre-stream turn with no\n * partial re-runs its user message (`retryTargetUserId`), unless the stream is\n * already terminal — a terminal stream is never retried (it completed), only\n * its submission is reconciled in dispatch.\n */\n private async _classifyRecoveredThinkTurn(\n input: ClassifyRecoveredTurnInput\n ): Promise<{\n recoveryKind: ChatRecoveryKind;\n detail: ThinkRecoveryClassification;\n }> {\n const streamIsTerminal =\n input.streamStatus === \"completed\" || input.streamStatus === \"error\";\n const retryTargetUserId = await this._recoverablePreStreamUserId(\n input.snapshot,\n input.streamId,\n input.partial\n );\n const shouldRetryBase = retryTargetUserId !== null && !streamIsTerminal;\n const recoveryKind: ChatRecoveryKind = shouldRetryBase\n ? \"retry\"\n : \"continue\";\n return { recoveryKind, detail: { retryTargetUserId } };\n }\n\n /**\n * The retry/continue/skip decision for a recovered chat turn, run after the\n * partial is persisted and the stream completed. Owns `Think`'s substrate\n * behavior the engine frame stays out of: a terminal stream reconciles the\n * durable submission (and is never retried/continued), and a `continue: false`\n * abandonment marks the submission interrupted + records a terminal status +\n * broadcasts so a reconnecting client is not frozen.\n */\n private async _dispatchRecoveredThinkTurn(\n input: DispatchRecoveredTurnInput<ThinkRecoveryClassification>\n ): Promise<void> {\n const {\n incident,\n options,\n snapshot,\n requestId,\n recoveryRootRequestId,\n streamStatus\n } = input;\n const { retryTargetUserId } = input.detail;\n const streamIsTerminal =\n streamStatus === \"completed\" || streamStatus === \"error\";\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._chatRecoveryEngine().scheduleRecovery({\n incident,\n recoveryKind: input.recoveryKind,\n callback: \"_chatRecoveryRetry\",\n data: {\n targetUserId: retryTargetUserId,\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n lastBody: snapshot?.lastBody ?? null,\n lastClientTools: snapshot?.lastClientTools ?? null,\n ...(recoveredRequestId ? { recoveredRequestId } : {})\n }\n });\n } else if (canContinue) {\n await this._chatRecoveryEngine().scheduleRecovery({\n incident,\n recoveryKind: input.recoveryKind,\n callback: \"_chatRecoveryContinue\",\n data: {\n ...(targetId ? { targetAssistantId: targetId } : {}),\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n ...(snapshot\n ? {\n lastBody: snapshot.lastBody ?? null,\n lastClientTools: snapshot.lastClientTools ?? null\n }\n : {}),\n ...(recoveredRequestId ? { recoveredRequestId } : {})\n }\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 is\n // correct), disabling recovery abandons the turn with no superseding turn.\n // 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\n private async _recoverablePreStreamUserId(\n snapshot: ChatFiberSnapshot | null,\n streamId: string,\n partial: { text: string; parts: unknown[] }\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 | 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 | 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 /**\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: ChatRecoveryScheduleCallback,\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined,\n maxAttempts: number\n ): Promise<boolean> {\n // The attempt-bump + scheduled/stable_timeout_retry persist + delayed\n // non-idempotent reschedule live in the shared ChatRecoveryEngine; this\n // method is the package's adapter binding, symmetric with `AIChatAgent`.\n // See design/rfc-chat-recovery-foundation.md.\n return this._chatRecoveryEngine().rescheduleAfterStableTimeout({\n incidentId: data?.incidentId,\n callback,\n data,\n fallbackMaxAttempts: maxAttempts\n });\n }\n\n /**\n * Park a recovery continuation that timed out waiting for stable state\n * because the turn is holding a pending CLIENT interaction (an\n * `input-available` client-tool part or an `approval-requested` part — see\n * `hasPendingInteraction`). Such a turn is WAITING ON THE HUMAN, not stuck:\n * the SPA replays the interrupted tool-result / approval after reconnect,\n * which drives a fresh continuation via the auto-continuation barrier\n * independently of the recovery retry loop. Burning the attempt budget on\n * that wait (each `waitUntilStable` times out because the human hasn't\n * answered) would seal a perfectly healthy turn on `stable_timeout` — the\n * exact symptom behind HITL \"session recovery errors\" under deploy churn.\n *\n * So instead of rescheduling or exhausting, we stop the loop and mark the\n * incident `skipped` (reason `awaiting_client_interaction`). That retains the\n * incident record (a later genuine interruption re-evaluates it) while\n * resolving the live \"recovering…\" indicator via `_updateChatRecoveryIncident`\n * so the client sees the parked tool-call UI rather than an eternal spinner.\n * A client that never returns is reclaimed by the incident TTL sweep and DO\n * idle-eviction. SERVER-tool orphans are excluded by `hasPendingInteraction`\n * (their `execute` died with the isolate), so they still recover normally.\n *\n * For a SUBMISSION-backed turn (`recoveredRequestId` present) the recovery\n * loop is the submission row's SOLE completion driver after a restart, and the\n * client's replay resumes the conversation as an independent auto-continuation\n * that never touches the submission. Parking would therefore leave the row\n * `running` until `_recoverSubmissionsOnStart` swept it to `error` on the next\n * restart. We instead complete it `completed` here: the park condition is a\n * fully-materialized client tool call in the leaf, which is exactly the\n * terminal state a non-interrupted submission reaches when its step emits a\n * client tool call (the model does not block on client tools — see\n * `_runProgrammaticMessagesTurn`, which marks such a step `completed`). The\n * human round-trip then proceeds via the normal auto-continuation, identical\n * to the non-crash flow.\n *\n * Returns `true` when the recovery was parked (caller must return), `false`\n * when there is no pending client interaction (caller proceeds to the normal\n * reschedule / exhaustion path).\n */\n private async _parkRecoveryForPendingInteraction(\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined\n ): Promise<boolean> {\n if (!this.hasPendingInteraction()) return false;\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"skipped\",\n \"awaiting_client_interaction\"\n );\n if (data?.recoveredRequestId) {\n await this._completeRecoveredSubmission(\n data.recoveredRequestId,\n \"completed\",\n null,\n null\n );\n }\n return true;\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-transient throw\n * in a recovery callback is SWALLOWED by `Agent._executeScheduleCallback`\n * (only a platform transient is re-thrown to preserve the one-shot row), so\n * without routing it here the alarm row is deleted with no terminal UX at\n * all — the half-finished message wedges silently. Shared by\n * `_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 seal is persisted only AFTER the\n * terminal writes in `_exhaustChatRecovery` succeed (see the ordering\n * note at the call below), so a give-up interrupted by a platform\n * transient re-runs in full instead of being half-sealed.\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 * Residual at-least-once edges, all 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 * • A platform transient interrupts `_exhaustChatRecovery` after the banner\n * broadcast — the deferred re-run re-fires `onExhausted` + the banner\n * (the terminal writes themselves are idempotent).\n */\n /**\n * Recovery continuation callbacks the alarm-boundary OOM circuit breaker may\n * back off / purge (#1825). See `Agent._cf_handleAlarmMemoryLimitReset`.\n */\n protected override _cf_recoveryAlarmCallbacks(): string[] {\n return [\"_chatRecoveryContinue\", \"_chatRecoveryRetry\"];\n }\n\n /**\n * Seal any still-live recovery incident as an out-of-memory exhaustion when\n * the alarm circuit breaker trips at its strike budget (#1825). Runs at the\n * outermost alarm frame (post-unwind), so the terminal banner / `onExhausted`\n * and the sealed-incident write can land where the mid-turn give-up's writes\n * OOMed. Reuses the shared give-up spine via `_exhaustRecoveryGiveUp`.\n */\n protected override async _cf_sealMemoryLimitedRecovery(): Promise<void> {\n const active = await listActiveChatRecoveryIncidents(this.ctx.storage);\n for (const { incident } of active) {\n const callback: ChatRecoveryScheduleCallback =\n incident.recoveryKind === \"retry\"\n ? \"_chatRecoveryRetry\"\n : \"_chatRecoveryContinue\";\n await this._exhaustRecoveryGiveUp(\n callback,\n { incidentId: incident.incidentId },\n \"out_of_memory\"\n );\n }\n }\n\n private _exhaustRecoveryGiveUp(\n callback: ChatRecoveryScheduleCallback,\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined,\n reason: string\n ): Promise<void> {\n // The give-up spine (read → re-entry-guard → build-exhausted-incident →\n // terminalize-before-seal → best-effort seal) lives in the shared\n // ChatRecoveryEngine; this is the package binding, symmetric with\n // `AIChatAgent`. Think keeps the `reason` parameter (its callers pass\n // `stable_timeout` | `recovery_error`) and the `recoveredRequestId` link in\n // the engine's root-id chain (supplied via the schedule payload). The\n // terminalize + stream/partial hooks are wired on the adapter above. See\n // design/rfc-chat-recovery-foundation.md.\n return this._chatRecoveryEngine().exhaustRecoveryGiveUp({\n callback,\n data,\n reason\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: ChatRecoveryScheduleCallback,\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined\n ): Promise<void> {\n return this._exhaustRecoveryGiveUp(callback, data, \"stable_timeout\");\n }\n\n /**\n * Apply the tight OOM-retry budget to a recovery error (#1825). Invoked from\n * `_handleRecoveryCallbackError`, i.e. for an OOM that is *thrown* out of a\n * recovery turn (typically from recovery bookkeeping or storage/SQL ops that\n * reject with the memory-limit-reset message after an isolate reset). An OOM\n * that surfaces as a returned `error` result means `continueLastTurn` already\n * terminalized the turn (client error frame + `onError`), so it is NOT routed\n * here — re-driving a terminalized turn would be wasteful and risk a second\n * terminal signal. `error` may be an Error or a wrapper with a `cause` chain.\n *\n * The reliable terminator is the begin-path (`evaluateChatRecoveryIncident`),\n * which seals once `oomAttempts` exceeds the budget; that runs before the\n * memory-heavy turn, in the low-memory window where writes succeed. This\n * method's job is to persist `oomAttempts` (small writes) so the begin path\n * can act on it, and to schedule a delayed re-run while under budget.\n *\n * Returns `true` when the error was an OOM and this method owns the outcome:\n * - under budget → a delayed re-run was scheduled (best-effort: a transient\n * spike may clear);\n * - over budget (or untrackable, or the bookkeeping itself OOMed) →\n * terminalized via the give-up path with `reason=\"out_of_memory\"`.\n * Returns `false` for non-OOM errors so the caller proceeds normally.\n */\n private async _handleRecoveryOom(\n callback: ChatRecoveryScheduleCallback,\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined,\n error: unknown\n ): Promise<boolean> {\n if (!isDurableObjectMemoryLimitReset(error)) return false;\n let decision: \"rescheduled\" | \"exhausted\" = \"exhausted\";\n try {\n decision = await this._chatRecoveryEngine().recordOomAndDecide({\n incidentId: data?.incidentId,\n callback,\n data,\n maxOomRetries: this._resolveChatRecoveryConfig().maxOomRetries\n });\n } catch (bookkeepingError) {\n // The bump/reschedule writes can themselves reject in the degraded isolate\n // that just OOMed. Fail closed (seal) rather than risk a silent wedge; the\n // finite `maxRecoveryWork` backstop covers anything that slips past.\n console.error(\n \"[Think] failed to record OOM recovery attempt; terminalizing\",\n bookkeepingError\n );\n decision = \"exhausted\";\n }\n if (decision === \"exhausted\") {\n await this._exhaustRecoveryGiveUp(callback, data, \"out_of_memory\");\n }\n return true;\n }\n\n /**\n * Handle an error thrown by `_chatRecoveryContinue` / `_chatRecoveryRetry`\n * after the incident was opened.\n *\n * - A platform transient (`isPlatformTransientError` from `agents` — a\n * deploy code-update reset / script supersede, a `retryable`-flagged\n * platform error, or \"Network connection lost.\", looking through wrappers\n * like `SqlError` via the `cause` chain) is re-thrown (after best-effort\n * marking the incident `failed` for observability) so\n * `Agent._executeScheduleCallback` preserves the one-shot alarm row and\n * the platform re-runs recovery once it is healthy again — the turn can\n * still recover, so it must NOT terminalize. Terminalizing here was the\n * #1730 freeze: the give-up's own seal needs the very storage that is\n * down, so it throws too, burns the in-process retry budget inside the\n * same reset window, and the row is consumed milliseconds before storage\n * recovers. The submission is deliberately left `running` — the deferred\n * re-run reads it via `_readRunningSubmissionByRequestId`, so marking it\n * terminal here would turn the preserved row into a guaranteed\n * `submission_not_running` no-op skip (a self-defeating defer).\n * - Any OTHER (application) 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-transient throw and then `alarm()` deletes the one-shot\n * row, so without terminalizing here the half-finished turn is dropped\n * with no terminal event and no banner (the user stares at a frozen\n * message until they send something new).\n */\n private async _handleRecoveryCallbackError(\n callback: ChatRecoveryScheduleCallback,\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined,\n error: unknown\n ): Promise<void> {\n // A memory-limit reset is NOT a platform transient (re-running the same\n // memory-heavy turn re-OOMs deterministically), so it must be classified\n // BEFORE the transient check and routed through the tight OOM-retry budget\n // instead of either deferring forever or terminalizing on the first hit\n // (#1825). Returns true once it has owned the outcome (rescheduled or\n // sealed); only fall through to the generic handling for non-OOM errors.\n if (await this._handleRecoveryOom(callback, data, error)) return;\n if (isPlatformTransientError(error)) {\n const message = error instanceof Error ? error.message : String(error);\n try {\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"failed\",\n message\n );\n } catch (bookkeepingError) {\n // Best-effort observability only — in the exact window this branch\n // fires (deploy reset / storage outage) the incident write itself can\n // reject; that must not replace the deferral with its own error.\n console.error(\n \"[Think] failed to mark recovery incident failed before deferring\",\n bookkeepingError\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 would be lost. Mirrors\n // `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 // PARK while a CLIENT interaction is pending — the turn is waiting for\n // the human, not churning; see `_chatRecoveryContinue` for the full\n // rationale.\n if (await this._parkRecoveryForPendingInteraction(data)) {\n return;\n }\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\n ? { signal: controller.signal, trigger: \"recovery-retry\" }\n : { trigger: \"recovery-retry\" }\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 // If this facet is an agent-tool child, its recovered turn just settled\n // outside `startAgentToolRun`'s finalizer — eagerly close the run so a\n // re-attached parent collects the terminal immediately rather than\n // waiting out a no-progress window. The pre-stream retry path settles a\n // fresh user turn that (like `continueLastTurn`) never hits the\n // finalizer, so it needs the same reconcile as `_chatRecoveryContinue`.\n await this._reconcileOwnStaleAgentToolChildRuns();\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 // PARK, don't burn the budget: a stable-state timeout while a CLIENT\n // interaction is pending is not churn — the turn is correctly waiting\n // for the SPA to replay an interrupted tool-result / approval after\n // reconnect, which drives a fresh continuation via the auto-continuation\n // barrier independently of this retry loop. Retrying here would just\n // time out again (the human hasn't answered) and eventually seal a\n // healthy turn on `stable_timeout`. So stop the loop, resolve the live\n // \"recovering…\" indicator, and let the client's replay resume the turn.\n if (await this._parkRecoveryForPendingInteraction(data)) {\n return;\n }\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\n ? { signal: controller.signal, trigger: \"recovery-continue\" }\n : { trigger: \"recovery-continue\" }\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 // If this facet is an agent-tool child, its recovered turn just settled\n // outside `startAgentToolRun`'s finalizer — eagerly close the run so a\n // re-attached parent collects the terminal immediately rather than\n // waiting out a no-progress window.\n await this._reconcileOwnStaleAgentToolChildRuns();\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 hasSettledToolResults: boolean;\n } {\n return aiSdkRecoveryCodec.toRecoveryPartial(\n this._resumableStream.getStreamChunks(streamId).map((chunk) => chunk.body)\n );\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 // A skipped turn settles out of the pre-stream set, but must NOT release\n // parked connections (#1784): a skip happens because a NEWER turn was\n // admitted (latest/merge supersede) or the queue generation advanced. The\n // earliest \"successor exists\" signal (`SubmitConcurrencyController.decide`)\n // fires before the successor's `_preStream.begin()`, so releasing here would\n // race a `begin()` that hasn't run yet and cut a parked client loose right\n // before the successor streams. Leave it parked: the successor flushes it on\n // stream start, or the final surviving turn's settle releases it. (Chat\n // clear releases parked connections explicitly via `resetTurnState`.)\n this._settlePreStreamTurn(requestId, { releaseParked: false });\n }\n\n /**\n * Mark an accepted turn (#1784) as settled. When `releaseParked` (the default)\n * and no accepted turn remains in flight and no stream is active, release every\n * connection parked on the pre-stream window with STREAM_RESUME_NONE. No-op once\n * they were flushed into STREAM_RESUMING on stream start. Skip paths pass\n * `releaseParked: false` so a parked client survives onto the successor turn\n * (see `_completeSkippedRequest`).\n */\n private _settlePreStreamTurn(\n requestId: string,\n options: { releaseParked?: boolean } = {}\n ): void {\n const idle = this._preStream.settle(requestId);\n const releaseParked = options.releaseParked ?? true;\n if (releaseParked && idle && !this._resumableStream.hasActiveStream()) {\n this._preStream.releaseAwaiting();\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 this._autoContinuation.schedule({\n connection,\n clientTools: this._lastClientTools,\n body: undefined,\n errorPrefix: \"[Think] Auto-continuation failed:\"\n });\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 this._autoContinuation.rearmForBatch();\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._autoContinuation.rearmForBatch();\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 _drainInteractionApplies(): Promise<void> {\n return drainInteractionApplies(\n () => this._continuation.pending !== null,\n () => 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 return hasIncompleteToolBatch(this.messages);\n }\n\n private _fireAutoContinuation(): void {\n const pending = this._continuation.pending;\n if (!pending) return;\n\n const { connection, requestId, clientTools } = pending;\n const abortSignal = this._aborts.getSignal(requestId);\n\n this._admitTurn({\n admission: \"queue\",\n trigger: \"auto-continuation\",\n requestId,\n continuation: true,\n allowNested: true,\n execute: 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 this._autoContinuation.activateDeferredAndReschedule();\n }\n\n /**\n * Run a continuation turn that does NOT require a live client connection.\n *\n * Used when a durable approval (a paused action or codemode execution) is\n * resolved via RPC from a surface with no open chat socket — e.g. an ops\n * dashboard, a webhook, or a voice backend approving hours/days later. The\n * connection-bound auto-continuation barrier (`_fireAutoContinuation`) cannot\n * fire without a `Connection`, so this mirrors its turn body but streams via\n * `broadcast` (a no-op when nobody is attached) and always persists, so a\n * client that reconnects later resumes the continued turn from history.\n *\n * Wrapped in `keepAliveWhile` because the resolving RPC returns before the\n * continuation finishes (mirrors the submission-drain pattern).\n */\n private _runConnectionlessContinuation(): void {\n void this.keepAliveWhile(async () => {\n const requestId = crypto.randomUUID();\n const abortSignal = this._aborts.getSignal(requestId);\n try {\n await this._admitTurn({\n admission: \"queue\",\n trigger: \"auto-continuation\",\n requestId,\n continuation: true,\n allowNested: true,\n execute: async () => {\n const continuationBody = 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: this._lastClientTools,\n body: this._lastBody,\n continuation: true\n })\n );\n if (result) {\n await this._streamResult(requestId, result, abortSignal, {\n continuation: true\n });\n }\n };\n\n if (this.chatRecovery) {\n await this._runChatRecoveryFiber(\n requestId,\n true,\n continuationBody\n );\n } else {\n await continuationBody();\n }\n }\n });\n } catch (error) {\n console.error(\"[Think] Connection-less continuation failed:\", error);\n } finally {\n this._aborts.remove(requestId);\n }\n });\n }\n\n // ── Response hook ──────────────────────────────────────────────\n\n /**\n * Render a reply attachment ({@link ReplyAttachment}) for delivery to the\n * active channel. Returns the text/markdown to post, or `undefined` to skip —\n * unknown types, or types a channel handles out of band (e.g. `voice_note`\n * via the voice transport). Override to customize per app/channel.\n */\n renderAttachment(\n attachment: ReplyAttachment\n ): string | { markdown: string } | undefined {\n switch (attachment.type) {\n case \"card\":\n return {\n markdown: `\\`\\`\\`json\\n${JSON.stringify(\n (attachment as { payload: unknown }).payload,\n null,\n 2\n )}\\n\\`\\`\\``\n };\n case \"email_draft\": {\n const draft = attachment as { subject?: string; to?: string[] };\n const lines = [\"**Email draft**\"];\n if (draft.to?.length) lines.push(`To: ${draft.to.join(\", \")}`);\n if (draft.subject) lines.push(`Subject: ${draft.subject}`);\n return { markdown: lines.join(\"\\n\") };\n }\n case \"voice_note\":\n return undefined;\n default:\n return undefined;\n }\n }\n\n /**\n * Deliver known reply attachments to the active channel (best-effort, never\n * fails the turn). Unknown types are ignored.\n */\n private async _renderChannelAttachments(\n attachments: ReplyAttachment[] | undefined\n ): Promise<void> {\n if (!attachments?.length) {\n return;\n }\n for (const attachment of attachments) {\n let rendered: string | { markdown: string } | undefined;\n try {\n rendered = this.renderAttachment(attachment);\n } catch (error) {\n console.warn(\n `[Think] renderAttachment threw: ${error instanceof Error ? error.message : String(error)}`\n );\n continue;\n }\n if (rendered === undefined) {\n continue;\n }\n try {\n await this.deliverNotice(rendered, { kind: \"interim\" });\n } catch (error) {\n console.warn(\n `[Think] failed to deliver channel attachment: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n }\n\n private async _fireResponseHook(result: ChatResponseResult): Promise<void> {\n // Surface advisory reply attachments recorded during this turn.\n result.attachments = this.replyAttachments(result.requestId);\n // Record the channel-level delivery for this turn (the turn-scoped channel\n // context is still set here — the response hook runs inside the turn body).\n const deliveredChannel = this._activeChannelContext;\n if (deliveredChannel) {\n this._emitChannelEvent({\n type: \"channel:delivered\",\n payload: {\n channel: deliveredChannel.channelId,\n kind: \"final\",\n turnEnded: true\n }\n });\n }\n await this._renderChannelAttachments(result.attachments);\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`/`interrupted`) or clear (on `completed`/`aborted`) the\n * durable terminal record so it can be replayed to clients on reconnect, and\n * resolve any in-progress \"recovering…\" indicator. A `completed`/`aborted`\n * turn is conveyed by the persisted messages, so the record is cleared; an\n * `error`/`interrupted` turn has no durable trace otherwise, so it is kept\n * until a later turn supersedes it.\n *\n * The storage primitives are shared with `@cloudflare/ai-chat`\n * (`_recordChatTerminal` / `_clearChatTerminal` / `_pendingChatTerminal`).\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._recordChatTerminal(requestId, body);\n } else {\n await this._clearChatTerminal();\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 /**\n * Persist a durable record of the last terminal turn so a client that\n * (re)connects after the turn ended still learns its outcome (#1645). Kept\n * until a later turn supersedes it (`_clearChatTerminal`); a single record is\n * sufficient because only the most recent terminal is relevant.\n */\n private async _recordChatTerminal(\n requestId: string,\n body: string\n ): Promise<void> {\n await recordChatTerminal(this.ctx.storage, requestId, body);\n }\n\n /** Clear the durable terminal record once a later turn supersedes it (#1645). */\n private async _clearChatTerminal(): Promise<void> {\n await clearChatTerminal(this.ctx.storage);\n }\n\n private async _pendingChatTerminal(): Promise<{\n requestId: string;\n body: string;\n } | null> {\n return pendingChatTerminal(this.ctx.storage);\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 await setChatRecovering(active, requestId, {\n storage: this.ctx.storage,\n messageType: MSG_CHAT_RECOVERING,\n broadcast: (frame) => this._broadcastChat(frame),\n now: Date.now()\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 an in-progress \"recovering…\" status (if any).\n *\n * A terminal error is deliberately NOT replayed here. A bare\n * `MSG_CHAT_RESPONSE` frame on connect is dropped by the `useAgentChat`\n * client because it never reaches a transport stream reader, so it cannot\n * become `useChat.error` — a failed turn would still look frozen (#1645).\n * The terminal outcome is instead surfaced over the resume handshake (the\n * shared {@link ResumeHandshake} drives `STREAM_RESUMING` → ACK → terminal\n * error frame), the only path that lands on the stream reader.\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 // Replay an in-progress \"recovering…\" status so a client that connects\n // mid-recovery reads the turn as working rather than frozen (#1620). This\n // is a plain status frame the client handles on connect (unlike a terminal\n // error, which must go through the resume handshake). It's mutually\n // exclusive with a terminal record (any terminal outcome clears recovering).\n // Skip a stale record (older than the flag TTL) so a turn whose recovery\n // was abandoned without a terminal can't show \"recovering…\" forever on\n // reconnect.\n const recoveringFrame = await buildChatRecoveringFrame(\n this.ctx.storage,\n MSG_CHAT_RECOVERING,\n Date.now()\n );\n if (recoveringFrame) {\n messages.push(recoveringFrame);\n }\n return messages;\n }\n\n // ── Resume helpers ──────────────────────────────────────────────\n\n /**\n * The shared resume-handshake driver (Tier-2). Lazily built; the\n * `ResumableStream` / `ContinuationState` / pending set are stable after\n * `onStart`, so a single instance threads them for the agent's lifetime. The\n * idle-connect payload (transcript + recovering, `_buildIdleConnectMessages`)\n * stays host-owned and is NOT part of the driver.\n */\n private _resumeHandshake(): ResumeHandshake {\n return (this._resumeHandshakeInstance ??= new ResumeHandshake({\n responseMessageType: MSG_CHAT_RESPONSE,\n resumableStream: this._resumableStream,\n continuation: this._continuation,\n preStream: this._preStream,\n pendingResumeConnections: this._pendingResumeConnections,\n pendingChatTerminal: () => this._pendingChatTerminal(),\n persistOrphanedStream: (streamId) =>\n this._persistOrphanedStream(streamId),\n isConnectionPresent: (connectionId) =>\n this.getConnection(connectionId) !== undefined\n }));\n }\n\n /**\n * Notify a connection about an active stream that can be resumed — delegates\n * to the shared {@link ResumeHandshake}. Kept as a thin method because it is\n * also called proactively from onConnect and the broadcast loop. See the\n * driver for the #1733 double-send contract.\n */\n private _notifyStreamResuming(connection: Connection): void {\n this._resumeHandshake().notifyStreamResuming(connection);\n }\n\n /**\n * Start a resumable stream and arm buffer cleanup. Wrapper around\n * `ResumableStream.start`: arming on START as well as finish guarantees a\n * stream whose DO is evicted mid-flight and never reaches a finish still gets\n * a future sweep instead of leaking its buffer.\n *\n * When a turn runs inside `runFiber` (durable recovery), the DO already\n * self-heals: `runFiber` holds `keepAlive`, which leaves a durable alarm in\n * storage that survives eviction, fires within ~keepAliveIntervalMs, and runs\n * the fiber-recovery scan — finalizing the stream (which arms cleanup) without\n * any client reconnect. Arming here is the safety net for any non-fiber stream\n * path, where no such alarm exists. The last-activity sweep threshold prevents\n * an actively streaming run from being reclaimed before it goes quiet (#1706).\n */\n protected _startResumableStream(\n requestId: string,\n options?: { messageId?: string }\n ): string {\n const streamId = this._resumableStream.start(requestId, options);\n // Flush connections parked during this turn's pre-stream window (#1784)\n // into STREAM_RESUMING now that a stream exists. No-op unless a client\n // reconnected before the first chunk. (Continuation-turn parks live in\n // `_continuation` and are flushed by the caller.)\n this._preStream.flushOnStreamStart((c) => this._notifyStreamResuming(c));\n void this._ensureStreamCleanupScheduled();\n return streamId;\n }\n\n /**\n * Mark a resumable stream completed and arm buffer cleanup. Wrapper around\n * `ResumableStream.complete` so every stream-finish path also schedules the\n * cleanup alarm (#1706).\n */\n protected _completeResumableStream(streamId: string): void {\n this._resumableStream.complete(streamId);\n void this._ensureStreamCleanupScheduled();\n }\n\n /**\n * Mark a resumable stream errored and arm buffer cleanup. Wrapper around\n * `ResumableStream.markError` — see {@link _completeResumableStream}.\n */\n protected _errorResumableStream(streamId: string): void {\n this._resumableStream.markError(streamId);\n void this._ensureStreamCleanupScheduled();\n }\n\n /**\n * Ensure a single cleanup alarm is pending for this DO's resumable-stream\n * buffers. Armed whenever a stream finishes so that idle/one-off chat DOs\n * still reclaim their buffers — the lazy sweep in {@link ResumableStream}\n * only fires when a *subsequent* stream completes, which never happens for a\n * chat that receives a single turn (#1706).\n *\n * `idempotent` dedupes on (callback, payload, owner) so repeated finishes\n * collapse onto one pending alarm rather than stacking.\n */\n protected async _ensureStreamCleanupScheduled({\n idempotent = true\n }: { idempotent?: boolean } = {}): Promise<void> {\n await this.schedule(\n STREAM_CLEANUP_DELAY_SECONDS,\n \"_cleanupStreamBuffers\",\n undefined,\n { idempotent }\n );\n }\n\n /**\n * Alarm callback: sweep aged stream buffers, re-arming while rows remain (see\n * the shared {@link cleanupStreamBuffers}).\n */\n async _cleanupStreamBuffers(): Promise<void> {\n await cleanupStreamBuffers(this._resumableStream, () =>\n this._ensureStreamCleanupScheduled({ idempotent: false })\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 // The accumulate loop and the `getMessage → update(merge) XOR append` upsert\n // are the shared `persistReconstructedOrphan` core. Think supplies the two\n // host-specific hooks:\n // - prepare: `_strippedForPersist` (same as `_persistAssistantMessage`) —\n // drop the internal final-answer parts and skip (`null`) an empty\n // structural-only assistant message.\n // - merge: Think replaces the whole message (no partial merge).\n // NOTE: progress is bumped at production/flush time in `_storeChunkDurably`\n // (#1637), NOT here — persisting on recovery or a client reconnect must not\n // be miscounted as new forward progress.\n const wrote = await persistReconstructedOrphan(chunks, {\n store: this._orphanStore(),\n fallbackId: crypto.randomUUID(),\n prepare: (message) => this._strippedForPersist(message),\n merge: (_existing, incoming) => incoming\n });\n if (wrote) this._broadcastMessages();\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\n// Register the HITL methods as client-callable. Imperative registration\n// (rather than `@callable()` decorator syntax on the methods) because TC39\n// decorators don't survive every consumer toolchain that compiles this file\n// from source (e.g. esbuild targeting ES2021).\nfor (const method of [\n Think.prototype.pendingExecutions,\n Think.prototype.pendingApprovals,\n Think.prototype.approveExecution,\n Think.prototype.rejectExecution\n]) {\n callable()(method, undefined as unknown as ClassMethodDecoratorContext);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgEA,SAAgB,2BACd,QACoC;CACpC,IAAI,WAAW,OAAO,OAAO;CAC7B,MAAM,OAAO,WAAW,OAAO,CAAC,IAAI;CACpC,OAAO;EACL,oBAAoB,KAAK,sBAAsB;EAC/C,cAAc,KAAK,gBAAgB,KAAK;EACxC,wBAAwB,KAAK,0BA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;CAYA,MAAgB,8BAA8B,EAC5C,aAAa,SACe,CAAC,GAAkB;EAC/C,MAAM,KAAK,SACT,8BACA,yBACA,KAAA,GACA,EAAE,WAAW,CACf;CACF;;;;;CAMA,MAAM,wBAAuC;EAC3C,MAAM,qBAAqB,KAAK,wBAC9B,KAAK,8BAA8B,EAAE,YAAY,MAAM,CAAC,CAC1D;CACF;CAEA,MAAc,uBAAuB,UAAiC;EACpE,KAAK,iBAAiB,YAAY;EAClC,MAAM,SAAS,KAAK,iBAAiB,gBAAgB,QAAQ;EAC7D,IAAI,OAAO,WAAW,GAAG;EAkBzB,IAAI,MANgB,2BAA2B,QAAQ;GACrD,OAAO,KAAK,aAAa;GACzB,YAAY,OAAO,WAAW;GAC9B,UAAU,YAAY,KAAK,oBAAoB,OAAO;GACtD,QAAQ,WAAW,aAAa;EAClC,CAAC,GACU,KAAK,mBAAmB;CACrC;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;AAh5ZE,MAAwB,cAAc;CACpC;CACA;CACA;CACA;AACF;AAmHA,MAAgB,kBAAkB;AAo6BlC,MAAe,sBAAsB;AA4BrC,MAAiB,4BAA4B,MAAU;AA81XzD,KAAK,MAAM,UAAU;CACnB,MAAM,UAAU;CAChB,MAAM,UAAU;CAChB,MAAM,UAAU;CAChB,MAAM,UAAU;AAClB,GACE,SAAS,CAAC,CAAC,QAAQ,KAAA,CAAmD"}
1
+ {"version":3,"file":"think.js","names":["Workspace","Session","withInvocationScope","agentContext"],"sources":["../src/media-eviction.ts","../src/channels/index.ts","../src/think.ts"],"sourcesContent":["/**\n * Aged-media eviction (#1710).\n *\n * Long-lived sessions accumulate inline base64 media — screenshot/image\n * tool results, data-URL file attachments — in the persisted transcript.\n * Read-time truncation hides that content from the model, but it stays in\n * storage forever and is rehydrated on every wake, so the boot footprint\n * grows with the number of images a session ever produced until SQLite's\n * allocator fails with `SQLITE_NOMEM`.\n *\n * This module rewrites oversized part values in AGED messages (the recent\n * tail is never touched) with small markers, optionally preserving the\n * original bytes as workspace files. Targets:\n *\n * - `file` parts whose `url` is a large `data:` URL — the part is\n * replaced with a text marker;\n * - large string values nested anywhere inside a tool part's `output` —\n * the string is replaced in place, preserving the container shape so\n * tool-specific `toModelOutput` handlers can still replay the result.\n *\n * Plain `text` parts are intentionally NOT evicted: they are user-visible\n * prose, and the row-size limit already bounds them at write time.\n */\n\nimport type { UIMessage } from \"ai\";\n\nexport interface MediaEvictionConfig {\n /**\n * Messages at the tail of the active path that are never evicted.\n * Think clamps this to at least the read-time truncation window\n * (4 messages — the recent span the model replays at full fidelity),\n * so a misconfigured low value can never strip content the model\n * still sees.\n * @default 8\n */\n keepRecentMessages?: number;\n /**\n * Minimum serialized size (in characters; base64 is ASCII so this equals\n * bytes for media) of a single part value to evict.\n * @default 32 * 1024\n */\n minPartBytes?: number;\n /**\n * Preserve evicted values as workspace files under\n * `/attachments/evicted/` instead of dropping them. The marker records\n * the file path.\n * @default true\n */\n externalizeToWorkspace?: boolean;\n /**\n * Maximum oversized stored rows processed per pass. Bounds how long a\n * single pass can take; remaining rows are picked up by later passes.\n * @default 64\n */\n maxRowsPerPass?: number;\n}\n\nexport interface ResolvedMediaEvictionConfig {\n keepRecentMessages: number;\n minPartBytes: number;\n externalizeToWorkspace: boolean;\n maxRowsPerPass: number;\n}\n\nexport function resolveMediaEvictionConfig(\n config: MediaEvictionConfig | boolean\n): ResolvedMediaEvictionConfig | null {\n if (config === false) return null;\n const base = config === true ? {} : config;\n return {\n keepRecentMessages: base.keepRecentMessages ?? 8,\n minPartBytes: base.minPartBytes ?? 32 * 1024,\n externalizeToWorkspace: base.externalizeToWorkspace ?? true,\n maxRowsPerPass: base.maxRowsPerPass ?? 64\n };\n}\n\n/** An oversized value extracted from a message, to be written to the workspace. */\nexport interface EvictedBlob {\n path: string;\n data: string;\n mediaType?: string;\n}\n\nexport interface EvictMessageResult {\n message: UIMessage;\n changed: boolean;\n /** Individual oversized values evicted. */\n parts: number;\n /** Total characters removed from the serialized message. */\n bytes: number;\n /** Values to persist before the rewritten row is stored (may be empty). */\n blobs: EvictedBlob[];\n}\n\nexport interface EvictMessageOptions {\n minPartBytes: number;\n /** When false, evicted values are dropped and markers record size only. */\n externalize: boolean;\n /** Workspace path for the n-th evicted value of this message. */\n pathFor: (index: number, extension: string) => string;\n}\n\nconst MAX_WALK_DEPTH = 8;\n\n/**\n * Replace oversized media values in a message with markers.\n * Returns a new message — the input is not mutated.\n */\nexport function evictLargeMediaFromMessage(\n message: UIMessage,\n options: EvictMessageOptions\n): EvictMessageResult {\n const state = {\n options,\n parts: 0,\n bytes: 0,\n blobs: [] as EvictedBlob[]\n };\n\n let changed = false;\n const parts = message.parts.map((part) => {\n // Large data-URL file attachments → text marker.\n if (part.type === \"file\" && \"url\" in part) {\n const url = (part as { url: string }).url;\n if (\n typeof url === \"string\" &&\n url.startsWith(\"data:\") &&\n url.length >= options.minPartBytes\n ) {\n changed = true;\n const mediaType =\n (part as { mediaType?: string }).mediaType ?? dataUrlMediaType(url);\n const path = extractBlob(state, url, mediaType);\n return {\n type: \"text\" as const,\n text: evictionMarker(url.length, path, mediaType)\n };\n }\n return part;\n }\n\n // Large strings nested in tool outputs → marker strings in place.\n if (\n (part.type.startsWith(\"tool-\") || part.type === \"dynamic-tool\") &&\n \"output\" in part\n ) {\n const output = (part as { output?: unknown }).output;\n if (output !== undefined) {\n const before = state.parts;\n const evicted = walkAndEvict(state, output, 0);\n if (state.parts > before) {\n changed = true;\n return { ...part, output: evicted };\n }\n }\n }\n\n return part;\n }) as UIMessage[\"parts\"];\n\n return {\n message: changed ? { ...message, parts } : message,\n changed,\n parts: state.parts,\n bytes: state.bytes,\n blobs: state.blobs\n };\n}\n\ntype WalkState = {\n options: EvictMessageOptions;\n parts: number;\n bytes: number;\n blobs: EvictedBlob[];\n};\n\nfunction walkAndEvict(\n state: WalkState,\n value: unknown,\n depth: number\n): unknown {\n if (typeof value === \"string\") {\n if (value.length < state.options.minPartBytes) return value;\n const mediaType = value.startsWith(\"data:\")\n ? dataUrlMediaType(value)\n : undefined;\n const path = extractBlob(state, value, mediaType);\n return evictionMarker(value.length, path, mediaType);\n }\n\n if (value === null || typeof value !== \"object\" || depth >= MAX_WALK_DEPTH) {\n return value;\n }\n\n if (Array.isArray(value)) {\n let changed = false;\n const result = value.map((item) => {\n const next = walkAndEvict(state, item, depth + 1);\n if (next !== item) changed = true;\n return next;\n });\n return changed ? result : value;\n }\n\n let changed = false;\n const result: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n const next = walkAndEvict(state, entry, depth + 1);\n if (next !== entry) changed = true;\n result[key] = next;\n }\n return changed ? result : value;\n}\n\n/** Record an evicted value; returns its workspace path or null when dropped. */\nfunction extractBlob(\n state: WalkState,\n data: string,\n mediaType: string | undefined\n): string | null {\n state.parts++;\n state.bytes += data.length;\n if (!state.options.externalize) return null;\n const path = state.options.pathFor(\n state.blobs.length,\n extensionFor(mediaType)\n );\n state.blobs.push({ path, data, mediaType });\n return path;\n}\n\nfunction evictionMarker(\n bytes: number,\n path: string | null,\n mediaType?: string\n): string {\n const media = mediaType ? `${mediaType}, ` : \"\";\n return path\n ? `[evicted ${media}${bytes} bytes; preserved at ${path}]`\n : `[evicted ${media}${bytes} bytes]`;\n}\n\nfunction dataUrlMediaType(url: string): string | undefined {\n const match = /^data:([^;,]+)/.exec(url);\n return match?.[1] || undefined;\n}\n\nfunction extensionFor(mediaType: string | undefined): string {\n if (!mediaType) return \"txt\";\n const subtype = mediaType.split(\"/\")[1]?.replace(/[^a-zA-Z0-9]/g, \"\");\n return subtype || \"bin\";\n}\n","import type { ToolSet } from \"ai\";\nimport type {\n MessengerCapabilities,\n MessengerContext,\n MessengerConversationMode,\n MessengerConversationResolver,\n MessengerDefinition,\n MessengerDeliveryPolicy,\n MessengerDeliverySurface,\n ThinkMessengers\n} from \"../messengers\";\n\n/** Surface family for a channel. Drives the default ingress/delivery wiring. */\nexport type ChannelKind = \"messenger\" | \"web\" | \"voice\" | \"custom\";\n\n/** A channel's capabilities are the same shape as a messenger's. */\nexport type ChannelCapabilities = MessengerCapabilities;\n\n/** A channel's delivery policy is the same shape as a messenger's. */\nexport type ChannelDeliveryPolicy = MessengerDeliveryPolicy;\n\n/** Where a channel posts replies/notices. */\nexport type ChannelDeliverySurface = MessengerDeliverySurface;\n\n/**\n * How events arrive for a channel. A discriminated union so `web`/`voice` do\n * not have to invent webhook fields they don't use. The `webhook` transport is\n * exactly today's messenger ingress (a full {@link MessengerDefinition}).\n */\nexport type ChannelIngress =\n | ({ transport: \"webhook\" } & MessengerDefinition)\n | { transport: \"websocket\" }\n | { transport: \"voice\" };\n\n/**\n * Turn-scoped context the runtime sets when a turn resolves to a channel. For\n * `kind: \"messenger\"` it wraps the existing {@link MessengerContext}.\n */\nexport interface ChannelContext {\n channelId: string;\n kind: ChannelKind;\n capabilities?: ChannelCapabilities;\n messenger?: MessengerContext;\n thread?: string;\n}\n\n/**\n * The public channel contract — the generalization of a messenger: an ingress,\n * a delivery surface, capabilities, conversation routing, a delivery policy, and\n * (new) per-channel policy.\n */\nexport interface ChannelDefinition {\n kind: ChannelKind;\n capabilities?: ChannelCapabilities;\n conversation?: MessengerConversationMode | MessengerConversationResolver;\n delivery?: ChannelDeliveryPolicy;\n /** Per-channel instructions, prepended to the system prompt for this channel. */\n instructions?: string | ((ctx: ChannelContext) => string | Promise<string>);\n /** Narrow the assembled tool set for this channel. */\n tools?: (all: ToolSet) => ToolSet;\n /** Per-channel cap on model steps for a turn. */\n maxTurns?: number;\n ingress: ChannelIngress;\n}\n\nexport type ThinkChannels = Record<string, ChannelDefinition>;\n\nexport type NormalizedChannelDefinition = ChannelDefinition & { id: string };\n\n/** Wrap a {@link MessengerDefinition} as a `kind: \"messenger\"` channel. */\nexport function messengerChannel(\n definition: MessengerDefinition\n): ChannelDefinition {\n return {\n kind: \"messenger\",\n capabilities: definition.capabilities,\n conversation: definition.conversation,\n delivery: definition.delivery,\n ingress: { transport: \"webhook\", ...definition }\n };\n}\n\nfunction messengerFromChannel(\n definition: ChannelDefinition\n): MessengerDefinition | undefined {\n const ingress = definition.ingress;\n if (ingress.transport !== \"webhook\") {\n return undefined;\n }\n const { transport: _transport, ...messenger } = ingress;\n return messenger;\n}\n\nconst IMPLICIT_WEB_CHANNEL: ChannelDefinition = {\n kind: \"web\",\n capabilities: { canStream: true, canEditMessages: true },\n ingress: { transport: \"websocket\" }\n};\n\nexport interface ResolvedChannels {\n /** Every resolved channel keyed by id (registry for per-channel policy). */\n channels: Map<string, NormalizedChannelDefinition>;\n /** Messenger-kind channels mapped back to the runtime's input shape. */\n messengers: ThinkMessengers;\n}\n\n/**\n * Merge the implicit `web` channel, `configureChannels()` entries, and\n * `getMessengers()` entries into a single channel registry, and extract the\n * messenger definitions that feed the unchanged `ThinkMessengerRuntime`.\n *\n * Resolution order: (1) implicit `web`; (2) `configureChannels()`; (3) each\n * `getMessengers()` entry as a `kind: \"messenger\"` channel. A duplicate id\n * across (2) and (3) throws.\n */\nexport function resolveChannels(\n configured: ThinkChannels,\n messengers: ThinkMessengers\n): ResolvedChannels {\n const channels = new Map<string, NormalizedChannelDefinition>();\n channels.set(\"web\", { ...IMPLICIT_WEB_CHANNEL, id: \"web\" });\n\n for (const [id, definition] of Object.entries(configured)) {\n // `web` is reserved for the built-in WebSocket chat surface. Users may\n // override its *policy* (instructions / tool narrowing / maxTurns) with a\n // `{ kind: \"web\" }` entry, but replacing it with another kind would silently\n // break the native chat ingress/delivery path — reject that footgun loudly.\n if (id === \"web\") {\n if (definition.kind !== \"web\") {\n throw new Error(\n `Channel \"web\" is reserved for the built-in WebSocket chat surface; configureChannels() may override its policy with a { kind: \"web\" } entry but cannot replace it with kind \"${definition.kind}\"`\n );\n }\n // Merge over the implicit web defaults so a policy-only override (e.g.\n // just `instructions`) keeps the built-in capabilities/ingress instead of\n // silently dropping them.\n channels.set(\"web\", {\n ...IMPLICIT_WEB_CHANNEL,\n ...definition,\n id: \"web\"\n });\n continue;\n }\n channels.set(id, { ...definition, id });\n }\n\n const messengerDefs: ThinkMessengers = {};\n\n for (const [id, definition] of Object.entries(configured)) {\n const messenger = messengerFromChannel(definition);\n if (definition.kind === \"messenger\" && messenger) {\n messengerDefs[id] = messenger;\n }\n }\n\n for (const [id, definition] of Object.entries(messengers)) {\n // Same reservation as the configureChannels() path: a messenger named\n // \"web\" would overwrite the built-in WebSocket chat surface with a\n // kind: \"messenger\" channel and break native chat ingress/delivery.\n if (id === \"web\") {\n throw new Error(\n `Channel \"web\" is reserved for the built-in WebSocket chat surface and cannot be declared as a messenger via getMessengers()`\n );\n }\n if (Object.prototype.hasOwnProperty.call(configured, id)) {\n throw new Error(\n `Channel id \"${id}\" is declared by both configureChannels() and getMessengers(); channel ids must be unique`\n );\n }\n channels.set(id, { ...messengerChannel(definition), id });\n messengerDefs[id] = definition;\n }\n\n return { channels, messengers: messengerDefs };\n}\n","/**\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 a model id string (resolved via the\n * built-in workers-ai-provider) or a LanguageModel\n * - getSystemPrompt() — return the legacy fallback system prompt\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 *\n * export class MyAgent extends Think<Env> {\n * getModel() {\n * // A string is resolved via the built-in workers-ai-provider off env.AI.\n * // Use a \"@cf/...\" id for Workers AI, or a \"provider/model\" slug like\n * // \"openai/gpt-5.5\" to route through AI Gateway.\n * return \"@cf/moonshotai/kimi-k2.7-code\";\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 { AsyncLocalStorage } from \"node:async_hooks\";\nimport * as aiSdk from \"ai\";\nimport type {\n FlexibleSchema,\n InferSchema,\n InferToolOutput,\n LanguageModel,\n ModelMessage,\n PrepareStepFunction,\n PrepareStepResult,\n StreamTextOnChunkCallback,\n GenerateTextOnStepFinishCallback,\n StopCondition,\n ToolSet,\n TypedToolCall,\n UIMessage\n} from \"ai\";\nimport {\n convertToModelMessages,\n hasToolCall,\n jsonSchema,\n // `stepCountIs` exists in both AI SDK v6 and v7 (v7 keeps it as an alias of\n // `isStepCount`). Using it keeps Think compatible with both majors.\n stepCountIs,\n streamText,\n tool\n} from \"ai\";\n/**\n * Callback type for the AI SDK tool-execution-finished hook, derived from\n * `streamText`'s options so it resolves under both AI SDK v6 and v7 (the\n * exported `OnToolExecutionEndCallback` type is v7-only).\n */\ntype ToolCallFinishCallback = NonNullable<\n Parameters<typeof streamText>[0][\"experimental_onToolCallFinish\"]\n>;\nimport { wrapAISDK } from \"agents/observability/ai\";\nimport { createWorkersAI } from \"workers-ai-provider\";\nimport { anthropic } from \"workers-ai-provider/anthropic\";\nimport { openai } from \"workers-ai-provider/openai\";\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 callable,\n getCurrentAgent,\n isDurableObjectMemoryLimitReset,\n isPlatformTransientError,\n __DO_NOT_USE_WILL_BREAK__agentContext as agentContext,\n __DO_NOT_USE_WILL_BREAK__withInvocationScope as withInvocationScope\n} from \"agents\";\n\nconst agentToolChunkEncoder = new TextEncoder();\nconst agentsAISDKInvocationBounded = Symbol.for(\n \"cloudflare.agents.ai-sdk.invocation-bounded\"\n);\nconst usesAISDKV7Telemetry = \"registerTelemetry\" in aiSdk;\nimport type {\n AgentToolLifecycleResult,\n AgentToolMilestone,\n AgentToolProgress,\n AgentToolProgressSnapshot,\n AgentToolRunInfo,\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 cleanupStreamBuffers,\n STREAM_CLEANUP_DELAY_SECONDS,\n ContinuationState,\n PreStreamTurns,\n AutoContinuationController,\n TIMED_OUT,\n awaitWithDeadline,\n drainInteractionApplies,\n interceptAgentToolBroadcast,\n AgentToolProgressEmitter,\n SubmitConcurrencyController,\n createToolsFromClientSchemas,\n AbortRegistry,\n applyToolUpdate,\n toolResultUpdate,\n crossMessageToolResultUpdate,\n toolApprovalUpdate,\n pausedExecutionUpdate,\n hasIncompleteToolBatch,\n partAwaitsClientInteraction,\n clientResolvableToolNames,\n parseProtocolMessage,\n aiSdkRecoveryCodec,\n ResumeHandshake,\n normalizeToolInput,\n repairInterruptedToolParts,\n toolPartHasSettledResult,\n persistReconstructedOrphan,\n reconcileMessages,\n resolveToolMergeId,\n createChatFiberSnapshot,\n unwrapChatFiberSnapshot,\n wrapChatFiberSnapshot,\n MAX_BOUND_PARAMS,\n buildInClauseStrings,\n resolveChatRecoveryConfig,\n chatRecoverySchedulePolicy,\n ChatRecoveryEngine,\n runChatRecoveryExhaustion,\n ChatStreamStalledError,\n iterateWithStallWatchdog,\n sweepStaleChatRecoveryIncidents,\n listActiveChatRecoveryIncidents,\n readChatRecoveryProgress,\n bumpChatRecoveryProgress,\n recordChatTerminal,\n clearChatTerminal,\n pendingChatTerminal,\n buildChatRecoveringFrame,\n setChatRecovering,\n AgentToolStreamProgressThrottle,\n StreamProgressCreditThrottle,\n shouldCreditStreamProgress,\n classifyAgentToolChildRecovery,\n type ChatRecoveryAdapter,\n type ChatFiberWakeHooks,\n type ResolvedRecoveryStream,\n type ClassifyRecoveredTurnInput,\n type DispatchRecoveredTurnInput,\n type ChatRecoveryScheduleCallback,\n type ChatRecoveryIncident,\n type ChatRecoveryKind\n} from \"agents/chat\";\nimport type {\n StreamChunkData,\n ClientToolSchema,\n ClientToolExecutor,\n MessagePart,\n SubmitConcurrencyDecision,\n ChatFiberSnapshot,\n OrphanPersistStore\n} from \"agents/chat\";\nimport { Session } from \"agents/experimental/memory/session\";\nimport type { SessionMessage } from \"agents/experimental/memory/session\";\nimport { truncateOlderMessages } from \"agents/experimental/memory/utils\";\nimport {\n evictLargeMediaFromMessage,\n resolveMediaEvictionConfig,\n type MediaEvictionConfig,\n type ResolvedMediaEvictionConfig\n} from \"./media-eviction\";\n\n/**\n * The recent-message span the model sees at FULL fidelity each turn —\n * `truncateOlderMessages`' default `keepRecent` (see `_assembleModelMessages`).\n *\n * Both memory bounds are anchored to this window (#1710):\n * - budgeted hydration never shrinks `this.messages` below it (the floor\n * passed to `session.getRecentHistory`), so windowing cannot starve the\n * model's context;\n * - media eviction never rewrites messages inside it (the\n * `keepRecentMessages` clamp), so content the model still replays at full\n * fidelity is never replaced with markers.\n */\nconst MODEL_RECENT_WINDOW = 4;\nconst DEFAULT_ACTION_TIMEOUT_MS = 30_000;\nconst ACTION_OUTPUT_MAX_CHARS = 20_000;\nconst MAX_REPLY_ATTACHMENTS_PER_TURN = 32;\nconst ACTION_LEDGER_SWEEP_INTERVAL_MS = 60 * 60 * 1000;\nconst ACTION_LEDGER_LAST_SWEPT_KEY = \"cf_think_action_ledger:last_swept_at\";\nconst ACTION_PENDING_SWEEP_INTERVAL_MS = 60 * 60 * 1000;\nconst ACTION_PENDING_LAST_SWEPT_KEY =\n \"cf_think_action_pending_approvals:last_swept_at\";\n/** Prefix for durable-pause action execution ids (vs codemode execution ids). */\nconst ACTION_PAUSE_ID_PREFIX = \"actpause_\";\nimport { Workspace } from \"@cloudflare/shell\";\nimport { createWorkspaceTools } from \"./tools/workspace\";\nimport { createFetchTools } from \"./tools/fetch\";\nimport type { CreateFetchToolsOptions, FetchToolEvent } from \"./tools/fetch\";\nimport { truncatePausedExecutionOutput } from \"./tools/execute\";\nimport { ExtensionManager, sanitizeName } from \"./extensions/manager\";\nimport { ThinkMessengerRuntime } from \"./messengers/chat-sdk\";\nimport type {\n DeliveryKind,\n MessengerContext,\n MessengerDeliverySurface,\n ThinkMessengers,\n MessengerThinkHost\n} from \"./messengers\";\nimport { resolveChannels } from \"./channels\";\nimport type {\n ChannelContext,\n NormalizedChannelDefinition,\n ThinkChannels\n} from \"./channels\";\n\nexport { messengerChannel } from \"./channels\";\nexport type {\n ChannelCapabilities,\n ChannelContext,\n ChannelDefinition,\n ChannelDeliveryPolicy,\n ChannelDeliverySurface,\n ChannelIngress,\n ChannelKind,\n NormalizedChannelDefinition,\n ThinkChannels\n} from \"./channels\";\nexport type { DeliveryKind, DeliveryTag } from \"./messengers\";\nexport { Session } from \"agents/experimental/memory/session\";\nexport type { SessionMessage } 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\";\nexport type {\n CreateFetchToolsOptions,\n FetchBindingTarget,\n FetchResult,\n FetchToolEvent,\n FetchErrorCode,\n FetchResponseMode,\n FetchRedirectPolicy\n} from \"./tools/fetch\";\n\ntype AgentSpanAttributes = Readonly<\n Record<string, string | number | boolean | undefined>\n>;\n\ntype UpdateAgentSpan = (attributes: AgentSpanAttributes) => void;\n\ntype AgentSpanHost = {\n _withAgentSpan<T>(\n operation: string,\n storagePhase: string,\n attributes: AgentSpanAttributes,\n run: (update: UpdateAgentSpan) => T | Promise<T>\n ): T | Promise<T>;\n};\n\nfunction withAgentSpan<T>(\n host: object,\n operation: string,\n storagePhase: string,\n attributes: AgentSpanAttributes,\n run: (update: UpdateAgentSpan) => Promise<T>\n): Promise<T>;\nfunction withAgentSpan<T>(\n host: object,\n operation: string,\n storagePhase: string,\n attributes: AgentSpanAttributes,\n run: (update: UpdateAgentSpan) => T\n): T;\nfunction withAgentSpan<T>(\n host: object,\n operation: string,\n storagePhase: string,\n attributes: AgentSpanAttributes,\n run: (update: UpdateAgentSpan) => T | Promise<T>\n): T | Promise<T> {\n return (host as AgentSpanHost)._withAgentSpan(\n operation,\n storagePhase,\n attributes,\n run\n );\n}\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_MESSAGE_UPDATED = CHAT_MESSAGE_TYPES.MESSAGE_UPDATED;\nconst MSG_CHAT_RECOVERING = CHAT_MESSAGE_TYPES.CHAT_RECOVERING;\n\nfunction shouldMarkSkippedAfterGenerationChange(\n status: SaveMessagesResult[\"status\"]\n): boolean {\n return status === \"completed\";\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === undefined) return \"undefined\";\n if (typeof value === \"function\" || typeof value === \"symbol\") {\n return String(value);\n }\n if (value === null || typeof value !== \"object\") {\n if (typeof value === \"bigint\") return `${value.toString()}n`;\n return JSON.stringify(value) ?? \"undefined\";\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 stableJsonEqual(left: unknown, right: unknown): boolean {\n return stableStringify(left) === stableStringify(right);\n}\n\nfunction actionErrorEnvelope(error: unknown): {\n error: { name: string; message: string };\n} {\n return {\n error: {\n name: error instanceof Error ? error.name : \"Error\",\n message: error instanceof Error ? error.message : String(error)\n }\n };\n}\n\nfunction streamErrorToString(error: unknown): string {\n if (error instanceof Error) return error.message;\n if (typeof error === \"string\") return error;\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n}\n\n/**\n * Normalizes the AI SDK tool-execution-finished event across major versions.\n *\n * Think registers a single `experimental_onToolCallFinish` callback, which is\n * the native option in AI SDK v6 and a supported alias for `onToolExecutionEnd`\n * in AI SDK v7 (resolved internally — see `ai`'s `streamText`). The two majors\n * hand the callback different event shapes:\n *\n * - v6: `{ toolCall, messages, success, output, error, durationMs, stepNumber }`\n * - v7: `{ toolCall, messages, toolExecutionMs, toolOutput: { type, output|error } }`\n * (no `stepNumber`)\n *\n * This collapses both into one shape so the rest of Think stays version-agnostic.\n */\nfunction normalizeToolFinishEvent(event: unknown): {\n toolCall: TypedToolCall<ToolSet>;\n messages: ModelMessage[];\n toolExecutionMs: number;\n stepNumber: number | undefined;\n success: boolean;\n output: unknown;\n error: unknown;\n} {\n const e = event as {\n toolCall: TypedToolCall<ToolSet>;\n messages: ModelMessage[];\n // v7\n toolExecutionMs?: number;\n toolOutput?: { type: string; output?: unknown; error?: unknown };\n // v6\n durationMs?: number;\n success?: boolean;\n output?: unknown;\n error?: unknown;\n stepNumber?: number;\n };\n const toolExecutionMs = e.toolExecutionMs ?? e.durationMs ?? 0;\n if (e.toolOutput) {\n const success = e.toolOutput.type === \"tool-result\";\n return {\n toolCall: e.toolCall,\n messages: e.messages,\n toolExecutionMs,\n // v7 does not provide a step number on this event.\n stepNumber: undefined,\n success,\n output: success ? e.toolOutput.output : undefined,\n error: success ? undefined : e.toolOutput.error\n };\n }\n const success = e.success ?? false;\n return {\n toolCall: e.toolCall,\n messages: e.messages,\n toolExecutionMs,\n stepNumber: e.stepNumber,\n success,\n output: success ? e.output : undefined,\n error: success ? undefined : e.error\n };\n}\n\nasync function* readableStreamToAsyncIterable<T>(\n stream: ReadableStream<T>\n): AsyncIterable<T> {\n const reader = stream.getReader();\n try {\n while (true) {\n const next = await reader.read();\n if (next.done) return;\n yield next.value;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\nfunction actionAuthorizationErrorEnvelope(\n reason: string | undefined,\n permissions: string[]\n): {\n error: { name: string; message: string; permissions: string[] };\n} {\n return {\n error: {\n name: \"ActionAuthorizationError\",\n message: reason ?? \"Action is not authorized\",\n permissions\n }\n };\n}\n\nfunction actionApprovalInputErrorEnvelope(): {\n error: { name: string; message: string };\n} {\n return {\n error: {\n name: \"ActionApprovalInputError\",\n message: \"Approved action input cannot be changed by beforeToolCall\"\n }\n };\n}\n\nfunction actionPendingErrorEnvelope(): {\n error: { name: string; message: string };\n} {\n return {\n error: {\n name: \"ActionPendingError\",\n message:\n \"A prior attempt of this action is in an unknown state; not re-executed. Manual reconciliation may be required.\"\n }\n };\n}\n\nfunction actionKeyConflictEnvelope(\n actionName: string,\n key: string\n): {\n error: { name: string; message: string };\n} {\n return {\n error: {\n name: \"ActionKeyConflict\",\n message: `Idempotency key \"${key}\" for action \"${actionName}\" was reused with different input. This is a programming error; do not retry.`\n }\n };\n}\n\nfunction encodeActionLedgerOutput(\n output: unknown\n): { ok: true; json: string; value: unknown } | { ok: false } {\n try {\n const json = JSON.stringify({\n valuePresent: output !== undefined,\n value: output\n });\n if (json === undefined) return { ok: false };\n const parsed = JSON.parse(json) as {\n valuePresent: boolean;\n value?: unknown;\n };\n if (output !== undefined && !(\"value\" in parsed)) {\n return { ok: false };\n }\n return {\n ok: true,\n json,\n value: parsed.valuePresent ? parsed.value : undefined\n };\n } catch {\n return { ok: false };\n }\n}\n\nfunction decodeActionLedgerOutput(json: string | null): unknown {\n if (json === null) return undefined;\n const parsed = JSON.parse(json) as {\n valuePresent?: unknown;\n value?: unknown;\n };\n return parsed.valuePresent === true ? parsed.value : undefined;\n}\n\nfunction safeStringifyActionOutput(output: unknown): {\n value?: string;\n lossy: boolean;\n error?: string;\n} {\n const seen = new WeakSet<object>();\n let lossy = false;\n try {\n const value = JSON.stringify(output, (_key, value: unknown) => {\n if (typeof value === \"bigint\") {\n lossy = true;\n return `${value.toString()}n`;\n }\n if (typeof value === \"object\" && value !== null) {\n if (seen.has(value)) {\n lossy = true;\n return \"[Circular]\";\n }\n seen.add(value);\n }\n return value;\n });\n return { value, lossy };\n } catch (error) {\n return {\n lossy: true,\n error: error instanceof Error ? error.message : String(error)\n };\n }\n}\n\nfunction prepareActionOutputForModel(output: unknown): unknown {\n if (typeof output === \"string\") {\n if (output.length <= ACTION_OUTPUT_MAX_CHARS) return output;\n return `${output.slice(0, ACTION_OUTPUT_MAX_CHARS)}\\n\\n[truncated ${output.length - ACTION_OUTPUT_MAX_CHARS} chars]`;\n }\n\n const serialized = safeStringifyActionOutput(output);\n if (serialized.error) {\n return {\n serialized: false,\n error: serialized.error\n };\n }\n if (serialized.value === undefined) return output;\n if (serialized.value.length <= ACTION_OUTPUT_MAX_CHARS) {\n if (!serialized.lossy) return output;\n return JSON.parse(serialized.value) as unknown;\n }\n\n return {\n truncated: true,\n chars: serialized.value.length,\n preview: `${serialized.value.slice(0, ACTION_OUTPUT_MAX_CHARS)}\\n\\n[truncated ${serialized.value.length - ACTION_OUTPUT_MAX_CHARS} chars]`\n };\n}\n\nfunction createActionAbortSignal(\n turnSignal: AbortSignal | undefined,\n timeoutMs: number | undefined\n): { signal: AbortSignal; cleanup: () => void } {\n const controller = new AbortController();\n let timeout: ReturnType<typeof setTimeout> | undefined;\n const abortFromTurn = () => controller.abort(turnSignal?.reason);\n\n if (turnSignal?.aborted) {\n abortFromTurn();\n } else {\n turnSignal?.addEventListener(\"abort\", abortFromTurn, { once: true });\n if (timeoutMs !== undefined && timeoutMs > 0) {\n timeout = setTimeout(() => {\n controller.abort(new Error(`Action timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n }\n }\n\n return {\n signal: controller.signal,\n cleanup: () => {\n if (timeout) clearTimeout(timeout);\n turnSignal?.removeEventListener(\"abort\", abortFromTurn);\n }\n };\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 * `Think`'s `classifyRecoveredTurn` detail (the {@link ChatFiberWakeHooks}\n * generic). `retryTargetUserId` is the pre-stream user message the turn re-runs\n * when it had no partial; the dispatch decision re-derives `streamIsTerminal` from\n * `streamStatus` rather than carrying it here.\n */\ntype ThinkRecoveryClassification = { retryTargetUserId: string | null };\n\n// `ChatRecoveryIncident` / `ChatRecoveryKind` / `CHAT_RECOVERY_INCIDENT_KEY_PREFIX`\n// are the canonical shared symbols from `agents/chat` (imported above); the\n// persisted incident shape and key prefix are owned by the engine package so\n// both consumers round-trip the same record across the deploy that ships them.\n\n// The durable, monotonic forward-progress counter (`CHAT_RECOVERY_PROGRESS_KEY`)\n// and its read/bump helpers now live in the shared engine (agents/chat) —\n// `readChatRecoveryProgress` / `bumpChatRecoveryProgress`. Bumped on each durable\n// content flush (`_storeChunkDurably`) — production time, so it reflects genuinely\n// new content and is immune to reconnects/re-persists; never recomputed from the\n// (compactable) transcript.\n// Recovery budget defaults (maxAttempts, maxRecoveryWork, stableTimeoutMs,\n// terminalMessage, noProgressTimeoutMs, alarm debounce) now live in the shared\n// incident engine (agents/chat) and are applied by `resolveChatRecoveryConfig`\n// / `evaluateChatRecoveryIncident`. See design/rfc-chat-recovery-foundation.md.\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// (Stable-state retry delay `CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS` and the\n// incident sweep — TTL selection, key prefix, and batched delete — now live in\n// agents/chat; the reschedule is owned by the shared engine and the sweep by the\n// shared `sweepStaleChatRecoveryIncidents` helper.)\n// (The recovering-flag key/TTL and the stream-cleanup delay/re-arm loop now live\n// in agents/chat — the durable recovery UX is driven via the shared\n// `setChatRecovering` / `buildChatRecoveringFrame` helpers, and buffer cleanup via\n// `STREAM_CLEANUP_DELAY_SECONDS` / `cleanupStreamBuffers`. The N9 throttle lives\n// there too as `AgentToolStreamProgressThrottle`.)\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// (The terminal-record key and the recovering-flag key now live in agents/chat;\n// the durable terminal/recovering records are driven via the shared\n// `recordChatTerminal` / `clearChatTerminal` / `pendingChatTerminal` /\n// `setChatRecovering` / `buildChatRecoveringFrame` helpers.)\n\n/**\n * A best-effort internal `onStart` step that failed on this wake and was\n * skipped so the agent could still come up (#1710).\n *\n * - `transcript-hydration` — reading the persisted conversation into the\n * in-memory message cache failed (e.g. `SQLITE_NOMEM` on an oversized,\n * media-heavy transcript). The agent starts with an empty in-memory view;\n * persisted history is untouched and the next safe-boundary sync retries.\n * - `scheduled-task-reconcile` — declarative scheduled tasks were not\n * reconciled on this wake; the next successful wake reconciles them.\n * - `durable-work-recovery` — pending submissions / workflow notifications\n * were not recovered or drained on this wake.\n */\nexport interface OnStartDegradation {\n step:\n | \"transcript-hydration\"\n | \"scheduled-task-reconcile\"\n | \"durable-work-recovery\";\n error: unknown;\n}\n\nexport type { MediaEvictionConfig } from \"./media-eviction\";\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 onError?: (error: unknown) => string;\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 * Client-defined tool schemas to expose to the model for this turn, mirroring\n * the `clientTools` carried over the WebSocket chat protocol. Use this when a\n * parent agent delegates to a Think sub-agent over RPC but the sub-agent still\n * needs access to tools the client (or parent) defines at runtime.\n *\n * On their own these are execute-less — the model's call surfaces as a tool\n * call through the stream callback. Provide {@link ChatOptions.onClientToolCall}\n * to also resolve those calls inline so the turn can continue to completion.\n */\n clientTools?: ClientToolSchema[];\n /**\n * Executes a client tool call and returns its output, completing the\n * round trip for {@link ChatOptions.clientTools} within the same turn.\n *\n * Without this, a client-tool call has no result and the turn ends with a\n * dangling tool call (the RPC stream callback has no inbound result channel).\n * With it, the model can call a client tool, receive the result, and keep\n * going — the same multi-step behavior the WebSocket path gets from\n * `cf_agent_tool_result` messages.\n */\n onClientToolCall?: ClientToolExecutor;\n /** Channel id this turn belongs to. See {@link RunTurnBase.channel}. */\n channel?: string;\n /**\n * Server-supplied metadata for this turn. Persisted on the turn's user\n * message alongside {@link ChatOptions.channel} (as `metadata.turnMetadata`)\n * so a recovered/continued turn re-resolves it from durable history, and\n * readable during the turn via {@link Think.activeTurnMetadata}.\n *\n * Trust contract mirrors the channel stamp: only server-side callers can set\n * it — reserved metadata keys on client-supplied messages are stripped at\n * intake. This gives messenger/RPC entry points (e.g.\n * {@link Think.chatWithMessengerContext}) a per-turn, recovery-safe carrier\n * for facts like \"which authenticated principal initiated this turn\" without\n * resorting to mutable agent-wide state.\n */\n metadata?: Record<string, unknown>;\n}\n\n/** Input accepted by {@link Think.runTurn}. */\nexport type TurnInputMessages =\n | string\n | UIMessage\n | UIMessage[]\n | ((current: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>);\n\n/** Shared base for {@link RunTurnOptions}; only `input` is common across modes. */\nexport interface RunTurnBase {\n input?: TurnInputMessages;\n /**\n * Channel id this turn belongs to (resolved against `configureChannels()` /\n * `getMessengers()`). Sets the turn-scoped channel context and is persisted on\n * the user message so a recovered/continued turn re-resolves it. Defaults to\n * the implicit `web` channel.\n */\n channel?: string;\n}\n\n/** Options for {@link Think.runTurn} with `mode: \"wait\"` (the default). */\nexport interface RunTurnWait extends RunTurnBase {\n mode?: \"wait\";\n continuation?: boolean;\n body?: Record<string, unknown>;\n signal?: AbortSignal;\n}\n\n/** Options for {@link Think.runTurn} with `mode: \"submit\"`. */\nexport interface RunTurnSubmit extends RunTurnBase {\n mode: \"submit\";\n submissionId?: string;\n idempotencyKey?: string;\n metadata?: Record<string, unknown>;\n}\n\n/** Options for {@link Think.runTurn} with `mode: \"stream\"`. */\nexport interface RunTurnStream extends RunTurnBase {\n mode: \"stream\";\n callback: StreamCallback;\n clientTools?: ClientToolSchema[];\n onClientToolCall?: ClientToolExecutor;\n signal?: AbortSignal;\n}\n\nexport type RunTurnOptions = RunTurnWait | RunTurnSubmit | RunTurnStream;\n\n/** Result of {@link Think.runTurn} in `mode: \"wait\"`. */\nexport type TurnResult = SaveMessagesResult & {\n message?: SessionMessage;\n continuation: boolean;\n};\n\nconst ACTION_BRAND: unique symbol = Symbol.for(\n \"cf.think.action\"\n) as typeof ACTION_BRAND;\n\nexport type ActionKind =\n | \"server\"\n | \"client\"\n | \"approval-gated\"\n | \"durable-pause\"\n | \"delegated-agent\";\n\nexport interface ActionContext {\n /** The agent instance currently executing the action. */\n agent: Think;\n env: Cloudflare.Env;\n /** Current turn request id. */\n requestId: string;\n toolCallId: string;\n /** Model messages visible to the tool call. */\n messages: ReadonlyArray<ModelMessage>;\n /** Combined action timeout and turn abort signal. */\n signal: AbortSignal;\n /**\n * Record an advisory delivery hint for this turn's final reply (voice note,\n * card, email draft, ...). Does not change the model-visible tool output.\n * No-op for approval/permission/idempotency policy evaluation and for\n * durable-pause approved-action resumes (their reply is delivered by a\n * later continuation turn in v1).\n */\n attachReply(attachment: ReplyAttachment): void;\n}\n\n/**\n * The attachment shape accepted by {@link ActionContext.attachReply}. An open\n * union: the named variants give autocomplete for common channels, and the\n * trailing `{ type: string; [k]: unknown }` keeps it extensible. Advisory only\n * — surfaces that don't recognize a `type` ignore it.\n */\nexport type ReplyAttachment =\n | { type: \"voice_note\" }\n | { type: \"email_draft\"; subject?: string; to?: string[] }\n | { type: \"card\"; payload: unknown }\n | { type: string; [k: string]: unknown };\n\nexport type ActionApprovalPolicy<Input> =\n | boolean\n | ((args: {\n input: Input;\n ctx: ActionContext;\n }) => boolean | Promise<boolean>);\n\nexport type ActionPermissionSpec<Input> =\n | readonly string[]\n | ((args: {\n input: Input;\n ctx: ActionContext;\n }) => readonly string[] | Promise<readonly string[]>);\n\nexport type ActionIdempotencyKey<Input> =\n | string\n | ((args: { input: Input; ctx: ActionContext }) => string | Promise<string>);\n\nexport type ActionAuthorizationDecision =\n | boolean\n | {\n allowed: boolean;\n reason?: string;\n grantedPermissions?: readonly string[];\n };\n\nexport interface ActionAuthorizationContext {\n requestId: string;\n toolCallId: string;\n action: string;\n kind: ActionKind;\n input: unknown;\n requiredPermissions: readonly string[];\n grantedPermissions?: readonly string[];\n messages: ReadonlyArray<ModelMessage>;\n agent: Think;\n env: Cloudflare.Env;\n}\n\nexport interface ActionApprovalDescriptor {\n requestId: string;\n toolCallId: string;\n action: string;\n summary: string;\n input: unknown;\n permissions: string[];\n risk?: \"low\" | \"medium\" | \"high\";\n kind: \"approval-gated\" | \"durable-pause\";\n}\n\n/**\n * A single approval awaiting a human decision, unified across pause backends so\n * dashboards/voice/messenger can list and reconcile everything pending with one\n * call. `source: \"action\"` is a parked `kind: \"durable-pause\"` action;\n * `source: \"codemode\"` is a paused `execute`-tool execution. Both resolve via\n * {@link Think.approveExecution} / {@link Think.rejectExecution}.\n */\nexport interface PendingApproval {\n executionId: string;\n source: \"action\" | \"codemode\";\n descriptor: ActionApprovalDescriptor;\n}\n\nexport interface ActionConfig<\n InputSchema extends FlexibleSchema = FlexibleSchema,\n Output = unknown\n> {\n /** Defaults to the registration key when returned from getActions(). */\n name?: string;\n description: string;\n inputSchema: InputSchema;\n /** Reserved metadata; output validation is not enforced yet. */\n outputSchema?: FlexibleSchema<Output>;\n /**\n * Stable key used to replay settled action results without re-running side\n * effects. Use domain identifiers that survive recovery retries (for example,\n * an order id or inbound event id); avoid request ids, timestamps, and random\n * values.\n */\n idempotencyKey?: ActionIdempotencyKey<InferSchema<InputSchema>>;\n permissions?: ActionPermissionSpec<InferSchema<InputSchema>>;\n approval?: ActionApprovalPolicy<InferSchema<InputSchema>>;\n approvalSummary?: string;\n approvalRisk?: \"low\" | \"medium\" | \"high\";\n timeoutMs?: number;\n kind?: ActionKind;\n execute(\n input: InferSchema<InputSchema>,\n ctx: ActionContext\n ): Promise<Output> | Output;\n}\n\nexport interface Action<\n InputSchema extends FlexibleSchema = FlexibleSchema,\n Output = unknown\n> {\n readonly [ACTION_BRAND]: true;\n readonly config: ActionConfig<InputSchema, Output>;\n}\n\nexport function action<\n const InputSchema extends FlexibleSchema,\n Output = unknown\n>(config: ActionConfig<InputSchema, Output>): Action<InputSchema, Output> {\n if (config.kind === \"durable-pause\" && config.approval === false) {\n throw new Error(\n `Action \"${config.name ?? \"(anonymous)\"}\": kind \"durable-pause\" with ` +\n `approval: false never parks for approval, defeating the purpose. ` +\n `Use kind \"server\" for an inline action, or omit approval (or set a ` +\n `predicate) to gate when it parks.`\n );\n }\n const descriptor: Action<InputSchema, Output> = {\n [ACTION_BRAND]: true,\n config: Object.freeze({ ...config })\n };\n return Object.freeze(descriptor);\n}\n\nexport function isAction(value: unknown): value is Action {\n return (\n typeof value === \"object\" &&\n value !== null &&\n (value as { [ACTION_BRAND]?: unknown })[ACTION_BRAND] === true\n );\n}\n\ntype CompiledActionMetadata = {\n actionName: string;\n summary: string;\n permissions?: string[];\n risk?: \"low\" | \"medium\" | \"high\";\n kind: \"approval-gated\" | \"durable-pause\";\n};\n\ntype NormalizedActionAuthorization = {\n allowed: boolean;\n reason?: string;\n grantedPermissions?: readonly string[];\n};\n\ntype TurnTrigger =\n | \"ws-chat\"\n | \"rpc\"\n | \"programmatic\"\n | \"submission\"\n | \"scheduled\"\n | \"agent-tool\"\n | \"auto-continuation\"\n | \"recovery-continue\"\n | \"recovery-retry\";\n\ntype TurnAdmission = \"queue\" | \"submit\" | \"execute-submission\";\n\ntype AdmittedQueueResult<T> =\n | { status: \"completed\"; value: T }\n | { status: \"stale\" };\n\ntype QueueTurnSpec<T> = {\n admission: \"queue\";\n trigger: TurnTrigger;\n requestId: string;\n generation?: number;\n continuation?: boolean;\n allowNested?: boolean;\n channel?: string;\n onQueued?: () => void;\n getStatus?: () => string | undefined;\n execute: () => Promise<T>;\n};\n\ntype NonQueueTurnSpec<T> = {\n admission: Exclude<TurnAdmission, \"queue\">;\n trigger: TurnTrigger;\n channel?: string;\n execute: () => Promise<T>;\n};\n\ntype TurnSpec<T> = QueueTurnSpec<T> | NonQueueTurnSpec<T>;\n\nconst admittedTurnContext = new AsyncLocalStorage<{\n agent: unknown;\n requestId: string;\n trigger: TurnTrigger;\n admission: \"queue\";\n channel?: string | undefined;\n continuation?: boolean | undefined;\n generation?: number | undefined;\n}>();\n\n// Drains the underlying model stream when a drain loop exits early (in-stream\n// error break, stall abort, user abort). The AI SDK tees its base stream, so\n// an abandoned tee branch would otherwise leave the tracing wrapper's\n// operation span open forever. One registration is associated with both the\n// stable pre-transform result and any wrapper returned by the test seam.\ntype InferenceStreamFinalizer = {\n started: boolean;\n run: () => Promise<void>;\n};\nconst inferenceStreamFinalizers = new WeakMap<\n object,\n InferenceStreamFinalizer\n>();\n\n/** Options for {@link Think.addMessages}. */\nexport interface AddMessagesOptions {\n /**\n * Parent to attach the first message under. Omitted (`undefined`) attaches to\n * the latest committed leaf at call time; `null` attaches at the root. An\n * explicit id that does not exist throws (fail fast rather than silently\n * misattaching). Subsequent messages in an array chain under the previous one.\n */\n parentId?: string | null;\n /**\n * `\"append\"` (default) inserts new rows, idempotent by message id.\n * `\"upsert\"` inserts, or updates in place when the id already exists (in which\n * case `parentId` is ignored — re-parenting is not supported).\n *\n * Idempotency is by id against the whole session tree, not just the target\n * path: if a message id already exists *anywhere* in history, `\"append\"` is a\n * no-op for it (no new row, no re-parent) and `\"upsert\"` updates it in place\n * wherever it lives. In both modes the next message in the array chains under\n * that existing id, so passing already-present ids mid-array threads new\n * messages onto the existing branch rather than forking a new one.\n */\n mode?: \"append\" | \"upsert\";\n /**\n * Broadcast the change to connected clients. Default `true`. Has no effect\n * when called from inside an active turn (e.g. a tool `execute`), where the\n * live view is intentionally not touched until the next turn's sync.\n */\n broadcast?: boolean;\n}\n\n/** Options for {@link Think.deliverNotice}. */\nexport interface DeliverNoticeOptions {\n /**\n * Target channel id. Defaults to the active turn's channel, else `\"web\"`.\n */\n channel?: string;\n /**\n * Also record the notice in the model-visible transcript so the next turn\n * knows it was said. Default `false`. For the `web` channel the note is always\n * appended to the transcript (its only render path); `informModel` then only\n * controls the phrasing.\n */\n informModel?: boolean;\n /** Delivery kind for the wire tag. Default `\"notice\"`. */\n kind?: DeliveryKind;\n /**\n * Conversation/thread hint, required for out-of-turn delivery to a\n * multi-thread messenger channel.\n */\n thread?: string;\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 progress_json?: string | null;\n last_signal_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 progress?: AgentToolProgressSnapshot;\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\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 ActionLedgerStatus = \"pending\" | \"settled\";\n\ntype ActionLedgerRow = {\n key: string;\n action_name: string;\n request_id: string | null;\n tool_call_id: string | null;\n input_hash: string;\n status: ActionLedgerStatus;\n result_json: string | null;\n created_at: number;\n updated_at: number;\n};\n\ntype ActionLedgerClaim =\n | { outcome: \"claimed\" }\n | { outcome: \"replay\"; row: ActionLedgerRow }\n | { outcome: \"pending\"; row: ActionLedgerRow }\n | { outcome: \"reclaimed\"; row: ActionLedgerRow }\n | { outcome: \"conflict\"; row: ActionLedgerRow };\n\ntype ActionLedgerRetentionConfig = {\n settledMs: number | false;\n pendingMs: number | false;\n maxSweepRows: number;\n};\n\ntype ActionLedgerSweepStatus = Extract<\n ActionLedgerStatus,\n \"pending\" | \"settled\"\n>;\n\ntype ActionLedgerEvent =\n | {\n type: \"action:ledger:replayed\";\n payload: { action: string; key: string; inputHash: string };\n }\n | {\n type: \"action:ledger:pending\";\n payload: { action: string; key: string; inputHash: string };\n }\n | {\n type: \"action:ledger:conflict\";\n payload: { action: string; key: string; inputHash: string };\n }\n | {\n type: \"action:ledger:serialize_failed\";\n payload: { action: string; key: string };\n }\n | {\n type: \"action:ledger:settled\";\n payload: { action: string; key: string; inputHash: string };\n }\n | {\n type: \"action:ledger:reclaimed\";\n payload: {\n action: string;\n key: string;\n inputHash: string;\n ageMs: number;\n };\n }\n | {\n type: \"action:ledger:swept\";\n payload: { settled: number; pending: number };\n };\n\ntype ChannelEvent =\n | {\n type: \"channel:resolved\";\n payload: { channel: string; kind: string; requestId?: string };\n }\n | {\n type: \"channel:delivered\";\n payload: { channel: string; kind: DeliveryKind; turnEnded: boolean };\n }\n | {\n type: \"notice:delivered\";\n payload: { channel: string; kind: DeliveryKind; informModel: boolean };\n }\n | {\n type: \"notice:failed\";\n payload: { channel: string; error: string };\n };\n\n/**\n * A durably-parked `kind: \"durable-pause\"` action awaiting human approval. The\n * row is the compaction-safe record of everything needed to run `execute` on\n * approve (the transcript part can be summarized away before approval), so it\n * carries the action name, the model's input, and the approval descriptor.\n */\ntype ActionPendingRow = {\n execution_id: string;\n action_name: string;\n tool_call_id: string;\n request_id: string | null;\n input_json: string;\n descriptor_json: string | null;\n created_at: number;\n};\n\ntype ActionPauseEvent =\n | {\n type: \"action:pause:created\";\n payload: { action: string; executionId: string; toolCallId: string };\n }\n | {\n type: \"action:pause:approved\";\n payload: { action: string; executionId: string };\n }\n | {\n type: \"action:pause:rejected\";\n payload: { action: string; executionId: string };\n }\n | {\n type: \"action:pause:swept\";\n payload: { swept: number };\n };\n\ntype ActionReplyEvent = {\n type: \"action:reply-attached\";\n payload: { action?: string; attachmentType: string };\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 /** Channel id this submission belongs to. See {@link RunTurnBase.channel}. */\n channel?: string;\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\n/**\n * Message-metadata keys that are server-written turn context (stamped by\n * `_stampChannel`) and trusted by hooks and recovery. They are stripped from\n * client-supplied messages at intake so a client can never forge them.\n */\nconst RESERVED_MESSAGE_METADATA_KEYS = [\"channel\", \"turnMetadata\"] as const;\n\n/**\n * Reserved name for the synthetic tool a workflow `step.prompt` turn uses to\n * deliver its structured final answer. The agent runs a full multi-step,\n * tool-using turn and ends it by calling this tool with arguments matching the\n * requested schema — exactly the way a sub-agent returns a result.\n *\n * Why a tool instead of the AI SDK `output`/`response_format` path: streaming a\n * JSON Schema `response_format` is rejected by some providers (Workers AI\n * returns `AiError 5023: JSON Schema mode is not supported with stream mode`),\n * whereas plain tool-calling streams on every provider. Capturing the tool\n * call's INPUT as the result keeps Think's single streaming engine intact\n * (persistence, recovery, resumable streams) and works uniformly across\n * Workers AI, OpenAI, and Anthropic.\n *\n * The name is namespaced to avoid clashing with user tools; if a user tool\n * already uses it, the turn picks a suffixed variant (see `_handleTurn`).\n */\nconst THINK_FINAL_ANSWER_TOOL_NAME = \"think_final_answer\";\n\n/**\n * Whether `name` is (or is a collision-suffixed variant of) the reserved\n * structured-output final-answer tool. Used to strip the internal tool's parts\n * from persisted assistant messages regardless of which per-turn name was used.\n */\nfunction isThinkFinalAnswerToolName(name: string): boolean {\n return (\n name === THINK_FINAL_ANSWER_TOOL_NAME ||\n name.startsWith(`${THINK_FINAL_ANSWER_TOOL_NAME}_`)\n );\n}\n\n/**\n * Build the system-prompt instruction that tells the model to terminate a\n * structured workflow turn by calling the given final-answer tool.\n */\nfunction thinkFinalAnswerInstruction(toolName: string): string {\n return (\n \"When you have everything you need to answer, you MUST call the \" +\n `\\`${toolName}\\` tool exactly once with arguments that match the required ` +\n \"schema. Do not write the final answer as plain text — the \" +\n `\\`${toolName}\\` tool call IS the answer and ends the task.`\n );\n}\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 ChatRecoveryProgressContext,\n ChatRecoveryOptions,\n MessageConcurrency,\n ResolvedChatRecoveryConfig,\n SaveMessagesOptions,\n SaveMessagesResult\n} from \"agents/chat\";\nimport type {\n ChatResponseResult,\n ChatRecoveryConfig,\n ChatRecoveryContext,\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 /**\n * Executor that resolves client-tool calls inline (RPC `chat()` path). When\n * present, `clientTools` are built WITH an `execute` that delegates to it, so\n * the turn completes the tool round trip itself instead of surfacing a\n * dangling tool call. Not persisted — recovery cannot replay a live executor.\n */\n clientToolExecutor?: ClientToolExecutor;\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 /**\n * Override the model for this turn (e.g. cheap model for continuations).\n * Accepts a model id string (resolved via the built-in provider, same rules\n * as {@link Think.getModel}) or a `LanguageModel`.\n */\n model?: ThinkModel;\n /** Override the assembled instructions prompt. */\n instructions?: string;\n /** @deprecated Prefer `instructions`. */\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 /**\n * Optional AI SDK telemetry configuration for this turn.\n *\n * Typed via the `experimental_telemetry` key, which exists in both AI SDK v6\n * and v7 (`telemetry` is v7-only), so this type resolves under either major.\n */\n telemetry?: Parameters<typeof streamText>[0][\"experimental_telemetry\"];\n /** @deprecated Prefer `telemetry`. */\n experimental_telemetry?: Parameters<\n typeof streamText\n >[0][\"experimental_telemetry\"];\n /**\n * Optional AI SDK stream transform(s) for this turn (`experimental_transform`).\n * Forwarded to `streamText` so callers can inspect/rewrite the stream — e.g.\n * detecting tool results that carry `{ content, sources }` and enqueuing\n * additional `source` parts via the transform's controller. Accepts a single\n * transform or an array applied in order.\n */\n experimental_transform?: Parameters<\n typeof streamText\n >[0][\"experimental_transform\"];\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\n/**\n * Provider-agnostic semantic classification of a chat-turn error.\n *\n * Think ships **no** provider-specific string/code matching — the app owns\n * that knowledge (it knows which provider/model it talks to), exactly like the\n * `tokenCounter` it already passes to `compactAfter()`. An app teaches Think\n * what an error *means* by overriding `classifyChatError()`; Think then reacts\n * generically (e.g. compact-and-retry on `context_overflow`).\n *\n * - `context_overflow` — the prompt exceeded the model's context window\n * (Anthropic `\"prompt is too long\"`, OpenAI `context_length_exceeded`, …).\n * The only category Think currently acts on (auto-compact + retry).\n * - `rate_limit` / `transient` — reserved for future backoff/retry policies.\n * - `fatal` — unrecoverable; surface terminally.\n * - `unknown` — default; Think applies its existing terminal behavior.\n */\nexport type ChatErrorClassification =\n | \"context_overflow\"\n | \"rate_limit\"\n | \"transient\"\n | \"fatal\"\n | \"unknown\";\n\n/**\n * Opt-in handling for a turn that overflows the model's context window\n * mid-flight. Compaction (`compactAfter()`) is only checked between turns, so a\n * long, tool-heavy turn can grow past the window before the next check; the\n * provider then rejects the request (`\"prompt is too long\"` /\n * `context_length_exceeded`). Both layers reuse the session's compaction\n * function and are provider-agnostic — the app maps the error via\n * {@link Think.classifyChatError}; Think never matches provider strings itself.\n *\n * Set `Think.contextOverflow` to enable. Leaving it unset disables both layers\n * (existing terminal behavior).\n */\nexport interface ContextOverflowConfig {\n /**\n * Reactive backstop. When a turn fails with an error classified as\n * `\"context_overflow\"`, discard the truncated partial, run\n * `session.compact()`, and re-run the turn from the compacted history. The\n * partial is intentionally not persisted: the turn restarts from scratch, so\n * keeping the cut-off assistant message would orphan it beside the recovered\n * answer (and duplicate any tool work the retry re-issues). If compaction\n * cannot shorten history or the retry budget is spent, the overflow surfaces\n * terminally through `onChatError` (classified) — it never loops or ends\n * silently. Default `false`.\n */\n reactive?: boolean;\n\n /**\n * Maximum compact-and-retry attempts for a single overflowing turn (the\n * reactive backstop). Independent of the proactive guard's cap — see\n * {@link proactive.maxCompactions}. Default `1`.\n */\n maxRetries?: number;\n\n /**\n * Proactive guard. Before each step, read the previous step's model-reported\n * `usage.inputTokens` and, if it crosses `maxInputTokens * (headroom ?? 0.9)`,\n * compact in place and feed the recompacted history into the upcoming step —\n * heading off the provider rejection before it happens. Keys off usage (every\n * provider reports it), not provider error strings. Unset disables it.\n *\n * If a provider omits `inputTokens`, the guard falls back to `usage.totalTokens`\n * (input + output) — a safe over-approximation that compacts slightly early\n * rather than missing the threshold. If neither is reported, the guard does\n * nothing that step (the reactive backstop still catches a genuine overflow).\n *\n * `maxCompactions` caps how many times the guard may compact within a single\n * step loop (default `1`, floored at `1`). It is independent of\n * {@link maxRetries} (the reactive budget): a no-op compaction would repeat on\n * every step, so the cap stops the guard from compacting (and emitting\n * `chat:context:compacted`) on each one.\n */\n proactive?: {\n maxInputTokens: number;\n headroom?: number;\n maxCompactions?: number;\n };\n}\n\n/**\n * Matches the context-window-overflow error messages of the common providers.\n * Anthropic (`prompt is too long`), OpenAI (`context_length_exceeded`,\n * `maximum context length`, `reduce the length of …`), Google Gemini (`exceeds\n * the maximum number of tokens`, `input token count`), Bedrock / Mistral /\n * others (`input is too long`, `too many tokens`, `context window`).\n *\n * This default deliberately favors recall over precision: a missed overflow\n * means no recovery (the feature's whole point), whereas a false positive\n * self-heals — the retry hits the same non-overflow error, the budget is spent,\n * and it surfaces terminally anyway. The vaguest fragment (`reduce the length`)\n * is anchored to `of` to match the real OpenAI phrasing without matching\n * unrelated prose. Apps that need stricter matching can wrap this classifier.\n */\nconst CONTEXT_OVERFLOW_PATTERN =\n /prompt is too long|context[_ ]length[_ ]exceeded|maximum context length|exceeds the maximum number of tokens|input token count|reduce the length of|input is too long|too many (?:input )?tokens|context window/i;\n\n/**\n * Opt-in default classifier for {@link Think.classifyChatError}. Matches the\n * context-window-overflow error messages of the common providers (Anthropic,\n * OpenAI, Google, Bedrock, Mistral, …) and returns `\"context_overflow\"`.\n *\n * Think ships this as an explicitly-imported helper rather than wiring it into\n * core, so the framework default stays free of provider strings. Assign it (or\n * delegate to it) when you do not need custom classification:\n *\n * @example\n * ```typescript\n * import { Think, defaultContextOverflowClassifier } from \"@cloudflare/think\";\n *\n * export class MyAgent extends Think<Env> {\n * override contextOverflow = { reactive: true };\n * override classifyChatError = defaultContextOverflowClassifier;\n * }\n * ```\n *\n * Or combine with your own checks:\n *\n * @example\n * ```typescript\n * override classifyChatError(error: unknown): ChatErrorClassification | void {\n * if (isMyRateLimit(error)) return \"rate_limit\";\n * return defaultContextOverflowClassifier(error);\n * }\n * ```\n */\nexport function defaultContextOverflowClassifier(\n error: unknown\n): ChatErrorClassification | undefined {\n let text: string;\n if (error instanceof Error) {\n text = error.message;\n } else if (typeof error === \"string\") {\n text = error;\n } else {\n try {\n text = JSON.stringify(error);\n } catch {\n text = String(error);\n }\n }\n return CONTEXT_OVERFLOW_PATTERN.test(text) ? \"context_overflow\" : undefined;\n}\n\nexport interface ChatErrorContext {\n requestId?: string;\n stage: \"parse\" | \"persist\" | \"turn\" | \"stream\" | \"recovery\" | \"transcript\";\n messagesPersisted?: boolean;\n /**\n * App-provided semantic classification (from `classifyChatError`), when\n * known. Lets `onChatError` overrides and observers distinguish e.g. a\n * context-overflow from a generic provider failure without re-matching\n * provider strings.\n */\n classification?: ChatErrorClassification;\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`, `instructions`, `messages`, `experimental_context`,\n * `providerOptions`). The previous `system` field remains available as a\n * deprecated alias.\n *\n * `model` is widened to {@link ThinkModel}: like {@link Think.getModel}, you\n * can return a model id string (resolved via the built-in provider) instead of\n * a `LanguageModel`. Think resolves it before handing the step to the AI SDK.\n */\nexport type StepConfig<TOOLS extends ToolSet = ToolSet> = Omit<\n PrepareStepResult<TOOLS>,\n \"model\"\n> & {\n model?: ThinkModel;\n};\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. With a concrete\n * tool set, narrowing on `ctx.toolName` narrows `ctx.input` to that tool's\n * input shape:\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 as string\n * }\n * }\n * ```\n */\nexport type ToolCallContext<TOOLS extends ToolSet = ToolSet> =\n PerToolCall<TOOLS> & ToolCallContextExtras;\n\n/** Per-call event extras attached to every {@link ToolCallContext}. */\ntype ToolCallContextExtras = {\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 * The `TypedToolCall<TOOLS>` union, re-keyed so that discriminating on\n * `toolName` narrows `input` per tool.\n *\n * The AI SDK's `TypedToolCall` includes a `DynamicToolCall` arm whose\n * `toolName: string` / `input: unknown` overlaps every static tool name —\n * leaving it in the union collapses `ctx.input` to `unknown` even after a\n * `toolName` check. When an explicit `TOOLS` generic is passed (so the keys\n * are a literal union), we distribute over those keys and drop the dynamic\n * arm so narrowing works. With the default `ToolSet` (keys are `string`) we\n * fall back to the raw union, preserving the prior loose behavior.\n */\ntype PerToolCall<TOOLS extends ToolSet> = string extends keyof TOOLS\n ? TypedToolCall<TOOLS>\n : {\n [K in keyof TOOLS]: Extract<TypedToolCall<TOOLS>, { toolName: K }>;\n }[keyof TOOLS];\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 `OnToolExecutionEndEvent`. The full\n * `TypedToolCall<TOOLS>` fields (`toolName`, `toolCallId`, `input`, …) are\n * spread at the top 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 * - `toolExecutionMs` — wall-clock execution time in milliseconds\n * - `durationMs` — deprecated alias for `toolExecutionMs`\n * - `toolOutput` — AI SDK v7 discriminated outcome\n * - `success`/`output`/`error` — deprecated normalized outcome aliases:\n * - on success: `success: true`, `output` typed per tool\n * - on failure: `success: false`, `error: unknown`\n *\n * Pass an explicit `TOOLS` generic for full input **and** output typing.\n * On the success branch, narrowing on `ctx.toolName` narrows `ctx.output`\n * to that tool's inferred output type (dynamic tools stay `unknown`):\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.toolName === \"search\" && ctx.success) {\n * ctx.output.results; // typed as the `search` tool's output\n * }\n * }\n * ```\n */\nexport type ToolCallResultContext<TOOLS extends ToolSet = ToolSet> =\n string extends keyof TOOLS\n ? TypedToolCall<TOOLS> & ToolCallResultBase & ToolCallOutcome<unknown>\n : {\n [K in keyof TOOLS]: Extract<TypedToolCall<TOOLS>, { toolName: K }> &\n ToolCallResultBase &\n ToolCallOutcome<InferToolOutput<TOOLS[K]>>;\n }[keyof TOOLS];\n\n/** Per-call extras attached to every {@link ToolCallResultContext}. */\ntype ToolCallResultBase = {\n readonly stepNumber: number | undefined;\n readonly messages: ReadonlyArray<ModelMessage>;\n /** Wall-clock execution time in milliseconds. */\n readonly toolExecutionMs: number;\n /** @deprecated Prefer `toolExecutionMs`. */\n readonly durationMs: number;\n};\n\n/**\n * The discriminated success/failure outcome of a tool call. On success the\n * `output` is typed (`O`); on failure the `error` is `unknown`.\n */\ntype ToolCallOutcome<O> =\n | {\n readonly toolOutput: { type: \"tool-result\"; output: O };\n /** @deprecated Prefer `toolOutput.type === \"tool-result\"`. */\n readonly success: true;\n /** @deprecated Prefer `toolOutput.output`. */\n readonly output: O;\n readonly error?: never;\n }\n | {\n readonly toolOutput: { type: \"tool-error\"; error: unknown };\n /** @deprecated Prefer `toolOutput.type === \"tool-error\"`. */\n readonly success: false;\n readonly output?: never;\n /** @deprecated Prefer `toolOutput.error`. */\n readonly error: unknown;\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 GenerateTextOnStepFinishCallback<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\n/**\n * @internal The subset of the AI SDK's `ToolExecuteOptions` that Think's\n * tool wrapper reads when resolving a `beforeToolCall` decision.\n */\ntype ToolDecisionOptions = {\n toolCallId: string;\n messages: ModelMessage[];\n abortSignal?: AbortSignal;\n context?: unknown;\n experimental_context?: unknown; // v6 alias kept for local wrappers if present\n};\n\n/**\n * An opinionated chat agent base class.\n *\n * @experimental The API surface may change before stabilizing.\n */\n/**\n * Keys of the global `AiModels` interface (from `@cloudflare/workers-types`)\n * whose model type extends `T`. Mirrors the derivation `workers-ai-provider`\n * uses, so the set stays in sync with the installed workers-types version.\n */\ntype WorkersAIModelIdsExtending<T> = {\n [K in keyof AiModels]: AiModels[K] extends T ? K : never;\n}[keyof AiModels];\n\n/**\n * A model id accepted by {@link Think.getModel}.\n *\n * Provides editor autocomplete for the Workers AI text-generation catalog\n * (`@cf/...`) while still accepting **any** string — including\n * `\"<provider>/<model>\"` AI Gateway slugs like `\"openai/gpt-5.5\"`, whose\n * validity is only known at runtime (the catalog is server-side and changes\n * independently of these types). The `(string & {})` arm is what keeps\n * arbitrary strings assignable without collapsing the autocomplete union.\n */\nexport type ThinkModelId =\n | Exclude<\n WorkersAIModelIdsExtending<BaseAiTextGeneration>,\n WorkersAIModelIdsExtending<BaseAiTextToImage>\n >\n | (string & {});\n\n/**\n * What {@link Think.getModel} may return: either a fully-constructed AI SDK\n * `LanguageModel`, or a {@link ThinkModelId} string resolved through Think's\n * built-in `workers-ai-provider`. Also the input type of {@link Think.resolveModel}.\n */\nexport type ThinkModel = LanguageModel | ThinkModelId;\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 * Whether Think automatically converts connected MCP tools to AI SDK tools\n * and merges them into each model turn.\n *\n * Set this to `false` when MCP tools are exposed through Code Mode or another\n * mechanism outside Think's automatic tool set. Connections, discovery,\n * `waitForMcpConnections`, raw tool listing and calls, and explicit\n * `this.mcp.getAITools()` calls are unaffected.\n *\n * @default true\n */\n includeMcpTools = true;\n\n /**\n * Wait for MCP server connections to be ready before the inference loop.\n * When {@link includeMcpTools} is enabled, their tools are then auto-merged\n * 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 /** Store model input/output on `chat` spans. */\n storeMessages = false;\n\n /** Store tool input/output on `execute_tool` spans. */\n storeTools = false;\n\n private _skillRegistry: SkillRegistry | null = null;\n private _loggedSkillWarnings = new Set<string>();\n private _loggedProtocolWarnings = 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 * Byte budget for hydrating the persisted transcript into the in-memory\n * message cache (`this.messages`).\n *\n * Hydration runs on every wake (and at safe boundaries during a session).\n * Without a budget it materializes the ENTIRE stored conversation — for\n * long-lived, media-heavy sessions that footprint approaches the isolate's\n * 128MB memory budget and the next SQLite allocation fails with\n * `SQLITE_NOMEM`, permanently bricking the DO (#1710).\n *\n * When the stored path exceeds the budget, only the most recent messages\n * that fit are hydrated — never fewer than the recent window the model\n * sees at full fidelity (the `truncateOlderMessages` default of 4), even\n * when those messages alone exceed the budget — a\n * `chat:hydration:windowed` observability event is emitted, and\n * `this.messages` exposes the bounded window. Durable storage is never\n * truncated by this — `session.getHistory()` still reads the full path.\n * The model-facing context is unaffected: older content is already\n * truncated at read time before each turn, and the hydration floor\n * guarantees the full-fidelity span is always present.\n *\n * The default (24MB) leaves headroom for the ~2-3x amplification between\n * stored JSON and parsed in-memory messages. Set to\n * `Number.POSITIVE_INFINITY` (or any non-positive value) to disable\n * windowing and always hydrate the full transcript.\n *\n * @default 24 * 1024 * 1024\n */\n hydrationByteBudget: number = 24 * 1024 * 1024;\n\n /**\n * Bound the PERSISTED transcript footprint by evicting oversized inline\n * media (base64 data-URL attachments, large strings inside tool outputs)\n * from messages that have aged out of the recent window.\n *\n * Read-time truncation already hides aged media from the model, but the\n * bytes stay in storage forever and are rehydrated on every wake — the\n * boot footprint grows with every image a session ever produced until\n * SQLite's allocator fails with `SQLITE_NOMEM` (#1710). Eviction passes\n * run in the background after the agent starts and as the conversation\n * grows; each pass processes a bounded number of oversized rows.\n *\n * By default evicted values are preserved as workspace files under\n * `/attachments/evicted/` (same Durable Object storage, but outside the\n * hydration path) and the in-message marker records the file path.\n * Pass a {@link MediaEvictionConfig} with `externalizeToWorkspace: false`\n * to drop the bytes instead of preserving them. Set this field to\n * `false` to disable eviction entirely.\n *\n * `keepRecentMessages` is clamped to at least the recent window the model\n * replays at full fidelity (4 messages), so eviction can never rewrite\n * content the model still sees.\n *\n * Requires a SessionProvider that implements `getHistoryRowStats`\n * (the default DO SQLite provider does); otherwise eviction is a no-op\n * and a warning is logged once.\n *\n * @default true\n */\n mediaEviction: MediaEvictionConfig | boolean = true;\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 * Assign this as a class field or in the constructor — NOT in `onStart()`.\n * On every wake the SDK evaluates recovery budgets (and may seal an\n * interrupted turn, firing `onExhausted`) before `onStart()` runs, so a config\n * set in `onStart()` is applied too late and the built-in defaults are used\n * for the recovery that matters. See {@link ChatRecoveryConfig}.\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 /**\n * Internal onStart steps that failed on this wake and were skipped so the\n * agent could still come up.\n *\n * onStart failures are terminal: partyserver resets its init state and\n * rethrows, so every subsequent wake — including platform alarm retries —\n * re-runs the failing onStart. A data-driven failure (e.g. SQLITE_NOMEM\n * hydrating an oversized transcript) would otherwise permanently brick the\n * DO and drive an unbounded alarm-retry loop (#1710).\n */\n protected _onStartDegradations: OnStartDegradation[] = [];\n\n /**\n * Internal onStart steps that failed on this wake and were skipped so the\n * agent could still come up (see {@link OnStartDegradation}). Empty when\n * boot was clean. Lets hosts and operators surface degraded boots —\n * e.g. via a health RPC — without subclassing.\n */\n getOnStartDegradations(): ReadonlyArray<OnStartDegradation> {\n return [...this._onStartDegradations];\n }\n\n private _activeMessengerContext?: MessengerContext;\n\n /**\n * Turn-scoped channel context (superset of `_activeMessengerContext`). Set on\n * both the queue and submit admission paths via `_withChannelContext`, read by\n * `deliverNotice` and per-channel policy. Save/restore keeps nested turns safe.\n */\n private _activeChannelContext?: ChannelContext;\n\n /**\n * Live delivery surface for the active turn, bound by `deliverMessengerReply`\n * so `deliverNotice` can post to the originating channel mid-turn. Save/restore\n * keeps nested turns safe.\n */\n private _activeDeliverySurface?: MessengerDeliverySurface;\n\n private _messengerRuntime?: ThinkMessengerRuntime;\n\n /** Resolved channel registry (implicit web + configureChannels + messengers). */\n private _channels?: Map<string, NormalizedChannelDefinition>;\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 * The codemode runtime behind the execute tool, when one has been created\n * via `createExecuteRuntime(this)` / `createExecuteTool(this)` (from\n * `@cloudflare/think/tools/execute`). Gives callables and lifecycle hooks\n * access to approvals (`approve`/`reject`/`pending`), the audit trail\n * (`executions`), `expirePaused`, and snippets.\n */\n codemode?: import(\"@cloudflare/codemode\").CodemodeRuntimeHandle;\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 /**\n * Opt-in HTTP fetch tools. Disabled by default — set to a config object to\n * register a generic `fetch_url` tool (when `allowlist` is provided) and one\n * `fetch_<name>` tool per `bindings` target. Read-only (GET), allowlisted,\n * and bounded; see {@link createFetchTools}.\n *\n * The workspace and an observability hook are injected automatically, so omit\n * `workspace`/`onEvent` here. This property is evaluated at construction, so\n * use it for static config — for per-tenant/dynamic allowlists call\n * `createFetchTools()` inside `getTools()` instead (it runs every turn).\n *\n * ```ts\n * fetchTools = { allowlist: [\"https://developers.cloudflare.com/**\"] };\n * ```\n */\n fetchTools: false | Omit<CreateFetchToolsOptions, \"workspace\" | \"onEvent\"> =\n false;\n\n constructor(ctx: DurableObjectState, env: Env) {\n super(ctx, env);\n\n const _onStart = this.onStart.bind(this);\n const startThink = async (\n props: Props | undefined,\n update: UpdateAgentSpan\n ) => {\n await withAgentSpan(\n this,\n \"initialize_think_session\",\n \"startup\",\n { \"cloudflare.agents.component\": \"think\" },\n 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 // The conversation grew — older messages may have aged out of\n // the keep-recent window. Only schedule the maintenance scan once\n // this session has actually observed oversized media; otherwise a\n // normal text-only chat would pay a row-stat read after every turn.\n this._scheduleMediaEvictionAfterAppend(\n 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 );\n\n // Force Session to initialize its tables (assistant_messages,\n // assistant_compactions, assistant_config, etc.) so that subsequent\n // config reads work.\n //\n // Hydration is bounded by `hydrationByteBudget` (a byte-budgeted\n // recent window on oversized transcripts), but even the budgeted read\n // can fail — and that failure must not escape onStart, or the DO is\n // bricked (#1710). Degrade to an empty in-memory view; persisted\n // history is untouched and the next safe-boundary `_syncMessages()`\n // retries.\n this._onStartDegradations = [];\n await withAgentSpan(\n this,\n \"hydrate_think_session\",\n \"startup\",\n { \"cloudflare.agents.component\": \"think\" },\n async () => {\n const hydrated = await this._runBestEffortOnStartStep(\n \"transcript-hydration\",\n () => this._syncMessages(),\n \"The agent is starting with an empty in-memory message view; \" +\n \"persisted history is untouched. If the error is SQLITE_NOMEM, \" +\n \"the stored transcript is too large to hydrate (often inline \" +\n \"base64 media in tool results) — compact or clear the session \" +\n \"to recover.\"\n );\n if (!hydrated) {\n this._replaceCachedMessages([]);\n }\n this._refreshMediaEvictionSignalFromCache();\n }\n );\n\n // 3-6. Extension initialization (if extensionLoader is set)\n if (this.extensionLoader) {\n await withAgentSpan(\n this,\n \"initialize_think_extensions\",\n \"startup\",\n { \"cloudflare.agents.component\": \"think\" },\n () => this._initializeExtensions()\n );\n }\n\n // 7. Protocol handlers\n await withAgentSpan(\n this,\n \"initialize_think_chat\",\n \"startup\",\n { \"cloudflare.agents.component\": \"think\" },\n async () => {\n this._resumableStream = new ResumableStream(this.sql.bind(this));\n this._restoreClientTools();\n this._restoreBody();\n this._setupProtocolHandlers();\n await this._initializeChannels();\n }\n );\n\n // 8. User's onStart\n await _onStart(props);\n\n // 9. Declarative scheduled tasks are code-defined and should reconcile\n // before draining any recovered programmatic work they may enqueue.\n // Best-effort: reconcile runs after the agent is otherwise functional,\n // and a failure (user getScheduledTasks() throwing, storage pressure)\n // must not brick the DO (#1710).\n await withAgentSpan(\n this,\n \"reconcile_think_schedules\",\n \"startup\",\n { \"cloudflare.agents.component\": \"think\" },\n () =>\n this._runBestEffortOnStartStep(\n \"scheduled-task-reconcile\",\n () => this._reconcileDeclaredScheduledTasks(),\n \"Declared scheduled tasks were not reconciled on this wake; the \" +\n \"next successful wake will reconcile them.\"\n )\n );\n\n // 10. Durable submissions may run user-defined model/hooks, so start them\n // after subclass initialization has completed. Best-effort for the same\n // reason as step 9.\n await withAgentSpan(\n this,\n \"recover_think_durable_work\",\n \"startup\",\n { \"cloudflare.agents.component\": \"think\" },\n () =>\n this._runBestEffortOnStartStep(\n \"durable-work-recovery\",\n async () => {\n await this._sweepActionLedger();\n await this._sweepActionPendingApprovals();\n await this._recoverSubmissionsOnStart();\n this._recoverWorkflowNotifications();\n if (this._hasPendingSubmissions()) {\n await this._scheduleSubmissionDrain();\n }\n if (this._hasPendingWorkflowNotifications()) {\n this._startWorkflowNotificationDrain();\n }\n },\n \"Pending submissions / workflow notifications were not recovered on \" +\n \"this wake; the next successful wake will recover them.\"\n )\n );\n\n // 11. Background bound on the persisted transcript: if hydration was\n // windowed, evict aged inline media so the footprint can converge down\n // (#1710). Runs after `blockConcurrencyWhile` releases — no boot cost.\n if (this._lastHydration?.truncated) {\n this._scheduleMediaEvictionPass({ force: true });\n }\n\n update({\n \"cloudflare.agents.hydration.messages\":\n this._lastHydration?.hydratedMessages,\n \"cloudflare.agents.hydration.content_bytes\":\n this._lastHydration?.totalContentBytes,\n \"cloudflare.agents.hydration.truncated\": this._lastHydration?.truncated,\n \"cloudflare.agents.start.degradations\": this._onStartDegradations.length\n });\n };\n this.onStart = (props?: Props) =>\n withAgentSpan(\n this,\n \"think_start\",\n \"startup\",\n { \"cloudflare.agents.component\": \"think\" },\n (update) => startThink(props, update)\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 * When the stored transcript exceeds `hydrationByteBudget`, this view is a\n * bounded window of the most recent messages (see `_lastHydration`); the\n * full history remains readable via `session.getHistory()`.\n */\n get messages(): UIMessage[] {\n return this._cachedMessages;\n }\n\n /**\n * Read the durable message path from session storage.\n *\n * Intentionally UNBUDGETED — unlike the cache refresh in `_syncMessages`,\n * which routes through `session.getRecentHistory(hydrationByteBudget)`, this\n * returns the full active path. Callers (message reconciliation, tool-update\n * application) must see every message: reconciliation diffs incoming client\n * messages against the complete server transcript, and a tool result can\n * target any message on the path, so a windowed read would drop rows and\n * corrupt the result.\n *\n * These full reads are not the unbounded boot-time hydration that bricked the\n * DO in #1710: they run during a live turn (never in `onStart`), so an\n * `SQLITE_NOMEM` here surfaces as a recoverable turn-level error rather than a\n * partyserver init-reset/alarm-retry loop. They also inherit step 1's\n * mitigation — `session.getHistory()` now fetches content in bounded chunks\n * (`messagesByPathIds`) instead of carrying blobs through the recursive CTE\n * and its `ORDER BY` sorter — and background media eviction shrinks the stored\n * footprint over time, so the steady-state read size converges down.\n */\n private async _readMessagesFromStorage(): Promise<UIMessage[]> {\n return (await this.session.getHistory()) as UIMessage[];\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. Delegates to the shared\n * `agents/chat` primitive so the repair pass and the backstop detector\n * (`_incompleteToolCallIds`) share the single source of truth for terminal\n * tool states.\n */\n private _toolPartHasSettledResult(record: Record<string, unknown>): boolean {\n return toolPartHasSettledResult(record);\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 // Delegates to the shared `agents/chat` primitive so Think and ai-chat run\n // identical repair logic. The overridable `repairInterruptedToolPart` hook\n // (default: flip to an errored result; subclasses can preserve a\n // client-resolved tool such as `ask_user` as text) is threaded through, and\n // the settled-result / input-normalization helpers are the shared defaults.\n return repairInterruptedToolParts(messages, {\n repairPart: (part) => this.repairInterruptedToolPart(part),\n isSettled: (record) => this._toolPartHasSettledResult(record),\n normalizeInput: (input) => normalizeToolInput(input)\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 /**\n * Run a best-effort internal onStart step, degrading on failure instead of\n * throwing.\n *\n * Throwing out of `onStart` is terminal: partyserver resets its init state\n * and rethrows, so every wake — including platform alarm retries — re-runs\n * the failing `onStart` and fails again. A data-driven failure (oversized\n * transcript, bad declared-task config) would permanently brick the DO and\n * drive an unbounded alarm-retry loop (#1710). Instead, record the\n * degradation, emit `chat:onstart:degraded`, and let the agent come up so\n * it stays reachable for remediation (compaction, clearing, redeploy).\n *\n * Returns `true` when the step succeeded.\n */\n private async _runBestEffortOnStartStep(\n step: OnStartDegradation[\"step\"],\n fn: () => unknown | Promise<unknown>,\n hint: string\n ): Promise<boolean> {\n try {\n await fn();\n return true;\n } catch (error) {\n this._onStartDegradations.push({ step, error });\n console.error(\n `[Think] onStart step \"${step}\" failed; continuing with degraded state. ${hint}`,\n error\n );\n this._emit(\"chat:onstart:degraded\", {\n step,\n error: error instanceof Error ? error.message : String(error)\n });\n return false;\n }\n }\n\n private _mediaEvictionRunning = false;\n private _mediaEvictionScheduled = false;\n private _mediaEvictionObservedOversized = false;\n\n /**\n * Schedule a background media-eviction pass (see `mediaEviction`).\n * Coalesces repeated requests; the timer fires after the current\n * event-loop work (and after `onStart`'s `blockConcurrencyWhile`), so\n * boot and turn latency are unaffected.\n */\n private _scheduleMediaEvictionPass(options?: { force?: boolean }): void {\n if (this._mediaEvictionScheduled || this._mediaEvictionRunning) return;\n const config = resolveMediaEvictionConfig(this.mediaEviction);\n if (!config) return;\n if (!options?.force && !this._mediaEvictionObservedOversized) return;\n this._mediaEvictionScheduled = true;\n setTimeout(() => {\n this._mediaEvictionScheduled = false;\n void this._evictAgedMediaBestEffort();\n }, 0);\n }\n\n private _scheduleMediaEvictionAfterAppend(message: UIMessage): void {\n const config = resolveMediaEvictionConfig(this.mediaEviction);\n if (!config) return;\n if (!this._mediaEvictionObservedOversized) {\n this._mediaEvictionObservedOversized = this._messageMayNeedMediaEviction(\n message,\n config\n );\n }\n if (!this._mediaEvictionObservedOversized) return;\n\n const keepRecent = Math.max(config.keepRecentMessages, MODEL_RECENT_WINDOW);\n if (this._cachedMessages.length > keepRecent) {\n this._scheduleMediaEvictionPass({ force: true });\n }\n }\n\n private _refreshMediaEvictionSignalFromCache(): void {\n const config = resolveMediaEvictionConfig(this.mediaEviction);\n if (!config) {\n this._mediaEvictionObservedOversized = false;\n return;\n }\n this._mediaEvictionObservedOversized = this._cachedMessages.some(\n (message) => this._messageMayNeedMediaEviction(message, config)\n );\n }\n\n private _messageMayNeedMediaEviction(\n message: UIMessage,\n config: ResolvedMediaEvictionConfig\n ): boolean {\n return JSON.stringify(message).length >= config.minPartBytes;\n }\n\n private _warnedEvictionUnsupported = false;\n\n /**\n * Evict oversized inline media from aged stored messages (#1710).\n *\n * Memory-bounded by design: row sizes come from `getHistoryRowStats()`\n * (no content loaded), only rows large enough to contain an evictable\n * part are parsed, and they are processed one at a time via\n * `session.internal_rewriteMessage` — the maintenance write path that\n * skips the full-history token-estimate broadcast a public\n * `updateMessage` performs per row. Evicted values are written to the\n * workspace BEFORE the row is rewritten, so a failed pass never loses\n * data. Best-effort: failures are logged and the next pass retries.\n *\n * The aged cutoff is `keepRecentMessages` clamped to at least\n * `MODEL_RECENT_WINDOW`: messages the model still replays at full\n * fidelity each turn are never rewritten, regardless of configuration.\n *\n * When a pass stops at `maxRowsPerPass` with eligible rows remaining,\n * another pass is scheduled automatically so a large backlog drains\n * without waiting for new appends. Termination is guaranteed: every\n * rewritten row drops below `minPartBytes` and is skipped by later\n * passes, so the eligible set strictly shrinks.\n *\n * Returns the pass totals, or `null` when eviction is disabled, already\n * running, or the provider cannot enumerate row sizes (warned once).\n */\n protected async _evictAgedMediaBestEffort(): Promise<{\n messages: number;\n parts: number;\n bytes: number;\n externalizedBytes: number;\n } | null> {\n if (this._mediaEvictionRunning) return null;\n const config = resolveMediaEvictionConfig(this.mediaEviction);\n if (!config) return null;\n this._mediaEvictionRunning = true;\n let backlogRemains = false;\n try {\n const stats = await this.session.getHistoryRowStats();\n if (!stats) {\n if (!this._warnedEvictionUnsupported) {\n this._warnedEvictionUnsupported = true;\n console.warn(\n \"[Think] mediaEviction is enabled but the configured \" +\n \"SessionProvider does not implement getHistoryRowStats; \" +\n \"media eviction is a no-op for this agent.\"\n );\n }\n return null;\n }\n const keepRecent = Math.max(\n config.keepRecentMessages,\n MODEL_RECENT_WINDOW\n );\n const aged = stats.slice(0, Math.max(0, stats.length - keepRecent));\n\n let processed = 0;\n const totals = { messages: 0, parts: 0, bytes: 0, externalizedBytes: 0 };\n for (const row of aged) {\n // A row smaller than the part threshold cannot contain an\n // evictable value — skip without parsing. Rewritten rows shrink\n // below the threshold, so later passes skip them here too.\n if (row.bytes < config.minPartBytes) continue;\n if (processed >= config.maxRowsPerPass) {\n backlogRemains = true;\n break;\n }\n processed++;\n\n const message = (await this.session.getMessage(\n row.id\n )) as UIMessage | null;\n if (!message) continue;\n\n const result = evictLargeMediaFromMessage(message, {\n minPartBytes: config.minPartBytes,\n externalize: config.externalizeToWorkspace,\n pathFor: (index, extension) =>\n `/attachments/evicted/${message.id}-${index}.${extension}`\n });\n if (!result.changed) continue;\n\n for (const blob of result.blobs) {\n await this.workspace.writeFile(blob.path, blob.data);\n totals.externalizedBytes += blob.data.length;\n }\n await this.session.internal_rewriteMessage(\n sanitizeMessage(result.message)\n );\n totals.messages++;\n totals.parts += result.parts;\n totals.bytes += result.bytes;\n }\n\n if (totals.messages > 0) {\n this._emit(\"chat:media:evicted\", totals);\n }\n return totals;\n } catch (error) {\n console.error(\n \"[Think] media eviction pass failed; a later pass will retry.\",\n error\n );\n return null;\n } finally {\n this._mediaEvictionRunning = false;\n if (backlogRemains) this._scheduleMediaEvictionPass({ force: true });\n }\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 /**\n * Result of the most recent cache refresh when `hydrationByteBudget` is\n * active. `truncated` means `this.messages` is a bounded recent window of\n * a larger stored transcript.\n */\n protected _lastHydration: {\n truncated: boolean;\n totalContentBytes: number;\n hydratedMessages: number;\n } | null = null;\n\n private _warnedHydrationWindowed = false;\n\n /**\n * Snapshot of the last `chat:hydration:windowed` emit, used to emit on\n * CHANGE rather than on every safe-boundary sync — a chronically\n * oversized session syncs many times per turn and would otherwise spam\n * identical events.\n */\n private _lastWindowedEmit: {\n totalContentBytes: number;\n hydratedMessages: number;\n } | null = null;\n\n /**\n * Refresh the live cache from durable storage at a safe boundary.\n *\n * Bounded by `hydrationByteBudget`: oversized transcripts hydrate as a\n * recent window instead of exhausting the isolate's memory (#1710). The\n * window never shrinks below `MODEL_RECENT_WINDOW` messages, so budgeted\n * hydration cannot starve the model-facing context assembly (which keeps\n * that many recent messages at full fidelity).\n */\n private async _syncMessages(): Promise<UIMessage[]> {\n const budget = this.hydrationByteBudget;\n if (!Number.isFinite(budget) || budget <= 0) {\n this._lastHydration = null;\n this._lastWindowedEmit = null;\n return this._replaceCachedMessages(await this._readMessagesFromStorage());\n }\n\n const recent = await this.session.getRecentHistory(\n budget,\n MODEL_RECENT_WINDOW\n );\n this._lastHydration = {\n truncated: recent.truncated,\n totalContentBytes: recent.totalContentBytes,\n hydratedMessages: recent.messages.length\n };\n if (recent.truncated) {\n if (!this._warnedHydrationWindowed) {\n this._warnedHydrationWindowed = true;\n console.warn(\n `[Think] Stored transcript (${recent.totalContentBytes} bytes) ` +\n `exceeds hydrationByteBudget (${budget} bytes); hydrated the ` +\n `most recent ${recent.messages.length} message(s) instead of ` +\n \"the full history. Durable storage is untouched. Compact the \" +\n \"session (or enable media eviction) to shrink it.\"\n );\n }\n const changed =\n this._lastWindowedEmit === null ||\n this._lastWindowedEmit.totalContentBytes !== recent.totalContentBytes ||\n this._lastWindowedEmit.hydratedMessages !== recent.messages.length;\n if (changed) {\n this._lastWindowedEmit = {\n totalContentBytes: recent.totalContentBytes,\n hydratedMessages: recent.messages.length\n };\n this._emit(\"chat:hydration:windowed\", {\n totalContentBytes: recent.totalContentBytes,\n budgetBytes: budget,\n hydratedMessages: recent.messages.length\n });\n }\n } else {\n this._lastWindowedEmit = null;\n }\n return this._replaceCachedMessages(recent.messages as UIMessage[]);\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 /** Sanitize + row-size-compact a message before it touches storage. */\n private _rowSafe(message: UIMessage): UIMessage {\n return enforceRowSizeLimit(sanitizeMessage(message), {\n warn: (m) => console.warn(`[Think] ${m}`)\n });\n }\n\n private async _appendMessageToHistory(\n message: UIMessage,\n parentId?: string | null\n ): Promise<UIMessage> {\n const safe = this._rowSafe(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 = this._rowSafe(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 = this._rowSafe(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 /**\n * The orphan-persist store adapter — orphan-persist steps **(c)/(d)** route\n * their write through this shared `OrphanPersistStore` seam (the\n * `SessionProvider` write-subset). Delegates to `this.session` with `_rowSafe`\n * applied at the write boundary (sanitize + row-size cap), exactly as Think's\n * other Session call sites do. The `SessionMessage → UIMessage` read cast is\n * confined here, matching those call sites.\n * @internal\n */\n protected _orphanStore(): OrphanPersistStore {\n return {\n getMessage: async (id) =>\n (await this.session.getMessage(id)) as UIMessage | null,\n appendMessage: (message, parentId) =>\n this.session.appendMessage(this._rowSafe(message), parentId),\n updateMessage: (message) =>\n this.session.updateMessage(this._rowSafe(message))\n };\n }\n\n private async _clearHistory(): Promise<void> {\n await this.session.clearMessages();\n // Drop any pending terminal record (#1645) so a stale exhaustion can't\n // replay onto a freshly-cleared (empty) conversation on reconnect. Covers\n // both the WS `chat-clear` path and the programmatic `clearMessages()` API.\n await this._clearChatTerminal();\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 /** Lazily-built shared resume-handshake driver (Tier-2). */\n private _resumeHandshakeInstance: ResumeHandshake | null = null;\n private _lastClientTools: ClientToolSchema[] | undefined;\n private _lastBody: Record<string, unknown> | undefined;\n private _continuation = new ContinuationState<Connection>();\n /**\n * Accepted-but-not-yet-streamed turns and the connections parked waiting for\n * one (#1784). See {@link ResumeHandshake} `preStream`.\n *\n * HIBERNATION INVARIANT: in-memory only, NOT persisted. Safe because the\n * pre-stream window cannot overlap hibernation — a turn between `begin()` and\n * stream start is an unresolved `onMessage` handler promise that pins the DO,\n * so eviction only happens once a durable stream exists (resumed via\n * `ResumableStream`) or the turn finished. Breaks if a pre-stream wait is ever\n * moved onto a durable alarm that releases the DO; if so, persist this state.\n */\n private _preStream = new PreStreamTurns<Connection>();\n // Shared auto-continuation barrier (#1649 / #1650): owns the coalesce timer\n // and the double-fire guard. Parameterized by this agent's stream-active\n // signal, apply-drain, and continuation-turn pipeline (`_fireAutoContinuation`).\n private _autoContinuation = new AutoContinuationController<Connection>({\n continuation: this._continuation,\n generateRequestId: () => crypto.randomUUID(),\n isStreamActive: () => this._streamingAssistant !== null,\n hasPendingInteraction: () => this._pendingInteractionPromise !== null,\n hasIncompleteToolBatch: () => this._hasIncompleteToolBatch(),\n drainInteractionApplies: () => this._drainInteractionApplies(),\n keepAliveWhile: <T>(fn: () => Promise<T>) => this.keepAliveWhile(fn),\n fire: () => this._fireAutoContinuation()\n });\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 /**\n * Request id → run id for in-flight agent-tool turns (null = resolved as\n * not an agent-tool turn, cached so unrelated turns don't re-query SQLite\n * per frame). Drives frame attribution in {@link broadcast}: a frame\n * belongs to a run iff it carries that run's turn request id, so an error\n * in an unrelated turn or a concurrent run can never leak into another\n * run's state (#1575).\n */\n private _agentToolRunsByRequestId = new Map<string, string | null>();\n private _submissionTableEnsured = false;\n private _workflowNotificationTableEnsured = false;\n private _declaredScheduledTasksTableEnsured = false;\n private _actionLedgerTableEnsured = false;\n private _actionPendingTableEnsured = 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 // Cheap idle guard so the common (no agent-tool child) broadcast path stays\n // allocation-free — only build the snoop hooks while a run is in flight.\n if (\n this._agentToolForwarders.size > 0 ||\n this._agentToolLiveSequences.size > 0\n ) {\n interceptAgentToolBroadcast(msg, {\n forwarders: this._agentToolForwarders,\n liveSequences: this._agentToolLiveSequences,\n lastErrors: this._agentToolLastErrors,\n responseType: MSG_CHAT_RESPONSE,\n runForRequest: (requestId) => this._agentToolRunForRequest(requestId)\n });\n }\n super.broadcast(msg, without);\n }\n\n /**\n * Resolve the agent-tool run whose turn owns a request id, or null when the\n * request is not an agent-tool turn. Falls back to the persisted child-run\n * row (whose `request_id` is written when the run's turn is bound, see\n * `startAgentToolRun`) so attribution survives a DO restart mid-run; either\n * outcome is cached.\n */\n private _agentToolRunForRequest(requestId: string): string | null {\n const cached = this._agentToolRunsByRequestId.get(requestId);\n if (cached !== undefined) return cached;\n // Active-run predicate: a child run is in flight while `status` is\n // `starting`/`running`; terminal rows set `status` AND `completed_at`\n // together (the lifecycle invariant), so this is equivalent to\n // `completed_at IS NULL` but states the intent. Kept consistent with\n // `_rebindAgentToolChildRunRequestId` and the ai-chat counterpart.\n const rows = this.sql<{ run_id: string }>`\n SELECT run_id FROM cf_agent_tool_child_runs\n WHERE request_id = ${requestId} AND status IN ('starting', 'running')\n LIMIT 1\n `;\n const runId = rows[0]?.run_id ?? null;\n this._agentToolRunsByRequestId.set(requestId, runId);\n return runId;\n }\n\n /**\n * Re-bind this facet's in-flight agent-tool child run to the CURRENT turn's\n * request id.\n *\n * When this facet is itself running as an agent-tool child and its turn is\n * interrupted (e.g. a deploy evicts it mid-run), the recovery continuation\n * (`continueLastTurn` / `_retryLastUserTurn`) mints a NEW request id. The\n * `cf_agent_tool_child_runs.request_id` column — and the in-memory attribution\n * map — still point at the pre-eviction turn, so `broadcast` can no longer\n * attribute the recovered turn's frames to the run. The parent's re-attach\n * tail then sees no forwarded chunks, its no-progress budget elapses, and it\n * abandons a healthy, still-advancing child as `interrupted`\n * (`agentToolReattachNoProgressTimeoutMs`). Re-binding the row to the recovery\n * turn's request id keeps frame attribution alive across recovery so the\n * parent re-attaches and follows the child to its real terminal.\n *\n * Safe to call on EVERY recovery continuation:\n * - Facets that never ran as an agent-tool child have no\n * `cf_agent_tool_child_runs` table → the guarded SELECT throws → no-op.\n * - A facet whose run already settled has no `starting`/`running` row → no-op.\n * - A child DO is addressed by its `runId` (`subAgent(cls, runId)`), so it\n * owns AT MOST ONE child-run row for its whole lifetime and is never reused\n * as a top-level chat agent — the single active row is unambiguously this\n * recovery's run. The `ORDER BY started_at DESC LIMIT 1` is defensive\n * belt-and-suspenders for that invariant.\n *\n * Uses the same `status IN ('starting','running')` active-run predicate as\n * `_agentToolRunForRequest` and the ai-chat counterpart (see the lifecycle\n * invariant note there).\n */\n private _rebindAgentToolChildRunRequestId(requestId: string): void {\n let runId: string | undefined;\n try {\n const rows = this.sql<{ run_id: string }>`\n SELECT run_id FROM cf_agent_tool_child_runs\n WHERE status IN ('starting', 'running')\n ORDER BY started_at DESC\n LIMIT 1\n `;\n runId = rows[0]?.run_id;\n } catch {\n // No child-run table on facets that never ran as an agent tool.\n return;\n }\n if (!runId) return;\n this._agentToolRunsByRequestId.set(requestId, runId);\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET request_id = ${requestId}\n WHERE run_id = ${runId}\n `;\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 model to use for inference. Must be overridden by subclasses.\n *\n * The return value can be either:\n *\n * - A **string** model id, resolved through the built-in\n * {@link https://www.npmjs.com/package/workers-ai-provider | workers-ai-provider}\n * off your `AI` binding (see {@link getAIBinding}). A `@cf/...` id hits\n * Workers AI directly; any other `\"<provider>/<model>\"` slug — e.g.\n * `\"openai/gpt-5.5\"`, `\"anthropic/claude-sonnet-4-5\"`, `\"google/gemini-2.5-pro\"`\n * — is routed through AI Gateway with resumable streaming on by default.\n * This is the common case: no extra package to install, no provider to wire.\n * - A fully-constructed AI SDK `LanguageModel`, for any other provider or for\n * full control over provider/gateway options.\n *\n * @example String (Workers AI)\n * ```typescript\n * getModel() {\n * return \"@cf/moonshotai/kimi-k2.7-code\";\n * }\n * ```\n *\n * @example String (third-party via AI Gateway)\n * ```typescript\n * getModel() {\n * return \"openai/gpt-5.5\";\n * }\n * ```\n *\n * @example Bring your own provider\n * ```typescript\n * import { createOpenAI } from \"@ai-sdk/openai\";\n * getModel() {\n * return createOpenAI({ apiKey: this.env.OPENAI_API_KEY })(\"gpt-5.5\");\n * }\n * ```\n */\n getModel(): ThinkModel {\n throw new Error(\n \"Override getModel() to return a model id string (e.g. \" +\n '\"@cf/moonshotai/kimi-k2.7-code\" or \"openai/gpt-5.5\") or a LanguageModel.'\n );\n }\n\n /**\n * Return the Workers AI binding used by the built-in default provider when\n * {@link getModel} returns a string. Defaults to `this.env.AI`. Override if\n * your binding is named something other than `AI`.\n */\n getAIBinding(): Ai {\n const binding = (this.env as { AI?: Ai }).AI;\n if (!binding) {\n throw new Error(\n \"Think's default model provider needs a Workers AI binding named \" +\n '\"AI\". Add `\"ai\": { \"binding\": \"AI\" }` to wrangler.jsonc, override ' +\n \"getAIBinding() to return your binding, or override getModel() to \" +\n \"return a LanguageModel.\"\n );\n }\n return binding;\n }\n\n /**\n * Lazily-constructed, instance-cached default provider. Bundles the `openai`\n * and `anthropic` wire-format plugins so a `\"<provider>/<model>\"` slug routes\n * through AI Gateway out of the box (covers OpenAI, Anthropic, Google,\n * xAI/Grok, Groq, and the OpenAI-compatible long tail).\n *\n * Cached per instance, which assumes {@link getAIBinding} is stable for the\n * lifetime of the agent (the default `this.env.AI` always is).\n */\n private _defaultProvider?: ReturnType<typeof createWorkersAI>;\n\n /**\n * Resolve a model value into a concrete AI SDK `LanguageModel`.\n *\n * Defaults to resolving {@link getModel}. A `LanguageModel` is returned as-is;\n * a string is built through the bundled default provider (see {@link getModel}\n * for the slug rules). Use this whenever you need a usable model outside the\n * main turn — e.g. a side `generateText` call for summarization/compaction —\n * since `getModel()` may return a bare string.\n */\n resolveModel(model: ThinkModel = this.getModel()): LanguageModel {\n if (typeof model !== \"string\") return model;\n this._defaultProvider ??= createWorkersAI({\n binding: this.getAIBinding(),\n providers: [openai, anthropic]\n });\n // `@cf/...` ids take Workers AI chat settings (sessionAffinity improves\n // prefix-cache hits). Any other slug is a catalog model routed through AI\n // Gateway; we pass no per-call settings, which avoids forcing options a\n // given provider/transport would reject.\n return model.startsWith(\"@cf/\")\n ? this._defaultProvider(model, { sessionAffinity: this.sessionAffinity })\n : this._defaultProvider(model);\n }\n\n /**\n * Return the fallback system prompt for the assistant.\n * Ignored when Session context blocks are configured. Use\n * `configureSession().withContext()` for always-on instructions that should\n * coexist with context blocks or skills.\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 action descriptors compiled into tools for the assistant. */\n getActions(): Record<string, Action> | Promise<Record<string, Action>> {\n return {};\n }\n\n /** Return messenger integrations that should be routed through this Think agent. */\n getMessengers(): ThinkMessengers {\n return {};\n }\n\n /**\n * Return the channels for this agent. Wraps (does not supersede)\n * {@link getMessengers}: the implicit `web` channel is always present, each\n * messenger from `getMessengers()` is absorbed as a `kind: \"messenger\"`\n * channel, and these entries add `web`/`voice`/`custom` surfaces plus\n * per-channel policy. A channel id that collides with a `getMessengers()` id\n * is an error.\n */\n configureChannels(): ThinkChannels | Promise<ThinkChannels> {\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, {\n ...options,\n channel: context.messengerId\n });\n } finally {\n this._activeMessengerContext = previous;\n }\n }\n\n /**\n * Bind the live messenger delivery surface for the active turn so\n * `deliverNotice` can post to the originating channel while a messenger turn\n * is running. Returns a restore function; save/restore keeps nested turns\n * safe. Called by `deliverMessengerReply`.\n */\n bindActiveDeliverySurface(surface: MessengerDeliverySurface): () => void {\n const previous = this._activeDeliverySurface;\n this._activeDeliverySurface = surface;\n return () => {\n this._activeDeliverySurface = previous;\n };\n }\n\n /**\n * The channel context for the active turn, if the turn resolved to a channel.\n * Readable from tools/hooks during a turn (e.g. to branch on `kind`).\n */\n get activeChannel(): ChannelContext | undefined {\n return this._activeChannelContext;\n }\n\n /**\n * The server-supplied metadata stamped on the active turn's user message\n * ({@link ChatOptions.metadata}). Like the channel stamp, it is persisted on\n * the durable user message, so recovered/continued turns re-resolve the same\n * value; client-supplied message metadata can never populate it (reserved\n * keys are stripped at intake). `undefined` when the turn carried none.\n */\n get activeTurnMetadata(): Record<string, unknown> | undefined {\n return this._turnMetadataFromMessages(this.messages);\n }\n\n /** Resolve a channel id to a turn-scoped {@link ChannelContext}, if registered. */\n private _resolveChannelContext(\n channel: string | undefined\n ): ChannelContext | undefined {\n if (!channel) {\n return undefined;\n }\n const definition = this._channels?.get(channel);\n if (!definition) {\n // A channel was requested but is not registered. Don't throw (a recovered\n // turn may name a channel later removed from `configureChannels()`), but\n // warn so a typo'd channel id is visible rather than silently policy-free.\n // `_channels` is undefined for sub-agents (no channel registry), where a\n // missing channel is expected, so only warn once the registry exists.\n if (this._channels) {\n console.warn(\n `[Think] turn requested channel \"${channel}\" which is not registered ` +\n `(configureChannels()/getMessengers()); no per-channel policy applied`\n );\n }\n return undefined;\n }\n this._emitChannelEvent({\n type: \"channel:resolved\",\n payload: {\n channel,\n kind: definition.kind,\n requestId: admittedTurnContext.getStore()?.requestId\n }\n });\n return {\n channelId: channel,\n kind: definition.kind,\n capabilities: definition.capabilities,\n messenger:\n definition.kind === \"messenger\" ? this.getMessengerContext() : undefined\n };\n }\n\n /**\n * Run `fn` with the turn-scoped channel context set for `channel`. No-op (just\n * runs `fn`) when the channel is unset or unregistered. Save/restore keeps\n * nested turns safe — mirrors `chatWithMessengerContext`.\n */\n private async _withChannelContext<T>(\n channel: string | undefined,\n fn: () => Promise<T>\n ): Promise<T> {\n const context = this._resolveChannelContext(channel);\n if (!context) {\n return fn();\n }\n const previous = this._activeChannelContext;\n this._activeChannelContext = context;\n try {\n return await fn();\n } finally {\n this._activeChannelContext = previous;\n }\n }\n\n /**\n * Stamp the channel id — and, when supplied, the caller's turn metadata —\n * onto user messages so a recovered/continued turn can re-resolve both from\n * durable history.\n */\n private _stampChannel(\n messages: UIMessage[],\n channel: string | undefined,\n turnMetadata?: Record<string, unknown>\n ): UIMessage[] {\n if (!channel && !turnMetadata) {\n return messages;\n }\n return messages.map((message) =>\n message.role === \"user\"\n ? {\n ...message,\n metadata: {\n ...(message.metadata as Record<string, unknown> | undefined),\n ...(channel ? { channel } : {}),\n ...(turnMetadata ? { turnMetadata } : {})\n }\n }\n : message\n );\n }\n\n /** Metadata of the latest user message in the given list, if any. */\n private _latestUserMessageMetadata(\n messages: UIMessage[]\n ): Record<string, unknown> | undefined {\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (message.role === \"user\") {\n return message.metadata as Record<string, unknown> | undefined;\n }\n }\n return undefined;\n }\n\n /** The channel stamped on the latest user message in the given list, if any. */\n private _channelFromMessages(messages: UIMessage[]): string | undefined {\n const channel = this._latestUserMessageMetadata(messages)?.channel;\n return typeof channel === \"string\" ? channel : undefined;\n }\n\n /** The turn metadata stamped on the latest user message, if any. */\n private _turnMetadataFromMessages(\n messages: UIMessage[]\n ): Record<string, unknown> | undefined {\n const turnMetadata =\n this._latestUserMessageMetadata(messages)?.turnMetadata;\n return turnMetadata &&\n typeof turnMetadata === \"object\" &&\n !Array.isArray(turnMetadata)\n ? (turnMetadata as Record<string, unknown>)\n : undefined;\n }\n\n /** Re-resolve the channel for a continuation from the latest user message. */\n private _channelFromLatestUserMessage(): string | undefined {\n return this._channelFromMessages(this.messages);\n }\n\n /**\n * Deliver a no-turn, channel-routed message — a deterministic status, fallback,\n * or notice — straight to the channel's delivery surface WITHOUT invoking the\n * model and WITHOUT opening a recovery incident.\n *\n * Routing precedence for the target channel: explicit `options.channel` → the\n * active turn's channel → `\"web\"`. The `web` channel renders via the transcript\n * (its only client render path), so a web notice is always transcript-visible;\n * messenger/voice deliver out of band and only touch the transcript when\n * `informModel: true`.\n *\n * Like `addMessages`, this bypasses the turn queue and is safe to call from\n * inside a tool `execute` without deadlocking.\n */\n async deliverNotice(\n text: string | { markdown: string },\n options?: DeliverNoticeOptions\n ): Promise<void> {\n const informModel = options?.informModel ?? false;\n const kind: DeliveryKind = options?.kind ?? \"notice\";\n const plain = typeof text === \"string\" ? text : text.markdown;\n const annotated = `[Delivered to the user out of band] ${plain}`;\n const channelId = options?.channel ?? this._activeChannelId() ?? \"web\";\n\n try {\n if (channelId === \"web\") {\n await this.addMessages([\n this._noticeMessage(informModel ? annotated : plain, kind)\n ]);\n } else {\n const surface =\n this._activeDeliverySurface ??\n (await this._messengerRuntime?.resolveDeliverySurface(\n channelId,\n options?.thread\n ));\n if (!surface) {\n const kindOf = this._channels?.get(channelId)?.kind;\n let hint: string;\n if (kindOf === undefined) {\n hint = `; channel \"${channelId}\" is not registered`;\n } else if (kindOf === \"messenger\") {\n hint = options?.thread\n ? ` (thread \"${options.thread}\")`\n : \"; pass { thread } for out-of-turn messenger notices\";\n } else {\n hint = `; channel kind \"${kindOf}\" has no out-of-turn delivery surface yet`;\n }\n throw new Error(\n `deliverNotice: cannot resolve a delivery surface for channel \"${channelId}\"${hint}`\n );\n }\n await surface.post(\n typeof text === \"string\" ? text : { markdown: text.markdown }\n );\n if (informModel) {\n await this.addMessages([this._noticeMessage(annotated, kind)]);\n }\n }\n this._emitChannelEvent({\n type: \"notice:delivered\",\n payload: { channel: channelId, kind, informModel }\n });\n } catch (error) {\n this._emitChannelEvent({\n type: \"notice:failed\",\n payload: {\n channel: channelId,\n error: error instanceof Error ? error.message : String(error)\n }\n });\n throw error;\n }\n }\n\n /**\n * The active turn's channel id, if any. Prefers the turn-scoped channel\n * context, then the active messenger turn's id; web turns have none, so\n * `deliverNotice` defaults to `\"web\"`.\n */\n private _activeChannelId(): string | undefined {\n return (\n this._activeChannelContext?.channelId ??\n this._activeMessengerContext?.messengerId\n );\n }\n\n private _noticeMessage(\n text: string,\n kind: DeliveryKind = \"notice\"\n ): UIMessage {\n return {\n id: crypto.randomUUID(),\n role: \"assistant\",\n parts: [{ type: \"text\", text }],\n metadata: { deliveryKind: kind }\n };\n }\n\n private async _initializeChannels(): Promise<void> {\n if (this.parentPath.length > 0) {\n return;\n }\n\n const configured = await this.configureChannels();\n const messengers = this.getMessengers();\n const { channels, messengers: messengerDefs } = resolveChannels(\n configured,\n messengers\n );\n this._channels = channels;\n\n if (Object.keys(messengerDefs).length === 0) {\n return;\n }\n\n this._messengerRuntime = new ThinkMessengerRuntime(\n messengerDefs,\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 const hasFetchTools = [...toolNames].some((name) =>\n name.startsWith(\"fetch_\")\n );\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 if (hasFetchTools) {\n lines.push(\n \"- If fetch tools are available, use them to read allowlisted HTTP resources (documentation, APIs). They are read-only and bounded; respect their allowlist and do not assume access to other URLs.\"\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 * Retention window for settled action ledger rows. Deleting a row ends the\n * idempotency guarantee for that key, so increase these windows for side\n * effects whose downstream idempotency horizon is longer. Set a status to\n * `false` to disable sweeping it.\n */\n actionLedgerRetention: ActionLedgerRetentionConfig = {\n settledMs: 30 * 24 * 60 * 60 * 1000,\n pendingMs: 90 * 24 * 60 * 60 * 1000,\n maxSweepRows: 500\n };\n\n /**\n * Lease window after which a durable `pending` action ledger row is assumed\n * abandoned (its executor isolate died) and may be reclaimed and re-run.\n * Reclaim re-runs `execute`, so it only applies to actions that declare an\n * explicit `idempotencyKey` — that key is the developer's assertion that the\n * keyed side effect is safe to retry. Fallback `tool:${toolCallId}` keys are\n * never reclaimed. Set to `false` to disable stale-pending reclaim entirely\n * (a stale row then blocks forever with `ActionPendingError`, the old\n * behavior). This is a retry lease, not a retention window: retention answers\n * \"when may we delete old rows?\"; the lease answers \"when may we assume the\n * previous executor died and retry safely?\". Keep `actionLedgerRetention.pendingMs`\n * well above this lease so reclaim happens before a sweep deletes the row.\n */\n actionLedgerPendingRetryLeaseMs: number | false = 5 * 60 * 1000;\n\n /**\n * Retention window for abandoned durable-pause approval rows — a\n * `kind: \"durable-pause\"` action that parked but was never approved or\n * rejected. Deleting a row makes that approval permanently unresolvable, so\n * default generously: \"approve days later from a dashboard\" is the use case.\n * Set to `false` to disable sweeping. Rows are deleted promptly on\n * approve/reject regardless; this only bounds truly abandoned pauses.\n */\n actionPendingApprovalTtlMs: number | false = 30 * 24 * 60 * 60 * 1000;\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 // ── Context-overflow handling (opt-in) ────────────────────────────\n //\n // Compaction normally only fires between turns (Session.compactAfter checks\n // the threshold on appendMessage). But a single long, tool-heavy turn grows\n // the prompt step-by-step inside one streamText loop and can exceed the\n // model's context window *mid-turn*, before the next pre-turn check — the\n // provider then 400s (\"prompt is too long\" / context_length_exceeded). The\n // `contextOverflow` config lets Think recover without baking provider\n // knowledge into core: the app classifies the error (`classifyChatError`),\n // Think reacts.\n\n /**\n * Opt-in handling for a turn that overflows the context window mid-flight.\n * See {@link ContextOverflowConfig}. Unset (the default) leaves the existing\n * terminal behavior unchanged.\n *\n * @example\n * ```typescript\n * override contextOverflow = {\n * reactive: true,\n * proactive: { maxInputTokens: 200_000 }\n * };\n * ```\n */\n contextOverflow?: ContextOverflowConfig;\n\n /** Whether the reactive compact-and-retry backstop is enabled. */\n private get _overflowReactiveEnabled(): boolean {\n return this.contextOverflow?.reactive === true;\n }\n\n /** Reactive compact-and-retry budget. */\n private get _overflowMaxRetries(): number {\n return this.contextOverflow?.maxRetries ?? 1;\n }\n\n /** Proactive guard config, when enabled. */\n private get _overflowGuard():\n | { maxInputTokens: number; headroom?: number; maxCompactions?: number }\n | undefined {\n return this.contextOverflow?.proactive;\n }\n\n /** Per-run cap on proactive compactions (independent of the reactive budget). */\n private get _overflowProactiveMaxCompactions(): number {\n return Math.max(1, this.contextOverflow?.proactive?.maxCompactions ?? 1);\n }\n\n /**\n * Count of model messages assembled from history at the start of the current\n * turn (captured in `_runInferenceLoop`). The proactive guard uses it to\n * splice this turn's in-flight steps onto a freshly recompacted head. Turns\n * are serialized, so a single value is safe.\n */\n private _turnModelMessageBaseline = 0;\n\n /**\n * The assembled tool set for the current turn, captured in\n * `_runInferenceLoop`. The proactive guard reuses it to convert the\n * recompacted history through the same `convertToModelMessages` tool schemas.\n * Turns are serialized, so a single value is safe.\n */\n private _activeTurnTools: ToolSet = {};\n private _activeTurnActionMetadata = new Map<string, CompiledActionMetadata>();\n private _activeTurnAuthorization: NormalizedActionAuthorization = {\n allowed: true\n };\n private _activeTurnActionApprovalDescriptors = new Map<\n string,\n ActionApprovalDescriptor\n >();\n private _activeTurnApprovedActionInputs = new Map<string, unknown>();\n private _activeActionLedgerExecutions = new Map<string, Promise<unknown>>();\n /**\n * Advisory reply attachments recorded by actions during the current admitted\n * turn (see `ctx.attachReply`). Single-slot because turns are serialized.\n * Reset at turn start in `_runInsideAdmittedTurnBody`; intentionally not\n * cleared at turn end so `onChatResponse` and `replyAttachments()` can read\n * it — the next turn's reset overwrites it.\n */\n private _activeTurnReplyAttachments: ReplyAttachment[] = [];\n private _activeTurnReplyAttachmentsRequestId: string | undefined;\n\n /**\n * Number of times the proactive guard has compacted within the current\n * `_runInferenceLoop` (reset at the top of each run). Capped at\n * `contextOverflow.proactive.maxCompactions` (default `1`) so a guard that\n * keeps reading over-budget usage can't compact on every step — once the head\n * is summarized, further compaction no-ops anyway, and a genuine remaining\n * overflow falls through to the reactive backstop.\n */\n private _proactiveCompactionsThisRun = 0;\n\n /** One-time guard for the \"recovery enabled but no classifier\" DX warning. */\n private _warnedMissingClassifier = false;\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 if (this.getSystemPrompt !== Think.prototype.getSystemPrompt) {\n const warning =\n \"getSystemPrompt() is only used as a fallback when no Session context blocks are configured. getSkills() registers a skills context block, so move always-on instructions into configureSession().withContext(...) instead.\";\n if (!this._loggedSkillWarnings.has(warning)) {\n this._loggedSkillWarnings.add(warning);\n console.warn(`[think] ${warning}`);\n }\n }\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 * Authorize action permissions for the current turn. Returning `true` grants\n * all action permissions. Returning `grantedPermissions` limits the default\n * `authorizeAction` implementation to that permission set.\n */\n authorizeTurn(\n _ctx: TurnContext\n ): ActionAuthorizationDecision | Promise<ActionAuthorizationDecision> {\n return true;\n }\n\n /**\n * Authorize a single action call after its model input and required\n * permissions are known. Override this for app-specific policy; the default\n * implementation enforces the grant returned from `authorizeTurn`.\n */\n authorizeAction(\n ctx: ActionAuthorizationContext\n ): ActionAuthorizationDecision | Promise<ActionAuthorizationDecision> {\n const turnAuthorization = this._activeTurnAuthorization;\n if (!turnAuthorization.allowed) {\n return {\n allowed: false,\n reason: turnAuthorization.reason\n };\n }\n if (turnAuthorization.grantedPermissions === undefined) {\n return true;\n }\n const granted = new Set(turnAuthorization.grantedPermissions);\n const missing = ctx.requiredPermissions.filter(\n (permission) => !granted.has(permission)\n );\n if (missing.length === 0) return true;\n return {\n allowed: false,\n reason: `Missing required permission: ${missing.join(\", \")}`\n };\n }\n\n /**\n * Enrich the approval descriptor shown in approval UIs for a paused codemode\n * `execute` execution. The default descriptor is derived from the first\n * pending action as `connector.method` with its args as the input; override\n * here to supply a human summary, the permissions it consumes, or a risk\n * level (returned fields are merged over the derived defaults).\n *\n * Not called for `kind: \"durable-pause\"` actions — those carry their own\n * descriptor from the `action()` config. Default returns `undefined` (use the\n * derived descriptor).\n */\n describePausedExecution(\n _pending: import(\"@cloudflare/codemode\").PendingAction[],\n _ctx: { requestId: string; toolCallId: string }\n ): Partial<ActionApprovalDescriptor> | undefined {\n return undefined;\n }\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 onStepEnd(ctx: StepContext): void | Promise<void> {\n return this.onStepFinish(ctx);\n }\n\n /**\n * Called after each step completes (initial, continue, tool-result).\n * Override for step-level logging or analytics.\n * @deprecated Prefer `onStepEnd`.\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 /**\n * Classify a raw chat-turn error into a provider-agnostic category.\n *\n * Think deliberately ships **no** provider-specific matching: it cannot know\n * that Anthropic's `\"prompt is too long\"` or OpenAI's\n * `context_length_exceeded` means \"context overflow\" without baking provider\n * knowledge into core. The app does know its provider/model, so it owns the\n * mapping — the same split Think already uses for `tokenCounter`.\n *\n * Currently this hook drives **only** context-overflow recovery: it is\n * consulted when a turn errors **and** `contextOverflow.reactive` is enabled\n * (if reactive is off, it is not called). Return `\"context_overflow\"` to run\n * the compact-and-retry backstop; if recovery cannot save the turn, that\n * classification is surfaced on the terminal `onChatError` call via\n * {@link ChatErrorContext.classification}. The other categories are reserved\n * for future use — returning one today is a no-op (the turn terminalizes as\n * usual) and it is **not** forwarded to `onChatError`. Returning\n * `void`/`\"unknown\"` keeps the existing terminal behavior.\n *\n * The argument may be an `Error`, an AI SDK `APICallError` (with\n * `statusCode`/`responseBody`), or — for in-stream provider errors that\n * surface as a stream error part rather than a throw — the error message\n * string. Narrow accordingly.\n *\n * The second argument carries a {@link ChatErrorContext}: when consulted for\n * overflow recovery it is `{ stage: \"stream\", requestId }`, so a classifier\n * can correlate the error with the in-flight turn (e.g. to call\n * {@link cancelChat}).\n *\n * @example Anthropic + OpenAI context-overflow\n * ```typescript\n * classifyChatError(error: unknown): ChatErrorClassification | void {\n * const text = error instanceof Error ? error.message : String(error);\n * if (/prompt is too long|context length|context_length_exceeded|maximum context/i.test(text)) {\n * return \"context_overflow\";\n * }\n * }\n * ```\n */\n classifyChatError(\n _error: unknown,\n _ctx?: ChatErrorContext\n ): ChatErrorClassification | void {}\n\n /**\n * Whether an error (thrown or surfaced as an in-stream error string) should\n * trigger the opt-in compact-and-retry backstop. Consults the app's\n * `classifyChatError` and the `contextOverflow.reactive` flag. Centralized\n * so both stream consumers (WebSocket + RPC) classify identically.\n */\n private _isRecoverableContextOverflow(\n error: unknown,\n requestId?: string\n ): boolean {\n if (!this._overflowReactiveEnabled) return false;\n // DX guard: enabling recovery without teaching Think which errors are\n // overflows silently does nothing. Warn once instead of failing quietly.\n if (this.classifyChatError === Think.prototype.classifyChatError) {\n if (!this._warnedMissingClassifier) {\n this._warnedMissingClassifier = true;\n console.warn(\n '[Think] contextOverflow.reactive is enabled but classifyChatError() is not overridden, so no error will ever be treated as a context overflow and recovery will never run. Override classifyChatError() (or assign the exported defaultContextOverflowClassifier) to return \"context_overflow\" for your provider\\'s context-window error (e.g. Anthropic \"prompt is too long\", OpenAI context_length_exceeded).'\n );\n }\n return false;\n }\n let classification: ChatErrorClassification | void;\n try {\n classification = this.classifyChatError(error, {\n stage: \"stream\",\n requestId\n });\n } catch (err) {\n console.warn(\n `[Think] classifyChatError threw; treating as non-overflow: ${err instanceof Error ? err.message : String(err)}`\n );\n return false;\n }\n return classification === \"context_overflow\";\n }\n\n /**\n * Compact the session in response to a context overflow (reactive backstop or\n * proactive guard). Returns whether history was actually shortened — a no-op\n * compaction (returns `null`) means a retry would just overflow again, so the\n * caller should fall through to the terminal error rather than loop.\n *\n * This is the single emit point for `chat:context:compacted`, so callers must\n * NOT emit it again.\n */\n private async _compactForContextOverflow(\n reason: \"reactive\" | \"proactive\",\n extra?: { requestId?: string; attempt?: number }\n ): Promise<boolean> {\n try {\n const result = await this.session.compact();\n const shortened = Boolean(result);\n this._emit(\"chat:context:compacted\", {\n reason,\n shortened,\n ...extra\n });\n return shortened;\n } catch (err) {\n console.warn(\n `[Think] context-overflow compaction failed: ${err instanceof Error ? err.message : String(err)}`\n );\n return false;\n }\n }\n\n /**\n * Finalize a context overflow that recovery could not fix (compaction was a\n * no-op, or the retry budget is spent). Routes the error through\n * `onChatError` with `classification: \"context_overflow\"` and emits\n * `chat:request:failed`, so every overflow terminal — whichever path it took\n * — is reported identically. Returns the (possibly app-reshaped) message for\n * the caller to deliver via its own transport (RPC callback / WS broadcast).\n */\n private _finalizeContextOverflowError(\n requestId: string,\n rawError: string | undefined\n ): string {\n const raw = rawError ?? \"Context window exceeded.\";\n const wrapped = this.onChatError(raw, {\n requestId,\n stage: \"stream\",\n messagesPersisted: true,\n classification: \"context_overflow\"\n });\n const message =\n wrapped instanceof Error ? wrapped.message : String(wrapped);\n this._emit(\"chat:request:failed\", {\n requestId,\n stage: \"stream\",\n messagesPersisted: true,\n error: message\n });\n return message;\n }\n\n // ── Extension initialization ───────────────────────────────────\n\n private async _initializeExtensions(): Promise<void> {\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 * Assemble provider-ready model messages from the current session history:\n * repair the transcript, truncate older messages, drop any still-incomplete\n * tool calls, and convert to `ModelMessage[]`. Shared by the turn entry point\n * and the proactive context guard so a mid-turn recompaction rebuilds the\n * head through the exact same pipeline.\n */\n private async _assembleModelMessages(\n tools: ToolSet\n ): Promise<Awaited<ReturnType<typeof convertToModelMessages>>> {\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 return convertToModelMessages(truncated, {\n tools,\n ignoreIncompleteToolCalls: true\n });\n }\n\n /**\n * Proactive context guard (Layer 1). Runs before each step from the\n * `prepareStep` wrapper. If `contextOverflow.proactive` is set and the *previous*\n * step's model-reported input tokens cross the budget, compact the session in\n * place and return recompacted messages for the upcoming step — heading off a\n * provider context-overflow 400 before it happens.\n *\n * Keys off `usage.inputTokens` (provider-agnostic; every provider reports it)\n * rather than any provider error string, and reuses `_assembleModelMessages`\n * so the recompacted head goes through the same repair/convert pipeline. The\n * current turn's in-flight steps (everything after `_turnModelMessageBaseline`)\n * are spliced back on so no completed work is lost.\n *\n * Best-effort: any failure (no-op compaction, reconciliation that would leave\n * an incomplete tool pair) returns `undefined` so the step proceeds unchanged\n * and the reactive backstop (`contextOverflow.reactive`) can still\n * catch a genuine overflow.\n */\n private async _maybeProactiveContextCompact(\n event: PrepareStepContext\n ): Promise<Awaited<ReturnType<typeof convertToModelMessages>> | undefined> {\n const guard = this._overflowGuard;\n if (!guard || guard.maxInputTokens <= 0) return undefined;\n // Proactive cap is independent of the reactive budget — it has its own\n // `proactive.maxCompactions` (default 1). This lets an app use the proactive\n // guard without the reactive backstop (and vice versa) and tune each freely.\n if (\n this._proactiveCompactionsThisRun >= this._overflowProactiveMaxCompactions\n )\n return undefined;\n\n const prev = event.steps?.at(-1);\n const used = prev?.usage?.inputTokens ?? prev?.usage?.totalTokens;\n if (used == null || !Number.isFinite(used)) return undefined;\n\n const headroom = guard.headroom ?? 0.9;\n if (used < guard.maxInputTokens * headroom) return undefined;\n\n try {\n // Count the ATTEMPT (not just successful shortenings) before compacting.\n // This bounds the guard to `proactiveCap` tries per run regardless of\n // outcome: a no-op compaction (e.g. nothing left to summarize) would be a\n // no-op again on every subsequent step, so consuming the slot here is\n // what stops it from compacting — and emitting `chat:context:compacted` —\n // on every step. A genuine remaining overflow falls through to the\n // reactive backstop. (Locked by the \"no-op\" proactive test.)\n this._proactiveCompactionsThisRun++;\n const shortened = await this._compactForContextOverflow(\"proactive\");\n if (!shortened) return undefined;\n\n // Rebuild the compacted head, then splice this turn's in-flight steps\n // (which are not yet persisted to the session) back onto the tail.\n const head = await this._assembleModelMessages(this._activeTurnTools);\n const tail = event.messages.slice(this._turnModelMessageBaseline);\n const merged = [...head, ...tail];\n // Re-baseline so a second guard fire this turn keeps the new tail. This\n // is correct only if the AI SDK carries our returned `messages` override\n // forward into the next step's `event.messages` (so the next slice sees\n // [recompacted head, ...in-flight steps], not the original uncompacted\n // array). Verified by the \"fires twice in one turn\" test in\n // assistant-agent-loop.test.ts — a clean multi-fire completion proves the\n // override propagates and the splice does not drop/duplicate tool pairs.\n this._turnModelMessageBaseline = head.length;\n return merged;\n } catch (err) {\n console.warn(\n `[Think] proactive context compaction failed; proceeding without it: ${err instanceof Error ? err.message : String(err)}`\n );\n return undefined;\n }\n }\n\n /**\n * Finalizes the traced inference stream after a drain loop exits: drains the\n * abandoned tee branch so the operation span closes even on early exits.\n * Idempotent (the finalizer is removed before it runs); the drain rides\n * `ctx.waitUntil` so it survives turn completion without blocking it.\n */\n private _drainInferenceStream(result: object): void {\n const finalizer = inferenceStreamFinalizers.get(result);\n inferenceStreamFinalizers.delete(result);\n if (!finalizer || finalizer.started) {\n return;\n }\n\n finalizer.started = true;\n // Invoke exactly once: start the drain, then try to extend its lifetime.\n // A missing/throwing waitUntil must not start a second tee consumer.\n const completion = finalizer.run();\n try {\n this.ctx.waitUntil(completion);\n } catch {\n // waitUntil unavailable (tests, exotic contexts): the drain is already\n // running; nothing further to attach it to.\n }\n }\n\n /**\n * Adds default identity and current-turn metadata to the AI SDK telemetry\n * options. The class identifies the logical agent implementation, the named\n * instance identifies the agent resource, and the opaque Durable Object id\n * identifies its one persisted conversation. Caller values override defaults.\n */\n private _turnTelemetry(\n base: Parameters<typeof streamText>[0][\"experimental_telemetry\"]\n ): Parameters<typeof streamText>[0][\"experimental_telemetry\"] {\n const settings = (base ?? {}) as unknown as Record<string, unknown>;\n const metadata =\n typeof settings.metadata === \"object\" && settings.metadata !== null\n ? (settings.metadata as Record<string, unknown>)\n : {};\n const turn = admittedTurnContext.getStore();\n return {\n ...settings,\n // AI SDK maps functionId to gen_ai.agent.name. Use the class name by\n // default while preserving an explicit caller label.\n functionId:\n typeof settings.functionId === \"string\"\n ? settings.functionId\n : this.constructor.name,\n metadata: {\n agentId: this.name,\n conversationId: this.ctx.id.toString(),\n ...(turn?.agent === this\n ? {\n \"cloudflare.agents.turn.request_id\": turn.requestId,\n \"cloudflare.agents.turn.trigger\": turn.trigger,\n \"cloudflare.agents.turn.admission\": turn.admission,\n ...(turn.channel !== undefined && {\n \"cloudflare.agents.turn.channel\": turn.channel\n }),\n ...(turn.continuation !== undefined && {\n \"cloudflare.agents.turn.continuation\": turn.continuation\n }),\n ...(turn.generation !== undefined && {\n \"cloudflare.agents.turn.generation\": turn.generation\n })\n }\n : {}),\n // beforeTurn remains authoritative. metadata.agentName, when supplied,\n // also takes precedence over functionId in the tracing adapter.\n ...metadata\n }\n } as unknown as Parameters<typeof streamText>[0][\"experimental_telemetry\"];\n }\n\n /** Builds the native AI SDK v7 telemetry settings and identity context. */\n private _turnTelemetryV7(\n base: Parameters<typeof streamText>[0][\"experimental_telemetry\"]\n ): {\n options: Record<string, unknown>;\n runtimeContext: Record<string, unknown>;\n } {\n const settings = (base ?? {}) as unknown as Record<string, unknown>;\n const metadata =\n typeof settings.metadata === \"object\" && settings.metadata !== null\n ? (settings.metadata as Record<string, unknown>)\n : {};\n const turn = admittedTurnContext.getStore();\n const runtimeContext: Record<string, unknown> = {\n agentId: this.name,\n conversationId: this.ctx.id.toString(),\n ...(turn?.agent === this\n ? {\n \"cloudflare.agents.turn.request_id\": turn.requestId,\n \"cloudflare.agents.turn.trigger\": turn.trigger,\n \"cloudflare.agents.turn.admission\": turn.admission,\n ...(turn.channel !== undefined && {\n \"cloudflare.agents.turn.channel\": turn.channel\n }),\n ...(turn.continuation !== undefined && {\n \"cloudflare.agents.turn.continuation\": turn.continuation\n }),\n ...(turn.generation !== undefined && {\n \"cloudflare.agents.turn.generation\": turn.generation\n })\n }\n : {}),\n ...metadata\n };\n const includedContext =\n typeof settings.includeRuntimeContext === \"object\" &&\n settings.includeRuntimeContext !== null\n ? (settings.includeRuntimeContext as Record<string, boolean>)\n : {};\n const localIntegrations = settings.integrations;\n const globalIntegrations = (\n globalThis as typeof globalThis & {\n AI_SDK_TELEMETRY_INTEGRATIONS?: unknown[];\n }\n ).AI_SDK_TELEMETRY_INTEGRATIONS;\n const integrations = [\n ...(localIntegrations !== undefined\n ? Array.isArray(localIntegrations)\n ? localIntegrations\n : [localIntegrations]\n : (globalIntegrations ?? []))\n ];\n const options: Record<string, unknown> = {\n ...settings,\n functionId:\n typeof settings.functionId === \"string\"\n ? settings.functionId\n : this.constructor.name,\n includeRuntimeContext: {\n ...Object.fromEntries(\n Object.keys(runtimeContext).map((key) => [key, true])\n ),\n ...includedContext\n },\n integrations\n };\n delete options.metadata;\n return { options, runtimeContext };\n }\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 const turn = admittedTurnContext.getStore();\n const invoke = await withAgentSpan(\n this,\n \"prepare_agent\",\n \"turn\",\n {\n \"cloudflare.agents.component\": \"think\",\n ...(turn?.agent === this\n ? {\n \"cloudflare.agents.turn.request_id\": turn.requestId,\n \"cloudflare.agents.turn.trigger\": turn.trigger,\n \"cloudflare.agents.turn.admission\": turn.admission,\n \"cloudflare.agents.turn.channel\": turn.channel,\n \"cloudflare.agents.turn.continuation\": turn.continuation,\n \"cloudflare.agents.turn.generation\": turn.generation\n }\n : {})\n },\n () => this._prepareInferenceInvocation(input)\n );\n return invoke();\n }\n\n private async _prepareInferenceInvocation(\n input: TurnInput\n ): Promise<() => StreamableResult> {\n // Keep one exposure policy for this inference attempt even if subclass\n // code changes the instance property while asynchronous setup is running.\n const includeMcpTools = this.includeMcpTools;\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 this._activeTurnAuthorization = { allowed: true };\n this._activeTurnApprovedActionInputs =\n this._approvedActionInputsFromTranscript();\n // Reset the proactive-compaction cap for this streamText run.\n this._proactiveCompactionsThisRun = 0;\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 fetchToolSet: ToolSet = this.fetchTools\n ? createFetchTools({\n ...this.fetchTools,\n workspace: this.workspace,\n onEvent: (event: FetchToolEvent) => {\n (\n this._emit as unknown as (\n type: string,\n payload: Record<string, unknown>\n ) => void\n ).call(this, \"tool:fetch\", { ...event });\n }\n })\n : {};\n const baseTools = this.getTools();\n const actionTools = await this._compileActionTools();\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(\n input.clientTools,\n input.clientToolExecutor\n ? { execute: input.clientToolExecutor }\n : undefined\n );\n let tools: ToolSet = {\n ...workspaceTools,\n ...fetchToolSet,\n ...baseTools,\n ...actionTools,\n ...extensionTools,\n ...contextTools,\n ...skillTools,\n ...(includeMcpTools ? (this.mcp?.getAITools?.() ?? {}) : {}),\n ...clientToolSet\n };\n\n // Per-channel policy (overridable defaults applied BEFORE `beforeTurn`):\n // narrow the tool set (the `config.tools` seam can only ADD, never remove)\n // and prepend channel instructions to the base system prompt.\n const channelContext = this._activeChannelContext;\n const channelDefinition = channelContext\n ? this._channels?.get(channelContext.channelId)\n : undefined;\n if (channelDefinition?.tools) {\n tools = channelDefinition.tools(tools);\n }\n\n const channelInstructions =\n channelDefinition?.instructions && channelContext\n ? typeof channelDefinition.instructions === \"function\"\n ? await channelDefinition.instructions(channelContext)\n : channelDefinition.instructions\n : undefined;\n\n const frozenPrompt = await this.session.freezeSystemPrompt();\n const rawBaseSystem = frozenPrompt || this.getSystemPrompt();\n const baseSystem = channelInstructions\n ? `${channelInstructions}\\n\\n${rawBaseSystem}`\n : rawBaseSystem;\n const system = this._systemPromptForTurn(baseSystem, tools);\n\n const messages = await this._assembleModelMessages(tools);\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.resolveModel();\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 // Workflow `step.prompt` turns produce their structured result by calling\n // the synthetic `final_answer` tool (see THINK_FINAL_ANSWER_TOOL_NAME) —\n // NOT via the AI SDK `output`/`response_format` path, which some providers\n // reject when streaming. We pre-build the JSON Schema once here.\n const structuredOutputSchema = workflowPrompt?.output\n ? jsonSchema(workflowPrompt.output.schema as never)\n : undefined;\n const wantsStructuredOutput = structuredOutputSchema !== undefined;\n\n const finalModel =\n config.model != null ? this.resolveModel(config.model) : model;\n const finalSystem =\n config.instructions ??\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 const finalTurnContext: TurnContext = {\n ...ctx,\n system: finalSystem,\n messages: finalMessages,\n tools: mergedTools,\n model: finalModel\n };\n this._activeTurnAuthorization = this._normalizeActionAuthorization(\n await this.authorizeTurn(finalTurnContext)\n );\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 // For a structured workflow turn, expose a final-answer tool alongside the\n // agent's real tools. The agent loops with its tools and terminates by\n // calling this one; its arguments are captured as the structured result.\n // Guard against a clash with a user tool of the same name by suffixing.\n let finalAnswerToolName = THINK_FINAL_ANSWER_TOOL_NAME;\n if (structuredOutputSchema) {\n let suffix = 1;\n while (finalAnswerToolName in finalTools) {\n finalAnswerToolName = `${THINK_FINAL_ANSWER_TOOL_NAME}_${suffix++}`;\n }\n finalTools[finalAnswerToolName] = tool({\n description:\n \"Provide your final answer. The arguments MUST match the required \" +\n \"schema. Calling this tool ends the task — call it exactly once when \" +\n \"you have everything you need.\",\n inputSchema: structuredOutputSchema,\n execute: async () => \"Final answer recorded.\"\n });\n }\n\n // Baseline for the proactive context guard: everything the AI SDK appends\n // to the model-message list after the assembled turn messages belongs to\n // this turn's steps, so a mid-turn recompaction can keep that tail and only\n // re-summarize the (now-compacted) head. Captured from the FINAL messages\n // and tools — after `beforeTurn` may have overridden them — so the tail\n // splice stays correct even when the override changes the message count.\n this._turnModelMessageBaseline = finalMessages.length;\n this._activeTurnTools = mergedTools;\n\n // `maxTurns` is an overridable per-channel default: a user `beforeTurn`\n // returning `maxSteps` still wins, then the channel cap, then the instance\n // default.\n const finalMaxSteps =\n config.maxSteps ?? channelDefinition?.maxTurns ?? 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 // `output` (AI SDK structured-output / `response_format`) is reserved for\n // the opt-in chat `TurnConfig.output` API. Workflow prompts use the\n // `final_answer` tool instead (see `wantsStructuredOutput`).\n const finalOutput = config.output;\n // On a structured workflow turn, append the instruction telling the model to\n // finish by calling `final_answer`. `filter(Boolean)` drops an absent system\n // prompt so we never stringify `undefined` into the prompt.\n const turnSystem = wantsStructuredOutput\n ? [finalSystem, thinkFinalAnswerInstruction(finalAnswerToolName)]\n .filter(Boolean)\n .join(\"\\n\\n\")\n : finalSystem;\n // Structured turns must not end with a plain-text answer that skips\n // `final_answer` (some models, e.g. Workers AI llama, otherwise just reply\n // in text and stop). Force tool use: when the agent has real tools, require\n // *a* tool each step so it can do work and then call `final_answer`; with no\n // real tools, pin the choice directly to `final_answer`. A caller-provided\n // `toolChoice` still wins.\n const structuredHasRealTools =\n wantsStructuredOutput &&\n Object.keys(finalTools).some((name) => name !== finalAnswerToolName);\n const finalToolChoice = wantsStructuredOutput\n ? (config.toolChoice ??\n (structuredHasRealTools\n ? \"required\"\n : { type: \"tool\" as const, toolName: finalAnswerToolName }))\n : config.toolChoice;\n const finalStopWhen = [\n stepCountIs(finalMaxSteps),\n // Stop as soon as the model calls `final_answer` so the structured turn\n // terminates at the answer instead of continuing to stream more steps.\n ...(wantsStructuredOutput ? [hasToolCall(finalAnswerToolName)] : []),\n ...(Array.isArray(config.stopWhen)\n ? config.stopWhen\n : config.stopWhen\n ? [config.stopWhen]\n : [])\n ];\n\n const turnTelemetry = config.telemetry ?? config.experimental_telemetry;\n const streamTextOptions = {\n model: finalModel,\n // `system` is accepted by both AI SDK v6 and v7 (v7 also accepts the\n // renamed `instructions`, but v6 does not). Use `system` for cross-major\n // compatibility.\n system: turnSystem,\n messages: finalMessages,\n tools: finalTools,\n // Keep the synthetic final-answer tool callable even when a caller\n // restricts `activeTools` — otherwise a structured turn could never call\n // it and would fail to produce output.\n activeTools:\n wantsStructuredOutput && config.activeTools\n ? [...config.activeTools, finalAnswerToolName]\n : config.activeTools,\n toolChoice: finalToolChoice,\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: usesAISDKV7Telemetry\n ? undefined\n : this._turnTelemetry(turnTelemetry),\n // Forward the per-turn stream transform(s) from TurnConfig so callers\n // can inspect/rewrite the stream (e.g. emit `source` parts derived from\n // tool results) without owning the stream pipeline themselves.\n experimental_transform: config.experimental_transform,\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 // Proactive context guard (Layer 1) runs first so `beforeStep` sees the\n // recompacted messages and can still override them if it wants to.\n const guarded = await this._maybeProactiveContextCompact(event);\n const result = await this.beforeStep(event);\n const base = result == null ? {} : result;\n // Only apply the guard's recompacted messages when the subclass didn't\n // set its own `messages` override for this step.\n const baseMessages = (base as { messages?: unknown }).messages;\n const withMessages =\n guarded && baseMessages === undefined\n ? { ...base, messages: guarded }\n : base;\n // Safety net for structured workflow turns: on the final permitted step,\n // force the model to call `final_answer` so the turn always terminates\n // with a schema-shaped result instead of running out of steps. Respect a\n // `toolChoice` the subclass already set for this step.\n const stepResult =\n wantsStructuredOutput &&\n event.stepNumber >= finalMaxSteps - 1 &&\n (withMessages as { toolChoice?: unknown }).toolChoice === undefined\n ? {\n ...withMessages,\n toolChoice: {\n type: \"tool\" as const,\n toolName: finalAnswerToolName\n },\n activeTools: [finalAnswerToolName]\n }\n : withMessages;\n // `beforeStep` may return a string `model` (StepConfig widens it to\n // ThinkModel); the AI SDK needs a concrete LanguageModel, so resolve it.\n const stepModel = (stepResult as { model?: ThinkModel }).model;\n if (typeof stepModel === \"string\") {\n return {\n ...stepResult,\n model: this.resolveModel(stepModel)\n } as PrepareStepResult<ToolSet>;\n }\n return stepResult as PrepareStepResult<ToolSet>;\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` is the step callback name in both AI SDK v6 and v7 (v7\n // also accepts the renamed `onStepEnd`, but v6 does not). Use the shared\n // name; it still dispatches to Think's `onStepEnd` hook.\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.onStepEnd(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 execution time and the discriminated `success`/`error`\n // outcome — including failures that propagate out of `execute`.\n //\n // We register `experimental_onToolCallFinish` (rather than the v7-only\n // `onToolExecutionEnd`) because it is the native option in AI SDK v6 and\n // a supported alias in v7 — `ai` resolves it to `onToolExecutionEnd`\n // internally and fires it exactly once. `normalizeToolFinishEvent`\n // reconciles the differing event shapes between the two majors.\n experimental_onToolCallFinish: (async (event) => {\n // The synthetic final-answer tool is internal plumbing for structured\n // workflow turns — do not surface it to user `afterToolCall` hooks or\n // extensions.\n const e = normalizeToolFinishEvent(event);\n if (e.toolCall.toolName === finalAnswerToolName) return;\n const { success, output, error } = e;\n const base = {\n ...e.toolCall,\n stepNumber: e.stepNumber,\n messages: e.messages,\n toolExecutionMs: e.toolExecutionMs,\n durationMs: e.toolExecutionMs\n };\n const ctx = (success\n ? {\n ...base,\n toolOutput: { type: \"tool-result\" as const, output },\n success: true as const,\n output\n }\n : {\n ...base,\n toolOutput: { type: \"tool-error\" as const, error },\n success: false as const,\n error\n }) as unknown as ToolCallResultContext;\n await this.afterToolCall(ctx);\n await this._pipelineExtensionToolCallFinish({\n toolCall: e.toolCall,\n stepNumber: e.stepNumber,\n durationMs: e.toolExecutionMs,\n success,\n output,\n error\n });\n }) as ToolCallFinishCallback\n } satisfies Parameters<typeof streamText>[0];\n\n const crossMajorOptions = streamTextOptions as unknown as Record<\n PropertyKey,\n unknown\n >;\n if (usesAISDKV7Telemetry) {\n const { options, runtimeContext } = this._turnTelemetryV7(turnTelemetry);\n delete crossMajorOptions.experimental_telemetry;\n crossMajorOptions.telemetry = options;\n crossMajorOptions.runtimeContext = runtimeContext;\n }\n if (admittedTurnContext.getStore()?.trigger === \"ws-chat\") {\n crossMajorOptions[agentsAISDKInvocationBounded] = true;\n }\n\n const inferenceStreamText = wrapAISDK(aiSdk, {\n storeMessages: this.storeMessages,\n storeTools: this.storeTools\n }).streamText;\n\n return () => {\n const result = inferenceStreamText(streamTextOptions);\n\n const outputPromise = wantsStructuredOutput\n ? // Structured workflow result = the `final_answer` tool call's INPUT\n // (its arguments), captured after the stream finishes. Take the last\n // call in case the model emitted more than one. `result.toolCalls` is a\n // `PromiseLike`, so wrap it to get a real `Promise` (for `.catch` below).\n Promise.resolve(result.toolCalls).then((calls) => {\n const finalCalls = calls.filter(\n (call) => call.toolName === finalAnswerToolName\n );\n const last = finalCalls[finalCalls.length - 1];\n if (!last) {\n throw new Error(\n `Model ended the turn without calling the ${finalAnswerToolName} tool`\n );\n }\n return last.input;\n })\n : finalOutput && result.output\n ? Promise.resolve(result.output)\n : 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: (options) => {\n const sendReasoning = options?.sendReasoning ?? finalSendReasoning;\n const onError = options?.onError ?? streamErrorToString;\n // Use the result's own `toUIMessageStream()` method rather than the\n // standalone `toUIMessageStream({ stream })` helper: the method exists\n // in both AI SDK v6 and v7 (deprecated in v7 but functional), whereas\n // the standalone helper and the `result.stream` property it needs are\n // v7-only.\n const uiStream = (\n result as {\n toUIMessageStream: (o: {\n sendReasoning?: boolean;\n onError?: (error: unknown) => string;\n }) => ReadableStream;\n }\n ).toUIMessageStream({ sendReasoning, onError });\n return readableStreamToAsyncIterable(uiStream);\n },\n output: outputPromise\n } satisfies StreamableResult;\n\n const finalizer: InferenceStreamFinalizer = {\n started: false,\n run: () =>\n // consumeStream never rejects (onError swallows) and is a no-op when\n // the stream already ran to completion.\n Promise.resolve(result.consumeStream({ onError: () => {} }))\n };\n inferenceStreamFinalizers.set(streamResult, finalizer);\n\n const finalized = this._transformInferenceResult(streamResult);\n if (finalized !== streamResult) {\n inferenceStreamFinalizers.set(finalized, finalizer);\n }\n return finalized;\n };\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 private _normalizeActionAuthorization(\n decision: ActionAuthorizationDecision\n ): NormalizedActionAuthorization {\n if (typeof decision === \"boolean\") {\n return { allowed: decision };\n }\n return {\n allowed: decision.allowed,\n ...(decision.reason !== undefined && { reason: decision.reason }),\n ...(decision.grantedPermissions !== undefined && {\n grantedPermissions: [...decision.grantedPermissions]\n })\n };\n }\n\n private _emitActionLedgerEvent(event: ActionLedgerEvent): void {\n const emit = this._emit as unknown as (\n type: string,\n payload: Record<string, unknown>\n ) => void;\n emit.call(this, event.type, event.payload);\n }\n\n private _emitChannelEvent(event: ChannelEvent): void {\n const emit = this._emit as unknown as (\n type: string,\n payload: Record<string, unknown>\n ) => void;\n emit.call(this, event.type, event.payload);\n }\n\n private _approvedActionInputsFromTranscript(): Map<string, unknown> {\n const approved = new Map<string, unknown>();\n for (const message of this.messages) {\n for (const part of message.parts ?? []) {\n if (typeof part !== \"object\" || part === null) continue;\n const record = part as Record<string, unknown>;\n const toolCallId =\n typeof record.toolCallId === \"string\" ? record.toolCallId : undefined;\n if (!toolCallId) continue;\n const approval = record.approval as\n | { approved?: unknown; descriptor?: unknown }\n | undefined;\n if (approval?.approved !== true) continue;\n const descriptor = approval.descriptor as\n | { input?: unknown; action?: unknown }\n | undefined;\n if (typeof descriptor?.action !== \"string\") continue;\n approved.set(\n toolCallId,\n \"input\" in descriptor ? descriptor.input : record.input\n );\n }\n }\n return approved;\n }\n\n private async _resolveActionPermissions(\n spec: ActionPermissionSpec<unknown> | undefined,\n input: unknown,\n ctx: ActionContext\n ): Promise<string[]> {\n if (spec === undefined) return [];\n const policyCtx = this._actionContextWithoutReply(ctx);\n const permissions =\n typeof spec === \"function\" ? await spec({ input, ctx: policyCtx }) : spec;\n return [...permissions];\n }\n\n private _actionContextWithoutReply(ctx: ActionContext): ActionContext {\n return {\n ...ctx,\n attachReply: () => {}\n };\n }\n\n private async _authorizeActionCall(options: {\n actionName: string;\n kind: ActionKind;\n input: unknown;\n ctx: ActionContext;\n permissions?: ActionPermissionSpec<unknown>;\n }): Promise<NormalizedActionAuthorization & { permissions: string[] }> {\n const permissions = await this._resolveActionPermissions(\n options.permissions,\n options.input,\n options.ctx\n );\n const decision = await this.authorizeAction({\n requestId: options.ctx.requestId,\n toolCallId: options.ctx.toolCallId,\n action: options.actionName,\n kind: options.kind,\n input: options.input,\n requiredPermissions: permissions,\n grantedPermissions: this._activeTurnAuthorization.grantedPermissions,\n messages: options.ctx.messages,\n agent: this,\n env: this.env as Cloudflare.Env\n });\n return {\n ...this._normalizeActionAuthorization(decision),\n permissions\n };\n }\n\n private async _compileActionTools(): Promise<ToolSet> {\n const actions = await this.getActions();\n const tools: ToolSet = {};\n this._activeTurnActionMetadata = new Map();\n this._activeTurnActionApprovalDescriptors = new Map();\n for (const [registrationName, descriptor] of Object.entries(actions)) {\n if (!isAction(descriptor)) {\n throw new Error(\n `getActions() entry \"${registrationName}\" must be created with action().`\n );\n }\n const toolName = descriptor.config.name ?? registrationName;\n const kind =\n descriptor.config.kind ??\n (descriptor.config.approval ? \"approval-gated\" : \"server\");\n if (kind === \"approval-gated\" || kind === \"durable-pause\") {\n const staticPermissions = Array.isArray(descriptor.config.permissions)\n ? [...descriptor.config.permissions]\n : undefined;\n this._activeTurnActionMetadata.set(toolName, {\n actionName: toolName,\n summary:\n descriptor.config.approvalSummary ?? descriptor.config.description,\n ...(staticPermissions !== undefined && {\n permissions: staticPermissions\n }),\n ...(descriptor.config.approvalRisk !== undefined && {\n risk: descriptor.config.approvalRisk\n }),\n kind\n });\n }\n tools[toolName] = this._actionToTool(descriptor, toolName, kind);\n }\n return tools;\n }\n\n private _actionToTool(\n descriptor: Action,\n toolName: string,\n kind: ActionKind\n ): ToolSet[string] {\n const config = descriptor.config;\n const executeAction = config.execute as (\n input: unknown,\n ctx: ActionContext\n ) => Promise<unknown> | unknown;\n const approval = config.approval as\n | ActionApprovalPolicy<unknown>\n | undefined;\n const permissions = config.permissions as\n | ActionPermissionSpec<unknown>\n | undefined;\n const idempotencyKey = config.idempotencyKey as\n | ActionIdempotencyKey<unknown>\n | undefined;\n\n return tool({\n description: config.description,\n metadata: {\n cfThinkAction: true,\n cfThinkActionApprovalConfigured:\n approval !== undefined && kind !== \"durable-pause\"\n },\n inputSchema: config.inputSchema as never,\n ...(approval !== undefined && kind !== \"durable-pause\"\n ? {\n needsApproval: async (\n input: unknown,\n options: {\n toolCallId: string;\n messages: ModelMessage[];\n }\n ) => {\n const ctx: ActionContext = {\n agent: this,\n env: this.env as Cloudflare.Env,\n requestId: admittedTurnContext.getStore()?.requestId ?? \"\",\n toolCallId: options.toolCallId,\n messages: options.messages,\n signal: new AbortController().signal,\n // No-op: approval/permission predicates must be pure and may\n // run twice (prompt + resume). Attachments belong to execute.\n attachReply: () => {}\n };\n if (\n this._activeTurnApprovedActionInputs.has(options.toolCallId)\n ) {\n return true;\n }\n const authorization = await this._authorizeActionCall({\n actionName: toolName,\n kind,\n input,\n ctx,\n permissions\n });\n if (!authorization.allowed) return false;\n const needsApproval =\n typeof approval === \"function\"\n ? await approval({ input, ctx })\n : approval;\n if (needsApproval) {\n this._activeTurnActionApprovalDescriptors.set(\n options.toolCallId,\n {\n requestId: ctx.requestId,\n toolCallId: options.toolCallId,\n action: toolName,\n summary: config.approvalSummary ?? config.description,\n input,\n permissions: authorization.permissions,\n ...(config.approvalRisk !== undefined && {\n risk: config.approvalRisk\n }),\n kind: \"approval-gated\"\n }\n );\n }\n return needsApproval;\n }\n }\n : {}),\n execute: async (\n input: unknown,\n options: {\n toolCallId?: string;\n messages?: ModelMessage[];\n abortSignal?: AbortSignal;\n }\n ): Promise<unknown> => {\n const { signal, cleanup } = createActionAbortSignal(\n options.abortSignal,\n config.timeoutMs ?? DEFAULT_ACTION_TIMEOUT_MS\n );\n const requestId = admittedTurnContext.getStore()?.requestId ?? \"\";\n const actionContext: ActionContext = {\n agent: this,\n env: this.env as Cloudflare.Env,\n requestId,\n toolCallId: options.toolCallId ?? \"\",\n messages: options.messages ?? [],\n signal,\n attachReply: (attachment) =>\n this._recordReplyAttachment(requestId, attachment, toolName)\n };\n const abortError = () =>\n signal.reason instanceof Error\n ? signal.reason\n : new Error(\n signal.reason ? String(signal.reason) : \"Action aborted\"\n );\n let onAbort: (() => void) | undefined;\n\n try {\n const authorization = await this._authorizeActionCall({\n actionName: toolName,\n kind,\n input,\n ctx: actionContext,\n permissions\n });\n if (!authorization.allowed) {\n return actionAuthorizationErrorEnvelope(\n authorization.reason,\n authorization.permissions\n );\n }\n if (signal.aborted) throw abortError();\n const abortPromise = new Promise<never>((_, reject) => {\n onAbort = () => reject(abortError());\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n const runAction = async () => {\n const output = await Promise.race([\n Promise.resolve(executeAction(input, actionContext)),\n abortPromise\n ]);\n return prepareActionOutputForModel(output);\n };\n\n if (kind === \"durable-pause\") {\n // The approval predicate gates whether to PARK (not whether an AI\n // SDK approval is needed). Absent → always park; a function may opt\n // a given input out of the human gate and run inline instead.\n const shouldPark =\n approval === undefined\n ? true\n : typeof approval === \"function\"\n ? await approval({\n input,\n ctx: this._actionContextWithoutReply(actionContext)\n })\n : approval;\n if (!shouldPark) {\n return await this._runLedgeredAction({\n toolName,\n idempotencyKey,\n input,\n ctx: actionContext,\n runAction\n });\n }\n return this._parkDurablePauseAction({\n toolName,\n input,\n ctx: actionContext,\n summary: config.approvalSummary ?? config.description,\n permissions: authorization.permissions,\n risk: config.approvalRisk\n });\n }\n\n return await this._runLedgeredAction({\n toolName,\n idempotencyKey,\n input,\n ctx: actionContext,\n runAction\n });\n } catch (error) {\n return actionErrorEnvelope(error);\n } finally {\n if (onAbort) signal.removeEventListener(\"abort\", onAbort);\n cleanup();\n }\n }\n });\n }\n\n /**\n * Run an action's `execute` through the action ledger: same-isolate\n * coalescing, durable claim/replay, settle-on-success, release-on-failure.\n * Shared by the inline server-action path and the durable-pause-on-approve\n * path so an action's side effect is replay-safe regardless of how it is\n * dispatched. `runAction` must already apply timeout/abort and\n * `prepareActionOutputForModel`.\n */\n private async _runLedgeredAction(args: {\n toolName: string;\n idempotencyKey: ActionIdempotencyKey<unknown> | undefined;\n input: unknown;\n ctx: ActionContext;\n runAction: () => Promise<unknown>;\n }): Promise<unknown> {\n const { toolName, idempotencyKey, input, ctx, runAction } = args;\n\n const ledgerKey = await this._resolveActionLedgerKey(\n toolName,\n idempotencyKey,\n input,\n this._actionContextWithoutReply(ctx)\n );\n if (!ledgerKey) {\n const attachmentCount = this._activeTurnReplyAttachments.length;\n try {\n return await runAction();\n } catch (error) {\n this._activeTurnReplyAttachments.length = attachmentCount;\n throw error;\n }\n }\n\n const active = this._activeActionLedgerExecutions.get(ledgerKey);\n if (active) {\n return await active;\n }\n\n const inputHash = this._actionInputHash(input);\n // An explicit `idempotencyKey` is the developer's assertion that retrying\n // the keyed side effect is safe; only those rows are reclaimable when stale.\n // Fallback `tool:${toolCallId}` keys stay conservative.\n const hasExplicitIdempotencyKey = idempotencyKey !== undefined;\n const claim = this._claimActionLedgerRow({\n key: ledgerKey,\n actionName: toolName,\n requestId: ctx.requestId,\n toolCallId: ctx.toolCallId,\n inputHash,\n retryablePending: hasExplicitIdempotencyKey,\n leaseMs: this.actionLedgerPendingRetryLeaseMs\n });\n if (claim.outcome === \"replay\") {\n this._emitActionLedgerEvent({\n type: \"action:ledger:replayed\",\n payload: { action: toolName, key: ledgerKey, inputHash }\n });\n return decodeActionLedgerOutput(claim.row.result_json);\n }\n if (claim.outcome === \"pending\") {\n this._emitActionLedgerEvent({\n type: \"action:ledger:pending\",\n payload: { action: toolName, key: ledgerKey, inputHash }\n });\n return actionPendingErrorEnvelope();\n }\n if (claim.outcome === \"conflict\") {\n this._emitActionLedgerEvent({\n type: \"action:ledger:conflict\",\n payload: { action: toolName, key: ledgerKey, inputHash }\n });\n return actionKeyConflictEnvelope(toolName, ledgerKey);\n }\n // `claimed` (fresh row) and `reclaimed` (stale row re-leased) both fall\n // through to execution below; reclaim just re-runs the keyed side effect.\n if (claim.outcome === \"reclaimed\") {\n this._emitActionLedgerEvent({\n type: \"action:ledger:reclaimed\",\n payload: {\n action: toolName,\n key: ledgerKey,\n inputHash,\n ageMs: Date.now() - claim.row.updated_at\n }\n });\n }\n\n const attachmentCount = this._activeTurnReplyAttachments.length;\n const execution = Promise.resolve().then(async () => {\n try {\n const prepared = await runAction();\n const encoded = encodeActionLedgerOutput(prepared);\n if (!encoded.ok) {\n this._releaseActionLedgerRow(ledgerKey);\n this._emitActionLedgerEvent({\n type: \"action:ledger:serialize_failed\",\n payload: { action: toolName, key: ledgerKey }\n });\n return prepared;\n }\n this._settleActionLedgerRow(ledgerKey, encoded.json);\n this._emitActionLedgerEvent({\n type: \"action:ledger:settled\",\n payload: { action: toolName, key: ledgerKey, inputHash }\n });\n return encoded.value;\n } catch (error) {\n this._activeTurnReplyAttachments.length = attachmentCount;\n throw error;\n }\n });\n this._activeActionLedgerExecutions.set(ledgerKey, execution);\n try {\n return await execution;\n } catch (error) {\n this._releaseActionLedgerRow(ledgerKey);\n return actionErrorEnvelope(error);\n } finally {\n this._activeActionLedgerExecutions.delete(ledgerKey);\n }\n }\n\n /**\n * Park a `kind: \"durable-pause\"` action for human approval. Persists a\n * compaction-safe pending row (action name + model input + approval\n * descriptor) so the approval survives history compaction, deploys, and\n * isolate eviction, then returns the minimal model-visible paused output.\n *\n * The action's `execute` does NOT run here — it runs later in\n * `approveExecution` via `_runLedgeredAction`, so the side effect is gated on\n * human approval AND remains replay-safe. The rich descriptor lives on the\n * row and on the transcript part, never embedded in the model-visible output.\n */\n private _parkDurablePauseAction(args: {\n toolName: string;\n input: unknown;\n ctx: ActionContext;\n summary: string;\n permissions: string[];\n risk?: \"low\" | \"medium\" | \"high\";\n }): {\n status: \"paused\";\n executionId: string;\n action: string;\n message: string;\n } {\n const { toolName, input, ctx, summary, permissions, risk } = args;\n const executionId = `${ACTION_PAUSE_ID_PREFIX}${crypto.randomUUID()}`;\n const descriptor: ActionApprovalDescriptor = {\n requestId: ctx.requestId,\n toolCallId: ctx.toolCallId,\n action: toolName,\n summary,\n input,\n permissions,\n ...(risk !== undefined && { risk }),\n kind: \"durable-pause\"\n };\n this._insertActionPendingRow({\n execution_id: executionId,\n action_name: toolName,\n tool_call_id: ctx.toolCallId,\n request_id: ctx.requestId || null,\n input_json: JSON.stringify(input),\n descriptor_json: JSON.stringify(descriptor),\n created_at: Date.now()\n });\n this._emitActionPauseEvent({\n type: \"action:pause:created\",\n payload: { action: toolName, executionId, toolCallId: ctx.toolCallId }\n });\n return {\n status: \"paused\",\n executionId,\n action: toolName,\n message:\n \"This action is awaiting human approval. Stop and wait for the \" +\n \"approval result before proceeding.\"\n };\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. The canonical form is an async\n * generator (`async function* execute(...)`), where calling `execute`\n * synchronously returns a direct `AsyncIterable`. For that form Think\n * preserves preliminary streaming: the wrapper is itself an async\n * generator that `await`s `beforeToolCall` and then yields every\n * chunk through unchanged. Non-streaming tools keep a scalar wrapper\n * so they never emit a synthetic `preliminary` tool-result chunk.\n *\n * The non-canonical `async function execute(...) { return makeIter(); }`\n * form returns a `Promise<AsyncIterable>`, which does not stream even\n * in the raw AI SDK (it would surface the iterator object as the final\n * output). Think collapses it to the last yielded value instead. If\n * you need preliminary streaming, use an `async function*` `execute`.\n */\n private _wrapToolsWithDecision(tools: ToolSet): ToolSet {\n const wrapped: ToolSet = {};\n // Capture `this` lexically so the streaming wrapper (which must be an\n // async generator function expression, not an arrow) can reach the\n // shared decision helper without a per-tool `.bind`.\n const self = this;\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 const metadata = t.metadata as Record<string, unknown> | undefined;\n const isApprovalConfiguredAction =\n metadata?.cfThinkAction === true &&\n metadata.cfThinkActionApprovalConfigured === true;\n\n // Canonical AI SDK streaming tools use an async generator `execute`\n // (`async function* execute(...)`). Detect that form so we can keep\n // preliminary streaming flowing through `beforeToolCall`. Everything\n // else routes through the scalar wrapper so non-streaming tools never\n // emit a synthetic `preliminary` tool-result.\n const isStreamingExecute =\n (originalExecute as { constructor?: { name?: string } }).constructor\n ?.name === \"AsyncGeneratorFunction\";\n\n const wrappedExecute = isStreamingExecute\n ? (input: unknown, options: ToolDecisionOptions) =>\n // Returning the generator synchronously (via the sync arrow)\n // keeps it a *direct* AsyncIterable so the AI SDK streams the\n // preliminary parts instead of awaiting a Promise<AsyncIterable>.\n (async function* () {\n const resolved = await self._resolveToolCallDecision(\n toolName,\n input,\n options,\n isDynamic,\n isApprovalConfiguredAction\n );\n if (!resolved.execute) {\n // Block/substitute is a scalar outcome, but this wrapper had\n // to commit to an AsyncIterable shape synchronously (before the\n // async decision was known) so the execute path can stream.\n // The AI SDK's `executeTool` turns every yielded value into a\n // `preliminary` tool-result plus a `final`, so this single\n // yield surfaces one synthetic `preliminary` chunk to observers\n // (e.g. onChunk) that the scalar wrapper never emits. The\n // model-visible final output is identical and correct, and this\n // matches how any streaming tool that emits a single value\n // already behaves — so we accept it rather than regress\n // streaming preservation for the (rare) block/substitute case.\n yield resolved.output;\n return;\n }\n const result = await originalExecute(\n resolved.finalInput,\n options\n );\n if (\n result != null &&\n typeof result === \"object\" &&\n Symbol.asyncIterator in (result as object)\n ) {\n // Stream the original tool's preliminary outputs through\n // unchanged — the AI SDK emits each as a `preliminary`\n // tool-result and the last as the final value.\n yield* result as AsyncIterable<unknown>;\n } else {\n yield result;\n }\n })()\n : async (\n input: unknown,\n options: ToolDecisionOptions\n ): Promise<unknown> => {\n const resolved = await self._resolveToolCallDecision(\n toolName,\n input,\n options,\n isDynamic,\n isApprovalConfiguredAction\n );\n if (!resolved.execute) return resolved.output;\n // Await before inspecting so we detect a direct AsyncIterable\n // return even from a non-async-generator `execute` (e.g. a\n // plain function that returns a generator). Such non-canonical\n // streaming shapes are collapsed to their last yielded value.\n const result = await originalExecute(resolved.finalInput, options);\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\n wrapped[toolName] = {\n ...(originalTool as object),\n execute: wrappedExecute\n } as ToolSet[string];\n }\n return wrapped;\n }\n\n /**\n * Shared `beforeToolCall` resolution for both the scalar and streaming\n * tool wrappers (see {@link _wrapToolsWithDecision}). Builds the\n * `ToolCallContext`, consults the subclass `beforeToolCall` hook,\n * dispatches the extension observation snapshot, and resolves the\n * returned `ToolCallDecision` into either \"run `execute` with this\n * input\" or \"short-circuit with this output\".\n */\n private async _resolveToolCallDecision(\n toolName: string,\n input: unknown,\n options: ToolDecisionOptions,\n isDynamic: boolean,\n isApprovalConfiguredAction: boolean\n ): Promise<\n { execute: true; finalInput: unknown } | { execute: false; output: unknown }\n > {\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 decision\n // 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 const approvedInput = isApprovalConfiguredAction\n ? this._activeTurnApprovedActionInputs.get(options.toolCallId)\n : undefined;\n if (\n approvedInput !== undefined &&\n !stableJsonEqual(finalInput, approvedInput)\n ) {\n return { execute: false, output: actionApprovalInputErrorEnvelope() };\n }\n return { execute: true, finalInput };\n }\n if (decision.action === \"block\") {\n return {\n execute: false,\n output:\n decision.reason ?? `Tool \"${toolName}\" was blocked by beforeToolCall.`\n };\n }\n // substitute\n return { execute: false, output: decision.output };\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 private async _admitTurn<T>(\n spec: QueueTurnSpec<T>\n ): Promise<AdmittedQueueResult<T>>;\n private async _admitTurn<T>(spec: NonQueueTurnSpec<T>): Promise<T>;\n private async _admitTurn<T>(\n spec: TurnSpec<T>\n ): Promise<AdmittedQueueResult<T> | T> {\n if (spec.admission !== \"queue\") {\n // The non-queue (submit/execute-submission) path runs `execute()` here\n // directly — it does NOT pass through `_runInsideAdmittedTurnBody`, so the\n // channel context must be set here too.\n return withAgentSpan(\n this,\n \"chat_submission\",\n \"submission\",\n {\n \"cloudflare.agents.component\": \"think\",\n \"cloudflare.agents.turn.trigger\": spec.trigger,\n \"cloudflare.agents.turn.admission\": spec.admission,\n \"cloudflare.agents.turn.channel\": spec.channel\n },\n () =>\n withAgentSpan(\n this,\n spec.admission === \"submit\"\n ? \"accept_chat_submission\"\n : \"execute_chat_submission\",\n \"submission\",\n {\n \"cloudflare.agents.component\": \"think\",\n \"cloudflare.agents.turn.trigger\": spec.trigger,\n \"cloudflare.agents.turn.admission\": spec.admission,\n \"cloudflare.agents.turn.channel\": spec.channel\n },\n () => this._withChannelContext(spec.channel, () => spec.execute())\n )\n );\n }\n\n if (!spec.allowNested) {\n this._assertNotInsideAdmittedTurn(spec.trigger);\n }\n\n return this.keepAliveWhile(async () => {\n const turnPromise = this._turnQueue.enqueue(\n spec.requestId,\n () => this._runInsideAdmittedTurnBody(spec),\n spec.generation === undefined\n ? undefined\n : { generation: spec.generation }\n );\n spec.onQueued?.();\n return turnPromise;\n });\n }\n\n private _assertNotInsideAdmittedTurn(trigger: TurnTrigger): void {\n if (admittedTurnContext.getStore()?.agent !== this) return;\n throw new Error(\n `Think turn admission (${trigger}) cannot be called from inside an active turn; use runTurn({ mode: \"submit\" }) or addMessages() instead`\n );\n }\n\n private async _runInsideAdmittedTurnBody<T>(\n spec: QueueTurnSpec<T>\n ): Promise<T> {\n // A turn is one unit of traced work and owns its own boundary, never that\n // of whatever admitted it. A handler that awaits its turn ends at the same\n // moment anyway; one that does not — an ack-and-return submit, or an\n // auto-continuation fired from a timer — would otherwise close every span\n // in a turn that is still running, or hand it a context already dead.\n return withInvocationScope(\n () =>\n withAgentSpan(\n this,\n \"chat_turn\",\n \"turn\",\n {\n \"cloudflare.agents.component\": \"think\",\n \"cloudflare.agents.turn.request_id\": spec.requestId,\n \"cloudflare.agents.turn.trigger\": spec.trigger,\n \"cloudflare.agents.turn.admission\": spec.admission,\n \"cloudflare.agents.turn.channel\": spec.channel,\n \"cloudflare.agents.turn.continuation\": spec.continuation,\n \"cloudflare.agents.turn.generation\": spec.generation\n },\n (update) =>\n admittedTurnContext.run(\n {\n agent: this,\n requestId: spec.requestId,\n trigger: spec.trigger,\n admission: spec.admission,\n channel: spec.channel,\n continuation: spec.continuation,\n generation: spec.generation\n },\n async () => {\n const startedAt = Date.now();\n this._emit(\"chat:turn:start\", {\n requestId: spec.requestId,\n trigger: spec.trigger,\n admission: spec.admission,\n ...(spec.continuation !== undefined && {\n continuation: spec.continuation\n }),\n ...(spec.generation !== undefined && {\n generation: spec.generation\n })\n });\n\n this._activeTurnReplyAttachments = [];\n this._activeTurnReplyAttachmentsRequestId = spec.requestId;\n\n try {\n const value = await this._withChannelContext(\n spec.channel,\n () => spec.execute()\n );\n const status = spec.getStatus?.() ?? \"completed\";\n this._emit(\"chat:turn:finish\", {\n requestId: spec.requestId,\n trigger: spec.trigger,\n admission: spec.admission,\n ...(spec.continuation !== undefined && {\n continuation: spec.continuation\n }),\n ...(spec.generation !== undefined && {\n generation: spec.generation\n }),\n status,\n durationMs: Date.now() - startedAt\n });\n update({ \"cloudflare.agents.turn.status\": status });\n return value;\n } catch (error) {\n const message =\n error instanceof Error ? error.message : String(error);\n this._emit(\"chat:turn:finish\", {\n requestId: spec.requestId,\n trigger: spec.trigger,\n admission: spec.admission,\n ...(spec.continuation !== undefined && {\n continuation: spec.continuation\n }),\n ...(spec.generation !== undefined && {\n generation: spec.generation\n }),\n status: \"error\",\n durationMs: Date.now() - startedAt,\n error: message\n });\n update({ \"cloudflare.agents.turn.status\": \"error\" });\n throw error;\n }\n }\n )\n ),\n { detached: true }\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(s), or a callback that derives them\n * from the in-queue transcript.\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: TurnInputMessages,\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 // Client tools supplied by the caller (e.g. a parent agent delegating to\n // this sub-agent). Both the schemas and the `onClientToolCall` executor are\n // forwarded per-turn only — deliberately NOT persisted into\n // `_lastClientTools`. The executor is a live RPC ref that dies with the\n // isolate, so unlike the WebSocket path there is no SPA that could ever\n // replay a `tool-result` after an eviction. Persisting the names would put\n // them in `_clientResolvableToolNames()`, causing recovery to misclassify a\n // dangling `input-available` orphan as a pending human interaction and park\n // forever. Keeping them per-turn lets such an orphan recover like a server\n // tool: `continueLastTurn`'s transcript repair errors it and the model\n // proceeds. `_runInferenceLoop` sources client tools from `input.clientTools`\n // (not `_lastClientTools`), so the live turn is unaffected.\n const clientTools = options?.clientTools?.length\n ? options.clientTools\n : undefined;\n const clientToolExecutor = options?.onClientToolCall;\n\n try {\n await callback.onStart({ requestId });\n await this._admitTurn({\n admission: \"queue\",\n trigger: \"rpc\",\n requestId,\n continuation: false,\n channel: options?.channel,\n execute: async () => {\n const resolved =\n typeof userMessage === \"function\"\n ? await userMessage(this.messages)\n : this._normalizeChatMessages(userMessage);\n\n for (const msg of this._stampChannel(\n resolved,\n options?.channel,\n options?.metadata\n )) {\n await this._appendMessageToHistory(msg);\n }\n this._broadcastMessages();\n\n const chatBody = async () => {\n // Bounded compact-and-retry loop (opt-in via\n // `contextOverflow.reactive`). A turn that overflows the context\n // window mid-flight is compacted and re-run from the persisted\n // partial instead of dying terminally. Every attempt re-runs the\n // SAME user turn from the now-compacted history, so it stays\n // `continuation: false` — an overflow retry is not an\n // auto-continuation, and `beforeTurn` should not treat it as one.\n for (let attempt = 0; ; attempt++) {\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 clientTools,\n clientToolExecutor,\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 // The consumer suppresses a classified overflow whenever recovery\n // is enabled; the driver (here) owns the retry-vs-terminal call so\n // every overflow terminal is reported identically.\n const { status, error } = await this._streamResultToRpcCallback(\n requestId,\n result,\n callback,\n abortSignal,\n { overflowRecovery: this._overflowReactiveEnabled }\n );\n\n if (status === \"overflow_retry\") {\n if (\n attempt < this._overflowMaxRetries &&\n !abortSignal?.aborted\n ) {\n const shortened = await this._compactForContextOverflow(\n \"reactive\",\n { requestId, attempt: attempt + 1 }\n );\n // Compaction shortened history → retry. A no-op compaction\n // can't fix the overflow, so fall through to terminal.\n if (shortened) continue;\n }\n // Budget spent, aborted, or compaction no-op: deliver terminally\n // (through onChatError, classified) so the turn never loops or ends\n // silently with no answer.\n const message = this._finalizeContextOverflowError(\n requestId,\n error\n );\n await callback.onError(message);\n }\n return;\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 /**\n * Unified turn admission API (Turns RFC, step 2).\n *\n * Thin facade over {@link Think.saveMessages}, {@link Think.continueLastTurn},\n * {@link Think.submitMessages}, and {@link Think.chat}. Each `mode` delegates\n * to the matching backing method with a narrowed option surface; the full\n * unified superset lands with `_admitTurn` (step 3).\n *\n * - `mode: \"wait\"` (default) — blocking turn; returns {@link TurnResult}.\n * - `mode: \"submit\"` — durable queued turn; returns {@link SubmitMessagesResult}.\n * - `mode: \"stream\"` — RPC-style streaming; returns `Promise<void>`.\n *\n * **Re-entrancy.** Calling `mode: \"wait\"` or `continuation: true` from inside\n * an active turn (a tool `execute`, a lifecycle hook) deadlocks on the turn\n * queue — identical to calling {@link Think.saveMessages} or\n * {@link Think.continueLastTurn} from there. Prefer `mode: \"submit\"` or\n * {@link Think.addMessages} instead. Precise nested-call detection is deferred\n * to `_admitTurn` (step 3).\n *\n * **Empty input (`wait`).** String, single-message, and array inputs that\n * normalize to an empty list short-circuit to `{ status: \"skipped\" }` without\n * running inference. A function `input` that resolves to `[]` at run time is\n * not pre-checked (the function must see the in-queue transcript); step 3's\n * `_admitTurn` centralizes empty-skip inside the queue.\n *\n * @experimental\n */\n runTurn(options: RunTurnWait): Promise<TurnResult>;\n runTurn(options: RunTurnSubmit): Promise<SubmitMessagesResult>;\n runTurn(options: RunTurnStream): Promise<void>;\n async runTurn(\n options: RunTurnOptions\n ): Promise<TurnResult | SubmitMessagesResult | void> {\n const mode = this._resolveRunTurnMode(options);\n if (mode === \"stream\") {\n return this._runTurnStream(options as RunTurnStream);\n }\n if (mode === \"submit\") {\n return this._runTurnSubmit(options as RunTurnSubmit);\n }\n return this._runTurnWait(options as RunTurnWait);\n }\n\n private _resolveRunTurnMode(\n options: RunTurnOptions\n ): \"wait\" | \"submit\" | \"stream\" {\n if (options === null || typeof options !== \"object\") {\n throw new TypeError(\"runTurn: options must be an object\");\n }\n\n const mode = (options as { mode?: unknown }).mode;\n if (mode === undefined || mode === \"wait\") return \"wait\";\n if (mode === \"submit\" || mode === \"stream\") return mode;\n throw new TypeError('runTurn: mode must be \"wait\", \"submit\", or \"stream\"');\n }\n\n private _validateRunTurnAdmission(\n options: RunTurnOptions,\n mode: \"wait\" | \"submit\" | \"stream\"\n ): void {\n const hasInput = options.input !== undefined;\n const continuation =\n mode === \"wait\" && (options as RunTurnWait).continuation === true;\n\n if (mode !== \"wait\" && (options as RunTurnWait).continuation === true) {\n throw new TypeError(\n 'runTurn: continuation is only supported with mode: \"wait\"'\n );\n }\n\n if (mode === \"stream\" && !(options as RunTurnStream).callback) {\n throw new TypeError('runTurn: mode \"stream\" requires callback');\n }\n\n if (mode === \"wait\") {\n if (hasInput && continuation) {\n throw new TypeError(\n \"runTurn: supply either input or continuation: true, not both\"\n );\n }\n if (!hasInput && !continuation) {\n throw new TypeError(\n \"runTurn: supply either input or continuation: true\"\n );\n }\n return;\n }\n\n if (!hasInput) {\n throw new TypeError(`runTurn: mode \"${mode}\" requires input`);\n }\n }\n\n private _userMessageFromText(text: string): UIMessage {\n return {\n id: crypto.randomUUID(),\n role: \"user\",\n parts: [{ type: \"text\", text }]\n };\n }\n\n private _normalizeRunTurnMessages(\n input: Exclude<\n TurnInputMessages,\n (current: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>\n >\n ): UIMessage[] {\n if (typeof input === \"string\") {\n if (input.length === 0) return [];\n return [this._userMessageFromText(input)];\n }\n if (Array.isArray(input)) {\n return input;\n }\n return [input];\n }\n\n private _normalizeChatMessages(\n input: Exclude<\n TurnInputMessages,\n (current: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>\n >\n ): UIMessage[] {\n if (typeof input === \"string\") {\n return [this._userMessageFromText(input)];\n }\n if (Array.isArray(input)) {\n return input;\n }\n return [input];\n }\n\n private _assertRunTurnSubmitInput(\n input: TurnInputMessages\n ): asserts input is string | UIMessage | UIMessage[] {\n if (typeof input === \"function\") {\n throw new Error(\n 'runTurn({ mode: \"submit\" }) does not support function input until _admitTurn (step 3)'\n );\n }\n }\n\n private async _enrichTurnResult(\n result: SaveMessagesResult,\n continuation: boolean\n ): Promise<TurnResult> {\n let message: SessionMessage | undefined;\n if (result.status === \"completed\") {\n const leaf = await this.session.getLatestLeaf();\n if (leaf?.role === \"assistant\") {\n message = leaf;\n }\n }\n return { ...result, continuation, message };\n }\n\n private async _runTurnWait(options: RunTurnWait): Promise<TurnResult> {\n this._validateRunTurnAdmission(options, \"wait\");\n\n if (options.continuation === true) {\n const result = await this.continueLastTurn(options.body, {\n signal: options.signal,\n channel: options.channel\n });\n return this._enrichTurnResult(result, true);\n }\n\n const input = options.input;\n if (input === undefined) {\n throw new TypeError(\"runTurn: supply either input or continuation: true\");\n }\n\n if (typeof input === \"function\") {\n const result = await this._runProgrammaticMessagesTurn(\n crypto.randomUUID(),\n input,\n { signal: options.signal, channel: options.channel }\n );\n return this._enrichTurnResult(result, false);\n }\n\n const messages = this._normalizeRunTurnMessages(input);\n if (messages.length === 0) {\n return { requestId: \"\", status: \"skipped\", continuation: false };\n }\n\n const result = await this._runProgrammaticMessagesTurn(\n crypto.randomUUID(),\n messages,\n { signal: options.signal, channel: options.channel }\n );\n return this._enrichTurnResult(result, false);\n }\n\n private async _runTurnSubmit(\n options: RunTurnSubmit\n ): Promise<SubmitMessagesResult> {\n this._validateRunTurnAdmission(options, \"submit\");\n\n const input = options.input;\n if (input === undefined) {\n throw new TypeError('runTurn: mode \"submit\" requires input');\n }\n\n this._assertRunTurnSubmitInput(input);\n const messages = this._normalizeRunTurnMessages(input);\n return this.submitMessages(messages, {\n submissionId: options.submissionId,\n idempotencyKey: options.idempotencyKey,\n metadata: options.metadata,\n channel: options.channel\n });\n }\n\n private async _runTurnStream(options: RunTurnStream): Promise<void> {\n this._validateRunTurnAdmission(options, \"stream\");\n\n const input = options.input;\n if (input === undefined) {\n throw new TypeError('runTurn: mode \"stream\" requires input');\n }\n\n if (typeof input !== \"function\") {\n const messages = this._normalizeRunTurnMessages(input);\n if (messages.length === 0) {\n await options.callback.onStart({ requestId: crypto.randomUUID() });\n await options.callback.onDone();\n return;\n }\n }\n\n return this.chat(input, options.callback, {\n signal: options.signal,\n clientTools: options.clientTools,\n onClientToolCall: options.onClientToolCall,\n channel: options.channel\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 // Latest progress snapshot (rfc-detached-agent-tools §progress). Only the\n // most recent `reportProgress` is retained; `last_signal_at` drives the\n // parent's resetting no-progress budget across eviction.\n this._addAgentToolChildRunColumnIfMissing(\n \"ALTER TABLE cf_agent_tool_child_runs ADD COLUMN progress_json TEXT\"\n );\n this._addAgentToolChildRunColumnIfMissing(\n \"ALTER TABLE cf_agent_tool_child_runs ADD COLUMN last_signal_at INTEGER\"\n );\n // Durable milestones (rfc-detached-agent-tools §progress, 4b). One row per\n // milestone; `sequence` is monotonic per run so replay/live races dedupe.\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_agent_tool_milestones (\n run_id TEXT NOT NULL,\n sequence INTEGER NOT NULL,\n name TEXT NOT NULL,\n data_json TEXT,\n at INTEGER NOT NULL,\n PRIMARY KEY (run_id, sequence)\n )\n `;\n }\n\n private _persistAgentToolMilestone(\n runId: string,\n name: string,\n data: unknown,\n at: number\n ): number {\n this._ensureAgentToolChildRunTable();\n const rows = this.sql<{ next: number }>`\n SELECT COALESCE(MAX(sequence), -1) + 1 AS next\n FROM cf_agent_tool_milestones WHERE run_id = ${runId}\n `;\n const sequence = rows[0]?.next ?? 0;\n this.sql`\n INSERT OR IGNORE INTO cf_agent_tool_milestones\n (run_id, sequence, name, data_json, at)\n VALUES (\n ${runId}, ${sequence}, ${name},\n ${data !== undefined ? JSON.stringify(data) : null}, ${at}\n )\n `;\n // A milestone is a progress signal too: advance the no-progress clock.\n this.sql`\n UPDATE cf_agent_tool_child_runs SET last_signal_at = ${at}\n WHERE run_id = ${runId}\n `;\n return sequence;\n }\n\n private _readAgentToolMilestones(runId: string): AgentToolMilestone[] {\n this._ensureAgentToolChildRunTable();\n return this.sql<{\n sequence: number;\n name: string;\n data_json: string | null;\n at: number;\n }>`\n SELECT sequence, name, data_json, at FROM cf_agent_tool_milestones\n WHERE run_id = ${runId} ORDER BY sequence ASC\n `.map((row) => ({\n name: row.name,\n sequence: row.sequence,\n at: row.at,\n ...(row.data_json != null\n ? { data: Think._parseAgentToolOutput(row.data_json) }\n : {})\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, progress_json,\n last_signal_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 const progress = Think._progressSnapshotFromRow(row);\n return progress ? { progress } : {};\n })(),\n ...(() => {\n const milestones = this._readAgentToolMilestones(row.run_id);\n return milestones.length > 0 ? { milestones } : {};\n })()\n };\n }\n\n /**\n * Rebuild the latest progress snapshot persisted by `reportProgress` from a\n * child run row, or `undefined` if the child never reported progress.\n */\n private static _progressSnapshotFromRow(\n row: AgentToolChildRunRow\n ): AgentToolProgressSnapshot | undefined {\n if (row.progress_json == null || row.last_signal_at == null)\n return undefined;\n try {\n const parsed = JSON.parse(row.progress_json) as Partial<\n Omit<AgentToolProgressSnapshot, \"at\">\n >;\n return { ...parsed, at: row.last_signal_at };\n } catch {\n return { at: row.last_signal_at };\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 private _agentToolProgressEmitterInstance: AgentToolProgressEmitter | null =\n null;\n\n private get _agentToolProgressEmitter(): AgentToolProgressEmitter {\n if (!this._agentToolProgressEmitterInstance) {\n this._agentToolProgressEmitterInstance = new AgentToolProgressEmitter({\n resolveActiveRun: () => {\n const requestId = admittedTurnContext.getStore()?.requestId;\n if (!requestId) return null;\n const runId = this._agentToolRunsByRequestId.get(requestId);\n return runId ? { runId, requestId } : null;\n },\n broadcast: (requestId, chunkBody) => {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: chunkBody,\n done: false\n });\n },\n persistSnapshot: (runId, snapshot, at) => {\n this._ensureAgentToolChildRunTable();\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET progress_json = ${JSON.stringify(snapshot)},\n last_signal_at = ${at}\n WHERE run_id = ${runId}\n `;\n },\n persistMilestone: (runId, name, data, at) =>\n this._persistAgentToolMilestone(runId, name, data, at)\n });\n }\n return this._agentToolProgressEmitterInstance;\n }\n\n override async reportProgress<T = unknown>(\n progress: AgentToolProgress<T>,\n options?: { persist?: boolean }\n ): Promise<void> {\n const result = this._agentToolProgressEmitter.report(progress, options);\n if (result === \"inactive\") {\n console.warn(\n \"[think] reportProgress() was called outside of an active agent-tool run; ignoring. Call it from within a turn that is running as a sub-agent.\"\n );\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 /**\n * Format the message injected back into the chat when a `detached:\n * { notify: true }` run finishes. Override to customize the prose (or return\n * an empty string to suppress the notification for a given outcome). The\n * default announces the terminal status and any summary/error so the model\n * has enough context to react.\n */\n protected formatDetachedCompletion(\n run: AgentToolRunInfo,\n result: AgentToolLifecycleResult\n ): string {\n const label = `Background task \"${run.agentType}\" (run ${run.runId})`;\n switch (result.status) {\n case \"completed\":\n return result.summary\n ? `${label} finished:\\n\\n${result.summary}`\n : `${label} finished successfully.`;\n case \"error\":\n return `${label} failed${result.error ? `: ${result.error}` : \".\"}`;\n case \"aborted\":\n return `${label} was cancelled.`;\n case \"interrupted\":\n return result.reason === \"budget-exceeded\"\n ? `${label} ran out of time before completing and was stopped.`\n : `${label} was interrupted before completing${result.error ? `: ${result.error}` : \".\"}`;\n default:\n return `${label} ended (${result.status}).`;\n }\n }\n\n /**\n * Serialize detached terminal delivery against the chat turn queue. A\n * fast-path push or backbone tick can land mid-turn, and an `onFinish` that\n * mutates state (`setState`, `submitMessages`, a follow-up `runAgentTool`)\n * running concurrently with an active LLM turn is a data race. Those paths\n * never run synchronously inside a turn body (they fire from `waitUntil` / a\n * scheduled alarm), so enqueuing on the turn queue runs the delivery strictly\n * between turns without risk of self-deadlock.\n *\n * An explicit `cancelAgentTool` (`serialize` unset) may be invoked from inside\n * the very turn that triggers it, where enqueuing WOULD self-deadlock, so it\n * runs inline in the caller's (or a fresh) `agentContext` instead. The Think\n * `notify` convenience is unaffected either way: it delivers via\n * `submitMessages`, which already serializes FIFO behind any active turn.\n */\n protected override async _runDetachedDelivery(\n invoke: () => Promise<void>,\n options?: { serialize?: boolean }\n ): Promise<void> {\n const inContext = () =>\n agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n invoke\n );\n if (!options?.serialize) {\n if (agentContext.getStore()?.agent === this) {\n await invoke();\n return;\n }\n await inContext();\n return;\n }\n await this.keepAliveWhile(() =>\n this._turnQueue.enqueue(\n `detached-delivery:${crypto.randomUUID()}`,\n inContext\n )\n );\n }\n\n /**\n * Targeted completion hook for `detached: { notify: true }`. Auto-wired by\n * `runAgentTool` (resolved by name so the base Agent stays decoupled from the\n * chat layer). Injects the formatted completion as a programmatic turn so the\n * model reacts to the background result. Idempotent per run + status, so an\n * exactly-once finish — or a soft give-up followed by a real completion —\n * never injects a duplicate, while a give-up and a later real completion are\n * surfaced as two distinct turns.\n */\n async _cfDetachedNotifyFinish(\n run: AgentToolRunInfo,\n result: AgentToolLifecycleResult\n ): Promise<void> {\n const text = this.formatDetachedCompletion(run, result);\n if (!text) return;\n await this.submitMessages(\n [\n {\n id: crypto.randomUUID(),\n role: \"user\",\n parts: [{ type: \"text\", text }]\n }\n ],\n {\n idempotencyKey: `detached-finish:${run.runId}:${result.status}`,\n metadata: {\n source: run.notifySource ?? \"detached-agent-tool\",\n runId: run.runId,\n agentType: run.agentType,\n status: result.status\n }\n }\n );\n }\n\n /**\n * Format the synthetic message injected when a `detached: { onMilestones }`\n * milestone is reached. Override to customize the prose (or return an empty\n * string to suppress a given milestone). The default announces the milestone\n * name and any structured data so the model can react in-conversation before\n * the run finishes.\n */\n protected formatDetachedMilestone(\n run: AgentToolRunInfo,\n milestone: AgentToolMilestone\n ): string {\n const label = `Background task \"${run.agentType}\" (run ${run.runId})`;\n const detail =\n milestone.data !== undefined\n ? `\\n\\n${JSON.stringify(milestone.data, null, 2)}`\n : \"\";\n return `${label} reached milestone \"${milestone.name}\".${detail}`;\n }\n\n /**\n * Targeted milestone hook for `detached: { onMilestones }`. Idempotent per run\n * + milestone NAME (not sequence — a name surfaces at most once even if\n * re-emitted), so the warm tail and the backbone reconcile converge. Fired\n * from both paths.\n *\n * - `\"narrate\"` (default): a synthetic **assistant** message injected directly\n * — no model turn — using a deterministic message id for idempotency\n * (`addMessages` is a no-op for an id already in history).\n * - `\"react\"`: a **user-role** turn so the model responds to the milestone\n * (idempotency via `submitMessages` + UNIQUE idempotency key).\n */\n protected override async _deliverDetachedMilestone(\n run: AgentToolRunInfo,\n milestone: AgentToolMilestone,\n mode: \"react\" | \"narrate\"\n ): Promise<void> {\n const text = this.formatDetachedMilestone(run, milestone);\n if (!text) return;\n const metadata = {\n source: run.notifySource ?? \"detached-agent-tool\",\n runId: run.runId,\n agentType: run.agentType,\n milestone: milestone.name\n };\n if (mode === \"narrate\") {\n await this.addMessages([\n {\n id: `detached-ms:${run.runId}:${milestone.name}`,\n role: \"assistant\",\n parts: [{ type: \"text\", text }],\n metadata\n }\n ]);\n return;\n }\n await this.submitMessages(\n [\n {\n id: crypto.randomUUID(),\n role: \"user\",\n parts: [{ type: \"text\", text }]\n }\n ],\n { idempotencyKey: `detached-ms:${run.runId}:${milestone.name}`, metadata }\n );\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 // Bind the run to its turn's request id BEFORE the turn starts —\n // in memory for live frame attribution in `broadcast`, and on the\n // child-run row so attribution survives a DO restart mid-run\n // (#1575). `saveMessages` would generate the id internally, so call\n // the inner turn runner with a pre-generated one instead.\n const requestId = crypto.randomUUID();\n this._agentToolRunsByRequestId.set(requestId, options.runId);\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET request_id = ${requestId}\n WHERE run_id = ${options.runId}\n `;\n const result = await this._runProgrammaticMessagesTurn(\n requestId,\n [this.formatAgentToolInput(input)],\n {\n signal: controller.signal,\n trigger: \"agent-tool\"\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 // Drop the progress emitter's per-run coalescing state.\n this._agentToolProgressEmitterInstance?.forget(options.runId);\n // Drop this run's request-id mappings. When no runs remain in flight\n // clear the whole map, so negatively-cached (null) entries for\n // unrelated turns can't accumulate for the DO's lifetime — the map is\n // only consulted while a run is active (#1575).\n if (this._agentToolAbortControllers.size === 0) {\n this._agentToolRunsByRequestId.clear();\n } else {\n for (const [reqId, runId] of this._agentToolRunsByRequestId) {\n if (runId === options.runId) {\n this._agentToolRunsByRequestId.delete(reqId);\n }\n }\n }\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 // Stop the original in-isolate run if it's still live...\n this._agentToolAbortControllers.get(runId)?.abort(reason);\n // ...and any in-flight chat-recovery turn driving this child facet after an\n // eviction. A recovered turn re-runs via `_chatRecoveryContinue` outside\n // `startAgentToolRun`, so it has no entry in `_agentToolAbortControllers`; a\n // child facet is dedicated to a single agent-tool run, so aborting its\n // active submissions tears the recovery down instead of letting it keep\n // grinding (and holding a fiber / keep-alive) after the parent gave up on\n // it and sealed `interrupted` (#1630 follow-up).\n for (const controller of this._submissionAbortControllers.values()) {\n controller.abort(reason);\n }\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 // Release any parent live-tail so it stops waiting on this run immediately.\n this._finalizeAgentToolChildRunTailers(runId);\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 _classifyAgentToolChildRecovery(): Promise<\n \"in-progress\" | \"failed\" | \"none\"\n > {\n return classifyAgentToolChildRecovery(this.ctx.storage);\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 /**\n * Eagerly terminalize this child facet's OWN agent-tool run row(s) once a\n * recovered turn has settled. A recovered turn re-runs via either\n * `_chatRecoveryContinue` → `continueLastTurn` or, for a pre-stream eviction,\n * `_chatRecoveryRetry` (a fresh user turn) — neither flows through\n * `startAgentToolRun`'s finalizer, so without this the run row strands\n * `running` and its tailers stay open until a parent inspect lazily\n * reconciles it — forcing a re-attached parent to wait out a full no-progress\n * window before collecting an already-finished result (#1630 follow-up).\n * Reconciling here closes the tail promptly so the parent collects the\n * terminal immediately. No-op on non-child facets (their\n * `cf_agent_tool_child_runs` table is empty) and on rows whose in-memory run\n * is still live (those are finalized by `startAgentToolRun`); the underlying\n * reconcile leaves a row `running` while its recovery is still in progress.\n */\n private async _reconcileOwnStaleAgentToolChildRuns(): Promise<void> {\n let rows: Array<{ run_id: string }>;\n try {\n rows = this.sql<{ run_id: string }>`\n SELECT run_id FROM cf_agent_tool_child_runs\n WHERE completed_at IS NULL\n `;\n } catch {\n // No child-run table on this facet (it never ran as a child) — nothing\n // to reconcile.\n return;\n }\n for (const { run_id } of rows) {\n if (this._agentToolAbortControllers.has(run_id)) continue;\n try {\n await this._reconcileStaleAgentToolChildRun(run_id);\n } catch {\n // Best-effort: a parent inspect still reconciles lazily.\n }\n }\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 const set = self._agentToolForwarders.get(runId);\n set?.delete(forward);\n // Drop the now-empty set so the broadcast idle-guard\n // (`_agentToolForwarders.size`) goes cold again. Otherwise a run that\n // was already terminal at attach — its `_finalizeAgentToolChildRunTailers`\n // already ran and won't run again — leaves an empty set keyed by runId,\n // and every subsequent broadcast on this DO keeps paying the\n // `interceptAgentToolBroadcast` cost forever.\n if (set && set.size === 0) self._agentToolForwarders.delete(runId);\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 // Stored chunk_index and the live forwarder sequence share one\n // monotonic numbering (see `getAgentToolChunks` + the broadcast snoop),\n // so a single high-water mark dedupes the stored-replay → live-\n // forwarding handoff: a chunk that lands in both the drained backlog AND\n // the live buffer (stored + broadcast during the drain) is emitted\n // exactly once, in order.\n let lastEmitted = options?.afterSequence ?? -1;\n const emit = (chunk: AgentToolStoredChunk) => {\n if (closed || chunk.sequence <= lastEmitted) return;\n lastEmitted = chunk.sequence;\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\n // While draining the stored backlog, park live chunks rather than\n // emitting them directly, so ordering/dedupe against the backlog is\n // resolved by `emit` while the forwarder (registered FIRST, below)\n // already catches everything the child produces.\n let draining = true;\n const pending: AgentToolStoredChunk[] = [];\n forward = (chunk: AgentToolStoredChunk) => {\n if (closed) return;\n if (draining) {\n pending.push(chunk);\n return;\n }\n emit(chunk);\n };\n\n // Register the live forwarder BEFORE draining the stored backlog.\n // Previously it was attached only AFTER `getAgentToolChunks` resolved;\n // any chunk the child stored AND broadcast during that `await` advanced\n // the live sequence with no forwarder attached, so it was neither in the\n // drained snapshot nor live-forwarded — silently dropped from the\n // parent's forward stream. A network-paced proxied child stream (a sub-\n // agent returning a remote `toUIMessageStreamResponse()`) hits this\n // window constantly, leaving tool parts stuck at `input-available`\n // (#1589).\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 try {\n const replayed = await self.getAgentToolChunks(runId, options);\n for (const chunk of replayed) {\n if (closed) return;\n emit(chunk);\n }\n\n // Flush chunks that arrived live during the drain, then switch the\n // forwarder to direct emit. No `await` between here and the drain loop\n // means no live chunk can slip past this handoff.\n draining = false;\n for (const chunk of pending) emit(chunk);\n pending.length = 0;\n\n const row = self._readAgentToolChildRun(runId);\n if (!row || row.completed_at !== null) {\n close();\n return;\n }\n\n // Run is still live: realign the live sequence to continue right after\n // the highest emitted chunk (which now includes any captured during the\n // drain). Realigning to `lastEmitted + 1` rather than the backlog's last\n // sequence keeps a post-restart re-attach — where the in-memory counter\n // is cold — from colliding with already-emitted chunks. Gating on the\n // terminal check above also avoids repopulating `_agentToolLiveSequences`\n // for an already-terminal run, which would re-heat the broadcast\n // idle-guard for the DO's lifetime.\n if (lastEmitted > (options?.afterSequence ?? -1)) {\n self._agentToolLiveSequences.set(runId, lastEmitted + 1);\n }\n } catch (error) {\n // A drain/read failure must surface to the consumer; detach first so\n // the forwarder we registered up front doesn't linger on this run.\n closed = true;\n detach();\n try {\n controller.error(error);\n } catch {\n // Stream already torn down.\n }\n }\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 // ── Action ledger ────────────────────────────────────────────────\n\n private _ensureActionLedgerTable(): void {\n if (this._actionLedgerTableEnsured) return;\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_think_action_ledger (\n key TEXT PRIMARY KEY,\n action_name TEXT NOT NULL,\n request_id TEXT,\n tool_call_id TEXT,\n input_hash TEXT NOT NULL,\n status TEXT NOT NULL,\n result_json TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL\n )\n `;\n this.sql`\n CREATE INDEX IF NOT EXISTS cf_think_action_ledger_sweep\n ON cf_think_action_ledger (status, updated_at)\n `;\n this._actionLedgerTableEnsured = true;\n }\n\n private _readActionLedgerRow(key: string): ActionLedgerRow | null {\n this._ensureActionLedgerTable();\n const rows = this.sql<ActionLedgerRow>`\n SELECT key, action_name, request_id, tool_call_id, input_hash, status,\n result_json, created_at, updated_at\n FROM cf_think_action_ledger\n WHERE key = ${key}\n LIMIT 1\n `;\n return rows[0] ?? null;\n }\n\n /**\n * Claim a ledger key for execution. Read-then-write with no `await` between\n * the read and any write, so within the single DO isolate two claims cannot\n * interleave — the same race-free idiom documented on\n * {@link _claimActionPendingRow}. The only way a durable `pending` row\n * outlives its writer is a crashed prior isolate, which has no live writer to\n * race; that is the row a stale reclaim safely re-runs.\n */\n private _claimActionLedgerRow(options: {\n key: string;\n actionName: string;\n requestId: string;\n toolCallId: string;\n inputHash: string;\n retryablePending: boolean;\n leaseMs: number | false;\n now?: number;\n }): ActionLedgerClaim {\n this._ensureActionLedgerTable();\n const now = options.now ?? Date.now();\n const existing = this._readActionLedgerRow(options.key);\n if (existing) {\n if (\n existing.action_name !== options.actionName ||\n existing.input_hash !== options.inputHash\n ) {\n return { outcome: \"conflict\", row: existing };\n }\n if (existing.status === \"settled\") {\n return { outcome: \"replay\", row: existing };\n }\n // `pending` from here. Reclaim only an explicit-key row whose lease has\n // expired; fresh rows, fallback keys, and a disabled lease still block.\n const stale =\n options.retryablePending &&\n options.leaseMs !== false &&\n now - existing.updated_at > options.leaseMs;\n if (!stale) {\n return { outcome: \"pending\", row: existing };\n }\n this.sql`\n UPDATE cf_think_action_ledger\n SET request_id = ${options.requestId || null},\n tool_call_id = ${options.toolCallId || null},\n updated_at = ${now}\n WHERE key = ${options.key} AND status = ${\"pending\"}\n `;\n return { outcome: \"reclaimed\", row: existing };\n }\n\n this.sql`\n INSERT INTO cf_think_action_ledger (\n key, action_name, request_id, tool_call_id, input_hash, status,\n result_json, created_at, updated_at\n )\n VALUES (\n ${options.key}, ${options.actionName}, ${options.requestId || null},\n ${options.toolCallId || null}, ${options.inputHash}, ${\"pending\"},\n ${null}, ${now}, ${now}\n )\n `;\n return { outcome: \"claimed\" };\n }\n\n private _settleActionLedgerRow(key: string, resultJson: string): void {\n this._ensureActionLedgerTable();\n this.sql`\n UPDATE cf_think_action_ledger\n SET status = ${\"settled\"},\n result_json = ${resultJson},\n updated_at = ${Date.now()}\n WHERE key = ${key}\n `;\n }\n\n private _releaseActionLedgerRow(key: string): void {\n this._ensureActionLedgerTable();\n this.sql`\n DELETE FROM cf_think_action_ledger\n WHERE key = ${key}\n `;\n }\n\n private async _resolveActionLedgerKey(\n actionName: string,\n spec: ActionIdempotencyKey<unknown> | undefined,\n input: unknown,\n ctx: ActionContext\n ): Promise<string | null> {\n if (spec !== undefined) {\n const key =\n typeof spec === \"function\" ? await spec({ input, ctx }) : spec;\n if (key.length === 0) {\n throw new Error(\n `Action \"${actionName}\" returned an empty idempotency key`\n );\n }\n return `action:${actionName}:${key}`;\n }\n return ctx.toolCallId ? `tool:${ctx.toolCallId}` : null;\n }\n\n private _actionInputHash(input: unknown): string {\n return stableHash(input);\n }\n\n private _actionLedgerRetentionForStatus(\n status: ActionLedgerSweepStatus\n ): number | false {\n return status === \"settled\"\n ? this.actionLedgerRetention.settledMs\n : this.actionLedgerRetention.pendingMs;\n }\n\n private _deleteActionLedgerRows(keys: string[]): number {\n let deleted = 0;\n for (let i = 0; i < keys.length; i += MAX_BOUND_PARAMS) {\n const batch = keys.slice(i, i + MAX_BOUND_PARAMS);\n const strings = buildInClauseStrings(\n \"DELETE FROM cf_think_action_ledger WHERE key IN \",\n batch.length\n );\n this.sql(strings, ...batch);\n deleted += batch.length;\n }\n return deleted;\n }\n\n private _sweepActionLedgerStatus(\n status: ActionLedgerSweepStatus,\n now: number,\n limit: number\n ): number {\n const retentionMs = this._actionLedgerRetentionForStatus(status);\n if (retentionMs === false || limit <= 0) return 0;\n const cutoff = now - retentionMs;\n const rows = this.sql<{ key: string }>`\n SELECT key\n FROM cf_think_action_ledger\n WHERE status = ${status}\n AND updated_at < ${cutoff}\n ORDER BY updated_at ASC\n LIMIT ${limit}\n `;\n return this._deleteActionLedgerRows(rows.map((row) => row.key));\n }\n\n private async _sweepActionLedger(options?: {\n force?: boolean;\n }): Promise<{ settled: number; pending: number }> {\n this._ensureActionLedgerTable();\n const now = Date.now();\n if (!options?.force) {\n const lastSwept =\n (await this.ctx.storage.get<number>(ACTION_LEDGER_LAST_SWEPT_KEY)) ?? 0;\n if (now - lastSwept < ACTION_LEDGER_SWEEP_INTERVAL_MS) {\n return { settled: 0, pending: 0 };\n }\n }\n\n const maxSweepRows = Math.max(\n 0,\n Math.floor(this.actionLedgerRetention.maxSweepRows)\n );\n const settled = this._sweepActionLedgerStatus(\"settled\", now, maxSweepRows);\n const pending = this._sweepActionLedgerStatus(\n \"pending\",\n now,\n Math.max(0, maxSweepRows - settled)\n );\n await this.ctx.storage.put(ACTION_LEDGER_LAST_SWEPT_KEY, now);\n this._emitActionLedgerEvent({\n type: \"action:ledger:swept\",\n payload: { settled, pending }\n });\n return { settled, pending };\n }\n\n // ── Durable-pause action approvals ──────────────────────────────\n\n private _emitActionReplyEvent(event: ActionReplyEvent): void {\n const emit = this._emit as unknown as (\n type: string,\n payload: Record<string, unknown>\n ) => void;\n emit.call(this, event.type, event.payload);\n }\n\n /**\n * Record an advisory reply attachment for the active turn. Advisory: a\n * non-object, a missing/non-string `type`, or exceeding the per-turn cap is\n * silently ignored. The attachment is JSON-normalized to a safe copy so a\n * later mutation of the caller's object can't corrupt it and downstream\n * persistence/RPC can't choke on bigint/circular values.\n */\n private _recordReplyAttachment(\n requestId: string,\n attachment: unknown,\n actionName?: string\n ): void {\n if (!requestId || requestId !== this._activeTurnReplyAttachmentsRequestId) {\n return;\n }\n if (\n typeof attachment !== \"object\" ||\n attachment === null ||\n Array.isArray(attachment) ||\n typeof (attachment as { type?: unknown }).type !== \"string\"\n ) {\n return;\n }\n if (\n this._activeTurnReplyAttachments.length >= MAX_REPLY_ATTACHMENTS_PER_TURN\n ) {\n return;\n }\n const serialized = safeStringifyActionOutput(attachment);\n if (serialized.error || serialized.value === undefined) {\n return;\n }\n const normalized = JSON.parse(serialized.value) as unknown;\n if (\n typeof normalized !== \"object\" ||\n normalized === null ||\n Array.isArray(normalized) ||\n typeof (normalized as { type?: unknown }).type !== \"string\"\n ) {\n return;\n }\n this._activeTurnReplyAttachments.push(normalized as ReplyAttachment);\n this._emitActionReplyEvent({\n type: \"action:reply-attached\",\n payload: {\n ...(actionName !== undefined && { action: actionName }),\n attachmentType: (normalized as { type: string }).type\n }\n });\n }\n\n private _cloneReplyAttachment(attachment: ReplyAttachment): ReplyAttachment {\n return JSON.parse(JSON.stringify(attachment)) as ReplyAttachment;\n }\n\n /**\n * Advisory reply attachments recorded during a turn via `ctx.attachReply`.\n * Returns deep copies. With no `requestId`, returns the most recent turn's\n * attachments; with a `requestId`, returns them only if they belong to that\n * turn (else `[]`).\n */\n replyAttachments(requestId?: string): ReplyAttachment[] {\n if (\n requestId !== undefined &&\n requestId !== this._activeTurnReplyAttachmentsRequestId\n ) {\n return [];\n }\n return this._activeTurnReplyAttachments.map((attachment) =>\n this._cloneReplyAttachment(attachment)\n );\n }\n\n private _emitActionPauseEvent(event: ActionPauseEvent): void {\n const emit = this._emit as unknown as (\n type: string,\n payload: Record<string, unknown>\n ) => void;\n emit.call(this, event.type, event.payload);\n }\n\n private _ensureActionPendingTable(): void {\n if (this._actionPendingTableEnsured) return;\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_think_action_pending_approvals (\n execution_id TEXT PRIMARY KEY,\n action_name TEXT NOT NULL,\n tool_call_id TEXT NOT NULL,\n request_id TEXT,\n input_json TEXT NOT NULL,\n descriptor_json TEXT,\n created_at INTEGER NOT NULL\n )\n `;\n this.sql`\n CREATE INDEX IF NOT EXISTS cf_think_action_pending_created\n ON cf_think_action_pending_approvals (created_at)\n `;\n this._actionPendingTableEnsured = true;\n }\n\n private _readActionPendingRow(executionId: string): ActionPendingRow | null {\n this._ensureActionPendingTable();\n const rows = this.sql<ActionPendingRow>`\n SELECT execution_id, action_name, tool_call_id, request_id, input_json,\n descriptor_json, created_at\n FROM cf_think_action_pending_approvals\n WHERE execution_id = ${executionId}\n LIMIT 1\n `;\n return rows[0] ?? null;\n }\n\n private _insertActionPendingRow(row: ActionPendingRow): void {\n this._ensureActionPendingTable();\n this.sql`\n INSERT INTO cf_think_action_pending_approvals (\n execution_id, action_name, tool_call_id, request_id, input_json,\n descriptor_json, created_at\n )\n VALUES (\n ${row.execution_id}, ${row.action_name}, ${row.tool_call_id},\n ${row.request_id}, ${row.input_json}, ${row.descriptor_json},\n ${row.created_at}\n )\n `;\n }\n\n /**\n * Atomically claim a pending-approval row for resolution: read it, then\n * delete it. SQLite calls are synchronous and there is no `await` between the\n * read and the delete, so within the single DO isolate this is race-free — a\n * concurrent `approveExecution`/`rejectExecution` for the same id can only run\n * at an await boundary, by which point the row is already gone (it sees\n * `null` → \"already resolved\"). The returned row is the caller's to resolve.\n */\n private _claimActionPendingRow(executionId: string): ActionPendingRow | null {\n this._ensureActionPendingTable();\n const row = this._readActionPendingRow(executionId);\n if (!row) return null;\n this.sql`\n DELETE FROM cf_think_action_pending_approvals\n WHERE execution_id = ${executionId}\n `;\n return row;\n }\n\n private _listActionPendingRows(): ActionPendingRow[] {\n this._ensureActionPendingTable();\n return this.sql<ActionPendingRow>`\n SELECT execution_id, action_name, tool_call_id, request_id, input_json,\n descriptor_json, created_at\n FROM cf_think_action_pending_approvals\n ORDER BY created_at ASC\n `;\n }\n\n private _deleteActionPendingRows(executionIds: string[]): number {\n let deleted = 0;\n for (let i = 0; i < executionIds.length; i += MAX_BOUND_PARAMS) {\n const batch = executionIds.slice(i, i + MAX_BOUND_PARAMS);\n const strings = buildInClauseStrings(\n \"DELETE FROM cf_think_action_pending_approvals WHERE execution_id IN \",\n batch.length\n );\n this.sql(strings, ...batch);\n deleted += batch.length;\n }\n return deleted;\n }\n\n private async _sweepActionPendingApprovals(options?: {\n force?: boolean;\n }): Promise<{ swept: number }> {\n this._ensureActionPendingTable();\n const ttl = this.actionPendingApprovalTtlMs;\n if (ttl === false) return { swept: 0 };\n const now = Date.now();\n if (!options?.force) {\n const lastSwept =\n (await this.ctx.storage.get<number>(ACTION_PENDING_LAST_SWEPT_KEY)) ??\n 0;\n if (now - lastSwept < ACTION_PENDING_SWEEP_INTERVAL_MS) {\n return { swept: 0 };\n }\n }\n const cutoff = now - ttl;\n const rows = this.sql<{ execution_id: string }>`\n SELECT execution_id\n FROM cf_think_action_pending_approvals\n WHERE created_at < ${cutoff}\n ORDER BY created_at ASC\n LIMIT 500\n `;\n const swept = this._deleteActionPendingRows(\n rows.map((row) => row.execution_id)\n );\n await this.ctx.storage.put(ACTION_PENDING_LAST_SWEPT_KEY, now);\n if (swept > 0) {\n this._emitActionPauseEvent({\n type: \"action:pause:swept\",\n payload: { swept }\n });\n }\n return { swept };\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(messages.map((message) => this._rowSafe(message)));\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 console.error(\"[Think] Submission failed\", {\n submissionId: inspection.submissionId,\n requestId: inspection.requestId,\n idempotencyKey: inspection.idempotencyKey,\n metadata: inspection.metadata,\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 if (!this._hasPendingWorkflowNotifications()) return;\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 const idsToDelete = rows\n .filter((row) => this._isTerminalSubmissionStatus(row.status))\n .map((row) => row.submission_id);\n\n // Batch deletes into `IN (...)` queries within the SQLite 100\n // bound-parameter limit to minimize round-trips during cleanup.\n let deleted = 0;\n for (let i = 0; i < idsToDelete.length; i += MAX_BOUND_PARAMS) {\n const batch = idsToDelete.slice(i, i + MAX_BOUND_PARAMS);\n const strings = buildInClauseStrings(\n \"DELETE FROM cf_think_submissions WHERE status IN ('completed', 'aborted', 'skipped', 'error') AND submission_id IN \",\n batch.length\n );\n this.sql(strings, ...batch);\n deleted += batch.length;\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 // Persist the channel on the user messages so the drained turn re-resolves\n // it from history (the model turn runs later in the submission drain).\n messages = this._stampChannel(messages, options?.channel);\n return this._admitTurn({\n admission: \"submit\",\n trigger: \"submission\",\n execute: async () => {\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 }\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\n return {\n ...this._inspectionFromSubmissionRow(row),\n accepted: true\n };\n }\n });\n }\n\n private async _scheduleSubmissionDrain(): Promise<void> {\n await this.schedule(0, \"_drainThinkSubmissions\", undefined, {\n idempotent: true\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 await this._admitTurn({\n admission: \"execute-submission\",\n trigger: \"submission\",\n execute: () => this._executeSubmission(row)\n });\n }\n\n private async _executeSubmission(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 trigger: \"submission\",\n captureProgrammaticStreamError: true,\n captureOutput: Boolean(workflowPrompt?.output),\n // The alarm-owned drain can inherit the ALS of a turn\n // that called `submitMessages` mid-turn (e.g. a detached-finish notify\n // from a `beforeTurn` hook). `allowNested` skips the\n // not-inside-active-turn guard for that case. Safe on every submission\n // path: nothing holding the turn queue ever awaits this turn, so the\n // queued submission simply runs once the parent turn frees the slot —\n // no deadlock, no need to scope this to detached notify.\n allowNested: true,\n workflowPrompt: workflowPrompt ?? undefined,\n shouldApplyMessages: () =>\n this._readSubmission(row.submission_id)?.status === \"running\",\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 const finalized = this._readSubmission(row.submission_id);\n if (finalized && this._isTerminalSubmissionStatus(finalized.status)) {\n this._insertWorkflowNotification(\n this._inspectionFromSubmissionRow(finalized),\n output\n );\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 const finalized = this._readSubmission(row.submission_id);\n if (finalized && this._isTerminalSubmissionStatus(finalized.status)) {\n this._insertWorkflowNotification(\n this._inspectionFromSubmissionRow(finalized)\n );\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 /**\n * Add messages to history WITHOUT starting a model turn.\n *\n * Distinct from {@link Think.saveMessages} (which runs a turn) and from\n * AIChatAgent's `persistMessages()` (which replaces/reconciles a flat array):\n * `addMessages` appends or upserts into the Session tree and never enqueues a\n * turn. Because it bypasses the turn queue, it never deadlocks — including\n * when called from inside a tool `execute` during an active turn.\n *\n * Array entries are appended **linearly**: the first attaches under the\n * resolved parent (the latest committed leaf by default, or `parentId`), and\n * each subsequent message attaches under the previous one, so imported history\n * stays a single path rather than a fan-out of siblings. Appends are\n * idempotent by message id; pass `{ mode: \"upsert\" }` to update an existing\n * message in place instead (upsert never re-parents). Any role may be written;\n * an `assistant` message added this way is inert transcript data (it does not\n * mark a completed turn or trigger auto-continuation).\n *\n * The live message cache stays coherent automatically (the Session keeps it\n * in sync on every write, branches included). Broadcast behaviour depends on\n * whether a turn is running:\n *\n * - **Out of a turn** (the supported pattern — \"add context, then run a\n * turn\"): the new messages are broadcast to connected clients immediately\n * (unless `broadcast: false`).\n * - **Inside a turn** (e.g. from a tool `execute`): no broadcast is sent, so a\n * full snapshot can't clobber the in-progress streamed message; the injected\n * messages ride along on the turn's next broadcast. The write is still\n * durable and visible to the running turn's next sync.\n */\n async addMessages(\n messages:\n | UIMessage[]\n | ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>),\n options?: AddMessagesOptions\n ): Promise<void> {\n const resolved =\n typeof messages === \"function\" ? await messages(this.messages) : messages;\n if (resolved.length === 0) return;\n\n const mode = options?.mode ?? \"append\";\n\n // Validate an explicit parentId up front. The Session provider silently\n // falls back to the root for an unknown parent; fail fast instead so a\n // typo'd id surfaces as an error rather than a misattached message.\n if (typeof options?.parentId === \"string\") {\n const parent = await this.session.getMessage(options.parentId);\n if (!parent) {\n throw new Error(\n `addMessages: parentId \"${options.parentId}\" does not exist in this session`\n );\n }\n }\n\n let parentId = options?.parentId;\n for (const message of resolved) {\n const existing = await this.session.getMessage(message.id);\n if (existing) {\n // Append mode is idempotent by id (existing id → no-op); upsert updates\n // the content in place. Neither path re-parents an existing message.\n if (mode === \"upsert\") await this._updateMessageInHistory(message);\n parentId = message.id;\n } else {\n const stored = await this._appendMessageToHistory(message, parentId);\n parentId = stored.id;\n }\n }\n\n // The live cache is kept coherent automatically by the Session change\n // listener wired in `onStart` (`internal_onMessagesChanged`), which handles\n // both linear appends and branches (an explicit `parentId` triggers a full\n // resync). So `addMessages` only owns the broadcast — and suppresses it\n // mid-turn: pushing a full `MSG_CHAT_MESSAGES` snapshot while a turn streams\n // would clobber the in-progress assistant message on connected clients (the\n // same reason the streaming path defers its snapshot). The injected messages\n // ride along on the turn's next broadcast.\n if (this._insideInferenceLoop) return;\n if (options?.broadcast !== false) {\n this._broadcastMessages();\n }\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 shouldApplyMessages?: () => boolean | Promise<boolean>;\n allowNested?: boolean;\n trigger?: TurnTrigger;\n channel?: string;\n }\n ): Promise<ProgrammaticMessagesResult> {\n const clientTools = this._lastClientTools;\n const body = options?.body ?? this._lastBody;\n const epoch = this._turnQueue.generation;\n // Explicit channel wins; otherwise re-resolve from persisted user-message\n // metadata (covers the submission drain replaying stamped messages).\n const channel =\n options?.channel ??\n (Array.isArray(messages)\n ? this._channelFromMessages(messages)\n : undefined);\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n let error: string | undefined;\n let output: unknown;\n let wasAborted = false;\n\n await this._admitTurn({\n admission: \"queue\",\n trigger: options?.trigger ?? \"programmatic\",\n requestId,\n continuation: false,\n allowNested: options?.allowNested,\n channel,\n getStatus: () => status,\n execute: async () => {\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n if (\n options?.shouldApplyMessages &&\n !(await options.shouldApplyMessages())\n ) {\n status = \"aborted\";\n return;\n }\n\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 if (\n options?.shouldApplyMessages &&\n !(await options.shouldApplyMessages())\n ) {\n status = \"aborted\";\n return;\n }\n\n for (const msg of this._stampChannel(resolved, channel)) {\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 // Bounded compact-and-retry loop (opt-in via\n // `contextOverflow.reactive`), mirroring the WebSocket and chat()\n // paths so programmatic turns (saveMessages / submitMessages /\n // scheduled prompts) recover from a mid-turn overflow too. Each\n // attempt re-runs the same turn (`continuation: false`).\n for (let attempt = 0; ; attempt++) {\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) return;\n\n let overflowError: string | undefined;\n let overflowRequested = false;\n const overflowRecovery = this._overflowReactiveEnabled\n ? {\n onRetry: (err?: string) => {\n overflowRequested = true;\n overflowError = err;\n }\n }\n : undefined;\n\n const streamResult = await this._streamResult(\n requestId,\n result,\n abortSignal,\n {\n captureProgrammaticStreamError:\n options?.captureProgrammaticStreamError,\n captureOutput: options?.captureOutput,\n overflowRecovery\n }\n );\n\n if (overflowRequested) {\n if (\n attempt < this._overflowMaxRetries &&\n !abortSignal?.aborted\n ) {\n const shortened = await this._compactForContextOverflow(\n \"reactive\",\n { requestId, attempt: attempt + 1 }\n );\n if (shortened) continue;\n }\n // Budget spent, aborted, or compaction no-op: surface terminally\n // through onChatError (classified). The caller reads status/error.\n error = this._finalizeContextOverflowError(\n requestId,\n overflowError\n );\n status = \"error\";\n return;\n }\n\n status = streamResult.status;\n error = streamResult.error;\n output = streamResult.output;\n return;\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 & { trigger?: TurnTrigger; channel?: string }\n ): Promise<SaveMessagesResult> {\n const trigger = options?.trigger ?? \"programmatic\";\n this._assertNotInsideAdmittedTurn(trigger);\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 // If this facet is itself an agent-tool child being recovered, re-bind its\n // run row to this turn's request id so the parent's re-attach tail keeps\n // attributing the continued turn's frames (no-op otherwise).\n this._rebindAgentToolChildRunRequestId(requestId);\n const clientTools = this._lastClientTools;\n const resolvedBody = body ?? this._lastBody;\n const epoch = this._turnQueue.generation;\n // Re-resolve the channel from durable history so a continued/recovered turn\n // re-applies per-channel policy.\n const channel = options?.channel ?? this._channelFromLatestUserMessage();\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n let error: string | undefined;\n let wasAborted = false;\n\n await this._admitTurn({\n admission: \"queue\",\n trigger,\n requestId,\n continuation: true,\n channel,\n getStatus: () => status,\n execute: 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 & { trigger?: TurnTrigger; channel?: string }\n ): Promise<SaveMessagesResult> {\n const trigger = options?.trigger ?? \"recovery-retry\";\n this._assertNotInsideAdmittedTurn(trigger);\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 // If this facet is itself an agent-tool child being recovered, re-bind its\n // run row to this turn's request id so the parent's re-attach tail keeps\n // attributing the retried turn's frames (no-op otherwise).\n this._rebindAgentToolChildRunRequestId(requestId);\n const epoch = this._turnQueue.generation;\n // Re-resolve the channel from the persisted user message so a recovered\n // retry re-applies per-channel policy, exactly like `continueLastTurn`. The\n // `metadata.channel` stamp survives the interruption; without this the\n // retried turn would silently fall back to the default policy.\n const channel = options?.channel ?? this._channelFromLatestUserMessage();\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n let error: string | undefined;\n let wasAborted = false;\n\n await this._admitTurn({\n admission: \"queue\",\n trigger,\n requestId,\n continuation: false,\n channel,\n getStatus: () => status,\n execute: 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 // No active stream. If a turn is accepted but its stream hasn't started\n // yet (#1784), park this connection and tell it to keep waiting (`park`\n // sends the keep-waiting frame; no-op otherwise). Either way send the\n // idle-connect transcript so the client renders the user message it\n // just submitted while it waits for the stream to begin.\n this._preStream.park(connection);\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 this._preStream.release(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 if (event.type === \"chat-request\") {\n await withAgentSpan(\n this,\n \"chat_interaction\",\n \"interaction\",\n {\n \"cloudflare.agents.component\": \"think\",\n \"cloudflare.agents.turn.request_id\": event.id\n },\n () => this._handleProtocolEvent(connection, event)\n );\n } else {\n await this._handleProtocolEvent(connection, event);\n }\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 await this._handleStreamResumeRequest(connection, event.probeId);\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 if (!this._loggedProtocolWarnings.has(\"client-pushed-messages\")) {\n this._loggedProtocolWarnings.add(\"client-pushed-messages\");\n console.warn(\n \"[think] Ignoring client-pushed chat messages; Think is \" +\n \"server-authoritative and does not persist flat transcript \" +\n \"overwrites. Use @cloudflare/think/react so setMessages stays \" +\n \"local-only, and use clearHistory() for persisted clears.\"\n );\n }\n break;\n }\n }\n\n private async _handleStreamResumeRequest(\n connection: Connection,\n probeId?: string\n ): Promise<void> {\n await this._resumeHandshake().handleResumeRequest(connection, probeId);\n }\n\n private async _handleStreamResumeAck(\n connection: Connection,\n requestId: string\n ): Promise<void> {\n await this._resumeHandshake().handleResumeAck(connection, requestId);\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 // A genuinely-new turn supersedes any pending terminal record (#1645) so a\n // stale exhaustion can't replay over the resume handshake to a client that\n // reconnects in the window between accepting this submit and the new turn\n // streaming. Mirrors `@cloudflare/ai-chat`; without it a reconnect in that\n // gap would surface the previous failed turn's error even though the user\n // has already moved on. Completion clears it too, but only once the turn\n // resolves — which leaves the gap open.\n await withAgentSpan(\n this,\n \"clear_previous_chat_state\",\n \"interaction\",\n {\n \"cloudflare.agents.component\": \"think\",\n \"cloudflare.agents.turn.request_id\": requestId,\n \"cloudflare.agents.turn.trigger\": \"ws-chat\"\n },\n () => this._clearChatTerminal()\n );\n\n // Mark this turn as accepted-but-not-yet-streamed (#1784) so a client that\n // reconnects/re-mounts before the stream starts is parked and told to keep\n // waiting (see _resumeHandshake / onConnect), then flushed into\n // STREAM_RESUMING on _startResumableStream or released on settle.\n this._preStream.begin(requestId);\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 const requestBody =\n Object.keys(customBody).length > 0 ? customBody : undefined;\n withAgentSpan(\n this,\n \"persist_chat_request_context\",\n \"interaction\",\n {\n \"cloudflare.agents.component\": \"think\",\n \"cloudflare.agents.turn.request_id\": requestId,\n \"cloudflare.agents.turn.trigger\": \"ws-chat\"\n },\n () => {\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 this._lastBody = requestBody;\n this._persistBody();\n }\n );\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 withAgentSpan(\n this,\n \"load_chat_history\",\n \"interaction\",\n {\n \"cloudflare.agents.component\": \"think\",\n \"cloudflare.agents.turn.request_id\": requestId,\n \"cloudflare.agents.turn.trigger\": \"ws-chat\"\n },\n () => this._readMessagesFromStorage()\n );\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 const persisted = await withAgentSpan(\n this,\n \"persist_incoming_messages\",\n \"interaction\",\n {\n \"cloudflare.agents.component\": \"think\",\n \"cloudflare.agents.turn.request_id\": requestId,\n \"cloudflare.agents.turn.trigger\": \"ws-chat\"\n },\n async () => {\n if (this._turnQueue.generation !== epoch) return false;\n\n for (const msg of reconciled) {\n if (this._turnQueue.generation !== epoch) return false;\n await this._persistIncomingMessage(msg, serverMessages);\n }\n\n if (this._turnQueue.generation !== epoch) return false;\n await this._syncMessages();\n return true;\n }\n );\n if (!persisted) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n\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._admitTurn({\n admission: \"queue\",\n trigger: \"ws-chat\",\n requestId,\n generation: epoch,\n continuation: false,\n onQueued: releaseIfPending,\n execute: 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 // Bounded compact-and-retry loop (opt-in via\n // `contextOverflow.reactive`). A turn that overflows the\n // context window mid-flight is compacted and re-run from the\n // persisted partial instead of dying terminally. Each attempt\n // re-runs the same turn (`continuation: false`) — not an\n // auto-continuation.\n for (let attempt = 0; ; attempt++) {\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 this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"No response was generated.\",\n done: true\n });\n return;\n }\n\n // The consumer suppresses a classified overflow whenever\n // recovery is enabled; the driver (here) owns the\n // retry-vs-terminal call so every overflow terminal is reported\n // identically.\n let overflowError: string | undefined;\n let overflowRequested = false;\n const overflowRecovery = this._overflowReactiveEnabled\n ? {\n onRetry: (error?: string) => {\n overflowRequested = true;\n overflowError = error;\n }\n }\n : undefined;\n\n await withAgentSpan(\n this,\n \"persist_chat_result\",\n \"turn\",\n {\n \"cloudflare.agents.component\": \"think\",\n \"cloudflare.agents.turn.request_id\": requestId,\n \"cloudflare.agents.turn.trigger\": \"ws-chat\",\n \"cloudflare.agents.turn.admission\": \"queue\",\n \"cloudflare.agents.turn.generation\": epoch,\n \"cloudflare.agents.turn.continuation\": false\n },\n () =>\n this._streamResult(requestId, result, abortSignal, {\n parentId: branchParentId,\n overflowRecovery\n })\n );\n\n if (overflowRequested) {\n if (\n attempt < this._overflowMaxRetries &&\n !abortSignal?.aborted\n ) {\n const shortened = await withAgentSpan(\n this,\n \"compact_chat_history\",\n \"turn\",\n {\n \"cloudflare.agents.component\": \"think\",\n \"cloudflare.agents.turn.request_id\": requestId,\n \"cloudflare.agents.turn.trigger\": \"ws-chat\",\n \"cloudflare.agents.turn.admission\": \"queue\",\n \"cloudflare.agents.turn.generation\": epoch,\n \"cloudflare.agents.turn.continuation\": false\n },\n () =>\n this._compactForContextOverflow(\"reactive\", {\n requestId,\n attempt: attempt + 1\n })\n );\n // Compaction shortened history → retry. A no-op compaction\n // can't fix the overflow, so fall through to terminal.\n if (shortened) continue;\n }\n // Budget spent, aborted, or compaction no-op: deliver\n // terminally (through onChatError, classified) so the turn\n // never loops or ends silently with no answer.\n const message = this._finalizeContextOverflowError(\n requestId,\n overflowError\n );\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: message,\n done: true,\n error: true\n });\n }\n return;\n }\n };\n\n if (this.chatRecovery) {\n await this._runChatRecoveryFiber(requestId, false, chatTurnBody);\n } else {\n await chatTurnBody();\n }\n }\n });\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 // Release any pre-stream parked connections (#1784). No-op when the turn\n // streamed (flushed on _startResumableStream); covers the no-response /\n // pre-stream-failure paths.\n this._settlePreStreamTurn(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 // Tear down the event-driven auto-continuation barrier (#1650): cancel the\n // coalesce timer and clear the double-fire guard so a reset mid-park can't\n // leave a stale flag pinning future continuations.\n this._autoContinuation.reset();\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._continuation.sendResumeNone();\n this._continuation.clearAll();\n this._preStream.releaseAwaiting();\n this._preStream.reset();\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 /**\n * Stamp the allocated assistant id onto a new turn's `start` chunk so a chat\n * client builds the live-streamed message under the SAME id this agent\n * persists under. Providers that emit no `start.messageId` (e.g. Workers AI)\n * otherwise leave the client to generate its own id; the live stream and the\n * persisted message broadcast then can't reconcile by id, and the originating\n * tab briefly renders the turn twice before collapsing. Mirrors the fix in\n * `@cloudflare/ai-chat`. Continuations are skipped — they reuse the existing\n * assistant message via the `continuation` frame flag, so the id must not\n * change mid-message. The orphan-recovery path inherits the id from the\n * stored chunk, so it needs no separate stamping.\n */\n private _alignStreamStartId(\n chunk: StreamChunkData,\n action: { type: string; messageId?: string } | undefined,\n accumulator: StreamAccumulator,\n continuation: boolean\n ): void {\n if (action?.type === \"start\" && action.messageId == null && !continuation) {\n (chunk as { messageId?: string }).messageId = accumulator.messageId;\n }\n }\n\n private _annotateActionApprovalChunk(\n requestId: string,\n chunk: StreamChunkData,\n pendingActionCalls: Map<\n string,\n { toolName: string; input: unknown | undefined }\n >,\n parts?: UIMessage[\"parts\"]\n ): StreamChunkData {\n const toolCallId =\n typeof chunk.toolCallId === \"string\"\n ? chunk.toolCallId\n : typeof chunk.id === \"string\"\n ? chunk.id\n : undefined;\n\n if (toolCallId) {\n if (\n (chunk.type === \"tool-input-start\" ||\n chunk.type === \"tool-input-available\" ||\n chunk.type === \"tool-call\") &&\n typeof chunk.toolName === \"string\"\n ) {\n const previous = pendingActionCalls.get(toolCallId);\n pendingActionCalls.set(toolCallId, {\n toolName: chunk.toolName,\n input:\n \"input\" in chunk\n ? normalizeToolInput(chunk.input).input\n : previous?.input\n });\n } else if (\"input\" in chunk) {\n const previous = pendingActionCalls.get(toolCallId);\n if (previous) {\n pendingActionCalls.set(toolCallId, {\n ...previous,\n input: normalizeToolInput(chunk.input).input\n });\n }\n }\n }\n\n // A durable pause (durable-pause action OR codemode execution) surfaces as\n // a `tool-output-available` chunk whose output is `status: \"paused\"`, NOT a\n // `tool-approval-request`. Attach the approval descriptor here so the paused\n // transcript part renders consistently in every approval UI.\n if (chunk.type === \"tool-output-available\" && toolCallId) {\n const descriptor = this._descriptorForPausedOutput(\n requestId,\n toolCallId,\n (chunk as { output?: unknown }).output\n );\n return descriptor ? { ...chunk, approvalDescriptor: descriptor } : chunk;\n }\n\n if (chunk.type !== \"tool-approval-request\" || !toolCallId) return chunk;\n\n const storedDescriptor =\n this._activeTurnActionApprovalDescriptors.get(toolCallId);\n if (storedDescriptor) {\n return {\n ...chunk,\n approvalDescriptor: storedDescriptor\n };\n }\n\n let pending = pendingActionCalls.get(toolCallId);\n if (!pending && parts) {\n const part = parts.find(\n (candidate) =>\n \"toolCallId\" in candidate && candidate.toolCallId === toolCallId\n ) as Record<string, unknown> | undefined;\n if (typeof part?.toolName === \"string\") {\n pending = {\n toolName: part.toolName,\n input: \"input\" in part ? normalizeToolInput(part.input).input : {}\n };\n }\n }\n if (!pending) return chunk;\n\n const metadata = this._activeTurnActionMetadata.get(pending.toolName);\n if (!metadata) return chunk;\n\n const descriptor: ActionApprovalDescriptor = {\n requestId,\n toolCallId,\n action: metadata.actionName,\n summary: metadata.summary,\n input: pending.input ?? {},\n permissions: metadata.permissions ?? [],\n ...(metadata.risk !== undefined && { risk: metadata.risk }),\n kind: metadata.kind\n };\n\n return {\n ...chunk,\n approvalDescriptor: descriptor\n };\n }\n\n /**\n * Build the approval descriptor for a paused tool output, the single source\n * of truth for rendering a pending approval. Durable-pause actions read the\n * descriptor persisted on their pending row (resolved permissions, survives\n * compaction); codemode pauses derive `connector.method` from the first\n * pending action and let {@link describePausedExecution} enrich it. Returns\n * `undefined` for non-paused outputs or when no descriptor can be built.\n */\n private _descriptorForPausedOutput(\n requestId: string,\n toolCallId: string,\n output: unknown\n ): ActionApprovalDescriptor | undefined {\n if (typeof output !== \"object\" || output === null) return undefined;\n const o = output as {\n status?: unknown;\n executionId?: unknown;\n pending?: unknown;\n };\n if (o.status !== \"paused\") return undefined;\n const executionId =\n typeof o.executionId === \"string\" ? o.executionId : undefined;\n\n if (executionId?.startsWith(ACTION_PAUSE_ID_PREFIX)) {\n const row = this._readActionPendingRow(executionId);\n if (!row?.descriptor_json) return undefined;\n try {\n return JSON.parse(row.descriptor_json) as ActionApprovalDescriptor;\n } catch {\n return undefined;\n }\n }\n\n const pending = Array.isArray(o.pending)\n ? (o.pending as import(\"@cloudflare/codemode\").PendingAction[])\n : [];\n const first = pending[0];\n if (!first) return undefined;\n const label = `${first.connector}.${first.method}`;\n const base: ActionApprovalDescriptor = {\n requestId,\n toolCallId,\n action: label,\n summary: label,\n input: first.args,\n permissions: [],\n kind: \"durable-pause\"\n };\n const override = this.describePausedExecution(pending, {\n requestId,\n toolCallId\n });\n if (!override) return base;\n return {\n ...base,\n ...override,\n // Identity fields are ours to set — an override can't retarget the part.\n requestId,\n toolCallId\n };\n }\n\n private _applyActionApprovalDescriptorToParts(\n chunk: StreamChunkData,\n parts: UIMessage[\"parts\"]\n ): void {\n if (\n (chunk.type !== \"tool-approval-request\" &&\n chunk.type !== \"tool-output-available\") ||\n typeof chunk.toolCallId !== \"string\" ||\n chunk.approvalDescriptor === undefined\n ) {\n return;\n }\n const part = parts.find(\n (candidate) =>\n \"toolCallId\" in candidate && candidate.toolCallId === chunk.toolCallId\n ) as Record<string, unknown> | undefined;\n if (!part) return;\n if (chunk.type === \"tool-approval-request\") {\n // A genuine AI SDK approval request: the descriptor rides on the\n // approval object (which also carries the eventual decision).\n part.approval = {\n ...(part.approval as Record<string, unknown> | undefined),\n descriptor: chunk.approvalDescriptor\n };\n return;\n }\n // A durable pause (durable-pause action / codemode) is a SETTLED\n // `output-available` part, not an AI SDK approval. Putting the descriptor\n // on `part.approval` would make `convertToModelMessages` emit a\n // `tool-approval-request` for an already-resolved output on the next turn\n // (an invalid prompt). Use a sibling field conversion ignores instead.\n part.approvalDescriptor = chunk.approvalDescriptor;\n }\n\n private async _streamResultToRpcCallback(\n requestId: string,\n result: StreamableResult,\n callback: StreamCallback,\n abortSignal?: AbortSignal,\n options?: {\n /**\n * When set, an in-stream error the app classifies as `context_overflow`\n * is treated as recoverable: the partial is persisted, the stream is\n * finalized cleanly (no terminal error to the caller), and\n * `{ status: \"overflow_retry\" }` is returned so the driver can compact\n * and re-run. Pass only while the retry budget allows.\n */\n overflowRecovery?: boolean;\n }\n ): Promise<{\n status: \"completed\" | \"error\" | \"aborted\" | \"overflow_retry\";\n error?: string;\n }> {\n const streamId = this._startResumableStream(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 // Set when an in-stream overflow error is recoverable (opt-in): suppresses\n // terminal delivery so the driver can compact and re-run the turn.\n let overflowRetry = false;\n\n const stallTimeoutMs =\n this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;\n // True only when the wrapped stream was pulled to natural exhaustion; a\n // break OR a throw (stall watchdog) leaves it false so the finally drains\n // the abandoned tee branch.\n let streamDrainedNaturally = false;\n try {\n this._insideInferenceLoop = true;\n const flushState = { chunksSinceFlush: 0, hasFlushedContent: false };\n const pendingActionCalls = new Map<\n string,\n { toolName: string; input: unknown | undefined }\n >();\n try {\n const guardedStream = iterateWithStallWatchdog(\n result.toUIMessageStream({ onError: streamErrorToString }),\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 = this._annotateActionApprovalChunk(\n requestId,\n chunk as unknown as StreamChunkData,\n pendingActionCalls,\n accumulator.parts\n );\n const { action } = accumulator.applyChunk(streamChunk);\n this._applyActionApprovalDescriptorToParts(\n streamChunk,\n accumulator.parts\n );\n\n if (action?.type === \"error\") {\n streamError = action.error;\n // Recoverable context overflow (opt-in): don't terminalize. Persist\n // the partial after the loop, then signal the driver to compact and\n // re-run. No `message:error`/`chat:request:failed`/error frame here\n // — the turn isn't over.\n if (\n options?.overflowRecovery &&\n this._isRecoverableContextOverflow(streamError, requestId)\n ) {\n overflowRetry = true;\n break;\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 });\n break;\n }\n\n this._alignStreamStartId(streamChunk, action, accumulator, false);\n\n const chunkBody = JSON.stringify(streamChunk);\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 streamDrainedNaturally = !(\n aborted ||\n overflowRetry ||\n streamError !== undefined\n );\n } finally {\n this._insideInferenceLoop = false;\n // Only early exits leave an abandoned tee branch; a naturally\n // exhausted stream needs no drain (consumeStream is not free — it\n // tees the base stream and traverses the buffered branch). A thrown\n // exit (stall watchdog) never reaches the assignment above, so it\n // drains too.\n if (!streamDrainedNaturally) {\n this._drainInferenceStream(result);\n }\n }\n\n // Recoverable context overflow: discard the partial, close the stream\n // cleanly without a terminal error, and hand control back to the driver.\n // No `onDone`/`onError` and no response hook — the turn is not finished;\n // the retry owns the terminal outcome.\n //\n // The partial is intentionally NOT persisted: the driver re-runs the turn\n // from scratch (`continuation: false`) against the compacted history, so\n // the retry produces a fresh assistant message. Persisting the truncated\n // partial would leave an orphan beside the recovered answer — and any tool\n // work it captured would be re-issued by the retry, duplicating records.\n // The live-streamed chunks already reached clients; the driver's\n // post-retry `_broadcastMessages()` reconciles them to the real answer.\n if (overflowRetry) {\n this._completeResumableStream(streamId);\n streamFinalized = true;\n return { status: \"overflow_retry\", error: streamError };\n }\n\n if (streamError) {\n this._errorResumableStream(streamId);\n } else {\n this._completeResumableStream(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._completeResumableStream(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 { 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 return WITHOUT the generic terminal path,\n // which would otherwise re-broadcast the raw stall error.\n if (!streamFinalized) {\n this._errorResumableStream(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 { status: \"aborted\" };\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._errorResumableStream(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 return {\n status:\n streamError || pendingRpcError\n ? \"error\"\n : aborted\n ? \"aborted\"\n : \"completed\"\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 }\n // Forward progress: advance the monotonic, compaction-immune progress\n // counter HERE (production time) rather than in `_persistOrphanedStream` —\n // so it bumps only on genuinely new content and is immune to client\n // reconnects / recovery re-persists (which don't flow through this path).\n // Decoupled from the flush decision and routed through the shared\n // host-agnostic rule ({@link shouldCreditStreamProgress}) so the bump TIMING\n // matches `AIChatAgent`: a milestone (started segment / settled tool) always\n // credits, and a long single segment's streaming deltas credit through a\n // time throttle. This is what the recovery no-progress window keys off\n // (#1637), and stays compaction-proof (#1628).\n if (\n shouldCreditStreamProgress({\n codec: aiSdkRecoveryCodec,\n type: chunk.type,\n throttle: this._streamProgressCredit,\n now: Date.now()\n })\n ) {\n await this._bumpChatRecoveryProgress();\n }\n }\n\n /** Per-isolate throttle for crediting recovery progress from mid-segment\n * streaming-content deltas (the shared `agents/chat` rule); reset per isolate\n * so the first delta after a restart always credits. */\n private _streamProgressCredit = new StreamProgressCreditThrottle();\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 * When set, an in-stream error the app classifies as `context_overflow`\n * is treated as recoverable: the partial is persisted, the stream is\n * finalized cleanly (no terminal error frame), `onRetry(error)` is invoked\n * so the driver can compact and re-run, and `{ status: \"aborted\" }` is\n * returned. Pass only while the retry budget allows.\n */\n overflowRecovery?: { onRetry: (error?: string) => void };\n }\n ): Promise<StreamResultStatus> {\n const clearGen = this._turnQueue.generation;\n const streamId = this._startResumableStream(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 // Set when an in-stream overflow error is recoverable (opt-in): suppresses\n // terminal delivery so the driver can compact and re-run the turn.\n let overflowRetry = false;\n const flushState = { chunksSinceFlush: 0, hasFlushedContent: false };\n const pendingActionCalls = new Map<\n string,\n { toolName: string; input: unknown | undefined }\n >();\n\n const stallTimeoutMs =\n this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;\n // True only when the wrapped stream was pulled to natural exhaustion; a\n // break OR a throw (stall watchdog) leaves it false so the finally drains\n // the abandoned tee branch.\n let streamDrainedNaturally = false;\n try {\n this._insideInferenceLoop = true;\n try {\n const guardedStream = iterateWithStallWatchdog(\n result.toUIMessageStream({ onError: streamErrorToString }),\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 = this._annotateActionApprovalChunk(\n requestId,\n chunk as unknown as StreamChunkData,\n pendingActionCalls,\n accumulator.parts\n );\n const { action } = accumulator.applyChunk(streamChunk);\n this._applyActionApprovalDescriptorToParts(\n streamChunk,\n accumulator.parts\n );\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 // Recoverable context overflow (opt-in): don't terminalize. Persist\n // the partial after the loop, then signal the driver to compact and\n // re-run. No `message:error`/`chat:request:failed`/error frame here.\n if (\n options?.overflowRecovery &&\n this._isRecoverableContextOverflow(streamError, requestId)\n ) {\n overflowRetry = true;\n break;\n }\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 this._alignStreamStartId(\n streamChunk,\n action,\n accumulator,\n continuation\n );\n\n const chunkBody = JSON.stringify(streamChunk);\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 streamDrainedNaturally = !(\n streamAborted ||\n overflowRetry ||\n streamError !== undefined\n );\n } finally {\n this._insideInferenceLoop = false;\n // Only early exits leave an abandoned tee branch; a naturally\n // exhausted stream needs no drain (consumeStream is not free — it\n // tees the base stream and traverses the buffered branch). A thrown\n // exit (stall watchdog) never reaches the assignment above, so it\n // drains too.\n if (!streamDrainedNaturally) {\n this._drainInferenceStream(result);\n }\n }\n\n // Recoverable context overflow: discard the partial, close this stream\n // segment WITHOUT a terminal frame, and hand control back to the driver\n // via `onRetry`. The inline retry runs in this same invocation and owns\n // the terminal outcome, so we must NOT emit a `done` frame here — and\n // `doneSent = true` keeps the outer `finally` from emitting one (it would\n // otherwise prematurely terminate the client's stream mid-recovery and\n // mark the segment errored).\n //\n // The partial is intentionally NOT persisted: the driver re-runs the turn\n // from scratch (`continuation: false`) against the compacted history, so\n // the retry produces a fresh assistant message. Persisting the truncated\n // partial would leave an orphan beside the recovered answer — and any tool\n // work it captured would be re-issued by the retry, duplicating records.\n // The live-streamed chunks already reached clients; the retry's\n // `_broadcastMessages()` reconciles them to the real answer.\n if (overflowRetry && options?.overflowRecovery) {\n this._completeResumableStream(streamId);\n this._pendingResumeConnections.clear();\n doneSent = true;\n options.overflowRecovery.onRetry(streamError);\n this._streamingAssistant = null;\n return { status: \"aborted\" };\n }\n\n if (streamError) {\n this._errorResumableStream(streamId);\n } else {\n this._completeResumableStream(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._completeResumableStream(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._errorResumableStream(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._errorResumableStream(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._errorResumableStream(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 /**\n * Single source of Think's strip + empty-skip persistence rule. Strips the\n * internal final-answer parts and returns the message to persist (the stripped\n * copy, or the original when nothing was stripped), or `null` when stripping\n * leaves nothing user-facing (only structural `step-start` markers, or\n * nothing) — in which case the caller skips persistence so a structured\n * workflow turn does not leave an empty assistant message in the conversation.\n * Shared by `_persistAssistantMessage` and the orphan-persist path so the rule\n * cannot drift between the live and recovery writes.\n */\n private _strippedForPersist(msg: UIMessage): UIMessage | null {\n const stripped = this._stripInternalFinalAnswerParts(msg);\n if (stripped === msg) return msg;\n const hasMeaningfulParts = stripped.parts.some(\n (part) => (part as { type?: string }).type !== \"step-start\"\n );\n return hasMeaningfulParts ? stripped : null;\n }\n\n private async _persistAssistantMessage(\n msg: UIMessage,\n parentId?: string\n ): Promise<void> {\n const toPersist = this._strippedForPersist(msg);\n if (toPersist === null) return;\n await this._upsertMessageInHistory(toPersist, parentId);\n }\n\n /**\n * Remove parts belonging to Think's internal structured-output final-answer\n * tool (`think_final_answer`, or a collision-suffixed variant) from a UI\n * message so the internal call/result never enters the persisted conversation\n * (and is never re-fed to the model on later turns). Stateless and matched by\n * the reserved name so it also covers recovery re-persist paths. Handles both\n * the static (`tool-<name>`) and dynamic (`dynamic-tool`) part shapes the AI\n * SDK can emit.\n */\n private _stripInternalFinalAnswerParts(msg: UIMessage): UIMessage {\n const parts = msg.parts.filter((part) => {\n const candidate = part as { type?: string; toolName?: string };\n if (\n typeof candidate.type === \"string\" &&\n candidate.type.startsWith(\"tool-\") &&\n isThinkFinalAnswerToolName(candidate.type.slice(\"tool-\".length))\n ) {\n return false;\n }\n if (\n candidate.type === \"dynamic-tool\" &&\n typeof candidate.toolName === \"string\" &&\n isThinkFinalAnswerToolName(candidate.toolName)\n ) {\n return false;\n }\n return true;\n });\n return parts.length === msg.parts.length ? msg : { ...msg, parts };\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 sanitized = this._stripReservedMessageMetadata(msg);\n const resolved =\n sanitized.role === \"assistant\"\n ? resolveToolMergeId(sanitized, serverMessages)\n : sanitized;\n await this._upsertMessageInHistory(resolved);\n }\n\n /**\n * Strip {@link RESERVED_MESSAGE_METADATA_KEYS} from a client-supplied message\n * at intake. Those keys are server-written turn context (stamped by\n * `_stampChannel`) that hooks and recovery re-resolve and trust, so a client\n * must never be able to forge them.\n */\n private _stripReservedMessageMetadata(msg: UIMessage): UIMessage {\n const metadata = msg.metadata as Record<string, unknown> | undefined;\n if (\n !metadata ||\n !RESERVED_MESSAGE_METADATA_KEYS.some((key) => key in metadata)\n ) {\n return msg;\n }\n const rest = { ...metadata };\n for (const key of RESERVED_MESSAGE_METADATA_KEYS) {\n delete rest[key];\n }\n return { ...msg, metadata: rest };\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 // ── Durable execution approvals (codemode HITL) ──────────────────\n //\n // A `requiresApproval` connector call inside the execute tool pauses the\n // run *durably*: the tool returns `{ status: \"paused\", executionId,\n // pending }` as a normal output, the model narrates what it needs, and the\n // turn ends. These callables are the resume path: approve/reject the\n // pending action on the codemode runtime, replace the paused output in the\n // transcript with the new outcome, and auto-continue so the model sees it.\n\n /**\n * The codemode runtime handle behind the execute tool. `this.codemode` is\n * assigned when `createExecuteRuntime(this)` / `createExecuteTool(this)`\n * runs (normally at turn start, via `getTools()`); after a DO restart no\n * turn may have run yet, so fall back to building the tools once.\n */\n private _codemodeRuntime():\n | import(\"@cloudflare/codemode\").CodemodeRuntimeHandle\n | undefined {\n if (!this.codemode) {\n try {\n this.getTools();\n } catch {\n // getTools may require turn-time context; without it there is\n // simply no runtime to resolve.\n }\n }\n return this.codemode;\n }\n\n /**\n * Pending (awaiting-approval) actions across paused executions of the\n * execute tool's codemode runtime — `{ executionId, seq, connector,\n * method, args }` each, with FULL args (the transcript copy is truncated).\n * Clients reconcile approval cards against this on load.\n *\n * Client-callable (registered below — see the `callable()` calls after the\n * class body).\n */\n async pendingExecutions(\n executionId?: string\n ): Promise<import(\"@cloudflare/codemode\").PendingAction[]> {\n const runtime = this._codemodeRuntime();\n if (!runtime) return [];\n return runtime.pending(executionId);\n }\n\n /**\n * List everything awaiting human approval — parked `kind: \"durable-pause\"`\n * actions and paused codemode executions — each carrying its\n * {@link ActionApprovalDescriptor}. The unified, descriptor-first view a\n * dashboard, voice backend, or messenger reconciles against; resolve any of\n * them via {@link approveExecution} / {@link rejectExecution}. Pass an\n * `executionId` to scope to one.\n *\n * Client-callable.\n */\n async pendingApprovals(executionId?: string): Promise<PendingApproval[]> {\n const out: PendingApproval[] = [];\n\n for (const row of this._listActionPendingRows()) {\n if (executionId && row.execution_id !== executionId) continue;\n if (!row.descriptor_json) continue;\n let descriptor: ActionApprovalDescriptor;\n try {\n descriptor = JSON.parse(\n row.descriptor_json\n ) as ActionApprovalDescriptor;\n } catch {\n continue;\n }\n out.push({\n executionId: row.execution_id,\n source: \"action\",\n descriptor\n });\n }\n\n const runtime = this._codemodeRuntime();\n if (runtime) {\n const pending = await runtime.pending(executionId);\n const seen = new Set<string>();\n for (const action of pending) {\n if (seen.has(action.executionId)) continue;\n seen.add(action.executionId);\n const group = pending.filter(\n (candidate) => candidate.executionId === action.executionId\n );\n const toolCallId =\n this._findExecutionToolCall(action.executionId) ?? \"\";\n const descriptor = this._descriptorForPausedOutput(\"\", toolCallId, {\n status: \"paused\",\n executionId: action.executionId,\n pending: group\n });\n if (descriptor) {\n out.push({\n executionId: action.executionId,\n source: \"codemode\",\n descriptor\n });\n }\n }\n }\n\n return out;\n }\n\n /**\n * Approve a paused execution and resume it. The run continues from where\n * it stopped (replaying logged work, executing the approved call); the\n * outcome — completed, errored, or paused again on the NEXT gated call —\n * replaces the paused tool output in the transcript and the chat\n * auto-continues so the model can act on it.\n *\n * Approving an execution that is no longer pending (already settled,\n * expired, or unknown) returns `{ status: \"error\" }` with an explanatory\n * message — it never throws.\n *\n * Client-callable.\n */\n async approveExecution(executionId: string): Promise<unknown> {\n // Durable-pause action approvals own the `actpause_` id space and resolve\n // against the pending-approval store, not the codemode runtime.\n if (executionId.startsWith(ACTION_PAUSE_ID_PREFIX)) {\n return await this._approveActionPause(executionId);\n }\n const runtime = this._codemodeRuntime();\n if (!runtime) {\n return {\n status: \"error\",\n executionId,\n error:\n \"No codemode runtime is configured — the execute tool was never \" +\n \"created on this agent.\"\n };\n }\n const output = truncatePausedExecutionOutput(\n await runtime.approve({ executionId })\n );\n await this._applyExecutionOutcome(executionId, output);\n return output;\n }\n\n /**\n * Approve a parked `kind: \"durable-pause\"` action and run its `execute`.\n *\n * Claim-by-delete makes this idempotent across tabs/recovery: only the caller\n * that removes the row runs the action; a racing approve/reject sees no row\n * and reports \"already resolved\". Authorization happened at PAUSE time — the\n * human approval is the authority now, so we do not re-authorize (the turn\n * context that `authorizeAction` needs is gone). The action runs through the\n * ledger so its side effect stays replay-safe, the outcome replaces the\n * paused transcript part, and the chat continues even with no socket open.\n */\n private async _approveActionPause(executionId: string): Promise<unknown> {\n const row = this._claimActionPendingRow(executionId);\n if (!row) {\n return {\n status: \"error\",\n executionId,\n error: `Execution \"${executionId}\" is no longer pending — it was approved or rejected elsewhere.`\n };\n }\n\n const action = await this._findRegisteredAction(row.action_name);\n if (!action) {\n const output = {\n status: \"error\",\n executionId,\n action: row.action_name,\n error:\n `Action \"${row.action_name}\" is no longer registered, so the ` +\n `approved call cannot run. The approval was consumed.`\n };\n await this._applyExecutionOutcome(executionId, output);\n return output;\n }\n\n let input: unknown;\n try {\n input = JSON.parse(row.input_json);\n } catch {\n input = {};\n }\n\n const output = await this._runApprovedActionPause(action, row, input);\n this._emitActionPauseEvent({\n type: \"action:pause:approved\",\n payload: { action: row.action_name, executionId }\n });\n await this._applyExecutionOutcome(executionId, output);\n return output;\n }\n\n /** Resolve a registered action by its resolved name (config.name ?? key). */\n private async _findRegisteredAction(name: string): Promise<Action | null> {\n const actions = await this.getActions();\n for (const [registrationName, candidate] of Object.entries(actions)) {\n if (!isAction(candidate)) continue;\n const resolved = candidate.config.name ?? registrationName;\n if (resolved === name) return candidate;\n }\n return null;\n }\n\n /**\n * Run a just-approved durable-pause action's `execute` through the ledger.\n * Mirrors the inline `_actionToTool` execute wrapper (timeout, abort race,\n * model-output prep) MINUS authorization — that was settled at pause time.\n */\n private async _runApprovedActionPause(\n action: Action,\n row: ActionPendingRow,\n input: unknown\n ): Promise<unknown> {\n const config = action.config;\n const executeAction = config.execute as (\n input: unknown,\n ctx: ActionContext\n ) => Promise<unknown> | unknown;\n const idempotencyKey = config.idempotencyKey as\n | ActionIdempotencyKey<unknown>\n | undefined;\n const { signal, cleanup } = createActionAbortSignal(\n undefined,\n config.timeoutMs ?? DEFAULT_ACTION_TIMEOUT_MS\n );\n const ctx: ActionContext = {\n agent: this,\n env: this.env as Cloudflare.Env,\n requestId: row.request_id ?? \"\",\n toolCallId: row.tool_call_id,\n messages: [],\n signal,\n // No-op: a durable-pause approved action is delivered by a later\n // continuation turn (different requestId), so a same-turn attachment\n // can't be delivered in v1.\n attachReply: () => {}\n };\n const abortError = () =>\n signal.reason instanceof Error\n ? signal.reason\n : new Error(signal.reason ? String(signal.reason) : \"Action aborted\");\n let onAbort: (() => void) | undefined;\n try {\n if (signal.aborted) throw abortError();\n const abortPromise = new Promise<never>((_, reject) => {\n onAbort = () => reject(abortError());\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n const runAction = async () => {\n const out = await Promise.race([\n Promise.resolve(executeAction(input, ctx)),\n abortPromise\n ]);\n return prepareActionOutputForModel(out);\n };\n return await this._runLedgeredAction({\n toolName: row.action_name,\n idempotencyKey,\n input,\n ctx,\n runAction\n });\n } catch (error) {\n return actionErrorEnvelope(error);\n } finally {\n if (onAbort) signal.removeEventListener(\"abort\", onAbort);\n cleanup();\n }\n }\n\n /**\n * Reject a paused execution's pending action, ending the run. The\n * transcript's paused output is replaced with\n * `{ status: \"rejected\", executionId, reason }` and the chat\n * auto-continues so the model can adapt (or explain) instead of erroring.\n *\n * Client-callable.\n */\n async rejectExecution(\n executionId: string,\n reason?: string\n ): Promise<unknown> {\n if (executionId.startsWith(ACTION_PAUSE_ID_PREFIX)) {\n return await this._rejectActionPause(executionId, reason);\n }\n const runtime = this._codemodeRuntime();\n if (!runtime) {\n return {\n status: \"error\",\n executionId,\n error:\n \"No codemode runtime is configured — the execute tool was never \" +\n \"created on this agent.\"\n };\n }\n const pending = await runtime.pending(executionId);\n if (pending.length === 0) {\n return {\n status: \"error\",\n executionId,\n error: `Execution \"${executionId}\" is no longer pending.`\n };\n }\n // `reject` reports whether it actually terminated the run. A `false`\n // means the action was resolved between our `pending()` check and the\n // reject (approve/reject interleave across facet RPC awaits — input\n // gates only cover storage). Writing \"rejected\" then would clobber a\n // paused part whose real outcome (e.g. an in-flight approval) is still\n // coming, so surface an error instead.\n const terminated = await runtime.reject({\n executionId,\n seq: pending[0].seq\n });\n if (!terminated) {\n return {\n status: \"error\",\n executionId,\n error: `Execution \"${executionId}\" is no longer pending — it was approved or rejected elsewhere.`\n };\n }\n const output = {\n status: \"rejected\",\n executionId,\n reason: reason ?? \"Rejected by user\"\n };\n await this._applyExecutionOutcome(executionId, output);\n return output;\n }\n\n /**\n * Reject a parked `kind: \"durable-pause\"` action. Claim-by-delete consumes\n * the pending row (idempotent across tabs/recovery), the action's `execute`\n * never runs, and the paused transcript part is replaced with a `rejected`\n * outcome so the model can adapt or explain.\n */\n private async _rejectActionPause(\n executionId: string,\n reason?: string\n ): Promise<unknown> {\n const row = this._claimActionPendingRow(executionId);\n if (!row) {\n return {\n status: \"error\",\n executionId,\n error: `Execution \"${executionId}\" is no longer pending — it was approved or rejected elsewhere.`\n };\n }\n const output = {\n status: \"rejected\",\n executionId,\n action: row.action_name,\n reason: reason ?? \"Rejected by user\"\n };\n this._emitActionPauseEvent({\n type: \"action:pause:rejected\",\n payload: { action: row.action_name, executionId }\n });\n await this._applyExecutionOutcome(executionId, output);\n return output;\n }\n\n /**\n * Replace a paused execute-tool output in the transcript with the\n * execution's new outcome and kick the auto-continuation so the model sees\n * it.\n *\n * When no paused part carries `executionId` — the output was already\n * replaced from another tab, or compaction summarized the part away — the\n * runtime has still durably applied the approval/rejection, so the outcome\n * must not be dropped: it is appended as a system note instead, and the\n * continuation still fires so the model can act on it.\n */\n private async _applyExecutionOutcome(\n executionId: string,\n output: unknown\n ): Promise<boolean> {\n const toolCallId = this._findPausedExecutionToolCall(executionId);\n if (!toolCallId) {\n // Already resolved in place (e.g. approved from another tab)? Then the\n // transcript has the outcome and nothing more is needed.\n if (this._findExecutionToolCall(executionId) != null) return false;\n let summary: string;\n try {\n summary = JSON.stringify(output)?.slice(0, 4_000) ?? String(output);\n } catch {\n summary = String(output);\n }\n await this._appendMessageToHistory({\n id: `exec-outcome-${executionId}-${crypto.randomUUID()}`,\n role: \"system\",\n parts: [\n {\n type: \"text\",\n text:\n `[execute tool] The paused execution \"${executionId}\" was ` +\n `resolved, but its tool call is no longer in the transcript ` +\n `(it may have been compacted). Outcome: ${summary}`\n }\n ]\n } as UIMessage);\n } else {\n await this._enqueueInteractionApply(() =>\n this._applyToolUpdateToMessages(\n pausedExecutionUpdate(toolCallId, executionId, output)\n )\n );\n }\n // Continue on the approving connection when there is one (WS callable),\n // else any open connection (DO-stub approval with clients attached). When\n // NO connection is open — an approval arriving via RPC from a dashboard,\n // webhook, or voice backend — fall back to a connection-independent\n // continuation so the model still advances and the result isn't stranded.\n const { connection } = getCurrentAgent();\n let target = connection;\n if (!target) {\n for (const open of this.getConnections()) {\n target = open;\n break;\n }\n }\n if (target) {\n this._scheduleAutoContinuation(target);\n } else {\n this._runConnectionlessContinuation();\n }\n return true;\n }\n\n /**\n * Find the tool part holding the paused output of `executionId` — in the\n * in-flight streaming accumulator first (an approval can land while a new\n * turn streams), then the persisted transcript, newest message first.\n */\n private _findPausedExecutionToolCall(executionId: string): string | null {\n return this._findExecutionToolCall(executionId, true);\n }\n\n /**\n * Find the tool part carrying `executionId` in its output. With\n * `pausedOnly`, only a still-paused output matches — used to locate the\n * part an approval outcome should replace. Without it, any settled output\n * matches — used to distinguish \"already resolved elsewhere\" from \"the\n * part is gone from the transcript\" (e.g. compacted away).\n */\n private _findExecutionToolCall(\n executionId: string,\n pausedOnly = false\n ): string | null {\n const matches = (part: Record<string, unknown>): boolean => {\n if (part.state !== \"output-available\") return false;\n if (typeof part.toolCallId !== \"string\") return false;\n const output = part.output as\n | { status?: unknown; executionId?: unknown }\n | null\n | undefined;\n return (\n output != null &&\n typeof output === \"object\" &&\n (!pausedOnly || output.status === \"paused\") &&\n output.executionId === executionId\n );\n };\n\n const streaming = this._streamingAssistant;\n if (streaming) {\n for (const part of streaming.parts as unknown as Array<\n Record<string, unknown>\n >) {\n if (matches(part)) return part.toolCallId as string;\n }\n }\n\n for (let i = this.messages.length - 1; i >= 0; i--) {\n const message = this.messages[i];\n if (message.role !== \"assistant\") continue;\n for (const part of message.parts as unknown as Array<\n Record<string, unknown>\n >) {\n if (matches(part)) return part.toolCallId as string;\n }\n }\n return null;\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 // Scan the in-flight accumulator first, mirroring `@cloudflare/ai-chat`'s\n // `_streamingMessage` check. A parallel-batch client tool can stream a\n // pending `input-available`/`approval-requested` part into\n // `_streamingAssistant` before the end-of-stream persist writes it to\n // `this.messages`. The hot `waitUntilStable` loop only consults this after\n // `waitForIdle()` (when the streaming turn has drained and the accumulator\n // is null), so the scan is a no-op there. It matters on the same-isolate\n // stall route, where the incident-eval callback runs mid-stream: without\n // it Think would budget a stall that ai-chat treats as \"awaiting client\"\n // (budget-free) — a self-correcting drift once the continuation re-reads\n // persisted state, but a real asymmetry the stall watchdog would expose.\n const streaming = this._streamingAssistant;\n if (\n streaming &&\n this._messageHasPendingInteraction(\n streaming.toMessage(),\n clientResolvable\n )\n ) {\n return true;\n }\n return this.messages.some(\n (message) =>\n message.role === \"assistant\" &&\n this._messageHasPendingInteraction(message, clientResolvable)\n );\n }\n\n /**\n * `true` when an auto-continuation is armed but has not yet fired (#1650): a\n * pending continuation that has not entered its turn (`!pastCoalesce`) whose\n * coalesce timer is still pending or whose completeness drain is in progress.\n * Mirrors `@cloudflare/ai-chat`'s `_hasArmedContinuation`, consuming the shared\n * controller's `isArmed()`.\n */\n private _hasArmedContinuation(): boolean {\n const pending = this._continuation.pending;\n return (\n pending !== null &&\n !pending.pastCoalesce &&\n this._autoContinuation.isArmed()\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 // An auto-continuation may be armed (#1650): the coalesce timer is\n // still pending or its drain is in flight. Report not-stable and wait\n // it out, mirroring `@cloudflare/ai-chat` — otherwise idle eviction /\n // recovery could act in the ~50ms window before the held continuation\n // fires (and the turn it enqueues then drains via the loop top).\n if (!this._hasArmedContinuation()) {\n return true;\n }\n if (\n (await this._awaitWithDeadline(\n new Promise<void>((resolve) =>\n setTimeout(resolve, AutoContinuationController.COALESCE_MS)\n ),\n deadline\n )) === TIMED_OUT\n ) {\n return false;\n }\n continue;\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 _awaitWithDeadline<T>(\n promise: Promise<T>,\n deadline: number | null\n ): Promise<T | typeof TIMED_OUT> {\n return awaitWithDeadline(promise, deadline);\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 return clientResolvableToolNames(this._lastClientTools);\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 return partAwaitsClientInteraction(part, clientResolvable);\n }\n\n // ── Chat recovery via fibers ───────────────────────────────────\n\n private _resolveChatRecoveryConfig(): ResolvedChatRecoveryConfig {\n // Delegates to the shared incident engine (agents/chat) so Think and\n // AIChatAgent resolve recovery config identically. See\n // design/rfc-chat-recovery-foundation.md.\n return resolveChatRecoveryConfig(this.chatRecovery);\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 // Storage read lives in the shared engine (agents/chat); this is the\n // package binding, symmetric with `AIChatAgent`.\n return readChatRecoveryProgress(this.ctx.storage);\n }\n\n /** Advance the durable recovery-progress counter. Called from\n * `_storeChunkDurably` when a stored chunk credits forward progress under the\n * shared rule (real, reconnect-immune forward progress). The increment lives\n * in the shared engine (agents/chat); this is the package binding. */\n private async _bumpChatRecoveryProgress(): Promise<void> {\n return bumpChatRecoveryProgress(this.ctx.storage);\n }\n\n /** Per-isolate N9 throttle gate (shared `agents/chat` helper); reset per\n * isolate so the first forwarded chunk after a restart always credits. */\n private _agentToolStreamProgress = new AgentToolStreamProgressThrottle();\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 if (this._agentToolStreamProgress.shouldCredit(Date.now())) {\n await this._bumpChatRecoveryProgress();\n }\n }\n\n private async _beginChatRecoveryIncident(input: {\n requestId: string;\n recoveryRootRequestId?: string | null;\n latestUserMessageId?: 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 // Incident orchestration (sweep -> read -> rehydrate interaction state ->\n // budget eval -> persist -> emit, with its ordering invariants) lives in the\n // shared ChatRecoveryEngine; this method is the package's adapter binding.\n // See design/rfc-chat-recovery-foundation.md.\n return this._chatRecoveryEngine().beginIncident(input);\n }\n\n /**\n * Lazily-built shared recovery engine. The adapter arrows capture `this`, so a\n * single cached instance is correct across calls (and across future engine\n * methods).\n */\n private _chatRecoveryEngineInstance?: ChatRecoveryEngine;\n private _chatRecoveryEngine(): ChatRecoveryEngine {\n return (this._chatRecoveryEngineInstance ??= new ChatRecoveryEngine({\n resolveConfig: () => this._resolveChatRecoveryConfig(),\n now: () => Date.now(),\n sweepStaleIncidents: (now) =>\n sweepStaleChatRecoveryIncidents(this.ctx.storage, now),\n getIncident: async (key) =>\n (await this.ctx.storage.get<ChatRecoveryIncident>(key)) ?? null,\n // Hibernation ordering guard. The budget decision consults\n // `hasPendingInteraction()` -> `_clientResolvableToolNames()` ->\n // `_lastClientTools` to keep a HITL turn (parked on a client-tool\n // `input-available` orphan) budget-free. On a fresh wake the base Agent\n // runs the boot-recovery path (`_handleInternalFiberRecovery`) BEFORE\n // onStart's `_restoreClientTools()`, so without this the in-memory cache\n // is empty and such a turn is misread as \"stuck\" and wrongly sealed (the\n // slow-human + deploy-churn case). Re-hydrate from the durable\n // `think_config` store — its own table, no Session init required, so the\n // read is safe this early; the guard keeps it idempotent with the later\n // onStart restore and a no-op on the live-isolate stall path where the\n // tools are already loaded. The engine invokes this BEFORE it reads\n // `isAwaitingClientInteraction()`.\n ensureInteractionStateLoaded: () => {\n if (this._lastClientTools === undefined) {\n this._restoreClientTools();\n }\n },\n // Messenger/workflow reply fibers (`think:messenger-reply`) are NOT chat\n // turns; the messenger runtime owns their recovery. The engine dispatches\n // this before the chat-fiber gate so such a fiber is never misread as an\n // orphaned chat turn. `Promise.resolve(false)` when no messenger runtime\n // is initialized (e.g. a child facet).\n tryHandleNonChatFiberRecovery: (ctx) =>\n this._messengerRuntime?.handleFiberRecovery(ctx) ??\n Promise.resolve(false),\n readProgress: () => this._chatRecoveryProgressMarker(),\n // A turn parked on a pending CLIENT interaction is waiting on the human,\n // not stuck, so the engine keeps it budget-free. SERVER-tool orphans are\n // excluded by `hasPendingInteraction` and still recover normally.\n isAwaitingClientInteraction: () => this.hasPendingInteraction(),\n putIncident: (key, incident) => this.ctx.storage.put(key, incident),\n deleteIncident: async (key) => {\n await this.ctx.storage.delete(key);\n },\n emitRecoveryEvent: (event) =>\n this._emit(event.type, {\n incidentId: event.incidentId,\n requestId: event.requestId,\n attempt: event.attempt,\n maxAttempts: event.maxAttempts,\n recoveryKind: event.recoveryKind,\n ...(event.reason ? { reason: event.reason } : {})\n }),\n scheduleRecovery: async (callback, data, reason, delaySeconds) => {\n await this.schedule(\n delaySeconds,\n callback,\n data,\n chatRecoverySchedulePolicy(reason)\n );\n },\n setRecovering: (active, requestId) =>\n this._setChatRecovering(active, requestId),\n onShouldKeepRecoveringError: (error) =>\n console.error(\n \"[Think] chatRecovery shouldKeepRecovering hook threw\",\n error\n ),\n exhaustChatRecovery: (incident, config, partial, streamId, createdAt) =>\n this._exhaustChatRecovery(\n incident,\n config,\n partial,\n streamId,\n createdAt\n ),\n resolveRecoveryStream: (requestId) =>\n this._resolveThinkRecoveryStream(requestId),\n getPartialStreamText: (streamId) => this._getPartialStreamText(streamId),\n activeChatRecoveryRootRequestId: () =>\n this._activeChatRecoveryRootRequestId,\n onGiveUpBookkeepingError: (phase, error) =>\n console.error(\n phase === \"read\"\n ? \"[Think] failed to read recovery incident during give-up; synthesizing\"\n : \"[Think] failed to persist sealed recovery incident during give-up\",\n error\n )\n } satisfies ChatRecoveryAdapter));\n }\n\n private async _updateChatRecoveryIncident(\n incidentId: string | undefined,\n status: ChatRecoveryIncident[\"status\"],\n reason?: string\n ): Promise<void> {\n // Incident state-machine transitions (delete-on-completed vs persist, the\n // completed/skipped/failed event emit, and the #1620 recovering-flag) live\n // in the shared ChatRecoveryEngine; this method is the package's adapter\n // binding, symmetric with `AIChatAgent`. The recovering-flag clear here\n // covers the benign-skip / failed paths that never reach a turn-level\n // terminal (exhaustion + normal completion also clear via\n // `_recordTerminalChatStatus`). See design/rfc-chat-recovery-foundation.md.\n return this._chatRecoveryEngine().updateIncident(\n incidentId,\n status,\n reason\n );\n }\n\n private async _exhaustChatRecovery(\n incident: ChatRecoveryIncident,\n config: ResolvedChatRecoveryConfig,\n // `parts` is the engine's vocabulary-agnostic `unknown[]`; Think owns the AI\n // SDK `UIMessage` vocabulary, so it re-asserts `MessagePart[]` at the\n // user-facing exhausted-context edge below.\n partial: { text: string; parts: unknown[] },\n streamId: string,\n createdAt: number\n ): Promise<void> {\n // Build + notification (event + onExhausted-swallow) and the\n // notify-before-terminalize invariant live in the engine helper; the\n // broadcast/terminal ordering inside `terminalize` is Think's own\n // (broadcast-first; see the note below). See\n // design/rfc-chat-recovery-foundation.md.\n await runChatRecoveryExhaustion(\n {\n incident,\n config,\n partialText: partial.text,\n partialParts: partial.parts as MessagePart[],\n streamId,\n createdAt\n },\n {\n emit: (event) => this._emit(\"chat:recovery:exhausted\", event),\n onExhausted: config.onExhausted,\n onError: (error) =>\n console.error(\"[Think] chatRecovery onExhausted hook threw\", error),\n terminalize: async (ctx) => {\n // Deliver the user-visible terminal banner BEFORE the bookkeeping\n // storage writes below. A `ctx.storage` write can reject mid-deploy\n // (the exact window recovery exhausts in), and if it threw before this\n // broadcast the user would be left staring at a half-finished message\n // with no terminal resolution. The broadcast itself touches no\n // storage, so ordering it first makes the banner resilient to a\n // failing `_recordTerminalChatStatus` / `_markRecoveredSubmissionInterrupted`.\n // `@cloudflare/ai-chat` terminalizes broadcast-first for the same\n // reason; only the set of durable writes below differs (Think also\n // writes a submission row).\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: ctx.requestId,\n body: ctx.terminalMessage,\n done: true,\n error: true\n });\n // Write the durable terminal record (#1645) FIRST among the storage\n // writes: it's the record a disconnected client replays on reconnect,\n // so it must not be skipped if the (independent) submission-row write\n // below throws.\n await this._recordTerminalChatStatus(\n \"interrupted\",\n ctx.requestId,\n ctx.terminalMessage\n );\n // The submission is keyed by the recovery ROOT request id;\n // `ctx.requestId` is the latest per-continuation id and won't match a\n // chained submission.\n await this._markRecoveredSubmissionInterrupted(\n ctx.recoveryRootRequestId ?? ctx.requestId,\n ctx.terminalMessage\n );\n }\n }\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 // 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._chatRecoveryEngine().scheduleRecovery({\n incident,\n recoveryKind: \"continue\",\n callback: \"_chatRecoveryContinue\",\n data: {\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 });\n return \"scheduled\";\n }\n\n protected override async _handleInternalFiberRecovery(\n ctx: FiberRecoveryContext\n ): Promise<boolean> {\n // The wake-recovery lifecycle (non-chat dispatch → chat gate → unwrap →\n // stream/partial → classify → begin-incident → exhausted-branch →\n // onChatRecovery → persist → complete → dispatch → catch→failed) lives in the\n // shared ChatRecoveryEngine; this binds the divergent organs as wake hooks,\n // symmetric with `AIChatAgent`. `Think` tracks terminal stream status and a\n // durable submission layer + session leaf, so its dispatch owns the\n // terminal-skip / submission-completion / interrupted-broadcast branches the\n // engine frame stays out of. See design/rfc-chat-recovery-foundation.md.\n return this._chatRecoveryEngine().handleChatFiberRecovery(ctx, {\n chatFiberPrefix: () =>\n (this.constructor as typeof Think).CHAT_FIBER_NAME + \":\",\n unwrapRecoverySnapshot: (fiber) => {\n const { snapshot, user } = unwrapChatFiberSnapshot<\"think-chat-turn\">(\n \"__cfThinkChatFiberSnapshot\",\n fiber.snapshot,\n \"think-chat-turn\"\n );\n return { snapshot, recoveryData: user };\n },\n classifyRecoveredTurn: (input) => this._classifyRecoveredThinkTurn(input),\n invokeOnChatRecovery: (input) =>\n this.onChatRecovery({\n incidentId: input.incident.incidentId,\n recoveryRootRequestId: input.recoveryRootRequestId,\n attempt: input.incident.attempt,\n maxAttempts: input.incident.maxAttempts,\n recoveryKind: input.recoveryKind,\n streamId: input.streamId,\n requestId: input.requestId,\n partialText: input.partial.text,\n // The engine seam is vocabulary-agnostic (`unknown[]`); Think owns the\n // AI SDK parts vocabulary, so re-assert it for the user-facing context.\n partialParts: input.partial.parts as MessagePart[],\n recoveryData: input.recoveryData,\n messages: [...this.messages],\n lastBody: input.snapshot?.lastBody ?? this._lastBody,\n lastClientTools:\n input.snapshot?.lastClientTools ?? this._lastClientTools,\n createdAt: input.createdAt\n }),\n shouldPersistOrphanedPartial: (input) =>\n this._shouldPersistOrphanedPartial(input.streamId, {\n streamStillActive: input.streamStillActive,\n streamIsTerminal:\n input.streamStatus === \"completed\" ||\n input.streamStatus === \"error\",\n snapshot: input.snapshot\n }),\n persistOrphanedStream: (streamId) =>\n this._persistOrphanedStream(streamId),\n completeRecoveredStream: (streamId) =>\n this._completeResumableStream(streamId),\n dispatchRecoveredTurn: (input) => this._dispatchRecoveredThinkTurn(input)\n } satisfies ChatFiberWakeHooks<ThinkRecoveryClassification>);\n }\n\n /**\n * Resolve the orphaned stream + its terminal status for a recovered chat turn.\n * Drives BOTH the wake path (full result) and the give-up terminalization\n * (which reads only `.streamId`; the terminal banner still fires when\n * `streamId` is `\"\"` — `_exhaustChatRecovery` does not require a stream).\n * Prefers the newest durable stream row keyed by the recovery-root request id;\n * falls back to the live active stream.\n */\n private _resolveThinkRecoveryStream(\n requestId: string\n ): ResolvedRecoveryStream {\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 const streamStillActive = Boolean(\n streamId &&\n this._resumableStream.hasActiveStream() &&\n this._resumableStream.activeStreamId === streamId\n );\n return { streamId, streamStillActive, streamStatus };\n }\n\n /**\n * Classify a recovered turn as `retry` or `continue`. A pre-stream turn with no\n * partial re-runs its user message (`retryTargetUserId`), unless the stream is\n * already terminal — a terminal stream is never retried (it completed), only\n * its submission is reconciled in dispatch.\n */\n private async _classifyRecoveredThinkTurn(\n input: ClassifyRecoveredTurnInput\n ): Promise<{\n recoveryKind: ChatRecoveryKind;\n detail: ThinkRecoveryClassification;\n }> {\n const streamIsTerminal =\n input.streamStatus === \"completed\" || input.streamStatus === \"error\";\n const retryTargetUserId = await this._recoverablePreStreamUserId(\n input.snapshot,\n input.streamId,\n input.partial\n );\n const shouldRetryBase = retryTargetUserId !== null && !streamIsTerminal;\n const recoveryKind: ChatRecoveryKind = shouldRetryBase\n ? \"retry\"\n : \"continue\";\n return { recoveryKind, detail: { retryTargetUserId } };\n }\n\n /**\n * The retry/continue/skip decision for a recovered chat turn, run after the\n * partial is persisted and the stream completed. Owns `Think`'s substrate\n * behavior the engine frame stays out of: a terminal stream reconciles the\n * durable submission (and is never retried/continued), and a `continue: false`\n * abandonment marks the submission interrupted + records a terminal status +\n * broadcasts so a reconnecting client is not frozen.\n */\n private async _dispatchRecoveredThinkTurn(\n input: DispatchRecoveredTurnInput<ThinkRecoveryClassification>\n ): Promise<void> {\n const {\n incident,\n options,\n snapshot,\n requestId,\n recoveryRootRequestId,\n streamStatus\n } = input;\n const { retryTargetUserId } = input.detail;\n const streamIsTerminal =\n streamStatus === \"completed\" || streamStatus === \"error\";\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._chatRecoveryEngine().scheduleRecovery({\n incident,\n recoveryKind: input.recoveryKind,\n callback: \"_chatRecoveryRetry\",\n data: {\n targetUserId: retryTargetUserId,\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n lastBody: snapshot?.lastBody ?? null,\n lastClientTools: snapshot?.lastClientTools ?? null,\n ...(recoveredRequestId ? { recoveredRequestId } : {})\n }\n });\n } else if (canContinue) {\n await this._chatRecoveryEngine().scheduleRecovery({\n incident,\n recoveryKind: input.recoveryKind,\n callback: \"_chatRecoveryContinue\",\n data: {\n ...(targetId ? { targetAssistantId: targetId } : {}),\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n ...(snapshot\n ? {\n lastBody: snapshot.lastBody ?? null,\n lastClientTools: snapshot.lastClientTools ?? null\n }\n : {}),\n ...(recoveredRequestId ? { recoveredRequestId } : {})\n }\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 is\n // correct), disabling recovery abandons the turn with no superseding turn.\n // 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\n private async _recoverablePreStreamUserId(\n snapshot: ChatFiberSnapshot | null,\n streamId: string,\n partial: { text: string; parts: unknown[] }\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 | 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 | 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 /**\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: ChatRecoveryScheduleCallback,\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined,\n maxAttempts: number\n ): Promise<boolean> {\n // The attempt-bump + scheduled/stable_timeout_retry persist + delayed\n // non-idempotent reschedule live in the shared ChatRecoveryEngine; this\n // method is the package's adapter binding, symmetric with `AIChatAgent`.\n // See design/rfc-chat-recovery-foundation.md.\n return this._chatRecoveryEngine().rescheduleAfterStableTimeout({\n incidentId: data?.incidentId,\n callback,\n data,\n fallbackMaxAttempts: maxAttempts\n });\n }\n\n /**\n * Park a recovery continuation that timed out waiting for stable state\n * because the turn is holding a pending CLIENT interaction (an\n * `input-available` client-tool part or an `approval-requested` part — see\n * `hasPendingInteraction`). Such a turn is WAITING ON THE HUMAN, not stuck:\n * the SPA replays the interrupted tool-result / approval after reconnect,\n * which drives a fresh continuation via the auto-continuation barrier\n * independently of the recovery retry loop. Burning the attempt budget on\n * that wait (each `waitUntilStable` times out because the human hasn't\n * answered) would seal a perfectly healthy turn on `stable_timeout` — the\n * exact symptom behind HITL \"session recovery errors\" under deploy churn.\n *\n * So instead of rescheduling or exhausting, we stop the loop and mark the\n * incident `skipped` (reason `awaiting_client_interaction`). That retains the\n * incident record (a later genuine interruption re-evaluates it) while\n * resolving the live \"recovering…\" indicator via `_updateChatRecoveryIncident`\n * so the client sees the parked tool-call UI rather than an eternal spinner.\n * A client that never returns is reclaimed by the incident TTL sweep and DO\n * idle-eviction. SERVER-tool orphans are excluded by `hasPendingInteraction`\n * (their `execute` died with the isolate), so they still recover normally.\n *\n * For a SUBMISSION-backed turn (`recoveredRequestId` present) the recovery\n * loop is the submission row's SOLE completion driver after a restart, and the\n * client's replay resumes the conversation as an independent auto-continuation\n * that never touches the submission. Parking would therefore leave the row\n * `running` until `_recoverSubmissionsOnStart` swept it to `error` on the next\n * restart. We instead complete it `completed` here: the park condition is a\n * fully-materialized client tool call in the leaf, which is exactly the\n * terminal state a non-interrupted submission reaches when its step emits a\n * client tool call (the model does not block on client tools — see\n * `_runProgrammaticMessagesTurn`, which marks such a step `completed`). The\n * human round-trip then proceeds via the normal auto-continuation, identical\n * to the non-crash flow.\n *\n * Returns `true` when the recovery was parked (caller must return), `false`\n * when there is no pending client interaction (caller proceeds to the normal\n * reschedule / exhaustion path).\n */\n private async _parkRecoveryForPendingInteraction(\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined\n ): Promise<boolean> {\n if (!this.hasPendingInteraction()) return false;\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"skipped\",\n \"awaiting_client_interaction\"\n );\n if (data?.recoveredRequestId) {\n await this._completeRecoveredSubmission(\n data.recoveredRequestId,\n \"completed\",\n null,\n null\n );\n }\n return true;\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-transient throw\n * in a recovery callback is SWALLOWED by `Agent._executeScheduleCallback`\n * (only a platform transient is re-thrown to preserve the one-shot row), so\n * without routing it here the alarm row is deleted with no terminal UX at\n * all — the half-finished message wedges silently. Shared by\n * `_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 seal is persisted only AFTER the\n * terminal writes in `_exhaustChatRecovery` succeed (see the ordering\n * note at the call below), so a give-up interrupted by a platform\n * transient re-runs in full instead of being half-sealed.\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 * Residual at-least-once edges, all 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 * • A platform transient interrupts `_exhaustChatRecovery` after the banner\n * broadcast — the deferred re-run re-fires `onExhausted` + the banner\n * (the terminal writes themselves are idempotent).\n */\n /**\n * Recovery continuation callbacks the alarm-boundary OOM circuit breaker may\n * back off / purge (#1825). See `Agent._cf_handleAlarmMemoryLimitReset`.\n */\n protected override _cf_recoveryAlarmCallbacks(): string[] {\n return [\"_chatRecoveryContinue\", \"_chatRecoveryRetry\"];\n }\n\n /**\n * Seal any still-live recovery incident as an out-of-memory exhaustion when\n * the alarm circuit breaker trips at its strike budget (#1825). Runs at the\n * outermost alarm frame (post-unwind), so the terminal banner / `onExhausted`\n * and the sealed-incident write can land where the mid-turn give-up's writes\n * OOMed. Reuses the shared give-up spine via `_exhaustRecoveryGiveUp`.\n */\n protected override async _cf_sealMemoryLimitedRecovery(): Promise<void> {\n const active = await listActiveChatRecoveryIncidents(this.ctx.storage);\n for (const { incident } of active) {\n const callback: ChatRecoveryScheduleCallback =\n incident.recoveryKind === \"retry\"\n ? \"_chatRecoveryRetry\"\n : \"_chatRecoveryContinue\";\n await this._exhaustRecoveryGiveUp(\n callback,\n { incidentId: incident.incidentId },\n \"out_of_memory\"\n );\n }\n }\n\n private _exhaustRecoveryGiveUp(\n callback: ChatRecoveryScheduleCallback,\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined,\n reason: string\n ): Promise<void> {\n // The give-up spine (read → re-entry-guard → build-exhausted-incident →\n // terminalize-before-seal → best-effort seal) lives in the shared\n // ChatRecoveryEngine; this is the package binding, symmetric with\n // `AIChatAgent`. Think keeps the `reason` parameter (its callers pass\n // `stable_timeout` | `recovery_error`) and the `recoveredRequestId` link in\n // the engine's root-id chain (supplied via the schedule payload). The\n // terminalize + stream/partial hooks are wired on the adapter above. See\n // design/rfc-chat-recovery-foundation.md.\n return this._chatRecoveryEngine().exhaustRecoveryGiveUp({\n callback,\n data,\n reason\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: ChatRecoveryScheduleCallback,\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined\n ): Promise<void> {\n return this._exhaustRecoveryGiveUp(callback, data, \"stable_timeout\");\n }\n\n /**\n * Apply the tight OOM-retry budget to a recovery error (#1825). Invoked from\n * `_handleRecoveryCallbackError`, i.e. for an OOM that is *thrown* out of a\n * recovery turn (typically from recovery bookkeeping or storage/SQL ops that\n * reject with the memory-limit-reset message after an isolate reset). An OOM\n * that surfaces as a returned `error` result means `continueLastTurn` already\n * terminalized the turn (client error frame + `onError`), so it is NOT routed\n * here — re-driving a terminalized turn would be wasteful and risk a second\n * terminal signal. `error` may be an Error or a wrapper with a `cause` chain.\n *\n * The reliable terminator is the begin-path (`evaluateChatRecoveryIncident`),\n * which seals once `oomAttempts` exceeds the budget; that runs before the\n * memory-heavy turn, in the low-memory window where writes succeed. This\n * method's job is to persist `oomAttempts` (small writes) so the begin path\n * can act on it, and to schedule a delayed re-run while under budget.\n *\n * Returns `true` when the error was an OOM and this method owns the outcome:\n * - under budget → a delayed re-run was scheduled (best-effort: a transient\n * spike may clear);\n * - over budget (or untrackable, or the bookkeeping itself OOMed) →\n * terminalized via the give-up path with `reason=\"out_of_memory\"`.\n * Returns `false` for non-OOM errors so the caller proceeds normally.\n */\n private async _handleRecoveryOom(\n callback: ChatRecoveryScheduleCallback,\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined,\n error: unknown\n ): Promise<boolean> {\n if (!isDurableObjectMemoryLimitReset(error)) return false;\n let decision: \"rescheduled\" | \"exhausted\" = \"exhausted\";\n try {\n decision = await this._chatRecoveryEngine().recordOomAndDecide({\n incidentId: data?.incidentId,\n callback,\n data,\n maxOomRetries: this._resolveChatRecoveryConfig().maxOomRetries\n });\n } catch (bookkeepingError) {\n // The bump/reschedule writes can themselves reject in the degraded isolate\n // that just OOMed. Fail closed (seal) rather than risk a silent wedge; the\n // finite `maxRecoveryWork` backstop covers anything that slips past.\n console.error(\n \"[Think] failed to record OOM recovery attempt; terminalizing\",\n bookkeepingError\n );\n decision = \"exhausted\";\n }\n if (decision === \"exhausted\") {\n await this._exhaustRecoveryGiveUp(callback, data, \"out_of_memory\");\n }\n return true;\n }\n\n /**\n * Handle an error thrown by `_chatRecoveryContinue` / `_chatRecoveryRetry`\n * after the incident was opened.\n *\n * - A platform transient (`isPlatformTransientError` from `agents` — a\n * deploy code-update reset / script supersede, a `retryable`-flagged\n * platform error, or \"Network connection lost.\", looking through wrappers\n * like `SqlError` via the `cause` chain) is re-thrown (after best-effort\n * marking the incident `failed` for observability) so\n * `Agent._executeScheduleCallback` preserves the one-shot alarm row and\n * the platform re-runs recovery once it is healthy again — the turn can\n * still recover, so it must NOT terminalize. Terminalizing here was the\n * #1730 freeze: the give-up's own seal needs the very storage that is\n * down, so it throws too, burns the in-process retry budget inside the\n * same reset window, and the row is consumed milliseconds before storage\n * recovers. The submission is deliberately left `running` — the deferred\n * re-run reads it via `_readRunningSubmissionByRequestId`, so marking it\n * terminal here would turn the preserved row into a guaranteed\n * `submission_not_running` no-op skip (a self-defeating defer).\n * - Any OTHER (application) 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-transient throw and then `alarm()` deletes the one-shot\n * row, so without terminalizing here the half-finished turn is dropped\n * with no terminal event and no banner (the user stares at a frozen\n * message until they send something new).\n */\n private async _handleRecoveryCallbackError(\n callback: ChatRecoveryScheduleCallback,\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined,\n error: unknown\n ): Promise<void> {\n // A memory-limit reset is NOT a platform transient (re-running the same\n // memory-heavy turn re-OOMs deterministically), so it must be classified\n // BEFORE the transient check and routed through the tight OOM-retry budget\n // instead of either deferring forever or terminalizing on the first hit\n // (#1825). Returns true once it has owned the outcome (rescheduled or\n // sealed); only fall through to the generic handling for non-OOM errors.\n if (await this._handleRecoveryOom(callback, data, error)) return;\n if (isPlatformTransientError(error)) {\n const message = error instanceof Error ? error.message : String(error);\n try {\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"failed\",\n message\n );\n } catch (bookkeepingError) {\n // Best-effort observability only — in the exact window this branch\n // fires (deploy reset / storage outage) the incident write itself can\n // reject; that must not replace the deferral with its own error.\n console.error(\n \"[Think] failed to mark recovery incident failed before deferring\",\n bookkeepingError\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 would be lost. Mirrors\n // `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 // PARK while a CLIENT interaction is pending — the turn is waiting for\n // the human, not churning; see `_chatRecoveryContinue` for the full\n // rationale.\n if (await this._parkRecoveryForPendingInteraction(data)) {\n return;\n }\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\n ? { signal: controller.signal, trigger: \"recovery-retry\" }\n : { trigger: \"recovery-retry\" }\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 // If this facet is an agent-tool child, its recovered turn just settled\n // outside `startAgentToolRun`'s finalizer — eagerly close the run so a\n // re-attached parent collects the terminal immediately rather than\n // waiting out a no-progress window. The pre-stream retry path settles a\n // fresh user turn that (like `continueLastTurn`) never hits the\n // finalizer, so it needs the same reconcile as `_chatRecoveryContinue`.\n await this._reconcileOwnStaleAgentToolChildRuns();\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 // PARK, don't burn the budget: a stable-state timeout while a CLIENT\n // interaction is pending is not churn — the turn is correctly waiting\n // for the SPA to replay an interrupted tool-result / approval after\n // reconnect, which drives a fresh continuation via the auto-continuation\n // barrier independently of this retry loop. Retrying here would just\n // time out again (the human hasn't answered) and eventually seal a\n // healthy turn on `stable_timeout`. So stop the loop, resolve the live\n // \"recovering…\" indicator, and let the client's replay resume the turn.\n if (await this._parkRecoveryForPendingInteraction(data)) {\n return;\n }\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\n ? { signal: controller.signal, trigger: \"recovery-continue\" }\n : { trigger: \"recovery-continue\" }\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 // If this facet is an agent-tool child, its recovered turn just settled\n // outside `startAgentToolRun`'s finalizer — eagerly close the run so a\n // re-attached parent collects the terminal immediately rather than\n // waiting out a no-progress window.\n await this._reconcileOwnStaleAgentToolChildRuns();\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 hasSettledToolResults: boolean;\n } {\n return aiSdkRecoveryCodec.toRecoveryPartial(\n this._resumableStream.getStreamChunks(streamId).map((chunk) => chunk.body)\n );\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 // A skipped turn settles out of the pre-stream set, but must NOT release\n // parked connections (#1784): a skip happens because a NEWER turn was\n // admitted (latest/merge supersede) or the queue generation advanced. The\n // earliest \"successor exists\" signal (`SubmitConcurrencyController.decide`)\n // fires before the successor's `_preStream.begin()`, so releasing here would\n // race a `begin()` that hasn't run yet and cut a parked client loose right\n // before the successor streams. Leave it parked: the successor flushes it on\n // stream start, or the final surviving turn's settle releases it. (Chat\n // clear releases parked connections explicitly via `resetTurnState`.)\n this._settlePreStreamTurn(requestId, { releaseParked: false });\n }\n\n /**\n * Mark an accepted turn (#1784) as settled. When `releaseParked` (the default)\n * and no accepted turn remains in flight and no stream is active, release every\n * connection parked on the pre-stream window with STREAM_RESUME_NONE. No-op once\n * they were flushed into STREAM_RESUMING on stream start. Skip paths pass\n * `releaseParked: false` so a parked client survives onto the successor turn\n * (see `_completeSkippedRequest`).\n */\n private _settlePreStreamTurn(\n requestId: string,\n options: { releaseParked?: boolean } = {}\n ): void {\n const idle = this._preStream.settle(requestId);\n const releaseParked = options.releaseParked ?? true;\n if (releaseParked && idle && !this._resumableStream.hasActiveStream()) {\n this._preStream.releaseAwaiting();\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 this._autoContinuation.schedule({\n connection,\n clientTools: this._lastClientTools,\n body: undefined,\n errorPrefix: \"[Think] Auto-continuation failed:\"\n });\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 this._autoContinuation.rearmForBatch();\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._autoContinuation.rearmForBatch();\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 _drainInteractionApplies(): Promise<void> {\n return drainInteractionApplies(\n () => this._continuation.pending !== null,\n () => 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 return hasIncompleteToolBatch(this.messages);\n }\n\n private _fireAutoContinuation(): void {\n const pending = this._continuation.pending;\n if (!pending) return;\n\n const { connection, requestId, clientTools } = pending;\n const abortSignal = this._aborts.getSignal(requestId);\n\n this._admitTurn({\n admission: \"queue\",\n trigger: \"auto-continuation\",\n requestId,\n continuation: true,\n allowNested: true,\n execute: 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 this._autoContinuation.activateDeferredAndReschedule();\n }\n\n /**\n * Run a continuation turn that does NOT require a live client connection.\n *\n * Used when a durable approval (a paused action or codemode execution) is\n * resolved via RPC from a surface with no open chat socket — e.g. an ops\n * dashboard, a webhook, or a voice backend approving hours/days later. The\n * connection-bound auto-continuation barrier (`_fireAutoContinuation`) cannot\n * fire without a `Connection`, so this mirrors its turn body but streams via\n * `broadcast` (a no-op when nobody is attached) and always persists, so a\n * client that reconnects later resumes the continued turn from history.\n *\n * Wrapped in `keepAliveWhile` because the resolving RPC returns before the\n * continuation finishes (mirrors the submission-drain pattern).\n */\n private _runConnectionlessContinuation(): void {\n void this.keepAliveWhile(async () => {\n const requestId = crypto.randomUUID();\n const abortSignal = this._aborts.getSignal(requestId);\n try {\n await this._admitTurn({\n admission: \"queue\",\n trigger: \"auto-continuation\",\n requestId,\n continuation: true,\n allowNested: true,\n execute: async () => {\n const continuationBody = 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: this._lastClientTools,\n body: this._lastBody,\n continuation: true\n })\n );\n if (result) {\n await this._streamResult(requestId, result, abortSignal, {\n continuation: true\n });\n }\n };\n\n if (this.chatRecovery) {\n await this._runChatRecoveryFiber(\n requestId,\n true,\n continuationBody\n );\n } else {\n await continuationBody();\n }\n }\n });\n } catch (error) {\n console.error(\"[Think] Connection-less continuation failed:\", error);\n } finally {\n this._aborts.remove(requestId);\n }\n });\n }\n\n // ── Response hook ──────────────────────────────────────────────\n\n /**\n * Render a reply attachment ({@link ReplyAttachment}) for delivery to the\n * active channel. Returns the text/markdown to post, or `undefined` to skip —\n * unknown types, or types a channel handles out of band (e.g. `voice_note`\n * via the voice transport). Override to customize per app/channel.\n */\n renderAttachment(\n attachment: ReplyAttachment\n ): string | { markdown: string } | undefined {\n switch (attachment.type) {\n case \"card\":\n return {\n markdown: `\\`\\`\\`json\\n${JSON.stringify(\n (attachment as { payload: unknown }).payload,\n null,\n 2\n )}\\n\\`\\`\\``\n };\n case \"email_draft\": {\n const draft = attachment as { subject?: string; to?: string[] };\n const lines = [\"**Email draft**\"];\n if (draft.to?.length) lines.push(`To: ${draft.to.join(\", \")}`);\n if (draft.subject) lines.push(`Subject: ${draft.subject}`);\n return { markdown: lines.join(\"\\n\") };\n }\n case \"voice_note\":\n return undefined;\n default:\n return undefined;\n }\n }\n\n /**\n * Deliver known reply attachments to the active channel (best-effort, never\n * fails the turn). Unknown types are ignored.\n */\n private async _renderChannelAttachments(\n attachments: ReplyAttachment[] | undefined\n ): Promise<void> {\n if (!attachments?.length) {\n return;\n }\n for (const attachment of attachments) {\n let rendered: string | { markdown: string } | undefined;\n try {\n rendered = this.renderAttachment(attachment);\n } catch (error) {\n console.warn(\n `[Think] renderAttachment threw: ${error instanceof Error ? error.message : String(error)}`\n );\n continue;\n }\n if (rendered === undefined) {\n continue;\n }\n try {\n await this.deliverNotice(rendered, { kind: \"interim\" });\n } catch (error) {\n console.warn(\n `[Think] failed to deliver channel attachment: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n }\n\n private async _fireResponseHook(result: ChatResponseResult): Promise<void> {\n // Surface advisory reply attachments recorded during this turn.\n result.attachments = this.replyAttachments(result.requestId);\n // Record the channel-level delivery for this turn (the turn-scoped channel\n // context is still set here — the response hook runs inside the turn body).\n const deliveredChannel = this._activeChannelContext;\n if (deliveredChannel) {\n this._emitChannelEvent({\n type: \"channel:delivered\",\n payload: {\n channel: deliveredChannel.channelId,\n kind: \"final\",\n turnEnded: true\n }\n });\n }\n await this._renderChannelAttachments(result.attachments);\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`/`interrupted`) or clear (on `completed`/`aborted`) the\n * durable terminal record so it can be replayed to clients on reconnect, and\n * resolve any in-progress \"recovering…\" indicator. A `completed`/`aborted`\n * turn is conveyed by the persisted messages, so the record is cleared; an\n * `error`/`interrupted` turn has no durable trace otherwise, so it is kept\n * until a later turn supersedes it.\n *\n * The storage primitives are shared with `@cloudflare/ai-chat`\n * (`_recordChatTerminal` / `_clearChatTerminal` / `_pendingChatTerminal`).\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._recordChatTerminal(requestId, body);\n } else {\n await this._clearChatTerminal();\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 /**\n * Persist a durable record of the last terminal turn so a client that\n * (re)connects after the turn ended still learns its outcome (#1645). Kept\n * until a later turn supersedes it (`_clearChatTerminal`); a single record is\n * sufficient because only the most recent terminal is relevant.\n */\n private async _recordChatTerminal(\n requestId: string,\n body: string\n ): Promise<void> {\n await recordChatTerminal(this.ctx.storage, requestId, body);\n }\n\n /** Clear the durable terminal record once a later turn supersedes it (#1645). */\n private async _clearChatTerminal(): Promise<void> {\n await clearChatTerminal(this.ctx.storage);\n }\n\n private async _pendingChatTerminal(): Promise<{\n requestId: string;\n body: string;\n } | null> {\n return pendingChatTerminal(this.ctx.storage);\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 await setChatRecovering(active, requestId, {\n storage: this.ctx.storage,\n messageType: MSG_CHAT_RECOVERING,\n broadcast: (frame) => this._broadcastChat(frame),\n now: Date.now()\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 an in-progress \"recovering…\" status (if any).\n *\n * A terminal error is deliberately NOT replayed here. A bare\n * `MSG_CHAT_RESPONSE` frame on connect is dropped by the `useAgentChat`\n * client because it never reaches a transport stream reader, so it cannot\n * become `useChat.error` — a failed turn would still look frozen (#1645).\n * The terminal outcome is instead surfaced over the resume handshake (the\n * shared {@link ResumeHandshake} drives `STREAM_RESUMING` → ACK → terminal\n * error frame), the only path that lands on the stream reader.\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 // Replay an in-progress \"recovering…\" status so a client that connects\n // mid-recovery reads the turn as working rather than frozen (#1620). This\n // is a plain status frame the client handles on connect (unlike a terminal\n // error, which must go through the resume handshake). It's mutually\n // exclusive with a terminal record (any terminal outcome clears recovering).\n // Skip a stale record (older than the flag TTL) so a turn whose recovery\n // was abandoned without a terminal can't show \"recovering…\" forever on\n // reconnect.\n const recoveringFrame = await buildChatRecoveringFrame(\n this.ctx.storage,\n MSG_CHAT_RECOVERING,\n Date.now()\n );\n if (recoveringFrame) {\n messages.push(recoveringFrame);\n }\n return messages;\n }\n\n // ── Resume helpers ──────────────────────────────────────────────\n\n /**\n * The shared resume-handshake driver (Tier-2). Lazily built; the\n * `ResumableStream` / `ContinuationState` / pending set are stable after\n * `onStart`, so a single instance threads them for the agent's lifetime. The\n * idle-connect payload (transcript + recovering, `_buildIdleConnectMessages`)\n * stays host-owned and is NOT part of the driver.\n */\n private _resumeHandshake(): ResumeHandshake {\n return (this._resumeHandshakeInstance ??= new ResumeHandshake({\n responseMessageType: MSG_CHAT_RESPONSE,\n resumableStream: this._resumableStream,\n continuation: this._continuation,\n preStream: this._preStream,\n pendingResumeConnections: this._pendingResumeConnections,\n pendingChatTerminal: () => this._pendingChatTerminal(),\n persistOrphanedStream: (streamId) =>\n this._persistOrphanedStream(streamId),\n isConnectionPresent: (connectionId) =>\n this.getConnection(connectionId) !== undefined\n }));\n }\n\n /**\n * Notify a connection about an active stream that can be resumed — delegates\n * to the shared {@link ResumeHandshake}. Kept as a thin method because it is\n * also called proactively from onConnect and the broadcast loop. See the\n * driver for the #1733 double-send contract.\n */\n private _notifyStreamResuming(connection: Connection): void {\n this._resumeHandshake().notifyStreamResuming(connection);\n }\n\n /**\n * Start a resumable stream and arm buffer cleanup. Wrapper around\n * `ResumableStream.start`: arming on START as well as finish guarantees a\n * stream whose DO is evicted mid-flight and never reaches a finish still gets\n * a future sweep instead of leaking its buffer.\n *\n * When a turn runs inside `runFiber` (durable recovery), the DO already\n * self-heals: `runFiber` holds `keepAlive`, which leaves a durable alarm in\n * storage that survives eviction, fires within ~keepAliveIntervalMs, and runs\n * the fiber-recovery scan — finalizing the stream (which arms cleanup) without\n * any client reconnect. Arming here is the safety net for any non-fiber stream\n * path, where no such alarm exists. The last-activity sweep threshold prevents\n * an actively streaming run from being reclaimed before it goes quiet (#1706).\n */\n protected _startResumableStream(\n requestId: string,\n options?: { messageId?: string }\n ): string {\n const streamId = this._resumableStream.start(requestId, options);\n // Flush connections parked during this turn's pre-stream window (#1784)\n // into STREAM_RESUMING now that a stream exists. No-op unless a client\n // reconnected before the first chunk. (Continuation-turn parks live in\n // `_continuation` and are flushed by the caller.)\n this._preStream.flushOnStreamStart((c) => this._notifyStreamResuming(c));\n void this._ensureStreamCleanupScheduled();\n return streamId;\n }\n\n /**\n * Mark a resumable stream completed and arm buffer cleanup. Wrapper around\n * `ResumableStream.complete` so every stream-finish path also schedules the\n * cleanup alarm (#1706).\n */\n protected _completeResumableStream(streamId: string): void {\n this._resumableStream.complete(streamId);\n void this._ensureStreamCleanupScheduled();\n }\n\n /**\n * Mark a resumable stream errored and arm buffer cleanup. Wrapper around\n * `ResumableStream.markError` — see {@link _completeResumableStream}.\n */\n protected _errorResumableStream(streamId: string): void {\n this._resumableStream.markError(streamId);\n void this._ensureStreamCleanupScheduled();\n }\n\n /**\n * Ensure a single cleanup alarm is pending for this DO's resumable-stream\n * buffers. Armed whenever a stream finishes so that idle/one-off chat DOs\n * still reclaim their buffers — the lazy sweep in {@link ResumableStream}\n * only fires when a *subsequent* stream completes, which never happens for a\n * chat that receives a single turn (#1706).\n *\n * `idempotent` dedupes on (callback, payload, owner) so repeated finishes\n * collapse onto one pending alarm rather than stacking.\n */\n protected async _ensureStreamCleanupScheduled({\n idempotent = true\n }: { idempotent?: boolean } = {}): Promise<void> {\n await this.schedule(\n STREAM_CLEANUP_DELAY_SECONDS,\n \"_cleanupStreamBuffers\",\n undefined,\n { idempotent }\n );\n }\n\n /**\n * Alarm callback: sweep aged stream buffers, re-arming while rows remain (see\n * the shared {@link cleanupStreamBuffers}).\n */\n async _cleanupStreamBuffers(): Promise<void> {\n await cleanupStreamBuffers(this._resumableStream, () =>\n this._ensureStreamCleanupScheduled({ idempotent: false })\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 // The accumulate loop and the `getMessage → update(merge) XOR append` upsert\n // are the shared `persistReconstructedOrphan` core. Think supplies the two\n // host-specific hooks:\n // - prepare: `_strippedForPersist` (same as `_persistAssistantMessage`) —\n // drop the internal final-answer parts and skip (`null`) an empty\n // structural-only assistant message.\n // - merge: Think replaces the whole message (no partial merge).\n // NOTE: progress is bumped at production/flush time in `_storeChunkDurably`\n // (#1637), NOT here — persisting on recovery or a client reconnect must not\n // be miscounted as new forward progress.\n const wrote = await persistReconstructedOrphan(chunks, {\n store: this._orphanStore(),\n fallbackId: crypto.randomUUID(),\n prepare: (message) => this._strippedForPersist(message),\n merge: (_existing, incoming) => incoming\n });\n if (wrote) this._broadcastMessages();\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\n// Register the HITL methods as client-callable. Imperative registration\n// (rather than `@callable()` decorator syntax on the methods) because TC39\n// decorators don't survive every consumer toolchain that compiles this file\n// from source (e.g. esbuild targeting ES2021).\nfor (const method of [\n Think.prototype.pendingExecutions,\n Think.prototype.pendingApprovals,\n Think.prototype.approveExecution,\n Think.prototype.rejectExecution\n]) {\n callable()(method, undefined as unknown as ClassMethodDecoratorContext);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgEA,SAAgB,2BACd,QACoC;CACpC,IAAI,WAAW,OAAO,OAAO;CAC7B,MAAM,OAAO,WAAW,OAAO,CAAC,IAAI;CACpC,OAAO;EACL,oBAAoB,KAAK,sBAAsB;EAC/C,cAAc,KAAK,gBAAgB,KAAK;EACxC,wBAAwB,KAAK,0BAA0B;EACvD,gBAAgB,KAAK,kBAAkB;CACzC;AACF;AA4BA,MAAM,iBAAiB;;;;;AAMvB,SAAgB,2BACd,SACA,SACoB;CACpB,MAAM,QAAQ;EACZ;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