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
@@ -1 +0,0 @@
1
- {"version":3,"file":"durable-object-lifecycle-D6nNQJJd.js","names":[],"sources":["../src/lifecycle/capability-runner.ts","../src/lifecycle/connection.ts","../src/lifecycle/transport-errors.ts","../src/lifecycle/durable-object-lifecycle.ts"],"sourcesContent":["import { lifecycleCapabilityId } from \"./capability\";\nimport type { LifecycleRouteContext } from \"./capability\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\n/** One capability's requested physical alarm. */\nexport type AlarmContribution =\n | number\n | {\n /** Epoch time in milliseconds. */\n readonly time: number;\n /** Ignore ordinary wake-time candidates while this request exists. */\n readonly exclusive: true;\n }\n | null;\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/**\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.\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 * Inspect an HTTP request before the host's request handler.\n *\n * Return a response to handle the request, or `undefined` to continue.\n */\n onRequest?(\n context: CapabilityRequestContext\n ): MaybePromise<Response | undefined | void>;\n\n /** Run work assigned to the capability when the host's alarm fires. */\n onAlarm?(): MaybePromise<void>;\n\n /** Handle one message routed to this capability identity. */\n onRoute?(context: LifecycleRouteContext): MaybePromise<unknown>;\n\n /** Return this capability's next requested physical alarm. */\n getNextAlarm?(): MaybePromise<AlarmContribution>;\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 and alarms run in declaration order, and\n * requests stop at the first response.\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 in declaration order.\n *\n * @param context - The request entering the Durable Object.\n * @returns The first capability response, or `undefined` when unhandled.\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 /** Return alarm requests from every installed capability. */\n async getAlarmContributions(): Promise<AlarmContribution[]> {\n await this.#ensureReady(\"contribute an alarm\");\n const contributions: AlarmContribution[] = [];\n for (const capability of this.#getCapabilities()) {\n const contribution = await capability.getNextAlarm?.();\n if (contribution !== undefined) contributions.push(contribution);\n }\n return contributions;\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 /** 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 /** Run every capability's alarm hook in declaration order. */\n async alarm(): Promise<void> {\n await this.#ensureReady(\"handle an alarm\");\n for (const capability of this.#getCapabilities()) {\n await capability.onAlarm?.();\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","// Polyfill WebSocket status code constants for environments that don't have them\n// in order to support libraries that expect standards-compatible WebSocket\n// implementations (e.g. PartySocket)\n\nimport type {\n Connection,\n ConnectionSetStateFn,\n ConnectionState\n} from \"./types\";\n\nif (!(\"OPEN\" in WebSocket)) {\n const WebSocketStatus = {\n // @ts-expect-error\n CONNECTING: WebSocket.READY_STATE_CONNECTING,\n // @ts-expect-error\n OPEN: WebSocket.READY_STATE_OPEN,\n // @ts-expect-error\n CLOSING: WebSocket.READY_STATE_CLOSING,\n // @ts-expect-error\n CLOSED: WebSocket.READY_STATE_CLOSED\n };\n\n Object.assign(WebSocket, WebSocketStatus);\n // @ts-expect-error\n Object.assign(WebSocket.prototype, WebSocketStatus);\n}\n\n/**\n * Store both platform attachments and user attachments in different namespaces\n */\ntype ConnectionAttachments = {\n __pk: {\n id: string;\n tags: string[];\n uri?: string;\n };\n __user?: unknown;\n};\n\nfunction tryGetManagedWebSocketMeta(\n ws: WebSocket\n): ConnectionAttachments[\"__pk\"] | null {\n try {\n // Avoid AttachmentCache.get() here: externally accepted sockets\n // can have an attachment without the managed __pk namespace.\n const attachment = WebSocket.prototype.deserializeAttachment.call(\n ws\n ) as unknown;\n if (!attachment || typeof attachment !== \"object\") {\n return null;\n }\n if (!(\"__pk\" in attachment)) {\n return null;\n }\n const pk = (attachment as ConnectionAttachments).__pk as unknown;\n if (!pk || typeof pk !== \"object\") {\n return null;\n }\n const { id, tags } = pk as {\n id?: unknown;\n tags?: unknown;\n };\n if (typeof id !== \"string\") {\n return null;\n }\n const { uri } = pk as { uri?: unknown };\n return {\n id,\n tags: Array.isArray(tags) ? tags : [],\n uri: typeof uri === \"string\" ? uri : undefined\n } satisfies ConnectionAttachments[\"__pk\"];\n } catch {\n return null;\n }\n}\n\nexport function isManagedWebSocket(ws: WebSocket): boolean {\n return tryGetManagedWebSocketMeta(ws) !== null;\n}\n\n/**\n * Cache websocket attachments to avoid having to rehydrate them on every property access.\n */\nclass AttachmentCache {\n #cache = new WeakMap<WebSocket, ConnectionAttachments>();\n\n get(ws: WebSocket): ConnectionAttachments {\n let attachment = this.#cache.get(ws);\n if (!attachment) {\n attachment = WebSocket.prototype.deserializeAttachment.call(\n ws\n ) as ConnectionAttachments;\n if (attachment !== undefined) {\n this.#cache.set(ws, attachment);\n } else {\n throw new Error(\"Missing managed WebSocket lifecycle attachment\");\n }\n }\n\n return attachment;\n }\n\n set(ws: WebSocket, attachment: ConnectionAttachments) {\n this.#cache.set(ws, attachment);\n WebSocket.prototype.serializeAttachment.call(ws, attachment);\n }\n}\n\nconst attachments = new AttachmentCache();\nconst connections = new WeakSet<Connection>();\nconst isWrapped = (ws: WebSocket): ws is Connection => {\n return connections.has(ws as Connection);\n};\n\n/**\n * Wraps a WebSocket with Connection fields that rehydrate the\n * socket attachments lazily only when requested.\n */\nexport const createConnection = (ws: WebSocket | Connection): Connection => {\n if (isWrapped(ws)) {\n return ws;\n }\n\n // if state was set on the socket before initializing the connection,\n // capture it here so we can persist it again\n let initialState;\n if (\"state\" in ws) {\n initialState = ws.state;\n delete ws.state;\n }\n\n const connection = Object.defineProperties(ws, {\n id: {\n configurable: true,\n get() {\n return attachments.get(ws).__pk.id;\n }\n },\n uri: {\n configurable: true,\n get() {\n return attachments.get(ws).__pk.uri ?? null;\n }\n },\n tags: {\n configurable: true,\n get() {\n // Default to [] for connections accepted before tags were stored\n return attachments.get(ws).__pk.tags ?? [];\n }\n },\n state: {\n configurable: true,\n get() {\n const attachment = attachments.get(ws);\n return (attachment.__user ?? null) as ConnectionState<unknown>;\n }\n },\n setState: {\n configurable: true,\n value: function setState<T>(setState: T | ConnectionSetStateFn<T>) {\n const state =\n setState instanceof Function\n ? setState((this as Connection<T>).state)\n : setState;\n attachments.set(ws, {\n ...attachments.get(ws),\n __user: state ?? null\n });\n return state as ConnectionState<T>;\n }\n }\n }) as Connection;\n\n if (initialState) {\n connection.setState(initialState);\n }\n\n connections.add(connection);\n return connection;\n};\n\nclass ConnectionIterator<T> implements IterableIterator<Connection<T>> {\n private index = 0;\n private sockets: WebSocket[] | undefined;\n constructor(\n private state: DurableObjectState,\n private tag?: string\n ) {}\n\n [Symbol.iterator](): IterableIterator<Connection<T>> {\n return this;\n }\n\n next(): IteratorResult<Connection<T>, number | undefined> {\n const sockets =\n this.sockets ?? (this.sockets = this.state.getWebSockets(this.tag));\n\n let socket: WebSocket;\n while ((socket = sockets[this.index++])) {\n // Only yield open sockets.\n if (socket.readyState === WebSocket.OPEN) {\n // Durable Objects hibernation APIs allow storing arbitrary sockets via\n // `state.acceptWebSocket()`. Ignore sockets without our attachment.\n if (!isManagedWebSocket(socket)) {\n continue;\n }\n const value = createConnection(socket) as Connection<T>;\n return { done: false, value };\n }\n }\n\n // reached the end of the iteratee\n return { done: true, value: undefined };\n }\n}\n\n/**\n * Deduplicate and validate connection tags.\n * Returns the final tag array (always includes the connection id as the first tag).\n */\nfunction prepareTags(connectionId: string, userTags: string[]): string[] {\n const tags = [connectionId, ...userTags.filter((t) => t !== connectionId)];\n\n // validate tags against documented restrictions\n // https://developers.cloudflare.com/durable-objects/api/hibernatable-websockets-api/#state-methods-for-websockets\n if (tags.length > 10) {\n throw new Error(\n \"A connection can only have 10 tags, including the default id tag.\"\n );\n }\n\n for (const tag of tags) {\n if (typeof tag !== \"string\") {\n throw new Error(`A connection tag must be a string. Received: ${tag}`);\n }\n if (tag === \"\") {\n throw new Error(\"A connection tag must not be an empty string.\");\n }\n if (tag.length > 256) {\n throw new Error(\"A connection tag must not exceed 256 characters\");\n }\n }\n\n return tags;\n}\n\n/** The platform-backed manager for hibernating WebSockets. */\nexport class ConnectionManager<TState = unknown> {\n constructor(private controller: DurableObjectState) {}\n\n getConnection<T = TState>(id: string) {\n // TODO: Should we cache the connections?\n const sockets = this.controller.getWebSockets(id);\n const matching = sockets.filter((ws) => {\n return tryGetManagedWebSocketMeta(ws)?.id === id;\n });\n\n if (matching.length === 0) return undefined;\n if (matching.length === 1)\n return createConnection(matching[0]) as Connection<T>;\n\n throw new Error(\n `More than one connection found for id ${id}. Did you mean to use getConnections(tag) instead?`\n );\n }\n\n getConnections<T = TState>(tag?: string | undefined) {\n return new ConnectionIterator<T>(this.controller, tag);\n }\n\n accept(connection: Connection, options: { tags: string[] }) {\n const tags = prepareTags(connection.id, options.tags);\n\n this.controller.acceptWebSocket(connection, tags);\n attachments.set(connection, {\n __pk: {\n id: connection.id,\n tags,\n uri: connection.uri ?? undefined\n },\n __user: null\n });\n\n return createConnection(connection);\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\";\nimport { nanoid } from \"nanoid\";\n\nimport { publishDiagnosticsEvent } from \"../observability/diagnostics\";\nimport {\n type AlarmContribution,\n CapabilityRunner,\n type DurableObjectCapability,\n type LifecycleEvent,\n type LifecycleEventSink\n} from \"./capability-runner\";\nimport {\n bindLifecycleCapability,\n lifecycleCapabilityId,\n LifecycleCapability,\n type LifecycleRouteAddress,\n type LifecycleServices\n} from \"./capability\";\nimport {\n createConnection,\n ConnectionManager,\n isManagedWebSocket\n} from \"./connection\";\n\nimport {\n runInLifecycleHostContext,\n runWithoutCurrentAgent,\n type LifecycleObject\n} from \"./current-agent\";\nimport { isBenignTeardownError } from \"./transport-errors\";\n\nimport type {\n Connection,\n ConnectionSetStateFn,\n ConnectionState\n} from \"./types\";\n\nexport {\n type AlarmContribution,\n type CapabilityRequestContext,\n type LifecycleEvent,\n type CapabilityStartContext,\n type DurableObjectCapability\n} from \"./capability-runner\";\nexport * from \"./types\";\n\n/** Payload delivered to a lifecycle-managed WebSocket callback. */\nexport type WSMessage = ArrayBuffer | ArrayBufferView | string;\n\nconst LEGACY_NAME_STORAGE_KEY = \"__ps_name\";\n\n/**\n * Reserved WebSocket close codes the runtime synthesizes when there\n * was no real Close frame from the peer:\n * - 1005 (NoStatusReceived) — peer's frame had no status code.\n * - 1006 (AbnormalClosure) — peer dropped the underlying transport\n * without sending a Close frame at all.\n * - 1015 (TLSHandshake) — TLS failure during connection setup.\n *\n * These cannot legally appear in an outgoing Close frame, and — more\n * importantly for our reciprocation path — there is no peer left to\n * receive a reciprocating Close frame. Trying to send one anyway can\n * succeed synchronously but fail asynchronously inside the runtime\n * with \"WebSocket peer disconnected\" / \"Network connection lost\",\n * which escapes a synchronous try/catch and surfaces as an unhandled\n * promise rejection.\n */\nfunction isReservedCloseCode(code: number): boolean {\n return code === 1005 || code === 1006 || code === 1015;\n}\n\n/**\n * Reciprocate a peer-initiated Close frame to complete the handshake.\n *\n * Best-effort: swallows synchronous errors from invalid codes,\n * oversize reasons, or sockets that have already been closed by user\n * code. Skips the reciprocation entirely when the peer didn't\n * actually send a Close frame (reserved codes 1005/1006/1015) — in\n * those cases the underlying transport is already gone and writing\n * to it would fail asynchronously, which we can't catch here.\n *\n * Used by the hibernating close handler to complete real close handshakes.\n */\nfunction closeQuietly(ws: WebSocket, code: number, reason: string): void {\n // No real Close frame from the peer → nothing to reciprocate.\n // Calling `ws.close(...)` here would synchronously succeed but\n // schedule an outbound write on a dead transport, which the runtime\n // would later reject with \"Network connection lost\". That rejection\n // can't be observed from here (it's not thrown synchronously and\n // ws.close() doesn't return a Promise to attach a `.catch` to), so\n // it would surface as an unhandled rejection.\n if (isReservedCloseCode(code)) return;\n try {\n ws.close(code, reason);\n } catch {\n // Reasons we end up here:\n // - the socket was already closed (user called `connection.close()`\n // in `onClose`, or the runtime auto-replied on compat dates\n // >= 2026-04-07 for the standard `accept()` API)\n // - `reason` exceeds the 123-byte UTF-8 limit (compat date\n // >= 2026-03-03)\n // - some other invariant violation we don't want to crash the\n // handler over\n // None of these are recoverable here; the handshake is either already\n // done or the runtime is out of our control.\n }\n}\n\nfunction mutableRequest(request: Request): Request {\n return new Request(request);\n}\n\nfunction selectAlarm(\n contributions: ReadonlyArray<AlarmContribution>\n): number | null {\n let ordinary: number | null = null;\n let exclusive: number | null = null;\n for (const contribution of contributions) {\n if (contribution === null) continue;\n const time =\n typeof contribution === \"number\" ? contribution : contribution.time;\n if (!Number.isFinite(time) || time < 0) {\n throw new Error(`Invalid alarm contribution: ${String(time)}`);\n }\n if (typeof contribution === \"object\" && contribution.exclusive) {\n exclusive = exclusive === null ? time : Math.min(exclusive, time);\n } else {\n ordinary = ordinary === null ? time : Math.min(ordinary, time);\n }\n }\n return exclusive ?? ordinary;\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).\n */\nexport type LifecycleHostInvoker = <T>(run: () => T) => 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/**\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 #connectionManager: ConnectionManager;\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 #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 >(host: DurableObject<Env>): Lifecycle<Env, Props> {\n const lifecycle = new Lifecycle<Env, Props>(host);\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 */\n constructor(host: DurableObject<Env>) {\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.#connectionManager = new ConnectionManager(this.#ctx);\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 * @param capability - The capability to add in dispatch order.\n * @returns This lifecycle.\n */\n use(capability: DurableObjectCapability<Props>): this {\n if (this.#capabilitiesLocked) {\n throw new Error(\"Lifecycle capabilities must be added before startup\");\n }\n const capabilityId = lifecycleCapabilityId(capability);\n if (\n capabilityId &&\n this.#capabilities.some(\n (candidate) => lifecycleCapabilityId(candidate) === capabilityId\n )\n ) {\n throw new Error(\n `Lifecycle capability ${JSON.stringify(capabilityId)} is already installed`\n );\n }\n this.#capabilities.push(capability);\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 ready: () => this.#readyForCapabilityOperation(),\n starting: () => this.#status === \"starting\",\n alarms: Object.freeze({\n rearm: () => this.rearmAlarm(),\n disabled: () => this.#alarmsDisabled\n }),\n runInHostContext: async (fn: () => unknown) =>\n this.#runInHostBoundary(fn),\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(fn: () => unknown): Promise<unknown> {\n const boundary = lifecycleHostInvokers.get(this);\n return Promise.resolve(\n boundary\n ? boundary(fn)\n : runInLifecycleHostContext({ host: this.#host }, fn)\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 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 const url = new URL(request.url);\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 // Create the websocket pair for the client\n const { 0: clientWebSocket, 1: serverWebSocket } = new WebSocketPair();\n let connectionId = url.searchParams.get(\"_pk\");\n if (!connectionId) {\n connectionId = nanoid();\n }\n\n let connection: Connection = Object.assign(serverWebSocket, {\n id: connectionId,\n uri: request.url,\n tags: [] as string[],\n state: null as unknown as ConnectionState<unknown>,\n setState<T = unknown>(setState: T | ConnectionSetStateFn<T>) {\n let state: T;\n if (setState instanceof Function) {\n state = setState(this.state as ConnectionState<T>);\n } else {\n state = setState;\n }\n\n // TODO: deepFreeze object?\n this.state = state as ConnectionState<T>;\n return this.state;\n }\n });\n\n const ctx = { request };\n\n // getConnectionTags already receives both connection and request\n // explicitly. TODO: run it in host context if shared callback code\n // develops a concrete need for getCurrentAgent() in this hook.\n const tags = this.#host.getConnectionTags\n ? await this.#host.getConnectionTags(connection, ctx)\n : [];\n\n // Hibernating WebSockets remain connected while the object is evicted.\n connection = this.#connectionManager.accept(connection, { tags });\n await runInLifecycleHostContext(\n { host: this.#host, connection, request },\n () => this.#host.onConnect?.(connection, ctx)\n );\n\n return new Response(null, { status: 101, webSocket: clientWebSocket });\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 // Ignore WebSockets accepted outside this lifecycle (e.g. via\n // `state.acceptWebSocket()` in user code). These sockets do not have the\n // managed attachment required to rehydrate a Connection.\n if (!isManagedWebSocket(ws)) {\n return;\n }\n\n try {\n const connection = createConnection(ws);\n\n await this.#ensureInitialized();\n return runInLifecycleHostContext({ host: this.#host, connection }, () =>\n this.#host.onMessage?.(connection, 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 and reciprocate a hibernating WebSocket close. */\n async webSocketClose(\n ws: WebSocket,\n code: number,\n reason: string,\n wasClean: boolean\n ): Promise<void> {\n if (!isManagedWebSocket(ws)) {\n return;\n }\n\n try {\n const connection = createConnection(ws);\n\n await this.#ensureInitialized();\n await runInLifecycleHostContext({ host: this.#host, connection }, () =>\n this.#host.onClose?.(connection, 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 } finally {\n // Reciprocate the peer's Close frame to complete the handshake.\n // The Hibernation API requires applications to do this — without it,\n // clients stay in CLOSING and end up reporting 1006 abnormal closure.\n // The standard `accept()` API gets this for free on compat dates\n // >= 2026-04-07 via the `web_socket_auto_reply_to_close` flag, but the\n // Hibernation API contract is unchanged: see\n // https://developers.cloudflare.com/durable-objects/api/base/#websocketclose\n // Calling close() on an already-closed socket is a silent no-op, so\n // this is safe regardless of compat date or whether user code in\n // `onClose` already called `connection.close()`.\n closeQuietly(ws, code, reason);\n }\n }\n\n /** @internal Dispatch a hibernating WebSocket error. */\n async webSocketError(ws: WebSocket, error: unknown): Promise<void> {\n if (!isManagedWebSocket(ws)) {\n return;\n }\n\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 // onError below.\n if (isBenignTeardownError(ws, error)) {\n return;\n }\n\n try {\n const connection = createConnection(ws);\n\n await this.#ensureInitialized();\n return runInLifecycleHostContext({ host: this.#host, connection }, () =>\n this.#host.onError?.(connection, 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 #sendMessageToConnection(connection: Connection, message: WSMessage): void {\n try {\n connection.send(message);\n } catch (_e) {\n // close connection\n connection.close(1011, \"Unexpected error\");\n }\n }\n\n /** Send a message to all connected clients, except connection ids listed in `without` */\n broadcast(\n msg: string | ArrayBuffer | ArrayBufferView,\n without?: string[] | undefined\n ): void {\n for (const connection of this.#connectionManager.getConnections()) {\n if (!without || !without.includes(connection.id)) {\n this.#sendMessageToConnection(connection, msg);\n }\n }\n }\n\n /** Get a connection by connection id */\n getConnection<TState = unknown>(id: string): Connection<TState> | undefined {\n return this.#connectionManager.getConnection<TState>(id);\n }\n\n /** Get all managed connections, optionally filtered by tag. */\n getConnections<TState = unknown>(tag?: string): Iterable<Connection<TState>> {\n return this.#connectionManager.getConnections<TState>(tag);\n }\n\n #props?: Props;\n\n /**\n * Recompute the physical Durable Object alarm from every capability.\n *\n * Concurrent requests are serialized so a later durable-state change cannot\n * be overwritten by an earlier alarm calculation.\n */\n async rearmAlarm(): Promise<void> {\n if (this.#alarmsDisabled) return;\n if (this.#status === \"starting\") {\n this.#rearmRequestedDuringStart = true;\n return;\n }\n if (this.#status === \"zero\") await this.start();\n\n const prior = this.#alarmRearmQueue;\n const next = prior\n .catch(() => {})\n .then(async () => {\n if (this.#alarmsDisabled) return;\n const contributions = await runWithoutCurrentAgent(() =>\n this.#capabilityRunner.getAlarmContributions()\n );\n const hostContribution = await runInLifecycleHostContext(\n { host: this.#host },\n () => this.#host.getNextAlarm?.()\n );\n if (hostContribution !== undefined) {\n contributions.push(hostContribution);\n }\n const alarm = selectAlarm(contributions);\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 /** 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 /** Dispatch lifecycle and host alarm callbacks after startup. */\n async alarm(): Promise<void> {\n await this.#ensureInitialized();\n await runWithoutCurrentAgent(() => this.#capabilityRunner.alarm());\n await runInLifecycleHostContext({ host: this.#host }, () =>\n this.#host.onAlarm?.()\n );\n await this.rearmAlarm();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsFA,IAAa,mBAAb,MAA6D;;;;;;;CAa3D,YACE,qBACA;;;;;6CAVS,KAAA;EAWT,uBAAA,sBAAA,MAA4B,mBAAA;CAC9B;;;;;;;;;CAUA,MAAM,MAAM,SAAuD;EACjE,IAAA,uBAAA,UAAI,IAAA,GAAe;EAEnB,MAAM,UAAA,uBAAA,eAAU,IAAA;EAChB,IAAI,SAAS;GACX,MAAM;GACN;EACF;EAEA,MAAM,UAAA,kBAAA,yBAAU,MAAA,SAAA,CAAA,CAAA,KAAA,MAAe,OAAO;EACtC,uBAAA,eAAA,MAAqB,OAAA;EACrB,IAAI;GACF,MAAM;EACR,SAAS,OAAO;GACd,IAAA,uBAAA,eAAI,IAAA,MAAuB,SACzB,uBAAA,eAAA,MAAqB,KAAA,CAAA;GAEvB,MAAM;EACR;CACF;;;;;;;CAQA,MAAM,QACJ,SAC+B;EAC/B,MAAA,kBAAA,yBAAM,MAAA,YAAA,CAAA,CAAA,KAAA,MAAkB,kBAAkB;EAC1C,KAAK,MAAM,cAAA,kBAAA,yBAAc,MAAA,gBAAA,CAAA,CAAA,KAAA,IAAsB,GAAG;GAChD,MAAM,WAAW,MAAM,WAAW,YAAY,OAAO;GACrD,IAAI,aAAa,KAAA,GAAW,OAAO;EACrC;CAEF;;CAGA,MAAM,wBAAsD;EAC1D,MAAA,kBAAA,yBAAM,MAAA,YAAA,CAAA,CAAA,KAAA,MAAkB,qBAAqB;EAC7C,MAAM,gBAAqC,CAAC;EAC5C,KAAK,MAAM,cAAA,kBAAA,yBAAc,MAAA,gBAAA,CAAA,CAAA,KAAA,IAAsB,GAAG;GAChD,MAAM,eAAe,MAAM,WAAW,eAAe;GACrD,IAAI,iBAAiB,KAAA,GAAW,cAAc,KAAK,YAAY;EACjE;EACA,OAA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