agents 0.27.0 → 0.28.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 (216) hide show
  1. package/dist/abortable-C1SpfVoi.js +21 -0
  2. package/dist/abortable-C1SpfVoi.js.map +1 -0
  3. package/dist/{agent-routing-Bhdbvf7s.d.ts → agent-routing-BMvWTFEp.d.ts} +21 -15
  4. package/dist/agent-routing.d.ts +1 -1
  5. package/dist/agent-tool-types.d.ts +1 -1
  6. package/dist/{agent-tools-bJZwBMfq.d.ts → agent-tools-ohoewW-B.d.ts} +2 -2
  7. package/dist/agent-tools.d.ts +1 -1
  8. package/dist/ai-ahruGw7e.d.ts +239 -0
  9. package/dist/{ai-sdk-OoGkFy3s.js → ai-sdk-C2iTAwUd.js} +44 -18
  10. package/dist/ai-sdk-C2iTAwUd.js.map +1 -0
  11. package/dist/browser/ai.d.ts +8 -227
  12. package/dist/browser/ai.js +259 -1
  13. package/dist/browser/ai.js.map +1 -0
  14. package/dist/browser/index.d.ts +56 -46
  15. package/dist/browser/index.js +4 -361
  16. package/dist/browser/{ai-sdk.d.ts → tools/ai-sdk.d.ts} +7 -7
  17. package/dist/browser/{ai-sdk.js → tools/ai-sdk.js} +5 -4
  18. package/dist/browser/tools/ai-sdk.js.map +1 -0
  19. package/dist/browser/tools/pi.d.ts +111 -0
  20. package/dist/browser/tools/pi.js +119 -0
  21. package/dist/browser/tools/pi.js.map +1 -0
  22. package/dist/browser/{tanstack-ai.d.ts → tools/tanstack-ai.d.ts} +39 -37
  23. package/dist/browser/{tanstack-ai.js → tools/tanstack-ai.js} +73 -59
  24. package/dist/browser/tools/tanstack-ai.js.map +1 -0
  25. package/dist/browser-CEdNlsaD.js +481 -0
  26. package/dist/browser-CEdNlsaD.js.map +1 -0
  27. package/dist/{browser-tmkcAAI3.d.ts → browser-D30VlpcA.d.ts} +63 -37
  28. package/dist/{browser-tool-CBqs6hqa.js → browser-tool-4iomavs_.js} +145 -49
  29. package/dist/browser-tool-4iomavs_.js.map +1 -0
  30. package/dist/{browser-tool-Bn-nzJQI.d.ts → browser-tool-vtrPOV8e.d.ts} +24 -5
  31. package/dist/{capability-B4WbF81e.js → capability-DBAKc6UZ.js} +1 -3
  32. package/dist/capability-DBAKc6UZ.js.map +1 -0
  33. package/dist/{capability-runner-O5VbQzqg.d.ts → capability-runner-BiVUtjqC.d.ts} +1 -7
  34. package/dist/chat/index.d.ts +4 -4
  35. package/dist/chat/index.js +1 -1
  36. package/dist/chat-sdk/index.d.ts +1 -1
  37. package/dist/chat-sdk/index.js +1 -1
  38. package/dist/{client-1tEQ1Oqz.js → client-BnYbNT3z.js} +3 -4
  39. package/dist/client-BnYbNT3z.js.map +1 -0
  40. package/dist/{client-DS3Dz9l0.d.ts → client-Bp-JwL3p.d.ts} +2 -2
  41. package/dist/client.d.ts +1 -1
  42. package/dist/{connector-58XDGvc3.js → connector-CtZylXdk.js} +3 -603
  43. package/dist/connector-CtZylXdk.js.map +1 -0
  44. package/dist/{connector-Cl-VqPmA.d.ts → connector-DEXzVoaY.d.ts} +9 -374
  45. package/dist/{conversations-DH0ut_8n.d.ts → conversations-FjHDRZyD.d.ts} +4 -4
  46. package/dist/{current-agent-C07C5o5Y.d.ts → current-agent-CKgT5d1O.d.ts} +3 -5
  47. package/dist/current-agent-DhoDkSnH.js.map +1 -1
  48. package/dist/{durable-object-lifecycle-DRqp475_.d.ts → durable-object-lifecycle-DOI_bzCH.d.ts} +2 -2
  49. package/dist/experimental/channels/index.d.ts +2 -2
  50. package/dist/experimental/channels/index.js +2 -2
  51. package/dist/experimental/channels/web/index.d.ts +2 -2
  52. package/dist/experimental/channels/web/index.js +1 -1
  53. package/dist/{gateway-BDC07gYO.d.ts → gateway-BFO6vRDn.d.ts} +2 -2
  54. package/dist/{handler-stateless-VvrWSAVA.js → handler-stateless-Bly_nSH3.js} +12 -3
  55. package/dist/handler-stateless-Bly_nSH3.js.map +1 -0
  56. package/dist/harness/ai-sdk/index.d.ts +2 -2
  57. package/dist/harness/ai-sdk/index.js +1 -1
  58. package/dist/harness/container/index.d.ts +2 -2
  59. package/dist/harness/container/index.js +3 -3
  60. package/dist/harness/opencode/index.d.ts +183 -7
  61. package/dist/harness/opencode/index.js +355 -24
  62. package/dist/harness/opencode/index.js.map +1 -1
  63. package/dist/harness/pi/index.d.ts +2 -2
  64. package/dist/harness/pi/index.js +3 -3
  65. package/dist/harness/store/index.d.ts +1 -1
  66. package/dist/harness/store/index.js +1 -1
  67. package/dist/harness/think/index.d.ts +2 -2
  68. package/dist/harness/think/index.js +363 -171
  69. package/dist/harness/think/index.js.map +1 -1
  70. package/dist/{images-Ce9SCu3X.js → images-C4hiIexM.js} +46 -4
  71. package/dist/images-C4hiIexM.js.map +1 -0
  72. package/dist/{index-D0A5tbWu.d.ts → index-BEL3ZV-s.d.ts} +2 -6
  73. package/dist/{index-Ib_4dwOo.d.ts → index-CBt8oRJt.d.ts} +3 -5
  74. package/dist/index.d.ts +4 -4
  75. package/dist/index.js +2 -2
  76. package/dist/input-schema-BQykTEp_.js +20 -0
  77. package/dist/input-schema-BQykTEp_.js.map +1 -0
  78. package/dist/{input-schema-DNrpTu49.js → input-schema-xBofjBKC.js} +3 -3
  79. package/dist/input-schema-xBofjBKC.js.map +1 -0
  80. package/dist/internal_context.d.ts +1 -1
  81. package/dist/lifecycle/index.d.ts +3 -3
  82. package/dist/lifecycle/index.js +2 -2
  83. package/dist/{lifecycle-CFu6OV03.js → lifecycle-DGorpAmA.js} +2 -4
  84. package/dist/lifecycle-DGorpAmA.js.map +1 -0
  85. package/dist/mcp/client/index.d.ts +1 -1
  86. package/dist/mcp/client/index.js +1 -1
  87. package/dist/mcp/index.d.ts +1 -1
  88. package/dist/mcp/index.js +18 -4
  89. package/dist/mcp/index.js.map +1 -1
  90. package/dist/mcp/server/index.js +1 -1
  91. package/dist/models/ai-sdk/index.d.ts +45 -17
  92. package/dist/models/ai-sdk/index.js +1 -1
  93. package/dist/models/opencode/index.d.ts +2 -2
  94. package/dist/models/opencode/index.js +1 -1
  95. package/dist/models/pi-ai/index.d.ts +8 -3
  96. package/dist/models/pi-ai/index.js +6 -6
  97. package/dist/models/pi-ai/index.js.map +1 -1
  98. package/dist/{options-pwTNq9z6.d.ts → options-CiIsJHXR.d.ts} +2 -6
  99. package/dist/queue/index.d.ts +1 -1
  100. package/dist/queue/index.js +1 -1
  101. package/dist/{queue-BB-zfIYF.js → queue-CcIjVYTE.js} +2 -2
  102. package/dist/{queue-BB-zfIYF.js.map → queue-CcIjVYTE.js.map} +1 -1
  103. package/dist/react.d.ts +2 -2
  104. package/dist/routing/index.d.ts +2 -2
  105. package/dist/routing/index.js +1 -1
  106. package/dist/{scheduler-CrFCnv_J.d.ts → scheduler-BCLESHSC.d.ts} +2 -12
  107. package/dist/{scheduler-DZ3xQfeK.js → scheduler-FIHv2-kJ.js} +2 -4
  108. package/dist/scheduler-FIHv2-kJ.js.map +1 -0
  109. package/dist/schedules/index.d.ts +1 -1
  110. package/dist/schedules/index.js +1 -1
  111. package/dist/serializable.d.ts +1 -1
  112. package/dist/session-store-Do4xkDcf.js +606 -0
  113. package/dist/session-store-Do4xkDcf.js.map +1 -0
  114. package/dist/session-store-DoPY12xM.d.ts +383 -0
  115. package/dist/sessions/index.d.ts +1 -1
  116. package/dist/sessions/index.js +1 -1
  117. package/dist/{sessions-B9pNuxdT.js → sessions-_vN5BEZX.js} +2 -2
  118. package/dist/{sessions-B9pNuxdT.js.map → sessions-_vN5BEZX.js.map} +1 -1
  119. package/dist/{settings-C45hDliX.js → settings-BjAiPd6Z.js} +7 -4
  120. package/dist/settings-BjAiPd6Z.js.map +1 -0
  121. package/dist/{settings-NgGwF7Qt.d.ts → settings-DnD__xuE.d.ts} +22 -4
  122. package/dist/{src-DgCbZtIR.js → src-CQxJFv4l.js} +8 -8
  123. package/dist/src-CQxJFv4l.js.map +1 -0
  124. package/dist/state/index.d.ts +1 -1
  125. package/dist/state/index.js +1 -3
  126. package/dist/state/index.js.map +1 -1
  127. package/dist/{store-DLeqKuj3.d.ts → store-BKM4Xm9M.d.ts} +23 -1
  128. package/dist/{store-vgcPYo8K.js → store-CslVzfN7.js} +28 -2
  129. package/dist/store-CslVzfN7.js.map +1 -0
  130. package/dist/streams/index.d.ts +1 -1
  131. package/dist/streams/index.js +1 -1
  132. package/dist/{streams-CITClVer.js → streams-lsHMJhRW.js} +2 -2
  133. package/dist/{streams-CITClVer.js.map → streams-lsHMJhRW.js.map} +1 -1
  134. package/dist/{streams-fbG61qM8.d.ts → streams-vrCtbUIn.d.ts} +2 -2
  135. package/dist/sub-routing.d.ts +1 -1
  136. package/dist/tasks/index.d.ts +1 -1
  137. package/dist/tasks/index.js +1 -1
  138. package/dist/{tasks-CkTZNaV1.js → tasks-BN_5AWqI.js} +2 -2
  139. package/dist/{tasks-CkTZNaV1.js.map → tasks-BN_5AWqI.js.map} +1 -1
  140. package/dist/{tasks-PtlB4Uyn.d.ts → tasks-E89KdwkS.d.ts} +2 -2
  141. package/dist/{tool-BPJEbwaX.d.ts → tool-CTp72Jb_.d.ts} +4 -4
  142. package/dist/tool-CxKsvxjm.js +1126 -0
  143. package/dist/tool-CxKsvxjm.js.map +1 -0
  144. package/dist/tool-DoVberpN.d.ts +301 -0
  145. package/dist/{tool-3PA8xjB_.js → tool-VF0qiO7q.js} +7 -18
  146. package/dist/tool-VF0qiO7q.js.map +1 -0
  147. package/dist/tool-helpers-O5BDVEAY.js +58 -0
  148. package/dist/tool-helpers-O5BDVEAY.js.map +1 -0
  149. package/dist/{transport-k2mFrtL8.d.ts → transport-DCyarnwm.d.ts} +2 -2
  150. package/dist/voice/index.d.ts +2 -2
  151. package/dist/web/fetch/index.d.ts +89 -0
  152. package/dist/web/fetch/index.js +20 -0
  153. package/dist/web/fetch/index.js.map +1 -0
  154. package/dist/web/fetch/tools/ai-sdk.d.ts +80 -0
  155. package/dist/web/fetch/tools/ai-sdk.js +47 -0
  156. package/dist/web/fetch/tools/ai-sdk.js.map +1 -0
  157. package/dist/web/fetch/tools/pi.d.ts +84 -0
  158. package/dist/web/fetch/tools/pi.js +88 -0
  159. package/dist/web/fetch/tools/pi.js.map +1 -0
  160. package/dist/web/fetch/tools/tanstack-ai.d.ts +78 -0
  161. package/dist/web/fetch/tools/tanstack-ai.js +45 -0
  162. package/dist/web/fetch/tools/tanstack-ai.js.map +1 -0
  163. package/dist/{websearch → web/search}/index.d.ts +1 -1
  164. package/dist/{websearch → web/search}/index.js +1 -1
  165. package/dist/{websearch → web/search}/tools/ai-sdk.d.ts +2 -2
  166. package/dist/{websearch → web/search}/tools/ai-sdk.js +3 -3
  167. package/dist/web/search/tools/ai-sdk.js.map +1 -0
  168. package/dist/{websearch → web/search}/tools/pi.d.ts +3 -3
  169. package/dist/{websearch → web/search}/tools/pi.js +2 -2
  170. package/dist/web/search/tools/pi.js.map +1 -0
  171. package/dist/{websearch → web/search}/tools/tanstack-ai.d.ts +2 -2
  172. package/dist/{websearch → web/search}/tools/tanstack-ai.js +3 -3
  173. package/dist/web/search/tools/tanstack-ai.js.map +1 -0
  174. package/dist/websockets/index.d.ts +2 -2
  175. package/dist/websockets/index.js +1 -1
  176. package/dist/{websockets-CmENGb-Z.js → websockets-C3zy8YR0.js} +3 -5
  177. package/dist/websockets-C3zy8YR0.js.map +1 -0
  178. package/dist/workflow-types.d.ts +1 -1
  179. package/dist/workflows.d.ts +1 -1
  180. package/dist/workflows.js +1 -1
  181. package/docs/browse-the-web.md +26 -1
  182. package/docs/fetch-the-web.md +276 -0
  183. package/docs/harnesses/pi.md +25 -0
  184. package/docs/index.md +99 -76
  185. package/docs/lifecycle.md +2 -3
  186. package/docs/mcp-client.md +1 -1
  187. package/docs/mcp-servers.md +1 -1
  188. package/docs/models-pi-ai.md +11 -0
  189. package/docs/models.md +45 -3
  190. package/docs/queue.md +2 -3
  191. package/docs/scheduling.md +2 -6
  192. package/docs/search-the-web.md +2 -0
  193. package/package.json +52 -27
  194. package/dist/ai-fm7xx1BK.js +0 -312
  195. package/dist/ai-fm7xx1BK.js.map +0 -1
  196. package/dist/ai-sdk-OoGkFy3s.js.map +0 -1
  197. package/dist/browser/ai-sdk.js.map +0 -1
  198. package/dist/browser/index.js.map +0 -1
  199. package/dist/browser/tanstack-ai.js.map +0 -1
  200. package/dist/browser-tool-CBqs6hqa.js.map +0 -1
  201. package/dist/capability-B4WbF81e.js.map +0 -1
  202. package/dist/client-1tEQ1Oqz.js.map +0 -1
  203. package/dist/connector-58XDGvc3.js.map +0 -1
  204. package/dist/handler-stateless-VvrWSAVA.js.map +0 -1
  205. package/dist/images-Ce9SCu3X.js.map +0 -1
  206. package/dist/input-schema-DNrpTu49.js.map +0 -1
  207. package/dist/lifecycle-CFu6OV03.js.map +0 -1
  208. package/dist/scheduler-DZ3xQfeK.js.map +0 -1
  209. package/dist/settings-C45hDliX.js.map +0 -1
  210. package/dist/src-DgCbZtIR.js.map +0 -1
  211. package/dist/store-vgcPYo8K.js.map +0 -1
  212. package/dist/tool-3PA8xjB_.js.map +0 -1
  213. package/dist/websearch/tools/ai-sdk.js.map +0 -1
  214. package/dist/websearch/tools/pi.js.map +0 -1
  215. package/dist/websearch/tools/tanstack-ai.js.map +0 -1
  216. package/dist/websockets-CmENGb-Z.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"images-Ce9SCu3X.js","names":["isRecord","isRecord","stripEchoSuffix"],"sources":["../src/models/core/errors.ts","../src/models/core/transport.ts","../src/models/core/gateway-providers.ts","../src/models/core/chat-completions/quirks.ts","../src/models/core/chat-completions/request.ts","../src/models/core/chat-completions/response.ts","../src/models/core/chat-completions/stream.ts","../src/models/core/sse.ts","../src/models/core/images.ts"],"sourcesContent":["/**\n * Coarse classification of a failed Cloudflare AI call.\n *\n * @experimental This surface is experimental and may change.\n */\nexport type CloudflareAIErrorCode =\n | \"auth\"\n | \"rate-limit\"\n | \"not-found\"\n | \"bad-request\"\n | \"provider-error\"\n | \"gateway-error\"\n | \"unknown\";\n\n/**\n * One leg of a {@link CloudflareAIError} fallback chain.\n *\n * @experimental This surface is experimental and may change.\n */\nexport interface CloudflareAIAttempt {\n /** The model id that was tried. */\n model: string;\n /** The error that leg failed with. */\n error: unknown;\n}\n\n/**\n * Error thrown for every failed Cloudflare AI call, whether it came back as a\n * non-2xx `Response` or as a thrown Workers AI binding error. Framework\n * modules wrap it into their own error type at their boundary (the AI SDK\n * module into an `APICallError`, so `ai`'s retry loop honours\n * {@link CloudflareAIError.isRetryable}).\n *\n * @experimental This surface is experimental and may change.\n */\nexport class CloudflareAIError extends Error {\n /** HTTP status, when the failure carried one. */\n readonly status: number | undefined;\n /** Coarse classification used for routing and fallback decisions. */\n readonly code: CloudflareAIErrorCode;\n /** `cf-aig-log-id` of the failed request, when the response carried one. */\n readonly logId: string | undefined;\n /** The model id that produced this error. */\n readonly model: string;\n /** Which binding path the request went down, for error reporting. */\n readonly url: string;\n /** The request body that failed. */\n readonly requestBodyValues: unknown;\n /** Response headers, when there was a response. */\n readonly responseHeaders: Record<string, string> | undefined;\n /** Raw response body text, when there was a response. */\n readonly responseBody: string | undefined;\n /** Whether a retry is worth attempting. */\n readonly isRetryable: boolean;\n /** Parsed error envelope, or other structured detail. */\n readonly data: unknown;\n /** Every leg tried, when this error ends a fallback chain. */\n readonly attempts: CloudflareAIAttempt[] | undefined;\n override readonly cause: unknown;\n\n constructor(options: {\n message: string;\n model: string;\n url: string;\n requestBodyValues: unknown;\n status?: number;\n code: CloudflareAIErrorCode;\n logId?: string;\n responseHeaders?: Record<string, string>;\n responseBody?: string;\n isRetryable?: boolean;\n data?: unknown;\n cause?: unknown;\n attempts?: CloudflareAIAttempt[];\n }) {\n super(options.message);\n this.name = \"CloudflareAIError\";\n this.status = options.status;\n this.code = options.code;\n this.logId = options.logId;\n this.model = options.model;\n this.url = options.url;\n this.requestBodyValues = options.requestBodyValues;\n this.responseHeaders = options.responseHeaders;\n this.responseBody = options.responseBody;\n this.isRetryable = options.isRetryable ?? isRetryableStatus(options.status);\n this.data = options.data;\n this.cause = options.cause;\n this.attempts = options.attempts;\n }\n}\n\n/**\n * Whether a status is worth retrying. Missing status means a transport-level\n * failure (connection reset, DNS, abort-adjacent), which is retryable.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function isRetryableStatus(status: number | undefined): boolean {\n if (status === undefined) return true;\n return status === 408 || status === 409 || status === 429 || status >= 500;\n}\n\n/**\n * Classifies an HTTP status into a {@link CloudflareAIErrorCode}. The\n * `AiGatewayError` envelope name catches gateway-level statuses that are not\n * otherwise meaningful (notably 402 \"insufficient balance\").\n */\nexport function classifyStatus(\n status: number | undefined,\n envelopeName?: string\n): CloudflareAIErrorCode {\n if (status === 401 || status === 403) return \"auth\";\n if (status === 429) return \"rate-limit\";\n if (status === 404) return \"not-found\";\n if (status === 400 || status === 422) return \"bad-request\";\n if (status !== undefined && status >= 500) return \"provider-error\";\n if (envelopeName === \"AiGatewayError\") return \"gateway-error\";\n return \"unknown\";\n}\n\n/**\n * Workers AI binding error codes that map onto an HTTP status.\n *\n * @see https://developers.cloudflare.com/workers-ai/platform/errors/\n */\nconst BINDING_CODE_STATUS: Record<number, number> = {\n 3003: 400,\n 3006: 413,\n 3007: 408,\n 3008: 408,\n 3023: 403,\n 3036: 429,\n 3039: 400,\n 3040: 429,\n 3041: 403,\n 3042: 404,\n 5004: 400,\n 5005: 405,\n 5007: 400,\n 5016: 403,\n 5018: 403,\n 5019: 405\n};\n\n/** Abort-shaped errors must propagate untouched so callers can detect them. */\nexport function isAbortError(error: unknown): boolean {\n const name =\n error instanceof Error || error instanceof DOMException\n ? error.name\n : undefined;\n return (\n name === \"AbortError\" ||\n name === \"ResponseAborted\" ||\n name === \"TimeoutError\"\n );\n}\n\nfunction messageOf(error: unknown): string {\n if (typeof error === \"string\") return error;\n if (error instanceof Error) return error.message;\n if (error !== null && typeof error === \"object\" && \"message\" in error) {\n const message = (error as { message: unknown }).message;\n if (typeof message === \"string\") return message;\n }\n return String(error);\n}\n\n/**\n * Extracts a Workers AI internal error code from a thrown binding error. The\n * binding reports codes inside the message text (`\"3040: Capacity temporarily\n * exceeded\"`) rather than as a status, so only known codes are accepted — an\n * unrelated leading number must not be misread as a code.\n */\nfunction bindingErrorCode(error: unknown): number | undefined {\n if (error !== null && typeof error === \"object\" && \"code\" in error) {\n const code = (error as { code: unknown }).code;\n if (typeof code === \"number\" && code in BINDING_CODE_STATUS) return code;\n }\n const matches = messageOf(error).matchAll(/\\b(\\d{3,5})\\s*:/g);\n for (const match of matches) {\n const code = Number(match[1]);\n if (code in BINDING_CODE_STATUS) return code;\n }\n return undefined;\n}\n\n/**\n * Normalizes a thrown Workers AI binding error into a {@link CloudflareAIError}.\n * Abort errors and errors that are already {@link CloudflareAIError}s pass through.\n */\nexport function normalizeThrownError(\n error: unknown,\n context: {\n model: string;\n url: string;\n requestBodyValues: unknown;\n }\n): unknown {\n if (isAbortError(error)) return error;\n if (error instanceof CloudflareAIError) return error;\n\n const code = bindingErrorCode(error);\n const status = code === undefined ? undefined : BINDING_CODE_STATUS[code];\n return new CloudflareAIError({\n cause: error,\n code: classifyStatus(status),\n data: code === undefined ? undefined : { code },\n // A recognised code decides for itself. Everything else is not worth\n // retrying: the binding is the only backend, so a throw with no status is\n // a programming error rather than a transport failure, and re-running it\n // on every fallback leg helps nobody.\n isRetryable: status === undefined ? false : isRetryableStatus(status),\n message: messageOf(error),\n model: context.model,\n requestBodyValues: context.requestBodyValues,\n status,\n url: context.url\n });\n}\n","import {\n CloudflareAIError,\n classifyStatus,\n normalizeThrownError\n} from \"./errors\";\nimport type { GatewayProviderName } from \"./gateway-providers\";\nimport type { AISettings, ResolvedGateway } from \"./settings\";\n\n/** The reported `url` for a universal call made through the binding. */\nconst UNIVERSAL_BINDING_URL = \"ai-gateway-binding\";\n\n/** One request on the Cloudflare run path. */\nexport interface TransportRequest {\n /** Model id — Workers AI slug or catalog `<author>/<model>`. */\n model: string;\n /** The provider-shaped request body (`input` on the run path). */\n input: Record<string, unknown>;\n /** Gateway options for this request. */\n gateway: ResolvedGateway;\n /** Extra request headers, merged last. */\n headers: Record<string, string>;\n /** Abort signal, forwarded to the binding or to `fetch`. */\n signal?: AbortSignal;\n}\n\n/**\n * One request on the universal AI Gateway path: a vendor's own request, routed\n * by the gateway to that vendor. The body is the vendor's, untouched — nothing\n * here knows the vendor's wire format.\n *\n * @experimental This surface is experimental and may change.\n */\nexport interface UniversalRequest {\n /** The gateway provider slug the request is routed to. */\n provider: GatewayProviderName | string;\n /** The vendor path the gateway appends to that provider's base URL. */\n endpoint: string;\n /** The vendor's own request headers, minus its credential header. */\n headers: Record<string, string>;\n /** The vendor's request body, verbatim. */\n query: unknown;\n /** Gateway options for this request. */\n gateway: ResolvedGateway;\n /** Extra headers merged last, outside the vendor's own set. */\n extraHeaders?: Record<string, string>;\n /** Abort signal, forwarded to the binding or to `fetch`. */\n signal?: AbortSignal;\n}\n\n/**\n * The single code path both backends implement. Always resolves to a raw\n * `Response`, so streaming and non-streaming calls share one path and nothing\n * is buffered on the caller's behalf.\n *\n * @experimental This surface is experimental and may change.\n */\nexport interface Transport {\n /** A stable identifier for the endpoint, used in error reporting. */\n readonly url: string;\n run(request: TransportRequest): Promise<Response>;\n /**\n * Sends a vendor's own request through the gateway's universal endpoint.\n * Always resolves to the vendor's raw `Response`, error responses included:\n * only the gateway's own failures (a missing gateway, an unpaid account) are\n * lifted into a {@link CloudflareAIError}, because the vendor's provider\n * knows how to read its own errors and we do not.\n */\n universal(request: UniversalRequest): Promise<Response>;\n /**\n * A log id read off the backend itself when the response carried none. The\n * Workers AI binding exposes the last gateway log id as a mutable property,\n * so it is captured per response rather than read late.\n */\n logIdFallback(response: Response): string | undefined;\n}\n\n/**\n * Drops entries whose value is `undefined`. The AI SDK types call headers as\n * `Record<string, string | undefined>`, and an undefined value reaches the\n * binding as the string \"undefined\" rather than as an absent header.\n */\nexport function definedHeaders(\n headers: Record<string, string | undefined> | undefined\n): Record<string, string> {\n const result: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers ?? {})) {\n if (value !== undefined) result[key] = value;\n }\n return result;\n}\n\n/** Copies response headers into a plain object. */\nexport function headersToObject(headers: Headers): Record<string, string> {\n const result: Record<string, string> = {};\n headers.forEach((value, key) => {\n result[key] = value;\n });\n return result;\n}\n\n/**\n * Some run-path responses arrive bare and some wrapped in the Cloudflare API\n * envelope. Unwrap only when the envelope keys are actually present, so a\n * provider payload that happens to have a `result` field is left alone.\n */\nexport function unwrapEnvelope(\n value: unknown,\n context?: { model: string; url: string; status: number }\n): unknown {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n return value;\n }\n const record = value as Record<string, unknown>;\n // A failure envelope may carry no `result` at all, only its errors.\n const failed =\n record.success === false && firstEnvelopeError(record) !== undefined;\n if (failed || (\"success\" in record && \"result\" in record)) {\n if (record.success === true) return record.result;\n // A failure envelope can arrive with a 2xx status. Parsing it as a\n // provider payload would produce an empty result and no diagnostic.\n throw new CloudflareAIError({\n code: classifyStatus(\n context?.status,\n typeof record.name === \"string\" ? record.name : undefined\n ),\n data: value,\n message: errorMessageFrom(value, context?.status),\n model: context?.model ?? \"\",\n requestBodyValues: undefined,\n status: context?.status,\n url: context?.url ?? \"\"\n });\n }\n return value;\n}\n\nfunction firstEnvelopeError(\n record: Record<string, unknown>\n): { code?: unknown; message?: unknown } | undefined {\n // Live gateway responses use `error` (an array of one); the documented\n // Cloudflare envelope uses `errors`. Accept either.\n for (const key of [\"error\", \"errors\"]) {\n const value = record[key];\n if (Array.isArray(value) && value.length > 0) {\n const first = value[0];\n if (first !== null && typeof first === \"object\") {\n return first as { code?: unknown; message?: unknown };\n }\n }\n if (value !== null && typeof value === \"object\" && !Array.isArray(value)) {\n return value as { code?: unknown; message?: unknown };\n }\n }\n return undefined;\n}\n\n/**\n * Pulls a human message out of any of the error envelopes the platform emits:\n * the gateway envelope (`error: [{ code, message }]`), the Workers AI\n * validation envelope (`message`/`description` only), a bare\n * `{ error: \"...\" }`, and the \"Model ID missing\" internal error, which carries\n * only `description`.\n */\nexport function errorMessageFrom(\n body: unknown,\n status: number | undefined\n): string {\n const record =\n body !== null && typeof body === \"object\" && !Array.isArray(body)\n ? (body as Record<string, unknown>)\n : undefined;\n if (record !== undefined) {\n const envelope = firstEnvelopeError(record);\n if (typeof envelope?.message === \"string\") return envelope.message;\n if (typeof record.error === \"string\") return record.error;\n if (typeof record.message === \"string\") return record.message;\n if (typeof record.description === \"string\") return record.description;\n }\n if (typeof body === \"string\" && body !== \"\") return body;\n return `HTTP ${status ?? \"error\"}`;\n}\n\n/** Builds a {@link CloudflareAIError} from a non-2xx run-path response. */\nexport async function errorFromResponse(\n response: Response,\n context: { model: string; url: string; requestBodyValues: unknown }\n): Promise<CloudflareAIError> {\n const text = await response.text().catch(() => \"\");\n let body: unknown = text;\n try {\n body = text === \"\" ? undefined : JSON.parse(text);\n } catch {\n // Not JSON — the raw text is the best message we have.\n }\n const record =\n body !== null && typeof body === \"object\" && !Array.isArray(body)\n ? (body as Record<string, unknown>)\n : undefined;\n const envelopeName =\n typeof record?.name === \"string\" ? record.name : undefined;\n const headers = headersToObject(response.headers);\n return new CloudflareAIError({\n code: classifyStatus(response.status, envelopeName),\n data: body,\n logId: headers[\"cf-aig-log-id\"],\n message: errorMessageFrom(body, response.status),\n model: context.model,\n requestBodyValues: context.requestBodyValues,\n responseBody: text,\n responseHeaders: headers,\n status: response.status,\n url: context.url\n });\n}\n\n/**\n * The gateway's own options for the universal call. The id is not among them:\n * it selects the gateway (`env.AI.gateway(id)`), and the binding's own `id`\n * field is deprecated.\n */\nfunction universalGatewayOptions(\n gateway: ResolvedGateway\n): UniversalGatewayOptions {\n // `id` is deprecated on this type but still required by it; the gateway is\n // already selected by `env.AI.gateway(id)`, so it repeats that id.\n const options: UniversalGatewayOptions = { id: gateway.id };\n if (gateway.skipCache !== undefined) options.skipCache = gateway.skipCache;\n if (gateway.cacheTtl !== undefined) options.cacheTtl = gateway.cacheTtl;\n if (gateway.cacheKey !== undefined) options.cacheKey = gateway.cacheKey;\n if (gateway.metadata !== undefined) options.metadata = gateway.metadata;\n if (gateway.collectLog !== undefined) options.collectLog = gateway.collectLog;\n if (gateway.eventId !== undefined) options.eventId = gateway.eventId;\n if (gateway.requestTimeoutMs !== undefined) {\n options.requestTimeoutMs = gateway.requestTimeoutMs;\n }\n if (gateway.retries !== undefined) options.retries = gateway.retries;\n return options;\n}\n\n/**\n * Whether a parsed body is the gateway's own error envelope rather than a\n * vendor payload — `{ success: false, error: [{ code, message }] }`, named\n * `AiGatewayError`. The gateway answers this for its own failures (no such\n * gateway, unified billing unpaid, provider not configured); everything else\n * on this path is the vendor's own error, which the vendor's provider reads.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function isGatewayErrorEnvelope(json: unknown): boolean {\n if (json === null || typeof json !== \"object\" || Array.isArray(json)) {\n return false;\n }\n const record = json as Record<string, unknown>;\n if (record.name === \"AiGatewayError\") return true;\n if (record.success !== false) return false;\n const errors = record.error ?? record.errors;\n return (\n Array.isArray(errors) &&\n errors.some(\n (entry) =>\n entry !== null &&\n typeof entry === \"object\" &&\n typeof (entry as { message?: unknown }).message === \"string\"\n )\n );\n}\n\n/**\n * Builds a {@link CloudflareAIError} from the gateway's own error envelope, so\n * a gateway failure on the universal path classifies and retries exactly as\n * one on the Workers AI run path.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function errorFromGatewayEnvelope(\n body: unknown,\n context: {\n model: string;\n url: string;\n requestBodyValues: unknown;\n status?: number;\n responseHeaders?: Record<string, string>;\n responseBody?: string;\n }\n): CloudflareAIError {\n const record =\n body !== null && typeof body === \"object\" && !Array.isArray(body)\n ? (body as Record<string, unknown>)\n : undefined;\n return new CloudflareAIError({\n code: classifyStatus(\n context.status,\n typeof record?.name === \"string\" ? record.name : \"AiGatewayError\"\n ),\n data: body,\n logId: context.responseHeaders?.[\"cf-aig-log-id\"],\n message: errorMessageFrom(body, context.status),\n model: context.model,\n requestBodyValues: context.requestBodyValues,\n responseBody: context.responseBody,\n responseHeaders: context.responseHeaders,\n status: context.status,\n url: context.url\n });\n}\n\n/**\n * The model id a universal request is about, for error reporting. Every vendor\n * body carries `model`; the endpoint is the fallback.\n */\nfunction universalModel(request: UniversalRequest): string {\n const query = request.query;\n if (query !== null && typeof query === \"object\" && !Array.isArray(query)) {\n const model = (query as Record<string, unknown>).model;\n if (typeof model === \"string\") return model;\n }\n return `${request.provider}/${request.endpoint}`;\n}\n\n/**\n * The `Ai` binding narrowed to the raw-response overload. The ambient\n * overloads pick their return type from the model id, and every catalog slug\n * lands on the `Record<string, unknown>` fallback, so the run-path signature\n * is stated explicitly here.\n */\ninterface RawResponseBinding {\n run(\n model: string,\n inputs: Record<string, unknown>,\n options: AiOptions & { returnRawResponse: true }\n ): Promise<Response>;\n}\n\n/** The keyless in-Worker backend: `env.AI.run(...)`. */\nfunction bindingTransport(binding: Ai): Transport {\n const raw = binding as unknown as RawResponseBinding;\n // `aiGatewayLogId` is a mutable property on the binding that every\n // concurrent `run` overwrites, so it is snapshotted against the response it\n // belongs to the moment that response arrives. A run that resolves while\n // another is mid-flight can still read the other's id; the window is one\n // microtask rather than the whole request.\n const logIds = new WeakMap<Response, string>();\n return {\n logIdFallback(response) {\n return logIds.get(response);\n },\n async run(request) {\n try {\n // Called as a method, never detached: the binding reads private\n // fields and throws on a detached reference.\n const response = await raw.run(request.model, request.input, {\n ...(Object.keys(request.headers).length > 0\n ? { extraHeaders: request.headers }\n : {}),\n gateway: request.gateway,\n returnRawResponse: true,\n signal: request.signal\n });\n const logId = binding.aiGatewayLogId;\n if (logId !== null && logId !== undefined) {\n logIds.set(response, logId);\n }\n return response;\n } catch (error) {\n // `returnRawResponse` resolves with a `Response` for upstream errors,\n // so a throw here means the binding itself failed (e.g. code 3040,\n // out of capacity).\n throw normalizeThrownError(error, {\n model: request.model,\n requestBodyValues: request.input,\n url: \"workers-ai-binding\"\n });\n }\n },\n async universal(request) {\n try {\n // Called as a method on the binding, and on the `AiGateway` it\n // returns: both read private fields.\n return await binding.gateway(request.gateway.id).run(\n {\n endpoint: request.endpoint,\n headers: request.headers,\n provider: request.provider,\n query: request.query\n },\n {\n ...(request.extraHeaders === undefined\n ? {}\n : { extraHeaders: request.extraHeaders }),\n gateway: universalGatewayOptions(request.gateway),\n signal: request.signal\n }\n );\n } catch (error) {\n throw normalizeThrownError(error, {\n model: universalModel(request),\n requestBodyValues: request.query,\n url: UNIVERSAL_BINDING_URL\n });\n }\n },\n url: \"workers-ai-binding\"\n };\n}\n\n/**\n * Builds the transport for a set of provider settings. The model id, not the\n * caller, decides the wire format; the transport only decides how the request\n * physically leaves the Worker.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function createTransport(settings: AISettings): Transport {\n if (settings.binding === undefined) {\n throw new Error(\"createAI requires { binding }: the Workers AI binding.\");\n }\n return bindingTransport(settings.binding);\n}\n","/**\n * The AI Gateway provider table: which gateway provider slug a vendor's own\n * base URL belongs to, and what the universal request's `endpoint` is for a\n * given upstream URL.\n *\n * This is platform knowledge, not vendor knowledge — the gateway publishes the\n * list, and every entry here appears in `AIGatewayProviders` from\n * `@cloudflare/workers-types`. Nothing about a vendor's wire format, model ids\n * or capabilities lives here: the vendor's own provider package builds the\n * request, and this table only says where it goes.\n *\n * Adapted from `@cloudflare/ai-gateway-provider`'s `providers.ts`.\n *\n * @experimental This surface is experimental and may change.\n */\n\n/**\n * The gateway provider slugs this table maps onto. A subset of the ambient\n * `AIGatewayProviders` union; {@link GatewayProviderNameCheck} keeps it one.\n *\n * @experimental This surface is experimental and may change.\n */\nexport const GATEWAY_PROVIDER_NAMES = [\n \"workers-ai\",\n \"anthropic\",\n \"openai\",\n \"azure-openai\",\n \"google-ai-studio\",\n \"google-vertex-ai\",\n \"grok\",\n \"mistral\",\n \"perplexity-ai\",\n \"replicate\",\n \"groq\",\n \"deepseek\",\n \"openrouter\",\n \"cerebras\",\n \"cohere\",\n \"huggingface\",\n \"aws-bedrock\",\n \"elevenlabs\",\n \"cartesia\"\n] as const;\n\n/**\n * A gateway provider slug.\n *\n * @experimental This surface is experimental and may change.\n */\nexport type GatewayProviderName = (typeof GATEWAY_PROVIDER_NAMES)[number];\n\n/**\n * Compile-time guard: every slug in this table must exist in the platform's\n * own provider union, so a workers-types bump that renames one fails `tsc`\n * here rather than at runtime with a 404 from the gateway.\n *\n * @internal\n */\nexport type GatewayProviderNameCheck<\n T extends AIGatewayProviders = GatewayProviderName\n> = T;\n\n/**\n * One row of the provider table.\n *\n * @experimental This surface is experimental and may change.\n */\nexport interface GatewayProvider {\n /** The gateway provider slug. */\n readonly name: GatewayProviderName;\n /** Matches the upstream host (`URL.host`), not the whole URL. */\n readonly host: RegExp;\n /**\n * Request headers carrying the vendor's own credential. They are stripped\n * before the request is handed to the gateway, which holds the real key\n * (unified billing or BYOK). Lowercase.\n */\n readonly authHeaders: readonly string[];\n /**\n * The universal request's `endpoint` for an upstream URL: everything after\n * the host, query string included, with the provider's fixed prefix removed.\n * `undefined` when the URL does not belong to this provider.\n */\n endpoint(url: string): string | undefined;\n}\n\n/** The default credential header; providers add their own on top. */\nconst AUTHORIZATION = [\"authorization\"] as const;\n\ninterface ProviderSpec {\n name: GatewayProviderName;\n host: RegExp;\n authHeaders?: readonly string[];\n /** A fixed path prefix stripped from the endpoint. */\n pathPrefix?: RegExp;\n /** A full replacement for the default path mapping. */\n endpoint?: (url: URL) => string | undefined;\n}\n\n/** Path after the host, leading slash removed, query string kept. */\nfunction pathOf(url: URL): string {\n return `${url.pathname.replace(/^\\/+/, \"\")}${url.search}`;\n}\n\nfunction buildProvider(spec: ProviderSpec): GatewayProvider {\n const map =\n spec.endpoint ??\n ((url: URL) => {\n const path = pathOf(url);\n return spec.pathPrefix === undefined\n ? path\n : path.replace(spec.pathPrefix, \"\");\n });\n return {\n authHeaders: spec.authHeaders ?? AUTHORIZATION,\n endpoint(url) {\n const parsed = parseUrl(url);\n if (parsed === undefined || !spec.host.test(parsed.host)) {\n return undefined;\n }\n return map(parsed);\n },\n host: spec.host,\n name: spec.name\n };\n}\n\nfunction parseUrl(url: string): URL | undefined {\n try {\n return new URL(url);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Azure names the deployment in the path; the gateway names it in the\n * endpoint as `<resource>/<deployment>/<rest>`.\n */\nfunction azureEndpoint(url: URL): string | undefined {\n const resource = /^([^.]+)\\.openai\\.azure\\.com$/.exec(url.host)?.[1];\n const rest = /^\\/openai\\/deployments\\/([^/]+)\\/(.+)$/.exec(url.pathname);\n if (resource === undefined || rest === null) return undefined;\n return `${resource}/${rest[1]}/${rest[2]}${url.search}`;\n}\n\n/**\n * Bedrock's region and service live in the host; the gateway wants them as the\n * first two endpoint segments.\n */\nfunction bedrockEndpoint(url: URL): string | undefined {\n const match = /^(bedrock[a-z0-9-]*)\\.([a-z0-9-]+)\\.amazonaws\\.com$/.exec(\n url.host\n );\n if (match === null) return undefined;\n return `${match[1]}/${match[2]}/${pathOf(url)}`;\n}\n\nconst SPECS: ProviderSpec[] = [\n {\n // Workers AI's own API host. `env.AI.run` is this package's path for\n // `@cf/` models; this row exists because the gateway lists the provider,\n // so a model object pointed at that host still resolves.\n host: /^api\\.cloudflare\\.com$/,\n name: \"workers-ai\",\n pathPrefix: /^client\\/v4\\/accounts\\/[^/]+\\/ai\\//\n },\n {\n authHeaders: [\"authorization\", \"x-api-key\"],\n host: /^api\\.anthropic\\.com$/,\n name: \"anthropic\"\n },\n { host: /^api\\.openai\\.com$/, name: \"openai\" },\n {\n authHeaders: [\"authorization\", \"api-key\"],\n endpoint: azureEndpoint,\n host: /^[^.]+\\.openai\\.azure\\.com$/,\n name: \"azure-openai\"\n },\n {\n authHeaders: [\"authorization\", \"x-goog-api-key\"],\n host: /^generativelanguage\\.googleapis\\.com$/,\n name: \"google-ai-studio\"\n },\n {\n host: /^(?:[a-z0-9-]+-)?aiplatform\\.googleapis\\.com$/,\n name: \"google-vertex-ai\"\n },\n { host: /^api\\.x\\.ai$/, name: \"grok\" },\n { host: /^api\\.mistral\\.ai$/, name: \"mistral\" },\n { host: /^api\\.perplexity\\.ai$/, name: \"perplexity-ai\" },\n { host: /^api\\.replicate\\.com$/, name: \"replicate\" },\n {\n host: /^api\\.groq\\.com$/,\n name: \"groq\",\n pathPrefix: /^openai\\/v1\\//\n },\n { host: /^api\\.deepseek\\.com$/, name: \"deepseek\" },\n {\n host: /^openrouter\\.ai$/,\n name: \"openrouter\",\n pathPrefix: /^api\\//\n },\n { host: /^api\\.cerebras\\.ai$/, name: \"cerebras\" },\n { host: /^api\\.cohere\\.(?:ai|com)$/, name: \"cohere\" },\n {\n host: /^(?:api-inference|router)\\.huggingface\\.co$/,\n name: \"huggingface\",\n pathPrefix: /^models\\//\n },\n {\n endpoint: bedrockEndpoint,\n host: /^bedrock.*\\.amazonaws\\.com$/,\n name: \"aws-bedrock\"\n },\n { host: /^api\\.elevenlabs\\.io$/, name: \"elevenlabs\" },\n { host: /^api\\.cartesia\\.ai$/, name: \"cartesia\" }\n];\n\n/**\n * The provider table, in declaration order. Hosts do not overlap, so the order\n * only decides which row a future overlapping host would win.\n *\n * @experimental This surface is experimental and may change.\n */\nexport const GATEWAY_PROVIDERS: readonly GatewayProvider[] =\n SPECS.map(buildProvider);\n\n/**\n * A vendor URL mapped onto the universal gateway request.\n *\n * @experimental This surface is experimental and may change.\n */\nexport interface ResolvedGatewayProvider {\n /** The gateway provider slug. */\n provider: GatewayProviderName;\n /** The universal request's `endpoint`. */\n endpoint: string;\n /** Request headers to strip before handing the request to the gateway. */\n authHeaders: readonly string[];\n}\n\n/**\n * The table row for a bare host (`api.anthropic.com`) or for anything a `URL`\n * can be built from. pi-ai models carry a `baseUrl` rather than a full request\n * URL, so both spellings resolve.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function gatewayProviderForHost(\n hostOrUrl: string\n): GatewayProvider | undefined {\n const host = parseUrl(hostOrUrl)?.host ?? hostOf(hostOrUrl);\n if (host === undefined) return undefined;\n return GATEWAY_PROVIDERS.find((provider) => provider.host.test(host));\n}\n\n/** Reads a host out of a bare host, `host/path` or `//host` spelling. */\nfunction hostOf(value: string): string | undefined {\n const host = value.replace(/^\\/\\//, \"\").split(\"/\")[0];\n return host === \"\" ? undefined : host;\n}\n\n/**\n * Maps a vendor request URL onto `{ provider, endpoint, authHeaders }` for the\n * universal gateway request, or `undefined` when the host is not a gateway\n * provider.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function resolveGatewayProvider(\n url: string\n): ResolvedGatewayProvider | undefined {\n const parsed = parseUrl(url);\n if (parsed === undefined) return undefined;\n for (const provider of GATEWAY_PROVIDERS) {\n if (!provider.host.test(parsed.host)) continue;\n const endpoint = provider.endpoint(url);\n if (endpoint === undefined) continue;\n return {\n authHeaders: provider.authHeaders,\n endpoint,\n provider: provider.name\n };\n }\n return undefined;\n}\n\n/**\n * {@link resolveGatewayProvider}, throwing a `TypeError` that names the host\n * and the provider list when the URL belongs to no gateway provider.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function requireGatewayProvider(url: string): ResolvedGatewayProvider {\n const resolved = resolveGatewayProvider(url);\n if (resolved !== undefined) return resolved;\n const host = parseUrl(url)?.host ?? url;\n throw new TypeError(\n `AI Gateway has no provider for ${host}. Requests are routed by host; the supported providers are ${GATEWAY_PROVIDER_NAMES.join(\", \")}.`\n );\n}\n\n/** The host a gateway-shaped base URL points at. */\nconst GATEWAY_HOST = \"gateway.ai.cloudflare.com\";\n\n/**\n * The provider slug of a gateway-shaped base URL —\n * `https://gateway.ai.cloudflare.com/v1/{account}/{gateway}/{slug}`. Generated\n * registries write models that way (pi-ai's Cloudflare AI Gateway catalog\n * leaves the account and gateway as literal placeholders), so the slug is\n * already in the path rather than implied by a vendor host. The account and\n * gateway segments are ignored: the binding has already chosen both.\n */\nfunction gatewayShapedSlug(url: URL): string | undefined {\n if (url.host !== GATEWAY_HOST) return undefined;\n const segments = url.pathname.split(\"/\").filter((part) => part !== \"\");\n if (segments[0] !== \"v1\" || segments.length < 4) return undefined;\n return segments[3];\n}\n\n/**\n * Whether a base URL is written in the gateway's own shape\n * (`https://gateway.ai.cloudflare.com/v1/{account}/{gateway}/{slug}`) rather\n * than as a vendor's. A generated Cloudflare registry writes models that way,\n * and the path after the slug is then the vendor's own, so a caller that\n * derives an endpoint from a base URL has to tell the two apart.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function isGatewayShapedUrl(url: string): boolean {\n return parseUrl(url)?.host === GATEWAY_HOST;\n}\n\nfunction isGatewayProviderName(slug: string): slug is GatewayProviderName {\n return (GATEWAY_PROVIDER_NAMES as readonly string[]).includes(slug);\n}\n\n/**\n * The gateway provider slug a model's base URL belongs to. Two spellings\n * resolve, because two kinds of registry write them:\n *\n * - a vendor's own base URL (`https://api.anthropic.com` → `anthropic`), which\n * is what a provider package configured for the vendor carries;\n * - a gateway-shaped base URL\n * (`https://gateway.ai.cloudflare.com/v1/{account}/{gateway}/anthropic` →\n * `anthropic`), which is what a generated Cloudflare registry carries.\n *\n * A base URL neither shape resolves is a wiring mistake rather than a request\n * failure, so it throws a `TypeError` naming what was not recognised.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function gatewaySlugForBaseUrl(baseUrl: string): GatewayProviderName {\n const url = parseUrl(baseUrl);\n const shaped = url === undefined ? undefined : gatewayShapedSlug(url);\n if (shaped !== undefined) {\n if (isGatewayProviderName(shaped)) return shaped;\n throw new TypeError(\n `AI Gateway has no provider \"${shaped}\" (from ${baseUrl}). The supported providers are ${GATEWAY_PROVIDER_NAMES.join(\", \")}.`\n );\n }\n const provider = gatewayProviderForHost(baseUrl);\n if (provider !== undefined) return provider.name;\n throw new TypeError(\n `AI Gateway has no provider for ${url?.host ?? baseUrl}. Requests are routed by the model's base URL; the supported providers are ${GATEWAY_PROVIDER_NAMES.join(\", \")}.`\n );\n}\n","/**\n * Where a Cloudflare catalog model departs from strict OpenAI chat\n * completions, and how. Every entry is backed by a live capture from the\n * conformance probes (`research/40-*.json`, `41-*.json`); the default for an\n * unknown id is strict OpenAI, so a new conformant model needs no code here.\n *\n * Framework-neutral: both the AI SDK and the pi-ai providers consult this.\n */\n\n/** A request feature that had to be changed or dropped for a model. */\nexport interface CompatWarning {\n feature: string;\n message: string;\n}\n\nexport interface ChatCompletionsQuirks {\n /** Which field carries the output-token cap. OpenAI's current models reject `max_tokens`. */\n maxTokensField: \"max_tokens\" | \"max_completion_tokens\";\n /**\n * How reasoning can be turned off. `chat-template` sends\n * `chat_template_kwargs.enable_thinking = false` (vLLM); `unsupported` drops\n * the request with a warning because the model keeps reasoning regardless.\n */\n reasoningOff: \"chat-template\" | \"unsupported\";\n /**\n * Which `reasoning_effort` levels the model accepts. `openai` is the full\n * set (`minimal` … `xhigh`); `basic` is `low | medium | high`, everything\n * else clamped.\n */\n reasoningEffortLevels: \"openai\" | \"basic\";\n /** Whether `chat_template_kwargs` is accepted at all. */\n chatTemplateKwargs: \"supported\" | \"unsupported\";\n /** Whether `response_format: json_schema` is accepted at all. */\n jsonSchema: \"supported\" | \"unsupported\";\n /** Whether the OpenAI-only `strict` flag belongs on the json_schema envelope. */\n jsonSchemaStrict: boolean;\n /**\n * `tool_choice: \"required\"`. `named-fallback` rewrites it to the single\n * named tool when there is exactly one (glm-4.7-flash answers 400 to\n * `required`, a gateway serialization bug), and drops it otherwise.\n */\n toolChoiceRequired: \"supported\" | \"named-fallback\";\n /** Whether image parts may reference a URL, or must carry inline bytes. */\n imageUrls: \"any\" | \"data-only\";\n /** Whether replayed assistant reasoning (`reasoning_content`) is accepted. */\n reasoningReplay: \"reasoning_content\" | \"drop\";\n /**\n * Whether a `user` turn may directly follow a `tool` turn. Mistral rejects\n * it (\"Unexpected role 'user' after role 'tool'\"), so an empty assistant\n * turn is inserted between them.\n */\n requiresAssistantAfterToolResult: boolean;\n /**\n * What the model accepts as a tool-call id. `alnum-9` is Mistral's rule:\n * exactly nine `[A-Za-z0-9]` characters, anything else is a 400.\n */\n toolCallIds: \"any\" | \"alnum-9\";\n /** A suffix the model echoes on its own id that callers never asked for. */\n modelEchoSuffix: string | undefined;\n /** Whether a replayed assistant turn may carry `content: null`. */\n nullAssistantContent: \"allowed\" | \"empty-string\";\n /**\n * Where the answer lands in a stream once reasoning has been turned off.\n * `reasoning` means the model's streaming parser mislabels the whole answer\n * as reasoning (its non-streaming body is fine), so the normalizer moves\n * those deltas back into `content`.\n */\n reasoningOffStreamLabel: \"content\" | \"reasoning\";\n}\n\nconst STRICT_OPENAI: ChatCompletionsQuirks = {\n chatTemplateKwargs: \"unsupported\",\n imageUrls: \"any\",\n jsonSchema: \"supported\",\n jsonSchemaStrict: false,\n maxTokensField: \"max_tokens\",\n modelEchoSuffix: undefined,\n nullAssistantContent: \"allowed\",\n reasoningEffortLevels: \"basic\",\n reasoningOff: \"unsupported\",\n reasoningOffStreamLabel: \"content\",\n reasoningReplay: \"drop\",\n requiresAssistantAfterToolResult: false,\n toolCallIds: \"any\",\n toolChoiceRequired: \"supported\"\n};\n\n/** Workers AI's vLLM front end: what every `@cf/` model has in common. */\nconst WORKERS_AI: ChatCompletionsQuirks = {\n ...STRICT_OPENAI,\n chatTemplateKwargs: \"supported\",\n imageUrls: \"data-only\",\n nullAssistantContent: \"empty-string\",\n reasoningOff: \"chat-template\",\n reasoningReplay: \"reasoning_content\"\n};\n\n/**\n * Longest-prefix overrides. Keep each one evidence-backed (the capture that\n * proves it is named in the comment) and delete it when the platform fixes\n * the deviation.\n */\nconst OVERRIDES: [prefix: string, quirks: Partial<ChatCompletionsQuirks>][] = [\n // 40-demos-...-E1: `tool_choice: \"required\"` + tools → 400 pydantic parse error.\n [\"@cf/zai-org/glm-4.7-flash\", { toolChoiceRequired: \"named-fallback\" }],\n // 40-demos-kimi-k3-G3 / 40-matt-kimi-k2.7-code-G_ctk: enable_thinking=false\n // leaves reasoning on; nothing turns it off.\n [\"@cf/moonshotai/\", { reasoningOff: \"unsupported\" }],\n // 40-demos-gpt-oss-120b-G3: same.\n [\"@cf/openai/\", { reasoningOff: \"unsupported\" }],\n // 40-demos-...-F1/F2/G3/J1: \"chat_template is not supported for Mistral\n // tokenizers\", \"Unexpected role 'user' after role 'tool'\".\n // 40-matt-mistral-small-3.1-24b-instruct-J: \"Tool call id was call_1 but\n // must be a-z, A-Z, 0-9, with a length of 9.\"\n [\n \"@cf/mistralai/\",\n {\n chatTemplateKwargs: \"unsupported\",\n jsonSchema: \"unsupported\",\n reasoningOff: \"unsupported\",\n requiresAssistantAfterToolResult: true,\n toolCallIds: \"alnum-9\"\n }\n ],\n // 40-demos-gemma-4-26b-a4b-it-A: echoes \"@cf/google/gemma-4-26b-a4b-it-external\".\n [\"@cf/google/\", { modelEchoSuffix: \"-external\" }],\n // 41-matt-nemotron-3-120b-a12b-K_emoji / S_usage_s: with enable_thinking=false\n // every streamed token arrives as `delta.reasoning` and `content` stays\n // empty, while the non-streaming body (A0, 40-...-G_ctk) puts the same\n // answer in `content` with `reasoning: null`.\n [\"@cf/nvidia/nemotron-\", { reasoningOffStreamLabel: \"reasoning\" }]\n];\n\n/** The quirks for a catalog id: base profile plus the longest matching override. */\nexport function quirksFor(modelId: string): ChatCompletionsQuirks {\n const base = modelId.startsWith(\"@cf/\") ? WORKERS_AI : STRICT_OPENAI;\n let best: [string, Partial<ChatCompletionsQuirks>] | undefined;\n for (const entry of OVERRIDES) {\n if (\n modelId.startsWith(entry[0]) &&\n (best === undefined || entry[0].length > best[0].length)\n ) {\n best = entry;\n }\n }\n return best === undefined ? base : { ...base, ...best[1] };\n}\n\n/** Whether an id is a Workers AI model rather than a third-party catalog model. */\nexport function isWorkersAI(modelId: string): boolean {\n return modelId.startsWith(\"@cf/\");\n}\n","/**\n * Rewrites a strict OpenAI chat-completions request body into what a given\n * catalog model accepts. Frameworks build the strict body from their own\n * prompt types; everything Cloudflare- or vendor-specific happens here, once.\n *\n * The rewrite never throws: a feature the model cannot take is dropped and\n * reported as a {@link CompatWarning}.\n */\n\nimport { type CompatWarning, quirksFor } from \"./quirks\";\n\nexport interface PreparedRequest {\n body: Record<string, unknown>;\n warnings: CompatWarning[];\n /**\n * Whether the body turns the model's reasoning off through the chat\n * template. The stream normalizer needs this for models whose streaming\n * parser mislabels the answer once thinking is off.\n */\n reasoningOff: boolean;\n}\n\ntype Message = Record<string, unknown>;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction clampEffort(effort: string): string {\n if (effort === \"minimal\") return \"low\";\n if (effort === \"xhigh\") return \"high\";\n return effort;\n}\n\n/** Drops URL image parts (keeps inline data URLs) from a user message. */\nfunction stripImageUrls(message: Message, warnings: CompatWarning[]): Message {\n if (!Array.isArray(message.content)) return message;\n let dropped = 0;\n const content = message.content.filter((part) => {\n if (!isRecord(part) || part.type !== \"image_url\") return true;\n const image = isRecord(part.image_url) ? part.image_url : undefined;\n const url = typeof image?.url === \"string\" ? image.url : \"\";\n if (url.startsWith(\"data:\")) return true;\n dropped += 1;\n return false;\n });\n if (dropped > 0) {\n warnings.push({\n feature: \"image-url\",\n message: `Workers AI models need image bytes; ${dropped} image URL${dropped === 1 ? \" was\" : \"s were\"} dropped.`\n });\n }\n return { ...message, content };\n}\n\n/** Nine `[A-Za-z0-9]` characters: what Mistral accepts as a tool-call id. */\nconst CONFORMANT_TOOL_CALL_ID = /^[0-9A-Za-z]{9}$/;\n\nconst TOOL_CALL_ID_ALPHABET =\n \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n/**\n * A deterministic nine-character id for an original id: the same conversation\n * replayed twice produces the same ids, so a provider cache or a log stays\n * comparable. `salt` is bumped only to break a collision.\n */\nfunction hashedToolCallId(original: string, salt: number): string {\n let state = (0x811c9dc5 ^ salt) >>> 0;\n for (let index = 0; index < original.length; index += 1) {\n state = Math.imul(state ^ original.charCodeAt(index), 0x01000193) >>> 0;\n }\n let id = \"\";\n for (let index = 0; index < 9; index += 1) {\n state = Math.imul(state ^ (state >>> 15), 0x01000193) >>> 0;\n id += TOOL_CALL_ID_ALPHABET[state % TOOL_CALL_ID_ALPHABET.length];\n }\n return id;\n}\n\n/** Every tool-call id a message set mentions, in the order it mentions them. */\nfunction toolCallIdsIn(messages: unknown[]): string[] {\n const ids: string[] = [];\n const seen = new Set<string>();\n const add = (value: unknown) => {\n if (typeof value !== \"string\" || seen.has(value)) return;\n seen.add(value);\n ids.push(value);\n };\n for (const message of messages) {\n if (!isRecord(message)) continue;\n if (Array.isArray(message.tool_calls)) {\n for (const call of message.tool_calls) {\n if (isRecord(call)) add(call.id);\n }\n }\n add(message.tool_call_id);\n }\n return ids;\n}\n\n/**\n * Plans the rewrite: which ids have to change, and to what. Ids that already\n * conform are kept exactly as they are — including as reserved values, so a\n * rewritten id can never collide with one.\n */\nfunction planToolCallIds(messages: unknown[]): Map<string, string> {\n const plan = new Map<string, string>();\n const ids = toolCallIdsIn(messages);\n const taken = new Set(ids.filter((id) => CONFORMANT_TOOL_CALL_ID.test(id)));\n for (const id of ids) {\n if (taken.has(id)) continue;\n let replacement = hashedToolCallId(id, 0);\n for (let salt = 1; taken.has(replacement) && salt <= 64; salt += 1) {\n replacement = hashedToolCallId(id, salt);\n }\n taken.add(replacement);\n plan.set(id, replacement);\n }\n return plan;\n}\n\n/** Applies the plan to an assistant `tool_calls` turn or a `tool` result. */\nfunction rewriteToolCallIds(\n message: Message,\n plan: Map<string, string>\n): Message {\n let rewritten = message;\n if (Array.isArray(rewritten.tool_calls)) {\n rewritten = {\n ...rewritten,\n tool_calls: rewritten.tool_calls.map((call) => {\n if (!isRecord(call) || typeof call.id !== \"string\") return call;\n const replacement = plan.get(call.id);\n return replacement === undefined ? call : { ...call, id: replacement };\n })\n };\n }\n if (typeof rewritten.tool_call_id === \"string\") {\n const replacement = plan.get(rewritten.tool_call_id);\n if (replacement !== undefined) {\n rewritten = { ...rewritten, tool_call_id: replacement };\n }\n }\n return rewritten;\n}\n\n/**\n * Applies the model's quirks to a strict OpenAI chat-completions body.\n *\n * Conventions the strict body follows, which this function translates:\n * - `max_tokens` is the cap; it becomes `max_completion_tokens` where needed.\n * - `reasoning_effort: null` means \"turn reasoning off\".\n * - Replayed assistant reasoning sits in `reasoning_content`.\n * - `response_format.json_schema` is the OpenAI `{ name, schema }` envelope.\n * - `chat_template_kwargs` may be present; it is only meaningful on Workers AI.\n */\nexport function prepareChatCompletionsRequest(\n input: Record<string, unknown>,\n modelId: string\n): PreparedRequest {\n const quirks = quirksFor(modelId);\n const warnings: CompatWarning[] = [];\n const body: Record<string, unknown> = { ...input };\n\n // Output-token cap.\n if (\n quirks.maxTokensField === \"max_completion_tokens\" &&\n \"max_tokens\" in body\n ) {\n body.max_completion_tokens = body.max_tokens;\n delete body.max_tokens;\n }\n\n // Reasoning.\n if (\"reasoning_effort\" in body) {\n const effort = body.reasoning_effort;\n if (effort === null) {\n delete body.reasoning_effort;\n if (quirks.reasoningOff === \"chat-template\") {\n body.chat_template_kwargs = {\n ...(isRecord(body.chat_template_kwargs)\n ? body.chat_template_kwargs\n : {}),\n enable_thinking: false\n };\n } else {\n warnings.push({\n feature: \"reasoning-off\",\n message: `Reasoning cannot be turned off on ${modelId}; the request was sent with the model's default effort.`\n });\n }\n } else if (\n typeof effort === \"string\" &&\n quirks.reasoningEffortLevels === \"basic\"\n ) {\n body.reasoning_effort = clampEffort(effort);\n }\n }\n if (\n \"chat_template_kwargs\" in body &&\n quirks.chatTemplateKwargs === \"unsupported\"\n ) {\n delete body.chat_template_kwargs;\n warnings.push({\n feature: \"chat-template-kwargs\",\n message: `${modelId} does not take chat_template_kwargs; they were dropped.`\n });\n }\n\n // Structured output.\n if (isRecord(body.response_format)) {\n if (quirks.jsonSchema === \"unsupported\") {\n delete body.response_format;\n warnings.push({\n feature: \"response-format\",\n message: `${modelId} does not support response_format; the request was sent without it.`\n });\n } else if (\n body.response_format.type === \"json_schema\" &&\n isRecord(body.response_format.json_schema)\n ) {\n const { strict: _strict, ...envelope } = body.response_format.json_schema;\n body.response_format = {\n ...body.response_format,\n json_schema: quirks.jsonSchemaStrict\n ? { ...envelope, strict: true }\n : envelope\n };\n }\n }\n\n // Tools.\n if (\n body.tool_choice === \"required\" &&\n quirks.toolChoiceRequired === \"named-fallback\"\n ) {\n const tools = Array.isArray(body.tools) ? body.tools : [];\n const only =\n tools.length === 1 && isRecord(tools[0]) ? tools[0] : undefined;\n const name =\n only !== undefined &&\n isRecord(only.function) &&\n typeof only.function.name === \"string\"\n ? only.function.name\n : undefined;\n if (name !== undefined) {\n body.tool_choice = { function: { name }, type: \"function\" };\n } else {\n delete body.tool_choice;\n warnings.push({\n feature: \"tool-choice-required\",\n message: `${modelId} rejects tool_choice \"required\"; the model was left free to choose.`\n });\n }\n }\n\n // Messages.\n if (Array.isArray(body.messages)) {\n // Two passes: the ids are planned over the whole conversation first, so an\n // assistant turn and the tool result answering it are rewritten to the\n // same value however far apart they sit.\n const toolCallIds =\n quirks.toolCallIds === \"alnum-9\"\n ? planToolCallIds(body.messages)\n : new Map<string, string>();\n if (toolCallIds.size > 0) {\n warnings.push({\n feature: \"tool-call-id\",\n message: `${modelId} needs 9-character alphanumeric tool-call ids; ${toolCallIds.size} id${toolCallIds.size === 1 ? \" was\" : \"s were\"} rewritten.`\n });\n }\n const messages: Message[] = [];\n let previousRole: unknown;\n for (const entry of body.messages) {\n if (!isRecord(entry)) continue;\n let message: Message = entry;\n if (toolCallIds.size > 0) {\n message = rewriteToolCallIds(message, toolCallIds);\n }\n if (message.role === \"user\" && quirks.imageUrls === \"data-only\") {\n message = stripImageUrls(message, warnings);\n }\n if (\n message.role === \"assistant\" &&\n message.content === null &&\n quirks.nullAssistantContent === \"empty-string\"\n ) {\n // 41-demos-gpt-oss-120b-O_replay_null: a replayed assistant turn with\n // `content: null` is a 400 on Workers AI; `\"\"` is accepted everywhere.\n message = { ...message, content: \"\" };\n }\n if (message.role === \"assistant\" && \"reasoning_content\" in message) {\n if (quirks.reasoningReplay === \"drop\") {\n const { reasoning_content: _reasoning, ...rest } = message;\n message = rest;\n warnings.push({\n feature: \"assistant-reasoning\",\n message: `${modelId} has no field for replayed reasoning; the assistant reasoning was dropped.`\n });\n }\n }\n if (\n quirks.requiresAssistantAfterToolResult &&\n previousRole === \"tool\" &&\n message.role === \"user\"\n ) {\n messages.push({ content: \"\", role: \"assistant\" });\n }\n messages.push(message);\n previousRole = message.role;\n }\n body.messages = messages;\n }\n\n const reasoningOff =\n isRecord(body.chat_template_kwargs) &&\n body.chat_template_kwargs.enable_thinking === false;\n return { body, reasoningOff, warnings };\n}\n","/**\n * Normalizes a chat-completions response body from the run path into the\n * strict OpenAI `chat.completion` shape, so framework parsers never see\n * Workers AI's native envelope or its field spellings.\n */\n\nimport { quirksFor } from \"./quirks\";\n\ntype Record_ = Record<string, unknown>;\n\nfunction isRecord(value: unknown): value is Record_ {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/** Native `{ name, arguments: object }` → OpenAI `{ id, type, function }`. */\nexport function normalizeToolCall(\n entry: unknown,\n index: number\n): Record_ | undefined {\n if (!isRecord(entry)) return undefined;\n const fn = isRecord(entry.function) ? entry.function : undefined;\n const name =\n typeof fn?.name === \"string\"\n ? fn.name\n : typeof entry.name === \"string\"\n ? entry.name\n : undefined;\n if (name === undefined) return undefined;\n const rawArguments =\n fn !== undefined && \"arguments\" in fn ? fn.arguments : entry.arguments;\n const args =\n typeof rawArguments === \"string\"\n ? rawArguments\n : rawArguments === undefined || rawArguments === null\n ? \"{}\"\n : JSON.stringify(rawArguments);\n return {\n ...(typeof entry.index === \"number\" ? { index: entry.index } : { index }),\n ...(typeof entry.id === \"string\" ? { id: entry.id } : {}),\n function: { arguments: args, name },\n type: \"function\",\n ...(entry.extra_content !== undefined\n ? { extra_content: entry.extra_content }\n : {})\n };\n}\n\n/** Text as the model produced it; structured-output models may return an object. */\nfunction contentText(value: unknown): string | null {\n if (typeof value === \"string\") return value;\n if (value === null || value === undefined) return null;\n return JSON.stringify(value);\n}\n\nfunction stripEchoSuffix(model: unknown, modelId: string): unknown {\n const suffix = quirksFor(modelId).modelEchoSuffix;\n if (typeof model !== \"string\" || suffix === undefined) return model;\n return model.endsWith(suffix) ? model.slice(0, -suffix.length) : model;\n}\n\n/** Puts reasoning under `reasoning_content` whichever spelling the model used. */\nfunction normalizeMessage(message: Record_): Record_ {\n const out: Record_ = { ...message };\n const reasoning =\n typeof out.reasoning_content === \"string\" && out.reasoning_content !== \"\"\n ? out.reasoning_content\n : typeof out.reasoning === \"string\" && out.reasoning !== \"\"\n ? out.reasoning\n : undefined;\n delete out.reasoning;\n if (reasoning !== undefined) out.reasoning_content = reasoning;\n else delete out.reasoning_content;\n if (\"content\" in out) out.content = contentText(out.content);\n if (Array.isArray(out.tool_calls)) {\n const calls = out.tool_calls\n .map((call, index) => normalizeToolCall(call, index))\n .filter((call): call is Record_ => call !== undefined);\n if (calls.length > 0) out.tool_calls = calls;\n else delete out.tool_calls;\n }\n return out;\n}\n\n/**\n * Returns the body in the strict `chat.completion` shape. Already-OpenAI\n * bodies come back with their reasoning spelling unified and the echoed model\n * id cleaned; native Workers AI `{ response, tool_calls, usage }` bodies are\n * lifted into `choices[0]`.\n */\nexport function normalizeChatCompletion(\n body: unknown,\n modelId: string\n): Record_ {\n if (!isRecord(body)) return { choices: [] };\n if (Array.isArray(body.choices)) {\n const choices = body.choices.map((choice) => {\n if (!isRecord(choice)) return choice;\n const message = isRecord(choice.message)\n ? normalizeMessage(choice.message)\n : choice.message;\n const hasToolCalls =\n isRecord(message) &&\n Array.isArray(message.tool_calls) &&\n message.tool_calls.length > 0;\n return {\n ...choice,\n message,\n finish_reason:\n choice.finish_reason ?? (hasToolCalls ? \"tool_calls\" : \"stop\")\n };\n });\n return { ...body, choices, model: stripEchoSuffix(body.model, modelId) };\n }\n if (\"response\" in body || \"tool_calls\" in body) {\n const toolCalls = Array.isArray(body.tool_calls)\n ? body.tool_calls\n .map((call, index) => normalizeToolCall(call, index))\n .filter((call): call is Record_ => call !== undefined)\n : [];\n const { response, tool_calls: _toolCalls, usage, ...rest } = body;\n return {\n ...rest,\n choices: [\n {\n finish_reason:\n typeof body.finish_reason === \"string\"\n ? body.finish_reason\n : toolCalls.length > 0\n ? \"tool_calls\"\n : \"stop\",\n index: 0,\n message: {\n content: contentText(response),\n role: \"assistant\",\n ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {})\n }\n }\n ],\n model: stripEchoSuffix(body.model, modelId),\n ...(usage !== undefined ? { usage } : {})\n };\n }\n return body;\n}\n","/**\n * Normalizes a chat-completions SSE stream from the run path into strict\n * OpenAI `chat.completion.chunk` events.\n *\n * Every Workers AI model streams the same three-part hybrid (live captures,\n * all families): OpenAI-shaped delta chunks that each carry a per-delta\n * `usage`, then a `choices: []` heartbeat, then a native\n * `{ response: \"\", usage }` tail with the cumulative usage, then `[DONE]`.\n * Some models also emit native `{ response: \"<text>\" }` deltas or top-level\n * `tool_calls`. After this transform a consumer sees only:\n *\n * - delta chunks without per-delta usage and with reasoning under\n * `reasoning_content`;\n * - at most one final `choices: []` chunk carrying the cumulative usage\n * (the OpenAI `stream_options.include_usage` shape);\n * - a `finish_reason` on some chunk before the end, synthesized when the\n * model finished cleanly without sending one;\n * - `[DONE]`.\n *\n * Input and output are SSE `data` payloads (strings), so it slots between the\n * SSE decoder and either framework's OpenAI chunk parser.\n */\n\nimport { isWorkersAI, quirksFor } from \"./quirks\";\nimport { normalizeToolCall } from \"./response\";\n\ntype Record_ = Record<string, unknown>;\n\nfunction isRecord(value: unknown): value is Record_ {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nconst NOISE_FIELDS = [\n \"p\",\n \"token_ids\",\n \"prompt_token_ids\",\n \"kv_transfer_params\"\n];\n\n/** Fields the run path adds to every chunk that mean nothing to a consumer. */\nfunction stripNoise(chunk: Record_): Record_ {\n const out = { ...chunk };\n for (const key of NOISE_FIELDS) delete out[key];\n return out;\n}\n\nfunction stripEchoSuffix(chunk: Record_, modelId: string): Record_ {\n const suffix = quirksFor(modelId).modelEchoSuffix;\n if (suffix === undefined || typeof chunk.model !== \"string\") return chunk;\n return chunk.model.endsWith(suffix)\n ? { ...chunk, model: chunk.model.slice(0, -suffix.length) }\n : chunk;\n}\n\nfunction normalizeDelta(delta: Record_, relabelReasoning: boolean): Record_ {\n const out: Record_ = { ...delta };\n const reasoning =\n typeof out.reasoning_content === \"string\" && out.reasoning_content !== \"\"\n ? out.reasoning_content\n : typeof out.reasoning === \"string\" && out.reasoning !== \"\"\n ? out.reasoning\n : undefined;\n delete out.reasoning;\n delete out.reasoning_content;\n if (reasoning !== undefined) {\n if (relabelReasoning) {\n // Reasoning is off, so these tokens are the answer (nemotron-3).\n out.content =\n (typeof out.content === \"string\" ? out.content : \"\") + reasoning;\n } else {\n out.reasoning_content = reasoning;\n }\n }\n if (Array.isArray(out.tool_calls)) {\n out.tool_calls = out.tool_calls.map((call, index) => {\n // Fragments and the null finalizer pass through untouched; only a\n // native complete call needs lifting into the OpenAI shape. A native\n // call names its tool at the top level, where no OpenAI fragment does,\n // and its arguments may be an object or already a string.\n if (!isRecord(call)) return call;\n const fn = isRecord(call.function) ? call.function : undefined;\n const args = fn !== undefined ? fn.arguments : call.arguments;\n const native = fn === undefined && typeof call.name === \"string\";\n return native || isRecord(args)\n ? (normalizeToolCall(call, index) ?? call)\n : call;\n });\n }\n return out;\n}\n\nexport interface StreamNormalizationOptions {\n /** Whether the request turned reasoning off (`PreparedRequest.reasoningOff`). */\n reasoningOff?: boolean;\n}\n\n/**\n * The transform. Backpressure is preserved: nothing is buffered except the\n * single pending usage chunk, which must wait for the tail.\n */\nexport function normalizeChatCompletionsStream(\n modelId: string,\n options: StreamNormalizationOptions = {}\n): TransformStream<string, string> {\n const quirks = quirksFor(modelId);\n const relabelReasoning =\n options.reasoningOff === true &&\n quirks.reasoningOffStreamLabel === \"reasoning\";\n let id: string | undefined;\n let model: string | undefined;\n let created: number | undefined;\n let sawFinishReason = false;\n let sawContent = false;\n let sawToolCalls = false;\n let sawDone = false;\n let finalUsage: unknown;\n let finalUsageTemplate: Record_ | undefined;\n // Workers AI stamps a per-delta usage on every content chunk and sends the\n // cumulative figure in its native tail; other vendors only ever put usage on\n // the final `choices: []` chunk, so theirs is left alone.\n const perDeltaUsage = isWorkersAI(modelId);\n\n const envelope = (extra: Record_): Record_ => ({\n ...(id !== undefined ? { id } : {}),\n object: \"chat.completion.chunk\",\n ...(created !== undefined ? { created } : {}),\n ...(model !== undefined ? { model } : {}),\n ...extra\n });\n\n const emit = (\n controller: TransformStreamDefaultController<string>,\n chunk: Record_\n ) => {\n controller.enqueue(JSON.stringify(chunk));\n };\n\n const emitTail = (controller: TransformStreamDefaultController<string>) => {\n if (!sawFinishReason && sawDone && (sawContent || sawToolCalls)) {\n emit(\n controller,\n envelope({\n choices: [\n {\n delta: {},\n finish_reason: sawToolCalls ? \"tool_calls\" : \"stop\",\n index: 0\n }\n ]\n })\n );\n sawFinishReason = true;\n }\n if (finalUsage !== undefined) {\n emit(controller, {\n ...(finalUsageTemplate ?? envelope({})),\n choices: [],\n usage: finalUsage\n });\n finalUsage = undefined;\n }\n if (sawDone) controller.enqueue(\"[DONE]\");\n };\n\n return new TransformStream<string, string>({\n flush(controller) {\n emitTail(controller);\n },\n transform(data, controller) {\n if (data === \"\") return;\n if (data === \"[DONE]\") {\n // Everything after the tail is emitted at flush, once.\n sawDone = true;\n return;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(data);\n } catch {\n // A malformed event is dropped rather than failing the stream.\n return;\n }\n if (!isRecord(parsed)) return;\n const chunk = stripEchoSuffix(stripNoise(parsed), modelId);\n\n if (typeof chunk.id === \"string\") id ??= chunk.id;\n if (typeof chunk.model === \"string\") model ??= chunk.model;\n if (typeof chunk.created === \"number\") created ??= chunk.created;\n\n // An error payload passes through untouched for the consumer to surface;\n // it also ends the generation, so no finish reason is synthesized after it.\n if (isRecord(chunk.error)) {\n sawFinishReason = true;\n controller.enqueue(JSON.stringify(chunk));\n return;\n }\n\n if (Array.isArray(chunk.choices)) {\n if (chunk.choices.length === 0) {\n // Heartbeat, or OpenAI's own final usage chunk: hold the usage\n // until the end so exactly one usage chunk is emitted.\n if (isRecord(chunk.usage)) {\n finalUsage = chunk.usage;\n finalUsageTemplate = { ...chunk, usage: undefined };\n delete finalUsageTemplate.usage;\n }\n return;\n }\n const choices = chunk.choices.map((choice) => {\n if (!isRecord(choice)) return choice;\n if (typeof choice.finish_reason === \"string\") sawFinishReason = true;\n const delta = isRecord(choice.delta)\n ? normalizeDelta(choice.delta, relabelReasoning)\n : choice.delta;\n if (isRecord(delta)) {\n if (typeof delta.content === \"string\" && delta.content !== \"\")\n sawContent = true;\n if (typeof delta.reasoning_content === \"string\") sawContent = true;\n if (Array.isArray(delta.tool_calls) && delta.tool_calls.length > 0)\n sawToolCalls = true;\n }\n if (!perDeltaUsage) return { ...choice, delta };\n const { usage: _perDeltaUsage, ...rest } = choice;\n return { ...rest, delta };\n });\n if (perDeltaUsage) {\n // The cumulative figure comes with the native tail.\n const { usage: _usage, ...rest } = chunk;\n emit(controller, { ...rest, choices });\n } else {\n emit(controller, { ...chunk, choices });\n }\n return;\n }\n\n // Native Workers AI events.\n if (\"response\" in chunk || \"tool_calls\" in chunk) {\n const text = chunk.response;\n const hasText = typeof text === \"string\" && text !== \"\";\n const calls = Array.isArray(chunk.tool_calls)\n ? chunk.tool_calls\n .map((call, index) => normalizeToolCall(call, index))\n .filter((call): call is Record_ => call !== undefined)\n : [];\n if (hasText || calls.length > 0) {\n if (hasText) sawContent = true;\n if (calls.length > 0) sawToolCalls = true;\n emit(\n controller,\n envelope({\n choices: [\n {\n delta: {\n ...(hasText ? { content: text } : {}),\n ...(calls.length > 0 ? { tool_calls: calls } : {})\n },\n finish_reason: null,\n index: 0\n }\n ]\n })\n );\n }\n if (isRecord(chunk.usage)) {\n // The native tail: cumulative usage for the whole stream.\n finalUsage = chunk.usage;\n finalUsageTemplate = undefined;\n }\n if (typeof chunk.finish_reason === \"string\") {\n sawFinishReason = true;\n emit(\n controller,\n envelope({\n choices: [\n { delta: {}, finish_reason: chunk.finish_reason, index: 0 }\n ]\n })\n );\n }\n }\n }\n });\n}\n","/**\n * Decodes a `text/event-stream` byte stream into the `data` payload of each\n * event, as a `TransformStream` so the whole pipeline keeps backpressure and\n * nothing is ever buffered beyond the current event.\n *\n * Handles all three line terminators the SSE spec allows (LF, CRLF and a bare\n * CR), multi-line `data:` fields (joined with `\\n`, per the spec), comment\n * lines (`:` prefixed), and non-`data` fields (`event:`, `id:`, `retry:`),\n * which are ignored. A trailing event that the server never terminated with a\n * blank line is still flushed.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function sseDataStream(): TransformStream<Uint8Array, string> {\n const decoder = new TextDecoder();\n let buffer = \"\";\n let data: string[] = [];\n\n const flushEvent = (controller: TransformStreamDefaultController<string>) => {\n if (data.length === 0) return;\n controller.enqueue(data.join(\"\\n\"));\n data = [];\n };\n\n const consumeLine = (\n line: string,\n controller: TransformStreamDefaultController<string>\n ) => {\n if (line === \"\") {\n flushEvent(controller);\n return;\n }\n if (line.startsWith(\":\")) return;\n const colon = line.indexOf(\":\");\n const field = colon === -1 ? line : line.slice(0, colon);\n if (field !== \"data\") return;\n let value = colon === -1 ? \"\" : line.slice(colon + 1);\n if (value.startsWith(\" \")) value = value.slice(1);\n data.push(value);\n };\n\n /**\n * Consumes whole lines out of the buffer. A buffer ending in a lone `\\r` is\n * held back while more bytes may arrive, because the next byte decides\n * whether that `\\r` was a CRLF pair or a bare-CR terminator.\n */\n const drain = (\n controller: TransformStreamDefaultController<string>,\n final: boolean\n ) => {\n for (;;) {\n const match = /\\r\\n|[\\r\\n]/.exec(buffer);\n if (match === null) break;\n const end = match.index + match[0].length;\n if (!final && match[0] === \"\\r\" && end === buffer.length) break;\n consumeLine(buffer.slice(0, match.index), controller);\n buffer = buffer.slice(end);\n }\n };\n\n return new TransformStream<Uint8Array, string>({\n flush(controller) {\n buffer += decoder.decode();\n drain(controller, true);\n // A server that closed without a final blank line still owes us the\n // last event; emit whatever is left rather than dropping it.\n if (buffer !== \"\") {\n consumeLine(buffer, controller);\n buffer = \"\";\n }\n flushEvent(controller);\n },\n transform(chunk, controller) {\n buffer += decoder.decode(chunk, { stream: true });\n drain(controller, false);\n }\n });\n}\n","/**\n * Workers AI text-to-image requests and answers, shared by both framework\n * modules.\n *\n * Two things about this catalog are easy to get wrong in one module and right\n * in the other, so neither module owns them: the flux-1 models take a two-key\n * subset of the common input shape, and the media type of a JSON answer is in\n * the bytes rather than in the model name (flux-1-schnell answers JPEG while\n * every other model here answers PNG).\n *\n * @experimental This surface is experimental and may change.\n */\n\nimport type { CompatWarning } from \"./chat-completions\";\n\n/**\n * `flux-1-schnell` takes `{ prompt, steps }` and nothing else — no size, no\n * seed, no guidance. Sending those anyway would be silently ignored, so they\n * come back as warnings instead.\n *\n * @see https://developers.cloudflare.com/workers-ai/models/flux-1-schnell/\n */\nconst PROMPT_AND_STEPS_ONLY = /^@cf\\/black-forest-labs\\/flux-1/;\n\n/**\n * The generation knobs Workers AI text-to-image models share, in this\n * package's own spelling. Each module maps its own call options onto them.\n *\n * @experimental This surface is experimental and may change.\n */\nexport interface ImageGenerationSettings {\n width?: number;\n height?: number;\n /** Diffusion steps. Sent as `num_steps`, or `steps` on the flux-1 models. */\n steps?: number;\n /** Classifier-free guidance scale. */\n guidance?: number;\n /** How strongly img2img transforms the input image, between 0 and 1. */\n strength?: number;\n negativePrompt?: string;\n seed?: number;\n /**\n * Whether the caller has a source image to attach. The field it goes in\n * differs per module, so only the warning is decided here.\n */\n sourceImage?: boolean;\n /** Whether the caller has an inpainting mask to attach. */\n mask?: boolean;\n}\n\n/**\n * A run-path image body with the knobs the model could not take reported.\n *\n * @experimental This surface is experimental and may change.\n */\nexport interface BuiltImageRequest {\n input: Record<string, unknown>;\n warnings: CompatWarning[];\n /**\n * The model takes `{ prompt, steps }` only, so the caller must not attach a\n * source image or a mask either.\n */\n minimal: boolean;\n}\n\n/**\n * Builds the run-path body for a text-to-image model: `prompt`, `width`,\n * `height`, `num_steps`, `guidance`, `strength`, `negative_prompt` and `seed`,\n * or the flux-1 two-key subset with a warning for everything dropped.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function buildImageInput(\n modelId: string,\n prompt: string,\n settings: ImageGenerationSettings\n): BuiltImageRequest {\n const warnings: CompatWarning[] = [];\n const input: Record<string, unknown> = { prompt };\n\n if (PROMPT_AND_STEPS_ONLY.test(modelId)) {\n if (settings.steps !== undefined) input.steps = settings.steps;\n for (const [feature, value] of [\n [\"size\", settings.width ?? settings.height],\n [\"seed\", settings.seed],\n [\"guidance\", settings.guidance],\n [\"negativePrompt\", settings.negativePrompt],\n [\"strength\", settings.strength],\n [\"files\", settings.sourceImage === true ? true : undefined],\n [\"mask\", settings.mask === true ? true : undefined]\n ] as const) {\n if (value !== undefined) {\n warnings.push({\n feature,\n message: `${modelId} takes only a prompt and steps.`\n });\n }\n }\n return { input, minimal: true, warnings };\n }\n\n if (settings.width !== undefined) input.width = settings.width;\n if (settings.height !== undefined) input.height = settings.height;\n if (settings.seed !== undefined) input.seed = settings.seed;\n if (settings.steps !== undefined) input.num_steps = settings.steps;\n if (settings.guidance !== undefined) input.guidance = settings.guidance;\n if (settings.strength !== undefined) input.strength = settings.strength;\n if (settings.negativePrompt !== undefined) {\n input.negative_prompt = settings.negativePrompt;\n }\n return { input, minimal: false, warnings };\n}\n\nconst JPEG_PREFIX = \"/9j/\";\nconst PNG_PREFIX = \"iVBORw0KGgo\";\nconst WEBP_PREFIX = \"UklGR\";\nconst GIF_PREFIX = \"R0lGOD\";\n\n/**\n * Sniffs an image media type from the head of its base64. The bytes decide,\n * never the model name: `flux-1-schnell` answers JPEG where every other model\n * in this catalog answers PNG.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function imageMediaTypeOf(base64: string): string {\n if (base64.startsWith(JPEG_PREFIX)) return \"image/jpeg\";\n if (base64.startsWith(PNG_PREFIX)) return \"image/png\";\n if (base64.startsWith(WEBP_PREFIX)) return \"image/webp\";\n if (base64.startsWith(GIF_PREFIX)) return \"image/gif\";\n return \"image/png\";\n}\n"],"mappings":";;;;;;;;;;AAmC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QAAQ,SAAS,IAAI;GACtB,CAAC,YAAY,SAAS,QAAQ;GAC9B,CAAC,kBAAkB,SAAS,cAAc;GAC1C,CAAC,YAAY,SAAS,QAAQ;GAC9B,CAAC,SAAS,SAAS,gBAAgB,OAAO,OAAO,KAAA,CAAS;GAC1D,CAAC,QAAQ,SAAS,SAAS,OAAO,OAAO,KAAA,CAAS;EACpD,GACE,IAAI,UAAU,KAAA,GACZ,SAAS,KAAK;GACZ;GACA,SAAS,GAAG,QAAQ;EACtB,CAAC;EAGL,OAAO;GAAE;GAAO,SAAS;GAAM;EAAS;CAC1C;CAEA,IAAI,SAAS,UAAU,KAAA,GAAW,MAAM,QAAQ,SAAS;CACzD,IAAI,SAAS,WAAW,KAAA,GAAW,MAAM,SAAS,SAAS;CAC3D,IAAI,SAAS,SAAS,KAAA,GAAW,MAAM,OAAO,SAAS;CACvD,IAAI,SAAS,UAAU,KAAA,GAAW,MAAM,YAAY,SAAS;CAC7D,IAAI,SAAS,aAAa,KAAA,GAAW,MAAM,WAAW,SAAS;CAC/D,IAAI,SAAS,aAAa,KAAA,GAAW,MAAM,WAAW,SAAS;CAC/D,IAAI,SAAS,mBAAmB,KAAA,GAC9B,MAAM,kBAAkB,SAAS;CAEnC,OAAO;EAAE;EAAO,SAAS;EAAO;CAAS;AAC3C;AAEA,MAAM,cAAc;AACpB,MAAM,aAAa;AACnB,MAAM,cAAc;AACpB,MAAM,aAAa;;;;;;;;AASnB,SAAgB,iBAAiB,QAAwB;CACvD,IAAI,OAAO,WAAW,WAAW,GAAG,OAAO;CAC3C,IAAI,OAAO,WAAW,UAAU,GAAG,OAAO;CAC1C,IAAI,OAAO,WAAW,WAAW,GAAG,OAAO;CAC3C,IAAI,OAAO,WAAW,UAAU,GAAG,OAAO;CAC1C,OAAO;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"input-schema-DNrpTu49.js","names":[],"sources":["../src/websearch/tools/input-schema.ts"],"sourcesContent":["/**\n * The zod input schema shared by the AI SDK and TanStack AI adapters. Kept\n * out of the core so the pi adapter, which uses TypeBox, does not need zod.\n * Internal — not an entry point.\n */\nimport { z } from \"zod\";\nimport {\n MAX_WEB_SEARCH_QUERY_LENGTH,\n type WebSearchToolInput\n} from \"../contract\";\n\n/**\n * The model's input schema. The description tells the model the host's\n * `limit`; a larger value is not rejected (which would cost a validation\n * round trip) but capped by the core.\n */\nexport function webSearchInputSchema(maxLimit: number) {\n return z.object({\n query: z\n .string()\n .min(1)\n .max(MAX_WEB_SEARCH_QUERY_LENGTH)\n .describe(\"What to search for.\"),\n limit: z\n .number()\n .int()\n .min(1)\n .optional()\n .describe(`How many results to return (at most ${maxLimit}).`)\n }) satisfies z.ZodType<WebSearchToolInput>;\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,SAAgB,qBAAqB,UAAkB;CACrD,OAAO,EAAE,OAAO;EACd,OAAO,EACJ,OAAO,CAAC,CACR,IAAI,CAAC,CAAC,CACN,IAAI,2BAA2B,CAAC,CAChC,SAAS,qBAAqB;EACjC,OAAO,EACJ,OAAO,CAAC,CACR,IAAI,CAAC,CACL,IAAI,CAAC,CAAC,CACN,SAAS,CAAC,CACV,SAAS,uCAAuC,SAAS,GAAG;CACjE,CAAC;AACH"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"lifecycle-CFu6OV03.js","names":[],"sources":["../src/lifecycle/capability-runner.ts","../src/lifecycle/abort.ts","../src/lifecycle/job-queue.ts","../src/lifecycle/job-driver.ts","../src/lifecycle/transport-errors.ts","../src/lifecycle/durable-object-lifecycle.ts"],"sourcesContent":["import { lifecycleCapabilityId } from \"./capability\";\nimport type { LifecycleRouteContext } from \"./capability\";\nimport type { WSMessage } from \"./types\";\nimport type {\n LifecycleJob,\n LifecycleJobContext,\n LifecycleJobOutcome\n} from \"./job-queue\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\n/** One best-effort event published by a Lifecycle capability. */\nexport type LifecycleEvent = {\n /** Stable capability or subsystem name. */\n readonly source: string;\n /** Stable event name within that source. */\n readonly type: string;\n /** Event-specific data. */\n readonly payload: unknown;\n};\n\n/** Terminal sink for best-effort Lifecycle events. */\nexport type LifecycleEventSink = (\n event: LifecycleEvent\n) => void | Promise<void>;\n\n/** Context supplied when durable capabilities start. */\nexport type CapabilityStartContext<Props extends object = object> = {\n /** Properties supplied while resolving the Durable Object. */\n readonly props: Props | undefined;\n};\n\n/** Context supplied when durable capabilities inspect an HTTP request. */\nexport type CapabilityRequestContext = {\n /** The request entering the Durable Object. */\n readonly request: Request;\n};\n\n/** Context supplied when a capability inspects a WebSocket upgrade. */\nexport type CapabilityWebSocketUpgradeContext = {\n /** The WebSocket upgrade request entering the Durable Object. */\n readonly request: Request;\n};\n\n/**\n * Context supplied when the alarm memory-limit circuit breaker records a\n * strike (#1825), to capabilities and the host alike.\n */\nexport type MemoryLimitContext = {\n /** Whether the breaker hit its strike budget and sealed recovery work. */\n readonly sealed: boolean;\n /** The backoff wake time (epoch ms) armed for an unsealed strike. */\n readonly nextTime?: number;\n /**\n * The queue job that was executing when the strike landed. Absent when the\n * reset happened during startup or host alarm work. Lifecycle has already\n * backed off or purged its row before invoking memory-limit policy.\n *\n * Capabilities whose durable state outlives their queue row use this to\n * apply the same policy to the underlying work — Tasks routes a struck\n * routed job's owner this way (see `setTaskRoutedMemoryLimitHandler`).\n */\n readonly executing?: LifecycleJob;\n /**\n * Recovery-loop jobs removed when this strike sealed the breaker. This is\n * a pre-purge snapshot because the durable rows no longer exist when\n * policy hooks run. No current capability reads this — Scheduler's own\n * former use of it (routing a sealed strike to every purged row's owning\n * dynamic agent) was retired once Tasks took over routed chat-recovery\n * wakes — but it stays available for a capability whose routed rows can\n * be purged as a pack, unlike Tasks' one-run-at-a-time model.\n */\n readonly purgedRecoveryLoopJobs?: ReadonlyArray<LifecycleJob>;\n};\n\n/**\n * A capability installed into a Durable Object lifecycle.\n *\n * Capabilities extending `LifecycleCapability` receive the standard storage,\n * readiness, alarm, event, and routing surface. Host-specific bindings and\n * protocol adapters remain explicit constructor dependencies. Hook parameters\n * carry only phase data; hooks do not run in ambient host context — a\n * capability-held user callback re-enters host context exactly once,\n * through `LifecycleServices.runInHostContext(fn, scope)`.\n *\n * A capability interacts with Lifecycle through exactly three channels:\n * these declared hooks, the `LifecycleServices` surface, and\n * composition-root `set*()` apertures. Any other direct reach in either\n * direction is a design smell.\n *\n * Dispatch contract, hook by hook:\n * - `onRequest` and `onWebSocketUpgrade` are offered in declaration\n * order, the catch-all last; the first capability to return a `Response`\n * claims the request, and a claimed upgrade's socket belongs to that\n * capability for its whole lifetime.\n * - `onWebSocketMessage`/`onWebSocketClose`/`onWebSocketError` are\n * platform wakes, offered in declaration order; return `true` to\n * consume one. Socket ownership is the capability's to determine —\n * keep a private hibernation-attachment namespace and recognize your\n * own sockets by it.\n * - `onRoute` is addressed to one capability by its id; `onJob` is\n * addressed by the due job's owning capability, with Lifecycle owning\n * the queue and the one physical alarm.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport interface DurableObjectCapability<Props extends object = object> {\n /**\n * How this capability claims traffic. Default: `\"selective\"`.\n *\n * A `\"selective\"` capability answers only requests and upgrades it\n * recognizes and declines the rest. A `\"catch-all\"` claims everything\n * offered to the hooks it implements, so Lifecycle always places it\n * last, whenever it was installed, and refuses a second catch-all for\n * the same hook. Catch-alls for disjoint hooks coexist: `WebSockets`\n * claims every upgrade and implements no `onRequest`, so an HTTP\n * catch-all installs beside it. Selective HTTP capabilities target\n * their own routes and run before either.\n */\n readonly claims?: \"selective\" | \"catch-all\";\n\n /** Initialize or recover the capability before the host handles work. */\n onStart?(context: CapabilityStartContext<Props>): MaybePromise<void>;\n\n /**\n * Act as middleware over HTTP requests, ahead of the host's request handler.\n *\n * Return a response to handle the request, or `undefined` to pass it to the\n * next capability and finally the host.\n */\n onRequest?(\n context: CapabilityRequestContext\n ): MaybePromise<Response | undefined | void>;\n\n /**\n * Claim a WebSocket upgrade before the host's legacy connection path.\n *\n * A capability that returns a response owns that socket and its lifetime,\n * including any hibernation attachment it needs to recognize the socket\n * later. Return `undefined` to decline.\n */\n onWebSocketUpgrade?(\n context: CapabilityWebSocketUpgradeContext\n ): MaybePromise<Response | undefined | void>;\n\n /**\n * Handle a platform `webSocketMessage` wake for a socket this capability\n * owns. Return `true` to consume the event; anything else offers it to\n * the next capability and finally the host's legacy path. Ownership is\n * the capability's to determine — typically via its own hibernation\n * attachment namespace.\n */\n onWebSocketMessage?(\n ws: WebSocket,\n message: WSMessage\n ): MaybePromise<boolean | void>;\n\n /** Handle a platform `webSocketClose` wake for an owned socket. */\n onWebSocketClose?(\n ws: WebSocket,\n code: number,\n reason: string,\n wasClean: boolean\n ): MaybePromise<boolean | void>;\n\n /** Handle a platform `webSocketError` wake for an owned socket. */\n onWebSocketError?(\n ws: WebSocket,\n error: unknown\n ): MaybePromise<boolean | void>;\n\n /**\n * Drive one due job this capability pushed into the Lifecycle queue.\n * Return an outcome to reschedule or retain the job; returning nothing\n * completes it.\n *\n * Dispatch must be bounded: the event loop awaits each job inline, so a\n * long-running `onJob` delays every other job on this object. Detach\n * unbounded work (start it, keep durable evidence, return) instead of\n * awaiting it here; a dispatch that outlives the job's hung timeout\n * logs a warning and emits `job:slow_dispatch`.\n */\n onJob?(\n context: LifecycleJobContext\n ): MaybePromise<LifecycleJobOutcome | void>;\n\n /**\n * Observe one job's terminal application failure after retry exhaustion.\n * The returned outcome decides advancement; returning nothing completes\n * the job.\n */\n onJobError?(\n context: LifecycleJobContext,\n error: unknown\n ): MaybePromise<LifecycleJobOutcome | void>;\n\n /**\n * Apply domain policy after the alarm memory-limit circuit breaker\n * records a strike (#1825). Lifecycle has already handled the queue: the\n * executing job and every `recoveryLoop`-flagged job are backed off (or\n * purged when `sealed`). Runs at the outermost alarm frame, post-unwind,\n * best-effort — the isolate resets right after, so keep writes small.\n */\n onMemoryLimit?(context: MemoryLimitContext): MaybePromise<void>;\n\n /** Handle one message routed to this capability identity. */\n onRoute?(context: LifecycleRouteContext): MaybePromise<unknown>;\n\n /** Release live or in-memory resources during explicit host destruction. */\n dispose?(): MaybePromise<void>;\n}\n\n/**\n * Runs ordered lifecycle phases for capabilities installed in a Durable Object.\n *\n * Capabilities are resolved lazily on the first phase and retained for the\n * lifetime of this runner. Startup runs in declaration order.\n * Requests dispatch as a middleware chain: the first capability to return a\n * response handles the request.\n */\nexport class CapabilityRunner<Props extends object = object> {\n readonly #resolveCapabilities: () => Iterable<DurableObjectCapability<Props>>;\n\n #capabilities: ReadonlyArray<DurableObjectCapability<Props>> | undefined;\n #startPromise: Promise<void> | undefined;\n #started = false;\n\n /**\n * Create a lifecycle whose capabilities are resolved immediately before the\n * first phase.\n *\n * @param resolveCapabilities - Returns capabilities in their startup order.\n */\n constructor(\n resolveCapabilities: () => Iterable<DurableObjectCapability<Props>>\n ) {\n this.#resolveCapabilities = resolveCapabilities;\n }\n\n /**\n * Start every capability sequentially.\n *\n * Concurrent callers share one startup attempt. A failed attempt is not\n * cached, allowing the host to retry its complete startup phase.\n *\n * @param context - Properties supplied while resolving the Durable Object.\n */\n async start(context: CapabilityStartContext<Props>): Promise<void> {\n if (this.#started) return;\n\n const pending = this.#startPromise;\n if (pending) {\n await pending;\n return;\n }\n\n const attempt = this.#runStart(context);\n this.#startPromise = attempt;\n try {\n await attempt;\n } catch (error) {\n if (this.#startPromise === attempt) {\n this.#startPromise = undefined;\n }\n throw error;\n }\n }\n\n /**\n * Offer a request to each capability middleware in registration order.\n *\n * @param context - The request entering the Durable Object.\n * @returns The first capability response, or `undefined` when no\n * capability claimed the request.\n */\n async request(\n context: CapabilityRequestContext\n ): Promise<Response | undefined> {\n await this.#ensureReady(\"handle a request\");\n for (const capability of this.#getCapabilities()) {\n const response = await capability.onRequest?.(context);\n if (response !== undefined) return response;\n }\n return undefined;\n }\n\n /**\n * Offer a WebSocket upgrade to each capability in declaration order.\n *\n * @param context - The upgrade request entering the Durable Object.\n * @returns The first capability response, or `undefined` when unclaimed.\n */\n async webSocketUpgrade(\n context: CapabilityWebSocketUpgradeContext\n ): Promise<Response | undefined> {\n await this.#ensureReady(\"handle a WebSocket upgrade\");\n for (const capability of this.#getCapabilities()) {\n const response = await capability.onWebSocketUpgrade?.(context);\n if (response !== undefined) return response;\n }\n return undefined;\n }\n\n /**\n * Offer a platform `webSocketMessage` wake to each capability in\n * declaration order.\n *\n * @returns Whether a capability consumed the event.\n */\n async webSocketMessage(ws: WebSocket, message: WSMessage): Promise<boolean> {\n await this.#ensureReady(\"handle a WebSocket message\");\n for (const capability of this.#getCapabilities()) {\n if ((await capability.onWebSocketMessage?.(ws, message)) === true) {\n return true;\n }\n }\n return false;\n }\n\n /** Offer a platform `webSocketClose` wake to each capability. */\n async webSocketClose(\n ws: WebSocket,\n code: number,\n reason: string,\n wasClean: boolean\n ): Promise<boolean> {\n await this.#ensureReady(\"handle a WebSocket close\");\n for (const capability of this.#getCapabilities()) {\n if (\n (await capability.onWebSocketClose?.(ws, code, reason, wasClean)) ===\n true\n ) {\n return true;\n }\n }\n return false;\n }\n\n /** Offer a platform `webSocketError` wake to each capability. */\n async webSocketError(ws: WebSocket, error: unknown): Promise<boolean> {\n await this.#ensureReady(\"handle a WebSocket error\");\n for (const capability of this.#getCapabilities()) {\n if ((await capability.onWebSocketError?.(ws, error)) === true) {\n return true;\n }\n }\n return false;\n }\n\n /** Find one installed capability by its stable id. */\n async findById(\n capabilityId: string\n ): Promise<DurableObjectCapability<Props> | undefined> {\n await this.#ensureReady(\"dispatch capability work\");\n return this.#getCapabilities().find(\n (candidate) => lifecycleCapabilityId(candidate) === capabilityId\n );\n }\n\n /** Route one message to an installed named capability. */\n async route(\n capabilityId: string,\n context: LifecycleRouteContext\n ): Promise<unknown> {\n await this.#ensureReady(\"route a capability message\");\n const capability = this.#getCapabilities().find(\n (candidate) => lifecycleCapabilityId(candidate) === capabilityId\n );\n if (!capability?.onRoute) {\n throw new Error(\n `Lifecycle capability ${JSON.stringify(capabilityId)} cannot receive routed messages`\n );\n }\n return capability.onRoute(context);\n }\n\n /**\n * Offer a memory-limit strike to every capability, best-effort.\n *\n * Deliberately not gated on startup: a strike can land while startup\n * itself is the work that exceeded the memory limit, and the breaker's\n * policy must still reach capabilities. One capability's failure does not\n * stop the next — the isolate is about to reset either way.\n */\n async memoryLimit(context: MemoryLimitContext): Promise<void> {\n for (const capability of this.#getCapabilities()) {\n try {\n await capability.onMemoryLimit?.(context);\n } catch (error) {\n console.error(\"Lifecycle capability memory-limit policy failed\", error);\n }\n }\n }\n\n /** Dispose installed capabilities in reverse registration order. */\n async dispose(): Promise<void> {\n for (const capability of [...this.#getCapabilities()].reverse()) {\n try {\n await capability.dispose?.();\n } catch (error) {\n console.error(\"Lifecycle capability disposal failed\", error);\n }\n }\n }\n\n async #runStart(context: CapabilityStartContext<Props>): Promise<void> {\n for (const capability of this.#getCapabilities()) {\n await capability.onStart?.(context);\n }\n this.#started = true;\n }\n\n async #ensureReady(operation: string): Promise<void> {\n const pending = this.#startPromise;\n if (pending) await pending;\n if (!this.#started) {\n throw new Error(\n `Cannot ${operation} before the Durable Object lifecycle has started`\n );\n }\n }\n\n #getCapabilities(): ReadonlyArray<DurableObjectCapability<Props>> {\n if (!this.#capabilities) {\n this.#capabilities = Object.freeze([...this.#resolveCapabilities()]);\n }\n return this.#capabilities;\n }\n}\n","/**\n * `DurableObjectState.abort()` accepts an options object newer than our\n * pinned `@cloudflare/workers-types`: `{ retryAlarm?: boolean }`. When\n * `retryAlarm` is false and the abort happens inside an alarm handler, the\n * platform does not retry that alarm (workerd `AbortOptions`,\n * `EXCEPTION_DURABLE_OBJECT_ABORT_NO_RETRY`). It has no effect outside an\n * alarm handler, and runtimes predating the option ignore the extra\n * argument, so passing it is always safe.\n */\ntype AbortWithOptions = (\n reason?: string,\n options?: { retryAlarm?: boolean }\n) => void;\n\n/**\n * Reset the Durable Object instance without the platform retrying the alarm\n * this invocation was handling. Never returns: `abort()` terminates\n * execution.\n */\nexport function abortWithoutAlarmRetry(\n ctx: DurableObjectState,\n reason: string\n): void {\n (ctx.abort as AbortWithOptions)(reason, { retryAlarm: false });\n}\n","/**\n * Durable job queue owned by Lifecycle.\n *\n * One timestamp-ordered table holds every pending job for the Durable\n * Object. A job is a serialisable callback address — owning capability plus\n * function name — with a due time and a payload. Capabilities and the host\n * push jobs through their scoped `LifecycleJobs` surface; Lifecycle's alarm\n * event loop drives due jobs and derives the physical alarm from queue\n * state. Payloads are opaque to the queue.\n */\n\nimport { nanoid } from \"nanoid\";\nimport type { RetryOptions } from \"../retries\";\nimport { SqlError } from \"../sql-error\";\n\n/** Capability id under which host-owned jobs are stored. */\nexport const HOST_JOB_CAPABILITY = \"host\";\n\n/** Seconds before an in-flight single-flight job is treated as hung. */\nconst DEFAULT_HUNG_TIMEOUT_SECONDS = 30;\n\n/** One durable job in the Lifecycle queue. */\nexport type LifecycleJob = {\n /** Unique job id. Stable across reschedules. */\n readonly id: string;\n /** Owning capability id, or `\"host\"`. */\n readonly capability: string;\n /** Serialisable function name the owner dispatches on. */\n readonly fn: string;\n /** Due time in epoch milliseconds. */\n readonly time: number;\n /** Owner-defined payload, JSON round-tripped. */\n readonly payload: unknown;\n /** Retry policy for dispatch, when the pusher supplied one. */\n readonly retry: RetryOptions | undefined;\n /** Whether the job is skipped while a previous run is in flight. */\n readonly singleflight: boolean;\n /** Whether the job suppresses ordinary alarm candidates while pending. */\n readonly exclusive: boolean;\n /** Whether the alarm memory-limit breaker governs this pending job (#1825). */\n readonly recoveryLoop: boolean;\n /** Creation time in epoch seconds. */\n readonly createdAt: number;\n};\n\n/** Options accepted when pushing one job. */\nexport type LifecycleJobPushOptions = {\n /** Serialisable function name the owner dispatches on. */\n readonly fn: string;\n /** Due time in epoch milliseconds. */\n readonly time: number;\n /** Owner-defined payload. Must be JSON-serializable. */\n readonly payload?: unknown;\n /**\n * Stable job id. A push with an existing id replaces that job.\n * Omitted ids are generated.\n */\n readonly id?: string;\n /** Retry policy for dispatch, overriding the queue default. */\n readonly retry?: RetryOptions;\n /** Skip this job while a previous run of it is still in flight. */\n readonly singleflight?: boolean;\n /**\n * Seconds before an in-flight single-flight run is treated as hung, and\n * before any long dispatch triggers the slow-dispatch warning. Default: 30.\n */\n readonly hungTimeoutSeconds?: number;\n /** Suppress ordinary alarm candidates while this job is pending. */\n readonly exclusive?: boolean;\n /**\n * Mark this job as part of a recovery loop that can deterministically\n * exhaust memory. On an alarm memory-limit strike the circuit breaker\n * (#1825) backs off every pending flagged job to the strike's backoff\n * time, and purges them all when it seals at the strike budget — so a\n * doomed loop cannot re-trigger through a sibling row while unrelated\n * jobs stay untouched.\n */\n readonly recoveryLoop?: boolean;\n};\n\n/**\n * What the owner tells Lifecycle after one job ran — the drive result.\n *\n * `undefined` (or no return) completes the job and deletes it.\n * `{ rescheduleAt }` suspends the job until a future time.\n * `\"yield\"` leaves the job due, waking again immediately.\n *\n * A same-id `push()` or `reschedule()` made while the job is dispatching\n * supersedes the drive result: the newer durable intent wins, and the\n * result is quietly discarded. Owners that both push and return outcomes\n * for the same job should derive both from the same durable state so the\n * two always agree.\n */\nexport type LifecycleJobOutcome =\n | undefined\n | { readonly rescheduleAt: number }\n | \"yield\";\n\n/** Context supplied when a job is dispatched to its owner. */\nexport type LifecycleJobContext = {\n /** The due job being executed. */\n readonly job: LifecycleJob;\n /** 1-indexed dispatch attempt within the current alarm invocation. */\n readonly attempt: number;\n};\n\n/** Job-queue access scoped to one owning capability. */\nexport type LifecycleJobs = {\n /**\n * Push one job. A push with an existing id replaces that job — ids are\n * scoped to their owner, so replacing (or colliding with) another\n * owner's job is impossible; a cross-owner id collision throws instead.\n */\n readonly push: (options: LifecycleJobPushOptions) => Promise<LifecycleJob>;\n /** Cancel one owned job. Returns false when no job matched. */\n readonly cancel: (id: string) => Promise<boolean>;\n /** Re-time one owned job. Returns false when no job matched. */\n readonly reschedule: (id: string, time: number) => Promise<boolean>;\n /** Read one owned job. */\n readonly get: (id: string) => LifecycleJob | undefined;\n /** List every owned job, ordered by due time. */\n readonly list: () => LifecycleJob[];\n /**\n * Recompute the physical alarm from queue state without mutating it.\n * Mutations re-arm automatically; use this only to recover a lost alarm\n * for existing jobs (e.g. an idempotent push that deduplicated).\n */\n readonly rearm: () => Promise<void>;\n};\n\n/** @internal Raw `cf_agents_jobs` SQLite row. */\nexport type JobStorageRow = {\n id: string;\n capability: string;\n fn: string;\n time: number;\n payload: string | null;\n retry_options: string | null;\n singleflight: number;\n hung_timeout_seconds: number | null;\n exclusive: number;\n recovery_loop: number;\n running: number;\n execution_started_at: number | null;\n created_at: number;\n};\n\n/** @internal Convert one raw queue row into its public job shape. */\nexport function jobFromRow(row: JobStorageRow): LifecycleJob {\n return {\n id: row.id,\n capability: row.capability,\n fn: row.fn,\n time: row.time,\n payload:\n typeof row.payload === \"string\" ? JSON.parse(row.payload) : undefined,\n retry:\n typeof row.retry_options === \"string\"\n ? (JSON.parse(row.retry_options) as RetryOptions)\n : undefined,\n singleflight: row.singleflight === 1,\n exclusive: row.exclusive === 1,\n recoveryLoop: row.recovery_loop === 1,\n createdAt: row.created_at\n };\n}\n\n/** @internal One row's hung/slow-dispatch threshold in milliseconds. */\nexport function hungTimeoutMs(row: JobStorageRow): number {\n return (row.hung_timeout_seconds ?? DEFAULT_HUNG_TIMEOUT_SECONDS) * 1000;\n}\n\n/** Whether an in-flight single-flight job has crossed its hung timeout. */\nexport function isHungRow(row: JobStorageRow, nowMs: number): boolean {\n return nowMs - (row.execution_started_at ?? 0) >= hungTimeoutMs(row);\n}\n\n/**\n * @internal SQL-backed job queue. Lifecycle owns the single instance; the\n * scoped `LifecycleJobs` surfaces delegate here with a fixed capability id.\n */\nexport class JobQueue {\n readonly #storage: DurableObjectStorage;\n #tableEnsured = false;\n\n constructor(storage: DurableObjectStorage) {\n this.#storage = storage;\n }\n\n #sql<T = JobStorageRow>(\n query: string,\n ...params: (string | number | null)[]\n ): T[] {\n this.#ensureTable();\n try {\n return [...this.#storage.sql.exec(query, ...params)] as T[];\n } catch (cause) {\n throw new SqlError(query, cause);\n }\n }\n\n #ensureTable(): void {\n if (this.#tableEnsured) return;\n this.#storage.sql.exec(`\n CREATE TABLE IF NOT EXISTS cf_agents_jobs (\n id TEXT PRIMARY KEY NOT NULL,\n capability TEXT NOT NULL,\n fn TEXT NOT NULL,\n time INTEGER NOT NULL,\n payload TEXT,\n retry_options TEXT,\n singleflight INTEGER NOT NULL DEFAULT 0,\n hung_timeout_seconds INTEGER,\n exclusive INTEGER NOT NULL DEFAULT 0,\n recovery_loop INTEGER NOT NULL DEFAULT 0,\n running INTEGER NOT NULL DEFAULT 0,\n execution_started_at INTEGER,\n created_at INTEGER NOT NULL DEFAULT (unixepoch())\n ) WITHOUT ROWID`);\n this.#tableEnsured = true;\n }\n\n push(capability: string, options: LifecycleJobPushOptions): LifecycleJob {\n if (!Number.isFinite(options.time) || options.time < 0) {\n throw new Error(`Invalid job time: ${String(options.time)}`);\n }\n if (typeof options.fn !== \"string\" || options.fn.trim() === \"\") {\n throw new Error(\"Jobs require a non-empty fn\");\n }\n const id = options.id ?? nanoid(9);\n // Job ids are scoped to their owner, like every other queue verb: a\n // same-id push replaces only the pusher's own job (the conflict update\n // is a no-op against another owner's row, surfaced as the ownership\n // error below), and it clears any in-flight dispatch marker so this\n // newer durable intent wins over a concurrently returned drive result.\n this.#sql(\n `INSERT INTO cf_agents_jobs\n (id, capability, fn, time, payload, retry_options, singleflight,\n hung_timeout_seconds, exclusive, recovery_loop, running,\n execution_started_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, NULL)\n ON CONFLICT(id) DO UPDATE SET\n fn = excluded.fn,\n time = excluded.time,\n payload = excluded.payload,\n retry_options = excluded.retry_options,\n singleflight = excluded.singleflight,\n hung_timeout_seconds = excluded.hung_timeout_seconds,\n exclusive = excluded.exclusive,\n recovery_loop = excluded.recovery_loop,\n running = 0,\n execution_started_at = NULL\n WHERE cf_agents_jobs.capability = excluded.capability`,\n id,\n capability,\n options.fn,\n Math.floor(options.time),\n options.payload === undefined ? null : JSON.stringify(options.payload),\n options.retry ? JSON.stringify(options.retry) : null,\n options.singleflight ? 1 : 0,\n options.hungTimeoutSeconds ?? null,\n options.exclusive ? 1 : 0,\n options.recoveryLoop ? 1 : 0\n );\n const job = this.get(capability, id);\n if (!job) {\n const owner = this.#sql<{ capability: string }>(\n \"SELECT capability FROM cf_agents_jobs WHERE id = ?\",\n id\n )[0]?.capability;\n throw new Error(\n owner !== undefined\n ? `Job id ${JSON.stringify(id)} already belongs to ` +\n `${JSON.stringify(owner)}; job ids are scoped to their owner`\n : `Failed to persist job ${id}`\n );\n }\n return job;\n }\n\n cancel(capability: string, id: string): boolean {\n const existing = this.#sql(\n \"SELECT id FROM cf_agents_jobs WHERE id = ? AND capability = ?\",\n id,\n capability\n );\n if (existing.length === 0) return false;\n this.#sql(\n \"DELETE FROM cf_agents_jobs WHERE id = ? AND capability = ?\",\n id,\n capability\n );\n return true;\n }\n\n reschedule(capability: string, id: string, time: number): boolean {\n if (!Number.isFinite(time) || time < 0) {\n throw new Error(`Invalid job time: ${String(time)}`);\n }\n const existing = this.#sql(\n \"SELECT id FROM cf_agents_jobs WHERE id = ? AND capability = ?\",\n id,\n capability\n );\n if (existing.length === 0) return false;\n this.#sql(\n `UPDATE cf_agents_jobs\n SET time = ?, running = 0, execution_started_at = NULL\n WHERE id = ? AND capability = ?`,\n Math.floor(time),\n id,\n capability\n );\n return true;\n }\n\n get(capability: string, id: string): LifecycleJob | undefined {\n const rows = this.#sql(\n \"SELECT * FROM cf_agents_jobs WHERE id = ? AND capability = ?\",\n id,\n capability\n );\n return rows[0] ? jobFromRow(rows[0]) : undefined;\n }\n\n list(capability: string): LifecycleJob[] {\n return this.#sql(\n \"SELECT * FROM cf_agents_jobs WHERE capability = ? ORDER BY time ASC\",\n capability\n ).map(jobFromRow);\n }\n\n /** Raw due rows at `nowMs`, ordered by due time. */\n due(nowMs: number): JobStorageRow[] {\n return this.#sql(\n \"SELECT * FROM cf_agents_jobs WHERE time <= ? ORDER BY time ASC\",\n Math.floor(nowMs)\n );\n }\n\n /** One job's current row when it still exists and is still due. */\n dueRow(id: string, nowMs: number): JobStorageRow | undefined {\n return this.#sql(\n \"SELECT * FROM cf_agents_jobs WHERE id = ? AND time <= ?\",\n id,\n Math.floor(nowMs)\n )[0];\n }\n\n markRunning(id: string, nowMs: number): void {\n this.#sql(\n `UPDATE cf_agents_jobs\n SET running = 1, execution_started_at = ?\n WHERE id = ?`,\n Math.floor(nowMs),\n id\n );\n }\n\n clearRunning(id: string): void {\n this.#sql(\n `UPDATE cf_agents_jobs\n SET running = 0, execution_started_at = NULL\n WHERE id = ?`,\n id\n );\n }\n\n delete(id: string): void {\n this.#sql(\"DELETE FROM cf_agents_jobs WHERE id = ?\", id);\n }\n\n /**\n * Unguarded retime for the alarm memory-limit breaker's backoff: the\n * platform-failure path clears the dispatch marker before the breaker\n * runs, so the guarded {@link applyOutcome} would no-op — and the\n * breaker's backoff must land regardless, it is protecting the object.\n */\n retime(id: string, time: number): void {\n this.#sql(\n `UPDATE cf_agents_jobs\n SET time = ?, running = 0, execution_started_at = NULL\n WHERE id = ?`,\n Math.floor(time),\n id\n );\n }\n\n /**\n * Back off every pending recovery-loop job that would fire before the\n * breaker's backoff time (#1825), so a doomed loop's sibling rows cannot\n * re-trigger it on the next wake. Unguarded like {@link retime}: the\n * breaker's backoff must land regardless of dispatch markers.\n */\n delayRecoveryLoopJobs(time: number): void {\n this.#sql(\n `UPDATE cf_agents_jobs\n SET time = ?, running = 0, execution_started_at = NULL\n WHERE recovery_loop = 1 AND time <= ?`,\n Math.floor(time),\n Math.floor(time)\n );\n }\n\n /**\n * Read every recovery-loop job before breaker sealing. The memory-limit\n * policy phase uses this snapshot after the rows are purged so routed owners\n * can terminalize their own durable recovery state.\n */\n recoveryLoopJobs(): LifecycleJob[] {\n return this.#sql(\n \"SELECT * FROM cf_agents_jobs WHERE recovery_loop = 1 ORDER BY time ASC\"\n ).map(jobFromRow);\n }\n\n /**\n * Purge every recovery-loop job when the breaker seals at its strike\n * budget (#1825). Unrelated jobs are untouched.\n */\n purgeRecoveryLoopJobs(): void {\n this.#sql(\"DELETE FROM cf_agents_jobs WHERE recovery_loop = 1\");\n }\n\n /**\n * Apply one drive result, guarded on the dispatch marker: every driven\n * job carries `running = 1` for the duration of its dispatch, and a\n * same-id `push()` or `reschedule()` made meanwhile clears it. A cleared\n * marker means newer durable intent exists, so the outcome quietly\n * defers to it instead of deleting or retiming the fresher job.\n */\n applyOutcome(id: string, outcome: LifecycleJobOutcome): void {\n if (outcome === undefined) {\n this.#sql(\"DELETE FROM cf_agents_jobs WHERE id = ? AND running = 1\", id);\n return;\n }\n if (outcome === \"yield\") {\n this.clearRunning(id);\n return;\n }\n if (\n typeof outcome === \"object\" &&\n Number.isFinite(outcome.rescheduleAt) &&\n outcome.rescheduleAt >= 0\n ) {\n this.#sql(\n `UPDATE cf_agents_jobs\n SET time = ?, running = 0, execution_started_at = NULL\n WHERE id = ? AND running = 1`,\n Math.floor(outcome.rescheduleAt),\n id\n );\n return;\n }\n throw new Error(`Invalid job outcome for ${id}`);\n }\n\n /**\n * The next physical alarm time derived from queue state, or `null` when\n * the queue holds nothing to wake for.\n *\n * Exclusive jobs suppress ordinary candidates. An ordinary candidate is\n * the earliest ready job clamped to the future (overdue rows survive\n * restarts and must re-fire immediately), merged with the earliest\n * hung-timeout recheck for in-flight single-flight jobs.\n */\n nextAlarmTime(nowMs: number): number | null {\n const exclusive = this.#sql<{ time: number | null }>(\n \"SELECT MIN(time) AS time FROM cf_agents_jobs WHERE exclusive = 1\"\n );\n if (exclusive[0]?.time !== null && exclusive[0]?.time !== undefined) {\n return exclusive[0].time;\n }\n\n const now = Math.floor(nowMs);\n let candidate: number | null = null;\n\n const ready = this.#sql<{ time: number | null }>(\n `SELECT MIN(time) AS time FROM cf_agents_jobs\n WHERE singleflight = 0\n OR running = 0\n OR coalesce(execution_started_at, 0) + coalesce(hung_timeout_seconds, ?) * 1000 <= ?`,\n DEFAULT_HUNG_TIMEOUT_SECONDS,\n now\n );\n if (ready[0]?.time !== null && ready[0]?.time !== undefined) {\n candidate = Math.max(ready[0].time, now + 1);\n }\n\n const inFlight = this.#sql<{ recheck: number | null }>(\n `SELECT MIN(coalesce(execution_started_at, 0) + coalesce(hung_timeout_seconds, ?) * 1000) AS recheck\n FROM cf_agents_jobs\n WHERE singleflight = 1\n AND running = 1\n AND coalesce(execution_started_at, 0) + coalesce(hung_timeout_seconds, ?) * 1000 > ?`,\n DEFAULT_HUNG_TIMEOUT_SECONDS,\n DEFAULT_HUNG_TIMEOUT_SECONDS,\n now\n );\n const recheck = inFlight[0]?.recheck;\n if (recheck !== null && recheck !== undefined) {\n candidate = candidate === null ? recheck : Math.min(candidate, recheck);\n }\n\n return candidate;\n }\n}\n","/**\n * Alarm event loop for the Lifecycle job queue.\n *\n * The driver owns everything that happens when the physical alarm fires:\n * the deadman pre-arm, driving due jobs in due order (single-flight skip and\n * hung recovery, per-job retries, platform-failure deferral, terminal\n * failure hooks), the backlog warning, and the alarm memory-limit circuit\n * breaker (#1825). Lifecycle wires it to the host and capabilities through\n * the narrow {@link JobDriverOptions} contract and keeps only the alarm\n * entry point itself.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport {\n isDurableObjectCodeUpdateReset,\n isDurableObjectMemoryLimitReset,\n isPlatformFailure,\n tryN\n} from \"../retries\";\nimport type { MemoryLimitContext } from \"./capability-runner\";\nimport {\n hungTimeoutMs,\n isHungRow,\n jobFromRow,\n type JobQueue,\n type JobStorageRow,\n type LifecycleJob,\n type LifecycleJobContext,\n type LifecycleJobOutcome\n} from \"./job-queue\";\n\n/** Default consecutive memory-limit strikes tolerated before sealing. */\nconst DEFAULT_MAX_ALARM_MEMORY_LIMIT_STRIKES = 3;\n\n/** Durable storage key for the alarm memory-limit strike counter (#1825). */\nconst OOM_ALARM_STRIKES_KEY = \"cf_agents:oom_alarm_strikes\";\n\n/** Default retry policy applied to jobs pushed without one. */\nconst DEFAULT_JOB_RETRY = {\n maxAttempts: 3,\n baseDelayMs: 100,\n maxDelayMs: 3000\n} as const;\n\n/** Due jobs for one capability above this count log a backlog warning. */\nconst JOB_BACKLOG_WARNING_THRESHOLD = 10;\n\n/**\n * Deadman pre-arm delay: armed before the event loop drives due jobs so an\n * isolate death mid-drive still wakes this object to resume its queue.\n */\nconst DEADMAN_ALARM_DELAY_MS = 30_000;\n\n/** The dispatch hooks one job owner exposes to the driver. */\nexport type JobDispatch = {\n readonly onJob: (\n context: LifecycleJobContext\n ) => Promise<LifecycleJobOutcome | void>;\n readonly onJobError?: (\n context: LifecycleJobContext,\n error: unknown\n ) => Promise<LifecycleJobOutcome | void>;\n};\n\n/** What the driver needs from its owning Lifecycle. */\nexport type JobDriverOptions = {\n readonly queue: JobQueue;\n readonly storage: DurableObjectStorage;\n /** Live teardown flag: once true, stop touching storage mid-phase. */\n readonly disabled: () => boolean;\n /** Resolve a job owner to its dispatch hooks, `undefined` when missing. */\n readonly resolveDispatch: (owner: string) => Promise<JobDispatch | undefined>;\n /** Consecutive memory-limit strikes tolerated before sealing (#1825). */\n readonly maxMemoryLimitStrikes: () => number | undefined;\n /** Capability and host domain policy applied on each memory-limit strike. */\n readonly onMemoryLimit: (context: MemoryLimitContext) => void | Promise<void>;\n /** Best-effort lifecycle telemetry. */\n readonly emit: (type: string, payload: unknown) => void;\n /** Recompute the physical alarm from queue state. */\n readonly rearm: () => Promise<void>;\n /**\n * Schedule an isolate reset after a memory-limit strike is fully\n * recorded, suppressing any retry of the current alarm. Returns\n * immediately; the reset lands after the invocation settles, and the next\n * wake is the backoff alarm the strike armed.\n */\n readonly reset: (reason: string) => void;\n};\n\n/** The dispatch an async flow belongs to while an alarm drives it. */\ntype AlarmScope = { readonly executing: JobStorageRow | undefined };\n\n/**\n * Carries the row a platform failure escaped from out to `runAlarm`'s catch,\n * across the rethrow from `#driveJob`. Attribution must not live in a shared\n * instance field: overlapping `alarm()` invocations (a deadman or the\n * platform's own re-fire racing a still-running invocation) dispatch jobs\n * concurrently, and a field would let a later dispatch overwrite the row an\n * earlier one is still unwinding for.\n */\nclass AttributedPlatformFailure {\n constructor(\n readonly row: JobStorageRow,\n readonly cause: unknown\n ) {}\n}\n\n/** One recorded memory-limit strike, shared by every flow that observed it. */\ntype MemoryLimitStrike = {\n readonly strikes: number;\n readonly limit: number;\n readonly sealed: boolean;\n /** The backoff wake time armed for an unsealed strike. */\n readonly nextTime: number | undefined;\n /** Recovery-loop jobs purged by a sealing strike, snapshotted beforehand. */\n readonly purgedRecoveryLoopJobs: LifecycleJob[] | undefined;\n};\n\n/** @internal Drives the job queue when the Durable Object alarm fires. */\nexport class JobDriver {\n readonly #options: JobDriverOptions;\n /**\n * Ambient dispatch identity for `trackAlarmWork`. Read through the async\n * flow rather than an instance slot so attribution stays correct when\n * alarm invocations overlap (tests drive `alarm()` by hand while the\n * platform fires its own).\n */\n readonly #alarmScope = new AsyncLocalStorage<AlarmScope>();\n #alarmsInFlight = 0;\n /**\n * Work handed off by alarm-driven jobs that has not settled yet. While it\n * is non-empty the alarm domain is not quiescent, so a clean alarm must not\n * clear the strike counter: a still-running handoff may yet report the\n * memory reset that alarm started.\n */\n readonly #outstandingAlarmWork = new Set<Promise<unknown>>();\n /**\n * The strike being recorded for the current memory-limit event. One reset\n * is often observed by several flows (an in-alarm job plus handed-off work,\n * or several handoffs awaiting the same condemned storage); they share this\n * record so the counter moves once per event. Cleared by a clean,\n * quiescent classification.\n */\n #strike: Promise<MemoryLimitStrike> | undefined;\n /**\n * Once a strike has been fully recorded in this isolate, no later\n * settlement may clear the durable counter — a slower, unrelated clean\n * sibling finishing after the strike (but before the isolate reset it\n * scheduled actually lands) must not erase what was just recorded. The\n * isolate reset always follows a recorded strike, so the next genuinely\n * clean cycle runs in a fresh isolate with a fresh `JobDriver` and this\n * flag back at its default; there is no cross-isolate state to reset.\n */\n #strikeRecordedThisIsolate = false;\n\n constructor(options: JobDriverOptions) {\n this.#options = options;\n }\n\n /**\n * Run one alarm invocation: initialize the lifecycle, drive due jobs, run\n * the host's alarm callback, and re-arm the physical alarm from queue\n * state — all inside the alarm memory-limit circuit breaker (#1825). A\n * memory-limit reset that propagates here is intercepted — every other\n * error re-throws unchanged so platform alarm-retry semantics hold — and\n * broken from this outermost frame, where the heavy turn has unwound and\n * small writes can land. Initialization runs inside the breaker because a\n * severe reset can be thrown before any job runs (boot hydration, #1825);\n * left unhandled it would re-throw to the platform, which auto-retries\n * the alarm forever.\n */\n async runAlarm(\n initialize: () => Promise<void>,\n runHostAlarm: () => Promise<void>\n ): Promise<void> {\n this.#alarmsInFlight++;\n // Only a clean pass (no memory-limit reset seen by this invocation\n // itself) is ever eligible to trigger the quiescence-clear check below —\n // a pass that just recorded a strike must not immediately re-check\n // quiescence and undo what it just set. Reaching quiescence again is a\n // job for some LATER, genuinely clean invocation or handoff settlement.\n let clean = false;\n try {\n try {\n await initialize();\n await this.#driveDueJobs();\n await this.#alarmScope.run({ executing: undefined }, runHostAlarm);\n clean = true;\n } catch (error) {\n // A platform failure from #driveJob carries its row out of the\n // rethrow; anything else (initialize/runHostAlarm) has no job to\n // attribute. Unwrap either way before classifying the real error.\n const attributed = error instanceof AttributedPlatformFailure;\n const cause = attributed ? error.cause : error;\n if (!isDurableObjectMemoryLimitReset(cause)) {\n throw attributed ? cause : error;\n }\n await this.#handleMemoryLimitReset(\n cause,\n attributed ? error.row : undefined\n );\n return;\n }\n } finally {\n // Re-check quiescence exactly when this alarm's own \"in flight\" status\n // ends, using the freshest counters — one of the two points (the\n // other is a handoff settling, see #settleAlarmWork) that must not be\n // skipped: whichever transition happens last is what performs the\n // clear, and each transition re-evaluates both conditions itself\n // rather than trusting a stale snapshot taken before the other side's\n // own transition landed.\n this.#alarmsInFlight--;\n if (clean) await this.#clearMemoryLimitStrikesWhenQuiescent();\n }\n await this.#options.rearm();\n }\n\n /**\n * Keep work a job handed off at a bounded return inside this alarm's\n * memory-limit breaker domain (#1825). The alarm itself returns promptly,\n * so other jobs stay live; the handoff is classified when it settles. A\n * memory-limit reset it reports records a strike against the job that\n * handed it off, exactly as an in-alarm reset would. Strikes clear only\n * once no handed-off work is outstanding and the last of it settled clean.\n *\n * @returns True when called from an alarm-driven dispatch or the host\n * alarm hook; false otherwise, in which case nothing is tracked. Tracking\n * the same promise again (a claim-backstop wake for an attempt already\n * handed off) is a no-op.\n */\n trackAlarmWork(work: Promise<unknown>): boolean {\n const scope = this.#alarmScope.getStore();\n if (!scope) return false;\n if (this.#outstandingAlarmWork.has(work)) return true;\n this.#outstandingAlarmWork.add(work);\n void work.then(\n () => this.#settleAlarmWork(work, undefined, scope.executing),\n (error) => this.#settleAlarmWork(work, error, scope.executing)\n );\n return true;\n }\n\n async #settleAlarmWork(\n work: Promise<unknown>,\n error: unknown,\n executing: JobStorageRow | undefined\n ): Promise<void> {\n try {\n if (this.#options.disabled()) return;\n if (isDurableObjectMemoryLimitReset(error)) {\n // Still outstanding while the strike is recorded, so an alarm\n // finishing concurrently cannot clear it from underneath.\n await this.#handleMemoryLimitReset(error, executing);\n return;\n }\n } finally {\n this.#outstandingAlarmWork.delete(work);\n }\n // This settle is itself a quiescence transition — re-check freshly\n // rather than trusting whether an alarm looked in flight before this\n // delete landed (see runAlarm's matching call for why neither side may\n // skip its own check).\n await this.#clearMemoryLimitStrikesWhenQuiescent();\n }\n\n /**\n * Clear the strike counter once the alarm domain is fully quiescent: no\n * alarm invocation in flight, no handed-off work outstanding, and no\n * strike recorded in this isolate that a fresh isolate hasn't yet\n * superseded. Called at every transition that could make either counter\n * newly zero (an alarm ending, a handoff settling) — each call re-reads\n * both fresh, so whichever transition happens last is the one that\n * performs the clear. Idempotent: redundant calls no-op.\n */\n async #clearMemoryLimitStrikesWhenQuiescent(): Promise<void> {\n if (this.#alarmsInFlight > 0) return;\n if (this.#outstandingAlarmWork.size > 0) return;\n if (this.#strikeRecordedThisIsolate) return;\n this.#strike = undefined;\n await this.#clearMemoryLimitStrikes();\n }\n\n /** Drive every due job once, in due-time order. */\n async #driveDueJobs(): Promise<void> {\n const nowMs = Date.now();\n const due = this.#options.queue.due(nowMs);\n if (due.length === 0) return;\n this.#warnBacklog(due);\n\n // Deadman pre-arm: before driving any job, arm a fallback alarm so a\n // death mid-drive that the platform cannot retry (or that swallows its\n // error) still wakes this object to resume. The normal re-arm at the end\n // of the alarm phase overwrites it.\n if (!this.#options.disabled()) {\n await this.#options.storage.setAlarm(nowMs + DEADMAN_ALARM_DELAY_MS);\n }\n\n for (const stale of due) {\n // Host teardown mid-phase: its storage is gone, stop touching it.\n if (this.#options.disabled()) return;\n\n // Refetch before claiming: an earlier dispatch in this loop may have\n // pushed, rescheduled, or cancelled this job since the due snapshot\n // was taken. A row that is gone or no longer due belongs to that\n // newer intent — skip it (the final re-arm owns any future wake). A\n // row that changed but is still due dispatches with its fresh data.\n const row = this.#options.queue.dueRow(stale.id, nowMs);\n if (!row) continue;\n\n if (row.singleflight === 1 && row.running === 1) {\n if (!isHungRow(row, nowMs)) {\n console.warn(\n `Skipping job ${row.id}: previous execution still running`\n );\n continue;\n }\n console.warn(\n `Forcing reset of hung job ${row.id} (started ${Math.round(\n (nowMs - (row.execution_started_at ?? 0)) / 1000\n )}s ago)`\n );\n }\n // Every dispatch is marked, not just single-flight: the marker is\n // what lets a same-id push made mid-dispatch supersede the returned\n // drive result (see JobQueue.applyOutcome).\n this.#options.queue.markRunning(row.id, nowMs);\n\n await this.#driveJob(row);\n }\n }\n\n /** Dispatch one due row to its owner with retry and failure policy. */\n async #driveJob(row: JobStorageRow): Promise<void> {\n const { queue, resolveDispatch, disabled } = this.#options;\n const job = jobFromRow(row);\n const dispatch = await resolveDispatch(row.capability);\n if (!dispatch) {\n console.error(\n `No installed capability or host handler for job ${row.id} ` +\n `(owner ${JSON.stringify(row.capability)}); dropping it`\n );\n queue.delete(row.id);\n return;\n }\n\n const maxAttempts = job.retry?.maxAttempts ?? DEFAULT_JOB_RETRY.maxAttempts;\n\n // Dispatch must be bounded: the drive loop awaits each job inline, so\n // one long dispatch delays every other job on this object. The queue\n // cannot safely abandon owner code, so the contract is enforced by\n // visibility — a dispatch that outlives the job's hung timeout warns\n // loudly and emits telemetry naming the owner.\n const slowWatchdog = setTimeout(() => {\n const seconds = Math.round(hungTimeoutMs(row) / 1000);\n console.warn(\n `Job ${row.id} (${row.capability}/${row.fn}) has been dispatching ` +\n `for over ${seconds}s. Long dispatches starve every other job on ` +\n `this object; onJob must detach unbounded work and return.`\n );\n try {\n this.#options.emit(\"job:slow_dispatch\", {\n capability: row.capability,\n fn: row.fn,\n id: row.id,\n thresholdMs: hungTimeoutMs(row)\n });\n } catch {\n // telemetry never blocks the dispatch\n }\n }, hungTimeoutMs(row));\n\n let outcome: LifecycleJobOutcome | void;\n try {\n outcome = await this.#alarmScope.run({ executing: row }, () =>\n tryN(maxAttempts, (attempt) => dispatch.onJob({ job, attempt }), {\n baseDelayMs: job.retry?.baseDelayMs ?? DEFAULT_JOB_RETRY.baseDelayMs,\n maxDelayMs: job.retry?.maxDelayMs ?? DEFAULT_JOB_RETRY.maxDelayMs,\n // In-process retries are futile on a superseded isolate (code\n // never reloads mid-invocation) and on a memory-limit reset (the\n // isolate is condemned, and a retry can read half-claimed state\n // as \"nothing to do\", converting the reset into a silent success\n // that the breaker never sees). Defer both to the alarm boundary.\n shouldRetry: (error) =>\n !isDurableObjectCodeUpdateReset(error) &&\n !isDurableObjectMemoryLimitReset(error)\n })\n );\n } catch (error) {\n if (disabled()) return;\n if (isPlatformFailure(error)) {\n // Platform-class failure: preserve the job and re-throw so the\n // platform retries a fresh invocation (or the memory-limit breaker\n // engages at the alarm boundary). Best-effort dispatch-marker reset\n // so the preserved job is not mistaken for one still in flight (and\n // a single-flight job does not wait out its hung timeout first).\n try {\n queue.clearRunning(row.id);\n } catch {\n // the hung timeout eventually recovers the flag\n }\n console.warn(\n `Deferring job ${row.id} to a fresh invocation after a ` +\n `platform failure; the job is preserved.`\n );\n // Carry the row out with the error rather than through a shared\n // field: an overlapping alarm's own #driveJob may already be\n // dispatching a different row by the time this unwinds to\n // runAlarm's catch.\n throw new AttributedPlatformFailure(row, error);\n }\n // Application failure after retry exhaustion: the owner observes it\n // and decides advancement; default is completion.\n try {\n outcome = await dispatch.onJobError?.(\n { job, attempt: maxAttempts },\n error\n );\n } catch (hookError) {\n console.error(`Job failure hook threw for ${row.id}`, hookError);\n }\n } finally {\n clearTimeout(slowWatchdog);\n }\n\n if (disabled()) return;\n queue.applyOutcome(row.id, outcome ?? undefined);\n }\n\n #warnBacklog(due: ReadonlyArray<JobStorageRow>): void {\n const counts = new Map<string, number>();\n for (const row of due) {\n counts.set(row.capability, (counts.get(row.capability) ?? 0) + 1);\n }\n for (const [owner, count] of counts) {\n if (count < JOB_BACKLOG_WARNING_THRESHOLD) continue;\n try {\n console.warn(\n `Processing ${count} due jobs for ${JSON.stringify(owner)} ` +\n `in a single alarm cycle. This usually means one-shot jobs are ` +\n `pushed repeatedly without a stable id.`\n );\n this.#options.emit(\"job:backlog_warning\", {\n capability: owner,\n count\n });\n } catch {\n // warning emission never blocks job processing\n }\n }\n }\n\n /**\n * Clear the durable memory-limit strike counter after a clean alarm so the\n * breaker counts CONSECUTIVE resets rather than lifetime ones (#1825).\n * Reads first and only writes when a strike is recorded. Best-effort.\n */\n async #clearMemoryLimitStrikes(): Promise<void> {\n const { storage } = this.#options;\n try {\n const prior = await storage.get<number>(OOM_ALARM_STRIKES_KEY);\n if (typeof prior === \"number\" && prior > 0) {\n await storage.delete(OOM_ALARM_STRIKES_KEY);\n }\n } catch {\n // a stale strike only costs one extra tolerated spike later\n }\n }\n\n /**\n * Alarm-boundary circuit breaker for Durable Object memory-limit resets\n * (#1825). Unhandled, the platform would auto-retry the alarm forever,\n * re-running the doomed work each cycle. A durable strike counter\n * tolerates a few consecutive resets — backing off the executing job and\n * every pending recovery-loop job so the retry is not a hot loop — then\n * seals: those jobs are purged and the capability + host memory-limit\n * policy hooks run.\n *\n * One reset is one event even when several flows observe it. The strike\n * is recorded once per event ({@link #recordMemoryLimitStrike}); every\n * observer then applies the per-job policy for the job it belongs to, and\n * the first observer finishes the event by re-arming, syncing, and\n * resetting the isolate. Each step is best-effort: even these small writes\n * can OOM, but swallowing still halts the platform's auto-retry, and a\n * later wake re-arms legitimate work.\n */\n async #handleMemoryLimitReset(\n error: unknown,\n executing: JobStorageRow | undefined\n ): Promise<void> {\n const { queue } = this.#options;\n const first = this.#strike === undefined;\n // Set before the first await below: closes the window as tightly as\n // possible against a still-outstanding clean sibling reaching quiescence\n // and clearing what this event is about to record.\n this.#strikeRecordedThisIsolate = true;\n this.#strike ??= this.#recordMemoryLimitStrike(error);\n const strike = await this.#strike;\n\n try {\n if (executing) {\n if (strike.sealed) {\n queue.delete(executing.id);\n } else if (strike.nextTime !== undefined) {\n queue.retime(executing.id, strike.nextTime);\n }\n }\n } catch {\n // best-effort at a failure boundary\n }\n\n try {\n await this.#options.onMemoryLimit({\n sealed: strike.sealed,\n nextTime: strike.nextTime,\n executing: executing ? jobFromRow(executing) : undefined,\n purgedRecoveryLoopJobs: first\n ? strike.purgedRecoveryLoopJobs\n : undefined\n });\n } catch {\n // best-effort domain policy; the purge above already broke the loop\n }\n\n if (!first) return;\n\n // Re-arm so unrelated work continues. Wrapped because it can itself OOM;\n // if it does, the next external wake re-arms.\n try {\n await this.#options.rearm();\n } catch {\n // best-effort\n }\n\n // Finish on a fresh isolate: the strike is durable and the backoff alarm\n // owns the next wake, so schedule a reset to reclaim the memory\n // footprint instead of limping on in the pressured isolate. Sync first —\n // a reset cancels unconfirmed writes, and the strike/backoff writes must\n // land. If any of this fails, fall through to the swallow-and-return\n // exit, which still halts the platform's alarm auto-retry.\n try {\n await this.#options.storage.sync();\n this.#options.reset(\n `Alarm memory-limit strike ${strike.strikes}/${strike.limit}${strike.sealed ? \" (sealed)\" : \"\"}; resetting isolate (#1825)`\n );\n } catch {\n // best-effort\n }\n }\n\n /**\n * Record one strike durably and apply the queue-wide policy that belongs\n * to the event rather than to any one job: recovery-loop rows back off (or\n * purge) as a pack, a sealing strike resets the counter, and the event is\n * emitted once.\n */\n async #recordMemoryLimitStrike(error: unknown): Promise<MemoryLimitStrike> {\n const { queue, storage } = this.#options;\n\n let strikes = 1;\n try {\n const prior = await storage.get<number>(OOM_ALARM_STRIKES_KEY);\n strikes = (typeof prior === \"number\" ? prior : 0) + 1;\n await storage.put(OOM_ALARM_STRIKES_KEY, strikes);\n } catch {\n // even the strike write OOMed; still progress toward sealing\n }\n\n const limit =\n this.#options.maxMemoryLimitStrikes() ??\n DEFAULT_MAX_ALARM_MEMORY_LIMIT_STRIKES;\n const sealed = strikes >= limit;\n console.error(\n `Alarm hit a Durable Object memory-limit reset (strike ${strikes}/${limit}` +\n `${sealed ? \", sealing recovery\" : \", will retry with backoff\"}). ` +\n \"Breaking the platform alarm-retry loop (#1825).\",\n error instanceof Error ? error.message : String(error)\n );\n\n const nextTime = sealed\n ? undefined\n : Date.now() + Math.min(300, 30 * strikes) * 1000;\n // Capture routed ownership before sealing deletes the rows. Domain policy\n // runs afterward, when the loop is already broken, and uses this snapshot\n // only to terminalize durable state owned outside the alarm host.\n let purgedRecoveryLoopJobs: LifecycleJob[] | undefined;\n try {\n if (sealed) purgedRecoveryLoopJobs = queue.recoveryLoopJobs();\n } catch {\n // best-effort at a failure boundary\n }\n\n try {\n // Recovery-loop rows travel as a pack: a doomed loop's sibling rows\n // would re-trigger it on the next wake, so they back off (or purge)\n // together with the row that struck.\n if (sealed) {\n queue.purgeRecoveryLoopJobs();\n } else if (nextTime !== undefined) {\n queue.delayRecoveryLoopJobs(nextTime);\n }\n } catch {\n // best-effort at a failure boundary\n }\n\n if (sealed) {\n try {\n await storage.delete(OOM_ALARM_STRIKES_KEY);\n } catch {\n // best-effort counter reset\n }\n }\n\n try {\n this.#options.emit(\"alarm:memory_limit_reset\", {\n strikes,\n limit,\n sealed,\n error: error instanceof Error ? error.message : String(error)\n });\n } catch {\n // event emission is non-critical\n }\n\n return { strikes, limit, sealed, nextTime, purgedRecoveryLoopJobs };\n }\n}\n","// Internal helpers for classifying WebSocket transport errors.\n// Not re-exported from the package entry point; imported by `index.ts` and\n// exercised directly by `tests/transport-errors.test.ts`.\n\n/** Standard `WebSocket.readyState` values. */\nconst CLOSING = 2;\nconst CLOSED = 3;\n\n/**\n * A retryable transport-teardown error (\"Network connection lost\" /\n * \"WebSocket peer disconnected\") that fires on a connection which is already\n * CLOSING/CLOSED is just the socket going away during or right after the close\n * handshake - not an application error. Surfacing it via `onError` spams logs\n * on every abrupt client disconnect, and even on clean closes when the peer\n * tears down its transport before our reciprocal Close frame lands. Suppress\n * it in that specific case only; genuine mid-connection (OPEN) errors still\n * reach `onError`.\n *\n * Detection prefers the structured `retryable` flag over message text so it\n * stays correct across `enhanced-error-serialization` (compat date\n * >= 2026-04-21), with a substring fallback for older error shapes.\n */\nexport function isBenignTeardownError(\n ws: { readyState?: number },\n error: unknown\n): boolean {\n const state = ws.readyState;\n if (state !== CLOSING && state !== CLOSED) return false;\n if (typeof error !== \"object\" || error === null) return false;\n const typed = error as { retryable?: boolean; message?: unknown };\n if (typed.retryable === true) return true;\n const message = typeof typed.message === \"string\" ? typed.message : \"\";\n return /Network connection lost|WebSocket peer disconnected/i.test(message);\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { DurableObject } from \"cloudflare:workers\";\n\nimport { publishDiagnosticsEvent } from \"../observability/diagnostics\";\nimport {\n CapabilityRunner,\n type DurableObjectCapability,\n type LifecycleEvent,\n type LifecycleEventSink\n} from \"./capability-runner\";\nimport { abortWithoutAlarmRetry } from \"./abort\";\nimport { JobDriver, type JobDispatch } from \"./job-driver\";\nimport {\n HOST_JOB_CAPABILITY,\n JobQueue,\n type LifecycleJobs,\n type LifecycleJobPushOptions\n} from \"./job-queue\";\nimport {\n bindLifecycleCapability,\n lifecycleCapabilityId,\n LifecycleCapability,\n type LifecycleHostContextScope,\n type LifecycleRouteAddress,\n type LifecycleServices,\n type LifecycleStatus\n} from \"./capability\";\nimport {\n runInLifecycleHostContext,\n runWithoutCurrentAgent,\n type LifecycleObject\n} from \"./current-agent\";\nimport { isBenignTeardownError } from \"./transport-errors\";\nimport type { WSMessage } from \"./types\";\n\nexport {\n type CapabilityRequestContext,\n type CapabilityWebSocketUpgradeContext,\n type LifecycleEvent,\n type CapabilityStartContext,\n type DurableObjectCapability,\n type MemoryLimitContext\n} from \"./capability-runner\";\nexport {\n type LifecycleJobContext,\n type LifecycleJobs,\n type LifecycleJob,\n type LifecycleJobOutcome,\n type LifecycleJobPushOptions\n} from \"./job-queue\";\nexport * from \"./types\";\n\nconst LEGACY_NAME_STORAGE_KEY = \"__ps_name\";\n\nfunction mutableRequest(request: Request): Request {\n return new Request(request);\n}\n\n/**\n * Decode props from the internal lifecycle props header.\n *\n * Handles both base64-encoded lifecycle props and, for\n * backwards compatibility with stubs/requests created by older versions,\n * raw JSON. Base64 never starts with `{` or `[`, so a leading brace/bracket\n * unambiguously identifies the legacy raw-JSON form.\n */\nfunction decodeProps(header: string): unknown {\n const trimmed = header.trim();\n if (trimmed.startsWith(\"{\") || trimmed.startsWith(\"[\")) {\n return JSON.parse(trimmed);\n }\n const binary = atob(header);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return JSON.parse(new TextDecoder().decode(bytes));\n}\n\n/** Internal envelope transported between routed Lifecycle instances. */\nexport type LifecycleRouteEnvelope = {\n readonly capability: string;\n readonly source: LifecycleRouteAddress | undefined;\n readonly payload: unknown;\n};\n\n/** Internal transport supplied by a host with routed child Lifecycles. */\nexport type LifecycleRouteTransport = {\n readonly source: LifecycleRouteAddress | undefined;\n readonly toRoot: (envelope: LifecycleRouteEnvelope) => Promise<unknown>;\n readonly to: (\n target: LifecycleRouteAddress,\n envelope: LifecycleRouteEnvelope\n ) => Promise<unknown>;\n};\n\ntype LifecycleHost<Env extends object, Props extends object> = LifecycleObject<\n Env,\n Props\n> & {\n readonly ctx: DurableObjectState;\n readonly constructor: { readonly name: string };\n};\n\n/**\n * Boundary wrapping user callbacks that capabilities run through\n * `LifecycleServices.runInHostContext`. The default boundary is\n * {@link runInLifecycleHostContext}; a host composition root may substitute\n * its own invocation wrapper (Agent adds tracing span scope). The optional\n * scope carries the live connection/request the callback runs on behalf of.\n */\nexport type LifecycleHostInvoker = <T>(\n run: () => T,\n scope?: LifecycleHostContextScope\n) => T;\n\nconst lifecycleEventSinks = new WeakMap<object, LifecycleEventSink>();\nconst lifecycleRouteTransports = new WeakMap<object, LifecycleRouteTransport>();\nconst lifecycleHostInvokers = new WeakMap<object, LifecycleHostInvoker>();\n\n/** Lifecycles whose startup the current async context is running inside. */\nconst lifecycleStartupScope = new AsyncLocalStorage<ReadonlySet<object>>();\n\n/** @internal Adapt the host invocation boundary at a composition root. */\nexport function setLifecycleHostInvoker<\n Env extends object,\n Props extends object\n>(lifecycle: Lifecycle<Env, Props>, invoker: LifecycleHostInvoker): void {\n lifecycleHostInvokers.set(lifecycle, invoker);\n}\n\n/** @internal Supply a host's routed Lifecycle transport. */\nexport function setLifecycleRouteTransport<\n Env extends object,\n Props extends object\n>(lifecycle: Lifecycle<Env, Props>, transport: LifecycleRouteTransport): void {\n lifecycleRouteTransports.set(lifecycle, transport);\n}\n\n/** @internal Adapt Lifecycle's default diagnostics sink at a composition root. */\nexport function setLifecycleEventSink<Env extends object, Props extends object>(\n lifecycle: Lifecycle<Env, Props>,\n sink: LifecycleEventSink\n): void {\n lifecycleEventSinks.set(lifecycle, sink);\n}\n\n/** Configuration accepted when constructing a {@link Lifecycle}. */\nexport type LifecycleOptions = {\n /**\n * Consecutive alarm invocations that may end in a Durable Object\n * memory-limit reset before the circuit breaker (#1825) seals recovery\n * work instead of backing it off. Default: 3.\n */\n readonly maxAlarmMemoryLimitStrikes?: number;\n};\n\n/**\n * Installs and coordinates the runtime lifecycle for a Durable Object.\n *\n * Construct this as an instance field on a class that directly extends\n * `DurableObject`, then call {@link Lifecycle.installHandlers}\n * from that class's constructor.\n *\n * @experimental The API surface may change before stabilizing.\n */\n/** The dispatch hooks a catch-all can monopolize; uniqueness is per hook. */\nconst CATCH_ALL_HOOKS = [\"onRequest\", \"onWebSocketUpgrade\"] as const;\n\nexport class Lifecycle<\n Env extends object = Cloudflare.Env,\n Props extends object = object\n> {\n readonly #host: LifecycleHost<Env, Props>;\n readonly #ctx: DurableObjectState;\n readonly #parentClassName: string;\n readonly #capabilities: DurableObjectCapability<Props>[] = [];\n readonly #capabilityRunner = new CapabilityRunner<Props>(\n () => this.#capabilities\n );\n readonly #jobQueue: JobQueue;\n readonly #jobDriver: JobDriver;\n\n #status: LifecycleStatus = \"zero\";\n #alarmRearmQueue: Promise<void> = Promise.resolve();\n #rearmRequestedDuringStart = false;\n #pendingEvents: LifecycleEvent[] = [];\n #alarmsDisabled = false;\n #capabilitiesLocked = false;\n #handlersInstalled = false;\n\n /**\n * Construct and install a lifecycle in one explicit operation.\n *\n * @param host - The Durable Object whose runtime handlers the lifecycle owns.\n * @returns The installed lifecycle.\n */\n static install<Env extends object, Props extends object = object>(\n host: DurableObject<Env>,\n options?: LifecycleOptions\n ): Lifecycle<Env, Props> {\n const lifecycle = new Lifecycle<Env, Props>(host, options);\n lifecycle.installHandlers();\n return lifecycle;\n }\n\n /**\n * Bind a lifecycle to a Durable Object instance without mutating its handlers.\n *\n * @param host - The Durable Object whose runtime lifecycle this object owns.\n * @param options - Policy configuration for this lifecycle.\n */\n constructor(host: DurableObject<Env>, options?: LifecycleOptions) {\n // SAFETY: DurableObject exposes ctx as protected to subclasses. The\n // lifecycle is constructed by that subclass with `this`, so this boundary\n // accesses the same runtime-owned context without exposing it publicly.\n this.#host = host as unknown as LifecycleHost<Env, Props>;\n this.#ctx = this.#host.ctx;\n this.#parentClassName = this.#host.constructor.name;\n this.#jobQueue = new JobQueue(this.#ctx.storage);\n this.#jobDriver = new JobDriver({\n queue: this.#jobQueue,\n storage: this.#ctx.storage,\n disabled: () => this.#alarmsDisabled,\n resolveDispatch: (owner) => this.#resolveJobDispatch(owner),\n maxMemoryLimitStrikes: () => options?.maxAlarmMemoryLimitStrikes,\n onMemoryLimit: async (context) => {\n // Capabilities first (each best-effort inside the runner), then the\n // host hook — a failed capability policy must not silence the host's.\n await this.#capabilityRunner.memoryLimit(context);\n await runInLifecycleHostContext({ host: this.#host }, () =>\n this.#host.onAlarmMemoryLimit?.(context)\n );\n },\n emit: (type, payload) =>\n this.#emitCapabilityEvent({ source: \"lifecycle\", type, payload }),\n rearm: () => this.rearmAlarm(),\n // Deferred a tick so the current invocation settles (its RPC/alarm\n // completes and its writes confirm) before the instance resets —\n // `abort()` throws an uncatchable error, mirroring Agent.destroy().\n reset: (reason) => {\n setTimeout(() => abortWithoutAlarmRetry(this.#ctx, reason), 0);\n }\n });\n }\n\n /**\n * Install platform fetch, alarm, and hibernating WebSocket handlers.\n *\n * Existing handlers are preserved for framework-owned dispatch such as the\n * Agent's sub-agent router and alarm circuit breaker. Calling this method\n * more than once is an error.\n */\n installHandlers(): void {\n if (this.#handlersInstalled) {\n throw new Error(\n \"Durable Object lifecycle handlers are already installed\"\n );\n }\n this.#handlersInstalled = true;\n\n const handlers = {\n fetch: this.fetch.bind(this),\n alarm: this.alarm.bind(this),\n webSocketMessage: this.webSocketMessage.bind(this),\n webSocketClose: this.webSocketClose.bind(this),\n webSocketError: this.webSocketError.bind(this)\n };\n for (const [name, handler] of Object.entries(handlers)) {\n if (name in this.#host) continue;\n Object.defineProperty(this.#host, name, {\n value: handler,\n configurable: true\n });\n }\n }\n\n /**\n * Add a reusable capability before this lifecycle starts.\n *\n * Capabilities dispatch in registration order, except that a capability\n * declaring `claims: \"catch-all\"` always comes last, whenever it was\n * installed. Catch-alls are unique per dispatch hook: two may coexist\n * when they claim disjoint traffic (one `onRequest`, one\n * `onWebSocketUpgrade`), but a second catch-all for the same hook could\n * never be reached and is refused.\n *\n * @param capability - The capability to add.\n * @returns This lifecycle.\n */\n use(capability: DurableObjectCapability<Props>): this {\n if (this.#capabilitiesLocked) {\n throw new Error(\"Lifecycle capabilities must be added before startup\");\n }\n const capabilityId = lifecycleCapabilityId(capability);\n if (\n capabilityId &&\n this.#capabilities.some(\n (candidate) => lifecycleCapabilityId(candidate) === capabilityId\n )\n ) {\n throw new Error(\n `Lifecycle capability ${JSON.stringify(capabilityId)} is already installed`\n );\n }\n\n const catchAllIndex = this.#capabilities.findIndex(\n (candidate) => candidate.claims === \"catch-all\"\n );\n if (capability.claims === \"catch-all\") {\n for (const hook of CATCH_ALL_HOOKS) {\n if (!capability[hook]) continue;\n const rival = this.#capabilities.find(\n (candidate) => candidate.claims === \"catch-all\" && candidate[hook]\n );\n if (!rival) continue;\n const installed = lifecycleCapabilityId(rival);\n throw new Error(\n `Lifecycle already has a catch-all for ${hook}${\n installed ? ` (${JSON.stringify(installed)})` : \"\"\n }; a second one could never be reached`\n );\n }\n this.#capabilities.push(capability);\n } else {\n this.#capabilities.splice(\n catchAllIndex === -1 ? this.#capabilities.length : catchAllIndex,\n 0,\n capability\n );\n }\n\n if (capability instanceof LifecycleCapability) {\n bindLifecycleCapability(\n capability,\n this.#servicesForCapability(capability.capabilityId)\n );\n }\n return this;\n }\n\n #servicesForCapability(capabilityId: string): LifecycleServices {\n const lifecycle = this;\n const envelope = (payload: unknown): LifecycleRouteEnvelope => ({\n capability: capabilityId,\n source: lifecycleRouteTransports.get(lifecycle)?.source,\n payload\n });\n return Object.freeze({\n get name() {\n return lifecycle.name;\n },\n className: this.#parentClassName,\n storage: this.#ctx.storage,\n sockets: Object.freeze({\n accept: (ws: WebSocket, tags: string[]) =>\n this.#ctx.acceptWebSocket(ws, tags),\n get: (tag?: string) => this.#ctx.getWebSockets(tag)\n }),\n ready: () => this.#readyForCapabilityOperation(),\n status: () => this.#status,\n jobs: this.#jobsForOwner(capabilityId),\n trackAlarmWork: (work: Promise<unknown>) =>\n this.#jobDriver.trackAlarmWork(work),\n runInHostContext: async (\n fn: () => unknown,\n scope?: LifecycleHostContextScope\n ) => this.#runInHostBoundary(fn, scope),\n events: Object.freeze({\n emit: (type: string, payload: unknown) =>\n this.#emitCapabilityEvent({ source: capabilityId, type, payload })\n }),\n routes: Object.freeze({\n get source() {\n return lifecycleRouteTransports.get(lifecycle)?.source;\n },\n toRoot: (payload: unknown) => {\n const transport = lifecycleRouteTransports.get(lifecycle);\n return transport\n ? transport.toRoot(envelope(payload))\n : this.#dispatchRoute(envelope(payload));\n },\n to: (target: LifecycleRouteAddress, payload: unknown) => {\n const transport = lifecycleRouteTransports.get(lifecycle);\n if (!transport) {\n throw new Error(\n \"Lifecycle has no transport for routed capabilities\"\n );\n }\n return transport.to(target, envelope(payload));\n }\n })\n });\n }\n\n /**\n * Run a user callback inside the host invocation boundary — plain host\n * context by default, or the composition root's substitute (Agent installs\n * its tracing invocation scope).\n */\n #runInHostBoundary(\n fn: () => unknown,\n scope?: LifecycleHostContextScope\n ): Promise<unknown> {\n const boundary = lifecycleHostInvokers.get(this);\n return Promise.resolve(\n boundary\n ? boundary(fn, scope)\n : runInLifecycleHostContext(\n {\n host: this.#host,\n connection: scope?.connection,\n request: scope?.request\n },\n fn\n )\n );\n }\n\n #readyForCapabilityOperation(): Promise<void> {\n return this.#ensureInitialized();\n }\n\n async #dispatchRoute(envelope: LifecycleRouteEnvelope): Promise<unknown> {\n await this.#ensureInitialized();\n return runWithoutCurrentAgent(() =>\n this.#capabilityRunner.route(envelope.capability, {\n source: envelope.source,\n payload: envelope.payload\n })\n );\n }\n\n /** @internal Deliver a generic capability envelope to this Lifecycle. */\n route(envelope: LifecycleRouteEnvelope): Promise<unknown> {\n return this.#dispatchRoute(envelope);\n }\n\n #emitCapabilityEvent(event: LifecycleEvent): void {\n if (event.source.trim() === \"\" || event.type.trim() === \"\") {\n throw new Error(\"Lifecycle events require non-empty source and type\");\n }\n if (this.#status !== \"started\") {\n this.#pendingEvents.push(event);\n return;\n }\n this.#publishCapabilityEvent(event);\n }\n\n #publishCapabilityEvent(event: LifecycleEvent): void {\n runWithoutCurrentAgent(() => {\n const sink = lifecycleEventSinks.get(this);\n try {\n if (!sink) {\n publishDiagnosticsEvent({\n source: event.source,\n type: event.type,\n agent: this.#parentClassName,\n name: this.name,\n payload: event.payload,\n timestamp: Date.now()\n });\n return;\n }\n const pending = sink(event);\n if (pending !== undefined) {\n this.#ctx.waitUntil(\n Promise.resolve(pending).catch((error) => {\n this.#reportEventSinkFailure(event, error);\n })\n );\n }\n } catch (error) {\n this.#reportEventSinkFailure(event, error);\n }\n });\n }\n\n #reportEventSinkFailure(event: LifecycleEvent, error: unknown): void {\n console.error(\n `Lifecycle event sink failed for ${event.source}:${event.type}`,\n error\n );\n }\n\n #deliverPendingEvents(): void {\n for (const event of this.#pendingEvents.splice(0)) {\n this.#publishCapabilityEvent(event);\n }\n }\n\n /**\n * Execute SQL queries against the Durable Object's database\n * @template T Type of the returned rows\n * @param strings SQL query template strings\n * @param values Values to be inserted into the query\n * @returns Array of query results\n */\n sql<T = Record<string, string | number | boolean | null>>(\n strings: TemplateStringsArray,\n ...values: (string | number | boolean | null)[]\n ) {\n let query = \"\";\n try {\n // Construct the SQL query with placeholders\n query = strings.reduce(\n (acc, str, i) => acc + str + (i < values.length ? \"?\" : \"\"),\n \"\"\n );\n\n // Execute the SQL query with the provided values\n return [...this.#ctx.storage.sql.exec(query, ...values)] as T[];\n } catch (error) {\n console.error(`failed to execute sql query: ${query}`, error);\n throw error;\n }\n }\n\n /**\n * Handle an incoming request for the owning Durable Object.\n *\n * Non-upgrade requests run through the capability middleware chain first,\n * then fall through to the host's `onRequest`.\n */\n async fetch(request: Request): Promise<Response> {\n try {\n const encodedProps = request.headers.get(\"x-agents-lifecycle-props\");\n if (encodedProps) {\n this.#props = decodeProps(encodedProps) as Props;\n request = mutableRequest(request);\n request.headers.delete(\"x-agents-lifecycle-props\");\n }\n\n await this.#ensureInitialized();\n\n if (request.headers.get(\"Upgrade\")?.toLowerCase() !== \"websocket\") {\n const capabilityResponse = await runWithoutCurrentAgent(() =>\n this.#capabilityRunner.request({ request })\n );\n if (capabilityResponse !== undefined) return capabilityResponse;\n if (this.#host.onRequest) {\n return await runInLifecycleHostContext(\n { host: this.#host, request },\n () => this.#host.onRequest!(request)\n );\n }\n return new Response(\"Not implemented\", { status: 404 });\n } else {\n // Lifecycle does not model WebSockets. A capability that owns\n // connection behavior (e.g. the WebSockets capability) claims the\n // upgrade here; without one, upgrades are not supported.\n const upgradeResponse = await runWithoutCurrentAgent(() =>\n this.#capabilityRunner.webSocketUpgrade({ request })\n );\n if (upgradeResponse !== undefined) return upgradeResponse;\n\n return new Response(\n \"WebSocket upgrades are not enabled on this Durable Object. Install a capability that claims them (e.g. WebSockets).\",\n { status: 404 }\n );\n }\n } catch (err) {\n console.error(\n `Error in ${this.#parentClassName}:${this.#ctx.id.name ?? \"<unnamed>\"} fetch:`,\n err\n );\n if (!(err instanceof Error)) throw err;\n if (request.headers.get(\"Upgrade\") === \"websocket\") {\n // Annoyingly, if we return an HTTP error in response to a WebSocket request, Chrome devtools\n // won't show us the response body! So... let's send a WebSocket response with an error\n // frame instead.\n const pair = new WebSocketPair();\n pair[1].accept();\n pair[1].send(JSON.stringify({ error: err.stack }));\n pair[1].close(1011, \"Uncaught exception during session setup\");\n return new Response(null, { status: 101, webSocket: pair[0] });\n } else {\n return new Response(err.stack, { status: 500 });\n }\n }\n }\n\n /** @internal Dispatch a hibernating WebSocket message. */\n async webSocketMessage(ws: WebSocket, message: WSMessage): Promise<void> {\n try {\n await this.#ensureInitialized();\n\n // Sockets are owned by whichever capability claimed their upgrade\n // (recognized via its own hibernation attachment). Wakes for sockets\n // no capability owns — e.g. `state.acceptWebSocket()` in user code —\n // are ignored.\n await runWithoutCurrentAgent(() =>\n this.#capabilityRunner.webSocketMessage(ws, message)\n );\n } catch (e) {\n console.error(\n `Error in ${this.#parentClassName}:${this.#ctx.id.name ?? \"<unnamed>\"} webSocketMessage:`,\n e\n );\n }\n }\n\n /** @internal Dispatch a hibernating WebSocket close. */\n async webSocketClose(\n ws: WebSocket,\n code: number,\n reason: string,\n wasClean: boolean\n ): Promise<void> {\n try {\n await this.#ensureInitialized();\n // The owning capability also reciprocates the close handshake, as\n // the Hibernation API contract requires.\n await runWithoutCurrentAgent(() =>\n this.#capabilityRunner.webSocketClose(ws, code, reason, wasClean)\n );\n } catch (e) {\n console.error(\n `Error in ${this.#parentClassName}:${this.#ctx.id.name ?? \"<unnamed>\"} webSocketClose:`,\n e\n );\n }\n }\n\n /** @internal Dispatch a hibernating WebSocket error. */\n async webSocketError(ws: WebSocket, error: unknown): Promise<void> {\n // Suppress retryable transport-teardown errors on an already closing/closed\n // socket — the connection going away during/after the close handshake, not\n // an application error. Genuine mid-connection (OPEN) errors still reach\n // the owning handler below.\n if (isBenignTeardownError(ws, error)) {\n return;\n }\n\n try {\n await this.#ensureInitialized();\n await runWithoutCurrentAgent(() =>\n this.#capabilityRunner.webSocketError(ws, error)\n );\n } catch (e) {\n console.error(\n `Error in ${this.#parentClassName}:${this.#ctx.id.name ?? \"<unnamed>\"} webSocketError:`,\n e\n );\n }\n }\n\n /**\n * Start lifecycle capabilities and the owning Durable Object.\n *\n * Runtime fetch, alarm, and WebSocket entry points call this automatically.\n * RPC methods may call it explicitly because native RPC bypasses fetch.\n *\n * Concurrent callers share one startup and all observe its outcome. A call\n * made from inside that startup, such as a capability or `onStart` calling\n * back into the host, returns immediately instead of waiting on itself.\n *\n * @param props - Optional properties supplied to capability and host startup.\n * Ignored while a startup is already in flight.\n */\n async start(props?: Props): Promise<void> {\n if (props !== undefined && this.#startup === undefined) {\n this.#props = props;\n }\n await this.#ensureInitialized();\n }\n\n /**\n * Whether lifecycle startup has completed for this instance.\n *\n * @returns `true` after capabilities and the host `onStart` have finished.\n */\n isStarted(): boolean {\n return this.#status === \"started\";\n }\n\n #startup: Promise<void> | undefined;\n\n #ensureInitialized(): Promise<void> {\n if (this.#status === \"started\") return Promise.resolve();\n if (this.#startup === undefined) {\n // Deferred a tick so `#startup` is assigned before startup can call\n // back into this method synchronously.\n const startup = Promise.resolve()\n .then(() => this.#runStartup())\n .finally(() => {\n if (this.#startup === startup) this.#startup = undefined;\n });\n this.#startup = startup;\n return startup;\n }\n if (lifecycleStartupScope.getStore()?.has(this)) return Promise.resolve();\n return this.#startup;\n }\n\n async #runStartup(): Promise<void> {\n if (this.#ctx.id.name === undefined && this.#legacyName === undefined) {\n this.#legacyName = await this.#ctx.storage.get<string>(\n LEGACY_NAME_STORAGE_KEY\n );\n }\n // Fail before host startup if neither native nor migrated identity exists.\n void this.name;\n\n this.#capabilitiesLocked = true;\n const scope = new Set(lifecycleStartupScope.getStore());\n scope.add(this);\n let error: unknown;\n await this.#ctx.blockConcurrencyWhile(() =>\n lifecycleStartupScope.run(scope, async () => {\n this.#status = \"starting\";\n try {\n await runWithoutCurrentAgent(() =>\n this.#capabilityRunner.start({ props: this.#props })\n );\n await runInLifecycleHostContext({ host: this.#host }, () =>\n this.#host.onStart?.(this.#props)\n );\n this.#status = \"started\";\n } catch (cause) {\n this.#status = \"zero\";\n error = cause;\n }\n })\n );\n // Re-throw outside blockConcurrencyWhile so the input gate is not\n // permanently broken and a later invocation can retry startup.\n if (error) {\n this.#rearmRequestedDuringStart = false;\n this.#pendingEvents.length = 0;\n throw error;\n }\n this.#deliverPendingEvents();\n if (this.#rearmRequestedDuringStart) {\n this.#rearmRequestedDuringStart = false;\n await this.rearmAlarm();\n }\n }\n\n #legacyName: string | undefined;\n\n /**\n * The name used to address this Durable Object.\n *\n * Native `ctx.id.name` is authoritative. A read-only legacy storage fallback\n * lets objects created by older PartyServer releases migrate without new\n * name writes.\n */\n get name(): string {\n const name = this.#ctx.id.name ?? this.#legacyName;\n if (name !== undefined) return name;\n throw new Error(\n `${this.#parentClassName} could not determine its Durable Object name. ` +\n \"Address it with idFromName() or getByName(). In local development, \" +\n \"update Wrangler/workerd and use a current compatibility_date. \" +\n \"newUniqueId(), idFromString(), and names over 1,024 bytes do not \" +\n \"expose ctx.id.name. Alarms created before 2026-03-15 must be \" +\n \"rescheduled from a named fetch or RPC handler.\"\n );\n }\n\n #props?: Props;\n\n /**\n * The host's scoped access to the Lifecycle work queue. Items pushed here\n * are dispatched to the host's `onJob` inside the host invocation\n * boundary.\n */\n get jobs(): LifecycleJobs {\n return this.#jobsForOwner(HOST_JOB_CAPABILITY);\n }\n\n #jobsForOwner(owner: string): LifecycleJobs {\n const rearmAfter = async <T>(mutate: () => T): Promise<T> => {\n const result = mutate();\n await this.rearmAlarm();\n return result;\n };\n return Object.freeze({\n push: (options: LifecycleJobPushOptions) =>\n rearmAfter(() => this.#jobQueue.push(owner, options)),\n cancel: (id: string) =>\n rearmAfter(() => this.#jobQueue.cancel(owner, id)),\n reschedule: (id: string, time: number) =>\n rearmAfter(() => this.#jobQueue.reschedule(owner, id, time)),\n get: (id: string) => this.#jobQueue.get(owner, id),\n list: () => this.#jobQueue.list(owner),\n rearm: () => this.rearmAlarm()\n });\n }\n\n /**\n * Recompute the physical Durable Object alarm from job-queue state.\n *\n * Concurrent requests are serialized so a later durable-state change cannot\n * be overwritten by an earlier alarm calculation. Queue mutations call this\n * automatically; it stays public for composition roots and tests.\n */\n async rearmAlarm(): Promise<void> {\n if (this.#alarmsDisabled) return;\n if (this.#status === \"starting\") {\n this.#rearmRequestedDuringStart = true;\n return;\n }\n\n const prior = this.#alarmRearmQueue;\n const next = prior\n .catch(() => {})\n .then(async () => {\n if (this.#alarmsDisabled) return;\n const alarm = this.#jobQueue.nextAlarmTime(Date.now());\n if (alarm === null) {\n await this.#ctx.storage.deleteAlarm();\n } else {\n await this.#ctx.storage.setAlarm(alarm);\n }\n });\n this.#alarmRearmQueue = next;\n await next;\n }\n\n /**\n * Keep work a job handed off at a bounded return inside the current\n * alarm's memory-limit breaker domain (#1825). Hosts call this where a\n * queue-driven callback detaches long work and returns.\n *\n * @returns True when called during an alarm invocation; false otherwise.\n */\n trackAlarmWork(work: Promise<unknown>): boolean {\n return this.#jobDriver.trackAlarmWork(work);\n }\n\n /** Dispose installed capabilities in reverse registration order. */\n async dispose(): Promise<void> {\n await runWithoutCurrentAgent(() => this.#capabilityRunner.dispose());\n }\n\n /** Permanently disable and clear alarms during explicit object teardown. */\n async disableAlarms(): Promise<void> {\n this.#alarmsDisabled = true;\n await this.#alarmRearmQueue.catch(() => {});\n await this.#ctx.storage.deleteAlarm();\n }\n\n /**\n * Run one alarm invocation. The job driver owns the event loop — deadman\n * pre-arm, due-job dispatch with retry and deferral policy, the alarm\n * memory-limit circuit breaker (#1825) — and re-arms the physical alarm\n * from queue state. The host's `onAlarm()` runs after due jobs, inside\n * the host invocation boundary.\n */\n async alarm(): Promise<void> {\n await this.#jobDriver.runAlarm(\n () => this.#ensureInitialized(),\n () =>\n runInLifecycleHostContext({ host: this.#host }, async () => {\n await this.#host.onAlarm?.();\n })\n );\n }\n\n /**\n * Resolve a job owner to its dispatch hooks. Host jobs run inside the\n * host invocation boundary; capability jobs run outside ambient host\n * context, like every other capability hook.\n */\n async #resolveJobDispatch(owner: string): Promise<JobDispatch | undefined> {\n if (owner === HOST_JOB_CAPABILITY) {\n const host = this.#host;\n if (!host.onJob) return undefined;\n // No host onJobError: a host job's terminal application failure\n // completes it, and the host re-derives its jobs from durable state.\n return {\n onJob: async (context) =>\n runInLifecycleHostContext({ host }, () => host.onJob!(context))\n };\n }\n const capability = await this.#capabilityRunner.findById(owner);\n if (!capability?.onJob) return undefined;\n return {\n onJob: async (context) =>\n runWithoutCurrentAgent(() => capability.onJob!(context)),\n onJobError: capability.onJobError\n ? async (context, error) =>\n runWithoutCurrentAgent(() => capability.onJobError!(context, error))\n : undefined\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA4NA,IAAa,mBAAb,MAA6D;;;;;;;CAa3D,YACE,qBACA;;;;;6CAVS,KAAA;EAWT,uBAAA,sBAAA,MAA4B,mBAAA;CAC9B;;;;;;;;;CAUA,MAAM,MAAM,SAAuD;EACjE,IAAA,uBAAA,UAAI,IAAA,GAAe;EAEnB,MAAM,UAAA,uBAAA,eAAU,IAAA;EAChB,IAAI,SAAS;GACX,MA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