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,862 +0,0 @@
1
- import { i as runWithoutCurrentAgent, r as runInLifecycleHostContext } from "./current-agent-DhoDkSnH.js";
2
- import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldSet2, r as _assertClassBrand, t as _classPrivateFieldGet2 } from "./classPrivateFieldGet2-DZBYAB34.js";
3
- import { n as publishDiagnosticsEvent } from "./diagnostics-CaBjfz4J.js";
4
- import { n as bindLifecycleCapability, r as lifecycleCapabilityId, t as LifecycleCapability } from "./capability-BjSKYpzg.js";
5
- import { t as _classPrivateMethodInitSpec } from "./classPrivateMethodInitSpec-qMjJ6sHQ.js";
6
- import { nanoid } from "nanoid";
7
- import "cloudflare:workers";
8
- //#region src/lifecycle/capability-runner.ts
9
- var _resolveCapabilities = /* @__PURE__ */ new WeakMap();
10
- var _capabilities$1 = /* @__PURE__ */ new WeakMap();
11
- var _startPromise = /* @__PURE__ */ new WeakMap();
12
- var _started = /* @__PURE__ */ new WeakMap();
13
- var _CapabilityRunner_brand = /* @__PURE__ */ new WeakSet();
14
- /**
15
- * Runs ordered lifecycle phases for capabilities installed in a Durable Object.
16
- *
17
- * Capabilities are resolved lazily on the first phase and retained for the
18
- * lifetime of this runner. Startup and alarms run in declaration order, and
19
- * requests stop at the first response.
20
- */
21
- var CapabilityRunner = class {
22
- /**
23
- * Create a lifecycle whose capabilities are resolved immediately before the
24
- * first phase.
25
- *
26
- * @param resolveCapabilities - Returns capabilities in their startup order.
27
- */
28
- constructor(resolveCapabilities) {
29
- _classPrivateMethodInitSpec(this, _CapabilityRunner_brand);
30
- _classPrivateFieldInitSpec(this, _resolveCapabilities, void 0);
31
- _classPrivateFieldInitSpec(this, _capabilities$1, void 0);
32
- _classPrivateFieldInitSpec(this, _startPromise, void 0);
33
- _classPrivateFieldInitSpec(this, _started, false);
34
- _classPrivateFieldSet2(_resolveCapabilities, this, resolveCapabilities);
35
- }
36
- /**
37
- * Start every capability sequentially.
38
- *
39
- * Concurrent callers share one startup attempt. A failed attempt is not
40
- * cached, allowing the host to retry its complete startup phase.
41
- *
42
- * @param context - Properties supplied while resolving the Durable Object.
43
- */
44
- async start(context) {
45
- if (_classPrivateFieldGet2(_started, this)) return;
46
- const pending = _classPrivateFieldGet2(_startPromise, this);
47
- if (pending) {
48
- await pending;
49
- return;
50
- }
51
- const attempt = _assertClassBrand(_CapabilityRunner_brand, this, _runStart).call(this, context);
52
- _classPrivateFieldSet2(_startPromise, this, attempt);
53
- try {
54
- await attempt;
55
- } catch (error) {
56
- if (_classPrivateFieldGet2(_startPromise, this) === attempt) _classPrivateFieldSet2(_startPromise, this, void 0);
57
- throw error;
58
- }
59
- }
60
- /**
61
- * Offer a request to each capability in declaration order.
62
- *
63
- * @param context - The request entering the Durable Object.
64
- * @returns The first capability response, or `undefined` when unhandled.
65
- */
66
- async request(context) {
67
- await _assertClassBrand(_CapabilityRunner_brand, this, _ensureReady).call(this, "handle a request");
68
- for (const capability of _assertClassBrand(_CapabilityRunner_brand, this, _getCapabilities).call(this)) {
69
- const response = await capability.onRequest?.(context);
70
- if (response !== void 0) return response;
71
- }
72
- }
73
- /** Return alarm requests from every installed capability. */
74
- async getAlarmContributions() {
75
- await _assertClassBrand(_CapabilityRunner_brand, this, _ensureReady).call(this, "contribute an alarm");
76
- const contributions = [];
77
- for (const capability of _assertClassBrand(_CapabilityRunner_brand, this, _getCapabilities).call(this)) {
78
- const contribution = await capability.getNextAlarm?.();
79
- if (contribution !== void 0) contributions.push(contribution);
80
- }
81
- return contributions;
82
- }
83
- /** Route one message to an installed named capability. */
84
- async route(capabilityId, context) {
85
- await _assertClassBrand(_CapabilityRunner_brand, this, _ensureReady).call(this, "route a capability message");
86
- const capability = _assertClassBrand(_CapabilityRunner_brand, this, _getCapabilities).call(this).find((candidate) => lifecycleCapabilityId(candidate) === capabilityId);
87
- if (!capability?.onRoute) throw new Error(`Lifecycle capability ${JSON.stringify(capabilityId)} cannot receive routed messages`);
88
- return capability.onRoute(context);
89
- }
90
- /** Dispose installed capabilities in reverse registration order. */
91
- async dispose() {
92
- for (const capability of [..._assertClassBrand(_CapabilityRunner_brand, this, _getCapabilities).call(this)].reverse()) try {
93
- await capability.dispose?.();
94
- } catch (error) {
95
- console.error("Lifecycle capability disposal failed", error);
96
- }
97
- }
98
- /** Run every capability's alarm hook in declaration order. */
99
- async alarm() {
100
- await _assertClassBrand(_CapabilityRunner_brand, this, _ensureReady).call(this, "handle an alarm");
101
- for (const capability of _assertClassBrand(_CapabilityRunner_brand, this, _getCapabilities).call(this)) await capability.onAlarm?.();
102
- }
103
- };
104
- async function _runStart(context) {
105
- for (const capability of _assertClassBrand(_CapabilityRunner_brand, this, _getCapabilities).call(this)) await capability.onStart?.(context);
106
- _classPrivateFieldSet2(_started, this, true);
107
- }
108
- async function _ensureReady(operation) {
109
- const pending = _classPrivateFieldGet2(_startPromise, this);
110
- if (pending) await pending;
111
- if (!_classPrivateFieldGet2(_started, this)) throw new Error(`Cannot ${operation} before the Durable Object lifecycle has started`);
112
- }
113
- function _getCapabilities() {
114
- if (!_classPrivateFieldGet2(_capabilities$1, this)) _classPrivateFieldSet2(_capabilities$1, this, Object.freeze([..._classPrivateFieldGet2(_resolveCapabilities, this).call(this)]));
115
- return _classPrivateFieldGet2(_capabilities$1, this);
116
- }
117
- //#endregion
118
- //#region src/lifecycle/connection.ts
119
- let _Symbol$iterator;
120
- if (!("OPEN" in WebSocket)) {
121
- const WebSocketStatus = {
122
- CONNECTING: WebSocket.READY_STATE_CONNECTING,
123
- OPEN: WebSocket.READY_STATE_OPEN,
124
- CLOSING: WebSocket.READY_STATE_CLOSING,
125
- CLOSED: WebSocket.READY_STATE_CLOSED
126
- };
127
- Object.assign(WebSocket, WebSocketStatus);
128
- Object.assign(WebSocket.prototype, WebSocketStatus);
129
- }
130
- function tryGetManagedWebSocketMeta(ws) {
131
- try {
132
- const attachment = WebSocket.prototype.deserializeAttachment.call(ws);
133
- if (!attachment || typeof attachment !== "object") return null;
134
- if (!("__pk" in attachment)) return null;
135
- const pk = attachment.__pk;
136
- if (!pk || typeof pk !== "object") return null;
137
- const { id, tags } = pk;
138
- if (typeof id !== "string") return null;
139
- const { uri } = pk;
140
- return {
141
- id,
142
- tags: Array.isArray(tags) ? tags : [],
143
- uri: typeof uri === "string" ? uri : void 0
144
- };
145
- } catch {
146
- return null;
147
- }
148
- }
149
- function isManagedWebSocket(ws) {
150
- return tryGetManagedWebSocketMeta(ws) !== null;
151
- }
152
- var _cache = /* @__PURE__ */ new WeakMap();
153
- /**
154
- * Cache websocket attachments to avoid having to rehydrate them on every property access.
155
- */
156
- var AttachmentCache = class {
157
- constructor() {
158
- _classPrivateFieldInitSpec(this, _cache, /* @__PURE__ */ new WeakMap());
159
- }
160
- get(ws) {
161
- let attachment = _classPrivateFieldGet2(_cache, this).get(ws);
162
- if (!attachment) {
163
- attachment = WebSocket.prototype.deserializeAttachment.call(ws);
164
- if (attachment !== void 0) _classPrivateFieldGet2(_cache, this).set(ws, attachment);
165
- else throw new Error("Missing managed WebSocket lifecycle attachment");
166
- }
167
- return attachment;
168
- }
169
- set(ws, attachment) {
170
- _classPrivateFieldGet2(_cache, this).set(ws, attachment);
171
- WebSocket.prototype.serializeAttachment.call(ws, attachment);
172
- }
173
- };
174
- const attachments = new AttachmentCache();
175
- const connections = /* @__PURE__ */ new WeakSet();
176
- const isWrapped = (ws) => {
177
- return connections.has(ws);
178
- };
179
- /**
180
- * Wraps a WebSocket with Connection fields that rehydrate the
181
- * socket attachments lazily only when requested.
182
- */
183
- const createConnection = (ws) => {
184
- if (isWrapped(ws)) return ws;
185
- let initialState;
186
- if ("state" in ws) {
187
- initialState = ws.state;
188
- delete ws.state;
189
- }
190
- const connection = Object.defineProperties(ws, {
191
- id: {
192
- configurable: true,
193
- get() {
194
- return attachments.get(ws).__pk.id;
195
- }
196
- },
197
- uri: {
198
- configurable: true,
199
- get() {
200
- return attachments.get(ws).__pk.uri ?? null;
201
- }
202
- },
203
- tags: {
204
- configurable: true,
205
- get() {
206
- return attachments.get(ws).__pk.tags ?? [];
207
- }
208
- },
209
- state: {
210
- configurable: true,
211
- get() {
212
- return attachments.get(ws).__user ?? null;
213
- }
214
- },
215
- setState: {
216
- configurable: true,
217
- value: function setState(setState) {
218
- const state = setState instanceof Function ? setState(this.state) : setState;
219
- attachments.set(ws, {
220
- ...attachments.get(ws),
221
- __user: state ?? null
222
- });
223
- return state;
224
- }
225
- }
226
- });
227
- if (initialState) connection.setState(initialState);
228
- connections.add(connection);
229
- return connection;
230
- };
231
- _Symbol$iterator = Symbol.iterator;
232
- var ConnectionIterator = class {
233
- constructor(state, tag) {
234
- this.state = state;
235
- this.tag = tag;
236
- this.index = 0;
237
- }
238
- [_Symbol$iterator]() {
239
- return this;
240
- }
241
- next() {
242
- const sockets = this.sockets ?? (this.sockets = this.state.getWebSockets(this.tag));
243
- let socket;
244
- while (socket = sockets[this.index++]) if (socket.readyState === WebSocket.OPEN) {
245
- if (!isManagedWebSocket(socket)) continue;
246
- return {
247
- done: false,
248
- value: createConnection(socket)
249
- };
250
- }
251
- return {
252
- done: true,
253
- value: void 0
254
- };
255
- }
256
- };
257
- /**
258
- * Deduplicate and validate connection tags.
259
- * Returns the final tag array (always includes the connection id as the first tag).
260
- */
261
- function prepareTags(connectionId, userTags) {
262
- const tags = [connectionId, ...userTags.filter((t) => t !== connectionId)];
263
- if (tags.length > 10) throw new Error("A connection can only have 10 tags, including the default id tag.");
264
- for (const tag of tags) {
265
- if (typeof tag !== "string") throw new Error(`A connection tag must be a string. Received: ${tag}`);
266
- if (tag === "") throw new Error("A connection tag must not be an empty string.");
267
- if (tag.length > 256) throw new Error("A connection tag must not exceed 256 characters");
268
- }
269
- return tags;
270
- }
271
- /** The platform-backed manager for hibernating WebSockets. */
272
- var ConnectionManager = class {
273
- constructor(controller) {
274
- this.controller = controller;
275
- }
276
- getConnection(id) {
277
- const matching = this.controller.getWebSockets(id).filter((ws) => {
278
- return tryGetManagedWebSocketMeta(ws)?.id === id;
279
- });
280
- if (matching.length === 0) return void 0;
281
- if (matching.length === 1) return createConnection(matching[0]);
282
- throw new Error(`More than one connection found for id ${id}. Did you mean to use getConnections(tag) instead?`);
283
- }
284
- getConnections(tag) {
285
- return new ConnectionIterator(this.controller, tag);
286
- }
287
- accept(connection, options) {
288
- const tags = prepareTags(connection.id, options.tags);
289
- this.controller.acceptWebSocket(connection, tags);
290
- attachments.set(connection, {
291
- __pk: {
292
- id: connection.id,
293
- tags,
294
- uri: connection.uri ?? void 0
295
- },
296
- __user: null
297
- });
298
- return createConnection(connection);
299
- }
300
- };
301
- //#endregion
302
- //#region src/lifecycle/transport-errors.ts
303
- /** Standard `WebSocket.readyState` values. */
304
- const CLOSING = 2;
305
- const CLOSED = 3;
306
- /**
307
- * A retryable transport-teardown error ("Network connection lost" /
308
- * "WebSocket peer disconnected") that fires on a connection which is already
309
- * CLOSING/CLOSED is just the socket going away during or right after the close
310
- * handshake - not an application error. Surfacing it via `onError` spams logs
311
- * on every abrupt client disconnect, and even on clean closes when the peer
312
- * tears down its transport before our reciprocal Close frame lands. Suppress
313
- * it in that specific case only; genuine mid-connection (OPEN) errors still
314
- * reach `onError`.
315
- *
316
- * Detection prefers the structured `retryable` flag over message text so it
317
- * stays correct across `enhanced-error-serialization` (compat date
318
- * >= 2026-04-21), with a substring fallback for older error shapes.
319
- */
320
- function isBenignTeardownError(ws, error) {
321
- const state = ws.readyState;
322
- if (state !== CLOSING && state !== CLOSED) return false;
323
- if (typeof error !== "object" || error === null) return false;
324
- const typed = error;
325
- if (typed.retryable === true) return true;
326
- const message = typeof typed.message === "string" ? typed.message : "";
327
- return /Network connection lost|WebSocket peer disconnected/i.test(message);
328
- }
329
- //#endregion
330
- //#region src/lifecycle/durable-object-lifecycle.ts
331
- const LEGACY_NAME_STORAGE_KEY = "__ps_name";
332
- /**
333
- * Reserved WebSocket close codes the runtime synthesizes when there
334
- * was no real Close frame from the peer:
335
- * - 1005 (NoStatusReceived) — peer's frame had no status code.
336
- * - 1006 (AbnormalClosure) — peer dropped the underlying transport
337
- * without sending a Close frame at all.
338
- * - 1015 (TLSHandshake) — TLS failure during connection setup.
339
- *
340
- * These cannot legally appear in an outgoing Close frame, and — more
341
- * importantly for our reciprocation path — there is no peer left to
342
- * receive a reciprocating Close frame. Trying to send one anyway can
343
- * succeed synchronously but fail asynchronously inside the runtime
344
- * with "WebSocket peer disconnected" / "Network connection lost",
345
- * which escapes a synchronous try/catch and surfaces as an unhandled
346
- * promise rejection.
347
- */
348
- function isReservedCloseCode(code) {
349
- return code === 1005 || code === 1006 || code === 1015;
350
- }
351
- /**
352
- * Reciprocate a peer-initiated Close frame to complete the handshake.
353
- *
354
- * Best-effort: swallows synchronous errors from invalid codes,
355
- * oversize reasons, or sockets that have already been closed by user
356
- * code. Skips the reciprocation entirely when the peer didn't
357
- * actually send a Close frame (reserved codes 1005/1006/1015) — in
358
- * those cases the underlying transport is already gone and writing
359
- * to it would fail asynchronously, which we can't catch here.
360
- *
361
- * Used by the hibernating close handler to complete real close handshakes.
362
- */
363
- function closeQuietly(ws, code, reason) {
364
- if (isReservedCloseCode(code)) return;
365
- try {
366
- ws.close(code, reason);
367
- } catch {}
368
- }
369
- function mutableRequest(request) {
370
- return new Request(request);
371
- }
372
- function selectAlarm(contributions) {
373
- let ordinary = null;
374
- let exclusive = null;
375
- for (const contribution of contributions) {
376
- if (contribution === null) continue;
377
- const time = typeof contribution === "number" ? contribution : contribution.time;
378
- if (!Number.isFinite(time) || time < 0) throw new Error(`Invalid alarm contribution: ${String(time)}`);
379
- if (typeof contribution === "object" && contribution.exclusive) exclusive = exclusive === null ? time : Math.min(exclusive, time);
380
- else ordinary = ordinary === null ? time : Math.min(ordinary, time);
381
- }
382
- return exclusive ?? ordinary;
383
- }
384
- /**
385
- * Decode props from the internal lifecycle props header.
386
- *
387
- * Handles both base64-encoded lifecycle props and, for
388
- * backwards compatibility with stubs/requests created by older versions,
389
- * raw JSON. Base64 never starts with `{` or `[`, so a leading brace/bracket
390
- * unambiguously identifies the legacy raw-JSON form.
391
- */
392
- function decodeProps(header) {
393
- const trimmed = header.trim();
394
- if (trimmed.startsWith("{") || trimmed.startsWith("[")) return JSON.parse(trimmed);
395
- const binary = atob(header);
396
- const bytes = new Uint8Array(binary.length);
397
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
398
- return JSON.parse(new TextDecoder().decode(bytes));
399
- }
400
- const lifecycleEventSinks = /* @__PURE__ */ new WeakMap();
401
- const lifecycleRouteTransports = /* @__PURE__ */ new WeakMap();
402
- const lifecycleHostInvokers = /* @__PURE__ */ new WeakMap();
403
- /** @internal Adapt the host invocation boundary at a composition root. */
404
- function setLifecycleHostInvoker(lifecycle, invoker) {
405
- lifecycleHostInvokers.set(lifecycle, invoker);
406
- }
407
- /** @internal Supply a host's routed Lifecycle transport. */
408
- function setLifecycleRouteTransport(lifecycle, transport) {
409
- lifecycleRouteTransports.set(lifecycle, transport);
410
- }
411
- /** @internal Adapt Lifecycle's default diagnostics sink at a composition root. */
412
- function setLifecycleEventSink(lifecycle, sink) {
413
- lifecycleEventSinks.set(lifecycle, sink);
414
- }
415
- var _host = /* @__PURE__ */ new WeakMap();
416
- var _ctx = /* @__PURE__ */ new WeakMap();
417
- var _parentClassName = /* @__PURE__ */ new WeakMap();
418
- var _capabilities = /* @__PURE__ */ new WeakMap();
419
- var _capabilityRunner = /* @__PURE__ */ new WeakMap();
420
- var _connectionManager = /* @__PURE__ */ new WeakMap();
421
- var _status = /* @__PURE__ */ new WeakMap();
422
- var _alarmRearmQueue = /* @__PURE__ */ new WeakMap();
423
- var _rearmRequestedDuringStart = /* @__PURE__ */ new WeakMap();
424
- var _pendingEvents = /* @__PURE__ */ new WeakMap();
425
- var _alarmsDisabled = /* @__PURE__ */ new WeakMap();
426
- var _capabilitiesLocked = /* @__PURE__ */ new WeakMap();
427
- var _handlersInstalled = /* @__PURE__ */ new WeakMap();
428
- var _Lifecycle_brand = /* @__PURE__ */ new WeakSet();
429
- var _legacyName = /* @__PURE__ */ new WeakMap();
430
- var _props = /* @__PURE__ */ new WeakMap();
431
- /**
432
- * Installs and coordinates the runtime lifecycle for a Durable Object.
433
- *
434
- * Construct this as an instance field on a class that directly extends
435
- * `DurableObject`, then call {@link Lifecycle.installHandlers}
436
- * from that class's constructor.
437
- *
438
- * @experimental The API surface may change before stabilizing.
439
- */
440
- var Lifecycle = class Lifecycle {
441
- /**
442
- * Construct and install a lifecycle in one explicit operation.
443
- *
444
- * @param host - The Durable Object whose runtime handlers the lifecycle owns.
445
- * @returns The installed lifecycle.
446
- */
447
- static install(host) {
448
- const lifecycle = new Lifecycle(host);
449
- lifecycle.installHandlers();
450
- return lifecycle;
451
- }
452
- /**
453
- * Bind a lifecycle to a Durable Object instance without mutating its handlers.
454
- *
455
- * @param host - The Durable Object whose runtime lifecycle this object owns.
456
- */
457
- constructor(host) {
458
- _classPrivateMethodInitSpec(this, _Lifecycle_brand);
459
- _classPrivateFieldInitSpec(this, _host, void 0);
460
- _classPrivateFieldInitSpec(this, _ctx, void 0);
461
- _classPrivateFieldInitSpec(this, _parentClassName, void 0);
462
- _classPrivateFieldInitSpec(this, _capabilities, []);
463
- _classPrivateFieldInitSpec(this, _capabilityRunner, new CapabilityRunner(() => _classPrivateFieldGet2(_capabilities, this)));
464
- _classPrivateFieldInitSpec(this, _connectionManager, void 0);
465
- _classPrivateFieldInitSpec(this, _status, "zero");
466
- _classPrivateFieldInitSpec(this, _alarmRearmQueue, Promise.resolve());
467
- _classPrivateFieldInitSpec(this, _rearmRequestedDuringStart, false);
468
- _classPrivateFieldInitSpec(this, _pendingEvents, []);
469
- _classPrivateFieldInitSpec(this, _alarmsDisabled, false);
470
- _classPrivateFieldInitSpec(this, _capabilitiesLocked, false);
471
- _classPrivateFieldInitSpec(this, _handlersInstalled, false);
472
- _classPrivateFieldInitSpec(this, _legacyName, void 0);
473
- _classPrivateFieldInitSpec(this, _props, void 0);
474
- _classPrivateFieldSet2(_host, this, host);
475
- _classPrivateFieldSet2(_ctx, this, _classPrivateFieldGet2(_host, this).ctx);
476
- _classPrivateFieldSet2(_parentClassName, this, _classPrivateFieldGet2(_host, this).constructor.name);
477
- _classPrivateFieldSet2(_connectionManager, this, new ConnectionManager(_classPrivateFieldGet2(_ctx, this)));
478
- }
479
- /**
480
- * Install platform fetch, alarm, and hibernating WebSocket handlers.
481
- *
482
- * Existing handlers are preserved for framework-owned dispatch such as the
483
- * Agent's sub-agent router and alarm circuit breaker. Calling this method
484
- * more than once is an error.
485
- */
486
- installHandlers() {
487
- if (_classPrivateFieldGet2(_handlersInstalled, this)) throw new Error("Durable Object lifecycle handlers are already installed");
488
- _classPrivateFieldSet2(_handlersInstalled, this, true);
489
- const handlers = {
490
- fetch: this.fetch.bind(this),
491
- alarm: this.alarm.bind(this),
492
- webSocketMessage: this.webSocketMessage.bind(this),
493
- webSocketClose: this.webSocketClose.bind(this),
494
- webSocketError: this.webSocketError.bind(this)
495
- };
496
- for (const [name, handler] of Object.entries(handlers)) {
497
- if (name in _classPrivateFieldGet2(_host, this)) continue;
498
- Object.defineProperty(_classPrivateFieldGet2(_host, this), name, {
499
- value: handler,
500
- configurable: true
501
- });
502
- }
503
- }
504
- /**
505
- * Add a reusable capability before this lifecycle starts.
506
- *
507
- * @param capability - The capability to add in dispatch order.
508
- * @returns This lifecycle.
509
- */
510
- use(capability) {
511
- if (_classPrivateFieldGet2(_capabilitiesLocked, this)) throw new Error("Lifecycle capabilities must be added before startup");
512
- const capabilityId = lifecycleCapabilityId(capability);
513
- if (capabilityId && _classPrivateFieldGet2(_capabilities, this).some((candidate) => lifecycleCapabilityId(candidate) === capabilityId)) throw new Error(`Lifecycle capability ${JSON.stringify(capabilityId)} is already installed`);
514
- _classPrivateFieldGet2(_capabilities, this).push(capability);
515
- if (capability instanceof LifecycleCapability) bindLifecycleCapability(capability, _assertClassBrand(_Lifecycle_brand, this, _servicesForCapability).call(this, capability.capabilityId));
516
- return this;
517
- }
518
- /** @internal Deliver a generic capability envelope to this Lifecycle. */
519
- route(envelope) {
520
- return _assertClassBrand(_Lifecycle_brand, this, _dispatchRoute).call(this, envelope);
521
- }
522
- /**
523
- * Execute SQL queries against the Durable Object's database
524
- * @template T Type of the returned rows
525
- * @param strings SQL query template strings
526
- * @param values Values to be inserted into the query
527
- * @returns Array of query results
528
- */
529
- sql(strings, ...values) {
530
- let query = "";
531
- try {
532
- query = strings.reduce((acc, str, i) => acc + str + (i < values.length ? "?" : ""), "");
533
- return [..._classPrivateFieldGet2(_ctx, this).storage.sql.exec(query, ...values)];
534
- } catch (error) {
535
- console.error(`failed to execute sql query: ${query}`, error);
536
- throw error;
537
- }
538
- }
539
- /**
540
- * Handle an incoming request for the owning Durable Object.
541
- */
542
- async fetch(request) {
543
- try {
544
- const encodedProps = request.headers.get("x-agents-lifecycle-props");
545
- if (encodedProps) {
546
- _classPrivateFieldSet2(_props, this, decodeProps(encodedProps));
547
- request = mutableRequest(request);
548
- request.headers.delete("x-agents-lifecycle-props");
549
- }
550
- await _assertClassBrand(_Lifecycle_brand, this, _ensureInitialized).call(this);
551
- const url = new URL(request.url);
552
- if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") {
553
- const capabilityResponse = await runWithoutCurrentAgent(() => _classPrivateFieldGet2(_capabilityRunner, this).request({ request }));
554
- if (capabilityResponse !== void 0) return capabilityResponse;
555
- if (_classPrivateFieldGet2(_host, this).onRequest) return await runInLifecycleHostContext({
556
- host: _classPrivateFieldGet2(_host, this),
557
- request
558
- }, () => _classPrivateFieldGet2(_host, this).onRequest(request));
559
- return new Response("Not implemented", { status: 404 });
560
- } else {
561
- const { 0: clientWebSocket, 1: serverWebSocket } = new WebSocketPair();
562
- let connectionId = url.searchParams.get("_pk");
563
- if (!connectionId) connectionId = nanoid();
564
- let connection = Object.assign(serverWebSocket, {
565
- id: connectionId,
566
- uri: request.url,
567
- tags: [],
568
- state: null,
569
- setState(setState) {
570
- let state;
571
- if (setState instanceof Function) state = setState(this.state);
572
- else state = setState;
573
- this.state = state;
574
- return this.state;
575
- }
576
- });
577
- const ctx = { request };
578
- const tags = _classPrivateFieldGet2(_host, this).getConnectionTags ? await _classPrivateFieldGet2(_host, this).getConnectionTags(connection, ctx) : [];
579
- connection = _classPrivateFieldGet2(_connectionManager, this).accept(connection, { tags });
580
- await runInLifecycleHostContext({
581
- host: _classPrivateFieldGet2(_host, this),
582
- connection,
583
- request
584
- }, () => _classPrivateFieldGet2(_host, this).onConnect?.(connection, ctx));
585
- return new Response(null, {
586
- status: 101,
587
- webSocket: clientWebSocket
588
- });
589
- }
590
- } catch (err) {
591
- console.error(`Error in ${_classPrivateFieldGet2(_parentClassName, this)}:${_classPrivateFieldGet2(_ctx, this).id.name ?? "<unnamed>"} fetch:`, err);
592
- if (!(err instanceof Error)) throw err;
593
- if (request.headers.get("Upgrade") === "websocket") {
594
- const pair = new WebSocketPair();
595
- pair[1].accept();
596
- pair[1].send(JSON.stringify({ error: err.stack }));
597
- pair[1].close(1011, "Uncaught exception during session setup");
598
- return new Response(null, {
599
- status: 101,
600
- webSocket: pair[0]
601
- });
602
- } else return new Response(err.stack, { status: 500 });
603
- }
604
- }
605
- /** @internal Dispatch a hibernating WebSocket message. */
606
- async webSocketMessage(ws, message) {
607
- if (!isManagedWebSocket(ws)) return;
608
- try {
609
- const connection = createConnection(ws);
610
- await _assertClassBrand(_Lifecycle_brand, this, _ensureInitialized).call(this);
611
- return runInLifecycleHostContext({
612
- host: _classPrivateFieldGet2(_host, this),
613
- connection
614
- }, () => _classPrivateFieldGet2(_host, this).onMessage?.(connection, message));
615
- } catch (e) {
616
- console.error(`Error in ${_classPrivateFieldGet2(_parentClassName, this)}:${_classPrivateFieldGet2(_ctx, this).id.name ?? "<unnamed>"} webSocketMessage:`, e);
617
- }
618
- }
619
- /** @internal Dispatch and reciprocate a hibernating WebSocket close. */
620
- async webSocketClose(ws, code, reason, wasClean) {
621
- if (!isManagedWebSocket(ws)) return;
622
- try {
623
- const connection = createConnection(ws);
624
- await _assertClassBrand(_Lifecycle_brand, this, _ensureInitialized).call(this);
625
- await runInLifecycleHostContext({
626
- host: _classPrivateFieldGet2(_host, this),
627
- connection
628
- }, () => _classPrivateFieldGet2(_host, this).onClose?.(connection, code, reason, wasClean));
629
- } catch (e) {
630
- console.error(`Error in ${_classPrivateFieldGet2(_parentClassName, this)}:${_classPrivateFieldGet2(_ctx, this).id.name ?? "<unnamed>"} webSocketClose:`, e);
631
- } finally {
632
- closeQuietly(ws, code, reason);
633
- }
634
- }
635
- /** @internal Dispatch a hibernating WebSocket error. */
636
- async webSocketError(ws, error) {
637
- if (!isManagedWebSocket(ws)) return;
638
- if (isBenignTeardownError(ws, error)) return;
639
- try {
640
- const connection = createConnection(ws);
641
- await _assertClassBrand(_Lifecycle_brand, this, _ensureInitialized).call(this);
642
- return runInLifecycleHostContext({
643
- host: _classPrivateFieldGet2(_host, this),
644
- connection
645
- }, () => _classPrivateFieldGet2(_host, this).onError?.(connection, error));
646
- } catch (e) {
647
- console.error(`Error in ${_classPrivateFieldGet2(_parentClassName, this)}:${_classPrivateFieldGet2(_ctx, this).id.name ?? "<unnamed>"} webSocketError:`, e);
648
- }
649
- }
650
- /**
651
- * Start lifecycle capabilities and the owning Durable Object.
652
- *
653
- * Runtime fetch, alarm, and WebSocket entry points call this automatically.
654
- * RPC methods may call it explicitly because native RPC bypasses fetch.
655
- *
656
- * @param props - Optional properties supplied to capability and host startup.
657
- */
658
- async start(props) {
659
- if (props !== void 0) _classPrivateFieldSet2(_props, this, props);
660
- await _assertClassBrand(_Lifecycle_brand, this, _ensureInitialized).call(this);
661
- }
662
- /**
663
- * The name used to address this Durable Object.
664
- *
665
- * Native `ctx.id.name` is authoritative. A read-only legacy storage fallback
666
- * lets objects created by older PartyServer releases migrate without new
667
- * name writes.
668
- */
669
- get name() {
670
- const name = _classPrivateFieldGet2(_ctx, this).id.name ?? _classPrivateFieldGet2(_legacyName, this);
671
- if (name !== void 0) return name;
672
- throw new Error(`${_classPrivateFieldGet2(_parentClassName, this)} could not determine its Durable Object name. Address it with idFromName() or getByName(). In local development, update Wrangler/workerd and use a current compatibility_date. newUniqueId(), idFromString(), and names over 1,024 bytes do not expose ctx.id.name. Alarms created before 2026-03-15 must be rescheduled from a named fetch or RPC handler.`);
673
- }
674
- /** Send a message to all connected clients, except connection ids listed in `without` */
675
- broadcast(msg, without) {
676
- for (const connection of _classPrivateFieldGet2(_connectionManager, this).getConnections()) if (!without || !without.includes(connection.id)) _assertClassBrand(_Lifecycle_brand, this, _sendMessageToConnection).call(this, connection, msg);
677
- }
678
- /** Get a connection by connection id */
679
- getConnection(id) {
680
- return _classPrivateFieldGet2(_connectionManager, this).getConnection(id);
681
- }
682
- /** Get all managed connections, optionally filtered by tag. */
683
- getConnections(tag) {
684
- return _classPrivateFieldGet2(_connectionManager, this).getConnections(tag);
685
- }
686
- /**
687
- * Recompute the physical Durable Object alarm from every capability.
688
- *
689
- * Concurrent requests are serialized so a later durable-state change cannot
690
- * be overwritten by an earlier alarm calculation.
691
- */
692
- async rearmAlarm() {
693
- if (_classPrivateFieldGet2(_alarmsDisabled, this)) return;
694
- if (_classPrivateFieldGet2(_status, this) === "starting") {
695
- _classPrivateFieldSet2(_rearmRequestedDuringStart, this, true);
696
- return;
697
- }
698
- if (_classPrivateFieldGet2(_status, this) === "zero") await this.start();
699
- const next = _classPrivateFieldGet2(_alarmRearmQueue, this).catch(() => {}).then(async () => {
700
- if (_classPrivateFieldGet2(_alarmsDisabled, this)) return;
701
- const contributions = await runWithoutCurrentAgent(() => _classPrivateFieldGet2(_capabilityRunner, this).getAlarmContributions());
702
- const hostContribution = await runInLifecycleHostContext({ host: _classPrivateFieldGet2(_host, this) }, () => _classPrivateFieldGet2(_host, this).getNextAlarm?.());
703
- if (hostContribution !== void 0) contributions.push(hostContribution);
704
- const alarm = selectAlarm(contributions);
705
- if (alarm === null) await _classPrivateFieldGet2(_ctx, this).storage.deleteAlarm();
706
- else await _classPrivateFieldGet2(_ctx, this).storage.setAlarm(alarm);
707
- });
708
- _classPrivateFieldSet2(_alarmRearmQueue, this, next);
709
- await next;
710
- }
711
- /** Dispose installed capabilities in reverse registration order. */
712
- async dispose() {
713
- await runWithoutCurrentAgent(() => _classPrivateFieldGet2(_capabilityRunner, this).dispose());
714
- }
715
- /** Permanently disable and clear alarms during explicit object teardown. */
716
- async disableAlarms() {
717
- _classPrivateFieldSet2(_alarmsDisabled, this, true);
718
- await _classPrivateFieldGet2(_alarmRearmQueue, this).catch(() => {});
719
- await _classPrivateFieldGet2(_ctx, this).storage.deleteAlarm();
720
- }
721
- /** Dispatch lifecycle and host alarm callbacks after startup. */
722
- async alarm() {
723
- await _assertClassBrand(_Lifecycle_brand, this, _ensureInitialized).call(this);
724
- await runWithoutCurrentAgent(() => _classPrivateFieldGet2(_capabilityRunner, this).alarm());
725
- await runInLifecycleHostContext({ host: _classPrivateFieldGet2(_host, this) }, () => _classPrivateFieldGet2(_host, this).onAlarm?.());
726
- await this.rearmAlarm();
727
- }
728
- };
729
- function _servicesForCapability(capabilityId) {
730
- const lifecycle = this;
731
- const envelope = (payload) => ({
732
- capability: capabilityId,
733
- source: lifecycleRouteTransports.get(lifecycle)?.source,
734
- payload
735
- });
736
- return Object.freeze({
737
- storage: _classPrivateFieldGet2(_ctx, this).storage,
738
- ready: () => _assertClassBrand(_Lifecycle_brand, this, _readyForCapabilityOperation).call(this),
739
- starting: () => _classPrivateFieldGet2(_status, this) === "starting",
740
- alarms: Object.freeze({
741
- rearm: () => this.rearmAlarm(),
742
- disabled: () => _classPrivateFieldGet2(_alarmsDisabled, this)
743
- }),
744
- runInHostContext: async (fn) => _assertClassBrand(_Lifecycle_brand, this, _runInHostBoundary).call(this, fn),
745
- events: Object.freeze({ emit: (type, payload) => _assertClassBrand(_Lifecycle_brand, this, _emitCapabilityEvent).call(this, {
746
- source: capabilityId,
747
- type,
748
- payload
749
- }) }),
750
- routes: Object.freeze({
751
- get source() {
752
- return lifecycleRouteTransports.get(lifecycle)?.source;
753
- },
754
- toRoot: (payload) => {
755
- const transport = lifecycleRouteTransports.get(lifecycle);
756
- return transport ? transport.toRoot(envelope(payload)) : _assertClassBrand(_Lifecycle_brand, this, _dispatchRoute).call(this, envelope(payload));
757
- },
758
- to: (target, payload) => {
759
- const transport = lifecycleRouteTransports.get(lifecycle);
760
- if (!transport) throw new Error("Lifecycle has no transport for routed capabilities");
761
- return transport.to(target, envelope(payload));
762
- }
763
- })
764
- });
765
- }
766
- /**
767
- * Run a user callback inside the host invocation boundary — plain host
768
- * context by default, or the composition root's substitute (Agent installs
769
- * its tracing invocation scope).
770
- */
771
- function _runInHostBoundary(fn) {
772
- const boundary = lifecycleHostInvokers.get(this);
773
- return Promise.resolve(boundary ? boundary(fn) : runInLifecycleHostContext({ host: _classPrivateFieldGet2(_host, this) }, fn));
774
- }
775
- async function _readyForCapabilityOperation() {
776
- if (_classPrivateFieldGet2(_status, this) === "starting" || _classPrivateFieldGet2(_status, this) === "started") return;
777
- await this.start();
778
- }
779
- async function _dispatchRoute(envelope) {
780
- await _assertClassBrand(_Lifecycle_brand, this, _ensureInitialized).call(this);
781
- return runWithoutCurrentAgent(() => _classPrivateFieldGet2(_capabilityRunner, this).route(envelope.capability, {
782
- source: envelope.source,
783
- payload: envelope.payload
784
- }));
785
- }
786
- function _emitCapabilityEvent(event) {
787
- if (event.source.trim() === "" || event.type.trim() === "") throw new Error("Lifecycle events require non-empty source and type");
788
- if (_classPrivateFieldGet2(_status, this) !== "started") {
789
- _classPrivateFieldGet2(_pendingEvents, this).push(event);
790
- return;
791
- }
792
- _assertClassBrand(_Lifecycle_brand, this, _publishCapabilityEvent).call(this, event);
793
- }
794
- function _publishCapabilityEvent(event) {
795
- runWithoutCurrentAgent(() => {
796
- const sink = lifecycleEventSinks.get(this);
797
- try {
798
- if (!sink) {
799
- publishDiagnosticsEvent({
800
- source: event.source,
801
- type: event.type,
802
- agent: _classPrivateFieldGet2(_parentClassName, this),
803
- name: this.name,
804
- payload: event.payload,
805
- timestamp: Date.now()
806
- });
807
- return;
808
- }
809
- const pending = sink(event);
810
- if (pending !== void 0) _classPrivateFieldGet2(_ctx, this).waitUntil(Promise.resolve(pending).catch((error) => {
811
- _assertClassBrand(_Lifecycle_brand, this, _reportEventSinkFailure).call(this, event, error);
812
- }));
813
- } catch (error) {
814
- _assertClassBrand(_Lifecycle_brand, this, _reportEventSinkFailure).call(this, event, error);
815
- }
816
- });
817
- }
818
- function _reportEventSinkFailure(event, error) {
819
- console.error(`Lifecycle event sink failed for ${event.source}:${event.type}`, error);
820
- }
821
- function _deliverPendingEvents() {
822
- for (const event of _classPrivateFieldGet2(_pendingEvents, this).splice(0)) _assertClassBrand(_Lifecycle_brand, this, _publishCapabilityEvent).call(this, event);
823
- }
824
- async function _ensureInitialized() {
825
- if (_classPrivateFieldGet2(_status, this) === "started") return;
826
- if (_classPrivateFieldGet2(_ctx, this).id.name === void 0 && _classPrivateFieldGet2(_legacyName, this) === void 0) _classPrivateFieldSet2(_legacyName, this, await _classPrivateFieldGet2(_ctx, this).storage.get(LEGACY_NAME_STORAGE_KEY));
827
- this.name;
828
- _classPrivateFieldSet2(_capabilitiesLocked, this, true);
829
- let error;
830
- await _classPrivateFieldGet2(_ctx, this).blockConcurrencyWhile(async () => {
831
- _classPrivateFieldSet2(_status, this, "starting");
832
- try {
833
- await runWithoutCurrentAgent(() => _classPrivateFieldGet2(_capabilityRunner, this).start({ props: _classPrivateFieldGet2(_props, this) }));
834
- await runInLifecycleHostContext({ host: _classPrivateFieldGet2(_host, this) }, () => _classPrivateFieldGet2(_host, this).onStart?.(_classPrivateFieldGet2(_props, this)));
835
- _classPrivateFieldSet2(_status, this, "started");
836
- } catch (cause) {
837
- _classPrivateFieldSet2(_status, this, "zero");
838
- error = cause;
839
- }
840
- });
841
- if (error) {
842
- _classPrivateFieldSet2(_rearmRequestedDuringStart, this, false);
843
- _classPrivateFieldGet2(_pendingEvents, this).length = 0;
844
- throw error;
845
- }
846
- _assertClassBrand(_Lifecycle_brand, this, _deliverPendingEvents).call(this);
847
- if (_classPrivateFieldGet2(_rearmRequestedDuringStart, this)) {
848
- _classPrivateFieldSet2(_rearmRequestedDuringStart, this, false);
849
- await this.rearmAlarm();
850
- }
851
- }
852
- function _sendMessageToConnection(connection, message) {
853
- try {
854
- connection.send(message);
855
- } catch (_e) {
856
- connection.close(1011, "Unexpected error");
857
- }
858
- }
859
- //#endregion
860
- export { setLifecycleRouteTransport as i, setLifecycleEventSink as n, setLifecycleHostInvoker as r, Lifecycle as t };
861
-
862
- //# sourceMappingURL=durable-object-lifecycle-D6nNQJJd.js.map