@cloudflare/think 0.10.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/README.md +73 -17
  2. package/dist/{chat-sdk-Bb93yaZh.js → chat-sdk-D6cUghsQ.js} +33 -8
  3. package/dist/chat-sdk-D6cUghsQ.js.map +1 -0
  4. package/dist/cli/index.js +224 -55
  5. package/dist/cli/index.js.map +1 -1
  6. package/dist/{codegen-CuPdJRpV.js → codegen-DlA2QQuU.js} +6 -38
  7. package/dist/codegen-DlA2QQuU.js.map +1 -0
  8. package/dist/{config-D512sQYg.d.ts → config-CD7hqncK.d.ts} +5 -5
  9. package/dist/extensions/index.js +1 -1
  10. package/dist/fetch-By3eIQ-a.d.ts +147 -0
  11. package/dist/framework/index.d.ts +17 -62
  12. package/dist/framework/index.js +3 -57
  13. package/dist/{think-i1Pkgb1R.d.ts → index-CR4-ffm_.d.ts} +1734 -736
  14. package/dist/{manager-BPndMP_6.js → manager-CSk5htym.js} +7 -7
  15. package/dist/{manager-BPndMP_6.js.map → manager-CSk5htym.js.map} +1 -1
  16. package/dist/{manifest-CpB-xngB.d.ts → manifest-DK5HuGga.d.ts} +16 -18
  17. package/dist/messengers/index.d.ts +59 -55
  18. package/dist/messengers/index.js +2 -2
  19. package/dist/messengers/telegram.d.ts +4 -4
  20. package/dist/messengers/telegram.js +1 -1
  21. package/dist/react.d.ts +79 -0
  22. package/dist/react.js +28 -0
  23. package/dist/react.js.map +1 -0
  24. package/dist/server-entry.d.ts +1 -1
  25. package/dist/server-entry.js +1 -1
  26. package/dist/server-entry.js.map +1 -1
  27. package/dist/studio/assets/{angular-html-z-TUogET.js → angular-html-D27LthTc.js} +1 -1
  28. package/dist/studio/assets/{angular-ts-DMGuEVeg.js → angular-ts-DtNL2gQ7.js} +1 -1
  29. package/dist/studio/assets/{apl-KvrEROqd.js → apl-BgEcDqM0.js} +1 -1
  30. package/dist/studio/assets/{astro-Bm_woEti.js → astro-CstbRF9e.js} +1 -1
  31. package/dist/studio/assets/{blade-BdCF3r89.js → blade-CLG-7epG.js} +1 -1
  32. package/dist/studio/assets/{c-CDqDtkvZ.js → c-CssQqwxO.js} +1 -1
  33. package/dist/studio/assets/{cobol-CeFM1vZz.js → cobol-CjmzHCjg.js} +1 -1
  34. package/dist/studio/assets/{coffee-2ed6LBym.js → coffee-B_rqYPkp.js} +1 -1
  35. package/dist/studio/assets/{cpp-Dj3nX0J4.js → cpp-5YyZJlb7.js} +1 -1
  36. package/dist/studio/assets/{crystal-BsIYZMQ3.js → crystal-D7uKze0i.js} +1 -1
  37. package/dist/studio/assets/{css-B48fnuoH.js → css-k9oPgg7G.js} +1 -1
  38. package/dist/studio/assets/{edge-C7qt1aza.js → edge-CGgsSt0x.js} +1 -1
  39. package/dist/studio/assets/{elixir-CiTmwoQ3.js → elixir-BX_d5Evo.js} +1 -1
  40. package/dist/studio/assets/{elm-exDZ-PRY.js → elm-DENxDm5e.js} +1 -1
  41. package/dist/studio/assets/{erb-3fmfgt-Q.js → erb-DvYOup03.js} +1 -1
  42. package/dist/studio/assets/{git-rebase-75I-C7zW.js → git-rebase-BsAdTS5A.js} +1 -1
  43. package/dist/studio/assets/{glimmer-js-JjRzYRv8.js → glimmer-js-e0h98Z67.js} +1 -1
  44. package/dist/studio/assets/{glimmer-ts-DcC_g6bi.js → glimmer-ts-C9s5Kv8m.js} +1 -1
  45. package/dist/studio/assets/{glsl-CHo__hpu.js → glsl-CCiyeTRs.js} +1 -1
  46. package/dist/studio/assets/{graphql-J3cHpSdo.js → graphql-BRtHwsqk.js} +1 -1
  47. package/dist/studio/assets/{hack-or1FCnPg.js → hack-Dnt0QXHh.js} +1 -1
  48. package/dist/studio/assets/{haml-uv3vtlo6.js → haml-EXGmzuB1.js} +1 -1
  49. package/dist/studio/assets/{handlebars--xrOP0sp.js → handlebars-CzyBIDJE.js} +1 -1
  50. package/dist/studio/assets/{highlighted-body-OFNGDK62-D5UBAw6b.js → highlighted-body-OFNGDK62-CQUFKLNu.js} +1 -1
  51. package/dist/studio/assets/{html-CWnTqWKh.js → html-BAT8b_VM.js} +1 -1
  52. package/dist/studio/assets/{html-derivative-DWyLco-z.js → html-derivative-7tkS-r6F.js} +1 -1
  53. package/dist/studio/assets/{http-BGB8mLqf.js → http-Cgka02Qq.js} +1 -1
  54. package/dist/studio/assets/{hurl-BWdvIVUG.js → hurl-Cbkh8WEw.js} +1 -1
  55. package/dist/studio/assets/index-D6n8vpkp.js +390 -0
  56. package/dist/studio/assets/index-DkGWw6ES.css +2 -0
  57. package/dist/studio/assets/{java-BqyrPpKF.js → java-DrRKiUno.js} +1 -1
  58. package/dist/studio/assets/{javascript-D8Aej0xg.js → javascript-9LAnHOxD.js} +1 -1
  59. package/dist/studio/assets/{jinja-SIORrXov.js → jinja-CqRt4prs.js} +1 -1
  60. package/dist/studio/assets/{jison-B2T4v51n.js → jison-BX-IOQpJ.js} +1 -1
  61. package/dist/studio/assets/{json-BFdVRj9r.js → json-dOrE-En8.js} +1 -1
  62. package/dist/studio/assets/{jsx-w4r1xieS.js → jsx-BSTPfqWX.js} +1 -1
  63. package/dist/studio/assets/{julia-BFBtDmmM.js → julia-Dvz-BPmf.js} +1 -1
  64. package/dist/studio/assets/{just-CjAPsU_y.js → just-BHQm0Atq.js} +1 -1
  65. package/dist/studio/assets/{latex-CghDKqKz.js → latex-CxdhxuXv.js} +1 -1
  66. package/dist/studio/assets/{liquid-Cp9loVkE.js → liquid-D-hM-Q_F.js} +1 -1
  67. package/dist/studio/assets/{lua-HNnIDxnY.js → lua-5qtqjLHq.js} +1 -1
  68. package/dist/studio/assets/{marko-BXT10Apm.js → marko-5FJaM2co.js} +1 -1
  69. package/dist/studio/assets/{mdc-CaiOz4_A.js → mdc-BhYW7lCG.js} +1 -1
  70. package/dist/studio/assets/mermaid-GHXKKRXX-CWM2EB-u.js +1 -0
  71. package/dist/studio/assets/{nginx-DgYZ5SY9.js → nginx-rtAXrRye.js} +1 -1
  72. package/dist/studio/assets/{nim-CAMVX-MV.js → nim-DQSmaN9U.js} +1 -1
  73. package/dist/studio/assets/{perl-Dc6Wp7SD.js → perl-B54AdcaE.js} +1 -1
  74. package/dist/studio/assets/{php-DgLi8LNU.js → php-DpvTxCny.js} +1 -1
  75. package/dist/studio/assets/{pug-ZHFv4Vgd.js → pug-Cyffw0Ho.js} +1 -1
  76. package/dist/studio/assets/{qml-DU62cSZp.js → qml-CxRetSkO.js} +1 -1
  77. package/dist/studio/assets/{r-BwU69RSh.js → r-CXWRxrXc.js} +1 -1
  78. package/dist/studio/assets/{razor-BUgi_XZM.js → razor-BJzI-zc9.js} +1 -1
  79. package/dist/studio/assets/{regexp-DuNhqfkW.js → regexp-dqxdfrnE.js} +1 -1
  80. package/dist/studio/assets/{rst-BB3BeaSy.js → rst-BW7eKYj4.js} +1 -1
  81. package/dist/studio/assets/{ruby-T0tkEfUZ.js → ruby-D5Npyj8-.js} +1 -1
  82. package/dist/studio/assets/{sas-CMhZa3S0.js → sas-DZLppjul.js} +1 -1
  83. package/dist/studio/assets/{scss-DtXjZ3vZ.js → scss-CbqoxyAe.js} +1 -1
  84. package/dist/studio/assets/{shellscript-BESt-FLs.js → shellscript-CFHqBeXu.js} +1 -1
  85. package/dist/studio/assets/{shellsession-8irtvYxL.js → shellsession-CbZDA4Bf.js} +1 -1
  86. package/dist/studio/assets/{soy-CIvhOgLR.js → soy-PImjtV58.js} +1 -1
  87. package/dist/studio/assets/{sql-obAOXh1G.js → sql-DhGo8urW.js} +1 -1
  88. package/dist/studio/assets/{stata-D3OCK8xW.js → stata-CjHWbU2v.js} +1 -1
  89. package/dist/studio/assets/{surrealql-Dk_bguB0.js → surrealql-o8Qr4t56.js} +1 -1
  90. package/dist/studio/assets/{svelte-C0-KQt-t.js → svelte-DlSIyEV1.js} +1 -1
  91. package/dist/studio/assets/{templ-lg4nvF9H.js → templ-qizfwU1w.js} +1 -1
  92. package/dist/studio/assets/{tex-BNcQSX7R.js → tex-Ca7T661H.js} +1 -1
  93. package/dist/studio/assets/{ts-tags-AgW9jVv0.js → ts-tags-DUmjLkgl.js} +1 -1
  94. package/dist/studio/assets/{tsx-CL8XyR3d.js → tsx-CfwgIqHW.js} +1 -1
  95. package/dist/studio/assets/{twig-VkSbsH0Y.js → twig-D7NAYUBY.js} +1 -1
  96. package/dist/studio/assets/{typescript-BfD1znAG.js → typescript-Bbz9oX-P.js} +1 -1
  97. package/dist/studio/assets/{vue-html-w3sbjuft.js → vue-html-CcxTb_Jn.js} +1 -1
  98. package/dist/studio/assets/{vue-gv_2i8Vk.js → vue-vYpz06zQ.js} +1 -1
  99. package/dist/studio/assets/{vue-vine-C9sgcRlL.js → vue-vine-DW4RqCKF.js} +1 -1
  100. package/dist/studio/assets/{xml-nNPxMKnG.js → xml-R4LZ_u4f.js} +1 -1
  101. package/dist/studio/assets/{xsl-C7iHP36x.js → xsl-CS-xzp3L.js} +1 -1
  102. package/dist/studio/assets/{yaml-Cq3YaG6o.js → yaml-CqDWbYXd.js} +1 -1
  103. package/dist/studio/index.html +2 -2
  104. package/dist/think.d.ts +3 -2
  105. package/dist/think.js +8406 -2
  106. package/dist/think.js.map +1 -0
  107. package/dist/tools/extensions.js +1 -1
  108. package/dist/tools/fetch.d.ts +22 -0
  109. package/dist/tools/fetch.js +646 -0
  110. package/dist/tools/fetch.js.map +1 -0
  111. package/dist/tools/workspace.js +2 -2
  112. package/dist/tools/workspace.js.map +1 -1
  113. package/dist/{types-codegen-B6c5KpYH.js → types-codegen-C-9yeFao.js} +9 -33
  114. package/dist/types-codegen-C-9yeFao.js.map +1 -0
  115. package/dist/vite.d.ts +5 -5
  116. package/dist/vite.js +1 -1
  117. package/dist/workflows.d.ts +1 -1
  118. package/docs/actions.md +297 -0
  119. package/docs/channels.md +185 -0
  120. package/docs/client-tools.md +233 -0
  121. package/docs/getting-started.md +314 -0
  122. package/docs/index.md +1324 -0
  123. package/docs/lifecycle-hooks.md +850 -0
  124. package/docs/messengers.md +197 -0
  125. package/docs/programmatic-submissions.md +206 -0
  126. package/docs/sub-agents.md +524 -0
  127. package/docs/tools.md +582 -0
  128. package/docs/workflows.md +217 -0
  129. package/package.json +50 -17
  130. package/dist/chat-sdk-Bb93yaZh.js.map +0 -1
  131. package/dist/codegen-CuPdJRpV.js.map +0 -1
  132. package/dist/framework/index.js.map +0 -1
  133. package/dist/studio/assets/index-Cbb3GlZY.js +0 -496
  134. package/dist/studio/assets/index-DN9_cL01.css +0 -2
  135. package/dist/studio/assets/mermaid-GHXKKRXX-I2ZcYo7k.js +0 -1
  136. package/dist/think-BYZXQ-vm.js +0 -6513
  137. package/dist/think-BYZXQ-vm.js.map +0 -1
  138. package/dist/types-codegen-B6c5KpYH.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"think-BYZXQ-vm.js","names":["agentContext"],"sources":["../src/media-eviction.ts","../src/think.ts"],"sourcesContent":["/**\n * Aged-media eviction (#1710).\n *\n * Long-lived sessions accumulate inline base64 media — screenshot/image\n * tool results, data-URL file attachments — in the persisted transcript.\n * Read-time truncation hides that content from the model, but it stays in\n * storage forever and is rehydrated on every wake, so the boot footprint\n * grows with the number of images a session ever produced until SQLite's\n * allocator fails with `SQLITE_NOMEM`.\n *\n * This module rewrites oversized part values in AGED messages (the recent\n * tail is never touched) with small markers, optionally preserving the\n * original bytes as workspace files. Targets:\n *\n * - `file` parts whose `url` is a large `data:` URL — the part is\n * replaced with a text marker;\n * - large string values nested anywhere inside a tool part's `output` —\n * the string is replaced in place, preserving the container shape so\n * tool-specific `toModelOutput` handlers can still replay the result.\n *\n * Plain `text` parts are intentionally NOT evicted: they are user-visible\n * prose, and the row-size limit already bounds them at write time.\n */\n\nimport type { UIMessage } from \"ai\";\n\nexport interface MediaEvictionConfig {\n /**\n * Messages at the tail of the active path that are never evicted.\n * Think clamps this to at least the read-time truncation window\n * (4 messages — the recent span the model replays at full fidelity),\n * so a misconfigured low value can never strip content the model\n * still sees.\n * @default 8\n */\n keepRecentMessages?: number;\n /**\n * Minimum serialized size (in characters; base64 is ASCII so this equals\n * bytes for media) of a single part value to evict.\n * @default 32 * 1024\n */\n minPartBytes?: number;\n /**\n * Preserve evicted values as workspace files under\n * `/attachments/evicted/` instead of dropping them. The marker records\n * the file path.\n * @default true\n */\n externalizeToWorkspace?: boolean;\n /**\n * Maximum oversized stored rows processed per pass. Bounds how long a\n * single pass can take; remaining rows are picked up by later passes.\n * @default 64\n */\n maxRowsPerPass?: number;\n}\n\nexport interface ResolvedMediaEvictionConfig {\n keepRecentMessages: number;\n minPartBytes: number;\n externalizeToWorkspace: boolean;\n maxRowsPerPass: number;\n}\n\nexport function resolveMediaEvictionConfig(\n config: MediaEvictionConfig | boolean\n): ResolvedMediaEvictionConfig | null {\n if (config === false) return null;\n const base = config === true ? {} : config;\n return {\n keepRecentMessages: base.keepRecentMessages ?? 8,\n minPartBytes: base.minPartBytes ?? 32 * 1024,\n externalizeToWorkspace: base.externalizeToWorkspace ?? true,\n maxRowsPerPass: base.maxRowsPerPass ?? 64\n };\n}\n\n/** An oversized value extracted from a message, to be written to the workspace. */\nexport interface EvictedBlob {\n path: string;\n data: string;\n mediaType?: string;\n}\n\nexport interface EvictMessageResult {\n message: UIMessage;\n changed: boolean;\n /** Individual oversized values evicted. */\n parts: number;\n /** Total characters removed from the serialized message. */\n bytes: number;\n /** Values to persist before the rewritten row is stored (may be empty). */\n blobs: EvictedBlob[];\n}\n\nexport interface EvictMessageOptions {\n minPartBytes: number;\n /** When false, evicted values are dropped and markers record size only. */\n externalize: boolean;\n /** Workspace path for the n-th evicted value of this message. */\n pathFor: (index: number, extension: string) => string;\n}\n\nconst MAX_WALK_DEPTH = 8;\n\n/**\n * Replace oversized media values in a message with markers.\n * Returns a new message — the input is not mutated.\n */\nexport function evictLargeMediaFromMessage(\n message: UIMessage,\n options: EvictMessageOptions\n): EvictMessageResult {\n const state = {\n options,\n parts: 0,\n bytes: 0,\n blobs: [] as EvictedBlob[]\n };\n\n let changed = false;\n const parts = message.parts.map((part) => {\n // Large data-URL file attachments → text marker.\n if (part.type === \"file\" && \"url\" in part) {\n const url = (part as { url: string }).url;\n if (\n typeof url === \"string\" &&\n url.startsWith(\"data:\") &&\n url.length >= options.minPartBytes\n ) {\n changed = true;\n const mediaType =\n (part as { mediaType?: string }).mediaType ?? dataUrlMediaType(url);\n const path = extractBlob(state, url, mediaType);\n return {\n type: \"text\" as const,\n text: evictionMarker(url.length, path, mediaType)\n };\n }\n return part;\n }\n\n // Large strings nested in tool outputs → marker strings in place.\n if (\n (part.type.startsWith(\"tool-\") || part.type === \"dynamic-tool\") &&\n \"output\" in part\n ) {\n const output = (part as { output?: unknown }).output;\n if (output !== undefined) {\n const before = state.parts;\n const evicted = walkAndEvict(state, output, 0);\n if (state.parts > before) {\n changed = true;\n return { ...part, output: evicted };\n }\n }\n }\n\n return part;\n }) as UIMessage[\"parts\"];\n\n return {\n message: changed ? { ...message, parts } : message,\n changed,\n parts: state.parts,\n bytes: state.bytes,\n blobs: state.blobs\n };\n}\n\ntype WalkState = {\n options: EvictMessageOptions;\n parts: number;\n bytes: number;\n blobs: EvictedBlob[];\n};\n\nfunction walkAndEvict(\n state: WalkState,\n value: unknown,\n depth: number\n): unknown {\n if (typeof value === \"string\") {\n if (value.length < state.options.minPartBytes) return value;\n const mediaType = value.startsWith(\"data:\")\n ? dataUrlMediaType(value)\n : undefined;\n const path = extractBlob(state, value, mediaType);\n return evictionMarker(value.length, path, mediaType);\n }\n\n if (value === null || typeof value !== \"object\" || depth >= MAX_WALK_DEPTH) {\n return value;\n }\n\n if (Array.isArray(value)) {\n let changed = false;\n const result = value.map((item) => {\n const next = walkAndEvict(state, item, depth + 1);\n if (next !== item) changed = true;\n return next;\n });\n return changed ? result : value;\n }\n\n let changed = false;\n const result: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n const next = walkAndEvict(state, entry, depth + 1);\n if (next !== entry) changed = true;\n result[key] = next;\n }\n return changed ? result : value;\n}\n\n/** Record an evicted value; returns its workspace path or null when dropped. */\nfunction extractBlob(\n state: WalkState,\n data: string,\n mediaType: string | undefined\n): string | null {\n state.parts++;\n state.bytes += data.length;\n if (!state.options.externalize) return null;\n const path = state.options.pathFor(\n state.blobs.length,\n extensionFor(mediaType)\n );\n state.blobs.push({ path, data, mediaType });\n return path;\n}\n\nfunction evictionMarker(\n bytes: number,\n path: string | null,\n mediaType?: string\n): string {\n const media = mediaType ? `${mediaType}, ` : \"\";\n return path\n ? `[evicted ${media}${bytes} bytes; preserved at ${path}]`\n : `[evicted ${media}${bytes} bytes]`;\n}\n\nfunction dataUrlMediaType(url: string): string | undefined {\n const match = /^data:([^;,]+)/.exec(url);\n return match?.[1] || undefined;\n}\n\nfunction extensionFor(mediaType: string | undefined): string {\n if (!mediaType) return \"txt\";\n const subtype = mediaType.split(\"/\")[1]?.replace(/[^a-zA-Z0-9]/g, \"\");\n return subtype || \"bin\";\n}\n","/**\n * Think — an opinionated chat agent base class.\n *\n * Works as both a **top-level agent** (speaking the `cf_agent_chat_*`\n * WebSocket protocol to browser clients) and a **sub-agent** (called\n * via `chat()` over RPC from a parent agent).\n *\n * Each instance gets its own SQLite storage backed by Session — providing\n * tree-structured messages, context blocks, compaction, FTS5 search, and\n * multi-session support.\n *\n * Configuration overrides:\n * - getModel() — return the LanguageModel to use\n * - getSystemPrompt() — return the system prompt (fallback when no context blocks)\n * - getTools() — return the ToolSet for the agentic loop\n * - maxSteps — max tool-call rounds per turn (default: 10)\n * - configureSession() — add context blocks, compaction, search, skills\n *\n * Lifecycle hooks:\n * - beforeTurn() — inspect/override context, tools, model before inference\n * - beforeStep() — per-step callback to override model, messages, tool selection\n * - beforeToolCall() — intercept tool calls (block, modify args, substitute result)\n * - afterToolCall() — inspect tool results after execution\n * - onStepFinish() — per-step callback (logging, analytics)\n * - onChunk() — per-chunk callback (streaming analytics)\n * - onChatResponse() — post-turn lifecycle hook (logging, chaining, analytics)\n * - onChatError() — customize error handling\n *\n * Production features:\n * - WebSocket chat protocol (compatible with useAgentChat / useChat)\n * - Sub-agent RPC streaming via StreamCallback\n * - Session-backed storage with tree-structured messages\n * - Context blocks with LLM-writable persistent memory\n * - Non-destructive compaction (summaries replace ranges at read time)\n * - FTS5 full-text search across conversation history\n * - Abort/cancel support via AbortRegistry\n * - Error handling with partial message persistence\n * - Message sanitization (strips OpenAI ephemeral metadata)\n * - Row size enforcement (compacts large tool outputs)\n * - Resumable streams (replay on reconnect)\n *\n * @experimental The API surface may change before stabilizing.\n *\n * @example\n * ```typescript\n * import { Think } from \"@cloudflare/think\";\n * import { createWorkersAI } from \"workers-ai-provider\";\n *\n * export class MyAgent extends Think<Env> {\n * getModel() {\n * return createWorkersAI({ binding: this.env.AI })(\"@cf/moonshotai/kimi-k2.7-code\");\n * }\n *\n * getSystemPrompt() {\n * return \"You are a helpful coding assistant.\";\n * }\n * }\n * ```\n *\n * @example With context blocks and self-updating memory\n * ```typescript\n * import { Think } from \"@cloudflare/think\";\n * import type { Session } from \"@cloudflare/think\";\n *\n * export class MemoryAgent extends Think<Env> {\n * getModel() { ... }\n *\n * configureSession(session: Session) {\n * return session\n * .withContext(\"soul\", {\n * provider: { get: async () => \"You are a helpful coding assistant.\" }\n * })\n * .withContext(\"memory\", {\n * description: \"Important facts learned during conversation.\",\n * maxTokens: 2000\n * })\n * .withCachedPrompt();\n * }\n * }\n * ```\n */\n\nimport type {\n LanguageModel,\n ModelMessage,\n PrepareStepFunction,\n PrepareStepResult,\n StreamTextOnChunkCallback,\n StreamTextOnStepFinishCallback,\n StreamTextOnToolCallFinishCallback,\n StopCondition,\n ToolSet,\n TypedToolCall,\n UIMessage\n} from \"ai\";\nimport {\n convertToModelMessages,\n hasToolCall,\n jsonSchema,\n stepCountIs,\n streamText,\n tool\n} from \"ai\";\nimport * as skills from \"agents/skills\";\nimport { SkillRegistry } from \"agents/skills\";\nimport type { SkillScriptRunner, SkillSource } from \"agents/skills\";\n\n// Re-export AI SDK types that appear on Think's public lifecycle hooks\n// so users can import them from a single place.\nexport type {\n PrepareStepFunction,\n PrepareStepResult,\n StepResult,\n StopCondition,\n TextStreamPart,\n TypedToolCall,\n TypedToolResult\n} from \"ai\";\nexport { skills };\nexport type { SkillRunContext, SkillSource } from \"agents/skills\";\nimport {\n Agent,\n callable,\n getCurrentAgent,\n isPlatformTransientError,\n __DO_NOT_USE_WILL_BREAK__agentContext as agentContext\n} from \"agents\";\n\nconst agentToolChunkEncoder = new TextEncoder();\nimport type {\n Connection,\n FiberRecoveryContext,\n RetryOptions,\n WSMessage\n} from \"agents\";\nimport {\n sanitizeMessage,\n enforceRowSizeLimit,\n StreamAccumulator,\n CHAT_MESSAGE_TYPES,\n TurnQueue,\n ResumableStream,\n ContinuationState,\n SubmitConcurrencyController,\n createToolsFromClientSchemas,\n AbortRegistry,\n applyToolUpdate,\n toolResultUpdate,\n crossMessageToolResultUpdate,\n toolApprovalUpdate,\n pausedExecutionUpdate,\n parseProtocolMessage,\n applyChunkToParts,\n normalizeToolInput,\n reconcileMessages,\n resolveToolMergeId,\n createChatFiberSnapshot,\n unwrapChatFiberSnapshot,\n wrapChatFiberSnapshot,\n MAX_BOUND_PARAMS,\n buildInClauseStrings\n} from \"agents/chat\";\nimport type {\n StreamChunkData,\n ClientToolSchema,\n ClientToolExecutor,\n MessagePart,\n SubmitConcurrencyDecision,\n ChatFiberSnapshot\n} from \"agents/chat\";\nimport { Session } from \"agents/experimental/memory/session\";\nimport { truncateOlderMessages } from \"agents/experimental/memory/utils\";\nimport {\n evictLargeMediaFromMessage,\n resolveMediaEvictionConfig,\n type MediaEvictionConfig,\n type ResolvedMediaEvictionConfig\n} from \"./media-eviction\";\n\n/**\n * The recent-message span the model sees at FULL fidelity each turn —\n * `truncateOlderMessages`' default `keepRecent` (see `_assembleModelMessages`).\n *\n * Both memory bounds are anchored to this window (#1710):\n * - budgeted hydration never shrinks `this.messages` below it (the floor\n * passed to `session.getRecentHistory`), so windowing cannot starve the\n * model's context;\n * - media eviction never rewrites messages inside it (the\n * `keepRecentMessages` clamp), so content the model still replays at full\n * fidelity is never replaced with markers.\n */\nconst MODEL_RECENT_WINDOW = 4;\nimport { Workspace } from \"@cloudflare/shell\";\nimport { createWorkspaceTools } from \"./tools/workspace\";\nimport { truncatePausedExecutionOutput } from \"./tools/execute\";\nimport { ExtensionManager, sanitizeName } from \"./extensions/manager\";\nimport { ThinkMessengerRuntime } from \"./messengers/chat-sdk\";\nimport type {\n MessengerContext,\n ThinkMessengers,\n MessengerThinkHost\n} from \"./messengers\";\n\nexport { Session } from \"agents/experimental/memory/session\";\nexport { Workspace } from \"@cloudflare/shell\";\nexport type { FiberContext, FiberRecoveryContext } from \"agents\";\nexport type { WorkspaceLike } from \"./tools/workspace\";\nimport type { WorkspaceLike } from \"./tools/workspace\";\n\n// ── Wire protocol constants ────────────────────────────────────────\nconst MSG_CHAT_MESSAGES = CHAT_MESSAGE_TYPES.CHAT_MESSAGES;\nconst MSG_CHAT_RESPONSE = CHAT_MESSAGE_TYPES.USE_CHAT_RESPONSE;\nconst MSG_CHAT_CLEAR = CHAT_MESSAGE_TYPES.CHAT_CLEAR;\nconst MSG_STREAM_RESUMING = CHAT_MESSAGE_TYPES.STREAM_RESUMING;\nconst MSG_STREAM_RESUME_NONE = CHAT_MESSAGE_TYPES.STREAM_RESUME_NONE;\nconst MSG_MESSAGE_UPDATED = CHAT_MESSAGE_TYPES.MESSAGE_UPDATED;\nconst MSG_CHAT_RECOVERING = CHAT_MESSAGE_TYPES.CHAT_RECOVERING;\n\nfunction sendIfOpen(connection: Connection, message: string): boolean {\n try {\n connection.send(message);\n return true;\n } catch (error) {\n if (isWebSocketClosedSendError(error)) return false;\n throw error;\n }\n}\n\nfunction isWebSocketClosedSendError(error: unknown): boolean {\n return (\n error instanceof TypeError &&\n error.message.includes(\"WebSocket send() after close\")\n );\n}\n\nfunction shouldMarkSkippedAfterGenerationChange(\n status: SaveMessagesResult[\"status\"]\n): boolean {\n return status === \"completed\";\n}\n\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== \"object\") {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return `[${value.map((item) => stableStringify(item)).join(\",\")}]`;\n }\n const record = value as Record<string, unknown>;\n return `{${Object.keys(record)\n .sort()\n .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`)\n .join(\",\")}}`;\n}\n\nfunction stableHash(value: unknown): string {\n const input = stableStringify(value);\n let h1 = 1779033703;\n let h2 = 3144134277;\n let h3 = 1013904242;\n let h4 = 2773480762;\n for (let i = 0; i < input.length; i++) {\n const code = input.charCodeAt(i);\n h1 = h2 ^ Math.imul(h1 ^ code, 597399067);\n h2 = h3 ^ Math.imul(h2 ^ code, 2869860233);\n h3 = h4 ^ Math.imul(h3 ^ code, 951274213);\n h4 = h1 ^ Math.imul(h4 ^ code, 2716044179);\n }\n h1 = Math.imul(h3 ^ (h1 >>> 18), 597399067);\n h2 = Math.imul(h4 ^ (h2 >>> 22), 2869860233);\n h3 = Math.imul(h1 ^ (h3 >>> 17), 951274213);\n h4 = Math.imul(h2 ^ (h4 >>> 19), 2716044179);\n return [h1, h2, h3, h4]\n .map((part) => (part >>> 0).toString(16).padStart(8, \"0\"))\n .join(\"\");\n}\n\nfunction validateTimezone(timezone: string): string {\n try {\n const formatter = new Intl.DateTimeFormat(\"en-US\", { timeZone: timezone });\n return formatter.resolvedOptions().timeZone;\n } catch {\n throw new Error(`Invalid timezone \"${timezone}\"`);\n }\n}\n\nfunction parseTime(value: string): { hour: number; minute: number } {\n const match = /^([01]\\d|2[0-3]):([0-5]\\d)$/.exec(value);\n if (!match) {\n throw new Error(`Invalid schedule time \"${value}\"; expected HH:mm`);\n }\n return { hour: Number(match[1]), minute: Number(match[2]) };\n}\n\nconst declaredScheduleDayNumbers: Record<string, number> = {\n sun: 0,\n sunday: 0,\n mon: 1,\n monday: 1,\n tue: 2,\n tuesday: 2,\n wed: 3,\n wednesday: 3,\n thu: 4,\n thursday: 4,\n fri: 5,\n friday: 5,\n sat: 6,\n saturday: 6\n};\n\nfunction parseDeclaredTaskSchedule(\n rawSchedule: string,\n taskTimezone: string | undefined,\n defaultTimezone: string | undefined\n): ParsedDeclaredSchedule {\n const result = tryParseDeclaredTaskSchedule(\n rawSchedule,\n taskTimezone,\n defaultTimezone\n );\n if (!result.ok) throw new Error(result.error);\n return result.schedule;\n}\n\nfunction tryParseDeclaredTaskSchedule(\n rawSchedule: string,\n taskTimezone: string | undefined,\n defaultTimezone: string | undefined\n): ParseDeclaredScheduleResult {\n try {\n return {\n ok: true,\n schedule: parseDeclaredTaskScheduleUnchecked(\n rawSchedule,\n taskTimezone,\n defaultTimezone\n )\n };\n } catch (error) {\n return {\n ok: false,\n error: error instanceof Error ? error.message : String(error)\n };\n }\n}\n\nfunction parseDeclaredTaskScheduleUnchecked(\n rawSchedule: string,\n taskTimezone: string | undefined,\n defaultTimezone: string | undefined\n): ParsedDeclaredSchedule {\n const trimmed = rawSchedule.trim().replace(/\\s+/g, \" \").toLowerCase();\n const inlineTimezoneMatch = /^(.*) in ([A-Za-z_][A-Za-z0-9_+\\-/]*)$/.exec(\n trimmed\n );\n const schedule = inlineTimezoneMatch?.[1] ?? trimmed;\n const inlineTimezone = inlineTimezoneMatch?.[2];\n if (\n inlineTimezone &&\n taskTimezone &&\n validateTimezone(inlineTimezone) !== validateTimezone(taskTimezone)\n ) {\n throw new Error(\n `Schedule timezone \"${inlineTimezone}\" does not match task timezone \"${taskTimezone}\"`\n );\n }\n\n const intervalMatch = /^every ([1-9]\\d*) (minute|minutes|hour|hours)$/.exec(\n schedule\n );\n if (intervalMatch) {\n if (inlineTimezone || taskTimezone) {\n throw new Error(\"Interval schedules cannot specify a timezone\");\n }\n const count = Number(intervalMatch[1]);\n const unit = intervalMatch[2];\n if (count === 1 && unit.endsWith(\"s\")) {\n throw new Error(`Use singular unit for \"${rawSchedule}\"`);\n }\n if (count !== 1 && !unit.endsWith(\"s\")) {\n throw new Error(`Use plural unit for \"${rawSchedule}\"`);\n }\n return {\n kind: \"interval\",\n intervalMs: count * (unit.startsWith(\"hour\") ? 60 * 60_000 : 60_000),\n normalizedSchedule: `every ${count} ${unit}`\n };\n }\n\n const timezone = inlineTimezone ?? taskTimezone ?? defaultTimezone;\n if (!timezone) {\n throw new Error(\n `Wall-clock schedule \"${rawSchedule}\" requires a timezone or getDefaultTimezone()`\n );\n }\n const resolvedTimezone = validateTimezone(timezone);\n\n const dailyMatch = /^every day at ([0-2]\\d:[0-5]\\d)$/.exec(schedule);\n if (dailyMatch) {\n const { hour, minute } = parseTime(dailyMatch[1]);\n return {\n kind: \"wall-clock\",\n normalizedSchedule: `every day at ${dailyMatch[1]}`,\n timezone: resolvedTimezone,\n hour,\n minute,\n days: \"daily\"\n };\n }\n\n const weekdayMatch = /^every weekday at ([0-2]\\d:[0-5]\\d)$/.exec(schedule);\n if (weekdayMatch) {\n const { hour, minute } = parseTime(weekdayMatch[1]);\n return {\n kind: \"wall-clock\",\n normalizedSchedule: `every weekday at ${weekdayMatch[1]}`,\n timezone: resolvedTimezone,\n hour,\n minute,\n days: \"weekday\"\n };\n }\n\n const weeklyMatch = /^every week on ([a-z,\\s]+) at ([0-2]\\d:[0-5]\\d)$/.exec(\n schedule\n );\n if (weeklyMatch) {\n const seen = new Set<number>();\n const days = weeklyMatch[1].split(\",\").map((day) => {\n const normalized = day.trim();\n const dayNumber = declaredScheduleDayNumbers[normalized];\n if (dayNumber === undefined) {\n throw new Error(`Invalid schedule day \"${normalized}\"`);\n }\n if (seen.has(dayNumber)) {\n throw new Error(`Duplicate schedule day \"${normalized}\"`);\n }\n seen.add(dayNumber);\n return dayNumber;\n });\n if (days.length === 0) {\n throw new Error(\"Weekly schedule requires at least one day\");\n }\n const { hour, minute } = parseTime(weeklyMatch[2]);\n return {\n kind: \"wall-clock\",\n normalizedSchedule: `every week on ${weeklyMatch[1]\n .split(\",\")\n .map((day) => day.trim())\n .join(\",\")} at ${weeklyMatch[2]}`,\n timezone: resolvedTimezone,\n hour,\n minute,\n days\n };\n }\n\n throw new Error(`Unsupported schedule DSL \"${rawSchedule}\"`);\n}\n\nfunction getZonedParts(date: Date, timezone: string): ZonedParts {\n const parts = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: timezone,\n calendar: \"iso8601\",\n numberingSystem: \"latn\",\n weekday: \"short\",\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hourCycle: \"h23\"\n }).formatToParts(date);\n const part = (type: Intl.DateTimeFormatPartTypes) =>\n parts.find((entry) => entry.type === type)?.value ?? \"\";\n return {\n year: Number(part(\"year\")),\n month: Number(part(\"month\")),\n day: Number(part(\"day\")),\n hour: Number(part(\"hour\")),\n minute: Number(part(\"minute\")),\n second: Number(part(\"second\")),\n weekday: [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"].indexOf(\n part(\"weekday\")\n )\n };\n}\n\nfunction compareLocalParts(\n left: Pick<ZonedParts, \"year\" | \"month\" | \"day\" | \"hour\" | \"minute\">,\n right: Pick<ZonedParts, \"year\" | \"month\" | \"day\" | \"hour\" | \"minute\">\n): number {\n const fields = [\"year\", \"month\", \"day\", \"hour\", \"minute\"] as const;\n for (const field of fields) {\n const diff = left[field] - right[field];\n if (diff !== 0) return diff;\n }\n return 0;\n}\n\nfunction findZonedInstant(\n target: Pick<ZonedParts, \"year\" | \"month\" | \"day\" | \"hour\" | \"minute\">,\n timezone: string\n): Date {\n const approximate = Date.UTC(\n target.year,\n target.month - 1,\n target.day,\n target.hour,\n target.minute\n );\n const start = approximate - 14 * 60 * 60_000;\n const end = approximate + 14 * 60 * 60_000;\n for (let time = start; time <= end; time += 60_000) {\n const candidate = new Date(time);\n const parts = getZonedParts(candidate, timezone);\n if (compareLocalParts(parts, target) === 0) return candidate;\n }\n for (let time = start; time <= end; time += 60_000) {\n const candidate = new Date(time);\n const parts = getZonedParts(candidate, timezone);\n if (compareLocalParts(parts, target) > 0) return candidate;\n }\n throw new Error(`Unable to resolve local time in timezone \"${timezone}\"`);\n}\n\nfunction addLocalDays(\n parts: Pick<ZonedParts, \"year\" | \"month\" | \"day\">,\n days: number\n): Pick<ZonedParts, \"year\" | \"month\" | \"day\"> {\n const date = new Date(\n Date.UTC(parts.year, parts.month - 1, parts.day + days)\n );\n return {\n year: date.getUTCFullYear(),\n month: date.getUTCMonth() + 1,\n day: date.getUTCDate()\n };\n}\n\nfunction isAllowedWallClockDay(\n weekday: number,\n days: ParsedDeclaredSchedule & { kind: \"wall-clock\" }\n): boolean {\n if (days.days === \"daily\") return true;\n if (days.days === \"weekday\") return weekday >= 1 && weekday <= 5;\n return days.days.includes(weekday);\n}\n\nfunction nextDeclaredScheduleTime(\n schedule: ParsedDeclaredSchedule,\n now: Date,\n previousScheduledFor?: number\n): Date {\n if (schedule.kind === \"interval\") {\n let next =\n previousScheduledFor === undefined\n ? now.getTime() + schedule.intervalMs\n : previousScheduledFor + schedule.intervalMs;\n while (next <= now.getTime()) next += schedule.intervalMs;\n return new Date(next);\n }\n\n const nowParts = getZonedParts(now, schedule.timezone);\n for (let offset = 0; offset < 370; offset++) {\n const localDate = addLocalDays(nowParts, offset);\n const candidate = findZonedInstant(\n {\n ...localDate,\n hour: schedule.hour,\n minute: schedule.minute\n },\n schedule.timezone\n );\n const weekday = getZonedParts(candidate, schedule.timezone).weekday;\n if (!isAllowedWallClockDay(weekday, schedule)) continue;\n if (candidate.getTime() > now.getTime()) return candidate;\n }\n throw new Error(\"Unable to compute next scheduled task occurrence\");\n}\n\ntype StreamResultStatus = {\n status: Exclude<SaveMessagesResult[\"status\"], \"skipped\">;\n error?: string;\n output?: unknown;\n};\n\ntype ProgrammaticMessagesResult = SaveMessagesResult & {\n output?: unknown;\n};\n\ntype ChatRecoveryRetryData = {\n targetUserId?: string;\n originalRequestId?: string;\n incidentId?: string;\n lastBody?: Record<string, unknown> | null;\n lastClientTools?: ClientToolSchema[] | null;\n recoveredRequestId?: string;\n};\n\ntype ChatRecoveryContinueData = {\n targetAssistantId?: string;\n originalRequestId?: string;\n incidentId?: string;\n lastBody?: Record<string, unknown> | null;\n lastClientTools?: ClientToolSchema[] | null;\n recoveredRequestId?: string;\n};\n\n/**\n * Thrown by `_iterateWithStallWatchdog` when the inactivity watchdog fires\n * (a model/transport stream that parks without ever throwing). Distinct from\n * in-band model/stream errors so the read-loop catch can route a stall into\n * bounded recovery (#1626) — a transient hang is retried within the existing\n * recovery budget — while genuine errors stay terminal.\n */\nclass ChatStreamStalledError extends Error {\n readonly isChatStreamStall = true;\n constructor(message: string) {\n super(message);\n this.name = \"ChatStreamStalledError\";\n }\n}\n\ntype ChatRecoveryKind = \"retry\" | \"continue\";\n\ntype ChatRecoveryIncident = {\n incidentId: string;\n requestId: string;\n /**\n * Stable root requestId for the whole continuation chain. The durable\n * submission is keyed by this (not the per-attempt `requestId`, which is\n * overwritten each continuation), so terminal paths must use it to mark the\n * submission. Optional for backward-compat with incidents persisted before\n * this field existed — fall back to `requestId`.\n */\n recoveryRootRequestId?: string;\n recoveryKind: ChatRecoveryKind;\n attempt: number;\n maxAttempts: number;\n status:\n | \"detected\"\n | \"scheduled\"\n | \"attempting\"\n | \"completed\"\n | \"skipped\"\n | \"exhausted\"\n | \"failed\";\n firstSeenAt: number;\n lastAttemptAt: number;\n /**\n * Epoch ms of the last attempt that observed forward progress. The recovery\n * budget is keyed to this (`now - lastProgressAt > NO_PROGRESS_WINDOW`), so a\n * turn that keeps producing content survives churn indefinitely while a\n * genuinely stuck turn is sealed within the window (#1637). Optional for\n * backward-compat — falls back to `firstSeenAt`.\n */\n lastProgressAt?: number;\n reason?: string;\n /**\n * High-water mark of the durable, monotonic recovery-progress counter (see\n * `_chatRecoveryProgressMarker`) observed for this incident. Used to\n * distinguish a turn that is making forward progress but keeps getting\n * interrupted by isolate resets (deploys) — which should NOT exhaust the\n * budget — from one that genuinely fails to advance. Sourced from a persisted\n * counter rather than the live transcript so compaction cannot lower it\n * (#1628).\n */\n progress?: number;\n /**\n * Value of the durable progress counter when this incident first opened. The\n * runaway-loop work budget is `progress - workBaseline` (work produced since\n * the incident began); compared against `maxRecoveryWork`. Optional for\n * backward-compat with incidents persisted before this field existed — a\n * missing baseline is treated as the current marker (zero work so far), so an\n * in-flight incident from an older build is never falsely sealed.\n */\n workBaseline?: number;\n};\n\nconst CHAT_RECOVERY_INCIDENT_KEY_PREFIX = \"cf:chat-recovery:incident:\";\n// Durable, monotonic forward-progress counter for recovery budget resets.\n// Bumped on each durable content flush (`_storeChunkDurably`) — production time,\n// so it reflects genuinely new content and is immune to reconnects/re-persists;\n// never recomputed from the (compactable) transcript. See\n// `_chatRecoveryProgressMarker`.\nconst CHAT_RECOVERY_PROGRESS_KEY = \"cf:chat-recovery:progress\";\n// Secondary backstop only. The primary recovery bound is the no-progress\n// wall clock below; with alarm debounce this cap rarely binds (it catches a\n// pathological tight alarm-loop). Kept high so the no-progress window seals\n// first under normal deploy cadence (#1637).\nconst DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS = 10;\n// Runaway-loop guard default. `Infinity` = no SDK-imposed work cap: a turn that\n// keeps making forward progress is never terminated by the framework on its own\n// (rfc-chat-recovery-work-budget). Integrators bound a content-emitting runaway\n// by setting `maxRecoveryWork` or a `shouldKeepRecovering` predicate.\nconst DEFAULT_CHAT_RECOVERY_MAX_WORK = Number.POSITIVE_INFINITY;\nconst DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS = 10_000;\n// Auto-continuation barrier (#1649 / #1650): when the model emits parallel tool\n// calls, the client answers each one independently and sends a `tool-result`\n// with `autoContinue` per result. A fast tool's result must NOT trigger\n// inference while a slower sibling is still `input-available` — doing so feeds\n// the provider an incomplete tool-result set (MissingToolResultsError) or, with\n// the transcript-repair backstop, silently flips the in-flight sibling to\n// errored and runs a spurious extra continuation. So we hold the continuation\n// until the step's batch settles (no `input-available`/`approval-requested`\n// siblings).\n//\n// The barrier is event-driven (#1650): auto-continuation is only ever triggered\n// by a tool-result/approval event, so instead of waiting on a fixed timer we\n// drain the in-flight applies, re-check, and — if a sibling is still unanswered\n// — simply return, leaving the pending continuation in place. The next sibling's\n// result re-arms the coalesce timer (or, after eviction, re-creates the pending\n// state from the persisted transcript) and re-runs the check; the continuation\n// fires once the final sibling lands. This means a legitimately slow answer (a\n// human-in-the-loop tool with no `execute`, an unbounded RPC) never fires\n// through to a spurious error, and a true orphan (a sibling that never arrives)\n// simply never auto-continues — the isolate is not pinned waiting for it.\n// Delay before retrying a continuation that timed out waiting for stable state.\n// Gives an actively-churning isolate (e.g. a deploy in flight) time to settle.\nconst CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS = 3;\nconst DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE =\n \"The assistant was interrupted and could not recover. Please try again.\";\n// Incidents that have not seen a new attempt within this window are assumed\n// abandoned and swept so durable storage does not grow without bound.\nconst CHAT_RECOVERY_INCIDENT_TTL_MS = 60 * 60 * 1000;\n// Max keys per Durable Object KV `delete([...])` call.\n// See https://developers.cloudflare.com/durable-objects/api/sqlite-storage-api/\nconst KV_DELETE_MAX_KEYS = 128;\n// PRIMARY recovery bound (#1637): seal an incident that has made no forward\n// progress for this long. Keyed to `lastProgressAt`, which resets on every\n// progress-bearing attempt — so a turn that keeps producing content survives\n// deploy churn indefinitely, while a genuinely stuck turn dies within 5 min.\n// Overridable per-agent via `chatRecovery.noProgressTimeoutMs`.\nconst DEFAULT_CHAT_RECOVERY_NO_PROGRESS_TIMEOUT_MS = 5 * 60 * 1000;\n// Alarm debounce: recovery alarms bunched within this window collapse into a\n// single attempt. A deploy rollout drops/reconnects the socket several times\n// over ~11–22s; without this, one logical deploy would burn several attempts.\nconst CHAT_RECOVERY_ALARM_DEBOUNCE_MS = 30 * 1000;\n// Staleness bound for the live \"recovering…\" flag (#1620). A flag older than\n// this is treated as abandoned (the owning incident died without a terminal,\n// e.g. the DO went idle) so it can neither pin the indicator on forever nor\n// suppress a genuinely-new recovering signal. This is NOT a recovery budget —\n// a progressing turn is bounded by work, not wall-clock\n// (rfc-chat-recovery-work-budget).\nconst CHAT_RECOVERING_FLAG_TTL_MS = 15 * 60 * 1000;\n// N9: while a parent re-attaches to and forwards a sub-agent's stream, credit\n// the parent's recovery progress at most this often. The marker only needs to\n// advance ≥once between recovery attempts (the no-progress window is minutes),\n// so this caps storage writes during high-rate child streaming. The throttle\n// state is in-memory (reset per isolate), so the first forwarded chunk after\n// ANY restart always bumps — guaranteeing every recovery attempt that observes\n// child output registers forward progress.\nconst AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS = 5_000;\n\n// How far ahead to schedule the resumable-stream buffer cleanup alarm. Set to\n// ResumableStream's short completion-grace window (COMPLETED_RETENTION_MS, 10m)\n// so a finished buffer is reclaimed promptly. The re-arm-while-reclaimable loop\n// (see _cleanupStreamBuffers) revisits any longer-lived rows — e.g. an\n// abandoned in-flight buffer on its 1h window — by waking again each interval\n// until they age out, then stops. Driving cleanup from an alarm (rather than\n// only piggybacking on the next stream completion) ensures idle/one-off chat\n// DOs still reclaim their buffers without waking forever (#1706).\nconst STREAM_CLEANUP_DELAY_SECONDS = 10 * 60;\n\n// Ephemeral user message appended when a model request would otherwise end in\n// an assistant message (see `ensureValidContinueCheckpoint`).\nconst CONTINUE_CHECKPOINT_PROMPT =\n \"Continue your previous response from exactly where it left off. Do not repeat any of it.\";\n\n/**\n * Ensure a model request does not end in an assistant message.\n *\n * Continuing a partial assistant turn (e.g. after a deploy interrupts a stream)\n * replays a transcript whose final message is that partial assistant message —\n * an \"assistant prefill\". Modern chat models reject this: Anthropic Claude 4.6+\n * returns a 400 (\"This model does not support assistant message prefill. The\n * conversation must end with a user message.\"). To reach a valid continue\n * checkpoint across providers we append an ephemeral user message. This shapes\n * only the model request; it is never persisted to the transcript.\n */\nfunction ensureValidContinueCheckpoint(\n messages: ModelMessage[]\n): ModelMessage[] {\n if (messages.length === 0) return messages;\n if (messages[messages.length - 1]?.role !== \"assistant\") return messages;\n return [...messages, { role: \"user\", content: CONTINUE_CHECKPOINT_PROMPT }];\n}\n\n// Durable record of the last turn that ended in a terminal error / abandoned\n// recovery. Replayed to clients on connect so a turn that failed while they\n// were disconnected (e.g. during a deploy/WS reconnect storm) is not silently\n// frozen — the terminal `MSG_CHAT_RESPONSE` broadcast is otherwise transient.\nconst CHAT_LAST_TERMINAL_KEY = \"cf:chat:last-terminal\";\n\n// Durable record of an in-progress durable recovery, so a \"recovering…\" status\n// can be broadcast live AND replayed to a client that connects mid-recovery\n// (#1620). Set when a recovery continuation/retry is scheduled; cleared on every\n// terminal outcome (completed/skipped/failed/exhausted) so the indicator can't\n// spin forever.\nconst CHAT_RECOVERING_KEY = \"cf:chat:recovering\";\n\n/**\n * A best-effort internal `onStart` step that failed on this wake and was\n * skipped so the agent could still come up (#1710).\n *\n * - `transcript-hydration` — reading the persisted conversation into the\n * in-memory message cache failed (e.g. `SQLITE_NOMEM` on an oversized,\n * media-heavy transcript). The agent starts with an empty in-memory view;\n * persisted history is untouched and the next safe-boundary sync retries.\n * - `scheduled-task-reconcile` — declarative scheduled tasks were not\n * reconciled on this wake; the next successful wake reconciles them.\n * - `durable-work-recovery` — pending submissions / workflow notifications\n * were not recovered or drained on this wake.\n */\nexport interface OnStartDegradation {\n step:\n | \"transcript-hydration\"\n | \"scheduled-task-reconcile\"\n | \"durable-work-recovery\";\n error: unknown;\n}\n\nexport type { MediaEvictionConfig } from \"./media-eviction\";\n\n/**\n * Callback interface for streaming chat events from a Think sub-agent.\n *\n * Designed to work across the sub-agent RPC boundary — implement as\n * an RpcTarget in the parent agent and pass to `chat()`.\n */\nexport interface ChatStartEvent {\n requestId: string;\n}\n\nexport interface StreamCallback {\n onStart(event: ChatStartEvent): void | Promise<void>;\n onEvent(json: string): void | Promise<void>;\n onDone(): void | Promise<void>;\n onError(error: string): void | Promise<void>;\n /**\n * The current attempt was interrupted (a stream-stall watchdog abort routed\n * into bounded recovery, #1626) and its final outcome will NOT arrive through\n * this callback. One of two things is true:\n * - a scheduled continuation — running in a LATER isolate invocation, without\n * this callback — will produce the answer (delivered to other channels,\n * e.g. WebSocket connections), OR\n * - the recovery budget was exhausted, so the turn was already terminalized\n * out-of-band (the configured `terminalMessage` + `onExhausted`) and is\n * terminally over — there is NO continuation to come.\n *\n * This is NOT `onDone` (this attempt did not complete) and NOT `onError` (the\n * raw stall is not surfaced as a terminal error here); without it the contract\n * `onStart → onEvent* → (onDone | onError)` is silently abandoned and a\n * consumer that treats the clean resolve as success finalizes a truncated\n * partial.\n *\n * Consumers should AVOID finalizing the partial on this signal — surface a\n * \"recovering…\" / \"interrupted, please retry\" state, or re-attach via a\n * durable channel — but must ALSO NOT block indefinitely waiting for a\n * continuation: per the exhausted case above, one may never come. Optional →\n * defaults to a no-op, so this is fully backward-compatible.\n *\n * Note: a deploy/eviction interruption kills the isolate (and this callback)\n * before this can fire — the caller observes a transport break instead. This\n * fires only for an in-isolate interruption (the stall→recovery path).\n */\n onInterrupted?(): void | Promise<void>;\n}\n\n/**\n * Minimal interface for the result of the inference loop.\n * The AI SDK's `streamText()` result satisfies this interface.\n */\nexport interface StreamableResult {\n toUIMessageStream(options?: {\n sendReasoning?: boolean;\n }): 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}\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\ntype AgentToolChildRunStatus =\n | \"starting\"\n | \"running\"\n | \"completed\"\n | \"error\"\n | \"aborted\";\n\ntype AgentToolChildRunRow = {\n run_id: string;\n request_id: string | null;\n stream_id: string | null;\n status: AgentToolChildRunStatus;\n summary: string | null;\n output_json: string | null;\n error_message: string | null;\n started_at: number;\n completed_at: number | null;\n};\n\ntype AgentToolRunInspection<Output = unknown> = {\n runId: string;\n status: AgentToolChildRunStatus;\n requestId?: string;\n streamId?: string;\n output?: Output;\n summary?: string;\n error?: string;\n startedAt: number;\n completedAt?: number;\n};\n\ntype Digit = \"0\" | \"1\" | \"2\" | \"3\" | \"4\" | \"5\" | \"6\" | \"7\" | \"8\" | \"9\";\ntype Hour = `0${Digit}` | `1${Digit}` | \"20\" | \"21\" | \"22\" | \"23\";\ntype Minute = `${\"0\" | \"1\" | \"2\" | \"3\" | \"4\" | \"5\"}${Digit}`;\nexport type ThinkTime = `${Hour}:${Minute}`;\nexport type ThinkIntervalSchedule =\n | `every ${number} minute${\"\" | \"s\"}`\n | `every ${number} hour${\"\" | \"s\"}`;\nexport type ThinkWallClockSchedule =\n | `every day at ${ThinkTime}`\n | `every weekday at ${ThinkTime}`\n | `every week on ${string} at ${ThinkTime}`;\nexport type ThinkScheduledTaskSchedule =\n | ThinkIntervalSchedule\n | ThinkWallClockSchedule\n | `${ThinkWallClockSchedule} in ${string}`;\n\nexport type ThinkScheduledTaskContext = {\n taskId: string;\n scheduledFor: number;\n scheduledForDate: Date;\n occurrenceKey: string;\n idempotencyKey: string;\n schedule: string;\n scheduleKind: \"interval\" | \"wall-clock\";\n timezone?: string;\n metadata?: Record<string, unknown>;\n};\n\ntype ThinkScheduledTaskPromptAction = {\n prompt: string | (() => string | Promise<string>);\n handler?: never;\n};\n\ntype ThinkScheduledTaskHandlerAction = {\n handler: (ctx: ThinkScheduledTaskContext) => void | Promise<void>;\n prompt?: never;\n};\n\ntype ThinkScheduledTaskBase = (\n | ThinkScheduledTaskPromptAction\n | ThinkScheduledTaskHandlerAction\n) & {\n retry?: RetryOptions;\n metadata?: Record<string, unknown>;\n};\n\nexport type ThinkScheduledTask =\n | (ThinkScheduledTaskBase & {\n schedule: ThinkIntervalSchedule;\n timezone?: never;\n })\n | (ThinkScheduledTaskBase & {\n schedule: ThinkWallClockSchedule;\n timezone?: string;\n })\n | (ThinkScheduledTaskBase & {\n schedule: `${ThinkWallClockSchedule} in ${string}`;\n timezone?: string;\n });\n\nexport type ThinkScheduledTasks = Record<string, ThinkScheduledTask>;\n\nexport function defineScheduledTasks<const T extends ThinkScheduledTasks>(\n tasks: T\n): T {\n return tasks;\n}\n\ntype ParsedDeclaredSchedule =\n | {\n kind: \"interval\";\n intervalMs: number;\n normalizedSchedule: string;\n }\n | {\n kind: \"wall-clock\";\n normalizedSchedule: string;\n timezone: string;\n hour: number;\n minute: number;\n days: \"daily\" | \"weekday\" | number[];\n };\n\ntype ParseDeclaredScheduleResult =\n | { ok: true; schedule: ParsedDeclaredSchedule }\n | { ok: false; error: string };\n\ntype NormalizedDeclaredTask = {\n taskId: string;\n prompt?: ThinkScheduledTaskPromptAction[\"prompt\"];\n handler?: ThinkScheduledTaskHandlerAction[\"handler\"];\n schedule: ParsedDeclaredSchedule;\n retry?: RetryOptions;\n metadata?: Record<string, unknown>;\n scheduleHash: string;\n taskHash: string;\n};\n\ntype DeclaredScheduledTaskRow = {\n owner_key: string;\n task_id: string;\n schedule_hash: string;\n task_hash: string;\n schedule_id: string | null;\n next_run_at: number | null;\n created_at: number;\n updated_at: number;\n};\n\ntype DeclaredScheduledTaskPayload = {\n taskId: string;\n scheduleHash: string;\n scheduledFor: number;\n};\n\ntype ZonedParts = {\n year: number;\n month: number;\n day: number;\n hour: number;\n minute: number;\n second: number;\n weekday: number;\n};\n\ntype AgentToolStoredChunk = {\n sequence: number;\n body: string;\n};\n\nexport type ThinkSubmissionStatus =\n | \"pending\"\n | \"running\"\n | \"completed\"\n | \"aborted\"\n | \"skipped\"\n | \"error\";\n\nexport type SubmitMessagesOptions = {\n submissionId?: string;\n idempotencyKey?: string;\n metadata?: Record<string, unknown>;\n};\n\ntype ThinkWorkflowPromptContext = {\n workflow: {\n name: string;\n id: string;\n stepName: string;\n eventType: string;\n };\n output?: {\n schema: unknown;\n };\n fingerprint?: string;\n};\n\nconst THINK_WORKFLOW_PROMPT_METADATA_KEY = \"__thinkWorkflowPrompt\";\n\n/**\n * Reserved name for the synthetic tool a workflow `step.prompt` turn uses to\n * deliver its structured final answer. The agent runs a full multi-step,\n * tool-using turn and ends it by calling this tool with arguments matching the\n * requested schema — exactly the way a sub-agent returns a result.\n *\n * Why a tool instead of the AI SDK `output`/`response_format` path: streaming a\n * JSON Schema `response_format` is rejected by some providers (Workers AI\n * returns `AiError 5023: JSON Schema mode is not supported with stream mode`),\n * whereas plain tool-calling streams on every provider. Capturing the tool\n * call's INPUT as the result keeps Think's single streaming engine intact\n * (persistence, recovery, resumable streams) and works uniformly across\n * Workers AI, OpenAI, and Anthropic.\n *\n * The name is namespaced to avoid clashing with user tools; if a user tool\n * already uses it, the turn picks a suffixed variant (see `_handleTurn`).\n */\nconst THINK_FINAL_ANSWER_TOOL_NAME = \"think_final_answer\";\n\n/**\n * Whether `name` is (or is a collision-suffixed variant of) the reserved\n * structured-output final-answer tool. Used to strip the internal tool's parts\n * from persisted assistant messages regardless of which per-turn name was used.\n */\nfunction isThinkFinalAnswerToolName(name: string): boolean {\n return (\n name === THINK_FINAL_ANSWER_TOOL_NAME ||\n name.startsWith(`${THINK_FINAL_ANSWER_TOOL_NAME}_`)\n );\n}\n\n/**\n * Build the system-prompt instruction that tells the model to terminate a\n * structured workflow turn by calling the given final-answer tool.\n */\nfunction thinkFinalAnswerInstruction(toolName: string): string {\n return (\n \"When you have everything you need to answer, you MUST call the \" +\n `\\`${toolName}\\` tool exactly once with arguments that match the required ` +\n \"schema. Do not write the final answer as plain text — the \" +\n `\\`${toolName}\\` tool call IS the answer and ends the task.`\n );\n}\n\nexport type ThinkSubmissionInspection = {\n submissionId: string;\n idempotencyKey?: string;\n requestId?: string;\n status: ThinkSubmissionStatus;\n error?: string;\n metadata?: Record<string, unknown>;\n createdAt: number;\n startedAt?: number;\n completedAt?: number;\n};\n\nexport type SubmitMessagesResult = ThinkSubmissionInspection & {\n accepted: boolean;\n};\n\nexport type ListSubmissionsOptions = {\n status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];\n limit?: number;\n};\n\nexport type DeleteSubmissionsOptions = {\n status?: ThinkSubmissionStatus | ThinkSubmissionStatus[];\n completedBefore?: Date;\n limit?: number;\n};\n\ntype ThinkSubmissionRow = {\n submission_id: string;\n idempotency_key: string | null;\n request_id: string | null;\n stream_id: string | null;\n status: ThinkSubmissionStatus;\n messages_json: string;\n metadata_json: string | null;\n error_message: string | null;\n created_at: number;\n messages_applied_at: number | null;\n started_at: number | null;\n completed_at: number | null;\n};\n\ntype ThinkWorkflowNotificationRow = {\n notification_id: string;\n submission_id: string;\n workflow_name: string;\n workflow_id: string;\n event_type: string;\n payload_json: string;\n attempts: number;\n last_error: string | null;\n created_at: number;\n updated_at: number;\n delivered_at: number | null;\n};\n\n// Lifecycle / result types are shared with `@cloudflare/ai-chat` via\n// `agents/chat`. Re-exported from Think so subclasses can import them\n// from `@cloudflare/think` directly.\nexport type {\n ChatResponseResult,\n ChatRecoveryConfig,\n ChatRecoveryContext,\n ChatRecoveryExhaustedContext,\n ChatRecoveryProgressContext,\n ChatRecoveryOptions,\n MessageConcurrency,\n ResolvedChatRecoveryConfig,\n SaveMessagesOptions,\n SaveMessagesResult\n} from \"agents/chat\";\nimport type {\n ChatResponseResult,\n ChatRecoveryConfig,\n ChatRecoveryContext,\n ChatRecoveryExhaustedContext,\n ChatRecoveryOptions,\n MessageConcurrency,\n ResolvedChatRecoveryConfig,\n SaveMessagesOptions,\n SaveMessagesResult\n} from \"agents/chat\";\n\n// ── Lifecycle hook types ────────────────────────────────────────\n\n/**\n * A chat turn request. Built automatically by each entry path\n * (WebSocket, chat(), saveMessages, auto-continuation) and passed\n * to Think's inference loop.\n */\nexport interface TurnInput {\n signal?: AbortSignal;\n /** Client-provided tool schemas for dynamic tool registration. */\n clientTools?: ClientToolSchema[];\n /**\n * Executor that resolves client-tool calls inline (RPC `chat()` path). When\n * present, `clientTools` are built WITH an `execute` that delegates to it, so\n * the turn completes the tool round trip itself instead of surfacing a\n * dangling tool call. Not persisted — recovery cannot replay a live executor.\n */\n clientToolExecutor?: ClientToolExecutor;\n /** Custom body fields from the client request. */\n body?: Record<string, unknown>;\n /** Internal workflow prompt configuration, never sourced from client body. */\n workflowPrompt?: ThinkWorkflowPromptContext;\n /** Whether this is a continuation turn (auto-continue after tool result, recovery). */\n continuation: boolean;\n}\n\n/**\n * Context passed to the `beforeTurn` hook.\n * Contains everything Think assembled — the hook can inspect and override.\n */\nexport interface TurnContext {\n /** Assembled system prompt (from context blocks or getSystemPrompt fallback). */\n system: string;\n /** Assembled model messages (truncated, pruned). */\n messages: ModelMessage[];\n /** Merged tool set (workspace + getTools + session + MCP + client + caller). */\n tools: ToolSet;\n /** The language model from getModel(). */\n model: LanguageModel;\n /** Whether this is a continuation turn. */\n continuation: boolean;\n /** Custom body fields from the client request. */\n body?: Record<string, unknown>;\n}\n\n/**\n * Configuration returned by the `beforeTurn` hook to override defaults.\n * All fields are optional — return only what you want to change.\n */\nexport interface TurnConfig {\n /** Override the model for this turn (e.g. cheap model for continuations). */\n model?: LanguageModel;\n /** Override the assembled system prompt. */\n system?: string;\n /** Override the assembled messages. */\n messages?: ModelMessage[];\n /** Extra tools to merge (additive — spread on top of existing tools). */\n tools?: ToolSet;\n /** Limit which tools the model can call (AI SDK activeTools). */\n activeTools?: string[];\n /** Force a specific tool call (AI SDK toolChoice). */\n toolChoice?: Parameters<typeof streamText>[0][\"toolChoice\"];\n /** Override maxSteps for this turn. */\n maxSteps?: number;\n /**\n * Additional AI SDK stop conditions for ending the turn early.\n * Think always keeps its `maxSteps` stop condition as a safety bound.\n */\n stopWhen?: StopCondition<ToolSet> | Array<StopCondition<ToolSet>>;\n /**\n * Controls whether reasoning chunks are included in the UI message stream\n * for this turn. Defaults to the instance-level `sendReasoning` setting.\n */\n sendReasoning?: boolean;\n /**\n * Override the stream-stall inactivity watchdog timeout for THIS turn only\n * (ms; `0` disables it for this turn). Defaults to the instance-level\n * `chatStreamStallTimeoutMs`. Because the watchdog measures the gap between\n * UI-message-stream chunks — which includes server-side tool execution — a\n * turn known to invoke a slow tool can raise (or disable) the timeout for\n * just that turn instead of permanently widening the global window. Auto-\n * resets after the turn.\n */\n chatStreamStallTimeoutMs?: number;\n /** Maximum number of tokens to generate for this turn. */\n maxOutputTokens?: Parameters<typeof streamText>[0][\"maxOutputTokens\"];\n /** Temperature setting for this turn. */\n temperature?: Parameters<typeof streamText>[0][\"temperature\"];\n /** Nucleus sampling setting for this turn. */\n topP?: Parameters<typeof streamText>[0][\"topP\"];\n /** Top-K sampling setting for this turn. */\n topK?: Parameters<typeof streamText>[0][\"topK\"];\n /** Presence penalty setting for this turn. */\n presencePenalty?: Parameters<typeof streamText>[0][\"presencePenalty\"];\n /** Frequency penalty setting for this turn. */\n frequencyPenalty?: Parameters<typeof streamText>[0][\"frequencyPenalty\"];\n /** Stop sequences for this turn. */\n stopSequences?: Parameters<typeof streamText>[0][\"stopSequences\"];\n /** Seed for deterministic sampling when supported by the model. */\n seed?: Parameters<typeof streamText>[0][\"seed\"];\n /** Maximum number of retries for this turn. Set to 0 to disable retries. */\n maxRetries?: Parameters<typeof streamText>[0][\"maxRetries\"];\n /** Timeout configuration for this turn. */\n timeout?: Parameters<typeof streamText>[0][\"timeout\"];\n /** Additional HTTP headers for provider requests on this turn. */\n headers?: Parameters<typeof streamText>[0][\"headers\"];\n /** Provider-specific options (AI SDK providerOptions). */\n providerOptions?: Record<string, unknown>;\n /** Optional AI SDK telemetry configuration for this turn. */\n experimental_telemetry?: Parameters<\n typeof streamText\n >[0][\"experimental_telemetry\"];\n /**\n * Optional AI SDK stream transform(s) for this turn (`experimental_transform`).\n * Forwarded to `streamText` so callers can inspect/rewrite the stream — e.g.\n * detecting tool results that carry `{ content, sources }` and enqueuing\n * additional `source` parts via the transform's controller. Accepts a single\n * transform or an array applied in order.\n */\n experimental_transform?: Parameters<\n typeof streamText\n >[0][\"experimental_transform\"];\n /**\n * Optional structured-output specification (AI SDK `output`).\n * Forwarded to `streamText` so the model's final response is parsed\n * against the supplied schema. Use the AI SDK's `Output.object({ schema })`\n * / `Output.text()` helpers. Combine with `activeTools: []` on the\n * terminal turn if your provider strips tools when structured output\n * is active (e.g. workers-ai-provider).\n */\n output?: Parameters<typeof streamText>[0][\"output\"];\n}\n\n/**\n * Provider-agnostic semantic classification of a chat-turn error.\n *\n * Think ships **no** provider-specific string/code matching — the app owns\n * that knowledge (it knows which provider/model it talks to), exactly like the\n * `tokenCounter` it already passes to `compactAfter()`. An app teaches Think\n * what an error *means* by overriding `classifyChatError()`; Think then reacts\n * generically (e.g. compact-and-retry on `context_overflow`).\n *\n * - `context_overflow` — the prompt exceeded the model's context window\n * (Anthropic `\"prompt is too long\"`, OpenAI `context_length_exceeded`, …).\n * The only category Think currently acts on (auto-compact + retry).\n * - `rate_limit` / `transient` — reserved for future backoff/retry policies.\n * - `fatal` — unrecoverable; surface terminally.\n * - `unknown` — default; Think applies its existing terminal behavior.\n */\nexport type ChatErrorClassification =\n | \"context_overflow\"\n | \"rate_limit\"\n | \"transient\"\n | \"fatal\"\n | \"unknown\";\n\n/**\n * Opt-in handling for a turn that overflows the model's context window\n * mid-flight. Compaction (`compactAfter()`) is only checked between turns, so a\n * long, tool-heavy turn can grow past the window before the next check; the\n * provider then rejects the request (`\"prompt is too long\"` /\n * `context_length_exceeded`). Both layers reuse the session's compaction\n * function and are provider-agnostic — the app maps the error via\n * {@link Think.classifyChatError}; Think never matches provider strings itself.\n *\n * Set `Think.contextOverflow` to enable. Leaving it unset disables both layers\n * (existing terminal behavior).\n */\nexport interface ContextOverflowConfig {\n /**\n * Reactive backstop. When a turn fails with an error classified as\n * `\"context_overflow\"`, discard the truncated partial, run\n * `session.compact()`, and re-run the turn from the compacted history. The\n * partial is intentionally not persisted: the turn restarts from scratch, so\n * keeping the cut-off assistant message would orphan it beside the recovered\n * answer (and duplicate any tool work the retry re-issues). If compaction\n * cannot shorten history or the retry budget is spent, the overflow surfaces\n * terminally through `onChatError` (classified) — it never loops or ends\n * silently. Default `false`.\n */\n reactive?: boolean;\n\n /**\n * Maximum compact-and-retry attempts for a single overflowing turn (the\n * reactive backstop). Independent of the proactive guard's cap — see\n * {@link proactive.maxCompactions}. Default `1`.\n */\n maxRetries?: number;\n\n /**\n * Proactive guard. Before each step, read the previous step's model-reported\n * `usage.inputTokens` and, if it crosses `maxInputTokens * (headroom ?? 0.9)`,\n * compact in place and feed the recompacted history into the upcoming step —\n * heading off the provider rejection before it happens. Keys off usage (every\n * provider reports it), not provider error strings. Unset disables it.\n *\n * If a provider omits `inputTokens`, the guard falls back to `usage.totalTokens`\n * (input + output) — a safe over-approximation that compacts slightly early\n * rather than missing the threshold. If neither is reported, the guard does\n * nothing that step (the reactive backstop still catches a genuine overflow).\n *\n * `maxCompactions` caps how many times the guard may compact within a single\n * step loop (default `1`, floored at `1`). It is independent of\n * {@link maxRetries} (the reactive budget): a no-op compaction would repeat on\n * every step, so the cap stops the guard from compacting (and emitting\n * `chat:context:compacted`) on each one.\n */\n proactive?: {\n maxInputTokens: number;\n headroom?: number;\n maxCompactions?: number;\n };\n}\n\n/**\n * Matches the context-window-overflow error messages of the common providers.\n * Anthropic (`prompt is too long`), OpenAI (`context_length_exceeded`,\n * `maximum context length`, `reduce the length of …`), Google Gemini (`exceeds\n * the maximum number of tokens`, `input token count`), Bedrock / Mistral /\n * others (`input is too long`, `too many tokens`, `context window`).\n *\n * This default deliberately favors recall over precision: a missed overflow\n * means no recovery (the feature's whole point), whereas a false positive\n * self-heals — the retry hits the same non-overflow error, the budget is spent,\n * and it surfaces terminally anyway. The vaguest fragment (`reduce the length`)\n * is anchored to `of` to match the real OpenAI phrasing without matching\n * unrelated prose. Apps that need stricter matching can wrap this classifier.\n */\nconst CONTEXT_OVERFLOW_PATTERN =\n /prompt is too long|context[_ ]length[_ ]exceeded|maximum context length|exceeds the maximum number of tokens|input token count|reduce the length of|input is too long|too many (?:input )?tokens|context window/i;\n\n/**\n * Opt-in default classifier for {@link Think.classifyChatError}. Matches the\n * context-window-overflow error messages of the common providers (Anthropic,\n * OpenAI, Google, Bedrock, Mistral, …) and returns `\"context_overflow\"`.\n *\n * Think ships this as an explicitly-imported helper rather than wiring it into\n * core, so the framework default stays free of provider strings. Assign it (or\n * delegate to it) when you do not need custom classification:\n *\n * @example\n * ```typescript\n * import { Think, defaultContextOverflowClassifier } from \"@cloudflare/think\";\n *\n * export class MyAgent extends Think<Env> {\n * override contextOverflow = { reactive: true };\n * override classifyChatError = defaultContextOverflowClassifier;\n * }\n * ```\n *\n * Or combine with your own checks:\n *\n * @example\n * ```typescript\n * override classifyChatError(error: unknown): ChatErrorClassification | void {\n * if (isMyRateLimit(error)) return \"rate_limit\";\n * return defaultContextOverflowClassifier(error);\n * }\n * ```\n */\nexport function defaultContextOverflowClassifier(\n error: unknown\n): ChatErrorClassification | undefined {\n let text: string;\n if (error instanceof Error) {\n text = error.message;\n } else if (typeof error === \"string\") {\n text = error;\n } else {\n try {\n text = JSON.stringify(error);\n } catch {\n text = String(error);\n }\n }\n return CONTEXT_OVERFLOW_PATTERN.test(text) ? \"context_overflow\" : undefined;\n}\n\nexport interface ChatErrorContext {\n requestId?: string;\n stage: \"parse\" | \"persist\" | \"turn\" | \"stream\" | \"recovery\" | \"transcript\";\n messagesPersisted?: boolean;\n /**\n * App-provided semantic classification (from `classifyChatError`), when\n * known. Lets `onChatError` overrides and observers distinguish e.g. a\n * context-overflow from a generic provider failure without re-matching\n * provider strings.\n */\n classification?: ChatErrorClassification;\n}\n\n/**\n * Context passed to the `beforeStep` hook before each AI SDK step in\n * the agentic loop. Backed by the AI SDK's `PrepareStepFunction<TOOLS>`\n * parameter — exposes the previous `steps`, the zero-based `stepNumber`,\n * the currently selected `model`, the `messages` about to be sent, and\n * `experimental_context`.\n *\n * Pass an explicit `TOOLS` generic for typed previous tool calls / results.\n *\n * Limitations (AI SDK boundary, not Think):\n * - No `abortSignal` is exposed in the context. If you do remote work\n * inside `beforeStep`, it cannot be cancelled by turn-level abort.\n * - `experimental_context` is typed `unknown`; users must narrow it.\n * - `output` cannot be overridden per-step — set it at the turn level\n * via `TurnConfig.output` (returned from `beforeTurn`).\n */\nexport type PrepareStepContext<TOOLS extends ToolSet = ToolSet> = Parameters<\n PrepareStepFunction<TOOLS>\n>[0];\n\n/**\n * Configuration returned by `beforeStep` to override defaults for the\n * current AI SDK step. This is the AI SDK's `PrepareStepResult<TOOLS>` —\n * return only the fields you want to override (`model`, `toolChoice`,\n * `activeTools`, `system`, `messages`, `experimental_context`,\n * `providerOptions`).\n */\nexport type StepConfig<TOOLS extends ToolSet = ToolSet> =\n PrepareStepResult<TOOLS>;\n\n/**\n * Context passed to the `beforeToolCall` hook **before** the tool's\n * `execute` function runs.\n *\n * Backed by the AI SDK's `OnToolCallStartEvent` (the parameter of\n * `experimental_onToolCallStart`). The full `TypedToolCall<TOOLS>`\n * fields (`toolName`, `toolCallId`, `input`, `providerMetadata`, the\n * dynamic/invalid/error discriminators) are spread at the top level for\n * convenience, with the per-call event extras attached:\n *\n * - `stepNumber` — index of the current step\n * - `messages` — conversation messages visible at tool execution time\n * - `abortSignal` — signal that aborts if the turn is cancelled\n *\n * Pass an explicit `TOOLS` generic for full input typing:\n *\n * ```ts\n * import type { ToolCallContext } from \"@cloudflare/think\";\n * import type { tools } from \"./my-tools\";\n *\n * beforeToolCall(ctx: ToolCallContext<typeof tools>) {\n * if (ctx.toolName === \"search\") {\n * ctx.input.query; // typed\n * }\n * }\n * ```\n */\nexport type ToolCallContext<TOOLS extends ToolSet = ToolSet> =\n TypedToolCall<TOOLS> & {\n /** Zero-based index of the current step where this tool call occurs. */\n readonly stepNumber: number | undefined;\n /** The conversation messages available at tool execution time. */\n readonly messages: ReadonlyArray<ModelMessage>;\n /** Signal for cancelling the operation. */\n readonly abortSignal: AbortSignal | undefined;\n };\n\n/**\n * Decision returned by `beforeToolCall` to control tool execution.\n * Return void/undefined to allow execution with original input.\n *\n * Discriminated union — each action has a clear, non-overlapping meaning:\n * - `allow` — execute the tool (optionally with modified input)\n * - `block` — don't execute; return `reason` as the tool result so the model can adjust\n * - `substitute` — don't execute; return `output` as the tool result (afterToolCall still fires)\n */\nexport type ToolCallDecision =\n | {\n action: \"allow\";\n /** Modified input — tool executes with this instead of the original. */\n input?: Record<string, unknown>;\n }\n | {\n action: \"block\";\n /** Returned as the tool result so the model can adjust. */\n reason?: string;\n }\n | {\n action: \"substitute\";\n /** The substitute tool output — model sees this instead of real execution. */\n output: unknown;\n /** Optional input attribution for the afterToolCall log. */\n input?: Record<string, unknown>;\n };\n\n/**\n * Context passed to the `afterToolCall` hook after a tool executes.\n *\n * Backed by the AI SDK's `OnToolCallFinishEvent` (the parameter of\n * `experimental_onToolCallFinish`). The full `TypedToolCall<TOOLS>`\n * fields (`toolName`, `toolCallId`, `input`, …) are spread at the top\n * level, plus the per-call event extras:\n *\n * - `stepNumber` — index of the current step\n * - `messages` — conversation messages visible at tool execution time\n * - `durationMs` — wall-clock execution time in milliseconds\n * - `success`/`output`/`error` — discriminated outcome:\n * - on success: `success: true`, `output: unknown`\n * - on failure: `success: false`, `error: unknown`\n *\n * Pass an explicit `TOOLS` generic for full input typing:\n *\n * ```ts\n * import type { ToolCallResultContext } from \"@cloudflare/think\";\n * import type { tools } from \"./my-tools\";\n *\n * afterToolCall(ctx: ToolCallResultContext<typeof tools>) {\n * if (ctx.success) {\n * console.log(`${ctx.toolName} took ${ctx.durationMs}ms`, ctx.output);\n * } else {\n * console.error(`${ctx.toolName} failed:`, ctx.error);\n * }\n * }\n * ```\n */\nexport type ToolCallResultContext<TOOLS extends ToolSet = ToolSet> =\n TypedToolCall<TOOLS> & {\n readonly stepNumber: number | undefined;\n readonly messages: ReadonlyArray<ModelMessage>;\n /** Wall-clock execution time in milliseconds. */\n readonly durationMs: number;\n } & (\n | {\n readonly success: true;\n readonly output: unknown;\n readonly error?: never;\n }\n | {\n readonly success: false;\n readonly output?: never;\n readonly error: unknown;\n }\n );\n\n/**\n * Context passed to the `onStepFinish` hook after each step completes.\n *\n * This is the AI SDK's `StepResult<TOOLS>` (= `OnStepFinishEvent<TOOLS>`) —\n * the full step record including `text`, `reasoning`, `toolCalls`,\n * `toolResults`, `files`, `sources`, `usage` (with `cachedInputTokens`,\n * `reasoningTokens`, `totalTokens`), `finishReason`, `warnings`, `request`,\n * `response`, and `providerMetadata` (where provider-specific cache\n * accounting like `cacheCreationInputTokens` lives).\n *\n * Pass an explicit `TOOLS` generic for typed `toolCalls`/`toolResults`.\n */\nexport type StepContext<TOOLS extends ToolSet = ToolSet> = Parameters<\n StreamTextOnStepFinishCallback<TOOLS>\n>[0];\n\n/**\n * Context passed to the `onChunk` hook for each streaming chunk.\n *\n * This is the AI SDK's `StreamTextOnChunkCallback` event — `{ chunk }`\n * where `chunk` is a discriminated union of `TextStreamPart` variants\n * (text-delta, reasoning-delta, source, tool-call, tool-input-start,\n * tool-input-delta, tool-result, raw).\n */\nexport type ChunkContext<TOOLS extends ToolSet = ToolSet> = Parameters<\n StreamTextOnChunkCallback<TOOLS>\n>[0];\n\n/**\n * @internal Re-export of the chunk variant union for consumers that need\n * to narrow on `chunk.type` without importing `TextStreamPart` directly.\n */\nexport type ChunkPart<TOOLS extends ToolSet = ToolSet> =\n ChunkContext<TOOLS>[\"chunk\"];\n\n/**\n * Configuration for a sandboxed extension, returned by getExtensions().\n */\nexport interface ExtensionConfig {\n /** Extension manifest (name, version, permissions, contributions). */\n manifest: import(\"./extensions/types\").ExtensionManifest;\n /** JavaScript source code defining the extension's tools. */\n source: string;\n}\n\nconst TIMED_OUT = Symbol(\"timed-out\");\n\n/**\n * An opinionated chat agent base class.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class Think<\n Env extends Cloudflare.Env = Cloudflare.Env,\n State = unknown,\n Props extends Record<string, unknown> = Record<string, unknown>\n> extends Agent<Env, State, Props> {\n // Root requestId of the in-flight recovery chain, threaded into each\n // continuation's snapshot so chained continuations keep owning the original\n // submission. This is a single instance field, NOT per-incident: it is only\n // safe because turns (and recovery fibers) are serialized by the turn queue,\n // so at most one recovery chain is active at a time. The `try/finally`\n // restore in `_chatRecoveryRetry` / `_chatRecoveryContinue` returns it to the\n // prior value once a continuation settles. If turns ever run concurrently,\n // this must move to per-incident storage.\n private _activeChatRecoveryRootRequestId: string | undefined;\n\n private static readonly CONFIG_KEYS = [\n \"_think_config\",\n \"lastClientTools\",\n \"lastBody\",\n \"skillsFingerprint\"\n ] as const;\n /**\n * Wait for MCP server connections to be ready before the inference\n * loop. MCP tools are auto-merged into the tool set.\n *\n * Set to `true` for a default 10s timeout, or `{ timeout: ms }`\n * for a custom timeout. Defaults to `false` (no waiting).\n */\n waitForMcpConnections: boolean | { timeout: number } = false;\n\n private _skillRegistry: SkillRegistry | null = null;\n private _loggedSkillWarnings = new Set<string>();\n\n /**\n * Controls how overlapping user submit requests behave while another\n * chat turn is already active or queued.\n *\n * @default \"queue\"\n */\n messageConcurrency: MessageConcurrency = \"queue\";\n\n /**\n * Byte budget for hydrating the persisted transcript into the in-memory\n * message cache (`this.messages`).\n *\n * Hydration runs on every wake (and at safe boundaries during a session).\n * Without a budget it materializes the ENTIRE stored conversation — for\n * long-lived, media-heavy sessions that footprint approaches the isolate's\n * 128MB memory budget and the next SQLite allocation fails with\n * `SQLITE_NOMEM`, permanently bricking the DO (#1710).\n *\n * When the stored path exceeds the budget, only the most recent messages\n * that fit are hydrated — never fewer than the recent window the model\n * sees at full fidelity (the `truncateOlderMessages` default of 4), even\n * when those messages alone exceed the budget — a\n * `chat:hydration:windowed` observability event is emitted, and\n * `this.messages` exposes the bounded window. Durable storage is never\n * truncated by this — `session.getHistory()` still reads the full path.\n * The model-facing context is unaffected: older content is already\n * truncated at read time before each turn, and the hydration floor\n * guarantees the full-fidelity span is always present.\n *\n * The default (24MB) leaves headroom for the ~2-3x amplification between\n * stored JSON and parsed in-memory messages. Set to\n * `Number.POSITIVE_INFINITY` (or any non-positive value) to disable\n * windowing and always hydrate the full transcript.\n *\n * @default 24 * 1024 * 1024\n */\n hydrationByteBudget: number = 24 * 1024 * 1024;\n\n /**\n * Bound the PERSISTED transcript footprint by evicting oversized inline\n * media (base64 data-URL attachments, large strings inside tool outputs)\n * from messages that have aged out of the recent window.\n *\n * Read-time truncation already hides aged media from the model, but the\n * bytes stay in storage forever and are rehydrated on every wake — the\n * boot footprint grows with every image a session ever produced until\n * SQLite's allocator fails with `SQLITE_NOMEM` (#1710). Eviction passes\n * run in the background after the agent starts and as the conversation\n * grows; each pass processes a bounded number of oversized rows.\n *\n * By default evicted values are preserved as workspace files under\n * `/attachments/evicted/` (same Durable Object storage, but outside the\n * hydration path) and the in-message marker records the file path.\n * Pass a {@link MediaEvictionConfig} with `externalizeToWorkspace: false`\n * to drop the bytes instead of preserving them. Set this field to\n * `false` to disable eviction entirely.\n *\n * `keepRecentMessages` is clamped to at least the recent window the model\n * replays at full fidelity (4 messages), so eviction can never rewrite\n * content the model still sees.\n *\n * Requires a SessionProvider that implements `getHistoryRowStats`\n * (the default DO SQLite provider does); otherwise eviction is a no-op\n * and a warning is logged once.\n *\n * @default true\n */\n mediaEviction: MediaEvictionConfig | boolean = true;\n\n /**\n * When true, chat turns are wrapped in `runFiber` for durable execution.\n * Enables `onChatRecovery` hook and `this.stash()` during streaming.\n *\n * Assign this as a class field or in the constructor — NOT in `onStart()`.\n * On every wake the SDK evaluates recovery budgets (and may seal an\n * interrupted turn, firing `onExhausted`) before `onStart()` runs, so a config\n * set in `onStart()` is applied too late and the built-in defaults are used\n * for the recovery that matters. See {@link ChatRecoveryConfig}.\n */\n chatRecovery: ChatRecoveryConfig = true;\n\n static readonly CHAT_FIBER_NAME = \"__cf_internal_chat_turn\";\n\n /**\n * The conversation session — messages, context, compaction, search.\n *\n * Direct message writes are observed and mirrored into Think's live cache.\n * Prefer the history helpers below when writing UI messages from subclasses;\n * they sanitize content and enforce row-size limits before delegating here.\n */\n session!: Session;\n\n /** Cached messages — kept in sync with session storage. */\n private _cachedMessages: UIMessage[] = [];\n\n /**\n * Internal onStart steps that failed on this wake and were skipped so the\n * agent could still come up.\n *\n * onStart failures are terminal: partyserver resets its init state and\n * rethrows, so every subsequent wake — including platform alarm retries —\n * re-runs the failing onStart. A data-driven failure (e.g. SQLITE_NOMEM\n * hydrating an oversized transcript) would otherwise permanently brick the\n * DO and drive an unbounded alarm-retry loop (#1710).\n */\n protected _onStartDegradations: OnStartDegradation[] = [];\n\n /**\n * Internal onStart steps that failed on this wake and were skipped so the\n * agent could still come up (see {@link OnStartDegradation}). Empty when\n * boot was clean. Lets hosts and operators surface degraded boots —\n * e.g. via a health RPC — without subclassing.\n */\n getOnStartDegradations(): ReadonlyArray<OnStartDegradation> {\n return [...this._onStartDegradations];\n }\n\n private _activeMessengerContext?: MessengerContext;\n\n private _messengerRuntime?: ThinkMessengerRuntime;\n\n /**\n * WorkerLoader binding for sandboxed extensions.\n * Set this to enable `getExtensions()` and dynamic extension loading.\n */\n extensionLoader?: WorkerLoader;\n\n /**\n * Extension manager — created automatically when `extensionLoader` is set.\n * Use for dynamic `load()` / `unload()` at runtime.\n */\n extensionManager?: import(\"./extensions/manager\").ExtensionManager;\n\n /**\n * Workspace filesystem available in `getTools()` and lifecycle hooks.\n * Defaults to a full `Workspace` backed by the DO's SQLite storage.\n *\n * Typed as `WorkspaceLike` rather than `Workspace` so subclasses can\n * replace it with anything that satisfies the interface — e.g. a proxy\n * that forwards to a shared workspace owned by a parent DO. Override as\n * a class field to skip the default init entirely:\n *\n * ```typescript\n * // Default init with R2 spillover for large files.\n * override workspace = new Workspace({\n * sql: this.ctx.storage.sql,\n * r2: this.env.R2,\n * name: () => this.name\n * });\n *\n * // Or a custom WorkspaceLike — e.g. a parent-owned shared workspace.\n * override workspace: WorkspaceLike = new SharedWorkspace(this);\n * ```\n */\n workspace!: WorkspaceLike;\n\n /**\n * The codemode runtime behind the execute tool, when one has been created\n * via `createExecuteRuntime(this)` / `createExecuteTool(this)` (from\n * `@cloudflare/think/tools/execute`). Gives callables and lifecycle hooks\n * access to approvals (`approve`/`reject`/`pending`), the audit trail\n * (`executions`), `expirePaused`, and snippets.\n */\n codemode?: import(\"@cloudflare/codemode\").CodemodeRuntimeHandle;\n\n /**\n * Include the default workspace Bash tool. Enabled by default so models can\n * run shell-style multi-file workflows against the workspace. Set to `false`\n * to omit it from the built-in workspace tools.\n */\n workspaceBash:\n | boolean\n | NonNullable<Parameters<typeof createWorkspaceTools>[1]>[\"bash\"] = true;\n\n constructor(ctx: DurableObjectState, env: Env) {\n super(ctx, env);\n\n const _onStart = this.onStart.bind(this);\n this.onStart = async () => {\n // 1. Workspace initialization\n if (!this.workspace) {\n this.workspace = new Workspace({\n sql: this.ctx.storage.sql,\n name: () => this.name\n });\n }\n\n // 2. Session configuration (builder phase — context blocks, compaction, skills)\n const baseSession = Session.create(this);\n this.session = await this.configureSession(baseSession);\n this.session.internal_onMessagesChanged(async (event) => {\n switch (event.type) {\n case \"append\":\n if (!event.inserted || event.parentId !== undefined) {\n await this._syncMessages();\n } else {\n this._upsertCachedMessage(event.message as UIMessage);\n }\n // The conversation grew — older messages may have aged out of\n // the keep-recent window. Only schedule the maintenance scan once\n // this session has actually observed oversized media; otherwise a\n // normal text-only chat would pay a row-stat read after every turn.\n this._scheduleMediaEvictionAfterAppend(event.message as UIMessage);\n break;\n case \"update\":\n this._patchCachedMessage(event.message as UIMessage);\n break;\n case \"clear\":\n this._replaceCachedMessages([]);\n break;\n case \"delete\":\n case \"compact\":\n await this._syncMessages();\n break;\n }\n });\n\n await this._initializeSkills();\n\n // Force Session to initialize its tables (assistant_messages,\n // assistant_compactions, assistant_config, etc.) so that subsequent\n // config reads work.\n //\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 const hydrated = await this._runBestEffortOnStartStep(\n \"transcript-hydration\",\n () => this._syncMessages(),\n \"The agent is starting with an empty in-memory message view; \" +\n \"persisted history is untouched. If the error is SQLITE_NOMEM, \" +\n \"the stored transcript is too large to hydrate (often inline \" +\n \"base64 media in tool results) — compact or clear the session \" +\n \"to recover.\"\n );\n if (!hydrated) {\n this._replaceCachedMessages([]);\n }\n this._refreshMediaEvictionSignalFromCache();\n\n // 3-6. Extension initialization (if extensionLoader is set)\n if (this.extensionLoader) {\n await this._initializeExtensions();\n }\n\n // 7. Protocol handlers\n this._resumableStream = new ResumableStream(this.sql.bind(this));\n this._restoreClientTools();\n this._restoreBody();\n this._setupProtocolHandlers();\n this._initializeMessengers();\n\n // 8. User's onStart\n await _onStart();\n\n // 9. Declarative scheduled tasks are code-defined and should reconcile\n // before draining any recovered programmatic work they may enqueue.\n // 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 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 // 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 this._runBestEffortOnStartStep(\n \"durable-work-recovery\",\n async () => {\n await this._recoverSubmissionsOnStart();\n this._recoverWorkflowNotifications();\n if (this._hasPendingSubmissions()) {\n this._startSubmissionDrain();\n }\n if (this._hasPendingWorkflowNotifications()) {\n this._startWorkflowNotificationDrain();\n }\n },\n \"Pending submissions / workflow notifications were not recovered on \" +\n \"this wake; the next successful wake will recover them.\"\n );\n\n // 11. Background bound on the persisted transcript: if hydration was\n // windowed, evict aged inline media so the footprint can converge down\n // (#1710). Runs after `blockConcurrencyWhile` releases — no boot cost.\n if (this._lastHydration?.truncated) {\n this._scheduleMediaEvictionPass({ force: true });\n }\n };\n }\n\n /**\n * Conversation history as Think's live in-memory view.\n *\n * Storage remains the durable source of truth, but runtime logic should read\n * through this cache so in-flight turns, tool updates, and recovery state all\n * observe the same message list. Use `_syncMessages()` only at safe\n * boundaries where a full storage reread cannot drop in-flight state.\n *\n * When the stored transcript exceeds `hydrationByteBudget`, this view is a\n * bounded window of the most recent messages (see `_lastHydration`); the\n * full history remains readable via `session.getHistory()`.\n */\n get messages(): UIMessage[] {\n return this._cachedMessages;\n }\n\n /**\n * Read the durable message path from session storage.\n *\n * Intentionally UNBUDGETED — unlike the cache refresh in `_syncMessages`,\n * which routes through `session.getRecentHistory(hydrationByteBudget)`, this\n * returns the full active path. Callers (message reconciliation, tool-update\n * application) must see every message: reconciliation diffs incoming client\n * messages against the complete server transcript, and a tool result can\n * target any message on the path, so a windowed read would drop rows and\n * corrupt the result.\n *\n * These full reads are not the unbounded boot-time hydration that bricked the\n * DO in #1710: they run during a live turn (never in `onStart`), so an\n * `SQLITE_NOMEM` here surfaces as a recoverable turn-level error rather than a\n * partyserver init-reset/alarm-retry loop. They also inherit step 1's\n * mitigation — `session.getHistory()` now fetches content in bounded chunks\n * (`messagesByPathIds`) instead of carrying blobs through the recursive CTE\n * and its `ORDER BY` sorter — and background media eviction shrinks the stored\n * footprint over time, so the steady-state read size converges down.\n */\n private async _readMessagesFromStorage(): Promise<UIMessage[]> {\n return (await this.session.getHistory()) as UIMessage[];\n }\n\n /**\n * Normalize a tool part's `input` into something the provider will accept.\n *\n * Malformed shapes 400 modern providers and persist forever once written:\n * a stringified-JSON `input` (e.g. `'{\"prompt\":\"a cat\"}'` instead of the\n * object), and any non-object `input` — `null`, `undefined`, `\"\"`, an array,\n * or a primitive — on a settled or interrupted tool call (Anthropic rejects\n * a `tool_use` block whose `input` is not an object). We parse the former and\n * default the latter to an empty object so the tool-call/tool-result pair\n * stays valid. Delegates to the shared `normalizeToolInput` so the read-side\n * repair and the write-side accumulator guard enforce the same invariant.\n */\n private _normalizeToolInput(record: Record<string, unknown>): {\n input: unknown;\n changed: boolean;\n } {\n return normalizeToolInput(\"input\" in record ? record.input : undefined);\n }\n\n /**\n * Whether a tool part already has a settled result the provider accepts, so\n * it must NOT be re-repaired into an errored result.\n *\n * Single source of truth for the terminal tool states, shared by the repair\n * pass and the backstop detector so they cannot drift. Mirror the AI SDK's\n * terminal states: `convertToModelMessages` emits a `tool-result` for\n * `output-available`, `output-error`, AND `output-denied` (a user-denied\n * approval — its denial reason becomes the tool-result). Omitting any of\n * these makes repair re-flip the part every turn — clobbering a real\n * `errorText`/denial with the generic \"interrupted\" message — and makes the\n * backstop falsely drop a valid call.\n */\n private _toolPartHasSettledResult(record: Record<string, unknown>): boolean {\n if (\"output\" in record || \"result\" in record) return true;\n const state = typeof record.state === \"string\" ? record.state : \"\";\n return (\n state === \"output-available\" ||\n state === \"output-error\" ||\n state === \"output-denied\"\n );\n }\n\n /**\n * Tool-call ids that still have no recorded result. After repair this should\n * be empty; a non-empty result means the backstop (`ignoreIncompleteToolCalls`)\n * will drop those calls — i.e. repair missed a shape and should be extended.\n *\n * `approval-responded` is deliberately excluded: an approved server tool has\n * no result *yet*, but it is not incomplete or abandoned — it is waiting for\n * its continuation to run `execute()`. `convertToModelMessages` keeps that\n * call (and the SDK executes it), so flagging it here would log a misleading\n * \"repair gap\" warning and emit a spurious `chat:transcript:repaired` event\n * on every approval continuation.\n */\n private _incompleteToolCallIds(messages: UIMessage[]): string[] {\n const ids: string[] = [];\n for (const message of messages) {\n for (const part of message.parts) {\n const record = part as Record<string, unknown>;\n const toolCallId =\n typeof record.toolCallId === \"string\" ? record.toolCallId : undefined;\n const isToolPart =\n typeof record.type === \"string\" &&\n (record.type.startsWith(\"tool-\") || record.type === \"dynamic-tool\") &&\n toolCallId;\n if (!isToolPart) continue;\n if (record.state === \"approval-responded\") continue;\n if (!this._toolPartHasSettledResult(record)) ids.push(toolCallId);\n }\n }\n return ids;\n }\n\n /**\n * Repair a single interrupted tool call — a tool part with no settled result,\n * left behind when a stream was cut off mid-flight. Returns the replacement\n * part that takes its place in the transcript. `input` has already been\n * normalized to a valid object.\n *\n * The default flips it to an errored tool result so the record survives (no\n * \"disappearing\" tool call) and `convertToModelMessages` still gets a\n * tool-result for it (avoiding `AI_MissingToolResultsError`).\n *\n * Override to customize the repaired shape for client-resolved tools — e.g.\n * convert an interrupted `ask_user` (a question with no server `execute`,\n * normally answered by the user's next message) into a plain text part\n * carrying the question prose, so the model sees it as ordinary conversation\n * rather than a tool error and compaction keeps the question verbatim. This\n * runs DURING transcript repair — before the repaired transcript is persisted\n * and sent to the model — so the conversion shapes the current turn, not just\n * the next one. A returned tool part MUST carry a settled result\n * (`output-available` / `output-error` / `output-denied` or an\n * `output`/`result` field); returning a non-tool part (e.g. text) is fine.\n */\n protected repairInterruptedToolPart(\n part: UIMessage[\"parts\"][number]\n ): UIMessage[\"parts\"][number] {\n return {\n ...part,\n state: \"output-error\",\n errorText: \"The tool call was interrupted before a result was recorded.\"\n } as UIMessage[\"parts\"][number];\n }\n\n private _repairToolTranscriptParts(messages: UIMessage[]): {\n messages: UIMessage[];\n removedToolCalls: number;\n normalizedInputs: number;\n toolCallIds: string[];\n } {\n let removedToolCalls = 0;\n let normalizedInputs = 0;\n const toolCallIds: string[] = [];\n const repaired: UIMessage[] = [];\n\n for (const message of messages) {\n const parts: UIMessage[\"parts\"] = [];\n let messageChanged = false;\n for (const part of message.parts) {\n const record = part as Record<string, unknown>;\n const toolCallId =\n typeof record.toolCallId === \"string\" ? record.toolCallId : undefined;\n const isToolPart =\n typeof record.type === \"string\" &&\n (record.type.startsWith(\"tool-\") || record.type === \"dynamic-tool\") &&\n toolCallId;\n if (!isToolPart) {\n parts.push(part);\n continue;\n }\n\n if (!this._toolPartHasSettledResult(record)) {\n const state = typeof record.state === \"string\" ? record.state : \"\";\n // An approved server tool waits at `approval-responded` until its\n // scheduled continuation runs `execute()`. It is not abandoned, so\n // preserve it verbatim — flipping it to an error (or removing it)\n // would strand the approval and prevent the real result from ever\n // being produced by the continuation.\n if (state === \"approval-responded\") {\n parts.push(part);\n continue;\n }\n // Preserve the interrupted/abandoned tool call instead of deleting\n // it. Deleting makes the call \"disappear\" from the (broadcast)\n // transcript and lets the model silently re-run it. `input` is\n // normalized to a valid object first, then `repairInterruptedToolPart`\n // decides the replacement shape (default: an errored result, so\n // conversion still gets a tool-result and the provider doesn't 400\n // with AI_MissingToolResultsError). Subclasses can override it to\n // preserve client-resolved tools (e.g. `ask_user`) as text.\n const normalized = this._normalizeToolInput(record);\n parts.push(\n this.repairInterruptedToolPart({\n ...part,\n input: normalized.input\n } as UIMessage[\"parts\"][number])\n );\n if (normalized.changed) normalizedInputs++;\n removedToolCalls++;\n messageChanged = true;\n toolCallIds.push(toolCallId);\n continue;\n }\n\n const normalized = this._normalizeToolInput(record);\n if (normalized.changed) {\n parts.push({\n ...part,\n input: normalized.input\n } as UIMessage[\"parts\"][number]);\n normalizedInputs++;\n messageChanged = true;\n continue;\n }\n\n parts.push(part);\n }\n\n repaired.push(messageChanged ? { ...message, parts } : message);\n }\n\n return {\n messages: repaired,\n removedToolCalls,\n normalizedInputs,\n toolCallIds\n };\n }\n\n private async _repairTranscriptForProvider(\n messages: UIMessage[]\n ): Promise<UIMessage[]> {\n const repair = this._repairToolTranscriptParts(messages);\n if (repair.removedToolCalls === 0 && repair.normalizedInputs === 0) {\n return messages;\n }\n\n // Repair preserves every message (orphans are flipped to errored in place,\n // never deleted), so there are no removed rows to delete — only updates.\n for (const message of repair.messages) {\n const original = messages.find(\n (candidate) => candidate.id === message.id\n );\n if (original && original.parts !== message.parts) {\n await this.session.updateMessage(sanitizeMessage(message));\n }\n }\n\n this._replaceCachedMessages(repair.messages);\n this._broadcastMessages();\n this._emit(\"chat:transcript:repaired\", {\n removedToolCalls: repair.removedToolCalls,\n normalizedInputs: repair.normalizedInputs,\n toolCallIds: repair.toolCallIds\n });\n return repair.messages;\n }\n\n /**\n * Run a best-effort internal onStart step, degrading on failure instead of\n * throwing.\n *\n * Throwing out of `onStart` is terminal: partyserver resets its init state\n * and rethrows, so every wake — including platform alarm retries — re-runs\n * the failing `onStart` and fails again. A data-driven failure (oversized\n * transcript, bad declared-task config) would permanently brick the DO and\n * drive an unbounded alarm-retry loop (#1710). Instead, record the\n * degradation, emit `chat:onstart:degraded`, and let the agent come up so\n * it stays reachable for remediation (compaction, clearing, redeploy).\n *\n * Returns `true` when the step succeeded.\n */\n private async _runBestEffortOnStartStep(\n step: OnStartDegradation[\"step\"],\n fn: () => unknown | Promise<unknown>,\n hint: string\n ): Promise<boolean> {\n try {\n await fn();\n return true;\n } catch (error) {\n this._onStartDegradations.push({ step, error });\n console.error(\n `[Think] onStart step \"${step}\" failed; continuing with degraded state. ${hint}`,\n error\n );\n this._emit(\"chat:onstart:degraded\", {\n step,\n error: error instanceof Error ? error.message : String(error)\n });\n return false;\n }\n }\n\n private _mediaEvictionRunning = false;\n private _mediaEvictionScheduled = false;\n private _mediaEvictionObservedOversized = false;\n\n /**\n * Schedule a background media-eviction pass (see `mediaEviction`).\n * Coalesces repeated requests; the timer fires after the current\n * event-loop work (and after `onStart`'s `blockConcurrencyWhile`), so\n * boot and turn latency are unaffected.\n */\n private _scheduleMediaEvictionPass(options?: { force?: boolean }): void {\n if (this._mediaEvictionScheduled || this._mediaEvictionRunning) return;\n const config = resolveMediaEvictionConfig(this.mediaEviction);\n if (!config) return;\n if (!options?.force && !this._mediaEvictionObservedOversized) return;\n this._mediaEvictionScheduled = true;\n setTimeout(() => {\n this._mediaEvictionScheduled = false;\n void this._evictAgedMediaBestEffort();\n }, 0);\n }\n\n private _scheduleMediaEvictionAfterAppend(message: UIMessage): void {\n const config = resolveMediaEvictionConfig(this.mediaEviction);\n if (!config) return;\n if (!this._mediaEvictionObservedOversized) {\n this._mediaEvictionObservedOversized = this._messageMayNeedMediaEviction(\n message,\n config\n );\n }\n if (!this._mediaEvictionObservedOversized) return;\n\n const keepRecent = Math.max(config.keepRecentMessages, MODEL_RECENT_WINDOW);\n if (this._cachedMessages.length > keepRecent) {\n this._scheduleMediaEvictionPass({ force: true });\n }\n }\n\n private _refreshMediaEvictionSignalFromCache(): void {\n const config = resolveMediaEvictionConfig(this.mediaEviction);\n if (!config) {\n this._mediaEvictionObservedOversized = false;\n return;\n }\n this._mediaEvictionObservedOversized = this._cachedMessages.some(\n (message) => this._messageMayNeedMediaEviction(message, config)\n );\n }\n\n private _messageMayNeedMediaEviction(\n message: UIMessage,\n config: ResolvedMediaEvictionConfig\n ): boolean {\n return JSON.stringify(message).length >= config.minPartBytes;\n }\n\n private _warnedEvictionUnsupported = false;\n\n /**\n * Evict oversized inline media from aged stored messages (#1710).\n *\n * Memory-bounded by design: row sizes come from `getHistoryRowStats()`\n * (no content loaded), only rows large enough to contain an evictable\n * part are parsed, and they are processed one at a time via\n * `session.internal_rewriteMessage` — the maintenance write path that\n * skips the full-history token-estimate broadcast a public\n * `updateMessage` performs per row. Evicted values are written to the\n * workspace BEFORE the row is rewritten, so a failed pass never loses\n * data. Best-effort: failures are logged and the next pass retries.\n *\n * The aged cutoff is `keepRecentMessages` clamped to at least\n * `MODEL_RECENT_WINDOW`: messages the model still replays at full\n * fidelity each turn are never rewritten, regardless of configuration.\n *\n * When a pass stops at `maxRowsPerPass` with eligible rows remaining,\n * another pass is scheduled automatically so a large backlog drains\n * without waiting for new appends. Termination is guaranteed: every\n * rewritten row drops below `minPartBytes` and is skipped by later\n * passes, so the eligible set strictly shrinks.\n *\n * Returns the pass totals, or `null` when eviction is disabled, already\n * running, or the provider cannot enumerate row sizes (warned once).\n */\n protected async _evictAgedMediaBestEffort(): Promise<{\n messages: number;\n parts: number;\n bytes: number;\n externalizedBytes: number;\n } | null> {\n if (this._mediaEvictionRunning) return null;\n const config = resolveMediaEvictionConfig(this.mediaEviction);\n if (!config) return null;\n this._mediaEvictionRunning = true;\n let backlogRemains = false;\n try {\n const stats = await this.session.getHistoryRowStats();\n if (!stats) {\n if (!this._warnedEvictionUnsupported) {\n this._warnedEvictionUnsupported = true;\n console.warn(\n \"[Think] mediaEviction is enabled but the configured \" +\n \"SessionProvider does not implement getHistoryRowStats; \" +\n \"media eviction is a no-op for this agent.\"\n );\n }\n return null;\n }\n const keepRecent = Math.max(\n config.keepRecentMessages,\n MODEL_RECENT_WINDOW\n );\n const aged = stats.slice(0, Math.max(0, stats.length - keepRecent));\n\n let processed = 0;\n const totals = { messages: 0, parts: 0, bytes: 0, externalizedBytes: 0 };\n for (const row of aged) {\n // A row smaller than the part threshold cannot contain an\n // evictable value — skip without parsing. Rewritten rows shrink\n // below the threshold, so later passes skip them here too.\n if (row.bytes < config.minPartBytes) continue;\n if (processed >= config.maxRowsPerPass) {\n backlogRemains = true;\n break;\n }\n processed++;\n\n const message = (await this.session.getMessage(\n row.id\n )) as UIMessage | null;\n if (!message) continue;\n\n const result = evictLargeMediaFromMessage(message, {\n minPartBytes: config.minPartBytes,\n externalize: config.externalizeToWorkspace,\n pathFor: (index, extension) =>\n `/attachments/evicted/${message.id}-${index}.${extension}`\n });\n if (!result.changed) continue;\n\n for (const blob of result.blobs) {\n await this.workspace.writeFile(blob.path, blob.data);\n totals.externalizedBytes += blob.data.length;\n }\n await this.session.internal_rewriteMessage(\n sanitizeMessage(result.message)\n );\n totals.messages++;\n totals.parts += result.parts;\n totals.bytes += result.bytes;\n }\n\n if (totals.messages > 0) {\n this._emit(\"chat:media:evicted\", totals);\n }\n return totals;\n } catch (error) {\n console.error(\n \"[Think] media eviction pass failed; a later pass will retry.\",\n error\n );\n return null;\n } finally {\n this._mediaEvictionRunning = false;\n if (backlogRemains) this._scheduleMediaEvictionPass({ force: true });\n }\n }\n\n /** Replace the live cache with a durable storage snapshot. */\n private _replaceCachedMessages(messages: UIMessage[]): UIMessage[] {\n this._cachedMessages = messages;\n return this._cachedMessages;\n }\n\n /**\n * Result of the most recent cache refresh when `hydrationByteBudget` is\n * active. `truncated` means `this.messages` is a bounded recent window of\n * a larger stored transcript.\n */\n protected _lastHydration: {\n truncated: boolean;\n totalContentBytes: number;\n hydratedMessages: number;\n } | null = null;\n\n private _warnedHydrationWindowed = false;\n\n /**\n * Snapshot of the last `chat:hydration:windowed` emit, used to emit on\n * CHANGE rather than on every safe-boundary sync — a chronically\n * oversized session syncs many times per turn and would otherwise spam\n * identical events.\n */\n private _lastWindowedEmit: {\n totalContentBytes: number;\n hydratedMessages: number;\n } | null = null;\n\n /**\n * Refresh the live cache from durable storage at a safe boundary.\n *\n * Bounded by `hydrationByteBudget`: oversized transcripts hydrate as a\n * recent window instead of exhausting the isolate's memory (#1710). The\n * window never shrinks below `MODEL_RECENT_WINDOW` messages, so budgeted\n * hydration cannot starve the model-facing context assembly (which keeps\n * that many recent messages at full fidelity).\n */\n private async _syncMessages(): Promise<UIMessage[]> {\n const budget = this.hydrationByteBudget;\n if (!Number.isFinite(budget) || budget <= 0) {\n this._lastHydration = null;\n this._lastWindowedEmit = null;\n return this._replaceCachedMessages(await this._readMessagesFromStorage());\n }\n\n const recent = await this.session.getRecentHistory(\n budget,\n MODEL_RECENT_WINDOW\n );\n this._lastHydration = {\n truncated: recent.truncated,\n totalContentBytes: recent.totalContentBytes,\n hydratedMessages: recent.messages.length\n };\n if (recent.truncated) {\n if (!this._warnedHydrationWindowed) {\n this._warnedHydrationWindowed = true;\n console.warn(\n `[Think] Stored transcript (${recent.totalContentBytes} bytes) ` +\n `exceeds hydrationByteBudget (${budget} bytes); hydrated the ` +\n `most recent ${recent.messages.length} message(s) instead of ` +\n \"the full history. Durable storage is untouched. Compact the \" +\n \"session (or enable media eviction) to shrink it.\"\n );\n }\n const changed =\n this._lastWindowedEmit === null ||\n this._lastWindowedEmit.totalContentBytes !== recent.totalContentBytes ||\n this._lastWindowedEmit.hydratedMessages !== recent.messages.length;\n if (changed) {\n this._lastWindowedEmit = {\n totalContentBytes: recent.totalContentBytes,\n hydratedMessages: recent.messages.length\n };\n this._emit(\"chat:hydration:windowed\", {\n totalContentBytes: recent.totalContentBytes,\n budgetBytes: budget,\n hydratedMessages: recent.messages.length\n });\n }\n } else {\n this._lastWindowedEmit = null;\n }\n return this._replaceCachedMessages(recent.messages as UIMessage[]);\n }\n\n /** Patch or append one message in the live cache after a durable write. */\n private _upsertCachedMessage(message: UIMessage): void {\n const index = this._cachedMessages.findIndex((m) => m.id === message.id);\n if (index === -1) {\n this._cachedMessages.push(message);\n } else {\n this._cachedMessages[index] = message;\n }\n }\n\n /** Patch a message that is already present in the live cache. */\n private _patchCachedMessage(message: UIMessage): void {\n const index = this._cachedMessages.findIndex((m) => m.id === message.id);\n if (index !== -1) {\n this._cachedMessages[index] = message;\n }\n }\n\n private async _appendMessageToHistory(\n message: UIMessage,\n parentId?: string | null\n ): Promise<UIMessage> {\n const safe = enforceRowSizeLimit(sanitizeMessage(message));\n await this.session.appendMessage(safe, parentId);\n return safe;\n }\n\n private async _updateMessageInHistory(\n message: UIMessage\n ): Promise<UIMessage> {\n const safe = enforceRowSizeLimit(sanitizeMessage(message));\n await this.session.updateMessage(safe);\n return safe;\n }\n\n private async _upsertMessageInHistory(\n message: UIMessage,\n parentId?: string | null\n ): Promise<UIMessage> {\n const safe = enforceRowSizeLimit(sanitizeMessage(message));\n const existing = await this.session.getMessage(safe.id);\n if (existing) {\n await this.session.updateMessage(safe);\n } else {\n await this.session.appendMessage(safe, parentId);\n }\n return safe;\n }\n\n private async _clearHistory(): Promise<void> {\n await this.session.clearMessages();\n // Drop any pending terminal record (#1645) so a stale exhaustion can't\n // replay onto a freshly-cleared (empty) conversation on reconnect. Covers\n // both the WS `chat-clear` path and the programmatic `clearMessages()` API.\n await this._clearChatTerminal();\n }\n\n /** Append a message while keeping Think's live message cache coherent. */\n protected appendMessageToHistory(\n message: UIMessage,\n parentId?: string | null\n ): Promise<UIMessage> {\n return this._appendMessageToHistory(message, parentId);\n }\n\n /** Update a message while keeping Think's live message cache coherent. */\n protected updateMessageInHistory(message: UIMessage): Promise<UIMessage> {\n return this._updateMessageInHistory(message);\n }\n\n /** Refresh Think's live message cache from the durable session path. */\n protected async syncMessagesFromStorage(): Promise<UIMessage[]> {\n return (await this._syncMessages()).slice();\n }\n\n private _aborts = new AbortRegistry();\n private _turnQueue = new TurnQueue();\n protected _resumableStream!: ResumableStream;\n private _pendingResumeConnections: Set<string> = new Set();\n private _lastClientTools: ClientToolSchema[] | undefined;\n private _lastBody: Record<string, unknown> | undefined;\n private _continuation = new ContinuationState<Connection>();\n private _continuationTimer: ReturnType<typeof setTimeout> | null = null;\n // True while a continuation is draining the in-flight tool-result/approval\n // applies on the parallel-tool-batch barrier (#1649 / #1650). Prevents a\n // second drain (and a double-fire) when more results arrive mid-drain — a\n // sibling that re-arms the coalesce timer during a drain is absorbed by the\n // in-progress drain rather than starting its own.\n private _continuationBarrierActive = false;\n private _insideResponseHook = false;\n private _insideInferenceLoop = false;\n private _pendingInteractionPromise: Promise<boolean> | null = null;\n // Serialization tail for client-tool result/approval applies (#1649). Each\n // apply is a read-modify-write of the full message; running siblings from a\n // parallel tool batch concurrently lets last-write-wins clobber the others\n // back to `input-available`. Chaining every apply off this tail makes them\n // commit atomically in arrival order.\n private _interactionApplyTail: Promise<void> = Promise.resolve();\n // The in-flight assistant message for the active streaming turn. Until\n // `_persistAssistantMessage` writes it at a turn boundary, the message lives\n // ONLY in this accumulator — not in storage and not in `this.messages`. A\n // client tool result can arrive over the WebSocket before that write (the\n // tool-call chunk was already broadcast), so a storage-only lookup in\n // `_applyToolUpdateToMessages` would miss the message and the part would\n // later be repaired as \"interrupted\" (#1649). Exposing the accumulator here\n // lets the apply write the result in place so it rides into the eventual\n // persist. Null when no stream is active. Mirrors `@cloudflare/ai-chat`'s\n // `_streamingMessage` handling.\n private _streamingAssistant: StreamAccumulator | null = null;\n private _submitConcurrency = new SubmitConcurrencyController({\n defaultDebounceMs: Think.MESSAGE_DEBOUNCE_MS\n });\n private static MESSAGE_DEBOUNCE_MS = 750;\n private _agentToolForwarders = new Map<\n string,\n Set<(chunk: AgentToolStoredChunk) => void>\n >();\n private _agentToolClosers = new Map<string, Set<() => void>>();\n private _agentToolAbortControllers = new Map<string, AbortController>();\n private _agentToolLastErrors = new Map<string, string>();\n private _agentToolPreTurnAssistantIds = new Map<string, Set<string>>();\n private _agentToolLiveSequences = new Map<string, number>();\n /**\n * Request id → run id for in-flight agent-tool turns (null = resolved as\n * not an agent-tool turn, cached so unrelated turns don't re-query SQLite\n * per frame). Drives frame attribution in {@link broadcast}: a frame\n * belongs to a run iff it carries that run's turn request id, so an error\n * in an unrelated turn or a concurrent run can never leak into another\n * run's state (#1575).\n */\n private _agentToolRunsByRequestId = new Map<string, string | null>();\n private _submissionTableEnsured = false;\n private _workflowNotificationTableEnsured = false;\n private _declaredScheduledTasksTableEnsured = false;\n private _drainingSubmissions = false;\n private _drainingWorkflowNotifications = false;\n private _submissionAbortControllers = new Map<string, AbortController>();\n private _programmaticStreamErrors = new Map<string, string>();\n protected static submissionRecoveryStaleMs = 15 * 60 * 1000;\n\n override broadcast(\n msg: string | ArrayBuffer | ArrayBufferView,\n without?: string[]\n ): void {\n // Inspect frames while any agent-tool run is in flight (live sequences\n // exist for the run's whole lifecycle), not only while a tailer is\n // attached — error capture must not depend on tailer timing (#1575).\n if (\n (this._agentToolForwarders.size > 0 ||\n this._agentToolLiveSequences.size > 0) &&\n typeof msg === \"string\"\n ) {\n try {\n const parsed = JSON.parse(msg) as {\n type?: unknown;\n body?: unknown;\n error?: unknown;\n id?: unknown;\n };\n if (\n parsed.type === MSG_CHAT_RESPONSE &&\n typeof parsed.id === \"string\"\n ) {\n // A frame belongs to a run iff it carries that run's turn request\n // id. Frames from unrelated turns (a user-driven turn on this\n // agent, or another run's turn) resolve to a different — or no —\n // run and are left alone, so concurrent runs cannot\n // cross-contaminate each other's progress or error state (#1575).\n const runId = this._agentToolRunForRequest(parsed.id);\n if (runId !== null) {\n if (parsed.error === true && typeof parsed.body === \"string\") {\n this._agentToolLastErrors.set(runId, parsed.body);\n } else if (\n typeof parsed.body === \"string\" &&\n parsed.body.length > 0\n ) {\n // Advance the live sequence even with no tailer attached so a\n // tailer registering mid-run resumes at the right offset.\n const sequence = this._agentToolLiveSequences.get(runId) ?? 0;\n this._agentToolLiveSequences.set(runId, sequence + 1);\n const chunk = { sequence, body: parsed.body };\n const forwarders = this._agentToolForwarders.get(runId);\n if (forwarders) {\n for (const forward of forwarders) forward(chunk);\n }\n }\n }\n }\n } catch {\n // Non-chat frames pass through unchanged.\n }\n }\n super.broadcast(msg, without);\n }\n\n /**\n * Resolve the agent-tool run whose turn owns a request id, or null when the\n * request is not an agent-tool turn. Falls back to the persisted child-run\n * row (whose `request_id` is written when the run's turn is bound, see\n * `startAgentToolRun`) so attribution survives a DO restart mid-run; either\n * outcome is cached.\n */\n private _agentToolRunForRequest(requestId: string): string | null {\n const cached = this._agentToolRunsByRequestId.get(requestId);\n if (cached !== undefined) return cached;\n const rows = this.sql<{ run_id: string }>`\n SELECT run_id FROM cf_agent_tool_child_runs\n WHERE request_id = ${requestId} AND completed_at IS NULL\n LIMIT 1\n `;\n const runId = rows[0]?.run_id ?? null;\n this._agentToolRunsByRequestId.set(requestId, runId);\n return runId;\n }\n\n override async alarm(): Promise<void> {\n await super.alarm();\n this._startWorkflowNotificationDrain();\n }\n\n // ── Dynamic config ──────────────────────────────────────────────\n\n #configCache: unknown = null;\n\n /**\n * Persist an arbitrary JSON-serializable configuration object for this\n * agent instance. Stored in the Think-private `think_config` table —\n * survives\n * restarts and hibernation. Pass the config shape as a method generic\n * for typed call sites:\n *\n * ```ts\n * this.configure<MyConfig>({ modelTier: \"fast\" });\n * ```\n *\n * Prefer `state` / `setState` from `Agent` when you want the value\n * broadcast to connected clients. Use `configure` for private\n * per-instance config that should stay server-side.\n */\n configure<T = Record<string, unknown>>(config: T): void {\n const json = JSON.stringify(config);\n this._configSet(\"_think_config\", json);\n this.#configCache = config;\n }\n\n /**\n * Read the persisted configuration, or null if never configured.\n * Pass the config shape as a method generic for a typed result:\n *\n * ```ts\n * const cfg = this.getConfig<MyConfig>();\n * ```\n */\n getConfig<T = Record<string, unknown>>(): T | null {\n if (this.#configCache !== null) return this.#configCache as T;\n const raw = this._configGet(\"_think_config\");\n if (raw !== undefined) {\n this.#configCache = JSON.parse(raw);\n return this.#configCache as T;\n }\n return null;\n }\n\n // ── Config storage helpers (think_config table) ─────────────────\n\n #configTableReady = false;\n\n protected _migrateLegacyConfigToThinkTable(): void {\n const rows = this.ctx.storage.sql\n .exec(\n \"SELECT sql FROM sqlite_master WHERE type='table' AND name='assistant_config'\"\n )\n .toArray() as Array<{ sql?: unknown }>;\n if (rows.length === 0) return;\n\n const ddl = String(rows[0].sql ?? \"\");\n if (!ddl.includes(\"session_id\")) return;\n\n // Older Think builds stored private config in Session's shared\n // `assistant_config(session_id, key, value)` table, even though\n // Think always used the empty session id. Copy only the Think-owned\n // keys into the dedicated `think_config` table and leave the shared\n // Session table untouched.\n for (const key of Think.CONFIG_KEYS) {\n const legacyRows = this.sql<{ value: string }>`\n SELECT value FROM assistant_config\n WHERE session_id = '' AND key = ${key}\n `;\n const value = legacyRows[0]?.value;\n if (value !== undefined) {\n this.sql`\n INSERT OR IGNORE INTO think_config (key, value)\n VALUES (${key}, ${value})\n `;\n }\n }\n }\n\n private _ensureConfigTable(): void {\n if (this.#configTableReady) return;\n this.sql`\n CREATE TABLE IF NOT EXISTS think_config (\n key TEXT NOT NULL,\n value TEXT NOT NULL,\n PRIMARY KEY (key)\n )\n `;\n this._migrateLegacyConfigToThinkTable();\n this.#configTableReady = true;\n }\n\n private _configSet(key: string, value: string): void {\n this._ensureConfigTable();\n this.sql`\n INSERT OR REPLACE INTO think_config (key, value)\n VALUES (${key}, ${value})\n `;\n }\n\n private _configGet(key: string): string | undefined {\n this._ensureConfigTable();\n const rows = this.sql<{ value: string }>`\n SELECT value FROM think_config\n WHERE key = ${key}\n `;\n return rows[0]?.value;\n }\n\n private _configDelete(key: string): void {\n this._ensureConfigTable();\n this.sql`\n DELETE FROM think_config\n WHERE key = ${key}\n `;\n }\n\n // ── Configuration overrides ─────────────────────────────────────\n\n /**\n * Return the language model to use for inference.\n * Must be overridden by subclasses.\n */\n getModel(): LanguageModel {\n throw new Error(\"Override getModel() to return a LanguageModel.\");\n }\n\n /**\n * Return the system prompt for the assistant.\n * Used as fallback when no context blocks are configured via `configureSession`.\n */\n getSystemPrompt(): string {\n return [\n \"You are a careful, capable assistant helping the user complete their task.\",\n \"Use available tools when they materially improve accuracy or let you act on the user's request. Before changing code, understand the relevant context: existing patterns, dependencies, tests, and nearby conventions.\",\n \"Keep changes focused on the user's request. Prefer small, idiomatic edits over broad rewrites or new abstractions. Do not introduce new dependencies, secrets, destructive actions, or persistent side effects unless the user clearly asks or approves.\",\n \"When the task is complex, briefly state your approach and keep the user informed with concise progress updates. If you modify code, verify with the smallest relevant test, build, typecheck, lint, or runtime check available, and report any checks you could not run.\",\n \"Be direct and useful in your final response: summarize the outcome, mention important files or commands, and call out real blockers or risks.\"\n ].join(\"\\n\\n\");\n }\n\n /** Return the tools available to the assistant. */\n getTools(): ToolSet {\n return {};\n }\n\n /** Return messenger integrations that should be routed through this Think agent. */\n getMessengers(): ThinkMessengers {\n return {};\n }\n\n getMessengerContext(): MessengerContext | undefined {\n if (this._activeMessengerContext) {\n return this._activeMessengerContext;\n }\n\n const message = this.messages.at(-1) as\n | (UIMessage & { metadata?: { messenger?: MessengerContext } })\n | undefined;\n return message?.metadata?.messenger;\n }\n\n async chatWithMessengerContext(\n userMessage: string | UIMessage,\n callback: StreamCallback,\n context: MessengerContext,\n options?: ChatOptions\n ): Promise<void> {\n const previous = this._activeMessengerContext;\n this._activeMessengerContext = context;\n try {\n await this.chat(userMessage, callback, options);\n } finally {\n this._activeMessengerContext = previous;\n }\n }\n\n private _initializeMessengers(): void {\n if (this.parentPath.length > 0) {\n return;\n }\n\n const messengers = this.getMessengers();\n if (Object.keys(messengers).length === 0) {\n return;\n }\n\n this._messengerRuntime = new ThinkMessengerRuntime(\n messengers,\n this as unknown as MessengerThinkHost\n );\n this._messengerRuntime.initialize();\n }\n\n /** Return code-declared scheduled tasks for this agent. */\n getScheduledTasks(): ThinkScheduledTasks | Promise<ThinkScheduledTasks> {\n return {};\n }\n\n /**\n * Reconcile code-declared scheduled tasks immediately.\n * Static declarations are reconciled on startup automatically; call this\n * after changing app-owned data that `getScheduledTasks()` reads.\n */\n async internal_reconcileScheduledTasks(): Promise<void> {\n await this._reconcileDeclaredScheduledTasks();\n }\n\n /**\n * Return the default timezone for wall-clock scheduled tasks.\n * Task-local timezone declarations take precedence.\n */\n getDefaultTimezone(): string | undefined | Promise<string | undefined> {\n return undefined;\n }\n\n private async _runChatRecoveryFiber<T>(\n requestId: string,\n continuation: boolean,\n fn: () => Promise<T>\n ): Promise<T> {\n const snapshot = createChatFiberSnapshot({\n kind: \"think-chat-turn\",\n requestId,\n recoveryRootRequestId: this._activeChatRecoveryRootRequestId ?? requestId,\n continuation,\n messages: this.messages,\n lastBody: this._lastBody,\n lastClientTools: this._lastClientTools\n });\n\n return this._runFiberWithStashWrapper(\n `${(this.constructor as typeof Think).CHAT_FIBER_NAME}:${requestId}`,\n async () => fn(),\n {\n initialSnapshot: wrapChatFiberSnapshot(\n \"__cfThinkChatFiberSnapshot\",\n snapshot,\n null\n ),\n wrapStash: (data) =>\n wrapChatFiberSnapshot(\"__cfThinkChatFiberSnapshot\", snapshot, data)\n }\n );\n }\n\n private _systemPromptForTurn(baseSystem: string, tools: ToolSet): string {\n if (baseSystem.includes(\"You are running inside a Think agent.\")) {\n return baseSystem;\n }\n\n return `${baseSystem.trimEnd()}\\n\\n${this._buildThinkCapabilityBlock(tools)}`;\n }\n\n private _buildThinkCapabilityBlock(tools: ToolSet): string {\n const toolNames = new Set(Object.keys(tools));\n const hasTools = toolNames.size > 0;\n const hasWorkspaceTools = [\n \"read\",\n \"write\",\n \"edit\",\n \"list\",\n \"find\",\n \"grep\",\n \"delete\"\n ].some((toolName) => toolNames.has(toolName));\n const hasContextTools =\n toolNames.has(\"load_context\") || toolNames.has(\"unload_context\");\n const hasExtensionTools =\n toolNames.has(\"load_extension\") || toolNames.has(\"list_extensions\");\n const hasExecuteTool = toolNames.has(\"execute\");\n\n const lines = [\n \"You are running inside a Think agent.\",\n \"\",\n \"Capabilities available in this turn:\"\n ];\n\n if (hasWorkspaceTools) {\n lines.push(\n \"- You can inspect and edit the agent workspace using the available file tools.\"\n );\n }\n\n if (hasTools) {\n lines.push(\n \"- Use the tools exposed in this turn when they materially improve accuracy or let you act on the user's request. Treat tool descriptions and schemas as the source of truth.\"\n );\n lines.push(\n \"- Some tools may call server code, browser/client code, MCP servers, extensions, or delegated agents. Use them according to their descriptions.\"\n );\n }\n\n if (hasContextTools) {\n lines.push(\n \"- If context-loading tools are available, use them to load relevant memory, skills, or project context before acting on incomplete information.\"\n );\n }\n\n if (hasExtensionTools) {\n lines.push(\n \"- If extension tools are available, use them only when loading or inspecting extensions directly helps with the task.\"\n );\n }\n\n if (hasExecuteTool) {\n lines.push(\n \"- If sandboxed execution is available, prefer it for safe, bounded checks or coordinated multi-step operations.\"\n );\n }\n\n lines.push(\n \"- Do not claim access to capabilities that are not exposed as tools in this turn.\"\n );\n\n return lines.join(\"\\n\");\n }\n\n /** Maximum number of tool-call steps per turn. Override via property or per-turn via TurnConfig. */\n maxSteps = 10;\n\n /**\n * Whether reasoning chunks are sent to chat clients by default. Override\n * per turn by returning `sendReasoning` from `beforeTurn`.\n */\n sendReasoning = true;\n\n /**\n * Inactivity watchdog for the streaming read loop, in milliseconds.\n *\n * If a turn's model stream produces no chunk for this long, the watchdog\n * aborts the turn and surfaces a terminal stream error instead of letting the\n * loop park forever on a hung provider/transport (the \"infinite spinner\"\n * failure: the stream never throws, so no error and no `done` ever arrives).\n * A `chat:stream:stalled` observability event is emitted when it fires.\n *\n * This measures the gap *between UI-message-stream chunks*, which includes\n * time spent executing server-side tools (no chunks flow while a tool runs).\n * Set it comfortably above your slowest expected model time-to-first-token\n * and your slowest tool execution, or you will abort healthy long turns.\n *\n * Default `0` (disabled) — opt in by setting a value (e.g. `120_000`).\n *\n * Can be overridden per-turn via `TurnConfig.chatStreamStallTimeoutMs`\n * (returned from `beforeTurn`) for turns with known-slow tools.\n */\n chatStreamStallTimeoutMs = 0;\n\n /**\n * Per-turn stall-watchdog timeout resolved from `TurnConfig` in\n * `_runInferenceLoop`, read by the stream loop when arming the watchdog.\n * `undefined` falls back to the instance-level `chatStreamStallTimeoutMs`.\n * Turns are serialized, so a single active value is safe; it is reset at the\n * top of every `_runInferenceLoop`.\n */\n private _activeStallTimeoutMs: number | undefined;\n\n // ── Context-overflow handling (opt-in) ────────────────────────────\n //\n // Compaction normally only fires between turns (Session.compactAfter checks\n // the threshold on appendMessage). But a single long, tool-heavy turn grows\n // the prompt step-by-step inside one streamText loop and can exceed the\n // model's context window *mid-turn*, before the next pre-turn check — the\n // provider then 400s (\"prompt is too long\" / context_length_exceeded). The\n // `contextOverflow` config lets Think recover without baking provider\n // knowledge into core: the app classifies the error (`classifyChatError`),\n // Think reacts.\n\n /**\n * Opt-in handling for a turn that overflows the context window mid-flight.\n * See {@link ContextOverflowConfig}. Unset (the default) leaves the existing\n * terminal behavior unchanged.\n *\n * @example\n * ```typescript\n * override contextOverflow = {\n * reactive: true,\n * proactive: { maxInputTokens: 200_000 }\n * };\n * ```\n */\n contextOverflow?: ContextOverflowConfig;\n\n /** Whether the reactive compact-and-retry backstop is enabled. */\n private get _overflowReactiveEnabled(): boolean {\n return this.contextOverflow?.reactive === true;\n }\n\n /** Reactive compact-and-retry budget. */\n private get _overflowMaxRetries(): number {\n return this.contextOverflow?.maxRetries ?? 1;\n }\n\n /** Proactive guard config, when enabled. */\n private get _overflowGuard():\n | { maxInputTokens: number; headroom?: number; maxCompactions?: number }\n | undefined {\n return this.contextOverflow?.proactive;\n }\n\n /** Per-run cap on proactive compactions (independent of the reactive budget). */\n private get _overflowProactiveMaxCompactions(): number {\n return Math.max(1, this.contextOverflow?.proactive?.maxCompactions ?? 1);\n }\n\n /**\n * Count of model messages assembled from history at the start of the current\n * turn (captured in `_runInferenceLoop`). The proactive guard uses it to\n * splice this turn's in-flight steps onto a freshly recompacted head. Turns\n * are serialized, so a single value is safe.\n */\n private _turnModelMessageBaseline = 0;\n\n /**\n * The assembled tool set for the current turn, captured in\n * `_runInferenceLoop`. The proactive guard reuses it to convert the\n * recompacted history through the same `convertToModelMessages` tool schemas.\n * Turns are serialized, so a single value is safe.\n */\n private _activeTurnTools: ToolSet = {};\n\n /**\n * Number of times the proactive guard has compacted within the current\n * `_runInferenceLoop` (reset at the top of each run). Capped at\n * `contextOverflow.proactive.maxCompactions` (default `1`) so a guard that\n * keeps reading over-budget usage can't compact on every step — once the head\n * is summarized, further compaction no-ops anyway, and a genuine remaining\n * overflow falls through to the reactive backstop.\n */\n private _proactiveCompactionsThisRun = 0;\n\n /** One-time guard for the \"recovery enabled but no classifier\" DX warning. */\n private _warnedMissingClassifier = false;\n\n /**\n * Configure the session. Called once during `onStart`.\n * Override to add context blocks, compaction, search, skills.\n *\n * @example\n * ```typescript\n * configureSession(session: Session) {\n * return session\n * .withContext(\"memory\", { description: \"Learned facts\", maxTokens: 2000 })\n * .withCachedPrompt();\n * }\n * ```\n */\n configureSession(session: Session): Session | Promise<Session> {\n return session;\n }\n\n /**\n * Return Agent Skills sources for this Think agent.\n *\n * Bundled skills are typically imported with the Agents Vite plugin:\n *\n * ```typescript\n * import productSkills from \"agents:skills\"; // -> ./skills next to this file\n * ```\n *\n * Sources are applied in order; the first source to register a skill name\n * wins, and later collisions are skipped with a logged warning.\n */\n getSkills(): SkillSource[] | Promise<SkillSource[]> {\n return [];\n }\n\n private async _initializeSkills(): Promise<void> {\n // A misconfigured or failing skill source must never prevent the agent\n // from starting. Any error here is logged and skills stay disabled.\n try {\n const sources = await this.getSkills();\n if (sources.length === 0) return;\n\n const registry = new SkillRegistry(sources, this.getSkillScriptRunner());\n await registry.load();\n this._logSkillWarnings(registry);\n this._skillRegistry = registry;\n\n await this.session.addContext(registry.contextLabel, {\n description: \"Think skills: available skill catalog\",\n provider: {\n get: () => registry.systemPrompt()\n }\n });\n\n const previous = this._configGet(\"skillsFingerprint\");\n if (previous !== registry.fingerprint) {\n await this.session.refreshSystemPrompt();\n this._configSet(\"skillsFingerprint\", registry.fingerprint);\n }\n } catch (error) {\n console.warn(\n `[think] Failed to initialize skills; continuing without them: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n /**\n * Log registry diagnostics (duplicate names, sources that failed to list),\n * deduped by message so a new collision after a deploy still surfaces while\n * the same warning is not repeated on every turn.\n */\n private _logSkillWarnings(registry: SkillRegistry): void {\n for (const warning of registry.warnings) {\n if (this._loggedSkillWarnings.has(warning)) continue;\n this._loggedSkillWarnings.add(warning);\n console.warn(`[think] ${warning}`);\n }\n }\n\n /**\n * Return an optional runner that enables the `run_skill_script` tool.\n *\n * @experimental Skill script execution is experimental and may change\n * before stabilizing.\n */\n getSkillScriptRunner(): SkillScriptRunner | null {\n return null;\n }\n\n private async _refreshSkillsIfChanged(): Promise<void> {\n if (!this._skillRegistry) return;\n\n // Refreshing pulls from live sources (e.g. R2); a transient failure must\n // not break the turn. Keep the last good catalog on error.\n try {\n await this._skillRegistry.refresh();\n this._logSkillWarnings(this._skillRegistry);\n const previous = this._configGet(\"skillsFingerprint\");\n if (previous !== this._skillRegistry.fingerprint) {\n await this.session.refreshSystemPrompt();\n this._configSet(\"skillsFingerprint\", this._skillRegistry.fingerprint);\n }\n } catch (error) {\n console.warn(\n `[think] Failed to refresh skills; using last known catalog: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n /**\n * Return sandboxed extension configurations. Defines load order,\n * which determines hook execution order.\n * Requires `extensionLoader` to be set.\n */\n getExtensions(): ExtensionConfig[] {\n return [];\n }\n\n // ── Lifecycle hooks ───────────────────────────────────────────\n\n /**\n * Called before `streamText` — inspect the assembled context and\n * return overrides. Think assembles tools, system prompt, and messages\n * internally; this hook sees the result and can override any part.\n *\n * Return `void` to accept all defaults.\n *\n * @example Switch model for continuations\n * ```typescript\n * beforeTurn(ctx: TurnContext) {\n * if (ctx.continuation) return { model: this.cheapModel };\n * }\n * ```\n *\n * @example Restrict active tools\n * ```typescript\n * beforeTurn(ctx: TurnContext) {\n * return { activeTools: [\"read\", \"write\"] };\n * }\n * ```\n */\n beforeTurn(\n _ctx: TurnContext\n ): TurnConfig | void | Promise<TurnConfig | void> {}\n\n /**\n * Called before each AI SDK step in the agentic loop. Backed by\n * `streamText({ prepareStep })`.\n *\n * Return `void` to accept the current step defaults, or return a\n * `StepConfig` to override the model, tool choice, active tools,\n * system prompt, messages, experimental context, or provider options\n * for this step. Use `beforeTurn` for turn-wide assembly and\n * `beforeStep` when the decision depends on the step number or\n * previous step results.\n *\n * @example Force search on the first step\n * ```typescript\n * beforeStep(ctx: PrepareStepContext) {\n * if (ctx.stepNumber === 0) {\n * return {\n * activeTools: [\"search\"],\n * toolChoice: { type: \"tool\", toolName: \"search\" }\n * };\n * }\n * }\n * ```\n *\n * @example Switch to a cheaper model after tool results land\n * ```typescript\n * beforeStep(ctx: PrepareStepContext) {\n * // assumes a `fastSummaryModel` field on your Think subclass\n * if (ctx.steps.some((s) => s.toolResults.length > 0)) {\n * return { model: this.fastSummaryModel };\n * }\n * }\n * ```\n */\n beforeStep(\n _ctx: PrepareStepContext\n ): StepConfig | void | Promise<StepConfig | void> {}\n\n /**\n * Called **before** the tool's `execute` function runs. Think wraps\n * every tool's `execute` so it can consult this hook and act on the\n * returned `ToolCallDecision`:\n *\n * - `void` (or `{ action: \"allow\" }` with no `input`) — run the\n * original `execute` with the original input.\n * - `{ action: \"allow\", input }` — run the original `execute` with\n * the substituted input.\n * - `{ action: \"block\", reason }` — skip `execute`; the model sees\n * `reason` as the tool's output.\n * - `{ action: \"substitute\", output }` — skip `execute`; the model\n * sees `output` as the tool's output.\n *\n * Only fires for server-side tools (tools with `execute`). Client\n * tools are handled on the client — Think can't intercept them.\n *\n * `afterToolCall` always fires after this hook (or after the original\n * `execute` when `allow`). For `block`/`substitute`, the substituted\n * value flows through `afterToolCall` as `success: true, output: ...`.\n *\n * @example Log tool calls\n * ```typescript\n * beforeToolCall(ctx: ToolCallContext) {\n * console.log(`Tool called: ${ctx.toolName}`, ctx.input);\n * }\n * ```\n *\n * @example Block a tool the model shouldn't be calling here\n * ```typescript\n * beforeToolCall(ctx: ToolCallContext): ToolCallDecision | void {\n * if (ctx.toolName === \"delete\" && this.isReadOnlyMode) {\n * return { action: \"block\", reason: \"delete is disabled in read-only mode\" };\n * }\n * }\n * ```\n *\n * @example Substitute a cached result\n * ```typescript\n * async beforeToolCall(ctx: ToolCallContext): Promise<ToolCallDecision | void> {\n * if (ctx.toolName === \"weather\") {\n * const cached = await this.cache.get(JSON.stringify(ctx.input));\n * if (cached) return { action: \"substitute\", output: cached };\n * }\n * }\n * ```\n */\n beforeToolCall(\n _ctx: ToolCallContext\n ): ToolCallDecision | void | Promise<ToolCallDecision | void> {}\n\n /**\n * Called **after** a tool's outcome is known — for real executions, for\n * `block` (carries the `reason` as `output`), and for `substitute`\n * (carries the substituted `output`). Backed by the AI SDK's\n * `experimental_onToolCallFinish`, so `durationMs` and the discriminated\n * `success`/`output`/`error` outcome reflect what the model actually\n * sees: a thrown error from the original `execute` becomes\n * `success: false, error: ...`; everything else (including blocked /\n * substituted calls) is `success: true, output: ...`.\n *\n * Override for logging, metrics, or result inspection.\n *\n * @example\n * ```typescript\n * afterToolCall(ctx: ToolCallResultContext) {\n * if (ctx.success) {\n * console.log(`${ctx.toolName} ok in ${ctx.durationMs}ms`);\n * } else {\n * console.error(`${ctx.toolName} failed:`, ctx.error);\n * }\n * }\n * ```\n */\n afterToolCall(_ctx: ToolCallResultContext): void | Promise<void> {}\n\n /**\n * Called after each step completes (initial, continue, tool-result).\n * Override for step-level logging or analytics.\n */\n onStepFinish(_ctx: StepContext): void | Promise<void> {}\n\n /**\n * Called for each streaming chunk. High-frequency — fires per token.\n * Override for streaming analytics, progress indicators, or token counting.\n * Observational only (void return).\n */\n onChunk(_ctx: ChunkContext): void | Promise<void> {}\n\n /**\n * Called after a chat turn completes and the assistant message has been\n * persisted. The turn lock is released before this hook runs, so it is\n * safe to call other methods from inside.\n *\n * Fires for all turn completion paths: WebSocket chat requests,\n * sub-agent RPC, and auto-continuation.\n *\n * Override for logging, chaining, analytics, usage tracking.\n */\n onChatResponse(_result: ChatResponseResult): void | Promise<void> {}\n\n /**\n * Handle an error that occurred during a chat turn.\n * Override to customize error handling (e.g. logging, metrics).\n */\n onChatError(error: unknown, _ctx?: ChatErrorContext): unknown {\n return error;\n }\n\n /**\n * Classify a raw chat-turn error into a provider-agnostic category.\n *\n * Think deliberately ships **no** provider-specific matching: it cannot know\n * that Anthropic's `\"prompt is too long\"` or OpenAI's\n * `context_length_exceeded` means \"context overflow\" without baking provider\n * knowledge into core. The app does know its provider/model, so it owns the\n * mapping — the same split Think already uses for `tokenCounter`.\n *\n * Currently this hook drives **only** context-overflow recovery: it is\n * consulted when a turn errors **and** `contextOverflow.reactive` is enabled\n * (if reactive is off, it is not called). Return `\"context_overflow\"` to run\n * the compact-and-retry backstop; if recovery cannot save the turn, that\n * classification is surfaced on the terminal `onChatError` call via\n * {@link ChatErrorContext.classification}. The other categories are reserved\n * for future use — returning one today is a no-op (the turn terminalizes as\n * usual) and it is **not** forwarded to `onChatError`. Returning\n * `void`/`\"unknown\"` keeps the existing terminal behavior.\n *\n * The argument may be an `Error`, an AI SDK `APICallError` (with\n * `statusCode`/`responseBody`), or — for in-stream provider errors that\n * surface as a stream error part rather than a throw — the error message\n * string. Narrow accordingly.\n *\n * The second argument carries a {@link ChatErrorContext}: when consulted for\n * overflow recovery it is `{ stage: \"stream\", requestId }`, so a classifier\n * can correlate the error with the in-flight turn (e.g. to call\n * {@link cancelChat}).\n *\n * @example Anthropic + OpenAI context-overflow\n * ```typescript\n * classifyChatError(error: unknown): ChatErrorClassification | void {\n * const text = error instanceof Error ? error.message : String(error);\n * if (/prompt is too long|context length|context_length_exceeded|maximum context/i.test(text)) {\n * return \"context_overflow\";\n * }\n * }\n * ```\n */\n classifyChatError(\n _error: unknown,\n _ctx?: ChatErrorContext\n ): ChatErrorClassification | void {}\n\n /**\n * Whether an error (thrown or surfaced as an in-stream error string) should\n * trigger the opt-in compact-and-retry backstop. Consults the app's\n * `classifyChatError` and the `contextOverflow.reactive` flag. Centralized\n * so both stream consumers (WebSocket + RPC) classify identically.\n */\n private _isRecoverableContextOverflow(\n error: unknown,\n requestId?: string\n ): boolean {\n if (!this._overflowReactiveEnabled) return false;\n // DX guard: enabling recovery without teaching Think which errors are\n // overflows silently does nothing. Warn once instead of failing quietly.\n if (this.classifyChatError === Think.prototype.classifyChatError) {\n if (!this._warnedMissingClassifier) {\n this._warnedMissingClassifier = true;\n console.warn(\n '[Think] contextOverflow.reactive is enabled but classifyChatError() is not overridden, so no error will ever be treated as a context overflow and recovery will never run. Override classifyChatError() (or assign the exported defaultContextOverflowClassifier) to return \"context_overflow\" for your provider\\'s context-window error (e.g. Anthropic \"prompt is too long\", OpenAI context_length_exceeded).'\n );\n }\n return false;\n }\n let classification: ChatErrorClassification | void;\n try {\n classification = this.classifyChatError(error, {\n stage: \"stream\",\n requestId\n });\n } catch (err) {\n console.warn(\n `[Think] classifyChatError threw; treating as non-overflow: ${err instanceof Error ? err.message : String(err)}`\n );\n return false;\n }\n return classification === \"context_overflow\";\n }\n\n /**\n * Compact the session in response to a context overflow (reactive backstop or\n * proactive guard). Returns whether history was actually shortened — a no-op\n * compaction (returns `null`) means a retry would just overflow again, so the\n * caller should fall through to the terminal error rather than loop.\n *\n * This is the single emit point for `chat:context:compacted`, so callers must\n * NOT emit it again.\n */\n private async _compactForContextOverflow(\n reason: \"reactive\" | \"proactive\",\n extra?: { requestId?: string; attempt?: number }\n ): Promise<boolean> {\n try {\n const result = await this.session.compact();\n const shortened = Boolean(result);\n this._emit(\"chat:context:compacted\", {\n reason,\n shortened,\n ...extra\n });\n return shortened;\n } catch (err) {\n console.warn(\n `[Think] context-overflow compaction failed: ${err instanceof Error ? err.message : String(err)}`\n );\n return false;\n }\n }\n\n /**\n * Finalize a context overflow that recovery could not fix (compaction was a\n * no-op, or the retry budget is spent). Routes the error through\n * `onChatError` with `classification: \"context_overflow\"` and emits\n * `chat:request:failed`, so every overflow terminal — whichever path it took\n * — is reported identically. Returns the (possibly app-reshaped) message for\n * the caller to deliver via its own transport (RPC callback / WS broadcast).\n */\n private _finalizeContextOverflowError(\n requestId: string,\n rawError: string | undefined\n ): string {\n const raw = rawError ?? \"Context window exceeded.\";\n const wrapped = this.onChatError(raw, {\n requestId,\n stage: \"stream\",\n messagesPersisted: true,\n classification: \"context_overflow\"\n });\n const message =\n wrapped instanceof Error ? wrapped.message : String(wrapped);\n this._emit(\"chat:request:failed\", {\n requestId,\n stage: \"stream\",\n messagesPersisted: true,\n error: message\n });\n return message;\n }\n\n // ── Extension initialization ───────────────────────────────────\n\n private async _initializeExtensions(): Promise<void> {\n // 3. Create ExtensionManager with host binding if HostBridgeLoopback\n // is re-exported from the worker entry point.\n const agentClassName = this.constructor.name;\n const agentId = this.ctx.id.toString();\n const ctxExports = (this.ctx as unknown as Record<string, unknown>)\n .exports as Record<string, unknown> | undefined;\n const hasBridge =\n ctxExports && typeof ctxExports.HostBridgeLoopback === \"function\";\n\n this.extensionManager = new ExtensionManager({\n loader: this.extensionLoader!,\n storage: this.ctx.storage,\n ...(hasBridge\n ? {\n createHostBinding: (\n permissions: import(\"./extensions/types\").ExtensionPermissions,\n ownContextLabels: string[]\n ) =>\n (\n ctxExports.HostBridgeLoopback as (opts: {\n props: Record<string, unknown>;\n }) => Fetcher\n )({\n props: {\n agentClassName,\n agentId,\n permissions,\n ownContextLabels\n }\n })\n }\n : {})\n });\n\n // 4. Load static extensions from getExtensions()\n const configs = this.getExtensions();\n for (const config of configs) {\n await this.extensionManager.load(config.manifest, config.source);\n }\n\n // 5. Restore dynamic extensions from DO storage\n await this.extensionManager.restore();\n\n // 6. Register extension context blocks in Session (mutation phase).\n // Context blocks use SQLite-backed AgentContextProvider (no bridge\n // delegation to the extension Worker). Extensions write to their\n // blocks via host.setContext() (Phase 3). Bridge providers that\n // delegate to extension Worker RPC methods are Phase 4.\n for (const ext of this.extensionManager.list()) {\n const manifest = this.extensionManager.getManifest(ext.name);\n if (!manifest?.context) continue;\n\n const prefix = sanitizeName(ext.name);\n for (const ctxDef of manifest.context) {\n const namespacedLabel = `${prefix}_${ctxDef.label}`;\n await this.session.addContext(namespacedLabel, {\n description: ctxDef.description,\n maxTokens: ctxDef.maxTokens\n });\n }\n }\n\n // Wire unload callback to clean up context blocks\n this.extensionManager.onUnload(async (_name, contextLabels) => {\n for (const label of contextLabels) {\n this.session.removeContext(label);\n }\n await this.session.refreshSystemPrompt();\n });\n }\n\n // ── Inference loop (Think owns this) ──────────────────────────\n\n /**\n * Assemble provider-ready model messages from the current session history:\n * repair the transcript, truncate older messages, drop any still-incomplete\n * tool calls, and convert to `ModelMessage[]`. Shared by the turn entry point\n * and the proactive context guard so a mid-turn recompaction rebuilds the\n * head through the exact same pipeline.\n */\n private async _assembleModelMessages(\n tools: ToolSet\n ): Promise<Awaited<ReturnType<typeof convertToModelMessages>>> {\n const history = await this._repairTranscriptForProvider(this.messages);\n const truncated = truncateOlderMessages(history) as UIMessage[];\n // `_repairTranscriptForProvider` above already heals orphan tool calls\n // (flipping them to errored results, preserving the record). This is the\n // last-line backstop: if any incomplete tool call still slips through\n // (compaction edge, addToolOutput race, an unrecognized part shape), drop it\n // here rather than letting the provider 400 with AI_MissingToolResultsError.\n //\n // The backstop drops silently. Repair should have left nothing incomplete,\n // so a non-empty set here means repair missed a shape — surface it (rather\n // than masking a repair bug) without breaking the turn.\n const incompleteAfterRepair = this._incompleteToolCallIds(truncated);\n if (incompleteAfterRepair.length > 0) {\n console.warn(\n `[Think] ${incompleteAfterRepair.length} incomplete tool call(s) survived transcript repair and will be dropped by ignoreIncompleteToolCalls: ${incompleteAfterRepair.join(\", \")}. This indicates a gap in _repairToolTranscriptParts.`\n );\n this._emit(\"chat:transcript:repaired\", {\n removedToolCalls: incompleteAfterRepair.length,\n normalizedInputs: 0,\n toolCallIds: incompleteAfterRepair\n });\n }\n return convertToModelMessages(truncated, {\n tools,\n ignoreIncompleteToolCalls: true\n });\n }\n\n /**\n * Proactive context guard (Layer 1). Runs before each step from the\n * `prepareStep` wrapper. If `contextOverflow.proactive` is set and the *previous*\n * step's model-reported input tokens cross the budget, compact the session in\n * place and return recompacted messages for the upcoming step — heading off a\n * provider context-overflow 400 before it happens.\n *\n * Keys off `usage.inputTokens` (provider-agnostic; every provider reports it)\n * rather than any provider error string, and reuses `_assembleModelMessages`\n * so the recompacted head goes through the same repair/convert pipeline. The\n * current turn's in-flight steps (everything after `_turnModelMessageBaseline`)\n * are spliced back on so no completed work is lost.\n *\n * Best-effort: any failure (no-op compaction, reconciliation that would leave\n * an incomplete tool pair) returns `undefined` so the step proceeds unchanged\n * and the reactive backstop (`contextOverflow.reactive`) can still\n * catch a genuine overflow.\n */\n private async _maybeProactiveContextCompact(\n event: PrepareStepContext\n ): Promise<Awaited<ReturnType<typeof convertToModelMessages>> | undefined> {\n const guard = this._overflowGuard;\n if (!guard || guard.maxInputTokens <= 0) return undefined;\n // Proactive cap is independent of the reactive budget — it has its own\n // `proactive.maxCompactions` (default 1). This lets an app use the proactive\n // guard without the reactive backstop (and vice versa) and tune each freely.\n if (\n this._proactiveCompactionsThisRun >= this._overflowProactiveMaxCompactions\n )\n return undefined;\n\n const prev = event.steps?.at(-1);\n const used = prev?.usage?.inputTokens ?? prev?.usage?.totalTokens;\n if (used == null || !Number.isFinite(used)) return undefined;\n\n const headroom = guard.headroom ?? 0.9;\n if (used < guard.maxInputTokens * headroom) return undefined;\n\n try {\n // Count the ATTEMPT (not just successful shortenings) before compacting.\n // This bounds the guard to `proactiveCap` tries per run regardless of\n // outcome: a no-op compaction (e.g. nothing left to summarize) would be a\n // no-op again on every subsequent step, so consuming the slot here is\n // what stops it from compacting — and emitting `chat:context:compacted` —\n // on every step. A genuine remaining overflow falls through to the\n // reactive backstop. (Locked by the \"no-op\" proactive test.)\n this._proactiveCompactionsThisRun++;\n const shortened = await this._compactForContextOverflow(\"proactive\");\n if (!shortened) return undefined;\n\n // Rebuild the compacted head, then splice this turn's in-flight steps\n // (which are not yet persisted to the session) back onto the tail.\n const head = await this._assembleModelMessages(this._activeTurnTools);\n const tail = event.messages.slice(this._turnModelMessageBaseline);\n const merged = [...head, ...tail];\n // Re-baseline so a second guard fire this turn keeps the new tail. This\n // is correct only if the AI SDK carries our returned `messages` override\n // forward into the next step's `event.messages` (so the next slice sees\n // [recompacted head, ...in-flight steps], not the original uncompacted\n // array). Verified by the \"fires twice in one turn\" test in\n // assistant-agent-loop.test.ts — a clean multi-fire completion proves the\n // override propagates and the splice does not drop/duplicate tool pairs.\n this._turnModelMessageBaseline = head.length;\n return merged;\n } catch (err) {\n console.warn(\n `[Think] proactive context compaction failed; proceeding without it: ${err instanceof Error ? err.message : String(err)}`\n );\n return undefined;\n }\n }\n\n /**\n * The single convergence point for all chat turn entry paths.\n * Merges tools, assembles context, fires lifecycle hooks, wraps tools\n * for interception, and calls streamText.\n */\n private async _runInferenceLoop(input: TurnInput): Promise<StreamableResult> {\n // Reset the per-turn watchdog override; `beforeTurn` may set it below. A\n // turn that doesn't override falls back to the instance-level value.\n this._activeStallTimeoutMs = undefined;\n // Reset the proactive-compaction cap for this streamText run.\n this._proactiveCompactionsThisRun = 0;\n if (this.waitForMcpConnections) {\n const timeout =\n typeof this.waitForMcpConnections === \"object\"\n ? this.waitForMcpConnections.timeout\n : 10_000;\n await this.mcp.waitForConnections({ timeout });\n }\n\n const workspaceTools = createWorkspaceTools(this.workspace, {\n bash: this.workspaceBash\n });\n const baseTools = this.getTools();\n const extensionTools = this.extensionManager?.getTools() ?? {};\n await this._refreshSkillsIfChanged();\n const contextTools = await this.session.tools();\n const skillTools = this._skillRegistry?.tools() ?? {};\n const clientToolSet = createToolsFromClientSchemas(\n input.clientTools,\n input.clientToolExecutor\n ? { execute: input.clientToolExecutor }\n : undefined\n );\n const tools: ToolSet = {\n ...workspaceTools,\n ...baseTools,\n ...extensionTools,\n ...contextTools,\n ...skillTools,\n ...(this.mcp?.getAITools?.() ?? {}),\n ...clientToolSet\n };\n\n const frozenPrompt = await this.session.freezeSystemPrompt();\n const baseSystem = frozenPrompt || this.getSystemPrompt();\n const system = this._systemPromptForTurn(baseSystem, tools);\n\n const messages = await this._assembleModelMessages(tools);\n\n if (messages.length === 0) {\n throw new Error(\n \"No messages to send to the model. This usually means the chat request \" +\n \"arrived before any messages were persisted.\"\n );\n }\n\n const model = this.getModel();\n const ctx: TurnContext = {\n system,\n messages,\n tools,\n model,\n continuation: input.continuation,\n body: input.body\n };\n\n const subclassConfig = (await this.beforeTurn(ctx)) ?? {};\n const config = await this._pipelineExtensionBeforeTurn(ctx, subclassConfig);\n const workflowPrompt = input.workflowPrompt;\n // 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 = config.model ?? model;\n const finalSystem =\n config.system ??\n this._systemPromptForTurn(\n baseSystem,\n config.tools ? { ...tools, ...config.tools } : tools\n );\n const finalMessages = ensureValidContinueCheckpoint(\n config.messages ?? messages\n );\n const mergedTools: ToolSet = config.tools\n ? { ...tools, ...config.tools }\n : tools;\n // Wrap each tool's `execute` so `beforeToolCall` is consulted before\n // the tool actually runs. The wrapped `execute` honors the returned\n // `ToolCallDecision` — `block` short-circuits with `reason`,\n // `substitute` returns `output` directly, `allow` runs the original\n // (optionally with modified `input`).\n const finalTools: ToolSet = this._wrapToolsWithDecision(mergedTools);\n // 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 const finalMaxSteps = config.maxSteps ?? this.maxSteps;\n const finalSendReasoning = config.sendReasoning ?? this.sendReasoning;\n // Resolve the per-turn stall-watchdog override (explicit `0` = off for this\n // turn). Read by `_streamResult` / `_streamResultToRpcCallback` when arming\n // the watchdog. `??` so a `0` override is honored, not treated as \"unset\".\n this._activeStallTimeoutMs =\n config.chatStreamStallTimeoutMs ?? this.chatStreamStallTimeoutMs;\n // `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 result = streamText({\n model: finalModel,\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: config.experimental_telemetry,\n // Forward the per-turn stream transform(s) from TurnConfig so callers\n // can inspect/rewrite the stream (e.g. emit `source` parts derived from\n // tool results) without owning the stream pipeline themselves.\n experimental_transform: config.experimental_transform,\n // Forward the per-turn structured-output spec from TurnConfig so\n // callers can use AI SDK `Output.object({ schema })` / `Output.text()`\n // on the terminal turn without dropping tools at model construction.\n output: finalOutput,\n abortSignal: input.signal,\n // Forward the AI SDK's `prepareStep` callback unchanged so subclasses\n // can make per-step decisions from the previous steps, current\n // messages, model, and experimental context.\n //\n // Subclass-only by design: extension dispatch is intentionally not\n // wired here. The prepareStep event includes a live `LanguageModel`\n // instance which is not JSON-serializable, and a returned override\n // can include the same — there's no useful \"snapshot, override\"\n // contract we could give to sandboxed extensions. If we expose\n // observation-only later it should go through a separate,\n // serialized event surface.\n //\n // `beforeStep` returning `void`/`undefined`/`null` is normalized to\n // `{}` so the AI SDK falls back to top-level settings (it accepts\n // `undefined` per docs but the typed return is non-null).\n prepareStep: (async (event) => {\n // Proactive context guard (Layer 1) runs first so `beforeStep` sees the\n // recompacted messages and can still override them if it wants to.\n const guarded = await this._maybeProactiveContextCompact(event);\n const result = await this.beforeStep(event);\n const base = result == null ? {} : result;\n // Only apply the guard's recompacted messages when the subclass didn't\n // set its own `messages` override for this step.\n const baseMessages = (base as { messages?: unknown }).messages;\n const withMessages =\n guarded && baseMessages === undefined\n ? { ...base, messages: guarded }\n : base;\n // Safety net for structured workflow turns: on the final permitted step,\n // force the model to call `final_answer` so the turn always terminates\n // with a schema-shaped result instead of running out of steps. Respect a\n // `toolChoice` the subclass already set for this step.\n if (\n wantsStructuredOutput &&\n event.stepNumber >= finalMaxSteps - 1 &&\n (withMessages as { toolChoice?: unknown }).toolChoice === undefined\n ) {\n return {\n ...withMessages,\n toolChoice: {\n type: \"tool\" as const,\n toolName: finalAnswerToolName\n },\n activeTools: [finalAnswerToolName]\n };\n }\n return withMessages;\n }) satisfies PrepareStepFunction<ToolSet>,\n onChunk: async (event) => {\n // Pass the AI SDK's chunk event through unchanged — gives users\n // access to the discriminated `TextStreamPart` chunk with all\n // provider metadata.\n await this.onChunk(event);\n await this._pipelineExtensionChunk(event);\n },\n onStepFinish: async (event) => {\n // Pass the full StepResult through — gives users access to\n // reasoning, sources, files, providerMetadata (cache tokens),\n // request/response, warnings, and the full LanguageModelUsage\n // that the AI SDK provides.\n await this.onStepFinish(event);\n await this._pipelineExtensionStepFinish(event);\n },\n // `beforeToolCall` is dispatched from the wrapped `execute` (see\n // `_wrapToolsWithDecision` above) so the returned `ToolCallDecision`\n // can actually intercept the call. `afterToolCall` is wired through\n // the AI SDK's `experimental_onToolCallFinish` callback so we get\n // accurate `durationMs` and the discriminated `success`/`error`\n // outcome — including failures that propagate out of `execute`.\n experimental_onToolCallFinish: (async (event) => {\n // 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 if (event.toolCall.toolName === finalAnswerToolName) return;\n const base = {\n ...event.toolCall,\n stepNumber: event.stepNumber,\n messages: event.messages,\n durationMs: event.durationMs\n };\n const ctx = (\n event.success\n ? { ...base, success: true as const, output: event.output }\n : { ...base, success: false as const, error: event.error }\n ) as ToolCallResultContext;\n await this.afterToolCall(ctx);\n await this._pipelineExtensionToolCallFinish(event);\n }) satisfies StreamTextOnToolCallFinishCallback<ToolSet>\n });\n\n const outputPromise = wantsStructuredOutput\n ? // Structured workflow result = the `final_answer` tool call's INPUT\n // (its arguments), captured after the stream finishes. Take the last\n // call in case the model emitted more than one. `result.toolCalls` is a\n // `PromiseLike`, so wrap it to get a real `Promise` (for `.catch` below).\n Promise.resolve(result.toolCalls).then((calls) => {\n const finalCalls = calls.filter(\n (call) => call.toolName === finalAnswerToolName\n );\n const last = finalCalls[finalCalls.length - 1];\n if (!last) {\n throw new Error(\n `Model ended the turn without calling the ${finalAnswerToolName} tool`\n );\n }\n return last.input;\n })\n : finalOutput && result.output\n ? Promise.resolve(result.output)\n : undefined;\n if (outputPromise) {\n // Attach a rejection observer immediately. `_streamResult()` will still\n // await this promise when captureOutput is enabled, but aborted streams can\n // reject before the stream consumer reaches that point.\n void outputPromise.catch(() => {});\n }\n\n const streamResult = {\n toUIMessageStream: () =>\n result.toUIMessageStream({ sendReasoning: finalSendReasoning }),\n output: outputPromise\n } satisfies StreamableResult;\n\n return this._transformInferenceResult(streamResult);\n }\n\n /** @internal Test seam — override in test agents to wrap the stream (e.g. error injection). */\n protected _transformInferenceResult(\n result: StreamableResult\n ): StreamableResult {\n return result;\n }\n\n /** Default hook timeout in milliseconds. */\n hookTimeout = 5000;\n\n /**\n * Pipeline beforeTurn through sandboxed extensions in load order.\n * Each extension sees the accumulated state from prior extensions\n * (snapshot is rebuilt after each extension's modifications).\n * Results are merged with last-write-wins for scalar fields.\n * Extensions that don't subscribe to beforeTurn are skipped.\n */\n private async _pipelineExtensionBeforeTurn(\n ctx: TurnContext,\n subclassConfig: TurnConfig\n ): Promise<TurnConfig> {\n if (!this.extensionManager) return subclassConfig;\n\n const subscribers = this.extensionManager.getHookSubscribers(\"beforeTurn\");\n if (subscribers.length === 0) return subclassConfig;\n\n const { createTurnContextSnapshot, parseHookResult } =\n await import(\"./extensions/hook-proxy\");\n\n let snapshot = createTurnContextSnapshot(ctx);\n let accumulated = { ...subclassConfig };\n\n // Apply subclass config to the initial snapshot so extensions\n // see the subclass overrides\n if (accumulated.system !== undefined) snapshot.system = accumulated.system;\n if (accumulated.maxSteps !== undefined)\n snapshot.messageCount = ctx.messages.length;\n\n for (const sub of subscribers) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n const resultJson = await Promise.race([\n sub.entrypoint.hook(\"beforeTurn\", snapshot),\n new Promise<string>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(`Hook timeout: ${sub.name}`)),\n this.hookTimeout\n );\n })\n ]);\n\n const parsed = parseHookResult(resultJson);\n if (\"config\" in parsed) {\n // Merge serializable scalars only. model and tools are skipped —\n // sandboxed extensions can't return LanguageModel or AI SDK Tool\n // objects (not serializable across RPC). Use activeTools to\n // control which tools the model can call.\n if (parsed.config.system !== undefined)\n accumulated.system = parsed.config.system;\n if (parsed.config.messages !== undefined)\n accumulated.messages = parsed.config.messages;\n if (parsed.config.activeTools !== undefined)\n accumulated.activeTools = parsed.config.activeTools;\n if (parsed.config.toolChoice !== undefined)\n accumulated.toolChoice = parsed.config.toolChoice;\n if (parsed.config.maxSteps !== undefined)\n accumulated.maxSteps = parsed.config.maxSteps;\n if (parsed.config.sendReasoning !== undefined)\n accumulated.sendReasoning = parsed.config.sendReasoning;\n if (parsed.config.maxOutputTokens !== undefined)\n accumulated.maxOutputTokens = parsed.config.maxOutputTokens;\n if (parsed.config.temperature !== undefined)\n accumulated.temperature = parsed.config.temperature;\n if (parsed.config.topP !== undefined)\n accumulated.topP = parsed.config.topP;\n if (parsed.config.topK !== undefined)\n accumulated.topK = parsed.config.topK;\n if (parsed.config.presencePenalty !== undefined)\n accumulated.presencePenalty = parsed.config.presencePenalty;\n if (parsed.config.frequencyPenalty !== undefined)\n accumulated.frequencyPenalty = parsed.config.frequencyPenalty;\n if (parsed.config.stopSequences !== undefined)\n accumulated.stopSequences = parsed.config.stopSequences;\n if (parsed.config.seed !== undefined)\n accumulated.seed = parsed.config.seed;\n if (parsed.config.maxRetries !== undefined)\n accumulated.maxRetries = parsed.config.maxRetries;\n if (parsed.config.timeout !== undefined)\n accumulated.timeout = parsed.config.timeout;\n if (parsed.config.headers !== undefined) {\n accumulated.headers = {\n ...(accumulated.headers ?? {}),\n ...parsed.config.headers\n };\n }\n if (parsed.config.providerOptions !== undefined) {\n accumulated.providerOptions = {\n ...(accumulated.providerOptions ?? {}),\n ...parsed.config.providerOptions\n };\n }\n // Update snapshot so next extension sees this extension's changes\n if (accumulated.system !== undefined)\n snapshot = { ...snapshot, system: accumulated.system };\n if (accumulated.activeTools !== undefined)\n snapshot = { ...snapshot, toolNames: accumulated.activeTools };\n } else if (\"error\" in parsed) {\n console.warn(\n `[Think] Extension \"${sub.name}\" beforeTurn error:`,\n parsed.error\n );\n }\n } catch (err) {\n console.warn(\n `[Think] Extension \"${sub.name}\" beforeTurn failed:`,\n err instanceof Error ? err.message : err\n );\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n\n return accumulated;\n }\n\n /**\n * Dispatch an observation hook to all extensions that subscribe to it.\n *\n * Used by `_pipelineExtensionToolCallStart`, `_pipelineExtensionToolCallFinish`,\n * `_pipelineExtensionStepFinish`, and `_pipelineExtensionChunk`. Unlike\n * `beforeTurn`, these hooks are observation-only — extensions can't\n * influence the turn — so we ignore return values, log errors, and\n * apply a per-extension timeout.\n *\n * `onChunk` is high-frequency (per token) — extensions that subscribe\n * to it pay an RPC cost per chunk and should be used sparingly.\n */\n private async _dispatchExtensionObservation(\n hookName: \"beforeToolCall\" | \"afterToolCall\" | \"onStepFinish\" | \"onChunk\",\n snapshot: unknown\n ): Promise<void> {\n if (!this.extensionManager) return;\n const subscribers = this.extensionManager.getHookSubscribers(hookName);\n if (subscribers.length === 0) return;\n\n for (const sub of subscribers) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n sub.entrypoint.hook(hookName, snapshot),\n new Promise<string>((_, reject) => {\n timer = setTimeout(\n () => reject(new Error(`Hook timeout: ${sub.name}`)),\n this.hookTimeout\n );\n })\n ]);\n } catch (err) {\n console.warn(\n `[Think] Extension \"${sub.name}\" ${hookName} failed:`,\n err instanceof Error ? err.message : err\n );\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n }\n\n /**\n * Wrap each tool's `execute` function so the agent's `beforeToolCall`\n * hook is consulted before the tool runs. The hook can return a\n * `ToolCallDecision` to:\n *\n * - `allow` (default if `void` is returned) — run the original\n * `execute`, optionally with a substituted `input`.\n * - `block` — skip `execute` and return `reason` (or a default string)\n * as the tool result. The model sees this as the tool's output.\n * - `substitute` — skip `execute` and return `output` directly. The\n * model sees this as the tool's output.\n *\n * The wrapped `execute` also dispatches the `beforeToolCall`\n * observation snapshot to subscribed extensions. `afterToolCall` is\n * still wired through the AI SDK's `experimental_onToolCallFinish`\n * callback so we get accurate `durationMs` and proper success/error\n * discrimination — `block` and `substitute` outcomes show up as\n * `success: true` with the substituted output; uncaught throws from\n * the original `execute` show up as `success: false` with the error.\n *\n * Tools without an `execute` (output-schema-only tools, client tools\n * routed via `needsApproval`) are left untouched.\n *\n * **Streaming tools (AsyncIterable):** the AI SDK supports tools whose\n * `execute` returns `AsyncIterable<output>` to emit preliminary\n * results before a final value. This works whether the iterator is\n * returned directly (sync function, `async function*`) or wrapped in\n * a Promise (`async function execute(...) { return makeIter(); }`).\n * Because the wrapper must `await beforeToolCall` first, preliminary\n * chunks are collapsed — only the *final* yielded value reaches the\n * model. If you need true preliminary streaming, override\n * `getTools()` to provide such tools and avoid using `beforeToolCall`\n * for them (or accept the collapse).\n */\n private _wrapToolsWithDecision(tools: ToolSet): ToolSet {\n const wrapped: ToolSet = {};\n for (const [toolName, originalTool] of Object.entries(tools)) {\n const t = originalTool as Record<string, unknown>;\n const originalExecute = t.execute as\n | ((input: unknown, options: unknown) => unknown | Promise<unknown>)\n | undefined;\n if (typeof originalExecute !== \"function\") {\n wrapped[toolName] = originalTool;\n continue;\n }\n\n const isDynamic = t.type === \"dynamic\";\n\n const wrappedExecute = async (\n input: unknown,\n options: {\n toolCallId: string;\n messages: ModelMessage[];\n abortSignal?: AbortSignal;\n experimental_context?: unknown;\n }\n ): Promise<unknown> => {\n // Build the discriminated `TypedToolCall`-shaped context.\n const toolCallBase = {\n type: \"tool-call\" as const,\n toolCallId: options.toolCallId,\n toolName,\n input,\n ...(isDynamic ? { dynamic: true as const } : {})\n };\n\n const ctx = {\n ...toolCallBase,\n stepNumber: undefined,\n messages: options.messages,\n abortSignal: options.abortSignal\n } as ToolCallContext;\n\n // Subclass decision first.\n const decision = await this.beforeToolCall(ctx);\n\n // Extension observation dispatch — runs after the subclass so\n // extensions see whatever effect the subclass had on the\n // decision shape (input substitution shows up in the snapshot).\n const dispatchInput =\n decision && decision.action === \"allow\" && decision.input\n ? decision.input\n : input;\n await this._pipelineExtensionToolCallStart({\n toolCall: {\n ...toolCallBase,\n input: dispatchInput\n } as TypedToolCall<ToolSet>,\n stepNumber: undefined\n });\n\n // Resolve the decision.\n if (!decision || decision.action === \"allow\") {\n const finalInput = decision?.input ?? input;\n // Await before inspecting so we detect AsyncIterable returns\n // whether the original `execute` returned them directly (sync\n // function or `async function*`) or wrapped in a Promise (a\n // plain async function that returns an iterator). Without the\n // await, `Symbol.asyncIterator in result` would be false for\n // any `Promise<AsyncIterable>`, the collapse below would be\n // skipped, and the AI SDK would treat the iterator instance\n // itself as the final output value (broken).\n const result = await originalExecute(finalInput, options);\n // If the resolved value is an AsyncIterable (streaming tool\n // emitting preliminary outputs), collapse to the last yielded\n // value. We trade preliminary streaming for `beforeToolCall`\n // interception support.\n if (\n result != null &&\n typeof result === \"object\" &&\n Symbol.asyncIterator in (result as object)\n ) {\n let last: unknown;\n for await (const part of result as AsyncIterable<unknown>) {\n last = part;\n }\n return last;\n }\n return result;\n }\n if (decision.action === \"block\") {\n return (\n decision.reason ??\n `Tool \"${toolName}\" was blocked by beforeToolCall.`\n );\n }\n // substitute\n return decision.output;\n };\n\n wrapped[toolName] = {\n ...(originalTool as object),\n execute: wrappedExecute\n } as ToolSet[string];\n }\n return wrapped;\n }\n\n private async _pipelineExtensionToolCallStart(event: {\n toolCall: TypedToolCall<ToolSet>;\n stepNumber: number | undefined;\n }): Promise<void> {\n if (!this.extensionManager) return;\n if (this.extensionManager.getHookSubscribers(\"beforeToolCall\").length === 0)\n return;\n const { createToolCallStartSnapshot } =\n await import(\"./extensions/hook-proxy\");\n await this._dispatchExtensionObservation(\n \"beforeToolCall\",\n createToolCallStartSnapshot(event)\n );\n }\n\n private async _pipelineExtensionToolCallFinish(event: {\n toolCall: TypedToolCall<ToolSet>;\n stepNumber: number | undefined;\n durationMs: number;\n success: boolean;\n output?: unknown;\n error?: unknown;\n }): Promise<void> {\n if (!this.extensionManager) return;\n if (this.extensionManager.getHookSubscribers(\"afterToolCall\").length === 0)\n return;\n const { createToolCallFinishSnapshot } =\n await import(\"./extensions/hook-proxy\");\n await this._dispatchExtensionObservation(\n \"afterToolCall\",\n createToolCallFinishSnapshot(event)\n );\n }\n\n private async _pipelineExtensionStepFinish(\n event: StepContext\n ): Promise<void> {\n if (!this.extensionManager) return;\n if (this.extensionManager.getHookSubscribers(\"onStepFinish\").length === 0)\n return;\n const { createStepFinishSnapshot } =\n await import(\"./extensions/hook-proxy\");\n await this._dispatchExtensionObservation(\n \"onStepFinish\",\n createStepFinishSnapshot(event)\n );\n }\n\n private async _pipelineExtensionChunk(event: ChunkContext): Promise<void> {\n if (!this.extensionManager) return;\n if (this.extensionManager.getHookSubscribers(\"onChunk\").length === 0)\n return;\n const { createChunkSnapshot } = await import(\"./extensions/hook-proxy\");\n await this._dispatchExtensionObservation(\n \"onChunk\",\n createChunkSnapshot(event as { chunk: { type: string } })\n );\n }\n\n // ── Host bridge methods (called by HostBridgeLoopback via DO RPC) ──\n\n async _hostReadFile(path: string): Promise<string | null> {\n return (await this.workspace.readFile(path)) ?? null;\n }\n\n async _hostWriteFile(path: string, content: string): Promise<void> {\n await this.workspace.writeFile(path, content);\n }\n\n async _hostDeleteFile(path: string): Promise<boolean> {\n try {\n await this.workspace.rm(path);\n return true;\n } catch {\n return false;\n }\n }\n\n async _hostListFiles(\n dir: string\n ): Promise<\n Array<{ name: string; type: string; size: number; path: string }>\n > {\n const entries = await this.workspace.readDir(dir);\n return entries.map((e) => ({\n name: e.name,\n type: e.type,\n size: e.size ?? 0,\n path: e.path ?? `${dir}/${e.name}`\n }));\n }\n\n async _hostGetContext(label: string): Promise<string | null> {\n const block = this.session.getContextBlock(label);\n return block?.content ?? null;\n }\n\n async _hostSetContext(label: string, content: string): Promise<void> {\n await this.session.replaceContextBlock(label, content);\n }\n\n async _hostGetMessages(\n limit?: number\n ): Promise<Array<{ id: string; role: string; content: string }>> {\n const history = this.messages;\n const sliced =\n limit !== undefined && limit !== null\n ? limit <= 0\n ? []\n : history.slice(-limit)\n : history;\n return sliced.map((m) => ({\n id: m.id,\n role: m.role,\n content: m.parts\n .filter((p): p is { type: \"text\"; text: string } => p.type === \"text\")\n .map((p) => p.text)\n .join(\"\")\n }));\n }\n\n async _hostSendMessage(content: string): Promise<void> {\n const msg = {\n id: crypto.randomUUID(),\n role: \"user\" as const,\n parts: [{ type: \"text\" as const, text: content }]\n };\n // Append directly to session — do NOT route through saveMessages,\n // which enqueues a full turn via TurnQueue and would deadlock if\n // called during an active turn (tool execution → host.sendMessage\n // → saveMessages → TurnQueue.enqueue → awaits current turn → deadlock).\n // The injected message is visible in the next turn's history.\n await this._appendMessageToHistory(msg);\n }\n\n async _hostGetSessionInfo(): Promise<{\n messageCount: number;\n }> {\n return {\n messageCount: this.messages.length\n };\n }\n\n // ── Sub-agent RPC entry point ───────────────────────────────────\n\n /**\n * Run a chat turn: persist the user message, run the agentic loop,\n * stream UIMessageChunk events via callback, and persist the\n * assistant's response.\n *\n * @param userMessage The user's message (string or UIMessage)\n * @param callback Streaming callback (typically an RpcTarget from the parent)\n * @param options Optional chat options (e.g. AbortSignal)\n */\n async chat(\n userMessage: string | UIMessage,\n callback: StreamCallback,\n options?: ChatOptions\n ): Promise<void> {\n const requestId = crypto.randomUUID();\n const abortSignal = this._aborts.getSignal(requestId);\n const detachExternal = this._aborts.linkExternal(\n requestId,\n options?.signal\n );\n const ignoredTools = (options as { tools?: unknown } | undefined)?.tools;\n if (\n ignoredTools != null &&\n typeof ignoredTools === \"object\" &&\n Object.keys(ignoredTools).length > 0\n ) {\n console.warn(\n \"[Think] chat() no longer accepts options.tools. Define durable tools on the child agent with getTools(), or use runAgentTool()/agentTool() for parent-child orchestration.\"\n );\n }\n\n // 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.keepAliveWhile(async () => {\n await this._turnQueue.enqueue(requestId, async () => {\n const userMsg: UIMessage =\n typeof userMessage === \"string\"\n ? {\n id: crypto.randomUUID(),\n role: \"user\",\n parts: [{ type: \"text\", text: userMessage }]\n }\n : userMessage;\n\n await this._appendMessageToHistory(userMsg);\n this._broadcastMessages();\n\n const chatBody = async () => {\n // Bounded compact-and-retry loop (opt-in via\n // `contextOverflow.reactive`). A turn that overflows the context\n // window mid-flight is compacted and re-run from the persisted\n // partial instead of dying terminally. Every attempt re-runs the\n // SAME user turn from the now-compacted history, so it stays\n // `continuation: false` — an overflow retry is not an\n // auto-continuation, and `beforeTurn` should not treat it as one.\n for (let attempt = 0; ; attempt++) {\n let result: StreamableResult;\n try {\n result = await agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n clientTools,\n clientToolExecutor,\n continuation: false\n })\n );\n } catch (error) {\n const wrapped = this.onChatError(error, {\n stage: \"turn\",\n messagesPersisted: true\n });\n const errorMessage =\n wrapped instanceof Error ? wrapped.message : String(wrapped);\n this._emit(\"chat:request:failed\", {\n stage: \"turn\",\n messagesPersisted: true,\n error: errorMessage\n });\n await callback.onError(errorMessage);\n return;\n }\n\n // The consumer suppresses a classified overflow whenever recovery\n // is enabled; the driver (here) owns the retry-vs-terminal call so\n // every overflow terminal is reported identically.\n const { status, error } = await this._streamResultToRpcCallback(\n requestId,\n result,\n callback,\n abortSignal,\n { overflowRecovery: this._overflowReactiveEnabled }\n );\n\n if (status === \"overflow_retry\") {\n if (\n attempt < this._overflowMaxRetries &&\n !abortSignal?.aborted\n ) {\n const shortened = await this._compactForContextOverflow(\n \"reactive\",\n { requestId, attempt: attempt + 1 }\n );\n // Compaction shortened history → retry. A no-op compaction\n // can't fix the overflow, so fall through to terminal.\n if (shortened) continue;\n }\n // Budget spent, aborted, or compaction no-op: deliver terminally\n // (through onChatError, classified) so the turn never loops or ends\n // silently with no answer.\n const message = this._finalizeContextOverflowError(\n requestId,\n error\n );\n await callback.onError(message);\n }\n return;\n }\n };\n\n if (this.chatRecovery) {\n await this._runChatRecoveryFiber(requestId, false, chatBody);\n } else {\n await chatBody();\n }\n });\n });\n } finally {\n detachExternal();\n this._aborts.remove(requestId);\n }\n }\n\n // ── Message access ──────────────────────────────────────────────\n\n /** Get the conversation history as UIMessage[]. */\n async getMessages(): Promise<UIMessage[]> {\n return this.messages.slice();\n }\n\n /** Clear all messages from storage. */\n async clearMessages(): Promise<void> {\n this.resetTurnState();\n await this._clearHistory();\n this._broadcast({ type: MSG_CHAT_CLEAR });\n }\n\n private _ensureAgentToolChildRunTable(): void {\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_agent_tool_child_runs (\n run_id TEXT PRIMARY KEY,\n request_id TEXT,\n stream_id TEXT,\n status TEXT NOT NULL,\n summary TEXT,\n output_json TEXT,\n error_message TEXT,\n started_at INTEGER NOT NULL,\n completed_at INTEGER\n )\n `;\n\n this._addAgentToolChildRunColumnIfMissing(\n \"ALTER TABLE cf_agent_tool_child_runs ADD COLUMN output_json TEXT\"\n );\n }\n\n private _addAgentToolChildRunColumnIfMissing(sql: string): void {\n try {\n this.ctx.storage.sql.exec(sql);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (!message.toLowerCase().includes(\"duplicate column\")) {\n throw error;\n }\n }\n }\n\n private _readAgentToolChildRun(runId: string): AgentToolChildRunRow | null {\n this._ensureAgentToolChildRunTable();\n const rows = this.sql<AgentToolChildRunRow>`\n SELECT run_id, request_id, stream_id, status, summary, output_json,\n error_message, started_at, completed_at\n FROM cf_agent_tool_child_runs\n WHERE run_id = ${runId}\n LIMIT 1\n `;\n return rows[0] ?? null;\n }\n\n private _inspectionFromChildRow<Output>(\n row: AgentToolChildRunRow,\n output?: Output\n ): AgentToolRunInspection<Output> {\n const storedOutput =\n row.output_json === null\n ? output\n : (Think._parseAgentToolOutput(row.output_json) as Output);\n\n return {\n runId: row.run_id,\n status: row.status,\n requestId: row.request_id ?? undefined,\n streamId: row.stream_id ?? undefined,\n output: storedOutput,\n summary: row.summary ?? undefined,\n error: row.error_message ?? undefined,\n startedAt: row.started_at,\n completedAt: row.completed_at ?? undefined\n };\n }\n\n protected formatAgentToolInput(input: unknown): UIMessage {\n const text =\n typeof input === \"string\" ? input : JSON.stringify(input, null, 2);\n return {\n id: crypto.randomUUID(),\n role: \"user\",\n parts: [{ type: \"text\", text }]\n };\n }\n\n protected getAgentToolOutput(_runId: string): unknown {\n return undefined;\n }\n\n protected getAgentToolSummary(runId: string, output: unknown): string {\n const text = this._getAgentToolFinalText(runId);\n if (text) return text;\n if (typeof output === \"string\") return output;\n if (output !== undefined) {\n try {\n return JSON.stringify(output);\n } catch {\n return String(output);\n }\n }\n return \"\";\n }\n\n async startAgentToolRun(\n input: unknown,\n options: { runId: string }\n ): Promise<AgentToolRunInspection> {\n const existing = this._readAgentToolChildRun(options.runId);\n if (existing) return this._inspectionFromChildRow(existing);\n\n const startedAt = Date.now();\n this.sql`\n INSERT INTO cf_agent_tool_child_runs (run_id, status, started_at)\n VALUES (${options.runId}, 'starting', ${startedAt})\n `;\n\n const controller = new AbortController();\n this._agentToolAbortControllers.set(options.runId, controller);\n this._agentToolLiveSequences.set(options.runId, 0);\n this._agentToolPreTurnAssistantIds.set(\n options.runId,\n new Set(\n this.messages.filter((m) => m.role === \"assistant\").map((m) => m.id)\n )\n );\n\n const epoch = this._turnQueue.generation;\n void this.keepAliveWhile(async () => {\n try {\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET status = 'running'\n WHERE run_id = ${options.runId} AND status = 'starting'\n `;\n // 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 }\n );\n const streamId =\n this._resumableStream\n .getAllStreamMetadata()\n .find((m) => m.request_id === result.requestId)?.id ?? null;\n const output = this.getAgentToolOutput(options.runId);\n const summary = this.getAgentToolSummary(options.runId, output);\n const streamError =\n result.error ?? this._agentToolLastErrors.get(options.runId);\n const skipped =\n result.status === \"skipped\" ||\n (result.status === \"aborted\" && this._turnQueue.generation !== epoch);\n const status: AgentToolChildRunStatus =\n result.status === \"error\" || skipped || streamError\n ? \"error\"\n : result.status === \"aborted\"\n ? \"aborted\"\n : \"completed\";\n const error: string | null =\n status === \"error\"\n ? (streamError ??\n \"Agent tool run was skipped before the child could finish.\")\n : null;\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET request_id = ${result.requestId},\n stream_id = ${streamId},\n status = ${status},\n summary = ${summary},\n output_json = ${Think._stringifyAgentToolOutput(output)},\n error_message = ${error},\n completed_at = ${Date.now()}\n WHERE run_id = ${options.runId}\n AND completed_at IS NULL\n `;\n } catch (error) {\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET status = 'error',\n error_message = ${error instanceof Error ? error.message : String(error)},\n completed_at = ${Date.now()}\n WHERE run_id = ${options.runId}\n AND completed_at IS NULL\n `;\n } finally {\n this._agentToolAbortControllers.delete(options.runId);\n this._agentToolForwarders.delete(options.runId);\n this._agentToolLiveSequences.delete(options.runId);\n // Drop 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 async _classifyAgentToolChildRecovery(): Promise<\n \"in-progress\" | \"failed\" | \"none\"\n > {\n const entries = await this.ctx.storage.list<ChatRecoveryIncident>({\n prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX\n });\n let failed = false;\n for (const incident of entries.values()) {\n if (\n incident.status === \"detected\" ||\n incident.status === \"scheduled\" ||\n incident.status === \"attempting\"\n ) {\n return \"in-progress\";\n }\n if (incident.status === \"exhausted\" || incident.status === \"failed\") {\n failed = true;\n }\n }\n return failed ? \"failed\" : \"none\";\n }\n\n async inspectAgentToolRun(\n runId: string\n ): Promise<AgentToolRunInspection | null> {\n let row = this._readAgentToolChildRun(runId);\n if (!row) return null;\n // A `running`/`starting` row with no live abort controller means the\n // original in-isolate run is gone (e.g. the parent was evicted while this\n // child run was in flight, #1630) — lazily reconcile it from the child's\n // own durable recovery before reporting.\n if (this._isStaleAgentToolChildRun(row)) {\n await this._reconcileStaleAgentToolChildRun(runId);\n row = this._readAgentToolChildRun(runId) ?? row;\n }\n return this._inspectionFromChildRow(row, this.getAgentToolOutput(runId));\n }\n\n private _isStaleAgentToolChildRun(row: AgentToolChildRunRow): boolean {\n return (\n (row.status === \"running\" || row.status === \"starting\") &&\n row.completed_at === null &&\n !this._agentToolAbortControllers.has(row.run_id)\n );\n }\n\n /**\n * Reconcile a stale (post-eviction) child run row from the child's own\n * durable recovery (#1630). The child facet self-heals its interrupted turn\n * via `chatRecovery`, but that path never writes the run row, so without this\n * the row strands `running` and the parent can only collect `interrupted`.\n *\n * Persisting the terminal here (rather than only computing it) is intentional:\n * it's a lazy materialization of the run's true terminal that also lets a\n * tailing parent's stream close promptly and makes subsequent inspects cheap.\n * While recovery is still resolving (active stream or in-progress incident)\n * the row is left `running` so the parent's bounded re-attach keeps waiting.\n */\n private async _reconcileStaleAgentToolChildRun(runId: string): Promise<void> {\n const recovery = await this._classifyAgentToolChildRecovery();\n if (recovery === \"in-progress\" || this._resumableStream.hasActiveStream()) {\n return;\n }\n // A settled recovery that produced an assistant turn is `completed`, even if\n // that turn ended on a tool result with no final text — keying off text\n // alone would mis-seal a legitimately-finished (but text-less) run as\n // `error`. `getAgentToolSummary` already falls back to \"\" when there is no\n // final text.\n const recoveredTurn =\n recovery !== \"failed\" && this._hasRecoveredAgentToolAssistantTurn(runId);\n if (recoveredTurn) {\n const output = this.getAgentToolOutput(runId);\n const summary = this.getAgentToolSummary(runId, output);\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET status = 'completed',\n summary = ${summary},\n output_json = ${Think._stringifyAgentToolOutput(output)},\n error_message = null,\n completed_at = ${Date.now()}\n WHERE run_id = ${runId} AND completed_at IS NULL\n `;\n } else {\n const error =\n \"Agent tool run was interrupted before the child could finish.\";\n this.sql`\n UPDATE cf_agent_tool_child_runs\n SET status = 'error',\n error_message = ${error},\n completed_at = ${Date.now()}\n WHERE run_id = ${runId} AND completed_at IS NULL\n `;\n }\n this._finalizeAgentToolChildRunTailers(runId);\n }\n\n /** Release a re-attached run's live tail + per-run streaming bookkeeping. */\n private _finalizeAgentToolChildRunTailers(runId: string): void {\n for (const close of this._agentToolClosers.get(runId) ?? []) {\n close();\n }\n this._agentToolClosers.delete(runId);\n this._agentToolForwarders.delete(runId);\n this._agentToolLiveSequences.delete(runId);\n this._agentToolLastErrors.delete(runId);\n this._agentToolPreTurnAssistantIds.delete(runId);\n }\n\n /**\n * Eagerly terminalize this child facet's OWN agent-tool run row(s) once a\n * recovered turn has settled. A recovered turn re-runs via either\n * `_chatRecoveryContinue` → `continueLastTurn` or, for a pre-stream eviction,\n * `_chatRecoveryRetry` (a fresh user turn) — neither flows through\n * `startAgentToolRun`'s finalizer, so without this the run row strands\n * `running` and its tailers stay open until a parent inspect lazily\n * reconciles it — forcing a re-attached parent to wait out a full no-progress\n * window before collecting an already-finished result (#1630 follow-up).\n * Reconciling here closes the tail promptly so the parent collects the\n * terminal immediately. No-op on non-child facets (their\n * `cf_agent_tool_child_runs` table is empty) and on rows whose in-memory run\n * is still live (those are finalized by `startAgentToolRun`); the underlying\n * reconcile leaves a row `running` while its recovery is still in progress.\n */\n private async _reconcileOwnStaleAgentToolChildRuns(): Promise<void> {\n let rows: Array<{ run_id: string }>;\n try {\n rows = this.sql<{ run_id: string }>`\n SELECT run_id FROM cf_agent_tool_child_runs\n WHERE completed_at IS NULL\n `;\n } catch {\n // No child-run table on this facet (it never ran as a child) — nothing\n // to reconcile.\n return;\n }\n for (const { run_id } of rows) {\n if (this._agentToolAbortControllers.has(run_id)) continue;\n try {\n await this._reconcileStaleAgentToolChildRun(run_id);\n } catch {\n // Best-effort: a parent inspect still reconciles lazily.\n }\n }\n }\n\n async getAgentToolChunks(\n runId: string,\n options?: { afterSequence?: number }\n ): Promise<AgentToolStoredChunk[]> {\n const row = this._readAgentToolChildRun(runId);\n if (!row?.stream_id) return [];\n this._resumableStream.flushBuffer();\n return this._resumableStream\n .getStreamChunks(row.stream_id)\n .filter((chunk) => chunk.chunk_index > (options?.afterSequence ?? -1))\n .map((chunk) => ({ sequence: chunk.chunk_index, body: chunk.body }));\n }\n\n async tailAgentToolRun(\n runId: string,\n options?: { afterSequence?: number; signal?: AbortSignal }\n ): Promise<ReadableStream<AgentToolStoredChunk>> {\n const self = this;\n const signal = options?.signal;\n let closed = false;\n let forward: ((chunk: AgentToolStoredChunk) => void) | undefined;\n const detach = () => {\n if (forward) {\n self._agentToolForwarders.get(runId)?.delete(forward);\n forward = undefined;\n }\n };\n const stream = new ReadableStream<Uint8Array>({\n async start(controller) {\n const close = () => {\n if (closed) return;\n closed = true;\n detach();\n try {\n controller.close();\n } catch {\n // Already closed.\n }\n };\n // Honor an external abort (e.g. a bounded re-attach budget) so a parent\n // tailing a still-running child can stop waiting without cancelling the\n // child itself — closing the stream unblocks the parent's forwarder.\n if (signal?.aborted) {\n close();\n return;\n }\n signal?.addEventListener(\"abort\", close, { once: true });\n\n const replayed = await self.getAgentToolChunks(runId, options);\n for (const chunk of replayed) {\n if (closed) return;\n controller.enqueue(\n agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\\n`)\n );\n }\n const lastReplay = replayed[replayed.length - 1]?.sequence;\n if (lastReplay !== undefined) {\n self._agentToolLiveSequences.set(runId, lastReplay + 1);\n }\n const row = self._readAgentToolChildRun(runId);\n if (!row || row.completed_at !== null) {\n close();\n return;\n }\n forward = (chunk: AgentToolStoredChunk) => {\n if (closed || chunk.sequence <= (options?.afterSequence ?? -1)) {\n return;\n }\n try {\n controller.enqueue(\n agentToolChunkEncoder.encode(`${JSON.stringify(chunk)}\\n`)\n );\n } catch {\n // The consumer detached (e.g. a parent's re-attach budget expired\n // and cancelled the reader) between the RPC cancel arriving and our\n // `cancel`/`close` running. Drop the chunk instead of surfacing a\n // \"Stream was cancelled\" rejection; the child run is unaffected.\n closed = true;\n detach();\n }\n };\n const forwarders = self._agentToolForwarders.get(runId) ?? new Set();\n forwarders.add(forward);\n self._agentToolForwarders.set(runId, forwarders);\n const closers = self._agentToolClosers.get(runId) ?? new Set();\n closers.add(close);\n self._agentToolClosers.set(runId, closers);\n },\n cancel() {\n // A consumer detaching from the tail (e.g. a parent's bounded re-attach\n // budget expiring, via reader.cancel()) is read-only — it must NOT\n // cancel the child run. Explicit cancellation flows through\n // cancelAgentToolRun. Mirrors @cloudflare/ai-chat's read-only tail.\n closed = true;\n detach();\n }\n });\n return stream as unknown as ReadableStream<AgentToolStoredChunk>;\n }\n\n private static _stringifyAgentToolOutput(output: unknown): string | null {\n if (output === undefined) return null;\n try {\n return JSON.stringify(output);\n } catch {\n return JSON.stringify(String(output));\n }\n }\n\n private static _parseAgentToolOutput(value: string | null): unknown {\n if (value === null) return undefined;\n try {\n return JSON.parse(value);\n } catch {\n return undefined;\n }\n }\n\n /**\n * Whether the run produced an assistant turn (text or tool-only). Used by the\n * post-eviction reconcile to mark a settled run `completed` even when it ended\n * without final text. A dedicated child facet starts with no assistant\n * messages, so a missing in-memory pre-turn snapshot is treated as empty.\n */\n private _hasRecoveredAgentToolAssistantTurn(runId: string): boolean {\n const before =\n this._agentToolPreTurnAssistantIds.get(runId) ?? new Set<string>();\n return this.messages.some(\n (msg) => msg.role === \"assistant\" && !before.has(msg.id)\n );\n }\n\n private _getAgentToolFinalText(runId: string): string | null {\n // A child facet is dedicated to a single agent-tool run, so any assistant\n // message it holds is that run's output. When the pre-turn snapshot is\n // missing — e.g. reconciling after a real eviction, where the in-memory\n // snapshot died with the original isolate (#1630) — treat it as empty so\n // the recovered transcript's assistant text is still surfaced as the\n // summary instead of being lost.\n const before =\n this._agentToolPreTurnAssistantIds.get(runId) ?? new Set<string>();\n for (const msg of this.messages) {\n if (msg.role !== \"assistant\" || before.has(msg.id)) continue;\n const text = msg.parts\n .map((part) => (part.type === \"text\" ? part.text : \"\"))\n .filter((part) => part.length > 0)\n .join(\"\\n\");\n if (text.length > 0) return text;\n }\n return null;\n }\n\n // ── Declarative scheduled tasks ─────────────────────────────────\n\n private _ensureDeclaredScheduledTasksTable(): void {\n if (this._declaredScheduledTasksTableEnsured) return;\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_think_scheduled_tasks (\n owner_key TEXT NOT NULL,\n task_id TEXT NOT NULL,\n schedule_hash TEXT NOT NULL,\n task_hash TEXT NOT NULL,\n schedule_id TEXT,\n next_run_at INTEGER,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n PRIMARY KEY (owner_key, task_id)\n )\n `;\n this._declaredScheduledTasksTableEnsured = true;\n }\n\n private _readDeclaredScheduledTaskRow(\n taskId: string\n ): DeclaredScheduledTaskRow | null {\n this._ensureDeclaredScheduledTasksTable();\n const ownerKey = this._declaredScheduleOwnerKey();\n const rows = this.sql<DeclaredScheduledTaskRow>`\n SELECT owner_key, task_id, schedule_hash, task_hash, schedule_id,\n next_run_at, created_at, updated_at\n FROM cf_think_scheduled_tasks\n WHERE task_id = ${taskId}\n AND owner_key = ${ownerKey}\n LIMIT 1\n `;\n return rows[0] ?? null;\n }\n\n private _listDeclaredScheduledTaskRows(): DeclaredScheduledTaskRow[] {\n this._ensureDeclaredScheduledTasksTable();\n const ownerKey = this._declaredScheduleOwnerKey();\n return this.sql<DeclaredScheduledTaskRow>`\n SELECT owner_key, task_id, schedule_hash, task_hash, schedule_id,\n next_run_at, created_at, updated_at\n FROM cf_think_scheduled_tasks\n WHERE owner_key = ${ownerKey}\n ORDER BY task_id ASC\n `;\n }\n\n private _updateDeclaredScheduledTaskSchedule(\n task: NormalizedDeclaredTask,\n ownerKey: string,\n scheduled: { scheduleId: string; scheduledFor: number },\n updatedAt = Date.now()\n ): void {\n this.sql`\n UPDATE cf_think_scheduled_tasks\n SET schedule_hash = ${task.scheduleHash},\n task_hash = ${task.taskHash},\n schedule_id = ${scheduled.scheduleId},\n next_run_at = ${scheduled.scheduledFor},\n updated_at = ${updatedAt}\n WHERE owner_key = ${ownerKey}\n AND task_id = ${task.taskId}\n `;\n }\n\n private async _normalizeDeclaredScheduledTasks(\n tasks: ThinkScheduledTasks,\n defaultTimezone: string | undefined\n ): Promise<Map<string, NormalizedDeclaredTask>> {\n const normalized = new Map<string, NormalizedDeclaredTask>();\n for (const [taskId, task] of Object.entries(tasks)) {\n if (!/^[A-Za-z0-9_-]+$/.test(taskId)) {\n throw new Error(\n `Invalid scheduled task id \"${taskId}\"; use letters, numbers, \"_\" or \"-\"`\n );\n }\n const schedule = parseDeclaredTaskSchedule(\n task.schedule,\n task.timezone,\n defaultTimezone\n );\n const hasPrompt = \"prompt\" in task && task.prompt !== undefined;\n const hasHandler = \"handler\" in task && task.handler !== undefined;\n if (hasPrompt === hasHandler) {\n throw new Error(\n `Scheduled task \"${taskId}\" must define exactly one of prompt or handler`\n );\n }\n const scheduleHash = stableHash({\n schedule,\n retry: task.retry\n });\n const actionHash = hasPrompt\n ? {\n type: \"prompt\",\n value: typeof task.prompt === \"string\" ? task.prompt : \"<function>\"\n }\n : { type: \"handler\" };\n const taskHash = stableHash({\n scheduleHash,\n action: actionHash,\n metadata: task.metadata\n });\n normalized.set(taskId, {\n taskId,\n ...(hasPrompt ? { prompt: task.prompt } : {}),\n ...(hasHandler ? { handler: task.handler } : {}),\n schedule,\n retry: task.retry,\n metadata: task.metadata,\n scheduleHash,\n taskHash\n });\n }\n return normalized;\n }\n\n private async _declaredScheduledTasksForNow(): Promise<\n Map<string, NormalizedDeclaredTask>\n > {\n const defaultTimezone = await this.getDefaultTimezone();\n const resolvedDefaultTimezone =\n defaultTimezone === undefined\n ? undefined\n : validateTimezone(defaultTimezone);\n return this._normalizeDeclaredScheduledTasks(\n await this.getScheduledTasks(),\n resolvedDefaultTimezone\n );\n }\n\n private _declaredScheduleOwnerKey(): string {\n return stableHash(this.selfPath);\n }\n\n private _declaredScheduleValidationError(\n rawSchedule: string,\n taskTimezone?: string,\n defaultTimezone?: string\n ): string | null {\n const resolvedDefaultTimezone =\n defaultTimezone === undefined\n ? undefined\n : validateTimezone(defaultTimezone);\n const result = tryParseDeclaredTaskSchedule(\n rawSchedule,\n taskTimezone,\n resolvedDefaultTimezone\n );\n return result.ok ? null : result.error;\n }\n\n private _nextDeclaredScheduleTimeForConfig(\n rawSchedule: string,\n now: Date,\n options: {\n taskTimezone?: string;\n defaultTimezone?: string;\n previousScheduledFor?: number;\n } = {}\n ): Date {\n const resolvedDefaultTimezone =\n options.defaultTimezone === undefined\n ? undefined\n : validateTimezone(options.defaultTimezone);\n return nextDeclaredScheduleTime(\n parseDeclaredTaskSchedule(\n rawSchedule,\n options.taskTimezone,\n resolvedDefaultTimezone\n ),\n now,\n options.previousScheduledFor\n );\n }\n\n private async _reconcileDeclaredScheduledTasks(): Promise<void> {\n const tasks = await this._declaredScheduledTasksForNow();\n this._ensureDeclaredScheduledTasksTable();\n const ownerKey = this._declaredScheduleOwnerKey();\n const now = Date.now();\n const existing = this._listDeclaredScheduledTaskRows();\n const seen = new Set<string>();\n\n for (const [taskId, task] of tasks) {\n seen.add(taskId);\n const row = existing.find((candidate) => candidate.task_id === taskId);\n if (!row) {\n this.sql`\n INSERT INTO cf_think_scheduled_tasks (\n owner_key, task_id, schedule_hash, task_hash, schedule_id,\n next_run_at, created_at, updated_at\n )\n VALUES (\n ${ownerKey}, ${taskId}, ${task.scheduleHash}, ${task.taskHash},\n NULL, NULL, ${now}, ${now}\n )\n `;\n const scheduled = await this._scheduleDeclaredTaskOccurrence(\n task,\n new Date(now)\n );\n this._updateDeclaredScheduledTaskSchedule(\n task,\n ownerKey,\n scheduled,\n now\n );\n continue;\n }\n\n if (row.schedule_hash !== task.scheduleHash) {\n if (row.schedule_id) await this.cancelSchedule(row.schedule_id);\n this.sql`\n UPDATE cf_think_scheduled_tasks\n SET schedule_hash = ${task.scheduleHash},\n task_hash = ${task.taskHash},\n schedule_id = NULL,\n next_run_at = NULL,\n updated_at = ${now}\n WHERE owner_key = ${ownerKey}\n AND task_id = ${taskId}\n `;\n const scheduled = await this._scheduleDeclaredTaskOccurrence(\n task,\n new Date(now)\n );\n this._updateDeclaredScheduledTaskSchedule(\n task,\n ownerKey,\n scheduled,\n now\n );\n continue;\n }\n\n if (!row.schedule_id) {\n const scheduled =\n row.next_run_at === null\n ? await this._scheduleDeclaredTaskOccurrence(task, new Date(now))\n : await this._scheduleDeclaredTaskOccurrenceAt(\n task,\n row.next_run_at\n );\n this._updateDeclaredScheduledTaskSchedule(\n task,\n ownerKey,\n scheduled,\n now\n );\n continue;\n }\n\n if (row.schedule_id) {\n const schedule = await this.getScheduleById(row.schedule_id);\n if (!schedule) {\n const scheduled =\n row.next_run_at === null\n ? await this._scheduleDeclaredTaskOccurrence(task, new Date(now))\n : await this._scheduleDeclaredTaskOccurrenceAt(\n task,\n row.next_run_at\n );\n this._updateDeclaredScheduledTaskSchedule(\n task,\n ownerKey,\n scheduled,\n now\n );\n continue;\n }\n }\n\n if (row.task_hash !== task.taskHash) {\n this.sql`\n UPDATE cf_think_scheduled_tasks\n SET task_hash = ${task.taskHash}, updated_at = ${now}\n WHERE owner_key = ${ownerKey}\n AND task_id = ${taskId}\n `;\n }\n }\n\n for (const row of existing) {\n if (seen.has(row.task_id)) continue;\n if (row.schedule_id) await this.cancelSchedule(row.schedule_id);\n this.sql`\n DELETE FROM cf_think_scheduled_tasks\n WHERE owner_key = ${ownerKey}\n AND task_id = ${row.task_id}\n `;\n }\n }\n\n private async _scheduleDeclaredTaskOccurrence(\n task: NormalizedDeclaredTask,\n now: Date,\n previousScheduledFor?: number\n ): Promise<{ scheduleId: string; scheduledFor: number }> {\n const next = nextDeclaredScheduleTime(\n task.schedule,\n now,\n previousScheduledFor\n );\n return this._scheduleDeclaredTaskOccurrenceAt(task, next.getTime());\n }\n\n private async _scheduleDeclaredTaskOccurrenceAt(\n task: NormalizedDeclaredTask,\n scheduledFor: number\n ): Promise<{ scheduleId: string; scheduledFor: number }> {\n const schedule = await this.schedule<DeclaredScheduledTaskPayload>(\n new Date(scheduledFor),\n \"_runDeclaredScheduledTask\",\n {\n taskId: task.taskId,\n scheduleHash: task.scheduleHash,\n scheduledFor\n },\n { idempotent: true }\n );\n return { scheduleId: schedule.id, scheduledFor };\n }\n\n private async _advanceDeclaredScheduledTask(\n task: NormalizedDeclaredTask,\n payload: DeclaredScheduledTaskPayload,\n ownerKey: string\n ): Promise<void> {\n const scheduled = await this._scheduleDeclaredTaskOccurrence(\n task,\n new Date(),\n payload.scheduledFor\n );\n this._updateDeclaredScheduledTaskSchedule(task, ownerKey, scheduled);\n }\n\n private _declaredScheduledTaskContext(\n task: NormalizedDeclaredTask,\n payload: DeclaredScheduledTaskPayload,\n ownerKey: string\n ): ThinkScheduledTaskContext {\n const occurrenceKey = `${payload.taskId}:${payload.scheduledFor}`;\n return {\n taskId: payload.taskId,\n scheduledFor: payload.scheduledFor,\n scheduledForDate: new Date(payload.scheduledFor),\n occurrenceKey,\n idempotencyKey: `think-schedule:${ownerKey}:${occurrenceKey}`,\n schedule: task.schedule.normalizedSchedule,\n scheduleKind: task.schedule.kind,\n ...(task.schedule.kind === \"wall-clock\" && {\n timezone: task.schedule.timezone\n }),\n ...(task.metadata !== undefined && { metadata: task.metadata })\n };\n }\n\n async _runDeclaredScheduledTask(\n payload: DeclaredScheduledTaskPayload\n ): Promise<void> {\n if (\n !payload ||\n typeof payload.taskId !== \"string\" ||\n typeof payload.scheduleHash !== \"string\" ||\n typeof payload.scheduledFor !== \"number\"\n ) {\n throw new Error(\"Invalid declared scheduled task payload\");\n }\n\n const row = this._readDeclaredScheduledTaskRow(payload.taskId);\n if (!row || row.schedule_hash !== payload.scheduleHash) return;\n if (row.next_run_at !== null && row.next_run_at > payload.scheduledFor) {\n return;\n }\n\n const tasks = await this._declaredScheduledTasksForNow();\n const task = tasks.get(payload.taskId);\n if (!task || task.scheduleHash !== payload.scheduleHash) return;\n\n const ownerKey = this._declaredScheduleOwnerKey();\n const context = this._declaredScheduledTaskContext(task, payload, ownerKey);\n\n let actionError: unknown;\n try {\n await this.retry(async () => {\n if (task.prompt !== undefined) {\n const prompt =\n typeof task.prompt === \"function\"\n ? await task.prompt()\n : task.prompt;\n await this.submitMessages(\n [\n {\n id: crypto.randomUUID(),\n role: \"user\",\n parts: [{ type: \"text\", text: prompt }]\n }\n ],\n {\n idempotencyKey: context.idempotencyKey,\n metadata: {\n ...task.metadata,\n source: \"scheduled-task\",\n ownerKey,\n taskId: payload.taskId,\n scheduledFor: payload.scheduledFor,\n schedule: task.schedule.normalizedSchedule\n }\n }\n );\n } else {\n await task.handler?.(context);\n }\n }, task.retry);\n } catch (error) {\n actionError = error;\n } finally {\n await this._advanceDeclaredScheduledTask(task, payload, ownerKey);\n }\n\n if (actionError !== undefined) {\n console.error(\n `[Think] Scheduled task \"${payload.taskId}\" failed; next occurrence was still scheduled`,\n actionError\n );\n try {\n await this.onError(actionError);\n } catch {\n // Preserve recurrence even if user error handling fails.\n }\n }\n }\n\n // ── Durable programmatic submissions ───────────────────────────\n\n private _ensureSubmissionTable(): void {\n if (this._submissionTableEnsured) return;\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_think_submissions (\n submission_id TEXT PRIMARY KEY,\n idempotency_key TEXT UNIQUE,\n request_id TEXT,\n stream_id TEXT,\n status TEXT NOT NULL,\n messages_json TEXT NOT NULL,\n metadata_json TEXT,\n error_message TEXT,\n created_at INTEGER NOT NULL,\n messages_applied_at INTEGER,\n started_at INTEGER,\n completed_at INTEGER\n )\n `;\n this.sql`\n CREATE INDEX IF NOT EXISTS cf_think_submissions_status_created_idx\n ON cf_think_submissions (status, created_at, submission_id)\n `;\n this.sql`\n CREATE INDEX IF NOT EXISTS cf_think_submissions_request_status_idx\n ON cf_think_submissions (request_id, status)\n `;\n this.sql`\n CREATE INDEX IF NOT EXISTS cf_think_submissions_status_completed_idx\n ON cf_think_submissions (status, completed_at, created_at)\n `;\n this._submissionTableEnsured = true;\n }\n\n private _ensureWorkflowNotificationTable(): void {\n if (this._workflowNotificationTableEnsured) return;\n this.sql`\n CREATE TABLE IF NOT EXISTS cf_think_workflow_notifications (\n notification_id TEXT PRIMARY KEY,\n submission_id TEXT NOT NULL,\n workflow_name TEXT NOT NULL,\n workflow_id TEXT NOT NULL,\n event_type TEXT NOT NULL,\n payload_json TEXT NOT NULL,\n attempts INTEGER NOT NULL DEFAULT 0,\n last_error TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n delivered_at INTEGER\n )\n `;\n try {\n this.ctx.storage.sql.exec(\n \"ALTER TABLE cf_think_workflow_notifications ADD COLUMN delivered_at INTEGER\"\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (!message.toLowerCase().includes(\"duplicate column\")) {\n throw error;\n }\n }\n this.sql`\n CREATE INDEX IF NOT EXISTS cf_think_workflow_notifications_created_idx\n ON cf_think_workflow_notifications (delivered_at, created_at, notification_id)\n `;\n this._workflowNotificationTableEnsured = true;\n }\n\n private _readSubmission(submissionId: string): ThinkSubmissionRow | null {\n this._ensureSubmissionTable();\n const rows = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE submission_id = ${submissionId}\n LIMIT 1\n `;\n return rows[0] ?? null;\n }\n\n private _readSubmissionByIdempotencyKey(\n idempotencyKey: string\n ): ThinkSubmissionRow | null {\n this._ensureSubmissionTable();\n const rows = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE idempotency_key = ${idempotencyKey}\n LIMIT 1\n `;\n return rows[0] ?? null;\n }\n\n private _normalizeStatusFilter(\n status?: ThinkSubmissionStatus | ThinkSubmissionStatus[]\n ): Set<ThinkSubmissionStatus> | null {\n if (!status) return null;\n return new Set(Array.isArray(status) ? status : [status]);\n }\n\n private _listSubmissionRows(\n options?: ListSubmissionsOptions\n ): ThinkSubmissionRow[] {\n this._ensureSubmissionTable();\n const limit = Math.min(Math.max(options?.limit ?? 50, 1), 100);\n const statuses = this._normalizeStatusFilter(options?.status);\n if (statuses) {\n return [...statuses]\n .flatMap((status) => this._listSubmissionRowsByStatus(status, limit))\n .sort((a, b) =>\n b.created_at === a.created_at\n ? b.submission_id.localeCompare(a.submission_id)\n : b.created_at - a.created_at\n )\n .slice(0, limit);\n }\n\n const rows = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n ORDER BY created_at DESC, submission_id DESC\n LIMIT ${limit}\n `;\n return rows;\n }\n\n private _listSubmissionRowsByStatus(\n status: ThinkSubmissionStatus,\n limit: number\n ): ThinkSubmissionRow[] {\n return this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE status = ${status}\n ORDER BY created_at DESC, submission_id DESC\n LIMIT ${limit}\n `;\n }\n\n private _inspectionFromSubmissionRow(\n row: ThinkSubmissionRow\n ): ThinkSubmissionInspection {\n const metadata = this._parseJsonObject(row.metadata_json);\n return {\n submissionId: row.submission_id,\n idempotencyKey: row.idempotency_key ?? undefined,\n requestId: row.request_id ?? undefined,\n status: row.status,\n error: row.error_message ?? undefined,\n metadata: metadata ?? undefined,\n createdAt: row.created_at,\n startedAt: row.started_at ?? undefined,\n completedAt: row.completed_at ?? undefined\n };\n }\n\n private _parseJsonObject(\n value: string | null\n ): Record<string, unknown> | null {\n if (value === null) return null;\n try {\n const parsed = JSON.parse(value) as unknown;\n if (\n parsed !== null &&\n typeof parsed === \"object\" &&\n !Array.isArray(parsed)\n ) {\n return parsed as Record<string, unknown>;\n }\n } catch {\n // Invalid metadata should not prevent inspection.\n }\n return null;\n }\n\n private _parseSubmissionMessages(value: string): UIMessage[] {\n const parsed = JSON.parse(value) as unknown;\n if (!Array.isArray(parsed)) {\n throw new Error(\"Stored submission messages are invalid\");\n }\n return parsed as UIMessage[];\n }\n\n private _serializeSubmissionMessages(messages: UIMessage[]): string {\n return JSON.stringify(\n messages.map((message) => enforceRowSizeLimit(sanitizeMessage(message)))\n );\n }\n\n private _serializeMetadata(\n metadata: Record<string, unknown> | undefined\n ): string | null {\n return metadata === undefined ? null : JSON.stringify(metadata);\n }\n\n private _readWorkflowPromptContext(\n metadata: Record<string, unknown> | null\n ): ThinkWorkflowPromptContext | null {\n const workflowPromptValue = metadata?.[THINK_WORKFLOW_PROMPT_METADATA_KEY];\n if (\n workflowPromptValue === null ||\n typeof workflowPromptValue !== \"object\" ||\n Array.isArray(workflowPromptValue)\n ) {\n return null;\n }\n const workflowPrompt = workflowPromptValue as Record<string, unknown>;\n const workflowValue = workflowPrompt.workflow;\n if (\n workflowValue === null ||\n typeof workflowValue !== \"object\" ||\n Array.isArray(workflowValue)\n ) {\n return null;\n }\n const workflowRecord = workflowValue as Record<string, unknown>;\n if (\n typeof workflowRecord.name !== \"string\" ||\n typeof workflowRecord.id !== \"string\" ||\n typeof workflowRecord.stepName !== \"string\" ||\n typeof workflowRecord.eventType !== \"string\"\n ) {\n return null;\n }\n const output = workflowPrompt.output;\n const outputRecord =\n output !== null && typeof output === \"object\" && !Array.isArray(output)\n ? (output as Record<string, unknown>)\n : null;\n return {\n workflow: {\n name: workflowRecord.name,\n id: workflowRecord.id,\n stepName: workflowRecord.stepName,\n eventType: workflowRecord.eventType\n },\n ...(outputRecord\n ? {\n output: {\n schema: outputRecord.schema\n }\n }\n : {}),\n ...(typeof workflowPrompt.fingerprint === \"string\" && {\n fingerprint: workflowPrompt.fingerprint\n })\n };\n }\n\n private async _emitSubmissionStatus(\n row: ThinkSubmissionRow,\n output?: unknown\n ): Promise<void> {\n const inspection = this._inspectionFromSubmissionRow(row);\n this._emit(\"submission:status\", {\n submissionId: inspection.submissionId,\n requestId: inspection.requestId,\n status: inspection.status\n });\n if (inspection.status === \"error\" && inspection.error) {\n this._emit(\"submission:error\", {\n submissionId: inspection.submissionId,\n requestId: inspection.requestId,\n error: inspection.error\n });\n }\n if (this._isTerminalSubmissionStatus(inspection.status)) {\n await this._enqueueWorkflowNotification(inspection, output);\n }\n await this.keepAliveWhile(async () => {\n try {\n await this.onSubmissionStatus(inspection);\n } catch (error) {\n console.error(\"[Think] onSubmissionStatus failed\", error);\n }\n });\n }\n\n protected onSubmissionStatus(\n _submission: ThinkSubmissionInspection\n ): void | Promise<void> {}\n\n private async _enqueueWorkflowNotification(\n submission: ThinkSubmissionInspection,\n output?: unknown\n ): Promise<void> {\n this._insertWorkflowNotification(submission, output);\n this._startWorkflowNotificationDrain();\n }\n\n private _insertWorkflowNotification(\n submission: ThinkSubmissionInspection,\n output?: unknown,\n override?: { status: ThinkSubmissionStatus; error: string }\n ): boolean {\n const workflowPrompt = this._readWorkflowPromptContext(\n submission.metadata ?? null\n );\n if (!workflowPrompt) return false;\n\n this._ensureWorkflowNotificationTable();\n const now = Date.now();\n const status = override?.status ?? submission.status;\n const error = override?.error ?? submission.error;\n const payload = {\n submissionId: submission.submissionId,\n status,\n ...(status === \"completed\" && { output }),\n ...(error && { error })\n };\n this.sql`\n INSERT OR IGNORE INTO cf_think_workflow_notifications (\n notification_id, submission_id, workflow_name, workflow_id, event_type,\n payload_json, attempts, last_error, created_at, updated_at, delivered_at\n )\n VALUES (\n ${`${submission.submissionId}:${workflowPrompt.workflow.eventType}`},\n ${submission.submissionId},\n ${workflowPrompt.workflow.name},\n ${workflowPrompt.workflow.id},\n ${workflowPrompt.workflow.eventType},\n ${JSON.stringify(payload)},\n 0,\n NULL,\n ${now},\n ${now},\n NULL\n )\n `;\n return true;\n }\n\n private _recoverWorkflowNotifications(): void {\n this._ensureSubmissionTable();\n this._ensureWorkflowNotificationTable();\n const terminalRows = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE status IN ('aborted', 'skipped', 'error')\n ORDER BY completed_at DESC, created_at DESC\n LIMIT 100\n `;\n\n let recovered = false;\n for (const row of terminalRows) {\n const inspection = this._inspectionFromSubmissionRow(row);\n const workflowPrompt = this._readWorkflowPromptContext(\n inspection.metadata ?? null\n );\n if (!workflowPrompt) continue;\n const notificationId = `${inspection.submissionId}:${workflowPrompt.workflow.eventType}`;\n const existing = this.sql<{ notification_id: string }>`\n SELECT notification_id\n FROM cf_think_workflow_notifications\n WHERE notification_id = ${notificationId}\n LIMIT 1\n `;\n if (existing[0]) continue;\n\n recovered = this._insertWorkflowNotification(inspection) || recovered;\n }\n if (recovered) this._startWorkflowNotificationDrain();\n }\n\n private _startWorkflowNotificationDrain(): void {\n if (!this._hasPendingWorkflowNotifications()) return;\n void this.keepAliveWhile(() => this._drainWorkflowNotifications()).catch(\n (error) => {\n console.error(\"[Think] Failed to drain workflow notifications\", error);\n void this._scheduleWorkflowNotificationAlarm();\n }\n );\n }\n\n private _hasPendingWorkflowNotifications(): boolean {\n this._ensureWorkflowNotificationTable();\n const pending = this.sql<{ notification_id: string }>`\n SELECT notification_id\n FROM cf_think_workflow_notifications\n WHERE delivered_at IS NULL\n LIMIT 1\n `;\n return pending.length > 0;\n }\n\n private async _drainWorkflowNotifications(): Promise<void> {\n if (this._drainingWorkflowNotifications) return;\n this._ensureWorkflowNotificationTable();\n this._drainingWorkflowNotifications = true;\n try {\n const rows = this.sql<ThinkWorkflowNotificationRow>`\n SELECT notification_id, submission_id, workflow_name, workflow_id,\n event_type, payload_json, attempts, last_error, created_at,\n updated_at, delivered_at\n FROM cf_think_workflow_notifications\n WHERE delivered_at IS NULL\n ORDER BY created_at ASC, notification_id ASC\n LIMIT 25\n `;\n for (const row of rows) {\n try {\n const payload = JSON.parse(row.payload_json) as unknown;\n await this.sendWorkflowEvent(\n row.workflow_name as string & {},\n row.workflow_id,\n {\n type: row.event_type,\n payload\n }\n );\n this.sql`\n UPDATE cf_think_workflow_notifications\n SET payload_json = '{}',\n last_error = NULL,\n updated_at = ${Date.now()},\n delivered_at = ${Date.now()}\n WHERE notification_id = ${row.notification_id}\n AND delivered_at IS NULL\n `;\n } catch (error) {\n this.sql`\n UPDATE cf_think_workflow_notifications\n SET attempts = attempts + 1,\n last_error = ${error instanceof Error ? error.message : String(error)},\n updated_at = ${Date.now()}\n WHERE notification_id = ${row.notification_id}\n `;\n }\n }\n } finally {\n this._drainingWorkflowNotifications = false;\n }\n await this._scheduleWorkflowNotificationAlarm();\n }\n\n private async _scheduleWorkflowNotificationAlarm(): Promise<void> {\n this._ensureWorkflowNotificationTable();\n const pending = this.sql<{ attempts: number }>`\n SELECT attempts\n FROM cf_think_workflow_notifications\n WHERE delivered_at IS NULL\n ORDER BY created_at ASC, notification_id ASC\n LIMIT 1\n `;\n if (!pending[0]) return;\n const delayMs = Math.min(\n 5 * 60 * 1000,\n 1000 * 2 ** Math.min(pending[0].attempts, 8)\n );\n const nextAlarm = Date.now() + delayMs;\n const existingAlarm = await this.ctx.storage.getAlarm();\n if (existingAlarm === null || existingAlarm > nextAlarm) {\n await this.ctx.storage.setAlarm(nextAlarm);\n }\n }\n\n async inspectSubmission(\n submissionId: string\n ): Promise<ThinkSubmissionInspection | null> {\n const row = this._readSubmission(submissionId);\n return row ? this._inspectionFromSubmissionRow(row) : null;\n }\n\n async listSubmissions(\n options?: ListSubmissionsOptions\n ): Promise<ThinkSubmissionInspection[]> {\n return this._listSubmissionRows(options).map((row) =>\n this._inspectionFromSubmissionRow(row)\n );\n }\n\n async deleteSubmission(submissionId: string): Promise<boolean> {\n const row = this._readSubmission(submissionId);\n if (!row || !this._isTerminalSubmissionStatus(row.status)) return false;\n this.sql`\n DELETE FROM cf_think_submissions\n WHERE submission_id = ${submissionId}\n AND status IN ('completed', 'aborted', 'skipped', 'error')\n `;\n return true;\n }\n\n async deleteSubmissions(options?: DeleteSubmissionsOptions): Promise<number> {\n this._ensureSubmissionTable();\n const statuses =\n this._normalizeStatusFilter(options?.status) ??\n new Set<ThinkSubmissionStatus>([\n \"completed\",\n \"aborted\",\n \"skipped\",\n \"error\"\n ]);\n const limit = Math.min(Math.max(options?.limit ?? 100, 1), 500);\n const completedBefore = options?.completedBefore?.getTime();\n const rows = [...statuses]\n .flatMap((status) =>\n this._listTerminalSubmissionRowsForDelete(\n status,\n limit,\n completedBefore\n )\n )\n .sort((a, b) =>\n (a.completed_at ?? a.created_at) === (b.completed_at ?? b.created_at)\n ? a.created_at - b.created_at\n : (a.completed_at ?? a.created_at) - (b.completed_at ?? b.created_at)\n )\n .slice(0, limit);\n\n const idsToDelete = rows\n .filter((row) => this._isTerminalSubmissionStatus(row.status))\n .map((row) => row.submission_id);\n\n // Batch deletes into `IN (...)` queries within the SQLite 100\n // bound-parameter limit to minimize round-trips during cleanup.\n let deleted = 0;\n for (let i = 0; i < idsToDelete.length; i += MAX_BOUND_PARAMS) {\n const batch = idsToDelete.slice(i, i + MAX_BOUND_PARAMS);\n const strings = buildInClauseStrings(\n \"DELETE FROM cf_think_submissions WHERE status IN ('completed', 'aborted', 'skipped', 'error') AND submission_id IN \",\n batch.length\n );\n this.sql(strings, ...batch);\n deleted += batch.length;\n }\n return deleted;\n }\n\n private _listTerminalSubmissionRowsForDelete(\n status: ThinkSubmissionStatus,\n limit: number,\n completedBefore: number | undefined\n ): ThinkSubmissionRow[] {\n if (completedBefore === undefined) {\n return this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE status = ${status}\n ORDER BY completed_at ASC, created_at ASC\n LIMIT ${limit}\n `;\n }\n\n return this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE status = ${status}\n AND completed_at IS NOT NULL\n AND completed_at < ${completedBefore}\n ORDER BY completed_at ASC, created_at ASC\n LIMIT ${limit}\n `;\n }\n\n private _isTerminalSubmissionStatus(status: ThinkSubmissionStatus): boolean {\n return (\n status === \"completed\" ||\n status === \"aborted\" ||\n status === \"skipped\" ||\n status === \"error\"\n );\n }\n\n async cancelSubmission(\n submissionId: string,\n reason?: unknown\n ): Promise<void> {\n const row = this._readSubmission(submissionId);\n if (!row || this._isTerminalSubmissionStatus(row.status)) return;\n\n const completedAt = Date.now();\n const errorMessage =\n reason === undefined\n ? null\n : reason instanceof Error\n ? reason.message\n : String(reason);\n this._submissionAbortControllers.get(submissionId)?.abort(reason);\n if (row.request_id) {\n this.abortRequest(row.request_id, reason);\n }\n\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'aborted',\n error_message = ${errorMessage},\n completed_at = ${completedAt}\n WHERE submission_id = ${submissionId}\n AND status IN ('pending', 'running')\n `;\n\n const updated = this._readSubmission(submissionId);\n if (updated?.status === \"aborted\") {\n await this._emitSubmissionStatus(updated);\n }\n }\n\n async submitMessages(\n messages: UIMessage[],\n options?: SubmitMessagesOptions\n ): Promise<SubmitMessagesResult> {\n this._ensureSubmissionTable();\n if (messages.length === 0) {\n throw new Error(\"submitMessages requires at least one message\");\n }\n\n const existingById = options?.submissionId\n ? this._readSubmission(options.submissionId)\n : null;\n const existingByKey = options?.idempotencyKey\n ? this._readSubmissionByIdempotencyKey(options.idempotencyKey)\n : null;\n\n if (\n existingById &&\n existingByKey &&\n existingById.submission_id !== existingByKey.submission_id\n ) {\n throw new Error(\n \"submissionId and idempotencyKey refer to different submissions\"\n );\n }\n if (\n existingByKey &&\n options?.submissionId &&\n existingByKey.submission_id !== options.submissionId\n ) {\n throw new Error(\n \"submissionId and idempotencyKey refer to different submissions\"\n );\n }\n if (\n existingById &&\n options?.idempotencyKey &&\n existingById.idempotency_key !== null &&\n existingById.idempotency_key !== options.idempotencyKey\n ) {\n throw new Error(\n \"submissionId and idempotencyKey refer to different submissions\"\n );\n }\n\n const existing = existingById ?? existingByKey;\n if (existing) {\n if (existing.status === \"pending\") {\n await this._scheduleSubmissionDrain();\n this._startSubmissionDrain();\n }\n return {\n ...this._inspectionFromSubmissionRow(existing),\n accepted: false\n };\n }\n\n const submissionId = options?.submissionId ?? crypto.randomUUID();\n const requestId = submissionId;\n const now = Date.now();\n const messagesJson = this._serializeSubmissionMessages(messages);\n const metadataJson = this._serializeMetadata(options?.metadata);\n\n this.sql`\n INSERT INTO cf_think_submissions (\n submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n )\n VALUES (\n ${submissionId}, ${options?.idempotencyKey ?? null}, ${requestId},\n NULL, 'pending', ${messagesJson}, ${metadataJson}, NULL, ${now},\n NULL, NULL, NULL\n )\n `;\n\n const row = this._readSubmission(submissionId);\n if (!row) {\n throw new Error(\"Failed to persist submission\");\n }\n\n this._emit(\"submission:create\", {\n submissionId: row.submission_id,\n requestId: row.request_id ?? undefined,\n idempotencyKey: row.idempotency_key ?? undefined\n });\n await this._emitSubmissionStatus(row);\n await this._scheduleSubmissionDrain();\n this._startSubmissionDrain();\n\n return {\n ...this._inspectionFromSubmissionRow(row),\n accepted: true\n };\n }\n\n private async _scheduleSubmissionDrain(): Promise<void> {\n await this.schedule(0, \"_drainThinkSubmissions\", undefined, {\n idempotent: true\n });\n }\n\n private _startSubmissionDrain(): void {\n void this.keepAliveWhile(() => this._drainSubmissions()).catch((error) => {\n console.error(\"[Think] Failed to drain submissions\", error);\n });\n }\n\n private _hasPendingSubmissions(): boolean {\n this._ensureSubmissionTable();\n const pending = this.sql<{ submission_id: string }>`\n SELECT submission_id\n FROM cf_think_submissions\n WHERE status = 'pending'\n LIMIT 1\n `;\n return pending.length > 0;\n }\n\n async _drainThinkSubmissions(): Promise<void> {\n await this._drainSubmissions();\n }\n\n private async _drainSubmissions(): Promise<void> {\n this._ensureSubmissionTable();\n if (this._drainingSubmissions) return;\n this._drainingSubmissions = true;\n try {\n while (true) {\n const rows = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE status = 'pending'\n ORDER BY created_at ASC, submission_id ASC\n LIMIT 1\n `;\n const row = rows[0];\n if (!row) break;\n await this._runSubmission(row);\n }\n } finally {\n this._drainingSubmissions = false;\n }\n }\n\n private async _runSubmission(row: ThinkSubmissionRow): Promise<void> {\n const requestId = row.request_id ?? row.submission_id;\n const startedAt = Date.now();\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'running',\n request_id = ${requestId},\n started_at = ${startedAt}\n WHERE submission_id = ${row.submission_id}\n AND status = 'pending'\n `;\n\n const claimed = this._readSubmission(row.submission_id);\n if (!claimed || claimed.status !== \"running\") return;\n await this._emitSubmissionStatus(claimed);\n\n const controller = new AbortController();\n this._submissionAbortControllers.set(row.submission_id, controller);\n let output: unknown;\n try {\n const messages = this._parseSubmissionMessages(row.messages_json);\n const metadata = this._parseJsonObject(row.metadata_json);\n const workflowPrompt = this._readWorkflowPromptContext(metadata);\n const result = await this._runProgrammaticMessagesTurn(\n requestId,\n messages,\n {\n signal: controller.signal,\n captureProgrammaticStreamError: true,\n captureOutput: Boolean(workflowPrompt?.output),\n workflowPrompt: workflowPrompt ?? undefined,\n shouldApplyMessages: () =>\n this._readSubmission(row.submission_id)?.status === \"running\",\n onMessagesApplied: () => {\n this.sql`\n UPDATE cf_think_submissions\n SET messages_applied_at = ${Date.now()}\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n AND messages_applied_at IS NULL\n `;\n }\n }\n );\n output = result.output;\n const streamId =\n this._resumableStream\n .getAllStreamMetadata()\n .find((metadata) => metadata.request_id === result.requestId)?.id ??\n null;\n const streamError = this._programmaticStreamErrors.get(result.requestId);\n const finalStatus = this._getSubmissionFinalStatus(\n result.status,\n result.error ?? streamError\n );\n const errorMessage = result.error ?? streamError ?? null;\n const completedAt = Date.now();\n this.ctx.storage.transactionSync(() => {\n this.sql`\n UPDATE cf_think_submissions\n SET status = ${finalStatus},\n request_id = ${result.requestId},\n stream_id = ${streamId},\n error_message = ${finalStatus === \"error\" ? errorMessage : null},\n completed_at = ${completedAt}\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n `;\n const finalized = this._readSubmission(row.submission_id);\n if (finalized && this._isTerminalSubmissionStatus(finalized.status)) {\n this._insertWorkflowNotification(\n this._inspectionFromSubmissionRow(finalized),\n output\n );\n }\n });\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n const completedAt = Date.now();\n this.ctx.storage.transactionSync(() => {\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'error',\n error_message = ${errorMessage},\n completed_at = ${completedAt}\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n `;\n const finalized = this._readSubmission(row.submission_id);\n if (finalized && this._isTerminalSubmissionStatus(finalized.status)) {\n this._insertWorkflowNotification(\n this._inspectionFromSubmissionRow(finalized)\n );\n }\n });\n } finally {\n this._programmaticStreamErrors.delete(requestId);\n this._submissionAbortControllers.delete(row.submission_id);\n const updated = this._readSubmission(row.submission_id);\n if (updated && this._isTerminalSubmissionStatus(updated.status)) {\n await this._emitSubmissionStatus(updated, output);\n }\n }\n }\n\n private _getSubmissionFinalStatus(\n resultStatus: SaveMessagesResult[\"status\"],\n streamError: string | undefined\n ): ThinkSubmissionStatus {\n return resultStatus === \"completed\" && streamError ? \"error\" : resultStatus;\n }\n\n private _markPendingSubmissionsSkipped(): ThinkSubmissionRow[] {\n this._ensureSubmissionTable();\n const pending = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE status = 'pending'\n `;\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'skipped',\n error_message = 'Submission was skipped by turn reset.',\n completed_at = ${Date.now()}\n WHERE status = 'pending'\n `;\n return pending;\n }\n\n private async _emitSkippedSubmissions(\n skipped: ThinkSubmissionRow[]\n ): Promise<void> {\n for (const row of skipped) {\n const updated = this._readSubmission(row.submission_id);\n if (updated?.status === \"skipped\") {\n await this._emitSubmissionStatus(updated);\n }\n }\n }\n\n private async _recoverSubmissionsOnStart(): Promise<void> {\n this._ensureSubmissionTable();\n\n const running = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE status = 'running'\n `;\n\n for (const row of running) {\n if (row.messages_applied_at === null) {\n let appliedState: \"none\" | \"partial\" | \"all\";\n try {\n appliedState = await this._getSubmissionMessagesAppliedState(row);\n } catch (error) {\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'error',\n error_message = ${error instanceof Error ? error.message : String(error)},\n completed_at = ${Date.now()}\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n `;\n const updated = this._readSubmission(row.submission_id);\n if (updated?.status === \"error\") {\n await this._emitSubmissionStatus(updated);\n }\n continue;\n }\n if (appliedState !== \"none\") {\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'error',\n error_message = ${appliedState === \"all\" ? \"Submission was interrupted after messages were applied.\" : \"Submission was interrupted after messages were partially applied.\"},\n completed_at = ${Date.now()}\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n `;\n const updated = this._readSubmission(row.submission_id);\n if (updated?.status === \"error\") {\n await this._emitSubmissionStatus(updated);\n }\n continue;\n }\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'pending',\n started_at = NULL\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n `;\n const updated = this._readSubmission(row.submission_id);\n if (updated?.status === \"pending\") {\n await this._emitSubmissionStatus(updated);\n }\n continue;\n }\n\n if (\n row.request_id &&\n ((this._hasRecoverableChatTurn(row.request_id) &&\n this._hasFreshRecoverableSubmissionEvidence(row)) ||\n this._hasScheduledRecoveredContinuation(row.request_id))\n ) {\n continue;\n }\n\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'error',\n error_message = 'Submission was interrupted after messages were applied.',\n completed_at = ${Date.now()}\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n `;\n const updated = this._readSubmission(row.submission_id);\n if (updated?.status === \"error\") {\n await this._emitSubmissionStatus(updated);\n }\n }\n }\n\n private async _getSubmissionMessagesAppliedState(\n row: ThinkSubmissionRow\n ): Promise<\"none\" | \"partial\" | \"all\"> {\n const messages = this._parseSubmissionMessages(row.messages_json);\n if (messages.length === 0) return \"all\";\n\n let applied = 0;\n for (const message of messages) {\n if (await this.session.getMessage(message.id)) applied++;\n }\n\n if (applied === 0) return \"none\";\n return applied === messages.length ? \"all\" : \"partial\";\n }\n\n private _hasRecoverableChatTurn(requestId: string): boolean {\n const fiberRows = this.sql<{ id: string }>`\n SELECT id FROM cf_agents_runs\n WHERE name = ${(this.constructor as typeof Think).CHAT_FIBER_NAME + \":\" + requestId}\n LIMIT 1\n `;\n if (fiberRows.length > 0) return true;\n\n const streamRows = this.sql<{ id: string }>`\n SELECT id FROM cf_ai_chat_stream_metadata\n WHERE request_id = ${requestId}\n AND status = 'streaming'\n LIMIT 1\n `;\n return streamRows.length > 0;\n }\n\n private _hasFreshRecoverableSubmissionEvidence(row: ThinkSubmissionRow) {\n if (!row.request_id) return false;\n const cutoff =\n Date.now() - (this.constructor as typeof Think).submissionRecoveryStaleMs;\n\n const fiberRows = this.sql<{ created_at: number }>`\n SELECT created_at FROM cf_agents_runs\n WHERE name = ${(this.constructor as typeof Think).CHAT_FIBER_NAME + \":\" + row.request_id}\n LIMIT 1\n `;\n if (fiberRows[0] && fiberRows[0].created_at >= cutoff) return true;\n\n const streamRows = this.sql<{ created_at: number }>`\n SELECT created_at FROM cf_ai_chat_stream_metadata\n WHERE request_id = ${row.request_id}\n AND status = 'streaming'\n ORDER BY created_at DESC\n LIMIT 1\n `;\n return streamRows[0] ? streamRows[0].created_at >= cutoff : false;\n }\n\n private _hasScheduledRecoveredContinuation(requestId: string): boolean {\n const rows = this.sql<{ payload: string | null }>`\n SELECT payload FROM cf_agents_schedules\n WHERE callback = '_chatRecoveryContinue'\n `;\n return rows.some((row) => {\n if (!row.payload) return false;\n try {\n const payload = JSON.parse(row.payload) as unknown;\n return (\n payload !== null &&\n typeof payload === \"object\" &&\n \"recoveredRequestId\" in payload &&\n (payload as { recoveredRequestId?: unknown }).recoveredRequestId ===\n requestId\n );\n } catch {\n return false;\n }\n });\n }\n\n // ── Programmatic API ───────────────────────────────────────────\n\n /**\n * Inject messages and trigger a model turn — without a WebSocket request.\n *\n * Use for scheduled responses, webhook-triggered turns, proactive agents,\n * or chaining from `onChatResponse`.\n *\n * Accepts static messages or a callback that derives messages from the\n * current state (useful when multiple calls queue up — the callback runs\n * with the latest messages when the turn actually starts).\n *\n * Pass `options.signal` to cancel the turn from outside without knowing\n * the internally-generated request id. The signal is linked to the\n * registry's controller for this turn — when it aborts, the inference\n * loop's signal aborts and the result reports `status: \"aborted\"`.\n * Pre-aborted signals short-circuit before any model work runs. See\n * {@link SaveMessagesOptions} for the integration point.\n *\n * @example Scheduled follow-up\n * ```typescript\n * async onScheduled() {\n * await this.saveMessages([{\n * id: crypto.randomUUID(),\n * role: \"user\",\n * parts: [{ type: \"text\", text: \"Time for your daily summary.\" }]\n * }]);\n * }\n * ```\n *\n * @example Function form\n * ```typescript\n * await this.saveMessages((current) => [\n * ...current,\n * { id: crypto.randomUUID(), role: \"user\", parts: [{ type: \"text\", text: \"Continue.\" }] }\n * ]);\n * ```\n *\n * @example External cancellation (helper-as-sub-agent)\n * ```typescript\n * // Inside a parent agent's tool execute — forward the AI SDK's\n * // abortSignal so a parent stop / tab close cancels the helper.\n * await helper.saveMessages([userMsg], { signal: abortSignal });\n * ```\n */\n async saveMessages(\n messages:\n | UIMessage[]\n | ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>),\n options?: SaveMessagesOptions\n ): Promise<SaveMessagesResult> {\n const requestId = crypto.randomUUID();\n return this._runProgrammaticMessagesTurn(requestId, messages, options);\n }\n\n /**\n * Add messages to history WITHOUT starting a model turn.\n *\n * Distinct from {@link Think.saveMessages} (which runs a turn) and from\n * AIChatAgent's `persistMessages()` (which replaces/reconciles a flat array):\n * `addMessages` appends or upserts into the Session tree and never enqueues a\n * turn. Because it bypasses the turn queue, it never deadlocks — including\n * when called from inside a tool `execute` during an active turn.\n *\n * Array entries are appended **linearly**: the first attaches under the\n * resolved parent (the latest committed leaf by default, or `parentId`), and\n * each subsequent message attaches under the previous one, so imported history\n * stays a single path rather than a fan-out of siblings. Appends are\n * idempotent by message id; pass `{ mode: \"upsert\" }` to update an existing\n * message in place instead (upsert never re-parents). Any role may be written;\n * an `assistant` message added this way is inert transcript data (it does not\n * mark a completed turn or trigger auto-continuation).\n *\n * The live message cache stays coherent automatically (the Session keeps it\n * in sync on every write, branches included). Broadcast behaviour depends on\n * whether a turn is running:\n *\n * - **Out of a turn** (the supported pattern — \"add context, then run a\n * turn\"): the new messages are broadcast to connected clients immediately\n * (unless `broadcast: false`).\n * - **Inside a turn** (e.g. from a tool `execute`): no broadcast is sent, so a\n * full snapshot can't clobber the in-progress streamed message; the injected\n * messages ride along on the turn's next broadcast. The write is still\n * durable and visible to the running turn's next sync.\n */\n async addMessages(\n messages:\n | UIMessage[]\n | ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>),\n options?: AddMessagesOptions\n ): Promise<void> {\n const resolved =\n typeof messages === \"function\" ? await messages(this.messages) : messages;\n if (resolved.length === 0) return;\n\n const mode = options?.mode ?? \"append\";\n\n // Validate an explicit parentId up front. The Session provider silently\n // falls back to the root for an unknown parent; fail fast instead so a\n // typo'd id surfaces as an error rather than a misattached message.\n if (typeof options?.parentId === \"string\") {\n const parent = await this.session.getMessage(options.parentId);\n if (!parent) {\n throw new Error(\n `addMessages: parentId \"${options.parentId}\" does not exist in this session`\n );\n }\n }\n\n let parentId = options?.parentId;\n for (const message of resolved) {\n const existing = await this.session.getMessage(message.id);\n if (existing) {\n // Append mode is idempotent by id (existing id → no-op); upsert updates\n // the content in place. Neither path re-parents an existing message.\n if (mode === \"upsert\") await this._updateMessageInHistory(message);\n parentId = message.id;\n } else {\n const stored = await this._appendMessageToHistory(message, parentId);\n parentId = stored.id;\n }\n }\n\n // The live cache is kept coherent automatically by the Session change\n // listener wired in `onStart` (`internal_onMessagesChanged`), which handles\n // both linear appends and branches (an explicit `parentId` triggers a full\n // resync). So `addMessages` only owns the broadcast — and suppresses it\n // mid-turn: pushing a full `MSG_CHAT_MESSAGES` snapshot while a turn streams\n // would clobber the in-progress assistant message on connected clients (the\n // same reason the streaming path defers its snapshot). The injected messages\n // ride along on the turn's next broadcast.\n if (this._insideInferenceLoop) return;\n if (options?.broadcast !== false) {\n this._broadcastMessages();\n }\n }\n\n private async _runProgrammaticMessagesTurn(\n requestId: string,\n messages:\n | UIMessage[]\n | ((currentMessages: UIMessage[]) => UIMessage[] | Promise<UIMessage[]>),\n options?: SaveMessagesOptions & {\n onMessagesApplied?: () => void;\n captureProgrammaticStreamError?: boolean;\n captureOutput?: boolean;\n body?: Record<string, unknown>;\n workflowPrompt?: ThinkWorkflowPromptContext;\n shouldApplyMessages?: () => boolean | Promise<boolean>;\n }\n ): Promise<ProgrammaticMessagesResult> {\n const clientTools = this._lastClientTools;\n const body = options?.body ?? this._lastBody;\n const epoch = this._turnQueue.generation;\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n let error: string | undefined;\n let output: unknown;\n let wasAborted = false;\n\n await this.keepAliveWhile(async () => {\n await this._turnQueue.enqueue(requestId, async () => {\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n if (\n options?.shouldApplyMessages &&\n !(await options.shouldApplyMessages())\n ) {\n status = \"aborted\";\n return;\n }\n\n const resolved =\n typeof messages === \"function\"\n ? await messages(this.messages)\n : messages;\n\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n if (\n options?.shouldApplyMessages &&\n !(await options.shouldApplyMessages())\n ) {\n status = \"aborted\";\n return;\n }\n\n for (const msg of resolved) {\n await this._appendMessageToHistory(msg);\n }\n options?.onMessagesApplied?.();\n this._broadcastMessages();\n\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n const abortSignal = this._aborts.getSignal(requestId);\n // Wire the optional external signal to the registry's controller\n // for this request. Detacher MUST run in `finally` to avoid\n // leaking listeners on a long-lived parent signal that drives\n // many helper turns.\n const detachExternal = this._aborts.linkExternal(\n requestId,\n options?.signal\n );\n try {\n const programmaticBody = async () => {\n // Bounded compact-and-retry loop (opt-in via\n // `contextOverflow.reactive`), mirroring the WebSocket and chat()\n // paths so programmatic turns (saveMessages / submitMessages /\n // scheduled prompts) recover from a mid-turn overflow too. Each\n // attempt re-runs the same turn (`continuation: false`).\n for (let attempt = 0; ; attempt++) {\n const result = await agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n clientTools,\n body,\n workflowPrompt: options?.workflowPrompt,\n continuation: false\n })\n );\n\n if (!result) return;\n\n let overflowError: string | undefined;\n let overflowRequested = false;\n const overflowRecovery = this._overflowReactiveEnabled\n ? {\n onRetry: (err?: string) => {\n overflowRequested = true;\n overflowError = err;\n }\n }\n : undefined;\n\n const streamResult = await this._streamResult(\n requestId,\n result,\n abortSignal,\n {\n captureProgrammaticStreamError:\n options?.captureProgrammaticStreamError,\n captureOutput: options?.captureOutput,\n overflowRecovery\n }\n );\n\n if (overflowRequested) {\n if (\n attempt < this._overflowMaxRetries &&\n !abortSignal?.aborted\n ) {\n const shortened = await this._compactForContextOverflow(\n \"reactive\",\n { requestId, attempt: attempt + 1 }\n );\n if (shortened) continue;\n }\n // Budget spent, aborted, or compaction no-op: surface terminally\n // through onChatError (classified). The caller reads status/error.\n error = this._finalizeContextOverflowError(\n requestId,\n overflowError\n );\n status = \"error\";\n return;\n }\n\n status = streamResult.status;\n error = streamResult.error;\n output = streamResult.output;\n return;\n }\n };\n\n if (this.chatRecovery) {\n await this._runChatRecoveryFiber(\n requestId,\n false,\n programmaticBody\n );\n } else {\n await programmaticBody();\n }\n } finally {\n if (abortSignal?.aborted) wasAborted = true;\n detachExternal();\n this._aborts.remove(requestId);\n }\n });\n });\n\n if (\n this._turnQueue.generation !== epoch &&\n shouldMarkSkippedAfterGenerationChange(status)\n ) {\n status = \"skipped\";\n } else if (wasAborted && status === \"completed\") {\n status = \"aborted\";\n }\n\n return {\n requestId,\n status,\n ...(error !== undefined && { error }),\n ...(output !== undefined && { output })\n };\n }\n\n /**\n * Run a new LLM call following the last assistant message.\n *\n * The model sees the full conversation (including the last assistant\n * response) and generates a new response. The new response is persisted\n * as a separate assistant message. Building block for chat recovery\n * (Phase 4), \"generate more\" buttons, and self-correction.\n *\n * Note: this creates a new message, not an append to the existing one.\n * True continuation-as-append (chunk rewriting) is planned for Phase 4.\n *\n * Returns early with `status: \"skipped\"` if there is no assistant message\n * to continue from.\n *\n * Pass `options.signal` to cancel the continuation from outside —\n * matches the {@link saveMessages} contract.\n */\n protected async continueLastTurn(\n body?: Record<string, unknown>,\n options?: SaveMessagesOptions\n ): Promise<SaveMessagesResult> {\n const lastLeaf = await this.session.getLatestLeaf();\n if (!lastLeaf || lastLeaf.role !== \"assistant\") {\n return { requestId: \"\", status: \"skipped\" };\n }\n\n const requestId = crypto.randomUUID();\n const clientTools = this._lastClientTools;\n const resolvedBody = body ?? this._lastBody;\n const epoch = this._turnQueue.generation;\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n let error: string | undefined;\n let wasAborted = false;\n\n await this.keepAliveWhile(async () => {\n await this._turnQueue.enqueue(requestId, async () => {\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n const abortSignal = this._aborts.getSignal(requestId);\n const detachExternal = this._aborts.linkExternal(\n requestId,\n options?.signal\n );\n try {\n const continueTurnBody = async () => {\n const result = await agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n clientTools,\n body: resolvedBody,\n continuation: true\n })\n );\n\n if (result) {\n const streamResult = await this._streamResult(\n requestId,\n result,\n abortSignal,\n {\n continuation: true\n }\n );\n status = streamResult.status;\n error = streamResult.error;\n }\n };\n\n if (this.chatRecovery) {\n await this._runChatRecoveryFiber(requestId, true, continueTurnBody);\n } else {\n await continueTurnBody();\n }\n } finally {\n if (abortSignal?.aborted) wasAborted = true;\n detachExternal();\n this._aborts.remove(requestId);\n }\n });\n });\n\n if (\n this._turnQueue.generation !== epoch &&\n shouldMarkSkippedAfterGenerationChange(status)\n ) {\n status = \"skipped\";\n } else if (wasAborted && status === \"completed\") {\n status = \"aborted\";\n }\n\n return { requestId, status, ...(error !== undefined && { error }) };\n }\n\n private async _retryLastUserTurn(\n clientTools?: ClientToolSchema[],\n body?: Record<string, unknown>,\n options?: SaveMessagesOptions\n ): Promise<SaveMessagesResult> {\n const lastLeaf = await this.session.getLatestLeaf();\n if (!lastLeaf || lastLeaf.role !== \"user\") {\n return { requestId: \"\", status: \"skipped\" };\n }\n\n const requestId = crypto.randomUUID();\n const epoch = this._turnQueue.generation;\n let status: SaveMessagesResult[\"status\"] = \"completed\";\n let error: string | undefined;\n let wasAborted = false;\n\n await this.keepAliveWhile(async () => {\n await this._turnQueue.enqueue(requestId, async () => {\n if (this._turnQueue.generation !== epoch) {\n status = \"skipped\";\n return;\n }\n\n const abortSignal = this._aborts.getSignal(requestId);\n const detachExternal = this._aborts.linkExternal(\n requestId,\n options?.signal\n );\n try {\n const retryTurnBody = async () => {\n const result = await agentContext.run(\n {\n agent: this,\n connection: undefined,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n clientTools,\n body,\n continuation: false\n })\n );\n\n if (result) {\n const streamResult = await this._streamResult(\n requestId,\n result,\n abortSignal\n );\n status = streamResult.status;\n error = streamResult.error;\n }\n };\n\n if (this.chatRecovery) {\n await this._runChatRecoveryFiber(requestId, false, retryTurnBody);\n } else {\n await retryTurnBody();\n }\n } finally {\n if (abortSignal?.aborted) wasAborted = true;\n detachExternal();\n this._aborts.remove(requestId);\n }\n });\n });\n\n if (\n this._turnQueue.generation !== epoch &&\n shouldMarkSkippedAfterGenerationChange(status)\n ) {\n status = \"skipped\";\n } else if (wasAborted && status === \"completed\") {\n status = \"aborted\";\n }\n\n return { requestId, status, ...(error !== undefined && { error }) };\n }\n\n // ── WebSocket protocol ──────────────────────────────────────────\n\n private _setupProtocolHandlers() {\n const _onConnect = this.onConnect.bind(this);\n this.onConnect = async (\n connection: Connection,\n ctx: { request: Request }\n ) => {\n const requestTargetsSubAgent = this._cf_requestTargetsSubAgent(\n ctx.request\n );\n if (requestTargetsSubAgent) {\n return _onConnect(connection, ctx);\n }\n\n if (this._resumableStream.hasActiveStream()) {\n // A stream is still in flight. The resume flow is the\n // authoritative source of state: `_notifyStreamResuming` tells\n // the client to send `STREAM_RESUME_ACK`, after which the\n // server replays buffered chunks and delivers a final\n // `MSG_CHAT_MESSAGES` broadcast once the turn completes.\n //\n // Sending `MSG_CHAT_MESSAGES` here would clobber the in-progress\n // assistant the client rebuilds from the replayed chunks,\n // because `this.messages` at this point still only contains\n // the user message — the assistant message is not persisted\n // until the stream finishes.\n this._notifyStreamResuming(connection);\n } else {\n for (const message of await this._buildIdleConnectMessages()) {\n connection.send(JSON.stringify(message));\n }\n }\n return _onConnect(connection, ctx);\n };\n\n const _onClose = this.onClose.bind(this);\n this.onClose = async (\n connection: Connection,\n code: number,\n reason: string,\n wasClean: boolean\n ) => {\n this._pendingResumeConnections.delete(connection.id);\n this._continuation.releaseConnection(connection.id);\n return _onClose(connection, code, reason, wasClean);\n };\n\n const _onMessage = this.onMessage.bind(this);\n this.onMessage = async (connection: Connection, message: WSMessage) => {\n const connectionTargetsSubAgent =\n this._cf_connectionTargetsSubAgent(connection);\n if (connectionTargetsSubAgent) {\n return _onMessage(connection, message);\n }\n\n if (typeof message === \"string\") {\n const event = parseProtocolMessage(message);\n if (event) {\n await this._handleProtocolEvent(connection, event);\n return;\n }\n }\n return _onMessage(connection, message);\n };\n\n const _onRequest = this.onRequest.bind(this);\n this.onRequest = async (request: Request) => {\n const url = new URL(request.url);\n if (\n url.pathname === \"/get-messages\" ||\n url.pathname.endsWith(\"/get-messages\")\n ) {\n return Response.json(this.messages);\n }\n const messengerResponse =\n await this._messengerRuntime?.handleRequest(request);\n if (messengerResponse) {\n return messengerResponse;\n }\n return _onRequest(request);\n };\n }\n\n private async _handleProtocolEvent(\n connection: Connection,\n event: NonNullable<ReturnType<typeof parseProtocolMessage>>\n ): Promise<void> {\n switch (event.type) {\n case \"stream-resume-request\":\n await this._handleStreamResumeRequest(connection);\n break;\n\n case \"stream-resume-ack\":\n await this._handleStreamResumeAck(connection, event.id);\n break;\n\n case \"chat-request\":\n if (event.init?.method === \"POST\") {\n await this._handleChatRequest(connection, event);\n }\n break;\n\n case \"tool-result\": {\n if (\n event.clientTools &&\n Array.isArray(event.clientTools) &&\n event.clientTools.length > 0\n ) {\n this._lastClientTools = event.clientTools as ClientToolSchema[];\n this._persistClientTools();\n }\n this._enqueueInteractionApply(() =>\n this._applyToolResult(\n event.toolCallId,\n event.output,\n event.state as \"output-error\" | undefined,\n event.errorText\n )\n );\n if (event.autoContinue) {\n this._scheduleAutoContinuation(connection);\n } else {\n this._rearmPendingAutoContinuationForBatch();\n }\n break;\n }\n\n case \"tool-approval\": {\n this._enqueueInteractionApply(() =>\n this._applyToolApproval(event.toolCallId, event.approved)\n );\n if (event.autoContinue) {\n this._scheduleAutoContinuation(connection);\n } else {\n this._rearmPendingAutoContinuationForBatch();\n }\n break;\n }\n\n case \"clear\":\n await this._handleClear(connection);\n break;\n\n case \"cancel\":\n this._aborts.cancel(event.id);\n break;\n\n case \"messages\":\n break;\n }\n }\n\n private async _handleStreamResumeRequest(\n connection: Connection\n ): Promise<void> {\n if (this._resumableStream.hasActiveStream()) {\n if (\n this._continuation.activeRequestId ===\n this._resumableStream.activeRequestId &&\n this._continuation.activeConnectionId !== null &&\n this._continuation.activeConnectionId !== connection.id\n ) {\n sendIfOpen(\n connection,\n JSON.stringify({ type: MSG_STREAM_RESUME_NONE })\n );\n } else {\n this._notifyStreamResuming(connection);\n }\n } else if (\n this._continuation.pending !== null &&\n (this._continuation.pending.connectionId === null ||\n this._continuation.pending.connectionId === connection.id)\n ) {\n this._continuation.awaitingConnections.set(connection.id, connection);\n } else if (await this._replayTerminalOnResume(connection)) {\n // A turn terminalized while no client was connected (#1645): drive the\n // resume handshake so the terminal error frame can be delivered on the\n // resumed stream (the only path that surfaces on the client) once this\n // connection ACKs — see `_handleStreamResumeAck`.\n } else {\n sendIfOpen(connection, JSON.stringify({ type: MSG_STREAM_RESUME_NONE }));\n }\n }\n\n private async _handleStreamResumeAck(\n connection: Connection,\n requestId: string\n ): Promise<void> {\n this._pendingResumeConnections.delete(connection.id);\n if (\n this._resumableStream.hasActiveStream() &&\n this._resumableStream.activeRequestId === requestId\n ) {\n const orphanedStreamId = this._resumableStream.replayChunks(\n connection,\n this._resumableStream.activeRequestId\n );\n if (orphanedStreamId) {\n await this._persistOrphanedStream(orphanedStreamId);\n }\n } else if (this._resumableStream.hasActiveStream()) {\n // Ignore ACKs for a different active stream request id.\n } else if (await this._replayTerminalOnAck(connection, requestId)) {\n // Delivered the pending terminal error frame on the resumed stream the\n // client just ACKed (#1645).\n } else if (\n !this._resumableStream.replayCompletedChunksByRequestId(\n connection,\n requestId\n )\n ) {\n sendIfOpen(\n connection,\n JSON.stringify({\n body: \"\",\n done: true,\n id: requestId,\n type: MSG_CHAT_RESPONSE,\n replay: true\n })\n );\n }\n }\n\n private async _handleChatRequest(\n connection: Connection,\n event: Extract<\n NonNullable<ReturnType<typeof parseProtocolMessage>>,\n { type: \"chat-request\" }\n >\n ) {\n if (!event.init?.body) return;\n\n let rawParsed: Record<string, unknown>;\n try {\n rawParsed = JSON.parse(event.init.body) as Record<string, unknown>;\n } catch (error) {\n const wrapped = this.onChatError(error, {\n requestId: event.id,\n stage: \"parse\",\n messagesPersisted: false\n });\n this._emit(\"chat:request:failed\", {\n requestId: event.id,\n stage: \"parse\",\n messagesPersisted: false,\n error: wrapped instanceof Error ? wrapped.message : String(wrapped)\n });\n return;\n }\n\n const {\n messages: incomingMessages,\n clientTools: rawClientTools,\n trigger: rawTrigger,\n ...customBody\n } = rawParsed as {\n messages?: UIMessage[];\n clientTools?: ClientToolSchema[];\n trigger?: string;\n [key: string]: unknown;\n };\n if (!Array.isArray(incomingMessages)) return;\n\n const isRegeneration = rawTrigger === \"regenerate-message\";\n const isSubmitMessage = !isRegeneration;\n const requestId = event.id;\n let messagesPersisted = false;\n let failureStage: ChatErrorContext[\"stage\"] = \"persist\";\n\n // ── Concurrency decision (before persisting anything) ────────\n const concurrencyDecision =\n this._getSubmitConcurrencyDecision(isSubmitMessage);\n\n if (concurrencyDecision.action === \"drop\") {\n this._rollbackDroppedSubmit(connection);\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n\n // 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 this._clearChatTerminal();\n\n const releasePendingEnqueue = this._submitConcurrency.beginEnqueue();\n let pendingEnqueue = true;\n const epoch = this._turnQueue.generation;\n const releaseIfPending = () => {\n if (!pendingEnqueue) return;\n pendingEnqueue = false;\n releasePendingEnqueue();\n };\n\n try {\n // ── Persist client tools and body (only for accepted requests) ──\n const requestClientTools =\n rawClientTools && rawClientTools.length > 0\n ? rawClientTools\n : undefined;\n if (requestClientTools) {\n this._lastClientTools = requestClientTools;\n this._persistClientTools();\n } else if (rawClientTools !== undefined) {\n this._lastClientTools = undefined;\n this._persistClientTools();\n }\n\n const requestBody =\n Object.keys(customBody).length > 0 ? customBody : undefined;\n this._lastBody = requestBody;\n this._persistBody();\n\n // ── Reconcile, persist, and broadcast user messages ──────────\n //\n // The client may post an in-flight assistant snapshot it minted\n // optimistically (e.g. while a previous tool call is still\n // streaming). Reconcile against the server's current active path\n // so client IDs map onto server IDs and stale client states pick\n // up the server's tool outputs. Without this, Session's\n // INSERT-OR-IGNORE-by-ID would persist a duplicate orphan\n // assistant row alongside the real server-generated one.\n const clientToolsForTurn = this._lastClientTools;\n const bodyForTurn = this._lastBody;\n\n const serverMessages = await this._readMessagesFromStorage();\n const reconciled = reconcileMessages(\n incomingMessages,\n serverMessages,\n sanitizeMessage\n );\n\n let branchParentId: string | undefined;\n if (isRegeneration && reconciled.length > 0) {\n branchParentId = reconciled[reconciled.length - 1].id;\n }\n\n if (this._turnQueue.generation !== epoch) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n\n for (const msg of reconciled) {\n if (this._turnQueue.generation !== epoch) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n\n await this._persistIncomingMessage(msg, serverMessages);\n }\n\n if (this._turnQueue.generation !== epoch) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n\n await this._syncMessages();\n this._broadcastMessages([connection.id]);\n messagesPersisted = true;\n\n // ── Enter turn queue ────────────────────────────────────────\n failureStage = \"turn\";\n const abortSignal = this._aborts.getSignal(requestId);\n\n await this.keepAliveWhile(async () => {\n const turnPromise = this._turnQueue.enqueue(\n requestId,\n async () => {\n // Superseded by a later overlapping submit (latest/merge/debounce)\n if (\n this._submitConcurrency.isSuperseded(\n concurrencyDecision.submitSequence\n )\n ) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n\n // Debounce: wait for quiet period\n if (concurrencyDecision.debounceUntilMs !== null) {\n await this._submitConcurrency.waitForTimestamp(\n concurrencyDecision.debounceUntilMs\n );\n\n if (this._turnQueue.generation !== epoch) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n if (\n this._submitConcurrency.isSuperseded(\n concurrencyDecision.submitSequence\n )\n ) {\n this._completeSkippedRequest(connection, requestId);\n return;\n }\n }\n\n const chatTurnBody = async () => {\n // Bounded compact-and-retry loop (opt-in via\n // `contextOverflow.reactive`). A turn that overflows the\n // context window mid-flight is compacted and re-run from the\n // persisted partial instead of dying terminally. Each attempt\n // re-runs the same turn (`continuation: false`) — not an\n // auto-continuation.\n for (let attempt = 0; ; attempt++) {\n const result = await agentContext.run(\n {\n agent: this,\n connection,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n clientTools: clientToolsForTurn,\n body: bodyForTurn,\n continuation: false\n })\n );\n\n if (!result) {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"No response was generated.\",\n done: true\n });\n return;\n }\n\n // The consumer suppresses a classified overflow whenever\n // recovery is enabled; the driver (here) owns the\n // retry-vs-terminal call so every overflow terminal is reported\n // identically.\n let overflowError: string | undefined;\n let overflowRequested = false;\n const overflowRecovery = this._overflowReactiveEnabled\n ? {\n onRetry: (error?: string) => {\n overflowRequested = true;\n overflowError = error;\n }\n }\n : undefined;\n\n await this._streamResult(requestId, result, abortSignal, {\n parentId: branchParentId,\n overflowRecovery\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 // Compaction shortened history → retry. A no-op compaction\n // can't fix the overflow, so fall through to terminal.\n if (shortened) continue;\n }\n // Budget spent, aborted, or compaction no-op: deliver\n // terminally (through onChatError, classified) so the turn\n // never loops or ends silently with no answer.\n const message = this._finalizeContextOverflowError(\n requestId,\n overflowError\n );\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: message,\n done: true,\n error: true\n });\n }\n return;\n }\n };\n\n if (this.chatRecovery) {\n await this._runChatRecoveryFiber(requestId, false, chatTurnBody);\n } else {\n await chatTurnBody();\n }\n },\n {\n generation: epoch\n }\n );\n releaseIfPending();\n\n const turnResult = await turnPromise;\n\n if (turnResult.status === \"stale\") {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n });\n }\n });\n } catch (error) {\n const wrapped = this.onChatError(error, {\n requestId,\n stage: failureStage,\n messagesPersisted\n });\n const errorMessage =\n wrapped instanceof Error ? wrapped.message : String(wrapped);\n this._emit(\"chat:request:failed\", {\n requestId,\n stage: failureStage,\n messagesPersisted,\n error: errorMessage\n });\n // Persist the terminal error before broadcasting it: the broadcast is\n // transient, so a client disconnected at this moment (a pre-stream\n // failure like message reconciliation) would otherwise never learn the\n // turn failed and stay frozen on reconnect (see `_buildIdleConnectMessages`).\n await this._recordTerminalChatStatus(\"error\", requestId, errorMessage);\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: errorMessage,\n done: true,\n error: true\n });\n } finally {\n releaseIfPending();\n this._aborts.remove(requestId);\n }\n }\n\n /**\n * Abort the active turn, invalidate queued turns, and reset\n * concurrency/continuation state. Call this when intercepting\n * clear events or implementing custom reset logic.\n *\n * Does NOT clear messages, streams, or persisted state —\n * only turn execution state.\n */\n protected resetTurnState(): void {\n this._turnQueue.reset();\n this._aborts.destroyAll();\n for (const controller of this._submissionAbortControllers.values()) {\n controller.abort(new Error(\"Turn state reset\"));\n }\n this._submissionAbortControllers.clear();\n const skippedSubmissions = this._markPendingSubmissionsSkipped();\n void this.keepAliveWhile(() =>\n this._emitSkippedSubmissions(skippedSubmissions)\n ).catch((error) => {\n console.error(\"[Think] Failed to skip pending submissions\", error);\n });\n if (this._continuationTimer) {\n clearTimeout(this._continuationTimer);\n this._continuationTimer = null;\n }\n this._submitConcurrency.reset();\n this._pendingInteractionPromise = null;\n // Drop the apply chain so new interactions don't serialize behind a stale\n // (possibly hung) apply from the turn we just reset (#1649).\n this._interactionApplyTail = Promise.resolve();\n // The streaming turn (if any) is being torn down; stop exposing its\n // accumulator so a late tool result doesn't apply to an abandoned message.\n this._streamingAssistant = null;\n this._continuationBarrierActive = false;\n this._continuation.sendResumeNone();\n this._continuation.clearAll();\n }\n\n /**\n * Abort a single in-flight chat turn by request id.\n *\n * Equivalent to the cancel path that fires when a client sends a\n * `chat-request-cancel` WebSocket message — the inference loop's\n * signal aborts, partial chunks already streamed are still\n * persisted, and the turn's `ChatResponseResult` reports\n * `status: \"aborted\"`.\n *\n * No-op if no controller exists for `requestId` (the turn already\n * completed, was never started, or used a different id).\n *\n * `chat()` callers can read the request id from\n * {@link StreamCallback.onStart} and later pass it here from another\n * RPC call.\n *\n * Prefer {@link SaveMessagesOptions.signal} when driving a turn\n * programmatically — it threads the abort intent in from the start\n * without requiring the caller to know the id.\n */\n cancelChat(requestId: string, reason?: string): void {\n this._aborts.cancel(requestId, reason);\n }\n\n /** Abort every in-flight chat turn on this agent. */\n cancelAllChats(): void {\n this._aborts.destroyAll();\n }\n\n protected abortRequest(requestId: string, reason?: unknown): void {\n this._aborts.cancel(requestId, reason);\n }\n\n /**\n * Abort every in-flight chat turn on this agent.\n *\n * Aborts all controllers in the registry and clears it. Used by\n * subclasses that drive single-purpose turns (e.g. a sub-agent\n * helper that runs one turn at a time over RPC) and want a coarse\n * \"cancel whatever is running\" handle without tracking request ids.\n *\n * Does NOT reset queued turns, continuation timers, or submit\n * concurrency state — use {@link resetTurnState} for the full\n * teardown that runs on `chat-clear`.\n */\n protected abortAllRequests(): void {\n this._aborts.destroyAll();\n }\n\n private async _handleClear(connection?: Connection) {\n this.resetTurnState();\n\n this._resumableStream.clearAll();\n this._pendingResumeConnections.clear();\n this._lastClientTools = undefined;\n this._persistClientTools();\n this._lastBody = undefined;\n this._persistBody();\n await this._clearHistory();\n this._broadcast(\n { type: MSG_CHAT_CLEAR },\n connection ? [connection.id] : undefined\n );\n }\n\n /**\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 async _streamResultToRpcCallback(\n requestId: string,\n result: StreamableResult,\n callback: StreamCallback,\n abortSignal?: AbortSignal,\n options?: {\n /**\n * When set, an in-stream error the app classifies as `context_overflow`\n * is treated as recoverable: the partial is persisted, the stream is\n * finalized cleanly (no terminal error to the caller), and\n * `{ status: \"overflow_retry\" }` is returned so the driver can compact\n * and re-run. Pass only while the retry budget allows.\n */\n overflowRecovery?: boolean;\n }\n ): Promise<{\n status: \"completed\" | \"error\" | \"aborted\" | \"overflow_retry\";\n error?: string;\n }> {\n const streamId = this._startResumableStream(requestId);\n const accumulator = new StreamAccumulator({\n messageId: crypto.randomUUID()\n });\n // Expose the in-flight message so a client tool result arriving before the\n // end-of-stream persist lands on the accumulator instead of being dropped\n // (#1649). Cleared in the `finally` below.\n this._streamingAssistant = accumulator;\n\n let streamFinalized = false;\n let assistantMsg: UIMessage | null = null;\n let aborted = false;\n let doneSent = false;\n let streamError: string | undefined;\n let pendingRpcError: string | undefined;\n // When a stall-recovery early-return schedules a continuation, the\n // continuation re-runs the turn and its own stream finalize re-triggers the\n // held barrier. Re-arming here too would let the 50ms coalesce timer fire a\n // SECOND continuation alongside the scheduled recovery one — a spurious\n // double model invocation. Mirror the WebSocket `_streamResult` recovery\n // paths and clear `_streamingAssistant` WITHOUT re-arming in that case.\n let skipFinalizeRearm = false;\n // Set when an in-stream overflow error is recoverable (opt-in): suppresses\n // terminal delivery so the driver can compact and re-run the turn.\n let overflowRetry = false;\n\n const stallTimeoutMs =\n this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;\n try {\n this._insideInferenceLoop = true;\n const flushState = { chunksSinceFlush: 0, hasFlushedContent: false };\n try {\n const guardedStream = this._iterateWithStallWatchdog(\n result.toUIMessageStream(),\n stallTimeoutMs,\n () => {\n this._emit(\"chat:stream:stalled\", {\n requestId,\n timeoutMs: stallTimeoutMs\n });\n this.abortRequest(\n requestId,\n new Error(\"chat stream stalled: inactivity watchdog fired\")\n );\n }\n );\n for await (const chunk of guardedStream) {\n if (abortSignal?.aborted) {\n aborted = true;\n break;\n }\n\n // RPC callbacks receive serialized UIMessage chunks directly; unlike\n // the WebSocket protocol, there is no wrapper frame to rewrite for\n // accumulator actions such as `error`.\n const streamChunk = chunk as unknown as StreamChunkData;\n const { action } = accumulator.applyChunk(streamChunk);\n\n if (action?.type === \"error\") {\n streamError = action.error;\n // Recoverable context overflow (opt-in): don't terminalize. Persist\n // the partial after the loop, then signal the driver to compact and\n // re-run. No `message:error`/`chat:request:failed`/error frame here\n // — the turn isn't over.\n if (\n options?.overflowRecovery &&\n this._isRecoverableContextOverflow(streamError, requestId)\n ) {\n overflowRetry = true;\n break;\n }\n this._emit(\"message:error\", { error: streamError });\n // An AI-SDK error surfaces as a stream error part (not a thrown\n // exception), so it lands here rather than in the `catch` below.\n // Bridge it to `chat:request:failed` too — observers shouldn't have\n // to know whether the failure threw or arrived as a chunk (the\n // post-`beforeTurn`, in-stream provider 400 class), and turn-count\n // telemetry needs the failed signal to balance `turn.started`.\n this._emit(\"chat:request:failed\", {\n requestId,\n stage: \"stream\",\n messagesPersisted: true,\n error: streamError\n });\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: action.error,\n done: false,\n error: true\n });\n break;\n }\n\n this._alignStreamStartId(streamChunk, action, accumulator, false);\n\n const chunkBody = JSON.stringify(chunk);\n await this._storeChunkDurably(\n streamId,\n streamChunk,\n chunkBody,\n flushState\n );\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: chunkBody,\n done: false\n });\n await callback.onEvent(chunkBody);\n }\n } finally {\n this._insideInferenceLoop = false;\n }\n\n // Recoverable context overflow: discard the partial, close the stream\n // cleanly without a terminal error, and hand control back to the driver.\n // No `onDone`/`onError` and no response hook — the turn is not finished;\n // the retry owns the terminal outcome.\n //\n // The partial is intentionally NOT persisted: the driver re-runs the turn\n // from scratch (`continuation: false`) against the compacted history, so\n // the retry produces a fresh assistant message. Persisting the truncated\n // partial would leave an orphan beside the recovered answer — and any tool\n // work it captured would be re-issued by the retry, duplicating records.\n // The live-streamed chunks already reached clients; the driver's\n // post-retry `_broadcastMessages()` reconciles them to the real answer.\n if (overflowRetry) {\n this._completeResumableStream(streamId);\n streamFinalized = true;\n return { status: \"overflow_retry\", error: streamError };\n }\n\n if (streamError) {\n this._errorResumableStream(streamId);\n } else {\n this._completeResumableStream(streamId);\n }\n streamFinalized = true;\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n });\n doneSent = true;\n\n assistantMsg = accumulator.toMessage();\n if (accumulator.parts.length > 0) {\n await this._persistAssistantMessage(assistantMsg);\n this._broadcastMessages();\n }\n\n if (streamError) {\n await this._fireResponseHook({\n message: assistantMsg,\n requestId,\n continuation: false,\n status: \"error\",\n error: streamError\n });\n pendingRpcError = streamError;\n } else if (!aborted) {\n await callback.onDone();\n await this._fireResponseHook({\n message: assistantMsg,\n requestId,\n continuation: false,\n status: \"completed\"\n });\n } else {\n await this._fireResponseHook({\n message: assistantMsg,\n requestId,\n continuation: false,\n status: \"aborted\"\n });\n }\n } catch (error) {\n // #1626: a stream-stall watchdog abort is a recoverable interruption, not\n // a terminal error. Persist the settled partial (re-anchor), route into\n // bounded recovery, and suppress the terminal error when a continuation is\n // scheduled; fall through to terminal only once the budget is exhausted.\n if (error instanceof ChatStreamStalledError) {\n if (!assistantMsg && accumulator.parts.length > 0) {\n assistantMsg = accumulator.toMessage();\n await this._persistAssistantMessage(assistantMsg);\n this._broadcastMessages();\n }\n const outcome = await this._routeStallToBoundedRecovery({\n requestId,\n streamId,\n partialParts: (assistantMsg ?? accumulator.toMessage()).parts,\n targetAssistantId: assistantMsg?.id\n });\n if (outcome === \"scheduled\") {\n if (!streamFinalized) {\n this._completeResumableStream(streamId);\n streamFinalized = true;\n }\n if (!doneSent) {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n });\n doneSent = true;\n }\n // The scheduled continuation (a later isolate invocation, without this\n // callback) owns the real terminal outcome. Signal the interruption so\n // the caller doesn't read this clean resolve as success and finalize a\n // truncated partial (#1644); NOT onDone/onError — see `onInterrupted`.\n skipFinalizeRearm = true;\n await callback.onInterrupted?.();\n return { status: \"aborted\" };\n }\n if (outcome === \"exhausted\") {\n // `_routeStallToBoundedRecovery` already delivered the terminal UX\n // (configured `terminalMessage` + done/error frame + `onExhausted` +\n // submission interrupted), identical to deploy-recovery exhaustion.\n // Finalize the stream and return WITHOUT the generic terminal path,\n // which would otherwise re-broadcast the raw stall error.\n if (!streamFinalized) {\n this._errorResumableStream(streamId);\n streamFinalized = true;\n }\n doneSent = true;\n // Exhaustion is terminal for the turn, but it was delivered out-of-band\n // by `_exhaustChatRecovery` (banner/`onExhausted`), NOT through this\n // callback's `onError`. Signal the interruption so a `chat()` consumer\n // doesn't mis-read the clean resolve as a successful completion (#1644).\n skipFinalizeRearm = true;\n await callback.onInterrupted?.();\n return { status: \"aborted\" };\n }\n // outcome === \"disabled\" (chat recovery off): fall through to the\n // generic terminal path below (unchanged watchdog behavior).\n }\n if (!streamFinalized) {\n this._errorResumableStream(streamId);\n streamFinalized = true;\n }\n if (!doneSent) {\n const streamError =\n error instanceof Error ? error.message : \"Stream error\";\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: streamError,\n done: true,\n error: true\n });\n doneSent = true;\n }\n\n if (!assistantMsg && accumulator.parts.length > 0) {\n assistantMsg = accumulator.toMessage();\n await this._persistAssistantMessage(assistantMsg);\n this._broadcastMessages();\n }\n\n const wrapped = this.onChatError(error, {\n requestId,\n stage: \"stream\",\n messagesPersisted: true\n });\n const errorMessage =\n wrapped instanceof Error ? wrapped.message : String(wrapped);\n this._emit(\"chat:request:failed\", {\n requestId,\n stage: \"stream\",\n messagesPersisted: true,\n error: errorMessage\n });\n\n if (assistantMsg) {\n await this._fireResponseHook({\n message: assistantMsg,\n requestId,\n continuation: false,\n status: \"error\",\n error: errorMessage\n });\n }\n\n await callback.onError(errorMessage);\n } finally {\n // The message is now durably persisted (success, error, or recovery\n // path), so subsequent tool results resolve against storage; stop\n // exposing the sealed accumulator (#1649) and re-check any continuation\n // the stream-active barrier held (#1650). A stall-recovery early-return\n // does a plain clear instead (no re-arm): its scheduled continuation\n // re-runs the turn and that finalize re-triggers the held barrier, so\n // re-arming here would double-fire alongside the recovery continuation.\n if (skipFinalizeRearm) {\n this._streamingAssistant = null;\n } else {\n this._onStreamingTurnFinalized();\n }\n }\n\n if (pendingRpcError) {\n await callback.onError(pendingRpcError);\n }\n\n return {\n status:\n streamError || pendingRpcError\n ? \"error\"\n : aborted\n ? \"aborted\"\n : \"completed\"\n };\n }\n\n /**\n * Whether storing this chunk should immediately flush the resumable-stream\n * buffer to SQLite.\n *\n * A settled tool result (`tool-output-available` / `tool-output-error` /\n * `tool-output-denied`) captures a completed, often non-idempotent side\n * effect — or, for a denial, a user decision — so it is flushed\n * **immediately**. An isolate eviction (deploy) before the next batch flush\n * would otherwise lose it, and recovery would re-anchor without it and re-run\n * the already-completed tool call (or drop the denial). Frequent recoverable\n * content (text / reasoning / tool-input streaming) is throttled to avoid\n * write amplification.\n */\n private _shouldFlushRecoverableChunk(\n chunk: StreamChunkData,\n chunksSinceFlush: number,\n hasFlushedContent: boolean\n ): boolean {\n if (\n chunk.type === \"tool-output-available\" ||\n chunk.type === \"tool-output-error\" ||\n chunk.type === \"tool-output-denied\"\n ) {\n return true;\n }\n const isThrottledRecoverable =\n chunk.type === \"text-delta\" ||\n chunk.type === \"reasoning-delta\" ||\n chunk.type === \"tool-input-available\";\n return (\n isThrottledRecoverable && (!hasFlushedContent || chunksSinceFlush >= 10)\n );\n }\n\n /**\n * Store a stream chunk, flushing settled tool results durably and promptly.\n * Shared by the WebSocket and sub-agent RPC streaming paths so both get\n * tool-call-level recovery durability (recovery loses at most the in-flight\n * step, never an already-completed tool call).\n */\n private async _storeChunkDurably(\n streamId: string,\n chunk: StreamChunkData,\n chunkBody: string,\n state: { chunksSinceFlush: number; hasFlushedContent: boolean }\n ): Promise<void> {\n this._resumableStream.storeChunk(streamId, chunkBody);\n state.chunksSinceFlush++;\n if (\n this._shouldFlushRecoverableChunk(\n chunk,\n state.chunksSinceFlush,\n state.hasFlushedContent\n )\n ) {\n this._resumableStream.flushBuffer();\n state.chunksSinceFlush = 0;\n state.hasFlushedContent = true;\n // Forward progress: new durable content was just flushed. Advance the\n // monotonic, compaction-immune progress counter HERE (production time)\n // rather than in `_persistOrphanedStream` — so it bumps only on genuinely\n // new content and is immune to client reconnects / recovery re-persists\n // (which don't flow through this path). This is what the recovery\n // no-progress window keys off (#1637), and stays compaction-proof (#1628).\n await this._bumpChatRecoveryProgress();\n }\n }\n\n /**\n * Wrap a UI-message stream with an inactivity watchdog. If no chunk arrives\n * within `timeoutMs`, `onStall` runs (aborting the upstream model stream) and\n * the iterator throws, so the consumer loop exits with a terminal error\n * instead of parking forever on a hung provider/transport. `timeoutMs <= 0`\n * passes the source through untouched.\n */\n private async *_iterateWithStallWatchdog<T>(\n source: AsyncIterable<T>,\n timeoutMs: number,\n onStall: () => void\n ): AsyncGenerator<T> {\n if (!(timeoutMs > 0)) {\n yield* source;\n return;\n }\n const iterator = source[Symbol.asyncIterator]();\n // Tracks whether the watchdog itself aborted the upstream. In that case we\n // must NOT also `iterator.return()` it: cancelling the readable after the\n // abort makes the AI SDK pipeline write to an already-cancelled readable\n // (\"readable side is no longer readable\"). Letting the abort error the\n // stream is the clean path.\n let selfAborted = false;\n try {\n while (true) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n let stalled = false;\n const stall = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n stalled = true;\n reject(\n new ChatStreamStalledError(\n `Chat stream stalled: no activity for ${timeoutMs}ms; the turn was aborted by the stall watchdog.`\n )\n );\n }, timeoutMs);\n });\n const nextPromise = iterator.next();\n // If the watchdog wins the race we abandon this read; aborting the\n // upstream stream makes it reject later, so pre-attach a no-op catch to\n // keep that abandoned rejection from surfacing as an unhandled rejection.\n nextPromise.catch(() => {});\n let next: IteratorResult<T>;\n try {\n next = await Promise.race([nextPromise, stall]);\n } catch (err) {\n if (stalled) {\n selfAborted = true;\n onStall();\n }\n throw err;\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n if (next.done) return;\n yield next.value;\n }\n } finally {\n // Forward early termination (consumer `break`/`throw`, e.g. an in-band\n // stream error where the abort signal is NOT set) to the source so its\n // reader is cancelled — otherwise the wrapped source would leak when the\n // consumer stops reading mid-stream. Skipped after a watchdog stall, which\n // already aborted the upstream (see `selfAborted` above).\n if (!selfAborted) {\n await iterator.return?.(undefined as never).catch(() => {});\n }\n }\n }\n\n private async _streamResult(\n requestId: string,\n result: StreamableResult,\n abortSignal?: AbortSignal,\n options?: {\n continuation?: boolean;\n parentId?: string;\n captureProgrammaticStreamError?: boolean;\n captureOutput?: boolean;\n /**\n * When set, an in-stream error the app classifies as `context_overflow`\n * is treated as recoverable: the partial is persisted, the stream is\n * finalized cleanly (no terminal error frame), `onRetry(error)` is invoked\n * so the driver can compact and re-run, and `{ status: \"aborted\" }` is\n * returned. Pass only while the retry budget allows.\n */\n overflowRecovery?: { onRetry: (error?: string) => void };\n }\n ): Promise<StreamResultStatus> {\n const clearGen = this._turnQueue.generation;\n const streamId = this._startResumableStream(requestId);\n const continuation = options?.continuation ?? false;\n const parentId = options?.parentId;\n\n if (this._continuation.pending?.requestId === requestId) {\n this._continuation.activatePending();\n this._continuation.flushAwaitingConnections((c) =>\n this._notifyStreamResuming(c)\n );\n }\n\n const accumulator = new StreamAccumulator({\n messageId: crypto.randomUUID()\n });\n // Expose the in-flight message so a client tool result arriving before the\n // end-of-stream persist lands on the accumulator instead of being dropped\n // (#1649). Cleared before every return path below.\n this._streamingAssistant = accumulator;\n\n let doneSent = false;\n let streamAborted = false;\n let streamError: string | undefined;\n let output: unknown;\n // Set when an in-stream overflow error is recoverable (opt-in): suppresses\n // terminal delivery so the driver can compact and re-run the turn.\n let overflowRetry = false;\n const flushState = { chunksSinceFlush: 0, hasFlushedContent: false };\n\n const stallTimeoutMs =\n this._activeStallTimeoutMs ?? this.chatStreamStallTimeoutMs;\n try {\n this._insideInferenceLoop = true;\n try {\n const guardedStream = this._iterateWithStallWatchdog(\n result.toUIMessageStream(),\n stallTimeoutMs,\n () => {\n this._emit(\"chat:stream:stalled\", {\n requestId,\n timeoutMs: stallTimeoutMs\n });\n // Tear down the upstream model stream so a hung provider/transport\n // is released; the watchdog's throw drives the terminal error below.\n this.abortRequest(\n requestId,\n new Error(\"chat stream stalled: inactivity watchdog fired\")\n );\n }\n );\n for await (const chunk of guardedStream) {\n if (abortSignal?.aborted) {\n streamAborted = true;\n break;\n }\n\n const streamChunk = chunk as unknown as StreamChunkData;\n const { action } = accumulator.applyChunk(streamChunk);\n\n // Approved server tools execute during a continuation stream, but\n // their original tool part lives in an earlier assistant message.\n // The accumulator can only own this turn's new content, so it\n // surfaces a terminal result for a prior message as a\n // `cross-message-tool-update`. Persist + broadcast it directly so\n // the approved result reaches clients and durable storage. The\n // update builder is first-write-wins (replay-safe) and preserves a\n // streamed `preliminary` flag; `_applyToolUpdateToMessages` skips\n // the write/broadcast when the matched part is already settled.\n if (action?.type === \"cross-message-tool-update\") {\n await this._applyToolUpdateToMessages(\n crossMessageToolResultUpdate(\n action.toolCallId,\n action.updateType,\n action.output,\n action.errorText,\n action.preliminary\n )\n );\n }\n\n if (action?.type === \"error\") {\n streamError = action.error;\n // Recoverable context overflow (opt-in): don't terminalize. Persist\n // the partial after the loop, then signal the driver to compact and\n // re-run. No `message:error`/`chat:request:failed`/error frame here.\n if (\n options?.overflowRecovery &&\n this._isRecoverableContextOverflow(streamError, requestId)\n ) {\n overflowRetry = true;\n break;\n }\n if (options?.captureProgrammaticStreamError) {\n this._programmaticStreamErrors.set(requestId, streamError);\n }\n this._emit(\"message:error\", { error: streamError });\n // An AI-SDK error surfaces as a stream error part (not a thrown\n // exception), so it lands here rather than in the `catch` below.\n // Bridge it to `chat:request:failed` too — observers shouldn't have\n // to know whether the failure threw or arrived as a chunk (the\n // post-`beforeTurn`, in-stream provider 400 class), and turn-count\n // telemetry needs the failed signal to balance `turn.started`.\n this._emit(\"chat:request:failed\", {\n requestId,\n stage: \"stream\",\n messagesPersisted: true,\n error: streamError\n });\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: action.error,\n done: false,\n error: true,\n ...(continuation && { continuation: true })\n });\n break;\n }\n\n this._alignStreamStartId(\n streamChunk,\n action,\n accumulator,\n continuation\n );\n\n const chunkBody = JSON.stringify(chunk);\n await this._storeChunkDurably(\n streamId,\n streamChunk,\n chunkBody,\n flushState\n );\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: chunkBody,\n done: false,\n ...(continuation && { continuation: true })\n });\n }\n } finally {\n this._insideInferenceLoop = false;\n }\n\n // Recoverable context overflow: discard the partial, close this stream\n // segment WITHOUT a terminal frame, and hand control back to the driver\n // via `onRetry`. The inline retry runs in this same invocation and owns\n // the terminal outcome, so we must NOT emit a `done` frame here — and\n // `doneSent = true` keeps the outer `finally` from emitting one (it would\n // otherwise prematurely terminate the client's stream mid-recovery and\n // mark the segment errored).\n //\n // The partial is intentionally NOT persisted: the driver re-runs the turn\n // from scratch (`continuation: false`) against the compacted history, so\n // the retry produces a fresh assistant message. Persisting the truncated\n // partial would leave an orphan beside the recovered answer — and any tool\n // work it captured would be re-issued by the retry, duplicating records.\n // The live-streamed chunks already reached clients; the retry's\n // `_broadcastMessages()` reconciles them to the real answer.\n if (overflowRetry && options?.overflowRecovery) {\n this._completeResumableStream(streamId);\n this._pendingResumeConnections.clear();\n doneSent = true;\n options.overflowRecovery.onRetry(streamError);\n this._streamingAssistant = null;\n return { status: \"aborted\" };\n }\n\n if (streamError) {\n this._errorResumableStream(streamId);\n } else {\n this._completeResumableStream(streamId);\n }\n this._pendingResumeConnections.clear();\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true,\n ...(continuation && { continuation: true })\n });\n doneSent = true;\n } catch (error) {\n // #1626: a stream-stall watchdog abort is a recoverable interruption, not\n // a terminal error. Persist the settled partial (so the continuation\n // re-anchors without re-running completed tool calls), then route into\n // bounded recovery; only fall through to the terminal path below once the\n // budget is exhausted.\n if (error instanceof ChatStreamStalledError) {\n let targetAssistantId: string | undefined;\n const partialMsg = accumulator.toMessage();\n if (\n this._turnQueue.generation === clearGen &&\n accumulator.parts.length > 0\n ) {\n await this._persistAssistantMessage(partialMsg, parentId);\n this._broadcastMessages();\n targetAssistantId = partialMsg.id;\n }\n const outcome = await this._routeStallToBoundedRecovery({\n requestId,\n streamId,\n partialParts: partialMsg.parts,\n targetAssistantId\n });\n if (outcome === \"scheduled\") {\n // Recovering: close the stream cleanly (no terminal error frame); the\n // scheduled continuation drives the turn to completion. Report\n // `aborted` so the caller does not terminalize the turn.\n this._completeResumableStream(streamId);\n this._pendingResumeConnections.clear();\n if (!doneSent) {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true,\n ...(continuation && { continuation: true })\n });\n doneSent = true;\n }\n // `aborted` (not `error`): this attempt was aborted by the watchdog;\n // the scheduled continuation owns the real terminal outcome. No\n // response hook fires here (the continuation fires it), mirroring how\n // a deploy-interrupted attempt is superseded by its continuation.\n // Plain clear (no auto-continuation re-check): recovery re-runs the\n // turn and its own stream finalize re-triggers the held barrier.\n this._streamingAssistant = null;\n return { status: \"aborted\" };\n }\n if (outcome === \"exhausted\") {\n // `_routeStallToBoundedRecovery` already delivered the terminal UX\n // (configured `terminalMessage` + done/error frame + `onExhausted` +\n // submission interrupted), identical to deploy-recovery exhaustion.\n // Finalize the stream and report `aborted` (not `error`) so the caller\n // does not re-run the generic terminal path on top of it.\n this._errorResumableStream(streamId);\n this._pendingResumeConnections.clear();\n doneSent = true;\n this._streamingAssistant = null;\n return { status: \"aborted\" };\n }\n // outcome === \"disabled\" (chat recovery off): fall through to the\n // generic terminal path (the watchdog's original \"kill the spinner\"\n // guarantee, unchanged).\n }\n streamError = error instanceof Error ? error.message : \"Stream error\";\n if (options?.captureProgrammaticStreamError) {\n this._programmaticStreamErrors.set(requestId, streamError);\n }\n this._errorResumableStream(streamId);\n this._pendingResumeConnections.clear();\n if (!doneSent) {\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: streamError,\n done: true,\n error: true,\n ...(continuation && { continuation: true })\n });\n doneSent = true;\n }\n } finally {\n if (!doneSent) {\n this._errorResumableStream(streamId);\n this._pendingResumeConnections.clear();\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true,\n ...(continuation && { continuation: true })\n });\n }\n }\n\n if (\n options?.captureOutput &&\n result.output &&\n !streamError &&\n !streamAborted\n ) {\n try {\n output = await result.output;\n } catch (error) {\n streamError =\n error instanceof Error ? error.message : \"Structured output error\";\n if (options.captureProgrammaticStreamError) {\n this._programmaticStreamErrors.set(requestId, streamError);\n }\n }\n }\n\n if (this._turnQueue.generation === clearGen) {\n try {\n const assistantMsg = accumulator.toMessage();\n\n if (accumulator.parts.length > 0) {\n await this._persistAssistantMessage(assistantMsg, parentId);\n this._broadcastMessages();\n }\n\n await this._fireResponseHook({\n message: assistantMsg,\n requestId,\n continuation,\n status: streamError\n ? \"error\"\n : streamAborted\n ? \"aborted\"\n : \"completed\",\n error: streamError\n });\n } catch (e) {\n console.error(\"Failed to persist assistant message:\", e);\n }\n }\n\n // The message is now persisted (or the turn was cleared), so subsequent\n // tool results resolve against storage; stop exposing the accumulator and\n // re-check any continuation the stream-active barrier held (#1650).\n this._onStreamingTurnFinalized();\n\n return streamError\n ? { status: \"error\", error: streamError }\n : {\n status: streamAborted ? \"aborted\" : \"completed\",\n ...(output !== undefined && { output })\n };\n }\n\n // ── Session-backed persistence ──────────────────────────────────\n\n private async _persistAssistantMessage(\n msg: UIMessage,\n parentId?: string\n ): Promise<void> {\n const stripped = this._stripInternalFinalAnswerParts(msg);\n if (stripped !== msg) {\n // If removing the internal final-answer tool leaves nothing user-facing\n // (only structural `step-start` markers, or nothing), skip persistence so\n // a structured workflow turn does not leave an empty assistant message in\n // the conversation.\n const hasMeaningfulParts = stripped.parts.some(\n (part) => (part as { type?: string }).type !== \"step-start\"\n );\n if (!hasMeaningfulParts) return;\n await this._upsertMessageInHistory(stripped, parentId);\n return;\n }\n await this._upsertMessageInHistory(msg, parentId);\n }\n\n /**\n * Remove parts belonging to Think's internal structured-output final-answer\n * tool (`think_final_answer`, or a collision-suffixed variant) from a UI\n * message so the internal call/result never enters the persisted conversation\n * (and is never re-fed to the model on later turns). Stateless and matched by\n * the reserved name so it also covers recovery re-persist paths. Handles both\n * the static (`tool-<name>`) and dynamic (`dynamic-tool`) part shapes the AI\n * SDK can emit.\n */\n private _stripInternalFinalAnswerParts(msg: UIMessage): UIMessage {\n const parts = msg.parts.filter((part) => {\n const candidate = part as { type?: string; toolName?: string };\n if (\n typeof candidate.type === \"string\" &&\n candidate.type.startsWith(\"tool-\") &&\n isThinkFinalAnswerToolName(candidate.type.slice(\"tool-\".length))\n ) {\n return false;\n }\n if (\n candidate.type === \"dynamic-tool\" &&\n typeof candidate.toolName === \"string\" &&\n isThinkFinalAnswerToolName(candidate.toolName)\n ) {\n return false;\n }\n return true;\n });\n return parts.length === msg.parts.length ? msg : { ...msg, parts };\n }\n\n /**\n * Persist an incoming message after reconciliation. For assistant\n * messages, also resolve their ID against any server-side row that\n * already owns the same `toolCallId` so we update the existing row\n * instead of inserting an orphan duplicate.\n */\n private async _persistIncomingMessage(\n msg: UIMessage,\n serverMessages: readonly UIMessage[]\n ): Promise<void> {\n const resolved =\n msg.role === \"assistant\" ? resolveToolMergeId(msg, serverMessages) : msg;\n await this._upsertMessageInHistory(resolved);\n }\n\n private _persistClientTools(): void {\n if (this._lastClientTools) {\n this._configSet(\"lastClientTools\", JSON.stringify(this._lastClientTools));\n } else {\n this._configDelete(\"lastClientTools\");\n }\n }\n\n private _restoreClientTools(): void {\n const raw = this._configGet(\"lastClientTools\");\n if (raw) {\n try {\n this._lastClientTools = JSON.parse(raw);\n } catch {\n this._lastClientTools = undefined;\n }\n }\n }\n\n private _persistBody(): void {\n if (this._lastBody) {\n this._configSet(\"lastBody\", JSON.stringify(this._lastBody));\n } else {\n this._configDelete(\"lastBody\");\n }\n }\n\n private _restoreBody(): void {\n const raw = this._configGet(\"lastBody\");\n if (raw) {\n try {\n this._lastBody = JSON.parse(raw);\n } catch {\n this._lastBody = undefined;\n }\n }\n }\n\n // ── Tool state updates (shared primitives from agents/chat) ─────\n\n /**\n * Serialize a client-tool result/approval apply behind any in-flight apply\n * (#1649). Parallel tool results arrive as independent WebSocket messages,\n * and each apply is a read-modify-write of the full message in durable\n * storage. Running them concurrently means every apply reads the same\n * snapshot (all siblings still `input-available`), patches only its own part,\n * and writes the whole message back — so the last write clobbers the others\n * back to `input-available`, and the auto-continuation barrier later times\n * out and the transcript-repair backstop errors the lost siblings.\n *\n * Chaining each apply off `_interactionApplyTail` makes the read-modify-write\n * atomic per result and in arrival order. `_pendingInteractionPromise` is set\n * to the newest link so the barrier's single-slot wake-up still observes the\n * latest apply; because the chain is serial, awaiting it transitively waits\n * for every predecessor.\n *\n * @internal\n */\n protected _enqueueInteractionApply(\n apply: () => Promise<void>\n ): Promise<boolean> {\n const run = async (): Promise<boolean> => {\n await apply();\n return true;\n };\n // `.then(run, run)` runs regardless of a predecessor's outcome so one\n // rejected apply can't poison the rest of the batch.\n const resultPromise = this._interactionApplyTail.then(run, run);\n this._interactionApplyTail = resultPromise.then(\n () => undefined,\n () => undefined\n );\n this._pendingInteractionPromise = resultPromise;\n resultPromise\n .finally(() => {\n if (this._pendingInteractionPromise === resultPromise) {\n this._pendingInteractionPromise = null;\n }\n })\n .catch(() => {});\n return resultPromise;\n }\n\n private async _applyToolResult(\n toolCallId: string,\n output: unknown,\n overrideState?: \"output-error\",\n errorText?: string\n ): Promise<void> {\n const update = toolResultUpdate(\n toolCallId,\n output,\n overrideState,\n errorText\n );\n await this._applyToolUpdateToMessages(update);\n }\n\n private async _applyToolApproval(\n toolCallId: string,\n approved: boolean\n ): Promise<void> {\n const update = toolApprovalUpdate(toolCallId, approved);\n await this._applyToolUpdateToMessages(update);\n }\n\n // ── 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 * 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 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 * Reject a paused execution's pending action, ending the run. The\n * transcript's paused output is replaced with\n * `{ status: \"rejected\", executionId, reason }` and the chat\n * auto-continues so the model can adapt (or explain) instead of erroring.\n *\n * Client-callable.\n */\n async rejectExecution(\n executionId: string,\n reason?: string\n ): Promise<unknown> {\n const runtime = this._codemodeRuntime();\n if (!runtime) {\n return {\n status: \"error\",\n executionId,\n error:\n \"No codemode runtime is configured — the execute tool was never \" +\n \"created on this agent.\"\n };\n }\n const pending = await runtime.pending(executionId);\n if (pending.length === 0) {\n return {\n status: \"error\",\n executionId,\n error: `Execution \"${executionId}\" is no longer pending.`\n };\n }\n // `reject` reports whether it actually terminated the run. A `false`\n // means the action was resolved between our `pending()` check and the\n // reject (approve/reject interleave across facet RPC awaits — input\n // gates only cover storage). Writing \"rejected\" then would clobber a\n // paused part whose real outcome (e.g. an in-flight approval) is still\n // coming, so surface an error instead.\n const terminated = await runtime.reject({\n executionId,\n seq: pending[0].seq\n });\n if (!terminated) {\n return {\n status: \"error\",\n executionId,\n error: `Execution \"${executionId}\" is no longer pending — it was approved or rejected elsewhere.`\n };\n }\n const output = {\n status: \"rejected\",\n executionId,\n reason: reason ?? \"Rejected by user\"\n };\n await this._applyExecutionOutcome(executionId, output);\n return output;\n }\n\n /**\n * Replace a paused execute-tool output in the transcript with the\n * execution's new outcome and kick the auto-continuation so the model sees\n * it.\n *\n * When no paused part carries `executionId` — the output was already\n * replaced from another tab, or compaction summarized the part away — the\n * runtime has still durably applied the approval/rejection, so the outcome\n * must not be dropped: it is appended as a system note instead, and the\n * continuation still fires so the model can act on it.\n */\n private async _applyExecutionOutcome(\n executionId: string,\n output: unknown\n ): Promise<boolean> {\n const toolCallId = this._findPausedExecutionToolCall(executionId);\n if (!toolCallId) {\n // Already resolved in place (e.g. approved from another tab)? Then the\n // transcript has the outcome and nothing more is needed.\n if (this._findExecutionToolCall(executionId) != null) return false;\n let summary: string;\n try {\n summary = JSON.stringify(output)?.slice(0, 4_000) ?? String(output);\n } catch {\n summary = String(output);\n }\n await this._appendMessageToHistory({\n id: `exec-outcome-${executionId}-${crypto.randomUUID()}`,\n role: \"system\",\n parts: [\n {\n type: \"text\",\n text:\n `[execute tool] The paused execution \"${executionId}\" was ` +\n `resolved, but its tool call is no longer in the transcript ` +\n `(it may have been compacted). Outcome: ${summary}`\n }\n ]\n } as UIMessage);\n } else {\n await this._enqueueInteractionApply(() =>\n this._applyToolUpdateToMessages(\n pausedExecutionUpdate(toolCallId, executionId, output)\n )\n );\n }\n // Continue on the approving connection when there is one (WS callable),\n // else any open connection (DO-stub approval with clients attached).\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 }\n return true;\n }\n\n /**\n * Find the tool part holding the paused output of `executionId` — in the\n * in-flight streaming accumulator first (an approval can land while a new\n * turn streams), then the persisted transcript, newest message first.\n */\n private _findPausedExecutionToolCall(executionId: string): string | null {\n return this._findExecutionToolCall(executionId, true);\n }\n\n /**\n * Find the tool part carrying `executionId` in its output. With\n * `pausedOnly`, only a still-paused output matches — used to locate the\n * part an approval outcome should replace. Without it, any settled output\n * matches — used to distinguish \"already resolved elsewhere\" from \"the\n * part is gone from the transcript\" (e.g. compacted away).\n */\n private _findExecutionToolCall(\n executionId: string,\n pausedOnly = false\n ): string | null {\n const matches = (part: Record<string, unknown>): boolean => {\n if (part.state !== \"output-available\") return false;\n if (typeof part.toolCallId !== \"string\") return false;\n const output = part.output as\n | { status?: unknown; executionId?: unknown }\n | null\n | undefined;\n return (\n output != null &&\n typeof output === \"object\" &&\n (!pausedOnly || output.status === \"paused\") &&\n output.executionId === executionId\n );\n };\n\n const streaming = this._streamingAssistant;\n if (streaming) {\n for (const part of streaming.parts as unknown as Array<\n Record<string, unknown>\n >) {\n if (matches(part)) return part.toolCallId as string;\n }\n }\n\n for (let i = this.messages.length - 1; i >= 0; i--) {\n const message = this.messages[i];\n if (message.role !== \"assistant\") continue;\n for (const part of message.parts as unknown as Array<\n Record<string, unknown>\n >) {\n if (matches(part)) return part.toolCallId as string;\n }\n }\n return null;\n }\n\n private async _applyToolUpdateToMessages(update: {\n toolCallId: string;\n matchStates: string[];\n apply: (part: Record<string, unknown>) => Record<string, unknown>;\n }): Promise<void> {\n // The message to update can live in two places. During a streaming turn\n // the assistant message exists ONLY in the in-flight accumulator until\n // `_persistAssistantMessage` writes it at a turn boundary; a parallel-\n // batch sibling can also have been persisted already by stall recovery.\n // Apply to BOTH so the result is correct regardless of where the message\n // currently is and survives the eventual `accumulator.toMessage()` persist\n // (which would otherwise downgrade an applied result back to\n // `input-available` — #1649). Mirrors `@cloudflare/ai-chat`'s streaming-\n // message handling, generalized to also cover the post-persist case.\n let broadcastMessage: UIMessage | undefined;\n\n // (1) In-flight accumulator. A client tool result that arrives over the\n // WebSocket before the end-of-stream persist would be missed by a\n // storage-only lookup and later repaired as \"interrupted\". Writing it in\n // place lets it ride into the persist.\n const streaming = this._streamingAssistant;\n if (streaming) {\n const accParts = streaming.parts as unknown as Array<\n Record<string, unknown>\n >;\n const result = applyToolUpdate(accParts, update);\n if (result && result.parts[result.index] !== accParts[result.index]) {\n // `accParts` is a typed alias of the accumulator's live array, so this\n // in-place write is reflected by `streaming.toMessage()` and the\n // eventual end-of-stream persist.\n accParts[result.index] = result.parts[result.index];\n broadcastMessage = streaming.toMessage();\n }\n }\n\n // (2) Durable storage. Handles messages already persisted — including\n // partials written mid-stream by stall recovery and cross-message tool\n // results that target an earlier message than this turn's.\n const history = await this._readMessagesFromStorage();\n for (let i = 0; i < history.length; i++) {\n const msg = history[i];\n const msgParts = msg.parts as Array<Record<string, unknown>>;\n const result = applyToolUpdate(msgParts, update);\n if (result) {\n // First-write-wins / idempotent re-apply: when `apply` leaves the\n // matched part untouched (same reference) — e.g. a provider replay of\n // an already-settled cross-message tool result (#1404) — there is\n // nothing to persist. Skip the durable write and the redundant\n // `MESSAGE_UPDATED` broadcast so clients don't churn on a no-op.\n if (result.parts[result.index] === msgParts[result.index]) {\n break;\n }\n const updatedMsg = {\n ...msg,\n parts: result.parts as UIMessage[\"parts\"]\n };\n const safe = await this._updateMessageInHistory(updatedMsg);\n // Session change callbacks may run after an immediately scheduled\n // continuation begins. Keep its input cache coherent synchronously.\n this._patchCachedMessage(safe);\n // Patch the live cache in place instead of doing a full\n // `_syncMessages()` round-trip.\n // A full re-read during a streaming turn drops in-flight messages\n // whose parent chain hasn't been persisted yet (see commits\n // 3f615a24 \"revert _syncMessages in _applyToolUpdateToMessages\"\n // and 6e76bd49 \"update cached messages in-place\"). The cache is\n // the source of truth during a turn; we only reconcile it here to\n // reflect the tool update that was just written to storage.\n broadcastMessage = safe;\n break;\n }\n }\n\n if (broadcastMessage) {\n this._broadcast({\n type: MSG_MESSAGE_UPDATED,\n message: broadcastMessage\n });\n }\n }\n\n // ── Stability + pending interactions ─────────────────────────────\n\n protected hasPendingInteraction(): boolean {\n const clientResolvable = this._clientResolvableToolNames();\n return this.messages.some(\n (message) =>\n message.role === \"assistant\" &&\n this._messageHasPendingInteraction(message, clientResolvable)\n );\n }\n\n protected async waitUntilStable(options?: {\n timeout?: number;\n }): Promise<boolean> {\n const deadline =\n options?.timeout != null ? Date.now() + options.timeout : null;\n\n while (true) {\n if (\n (await this._awaitWithDeadline(\n this._submitConcurrency.waitForIdle(() =>\n this._turnQueue.waitForIdle()\n ),\n deadline\n )) === TIMED_OUT\n ) {\n return false;\n }\n\n if (!this.hasPendingInteraction()) {\n return true;\n }\n\n const pending = this._pendingInteractionPromise;\n if (pending) {\n let result: boolean | typeof TIMED_OUT;\n try {\n result = await this._awaitWithDeadline(pending, deadline);\n } catch {\n continue;\n }\n if (result === TIMED_OUT) {\n return false;\n }\n } else {\n if (\n (await this._awaitWithDeadline(\n new Promise<void>((resolve) => setTimeout(resolve, 100)),\n deadline\n )) === TIMED_OUT\n ) {\n return false;\n }\n }\n }\n }\n\n private async _awaitWithDeadline<T>(\n promise: Promise<T>,\n deadline: number | null\n ): Promise<T | typeof TIMED_OUT> {\n if (deadline == null) {\n return promise;\n }\n const remainingMs = Math.max(0, deadline - Date.now());\n let timer: ReturnType<typeof setTimeout>;\n const result = await Promise.race([\n promise,\n new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(() => resolve(TIMED_OUT), remainingMs);\n })\n ]);\n clearTimeout(timer!);\n return result;\n }\n\n private _messageHasPendingInteraction(\n message: UIMessage,\n clientResolvable: Set<string>\n ): boolean {\n return message.parts.some((part) =>\n this._partAwaitsClientInteraction(part, clientResolvable)\n );\n }\n\n /**\n * Names of the tools whose interrupted `input-available` part can still be\n * resolved by the CLIENT after a restart — i.e. the client tools (no server\n * `execute`) from the last request, which the SPA answers by replaying a\n * `tool-result` over the WebSocket. A server tool is intentionally absent:\n * its `execute()` promise died with the evicted isolate, so nothing will\n * ever post its result.\n */\n private _clientResolvableToolNames(): Set<string> {\n const names = new Set<string>();\n for (const tool of this._lastClientTools ?? []) {\n if (tool?.name) names.add(tool.name);\n }\n return names;\n }\n\n /** Extract a tool part's name from its `tool-<name>` / `dynamic-tool` shape. */\n private _toolPartName(record: Record<string, unknown>): string | undefined {\n const type = typeof record.type === \"string\" ? record.type : \"\";\n if (type === \"dynamic-tool\") {\n return typeof record.toolName === \"string\" ? record.toolName : undefined;\n }\n if (type.startsWith(\"tool-\")) {\n return type.slice(\"tool-\".length);\n }\n return undefined;\n }\n\n /**\n * Whether a part is still awaiting a CLIENT interaction that can genuinely\n * arrive after a restart, so `waitUntilStable` must keep waiting for it:\n * - `approval-requested`: a reconnecting client can replay the approval.\n * - `input-available` for a CLIENT tool: the SPA can replay the\n * `tool-result` (this is why client-tool recovery works — see the\n * `tool-result` handler, which sets `_pendingInteractionPromise`).\n *\n * A SERVER tool's `input-available` is deliberately NOT pending. After an\n * eviction its `execute()` promise is gone and no interaction will ever\n * resolve it, so treating it as pending wedges `waitUntilStable` forever:\n * the recovery continuation times out every attempt, burns the attempt\n * budget on a wait that can never converge, and — if any transient\n * storage/schedule error throws on the way — the one-shot recovery alarm row\n * is swallowed and deleted with no terminal `onExhausted` (the half-finished\n * message wedges silently). Excluding it lets `waitUntilStable` converge so\n * `continueLastTurn` runs, where the existing transcript-repair pass\n * (`_repairTranscriptForProvider`) flips the orphan to an errored result and\n * the model proceeds.\n */\n private _partAwaitsClientInteraction(\n part: UIMessage[\"parts\"][number],\n clientResolvable: Set<string>\n ): boolean {\n if (!(\"state\" in part)) return false;\n const record = part as Record<string, unknown>;\n const state = record.state;\n if (state === \"approval-requested\") return true;\n if (state !== \"input-available\") return false;\n const toolName = this._toolPartName(record);\n return toolName != null && clientResolvable.has(toolName);\n }\n\n // ── Chat recovery via fibers ───────────────────────────────────\n\n private _resolveChatRecoveryConfig(): ResolvedChatRecoveryConfig {\n const raw = this.chatRecovery;\n const custom = typeof raw === \"object\" ? raw : undefined;\n return {\n enabled: raw !== false,\n maxAttempts: Math.max(\n 1,\n Math.floor(custom?.maxAttempts ?? DEFAULT_CHAT_RECOVERY_MAX_ATTEMPTS)\n ),\n stableTimeoutMs: Math.max(\n 0,\n Math.floor(\n custom?.stableTimeoutMs ?? DEFAULT_CHAT_RECOVERY_STABLE_TIMEOUT_MS\n )\n ),\n terminalMessage:\n custom?.terminalMessage ?? DEFAULT_CHAT_RECOVERY_TERMINAL_MESSAGE,\n noProgressTimeoutMs: Math.max(\n 0,\n Math.floor(\n custom?.noProgressTimeoutMs ??\n DEFAULT_CHAT_RECOVERY_NO_PROGRESS_TIMEOUT_MS\n )\n ),\n maxRecoveryWork:\n typeof custom?.maxRecoveryWork === \"number\" &&\n custom.maxRecoveryWork >= 0\n ? custom.maxRecoveryWork\n : DEFAULT_CHAT_RECOVERY_MAX_WORK,\n ...(custom?.shouldKeepRecovering\n ? { shouldKeepRecovering: custom.shouldKeepRecovering }\n : {}),\n ...(custom?.onExhausted ? { onExhausted: custom.onExhausted } : {})\n };\n }\n\n private _chatRecoveryIncidentId(input: {\n requestId: string;\n recoveryRootRequestId?: string | null;\n latestUserMessageId?: string | null;\n targetAssistantId?: string | null;\n recoveryKind: ChatRecoveryKind;\n }): string {\n // `recoveryKind` is intentionally NOT part of the identity: a single\n // interrupted turn can flip between \"retry\" (no chunks persisted) and\n // \"continue\" (partial chunks exist) across restarts, and the attempt\n // budget must be shared so recovery stays bounded by `maxAttempts`.\n return [\n input.recoveryRootRequestId ?? input.requestId,\n input.latestUserMessageId ?? \"\"\n ].join(\":\");\n }\n\n private _chatRecoveryIncidentKey(incidentId: string): string {\n return `${CHAT_RECOVERY_INCIDENT_KEY_PREFIX}${encodeURIComponent(incidentId)}`;\n }\n\n /**\n * Monotonic forward-progress signal for recovery budget resets.\n *\n * This used to count assistant messages in `this.messages`, but that is\n * recomputed from the live, mutable transcript. Compaction collapses older\n * assistant messages into a summary, lowering the count — so a turn that had\n * genuinely advanced could read as \"no progress\" between attempts and exhaust\n * its budget prematurely (#1628). Instead we read a durably-persisted counter\n * that only ever increments — bumped at production time when new content is\n * durably flushed (see `_storeChunkDurably`), which is genuine forward\n * progress and is immune to client reconnects / recovery re-persists — so\n * compaction can never lower it and a reconnect can't fake it (#1637).\n */\n private async _chatRecoveryProgressMarker(): Promise<number> {\n return (\n (await this.ctx.storage.get<number>(CHAT_RECOVERY_PROGRESS_KEY)) ?? 0\n );\n }\n\n /** Advance the durable recovery-progress counter. Called from\n * `_storeChunkDurably` when new content is durably flushed (real, reconnect-\n * immune forward progress). */\n private async _bumpChatRecoveryProgress(): Promise<void> {\n const current =\n (await this.ctx.storage.get<number>(CHAT_RECOVERY_PROGRESS_KEY)) ?? 0;\n await this.ctx.storage.put(CHAT_RECOVERY_PROGRESS_KEY, current + 1);\n }\n\n /** In-memory wall-clock of the last N9 child-stream progress bump (reset per\n * isolate so the first forwarded chunk after a restart always credits). */\n private _lastAgentToolStreamProgressAt = 0;\n\n /**\n * N9: forwarding a sub-agent's chunks IS forward progress for this parent\n * turn, so credit the parent's recovery progress marker — otherwise a parent\n * whose turn merely `await`s a child banks no progress of its own and its\n * no-progress window exhausts while the child is healthily streaming. Only\n * invoked after a child actually produced output (see\n * `_forwardAgentToolStream`), so a silent child still lets the parent exhaust.\n * Throttled (and reset per isolate) so we never write storage per token.\n */\n protected override async _onAgentToolStreamProgress(): Promise<void> {\n const now = Date.now();\n if (\n now - this._lastAgentToolStreamProgressAt <\n AGENT_TOOL_STREAM_PROGRESS_BUMP_THROTTLE_MS\n ) {\n return;\n }\n this._lastAgentToolStreamProgressAt = now;\n await this._bumpChatRecoveryProgress();\n }\n\n /** Sweep recovery incidents that have been inactive past the TTL. */\n private async _sweepStaleChatRecoveryIncidents(now: number): Promise<void> {\n const entries = await this.ctx.storage.list<ChatRecoveryIncident>({\n prefix: CHAT_RECOVERY_INCIDENT_KEY_PREFIX\n });\n const staleKeys: string[] = [];\n for (const [key, incident] of entries) {\n const lastActive = incident?.lastAttemptAt ?? incident?.firstSeenAt ?? 0;\n if (now - lastActive > CHAT_RECOVERY_INCIDENT_TTL_MS) {\n staleKeys.push(key);\n }\n }\n // Batch deletes — the DO storage KV delete accepts up to 128 keys per call,\n // collapsing N awaited round-trips into ceil(N / 128).\n for (let i = 0; i < staleKeys.length; i += KV_DELETE_MAX_KEYS) {\n await this.ctx.storage.delete(staleKeys.slice(i, i + KV_DELETE_MAX_KEYS));\n }\n }\n\n private async _beginChatRecoveryIncident(input: {\n requestId: string;\n recoveryRootRequestId?: string | null;\n latestUserMessageId?: string | null;\n targetAssistantId?: string | null;\n recoveryKind: ChatRecoveryKind;\n /** Test-only clock injection for deterministic debounce/window timing. */\n nowMs?: number;\n }): Promise<{\n incident: ChatRecoveryIncident;\n config: ResolvedChatRecoveryConfig;\n exhausted: boolean;\n }> {\n const config = this._resolveChatRecoveryConfig();\n const incidentId = this._chatRecoveryIncidentId(input);\n const key = this._chatRecoveryIncidentKey(incidentId);\n const now = input.nowMs ?? Date.now();\n await this._sweepStaleChatRecoveryIncidents(now);\n const existing = await this.ctx.storage.get<ChatRecoveryIncident>(key);\n\n // Hibernation ordering guard. The budget decision below 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 runs\n // the boot-recovery path (`_handleInternalFiberRecovery`) BEFORE onStart's\n // `_restoreClientTools()`, so without this the in-memory cache is empty and\n // such a turn is misread as \"stuck\" and wrongly sealed (the slow-human +\n // deploy-churn case). Re-hydrate from the durable `think_config` store — its\n // own table, no Session init required, so the read is safe this early; the\n // guard keeps it idempotent with the later onStart restore and a no-op on\n // the live-isolate stall path where the tools are already loaded.\n if (this._lastClientTools === undefined) {\n this._restoreClientTools();\n }\n\n // Forward-progress detection. A mid-turn deploy resets the Durable Object\n // (\"code was updated\"); the interrupted continuation is re-detected on the\n // next wake. A turn that followed real progress (more durably-produced\n // content than the last attempt saw) is environmental churn, not a poison\n // turn.\n const prevProgress = existing?.progress ?? 0;\n const currentProgress = await this._chatRecoveryProgressMarker();\n const madeProgress = existing != null && currentProgress > prevProgress;\n\n // A turn parked on a pending CLIENT interaction (an `input-available`\n // client-tool part or an `approval-requested` part — see\n // `hasPendingInteraction`) is WAITING ON THE HUMAN, not stuck. It produces\n // no forward progress by design until the SPA replays the tool-result /\n // approval after reconnect, which drives a fresh continuation via the\n // auto-continuation barrier independently of recovery. Spending the recovery\n // budget on that wait would seal a perfectly healthy turn whose human is\n // simply slow (e.g. a mid-turn deploy during a confirmation prompt that the\n // user takes more than `noProgressTimeoutMs` to answer). So while a client\n // interaction is pending the turn is budget-free: the no-progress window,\n // attempt cap, work budget, and caller predicate are all suppressed, and the\n // no-progress clock is kept fresh so the turn has a full window once the\n // human finally answers. SERVER-tool orphans are deliberately excluded by\n // `hasPendingInteraction` (their `execute` died with the isolate, so nothing\n // will resolve them) — they still recover normally. The recovery\n // continuation additionally PARKS (skips, no reschedule) on a stable-state\n // timeout while this holds; see `_chatRecoveryContinue`/`_chatRecoveryRetry`.\n const awaitingClientInteraction = this.hasPendingInteraction();\n\n // Recovery budget (#1637, rfc-chat-recovery-work-budget). A turn making\n // genuine forward progress survives unbounded deploy churn — duration is\n // never a bound. The instruments are decoupled by what they catch:\n // • STUCK — no-progress window: `lastProgressAt` resets on every\n // progress-bearing attempt, so a turn that keeps producing content\n // survives churn indefinitely; a stuck turn is sealed after 5 min.\n // • DEBOUNCE — alarms bunched within `ALARM_DEBOUNCE_MS` collapse into one\n // attempt, so a single rollout's reconnect storm isn't N attempts.\n // • ALARM-LOOP — the attempt cap (resets on progress) catches a tight\n // no-progress alarm loop.\n // • RUNAWAY — the work budget seals a loop that keeps emitting content but\n // never converges. Keyed to WORK done (produced content/tool units since\n // the incident opened), not wall-clock, because a healthy long turn and a\n // runaway differ by bounded work, not duration. Defaults to no cap.\n // • CALLER — `shouldKeepRecovering` lets the integrator express a\n // token/cost/step budget the SDK should not hardcode.\n const lastProgressAt =\n madeProgress || awaitingClientInteraction\n ? now\n : (existing?.lastProgressAt ?? existing?.firstSeenAt ?? now);\n const noProgressExceeded =\n existing != null &&\n !awaitingClientInteraction &&\n now - lastProgressAt > config.noProgressTimeoutMs;\n // Reuse the durable progress counter as a work meter. Baseline is captured\n // when the incident opens; `work` is what the turn produced since.\n const workBaseline = existing?.workBaseline ?? currentProgress;\n const progress = Math.max(prevProgress, currentProgress);\n const work = progress - workBaseline;\n const workBudgetExceeded =\n existing != null &&\n Number.isFinite(config.maxRecoveryWork) &&\n work > config.maxRecoveryWork;\n const debounced =\n existing != null &&\n !madeProgress &&\n now - existing.lastAttemptAt < CHAT_RECOVERY_ALARM_DEBOUNCE_MS;\n\n const attempt = madeProgress\n ? 1\n : debounced\n ? (existing?.attempt ?? 1)\n : (existing?.attempt ?? 0) + 1;\n\n // Consult the caller predicate only when no hard bound has already sealed\n // the incident — a buggy/expensive hook must not run after we've decided,\n // and a throwing hook must not wedge the turn (log and treat as \"continue\").\n let abortedByCaller = false;\n if (\n existing != null &&\n !awaitingClientInteraction &&\n config.shouldKeepRecovering &&\n !noProgressExceeded &&\n !workBudgetExceeded &&\n attempt <= config.maxAttempts\n ) {\n try {\n const decision = await config.shouldKeepRecovering({\n incidentId,\n requestId: input.requestId,\n recoveryRootRequestId: input.recoveryRootRequestId ?? input.requestId,\n attempt,\n maxAttempts: config.maxAttempts,\n recoveryKind: input.recoveryKind,\n work,\n ageMs: now - (existing.firstSeenAt ?? now)\n });\n abortedByCaller = decision === false;\n } catch (error) {\n console.error(\n \"[Think] chatRecovery shouldKeepRecovering hook threw\",\n error\n );\n }\n }\n\n const exhausted =\n !awaitingClientInteraction &&\n (noProgressExceeded ||\n workBudgetExceeded ||\n abortedByCaller ||\n attempt > config.maxAttempts);\n const incident: ChatRecoveryIncident = {\n incidentId,\n requestId: input.requestId,\n recoveryRootRequestId: input.recoveryRootRequestId ?? input.requestId,\n recoveryKind: input.recoveryKind,\n attempt,\n maxAttempts: config.maxAttempts,\n status: exhausted ? \"exhausted\" : \"attempting\",\n firstSeenAt: existing?.firstSeenAt ?? now,\n lastAttemptAt: now,\n lastProgressAt,\n progress,\n workBaseline,\n ...(exhausted\n ? {\n reason: workBudgetExceeded\n ? \"work_budget_exceeded\"\n : noProgressExceeded\n ? \"no_progress_timeout\"\n : abortedByCaller\n ? \"recovery_aborted\"\n : \"max_attempts_exceeded\"\n }\n : {})\n };\n await this.ctx.storage.put(key, incident);\n\n if (!existing) {\n this._emit(\"chat:recovery:detected\", {\n incidentId,\n requestId: input.requestId,\n attempt,\n maxAttempts: config.maxAttempts,\n recoveryKind: input.recoveryKind\n });\n }\n this._emit(\"chat:recovery:attempt\", {\n incidentId,\n requestId: input.requestId,\n attempt,\n maxAttempts: config.maxAttempts,\n recoveryKind: input.recoveryKind\n });\n\n return { incident, config, exhausted };\n }\n\n private async _updateChatRecoveryIncident(\n incidentId: string | undefined,\n status: ChatRecoveryIncident[\"status\"],\n reason?: string\n ): Promise<void> {\n if (!incidentId) return;\n const key = this._chatRecoveryIncidentKey(incidentId);\n const incident = await this.ctx.storage.get<ChatRecoveryIncident>(key);\n if (!incident) return;\n // A completed recovery is terminal and will not be retried, so drop the\n // record instead of leaving it in storage forever. Non-completed states\n // (scheduled/skipped/failed) are retained so the attempt budget survives\n // across restarts; the TTL sweep eventually reclaims abandoned ones.\n if (status === \"completed\") {\n await this.ctx.storage.delete(key);\n } else {\n await this.ctx.storage.put(key, {\n ...incident,\n status,\n ...(reason ? { reason } : {})\n } satisfies ChatRecoveryIncident);\n }\n\n const eventType =\n status === \"completed\"\n ? \"chat:recovery:completed\"\n : status === \"skipped\"\n ? \"chat:recovery:skipped\"\n : status === \"failed\"\n ? \"chat:recovery:failed\"\n : undefined;\n if (eventType) {\n this._emit(eventType, {\n incidentId,\n requestId: incident.requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind: incident.recoveryKind,\n ...(reason ? { reason } : {})\n });\n }\n\n // Live \"recovering…\" status (#1620): a scheduled continuation/retry means\n // recovery is in progress; a terminal incident state resolves it. Keyed by\n // the recovery-root request id so it lines up with the turn the client is\n // watching. (Exhaustion + normal completion also clear via\n // `_recordTerminalChatStatus`; this covers the benign-skip / failed paths\n // that never reach a turn-level terminal.)\n if (status === \"scheduled\") {\n await this._setChatRecovering(\n true,\n incident.recoveryRootRequestId ?? incident.requestId\n );\n } else if (\n status === \"completed\" ||\n status === \"skipped\" ||\n status === \"failed\"\n ) {\n await this._setChatRecovering(false);\n }\n }\n\n private async _exhaustChatRecovery(\n incident: ChatRecoveryIncident,\n config: ResolvedChatRecoveryConfig,\n partial: { text: string; parts: MessagePart[] },\n streamId: string,\n createdAt: number\n ): Promise<void> {\n const ctx: ChatRecoveryExhaustedContext = {\n incidentId: incident.incidentId,\n requestId: incident.requestId,\n recoveryRootRequestId:\n incident.recoveryRootRequestId ?? incident.requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind: incident.recoveryKind,\n streamId,\n createdAt,\n partialText: partial.text,\n partialParts: partial.parts,\n reason: incident.reason ?? \"max_attempts_exceeded\",\n terminalMessage: config.terminalMessage\n };\n this._emit(\"chat:recovery:exhausted\", ctx);\n // A throwing onExhausted hook must not prevent the terminal UX from being\n // delivered, otherwise the turn wedges with no user-visible resolution.\n try {\n await config.onExhausted?.(ctx);\n } catch (error) {\n console.error(\"[Think] chatRecovery onExhausted hook threw\", error);\n }\n // Deliver the user-visible terminal banner BEFORE the bookkeeping storage\n // writes below. A `ctx.storage` write can reject mid-deploy (the exact\n // window recovery exhausts in), and if it threw before this broadcast the\n // user would be left staring at a half-finished message with no terminal\n // resolution. The broadcast itself touches no storage, so ordering it first\n // makes the banner resilient to a failing `_recordTerminalChatStatus` /\n // `_markRecoveredSubmissionInterrupted`.\n //\n // (`@cloudflare/ai-chat` persists before broadcasting instead. Ordering\n // can't rescue a terminal-record write that itself fails, so that choice\n // gains no reconnect reliability under storage failure while losing this\n // banner resilience — hence Think keeps broadcast-first.)\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: incident.requestId,\n body: config.terminalMessage,\n done: true,\n error: true\n });\n // Write the durable terminal record (#1645) FIRST among the storage writes:\n // it's the record a disconnected client replays on reconnect, so it must\n // not be skipped if the (independent) submission-row write below throws.\n await this._recordTerminalChatStatus(\n \"interrupted\",\n incident.requestId,\n config.terminalMessage\n );\n // The submission is keyed by the recovery ROOT request id; `incident.requestId`\n // is the latest per-continuation id and won't match a chained submission.\n await this._markRecoveredSubmissionInterrupted(\n incident.recoveryRootRequestId ?? incident.requestId,\n config.terminalMessage\n );\n // The exhausted record is retained for inspection and reclaimed later by\n // the TTL sweep; only successful (completed) incidents are deleted eagerly.\n }\n\n /**\n * Route a stream-stall watchdog abort into bounded recovery instead of a\n * terminal error (#1626). A stall happens inside a LIVE isolate (no DO\n * restart), so the normal restart-detected recovery path never runs — we\n * open/advance a recovery incident here and schedule a continuation, reusing\n * the SAME budget (`maxAttempts` + wall-clock window + progress-aware reset)\n * as deploy/eviction recovery. A transient hang recovers; a persistently\n * hanging provider exhausts the budget. Idempotency matches deploy recovery:\n * settled tool results are durable and won't re-run, but a tool that was\n * mid-execution when the stall fired re-runs on the continuation.\n *\n * Returns:\n * - `\"scheduled\"` — a continuation was scheduled; the caller suppresses the\n * terminal error and closes the stream cleanly.\n * - `\"exhausted\"` — the budget is spent; this routes through the SAME\n * `_exhaustChatRecovery` path as deploy recovery (fires `onExhausted`,\n * emits `chat:recovery:exhausted`, marks the submission interrupted, and\n * delivers the configured `terminalMessage`). The caller must NOT run the\n * generic terminal path — the terminal UX is already delivered.\n * - `\"disabled\"` — chat recovery is off; the caller falls through to the\n * generic terminal error (the watchdog's original \"kill the spinner\"\n * behavior, unchanged).\n */\n private async _routeStallToBoundedRecovery(input: {\n requestId: string;\n streamId: string;\n partialParts: MessagePart[];\n targetAssistantId?: string;\n }): Promise<\"scheduled\" | \"exhausted\" | \"disabled\"> {\n // Stall-recovery is automatic only when chat recovery is enabled (the\n // default for Think). With recovery off, a stall stays terminal — there is\n // no budget/continuation machinery to route into.\n if (!this._resolveChatRecoveryConfig().enabled) return \"disabled\";\n const recoveryRootRequestId =\n this._activeChatRecoveryRootRequestId ?? input.requestId;\n const latestUserMessageId =\n [...this.messages].reverse().find((m) => m.role === \"user\")?.id ?? null;\n const { incident, config, exhausted } =\n await this._beginChatRecoveryIncident({\n requestId: input.requestId,\n recoveryRootRequestId,\n latestUserMessageId,\n recoveryKind: \"continue\"\n });\n if (exhausted) {\n // Budget spent: deliver the SAME terminal UX as deploy-recovery\n // exhaustion (terminalMessage + onExhausted + chat:recovery:exhausted +\n // submission interrupted) instead of letting the raw stall error leak\n // out. `firstSeenAt` is the closest available turn-start proxy here.\n const partialText = input.partialParts\n .filter(\n (p): p is { type: \"text\"; text: string } =>\n (p as { type?: string }).type === \"text\"\n )\n .map((p) => p.text)\n .join(\"\");\n await this._exhaustChatRecovery(\n incident,\n config,\n { text: partialText, parts: input.partialParts },\n input.streamId,\n incident.firstSeenAt\n );\n return \"exhausted\";\n }\n await this._updateChatRecoveryIncident(incident.incidentId, \"scheduled\");\n this._emit(\"chat:recovery:scheduled\", {\n incidentId: incident.incidentId,\n requestId: input.requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind: \"continue\"\n });\n // If a durable submission is running for this turn, the continuation must\n // complete it (otherwise the submission hangs) — same as deploy recovery.\n const recoveredRequestId = this._hasRunningSubmission(recoveryRootRequestId)\n ? recoveryRootRequestId\n : undefined;\n await this.schedule(\n 0,\n \"_chatRecoveryContinue\",\n {\n ...(input.targetAssistantId\n ? { targetAssistantId: input.targetAssistantId }\n : {}),\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n lastBody: this._lastBody ?? null,\n lastClientTools: this._lastClientTools ?? null,\n ...(recoveredRequestId ? { recoveredRequestId } : {})\n },\n { idempotent: true }\n );\n return \"scheduled\";\n }\n\n protected override async _handleInternalFiberRecovery(\n ctx: FiberRecoveryContext\n ): Promise<boolean> {\n if (await this._messengerRuntime?.handleFiberRecovery(ctx)) {\n return true;\n }\n\n const chatPrefix = (this.constructor as typeof Think).CHAT_FIBER_NAME + \":\";\n if (!ctx.name.startsWith(chatPrefix)) {\n return false;\n }\n\n const requestId = ctx.name.slice(chatPrefix.length);\n const { snapshot: recoverySnapshot, user: recoveryData } =\n unwrapChatFiberSnapshot<\"think-chat-turn\">(\n \"__cfThinkChatFiberSnapshot\",\n ctx.snapshot,\n \"think-chat-turn\"\n );\n\n let streamId = \"\";\n let streamStatus: \"streaming\" | \"completed\" | \"error\" | undefined;\n if (requestId) {\n const rows = this.sql<{\n id: string;\n status: \"streaming\" | \"completed\" | \"error\";\n }>`\n SELECT id, status FROM cf_ai_chat_stream_metadata\n WHERE request_id = ${requestId}\n ORDER BY created_at DESC LIMIT 1\n `;\n if (rows.length > 0) {\n streamId = rows[0].id;\n streamStatus = rows[0].status;\n }\n }\n if (!streamId && this._resumableStream.hasActiveStream()) {\n streamId = this._resumableStream.activeStreamId ?? \"\";\n streamStatus = \"streaming\";\n }\n\n const partial = streamId\n ? this._getPartialStreamText(streamId)\n : { text: \"\", parts: [] as MessagePart[] };\n\n const streamStillActive =\n streamId &&\n this._resumableStream.hasActiveStream() &&\n this._resumableStream.activeStreamId === streamId;\n\n const streamIsTerminal =\n streamStatus === \"completed\" || streamStatus === \"error\";\n\n const retryTargetUserId = await this._recoverablePreStreamUserId(\n recoverySnapshot,\n streamId ?? \"\",\n partial\n );\n const shouldRetryBase = retryTargetUserId !== null && !streamIsTerminal;\n const recoveryKind: ChatRecoveryKind = shouldRetryBase\n ? \"retry\"\n : \"continue\";\n const recoveryRootRequestId =\n recoverySnapshot?.recoveryRootRequestId ?? requestId;\n const { incident, config, exhausted } =\n await this._beginChatRecoveryIncident({\n requestId,\n recoveryRootRequestId,\n latestUserMessageId: recoverySnapshot?.latestUserMessageId,\n recoveryKind\n });\n\n if (exhausted) {\n // Preserve the settled partial before sealing the turn. Exhaustion is\n // decided BEFORE `onChatRecovery` is consulted, so without this the\n // settled (often non-idempotent) tool results the turn already produced\n // are discarded and the model re-runs them on the next message (#1631).\n // Same gating as the normal path below so an already-persisted partial is\n // never duplicated.\n if (\n await this._shouldPersistOrphanedPartial(streamId, {\n streamStillActive: Boolean(streamStillActive),\n streamIsTerminal,\n snapshot: recoverySnapshot\n })\n ) {\n await this._persistOrphanedStream(streamId);\n }\n await this._exhaustChatRecovery(\n incident,\n config,\n partial,\n streamId ?? \"\",\n ctx.createdAt\n );\n return true;\n }\n\n // Any throw after the incident is opened (user `onChatRecovery`, orphan\n // persistence, scheduling) must flip the incident to a terminal `failed`\n // state and emit, otherwise it leaks in `attempting` and is never\n // observable as a stuck turn.\n try {\n const options =\n (await this.onChatRecovery({\n incidentId: incident.incidentId,\n recoveryRootRequestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind,\n streamId: streamId ?? \"\",\n requestId,\n partialText: partial.text,\n partialParts: partial.parts,\n recoveryData,\n messages: [...this.messages],\n lastBody: recoverySnapshot?.lastBody ?? this._lastBody,\n lastClientTools:\n recoverySnapshot?.lastClientTools ?? this._lastClientTools,\n createdAt: ctx.createdAt\n })) ?? {};\n\n const shouldPersist = await this._shouldPersistOrphanedPartial(streamId, {\n streamStillActive: Boolean(streamStillActive),\n streamIsTerminal,\n snapshot: recoverySnapshot\n });\n\n // Settled work — completed, often non-idempotent tool results — is NEVER\n // dropped by recovery. `persist: false` only suppresses persistence of a\n // partial that has nothing settled to lose; a partial carrying settled\n // tool results is persisted regardless, so an app can never accidentally\n // discard completed work (and never needs `{ persist: true }` just to be\n // safe). A safe default beats a warning about an unsafe one (#1631).\n if (\n shouldPersist &&\n (options.persist !== false ||\n this._partialHasSettledToolResults(partial.parts))\n ) {\n await this._persistOrphanedStream(streamId);\n }\n\n if (streamStillActive) {\n this._completeResumableStream(streamId);\n }\n\n const shouldRetry =\n retryTargetUserId !== null &&\n options.continue !== false &&\n !streamIsTerminal;\n const lastLeaf = shouldRetry ? null : await this.session.getLatestLeaf();\n const targetId =\n lastLeaf?.role === \"assistant\" && !streamIsTerminal\n ? lastLeaf.id\n : undefined;\n const canContinue =\n !shouldRetry && options.continue !== false && !streamIsTerminal;\n // The durable submission is keyed by the recovery ROOT request id (stable\n // across the whole continuation chain), not this turn's per-continuation\n // requestId. Keying off `requestId` loses the link on every chained\n // continuation, so the continuation that finally completes the turn can no\n // longer mark the submission done (see investigate/recovery-* findings).\n const hasRunningSubmission = this._hasRunningSubmission(\n recoveryRootRequestId\n );\n\n if (streamIsTerminal && hasRunningSubmission) {\n await this._completeRecoveredSubmission(\n recoveryRootRequestId,\n streamStatus === \"completed\" ? \"completed\" : \"error\",\n requestId,\n streamStatus === \"completed\"\n ? null\n : \"Recovered chat stream had already errored.\"\n );\n }\n\n const recoveredRequestId =\n (canContinue || shouldRetry) && hasRunningSubmission\n ? recoveryRootRequestId\n : undefined;\n\n if (shouldRetry) {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"scheduled\"\n );\n this._emit(\"chat:recovery:scheduled\", {\n incidentId: incident.incidentId,\n requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind\n });\n await this.schedule(\n 0,\n \"_chatRecoveryRetry\",\n {\n targetUserId: retryTargetUserId,\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n lastBody: recoverySnapshot?.lastBody ?? null,\n lastClientTools: recoverySnapshot?.lastClientTools ?? null,\n ...(recoveredRequestId ? { recoveredRequestId } : {})\n },\n { idempotent: true }\n );\n } else if (canContinue) {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"scheduled\"\n );\n this._emit(\"chat:recovery:scheduled\", {\n incidentId: incident.incidentId,\n requestId,\n attempt: incident.attempt,\n maxAttempts: incident.maxAttempts,\n recoveryKind\n });\n await this.schedule(\n 0,\n \"_chatRecoveryContinue\",\n {\n ...(targetId ? { targetAssistantId: targetId } : {}),\n originalRequestId: recoveryRootRequestId,\n incidentId: incident.incidentId,\n ...(recoverySnapshot\n ? {\n lastBody: recoverySnapshot.lastBody ?? null,\n lastClientTools: recoverySnapshot.lastClientTools ?? null\n }\n : {}),\n ...(recoveredRequestId ? { recoveredRequestId } : {})\n },\n { idempotent: true }\n );\n } else if (options.continue === false && !streamIsTerminal) {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"skipped\",\n \"continue_disabled\"\n );\n const disabledMessage =\n \"Submission was interrupted and chat recovery was disabled.\";\n // Key off the recovery ROOT, not this continuation's `requestId` — a\n // chained submission's row still carries the root id, so passing the\n // per-continuation id would miss it and leave it stuck `running`.\n await this._markRecoveredSubmissionInterrupted(\n recoveryRootRequestId,\n disabledMessage\n );\n // Unlike `conversation_changed` (a newer turn owns the UI, so silence\n // is correct), disabling recovery abandons the turn with no superseding\n // turn. Surface it like exhaustion so a reconnecting client isn't frozen.\n await this._recordTerminalChatStatus(\n \"interrupted\",\n requestId,\n disabledMessage\n );\n this._broadcastChat({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: disabledMessage,\n done: true,\n error: true\n });\n } else {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"skipped\",\n streamIsTerminal ? \"stream_terminal\" : \"not_recoverable\"\n );\n }\n\n return true;\n } catch (error) {\n await this._updateChatRecoveryIncident(\n incident.incidentId,\n \"failed\",\n error instanceof Error ? error.message : String(error)\n );\n throw error;\n }\n }\n\n private async _recoverablePreStreamUserId(\n snapshot: ChatFiberSnapshot<\"think-chat-turn\"> | null,\n streamId: string,\n partial: { text: string; parts: MessagePart[] }\n ): Promise<string | null> {\n if (\n !snapshot ||\n snapshot.continuation ||\n !snapshot.latestUserMessageId ||\n streamId ||\n partial.text ||\n partial.parts.length > 0\n ) {\n return null;\n }\n\n const lastLeaf = await this.session.getLatestLeaf();\n return lastLeaf?.role === \"user\" &&\n lastLeaf.id === snapshot.latestUserMessageId\n ? snapshot.latestUserMessageId\n : null;\n }\n\n private async _hasPersistedRecoveredAssistant(\n snapshot: ChatFiberSnapshot<\"think-chat-turn\"> | null\n ): Promise<boolean> {\n const lastLeaf = await this.session.getLatestLeaf();\n return (\n lastLeaf?.role === \"assistant\" &&\n lastLeaf.id !== snapshot?.latestMessageId\n );\n }\n\n /**\n * Whether the orphaned stream's partial should be materialized into an\n * assistant message: there is a stream, and it is either still active or\n * terminal-but-not-yet-persisted. Shared by the normal recovery path AND the\n * exhaustion path so neither discards settled work nor duplicates a partial\n * an earlier attempt already saved.\n */\n private async _shouldPersistOrphanedPartial(\n streamId: string,\n opts: {\n streamStillActive: boolean;\n streamIsTerminal: boolean;\n snapshot: ChatFiberSnapshot<\"think-chat-turn\"> | null;\n }\n ): Promise<boolean> {\n if (!streamId) return false;\n const alreadyPersisted =\n opts.streamIsTerminal &&\n (await this._hasPersistedRecoveredAssistant(opts.snapshot));\n return (\n opts.streamStillActive || (opts.streamIsTerminal && !alreadyPersisted)\n );\n }\n\n /** Whether a reconstructed partial carries any settled (provider-accepted)\n * tool result — the completed, often non-idempotent work that a\n * `{ persist: false }` recovery return would silently discard. */\n private _partialHasSettledToolResults(parts: MessagePart[]): boolean {\n return parts.some((part) => {\n const record = part as Record<string, unknown>;\n const type = typeof record.type === \"string\" ? record.type : \"\";\n return (\n (type.startsWith(\"tool-\") || type === \"dynamic-tool\") &&\n this._toolPartHasSettledResult(record)\n );\n });\n }\n\n /**\n * Reschedule a recovery callback that timed out waiting for stable state,\n * consuming one attempt. Returns `true` if rescheduled, `false` if the\n * attempt budget is exhausted (the caller then fails the turn terminally).\n *\n * Shared by `_chatRecoveryRetry` and `_chatRecoveryContinue` so the\n * non-idempotent scheduling invariant lives in exactly one place — a fix to\n * one path can't silently diverge from the other. Mirrors the same helper in\n * `@cloudflare/ai-chat`.\n */\n private async _rescheduleRecoveryAfterStableTimeout(\n callback: \"_chatRecoveryContinue\" | \"_chatRecoveryRetry\",\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined,\n maxAttempts: number\n ): Promise<boolean> {\n const incidentKey = data?.incidentId\n ? this._chatRecoveryIncidentKey(data.incidentId)\n : null;\n const incident = incidentKey\n ? await this.ctx.storage.get<ChatRecoveryIncident>(incidentKey)\n : null;\n if (!incident || !incidentKey) return false;\n const attempt = incident.attempt ?? 0;\n if (attempt >= (incident.maxAttempts ?? maxAttempts)) return false;\n await this.ctx.storage.put(incidentKey, {\n ...incident,\n attempt: attempt + 1,\n status: \"scheduled\",\n lastAttemptAt: Date.now(),\n reason: \"stable_timeout_retry\"\n });\n // Must NOT be idempotent: this runs INSIDE the currently-executing one-shot\n // schedule row (which `alarm()` deletes only after we return). An idempotent\n // reschedule would dedup onto that row and then be deleted with it — the\n // retry would silently never fire, stalling the turn. A fresh delayed row\n // survives the deletion.\n await this.schedule(\n CHAT_RECOVERY_STABLE_RETRY_DELAY_SECONDS,\n callback,\n data ?? {},\n { idempotent: false }\n );\n return true;\n }\n\n /**\n * 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 * Resolve the stream id for a recovery turn so the give-up terminalization\n * can surface whatever partial the turn produced. Prefers the durable stream\n * row keyed by the recovery-root request id; falls back to the live active\n * stream. Returns `\"\"` when neither is available (the terminal banner still\n * fires — `_exhaustChatRecovery` does not require a stream).\n */\n private _resolveRecoveryStreamId(requestId: string): string {\n if (requestId) {\n const fromMetadata = this._resumableStream\n .getAllStreamMetadata()\n .find((metadata) => metadata.request_id === requestId)?.id;\n if (fromMetadata) return fromMetadata;\n }\n return this._resumableStream.hasActiveStream()\n ? (this._resumableStream.activeStreamId ?? \"\")\n : \"\";\n }\n\n /**\n * Terminalize a recovery turn that is giving up — whether because the\n * stable-state-timeout retry budget drained, or because the recovery\n * continuation threw a non-recoverable error — by routing through the SAME\n * `_exhaustChatRecovery` path as deploy-recovery and stall exhaustion\n * (#1626/#1631). It fires `onExhausted`, emits `chat:recovery:exhausted`,\n * marks the durable submission interrupted, records the terminal chat status,\n * and delivers the configured `terminalMessage`. `reason` carries the cause\n * (`stable_timeout` for a budget give-up, `recovery_error` for a thrown\n * error) through to `onExhausted` / `chat:recovery:exhausted`.\n *\n * This replaces the older give-up that only set the incident to `failed` and\n * completed the recovered submission as `error`, which bypassed\n * `_exhaustChatRecovery` entirely — so an app relying on `onExhausted` for the\n * terminal banner regressed to an eternal spinner when recovery gave up under\n * extreme churn. The error path matters just as much: a non-transient throw\n * in a recovery callback is SWALLOWED by `Agent._executeScheduleCallback`\n * (only a platform transient is re-thrown to preserve the one-shot row), so\n * without routing it here the alarm row is deleted with no terminal UX at\n * all — the half-finished message wedges silently. Shared by\n * `_chatRecoveryRetry` and `_chatRecoveryContinue`.\n *\n * Exactly-once terminalization is defended by two independent guards:\n * 1. The `stored?.status === \"exhausted\"` re-entry guard below — once an\n * incident is sealed, a duplicate stale alarm (or retried callback)\n * returns before re-firing. The seal is persisted only AFTER the\n * terminal writes in `_exhaustChatRecovery` succeed (see the ordering\n * note at the call below), so a give-up interrupted by a platform\n * transient re-runs in full instead of being half-sealed.\n * 2. The durable-submission paths additionally short-circuit earlier at the\n * `submission_not_running` check (the submission is already `error` after\n * the first give-up). This is the ONLY guard `@cloudflare/ai-chat` lacks\n * (no submission layer), so guard #1 carries it there.\n *\n * Residual at-least-once edges, all deliberately accepted as \"deliver a\n * second banner\" ≫ \"silently drop the turn\":\n * • No `incidentId` at all in the payload (only reachable via a direct/test\n * invocation — every production scheduler carries one): the synthesized\n * incident can't be persisted (no key), so guard #1 can't arm.\n * • The record is swept AGAIN between two alarms (guard #1 re-persists on the\n * first, so this needs a second independent sweep) — vanishingly unlikely.\n * • A platform transient interrupts `_exhaustChatRecovery` after the banner\n * broadcast — the deferred re-run re-fires `onExhausted` + the banner\n * (the terminal writes themselves are idempotent).\n */\n private async _exhaustRecoveryGiveUp(\n callback: \"_chatRecoveryContinue\" | \"_chatRecoveryRetry\",\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined,\n reason: string\n ): Promise<void> {\n const config = this._resolveChatRecoveryConfig();\n const incidentKey = data?.incidentId\n ? this._chatRecoveryIncidentKey(data.incidentId)\n : null;\n // The incident read/write below are best-effort: they back the re-entry\n // guard, not the terminal UX. Under deploy storage stress they can reject,\n // but terminalization MUST still fire — a failed bookkeeping op here is\n // exactly what used to drop the turn silently. So tolerate a failed read\n // (synthesize the incident) and a failed write (accept a possible second\n // banner) rather than letting either abort `_exhaustChatRecovery`.\n let stored: ChatRecoveryIncident | null = null;\n if (incidentKey) {\n try {\n stored =\n (await this.ctx.storage.get<ChatRecoveryIncident>(incidentKey)) ??\n null;\n } catch (readError) {\n console.error(\n \"[Think] failed to read recovery incident during give-up; synthesizing\",\n readError\n );\n }\n }\n\n // Re-entry guard #1 (see method doc): a sealed incident means\n // terminalization already happened, so a duplicate stale alarm must not\n // re-fire `onExhausted` / re-broadcast the banner.\n if (stored?.status === \"exhausted\") return;\n\n const rootRequestId =\n data?.originalRequestId ??\n data?.recoveredRequestId ??\n this._activeChatRecoveryRootRequestId ??\n stored?.recoveryRootRequestId ??\n stored?.requestId ??\n \"\";\n\n const incident: ChatRecoveryIncident = stored\n ? { ...stored, status: \"exhausted\", reason }\n : {\n // Silent-drop guard: the incident record is gone (no `incidentId`, or\n // it was swept/deleted before this stale alarm fired). Synthesize a\n // minimal incident so the turn STILL terminalizes through\n // `onExhausted` instead of being dropped with no terminal UX — the\n // exact \"eternal spinner\" failure mode this fix closes.\n incidentId: data?.incidentId ?? crypto.randomUUID(),\n requestId: rootRequestId,\n recoveryRootRequestId: rootRequestId,\n recoveryKind:\n callback === \"_chatRecoveryRetry\" ? \"retry\" : \"continue\",\n attempt: config.maxAttempts,\n maxAttempts: config.maxAttempts,\n status: \"exhausted\",\n firstSeenAt: Date.now(),\n lastAttemptAt: Date.now(),\n reason\n };\n\n const streamId = this._resolveRecoveryStreamId(\n incident.recoveryRootRequestId ?? incident.requestId\n );\n const partial = streamId\n ? this._getPartialStreamText(streamId)\n : { text: \"\", parts: [] as MessagePart[] };\n\n // Terminalize BEFORE sealing the incident. The terminal writes inside\n // `_exhaustChatRecovery` (`_recordTerminalChatStatus`,\n // `_markRecoveredSubmissionInterrupted`) hit storage and can reject with a\n // platform transient in exactly the window a give-up tends to run in\n // (#1730: deploy reset / storage outage). Letting that throw propagate is\n // deliberate: the recovery callback's caller (`Agent._executeScheduleCallback`)\n // defers the one-shot row on a platform transient, so the WHOLE give-up\n // re-runs on a healthy isolate instead of half-sealing. Sealing first\n // would arm the re-entry guard above and turn that re-run into a no-op —\n // dropping the durable terminal record and the submission's terminal\n // state. The re-run is idempotent: `_recordTerminalChatStatus` overwrites\n // the same key and `_markRecoveredSubmissionInterrupted` is gated on\n // `status = 'running'`; `onExhausted` + the banner may fire again — the\n // documented at-least-once edge (\"deliver a second banner\" ≫ \"silently\n // drop the turn\").\n await this._exhaustChatRecovery(\n incident,\n config,\n partial,\n streamId,\n incident.firstSeenAt\n );\n\n // Persist the sealed incident (retained for inspection / TTL sweep) so the\n // re-entry guard above sees `exhausted` if a duplicate stale alarm fires.\n // Best-effort: terminalization already fully succeeded, so a failed seal\n // write costs at most a re-delivered banner on a duplicate alarm.\n if (incidentKey) {\n try {\n await this.ctx.storage.put(incidentKey, incident);\n } catch (writeError) {\n console.error(\n \"[Think] failed to persist sealed recovery incident during give-up\",\n writeError\n );\n }\n }\n }\n\n /**\n * Give-up after the stable-state-timeout retry budget drained. Thin wrapper\n * over `_exhaustRecoveryGiveUp` so the give-up cause is recorded as\n * `stable_timeout`.\n */\n private _exhaustRecoveryAfterStableTimeout(\n callback: \"_chatRecoveryContinue\" | \"_chatRecoveryRetry\",\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined\n ): Promise<void> {\n return this._exhaustRecoveryGiveUp(callback, data, \"stable_timeout\");\n }\n\n /**\n * Handle an error thrown by `_chatRecoveryContinue` / `_chatRecoveryRetry`\n * after the incident was opened.\n *\n * - A platform transient (`isPlatformTransientError` from `agents` — a\n * deploy code-update reset / script supersede, a `retryable`-flagged\n * platform error, or \"Network connection lost.\", looking through wrappers\n * like `SqlError` via the `cause` chain) is re-thrown (after best-effort\n * marking the incident `failed` for observability) so\n * `Agent._executeScheduleCallback` preserves the one-shot alarm row and\n * the platform re-runs recovery once it is healthy again — the turn can\n * still recover, so it must NOT terminalize. Terminalizing here was the\n * #1730 freeze: the give-up's own seal needs the very storage that is\n * down, so it throws too, burns the in-process retry budget inside the\n * same reset window, and the row is consumed milliseconds before storage\n * recovers. The submission is deliberately left `running` — the deferred\n * re-run reads it via `_readRunningSubmissionByRequestId`, so marking it\n * terminal here would turn the preserved row into a guaranteed\n * `submission_not_running` no-op skip (a self-defeating defer).\n * - Any OTHER (application) error is terminalized through the give-up path\n * (`onExhausted` + the `terminalMessage` banner) and NOT re-thrown. This is\n * the fix for the silent-seal failure mode: `_executeScheduleCallback`\n * swallows a non-transient throw and then `alarm()` deletes the one-shot\n * row, so without terminalizing here the half-finished turn is dropped\n * with no terminal event and no banner (the user stares at a frozen\n * message until they send something new).\n */\n private async _handleRecoveryCallbackError(\n callback: \"_chatRecoveryContinue\" | \"_chatRecoveryRetry\",\n data: ChatRecoveryContinueData | ChatRecoveryRetryData | undefined,\n error: unknown\n ): Promise<void> {\n if (isPlatformTransientError(error)) {\n const message = error instanceof Error ? error.message : String(error);\n try {\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"failed\",\n message\n );\n } catch (bookkeepingError) {\n // Best-effort observability only — in the exact window this branch\n // fires (deploy reset / storage outage) the incident write itself can\n // reject; that must not replace the deferral with its own error.\n console.error(\n \"[Think] failed to mark recovery incident failed before deferring\",\n bookkeepingError\n );\n }\n throw error;\n }\n // Preserve the underlying error for operators — the give-up path records\n // only the `recovery_error` category on the incident / `onExhausted` ctx,\n // so without this log the actual cause would be lost. Mirrors\n // `Agent._executeScheduleCallback`'s own logging.\n console.error(\n `[Think] ${callback} threw during recovery; terminalizing instead of leaving the turn wedged`,\n error\n );\n // `_exhaustRecoveryGiveUp` marks the submission interrupted + records the\n // terminal chat status itself (via `_exhaustChatRecovery`), so it fully\n // replaces the old mark-failed + complete-as-error bookkeeping here.\n await this._exhaustRecoveryGiveUp(callback, data, \"recovery_error\");\n }\n\n async _chatRecoveryRetry(data?: ChatRecoveryRetryData): Promise<void> {\n const recoveredSubmission = data?.recoveredRequestId\n ? this._readRunningSubmissionByRequestId(data.recoveredRequestId)\n : null;\n if (data?.recoveredRequestId && !recoveredSubmission) {\n await this._updateChatRecoveryIncident(\n data.incidentId,\n \"skipped\",\n \"submission_not_running\"\n );\n return;\n }\n\n const previousRootRequestId = this._activeChatRecoveryRootRequestId;\n this._activeChatRecoveryRootRequestId =\n data?.originalRequestId ?? previousRootRequestId;\n const controller = recoveredSubmission ? new AbortController() : null;\n if (recoveredSubmission && controller) {\n this._submissionAbortControllers.set(\n recoveredSubmission.submission_id,\n controller\n );\n }\n\n try {\n const recoveryConfig = this._resolveChatRecoveryConfig();\n const ready = await this.waitUntilStable({\n timeout: recoveryConfig.stableTimeoutMs\n });\n if (!ready) {\n // PARK while a CLIENT interaction is pending — the turn is waiting for\n // the human, not churning; see `_chatRecoveryContinue` for the full\n // rationale.\n if (await this._parkRecoveryForPendingInteraction(data)) {\n return;\n }\n // Transient under churn — reschedule within the attempt budget rather\n // than terminally failing the turn (see _chatRecoveryContinue).\n if (\n await this._rescheduleRecoveryAfterStableTimeout(\n \"_chatRecoveryRetry\",\n data,\n recoveryConfig.maxAttempts\n )\n ) {\n return;\n }\n // Budget spent: terminalize through the SAME exhaustion path as deploy\n // recovery (fires `onExhausted`, delivers the `terminalMessage` banner,\n // marks the submission interrupted) instead of silently dropping the\n // turn — otherwise an app relying on `onExhausted` sees an eternal\n // spinner.\n await this._exhaustRecoveryAfterStableTimeout(\n \"_chatRecoveryRetry\",\n data\n );\n return;\n }\n\n const lastLeaf = await this.session.getLatestLeaf();\n if (!lastLeaf || lastLeaf.role !== \"user\") {\n // The user turn is no longer the leaf — it was already answered (an\n // assistant message now follows) or the conversation moved on. This is\n // a benign skip, not an error: a completing turn marks the submission\n // `completed`; otherwise it is terminally `skipped`, never `error`.\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"skipped\",\n \"no_unanswered_user_message\"\n );\n if (data?.recoveredRequestId) {\n await this._completeRecoveredSubmission(\n data.recoveredRequestId,\n \"skipped\",\n null,\n null\n );\n }\n return;\n }\n\n if (data?.targetUserId && lastLeaf.id !== data.targetUserId) {\n // Superseded by a genuinely newer user turn — terminal `skipped`, not an\n // error (recovery being superseded is benign).\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"skipped\",\n \"conversation_changed\"\n );\n if (data?.recoveredRequestId) {\n await this._completeRecoveredSubmission(\n data.recoveredRequestId,\n \"skipped\",\n null,\n null\n );\n }\n return;\n }\n\n this._applyRecoveredRequestContext(data);\n const result = await this._retryLastUserTurn(\n this._lastClientTools,\n this._lastBody,\n controller ? { signal: controller.signal } : undefined\n );\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n result.status === \"completed\"\n ? \"completed\"\n : result.status === \"skipped\"\n ? \"skipped\"\n : \"failed\",\n result.error\n );\n if (data?.recoveredRequestId) {\n await this._completeRecoveredSubmission(\n data.recoveredRequestId,\n result.status,\n result.requestId || null,\n result.status === \"completed\"\n ? null\n : (result.error ?? `Recovery retry ${result.status}.`)\n );\n }\n } catch (error) {\n await this._handleRecoveryCallbackError(\n \"_chatRecoveryRetry\",\n data,\n error\n );\n } finally {\n this._activeChatRecoveryRootRequestId = previousRootRequestId;\n if (recoveredSubmission) {\n this._submissionAbortControllers.delete(\n recoveredSubmission.submission_id\n );\n }\n // If this facet is an agent-tool child, its recovered turn just settled\n // outside `startAgentToolRun`'s finalizer — eagerly close the run so a\n // re-attached parent collects the terminal immediately rather than\n // waiting out a no-progress window. The pre-stream retry path settles a\n // fresh user turn that (like `continueLastTurn`) never hits the\n // finalizer, so it needs the same reconcile as `_chatRecoveryContinue`.\n await this._reconcileOwnStaleAgentToolChildRuns();\n }\n }\n\n private _hasRunningSubmission(requestId: string): boolean {\n return this._readRunningSubmissionByRequestId(requestId) !== null;\n }\n\n private _readRunningSubmissionByRequestId(\n requestId: string\n ): ThinkSubmissionRow | null {\n this._ensureSubmissionTable();\n const rows = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE request_id = ${requestId}\n AND status = 'running'\n LIMIT 1\n `;\n return rows[0] ?? null;\n }\n\n private async _markRecoveredSubmissionInterrupted(\n requestId: string,\n message: string\n ): Promise<void> {\n this._ensureSubmissionTable();\n const rows = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE request_id = ${requestId}\n AND status = 'running'\n LIMIT 1\n `;\n const row = rows[0];\n if (!row) return;\n this.sql`\n UPDATE cf_think_submissions\n SET status = 'error',\n error_message = ${message},\n completed_at = ${Date.now()}\n WHERE submission_id = ${row.submission_id}\n AND status = 'running'\n `;\n const updated = this._readSubmission(row.submission_id);\n if (updated) await this._emitSubmissionStatus(updated);\n }\n\n private async _completeRecoveredSubmission(\n originalRequestId: string,\n status: ThinkSubmissionStatus,\n requestId: string | null,\n errorMessage: string | null\n ): Promise<void> {\n this._ensureSubmissionTable();\n const completedAt = Date.now();\n const streamId = requestId\n ? (this._resumableStream\n .getAllStreamMetadata()\n .find((metadata) => metadata.request_id === requestId)?.id ?? null)\n : null;\n this.sql`\n UPDATE cf_think_submissions\n SET status = ${status},\n request_id = COALESCE(${requestId}, request_id),\n stream_id = COALESCE(${streamId}, stream_id),\n error_message = ${errorMessage},\n completed_at = ${completedAt}\n WHERE request_id = ${originalRequestId}\n AND status = 'running'\n `;\n const rows = this.sql<ThinkSubmissionRow>`\n SELECT submission_id, idempotency_key, request_id, stream_id, status,\n messages_json, metadata_json, error_message, created_at,\n messages_applied_at, started_at, completed_at\n FROM cf_think_submissions\n WHERE request_id = COALESCE(${requestId}, ${originalRequestId})\n ORDER BY completed_at DESC\n LIMIT 1\n `;\n const updated = rows[0];\n if (updated && this._isTerminalSubmissionStatus(updated.status)) {\n await this._emitSubmissionStatus(updated);\n }\n }\n\n protected async onChatRecovery(\n _ctx: ChatRecoveryContext\n ): Promise<ChatRecoveryOptions | void> {\n return {};\n }\n\n async _chatRecoveryContinue(data?: ChatRecoveryContinueData): Promise<void> {\n const recoveredSubmission = data?.recoveredRequestId\n ? this._readRunningSubmissionByRequestId(data.recoveredRequestId)\n : null;\n if (data?.recoveredRequestId && !recoveredSubmission) {\n await this._updateChatRecoveryIncident(\n data.incidentId,\n \"skipped\",\n \"submission_not_running\"\n );\n return;\n }\n\n const previousRootRequestId = this._activeChatRecoveryRootRequestId;\n this._activeChatRecoveryRootRequestId =\n data?.originalRequestId ?? previousRootRequestId;\n const controller = recoveredSubmission ? new AbortController() : null;\n if (recoveredSubmission && controller) {\n this._submissionAbortControllers.set(\n recoveredSubmission.submission_id,\n controller\n );\n }\n\n try {\n const recoveryConfig = this._resolveChatRecoveryConfig();\n const ready = await this.waitUntilStable({\n timeout: recoveryConfig.stableTimeoutMs\n });\n if (!ready) {\n // PARK, don't burn the budget: a stable-state timeout while a CLIENT\n // interaction is pending is not churn — the turn is correctly waiting\n // for the SPA to replay an interrupted tool-result / approval after\n // reconnect, which drives a fresh continuation via the auto-continuation\n // barrier independently of this retry loop. Retrying here would just\n // time out again (the human hasn't answered) and eventually seal a\n // healthy turn on `stable_timeout`. So stop the loop, resolve the live\n // \"recovering…\" indicator, and let the client's replay resume the turn.\n if (await this._parkRecoveryForPendingInteraction(data)) {\n return;\n }\n console.warn(\n \"[Think] _chatRecoveryContinue timed out waiting for stable state\"\n );\n // A stable-state timeout under deploy churn is usually transient (the\n // isolate is still settling / another deploy is in flight). Reschedule\n // within the attempt budget instead of terminally failing the turn at\n // attempt 1; only give up once the budget is genuinely exhausted.\n if (\n await this._rescheduleRecoveryAfterStableTimeout(\n \"_chatRecoveryContinue\",\n data,\n recoveryConfig.maxAttempts\n )\n ) {\n return;\n }\n // Budget spent: terminalize through the SAME exhaustion path as deploy\n // recovery (fires `onExhausted`, delivers the `terminalMessage` banner,\n // marks the submission interrupted) instead of silently dropping the\n // turn — otherwise an app relying on `onExhausted` sees an eternal\n // spinner.\n await this._exhaustRecoveryAfterStableTimeout(\n \"_chatRecoveryContinue\",\n data\n );\n return;\n }\n\n const targetId = data?.targetAssistantId;\n const lastLeaf = await this.session.getLatestLeaf();\n if (targetId && lastLeaf?.id !== targetId) {\n // The target assistant message is no longer the leaf. This is NOT an\n // error and must never clobber the submission to `error`:\n // - leaf is an ASSISTANT message → recovery's OWN later continuation\n // advanced (or already completed) this turn. This continuation is\n // stale/superseded; skip benignly and leave the submission alone so\n // the active continuation marks the real outcome (`completed`).\n // - leaf is a USER message → a genuinely newer turn superseded this\n // one; mark the submission `skipped` (terminal, non-error) so it\n // doesn't hang waiting on a turn nobody will finish.\n const supersededByNewerUserTurn = lastLeaf?.role === \"user\";\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n \"skipped\",\n \"conversation_changed\"\n );\n if (data?.recoveredRequestId && supersededByNewerUserTurn) {\n await this._completeRecoveredSubmission(\n data.recoveredRequestId,\n \"skipped\",\n null,\n null\n );\n }\n return;\n }\n\n this._applyRecoveredRequestContext(data);\n const result = await this.continueLastTurn(\n undefined,\n controller ? { signal: controller.signal } : undefined\n );\n await this._updateChatRecoveryIncident(\n data?.incidentId,\n result.status === \"completed\"\n ? \"completed\"\n : result.status === \"skipped\"\n ? \"skipped\"\n : \"failed\",\n result.error\n );\n if (data?.recoveredRequestId) {\n await this._completeRecoveredSubmission(\n data.recoveredRequestId,\n result.status,\n result.requestId || null,\n result.status === \"completed\"\n ? null\n : (result.error ?? `Recovery ${result.status}.`)\n );\n }\n } catch (error) {\n await this._handleRecoveryCallbackError(\n \"_chatRecoveryContinue\",\n data,\n error\n );\n } finally {\n this._activeChatRecoveryRootRequestId = previousRootRequestId;\n if (recoveredSubmission) {\n this._submissionAbortControllers.delete(\n recoveredSubmission.submission_id\n );\n }\n // 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 } {\n const chunks = this._resumableStream.getStreamChunks(streamId);\n const parts: MessagePart[] = [];\n\n for (const chunk of chunks) {\n try {\n const data = JSON.parse(chunk.body);\n applyChunkToParts(parts, data);\n } catch {\n // skip malformed chunks\n }\n }\n\n const text = parts\n .filter(\n (p): p is MessagePart & { type: \"text\"; text: string } =>\n p.type === \"text\" && \"text\" in p\n )\n .map((p) => p.text)\n .join(\"\");\n\n return { text, parts };\n }\n\n // ── Concurrency strategies ──────────────────────────────────────\n\n private _getSubmitConcurrencyDecision(\n isSubmitMessage: boolean\n ): SubmitConcurrencyDecision {\n return this._submitConcurrency.decide({\n concurrency: this.messageConcurrency,\n isSubmitMessage,\n queuedTurns: this._turnQueue.queuedCount()\n });\n }\n\n private _completeSkippedRequest(\n connection: Connection,\n requestId: string\n ): void {\n connection.send(\n JSON.stringify({\n type: MSG_CHAT_RESPONSE,\n id: requestId,\n body: \"\",\n done: true\n })\n );\n }\n\n private _rollbackDroppedSubmit(connection: Connection): void {\n connection.send(\n JSON.stringify({\n type: MSG_CHAT_MESSAGES,\n messages: this.messages\n })\n );\n }\n\n // ── Auto-continuation ──────────────────────────────────────────\n\n private _scheduleAutoContinuation(connection: Connection): void {\n if (this._continuation.pending?.pastCoalesce) {\n this._continuation.deferred = {\n connection,\n connectionId: connection.id,\n clientTools: this._lastClientTools,\n body: undefined,\n errorPrefix: \"[Think] Auto-continuation failed:\",\n prerequisite: null\n };\n return;\n }\n\n if (this._continuation.pending) {\n this._continuation.pending.connection = connection;\n this._continuation.pending.connectionId = connection.id;\n this._continuation.pending.clientTools = this._lastClientTools;\n this._continuation.awaitingConnections.set(connection.id, connection);\n this._resetAutoContinuationTimer();\n return;\n }\n\n this._continuation.pending = {\n connection,\n connectionId: connection.id,\n requestId: crypto.randomUUID(),\n clientTools: this._lastClientTools,\n body: undefined,\n errorPrefix: \"[Think] Auto-continuation failed:\",\n prerequisite: null,\n pastCoalesce: false\n };\n this._continuation.awaitingConnections.set(connection.id, connection);\n this._resetAutoContinuationTimer();\n }\n\n /**\n * Re-arm the barrier for a tool result/approval that arrived WITHOUT\n * `autoContinue` (#1650). The client sends `autoContinue: false` for an\n * errored tool result (it declines to auto-continue a standalone error), but\n * in a parallel batch a SIBLING may already have requested continuation — and\n * this result can be the one that completes the batch. In that case we must\n * re-run the barrier check so the continuation the sibling requested still\n * fires once the batch is whole.\n *\n * Unlike `_scheduleAutoContinuation` this never CREATES a pending\n * continuation: a standalone errored tool (no opted-in sibling, so no pending)\n * must not auto-continue. It also no-ops once the continuation is running\n * (`pastCoalesce`) — a late result then defers/applies through the normal\n * path rather than re-arming.\n */\n private _rearmPendingAutoContinuationForBatch(): void {\n const pending = this._continuation.pending;\n if (!pending || pending.pastCoalesce) return;\n this._resetAutoContinuationTimer();\n }\n\n /**\n * Called when a streaming assistant turn finalizes (its message, with ALL\n * tool parts, is now persisted). Clears the in-flight accumulator and re-runs\n * the auto-continuation barrier for a continuation the stream-active gate held\n * (#1650). This is essential for an all-fast parallel batch whose every result\n * landed mid-stream: once the stream ends there is no further tool-result\n * event to re-arm the barrier, so without this re-check the held continuation\n * would never fire. A slow batch is also re-checked here and simply continues\n * to hold (event-driven) until its remaining siblings answer.\n */\n private _onStreamingTurnFinalized(): void {\n this._streamingAssistant = null;\n this._rearmPendingAutoContinuationForBatch();\n }\n\n private _resetAutoContinuationTimer(): void {\n if (this._continuationTimer) {\n clearTimeout(this._continuationTimer);\n }\n this._continuationTimer = setTimeout(() => {\n this._continuationTimer = null;\n const pending = this._continuation.pending;\n if (!pending) return;\n this._fireAutoContinuationWhenStable(pending.connection);\n }, 50);\n }\n\n /**\n * Fire an auto-continuation, but only once the model's parallel tool-call\n * batch is fully answered (#1649). When the model emits several tool calls in\n * one step the client answers each independently, so the first `autoContinue`\n * arrives while slower siblings are still `input-available`. Continuing then\n * would feed the provider an incomplete tool-result set\n * (`MissingToolResultsError`) or, via the transcript-repair backstop, silently\n * error the in-flight sibling and run a spurious extra continuation.\n *\n * The barrier is event-driven (#1650). Auto-continuation is only ever\n * triggered by a tool-result/approval event, so rather than wait on a fixed\n * timer we drain the in-flight applies, re-check, and — if the batch is still\n * incomplete — return WITHOUT firing and WITHOUT holding the isolate, leaving\n * `_continuation.pending` in place. The next sibling's result re-arms the\n * coalesce timer (`_scheduleAutoContinuation`) and re-runs this check; the\n * continuation fires once the final sibling lands. If the in-memory pending\n * state is lost to eviction between siblings, the final result re-creates it\n * from the persisted transcript and fires with a complete batch — self-healing.\n * A true orphan (a sibling that never arrives) simply never auto-continues,\n * which is correct: there is nothing valid to continue, and a later user turn\n * / chat recovery repairs the transcript.\n *\n * The barrier also holds while the assistant turn is still streaming (the\n * stream-active gate below): mid-stream the batch can still grow with tool\n * calls the model hasn't emitted yet, so no completeness check is meaningful.\n * `_onStreamingTurnFinalized` re-runs the check once the stream ends.\n */\n private _fireAutoContinuationWhenStable(connection: Connection): void {\n if (!this._continuation.pending) return;\n // The continuation is already running (a sibling result re-armed the timer\n // after it started). New results coalesce/defer into it — don't double-fire.\n if (this._continuation.pending.pastCoalesce) return;\n // A drain is already in progress; the sibling that re-armed the timer is\n // absorbed by it. Only one drain must run, and it re-checks on completion.\n if (this._continuationBarrierActive) return;\n // Stream-active gate (#1650, #1649). While the model is still streaming the\n // assistant turn we CANNOT know the parallel tool batch is complete: the\n // model emits tool calls sequentially, so a fast client tool can resolve\n // before its slower siblings have even been streamed. At that point the\n // siblings exist nowhere — not in `this.messages`, not in the in-flight\n // `_streamingAssistant` accumulator — so no batch check can see them, and\n // firing now would enqueue a continuation that repairs the (later\n // materialized, still-pending) siblings to errored. The only signal that\n // \"more tool calls may still arrive\" is that the stream is open, so we hold\n // without firing. `_onStreamingTurnFinalized` re-runs this check once the\n // stream ends and the batch is fully materialized, and any later sibling\n // result re-arms it via `_scheduleAutoContinuation`.\n if (this._streamingAssistant) return;\n // Fast path: no apply in flight and the leaf step is not mid-batch.\n if (!this._pendingInteractionPromise && !this._hasIncompleteToolBatch()) {\n this._fireAutoContinuation(connection);\n return;\n }\n this._continuationBarrierActive = true;\n // keepAlive only for the bounded drain — the duration of the applies that\n // have ALREADY arrived, not an open-ended wait for siblings that haven't.\n // The pending-continuation state is in-memory, so we must not hibernate\n // mid-apply; once the drain returns we release and let the isolate idle.\n this.keepAliveWhile(() => this._drainInteractionApplies())\n .catch(() => {})\n .finally(() => {\n // Clear the flag and re-check synchronously — no `await` between here\n // and the fire/return decision, so a sibling-armed coalesce timer (a\n // macrotask) cannot interleave and double-fire. `_fireAutoContinuation`\n // cancels that timer; the incomplete-return path leaves it armed so the\n // sibling that armed it re-runs this check when it fires.\n this._continuationBarrierActive = false;\n const pending = this._continuation.pending;\n if (!pending || pending.pastCoalesce) return;\n // A stream (re)started during the drain — hold; the finalize re-trigger\n // will re-check once the batch is fully materialized.\n if (this._streamingAssistant) return;\n // Still waiting on an unanswered sibling — return without firing. The\n // result that completes the batch re-triggers this check via its own\n // `_scheduleAutoContinuation`; we do not pin the isolate in the interim.\n if (this._hasIncompleteToolBatch()) return;\n this._fireAutoContinuation(pending.connection);\n });\n }\n\n /**\n * Drain every in-flight tool-result/approval apply, including any enqueued\n * while we wait, so the subsequent `_hasIncompleteToolBatch()` re-check sees\n * every result that has ALREADY arrived. Bounded by real apply activity (a\n * storage write each), never by a fixed timer: a batch with no further\n * results drains in the time its pending applies take and then returns. The\n * loop re-reads `_interactionApplyTail` after each await because a sibling can\n * extend the tail mid-drain; we stop once the tail stops advancing.\n */\n private async _drainInteractionApplies(): Promise<void> {\n let tail = this._interactionApplyTail;\n // Bounded: each iteration only continues if a NEW apply was chained during\n // the await, and applies are not self-perpetuating (only an inbound result\n // enqueues one), so the tail necessarily stabilizes.\n for (;;) {\n // The pending continuation was cleared (chat clear / turn reset) — nothing\n // to drain for; bail so the isolate isn't held by a stale drain.\n if (!this._continuation.pending) return;\n try {\n await tail;\n } catch {\n // A rejected apply is irrelevant to completeness — re-read and re-check.\n }\n if (this._interactionApplyTail === tail) return;\n tail = this._interactionApplyTail;\n }\n }\n\n /**\n * `true` when the latest assistant message is mid-batch: it carries at least\n * one settled tool result AND at least one tool call/approval still awaiting a\n * client result. That is the #1649 signature — the model fanned out parallel\n * tool calls and only some have been answered. Scoped to the leaf (the step\n * the continuation answers) so an unrelated dangling tool in an earlier\n * message doesn't block a legitimate follow-up continuation.\n */\n private _hasIncompleteToolBatch(): boolean {\n // Zero-allocation backward scan for the latest assistant message — this\n // runs on every barrier poll tick, and `this.messages` can be large.\n const messages = this.messages;\n let leaf: (typeof messages)[number] | undefined;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i].role === \"assistant\") {\n leaf = messages[i];\n break;\n }\n }\n if (!leaf) return false;\n let hasPending = false;\n let hasSettled = false;\n for (const part of leaf.parts) {\n const record = part as Record<string, unknown>;\n const state = record.state;\n if (state === \"input-available\" || state === \"approval-requested\") {\n hasPending = true;\n } else if (\n typeof record.type === \"string\" &&\n (record.type.startsWith(\"tool-\") || record.type === \"dynamic-tool\") &&\n (state === \"output-available\" ||\n state === \"output-error\" ||\n state === \"output-denied\" ||\n state === \"approval-responded\")\n ) {\n hasSettled = true;\n }\n if (hasPending && hasSettled) return true;\n }\n return false;\n }\n\n private _fireAutoContinuation(connection: Connection): void {\n const pending = this._continuation.pending;\n if (!pending) return;\n\n // Cancel any still-armed coalesce timer so a sibling result that re-armed\n // it during a barrier wait can't fire a duplicate continuation after this\n // one starts (#1649).\n if (this._continuationTimer) {\n clearTimeout(this._continuationTimer);\n this._continuationTimer = null;\n }\n\n const { requestId, clientTools } = pending;\n const abortSignal = this._aborts.getSignal(requestId);\n\n this.keepAliveWhile(async () => {\n await this._turnQueue.enqueue(requestId, async () => {\n if (this._continuation.pending) {\n this._continuation.pending.pastCoalesce = true;\n }\n let streamed = false;\n try {\n const continuationBody = async () => {\n const result = await agentContext.run(\n {\n agent: this,\n connection,\n request: undefined,\n email: undefined\n },\n () =>\n this._runInferenceLoop({\n signal: abortSignal,\n clientTools,\n body: this._lastBody,\n continuation: true\n })\n );\n if (result) {\n await this._streamResult(requestId, result, abortSignal, {\n continuation: true\n });\n streamed = true;\n }\n };\n\n if (this.chatRecovery) {\n await this._runChatRecoveryFiber(requestId, true, continuationBody);\n } else {\n await continuationBody();\n }\n } finally {\n this._aborts.remove(requestId);\n if (!streamed) {\n this._continuation.sendResumeNone();\n }\n this._continuation.clearPending();\n this._activateDeferredContinuation();\n }\n });\n }).catch((error) => {\n console.error(\"[Think] Auto-continuation failed:\", error);\n this._aborts.remove(requestId);\n });\n }\n\n private _activateDeferredContinuation(): void {\n const pending = this._continuation.activateDeferred(() =>\n crypto.randomUUID()\n );\n if (!pending) return;\n\n this._fireAutoContinuationWhenStable(pending.connection);\n }\n\n // ── Response hook ──────────────────────────────────────────────\n\n private async _fireResponseHook(result: ChatResponseResult): Promise<void> {\n // Record the terminal status durably so a client connecting after the turn\n // ended still learns its outcome (see `_buildIdleConnectMessages`).\n await this._recordTerminalChatStatus(\n result.status,\n result.requestId,\n result.error ?? \"The assistant was interrupted.\"\n );\n if (this._insideResponseHook) return;\n this._insideResponseHook = true;\n try {\n await this.onChatResponse(result);\n } catch (err) {\n console.error(\"[Think] onChatResponse error:\", err);\n } finally {\n this._insideResponseHook = false;\n }\n }\n\n /**\n * Persist (on `error`/`interrupted`) or clear (on `completed`/`aborted`) the\n * durable terminal record so it can be replayed to clients on reconnect, and\n * resolve any in-progress \"recovering…\" indicator. A `completed`/`aborted`\n * turn is conveyed by the persisted messages, so the record is cleared; an\n * `error`/`interrupted` turn has no durable trace otherwise, so it is kept\n * until a later turn supersedes it.\n *\n * The storage primitives are shared with `@cloudflare/ai-chat`\n * (`_recordChatTerminal` / `_clearChatTerminal` / `_pendingChatTerminal`).\n */\n private async _recordTerminalChatStatus(\n status: ChatResponseResult[\"status\"] | \"interrupted\",\n requestId: string,\n body: string\n ): Promise<void> {\n if (status === \"error\" || status === \"interrupted\") {\n await this._recordChatTerminal(requestId, body);\n } else {\n await this._clearChatTerminal();\n }\n // Any terminal turn outcome resolves an in-progress recovery (#1620): a\n // recovered turn that completes, errors, or is exhausted must clear the\n // \"recovering…\" indicator so it never spins forever.\n await this._setChatRecovering(false);\n }\n\n /**\n * Persist a durable record of the last terminal turn so a client that\n * (re)connects after the turn ended still learns its outcome (#1645). Kept\n * until a later turn supersedes it (`_clearChatTerminal`); a single record is\n * sufficient because only the most recent terminal is relevant.\n */\n private async _recordChatTerminal(\n requestId: string,\n body: string\n ): Promise<void> {\n await this.ctx.storage.put(CHAT_LAST_TERMINAL_KEY, { requestId, body });\n }\n\n /** Clear the durable terminal record once a later turn supersedes it (#1645). */\n private async _clearChatTerminal(): Promise<void> {\n await this.ctx.storage.delete(CHAT_LAST_TERMINAL_KEY);\n }\n\n private async _pendingChatTerminal(): Promise<{\n requestId: string;\n body: string;\n } | null> {\n return (\n (await this.ctx.storage.get<{ requestId: string; body: string }>(\n CHAT_LAST_TERMINAL_KEY\n )) ?? null\n );\n }\n\n /**\n * Replay a pending terminal outcome (#1645) over the resume handshake so a\n * reconnecting client surfaces it exactly like a live exhaustion. A bare\n * terminal frame sent on connect is dropped by the `useAgentChat` client\n * because it never reaches a transport stream reader; only a frame delivered\n * on a resumed stream becomes `useChat.error` (this is why the terminal is\n * NOT included in `_buildIdleConnectMessages`). So we drive `STREAM_RESUMING`\n * here and send the error frame once the client ACKs (see\n * `_replayTerminalOnAck`). Returns true if a terminal was pending.\n */\n private async _replayTerminalOnResume(\n connection: Connection\n ): Promise<boolean> {\n const pending = await this._pendingChatTerminal();\n if (!pending) return false;\n sendIfOpen(\n connection,\n JSON.stringify({ type: MSG_STREAM_RESUMING, id: pending.requestId })\n );\n return true;\n }\n\n /**\n * Deliver the pending terminal error frame on the resumed stream the client\n * ACKed (#1645). The record is retained (cleared only when a later turn\n * supersedes it) so concurrent reconnects each learn the outcome.\n */\n private async _replayTerminalOnAck(\n connection: Connection,\n requestId: string\n ): Promise<boolean> {\n const pending = await this._pendingChatTerminal();\n if (!pending || pending.requestId !== requestId) return false;\n // Replay any partial content the errored stream produced before the\n // error, so the reconnecting client observes the same sequence a live\n // client did — content chunks, then the terminal error (#1575). If the\n // connection drops mid-replay, skip the terminal frame; the record is\n // retained, so the next reconnect retries the whole sequence.\n if (\n !this._resumableStream.replayErroredChunksByRequestId(\n connection,\n pending.requestId\n )\n ) {\n return true;\n }\n sendIfOpen(\n connection,\n JSON.stringify({\n body: pending.body,\n done: true,\n error: true,\n id: pending.requestId,\n type: MSG_CHAT_RESPONSE\n })\n );\n return true;\n }\n\n /**\n * Set or clear the live \"recovering…\" status for a durable chat turn (#1620).\n * Persists a durable record (replayed on connect via `_buildIdleConnectMessages`)\n * and broadcasts a `MSG_CHAT_RECOVERING` frame — but only on a genuine\n * transition, so a deploy/reconnect storm (which re-detects recovery many\n * times) doesn't spam the wire. Cleared on every terminal outcome so the\n * indicator can't spin forever.\n */\n private async _setChatRecovering(\n active: boolean,\n requestId?: string\n ): Promise<void> {\n const existing = await this.ctx.storage.get<{\n requestId?: string;\n at?: number;\n }>(CHAT_RECOVERING_KEY);\n // A flag older than the TTL is stale: the owning incident was abandoned\n // without ever reaching a terminal (e.g. the DO went idle before recovery\n // could resolve), so its terminal-clear never ran. Treat it as\n // not-recovering so a stuck record can neither pin the indicator \"on\"\n // forever nor suppress a genuinely-new recovering signal.\n const activeExisting =\n existing && Date.now() - (existing.at ?? 0) < CHAT_RECOVERING_FLAG_TTL_MS;\n if (active) {\n if (activeExisting) return; // already recovering — idempotent, no re-broadcast\n await this.ctx.storage.put(CHAT_RECOVERING_KEY, {\n ...(requestId ? { requestId } : {}),\n at: Date.now()\n });\n } else {\n if (!existing) return; // not recovering — nothing to clear\n await this.ctx.storage.delete(CHAT_RECOVERING_KEY);\n requestId = requestId ?? existing.requestId;\n }\n this._broadcastChat({\n type: MSG_CHAT_RECOVERING,\n recovering: active,\n ...(requestId ? { id: requestId } : {})\n });\n }\n\n /**\n * Messages sent to a client on connect when no stream is active: the current\n * transcript, plus a replay of 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\n * (`_replayTerminalOnResume` → ACK → `_replayTerminalOnAck`), the only path\n * that lands on the stream reader.\n */\n private async _buildIdleConnectMessages(): Promise<\n Array<Record<string, unknown>>\n > {\n const messages: Array<Record<string, unknown>> = [\n { type: MSG_CHAT_MESSAGES, messages: this.messages }\n ];\n // Replay an in-progress \"recovering…\" status so a client that connects\n // mid-recovery reads the turn as working rather than frozen (#1620). This\n // is a plain status frame the client handles on connect (unlike a terminal\n // error, which must go through the resume handshake). It's mutually\n // exclusive with a terminal record (any terminal outcome clears recovering).\n // Skip a stale record (older than the flag TTL) so a turn whose recovery\n // was abandoned without a terminal can't show \"recovering…\" forever on\n // reconnect.\n const recovering = await this.ctx.storage.get<{\n requestId?: string;\n at?: number;\n }>(CHAT_RECOVERING_KEY);\n if (\n recovering &&\n Date.now() - (recovering.at ?? 0) < CHAT_RECOVERING_FLAG_TTL_MS\n ) {\n messages.push({\n type: MSG_CHAT_RECOVERING,\n recovering: true,\n ...(recovering.requestId ? { id: recovering.requestId } : {})\n });\n }\n return messages;\n }\n\n // ── Resume helpers ──────────────────────────────────────────────\n\n private _notifyStreamResuming(connection: Connection): void {\n if (!this._resumableStream.hasActiveStream()) return;\n const sent = sendIfOpen(\n connection,\n JSON.stringify({\n type: MSG_STREAM_RESUMING,\n id: this._resumableStream.activeRequestId\n })\n );\n if (sent) {\n this._pendingResumeConnections.add(connection.id);\n }\n }\n\n /**\n * Start a resumable stream and arm buffer cleanup. Wrapper around\n * `ResumableStream.start`: arming on START as well as finish guarantees a\n * stream whose DO is evicted mid-flight and never reaches a finish still gets\n * a future sweep instead of leaking its buffer.\n *\n * When a turn runs inside `runFiber` (durable recovery), the DO already\n * self-heals: `runFiber` holds `keepAlive`, which leaves a durable alarm in\n * storage that survives eviction, fires within ~keepAliveIntervalMs, and runs\n * the fiber-recovery scan — finalizing the stream (which arms cleanup) without\n * any client reconnect. Arming here is the safety net for any non-fiber stream\n * path, where no such alarm exists. The last-activity sweep threshold prevents\n * an actively streaming run from being reclaimed before it goes quiet (#1706).\n */\n protected _startResumableStream(\n requestId: string,\n options?: { messageId?: string }\n ): string {\n const streamId = this._resumableStream.start(requestId, options);\n void this._ensureStreamCleanupScheduled();\n return streamId;\n }\n\n /**\n * Mark a resumable stream completed and arm buffer cleanup. Wrapper around\n * `ResumableStream.complete` so every stream-finish path also schedules the\n * cleanup alarm (#1706).\n */\n protected _completeResumableStream(streamId: string): void {\n this._resumableStream.complete(streamId);\n void this._ensureStreamCleanupScheduled();\n }\n\n /**\n * Mark a resumable stream errored and arm buffer cleanup. Wrapper around\n * `ResumableStream.markError` — see {@link _completeResumableStream}.\n */\n protected _errorResumableStream(streamId: string): void {\n this._resumableStream.markError(streamId);\n void this._ensureStreamCleanupScheduled();\n }\n\n /**\n * Ensure a single cleanup alarm is pending for this DO's resumable-stream\n * buffers. Armed whenever a stream finishes so that idle/one-off chat DOs\n * still reclaim their buffers — the lazy sweep in {@link ResumableStream}\n * only fires when a *subsequent* stream completes, which never happens for a\n * chat that receives a single turn (#1706).\n *\n * `idempotent` dedupes on (callback, payload, owner) so repeated finishes\n * collapse onto one pending alarm rather than stacking.\n */\n protected async _ensureStreamCleanupScheduled({\n idempotent = true\n }: { idempotent?: boolean } = {}): Promise<void> {\n await this.schedule(\n STREAM_CLEANUP_DELAY_SECONDS,\n \"_cleanupStreamBuffers\",\n undefined,\n { idempotent }\n );\n }\n\n /**\n * Alarm callback: sweep aged stream buffers, then re-arm only while rows\n * remain so a fully-swept DO stops waking itself.\n */\n async _cleanupStreamBuffers(): Promise<void> {\n this._resumableStream.cleanup();\n if (this._resumableStream.hasReclaimableStreams()) {\n // Must NOT be idempotent: this runs INSIDE the currently-executing\n // one-shot schedule row, which `alarm()` deletes only after we return. An\n // idempotent reschedule would dedup onto that row and then be deleted with\n // it — the re-arm would silently never fire, leaving buffers that survived\n // this sweep (e.g. a younger turn) uncollected. A fresh delayed row\n // survives the deletion (mirrors the chat-recovery reschedule).\n await this._ensureStreamCleanupScheduled({ idempotent: false });\n }\n }\n\n private async _persistOrphanedStream(streamId: string): Promise<void> {\n this._resumableStream.flushBuffer();\n const chunks = this._resumableStream.getStreamChunks(streamId);\n if (chunks.length === 0) return;\n\n const accumulator = new StreamAccumulator({\n messageId: crypto.randomUUID()\n });\n for (const chunk of chunks) {\n try {\n accumulator.applyChunk(JSON.parse(chunk.body) as StreamChunkData);\n } catch {\n // skip malformed chunks\n }\n }\n\n if (accumulator.parts.length > 0) {\n await this._persistAssistantMessage(accumulator.toMessage());\n // NOTE: progress is bumped at production/flush time in `_storeChunkDurably`\n // (#1637), NOT here — persisting on recovery or a client reconnect must\n // not be miscounted as new forward progress.\n this._broadcastMessages();\n }\n }\n\n private _broadcastChat(message: Record<string, unknown>, exclude?: string[]) {\n const allExclusions = [\n ...(exclude || []),\n ...this._pendingResumeConnections\n ];\n this.broadcast(JSON.stringify(message), allExclusions);\n }\n\n private _broadcast(message: Record<string, unknown>, exclude?: string[]) {\n this.broadcast(JSON.stringify(message), exclude);\n }\n\n private _broadcastMessages(exclude?: string[]) {\n this._broadcast(\n { type: MSG_CHAT_MESSAGES, messages: this.messages },\n exclude\n );\n }\n}\n\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.approveExecution,\n Think.prototype.rejectExecution\n]) {\n callable()(method, undefined as unknown as ClassMethodDecoratorContext);\n}\n"],"mappings":";;;;;;;;;;;;;AAgEA,SAAgB,2BACd,QACoC;CACpC,IAAI,WAAW,OAAO,OAAO;CAC7B,MAAM,OAAO,WAAW,OAAO,CAAC,IAAI;CACpC,OAAO;EACL,oBAAoB,KAAK,sBAAsB;EAC/C,cAAc,KAAK,gBAAgB,KAAK;EACxC,wBAAwB,KAAK,0BAA0B;EACvD,gBAAgB,KAAK,kBAAkB;CACzC;AACF;AA4BA,MAAM,iBAAiB;;;;;AAMvB,SAAgB,2BACd,SACA,SACoB;CACpB,MAAM,QAAQ;EACZ;EACA,OAAO;EACP,OAAO;EACP,OAAO,CAAC;CACV;CAEA,IAAI,UAAU;CACd,MAAM,QAAQ,QAAQ,MAAM,KAAK,SAAS;EAExC,IAAI,KAAK,SAAS,UAAU,SAAS,MAAM;GACzC,MAAM,MAAO,KAAyB;GACtC,IACE,OAAO,QAAQ,YACf,IAAI,WAAW,OAAO,KACtB,IAAI,UAAU,QAAQ,cACtB;IACA,UAAU;IACV,MAAM,YACH,KAAgC,aAAa,i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