agents 0.22.0 → 0.23.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 (186) hide show
  1. package/README.md +20 -1
  2. package/dist/{agent-routing-CnkaHb-v.d.ts → agent-routing-DE5zmCQ8.d.ts} +1038 -394
  3. package/dist/agent-routing.d.ts +1 -1
  4. package/dist/agent-tool-types.d.ts +26 -26
  5. package/dist/{agent-tools-C0XJqWzB.d.ts → agent-tools-DtXMTDGM.d.ts} +7 -7
  6. package/dist/agent-tools.d.ts +21 -21
  7. package/dist/browser/ai.js +4 -1
  8. package/dist/browser/ai.js.map +1 -1
  9. package/dist/browser/tanstack-ai.js.map +1 -1
  10. package/dist/callable-decorator-DP__HhBA.d.ts +72 -0
  11. package/dist/callable-decorator.d.ts +18 -0
  12. package/dist/callable-decorator.js +71 -0
  13. package/dist/callable-decorator.js.map +1 -0
  14. package/dist/capability-BjSKYpzg.js.map +1 -1
  15. package/dist/capability-runner-Be_-PLR1.d.ts +459 -0
  16. package/dist/channel-Bnm4S7T2.d.ts +491 -0
  17. package/dist/channels/ai-sdk.d.ts +46 -0
  18. package/dist/channels/ai-sdk.js +120 -0
  19. package/dist/channels/ai-sdk.js.map +1 -0
  20. package/dist/channels/email.d.ts +95 -0
  21. package/dist/channels/email.js +323 -0
  22. package/dist/channels/email.js.map +1 -0
  23. package/dist/channels/index.d.ts +233 -0
  24. package/dist/channels/index.js +608 -0
  25. package/dist/channels/index.js.map +1 -0
  26. package/dist/channels/slack.d.ts +140 -0
  27. package/dist/channels/slack.js +614 -0
  28. package/dist/channels/slack.js.map +1 -0
  29. package/dist/channels/tanstack-ai.d.ts +39 -0
  30. package/dist/channels/tanstack-ai.js +17 -0
  31. package/dist/channels/tanstack-ai.js.map +1 -0
  32. package/dist/channels/telegram.d.ts +106 -0
  33. package/dist/channels/telegram.js +427 -0
  34. package/dist/channels/telegram.js.map +1 -0
  35. package/dist/channels/voice.d.ts +45 -0
  36. package/dist/channels/voice.js +122 -0
  37. package/dist/channels/voice.js.map +1 -0
  38. package/dist/chat/index.d.ts +2325 -2019
  39. package/dist/chat/index.js +888 -518
  40. package/dist/chat/index.js.map +1 -1
  41. package/dist/chat-sdk/index.d.ts +7 -7
  42. package/dist/chat-sdk/index.js +1 -1
  43. package/dist/client.d.ts +1 -1
  44. package/dist/context/index.d.ts +216 -0
  45. package/dist/context/index.js +454 -0
  46. package/dist/context/index.js.map +1 -0
  47. package/dist/{current-agent-CuMErtly.d.ts → current-agent-Da_C9a3b.d.ts} +90 -107
  48. package/dist/current-agent-DhoDkSnH.js.map +1 -1
  49. package/dist/{diagnostics-CaBjfz4J.js → diagnostics-BzvaX2UT.js} +5 -1
  50. package/dist/diagnostics-BzvaX2UT.js.map +1 -0
  51. package/dist/diagnostics-C4jcz3VK.js +360 -0
  52. package/dist/diagnostics-C4jcz3VK.js.map +1 -0
  53. package/dist/index-BB0kqhIz.d.ts +101 -0
  54. package/dist/index-BVVgDSdq.d.ts +1 -0
  55. package/dist/index-XDkuQ7zm.d.ts +89 -0
  56. package/dist/{index-DcSAZKsB.d.ts → index-YSKgfgg9.d.ts} +3 -1
  57. package/dist/index.d.ts +91 -82
  58. package/dist/index.js +3 -2
  59. package/dist/ingress-BfetZbMO.js +83 -0
  60. package/dist/ingress-BfetZbMO.js.map +1 -0
  61. package/dist/internal-CYlgHl1l.js +59 -0
  62. package/dist/internal-CYlgHl1l.js.map +1 -0
  63. package/dist/internal_context.d.ts +1 -1
  64. package/dist/lifecycle/index.d.ts +35 -17
  65. package/dist/lifecycle/index.js +1 -1
  66. package/dist/lifecycle-CMRGjZdw.js +1299 -0
  67. package/dist/lifecycle-CMRGjZdw.js.map +1 -0
  68. package/dist/mcp/client/index.d.ts +20 -20
  69. package/dist/mcp/index.d.ts +35 -35
  70. package/dist/mcp/index.js +1 -1
  71. package/dist/observability/index.d.ts +1 -1
  72. package/dist/observability/index.js +1 -1
  73. package/dist/react.d.ts +4 -4
  74. package/dist/{retries-CAvxtG9d.d.ts → retries-D9Ds-1lz.d.ts} +17 -6
  75. package/dist/retries.d.ts +8 -6
  76. package/dist/retries.js +13 -1
  77. package/dist/retries.js.map +1 -1
  78. package/dist/routing/index.d.ts +137 -0
  79. package/dist/routing/index.js +244 -0
  80. package/dist/routing/index.js.map +1 -0
  81. package/dist/sanitize-D9TujEK8.js +79 -0
  82. package/dist/sanitize-D9TujEK8.js.map +1 -0
  83. package/dist/scheduler-DD9NdYbF.js +665 -0
  84. package/dist/scheduler-DD9NdYbF.js.map +1 -0
  85. package/dist/{scheduler-DQoTGoAW.d.ts → scheduler-Dwh85ZGl.d.ts} +21 -22
  86. package/dist/schedules/index.d.ts +1 -1
  87. package/dist/schedules/index.js +1 -1
  88. package/dist/sentence-chunker-BAidJ4DA.d.ts +68 -0
  89. package/dist/serializable.d.ts +1 -1
  90. package/dist/sessions/index.d.ts +441 -0
  91. package/dist/sessions/index.js +2063 -0
  92. package/dist/sessions/index.js.map +1 -0
  93. package/dist/skills/index.d.ts +99 -0
  94. package/dist/skills/index.js +254 -5
  95. package/dist/skills/index.js.map +1 -1
  96. package/dist/{src-5W6JNKVb.js → src-DlSHshb2.js} +1460 -1110
  97. package/dist/src-DlSHshb2.js.map +1 -0
  98. package/dist/streams/index.d.ts +120 -0
  99. package/dist/streams/index.js +107 -0
  100. package/dist/streams/index.js.map +1 -0
  101. package/dist/streams-D6tJ0NN9.d.ts +370 -0
  102. package/dist/streams-DZKgAj9b.js +709 -0
  103. package/dist/streams-DZKgAj9b.js.map +1 -0
  104. package/dist/sub-routing.d.ts +12 -12
  105. package/dist/surface-bZZJqBka.js +17 -0
  106. package/dist/surface-bZZJqBka.js.map +1 -0
  107. package/dist/tasks/index.d.ts +64 -0
  108. package/dist/tasks/index.js +2 -0
  109. package/dist/tasks-BRJ5zgya.d.ts +517 -0
  110. package/dist/tasks-ylZgBjhj.js +1656 -0
  111. package/dist/tasks-ylZgBjhj.js.map +1 -0
  112. package/dist/text-segment-joiner-BtAFQSA_.js +57 -0
  113. package/dist/text-segment-joiner-BtAFQSA_.js.map +1 -0
  114. package/dist/text-stream-CpdiKrJB.js +272 -0
  115. package/dist/text-stream-CpdiKrJB.js.map +1 -0
  116. package/dist/tokens-nHAKcN6M.js +52 -0
  117. package/dist/tokens-nHAKcN6M.js.map +1 -0
  118. package/dist/tool-schema-CBjGPrsQ.js +31 -0
  119. package/dist/tool-schema-CBjGPrsQ.js.map +1 -0
  120. package/dist/types-B7LojTe4.d.ts +202 -0
  121. package/dist/types-_Faxb570.d.ts +439 -0
  122. package/dist/voice/client.d.ts +226 -0
  123. package/dist/voice/client.js +932 -0
  124. package/dist/voice/client.js.map +1 -0
  125. package/dist/voice/errors.d.ts +43 -0
  126. package/dist/voice/errors.js +41 -0
  127. package/dist/voice/errors.js.map +1 -0
  128. package/dist/voice/index.d.ts +271 -0
  129. package/dist/voice/index.js +1812 -0
  130. package/dist/voice/index.js.map +1 -0
  131. package/dist/voice/react.d.ts +167 -0
  132. package/dist/voice/react.js +234 -0
  133. package/dist/voice/react.js.map +1 -0
  134. package/dist/voice/sfu.d.ts +71 -0
  135. package/dist/voice/sfu.js +157 -0
  136. package/dist/voice/sfu.js.map +1 -0
  137. package/dist/voice/text.d.ts +6 -0
  138. package/dist/voice/text.js +2 -0
  139. package/dist/voice/types.d.ts +58 -0
  140. package/dist/voice/types.js +18 -0
  141. package/dist/voice/types.js.map +1 -0
  142. package/dist/voice/workers-ai.d.ts +136 -0
  143. package/dist/voice/workers-ai.js +568 -0
  144. package/dist/voice/workers-ai.js.map +1 -0
  145. package/dist/websockets/index.d.ts +192 -0
  146. package/dist/websockets/index.js +2 -0
  147. package/dist/websockets-DUfRHPRq.js +502 -0
  148. package/dist/websockets-DUfRHPRq.js.map +1 -0
  149. package/dist/workflow-types.d.ts +25 -25
  150. package/dist/workflows.d.ts +21 -21
  151. package/dist/workflows.js +1 -1
  152. package/docs/agent-class.md +2 -2
  153. package/docs/agent-tools.md +2 -1
  154. package/docs/channels.md +323 -0
  155. package/docs/chat-agents.md +6 -13
  156. package/docs/context.md +131 -0
  157. package/docs/index.md +15 -12
  158. package/docs/lifecycle.md +102 -55
  159. package/docs/long-running-agents.md +2 -2
  160. package/docs/mcp-servers.md +5 -1
  161. package/docs/resumable-streaming.md +1 -1
  162. package/docs/routing.md +105 -0
  163. package/docs/sessions.md +237 -871
  164. package/docs/streams.md +213 -0
  165. package/docs/sub-agents.md +184 -124
  166. package/docs/tasks.md +246 -0
  167. package/docs/voice.md +745 -0
  168. package/package.json +115 -13
  169. package/dist/capability-runner-CvHGZqUu.d.ts +0 -150
  170. package/dist/compaction-helpers-iiKMr2TQ.js +0 -340
  171. package/dist/compaction-helpers-iiKMr2TQ.js.map +0 -1
  172. package/dist/compaction-helpers-wUz6M3us.d.ts +0 -621
  173. package/dist/diagnostics-CaBjfz4J.js.map +0 -1
  174. package/dist/durable-object-lifecycle-D6nNQJJd.js +0 -862
  175. package/dist/durable-object-lifecycle-D6nNQJJd.js.map +0 -1
  176. package/dist/experimental/memory/session/index.d.ts +0 -671
  177. package/dist/experimental/memory/session/index.js +0 -2379
  178. package/dist/experimental/memory/session/index.js.map +0 -1
  179. package/dist/experimental/memory/utils/index.d.ts +0 -96
  180. package/dist/experimental/memory/utils/index.js +0 -79
  181. package/dist/experimental/memory/utils/index.js.map +0 -1
  182. package/dist/scheduler-CR9RHGos.js +0 -857
  183. package/dist/scheduler-CR9RHGos.js.map +0 -1
  184. package/dist/src-5W6JNKVb.js.map +0 -1
  185. package/dist/tool-output-truncation-CNnnGZQ3.js +0 -98
  186. package/dist/tool-output-truncation-CNnnGZQ3.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lifecycle-CMRGjZdw.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, fallbacks last; the first capability to return a `Response`\n * claims the request, and a claimed upgrade's socket belongs to that\n * capability for its whole lifetime.\n * - `onWebSocketMessage`/`onWebSocketClose`/`onWebSocketError` are\n * platform wakes, offered in declaration order; return `true` to\n * consume one. Socket ownership is the capability's to determine —\n * keep a private hibernation-attachment namespace and recognize your\n * own sockets by it.\n * - `onRoute` is addressed to one capability by its id; `onJob` is\n * addressed by the due job's owning capability, with Lifecycle owning\n * the queue and the one physical alarm.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport interface DurableObjectCapability<Props extends object = object> {\n /** 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 { 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} 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<\n Env extends object,\n Props extends Record<string, unknown>\n> = LifecycleObject<Env, Props> & {\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/** @internal Adapt the host invocation boundary at a composition root. */\nexport function setLifecycleHostInvoker<\n Env extends object,\n Props extends Record<string, unknown>\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 Record<string, unknown>\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<\n Env extends object,\n Props extends Record<string, unknown>\n>(lifecycle: Lifecycle<Env, Props>, sink: LifecycleEventSink): 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/** Placement of a capability in the dispatch order. */\nexport type LifecycleUseOptions = {\n /**\n * Dispatch after every non-fallback capability, whenever it was\n * installed. For a host's catch-all, such as a WebSockets capability\n * that claims every upgrade, so middleware installed later still runs\n * first.\n */\n readonly fallback?: boolean;\n};\n\n/**\n * Installs and coordinates the runtime lifecycle for a Durable Object.\n *\n * Construct this as an instance field on a class that directly extends\n * `DurableObject`, then call {@link Lifecycle.installHandlers}\n * from that class's constructor.\n *\n * @experimental The API surface may change before stabilizing.\n */\nexport class Lifecycle<\n Env extends object = Cloudflare.Env,\n Props extends Record<string, unknown> = Record<string, unknown>\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: \"zero\" | \"starting\" | \"started\" = \"zero\";\n #alarmRearmQueue: Promise<void> = Promise.resolve();\n #rearmRequestedDuringStart = false;\n #pendingEvents: LifecycleEvent[] = [];\n #alarmsDisabled = false;\n #capabilitiesLocked = false;\n readonly #fallbacks = new Set<DurableObjectCapability<Props>>();\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<\n Env extends object,\n Props extends Record<string, unknown> = Record<string, unknown>\n >(\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 fallbacks\n * always come after non-fallbacks.\n *\n * @param capability - The capability to add.\n * @param options - Dispatch placement.\n * @returns This lifecycle.\n */\n use(\n capability: DurableObjectCapability<Props>,\n options?: LifecycleUseOptions\n ): 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 firstFallback = this.#capabilities.findIndex((candidate) =>\n this.#fallbacks.has(candidate)\n );\n if (options?.fallback) this.#fallbacks.add(capability);\n this.#capabilities.splice(\n options?.fallback || firstFallback === -1\n ? this.#capabilities.length\n : firstFallback,\n 0,\n capability\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 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 starting: () => this.#status === \"starting\",\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 async #readyForCapabilityOperation(): Promise<void> {\n if (this.#status === \"starting\" || this.#status === \"started\") return;\n await this.start();\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 * @param props - Optional properties supplied to capability and host startup.\n */\n async start(props?: Props): Promise<void> {\n if (props !== undefined) this.#props = props;\n await this.#ensureInitialized();\n }\n\n async #ensureInitialized(): Promise<void> {\n if (this.#status === \"started\") return;\n\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 let error: unknown;\n await this.#ctx.blockConcurrencyWhile(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 // 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 runWithout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,oBAA0B,OAAiD;CACzE,IAAI,UAAA,QAA+B;EACjC,MAAM,OAAA,uBAAA,OAAO,IAAA;EACb,IAAI,CAAC,KAAK,OAAO,OAAO,KAAA;EAGxB,OAAO,EACL,OAAO,OAAO,YACZ,0BAA0B,EAAE,KAAK,SAAS,KAAK,MAAO,OAAO,CAAC,EAClE;CACF;CACA,MAAM,aAAa,MAAA,uBAAA,mBAAM,IAAA,CAAA,CAAuB,SAAS,KAAK;CAC9D,IAAI,CAAC,YAAY,OAAO,OAAO,KAAA;CAC/B,OAAO;EACL,OAAO,OAAO,YACZ,6BAA6B,WAAW,MAAO,OAAO,CAAC;EACzD,YAAY,WAAW,aACnB,OAAO,SAAS,UACd,6BAA6B,WAAW,WAAY,SAAS,KAAK,CAAC,IACrE,KAAA;CACN;AACF"}
