agents 0.28.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/dist/{agent-routing-QDcchcQP.d.ts → agent-routing-CDbpVjYq.d.ts} +18 -8
  2. package/dist/agent-routing.d.ts +1 -1
  3. package/dist/agent-tool-types.d.ts +1 -1
  4. package/dist/{agent-tools-DHL2XI7u.d.ts → agent-tools-C8DH8Yii.d.ts} +2 -2
  5. package/dist/agent-tools.d.ts +1 -1
  6. package/dist/{ai-ahruGw7e.d.ts → ai-iXw0uOGj.d.ts} +3 -3
  7. package/dist/{ai-sdk-Bdsf6mSA.js → ai-sdk-DRPh2rRa.js} +218 -132
  8. package/dist/ai-sdk-DRPh2rRa.js.map +1 -0
  9. package/dist/browser/ai.d.ts +1 -1
  10. package/dist/browser/ai.js +2 -2
  11. package/dist/browser/index.d.ts +8 -8
  12. package/dist/browser/index.js +3 -3
  13. package/dist/browser/tools/ai-sdk.d.ts +2 -2
  14. package/dist/browser/tools/ai-sdk.js +1 -1
  15. package/dist/browser/tools/pi.d.ts +1 -1
  16. package/dist/browser/tools/pi.js +3 -3
  17. package/dist/browser/tools/pi.js.map +1 -1
  18. package/dist/browser/tools/tanstack-ai.d.ts +2 -2
  19. package/dist/browser/tools/tanstack-ai.js +1 -1
  20. package/dist/{browser-CEdNlsaD.js → browser-DccPw_wW.js} +130 -79
  21. package/dist/browser-DccPw_wW.js.map +1 -0
  22. package/dist/{browser-D30VlpcA.d.ts → browser-DlXhSAdf.d.ts} +41 -37
  23. package/dist/{browser-tool-4iomavs_.js → browser-tool-B1mhifin.js} +3 -3
  24. package/dist/{browser-tool-4iomavs_.js.map → browser-tool-B1mhifin.js.map} +1 -1
  25. package/dist/{browser-tool-vtrPOV8e.d.ts → browser-tool-Cxjk5sgG.d.ts} +2 -2
  26. package/dist/chat/index.d.ts +143 -71
  27. package/dist/chat/index.js +269 -110
  28. package/dist/chat/index.js.map +1 -1
  29. package/dist/chat-sdk/index.d.ts +1 -1
  30. package/dist/chat-sdk/index.js +1 -1
  31. package/dist/cli.js +33 -33
  32. package/dist/{client-BGIQKJhX.d.ts → client-C27CtRZr.d.ts} +2 -2
  33. package/dist/client.d.ts +1 -1
  34. package/dist/{connector-DEXzVoaY.d.ts → connector-20DJ6p4k.d.ts} +2 -2
  35. package/dist/{connector-CtZylXdk.js → connector-DAXBOIIi.js} +2 -2
  36. package/dist/{connector-CtZylXdk.js.map → connector-DAXBOIIi.js.map} +1 -1
  37. package/dist/experimental/channels/web/index.js +1 -1
  38. package/dist/{handler-stateless-VvrWSAVA.js → handler-stateless-Bly_nSH3.js} +12 -3
  39. package/dist/handler-stateless-Bly_nSH3.js.map +1 -0
  40. package/dist/harness/container/index.js +1 -1
  41. package/dist/harness/container/index.js.map +1 -1
  42. package/dist/harness/opencode/index.d.ts +182 -6
  43. package/dist/harness/opencode/index.js +354 -23
  44. package/dist/harness/opencode/index.js.map +1 -1
  45. package/dist/harness/pi/index.d.ts +13 -5
  46. package/dist/harness/pi/index.js +8 -214
  47. package/dist/harness/pi/index.js.map +1 -1
  48. package/dist/{images-Ce9SCu3X.js → images-xaDv2Fqe.js} +662 -152
  49. package/dist/images-xaDv2Fqe.js.map +1 -0
  50. package/dist/index-DCxk3OSJ.d.ts +378 -0
  51. package/dist/{index-kbSUIer3.d.ts → index-iv9FTXX9.d.ts} +80 -112
  52. package/dist/index.d.ts +1 -1
  53. package/dist/index.js +1 -1
  54. package/dist/{input-schema-D2QAtHZH.js → input-schema-B0Etuo-o.js} +2 -2
  55. package/dist/{input-schema-D2QAtHZH.js.map → input-schema-B0Etuo-o.js.map} +1 -1
  56. package/dist/lifecycle/index.js +1 -1
  57. package/dist/{lifecycle-DGorpAmA.js → lifecycle-ClT4DmF2.js} +11 -3
  58. package/dist/lifecycle-ClT4DmF2.js.map +1 -0
  59. package/dist/mcp/client/index.d.ts +1 -1
  60. package/dist/mcp/index.d.ts +1 -1
  61. package/dist/mcp/index.js +17 -3
  62. package/dist/mcp/index.js.map +1 -1
  63. package/dist/mcp/server/index.js +1 -1
  64. package/dist/models/ai-sdk/index.d.ts +31 -326
  65. package/dist/models/ai-sdk/index.js +1 -1
  66. package/dist/models/opencode/index.d.ts +25 -13
  67. package/dist/models/opencode/index.js +16 -11
  68. package/dist/models/opencode/index.js.map +1 -1
  69. package/dist/models/pi-ai/index.d.ts +17 -13
  70. package/dist/models/pi-ai/index.js +89 -36
  71. package/dist/models/pi-ai/index.js.map +1 -1
  72. package/dist/react.d.ts +2 -2
  73. package/dist/routing/index.d.ts +1 -1
  74. package/dist/serializable.d.ts +1 -1
  75. package/dist/{session-store-DoPY12xM.d.ts → session-store-_IK6dV-w.d.ts} +14 -2
  76. package/dist/{session-store-Do4xkDcf.js → session-store-yvwq1f9x.js} +55 -2
  77. package/dist/session-store-yvwq1f9x.js.map +1 -0
  78. package/dist/{settings-C45hDliX.js → settings-Dk2il2Hf.js} +10 -4
  79. package/dist/settings-Dk2il2Hf.js.map +1 -0
  80. package/dist/skills/index.d.ts +22 -28
  81. package/dist/skills/index.js +183 -143
  82. package/dist/skills/index.js.map +1 -1
  83. package/dist/{src-CQxJFv4l.js → src-6lr7MtM_.js} +3 -3
  84. package/dist/src-6lr7MtM_.js.map +1 -0
  85. package/dist/sub-routing.d.ts +1 -1
  86. package/dist/{tool-cQRkwSZZ.js → tool-DkT_DJBm.js} +2 -2
  87. package/dist/tool-DkT_DJBm.js.map +1 -0
  88. package/dist/transport-CPh7YGiw.d.ts +623 -0
  89. package/dist/voice/index.d.ts +1 -1
  90. package/dist/web/fetch/tools/pi.js +2 -2
  91. package/dist/web/fetch/tools/pi.js.map +1 -1
  92. package/dist/web/search/index.js +1 -1
  93. package/dist/web/search/tools/ai-sdk.js +2 -2
  94. package/dist/web/search/tools/pi.js +3 -3
  95. package/dist/web/search/tools/pi.js.map +1 -1
  96. package/dist/web/search/tools/tanstack-ai.js +2 -2
  97. package/dist/websockets/index.js +1 -1
  98. package/dist/{websockets-C3zy8YR0.js → websockets-CqxnntmE.js} +2 -2
  99. package/dist/{websockets-C3zy8YR0.js.map → websockets-CqxnntmE.js.map} +1 -1
  100. package/dist/workflow-types.d.ts +1 -1
  101. package/dist/workflows.d.ts +1 -1
  102. package/dist/workflows.js +1 -1
  103. package/docs/browse-the-web.md +1 -1
  104. package/docs/chat-agents.md +19 -18
  105. package/docs/harnesses/pi.md +47 -18
  106. package/docs/mcp-client.md +1 -1
  107. package/docs/mcp-servers.md +1 -1
  108. package/docs/models-pi-ai.md +70 -17
  109. package/docs/models.md +219 -152
  110. package/package.json +14 -14
  111. package/dist/ai-sdk-Bdsf6mSA.js.map +0 -1
  112. package/dist/browser-CEdNlsaD.js.map +0 -1
  113. package/dist/handler-stateless-VvrWSAVA.js.map +0 -1
  114. package/dist/images-Ce9SCu3X.js.map +0 -1
  115. package/dist/lifecycle-DGorpAmA.js.map +0 -1
  116. package/dist/session-store-Do4xkDcf.js.map +0 -1
  117. package/dist/settings-C45hDliX.js.map +0 -1
  118. package/dist/settings-NgGwF7Qt.d.ts +0 -331
  119. package/dist/src-CQxJFv4l.js.map +0 -1
  120. package/dist/tool-cQRkwSZZ.js.map +0 -1
  121. package/dist/transport-k2mFrtL8.d.ts +0 -200
