@cloudflare/think 0.23.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +30 -40
  2. package/dist/{chat-sdk-BEjKXjCm.js → chat-sdk-4Nu96eDX.js} +375 -256
  3. package/dist/chat-sdk-4Nu96eDX.js.map +1 -0
  4. package/dist/extensions/index.d.ts +30 -72
  5. package/dist/extensions/index.js +45 -47
  6. package/dist/extensions/index.js.map +1 -1
  7. package/dist/{fetch-DO3uQ9py.js → fetch-BbYxtlff.js} +10 -2
  8. package/dist/fetch-BbYxtlff.js.map +1 -0
  9. package/dist/manager-B3rcb_6p.js +493 -0
  10. package/dist/manager-B3rcb_6p.js.map +1 -0
  11. package/dist/manager-CWGumyKi.d.ts +3391 -0
  12. package/dist/messengers/index.d.ts +54 -66
  13. package/dist/messengers/index.js +2 -2
  14. package/dist/messengers/telegram.d.ts +4 -4
  15. package/dist/messengers/telegram.js +1 -1
  16. package/dist/think.d.ts +2 -2
  17. package/dist/think.js +8493 -10725
  18. package/dist/think.js.map +1 -1
  19. package/dist/tools/browser.d.ts +1 -1
  20. package/dist/tools/browser.js +1 -1
  21. package/dist/tools/browser.js.map +1 -1
  22. package/dist/tools/execute.d.ts +2 -2
  23. package/dist/tools/execute.js +2 -2
  24. package/dist/tools/execute.js.map +1 -1
  25. package/dist/tools/extensions.d.ts +1 -1
  26. package/dist/tools/extensions.js +1 -1
  27. package/dist/tools/fetch.js +1 -1
  28. package/dist/workflows.d.ts +5 -2
  29. package/docs/actions.md +12 -0
  30. package/docs/channels.md +10 -4
  31. package/docs/client-tools.md +57 -27
  32. package/docs/context.md +92 -0
  33. package/docs/getting-started.md +4 -4
  34. package/docs/index.md +112 -52
  35. package/docs/lifecycle-hooks.md +10 -21
  36. package/docs/multi-chat.md +6 -6
  37. package/docs/programmatic-submissions.md +28 -10
  38. package/docs/sub-agents.md +45 -51
  39. package/docs/tools.md +41 -15
  40. package/docs/workflows.md +5 -4
  41. package/package.json +15 -10
  42. package/dist/chat-sdk-BEjKXjCm.js.map +0 -1
  43. package/dist/fetch-DO3uQ9py.js.map +0 -1
  44. package/dist/hook-proxy-DY2sBNa0.js +0 -117
  45. package/dist/hook-proxy-DY2sBNa0.js.map +0 -1
  46. package/dist/index-DDnny6kt.d.ts +0 -5847
  47. package/dist/manager-BubfmA3q.js +0 -313
  48. package/dist/manager-BubfmA3q.js.map +0 -1
  49. package/dist/manager-rze95KCk.d.ts +0 -235
package/dist/think.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"think.js","names":["agentContext","withInvocationScope"],"sources":["../src/skills.ts","../src/session.ts","../src/media-eviction.ts","../src/channels/index.ts","../src/think.ts"],"sourcesContent":["/**\n * The `skills` namespace Think re-exports: `agents/skills`, plus the\n * experimental script runner from `agents/skills/runner` so `skills.runner()`\n * keeps working for Think users.\n *\n * The exports are listed by name: the declaration bundler drops\n * `export * from` an external package inside a namespace.\n *\n * @module\n */\nexport {\n DEFAULT_WORKSPACE_SKILLS_ROOT,\n formatSkill,\n formatSkillDiagnostic,\n fromManifest,\n InvalidSkillResourcePathError,\n isModelInvocable,\n loadSkillCatalog,\n manifest,\n parseSkill,\n parseSkillName,\n parseSkillResourcePath,\n r2,\n renderSkillResource,\n SkillParseError,\n SkillResourceNotFoundError,\n SkillSourceError,\n UnknownSkillError,\n workspace\n} from \"agents/skills\";\nexport type {\n InvalidSkill,\n ListedSkill,\n LoadSkillCatalogOptions,\n ParseSkillOptions,\n R2SkillSourceOptions,\n Skill,\n SkillCatalog,\n SkillCatalogEntry,\n SkillCatalogResource,\n SkillDiagnostic,\n SkillListing,\n SkillManifest,\n SkillManifestEntry,\n SkillManifestResource,\n SkillName,\n SkillParseErrorCode,\n SkillParseResult,\n SkillResource,\n SkillResourceError,\n SkillResourceInfo,\n SkillResourceKind,\n SkillResourcePath,\n SkillResult,\n SkillRunContext,\n SkillScriptContext,\n SkillScriptFile,\n SkillScriptRequest,\n SkillScriptRunner,\n SkillScriptWorkspace,\n SkillSource,\n SkillWorkspace,\n WorkspaceSkillSourceOptions\n} from \"agents/skills\";\nexport { runner } from \"agents/skills/runner\";\nexport type { WorkerSkillScriptRunnerOptions } from \"agents/skills/runner\";\n","/**\n * Think's conversation handle.\n *\n * Wraps the `agents/sessions` `Session` handle that `Think.sessions` hands\n * out, so that a subclass written against the pre-Sessions Think API keeps\n * compiling and running unchanged:\n *\n * - the context builder methods (`withContext`, `withCachedPrompt`) that\n * used to live on the session, now queued and folded into\n * `Think.configureContext()`;\n * - the context accessors (`addContext`, `getContextBlock`,\n * `refreshSystemPrompt`, `tools`, ...), now forwarded to `Think.context`;\n * - the positional `appendMessage(message, parentId)` and\n * `getHistory(leafId)` forms alongside the options-object forms.\n *\n * Storage calls delegate to the real handle; the context forwards are\n * deprecated and exist only so an upgrade is a no-op. New code should read\n * `this.context` directly and declare blocks in `configureContext()`.\n *\n * The wrapper is explicit forwarding rather than a subclass or Proxy because\n * `Session` keeps its state in `#private` fields, which neither survives.\n */\n\nimport type { ToolSet } from \"ai\";\nimport type {\n AppendOptions,\n AppendResult,\n CompactionFunction,\n CompactResult,\n HistoryBatchReadOptions,\n HistoryReadOptions,\n RecentHistoryResult,\n SearchResult,\n Session,\n SessionMessage,\n SessionRowStat,\n StoredCompaction,\n WriteOptions\n} from \"agents/sessions\";\nimport type {\n ContextBlock,\n ContextBlocks,\n ContextConfig,\n WritableContextProvider\n} from \"agents/context\";\n\n/** Options for a block declared through `withContext()` / `addContext()`. */\nexport type SessionContextOptions = Omit<ContextConfig, \"label\">;\n\n/** Receives an error thrown by the registered compaction function. */\nexport type CompactionErrorHandler = (error: unknown) => void | Promise<void>;\n\n/**\n * @deprecated `compactAfter()` gates on the token estimate Sessions stamps on\n * each row; a custom counter is no longer consulted. Accepted so existing\n * calls compile.\n */\nexport interface CompactAfterOptions {\n tokenCounter?: unknown;\n}\n\nexport class ThinkSession {\n readonly #handle: Session;\n readonly #context: () => ContextBlocks;\n /** Blocks queued by `withContext()`; `null` once startup consumed them. */\n #pendingContext: ContextConfig[] | null = [];\n #promptStore: WritableContextProvider | undefined;\n #compactionErrorHandler: CompactionErrorHandler | null = null;\n\n /** @internal Constructed by Think during `onStart`. */\n constructor(handle: Session, context: () => ContextBlocks) {\n this.#handle = handle;\n this.#context = context;\n }\n\n get sessionId(): string {\n return this.#handle.sessionId;\n }\n\n /** @internal Blocks declared through `withContext()` during configuration. */\n internal_takePendingContext(): ContextConfig[] {\n const pending = this.#pendingContext ?? [];\n this.#pendingContext = null;\n return pending;\n }\n\n /** @internal A custom frozen-prompt store passed to `withCachedPrompt()`. */\n internal_promptStore(): WritableContextProvider | undefined {\n return this.#promptStore;\n }\n\n // ── Builder (configureSession) ────────────────────────────────────────────\n\n /**\n * Declare a prompt context block.\n *\n * @deprecated Return the block from `configureContext()` instead. Only\n * callable inside `configureSession()`; after startup use\n * `this.context.addBlock()`.\n */\n withContext(label: string, options: SessionContextOptions = {}): this {\n if (!this.#pendingContext) {\n throw new Error(\n \"withContext() is only available inside configureSession(). \" +\n \"After startup, add a block with this.context.addBlock().\"\n );\n }\n this.#pendingContext.push({ label, ...options });\n return this;\n }\n\n /**\n * Persist the frozen system prompt.\n *\n * @deprecated The frozen prompt is always persisted now, so this is a\n * no-op. A custom `provider` is still honoured as the prompt store.\n */\n withCachedPrompt(provider?: WritableContextProvider): this {\n if (provider) this.#promptStore = provider;\n return this;\n }\n\n /** Register the function `compact()` calls to summarize a branch. */\n onCompaction(fn: CompactionFunction): this {\n this.#handle.onCompaction(async (messages) => {\n try {\n return await fn(messages);\n } catch (error) {\n const handler = this.#compactionErrorHandler;\n if (!handler) throw error;\n await handler(error);\n return null;\n }\n });\n return this;\n }\n\n /**\n * Auto-compact after an append once the stamped token estimate crosses the\n * threshold. Requires `onCompaction()`.\n */\n compactAfter(tokenThreshold: number, _options?: CompactAfterOptions): this {\n this.#handle.compactAfter(tokenThreshold);\n return this;\n }\n\n /**\n * Observe compaction failures. When set, a failing compaction function\n * calls the handler and the compaction is skipped; without one the failure\n * is reported through the `session:error` capability event.\n */\n onCompactionError(handler: CompactionErrorHandler): this {\n this.#compactionErrorHandler = handler;\n return this;\n }\n\n // ── Reads ────────────────────────────────────────────────────────────────\n\n history(\n options?: HistoryReadOptions\n ): AsyncGenerator<SessionMessage, void, undefined> {\n return this.#handle.history(options);\n }\n\n historyBatches(\n options?: HistoryBatchReadOptions\n ): AsyncGenerator<SessionMessage[], void, undefined> {\n return this.#handle.historyBatches(options);\n }\n\n /**\n * Materialize the whole selected path. Accepts a leaf id positionally, as\n * the pre-Sessions API did, or a read-options object.\n */\n getHistory(\n leafIdOrOptions?: string | null | HistoryReadOptions\n ): Promise<SessionMessage[]> {\n return this.#handle.getHistory(readOptions(leafIdOrOptions));\n }\n\n /**\n * Byte-budgeted read of the most recent messages on the active path. The\n * pre-Sessions `minRecentMessages` argument is accepted and ignored: the\n * budget is a hard ceiling, and the newest message is always returned.\n */\n getRecentHistory(\n maxContentBytes: number,\n optionsOrMinRecentMessages?: number | Pick<HistoryReadOptions, \"leafId\">\n ): Promise<RecentHistoryResult> {\n const options =\n typeof optionsOrMinRecentMessages === \"object\"\n ? optionsOrMinRecentMessages\n : undefined;\n return this.#handle.getRecentHistory(maxContentBytes, options);\n }\n\n getHistoryRowStats(leafId?: string | null): Promise<SessionRowStat[]> {\n return this.#handle.getHistoryRowStats(leafId);\n }\n\n /** @deprecated Read `getHistoryRowStats()` and take its length. */\n async getPathLength(leafId?: string | null): Promise<number> {\n return (await this.#handle.getHistoryRowStats(leafId)).length;\n }\n\n getMessage(id: string): Promise<SessionMessage | null> {\n return this.#handle.getMessage(id);\n }\n\n getLatestLeaf(): Promise<SessionMessage | null> {\n return this.#handle.getLatestLeaf();\n }\n\n getBranches(messageId: string): Promise<SessionMessage[]> {\n return this.#handle.getBranches(messageId);\n }\n\n search(query: string, options?: { limit?: number }): Promise<SearchResult[]> {\n return this.#handle.search(query, options);\n }\n\n // ── Writes ───────────────────────────────────────────────────────────────\n\n /**\n * Append one message. Accepts the parent id positionally, as the\n * pre-Sessions API did, or an options object.\n */\n appendMessage(\n message: SessionMessage,\n parentIdOrOptions?: string | null | AppendOptions\n ): Promise<AppendResult> {\n return this.#handle.appendMessage(\n message,\n appendOptions(parentIdOrOptions)\n );\n }\n\n updateMessage(\n message: SessionMessage,\n options?: WriteOptions\n ): Promise<SessionMessage | null> {\n return this.#handle.updateMessage(message, options);\n }\n\n upsertMessage(\n message: SessionMessage,\n parentIdOrOptions?: string | null | AppendOptions\n ): Promise<AppendResult> {\n return this.#handle.upsertMessage(\n message,\n appendOptions(parentIdOrOptions)\n );\n }\n\n importMessage(\n message: SessionMessage,\n options: { parentId: string | null; createdAt: number }\n ): Promise<void> {\n return this.#handle.importMessage(message, options);\n }\n\n deleteMessages(messageIds: string[]): Promise<void> {\n return this.#handle.deleteMessages(messageIds);\n }\n\n clearMessages(): Promise<void> {\n return this.#handle.clearMessages();\n }\n\n // ── Compaction ───────────────────────────────────────────────────────────\n\n addCompaction(\n summary: string,\n fromMessageId: string,\n toMessageId: string\n ): Promise<StoredCompaction> {\n return this.#handle.addCompaction(summary, fromMessageId, toMessageId);\n }\n\n getCompactions(): Promise<StoredCompaction[]> {\n return this.#handle.getCompactions();\n }\n\n compact(leafId?: string | null): Promise<CompactResult | null> {\n return this.#handle.compact(leafId);\n }\n\n // ── Context forwards ─────────────────────────────────────────────────────\n //\n // Prompt context lives on `Think.context` now. These forwards keep the\n // pre-Sessions call sites working and will be removed in a later minor.\n\n /** @deprecated Use `this.context.addBlock({ label, ...options })`. */\n addContext(\n label: string,\n options: SessionContextOptions = {}\n ): Promise<ContextBlock> {\n return this.#context().addBlock({ label, ...options });\n }\n\n /** @deprecated Use `this.context.removeBlock(label)`. */\n removeContext(label: string): boolean {\n return this.#context().removeBlock(label);\n }\n\n /** @deprecated Use `this.context.getBlock(label)`. */\n getContextBlock(label: string): ContextBlock | null {\n return this.#context().getBlock(label);\n }\n\n /** @deprecated Use `this.context.getBlocks()`. */\n getContextBlocks(): ContextBlock[] {\n return this.#context().getBlocks();\n }\n\n /** @deprecated Use `this.context.setBlock(label, content)`. */\n replaceContextBlock(label: string, content: string): Promise<ContextBlock> {\n return this.#context().setBlock(label, content);\n }\n\n /** @deprecated Use `this.context.appendToBlock(label, content)`. */\n appendContextBlock(label: string, content: string): Promise<ContextBlock> {\n return this.#context().appendToBlock(label, content);\n }\n\n /** @deprecated Use `this.context.freezeSystemPrompt()`. */\n freezeSystemPrompt(): Promise<string> {\n return this.#context().freezeSystemPrompt();\n }\n\n /** @deprecated Use `this.context.refreshSystemPrompt()`. */\n refreshSystemPrompt(): Promise<string> {\n return this.#context().refreshSystemPrompt();\n }\n\n /** @deprecated Use `this.context.tools()`. */\n tools(): Promise<ToolSet> {\n return this.#context().tools();\n }\n}\n\nfunction readOptions(\n leafIdOrOptions: string | null | HistoryReadOptions | undefined\n): HistoryReadOptions | undefined {\n if (leafIdOrOptions === undefined) return undefined;\n if (leafIdOrOptions === null || typeof leafIdOrOptions === \"string\") {\n return { leafId: leafIdOrOptions };\n }\n return leafIdOrOptions;\n}\n\nfunction appendOptions(\n parentIdOrOptions: string | null | AppendOptions | undefined\n): AppendOptions | undefined {\n if (parentIdOrOptions === undefined) return undefined;\n if (parentIdOrOptions === null || typeof parentIdOrOptions === \"string\") {\n return { parentId: parentIdOrOptions };\n }\n return parentIdOrOptions;\n}\n","/**\n * Aged-media eviction — a CONTEXT-WINDOW technique owned by Think.\n *\n * This is deliberately not how Sessions stores a message, and the two must\n * not be confused:\n *\n * - Row chunking is a STORAGE detail. A message too large for one SQLite\n * row is split across continuation rows and reassembled on read, byte\n * for byte. Invisible to the model and lossless.\n * - Media eviction is a CONTEXT decision. Once a screenshot has aged out\n * of the recent window, re-sending it on every turn is pure cost, so\n * Think removes it from the conversation and leaves a marker naming a\n * Workspace file. Visible to the model and lossy on purpose — the agent\n * reads the file back with the workspace `read` tool when it actually\n * needs the picture again.\n *\n * The bytes are written to the Workspace RAW (not as a `data:` URL string)\n * with their real mime type, so `read` recognises `image/*` and puts a real\n * image back into the model's context.\n *\n * Evicted values are:\n * - `file` parts whose `url` is a large `data:` URL — the part becomes a\n * text marker;\n * - large `data:` strings nested anywhere inside a tool part's `output`\n * (screenshots commonly arrive that way) — the string is replaced in\n * place so tool-specific `toModelOutput` handlers still work.\n *\n * Plain text parts are never evicted: they are the conversation itself.\n */\n\nimport type { UIMessage } from \"ai\";\n\n/** Nested tool-output walks stop here so hostile output cannot recurse forever. */\nconst MAX_WALK_DEPTH = 8;\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 window the model replays at\n * full fidelity, so a misconfigured low value can never strip content the\n * model still sees.\n * @default 8\n */\n keepRecentMessages?: number;\n /**\n * Minimum decoded payload size, in bytes, for a value to be evicted.\n * @default 32 * 1024\n */\n minPartBytes?: number;\n /**\n * Maximum stored rows processed per pass. Bounds how long a single pass\n * can take; remaining rows are picked up by the next pass.\n * @default 64\n */\n maxRowsPerPass?: number;\n /**\n * @deprecated Ignored. Evicted bytes are always preserved in the Workspace\n * under `/workspace/attachments/evicted/`; there is no drop-the-bytes mode. Accepted\n * so existing configurations keep compiling.\n */\n externalizeToWorkspace?: boolean;\n}\n\nexport interface ResolvedMediaEvictionConfig {\n keepRecentMessages: number;\n minPartBytes: number;\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 maxRowsPerPass: base.maxRowsPerPass ?? 64\n };\n}\n\n/**\n * The exact marker Think has always written. Old and new markers are\n * byte-identical, so a transcript evicted before and after the Sessions\n * replatform reads the same and old markers keep resolving.\n */\nexport function evictionMarker(\n bytes: number,\n path: string,\n mediaType?: string\n): string {\n const media = mediaType ? `${mediaType}, ` : \"\";\n return `[evicted ${media}${bytes} bytes; preserved at ${path}]`;\n}\n\nexport interface EvictMessageOptions {\n /** Minimum decoded payload size to evict. */\n minPartBytes: number;\n /**\n * Persist one payload and return the Workspace path it was written to.\n * `index` is the 0-based ordinal of the evicted value within the message.\n */\n write(\n index: number,\n bytes: Uint8Array,\n mediaType: string | undefined\n ): Promise<string>;\n}\n\nexport interface EvictMessageResult {\n /** Rewritten message, or the original reference when nothing was evicted. */\n message: UIMessage;\n changed: boolean;\n /** Individual values replaced by markers. */\n parts: number;\n /** Decoded payload bytes removed from the conversation. */\n bytes: number;\n}\n\ninterface WalkState {\n options: EvictMessageOptions;\n index: number;\n parts: number;\n bytes: number;\n}\n\n/**\n * Replace aged oversized media in one message with markers, writing the\n * bytes to the Workspace first. Returns a new message — the input is never\n * mutated, and nothing is written when nothing qualifies.\n */\nexport async function evictMediaFromMessage(\n message: UIMessage,\n options: EvictMessageOptions\n): Promise<EvictMessageResult> {\n const state: WalkState = { options, index: 0, parts: 0, bytes: 0 };\n let changed = false;\n const parts: UIMessage[\"parts\"] = [];\n\n for (const part of message.parts) {\n if (part.type === \"file\" && \"url\" in part) {\n const marker = await evictUrl(\n state,\n (part as { url: string }).url,\n (part as { mediaType?: string }).mediaType\n );\n if (marker !== null) {\n changed = true;\n parts.push({ type: \"text\", text: marker });\n continue;\n }\n parts.push(part);\n continue;\n }\n\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 rewritten = await walkAndEvict(state, output, 0);\n if (state.parts > before) {\n changed = true;\n parts.push({ ...part, output: rewritten } as UIMessage[\"parts\"][0]);\n continue;\n }\n }\n }\n\n parts.push(part);\n }\n\n return {\n message: changed ? { ...message, parts } : message,\n changed,\n parts: state.parts,\n bytes: state.bytes\n };\n}\n\n/**\n * Evict one stored payload locator. Returns its marker, or `null` when the\n * value is not an evictable payload or is below the size threshold.\n */\nasync function evictUrl(\n state: WalkState,\n url: unknown,\n fallbackMediaType?: string\n): Promise<string | null> {\n if (typeof url !== \"string\") return null;\n const payload = resolvePayload(state, url);\n if (!payload) return null;\n const mediaType = payload.mediaType ?? fallbackMediaType;\n const path = await state.options.write(state.index, payload.bytes, mediaType);\n state.index++;\n state.parts++;\n state.bytes += payload.bytes.byteLength;\n return evictionMarker(payload.bytes.byteLength, path, mediaType);\n}\n\n/**\n * A stored payload is always an inline `data:` URL now, so eviction decodes\n * it directly.\n */\nfunction resolvePayload(\n state: WalkState,\n url: string\n): { bytes: Uint8Array; mediaType?: string } | null {\n const { minPartBytes } = state.options;\n if (!url.startsWith(\"data:\")) return null;\n // A `data:` URL is always larger than its payload, so the cheap string\n // length rules out small values before any decoding happens.\n if (url.length < minPartBytes) return null;\n const decoded = decodeDataUrl(url);\n if (!decoded || decoded.bytes.byteLength < minPartBytes) return null;\n return decoded;\n}\n\nasync function walkAndEvict(\n state: WalkState,\n value: unknown,\n depth: number\n): Promise<unknown> {\n if (typeof value === \"string\") {\n return (await evictUrl(state, value)) ?? value;\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: unknown[] = [];\n for (const item of value) {\n const next = await walkAndEvict(state, item, depth + 1);\n if (next !== item) changed = true;\n result.push(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 = await walkAndEvict(state, entry, depth + 1);\n if (next !== entry) changed = true;\n result[key] = next;\n }\n return changed ? result : value;\n}\n\n/**\n * Whether a pass over `message` could evict anything: a file part or a tool\n * output holding a `data:` URL at least `minPartBytes` long. Decodes nothing —\n * this is the in-memory gate that decides whether a pass is worth scheduling,\n * so a decoded payload that turns out smaller than the threshold is merely a\n * pass that changes nothing.\n */\nexport function hasEvictableMedia(\n message: UIMessage,\n minPartBytes: number\n): boolean {\n const isCandidate = (value: unknown): boolean =>\n typeof value === \"string\" &&\n value.length >= minPartBytes &&\n value.startsWith(\"data:\");\n const walk = (value: unknown, depth: number): boolean => {\n if (isCandidate(value)) return true;\n if (\n value === null ||\n typeof value !== \"object\" ||\n depth >= MAX_WALK_DEPTH\n ) {\n return false;\n }\n const entries = Array.isArray(value) ? value : Object.values(value);\n return entries.some((entry) => walk(entry, depth + 1));\n };\n for (const part of message.parts) {\n if (part.type === \"file\" && \"url\" in part) {\n if (isCandidate((part as { url: unknown }).url)) return true;\n continue;\n }\n if (\n (part.type.startsWith(\"tool-\") || part.type === \"dynamic-tool\") &&\n \"output\" in part &&\n walk((part as { output?: unknown }).output, 0)\n ) {\n return true;\n }\n }\n return false;\n}\n\n/** Decode a `data:` URL into raw bytes. Returns null when it is malformed. */\nexport function decodeDataUrl(\n url: string\n): { bytes: Uint8Array; mediaType?: string } | null {\n const comma = url.indexOf(\",\");\n if (comma === -1) return null;\n const header = url.slice(\"data:\".length, comma);\n const base64 = /;base64$/i.test(header);\n const mediaType =\n header\n .replace(/;base64$/i, \"\")\n .split(\";\")[0]\n ?.trim() || undefined;\n const payload = url.slice(comma + 1);\n try {\n if (base64) {\n const binary = atob(payload);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return mediaType === undefined ? { bytes } : { bytes, mediaType };\n }\n const bytes = new TextEncoder().encode(decodeURIComponent(payload));\n return mediaType === undefined ? { bytes } : { bytes, mediaType };\n } catch {\n return null;\n }\n}\n\n/** File extension for an evicted payload, derived from its media type. */\nexport function 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\n/** Workspace path for the n-th value evicted from a message. */\nexport function evictedFilePath(\n messageId: string,\n index: number,\n mediaType: string | undefined\n): string {\n return `/workspace/attachments/evicted/${messageId}-${index}.${extensionFor(mediaType)}`;\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 holds one conversation in its own SQLite storage, backed by\n * Sessions — providing tree-structured messages, context blocks, compaction,\n * and FTS5 search.\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() — instructions at the top of the system prompt\n * - getTools() — return the ToolSet for the agentic loop\n * - maxSteps — max tool-call rounds per turn (default: 10)\n * - configureSession() — compaction and search policy\n * - configureContext() — declare prompt context blocks\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 { ContextConfig } from \"agents/context\";\n *\n * export class MemoryAgent extends Think<Env> {\n * getModel() { ... }\n *\n * configureContext(): ContextConfig[] {\n * return [\n * {\n * label: \"soul\",\n * provider: { get: async () => \"You are a helpful coding assistant.\" }\n * },\n * {\n * label: \"memory\",\n * description: \"Important facts learned during conversation.\",\n * maxTokens: 2000\n * }\n * ];\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 TextStreamPart,\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 \"./skills\";\nimport { formatSkillDiagnostic, loadSkillCatalog } from \"agents/skills\";\nimport { createSkillTools } from \"agents/skills/tools/ai-sdk\";\nimport type {\n SkillCatalog,\n SkillScriptRunner,\n SkillSource\n} 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 {\n Skill,\n SkillCatalog,\n SkillRunContext,\n SkillSource\n} from \"agents/skills\";\nimport {\n Agent,\n callable,\n getCurrentAgent,\n isDurableObjectCodeUpdateReset,\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 SubAgentClass,\n WSMessage\n} from \"agents\";\nimport {\n sanitizeMessage,\n enforceRowSizeLimit,\n StreamAccumulator,\n CHAT_MESSAGE_TYPES,\n TurnQueue,\n ResumableStream,\n createChatStreams,\n ContinuationState,\n PreStreamTurns,\n AutoContinuationController,\n TIMED_OUT,\n awaitWithDeadline,\n drainInteractionApplies,\n interceptAgentToolBroadcast,\n isPositionlessAgentToolChunk,\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 isLateToolInputChunk,\n lateToolInputForwardChunks,\n repairInterruptedToolParts,\n toolPartHasSettledResult,\n persistReconstructedOrphan,\n reconcileMessages,\n CHAT_RECOVERY_TASK_NAME,\n chatRecoveryTaskRunOptions,\n createChatRecoveryTaskDefinition,\n createChatTurnTaskDefinition,\n dispatchChatRecoveryToHandoff,\n createChatFiberSnapshot,\n unwrapChatFiberSnapshot,\n wrapChatFiberSnapshot,\n MAX_BOUND_PARAMS,\n buildInClauseStrings,\n resolveChatRecoveryConfig,\n ChatRecoveryEngine,\n runChatRecoveryExhaustion,\n chatRecoveryBackoffSeconds,\n retryAfterSeconds,\n isDurableObjectResetError,\n ChatStreamStalledError,\n iterateWithStallWatchdog,\n sweepStaleChatRecoveryIncidents,\n listActiveChatRecoveryIncidents,\n readChatRecoveryProgress,\n CHAT_RECOVERY_PROGRESS_KEY,\n recordChatTerminal,\n clearChatTerminal,\n pendingChatTerminal,\n originMessageIds,\n withOriginMessageIds,\n buildChatRecoveringFrame,\n setChatRecovering,\n AgentToolStreamProgressThrottle,\n classifyAgentToolChildRecovery,\n type ChatRecoveryAdapter,\n type ChatFiberWakeHooks,\n type ResolvedRecoveryStream,\n type ClassifyRecoveredTurnInput,\n type DispatchRecoveredTurnInput,\n type ChatRecoveryScheduleCallback,\n type ChatRecoveryTaskReason,\n CHAT_RECOVERY_INCIDENT_KEY_PREFIX,\n type ChatRecoveryIncident,\n type ChatRecoveryKind\n} from \"agents/chat\";\nimport type { Streams } from \"agents/streams\";\nimport { CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS } from \"agents/chat\";\nimport type {\n StreamChunkData,\n ClientToolSchema,\n ClientToolExecutor,\n MessagePart,\n SubmitConcurrencyDecision,\n ChatFiberSnapshot,\n ChatTurnOutcome,\n OrphanPersistStore\n} from \"agents/chat\";\nimport { truncateOlderMessages, truncateOlderToolResults } from \"agents/chat\";\nimport {\n Sessions,\n isCompactionMessage,\n type SessionMessage\n} from \"agents/sessions\";\nimport { ThinkSession } from \"./session\";\nimport {\n AgentContextProvider,\n ContextBlocks,\n type ContextConfig,\n type WritableContextProvider\n} from \"agents/context\";\n\n/**\n * The shortest recent-message span the model sees at FULL fidelity each turn\n * (see `_assembleModelMessages` and {@link MODEL_TRUNCATION_STEP}).\n *\n * Both memory bounds are anchored to this window (#1710):\n * - budgeted hydration (`hydrationByteBudget`) is a hard byte ceiling, so a\n * window of unusually large messages can be shorter than this; the model\n * then sees what fits rather than exhausting isolate memory;\n * - media eviction never rewrites messages above the stepped truncation\n * cutoff (see {@link mediaEvictionCutoff}), so the rows the model replays\n * at full fidelity are never stripped.\n */\nconst MODEL_RECENT_WINDOW = 4;\n\n/**\n * Default `truncationStep`. Read-time truncation cuts the history at a\n * multiple of this many messages,\n * so the full-fidelity span grows from `MODEL_RECENT_WINDOW` to\n * `MODEL_RECENT_WINDOW + MODEL_TRUNCATION_STEP - 1` messages between cuts.\n * Providers cache on a byte-identical prompt prefix, and a cutoff that moved\n * every turn rewrote a message near the end of that prefix on every turn\n * (#2200). Stepping it rewrites the prefix once per step instead.\n */\nconst MODEL_TRUNCATION_STEP = 8;\n\n/**\n * Drop the keys of a `start` chunk's metadata that the extended assistant\n * message already carries, so a recovery continuation re-running the metadata\n * writer cannot overwrite them (#2321).\n */\nfunction withoutOverwrittenStartMetadata(\n chunk: StreamChunkData,\n existing: unknown\n): StreamChunkData {\n if (\n chunk.type !== \"start\" ||\n existing === null ||\n typeof existing !== \"object\" ||\n chunk.messageMetadata === null ||\n typeof chunk.messageMetadata !== \"object\"\n ) {\n return chunk;\n }\n const messageMetadata = Object.fromEntries(\n Object.entries(chunk.messageMetadata).filter(\n ([key]) => !Object.prototype.hasOwnProperty.call(existing, key)\n )\n );\n return { ...chunk, messageMetadata };\n}\n\n/** Copy a turn context without reading its lazily resolved `model`. */\nfunction turnContextWithoutModel(ctx: TurnContext): Omit<TurnContext, \"model\"> {\n const { model: _model, ...descriptors } =\n Object.getOwnPropertyDescriptors(ctx);\n return Object.defineProperties({}, descriptors) as Omit<TurnContext, \"model\">;\n}\n\n/** `Infinity` never moves the cutoff; any other invalid step cuts every turn. */\nfunction truncationStepSize(step: number): number {\n if (step === Number.POSITIVE_INFINITY) return step;\n return Number.isFinite(step) ? Math.max(1, Math.floor(step)) : 1;\n}\n\nfunction truncationKeepRecent(messageCount: number, step: number): number {\n const safeStep = truncationStepSize(step);\n if (messageCount <= MODEL_RECENT_WINDOW) return MODEL_RECENT_WINDOW;\n if (safeStep === Number.POSITIVE_INFINITY) return messageCount;\n return (\n MODEL_RECENT_WINDOW + ((messageCount - MODEL_RECENT_WINDOW) % safeStep)\n );\n}\n\n/**\n * Index below which media eviction may rewrite messages: the stepped\n * truncation cutoff, moved back whole steps until at least\n * `keepRecentMessages` messages stay above it. It only moves when the\n * truncation cutoff does, so eviction rewrites the cached prompt prefix at\n * most once per step and never inside the full-fidelity window (#2356).\n * With stepping disabled (`truncationStep = Infinity`) there is no cutoff to\n * align with, and eviction keeps exactly `keepRecentMessages`.\n */\nfunction mediaEvictionCutoff(\n messageCount: number,\n keepRecentMessages: number,\n step: number\n): number {\n const keep = Math.max(keepRecentMessages, MODEL_RECENT_WINDOW);\n const safeStep = truncationStepSize(step);\n if (safeStep === Number.POSITIVE_INFINITY) {\n return Math.max(0, messageCount - keep);\n }\n const stepsBack = Math.ceil((keep - MODEL_RECENT_WINDOW) / safeStep);\n return Math.max(\n 0,\n messageCount -\n truncationKeepRecent(messageCount, safeStep) -\n stepsBack * safeStep\n );\n}\nconst DEFAULT_ACTION_TIMEOUT_MS = 30_000;\n\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 DEFERRED_RESOLVED_PAUSES_KEY = \"cf_think_deferred_resolved_pauses\";\nconst PENDING_RESPONSE_HOOK_PREFIX = \"cf_think_pending_response_hook:\";\nconst MESSENGER_RECOVERY_PREFIX = \"cf_think_messenger_recovery:\";\n\n/**\n * A messenger reply this agent owes after chat recovery settles, keyed by the\n * recovery incident. `outcome` is set once the incident settles, so a reset\n * between settling and posting re-delivers on the next start.\n */\ntype MessengerRecoveryDelivery = {\n messengerId: string;\n threadId: string;\n partialText: string;\n outcome?: \"completed\" | \"interrupted\";\n text?: string;\n /**\n * Posts of the reply already attempted. Advanced before each post, so a\n * reset mid-post resumes after it rather than posting it twice.\n */\n posted?: number;\n};\n\nconst MESSENGER_RECOVERY_RETRY_CALLBACK = \"_cfRetryMessengerRecoveryDelivery\";\nconst MESSENGER_RECOVERY_MAX_RETRIES = 8;\n\nconst WORKERS_AI_MODEL_PREFIXES = [\"@cf/\", \"@hf/\"];\n\nfunction isWorkersAIModelId(model: string): boolean {\n return WORKERS_AI_MODEL_PREFIXES.some(\n (prefix) => model.startsWith(prefix) && model.length > prefix.length\n );\n}\n\nfunction messageText(message: UIMessage | undefined): string {\n return (message?.parts ?? [])\n .filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n .map((p) => p.text)\n .join(\"\");\n}\n\nfunction settleMessengerRecoveryDelivery(\n delivery: MessengerRecoveryDelivery,\n outcome: \"completed\" | \"interrupted\",\n text?: string\n): MessengerRecoveryDelivery {\n if (outcome !== \"completed\") return { ...delivery, outcome };\n const recovered = text ?? \"\";\n return {\n ...delivery,\n outcome,\n text: recovered.startsWith(delivery.partialText)\n ? recovered.slice(delivery.partialText.length)\n : recovered\n };\n}\n\ntype PendingResponseHook = {\n requestId: string;\n messageId: string;\n continuation: boolean;\n status: ChatResponseResult[\"status\"];\n error?: string;\n};\n\n/**\n * Carries an in-stream error that `classifyChatError` marked transient out of\n * the drain loop, so it reaches the same recovery routing as a thrown error.\n * `original` is the provider error the stream reported, when it had one.\n */\nclass TransientChatStreamError extends Error {\n constructor(\n message: string,\n readonly classification: ChatErrorClassification,\n readonly original: unknown\n ) {\n super(message);\n this.name = \"TransientChatStreamError\";\n }\n}\n\n/** A live stream interruption (stall or transient error) to route to recovery. */\ntype StreamInterruptionRoute = {\n requestId: string;\n streamId: string;\n partialParts: MessagePart[];\n persistPartial: () => Promise<string | undefined>;\n /** The user message a regeneration answers as a new sibling branch. */\n branchParentId?: string;\n /** Delay the continuation with exponential backoff (transient errors). */\n backoff?: boolean;\n /** Provider `Retry-After` (rate limits); extends the backoff delay. */\n retryAfterSeconds?: number;\n};\n\ntype ResolvedPauseOutcome = { executionId: string; output: unknown };\n\nfunction isPausedToolPart(part: Record<string, unknown>): boolean {\n const output = part.output as { status?: unknown } | null | undefined;\n return (\n part.state === \"output-available\" &&\n output != null &&\n typeof output === \"object\" &&\n output.status === \"paused\"\n );\n}\n\nfunction ownsPausedToolCall(message: UIMessage, toolCallId: string): boolean {\n return (message.parts as unknown as Array<Record<string, unknown>>).some(\n (part) => part.toolCallId === toolCallId && isPausedToolPart(part)\n );\n}\n\n/** The tool call id of a part whose output carries `executionId`, if any. */\nfunction executionToolCallIn(\n message: UIMessage,\n executionId: string,\n pausedOnly: boolean\n): string | null {\n if (message.role !== \"assistant\") return null;\n for (const part of message.parts as unknown as Array<\n Record<string, unknown>\n >) {\n if (part.state !== \"output-available\") continue;\n if (typeof part.toolCallId !== \"string\") continue;\n const output = part.output as\n | { status?: unknown; executionId?: unknown }\n | null\n | undefined;\n if (\n output != null &&\n typeof output === \"object\" &&\n (!pausedOnly || output.status === \"paused\") &&\n output.executionId === executionId\n ) {\n return part.toolCallId;\n }\n }\n return null;\n}\n\n/**\n * A client that missed a pause's resolution resubmits its part still paused,\n * and reconciliation protects server results only from pre-output client\n * states. Keep the server's resolved part, and drop the pending-state text\n * after it as the resolution did.\n *\n * Providers may reuse a toolCallId across turns, so the resolution is taken\n * only from the server row the message reconciled to; a pause still pending\n * there stays pending. A resolution on any other row can belong to another\n * turn.\n */\nfunction keepResolvedPauses(\n incoming: UIMessage[],\n serverMessages: readonly UIMessage[]\n): UIMessage[] {\n type Part = UIMessage[\"parts\"][number];\n const resolvedByMessage = new Map<string, Map<string, Part>>();\n for (const message of serverMessages) {\n if (message.role !== \"assistant\") continue;\n for (const part of message.parts) {\n const record = part as Record<string, unknown>;\n if (\n typeof record.toolCallId === \"string\" &&\n (record.state === \"output-available\" ||\n record.state === \"output-error\" ||\n record.state === \"output-denied\") &&\n !isPausedToolPart(record)\n ) {\n let own = resolvedByMessage.get(message.id);\n if (!own) {\n own = new Map();\n resolvedByMessage.set(message.id, own);\n }\n own.set(record.toolCallId, part);\n }\n }\n }\n if (resolvedByMessage.size === 0) return incoming;\n\n return incoming.map((message) => {\n if (message.role !== \"assistant\") return message;\n const own = resolvedByMessage.get(message.id);\n if (!own) return message;\n const stale = new Map<string, Part>();\n for (const part of message.parts) {\n const record = part as Record<string, unknown>;\n if (typeof record.toolCallId !== \"string\" || !isPausedToolPart(record)) {\n continue;\n }\n const server = own.get(record.toolCallId);\n if (server) stale.set(record.toolCallId, server);\n }\n if (stale.size === 0) return message;\n let parts = message.parts;\n for (const [toolCallId, server] of stale) {\n parts = dropGenerationAfterToolCall(\n parts.map((part) =>\n \"toolCallId\" in part && part.toolCallId === toolCallId ? server : part\n ),\n toolCallId\n );\n }\n return { ...message, parts };\n });\n}\n/**\n * Whether a workspace is a Computer `Workspace` this agent owns, as opposed\n * to a client for one another Durable Object owns. Checked by shape so a\n * second copy of `@cloudflare/computer` in the bundle still matches.\n */\nfunction isLocalWorkspace(\n workspace: ThinkWorkspace\n): workspace is ThinkWorkspace & Pick<Workspace, \"ready\" | \"stub\"> {\n return (\n \"ready\" in workspace &&\n typeof workspace.ready === \"function\" &&\n \"stub\" in workspace &&\n typeof workspace.stub === \"function\"\n );\n}\n\n/** Context block label for the skills catalog. */\nconst SKILLS_CONTEXT_LABEL = \"think_skills\";\n\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, type WorkspaceStub } from \"@cloudflare/computer\";\nimport { createAITools } from \"@cloudflare/computer/tools/ai-sdk\";\nimport {\n WorkspaceFiles,\n resolveWorkspacePath,\n type ThinkWorkspace\n} from \"./workspace-files\";\nimport {\n evictMediaFromMessage,\n evictedFilePath,\n resolveMediaEvictionConfig,\n type MediaEvictionConfig,\n hasEvictableMedia\n} from \"./media-eviction\";\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 {\n DEFAULT_MESSENGER_CONCURRENCY,\n MESSENGER_REPLY_FIBER_NAME\n} from \"./messengers\";\nimport type {\n DeliveryKind,\n MessengerConcurrency,\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 { ThinkSession, ThinkSession as Session } from \"./session\";\nexport type {\n CompactAfterOptions,\n CompactionErrorHandler,\n SessionContextOptions\n} from \"./session\";\nexport type { SessionMessage } from \"agents/sessions\";\nexport type { FiberContext, FiberRecoveryContext } from \"agents\";\nexport type {\n ThinkWorkspace,\n ThinkWorkspaceFilesystem\n} from \"./workspace-files\";\n\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 * A recovery continuation opens its own text and reasoning parts, and an end\n * chunk only closes the newest part of its type, so a part the interruption\n * left streaming would never be closed.\n */\nfunction settleInterruptedPart(part: UIMessage[\"parts\"][number]) {\n return (part.type === \"text\" || part.type === \"reasoning\") &&\n part.state === \"streaming\"\n ? { ...part, state: \"done\" as const }\n : part;\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\n// findZonedInstant calls getZonedParts once per minute across a 28-hour\n// window, so building a formatter per call dominated the CPU cost of resolving\n// a wall-clock occurrence. Formatters are stateless, so keep one per timezone.\n// The map holds at most one entry per distinct timezone, and an invalid\n// timezone throws before anything is cached.\nconst zonedPartsFormatters = new Map<string, Intl.DateTimeFormat>();\n\nfunction getZonedPartsFormatter(timezone: string): Intl.DateTimeFormat {\n let formatter = zonedPartsFormatters.get(timezone);\n if (!formatter) {\n formatter = 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 });\n zonedPartsFormatters.set(timezone, formatter);\n }\n return formatter;\n}\n\nfunction getZonedParts(date: Date, timezone: string): ZonedParts {\n const parts = getZonedPartsFormatter(timezone).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 /**\n * Set when the interrupted turn regenerated `targetUserId`: the leaf the new\n * response branches beside. The retry answers `targetUserId` as a sibling\n * branch, and only while this is still the leaf.\n */\n regeneratedLeafId?: string;\n originalRequestId?: string;\n incidentId?: string;\n originMessageIds?: 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 originMessageIds?: string[];\n lastBody?: Record<string, unknown> | null;\n lastClientTools?: ClientToolSchema[] | null;\n recoveredRequestId?: string;\n};\n\n/**\n * Think's chat fiber snapshot. `branchParentId` is set for a regeneration: the\n * user message the turn answers as a new sibling branch.\n */\ntype ThinkChatFiberSnapshot = ChatFiberSnapshot<\"think-chat-turn\"> & {\n branchParentId?: string;\n};\n\nfunction regenerationParentOf(\n snapshot: ChatFiberSnapshot | null\n): string | undefined {\n const parentId = (snapshot as ThinkChatFiberSnapshot | null)?.branchParentId;\n return typeof parentId === \"string\" ? parentId : undefined;\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 monotonic forward-progress marker the recovery budget keys off is\n// derived from the stream log (`ResumableStream.progressMarker`): durably\n// flushed segments, folded into a retired total as their rows are deleted.\n// Nothing is written per chunk. The pre-derivation KV counter\n// (`CHAT_RECOVERY_PROGRESS_KEY`) is read once per isolate and seeded into the\n// marker, so it is never read lower than an in-flight incident recorded.\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// 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/**\n * Carry a context reminder (`ContextBlocks.reminder()`) after the cached\n * prefix without persisting it. It joins the final user message when there is\n * one, since not every provider accepts two user messages in a row. A request\n * ending in a partial assistant message gets the continue checkpoint here,\n * carrying the reminder, so `ensureValidContinueCheckpoint` adds nothing.\n */\nfunction withContextReminder(\n messages: ModelMessage[],\n reminder: string | null\n): ModelMessage[] {\n if (!reminder || messages.length === 0) return messages;\n const part = { type: \"text\" as const, text: reminder };\n const lastIndex = messages.length - 1;\n const last = messages[lastIndex];\n if (last.role === \"user\") {\n const content =\n typeof last.content === \"string\"\n ? [{ type: \"text\" as const, text: last.content }, part]\n : [...last.content, part];\n return [...messages.slice(0, lastIndex), { ...last, content }];\n }\n const content =\n last.role === \"assistant\"\n ? [{ type: \"text\" as const, text: CONTINUE_CHECKPOINT_PROMPT }, part]\n : [part];\n return [...messages, { role: \"user\", content }];\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 * `info.deliversRecoveredReply` is true when the interrupted turn was a\n * messenger turn and this agent will post the recovered answer (or the\n * interrupted apology, if recovery gives up) to the messenger thread itself.\n */\n onInterrupted?(info?: ChatInterruptedInfo): void | Promise<void>;\n}\n\nexport interface ChatInterruptedInfo {\n deliversRecoveredReply?: boolean;\n}\n\n/**\n * Produces server-authored assistant-message metadata from AI SDK stream parts.\n * Forwarded to the AI SDK `toUIMessageStream` so a Think turn can stamp\n * structured metadata onto the assistant message it persists. Called for every\n * stream part; use `part.type` to choose when to return metadata (`start` and\n * `finish` are the conventional points). Each non-`undefined` return is\n * shallow-merged into the message's metadata. The return value is broadcast to\n * clients and persisted, so it must be\n * JSON-serializable and must not carry server-only secrets.\n *\n * `continuation` is true when the turn continues an earlier one (a recovery\n * continuation or an auto-continue after a tool result). A recovery\n * continuation streams into the interrupted assistant message, so its `start`\n * part cannot overwrite keys that message already has: a `createdAt` stamped\n * on the original `start` survives. Keys the continuation's `start` adds, and\n * everything from later parts, merge as usual.\n *\n * The `Metadata` parameter defaults to the opaque `Record<string, unknown>` used\n * everywhere metadata rides today; it is the seam a future typed-metadata story\n * (issue #1676) narrows without a breaking change.\n */\nexport type MessageMetadataCallback<\n Metadata extends Record<string, unknown> = Record<string, unknown>\n> = (options: {\n part: TextStreamPart<ToolSet>;\n continuation: boolean;\n}) => Metadata | undefined;\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. Omit it to\n * run without a channel context. (WebSocket chat turns always run on the\n * 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 /** Persisted assistant produced by this completed turn; absent otherwise. */\n message?: SessionMessage;\n /**\n * Parsed structured output when the turn's `TurnConfig.output` produced\n * one. A structured output that fails to parse ends the turn with\n * `status: \"error\"`.\n */\n output?: unknown;\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 RejectExecutionOptions {\n /**\n * Whether Think starts a model continuation after recording the rejection.\n * Defaults to `true`. Set this to `false` when the caller wants the\n * conversation to remain paused until a later user turn.\n */\n autoContinue?: boolean;\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\n/** What admitted a turn. Exposed on {@link ActiveTurn} and {@link TurnContext}. */\nexport type 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 /**\n * Ignore `channel` and extend the previous turn's channel, resolved when the\n * turn starts rather than when it is admitted, so it sees turns queued\n * ahead of it.\n */\n inheritChannel?: boolean;\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// A messenger turn waits in the turn queue before it runs, and a concurrent\n// messenger turn can be admitted meanwhile, so the context has to travel with\n// the call chain rather than sit on the instance.\nconst messengerTurnContext = new AsyncLocalStorage<{\n agent: unknown;\n context: MessengerContext;\n ended: boolean;\n}>();\n\n// Recovery acceptance belongs to the successor's async call chain, including\n// pre-admission awaits and time spent in the turn queue. Concurrent turns on\n// the same agent must not claim its handoff to a durable root chat Task.\nconst recoveredTurnAcceptanceContext = new AsyncLocalStorage<{\n agent: unknown;\n onAccepted: (successorRequestId: string) => void;\n workflowPrompt?: ThinkWorkflowPromptContext;\n}>();\n\n// A `runTurn` continuation dispatched through an overridden `continueLastTurn`:\n// the base method, when the override delegates to it, records the full result\n// (with structured output) for that `runTurn` call alone.\nfunction isTransientClassification(\n classification: ChatErrorClassification | undefined\n): classification is \"transient\" | \"rate_limit\" {\n return classification === \"transient\" || classification === \"rate_limit\";\n}\n\nconst continuationOutputContext = new AsyncLocalStorage<{\n agent: unknown;\n taken: boolean;\n result?: ProgrammaticMessagesResult;\n}>();\n\n// A `runTurn({ mode: \"wait\" })` call records the assistant message each turn\n// persists, keyed by that turn's request ID. The context travels through the\n// turn queue and inherited async work, so keying (not a single slot) keeps a\n// later turn in the same context — e.g. an overridden `continueLastTurn` that\n// runs another `saveMessages` — from replacing this turn's answer.\nconst waitTurnResultContext = new AsyncLocalStorage<{\n agent: unknown;\n messageIds: Map<string, string>;\n}>();\n\n// Marks code running inside `onSubmissionStatus`. The emit holds a terminal\n// submission's waiters until the hook returns, and runs inside the turn that\n// finalized it, so a wait from the hook can never settle.\nconst submissionStatusHookContext = new AsyncLocalStorage<{\n agent: unknown;\n ended: boolean;\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/** Queue callback that delivers one terminal-submission workflow event. */\nconst WORKFLOW_NOTIFICATION_CALLBACK = \"_cfDeliverWorkflowNotification\";\n/**\n * A workflow notification never retries in-process: a failed delivery\n * schedules its own retry with backoff (see `_cfDeliverWorkflowNotification`)\n * so the alarm loop is not held while a workflow is unreachable.\n */\nconst WORKFLOW_NOTIFICATION_RETRY: RetryOptions = { maxAttempts: 1 };\n/** Longest wait between two delivery attempts of one workflow notification. */\nconst WORKFLOW_NOTIFICATION_MAX_BACKOFF_SECONDS = 10 * 60;\n/**\n * How long delivery of one workflow notification keeps being retried after\n * its first failure. Long enough to ride out an outage of the workflow\n * binding; a target still failing after this is treated as permanently\n * unreachable rather than waking the object every ten minutes forever.\n */\nconst WORKFLOW_NOTIFICATION_GIVE_UP_MS = 12 * 60 * 60 * 1000;\n/** Queue callback that runs one connection-less continuation turn. */\nconst CONNECTIONLESS_CONTINUATION_CALLBACK = \"_cfRunConnectionlessContinuation\";\nconst CONNECTIONLESS_CONTINUATION_QUEUE_ID = \"connectionless-continuation\";\n/** Queue callback that runs one media-eviction pass. */\nconst MEDIA_EVICTION_CALLBACK = \"_cfEvictAgedMedia\";\n/** Queue callback that runs one pending submission. */\nconst SUBMISSION_RUN_CALLBACK = \"_cfRunSubmission\";\n\nfunction workflowNotificationItemId(\n submissionId: string,\n eventType: string\n): string {\n return `workflow-notification:${submissionId}:${eventType}`;\n}\n\nfunction submissionRunItemId(submissionId: string): string {\n return `submission:${submissionId}`;\n}\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\nconst cachedMessageEncoder = new TextEncoder();\n\n/**\n * A cached message's size in the unit the hydration budget is measured in:\n * UTF-8 bytes of its serialized form, not UTF-16 code units.\n */\nfunction cachedMessageBytes(message: UIMessage): number {\n return cachedMessageEncoder.encode(JSON.stringify(message)).byteLength;\n}\n\nfunction reservedMetadataOf(\n message: UIMessage\n): Record<string, unknown> | undefined {\n const metadata = message.metadata;\n if (\n typeof metadata !== \"object\" ||\n metadata === null ||\n Array.isArray(metadata)\n ) {\n return undefined;\n }\n const reserved: Record<string, unknown> = {};\n for (const key of RESERVED_MESSAGE_METADATA_KEYS) {\n if (key in metadata) {\n reserved[key] = (metadata as Record<string, unknown>)[key];\n }\n }\n return Object.keys(reserved).length > 0 ? reserved : undefined;\n}\n\n/**\n * `parts` without the text and reasoning that follow the part for\n * `toolCallId`, up to the end of the step that read its output: the rest of\n * the tool call's own step and the next one. Later steps answer other tool\n * results and are kept. Returns `parts` itself when nothing is dropped.\n */\nfunction dropGenerationAfterToolCall(\n parts: UIMessage[\"parts\"],\n toolCallId: string\n): UIMessage[\"parts\"] {\n const index = parts.findIndex(\n (part) => \"toolCallId\" in part && part.toolCallId === toolCallId\n );\n if (index === -1) return parts;\n let end = parts.length;\n let stepStarts = 0;\n for (let i = index + 1; i < parts.length; i++) {\n if (parts[i].type === \"step-start\" && ++stepStarts === 2) {\n end = i;\n break;\n }\n }\n const kept = parts.filter(\n (part, i) =>\n i <= index ||\n i >= end ||\n (part.type !== \"text\" && part.type !== \"reasoning\")\n );\n return kept.length === parts.length ? parts : kept;\n}\n\n/**\n * The stored form of a client-sourced message's metadata: Sessions drops the\n * reserved keys on every client write, so a compare against a stored row has\n * to drop them too. Mirrors `SessionCore.stripReservedMetadata` for the keys\n * Think registers.\n */\nfunction stripReservedMetadata(message: UIMessage): UIMessage {\n const metadata = message.metadata;\n if (\n typeof metadata !== \"object\" ||\n metadata === null ||\n Array.isArray(metadata)\n ) {\n return message;\n }\n const remaining: Record<string, unknown> = { ...metadata };\n let changed = false;\n for (const key of RESERVED_MESSAGE_METADATA_KEYS) {\n if (key in remaining) {\n delete remaining[key];\n changed = true;\n }\n }\n if (!changed) return message;\n if (Object.keys(remaining).length > 0) {\n return { ...message, metadata: remaining };\n }\n const { metadata: _dropped, ...withoutMetadata } = message;\n return withoutMetadata as UIMessage;\n}\n\n/** Stable id prefix for fallback notes that preserve orphaned execution outcomes. */\nconst EXECUTION_OUTCOME_MESSAGE_PREFIX = \"exec-outcome-\";\n\n/**\n * Present framework-authored execution outcome notes to providers as user\n * context. Think persists these notes as system messages so clients and\n * recovery do not mistake them for human input, but AI SDK v7 and strict\n * providers reject system messages in arbitrary transcript\n * positions. The provider-only projection leaves current and legacy session\n * history unchanged.\n */\nfunction toProviderSafeExecutionOutcomeMessage(message: UIMessage): UIMessage {\n return message.role === \"system\" &&\n message.id.startsWith(EXECUTION_OUTCOME_MESSAGE_PREFIX)\n ? { ...message, role: \"user\" }\n : message;\n}\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 /** Id of the assistant message this submission's turn persisted. */\n messageId?: string;\n};\n\nexport type SubmitMessagesResult = ThinkSubmissionInspection & {\n accepted: boolean;\n};\n\nexport type WaitForSubmissionOptions = {\n /**\n * Stop waiting after this many milliseconds and return the submission as it\n * is then, still `pending` or `running`, or `null` if it was deleted.\n */\n timeoutMs?: number;\n};\n\n/** What {@link Think.cancelSubmission} did. */\nexport type CancelSubmissionResult =\n | {\n /** No submission has this id. */\n outcome: \"not_found\";\n submissionId: string;\n }\n | {\n /** The submission had already finished; nothing changed. */\n outcome: \"already_terminal\";\n submissionId: string;\n submission: ThinkSubmissionInspection;\n }\n | {\n /** The submission is now `aborted`. */\n outcome: \"cancelled\";\n submissionId: string;\n /**\n * `\"pending\"`: removed before its turn started. `\"running\"`: its turn\n * had been claimed and was signalled to abort; side effects already\n * under way may still finish.\n */\n previousStatus: \"pending\" | \"running\";\n /**\n * Whether any of the submission's messages were written to the\n * conversation when it was cancelled. A claimed submission can still be\n * `false` when it is cancelled before its turn applies them.\n */\n messagesApplied: boolean;\n submission: ThinkSubmissionInspection;\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\n/** A turn's durable cutover fact, not the stream transport's lifecycle. */\ntype SubmissionTurnResult =\n | { status: \"completed\"; output?: unknown }\n | { status: \"aborted\" | \"retry\" | \"error\" };\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 result_status: SubmissionTurnResult[\"status\"] | null;\n output_json: string | null;\n message_id: string | null;\n};\n\n/** Payload of one queued workflow notification. */\ntype WorkflowNotificationPayload = {\n workflowName: string;\n workflowId: string;\n event: { type: string; payload: unknown };\n /** Failed deliveries so far; drives the retry backoff. */\n attempts?: number;\n /** Epoch ms of the first failed delivery; bounds the retry window. */\n firstFailedAt?: number;\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: an overridden `getSystemPrompt()`, then context blocks. */\n system: string;\n /**\n * Assembled model messages (truncated, pruned). When a `whenChanged:\n * \"remind\"` context block has changed since the prompt froze, its current\n * value rides at the end, inside the last user message when there is one.\n */\n messages: ModelMessage[];\n /** Merged tool set (workspace + getTools + session + MCP + client + caller). */\n tools: ToolSet;\n /**\n * The language model from getModel(), resolved on first read — a\n * `beforeTurn` that returns its own `model` without reading this never\n * resolves the default.\n */\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 * The request this turn runs for: the same id `beforePersist`,\n * `onChatResponse` and `onChatError` see. Undefined for inference that runs\n * outside an admitted turn.\n */\n requestId?: string;\n /** What admitted this turn. Undefined outside an admitted turn. */\n trigger?: TurnTrigger;\n /**\n * Aborts when the turn is cancelled. Pass it to any I/O `beforeTurn` awaits\n * so a stopped turn does not wait for it to finish.\n */\n abortSignal?: AbortSignal;\n /**\n * The messenger thread this turn answers, fixed when the turn was admitted.\n * Unlike {@link Think.getMessengerContext}, it never falls back to another\n * turn's message.\n */\n messenger?: MessengerContext;\n}\n\n/**\n * The turn currently running on this agent. See {@link Think.activeTurn}.\n */\nexport interface ActiveTurn {\n /** Request id shared by every hook, tool call and event of this turn. */\n requestId: string;\n trigger: TurnTrigger;\n continuation: boolean;\n /** Channel the turn resolved to, when it has one. */\n channel?: string;\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 * Produces server-authored assistant-message metadata for this turn — the\n * write path that lets a turn attach structured metadata (e.g. a `createdAt`\n * timestamp) to the assistant message Think persists, matching the AI SDK\n * `messageMetadata` callback base `AIChatAgent` + `streamText` already accept.\n * Overrides the instance-level {@link Think.messageMetadata} for this turn.\n * Configure from a Think subclass; sandboxed extensions cannot send functions\n * over RPC. See {@link MessageMetadataCallback} for when it is called and the\n * serialization constraints on its return value.\n */\n messageMetadata?: MessageMetadataCallback;\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 * Repairs tool calls that the AI SDK cannot parse or validate before tool\n * execution. The returned tool call is parsed and validated again. Configure\n * this function from a Think subclass; sandboxed extensions cannot send\n * functions over RPC.\n *\n * Typed via the `experimental_repairToolCall` key, which exists in both AI\n * SDK v6 and v7 (`repairToolCall` is v7-only), so this type resolves under\n * either supported major.\n */\n repairToolCall?: Parameters<\n typeof streamText\n >[0][\"experimental_repairToolCall\"];\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 * Think compacts and retries when `contextOverflow.reactive` is enabled.\n * - `rate_limit` / `transient` — a stream error worth retrying (a 429, a\n * dropped connection). Think routes the turn into bounded chat recovery, like\n * a stream stall, and schedules the continuation with exponential backoff.\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 * `true` when the failed turn was a server-started continuation (for\n * example after a tool approval or a client tool result) rather than a\n * turn a client or caller submitted.\n */\n continuation?: 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 * Request id of the turn making this call, matching `TurnContext.requestId`\n * and `onChatResponse`. Undefined outside an admitted turn.\n */\n readonly requestId?: string;\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 /** Request id of the turn that made this call; see `ToolCallContext`. */\n readonly requestId?: string;\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\n/**\n * Definition name for messenger reply runs on the Tasks capability. The\n * reserved prefix keeps it outside the public `fibers.run()` surface; the\n * recovery context still carries the historical `MESSENGER_REPLY_FIBER_NAME`\n * so the messenger runtime's recovery gate is unchanged.\n */\nconst MESSENGER_REPLY_TASK_DEFINITION = \"__cf_internal_messenger_reply\";\n\n// Agent wraps subclass methods during super(), copying inherited methods onto\n// the concrete prototype. Snapshot the chain first so later checks see user\n// declarations rather than framework-installed wrappers.\nconst declaredPrototypeMembers = new WeakMap<\n object,\n ReadonlySet<PropertyKey>\n>();\n\nfunction snapshotDeclaredMembers(prototype: object): void {\n for (\n let current: object | null = prototype;\n current && current !== Think.prototype;\n current = Object.getPrototypeOf(current) as object | null\n ) {\n if (!declaredPrototypeMembers.has(current)) {\n declaredPrototypeMembers.set(current, new Set(Reflect.ownKeys(current)));\n }\n }\n}\n\nfunction isMethodOverridden(instance: object, methodName: string): boolean {\n // Agent's auto-wrapper writes to the concrete prototype, not the instance;\n // an own member here is a subclass class-field override initialized later.\n if (Object.prototype.hasOwnProperty.call(instance, methodName)) return true;\n\n for (\n let current: object | null = Object.getPrototypeOf(instance) as object;\n current && current !== Think.prototype;\n current = Object.getPrototypeOf(current) as object | null\n ) {\n if (declaredPrototypeMembers.get(current)?.has(methodName)) return true;\n }\n return false;\n}\n\nexport class Think<\n Env extends Cloudflare.Env = Cloudflare.Env,\n State = unknown,\n Props extends object = object\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 * The originating user message ids of the active recovery chain (#2280),\n * carried in the recovery payload because the successor turn runs under a\n * fresh request id. Scoped to the recovery callback's async context, so a\n * concurrent client request never inherits them.\n */\n private _chatRecoveryOriginIdsScope = new AsyncLocalStorage<\n string[] | undefined\n >();\n\n private get _activeChatRecoveryOriginIds(): string[] | undefined {\n return this._chatRecoveryOriginIdsScope.getStore();\n }\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 _skillSources: readonly SkillSource[] = [];\n private _skillCatalog: SkillCatalog | 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 * How the Chat SDK handles messages that arrive in a messenger thread while\n * the agent is still answering, or before it starts. Accepts any Chat SDK\n * `concurrency` value: `\"queue\"`, `\"debounce\"`, `\"burst\"`, `\"concurrent\"`,\n * `\"drop\"`, or a `ConcurrencyConfig`. One setting covers every messenger on\n * the agent. Set it as a class field: it is read before `onStart` runs.\n *\n * @default { strategy: \"burst\", debounceMs: 600 }\n */\n messengerConcurrency: MessengerConcurrency = DEFAULT_MESSENGER_CONCURRENCY;\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 budget counts what hydration actually costs: a row's stored bytes\n * plus the attachment bytes its pointers inflate back when reconstructed\n * inline. A pointer row is therefore charged its payload, not its ~100\n * stored bytes, so the ceiling bounds isolate memory rather than the\n * on-disk footprint. Set to `Number.POSITIVE_INFINITY` (or any\n * non-positive value) to disable windowing and always hydrate the full\n * transcript.\n *\n * Once the transcript exceeds the budget, the hydrated window's start\n * slides forward as messages are added, which rewrites the start of the\n * prompt and defeats provider prompt caching (and the step alignment of\n * `truncationStep`) until the transcript fits again.\n *\n * @default 32 * 1024 * 1024\n */\n hydrationByteBudget: number = 32 * 1024 * 1024;\n\n /**\n * Aged-media eviction — a CONTEXT-WINDOW technique, not a storage setting.\n *\n * Once media has aged past `keepRecentMessages` on the active path, Think\n * removes it from the conversation so the model stops re-reading a large\n * image on every turn, and leaves a marker naming a Workspace file under\n * `/attachments/evicted/`. The bytes are written raw with their real mime\n * type, so the agent can read the picture back with the workspace `read`\n * tool when it deliberately needs it again. Visible to the model and lossy\n * on purpose.\n *\n * This is separate from Sessions attachment storage, which is invisible\n * and lossless: a large payload may be held as an `attachment:sha256:`\n * pointer whether eviction is on or off.\n *\n * `false` keeps aged media in the conversation, so the model keeps seeing\n * it. It does NOT change where Sessions keeps the bytes.\n *\n * Eviction only rewrites messages below the stepped read-time truncation\n * cutoff (see `truncationStep`), moved back whole steps until at least\n * `keepRecentMessages` messages stay above it. It therefore never rewrites\n * a message the model still replays at full fidelity, and it changes the\n * cached prompt prefix at most once per truncation step rather than every\n * turn. The media of up to `keepRecentMessages + truncationStep - 1`\n * recent messages can stay in context.\n *\n * @default true\n */\n mediaEviction: MediaEvictionConfig | boolean = true;\n\n /**\n * Durable chat recovery configuration. Every chat turn runs in `runFiber`,\n * enabling `onChatRecovery` and `this.stash()` during streaming. Assign an\n * object to tune recovery budgets and terminal behavior.\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 /** Durable conversation history installed on this Agent's Lifecycle. */\n readonly sessions = new Sessions({\n reservedMetadataKeys: RESERVED_MESSAGE_METADATA_KEYS\n });\n\n /**\n * The default conversation handle configured by `configureSession()`.\n * Storage lives on the `agents/sessions` handle it wraps; the context\n * methods it still carries forward to {@link Think.context}.\n */\n session!: ThinkSession;\n\n /** Prompt context blocks for this agent, built from `configureContext()`. */\n #contextBlocks: ContextBlocks | undefined;\n\n /**\n * The agent's context blocks. Available once the Lifecycle has started.\n */\n protected get context(): ContextBlocks {\n if (!this.#contextBlocks) {\n throw new Error(\n \"Context is not initialized yet; it is available after onStart().\"\n );\n }\n return this.#contextBlocks;\n }\n\n /** Durable SQLite storage for one context block of this agent. */\n #contextProvider(label: string): WritableContextProvider {\n const sessionId = this.session?.sessionId ?? \"\";\n return new AgentContextProvider(\n this,\n sessionId ? `${label}_${sessionId}` : label\n );\n }\n\n /** Cached messages, kept in sync with session storage. */\n private _cachedMessages: UIMessage[] = [];\n private _unsubscribeSessionChanges: (() => void) | undefined;\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 /**\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 * Channel of the latest queue turn that ran inference, which a continuation\n * without an explicit channel extends. Cleared by `resetTurnState`. Differs from the latest user message's\n * channel when a WebSocket regeneration reuses a message another channel\n * stored, or a continuation ran on an explicit channel. In memory only:\n * after an eviction, continuations fall back to history.\n */\n private _lastTurnChannel?: { channel: string | undefined };\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 * The agent's Workspace, available in `getTools()` and lifecycle hooks.\n * Defaults to a `Workspace` from `@cloudflare/computer` on this Durable\n * Object's storage, with no execution backends.\n *\n * Override it as a class field to add backends, mounts, or git, or to\n * work in a Workspace another Durable Object owns:\n *\n * ```typescript\n * import { Workspace, type WorkspaceStub } from \"@cloudflare/computer\";\nimport { createAITools } from \"@cloudflare/computer/tools/ai-sdk\";\n *\n * override workspace = new Workspace({\n * storage: this.ctx.storage,\n * backends: [...]\n * });\n *\n * // A Workspace owned by a parent Durable Object.\n * override workspace = await getWorkspace(parentStub);\n * ```\n */\n workspace!: ThinkWorkspace;\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 * 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 snapshotDeclaredMembers(new.target.prototype);\n super(ctx, env);\n\n this.lifecycle.use(this.sessions);\n this.lifecycle.use(this.streams);\n this._registerChatTurnTaskDefinition();\n this._registerChatRecoveryTaskDefinition();\n this._registerMessengerReplyTaskDefinition();\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({ storage: this.ctx.storage });\n }\n\n // 2. Session configuration (builder phase: compaction, and the\n // pre-Sessions `withContext()` chain, folded into the blocks\n // `configureContext()` declares).\n this.session = await this.configureSession(\n new ThinkSession(this.sessions.session(), () => this.context)\n );\n this.#contextBlocks = new ContextBlocks(\n [\n ...(await this.configureContext()),\n ...this.session.internal_takePendingContext()\n ],\n this.session.internal_promptStore() ??\n this.#contextProvider(\"_system_prompt\"),\n (label) => this.#contextProvider(label)\n );\n // Load blocks now rather than on the first turn, as Think always\n // has: the synchronous accessors (`this.context.getBlock()` and the\n // pre-Sessions `session.getContextBlock()`) are expected to answer\n // as soon as the object has started.\n await this.#contextBlocks.load();\n this._unsubscribeSessionChanges?.();\n this._unsubscribeSessionChanges = this.sessions\n .session(this.session.sessionId)\n .mirror<UIMessage>({\n get: () => this._cachedMessages,\n set: (messages) => {\n this._replaceCachedMessages(messages);\n },\n transform: (message) => message as UIMessage,\n intercept: async (event) => {\n switch (event.type) {\n case \"append\":\n // A branch append moves the path itself, which no\n // in-place patch expresses.\n if (event.inserted && event.parentId === undefined) {\n return false;\n }\n await this._syncMessages();\n return true;\n case \"import\":\n // A row the cache never saw. Re-derive at the next safe\n // boundary instead of mirroring a migration row by row.\n this._cacheCoversActivePath = false;\n return true;\n case \"clear\":\n this._replaceCachedMessages([]);\n this._cacheCoversActivePath = true;\n return true;\n case \"compaction\":\n case \"delete\":\n await this._syncMessages();\n return true;\n case \"compact\":\n await this._syncMessages();\n await this.#contextBlocks?.refreshSystemPrompt();\n return true;\n default:\n return false;\n }\n },\n onApplied: (event, message, previous) => {\n if (event.type === \"update\") {\n if (previous) this._noteCachedReplacement(previous, message);\n return;\n }\n // A linear append is what ages older messages, so this is\n // where an eviction pass becomes worth scheduling; the gate\n // decides from memory. It also grows the cache past what the\n // last refresh measured.\n this._noteCachedGrowth(cachedMessageBytes(message));\n if (this._mediaEvictionFruitless) {\n this._mediaEvictionFruitless.appendsSince++;\n }\n if (this._mediaEvictionRunning) {\n this._mediaEvictionAppendsDuringPass++;\n }\n this._scheduleMediaEvictionPass();\n }\n });\n\n await this._initializeSkills();\n }\n );\n\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 }\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(\n this.streams,\n this.sql.bind(this),\n {\n // Rollback insurance: a build still on the KV counter reads a\n // marker no lower than one recorded under the derived marker.\n // One put per stream retired, none per chunk.\n onProgress: (durable) => {\n void this.ctx.storage\n .put(CHAT_RECOVERY_PROGRESS_KEY, durable)\n .catch(() => {});\n }\n }\n );\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._migrateLegacyWorkflowNotifications();\n await this._replayPendingResponseHooks();\n await this._replayMessengerRecoveryDeliveries();\n await this._recoverSubmissionsOnStart();\n },\n \"Pending submissions / workflow notifications were not recovered on \" +\n \"this wake; the next successful wake will recover them.\"\n )\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. Its caller, message reconciliation, must see\n * every message: it diffs incoming client messages against the complete\n * server transcript, so a windowed read would drop rows and corrupt the\n * result. It is reached only when the live cache does not already cover the\n * path (`_serverTranscriptForReconcile`); tool-update application resolves\n * its one target row without it (`_resolveToolCallOwner`).\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 * It also receives an approved call that never ran (state still\n * `approval-responded`) once a later turn moves past it without a\n * continuation executing it.\n */\n protected repairInterruptedToolPart(\n part: UIMessage[\"parts\"][number]\n ): UIMessage[\"parts\"][number] {\n return {\n ...part,\n state: \"output-error\",\n errorText:\n (part as { state?: string }).state === \"approval-responded\"\n ? \"The tool call was approved but did not run before the next turn started.\"\n : \"The tool call was interrupted before a result was recorded.\"\n } as UIMessage[\"parts\"][number];\n }\n\n /**\n * Whether the inference being prepared may repair `approval-responded`\n * parts: it is not a continuation, and no continuation is waiting to run\n * them.\n */\n private _repairApprovalRespondedThisTurn = false;\n\n private async _mayRepairApprovalResponded(\n continuation: boolean\n ): Promise<boolean> {\n if (continuation) return false;\n if (this._continuation.pending || this._continuation.deferred) {\n return false;\n }\n return (\n (await this.getQueue(CONNECTIONLESS_CONTINUATION_QUEUE_ID)) === undefined\n );\n }\n\n private _repairToolTranscriptParts(\n messages: UIMessage[],\n options: { repairApprovalResponded?: boolean } = {}\n ): {\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 repairApprovalResponded: options.repairApprovalResponded\n });\n }\n\n private async _repairTranscriptForProvider(\n messages: UIMessage[]\n ): Promise<UIMessage[]> {\n const repair = this._repairToolTranscriptParts(messages, {\n repairApprovalResponded: this._repairApprovalRespondedThisTurn\n });\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(message);\n }\n }\n\n // `messages` can be a cut or off-cache path, so merge by id rather than\n // replacing the cache with it.\n const repairedById = new Map(\n repair.messages.map((message) => [message.id, message])\n );\n this._replaceCachedMessages(\n this.messages.map((message) => repairedById.get(message.id) ?? message)\n );\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 /**\n * A request that arrived while a pass was running. That pass read its\n * candidates before the request's append landed, so the request is kept\n * and re-evaluated once the pass ends rather than dropped.\n */\n private _mediaEvictionPending = false;\n /**\n * Linear appends that landed while a pass was running. The pass read its\n * candidates before them, so a fruitless result records them as appends\n * since — not zero — and the request they left pending can pass the gate.\n */\n private _mediaEvictionAppendsDuringPass = 0;\n /**\n * The last pass that found nothing to evict while aged rows were hidden\n * from the cache: the stored size it saw, and how many linear appends have\n * landed since. Until either changes enough, another pass would scan the\n * same rows to the same answer. A refresh that measures a different size\n * re-arms it, and so do `keepRecentMessages` appends: that is what it takes\n * for a row the pass had to protect to age into a candidate. An update\n * that grows a cached row clears it outright (`_patchCachedMessage`).\n */\n private _mediaEvictionFruitless: {\n storedBytes: number;\n appendsSince: number;\n } | null = null;\n\n /**\n * Whether the cache can stand in for the stored path when deciding if an\n * eviction pass is worth running. It cannot when the hydration is a window\n * of the path, or when a compaction overlay collapses rows the pass would\n * still read and rewrite.\n */\n private _agedRowsHiddenFromCache(): boolean {\n return (\n this._lastHydration?.truncated === true ||\n this._cachedMessages.some((message) =>\n isCompactionMessage(message as SessionMessage)\n )\n );\n }\n\n /**\n * Queue a bounded media-eviction pass (see `mediaEviction`).\n *\n * The pass is one queue item with a stable id, so repeated requests\n * coalesce and the pass runs from the alarm loop, never inside the\n * request or the `blockConcurrencyWhile` cache refresh that asked for it.\n * A request that lands while a pass is running is re-evaluated once the\n * pass ends, so media aged by an append during the pass is not left until\n * the next one. `_evictAgedMediaBestEffort` swallows its own failures, so\n * a bad pass can never brick the object.\n */\n private _scheduleMediaEvictionPass(): void {\n if (this._mediaEvictionRunning) {\n this._mediaEvictionPending = true;\n return;\n }\n const config = resolveMediaEvictionConfig(this.mediaEviction);\n if (!config) return;\n // Decide from memory whether a pass could evict anything, so a pass is\n // not the way to find out: its first act is a content-free scan of the\n // whole stored path, and this runs after every cache refresh and every\n // linear append.\n //\n // When the cache holds every aged row, it is the same rows the pass\n // would read, so a pass is scheduled only when an aged cached message\n // still carries an inline payload. When it does not — a windowed\n // hydration, or rows hidden under a compaction overlay — a pass is\n // scheduled once per distinct stored size, since until the bytes change\n // it would scan the same rows to the same answer.\n const keepRecent = Math.max(config.keepRecentMessages, MODEL_RECENT_WINDOW);\n if (this._agedRowsHiddenFromCache()) {\n const fruitless = this._mediaEvictionFruitless;\n if (\n fruitless !== null &&\n this._lastHydration !== null &&\n fruitless.storedBytes === this._lastHydration.totalContentBytes &&\n fruitless.appendsSince < keepRecent\n ) {\n return;\n }\n } else {\n const aged = this._cachedMessages.slice(\n 0,\n mediaEvictionCutoff(\n this._cachedMessages.length,\n config.keepRecentMessages,\n this.truncationStep\n )\n );\n if (\n !aged.some((message) => hasEvictableMedia(message, config.minPartBytes))\n ) {\n return;\n }\n }\n void this.queue(MEDIA_EVICTION_CALLBACK, undefined, {\n id: \"media-eviction\"\n }).catch((error) => {\n console.error(\"[Think] Failed to queue media eviction pass\", error);\n });\n }\n\n /**\n * Run one media-eviction pass.\n * @internal Queue callback.\n */\n async _cfEvictAgedMedia(): Promise<void> {\n await this._evictAgedMediaBestEffort();\n }\n\n /**\n * Remove aged media from the conversation, leaving a Workspace pointer the\n * agent can read back.\n *\n * Memory-bounded by design: candidate sizes come from `getHistoryRowStats()`\n * (no content loaded), only rows big enough to hold an evictable payload are\n * read, and they are processed one at a time. Bytes are written to the\n * Workspace BEFORE the row is rewritten, so a failed pass never loses data;\n * once the rewritten row is stored, its Sessions attachment reference is\n * gone and the blob is reaped, so the bytes live in exactly one place.\n *\n * The aged cutoff is {@link mediaEvictionCutoff}: the stepped truncation\n * cutoff, kept at least `keepRecentMessages` back. Messages the model still\n * replays at full fidelity are never rewritten, whatever the configuration\n * says, and the cutoff moves only once per truncation step.\n *\n * Best-effort: failures are logged and the next pass retries. When a pass\n * stops at `maxRowsPerPass` having made progress, the next one is scheduled\n * so a backlog drains on its own; a pass that changed nothing does not\n * reschedule, which is what guarantees termination.\n */\n protected async _evictAgedMediaBestEffort(): Promise<{\n messages: number;\n parts: number;\n bytes: number;\n backlogRemains: boolean;\n } | null> {\n if (this._mediaEvictionRunning) return null;\n const config = resolveMediaEvictionConfig(this.mediaEviction);\n if (!config) return null;\n this._mediaEvictionRunning = true;\n this._mediaEvictionAppendsDuringPass = 0;\n const totals = {\n messages: 0,\n parts: 0,\n bytes: 0,\n backlogRemains: false\n };\n try {\n const files = new WorkspaceFiles(this.workspace);\n const stats = await this.session.getHistoryRowStats();\n const aged = stats.slice(\n 0,\n mediaEvictionCutoff(\n stats.length,\n config.keepRecentMessages,\n this.truncationStep\n )\n );\n\n let processed = 0;\n for (const row of aged) {\n // The stored row is not large enough to hold an evictable payload —\n // skip without reading it. A rewritten row drops below this line and\n // is skipped by every later pass.\n if (row.bytes < config.minPartBytes) continue;\n if (processed >= config.maxRowsPerPass) {\n totals.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 = await evictMediaFromMessage(message, {\n minPartBytes: config.minPartBytes,\n write: async (index, bytes, mediaType) => {\n const path = evictedFilePath(message.id, index, mediaType);\n await files.write(path, bytes);\n return path;\n }\n });\n if (!result.changed) continue;\n\n // The rewritten row no longer carries the payload, so the bytes now\n // exist only as the Workspace file.\n await this._updateMessageInHistory(result.message);\n totals.messages++;\n totals.parts += result.parts;\n totals.bytes += result.bytes;\n }\n\n if (totals.messages > 0) {\n this._mediaEvictionFruitless = null;\n this._emit(\"chat:media:evicted\", {\n messages: totals.messages,\n parts: totals.parts,\n bytes: totals.bytes,\n externalizedBytes: totals.bytes\n });\n } else if (this._agedRowsHiddenFromCache() && this._lastHydration) {\n this._mediaEvictionFruitless = {\n storedBytes: this._lastHydration.totalContentBytes,\n appendsSince: this._mediaEvictionAppendsDuringPass\n };\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 // Only chain when this pass actually shrank something: a pass that\n // changed nothing would otherwise reschedule itself forever.\n if (totals.backlogRemains && totals.messages > 0) {\n this._scheduleMediaEvictionPass();\n }\n // A request that landed mid-pass goes back through the gate now, so\n // media aged by an append during this pass is not left until the\n // next one. The gate, not the request, decides whether a pass runs.\n if (this._mediaEvictionPending) {\n this._mediaEvictionPending = false;\n this._scheduleMediaEvictionPass();\n }\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 * `true` while `this.messages` holds every message on the active path.\n * That is the common case: the default `hydrationByteBudget` admits whole\n * transcripts, and the Sessions change feed patches the cache after every\n * durable write. Set by `_syncMessages()`; `false` when the last refresh\n * was windowed, failed, or has not run yet. Readers that need the complete\n * path — reconciliation, tool-update lookups — consult it to decide whether\n * the cache can answer or storage must be read.\n */\n private _cacheCoversActivePath = false;\n\n /**\n * Serialized bytes the cache has grown by since the last refresh — new\n * messages and updates that enlarged existing ones, measured as UTF-8 the\n * way the budget is. The hydration budget was measured at that refresh;\n * once the growth since would carry the cache past it, the cache stops\n * claiming to cover the path, so the next boundary re-reads storage and\n * re-windows (#1710).\n */\n private _cachedBytesSinceSync = 0;\n\n private _noteCachedGrowth(bytes: number): void {\n const budget = this.hydrationByteBudget;\n if (\n bytes <= 0 ||\n !Number.isFinite(budget) ||\n budget <= 0 ||\n !this._lastHydration\n ) {\n return;\n }\n this._cachedBytesSinceSync += bytes;\n if (\n this._lastHydration.totalContentBytes + this._cachedBytesSinceSync >\n budget\n ) {\n this._cacheCoversActivePath = false;\n }\n }\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 * budget is a hard ceiling with no message-count floor beneath it — a floor\n * that admitted rows regardless of size would defeat the bound it sits\n * under. A window of unusually large messages can therefore be shorter than\n * `MODEL_RECENT_WINDOW`; `getHistory()` still reads the full path.\n */\n private async _syncMessages(): Promise<UIMessage[]> {\n // A refresh that throws leaves the cache unreliable until the next one.\n this._cacheCoversActivePath = false;\n this._cachedBytesSinceSync = 0;\n const budget = this.hydrationByteBudget;\n if (!Number.isFinite(budget) || budget <= 0) {\n this._lastHydration = null;\n this._lastWindowedEmit = null;\n const full = this._replaceCachedMessages(\n await this._readMessagesFromStorage()\n );\n this._cacheCoversActivePath = true;\n this._scheduleMediaEvictionPass();\n return full;\n }\n\n const recent = await this.session.getRecentHistory(budget);\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 const hydrated = this._replaceCachedMessages(\n recent.messages as UIMessage[]\n );\n this._cacheCoversActivePath = !recent.truncated;\n this._scheduleMediaEvictionPass();\n return hydrated;\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) return;\n const previous = this._cachedMessages[index];\n this._cachedMessages[index] = message;\n this._noteCachedReplacement(previous, message);\n }\n\n /**\n * An update that enlarges a cached message (a tool result landing on it)\n * grows the cache exactly as an append does, so it is charged against the\n * hydration budget the same way; and it may have put an inline payload on\n * an aged row, so a fruitless eviction pass no longer stands.\n */\n private _noteCachedReplacement(previous: UIMessage, next: UIMessage): void {\n const grew = cachedMessageBytes(next) - cachedMessageBytes(previous);\n if (grew > 0) {\n this._noteCachedGrowth(grew);\n this._mediaEvictionFruitless = null;\n }\n }\n\n private async _appendMessageToHistory(\n message: UIMessage,\n parentId?: string | null\n ): Promise<UIMessage> {\n const result = await this.session.appendMessage(message, { parentId });\n return result.message as UIMessage;\n }\n\n private async _updateMessageInHistory(\n message: UIMessage\n ): Promise<UIMessage> {\n // `null` means the row is gone (a concurrent clear or delete). Keep the\n // caller's copy so the live cache stays coherent.\n return ((await this.session.updateMessage(message)) ??\n message) as UIMessage;\n }\n\n private async _upsertMessageInHistory(\n message: UIMessage,\n parentId?: string | null,\n source: \"client\" | \"server\" = \"server\"\n ): Promise<UIMessage> {\n const result = await this.session.upsertMessage(message, {\n parentId,\n source\n });\n return result.message as UIMessage;\n }\n\n /** Session-backed orphan persistence with Think's default branch. */\n protected _orphanStore(): OrphanPersistStore {\n return {\n getMessage: async (id) =>\n (await this.session.getMessage(id)) as UIMessage | null,\n appendMessage: async (message, parentId) => {\n await this.session.appendMessage(message, { parentId });\n },\n updateMessage: async (message) => {\n await this.session.updateMessage(message);\n }\n };\n }\n\n private async _clearHistory(): Promise<void> {\n await this.session.clearMessages();\n // The transcript carried the skill-load record, so a cleared session\n // starts with no skills loaded and a prompt rebuilt without them.\n await this.#contextBlocks?.refreshSystemPrompt();\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 /**\n * The Streams capability backing `_resumableStream`: chat's in-flight\n * output lives in the shared durable chunk log, readable by any\n * `streams.read()` consumer on this Durable Object.\n */\n readonly streams: Streams = createChatStreams();\n\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 // Resolved pauses, by tool call id, whose outcome write or generation drop\n // may not have landed: the outcome is being written, or its own turn was\n // still streaming. See `_dropGenerationAfterResolvedPause`. Mirrored in\n // storage with the outcome so both survive a restart before the next turn;\n // loaded once per isolate.\n private _deferredResolvedPauses = new Map<string, ResolvedPauseOutcome>();\n private _deferredResolvedPausesLoad: Promise<void> | undefined;\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 /** Runs started with `eventDelivery: \"terminal\"`: their chunks are not broadcast. */\n private _agentToolTerminalOnlyRuns = new Set<string>();\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 _declaredScheduledTasksTableEnsured = false;\n private _warnedFacetScheduledTasksDisarmed = false;\n private _actionLedgerTableEnsured = false;\n private _actionPendingTableEnsured = false;\n private _submissionAbortControllers = new Map<string, AbortController>();\n private _submissionsApplyingMessages = new Set<string>();\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 this._agentToolTerminalOnlyRuns.size > 0\n ) {\n const chunkRunId = interceptAgentToolBroadcast(msg, {\n forwarders: this._agentToolForwarders,\n liveSequences: this._agentToolLiveSequences,\n lastErrors: this._agentToolLastErrors,\n onError: (runId, body) => this._recordAgentToolStreamError(runId, body),\n responseType: MSG_CHAT_RESPONSE,\n runForRequest: (requestId) => this._agentToolRunForRequest(requestId),\n terminalOnlyRuns: this._agentToolTerminalOnlyRuns\n });\n if (\n chunkRunId !== null &&\n this._agentToolTerminalOnlyRuns.has(chunkRunId)\n ) {\n return;\n }\n }\n super.broadcast(msg, without);\n }\n\n /**\n * Durably record a run's stream error on its still-open child-run row, so a\n * stale-row reconcile after an eviction (before the finalizer seals `error`)\n * still sees the failure. Leaves `status` to the finalizer / reconcile.\n */\n private _recordAgentToolStreamError(runId: string, body: string): void {\n try {\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET error_message = ${body}\n WHERE run_id = ${runId} AND completed_at IS NULL\n `;\n } catch {\n // Best-effort: broadcast must never throw; the in-memory capture remains.\n }\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; event_delivery: string | null }>`\n SELECT run_id, event_delivery 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 if (runId && rows[0]?.event_delivery === \"terminal\") {\n this._agentToolTerminalOnlyRuns.add(runId);\n }\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 → no-op (the table is not created).\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 // No child-run table on facets that never ran as an agent tool; don't\n // create one. An existing table may predate newer columns (a fresh isolate\n // after upgrade recovers before any other child-run access), so migrate it.\n const tables = this.sql<{ name: string }>`\n SELECT name FROM sqlite_master\n WHERE type = 'table' AND name = 'cf_agent_tool_child_runs'\n `;\n if (tables.length === 0) return;\n this._ensureAgentToolChildRunTable();\n const rows = this.sql<{ run_id: string; event_delivery: string | null }>`\n SELECT run_id, event_delivery FROM cf_agent_tool_child_runs\n WHERE status IN ('starting', 'running')\n ORDER BY started_at DESC\n LIMIT 1\n `;\n const runId = rows[0]?.run_id;\n const terminalOnly = rows[0]?.event_delivery === \"terminal\";\n if (!runId) return;\n if (terminalOnly) this._agentToolTerminalOnlyRuns.add(runId);\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 // ── 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 legacy = this.ctx.storage.sql\n .exec(\n `SELECT name FROM sqlite_master\n WHERE type = 'table'\n AND name IN ('assistant_config', 'assistant_config__lifted_v1')`\n )\n .toArray()\n .map((row) => String(row.name));\n // Sessions leaves `assistant_config` alone; these keys are Think's, so\n // Think lifts them into its own table and drops the source.\n const source = legacy.includes(\"assistant_config\")\n ? \"assistant_config\"\n : legacy.includes(\"assistant_config__lifted_v1\")\n ? \"assistant_config__lifted_v1\"\n : null;\n if (!source) return;\n\n for (const key of Think.CONFIG_KEYS) {\n const rows =\n source === \"assistant_config\"\n ? this.sql<{ value: string }>`\n SELECT value FROM assistant_config\n WHERE session_id = '' AND key = ${key}\n `\n : this.sql<{ value: string }>`\n SELECT value FROM assistant_config__lifted_v1\n WHERE session_id = '' AND key = ${key}\n `;\n const value = rows[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 // Config is a handful of small rows and every key Think reads now lives in\n // think_config, so the source has nothing left to give.\n this.ctx.storage.sql.exec(`DROP TABLE ${source}`);\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 /**\n * Last value each `think_config` key was seen to hold in this isolate.\n * Only this object writes the table, so a write whose value matches is a\n * no-op and skips the row — the request body and client-tool schemas are\n * re-persisted on every chat request and rarely change.\n */\n readonly #configMemo = new Map<string, string | undefined>();\n\n private _configSet(key: string, value: string): void {\n this._ensureConfigTable();\n if (this.#configMemo.get(key) === value) return;\n this.sql`\n INSERT OR REPLACE INTO think_config (key, value)\n VALUES (${key}, ${value})\n `;\n this.#configMemo.set(key, value);\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 const value = rows[0]?.value;\n this.#configMemo.set(key, value);\n return value;\n }\n\n private _configDelete(key: string): void {\n this._ensureConfigTable();\n if (this.#configMemo.has(key) && this.#configMemo.get(key) === undefined) {\n return;\n }\n this.sql`\n DELETE FROM think_config\n WHERE key = ${key}\n `;\n this.#configMemo.set(key, undefined);\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 * Return AI Gateway options for a string model resolved by the default\n * provider. Called on every {@link resolveModel} call: once per turn for the\n * default model (skipped when `beforeTurn` returns its own `model` without\n * reading `ctx.model`), plus once for each string `model` override returned\n * from `beforeTurn` or `beforeStep`. It can read {@link activeTurn}, the\n * messenger context, or agent state. Use it to pick a gateway `id` and to\n * attach `metadata`, which AI Gateway records on the request log as\n * `cf-aig-metadata`. It must return synchronously; a returned Promise is\n * rejected with an error.\n *\n * Defaults to `undefined`: catalog slugs use the account's `default`\n * gateway, and `@cf/...` ids call Workers AI without a gateway. Not called\n * for a model that is already a `LanguageModel`.\n */\n getGateway(_model: string): GatewayOptions | undefined {\n return undefined;\n }\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 // The provider sends every `@...` id straight to `env.AI.run(model)`, so a\n // malformed one would only fail at inference time.\n const isWorkersAI = isWorkersAIModelId(model);\n const slash = model.indexOf(\"/\");\n if (\n !isWorkersAI &&\n (model.startsWith(\"@\") || slash <= 0 || slash === model.length - 1)\n ) {\n throw new Error(\n `Invalid model id ${JSON.stringify(model)}. Use a Workers AI id ` +\n '(e.g. \"@cf/moonshotai/kimi-k2.7-code\") or a \"<provider>/<model>\" ' +\n 'AI Gateway slug (e.g. \"openai/gpt-5.5\"), or return a LanguageModel.'\n );\n }\n const gateway = this.getGateway(model);\n if (\n gateway !== null &&\n typeof gateway === \"object\" &&\n typeof (gateway as { then?: unknown }).then === \"function\"\n ) {\n throw new Error(\n `getGateway() returned a Promise for model \"${model}\". It must return ` +\n \"GatewayOptions (or undefined) synchronously; resolve any async \" +\n \"lookup in beforeTurn and return the model from there instead.\"\n );\n }\n this._defaultProvider ??= createWorkersAI({\n binding: this.getAIBinding(),\n providers: [openai, anthropic]\n });\n // Workers AI 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 other per-call settings, which avoids forcing\n // options a given provider/transport would reject.\n return isWorkersAI\n ? this._defaultProvider(model, {\n sessionAffinity: this.sessionAffinity,\n ...(gateway && { gateway })\n })\n : this._defaultProvider(model, gateway && { gateway });\n }\n\n /**\n * Return the instructions at the top of the system prompt.\n *\n * An override always comes first, followed by the context blocks from\n * `configureContext()`, skills, and extensions. Think's default text is\n * used only when the agent overrides nothing and has no context blocks.\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 /**\n * The base system prompt for a turn: an overridden `getSystemPrompt()`,\n * then the frozen context blocks. Think's default `getSystemPrompt()` is\n * only a fallback for an agent with no context blocks.\n *\n * @internal Exposed to subclasses for tests.\n */\n protected async _buildBaseSystemPrompt(): Promise<string> {\n const blocks = await this.context.freezeSystemPrompt();\n if (!isMethodOverridden(this, \"getSystemPrompt\")) {\n return blocks || this.getSystemPrompt();\n }\n return [this.getSystemPrompt(), blocks]\n .filter((part) => part.trim().length > 0)\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 const active = this._activeMessengerContext();\n if (active) {\n return active;\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 private _activeMessengerContext(): MessengerContext | undefined {\n const store = messengerTurnContext.getStore();\n return store?.agent === this && !store.ended ? store.context : undefined;\n }\n\n async chatWithMessengerContext(\n userMessage: string | UIMessage,\n callback: StreamCallback,\n context: MessengerContext,\n options?: ChatOptions\n ): Promise<void> {\n // Async work the turn leaves behind keeps this store, so it is marked\n // ended rather than trusted to go out of scope.\n const store = { agent: this, context, ended: false };\n try {\n await messengerTurnContext.run(store, () =>\n this.chat(userMessage, callback, {\n ...options,\n channel: context.messengerId\n })\n );\n } finally {\n store.ended = true;\n }\n }\n\n /**\n * The turn currently running on this agent, readable from `beforeTurn`,\n * `beforeToolCall`, tool `execute`, `onChatResponse` and anything they call.\n * Undefined outside a turn, including from code a turn scheduled to run\n * later.\n */\n get activeTurn(): ActiveTurn | undefined {\n const turn = this._activeAdmittedTurn();\n if (!turn) return undefined;\n return {\n requestId: turn.requestId,\n trigger: turn.trigger,\n continuation: turn.continuation ?? false,\n ...(turn.channel !== undefined && { channel: turn.channel })\n };\n }\n\n /** The admitted-turn store of the turn running now, if the caller is in it. */\n private _activeAdmittedTurn() {\n const turn = admittedTurnContext.getStore();\n if (!turn || turn.agent !== this) return undefined;\n // The store outlives the turn in any async work the turn scheduled.\n if (this._turnQueue.activeRequestId !== turn.requestId) return undefined;\n return turn;\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 * Undefined outside a turn, like {@link activeTurn} — including from work a\n * turn left behind that runs while a later turn holds another channel.\n */\n get activeChannel(): ChannelContext | undefined {\n const turn = this._activeAdmittedTurn();\n const context = this._activeChannelContext;\n return turn && context?.channelId === turn.channel ? context : undefined;\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 private _channelForAutoContinuation(): string | undefined {\n return this._lastTurnChannel\n ? this._lastTurnChannel.channel\n : this._channelFromLatestUserMessage();\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 * Post a recovered messenger reply, or the interrupted apology, to a thread.\n * Called by a conversation sub-agent (or this agent) once chat recovery of\n * an interrupted messenger turn settles; only the host holds the messenger\n * runtime (#2106).\n *\n * @internal\n */\n async _cf_deliverRecoveredMessengerReply(input: {\n messengerId: string;\n threadId: string;\n outcome: \"completed\" | \"interrupted\";\n text?: string;\n partialPosted?: boolean;\n chunk: number;\n }): Promise<{ chunks: number }> {\n if (!this._messengerRuntime) {\n throw new Error(\n `Cannot deliver a recovered reply for messenger \"${input.messengerId}\": this agent has no messenger runtime`\n );\n }\n return this._messengerRuntime.deliverRecoveredReply(input);\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.activeChannel?.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 { concurrency: this.messengerConcurrency }\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 * Return which instances of this class arm the declared scheduled tasks.\n *\n * `\"root\"` (the default) arms them only on the top-level agent. Because\n * `getScheduledTasks()` is usually a static code declaration, it returns the\n * same tasks on every instance — so without this scope an agent that also\n * has sub-agents would arm one private copy per live facet and dispatch each\n * occurrence once per facet on top of the root (#1877).\n *\n * Return `\"all\"` to arm on facets as well. That is only correct when\n * `getScheduledTasks()` genuinely varies per facet (for example when it\n * reads per-facet state), since each facet then owns an independent\n * schedule.\n *\n * The value must be stable across wakes. Reporting `\"root\"` on a facet that\n * previously armed cancels its occurrences, so a scope that flickers with\n * request-scoped or not-yet-loaded state will repeatedly tear down and\n * re-create that facet's schedule.\n */\n getScheduledTasksScope(): \"root\" | \"all\" | Promise<\"root\" | \"all\"> {\n return \"root\";\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 /**\n * Live chat-turn closures keyed by run nonce. A closure exists only in the\n * isolate that accepted the turn; recovery after interruption never re-runs\n * it — the definition's `recover` callback hands the interruption to the\n * shared ChatRecoveryEngine instead.\n */\n /**\n * Start time and latest `stash()` data of each chat turn running in this\n * isolate, keyed by request id. A stream stall is recovered while the turn is\n * still live, so `onChatRecovery` reads these instead of a fiber snapshot.\n */\n private readonly _liveChatRecoveryTurns = new Map<\n string,\n { createdAt: number; recoveryData: unknown }\n >();\n\n private readonly _liveChatTurnClosures = new Map<\n string,\n {\n initial: unknown;\n wrap: (data: unknown) => unknown;\n run: () => Promise<unknown>;\n settle: {\n resolve: (value: unknown) => void;\n reject: (error: unknown) => void;\n };\n }\n >();\n\n /**\n * Register the shared chat-turn Task definition (see\n * `agents/chat` `createChatTurnTaskDefinition` for the turn logic): the\n * host wires its protected internals through the hooks.\n */\n private _registerChatTurnTaskDefinition(): void {\n const chatFiberName = (this.constructor as typeof Think).CHAT_FIBER_NAME;\n this.tasks.register(\n chatFiberName,\n createChatTurnTaskDefinition({\n definitionName: chatFiberName,\n storage: this.ctx.storage,\n getRunCreatedAt: async (runId) =>\n (await this.tasks.get(runId))?.createdAt ?? null,\n getLiveClosure: (nonce) => this._liveChatTurnClosures.get(nonce),\n keepAliveWhile: (fn) => this.keepAliveWhile(fn),\n withStash: (context, fn) => this._withFiberStash(context, fn),\n handleRecovery: (ctx) => this._handleInternalFiberRecovery(ctx)\n })\n );\n }\n\n /** Register the shared Tasks transport for recovery continuations. */\n private _registerChatRecoveryTaskDefinition(): void {\n // SAFETY: the recovery engine is the sole producer of each callback's\n // payload and the Task persists it verbatim, so the callback name selects\n // the matching host input type.\n this.tasks.register(\n CHAT_RECOVERY_TASK_NAME,\n createChatRecoveryTaskDefinition({\n _chatRecoveryContinue: (data) =>\n this._chatRecoveryContinue(data as ChatRecoveryContinueData),\n _chatRecoveryRetry: (data) =>\n this._chatRecoveryRetry(data as ChatRecoveryRetryData)\n })\n );\n }\n\n /**\n * Run a queue-driven recovery callback to its model handoff and return;\n * the turn continues as tracked alarm work, and a detached platform\n * failure enqueues one replacement attempt through the same transport.\n */\n private _dispatchChatRecovery(\n callback: ChatRecoveryScheduleCallback,\n data: Record<string, unknown> | undefined,\n detached: (onTurnStarted: () => void) => Promise<void>\n ): Promise<void> {\n return dispatchChatRecoveryToHandoff({\n // Each run is one attempt under the interruption budget: it counts an\n // earlier attempt that died and records itself before any heavy work.\n detached: (onTurnStarted) =>\n this._chatRecoveryEngine().runRecoveryAttempt({\n callback,\n data,\n run: () => detached(onTurnStarted)\n }),\n track: (turn) => this.lifecycle.trackAlarmWork(turn),\n redefer: (dedupeKey) =>\n this._enqueueChatRecovery(\n callback,\n data ?? {},\n \"redefer\",\n CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS,\n dedupeKey\n ),\n onDetachedError: (error) =>\n console.error(`[Think] ${callback} dispatch failed`, error)\n });\n }\n\n /**\n * Enqueue one recovery attempt on the shared Tasks transport. Tasks\n * mirrors a routed dynamic agent's wake to the root's alarm; the run\n * itself, and this continuation's replay, still execute here. `dedupeKey`\n * keys a retried enqueue so it joins its own prior attempt instead of\n * duplicating it — see {@link chatRecoveryTaskRunOptions}.\n */\n private async _enqueueChatRecovery(\n callback: ChatRecoveryScheduleCallback,\n data: Record<string, unknown>,\n reason: ChatRecoveryTaskReason,\n delaySeconds: number,\n dedupeKey?: string\n ): Promise<void> {\n const input = { callback, data, delaySeconds };\n await this.tasks.__DO_NOT_USE_WILL_BREAK__enqueue(\n CHAT_RECOVERY_TASK_NAME,\n input,\n chatRecoveryTaskRunOptions(input, reason, dedupeKey)\n );\n }\n\n /**\n * The messenger-reply Task definition. A live webhook reply executes as\n * one journaled step through the runtime's closure registry, persisting\n * its re-entry snapshot in host storage; a replay whose closure is gone\n * is recovered on wake by the same\n * `ThinkMessengerRuntime.handleFiberRecovery` the legacy scan used.\n */\n private _registerMessengerReplyTaskDefinition(): void {\n this.tasks.register(\n MESSENGER_REPLY_TASK_DEFINITION,\n async (input, step) => {\n const { nonce } = input as { nonce: string };\n await step.do(\n \"deliver\",\n { retries: { limit: 1 }, timeout: \"1 day\" },\n async ({ signal }) => {\n const runtime = this._messengerRuntime;\n if (!runtime) {\n throw new Error(\"Messenger runtime is unavailable\");\n }\n const runId = `msgr_${nonce}`;\n const persistKey = `__cf_messenger_recovery:${runId}`;\n if (!runtime.hasLiveReply(nonce)) {\n // Replay after an unclean interruption: recover through the\n // runtime seam, preferring the snapshot a prior attempt (live\n // or recovering) persisted before being interrupted itself.\n const persisted = await this.ctx.storage.get(persistKey);\n const createdAt =\n (await this.tasks.get(runId))?.createdAt ?? Date.now();\n const ctx: FiberRecoveryContext = {\n id: runId,\n name: MESSENGER_REPLY_FIBER_NAME,\n snapshot: (persisted ?? null) as unknown,\n createdAt,\n recoveryReason: \"interrupted\"\n };\n await runtime.handleFiberRecovery(ctx, {\n persistRecoverySnapshot: async (snapshot) => {\n await this.ctx.storage.put(persistKey, snapshot);\n },\n // Platform failures leave the step claimed and the run is\n // replayed; any other error fails this single-attempt step.\n retriesAfter: (error) =>\n isPlatformTransientError(error) ||\n isDurableObjectMemoryLimitReset(error) ||\n isDurableObjectCodeUpdateReset(error)\n });\n await this.ctx.storage.delete(persistKey);\n return undefined;\n }\n // The initial \"accepted\" snapshot must be durable before any\n // delivery work begins: an isolate lost mid-answer recovers\n // through this snapshot, and without it replay could neither\n // deliver nor apologize.\n const initial = runtime.initialReplySnapshot(nonce);\n if (initial !== undefined) {\n await this.ctx.storage.put(persistKey, initial);\n }\n // Later fire-and-forget stash writes are safe: Durable Object\n // storage applies same-key operations in issuance order, so the\n // delete below can never be overtaken by an earlier put. A crash\n // loses only the unflushed tail, which recovery tolerates by\n // design (the snapshot is a hint; stream evidence is\n // authoritative).\n await runtime.executeLiveReply(nonce, {\n id: runId,\n signal,\n stash: (data) =>\n void this.ctx.storage.put(persistKey, data).catch(() => {}),\n snapshot: null\n });\n await this.ctx.storage.delete(persistKey);\n return undefined;\n }\n );\n }\n );\n }\n\n /**\n * Host seam for {@link ThinkMessengerRuntime}: durably accept one reply\n * run on the Tasks capability and execute it inline while this isolate\n * lives.\n * @internal\n */\n async _runMessengerReplyTask(input: {\n nonce: string;\n idempotencyKey: string;\n metadata: Record<string, unknown>;\n }): Promise<{ accepted: boolean }> {\n const receipt = await this.tasks.__DO_NOT_USE_WILL_BREAK__runAttached(\n MESSENGER_REPLY_TASK_DEFINITION,\n { nonce: input.nonce },\n {\n runId: `msgr_${input.nonce}`,\n idempotencyKey: input.idempotencyKey,\n metadata: input.metadata as Record<\n string,\n import(\"agents/tasks\").TaskJson\n >\n }\n );\n return { accepted: receipt.accepted };\n }\n\n private async _runChatRecoveryFiber<T>(\n requestId: string,\n continuation: boolean,\n fn: () => Promise<T>,\n branchParentId?: string\n ): Promise<T> {\n const snapshot: ThinkChatFiberSnapshot = {\n ...createChatFiberSnapshot({\n kind: \"think-chat-turn\",\n requestId,\n recoveryRootRequestId:\n this._activeChatRecoveryRootRequestId ?? requestId,\n continuation,\n messages: this.messages,\n lastBody: this._lastBody,\n lastClientTools: this._lastClientTools,\n originMessageIds: this._originMessageIdsFor(requestId)\n }),\n ...(branchParentId !== undefined && { branchParentId })\n };\n const liveTurn = { createdAt: Date.now(), recoveryData: null as unknown };\n const wrap = (data: unknown) => {\n liveTurn.recoveryData = data;\n return wrapChatFiberSnapshot(\n \"__cfThinkChatFiberSnapshot\",\n snapshot,\n data\n );\n };\n this._liveChatRecoveryTurns.set(requestId, liveTurn);\n try {\n return await this._runWrappedChatRecoveryFiber(\n requestId,\n continuation,\n wrap,\n fn\n );\n } finally {\n if (this._liveChatRecoveryTurns.get(requestId) === liveTurn) {\n this._liveChatRecoveryTurns.delete(requestId);\n }\n }\n }\n\n private async _runWrappedChatRecoveryFiber<T>(\n requestId: string,\n continuation: boolean,\n wrap: (data: unknown) => unknown,\n fn: () => Promise<T>\n ): Promise<T> {\n const acceptance = recoveredTurnAcceptanceContext.getStore();\n const onAccepted =\n acceptance?.agent === this ? acceptance.onAccepted : undefined;\n\n // Facet-hosted turns stay on the legacy fiber engine: the Tasks\n // capability does not accept runs on routed sub-agents yet, and facet\n // recovery routes through the root's facet-run index.\n if (this.parentPath.length > 0) {\n return this._runFiberWithStashWrapper(\n `${(this.constructor as typeof Think).CHAT_FIBER_NAME}:${requestId}`,\n async () => {\n // The legacy engine has persisted the successor fiber and snapshot\n // (and registered the facet run) before entering this closure.\n onAccepted?.(requestId);\n return fn();\n },\n { initialSnapshot: wrap(null), wrapStash: wrap }\n );\n }\n\n const nonce = crypto.randomUUID();\n let resolveOutcome!: (value: unknown) => void;\n let rejectOutcome!: (error: unknown) => void;\n const outcome = new Promise<unknown>((resolve, reject) => {\n resolveOutcome = resolve;\n rejectOutcome = reject;\n });\n // Rejections can land while `runAttached` is still being awaited (before\n // the outcome listener attaches); mark them handled so workerd does not\n // report an unhandled rejection the wrapper is about to consume.\n outcome.catch(() => {});\n // The turn closure re-enters the caller's invocation context (live\n // connection/request), exactly as legacy inline fiber execution did: the\n // capability's host boundary intentionally carries no connection.\n const ambient = agentContext.getStore();\n const run = (): Promise<T> => {\n // Tasks accepts the run durably before invoking its live closure. Rebind\n // submission ownership before telling the recovery Task it may settle,\n // so startup can always find either predecessor or successor evidence.\n onAccepted?.(requestId);\n return ambient ? agentContext.run(ambient, fn) : fn();\n };\n this._liveChatTurnClosures.set(nonce, {\n initial: wrap(null),\n wrap,\n run,\n settle: { resolve: resolveOutcome, reject: rejectOutcome }\n });\n try {\n await this.tasks.__DO_NOT_USE_WILL_BREAK__runAttached(\n (this.constructor as typeof Think).CHAT_FIBER_NAME,\n { requestId, continuation, nonce },\n { runId: `chat_${nonce}`, retain: false, metadata: { requestId } }\n );\n return (await outcome) as T;\n } finally {\n this._liveChatTurnClosures.delete(nonce);\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 \"ls\",\n \"find\",\n \"grep\",\n \"delete\"\n ].some((toolName) => toolNames.has(toolName));\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 (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 * Read-time truncation moves its cutoff once every this many messages, so\n * the provider's cached prompt prefix survives the turns in between. Up to\n * `truncationStep + 3` recent messages stay at full fidelity. Set it to `1`\n * to cut every turn, which keeps the fewest full-fidelity messages for\n * models with a small context window. `Infinity` never moves the cutoff, so\n * read-time truncation is off and every message stays at full fidelity;\n * media eviction then keeps exactly `keepRecentMessages` and rewrites the\n * prefix whenever a message ages out. Other non-finite or non-positive\n * values behave like `1`.\n *\n * @default 8\n */\n truncationStep = MODEL_TRUNCATION_STEP;\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 * Default writer for server-authored assistant-message metadata, applied to\n * every turn. Override (or supply) per turn by returning `messageMetadata`\n * from `beforeTurn` ({@link TurnConfig.messageMetadata}). Set this when the\n * metadata is turn-independent — e.g. stamping a `createdAt` timestamp on\n * every assistant message — so callers need not repeat it in `beforeTurn`.\n * See {@link MessageMetadataCallback} for when it is called and the\n * serialization constraints on its return value.\n */\n messageMetadata?: MessageMetadataCallback;\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 /** The context reminder the current turn was assembled with. */\n private _turnContextReminder: string | null = null;\n\n /**\n * The last message the current turn's model history reaches, when that is\n * not the leaf: a regeneration answers its parent user message, so the\n * response it replaces (a stored sibling branch) stays out of the prompt.\n */\n private _turnHistoryLeafId: string | undefined;\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 conversation storage. Called once during `onStart`. Override to\n * set the compaction policy; prompt context is declared by\n * {@link Think.configureContext} instead.\n *\n * The handle still accepts the pre-Sessions `withContext()` and\n * `withCachedPrompt()` chain, so an existing override keeps working; those\n * blocks are appended after the ones `configureContext()` returns.\n *\n * @example\n * ```typescript\n * configureSession(session: Session) {\n * return session\n * .onCompaction(createCompactFunction({ summarize }))\n * .compactAfter(80_000);\n * }\n * ```\n */\n configureSession(\n session: ThinkSession\n ): ThinkSession | Promise<ThinkSession> {\n return session;\n }\n\n /**\n * Declare the prompt context blocks for this agent.\n *\n * Blocks render into the system prompt and, when their provider is\n * writable, give the model `set_context` to update them. A block declared\n * without a provider is auto-wired to durable per-agent SQLite storage.\n *\n * @example\n * ```typescript\n * configureContext(): ContextConfig[] {\n * return [\n * { label: \"soul\", provider: { get: async () => \"You are helpful.\" } },\n * { label: \"memory\", description: \"Learned facts\", maxTokens: 2000 }\n * ];\n * }\n * ```\n */\n configureContext(): ContextConfig[] | Promise<ContextConfig[]> {\n return [];\n }\n\n /**\n * Return Agent Skills sources for this Think agent.\n *\n * A skill is a directory with a `SKILL.md` file, as defined by\n * https://agentskills.io. Keep skills as files in the agent's Workspace\n * and they become available as soon as they are written:\n *\n * ```typescript\n * getSkills() {\n * return [skills.workspace(this.workspace)]; // /workspace/.agents/skills\n * }\n * ```\n *\n * `skills.r2()` reads skills from an R2 bucket and `skills.manifest()`\n * defines them in code. Sources are applied in order; the first source to\n * provide a skill name wins, and later collisions are skipped with a\n * logged warning. Sources are listed again before every turn.\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 this._skillSources = sources;\n await this._loadSkillCatalog();\n\n // `whenChanged: \"remind\"` keeps the frozen system prompt (and the\n // provider's prefix cache) stable when skills change mid-conversation.\n // The new catalog goes out as a reminder after the cached prefix, and\n // is folded into the system prompt at the next rebuild (compaction or\n // clearing history).\n await this.context.addBlock({\n label: SKILLS_CONTEXT_LABEL,\n description: \"Think skills: available skill catalog\",\n whenChanged: \"remind\",\n provider: {\n get: async () =>\n this._skillCatalog?.prompt() ?? \"No skills are available.\"\n }\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 /** Load the catalog from every source and log new diagnostics. */\n private async _loadSkillCatalog(): Promise<SkillCatalog> {\n // `previous` keeps a source's last skills when it fails to list, so a\n // transient outage (an R2 blip) does not drop them for a turn.\n const catalog = await loadSkillCatalog(this._skillSources, {\n previous: this._skillCatalog ?? undefined\n });\n for (const diagnostic of catalog.diagnostics) {\n this._warnSkillsOnce(formatSkillDiagnostic(diagnostic));\n }\n this._skillCatalog = catalog;\n return catalog;\n }\n\n /**\n * Log a skills warning once per object lifetime, so a new problem after a\n * deploy still surfaces while the same warning is not repeated every turn.\n */\n private _warnSkillsOnce(warning: string): void {\n if (this._loggedSkillWarnings.has(warning)) return;\n this._loggedSkillWarnings.add(warning);\n console.warn(`[think] ${warning}`);\n }\n\n /**\n * Return an optional runner that enables the `run_skill_script` tool.\n *\n * Prefer keeping skills in the Workspace and letting the agent run their\n * scripts with its shell tools.\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._skillCatalog) return;\n\n // Sources are live (a Workspace, R2); a transient failure must not break\n // the turn. Keep the last good catalog on error. The skills block is a\n // reminder block, so a changed catalog reaches the model without\n // rebuilding the frozen system prompt.\n try {\n await this._loadSkillCatalog();\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 * Think consults it when a turn's stream errors. Return `\"context_overflow\"`\n * to run the compact-and-retry backstop (only when `contextOverflow.reactive`\n * is enabled); if recovery cannot save the turn, that classification is\n * surfaced on the terminal `onChatError` call via\n * {@link ChatErrorContext.classification}. Return `\"transient\"` or\n * `\"rate_limit\"` to route the turn into bounded chat recovery (the same path\n * as a stream stall: `onChatRecovery`, `chatRecovery.maxAttempts`, then the\n * exhaustion message), with the continuation delayed by exponential backoff.\n * Returning `void`, `\"fatal\"`, or `\"unknown\"` keeps the existing terminal\n * 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 * The app's `classifyChatError` verdict for a stream error (thrown or\n * surfaced as an in-stream error string). Call once per error: the hook may\n * be stateful or have side effects.\n */\n private _classifyStreamError(\n error: unknown,\n requestId: string\n ): ChatErrorClassification | undefined {\n if (!isMethodOverridden(this, \"classifyChatError\")) return undefined;\n try {\n return (\n this.classifyChatError(error, { stage: \"stream\", requestId }) ??\n undefined\n );\n } catch (err) {\n console.warn(\n `[Think] classifyChatError threw; treating as unclassified: ${err instanceof Error ? err.message : String(err)}`\n );\n return undefined;\n }\n }\n\n /**\n * Whether a classified stream error should trigger the opt-in\n * compact-and-retry backstop. Centralized so both stream consumers\n * (WebSocket + RPC) decide identically.\n */\n private _isRecoverableContextOverflow(\n classification: ChatErrorClassification | undefined\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 (!isMethodOverridden(this, \"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 return classification === \"context_overflow\";\n }\n\n /**\n * The `\"transient\"` or `\"rate_limit\"` class the app assigned a stream\n * error, else `undefined`. Such errors route into bounded chat recovery like\n * a stream stall instead of terminalizing the turn (#2085). Without a\n * `classifyChatError` override nothing is transient, so today's terminal\n * behavior is unchanged. A Durable Object reset is never transient here: the\n * restart's own recovery owns the turn.\n */\n private _transientStreamClassification(\n error: unknown,\n requestId: string\n ): ChatErrorClassification | undefined {\n if (error instanceof TransientChatStreamError) return error.classification;\n if (error instanceof ChatStreamStalledError) return undefined;\n if (isDurableObjectResetError(error)) return undefined;\n const classification = this._classifyStreamError(error, requestId);\n return isTransientClassification(classification)\n ? classification\n : undefined;\n }\n\n /** The provider `Retry-After` to honor for a rate-limited stream error. */\n private _streamErrorRetryAfter(\n error: unknown,\n classification: ChatErrorClassification | undefined\n ): number | undefined {\n if (classification !== \"rate_limit\") return undefined;\n return retryAfterSeconds(\n error instanceof TransientChatStreamError ? error.original : error\n );\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(this._turnHistoryLeafId);\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.context.addBlock({\n label: 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.context.removeBlock(label);\n }\n await this.context.refreshSystemPrompt();\n });\n }\n\n // ── Inference loop (Think owns this) ──────────────────────────\n\n /**\n * The repaired history the current turn's model request is built from: the\n * active path, cut at `_turnHistoryLeafId` when one is set. A leaf off the\n * cached path (another branch, or outside a windowed cache) is read from\n * storage. The cut comes before repair so messages past the leaf, which the\n * request never sees, are not rewritten.\n */\n private async _turnHistory(): Promise<UIMessage[]> {\n const leafId = this._turnHistoryLeafId;\n if (leafId === undefined) {\n return this._repairTranscriptForProvider(this.messages);\n }\n const cut = this.messages.findIndex((message) => message.id === leafId);\n if (cut >= 0) {\n return this._repairTranscriptForProvider(this.messages.slice(0, cut + 1));\n }\n const budget = this.hydrationByteBudget;\n const path = (\n Number.isFinite(budget) && budget > 0\n ? (await this.session.getRecentHistory(budget, { leafId })).messages\n : await this.session.getHistory({ leafId })\n ) as UIMessage[];\n return this._repairTranscriptForProvider(path);\n }\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._turnHistory();\n const providerSafeHistory = history.map(\n toProviderSafeExecutionOutcomeMessage\n );\n const keepRecent = truncationKeepRecent(\n providerSafeHistory.length,\n this.truncationStep\n );\n const truncated = truncateOlderMessages(providerSafeHistory, {\n keepRecent,\n toolOutputs: false\n }) as UIMessage[];\n // `_repairTranscriptForProvider` above already heals orphan tool calls\n // (flipping them to errored results, preserving the record). This is the\n // last-line backstop: if any incomplete tool call still slips through\n // (compaction edge, addToolOutput race, an unrecognized part shape), drop it\n // here rather than letting the provider 400 with AI_MissingToolResultsError.\n //\n // The backstop drops silently. Repair should have left nothing incomplete,\n // so a non-empty set here means repair missed a shape — surface it (rather\n // than masking a repair bug) without breaking the turn.\n const incompleteAfterRepair = this._incompleteToolCallIds(truncated);\n if (incompleteAfterRepair.length > 0) {\n console.warn(\n `[Think] ${incompleteAfterRepair.length} incomplete tool call(s) survived transcript repair and will be dropped by ignoreIncompleteToolCalls: ${incompleteAfterRepair.join(\", \")}. This indicates a gap in _repairToolTranscriptParts.`\n );\n this._emit(\"chat:transcript:repaired\", {\n removedToolCalls: incompleteAfterRepair.length,\n normalizedInputs: 0,\n toolCallIds: incompleteAfterRepair\n });\n }\n const modelMessages = await convertToModelMessages(truncated, {\n tools,\n ignoreIncompleteToolCalls: true\n });\n return truncateOlderToolResults(modelMessages, truncated, { keepRecent });\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 // The compaction refreshed the stored prompt, but this request keeps\n // the system prompt it started with, so it still needs the reminder.\n const head = withContextReminder(\n await this._assembleModelMessages(this._activeTurnTools),\n this._turnContextReminder\n );\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. `historyLeafId` cuts the model\n * history at that message (see `_turnHistoryLeafId`).\n */\n private async _runInferenceLoop(\n input: TurnInput,\n historyLeafId?: string\n ): Promise<StreamableResult> {\n const turn = admittedTurnContext.getStore();\n const active = this._activeAdmittedTurn();\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, historyLeafId)\n );\n const result = invoke();\n // Recorded once the stream starts, not at admission: a turn skipped by a\n // reset or a cancelled submission, or one whose preparation threw, never\n // ran, so a continuation must not extend it.\n if (active) this._lastTurnChannel = { channel: active.channel };\n return result;\n }\n\n private async _prepareInferenceInvocation(\n input: TurnInput,\n historyLeafId: string | undefined\n ): Promise<() => StreamableResult> {\n this._turnHistoryLeafId = historyLeafId;\n await this._flushDeferredResolvedPauses();\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 this._repairApprovalRespondedThisTurn =\n await this._mayRepairApprovalResponded(input.continuation);\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 // Computer's tools: exec offers every backend the Workspace has.\n const workspaceTools: ToolSet = createAITools({\n workspace: this.workspace\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.context.tools();\n const skillTools = this._skillCatalog\n ? createSkillTools(this._skillCatalog, {\n scriptRunner: this.getSkillScriptRunner()\n })\n : {};\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 rawBaseSystem = await this._buildBaseSystemPrompt();\n const baseSystem = channelInstructions\n ? `${channelInstructions}\\n\\n${rawBaseSystem}`\n : rawBaseSystem;\n const system = this._systemPromptForTurn(baseSystem, tools);\n\n this._turnContextReminder = await this.context.reminder();\n const messages = withContextReminder(\n await this._assembleModelMessages(tools),\n this._turnContextReminder\n );\n\n if (messages.length === 0) {\n throw new Error(\n \"No messages to send to the model. This usually means the chat request \" +\n \"arrived before any messages were persisted.\"\n );\n }\n\n // The default model is resolved on first read, so a `beforeTurn` that\n // returns its own `model` without reading `ctx.model` never calls\n // `getGateway` or needs the AI binding for the default.\n let defaultModel: LanguageModel | undefined;\n const resolveDefaultModel = () => (defaultModel ??= this.resolveModel());\n const turn = this.activeTurn;\n const messenger = this._activeMessengerContext();\n const ctx: TurnContext = {\n system,\n messages,\n tools,\n get model() {\n return resolveDefaultModel();\n },\n continuation: input.continuation,\n body: input.body,\n ...(turn && { requestId: turn.requestId, trigger: turn.trigger }),\n ...(input.signal && { abortSignal: input.signal }),\n ...(messenger && { messenger })\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\n ? this.resolveModel(config.model)\n : resolveDefaultModel();\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 ...turnContextWithoutModel(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 const metadataWriter = config.messageMetadata ?? this.messageMetadata;\n const continuation = input.continuation ?? false;\n const finalMessageMetadata =\n metadataWriter &&\n ((options: { part: TextStreamPart<ToolSet> }) =>\n metadataWriter({ ...options, continuation }));\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 // `experimental_repairToolCall` is the common option name across AI SDK\n // v6 and v7. TurnConfig exposes the stable v7 name while this boundary\n // keeps both supported majors working.\n experimental_repairToolCall: config.repairToolCall,\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(\n guarded ? { ...event, messages: guarded } : event\n );\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 requestId = this.activeTurn?.requestId;\n const base = {\n ...e.toolCall,\n stepNumber: e.stepNumber,\n messages: e.messages,\n toolExecutionMs: e.toolExecutionMs,\n durationMs: e.toolExecutionMs,\n ...(requestId !== undefined && { requestId })\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\n ? // `result.output` is a getter that builds a new promise per read.\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 messageMetadata?: (options: {\n part: TextStreamPart<ToolSet>;\n }) => Record<string, unknown> | undefined;\n }) => ReadableStream;\n }\n ).toUIMessageStream({\n sendReasoning,\n onError,\n messageMetadata: finalMessageMetadata\n });\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(\n ctx,\n subclassConfig.model ?? undefined\n );\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 requestId = this.activeTurn?.requestId;\n const ctx = {\n ...toolCallBase,\n stepNumber: undefined,\n messages: options.messages,\n abortSignal: options.abortSignal,\n ...(requestId !== undefined && { requestId })\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 /**\n * Hand out an RPC stub to this agent's Workspace. `getWorkspace(stub)`\n * from `@cloudflare/computer` calls it to reach the Workspace from\n * another Worker or Durable Object, and the Worker shell backend calls it\n * so its isolate can reach back into the Workspace.\n *\n * Only a Workspace this agent owns can hand out a stub; a client for\n * another object's Workspace cannot.\n */\n async __getWorkspaceStub(): Promise<WorkspaceStub> {\n await this.__unsafe_ensureInitialized();\n const workspace = this.workspace;\n if (!isLocalWorkspace(workspace)) {\n throw new Error(\n \"[Think] This agent's workspace belongs to another Durable Object, \" +\n \"so it cannot hand out a Workspace stub.\"\n );\n }\n await workspace.ready();\n return workspace.stub();\n }\n\n // ── Host bridge methods (called by HostBridgeLoopback via DO RPC) ──\n\n async _hostReadFile(path: string): Promise<string | null> {\n await this.__unsafe_ensureInitialized();\n return new WorkspaceFiles(this.workspace).readText(\n resolveWorkspacePath(path)\n );\n }\n\n async _hostWriteFile(path: string, content: string): Promise<void> {\n await this.__unsafe_ensureInitialized();\n await new WorkspaceFiles(this.workspace).write(\n resolveWorkspacePath(path),\n content\n );\n }\n\n async _hostDeleteFile(path: string): Promise<boolean> {\n await this.__unsafe_ensureInitialized();\n try {\n await new WorkspaceFiles(this.workspace).remove(\n resolveWorkspacePath(path)\n );\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 await this.__unsafe_ensureInitialized();\n const entries = await new WorkspaceFiles(this.workspace).list(\n resolveWorkspacePath(dir)\n );\n return entries.map((e) => ({\n name: e.name,\n type: e.type,\n size: e.size,\n path: e.path\n }));\n }\n\n async _hostGetContext(label: string): Promise<string | null> {\n await this.__unsafe_ensureInitialized();\n const block = this.context.getBlock(label);\n return block?.content ?? null;\n }\n\n async _hostSetContext(label: string, content: string): Promise<void> {\n await this.__unsafe_ensureInitialized();\n await this.context.setBlock(label, content);\n }\n\n async _hostGetMessages(\n limit?: number\n ): Promise<Array<{ id: string; role: string; content: string }>> {\n await this.__unsafe_ensureInitialized();\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 await this.__unsafe_ensureInitialized();\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 await this.__unsafe_ensureInitialized();\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, and do not waitForSubmission() on it from inside the turn`\n );\n }\n\n private async _runInsideAdmittedTurnBody<T>(\n admitted: QueueTurnSpec<T>\n ): Promise<T> {\n const spec = admitted.inheritChannel\n ? { ...admitted, channel: this._channelForAutoContinuation() }\n : admitted;\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 await this._runChatRecoveryFiber(requestId, false, chatBody);\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. A submitted turn runs only after the\n * current turn ends, so {@link Think.waitForSubmission} on it from inside\n * the turn throws rather than deadlocking. Precise nested-call detection is\n * deferred 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: ProgrammaticMessagesResult,\n continuation: boolean\n ): Promise<TurnResult> {\n const capture = waitTurnResultContext.getStore();\n const messageId =\n result.status === \"completed\" && capture?.agent === this\n ? capture.messageIds.get(result.requestId)\n : undefined;\n const message =\n messageId !== undefined ? await this.session.getMessage(messageId) : null;\n return {\n ...result,\n continuation,\n ...(message !== null && { message })\n };\n }\n\n private async _runTurnWait(options: RunTurnWait): Promise<TurnResult> {\n this._validateRunTurnAdmission(options, \"wait\");\n\n const capture = { agent: this, messageIds: new Map<string, string>() };\n return waitTurnResultContext.run(capture, async () => {\n if (options.continuation === true) {\n const continueOptions = {\n signal: options.signal,\n channel: options.channel\n };\n if (!isMethodOverridden(this, \"continueLastTurn\")) {\n const result = await this._continueLastTurn(options.body, {\n ...continueOptions,\n captureOutput: true\n });\n return this._enrichTurnResult(result, true);\n }\n const outputCapture: {\n agent: unknown;\n taken: boolean;\n result?: ProgrammaticMessagesResult;\n } = { agent: this, taken: false };\n const returned = await continuationOutputContext.run(\n outputCapture,\n () => this.continueLastTurn(options.body, continueOptions)\n );\n const captured = outputCapture.result;\n return this._enrichTurnResult(\n captured?.requestId === returned.requestId && \"output\" in captured\n ? { ...returned, output: captured.output }\n : returned,\n true\n );\n }\n\n const input = options.input;\n if (input === undefined) {\n throw new TypeError(\n \"runTurn: supply either input or continuation: true\"\n );\n }\n\n if (typeof input === \"function\") {\n const result = await this._runProgrammaticMessagesTurn(\n crypto.randomUUID(),\n input,\n {\n signal: options.signal,\n channel: options.channel,\n captureOutput: true\n }\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 {\n signal: options.signal,\n channel: options.channel,\n captureOutput: true\n }\n );\n return this._enrichTurnResult(result, false);\n });\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 #agentToolChildRunTableReady = false;\n\n private _ensureAgentToolChildRunTable(): void {\n // Runs ahead of every milestone, progress snapshot and child-run read, so\n // the DDL (two CREATE IF NOT EXISTS plus three ALTER attempts that throw\n // and are swallowed) is paid once per isolate, not per call.\n if (this.#agentToolChildRunTableReady) return;\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 this._addAgentToolChildRunColumnIfMissing(\n \"ALTER TABLE cf_agent_tool_child_runs ADD COLUMN event_delivery TEXT\"\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 this.#agentToolChildRunTableReady = true;\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 // An open row may carry a recorded stream error that isn't terminal yet.\n error:\n row.completed_at === null\n ? undefined\n : (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; eventDelivery?: \"full\" | \"terminal\" }\n ): Promise<AgentToolRunInspection> {\n const existing = this._readAgentToolChildRun(options.runId);\n if (existing) return this._inspectionFromChildRow(existing);\n\n const startedAt = Date.now();\n const eventDelivery =\n options.eventDelivery === \"terminal\" ? \"terminal\" : null;\n this.sql`\n INSERT INTO cf_agent_tool_child_runs\n (run_id, status, started_at, event_delivery)\n VALUES (${options.runId}, 'starting', ${startedAt}, ${eventDelivery})\n `;\n\n const controller = new AbortController();\n this._agentToolAbortControllers.set(options.runId, controller);\n this._agentToolLiveSequences.set(options.runId, 0);\n if (eventDelivery === \"terminal\") {\n this._agentToolTerminalOnlyRuns.add(options.runId);\n }\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 this._agentToolTerminalOnlyRuns.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 options?: { reconcile?: boolean }\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 (options?.reconcile !== false && 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 stream error recorded on the open row means the turn failed even if it\n // persisted an assistant reply — matching the live finalizer, which fails a\n // run whenever a stream error was captured.\n const recordedError = this._readAgentToolChildRun(runId)?.error_message;\n if (recordedError != null) {\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET status = 'error',\n error_message = ${recordedError},\n completed_at = ${Date.now()}\n WHERE run_id = ${runId} AND completed_at IS NULL\n `;\n this._finalizeAgentToolChildRunTailers(runId);\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 // A live in-isolate run keeps suppressing until `startAgentToolRun`'s\n // finally; a recovered turn never reaches that finally.\n if (!this._agentToolAbortControllers.has(runId)) {\n this._agentToolTerminalOnlyRuns.delete(runId);\n }\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 /**\n * After this DO restarts, `_agentToolLiveSequences` is cold while the stored\n * backlog sits at N, and a chat-recovery resume re-attaches via\n * `tailAgentToolRun` without re-running `startAgentToolRun` (which seeds the\n * counter). Unseeded, the broadcast snoop numbers the recovered turn's chunks\n * from 0 and the tail's high-water dedupe drops them. Seeds only a\n * non-terminal run, so a terminal one doesn't re-heat the broadcast\n * idle-guard; a warm counter is authoritative. Returns whether it seeded.\n */\n private _seedAgentToolLiveSequence(runId: string): boolean {\n if (this._agentToolLiveSequences.has(runId)) return false;\n const row = this._readAgentToolChildRun(runId);\n if (!row?.stream_id || row.completed_at !== null) return false;\n this._resumableStream.flushBuffer();\n this._agentToolLiveSequences.set(\n runId,\n this._resumableStream.getStreamChunks(row.stream_id).length\n );\n return true;\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. Progress/milestone frames and unstored\n // chunks have no stored position (they reuse the next one), so they\n // bypass the high-water mark instead of moving it.\n let lastEmitted = options?.afterSequence ?? -1;\n const emit = (chunk: AgentToolStoredChunk) => {\n if (closed) return;\n if (!isPositionlessAgentToolChunk(chunk)) {\n if (chunk.sequence <= lastEmitted) return;\n lastEmitted = chunk.sequence;\n }\n try {\n controller.enqueue(\n agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\\n`)\n );\n } catch {\n // The consumer detached (e.g. a parent's re-attach budget expired\n // and cancelled the reader) between the RPC cancel arriving and our\n // `cancel`/`close` running. Drop the chunk instead of surfacing a\n // \"Stream was cancelled\" rejection; the child run is unaffected.\n closed = true;\n detach();\n }\n };\n\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 //\n // Seed a cold live counter first, so a chunk broadcast while this tail\n // drains continues the stored numbering.\n const seeded = self._seedAgentToolLiveSequence(runId);\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 // Don't leave a seeded counter re-heating the broadcast idle-guard\n // for a terminal run.\n if (seeded) self._agentToolLiveSequences.delete(runId);\n close();\n return;\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 /**\n * Whether this instance arms the declared scheduled tasks.\n *\n * The root always arms. Facets only arm when the class opts in via\n * `getScheduledTasksScope()`; see that hook for why root-only is the\n * default (#1877). `parentPath` is hydrated before the reconcile step of\n * `onStart` — persisted by `_cf_initAsFacet` on a facet's first boot, and\n * restored from storage by the base agent on every later wake.\n */\n private async _declaredScheduledTasksArmedHere(): Promise<boolean> {\n if (this.parentPath.length === 0) return true;\n return (await this.getScheduledTasksScope()) === \"all\";\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 // A facet that does not arm reconciles against an empty task set rather\n // than skipping outright: the prune pass below then cancels and deletes\n // any rows an earlier version armed here, so pre-existing duplicates heal\n // on the next wake instead of firing forever (#1877).\n const armed = await this._declaredScheduledTasksArmedHere();\n const tasks = armed\n ? await this._declaredScheduledTasksForNow()\n : new Map<string, NormalizedDeclaredTask>();\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 if (!armed) await this._warnFacetScheduledTasksDisarmed(existing.length);\n }\n\n /**\n * Warn once when a sub-agent declares tasks it will not arm.\n *\n * Two populations need this, and only one of them leaves a trace. A facet\n * upgrading from the pre-#1877 default has rows to prune, so `armedCount`\n * is non-zero. A facet declaring tasks for the first time under the root\n * default never armed anything, so the only way to tell it apart from a\n * class that declares nothing is to ask — otherwise its schedule is\n * silently inert, which is the failure mode #1877 was filed about.\n */\n private async _warnFacetScheduledTasksDisarmed(\n armedCount: number\n ): Promise<void> {\n if (this._warnedFacetScheduledTasksDisarmed) return;\n let declaredCount = armedCount;\n if (declaredCount === 0) {\n try {\n declaredCount = Object.keys(await this.getScheduledTasks()).length;\n } catch {\n // Only the warning depends on this; a declaration that throws still\n // surfaces from whichever instance actually arms it.\n return;\n }\n }\n if (declaredCount === 0) return;\n this._warnedFacetScheduledTasksDisarmed = true;\n console.warn(\n `[Think] Sub-agent \"${this.name}\" declares ${declaredCount} scheduled ` +\n `task(s) that are not armed here. Declared tasks run on the root ` +\n `agent only, so each occurrence fires once rather than once per live ` +\n `sub-agent (#1877)` +\n (armedCount > 0\n ? `; the occurrences this sub-agent had already armed have been ` +\n `cancelled`\n : ``) +\n `. Override getScheduledTasksScope() to return \"all\" if this class ` +\n `intentionally declares per-sub-agent tasks.`\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 // A dispatch can reach a facet that no longer arms — either racing the\n // reconcile that prunes its rows, or arriving before this wake got that\n // far. Returning here keeps the `finally` below from re-arming the very\n // occurrence the prune is trying to retire (#1877).\n if (!(await this._declaredScheduledTasksArmedHere())) return;\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 -- Closed vocabulary: 'completed' | 'aborted' | 'retry'. NULL is legacy\n -- or an unsettled attempt; 'retry' is NOT terminal completion evidence.\n result_status TEXT,\n output_json TEXT,\n message_id TEXT\n )\n `;\n // This table is unversioned. Add nullable columns for existing objects,\n // preserving unstamped rows for the legacy stream-evidence fallback.\n for (const statement of [\n \"ALTER TABLE cf_think_submissions ADD COLUMN result_status TEXT\",\n \"ALTER TABLE cf_think_submissions ADD COLUMN output_json TEXT\",\n \"ALTER TABLE cf_think_submissions ADD COLUMN message_id TEXT\"\n ]) {\n try {\n this.ctx.storage.sql.exec(statement);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (!message.toLowerCase().includes(\"duplicate column\")) throw error;\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 _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, result_status, output_json,\n message_id\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, result_status, output_json,\n message_id\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, result_status, output_json,\n message_id\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, result_status, output_json,\n message_id\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 ...(row.message_id !== null && { messageId: row.message_id })\n };\n }\n\n private _parseJsonObject(\n value: string | null\n ): Record<string, unknown> | null {\n if (value === null) return null;\n try {\n const parsed = JSON.parse(value) as unknown;\n if (\n parsed !== null &&\n typeof parsed === \"object\" &&\n !Array.isArray(parsed)\n ) {\n return parsed as Record<string, unknown>;\n }\n } catch {\n // Invalid metadata should not prevent inspection.\n }\n return null;\n }\n\n private _parseSubmissionMessages(value: string): UIMessage[] {\n const parsed = JSON.parse(value) as unknown;\n if (!Array.isArray(parsed)) {\n throw new Error(\"Stored submission messages are invalid\");\n }\n return parsed as UIMessage[];\n }\n\n private _serializeSubmissionMessages(messages: UIMessage[]): string {\n return JSON.stringify(\n messages.map((message) =>\n enforceRowSizeLimit(sanitizeMessage(message), {\n warn: (warning) => console.warn(`[Think] ${warning}`)\n })\n )\n );\n }\n\n private _serializeMetadata(\n metadata: Record<string, unknown> | undefined\n ): string | null {\n return metadata === undefined ? null : JSON.stringify(metadata);\n }\n\n private _readWorkflowPromptContext(\n metadata: Record<string, unknown> | null\n ): ThinkWorkflowPromptContext | null {\n const workflowPromptValue = metadata?.[THINK_WORKFLOW_PROMPT_METADATA_KEY];\n if (\n workflowPromptValue === null ||\n typeof workflowPromptValue !== \"object\" ||\n Array.isArray(workflowPromptValue)\n ) {\n return null;\n }\n const workflowPrompt = workflowPromptValue as Record<string, unknown>;\n const workflowValue = workflowPrompt.workflow;\n if (\n workflowValue === null ||\n typeof workflowValue !== \"object\" ||\n Array.isArray(workflowValue)\n ) {\n return null;\n }\n const workflowRecord = workflowValue as Record<string, unknown>;\n if (\n typeof workflowRecord.name !== \"string\" ||\n typeof workflowRecord.id !== \"string\" ||\n typeof workflowRecord.stepName !== \"string\" ||\n typeof workflowRecord.eventType !== \"string\"\n ) {\n return null;\n }\n const output = workflowPrompt.output;\n const outputRecord =\n output !== null && typeof output === \"object\" && !Array.isArray(output)\n ? (output as Record<string, unknown>)\n : null;\n return {\n workflow: {\n name: workflowRecord.name,\n id: workflowRecord.id,\n stepName: workflowRecord.stepName,\n eventType: workflowRecord.eventType\n },\n ...(outputRecord\n ? {\n output: {\n schema: outputRecord.schema\n }\n }\n : {}),\n ...(typeof workflowPrompt.fingerprint === \"string\" && {\n fingerprint: workflowPrompt.fingerprint\n })\n };\n }\n\n private async _emitSubmissionStatus(row: ThinkSubmissionRow): Promise<void> {\n const inspection = this._inspectionFromSubmissionRow(row);\n const terminal = this._isTerminalSubmissionStatus(inspection.status);\n if (terminal) this._terminalStatusEmits.add(inspection.submissionId);\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 try {\n await this.keepAliveWhile(async () => {\n const hook = { agent: this, ended: false };\n try {\n await submissionStatusHookContext.run(hook, () =>\n this.onSubmissionStatus(inspection)\n );\n } catch (error) {\n console.error(\"[Think] onSubmissionStatus failed\", error);\n } finally {\n hook.ended = true;\n }\n });\n } finally {\n if (terminal) {\n const id = inspection.submissionId;\n this._terminalStatusEmits.delete(id);\n const held = this._waitersHeldForDeletedEmit.get(id);\n this._waitersHeldForDeletedEmit.delete(id);\n for (const waiter of held ?? []) waiter(inspection);\n const current = this._readSubmission(id);\n if (current?.created_at === row.created_at) {\n this._resolveSubmissionWaiters(inspection);\n }\n }\n }\n }\n\n private _resolveSubmissionWaiters(\n submission: ThinkSubmissionInspection\n ): void {\n const waiters = this._submissionWaiters.get(submission.submissionId);\n this._submissionWaiters.delete(submission.submissionId);\n for (const waiter of waiters ?? []) waiter(submission);\n }\n\n private _submissionWaiters = new Map<\n string,\n Set<(submission: ThinkSubmissionInspection) => void>\n >();\n\n /**\n * Submissions whose row is terminal but whose `onSubmissionStatus` has not\n * finished. `waitForSubmission` keeps waiting for these.\n */\n private _terminalStatusEmits = new Set<string>();\n\n /** Waiters of a submission deleted while its terminal emit was in flight. */\n private _waitersHeldForDeletedEmit = new Map<\n string,\n Set<(submission: ThinkSubmissionInspection) => void>\n >();\n\n /**\n * Resolve once the submission reaches a terminal status (`completed`,\n * `aborted`, `skipped` or `error`), after `onSubmissionStatus` has run for\n * it. Resolves immediately for a submission that already finished, and with\n * `null` for an unknown id. An `error` status resolves rather than rejects;\n * read `status` and `error` from the result.\n *\n * The wait lives in this object's memory, so it rejects if the object\n * restarts. The submission itself is durable: call again to keep waiting.\n *\n * Throws when called from inside a turn (a tool `execute`, a lifecycle\n * hook) or from `onSubmissionStatus` for a submission that has not\n * finished: a submission only runs once the current turn frees the turn\n * queue, and its status settles only after the hook returns, so the wait\n * could never resolve. Return the submission id and wait from outside the\n * turn instead.\n */\n async waitForSubmission(\n submissionId: string,\n options?: WaitForSubmissionOptions\n ): Promise<ThinkSubmissionInspection | null> {\n const row = this._readSubmission(submissionId);\n if (!row) return null;\n if (\n this._isTerminalSubmissionStatus(row.status) &&\n !this._terminalStatusEmits.has(submissionId)\n ) {\n return this._inspectionFromSubmissionRow(row);\n }\n const hook = submissionStatusHookContext.getStore();\n if (hook?.agent === this && !hook.ended) {\n throw new Error(\n \"waitForSubmission() cannot be called from onSubmissionStatus: the submission settles only after the hook returns\"\n );\n }\n if (this._activeAdmittedTurn()) {\n throw new Error(\n \"waitForSubmission() cannot be called from inside an active turn: the submission runs only after this turn ends\"\n );\n }\n return new Promise((resolve) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const waiter = (submission: ThinkSubmissionInspection) => {\n clearTimeout(timer);\n resolve(submission);\n };\n let waiters = this._submissionWaiters.get(submissionId);\n if (!waiters) {\n waiters = new Set();\n this._submissionWaiters.set(submissionId, waiters);\n }\n waiters.add(waiter);\n if (options?.timeoutMs !== undefined) {\n timer = setTimeout(() => {\n const current = this._submissionWaiters.get(submissionId);\n current?.delete(waiter);\n if (current?.size === 0) this._submissionWaiters.delete(submissionId);\n const latest = this._readSubmission(submissionId);\n resolve(latest ? this._inspectionFromSubmissionRow(latest) : null);\n }, options.timeoutMs);\n }\n });\n }\n\n protected onSubmissionStatus(\n _submission: ThinkSubmissionInspection\n ): void | Promise<void> {}\n\n /**\n * Queue the workflow event for a submission that just went terminal.\n *\n * The item is written synchronously (the Lifecycle has started whenever a\n * submission transitions), so call this in the same synchronous block as\n * the terminal status write: the two commit together and no recovery scan\n * is needed. A repeated push for the same submission and event type\n * replaces the pending item rather than duplicating it.\n */\n private _insertWorkflowNotification(\n submission: ThinkSubmissionInspection,\n output?: unknown\n ): boolean {\n const workflowPrompt = this._readWorkflowPromptContext(\n submission.metadata ?? null\n );\n if (!workflowPrompt) return false;\n\n const { status, error } = submission;\n const payload = {\n submissionId: submission.submissionId,\n status,\n ...(status === \"completed\" && { output }),\n ...(error && { error })\n };\n void this.queue(\n WORKFLOW_NOTIFICATION_CALLBACK,\n {\n workflowName: workflowPrompt.workflow.name,\n workflowId: workflowPrompt.workflow.id,\n event: { type: workflowPrompt.workflow.eventType, payload }\n } satisfies WorkflowNotificationPayload,\n {\n id: workflowNotificationItemId(\n submission.submissionId,\n workflowPrompt.workflow.eventType\n ),\n retry: WORKFLOW_NOTIFICATION_RETRY\n }\n ).catch((error) => {\n console.error(\"[Think] Failed to queue workflow notification\", error);\n });\n return true;\n }\n\n /** Queue the workflow event for a row that a caller just made terminal. */\n private _enqueueTerminalWorkflowNotification(\n row: ThinkSubmissionRow | null,\n output?: unknown\n ): void {\n if (!row || !this._isTerminalSubmissionStatus(row.status)) return;\n this._insertWorkflowNotification(\n this._inspectionFromSubmissionRow(row),\n output\n );\n }\n\n /**\n * Deliver one workflow notification. Runs from the queue on first\n * delivery; a failed delivery schedules this same callback again with\n * exponential backoff (2s doubling, capped at ten minutes) so a\n * temporarily unreachable workflow still gets its terminal event. Once\n * the first failure is twelve hours old delivery gives up by throwing:\n * the dispatching capability reports it through its error event and the\n * Agent's `onError`.\n * @internal Queue and schedule callback.\n */\n async _cfDeliverWorkflowNotification(\n payload: WorkflowNotificationPayload\n ): Promise<void> {\n try {\n await this.sendWorkflowEvent(\n payload.workflowName as string & {},\n payload.workflowId,\n payload.event\n );\n } catch (error) {\n const attempts = (payload.attempts ?? 0) + 1;\n const firstFailedAt = payload.firstFailedAt ?? Date.now();\n if (Date.now() - firstFailedAt >= WORKFLOW_NOTIFICATION_GIVE_UP_MS) {\n const summary =\n `Workflow notification for submission ${JSON.stringify(\n (payload.event.payload as { submissionId?: string })?.submissionId\n )} (${payload.workflowName}/${payload.workflowId}, ${payload.event.type}) ` +\n `could not be delivered after ${attempts} attempts over 12h; giving up`;\n console.error(`[Think] ${summary}`, error);\n // Deliberately no `cause`: the dispatching capability preserves any\n // error whose cause chain is a platform-class failure, which would\n // keep the item alive past this cutoff.\n throw new Error(summary);\n }\n const delaySeconds = Math.min(\n WORKFLOW_NOTIFICATION_MAX_BACKOFF_SECONDS,\n 2 ** Math.min(attempts, 20)\n );\n console.error(\n `[Think] Workflow notification delivery failed (attempt ${attempts}); ` +\n `retrying in ${delaySeconds}s`,\n error\n );\n await this.schedule(delaySeconds, WORKFLOW_NOTIFICATION_CALLBACK, {\n ...payload,\n attempts,\n firstFailedAt\n } satisfies WorkflowNotificationPayload);\n }\n }\n\n /**\n * Move undelivered rows of the retired `cf_think_workflow_notifications`\n * outbox into the queue and drop the table. Idempotent: a missing table\n * means a fresh object or a completed migration.\n *\n * TEMPORARY: one-shot upgrade path for objects that were mid-delivery when\n * this release landed. Remove in the next minor release, once every\n * deployed object has started on this version and migrated.\n */\n private async _migrateLegacyWorkflowNotifications(): Promise<void> {\n const tables = this.ctx.storage.sql\n .exec(\n \"SELECT name FROM sqlite_master WHERE type='table' AND name='cf_think_workflow_notifications'\"\n )\n .toArray();\n if (tables.length === 0) return;\n\n const rows = this.sql<{\n submission_id: string;\n workflow_name: string;\n workflow_id: string;\n event_type: string;\n payload_json: string;\n }>`\n SELECT submission_id, workflow_name, workflow_id, event_type, payload_json\n FROM cf_think_workflow_notifications\n WHERE delivered_at IS NULL\n ORDER BY created_at ASC, notification_id ASC\n `;\n for (const row of rows) {\n let payload: unknown;\n try {\n payload = JSON.parse(row.payload_json);\n } catch {\n continue;\n }\n await this.queue(\n WORKFLOW_NOTIFICATION_CALLBACK,\n {\n workflowName: row.workflow_name,\n workflowId: row.workflow_id,\n event: { type: row.event_type, payload }\n } satisfies WorkflowNotificationPayload,\n {\n id: workflowNotificationItemId(row.submission_id, row.event_type),\n retry: WORKFLOW_NOTIFICATION_RETRY\n }\n );\n }\n this.sql`DROP TABLE cf_think_workflow_notifications`;\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 this._releaseDeletedSubmissionWaiters([row]);\n return true;\n }\n\n private _releaseDeletedSubmissionWaiters(rows: ThinkSubmissionRow[]): void {\n for (const row of rows) {\n const id = row.submission_id;\n if (!this._terminalStatusEmits.has(id)) {\n this._resolveSubmissionWaiters(this._inspectionFromSubmissionRow(row));\n continue;\n }\n // The in-flight emit settles these after its hook; a new row that\n // reuses the id gets a fresh waiter set.\n const waiters = this._submissionWaiters.get(id);\n if (!waiters) continue;\n this._submissionWaiters.delete(id);\n const held = this._waitersHeldForDeletedEmit.get(id) ?? new Set();\n for (const waiter of waiters) held.add(waiter);\n this._waitersHeldForDeletedEmit.set(id, held);\n }\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 rowsToDelete = rows.filter((row) =>\n this._isTerminalSubmissionStatus(row.status)\n );\n const idsToDelete = rowsToDelete.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 this._releaseDeletedSubmissionWaiters(rowsToDelete);\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, result_status, output_json,\n message_id\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, result_status, output_json,\n message_id\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<CancelSubmissionResult> {\n const row = this._readSubmission(submissionId);\n if (!row) return { outcome: \"not_found\", submissionId };\n if (this._isTerminalSubmissionStatus(row.status)) {\n return {\n outcome: \"already_terminal\",\n submissionId,\n submission: this._inspectionFromSubmissionRow(row)\n };\n }\n const previousStatus = row.status as \"pending\" | \"running\";\n // Once the append loop starts it finishes even if cancelled, so starting\n // it is what applies the messages.\n let messagesApplied =\n row.messages_applied_at !== null ||\n this._submissionsApplyingMessages.has(submissionId);\n const runningHere = this._submissionAbortControllers.has(submissionId);\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 result_status = NULL,\n output_json = NULL\n WHERE submission_id = ${submissionId}\n AND status IN ('pending', 'running')\n `;\n\n const updated = this._readSubmission(submissionId);\n if (!updated) return { outcome: \"not_found\", submissionId };\n if (updated.status !== \"aborted\") {\n return {\n outcome: \"already_terminal\",\n submissionId,\n submission: this._inspectionFromSubmissionRow(updated)\n };\n }\n this._enqueueTerminalWorkflowNotification(updated);\n this._terminalStatusEmits.add(submissionId);\n try {\n // A submission claimed before a restart has no in-memory record of its\n // appends, so fall back to the stored-message check recovery uses.\n if (!messagesApplied && previousStatus === \"running\" && !runningHere) {\n messagesApplied =\n (await this._getSubmissionMessagesAppliedState(updated)) !== \"none\";\n }\n await this.dequeue(submissionRunItemId(submissionId));\n } finally {\n await this._emitSubmissionStatus(updated);\n }\n return {\n outcome: \"cancelled\",\n submissionId,\n previousStatus,\n messagesApplied,\n submission: this._inspectionFromSubmissionRow(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._queueSubmissionRun(existing.submission_id);\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._queueSubmissionRun(submissionId);\n\n return {\n ...this._inspectionFromSubmissionRow(row),\n accepted: true\n };\n }\n });\n }\n\n /**\n * Queue the run of one pending submission. Idempotent: the stable id\n * replaces an item already queued for the submission in place, keeping\n * its FIFO slot, and re-arms the physical alarm so a lost alarm recovers.\n */\n private async _queueSubmissionRun(submissionId: string): Promise<void> {\n await this.queue(\n SUBMISSION_RUN_CALLBACK,\n { submissionId },\n { id: submissionRunItemId(submissionId) }\n );\n }\n\n /** Queue a run for every pending submission that has none. */\n private async _queuePendingSubmissionRuns(): Promise<void> {\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 ORDER BY created_at ASC, submission_id ASC\n `;\n for (const row of pending) {\n await this._queueSubmissionRun(row.submission_id);\n }\n }\n\n /**\n * Run one pending submission. Runs on the Lifecycle alarm loop through the\n * Queue capability, one item at a time in submission order; a row that is\n * no longer pending (cancelled, skipped, or claimed by an overlapping\n * dispatch) is a no-op.\n * @internal Queue callback.\n */\n async _cfRunSubmission(payload: { submissionId: string }): Promise<void> {\n this._ensureSubmissionTable();\n const row = this._readSubmission(payload.submissionId);\n if (!row || row.status !== \"pending\") return;\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\n // Registered before the running hook so a cancel landing during the hook\n // aborts this run and reports it as running here.\n const controller = new AbortController();\n this._submissionAbortControllers.set(row.submission_id, controller);\n let output: unknown;\n // Whether this run wrote the terminal status. A cancel or reset that got\n // there first emits it itself.\n let finalizedHere = false;\n try {\n await this._emitSubmissionStatus(claimed);\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 onApplyingMessages: () => {\n this._submissionsApplyingMessages.add(row.submission_id);\n },\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 if (this._recoveryOwnedSubmissions.delete(row.submission_id)) return;\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 finalizedHere =\n this._readSubmission(row.submission_id)?.status === \"running\";\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 result_status = NULL,\n output_json = NULL\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 finalizedHere =\n this._readSubmission(row.submission_id)?.status === \"running\";\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'error',\n error_message = ${errorMessage},\n completed_at = ${completedAt},\n result_status = NULL,\n output_json = NULL\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 this._submissionsApplyingMessages.delete(row.submission_id);\n const updated = this._readSubmission(row.submission_id);\n if (\n finalizedHere &&\n updated &&\n this._isTerminalSubmissionStatus(updated.status)\n ) {\n await this._emitSubmissionStatus(updated);\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, result_status, output_json,\n message_id\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 const skipped: ThinkSubmissionRow[] = [];\n for (const row of pending) {\n const updated = this._readSubmission(row.submission_id);\n this._enqueueTerminalWorkflowNotification(updated);\n if (updated) {\n skipped.push(updated);\n // Emitted one at a time after this returns; until each emit finishes,\n // `waitForSubmission` keeps waiting on it.\n this._terminalStatusEmits.add(updated.submission_id);\n }\n void this.dequeue(submissionRunItemId(row.submission_id)).catch(\n (error) => {\n console.error(\"[Think] Failed to dequeue skipped submission\", error);\n }\n );\n }\n return skipped;\n }\n\n private async _emitSkippedSubmissions(\n skipped: ThinkSubmissionRow[]\n ): Promise<void> {\n for (const row of skipped) {\n const id = row.submission_id;\n const updated = this._readSubmission(id);\n if (\n updated?.status === \"skipped\" &&\n updated.created_at === row.created_at\n ) {\n try {\n await this._emitSubmissionStatus(updated);\n continue;\n } catch (error) {\n console.error(\"[Think] Failed to emit skipped submission\", error);\n }\n }\n // Deleted or replaced before its emit (or the emit failed): settle the\n // waiters held for it so none is stranded.\n this._terminalStatusEmits.delete(id);\n const held = this._waitersHeldForDeletedEmit.get(id);\n this._waitersHeldForDeletedEmit.delete(id);\n const inspection = this._inspectionFromSubmissionRow(row);\n for (const waiter of held ?? []) waiter(inspection);\n if (updated?.created_at === row.created_at) {\n this._resolveSubmissionWaiters(inspection);\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, result_status, output_json,\n message_id\n FROM cf_think_submissions\n WHERE status = 'running'\n `;\n\n for (const row of running) {\n // A cutover fact wins even if an old Task/recovery callback remains.\n // Streams also complete on abort and overflow retry, so their lifecycle\n // alone cannot tell us whether this submission produced an answer.\n if (\n row.result_status === \"completed\" ||\n row.result_status === \"aborted\"\n ) {\n await this._completeRecoveredSubmission(\n row,\n row.result_status,\n row.request_id,\n null\n );\n continue;\n }\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 this._enqueueTerminalWorkflowNotification(updated);\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 this._enqueueTerminalWorkflowNotification(updated);\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 (await this._hasScheduledChatRecovery(row)))\n ) {\n continue;\n }\n\n // An error stamp survives its stream rows being reclaimed by a later\n // turn; pending recovery above still takes priority, so it settles the\n // ledger only once no retry remains. Legacy rows have no cutover fact;\n // keep their exact-stream fallback. An overflow segment deliberately\n // discarded its partial for a retry, so its completed stream is NOT an\n // answer — without recovery a retry stamp falls through to interruption.\n const terminalStream = row.request_id\n ? this._resumableStream.latestStreamInfoForRequest(row.request_id)\n : null;\n const errored =\n row.result_status === \"error\" || terminalStream?.status === \"error\";\n if (\n errored ||\n (terminalStream?.status === \"completed\" &&\n row.result_status !== \"retry\")\n ) {\n await this._completeRecoveredSubmission(\n row,\n errored ? \"error\" : \"completed\",\n row.request_id,\n errored ? \"Recovered chat stream had already errored.\" : null\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 this._enqueueTerminalWorkflowNotification(updated);\n await this._emitSubmissionStatus(updated);\n }\n }\n\n // Rows still pending (reverted above, or accepted before their run\n // item existed) get their run queued; queued ones keep their slot.\n await this._queuePendingSubmissionRuns();\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 /**\n * Wall-clock creation time of a non-terminal chat-turn run on the Tasks\n * capability, or null. The metadata column holds the exact JSON the chat\n * wrapper wrote, so string equality matches the requestId.\n */\n private _recoverableChatTurnTaskCreatedAt(requestId: string): number | null {\n const rows = this.sql<{ created_at: number }>`\n SELECT created_at FROM cf_agents_task_runs\n WHERE definition = ${(this.constructor as typeof Think).CHAT_FIBER_NAME}\n AND state IN ('pending', 'running', 'waiting', 'recovering')\n AND metadata = ${JSON.stringify({ requestId })}\n LIMIT 1\n `;\n return rows[0]?.created_at ?? null;\n }\n\n private _hasRecoverableChatTurn(requestId: string): boolean {\n // A settled fiber whose row delete failed keeps `completed_at` (#2363).\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 AND completed_at IS NULL\n LIMIT 1\n `;\n if (fiberRows.length > 0) return true;\n if (this._recoverableChatTurnTaskCreatedAt(requestId) !== null) {\n return true;\n }\n\n return (\n this._resumableStream.latestActiveStreamInfoForRequest(requestId) !== null\n );\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 AND completed_at IS NULL\n LIMIT 1\n `;\n if (fiberRows[0] && fiberRows[0].created_at >= cutoff) return true;\n\n const capabilityCreatedAt = this._recoverableChatTurnTaskCreatedAt(\n row.request_id\n );\n if (capabilityCreatedAt !== null && capabilityCreatedAt >= cutoff) {\n return true;\n }\n\n const streamInfo = this._resumableStream.latestActiveStreamInfoForRequest(\n row.request_id\n );\n return streamInfo ? streamInfo.createdAt >= cutoff : false;\n }\n\n private async _hasScheduledChatRecovery(\n submission: Pick<ThinkSubmissionRow, \"submission_id\" | \"request_id\">\n ): Promise<boolean> {\n const isChatRecoveryCallback = (\n callback: unknown\n ): callback is ChatRecoveryScheduleCallback =>\n callback === \"_chatRecoveryContinue\" || callback === \"_chatRecoveryRetry\";\n const matchesSubmission = (recoveredRequestId: unknown): boolean =>\n typeof recoveredRequestId === \"string\" &&\n this._readRunningSubmissionForRecovery(recoveredRequestId)\n ?.submission_id === submission.submission_id;\n\n const recoveryRuns = await this.tasks.list({\n definition: CHAT_RECOVERY_TASK_NAME,\n status: [\"pending\", \"running\", \"waiting\"],\n limit: Number.MAX_SAFE_INTEGER\n });\n if (\n recoveryRuns.some(\n (run) =>\n isChatRecoveryCallback(run.metadata?.callback) &&\n matchesSubmission(run.metadata.recoveredRequestId)\n )\n ) {\n return true;\n }\n\n // Legacy scheduled recovery callbacks remain readable while durable rows\n // created before the Tasks transport upgrade drain naturally.\n return (await this.listSchedules()).some((schedule) => {\n if (!isChatRecoveryCallback(schedule.callback)) return false;\n const payload: unknown = schedule.payload;\n return (\n payload !== null &&\n typeof payload === \"object\" &&\n \"recoveredRequestId\" in payload &&\n matchesSubmission(\n (payload as { recoveredRequestId?: unknown }).recoveredRequestId\n )\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 Sessions change\n // listener wired in `onStart`, 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 onApplyingMessages?: () => void;\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 options?.onApplyingMessages?.();\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 await this._runChatRecoveryFiber(requestId, false, programmaticBody);\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 * Recovery continuations (`trigger: \"recovery-continue\"`) are the exception:\n * they stream into the interrupted assistant message so it stays one message.\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 store = continuationOutputContext.getStore();\n const capture = store?.agent === this && !store.taken ? store : undefined;\n if (capture) capture.taken = true;\n const full = await this._continueLastTurn(\n body,\n capture ? { ...options, captureOutput: true } : options\n );\n if (capture) capture.result = full;\n const { output: _output, ...result } = full;\n return result;\n }\n\n private async _continueLastTurn(\n body?: Record<string, unknown>,\n options?: SaveMessagesOptions & {\n trigger?: TurnTrigger;\n channel?: string;\n captureOutput?: boolean;\n }\n ): Promise<ProgrammaticMessagesResult> {\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 workflowPrompt = this._recoveredWorkflowPrompt();\n const captureOutput =\n options?.captureOutput || Boolean(workflowPrompt?.output);\n const epoch = this._turnQueue.generation;\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n let error: string | undefined;\n let output: unknown;\n let wasAborted = false;\n\n await this._admitTurn({\n admission: \"queue\",\n trigger,\n requestId,\n continuation: true,\n // Without an explicit channel, a continued/recovered turn re-applies the\n // per-channel policy of the turn it extends.\n channel: options?.channel,\n inheritChannel: options?.channel === undefined,\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 workflowPrompt,\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 extendLeafAssistant: trigger === \"recovery-continue\",\n captureOutput\n }\n );\n status = streamResult.status;\n error = streamResult.error;\n output = streamResult.output;\n }\n };\n\n await this._runChatRecoveryFiber(requestId, true, continueTurnBody);\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 private async _retryLastUserTurn(\n clientTools?: ClientToolSchema[],\n body?: Record<string, unknown>,\n options?: SaveMessagesOptions & {\n trigger?: TurnTrigger;\n channel?: string;\n /** Answer this user message as a new sibling branch (a regeneration). */\n branchParentId?: string;\n }\n ): Promise<SaveMessagesResult> {\n const trigger = options?.trigger ?? \"recovery-retry\";\n this._assertNotInsideAdmittedTurn(trigger);\n const branchParentId = options?.branchParentId;\n const target =\n branchParentId === undefined\n ? await this.session.getLatestLeaf()\n : await this.session.getMessage(branchParentId);\n if (!target || target.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 const workflowPrompt = this._recoveredWorkflowPrompt();\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 {\n signal: abortSignal,\n clientTools,\n body,\n workflowPrompt,\n continuation: false\n },\n branchParentId\n )\n );\n\n if (result) {\n const streamResult = await this._streamResult(\n requestId,\n result,\n abortSignal,\n {\n captureOutput: Boolean(workflowPrompt?.output),\n parentId: branchParentId\n }\n );\n status = streamResult.status;\n error = streamResult.error;\n }\n };\n\n await this._runChatRecoveryFiber(\n requestId,\n false,\n retryTurnBody,\n branchParentId\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 await this._cancelScheduledRecovery(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 const requestOriginIds = originMessageIds(incomingMessages);\n if (requestOriginIds) {\n this._requestOriginMessageIds.set(requestId, requestOriginIds);\n }\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 this._requestOriginMessageIds.delete(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 reconciledTurn = await this._reconcileAndPersistIncoming(\n incomingMessages,\n {\n requestId,\n isRegeneration,\n isCurrent: () => this._turnQueue.generation === epoch,\n channel: \"web\"\n }\n );\n if (!reconciledTurn) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n const { branchParentId } = reconciledTurn;\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 channel: \"web\",\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 {\n signal: abortSignal,\n clientTools: clientToolsForTurn,\n body: bodyForTurn,\n continuation: false\n },\n branchParentId\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 await this._runChatRecoveryFiber(\n requestId,\n false,\n chatTurnBody,\n branchParentId\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 outcome: \"skipped\"\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 this._requestOriginMessageIds.delete(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._lastTurnChannel = undefined;\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 void this.keepAliveWhile(() => this._cancelScheduledRecovery(requestId));\n }\n\n /**\n * A cancel can land while the turn's recovery is waiting out its backoff,\n * with nothing in flight to abort: cancel the scheduled recovery instead,\n * so the queued callback bails when it fires.\n */\n private async _cancelScheduledRecovery(requestId: string): Promise<void> {\n try {\n await this._chatRecoveryEngine().cancelScheduledRecovery(requestId);\n } catch (error) {\n console.error(\n \"[Think] failed to cancel a scheduled chat recovery\",\n error\n );\n }\n }\n\n /**\n * Whether the user cancelled this recovery while it was scheduled. A\n * submission the recovery owned settles as `aborted`.\n */\n private async _recoveryCancelled(\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined\n ): Promise<boolean> {\n if (\n !(await this._chatRecoveryEngine().isRecoveryCancelled(data?.incidentId))\n )\n return false;\n if (data?.recoveredRequestId) {\n await this._completeRecoveredSubmission(\n data.recoveredRequestId,\n \"aborted\",\n null,\n null\n );\n }\n return true;\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; inputText?: string }\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 } else if (\n chunk.type === \"tool-input-delta\" &&\n typeof chunk.inputTextDelta === \"string\"\n ) {\n const previous = pendingActionCalls.get(toolCallId);\n if (previous) {\n pendingActionCalls.set(toolCallId, {\n ...previous,\n inputText: (previous.inputText ?? \"\") + chunk.inputTextDelta\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:\n pending.input ??\n (pending.inputText !== undefined\n ? normalizeToolInput(pending.inputText).input\n : {}),\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 persistedAssistantId: string | undefined;\n // Set once the stream is fully consumed and end-of-turn persistence and\n // hooks begin. A failure past this point is not a stream interruption, so\n // it must never route into recovery (the turn already has its answer).\n let streamDrained = false;\n let aborted = false;\n let doneSent = false;\n let streamError: string | undefined;\n let streamErrorCause: unknown;\n let pendingRpcError: string | undefined;\n let thrownError: 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; inputText?: string }\n >();\n const approvalRequests = new Map<string, StreamChunkData>();\n try {\n const guardedStream = iterateWithStallWatchdog(\n result.toUIMessageStream({\n onError: (error) => {\n streamErrorCause = error;\n return streamErrorToString(error);\n }\n }),\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 lateToolInput = isLateToolInputChunk(\n accumulator.parts,\n streamChunk\n );\n if (streamChunk.type === \"tool-approval-request\") {\n approvalRequests.set(streamChunk.toolCallId ?? \"\", streamChunk);\n }\n const { action } = accumulator.applyChunk(streamChunk);\n this._applyActionApprovalDescriptorToParts(\n streamChunk,\n accumulator.parts\n );\n if (lateToolInput) {\n for (const forwarded of lateToolInputForwardChunks(\n accumulator.parts,\n streamChunk,\n approvalRequests.get(streamChunk.toolCallId ?? \"\")\n )) {\n const chunkBody = JSON.stringify(forwarded);\n const seq = await this._storeChunkDurably(\n streamId,\n forwarded,\n chunkBody,\n flushState\n );\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: chunkBody,\n done: false,\n ...(seq !== undefined && { seq })\n });\n await callback.onEvent(chunkBody);\n }\n continue;\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 const classification = this._classifyStreamError(\n streamErrorCause ?? streamError,\n requestId\n );\n if (\n options?.overflowRecovery &&\n this._isRecoverableContextOverflow(classification)\n ) {\n overflowRetry = true;\n break;\n }\n if (\n isTransientClassification(classification) &&\n !isDurableObjectResetError(streamErrorCause ?? streamError)\n ) {\n throw new TransientChatStreamError(\n streamError,\n classification,\n streamErrorCause\n );\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 const seq = 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 ...(seq !== undefined && { seq })\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._completeSubmissionRetryStream(streamId, requestId);\n streamFinalized = true;\n return { status: \"overflow_retry\", error: streamError };\n }\n\n streamDrained = true;\n if (streamError) {\n this._errorResumableStream(streamId, requestId);\n } else {\n this._finishResumableStream(\n streamId,\n aborted ? \"aborted\" : \"completed\"\n );\n }\n streamFinalized = true;\n\n assistantMsg = accumulator.toMessage();\n const response: ChatResponseResult = {\n message: assistantMsg,\n requestId,\n continuation: false,\n status: streamError ? \"error\" : aborted ? \"aborted\" : \"completed\",\n ...(streamError && { error: streamError })\n };\n if (accumulator.parts.length > 0) {\n await this._rememberPendingResponseHook(response);\n persistedAssistantId = await this._persistAssistantMessageWithCutover(\n streamId,\n assistantMsg,\n undefined,\n this._streamCutoverOptions(requestId),\n { requestId, result: { status: aborted ? \"aborted\" : \"completed\" } }\n );\n this._broadcastMessages();\n }\n // After the transcript broadcast: `done` flips `useAgentChat` to ready,\n // and a later snapshot would drop a message sent in between (#2119).\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true,\n outcome: response.status\n });\n doneSent = true;\n // A stripped/empty response still records its outcome with settlement.\n this._finalizeSubmissionStream(requestId, {\n status: aborted ? \"aborted\" : \"completed\"\n });\n\n if (streamError) {\n pendingRpcError = streamError;\n } else if (!aborted) {\n await callback.onDone();\n }\n await this._fireLiveResponseHook(response);\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 // Errors the app classifies as transient/rate_limit take the same route,\n // unless the caller aborted the turn.\n const stalled = error instanceof ChatStreamStalledError;\n const transientClassification =\n stalled || streamDrained || abortSignal?.aborted\n ? undefined\n : this._transientStreamClassification(error, requestId);\n if (!streamDrained && (stalled || transientClassification)) {\n const outcome = await this._routeStreamInterruption({\n requestId,\n streamId,\n backoff: !stalled,\n retryAfterSeconds: this._streamErrorRetryAfter(\n error,\n transientClassification\n ),\n partialParts: accumulator.toMessage().parts,\n persistPartial: async () => {\n if (persistedAssistantId) return persistedAssistantId;\n if (accumulator.parts.length === 0) return undefined;\n const partial = accumulator.toMessage();\n if (!(await this._persistAssistantMessage(partial))) {\n return undefined;\n }\n assistantMsg = partial;\n persistedAssistantId = partial.id;\n this._broadcastMessages();\n return persistedAssistantId;\n }\n });\n if (outcome === \"scheduled\") {\n if (!streamFinalized) {\n this._completeResumableStream(streamId, \"recovering\");\n streamFinalized = true;\n }\n if (!doneSent) {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true,\n outcome: \"recovering\"\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 this._messengerRecoveryClaims.delete(requestId)\n ? { deliversRecoveredReply: true }\n : undefined\n );\n return { status: \"aborted\" };\n }\n if (outcome === \"exhausted\" || outcome === \"declined\") {\n // `_routeStallToBoundedRecovery` already delivered the terminal UX\n // (exhaustion: configured `terminalMessage` + `onExhausted`; declined:\n // the declined message), with the done/error frame and the submission\n // marked interrupted. Finalize the stream and return WITHOUT the\n // generic terminal path, which would re-broadcast the raw stall error.\n if (!streamFinalized) {\n this._errorResumableStream(streamId, requestId);\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 }\n // A finished stream whose final persist threw still awaits its cutover.\n if (\n !streamFinalized ||\n this._resumableStream.pendingCutoverId === streamId\n ) {\n this._errorResumableStream(streamId, requestId);\n streamFinalized = true;\n }\n try {\n if (!assistantMsg && accumulator.parts.length > 0) {\n assistantMsg = accumulator.toMessage();\n await this._persistAssistantMessage(assistantMsg);\n this._broadcastMessages();\n }\n } finally {\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\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 thrownError = errorMessage;\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._fireLiveResponseHook({\n message: assistantMsg,\n requestId,\n continuation: false,\n status: \"error\",\n error: errorMessage\n });\n } else {\n await this._forgetPendingResponseHook(requestId).catch(() => {});\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 const error = thrownError ?? pendingRpcError ?? streamError;\n if (error !== undefined) return { status: \"error\", error };\n return { status: aborted ? \"aborted\" : \"completed\" };\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<number | undefined> {\n const seq = 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 needs no write of its own: the flush above IS the\n // durable record of new content, and the recovery marker is derived from\n // the stream log (`_chatRecoveryProgressMarker`). A reconnect replay or a\n // recovery re-persist reads the log without appending, so neither can\n // fake progress (#1637), and compaction never touches it (#1628).\n return seq;\n }\n\n private async _streamResult(\n requestId: string,\n result: StreamableResult,\n abortSignal?: AbortSignal,\n options?: {\n continuation?: boolean;\n parentId?: string;\n captureProgrammaticStreamError?: boolean;\n captureOutput?: boolean;\n /**\n * 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 * Stream into the assistant leaf (same id, existing parts) instead of a\n * new assistant message. Recovery continuations set this so an\n * interrupted answer stays one message (#1876); other continuations keep\n * the documented `continueLastTurn()` behavior of a separate message.\n */\n extendLeafAssistant?: boolean;\n }\n ): Promise<StreamResultStatus> {\n const clearGen = this._turnQueue.generation;\n const continuation = options?.continuation ?? false;\n const parentId = options?.parentId;\n const streamId = this._startResumableStream(requestId, {\n continuation,\n ...(parentId !== undefined && { parentMessageId: parentId })\n });\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 leaf = this.messages.at(-1);\n const continuationAssistant =\n continuation && options?.extendLeafAssistant && leaf?.role === \"assistant\"\n ? leaf\n : undefined;\n const leafMetadata = continuationAssistant?.metadata;\n const accumulator = new StreamAccumulator({\n messageId: continuationAssistant?.id ?? crypto.randomUUID(),\n continuation: continuationAssistant !== undefined,\n existingParts: continuationAssistant?.parts.map(settleInterruptedPart),\n existingMetadata:\n leafMetadata !== null && typeof leafMetadata === \"object\"\n ? (leafMetadata as Record<string, unknown>)\n : undefined\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 // The terminal frame flips `useAgentChat` to ready, so it is held until\n // the assistant message is persisted and the transcript broadcast (#2119).\n let terminalFrame: Record<string, unknown> | undefined;\n let streamAborted = false;\n let streamError: string | undefined;\n let streamErrorCause: unknown;\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; inputText?: string }\n >();\n const approvalRequests = new Map<string, StreamChunkData>();\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({\n onError: (error) => {\n streamErrorCause = error;\n return streamErrorToString(error);\n }\n }),\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 = withoutOverwrittenStartMetadata(\n this._annotateActionApprovalChunk(\n requestId,\n chunk as unknown as StreamChunkData,\n pendingActionCalls,\n accumulator.parts\n ),\n continuationAssistant ? leafMetadata : undefined\n );\n const lateToolInput = isLateToolInputChunk(\n accumulator.parts,\n streamChunk\n );\n if (streamChunk.type === \"tool-approval-request\") {\n approvalRequests.set(streamChunk.toolCallId ?? \"\", streamChunk);\n }\n const { action } = accumulator.applyChunk(streamChunk);\n this._applyActionApprovalDescriptorToParts(\n streamChunk,\n accumulator.parts\n );\n if (lateToolInput) {\n for (const forwarded of lateToolInputForwardChunks(\n accumulator.parts,\n streamChunk,\n approvalRequests.get(streamChunk.toolCallId ?? \"\")\n )) {\n const chunkBody = JSON.stringify(forwarded);\n const seq = await this._storeChunkDurably(\n streamId,\n forwarded,\n chunkBody,\n flushState\n );\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: chunkBody,\n done: false,\n ...(seq !== undefined && { seq }),\n ...(continuation && { continuation: true })\n });\n }\n continue;\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 const classification = this._classifyStreamError(\n streamErrorCause ?? streamError,\n requestId\n );\n if (\n options?.overflowRecovery &&\n this._isRecoverableContextOverflow(classification)\n ) {\n overflowRetry = true;\n break;\n }\n if (\n isTransientClassification(classification) &&\n !isDurableObjectResetError(streamErrorCause ?? streamError)\n ) {\n throw new TransientChatStreamError(\n streamError,\n classification,\n streamErrorCause\n );\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 const seq = 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 ...(seq !== undefined && { seq }),\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._completeSubmissionRetryStream(streamId, requestId);\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, requestId);\n } else {\n this._finishResumableStream(\n streamId,\n streamAborted ? \"aborted\" : \"completed\"\n );\n }\n this._pendingResumeConnections.clear();\n terminalFrame = {\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true,\n outcome: streamError\n ? \"error\"\n : streamAborted\n ? \"aborted\"\n : \"completed\",\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. Errors the app classifies as transient/rate_limit\n // take the same route, unless the caller aborted the turn.\n const stalled = error instanceof ChatStreamStalledError;\n const transientClassification =\n stalled || abortSignal?.aborted\n ? undefined\n : this._transientStreamClassification(error, requestId);\n if (stalled || transientClassification) {\n const partialMsg = accumulator.toMessage();\n const outcome = await this._routeStreamInterruption({\n requestId,\n streamId,\n backoff: !stalled,\n retryAfterSeconds: this._streamErrorRetryAfter(\n error,\n transientClassification\n ),\n partialParts: partialMsg.parts,\n branchParentId: parentId,\n persistPartial: async () => {\n if (\n this._turnQueue.generation !== clearGen ||\n accumulator.parts.length === 0\n ) {\n return undefined;\n }\n if (!(await this._persistAssistantMessage(partialMsg, parentId))) {\n return undefined;\n }\n this._broadcastMessages();\n return partialMsg.id;\n }\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, \"recovering\");\n this._pendingResumeConnections.clear();\n if (!doneSent) {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true,\n outcome: \"recovering\",\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\" || outcome === \"declined\") {\n // `_routeStallToBoundedRecovery` already delivered the terminal UX\n // (exhaustion: configured `terminalMessage` + `onExhausted`; declined:\n // the declined message), with the done/error frame and the submission\n // marked interrupted. Finalize the stream and report `aborted` (not\n // `error`) so the caller does not re-run the generic terminal path.\n this._errorResumableStream(streamId, requestId);\n this._pendingResumeConnections.clear();\n doneSent = true;\n this._streamingAssistant = null;\n return { status: \"aborted\" };\n }\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, requestId);\n this._pendingResumeConnections.clear();\n if (!doneSent) {\n terminalFrame = {\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, requestId);\n this._pendingResumeConnections.clear();\n terminalFrame = {\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true,\n ...(continuation && { continuation: true })\n };\n }\n }\n\n const sendTerminalFrame = () => {\n if (!terminalFrame) return;\n this._broadcastChat(terminalFrame);\n terminalFrame = undefined;\n };\n\n try {\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 this._errorResumableStream(streamId, requestId);\n if (terminalFrame) {\n terminalFrame = { ...terminalFrame, outcome: \"error\" };\n }\n }\n }\n\n const submissionResult: SubmissionTurnResult = streamAborted\n ? { status: \"aborted\" }\n : { status: \"completed\", output };\n if (this._turnQueue.generation === clearGen) {\n try {\n const assistantMsg = accumulator.toMessage();\n const response: ChatResponseResult = {\n message: assistantMsg,\n requestId,\n continuation,\n status: streamError\n ? \"error\"\n : streamAborted\n ? \"aborted\"\n : \"completed\",\n error: streamError\n };\n\n if (accumulator.parts.length > 0) {\n await this._rememberPendingResponseHook(response);\n const persistedMessageId =\n await this._persistAssistantMessageWithCutover(\n streamId,\n assistantMsg,\n parentId,\n this._streamCutoverOptions(requestId),\n { requestId, result: submissionResult }\n );\n if (\n !streamError &&\n !streamAborted &&\n persistedMessageId !== undefined\n ) {\n const capture = waitTurnResultContext.getStore();\n if (capture?.agent === this) {\n capture.messageIds.set(requestId, persistedMessageId);\n }\n }\n this._broadcastMessages();\n }\n sendTerminalFrame();\n // Nothing user-facing to persist (e.g. only a final-answer tool): the\n // output and terminal outcome still commit with stream settlement.\n this._finalizeSubmissionStream(requestId, submissionResult);\n\n await this._fireLiveResponseHook(response);\n } catch (e) {\n await this._forgetPendingResponseHook(requestId).catch(() => {});\n console.error(\"Failed to persist assistant message:\", e);\n streamError =\n e instanceof Error\n ? e.message\n : \"Assistant message persistence failed\";\n this._errorResumableStream(streamId, requestId);\n if (terminalFrame && !terminalFrame.error) {\n terminalFrame = {\n ...terminalFrame,\n body: streamError,\n error: true,\n outcome: \"error\"\n };\n }\n }\n }\n this._finalizeSubmissionStream(requestId, submissionResult);\n } finally {\n sendTerminalFrame();\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 /** Resolves to `false` when stripping left nothing to persist. */\n private async _persistAssistantMessage(\n msg: UIMessage,\n parentId?: string\n ): Promise<boolean> {\n const toPersist = this._strippedForPersist(msg);\n if (toPersist === null) return false;\n await this._upsertMessageInHistory(toPersist, parentId);\n return true;\n }\n\n /**\n * The cutover: persist the finished turn's assistant message, settle its\n * resumable stream and delete the stream's rows in ONE SQLite transaction,\n * so a crash leaves either the live stream (recovery rebuilds the message\n * from it) or the message — never neither, never both. The session\n * change feed and auto-compaction run once the transaction has committed.\n */\n private async _persistAssistantMessageWithCutover(\n streamId: string,\n msg: UIMessage,\n parentId?: string,\n options: { discard?: boolean } = {},\n submission?: { requestId: string; result: SubmissionTurnResult }\n ): Promise<string | undefined> {\n const toPersist = this._strippedForPersist(msg);\n if (toPersist === null) return undefined;\n if (this._resumableStream.pendingCutoverId !== streamId) {\n // The stream was settled by another path (a stall, an error): plain persist.\n await this._upsertMessageInHistory(toPersist, parentId);\n if (submission) {\n this._recordSubmissionMessage(submission.requestId, toPersist.id);\n }\n return toPersist.id;\n }\n const sync = this.sessions.session().__DO_NOT_USE_WILL_BREAK__sync();\n let after: (() => Promise<void>) | undefined;\n try {\n this._resumableStream.cutover(\n streamId,\n () => {\n after = sync.upsert(toPersist as SessionMessage, {\n parentId,\n source: \"server\"\n }).after;\n if (submission) {\n this._recordSubmissionTurnResult(\n submission.requestId,\n submission.result,\n toPersist.id\n );\n }\n },\n options\n );\n } catch (error) {\n // The settle transaction rolled back: the row never landed, but the\n // session's in-memory caches already counted it.\n sync.abandon();\n throw error;\n }\n await after?.();\n return toPersist.id;\n }\n\n /**\n * Whether this turn's stream rows can go with its cutover. An agent-tool\n * child turn keeps them: the parent tails the stored chunks after the\n * child completes (`getAgentToolChunks`), so the rows are reclaimed by\n * the child's next `start()` instead, as `AIChatAgent` does. A running\n * submission needs no stream evidence: its durable outcome stamp commits\n * in the same transaction as this cutover.\n */\n private _streamCutoverOptions(requestId: string): { discard: boolean } {\n return { discard: !this._agentToolRunsByRequestId.get(requestId) };\n }\n\n /** Write only inside the transaction that settles this exact request's stream. */\n private _recordSubmissionTurnResult(\n requestId: string,\n result: SubmissionTurnResult,\n messageId?: string\n ): void {\n const row = this._readRunningSubmissionForRecovery(requestId);\n if (!row || row.request_id !== requestId) {\n if (messageId) this._recordAbortedSubmissionMessage(requestId, messageId);\n return;\n }\n this.sql`\n UPDATE cf_think_submissions\n SET result_status = ${result.status},\n output_json = ${result.status === \"completed\" && result.output !== undefined ? JSON.stringify(result.output) : null},\n message_id = COALESCE(${messageId ?? null}, message_id)\n WHERE submission_id = ${row.submission_id} AND status = 'running'\n `;\n }\n\n private _recordSubmissionMessage(requestId: string, messageId: string): void {\n const row = this._readRunningSubmissionForRecovery(requestId);\n if (!row || row.request_id !== requestId) {\n this._recordAbortedSubmissionMessage(requestId, messageId);\n return;\n }\n this.sql`\n UPDATE cf_think_submissions\n SET message_id = ${messageId}\n WHERE submission_id = ${row.submission_id} AND status = 'running'\n `;\n }\n\n /**\n * Cancellation settles a submission as `aborted` before the stream persists\n * its partial; link that message without touching the terminal status. A\n * row that never started (a reused submission id cancelled while queued)\n * cannot own the partial.\n */\n private _recordAbortedSubmissionMessage(\n requestId: string,\n messageId: string\n ): void {\n this.sql`\n UPDATE cf_think_submissions\n SET message_id = ${messageId}\n WHERE request_id = ${requestId}\n AND status = 'aborted'\n AND started_at IS NOT NULL\n AND message_id IS NULL\n `;\n }\n\n /** Empty/stripped messages have the same atomic outcome cutover as messages. */\n private _finalizeSubmissionStream(\n requestId: string,\n result: SubmissionTurnResult\n ): void {\n if (this._resumableStream.pendingCutoverId === null) return;\n this.ctx.storage.transactionSync(() => {\n this._resumableStream.finalizePending();\n this._recordSubmissionTurnResult(requestId, result);\n });\n }\n\n /** Keep overflow chunks for consumers, but never call that segment an answer. */\n private _completeSubmissionRetryStream(\n streamId: string,\n requestId: string\n ): void {\n this.ctx.storage.transactionSync(() => {\n this._completeResumableStream(streamId);\n this._recordSubmissionTurnResult(requestId, { status: \"retry\" });\n });\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 * Turn-start persistence of the client's transcript: reconcile the posted\n * messages against the server's active path, write only what changed, and\n * leave the live cache current. Returns `null` when a newer request\n * superseded this one part-way through (`isCurrent` turned false).\n *\n * Storage traffic here is independent of transcript length: the server\n * transcript comes from the live cache when it covers the path, unchanged\n * echoed messages are skipped before Sessions is asked, and the cache is\n * re-read only when it is windowed.\n */\n private async _reconcileAndPersistIncoming(\n incomingMessages: UIMessage[],\n options: {\n requestId: string;\n isRegeneration: boolean;\n isCurrent: () => boolean;\n /** Channel stamped on user messages the server has not stored yet. */\n channel?: string;\n }\n ): Promise<{ branchParentId: string | undefined } | null> {\n const spanAttributes = {\n \"cloudflare.agents.component\": \"think\",\n \"cloudflare.agents.turn.request_id\": options.requestId,\n \"cloudflare.agents.turn.trigger\": \"ws-chat\"\n };\n const serverMessages = await withAgentSpan(\n this,\n \"load_chat_history\",\n \"interaction\",\n spanAttributes,\n () => this._serverTranscriptForReconcile()\n );\n const serverMessagesById = new Map(\n serverMessages.map((message) => [message.id, message])\n );\n const reconciled = keepResolvedPauses(\n reconcileMessages(incomingMessages, serverMessages, sanitizeMessage),\n serverMessages\n );\n\n let branchParentId: string | undefined;\n if (options.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 spanAttributes,\n async () => {\n if (!options.isCurrent()) return false;\n\n for (const msg of reconciled) {\n if (!options.isCurrent()) return false;\n await this._persistIncomingMessage(\n msg,\n serverMessagesById,\n options.channel\n );\n }\n\n if (!options.isCurrent()) return false;\n // The change feed patched the cache for every write above (a linear\n // append lands in place; a branch append already forced a full\n // refresh), so a cache that covers the path is current. Only a\n // windowed or unhydrated cache needs storage to re-derive its view.\n if (!this._cacheCoversActivePath) {\n await this._syncMessages();\n }\n return true;\n }\n );\n return persisted ? { branchParentId } : null;\n }\n\n /**\n * The server transcript that reconciliation diffs client messages against.\n * The live cache answers when it holds the whole active path — the common\n * case, kept current by the change feed after every durable write. A\n * windowed or unhydrated cache falls back to the full storage read, since\n * reconciliation must see every message (`_readMessagesFromStorage`).\n *\n * Returns a snapshot: the writes that follow patch the cache through the\n * change feed while the caller is still iterating.\n */\n private async _serverTranscriptForReconcile(): Promise<UIMessage[]> {\n if (this._cacheCoversActivePath) return [...this._cachedMessages];\n return this._readMessagesFromStorage();\n }\n\n /**\n * Persist an incoming message after batch reconciliation has resolved\n * assistant IDs (one-to-one against server rows) and merged any\n * server-owned tool outputs.\n *\n * A message whose stored form is what the server already holds is skipped\n * outright. The client posts its whole transcript on every request, so\n * without this every prior message would cost Sessions an existence read\n * plus a full-row compare (and, for media, a decode and hash of every\n * payload) per turn — reads spent discovering nothing changed.\n *\n * Reserved metadata (`channel`, `turnMetadata`) is server-owned. The client's\n * copy is ignored, a stored row keeps its own, and a new user message gets\n * `channel` when the caller supplies one.\n */\n private async _persistIncomingMessage(\n msg: UIMessage,\n serverMessagesById?: ReadonlyMap<string, UIMessage>,\n channel?: string\n ): Promise<void> {\n const prior = serverMessagesById?.get(msg.id);\n const incoming = stripReservedMetadata(sanitizeMessage(msg));\n if (\n prior &&\n JSON.stringify(stripReservedMetadata(prior)) === JSON.stringify(incoming)\n ) {\n return;\n }\n const reserved = prior\n ? reservedMetadataOf(prior)\n : incoming.role === \"user\" && channel\n ? { channel }\n : undefined;\n if (!reserved) {\n await this._upsertMessageInHistory(msg, undefined, \"client\");\n return;\n }\n await this._upsertMessageInHistory(\n {\n ...incoming,\n metadata: {\n ...(incoming.metadata as Record<string, unknown> | undefined),\n ...reserved\n }\n },\n undefined,\n \"server\"\n );\n }\n\n /**\n * The serialized form last written to (or read from) `think_config` for a\n * request-context key. Every chat request re-sends its client tools and\n * body; comparing here turns the per-request write into a no-op when\n * nothing changed. `undefined` means \"not persisted\" (row absent).\n */\n private _persistedRequestContext: {\n lastClientTools?: string;\n lastBody?: string;\n } = {};\n\n private _persistRequestContextKey(\n key: \"lastClientTools\" | \"lastBody\",\n value: unknown\n ): void {\n const json = value ? JSON.stringify(value) : undefined;\n if (this._persistedRequestContext[key] === json) return;\n if (json === undefined) {\n this._configDelete(key);\n } else {\n this._configSet(key, json);\n }\n this._persistedRequestContext[key] = json;\n }\n\n private _persistClientTools(): void {\n this._persistRequestContextKey(\"lastClientTools\", this._lastClientTools);\n }\n\n private _restoreClientTools(): void {\n const raw = this._configGet(\"lastClientTools\");\n this._persistedRequestContext.lastClientTools = raw;\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 this._persistRequestContextKey(\"lastBody\", this._lastBody);\n }\n\n private _restoreBody(): void {\n const raw = this._configGet(\"lastBody\");\n this._persistedRequestContext.lastBody = raw;\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 * Pass `{ autoContinue: false }` to record the rejection without starting a\n * model continuation.\n *\n * Client-callable.\n */\n async rejectExecution(\n executionId: string,\n reason?: string,\n options?: RejectExecutionOptions\n ): Promise<unknown> {\n if (executionId.startsWith(ACTION_PAUSE_ID_PREFIX)) {\n return await this._rejectActionPause(executionId, reason, options);\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, options);\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 options?: RejectExecutionOptions\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, options);\n return output;\n }\n\n /**\n * Replace a paused execute-tool or durable-action output in the transcript\n * with the execution's new outcome and kick the auto-continuation so the\n * model sees 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 framework-authored system note,\n * and the continuation still fires so the model can act on it. Provider\n * assembly projects this narrowly identified note to ordinary user context\n * without changing its durable authorship.\n */\n private async _applyExecutionOutcome(\n executionId: string,\n output: unknown,\n options?: RejectExecutionOptions\n ): Promise<boolean> {\n const toolCallId = await this._findExecutionToolCallDurably(\n executionId,\n true\n );\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 ((await this._findExecutionToolCallDurably(executionId)) != null) {\n return false;\n }\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 const outcomeSource = executionId.startsWith(ACTION_PAUSE_ID_PREFIX)\n ? \"durable action\"\n : \"execute tool\";\n await this._appendMessageToHistory({\n id: `${EXECUTION_OUTCOME_MESSAGE_PREFIX}${executionId}-${crypto.randomUUID()}`,\n role: \"system\",\n parts: [\n {\n type: \"text\",\n text:\n `[${outcomeSource}] 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(async () => {\n // Recorded before the outcome is written, so a restart before either\n // write lands still applies both before the next inference.\n await this._rememberResolvedPause(toolCallId, { executionId, output });\n await this._applyToolUpdateToMessages(\n pausedExecutionUpdate(toolCallId, executionId, output)\n );\n await this._dropGenerationAfterResolvedPause(toolCallId);\n });\n }\n if (options?.autoContinue === false) {\n // No continuation will run the deferred drop, so apply it once the\n // parking turn has persisted its message.\n if (toolCallId && this._deferredResolvedPauses.has(toolCallId)) {\n if (this._streamingAssistant) {\n this._flushResolvedPausesOnFinalize = true;\n } else {\n await this._enqueueInteractionApply(() =>\n this._flushDeferredResolvedPauses()\n );\n }\n }\n // Re-arm the barrier so a sibling that already opted in fires once the\n // batch is whole, matching the client tool-result/approval path.\n this._rearmPendingAutoContinuationForBatch();\n return true;\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 await this._queueConnectionlessContinuation();\n }\n return true;\n }\n\n /**\n * Find the tool part carrying `executionId` in its output — in the in-flight\n * streaming accumulator first (an approval can land while a new turn\n * streams), then the in-memory transcript, newest message first. 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 streaming = this._streamingAssistant;\n if (streaming) {\n const found = executionToolCallIn(\n { role: \"assistant\", parts: streaming.parts } as unknown as UIMessage,\n executionId,\n pausedOnly\n );\n if (found) return found;\n }\n\n for (let i = this.messages.length - 1; i >= 0; i--) {\n const found = executionToolCallIn(\n this.messages[i],\n executionId,\n pausedOnly\n );\n if (found) return found;\n }\n return null;\n }\n\n /**\n * {@link _findExecutionToolCall}, falling back to storage when the hydrated\n * window does not cover the whole transcript, so a long-lived pause is\n * still resolved in place.\n */\n private async _findExecutionToolCallDurably(\n executionId: string,\n pausedOnly = false\n ): Promise<string | null> {\n const found = this._findExecutionToolCall(executionId, pausedOnly);\n if (found || this._cacheCoversActivePath) return found;\n for await (const message of this.session.history({ newestFirst: true })) {\n const stored = executionToolCallIn(\n message as UIMessage,\n executionId,\n pausedOnly\n );\n if (stored) return stored;\n }\n return null;\n }\n\n /**\n * Text and reasoning the model wrote after a paused tool result were written\n * against the pending state (\"once approved, ...\"). Once the pause resolves\n * they contradict the result, so drop them before the continuation reads the\n * transcript. Tool, file, and other parts after the pause stay.\n *\n * While the turn that paused is still streaming, its accumulator owns the\n * message and appends deltas to the last text part, so parts cannot be\n * removed underneath it. The drop is deferred to the next inference, which\n * is queued behind that turn and runs after it persists.\n *\n * The resolved pause stays recorded (see `_rememberResolvedPause`) until\n * the drop has been applied.\n */\n private async _dropGenerationAfterResolvedPause(\n toolCallId: string\n ): Promise<void> {\n const streaming = this._streamingAssistant;\n if (\n streaming?.parts.some(\n (part) => \"toolCallId\" in part && part.toolCallId === toolCallId\n )\n ) {\n return;\n }\n const owner = await this._resolveToolCallOwner(toolCallId, undefined);\n const parts = owner\n ? dropGenerationAfterToolCall(owner.parts, toolCallId)\n : undefined;\n if (owner && parts && parts !== owner.parts) {\n const safe = await this._updateMessageInHistory({ ...owner, parts });\n this._patchCachedMessage(safe);\n this._broadcast({ type: MSG_MESSAGE_UPDATED, message: safe });\n }\n await this._forgetResolvedPause(toolCallId);\n }\n\n private _loadResolvedPauses(): Promise<void> {\n this._deferredResolvedPausesLoad ??= (async () => {\n const stored = await this.ctx.storage.get<\n Array<[string, ResolvedPauseOutcome]>\n >(DEFERRED_RESOLVED_PAUSES_KEY);\n for (const [toolCallId, outcome] of stored ?? []) {\n if (!this._deferredResolvedPauses.has(toolCallId)) {\n this._deferredResolvedPauses.set(toolCallId, outcome);\n }\n }\n })().catch((error: unknown) => {\n // Let the next caller retry instead of treating the key as empty.\n this._deferredResolvedPausesLoad = undefined;\n throw error;\n });\n return this._deferredResolvedPausesLoad;\n }\n\n private async _rememberResolvedPause(\n toolCallId: string,\n outcome: ResolvedPauseOutcome\n ): Promise<void> {\n await this._loadResolvedPauses();\n this._deferredResolvedPauses.set(toolCallId, outcome);\n await this.ctx.storage.put(DEFERRED_RESOLVED_PAUSES_KEY, [\n ...this._deferredResolvedPauses\n ]);\n }\n\n private async _forgetResolvedPause(toolCallId: string): Promise<void> {\n await this._loadResolvedPauses();\n if (!this._deferredResolvedPauses.delete(toolCallId)) return;\n if (this._deferredResolvedPauses.size === 0) {\n await this.ctx.storage.delete(DEFERRED_RESOLVED_PAUSES_KEY);\n } else {\n await this.ctx.storage.put(DEFERRED_RESOLVED_PAUSES_KEY, [\n ...this._deferredResolvedPauses\n ]);\n }\n }\n\n private async _flushDeferredResolvedPauses(): Promise<void> {\n await this._loadResolvedPauses();\n for (const [toolCallId, outcome] of [...this._deferredResolvedPauses]) {\n // Still paused: a restart landed before the outcome was written, and the\n // execution it resolved is already consumed, so write it now. The owner\n // is looked up in storage when the hydrated window does not hold it.\n const owner = await this._resolveToolCallOwner(toolCallId, undefined);\n if (owner && ownsPausedToolCall(owner, toolCallId)) {\n await this._applyToolUpdateToMessages(\n pausedExecutionUpdate(toolCallId, outcome.executionId, outcome.output)\n );\n }\n await this._dropGenerationAfterResolvedPause(toolCallId);\n }\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 let accumulatorOwnsCall = false;\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) {\n accumulatorOwnsCall = true;\n if (result.parts[result.index] !== accParts[result.index]) {\n // `accParts` is a typed alias of the accumulator's live array, so\n // this in-place write is reflected by `streaming.toMessage()` and\n // the eventual end-of-stream persist.\n accParts[result.index] = result.parts[result.index];\n broadcastMessage = streaming.toMessage();\n }\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 //\n // The owning row is resolved without reading the transcript (see\n // `_resolveToolCallOwner`) and read as one row, so the apply stays a\n // first-write-wins read-modify-write of the STORED form: when `apply`\n // leaves the matched part untouched (same reference) — e.g. a provider\n // replay of an already-settled cross-message tool result (#1404) — there\n // is nothing to persist, and the durable write and the redundant\n // `MESSAGE_UPDATED` broadcast are both skipped so clients don't churn.\n const owner = await this._resolveToolCallOwner(\n update.toolCallId,\n accumulatorOwnsCall && streaming ? streaming.messageId : undefined\n );\n if (owner) {\n const ownerParts = owner.parts as Array<Record<string, unknown>>;\n const result = applyToolUpdate(ownerParts, update);\n if (result && result.parts[result.index] !== ownerParts[result.index]) {\n const updatedMsg = {\n ...owner,\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 // Patch the live cache in place instead of doing a full\n // `_syncMessages()` round-trip: a full re-read during a streaming\n // turn drops in-flight messages whose parent chain hasn't been\n // persisted yet (see commits 3f615a24 \"revert _syncMessages in\n // _applyToolUpdateToMessages\" and 6e76bd49 \"update cached messages\n // in-place\"). The cache is the source of truth during a turn; we only\n // reconcile it here to reflect the tool update just written.\n this._patchCachedMessage(safe);\n broadcastMessage = safe;\n }\n }\n\n if (broadcastMessage) {\n this._broadcast({\n type: MSG_MESSAGE_UPDATED,\n message: broadcastMessage\n });\n }\n }\n\n /**\n * The persisted message that owns `toolCallId`, read as one row — or\n * `null` when no persisted row owns it.\n *\n * Lookup order, cheapest first:\n *\n * 1. `liveMessageId`, when the in-flight accumulator owns the call. A row\n * under that id exists only when stall recovery persisted a partial\n * mid-stream. When it does not, the call is not on its own row — but a\n * provider can replay a prior tool round-trip into a fresh continuation\n * accumulator (#1404), so the persisted owner may still be an earlier\n * message; the cache is checked for that before concluding there is\n * nothing durable to update. Storage is never walked for a call the\n * live turn owns: every row it could target is on the cached path.\n * 2. The live cache, for the id only. Whatever names the row, the returned\n * message is always the STORED form: the apply must compare against\n * what storage holds, and the cache may be patched ahead of it.\n * 3. Storage, newest first, stopping at the first owner. Reached only when\n * the cache does not cover the active path (a windowed hydration, a\n * boot whose hydration failed, or rows imported behind the cache): a\n * cross-message result can target a row older than the window, and the\n * path is read from the leaf so a recent hit costs the rows it passed,\n * not the transcript.\n *\n * This is what keeps a long turn's tool updates independent of transcript\n * length: the previous shape re-read the whole path per update.\n */\n private async _resolveToolCallOwner(\n toolCallId: string,\n liveMessageId: string | undefined\n ): Promise<UIMessage | null> {\n const owns = (message: UIMessage): boolean =>\n message.parts.some(\n (part) => (part as { toolCallId?: unknown }).toolCallId === toolCallId\n );\n const stored = async (id: string): Promise<UIMessage | null> => {\n const row = (await this.session.getMessage(id)) as UIMessage | null;\n return row && owns(row) ? row : null;\n };\n const cachedOwnerId = (): string | null => {\n for (let i = this._cachedMessages.length - 1; i >= 0; i--) {\n if (owns(this._cachedMessages[i])) return this._cachedMessages[i].id;\n }\n return null;\n };\n\n if (liveMessageId !== undefined) {\n const live = await stored(liveMessageId);\n if (live) return live;\n const cachedId = cachedOwnerId();\n return cachedId === null ? null : stored(cachedId);\n }\n const cachedId = cachedOwnerId();\n if (cachedId !== null) return stored(cachedId);\n if (this._cacheCoversActivePath) return null;\n for await (const message of this.session.history({ newestFirst: true })) {\n if (owns(message as UIMessage)) return message as UIMessage;\n }\n return null;\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). It then became a KV counter bumped per\n * credited chunk. It is now derived from the stream log the chunks were\n * already flushed to (`ResumableStream.progressMarker`): the log only grows\n * when new content lands durably, a reconnect replay or a recovery\n * re-persist reads it without appending (#1637), and compaction rewrites\n * the transcript, not the log. Nothing is written per chunk.\n *\n * The pre-derivation KV counter is folded in once per isolate, so a marker\n * an in-flight incident already recorded is never read lower after the\n * upgrade.\n */\n private async _chatRecoveryProgressMarker(): Promise<number> {\n // Memoized as the promise, not a flag: two concurrent readers both wait\n // for the seed to land, so neither can hand the engine an unseeded\n // marker as an incident's work baseline. A failed read is not cached:\n // the next evaluation retries it instead of failing for the isolate's\n // life on a transient storage error.\n this._progressSeed ??= readChatRecoveryProgress(this.ctx.storage).then(\n (legacy) => this._resumableStream.seedProgress(legacy),\n (error: unknown) => {\n this._progressSeed = null;\n throw error;\n }\n );\n await this._progressSeed;\n return this._resumableStream.progressMarker();\n }\n\n private _progressSeed: Promise<void> | null = null;\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. The\n * child's output goes to clients, not to this object's stream log, so the\n * derived marker cannot see it; this is the one explicit credit left. 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 this._resumableStream.creditProgress();\n }\n }\n\n private async _beginChatRecoveryIncident(input: {\n requestId: string;\n recoveryRootRequestId?: string | null;\n latestUserMessageId?: string | null;\n recoveryKind: ChatRecoveryKind;\n trigger: \"interrupted\" | \"stalled\";\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 listActiveIncidents: async () =>\n (await listActiveChatRecoveryIncidents(this.ctx.storage)).map(\n ({ incident }) => incident\n ),\n putIncident: (key, incident) => this.ctx.storage.put(key, incident),\n syncStorage: () => this.ctx.storage.sync(),\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 if (event.type === \"chat:recovery:completed\") {\n this._settleMessengerRecovery(event.incidentId, \"completed\");\n } else if (\n event.type === \"chat:recovery:skipped\" ||\n (event.type === \"chat:recovery:failed\" &&\n !this._deferringRecoveryIncidents.has(event.incidentId))\n ) {\n this._settleMessengerRecovery(event.incidentId, \"interrupted\");\n }\n },\n scheduleRecovery: (callback, data, reason, delaySeconds) =>\n this._enqueueChatRecovery(callback, data, reason, delaySeconds),\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: (\n incident,\n config,\n partial,\n streamId,\n createdAt,\n originMessageIds\n ) =>\n this._exhaustChatRecovery(\n incident,\n config,\n partial,\n streamId,\n createdAt,\n originMessageIds\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 originMessageIds?: string[]\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) => {\n this._emit(\"chat:recovery:exhausted\", event);\n this._settleMessengerRecovery(incident.incidentId, \"interrupted\");\n },\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 const messageIds =\n this._originMessageIdsFor(ctx.requestId) ?? originMessageIds;\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: ctx.requestId,\n body: ctx.terminalMessage,\n done: true,\n error: true,\n ...(messageIds ? { messageIds } : {})\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 messageIds\n );\n // The recovery root locates the stable submission identity even\n // after request_id has been rebound to an accepted successor.\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 recovery, reusing the\n * SAME budget (`maxAttempts` + wall-clock window + progress-aware reset) and\n * the same `onChatRecovery` decision as deploy/eviction recovery (#2042). A\n * transient hang recovers; a persistently hanging provider exhausts the\n * budget. Idempotency matches deploy recovery: settled tool results are\n * durable and won't re-run, but a tool that was mid-execution when the stall\n * fired re-runs on the continuation.\n *\n * A stall before the first assistant chunk leaves the user's message as the\n * leaf, so there is nothing to continue: it schedules a retry of that user\n * turn instead (#1941).\n *\n * `persistPartial` saves the settled partial and resolves to its message id\n * (or `undefined` when nothing was saved). It runs unless `onChatRecovery`\n * returns `persist: false` and the partial holds no settled tool results.\n *\n * Returns:\n * - `\"scheduled\"` — recovery 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`).\n * - `\"declined\"` — `onChatRecovery` returned `continue: false`; the turn is\n * marked interrupted and the declined message is delivered.\n * - `\"failed\"` — `onChatRecovery` threw; the incident is marked `failed` and\n * the caller runs its generic terminal error path.\n *\n * For `\"exhausted\"` and `\"declined\"` the terminal UX is already delivered, so\n * the caller must NOT run the generic terminal path.\n */\n private async _routeStallToBoundedRecovery(\n input: StreamInterruptionRoute\n ): Promise<\"scheduled\" | \"exhausted\" | \"declined\" | \"failed\"> {\n const recoveryRootRequestId =\n this._activeChatRecoveryRootRequestId ?? input.requestId;\n const originIds = this._originMessageIdsFor(input.requestId);\n const latestUserMessageId =\n [...this.messages].reverse().find((m) => m.role === \"user\")?.id ?? null;\n const retryTargetUserId =\n input.partialParts.length === 0\n ? (input.branchParentId ?? (await this._latestUserLeafId()))\n : null;\n const recoveryKind: ChatRecoveryKind = retryTargetUserId\n ? \"retry\"\n : \"continue\";\n const { incident, config, exhausted } =\n await this._beginChatRecoveryIncident({\n requestId: input.requestId,\n recoveryRootRequestId,\n latestUserMessageId,\n recoveryKind,\n trigger: \"stalled\"\n });\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 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 await input.persistPartial();\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\n const liveTurn = this._liveChatRecoveryTurns.get(input.requestId);\n let options: ChatRecoveryOptions;\n try {\n options =\n (await this.onChatRecovery({\n incidentId: incident.incidentId,\n recoveryRootRequestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind,\n streamId: input.streamId,\n requestId: input.requestId,\n partialText,\n partialParts: input.partialParts,\n recoveryData: liveTurn?.recoveryData ?? null,\n messages: [...this.messages],\n lastBody: this._lastBody,\n lastClientTools: this._lastClientTools,\n createdAt: liveTurn?.createdAt ?? incident.firstSeenAt\n })) ?? {};\n } catch (error) {\n console.error(\n \"[Think] onChatRecovery threw during stall recovery:\",\n error\n );\n await input.persistPartial();\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"failed\",\n error instanceof Error ? error.message : String(error)\n );\n return \"failed\";\n }\n\n const targetAssistantId =\n options.persist !== false ||\n this._getPartialStreamText(input.streamId).hasSettledToolResults\n ? await input.persistPartial()\n : undefined;\n\n // If a durable submission is running for this turn, the recovery must\n // complete it (otherwise the submission hangs) — same as deploy recovery.\n const recoveredRequestId = this._readRunningSubmissionForRecovery(\n recoveryRootRequestId\n )?.submission_id;\n\n if (options.continue === false) {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"skipped\",\n \"continue_disabled\"\n );\n const declinedMessage =\n \"Submission was interrupted and automatic continuation was declined.\";\n await this._markRecoveredSubmissionInterrupted(\n recoveryRootRequestId,\n declinedMessage\n );\n await this._recordTerminalChatStatus(\n \"interrupted\",\n input.requestId,\n declinedMessage\n );\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: input.requestId,\n body: declinedMessage,\n done: true,\n error: true\n });\n return \"declined\";\n }\n\n // Re-read the leaf: `persist: false` can leave the user's message as the\n // leaf even when the stall produced a partial.\n const unansweredUserId = targetAssistantId\n ? null\n : input.partialParts.length === 0\n ? retryTargetUserId\n : (input.branchParentId ?? (await this._latestUserLeafId()));\n await this._claimMessengerRecoveryDelivery(\n input.requestId,\n incident.incidentId,\n partialText\n );\n // Stalls count too: a turn that streams a little and then stalls resets\n // the progress-keyed attempt cap every time, so this is its only bound.\n const retries = await this._chatRecoveryEngine().recordTransientRetry(\n incident.incidentId\n );\n const delaySeconds = input.backoff\n ? chatRecoveryBackoffSeconds(retries, input.retryAfterSeconds)\n : undefined;\n const reason =\n this._activeChatRecoveryRootRequestId !== undefined\n ? \"chained_retry\"\n : undefined;\n if (unansweredUserId) {\n await this._chatRecoveryEngine().scheduleRecovery({\n incident,\n delaySeconds,\n reason,\n recoveryKind: \"retry\",\n callback: \"_chatRecoveryRetry\",\n data: {\n targetUserId: unansweredUserId,\n ...(input.branchParentId !== undefined && {\n regeneratedLeafId: (await this.session.getLatestLeaf())?.id\n }),\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n lastBody: this._lastBody ?? null,\n lastClientTools: this._lastClientTools ?? null,\n ...(originIds ? { originMessageIds: originIds } : {}),\n ...(recoveredRequestId ? { recoveredRequestId } : {})\n }\n });\n this._rescheduledRecoveryIncidents.add(incident.incidentId);\n this._claimSubmissionForRecovery(recoveredRequestId, reason);\n return \"scheduled\";\n }\n\n await this._chatRecoveryEngine().scheduleRecovery({\n incident,\n delaySeconds,\n reason,\n recoveryKind: \"continue\",\n callback: \"_chatRecoveryContinue\",\n data: {\n ...(targetAssistantId ? { targetAssistantId } : {}),\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n lastBody: this._lastBody ?? null,\n lastClientTools: this._lastClientTools ?? null,\n ...(originIds ? { originMessageIds: originIds } : {}),\n ...(recoveredRequestId ? { recoveredRequestId } : {})\n }\n });\n this._rescheduledRecoveryIncidents.add(incident.incidentId);\n this._claimSubmissionForRecovery(recoveredRequestId, reason);\n return \"scheduled\";\n }\n\n /**\n * {@link _routeStallToBoundedRecovery} for a stream consumer's `catch`: a\n * routing failure (e.g. a rejected incident write) degrades to `\"failed\"`,\n * so the caller still delivers its terminal error frame.\n */\n private async _routeStreamInterruption(\n input: StreamInterruptionRoute\n ): Promise<\"scheduled\" | \"exhausted\" | \"declined\" | \"failed\"> {\n try {\n return await this._routeStallToBoundedRecovery(input);\n } catch (error) {\n console.error(\n \"[Think] routing a stream interruption into recovery failed; delivering the terminal error\",\n error\n );\n return \"failed\";\n }\n }\n\n /**\n * Submissions whose turn scheduled recovery: the recovery completes them,\n * so the submission runner must leave them `running`.\n */\n private _recoveryOwnedSubmissions = new Set<string>();\n\n private _claimSubmissionForRecovery(\n submissionId: string | undefined,\n reason: \"chained_retry\" | undefined\n ): void {\n // Inside a recovery attempt the callback already owns the submission.\n if (submissionId && reason === undefined) {\n this._recoveryOwnedSubmissions.add(submissionId);\n }\n }\n\n /**\n * Incidents marked `failed` only for observability while the platform\n * re-runs the same recovery attempt; their messenger reply stays pending.\n */\n private _deferringRecoveryIncidents = new Set<string>();\n\n /** Incidents whose running recovery attempt scheduled the next attempt. */\n private _rescheduledRecoveryIncidents = new Set<string>();\n\n private _takeRecoveryReschedule(incidentId: string | undefined): boolean {\n return (\n incidentId !== undefined &&\n this._rescheduledRecoveryIncidents.delete(incidentId)\n );\n }\n\n private async _latestUserLeafId(): Promise<string | null> {\n const leaf = await this.session.getLatestLeaf();\n return leaf?.role === \"user\" ? leaf.id : null;\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 const chatFiberPrefix =\n (this.constructor as typeof Think).CHAT_FIBER_NAME + \":\";\n if (\n ctx.name.startsWith(chatFiberPrefix) &&\n (await this._settlePersistedChatTurn(\n ctx.name.slice(chatFiberPrefix.length)\n ))\n ) {\n return true;\n }\n return this._recoverChatFiber(ctx);\n }\n\n /**\n * A turn that owes its response hook and already persisted its message\n * finished: its stream rows may be gone with the cutover, so recovery would\n * otherwise re-run it. Fire the owed hook and settle the submission instead.\n */\n private async _settlePersistedChatTurn(requestId: string): Promise<boolean> {\n const hook = await this.ctx.storage.get<PendingResponseHook>(\n PENDING_RESPONSE_HOOK_PREFIX + requestId\n );\n if (!hook || !(await this.session.getMessage(hook.messageId))) {\n return false;\n }\n await this._replayPendingResponseHooks(requestId);\n await this._completeRecoveredSubmission(\n requestId,\n hook.status === \"error\" ? \"error\" : \"completed\",\n requestId,\n hook.error ?? null\n );\n return true;\n }\n\n private _recoverChatFiber(ctx: FiberRecoveryContext): Promise<boolean> {\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 info = this._resumableStream.latestStreamInfoForRequest(requestId);\n if (info) {\n streamId = info.id;\n streamStatus = info.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 turn that left no\n * persisted partial re-runs its user message (`retryTargetUserId`), unless\n * the stream is already terminal — a terminal stream is never retried (it\n * completed), only its submission is reconciled in dispatch.\n *\n * The stream row is opened before inference, so an interrupted turn can\n * have a stream id and still nothing to continue from; what decides retry is\n * the absence of persisted content and a leaf that is still the turn's user\n * message. Mirrors `AIChatAgent`'s empty-partial new-turn rule (#1691): a\n * `continue` here would find no assistant message and skip the turn.\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.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 originIds =\n this._originMessageIdsFor(requestId) ?? snapshot?.originMessageIds;\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 // Keep recovery payloads linked to the stable submission/root identity;\n // request_id now follows the accepted successor for startup evidence.\n // The recovery lookup accepts either identity, including released payloads.\n const recoveredSubmission = this._readRunningSubmissionForRecovery(\n recoveryRootRequestId\n );\n\n if (streamIsTerminal && recoveredSubmission) {\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) && recoveredSubmission\n ? recoveredSubmission.submission_id\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 ...(regenerationParentOf(snapshot) !== undefined &&\n snapshot?.latestMessageId && {\n regeneratedLeafId: snapshot.latestMessageId\n }),\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n lastBody: snapshot?.lastBody ?? null,\n lastClientTools: snapshot?.lastClientTools ?? null,\n ...(originIds ? { originMessageIds: originIds } : {}),\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 ...(originIds ? { originMessageIds: originIds } : {}),\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 declinedMessage =\n \"Submission was interrupted and automatic continuation was declined.\";\n // The recovery root still locates the submission after request_id has\n // moved to a successor turn.\n await this._markRecoveredSubmissionInterrupted(\n recoveryRootRequestId,\n declinedMessage\n );\n // Unlike `conversation_changed` (a newer turn owns the UI, so silence is\n // correct), declining continuation abandons the turn with no superseding\n // turn. Surface it like exhaustion so a reconnecting client isn't frozen.\n await this._recordTerminalChatStatus(\n \"interrupted\",\n requestId,\n declinedMessage\n );\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: declinedMessage,\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 partial: { text: string; parts: unknown[] }\n ): Promise<string | null> {\n // A partial holding only the internal final-answer tool persists nothing,\n // so the user message stays the leaf and there is nothing to continue.\n if (\n !snapshot ||\n snapshot.continuation ||\n !snapshot.latestUserMessageId ||\n partial.text ||\n (partial.parts.length > 0 &&\n this._strippedForPersist({\n id: \"\",\n role: \"assistant\",\n parts: partial.parts as UIMessage[\"parts\"]\n }) !== null)\n ) {\n return null;\n }\n\n const lastLeaf = await this.session.getLatestLeaf();\n // A regeneration branches beside the response it replaces, so that\n // response, not the user message, is still the leaf.\n const branchParentId = regenerationParentOf(snapshot);\n if (branchParentId !== undefined) {\n return lastLeaf !== null && lastLeaf.id === snapshot.latestMessageId\n ? branchParentId\n : null;\n }\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 the driving Task attempt (or the\n * routed one-shot schedule row) — only a platform transient is re-thrown to\n * preserve it — so without routing it here the run/row settles with no\n * terminal UX at 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 recovery enqueue carries one): the\n * synthesized incident can't be persisted (no key), so guard #1 can't\n * 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 * Host memory-limit policy hook (#1825), dispatched structurally by\n * Lifecycle's circuit breaker — protected because it is framework\n * machinery, not part of the public Think API. Tasks applies the breaker to\n * root recovery runs; the routed dynamic-agent fallback applies it to\n * `recoveryLoop` schedule rows (see `RecoveryLoopScheduleOptions`). At the\n * strike budget this hook seals active incidents via\n * {@link _cf_sealMemoryLimitedRecovery}.\n */\n protected async onAlarmMemoryLimit(context: { readonly sealed: boolean }) {\n if (!context.sealed) return;\n await this._cf_sealMemoryLimitedRecovery();\n }\n\n /**\n * Seal any still-live recovery incident as an out-of-memory exhaustion\n * when the alarm circuit breaker trips at its strike budget (#1825). Runs\n * at the outermost alarm frame (post-unwind), so the terminal banner /\n * `onExhausted` and the sealed-incident write can land where the mid-turn\n * give-up's writes OOMed. Reuses the shared give-up spine via\n * `_exhaustRecoveryGiveUp`.\n */\n private 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 * Handle an error thrown by `_chatRecoveryContinue` / `_chatRecoveryRetry`\n * after the incident was opened.\n *\n * - A Durable Object memory-limit reset is re-thrown with no bookkeeping.\n * The isolate is condemned: its storage calls reject and unconfirmed\n * writes are discarded, so nothing written here would survive (#2613).\n * The attempt's `attemptsInFlight` entry stays behind, and the next\n * attempt counts it against `maxInterruptedAttempts` before running\n * anything heavy.\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 the current\n * attempt (the driving Task run, or the routed one-shot schedule row) is\n * preserved and 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 `_readRunningSubmissionForRecovery`, 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: the driving attempt swallows\n * a non-transient throw and settles without terminalizing, so without\n * terminalizing here the half-finished turn is dropped with no terminal\n * event and no banner (the user stares at a frozen message until they\n * send something new).\n */\n private async _handleRecoveryCallbackError(\n callback: ChatRecoveryScheduleCallback,\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined,\n error: unknown\n ): Promise<void> {\n // Classified before the transient check: a memory-limit reset is not a\n // transient, and the generic path below would try to terminalize through\n // storage that is already gone.\n if (isDurableObjectMemoryLimitReset(error)) throw error;\n if (isPlatformTransientError(error)) {\n const message = error instanceof Error ? error.message : String(error);\n const incidentId = data?.incidentId;\n if (incidentId) this._deferringRecoveryIncidents.add(incidentId);\n try {\n await this._updateChatRecoveryIncident(incidentId, \"failed\", message);\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 } finally {\n if (incidentId) this._deferringRecoveryIncidents.delete(incidentId);\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.\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 /**\n * Keep the recovery callback as owner until a chat Task or facet fiber is durably\n * accepted. At acceptance, move the running submission to the successor's\n * request identity before signaling handoff. If an override never starts a\n * durable successor, the signal stays inert and the callback owns the work\n * until the override returns.\n */\n private async _runRecoveredTurnAfterAcceptance<T>(\n recoveredSubmission: ThinkSubmissionRow | null,\n onTurnStarted: (() => void) | undefined,\n run: () => Promise<T>\n ): Promise<T> {\n let signaled = false;\n const onAccepted = (successorRequestId: string): void => {\n if (signaled) return;\n signaled = true;\n if (recoveredSubmission) {\n this.sql`\n UPDATE cf_think_submissions\n SET request_id = ${successorRequestId}\n WHERE submission_id = ${recoveredSubmission.submission_id}\n AND status = 'running'\n `;\n }\n onTurnStarted?.();\n };\n const workflowPrompt = recoveredSubmission\n ? this._readWorkflowPromptContext(\n this._parseJsonObject(recoveredSubmission.metadata_json)\n )\n : null;\n return recoveredTurnAcceptanceContext.run(\n { agent: this, onAccepted, workflowPrompt: workflowPrompt ?? undefined },\n run\n );\n }\n\n /**\n * The workflow prompt of the submission a recovery turn is completing. A\n * structured prompt must re-arm its final-answer tool on the recovered turn,\n * or the turn can never produce the output the workflow waits for.\n */\n private _recoveredWorkflowPrompt(): ThinkWorkflowPromptContext | undefined {\n const acceptance = recoveredTurnAcceptanceContext.getStore();\n return acceptance?.agent === this ? acceptance.workflowPrompt : undefined;\n }\n\n async _chatRecoveryRetry(data?: ChatRecoveryRetryData): Promise<void> {\n await this._dispatchChatRecovery(\n \"_chatRecoveryRetry\",\n data,\n (onTurnStarted) =>\n this._chatRecoveryOriginIdsScope.run(data?.originMessageIds, () =>\n this._chatRecoveryRetryDetached(data, onTurnStarted)\n )\n );\n }\n\n protected async _chatRecoveryRetryDetached(\n data?: ChatRecoveryRetryData,\n onTurnStarted?: () => void\n ): Promise<void> {\n if (await this._recoveryCancelled(data)) return;\n const recoveredSubmission = data?.recoveredRequestId\n ? this._readRunningSubmissionForRecovery(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 const regeneratedLeafId = data?.regeneratedLeafId;\n if (\n !lastLeaf ||\n (regeneratedLeafId === undefined && lastLeaf.role !== \"user\")\n ) {\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 const expectedLeafId = regeneratedLeafId ?? data?.targetUserId;\n if (expectedLeafId && lastLeaf.id !== expectedLeafId) {\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 this._takeRecoveryReschedule(data?.incidentId);\n const result = await this._runRecoveredTurnAfterAcceptance(\n recoveredSubmission,\n onTurnStarted,\n () =>\n this._retryLastUserTurn(this._lastClientTools, this._lastBody, {\n ...(controller && { signal: controller.signal }),\n trigger: \"recovery-retry\",\n ...(regeneratedLeafId !== undefined && {\n branchParentId: data?.targetUserId\n })\n })\n );\n if (\n result.status !== \"completed\" &&\n this._takeRecoveryReschedule(data?.incidentId)\n ) {\n // Interrupted again: the attempt it scheduled owns the outcome.\n return;\n }\n await this._stageMessengerRecoveryOutcome(data, result.status);\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 recoveredSubmission ?? 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 /**\n * Recovery payloads retain the original submission/root identity while\n * request_id follows the accepted successor. Match both so released payloads,\n * redeferred callbacks, and exhaustion can still locate the running row.\n * Exact submission identity wins even when terminal: a redelivery must not\n * fall through to another submission whose successor request collides.\n */\n private _readRunningSubmissionForRecovery(\n recoveredRequestId: 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, result_status, output_json,\n message_id\n FROM cf_think_submissions\n WHERE submission_id = ${recoveredRequestId}\n OR (request_id = ${recoveredRequestId} AND status = 'running')\n ORDER BY (submission_id = ${recoveredRequestId}) DESC\n LIMIT 1\n `;\n return rows[0]?.status === \"running\" ? rows[0] : null;\n }\n\n private async _markRecoveredSubmissionInterrupted(\n recoveredRequestId: string,\n message: string\n ): Promise<void> {\n const row = this._readRunningSubmissionForRecovery(recoveredRequestId);\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 result_status = NULL,\n output_json = 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 === \"error\") {\n this._enqueueTerminalWorkflowNotification(updated);\n await this._emitSubmissionStatus(updated);\n }\n }\n\n private async _completeRecoveredSubmission(\n recoveredSubmission: ThinkSubmissionRow | string,\n status: ThinkSubmissionStatus,\n requestId: string | null,\n errorMessage: string | null\n ): Promise<void> {\n const row =\n typeof recoveredSubmission === \"string\"\n ? this._readRunningSubmissionForRecovery(recoveredSubmission)\n : this._readSubmission(recoveredSubmission.submission_id);\n // No await between this guard and the status write/notification enqueue:\n // competing startup and detached-finalizer paths cannot both emit.\n if (row?.status !== \"running\") return;\n let output: unknown;\n if (row.result_status === \"completed\" || row.result_status === \"aborted\") {\n status = row.result_status;\n errorMessage = null;\n if (status === \"completed\" && row.output_json !== null) {\n output = JSON.parse(row.output_json);\n }\n } else if (row.result_status === \"error\" && status === \"completed\") {\n // A stamped stream error contradicts inferred success: no later cutover\n // replaced the stamp, so the turn never durably produced an answer.\n status = \"error\";\n errorMessage = \"Recovered chat stream had already errored.\";\n } else if (row.result_status === \"retry\" && status === \"completed\") {\n // A retry segment is not a terminal result. If durable recovery still\n // owns the work leave it running; otherwise use the interruption path.\n if (\n (row.request_id &&\n this._hasRecoverableChatTurn(row.request_id) &&\n this._hasFreshRecoverableSubmissionEvidence(row)) ||\n (await this._hasScheduledChatRecovery(row))\n )\n return;\n await this._markRecoveredSubmissionInterrupted(\n row.submission_id,\n \"Submission was interrupted after messages were applied.\"\n );\n return;\n }\n const completedAt = Date.now();\n const streamId = requestId\n ? (this._resumableStream.latestStreamInfoForRequest(requestId)?.id ??\n null)\n : null;\n this.ctx.storage.transactionSync(() => {\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 result_status = NULL,\n output_json = NULL\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n `;\n this._enqueueTerminalWorkflowNotification(\n this._readSubmission(row.submission_id),\n output\n );\n });\n const updated = this._readSubmission(row.submission_id);\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 await this._dispatchChatRecovery(\n \"_chatRecoveryContinue\",\n data,\n (onTurnStarted) =>\n this._chatRecoveryOriginIdsScope.run(data?.originMessageIds, () =>\n this._chatRecoveryContinueDetached(data, onTurnStarted)\n )\n );\n }\n\n protected async _chatRecoveryContinueDetached(\n data?: ChatRecoveryContinueData,\n onTurnStarted?: () => void\n ): Promise<void> {\n if (await this._recoveryCancelled(data)) return;\n const recoveredSubmission = data?.recoveredRequestId\n ? this._readRunningSubmissionForRecovery(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 this._takeRecoveryReschedule(data?.incidentId);\n const result = await this._runRecoveredTurnAfterAcceptance(\n recoveredSubmission,\n onTurnStarted,\n () =>\n this.continueLastTurn(\n undefined,\n controller\n ? { signal: controller.signal, trigger: \"recovery-continue\" }\n : { trigger: \"recovery-continue\" }\n )\n );\n if (\n result.status !== \"completed\" &&\n this._takeRecoveryReschedule(data?.incidentId)\n ) {\n // Interrupted again: the attempt it scheduled owns the outcome.\n return;\n }\n await this._stageMessengerRecoveryOutcome(data, result.status);\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 recoveredSubmission ?? 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 this._withOriginMessageIds({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true,\n outcome: \"skipped\"\n })\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 if (this._flushResolvedPausesOnFinalize) {\n this._flushResolvedPausesOnFinalize = false;\n void this.keepAliveWhile(() =>\n this._enqueueInteractionApply(() => this._flushDeferredResolvedPauses())\n ).catch((error) => {\n console.error(\"[Think] Failed to apply resolved pauses\", error);\n });\n }\n this._autoContinuation.rearmForBatch();\n }\n\n /**\n * A pause resolved without a continuation while its turn was streaming; its\n * deferred drop runs when that turn finalizes instead of at the next\n * inference.\n */\n private _flushResolvedPausesOnFinalize = false;\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 let reported = false;\n this._admitTurn({\n admission: \"queue\",\n trigger: \"auto-continuation\",\n requestId,\n continuation: true,\n inheritChannel: 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 await this._runChatRecoveryFiber(requestId, true, continuationBody);\n } catch (error) {\n if (!streamed) {\n reported = await this._reportContinuationFailure(\n requestId,\n error,\n abortSignal\n );\n }\n throw error;\n } finally {\n this._aborts.remove(requestId);\n this._settleContinuationTurn(requestId, streamed);\n }\n }\n }).catch((error) => {\n if (!reported) {\n console.error(\"[Think] Auto-continuation failed:\", error);\n }\n this._aborts.remove(requestId);\n });\n }\n\n /**\n * Report a continuation turn that failed before it streamed, the way a\n * failed client turn is reported: `onChatError`, `chat:request:failed`, a\n * recorded terminal status, `onChatResponse` for the assistant message it\n * would have extended, and an error frame. Aborts and Durable Object resets\n * are left to their own paths.\n *\n * @returns Whether the failure was reported.\n */\n private async _reportContinuationFailure(\n requestId: string,\n error: unknown,\n abortSignal: AbortSignal | undefined\n ): Promise<boolean> {\n if (abortSignal?.aborted || isDurableObjectResetError(error)) return false;\n const wrapped = this.onChatError(error, {\n requestId,\n stage: \"turn\",\n messagesPersisted: true,\n continuation: true\n });\n const errorMessage =\n wrapped instanceof Error ? wrapped.message : String(wrapped);\n this._emit(\"chat:request:failed\", {\n requestId,\n stage: \"turn\",\n messagesPersisted: true,\n error: errorMessage\n });\n // Clients learn the turn failed before `onChatResponse` runs: a slow\n // hook must not hold the error frame.\n await this._recordTerminalChatStatus(\n \"error\",\n requestId,\n errorMessage\n ).catch((recordError: unknown) => {\n console.error(\n \"[Think] failed to record a continuation failure:\",\n recordError\n );\n });\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: errorMessage,\n done: true,\n error: true,\n continuation: true\n });\n const message = [...this.messages]\n .reverse()\n .find((candidate) => candidate.role === \"assistant\");\n if (message) {\n await this._fireLiveResponseHook({\n message,\n requestId,\n continuation: true,\n status: \"error\",\n error: errorMessage\n });\n }\n return true;\n }\n\n /**\n * Settle the continuation state when an auto-continuation turn ends (#2443).\n *\n * A turn only owns `pending` until its stream starts: `_streamResult` moves\n * that pending to the active slot, freeing `pending` for the NEXT\n * continuation. A client tool result that lands while this turn is still\n * streaming (a fast client tool chained across steps) creates that next\n * pending, and the stream-finalize re-arm fires it. So `pending` is cleared\n * here only while it still holds this turn's request — a turn that never\n * streamed (failed, aborted, or produced nothing before its stream started).\n * Clearing unconditionally would drop the newer pending and stall the chat.\n *\n * A newer pending that has not started also covers any `deferred` follow-up:\n * that result arrived before this turn's stream and the newer continuation\n * runs after it, so firing the deferred too would run a redundant turn that\n * replays a transcript ending in assistant text.\n */\n private _settleContinuationTurn(requestId: string, streamed: boolean): void {\n const pending = this._continuation.pending;\n if (pending?.requestId === requestId) {\n if (!streamed) {\n this._continuation.sendResumeNone();\n }\n this._continuation.clearPending();\n } else if (pending && !pending.pastCoalesce) {\n this._continuation.clearDeferred();\n }\n this._activateDeferredContinuation();\n }\n\n private _activateDeferredContinuation(): void {\n this._autoContinuation.activateDeferredAndReschedule();\n }\n\n /**\n * Queue 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 * item is durable, so the turn still runs if the object leaves memory\n * before the alarm fires; the last request body and client tools it needs\n * are persisted config, restored on start. Approvals landing while one\n * continuation is pending or running coalesce onto the single item.\n */\n private async _queueConnectionlessContinuation(): Promise<void> {\n await this.queue(CONNECTIONLESS_CONTINUATION_CALLBACK, undefined, {\n id: CONNECTIONLESS_CONTINUATION_QUEUE_ID\n });\n }\n\n /**\n * Run one connection-less continuation turn. Mirrors the connection-bound\n * auto-continuation turn body but streams via `broadcast` (a no-op when\n * nobody is attached) and always persists, so a client that reconnects\n * later resumes the continued turn from history.\n * @internal Queue callback.\n */\n async _cfRunConnectionlessContinuation(): Promise<void> {\n const requestId = crypto.randomUUID();\n const abortSignal = this._aborts.getSignal(requestId);\n let streamed = false;\n let reported = false;\n try {\n await this._admitTurn({\n admission: \"queue\",\n trigger: \"auto-continuation\",\n requestId,\n continuation: true,\n inheritChannel: 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 streamed = true;\n }\n };\n\n try {\n await this._runChatRecoveryFiber(requestId, true, continuationBody);\n } catch (error) {\n if (!streamed) {\n reported = await this._reportContinuationFailure(\n requestId,\n error,\n abortSignal\n );\n }\n throw error;\n }\n }\n });\n } catch (error) {\n if (!reported) {\n console.error(\"[Think] Connection-less continuation failed:\", error);\n }\n } finally {\n this._aborts.remove(requestId);\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 * Fire a live turn's response hook, then drop its pending marker. When the\n * bookkeeping before `onChatResponse` throws (attachment delivery, the\n * terminal-status write), the hook has not run: the marker is kept, with\n * this outcome, so the next start replays it.\n */\n private async _fireLiveResponseHook(\n result: ChatResponseResult\n ): Promise<void> {\n try {\n await this._fireResponseHook(result);\n } catch (error) {\n console.error(\"[Think] onChatResponse deferred to replay:\", error);\n await this._rememberPendingResponseHook(result).catch(() => {});\n this._responseHooksInFlight.delete(result.requestId);\n return;\n }\n await this._forgetPendingResponseHook(result.requestId).catch(\n (error: unknown) => {\n console.error(\"[Think] failed to clear a response hook marker:\", error);\n }\n );\n }\n\n /** Request ids whose response hook the live turn still owes. */\n private _responseHooksInFlight = new Set<string>();\n private _pendingResponseHookReplay: Promise<void> | undefined;\n\n /**\n * Record, before the assistant message is persisted, that this turn owes\n * `onChatResponse`, so a reset between the persist and the hook replays it.\n */\n private async _rememberPendingResponseHook(\n result: ChatResponseResult\n ): Promise<void> {\n this._responseHooksInFlight.add(result.requestId);\n const pending: PendingResponseHook = {\n requestId: result.requestId,\n messageId: result.message.id,\n continuation: result.continuation,\n status: result.status,\n ...(result.error !== undefined && { error: result.error })\n };\n await this.ctx.storage.put(\n PENDING_RESPONSE_HOOK_PREFIX + result.requestId,\n pending\n );\n }\n\n private async _forgetPendingResponseHook(requestId: string): Promise<void> {\n await this.ctx.storage.delete(PENDING_RESPONSE_HOOK_PREFIX + requestId);\n this._responseHooksInFlight.delete(requestId);\n }\n\n /**\n * Fire the response hooks a reset interrupted. A hook whose message never\n * persisted is dropped: that turn is recovered, and fires, on its own.\n */\n private _replayPendingResponseHooks(requestId?: string): Promise<void> {\n const previous = this._pendingResponseHookReplay ?? Promise.resolve();\n const replay = previous\n .catch(() => {})\n .then(() => this._replayPendingResponseHooksNow(requestId));\n const tracked = replay.finally(() => {\n if (this._pendingResponseHookReplay === tracked) {\n this._pendingResponseHookReplay = undefined;\n }\n });\n this._pendingResponseHookReplay = tracked;\n return tracked;\n }\n\n private async _replayPendingResponseHooksNow(\n requestId?: string\n ): Promise<void> {\n const pending =\n requestId === undefined\n ? await this.ctx.storage.list<PendingResponseHook>({\n prefix: PENDING_RESPONSE_HOOK_PREFIX\n })\n : new Map([\n [\n PENDING_RESPONSE_HOOK_PREFIX + requestId,\n await this.ctx.storage.get<PendingResponseHook>(\n PENDING_RESPONSE_HOOK_PREFIX + requestId\n )\n ]\n ]);\n for (const [key, hook] of pending) {\n if (!hook || this._responseHooksInFlight.has(hook.requestId)) continue;\n // Chat recovery reads this marker to settle the turn instead of\n // re-running it, so leave it for recovery while the turn is pending.\n if (\n requestId === undefined &&\n this._hasRecoverableChatTurn(hook.requestId)\n ) {\n continue;\n }\n const message = await this.session.getMessage(hook.messageId);\n if (message) {\n await this._fireResponseHook({\n message: message as UIMessage,\n requestId: hook.requestId,\n continuation: hook.continuation,\n status: hook.status,\n ...(hook.error !== undefined && { error: hook.error }),\n recovered: true\n });\n }\n await this.ctx.storage.delete(key);\n }\n }\n\n /** Request ids whose interruption handed messenger delivery to recovery. */\n private _messengerRecoveryClaims = new Set<string>();\n\n /**\n * An interrupted messenger turn that recovery will continue: record where\n * the recovered answer goes before the continuation is scheduled, so the\n * messenger delivery can skip its apology (#2106). A continuation attempt\n * of the same incident keeps the existing record.\n */\n private async _claimMessengerRecoveryDelivery(\n requestId: string,\n incidentId: string,\n partialText: string\n ): Promise<void> {\n const context = this._activeMessengerContext();\n if (!context) return;\n const delivery: MessengerRecoveryDelivery = {\n messengerId: context.messengerId,\n threadId: context.thread.id,\n partialText\n };\n await this.ctx.storage.put(\n MESSENGER_RECOVERY_PREFIX + incidentId,\n delivery\n );\n this._messengerRecoveryClaims.add(requestId);\n }\n\n /**\n * Durably record a messenger reply's outcome before its recovery incident\n * settles: once the incident is terminal, nothing re-emits the event that\n * would settle the reply after a reset. The recovered text is read before\n * any await, so a later turn cannot replace it.\n */\n private async _stageMessengerRecoveryOutcome(\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined,\n status: SaveMessagesResult[\"status\"]\n ): Promise<void> {\n if (!data?.incidentId) return;\n const text =\n status === \"completed\" ? this._recoveredReplyText(data) : undefined;\n const key = MESSENGER_RECOVERY_PREFIX + data.incidentId;\n const delivery = await this.ctx.storage.get<MessengerRecoveryDelivery>(key);\n if (!delivery || delivery.outcome) return;\n await this.ctx.storage.put(\n key,\n settleMessengerRecoveryDelivery(\n delivery,\n text === undefined ? \"interrupted\" : \"completed\",\n text\n )\n );\n }\n\n private _recoveredReplyText(\n data: ChatRecoveryContinueData | ChatRecoveryRetryData\n ): string {\n const messages = this.messages;\n let reply: UIMessage | undefined;\n if (\"targetAssistantId\" in data && data.targetAssistantId) {\n reply = messages.find((m) => m.id === data.targetAssistantId);\n } else if (\"targetUserId\" in data && data.targetUserId) {\n const index = messages.findIndex((m) => m.id === data.targetUserId);\n const next = index >= 0 ? messages[index + 1] : undefined;\n if (next?.role === \"assistant\") reply = next;\n }\n reply ??= messages.filter((m) => m.role === \"assistant\").at(-1);\n return messageText(reply);\n }\n\n /** Incidents whose messenger reply is being delivered by this isolate. */\n private _settlingMessengerRecoveries = new Set<string>();\n\n private _settleMessengerRecovery(\n incidentId: string,\n outcome: \"completed\" | \"interrupted\"\n ): void {\n const text =\n outcome === \"completed\"\n ? messageText(\n this.messages.filter((m) => m.role === \"assistant\").at(-1)\n )\n : undefined;\n if (this._settlingMessengerRecoveries.has(incidentId)) return;\n this._settlingMessengerRecoveries.add(incidentId);\n const key = MESSENGER_RECOVERY_PREFIX + incidentId;\n void this.keepAliveWhile(async () => {\n let delivery = await this.ctx.storage.get<MessengerRecoveryDelivery>(key);\n if (!delivery) return;\n if (!delivery.outcome) {\n delivery = settleMessengerRecoveryDelivery(delivery, outcome, text);\n await this.ctx.storage.put(key, delivery);\n }\n await this._deliverMessengerRecovery(key);\n })\n .catch((error: unknown) =>\n this._retryMessengerRecoveryDeliveryLater(key, 0, error)\n )\n .finally(() => {\n this._settlingMessengerRecoveries.delete(incidentId);\n });\n }\n\n /** The latest delivery of each recovered reply key, in call order. */\n private _messengerRecoveryDeliveries = new Map<string, Promise<void>>();\n\n /**\n * Deliver a recovered reply after any delivery of the same key already\n * running in this isolate: startup replay, live settlement and scheduled\n * retries interleave across awaits, and each must see the cursor the\n * previous one advanced.\n */\n private async _deliverMessengerRecovery(key: string): Promise<void> {\n const previous = this._messengerRecoveryDeliveries.get(key);\n const run = (previous ?? Promise.resolve()).then(() =>\n this._postMessengerRecovery(key)\n );\n const tail = run.catch(() => {});\n this._messengerRecoveryDeliveries.set(key, tail);\n try {\n await run;\n } finally {\n if (this._messengerRecoveryDeliveries.get(key) === tail) {\n this._messengerRecoveryDeliveries.delete(key);\n }\n }\n }\n\n /**\n * Post a settled recovered reply, one post at a time, then drop its record.\n * Each post goes out at most once: the cursor advances before it, and a\n * rejected post may still have landed (a timeout after the platform\n * accepted it), so the retry resumes with the next post.\n */\n private async _postMessengerRecovery(key: string): Promise<void> {\n let delivery = await this.ctx.storage.get<MessengerRecoveryDelivery>(key);\n if (!delivery?.outcome) return;\n const input = {\n messengerId: delivery.messengerId,\n threadId: delivery.threadId,\n outcome: delivery.outcome,\n ...(delivery.text !== undefined && { text: delivery.text }),\n partialPosted: delivery.partialText.trim().length > 0\n };\n const parent = this.parentPath.at(-1);\n // `parentAgent` resolves the parent by class name only.\n const host = parent\n ? await this.parentAgent({\n name: parent.className\n } as unknown as SubAgentClass<Think>)\n : this;\n let chunks: number | undefined;\n for (;;) {\n delivery = await this.ctx.storage.get<MessengerRecoveryDelivery>(key);\n if (!delivery?.outcome) return;\n const posted = delivery.posted ?? 0;\n if (chunks !== undefined && posted >= chunks) break;\n await this.ctx.storage.put(key, { ...delivery, posted: posted + 1 });\n ({ chunks } = await host._cf_deliverRecoveredMessengerReply({\n ...input,\n chunk: posted\n }));\n }\n await this.ctx.storage.delete(key);\n }\n\n /** Retry a recovered messenger reply whose live delivery failed. */\n private async _retryMessengerRecoveryDeliveryLater(\n key: string,\n attempts: number,\n error: unknown\n ): Promise<void> {\n if (attempts >= MESSENGER_RECOVERY_MAX_RETRIES) {\n console.error(\n `[Think] recovered messenger reply delivery failed ${attempts + 1} times; the next wake replays it`,\n error\n );\n return;\n }\n const delaySeconds = 2 ** (attempts + 1);\n console.error(\n `[Think] recovered messenger reply delivery failed; retrying in ${delaySeconds}s`,\n error\n );\n try {\n await this.schedule(delaySeconds, MESSENGER_RECOVERY_RETRY_CALLBACK, {\n key,\n attempts: attempts + 1\n });\n } catch (scheduleError) {\n console.error(\n \"[Think] failed to schedule a recovered messenger reply retry\",\n scheduleError\n );\n }\n }\n\n /**\n * Retry delivering a recovered messenger reply (see\n * {@link _retryMessengerRecoveryDeliveryLater}).\n * @internal Schedule callback.\n */\n async _cfRetryMessengerRecoveryDelivery(payload: {\n key: string;\n attempts: number;\n }): Promise<void> {\n try {\n await this._deliverMessengerRecovery(payload.key);\n } catch (error) {\n await this._retryMessengerRecoveryDeliveryLater(\n payload.key,\n payload.attempts,\n error\n );\n }\n }\n\n private async _replayMessengerRecoveryDeliveries(): Promise<void> {\n const pending = await this.ctx.storage.list<MessengerRecoveryDelivery>({\n prefix: MESSENGER_RECOVERY_PREFIX\n });\n for (const [key, delivery] of pending) {\n if (!delivery.outcome) {\n // Settled while an earlier isolate was delivering: the incident is\n // gone or gave up, and no event will settle this record again.\n const incident = await this.ctx.storage.get<ChatRecoveryIncident>(\n CHAT_RECOVERY_INCIDENT_KEY_PREFIX +\n encodeURIComponent(key.slice(MESSENGER_RECOVERY_PREFIX.length))\n );\n if (\n incident &&\n incident.status !== \"skipped\" &&\n incident.status !== \"exhausted\"\n ) {\n continue;\n }\n await this.ctx.storage.put(\n key,\n settleMessengerRecoveryDelivery(delivery, \"interrupted\")\n );\n }\n try {\n await this._deliverMessengerRecovery(key);\n } catch (error) {\n await this._retryMessengerRecoveryDeliveryLater(key, 0, error);\n }\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 messageIds?: string[]\n ): Promise<void> {\n if (status === \"error\" || status === \"interrupted\") {\n await this._recordChatTerminal(requestId, body, messageIds);\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 messageIds = this._originMessageIdsFor(requestId)\n ): Promise<void> {\n await recordChatTerminal(this.ctx.storage, requestId, body, messageIds);\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 messageIds?: 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, connect: true }\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?: {\n messageId?: string;\n parentMessageId?: string;\n continuation?: boolean;\n }\n ): string {\n const originIds =\n this._requestOriginMessageIds.get(requestId) ??\n this._activeChatRecoveryOriginIds;\n const streamId = this._resumableStream.start(requestId, {\n ...options,\n ...(originIds && { originMessageIds: originIds })\n });\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 return streamId;\n }\n\n /** Mark a resumable stream completed (settled now, rows kept until reclaim). */\n protected _completeResumableStream(\n streamId: string,\n outcome?: ChatTurnOutcome\n ): void {\n this._resumableStream.complete(streamId, outcome);\n this._afterResumableStreamEnded();\n }\n\n /**\n * A connection offered the stream that never ACKed (`resume: false`, or\n * gone quiet) must still get the terminal frame and every later broadcast.\n */\n private _afterResumableStreamEnded(): void {\n this._pendingResumeConnections.clear();\n }\n\n /**\n * The producer finished; leave the row for the cutover that persists the\n * assistant message (`_persistAssistantMessageWithCutover`). Every path\n * that calls this must end in that cutover or `finalizePending()`.\n */\n protected _finishResumableStream(\n streamId: string,\n outcome?: ChatTurnOutcome\n ): void {\n this._resumableStream.finish(streamId, outcome);\n this._afterResumableStreamEnded();\n }\n\n /** Mark a resumable stream errored. */\n protected _errorResumableStream(streamId: string, requestId?: string): void {\n this._afterResumableStreamEnded();\n this.ctx.storage.transactionSync(() => {\n this._resumableStream.markError(streamId);\n // An error stamp is not necessarily terminal — recovery may retry the\n // turn (startup gives pending recovery priority). It supersedes any\n // completed or retry stamp from an earlier segment, and it survives\n // this errored stream's rows being reclaimed by a later turn.\n if (requestId) {\n this._recordSubmissionTurnResult(requestId, { status: \"error\" });\n }\n });\n }\n\n /**\n * @deprecated Streams are reclaimed at cutover and on the next stream\n * start; no alarm is armed any more. Kept so a cleanup alarm persisted by\n * an earlier version still resolves to a callback when it fires.\n */\n async _cleanupStreamBuffers(): Promise<void> {\n this._resumableStream.reclaim();\n }\n\n /**\n * The message an orphaned stream's assistant message branches from, so the\n * reconstructed message lands where the live turn would have persisted it:\n * a regeneration beside the response it replaces, not under it. Undefined\n * for a turn that appends to the latest leaf, and on an `agents` release\n * that does not record the parent.\n */\n private _orphanParentId(streamId: string): string | undefined {\n const stream = this._resumableStream as ResumableStream & {\n getStreamParentMessageId?: (streamId: string) => string | null;\n };\n return stream.getStreamParentMessageId?.(streamId) ?? undefined;\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 let persistedId: string | undefined;\n const store = this._orphanStore();\n const parentId = this._orphanParentId(streamId);\n const wrote = await persistReconstructedOrphan(chunks, {\n store:\n parentId === undefined\n ? store\n : {\n ...store,\n appendMessage: (message) => store.appendMessage(message, parentId)\n },\n fallbackId: crypto.randomUUID(),\n prepare: (message) => {\n const prepared = this._strippedForPersist(message);\n persistedId = prepared?.id;\n return prepared;\n },\n merge: (_existing, incoming) => incoming\n });\n if (!wrote) return;\n const requestId =\n this._resumableStream.getStreamMetadata(streamId)?.request_id;\n if (requestId && persistedId) {\n this._recordSubmissionMessage(requestId, persistedId);\n }\n 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(\n JSON.stringify(this._withOriginMessageIds(message)),\n allExclusions\n );\n }\n\n /**\n * User message ids a WebSocket chat request originated from (#2280), keyed\n * by request id while the request is handled. After that (or after a\n * restart) the request's stream metadata is the fallback.\n */\n private _requestOriginMessageIds = new Map<string, string[]>();\n\n private _originMessageIdsFor(requestId: string): string[] | undefined {\n return (\n this._requestOriginMessageIds.get(requestId) ??\n this._resumableStream.getOriginMessageIds(requestId) ??\n this._activeChatRecoveryOriginIds\n );\n }\n\n private _withOriginMessageIds(\n message: Record<string, unknown>\n ): Record<string, unknown> {\n if (\n message.type !== MSG_CHAT_RESPONSE ||\n typeof message.id !== \"string\" ||\n !(message.done || message.error)\n ) {\n return message;\n }\n return withOriginMessageIds(message, this._originMessageIdsFor(message.id));\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC6DA,IAAa,eAAb,MAA0B;;CASxB,YAAY,QAAiB,SAA8B;;;oDALjB,CAAC,CAAA;;4DAEc,IAAA;EAIvD,uBAAA,SAAA,MAAe,MAAA;EACf,uBAAA,UAAA,MAAgB,OAAA;CAClB;CAEA,IAAI,YAAoB;EACtB,OAAA,uBAAA,SAAO,IAAA,CAAA,CAAa;CACtB;;CAGA,8BAA+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,YAAY,KAAK,SAAS,aAAa;CAC7C,OAAO,IAAI,qBACT,MACA,YAAY,GAAG,MAAM,GAAG,cAAc,KACxC;AACF;AAhLA,MAAwB,cAAc;CACpC;CACA;CACA;CACA;AACF;AAuIA,MAAgB,kBAAkB;AAqpClC,MAAe,sBAAsB;AA6BrC,MAAiB,4BAA4B,MAAU;AAkudzD,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":["decision","agentContext","encoder","ExtensionManager","agentContext","Think"],"sources":["../src/attachments.ts","../src/config-store.ts","../src/action-ledger.ts","../src/actions.ts","../src/action-tools.ts","../src/action-run.ts","../src/turn-trace.ts","../src/model.ts","../src/messengers/recovered-reply.ts","../src/harness/released-replies.ts","../src/channels/index.ts","../src/channels/runtime.ts","../src/turn-metadata.ts","../src/harness/messenger-channels.ts","../src/scheduled-tasks.ts","../src/harness/extensions/workspace.ts","../src/harness/extensions/fetch.ts","../src/harness/extensions/skills.ts","../src/harness/extensions/sandboxed.ts","../src/harness/extensions/actions.ts","../src/execution-parts.ts","../src/reply-attachments.ts","../src/extensions/host-api.ts","../src/extensions/wiring.ts","../src/skills-runtime.ts","../src/overrides.ts","../src/workflow-notifications.ts","../src/inference/structured-output.ts","../src/submissions.ts","../src/session.ts","../src/release-submissions.ts","../src/system-prompt.ts","../src/inference/model-messages.ts","../src/media-eviction.ts","../src/transcript-cache.ts","../src/skills.ts","../src/turn-types.ts","../src/think.ts"],"sourcesContent":["/**\n * How reply attachments reach a channel. An action attaches them with\n * `ctx.attachReply`; after the turn, each one is rendered to text and posted\n * to the active channel as an interim notice. Best-effort: a failure is\n * logged and never fails the turn.\n */\n\nimport type { ReplyAttachment } from \"./actions\";\n\ntype RenderedAttachment = string | { markdown: string } | undefined;\n\n/**\n * The default text for a reply attachment, or `undefined` to skip it:\n * unknown types, and types a channel handles out of band (`voice_note`).\n *\n * @internal\n */\nexport function defaultAttachmentText(\n attachment: ReplyAttachment\n): RenderedAttachment {\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 * Render each attachment and post it. Failures are logged and skipped.\n *\n * @internal\n */\nexport async function deliverReplyAttachments(\n attachments: ReplyAttachment[] | undefined,\n render: (attachment: ReplyAttachment) => RenderedAttachment,\n post: (rendered: string | { markdown: string }) => Promise<void>\n): Promise<void> {\n if (!attachments?.length) {\n return;\n }\n for (const attachment of attachments) {\n let rendered: RenderedAttachment;\n try {\n rendered = render(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 post(rendered);\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 * Think's private keyed config rows, in the `think_config` table, as a\n * Lifecycle capability that owns the table and its one migration (lifting\n * Think's keys out of the legacy `assistant_config` table).\n *\n * Durable: every row. In memory: the last value each key was seen to hold in\n * this isolate, so a write of an unchanged value skips the row. Only this\n * capability writes the table, which is what makes the memo safe.\n */\n\nimport { LifecycleCapability } from \"agents/lifecycle\";\n\n/** Keys Think reads that older versions stored in `assistant_config`. */\nconst LEGACY_CONFIG_KEYS = [\n \"_think_config\",\n \"lastClientTools\",\n \"lastBody\",\n \"skillsFingerprint\"\n] as const;\n\n/**\n * Whether a table named exactly `table` exists. Preparing a query against a\n * missing table fails and reads no rows, while a `sqlite_master` lookup reads\n * every schema row, so the catalog is only consulted once the cheap probe\n * finds something (it also accepts views and other letter cases). For one-way\n * migration checks that run on every wake.\n * @internal\n */\nexport function tableExists(sql: SqlStorage, table: string): boolean {\n try {\n sql.exec(`SELECT 1 FROM \"${table}\" LIMIT 0`);\n } catch (error) {\n if (String(error).includes(\"no such table\")) return false;\n throw error;\n }\n return (\n sql\n .exec(\n \"SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?\",\n table\n )\n .toArray().length > 0\n );\n}\n\n/** @internal */\nexport class ThinkConfigStore extends LifecycleCapability {\n #ready = false;\n readonly #memo = new Map<string, string | undefined>();\n\n constructor() {\n super(\"think-config\");\n }\n\n /** Create the table and lift legacy rows before anything reads them. */\n override onStart(): void {\n this.#ensureTable();\n }\n\n get #sql(): SqlStorage {\n return this.lifecycle.storage.sql;\n }\n\n /** The stored value of `key`, or `undefined`. Always reads the row. */\n get(key: string): string | undefined {\n this.#ensureTable();\n const value = this.#sql\n .exec<{ value: string }>(\n \"SELECT value FROM think_config WHERE key = ?\",\n key\n )\n .toArray()[0]?.value;\n this.#memo.set(key, value);\n return value;\n }\n\n /** Store `value` under `key`. Skips the write when the value is unchanged. */\n set(key: string, value: string): void {\n this.#ensureTable();\n if (this.#memo.get(key) === value) return;\n this.#sql.exec(\n \"INSERT OR REPLACE INTO think_config (key, value) VALUES (?, ?)\",\n key,\n value\n );\n this.#memo.set(key, value);\n }\n\n /** Delete `key`. Skips the write when the key is known to be absent. */\n delete(key: string): void {\n this.#ensureTable();\n if (this.#memo.has(key) && this.#memo.get(key) === undefined) return;\n this.#sql.exec(\"DELETE FROM think_config WHERE key = ?\", key);\n this.#memo.set(key, undefined);\n }\n\n /**\n * Lift Think's keys out of the legacy `assistant_config` table (or its\n * `assistant_config__lifted_v1` rename) into `think_config`, then drop the\n * source. A key already in `think_config` wins.\n */\n migrateLegacy(): void {\n // Sessions leaves `assistant_config` alone; these keys are Think's, so\n // Think lifts them into its own table and drops the source.\n const source = tableExists(this.#sql, \"assistant_config\")\n ? \"assistant_config\"\n : tableExists(this.#sql, \"assistant_config__lifted_v1\")\n ? \"assistant_config__lifted_v1\"\n : null;\n if (!source) return;\n\n for (const key of LEGACY_CONFIG_KEYS) {\n const value = this.#sql\n .exec<{ value: string }>(\n `SELECT value FROM ${source} WHERE session_id = '' AND key = ?`,\n key\n )\n .toArray()[0]?.value;\n if (value !== undefined) {\n this.#sql.exec(\n \"INSERT OR IGNORE INTO think_config (key, value) VALUES (?, ?)\",\n key,\n value\n );\n }\n }\n // Config is a handful of small rows and every key Think reads now lives in\n // think_config, so the source has nothing left to give.\n this.#sql.exec(`DROP TABLE ${source}`);\n }\n\n #ensureTable(): void {\n if (this.#ready) return;\n this.#sql.exec(`\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.migrateLegacy();\n this.#ready = true;\n }\n}\n","/**\n * The action ledger and durable-pause decisions as Task runs. Nothing here\n * stores anything of its own: an effect is a run of `EFFECT_TASK` under the\n * effect's key, and a decision is a run of `DECISION_TASK` that parks until\n * `approveExecution` / `rejectExecution` settles it from outside.\n *\n * @internal\n */\n\nimport { tableExists } from \"./config-store\";\nimport type { TaskJson, TaskValue, Tasks } from \"agents/tasks\";\nimport {\n removeReleaseTable,\n TaskSettlement,\n type TaskRecord\n} from \"agents/internal\";\n\n/** Run definition of one side effect, run once per key. */\nexport const EFFECT_TASK = \"__cf_think_action_effect\";\n/** Run definition of one durable-pause decision. */\nexport const DECISION_TASK = \"__cf_think_action_decision\";\n\n/** A value past this many characters is not recorded (SQLite row limit). */\nconst MAX_RECORDED_CHARS = 1_000_000;\n\n/**\n * A stable string form of a value: object keys sorted, so two objects with\n * the same entries in another order give the same string. A `Date` is\n * written as its ISO time.\n */\nexport function stableStringify(value: unknown): string {\n return stringifyStable(value, true);\n}\n\n/**\n * `datesAsTimes: false` is think@0.24.0's form: it had no case for a\n * `Date`, which it wrote as an object with no keys.\n */\nfunction stringifyStable(value: unknown, datesAsTimes: boolean): string {\n if (value === undefined) return \"undefined\";\n if (datesAsTimes && value instanceof Date) {\n return `Date(${Number.isNaN(value.getTime()) ? \"Invalid\" : value.toISOString()})`;\n }\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) => stringifyStable(item, datesAsTimes)).join(\",\")}]`;\n }\n const record = value as Record<string, unknown>;\n return `{${Object.keys(record)\n .sort()\n .map(\n (key) =>\n `${JSON.stringify(key)}:${stringifyStable(record[key], datesAsTimes)}`\n )\n .join(\",\")}}`;\n}\n\n/**\n * A 128-bit hash of {@link stableStringify}: tells inputs apart, hides\n * nothing. The function Think's action ledger always used, so rows an older\n * version wrote still match.\n */\nexport function stableHash(value: unknown): string {\n return hashOf(stableStringify(value));\n}\n\n/**\n * The hash think@0.24.0 gives the same value: equal to {@link stableHash}\n * unless the value holds a `Date`. 0.24.0 checks a repeated keyed call\n * against the hash in its own ledger row, and wrote its rows with it.\n */\nexport function releasedStableHash(value: unknown): string {\n return hashOf(stringifyStable(value, false));\n}\n\nfunction hashOf(input: string): string {\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\n/** What {@link runEffectOnce} did. */\nexport type EffectOutcome =\n /** This call ran the effect and recorded its value. */\n | { status: \"ran\"; value: unknown }\n /** The value was recorded earlier; the effect did not run. */\n | { status: \"replayed\"; value: unknown }\n /** A stale claim was taken over and the effect ran again. */\n | { status: \"reclaimed\"; value: unknown; ageMs: number }\n /** An earlier attempt claimed the key and never finished. Nothing ran. */\n | { status: \"in-doubt\"; ageMs: number }\n /** The key was used with another name or input. Nothing ran. */\n | { status: \"conflict\" }\n /** The effect ran but its value cannot be recorded; a later call runs it again. */\n | { status: \"unrecorded\"; value: unknown };\n\ntype EffectInput = {\n name: string;\n inputHash: string;\n /**\n * The row came from think@0.24.0's ledger: its hash is in 0.24.0's\n * form, which a row this version wrote never is.\n */\n released?: true;\n};\n\n/** What a running effect carries in this isolate. */\ntype Running = {\n name: string;\n inputHash: string;\n promise: Promise<EffectOutcome>;\n};\n\n/** In-memory companion of the effect runs in flight in this isolate. */\nexport type EffectState = {\n readonly running: Map<string, Running>;\n /** A value the run could not record, or what `run` threw, by run id. */\n readonly unrecorded: Map<string, { value: unknown } | { thrown: unknown }>;\n};\n\nexport function createEffectState(): EffectState {\n return { running: new Map(), unrecorded: new Map() };\n}\n\nconst RELEASED_LEDGER = \"cf_think_action_ledger\";\nconst RELEASED_APPROVALS = \"cf_think_action_pending_approvals\";\nconst RELEASED_RESOLVED_PAUSES = \"cf_think_deferred_resolved_pauses\";\n\nconst EFFECT_RUN_PREFIX = \"__cf_effect:\";\nconst DECISION_RUN_PREFIX = \"__cf_decision:\";\n\n/** The value an effect run recorded (`{}` for a void one). */\nexport function recordedValue(result: unknown): unknown {\n return result !== null &&\n typeof result === \"object\" &&\n Object.hasOwn(result, \"value\")\n ? (result as { value: unknown }).value\n : undefined;\n}\n\n/** The run id of an effect key. Run ids are one space per agent. */\nexport function effectRunId(key: string): string {\n return `${EFFECT_RUN_PREFIX}${key}`;\n}\n\n/** The effect key of an effect run id. */\nexport function effectKeyOf(runId: string): string {\n return runId.slice(EFFECT_RUN_PREFIX.length);\n}\n\n/** The run id of a decision, from the id shown to callers. */\nexport function decisionRunId(id: string): string {\n return `${DECISION_RUN_PREFIX}${id}`;\n}\n\n/** The id shown to callers, from a decision run id. */\nexport function decisionIdOf(runId: string): string {\n return runId.slice(DECISION_RUN_PREFIX.length);\n}\n\n/**\n * Register the effect definition. Attempt 1 runs the effect the caller passed\n * as `local`. A later attempt (a reset cut the first off) has no effect to\n * run and parks the run as `in-doubt`: whether the effect happened is\n * unknown, and the next caller decides.\n */\nexport function registerEffectTask(tasks: Tasks, state: EffectState): void {\n tasks.register(\n EFFECT_TASK,\n async (_input, step) => {\n const run = step.local as (() => Promise<unknown>) | undefined;\n if (!run) return TaskSettlement.park(\"in-doubt\");\n let value: unknown;\n try {\n value = await run();\n } catch (thrown) {\n state.unrecorded.set(step.id, { thrown });\n return TaskSettlement.failed(thrown);\n }\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n json = undefined;\n }\n if (\n (value !== undefined && json === undefined) ||\n (json !== undefined && json.length > MAX_RECORDED_CHARS)\n ) {\n state.unrecorded.set(step.id, { value });\n return TaskSettlement.skipped(\"unrecorded\");\n }\n // Wrapped, so a void result replays as void and not as null.\n return (\n json === undefined ? {} : { value: JSON.parse(json) }\n ) as TaskValue;\n },\n { attached: true }\n );\n}\n\n/**\n * Run `run` once for `key` and record its value as the run's result. A\n * later call with the same key, name and input returns the recorded value.\n * A call while this isolate runs the key shares that run. A claim a reset\n * left answers `in-doubt` and runs nothing, unless `reclaimAfterMs` allows\n * taking it over. If `run` throws, the run is deleted and the error\n * rethrown, so a later call runs again.\n */\nexport async function runEffectOnce(\n tasks: Tasks,\n state: EffectState,\n options: {\n key: string;\n name: string;\n input: unknown;\n run: () => Promise<unknown>;\n reclaimAfterMs: number | false;\n }\n): Promise<EffectOutcome> {\n const runId = effectRunId(options.key);\n const inputHash = stableHash(options.input);\n // 0.24.0's form of the same input (different only where it holds a\n // `Date`): what a row carried from 0.24.0 has, and what a row written\n // for 0.24.0 must have.\n const releasedHash = releasedStableHash(options.input);\n const live = state.running.get(runId);\n if (live) {\n if (live.name !== options.name || live.inputHash !== inputHash) {\n return { status: \"conflict\" };\n }\n return live.promise;\n }\n let reclaimedAge: number | undefined;\n const existing = tasks.peek(runId);\n if (existing) {\n const stored = tasks.inputOf<EffectInput>(runId);\n if (\n stored?.name !== options.name ||\n (stored.inputHash !== inputHash &&\n // 0.24.0's form only for a row 0.24.0 wrote: for a row of this\n // version it would take a `Date` for an object with no keys.\n !(stored.released === true && stored.inputHash === releasedHash))\n ) {\n return { status: \"conflict\" };\n }\n if (existing.status === \"completed\") {\n return { status: \"replayed\", value: recordedValue(existing.result) };\n }\n if (existing.status === \"pending\" || existing.status === \"running\") {\n const ageMs = Date.now() - existing.createdAt;\n const lease = options.reclaimAfterMs;\n if (lease === false || ageMs <= lease) {\n return { status: \"in-doubt\", ageMs };\n }\n reclaimedAge = ageMs;\n }\n }\n // Registered before the first await, so a same-isolate caller shares it.\n const promise = (async (): Promise<EffectOutcome> => {\n try {\n if (reclaimedAge !== undefined) {\n await tasks.settle(runId, TaskSettlement.aborted(\"reclaimed\"));\n }\n // An ended run that recorded nothing frees the key.\n if (existing) tasks.deleteRun(runId);\n await tasks.run(\n EFFECT_TASK,\n { name: options.name, inputHash } satisfies EffectInput,\n { runId, start: \"now\", local: options.run }\n );\n const record = tasks.peek(runId);\n const kept = state.unrecorded.get(runId);\n if (record?.status === \"completed\") {\n return reclaimedAge === undefined\n ? { status: \"ran\", value: recordedValue(record.result) }\n : {\n status: \"reclaimed\",\n value: recordedValue(record.result),\n ageMs: reclaimedAge\n };\n }\n // Failed or unrecordable: the key is free again.\n tasks.deleteRun(runId);\n if (kept && \"thrown\" in kept) throw kept.thrown;\n if (kept && \"value\" in kept) {\n return { status: \"unrecorded\", value: kept.value };\n }\n throw new Error(`Effect \"${options.key}\" ended ${record?.status}`);\n } finally {\n state.unrecorded.delete(runId);\n }\n })();\n state.running.set(runId, { name: options.name, inputHash, promise });\n try {\n return await promise;\n } finally {\n state.running.delete(runId);\n }\n}\n\n/**\n * Delete recorded effects settled before `settledBefore`, and effects left\n * in doubt (a reset cut them off) created before `pendingBefore`.\n */\nexport async function sweepEffects(\n tasks: Tasks,\n options: {\n settledBefore: number | null;\n pendingBefore: number | null;\n limit: number;\n }\n): Promise<{ settled: number; pending: number }> {\n const settled =\n options.settledBefore === null || options.limit <= 0\n ? 0\n : await tasks.delete({\n definition: EFFECT_TASK,\n status: [\"completed\"],\n settledBefore: new Date(options.settledBefore),\n limit: options.limit\n });\n let pending = 0;\n if (options.pendingBefore !== null && options.limit > settled) {\n for (const record of tasks.peekList({\n definition: EFFECT_TASK,\n status: [\"pending\", \"running\"],\n order: \"oldest\",\n limit: options.limit - settled\n })) {\n if (record.createdAt >= options.pendingBefore) break;\n await tasks.settle(record.runId, TaskSettlement.aborted(\"expired\"));\n if (tasks.deleteRun(record.runId)) pending += 1;\n }\n }\n return { settled, pending };\n}\n\n/** What a decision run starts with. */\nexport type DecisionInput =\n /** A durable-pause action parked for approval. */\n | {\n kind: \"action\";\n action: string;\n toolCallId: string;\n requestId: string | null;\n input: TaskJson;\n }\n /** A codemode execution its runtime already decided: only the outcome is recorded. */\n | {\n kind: \"codemode\";\n executionId: string;\n verdict: TaskJson;\n output: TaskJson;\n };\n\n/** A verdict as the decision run's result. */\nexport type DecisionVerdict = {\n approved: boolean;\n reason?: string;\n autoContinue?: boolean;\n connectionId?: string;\n};\n\n/**\n * Register the decision definition. An action decision parks at once until\n * `settle()` ends it with its verdict; a codemode one completes at once with\n * its recorded outcome. `onSettled` runs for a completed decision, at least\n * once: a reset before it returns runs it again.\n */\nexport function registerDecisionTask(\n tasks: Tasks,\n onSettled: (runId: string) => Promise<void>\n): void {\n tasks.register(\n DECISION_TASK,\n (input) => {\n const decision = input as DecisionInput;\n // A codemode decision is recorded: its verdict and outcome are its\n // input, so nothing is stored twice.\n if (decision.kind === \"codemode\") return null;\n return TaskSettlement.park(\"decision\");\n },\n {\n attached: true,\n onStatus: async (snapshot) => {\n if (snapshot.status === \"completed\") await onSettled(snapshot.runId);\n }\n }\n );\n}\n\n/** Park a durable-pause action for a decision. */\nexport async function parkDecision(\n tasks: Tasks,\n options: {\n id: string;\n input: DecisionInput;\n descriptor?: TaskJson;\n }\n): Promise<void> {\n const metadata = {\n ...(options.descriptor !== undefined && {\n descriptor: options.descriptor\n })\n };\n await tasks.run(DECISION_TASK, options.input, {\n runId: decisionRunId(options.id),\n start: \"now\",\n ...(Object.keys(metadata).length > 0 && { metadata })\n });\n}\n\n/** Whether `record` is a decision still waiting for its verdict. */\nexport function isPendingDecision(record: TaskRecord | undefined): boolean {\n return (\n record?.definition === DECISION_TASK &&\n record.status === \"pending\" &&\n record.waitReason === \"park\"\n );\n}\n\n/**\n * The decisions still waiting for a verdict, oldest first: all of them\n * unless `limit` is given (their number is bounded by the approval TTL).\n */\nexport function pendingDecisions(\n tasks: Tasks,\n limit = Number.MAX_SAFE_INTEGER\n): TaskRecord[] {\n return tasks\n .peekList({\n definition: DECISION_TASK,\n status: [\"pending\"],\n order: \"oldest\",\n limit\n })\n .filter(isPendingDecision);\n}\n\n/** Expire decisions nobody made, created before `before`. */\nexport async function sweepDecisions(\n tasks: Tasks,\n before: number,\n limit: number\n): Promise<number> {\n let swept = 0;\n for (const record of pendingDecisions(tasks, limit)) {\n if (swept >= limit || record.createdAt >= before) break;\n await tasks.settle(record.runId, TaskSettlement.aborted(\"expired\"));\n if (tasks.deleteRun(record.runId)) swept += 1;\n }\n return swept;\n}\n\n/** A run as Tasks' synchronous import takes it. */\ntype ImportedRun = Parameters<Tasks[\"importRun\"]>[0];\n\n/**\n * The step of the one migration that moves what think@0.24.0 stored for\n * actions into runs, and removes it. It runs once, inside the migration's\n * transaction, so a reset in the middle leaves 0.24.0's storage whole and\n * the next start moves it all.\n * - `cf_think_action_ledger` rows become effect runs. Keys, input hashes and\n * recorded values keep their form, so a settled action still replays; an\n * unsettled claim comes back in doubt.\n * - `cf_think_action_pending_approvals` rows become decisions that wait for\n * a verdict under their ids (their TTL counts from now).\n * - `cf_think_deferred_resolved_pauses` entries become completed decisions\n * carrying `resolvedPause`, which the next inference writes.\n * Both tables are dropped, and the three keys deleted with the two that\n * timed 0.24.0's sweeps. A row that cannot become a run stays in its\n * table, which is then kept ({@link releasedActionsLeft}): the start after\n * keeps the release's key, so the next start tries that row again.\n *\n * @param importRun - Tasks' synchronous import: false when the run exists.\n */\nexport function releasedActionsMigration(\n importRun: (sql: SqlStorage, run: ImportedRun) => boolean\n): (storage: { readonly sql: SqlStorage; readonly kv: SyncKvStorage }) => void {\n return (storage) => {\n const { sql, kv } = storage;\n if (tableExists(sql, RELEASED_LEDGER)) {\n const rows = sql.exec<{\n key: string;\n action_name: string;\n input_hash: string;\n status: \"pending\" | \"settled\";\n result_json: string | null;\n updated_at: number;\n }>(\n `SELECT key, action_name, input_hash, status, result_json, updated_at\n FROM ${RELEASED_LEDGER}`\n );\n let left = 0;\n for (const row of [...rows]) {\n const recorded = parseJson(row.result_json) as\n | { valuePresent?: boolean; value?: TaskJson }\n | undefined;\n const moved = moveRow(`action \"${row.key}\"`, () =>\n importRun(sql, {\n runId: effectRunId(row.key),\n definition: EFFECT_TASK,\n status: row.status === \"settled\" ? \"completed\" : \"running\",\n attempt: 1,\n input: {\n name: row.action_name,\n inputHash: row.input_hash,\n released: true\n } satisfies EffectInput,\n ...(row.status === \"settled\" && {\n result:\n recorded?.valuePresent === true\n ? { value: recorded.value ?? null }\n : {}\n }),\n // The claim's age is what a reclaim measures.\n createdAt: row.updated_at,\n settledAt: row.updated_at\n })\n );\n if (!moved) {\n left += 1;\n continue;\n }\n sql.exec(`DELETE FROM ${RELEASED_LEDGER} WHERE key = ?`, row.key);\n }\n // The table goes only when every row is a run here.\n if (left === 0) removeReleaseTable(storage, RELEASED_LEDGER);\n }\n if (tableExists(sql, RELEASED_APPROVALS)) {\n const rows = sql.exec<{\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 }>(\n `SELECT execution_id, action_name, tool_call_id, request_id,\n input_json, descriptor_json\n FROM ${RELEASED_APPROVALS}`\n );\n let left = 0;\n for (const row of [...rows]) {\n const descriptor = parseJson(row.descriptor_json);\n // Pending: Tasks' start runs it, and the decision parks itself.\n const moved = moveRow(`approval \"${row.execution_id}\"`, () =>\n importRun(sql, {\n runId: decisionRunId(row.execution_id),\n definition: DECISION_TASK,\n status: \"pending\",\n attempt: 0,\n input: {\n kind: \"action\",\n action: row.action_name,\n toolCallId: row.tool_call_id,\n requestId: row.request_id,\n // Only a missing or unreadable input becomes `{}`; JSON null\n // stays.\n input: inputOrEmpty(parseJson(row.input_json))\n } satisfies DecisionInput,\n ...(descriptor !== undefined && { metadata: { descriptor } }),\n createdAt: Date.now()\n })\n );\n if (!moved) {\n left += 1;\n continue;\n }\n sql.exec(\n `DELETE FROM ${RELEASED_APPROVALS} WHERE execution_id = ?`,\n row.execution_id\n );\n }\n if (left === 0) removeReleaseTable(storage, RELEASED_APPROVALS);\n }\n const deferred = kv.get<\n Array<[string, { executionId: string; output: TaskJson }]>\n >(RELEASED_RESOLVED_PAUSES);\n for (const [toolCallId, outcome] of deferred ?? []) {\n importRun(sql, {\n runId: decisionRunId(`migrated_${outcome.executionId}_${toolCallId}`),\n definition: DECISION_TASK,\n status: \"completed\",\n attempt: 1,\n metadata: {\n resolvedPause: {\n toolCallId,\n executionId: outcome.executionId,\n output: outcome.output\n }\n },\n createdAt: Date.now()\n });\n }\n // Only a key that is there is deleted: an object with nothing of\n // 0.24.0's actions writes nothing here.\n for (const key of [\n RELEASED_RESOLVED_PAUSES,\n `${RELEASED_LEDGER}:last_swept_at`,\n `${RELEASED_APPROVALS}:last_swept_at`\n ]) {\n if (kv.get(key) !== undefined) kv.delete(key);\n }\n };\n}\n\n/** Move one of 0.24.0's rows; false when it cannot become a run. */\nfunction moveRow(what: string, move: () => unknown): boolean {\n try {\n move();\n return true;\n } catch (error) {\n console.error(\n `[Think] The ${what} think@0.24.0 stored was not carried over; its row is kept`,\n error\n );\n return false;\n }\n}\n\n/** Whether a row of 0.24.0's action tables is still to be moved. */\nexport function releasedActionsLeft(sql: SqlStorage): boolean {\n // A facet may keep a table, emptied (`removeReleaseTable`): a row says so.\n return [RELEASED_LEDGER, RELEASED_APPROVALS].some(\n (table) =>\n tableExists(sql, table) &&\n sql.exec(`SELECT 1 FROM ${table} LIMIT 1`).toArray().length > 0\n );\n}\n\nfunction inputOrEmpty(input: TaskJson | undefined): TaskJson {\n return input === undefined ? {} : input;\n}\n\nfunction parseJson(json: string | null): TaskJson | undefined {\n if (json === null) return undefined;\n try {\n return JSON.parse(json) as TaskJson;\n } catch {\n return undefined;\n }\n}\n","/**\n * The action API: `action()` declares a typed tool with policy (approval,\n * permissions, idempotency, timeout), and `getActions()` returns them for\n * Think to compile into the turn's tools.\n */\n\nimport type { FlexibleSchema, InferSchema, ModelMessage } from \"ai\";\nimport type { Think } from \"./think\";\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\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\n/** @internal What a compiled action tool carries for approval descriptors. */\nexport type CompiledActionMetadata = {\n actionName: string;\n summary: string;\n permissions?: string[];\n risk?: \"low\" | \"medium\" | \"high\";\n kind: \"approval-gated\" | \"durable-pause\";\n};\n\n/** @internal An authorization decision with defaults applied. */\nexport type NormalizedActionAuthorization = {\n allowed: boolean;\n reason?: string;\n grantedPermissions?: readonly string[];\n};\n","/**\n * How a turn compiles the agent's actions (`getActions()`) into AI SDK tools:\n * authorization through `authorizeAction`, the approval gate, the timeout\n * and abort race, and the hand-off to the action ledger or a durable pause.\n */\n\nimport type { ModelMessage, ToolSet } from \"ai\";\nimport { tool } from \"ai\";\nimport {\n isAction,\n type Action,\n type ActionApprovalDescriptor,\n type ActionApprovalPolicy,\n type ActionAuthorizationContext,\n type ActionAuthorizationDecision,\n type ActionContext,\n type ActionIdempotencyKey,\n type ActionKind,\n type ActionPermissionSpec,\n type CompiledActionMetadata,\n type NormalizedActionAuthorization\n} from \"./actions\";\nimport type { Think } from \"./think\";\n\n/**\n * What compiled action tools call on their agent.\n *\n * @internal\n */\nexport interface ActionToolHost {\n readonly agent: Think;\n /** The agent's bindings, read each time an action runs. */\n env(): Cloudflare.Env;\n /** Request id of the admitted turn, or `\"\"`. */\n requestId(): string;\n /** Whether a human already approved this call (its transcript part). */\n isApproved(toolCallId: string): boolean;\n /** Permissions `authorizeTurn` granted the current turn. */\n grantedPermissions(): readonly string[] | undefined;\n authorizeAction(\n ctx: ActionAuthorizationContext\n ): ActionAuthorizationDecision | Promise<ActionAuthorizationDecision>;\n recordApprovalDescriptor(\n toolCallId: string,\n descriptor: ActionApprovalDescriptor\n ): void;\n recordReplyAttachment(\n requestId: string,\n attachment: unknown,\n actionName: string\n ): void;\n /**\n * Whether this call runs because a human approved it, after the turn that\n * asked ended (a host without `parkDurablePause`).\n */\n ranAfterApproval?(toolCallId: string): Promise<boolean>;\n /** Run the action through the action ledger (claim, run once, record). */\n runLedgered(args: {\n toolName: string;\n idempotencyKey: ActionIdempotencyKey<unknown> | undefined;\n input: unknown;\n ctx: ActionContext;\n runAction: () => Promise<unknown>;\n }): Promise<unknown>;\n /**\n * Park a durable-pause action for approval; returns the tool output.\n * Without it (on ThinkHarness), a durable-pause action asks for approval\n * like an approval-gated one, and its tool call waits in the transcript.\n */\n parkDurablePause?(args: {\n toolName: string;\n input: unknown;\n ctx: ActionContext;\n summary: string;\n permissions: string[];\n risk?: \"low\" | \"medium\" | \"high\";\n }): Promise<unknown>;\n /**\n * Run an action's `execute` in the context its turn's caller gives it\n * (the tab's connection). Without it, the action runs in the caller's.\n */\n insideTurn?<T>(run: () => Promise<T>): Promise<T>;\n}\n\n/** @internal */\nexport const DEFAULT_ACTION_TIMEOUT_MS = 30_000;\nconst ACTION_OUTPUT_MAX_CHARS = 20_000;\n\n/** @internal */\nexport function 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\n/** @internal */\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\n/** @internal */\nexport function 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\n/** @internal */\nexport function 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\n/** @internal */\nexport function 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\n/** @internal */\nexport function 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\n/** @internal */\nexport function 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/** @internal */\nexport async function resolveActionPermissions(\n spec: ActionPermissionSpec<unknown> | undefined,\n input: unknown,\n ctx: ActionContext\n): Promise<string[]> {\n if (spec === undefined) return [];\n const policyCtx = actionContextWithoutReply(ctx);\n const permissions =\n typeof spec === \"function\" ? await spec({ input, ctx: policyCtx }) : spec;\n return [...permissions];\n}\n\n/** @internal */\nexport function actionContextWithoutReply(ctx: ActionContext): ActionContext {\n return {\n ...ctx,\n attachReply: () => {}\n };\n}\n\nasync function authorizeActionCall(\n host: ActionToolHost,\n options: {\n actionName: string;\n kind: ActionKind;\n input: unknown;\n ctx: ActionContext;\n permissions?: ActionPermissionSpec<unknown>;\n }\n): Promise<NormalizedActionAuthorization & { permissions: string[] }> {\n const permissions = await resolveActionPermissions(\n options.permissions,\n options.input,\n options.ctx\n );\n const decision = await host.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: host.grantedPermissions(),\n messages: options.ctx.messages,\n agent: host.agent,\n env: host.env()\n });\n return {\n ...normalizeActionAuthorization(decision),\n permissions\n };\n}\n\n/** @internal */\nexport function compileActionTools(\n actions: Record<string, Action>,\n host: ActionToolHost,\n metadata: Map<string, CompiledActionMetadata>\n): ToolSet {\n const tools: ToolSet = {};\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 metadata.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] = actionToTool(host, descriptor, toolName, kind);\n }\n return tools;\n}\n\nfunction actionToTool(\n host: ActionToolHost,\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 ActionApprovalPolicy<unknown> | 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 (kind === \"durable-pause\" && !host.parkDurablePause)\n ? {\n needsApproval: async (\n input: unknown,\n options: {\n toolCallId: string;\n messages: ModelMessage[];\n }\n ) => {\n const ctx: ActionContext = {\n agent: host.agent,\n env: host.env(),\n requestId: host.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 (host.isApproved(options.toolCallId)) {\n return true;\n }\n const authorization = await authorizeActionCall(host, {\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 ?? true);\n if (needsApproval) {\n host.recordApprovalDescriptor(options.toolCallId, {\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:\n kind === \"durable-pause\" ? \"durable-pause\" : \"approval-gated\"\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 requestId = host.requestId();\n // A call the host ran only once a human approved it (ThinkHarness's\n // durable pause): as on Think, it keeps no reply attachment, since the\n // turn that asked has ended. The host says so from the call itself,\n // whatever the action's configuration is now.\n const waited =\n !host.parkDurablePause && options.toolCallId !== undefined\n ? ((await host.ranAfterApproval?.(options.toolCallId)) ?? false)\n : false;\n const { signal, cleanup } = createActionAbortSignal(\n options.abortSignal,\n config.timeoutMs ?? DEFAULT_ACTION_TIMEOUT_MS\n );\n const actionContext: ActionContext = {\n agent: host.agent,\n env: host.env(),\n requestId,\n toolCallId: options.toolCallId ?? \"\",\n messages: options.messages ?? [],\n signal,\n attachReply: (attachment) =>\n host.recordReplyAttachment(requestId, attachment, toolName)\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\n try {\n const authorization = await authorizeActionCall(host, {\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 runContext = waited\n ? actionContextWithoutReply(actionContext)\n : actionContext;\n const abortPromise = new Promise<never>((_, reject) => {\n onAbort = () => reject(abortError());\n signal.addEventListener(\"abort\", onAbort, { once: true });\n });\n // Raced only when the action runs: a call that parks, or fails its\n // approval predicate, past its timeout leaves the rejection unread.\n abortPromise.catch(() => {});\n const runAction = async () => {\n const output = await Promise.race([\n host.insideTurn\n ? host.insideTurn(async () => executeAction(input, runContext))\n : Promise.resolve(executeAction(input, runContext)),\n abortPromise\n ]);\n return prepareActionOutputForModel(output);\n };\n\n if (kind === \"durable-pause\" && host.parkDurablePause) {\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: actionContextWithoutReply(actionContext)\n })\n : approval;\n if (!shouldPark) {\n return await host.runLedgered({\n toolName,\n idempotencyKey,\n input,\n ctx: actionContext,\n runAction\n });\n }\n return await host.parkDurablePause({\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 host.runLedgered({\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 * Running an action through the action ledger: the idempotency key, the\n * durable claim and replay, and the ledger events.\n *\n * @internal Not exported from any entry point.\n */\n\nimport { __DO_NOT_USE_WILL_BREAK__agentContext as agentContext } from \"agents\";\nimport type { Tasks } from \"agents/tasks\";\nimport {\n runEffectOnce,\n stableHash,\n type EffectOutcome,\n type EffectState\n} from \"./action-ledger\";\nimport { actionContextWithoutReply, actionErrorEnvelope } from \"./action-tools\";\nimport type { ActionContext, ActionIdempotencyKey } from \"./actions\";\n\n/** @internal */\nexport type 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\n/** @internal */\nexport type LedgeredActionArgs = {\n toolName: string;\n idempotencyKey: ActionIdempotencyKey<unknown> | undefined;\n input: unknown;\n ctx: ActionContext;\n runAction: () => Promise<unknown>;\n /**\n * What to answer for a claim another attempt left that its lease lets\n * be taken over later (an explicit key with a finite lease). Without\n * it, that claim answers `ActionPendingError`.\n */\n onReclaimableInDoubt?: () => unknown;\n};\n\n/** What `runLedgeredAction` needs from its agent. @internal */\nexport type ActionLedgerDeps = {\n tasks: Tasks;\n effects: EffectState;\n pendingRetryLeaseMs: number | false;\n emit(event: ActionLedgerEvent): void;\n /** The turn's reply attachments, which a failed run takes back. */\n attachments: { count(): number; truncate(count: number): void };\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\nasync function 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 = 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/**\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 * @internal\n */\nexport async function runLedgeredAction(\n deps: ActionLedgerDeps,\n args: LedgeredActionArgs\n): Promise<unknown> {\n const { toolName, idempotencyKey, input, ctx, runAction } = args;\n const key = await resolveActionLedgerKey(\n toolName,\n idempotencyKey,\n input,\n actionContextWithoutReply(ctx)\n );\n // A failed run takes back the reply attachments it recorded.\n const attachmentCount = deps.attachments.count();\n // The effect runs inside its task; the caller's connection and request\n // stay ambient for it, as when it ran inline.\n const caller = agentContext.getStore();\n const run = async () => {\n try {\n return await (caller ? agentContext.run(caller, runAction) : runAction());\n } catch (error) {\n deps.attachments.truncate(attachmentCount);\n throw error;\n }\n };\n if (!key) return await run();\n\n let outcome: EffectOutcome;\n try {\n outcome = await runEffectOnce(deps.tasks, deps.effects, {\n key,\n name: toolName,\n input,\n // An explicit `idempotencyKey` is the developer's assertion that\n // retrying the keyed side effect is safe, so only those claims may be\n // taken over when stale. Fallback `tool:${toolCallId}` keys never are.\n reclaimAfterMs:\n idempotencyKey !== undefined ? deps.pendingRetryLeaseMs : false,\n run\n });\n } catch (error) {\n return actionErrorEnvelope(error);\n }\n const event = { action: toolName, key, inputHash: stableHash(input) };\n switch (outcome.status) {\n case \"replayed\":\n deps.emit({\n type: \"action:ledger:replayed\",\n payload: event\n });\n return outcome.value;\n case \"in-doubt\": {\n deps.emit({\n type: \"action:ledger:pending\",\n payload: event\n });\n if (\n args.onReclaimableInDoubt &&\n idempotencyKey !== undefined &&\n deps.pendingRetryLeaseMs !== false\n ) {\n return args.onReclaimableInDoubt();\n }\n return actionPendingErrorEnvelope();\n }\n case \"conflict\":\n deps.emit({\n type: \"action:ledger:conflict\",\n payload: event\n });\n return actionKeyConflictEnvelope(toolName, key);\n case \"unrecorded\":\n deps.emit({\n type: \"action:ledger:serialize_failed\",\n payload: { action: toolName, key }\n });\n return outcome.value;\n case \"reclaimed\":\n deps.emit({\n type: \"action:ledger:reclaimed\",\n payload: { ...event, ageMs: outcome.ageMs }\n });\n break;\n case \"ran\":\n break;\n }\n deps.emit({\n type: \"action:ledger:settled\",\n payload: event\n });\n return outcome.value;\n}\n","/**\n * The turn a model call's spans describe: the\n * `cloudflare.agents.turn.*` attributes, with the values think@0.24.0 set.\n *\n * @internal\n */\nexport function turnTraceOf(turn: {\n readonly requestId: string;\n /** What admitted the turn, as its hooks are told. */\n readonly trigger: string;\n readonly channel?: string;\n /** Whether the turn continues a reply stored before it began. */\n readonly continuation: boolean;\n /** How many times the chat was cleared. */\n readonly generation: number;\n}): {\n readonly requestId: string;\n readonly trigger: string;\n readonly admission: string;\n readonly channel?: string;\n readonly continuation: boolean;\n readonly generation?: number;\n} {\n return {\n requestId: turn.requestId,\n trigger: turn.trigger,\n // A turn is admitted through the queue; `submit` and\n // `execute-submission` name the steps before it, which call no model.\n admission: \"queue\",\n ...(turn.channel !== undefined && { channel: turn.channel }),\n // A recovered turn that takes up what a reset cut off continues it.\n continuation: turn.continuation || turn.trigger === \"recovery-continue\",\n // The clear generation is a tab's turn's alone.\n ...(turn.trigger === \"ws-chat\" && { generation: turn.generation })\n };\n}\n","/**\n * Resolves a `ThinkModel` (a model id string or a `LanguageModel`) into a\n * `LanguageModel` through the bundled `workers-ai-provider`.\n */\n\nimport type { LanguageModel } from \"ai\";\nimport { createWorkersAI } from \"workers-ai-provider\";\nimport { anthropic } from \"workers-ai-provider/anthropic\";\nimport { openai } from \"workers-ai-provider/openai\";\nimport type { ThinkModel } from \"./turn-types\";\n\nconst WORKERS_AI_MODEL_PREFIXES = [\"@cf/\", \"@hf/\"];\n\n/**\n * Whether `model` is a Workers AI id (`@cf/...` or `@hf/...`).\n *\n * @internal\n */\nexport function isWorkersAIModelId(model: string): boolean {\n return WORKERS_AI_MODEL_PREFIXES.some(\n (prefix) => model.startsWith(prefix) && model.length > prefix.length\n );\n}\n\n/**\n * What a {@link ThinkModelResolver} reads from its agent.\n *\n * @internal\n */\ninterface ThinkModelResolverOptions {\n /** The Workers AI binding. Read once, when the first string model resolves. */\n readonly binding: () => Ai;\n /** AI Gateway options for a string model. Must return synchronously. */\n readonly gateway: (model: string) => GatewayOptions | undefined;\n /** Session affinity for Workers AI ids. */\n readonly sessionAffinity: () => string;\n}\n\n/**\n * Builds models through one default provider per agent. The provider is\n * created on first use and cached, which assumes the binding is stable for\n * the lifetime of the agent.\n *\n * @internal\n */\nexport class ThinkModelResolver {\n readonly #options: ThinkModelResolverOptions;\n #provider?: ReturnType<typeof createWorkersAI>;\n\n constructor(options: ThinkModelResolverOptions) {\n this.#options = options;\n }\n\n /**\n * Return `model` as a `LanguageModel`. A `LanguageModel` is returned as-is.\n * A string must be a Workers AI id or a `\"<provider>/<model>\"` AI Gateway\n * slug.\n */\n resolve(model: ThinkModel): LanguageModel {\n if (typeof model !== \"string\") return model;\n // The provider sends every `@...` id straight to `env.AI.run(model)`, so a\n // malformed one would only fail at inference time.\n const isWorkersAI = isWorkersAIModelId(model);\n const slash = model.indexOf(\"/\");\n if (\n !isWorkersAI &&\n (model.startsWith(\"@\") || slash <= 0 || slash === model.length - 1)\n ) {\n throw new Error(\n `Invalid model id ${JSON.stringify(model)}. Use a Workers AI id ` +\n '(e.g. \"@cf/deepseek-ai/deepseek-v4.1-flash-1017\") or a \"<provider>/<model>\" ' +\n 'AI Gateway slug (e.g. \"openai/gpt-5.5\"), or return a LanguageModel.'\n );\n }\n const gateway = this.#options.gateway(model);\n if (\n gateway !== null &&\n typeof gateway === \"object\" &&\n typeof (gateway as { then?: unknown }).then === \"function\"\n ) {\n throw new Error(\n `getGateway() returned a Promise for model \"${model}\". It must return ` +\n \"GatewayOptions (or undefined) synchronously; resolve any async \" +\n \"lookup in beforeTurn and return the model from there instead.\"\n );\n }\n // The bundled `openai` and `anthropic` wire formats let a\n // `\"<provider>/<model>\"` slug route through AI Gateway (OpenAI, Anthropic,\n // Google, xAI, Groq and the OpenAI-compatible long tail).\n this.#provider ??= createWorkersAI({\n binding: this.#options.binding(),\n providers: [openai, anthropic]\n });\n // Workers AI 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 other per-call settings, which avoids forcing\n // options a given provider/transport would reject.\n return isWorkersAI\n ? this.#provider(model, {\n sessionAffinity: this.#options.sessionAffinity(),\n ...(gateway && { gateway })\n })\n : this.#provider(model, gateway && { gateway });\n }\n}\n","import type { DeliverySink } from \"agents/internal\";\n\n/**\n * Where a messenger reply goes that chat recovery will finish: the\n * delivery's payload, sent when the turn is interrupted. The reply is held\n * until recovery settles and releases it with its {@link RecoveredReplyOutcome}.\n *\n * @internal\n */\nexport type RecoveredReplyClaim = {\n messengerId: string;\n threadId: string;\n /** What the interrupted turn already posted. */\n partialText: string;\n};\n\n/**\n * What recovery settled: the delivery's checkpoint once released. `text`\n * is the recovered answer without what was already posted.\n *\n * @internal\n */\nexport type RecoveredReplyOutcome = {\n outcome: \"completed\" | \"interrupted\";\n text?: string;\n};\n\n/** What the messenger host needs to post one part of a recovered reply. */\nexport type RecoveredReplyPost = {\n messengerId: string;\n threadId: string;\n outcome: \"completed\" | \"interrupted\";\n text?: string;\n partialPosted: boolean;\n chunk: number;\n /**\n * Post the messenger's error text instead of the reply: a post of the\n * reply failed and is not sent again.\n */\n notice?: true;\n};\n\n/** The sink recovered messenger replies are delivered through. @internal */\nexport const RECOVERED_REPLY_SINK = \"think-messenger-recovery\";\n\n/** One delivery per recovery incident. @internal */\nexport function recoveredReplyId(incidentId: string): string {\n return `messenger-recovery:${incidentId}`;\n}\n\n/**\n * Most bytes of reply text kept for delivery, so it fits the run's\n * checkpoint with room to spare. No messenger posts a reply anywhere near\n * this long.\n */\nconst MAX_REPLY_TEXT_BYTES = 900_000;\n\nconst encoder = new TextEncoder();\n\nfunction capText(text: string): string {\n if (encoder.encode(text).byteLength <= MAX_REPLY_TEXT_BYTES) return text;\n let end = Math.min(text.length, MAX_REPLY_TEXT_BYTES);\n while (\n end > 0 &&\n encoder.encode(text.slice(0, end)).byteLength > MAX_REPLY_TEXT_BYTES - 3\n ) {\n end = Math.floor(end * 0.9);\n }\n return `${text.slice(0, end)}…`;\n}\n\n/** The claim, cut to fit a delivery. @internal */\nexport function recoveredReplyClaim(\n claim: RecoveredReplyClaim\n): RecoveredReplyClaim {\n return { ...claim, partialText: capText(claim.partialText) };\n}\n\n/**\n * The outcome to release a claim with: a recovered text drops the part\n * already posted.\n *\n * @internal\n */\nexport function recoveredReplyOutcome(\n claim: RecoveredReplyClaim,\n outcome: \"completed\" | \"interrupted\",\n text?: string\n): RecoveredReplyOutcome {\n if (outcome !== \"completed\") return { outcome };\n const recovered = text ?? \"\";\n return {\n outcome,\n text: capText(\n recovered.startsWith(claim.partialText)\n ? recovered.slice(claim.partialText.length)\n : recovered\n )\n };\n}\n\n/**\n * The sink. Held until recovery releases it with an outcome. Each post goes\n * out at most once: the checkpoint's `posted` advances before it, because a\n * rejected post may still have landed (a timeout after the platform\n * accepted it), so a retry resumes with the next post. A reply that lost a\n * post this way ends with the messenger's error text, once, so the thread\n * is not left with part of an answer, or none, and no word. `connect` resolves\n * the messenger host first; failing to reach it fails the attempt without\n * spending a post.\n *\n * @internal\n */\nexport function recoveredReplySink(\n connect: () => Promise<\n (input: RecoveredReplyPost) => Promise<{ chunks: number }>\n >\n): DeliverySink<RecoveredReplyClaim> {\n return {\n // A post that hangs past the attempt timeout keeps running while the\n // retry moves to the next post, so the timeout is long: a reply's posts\n // arrive out of order only if one post hangs for five minutes.\n attemptTimeoutMs: 5 * 60 * 1000,\n deliver: async (claim, attempt) => {\n const outcome =\n attempt.checkpoint.get<RecoveredReplyOutcome[\"outcome\"]>(\"outcome\");\n if (outcome === undefined) return \"hold\";\n const text = attempt.checkpoint.get<string>(\"text\");\n const post = await connect();\n let next = attempt.checkpoint.get<number>(\"posted\") ?? 0;\n let chunks: number | undefined;\n while (chunks === undefined || next < chunks) {\n attempt.checkpoint.set(\"posted\", next + 1);\n try {\n ({ chunks } = await post({\n messengerId: claim.messengerId,\n threadId: claim.threadId,\n outcome,\n ...(text !== undefined && { text }),\n partialPosted: claim.partialText.trim().length > 0,\n chunk: next\n }));\n } catch (error) {\n attempt.checkpoint.set(LOST_A_POST, true);\n throw error;\n }\n next += 1;\n }\n await tellOfLostPost(\n claim,\n attempt.checkpoint,\n () => attempt.checkpoint.set(TOLD_OF_LOST_POST, true),\n post\n );\n },\n // Given up with posts still to send: the thread is told all the same.\n onGiveUp: async (_error, claim, checkpoint) => {\n await tellOfLostPost(claim, checkpoint, undefined, await connect());\n }\n };\n}\n\nconst LOST_A_POST = \"lostPost\";\nconst TOLD_OF_LOST_POST = \"toldOfLostPost\";\n\n/** Post the error text for a reply that lost a post, at most once. */\nasync function tellOfLostPost(\n claim: RecoveredReplyClaim,\n checkpoint: Parameters<\n NonNullable<DeliverySink<RecoveredReplyClaim>[\"onGiveUp\"]>\n >[2],\n /** Remember that the thread was told. Not at a give-up, which comes once. */\n told: (() => void) | undefined,\n post: (input: RecoveredReplyPost) => Promise<{ chunks: number }>\n): Promise<void> {\n if (checkpoint.get<boolean>(LOST_A_POST) !== true) return;\n if (checkpoint.get<boolean>(TOLD_OF_LOST_POST) === true) return;\n told?.();\n try {\n await post({\n messengerId: claim.messengerId,\n threadId: claim.threadId,\n outcome: \"interrupted\",\n partialPosted: true,\n chunk: 0,\n notice: true\n });\n } catch (error) {\n console.error(\"[Think] Messenger failure notice failed\", error);\n }\n}\n\n/** Storage prefix of the replies the released version kept. */\nconst LEGACY_PREFIX = \"cf_think_messenger_recovery:\";\n\n/** A reply as the released version kept it. */\ntype LegacyRecoveredReply = RecoveredReplyClaim & {\n outcome?: \"completed\" | \"interrupted\";\n text?: string;\n posted?: number;\n};\n\n/**\n * Move the replies the released version kept under\n * `cf_think_messenger_recovery:` into deliveries: `posted` and a settled\n * outcome go to the checkpoint; an unsettled one whose incident `isGone`\n * is settled `interrupted`, the rest wait for recovery as held deliveries.\n * One bad record does not hold back the rest, or the start.\n *\n * TEMPORARY: one-shot upgrade path. Remove in the next minor.\n *\n * @returns Whether every record was moved (false: a later start tries).\n * @internal\n */\nexport async function migrateLegacyRecoveredReplies(\n storage: DurableObjectStorage,\n isGone: (incidentId: string) => Promise<boolean>,\n importReply: (\n id: string,\n claim: RecoveredReplyClaim,\n progress: Record<string, string | number>\n ) => Promise<unknown>\n): Promise<boolean> {\n const legacy = await storage.list<LegacyRecoveredReply>({\n prefix: LEGACY_PREFIX\n });\n let moved = true;\n for (const [key, reply] of legacy) {\n try {\n const incidentId = key.slice(LEGACY_PREFIX.length);\n const outcome =\n reply.outcome ??\n ((await isGone(incidentId)) ? (\"interrupted\" as const) : undefined);\n await importReply(\n recoveredReplyId(incidentId),\n recoveredReplyClaim(reply),\n {\n ...(outcome !== undefined && { outcome }),\n ...(reply.text !== undefined && { text: capText(reply.text) }),\n ...(reply.posted !== undefined && { posted: reply.posted })\n }\n );\n await storage.delete(key);\n } catch (error) {\n moved = false;\n console.error(`[Think] could not migrate recovered reply ${key}`, error);\n }\n }\n return moved;\n}\n","/**\n * TEMPORARY: remove in the next minor. The recovered messenger replies\n * think@0.24.0 kept under `cf_think_messenger_recovery:`, carried as\n * deliveries: on the root\n * and in any sub-agent (0.24 kept most of them in a thread's sub-agent, of\n * this class or a resolver's), with or without messengers of its own. Each\n * is posted by the agent that owns the messenger.\n *\n * The sink stays after the import goes: a reply whose model call was tried\n * again posts through it.\n *\n * @internal\n */\n\nimport {\n deliveryDefinition,\n registerDeliverySink,\n releaseDelivery,\n sendDelivery\n} from \"agents/internal\";\nimport {\n CHAT_RECOVERY_INCIDENT_KEY_PREFIX,\n CHAT_RECOVERY_TASK_NAME,\n type ChatRecoveryIncident\n} from \"agents/chat\";\nimport type { Tasks } from \"agents/tasks\";\nimport {\n migrateLegacyRecoveredReplies,\n RECOVERED_REPLY_SINK,\n recoveredReplyId,\n recoveredReplyOutcome,\n recoveredReplySink,\n type RecoveredReplyClaim,\n type RecoveredReplyPost\n} from \"../messengers/recovered-reply\";\n\n/** @internal */\nexport type ReleasedReplies = {\n /**\n * Move the replies 0.24 kept into deliveries. Called at start.\n *\n * @param releaseRan - Whether 0.24 ran since its records were last moved.\n * @returns Whether every record was moved (false: a later start tries).\n */\n importAll(releaseRan: boolean): Promise<boolean>;\n /** Release the reply held for a 0.24 recovery incident. */\n release(\n incidentId: string,\n outcome: \"completed\" | \"interrupted\",\n text?: string\n ): Promise<boolean>;\n};\n\n/**\n * Register the recovered-reply sink, and 0.24's recovery job, on `tasks`.\n * `post` connects to whoever posts a piece of a reply.\n *\n * @internal\n */\nexport function releasedReplies(options: {\n tasks: Tasks;\n storage: DurableObjectStorage;\n post(): Promise<(input: RecoveredReplyPost) => Promise<{ chunks: number }>>;\n /**\n * A recovery job 0.24 queued has come due and held no messenger reply:\n * the host takes up the request it was to retry or continue.\n */\n takeUp?(data: Record<string, unknown>): Promise<void>;\n}): ReleasedReplies {\n const { tasks, storage } = options;\n\n // A recovered reply is posted as Think posts it: the rest of the answer,\n // from its cursor, the apology, or the empty-response text.\n registerDeliverySink(\n tasks,\n RECOVERED_REPLY_SINK,\n recoveredReplySink(options.post)\n );\n\n /** Whether a 0.24 recovery incident is over (or never was). */\n async function incidentGone(incidentId: string): Promise<boolean> {\n const incident = await storage.get<ChatRecoveryIncident>(\n CHAT_RECOVERY_INCIDENT_KEY_PREFIX + encodeURIComponent(incidentId)\n );\n return (\n !incident ||\n incident.status === \"skipped\" ||\n incident.status === \"exhausted\"\n );\n }\n\n async function release(\n incidentId: string,\n outcome: \"completed\" | \"interrupted\",\n text?: string\n ): Promise<boolean> {\n const id = recoveredReplyId(incidentId);\n const claim = tasks.inputOf<RecoveredReplyClaim>(id);\n if (!claim) return false;\n await releaseDelivery(\n tasks,\n id,\n recoveredReplyOutcome(claim, outcome, text)\n );\n return true;\n }\n\n // A recovery job 0.24 queued, come due (it waited out its backoff). A\n // messenger reply held for its incident is released as interrupted: that\n // thread is told. Any other request it was to retry or continue is taken\n // up by the host, so it is answered and not lost.\n tasks.register(CHAT_RECOVERY_TASK_NAME, async (input: unknown) => {\n const data = (input as { data?: Record<string, unknown> } | null)?.data;\n const incidentId = data?.incidentId;\n const held =\n typeof incidentId === \"string\" &&\n (await release(incidentId, \"interrupted\"));\n if (!held && data) await options.takeUp?.(data);\n });\n\n return {\n async importAll(releaseRan) {\n // As Think moves them: settled ones are delivered; one whose incident\n // still recovers is held, at once, so a release finds it; the rest\n // are apologized for. 0.24's records are read only at a start after\n // it ran: once moved they are gone.\n const moved =\n !releaseRan ||\n (await migrateLegacyRecoveredReplies(\n storage,\n incidentGone,\n (id, claim, progress) =>\n progress.outcome === undefined\n ? sendDelivery(tasks, RECOVERED_REPLY_SINK, id, claim)\n : sendDelivery(tasks, RECOVERED_REPLY_SINK, id, claim, {\n sentAt: Date.now(),\n attempts: 0,\n progress\n })\n ));\n // A held reply whose incident is gone: nothing will release it now.\n const prefix = recoveredReplyId(\"\");\n for (const held of tasks.peekList({\n definition: deliveryDefinition(RECOVERED_REPLY_SINK),\n status: [\"pending\"],\n parked: true,\n results: false\n })) {\n const incidentId = held.runId.slice(prefix.length);\n if (await incidentGone(incidentId)) {\n await release(incidentId, \"interrupted\");\n }\n }\n return moved;\n },\n release\n };\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\ninterface 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 * Channel resolution and out-of-turn notices for a Think agent. The channel\n * registry itself is built by {@link resolveChannels}; this module turns a\n * channel id into a turn's {@link ChannelContext} and delivers notices to a\n * channel's surface.\n */\n\nimport type { UIMessage } from \"ai\";\nimport type {\n DeliveryKind,\n MessengerContext,\n MessengerDeliverySurface\n} from \"../messengers\";\nimport type { DeliverNoticeOptions } from \"../turn-types\";\nimport type { ChannelContext, NormalizedChannelDefinition } from \"./index\";\n\n/**\n * Observability events about channels.\n *\n * @internal\n */\nexport type 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 * Resolve a channel id to a turn-scoped {@link ChannelContext}. `registry`\n * is `undefined` on an agent that has no channel registry (a sub-agent),\n * where a missing channel is expected.\n *\n * @internal\n */\nexport function resolveChannelContext(\n channel: string | undefined,\n options: {\n registry: ReadonlyMap<string, NormalizedChannelDefinition> | undefined;\n requestId: string | undefined;\n messengerContext: () => MessengerContext | undefined;\n emit: (event: ChannelEvent) => void;\n }\n): ChannelContext | undefined {\n if (!channel) {\n return undefined;\n }\n const definition = options.registry?.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 if (options.registry) {\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 options.emit({\n type: \"channel:resolved\",\n payload: {\n channel,\n kind: definition.kind,\n requestId: options.requestId\n }\n });\n return {\n channelId: channel,\n kind: definition.kind,\n capabilities: definition.capabilities,\n messenger:\n definition.kind === \"messenger\" ? options.messengerContext() : undefined\n };\n}\n\n/**\n * A framework-authored assistant message that carries a notice.\n *\n * @internal\n */\nfunction noticeMessage(text: string, kind: DeliveryKind = \"notice\"): UIMessage {\n return {\n id: crypto.randomUUID(),\n role: \"assistant\",\n parts: [{ type: \"text\", text }],\n metadata: { deliveryKind: kind }\n };\n}\n\n/**\n * What {@link deliverChannelNotice} needs from the agent.\n *\n * @internal\n */\ninterface ChannelNoticeTarget {\n /** The channel to deliver to. */\n readonly channelId: string;\n readonly registry:\n | ReadonlyMap<string, NormalizedChannelDefinition>\n | undefined;\n /** The delivery surface for a non-web channel, if one can be found. */\n readonly surface: () => Promise<MessengerDeliverySurface | undefined>;\n /** Append to the transcript without starting a turn. */\n readonly addMessages: (messages: UIMessage[]) => Promise<unknown>;\n readonly emit: (event: ChannelEvent) => void;\n}\n\n/**\n * Deliver a no-turn notice to a channel. The `web` channel renders through\n * the transcript, so a web notice is always appended; other channels post to\n * their delivery surface and touch the transcript only with `informModel`.\n *\n * @throws When a non-web channel has no delivery surface.\n *\n * @internal\n */\nexport async function deliverChannelNotice(\n text: string | { markdown: string },\n options: DeliverNoticeOptions | undefined,\n target: ChannelNoticeTarget\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 = target.channelId;\n\n try {\n if (channelId === \"web\") {\n await target.addMessages([\n noticeMessage(informModel ? annotated : plain, kind)\n ]);\n } else {\n const surface = await target.surface();\n if (!surface) {\n const kindOf = target.registry?.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 target.addMessages([noticeMessage(annotated, kind)]);\n }\n }\n target.emit({\n type: \"notice:delivered\",\n payload: { channel: channelId, kind, informModel }\n });\n } catch (error) {\n target.emit({\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 * Server-written turn context on user messages: the channel a turn ran on\n * and the caller's turn metadata. Both are stamped on the durable user\n * message so a recovered or continued turn re-resolves them from history,\n * and both are reserved keys that a client can never set.\n */\n\nimport type { UIMessage } from \"ai\";\n\n/**\n * Message-metadata keys that are server-written turn context (stamped by\n * {@link stampTurnContext}) and trusted by hooks and recovery. They are\n * stripped from client-supplied messages at intake so a client can never\n * forge them.\n *\n * @internal\n */\nexport const RESERVED_MESSAGE_METADATA_KEYS = [\n \"channel\",\n \"turnMetadata\"\n] as const;\n\n/**\n * The reserved keys `message` carries, or `undefined` when it has none.\n *\n * @internal\n */\nexport function reservedMetadataOf(\n message: UIMessage\n): Record<string, unknown> | undefined {\n const metadata = message.metadata;\n if (\n typeof metadata !== \"object\" ||\n metadata === null ||\n Array.isArray(metadata)\n ) {\n return undefined;\n }\n const reserved: Record<string, unknown> = {};\n for (const key of RESERVED_MESSAGE_METADATA_KEYS) {\n if (key in metadata) {\n reserved[key] = (metadata as Record<string, unknown>)[key];\n }\n }\n return Object.keys(reserved).length > 0 ? reserved : undefined;\n}\n\n/**\n * The stored form of a client-sourced message's metadata: Sessions drops the\n * reserved keys on every client write, so a compare against a stored row has\n * to drop them too. Mirrors `SessionCore.stripReservedMetadata` for the keys\n * Think registers.\n *\n * @internal\n */\nexport function stripReservedMetadata(message: UIMessage): UIMessage {\n const metadata = message.metadata;\n if (\n typeof metadata !== \"object\" ||\n metadata === null ||\n Array.isArray(metadata)\n ) {\n return message;\n }\n const remaining: Record<string, unknown> = { ...metadata };\n let changed = false;\n for (const key of RESERVED_MESSAGE_METADATA_KEYS) {\n if (key in remaining) {\n delete remaining[key];\n changed = true;\n }\n }\n if (!changed) return message;\n if (Object.keys(remaining).length > 0) {\n return { ...message, metadata: remaining };\n }\n const { metadata: _dropped, ...withoutMetadata } = message;\n return withoutMetadata as UIMessage;\n}\n\n/**\n * Stamp the channel id, and the caller's turn metadata when supplied, onto\n * the user messages.\n *\n * @internal\n */\nexport function stampTurnContext(\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. */\nfunction 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/**\n * The channel stamped on the latest user message in the given list, if any.\n *\n * @internal\n */\nexport function channelFromMessages(messages: UIMessage[]): string | undefined {\n const channel = latestUserMessageMetadata(messages)?.channel;\n return typeof channel === \"string\" ? channel : undefined;\n}\n\n/**\n * The turn metadata stamped on the latest user message, if any.\n *\n * @internal\n */\nexport function turnMetadataFromMessages(\n messages: UIMessage[]\n): Record<string, unknown> | undefined {\n const turnMetadata = 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 * Think's messengers, on Channels. Each messenger from\n * `getMessengers()` takes its webhooks through Think's Chat SDK `Chat` (the\n * release's state rows: subscriptions, thread locks, queued messages),\n * which decides what is answered, and where, as in Think. An event answered\n * here (`conversation: \"self\"`) joins the harness's default session through\n * `Channels.forHarness`, and its reply goes out through the messenger's Chat\n * SDK Channel as a delivery run, to the asking thread only. An event whose\n * conversation is a sub-agent's (`\"thread\"`, the default, or a resolver's\n * target) is answered there, and this object posts the reply to the thread\n * in a messenger reply run, as Think does.\n *\n * Durable: each turn's asker in KV until the turn settles (with Chat SDK\n * state, Channels' Streams and KV, and the deliveries' runs). In memory:\n * the definitions, the `Chat`, and the turns webhooks wait on.\n */\n\nimport type { UIMessage } from \"ai\";\nimport type { Adapter, Chat, Thread as ChatThread } from \"chat\";\nimport type { ThinkHarness } from \"agents/harness/think\";\nimport type { StreamCallback } from \"../turn-types\";\nimport {\n chatSdkChannel,\n deliverToSurfaces,\n sendDelivery\n} from \"agents/internal\";\nimport {\n RECOVERED_REPLY_SINK,\n recoveredReplyId,\n recoveredReplyOutcome,\n type RecoveredReplyClaim,\n type RecoveredReplyPost\n} from \"../messengers/recovered-reply\";\nimport {\n Channels,\n type ChannelMessageSurface,\n type ChannelsHost,\n type ConversationUpdate\n} from \"agents/experimental/channels\";\n\n/** A Channels turn's status, from its update. */\ntype TurnStatus = Extract<ConversationUpdate, { type: \"turn\" }>[\"turn\"];\n\n/** A message's text, its text parts joined. */\nfunction messageText(message: UIMessage | undefined): string {\n return (message?.parts ?? [])\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\");\n}\nimport { Streams } from \"agents/streams\";\nimport type { Tasks } from \"agents/tasks\";\nimport {\n createMessengerChat,\n defaultConversationName,\n drainStrandedQueue,\n reviveMessengerThread,\n idempotencyKeyForEvent,\n normalizeMessengers,\n recoveredReplyPosts,\n withMessengerQueueTtl,\n type MessengerConcurrency,\n type MessengerThinkTarget,\n type NormalizedMessengerDefinition,\n type ThinkMessengers\n} from \"../messengers/chat-sdk\";\nimport {\n deliverMessengerReply,\n ERROR_MESSENGER_RESPONSE,\n INTERRUPTED_MESSENGER_RESPONSE,\n messengerReplyRecoveryMode,\n reviveMessengerEvent\n} from \"../messengers/delivery\";\nimport {\n RELEASED_REPLY_DEFINITION,\n registerMessengerReplySink,\n releasedSnapshot,\n sendMessengerReply,\n type RecordReplyStage,\n postApology\n} from \"../messengers/reply-task\";\nimport {\n messengerContextFromEvent,\n serializableMessengerEvent,\n toMessengerUserMessage,\n type MessengerContext,\n type MessengerEvent\n} from \"../messengers/events\";\n\n/**\n * A capability installed before Think can know whether its app has any\n * messengers: it does nothing at startup, and starts (its schema, its\n * reads) only when the first messenger is mounted. An agent with no\n * messengers never pays for it.\n */\nclass StreamsStartedOnDemand extends Streams {\n #wanted = false;\n override async onStart(): Promise<void> {\n if (this.#wanted) await super.onStart();\n }\n /** Run the start that was held back. */\n async startNow(): Promise<void> {\n if (this.#wanted) return;\n this.#wanted = true;\n await super.onStart();\n }\n}\n\n/** As {@link StreamsStartedOnDemand}, for Channels. */\nclass ChannelsStartedOnDemand extends Channels {\n #wanted = false;\n override async onStart(): Promise<void> {\n if (this.#wanted) await super.onStart();\n }\n /** Run the start that was held back. */\n async startNow(): Promise<void> {\n if (this.#wanted) return;\n this.#wanted = true;\n await super.onStart();\n }\n}\n\n/** @internal */\nexport type ThinkMessengerChannels = {\n readonly channels: Channels;\n /**\n * Mount the app's messengers, once: called when Think has started far\n * enough to read them (after its session, context and transcript). With\n * none, nothing is started and nothing is read or written.\n */\n fill(messengers: ThinkMessengers): Promise<void>;\n /** Take a webhook for a messenger; `undefined` when none owns its path. */\n receive(request: Request): Promise<Response | undefined>;\n /** The messengers' ids. */\n readonly ids: readonly string[];\n /**\n * The messenger whose webhook sent user message `messageId`, while its\n * turn runs (the message's id is its event's).\n */\n channelOf(messageId: string): string | undefined;\n /** The messenger context of user message `messageId`, while its turn runs. */\n contextOf(messageId: string): MessengerContext | undefined;\n /** Post one piece of a recovered reply with this object's messenger. */\n deliverRecoveredReply(input: RecoveredReplyPost): Promise<{ chunks: number }>;\n /** Where a notice to messenger `id`'s `thread` is posted, if anywhere. */\n noticeSurface(\n id: string,\n thread: string | undefined\n ):\n | { post(text: string | { markdown: string }): Promise<unknown> }\n | undefined;\n};\n\ntype ChannelEvent = Parameters<Channels[\"receive\"]>[0];\ntype MessagePart = Extract<\n ChannelEvent,\n { type: \"message\" }\n>[\"message\"][\"parts\"][number];\n\n/**\n * The messengers as Channels, or `undefined` when there are none. Only the\n * root object takes their webhooks, as in Think; whether this one is the\n * root is known only once it started (a sub-agent learns its path then), so\n * it is asked per request, and a sub-agent's Channels stay idle.\n *\n * @internal\n */\nexport function messengerChannels(options: {\n harness: ThinkHarness;\n tasks: Tasks;\n /** Whether this object is the root, not a sub-agent. */\n root(): boolean;\n /** Where each turn's asker is kept, so a reply after a reset finds it. */\n kv: SyncKvStorage;\n /** Where think@0.24.0 kept the replies it left unfinished. */\n storage: DurableObjectStorage;\n /** The Think object: Chat SDK state lives on its sub-agents. */\n parent: unknown;\n /** Read when the first webhook arrives, as Think reads it at start. */\n concurrency(): MessengerConcurrency;\n /**\n * The sub-agent a thread's conversation is in (`conversation: \"thread\"`,\n * the default, or a resolver's `subagent` target), as in Think: this\n * class unless the target names another.\n */\n subAgent(\n agentClass: unknown,\n name: string\n ): Promise<Required<MessengerThinkTarget>>;\n}): ThinkMessengerChannels {\n // Empty until `fill()`: the app's messengers are read once Think has\n // started far enough for its `getMessengers()` to run, after this was\n // installed.\n const definitions: NormalizedMessengerDefinition[] = [];\n /**\n * The deliveries' first attempts of each operation, collected for every\n * answer waiting on it.\n */\n const attempts = new Map<string, Set<Promise<void>[]>>();\n /** Each waiting answer's operation, told when Channels settles the turn. */\n const settled = new Map<string, Set<() => void>>();\n let turnsHost: ChannelsHost | undefined;\n const streams = new StreamsStartedOnDemand({ name: \"think-messengers\" });\n /** Each running turn's first response in this isolate. */\n const firstResponses = new Map<string, string>();\n /**\n * Turns whose model call failed and was tried again in this isolate, with\n * what their first attempt had written: the later attempts are not\n * delivered live, but posted once the turn settles, as Think posts a\n * recovered reply (the rest of the answer, the apology, or the\n * empty-response text). A reset's rerun, in a new isolate, streams.\n */\n const retried = new Map<string, Promise<string>>();\n\n /** The text of saved message `id`, or \"\" when there is none. */\n async function textOf(id: string | undefined): Promise<string> {\n if (id === undefined) return \"\";\n const messages = await options.harness.session().messages();\n return messageText(messages.find((message) => message.id === id));\n }\n\n /** The text response `responseId` streamed (what went out live). */\n async function partialText(responseId: string): Promise<string> {\n let text = \"\";\n for await (const { chunk } of streams.read(responseId)) {\n const delta = chunk as { type?: unknown; delta?: unknown };\n if (delta.type === \"text-delta\" && typeof delta.delta === \"string\") {\n text += delta.delta;\n }\n }\n return text;\n }\n\n /** Post a retried turn's reply to its asker, as Think posts a recovered one. */\n async function postRetried(\n asker: ChannelMessageSurface,\n turn: Extract<TurnStatus, { status: \"settled\" }>,\n partial: Promise<string>\n ): Promise<void> {\n const definition = definitions.find((d) => d.id === asker.channelKey);\n const threadId = (asker.address as { threadId?: unknown }).threadId;\n if (!definition || typeof threadId !== \"string\") return;\n const posted = await partial;\n const text = await textOf(turn.messageIds.at(-1));\n // Posted as a recovered reply is: a durable delivery that keeps its\n // cursor, so a rejected part does not hold back the parts after it.\n const claim: RecoveredReplyClaim = {\n messengerId: definition.id,\n threadId,\n partialText: posted\n };\n const outcome = recoveredReplyOutcome(\n claim,\n turn.outcome === \"failed\" ? \"interrupted\" : \"completed\",\n text\n );\n // A new delivery: its first attempt runs now, so the webhook that\n // waits on it holds the thread until the reply is posted.\n await sendDelivery(\n options.tasks,\n RECOVERED_REPLY_SINK,\n recoveredReplyId(`retried:${turn.startedBy}`),\n claim,\n undefined,\n {\n progress: {\n outcome: outcome.outcome,\n ...(outcome.text !== undefined && { text: outcome.text })\n }\n }\n );\n }\n\n /**\n * Watch `operation`'s turn from before Channels takes it. `settled()`\n * resolves once Channels settled the turn, after every update before it\n * was published (so the turn's deliveries started). It waits for the\n * harness first; a turn Channels settled already (a repeated event) is no\n * longer in its snapshot.\n */\n function watchTurn(operation: string): TurnWatch {\n let resolve!: () => void;\n const seen = new Promise<void>((r) => (resolve = r));\n const waiters = settled.get(operation) ?? new Set();\n settled.set(operation, waiters.add(resolve));\n const release = () => {\n waiters.delete(resolve);\n if (waiters.size === 0 && settled.get(operation) === waiters) {\n settled.delete(operation);\n }\n };\n return {\n release,\n async settled() {\n try {\n await options.harness.session().wait(operation);\n const host = turnsHost;\n const snapshot =\n host && (await host.snapshot(host.defaultConversation()));\n const open = snapshot?.turns.some(\n (turn) => turn.startedBy === operation && turn.status !== \"settled\"\n );\n if (open) await seen;\n } finally {\n release();\n }\n }\n };\n }\n\n const channels = new ChannelsStartedOnDemand({\n harness: options.harness,\n streams,\n channels: Object.fromEntries([\n // Sees each turn settle after every update before it was published\n // (so its deliveries started), for the answer that waits on it.\n [\n TURNS_KEY,\n {\n mount(host: ChannelsHost) {\n turnsHost = host;\n },\n publish(_conversationId: string, update: ConversationUpdate) {\n if (update.type === \"turn\" && update.turn.status === \"running\") {\n const { startedBy, responseId } = update.turn;\n const first = firstResponses.get(startedBy);\n if (first === undefined) {\n firstResponses.set(startedBy, responseId);\n } else if (\n first !== responseId &&\n !retried.has(startedBy) &&\n // Its webhook still waits here: the model call failed and\n // was tried again. A reset's rerun has no live webhook.\n attempts.has(startedBy)\n ) {\n retried.set(startedBy, partialText(first));\n }\n }\n if (update.type === \"turn\" && update.turn.status === \"settled\") {\n const startedBy = update.turn.startedBy;\n firstResponses.delete(startedBy);\n const partial = retried.get(startedBy);\n retried.delete(startedBy);\n const kept = options.kv.get<ChannelMessageSurface>(\n askerKey(startedBy)\n );\n if (partial && kept) {\n const posting = postRetried(kept, update.turn, partial);\n // The answer that waits on the turn waits on this too.\n const waiting = attempts.get(startedBy);\n if (waiting) {\n for (const mine of waiting) mine.push(posting);\n } else {\n void posting.catch((error: unknown) =>\n console.error(\n \"[Think] A retried reply was not posted\",\n error\n )\n );\n }\n }\n // A turn no webhook here waits on is one a reset cut off and\n // the harness ran again: the Chat handler that held its thread\n // died with the reset, so what queued behind it is drained, as\n // Think drains it after recovering a reply.\n const asker = options.kv.get<ChannelMessageSurface>(\n askerKey(startedBy)\n );\n if (asker && !attempts.has(startedBy)) {\n drainLater(asker);\n }\n // Its replies have started: the asker is not read again.\n options.kv.delete(askerKey(startedBy));\n options.kv.delete(contextKey(startedBy));\n for (const resolve of settled.get(update.turn.startedBy) ?? []) {\n resolve();\n }\n }\n }\n }\n ]\n ])\n });\n\n /** Failure notices being posted (see `onGiveUp` below). */\n const notices = new Map<string, Set<Promise<void>>>();\n\n /** The Channel one messenger's replies are delivered through. */\n const channelOfMessenger = (definition: NormalizedMessengerDefinition) => {\n const channel = chatSdkChannel({\n adapter: definition.adapter,\n name: definition.adapterName,\n path: definition.path,\n // The Chat below owns the adapter's webhooks and its chat\n // instance; this Channel only sends.\n initialize: () => chat().initialize(),\n ...(definition.userName && { userName: definition.userName })\n });\n return deliverToSurfaces(channel, {\n tasks: options.tasks,\n // A reply whose post the provider failed is not posted again (part\n // of it may be in the thread): the thread is told it could not be\n // answered, as when the reply runs in the thread's sub-agent and\n // as in 0.24.\n onGiveUp: (delivery) => {\n const notice = Promise.resolve(\n channel.deliver?.(\n delivery.surface,\n {\n markdown:\n definition.delivery?.errorResponseText ??\n ERROR_MESSENGER_RESPONSE\n },\n { delivery: { deliveryId: `${delivery.responseId}:not-sent` } }\n )\n ).then(\n () => undefined,\n (error: unknown) => {\n console.error(\"[Think] Messenger failure notice failed\", error);\n }\n );\n // The event's handler waits for it before it lets the thread go,\n // so the notice is not overtaken by the next message's reply.\n // Its own thread only: another thread's handler does not wait.\n const thread = JSON.stringify(delivery.surface);\n const pending = notices.get(thread) ?? new Set();\n notices.set(thread, pending.add(notice));\n void notice.finally(() => {\n pending.delete(notice);\n if (pending.size === 0 && notices.get(thread) === pending) {\n notices.delete(thread);\n }\n });\n return notice;\n },\n // Every thread shares the default session, as in Think: a reply\n // goes to the thread whose message started its turn, only.\n asker: (startedBy) =>\n retried.has(startedBy)\n ? undefined\n : options.kv.get<ChannelMessageSurface>(askerKey(startedBy)),\n sending: (startedBy, attempt) =>\n attempts.get(startedBy)?.forEach((mine) => mine.push(attempt))\n });\n };\n\n /**\n * Answer one event the Chat routed here: it joins the default session,\n * and the handler (holding the thread's lock, as in Think) returns once\n * Channels settled the turn and its deliveries' first attempts ended (one\n * that failed and waits to retry is not waited for).\n */\n async function answer(\n definition: NormalizedMessengerDefinition,\n event: MessengerEvent\n ): Promise<void> {\n const eventId = idempotencyKeyForEvent(event);\n const author = event.message?.author ?? event.action?.user;\n const threadId = event.thread.id;\n const surface: ChannelMessageSurface = {\n channelKey: definition.id,\n version: 1,\n address: { threadId },\n label: `${definition.adapterName} · ${threadId}`,\n key: threadId\n };\n const mine: Promise<void>[] = [];\n const waiting = attempts.get(eventId) ?? new Set();\n attempts.set(eventId, waiting.add(mine));\n // Watched before Channels takes it, so its settling is seen.\n const turn = watchTurn(eventId);\n try {\n options.kv.put(askerKey(eventId), surface);\n // As in Think, the turn's messenger context, from the event.\n options.kv.put(contextKey(eventId), messengerContextFromEvent(event));\n await channels.receive(\n {\n type: \"message\",\n eventId,\n message: {\n id: eventId,\n role: \"user\",\n parts: messageParts(\n toMessengerUserMessage(event, definition.channelSpeakerLabel)\n )\n }\n },\n {\n route: definition.id,\n participant: {\n id: `${definition.adapterName}:${author?.userId ?? \"unknown\"}`\n },\n surface\n }\n );\n await turn.settled();\n await Promise.all(mine);\n // A delivery given up tells the thread before the thread is let go.\n await Promise.all(notices.get(JSON.stringify(surface)) ?? []);\n // Also here: a repeated event's turn settled before it came, and will\n // not settle again.\n options.kv.delete(askerKey(eventId));\n options.kv.delete(contextKey(eventId));\n } finally {\n turn.release();\n waiting.delete(mine);\n if (waiting.size === 0 && attempts.get(eventId) === waiting) {\n attempts.delete(eventId);\n }\n }\n }\n\n // TEMPORARY: remove in the next minor after this ships. A reply\n // think@0.24.0 left unfinished: answered again if no text of it went out,\n // apologized for if some did, as Think does; a completed one posts\n // nothing more.\n options.tasks.register(RELEASED_REPLY_DEFINITION, async (_input, step) => {\n const key = `__cf_messenger_recovery:${step.id}`;\n const kept = await options.storage.get(key);\n const snapshot = releasedSnapshot(kept);\n const event = snapshot && reviveMessengerEvent(snapshot.event);\n const definition =\n event && definitions.find((d) => d.id === event.messengerId);\n if (snapshot && event && definition) {\n const mode = messengerReplyRecoveryMode(snapshot.stage);\n try {\n if (mode === \"answer\") await answer(definition, event);\n if (mode === \"apologize\") {\n await chat().initialize();\n const { adapter } = definition;\n await postApology(\n {\n post: (markdown) =>\n adapter.postMessage(event.thread.id, { markdown })\n },\n definition.delivery?.interruptedResponseText ??\n INTERRUPTED_MESSENGER_RESPONSE,\n definition.delivery?.errorResponseText ?? ERROR_MESSENGER_RESPONSE,\n // The reply is over: a restart does not apologize again. The\n // snapshot stays, as completed, so that restart still knows\n // the thread whose queue it has to answer.\n () =>\n options.storage.put(key, {\n ...(kept as object),\n stage: \"completed\"\n })\n );\n }\n } finally {\n // As Think does after recovering a reply, even one that failed:\n // what queued behind it is answered, whatever the reply's stage.\n drainThread(definition, event.thread.id);\n }\n }\n await options.storage.delete(key);\n });\n\n // A recovered reply is posted as Think posts it (the sink is the\n // released-replies module's): the rest of the answer, from its cursor,\n // the apology, or the empty-response text.\n /** Post piece `input.chunk` of a recovered reply; how many there are. */\n async function deliverRecoveredReply(\n input: RecoveredReplyPost\n ): Promise<{ chunks: number }> {\n const definition = definitions.find((d) => d.id === input.messengerId);\n if (!definition) return { chunks: 0 };\n const posts = recoveredReplyPosts(definition, input);\n const post = posts[input.chunk];\n if (post !== undefined) {\n await chat().initialize();\n await definition.adapter.postMessage(input.threadId, post);\n }\n return { chunks: posts.length };\n }\n\n /** Drain the thread `asker` names, in the background. */\n function drainLater(asker: ChannelMessageSurface): void {\n const definition = definitions.find((d) => d.id === asker.channelKey);\n const threadId = (asker.address as { threadId?: unknown }).threadId;\n if (!definition || typeof threadId !== \"string\") return;\n drainThread(definition, threadId);\n }\n\n /** Drain `threadId`'s stranded queue, in the background. */\n function drainThread(\n definition: NormalizedMessengerDefinition,\n threadId: string\n ): void {\n const drain = () => drainStrandedQueue(chat(), definition, threadId);\n const keepAlive = (\n options.parent as {\n keepAliveWhile?: <T>(fn: () => Promise<T>) => Promise<T>;\n }\n ).keepAliveWhile;\n const running = keepAlive ? keepAlive.call(options.parent, drain) : drain();\n void running.catch((error: unknown) => {\n console.error(\n `[Think] Failed to drain messages queued on ${threadId}`,\n error\n );\n });\n }\n\n /**\n * Where an event's conversation is, as Think resolves it: here\n * (`\"self\"`), or a sub-agent's turn this object posts the reply of.\n */\n async function conversationOf(\n definition: NormalizedMessengerDefinition,\n event: MessengerEvent\n ): Promise<Required<MessengerThinkTarget> | \"self\"> {\n const conversation = definition.conversation ?? \"thread\";\n const target =\n typeof conversation === \"function\"\n ? await conversation(event)\n : conversation === \"self\"\n ? { target: \"self\" as const }\n : {\n name: defaultConversationName(event),\n target: \"subagent\" as const\n };\n if (target.target === \"self\") return \"self\";\n const stub = await options.subAgent(target.agentClass, target.name);\n // A live thread cannot cross the sub-agent RPC boundary.\n return {\n cancelChat: (requestId, reason) => stub.cancelChat(requestId, reason),\n chat: (userMessage, callback) => stub.chat(userMessage, callback),\n chatWithMessengerContext: (userMessage, callback, context) =>\n stub.chatWithMessengerContext(userMessage, callback, context)\n };\n }\n\n /**\n * Post a sub-agent's answer to `event` to its thread, as Think does. A\n * model call the sub-agent tried again after a transient failure, once\n * some text had streamed, is posted as Think posts a recovered reply: the\n * streamed part ends as it is, and the rest follows as its own post (or\n * the apology, if the retry failed).\n */\n async function replyFrom(\n target: Required<MessengerThinkTarget>,\n definition: NormalizedMessengerDefinition,\n event: MessengerEvent,\n thread: ChatThread,\n record: RecordReplyStage\n ): Promise<void> {\n const retried = { interrupted: false, rest: \"\", failed: false };\n const follow = (callback: StreamCallback): StreamCallback => {\n let streamed = false;\n return {\n onStart: (start) => callback.onStart(start),\n onEvent(json) {\n const chunk = JSON.parse(json) as { type?: string; delta?: string };\n if (retried.interrupted) {\n if (chunk.type === \"text-delta\") retried.rest += chunk.delta ?? \"\";\n return;\n }\n if (chunk.type === \"text-delta\" && chunk.delta) streamed = true;\n return callback.onEvent(json);\n },\n onDone: () => (retried.interrupted ? undefined : callback.onDone()),\n onError(error) {\n if (!retried.interrupted) return callback.onError(error);\n retried.failed = true;\n },\n // The sub-agent tries a cut model call again within the turn, and\n // goes on from where the cut attempt stopped. Before any text\n // there is nothing to end: the retry is the reply.\n onInterrupted(info) {\n if (!streamed || retried.interrupted) return;\n retried.interrupted = true;\n return callback.onInterrupted?.(info);\n }\n };\n };\n await deliverMessengerReply({\n event,\n onStage: record,\n policy: definition.delivery,\n snapshotEvent: serializableMessengerEvent(event),\n surface: thread,\n target: {\n cancelChat: target.cancelChat,\n chat: (message, callback) => target.chat(message, follow(callback)),\n chatWithMessengerContext: (message, callback, context) =>\n target.chatWithMessengerContext(message, follow(callback), context)\n },\n userMessage: toMessengerUserMessage(event, definition.channelSpeakerLabel)\n });\n if (!retried.interrupted) return;\n const posts =\n retried.failed || retried.rest === \"\"\n ? [\n definition.delivery?.interruptedResponseText ??\n INTERRUPTED_MESSENGER_RESPONSE\n ]\n : (definition.delivery?.splitText?.(retried.rest) ?? [retried.rest]);\n for (const post of posts) await thread.post(post);\n }\n\n /**\n * Answer an event the Chat routed here where its conversation is. In a\n * sub-agent's, as in Think: the sub-agent runs the turn, and this object\n * posts what it streams to the thread, in a reply run that a reset\n * answers again, or apologizes for, by the stage it reached.\n */\n async function route(\n definition: NormalizedMessengerDefinition,\n event: MessengerEvent,\n thread: ChatThread\n ): Promise<void> {\n const target = await conversationOf(definition, event);\n if (target === \"self\") return answer(definition, event);\n await sendMessengerReply(options.tasks, idempotencyKeyForEvent(event), {\n payload: {\n event: serializableMessengerEvent(event),\n thread: thread.toJSON()\n },\n answer: (record) => replyFrom(target, definition, event, thread, record)\n });\n }\n\n registerMessengerReplySink(options.tasks, () => ({\n async recoverReply(payload, stage, record) {\n const event = reviveMessengerEvent(payload.event);\n const definition = definitions.find((d) => d.id === event.messengerId);\n if (!definition) {\n throw new Error(\n `No messenger definition found for recovered messenger ${event.messengerId}`\n );\n }\n await chat().initialize();\n const thread = reviveMessengerThread(chat(), definition, payload.thread);\n const mode = messengerReplyRecoveryMode(stage);\n if (mode === \"answer\") {\n const target = await conversationOf(definition, event);\n if (target === \"self\") await answer(definition, event);\n else await replyFrom(target, definition, event, thread, record);\n }\n if (mode === \"apologize\") {\n // As Think posts it: plain text.\n await postApology(\n thread,\n definition.delivery?.interruptedResponseText ??\n INTERRUPTED_MESSENGER_RESPONSE,\n definition.delivery?.errorResponseText ?? ERROR_MESSENGER_RESPONSE,\n () => record(\"completed\")\n );\n record(\"completed\");\n }\n },\n drainAfterRecovery(payload) {\n const definition = definitions.find(\n (d) => d.id === payload.event.messengerId\n );\n if (definition) drainThread(definition, payload.event.thread.id);\n }\n }));\n\n let made: Chat<Record<string, Adapter>> | undefined;\n const chat = () =>\n (made ??= createMessengerChat({\n definitions,\n concurrency: withMessengerQueueTtl(options.concurrency()),\n parent: options.parent,\n onEvent: (definition, event, thread) => route(definition, event, thread)\n }));\n\n return {\n channels,\n get ids() {\n return definitions.map((definition) => definition.id);\n },\n async fill(messengers) {\n if (definitions.length > 0) {\n throw new Error(\"The messengers are already mounted\");\n }\n const declared = normalizeMessengers(messengers);\n if (declared.some((definition) => definition.id === TURNS_KEY)) {\n throw new Error(`\"${TURNS_KEY}\" is reserved and is not a messenger id`);\n }\n if (declared.length === 0) return;\n for (const definition of declared) {\n channels.internal_addChannel(\n definition.id,\n channelOfMessenger(definition)\n );\n definitions.push(definition);\n }\n // The start held back until there was a messenger to start for.\n await streams.startNow();\n await channels.startNow();\n },\n channelOf(messageId) {\n return options.kv.get<ChannelMessageSurface>(askerKey(messageId))\n ?.channelKey;\n },\n contextOf(messageId) {\n return options.kv.get<MessengerContext>(contextKey(messageId));\n },\n deliverRecoveredReply,\n noticeSurface(id, thread) {\n const definition = definitions.find((d) => d.id === id);\n if (!definition || thread === undefined) return undefined;\n return {\n async post(text) {\n await chat().initialize();\n // A string goes as plain text, as Think posts it.\n return definition.adapter.postMessage(thread, text);\n }\n };\n },\n async receive(request) {\n if (!options.root()) return undefined;\n const pathname = new URL(request.url).pathname;\n const definition = definitions.find((d) => d.path === pathname);\n if (!definition) return undefined;\n if (request.method !== \"POST\") {\n return new Response(\"Method not allowed\", { status: 405 });\n }\n // Think's webhook check comes first: a request it refuses never\n // reaches the adapter.\n if (definition.verifyWebhook !== false) {\n const verdict = await definition.verifyWebhook(\n request.clone() as Request\n );\n if (verdict instanceof Response) return verdict;\n if (verdict === false) {\n return new Response(\"Unauthorized\", { status: 401 });\n }\n }\n return chat().webhooks[definition.adapterName](request);\n }\n };\n}\n\ntype TurnWatch = { settled(): Promise<void>; release(): void };\n\n/** The key of the Channel that watches turns settle; not a messenger id. */\nconst TURNS_KEY = \"think:turns\";\n\nfunction contextKey(eventId: string): string {\n return `cf_think_messenger_context:${eventId}`;\n}\n\nfunction askerKey(eventId: string): string {\n return `cf_think_messenger_asker:${eventId}`;\n}\n\n/** The user message Think builds for an event, as Channels message parts. */\nfunction messageParts(message: UIMessage): MessagePart[] {\n const parts: MessagePart[] = [];\n for (const part of message.parts) {\n if (part.type === \"text\") parts.push({ type: \"text\", text: part.text });\n else if (part.type === \"file\") {\n parts.push({\n type: \"file\",\n url: part.url,\n mediaType: part.mediaType,\n ...(part.filename !== undefined && { filename: part.filename })\n });\n }\n }\n return parts;\n}\n","/**\n * Think's code-declared scheduled tasks, mapped onto the Scheduler's\n * declared schedules. A `prompt` task becomes a durable submission; a\n * `handler` task runs the handler.\n */\n\nimport type { UIMessage } from \"ai\";\nimport type { RetryOptions } from \"agents\";\nimport type { Scheduler } from \"agents/schedules\";\nimport { stableHash } from \"./action-ledger\";\nimport {\n declareSchedules,\n type DeclaredSchedule,\n type DeclaredScheduleContext,\n type DeclaredScheduleExpression,\n type DeclaredSchedules\n} from \"agents/internal\";\n\n// Think's public schedule types are its own, written out, so its published\n// types never name the internal declared-schedule types they match.\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\n// The two sets of types must stay the same shape.\ntype Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;\nconst _sameSchedule: Same<\n ThinkScheduledTaskSchedule,\n DeclaredScheduleExpression\n> = true;\nconst _sameContext: Same<\n ThinkScheduledTaskContext,\n Omit<DeclaredScheduleContext, \"name\"> & { taskId: string }\n> = true;\nvoid _sameSchedule;\nvoid _sameContext;\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\n/** Submits a scheduled prompt, as `Think.submitMessages()` does. */\ntype SubmitScheduledPrompt = (\n messages: UIMessage[],\n options: { idempotencyKey: string; metadata: Record<string, unknown> }\n) => Promise<unknown>;\n\n/**\n * Map Think's task declaration onto Scheduler declared schedules.\n * `ownerKey` identifies this agent in submission metadata.\n */\nexport function toDeclaredSchedules(\n tasks: ThinkScheduledTasks,\n ownerKey: string,\n submit: SubmitScheduledPrompt\n): DeclaredSchedules {\n // fromEntries defines every name as an own property, `__proto__` included.\n return Object.fromEntries(\n Object.entries(tasks).map(([taskId, task]) => {\n const hasPrompt = task.prompt !== undefined;\n const hasHandler = 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 declared: DeclaredSchedule = {\n schedule: task.schedule,\n ...(task.timezone !== undefined && { timezone: task.timezone }),\n ...(task.retry !== undefined && { retry: task.retry }),\n ...(task.metadata !== undefined && { metadata: task.metadata }),\n run: async ({ name, ...occurrence }) => {\n if (task.handler) {\n await task.handler({ taskId: name, ...occurrence });\n return;\n }\n const prompt =\n typeof task.prompt === \"function\"\n ? await task.prompt()\n : task.prompt;\n await submit(\n [\n {\n id: crypto.randomUUID(),\n role: \"user\",\n parts: [{ type: \"text\", text: prompt ?? \"\" }]\n }\n ],\n {\n idempotencyKey: occurrence.idempotencyKey,\n metadata: {\n ...task.metadata,\n source: \"scheduled-task\",\n ownerKey,\n taskId: name,\n scheduledFor: occurrence.scheduledFor,\n schedule: occurrence.schedule\n }\n }\n );\n }\n };\n return [taskId, declared];\n })\n );\n}\n\n/**\n * Reconcile an agent's code-declared scheduled tasks with the Scheduler's\n * declared schedules, keyed by the agent's path. `tasks` and `timezone`\n * are read again when an occurrence runs; a prompt task submits through\n * `submit`.\n */\nexport function reconcileScheduledTasks(options: {\n readonly scheduler: Scheduler;\n readonly selfPath: unknown;\n readonly tasks: () => ThinkScheduledTasks | Promise<ThinkScheduledTasks>;\n readonly timezone: () => string | undefined | Promise<string | undefined>;\n readonly submit: SubmitScheduledPrompt;\n}): Promise<void> {\n const ownerKey = stableHash(options.selfPath);\n return declareSchedules(\n options.scheduler,\n async () =>\n toDeclaredSchedules(await options.tasks(), ownerKey, options.submit),\n {\n group: \"think\",\n defaultTimezone: options.timezone,\n idempotencyKeyPrefix: `think-schedule:${ownerKey}`\n }\n );\n}\n","/**\n * The workspace tools as an extension on ThinkHarness's core: Computer's\n * AI SDK tools over a Workspace, the same call Think makes for every turn.\n *\n * @internal Not exported from any entry point.\n */\nimport { createAITools } from \"@cloudflare/computer/tools/ai-sdk\";\nimport type { ThinkWorkspace } from \"../../workspace-files\";\nimport type { ThinkHarnessOptions } from \"agents/harness/think\";\n\n/** An extension, as ThinkHarness's `extensions` option takes it. @internal */\nexport type ThinkExtension = NonNullable<\n ThinkHarnessOptions[\"extensions\"]\n>[number][\"extension\"];\n\n/**\n * Set a tool, marked safe to run again after an interruption when its name\n * is in `rerun`: a read that changes nothing. Other tools cut off by a\n * reset are reported to the model as interrupted.\n *\n * @internal\n */\nexport function setTool<T extends object>(\n tools: { set(name: string, tool: T): unknown },\n name: string,\n tool: T,\n rerun: ReadonlySet<string>\n): void {\n tools.set(name, rerun.has(name) ? { ...tool, recovery: \"rerun\" } : tool);\n}\n\n/** The workspace tools that only read. */\nconst WORKSPACE_READS = new Set([\"read\", \"ls\", \"grep\", \"find\"]);\n\n/**\n * Offer the workspace's tools: file reads and writes, search and, when the\n * workspace has execution backends, `exec`. The workspace is read when the\n * tools are built, so a host may assign it after construction.\n *\n * @internal\n */\nexport function workspaceExtension(\n workspace: () => ThinkWorkspace\n): ThinkExtension {\n return (ctx) =>\n ctx.tools.transform((tools) => {\n for (const [name, tool] of Object.entries(\n createAITools({ workspace: workspace() })\n )) {\n setTool(tools, name, tool, WORKSPACE_READS);\n }\n });\n}\n","/**\n * The fetch tools as an extension on ThinkHarness's core: the allowlisted,\n * read-only `fetch_*` tools Think offers when its `fetchTools` is set.\n *\n * @internal Not exported from any entry point.\n */\nimport {\n createFetchTools,\n type CreateFetchToolsOptions,\n type FetchToolEvent\n} from \"../../tools/fetch\";\nimport type { ThinkWorkspace } from \"../../workspace-files\";\nimport { setTool, type ThinkExtension } from \"./workspace\";\n\n/** The fetch tools that only read. */\nconst FETCH_READS = new Set([\"fetch_url\"]);\n\n/**\n * Offer the fetch tools for `options()`, or none while it is `false`. The\n * workspace takes spilled bodies; `onEvent` observes each fetch.\n *\n * @internal\n */\nexport function fetchExtension(\n options: () => false | Omit<CreateFetchToolsOptions, \"workspace\" | \"onEvent\">,\n workspace: () => ThinkWorkspace,\n onEvent: (event: FetchToolEvent) => void\n): ThinkExtension {\n return (ctx) =>\n ctx.tools.transform((tools) => {\n const configured = options();\n if (!configured) return;\n for (const [name, tool] of Object.entries(\n createFetchTools({ ...configured, workspace: workspace(), onEvent })\n )) {\n setTool(tools, name, tool, FETCH_READS);\n }\n });\n}\n","/**\n * The skills from `getSkills()` as an extension on ThinkHarness's core: the\n * skill tools, listed again on each build. The catalog itself is a block\n * of Think's context (`ThinkSkills.initialize`, at start), which reminds\n * the model when it changes. The same `ThinkSkills` Think uses.\n *\n * @internal Not exported from any entry point.\n */\nimport type { SkillScriptRunner } from \"agents/skills\";\nimport type { ThinkSkills } from \"../../skills-runtime\";\nimport { setTool, type ThinkExtension } from \"./workspace\";\n\n/** The skills tools that only read. */\nconst SKILL_READS = new Set([\"activate_skill\", \"read_skill_resource\"]);\n\n/**\n * List the catalog again on each build and offer its tools; nothing while\n * no catalog loaded.\n *\n * @internal\n */\nexport function skillsExtension(\n skills: ThinkSkills,\n scriptRunner: () => SkillScriptRunner | null\n): ThinkExtension {\n return (ctx) => {\n ctx.tools.transform(async (tools) => {\n await skills.refresh();\n for (const [name, tool] of Object.entries(skills.tools(scriptRunner))) {\n setTool(tools, name, tool, SKILL_READS);\n }\n });\n };\n}\n","/**\n * Think's sandboxed extensions (loaded from source through\n * `extensionLoader`) as one extension on ThinkHarness's core: the tools\n * the released `ExtensionManager` offers, which run in each extension's\n * Worker.\n *\n * @internal Not exported from any entry point.\n */\nimport type { ExtensionManager } from \"../../extensions/manager\";\nimport type { ThinkExtension } from \"./workspace\";\n\n/**\n * Offer the tools of the manager's extensions, read at each build, so an\n * extension loaded or unloaded at run time shows from the next turn.\n *\n * @internal\n */\nexport function sandboxedExtensions(\n manager: () => ExtensionManager | undefined\n): ThinkExtension {\n return (ctx) =>\n ctx.tools.transform((tools) => {\n for (const [name, tool] of Object.entries(manager()?.getTools() ?? {})) {\n tools.set(name, tool);\n }\n });\n}\n","/**\n * The agent's actions (`getActions()`) as an extension on ThinkHarness's\n * core: each action is a tool. An approval-gated or durable-pause action\n * asks for approval, so its call waits in the transcript until it is\n * decided; the approved call runs through the action ledger in its tool\n * step.\n *\n * @internal Not exported from any entry point.\n */\nimport { compileActionTools, type ActionToolHost } from \"../../action-tools\";\nimport type { Action, CompiledActionMetadata } from \"../../actions\";\nimport type { ThinkExtension } from \"./workspace\";\n\n/**\n * Offer `actions()` as tools, each turn. `metadata` is refilled with each\n * approval-gated action's summary, permissions and risk, for listing.\n *\n * @internal\n */\nexport function actionsExtension(\n actions: () => Record<string, Action> | Promise<Record<string, Action>>,\n host: ActionToolHost,\n metadata: Map<string, CompiledActionMetadata>\n): ThinkExtension {\n return (ctx) =>\n ctx.tools.transform(async (tools) => {\n metadata.clear();\n for (const [name, tool] of Object.entries(\n compileActionTools(await actions(), host, metadata)\n )) {\n tools.set(name, tool);\n }\n });\n}\n","/**\n * How a paused `createExecuteTool` execution is found in, and settled on,\n * a stored reply. Internal: Think uses it.\n */\nimport type { UIMessage } from \"ai\";\n\n/** The tool call id of a part whose output carries `executionId`, if any. */\nexport function executionToolCallIn(\n message: UIMessage,\n executionId: string,\n pausedOnly: boolean\n): string | null {\n if (message.role !== \"assistant\") return null;\n for (const part of message.parts as unknown as Array<\n Record<string, unknown>\n >) {\n if (part.state !== \"output-available\") continue;\n if (typeof part.toolCallId !== \"string\") continue;\n const output = part.output as\n | { status?: unknown; executionId?: unknown }\n | null\n | undefined;\n if (\n output != null &&\n typeof output === \"object\" &&\n (!pausedOnly || output.status === \"paused\") &&\n output.executionId === executionId\n ) {\n return part.toolCallId;\n }\n }\n return null;\n}\n\n/**\n * `parts` without the text and reasoning that follow the part for\n * `toolCallId`, up to the end of the step that read its output: the rest of\n * the tool call's own step and the next one. Later steps answer other tool\n * results and are kept. Returns `parts` itself when nothing is dropped.\n */\nexport function dropGenerationAfterToolCall(\n parts: UIMessage[\"parts\"],\n toolCallId: string\n): UIMessage[\"parts\"] {\n const index = parts.findIndex(\n (part) => \"toolCallId\" in part && part.toolCallId === toolCallId\n );\n if (index === -1) return parts;\n let end = parts.length;\n let stepStarts = 0;\n for (let i = index + 1; i < parts.length; i++) {\n if (parts[i].type === \"step-start\" && ++stepStarts === 2) {\n end = i;\n break;\n }\n }\n const kept = parts.filter(\n (part, i) =>\n i <= index ||\n i >= end ||\n (part.type !== \"text\" && part.type !== \"reasoning\")\n );\n return kept.length === parts.length ? parts : kept;\n}\n","/**\n * A turn's advisory reply attachments, recorded by actions through\n * `ctx.attachReply`. Think keeps one per agent, for the latest turn.\n *\n * @internal Not exported from any entry point.\n */\nimport { safeStringifyActionOutput } from \"./action-tools\";\nimport type { ReplyAttachment } from \"./actions\";\n\nconst MAX_REPLY_ATTACHMENTS_PER_TURN = 32;\n\n/** @internal */\nexport class ReplyAttachments {\n #requestId: string | undefined;\n #attachments: ReplyAttachment[] = [];\n\n /** Start a turn: earlier attachments are dropped. */\n begin(requestId: string): void {\n this.#requestId = requestId;\n this.#attachments = [];\n }\n\n /**\n * Record one for `requestId`'s turn, JSON-normalized to a safe copy.\n * Returns its `type`, or `undefined` when it was ignored: another turn's,\n * not an object with a string `type`, not JSON, or over the cap.\n */\n record(requestId: string, attachment: unknown): string | undefined {\n if (!requestId || requestId !== this.#requestId) return;\n if (!isAttachment(attachment)) return;\n if (this.#attachments.length >= MAX_REPLY_ATTACHMENTS_PER_TURN) return;\n const serialized = safeStringifyActionOutput(attachment);\n if (serialized.error || serialized.value === undefined) return;\n const normalized = JSON.parse(serialized.value) as unknown;\n if (!isAttachment(normalized)) return;\n this.#attachments.push(normalized);\n return normalized.type;\n }\n\n count(): number {\n return this.#attachments.length;\n }\n\n /** Take back the ones recorded after the first `count`. */\n truncate(count: number): void {\n this.#attachments.length = count;\n }\n\n /**\n * Deep copies. With no `requestId`, the latest turn's; with one, only if\n * they belong to that turn (else `[]`).\n */\n list(requestId?: string): ReplyAttachment[] {\n if (requestId !== undefined && requestId !== this.#requestId) return [];\n return this.#attachments.map(\n (attachment) => JSON.parse(JSON.stringify(attachment)) as ReplyAttachment\n );\n }\n}\n\nfunction isAttachment(value: unknown): value is ReplyAttachment {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as { type?: unknown }).type === \"string\"\n );\n}\n","/**\n * What a sandboxed extension can reach on its Think agent through\n * `HostBridgeLoopback`. The loopback checks the extension's permissions\n * before it calls the agent; this module is the agent side.\n */\n\nimport type { UIMessage } from \"ai\";\nimport type { Context } from \"agents/context\";\nimport { WorkspaceFiles, resolveWorkspacePath } from \"../workspace-files\";\nimport type { ThinkWorkspace } from \"../workspace-files\";\n\n/** @internal */\nexport interface ThinkHostFileEntry {\n name: string;\n type: string;\n size: number;\n path: string;\n}\n\n/** @internal */\nexport interface ThinkHostMessage {\n id: string;\n role: string;\n content: string;\n}\n\n/**\n * The operations `HostBridgeLoopback` forwards to the agent.\n *\n * @internal\n */\nexport interface ThinkHostApi {\n readFile(path: string): Promise<string | null>;\n writeFile(path: string, content: string): Promise<void>;\n /** `false` when the file could not be removed. */\n deleteFile(path: string): Promise<boolean>;\n listFiles(dir: string): Promise<ThinkHostFileEntry[]>;\n getContext(label: string): Promise<string | null>;\n setContext(label: string, content: string): Promise<void>;\n /** The last `limit` messages as plain text; all of them when omitted. */\n getMessages(limit?: number): Promise<ThinkHostMessage[]>;\n /** Append a user message, visible to the next turn. */\n sendMessage(content: string): Promise<void>;\n getSessionInfo(): Promise<{ messageCount: number }>;\n}\n\n/** @internal */\nexport type ThinkHostOperation = keyof ThinkHostApi;\n\n/**\n * What {@link createThinkHostApi} reads from the agent.\n *\n * @internal\n */\ninterface ThinkHostApiOptions {\n readonly workspace: () => ThinkWorkspace;\n readonly context: () => Context;\n readonly messages: () => UIMessage[];\n /**\n * Append a message to the session directly. It must not start a turn: an\n * extension tool can call `sendMessage` during a turn, and waiting for the\n * turn queue there would deadlock.\n */\n readonly appendMessage: (message: UIMessage) => Promise<unknown>;\n}\n\n/** @internal */\nexport function createThinkHostApi(options: ThinkHostApiOptions): ThinkHostApi {\n const files = () => new WorkspaceFiles(options.workspace());\n return {\n readFile: (path) => files().readText(resolveWorkspacePath(path)),\n writeFile: (path, content) =>\n files().write(resolveWorkspacePath(path), content),\n async deleteFile(path) {\n try {\n await files().remove(resolveWorkspacePath(path));\n return true;\n } catch {\n return false;\n }\n },\n async listFiles(dir) {\n const entries = await files().list(resolveWorkspacePath(dir));\n return entries.map((e) => ({\n name: e.name,\n type: e.type,\n size: e.size,\n path: e.path\n }));\n },\n async getContext(label) {\n return options.context().getBlock(label)?.content ?? null;\n },\n async setContext(label, content) {\n await options.context().setBlock(label, content);\n },\n async getMessages(limit) {\n const history = options.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 async sendMessage(content) {\n await options.appendMessage({\n id: crypto.randomUUID(),\n role: \"user\",\n parts: [{ type: \"text\", text: content }]\n });\n },\n async getSessionInfo() {\n return { messageCount: options.messages().length };\n }\n };\n}\n\n/**\n * Run one host operation by name. Rejects a name that is not an operation.\n *\n * @internal\n */\nexport function callThinkHostApi<K extends ThinkHostOperation>(\n api: ThinkHostApi,\n operation: K,\n args: Parameters<ThinkHostApi[K]>\n): ReturnType<ThinkHostApi[K]> {\n if (!Object.prototype.hasOwnProperty.call(api, operation)) {\n throw new Error(`Unknown host operation: ${String(operation)}`);\n }\n const fn = api[operation] as (\n ...callArgs: Parameters<ThinkHostApi[K]>\n ) => ReturnType<ThinkHostApi[K]>;\n return fn(...args);\n}\n","/**\n * How a Think agent sets up its extensions and sends them its turn events.\n *\n * @internal\n */\nimport type { Context } from \"agents/context\";\nimport type { ToolSet, TypedToolCall } from \"ai\";\nimport type {\n ChunkContext,\n ExtensionConfig,\n StepContext,\n TurnConfig,\n TurnContext\n} from \"../turn-types\";\n\nimport type { ExtensionManager as ExtensionCore } from \"agents/internal\";\nimport { asNetworkGateway, ExtensionManager } from \"./manager\";\nimport {\n createChunkSnapshot,\n createStepFinishSnapshot,\n createToolCallFinishSnapshot,\n createToolCallStartSnapshot,\n createTurnContextSnapshot,\n sanitizeName,\n type ReleasedHookName,\n type ReleasedHooks\n} from \"./released\";\nimport type { ExtensionPermissions } from \"./types\";\n\n/**\n * What {@link createThinkExtensionManager} needs from the agent.\n *\n * @internal\n */\ninterface ThinkExtensionManagerOptions {\n readonly loader: WorkerLoader;\n readonly storage: DurableObjectStorage;\n readonly agentClassName: string;\n readonly agentId: string;\n /** The agent's path from the root, root first (`Agent#selfPath`). */\n readonly agentPath: readonly { className: string; name: string }[];\n /** The root's jurisdiction, for a sub-agent's lookup of its root. */\n readonly rootJurisdiction: DurableObjectJurisdiction | undefined;\n /** `ctx.exports` of the agent's Durable Object. */\n readonly exports: Record<string, unknown> | undefined;\n}\n\n/**\n * Create the extension manager. Extensions get a host binding only when the\n * Worker entry re-exports `HostBridgeLoopback`.\n *\n * @internal\n */\nexport function createThinkExtensionManager(\n options: ThinkExtensionManagerOptions\n): ExtensionManager {\n const { agentClassName, agentId, agentPath, rootJurisdiction, exports } =\n options;\n const hasBridge = exports && typeof exports.HostBridgeLoopback === \"function\";\n\n return new ExtensionManager({\n loader: options.loader,\n storage: options.storage,\n ...(hasBridge\n ? {\n workerIdScope: `${agentClassName}:${agentId}`,\n createHostBinding: asNetworkGateway(\n (permissions: ExtensionPermissions, ownContextLabels: string[]) =>\n (\n exports.HostBridgeLoopback as (opts: {\n props: Record<string, unknown>;\n }) => Fetcher\n )({\n props: {\n agentClassName,\n agentId,\n // A sub-agent is reached through its root.\n ...(agentPath.length > 1 && {\n agentPath: agentPath.map(({ className, name }) => ({\n className,\n name\n })),\n ...(rootJurisdiction && { rootJurisdiction })\n }),\n permissions,\n ownContextLabels\n }\n })\n )\n }\n : {})\n });\n}\n\n/**\n * Load the static extensions, restore the dynamic ones from storage, and\n * register each extension's context blocks under a name-prefixed label.\n * Unloading an extension removes its blocks.\n *\n * @internal\n */\nexport async function loadThinkExtensions(\n manager: ExtensionManager,\n configs: ExtensionConfig[],\n context: Context\n): Promise<void> {\n for (const config of configs) {\n await manager.load(config.manifest, config.source);\n }\n\n await manager.restore();\n\n // Context blocks use SQLite-backed storage on the agent. Extensions write\n // to their blocks through `host.setContext()`.\n for (const ext of manager.list()) {\n const manifest = manager.getManifest(ext.name);\n if (!manifest?.context) continue;\n\n const prefix = sanitizeName(ext.name);\n for (const ctxDef of manifest.context) {\n await context.addBlock({\n label: `${prefix}_${ctxDef.label}`,\n description: ctxDef.description,\n maxTokens: ctxDef.maxTokens\n });\n }\n }\n\n manager.onUnload(async (_name, contextLabels) => {\n for (const label of contextLabels) {\n context.removeBlock(label);\n }\n await context.refreshSystemPrompt();\n });\n}\n\n/**\n * Sends one agent's turn events to its extensions' hooks. Each event's\n * snapshot is made only when an extension subscribes to it.\n *\n * @internal\n */\nexport class ThinkExtensionHooks {\n readonly #core: () => ExtensionCore<ReleasedHooks> | undefined;\n\n constructor(core: () => ExtensionCore<ReleasedHooks> | undefined) {\n this.#core = core;\n }\n\n /**\n * Fold `config` (what the subclass's `beforeTurn` returned) through every\n * extension that subscribes to `beforeTurn`, in load order.\n */\n async beforeTurn(ctx: TurnContext, config: TurnConfig): Promise<TurnConfig> {\n const core = this.#core();\n if (!core || !(await core.subscribed(\"beforeTurn\"))) return config;\n // Extensions see the subclass's system prompt.\n const snapshot = createTurnContextSnapshot(ctx, config.model ?? undefined);\n if (config.system !== undefined) snapshot.system = config.system;\n return core.hook(\"beforeTurn\", { snapshot, config });\n }\n\n /** Tell subscribed extensions a tool call is about to run. */\n toolCallStart(event: {\n toolCall: TypedToolCall<ToolSet>;\n stepNumber: number | undefined;\n }): Promise<void> {\n return this.#observe(\"beforeToolCall\", () =>\n createToolCallStartSnapshot(event)\n );\n }\n\n /** Tell subscribed extensions a tool call finished. */\n toolCallFinish(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 return this.#observe(\"afterToolCall\", () =>\n createToolCallFinishSnapshot(event)\n );\n }\n\n /** Tell subscribed extensions a step finished. */\n stepFinish(event: StepContext): Promise<void> {\n return this.#observe(\"onStepFinish\", () => createStepFinishSnapshot(event));\n }\n\n /**\n * Tell subscribed extensions about a stream chunk. This runs per token, so\n * an extension that subscribes pays an RPC per chunk.\n */\n chunk(event: ChunkContext): Promise<void> {\n return this.#observe(\"onChunk\", () =>\n createChunkSnapshot(event as { chunk: { type: string } })\n );\n }\n\n async #observe(\n hook: Exclude<ReleasedHookName, \"beforeTurn\">,\n snapshot: () => unknown\n ): Promise<void> {\n const core = this.#core();\n if (!core || !(await core.subscribed(hook))) return;\n await core.hook(hook, snapshot());\n }\n}\n","/**\n * The skills a Think agent loads from `getSkills()`: the catalog, its prompt\n * block and the skill tools for each turn.\n *\n * In memory only: the catalog, the sources and the warnings already logged.\n * Sources keep their own storage (a Workspace, R2, a manifest), and the\n * catalog is listed again before every turn.\n */\n\nimport type { ToolSet } from \"ai\";\nimport type { Context } from \"agents/context\";\nimport { formatSkillDiagnostic, loadSkillCatalog } from \"agents/skills\";\nimport type {\n SkillCatalog,\n SkillScriptRunner,\n SkillSource\n} from \"agents/skills\";\nimport { createSkillTools } from \"agents/skills/tools/ai-sdk\";\n\n/**\n * Label of the context block that carries the skill catalog.\n *\n * @internal\n */\nexport const SKILLS_CONTEXT_LABEL = \"think_skills\";\n\n/**\n * Description of the skill catalog's context block.\n *\n * @internal\n */\nexport const SKILLS_CONTEXT_DESCRIPTION =\n \"Think skills: available skill catalog\";\n\n/** @internal */\nexport class ThinkSkills {\n #sources: readonly SkillSource[] = [];\n #catalog: SkillCatalog | null = null;\n readonly #warnings = new Set<string>();\n\n /**\n * Load the catalog and register its context block. A failing source never\n * stops the agent from starting: the error is logged and skills stay off.\n */\n async initialize(\n getSources: () => SkillSource[] | Promise<SkillSource[]>,\n context: Context\n ): Promise<void> {\n if (!(await this.start(getSources))) return;\n try {\n // `whenChanged: \"remind\"` keeps the frozen system prompt (and the\n // provider's prefix cache) stable when skills change mid-conversation.\n // The new catalog goes out as a reminder after the cached prefix, and\n // is folded into the system prompt at the next rebuild (compaction or\n // clearing history).\n await context.addBlock({\n label: SKILLS_CONTEXT_LABEL,\n description: SKILLS_CONTEXT_DESCRIPTION,\n whenChanged: \"remind\",\n provider: { get: async () => this.prompt() }\n });\n } catch (error) {\n warnInitializeFailed(error);\n }\n }\n\n /**\n * Load the catalog. False when there are no sources or loading failed\n * (logged): skills stay off.\n */\n async start(\n getSources: () => SkillSource[] | Promise<SkillSource[]>\n ): Promise<boolean> {\n try {\n const sources = await getSources();\n if (sources.length === 0) return false;\n this.#sources = sources;\n await this.#load();\n return true;\n } catch (error) {\n warnInitializeFailed(error);\n return false;\n }\n }\n\n /** Whether a catalog loaded: skills are on. */\n get loaded(): boolean {\n return this.#catalog !== null;\n }\n\n /** The catalog's prompt block text. */\n prompt(): string {\n return this.#catalog?.prompt() ?? \"No skills are available.\";\n }\n\n /**\n * List the sources again. Sources are live (a Workspace, R2), so a failure\n * keeps the last good catalog rather than breaking the turn. The skills\n * block is a reminder block, so a changed catalog reaches the model without\n * rebuilding the frozen system prompt.\n */\n async refresh(): Promise<void> {\n if (!this.#catalog) return;\n try {\n await this.#load();\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 /** The skill tools for a turn, or none when no catalog loaded. */\n tools(scriptRunner: () => SkillScriptRunner | null): ToolSet {\n return this.#catalog\n ? createSkillTools(this.#catalog, { scriptRunner: scriptRunner() })\n : {};\n }\n\n /** Load the catalog from every source and log new diagnostics. */\n async #load(): Promise<void> {\n // `previous` keeps a source's last skills when it fails to list, so a\n // transient outage (an R2 blip) does not drop them for a turn.\n const catalog = await loadSkillCatalog(this.#sources, {\n previous: this.#catalog ?? undefined\n });\n for (const diagnostic of catalog.diagnostics) {\n this.#warnOnce(formatSkillDiagnostic(diagnostic));\n }\n this.#catalog = catalog;\n }\n\n /**\n * Log a skills warning once per object lifetime, so a new problem after a\n * deploy still surfaces while the same warning is not repeated every turn.\n */\n #warnOnce(warning: string): void {\n if (this.#warnings.has(warning)) return;\n this.#warnings.add(warning);\n console.warn(`[think] ${warning}`);\n }\n}\n\nfunction warnInitializeFailed(error: unknown): void {\n console.warn(\n `[think] Failed to initialize skills; continuing without them: ${error instanceof Error ? error.message : String(error)}`\n );\n}\n","/**\n * Whether a subclass declared a method itself. `Agent` wraps subclass\n * methods during `super()`, copying inherited methods onto the concrete\n * prototype, so a plain prototype lookup cannot tell a user override from a\n * framework-installed wrapper. The prototype chain is snapshotted before\n * `super()` runs, and later checks read the snapshot.\n */\n\n/** @internal */\ninterface DeclaredOverrides {\n /** Record the members each prototype below the base declares. Call before `super()`. */\n snapshot(prototype: object): void;\n /** Whether `instance`'s class (below the base) declares `methodName`. */\n isOverridden(instance: object, methodName: string): boolean;\n}\n\n/**\n * Track overrides of the methods of `base()` (read lazily).\n *\n * @internal\n */\nexport function declaredOverrides(base: () => object): DeclaredOverrides {\n const declared = new WeakMap<object, ReadonlySet<PropertyKey>>();\n return {\n snapshot(prototype) {\n for (\n let current: object | null = prototype;\n current && current !== base();\n current = Object.getPrototypeOf(current) as object | null\n ) {\n if (!declared.has(current)) {\n declared.set(current, new Set(Reflect.ownKeys(current)));\n }\n }\n },\n isOverridden(instance, methodName) {\n // Agent's auto-wrapper writes to the concrete prototype, not the\n // instance; an own member here is a subclass class-field override\n // initialized later.\n if (Object.prototype.hasOwnProperty.call(instance, methodName)) {\n return true;\n }\n for (\n let current: object | null = Object.getPrototypeOf(instance) as object;\n current && current !== base();\n current = Object.getPrototypeOf(current) as object | null\n ) {\n if (declared.get(current)?.has(methodName)) return true;\n }\n return false;\n }\n };\n}\n","import { sendDelivery } from \"agents/internal\";\nimport type { DeliverySink } from \"agents/internal\";\nimport type { Tasks } from \"agents/tasks\";\nimport type { ThinkSubmissionInspection } from \"./submissions\";\nimport type { ThinkWorkflowPromptContext } from \"./turn-types\";\n\n/**\n * The workflow event a terminal submission owes, delivered until the\n * workflow accepts it.\n *\n * @internal\n */\nexport type WorkflowNotification = {\n workflowName: string;\n workflowId: string;\n event: { type: string; payload: WorkflowEventPayload };\n};\n\n/** What a submission's workflow event carries. */\ntype WorkflowEventPayload = {\n submissionId?: string;\n status?: string;\n output?: unknown;\n error?: string;\n [key: string]: unknown;\n};\n\n/** The sink workflow notifications are delivered through. @internal */\nexport const WORKFLOW_NOTIFICATION_SINK = \"think-workflow-notification\";\n\n/**\n * One delivery per submission and event type. The id is the queue item id\n * the released version used, so a repeat joins the open delivery.\n *\n * @internal\n */\nexport function workflowNotificationId(\n submissionId: string,\n eventType: string\n): string {\n return `workflow-notification:${submissionId}:${eventType}`;\n}\n\n/**\n * The sink. The delivery defaults (2 s doubling, ten-minute cap, giving up\n * twelve hours after the notification was sent) ride out an outage of the\n * workflow binding without waking the object forever for a workflow that\n * is gone. `onGiveUp` gets the give-up error (Think passes it to `onError`).\n *\n * @internal\n */\nexport function workflowNotificationSink(\n send: (notification: WorkflowNotification) => Promise<void>,\n onGiveUp: (error: Error) => void | Promise<void>\n): DeliverySink<WorkflowNotification> {\n return {\n deliver: (notification) => send(notification),\n onGiveUp,\n giveUpError: (notification, _id, attempts, cause) =>\n new Error(\n `Workflow notification for submission ${JSON.stringify(\n notification.event.payload?.submissionId\n )} (${notification.workflowName}/${notification.workflowId}, ${notification.event.type}) ` +\n `could not be delivered after ${attempts} attempts; giving up: ` +\n (cause instanceof Error ? cause.message : String(cause))\n )\n };\n}\n\n/**\n * The delivery a queue item or scheduled retry of the released version\n * carries (`_cfDeliverWorkflowNotification`). A retry keeps its give-up\n * window (`firstFailedAt`) and its backoff (`attempts`).\n *\n * TEMPORARY: remove with `_cfDeliverWorkflowNotification` in the next minor.\n *\n * @internal\n */\nexport function legacyWorkflowNotification(\n payload: WorkflowNotification & { attempts?: number; firstFailedAt?: number }\n): {\n id: string;\n notification: WorkflowNotification;\n resume?: { sentAt: number; attempts: number };\n} {\n return {\n id: workflowNotificationId(\n payload.event.payload?.submissionId ?? \"\",\n payload.event.type\n ),\n notification: {\n workflowName: payload.workflowName,\n workflowId: payload.workflowId,\n event: payload.event\n },\n ...(payload.firstFailedAt !== undefined && {\n resume: {\n sentAt: payload.firstFailedAt,\n attempts: payload.attempts ?? 1\n }\n })\n };\n}\n\n/** The submission metadata key a workflow's prompt is kept under. */\nconst WORKFLOW_PROMPT_METADATA_KEY = \"__thinkWorkflowPrompt\";\n\n/**\n * The workflow prompt a submission's metadata carries, if it is one a\n * workflow step submitted.\n *\n * @internal\n */\nexport function workflowPromptContext(\n metadata: Record<string, unknown> | null | undefined\n): ThinkWorkflowPromptContext | null {\n const workflowPromptValue = metadata?.[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/**\n * Send the workflow event a terminal submission owes. False when the\n * submission is not a workflow's. A repeat while the delivery is open joins\n * it (the id is stable).\n *\n * @internal\n */\nexport function sendWorkflowNotification(\n tasks: Tasks,\n submission: ThinkSubmissionInspection,\n output: unknown,\n /**\n * Called once the delivery is accepted (its run exists and retries on\n * its own). Not called when the accept fails: a later report sends again.\n */\n accepted: () => void\n): boolean {\n const workflowPrompt = workflowPromptContext(submission.metadata ?? null);\n if (!workflowPrompt) return false;\n\n const { status, error } = submission;\n const payload = {\n submissionId: submission.submissionId,\n status,\n ...(status === \"completed\" && { output }),\n ...(error && { error })\n };\n void sendDelivery(\n tasks,\n WORKFLOW_NOTIFICATION_SINK,\n workflowNotificationId(\n submission.submissionId,\n workflowPrompt.workflow.eventType\n ),\n {\n workflowName: workflowPrompt.workflow.name,\n workflowId: workflowPrompt.workflow.id,\n event: { type: workflowPrompt.workflow.eventType, payload }\n } satisfies WorkflowNotification\n ).then(accepted, (error) => {\n console.error(\"[Think] Failed to send workflow notification\", error);\n });\n return true;\n}\n","/**\n * Structured workflow turns. A workflow `step.prompt` turn that asks for an\n * output schema ends by calling a synthetic final-answer tool; its arguments\n * are the structured result.\n */\n\nimport type { UIMessage } from \"ai\";\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 *\n * @internal\n */\nexport const 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 *\n * @internal\n */\nexport function 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 *\n * @internal\n */\nexport function 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\n/**\n * `message` without the parts of the internal final-answer tool, which a\n * structured workflow turn uses as plumbing and never stores.\n *\n * @internal\n */\nexport function withoutFinalAnswerParts(message: UIMessage): UIMessage {\n const parts = message.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 === message.parts.length\n ? message\n : { ...message, parts };\n}\n","/**\n * Durable programmatic submissions: the public types, and how a submission\n * maps onto its run on the Tasks capability. `Think` runs the turn; Tasks\n * keeps the record, its order in the submissions lane and its waiters.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { TaskJson } from \"agents/tasks\";\nimport { MAX_FRAMEWORK_METADATA_BYTES, type TaskRecord } from \"agents/internal\";\n\nexport type ThinkSubmissionStatus =\n | \"pending\"\n | \"running\"\n | \"completed\"\n | \"aborted\"\n | \"skipped\"\n | \"error\";\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 /** Id of the assistant message this submission's turn persisted. */\n messageId?: string;\n};\n\nexport type SubmitMessagesResult = ThinkSubmissionInspection & {\n accepted: boolean;\n};\n\nexport type WaitForSubmissionOptions = {\n /**\n * Stop waiting after this many milliseconds and return the submission as it\n * is then, still `pending` or `running`, or `null` if it was deleted.\n */\n timeoutMs?: number;\n};\n\n/** What {@link Think.cancelSubmission} did. */\nexport type CancelSubmissionResult =\n | {\n /** No submission has this id. */\n outcome: \"not_found\";\n submissionId: string;\n }\n | {\n /** The submission had already finished; nothing changed. */\n outcome: \"already_terminal\";\n submissionId: string;\n submission: ThinkSubmissionInspection;\n }\n | {\n /** The submission is now `aborted`. */\n outcome: \"cancelled\";\n submissionId: string;\n /**\n * `\"pending\"`: removed before its turn started. `\"running\"`: its turn\n * had been claimed and was signalled to abort; side effects already\n * under way may still finish.\n */\n previousStatus: \"pending\" | \"running\";\n /**\n * Whether any of the submission's messages were written to the\n * conversation when it was cancelled. A claimed submission can still be\n * `false` when it is cancelled before its turn applies them.\n */\n messagesApplied: boolean;\n submission: ThinkSubmissionInspection;\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\n/** A turn's durable cutover fact, not the stream transport's lifecycle. */\nexport type SubmissionTurnResult =\n | { status: \"completed\"; output?: unknown }\n | { status: \"aborted\" | \"retry\" | \"error\" };\n\nexport const SUBMISSION_LANE = \"submissions\";\n/** The metadata key holding what a submission's turn records about itself. */\nexport const SUBMISSION_PROGRESS_KEY = \"__cf_progress\";\n\n/** How a submission ends when its stored messages cannot be read. */\nexport const SUBMISSION_MESSAGES_INVALID =\n \"Stored submission messages are invalid\";\n\n/** What a submission's turn records about itself, in its run's metadata. */\nexport type SubmissionProgress = {\n /** The request id of the turn answering it; recovery moves it. */\n requestId?: string;\n streamId?: string;\n /** Set once its messages were appended to the session. */\n messagesAppliedAt?: number;\n /** The cutover outcome, written with the stream's settle. */\n resultStatus?: SubmissionTurnResult[\"status\"];\n output?: unknown;\n /** The assistant message its turn persisted. */\n messageId?: string;\n /** Its workflow event was queued; a repeated terminal report skips it. */\n workflowNotified?: boolean;\n};\n\n/** A row of the retired `cf_think_submissions` table. */\nexport type LegacySubmissionRow = {\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 result_status?: SubmissionTurnResult[\"status\"] | null;\n output_json?: string | null;\n message_id?: string | null;\n};\n\nexport type TerminalSubmissionStatus = Exclude<\n ThinkSubmissionStatus,\n \"pending\" | \"running\"\n>;\n\nexport const TERMINAL_SUBMISSION_STATUSES: TerminalSubmissionStatus[] = [\n \"completed\",\n \"aborted\",\n \"skipped\",\n \"error\"\n];\n\nexport function isTerminalSubmissionStatus(\n status: ThinkSubmissionStatus\n): status is TerminalSubmissionStatus {\n return status !== \"pending\" && status !== \"running\";\n}\n\n/** A Task status as the submission status it is. */\nfunction submissionStatus(record: TaskRecord): ThinkSubmissionStatus {\n // A parked submission's turn is still under way, owned by chat recovery.\n if (record.status === \"pending\" && record.waitReason === \"park\") {\n return \"running\";\n }\n return record.status;\n}\n\n/** What a submission's turn recorded about itself. */\nexport function submissionProgress(record: TaskRecord): SubmissionProgress {\n return (record.metadata?.[SUBMISSION_PROGRESS_KEY] ??\n {}) as SubmissionProgress;\n}\n\n/** The metadata the app gave, without what Think keeps there. */\nfunction appMetadata(record: TaskRecord): Record<string, unknown> | undefined {\n if (!record.metadata) return undefined;\n const { [SUBMISSION_PROGRESS_KEY]: _progress, ...rest } = record.metadata;\n return Object.keys(rest).length > 0 ? rest : undefined;\n}\n\n/** The error message a submission ended with (an abort's reason). */\nfunction submissionError(record: TaskRecord): string | undefined {\n if (record.error) return record.error.message;\n if (record.status === \"aborted\" || record.status === \"skipped\") {\n return record.reason;\n }\n return undefined;\n}\n\nexport function submissionInspection(\n record: TaskRecord\n): ThinkSubmissionInspection {\n const progress = submissionProgress(record);\n const metadata = appMetadata(record);\n const error = submissionError(record);\n return {\n submissionId: record.runId,\n ...(record.idempotencyKey !== undefined && {\n idempotencyKey: record.idempotencyKey\n }),\n requestId: progress.requestId ?? record.runId,\n status: submissionStatus(record),\n ...(error !== undefined && { error }),\n ...(metadata !== undefined && { metadata }),\n createdAt: record.createdAt,\n ...(record.startedAt !== undefined && { startedAt: record.startedAt }),\n ...(record.settledAt !== undefined && { completedAt: record.settledAt }),\n ...(progress.messageId !== undefined && { messageId: progress.messageId })\n };\n}\n\n/** What a submission's outcome is, as the value a release hands its run. */\nexport type SubmissionOutcome = {\n status: TerminalSubmissionStatus;\n error?: string;\n output?: TaskJson;\n};\n\n/** What a submission a turn reset ended reports as its error. */\nexport const SKIPPED_BY_RESET = \"Submission was skipped by turn reset.\";\n\n/** A cancel reason as the text a cancelled submission reports. */\nexport function cancelReason(reason: unknown): string | undefined {\n if (reason === undefined) return undefined;\n if (reason instanceof Error) return reason.message;\n return typeof reason === \"string\" ? reason : String(reason);\n}\n\n/** End a submission `error`. */\nexport function submissionFailed(error?: unknown): SubmissionOutcome {\n const message =\n error instanceof Error\n ? error.message\n : typeof error === \"string\"\n ? error\n : undefined;\n return { status: \"error\", ...(message !== undefined && { error: message }) };\n}\n\nconst utf8 = new TextEncoder();\n\n/**\n * Room a migrated open submission keeps for the progress it records (ids\n * and timestamps; a structured output too large for the room is left to\n * the run's result, see `progressOutputFits`).\n */\nconst PROGRESS_HEADROOM_BYTES = 100_000;\n\n/**\n * The metadata a new submission is stored with: the app's own fields, without\n * Think's progress key (Think writes it), checked against the room that\n * leaves the turn's progress (ids, timestamps) beside it.\n *\n * @throws When the app's metadata leaves no room for the progress.\n */\nexport function admittedSubmissionMetadata(\n metadata: Record<string, unknown> | undefined\n): Record<string, TaskJson> | undefined {\n if (metadata === undefined) return undefined;\n const { [SUBMISSION_PROGRESS_KEY]: _progress, ...app } = metadata;\n const limit = MAX_FRAMEWORK_METADATA_BYTES - PROGRESS_HEADROOM_BYTES;\n const bytes = jsonBytes(app);\n if (bytes > limit) {\n throw new Error(\n `Submission metadata is ${bytes} bytes; at most ${limit} fit beside the submission's progress`\n );\n }\n return app as Record<string, TaskJson>;\n}\n\n/**\n * Largest structured output a submission may complete with. Only a workflow\n * prompt has one, and its workflow is sent it in one event, which holds at\n * most 1 MiB (Workflows' event payload limit); the rest of the event (ids,\n * status) gets the margin.\n */\nconst MAX_SUBMISSION_OUTPUT_BYTES = 1_048_576 - 4_096;\n\n/** Whether a submission's structured output can be delivered. */\nexport function submissionOutputFits(output: unknown): boolean {\n return (\n output === undefined || jsonBytes(output) <= MAX_SUBMISSION_OUTPUT_BYTES\n );\n}\n\n/** A submission that completed with an output too large to deliver. */\nexport function submissionOutputTooLarge(output: unknown): SubmissionOutcome {\n return submissionFailed(\n `Structured output is ${jsonBytes(output)} bytes; a workflow event holds at most ${MAX_SUBMISSION_OUTPUT_BYTES}`\n );\n}\n\n/**\n * Whether a turn's structured output still fits in a submission's metadata\n * beside what it holds. One that does not is not recorded as progress: the\n * run's result carries it once the submission settles.\n */\nexport function progressOutputFits(\n metadata: Record<string, TaskJson> | undefined,\n output: unknown\n): boolean {\n if (output === undefined) return true;\n return (\n jsonBytes(metadata ?? {}) + jsonBytes(output) + 16 <=\n MAX_FRAMEWORK_METADATA_BYTES\n );\n}\n\n/**\n * The structured answer the release kept with a running submission's row\n * when its turn ended (0.24 wrote it before the submission's end), when it\n * fits beside the submission's `metadata`. One that does not fit is left\n * out: the submission keeps its metadata, and whoever waits is told it\n * ended without an answer.\n */\nexport function legacySubmissionAnswer(\n row: Pick<LegacySubmissionRow, \"output_json\">,\n metadata: Record<string, TaskJson>\n): TaskJson | undefined {\n if (row.output_json == null) return undefined;\n const answer = parseJsonValue(row.output_json);\n if (answer === null) return undefined;\n return jsonBytes({\n ...metadata,\n [SUBMISSION_PROGRESS_KEY]: { output: answer }\n }) <= MAX_FRAMEWORK_METADATA_BYTES\n ? (answer as TaskJson)\n : undefined;\n}\n\nfunction jsonBytes(value: unknown): number {\n return utf8.encode(JSON.stringify(value)).byteLength;\n}\n\nfunction parseJsonValue(value: string | null | undefined): unknown {\n if (typeof value !== \"string\") return null;\n try {\n return JSON.parse(value) as unknown;\n } catch {\n return null;\n }\n}\n\n/**\n * Drop the largest of `fields` (key and value, as stored) until `bytes`\n * fits `budget`, keeping every one that still fits. Sizes are measured\n * once. Mutates `fields`; returns the keys dropped and the bytes left.\n */\nfunction dropLargestFields(\n fields: Record<string, TaskJson>,\n bytes: number,\n budget: number\n): { keys: string[]; bytes: number } {\n const sized = Object.entries(fields)\n .map(([key, value]) => ({\n key,\n size: jsonBytes(key) + jsonBytes(value) + 2\n }))\n .sort((a, b) => b.size - a.size);\n const keys: string[] = [];\n for (const { key, size } of sized) {\n if (bytes <= budget) break;\n delete fields[key];\n keys.push(key);\n bytes -= size;\n }\n return { keys, bytes };\n}\n\n/**\n * The app's own metadata of a row of the retired table, as a run can hold\n * it: without Think's progress key (an app field of that name was never\n * readable back), and with the largest fields dropped, and logged, when\n * the whole does not fit.\n */\nexport function legacySubmissionAppMetadata(\n row: Pick<LegacySubmissionRow, \"submission_id\" | \"metadata_json\" | \"status\">\n): Record<string, TaskJson> {\n const metadata = parseJsonValue(row.metadata_json);\n if (\n metadata === null ||\n typeof metadata !== \"object\" ||\n Array.isArray(metadata)\n ) {\n return {};\n }\n const fields = { ...(metadata as Record<string, TaskJson>) };\n delete fields[SUBMISSION_PROGRESS_KEY];\n // An open submission still records as it runs: leave room. A finished\n // one never writes again.\n const open = row.status === \"pending\" || row.status === \"running\";\n const budget =\n MAX_FRAMEWORK_METADATA_BYTES - (open ? PROGRESS_HEADROOM_BYTES : 0);\n const bytes = jsonBytes(fields);\n if (bytes > budget) {\n const dropped = dropLargestFields(fields, bytes, budget);\n console.warn(\n `[Think] Submission \"${row.submission_id}\": metadata too large to keep; dropped fields ${dropped.keys.join(\", \")}`\n );\n }\n return fields;\n}\n\n/**\n * Runs each submission's status reports one after another, in the order\n * they arrive, so an app that stores the latest status never ends on an\n * earlier one (a slow `running` hook finishing after `aborted`). Reports of\n * different submissions do not wait for each other. A report caused from\n * inside a running report of the same submission (its hook cancelled it)\n * runs at once: queued behind that report, neither would return. Holds one\n * promise per submission with a report in flight, removed when its last\n * one ends.\n *\n * @internal\n */\nexport class SubmissionStatusQueue {\n readonly #tails = new Map<string, Promise<void>>();\n readonly #running = new AsyncLocalStorage<{\n readonly queue: SubmissionStatusQueue;\n readonly submissionId: string;\n }>();\n\n /**\n * Whether this is running inside a report of this queue's: of the given\n * submission's, or of any when none is given.\n */\n reporting(submissionId?: string): boolean {\n const inside = this.#running.getStore();\n return (\n inside?.queue === this &&\n (submissionId === undefined || inside.submissionId === submissionId)\n );\n }\n\n /** Run `report` after the submission's earlier reports have ended. */\n run(submissionId: string, report: () => Promise<void>): Promise<void> {\n const inside = this.#running.getStore();\n const marked = () =>\n this.#running.run({ queue: this, submissionId }, report);\n if (inside?.queue === this && inside.submissionId === submissionId) {\n return marked();\n }\n const previous = this.#tails.get(submissionId) ?? Promise.resolve();\n // A failed report does not hold up the next; its caller still sees it.\n const next = previous.then(marked);\n const tail = next.catch(() => {});\n this.#tails.set(submissionId, tail);\n void tail.then(() => {\n if (this.#tails.get(submissionId) === tail) {\n this.#tails.delete(submissionId);\n }\n });\n return next;\n }\n}\n","/**\n * Think's conversation handle.\n *\n * Wraps the `agents/sessions` `Session` handle that `Think.sessions` hands\n * out, so that a subclass written against the pre-Sessions Think API keeps\n * compiling and running unchanged:\n *\n * - the context builder methods (`withContext`, `withCachedPrompt`) that\n * used to live on the session, now queued and folded into\n * `Think.configureContext()`;\n * - the context accessors (`addContext`, `getContextBlock`,\n * `refreshSystemPrompt`, `tools`, ...), now forwarded to `Think.context`;\n * - the positional `appendMessage(message, parentId)` and\n * `getHistory(leafId)` forms alongside the options-object forms.\n *\n * Storage calls delegate to the real handle; the context forwards are\n * deprecated and exist only so an upgrade is a no-op. New code should read\n * `this.context` directly and declare blocks in `configureContext()`.\n *\n * The wrapper is explicit forwarding rather than a subclass or Proxy because\n * `Session` keeps its state in `#private` fields, which neither survives.\n */\n\nimport type { ToolSet } from \"ai\";\nimport type {\n AppendOptions,\n AppendResult,\n CompactionFunction,\n CompactResult,\n HistoryBatchReadOptions,\n HistoryReadOptions,\n RecentHistoryResult,\n SearchResult,\n Session,\n SessionMessage,\n SessionRowStat,\n StoredCompaction,\n WriteOptions\n} from \"agents/sessions\";\nimport type {\n ContextBlock,\n Context,\n ContextConfig,\n WritableContextProvider\n} from \"agents/context\";\n\n/** Options for a block declared through `withContext()` / `addContext()`. */\nexport type SessionContextOptions = Omit<ContextConfig, \"label\">;\n\n/** Receives an error thrown by the registered compaction function. */\nexport type CompactionErrorHandler = (error: unknown) => void | Promise<void>;\n\n/**\n * @deprecated `compactAfter()` gates on the token estimate Sessions stamps on\n * each row; a custom counter is no longer consulted. Accepted so existing\n * calls compile.\n */\nexport interface CompactAfterOptions {\n tokenCounter?: unknown;\n}\n\nexport class ThinkSession {\n readonly #handle: Session;\n readonly #context: () => Context;\n /** Blocks queued by `withContext()`; `null` once startup consumed them. */\n #pendingContext: ContextConfig[] | null = [];\n #promptStore: WritableContextProvider | undefined;\n #compactionErrorHandler: CompactionErrorHandler | null = null;\n\n /** @internal Constructed by Think during `onStart`. */\n constructor(handle: Session, context: () => Context) {\n this.#handle = handle;\n this.#context = context;\n }\n\n get sessionId(): string {\n return this.#handle.sessionId;\n }\n\n /** @internal Blocks declared through `withContext()` during configuration. */\n internal_takePendingContext(): ContextConfig[] {\n const pending = this.#pendingContext ?? [];\n this.#pendingContext = null;\n return pending;\n }\n\n /** @internal A custom frozen-prompt store passed to `withCachedPrompt()`. */\n internal_promptStore(): WritableContextProvider | undefined {\n return this.#promptStore;\n }\n\n // ── Builder (configureSession) ────────────────────────────────────────────\n\n /**\n * Declare a prompt context block.\n *\n * @deprecated Return the block from `configureContext()` instead. Only\n * callable inside `configureSession()`; after startup use\n * `this.context.addBlock()`.\n */\n withContext(label: string, options: SessionContextOptions = {}): this {\n if (!this.#pendingContext) {\n throw new Error(\n \"withContext() is only available inside configureSession(). \" +\n \"After startup, add a block with this.context.addBlock().\"\n );\n }\n this.#pendingContext.push({ label, ...options });\n return this;\n }\n\n /**\n * Persist the frozen system prompt.\n *\n * @deprecated The session records the prompt each turn was sent with, so\n * this is not needed. A custom `provider` is still read: a prompt frozen\n * in it before is what the turns sent before are sent. It is not written.\n */\n withCachedPrompt(provider?: WritableContextProvider): this {\n if (provider) this.#promptStore = provider;\n return this;\n }\n\n /** Register the function `compact()` calls to summarize a branch. */\n onCompaction(fn: CompactionFunction): this {\n this.#handle.onCompaction(async (messages) => {\n try {\n return await fn(messages);\n } catch (error) {\n const handler = this.#compactionErrorHandler;\n if (!handler) throw error;\n await handler(error);\n return null;\n }\n });\n return this;\n }\n\n /**\n * Auto-compact after an append once the stamped token estimate crosses the\n * threshold. Requires `onCompaction()`.\n */\n compactAfter(tokenThreshold: number, _options?: CompactAfterOptions): this {\n this.#handle.compactAfter(tokenThreshold);\n return this;\n }\n\n /**\n * Observe compaction failures. When set, a failing compaction function\n * calls the handler and the compaction is skipped; without one the failure\n * is reported through the `session:error` capability event.\n */\n onCompactionError(handler: CompactionErrorHandler): this {\n this.#compactionErrorHandler = handler;\n return this;\n }\n\n // ── Reads ────────────────────────────────────────────────────────────────\n\n history(\n options?: HistoryReadOptions\n ): AsyncGenerator<SessionMessage, void, undefined> {\n return this.#handle.history(options);\n }\n\n historyBatches(\n options?: HistoryBatchReadOptions\n ): AsyncGenerator<SessionMessage[], void, undefined> {\n return this.#handle.historyBatches(options);\n }\n\n /**\n * Materialize the whole selected path. Accepts a leaf id positionally, as\n * the pre-Sessions API did, or a read-options object.\n */\n getHistory(\n leafIdOrOptions?: string | null | HistoryReadOptions\n ): Promise<SessionMessage[]> {\n return this.#handle.getHistory(readOptions(leafIdOrOptions));\n }\n\n /**\n * Byte-budgeted read of the most recent messages on the active path. The\n * pre-Sessions `minRecentMessages` argument is accepted and ignored: the\n * budget is a hard ceiling, and the newest message is always returned.\n */\n getRecentHistory(\n maxContentBytes: number,\n optionsOrMinRecentMessages?: number | Pick<HistoryReadOptions, \"leafId\">\n ): Promise<RecentHistoryResult> {\n const options =\n typeof optionsOrMinRecentMessages === \"object\"\n ? optionsOrMinRecentMessages\n : undefined;\n return this.#handle.getRecentHistory(maxContentBytes, options);\n }\n\n getHistoryRowStats(leafId?: string | null): Promise<SessionRowStat[]> {\n return this.#handle.getHistoryRowStats(leafId);\n }\n\n /** @deprecated Read `getHistoryRowStats()` and take its length. */\n async getPathLength(leafId?: string | null): Promise<number> {\n return (await this.#handle.getHistoryRowStats(leafId)).length;\n }\n\n /** @internal A page of the stored path from the newest row back (media eviction). */\n internal_storedPathRows(options: {\n skip: number;\n limit: number;\n measure?: boolean;\n after?: string;\n }): Promise<Array<{ id: string; bytes: number }>> {\n return this.#handle.internal_storedPathRows(options);\n }\n\n getMessage(id: string): Promise<SessionMessage | null> {\n return this.#handle.getMessage(id);\n }\n\n getLatestLeaf(): Promise<SessionMessage | null> {\n return this.#handle.getLatestLeaf();\n }\n\n getBranches(messageId: string): Promise<SessionMessage[]> {\n return this.#handle.getBranches(messageId);\n }\n\n search(query: string, options?: { limit?: number }): Promise<SearchResult[]> {\n return this.#handle.search(query, options);\n }\n\n // ── Writes ───────────────────────────────────────────────────────────────\n\n /**\n * Append one message. Accepts the parent id positionally, as the\n * pre-Sessions API did, or an options object.\n */\n appendMessage(\n message: SessionMessage,\n parentIdOrOptions?: string | null | AppendOptions\n ): Promise<AppendResult> {\n return this.#handle.appendMessage(\n message,\n appendOptions(parentIdOrOptions)\n );\n }\n\n updateMessage(\n message: SessionMessage,\n options?: WriteOptions\n ): Promise<SessionMessage | null> {\n return this.#handle.updateMessage(message, options);\n }\n\n upsertMessage(\n message: SessionMessage,\n parentIdOrOptions?: string | null | AppendOptions\n ): Promise<AppendResult> {\n return this.#handle.upsertMessage(\n message,\n appendOptions(parentIdOrOptions)\n );\n }\n\n importMessage(\n message: SessionMessage,\n options: { parentId: string | null; createdAt: number }\n ): Promise<void> {\n return this.#handle.importMessage(message, options);\n }\n\n deleteMessages(messageIds: string[]): Promise<void> {\n return this.#handle.deleteMessages(messageIds);\n }\n\n clearMessages(): Promise<void> {\n return this.#handle.clearMessages();\n }\n\n // ── Compaction ───────────────────────────────────────────────────────────\n\n addCompaction(\n summary: string,\n fromMessageId: string,\n toMessageId: string\n ): Promise<StoredCompaction> {\n return this.#handle.addCompaction(summary, fromMessageId, toMessageId);\n }\n\n getCompactions(): Promise<StoredCompaction[]> {\n return this.#handle.getCompactions();\n }\n\n compact(leafId?: string | null): Promise<CompactResult | null> {\n return this.#handle.compact(leafId);\n }\n\n // ── Context forwards ─────────────────────────────────────────────────────\n //\n // Prompt context lives on `Think.context` now. These forwards keep the\n // pre-Sessions call sites working and will be removed in a later minor.\n\n /** @deprecated Use `this.context.addBlock({ label, ...options })`. */\n addContext(\n label: string,\n options: SessionContextOptions = {}\n ): Promise<ContextBlock> {\n return this.#context().addBlock({ label, ...options });\n }\n\n /** @deprecated Use `this.context.removeBlock(label)`. */\n removeContext(label: string): boolean {\n return this.#context().removeBlock(label);\n }\n\n /** @deprecated Use `this.context.getBlock(label)`. */\n getContextBlock(label: string): ContextBlock | null {\n return this.#context().getBlock(label);\n }\n\n /** @deprecated Use `this.context.getBlocks()`. */\n getContextBlocks(): ContextBlock[] {\n return this.#context().getBlocks();\n }\n\n /** @deprecated Use `this.context.setBlock(label, content)`. */\n replaceContextBlock(label: string, content: string): Promise<ContextBlock> {\n return this.#context().setBlock(label, content);\n }\n\n /** @deprecated Use `this.context.appendToBlock(label, content)`. */\n appendContextBlock(label: string, content: string): Promise<ContextBlock> {\n return this.#context().appendToBlock(label, content);\n }\n\n /** @deprecated Use `this.context.freezeSystemPrompt()`. */\n freezeSystemPrompt(): Promise<string> {\n return this.#context().freezeSystemPrompt();\n }\n\n /** @deprecated Use `this.context.refreshSystemPrompt()`. */\n refreshSystemPrompt(): Promise<string> {\n return this.#context().refreshSystemPrompt();\n }\n\n /** @deprecated Use `this.context.tools()`. */\n tools(): Promise<ToolSet> {\n return this.#context().tools();\n }\n}\n\nfunction readOptions(\n leafIdOrOptions: string | null | HistoryReadOptions | undefined\n): HistoryReadOptions | undefined {\n if (leafIdOrOptions === undefined) return undefined;\n if (leafIdOrOptions === null || typeof leafIdOrOptions === \"string\") {\n return { leafId: leafIdOrOptions };\n }\n return leafIdOrOptions;\n}\n\nfunction appendOptions(\n parentIdOrOptions: string | null | AppendOptions | undefined\n): AppendOptions | undefined {\n if (parentIdOrOptions === undefined) return undefined;\n if (parentIdOrOptions === null || typeof parentIdOrOptions === \"string\") {\n return { parentId: parentIdOrOptions };\n }\n return parentIdOrOptions;\n}\n","/**\n * The submissions table of think 0.24 in the one migration of a release's\n * storage. Its rows are moved by Think's own carrier, which needs the\n * harness and the app's hooks and so runs in the start, not here.\n */\nimport { removeReleaseTable } from \"agents/internal\";\n\n/** The table think 0.24 kept its submissions in. */\nexport const RELEASED_SUBMISSIONS = \"cf_think_submissions\";\n\n/**\n * @internal The step of the upgrade from think 0.24 for its submissions:\n * the release's table goes once it holds no row. The carrier deletes each\n * row as it moves it, so that is the first start for an object that had\n * no submission, and the start after the carry for one whose carry was cut\n * short. (What the release queued to run its submissions is taken by\n * `Think._cfRunSubmission`, which does nothing.)\n */\nexport function migrateReleasedSubmissions(storage: {\n readonly sql: SqlStorage;\n readonly kv: SyncKvStorage;\n}): void {\n removeEmptiedSubmissionsTable(storage);\n}\n\n/**\n * @internal Remove the release's submissions table when it is there and\n * holds no row. A root drops it; a sub-agent keeps it, empty, and writes\n * nothing.\n */\nexport function removeEmptiedSubmissionsTable(storage: {\n readonly sql: SqlStorage;\n readonly kv: SyncKvStorage;\n}): void {\n let rows: number;\n try {\n rows = storage.sql\n .exec<{ n: number }>(`SELECT COUNT(*) AS n FROM ${RELEASED_SUBMISSIONS}`)\n .one().n;\n } catch {\n return; // No table.\n }\n if (rows === 0) removeReleaseTable(storage, RELEASED_SUBMISSIONS);\n}\n","/**\n * The capability block Think appends to a turn's system prompt: one line per\n * kind of tool the turn exposes.\n */\n\nimport type { ToolSet } from \"ai\";\n\nconst CAPABILITY_BLOCK_HEADING = \"You are running inside a Think agent.\";\n\n/**\n * Think's default `getSystemPrompt()`: used only when the agent overrides\n * nothing and has no context blocks.\n *\n * @internal\n */\nexport const DEFAULT_SYSTEM_PROMPT = [\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 * Append the capability block for `tools` to `baseSystem`. A prompt that\n * already carries the block (an override that includes it) is returned as-is.\n *\n * @internal\n */\nexport function systemPromptForTurn(\n baseSystem: string,\n tools: ToolSet\n): string {\n if (baseSystem.includes(CAPABILITY_BLOCK_HEADING)) {\n return baseSystem;\n }\n\n return `${baseSystem.trimEnd()}\\n\\n${capabilityBlock(tools)}`;\n}\n\n/**\n * The capability block for the tools a turn exposes.\n *\n * @internal\n */\nexport function capabilityBlock(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 \"ls\",\n \"find\",\n \"grep\",\n \"delete\"\n ].some((toolName) => toolNames.has(toolName));\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 CAPABILITY_BLOCK_HEADING,\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 (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 * How a turn's model request is built from the stored transcript: read-time\n * truncation, the provider-safe projection, the context reminder and the\n * continue checkpoint. Nothing here writes the transcript; every change\n * shapes only the request.\n */\n\nimport type { ModelMessage, ToolSet, UIMessage } from \"ai\";\nimport { convertToModelMessages } from \"ai\";\nimport {\n MODEL_RECENT_WINDOW,\n ensureValidContinueCheckpoint,\n truncateOlderMessages,\n truncateOlderToolResults,\n truncationKeepRecent,\n truncationStepSize,\n type BeforeTurnRepairResult\n} from \"agents/chat\";\n\n/**\n * Default `truncationStep`. Read-time truncation cuts the history at a\n * multiple of this many messages,\n * so the full-fidelity span grows from `MODEL_RECENT_WINDOW` to\n * `MODEL_RECENT_WINDOW + MODEL_TRUNCATION_STEP - 1` messages between cuts.\n * Providers cache on a byte-identical prompt prefix, and a cutoff that moved\n * every turn rewrote a message near the end of that prefix on every turn\n * (#2200). Stepping it rewrites the prefix once per step instead.\n *\n * @internal\n */\nexport const MODEL_TRUNCATION_STEP = 8;\n\n/**\n * Index below which media eviction may rewrite messages: the stepped\n * truncation cutoff, moved back whole steps until at least\n * `keepRecentMessages` messages stay above it. It only moves when the\n * truncation cutoff does, so eviction rewrites the cached prompt prefix at\n * most once per step and never inside the full-fidelity window (#2356).\n * With stepping disabled (`truncationStep = Infinity`) there is no cutoff to\n * align with, and eviction keeps exactly `keepRecentMessages`.\n *\n * @internal\n */\nexport function mediaEvictionCutoff(\n messageCount: number,\n keepRecentMessages: number,\n step: number\n): number {\n const keep = Math.max(keepRecentMessages, MODEL_RECENT_WINDOW);\n const safeStep = truncationStepSize(step);\n if (safeStep === Number.POSITIVE_INFINITY) {\n return Math.max(0, messageCount - keep);\n }\n const stepsBack = Math.ceil((keep - MODEL_RECENT_WINDOW) / safeStep);\n return Math.max(\n 0,\n messageCount -\n truncationKeepRecent(messageCount, safeStep) -\n stepsBack * safeStep\n );\n}\n\n/**\n * Stable id prefix for fallback notes that preserve orphaned execution outcomes.\n *\n * @internal\n */\nexport const EXECUTION_OUTCOME_MESSAGE_PREFIX = \"exec-outcome-\";\n\n/**\n * Present framework-authored execution outcome notes to providers as user\n * context. Think persists these notes as system messages so clients and\n * recovery do not mistake them for human input, but AI SDK v7 and strict\n * providers reject system messages in arbitrary transcript\n * positions. The provider-only projection leaves current and legacy session\n * history unchanged.\n *\n * @internal\n */\nexport function toProviderSafeExecutionOutcomeMessage(\n message: UIMessage\n): UIMessage {\n return message.role === \"system\" &&\n message.id.startsWith(EXECUTION_OUTCOME_MESSAGE_PREFIX)\n ? { ...message, role: \"user\" }\n : message;\n}\n\n// The continue prompt and the rule that ends a request in it are the chat\n// module's, shared with `AIChatAgent`.\nexport { ensureValidContinueCheckpoint };\n\n/**\n * What {@link modelMessagesFromHistory} needs besides the repaired history.\n *\n * @internal\n */\ninterface ModelMessagesOptions {\n readonly tools: ToolSet;\n /** The agent's `truncationStep`. */\n readonly truncationStep: number;\n /** Tool call ids in `messages` that have no settled result. */\n readonly incompleteToolCallIds: (messages: UIMessage[]) => string[];\n /** Called when calls with no result survived repair and are dropped. */\n readonly onIncompleteToolCalls: (toolCallIds: string[]) => void;\n}\n\n/**\n * Build the provider-ready model messages for a turn from its repaired\n * history: project execution outcomes for providers, truncate older\n * messages, drop any still-incomplete tool calls, and convert.\n *\n * @throws When repair kept a tool call a client still has to answer. A\n * continuation turn in that state has nothing to continue, and the request\n * would hold a call with no result.\n *\n * @internal\n */\nexport async function modelMessagesFromHistory(\n repair: BeforeTurnRepairResult,\n options: ModelMessagesOptions\n): Promise<ModelMessage[]> {\n // The rule holds where the request is built: a continuation turn whose\n // repair kept a call a client still has to answer has nothing to\n // continue. The continuation entry points end such a turn before it\n // gets here (`ChatTurns.continuationWaitsOnClient`). One that did not\n // must not reach the model: the request would hold a call with no\n // result, and with it dropped the model calls the same tool again.\n if (repair.keptToolCallIds.length > 0) {\n throw new Error(\n `[Think] A continuation turn cannot call the model while its reply waits on a client for tool call(s) ${repair.keptToolCallIds.join(\", \")}.`\n );\n }\n const history = repair.messages;\n const providerSafeHistory = history.map(\n toProviderSafeExecutionOutcomeMessage\n );\n const keepRecent = truncationKeepRecent(\n providerSafeHistory.length,\n options.truncationStep\n );\n const truncated = truncateOlderMessages(providerSafeHistory, {\n keepRecent,\n toolOutputs: false\n }) as UIMessage[];\n // The before-turn repair 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 = options.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 the before-turn repair.`\n );\n options.onIncompleteToolCalls(incompleteAfterRepair);\n }\n const modelMessages = await convertToModelMessages(truncated, {\n tools: options.tools,\n ignoreIncompleteToolCalls: true\n });\n return truncateOlderToolResults(modelMessages, truncated, { keepRecent });\n}\n","/**\n * Aged-media eviction — a CONTEXT-WINDOW technique owned by Think.\n *\n * This is deliberately not how Sessions stores a message, and the two must\n * not be confused:\n *\n * - Row chunking is a STORAGE detail. A message too large for one SQLite\n * row is split across continuation rows and reassembled on read, byte\n * for byte. Invisible to the model and lossless.\n * - Media eviction is a CONTEXT decision. Once a screenshot has aged out\n * of the recent window, re-sending it on every turn is pure cost, so\n * Think removes it from the conversation and leaves a marker naming a\n * Workspace file. Visible to the model and lossy on purpose — the agent\n * reads the file back with the workspace `read` tool when it actually\n * needs the picture again.\n *\n * The bytes are written to the Workspace RAW (not as a `data:` URL string)\n * with their real mime type, so `read` recognises `image/*` and puts a real\n * image back into the model's context.\n *\n * Evicted values are:\n * - `file` parts whose `url` is a large `data:` URL — the part becomes a\n * text marker;\n * - large `data:` strings nested anywhere inside a tool part's `output`\n * (screenshots commonly arrive that way) — the string is replaced in\n * place so tool-specific `toModelOutput` handlers still work.\n *\n * Plain text parts are never evicted: they are the conversation itself.\n */\n\nimport type { UIMessage } from \"ai\";\nimport { LifecycleCapability } from \"agents/lifecycle\";\nimport { MODEL_RECENT_WINDOW } from \"agents/chat\";\nimport { mediaEvictionCutoff } from \"./inference/model-messages\";\n\n/** Nested tool-output walks stop here so hostile output cannot recurse forever. */\nconst MAX_WALK_DEPTH = 8;\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 window the model replays at\n * full fidelity, so a misconfigured low value can never strip content the\n * model still sees.\n * @default 8\n */\n keepRecentMessages?: number;\n /**\n * Minimum decoded payload size, in bytes, for a value to be evicted.\n * @default 32 * 1024\n */\n minPartBytes?: number;\n /**\n * Maximum stored rows processed per pass. Bounds how long a single pass\n * can take; remaining rows are picked up by the next pass.\n * @default 64\n */\n maxRowsPerPass?: number;\n /**\n * @deprecated Ignored. Evicted bytes are always preserved in the Workspace\n * under `/workspace/attachments/evicted/`; there is no drop-the-bytes mode. Accepted\n * so existing configurations keep compiling.\n */\n externalizeToWorkspace?: boolean;\n}\n\ninterface ResolvedMediaEvictionConfig {\n keepRecentMessages: number;\n minPartBytes: number;\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 maxRowsPerPass: base.maxRowsPerPass ?? 64\n };\n}\n\n/**\n * The exact marker Think has always written. Old and new markers are\n * byte-identical, so a transcript evicted before and after the Sessions\n * replatform reads the same and old markers keep resolving.\n */\nfunction evictionMarker(\n bytes: number,\n path: string,\n mediaType?: string\n): string {\n const media = mediaType ? `${mediaType}, ` : \"\";\n return `[evicted ${media}${bytes} bytes; preserved at ${path}]`;\n}\n\ninterface EvictMessageOptions {\n /** Minimum decoded payload size to evict. */\n minPartBytes: number;\n /**\n * Persist one payload and return the Workspace path it was written to.\n * `index` is the 0-based ordinal of the evicted value within the message.\n */\n write(\n index: number,\n bytes: Uint8Array,\n mediaType: string | undefined\n ): Promise<string>;\n}\n\ninterface EvictMessageResult {\n /** Rewritten message, or the original reference when nothing was evicted. */\n message: UIMessage;\n changed: boolean;\n /** Individual values replaced by markers. */\n parts: number;\n /** Decoded payload bytes removed from the conversation. */\n bytes: number;\n}\n\ninterface WalkState {\n options: EvictMessageOptions;\n index: number;\n parts: number;\n bytes: number;\n}\n\n/**\n * Replace aged oversized media in one message with markers, writing the\n * bytes to the Workspace first. Returns a new message — the input is never\n * mutated, and nothing is written when nothing qualifies.\n */\nasync function evictMediaFromMessage(\n message: UIMessage,\n options: EvictMessageOptions\n): Promise<EvictMessageResult> {\n const state: WalkState = { options, index: 0, parts: 0, bytes: 0 };\n let changed = false;\n const parts: UIMessage[\"parts\"] = [];\n\n for (const part of message.parts) {\n if (part.type === \"file\" && \"url\" in part) {\n const marker = await evictUrl(\n state,\n (part as { url: string }).url,\n (part as { mediaType?: string }).mediaType\n );\n if (marker !== null) {\n changed = true;\n parts.push({ type: \"text\", text: marker });\n continue;\n }\n parts.push(part);\n continue;\n }\n\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 rewritten = await walkAndEvict(state, output, 0);\n if (state.parts > before) {\n changed = true;\n parts.push({ ...part, output: rewritten } as UIMessage[\"parts\"][0]);\n continue;\n }\n }\n }\n\n parts.push(part);\n }\n\n return {\n message: changed ? { ...message, parts } : message,\n changed,\n parts: state.parts,\n bytes: state.bytes\n };\n}\n\n/**\n * Evict one stored payload locator. Returns its marker, or `null` when the\n * value is not an evictable payload or is below the size threshold.\n */\nasync function evictUrl(\n state: WalkState,\n url: unknown,\n fallbackMediaType?: string\n): Promise<string | null> {\n if (typeof url !== \"string\") return null;\n const payload = resolvePayload(state, url);\n if (!payload) return null;\n const mediaType = payload.mediaType ?? fallbackMediaType;\n const path = await state.options.write(state.index, payload.bytes, mediaType);\n state.index++;\n state.parts++;\n state.bytes += payload.bytes.byteLength;\n return evictionMarker(payload.bytes.byteLength, path, mediaType);\n}\n\n/**\n * A stored payload is always an inline `data:` URL now, so eviction decodes\n * it directly.\n */\nfunction resolvePayload(\n state: WalkState,\n url: string\n): { bytes: Uint8Array; mediaType?: string } | null {\n const { minPartBytes } = state.options;\n if (!url.startsWith(\"data:\")) return null;\n // A `data:` URL is always larger than its payload, so the cheap string\n // length rules out small values before any decoding happens.\n if (url.length < minPartBytes) return null;\n const decoded = decodeDataUrl(url);\n if (!decoded || decoded.bytes.byteLength < minPartBytes) return null;\n return decoded;\n}\n\nasync function walkAndEvict(\n state: WalkState,\n value: unknown,\n depth: number\n): Promise<unknown> {\n if (typeof value === \"string\") {\n return (await evictUrl(state, value)) ?? value;\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: unknown[] = [];\n for (const item of value) {\n const next = await walkAndEvict(state, item, depth + 1);\n if (next !== item) changed = true;\n result.push(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 = await walkAndEvict(state, entry, depth + 1);\n if (next !== entry) changed = true;\n result[key] = next;\n }\n return changed ? result : value;\n}\n\n/**\n * Whether a pass over `message` could evict anything: a file part or a tool\n * output holding a `data:` URL at least `minPartBytes` long. Decodes nothing —\n * this is the in-memory gate that decides whether a pass is worth scheduling,\n * so a decoded payload that turns out smaller than the threshold is merely a\n * pass that changes nothing.\n */\nexport function hasEvictableMedia(\n message: UIMessage,\n minPartBytes: number\n): boolean {\n const isCandidate = (value: unknown): boolean =>\n typeof value === \"string\" &&\n value.length >= minPartBytes &&\n value.startsWith(\"data:\");\n const walk = (value: unknown, depth: number): boolean => {\n if (isCandidate(value)) return true;\n if (\n value === null ||\n typeof value !== \"object\" ||\n depth >= MAX_WALK_DEPTH\n ) {\n return false;\n }\n const entries = Array.isArray(value) ? value : Object.values(value);\n return entries.some((entry) => walk(entry, depth + 1));\n };\n for (const part of message.parts) {\n if (part.type === \"file\" && \"url\" in part) {\n if (isCandidate((part as { url: unknown }).url)) return true;\n continue;\n }\n if (\n (part.type.startsWith(\"tool-\") || part.type === \"dynamic-tool\") &&\n \"output\" in part &&\n walk((part as { output?: unknown }).output, 0)\n ) {\n return true;\n }\n }\n return false;\n}\n\n/** Decode a `data:` URL into raw bytes. Returns null when it is malformed. */\nfunction decodeDataUrl(\n url: string\n): { bytes: Uint8Array; mediaType?: string } | null {\n const comma = url.indexOf(\",\");\n if (comma === -1) return null;\n const header = url.slice(\"data:\".length, comma);\n const base64 = /;base64$/i.test(header);\n const mediaType =\n header\n .replace(/;base64$/i, \"\")\n .split(\";\")[0]\n ?.trim() || undefined;\n const payload = url.slice(comma + 1);\n try {\n if (base64) {\n const binary = atob(payload);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return mediaType === undefined ? { bytes } : { bytes, mediaType };\n }\n const bytes = new TextEncoder().encode(decodeURIComponent(payload));\n return mediaType === undefined ? { bytes } : { bytes, mediaType };\n } catch {\n return null;\n }\n}\n\n/** File extension for an evicted payload, derived from its media type. */\nexport function 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\n/** Workspace path for the n-th value evicted from a message. */\nfunction evictedFilePath(\n messageId: string,\n index: number,\n mediaType: string | undefined\n): string {\n return `/workspace/attachments/evicted/${messageId}-${index}.${extensionFor(mediaType)}`;\n}\n\n/**\n * Totals of one eviction pass.\n *\n * @internal\n */\nexport interface MediaEvictionPassResult {\n messages: number;\n parts: number;\n bytes: number;\n backlogRemains: boolean;\n}\n\n/**\n * What {@link MediaEvictionPasses} reads from and does on its agent.\n *\n * @internal\n */\ninterface MediaEvictionPassHost {\n /** The resolved `mediaEviction` setting; `null` when eviction is off. */\n config(): ResolvedMediaEvictionConfig | null;\n truncationStep(): number;\n /** The hydrated message cache. */\n cachedMessages(): readonly UIMessage[];\n /**\n * Whether the cache cannot stand in for the stored path: the hydration is\n * a window of it, or a compaction overlay hides rows a pass would read.\n */\n agedRowsHiddenFromCache(): boolean;\n /** Stored content bytes the last hydration measured, if known. */\n storedBytes(): number | null;\n /** A page of the stored path from the newest row back, sizes with `measure`. */\n storedPathRows(options: {\n skip: number;\n limit: number;\n measure?: boolean;\n after?: string;\n }): Promise<ReadonlyArray<{ id: string; bytes: number }>>;\n readMessage(id: string): Promise<UIMessage | null>;\n /**\n * A file writer for one pass, opened once at the start of the pass so every\n * payload of the pass lands in the same Workspace.\n */\n openFiles(): { write(path: string, bytes: Uint8Array): Promise<void> };\n updateMessage(message: UIMessage): Promise<unknown>;\n emitEvicted(totals: Omit<MediaEvictionPassResult, \"backlogRemains\">): void;\n /**\n * Queue a pass on a routed Lifecycle (a sub-agent facet), which has no\n * alarm of its own: the host's Queue routes the item through the root.\n * Goes away with facets.\n */\n queueRouted(): Promise<unknown>;\n}\n\n/**\n * The newest aged row a completed pass examined, and its position from the\n * root: one KV key, written when a pass moves it.\n */\nconst CURSOR_KEY = \"think-media-eviction:cursor\";\ntype EvictionCursor = { id: string; index: number };\n\n/** Aged rows one stored-path read returns. */\nconst MEDIA_EVICTION_PAGE_ROWS = 256;\n\n/** One pass at a time: requests coalesce on this job id. */\n/** @internal The id of the queued pass job; tests wait on it. */\nexport const PASS_JOB_ID = \"think-media-eviction:pass\";\n\n/**\n * Schedules and runs bounded media-eviction passes for one agent, as a\n * Lifecycle capability that owns the pass job.\n *\n * Durable: the pending pass job (one id, so repeated requests coalesce).\n * In memory only: whether a pass is running, a request that arrived during\n * it, and the last fruitless pass. The gate in {@link request} decides from\n * memory whether a pass could evict anything before queuing one. Passes run\n * from the alarm, never inside the request or refresh that asked for them.\n *\n * @internal\n */\nexport class MediaEvictionPasses extends LifecycleCapability {\n readonly #host: MediaEvictionPassHost;\n #running = false;\n /**\n * A request that arrived while a pass was running. That pass read its\n * candidates before the request's append landed, so the request is kept\n * and re-evaluated once the pass ends rather than dropped.\n */\n #pending = false;\n /**\n * Linear appends that landed while a pass was running. The pass read its\n * candidates before them, so a fruitless result records them as appends\n * since — not zero — and the request they left pending can pass the gate.\n */\n #appendsDuringPass = 0;\n /**\n * The last pass that found nothing to evict while aged rows were hidden\n * from the cache: the stored size it saw, and how many linear appends have\n * landed since. Until either changes enough, another pass would scan the\n * same rows to the same answer. A refresh that measures a different size\n * re-arms it, and so do `keepRecentMessages` appends: that is what it takes\n * for a row the pass had to protect to age into a candidate. An update\n * that grows a cached row clears it outright ({@link invalidate}).\n */\n #fruitless: { storedBytes: number; appendsSince: number } | null = null;\n /** A row grew: the durable cursor no longer vouches for what is below it. */\n #cursorStale = false;\n\n constructor(host: MediaEvictionPassHost) {\n super(\"think-media-eviction\");\n this.#host = host;\n }\n\n /** Run the queued pass. A failed pass logs and ends; the next request retries. */\n async onJob(): Promise<void> {\n await this.run();\n }\n\n /** Whether a pass is running now. */\n get running(): boolean {\n return this.#running;\n }\n\n /**\n * A linear append landed. Appends are what age older messages, so this\n * is where a pass becomes worth scheduling.\n */\n noteAppend(): void {\n if (this.#fruitless) this.#fruitless.appendsSince++;\n if (this.#running) this.#appendsDuringPass++;\n this.request();\n }\n\n /** A cached row grew, so an aged row may now hold a payload. */\n invalidate(): void {\n this.#fruitless = null;\n this.#cursorStale = true;\n }\n\n /**\n * A row the cache does not hold changed (a late tool result on an older\n * reply). It may now hold media below the cursor, so the next pass starts\n * over. A pass's own rewrites land while it runs and are not counted.\n */\n rowChangedOutsideCache(): void {\n if (this.#running) return;\n this.#cursorStale = true;\n }\n\n /**\n * Queue a pass if one could evict anything. A request that lands while a\n * pass runs is re-evaluated once the pass ends, so media aged by an append\n * during the pass is not left until the next one. Passes run from the\n * alarm loop, never inside the request or cache refresh that asked.\n */\n request(): void {\n if (this.#running) {\n this.#pending = true;\n return;\n }\n const config = this.#host.config();\n if (!config) return;\n // Decide from memory whether a pass could evict anything, so a pass is\n // not the way to find out: its first act is a content-free scan of the\n // whole stored path, and this runs after every cache refresh and every\n // linear append.\n //\n // When the cache holds every aged row, it is the same rows the pass\n // would read, so a pass is scheduled only when an aged cached message\n // still carries an inline payload. When it does not — a windowed\n // hydration, or rows hidden under a compaction overlay — a pass is\n // scheduled once per distinct stored size, since until the bytes change\n // it would scan the same rows to the same answer.\n const keepRecent = Math.max(config.keepRecentMessages, MODEL_RECENT_WINDOW);\n if (this.#host.agedRowsHiddenFromCache()) {\n const fruitless = this.#fruitless;\n const storedBytes = this.#host.storedBytes();\n if (\n fruitless !== null &&\n storedBytes !== null &&\n fruitless.storedBytes === storedBytes &&\n fruitless.appendsSince < keepRecent\n ) {\n return;\n }\n } else {\n const cached = this.#host.cachedMessages();\n const aged = cached.slice(\n 0,\n mediaEvictionCutoff(\n cached.length,\n config.keepRecentMessages,\n this.#host.truncationStep()\n )\n );\n if (\n !aged.some((message) => hasEvictableMedia(message, config.minPartBytes))\n ) {\n return;\n }\n }\n const queued = this.lifecycle.routes.source\n ? this.#host.queueRouted()\n : this.lifecycle.jobs.push({\n id: PASS_JOB_ID,\n fn: \"pass\",\n time: Date.now()\n });\n void queued.catch((error) => {\n console.error(\"[Think] Failed to queue media eviction pass\", error);\n });\n }\n\n /**\n * Remove aged media from the conversation, leaving a Workspace pointer the\n * agent can read back.\n *\n * Memory-bounded by design: candidate sizes come from the row stats (no\n * content loaded), only rows big enough to hold an evictable payload are\n * read, and they are processed one at a time. Bytes are written to the\n * Workspace BEFORE the row is rewritten, so a failed pass never loses data;\n * once the rewritten row is stored, its Sessions attachment reference is\n * gone and the blob is reaped, so the bytes live in exactly one place.\n *\n * The aged cutoff is {@link mediaEvictionCutoff}: the stepped truncation\n * cutoff, kept at least `keepRecentMessages` back. Messages the model still\n * replays at full fidelity are never rewritten, and the cutoff moves only\n * once per truncation step.\n *\n * Best-effort: failures are logged and the next pass retries. When a pass\n * stops at `maxRowsPerPass` having made progress, the next one is scheduled\n * so a backlog drains on its own; a pass that changed nothing does not\n * reschedule, which is what guarantees termination.\n *\n * @returns `null` when eviction is off, a pass is already running, or the\n * pass failed.\n */\n async run(): Promise<MediaEvictionPassResult | null> {\n if (this.#running) return null;\n const config = this.#host.config();\n if (!config) return null;\n this.#running = true;\n this.#appendsDuringPass = 0;\n const totals: MediaEvictionPassResult = {\n messages: 0,\n parts: 0,\n bytes: 0,\n backlogRemains: false\n };\n try {\n const files = this.#host.openFiles();\n // Where earlier passes got to: the newest aged row they examined, and\n // its position from the root. Rows at or below it have been examined\n // (and evicted or left), so a pass reads from the leaf down to it and\n // no further: a restart re-reads only what was added since.\n const storage = this.lifecycleServices?.storage;\n if (this.#cursorStale) {\n await storage?.delete(CURSOR_KEY);\n this.#cursorStale = false;\n }\n const cursor = await storage?.get<EvictionCursor>(CURSOR_KEY);\n // Count the rows above the cursor (ids only, one page at a time). The\n // cutoff needs the path's length; the cursor's position stands in for\n // everything below it. Without a cursor on this path (the first pass,\n // a branch switch, a deleted row) the walk counts to the root.\n let above = 0;\n let reached = false;\n // Pages start small and grow: the cursor is usually a few rows down.\n for (let after: string | undefined, limit = 32; ;) {\n const page = await this.#host.storedPathRows(\n after === undefined ? { skip: 0, limit } : { skip: 0, limit, after }\n );\n limit = Math.min(limit * 4, MEDIA_EVICTION_PAGE_ROWS);\n if (page.length === 0) break;\n const at = cursor ? page.findIndex((row) => row.id === cursor.id) : -1;\n if (at >= 0) {\n above += at;\n reached = true;\n break;\n }\n above += page.length;\n after = page[page.length - 1].id;\n }\n // A delete below the cursor makes `total` too large, which can only\n // move the cut within one truncation step (`keep` depends on the\n // length modulo the step and never drops below `keepRecentMessages`).\n const total = reached && cursor ? cursor.index + 1 + above : above;\n const keep =\n total -\n mediaEvictionCutoff(\n total,\n config.keepRecentMessages,\n this.#host.truncationStep()\n );\n // The aged rows this pass must examine: from the cutoff down to the\n // cursor, or to the root.\n const end = reached ? above : total;\n let newestAged: string | undefined;\n\n // Collect the rows large enough to hold an evictable payload, with\n // their depth from the leaf; smaller rows are skipped without being\n // read, and a rewritten row drops below the line for every later pass.\n const candidates: Array<{ id: string; depth: number }> = [];\n let after: string | undefined;\n for (let read = keep; read < end;) {\n const page = (\n await this.#host.storedPathRows(\n after === undefined\n ? { skip: keep, limit: MEDIA_EVICTION_PAGE_ROWS, measure: true }\n : {\n skip: 0,\n limit: MEDIA_EVICTION_PAGE_ROWS,\n measure: true,\n after\n }\n )\n ).slice(0, end - read);\n if (page.length === 0) break;\n newestAged ??= page[0].id;\n page.forEach((row, at) => {\n if (row.bytes >= config.minPartBytes) {\n candidates.push({ id: row.id, depth: read + at });\n }\n });\n read += page.length;\n after = page[page.length - 1].id;\n }\n\n // Oldest first, so a pass cut short at `maxRowsPerPass` has examined\n // everything from the cursor up to its last row, and the cursor can\n // move there. A run of large rows without media no longer stalls it.\n let reachedTo: { id: string; depth: number } | undefined;\n for (let i = candidates.length - 1; i >= 0; i--) {\n if (candidates.length - 1 - i >= config.maxRowsPerPass) {\n totals.backlogRemains = true;\n break;\n }\n const row = candidates[i];\n reachedTo = row;\n const message = await this.#host.readMessage(row.id);\n if (!message) continue;\n\n const result = await evictMediaFromMessage(message, {\n minPartBytes: config.minPartBytes,\n write: async (index, bytes, mediaType) => {\n const path = evictedFilePath(message.id, index, mediaType);\n await files.write(path, bytes);\n return path;\n }\n });\n if (!result.changed) continue;\n\n // The rewritten row no longer carries the payload, so the bytes now\n // exist only as the Workspace file.\n await this.#host.updateMessage(result.message);\n totals.messages++;\n totals.parts += result.parts;\n totals.bytes += result.bytes;\n }\n\n // Move the cursor up to what this pass examined, one write: the newest\n // aged row, or the last candidate a pass cut short reached.\n const advanceTo = totals.backlogRemains\n ? reachedTo\n : newestAged === undefined\n ? undefined\n : { id: newestAged, depth: keep };\n if (storage && advanceTo) {\n await storage.put(CURSOR_KEY, {\n id: advanceTo.id,\n index: total - 1 - advanceTo.depth\n } satisfies EvictionCursor);\n }\n const storedBytes = this.#host.storedBytes();\n if (totals.messages > 0) {\n this.#fruitless = null;\n this.#host.emitEvicted({\n messages: totals.messages,\n parts: totals.parts,\n bytes: totals.bytes\n });\n } else if (this.#host.agedRowsHiddenFromCache() && storedBytes !== null) {\n this.#fruitless = {\n storedBytes,\n appendsSince: this.#appendsDuringPass\n };\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.#running = false;\n // Only chain when this pass actually shrank something: a pass that\n // changed nothing would otherwise reschedule itself forever.\n if (totals.backlogRemains && totals.messages > 0) {\n this.request();\n }\n // A request that landed mid-pass goes back through the gate now, so\n // media aged by an append during this pass is not left until the\n // next one. The gate, not the request, decides whether a pass runs.\n if (this.#pending) {\n this.#pending = false;\n this.request();\n }\n }\n }\n}\n","/**\n * Think's live in-memory view of the conversation (`this.messages`).\n *\n * Storage (Sessions) is the durable source of truth. The cache is refreshed\n * from it at safe boundaries and patched by the Sessions change feed between\n * them. Refreshes are bounded by `hydrationByteBudget`: an oversized\n * transcript hydrates as a recent window instead of exhausting the isolate's\n * memory (#1710).\n *\n * In memory only: the cached messages, the last hydration's measurements and\n * whether the cache covers the whole active path.\n */\n\nimport { RECENT_MESSAGE_LIMIT } from \"agents/internal\";\nimport type { UIMessage } from \"ai\";\n\nconst encoder = new TextEncoder();\n\n/**\n * A cached message's size in the unit the hydration budget is measured in:\n * UTF-8 bytes of its serialized form, not UTF-16 code units.\n *\n * @internal\n */\n\n/**\n * What the view charges each message it grows by, on top of its stored\n * bytes, as the released Think's did. The budgeted read counts stored\n * bytes alone; this charge decides when a view that grew re-windows, and\n * so what a warm object holds (think@0.24.0 under a 2,000 byte budget:\n * ten messages after twenty turns).\n *\n * @internal\n */\nexport const HYDRATION_MESSAGE_OVERHEAD_BYTES = 1024;\nexport function cachedMessageBytes(message: UIMessage): number {\n return encoder.encode(JSON.stringify(message)).byteLength;\n}\n\n/**\n * What the last budgeted refresh measured.\n *\n * @internal\n */\nexport interface HydrationResult {\n /** `true` when the cache is a recent window of a larger transcript. */\n truncated: boolean;\n totalContentBytes: number;\n hydratedMessages: number;\n}\n\n/**\n * What a {@link ThinkTranscriptCache} reads from its agent.\n *\n * @internal\n */\nexport interface TranscriptCacheHost {\n /** The agent's `hydrationByteBudget`. Non-finite or non-positive: no budget. */\n budget(): number;\n /** The full active path, unbudgeted. */\n readAll(): Promise<UIMessage[]>;\n readRecent(budget: number): Promise<{\n messages: UIMessage[];\n truncated: boolean;\n totalContentBytes: number;\n }>;\n /** A windowed refresh measured something new. */\n emitWindowed(payload: {\n totalContentBytes: number;\n budgetBytes: number;\n hydratedMessages: number;\n }): void;\n /** Called after every successful refresh. */\n refreshed(): void;\n}\n\n/** @internal */\nexport class ThinkTranscriptCache {\n readonly #host: TranscriptCacheHost;\n\n /** The cached messages. */\n messages: UIMessage[] = [];\n\n /**\n * Result of the most recent refresh when the budget is active. `null`\n * when no budget applies or no refresh has run.\n */\n lastHydration: HydrationResult | null = null;\n\n /**\n * `true` while the cache holds every message on the active path. That is\n * the common case: the default budget admits whole transcripts, and the\n * Sessions change feed patches the cache after every durable write. Set by\n * {@link sync}; `false` when the last refresh was windowed, failed, or has\n * not run yet. Readers that need the complete path consult it to decide\n * whether the cache can answer or storage must be read.\n */\n coversActivePath = false;\n\n /**\n * Serialized bytes the cache has grown by since the last refresh. Once the\n * growth would carry the cache past the budget measured at that refresh,\n * the cache stops claiming to cover the path, so the next boundary re-reads\n * storage and re-windows (#1710).\n */\n #bytesSinceSync = 0;\n /**\n * `true` after a windowed refresh while the cache is still that window\n * plus messages appended at its tail: current, only longer.\n */\n #windowCurrent = false;\n #warnedWindowed = false;\n /**\n * Snapshot of the last windowed emit, so a chronically oversized session\n * that syncs many times per turn emits on change, not on every sync.\n */\n #lastWindowedEmit: {\n totalContentBytes: number;\n hydratedMessages: number;\n } | null = null;\n\n constructor(host: TranscriptCacheHost) {\n this.#host = host;\n }\n\n /** Replace the cache with a durable storage snapshot. */\n replace(messages: UIMessage[]): UIMessage[] {\n this.messages = messages;\n return this.messages;\n }\n\n /**\n * Storage changed in a way the cache can't follow in place (an import):\n * the next boundary re-reads.\n */\n markStale(): void {\n this.coversActivePath = false;\n this.#windowCurrent = false;\n }\n\n /**\n * Re-read storage at a safe boundary only when the cache can't answer: it\n * isn't hydrated, it was marked stale, or a window has grown past an\n * eighth of the budget since its refresh (re-windowing trims it). A window\n * that only had messages appended at its tail is current, so a chat\n * request doesn't re-hydrate after each write. The cache holds at most\n * the budget plus that eighth.\n */\n async refreshIfNeeded(): Promise<void> {\n // A budgeted read returns at most `RECENT_MESSAGE_LIMIT` messages, so\n // a view that outgrew it by an eighth re-windows too: short messages\n // never reach the byte allowance, and a restart would hold fewer.\n const budget = this.#host.budget();\n if (\n Number.isFinite(budget) &&\n budget > 0 &&\n this.messages.length > RECENT_MESSAGE_LIMIT + RECENT_MESSAGE_LIMIT / 8\n ) {\n await this.sync();\n return;\n }\n if (this.coversActivePath) return;\n if (\n this.#windowCurrent &&\n this.#bytesSinceSync <= this.#host.budget() / 8\n ) {\n return;\n }\n await this.sync();\n }\n\n /** Charge `bytes` of growth since the last refresh against the budget. */\n noteGrowth(bytes: number): void {\n const budget = this.#host.budget();\n if (\n bytes <= 0 ||\n !Number.isFinite(budget) ||\n budget <= 0 ||\n !this.lastHydration\n ) {\n return;\n }\n this.#bytesSinceSync += bytes;\n if (this.lastHydration.totalContentBytes + this.#bytesSinceSync > budget) {\n this.coversActivePath = false;\n }\n }\n\n /**\n * Refresh the cache from durable storage at a safe boundary. The budget is\n * a hard ceiling with no message-count floor beneath it, so a window of\n * unusually large messages can be shorter than the model's recent window;\n * `getHistory()` still reads the full path.\n */\n async sync(): Promise<UIMessage[]> {\n // A refresh that throws leaves the cache unreliable until the next one.\n this.coversActivePath = false;\n this.#windowCurrent = false;\n this.#bytesSinceSync = 0;\n const budget = this.#host.budget();\n if (!Number.isFinite(budget) || budget <= 0) {\n this.lastHydration = null;\n this.#lastWindowedEmit = null;\n const full = this.replace(await this.#host.readAll());\n this.coversActivePath = true;\n this.#host.refreshed();\n return full;\n }\n\n const recent = await this.#host.readRecent(budget);\n this.lastHydration = {\n truncated: recent.truncated,\n totalContentBytes: recent.totalContentBytes,\n hydratedMessages: recent.messages.length\n };\n if (recent.truncated) {\n if (!this.#warnedWindowed) {\n this.#warnedWindowed = 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.#host.emitWindowed({\n totalContentBytes: recent.totalContentBytes,\n budgetBytes: budget,\n hydratedMessages: recent.messages.length\n });\n }\n } else {\n this.#lastWindowedEmit = null;\n }\n const hydrated = this.replace(recent.messages);\n this.coversActivePath = !recent.truncated;\n this.#windowCurrent = recent.truncated;\n this.#host.refreshed();\n return hydrated;\n }\n}\n","/**\n * The `skills` namespace Think re-exports: `agents/skills`, plus the\n * experimental script runner from `agents/skills/runner` so `skills.runner()`\n * keeps working for Think users.\n *\n * The exports are listed by name: the declaration bundler drops\n * `export * from` an external package inside a namespace.\n *\n * @module\n */\nexport {\n DEFAULT_WORKSPACE_SKILLS_ROOT,\n formatSkill,\n formatSkillDiagnostic,\n fromManifest,\n InvalidSkillResourcePathError,\n isModelInvocable,\n loadSkillCatalog,\n manifest,\n parseSkill,\n parseSkillName,\n parseSkillResourcePath,\n r2,\n renderSkillResource,\n SkillParseError,\n SkillResourceNotFoundError,\n SkillSourceError,\n UnknownSkillError,\n workspace\n} from \"agents/skills\";\nexport type {\n InvalidSkill,\n ListedSkill,\n LoadSkillCatalogOptions,\n ParseSkillOptions,\n R2SkillSourceOptions,\n Skill,\n SkillCatalog,\n SkillCatalogEntry,\n SkillCatalogResource,\n SkillDiagnostic,\n SkillListing,\n SkillManifest,\n SkillManifestEntry,\n SkillManifestResource,\n SkillName,\n SkillParseErrorCode,\n SkillParseResult,\n SkillResource,\n SkillResourceError,\n SkillResourceInfo,\n SkillResourceKind,\n SkillResourcePath,\n SkillResult,\n SkillRunContext,\n SkillScriptContext,\n SkillScriptFile,\n SkillScriptRequest,\n SkillScriptRunner,\n SkillScriptWorkspace,\n SkillSource,\n SkillWorkspace,\n WorkspaceSkillSourceOptions\n} from \"agents/skills\";\nexport { runner } from \"agents/skills/runner\";\nexport type { WorkerSkillScriptRunnerOptions } from \"agents/skills/runner\";\n","/**\n * Public turn, hook and option types of `Think`. Re-exported from\n * `@cloudflare/think`.\n */\n\nimport type {\n GenerateTextOnStepFinishCallback,\n InferToolOutput,\n LanguageModel,\n ModelMessage,\n PrepareStepFunction,\n PrepareStepResult,\n StopCondition,\n StreamTextOnChunkCallback,\n TextStreamPart,\n ToolSet,\n TypedToolCall,\n UIMessage,\n streamText\n} from \"ai\";\nimport type {\n ClientToolExecutor,\n ClientToolSchema,\n SaveMessagesResult\n} from \"agents/chat\";\nimport { CONTEXT_OVERFLOW_PATTERN } from \"agents/chat\";\nimport type { SessionMessage } from \"agents/sessions\";\nimport type { DeliveryKind, MessengerContext } from \"./messengers\";\n// Type-only, for the `{@link Think.*}` references in this file's docs.\n// oxlint-disable-next-line no-unused-vars\nimport type { Think } from \"./think\";\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\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\n/**\n * The sink of a `chat()` turn. The calls are `onStart`, then `onEvent` for\n * each chunk, then one terminal call: `onDone`, `onError` or\n * `onInterrupted`.\n *\n * A turn the caller cancels itself (its `signal`, or `cancelChat()` with the\n * id from `onStart`) gets no terminal call. The promise `chat()` returns\n * resolves, and that is the signal the turn is over. This holds whether the\n * cancel lands while the reply streams (the partial reply is stored) or\n * before the turn's message is stored (nothing is stored and the model is\n * never called).\n *\n * A chat cleared under the turn is reported through `onError`, unless the\n * caller had already cancelled.\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 * `info.deliversRecoveredReply` is true when the interrupted turn was a\n * messenger turn and this agent will post the recovered answer (or the\n * interrupted apology, if recovery gives up) to the messenger thread itself.\n */\n onInterrupted?(info?: ChatInterruptedInfo): void | Promise<void>;\n}\n\nexport interface ChatInterruptedInfo {\n deliversRecoveredReply?: boolean;\n}\n\n/**\n * Produces server-authored assistant-message metadata from AI SDK stream parts.\n * Forwarded to the AI SDK `toUIMessageStream` so a Think turn can stamp\n * structured metadata onto the assistant message it persists. Called for every\n * stream part; use `part.type` to choose when to return metadata (`start` and\n * `finish` are the conventional points). Each non-`undefined` return is\n * shallow-merged into the message's metadata. The return value is broadcast to\n * clients and persisted, so it must be\n * JSON-serializable and must not carry server-only secrets.\n *\n * `continuation` is true when the turn continues an earlier one (a recovery\n * continuation or an auto-continue after a tool result). A recovery\n * continuation streams into the interrupted assistant message, so its `start`\n * part cannot overwrite keys that message already has: a `createdAt` stamped\n * on the original `start` survives. Keys the continuation's `start` adds, and\n * everything from later parts, merge as usual.\n *\n * The `Metadata` parameter defaults to the opaque `Record<string, unknown>` used\n * everywhere metadata rides today; it is the seam a future typed-metadata story\n * (issue #1676) narrows without a breaking change.\n */\nexport type MessageMetadataCallback<\n Metadata extends Record<string, unknown> = Record<string, unknown>\n> = (options: {\n part: TextStreamPart<ToolSet>;\n continuation: boolean;\n}) => Metadata | undefined;\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. Omit it to\n * run without a channel context. (WebSocket chat turns always run on the\n * 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 /** Persisted assistant produced by this completed turn; absent otherwise. */\n message?: SessionMessage;\n /**\n * Parsed structured output when the turn's `TurnConfig.output` produced\n * one. A structured output that fails to parse ends the turn with\n * `status: \"error\"`.\n */\n output?: unknown;\n continuation: boolean;\n};\n\n/** What admitted a turn. Exposed on {@link ActiveTurn} and {@link TurnContext}. */\nexport type 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\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\n/** @internal Workflow `step.prompt` settings carried on a turn. */\nexport type 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\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: an overridden `getSystemPrompt()`, then context blocks. */\n system: string;\n /**\n * Assembled model messages (truncated, pruned). When a `whenChanged:\n * \"remind\"` context block has changed since the prompt froze, its current\n * value rides at the end, inside the last user message when there is one.\n */\n messages: ModelMessage[];\n /** Merged tool set (workspace + getTools + session + MCP + client + caller). */\n tools: ToolSet;\n /**\n * The language model from getModel(), resolved on first read — a\n * `beforeTurn` that returns its own `model` without reading this never\n * resolves the default.\n */\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 * The request this turn runs for: the same id `beforePersist`,\n * `onChatResponse` and `onChatError` see. Undefined for inference that runs\n * outside an admitted turn.\n */\n requestId?: string;\n /** What admitted this turn. Undefined outside an admitted turn. */\n trigger?: TurnTrigger;\n /**\n * Aborts when the turn is cancelled. Pass it to any I/O `beforeTurn` awaits\n * so a stopped turn does not wait for it to finish.\n */\n abortSignal?: AbortSignal;\n /**\n * The messenger thread this turn answers, fixed when the turn was admitted.\n * Unlike {@link Think.getMessengerContext}, it never falls back to another\n * turn's message.\n */\n messenger?: MessengerContext;\n}\n\n/**\n * The turn currently running on this agent. See {@link Think.activeTurn}.\n */\nexport interface ActiveTurn {\n /** Request id shared by every hook, tool call and event of this turn. */\n requestId: string;\n trigger: TurnTrigger;\n continuation: boolean;\n /** Channel the turn resolved to, when it has one. */\n channel?: string;\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 * Produces server-authored assistant-message metadata for this turn — the\n * write path that lets a turn attach structured metadata (e.g. a `createdAt`\n * timestamp) to the assistant message Think persists, matching the AI SDK\n * `messageMetadata` callback base `AIChatAgent` + `streamText` already accept.\n * Overrides the instance-level {@link Think.messageMetadata} for this turn.\n * Configure from a Think subclass; sandboxed extensions cannot send functions\n * over RPC. See {@link MessageMetadataCallback} for when it is called and the\n * serialization constraints on its return value.\n */\n messageMetadata?: MessageMetadataCallback;\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 * Repairs tool calls that the AI SDK cannot parse or validate before tool\n * execution. The returned tool call is parsed and validated again. Configure\n * this function from a Think subclass; sandboxed extensions cannot send\n * functions over RPC.\n *\n * Typed via the `experimental_repairToolCall` key, which exists in both AI\n * SDK v6 and v7 (`repairToolCall` is v7-only), so this type resolves under\n * either supported major.\n */\n repairToolCall?: Parameters<\n typeof streamText\n >[0][\"experimental_repairToolCall\"];\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 * Think compacts and retries when `contextOverflow.reactive` is enabled.\n * - `rate_limit` / `transient` — a stream error worth retrying (a 429, a\n * dropped connection). Think routes the turn into bounded chat recovery, like\n * a stream stall, and schedules the continuation with exponential backoff.\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 */\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 * `true` when the failed turn was a server-started continuation (for\n * example after a tool approval or a client tool result) rather than a\n * turn a client or caller submitted.\n */\n continuation?: 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 // The SDK's type includes `undefined` on some majors; `Omit` over that\n // union would keep no field.\n NonNullable<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 * Request id of the turn making this call, matching `TurnContext.requestId`\n * and `onChatResponse`. Undefined outside an admitted turn.\n */\n readonly requestId?: string;\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 /** Request id of the turn that made this call; see `ToolCallContext`. */\n readonly requestId?: string;\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 * 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","import { defaultAttachmentText, deliverReplyAttachments } from \"./attachments\";\nimport type {\n ActionApprovalDescriptor,\n Action,\n ActionAuthorizationContext,\n ActionAuthorizationDecision,\n ActionPermissionSpec,\n CompiledActionMetadata,\n ReplyAttachment,\n NormalizedActionAuthorization\n} from \"./actions\";\nimport { runLedgeredAction } from \"./action-run\";\nimport { turnTraceOf } from \"./turn-trace\";\nimport { truncatePausedExecutionOutput } from \"./tools/execute\";\nimport {\n Agent,\n type AgentContext,\n type Connection,\n type ConnectionContext,\n type FiberRecoveryContext,\n type SubAgentClass,\n type WSMessage,\n callable,\n isPlatformTransientError,\n __DO_NOT_USE_WILL_BREAK__agentContext as agentContext,\n type AgentToolLifecycleResult,\n type AgentToolMilestone,\n type AgentToolProgress,\n type AgentToolRunInfo,\n type AgentToolRunInspection,\n type AgentToolStoredChunk\n} from \"agents\";\nimport {\n CHAT_LAST_TERMINAL_KEY,\n CHAT_REQUEST_CONTEXT_KEY,\n recordRecentChatTerminal,\n type ChatTerminalRecord,\n DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS,\n requestContextFromLegacy,\n storableRequestContext,\n unwrapChatFiberSnapshot,\n interruptedToolPartAsError,\n sweepStaleChatRecoveryIncidents,\n CHAT_MESSAGE_TYPES,\n buildChatRecoveringFrame,\n setChatRecovering,\n unexecutedToolNames,\n type ChatRecoveryConfig,\n type ChatRecoveryContext,\n type ChatRecoveryExhaustedContext,\n type ChatRecoveryOptions,\n classifyProviderError,\n runningChatTurn,\n truncateOlderMessages,\n truncateOlderToolResults,\n truncationKeepRecent,\n AgentToolStreamProgressThrottle,\n progressCreditOf,\n partialHasSettledToolResults,\n type ChatResponseResult,\n type SaveMessagesOptions,\n type SaveMessagesResult,\n AgentToolProgressEmitter,\n agentToolTurnChunks,\n agentToolTurnId,\n agentToolTurnOf,\n noteAgentToolStop,\n carryForwardAgentToolRuns,\n ReplyStreams,\n chatDispatch,\n createToolsFromClientSchemas,\n forgetTab,\n inspectAgentToolTurn,\n liveTurnsOf,\n recordAgentToolProgress,\n releasedAgentToolRunOfRequest,\n resumeChat,\n startAgentToolTurn,\n tailAgentToolTurn,\n type ChatArrival,\n type MessageConcurrency,\n migrateReleasedChatProgress,\n storedAsFacet\n} from \"agents/chat\";\nimport {\n ThinkChat,\n ThinkHarness,\n type ThinkErrorClass,\n type ThinkOperationResult,\n type ThinkOperationStatus,\n type ThinkStreamCallback,\n type ThinkToolCallDecision,\n type ThinkTurnConfig,\n type ThinkTurnContext\n} from \"agents/harness/think\";\nimport {\n convertToModelMessages,\n getToolName,\n isToolUIPart,\n jsonSchema,\n tool,\n type LanguageModel,\n type LanguageModelUsage,\n type ModelMessage,\n type Tool,\n type ToolSet,\n type TypedToolCall,\n type UIMessage,\n type UIMessageChunk\n} from \"ai\";\nimport { ThinkModelResolver } from \"./model\";\nimport type { RecoveredReplyPost } from \"./messengers/recovered-reply\";\nimport {\n releasedReplies,\n type ReleasedReplies\n} from \"./harness/released-replies\";\nimport {\n DEFAULT_MESSENGER_CONCURRENCY,\n type MessengerConcurrency,\n type MessengerContext,\n type MessengerDeliverySurface,\n type MessengerThinkTarget,\n type ThinkMessengers\n} from \"./messengers\";\nimport {\n resolveChannels,\n type ChannelContext,\n type NormalizedChannelDefinition,\n type ThinkChannels\n} from \"./channels\";\nimport {\n deliverChannelNotice,\n resolveChannelContext\n} from \"./channels/runtime\";\nimport {\n channelFromMessages,\n stampTurnContext,\n turnMetadataFromMessages\n} from \"./turn-metadata\";\nimport type {\n ActiveTurn,\n DeliverNoticeOptions,\n ChatErrorContext,\n ContextOverflowConfig,\n ExtensionConfig,\n MessageMetadataCallback,\n OnStartDegradation,\n AddMessagesOptions,\n ChatErrorClassification,\n RunTurnOptions,\n RunTurnStream,\n RunTurnSubmit,\n RunTurnWait,\n TurnResult,\n ChatOptions,\n ChunkContext,\n PrepareStepContext,\n StepConfig,\n StepContext,\n StreamCallback,\n ThinkModel,\n ToolCallContext,\n ToolCallDecision,\n ToolCallResultContext,\n TurnConfig,\n TurnContext,\n TurnInputMessages,\n TurnTrigger\n} from \"./turn-types\";\nimport {\n messengerChannels,\n type ThinkMessengerChannels\n} from \"./harness/messenger-channels\";\nimport {\n reconcileScheduledTasks,\n type ThinkScheduledTasks\n} from \"./scheduled-tasks\";\nimport { Workspace, type WorkspaceStub } from \"@cloudflare/computer\";\nimport { workspaceExtension } from \"./harness/extensions/workspace\";\nimport { fetchExtension } from \"./harness/extensions/fetch\";\nimport { skillsExtension } from \"./harness/extensions/skills\";\nimport { sandboxedExtensions } from \"./harness/extensions/sandboxed\";\nimport { actionsExtension } from \"./harness/extensions/actions\";\nimport {\n actionApprovalInputErrorEnvelope,\n actionErrorEnvelope,\n compileActionTools,\n prepareActionOutputForModel,\n normalizeActionAuthorization,\n resolveActionPermissions,\n type ActionToolHost\n} from \"./action-tools\";\nimport {\n createEffectState,\n decisionIdOf,\n DECISION_TASK,\n decisionRunId,\n isPendingDecision,\n parkDecision,\n pendingDecisions,\n releasedActionsLeft,\n releasedActionsMigration,\n registerDecisionTask,\n registerEffectTask,\n stableStringify,\n sweepDecisions,\n sweepEffects,\n type DecisionInput,\n type DecisionVerdict\n} from \"./action-ledger\";\nimport {\n dropGenerationAfterToolCall,\n executionToolCallIn\n} from \"./execution-parts\";\nimport type {\n CodemodeRuntimeHandle,\n PendingAction\n} from \"@cloudflare/codemode\";\nimport { ReplyAttachments } from \"./reply-attachments\";\nimport {\n callThinkHostApi,\n createThinkHostApi,\n type ThinkHostApi,\n type ThinkHostOperation\n} from \"./extensions/host-api\";\nimport type { ExtensionManager } from \"./extensions/manager\";\nimport {\n createThinkExtensionManager,\n loadThinkExtensions,\n ThinkExtensionHooks\n} from \"./extensions/wiring\";\nimport { ThinkSkills } from \"./skills-runtime\";\nimport { declaredOverrides } from \"./overrides\";\nimport type { SkillScriptRunner, SkillSource } from \"agents/skills\";\nimport {\n CONTEXT_REMINDER_MESSAGE_ID,\n FIBER_TASK,\n legacyFiberOpen,\n SUPERSEDED_BY,\n GAVE_UP_TEXT_MAX,\n TURN_NOT_CONTINUED,\n legacyFiberSnapshot,\n legacyOpenFibers,\n importTaskRun,\n mcpConnectionsExtension,\n mcpExtension,\n registerDeliverySink,\n sendDelivery,\n moveReleaseStreams\n} from \"agents/internal\";\nimport {\n WORKFLOW_NOTIFICATION_SINK,\n legacyWorkflowNotification,\n sendWorkflowNotification,\n workflowNotificationSink,\n workflowPromptContext\n} from \"./workflow-notifications\";\nimport {\n THINK_FINAL_ANSWER_TOOL_NAME,\n thinkFinalAnswerInstruction,\n withoutFinalAnswerParts\n} from \"./inference/structured-output\";\nimport {\n admittedSubmissionMetadata,\n SKIPPED_BY_RESET,\n SUBMISSION_MESSAGES_INVALID,\n submissionOutputFits,\n submissionOutputTooLarge,\n SUBMISSION_PROGRESS_KEY,\n cancelReason,\n legacySubmissionAnswer,\n legacySubmissionAppMetadata,\n isTerminalSubmissionStatus,\n SubmissionStatusQueue,\n TERMINAL_SUBMISSION_STATUSES,\n type DeleteSubmissionsOptions,\n type LegacySubmissionRow,\n type ListSubmissionsOptions,\n type ThinkSubmissionStatus,\n type CancelSubmissionResult,\n type WaitForSubmissionOptions,\n type SubmitMessagesResult,\n type ThinkSubmissionInspection\n} from \"./submissions\";\nimport type { TaskJson, TaskStatus } from \"agents/tasks\";\nimport type { CreateFetchToolsOptions } from \"./tools/fetch\";\nimport {\n isLocalWorkspace,\n type ThinkWorkspace,\n WorkspaceFiles\n} from \"./workspace-files\";\nimport { ThinkSession } from \"./session\";\nimport { tableExists, ThinkConfigStore } from \"./config-store\";\nimport {\n migrateReleasedSubmissions,\n removeEmptiedSubmissionsTable\n} from \"./release-submissions\";\nimport { DEFAULT_SYSTEM_PROMPT, systemPromptForTurn } from \"./system-prompt\";\nimport {\n isCompactionMessage,\n type Session,\n type SessionMessage,\n type Sessions\n} from \"agents/sessions\";\nimport type { Streams } from \"agents/streams\";\nimport {\n MediaEvictionPasses,\n resolveMediaEvictionConfig,\n type MediaEvictionConfig\n} from \"./media-eviction\";\nimport {\n EXECUTION_OUTCOME_MESSAGE_PREFIX,\n MODEL_TRUNCATION_STEP,\n toProviderSafeExecutionOutcomeMessage\n} from \"./inference/model-messages\";\nimport {\n HYDRATION_MESSAGE_OVERHEAD_BYTES,\n cachedMessageBytes,\n ThinkTranscriptCache,\n type HydrationResult\n} from \"./transcript-cache\";\nimport {\n AgentContextProvider,\n Context,\n type ContextConfig\n} from \"agents/context\";\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 holds one conversation in its own SQLite storage, backed by\n * Sessions — providing tree-structured messages, context blocks, compaction,\n * and FTS5 search.\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() — instructions at the top of the system prompt\n * - getTools() — return the ToolSet for the agentic loop\n * - maxSteps — max tool-call rounds per turn (default: 10)\n * - configureSession() — compaction and search policy\n * - configureContext() — declare prompt context blocks\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 (one abort signal per request)\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/deepseek-ai/deepseek-v4.1-flash-1017\";\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 { ContextConfig } from \"agents/context\";\n *\n * export class MemoryAgent extends Think<Env> {\n * getModel() { ... }\n *\n * configureContext(): ContextConfig[] {\n * return [\n * {\n * label: \"soul\",\n * provider: { get: async () => \"You are a helpful coding assistant.\" }\n * },\n * {\n * label: \"memory\",\n * description: \"Important facts learned during conversation.\",\n * maxTokens: 2000\n * }\n * ];\n * }\n * }\n * ```\n */\n\nimport * as skills from \"./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 {\n Skill,\n SkillCatalog,\n SkillRunContext,\n SkillSource\n} from \"agents/skills\";\n\nexport type {\n CancelSubmissionResult,\n DeleteSubmissionsOptions,\n ListSubmissionsOptions,\n SubmitMessagesResult,\n ThinkSubmissionInspection,\n ThinkSubmissionStatus,\n WaitForSubmissionOptions\n} from \"./submissions\";\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 } from \"./messengers\";\nexport { ThinkSession, ThinkSession as Session } from \"./session\";\nexport type {\n CompactAfterOptions,\n CompactionErrorHandler,\n SessionContextOptions\n} from \"./session\";\nexport type { SessionMessage } from \"agents/sessions\";\nexport type { FiberContext, FiberRecoveryContext } from \"agents\";\nexport type {\n ThinkIntervalSchedule,\n ThinkScheduledTask,\n ThinkScheduledTaskContext,\n ThinkScheduledTasks,\n ThinkScheduledTaskSchedule,\n ThinkTime,\n ThinkWallClockSchedule\n} from \"./scheduled-tasks\";\nexport type {\n ThinkWorkspace,\n ThinkWorkspaceFilesystem\n} from \"./workspace-files\";\n\nexport type {\n CreateFetchToolsOptions,\n FetchBindingTarget,\n FetchResult,\n FetchToolEvent,\n FetchErrorCode,\n FetchResponseMode,\n FetchRedirectPolicy\n} from \"./tools/fetch\";\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 monotonic forward-progress marker the recovery budget keys off is\n// derived from the stream log (`ReplyStreams.progressMarker`): durably\n// flushed segments, folded into a retired total as their rows are deleted.\n// Nothing is written per chunk. The pre-derivation KV counter\n// (`CHAT_RECOVERY_PROGRESS_KEY`) is read once per isolate and seeded into the\n// marker, so it is never read lower than an in-flight incident recorded.\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// The N9 throttle lives\n// there too as `AgentToolStreamProgressThrottle`.)\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\nexport type { MediaEvictionConfig } from \"./media-eviction\";\nexport { action, isAction } from \"./actions\";\nexport type {\n Action,\n ActionApprovalDescriptor,\n ActionApprovalPolicy,\n ActionAuthorizationContext,\n ActionAuthorizationDecision,\n ActionConfig,\n ActionContext,\n ActionIdempotencyKey,\n ActionKind,\n ActionPermissionSpec,\n ReplyAttachment\n} from \"./actions\";\nexport { defaultContextOverflowClassifier } from \"./turn-types\";\nexport type {\n ActiveTurn,\n AddMessagesOptions,\n ChatErrorClassification,\n ChatErrorContext,\n ChatInterruptedInfo,\n ChatOptions,\n ChatStartEvent,\n ChunkContext,\n ChunkPart,\n ContextOverflowConfig,\n DeliverNoticeOptions,\n ExtensionConfig,\n MessageMetadataCallback,\n OnStartDegradation,\n PrepareStepContext,\n RunTurnBase,\n RunTurnOptions,\n RunTurnStream,\n RunTurnSubmit,\n RunTurnWait,\n StepConfig,\n StepContext,\n StreamCallback,\n StreamableResult,\n ThinkModel,\n ThinkModelId,\n ToolCallContext,\n ToolCallDecision,\n ToolCallResultContext,\n TurnConfig,\n TurnContext,\n TurnInput,\n TurnInputMessages,\n TurnResult,\n TurnTrigger\n} from \"./turn-types\";\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 RejectExecutionOptions {\n /**\n * Whether Think starts a model continuation after recording the rejection.\n * Defaults to `true`. Set this to `false` when the caller wants the\n * conversation to remain paused until a later user turn.\n */\n autoContinue?: boolean;\n}\n\nexport type SubmitMessagesOptions = {\n submissionId?: string;\n idempotencyKey?: string;\n metadata?: Record<string, unknown>;\n /** Channel id this submission belongs to. See the `channel` option of {@link RunTurnOptions}. */\n channel?: string;\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 SkippedTurnReason\n} from \"agents/chat\";\n\nconst { snapshot: snapshotDeclaredMembers, isOverridden: isMethodOverridden } =\n declaredOverrides(() => Think.prototype);\n\nfunction toInput(\n input: Exclude<TurnInputMessages, (current: UIMessage[]) => unknown>\n): UIMessage[] {\n if (typeof input === \"string\") {\n return [\n {\n id: crypto.randomUUID(),\n role: \"user\",\n parts: [{ type: \"text\", text: input }]\n }\n ];\n }\n return Array.isArray(input) ? input : [input];\n}\n\n/**\n * Parts without the `step-start` the dropped waiting text leaves at their\n * end: the continuation opens its own step in the same message, so the\n * leftover would be an empty step before it.\n */\nfunction withoutTrailingStepStart(\n parts: UIMessage[\"parts\"]\n): UIMessage[\"parts\"] {\n let end = parts.length;\n while (end > 0 && parts[end - 1]?.type === \"step-start\") end--;\n // An attempt a reset cut off can leave a step that opened nothing, too:\n // one `step-start` stands for a run of them.\n const kept = parts\n .slice(0, end)\n .filter(\n (part, at, all) =>\n part.type !== \"step-start\" || all[at + 1]?.type !== \"step-start\"\n );\n return kept.length === parts.length ? parts : kept;\n}\n\n/** The field a written outcome's call keeps: the execution it resolves. */\nconst RESOLVED_EXECUTION_FIELD = \"resolvedExecutionId\";\n\n/** Whether `message` holds the call an execution's outcome was written to. */\nfunction resolvesExecution(message: UIMessage, executionId: string): boolean {\n return message.parts.some(\n (part) =>\n (part as Record<string, unknown>)[RESOLVED_EXECUTION_FIELD] ===\n executionId\n );\n}\n\n/** An approved action whose claim a reset left behind waits for it. */\nconst DEFER_DECISION = Symbol(\"think.deferDecision\");\n\n/** As in 0.24: what approving a call whose action was removed answers. */\nfunction removedActionError(action: string): string {\n return (\n `Action \"${action}\" is no longer registered, so the ` +\n `approved call cannot run. The approval was consumed.`\n );\n}\n\n/** As in 0.24: tries of an approved durable pause before it gives up. */\nconst MAX_DECISION_TRIES = 3;\n\n/**\n * An action's error envelope, capped as an action output is (an output\n * already was): the outcome is kept on its decision until written.\n */\nfunction capErrorEnvelope(output: unknown): unknown {\n const error =\n output !== null && typeof output === \"object\"\n ? (output as { error?: unknown }).error\n : undefined;\n return error !== null &&\n typeof error === \"object\" &&\n typeof (error as { message?: unknown }).message === \"string\"\n ? prepareActionOutputForModel(output)\n : output;\n}\n\n/** The wire type of the recovering status frame (#1620). */\nconst CHAT_RECOVERING_FRAME = CHAT_MESSAGE_TYPES.CHAT_RECOVERING;\n\n/** Marks an operation that answers the history with a new reply. */\nconst NEW_REPLY_KEY = \"cf_think_new_reply\";\n\ntype StaticTurnInput = Exclude<\n TurnInputMessages,\n (current: UIMessage[]) => unknown\n>;\n\n/** As 0.24's runTurn read static input: an empty string is no message. */\nfunction runTurnMessages(input: StaticTurnInput): UIMessage[] {\n if (typeof input === \"string\" && input.length === 0) return [];\n return toInput(input);\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** Think's submission status for a harness operation status. */\nfunction submissionStatus(\n status: ThinkOperationStatus & { readonly abortReason?: string }\n): ThinkSubmissionInspection[\"status\"] {\n switch (status.status) {\n case \"queued\":\n return \"pending\";\n case \"running\":\n return \"running\";\n case \"done\":\n return \"completed\";\n case \"unanswered\":\n // A turn reset stops its submissions with this reason; as in 0.24,\n // they end skipped.\n if (status.abortReason === SKIPPED_BY_RESET) return \"skipped\";\n return status.reason === \"aborted\" || status.reason === \"withdrawn\"\n ? \"aborted\"\n : \"error\";\n }\n}\n\n/** The Tasks definition think@0.24.0 ran a chat turn under. */\nconst RELEASED_CHAT_TURN_DEFINITION = \"__cf_internal_chat_turn\";\n/**\n * TEMPORARY (the import): a release's fiber turn that went on as its\n * submission's operation at start, by the turn's request id, until the\n * fiber's recovery has seen it.\n */\nconst RELEASED_FIBER_SUBMISSION_PREFIX = \"cf_think_released_fiber_turn:\";\n/** The note's value for a turn that was found finished: no operation. */\nconst RELEASED_FIBER_TURN_FINISHED = \"\\u0000finished\";\n/** Where a release kept a response hook its turn still owed. */\nconst RELEASED_OWED_RESPONSE_HOOK_PREFIX = \"cf_think_pending_response_hook:\";\n\n/**\n * `added` without the tool calls `prompt` already holds (by call id): a\n * rewritten prompt may keep an approved call, and what is added for it is\n * then its result alone. One call and one result per id.\n */\nfunction withoutRepeatedCalls(\n prompt: readonly ModelMessage[],\n added: ModelMessage[]\n): ModelMessage[] {\n const held = new Set<string>();\n for (const message of prompt) {\n if (message.role !== \"assistant\" || typeof message.content === \"string\") {\n continue;\n }\n for (const part of message.content) {\n if (part.type === \"tool-call\") held.add(part.toolCallId);\n }\n }\n if (held.size === 0) return added;\n return added.flatMap((message) => {\n if (message.role !== \"assistant\" || typeof message.content === \"string\") {\n return [message];\n }\n const content = message.content.filter(\n (part) =>\n !(\n (part.type === \"tool-call\" ||\n part.type === \"tool-approval-request\") &&\n held.has(part.toolCallId)\n )\n );\n return content.length === 0 ? [] : [{ ...message, content }];\n });\n}\n\n/** The operation a decision's continuation runs as, by its execution. */\nconst DECISION_CONTINUE_PREFIX = \"decision-continue:\";\n/**\n * The queue item a decision's continuation starts through, and its\n * callback: the names think@0.24.0 queued its own under, so an item a\n * release left is run too.\n */\nconst DECISION_CONTINUATION_QUEUE_ID = \"connectionless-continuation\";\nconst DECISION_CONTINUATION_CALLBACK = \"_cfRunConnectionlessContinuation\";\n\n/** What Think reports for a submission interrupted and not recovered. */\nconst SUBMISSION_INTERRUPTED =\n \"Submission was interrupted after messages were applied.\";\n/**\n * An operation's reason as an app is told it: a turn that was cut and not\n * taken up again says so in Think's released sentence, not in the\n * harness's word for it.\n */\nfunction saidOf(result: {\n readonly reason?: string;\n readonly gaveUpWith?: string;\n}): string | undefined {\n // A turn recovery gave up says what its last model call failed with,\n // or the sentence its tab is shown.\n if (result.reason === \"interrupted\") {\n return result.gaveUpWith ?? SUBMISSION_INTERRUPTED;\n }\n return result.reason;\n}\n/** The same, when only some of its messages had been stored. */\nconst SUBMISSION_PARTLY_APPLIED =\n \"Submission was interrupted after messages were partially applied.\";\n\n/**\n * Submissions read per page when deleting in bulk, whatever the limit: a\n * small limit does not cost a read per submission it passes over.\n */\nconst DELETE_PAGE = 100;\n\n/** An operation's inspection: its status, times, key and metadata. */\ntype ThinkOperationInspection = NonNullable<\n Awaited<ReturnType<ThinkHarness[\"inspection\"]>>\n>;\n\n/** A harness operation as 0.24's submission inspection. */\nfunction submissionInspection(\n status: ThinkOperationInspection\n): ThinkSubmissionInspection {\n // The metadata the app gave, without what Think keeps beside it.\n const { [SUBMISSION_PROGRESS_KEY]: _progress, ...app } =\n status.metadata ?? {};\n const metadata = Object.keys(app).length > 0 ? app : undefined;\n return {\n submissionId: status.operationId,\n requestId: status.operationId,\n status: submissionStatus(status),\n createdAt: status.createdAt,\n ...(status.startedAt !== undefined && { startedAt: status.startedAt }),\n ...(status.settledAt !== undefined && { completedAt: status.settledAt }),\n ...(status.idempotencyKey !== undefined && {\n idempotencyKey: status.idempotencyKey\n }),\n ...(metadata !== undefined && { metadata }),\n // A cancel's own reason, as in 0.24; else how the operation ended. A\n // turn that was interrupted and not recovered is reported in Think's\n // words. A stop with no reason is the status alone: `aborted` is not\n // an error, nor is any of the harness's own words for a turn that\n // never ran (stopped while it waited, say).\n ...(status.status === \"unanswered\" &&\n (status.abortReason ??\n (status.reason === undefined ||\n status.reason === \"aborted\" ||\n NEVER_RAN.has(status.reason)\n ? undefined\n : status.reason)) !== undefined && {\n error: status.abortReason ?? saidOf(status)\n }),\n ...(\"messageId\" in status &&\n status.messageId !== undefined && { messageId: status.messageId })\n };\n}\n\n/** A status filter as a list, or none. */\nfunction submissionStatuses(\n status: ThinkSubmissionStatus | ThinkSubmissionStatus[] | undefined\n): ThinkSubmissionStatus[] | undefined {\n if (status === undefined) return undefined;\n return Array.isArray(status) ? status : [status];\n}\n\n/**\n * The run statuses a submission of these statuses can have. An operation\n * that ended unanswered is a completed run, so a terminal status other\n * than `completed` also looks at completed runs; callers match the mapped\n * status after.\n */\nfunction taskStatusesFor(\n wanted: readonly ThinkSubmissionStatus[]\n): TaskStatus[] {\n const out = new Set<TaskStatus>();\n for (const status of wanted) {\n if (status === \"pending\" || status === \"running\") {\n out.add(\"pending\");\n out.add(\"running\");\n } else {\n out.add(\"completed\");\n if (status !== \"completed\") out.add(status);\n // A submission a turn reset ended is an aborted run.\n if (status === \"skipped\") out.add(\"aborted\");\n }\n }\n return [...out];\n}\n\n/** What a `chat()` caller is told when a reset cuts its turn off (as 0.24). */\nconst CHAT_CLEARED_ERROR = \"The chat was cleared before the turn finished.\";\n\n/** What Think says when a turn is asked for with no message to send. */\nconst NO_MESSAGES_TO_SEND =\n \"No messages to send to the model. This usually means the chat request \" +\n \"arrived before any messages were persisted.\";\n\n/** The reasons ThinkHarness ends an operation with when it never ran. */\nconst NEVER_RAN = new Set([\n \"withdrawn\",\n \"not_waiting\",\n \"not_found\",\n \"empty\",\n \"awaiting_client\"\n]);\n\n/** A programmatic turn stopped, or cleared by a reset, before it began. */\nfunction cutOffBeforeStart(cut: \"stopped\" | \"cleared\"): SaveMessagesResult {\n return cut === \"cleared\"\n ? { requestId: crypto.randomUUID(), status: \"skipped\", reason: \"cleared\" }\n : { requestId: crypto.randomUUID(), status: \"aborted\", reason: \"stopped\" };\n}\n\nfunction saveResult(result: ThinkOperationResult): SaveMessagesResult {\n if (result.status === \"done\") {\n return { requestId: result.operationId, status: \"completed\" };\n }\n // A stopped turn ends \"aborted\"; one stopped while it waited, before it\n // started, ends \"withdrawn\". Think reports both as aborted by a stop.\n if (result.reason === \"aborted\" || result.reason === \"withdrawn\") {\n return {\n requestId: result.operationId,\n status: \"aborted\",\n reason: \"stopped\"\n };\n }\n return {\n requestId: result.operationId,\n status: \"error\",\n ...(result.reason !== undefined && { error: saidOf(result) })\n };\n}\n\n/** The request a tab's stop frame names, if `message` is one. */\nfunction cancelledRequestOf(message: WSMessage): string | undefined {\n if (typeof message !== \"string\" || !message.includes(\"_cancel\")) {\n return undefined;\n }\n try {\n const frame = JSON.parse(message) as { type?: unknown; id?: unknown };\n return frame.type === \"cf_agent_chat_request_cancel\" &&\n typeof frame.id === \"string\"\n ? frame.id\n : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Whether a tab's frame is a chat clear. */\nfunction isChatClear(message: WSMessage): boolean {\n if (typeof message !== \"string\" || !message.includes(\"chat_clear\")) {\n return false;\n }\n try {\n return (\n (JSON.parse(message) as { type?: unknown }).type === \"cf_agent_chat_clear\"\n );\n } catch {\n return false;\n }\n}\n\nexport class Think<\n Env extends Cloudflare.Env = Cloudflare.Env,\n State = unknown,\n Props extends object = object\n> extends Agent<Env, State, Props> {\n static readonly CHAT_FIBER_NAME = \"__cf_internal_chat_turn\";\n /**\n * How long after its turn started an interrupted submission is still\n * recovered. Past it, the submission ends `error`.\n */\n protected static submissionRecoveryStaleMs = 15 * 60 * 1000;\n\n /** Model calls per turn. Read per call, so a subclass field applies. */\n maxSteps = 10;\n /** Whether reasoning reaches the stream, as in 0.24; a turn may say. */\n sendReasoning = true;\n\n /** How a messenger thread's burst of messages is answered, as in 0.24. */\n messengerConcurrency: MessengerConcurrency = DEFAULT_MESSENGER_CONCURRENCY;\n\n /**\n * Metadata for every assistant message, as in 0.24. A turn's\n * `beforeTurn` may return its own `messageMetadata` instead.\n */\n messageMetadata?: MessageMetadataCallback;\n\n /**\n * Opt-in handling for a turn that overflows the context window, as on\n * Think. Unset leaves an overflow terminal.\n */\n contextOverflow?: ContextOverflowConfig;\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 /** @internal */\n readonly harness: ThinkHarness;\n readonly #chat: ThinkChat;\n /**\n * The messengers from `getMessengers()` and `configureChannels()`, as\n * Chat SDK Channels, once start has read them; `undefined` on a\n * sub-agent and for an app with none.\n */\n #messengers: ThinkMessengerChannels | undefined;\n /** Where the messengers mount: installed empty on the root, filled at start. */\n #messengerSlot: ThinkMessengerChannels | undefined;\n\n /**\n * Install the empty slot the messengers mount in: on the root, before\n * startup locks the capabilities. It calls nothing of the app's and\n * touches no storage; `onStart` fills it once it has read the messengers.\n */\n #reserveMessengerSlot(): void {\n // As in 0.24: a sub-agent has no messengers. Its root's post for it.\n if (this.#messengerSlot || this.parentPath.length > 0) return;\n this.#messengerSlot = messengerChannels({\n harness: this.harness,\n tasks: this.tasks,\n root: () => this.parentPath.length === 0,\n kv: this.ctx.storage.kv,\n storage: this.ctx.storage,\n parent: this,\n concurrency: () => this.messengerConcurrency,\n // A thread's conversation: a sub-agent of this class unless the\n // resolver names another, as in 0.24.\n subAgent: async (agentClass, name) =>\n (await this.subAgent(\n (agentClass ?? this.constructor) as SubAgentClass<Think>,\n name\n )) as unknown as Required<MessengerThinkTarget>\n });\n this.lifecycle\n .use(this.#messengerSlot.channels.streams)\n .use(this.#messengerSlot.channels);\n }\n /** TEMPORARY (the import): the recovered replies think@0.24.0 kept. */\n readonly #releasedReplies: ReleasedReplies;\n readonly #handlers: Parameters<\n ConstructorParameters<typeof ThinkChat>[0][\"webSockets\"][\"use\"]\n >[0][] = [];\n\n /** The conversation, configured by {@link configureSession}. */\n session!: ThinkSession;\n\n /**\n * The agent's Workspace, as in 0.24: a subclass may assign its own; by\n * default one on this Durable Object's storage, made at start.\n */\n workspace!: ThinkWorkspace;\n\n /** Offer the connected MCP servers' tools each turn, as in 0.24. */\n includeMcpTools = true;\n\n /** Wait for MCP connections before a turn's tools are built, as in 0.24. */\n waitForMcpConnections: boolean | { timeout: number } = false;\n\n /** WorkerLoader binding for sandboxed extensions, as in 0.24. */\n extensionLoader?: WorkerLoader;\n\n /** The sandboxed extensions, made at start when `extensionLoader` is set. */\n extensionManager?: ExtensionManager;\n\n /** Per-extension hook timeout in milliseconds, as in 0.24. */\n hookTimeout = 5000;\n\n /** Runs the sandboxed extensions' hooks of each turn, as 0.24 did. */\n readonly #extensionHooks = new ThinkExtensionHooks(\n () =>\n this.extensionManager &&\n this.extensionManager.coreFor(() => this.hookTimeout)\n );\n\n /** Think's opt-in fetch tools, as in 0.24: off unless set. */\n fetchTools: false | Omit<CreateFetchToolsOptions, \"workspace\" | \"onEvent\"> =\n false;\n\n /**\n * As in 0.24: the byte budget for the in-memory message view. A stored\n * transcript larger than this is hydrated as its most recent messages\n * that fit, and `chat:hydration:windowed` is emitted. Non-finite or\n * non-positive: always the whole transcript.\n *\n * @default 32 * 1024 * 1024\n */\n hydrationByteBudget: number = 32 * 1024 * 1024;\n\n /** The in-memory message view, bounded by `hydrationByteBudget`. */\n readonly #transcript = new ThinkTranscriptCache({\n budget: () => this.hydrationByteBudget,\n // As in 0.24, through the session `configureSession` returned, so an\n // app's wrapping of its reads applies; before it exists, the harness's.\n readAll: async () =>\n this.session\n ? ((await this.session.getHistory()) as UIMessage[])\n : this.harness.session().messages(),\n readRecent: async (budget) => {\n const recent = this.session\n ? await this.session.getRecentHistory(budget)\n : await (await this.#rootHandle()).getRecentHistory(budget);\n return { ...recent, messages: recent.messages as UIMessage[] };\n },\n emitWindowed: (payload) => this._emit(\"chat:hydration:windowed\", payload),\n // A refresh is where an eviction pass may become worth scheduling, as\n // in 0.24.\n refreshed: () => this.#mediaEviction.request()\n });\n\n /**\n * Evict aged media from the conversation, as in 0.24: the bytes go to\n * the Workspace and a marker stays in the message.\n */\n mediaEviction: MediaEvictionConfig | boolean = true;\n\n /** How many messages the media-eviction cutoff moves by at a time. */\n truncationStep = MODEL_TRUNCATION_STEP;\n\n /** Aged-media eviction passes: Think's capability, on this shell's view. */\n readonly #mediaEviction = new MediaEvictionPasses({\n config: () => resolveMediaEvictionConfig(this.mediaEviction),\n truncationStep: () => this.truncationStep,\n cachedMessages: () => this.#transcript.messages,\n agedRowsHiddenFromCache: () =>\n this.#transcript.lastHydration?.truncated === true ||\n this.#transcript.messages.some((message) =>\n isCompactionMessage(message as unknown as SessionMessage)\n ),\n storedBytes: () =>\n this.#transcript.lastHydration?.totalContentBytes ?? null,\n storedPathRows: (options) => this.session.internal_storedPathRows(options),\n readMessage: async (id) =>\n (await this.session.getMessage(id)) as unknown as UIMessage | null,\n openFiles: () => new WorkspaceFiles(this.workspace),\n // An update, never an insert, as in 0.24: a row a clear removed\n // during the pass stays removed.\n updateMessage: (message) =>\n this.session.updateMessage(message as unknown as SessionMessage),\n emitEvicted: (totals) =>\n (\n this._emit as unknown as (\n type: string,\n payload: Record<string, unknown>\n ) => void\n ).call(this, \"chat:media:evicted\", {\n ...totals,\n externalizedBytes: totals.bytes\n }),\n // A facet has no alarm of its own: its pass goes through the root's\n // queue, named by its path, as in 0.24.\n queueRouted: () =>\n this.queue(\"_cfEvictAgedMedia\", undefined, {\n id: `media-eviction:${JSON.stringify(this.selfPath)}`\n })\n });\n #context: Context | undefined;\n /** Ends the view's subscription to the root session's change feed. */\n #unsubscribeMirror: (() => void) | undefined;\n #handle: Session | undefined;\n /** Each submission's status reports, run one at a time in order. */\n readonly #submissionStatuses = new SubmissionStatusQueue();\n /** Skills from `getSkills()`, loaded in onStart as 0.24 loaded them. */\n readonly #skills = new ThinkSkills();\n /** Think's `think_config` rows, the table and migration Think has. */\n readonly #config = new ThinkConfigStore();\n #configCache: unknown = null;\n /** What `beforeTurn` returned for the running operation's turn. */\n #ownTurn:\n | {\n readonly operationId: string;\n readonly own: TurnConfig | void;\n /** When the turn's first model call was prepared (ms). */\n readonly startedAt: number;\n /** The default model, once a call of the turn resolved it. */\n defaultModel?: LanguageModel;\n /** The messages `beforeTurn` rewrote the turn's prompt to, if any. */\n messages?: TurnConfig[\"messages\"];\n /** How many parts of a continued reply the rewrite already had. */\n replyParts?: number;\n /** The calls of that reply that were still open at the rewrite. */\n openCalls?: Set<string>;\n /** Whether the turn continues a reply (its first call's value). */\n continuation?: boolean;\n /** The message the turn's history ends at. */\n readonly leafId?: string;\n /** The proactive compactions the turn tried (`contextOverflow`). */\n proactive?: number;\n /** The history a proactive compaction left, for the turn's later calls. */\n compactedHead?: UIMessage[];\n /** The turn's `stopWhen`, checked as each step ends. */\n stopWhen?: TurnConfig[\"stopWhen\"];\n /** The writer of the reply's finish metadata, and its last part. */\n finishWrite?: (part: unknown) => Record<string, unknown> | undefined;\n lastFinish?: unknown;\n /** Each step's usage and finish reason, for `stopWhen`. */\n stepMeta?: Array<{ usage?: LanguageModelUsage; finishReason?: string }>;\n /** The step whose server tools `stopWhen` waits on. */\n pendingStop?: {\n readonly step: number;\n readonly message: UIMessage;\n readonly segment: number;\n readonly waiting: Set<string>;\n readonly results: unknown[];\n };\n }\n | undefined;\n /**\n * What started each operation (Think's `TurnTrigger`) and its turn's\n * abort signal, by operation id, until it settles.\n */\n readonly #turns = new Map<string, { readonly trigger: TurnTrigger }>();\n /**\n * A signal for a resumed approval's grant, by operation, until the\n * operation settles: it fires if the operation ends unanswered.\n */\n readonly #grantSignals = new Map<string, AbortController>();\n\n async #grantSignal(operationId: string): Promise<AbortSignal> {\n const kept = this.#grantSignals.get(operationId);\n if (kept) return kept.signal;\n // An operation that already ended (stopped while the grant was being\n // prepared) gets a signal that says so, and nothing is kept for it.\n const status = await this.harness.session().inspect(operationId);\n if (status && status.status !== \"queued\" && status.status !== \"running\") {\n return stoppedStatus(status)\n ? AbortSignal.abort()\n : new AbortController().signal;\n }\n // A grant prepared beside this one while it waited keeps its signal:\n // one signal per operation, so a stop reaches both.\n const raced = this.#grantSignals.get(operationId);\n if (raced) return raced.signal;\n const controller = new AbortController();\n this.#grantSignals.set(operationId, controller);\n return controller.signal;\n }\n /**\n * A step that called tools, by operation, until its tools ran: at most\n * one per running operation, removed when it ends.\n */\n readonly #openSteps = new Map<string, OpenStep>();\n /**\n * The input the model gave each running tool call, by call id, from\n * `beforeToolCall` to `afterToolCall`, which removes it; what an\n * operation leaves goes when it settles.\n */\n readonly #modelInputs = new Map<\n string,\n {\n readonly operationId: string;\n readonly input: unknown;\n /** When the call was decided, for its duration. */\n started: number;\n }\n >();\n /** Builds string models through one cached default provider, as 0.24. */\n readonly #models = new ThinkModelResolver({\n binding: () => this.getAIBinding(),\n gateway: (model) => this.getGateway(model),\n sessionAffinity: () => this.sessionAffinity\n });\n /**\n * Render a reply attachment for delivery to the turn's channel, as on\n * Think: the text or markdown to post, or `undefined` to skip it (unknown\n * types, and types a channel handles itself, such as `voice_note`).\n */\n renderAttachment(\n attachment: ReplyAttachment\n ): string | { markdown: string } | undefined {\n return defaultAttachmentText(attachment);\n }\n\n /** The latest turn's reply attachments, as in 0.24. */\n readonly #replyAttachments = new ReplyAttachments();\n /** The action ledger's coalescing, as in 0.24. */\n readonly #effects = createEffectState();\n /** Each approval-gated action's summary, permissions and risk. */\n readonly #actionMetadata = new Map<string, CompiledActionMetadata>();\n /**\n * The descriptors of calls asked for approval since this isolate started.\n * After a restart a pending call's descriptor is computed again from its\n * action and input.\n */\n readonly #actionDescriptors = new Map<string, ActionApprovalDescriptor>();\n\n constructor(ctx: AgentContext, env: Env) {\n snapshotDeclaredMembers(new.target.prototype);\n super(ctx, env);\n registerDeliverySink(\n this.tasks,\n WORKFLOW_NOTIFICATION_SINK,\n workflowNotificationSink(\n (notification) =>\n this.sendWorkflowEvent(\n notification.workflowName as string & {},\n notification.workflowId,\n notification.event\n ),\n (error) => this.onError(error)\n )\n );\n registerEffectTask(this.tasks, this.#effects);\n // Decisions a released Think parked for durable-pause actions\n // (`actpause_…`) are carried forward: listed, and decided here (H11).\n registerDecisionTask(this.tasks, (runId) => this.#decisionReport(runId));\n const self = this;\n this.harness = new ThinkHarness({\n // The Agent's own Tasks, which Think's runs already use.\n tasks: this.tasks,\n // In Think's tool order: the workspace's tools, then fetch.\n extensions: [\n // Think waits for MCP connections at the top of a turn, before any\n // tool is built.\n {\n name: \"mcp-connections\",\n extension: mcpConnectionsExtension(\n () => this.mcp,\n () => this.waitForMcpConnections\n )\n },\n {\n name: \"workspace\",\n // Made here when first needed, as at start: Channels follows a\n // run cut off by a reset as it starts, before Think's onStart.\n extension: workspaceExtension(\n () =>\n (this.workspace ??= new Workspace({ storage: this.ctx.storage }))\n )\n },\n {\n name: \"fetch\",\n extension: fetchExtension(\n () => this.fetchTools,\n () => this.workspace,\n (event) =>\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 // The actions follow the agent's own tools, as in 0.24.\n {\n name: \"actions\",\n after: true,\n extension: actionsExtension(\n () => this.getActions(),\n this.#actionToolHost,\n this.#actionMetadata\n )\n },\n // The sandboxed extensions' tools follow the actions, as in\n // Think. Then skills, then MCP tools.\n {\n name: \"sandboxed\",\n after: true,\n extension: sandboxedExtensions(() => this.extensionManager)\n },\n {\n name: \"skills\",\n after: true,\n extension: skillsExtension(this.#skills, () =>\n this.getSkillScriptRunner()\n )\n },\n {\n name: \"mcp\",\n after: true,\n extension: mcpExtension({\n manager: () => this.mcp,\n include: () => this.includeMcpTools\n })\n },\n // A workflow turn's final-answer tool, last: its name is chosen\n // against every tool the turn offers, as in 0.24.\n {\n name: \"final-answer\",\n after: true,\n extension: (ctx) =>\n ctx.tools.transform((tools) => this.#addFinalAnswer(tools))\n }\n ],\n // Think's reserved keys, so client writes are stripped the same way.\n reservedMetadataKeys: [\"channel\", \"turnMetadata\"],\n // Think's own API writes and configures the Sessions handle directly.\n configureSession: (handle, id) => {\n if (id === this.harness.session().id) this.#handle = handle;\n },\n // The root session's blocks, built in onStart, as 0.24 built them.\n context: (_handle, id) =>\n id === this.harness.session().id ? this.#context : undefined,\n model: async () => this.resolveModel(await this.getModel()),\n // As in 0.24: an overridden getSystemPrompt() stays above the\n // context blocks; the default is only the fallback when the context\n // has no text, the skill catalog's and a prompt a release froze\n // included.\n system: async () => {\n if (isMethodOverridden(this, \"getSystemPrompt\")) {\n return this.getSystemPrompt();\n }\n if (this.#skills.loaded) return undefined;\n if (this.#context && this.#context.getBlocks().length > 0) {\n return undefined;\n }\n // From the window Think holds, not the whole path: a chat can be\n // too long to read root-first.\n const frozen =\n (await this.#context?.freezeSystemPrompt({\n messages: this.messages as SessionMessage[]\n })) ?? \"\";\n return frozen ? undefined : this.getSystemPrompt();\n },\n // As in 0.24: a tool a tab's turn runs sees that tab's connection.\n tools: async () => this.#withTurnConnection(await this.getTools()),\n // The harness cuts older messages as 0.24 did, by its step.\n truncationStep: () => this.truncationStep,\n // As in 0.24: an execution-outcome note is stored as a system\n // message and sent to the model as user context.\n providerMessage: toProviderSafeExecutionOutcomeMessage,\n // The replies a tab's request sent, for the reconciling of its list.\n // As in 0.24: traced out of the box, named by the class, the\n // instance and the Durable Object; payloads only when opted in.\n tracing: (call) => ({\n agentName: this.constructor.name,\n agentId: this.name,\n conversationId: this.ctx.id.toString(),\n ...(call !== undefined && {\n turn: turnTraceOf({\n requestId: call.operationId,\n // What admitted the turn, as its hooks are told.\n // A span opened before the turn's first hook (its setup) is\n // named as the turn will be: a tab's request, a submission.\n trigger:\n this.#turns.get(call.operationId)?.trigger ??\n (this.#webRequests.has(call.operationId)\n ? \"ws-chat\"\n : call.origin === \"submission\"\n ? \"submission\"\n : call.origin === \"tool-answer\" ||\n call.operationId.startsWith(DECISION_CONTINUE_PREFIX)\n ? \"auto-continuation\"\n : \"programmatic\"),\n // A tool's answer continues its turn on that turn's channel.\n ...(this.#turnChannel?.operationId === call.operationId &&\n this.#turnChannel.channelId !== undefined\n ? { channel: this.#turnChannel.channelId }\n : this.#webRequests.has(call.operationId)\n ? { channel: \"web\" }\n : (call.origin === \"tool-answer\" ||\n call.operationId.startsWith(DECISION_CONTINUE_PREFIX)) &&\n this.#lastTurnChannel !== undefined && {\n channel: this.#lastTurnChannel\n }),\n continuation: call.continuation,\n generation: this.#clears\n })\n }),\n storeMessages: this.storeMessages,\n storeTools: this.storeTools\n }),\n repliesSentWith: (operationId) => this.#repliesSent.get(operationId),\n hydrationByteBudget: () => this.hydrationByteBudget,\n // As in 0.24: a browser's new user message is stored with its\n // channel, which only the server sets.\n questionMetadata: (operationId) =>\n this.#webRequests.has(operationId) ? { channel: \"web\" } : undefined,\n approvalDescriptor: (toolCallId) =>\n this.#actionDescriptors.get(toolCallId),\n // An app's `repairInterruptedToolPart` decides, as in 0.24; its\n // `super` call answers what the harness would.\n repairInterruptedToolPart: (part, repaired, clientToolNames) => {\n this.#harnessRepair = { repaired, clientToolNames };\n try {\n return this.repairInterruptedToolPart(part);\n } finally {\n this.#harnessRepair = undefined;\n }\n },\n // A turn's `beforeTurn` may set its own, as in 0.24.\n get maxSteps() {\n return self.#turnMaxSteps ?? self.maxSteps;\n },\n // One submission's reports in order, as in 0.24.\n onSubmissionStatus: (status) =>\n this.#submissionStatuses.run(status.operationId, () =>\n this.#submissionStatus(status)\n ),\n // Think's `chatRecovery`, read when a run starts, as in 0.24.\n get recovery() {\n return self.#recoveryOptions();\n },\n hooks: {\n // As in 0.24: a workflow turn's final-answer tool is plumbing,\n // never stored. A reply that held only it is not stored at all.\n // As in 0.24: a structured workflow turn that ends without its\n // final-answer tool's answer fails.\n finishMetadata: ({ operationId }) => {\n const own = this.#ownTurn;\n if (own?.operationId !== operationId) return undefined;\n const part = own.lastFinish;\n own.lastFinish = undefined;\n return part === undefined ? undefined : own.finishWrite?.(part);\n },\n beforeTurnEnd: ({ operationId }) => {\n const final = this.#finalAnswer;\n if (final?.operationId === operationId && !final.output) {\n throw new Error(\n `Model ended the turn without calling the ${final.name} tool`\n );\n }\n // As in 0.24: an answer too large for the workflow's event\n // fails the submission, with the reason.\n if (\n final?.operationId === operationId &&\n final.output &&\n !submissionOutputFits(final.output.value)\n ) {\n throw new Error(submissionOutputTooLarge(final.output.value).error);\n }\n // Kept with the submission before the turn ends, as 0.24 kept\n // it with the outcome: a reset before the workflow is told must\n // not lose the answer.\n if (final?.operationId === operationId && final.output) {\n this.tasks.patchMetadata(operationId, SUBMISSION_PROGRESS_KEY, {\n output: final.output.value as TaskJson\n });\n }\n },\n storedReply: (stored) => {\n const message = this.#withPausedDescriptors(stored);\n const kept = withoutFinalAnswerParts(message);\n return kept === message ||\n kept.parts.some((part) => part.type !== \"step-start\")\n ? kept\n : { ...kept, parts: [] };\n },\n onRecovery: (context) => this.#onRecovery(context),\n onContextOverflow: ({ operationId, signal }) =>\n this.#onContextOverflow(operationId, signal),\n beforeTurn: (turn) => this.#beforeTurn(turn),\n beforeToolCall: async (call) => {\n // As in 0.24, the final-answer tool is plumbing: no hook sees it.\n if (this.#isFinalAnswer(call)) return undefined;\n // The step's chunks reach extensions before its tool calls do.\n await this.#chunkHooks;\n // A call approved after a restart runs before any model call of\n // its turn: the turn's grant is asked for here.\n await this.#authorizeTurn(call.operationId, async () => {\n // Asked for here, and only resolved when the grant reads it:\n // a failing `getModel()` fails that read, as in 0.24.\n let chosen: ThinkModel | undefined;\n let failure: unknown;\n try {\n chosen = await this.getModel();\n } catch (error) {\n failure = error;\n }\n let model: LanguageModel | undefined;\n const self = this;\n return {\n system: this.getSystemPrompt(),\n messages: await convertToModelMessages(this.messages, {\n ignoreIncompleteToolCalls: true\n }),\n tools: {},\n // Resolved only when read, as in 0.24.\n get model() {\n if (failure !== undefined) throw failure;\n return (model ??= self.resolveModel(chosen as ThinkModel));\n },\n continuation: true,\n requestId: call.operationId,\n // As 0.24's resuming turn: what started it (after a restart,\n // an approval's continuation), and a signal that fires if the\n // operation is stopped.\n trigger:\n this.#turns.get(call.operationId)?.trigger ??\n \"auto-continuation\",\n abortSignal: await this.#grantSignal(call.operationId)\n } as unknown as TurnContext;\n });\n const decision = await this.#beforeToolCall(call);\n // As in 0.24: an approved action runs with the input a human\n // approved, or not at all.\n if (\n decision?.action === \"run\" &&\n decision.input !== undefined &&\n this.#actionMetadata.has(call.toolName)\n ) {\n const approved = await this.#approvedInput(call.toolCallId);\n if (\n approved.found &&\n stableStringify(decision.input) !==\n stableStringify(approved.input)\n ) {\n return {\n action: \"substitute\",\n output: actionApprovalInputErrorEnvelope()\n };\n }\n }\n // As in 0.24: extensions hear of a call that runs, with the\n // input it runs with.\n if (!decision || decision.action === \"run\") {\n const input =\n decision?.action === \"run\" && decision.input !== undefined\n ? decision.input\n : call.input;\n await this.#extensionHooks.toolCallStart({\n // SAFETY: a snapshot reads the name, id and input only.\n toolCall: { ...call, input } as unknown as TypedToolCall<ToolSet>,\n stepNumber: undefined\n });\n // The call's time starts as it runs, after the extensions heard.\n const kept = this.#modelInputs.get(call.toolCallId);\n if (kept) {\n this.#modelInputs.set(call.toolCallId, {\n ...kept,\n started: Date.now()\n });\n }\n }\n return decision;\n },\n afterToolCall: async (result) => {\n if (this.#isFinalAnswer(result)) return;\n await this.#toolSettledForStop(result.operationId, {\n toolCallId: result.toolCallId,\n toolName: result.toolName,\n input: result.input,\n ok: result.ok,\n ...(result.ok && { output: result.output })\n });\n const kept = this.#modelInputs.get(result.toolCallId);\n // From the decision to run it to its result, as 0.24 timed\n // `execute`: not the approval before it or the hooks after.\n const toolExecutionMs = kept ? Date.now() - kept.started : 0;\n await this.#extensionHooks.toolCallFinish({\n // SAFETY: a snapshot reads the name, id and input only.\n toolCall: result as unknown as TypedToolCall<ToolSet>,\n stepNumber: undefined,\n durationMs: toolExecutionMs,\n success: result.ok,\n ...(result.ok\n ? { output: result.output }\n : { error: result.errorText })\n });\n const modelInput = kept ? kept.input : result.input;\n this.#modelInputs.delete(result.toolCallId);\n // What `execute` threw, in the isolate that ran it; a failure\n // read back after a restart has its text only.\n const error = result.ok\n ? undefined\n : \"error\" in result\n ? result.error\n : result.errorText;\n return this.afterToolCall({\n type: \"tool-call\",\n toolName: result.toolName,\n toolCallId: result.toolCallId,\n input: modelInput,\n stepNumber: result.step,\n messages: result.messages ?? [],\n requestId: result.operationId,\n toolExecutionMs,\n durationMs: toolExecutionMs,\n ...(result.ok\n ? {\n toolOutput: { type: \"tool-result\", output: result.output },\n success: true,\n output: result.output\n }\n : {\n toolOutput: { type: \"tool-error\", error },\n success: false,\n error\n })\n } as unknown as ToolCallResultContext);\n },\n onStepFinish: async ({\n message,\n finishReason,\n operationId,\n step,\n usage,\n record\n }) => {\n await this.#chunkHooks;\n // The step before this one ran its tools since: its results are\n // in this message now.\n await this.#endStep(operationId, message);\n const segment = stepSegments(message);\n const ended = {\n operationId,\n step,\n finishReason,\n segment,\n usage,\n record\n };\n await this.#stepEndedForStop(operationId, step, message, segment, {\n ...(usage && { usage }),\n ...(finishReason !== undefined && { finishReason })\n });\n\n // A step that called tools ends once they ran, as an AI SDK step\n // does: at the next step, or at the turn's end.\n if (stepResultOf(message, segment).toolCalls.length > 0) {\n this.#openSteps.set(operationId, ended);\n return;\n }\n await this.#stepEnded(ended, message);\n },\n onChunk: ({ chunk, operationId }) => {\n // The reply's `start` goes out when the model call starts, ahead\n // of anything the model streams: a call that fails after it has\n // still streamed nothing (its failure's stage is the turn's).\n if (chunk.type !== \"start\") this.#streamed.add(operationId);\n // It sends: a tab that connects now is offered the stream, not\n // told it is recovering.\n this.#recoveryAttempts.add(operationId);\n this.#noteLiveCall(operationId, chunk);\n // The AI SDK's stream part, which Think gives its extensions and\n // `onChunk` alike.\n const part = streamPartOf(chunk, this.#callsOf(operationId), (id) =>\n this.#storedCall(id)\n );\n this.#dispatchChunk(part);\n },\n onTurnEnd: async (end) => {\n // The decisions that waited for this turn's reply to be stored,\n // as their runs record it (durable): written one after another.\n this.#reportAwaitingDecisions(end.operationId);\n // Its recovering status ends with it, however it ended.\n await this.#endRecovering(end.operationId);\n // Its messenger context, for its response hook, taken first so it\n // is forgotten whichever way the hook ends. A turn that did not\n // run here (a terminal report replayed after a reset) reads it\n // from its user message as stored.\n const ranHere = this.#ranHere.delete(end.operationId);\n const kept = this.#responseContexts.get(end.operationId);\n this.#responseContexts.delete(end.operationId);\n const responding =\n kept ??\n (!ranHere && this.#messengers\n ? await this.#storedMessengerContext(\n end.message?.id ?? end.messageId\n )\n : undefined);\n // A turn no `chat()` caller waits on: an overflow it could not\n // recover reaches `onChatError` here, classified, as 0.24 reported\n // it for every turn. A stopped turn did not fail.\n const overflowReported =\n !this.#chatClears.has(end.operationId) &&\n this.#overflowed.delete(end.operationId) &&\n end.status === \"unanswered\" &&\n end.reason !== \"aborted\" &&\n end.reason !== \"withdrawn\";\n if (overflowReported) {\n try {\n this.onChatError(end.reason ?? \"Context window exceeded.\", {\n requestId: end.operationId,\n stage: \"stream\",\n messagesPersisted: true,\n classification: \"context_overflow\"\n });\n } catch (error) {\n console.error(\"[Think] onChatError threw\", error);\n }\n }\n // The extensions' chunk hooks finish inside the turn, as in 0.24.\n await this.#chunkHooks;\n const continued = this.#continued.get(end.operationId);\n this.#continued.delete(end.operationId);\n this.#newReplies.delete(end.operationId);\n this.#turnFinished(\n end.operationId,\n end.status === \"done\"\n ? \"completed\"\n : end.reason === \"aborted\" || end.reason === \"withdrawn\"\n ? \"aborted\"\n : \"error\"\n );\n const streamed = this.#streamed.delete(end.operationId);\n // What the model's call last threw goes with the turn; a `chat()`\n // caller still waiting drops it itself.\n const thrown = this.#thrown.get(end.operationId);\n if (!this.#chatClears.has(end.operationId)) {\n this.#thrown.delete(end.operationId);\n }\n this.#liveCalls.delete(end.operationId);\n this.#toolCalls.delete(end.operationId);\n const clearsAtStart = this.#clearsAtStart.get(end.operationId);\n this.#clearsAtStart.delete(end.operationId);\n // A clear that ran, or runs, while the turn was open.\n const clearedUnder =\n this.#clearing > 0 ||\n (clearsAtStart !== undefined && clearsAtStart !== this.#clears);\n if (end.message) await this.#endStep(end.operationId, end.message);\n else this.#openSteps.delete(end.operationId);\n // A turn that never ran has no response: one stopped while it\n // waited, or input the harness turned away before a model call (a\n // tool result no call waits for, an empty or unknown operation).\n const stoppedByCaller = this.#callerStops.delete(end.operationId);\n // As in 0.24, a turn the chat was cleared under, running or\n // waiting, gets no response hook. Its `chat()` caller is told of\n // the clear, unless it had stopped the turn itself first.\n if (\n end.status === \"unanswered\" &&\n (end.reason === \"aborted\" || end.reason === \"withdrawn\") &&\n clearedUnder\n ) {\n if (!stoppedByCaller && this.#chatClears.has(end.operationId)) {\n this.#chatClears.set(end.operationId, true);\n }\n return;\n }\n // A turn that wrote a message ran, whatever its reason's text.\n if (\n end.status === \"unanswered\" &&\n end.message === undefined &&\n end.reason !== undefined &&\n // A request a later one took the place of while it waited\n // (`messageConcurrency: \"latest\"`) never ran either.\n (NEVER_RAN.has(end.reason) || end.reason.startsWith(SUPERSEDED_BY))\n ) {\n return;\n }\n // A request stopped while it waited in the queue never ran: as on\n // Think it gets no response hook. Its run says so (the dispatch\n // marks it); read only for a stopped turn that wrote nothing and\n // never reached `beforeTurn`.\n if (\n end.status === \"unanswered\" &&\n end.reason === \"aborted\" &&\n end.message === undefined &&\n continued === undefined &&\n !streamed\n ) {\n const record = await this.harness.inspection(\n this.harness.session().id,\n end.operationId\n );\n const chat = record?.metadata?.chat as\n | { stopped?: unknown }\n | undefined;\n if (chat?.stopped === true) return;\n }\n if (end.status === \"unanswered\" && end.reason !== \"aborted\") {\n // As in 0.24, a failed turn is reported to observability: in its\n // stream once the model streamed (a message error too, as the\n // reply pump reports one), in the turn before that. Its messages\n // were placed once it reached `beforeTurn`.\n let error = saidOf(end) ?? \"unanswered\";\n const stage = streamed ? \"stream\" : \"turn\";\n // As in 0.24, the app's `onChatError` hears every failed turn\n // with the turn it failed in, a continuation's included, and\n // the event carries what it returned: a tab's turn, a\n // `saveMessages` turn and a `chat()` caller's alike (that\n // caller's callback is handed the same text). An overflow is\n // reported above, or by `chat()` with its classification.\n const forCaller = this.#chatClears.has(end.operationId);\n if (\n !overflowReported &&\n !(forCaller && this.#overflowed.has(end.operationId))\n ) {\n error = this.#reportChatError(\n end.operationId,\n error,\n {\n requestId: end.operationId,\n stage,\n messagesPersisted: continued !== undefined,\n ...(continued === true && { continuation: true })\n },\n thrown\n );\n // Kept only for a `chat()` caller that has yet to be told.\n if (!forCaller) this.#chatErrorTexts.delete(end.operationId);\n }\n if (!overflowReported && !forCaller) {\n // As in 0.24: a turn that failed before the model streamed\n // is reported through `onError` as well (its run failed).\n if (!streamed) {\n try {\n await this.onError(new Error(saidOf(end) ?? \"unanswered\"));\n } catch {\n // The default `onError` rethrows what it is given.\n }\n }\n }\n if (streamed) this._emit(\"message:error\", { error });\n this._emit(\"chat:request:failed\", {\n requestId: end.operationId,\n stage,\n messagesPersisted: continued !== undefined,\n error\n });\n }\n // As in 0.24, a turn the app declined to continue\n // (`onChatRecovery`) gets no response hook: the app ended it.\n if (\n end.status === \"unanswered\" &&\n end.reason === TURN_NOT_CONTINUED\n ) {\n return;\n }\n // As in 0.24: the turn's reply attachments go with its result,\n // and each one this agent can render is posted to the turn's\n // channel as an interim notice first.\n const attachments = this.replyAttachments(end.operationId);\n const turnChannel =\n this.#turnChannel?.operationId === end.operationId\n ? this.#turnChannel.channelId\n : undefined;\n // As in 0.24: a turn that ran on a channel says its final reply\n // was delivered, before its attachments and its response hook.\n if (turnChannel !== undefined) {\n (\n this._emit as unknown as (\n type: string,\n payload: Record<string, unknown>\n ) => void\n ).call(this, \"channel:delivered\", {\n channel: turnChannel,\n kind: \"final\",\n turnEnded: true\n });\n }\n this.#respondingContext = responding;\n await deliverReplyAttachments(\n attachments,\n (attachment) => this.renderAttachment(attachment),\n (rendered) =>\n this.deliverNotice(rendered, {\n kind: \"interim\",\n ...(turnChannel !== undefined && { channel: turnChannel }),\n ...(responding && { thread: responding.thread.id })\n })\n );\n this.#respondingContext = responding;\n // As in 0.24, the response hook runs inside the connection of\n // the tab the turn ran for (its request, or the tool answer that\n // continued it), when that tab is still there.\n const tab =\n end.origin === undefined\n ? undefined\n : this.getConnection(end.origin);\n const respond = (run: () => Promise<void>) =>\n tab\n ? agentContext.run(\n {\n agent: this,\n connection: tab,\n request: undefined,\n email: undefined\n },\n run\n )\n : run();\n try {\n await respond(async () =>\n this.onChatResponse({\n attachments,\n // As in 0.24, a turn that ended before it wrote anything still\n // reports, with an empty assistant message.\n message: end.message ?? {\n id: end.messageId ?? crypto.randomUUID(),\n role: \"assistant\",\n parts: []\n },\n requestId: end.operationId,\n // As `beforeTurn` saw it, if the turn got that far: from\n // this isolate, or from the turn's stored result when the\n // hook is called again after a reset.\n continuation: continued ?? end.continuation ?? false,\n status:\n end.status === \"done\"\n ? \"completed\"\n : end.reason === \"aborted\"\n ? \"aborted\"\n : \"error\",\n ...(end.status === \"unanswered\" &&\n end.reason !== undefined && { error: saidOf(end) }),\n // As in 0.24: a hook delivered after a restart for a turn\n // whose reply was stored before it (no model call here).\n ...(continued === undefined &&\n end.message !== undefined && { recovered: true })\n })\n );\n } finally {\n this.#respondingContext = undefined;\n }\n },\n classifyError: (error, context) =>\n this.#classify(error, context?.operationId)\n }\n });\n // Turns frame their replies to the tabs themselves (H2c): the harness\n // hands them this host from the start, so an RPC turn frames too.\n this.harness.chatDeps(\"\", this.#chatHostDeps());\n this.#chat = new ThinkChat({\n harness: this.harness,\n // Turns frame their own replies and the shared dispatch answers\n // resumes (H2c): ThinkChat keeps the transcript, clear and connect\n // frames.\n turnFrames: false,\n // As in 0.24, replayed only while no attempt sends: a tab that\n // connects during the recovered attempt's stream is offered it.\n recovering: async () => {\n const frame = await buildChatRecoveringFrame(\n this.ctx.storage,\n CHAT_RECOVERING_FRAME,\n Date.now()\n );\n return frame && this.#recoveryAttempts.has(String(frame.id))\n ? null\n : frame;\n },\n // What a tab is sent is this agent's view of the chat, as in 0.24:\n // the messages it holds in memory, bounded by `hydrationByteBudget`.\n // Re-read first when something other than a turn wrote.\n transcript: (reread) => this.#clientTranscript(reread),\n webSockets: {\n getConnections: () => this.getConnections(),\n use: (handlers) => {\n this.#handlers.push(handlers);\n }\n }\n });\n this.harness.observe((session, event) => {\n // A tool's progress, which the harness gives its observers: Think's\n // `onChunk` hears it as the AI SDK's preliminary tool-result.\n if (\n event.type === \"chunk\" &&\n event.chunk.type === \"tool-output-available\" &&\n event.chunk.preliminary\n ) {\n this.#dispatchChunk(\n streamPartOf(event.chunk, this.#callsOf(event.operationId), (id) =>\n this.#storedCall(id)\n )\n );\n }\n if (event.type === \"prefix-changed\") {\n this._emit(\"chat:prefix:changed\", {\n session,\n requestId: event.operationId,\n causes: event.causes\n });\n }\n if (event.type === \"run-end\") {\n this.#wakeStableWaiters();\n this.#running = undefined;\n this.#ownTurn = undefined;\n this.#actionTurn = undefined;\n this.#extensionTurn = undefined;\n this.#turnMaxSteps = undefined;\n }\n // A settled operation's turn is over: its signal fires if it was cut\n // short, and it is forgotten.\n if (\n event.type === \"operation\" &&\n (event.status.status === \"done\" || event.status.status === \"unanswered\")\n ) {\n this.#turns.delete(event.status.operationId);\n this.#singleTry.delete(event.status.operationId);\n this.#webRequests.delete(event.status.operationId);\n this.#repliesSent.delete(event.status.operationId);\n const grant = this.#grantSignals.get(event.status.operationId);\n if (grant) {\n // As 0.24's turn signal: it fires on a stop, not on a failure.\n if (stoppedStatus(event.status)) grant.abort();\n this.#grantSignals.delete(event.status.operationId);\n }\n this.#messengerContexts.delete(event.status.operationId);\n this.#explicitChannels.delete(event.status.operationId);\n // A call the operation left without an afterToolCall is forgotten.\n for (const [toolCallId, kept] of this.#modelInputs) {\n if (kept.operationId === event.status.operationId) {\n this.#modelInputs.delete(toolCallId);\n }\n }\n }\n });\n this.lifecycle.use(this.harness);\n this.lifecycle.use(this.#config);\n this.lifecycle.use(this.#mediaEviction);\n // `getMessengers()` and `configureChannels()` are the app's, and are\n // read where Think has always read them: at start, after the session,\n // the context and the transcript exist. Channels has to be installed\n // before startup locks the capabilities, so an empty slot is installed\n // at the beginning of startup (the root is not known before), with no\n // call into the app; start fills it.\n this.lifecycle.internal_beforeStartup(() => this.#reserveMessengerSlot());\n // TEMPORARY (the import): the recovered replies think@0.24.0 kept, on\n // the root and in any sub-agent, as 0.24 carried them. A sub-agent\n // posts through the agent that owns the messenger, as in 0.24.\n this.#releasedReplies = releasedReplies({\n tasks: this.tasks,\n storage: this.ctx.storage,\n post: async () => {\n const parent = this.parentPath.at(-1);\n const host = parent\n ? ((await this.parentAgent({\n name: parent.className\n } as unknown as SubAgentClass<Think>)) as unknown as Think)\n : this;\n return (input) => host._cf_deliverRecoveredMessengerReply(input);\n },\n takeUp: (data) => this.#takeUpReleasedRecovery(data)\n });\n const onStart = this.onStart.bind(this);\n // The start's steps as spans, under the names think 0.24 gave them: a\n // reader of a trace sees each step's storage work as one block.\n const startSpan = <T>(name: string, run: () => T): T =>\n this._withAgentSpan(\n name,\n \"startup\",\n { \"cloudflare.agents.component\": \"think\" },\n run\n );\n const startThink = async (props: Props | undefined) => {\n // What this start degrades is counted from its first step.\n this.#onStartDegradations = [];\n if (!this.workspace) {\n this.workspace = new Workspace({ storage: this.ctx.storage });\n }\n const context = await startSpan(\"initialize_think_session\", async () => {\n const handle = await this.#rootHandle();\n this.session = await this.configureSession(\n new ThinkSession(handle, () => this.context)\n );\n const sessionId = this.session.sessionId;\n this.#context = new Context(handle, {\n blocks: [\n ...(await this.configureContext()),\n ...this.session.internal_takePendingContext()\n ],\n sql: this,\n // As in 0.24: the prompt a release froze (a custom store, or the\n // `_system_prompt` row) is read, never written, so the turns sent\n // before the upgrade are sent it.\n promptStore:\n this.session.internal_promptStore() ??\n new AgentContextProvider(\n this,\n sessionId ? `_system_prompt_${sessionId}` : \"_system_prompt\"\n )\n });\n await this.#context.load();\n // TEMPORARY: remove in the next minor. The recovered replies\n // think@0.24.0 kept, delivered as deliveries: on the root, and in any\n // sub-agent, where 0.24 kept them by default.\n await this.#bestEffortStartStep(\n \"durable-work-recovery\",\n () => this.#importReleasedReplies(),\n \"Messenger replies an earlier version kept were not carried \" +\n \"forward on this wake; the next successful wake will carry them.\"\n );\n // As in 0.24: the catalog is a block of the app's context from\n // the start, so `this.context` shows it before any turn has run.\n await this.#skills.initialize(() => this.getSkills(), this.#context);\n return this.#context;\n });\n this.harness.observe((session, event) => {\n if (session !== this.harness.session().id) return;\n if (event.type === \"reset\") {\n this.#transcript.replace([]);\n this.#lastTurnChannel = undefined;\n }\n // A message is applied by the root session's change feed below,\n // which knows an append from an update, as in 0.24.\n if (event.type === \"message\") this.#wakeStableWaiters();\n // A reset, a delete or a compaction reaches the view through the\n // change feed too (clear, delete, compaction): it re-reads there.\n if (event.type === \"reset\" || event.type === \"transcript\") {\n this.#wakeStableWaiters();\n }\n });\n // As in 0.24, the view follows the root session's own change feed:\n // every write, the harness's and one made straight to the session (an\n // app's, or a late tool result on an older reply), reaches it and\n // media eviction, told apart as an append or an update.\n this.#unsubscribeMirror?.();\n this.#unsubscribeMirror = (await this.#rootHandle()).mirror<UIMessage>({\n get: () => this.#transcript.messages,\n set: (messages) => this.#transcript.replace(messages),\n transform: (message) => message as unknown as UIMessage,\n intercept: async (event) => {\n switch (event.type) {\n case \"append\":\n // An append under the view's tail extends it in place; a\n // branch append moves the path, which a patch cannot express.\n if (\n !event.inserted ||\n event.parentId === undefined ||\n event.parentId ===\n (this.#transcript.messages.at(-1)?.id ?? null)\n ) {\n return false;\n }\n // A branch under a message the view holds (a regenerated\n // reply under its question), when the view is the whole\n // active path: the new path is the view up to that message,\n // then the new one. Cut here, and the append extends it in\n // place: the stored path is not read again.\n {\n const view = this.#transcript.messages;\n const at = view.findIndex(\n (message) => message.id === event.parentId\n );\n if (this.#transcript.coversActivePath && at >= 0) {\n this.#transcript.replace(view.slice(0, at + 1));\n return false;\n }\n }\n await this.#transcript.sync();\n return true;\n case \"update\":\n // An update to a row the view does not hold (an older reply a\n // late tool result lands on) may have put media on a row\n // media eviction already examined.\n if (\n !this.#transcript.messages.some(\n (message) => message.id === event.message.id\n )\n ) {\n this.#mediaEviction.rowChangedOutsideCache();\n }\n return false;\n case \"import\":\n this.#transcript.markStale();\n return true;\n case \"clear\":\n this.#transcript.replace([]);\n this.#transcript.coversActivePath = true;\n return true;\n // think@0.24.0 also refreshed its context's prompt on a\n // compaction; the harness's step loop owns the context and\n // records the change itself.\n case \"delete\":\n case \"compaction\":\n case \"compact\":\n await this.#transcript.sync();\n this.#wakeStableWaiters();\n return true;\n default:\n return false;\n }\n },\n onApplied: (event, message, previous) => {\n if (event.type === \"update\") {\n // A row that grew may now hold media the cursor has passed; a\n // pass's own rewrites shrink rows and leave it alone.\n // Charged against the budget as 0.24 charged it.\n const grew = previous\n ? cachedMessageBytes(message) - cachedMessageBytes(previous)\n : 0;\n if (grew > 0) {\n this.#transcript.noteGrowth(grew);\n this.#mediaEviction.invalidate();\n }\n return;\n }\n // A budgeted refresh charges each message an overhead on top of\n // its bytes, so growth is charged the same way.\n this.#transcript.noteGrowth(\n cachedMessageBytes(message) + HYDRATION_MESSAGE_OVERHEAD_BYTES\n );\n this.#mediaEviction.noteAppend();\n }\n });\n // As in 0.24: a transcript that cannot be read must not stop the\n // agent from starting; it starts with an empty view.\n // The list just read IS the stored chat when the read was the whole\n // path and nothing else touched the chat while it was read (a turn\n // recovered during the start): the chat module may then take it for\n // the stored chat without reading that again.\n const heldTrust = this.harness.heldTrust();\n const heldEpoch = heldTrust.epoch;\n const hydrated = await startSpan(\"hydrate_think_session\", () =>\n this.#bestEffortStartStep(\n \"transcript-hydration\",\n () => this.#sync(),\n \"The agent is starting with an empty in-memory message view; \" +\n \"persisted history is untouched.\"\n )\n );\n if (!hydrated) {\n // The view is empty, not the stored path: a read can have covered\n // the path and the step still fail (what follows the read threw),\n // so the view is marked stale; a turn then reads the stored chat.\n this.#transcript.replace([]);\n this.#transcript.markStale();\n }\n if (\n hydrated &&\n this.#transcript.coversActivePath &&\n heldTrust.epoch === heldEpoch\n ) {\n heldTrust.trusted = true;\n }\n // As in 0.24: the app's extensions load once the transcript is read\n // (after its skills), so `getExtensions()` sees the conversation.\n if (this.extensionLoader) {\n this.extensionManager = createThinkExtensionManager({\n loader: this.extensionLoader,\n storage: this.ctx.storage,\n agentClassName: this.constructor.name,\n agentId: this.ctx.id.toString(),\n agentPath: this.selfPath,\n rootJurisdiction: this._cf_rootJurisdictionOptions()?.jurisdiction,\n exports: (\n this.ctx as unknown as { exports?: Record<string, unknown> }\n ).exports\n });\n await loadThinkExtensions(\n this.extensionManager,\n this.getExtensions(),\n context\n );\n }\n // As in 0.24: the channels and messengers, read once, on the root,\n // after the session, the context blocks and the transcript: an\n // override may read any of them.\n if (this.parentPath.length === 0) {\n const resolved = resolveChannels(\n await this.configureChannels(),\n this.getMessengers() as ThinkMessengers\n );\n this.#channels = resolved.channels;\n const slot = this.#messengerSlot;\n if (slot && slot.ids.length === 0) {\n await slot.fill(resolved.messengers as ThinkMessengers);\n }\n this.#messengers = slot && slot.ids.length > 0 ? slot : undefined;\n }\n startSpan(\"initialize_think_chat\", () => this.#installProtocol());\n // What a release left, carried before the app's onStart (it may read a\n // submission): the request context; the submissions, a running one\n // with its own turn's run; the chat turns left; the agent-tool runs,\n // whose running ones end here (nothing of this version owns them).\n await this.#bestEffortStartStep(\n \"durable-work-recovery\",\n () => this.#carryReleasedLastTerminal(),\n \"The end of the last failed turn an earlier version kept was not \" +\n \"carried forward on this wake; the next successful wake will carry it.\"\n );\n await this.#bestEffortStartStep(\n \"durable-work-recovery\",\n () => this.#carryReleasedRequestContext(),\n \"The request context an earlier version stored was not carried \" +\n \"forward on this wake; the next successful wake will carry it.\"\n );\n // A reply the release was in the middle of comes first: it holds\n // the lane, and the submissions queued behind it follow it, as they\n // did on the release. A running submission's own turn is carried\n // with its submission.\n let withSubmissions = false;\n await this.#bestEffortStartStep(\n \"durable-work-recovery\",\n async () => {\n withSubmissions = await this.#carryReleasedChatTurns(\"unowned\");\n await this.#carryReleasedFiberTurnsAhead();\n },\n \"Chat turns an earlier version was running were not carried \" +\n \"forward on this wake; the next successful wake will carry them.\"\n );\n await this.#bestEffortStartStep(\n \"durable-work-recovery\",\n () => this.#carryReleasedSubmissions(),\n \"Submissions an earlier version stored were not carried forward on \" +\n \"this wake; the next successful wake will carry them.\"\n );\n if (withSubmissions) {\n // A turn whose submission was not moved is carried on its own.\n await this.#bestEffortStartStep(\n \"durable-work-recovery\",\n () => this.#carryReleasedChatTurns(\"all\"),\n \"Chat turns an earlier version was running were not carried \" +\n \"forward on this wake; the next successful wake will carry them.\"\n );\n }\n await this.#bestEffortStartStep(\n \"durable-work-recovery\",\n () => this.#fireReleasedOwedHooks(),\n \"Response hooks an earlier version left owed were not fired on \" +\n \"this wake; the next successful wake will fire them.\"\n );\n await this.#bestEffortStartStep(\n \"durable-work-recovery\",\n () => this.#carryReleasedAgentToolRuns(),\n \"Agent-tool runs an earlier version stored were not carried forward \" +\n \"on this wake; the next successful wake will carry them.\"\n );\n // The approvals 0.24 had parked came over in the migration as\n // decisions due at once: each parks now, before `onStart`, so the\n // app's own start sees them as 0.24's did.\n await this.#bestEffortStartStep(\n \"durable-work-recovery\",\n async () => {\n if (!this._releaseRanSince) return;\n // A row that could not become a run is still in 0.24's table:\n // the next start tries it again.\n if (releasedActionsLeft(this.ctx.storage.sql)) {\n this._releaseCarryNotDone();\n }\n await this.tasks.runDue(DECISION_TASK);\n },\n \"Approvals an earlier version parked were not parked again.\"\n );\n await onStart(props);\n await startSpan(\"recover_think_durable_work\", async () => {\n await this.#runOwedHooksAfterStart();\n // Best-effort, as in 0.24: a getScheduledTasks() that throws must\n // not stop the agent from starting.\n // As 0.24 did at the next interaction: the durable pauses a release\n // had resolved but not yet written into the transcript.\n await this.#bestEffortStartStep(\n \"durable-work-recovery\",\n () => this.#writeReleasedResolvedPauses(),\n \"Resolved durable pauses an earlier version kept were not written.\"\n );\n // Decisions a reset left waiting for their parking reply: that turn\n // is recovered or gone now, so each is reported again.\n this.#reportAwaitingDecisions();\n // As in 0.24: expired action ledger rows are deleted at start.\n try {\n await this.#sweepActionLedger();\n } catch (error) {\n console.error(\"[Think] The action ledger was not swept\", error);\n }\n });\n await startSpan(\"reconcile_think_schedules\", () =>\n this.#bestEffortStartStep(\n \"scheduled-task-reconcile\",\n () => this.internal_reconcileScheduledTasks(),\n \"Declared scheduled tasks were not reconciled on this wake; the \" +\n \"next successful wake will reconcile them.\"\n )\n );\n };\n this.onStart = (props?: Props) =>\n this._withAgentSpan(\n \"think_start\",\n \"startup\",\n { \"cloudflare.agents.component\": \"think\" },\n async (update) => {\n await startThink(props);\n // As 0.24 reported it: what the transcript's read hydrated, and\n // how many start steps were degraded.\n const hydration = this.#transcript.lastHydration;\n update({\n ...(hydration && {\n \"cloudflare.agents.hydration.messages\":\n hydration.hydratedMessages,\n \"cloudflare.agents.hydration.content_bytes\":\n hydration.totalContentBytes,\n \"cloudflare.agents.hydration.truncated\": hydration.truncated\n }),\n \"cloudflare.agents.start.degradations\":\n this.#onStartDegradations.length\n });\n }\n );\n }\n\n /**\n * The chat turns a release was running when the upgrade came: each is a\n * Tasks run under the release's definition, with what the turn stashed in\n * storage under its run id. Each becomes this harness's operation, cut\n * off, so it is recovered as any interrupted turn is: `onChatRecovery` is\n * asked, with the stash, and the question is answered. The release's run\n * and stash go.\n */\n /**\n * @param which - \"unowned\": every turn but a running submission's (that\n * one is carried with its submission). \"all\": what is left.\n * @returns Whether a turn was left for its submission.\n */\n async #carryReleasedChatTurns(which: \"unowned\" | \"all\"): Promise<boolean> {\n const runs = this.#releasedChatTurns();\n if (runs.length === 0) return false;\n const owned =\n which === \"unowned\"\n ? (this.#releasedRunningSubmissionRequests() ?? new Set<string>())\n : new Set<string>();\n let left = false;\n for (const run of runs) {\n const requestId = this.#releasedRequestOf(run);\n if (requestId !== undefined && owned.has(requestId)) {\n left = true;\n continue;\n }\n if (requestId !== undefined) {\n await this.#importReleasedTurn(requestId, {\n persisted: await this.ctx.storage.get(\n `__cf_chat_turn_snapshot:${run.runId}`\n ),\n createdAt: run.createdAt,\n ...(run.startedAt !== undefined && { startedAt: run.startedAt }),\n finished: () => this.#dropReleasedChatTurn(run)\n });\n }\n await this.#dropReleasedChatTurn(run);\n }\n return left;\n }\n\n /**\n * A turn the release kept as a fiber (a sub-agent's shape) is taken up\n * when its fiber is recovered, after this start. With submissions queued\n * behind it that is too late: they would run first. So it is carried\n * here, ahead of them, and its fiber finds it carried. A running\n * submission's own turn goes with its submission.\n */\n async #carryReleasedFiberTurnsAhead(): Promise<void> {\n // Only when the release ran since the last carry: its kept rows are\n // not a reason to look for its fibers at every start.\n if (!this._releaseRanSince) return;\n const sql = this.ctx.storage.sql;\n if (\n !tableExists(sql, \"cf_think_submissions\") ||\n sql.exec(\"SELECT 1 FROM cf_think_submissions LIMIT 1\").toArray()\n .length === 0\n ) {\n return;\n }\n const owned = this.#releasedRunningSubmissionRequests() ?? new Set();\n const prefix = `${RELEASED_CHAT_TURN_DEFINITION}:`;\n // Still in the release's own fiber table (this start's carry of that\n // table comes later), or already carried as a fiber run.\n const fibers = new Map<string, { persisted: unknown; createdAt: number }>();\n for (const fiber of legacyOpenFibers(this.ctx.storage, prefix)) {\n fibers.set(fiber.name, {\n persisted: fiber.snapshot,\n createdAt: fiber.createdAt\n });\n }\n for (const record of this.tasks.peekList({\n definition: FIBER_TASK,\n status: [\"pending\", \"running\"]\n })) {\n const name = this.tasks.inputOf<{ name?: unknown }>(record.runId)?.name;\n if (typeof name !== \"string\" || !name.startsWith(prefix)) continue;\n fibers.set(name, {\n persisted: this.tasks.checkpointOf(record.runId, \"snapshot\"),\n createdAt: record.createdAt\n });\n }\n for (const [name, fiber] of fibers) {\n const requestId = name.slice(prefix.length);\n if (owned.has(requestId)) continue;\n const operationId = await this.#importReleasedTurn(requestId, fiber);\n // Its fiber is told, durably, what became of the turn: the operation\n // it went on as, or that it was already finished (its reply stored,\n // only its response hook owed). Either way the fiber, recovered\n // later, has nothing more to do.\n this.ctx.storage.kv.put(\n RELEASED_FIBER_SUBMISSION_PREFIX + requestId,\n operationId ?? RELEASED_FIBER_TURN_FINISHED\n );\n }\n }\n\n /**\n * A chat turn a release ran as a fiber (think@0.24.0 in a sub-agent, and\n * older releases everywhere), carried forward as a fiber run: recovered\n * like its Tasks run would be. Every other fiber is the app's.\n * @internal\n */\n protected override async _handleInternalFiberRecovery(\n ctx: FiberRecoveryContext\n ): Promise<boolean> {\n const prefix = `${RELEASED_CHAT_TURN_DEFINITION}:`;\n if (!ctx.name.startsWith(prefix)) return false;\n const requestId = ctx.name.slice(prefix.length);\n // A submission's turn was carried with its submission at start, as\n // that submission's operation, with what this fiber stashed: the fiber\n // has nothing more to give.\n const kv = this.ctx.storage.kv;\n const carried = RELEASED_FIBER_SUBMISSION_PREFIX + requestId;\n const submissionId = kv.get<string>(carried);\n if (submissionId !== undefined) kv.delete(carried);\n // The note is written before the submission's operation: when that\n // import failed there is no operation, and the turn is carried here.\n if (\n submissionId !== RELEASED_FIBER_TURN_FINISHED &&\n (submissionId === undefined ||\n !(await this.harness.inspection(\n this.harness.session().id,\n submissionId\n )))\n ) {\n await this.#importReleasedTurn(requestId, {\n persisted: ctx.snapshot,\n createdAt: ctx.createdAt\n });\n }\n // An agent-tool run that waited for this turn is the turn's run now:\n // what its row held goes onto it, and the row goes.\n await this.#carryReleasedAgentToolRuns();\n return true;\n }\n\n /**\n * A release's open chat turn becomes this version's, cut off, under the\n * id its tab knows it by: its frames, and its end, name that request.\n */\n async #importReleasedTurn(\n requestId: string,\n turn: {\n persisted: unknown;\n createdAt: number;\n startedAt?: number;\n /** Drops the release's run of a turn that turns out to be finished. */\n finished?: () => Promise<void>;\n }\n ): Promise<string | undefined> {\n if (await this.#settleReleasedTurn(requestId, turn.finished)) {\n return undefined;\n }\n const session = this.harness.session().id;\n // The turn of an agent-tool run the release left open carries on as\n // that run's turn, so its parent still gets its result.\n const toolRun = releasedAgentToolRunOfRequest(\n this.ctx.storage.sql,\n RELEASED_THINK_AGENT_TOOL_TABLES.runs,\n requestId\n );\n const { user } = unwrapChatFiberSnapshot(\n \"__cfThinkChatFiberSnapshot\",\n turn.persisted\n );\n const operationId = toolRun ? agentToolTurnId(toolRun.runId) : requestId;\n await this.#storeReleasedPartial(requestId, operationId);\n await this.harness.importInterruptedTurn(session, {\n operationId,\n ...(user !== null && { stash: user as TaskJson }),\n createdAt: turn.createdAt,\n ...(turn.startedAt !== undefined && { startedAt: turn.startedAt }),\n dispatched: toolRun\n ? {\n metadata: {\n agentTool: {\n runId: toolRun.runId,\n startMessageId: null,\n ...(toolRun.terminalOnly && { terminalOnly: true })\n },\n // Its reply's stream is kept for its parent, as every\n // agent-tool turn's is.\n chat: { keepStream: true }\n }\n }\n : {}\n });\n if (toolRun) this.#turns.set(operationId, { trigger: \"agent-tool\" });\n return operationId;\n }\n\n /**\n * What a release's turn had streamed when the upgrade cut it off is\n * stored as its reply, as the release stores a stream that lost its\n * producer: the carried turn then continues that reply, so nothing a tab\n * was shown is lost. The release's stream is closed.\n */\n async #storeReleasedPartial(\n requestId: string,\n operationId: string\n ): Promise<void> {\n const released = new ReplyStreams({\n streamStarted: () => {},\n streamEnded: () => {},\n originMessageIds: () => undefined,\n transaction: (fn) => this.ctx.storage.transactionSync(fn)\n });\n released.open(\n this.streams,\n this.sql.bind(this),\n () => this.parentPath.length > 0\n );\n // The release streamed its replies into the default Streams tables;\n // this version's are the harness's own. Its stream is moved over first.\n await this.harness.adoptStreamTagged(requestId);\n const stream = released.latestStreamInfoForRequest(requestId);\n if (!stream || (stream.status !== \"streaming\" && !stream.cutOff)) return;\n const handle = await this.#rootHandle();\n const stored = await released.persistOrphan(stream.id, {\n store: {\n getMessage: async (id) =>\n ((await handle.getMessage(id)) as UIMessage | null) ?? null,\n appendMessage: async (message, parentId) => {\n await handle.appendMessage(message as never, {\n ...(parentId !== undefined && { parentId })\n });\n },\n updateMessage: async (message) => {\n await handle.upsertMessage(message as never);\n }\n },\n // The carried turn settles what the reply left open, as any\n // interrupted turn's recovery does.\n settle: (message) => message\n });\n released.complete(stream.id);\n // The app's `onChatRecovery` is told what was streamed, as the release\n // told it. In memory: the recovery runs in this isolate, right after.\n const reply = stored ? await handle.getMessage(stored) : null;\n if (reply) {\n this.#releasedPartials.set(operationId, reply as unknown as UIMessage);\n }\n }\n\n /**\n * The reply each carried turn's release had streamed, as stored, until\n * its recovery.\n */\n readonly #releasedPartials = new Map<string, UIMessage>();\n\n /**\n * A release's turn that had stored its reply and was cut off in its\n * response hook is finished: the release kept the hook it owed under a\n * key, with the reply's id. Nothing is asked of the model again. The hook\n * runs, marked recovered, as the release runs it, and then the key goes.\n *\n * `finish` writes that the turn is over (its run dropped, its submission\n * settled) BEFORE the hook runs: a reset while the hook runs then finds a\n * finished turn, never one to answer again. The hook itself is delivered\n * at least once, as on the release: cut off, it is owed still.\n */\n async #settleReleasedTurn(\n requestId: string,\n finish?: (\n messageId: string,\n /** How the release recorded the turn's end, with its hook owed. */\n ended: { status: \"completed\" | \"error\" | \"aborted\"; error?: string }\n ) => Promise<void>\n ): Promise<string | undefined> {\n // One settling per request in an isolate: the key goes only after the\n // hook returned, so a second reader that finds it while the hook is\n // still owed or running joins that one and does not start it again.\n const settling = this.#settlingReleasedTurns.get(requestId);\n if (settling) return settling;\n const settled = this.#settleReleasedTurnOnce(requestId, finish);\n this.#settlingReleasedTurns.set(requestId, settled);\n // Nothing to settle (no key, or its reply is not stored): the request\n // is free for its recovery.\n const free = () => this.#settlingReleasedTurns.delete(requestId);\n void settled.then((messageId) => {\n if (messageId === undefined) free();\n }, free);\n return settled;\n }\n\n readonly #settlingReleasedTurns = new Map<\n string,\n Promise<string | undefined>\n >();\n\n /** Whether the app's `onStart` has run in this isolate. */\n #appStarted = false;\n\n /** The owed hooks found before the app's `onStart` ran, in order. */\n readonly #owedHooksAfterStart: Array<() => Promise<void>> = [];\n\n /**\n * Run the hooks a release left owed that were found while this agent was\n * still starting. think@0.24.0 replays them after the app's `onStart`, so\n * a hook finds what `onStart` set up.\n */\n async #runOwedHooksAfterStart(): Promise<void> {\n this.#appStarted = true;\n for (const run of this.#owedHooksAfterStart.splice(0)) {\n try {\n await run();\n } catch (error) {\n console.error(\n \"[Think] A response hook a released version left owed was not settled\",\n error\n );\n }\n }\n }\n\n async #settleReleasedTurnOnce(\n requestId: string,\n finish?: (\n messageId: string,\n ended: { status: \"completed\" | \"error\" | \"aborted\"; error?: string }\n ) => Promise<void>\n ): Promise<string | undefined> {\n const key = RELEASED_OWED_RESPONSE_HOOK_PREFIX + requestId;\n const owed = await this.ctx.storage.get<{\n messageId?: string;\n continuation?: boolean;\n status?: \"completed\" | \"error\" | \"aborted\";\n error?: string;\n }>(key);\n if (!owed?.messageId) return undefined;\n const message = await (await this.#rootHandle()).getMessage(owed.messageId);\n if (!message) return undefined;\n await finish?.(owed.messageId, {\n status: owed.status ?? \"completed\",\n ...(owed.error !== undefined && { error: owed.error })\n });\n const run = async () => {\n try {\n await this.onChatResponse({\n // After a restart the turn's attachments are gone, as on the\n // release.\n attachments: [],\n message: message as UIMessage,\n requestId,\n continuation: owed.continuation === true,\n status: owed.status ?? \"completed\",\n ...(owed.error !== undefined && { error: owed.error }),\n recovered: true\n });\n } catch (error) {\n // As think@0.24.0: a hook that throws is reported here and not run\n // again on every wake.\n console.error(\"[Think] onChatResponse error:\", error);\n }\n try {\n await this.ctx.storage.delete(key);\n } finally {\n this.#settlingReleasedTurns.delete(requestId);\n }\n };\n // The turn is finished from here. Its hook runs after the app's\n // `onStart`, as on the release: at once when the agent has started,\n // else when its start gets there.\n if (this.#appStarted) await run();\n else this.#owedHooksAfterStart.push(run);\n return owed.messageId;\n }\n\n /**\n * The response hooks a release left owed for turns that have no run\n * left (the reply was stored and the isolate went before the hook\n * returned): each is fired once, and its key dropped. A turn that still\n * has a run or a fiber to recover is settled by that recovery, which\n * reads the key itself. One prefix read per start, as in 0.24.\n */\n async #fireReleasedOwedHooks(): Promise<void> {\n const owed = await this.ctx.storage.list({\n prefix: RELEASED_OWED_RESPONSE_HOOK_PREFIX\n });\n if (owed.size === 0) return;\n for (const key of owed.keys()) {\n const requestId = key.slice(RELEASED_OWED_RESPONSE_HOOK_PREFIX.length);\n const recovering = this.tasks.peekList({\n definition: FIBER_TASK,\n status: [\"pending\", \"running\"],\n input: { name: `${RELEASED_CHAT_TURN_DEFINITION}:${requestId}` },\n limit: 1\n });\n if (recovering.length > 0) continue;\n // Still open as an operation under that request: its own end runs\n // the hook, once. The key goes, or a later start would run it again.\n const carried = await this.harness.session().inspect(requestId);\n if (carried?.status === \"queued\" || carried?.status === \"running\") {\n await this.ctx.storage.delete(key);\n continue;\n }\n // A key whose reply is not stored reports nothing, and goes.\n if ((await this.#settleReleasedTurn(requestId)) === undefined) {\n await this.ctx.storage.delete(key);\n }\n }\n }\n\n /** The chat-turn runs a release left open. */\n #releasedChatTurns() {\n return this.tasks.peekList({\n definition: RELEASED_CHAT_TURN_DEFINITION,\n status: [\"pending\", \"running\"]\n });\n }\n\n /** The request a release's chat-turn run answers. */\n #releasedRequestOf(run: { readonly runId: string }): string | undefined {\n const requestId = this.tasks.inputOf<{ requestId?: unknown }>(\n run.runId\n )?.requestId;\n return typeof requestId === \"string\" ? requestId : undefined;\n }\n\n /** What a release's chat turn had stashed, from its snapshot. */\n async #releasedStashOf(run: {\n readonly runId: string;\n }): Promise<{ stash?: TaskJson }> {\n const { user } = unwrapChatFiberSnapshot(\n \"__cfThinkChatFiberSnapshot\",\n await this.ctx.storage.get(`__cf_chat_turn_snapshot:${run.runId}`)\n );\n return user !== null ? { stash: user as TaskJson } : {};\n }\n\n /** The operation holds the turn now: the release's run must not run. */\n async #dropReleasedChatTurn(run: { readonly runId: string }): Promise<void> {\n await this.tasks.cancel(run.runId, \"carried forward\");\n this.tasks.deleteRun(run.runId);\n await this.ctx.storage.delete(`__cf_chat_turn_snapshot:${run.runId}`);\n }\n\n /**\n * A Think from an earlier release kept the end of its last failed turn\n * under one key, for a tab that was away. Carried once into the chat's\n * record of its last requests' ends, which a tab's resume reads.\n */\n #carryReleasedLastTerminal(): void {\n const kv = this.ctx.storage.kv;\n const last = kv.get<ChatTerminalRecord>(CHAT_LAST_TERMINAL_KEY);\n if (last === undefined) return;\n recordRecentChatTerminal(kv, {\n id: last.requestId,\n body: last.body,\n done: true,\n error: true,\n ...(last.messageIds && { messageIds: last.messageIds })\n });\n kv.delete(CHAT_LAST_TERMINAL_KEY);\n }\n\n /**\n * A Think from an earlier release kept the last request's client tools\n * and body in `think_config` (`lastClientTools`, `lastBody`): moved\n * once into the session's request context, which turns read, and the\n * two keys deleted. A start that could not move them leaves them for\n * the next. One over the row budget is not kept.\n */\n async #carryReleasedRequestContext(): Promise<void> {\n // Only that release writes these keys, and it leaves its mark when it\n // starts: an object it has not run on since has nothing to carry.\n if (!this._releaseRanSince) return;\n const lastClientTools = this.#config.get(\"lastClientTools\");\n const lastBody = this.#config.get(\"lastBody\");\n if (lastClientTools === undefined && lastBody === undefined) return;\n const handle = await this.#rootHandle();\n // A request this version took since is the chat's newest: the\n // release's older values are not written over it (an earlier start\n // that could not move them left them here).\n if ((await handle.internal_config(CHAT_REQUEST_CONTEXT_KEY)) === null) {\n const context = requestContextFromLegacy(lastClientTools, lastBody);\n const storable = storableRequestContext(context);\n await handle.internal_setConfig(CHAT_REQUEST_CONTEXT_KEY, storable);\n // Too large to store: this isolate still runs with it, as 0.24\n // kept what it read in memory.\n if (storable === null && context !== null) {\n this.harness.keepRequestContext(this.harness.session().id, context);\n }\n }\n this.#config.delete(\"lastClientTools\");\n this.#config.delete(\"lastBody\");\n }\n\n /**\n * A tab cleared the chat before a start could move the request context\n * an earlier release kept: it goes with the chat, so the next start\n * does not bring it back.\n */\n #clearReleasedRequestContext(): void {\n if (!this._releaseRanSince) return;\n // Read first: a key that is not there is not deleted (no statement\n // with nothing to remove).\n for (const key of [\"lastClientTools\", \"lastBody\"] as const) {\n if (this.#config.get(key) !== undefined) this.#config.delete(key);\n }\n }\n\n /**\n * Move the submissions a release kept in `cf_think_submissions` into the\n * harness's runs, once, each row deleted as it is moved and the table\n * removed after the last: a pending one runs in its\n * turn, a settled one keeps its status, key, metadata and times. One the\n * release left running is recovered with its turn when the turn's run is\n * there (`#carryReleasedChatTurns`); with none, it is asked again from its\n * question when its messages were not applied yet, and ends interrupted\n * when they were, as 0.24 ended a submission whose turn it could not\n * recover. The item the release queued to run each one goes with it.\n */\n async #carryReleasedSubmissions(): Promise<void> {\n // Read only when the release ran since the last carry.\n if (!this._releaseRanSince) return;\n const rows = this.#releasedSubmissionRows();\n if (rows === undefined || rows.length === 0) return;\n // The running one first: it holds the lane, and the pending ones follow.\n rows.sort(\n (a, b) => Number(b.status === \"running\") - Number(a.status === \"running\")\n );\n const session = this.harness.session().id;\n // The turn a running submission was in, by its request.\n const turns = new Map(\n this.#releasedChatTurns().map((run) => [\n this.#releasedRequestOf(run),\n run\n ])\n );\n let failed = 0;\n for (const row of rows) {\n try {\n // A start that carries again (a reset cut the one before, between\n // a submission's import and its row's removal) meets one it\n // carried. Such a submission is left as it is here; what the release left\n // to run it (its queue item, its turn) goes: it is not a second\n // run.\n if (\n (await this.harness.inspection(session, row.submission_id)) !==\n undefined\n ) {\n await this.#dropReleasedSubmission(row.submission_id);\n if (row.status === \"running\" && row.request_id !== null) {\n const releasedTurn = turns.get(row.request_id);\n if (releasedTurn) {\n await this.#dropReleasedChatTurn(releasedTurn);\n } else if (this.#releasedFiberTurnWaits(row.request_id)) {\n this.ctx.storage.kv.put(\n RELEASED_FIBER_SUBMISSION_PREFIX + row.request_id,\n row.submission_id\n );\n }\n }\n continue;\n }\n const turn =\n row.status === \"running\" && row.request_id !== null\n ? turns.get(row.request_id)\n : undefined;\n // What a run cannot hold of the release's metadata is dropped\n // field by field, as 0.24's own move of these rows did.\n const metadata = legacySubmissionAppMetadata(row);\n const submission = {\n ...(row.idempotency_key !== null && {\n idempotencyKey: row.idempotency_key\n }),\n ...(Object.keys(metadata).length > 0 && { metadata })\n };\n // Its turn is a fiber the release left (a sub-agent's shape), taken\n // up after this start: the submission carries on as that turn, as\n // with a Tasks run, and the fiber finds it carried.\n const fiber =\n !turn &&\n row.status === \"running\" &&\n row.request_id !== null &&\n this.#releasedFiberTurnWaits(row.request_id);\n // Its reply was stored and only its response hook was owed: the\n // hook runs, marked recovered, and the submission is done with that\n // reply. Nothing is asked of the model.\n const turnRequest = row.request_id;\n const replied =\n (turn || fiber) && turnRequest !== null\n ? await this.#settleReleasedTurn(\n turnRequest,\n async (messageId, ended) => {\n const messages: unknown = JSON.parse(row.messages_json);\n // The structured answer the release kept with its row when\n // the turn ended goes with the submission, for the\n // workflow that waits for it.\n const answer =\n ended.status === \"completed\"\n ? legacySubmissionAnswer(row, metadata)\n : undefined;\n await this.harness.importSubmission(session, {\n operationId: row.submission_id,\n // As the release's turn ended: a reply stored with the\n // turn's error (what it had streamed before the model\n // failed) is a failed submission, not an answered one.\n state:\n ended.status === \"completed\"\n ? \"done\"\n : ended.status === \"error\"\n ? \"failed\"\n : \"aborted\",\n ...(ended.status === \"error\" &&\n ended.error !== undefined && { reason: ended.error }),\n messages: Array.isArray(messages)\n ? (messages as UIMessage[])\n : [],\n ...submission,\n ...(answer !== undefined && {\n metadata: {\n ...metadata,\n [SUBMISSION_PROGRESS_KEY]: { output: answer }\n }\n }),\n createdAt: row.created_at,\n ...(row.started_at !== null && {\n startedAt: row.started_at\n }),\n settledAt: Date.now(),\n messageId\n });\n if (turn) await this.#dropReleasedChatTurn(turn);\n // Its fiber, taken up after this start, finds it carried.\n if (fiber) {\n this.ctx.storage.kv.put(\n RELEASED_FIBER_SUBMISSION_PREFIX + turnRequest,\n row.submission_id\n );\n }\n await this.#dropReleasedSubmission(row.submission_id);\n }\n )\n : undefined;\n if (replied !== undefined) {\n // Its end is reported once, as 0.24 reported the end of a\n // submission whose turn it had finished: the events, the\n // workflow that waits for it (with the answer), the app's hook.\n // After the app's `onStart`, and after the turn's owed response\n // hook, as that hook is: the app's status hook finds what\n // `onStart` set up.\n const report = async () => {\n const ended = await this.harness.inspection(\n session,\n row.submission_id\n );\n if (ended) await this.#submissionStatus(ended);\n };\n if (this.#appStarted) await report();\n else this.#owedHooksAfterStart.push(report);\n continue;\n }\n if (fiber && row.request_id !== null) {\n // The fiber is named by the turn's request, which the release's\n // own recovery may have renamed since the submission began: it\n // is told, durably, that its turn went on as this submission.\n this.ctx.storage.kv.put(\n RELEASED_FIBER_SUBMISSION_PREFIX + row.request_id,\n row.submission_id\n );\n const { user } = unwrapChatFiberSnapshot(\n \"__cfThinkChatFiberSnapshot\",\n this.#releasedFiberSnapshot(row.request_id)\n );\n // What the release had streamed is kept (its stream is tagged\n // with the turn's request).\n await this.#storeReleasedPartial(row.request_id, row.submission_id);\n await this.harness.importInterruptedTurn(session, {\n operationId: row.submission_id,\n // What the turn stashed for its recovery, from the fiber.\n ...(user !== null && { stash: user as TaskJson }),\n createdAt: row.created_at,\n ...(row.started_at !== null && { startedAt: row.started_at }),\n submission\n });\n await this.#dropReleasedSubmission(row.submission_id);\n continue;\n }\n if (turn) {\n // Its turn was running: the submission is recovered with it, and\n // what it had streamed is kept.\n await this.#storeReleasedPartial(\n row.request_id ?? row.submission_id,\n row.submission_id\n );\n await this.harness.importInterruptedTurn(session, {\n operationId: row.submission_id,\n ...(await this.#releasedStashOf(turn)),\n createdAt: row.created_at,\n ...(row.started_at !== null && { startedAt: row.started_at }),\n submission\n });\n await this.#dropReleasedChatTurn(turn);\n await this.#dropReleasedSubmission(row.submission_id);\n continue;\n }\n // Messages that do not parse: a submission still to run fails, as\n // it did in 0.24 when its turn came; a settled one keeps its end.\n let messages: unknown;\n try {\n messages = JSON.parse(row.messages_json);\n } catch {\n messages = undefined;\n }\n // A running row the release had not marked applied may still have\n // stored its messages (it stopped between the two writes). As the\n // release decided it: with any of them in the conversation the\n // submission is not run again.\n let stored = 0;\n const own = Array.isArray(messages) ? (messages as UIMessage[]) : [];\n if (row.status === \"running\" && row.messages_applied_at === null) {\n const handle = await this.#rootHandle();\n for (const message of own) {\n if (await handle.getMessage(message.id)) stored++;\n }\n }\n const applied = row.messages_applied_at !== null || stored > 0;\n const state =\n row.status === \"completed\"\n ? \"done\"\n : row.status === \"pending\" || (row.status === \"running\" && !applied)\n ? \"queued\"\n : row.status === \"error\" || row.status === \"running\"\n ? \"failed\"\n : \"aborted\";\n const broken = !Array.isArray(messages) && state === \"queued\";\n await this.harness.importSubmission(session, {\n operationId: row.submission_id,\n state: broken ? \"failed\" : state,\n messages: Array.isArray(messages) ? (messages as UIMessage[]) : [],\n ...submission,\n createdAt: row.created_at,\n ...(row.started_at !== null && { startedAt: row.started_at }),\n ...(row.completed_at !== null && { settledAt: row.completed_at }),\n ...(broken\n ? { reason: SUBMISSION_MESSAGES_INVALID }\n : row.status === \"running\"\n ? {\n reason:\n stored > 0 && stored < own.length\n ? SUBMISSION_PARTLY_APPLIED\n : SUBMISSION_INTERRUPTED\n }\n : row.status === \"skipped\"\n ? { reason: SKIPPED_BY_RESET }\n : row.error_message !== null && { reason: row.error_message }),\n ...(row.message_id != null && { messageId: row.message_id })\n });\n // A submission the upgrade itself ends (its turn is gone, or its\n // messages do not parse) is reported as 0.24 reported the end it\n // gives one at start: the events, the workflow, the app's hook.\n if ((broken || state === \"failed\") && row.status !== \"error\") {\n const ended = await this.harness.inspection(\n session,\n row.submission_id\n );\n if (ended) await this.#submissionStatus(ended);\n }\n } catch (error) {\n // Left in the old table for the next start; the rest still move.\n failed++;\n console.error(\n `[Think] Submission ${row.submission_id} was not moved`,\n error\n );\n continue;\n }\n await this.#dropReleasedSubmission(row.submission_id);\n }\n if (failed > 0) {\n console.error(`[Think] ${failed} submissions stay for the next start`);\n this._releaseCarryNotDone();\n return;\n }\n // Every row is a submission here: the release's table goes.\n removeEmptiedSubmissionsTable(this.ctx.storage);\n }\n\n /**\n * A queue item or schedule think 0.24 left to run a submission names\n * this method. This version's carrier runs that submission itself\n * (`#carryReleasedSubmissions`), so the item has nothing to do: it is\n * taken and removed. Without the method the queue would log a callback\n * that is not there, once per item; in a sub-agent the item is held by\n * its root, where the migration's steps of this class do not run.\n * @internal Queue and schedule callback.\n */\n async _cfRunSubmission(): Promise<void> {}\n\n /**\n * A queue item or scheduled retry of a workflow notification from the\n * released version, which names this method: sent as a delivery, which\n * retries on its own.\n * @internal Queue and schedule callback.\n */\n async _cfDeliverWorkflowNotification(\n payload: Parameters<typeof legacyWorkflowNotification>[0]\n ): Promise<void> {\n const { id, notification, resume } = legacyWorkflowNotification(payload);\n await sendDelivery(\n this.tasks,\n WORKFLOW_NOTIFICATION_SINK,\n id,\n notification,\n resume\n );\n }\n\n /** A carried submission's row goes, with the queue item that ran it. */\n async #dropReleasedSubmission(submissionId: string): Promise<void> {\n // Moved: its row goes from the release's table. A start that carries\n // again (a reset cut this one) no longer meets it.\n this.ctx.storage.sql.exec(\n \"DELETE FROM cf_think_submissions WHERE submission_id = ?\",\n submissionId\n );\n // The item the release queued to run it, where the migration's step\n // did not take it (an object migrated before that step existed).\n await this.dequeue(`submission:${submissionId}`);\n }\n\n /**\n * The requests of the submissions a release left running: their ids\n * alone, not the rows' messages. None when no table.\n */\n #releasedRunningSubmissionRequests(): Set<string> | undefined {\n const sql = this.ctx.storage.sql;\n if (!tableExists(sql, \"cf_think_submissions\")) return undefined;\n return new Set(\n sql\n .exec<{ request_id: string }>(\n `SELECT request_id FROM cf_think_submissions\n WHERE status = 'running' AND request_id IS NOT NULL`\n )\n .toArray()\n .map((row) => row.request_id)\n );\n }\n\n /** The submissions a release kept, oldest first; none when no table. */\n #releasedSubmissionRows(): LegacySubmissionRow[] | undefined {\n const sql = this.ctx.storage.sql;\n if (!tableExists(sql, \"cf_think_submissions\")) return undefined;\n return sql\n .exec(\n \"SELECT * FROM cf_think_submissions ORDER BY created_at ASC, submission_id ASC\"\n )\n .toArray() as unknown as LegacySubmissionRow[];\n }\n\n #onStartDegradations: OnStartDegradation[] = [];\n\n /**\n * The onStart steps that failed on this wake and were skipped so the\n * agent could still come up, as in 0.24. Empty when the start was clean.\n */\n getOnStartDegradations(): ReadonlyArray<OnStartDegradation> {\n return [...this.#onStartDegradations];\n }\n\n /**\n * Run an onStart step whose failure must not stop the agent starting:\n * record it, report it, and go on, as 0.24 did. `true` when it ran.\n */\n async #bestEffortStartStep(\n step: OnStartDegradation[\"step\"],\n fn: () => unknown,\n hint: string\n ): Promise<boolean> {\n try {\n await fn();\n return true;\n } catch (error) {\n // What a release left may not be carried yet: the next start tries.\n if (step === \"durable-work-recovery\") this._releaseCarryNotDone();\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 /**\n * @internal Think's steps of the one migration of what think@0.24.0\n * stored, run in the Agent's constructor: they read nothing of the\n * instance but whether it is a sub-agent.\n */\n protected override _releaseMigrationSteps(): readonly ((storage: {\n readonly sql: SqlStorage;\n readonly kv: SyncKvStorage;\n }) => void)[] {\n const steps = [\n releasedActionsMigration(importTaskRun),\n migrateReleasedSubmissions,\n migrateReleasedChatProgress\n ];\n // The release's ended streams move into the harness's own tables at a\n // root only. A sub-agent's stay in the release's tables and are moved\n // over one at a time, when a carried turn asks for one.\n return storedAsFacet(this.ctx.storage.kv)\n ? steps\n : [...steps, moveReleaseStreams(\"@think-harness\")];\n }\n\n // ── Overridable configuration ─────────────────────────────────────\n\n getModel(): ThinkModel {\n throw new Error(\n \"Override getModel() to return a model id string (e.g. \" +\n '\"@cf/deepseek-ai/deepseek-v4.1-flash-1017\" or \"openai/gpt-5.5\") or a LanguageModel.'\n );\n }\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 getGateway(_model: string): GatewayOptions | undefined {\n return undefined;\n }\n\n /**\n * Resolve a model value into a concrete AI SDK `LanguageModel`, as on\n * Think: with no argument, the one `getModel()` returns.\n */\n resolveModel(model: ThinkModel = this.getModel()): LanguageModel {\n return this.#models.resolve(model);\n }\n\n getSystemPrompt(): string {\n return DEFAULT_SYSTEM_PROMPT;\n }\n\n getTools(): ToolSet {\n return {};\n }\n\n configureSession(\n session: ThinkSession\n ): ThinkSession | Promise<ThinkSession> {\n return session;\n }\n\n /**\n * Persist a JSON-serializable configuration for this agent, as in 0.24:\n * private to the server, kept across restarts.\n */\n configure<T = Record<string, unknown>>(config: T): void {\n this.#config.set(\"_think_config\", JSON.stringify(config));\n this.#configCache = config;\n }\n\n /** The configuration stored by {@link configure}, or null, as in 0.24. */\n getConfig<T = Record<string, unknown>>(): T | null {\n if (this.#configCache !== null) return this.#configCache as T;\n const raw = this.#config.get(\"_think_config\");\n if (raw === undefined) return null;\n this.#configCache = JSON.parse(raw);\n return this.#configCache as T;\n }\n\n /** The skill sources, as in 0.24: none unless overridden. */\n getSkills(): SkillSource[] | Promise<SkillSource[]> {\n return [];\n }\n\n /** A runner for `run_skill_script`, as in 0.24: none unless overridden. */\n getSkillScriptRunner(): SkillScriptRunner | null {\n return null;\n }\n\n /** Declare the prompt context blocks, as in 0.24. */\n configureContext(): ContextConfig[] | Promise<ContextConfig[]> {\n return [];\n }\n\n /** The root session's context blocks. Available once started. */\n protected get context(): Context {\n if (!this.#context) {\n throw new Error(\n \"Context is not initialized yet; it is available after onStart().\"\n );\n }\n return this.#context;\n }\n\n // Overrides an app may define, as on think@0.24.0: each returns the\n // released empty default.\n /**\n * Sandboxed extensions to load at start, in order, as in 0.24. Needs\n * `extensionLoader`.\n */\n getExtensions(): ExtensionConfig[] {\n return [];\n }\n getActions(): Record<string, Action> | Promise<Record<string, Action>> {\n return {};\n }\n\n /**\n * Authorize action permissions for the current turn, as in 0.24.\n * Returning `true` grants all of them; `grantedPermissions` limits the\n * default `authorizeAction` to that set.\n */\n authorizeTurn(\n _ctx: TurnContext\n ): ActionAuthorizationDecision | Promise<ActionAuthorizationDecision> {\n return true;\n }\n\n /**\n * Authorize a single action call, as in 0.24. The default enforces the\n * grant `authorizeTurn` returned for the turn.\n */\n authorizeAction(\n ctx: ActionAuthorizationContext\n ): ActionAuthorizationDecision | Promise<ActionAuthorizationDecision> {\n const turn = this.#actionTurn?.authorization ?? { allowed: true };\n if (!turn.allowed) return { allowed: false, reason: turn.reason };\n if (turn.grantedPermissions === undefined) return true;\n const granted = new Set(turn.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 * The running operation and what `authorizeTurn` granted it. Set before\n * its first model call, or, for a call approved after a restart, before\n * that call runs.\n */\n #actionTurn:\n | { operationId: string; authorization: NormalizedActionAuthorization }\n | undefined;\n\n async #authorizeTurn(\n operationId: string,\n context: () => Promise<TurnContext>\n ): Promise<void> {\n if (this.#actionTurn?.operationId === operationId) return;\n this.#replyAttachments.begin(operationId);\n this.#actionTurn = {\n operationId,\n authorization: normalizeActionAuthorization(\n await this.authorizeTurn(await context())\n )\n };\n }\n\n /**\n * As in 0.24: how long settled and pending action ledger rows are kept.\n * Deleting a row ends the idempotency guarantee for its key.\n */\n actionLedgerRetention: {\n settledMs: number | false;\n pendingMs: number | false;\n maxSweepRows: number;\n } = {\n settledMs: 30 * 24 * 60 * 60 * 1000,\n pendingMs: 90 * 24 * 60 * 60 * 1000,\n maxSweepRows: 500\n };\n\n async #sweepActionLedger(): Promise<void> {\n const now = Date.now();\n const retention = this.actionLedgerRetention;\n const swept = await sweepEffects(this.tasks, {\n settledBefore:\n retention.settledMs === false ? null : now - retention.settledMs,\n pendingBefore:\n retention.pendingMs === false ? null : now - retention.pendingMs,\n limit: Math.max(0, Math.floor(retention.maxSweepRows))\n });\n (\n this._emit as unknown as (\n type: string,\n payload: Record<string, unknown>\n ) => void\n ).call(this, \"action:ledger:swept\", { ...swept });\n const ttl = this.actionPendingApprovalTtlMs;\n const decisions =\n ttl === false ? 0 : await sweepDecisions(this.tasks, now - ttl, 500);\n if (decisions > 0) {\n (\n this._emit as unknown as (\n type: string,\n payload: Record<string, unknown>\n ) => void\n ).call(this, \"action:pause:swept\", { swept: decisions });\n }\n }\n\n /**\n * As in 0.24: how long a parked durable pause waits for its decision.\n * Older ones are dropped at start; `false` keeps them.\n */\n actionPendingApprovalTtlMs: number | false = 30 * 24 * 60 * 60 * 1000;\n\n /** As in 0.24: how long a stale claim of a keyed action is held. */\n actionLedgerPendingRetryLeaseMs: number | false = 5 * 60 * 1000;\n\n /** What the actions call on this agent. */\n readonly #actionToolHost: ActionToolHost = {\n agent: this,\n insideTurn: (run) => this.#insideTurn(run),\n env: () => this.env as Cloudflare.Env,\n requestId: () => this.#actionTurn?.operationId ?? \"\",\n // An approved call runs without asking again: the harness decides that\n // from its answered approval.\n isApproved: () => false,\n grantedPermissions: () =>\n this.#actionTurn?.authorization.grantedPermissions,\n authorizeAction: (ctx) => this.authorizeAction(ctx),\n recordApprovalDescriptor: (toolCallId, descriptor) =>\n this.#actionDescriptors.set(toolCallId, descriptor),\n // The stored call was a durable pause, approved before this run: the\n // kind it was asked as (its stored tool metadata: an action whose\n // approval is not an AI SDK approval gate), not what the action is now.\n ranAfterApproval: async (toolCallId) => {\n // Only the latest stored reply can hold the call this run answers: the\n // run continues it. One message is read, not the transcript, and a\n // call there counts only while it waits for this run (approved, no\n // output yet): a new call that reused an older call's id is not\n // stored yet, and the older call already has its output.\n const leaf = (await (await this.#rootHandle()).getLatestLeaf()) as\n | { role?: string; parts?: unknown[] }\n | null\n | undefined;\n if (leaf?.role !== \"assistant\") return false;\n return (leaf.parts ?? []).some((part) => {\n const record = part as {\n toolCallId?: unknown;\n state?: unknown;\n toolMetadata?: {\n cfThinkAction?: unknown;\n cfThinkActionApprovalConfigured?: unknown;\n };\n approval?: { approved?: unknown };\n };\n return (\n record.toolCallId === toolCallId &&\n record.state === \"approval-responded\" &&\n record.approval?.approved === true &&\n record.toolMetadata?.cfThinkAction === true &&\n record.toolMetadata.cfThinkActionApprovalConfigured === false\n );\n });\n },\n recordReplyAttachment: (requestId, attachment, actionName) => {\n const attachmentType = this.#replyAttachments.record(\n requestId,\n attachment\n );\n if (attachmentType === undefined) return;\n (\n this._emit as unknown as (\n type: string,\n payload: Record<string, unknown>\n ) => void\n ).call(this, \"action:reply-attached\", {\n action: actionName,\n attachmentType\n });\n },\n // As in 0.24: a durable-pause action parks into a decision run and the\n // turn goes on with the paused placeholder; approve or reject it later.\n parkDurablePause: async ({\n toolName,\n input,\n ctx,\n summary,\n permissions,\n risk\n }) => {\n const executionId = `actpause_${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.#pausedDescriptors.set(executionId, descriptor);\n await parkDecision(this.tasks, {\n id: executionId,\n input: {\n kind: \"action\",\n action: toolName,\n toolCallId: ctx.toolCallId,\n requestId: ctx.requestId || null,\n input: input as TaskJson\n },\n descriptor: descriptor as unknown as TaskJson\n });\n (\n this._emit as unknown as (\n type: string,\n payload: Record<string, unknown>\n ) => void\n ).call(this, \"action:pause:created\", {\n action: toolName,\n executionId,\n 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 runLedgered: (args) =>\n runLedgeredAction(\n {\n tasks: this.tasks,\n effects: this.#effects,\n pendingRetryLeaseMs: this.actionLedgerPendingRetryLeaseMs,\n emit: (event) =>\n (\n this._emit as unknown as (\n type: string,\n payload: Record<string, unknown>\n ) => void\n ).call(this, event.type, event.payload),\n attachments: {\n count: () => this.#replyAttachments.count(),\n truncate: (n) => this.#replyAttachments.truncate(n)\n }\n },\n args\n )\n };\n\n /**\n * Advisory reply attachments the latest turn's actions recorded through\n * `ctx.attachReply`, as in 0.24: with a `requestId`, only if they belong\n * to that turn.\n */\n replyAttachments(requestId?: string): ReplyAttachment[] {\n return this.#replyAttachments.list(requestId);\n }\n\n /**\n * Everything awaiting human approval: the action calls of the latest reply\n * that wait for a decision, each with its descriptor. Resolve one with\n * `approveExecution` or `rejectExecution`, by its `executionId`.\n */\n async pendingApprovals(executionId?: string): Promise<PendingApproval[]> {\n const actions = await this.getActions();\n if (this.#actionMetadata.size === 0) {\n // A fresh isolate: compile the actions once for their metadata.\n compileActionTools(actions, this.#actionToolHost, this.#actionMetadata);\n }\n const out: PendingApproval[] = [];\n // A released Think's parked durable-pause decisions, with the\n // descriptor it kept for each.\n for (const record of pendingDecisions(this.tasks)) {\n const id = decisionIdOf(record.runId);\n if (executionId !== undefined && id !== executionId) continue;\n const descriptor = record.metadata?.descriptor;\n if (descriptor === undefined) continue;\n out.push({\n executionId: id,\n source: \"action\",\n descriptor: descriptor as unknown as PendingApproval[\"descriptor\"]\n });\n }\n for (const call of await this.harness.pendingApprovals(\n this.harness.session().id\n )) {\n if (executionId !== undefined && call.approvalId !== executionId) {\n continue;\n }\n const metadata = this.#actionMetadata.get(call.toolName);\n if (!metadata) {\n // No action of that name is offered now (it was removed, or a\n // fresh isolate never compiled it): the stored call still names\n // its action through the descriptor it was asked with, so it stays\n // listed and its approval is answered, as in 0.24.\n const stored = await this.#storedActionDescriptor(call.approvalId);\n if (stored) {\n out.push({\n executionId: call.approvalId,\n source: \"action\",\n descriptor: stored\n });\n }\n continue;\n }\n out.push({\n executionId: call.approvalId,\n source: \"action\",\n // After a restart the stored call still carries the descriptor it\n // was asked with, which names the request that asked.\n descriptor: this.#actionDescriptors.get(call.toolCallId) ??\n (await this.#storedActionDescriptor(call.approvalId)) ?? {\n requestId: \"\",\n toolCallId: call.toolCallId,\n action: metadata.actionName,\n summary: metadata.summary,\n input: call.input,\n // Computed again from the input, as when the call was asked.\n permissions:\n metadata.permissions !== undefined\n ? [...metadata.permissions]\n : await resolveActionPermissions(\n Object.entries(actions).find(\n ([key, action]) =>\n (action.config.name ?? key) === call.toolName\n )?.[1].config.permissions as\n | ActionPermissionSpec<unknown>\n | undefined,\n call.input,\n {\n agent: this,\n env: this.env as Cloudflare.Env,\n requestId: \"\",\n toolCallId: call.toolCallId,\n messages: [],\n signal: new AbortController().signal,\n attachReply: () => {}\n }\n ),\n ...(metadata.risk !== undefined && { risk: metadata.risk }),\n kind: metadata.kind\n }\n });\n }\n // The execute tool's paused executions, one card each, as in 0.24:\n // named after the first call that waits, then enriched by the agent.\n const runtime = await this.#codemodeRuntime();\n if (runtime) {\n const pending = await runtime.pending(executionId);\n const messages = await this.harness.session().messages();\n for (const id of new Set(pending.map((call) => call.executionId))) {\n const group = pending.filter((call) => call.executionId === id);\n const first = group[0];\n let toolCallId = \"\";\n for (const message of messages) {\n const found = executionToolCallIn(message, id, false);\n if (found !== null) toolCallId = found;\n }\n const label = `${first.connector}.${first.method}`;\n out.push({\n executionId: id,\n source: \"codemode\",\n descriptor: {\n action: label,\n summary: label,\n input: first.args,\n permissions: [],\n kind: \"durable-pause\",\n ...this.describePausedExecution(group, {\n requestId: \"\",\n toolCallId\n }),\n // The card's identity is not the agent's to change.\n requestId: \"\",\n toolCallId\n }\n });\n }\n }\n return out;\n }\n\n /**\n * Enrich the approval descriptor shown for a paused `execute` execution.\n * The default is derived from the first pending call as\n * `connector.method` with its args as the input; return a summary, the\n * permissions it consumes or a risk level to merge over it. Not called\n * for durable-pause actions, which carry their own descriptor.\n */\n describePausedExecution(\n _pending: PendingAction[],\n _ctx: { requestId: string; toolCallId: string }\n ): Partial<ActionApprovalDescriptor> | undefined {\n return undefined;\n }\n\n /** Publish a durable pause's decision (`action:pause:approved` / `rejected`). */\n #emitPauseDecided(\n type: \"action:pause:approved\" | \"action:pause:rejected\",\n action: string,\n executionId: string\n ): void {\n (\n this._emit as unknown as (\n type: string,\n payload: Record<string, unknown>\n ) => void\n ).call(this, type, { action, executionId });\n }\n\n /**\n * A released decision's verdict arrived: run the approved action (or\n * build the rejection), write its outcome into the paused tool call the\n * released reply holds, where the caller reads it.\n */\n async #onReleasedDecisionSettled(\n runId: string,\n /** The turn that just ended and so no longer writes its reply. */\n ended?: string\n ): Promise<void> {\n const input = this.tasks.inputOf<{\n kind: string;\n action: string;\n toolCallId: string;\n input: unknown;\n }>(runId);\n const record = this.tasks.peek(runId);\n if (!input || !record) return;\n if (input.kind === \"codemode\") {\n // An execution its runtime decided: only the outcome is written.\n const decided = this.tasks.inputOf<{\n executionId: string;\n verdict: DecisionVerdict;\n output: unknown;\n }>(runId);\n if (decided) {\n await this.#applyExecutionOutcome(\n decided.executionId,\n decided.output,\n decided.verdict\n );\n }\n this.tasks.deleteRun(runId);\n return;\n }\n if (input.kind !== \"action\") return;\n const executionId = decisionIdOf(runId);\n const verdict = (record.result ?? {}) as DecisionVerdict;\n // Counted, and synced, before anything runs, as in 0.24: a try that\n // ends the isolate still counts, and the third gives up.\n const tries = Number(record.metadata?.tries ?? 0) + 1;\n this.tasks.updateMetadata(runId, (metadata) => ({ ...metadata, tries }));\n await this.ctx.storage.sync();\n if (tries > MAX_DECISION_TRIES + 1) {\n console.error(`[Think] Decision \"${runId}\" was given up on`);\n this.tasks.deleteRun(runId);\n return;\n }\n let output: unknown;\n const kept = record.metadata?.outcome as { output?: unknown } | undefined;\n if (kept !== undefined) {\n // The action already ran and its outcome was kept: a reset before\n // the transcript write does not run it again, as in 0.24.\n output = kept.output;\n } else if (tries > MAX_DECISION_TRIES) {\n output = {\n status: \"error\",\n executionId,\n action: input.action,\n error: `The approved action did not finish in ${MAX_DECISION_TRIES} tries.`\n };\n } else if (verdict.approved) {\n // The approved call runs; it does not park again. A claim a reset\n // left behind defers the decision until the lease lets it run.\n const host = this.#actionToolHost;\n const tools = compileActionTools(\n await this.getActions(),\n {\n ...host,\n parkDurablePause: undefined,\n // As in 0.24: the approval is the authority now, so the call is\n // not authorized again, and it runs with the request that parked\n // it.\n requestId: () =>\n (input as { requestId?: string | null }).requestId ?? \"\",\n authorizeAction: () => true,\n // It ran because a human approved it: no reply attachment, as on\n // Think, whatever turn is current.\n ranAfterApproval: async () => true,\n runLedgered: (args) =>\n host.runLedgered({\n ...args,\n onReclaimableInDoubt: () => DEFER_DECISION\n } as typeof args)\n },\n new Map()\n );\n const tool = tools[input.action] as\n | { execute?: (input: unknown, options: unknown) => unknown }\n | undefined;\n try {\n output = tool?.execute\n ? await tool.execute(input.input, {\n toolCallId: input.toolCallId,\n messages: []\n })\n : {\n status: \"error\",\n executionId,\n action: input.action,\n error: removedActionError(input.action)\n };\n } catch (error) {\n output = prepareActionOutputForModel(actionErrorEnvelope(error));\n }\n if (output === DEFER_DECISION) {\n // Its claim is still held by an attempt a reset cut off: give the\n // try back and report again later, as in 0.24.\n this.tasks.updateMetadata(runId, (metadata) => ({\n ...metadata,\n tries: tries - 1\n }));\n throw new Error(`Decision \"${runId}\" waits for its action's claim`);\n }\n output = capErrorEnvelope(output);\n // As in 0.24: said once the approved call has run (not for an action\n // that is no longer registered, whose approval ran nothing).\n if (tool?.execute) {\n this.#emitPauseDecided(\n \"action:pause:approved\",\n input.action,\n executionId\n );\n }\n } else {\n output = {\n status: \"rejected\",\n executionId,\n action: input.action,\n reason: verdict.reason ?? \"Rejected by user\"\n };\n this.#emitPauseDecided(\n \"action:pause:rejected\",\n input.action,\n executionId\n );\n }\n // For the `approveExecution` / `rejectExecution` call that settled the\n // decision in this isolate: it returns the outcome, as 0.24 did, also\n // when the released reply holds no paused part to write it to.\n if (record.metadata?.awaitingParking === undefined) {\n this.#releasedOutcomes.set(runId, output);\n }\n if (kept === undefined) {\n // Kept, and synced, before the transcript write. (An action run\n // through the ledger is also claimed there, so a reset while it ran\n // replays its record.)\n this.tasks.updateMetadata(runId, (metadata) => ({\n ...metadata,\n outcome: { output: output as TaskJson }\n }));\n await this.ctx.storage.sync();\n }\n // The write's record, kept on the run before the transcript write: a\n // report a reset replays after the write finds it, never another call\n // that reused the provider's tool-call id.\n const receipt = {\n written: record.metadata?.written as\n | { messageId: string; continues: boolean }\n | undefined,\n keep: async (written: { messageId: string; continues: boolean }) => {\n this.tasks.updateMetadata(runId, (metadata) => ({\n ...metadata,\n written: written as unknown as TaskJson\n }));\n await this.ctx.storage.sync();\n }\n };\n // The reply that parked it may still be being written (approved during\n // its turn): the report ends here without blocking (an alarm may be\n // driving it, and that turn's own wake must not wait behind it). The\n // parking turn's end reports it again; a reset replays it on start.\n // A turn still writing the reply that holds (or will hold) the call\n // would store its own copy of that reply over the outcome: the parking\n // turn mid-stream, or the turn a reset left recovering it. The report\n // waits for that turn's end (recorded on the run, synced), unless it is\n // the turn that just ended.\n const inFlight = await this.harness.session().inFlight();\n if (inFlight && inFlight.operationId !== ended) {\n const stored = await this.harness.session().messages();\n const latest = stored.at(-1);\n const pausedThere =\n latest !== undefined &&\n executionToolCallIn(latest, executionId, true) !== null;\n const pausedAnywhere = stored.some(\n (message) =>\n executionToolCallIn(message, executionId, true) !== null ||\n resolvesExecution(message, executionId)\n );\n if (pausedThere || !pausedAnywhere) {\n this.tasks.updateMetadata(runId, (metadata) => ({\n ...metadata,\n tries: tries - 1,\n awaitingParking: inFlight.operationId\n }));\n await this.ctx.storage.sync();\n return;\n }\n }\n this.#pausedDescriptors.delete(executionId);\n // Written over the paused output, the reply's waiting text dropped, and\n // the turn continued unless the verdict or a later message says not to.\n await this.#applyExecutionOutcome(executionId, output, verdict, receipt);\n this.tasks.deleteRun(runId);\n }\n\n /**\n * Write each durable pause a release had resolved but not written (its\n * completed decision run keeps `resolvedPause`) into the paused call of\n * the transcript, once: the action is not run again. The run goes after.\n */\n async #writeReleasedResolvedPauses(): Promise<void> {\n const records = this.tasks.peekList({\n definition: DECISION_TASK,\n status: [\"completed\"],\n order: \"oldest\"\n });\n if (records.length === 0) return;\n const handle = await this.#rootHandle();\n for (const record of records) {\n const pause = record.metadata?.resolvedPause as\n | { toolCallId: string; executionId: string; output: unknown }\n | undefined;\n if (!pause) continue;\n // The paused call is the one whose output names this execution (a\n // provider may reuse a tool-call id across replies), newest first; it\n // takes the outcome, and the text that described the wait goes, as on\n // Think.\n const messages = await this.harness.session().messages();\n for (let at = messages.length - 1; at >= 0; at--) {\n const message = messages[at];\n const toolCallId = executionToolCallIn(\n message,\n pause.executionId,\n true\n );\n if (toolCallId === null) continue;\n const parts = message.parts.map((part) =>\n \"toolCallId\" in part && part.toolCallId === toolCallId\n ? ({\n ...part,\n state: \"output-available\",\n output: pause.output\n } as UIMessage[\"parts\"][number])\n : part\n );\n await handle.updateMessage({\n ...message,\n parts: dropGenerationAfterToolCall(parts, toolCallId)\n } as never);\n break;\n }\n this.tasks.deleteRun(record.runId);\n }\n await this.#refresh();\n }\n\n /**\n * The descriptor of each durable pause this isolate parked, until it is\n * decided: the stored paused call carries it as `approvalDescriptor`, as\n * in 0.24, beside the output the model reads.\n */\n readonly #pausedDescriptors = new Map<string, ActionApprovalDescriptor>();\n\n /**\n * The descriptor of a paused `execute` execution, as in 0.24: named\n * after its first waiting call, enriched by the agent, with the request\n * that asked. Built once for each pause, when its reply is first stored.\n */\n #describePausedExecute(\n executionId: string,\n toolCallId: string,\n pending: unknown,\n requestId = this.#actionTurn?.operationId ?? \"\"\n ): ActionApprovalDescriptor | undefined {\n const group = Array.isArray(pending) ? (pending as PendingAction[]) : [];\n const first = group[0];\n if (!first) return undefined;\n const label = `${first.connector}.${first.method}`;\n const descriptor: ActionApprovalDescriptor = {\n action: label,\n summary: label,\n input: first.args,\n permissions: [],\n kind: \"durable-pause\",\n ...this.describePausedExecution(group, { requestId, toolCallId }),\n // The card's identity is not the agent's to change.\n requestId,\n toolCallId\n };\n this.#pausedDescriptors.set(executionId, descriptor);\n return descriptor;\n }\n\n /** A reply with each paused call this isolate parked described. */\n #withPausedDescriptors(message: UIMessage): UIMessage {\n if (\n !message.parts.some(\n (part) =>\n (\n (part as { output?: unknown }).output as\n | { status?: unknown }\n | null\n | undefined\n )?.status === \"paused\"\n )\n ) {\n return message;\n }\n let changed = false;\n const parts = message.parts.map((part) => {\n const output = (part as { output?: unknown }).output as\n | { status?: unknown; executionId?: unknown }\n | null\n | undefined;\n // A part stored with its descriptor keeps it: the request that asked\n // stays the one named, whichever turn stores the reply again.\n if ((part as { approvalDescriptor?: unknown }).approvalDescriptor) {\n return part;\n }\n const descriptor =\n output?.status === \"paused\" && typeof output.executionId === \"string\"\n ? (this.#pausedDescriptors.get(output.executionId) ??\n (this.tasks.peek(decisionRunId(output.executionId))?.metadata\n ?.descriptor as ActionApprovalDescriptor | undefined) ??\n this.#describePausedExecute(\n output.executionId,\n (part as { toolCallId?: string }).toolCallId ?? \"\",\n (output as { pending?: unknown }).pending\n ))\n : undefined;\n if (!descriptor) return part;\n changed = true;\n return {\n ...part,\n approvalDescriptor: descriptor\n } as unknown as typeof part;\n });\n return changed ? { ...message, parts } : message;\n }\n\n /**\n * Decision reports, one after another: each reads the transcript and\n * writes its call, so two for one reply never write from stale copies.\n */\n #decisions: Promise<void> = Promise.resolve();\n\n #decisionReport(runId: string): Promise<void> {\n const next = this.#decisions.then(() =>\n this.#onReleasedDecisionSettled(runId)\n );\n this.#decisions = next.catch(() => {});\n return next;\n }\n\n /**\n * Report again the decisions that waited for a turn's reply to be stored\n * (`operationId`), or, with none, those whose parking turn is no longer\n * in flight (at start, after a reset).\n */\n #reportAwaitingDecisions(operationId?: string): void {\n const runIds = this.tasks\n .peekList({\n definition: DECISION_TASK,\n status: [\"completed\"],\n order: \"oldest\"\n })\n .filter((record) => {\n const awaiting = record.metadata?.awaitingParking;\n return (\n typeof awaiting === \"string\" &&\n (operationId === undefined || awaiting === operationId)\n );\n })\n .map((record) => record.runId);\n if (runIds.length === 0) return;\n // All of them are written before any continues the reply: a\n // continuation stores its own copy of the reply it extends.\n const batch = this.#decisions.then(async () => {\n this.#heldContinuations = [];\n try {\n for (const runId of runIds) {\n try {\n await this.#onReleasedDecisionSettled(runId, operationId);\n } catch (error) {\n console.error(`[Think] Decision \"${runId}\" was not written`, error);\n }\n }\n } finally {\n const held = this.#heldContinuations;\n this.#heldContinuations = undefined;\n // One continuation: the last decision's, by its stable id.\n await held.at(-1)?.();\n }\n });\n this.#decisions = batch.catch(() => {});\n }\n\n /** While a batch is written, the continuations it owes, in order. */\n #heldContinuations: Array<() => Promise<unknown>> | undefined;\n\n /** A released decision's outcome, until its decide call reads it. */\n readonly #releasedOutcomes = new Map<string, unknown>();\n\n /** Decide a released Think's parked durable-pause. */\n async #decideReleased(\n executionId: string,\n approved: boolean,\n reason?: string,\n autoContinue?: boolean\n ): Promise<unknown> {\n const runId = decisionRunId(executionId);\n if (!isPendingDecision(this.tasks.peek(runId))) {\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 toolCallId = this.tasks.inputOf<{ toolCallId?: string }>(\n runId\n )?.toolCallId;\n await this.tasks.settle(runId, {\n approved,\n ...(reason !== undefined && { reason }),\n ...(autoContinue !== undefined && { autoContinue })\n });\n if (this.#releasedOutcomes.has(runId)) {\n const output = this.#releasedOutcomes.get(runId);\n this.#releasedOutcomes.delete(runId);\n return output;\n }\n // The outcome, read where it was written: the decided tool call.\n for (const message of await this.harness.session().messages()) {\n const part = message.parts.find(\n (candidate) =>\n \"toolCallId\" in candidate && candidate.toolCallId === toolCallId\n ) as { state?: string; output?: unknown } | undefined;\n if (!part) continue;\n if (\n (part.output as { status?: unknown } | undefined)?.status === \"paused\"\n ) {\n // Recorded, and run once the action can (as in 0.24).\n return {\n status: \"error\",\n executionId,\n error:\n \"The decision was recorded; its outcome is written when the \" +\n \"action can run.\"\n };\n }\n return part.state === \"output-available\" ? part.output : undefined;\n }\n return undefined;\n }\n\n /**\n * Set by `createExecuteTool(this)`: the codemode runtime whose paused\n * executions `pendingExecutions`, `approveExecution` and `rejectExecution`\n * reach, as in 0.24.\n */\n codemode?: CodemodeRuntimeHandle;\n\n /** The codemode runtime, building the tools once to find it. */\n async #codemodeRuntime(): Promise<CodemodeRuntimeHandle | undefined> {\n if (!this.codemode) {\n try {\n await this.getTools();\n } catch {\n // getTools may need a turn's context; without it there is no\n // runtime to resolve.\n }\n }\n return this.codemode;\n }\n\n /**\n * The actions awaiting approval across the execute tool's paused\n * executions, with their full args, as in 0.24.\n */\n async pendingExecutions(executionId?: string): Promise<PendingAction[]> {\n const runtime = await this.#codemodeRuntime();\n return runtime ? runtime.pending(executionId) : [];\n }\n\n /**\n * Decide a paused execution of the execute tool. Its runtime holds the\n * pending call and runs the decision itself; the outcome is recorded as a\n * decision run that completes at once, so the transcript write survives a\n * reset and the runtime is not asked twice.\n */\n async #decideExecution(\n executionId: string,\n verdict: DecisionVerdict\n ): Promise<unknown> {\n // A later pause of this execution is described afresh.\n this.#pausedDescriptors.delete(executionId);\n const runtime = await this.#codemodeRuntime();\n if (!runtime) {\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 pending = await runtime.pending(executionId);\n let output: unknown;\n if (verdict.approved) {\n output = truncatePausedExecutionOutput(\n await runtime.approve({ executionId })\n );\n } else {\n if (pending.length === 0) {\n return {\n status: \"error\",\n executionId,\n error: `Execution \"${executionId}\" is no longer pending.`\n };\n }\n // False: the call was resolved between the read above and here.\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 output = {\n status: \"rejected\",\n executionId,\n reason: verdict.reason ?? \"Rejected by user\"\n };\n }\n if (pending.length === 0) {\n // Nothing was pending (expired, settled, unknown): the runtime's\n // answer still corrects a stale card, and nothing is recorded.\n await this.#applyExecutionOutcome(executionId, output, verdict);\n return output;\n }\n try {\n await this.tasks.run(\n DECISION_TASK,\n {\n kind: \"codemode\",\n executionId,\n verdict: verdict as unknown as TaskJson,\n output: output as TaskJson\n } satisfies DecisionInput,\n {\n runId: decisionRunId(`codemode_${crypto.randomUUID()}`),\n start: \"now\"\n }\n );\n } catch (error) {\n // Too large to record: the runtime has decided, so the outcome is\n // written now; only its safety across a reset is lost.\n console.error(\n `[Think] The outcome of \"${executionId}\" was not recorded`,\n error\n );\n await this.#applyExecutionOutcome(executionId, output, verdict);\n }\n return output;\n }\n\n /**\n * Write a decided execution's outcome over the paused output of its tool\n * call, drop what the reply said while it waited, and continue the turn\n * so the model reads the outcome, unless the verdict says not to, the\n * execution paused again, or the conversation has moved on past the\n * reply that paused.\n */\n async #applyExecutionOutcome(\n executionId: string,\n output: unknown,\n verdict: DecisionVerdict,\n /**\n * A durable record of the write, for a report a reset may replay: it\n * is kept before the transcript is written, and names the reply and\n * whether a continuation is owed. A replay that finds no paused call\n * but this record knows the outcome was written.\n */\n receipt?: {\n readonly written?: { messageId: string; continues: boolean };\n keep(written: { messageId: string; continues: boolean }): Promise<void>;\n }\n ): Promise<void> {\n const handle = await this.#rootHandle();\n const messages = await this.harness.session().messages();\n // A continuation has a stable id per execution, so a replayed report\n // never starts a second one.\n const continueOnce = async () => {\n const go = async () => {\n // As in 0.24: the continuation starts through a queue item with\n // one id. An approval that arrives before the item has run\n // replaces it, so one model call reads both outcomes; one that\n // arrives while its continuation runs queues the next.\n await this.queue(\n DECISION_CONTINUATION_CALLBACK,\n { executionId, ...(pausedIn !== undefined && { pausedIn }) },\n { id: DECISION_CONTINUATION_QUEUE_ID }\n );\n };\n if (this.#heldContinuations) this.#heldContinuations.push(go);\n else await go();\n };\n let written = false;\n /** The reply that holds the paused call. */\n let pausedIn: string | undefined;\n for (let at = messages.length - 1; at >= 0 && !written; at--) {\n const message = messages[at];\n const toolCallId = executionToolCallIn(message, executionId, true);\n if (toolCallId === null) continue;\n pausedIn = message.id;\n const repaused =\n (output as { status?: unknown } | null)?.status === \"paused\";\n // The calls that wait now, with their whole arguments (the output's\n // copy is cut short for the model), as `pendingApprovals()` reads\n // them.\n const waiting = repaused\n ? await (await this.#codemodeRuntime())?.pending(executionId)\n : undefined;\n // The call names the execution it resolves: written in the same\n // update as the outcome, so a replayed report knows it was written.\n const withOutcome = message.parts.map((part) => {\n if (!(\"toolCallId\" in part) || part.toolCallId !== toolCallId) {\n return part;\n }\n // One that paused again waits on another call: its card describes\n // that call, for the request that asked the first time.\n const asked = (\n part as { approvalDescriptor?: ActionApprovalDescriptor }\n ).approvalDescriptor;\n const described =\n repaused && asked\n ? this.#describePausedExecute(\n executionId,\n toolCallId,\n waiting?.length\n ? waiting\n : (output as { pending?: unknown }).pending,\n asked.requestId\n )\n : undefined;\n return {\n ...part,\n output,\n ...(described && { approvalDescriptor: described }),\n [RESOLVED_EXECUTION_FIELD]: executionId\n } as unknown as UIMessage[\"parts\"][number];\n });\n // One that paused again still waits, as the text after it says.\n const parts = repaused\n ? withOutcome\n : withoutTrailingStepStart(\n dropGenerationAfterToolCall(withOutcome, toolCallId)\n );\n // Decided before the receipt: a report a reset replays after the\n // write makes the same choice. As think@0.24.0: the reply continues\n // after each approval, whatever it already ends in (a later step may\n // have parked another call and said so).\n await receipt?.keep({\n messageId: message.id,\n continues: !repaused && verdict.autoContinue !== false\n });\n await handle.updateMessage({ ...message, parts } as never);\n written = true;\n await this.#refresh();\n if (repaused) return;\n }\n // A replay after the write: the call names this execution, and the\n // receipt says whether a continuation was owed. A receipt alone is no\n // proof: the write may not have happened.\n if (\n !written &&\n messages.some((message) => resolvesExecution(message, executionId))\n ) {\n if (receipt?.written?.continues) {\n // The reply the receipt names held the call: a later reply is\n // still left as it is.\n pausedIn = receipt.written.messageId;\n await continueOnce();\n }\n return;\n }\n // Already resolved in place (from another tab): nothing more to do.\n if (\n !written &&\n messages.some(\n (message) => executionToolCallIn(message, executionId, false) !== null\n )\n ) {\n return;\n }\n if (!written) {\n // Its tool call is gone (compacted away): the outcome is kept as a\n // note the model reads, as in 0.24.\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: `${EXECUTION_OUTCOME_MESSAGE_PREFIX}${executionId}-${crypto.randomUUID()}`,\n role: \"system\",\n parts: [\n {\n type: \"text\",\n text:\n // As in 0.24: the source the execution's id names.\n `[${executionId.startsWith(\"actpause_\") ? \"durable action\" : \"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 }\n if (verdict.autoContinue === false) return;\n // Also when later messages follow the reply that paused: as\n // think@0.24.0, the model is asked again with the outcome.\n await continueOnce();\n }\n\n /**\n * The descriptor the waiting call with this approval id was asked with:\n * only that call, still waiting, so an earlier call that reused the id is\n * never read.\n */\n async #storedActionDescriptor(\n approvalId: string\n ): Promise<PendingApproval[\"descriptor\"] | undefined> {\n const messages = await this.harness.session().messages();\n for (let at = messages.length - 1; at >= 0; at--) {\n for (const part of messages[at].parts) {\n const record = part as {\n state?: unknown;\n approval?: { id?: unknown; descriptor?: { action?: unknown } };\n };\n if (\n record.state === \"approval-requested\" &&\n record.approval?.id === approvalId &&\n typeof record.approval.descriptor?.action === \"string\"\n ) {\n return record.approval\n .descriptor as unknown as PendingApproval[\"descriptor\"];\n }\n }\n }\n return undefined;\n }\n\n /** The pending approvals that are action calls (not paused executions). */\n async #pendingActionApprovals(\n executionId: string\n ): Promise<PendingApproval[]> {\n return (await this.pendingApprovals(executionId)).filter(\n (approval) => approval.source === \"action\"\n );\n }\n\n /** Approve a pending action call; the turn continues and runs it. */\n async approveExecution(executionId: string): Promise<unknown> {\n if (executionId.startsWith(\"actpause_\")) {\n return this.#decideReleased(executionId, true);\n }\n if ((await this.#pendingActionApprovals(executionId)).length === 0) {\n return this.#decideExecution(executionId, { approved: true });\n }\n return this.#decide(executionId, true);\n }\n\n /**\n * Reject a pending action call; the turn continues with the refusal, or\n * waits for a later turn with `{ autoContinue: false }`.\n */\n async rejectExecution(\n executionId: string,\n reason?: string,\n options?: RejectExecutionOptions\n ): Promise<unknown> {\n if (executionId.startsWith(\"actpause_\")) {\n return this.#decideReleased(\n executionId,\n false,\n reason,\n options?.autoContinue\n );\n }\n if ((await this.#pendingActionApprovals(executionId)).length === 0) {\n return this.#decideExecution(executionId, {\n approved: false,\n ...(reason !== undefined && { reason }),\n ...(options?.autoContinue !== undefined && {\n autoContinue: options.autoContinue\n })\n });\n }\n return this.#decide(executionId, false, reason, options?.autoContinue);\n }\n\n async #decide(\n executionId: string,\n approved: boolean,\n reason?: string,\n autoContinue?: boolean\n ): Promise<unknown> {\n const [pending] = await this.#pendingActionApprovals(executionId);\n if (!pending) {\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 session = this.harness.session();\n // As in 0.24: an approval for an action the app no longer offers runs\n // nothing. The call is refused, so the approval is consumed, and the\n // caller is told why.\n const action = pending.descriptor.action;\n // Every action offered now, gated or not: one whose gate was taken off\n // but whose name stays is still the app's action.\n const offered = compileActionTools(\n await this.getActions(),\n this.#actionToolHost,\n new Map()\n );\n const removed = approved && !Object.hasOwn(offered, action);\n const removedError = removedActionError(action);\n const receipt = await session.submit(\n removed\n ? {\n type: \"approval\",\n approvalId: executionId,\n approved: false,\n reason: removedError\n }\n : {\n type: \"approval\",\n approvalId: executionId,\n approved,\n ...(reason !== undefined && { reason })\n },\n removed\n ? { autoContinue: false }\n : autoContinue === undefined\n ? {}\n : { autoContinue }\n );\n // Recorded, so the call is never listed again. A decision stopped\n // before this point leaves the call pending with its descriptor.\n this.#actionDescriptors.delete(pending.descriptor.toolCallId);\n const result = await session.wait(receipt.operationId);\n await this.#refresh();\n // A decision the harness did not apply leaves the call waiting: that\n // alone is an error. A follow-up reply that failed after the action\n // ran is not.\n if ((await this.pendingApprovals(executionId)).length > 0) {\n return {\n status: \"error\",\n executionId,\n error:\n result.status === \"done\"\n ? \"not applied\"\n : (result.reason ?? result.status)\n };\n }\n if (removed)\n return { status: \"error\", executionId, action, error: removedError };\n // As in 0.24: the action's outcome, or the rejection. Read from the\n // call's final state, not from this decision: when two decisions race,\n // the one the harness applied is what happened.\n const toolCallId = pending.descriptor.toolCallId;\n let final:\n | {\n state?: unknown;\n output?: unknown;\n errorText?: unknown;\n approval?: { reason?: unknown };\n }\n | undefined;\n for (const message of this.messages) {\n for (const part of message.parts) {\n if (\"toolCallId\" in part && part.toolCallId === toolCallId) {\n final = part as typeof final;\n }\n }\n }\n if (final?.state === \"output-denied\") {\n return {\n status: \"rejected\",\n executionId,\n // The reason the applied rejection carries, whichever caller sent\n // it.\n reason:\n (typeof final.approval?.reason === \"string\"\n ? final.approval.reason\n : undefined) ?? \"Rejected by user\"\n };\n }\n if (final?.state === \"output-available\") return final.output;\n if (final?.state === \"output-error\") {\n return { status: \"error\", executionId, error: final.errorText };\n }\n return {\n status: \"error\",\n executionId,\n error:\n \"The decision was recorded; its outcome is written when the \" +\n \"action can run.\"\n };\n }\n getMessengers(): ThinkMessengers {\n return {};\n }\n\n /**\n * Run each tool's `execute` with the connection of the tab whose turn\n * calls it, as 0.24 ran a turn inside its tab's connection: the\n * operation the call runs inside names the tab (`chat.origin` in its\n * run's metadata, a tool answer's continuation included). A tab that has\n * gone, or a turn no tab sent, gives none.\n */\n #withTurnConnection(tools: ToolSet): ToolSet {\n const wrapped: ToolSet = {};\n for (const [name, tool] of Object.entries(tools)) {\n const execute = tool.execute;\n // Exactly what `execute` returns, an async iterable included, so a\n // streaming tool's preliminary outputs still stream: the connection\n // is found without an await.\n wrapped[name] = execute\n ? ({\n ...tool,\n execute: (input: unknown, options: never) => {\n const connection = this.#turnConnectionNow();\n if (!connection) return execute(input, options);\n const store = {\n agent: this,\n connection,\n request: undefined,\n email: undefined\n };\n const result = agentContext.run(store, () =>\n execute(input, options)\n );\n // A generator's body runs as it is read: each step inside\n // the connection too, a promised one's included.\n const inside = (value: unknown) =>\n isAsyncIterable(value)\n ? stepsInside(value, (step) => agentContext.run(store, step))\n : value;\n return result instanceof Promise\n ? result.then(inside)\n : inside(result);\n }\n } as ToolSet[string])\n : tool;\n }\n return wrapped;\n }\n\n /** The open connection of the tab whose turn the caller runs inside. */\n #turnConnectionNow(): Connection | undefined {\n const origin = this.harness.originOf(this.harness.session().id);\n return origin === undefined ? undefined : this.getConnection(origin);\n }\n\n /** Run `run` with the connection of the tab whose turn calls it, if any. */\n async #insideTurn<T>(run: () => Promise<T>): Promise<T> {\n const connection = this.#turnConnectionNow();\n if (!connection) return run();\n return agentContext.run(\n { agent: this, connection, request: undefined, email: undefined },\n run\n );\n }\n\n /** The surface `bindActiveDeliverySurface()` bound, while it is bound. */\n #boundSurface: MessengerDeliverySurface | undefined;\n\n /**\n * Bind a messenger reply's delivery surface, as 0.24 did, so a\n * `deliverNotice` while it is bound posts there. Returns the restore\n * function; nested binds restore in order. Called by\n * `deliverMessengerReply`.\n */\n bindActiveDeliverySurface(surface: MessengerDeliverySurface): () => void {\n const previous = this.#boundSurface;\n this.#boundSurface = surface;\n return () => {\n this.#boundSurface = previous;\n };\n }\n\n /**\n * Post a notice outside a turn, as 0.24 did: to the web transcript\n * (`\"web\"`, the default) as an assistant message that starts no turn, or\n * to a messenger's `thread`.\n */\n async deliverNotice(\n text: string | { markdown: string },\n options?: DeliverNoticeOptions\n ): Promise<void> {\n // As in 0.24: the active turn's channel and thread, unless given. A\n // messenger turn's thread while it runs, or while its response hook\n // does; outside a turn, `web`.\n const running = this.#running?.requestId;\n const active =\n (running !== undefined\n ? this.#messengerContexts.get(running)\n : undefined) ?? this.#respondingContext;\n const channelId =\n options?.channel ??\n this.activeChannel?.channelId ??\n active?.messengerId ??\n \"web\";\n const thread =\n options?.thread ??\n (active?.messengerId === channelId ? active.thread.id : undefined);\n const given = thread !== undefined ? { ...options, thread } : options;\n await deliverChannelNotice(text, given, {\n channelId,\n registry: this.#channels,\n surface: async () =>\n this.#boundSurface ??\n (this.#messengers?.noticeSurface(channelId, thread) as never),\n addMessages: (messages) => this.addMessages(messages),\n emit: (event) => {\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 /**\n * Return the channels for this agent, as in 0.24: the implicit `web`\n * channel and each messenger are always present; these add surfaces and\n * per-channel policy (instructions, a narrower tool set, `maxTurns`).\n */\n configureChannels(): ThinkChannels | Promise<ThinkChannels> {\n return {};\n }\n getScheduledTasks(): ThinkScheduledTasks | Promise<ThinkScheduledTasks> {\n return {};\n }\n\n getDefaultTimezone(): string | undefined | Promise<string | undefined> {\n return undefined;\n }\n\n /** Reconcile code-declared scheduled tasks, as 0.24 did. */\n internal_reconcileScheduledTasks(): Promise<void> {\n return reconcileScheduledTasks({\n scheduler: this.scheduler,\n selfPath: this.selfPath,\n tasks: () => this.getScheduledTasks(),\n timezone: () => this.getDefaultTimezone(),\n submit: (messages, options) => this.submitMessages(messages, options)\n });\n }\n\n // ── Lifecycle hooks ───────────────────────────────────────────────\n\n beforeTurn(\n _ctx: TurnContext\n ): TurnConfig | void | Promise<TurnConfig | void> {}\n\n beforeToolCall(\n _ctx: ToolCallContext\n ): ToolCallDecision | void | Promise<ToolCallDecision | void> {}\n\n afterToolCall(_ctx: ToolCallResultContext): void | Promise<void> {}\n\n /** An operation's trigger and signal: a submission unless set first. */\n /** The turns that reached a model call, with what `chat:turn:finish` repeats. */\n readonly #turnEvents = new Map<\n string,\n {\n trigger: TurnTrigger;\n continuation: boolean;\n generation: number;\n startedAt: number;\n }\n >();\n\n /**\n * As in 0.24: `chat:turn:start` when a turn starts its work (here its\n * first model call), with the clear count it started under.\n */\n #turnStarted(\n operationId: string,\n trigger: TurnTrigger,\n continuation: boolean\n ): void {\n const meta = {\n trigger,\n continuation,\n generation: this.#clears,\n startedAt: Date.now()\n };\n this.#turnEvents.set(operationId, meta);\n this._emit(\"chat:turn:start\", {\n requestId: operationId,\n trigger,\n admission: \"queue\",\n continuation,\n generation: meta.generation\n });\n }\n\n /** As in 0.24: `chat:turn:finish` for a turn that started. */\n #turnFinished(\n operationId: string,\n status: \"completed\" | \"aborted\" | \"error\"\n ): void {\n const meta = this.#turnEvents.get(operationId);\n if (!meta) return;\n this.#turnEvents.delete(operationId);\n this._emit(\"chat:turn:finish\", {\n requestId: operationId,\n trigger: meta.trigger,\n admission: \"queue\",\n continuation: meta.continuation,\n generation: meta.generation,\n status,\n durationMs: Date.now() - meta.startedAt\n });\n }\n\n /**\n * As in 0.24: a turn that waits for its own reply cannot be asked for\n * from inside this agent's running turn, which it would wait behind.\n */\n #assertNotInsideTurn(trigger: TurnTrigger): void {\n if (this.harness.insideOperation(this.harness.session().id) === undefined)\n 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, and do not waitForSubmission() on it from inside the turn`\n );\n }\n\n /**\n * The operations that answer the history with a new reply and no message\n * of their own (continueLastTurn, an empty saveMessages): as in 0.24, a\n * continuation, though the harness writes a new assistant message.\n */\n readonly #newReplies = new Set<string>();\n\n #isContinuation(turn: { operationId: string; continuation: boolean }) {\n return turn.continuation || this.#newReplies.has(turn.operationId);\n }\n\n /**\n * `ThinkSession.chat()` for a new reply with no message of its own: the\n * reply's chunks to `callbacks` as they stream, then its end.\n */\n async #streamReply(\n operationId: string,\n callbacks: ThinkStreamCallback\n ): Promise<void> {\n const session = this.harness.session();\n let delivered = Promise.resolve();\n const deliver = (fn: () => void | Promise<void>) => {\n delivered = delivered.then(fn).catch((error: unknown) => {\n console.error(\"[Think] chat callback failed\", error);\n });\n };\n // As for a turn with a new message: the caller hears the reply is\n // done after its last chunk and before the turn-end hook runs, and its\n // `onDone` is not waited for there.\n let doneSent = false;\n let finished: Promise<void> = Promise.resolve();\n const unsubscribe = session.subscribe((event) => {\n if (event.type === \"chunk\" && event.operationId === operationId) {\n deliver(() => callbacks.onEvent(JSON.stringify(event.chunk)));\n }\n if (event.type === \"interrupted\" && event.operationId === operationId) {\n deliver(() => callbacks.onInterrupted?.());\n }\n if (\n event.type === \"operation\" &&\n event.status.operationId === operationId &&\n event.status.status === \"done\" &&\n !doneSent\n ) {\n doneSent = true;\n deliver(() => {\n finished = Promise.resolve()\n .then(() => callbacks.onDone())\n .catch((error: unknown) => {\n console.error(\"[Think] chat callback failed\", error);\n });\n });\n }\n });\n this.harness.trackChatDelivery(session.id, operationId, () => delivered);\n try {\n const receipt = await this.#replyAgain(operationId);\n deliver(() => callbacks.onStart?.({ operationId: receipt.operationId }));\n const result = await session.wait(receipt.operationId);\n unsubscribe();\n await delivered;\n await finished;\n if (result.status === \"done\") {\n if (!doneSent) await callbacks.onDone();\n } else await callbacks.onError(saidOf(result) ?? \"unanswered\");\n } finally {\n unsubscribe();\n this.harness.trackChatDelivery(session.id, operationId, undefined);\n }\n }\n\n /**\n * Ask the harness for a new reply over the history as it stands. Only a\n * continuation (`continueLastTurn`) waits while the reply waits on a\n * client; a new turn with no new message asks the model, as in 0.24.\n */\n #replyAgain(\n operationId: string,\n continuation = false,\n body?: Record<string, unknown>\n ) {\n this.#newReplies.add(operationId);\n return this.harness.enqueue(\n this.harness.session().id,\n continuation ? { kind: \"reply\", continuation: true } : { kind: \"reply\" },\n // Kept with the operation, so a turn restored after a restart is\n // still told it continues.\n {\n operationId,\n metadata: { [NEW_REPLY_KEY]: true },\n ...(body !== undefined && { body })\n }\n );\n }\n\n /**\n * Whether a turn this isolate did not start is a new reply, from its\n * record: one read, made only for a turn that could be one (not marked a\n * continuation, answering a history that ends with a reply).\n */\n async #restoreNewReply(turn: ThinkTurnContext): Promise<void> {\n const { operationId } = turn;\n if (\n turn.continuation ||\n this.#newReplies.has(operationId) ||\n this.#turns.has(operationId) ||\n turn.messages.at(-1)?.role !== \"assistant\"\n ) {\n return;\n }\n const inspection = await this.harness.inspection(\n this.harness.session().id,\n operationId\n );\n if (inspection?.metadata?.[NEW_REPLY_KEY] === true) {\n this.#newReplies.add(operationId);\n }\n }\n\n /** A new operation id for a turn a method call asks for (`programmatic`). */\n #programmaticTurn(): string {\n const operationId = crypto.randomUUID();\n this.#turns.set(operationId, { trigger: \"programmatic\" });\n return operationId;\n }\n\n /**\n * What admitted the turn, as 0.24 named it. Decided here, once per\n * model call, and kept: `beforeTurn`'s context, `activeTurn`, the turn's\n * events and its trace read the same value.\n */\n #turnOf(turn: {\n readonly operationId: string;\n readonly origin?: ThinkTurnContext[\"origin\"];\n }): { readonly trigger: TurnTrigger } {\n const { operationId, origin } = turn;\n const known = this.#turns.get(operationId);\n let trigger: TurnTrigger;\n if (origin !== undefined && origin.attempt > 1) {\n // A turn that runs again after a reset or a stall is its recovery:\n // it continues what the cut-off attempt left, or answers again.\n trigger =\n origin.mode === \"continue\" ? \"recovery-continue\" : \"recovery-retry\";\n } else if (known) {\n // Named by what started it here: a method call, an agent tool.\n return known;\n } else if (\n origin?.trigger === \"tool-answer\" ||\n operationId.startsWith(DECISION_CONTINUE_PREFIX)\n ) {\n trigger = \"auto-continuation\";\n } else if (origin?.web || this.#webRequests.has(operationId)) {\n trigger = \"ws-chat\";\n } else {\n trigger = \"submission\";\n }\n const identity = { trigger };\n this.#turns.set(operationId, identity);\n return identity;\n }\n\n /** End the operation's open step, if any, from `message`. */\n async #endStep(operationId: string, message: UIMessage): Promise<void> {\n const open = this.#openSteps.get(operationId);\n if (!open) return;\n this.#openSteps.delete(operationId);\n await this.#stepEnded(open, message);\n }\n\n /** Tell the extensions and `onStepEnd` that a step ended. */\n async #stepEnded(step: OpenStep, message: UIMessage): Promise<void> {\n const result = stepResultOf(message, step.segment);\n await this.#extensionHooks.stepFinish({\n stepNumber: step.step,\n finishReason: step.finishReason ?? \"unknown\",\n ...(step.usage && { usage: step.usage }),\n ...result\n // SAFETY: the fields a step snapshot reads are all here.\n } as unknown as StepContext);\n const record =\n typeof step.record === \"object\" && step.record !== null\n ? (step.record as {\n readonly sources?: unknown;\n readonly files?: unknown;\n readonly reasoning?: unknown;\n })\n : undefined;\n await this.onStepEnd({\n // The AI SDK's step record (sources, files, provider metadata, the\n // response), under what the reply holds for the step: its tool\n // results are in the reply, since the harness runs the tools.\n response: { messages: [] },\n ...(typeof step.record === \"object\" && step.record),\n // The record's own getters, which a spread does not copy.\n ...(record && {\n sources: record.sources,\n files: record.files,\n reasoning: record.reasoning\n }),\n ...result,\n finishReason: step.finishReason,\n ...(step.usage && { usage: step.usage }),\n message,\n stepNumber: step.step,\n requestId: step.operationId\n } as unknown as StepContext);\n }\n\n /** Before each model call, as the AI SDK's `prepareStep` in Think. */\n beforeStep(\n _ctx: PrepareStepContext\n ): StepConfig | void | Promise<StepConfig | void> {}\n\n /** After each step, as in 0.24. */\n onStepEnd(ctx: StepContext): void | Promise<void> {\n return this.onStepFinish(ctx);\n }\n\n /** @deprecated Prefer `onStepEnd`, as in 0.24. */\n onStepFinish(_ctx: StepContext): void | Promise<void> {}\n\n onChunk(_ctx: ChunkContext): void | Promise<void> {}\n\n onChatResponse(_result: ChatResponseResult): void | Promise<void> {}\n\n onChatError(error: unknown, _ctx?: ChatErrorContext): unknown {\n return error;\n }\n\n classifyChatError(\n _error: unknown,\n _ctx?: ChatErrorContext\n ): ChatErrorClassification | void {}\n\n // ── Messages ──────────────────────────────────────────────────────\n\n /**\n * Result of the most recent refresh when `hydrationByteBudget` applies.\n * `truncated` means `this.messages` is a recent window of a larger\n * stored transcript.\n */\n protected get _lastHydration(): HydrationResult | null {\n return this.#transcript.lastHydration;\n }\n\n get messages(): UIMessage[] {\n return this.#transcript.messages;\n }\n\n /** The channel of the running turn, if it resolved to one. */\n get activeChannel(): ChannelContext | undefined {\n const turn = this.#turnChannel;\n return turn && turn.operationId === this.activeTurn?.requestId\n ? turn.context\n : undefined;\n }\n\n /** The channel the last turn ran on, for a continuation, as in 0.24. */\n #lastTurnChannel: string | undefined;\n /**\n * Continue the latest reply, as in 0.24: on `channel` when one is given,\n * otherwise on the channel the last turn ran on.\n */\n async #continue(\n channel: string | undefined,\n body?: Record<string, unknown>,\n trigger: TurnTrigger = \"programmatic\"\n ) {\n const operationId = this.#programmaticTurn();\n if (trigger !== \"programmatic\") this.#turns.set(operationId, { trigger });\n if (channel !== undefined) this.#explicitChannels.set(operationId, channel);\n try {\n // As in 0.24: a new assistant message, not an append.\n return await this.#replyAgain(operationId, true, body);\n } catch (error) {\n this.#explicitChannels.delete(operationId);\n // The turn never started: what it was to run under goes with it.\n this.#turns.delete(operationId);\n throw error;\n }\n }\n\n /** Continuations given their own channel, until they start. */\n #explicitChannels = new Map<string, string>();\n /** Operations a browser's chat request started: they run on `web`. */\n #webRequests = new Set<string>();\n\n /**\n * The ids of the replies each open tab request sent with its list, until\n * the request settles. In memory: after a reset the list is reconciled\n * without them.\n */\n #repliesSent = new Map<string, ReadonlySet<string>>();\n /** The channel registry, read at start (none on a sub-agent). */\n #channels: Map<string, NormalizedChannelDefinition> | undefined;\n /** The running operation's channel, resolved at its first model call. */\n #turnChannel:\n | {\n operationId: string;\n /** The channel asked for, registered or not. */\n channelId: string | undefined;\n context: ChannelContext | undefined;\n definition: NormalizedChannelDefinition | undefined;\n }\n | undefined;\n\n /**\n * The server-supplied metadata stamped on the turn's user message, as on\n * Think: read from the latest user message, so a recovered or continued\n * turn reads the same value.\n */\n get activeTurnMetadata(): Record<string, unknown> | undefined {\n return turnMetadataFromMessages(this.messages);\n }\n\n /** The turn running now, if any. */\n get activeTurn(): ActiveTurn | undefined {\n // As in 0.24: work a turn started belongs to that turn (the chat\n // module's context around its reply), so work it left running doesn't\n // see a later turn that runs when it does.\n const running =\n runningChatTurn() === undefined ||\n this.harness.insideOperation(this.harness.session().id) ===\n this.#running?.requestId\n ? this.#running\n : undefined;\n if (!running) return undefined;\n // The turn's channel, once it is resolved, as in 0.24.\n const channel =\n this.#turnChannel?.operationId === running.requestId\n ? this.#turnChannel.channelId\n : undefined;\n return channel === undefined ? running : { ...running, channel };\n }\n\n /** Durable conversation history, as in 0.24: the harness's Sessions. */\n get sessions(): Sessions {\n return this.#agentToolDeps().sessions;\n }\n\n /** The durable chunk log replies stream to, as in 0.24. */\n get streams(): Streams {\n return this.#agentToolDeps().streams;\n }\n\n /** The running operations whose model has streamed; dropped at their end. */\n #streamed = new Set<string>();\n /** Whether each running operation continues a reply; dropped at its end. */\n #continued = new Map<string, boolean>();\n #running:\n | { requestId: string; trigger: TurnTrigger; continuation: boolean }\n | undefined;\n\n /**\n * Hand out an RPC stub to this agent's Workspace, as in 0.24.\n * `getWorkspace(stub)` from `@cloudflare/computer` calls it to reach the\n * Workspace from another Worker or Durable Object. Only a Workspace this\n * agent owns can hand out a stub.\n */\n async __getWorkspaceStub(): Promise<WorkspaceStub> {\n await this.__unsafe_ensureInitialized();\n const workspace = this.workspace;\n if (!isLocalWorkspace(workspace)) {\n throw new Error(\n \"[Think] This agent's workspace belongs to another Durable Object, \" +\n \"so it cannot hand out a Workspace stub.\"\n );\n }\n await workspace.ready();\n return workspace.stub();\n }\n\n /**\n * Resolved at the next run's end or transcript change, for\n * {@link waitUntilStable}: a client's answer applied with no continuation\n * changes the transcript and ends no run.\n */\n readonly #stableWaiters: Array<() => void> = [];\n\n #wakeStableWaiters(): void {\n for (const wake of this.#stableWaiters.splice(0)) wake();\n }\n\n /**\n * Controls how overlapping user submit requests behave while another\n * chat turn is already active or queued, as in 0.24.\n *\n * @default \"queue\"\n */\n messageConcurrency: MessageConcurrency = \"queue\";\n\n /** How a tab's request joins the lane, as `messageConcurrency` says. */\n #arrival(): ChatArrival {\n const concurrency = this.messageConcurrency;\n if (typeof concurrency !== \"object\") return concurrency;\n // A missing or invalid window falls back to Think's default.\n const { debounceMs } = concurrency;\n return {\n debounceMs:\n typeof debounceMs === \"number\" &&\n Number.isFinite(debounceMs) &&\n debounceMs >= 0\n ? debounceMs\n : 750\n };\n }\n\n async getMessages(): Promise<UIMessage[]> {\n return this.harness.session().messages();\n }\n\n /** Re-read the transcript and return it, as in 0.24. */\n protected async syncMessagesFromStorage(): Promise<UIMessage[]> {\n await this.#sync();\n return this.#transcript.messages.slice();\n }\n\n /** Add messages to the conversation and run a turn over it. */\n async saveMessages(\n messages:\n | UIMessage[]\n | ((current: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>),\n options?: SaveMessagesOptions\n ): Promise<SaveMessagesResult> {\n this.#assertNotInsideTurn(\"programmatic\");\n // As in 0.24: a turn stopped before it starts builds and stores nothing.\n const cut = await this.#cutOffByStop(options?.signal);\n if (cut) return cutOffBeforeStart(cut);\n await this.#refresh();\n const resolved =\n typeof messages === \"function\" ? await messages(this.messages) : messages;\n const session = this.harness.session();\n // As in 0.24: a message the conversation already holds is left as it\n // is stored (the harness drops it when it places the turn, asking\n // storage, not the window `this.messages` may be), and nothing new to\n // store still runs a new reply over the history as it stands.\n const receipt =\n resolved.length === 0\n ? await this.#replyAgain(this.#programmaticTurn())\n : await session.submit(resolved, {\n operationId: this.#programmaticTurn()\n });\n const result = await this.#waitForTurn(\n receipt.operationId,\n options?.signal\n );\n // As in 0.24: with nothing stored and nothing given there is nothing\n // to send, and the call fails in Think's words, not the harness's.\n if (result.status === \"error\" && result.error === \"not_found\") {\n throw new Error(NO_MESSAGES_TO_SEND);\n }\n return result;\n }\n\n async clearMessages(): Promise<void> {\n this.#actionDescriptors.clear();\n this.#pausedDescriptors.clear();\n this.#clearing++;\n this.#clears++;\n // As in 0.24, a turn started before the clear but not yet submitted is\n // cut off by it: it counts as a stop, so that turn is skipped as cleared.\n this.#stops++;\n this.#lastStop = \"cleared\";\n // The chat's request context (the tab's last body and client tools)\n // outlives a clear, as in 0.24: a turn the server starts afterwards\n // still runs with it.\n const requestContext = await (\n await this.#rootHandle()\n ).internal_config(CHAT_REQUEST_CONTEXT_KEY);\n const resetting = this.harness.session().reset();\n this.#stopping = resetting.catch(() => {});\n try {\n // A decision's continuation still queued answers the chat as it was.\n await this.dequeue(DECISION_CONTINUATION_QUEUE_ID);\n await resetting;\n if (requestContext !== null) {\n await (\n await this.#rootHandle()\n ).internal_setConfig(CHAT_REQUEST_CONTEXT_KEY, requestContext);\n }\n } finally {\n this.#clearing--;\n }\n await this.#refresh();\n }\n\n /** Clears so far, and the count each running operation started under. */\n #clears = 0;\n #clearsAtStart = new Map<string, number>();\n /** Clears in progress: a turn they stop ends cleared, not stopped. */\n #clearing = 0;\n /**\n * The operations a `chat()` call waits on, and whether a clear stopped\n * each. Only those are tracked; each entry goes when its call returns.\n */\n #chatClears = new Map<string, boolean>();\n\n protected async continueLastTurn(\n body?: Record<string, unknown>,\n options?: SaveMessagesOptions & { trigger?: TurnTrigger; channel?: string }\n ): Promise<SaveMessagesResult> {\n // As in 0.24: the turn runs under the trigger the caller names.\n const trigger = options?.trigger ?? \"programmatic\";\n this.#assertNotInsideTurn(trigger);\n // As in 0.24: with no assistant message to continue, nothing runs.\n await this.#refresh();\n if (this.#transcript.messages.at(-1)?.role !== \"assistant\") {\n return {\n requestId: \"\",\n status: \"skipped\",\n reason: \"nothing-to-continue\"\n };\n }\n const cut = await this.#cutOffByStop(options?.signal);\n if (cut) return cutOffBeforeStart(cut);\n const receipt = await this.#continue(options?.channel, body, trigger);\n const result = await this.#waitForTurn(\n receipt.operationId,\n options?.signal\n );\n // While the reply still waits on a client (a client tool's call, an\n // approval) there is nothing to continue: the client's answer continues\n // it, and the waiting call is left as it is. think@0.24.0 called the\n // model again here and ended the waiting call as an error.\n return result.status === \"error\" && result.error === \"awaiting_client\"\n ? { requestId: \"\", status: \"skipped\", reason: \"awaiting-client\" }\n : result;\n }\n\n /**\n * Wait for a programmatic turn to end. The caller's signal stops it as a\n * stop from a tab would, so the turn ends `aborted`.\n */\n async #waitForTurn(\n operationId: string,\n signal: AbortSignal | undefined\n ): Promise<SaveMessagesResult> {\n const session = this.harness.session();\n const stop = () => this.#stopForCaller(operationId);\n signal?.addEventListener(\"abort\", stop, { once: true });\n try {\n if (signal?.aborted) stop();\n const result = await session.wait(operationId);\n await this.#refresh();\n return saveResult(result);\n } finally {\n signal?.removeEventListener(\"abort\", stop);\n }\n }\n\n /** Add messages to the conversation without running a turn. */\n async addMessages(\n messages:\n | UIMessage[]\n | ((current: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>),\n options?: AddMessagesOptions\n ): Promise<void> {\n await this.#refresh();\n const resolved =\n typeof messages === \"function\" ? await messages(this.messages) : messages;\n const handle = await this.#rootHandle();\n // As in 0.24: an unknown explicit parent fails here; the session would\n // attach the message to the root instead.\n if (\n typeof options?.parentId === \"string\" &&\n !(await handle.getMessage(options.parentId))\n ) {\n throw new Error(\n `addMessages: parentId \"${options.parentId}\" does not exist in this session`\n );\n }\n let parentId = options?.parentId;\n for (const message of resolved) {\n const stored = message as unknown as SessionMessage;\n if (options?.mode === \"upsert\") {\n await handle.upsertMessage(stored, { parentId });\n } else {\n await handle.appendMessage(stored, { parentId });\n }\n parentId = message.id;\n }\n await this.#refresh();\n }\n\n /**\n * Each running turn's tool calls by id, so `onChunk` can name a call's\n * tool and input on its result, as the AI SDK's stream parts do.\n */\n readonly #toolCalls = new Map<\n string,\n Map<string, { toolName: string; input: unknown }>\n >();\n\n /**\n * A call the transcript holds already, as one approved before its turn\n * runs it: its tool and input.\n */\n #storedCall(\n toolCallId: string\n ): { toolName: string; input: unknown } | undefined {\n for (let i = this.#transcript.messages.length - 1; i >= 0; i--) {\n for (const part of this.#transcript.messages[i].parts) {\n if (isToolUIPart(part) && part.toolCallId === toolCallId) {\n return { toolName: getToolName(part), input: part.input };\n }\n }\n }\n return undefined;\n }\n\n /**\n * A stream part to the extensions' `onChunk` and the subclass's, as\n * 0.24 gave both the same part.\n */\n #dispatchChunk(part: unknown): void {\n const typed = part as { type?: string; id?: string };\n // An extension's snapshot names a tool input's call by `toolCallId`.\n const forExtensions =\n (typed.type === \"tool-input-start\" ||\n typed.type === \"tool-input-delta\") &&\n typed.id !== undefined\n ? { ...typed, toolCallId: typed.id }\n : part;\n // In order, one after another, as 0.24 awaited each chunk's hooks.\n this.#chunkHooks = this.#chunkHooks\n .then(() =>\n this.#extensionHooks.chunk({\n chunk: forExtensions\n } as unknown as ChunkContext)\n )\n .catch((error: unknown) =>\n console.error(\"[Think] An extension's onChunk failed\", error)\n );\n void this.onChunk({ chunk: part } as unknown as ChunkContext);\n }\n\n #callsOf(operationId: string) {\n let calls = this.#toolCalls.get(operationId);\n if (!calls) this.#toolCalls.set(operationId, (calls = new Map()));\n return calls;\n }\n\n /** The extensions' `onChunk` calls, chained so they run in order. */\n #chunkHooks: Promise<void> = Promise.resolve();\n\n /** The running turn's own `maxSteps`, from its `beforeTurn`. */\n #turnMaxSteps: number | undefined;\n\n /**\n * The running operation's workflow prompt, when it asked for structured\n * output: the turn offers `think_final_answer` with its schema, and the\n * call's input is the output the workflow is told.\n */\n #finalAnswer:\n | {\n readonly operationId: string;\n readonly schema: unknown;\n name: string;\n output?: { readonly value: unknown };\n }\n | undefined;\n\n /** Whether `call` is the running workflow turn's final-answer tool. */\n #isFinalAnswer(call: {\n readonly operationId: string;\n readonly toolName: string;\n }): boolean {\n const final = this.#finalAnswer;\n return (\n final?.operationId === call.operationId && final.name === call.toolName\n );\n }\n\n /** On a workflow turn, add the final-answer tool to the turn's tools. */\n #addFinalAnswer(tools: {\n has(name: string): boolean;\n set(name: string, tool: Tool): void;\n }): void {\n const final = this.#finalAnswer;\n if (!final) return;\n // As in 0.24: when another tool has the name, it gets a suffixed one.\n let name = THINK_FINAL_ANSWER_TOOL_NAME;\n for (let suffix = 1; tools.has(name); suffix++) {\n name = `${THINK_FINAL_ANSWER_TOOL_NAME}_${suffix}`;\n }\n final.name = name;\n tools.set(\n name,\n 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 \" +\n \"when you have everything you need.\",\n inputSchema: jsonSchema(final.schema as never),\n execute: async (input: unknown) => {\n final.output = { value: input };\n // The answer ends the turn: no model call after it.\n this.#turnMaxSteps = 0;\n return \"Final answer recorded.\";\n }\n })\n );\n }\n\n /** The extensions' `beforeTurn` changes, kept for the operation. */\n #extensionTurn:\n | { readonly operationId: string; readonly changes: TurnConfig }\n | undefined;\n\n /** What a sandboxed extension can reach on this agent, as in 0.24. */\n readonly #hostApi = createThinkHostApi({\n workspace: () => this.workspace,\n context: () => this.context,\n messages: () => this.#transcript.messages,\n // Not a submission: a tool calling this during a turn would wait on\n // its own turn. One appended from `beforeTurn` comes before the reply,\n // as in 0.24: the harness attaches the reply to it.\n appendMessage: (message) => this.appendMessageToHistory(message)\n });\n\n /**\n * Run one host operation for a sandboxed extension, as in 0.24.\n * `HostBridgeLoopback` calls this after it checks the extension's\n * permissions.\n *\n * @internal\n */\n async _cfHostBridge<K extends ThinkHostOperation>(\n operation: K,\n args: Parameters<ThinkHostApi[K]>\n ): Promise<Awaited<ReturnType<ThinkHostApi[K]>>> {\n await this.__unsafe_ensureInitialized();\n return await callThinkHostApi(this.#hostApi, operation, args);\n }\n\n /** The harness's own repair of the part being repaired now. */\n #harnessRepair:\n | {\n readonly repaired: UIMessage[\"parts\"][number];\n readonly clientToolNames: ReadonlySet<string>;\n }\n | undefined;\n\n /**\n * Repair a single interrupted tool call: a tool part with no settled\n * result, left behind when a stream was cut off. Returns the part that\n * takes its place in the transcript, as in 0.24. A call the\n * conversation moved past (an approval never given, an approved call no\n * turn ran, a client's call never answered) is told to the model in\n * Think's words. For a server tool an interruption cut off, the default\n * is the harness's repair: a call to a tool safe to run again stays as\n * it was, any other becomes an errored result.\n */\n protected repairInterruptedToolPart(\n part: UIMessage[\"parts\"][number]\n ): UIMessage[\"parts\"][number] {\n const repair = this.#harnessRepair;\n const record = part as { state?: unknown; type?: unknown };\n const name =\n typeof record.type === \"string\" && record.type.startsWith(\"tool-\")\n ? record.type.slice(\"tool-\".length)\n : undefined;\n const movedPast =\n record.state === \"approval-responded\" ||\n record.state === \"approval-requested\" ||\n (record.state === \"input-available\" &&\n name !== undefined &&\n repair?.clientToolNames.has(name) === true);\n return repair && !movedPast\n ? repair.repaired\n : interruptedToolPartAsError(\n part,\n repair ? { clientToolNames: repair.clientToolNames } : {}\n );\n }\n\n protected async appendMessageToHistory(\n message: UIMessage,\n parentId?: string | null\n ): Promise<UIMessage> {\n await (\n await this.#rootHandle()\n ).appendMessage(message as unknown as SessionMessage, {\n parentId\n });\n await this.#refresh();\n return message;\n }\n\n /** Update a stored message, and the message view with it, as in 0.24. */\n protected async updateMessageInHistory(\n message: UIMessage\n ): Promise<UIMessage> {\n await (\n await this.#rootHandle()\n ).updateMessage(message as unknown as SessionMessage);\n await this.#refresh();\n return message;\n }\n\n /**\n * The running messenger turn's context, as in 0.24; outside one, the\n * latest message's.\n */\n getMessengerContext(): MessengerContext | undefined {\n const running = this.#running?.requestId;\n const active =\n running !== undefined ? this.#messengerContexts.get(running) : undefined;\n if (active) return active;\n // While `onChatResponse` runs, its turn's, from its user message.\n if (this.#respondingContext) return this.#respondingContext;\n return messengerOf(this.messages.at(-1));\n }\n\n /** The messenger context of the turn whose `onChatResponse` runs. */\n #respondingContext: MessengerContext | undefined;\n\n /**\n * A message's messenger context, trusted only when the server stamped its\n * messenger's channel on it (a client's write cannot set the channel).\n */\n #trustedMessengerOf(\n message: UIMessage | undefined\n ): MessengerContext | undefined {\n const context = messengerOf(message);\n const channel = message ? channelFromMessages([message]) : undefined;\n return context && channel === context.messengerId ? context : undefined;\n }\n\n /** Each turn's messenger context, kept for its response hook. */\n #responseContexts = new Map<string, MessengerContext>();\n /** Operations whose turn ran in this isolate, until their end hook. */\n #ranHere = new Set<string>();\n\n /** The latest user message's trusted messenger context, as stored. */\n async #storedMessengerContext(\n replyId: string | undefined\n ): Promise<MessengerContext | undefined> {\n // The turn's own user message: the nearest one on the stored path that\n // ends at its reply (the hydrated window, or the active branch, may not\n // hold it), read newest first so only the rows up to it are loaded.\n // With no reply stored, the latest user message.\n if (replyId !== undefined) {\n const handle = await this.#rootHandle();\n let stored = false;\n for await (const message of handle.history({\n leafId: replyId,\n newestFirst: true\n })) {\n stored = true;\n if (message.role === \"user\") {\n return this.#trustedMessengerOf(message as unknown as UIMessage);\n }\n }\n if (stored) return undefined;\n }\n await this.#refresh();\n const user = [...this.#transcript.messages]\n .reverse()\n .find((message) => message.role === \"user\");\n return this.#trustedMessengerOf(user);\n }\n\n /**\n * Run a turn for a messenger event, as in 0.24: the context is kept on\n * the user message, and the turn runs on the messenger's channel.\n */\n async chatWithMessengerContext(\n userMessage: string | UIMessage,\n callback: StreamCallback,\n context: MessengerContext,\n options?: ChatOptions\n ): Promise<void> {\n // The turn's context names its author, as the context stored on a\n // messenger's user message does: the sender of a message, or the user\n // who pressed an action. A caller that hands over the event itself has\n // the author only inside its message or action.\n const author =\n context.author ?? context.message?.author ?? context.action?.user;\n const messenger: MessengerContext =\n context.author === undefined && author !== undefined\n ? { ...context, author }\n : context;\n const messages = toInput(userMessage).map((message) =>\n message.role === \"user\"\n ? {\n ...message,\n metadata: {\n ...(message.metadata as Record<string, unknown> | undefined),\n messenger\n }\n }\n : message\n );\n // A messenger posts the rest of a reply that was cut itself: it goes\n // on hearing the reply after `onInterrupted`.\n this.#followsInterrupted.add(callback);\n await this.chat(messages, callback, {\n ...options,\n channel: context.messengerId\n });\n }\n\n /** Callbacks that go on receiving a reply after `onInterrupted`. */\n #followsInterrupted = new WeakSet<StreamCallback>();\n\n /** Each running operation's messenger context; dropped at its end. */\n #messengerContexts = new Map<string, MessengerContext>();\n\n /**\n * The tools a client answers, as in 0.24: those the last turn had that\n * the server does not run (the client's own, and the app's declared with\n * no `execute`). Read once per isolate, since `hasPendingInteraction()`\n * is polled; stored, so the answer is there after a restart.\n */\n #unexecutedTools: string[] | undefined;\n /** Whether a `think_config` row holds the list; read once per isolate. */\n #unexecutedToolsStored: boolean | undefined;\n\n /** Store which of a turn's tools the server does not run, as 0.24 did. */\n #recordUnexecutedTools(tools: ToolSet): void {\n const names = unexecutedToolNames(tools);\n this.#unexecutedTools = names;\n // An empty list with no row stored says nothing a reader does not\n // already assume, so it costs no write; an unchanged one is skipped by\n // the store.\n this.#unexecutedToolsStored ??=\n this.#config.get(\"unexecutedTools\") !== undefined;\n if (names.length === 0 && !this.#unexecutedToolsStored) return;\n this.#config.set(\"unexecutedTools\", JSON.stringify(names));\n this.#unexecutedToolsStored = true;\n }\n\n /**\n * The list, read once per isolate. Before the first turn on this version\n * there is no record, so read `getTools()`, where an app declares a tool\n * without `execute`, as 0.24 did.\n */\n #unexecutedToolNames(): string[] {\n if (this.#unexecutedTools) return this.#unexecutedTools;\n const stored = this.#config.get(\"unexecutedTools\");\n if (stored !== undefined) {\n try {\n const parsed: unknown = JSON.parse(stored);\n if (Array.isArray(parsed)) {\n this.#unexecutedTools = parsed.filter(\n (name): name is string => typeof name === \"string\"\n );\n return this.#unexecutedTools;\n }\n } catch {\n // Fall through to the app's tools.\n }\n }\n try {\n this.#unexecutedTools = unexecutedToolNames(this.getTools());\n } catch {\n // `getTools()` can need turn-time context: without it, nothing is\n // known to be a client's.\n this.#unexecutedTools = [];\n }\n return this.#unexecutedTools;\n }\n\n /**\n * Each running operation's tool calls that have streamed and not had a\n * result yet, by call id: what Think's in-flight accumulator holds before\n * the reply is stored. Dropped at the operation's end.\n */\n readonly #liveCalls = new Map<\n string,\n Map<string, { toolName: string; approval: boolean }>\n >();\n\n /** Track a streamed tool call until its result streams too. */\n #noteLiveCall(operationId: string, chunk: UIMessageChunk): void {\n const calls = (): Map<string, { toolName: string; approval: boolean }> => {\n let held = this.#liveCalls.get(operationId);\n if (!held) {\n held = new Map();\n this.#liveCalls.set(operationId, held);\n }\n return held;\n };\n switch (chunk.type) {\n case \"tool-input-available\":\n calls().set(chunk.toolCallId, {\n toolName: chunk.toolName,\n approval: false\n });\n return;\n case \"tool-approval-request\": {\n const call = this.#liveCalls.get(operationId)?.get(chunk.toolCallId);\n if (call) call.approval = true;\n return;\n }\n case \"tool-output-available\":\n case \"tool-output-error\":\n case \"tool-output-denied\":\n this.#liveCalls.get(operationId)?.delete(chunk.toolCallId);\n return;\n default:\n return;\n }\n }\n\n /**\n * Whether the latest message has a tool call waiting on a client, as on\n * Think: an approval, or a call with no result to a tool a client\n * answers. A call to any other tool was the server's to run; unanswered\n * in a stored reply, it is dead (a removed tool, or an MCP tool not yet\n * reconnected, included).\n */\n protected hasPendingInteraction(): boolean {\n const answerable = new Set(this.#unexecutedToolNames());\n // A reply still streaming: its calls with no result yet, as 0.24's\n // accumulator held them.\n for (const calls of this.#liveCalls.values()) {\n for (const call of calls.values()) {\n if (call.approval || answerable.has(call.toolName)) return true;\n }\n }\n const last = this.#transcript.messages.at(-1);\n const parts = last?.parts ?? [];\n if (!parts.some((part) => \"toolCallId\" in part)) return false;\n return parts.some((part) => {\n if (!(\"toolCallId\" in part)) return false;\n if (part.state === \"approval-requested\") return true;\n if (part.state !== \"input-available\") return false;\n return answerable.has(\n getToolName(part as Parameters<typeof getToolName>[0])\n );\n });\n }\n\n /**\n * Resolve `true` once no operation is open and nothing waits on a client,\n * or `false` when `timeout` milliseconds pass first, as in 0.24.\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 const session = this.harness.session();\n for (;;) {\n // Listen before looking, so a change in between still wakes us. The\n // waiter goes when this round ends, however it ends.\n let wake!: () => void;\n const ended = new Promise<void>((resolve) => {\n wake = resolve;\n this.#stableWaiters.push(resolve);\n });\n // A wait on an open operation ends with this round.\n const round = new AbortController();\n try {\n const [open] = await session.pending();\n // A decision's continuation still queued is work to come.\n const owed =\n open === undefined &&\n (await this.getQueue(DECISION_CONTINUATION_QUEUE_ID)) !== undefined;\n if (open === undefined && !owed) {\n await this.#refresh();\n if (!this.hasPendingInteraction()) return true;\n } else if (open !== undefined) {\n // A run's end is told before its operation has settled, and\n // nothing is told after: the oldest open operation settling\n // wakes this round too, so it looks again.\n session.wait(open.operationId, round.signal).then(wake, wake);\n }\n if (deadline === null) {\n await ended;\n continue;\n }\n const remaining = deadline - Date.now();\n if (remaining <= 0) return false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timedOut = await Promise.race([\n ended.then(() => false),\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(true), remaining);\n })\n ]);\n clearTimeout(timer);\n if (timedOut) return false;\n } finally {\n round.abort();\n const index = this.#stableWaiters.indexOf(wake);\n if (index !== -1) this.#stableWaiters.splice(index, 1);\n }\n }\n }\n\n // ── Turns ─────────────────────────────────────────────────────────\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 if (options === null || typeof options !== \"object\") {\n throw new TypeError(\"runTurn: options must be an object\");\n }\n // As in 0.24: the same checks, in the same order, with the same words.\n const mode = (options as { mode?: unknown }).mode ?? \"wait\";\n if (mode !== \"wait\" && mode !== \"submit\" && mode !== \"stream\") {\n throw new TypeError(\n 'runTurn: mode must be \"wait\", \"submit\", or \"stream\"'\n );\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 if (mode === \"stream\" && !(options as RunTurnStream).callback) {\n throw new TypeError('runTurn: mode \"stream\" requires callback');\n }\n if (mode !== \"wait\" && options.input === undefined) {\n throw new TypeError(`runTurn: mode \"${mode}\" requires input`);\n }\n if (mode === \"stream\") {\n const stream = options as RunTurnStream;\n // As in 0.24: static input with no messages streams an empty turn.\n if (\n typeof stream.input !== \"function\" &&\n runTurnMessages(stream.input as StaticTurnInput).length === 0\n ) {\n await stream.callback.onStart({ requestId: crypto.randomUUID() });\n await stream.callback.onDone();\n return;\n }\n return this.chat(stream.input as TurnInputMessages, stream.callback, {\n ...(stream.signal && { signal: stream.signal }),\n ...(stream.channel !== undefined && { channel: stream.channel })\n });\n }\n if (mode === \"submit\") {\n const submit = options as RunTurnSubmit;\n // As in 0.24: a submission's input is fixed when it is accepted.\n if (typeof submit.input === \"function\") {\n throw new Error(\n 'runTurn({ mode: \"submit\" }) does not support function input until _admitTurn (step 3)'\n );\n }\n const messages = runTurnMessages(submit.input as StaticTurnInput);\n return this.submitMessages(messages, {\n ...(submit.submissionId !== undefined && {\n submissionId: submit.submissionId\n }),\n ...(submit.idempotencyKey !== undefined && {\n idempotencyKey: submit.idempotencyKey\n }),\n ...(submit.metadata !== undefined && { metadata: submit.metadata }),\n ...(submit.channel !== undefined && { channel: submit.channel })\n });\n }\n const wait = options as RunTurnWait;\n if (wait.input !== undefined && wait.continuation) {\n throw new TypeError(\n \"runTurn: supply either input or continuation: true, not both\"\n );\n }\n if (wait.input === undefined && !wait.continuation) {\n throw new TypeError(\"runTurn: supply either input or continuation: true\");\n }\n // As in 0.24: static input with no messages runs no turn.\n if (\n wait.input !== undefined &&\n typeof wait.input !== \"function\" &&\n runTurnMessages(wait.input as StaticTurnInput).length === 0\n ) {\n return { requestId: \"\", status: \"skipped\", continuation: false };\n }\n this.#assertNotInsideTurn(\"programmatic\");\n // As in 0.24: a continuation is continueLastTurn's turn, through an\n // override too; the result carries the reply it wrote.\n if (wait.continuation) {\n const result = await this.continueLastTurn(undefined, {\n ...(wait.signal && { signal: wait.signal }),\n ...(wait.channel !== undefined && { channel: wait.channel })\n });\n const settled = result.requestId\n ? await this.harness.session().wait(result.requestId)\n : undefined;\n await this.#refresh();\n // As in 0.24: the reply only for a turn the override says completed;\n // the structured output whatever it says.\n const message =\n result.status === \"completed\" &&\n settled?.status === \"done\" &&\n settled.messageId !== undefined\n ? this.#transcript.messages.find((m) => m.id === settled.messageId)\n : undefined;\n // A `beforeTurn` that asked for structured output gets it parsed.\n const output =\n settled?.status === \"done\"\n ? this.harness.operationOutput(\n this.harness.session().id,\n result.requestId\n )\n : undefined;\n return {\n ...result,\n continuation: true,\n ...(message && { message: message as unknown as SessionMessage }),\n ...(output !== undefined && { output })\n };\n }\n // As saveMessages: a turn stopped before it starts builds nothing.\n const cut = await this.#cutOffByStop(wait.signal);\n if (cut) return { ...cutOffBeforeStart(cut), continuation: false };\n const session = this.harness.session();\n const input = wait.input;\n const messages =\n typeof input === \"function\"\n ? await input(this.messages)\n : toInput(\n input as Exclude<\n TurnInputMessages,\n (current: UIMessage[]) => unknown\n >\n );\n const operationId = this.#programmaticTurn();\n // As in 0.24: a function that adds nothing still runs a new reply.\n const receipt =\n messages.length === 0\n ? await this.#replyAgain(operationId)\n : await session.submit(\n // As in 0.24: the channel is stamped on the durable user\n // message, so a continuation or a recovered turn resolves it.\n wait.channel ? stampTurnContext(messages, wait.channel) : messages,\n { operationId }\n );\n wait.signal?.addEventListener(\n \"abort\",\n () => void session.abort(receipt.operationId),\n { once: true }\n );\n const result = await session.wait(receipt.operationId);\n await this.#refresh();\n const message =\n result.status === \"done\" && result.messageId !== undefined\n ? this.#transcript.messages.find((m) => m.id === result.messageId)\n : undefined;\n // A `beforeTurn` that asked for structured output gets it parsed.\n const output =\n result.status === \"done\"\n ? this.harness.operationOutput(session.id, receipt.operationId)\n : undefined;\n return {\n ...saveResult(result),\n continuation: false,\n ...(message && { message: message as unknown as SessionMessage }),\n ...(output !== undefined && { output })\n };\n }\n\n // ── Submissions ───────────────────────────────────────────────────\n\n async submitMessages(\n messages: UIMessage[],\n options?: SubmitMessagesOptions\n ): Promise<SubmitMessagesResult> {\n if (messages.length === 0) {\n throw new Error(\"submitMessages requires at least one message\");\n }\n const metadata = admittedSubmissionMetadata(options?.metadata);\n const { submissionId, idempotencyKey } = options ?? {};\n if (submissionId !== undefined && idempotencyKey) {\n // Think's message for a pair that names two submissions; the harness\n // refuses the pair too.\n const session = this.harness.session().id;\n const keyed = await this.harness.keyedOperation(session, idempotencyKey);\n const byId = await this.harness.inspection(session, submissionId);\n if (\n (keyed !== undefined && keyed !== submissionId) ||\n (byId?.idempotencyKey !== undefined &&\n byId.idempotencyKey !== idempotencyKey)\n ) {\n throw new Error(\n \"submissionId and idempotencyKey refer to different submissions\"\n );\n }\n }\n // As in 0.24: the channel is stamped on the user messages, so the\n // turn that runs them resolves it. Accepting it is a span of its own,\n // under the names 0.24 gave it.\n const accepting = {\n \"cloudflare.agents.component\": \"think\",\n \"cloudflare.agents.turn.trigger\": \"submission\",\n \"cloudflare.agents.turn.admission\": \"submit\",\n ...(options?.channel !== undefined && {\n \"cloudflare.agents.turn.channel\": options.channel\n })\n };\n const receipt = await this._withAgentSpan(\n \"chat_submission\",\n \"submission\",\n accepting,\n () =>\n this._withAgentSpan(\n \"accept_chat_submission\",\n \"submission\",\n accepting,\n () =>\n this.harness\n .session()\n .submit(stampTurnContext(messages, options?.channel), {\n ...(options?.submissionId !== undefined && {\n operationId: options.submissionId\n }),\n submission: true,\n // An empty key is no key, as in 0.24.\n ...(options?.idempotencyKey && {\n idempotencyKey: options.idempotencyKey\n }),\n ...(metadata !== undefined && { metadata })\n })\n )\n );\n const inspection = await this.inspectSubmission(receipt.operationId);\n return {\n ...(inspection ?? {\n submissionId: receipt.operationId,\n status: \"pending\",\n createdAt: Date.now()\n }),\n accepted: receipt.accepted\n };\n }\n\n async inspectSubmission(\n submissionId: string\n ): Promise<ThinkSubmissionInspection | null> {\n const status = await this.harness.inspection(\n this.harness.session().id,\n submissionId\n );\n return status ? submissionInspection(status) : null;\n }\n\n async listSubmissions(\n options?: ListSubmissionsOptions\n ): Promise<ThinkSubmissionInspection[]> {\n const wanted = submissionStatuses(options?.status);\n if (wanted?.length === 0) return [];\n const session = this.harness.session().id;\n const limit = Math.min(Math.max(options?.limit ?? 50, 1), 100);\n if (!wanted) {\n return (await this.harness.submissions(session, { limit })).map(\n submissionInspection\n );\n }\n // Several submission statuses share a run status (a queued and a\n // started operation are both open runs; an aborted one is a completed\n // run), so a page can hold submissions that were not asked for: read on\n // until `limit` of the wanted ones are found, or there are no more.\n const status = taskStatusesFor(wanted);\n const found: ThinkSubmissionInspection[] = [];\n let after: { operationId: string; createdAt: number } | undefined;\n for (let size = limit; ; size = DELETE_PAGE) {\n const page = await this.harness.submissions(session, {\n status,\n ...(after && { after }),\n limit: size\n });\n for (const item of page) {\n const submission = submissionInspection(item);\n if (!wanted.includes(submission.status)) continue;\n found.push(submission);\n if (found.length === limit) return found;\n }\n const last = page.at(-1);\n if (page.length < size || !last) return found;\n after = { operationId: last.operationId, createdAt: last.createdAt };\n }\n }\n\n async deleteSubmission(submissionId: string): Promise<boolean> {\n const deleted = await this.harness.deleteSubmission(\n this.harness.session().id,\n submissionId\n );\n // Nothing of a release to remove with it: a carried submission's row\n // left the release's table when it was carried.\n return deleted;\n }\n\n async deleteSubmissions(options?: DeleteSubmissionsOptions): Promise<number> {\n const wanted = (\n submissionStatuses(options?.status) ?? TERMINAL_SUBMISSION_STATUSES\n ).filter(isTerminalSubmissionStatus);\n if (wanted.length === 0) return 0;\n const session = this.harness.session().id;\n const limit = Math.min(Math.max(options?.limit ?? 100, 1), 500);\n const matches: readonly ThinkSubmissionStatus[] = wanted;\n const matching = (submission: ThinkSubmissionInspection) =>\n matches.includes(submission.status) &&\n (!options?.completedBefore ||\n (submission.completedAt !== undefined &&\n submission.completedAt < options.completedBefore.getTime()));\n // Oldest accepted first (Think deletes oldest settled first; the two\n // differ only for a submission that settled before an older one).\n // Matched on Think's status, so a run the harness counts as completed\n // but which ended unanswered is not taken for a completed submission.\n // Read a page of `DELETE_PAGE` at a time, each after the last one read, so a\n // long run of submissions that do not match is passed over, never\n // read twice, and no more than a page is in memory.\n let deleted = 0;\n // The last record read, as it was read: it may be deleted by then.\n let after: { operationId: string; createdAt: number } | undefined;\n while (deleted < limit) {\n const listed = await this.harness.submissions(session, {\n status: taskStatusesFor(wanted),\n order: \"oldest\",\n ...(after !== undefined && { after }),\n limit: DELETE_PAGE\n });\n for (const submission of listed.map(submissionInspection)) {\n if (deleted >= limit) break;\n if (!matching(submission)) continue;\n if (\n await this.harness.deleteSubmission(session, submission.submissionId)\n ) {\n deleted++;\n }\n }\n if (listed.length < DELETE_PAGE) break;\n const last = listed[listed.length - 1];\n after = { operationId: last.operationId, createdAt: last.createdAt };\n }\n return deleted;\n }\n\n /** Called when a submission's status changes, as in 0.24. */\n protected onSubmissionStatus(\n _submission: ThinkSubmissionInspection\n ): void | Promise<void> {}\n\n /**\n * The harness's report of a submission's status: Think's events, then\n * the app's hook, before a wait on the submission resolves.\n */\n async #submissionStatus(status: ThinkOperationInspection): Promise<void> {\n const inspection = submissionInspection(status);\n const { submissionId, requestId } = inspection;\n // A workflow prompt that asks for structured output arms the turn's\n // final-answer tool before its tools are built.\n if (status.status === \"running\") {\n const schema = workflowPromptContext(inspection.metadata ?? null)?.output\n ?.schema;\n this.#finalAnswer =\n schema === undefined\n ? undefined\n : {\n operationId: status.operationId,\n schema,\n name: THINK_FINAL_ANSWER_TOOL_NAME\n };\n }\n if (status.status === \"queued\") {\n this._emit(\"submission:create\", {\n submissionId,\n requestId,\n idempotencyKey: inspection.idempotencyKey\n });\n }\n // The workflow that submitted it is told first, as in 0.24, and once\n // per submission: a repeated terminal report (a reset cut the app's\n // hook below short) must not queue an event the workflow already got.\n if (isTerminalSubmissionStatus(inspection.status)) {\n const final =\n this.#finalAnswer?.operationId === status.operationId\n ? this.#finalAnswer\n : undefined;\n if (final) this.#finalAnswer = undefined;\n const progress = status.metadata?.[SUBMISSION_PROGRESS_KEY] as\n | { workflowNotified?: boolean; output?: unknown }\n | undefined;\n const told = progress?.workflowNotified;\n // Marked once the event's delivery is accepted, not before: an\n // accept that fails leaves the next report to send it.\n if (told !== true) {\n sendWorkflowNotification(\n this.tasks,\n inspection,\n // This isolate's answer, or the one kept with the submission\n // when the turn ended in an isolate that is gone.\n final?.output ? final.output.value : progress?.output,\n () =>\n this.tasks.patchMetadata(submissionId, SUBMISSION_PROGRESS_KEY, {\n workflowNotified: true\n })\n );\n }\n }\n this._emit(\"submission:status\", {\n submissionId,\n requestId,\n status: inspection.status\n });\n if (inspection.status === \"error\" && inspection.error) {\n this._emit(\"submission:error\", {\n submissionId,\n requestId,\n error: inspection.error\n });\n console.error(\"[Think] Submission failed\", {\n submissionId,\n requestId,\n idempotencyKey: inspection.idempotencyKey,\n metadata: inspection.metadata,\n error: inspection.error\n });\n }\n try {\n await this.onSubmissionStatus(inspection);\n } catch (error) {\n console.error(\"[Think] onSubmissionStatus failed\", error);\n }\n }\n\n async waitForSubmission(\n submissionId: string,\n options?: WaitForSubmissionOptions\n ): Promise<ThinkSubmissionInspection | null> {\n const before = await this.harness.inspection(\n this.harness.session().id,\n submissionId\n );\n if (!before) return null;\n const open = before.status === \"queued\" || before.status === \"running\";\n if (\n this.#submissionStatuses.reporting(submissionId) ||\n (open && this.#submissionStatuses.reporting())\n ) {\n // As in 0.24: the hook's own submission, or one still open, settles\n // only after the hook returns.\n throw new Error(\n \"waitForSubmission() cannot be called from onSubmissionStatus: the submission settles only after the hook returns\"\n );\n }\n // As in 0.24: from inside this agent's running turn, a submission that\n // is still open runs only after that turn ends, so the wait could not.\n // Work an earlier turn left running is not inside a turn any more.\n if (\n open &&\n this.harness.insideOperation(this.harness.session().id) !== undefined\n ) {\n throw new Error(\n \"waitForSubmission() cannot be called from inside an active turn: the submission runs only after this turn ends\"\n );\n }\n // A timeout stops only the wait: the submission is returned as it is\n // then, still open, or `null` when it was deleted meanwhile.\n const timeout =\n options?.timeoutMs === undefined\n ? undefined\n : AbortSignal.timeout(options.timeoutMs);\n let settled: ThinkOperationInspection | undefined;\n try {\n settled = await this.harness.settled(\n this.harness.session().id,\n submissionId,\n timeout\n );\n } catch (error) {\n if (!timeout?.aborted) throw error;\n return this.inspectSubmission(submissionId);\n }\n // Read again; deleted meanwhile (the app's terminal hook may delete\n // it), the wait still has it as it settled, with a cancel's reason.\n return (\n (await this.inspectSubmission(submissionId)) ??\n submissionInspection(\n settled ?? {\n ...before,\n status: \"unanswered\",\n reason: \"not_found\",\n settledAt: before.settledAt ?? Date.now()\n }\n )\n );\n }\n\n // ── Programmatic chat ─────────────────────────────────────────────\n\n async chat(\n userMessage: TurnInputMessages,\n callback: StreamCallback,\n options?: ChatOptions\n ): Promise<void> {\n this.#assertNotInsideTurn(\"rpc\");\n // As in 0.24: tools are the agent's own, not the caller's.\n const ignored = (options as { tools?: unknown } | undefined)?.tools;\n if (\n ignored != null &&\n typeof ignored === \"object\" &&\n Object.keys(ignored).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 const cut = await this.#cutOffByStop(options?.signal);\n const operationId = crypto.randomUUID();\n if (cut) {\n // As in 0.24: the caller hears the request start. One its own signal\n // stopped hears nothing more; one a reset cut off is told the chat was\n // cleared, since a silent end would read as an answer.\n await callback.onStart({ requestId: operationId });\n if (cut === \"cleared\" && !options?.signal?.aborted) {\n await callback.onError(CHAT_CLEARED_ERROR);\n }\n return;\n }\n // As in 0.24: the channel and the caller's turn metadata are stamped\n // on the durable user message.\n const given = stampTurnContext(\n typeof userMessage === \"function\"\n ? await userMessage(this.messages)\n : toInput(userMessage),\n options?.channel,\n options?.metadata\n );\n // As in 0.24: a caller that stopped its request while its message was\n // worked out hears the request start and nothing more. Nothing is\n // stored and the model is not asked.\n if (options?.signal?.aborted) {\n await callback.onStart({ requestId: operationId });\n return;\n }\n // As in 0.24: a message under an id the transcript already holds is\n // not written again; the stored one stands.\n const held = await this.harness.storedIds(\n this.harness.session().id,\n given.map((message) => message.id)\n );\n const messages =\n held.size === 0 ? given : given.filter((m) => !held.has(m.id));\n this.#turns.set(operationId, { trigger: \"rpc\" });\n // As in 0.24: the caller's client tools, and the function that runs\n // them, are this turn's only. Nothing of them is stored.\n const session = this.harness.session().id;\n if (options?.clientTools?.length) {\n this.harness.lendTools(\n session,\n operationId,\n createToolsFromClientSchemas(\n options.clientTools,\n options.onClientToolCall\n ? { execute: options.onClientToolCall }\n : undefined\n )\n );\n }\n options?.signal?.addEventListener(\n \"abort\",\n () => this.#stopForCaller(operationId),\n { once: true }\n );\n this.#chatClears.set(operationId, false);\n // As on Think: a caller told its reply was interrupted hears nothing\n // more. The recovered reply is stored and sent to the tabs.\n let interrupted = false;\n const follows = this.#followsInterrupted.has(callback);\n const silenced = () => interrupted && !follows;\n try {\n // As in 0.24: no message to add still streams a new reply over the\n // history as it stands.\n const chat =\n messages.length === 0\n ? (callbacks: ThinkStreamCallback) =>\n this.#streamReply(operationId, callbacks)\n : (callbacks: ThinkStreamCallback) =>\n this.harness\n .session()\n .chat(messages, callbacks, { operationId })\n .then(() => {});\n // As in 0.24, what the caller's `onDone` throws is the caller's to\n // hear: `chat()` rejects with it once the reply has ended. (The\n // harness reports a failed callback and goes on.)\n let doneFailed: { error: unknown } | undefined;\n await chat({\n onStart: () => callback.onStart({ requestId: operationId }),\n onEvent: (json) => (silenced() ? undefined : callback.onEvent(json)),\n onInterrupted: () => {\n if (interrupted) return;\n interrupted = true;\n return callback.onInterrupted?.(\n follows ? { deliversRecoveredReply: true } : undefined\n );\n },\n onDone: async () => {\n if (silenced()) return;\n try {\n await callback.onDone();\n } catch (error) {\n doneFailed = { error };\n }\n },\n onError: (error) => {\n // A stopped turn is not an error: as in 0.24, its caller hears\n // neither `onDone` nor `onError`, and `onChatError` does not run.\n // \"aborted\" is the harness's reason for a stop, and \"withdrawn\" for\n // a stop that reached the turn while it waited (see `saveResult`).\n if (error === \"aborted\" || error === \"withdrawn\") return;\n // The same hook call as every other path's, made once: here or\n // at the turn's end, whichever comes first.\n const said = this.#reportChatError(\n operationId,\n error,\n this.#overflowed.has(operationId)\n ? {\n requestId: operationId,\n stage: \"stream\",\n messagesPersisted: true,\n classification: \"context_overflow\"\n }\n : {\n requestId: operationId,\n stage: this.#streamed.has(operationId) ? \"stream\" : \"turn\",\n messagesPersisted: this.#continued.has(operationId),\n ...(this.#continued.get(operationId) === true && {\n continuation: true\n })\n }\n );\n // A caller told its reply was interrupted hears nothing more.\n return silenced() ? undefined : callback.onError(said);\n }\n });\n if (\n this.#chatClears.get(operationId) === true &&\n !options?.signal?.aborted &&\n !silenced()\n ) {\n await callback.onError(CHAT_CLEARED_ERROR);\n }\n if (doneFailed) throw doneFailed.error;\n } finally {\n this.#chatClears.delete(operationId);\n this.#overflowed.delete(operationId);\n this.#thrown.delete(operationId);\n this.#chatErrorTexts.delete(operationId);\n this.harness.lendTools(session, operationId, undefined);\n }\n await this.#refresh();\n }\n\n async cancelSubmission(\n submissionId: string,\n reason?: unknown\n ): Promise<CancelSubmissionResult> {\n const before = await this.inspectSubmission(submissionId);\n if (!before) return { outcome: \"not_found\", submissionId };\n if (before.status !== \"pending\" && before.status !== \"running\") {\n return { outcome: \"already_terminal\", submissionId, submission: before };\n }\n const session = this.harness.session().id;\n // Read before the cancel: the app's terminal hook may delete the record.\n const ids = await this.harness.submittedMessageIds(session, submissionId);\n // Whether its own turn wrote them, also read before the cancel.\n const placed = await this.harness.placed(session, submissionId);\n await this.harness.abort(session, submissionId, cancelReason(reason));\n await this.harness.session().wait(submissionId);\n const after = (await this.inspectSubmission(submissionId)) ?? before;\n // Only a submission whose turn placed its messages applied them: one\n // cancelled before that wrote nothing, even if a message of the same\n // id was already in the conversation.\n const messagesApplied =\n before.status === \"running\" &&\n placed &&\n ids.length > 0 &&\n (await this.harness.storedIds(session, ids)).size > 0;\n return {\n outcome: \"cancelled\",\n submissionId,\n previousStatus: before.status,\n messagesApplied,\n submission: after\n };\n }\n\n /** Stop one turn by its request id; it ends `aborted`. */\n protected abortRequest(requestId: string, reason?: unknown): void {\n this.#noteAgentToolStop(requestId, reason);\n this.#stopForCaller(requestId);\n }\n\n /**\n * A stop, with a reason, of the turn of an agent-tool run: the run\n * reports that reason to its parent, as in 0.24. Marked at once, so the\n * parent reads it before the stop lands.\n */\n #noteAgentToolStop(requestId: string, reason: unknown): void {\n const text = abortText(reason);\n if (text !== undefined) {\n noteAgentToolStop(this.#agentToolDeps(), requestId, text);\n }\n }\n\n /**\n * Stop one turn by its request id, as 0.24 did. An agent-tool run\n * whose turn it is reports the reason.\n */\n cancelChat(requestId: string, reason?: string): void {\n this.#noteAgentToolStop(requestId, reason);\n // As in 0.24: synchronous. The stop is asked for when this returns\n // and is kept alive until it lands; a failure is logged there.\n void this.#stopForCaller(requestId).catch(() => {});\n }\n\n /**\n * The operations their callers stopped, until each ends: a clear that\n * lands while one unwinds did not stop it.\n */\n #callerStops = new Set<string>();\n #stopForCaller(operationId: string): Promise<boolean> {\n this.#callerStops.add(operationId);\n const stopping = this.harness\n .session()\n .abort(operationId)\n .then(\n (stopped) => {\n // Nothing was open under that id, so no turn end will clear it.\n if (!stopped) this.#callerStops.delete(operationId);\n return stopped;\n },\n (error: unknown) => {\n this.#callerStops.delete(operationId);\n throw error;\n }\n );\n void this.keepAliveWhile(() => stopping).catch((error: unknown) =>\n console.error(\"[Think] Stopping a turn failed\", error)\n );\n return stopping;\n }\n\n /** Stop every turn, running or waiting; each ends `aborted`. */\n protected abortAllRequests(): void {\n this.#stopEveryTurn(\"stopped\");\n }\n\n /**\n * Stop every turn, running or waiting, and keep the transcript. A\n * `clearMessages` resets the session as well.\n */\n protected resetTurnState(): void {\n this.#stopEveryTurn(\"cleared\");\n // The channel a continuation would extend goes with the turns.\n this.#lastTurnChannel = undefined;\n }\n\n /**\n * A stop of every turn that is open now. The harness reads the open turns\n * once it is ready, so the turns this shell starts afterwards wait for the\n * stop first, as 0.24's synchronous reset cut them off.\n */\n #stopping: Promise<unknown> = Promise.resolve();\n /** Counts the stops of every turn, so a turn waiting for one sees the next. */\n #stops = 0;\n /** What the latest stop does to a turn it cuts off before it starts. */\n #lastStop: \"stopped\" | \"cleared\" = \"stopped\";\n #stopEveryTurn(kind: \"stopped\" | \"cleared\"): void {\n // A decision's continuation still queued is stopped with the rest.\n void this.dequeue(DECISION_CONTINUATION_QUEUE_ID)\n .catch(() => {})\n .then(() => this.#wakeStableWaiters());\n this.#stops++;\n this.#lastStop = kind;\n const stopping =\n kind === \"cleared\"\n ? this.harness.abort(\n this.harness.session().id,\n undefined,\n SKIPPED_BY_RESET\n )\n : this.harness.session().abort();\n // A failed stop is reported, and does not fail the turns after it.\n this.#stopping = stopping.catch(() => {});\n void this.keepAliveWhile(() => stopping).catch((error: unknown) =>\n console.error(\"[Think] Stopping every turn failed\", error)\n );\n }\n\n /**\n * Wait for the stop in progress, and say what cut a turn off before it\n * started, if anything: its caller's signal, or another stop that came\n * while it waited (that stop was meant for it too). As in 0.24, a reset\n * skips it as cleared, and `abortAllRequests` stops it.\n */\n async #cutOffByStop(\n signal: AbortSignal | undefined\n ): Promise<\"stopped\" | \"cleared\" | undefined> {\n if (signal?.aborted) return \"stopped\";\n const stops = this.#stops;\n await this.#stopping;\n if (this.#stops !== stops) return this.#lastStop;\n return signal?.aborted ? \"stopped\" : undefined;\n }\n\n cancelAllChats(): void {\n // As in 0.24: synchronous. The stop is asked for when this returns\n // and is kept alive until it lands.\n const stopping = (async () => {\n // A decision's continuation still queued is stopped with the rest.\n await this.dequeue(DECISION_CONTINUATION_QUEUE_ID);\n await this.harness.session().abort();\n // The queued continuation counted as work owed: a waiter looks again.\n this.#wakeStableWaiters();\n })();\n void this.keepAliveWhile(() => stopping).catch((error: unknown) =>\n console.error(\"[Think] Stopping every chat failed\", error)\n );\n }\n\n /**\n * Start the continuation a decision asked for: the reply goes on with\n * the outcomes the transcript holds by now.\n * @internal Queue callback.\n */\n async _cfRunConnectionlessContinuation(payload?: {\n executionId?: string;\n /** The reply that held the paused call when it was decided. */\n pausedIn?: string;\n }): Promise<void> {\n try {\n // One already waiting to start reads the same outcomes.\n const waiting = (await this.harness.session().pending()).some(\n (operation) =>\n operation.status === \"queued\" &&\n operation.operationId.startsWith(DECISION_CONTINUE_PREFIX)\n );\n if (waiting) return;\n const executionId = payload?.executionId;\n const operationId = `${DECISION_CONTINUE_PREFIX}${executionId ?? crypto.randomUUID()}`;\n // A later reply is not the one that paused: it is left as it is, and\n // the model's answer to the outcome is a message of its own, as on\n // think@0.24.0.\n await this.#refresh();\n const latest = this.#transcript.messages.at(-1);\n if (\n payload?.pausedIn !== undefined &&\n latest?.role === \"assistant\" &&\n latest.id !== payload.pausedIn\n ) {\n await this.#replyAgain(operationId);\n return;\n }\n await this.harness.session().continue({ operationId });\n } finally {\n this.#wakeStableWaiters();\n }\n }\n\n // ── Left over from Think's previous engine ────────────────────────\n\n // Scheduler jobs that the previous engine queued call these by name. The\n // turns they would have recovered are gone after the move, so each\n // completes without doing anything instead of failing on retry.\n /**\n * As in 0.24: how often an interrupted turn is attempted again. `true`\n * keeps the default budget.\n */\n chatRecovery: ChatRecoveryConfig = true;\n\n /**\n * As in 0.24: decide what an interrupted turn does. Return\n * `{ continue: false }` to give it up; the default continues it within\n * the `chatRecovery` budget.\n */\n protected async onChatRecovery(\n _ctx: ChatRecoveryContext\n ): Promise<ChatRecoveryOptions | void> {\n return {};\n }\n\n /**\n * As in 0.24: how long a model stream may send nothing before the turn\n * is treated as interrupted. `0`, the default, turns the watchdog off.\n */\n chatStreamStallTimeoutMs = 0;\n\n /** The running model call's own stall timeout, from `beforeTurn`. */\n #turnStallTimeoutMs: number | undefined;\n\n #recoveryOptions(): {\n maxAttempts?: number;\n stallTimeoutMs: number;\n chatRecovery?: Exclude<ChatRecoveryConfig, true>;\n } {\n const config = this.chatRecovery;\n const stallTimeoutMs =\n this.#turnStallTimeoutMs ?? this.chatStreamStallTimeoutMs;\n // Think's released config, as it is: the turn definition's recovery\n // budget honours its fields.\n const onExhausted = config === true ? undefined : config.onExhausted;\n // The definition announces a give-up (see the host's `emit`), then\n // the app is told, as in 0.24. The definition names a turn by its\n // run; an app knows it by its request (the operation) id.\n const exhausted = (ctx: ChatRecoveryExhaustedContext) =>\n onExhausted?.(withOperationIds(ctx));\n if (config === true) {\n return { stallTimeoutMs, chatRecovery: { onExhausted: exhausted } };\n }\n const { shouldKeepRecovering } = config;\n return {\n ...(config.maxAttempts !== undefined && {\n maxAttempts: config.maxAttempts\n }),\n stallTimeoutMs,\n chatRecovery: {\n ...config,\n onExhausted: exhausted,\n ...(shouldKeepRecovering && {\n shouldKeepRecovering: (ctx) =>\n shouldKeepRecovering(withOperationIds(ctx))\n })\n }\n };\n }\n\n /** The operations this isolate marked recovering, until their terminal. */\n readonly #recovering = new Set<string>();\n /**\n * The turns that have sent a chunk since their recovery was last\n * scheduled (or since they started): while one sends, the recovering\n * status is not replayed to a tab that connects. Kept by what the turn\n * sends, not by recovery events, so it holds in an isolate that did not\n * schedule the recovery itself.\n */\n readonly #recoveryAttempts = new Set<string>();\n\n /** Reset per isolate: the first forwarded chunk after a restart credits. */\n readonly #childProgress = new AgentToolStreamProgressThrottle();\n\n /**\n * As in 0.24 (N9): forwarding a sub-agent's chunks is progress for the\n * turn that waits on it. The child's output goes to the tabs, not into\n * this turn's stream, so the turn is credited on its run (the credit the\n * chat turn's recovery budget reads), at most once per throttle window.\n * A silent child credits nothing, and its parent is still given up.\n */\n protected override async _onAgentToolStreamProgress(): Promise<void> {\n if (!this.#childProgress.shouldCredit(Date.now())) return;\n // The turn that runs now: after a reset it reruns its tool before any\n // model call, so it is read from the harness, not from this object.\n const session = this.harness.session().id;\n const operationId = (await this.harness.session().pending()).find(\n (operation) => operation.status === \"running\"\n )?.operationId;\n if (operationId === undefined) return;\n // A turn the dispatch started is named by its request; another by its\n // session too.\n const runId = this.tasks.peek(operationId)\n ? operationId\n : JSON.stringify([session, operationId]);\n const deps = this.harness.chatDeps(session, this.#chatHostDeps());\n this.tasks.patchMetadata(runId, \"chat\", {\n progressCredit: progressCreditOf(deps, runId) + 1\n });\n }\n\n /** Clear the recovering status of an operation that ended (#1620). */\n async #endRecovering(\n operationId: string,\n /** A recovery's own end: cleared by what is stored, even if this isolate never marked it (a reset came between). */\n stored = false\n ): Promise<void> {\n this.#recoveryAttempts.delete(operationId);\n if (!this.#recovering.delete(operationId) && !stored) return;\n await setChatRecovering(false, operationId, {\n storage: this.ctx.storage,\n messageType: CHAT_RECOVERING_FRAME,\n broadcast: (frame) => this.broadcast(JSON.stringify(frame)),\n now: Date.now()\n });\n }\n\n async #onRecovery(context: {\n readonly operationId: string;\n readonly attempt: number;\n readonly partial: UIMessage | undefined;\n readonly recoveryData?: unknown;\n readonly body?: Record<string, unknown>;\n readonly clientTools?: ReadonlyArray<\n NonNullable<ChatRecoveryContext[\"lastClientTools\"]>[number]\n >;\n }): Promise<\"continue\" | \"abandon\" | ChatRecoveryOptions> {\n // The recovery incidents a release kept: the ones inactive past their\n // TTL go when a recovery runs, as 0.24 swept them. Nothing writes new\n // ones here. Best-effort: a failed sweep must not fail the recovery.\n try {\n await sweepStaleChatRecoveryIncidents(this.ctx.storage, Date.now());\n } catch (error) {\n console.error(\n \"[Think] Released recovery incidents were not swept\",\n error\n );\n }\n // As in 0.24: a submission cut off by a reset whose turn started\n // longer ago than the stale window is not recovered. It ends `error`.\n // An attempt that already asked the model in this isolate is a live\n // retry (a stalled stream), which the window does not judge.\n if (this.#turnChannel?.operationId !== context.operationId) {\n const [running] = await this.harness.submissions(\n this.harness.session().id,\n { status: [\"running\"], limit: 1 }\n );\n if (\n running?.operationId === context.operationId &&\n Date.now() - (running.startedAt ?? running.createdAt) >\n (this.constructor as typeof Think).submissionRecoveryStaleMs\n ) {\n return \"abandon\";\n }\n }\n // A turn carried over an upgrade continues the reply its release had\n // streamed, which was stored before it: that is its partial.\n const carried = this.#releasedPartials.get(context.operationId);\n this.#releasedPartials.delete(context.operationId);\n const ownPartial = (context.partial?.parts.length ?? 0) > 0;\n const parts = [\n ...(ownPartial ? (context.partial?.parts ?? []) : (carried?.parts ?? []))\n ];\n const config = this.chatRecovery;\n const decision = await this.onChatRecovery({\n // One incident per operation: the harness attempts an operation\n // again until it is answered or given up.\n incidentId: context.operationId,\n recoveryRootRequestId: context.operationId,\n attempt: context.attempt,\n maxAttempts:\n config === true\n ? DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS\n : (config.maxAttempts ?? DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS),\n recoveryKind: parts.length > 0 ? \"continue\" : \"retry\",\n streamId: context.operationId,\n requestId: context.operationId,\n // What the interrupted turn was asked with, as 0.24 kept it.\n ...(context.body !== undefined && { lastBody: context.body }),\n ...(context.clientTools !== undefined &&\n context.clientTools.length > 0 && {\n lastClientTools: [...context.clientTools]\n }),\n partialText: parts\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\"),\n partialParts: parts,\n recoveryData: context.recoveryData ?? null,\n messages: [...this.messages],\n // When the turn started, as 0.24 gave it (not its time in the\n // queue), so an app can refuse stale work.\n createdAt: await this.#turnStartedAt(context.operationId)\n });\n // `persist: false` drops what the release had streamed too, unless it\n // holds a tool's settled result. The turn definition drops only what\n // its own run streamed, and this reply was stored before the run.\n if (\n carried &&\n !ownPartial &&\n decision?.persist === false &&\n !partialHasSettledToolResults(carried.parts as never)\n ) {\n const handle = await this.#rootHandle();\n if (decision.continue === false) {\n await handle.deleteMessages([carried.id]);\n } else {\n // The turn goes on: the reply is left holding nothing, which the\n // turn definition removes before it answers the question again.\n // Deleted here, the turn would find no reply to continue and end.\n await handle.upsertMessage({ ...carried, parts: [] } as never);\n }\n }\n // The app's answer goes to the turn definition as given: it drops the\n // partial for `persist: false`, as 0.24's recovery did.\n if (decision?.continue !== false && decision?.persist !== false) {\n return \"continue\";\n }\n return { continue: decision.continue, persist: decision.persist };\n }\n\n async #turnStartedAt(operationId: string): Promise<number> {\n const run = await this.harness.inspection(\n this.harness.session().id,\n operationId\n );\n return run?.startedAt ?? run?.createdAt ?? Date.now();\n }\n\n // A job think@0.24.0 queued to recover an incident: that recovery does\n // not run after the move, so the messenger reply held for it is\n // released as interrupted (the apology). TEMPORARY: remove in the next\n // minor.\n async _chatRecoveryRetry(data?: Record<string, unknown>): Promise<void> {\n await this.#releaseHeldReply(data);\n }\n async _chatRecoveryContinue(data?: Record<string, unknown>): Promise<void> {\n await this.#releaseHeldReply(data);\n }\n\n async #releaseHeldReply(data?: Record<string, unknown>): Promise<void> {\n const held =\n typeof data?.incidentId === \"string\" &&\n (await this.#releasedReplies.release(data.incidentId, \"interrupted\"));\n if (!held && data) await this.#takeUpReleasedRecovery(data);\n }\n\n /**\n * A request think@0.24.0 was waiting to retry or continue when the\n * upgrade came (a model error it retries after a backoff, a recovery it\n * had scheduled): its job has come due here. The request is taken up as\n * a turn cut off under its own id, so it is answered, or ends with an\n * error its tab and the hooks hear. A submission's is carried with its\n * submission; one already carried or ended here is left.\n */\n async #takeUpReleasedRecovery(data: Record<string, unknown>): Promise<void> {\n const requestId = data.originalRequestId;\n if (typeof requestId !== \"string\" || requestId === \"\") return;\n if (typeof data.recoveredRequestId === \"string\") return;\n const session = this.harness.session().id;\n if (await this.harness.inspection(session, requestId)) return;\n await this.#importReleasedTurn(requestId, {\n persisted: undefined,\n createdAt: Date.now()\n });\n }\n\n /**\n * Post a piece of a recovered messenger reply, for a thread's sub-agent,\n * as 0.24 did: only the agent that owns the messenger posts it.\n *\n * @internal\n */\n async _cf_deliverRecoveredMessengerReply(\n input: RecoveredReplyPost\n ): Promise<{ chunks: number }> {\n if (!this.#messengers) {\n throw new Error(\n `Cannot deliver a recovered reply for messenger \"${input.messengerId}\": this agent has no messenger runtime`\n );\n }\n return this.#messengers.deliverRecoveredReply(input);\n }\n\n /**\n * TEMPORARY: remove in the next minor. Think's start step for the\n * recovered replies think@0.24.0 kept; the shell runs it at start.\n * @internal\n */\n async _replayMessengerRecoveryDeliveries(): Promise<void> {\n await this.#importReleasedReplies();\n }\n\n /** 0.24's recovered replies, read only at a start after it ran. */\n async #importReleasedReplies(): Promise<void> {\n const moved = await this.#releasedReplies.importAll(this._releaseRanSince);\n // One that could not be moved is still in 0.24's record: the next\n // start tries again.\n if (!moved) this._releaseCarryNotDone();\n }\n\n /**\n * TEMPORARY: remove in the next minor. Release the reply held for a\n * think@0.24.0 recovery incident, as 0.24 did.\n * @internal\n */\n async _releaseMessengerRecovery(\n incidentId: string,\n outcome: \"completed\" | \"interrupted\",\n text?: string\n ): Promise<void> {\n await this.#releasedReplies.release(incidentId, outcome, text);\n }\n async _cfRetryMessengerRecoveryDelivery(): Promise<void> {}\n\n // ── Harness wiring ────────────────────────────────────────────────\n\n async #beforeTurn(turn: ThinkTurnContext): Promise<ThinkTurnConfig | void> {\n // The turn's channel, from the stamp on its latest user message, as\n // 0.24 resolved it for a new, continued or recovered turn.\n if (this.#turnChannel?.operationId !== turn.operationId) {\n await this.#restoreNewReply(turn);\n // A context reminder the harness adds as a message of its own is not\n // the turn's user message.\n const history = turn.messages.filter(\n (message) => message.id !== CONTEXT_REMINDER_MESSAGE_ID\n );\n const web = this.#webRequests.delete(turn.operationId);\n const explicit = this.#explicitChannels.get(turn.operationId);\n this.#explicitChannels.delete(turn.operationId);\n const user = [...history].reverse().find((m) => m.role === \"user\");\n // As in 0.24: a browser's request runs on `web`; a continuation on\n // the channel the last turn ran on; anything else on its stamp. A\n // messenger's message is stamped once its turn starts.\n let channel =\n explicit ??\n (web\n ? \"web\"\n : ((this.#isContinuation(turn) ? this.#lastTurnChannel : undefined) ??\n channelFromMessages(history)));\n // A browser's new user message is stamped `web` here, as 0.24 stamped\n // it at intake: the client's own write cannot carry the key, and the\n // harness writes the message when its turn starts.\n // (Stamped when it was placed; one placed before that existed, a\n // carried turn's, is stamped here.)\n if (web && user && channelFromMessages([user]) === undefined) {\n await this.#stamp(user.id, \"web\");\n }\n const messenger =\n channel === undefined && user\n ? this.#messengers?.channelOf(user.id)\n : undefined;\n // As in 0.24, the turn's messenger context: kept on its user\n // message, or the webhook's, stamped with the channel.\n const webhook = user ? this.#messengers?.contextOf(user.id) : undefined;\n // A message's own context is trusted only on a messenger's channel,\n // which only the server stamps: a browser cannot claim a sender.\n const context = this.#trustedMessengerOf(user) ?? webhook;\n this.#ranHere.add(turn.operationId);\n if (context) {\n this.#messengerContexts.set(turn.operationId, context);\n this.#responseContexts.set(turn.operationId, context);\n }\n if (messenger !== undefined && user) {\n channel = messenger;\n await this.#stamp(\n user.id,\n messenger,\n webhook && { messenger: webhook }\n );\n }\n const emit = this._emit as unknown as (\n type: string,\n payload: Record<string, unknown>\n ) => void;\n this.#turnChannel = {\n operationId: turn.operationId,\n channelId: channel,\n context: resolveChannelContext(channel, {\n registry: this.#channels,\n requestId: turn.operationId,\n messengerContext: () => context,\n emit: (event) => emit.call(this, event.type, event.payload)\n }),\n definition: channel ? this.#channels?.get(channel) : undefined\n };\n }\n const channel = this.#turnChannel.context\n ? this.#turnChannel.definition\n : undefined;\n // Every tool on offer, as 0.24's `beforeTurn` saw them, narrowed by\n // the channel's policy.\n const tools = channel?.tools ? channel.tools(turn.toolSet) : turn.toolSet;\n // Resolved only when read, as in 0.24: a `beforeTurn` that sets its\n // own model never needs the default's binding.\n // The step before this call ran its tools: it ends now, before this\n // call's hooks, as an AI SDK step ends before the next `prepareStep`.\n const reply = turn.messages.at(-1);\n // The step that just ended, whose usage the proactive guard reads.\n const lastUsage =\n turn.step > 0 ? this.#openSteps.get(turn.operationId)?.usage : undefined;\n if (turn.step > 0 && reply?.role === \"assistant\") {\n await this.#endStep(turn.operationId, reply);\n }\n const chosen = await this.getModel();\n // Resolved once per turn (and only when read), as in 0.24: a\n // `getGateway` that reads the turn's state picks one gateway for all\n // of the turn's model calls.\n const kept =\n this.#ownTurn?.operationId === turn.operationId\n ? this.#ownTurn\n : undefined;\n let resolved: LanguageModel | undefined = kept?.defaultModel;\n const resolveDefault = () => {\n resolved ??= this.resolveModel(chosen);\n if (this.#ownTurn?.operationId === turn.operationId) {\n this.#ownTurn.defaultModel = resolved;\n }\n return resolved;\n };\n const identity = this.#turnOf(turn);\n const continuation = this.#isContinuation(turn);\n this.#running = {\n requestId: turn.operationId,\n trigger: identity.trigger,\n continuation\n };\n // The first call of an operation says whether it continues a reply.\n if (!this.#continued.has(turn.operationId)) {\n // A turn that placed a question re-windows a view grown past its\n // budget here, where 0.24 did (after it stores the question), so\n // a warm object holds what Think's holds. Best-effort: a read that\n // fails leaves the view as it is.\n if (!continuation) {\n await this.#transcript.refreshIfNeeded().catch((error: unknown) => {\n console.warn(\"[Think] Could not re-window the transcript\", error);\n });\n }\n this.#recordUnexecutedTools(tools);\n this.#continued.set(turn.operationId, continuation);\n this.#clearsAtStart.set(turn.operationId, this.#clears);\n this.#turnStarted(turn.operationId, identity.trigger, continuation);\n }\n // As in 0.24: the capability block for the turn's tools follows the\n // prompt, unless a `beforeTurn` gives its own.\n const prompt = turn.system ?? this.getSystemPrompt();\n // As in 0.24: the channel's instructions come before the prompt.\n const instructions =\n channel?.instructions && this.#turnChannel.context\n ? typeof channel.instructions === \"function\"\n ? await channel.instructions(this.#turnChannel.context)\n : channel.instructions\n : undefined;\n const base = instructions ? `${instructions}\\n\\n${prompt}` : prompt;\n const context = {\n system: systemPromptForTurn(base, tools),\n // As the model would be sent them: older tool results cut, as on\n // Think.\n messages: await turn.modelMessages(),\n tools,\n get model() {\n return resolveDefault();\n },\n continuation,\n // The tab's request body, as in 0.24.\n // A request with no custom fields runs with no body, as in 0.24\n // (the empty body is what cleared the chat's earlier one).\n ...(turn.body !== undefined &&\n Object.keys(turn.body).length > 0 && { body: turn.body }),\n requestId: turn.operationId,\n trigger: identity.trigger,\n abortSignal: turn.signal,\n ...(this.#messengerContexts.has(turn.operationId) && {\n messenger: this.#messengerContexts.get(turn.operationId)\n })\n };\n // As in 0.24, `beforeTurn` runs once per turn; the harness asks\n // before every model call, and later calls reuse what it returned.\n const first = this.#ownTurn?.operationId !== turn.operationId;\n const own = first\n ? await this.beforeTurn(context)\n : (this.#ownTurn?.own ?? undefined);\n if (first) {\n // The message the turn's history ends at (a regenerate's is its\n // question, not the active leaf), for a reactive compaction.\n const leafId = turn.messages\n .filter((message) => message.id !== CONTEXT_REMINDER_MESSAGE_ID)\n .at(-1)?.id;\n this.#ownTurn = {\n operationId: turn.operationId,\n own,\n startedAt: Date.now(),\n ...(resolved && { defaultModel: resolved }),\n ...(leafId !== undefined && { leafId })\n };\n }\n // As in 0.24: a turn may set its own stall timeout. The harness asks\n // before every model call and reads `recovery` right after.\n this.#turnStallTimeoutMs = own?.chatStreamStallTimeoutMs;\n // The sandboxed extensions see the subclass's config, as in 0.24,\n // once per operation: Think prepares a turn once for its whole tool\n // loop, and the harness asks before every model call.\n const folded =\n this.#extensionTurn?.operationId === turn.operationId\n ? this.#extensionTurn.changes\n : undefined;\n const config =\n folded !== undefined\n ? { ...(own ?? {}), ...folded }\n : await this.#extensionHooks.beforeTurn(\n // SAFETY: the fields a turn snapshot reads are all here.\n context as unknown as TurnContext,\n own ?? {}\n );\n if (folded === undefined) {\n // `messages` is the first call's transcript: a later call has the\n // tool results since, so it is not kept.\n const { messages: _messages, ...kept } = changesOf(own ?? {}, config);\n this.#extensionTurn = { operationId: turn.operationId, changes: kept };\n }\n // A channel's `maxTurns` is a default a `beforeTurn` may override.\n this.#turnMaxSteps = config.maxSteps ?? channel?.maxTurns;\n // The model stays lazy, as in 0.24: spreading `context` would read\n // its `model` getter and resolve the default.\n const turnModel = config.model;\n let grantModel: LanguageModel | undefined;\n const self = this;\n await this.#authorizeTurn(\n turn.operationId,\n async () =>\n ({\n system: config.system ?? context.system,\n messages: config.messages ?? context.messages,\n tools: context.tools,\n // Resolved once, when first read.\n get model() {\n return (grantModel ??=\n turnModel !== undefined\n ? self.resolveModel(turnModel)\n : resolveDefault());\n },\n continuation: context.continuation,\n requestId: context.requestId,\n // As in 0.24: the grant sees what started the turn, and its\n // signal, so it can stop its own I/O when the turn stops.\n trigger: context.trigger,\n abortSignal: context.abortSignal\n }) as unknown as TurnContext\n );\n if (this.#ownTurn?.operationId === turn.operationId) {\n this.#ownTurn.stopWhen = config.stopWhen;\n }\n // Then `beforeStep`, before each model call, as the AI SDK's\n // `prepareStep` ran in 0.24. Its fields win for this call.\n // A `beforeTurn` that rewrote the messages rewrote them for the whole\n // turn, as 0.24's base prompt: a later call sends them with what this\n // turn's reply added since.\n if (first && config.messages && this.#ownTurn) {\n this.#ownTurn.messages = config.messages;\n // A continued reply's parts so far are in the rewritten prompt's\n // source already: a later call adds only what this turn adds.\n // The reply it continues, though a context reminder may follow it.\n const continued = [...turn.messages]\n .reverse()\n .find((m) => m.role === \"assistant\");\n this.#ownTurn.replyParts =\n turn.continuation && continued ? continued.parts.length : 0;\n // Calls of that reply still open now (an approved one that runs\n // after this hook): their outcome is this turn's to add.\n this.#ownTurn.openCalls = new Set(\n (turn.continuation && continued ? continued.parts : []).flatMap(\n (part) =>\n \"toolCallId\" in part &&\n part.state !== \"output-available\" &&\n part.state !== \"output-error\" &&\n part.state !== \"output-denied\"\n ? [part.toolCallId]\n : []\n )\n );\n }\n const compacted = await this.#compactBeforeStep(turn, lastUsage, tools);\n const rewritten = this.#ownTurn?.messages;\n // This turn's reply, and what follows it (a context reminder), as the\n // harness projects them for this call.\n let replyAt = turn.messages.length - 1;\n while (replyAt >= 0 && turn.messages[replyAt].role !== \"assistant\") {\n replyAt--;\n }\n const ownReply = replyAt >= 0 ? turn.messages[replyAt] : undefined;\n const added =\n ownReply && !first\n ? [\n {\n ...ownReply,\n parts: [\n // A call that was open when the prompt was rewritten and\n // has its outcome now.\n ...ownReply.parts\n .slice(0, this.#ownTurn?.replyParts ?? 0)\n .filter(\n (part) =>\n \"toolCallId\" in part &&\n this.#ownTurn?.openCalls?.has(part.toolCallId) === true &&\n (part.state === \"output-available\" ||\n part.state === \"output-error\" ||\n part.state === \"output-denied\")\n ),\n ...ownReply.parts.slice(this.#ownTurn?.replyParts ?? 0)\n ]\n },\n ...turn.messages.slice(replyAt + 1)\n ].filter((m) => m.parts.length > 0)\n : [];\n const turnMessages = compacted\n ? compacted\n : rewritten === undefined\n ? undefined\n : added.length === 0\n ? rewritten\n : [\n ...rewritten,\n ...withoutRepeatedCalls(\n rewritten,\n await convertToModelMessages(added, {\n tools,\n ignoreIncompleteToolCalls: true\n })\n )\n ];\n // As in 0.24, whose stream has started when `prepareStep` runs: the\n // reply begins here, and a tab that comes back is offered it.\n const startWriter = config.messageMetadata ?? this.messageMetadata;\n const startContinuation = first\n ? turn.continuation\n : (this.#ownTurn?.continuation ?? turn.continuation);\n turn.begin(\n startWriter && turn.step === 0\n ? ({ part }) =>\n startWriter({\n // SAFETY: the parts are the AI SDK's stream parts.\n part: part as Parameters<MessageMetadataCallback>[0][\"part\"],\n continuation: startContinuation\n })\n : undefined\n );\n const step: StepFields = isMethodOverridden(this, \"beforeStep\")\n ? (((await this.beforeStep({\n stepNumber: turn.step,\n steps: previousSteps(turn),\n get model() {\n return config.model !== undefined\n ? self.resolveModel(config.model)\n : resolveDefault();\n },\n messages: turnMessages ?? context.messages,\n experimental_context: undefined\n } as unknown as PrepareStepContext)) ?? {}) as StepFields)\n : {};\n const stepSystem = systemText(step.instructions ?? step.system);\n const system =\n stepSystem ??\n config.instructions ??\n config.system ??\n systemPromptForTurn(\n base,\n config.tools ? { ...tools, ...config.tools } : tools\n );\n const model = step.model ?? config.model;\n // Without an override, the turn's one resolution of the default.\n // As in 0.24, the model the grant was given is the one the call uses,\n // unless a step changed it: a string override is resolved once.\n const sent =\n model === undefined\n ? resolveDefault()\n : model === turnModel\n ? (grantModel ??= this.resolveModel(model))\n : this.resolveModel(model);\n const messages = step.messages ?? turnMessages;\n // A narrowing channel limits the tools the model is offered.\n // A narrowing channel limits the tools the model is offered, and a\n // selection cannot bring back a tool it removed.\n const selected = step.activeTools ?? config.activeTools;\n const chosenTools = channel?.tools\n ? (selected ?? Object.keys(tools)).filter((name) => name in tools)\n : selected;\n // A workflow turn that asked for structured output ends by calling the\n // final-answer tool, as in 0.24: the prompt says so, and a tool call\n // is required.\n const final =\n this.#finalAnswer?.operationId === turn.operationId\n ? this.#finalAnswer\n : undefined;\n // As in 0.24: with tools of its own the turn must call one each step,\n // else the final-answer tool; and on its last permitted step, that one.\n const lastStep =\n final !== undefined &&\n step.toolChoice === undefined &&\n // The turn's own limit: its override, else its channel's, as 0.24.\n turn.step >= (this.#turnMaxSteps ?? this.maxSteps) - 1;\n const pinned = final && { type: \"tool\" as const, toolName: final.name };\n const toolChoice = lastStep\n ? pinned\n : (step.toolChoice ??\n config.toolChoice ??\n (final\n ? Object.keys(tools).some((name) => name !== final.name)\n ? \"required\"\n : pinned\n : undefined));\n // A turn that names its active tools keeps the final-answer tool on.\n const activeTools =\n final && lastStep\n ? [final.name]\n : final && chosenTools\n ? [...chosenTools, final.name]\n : chosenTools;\n // As in 0.24: a step's provider options are merged onto the turn's.\n const providerOptions = mergedOptions(\n config.providerOptions,\n step.providerOptions\n );\n // `maxRetries: 0` asks for one try: an unclassified provider error is\n // then not tried again by the turn either.\n if (config.maxRetries === 0) this.#singleTry.add(turn.operationId);\n else this.#singleTry.delete(turn.operationId);\n const callSettings = defined({\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 // As in 0.24, where one `streamText` call ran the whole turn: the\n // turn's total is what is left of it at this model call.\n timeout: remainingTurnTimeout(\n config.timeout,\n Date.now() - (this.#ownTurn?.startedAt ?? Date.now())\n ),\n headers: config.headers,\n // As in 0.24: the turn's telemetry, under either spelling. The\n // harness adds the agent, the conversation and the turn to it.\n experimental_telemetry: config.telemetry ?? config.experimental_telemetry,\n experimental_transform: config.experimental_transform,\n experimental_repairToolCall: config.repairToolCall\n });\n // As in 0.24: recorded once the turn is prepared, so a continuation\n // never extends a turn whose preparation threw.\n if (first) this.#lastTurnChannel = this.#turnChannel.channelId;\n const writer = config.messageMetadata ?? this.messageMetadata;\n // Whether the turn continues a reply, as 0.24 told the writer: the\n // turn's own value, from its first call, not each call's.\n if (first && this.#ownTurn) {\n this.#ownTurn.continuation = turn.continuation;\n }\n const turnContinuation = this.#ownTurn?.continuation ?? turn.continuation;\n // The writer hears the reply's finish once, when the harness ends the\n // turn's stream (`finishMetadata`), with the last call's finish part.\n if (writer && this.#ownTurn?.operationId === turn.operationId) {\n this.#ownTurn.finishWrite = (part) =>\n writer({\n // SAFETY: the parts are the AI SDK's stream parts.\n part: part as Parameters<MessageMetadataCallback>[0][\"part\"],\n continuation: turnContinuation\n });\n }\n const sentSystem =\n final && typeof system === \"string\"\n ? [system, thinkFinalAnswerInstruction(final.name)]\n .filter(Boolean)\n .join(\"\\n\\n\")\n : system;\n return {\n model: sent,\n ...(typeof sentSystem === \"string\" && { system: sentSystem }),\n ...(messages && { messages }),\n ...(activeTools && { activeTools: [...activeTools] }),\n ...(toolChoice !== undefined && {\n // SAFETY: Think's and the harness's tool choice are the AI SDK's.\n toolChoice: toolChoice as ThinkTurnConfig[\"toolChoice\"]\n }),\n ...(providerOptions !== undefined && {\n // SAFETY: provider options are JSON by the AI SDK's contract.\n providerOptions: providerOptions as NonNullable<\n ThinkTurnConfig[\"providerOptions\"]\n >\n }),\n ...(config.maxOutputTokens !== undefined && {\n maxOutputTokens: config.maxOutputTokens\n }),\n ...(config.temperature !== undefined && {\n temperature: config.temperature\n }),\n // The rest of Think's call settings, as `streamText` takes them.\n ...(Object.keys(callSettings).length > 0 && { callSettings }),\n // As in 0.24: a workflow turn's answer is its final-answer tool's\n // input, which takes the place of the AI SDK's structured output.\n ...(config.output !== undefined &&\n final === undefined && { output: config.output }),\n sendReasoning: config.sendReasoning ?? this.sendReasoning,\n // As in 0.24: the turn's writer, else the agent's, told whether the\n // turn continues a reply.\n ...(writer && {\n messageMetadata: ({ part }: { readonly part: unknown }) => {\n // As 0.24's one stream for the whole turn: the writer hears the\n // turn's start once, on its first call, and its finish once, on\n // the call that ends it (not a tool round's).\n const kind = (part as { type?: string }).type;\n if (kind === \"start\" && turn.step > 0) return undefined;\n if (kind === \"finish\") {\n if (this.#ownTurn?.operationId === turn.operationId) {\n this.#ownTurn.lastFinish = part;\n }\n return undefined;\n }\n return writer({\n // SAFETY: the parts are the AI SDK's stream parts.\n part: part as Parameters<MessageMetadataCallback>[0][\"part\"],\n continuation: turnContinuation\n });\n }\n })\n } as ThinkTurnConfig;\n }\n\n /** Stamp `channel` on stored user message `id`, unless it has one. */\n async #stamp(\n id: string,\n channel: string,\n extra?: Record<string, unknown>\n ): Promise<void> {\n const handle = await this.#rootHandle();\n const stored = await handle.getMessage(id);\n if (!stored || stored.role !== \"user\") return;\n if (channelFromMessages([stored as UIMessage]) !== undefined) return;\n const [stamped] = stampTurnContext(\n [\n extra\n ? {\n ...(stored as UIMessage),\n metadata: {\n ...(stored.metadata as Record<string, unknown> | undefined),\n ...extra\n }\n }\n : (stored as UIMessage)\n ],\n channel\n );\n await handle.updateMessage(stamped as SessionMessage);\n }\n\n /** The input a human approved for a call, from the latest reply. */\n async #approvedInput(\n toolCallId: string\n ): Promise<{ found: false } | { found: true; input: unknown }> {\n const leaf = await (await this.#rootHandle()).getLatestLeaf();\n for (const part of leaf?.parts ?? []) {\n const record = part as {\n toolCallId?: unknown;\n input?: unknown;\n approval?: { approved?: unknown };\n };\n if (\n record.toolCallId === toolCallId &&\n record.approval?.approved === true\n ) {\n return { found: true, input: record.input };\n }\n }\n return { found: false };\n }\n\n async #beforeToolCall(call: {\n readonly operationId: string;\n readonly toolCallId: string;\n readonly toolName: string;\n readonly input: unknown;\n readonly step?: number;\n readonly messages?: readonly ModelMessage[];\n readonly signal?: AbortSignal;\n }): Promise<ThinkToolCallDecision | void> {\n // `afterToolCall` sees the input the model gave, as in 0.24, even when\n // the call runs with one `beforeToolCall` substituted.\n const kept = {\n operationId: call.operationId,\n input: call.input,\n started: Date.now()\n };\n this.#modelInputs.set(call.toolCallId, kept);\n let decision: ToolCallDecision | void;\n try {\n decision = await this.beforeToolCall({\n type: \"tool-call\",\n toolName: call.toolName,\n toolCallId: call.toolCallId,\n input: call.input,\n // As the AI SDK's tool-call event in 0.24: the step the call was\n // made in, the messages its `execute` gets, the turn's stop.\n stepNumber: call.step,\n messages: call.messages ?? [],\n abortSignal: call.signal,\n requestId: call.operationId\n } as unknown as ToolCallContext);\n } catch (error) {\n // As a throwing `execute`: the call settles as a tool error, with\n // the error as the AI SDK words it in 0.24.\n return { action: \"block\", reason: String(error) };\n }\n // The call's time starts once it is decided.\n kept.started = Date.now();\n if (!decision) return;\n switch (decision.action) {\n case \"block\":\n // As in 0.24, a blocked call answers the model with the reason.\n return {\n action: \"substitute\",\n output:\n decision.reason ??\n `Tool \"${call.toolName}\" was blocked by beforeToolCall.`\n };\n case \"substitute\":\n return { action: \"substitute\", output: decision.output };\n default:\n return {\n action: \"run\",\n ...(\"input\" in decision && { input: decision.input })\n };\n }\n }\n\n /**\n * As in 0.24: with `contextOverflow.reactive`, an overflowing call\n * compacts the session and the turn runs again, `beforeTurn` included.\n * Without it, or when compaction can't shorten the history, the\n * overflow ends the turn.\n */\n async #onContextOverflow(\n operationId: string,\n signal: AbortSignal\n ): Promise<boolean> {\n // A stopped turn is not compacted, nor run again; nor one whose retry\n // budget is zero, as 0.24 counted it.\n const config = this.contextOverflow;\n if (!config?.reactive || signal.aborted) return false;\n if ((config.maxRetries ?? 1) <= 0) return false;\n // The branch the turn answers, as 0.24 compacted it (a regenerate\n // answers an earlier message than the active leaf).\n const leafId =\n this.#ownTurn?.operationId === operationId\n ? this.#ownTurn.leafId\n : undefined;\n let shortened = false;\n try {\n shortened = Boolean(await this.session.compact(leafId));\n } catch (error) {\n console.warn(\n `[Think] context-overflow compaction failed: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n this._emit(\"chat:context:compacted\", {\n reason: \"reactive\",\n shortened,\n requestId: operationId,\n attempt: 1\n });\n // Stopped while it compacted: the turn ends.\n if (signal.aborted) return false;\n if (shortened && this.#ownTurn?.operationId === operationId) {\n // The retry is the same turn run again: its hooks run again.\n this.#ownTurn = undefined;\n this.#extensionTurn = undefined;\n }\n return shortened;\n }\n\n /**\n * Think's proactive guard (`contextOverflow.proactive`): when the step\n * before reported input tokens past the budget, compact the session and\n * send this call the compacted history with the turn's reply so far.\n * Best-effort: on any failure the call goes on unchanged.\n */\n async #compactBeforeStep(\n turn: ThinkTurnContext,\n usage: LanguageModelUsage | undefined,\n tools: ToolSet\n ): Promise<ModelMessage[] | undefined> {\n const guard = this.contextOverflow?.proactive;\n const own = this.#ownTurn;\n if (!guard || guard.maxInputTokens <= 0) return undefined;\n if (own?.operationId !== turn.operationId) return undefined;\n // The turn's reply, and what the harness projects after it for this\n // call (the context reminder), found by role, not position.\n let replyAt = turn.messages.length - 1;\n while (replyAt >= 0 && turn.messages[replyAt].role !== \"assistant\") {\n replyAt--;\n }\n const reply = replyAt >= 0 ? turn.messages[replyAt] : undefined;\n const after = turn.messages.slice(replyAt + 1);\n // The compacted history, then the live reply (never a stored copy of\n // it under the same id) and the call's projection after it.\n // Cut as every call's history is, by the agent's `truncationStep`:\n // older messages' text and tool results shortened, the recent ones\n // (the live reply among them) whole.\n const withLive = async (head: UIMessage[]) => {\n const history = head.filter((m) => m.id !== reply?.id);\n const messages = [...history, ...(reply ? [reply] : []), ...after];\n // The cutoff counts the compacted history only, as every call's\n // counts the stored transcript: the live reply and what follows it\n // stay whole without moving it.\n const keepRecent =\n messages.length -\n history.length +\n truncationKeepRecent(history.length, this.truncationStep);\n const cut = truncateOlderMessages(messages, {\n keepRecent,\n toolOutputs: false\n }) as UIMessage[];\n return truncateOlderToolResults(\n await convertToModelMessages(cut, {\n tools,\n ignoreIncompleteToolCalls: true\n }),\n cut,\n { keepRecent }\n );\n };\n // Once compacted, every later call of the turn sends the compacted\n // history: the harness's own transcript for the turn predates it.\n const compactedHead = own.compactedHead;\n const tried = own.proactive ?? 0;\n const used = usage?.inputTokens ?? usage?.totalTokens;\n const due =\n tried < Math.max(1, guard.maxCompactions ?? 1) &&\n used != null &&\n Number.isFinite(used) &&\n used >= guard.maxInputTokens * (guard.headroom ?? 0.9);\n if (!due) return compactedHead ? withLive(compactedHead) : undefined;\n try {\n // The attempt counts, so a no-op compaction isn't tried every step.\n own.proactive = tried + 1;\n // The branch the turn answers, not the session's active one (a\n // regenerate answers an earlier message).\n // The turn's leaf before its reply: its question, or the last message\n // a programmatic input supplied (an assistant's too).\n const question =\n replyAt > 0\n ? turn.messages[replyAt - 1]?.id\n : turn.messages[turn.messages.length - 1]?.id;\n const shortened = Boolean(await this.session.compact(question));\n this._emit(\"chat:context:compacted\", {\n reason: \"proactive\",\n shortened\n });\n if (!shortened) {\n return compactedHead ? withLive(compactedHead) : undefined;\n }\n // Through the context's projection, as every other call's history:\n // the reminders recorded on its messages, and those a summary hides,\n // are sent again.\n const stored = await this.session.getHistory(question);\n const head = (\n this.#context ? await this.#context.project(stored) : stored\n ) as UIMessage[];\n own.compactedHead = head;\n return await withLive(head);\n } catch (error) {\n console.warn(\n `[Think] proactive context compaction failed; proceeding without it: ${error instanceof Error ? error.message : String(error)}`\n );\n return compactedHead ? withLive(compactedHead) : undefined;\n }\n }\n\n /**\n * As in 0.24, a turn's `stopWhen` beside its `maxSteps`: once a step\n * meets a condition, the turn ends after that step's tools ran.\n */\n /**\n * As in 0.24, a turn's `stopWhen` beside its `maxSteps`, checked when a\n * step is settled: at once for a step without tool calls, else once its\n * server tools have returned (the AI SDK checks after the step's tools).\n * The steps are given with their usage and finish reason. Once met, the\n * turn makes no further model call.\n */\n async #stepEndedForStop(\n operationId: string,\n step: number,\n message: UIMessage,\n segment: number,\n meta: { usage?: LanguageModelUsage; finishReason?: string }\n ): Promise<void> {\n const own = this.#ownTurn;\n if (own?.operationId !== operationId || !own.stopWhen) return;\n const metas = (own.stepMeta ??= []);\n metas[step] = meta;\n // Only the calls the harness will run report back: one that is\n // settled already (its input didn't parse) or the provider ran is\n // not waited on.\n const calls = (\n stepResultOf(message, segment).toolCalls as Array<{\n toolCallId: string;\n }>\n ).filter((call) => {\n const part = message.parts.find(\n (p) => \"toolCallId\" in p && p.toolCallId === call.toolCallId\n ) as { state?: string; providerExecuted?: boolean } | undefined;\n return part?.state === \"input-available\" && !part.providerExecuted;\n });\n if (calls.length === 0) {\n await this.#checkStopWhen(own, step, message, segment, []);\n return;\n }\n own.pendingStop = {\n step,\n message,\n segment,\n waiting: new Set(calls.map((call) => call.toolCallId)),\n results: []\n };\n }\n\n /** A server tool of the step returned: check `stopWhen` once all have. */\n async #toolSettledForStop(\n operationId: string,\n result: {\n readonly toolCallId: string;\n readonly toolName: string;\n readonly input: unknown;\n readonly ok: boolean;\n readonly output?: unknown;\n }\n ): Promise<void> {\n const own = this.#ownTurn;\n const pending = own?.pendingStop;\n if (own?.operationId !== operationId || !pending) return;\n if (!pending.waiting.delete(result.toolCallId)) return;\n if (result.ok) {\n pending.results.push({\n type: \"tool-result\",\n toolCallId: result.toolCallId,\n toolName: result.toolName,\n input: result.input,\n output: result.output\n });\n }\n if (pending.waiting.size > 0) return;\n own.pendingStop = undefined;\n await this.#checkStopWhen(\n own,\n pending.step,\n pending.message,\n pending.segment,\n pending.results\n );\n }\n\n async #checkStopWhen(\n own: {\n readonly stopWhen?: TurnConfig[\"stopWhen\"];\n readonly stepMeta?: Array<{\n usage?: LanguageModelUsage;\n finishReason?: string;\n }>;\n },\n step: number,\n message: UIMessage,\n segment: number,\n settled: unknown[]\n ): Promise<void> {\n if (!own.stopWhen) return;\n const conditions = Array.isArray(own.stopWhen)\n ? own.stopWhen\n : [own.stopWhen];\n const steps: unknown[] = [];\n for (let at = segment - step, n = 0; at <= segment; at++, n++) {\n const result = stepResultOf(message, at);\n const meta = own.stepMeta?.[n] ?? {};\n steps.push({\n ...result,\n // The step being settled has its tools' results from their calls.\n ...(at === segment &&\n settled.length > 0 && {\n toolResults: [...result.toolResults, ...settled]\n }),\n usage: meta.usage,\n finishReason: meta.finishReason\n });\n }\n // SAFETY: a condition reads the steps' calls, results, usage and finish.\n const met = await Promise.all(\n conditions.map((condition) =>\n condition({ steps } as unknown as Parameters<typeof condition>[0])\n )\n );\n if (met.some(Boolean)) this.#turnMaxSteps = step + 1;\n }\n\n #classify(error: unknown, operationId?: string): ThinkErrorClass {\n // As in 0.24: the app's classifier wins, hearing the turn it\n // classifies for; without a verdict from it, what the provider's\n // error says.\n let classification: ChatErrorClassification | void = undefined;\n if (isMethodOverridden(this, \"classifyChatError\")) {\n try {\n classification = this.classifyChatError(error, {\n ...(operationId !== undefined && { requestId: operationId }),\n stage: \"stream\"\n });\n } catch (err) {\n console.warn(\n `[Think] classifyChatError threw; treating as unclassified: ${err instanceof Error ? err.message : String(err)}`\n );\n return \"fail\";\n }\n }\n // The object the model's call threw, for `onChatError`, while this\n // isolate lives.\n if (operationId !== undefined) this.#thrown.set(operationId, error);\n const appSaid = classification !== undefined;\n classification ??= classifyProviderError(error);\n const overflow = classification === \"context_overflow\";\n // The operation's latest failure decides how its caller hears it: an\n // overflow, or (after a retry that failed otherwise) not.\n if (operationId !== undefined) {\n if (overflow) this.#overflowed.add(operationId);\n else this.#overflowed.delete(operationId);\n }\n if (overflow) return \"context-overflow\";\n // A transient or rate-limited error is tried again within\n // chatRecovery's budget. An app's own classification wins; without one,\n // a platform transient (a lost connection) is tried again too.\n // The app's verdict or, without one, the provider's: a 429 or a 503 is\n // tried again too.\n // Without the app's verdict, a turn whose `beforeTurn` asked for no\n // retries ends on the provider's error, as in 0.24.\n const single =\n !appSaid && operationId !== undefined && this.#singleTry.has(operationId);\n if (\n !single &&\n (classification === \"transient\" || classification === \"rate_limit\")\n ) {\n return \"retry\";\n }\n return !appSaid && !single && isPlatformTransientError(error)\n ? \"retry\"\n : \"fail\";\n }\n\n /**\n * Operations a context overflow ended, until their caller is told, so\n * it hears the error as an overflow, as in 0.24. One entry per running\n * operation at most, deleted when reported or at the turn's end.\n */\n readonly #overflowed = new Set<string>();\n /** Turns whose `beforeTurn` set `maxRetries: 0`, until they settle. */\n readonly #singleTry = new Set<string>();\n\n /** The error each open turn's model call last threw, as thrown. */\n readonly #thrown = new Map<string, unknown>();\n\n /** What the app's `onChatError` returned for a failed turn, as text. */\n readonly #chatErrorTexts = new Map<string, string>();\n\n /**\n * The app's `onChatError` for a failed turn, once, whichever path the\n * turn came by, with the request and where it failed, as 0.24 handed\n * it. The error is the object the model's call threw when the turn\n * ended with it in this isolate; after a restart only its text is left.\n * Returns what the hook returned, as text: the caller's callback and the\n * `chat:request:failed` event both carry it.\n */\n #reportChatError(\n operationId: string,\n reason: string,\n context: ChatErrorContext,\n thrown: unknown = this.#thrown.get(operationId)\n ): string {\n const said = this.#chatErrorTexts.get(operationId);\n if (said !== undefined) return said;\n const error =\n thrown !== undefined &&\n (errorText(thrown) === reason ||\n // A long message, as a given-up turn's result keeps it: cut.\n errorText(thrown).slice(0, GAVE_UP_TEXT_MAX) === reason)\n ? thrown\n : new Error(reason);\n let text = reason;\n try {\n text = errorText(this.onChatError(error, context));\n } catch (hookError) {\n console.error(\"[Think] onChatError threw\", hookError);\n }\n this.#chatErrorTexts.set(operationId, text);\n return text;\n }\n\n /** The root session's Sessions handle, which the harness hands over on first use. */\n async #rootHandle(): Promise<Session> {\n if (!this.#handle) await this.harness.session().messages();\n if (!this.#handle)\n throw new Error(\"The harness did not configure the root session\");\n return this.#handle;\n }\n\n /**\n * Run one media-eviction pass queued on the Agent queue, by a sub-agent\n * facet, as in 0.24.\n * @internal Queue callback.\n */\n async _cfEvictAgedMedia(): Promise<void> {\n await this.#mediaEviction.run();\n }\n\n async #sync(): Promise<void> {\n await this.#transcript.sync();\n }\n\n /**\n * Bring the view up to date at a boundary, as 0.24 did: the session's\n * change feed patches it after every write, so storage is read again\n * only when the view cannot answer (not hydrated, marked stale, or a\n * window that has grown past its allowance).\n */\n async #refresh(): Promise<void> {\n await this.#transcript.refreshIfNeeded();\n }\n\n /** The host side of the shared chat dispatch: storage, sockets, events. */\n /**\n * What a tab is sent as the chat's messages. As 0.24 sent\n * `this.messages`: the view as it stands, which holds what this\n * lifetime appended until its next re-window. A connect does not\n * re-window it; a write outside a turn is read first (`reread`).\n */\n async #clientTranscript(reread: boolean): Promise<readonly UIMessage[]> {\n if (reread) await this.#transcript.sync();\n return this.#transcript.messages;\n }\n\n #chatHostDeps() {\n return {\n kv: this.ctx.storage.kv,\n // The list a tab is sent by the shared dispatch (a request that\n // ended while its tab was away) is this agent's view of the chat\n // too, bounded by `hydrationByteBudget`, never the whole transcript.\n transcript: (reread: boolean) => this.#clientTranscript(reread),\n // The chat as this agent holds it in memory, when that is the whole\n // stored path: a turn that ends at its newest message is given these\n // and reads no stored message again. A view that is only the newest\n // part of a long chat (or one not hydrated, or marked stale) gives\n // none (`undefined`, not an empty list): the turn reads as before,\n // and a tab's list is still compared with the view Think shows\n // (`transcript`), so its messages are not read one by one.\n heldMessages: () =>\n this.#transcript.coversActivePath\n ? this.#transcript.messages\n : undefined,\n // Offered only when the view is the whole stored path (above): so a\n // transcript that ends at an older message may be cut from it.\n heldIsWhole: () => this.#transcript.coversActivePath,\n // The chat dispatch's span around a tab's request\n // (`chat_interaction`) is this agent's. A turn's own spans\n // (`chat_turn`, the stores) are the harness's, with the turn's\n // attributes.\n span: <T>(\n name: string,\n phase: string,\n attributes: Readonly<\n Record<string, string | number | boolean | undefined>\n >,\n run: () => T\n ): T => {\n const given: Record<string, string | number | boolean> = {\n \"cloudflare.agents.component\": \"think\"\n };\n for (const [key, value] of Object.entries(attributes)) {\n if (value !== undefined) given[key] = value;\n }\n return this._withAgentSpan(name, phase, given, run);\n },\n webSockets: {\n getConnections: () => this.getConnections(),\n // Frames are made with no tab connected when something else reads\n // them: a parent waiting for an agent-tool run's first frame, or an\n // app's own `broadcast`.\n observed: () =>\n this.#agentToolTailWaits.size > 0 ||\n this.broadcast !== Think.prototype.broadcast,\n // Through `broadcast`, as in 0.24, so an app's override is handed\n // every frame a turn sends.\n broadcast: (text: string, without: string[]) => {\n if (this.#agentToolFrame(text) === \"suppress\") return;\n this.broadcast(text, without);\n }\n },\n emit: (type: string, payload: Record<string, unknown>) => {\n // As in 0.24 (#1620): a scheduled recovery reads as recovering\n // until the incident ends, for the tabs now and one that connects.\n if (type === \"chat:recovery:scheduled\") {\n const requestId = String(payload.requestId);\n this.#recovering.add(requestId);\n this.#recoveryAttempts.delete(requestId);\n void setChatRecovering(true, requestId, {\n storage: this.ctx.storage,\n messageType: CHAT_RECOVERING_FRAME,\n broadcast: (frame) => this.broadcast(JSON.stringify(frame)),\n now: Date.now()\n }).catch((error) =>\n console.error(\"[Think] The recovering status was not set\", error)\n );\n } else if (\n type === \"chat:recovery:completed\" ||\n type === \"chat:recovery:skipped\" ||\n type === \"chat:recovery:failed\" ||\n type === \"chat:recovery:exhausted\"\n ) {\n void this.#endRecovering(String(payload.requestId), true).catch(\n (error) =>\n console.error(\n \"[Think] The recovering status was not cleared\",\n error\n )\n );\n }\n // A reply that failed as it streamed is reported once, by the\n // turn's end below (a message error, then the failed request, as\n // in 0.24): the definition's own report of it is not repeated.\n if (type === \"chat:request:failed\" && payload.stage === \"stream\") {\n return;\n }\n // A give-up names the turn by its request id, as an app knows it.\n if (type === \"chat:recovery:exhausted\") {\n payload = withOperationIds(\n payload as unknown as ChatRecoveryExhaustedContext\n ) as unknown as Record<string, unknown>;\n }\n // As in 0.24: a request that could not be read is the app's\n // `onChatError` to hear, and the event carries what it returned.\n // (The tab's end frame is the dispatch's, with the parser's text.)\n if (type === \"chat:request:failed\" && payload.stage === \"parse\") {\n const wrapped = this.onChatError(new Error(String(payload.error)), {\n requestId: String(payload.requestId),\n stage: \"parse\",\n messagesPersisted: false\n });\n payload = { ...payload, error: errorText(wrapped) };\n }\n (\n this._emit as unknown as (\n type: string,\n payload: Record<string, unknown>\n ) => void\n ).call(this, type, payload);\n }\n };\n }\n\n /** Route this Agent's connections through ThinkChat's handlers. */\n #installProtocol(): void {\n const onConnect = this.onConnect.bind(this);\n this.onConnect = async (connection: Connection, ctx: ConnectionContext) => {\n // A sub-agent's tab is the sub-agent's to answer, as in 0.24. Asked\n // of the request: the connection is not marked as the child's yet.\n if (this._cf_requestTargetsSubAgent(ctx.request)) {\n return onConnect(connection, ctx);\n }\n // The session's open operations, read once for this connect: the\n // chat's connect and the resume offer below both ask.\n const open = await this.harness.session().pending();\n for (const handlers of this.#handlers) {\n await handlers.onConnect?.(connection, ctx, open);\n }\n // A turn streams or waits to: the tab is offered its stream through\n // the shared dispatch, the one resume path (H2c), as AIChatAgent's is.\n const session = this.harness.session().id;\n if (open.length > 0) {\n await resumeChat(\n this.harness.chatDeps(session, this.#chatHostDeps()),\n { ...this.harness.chatLane(session), arrival: this.#arrival() },\n connection\n );\n }\n return onConnect(connection, ctx);\n };\n const onMessage = this.onMessage.bind(this);\n this.onMessage = async (connection: Connection, message: WSMessage) => {\n if (this._cf_connectionTargetsSubAgent(connection)) {\n return onMessage(connection, message);\n }\n // As in 0.24: a browser's chat request runs on the `web` channel.\n const asked = chatRequestOf(message);\n const request = asked?.id;\n if (asked) {\n this.#webRequests.add(asked.id);\n if (asked.replies) this.#repliesSent.set(asked.id, asked.replies);\n }\n // A tab's chat frames go through the shared chat dispatch (H2c), onto\n // the harness's root session.\n const session = this.harness.session().id;\n // A stop of a turn that has started goes to the harness, the one\n // keeper of what it streamed (its reply's branch, client tools and\n // events); a request still waiting keeps its place on the dispatch.\n const stopped = cancelledRequestOf(message);\n if (stopped !== undefined) {\n const status = await this.harness.session().inspect(stopped);\n // A turn waiting out a retry's backoff is not running: the\n // dispatch ends it, keeps what it streamed and reports its\n // recovery as stopped by the user, as in 0.24.\n const waiting = this.tasks.peek(stopped);\n const backingOff =\n waiting?.status === \"pending\" && waiting.waitReason === \"retry\";\n // Nor is one a reset cut that has not been woken: no attempt runs\n // to end it, so the dispatch ends it, and its recovery with it.\n if (\n status?.status === \"running\" &&\n !backingOff &&\n this.harness.attemptRuns(session, stopped)\n ) {\n await this.harness.session().abort(stopped);\n return;\n }\n }\n if (\n await chatDispatch(\n this.harness.chatDeps(session, this.#chatHostDeps()),\n { ...this.harness.chatLane(session), arrival: this.#arrival() },\n connection,\n message,\n // A request that waits behind a turn shows on every tab at once:\n // when it is accepted, not when the dispatch returns (in a\n // sub-agent that is when its turn has ended).\n { accepted: () => this.#chat.showWaiting() }\n )\n ) {\n // A clear drops the client tools the tabs declared, with the chat:\n // the ones an earlier release kept too, if no start moved them yet.\n if (isChatClear(message)) {\n await this.harness.forgetClientTools(session);\n this.#clearReleasedRequestContext();\n }\n // A request the dispatch ended without a run (dropped, or refused)\n // is forgotten now; one that runs, when it settles.\n if (\n request !== undefined &&\n !(await this.harness.inspection(session, request))\n ) {\n this.#webRequests.delete(request);\n this.#repliesSent.delete(request);\n }\n return;\n }\n for (const handlers of this.#handlers) {\n if ((await handlers.onMessage?.(connection, message)) === true) {\n // A request that started nothing (refused, or a resend of one\n // that ended) is forgotten now; one that runs, when it settles.\n if (\n request !== undefined &&\n !(await this.harness.inspection(this.harness.session().id, request))\n ) {\n this.#webRequests.delete(request);\n this.#repliesSent.delete(request);\n }\n return;\n }\n }\n return onMessage(connection, message);\n };\n const onClose = this.onClose.bind(this);\n this.onClose = async (connection, code, reason, wasClean) => {\n // The chat's in-memory records of the tab go with it: the stream it\n // was offered, the resume it waited for.\n if (!this._cf_connectionTargetsSubAgent(connection)) {\n const session = this.harness.session().id;\n forgetTab(\n this.harness.chatDeps(session, this.#chatHostDeps()),\n connection.id\n );\n }\n if (this._cf_connectionTargetsSubAgent(connection)) {\n return onClose(connection, code, reason, wasClean);\n }\n for (const handlers of this.#handlers) {\n await handlers.onClose?.(connection, code, reason, wasClean);\n }\n return onClose(connection, code, reason, wasClean);\n };\n const onRequest = this.onRequest.bind(this);\n this.onRequest = async (request: Request) => {\n const handled =\n (await this.#chat.onRequest({ request })) ??\n (await this.#messengers?.receive(request));\n return handled ?? onRequest(request);\n };\n }\n // ── Detached agent-tool runs this agent started ──────────────────────\n\n /**\n * The message put back into the chat when a `detached: { notify: true }`\n * run ends, as 0.24 worded it. Override it (an empty string sends none).\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 * The message put into the chat when a `detached: { onMilestones }`\n * milestone is reached, as 0.24 worded it. Override it (an empty string\n * sends none).\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 * `detached: { notify: true }`: the run's end becomes a submitted turn,\n * once per run and status, as in 0.24.\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 * A milestone of a detached run, as in 0.24: `\"narrate\"` adds an\n * assistant line (no model call, once per run and name); `\"react\"`\n * submits a user turn (once per run and name).\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 /**\n * A detached run's delivery that could land mid-turn (`serialize`) waits\n * for the turn running now to end, as 0.24 ran it between turns; an\n * explicit cancel may come from inside a turn, so it runs at once.\n */\n protected override async _runDetachedDelivery(\n invoke: () => Promise<void>,\n options?: { serialize?: boolean }\n ): Promise<void> {\n if (options?.serialize) {\n const session = this.harness.session();\n for (const operation of await session.pending()) {\n if (operation.status === \"running\") {\n await session.wait(operation.operationId);\n }\n }\n }\n await super._runDetachedDelivery(invoke, options);\n }\n\n // ── As an agent tool ────────────────────────────────────────────────\n // A parent runs this agent as a tool through these methods. The run is\n // one operation of the root session, `agent-tool:<runId>`, so every\n // attempt of its turn (a reset replays it) stays that run.\n\n /** The message an agent-tool run's input becomes. */\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 /** A completed agent-tool run's output. Default: none. */\n protected getAgentToolOutput(_runId: string): unknown {\n return undefined;\n }\n\n /** A completed agent-tool run's summary. Default: its reply's text. */\n protected getAgentToolSummary(runId: string, output: unknown): string {\n const text = this.#agentToolReplyText.get(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 /** The text of a completed agent-tool run's reply, while its result is made. */\n readonly #agentToolReplyText = new Map<string, string>();\n\n /**\n * The agent-tool runs a release kept in its own tables\n * (`cf_agent_tool_child_runs`, with their milestones), onto the runs this\n * version reads, once: a finished one keeps its result, progress and\n * milestones; one still running ends as an error, since nothing here owns\n * its turn. A root drops the tables; a sub-agent empties them.\n */\n async #carryReleasedAgentToolRuns(): Promise<void> {\n await carryForwardAgentToolRuns(\n this.#agentToolDeps(),\n this.ctx.storage.sql,\n RELEASED_THINK_AGENT_TOOL_TABLES,\n this.harness.chatLane(this.harness.session().id).definition,\n // A run whose turn the release kept as a fiber waits for that fiber's\n // recovery, which carries the turn on as the run's and comes here\n // again.\n (requestId) => this.#releasedFiberTurnWaits(requestId)\n );\n }\n\n /** Whether a release's fiber for the turn of `requestId` is still open. */\n #releasedFiberTurnWaits(requestId: string): boolean {\n const name = `${RELEASED_CHAT_TURN_DEFINITION}:${requestId}`;\n // Still in the release's own fiber table: this start's carry of that\n // table comes after this step.\n if (legacyFiberOpen(this.ctx.storage, name)) return true;\n return this.tasks\n .peekList({ definition: FIBER_TASK, status: [\"pending\", \"running\"] })\n .some(\n (record) =>\n this.tasks.inputOf<{ name?: unknown }>(record.runId)?.name === name\n );\n }\n\n /** What a release's fiber turn stashed, before or after its carry. */\n #releasedFiberSnapshot(requestId: string): unknown {\n const name = `${RELEASED_CHAT_TURN_DEFINITION}:${requestId}`;\n const legacy = legacyFiberSnapshot(this.ctx.storage, name);\n if (legacy !== undefined) return legacy;\n const run = this.tasks\n .peekList({ definition: FIBER_TASK, status: [\"pending\", \"running\"] })\n .find(\n (record) =>\n this.tasks.inputOf<{ name?: unknown }>(record.runId)?.name === name\n );\n return run ? this.tasks.checkpointOf(run.runId, \"snapshot\") : undefined;\n }\n\n /** The chat module's side of this agent, for its agent-tool turns. */\n #agentToolDeps() {\n return this.harness.chatDeps(\n this.harness.session().id,\n this.#chatHostDeps()\n );\n }\n\n /**\n * Parents waiting for an agent-tool turn's stream to open, by the turn's\n * id: its first frame wakes them.\n */\n readonly #agentToolTailWaits = new Map<string, Set<() => void>>();\n\n /**\n * A frame a turn sends: it wakes the parents waiting on its turn, and a\n * chunk of a run started with `eventDelivery: \"terminal\"` is not sent to\n * this agent's own tabs, as in 0.24.\n */\n #agentToolFrame(text: string): \"send\" | \"suppress\" {\n if (\n this.#agentToolTailWaits.size === 0 &&\n !text.includes(AGENT_TOOL_OPERATION_PREFIX)\n ) {\n return \"send\";\n }\n let frame: { id?: unknown; done?: unknown };\n try {\n frame = JSON.parse(text) as { id?: unknown; done?: unknown };\n } catch {\n return \"send\";\n }\n if (typeof frame.id !== \"string\") return \"send\";\n const waiting = this.#agentToolTailWaits.get(frame.id);\n if (waiting) {\n this.#agentToolTailWaits.delete(frame.id);\n for (const wake of waiting) wake();\n }\n if (frame.done === true) {\n this.#agentToolTerminalOnly.delete(frame.id);\n return \"send\";\n }\n // Fixed when the run starts: read once per turn, not per frame.\n let terminalOnly = this.#agentToolTerminalOnly.get(frame.id);\n if (terminalOnly === undefined) {\n terminalOnly =\n agentToolTurnOf(this.#agentToolDeps(), frame.id)?.terminalOnly === true;\n this.#agentToolTerminalOnly.set(frame.id, terminalOnly);\n }\n return terminalOnly ? \"suppress\" : \"send\";\n }\n\n /**\n * Whether a streaming agent-tool turn sends this agent's tabs only its\n * end, by the turn's id, until its end frame.\n */\n readonly #agentToolTerminalOnly = new Map<string, boolean>();\n\n /**\n * `reportProgress`: frames coalesced as in 0.24, kept on the run's\n * metadata and put on its live reply, so a parent following it and this\n * agent's tabs see them as they come.\n */\n readonly #agentToolProgress = new AgentToolProgressEmitter({\n resolveActiveRun: () => {\n const requestId = runningChatTurn();\n if (!requestId) return null;\n const meta = agentToolTurnOf(this.#agentToolDeps(), requestId);\n return meta ? { runId: meta.runId, requestId } : null;\n },\n broadcast: (_requestId, body) => {\n const deps = this.#agentToolDeps();\n liveTurnsOf(deps.streams)\n .get(deps.session ?? \"\")\n ?.inject(JSON.parse(body) as UIMessageChunk);\n },\n persistSnapshot: (runId, snapshot, at) => {\n recordAgentToolProgress(this.#agentToolDeps(), agentToolTurnId(runId), {\n kind: \"progress\",\n snapshot: { ...snapshot, at }\n });\n },\n persistMilestone: (runId, name, data, at) => {\n const id = agentToolTurnId(runId);\n const fields = (\n this.tasks.peek(id)?.metadata as\n | { agentTool?: Record<string, unknown> }\n | undefined\n )?.agentTool;\n const sequence = Object.keys(fields ?? {}).filter((key) =>\n key.startsWith(\"milestone:\")\n ).length;\n recordAgentToolProgress(this.#agentToolDeps(), id, {\n kind: \"milestone\",\n milestone: {\n name,\n sequence,\n at,\n ...(data !== undefined && { data })\n } as AgentToolMilestone\n });\n return sequence;\n }\n });\n\n override async reportProgress<T = unknown>(\n progress: AgentToolProgress<T>,\n options?: { persist?: boolean }\n ): Promise<void> {\n if (this.#agentToolProgress.report(progress, options) === \"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 async startAgentToolRun(\n input: unknown,\n options: {\n runId: string;\n signal?: AbortSignal;\n eventDelivery?: \"full\" | \"terminal\";\n }\n ): Promise<AgentToolRunInspection> {\n const { runId } = options;\n const turnId = agentToolTurnId(runId);\n const deps = this.#agentToolDeps();\n // A start of a run this agent has returns it.\n if (!deps.tasks.peek(turnId)) {\n // A parent that stopped before the run started starts nothing.\n if (options.signal?.aborted) {\n return {\n runId,\n status: \"aborted\",\n startedAt: Date.now(),\n error: abortText(options.signal.reason) ?? \"cancelled\"\n };\n }\n await this.#refresh();\n this.#turns.set(turnId, { trigger: \"agent-tool\" });\n // The run is a server turn on the chat's lane under its own id.\n await startAgentToolTurn(\n deps,\n this.harness.chatLane(this.harness.session().id),\n runId,\n this.formatAgentToolInput(input),\n {\n terminalOnly: options.eventDelivery === \"terminal\",\n startMessageId: this.messages.at(-1)?.id ?? null\n }\n );\n }\n // A parent that stops while the run waits or runs cancels it.\n options.signal?.addEventListener(\n \"abort\",\n () => void this.cancelAgentToolRun(runId, options.signal?.reason),\n { once: true }\n );\n return (\n (await this.inspectAgentToolRun(runId)) ?? {\n runId,\n status: \"running\",\n startedAt: Date.now()\n }\n );\n }\n\n async cancelAgentToolRun(runId: string, reason?: unknown): Promise<void> {\n const id = agentToolTurnId(runId);\n // A stop with no reason is recorded with none, as in 0.24.\n const text = abortText(reason) ?? \"\";\n const status = this.tasks.peek(id)?.status;\n // Marked at once, so a parent reads it aborted before the stop lands.\n if (status === \"pending\" || status === \"running\") {\n this.tasks.patchMetadata(id, \"agentTool\", { cancelled: text });\n }\n // The harness keeps what a started turn streamed, and withdraws one\n // that waits. The run records the caller's reason, and none when the\n // caller gave none. The cancel returns once it is asked, as in 0.24:\n // the run already reads aborted, and a turn held in a hook that does\n // not watch its signal (an app's `onChatRecovery`) ends when it returns.\n const stopping = this.harness\n .abort(this.harness.session().id, id, text === \"\" ? undefined : text)\n .catch((error: unknown) => {\n console.error(\"[Think] An agent-tool run's stop failed\", error);\n });\n this.ctx.waitUntil(stopping);\n }\n\n async inspectAgentToolRun(\n runId: string,\n // `reconcile: false` asks for the stored state without sealing a stale\n // run first. This inspection never seals one (Tasks recovers a run\n // itself), so both read the same.\n _options?: { reconcile?: boolean }\n ): Promise<AgentToolRunInspection | null> {\n const inspection = await this.#inspectAgentToolRun(runId);\n // A stop that gave no reason reports none.\n if (inspection?.status === \"aborted\" && inspection.error === \"\") {\n const { error: _error, ...rest } = inspection;\n return rest as AgentToolRunInspection;\n }\n return inspection;\n }\n\n async #inspectAgentToolRun(\n runId: string\n ): Promise<AgentToolRunInspection | null> {\n const id = agentToolTurnId(runId);\n // How the operation ended is the harness's to say: its run's result is\n // the operation's outcome.\n // A run carried from a release was never the harness's operation: what\n // the release recorded stands.\n const meta = agentToolTurnOf(this.#agentToolDeps(), id) as\n | { result?: unknown; carriedInInput?: unknown }\n | undefined;\n const carried =\n meta?.carriedInInput === true ||\n (meta?.result !== undefined &&\n !isOperationOutcome(this.tasks.peek(id)?.result));\n const ended = carried\n ? undefined\n : await this.harness.inspection(this.harness.session().id, id);\n const unanswered = ended?.status === \"unanswered\" ? ended : undefined;\n const inspection = inspectAgentToolTurn(\n this.#agentToolDeps(),\n runId,\n (messageId) =>\n unanswered\n ? { output: undefined, summary: null }\n : this.#agentToolResult(runId, messageId)\n );\n if (!inspection || !unanswered) return inspection;\n const {\n output: _output,\n summary: _summary,\n ...base\n } = inspection as {\n output?: unknown;\n summary?: string;\n } & AgentToolRunInspection;\n // A turn reset skips the run, as in 0.24: an error, not a cancel.\n if (unanswered.abortReason === SKIPPED_BY_RESET) {\n return {\n ...base,\n status: \"error\",\n error: \"Agent tool run was skipped before the child could finish.\"\n };\n }\n if (inspection.status === \"aborted\") return inspection;\n if (\n unanswered.abortReason !== undefined ||\n unanswered.reason === \"aborted\" ||\n unanswered.reason === \"withdrawn\"\n ) {\n return {\n ...base,\n status: \"aborted\",\n ...(unanswered.abortReason !== undefined && {\n error: unanswered.abortReason\n })\n };\n }\n return {\n ...base,\n status: \"error\",\n error: saidOf(unanswered) ?? \"Agent tool run failed\"\n };\n }\n\n /**\n * A completed run's output and summary, made once from its reply and\n * kept on the run, so a later read returns the same result.\n */\n #agentToolResult(\n runId: string,\n messageId: string | undefined\n ): { output: unknown; summary: string | null } {\n const reply = messageId\n ? this.messages.find((message) => message.id === messageId)\n : undefined;\n const text = reply?.parts\n .map((part) => (part.type === \"text\" ? part.text : \"\"))\n .filter((part) => part.length > 0)\n .join(\"\\n\");\n if (text) this.#agentToolReplyText.set(runId, text);\n try {\n const output = this.getAgentToolOutput(runId);\n const summary = this.getAgentToolSummary(runId, output);\n this.tasks.patchMetadata(agentToolTurnId(runId), \"agentTool\", {\n result: {\n ...(output !== undefined && { output }),\n summary\n } as TaskJson\n });\n return { output, summary };\n } finally {\n this.#agentToolReplyText.delete(runId);\n }\n }\n\n async getAgentToolChunks(\n runId: string,\n options?: { afterSequence?: number }\n ): Promise<AgentToolStoredChunk[]> {\n return agentToolTurnChunks(this.#agentToolDeps(), runId, options);\n }\n\n /**\n * Follow the run: its chunks after `afterSequence`, then each chunk its\n * reply streams, until the run ends or `signal` aborts. Cancelling the\n * stream only detaches.\n *\n * The stream carries newline-delimited JSON, one chunk a line, as bytes:\n * a stream that crosses the sub-agent's RPC boundary can carry nothing\n * else. It is typed as the chunks it encodes, as released.\n */\n async tailAgentToolRun(\n runId: string,\n options?: { afterSequence?: number; signal?: AbortSignal }\n ): Promise<ReadableStream<AgentToolStoredChunk>> {\n return (await this.#tailAgentToolRunBytes(\n runId,\n options\n )) as unknown as ReadableStream<AgentToolStoredChunk>;\n }\n\n async #tailAgentToolRunBytes(\n runId: string,\n options?: { afterSequence?: number; signal?: AbortSignal }\n ): Promise<ReadableStream<Uint8Array>> {\n const tail = await tailAgentToolTurn(this.#agentToolDeps(), runId, options);\n if (tail) return tail;\n // Returned at once, so the parent's deadlines apply from here: a turn\n // that has not opened its stream is waited for in the first read.\n let inner: ReadableStreamDefaultReader<Uint8Array> | undefined;\n return new ReadableStream<Uint8Array>({\n pull: async (controller) => {\n inner ??= (\n await this.#agentToolTailOnceOpen(runId, options)\n ).getReader();\n const next = await inner.read();\n if (next.done) controller.close();\n else controller.enqueue(next.value);\n },\n cancel: async (reason) => {\n await inner?.cancel(reason);\n }\n });\n }\n\n /**\n * Run `runId`'s tail once its turn has opened its stream (its first frame\n * wakes the wait), or the chunks it has when it ended or was stopped.\n */\n async #agentToolTailOnceOpen(\n runId: string,\n options?: { afterSequence?: number; signal?: AbortSignal }\n ): Promise<ReadableStream<Uint8Array>> {\n const id = agentToolTurnId(runId);\n const open = () => {\n const status = this.tasks.peek(id)?.status;\n return status === \"pending\" || status === \"running\";\n };\n if (open() && !options?.signal?.aborted) {\n let wake!: () => void;\n const started = new Promise<void>((resolve) => (wake = resolve));\n const waits = this.#agentToolTailWaits.get(id) ?? new Set();\n waits.add(wake);\n this.#agentToolTailWaits.set(id, waits);\n // A stop wakes the wait too.\n options?.signal?.addEventListener(\"abort\", wake, { once: true });\n try {\n await Promise.race([started, this.tasks.wait(id).then(() => {})]);\n } finally {\n options?.signal?.removeEventListener(\"abort\", wake);\n waits.delete(wake);\n if (waits.size === 0 && this.#agentToolTailWaits.get(id) === waits) {\n this.#agentToolTailWaits.delete(id);\n }\n }\n if (!options?.signal?.aborted) {\n const tail = await tailAgentToolTurn(\n this.#agentToolDeps(),\n runId,\n options\n );\n if (tail) return tail;\n }\n }\n // Not streaming: the chunks there are, page by page, then the end.\n const encoder = new TextEncoder();\n let after = options?.afterSequence;\n return new ReadableStream<Uint8Array>({\n pull: async (controller) => {\n const page = await this.getAgentToolChunks(runId, {\n ...(after !== undefined && { afterSequence: after })\n });\n if (page.length === 0) {\n controller.close();\n return;\n }\n after = page[page.length - 1].sequence;\n controller.enqueue(\n encoder.encode(\n page.map((chunk) => `${JSON.stringify(chunk)}\\n`).join(\"\")\n )\n );\n }\n });\n }\n}\n\n/** A run id (`[\"\", operationId]`) as the operation id it names. */\nfunction operationIdOf(id: string): string {\n if (!id.startsWith(\"[\")) return id;\n try {\n const parsed: unknown = JSON.parse(id);\n return Array.isArray(parsed) && typeof parsed[1] === \"string\"\n ? parsed[1]\n : id;\n } catch {\n return id;\n }\n}\n\n/**\n * A recovery context with its ids as the operation ids an app knows, the\n * ones `onChatRecovery` is given: one incident id across every hook.\n */\nfunction withOperationIds<\n T extends {\n requestId: string;\n recoveryRootRequestId: string;\n incidentId?: string;\n streamId?: string;\n }\n>(ctx: T): T {\n return {\n ...ctx,\n requestId: operationIdOf(ctx.requestId),\n recoveryRootRequestId: operationIdOf(ctx.recoveryRootRequestId),\n // The definition derives both from the run id in its own formats\n // (`<run>:`, `chat-turn:<run>`); an app is given the operation id for\n // each, as `onChatRecovery` gives them.\n ...(ctx.incidentId !== undefined && {\n incidentId: operationIdOf(ctx.requestId)\n }),\n ...(ctx.streamId !== undefined && {\n streamId: operationIdOf(ctx.requestId)\n })\n };\n}\n\n/** Whether an operation's status says it was stopped (not failed). */\nfunction stoppedStatus(status: { status: string; reason?: string }): boolean {\n return (\n status.status === \"unanswered\" &&\n (status.reason === \"aborted\" || status.reason === \"withdrawn\")\n );\n}\n\n/** The operation an agent-tool run is. */\nconst AGENT_TOOL_OPERATION_PREFIX = \"agent-tool:\";\n\n/** Whether a run's result is a harness operation's outcome. */\nfunction isOperationOutcome(result: unknown): boolean {\n const status = (result as { status?: unknown } | undefined)?.status;\n return status === \"done\" || status === \"unanswered\";\n}\n\n/** The tables think@0.24.0 kept its agent-tool child runs in. */\nconst RELEASED_THINK_AGENT_TOOL_TABLES = {\n runs: \"cf_agent_tool_child_runs\",\n milestones: \"cf_agent_tool_milestones\"\n} as const;\n\n/** A cancel's reason as text, or `undefined` when none was given. */\nfunction abortText(reason: unknown): string | undefined {\n if (reason instanceof Error) return reason.message;\n return reason === undefined || reason === null ? undefined : String(reason);\n}\n\n/** A step that ended, waiting for its tools when it called any. */\ntype OpenStep = {\n readonly operationId: string;\n readonly step: number;\n readonly finishReason: string | undefined;\n /** Which of the reply's steps it is, counted by `step-start` parts. */\n readonly segment: number;\n /** The step's token usage, when the provider gave it. */\n readonly usage?: LanguageModelUsage;\n /** The AI SDK's record of the step's model call. */\n readonly record?: unknown;\n};\n\n/**\n * A turn's `timeout` for one of its model calls: the total is what is left\n * of it after `elapsedMs`, at least one millisecond so the call still ends\n * on the timeout; the per-step and per-chunk limits are per call already.\n */\nfunction remainingTurnTimeout(\n timeout: TurnConfig[\"timeout\"],\n elapsedMs: number\n): TurnConfig[\"timeout\"] {\n if (timeout === undefined) return undefined;\n if (typeof timeout === \"number\") return Math.max(1, timeout - elapsedMs);\n if (timeout.totalMs === undefined) return timeout;\n return { ...timeout, totalMs: Math.max(1, timeout.totalMs - elapsedMs) };\n}\n\n/** `over` merged onto `base`, plain objects key by key, as the AI SDK does. */\nfunction mergedOptions(base: unknown, over: unknown): unknown {\n const plain = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n if (over === undefined) return base;\n if (!plain(base) || !plain(over)) return over;\n const merged: Record<string, unknown> = { ...base };\n for (const [key, value] of Object.entries(over)) {\n merged[key] = mergedOptions(base[key], value);\n }\n return merged;\n}\n\n/** The fields of a `StepConfig` Think applies. */\ntype StepFields = {\n readonly providerOptions?: unknown;\n readonly model?: ThinkModel;\n readonly instructions?: unknown;\n readonly system?: unknown;\n readonly messages?: TurnConfig[\"messages\"];\n readonly activeTools?: readonly string[];\n readonly toolChoice?: unknown;\n};\n\n/**\n * The steps an operation's model calls made before this one, in the AI\n * SDK's step terms, from the reply they are on: the last message, when\n * this is not the first call.\n */\nfunction previousSteps(turn: ThinkTurnContext) {\n const reply = turn.messages.at(-1);\n if (turn.step === 0 || reply?.role !== \"assistant\") return [];\n const segments = stepSegments(reply);\n const steps = [];\n for (let segment = segments - turn.step + 1; segment <= segments; segment++) {\n steps.push(stepResultOf(reply, segment));\n }\n return steps;\n}\n\n/** How many steps a reply has, by its `step-start` parts. */\nfunction stepSegments(message: UIMessage): number {\n return message.parts.filter((part) => part.type === \"step-start\").length;\n}\n\n/**\n * What one step of the reply says (the `segment`-th, by `step-start`\n * parts), in the AI SDK's step terms: its text, reasoning, the tool calls\n * it made and the results it has.\n */\nfunction stepResultOf(message: UIMessage, segment: number) {\n const parts: UIMessage[\"parts\"] = [];\n let seen = 0;\n for (const part of message.parts) {\n if (part.type === \"step-start\") {\n seen += 1;\n continue;\n }\n // A reply without step parts is one step.\n if (seen === segment || (segment === 0 && seen === 0)) parts.push(part);\n }\n const toolCalls: unknown[] = [];\n const toolResults: unknown[] = [];\n for (const part of parts) {\n if (!isToolUIPart(part)) continue;\n const toolName = getToolName(part);\n toolCalls.push({\n type: \"tool-call\",\n toolCallId: part.toolCallId,\n toolName,\n input: part.input\n });\n if (part.state === \"output-available\") {\n toolResults.push({\n type: \"tool-result\",\n toolCallId: part.toolCallId,\n toolName,\n input: part.input,\n output: part.output\n });\n }\n }\n return {\n text: parts.map((part) => (part.type === \"text\" ? part.text : \"\")).join(\"\"),\n reasoningText:\n parts\n .map((part) => (part.type === \"reasoning\" ? part.text : \"\"))\n .join(\"\") || undefined,\n toolCalls,\n toolResults\n };\n}\n\n/**\n * A step's `instructions` or `system` as text: a string, or the text of\n * the system messages the AI SDK also takes there.\n */\nfunction systemText(value: unknown): string | undefined {\n if (typeof value === \"string\") return value;\n const messages = Array.isArray(value) ? value : value ? [value] : [];\n const texts = messages.flatMap((message: unknown) => {\n const content = (message as { content?: unknown } | null)?.content;\n return typeof content === \"string\" ? [content] : [];\n });\n return texts.length > 0 ? texts.join(\"\\n\\n\") : undefined;\n}\n\n/**\n * A UI chunk as the AI SDK's stream has it in Think's `onChunk`: a tool's\n * output is a `tool-result` (or `tool-error`) part, a delta carries its\n * `text`. Other chunks pass as they are.\n */\nfunction streamPartOf(\n chunk: UIMessageChunk,\n calls: Map<string, { toolName: string; input: unknown }>,\n stored: (\n toolCallId: string\n ) => { toolName: string; input: unknown } | undefined\n): unknown {\n const named = (toolCallId: string) =>\n calls.get(toolCallId) ?? stored(toolCallId);\n switch (chunk.type) {\n case \"tool-input-error\":\n // The AI SDK reports a call it couldn't parse as an invalid call.\n calls.set(chunk.toolCallId, {\n toolName: chunk.toolName,\n input: chunk.input\n });\n return {\n type: \"tool-call\",\n toolCallId: chunk.toolCallId,\n toolName: chunk.toolName,\n input: chunk.input,\n invalid: true,\n error: chunk.errorText,\n ...(chunk.providerExecuted && { providerExecuted: true }),\n ...(chunk.dynamic && { dynamic: true })\n };\n case \"tool-input-start\":\n return {\n type: \"tool-input-start\",\n id: chunk.toolCallId,\n toolName: chunk.toolName\n };\n case \"tool-input-delta\":\n return {\n type: \"tool-input-delta\",\n id: chunk.toolCallId,\n delta: chunk.inputTextDelta\n };\n case \"tool-input-available\": {\n // The call, as the AI SDK's stream has it; its result names it again.\n calls.set(chunk.toolCallId, {\n toolName: chunk.toolName,\n input: chunk.input\n });\n return {\n type: \"tool-call\",\n toolCallId: chunk.toolCallId,\n toolName: chunk.toolName,\n input: chunk.input,\n ...(chunk.providerExecuted && { providerExecuted: true }),\n ...(chunk.dynamic && { dynamic: true })\n };\n }\n case \"tool-output-available\":\n return {\n type: \"tool-result\",\n toolCallId: chunk.toolCallId,\n ...named(chunk.toolCallId),\n output: chunk.output,\n ...(chunk.preliminary && { preliminary: true })\n };\n case \"tool-output-error\":\n return {\n type: \"tool-error\",\n toolCallId: chunk.toolCallId,\n ...named(chunk.toolCallId),\n error: chunk.errorText\n };\n default:\n return \"delta\" in chunk ? { ...chunk, text: chunk.delta } : chunk;\n }\n}\n\n/** `fields` without its undefined ones. */\nfunction defined<T extends Record<string, unknown>>(fields: T): Partial<T> {\n return Object.fromEntries(\n Object.entries(fields).filter(([, value]) => value !== undefined)\n ) as Partial<T>;\n}\n\n/** The fields `folded` set or changed relative to `own`. */\nfunction changesOf(own: TurnConfig, folded: TurnConfig): TurnConfig {\n const changes: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(folded)) {\n if ((own as Record<string, unknown>)[key] !== value) changes[key] = value;\n }\n // SAFETY: every key is one of `folded`'s, a TurnConfig's.\n return changes as TurnConfig;\n}\n\n// The approval methods are client-callable, as in 0.24.\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\n/**\n * A browser's chat request, if `message` is one: its id, and the ids of the\n * assistant messages it sent, if any. The frame is parsed once here. Its\n * body is parsed only when it names an assistant message, which a tab's\n * list does once the chat has a reply: one parse of the list per such\n * request, beside the dispatch's own.\n */\nfunction chatRequestOf(\n message: WSMessage\n): { id: string; replies?: ReadonlySet<string> } | undefined {\n if (typeof message !== \"string\") return undefined;\n try {\n const frame = JSON.parse(message) as {\n type?: unknown;\n id?: unknown;\n init?: { body?: unknown };\n };\n if (\n frame.type !== \"cf_agent_use_chat_request\" ||\n typeof frame.id !== \"string\"\n ) {\n return undefined;\n }\n const body = frame.init?.body;\n if (typeof body !== \"string\" || !body.includes('\"assistant\"')) {\n return { id: frame.id };\n }\n const messages = (JSON.parse(body) as { messages?: unknown }).messages;\n const replies = new Set<string>();\n if (Array.isArray(messages)) {\n for (const sent of messages as Array<{ id?: unknown; role?: unknown }>) {\n if (sent.role === \"assistant\" && typeof sent.id === \"string\") {\n replies.add(sent.id);\n }\n }\n }\n return { id: frame.id, ...(replies.size > 0 && { replies }) };\n } catch {\n return undefined;\n }\n}\n\n/** The messenger context a user message keeps, if any. */\nfunction messengerOf(\n message: UIMessage | undefined\n): MessengerContext | undefined {\n const messenger = (message?.metadata as { messenger?: unknown } | undefined)\n ?.messenger;\n return messenger && typeof messenger === \"object\"\n ? (messenger as MessengerContext)\n : undefined;\n}\n\n/** Whether `value` is an async iterable (not a promise of one). */\nfunction isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { [Symbol.asyncIterator]?: unknown })[\n Symbol.asyncIterator\n ] === \"function\"\n );\n}\n\n/** `source`, each of its steps run through `inside`. */\nfunction stepsInside<T>(\n source: AsyncIterable<T>,\n inside: <R>(step: () => R) => R\n): AsyncIterable<T> {\n return {\n [Symbol.asyncIterator]() {\n const iterator = inside(() => source[Symbol.asyncIterator]());\n return {\n next: (...args: [] | [unknown]) => inside(() => iterator.next(...args)),\n return: (value?: unknown) =>\n inside(\n () =>\n iterator.return?.(value) ??\n Promise.resolve({ done: true as const, value: undefined as T })\n ),\n throw: (error?: unknown) =>\n inside(() => iterator.throw?.(error) ?? Promise.reject(error))\n };\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiBA,SAAgB,sBACd,YACoB;CACpB,QAAQ,WAAW,MAAnB;EACE,KAAK,QACH,OAAO,EACL,UAAU,eAAe,KAAK,UAC3B,WAAoC,SACrC,MACA,CACF,EAAE,UACJ;EACF,KAAK,eAAe;GAClB,MAAM,QAAQ;GACd,MAAM,QAAQ,CAAC,iBAAiB;GAChC,IAAI,MAAM,IAAI,QAAQ,MAAM,KAAK,OAAO,MAAM,GAAG,KAAK,IAAI,GAAG;GAC7D,IAAI,MAAM,SAAS,MAAM,KAAK,YAAY,MAAM,SAAS;GACzD,OAAO,EAAE,UAAU,MAAM,KAAK,IAAI,EAAE;EACtC;EACA,KAAK,cACH;EACF,SACE;CACJ;AACF;;;;;;AAOA,eAAsB,wBACpB,aACA,QACA,MACe;CACf,IAAI,CAAC,aAAa,QAChB;CAEF,KAAK,MAAM,cAAc,aAAa;EACpC,IAAI;EACJ,IAAI;GACF,WAAW,OAAO,UAAU;EAC9B,SAAS,OAAO;GACd,QAAQ,KACN,mCAAmC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAC1F;GACA;EACF;EACA,IAAI,aAAa,KAAA,GACf;EAEF,IAAI;GACF,MAAM,KAAK,QAAQ;EACrB,SAAS,OAAO;GACd,QAAQ,KACN,iDAAiD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GACxG;EACF;CACF;AACF;;;;;;;;;;;;;AChEA,MAAM,qBAAqB;CACzB;CACA;CACA;CACA;AACF;;;;;;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