@@ -1,24 +1,24 @@
1
1
  import {
2
- Bt as MCPClientManagerOptions,
3
- Ft as MCPAITool,
4
- Gt as MCPOAuthCallbackResult,
5
- Ht as MCPClientOAuthResult,
6
- It as MCPAIToolSet,
7
- Jt as MCP_SERVER_ID_MAX_LENGTH,
8
- Kt as MCPServerFilter,
9
- Lt as MCPClientElicitationHandler,
10
- Nt as ElicitRequest,
11
- Pt as ElicitResult,
12
- Rt as MCPClientElicitationHandlers,
13
- Ut as MCPConnectionResult,
14
- Vt as MCPClientOAuthCallbackConfig,
15
- Wt as MCPDiscoverResult,
16
- Xt as getNamespacedData,
17
- Yt as RegisterServerOptions,
18
- Zt as normalizeServerId,
19
- qt as MCPServerOptions,
20
- zt as MCPClientManager
21
- } from "../../agent-routing-CnkaHb-v.js";
2
+ At as MCPAITool,
3
+ Bt as MCPOAuthCallbackResult,
4
+ Ft as MCPClientManagerOptions,
5
+ Gt as getNamespacedData,
6
+ Ht as MCPServerOptions,
7
+ It as MCPClientOAuthCallbackConfig,
8
+ Kt as normalizeServerId,
9
+ Lt as MCPClientOAuthResult,
10
+ Mt as MCPClientElicitationHandler,
11
+ Nt as MCPClientElicitationHandlers,
12
+ Ot as ElicitRequest,
13
+ Pt as MCPClientManager,
14
+ Rt as MCPConnectionResult,
15
+ Ut as MCP_SERVER_ID_MAX_LENGTH,
16
+ Vt as MCPServerFilter,
17
+ Wt as RegisterServerOptions,
18
+ jt as MCPAIToolSet,
19
+ kt as ElicitResult,
20
+ zt as MCPDiscoverResult
21
+ } from "../../agent-routing-DE5zmCQ8.js";
22
22
  export {
23
23
  type ElicitRequest,
24
24
  type ElicitResult,
@@ -1,39 +1,39 @@
1
1
  import {
2
- $t as MCPElicitationHandlers,
3
- Ht as MCPClientOAuthResult,
4
- Jt as MCP_SERVER_ID_MAX_LENGTH,
5
- Lt as MCPClientElicitationHandler,
6
- Qt as MCPElicitationHandler,
7
- Rt as MCPClientElicitationHandlers,
8
- Sn as StreamableHTTPEdgeClientTransport,
9
- Ut as MCPConnectionResult,
10
- Vt as MCPClientOAuthCallbackConfig,
11
- Wt as MCPDiscoverResult,
12
- Zt as normalizeServerId,
13
- _n as MCPStorageApi,
14
- an as ElicitRequest,
15
- bn as WorkerTransportOptions,
16
- cn as McpAgent,
17
- dn as createMcpHandler,
18
- en as RPCClientTransport,
19
- fn as experimental_createMcpHandler,
20
- gn as createLegacyMcpHandler,
21
- hn as LegacyMcpHandler,
22
- in as RPC_DO_PREFIX,
23
- ln as ClearableEventStore,
24
- mn as CreateMcpHandlerOptions,
25
- nn as RPCServerTransport,
26
- on as ElicitRequestSchema,
27
- pn as CreateLegacyMcpHandlerOptions,
28
- qt as MCPServerOptions,
29
- rn as RPCServerTransportOptions,
30
- sn as ElicitResult,
31
- tn as RPCClientTransportOptions,
32
- un as DurableObjectEventStore,
33
- vn as TransportState,
34
- xn as SSEEdgeClientTransport,
35
- yn as WorkerTransport
36
- } from "../agent-routing-CnkaHb-v.js";
2
+ $t as RPC_DO_PREFIX,
3
+ Ht as MCPServerOptions,
4
+ It as MCPClientOAuthCallbackConfig,
5
+ Jt as MCPElicitationHandlers,
6
+ Kt as normalizeServerId,
7
+ Lt as MCPClientOAuthResult,
8
+ Mt as MCPClientElicitationHandler,
9
+ Nt as MCPClientElicitationHandlers,
10
+ Qt as RPCServerTransportOptions,
11
+ Rt as MCPConnectionResult,
12
+ Ut as MCP_SERVER_ID_MAX_LENGTH,
13
+ Xt as RPCClientTransportOptions,
14
+ Yt as RPCClientTransport,
15
+ Zt as RPCServerTransport,
16
+ _n as StreamableHTTPEdgeClientTransport,
17
+ an as DurableObjectEventStore,
18
+ cn as CreateLegacyMcpHandlerOptions,
19
+ dn as createLegacyMcpHandler,
20
+ en as ElicitRequest,
21
+ fn as MCPStorageApi,
22
+ gn as SSEEdgeClientTransport,
23
+ hn as WorkerTransportOptions,
24
+ in as ClearableEventStore,
25
+ ln as CreateMcpHandlerOptions,
26
+ mn as WorkerTransport,
27
+ nn as ElicitResult,
28
+ on as createMcpHandler,
29
+ pn as TransportState,
30
+ qt as MCPElicitationHandler,
31
+ rn as McpAgent,
32
+ sn as experimental_createMcpHandler,
33
+ tn as ElicitRequestSchema,
34
+ un as LegacyMcpHandler,
35
+ zt as MCPDiscoverResult
36
+ } from "../agent-routing-DE5zmCQ8.js";
37
37
  import {
38
38
  a as McpAuthContext,
39
39
  n as StatelessMcpHandler,
package/dist/mcp/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { getAgentByName } from "../agent-routing.js";
2
2
  import "../types.js";
3
+ import { i as getCurrentAgent, t as Agent } from "../src-DlSHshb2.js";
3
4
  import { c as RPCServerTransport, i as normalizeServerId, l as RPC_DO_PREFIX, n as MCP_SERVER_ID_MAX_LENGTH, s as RPCClientTransport, u as isDurableObjectNamespace } from "../client-jagG8a9_.js";
4
- import { a as getCurrentAgent, t as Agent } from "../src-5W6JNKVb.js";
5
5
  import { n as getMcpAuthContext, r as runWithAuthContext, t as createStatelessMcpHandler } from "../handler-stateless-VvrWSAVA.js";
6
6
  import { SSEClientTransport, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
7
7
  import { ElicitRequestSchema, InitializeRequestSchema, JSONRPCMessageSchema, SUPPORTED_PROTOCOL_VERSIONS, isInitializeRequest, isJSONRPCErrorResponse, isJSONRPCNotification, isJSONRPCRequest, isJSONRPCResultResponse } from "@modelcontextprotocol/sdk/types.js";
@@ -5,7 +5,7 @@ import {
5
5
  o as channels,
6
6
  r as ObservabilityEvent,
7
7
  t as ChannelEventMap
8
- } from "../index-DcSAZKsB.js";
8
+ } from "../index-YSKgfgg9.js";
9
9
  export {
10
10
  ChannelEventMap,
11
11
  Observability,
@@ -1,4 +1,4 @@
1
- import { n as publishDiagnosticsEvent, t as channels } from "../diagnostics-CaBjfz4J.js";
1
+ import { n as publishDiagnosticsEvent, t as channels } from "../diagnostics-BzvaX2UT.js";
2
2
  import { subscribe as subscribe$1, unsubscribe } from "node:diagnostics_channel";
3
3
  //#region src/observability/index.ts
4
4
  /**
package/dist/react.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import {
2
- $ as AgentToolRunPart,
3
- et as AgentToolRunState,
4
- w as MCPServersState
5
- } from "./agent-routing-CnkaHb-v.js";
2
+ C as MCPServersState,
3
+ J as AgentToolRunPart,
4
+ Y as AgentToolRunState
5
+ } from "./agent-routing-DE5zmCQ8.js";
6
6
  import { ClientParameters } from "./serializable.js";
7
7
  import {
8
8
  AgentConnectionError,
@@ -111,17 +111,28 @@ declare function isDurableObjectMemoryLimitReset(error: unknown): boolean;
111
111
  * error — re-running yields the same failure). A genuine application error
112
112
  * carries none of these signals, so it is never misclassified by this check.
113
113
  */
114
+ /**
115
+ * Whether a failure is the PLATFORM's rather than the application's — any
116
+ * platform transient (see {@link isPlatformTransientError}, which includes
117
+ * superseded-isolate resets) or a memory-limit reset. Failed work in this
118
+ * class must be PRESERVED and deferred, never completed as an application
119
+ * failure. The two sub-classes defer differently: transients re-run
120
+ * indefinitely (the platform recovers), while memory-limit deferral is
121
+ * bounded by the alarm circuit breaker (#1825).
122
+ */
123
+ declare function isPlatformFailure(error: unknown): boolean;
114
124
  declare function isPlatformTransientError(error: unknown): boolean;
115
125
  //#endregion
116
126
  export {
117
127
  isErrorRetryable as a,
118
- tryN as c,
128
+ jitterBackoff as c,
119
129
  isDurableObjectStorageReset as i,
120
- validateRetryOptions as l,
130
+ tryN as l,
121
131
  isDurableObjectCodeUpdateReset as n,
122
- isPlatformTransientError as o,
132
+ isPlatformFailure as o,
123
133
  isDurableObjectMemoryLimitReset as r,
124
- jitterBackoff as s,
125
- RetryOptions as t
134
+ isPlatformTransientError as s,
135
+ RetryOptions as t,
136
+ validateRetryOptions as u
126
137
  };
127
- //# sourceMappingURL=retries-CAvxtG9d.d.ts.map
138
+ //# sourceMappingURL=retries-D9Ds-1lz.d.ts.map
package/dist/retries.d.ts CHANGED
@@ -1,20 +1,22 @@
1
1
  import {
2
2
  a as isErrorRetryable,
3
- c as tryN,
3
+ c as jitterBackoff,
4
4
  i as isDurableObjectStorageReset,
5
- l as validateRetryOptions,
5
+ l as tryN,
6
6
  n as isDurableObjectCodeUpdateReset,
7
- o as isPlatformTransientError,
7
+ o as isPlatformFailure,
8
8
  r as isDurableObjectMemoryLimitReset,
9
- s as jitterBackoff,
10
- t as RetryOptions
11
- } from "./retries-CAvxtG9d.js";
9
+ s as isPlatformTransientError,
10
+ t as RetryOptions,
11
+ u as validateRetryOptions
12
+ } from "./retries-D9Ds-1lz.js";
12
13
  export {
13
14
  RetryOptions,
14
15
  isDurableObjectCodeUpdateReset,
15
16
  isDurableObjectMemoryLimitReset,
16
17
  isDurableObjectStorageReset,
17
18
  isErrorRetryable,
19
+ isPlatformFailure,
18
20
  isPlatformTransientError,
19
21
  jitterBackoff,
20
22
  tryN,
package/dist/retries.js CHANGED
@@ -213,6 +213,18 @@ function isDurableObjectMemoryLimitReset(error) {
213
213
  * error — re-running yields the same failure). A genuine application error
214
214
  * carries none of these signals, so it is never misclassified by this check.
215
215
  */
216
+ /**
217
+ * Whether a failure is the PLATFORM's rather than the application's — any
218
+ * platform transient (see {@link isPlatformTransientError}, which includes
219
+ * superseded-isolate resets) or a memory-limit reset. Failed work in this
220
+ * class must be PRESERVED and deferred, never completed as an application
221
+ * failure. The two sub-classes defer differently: transients re-run
222
+ * indefinitely (the platform recovers), while memory-limit deferral is
223
+ * bounded by the alarm circuit breaker (#1825).
224
+ */
225
+ function isPlatformFailure(error) {
226
+ return isPlatformTransientError(error) || isDurableObjectMemoryLimitReset(error);
227
+ }
216
228
  function isPlatformTransientError(error) {
217
229
  for (const e of selfAndCauses(error)) {
218
230
  const message = errorMessageOf(e);
@@ -224,6 +236,6 @@ function isPlatformTransientError(error) {
224
236
  return false;
225
237
  }
226
238
  //#endregion
227
- export { isDurableObjectCodeUpdateReset, isDurableObjectMemoryLimitReset, isDurableObjectStorageReset, isErrorRetryable, isPlatformTransientError, jitterBackoff, tryN, validateRetryOptions };
239
+ export { isDurableObjectCodeUpdateReset, isDurableObjectMemoryLimitReset, isDurableObjectStorageReset, isErrorRetryable, isPlatformFailure, isPlatformTransientError, jitterBackoff, tryN, validateRetryOptions };
228
240
 
229
241
  //# sourceMappingURL=retries.js.map