@@ -1 +0,0 @@
1
- {"version":3,"file":"lifecycle-DGorpAmA.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 */\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/** 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":";;;;;;;;;;;;;;;;;;;;;;;;AA0NA,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,MAAM;GACN;EACF;EAEA,MAAM,UAAA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/browser/cdp-connection.ts","../src/browser/browser-run.ts","../src/browser/connector-validation.ts","../src/browser/live-view.ts","../src/browser/spec.ts","../src/browser/session-store.ts"],"sourcesContent":["interface PendingCommand {\n resolve: (result: unknown) => void;\n reject: (error: Error) => void;\n timeoutId: ReturnType<typeof setTimeout>;\n method: string;\n sessionId?: string;\n startedAt: number;\n}\n\ninterface DebugEntry {\n at: string;\n type: string;\n [key: string]: unknown;\n}\n\nexport interface CdpSendOptions {\n timeoutMs?: number;\n sessionId?: string;\n}\n\nexport interface CdpAttachOptions {\n timeoutMs?: number;\n}\n\n/** Construction options for {@link CdpConnection}. */\nexport interface CdpConnectionOptions {\n /** Default per-command timeout. Defaults to 10 seconds. */\n timeoutMs?: number;\n /**\n * Invoked exactly once when the session reaches a terminal state — an\n * explicit `close()`, peer closure, or a socket error.\n */\n onClose?: () => void;\n /** Browser Run session id, when connected to a session-scoped browser. */\n sessionId?: string;\n /** Invoked on every CDP command sent — an activity signal for idle tracking. */\n onActivity?: () => void;\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\n/** JSON-RPC's \"method not found\" code, which Chrome also uses for CDP. */\nexport const CDP_METHOD_NOT_FOUND = -32601;\n\n/** The browser answered a command with a JSON-RPC error. */\nexport class CdpProtocolError extends Error {\n override readonly name = \"CdpProtocolError\";\n /** JSON-RPC error code, e.g. {@link CDP_METHOD_NOT_FOUND}. */\n readonly code: number | undefined;\n /** The CDP method that failed. */\n readonly method: string;\n\n constructor(method: string, code: number | undefined, message: string) {\n super(`CDP error ${code ?? \"unknown\"}: ${message} for ${method}`);\n this.code = code;\n this.method = method;\n }\n}\nconst MAX_DEBUG_ENTRIES = 400;\n\n/**\n * One Chrome DevTools Protocol connection over an open WebSocket. Manages\n * command correlation, timeouts, per-tab CDP sessions, and a debug event\n * ring buffer.\n *\n * Used host-side (not in the sandbox) — the sandbox calls into this\n * via DynamicWorkerExecutor's ToolDispatcher RPC.\n */\nexport class CdpConnection {\n #socket: WebSocket;\n #nextId = 1;\n #pending = new Map<number, PendingCommand>();\n #debugLog: DebugEntry[] = [];\n #defaultTimeoutMs: number;\n #dispose?: () => void;\n #disposed = false;\n #onActivity?: () => void;\n readonly sessionId?: string;\n\n constructor(socket: WebSocket, options?: CdpConnectionOptions);\n /**\n * @deprecated Pass a {@link CdpConnectionOptions} object instead —\n * `new CdpConnection(socket, { timeoutMs, onClose, sessionId })`. The\n * positional form will be removed.\n */\n constructor(\n socket: WebSocket,\n timeoutMs?: number,\n onClose?: () => void,\n sessionId?: string\n );\n constructor(\n socket: WebSocket,\n optionsOrTimeoutMs?: CdpConnectionOptions | number,\n onClose?: () => void,\n sessionId?: string\n ) {\n const options: CdpConnectionOptions =\n typeof optionsOrTimeoutMs === \"object\"\n ? optionsOrTimeoutMs\n : { timeoutMs: optionsOrTimeoutMs, onClose, sessionId };\n this.#socket = socket;\n this.#defaultTimeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n this.#dispose = options.onClose;\n this.sessionId = options.sessionId;\n this.#onActivity = options.onActivity;\n\n socket.addEventListener(\"message\", (event) => this.#handleMessage(event));\n socket.addEventListener(\"error\", () => {\n this.#rejectAll(new Error(\"CDP socket error\"));\n this.#runDispose();\n });\n socket.addEventListener(\"close\", () => {\n this.#rejectAll(new Error(\"CDP connection closed\"));\n this.#runDispose();\n });\n }\n\n send(\n method: string,\n params?: unknown,\n options: CdpSendOptions = {}\n ): Promise<unknown> {\n this.#onActivity?.();\n const id = this.#nextId++;\n const timeoutMs = options.timeoutMs ?? this.#defaultTimeoutMs;\n const sessionId =\n typeof options.sessionId === \"string\" && options.sessionId.length > 0\n ? options.sessionId\n : undefined;\n\n const domain = typeof method === \"string\" ? method.split(\".\")[0] : \"\";\n if (!sessionId && domain && ![\"Browser\", \"Target\"].includes(domain)) {\n this.#recordDebug(\"warning\", {\n id,\n method,\n reason: \"target-scoped method sent without sessionId\"\n });\n }\n\n const result = new Promise<unknown>((resolve, reject) => {\n const startedAt = performance.now();\n const timeoutId = setTimeout(() => {\n this.#pending.delete(id);\n reject(\n new Error(`CDP command timed out after ${timeoutMs}ms: ${method}`)\n );\n }, timeoutMs);\n this.#pending.set(id, {\n resolve,\n reject,\n timeoutId,\n method,\n sessionId,\n startedAt\n });\n });\n\n this.#recordDebug(\"send\", { id, method, sessionId, timeoutMs });\n try {\n this.#socket.send(JSON.stringify({ id, method, params, sessionId }));\n } catch (error) {\n // A closed socket throws on send: fail this command now rather than\n // leave it pending until it times out.\n const pending = this.#pending.get(id);\n if (pending) {\n clearTimeout(pending.timeoutId);\n this.#pending.delete(id);\n pending.reject(\n error instanceof Error ? error : new Error(String(error))\n );\n }\n }\n return result;\n }\n\n async attachToTarget(\n targetId: string,\n options: CdpAttachOptions = {}\n ): Promise<string> {\n if (typeof targetId !== \"string\" || !targetId) {\n throw new Error(\n \"attachToTarget requires a targetId — list open tabs with \" +\n \"send('Target.getTargets') or create one with \" +\n \"send('Target.createTarget', { url })\"\n );\n }\n\n const result = (await this.send(\n \"Target.attachToTarget\",\n {\n targetId,\n flatten: true\n },\n { timeoutMs: options.timeoutMs }\n )) as { sessionId?: string };\n\n const sessionId = result?.sessionId ?? \"\";\n if (!sessionId) {\n throw new Error(\n `Target.attachToTarget did not return a sessionId for target ${targetId}`\n );\n }\n\n this.#recordDebug(\"attach\", { targetId, sessionId });\n return sessionId;\n }\n\n getDebugLog(limit = 50): DebugEntry[] {\n const normalized = Number.isFinite(limit)\n ? Math.max(1, Math.floor(limit))\n : 50;\n return this.#debugLog.slice(-normalized);\n }\n\n clearDebugLog(): void {\n this.#debugLog = [];\n }\n\n disconnect(): void {\n this.#rejectAll(new Error(\"CDP session disconnected\"));\n try {\n this.#socket.close(1000, \"Done\");\n } catch {\n // socket may already be closed\n }\n }\n\n close(): void {\n this.disconnect();\n this.#runDispose();\n }\n\n /**\n * Run the dispose callback exactly once, on the first terminal event —\n * an explicit {@link close}, peer closure, or a socket error.\n */\n #runDispose(): void {\n if (this.#disposed) return;\n this.#disposed = true;\n this.#dispose?.();\n }\n\n #rejectAll(error: Error): void {\n for (const [id, pending] of this.#pending.entries()) {\n clearTimeout(pending.timeoutId);\n this.#pending.delete(id);\n pending.reject(error);\n }\n }\n\n #handleMessage(event: MessageEvent): void {\n if (typeof event.data !== \"string\") {\n return;\n }\n\n let payload: Record<string, unknown>;\n try {\n payload = JSON.parse(event.data) as Record<string, unknown>;\n } catch {\n return;\n }\n\n this.#recordDebug(\"receive\", {\n id: payload.id,\n method: payload.method,\n sessionId: payload.sessionId,\n hasError: !!payload.error\n });\n\n if (typeof payload.id !== \"number\") {\n return;\n }\n\n const pending = this.#pending.get(payload.id);\n if (!pending) {\n return;\n }\n\n clearTimeout(pending.timeoutId);\n this.#pending.delete(payload.id);\n\n if (payload.error) {\n const err = payload.error as { code?: unknown; message?: string };\n pending.reject(\n new CdpProtocolError(\n pending.method,\n typeof err.code === \"number\" ? err.code : undefined,\n err.message ?? \"CDP error\"\n )\n );\n return;\n }\n\n pending.resolve(payload.result);\n }\n\n #recordDebug(type: string, data: Record<string, unknown>): void {\n this.#debugLog.push({\n at: new Date().toISOString(),\n type,\n ...data\n });\n if (this.#debugLog.length > MAX_DEBUG_ENTRIES) {\n this.#debugLog.splice(0, this.#debugLog.length - MAX_DEBUG_ENTRIES);\n }\n }\n}\n\nconst LOCALHOST_HOSTS = new Set([\n \"localhost\",\n \"127.0.0.1\",\n \"0.0.0.0\",\n \"::1\",\n \"[::1]\"\n]);\n\n/**\n * Connect to a browser via a CDP base URL (e.g. http://localhost:9222).\n * Discovers the WebSocket debugger URL via /json/version,\n * rewrites localhost URLs to the base URL host, and opens the WebSocket.\n *\n * Useful for local development with `chrome --remote-debugging-port=9222`\n * or when connecting through a tunnel.\n */\nexport async function connectUrl(\n baseUrl: string,\n options?: { timeoutMs?: number; headers?: Record<string, string> }\n): Promise<CdpConnection> {\n const endpoint = new URL(\"/json/version\", baseUrl).toString();\n const response = await fetch(endpoint, {\n headers: options?.headers\n });\n if (!response.ok) {\n throw new Error(\n `Failed to discover CDP endpoint at ${endpoint}: ${response.status}`\n );\n }\n\n const payload = (await response.json()) as {\n webSocketDebuggerUrl?: string;\n };\n if (!payload.webSocketDebuggerUrl) {\n throw new Error(\"CDP /json/version did not include webSocketDebuggerUrl\");\n }\n\n let wsUrl = payload.webSocketDebuggerUrl;\n const parsed = new URL(wsUrl);\n if (LOCALHOST_HOSTS.has(parsed.hostname)) {\n const base = new URL(baseUrl);\n parsed.hostname = base.hostname;\n parsed.port = base.port;\n parsed.protocol = base.protocol;\n } else {\n // Workers runtime requires fetch + Upgrade header for outbound WebSockets\n parsed.protocol = parsed.protocol === \"wss:\" ? \"https:\" : \"http:\";\n }\n const fetchUrl = parsed.toString();\n\n const wsResponse = await fetch(fetchUrl, {\n headers: { ...options?.headers, Upgrade: \"websocket\" }\n });\n const ws = wsResponse.webSocket;\n if (!ws) {\n throw new Error(\n `Failed to establish CDP WebSocket at ${fetchUrl} (status ${wsResponse.status})`\n );\n }\n ws.accept();\n\n return new CdpConnection(ws, { timeoutMs: options?.timeoutMs });\n}\n\n/** @deprecated Renamed to {@link CdpConnection}. */\nexport const CdpSession = CdpConnection;\n/** @deprecated Renamed to {@link CdpConnection}. */\nexport type CdpSession = CdpConnection;\n","import { CdpConnection } from \"./cdp-connection\";\n\n/**\n * A Browser Rendering binding. Structural so it accepts both the classic\n * `Fetcher`-typed binding and the newer `BrowserRun` type generated by\n * `wrangler types` — we only ever use its `fetch` surface.\n */\nexport interface BrowserBinding {\n fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;\n}\n\n/**\n * Browser Run [hostname guardrails](https://developers.cloudflare.com/browser-run/features/guardrails/):\n * restrict which hostnames the session's HTTP/HTTPS requests may reach. Fixed\n * at session launch for every connection to the session, including Live View.\n * Omitted entirely, the platform default applies: all hostnames are allowed.\n * Not supported by Kitesurf.\n */\nexport interface BrowserSessionGuardrails {\n /**\n * Hostname patterns the browser may request — bare hostnames only (no\n * protocol, port, or path). `*.example.com` matches subdomains; add\n * `example.com` separately to allow the apex.\n */\n allowedDomains?: string[];\n /** Named Cloudflare-maintained domain sets, e.g. `\"common-cdns\"`. */\n allowedDomainSets?: string[];\n}\n\nexport interface BrowserTargetInfo {\n id: string;\n type?: string;\n url?: string;\n title?: string;\n description?: string;\n devtoolsFrontendUrl?: string;\n webSocketDebuggerUrl?: string;\n}\n\nexport interface BrowserSessionInfo {\n sessionId: string;\n targets?: BrowserTargetInfo[];\n webSocketDebuggerUrl?: string;\n}\n\n/** {@link connectBrowser} options for the default Chromium engine. */\nexport interface ConnectChromiumBrowserOptions {\n /** Select the browser engine. Defaults to Chromium. */\n browser?: \"chromium\";\n timeoutMs?: number;\n keepAliveMs?: number;\n includeTargets?: boolean;\n /**\n * Opt into Browser Run [session recording](https://developers.cloudflare.com/browser-run/features/session-recording/):\n * an rrweb capture of DOM changes, input, and navigation, finalized when the\n * session closes. Set at session-launch time. Retrieve later with\n * {@link getBrowserRecording}.\n */\n recording?: boolean;\n}\n\n/**\n * {@link connectBrowser} options for Kitesurf, Cloudflare's connection-scoped,\n * agent-first browser engine. A Kitesurf browser lives and dies with its\n * WebSocket, so the Chromium-only options (`keepAliveMs`, `includeTargets`,\n * `recording`) do not exist on this arm.\n */\nexport interface ConnectKitesurfBrowserOptions {\n browser: \"kitesurf\";\n timeoutMs?: number;\n}\n\n/**\n * Engine-discriminated {@link connectBrowser} options: selecting\n * `browser: \"kitesurf\"` removes the Chromium-only options at the type level.\n */\nexport type ConnectBrowserOptions =\n | ConnectChromiumBrowserOptions\n | ConnectKitesurfBrowserOptions;\n\n/** An rrweb session recording for a closed Browser Run session. */\nexport interface BrowserRecording {\n sessionId: string;\n /** Recording length in milliseconds. */\n duration: number;\n /**\n * rrweb event arrays keyed by CDP target id (one per tab). Each value can be\n * passed directly to `rrweb-player` to replay that tab.\n */\n events: Record<string, unknown[]>;\n}\n\nexport class BrowserRenderingError extends Error {\n constructor(\n message: string,\n readonly status: number\n ) {\n super(message);\n this.name = \"BrowserRenderingError\";\n }\n}\n\n/**\n * Whether an error means the platform session is gone: Browser Run uses 404\n * for unknown ids and 410 after `keep_alive` expiry.\n */\nexport function isMissingBrowserSession(error: unknown): boolean {\n return (\n error instanceof BrowserRenderingError &&\n (error.status === 404 || error.status === 410)\n );\n}\n\nfunction browserSessionEndpoint(\n sessionId?: string,\n options?: {\n keepAliveMs?: number;\n includeTargets?: boolean;\n recording?: boolean;\n browser?: \"kitesurf\";\n }\n): string {\n const path = sessionId\n ? `/v1/devtools/browser/${sessionId}`\n : \"/v1/devtools/browser\";\n const url = new URL(`https://localhost${path}`);\n\n if (options?.keepAliveMs !== undefined) {\n url.searchParams.set(\"keep_alive\", String(options.keepAliveMs));\n }\n if (options?.includeTargets) {\n url.searchParams.set(\"targets\", \"true\");\n }\n if (options?.recording) {\n url.searchParams.set(\"recording\", \"true\");\n }\n if (options?.browser) {\n url.searchParams.set(\"browser\", options.browser);\n }\n\n return url.toString();\n}\n\nasync function parseBrowserSessionInfo(\n response: Response\n): Promise<BrowserSessionInfo> {\n const payload = (await response.json()) as {\n sessionId?: unknown;\n targets?: unknown;\n webSocketDebuggerUrl?: unknown;\n };\n const sessionId =\n typeof payload.sessionId === \"string\" ? payload.sessionId : \"\";\n\n if (!sessionId) {\n throw new Error(\"Browser Rendering response did not include a sessionId\");\n }\n\n return {\n sessionId,\n targets: Array.isArray(payload.targets)\n ? (payload.targets as BrowserTargetInfo[])\n : undefined,\n webSocketDebuggerUrl:\n typeof payload.webSocketDebuggerUrl === \"string\"\n ? payload.webSocketDebuggerUrl\n : undefined\n };\n}\n\nexport async function createBrowserSession(\n browser: BrowserBinding,\n options?: {\n keepAliveMs?: number;\n includeTargets?: boolean;\n recording?: boolean;\n guardrails?: BrowserSessionGuardrails;\n }\n): Promise<BrowserSessionInfo> {\n // Guardrails ride the acquire request's JSON body (the query string only\n // carries scalar options). The endpoint accepts an empty `{}` body —\n // verified against the live acquire API — so the request shape stays\n // uniform whether or not guardrails are set.\n const response = await browser.fetch(\n browserSessionEndpoint(undefined, options),\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(\n options?.guardrails ? { guardrails: options.guardrails } : {}\n )\n }\n );\n\n if (!response.ok) {\n throw new BrowserRenderingError(\n `Failed to create Browser Rendering session: ${response.status}`,\n response.status\n );\n }\n\n return parseBrowserSessionInfo(response);\n}\n\nexport async function listBrowserTargets(\n browser: BrowserBinding,\n sessionId: string\n): Promise<BrowserTargetInfo[]> {\n const response = await browser.fetch(\n `https://localhost/v1/devtools/browser/${sessionId}/json/list`\n );\n\n if (!response.ok) {\n throw new BrowserRenderingError(\n `Failed to list Browser Rendering targets for ${sessionId}: ${response.status}`,\n response.status\n );\n }\n\n const payload = (await response.json()) as unknown;\n return Array.isArray(payload) ? (payload as BrowserTargetInfo[]) : [];\n}\n\nexport async function deleteBrowserSession(\n browser: BrowserBinding,\n sessionId: string\n): Promise<void> {\n const response = await browser.fetch(\n `https://localhost/v1/devtools/browser/${sessionId}`,\n { method: \"DELETE\" }\n );\n\n if (!response.ok && response.status !== 404) {\n throw new BrowserRenderingError(\n `Failed to delete Browser Rendering session ${sessionId}: ${response.status}`,\n response.status\n );\n }\n}\n\n/**\n * Connect to a Browser Rendering session and delete it when closed.\n */\nexport async function connectBrowser(\n browser: BrowserBinding,\n options?: number | ConnectBrowserOptions\n): Promise<CdpConnection> {\n const normalizedOptions: ConnectBrowserOptions =\n typeof options === \"number\" ? { timeoutMs: options } : (options ?? {});\n if (normalizedOptions.browser === \"kitesurf\") {\n // The options union already rejects these at the type level for literal\n // call sites; plain-JS callers and spreads can still smuggle them in.\n // Explicitly disabled values are tolerated but never sent — `keep_alive=0`\n // is not a valid Kitesurf query parameter.\n const smuggled = normalizedOptions as {\n keepAliveMs?: number;\n includeTargets?: boolean;\n recording?: boolean;\n };\n if (smuggled.keepAliveMs || smuggled.includeTargets || smuggled.recording) {\n throw new Error(\n \"Kitesurf does not support keepAliveMs, includeTargets, or recording\"\n );\n }\n }\n\n const response = await browser.fetch(\n browserSessionEndpoint(\n undefined,\n normalizedOptions.browser === \"kitesurf\"\n ? { browser: \"kitesurf\" }\n : {\n keepAliveMs: normalizedOptions.keepAliveMs,\n includeTargets: normalizedOptions.includeTargets,\n recording: normalizedOptions.recording\n }\n ),\n { headers: { Upgrade: \"websocket\" } }\n );\n\n const ws = response.webSocket;\n if (!ws) {\n throw new Error(\n \"Browser Rendering binding did not return a WebSocket. \" +\n \"Ensure the 'browser' binding is configured in wrangler.jsonc.\"\n );\n }\n\n if (normalizedOptions.browser === \"kitesurf\") {\n // A Kitesurf browser is scoped to this WebSocket. Browser Run may return\n // an ID for analytics correlation, but it cannot be used with the\n // session-scoped reconnect or delete endpoints.\n ws.accept();\n return new CdpConnection(ws, { timeoutMs: normalizedOptions.timeoutMs });\n }\n\n const sessionId = response.headers.get(\"cf-browser-session-id\");\n if (!sessionId) {\n throw new Error(\n \"Browser Rendering binding did not include a session ID when opening the CDP WebSocket\"\n );\n }\n\n ws.accept();\n return new CdpConnection(ws, {\n timeoutMs: normalizedOptions.timeoutMs,\n onClose: () => {\n deleteBrowserSession(browser, sessionId).catch((error: unknown) => {\n console.warn(\n `[agents/browser] Failed to delete one-shot Browser Run session ${sessionId}`,\n error\n );\n });\n },\n sessionId\n });\n}\n\n/**\n * Fetch a Browser Run [session recording](https://developers.cloudflare.com/browser-run/features/session-recording/)\n * by session id, via the Browser Rendering REST API.\n *\n * A recording is only available **after** the session closes (explicit\n * `closeSession()`, idle `keep_alive` expiry, or sweep) and is retained for 30\n * days. Capture the session id while the session is alive — e.g. from\n * `connector.liveView()`/`sessionInfo()` — then call this once it has ended.\n *\n * Unlike the binding-based helpers, this hits `api.cloudflare.com` directly, so\n * it needs an account id and an API token with `Browser Rendering` read access\n * (the Workers Browser Run binding cannot read recordings).\n */\nexport async function getBrowserRecording(options: {\n accountId: string;\n apiToken: string;\n sessionId: string;\n /** Override for testing; defaults to the global `fetch`. */\n fetchImpl?: typeof fetch;\n}): Promise<BrowserRecording> {\n const { accountId, apiToken, sessionId } = options;\n const fetchImpl = options.fetchImpl ?? fetch;\n const endpoint = `https://api.cloudflare.com/client/v4/accounts/${accountId}/browser-rendering/recording/${sessionId}`;\n\n const response = await fetchImpl(endpoint, {\n headers: { Authorization: `Bearer ${apiToken}` }\n });\n\n if (!response.ok) {\n throw new BrowserRenderingError(\n `Failed to fetch Browser Run recording for ${sessionId}: ${response.status}`,\n response.status\n );\n }\n\n // The recording endpoint returns the recording object directly; tolerate a\n // standard v4 `{ result }` envelope in case that changes.\n const payload = (await response.json()) as\n | BrowserRecording\n | { result?: BrowserRecording };\n const recording =\n \"result\" in payload && payload.result ? payload.result : payload;\n\n return recording as BrowserRecording;\n}\n\nexport interface ConnectBrowserSessionOptions {\n timeoutMs?: number;\n /**\n * Invoked once when the returned {@link CdpConnection} reaches a terminal\n * state — an explicit `close()`, peer closure, or a socket error. The\n * session itself is never deleted on close — pass an `onClose` that\n * deletes it for one-shot (create-and-close) semantics.\n */\n onClose?: () => void;\n /**\n * Invoked on every CDP command sent over the returned {@link CdpConnection} —\n * an activity signal for idle tracking. Keep it cheap and synchronous;\n * throttle any I/O it triggers.\n */\n onActivity?: () => void;\n}\n\n/**\n * Connect to an existing Browser Rendering session without deleting it on close.\n */\nexport async function connectBrowserSession(\n browser: BrowserBinding,\n sessionId: string,\n options?: ConnectBrowserSessionOptions\n): Promise<CdpConnection>;\n/**\n * @deprecated Pass `{ timeoutMs }` instead of a bare number — the numeric\n * form will be removed.\n */\nexport async function connectBrowserSession(\n browser: BrowserBinding,\n sessionId: string,\n timeoutMs?: number\n): Promise<CdpConnection>;\nexport async function connectBrowserSession(\n browser: BrowserBinding,\n sessionId: string,\n options?: number | ConnectBrowserSessionOptions\n): Promise<CdpConnection> {\n const normalized =\n typeof options === \"number\" ? { timeoutMs: options } : (options ?? {});\n const response = await browser.fetch(browserSessionEndpoint(sessionId), {\n headers: { Upgrade: \"websocket\" }\n });\n\n const ws = response.webSocket;\n if (!ws) {\n // Carry the upgrade status: a 404/410 here means the browser expired\n // after the caller last saw it alive (see isMissingBrowserSession).\n throw new BrowserRenderingError(\n `Browser Rendering binding did not return a WebSocket for session ${sessionId} (${response.status})`,\n response.status\n );\n }\n\n ws.accept();\n return new CdpConnection(ws, {\n timeoutMs: normalized.timeoutMs,\n onClose: normalized.onClose,\n sessionId,\n onActivity: normalized.onActivity\n });\n}\n\n/** One-shot session options for the default Chromium engine. */\nexport interface OneShotChromiumSessionOptions {\n /** Select the browser engine. Defaults to Chromium. */\n browser?: \"chromium\";\n timeoutMs?: number;\n /** Platform `keep_alive` in milliseconds. */\n keepAliveMs?: number;\n /** Opt into Browser Run session recording (rrweb capture). */\n recording?: boolean;\n /** Hostname guardrails, fixed at launch. */\n guardrails?: BrowserSessionGuardrails;\n}\n\n/**\n * One-shot session options for Kitesurf. The Chromium-only options —\n * `guardrails`, `keepAliveMs`, `recording` — do not exist on this arm:\n * Kitesurf does not support them.\n */\nexport interface OneShotKitesurfSessionOptions {\n browser: \"kitesurf\";\n timeoutMs?: number;\n}\n\n/**\n * Engine-discriminated {@link openOneShotBrowserSession} options: selecting\n * `browser: \"kitesurf\"` removes the Chromium-only options at the type level.\n */\nexport type OneShotBrowserSessionOptions =\n | OneShotChromiumSessionOptions\n | OneShotKitesurfSessionOptions;\n\n/**\n * Open a one-shot browser session: create, connect, and delete the platform\n * session when the returned {@link CdpConnection} closes. No store involved —\n * one-shot sessions have no name and no durability.\n */\nexport async function openOneShotBrowserSession(\n browser: BrowserBinding,\n options: OneShotBrowserSessionOptions = {}\n): Promise<CdpConnection> {\n if (options.browser === \"kitesurf\") {\n // The options union already rejects these at the type level for literal\n // call sites; plain-JS callers and spreads can still smuggle them in, so\n // fail loudly in one place with one message.\n const smuggled = options as {\n guardrails?: unknown;\n keepAliveMs?: unknown;\n recording?: unknown;\n };\n if (smuggled.guardrails || smuggled.keepAliveMs || smuggled.recording) {\n throw new Error(\n \"Kitesurf does not support guardrails, keepAliveMs, or recording\"\n );\n }\n // Kitesurf browsers are scoped to their WebSocket — connectBrowser is\n // already one-shot there.\n return connectBrowser(browser, {\n browser: \"kitesurf\",\n timeoutMs: options.timeoutMs\n });\n }\n\n const info = await createBrowserSession(browser, {\n keepAliveMs: options.keepAliveMs,\n recording: options.recording,\n guardrails: options.guardrails\n });\n try {\n return await connectBrowserSession(browser, info.sessionId, {\n timeoutMs: options.timeoutMs,\n onClose: () => {\n deleteBrowserSession(browser, info.sessionId).catch(\n (error: unknown) => {\n console.warn(\n `[agents/browser] Failed to delete one-shot Browser Run session ${info.sessionId}`,\n error\n );\n }\n );\n }\n });\n } catch (error) {\n // The session was allocated but never got its delete-on-close owner —\n // reclaim it now instead of leaving it to expire.\n try {\n await deleteBrowserSession(browser, info.sessionId);\n } catch {\n // Best-effort: keep_alive expiry reclaims it.\n }\n throw error;\n }\n}\n","import { Validator, type OutputUnit, type Schema } from \"@cfworker/json-schema\";\nimport type { ConnectorTool } from \"@cloudflare/codemode\";\n\nfunction formatToolValidationError(\n connector: string,\n tool: string,\n errors: OutputUnit[]\n): string {\n // A failing property emits both a generic parent `properties` error and a\n // specific child error. Prefer the latter so the model sees what to fix.\n const specific = errors.filter((error) => error.keyword !== \"properties\");\n const relevant = specific.length > 0 ? specific : errors;\n const details = relevant.map((error) => {\n const location = error.instanceLocation\n .replace(/^#\\/?/, \"\")\n .replaceAll(\"~1\", \"/\")\n .replaceAll(\"~0\", \"~\")\n .replaceAll(\"/\", \".\");\n return `${location ? ` at ${location}` : \"\"}: ${error.error}`;\n });\n return `Invalid arguments for ${connector}.${tool}${details.join(\";\")}`;\n}\n\n/**\n * Validate a connector tool's arguments against its input schema before it\n * runs, so the model gets a precise error instead of a failure deep inside\n * browser work. An omitted argument counts as `{}`: argumentless tools are\n * documented as `cdp.spec()`.\n */\nexport function validateConnectorArgs(\n connector: string,\n name: string,\n tool: ConnectorTool\n): ConnectorTool {\n if (!tool.inputSchema) return tool;\n\n // Both types describe draft-7 schemas, but @cfworker's `Schema` type is\n // narrower than JSONSchema7 around boolean subschemas.\n const schema = tool.inputSchema as unknown as Schema;\n const validator = new Validator(schema, \"7\", false);\n return {\n ...tool,\n execute: async (args, ctx) => {\n const input = args === undefined ? {} : args;\n const result = validator.validate(input);\n if (!result.valid) {\n throw new Error(\n formatToolValidationError(connector, name, result.errors)\n );\n }\n return await tool.execute(input, ctx);\n }\n };\n}\n","/**\n * Live View vocabulary shared by every host-side surface that mints links:\n * the connector's `getLiveViewUrl` tool and `Browser.liveView()`. Live View\n * URLs are bearer credentials — mint them fresh from a target listing when a\n * human is about to view, and never persist them.\n */\n\nimport type { BrowserTargetInfo } from \"./browser-run\";\n\n/**\n * Live View rendering mode (the `mode` query param the hosted UI at\n * `live.browser.run` understands):\n *\n * - `\"tab\"` — a standalone, interactive page view (best for handing control\n * to a human).\n * - `\"devtools\"` — the full DevTools inspector panel (Elements, Console,\n * Network, …).\n *\n * Omit it to use whatever mode the binding's `devtoolsFrontendUrl` defaults\n * to.\n */\nexport type LiveViewMode = \"tab\" | \"devtools\";\n\n/** A single tab's Live View URL. */\nexport interface BrowserLiveViewUrl {\n /** Open this in a browser to watch/control the tab in real time. */\n url: string;\n /** CDP target (tab) id the URL points at. */\n targetId: string;\n /** Milliseconds the URL stays valid from when it was generated (~5 min). */\n expiresInMs: number;\n}\n\nexport interface BrowserLiveViewTarget {\n targetId: string;\n /** Embeddable Live View URL (the `devtoolsFrontendUrl`) for this tab. */\n url: string;\n /** The page the tab is currently showing (e.g. `https://example.com`). */\n pageUrl?: string;\n title?: string;\n type?: string;\n}\n\n/** Live View URLs for every tab in a session. */\nexport interface BrowserLiveView {\n sessionId: string;\n targets: BrowserLiveViewTarget[];\n /** Milliseconds the URLs stay valid from when they were generated (~5 min). */\n expiresInMs: number;\n}\n\n/**\n * Browser Run mints `devtoolsFrontendUrl`s (the Live View links) that are\n * valid for ~5 minutes. We surface the window so callers can decide how long\n * a shared link is good for before re-listing targets.\n */\nexport const LIVE_VIEW_URL_TTL_MS = 5 * 60 * 1000;\n\n/**\n * Rewrite the hosted Live View UI's `mode` query param (`tab` | `devtools`).\n * The raw `devtoolsFrontendUrl` is returned unchanged when no mode is asked\n * for or the URL can't be parsed.\n */\nexport function applyLiveViewMode(rawUrl: string, mode?: LiveViewMode): string {\n if (!mode) return rawUrl;\n try {\n const url = new URL(rawUrl);\n url.searchParams.set(\"mode\", mode === \"devtools\" ? \"devtools\" : \"tab\");\n return url.toString();\n } catch {\n return rawUrl;\n }\n}\n\n/**\n * Project a fresh target listing into Live View links — one per tab that has\n * a `devtoolsFrontendUrl`. Pure; the caller supplies just-listed targets.\n */\nexport function createLiveView(\n sessionId: string,\n targets: BrowserTargetInfo[],\n mode?: LiveViewMode\n): BrowserLiveView {\n return {\n sessionId,\n targets: targets\n .filter((target) => target.devtoolsFrontendUrl)\n .map((target) => ({\n targetId: target.id,\n url: applyLiveViewMode(target.devtoolsFrontendUrl!, mode),\n pageUrl: target.url,\n title: target.title,\n type: target.type\n })),\n expiresInMs: LIVE_VIEW_URL_TTL_MS\n };\n}\n","/**\n * Chrome DevTools Protocol spec fetching + caching.\n *\n * The raw `/json/protocol` payload is normalized into a searchable shape and\n * cached per source: `cdpUrl` specs by endpoint + headers, Browser Rendering\n * specs by the binding itself (a WeakMap) so two different bindings in the\n * same isolate don't share an entry. The CDP protocol is identical across\n * bindings, but per-binding keys avoid surprising cross-binding cache reads.\n */\n\nimport type { BrowserBinding } from \"./browser-run\";\n\n/** A parameter, return value, or type property in the raw protocol. */\ninterface RawCdpField {\n name: string;\n description?: string;\n optional?: boolean;\n experimental?: boolean;\n deprecated?: boolean;\n type?: string;\n $ref?: string;\n enum?: string[];\n items?: { type?: string; $ref?: string; enum?: string[] };\n}\n\ninterface RawCdpCommand {\n name: string;\n description?: string;\n experimental?: boolean;\n deprecated?: boolean;\n parameters?: RawCdpField[];\n returns?: RawCdpField[];\n}\n\ninterface RawCdpEvent {\n name: string;\n description?: string;\n experimental?: boolean;\n deprecated?: boolean;\n parameters?: RawCdpField[];\n}\n\ninterface RawCdpType {\n id: string;\n description?: string;\n experimental?: boolean;\n deprecated?: boolean;\n type?: string;\n enum?: string[];\n properties?: RawCdpField[];\n items?: { type?: string; $ref?: string; enum?: string[] };\n}\n\n/** Raw CDP protocol domain from `/json/protocol` */\ninterface RawCdpDomain {\n domain: string;\n description?: string;\n experimental?: boolean;\n deprecated?: boolean;\n commands?: RawCdpCommand[];\n events?: RawCdpEvent[];\n types?: RawCdpType[];\n}\n\n/**\n * The element type of an array field or type. `$ref` is always\n * domain-qualified (`\"Network.Cookie\"`), matching a type's `name`.\n */\nexport interface CdpItems {\n type?: string;\n $ref?: string;\n enum?: string[];\n}\n\n/**\n * A command parameter, return value, event parameter, or type property.\n * Either `type` (a JSON type such as `\"string\"` or `\"array\"`) or `$ref`\n * (a domain-qualified type name matching a type's `name`) is set.\n */\nexport interface CdpField {\n name: string;\n description?: string;\n optional?: boolean;\n experimental?: boolean;\n deprecated?: boolean;\n type?: string;\n $ref?: string;\n enum?: string[];\n items?: CdpItems;\n}\n\nexport interface SearchableCdpSpec {\n domains: Array<{\n name: string;\n description?: string;\n experimental?: boolean;\n deprecated?: boolean;\n commands: Array<{\n name: string;\n method: string;\n description?: string;\n experimental?: boolean;\n deprecated?: boolean;\n parameters: CdpField[];\n returns: CdpField[];\n }>;\n events: Array<{\n name: string;\n event: string;\n description?: string;\n experimental?: boolean;\n deprecated?: boolean;\n parameters: CdpField[];\n }>;\n types: Array<{\n id: string;\n name: string;\n description?: string;\n experimental?: boolean;\n deprecated?: boolean;\n /** JSON type of the value, e.g. `\"string\"`, `\"object\"`, `\"array\"`. */\n type?: string;\n enum?: string[];\n properties: CdpField[];\n items?: CdpItems;\n }>;\n }>;\n}\n\nexport interface CdpSpecSource {\n /** Browser Rendering binding (Fetcher) — used in production */\n browser?: BrowserBinding;\n /** CDP base URL override (e.g. http://localhost:9222) */\n cdpUrl?: string;\n /** Headers to send with CDP URL discovery requests */\n cdpHeaders?: Record<string, string>;\n /**\n * An existing Browser Run session to read the protocol from. Without it,\n * loading through the binding creates (and deletes) a throwaway session.\n */\n sessionId?: string;\n}\n\nconst MISSING_BROWSER_CONFIG =\n \"Either 'browser' (Fetcher binding) or 'cdpUrl' must be provided\";\n\ninterface SpecCacheEntry {\n spec: SearchableCdpSpec;\n cachedAt: number;\n}\n\nconst urlSpecCache = new Map<string, SpecCacheEntry>();\nconst bindingSpecCache = new WeakMap<BrowserBinding, SpecCacheEntry>();\n\nconst CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes\n\n/** Qualify a same-domain `$ref` (`\"FrameId\"` → `\"Page.FrameId\"`). */\nfunction qualifyRef(domain: string, ref: string | undefined) {\n if (ref === undefined) return undefined;\n return ref.includes(\".\") ? ref : `${domain}.${ref}`;\n}\n\nfunction normalizeItems(\n domain: string,\n items: RawCdpType[\"items\"]\n): CdpItems | undefined {\n if (!items) return undefined;\n return {\n type: items.type,\n $ref: qualifyRef(domain, items.$ref),\n enum: items.enum\n };\n}\n\nfunction normalizeFields(\n domain: string,\n fields: RawCdpField[] | undefined\n): CdpField[] {\n return (fields ?? []).map((field) => ({\n name: field.name,\n description: field.description,\n optional: field.optional,\n experimental: field.experimental,\n deprecated: field.deprecated,\n type: field.type,\n $ref: qualifyRef(domain, field.$ref),\n enum: field.enum,\n items: normalizeItems(domain, field.items)\n }));\n}\n\nfunction normalizeCdpSpec(spec: {\n domains?: RawCdpDomain[];\n}): SearchableCdpSpec {\n return {\n domains: (spec.domains ?? []).map(({ domain, ...raw }) => ({\n name: domain,\n description: raw.description,\n experimental: raw.experimental,\n deprecated: raw.deprecated,\n commands: (raw.commands ?? []).map((command) => ({\n name: command.name,\n method: `${domain}.${command.name}`,\n description: command.description,\n experimental: command.experimental,\n deprecated: command.deprecated,\n parameters: normalizeFields(domain, command.parameters),\n returns: normalizeFields(domain, command.returns)\n })),\n events: (raw.events ?? []).map((event) => ({\n name: event.name,\n event: `${domain}.${event.name}`,\n description: event.description,\n experimental: event.experimental,\n deprecated: event.deprecated,\n parameters: normalizeFields(domain, event.parameters)\n })),\n types: (raw.types ?? []).map((type) => ({\n id: type.id,\n name: `${domain}.${type.id}`,\n description: type.description,\n experimental: type.experimental,\n deprecated: type.deprecated,\n type: type.type,\n enum: type.enum,\n properties: normalizeFields(domain, type.properties),\n items: normalizeItems(domain, type.items)\n }))\n }))\n };\n}\n\nfunction getSpecCacheKey(\n source: string,\n headers?: Record<string, string>\n): string {\n const headerEntries = Object.entries(headers ?? {}).sort(([a], [b]) =>\n a.localeCompare(b)\n );\n return `${source}:${JSON.stringify(headerEntries)}`;\n}\n\nasync function getCachedSpec<K>(\n cache: {\n get(key: K): SpecCacheEntry | undefined;\n set(key: K, entry: SpecCacheEntry): void;\n },\n key: K,\n load: () => Promise<{ domains?: RawCdpDomain[] }>\n): Promise<SearchableCdpSpec> {\n const cached = cache.get(key);\n if (cached && Date.now() - cached.cachedAt < CACHE_TTL_MS) {\n return cached.spec;\n }\n\n const spec = normalizeCdpSpec(await load());\n cache.set(key, { spec, cachedAt: Date.now() });\n return spec;\n}\n\nasync function fetchCdpSpecFromUrl(\n cdpBaseUrl: string,\n headers?: Record<string, string>\n): Promise<SearchableCdpSpec> {\n const endpoint = new URL(\"/json/protocol\", cdpBaseUrl).toString();\n\n return getCachedSpec(\n urlSpecCache,\n getSpecCacheKey(endpoint, headers),\n async () => {\n const response = await fetch(endpoint, { headers });\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch CDP spec from ${endpoint}: ${response.status}`\n );\n }\n\n return (await response.json()) as { domains?: RawCdpDomain[] };\n }\n );\n}\n\nasync function fetchCdpSpecFromSession(\n browser: BrowserBinding,\n sessionId: string\n): Promise<SearchableCdpSpec> {\n return getCachedSpec(bindingSpecCache, browser, async () => {\n const response = await browser.fetch(\n `https://localhost/v1/devtools/browser/${sessionId}/json/protocol`\n );\n if (!response.ok) {\n throw new Error(\n `Failed to fetch CDP spec from Browser Rendering: ${response.status}`\n );\n }\n return (await response.json()) as { domains?: RawCdpDomain[] };\n });\n}\n\nasync function fetchCdpSpecFromBrowser(\n browser: BrowserBinding\n): Promise<SearchableCdpSpec> {\n return getCachedSpec(bindingSpecCache, browser, async () => {\n const createResponse = await browser.fetch(\n \"https://localhost/v1/devtools/browser\",\n {\n method: \"POST\"\n }\n );\n\n if (!createResponse.ok) {\n throw new Error(\n \"Failed to create Browser Rendering session for protocol fetch: \" +\n `${createResponse.status}`\n );\n }\n\n const payload = (await createResponse.json()) as { sessionId?: string };\n const sessionId = payload.sessionId;\n if (!sessionId) {\n throw new Error(\n \"Browser Rendering session response did not include a sessionId\"\n );\n }\n\n try {\n const response = await browser.fetch(\n `https://localhost/v1/devtools/browser/${sessionId}/json/protocol`\n );\n\n if (!response.ok) {\n throw new Error(\n \"Failed to fetch CDP spec from Browser Rendering: \" +\n `${response.status}`\n );\n }\n\n return (await response.json()) as { domains?: RawCdpDomain[] };\n } finally {\n try {\n await browser.fetch(\n `https://localhost/v1/devtools/browser/${sessionId}`,\n {\n method: \"DELETE\"\n }\n );\n } catch {\n // Cleanup failure should not mask the original result or error\n }\n }\n });\n}\n\n/** Load the (cached) searchable CDP spec for a browser source. */\nexport async function loadCdpSpec(\n source: CdpSpecSource\n): Promise<SearchableCdpSpec> {\n if (source.cdpUrl) {\n return fetchCdpSpecFromUrl(source.cdpUrl, source.cdpHeaders);\n }\n if (source.browser && source.sessionId) {\n return fetchCdpSpecFromSession(source.browser, source.sessionId);\n }\n if (source.browser) {\n return fetchCdpSpecFromBrowser(source.browser);\n }\n throw new Error(MISSING_BROWSER_CONFIG);\n}\n","type MaybePromise<T> = T | Promise<T>;\n\nexport interface StoredBrowserSession {\n sessionId: string;\n createdAt: number;\n updatedAt: number;\n /**\n * Set when a sweep closed this entry's Browser Run session but kept the\n * entry as a tombstone, so a later resume of the owning execution fails\n * loudly instead of silently continuing in a fresh browser.\n */\n closedAt?: number;\n /**\n * Browser scope records only: the tab (CDP `targetId`) the scope last\n * worked in, so `sessionId: \"active\"` in a later execution lands on the\n * same page. CDP session ids die with each connection; target ids live as\n * long as the tab.\n */\n activeTargetId?: string;\n}\n\nexport interface BrowserSessionLock {\n release(): MaybePromise<void>;\n}\n\nexport interface BrowserSessionStore {\n /**\n * Acquire an exclusive lock for this session key. The lock must serialize\n * all holders using the same key. Held only around storage reads/writes —\n * never across Browser Rendering network calls.\n */\n acquireLock(key: string): MaybePromise<BrowserSessionLock>;\n get(key: string): MaybePromise<StoredBrowserSession | undefined>;\n set(key: string, session: StoredBrowserSession): MaybePromise<void>;\n delete(key: string): MaybePromise<void>;\n /**\n * List stored sessions by key prefix. Optional — used by sweeps to find\n * orphaned per-execution sessions; without it only the shared session key\n * is swept.\n */\n list?(prefix: string): MaybePromise<Map<string, StoredBrowserSession>>;\n}\n\n/**\n * A {@link BrowserSessionStore} that can list by prefix, as `Browser` needs:\n * it lists a browser's scope records to cap them and to see which tabs\n * other scopes are working in.\n */\nexport type ListableBrowserSessionStore = BrowserSessionStore &\n Required<Pick<BrowserSessionStore, \"list\">>;\n\nexport class DurableBrowserSessionStore implements BrowserSessionStore {\n static #queues = new WeakMap<\n DurableObjectStorage,\n Map<string, Promise<void>>\n >();\n\n constructor(private readonly storage: DurableObjectStorage) {}\n\n async acquireLock(key: string): Promise<BrowserSessionLock> {\n let queues = DurableBrowserSessionStore.#queues.get(this.storage);\n if (!queues) {\n queues = new Map();\n DurableBrowserSessionStore.#queues.set(this.storage, queues);\n }\n\n const previous = queues.get(key) ?? Promise.resolve();\n let releaseQueue: () => void = () => undefined;\n const current = previous.then(\n () =>\n new Promise<void>((resolve) => {\n releaseQueue = resolve;\n })\n );\n queues.set(key, current);\n await previous;\n\n let released = false;\n return {\n release: () => {\n if (released) return;\n released = true;\n if (queues.get(key) === current) {\n queues.delete(key);\n }\n releaseQueue();\n }\n };\n }\n\n async get(key: string): Promise<StoredBrowserSession | undefined> {\n return this.storage.get<StoredBrowserSession>(this.#storageKey(key));\n }\n\n async set(key: string, session: StoredBrowserSession): Promise<void> {\n await this.storage.put(this.#storageKey(key), session);\n }\n\n async delete(key: string): Promise<void> {\n await this.storage.delete(this.#storageKey(key));\n }\n\n async list(prefix: string): Promise<Map<string, StoredBrowserSession>> {\n const storagePrefix = this.#storageKey(prefix);\n const entries = await this.storage.list<StoredBrowserSession>({\n prefix: storagePrefix\n });\n const result = new Map<string, StoredBrowserSession>();\n for (const [storageKey, value] of entries) {\n result.set(storageKey.slice(\"browser-session:\".length), value);\n }\n return result;\n }\n\n #storageKey(key: string): string {\n return `browser-session:${key}`;\n }\n}\n\n/**\n * Default idle window used by {@link BrowserConnector.sweep} for the shared\n * (reuse/promoted) session entry.\n */\nexport const DEFAULT_SWEEP_IDLE_MS = 10 * 60 * 1000;\n"],"mappings":";;;;AAuCA,MAAM,qBAAqB;;AAG3B,MAAa,uBAAuB;;AAGpC,IAAa,mBAAb,cAAsC,MAAM;CAO1C,YAAY,QAAgB,MAA0B,SAAiB;EACrE,MAAM,aAAa,QAAQ,UAAU,IAAI,QAAQ,OAAO,QAAQ;EAPlE,KAAkB,OAAO;EAQvB,KAAK,OAAO;EACZ,KAAK,SAAS;CAChB;AACF;AACA,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;AAU1B,IAAa,gBAAb,MAA2B;CAuBzB,YACE,QACA,oBACA,SACA,WACA;;;4CA1BQ,CAAA;6DACC,IAAI,IAA4B,CAAA;8CACjB,CAAC,CAAA;;;8CAGf,KAAA;;EAsBV,MAAM,UACJ,OAAO,uBAAuB,WAC1B,qBACA;GAAE,WAAW;GAAoB;GAAS;EAAU;EAC1D,uBAAA,SAAA,MAAe,MAAA;EACf,uBAAA,mBAAA,MAAyB,QAAQ,aAAa,kBAAA;EAC9C,uBAAA,UAAA,MAAgB,QAAQ,OAAA;EACxB,KAAK,YAAY,QAAQ;EACzB,uBAAA,aAAA,MAAmB,QAAQ,UAAA;EAE3B,OAAO,iBAAiB,YAAY,UAAA,kBAAA,sBAAU,MAAA,cAAA,CAAA,CAAA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M;EAC7C,MAAM,UAAU,MAAM,KAAK,QAAQ,KAA2B,EAC5D,QAAQ,cACV,CAAC;EACD,MAAM,yBAAS,IAAI,IAAkC;EACrD,KAAK,MAAM,CAAC,YAAY,UAAU,SAChC,OAAO,IAAI,WAAW,MAAM,EAAyB,GAAG,KAAK;EAE/D,OAAO;CACT;AAKF;AAHE,SAAA,YAAY,KAAqB;CAC/B,OAAO,mBAAmB;AAC5B;mCAhEiB,IAAI,QAGnB,EAAA;;;;;AAoEJ,MAAa,wBAAwB,MAAU"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"settings-C45hDliX.js","names":[],"sources":["../src/models/core/settings.ts"],"sourcesContent":["import type { WorkersAIModelId } from \"./catalog\";\n\n/** The gateway id Cloudflare auto-creates on first use. */\nexport const DEFAULT_GATEWAY_ID = \"default\";\n\n/** Key that per-call options live under in a framework's per-call options bag. */\nexport const PROVIDER_OPTIONS_KEY = \"cloudflare\";\n\n/**\n * AI Gateway settings for a request. The gateway is an option, not a separate\n * product: every call goes through one, and `id` defaults to `\"default\"`,\n * which Cloudflare creates on first use.\n *\n * @experimental This surface is experimental and may change.\n */\nexport interface GatewayOptions {\n /** Gateway id. Defaults to `\"default\"` (auto-created on first use). */\n id?: string;\n /** Bypass the cache for this request. */\n skipCache?: boolean;\n /** Cache lifetime in seconds. */\n cacheTtl?: number;\n /** Explicit cache key, instead of the request-derived one. */\n cacheKey?: string;\n /** Whether the gateway stores the request/response in its log. */\n collectLog?: boolean;\n /** Arbitrary key/values attached to the gateway log entry. */\n metadata?: Record<string, string | number | boolean | null>;\n /** Correlates several requests into one gateway event. */\n eventId?: string;\n /** Upstream request timeout in milliseconds. */\n requestTimeoutMs?: number;\n /** Server-side retry policy for the upstream provider call. */\n retries?: {\n maxAttempts?: 1 | 2 | 3 | 4 | 5;\n retryDelayMs?: number;\n backoff?: \"constant\" | \"linear\" | \"exponential\";\n };\n}\n\n/**\n * How `createAI` reaches Cloudflare: the Workers AI binding, and nothing else.\n * Workers AI models go through `env.AI.run`, vendor models through\n * `env.AI.gateway(id).run` — both are the binding, so there is no HTTP\n * transport, no account id and no API token to hold.\n *\n * @experimental This surface is experimental and may change.\n */\nexport type AISettings = {\n /** The `AI` binding from a Worker's env. */\n binding: Ai;\n} & ProviderGatewaySettings;\n\n/**\n * Provider-wide gateway defaults, in either spelling: nested under `gateway`,\n * or flat (`{ id: \"prod\", cacheTtl: 60 }`). Both merge, the flat key winning.\n *\n * @experimental This surface is experimental and may change.\n */\nexport interface ProviderGatewaySettings extends GatewayOptions {\n /** Gateway id or full gateway options. */\n gateway?: string | GatewayOptions;\n}\n\n/**\n * Per-model and per-call options. The flat gateway keys are sugar for\n * `gateway: { ... }`; both forms merge, with the flat key winning.\n *\n * The same shape is accepted per call under\n * `providerOptions.cloudflare`, where it takes precedence over the per-model\n * options, which in turn take precedence over the `createAI` settings.\n *\n * `Leg` is what a framework module accepts as a fallback leg. Workers AI ids\n * are the only kind this module can resolve on its own, so they are the\n * default; a module whose legs may also be model objects says so\n * (`ModelOptions<WorkersAIModelId | LanguageModelV4>`) rather than rebuilding\n * the type.\n *\n * @experimental This surface is experimental and may change.\n */\nexport interface ModelOptions<\n Leg = WorkersAIModelId\n> extends ProviderGatewaySettings {\n /**\n * Models to try, in order, if the primary fails before any output is\n * produced. A leg travels with the chain's gateway options — those win over\n * a leg's own, and `metadata` merges — while everything a leg was built with\n * itself stays its own. Client-side today; becomes server-side when the\n * platform ships model-first routing.\n */\n fallback?: Leg[];\n /** Extra request headers, merged last. */\n headers?: Record<string, string>;\n /**\n * Workers AI only: route same-key requests to the same replica for\n * prefix-cache hits. Sent as the `x-session-affinity` header.\n */\n sessionAffinity?: string;\n /**\n * Explicit reasoning effort. `null` disables reasoning on models that\n * support toggling it. The unified AI SDK `reasoning` call option maps onto\n * this when this is not set.\n */\n reasoningEffort?: \"low\" | \"medium\" | \"high\" | null;\n /**\n * Workers AI only: forwarded verbatim as `chat_template_kwargs`, e.g.\n * `{ enable_thinking: false }`.\n */\n chatTemplateKwargs?: Record<string, unknown>;\n}\n\n/** A gateway config with the id filled in. */\nexport interface ResolvedGateway extends GatewayOptions {\n id: string;\n}\n\n/** Everything one request needs, after merging all three option layers. */\nexport interface ResolvedOptions {\n gateway: ResolvedGateway;\n headers: Record<string, string>;\n sessionAffinity: string | undefined;\n reasoningEffort: \"low\" | \"medium\" | \"high\" | null | undefined;\n chatTemplateKwargs: Record<string, unknown> | undefined;\n /**\n * The fallback legs given as ids. A module whose legs may also be model\n * objects keeps its own ordered list; this one is what the id-only callers\n * (embeddings, the other modalities) need.\n */\n fallback: string[];\n}\n\n/** The id legs of a fallback list; model objects are their module's business. */\nfunction idLegs(fallback: unknown[] | undefined): string[] {\n return (fallback ?? []).filter(\n (leg): leg is string => typeof leg === \"string\"\n );\n}\n\n/** Strips `undefined` values so a later layer never blanks an earlier one. */\nfunction defined<T extends object>(value: T): T {\n const result: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value)) {\n if (entry !== undefined) result[key] = entry;\n }\n return result as T;\n}\n\nfunction normalizeGateway(\n gateway: string | GatewayOptions | undefined\n): GatewayOptions {\n if (gateway === undefined) return {};\n // An explicit `undefined` inside a gateway object means \"not set\", exactly\n // as the flat sugar does; it must not blank out a lower layer's value.\n return typeof gateway === \"string\" ? { id: gateway } : defined(gateway);\n}\n\n/**\n * Folds one layer's flat gateway sugar into its `gateway` object. The flat key\n * wins over the nested one, and an explicit `undefined` on either never blanks\n * a lower layer.\n */\nfunction layerGateway(\n options: ProviderGatewaySettings | undefined\n): GatewayOptions {\n if (options === undefined) return {};\n return {\n ...normalizeGateway(options.gateway),\n ...defined({\n cacheKey: options.cacheKey,\n cacheTtl: options.cacheTtl,\n collectLog: options.collectLog,\n eventId: options.eventId,\n id: options.id,\n metadata: options.metadata,\n requestTimeoutMs: options.requestTimeoutMs,\n retries: options.retries,\n skipCache: options.skipCache\n })\n };\n}\n\n/** The flat gateway sugar {@link layerGateway} folds into `gateway`. */\nconst FLAT_GATEWAY_KEYS = [\n \"cacheKey\",\n \"cacheTtl\",\n \"collectLog\",\n \"eventId\",\n \"gateway\",\n \"id\",\n \"metadata\",\n \"requestTimeoutMs\",\n \"retries\",\n \"skipCache\"\n] as const;\n\n/**\n * One layer's gateway options as a single object, both spellings folded in.\n * Exported so a module that collapses two option layers into one bag (a\n * fallback leg inheriting a chain's gateway) can merge them field by field\n * rather than replacing one object with the other.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function gatewayLayerOf(\n options: ProviderGatewaySettings | undefined\n): GatewayOptions {\n return layerGateway(options);\n}\n\n/** An option bag without the gateway keys, whichever spelling they used. */\nfunction withoutGatewayKeys<Leg>(\n options: ModelOptions<Leg>\n): ModelOptions<Leg> {\n const rest: Record<string, unknown> = { ...options };\n for (const key of FLAT_GATEWAY_KEYS) delete rest[key];\n return defined(rest as ModelOptions<Leg>);\n}\n\n/**\n * Collapses two option layers into one bag, `override` winning field by field.\n *\n * The gateway keys of both are folded into a single `gateway` object, so\n * neither layer's flat sugar can out-rank the other's nested spelling when the\n * bag is resolved later, and `metadata` merges rather than replaces — the same\n * rules {@link resolveOptions} applies across its three layers.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function mergeModelOptions<Leg>(\n base: ModelOptions<Leg> | undefined,\n override: ModelOptions<Leg> | undefined\n): ModelOptions<Leg> | undefined {\n if (base === undefined) return override;\n if (override === undefined) return base;\n const layers = [layerGateway(base), layerGateway(override)];\n const gateway: GatewayOptions = Object.assign({}, ...layers);\n const metadata = Object.assign({}, ...layers.map((layer) => layer.metadata));\n const retries = mergeRetries(layers);\n // Headers merge field by field, as they do across `resolveOptions`' three\n // layers: replacing the object wholesale would drop a header the lower layer\n // was configured with. The spread comes after the override's own keys so it\n // wins over the `headers` that spread carried.\n const headers = { ...base.headers, ...override.headers };\n return {\n ...withoutGatewayKeys(base),\n ...withoutGatewayKeys(override),\n ...(Object.keys(headers).length > 0 ? { headers } : {}),\n gateway: {\n ...gateway,\n ...(Object.keys(metadata).length > 0 ? { metadata } : {}),\n ...(retries === undefined ? {} : { retries })\n }\n };\n}\n\n/**\n * Merges the retry policies field by field, so a provider-wide `backoff` still\n * applies when a call only sets `maxAttempts`. `undefined` on any layer means\n * \"not set\" and never blanks a lower one.\n */\nfunction mergeRetries(\n layers: GatewayOptions[]\n): GatewayOptions[\"retries\"] | undefined {\n const merged = layers.reduce<NonNullable<GatewayOptions[\"retries\"]>>(\n (result, layer) => ({\n ...result,\n ...(layer.retries === undefined ? {} : defined(layer.retries))\n }),\n {}\n );\n return Object.keys(merged).length > 0 ? merged : undefined;\n}\n\n/**\n * Merges the option layers. Precedence is per-call\n * (`providerOptions.cloudflare`) > per-model (`ai(id, options)`) >\n * provider (`createAI({ ... })`).\n *\n * The provider layer takes the whole settings object as well as a bare\n * `gateway` value, so `createAI({ binding, id: \"prod\", cacheTtl: 60 })` reads\n * the same as `createAI({ binding, gateway: { id: \"prod\", cacheTtl: 60 } })`.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function resolveOptions(\n provider: string | ProviderGatewaySettings | undefined,\n model: ModelOptions<unknown> | undefined,\n call: ModelOptions<unknown> | undefined\n): ResolvedOptions {\n const layers =\n typeof provider === \"string\"\n ? [normalizeGateway(provider), layerGateway(model), layerGateway(call)]\n : [layerGateway(provider), layerGateway(model), layerGateway(call)];\n const gateway: GatewayOptions = Object.assign({}, ...layers);\n const metadata = Object.assign({}, ...layers.map((layer) => layer.metadata));\n const retries = mergeRetries(layers);\n return {\n chatTemplateKwargs: call?.chatTemplateKwargs ?? model?.chatTemplateKwargs,\n fallback: idLegs(call?.fallback ?? model?.fallback),\n gateway: {\n ...gateway,\n id: gateway.id ?? DEFAULT_GATEWAY_ID,\n ...(Object.keys(metadata).length > 0 ? { metadata } : {}),\n ...(retries === undefined ? {} : { retries })\n },\n headers: { ...model?.headers, ...call?.headers },\n // `null` is a meaningful value here (it disables reasoning), so the call\n // layer wins on any value it actually set, not just on a truthy one.\n reasoningEffort:\n call?.reasoningEffort !== undefined\n ? call.reasoningEffort\n : model?.reasoningEffort,\n sessionAffinity: call?.sessionAffinity ?? model?.sessionAffinity\n };\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\nfunction asStringRecord(value: unknown): Record<string, string> | undefined {\n const record = asRecord(value);\n if (record === undefined) return undefined;\n const result: Record<string, string> = {};\n for (const [key, entry] of Object.entries(record)) {\n if (typeof entry === \"string\") result[key] = entry;\n }\n return result;\n}\n\nfunction asString(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction asNumber(value: unknown): number | undefined {\n return typeof value === \"number\" ? value : undefined;\n}\n\nfunction asBoolean(value: unknown): boolean | undefined {\n return typeof value === \"boolean\" ? value : undefined;\n}\n\nfunction asReasoningEffort(\n value: unknown\n): \"low\" | \"medium\" | \"high\" | null | undefined {\n if (value === null) return null;\n if (value === \"low\" || value === \"medium\" || value === \"high\") return value;\n return undefined;\n}\n\n/**\n * Metadata values the gateway accepts are scalars only; a nested object or\n * array would be rejected by the binding, so drop those rather than forward\n * them.\n */\nfunction asMetadata(value: unknown): GatewayOptions[\"metadata\"] {\n const record = asRecord(value);\n if (record === undefined) return undefined;\n const result: NonNullable<GatewayOptions[\"metadata\"]> = {};\n for (const [key, entry] of Object.entries(record)) {\n if (\n entry === null ||\n typeof entry === \"string\" ||\n typeof entry === \"number\" ||\n typeof entry === \"boolean\"\n ) {\n result[key] = entry;\n }\n }\n return result;\n}\n\nconst BACKOFFS = [\"constant\", \"linear\", \"exponential\"] as const;\n\n/** Reads the retry policy field by field; the binding validates it strictly. */\nfunction asRetries(value: unknown): GatewayOptions[\"retries\"] {\n const record = asRecord(value);\n if (record === undefined) return undefined;\n const maxAttempts = asNumber(record.maxAttempts);\n const backoff = asString(record.backoff);\n const retries = defined({\n backoff: BACKOFFS.find((entry) => entry === backoff),\n maxAttempts:\n maxAttempts !== undefined &&\n Number.isInteger(maxAttempts) &&\n maxAttempts >= 1 &&\n maxAttempts <= 5\n ? (maxAttempts as 1 | 2 | 3 | 4 | 5)\n : undefined,\n retryDelayMs: asNumber(record.retryDelayMs)\n });\n // An empty policy is not a policy: returning `{}` would out-rank a lower\n // layer's real one when the layers merge.\n return Object.keys(retries).length > 0 ? retries : undefined;\n}\n\n/** Reads the shared gateway keys out of a loosely-typed record. */\nfunction parseGatewayFields(raw: Record<string, unknown>): GatewayOptions {\n return defined({\n cacheKey: asString(raw.cacheKey),\n cacheTtl: asNumber(raw.cacheTtl),\n collectLog: asBoolean(raw.collectLog),\n eventId: asString(raw.eventId),\n id: asString(raw.id),\n metadata: asMetadata(raw.metadata),\n requestTimeoutMs: asNumber(raw.requestTimeoutMs),\n retries: asRetries(raw.retries),\n skipCache: asBoolean(raw.skipCache)\n });\n}\n\n/**\n * Reads per-call options out of a loosely-typed options bag (the value a\n * framework keeps under {@link PROVIDER_OPTIONS_KEY}).\n *\n * The bag is plain JSON, so every field is read defensively: anything of an\n * unexpected type is dropped rather than thrown, because a malformed\n * observability hint should never fail a generation.\n *\n * @experimental This surface is experimental and may change.\n */\nexport function parseModelOptions(value: unknown): ModelOptions | undefined {\n const raw = asRecord(value);\n if (raw === undefined) return undefined;\n\n const nested = asRecord(raw.gateway);\n const gateway: string | GatewayOptions | undefined =\n typeof raw.gateway === \"string\"\n ? raw.gateway\n : nested !== undefined\n ? parseGatewayFields(nested)\n : undefined;\n\n const fallback = Array.isArray(raw.fallback)\n ? raw.fallback.filter(\n (entry): entry is WorkersAIModelId => typeof entry === \"string\"\n )\n : undefined;\n\n return defined({\n ...parseGatewayFields(raw),\n chatTemplateKwargs: asRecord(raw.chatTemplateKwargs),\n fallback,\n gateway,\n headers: asStringRecord(raw.headers),\n reasoningEffort: asReasoningEffort(raw.reasoningEffort),\n sessionAffinity: asString(raw.sessionAffinity)\n });\n}\n"],"mappings":";;AAGA,MAAa,qBAAqB;;AAGlC,MAAa,uBAA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