agents 0.29.0 → 0.30.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 (35) hide show
  1. package/dist/browser/tools/pi.d.ts +6 -2
  2. package/dist/browser/tools/pi.js +6 -2
  3. package/dist/browser/tools/pi.js.map +1 -1
  4. package/dist/chat-sdk/index.js +1 -1
  5. package/dist/cli.js +46 -45
  6. package/dist/experimental/channels/web/index.js +1 -1
  7. package/dist/harness/container/index.js +1 -1
  8. package/dist/harness/opencode/index.js +1 -1
  9. package/dist/harness/pi/index.d.ts +57 -35
  10. package/dist/harness/pi/index.js +261 -119
  11. package/dist/harness/pi/index.js.map +1 -1
  12. package/dist/index.js +1 -1
  13. package/dist/lifecycle/index.js +1 -1
  14. package/dist/{lifecycle-ClT4DmF2.js → lifecycle-v1rKHV2C.js} +57 -17
  15. package/dist/lifecycle-v1rKHV2C.js.map +1 -0
  16. package/dist/mcp/index.js +1 -1
  17. package/dist/models/pi-ai/index.js +2 -2
  18. package/dist/models/pi-ai/index.js.map +1 -1
  19. package/dist/{src-6lr7MtM_.js → src-DfLzdwlK.js} +3 -3
  20. package/dist/{src-6lr7MtM_.js.map → src-DfLzdwlK.js.map} +1 -1
  21. package/dist/web/fetch/tools/pi.d.ts +10 -6
  22. package/dist/web/fetch/tools/pi.js +10 -6
  23. package/dist/web/fetch/tools/pi.js.map +1 -1
  24. package/dist/web/search/tools/pi.d.ts +10 -6
  25. package/dist/web/search/tools/pi.js +10 -6
  26. package/dist/web/search/tools/pi.js.map +1 -1
  27. package/dist/websockets/index.js +1 -1
  28. package/dist/{websockets-CqxnntmE.js → websockets-CyoeosdO.js} +2 -2
  29. package/dist/{websockets-CqxnntmE.js.map → websockets-CyoeosdO.js.map} +1 -1
  30. package/dist/workflows.js +1 -1
  31. package/docs/harnesses/pi.md +62 -28
  32. package/docs/lifecycle.md +7 -1
  33. package/docs/models-pi-ai.md +5 -1
  34. package/package.json +11 -6
  35. package/dist/lifecycle-ClT4DmF2.js.map +0 -1
@@ -11,10 +11,10 @@ Pi owns everything about a run: the transcript, the inbox of steers and follow-u
11
11
  ## Install the Pi packages
12
12
 
13
13
  ```sh
14
- npm install agents @earendil-works/pi-durable @earendil-works/pi-ai
14
+ npm install agents @earendil-works/pi-durable @earendil-works/pi-ai @earendil-works/chord
15
15
  ```
16
16
 
17
- Both Pi packages are optional peer dependencies of `agents`, at `~1.3.0`. pi-durable is experimental, and its API can change in minor releases, so `agents` supports one Pi minor at a time. The examples use Workers AI through the `AI` binding. To configure the binding and choose other models, refer to [Models for pi-ai](../models-pi-ai.md).
17
+ The three Pi packages are optional peer dependencies of `agents`, at `~1.4.0`. pi-durable is experimental, and its API can change in minor releases, so `agents` supports one Pi minor at a time. The examples use Workers AI through the `AI` binding. To configure the binding and choose other models, refer to [Models for pi-ai](../models-pi-ai.md).
18
18
 
19
19
  ## Create the harness
20
20
 
@@ -27,20 +27,17 @@ import { Agent } from "agents";
27
27
  import { PiHarness } from "agents/harness/pi";
28
28
  import { createAI } from "agents/models/pi-ai";
29
29
 
30
- // Skip Pi's idle caches (refer to the note below).
31
- const settings = { contextRetentionMs: 0, documentRetentionMs: 0 };
32
-
33
30
  export class Assistant extends Agent<Env> {
34
31
  ai = createAI({ binding: this.env.AI });
35
32
  registry = createRegistry();
36
33
 
37
34
  harness = new PiHarness({
38
- harness: ({ storage, context }) => {
35
+ harness: ({ storage, context, onWake }) => {
39
36
  const models = createModels();
40
37
  models.setProvider(this.ai.provider);
41
38
  return Harness.open(
42
39
  storage,
43
- { models, registry: this.registry, settings },
40
+ { models, registry: this.registry, onWake },
44
41
  context
45
42
  );
46
43
  },
@@ -61,14 +58,14 @@ export class Assistant extends Agent<Env> {
61
58
  }
62
59
  ```
63
60
 
64
- | Option | What it is |
65
- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
66
- | `harness` | Required. Receives `{ storage, context }` and returns Pi's `Harness`, usually from `Harness.open`. Models, the registry, `settings`, `env` and `onReport` are all yours to build here. |
67
- | `defaults` | What a new session starts with: `model`, a pi-ai `Model` such as `ai("@cf/…")`, and `thinkingLevel`. Without a model, a session's prompts end unanswered (`no_model`) until one is set. |
61
+ | Option | What it is |
62
+ | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
63
+ | `harness` | Required. Receives `{ storage, context, onWake }` and returns Pi's `Harness`, usually from `Harness.open`. Pass `onWake` to `Harness.open`, so the object can hibernate while Pi's tasks sleep (see [How recovery works](#how-recovery-works)). Models, the registry, `settings`, `env` and `onReport` are all yours to build here. |
64
+ | `defaults` | What a new session starts with: `model`, a pi-ai `Model` such as `ai("@cf/…")`, and `thinkingLevel`. Without a model, a session's prompts end unanswered (`no_model`) until one is set. |
68
65
 
69
- Set Pi's `contextRetentionMs` and `documentRetentionMs` settings to `0`. Pi keeps idle caches behind timers that default to ten minutes, and a pending timer keeps a Durable Object in memory: it cannot hibernate or be evicted, and it is billed for that time. The object's SQLite is local, so the caches save little.
66
+ Create the registry per object, as the `registry` field above does, not at module scope: Pi keeps every `Harness` subscribed to its registry until the `Harness` closes, and an evicted object never closes it.
70
67
 
71
- The factory runs as part of startup, once per isolate. If it throws the operation that triggered it fails and the next operation tries again.
68
+ The factory runs once per open: at startup, and again after a storage error (see [How recovery works](#how-recovery-works)), so keep it safe to run more than once. If it throws the operation that triggered it fails and the next operation tries again.
72
69
 
73
70
  A model in `defaults` or `session.setModel()` is stored by its provider and id only. Pi resolves it at each request against the `Models` the factory opened Pi with, so it must be a model those `Models` list. Options passed to `ai(id, options)` there, such as `fallback`, are not applied.
74
71
 
@@ -98,14 +95,18 @@ const wordCount: ToolRegistration<typeof WordCount> = {
98
95
  }
99
96
  };
100
97
 
101
- const registry = createRegistry();
102
- registry.install({
103
- name: "writing",
104
- sections: [
105
- { key: "preamble", render: () => "You are an editor.", tag: false }
106
- ],
107
- tools: [wordCount]
108
- });
98
+ // One per object, as a field: `registry = createWritingRegistry();`
99
+ function createWritingRegistry() {
100
+ const registry = createRegistry();
101
+ registry.install({
102
+ name: "writing",
103
+ sections: [
104
+ { key: "preamble", render: () => "You are an editor.", tag: false }
105
+ ],
106
+ tools: [wordCount]
107
+ });
108
+ return registry;
109
+ }
109
110
  ```
110
111
 
111
112
  - **Tool arguments are typed from the schema.** Type a tool as `ToolRegistration<typeof Parameters>`; a bare `ToolRegistration` types its arguments as `unknown`.
@@ -122,11 +123,11 @@ Pi's extensions can do more: hooks on model requests and tool calls (`hook(ToolT
122
123
  ```ts
123
124
  import { skills } from "agents/harness/pi";
124
125
 
125
- harness: async ({ storage, context }) => {
126
+ harness: async ({ storage, context, onWake }) => {
126
127
  this.registry.install(await skills(sources));
127
128
  return Harness.open(
128
129
  storage,
129
- { models, registry: this.registry, settings },
130
+ { models, registry: this.registry, onWake },
130
131
  context
131
132
  );
132
133
  };
@@ -144,7 +145,7 @@ import { browserTool } from "agents/browser/pi";
144
145
 
145
146
  readonly browser = new Browser({ provider: browserRun(this.env.BROWSER) });
146
147
 
147
- harness: async ({ storage, context }) => {
148
+ harness: async ({ storage, context, onWake }) => {
148
149
  this.registry.install({
149
150
  name: "browser",
150
151
  tools: [
@@ -153,7 +154,7 @@ harness: async ({ storage, context }) => {
153
154
  });
154
155
  return Harness.open(
155
156
  storage,
156
- { models, registry: this.registry, settings },
157
+ { models, registry: this.registry, onWake },
157
158
  context
158
159
  );
159
160
  };
@@ -189,14 +190,15 @@ const result = await session.wait(receipt.operationId);
189
190
  | `wait(operationId, signal?)` | The operation's result once Pi settles it. Aborting `signal` stops only the wait, not the work. |
190
191
  | `steer(input)` | `submit` with `whenBusy: "steer"`. |
191
192
  | `abort(operationId?)` | Withdraws a queued operation, or with no id, stops everything running in the session. |
192
- | `pending()` | Operations Pi has not settled yet: queued, or part of the running work. |
193
+ | `pending()` | Operations Pi has not settled yet: queued, part of the running work, or `parked` (see [How recovery works](#how-recovery-works)). |
194
+ | `retry()` | Runs again the tasks Pi's restart limit parked in the session's work. Resolves `false` when nothing was parked. |
193
195
  | `messages()` | Pi's transcript entries since the newest reset. |
194
196
  | `events()` | Pi's agent events: a `snapshot`, then one batch per commit. |
195
197
  | `reset(handoff?)` | Starts a new context, optionally from a handoff note. |
196
198
  | `setModel(model)` | Changes this session's model. |
197
199
  | `busy()` | Whether a run is going. |
198
200
 
199
- `harness.prompt()`, `submit()`, `wait()`, `abort()`, `messages()` and `pending()` act on the root session, or on `{ session }`. `harness.sessions` has `create()`, `fork(from)`, `get(id)` and `list()`, which includes sessions subagents created. `ROOT_SESSION` is the root's id.
201
+ `harness.prompt()`, `submit()`, `wait()`, `abort()`, `retry()`, `messages()` and `pending()` act on the root session, or on `{ session }`. `harness.sessions` has `create()`, `fork(from)`, `get(id)` and `list()`, which includes sessions subagents created. `ROOT_SESSION` is the root's id.
200
202
 
201
203
  `messages()` and `events()` are Pi's own records, not a UI-ready chat transcript. The example below folds them into one.
202
204
 
@@ -216,9 +218,41 @@ The kind is a label, not a permission. It records what your code said the input
216
218
 
217
219
  The example app folds the transcript into chat messages, ignores `kind` and `data`, and shows every input as a user message. To show labelled input differently, read them from the entry.
218
220
 
221
+ ### Inputs queued behind a failed run
222
+
223
+ A run fails with `model_error` when the model errors and Pi does not retry or the error outlasts its retries, and with `no_model` when the session has no usable model. Its own operation settles `unanswered` with that reason. Pi's `settings.afterFailedRun` decides what happens to the inputs queued behind it. Refer to [Failures and Recovery](https://github.com/earendil-works/pi/tree/main/packages/durable#failures-and-recovery) in the pi-durable README for what each value does. Set it in the factory:
224
+
225
+ ```ts
226
+ harness: ({ storage, context, onWake }) =>
227
+ Harness.open(
228
+ storage,
229
+ {
230
+ models,
231
+ registry: this.registry,
232
+ onWake,
233
+ settings: { afterFailedRun: "withdraw" }
234
+ },
235
+ context
236
+ );
237
+ ```
238
+
239
+ | Value | What callers see |
240
+ | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
241
+ | `keep` (default) | `pending()` lists the inputs as `queued`, `busy()` is `false`, and `wait()` keeps waiting. The next `submit()` runs them first, in order, then the new input. The next `reset()` runs them in the new context. |
242
+ | `continue` | `wait()` returns their results as usual. If the cause persists, such as a missing model, each queued input fails in its own run. |
243
+ | `withdraw` | `wait()` returns `{ status: "unanswered", reason: "run_failed" }`, and `pending()` no longer lists them. |
244
+
245
+ With `keep`, the kept inputs are not work to Pi: its `wake()` counts tasks, not queued inputs. The wake job completes, and the object can hibernate until the next `submit()` or `reset()`. Pass a `signal` to `wait()` if a caller should not wait that long. To withdraw a kept input, call `abort(operationId)`, which settles it `unanswered` with reason `aborted`. `session.abort()` with no id stops the whole session, which withdraws every kept input too.
246
+
219
247
  ## How recovery works
220
248
 
221
- The harness schedules one lifecycle job per session with work. The job waits on Pi's tasks, refreshes itself as a heartbeat while they run, and completes when they settle. If the object is evicted or crashes, the job is still due, so its alarm restarts the object. Pi reopens its stored state and resumes the session's work: a replay-safe tool call runs again, and an unsafe one is reported to the model as interrupted.
249
+ The harness schedules one lifecycle job, driven by Pi's `wake()`. While Pi has work running, the job waits on it and refreshes itself as a heartbeat. While Pi's tasks sleep, such as a retry backoff, the job is due when the first one wakes. Pi says when through the `onWake` the factory passes to `Harness.open`, and sets no in-memory timer of its own, so the object can hibernate until then. Without `onWake` the harness still works, but Pi's timer keeps the object in memory, and billed, while a task sleeps, and the harness logs a warning. When Pi has nothing to do, the job completes. If the object is evicted or crashes, the job is still due, so its alarm restarts the object. Pi reopens its stored state and resumes the session's work: a replay-safe tool call runs again, and an unsafe one is reported to the model as interrupted.
250
+
251
+ A task that keeps crashing the object would restart it forever, so Pi parks a task cut off by a crash or eviction `settings.restartLimit` times in a row (default 5) without progress. A parked task is not work: the job completes and the object can hibernate. Its operations show as `parked` in `pending()`, and `wait()` keeps waiting. If your factory passes `onReport` to `Harness.open`, Pi reports it there as `task_parked`. Once you have dealt with the cause, `session.retry()` runs it again and wakes the harness; `session.abort()` gives up on it instead.
252
+
253
+ A storage error closes Pi for good: the call that hit it rejects with the error, and calls and `events()` streams already underway end with Pi's `SessionFailed`, so retry them. If your factory passes `onReport` to `Harness.open`, Pi reports the failure there as `session_failed`. Once the failed Pi has closed, the harness opens Pi again, which runs the factory again, on the next call or the job's next step. Closing waits for running task code, such as a tool call, to return, so code that ignores its abort signal delays the reopen. Pi recovers from what it committed and resumes its work the same way.
254
+
255
+ If a step of the job fails, such as when the factory throws, the job is not dropped. It tries again after 30 seconds, doubling the delay with each failure in a row up to 10 minutes, and goes back to its usual schedule once a step succeeds. A Durable Object memory-limit reset that fails Pi while the job waits on it counts against the alarm's memory-limit circuit breaker. Lifecycle backs the job off and drops it after repeated resets. The next call opens Pi again and pushes the job again, so Pi's restart limit is what eventually parks a task that keeps causing resets.
222
256
 
223
257
  Every operation waits for the object's startup, which runs the factory. A call over RPC that arrives first waits for it rather than opening Pi on its own.
224
258
 
package/docs/lifecycle.md CHANGED
@@ -234,7 +234,13 @@ physical alarm automatically — there is no explicit rearm call. When the
234
234
  alarm fires, Lifecycle drives due jobs in due order as an event loop, then
235
235
  runs host `onAlarm()`, then re-arms from queue state. Before driving any job
236
236
  it arms a deadman pre-alarm so an isolate death mid-drive still wakes the
237
- object to resume.
237
+ object to resume. While the queue holds jobs, it also arms a fallback alarm
238
+ before startup runs, at the next job's time but at least 30 seconds out. An
239
+ alarm whose startup throws still leaves that wake, whether or not the
240
+ platform's own alarm retries run, so the failed startup is retried then. A
241
+ startup that pushes or reschedules jobs and then throws, from an alarm or a
242
+ request, arms the same fallback from the queue as it stands, so those jobs
243
+ keep a wake too.
238
244
 
239
245
  A job's drive result decides what happens next: returning nothing completes
240
246
  and deletes it, `{ rescheduleAt }` suspends it until a future time, and
@@ -166,6 +166,10 @@ A session stores its model as `{ provider, modelId }`, not as a model object, so
166
166
  `@cf/…` and `<provider>/<id>` forms there. Options given to `ai(model, options)` do not reach a
167
167
  session; set them on `createAI` instead.
168
168
 
169
+ A model stream that is cut off, or that sends nothing for `streamIdleTimeoutMs`, ends in an error
170
+ pi-ai's `isRetryableAssistantError()` treats as transient, so the harness retries the turn under
171
+ its retry settings rather than failing it.
172
+
169
173
  `ai.streamFn` is `streamSimple`, bound, for frameworks that take a stream function, such as
170
174
  pi-agent-core's `Agent({ streamFn })`.
171
175
 
@@ -366,7 +370,7 @@ Every other model in the catalog takes the full set.
366
370
 
367
371
  ## Beta
368
372
 
369
- This subpath needs `@earendil-works/pi-ai@~1.3.0`, an optional peer of `agents`. `agents`
373
+ This subpath needs `@earendil-works/pi-ai@~1.4.0`, an optional peer of `agents`. `agents`
370
374
  takes no vendor package as a dependency, optional or otherwise. The surface is in beta
371
375
  and may change in a minor release. An unlisted `@cf/` id resolves with default metadata (a
372
376
  128k context window, 8192 output tokens, zero cost); pass overrides when you know better.
package/package.json CHANGED
@@ -12,7 +12,7 @@
12
12
  "bin": {
13
13
  "agents": "./dist/cli.js"
14
14
  },
15
- "version": "0.29.0",
15
+ "version": "0.30.0",
16
16
  "license": "MIT",
17
17
  "repository": {
18
18
  "directory": "packages/agents",
@@ -43,9 +43,10 @@
43
43
  "@ai-sdk/react": "^4.0.0",
44
44
  "@ai-sdk/valibot": "3.0.6",
45
45
  "@cloudflare/codemode": "^0.5.5",
46
- "@earendil-works/pi-ai": "~1.3.0",
47
- "@earendil-works/pi-durable": "~1.3.0",
48
- "@earendil-works/pi-tui": "1.3.0",
46
+ "@earendil-works/chord": "~1.4.0",
47
+ "@earendil-works/pi-ai": "~1.4.0",
48
+ "@earendil-works/pi-durable": "~1.4.0",
49
+ "@earendil-works/pi-tui": "1.4.0",
49
50
  "@modelcontextprotocol/client": "2.3.1",
50
51
  "@modelcontextprotocol/conformance-v2": "npm:@modelcontextprotocol/conformance@0.2.0-alpha.12",
51
52
  "@modelcontextprotocol/sdk": "1.32.1",
@@ -71,8 +72,9 @@
71
72
  "@ai-sdk/provider": "^4.0.0",
72
73
  "@ai-sdk/react": "^3.0.0 || ^4.0.0",
73
74
  "@cloudflare/codemode": ">=0.5.0",
74
- "@earendil-works/pi-ai": "~1.3.0",
75
- "@earendil-works/pi-durable": "~1.3.0",
75
+ "@earendil-works/chord": "~1.4.0",
76
+ "@earendil-works/pi-ai": "~1.4.0",
77
+ "@earendil-works/pi-durable": "~1.4.0",
76
78
  "@modelcontextprotocol/client": "2.3.1",
77
79
  "@modelcontextprotocol/sdk": "1.32.1",
78
80
  "@modelcontextprotocol/server": "2.3.1",
@@ -98,6 +100,9 @@
98
100
  "@cloudflare/codemode": {
99
101
  "optional": true
100
102
  },
103
+ "@earendil-works/chord": {
104
+ "optional": true
105
+ },
101
106
  "@earendil-works/pi-ai": {
102
107
  "optional": true
103
108
  },
@@ -1 +0,0 @@
1
- {"version":3,"file":"lifecycle-ClT4DmF2.js","names":[],"sources":["../src/lifecycle/capability-runner.ts","../src/lifecycle/abort.ts","../src/lifecycle/job-queue.ts","../src/lifecycle/job-driver.ts","../src/lifecycle/transport-errors.ts","../src/lifecycle/durable-object-lifecycle.ts"],"sourcesContent":["import { lifecycleCapabilityId } from \"./capability\";\nimport type { LifecycleRouteContext } from \"./capability\";\nimport type { WSMessage } from \"./types\";\nimport type {\n LifecycleJob,\n LifecycleJobContext,\n LifecycleJobOutcome\n} from \"./job-queue\";\n\ntype MaybePromise<T> = T | Promise<T>;\n\n/** One best-effort event published by a Lifecycle capability. */\nexport type LifecycleEvent = {\n /** Stable capability or subsystem name. */\n readonly source: string;\n /** Stable event name within that source. */\n readonly type: string;\n /** Event-specific data. */\n readonly payload: unknown;\n};\n\n/** Terminal sink for best-effort Lifecycle events. */\nexport type LifecycleEventSink = (\n event: LifecycleEvent\n) => void | Promise<void>;\n\n/** Context supplied when durable capabilities start. */\nexport type CapabilityStartContext<Props extends object = object> = {\n /** Properties supplied while resolving the Durable Object. */\n readonly props: Props | undefined;\n};\n\n/** Context supplied when durable capabilities inspect an HTTP request. */\nexport type CapabilityRequestContext = {\n /** The request entering the Durable Object. */\n readonly request: Request;\n};\n\n/** Context supplied when a capability inspects a WebSocket upgrade. */\nexport type CapabilityWebSocketUpgradeContext = {\n /** The WebSocket upgrade request entering the Durable Object. */\n readonly request: Request;\n};\n\n/**\n * Context supplied when the alarm memory-limit circuit breaker records a\n * strike (#1825), to capabilities and the host alike.\n */\nexport type MemoryLimitContext = {\n /** Whether the breaker hit its strike budget and sealed recovery work. */\n readonly sealed: boolean;\n /** The backoff wake time (epoch ms) armed for an unsealed strike. */\n readonly nextTime?: number;\n /**\n * The queue job that was executing when the strike landed. Absent when the\n * reset happened during startup or host alarm work. Lifecycle has already\n * backed off or purged its row before invoking memory-limit policy.\n *\n * Capabilities whose durable state outlives their queue row use this to\n * apply the same policy to the underlying work — Tasks routes a struck\n * routed job's owner this way (see `setTaskRoutedMemoryLimitHandler`).\n */\n readonly executing?: LifecycleJob;\n /**\n * Recovery-loop jobs removed when this strike sealed the breaker. This is\n * a pre-purge snapshot because the durable rows no longer exist when\n * policy hooks run. No current capability reads this — Scheduler's own\n * former use of it (routing a sealed strike to every purged row's owning\n * dynamic agent) was retired once Tasks took over routed chat-recovery\n * wakes — but it stays available for a capability whose routed rows can\n * be purged as a pack, unlike Tasks' one-run-at-a-time model.\n */\n readonly purgedRecoveryLoopJobs?: ReadonlyArray<LifecycleJob>;\n};\n\n/**\n * A capability installed into a Durable Object lifecycle.\n *\n * Capabilities extending `LifecycleCapability` receive the standard storage,\n * readiness, alarm, event, and routing surface. Host-specific bindings and\n * protocol adapters remain explicit constructor dependencies. Hook parameters\n * carry only phase data; hooks do not run in ambient host context — a\n * capability-held user callback re-enters host context exactly once,\n * through `LifecycleServices.runInHostContext(fn, scope)`.\n *\n * A capability interacts with Lifecycle through exactly three channels:\n * these declared hooks, the `LifecycleServices` surface, and\n * composition-root `set*()` apertures. Any other direct reach in either\n * direction is a design smell.\n *\n * Dispatch contract, hook by hook:\n * - `onRequest` and `onWebSocketUpgrade` are offered in declaration\n * order, the catch-all last; the first capability to return a `Response`\n * claims the request, and a claimed upgrade's socket belongs to that\n * capability for its whole lifetime.\n * - `onWebSocketMessage`/`onWebSocketClose`/`onWebSocketError` are\n * platform wakes, offered in declaration order; return `true` to\n * consume one. Socket ownership is the capability's to determine —\n * keep a private hibernation-attachment namespace and recognize your\n * own sockets by it.\n * - `onRoute` is addressed to one capability by its id; `onJob` is\n * addressed by the due job's owning capability, with Lifecycle owning\n * the queue and the one physical alarm.\n */\nexport interface DurableObjectCapability<Props extends object = object> {\n /**\n * How this capability claims traffic. Default: `\"selective\"`.\n *\n * A `\"selective\"` capability answers only requests and upgrades it\n * recognizes and declines the rest. A `\"catch-all\"` claims everything\n * offered to the hooks it implements, so Lifecycle always places it\n * last, whenever it was installed, and refuses a second catch-all for\n * the same hook. Catch-alls for disjoint hooks coexist: `WebSockets`\n * claims every upgrade and implements no `onRequest`, so an HTTP\n * catch-all installs beside it. Selective HTTP capabilities target\n * their own routes and run before either.\n */\n readonly claims?: \"selective\" | \"catch-all\";\n\n /** Initialize or recover the capability before the host handles work. */\n onStart?(context: CapabilityStartContext<Props>): MaybePromise<void>;\n\n /**\n * Act as middleware over HTTP requests, ahead of the host's request handler.\n *\n * Return a response to handle the request, or `undefined` to pass it to the\n * next capability and finally the host.\n */\n onRequest?(\n context: CapabilityRequestContext\n ): MaybePromise<Response | undefined | void>;\n\n /**\n * Claim a WebSocket upgrade before the host's legacy connection path.\n *\n * A capability that returns a response owns that socket and its lifetime,\n * including any hibernation attachment it needs to recognize the socket\n * later. Return `undefined` to decline.\n */\n onWebSocketUpgrade?(\n context: CapabilityWebSocketUpgradeContext\n ): MaybePromise<Response | undefined | void>;\n\n /**\n * Handle a platform `webSocketMessage` wake for a socket this capability\n * owns. Return `true` to consume the event; anything else offers it to\n * the next capability and finally the host's legacy path. Ownership is\n * the capability's to determine — typically via its own hibernation\n * attachment namespace.\n */\n onWebSocketMessage?(\n ws: WebSocket,\n message: WSMessage\n ): MaybePromise<boolean | void>;\n\n /** Handle a platform `webSocketClose` wake for an owned socket. */\n onWebSocketClose?(\n ws: WebSocket,\n code: number,\n reason: string,\n wasClean: boolean\n ): MaybePromise<boolean | void>;\n\n /** Handle a platform `webSocketError` wake for an owned socket. */\n onWebSocketError?(\n ws: WebSocket,\n error: unknown\n ): MaybePromise<boolean | void>;\n\n /**\n * Drive one due job this capability pushed into the Lifecycle queue.\n * Return an outcome to reschedule or retain the job; returning nothing\n * completes it.\n *\n * Dispatch must be bounded: the event loop awaits each job inline, so a\n * long-running `onJob` delays every other job on this object. Detach\n * unbounded work (start it, keep durable evidence, return) instead of\n * awaiting it here; a dispatch that outlives the job's hung timeout\n * logs a warning and emits `job:slow_dispatch`.\n */\n onJob?(\n context: LifecycleJobContext\n ): MaybePromise<LifecycleJobOutcome | void>;\n\n /**\n * Observe one job's terminal application failure after retry exhaustion.\n * The returned outcome decides advancement; returning nothing completes\n * the job.\n */\n onJobError?(\n context: LifecycleJobContext,\n error: unknown\n ): MaybePromise<LifecycleJobOutcome | void>;\n\n /**\n * Apply domain policy after the alarm memory-limit circuit breaker\n * records a strike (#1825). Lifecycle has already handled the queue: the\n * executing job and every `recoveryLoop`-flagged job are backed off (or\n * purged when `sealed`). Runs at the outermost alarm frame, post-unwind,\n * best-effort — the isolate resets right after, so keep writes small.\n */\n onMemoryLimit?(context: MemoryLimitContext): MaybePromise<void>;\n\n /** Handle one message routed to this capability identity. */\n onRoute?(context: LifecycleRouteContext): MaybePromise<unknown>;\n\n /** Release live or in-memory resources during explicit host destruction. */\n dispose?(): MaybePromise<void>;\n}\n\n/**\n * Runs ordered lifecycle phases for capabilities installed in a Durable Object.\n *\n * Capabilities are resolved lazily on the first phase and retained for the\n * lifetime of this runner. Startup runs in declaration order.\n * Requests dispatch as a middleware chain: the first capability to return a\n * response handles the request.\n */\nexport class CapabilityRunner<Props extends object = object> {\n readonly #resolveCapabilities: () => Iterable<DurableObjectCapability<Props>>;\n\n #capabilities: ReadonlyArray<DurableObjectCapability<Props>> | undefined;\n #startPromise: Promise<void> | undefined;\n #started = false;\n\n /**\n * Create a lifecycle whose capabilities are resolved immediately before the\n * first phase.\n *\n * @param resolveCapabilities - Returns capabilities in their startup order.\n */\n constructor(\n resolveCapabilities: () => Iterable<DurableObjectCapability<Props>>\n ) {\n this.#resolveCapabilities = resolveCapabilities;\n }\n\n /**\n * Start every capability sequentially.\n *\n * Concurrent callers share one startup attempt. A failed attempt is not\n * cached, allowing the host to retry its complete startup phase.\n *\n * @param context - Properties supplied while resolving the Durable Object.\n */\n async start(context: CapabilityStartContext<Props>): Promise<void> {\n if (this.#started) return;\n\n const pending = this.#startPromise;\n if (pending) {\n await pending;\n return;\n }\n\n const attempt = this.#runStart(context);\n this.#startPromise = attempt;\n try {\n await attempt;\n } catch (error) {\n if (this.#startPromise === attempt) {\n this.#startPromise = undefined;\n }\n throw error;\n }\n }\n\n /**\n * Offer a request to each capability middleware in registration order.\n *\n * @param context - The request entering the Durable Object.\n * @returns The first capability response, or `undefined` when no\n * capability claimed the request.\n */\n async request(\n context: CapabilityRequestContext\n ): Promise<Response | undefined> {\n await this.#ensureReady(\"handle a request\");\n for (const capability of this.#getCapabilities()) {\n const response = await capability.onRequest?.(context);\n if (response !== undefined) return response;\n }\n return undefined;\n }\n\n /**\n * Offer a WebSocket upgrade to each capability in declaration order.\n *\n * @param context - The upgrade request entering the Durable Object.\n * @returns The first capability response, or `undefined` when unclaimed.\n */\n async webSocketUpgrade(\n context: CapabilityWebSocketUpgradeContext\n ): Promise<Response | undefined> {\n await this.#ensureReady(\"handle a WebSocket upgrade\");\n for (const capability of this.#getCapabilities()) {\n const response = await capability.onWebSocketUpgrade?.(context);\n if (response !== undefined) return response;\n }\n return undefined;\n }\n\n /**\n * Offer a platform `webSocketMessage` wake to each capability in\n * declaration order.\n *\n * @returns Whether a capability consumed the event.\n */\n async webSocketMessage(ws: WebSocket, message: WSMessage): Promise<boolean> {\n await this.#ensureReady(\"handle a WebSocket message\");\n for (const capability of this.#getCapabilities()) {\n if ((await capability.onWebSocketMessage?.(ws, message)) === true) {\n return true;\n }\n }\n return false;\n }\n\n /** Offer a platform `webSocketClose` wake to each capability. */\n async webSocketClose(\n ws: WebSocket,\n code: number,\n reason: string,\n wasClean: boolean\n ): Promise<boolean> {\n await this.#ensureReady(\"handle a WebSocket close\");\n for (const capability of this.#getCapabilities()) {\n if (\n (await capability.onWebSocketClose?.(ws, code, reason, wasClean)) ===\n true\n ) {\n return true;\n }\n }\n return false;\n }\n\n /** Offer a platform `webSocketError` wake to each capability. */\n async webSocketError(ws: WebSocket, error: unknown): Promise<boolean> {\n await this.#ensureReady(\"handle a WebSocket error\");\n for (const capability of this.#getCapabilities()) {\n if ((await capability.onWebSocketError?.(ws, error)) === true) {\n return true;\n }\n }\n return false;\n }\n\n /** Find one installed capability by its stable id. */\n async findById(\n capabilityId: string\n ): Promise<DurableObjectCapability<Props> | undefined> {\n await this.#ensureReady(\"dispatch capability work\");\n return this.#getCapabilities().find(\n (candidate) => lifecycleCapabilityId(candidate) === capabilityId\n );\n }\n\n /** Route one message to an installed named capability. */\n async route(\n capabilityId: string,\n context: LifecycleRouteContext\n ): Promise<unknown> {\n await this.#ensureReady(\"route a capability message\");\n const capability = this.#getCapabilities().find(\n (candidate) => lifecycleCapabilityId(candidate) === capabilityId\n );\n if (!capability?.onRoute) {\n throw new Error(\n `Lifecycle capability ${JSON.stringify(capabilityId)} cannot receive routed messages`\n );\n }\n return capability.onRoute(context);\n }\n\n /**\n * Offer a memory-limit strike to every capability, best-effort.\n *\n * Deliberately not gated on startup: a strike can land while startup\n * itself is the work that exceeded the memory limit, and the breaker's\n * policy must still reach capabilities. One capability's failure does not\n * stop the next — the isolate is about to reset either way.\n */\n async memoryLimit(context: MemoryLimitContext): Promise<void> {\n for (const capability of this.#getCapabilities()) {\n try {\n await capability.onMemoryLimit?.(context);\n } catch (error) {\n console.error(\"Lifecycle capability memory-limit policy failed\", error);\n }\n }\n }\n\n /** Dispose installed capabilities in reverse registration order. */\n async dispose(): Promise<void> {\n for (const capability of [...this.#getCapabilities()].reverse()) {\n try {\n await capability.dispose?.();\n } catch (error) {\n console.error(\"Lifecycle capability disposal failed\", error);\n }\n }\n }\n\n async #runStart(context: CapabilityStartContext<Props>): Promise<void> {\n for (const capability of this.#getCapabilities()) {\n await capability.onStart?.(context);\n }\n this.#started = true;\n }\n\n async #ensureReady(operation: string): Promise<void> {\n const pending = this.#startPromise;\n if (pending) await pending;\n if (!this.#started) {\n throw new Error(\n `Cannot ${operation} before the Durable Object lifecycle has started`\n );\n }\n }\n\n #getCapabilities(): ReadonlyArray<DurableObjectCapability<Props>> {\n if (!this.#capabilities) {\n this.#capabilities = Object.freeze([...this.#resolveCapabilities()]);\n }\n return this.#capabilities;\n }\n}\n","/**\n * Reset the Durable Object instance without the platform retrying the alarm\n * this invocation was handling. Never returns: `abort()` terminates\n * execution.\n *\n * `retryAlarm: false` only matters inside an alarm handler (workerd\n * `EXCEPTION_DURABLE_OBJECT_ABORT_NO_RETRY`). Runtimes older than the option\n * ignore the extra argument, so passing it is always safe.\n */\nexport function abortWithoutAlarmRetry(\n ctx: DurableObjectState,\n reason: string\n): void {\n ctx.abort(reason, { retryAlarm: false });\n}\n","/**\n * Durable job queue owned by Lifecycle.\n *\n * One timestamp-ordered table holds every pending job for the Durable\n * Object. A job is a serialisable callback address — owning capability plus\n * function name — with a due time and a payload. Capabilities and the host\n * push jobs through their scoped `LifecycleJobs` surface; Lifecycle's alarm\n * event loop drives due jobs and derives the physical alarm from queue\n * state. Payloads are opaque to the queue.\n */\n\nimport { nanoid } from \"nanoid\";\nimport type { RetryOptions } from \"../retries\";\nimport { SqlError } from \"../sql-error\";\n\n/** Capability id under which host-owned jobs are stored. */\nexport const HOST_JOB_CAPABILITY = \"host\";\n\n/** Seconds before an in-flight single-flight job is treated as hung. */\nconst DEFAULT_HUNG_TIMEOUT_SECONDS = 30;\n\n/** One durable job in the Lifecycle queue. */\nexport type LifecycleJob = {\n /** Unique job id. Stable across reschedules. */\n readonly id: string;\n /** Owning capability id, or `\"host\"`. */\n readonly capability: string;\n /** Serialisable function name the owner dispatches on. */\n readonly fn: string;\n /** Due time in epoch milliseconds. */\n readonly time: number;\n /** Owner-defined payload, JSON round-tripped. */\n readonly payload: unknown;\n /** Retry policy for dispatch, when the pusher supplied one. */\n readonly retry: RetryOptions | undefined;\n /** Whether the job is skipped while a previous run is in flight. */\n readonly singleflight: boolean;\n /** Whether the job suppresses ordinary alarm candidates while pending. */\n readonly exclusive: boolean;\n /** Whether the alarm memory-limit breaker governs this pending job (#1825). */\n readonly recoveryLoop: boolean;\n /** Creation time in epoch seconds. */\n readonly createdAt: number;\n};\n\n/** Options accepted when pushing one job. */\nexport type LifecycleJobPushOptions = {\n /** Serialisable function name the owner dispatches on. */\n readonly fn: string;\n /** Due time in epoch milliseconds. */\n readonly time: number;\n /** Owner-defined payload. Must be JSON-serializable. */\n readonly payload?: unknown;\n /**\n * Stable job id. A push with an existing id replaces that job.\n * Omitted ids are generated.\n */\n readonly id?: string;\n /** Retry policy for dispatch, overriding the queue default. */\n readonly retry?: RetryOptions;\n /** Skip this job while a previous run of it is still in flight. */\n readonly singleflight?: boolean;\n /**\n * Seconds before an in-flight single-flight run is treated as hung, and\n * before any long dispatch triggers the slow-dispatch warning. Default: 30.\n */\n readonly hungTimeoutSeconds?: number;\n /** Suppress ordinary alarm candidates while this job is pending. */\n readonly exclusive?: boolean;\n /**\n * Mark this job as part of a recovery loop that can deterministically\n * exhaust memory. On an alarm memory-limit strike the circuit breaker\n * (#1825) backs off every pending flagged job to the strike's backoff\n * time, and purges them all when it seals at the strike budget — so a\n * doomed loop cannot re-trigger through a sibling row while unrelated\n * jobs stay untouched.\n */\n readonly recoveryLoop?: boolean;\n};\n\n/**\n * What the owner tells Lifecycle after one job ran — the drive result.\n *\n * `undefined` (or no return) completes the job and deletes it.\n * `{ rescheduleAt }` suspends the job until a future time.\n * `\"yield\"` leaves the job due, waking again immediately.\n *\n * A same-id `push()` or `reschedule()` made while the job is dispatching\n * supersedes the drive result: the newer durable intent wins, and the\n * result is quietly discarded. Owners that both push and return outcomes\n * for the same job should derive both from the same durable state so the\n * two always agree.\n */\nexport type LifecycleJobOutcome =\n | undefined\n | { readonly rescheduleAt: number }\n | \"yield\";\n\n/** Context supplied when a job is dispatched to its owner. */\nexport type LifecycleJobContext = {\n /** The due job being executed. */\n readonly job: LifecycleJob;\n /** 1-indexed dispatch attempt within the current alarm invocation. */\n readonly attempt: number;\n};\n\n/** Job-queue access scoped to one owning capability. */\nexport type LifecycleJobs = {\n /**\n * Push one job. A push with an existing id replaces that job — ids are\n * scoped to their owner, so replacing (or colliding with) another\n * owner's job is impossible; a cross-owner id collision throws instead.\n */\n readonly push: (options: LifecycleJobPushOptions) => Promise<LifecycleJob>;\n /** Cancel one owned job. Returns false when no job matched. */\n readonly cancel: (id: string) => Promise<boolean>;\n /** Re-time one owned job. Returns false when no job matched. */\n readonly reschedule: (id: string, time: number) => Promise<boolean>;\n /** Read one owned job. */\n readonly get: (id: string) => LifecycleJob | undefined;\n /** List every owned job, ordered by due time. */\n readonly list: () => LifecycleJob[];\n /**\n * Recompute the physical alarm from queue state without mutating it.\n * Mutations re-arm automatically; use this only to recover a lost alarm\n * for existing jobs (e.g. an idempotent push that deduplicated).\n */\n readonly rearm: () => Promise<void>;\n};\n\n/** @internal Raw `cf_agents_jobs` SQLite row. */\nexport type JobStorageRow = {\n id: string;\n capability: string;\n fn: string;\n time: number;\n payload: string | null;\n retry_options: string | null;\n singleflight: number;\n hung_timeout_seconds: number | null;\n exclusive: number;\n recovery_loop: number;\n running: number;\n execution_started_at: number | null;\n created_at: number;\n};\n\n/** @internal Convert one raw queue row into its public job shape. */\nexport function jobFromRow(row: JobStorageRow): LifecycleJob {\n return {\n id: row.id,\n capability: row.capability,\n fn: row.fn,\n time: row.time,\n payload:\n typeof row.payload === \"string\" ? JSON.parse(row.payload) : undefined,\n retry:\n typeof row.retry_options === \"string\"\n ? (JSON.parse(row.retry_options) as RetryOptions)\n : undefined,\n singleflight: row.singleflight === 1,\n exclusive: row.exclusive === 1,\n recoveryLoop: row.recovery_loop === 1,\n createdAt: row.created_at\n };\n}\n\n/** @internal One row's hung/slow-dispatch threshold in milliseconds. */\nexport function hungTimeoutMs(row: JobStorageRow): number {\n return (row.hung_timeout_seconds ?? DEFAULT_HUNG_TIMEOUT_SECONDS) * 1000;\n}\n\n/** Whether an in-flight single-flight job has crossed its hung timeout. */\nexport function isHungRow(row: JobStorageRow, nowMs: number): boolean {\n return nowMs - (row.execution_started_at ?? 0) >= hungTimeoutMs(row);\n}\n\n/**\n * @internal SQL-backed job queue. Lifecycle owns the single instance; the\n * scoped `LifecycleJobs` surfaces delegate here with a fixed capability id.\n */\nexport class JobQueue {\n readonly #storage: DurableObjectStorage;\n #tableEnsured = false;\n\n constructor(storage: DurableObjectStorage) {\n this.#storage = storage;\n }\n\n #sql<T = JobStorageRow>(\n query: string,\n ...params: (string | number | null)[]\n ): T[] {\n this.#ensureTable();\n try {\n return [...this.#storage.sql.exec(query, ...params)] as T[];\n } catch (cause) {\n throw new SqlError(query, cause);\n }\n }\n\n #ensureTable(): void {\n if (this.#tableEnsured) return;\n this.#storage.sql.exec(`\n CREATE TABLE IF NOT EXISTS cf_agents_jobs (\n id TEXT PRIMARY KEY NOT NULL,\n capability TEXT NOT NULL,\n fn TEXT NOT NULL,\n time INTEGER NOT NULL,\n payload TEXT,\n retry_options TEXT,\n singleflight INTEGER NOT NULL DEFAULT 0,\n hung_timeout_seconds INTEGER,\n exclusive INTEGER NOT NULL DEFAULT 0,\n recovery_loop INTEGER NOT NULL DEFAULT 0,\n running INTEGER NOT NULL DEFAULT 0,\n execution_started_at INTEGER,\n created_at INTEGER NOT NULL DEFAULT (unixepoch())\n ) WITHOUT ROWID`);\n this.#tableEnsured = true;\n }\n\n push(capability: string, options: LifecycleJobPushOptions): LifecycleJob {\n if (!Number.isFinite(options.time) || options.time < 0) {\n throw new Error(`Invalid job time: ${String(options.time)}`);\n }\n if (typeof options.fn !== \"string\" || options.fn.trim() === \"\") {\n throw new Error(\"Jobs require a non-empty fn\");\n }\n const id = options.id ?? nanoid(9);\n // Job ids are scoped to their owner, like every other queue verb: a\n // same-id push replaces only the pusher's own job (the conflict update\n // is a no-op against another owner's row, surfaced as the ownership\n // error below), and it clears any in-flight dispatch marker so this\n // newer durable intent wins over a concurrently returned drive result.\n this.#sql(\n `INSERT INTO cf_agents_jobs\n (id, capability, fn, time, payload, retry_options, singleflight,\n hung_timeout_seconds, exclusive, recovery_loop, running,\n execution_started_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, NULL)\n ON CONFLICT(id) DO UPDATE SET\n fn = excluded.fn,\n time = excluded.time,\n payload = excluded.payload,\n retry_options = excluded.retry_options,\n singleflight = excluded.singleflight,\n hung_timeout_seconds = excluded.hung_timeout_seconds,\n exclusive = excluded.exclusive,\n recovery_loop = excluded.recovery_loop,\n running = 0,\n execution_started_at = NULL\n WHERE cf_agents_jobs.capability = excluded.capability`,\n id,\n capability,\n options.fn,\n Math.floor(options.time),\n options.payload === undefined ? null : JSON.stringify(options.payload),\n options.retry ? JSON.stringify(options.retry) : null,\n options.singleflight ? 1 : 0,\n options.hungTimeoutSeconds ?? null,\n options.exclusive ? 1 : 0,\n options.recoveryLoop ? 1 : 0\n );\n const job = this.get(capability, id);\n if (!job) {\n const owner = this.#sql<{ capability: string }>(\n \"SELECT capability FROM cf_agents_jobs WHERE id = ?\",\n id\n )[0]?.capability;\n throw new Error(\n owner !== undefined\n ? `Job id ${JSON.stringify(id)} already belongs to ` +\n `${JSON.stringify(owner)}; job ids are scoped to their owner`\n : `Failed to persist job ${id}`\n );\n }\n return job;\n }\n\n cancel(capability: string, id: string): boolean {\n const existing = this.#sql(\n \"SELECT id FROM cf_agents_jobs WHERE id = ? AND capability = ?\",\n id,\n capability\n );\n if (existing.length === 0) return false;\n this.#sql(\n \"DELETE FROM cf_agents_jobs WHERE id = ? AND capability = ?\",\n id,\n capability\n );\n return true;\n }\n\n reschedule(capability: string, id: string, time: number): boolean {\n if (!Number.isFinite(time) || time < 0) {\n throw new Error(`Invalid job time: ${String(time)}`);\n }\n const existing = this.#sql(\n \"SELECT id FROM cf_agents_jobs WHERE id = ? AND capability = ?\",\n id,\n capability\n );\n if (existing.length === 0) return false;\n this.#sql(\n `UPDATE cf_agents_jobs\n SET time = ?, running = 0, execution_started_at = NULL\n WHERE id = ? AND capability = ?`,\n Math.floor(time),\n id,\n capability\n );\n return true;\n }\n\n get(capability: string, id: string): LifecycleJob | undefined {\n const rows = this.#sql(\n \"SELECT * FROM cf_agents_jobs WHERE id = ? AND capability = ?\",\n id,\n capability\n );\n return rows[0] ? jobFromRow(rows[0]) : undefined;\n }\n\n list(capability: string): LifecycleJob[] {\n return this.#sql(\n \"SELECT * FROM cf_agents_jobs WHERE capability = ? ORDER BY time ASC\",\n capability\n ).map(jobFromRow);\n }\n\n /** Raw due rows at `nowMs`, ordered by due time. */\n due(nowMs: number): JobStorageRow[] {\n return this.#sql(\n \"SELECT * FROM cf_agents_jobs WHERE time <= ? ORDER BY time ASC\",\n Math.floor(nowMs)\n );\n }\n\n /** One job's current row when it still exists and is still due. */\n dueRow(id: string, nowMs: number): JobStorageRow | undefined {\n return this.#sql(\n \"SELECT * FROM cf_agents_jobs WHERE id = ? AND time <= ?\",\n id,\n Math.floor(nowMs)\n )[0];\n }\n\n markRunning(id: string, nowMs: number): void {\n this.#sql(\n `UPDATE cf_agents_jobs\n SET running = 1, execution_started_at = ?\n WHERE id = ?`,\n Math.floor(nowMs),\n id\n );\n }\n\n clearRunning(id: string): void {\n this.#sql(\n `UPDATE cf_agents_jobs\n SET running = 0, execution_started_at = NULL\n WHERE id = ?`,\n id\n );\n }\n\n delete(id: string): void {\n this.#sql(\"DELETE FROM cf_agents_jobs WHERE id = ?\", id);\n }\n\n /**\n * Unguarded retime for the alarm memory-limit breaker's backoff: the\n * platform-failure path clears the dispatch marker before the breaker\n * runs, so the guarded {@link applyOutcome} would no-op — and the\n * breaker's backoff must land regardless, it is protecting the object.\n */\n retime(id: string, time: number): void {\n this.#sql(\n `UPDATE cf_agents_jobs\n SET time = ?, running = 0, execution_started_at = NULL\n WHERE id = ?`,\n Math.floor(time),\n id\n );\n }\n\n /**\n * Back off every pending recovery-loop job that would fire before the\n * breaker's backoff time (#1825), so a doomed loop's sibling rows cannot\n * re-trigger it on the next wake. Unguarded like {@link retime}: the\n * breaker's backoff must land regardless of dispatch markers.\n */\n delayRecoveryLoopJobs(time: number): void {\n this.#sql(\n `UPDATE cf_agents_jobs\n SET time = ?, running = 0, execution_started_at = NULL\n WHERE recovery_loop = 1 AND time <= ?`,\n Math.floor(time),\n Math.floor(time)\n );\n }\n\n /**\n * Read every recovery-loop job before breaker sealing. The memory-limit\n * policy phase uses this snapshot after the rows are purged so routed owners\n * can terminalize their own durable recovery state.\n */\n recoveryLoopJobs(): LifecycleJob[] {\n return this.#sql(\n \"SELECT * FROM cf_agents_jobs WHERE recovery_loop = 1 ORDER BY time ASC\"\n ).map(jobFromRow);\n }\n\n /**\n * Purge every recovery-loop job when the breaker seals at its strike\n * budget (#1825). Unrelated jobs are untouched.\n */\n purgeRecoveryLoopJobs(): void {\n this.#sql(\"DELETE FROM cf_agents_jobs WHERE recovery_loop = 1\");\n }\n\n /**\n * Apply one drive result, guarded on the dispatch marker: every driven\n * job carries `running = 1` for the duration of its dispatch, and a\n * same-id `push()` or `reschedule()` made meanwhile clears it. A cleared\n * marker means newer durable intent exists, so the outcome quietly\n * defers to it instead of deleting or retiming the fresher job.\n */\n applyOutcome(id: string, outcome: LifecycleJobOutcome): void {\n if (outcome === undefined) {\n this.#sql(\"DELETE FROM cf_agents_jobs WHERE id = ? AND running = 1\", id);\n return;\n }\n if (outcome === \"yield\") {\n this.clearRunning(id);\n return;\n }\n if (\n typeof outcome === \"object\" &&\n Number.isFinite(outcome.rescheduleAt) &&\n outcome.rescheduleAt >= 0\n ) {\n this.#sql(\n `UPDATE cf_agents_jobs\n SET time = ?, running = 0, execution_started_at = NULL\n WHERE id = ? AND running = 1`,\n Math.floor(outcome.rescheduleAt),\n id\n );\n return;\n }\n throw new Error(`Invalid job outcome for ${id}`);\n }\n\n /**\n * The next physical alarm time derived from queue state, or `null` when\n * the queue holds nothing to wake for.\n *\n * Exclusive jobs suppress ordinary candidates. An ordinary candidate is\n * the earliest ready job clamped to the future (overdue rows survive\n * restarts and must re-fire immediately), merged with the earliest\n * hung-timeout recheck for in-flight single-flight jobs.\n */\n nextAlarmTime(nowMs: number): number | null {\n const exclusive = this.#sql<{ time: number | null }>(\n \"SELECT MIN(time) AS time FROM cf_agents_jobs WHERE exclusive = 1\"\n );\n if (exclusive[0]?.time !== null && exclusive[0]?.time !== undefined) {\n return exclusive[0].time;\n }\n\n const now = Math.floor(nowMs);\n let candidate: number | null = null;\n\n const ready = this.#sql<{ time: number | null }>(\n `SELECT MIN(time) AS time FROM cf_agents_jobs\n WHERE singleflight = 0\n OR running = 0\n OR coalesce(execution_started_at, 0) + coalesce(hung_timeout_seconds, ?) * 1000 <= ?`,\n DEFAULT_HUNG_TIMEOUT_SECONDS,\n now\n );\n if (ready[0]?.time !== null && ready[0]?.time !== undefined) {\n candidate = Math.max(ready[0].time, now + 1);\n }\n\n const inFlight = this.#sql<{ recheck: number | null }>(\n `SELECT MIN(coalesce(execution_started_at, 0) + coalesce(hung_timeout_seconds, ?) * 1000) AS recheck\n FROM cf_agents_jobs\n WHERE singleflight = 1\n AND running = 1\n AND coalesce(execution_started_at, 0) + coalesce(hung_timeout_seconds, ?) * 1000 > ?`,\n DEFAULT_HUNG_TIMEOUT_SECONDS,\n DEFAULT_HUNG_TIMEOUT_SECONDS,\n now\n );\n const recheck = inFlight[0]?.recheck;\n if (recheck !== null && recheck !== undefined) {\n candidate = candidate === null ? recheck : Math.min(candidate, recheck);\n }\n\n return candidate;\n }\n}\n","/**\n * Alarm event loop for the Lifecycle job queue.\n *\n * The driver owns everything that happens when the physical alarm fires:\n * the deadman pre-arm, driving due jobs in due order (single-flight skip and\n * hung recovery, per-job retries, platform-failure deferral, terminal\n * failure hooks), the backlog warning, and the alarm memory-limit circuit\n * breaker (#1825). Lifecycle wires it to the host and capabilities through\n * the narrow {@link JobDriverOptions} contract and keeps only the alarm\n * entry point itself.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport {\n isDurableObjectCodeUpdateReset,\n isDurableObjectMemoryLimitReset,\n isPlatformFailure,\n tryN\n} from \"../retries\";\nimport type { MemoryLimitContext } from \"./capability-runner\";\nimport {\n hungTimeoutMs,\n isHungRow,\n jobFromRow,\n type JobQueue,\n type JobStorageRow,\n type LifecycleJob,\n type LifecycleJobContext,\n type LifecycleJobOutcome\n} from \"./job-queue\";\n\n/** Default consecutive memory-limit strikes tolerated before sealing. */\nconst DEFAULT_MAX_ALARM_MEMORY_LIMIT_STRIKES = 3;\n\n/** Durable storage key for the alarm memory-limit strike counter (#1825). */\nconst OOM_ALARM_STRIKES_KEY = \"cf_agents:oom_alarm_strikes\";\n\n/** Default retry policy applied to jobs pushed without one. */\nconst DEFAULT_JOB_RETRY = {\n maxAttempts: 3,\n baseDelayMs: 100,\n maxDelayMs: 3000\n} as const;\n\n/** Due jobs for one capability above this count log a backlog warning. */\nconst JOB_BACKLOG_WARNING_THRESHOLD = 10;\n\n/**\n * Deadman pre-arm delay: armed before the event loop drives due jobs so an\n * isolate death mid-drive still wakes this object to resume its queue.\n */\nconst DEADMAN_ALARM_DELAY_MS = 30_000;\n\n/** The dispatch hooks one job owner exposes to the driver. */\nexport type JobDispatch = {\n readonly onJob: (\n context: LifecycleJobContext\n ) => Promise<LifecycleJobOutcome | void>;\n readonly onJobError?: (\n context: LifecycleJobContext,\n error: unknown\n ) => Promise<LifecycleJobOutcome | void>;\n};\n\n/** What the driver needs from its owning Lifecycle. */\nexport type JobDriverOptions = {\n readonly queue: JobQueue;\n readonly storage: DurableObjectStorage;\n /** Live teardown flag: once true, stop touching storage mid-phase. */\n readonly disabled: () => boolean;\n /** Resolve a job owner to its dispatch hooks, `undefined` when missing. */\n readonly resolveDispatch: (owner: string) => Promise<JobDispatch | undefined>;\n /** Consecutive memory-limit strikes tolerated before sealing (#1825). */\n readonly maxMemoryLimitStrikes: () => number | undefined;\n /** Capability and host domain policy applied on each memory-limit strike. */\n readonly onMemoryLimit: (context: MemoryLimitContext) => void | Promise<void>;\n /** Best-effort lifecycle telemetry. */\n readonly emit: (type: string, payload: unknown) => void;\n /** Recompute the physical alarm from queue state. */\n readonly rearm: () => Promise<void>;\n /**\n * Schedule an isolate reset after a memory-limit strike is fully\n * recorded, suppressing any retry of the current alarm. Returns\n * immediately; the reset lands after the invocation settles, and the next\n * wake is the backoff alarm the strike armed.\n */\n readonly reset: (reason: string) => void;\n};\n\n/** The dispatch an async flow belongs to while an alarm drives it. */\ntype AlarmScope = { readonly executing: JobStorageRow | undefined };\n\n/**\n * Carries the row a platform failure escaped from out to `runAlarm`'s catch,\n * across the rethrow from `#driveJob`. Attribution must not live in a shared\n * instance field: overlapping `alarm()` invocations (a deadman or the\n * platform's own re-fire racing a still-running invocation) dispatch jobs\n * concurrently, and a field would let a later dispatch overwrite the row an\n * earlier one is still unwinding for.\n */\nclass AttributedPlatformFailure {\n constructor(\n readonly row: JobStorageRow,\n readonly cause: unknown\n ) {}\n}\n\n/** One recorded memory-limit strike, shared by every flow that observed it. */\ntype MemoryLimitStrike = {\n readonly strikes: number;\n readonly limit: number;\n readonly sealed: boolean;\n /** The backoff wake time armed for an unsealed strike. */\n readonly nextTime: number | undefined;\n /** Recovery-loop jobs purged by a sealing strike, snapshotted beforehand. */\n readonly purgedRecoveryLoopJobs: LifecycleJob[] | undefined;\n};\n\n/** @internal Drives the job queue when the Durable Object alarm fires. */\nexport class JobDriver {\n readonly #options: JobDriverOptions;\n /**\n * Ambient dispatch identity for `trackAlarmWork`. Read through the async\n * flow rather than an instance slot so attribution stays correct when\n * alarm invocations overlap (tests drive `alarm()` by hand while the\n * platform fires its own).\n */\n readonly #alarmScope = new AsyncLocalStorage<AlarmScope>();\n #alarmsInFlight = 0;\n /**\n * Work handed off by alarm-driven jobs that has not settled yet. While it\n * is non-empty the alarm domain is not quiescent, so a clean alarm must not\n * clear the strike counter: a still-running handoff may yet report the\n * memory reset that alarm started.\n */\n readonly #outstandingAlarmWork = new Set<Promise<unknown>>();\n /**\n * The strike being recorded for the current memory-limit event. One reset\n * is often observed by several flows (an in-alarm job plus handed-off work,\n * or several handoffs awaiting the same condemned storage); they share this\n * record so the counter moves once per event. Cleared by a clean,\n * quiescent classification.\n */\n #strike: Promise<MemoryLimitStrike> | undefined;\n /**\n * Once a strike has been fully recorded in this isolate, no later\n * settlement may clear the durable counter — a slower, unrelated clean\n * sibling finishing after the strike (but before the isolate reset it\n * scheduled actually lands) must not erase what was just recorded. The\n * isolate reset always follows a recorded strike, so the next genuinely\n * clean cycle runs in a fresh isolate with a fresh `JobDriver` and this\n * flag back at its default; there is no cross-isolate state to reset.\n */\n #strikeRecordedThisIsolate = false;\n\n constructor(options: JobDriverOptions) {\n this.#options = options;\n }\n\n /**\n * Run one alarm invocation: initialize the lifecycle, drive due jobs, run\n * the host's alarm callback, and re-arm the physical alarm from queue\n * state — all inside the alarm memory-limit circuit breaker (#1825). A\n * memory-limit reset that propagates here is intercepted — every other\n * error re-throws unchanged so platform alarm-retry semantics hold — and\n * broken from this outermost frame, where the heavy turn has unwound and\n * small writes can land. Initialization runs inside the breaker because a\n * severe reset can be thrown before any job runs (boot hydration, #1825);\n * left unhandled it would re-throw to the platform, which auto-retries\n * the alarm forever.\n */\n async runAlarm(\n initialize: () => Promise<void>,\n runHostAlarm: () => Promise<void>\n ): Promise<void> {\n this.#alarmsInFlight++;\n // Only a clean pass (no memory-limit reset seen by this invocation\n // itself) is ever eligible to trigger the quiescence-clear check below —\n // a pass that just recorded a strike must not immediately re-check\n // quiescence and undo what it just set. Reaching quiescence again is a\n // job for some LATER, genuinely clean invocation or handoff settlement.\n let clean = false;\n try {\n try {\n await initialize();\n await this.#driveDueJobs();\n await this.#alarmScope.run({ executing: undefined }, runHostAlarm);\n clean = true;\n } catch (error) {\n // A platform failure from #driveJob carries its row out of the\n // rethrow; anything else (initialize/runHostAlarm) has no job to\n // attribute. Unwrap either way before classifying the real error.\n const attributed = error instanceof AttributedPlatformFailure;\n const cause = attributed ? error.cause : error;\n if (!isDurableObjectMemoryLimitReset(cause)) {\n throw attributed ? cause : error;\n }\n await this.#handleMemoryLimitReset(\n cause,\n attributed ? error.row : undefined\n );\n return;\n }\n } finally {\n // Re-check quiescence exactly when this alarm's own \"in flight\" status\n // ends, using the freshest counters — one of the two points (the\n // other is a handoff settling, see #settleAlarmWork) that must not be\n // skipped: whichever transition happens last is what performs the\n // clear, and each transition re-evaluates both conditions itself\n // rather than trusting a stale snapshot taken before the other side's\n // own transition landed.\n this.#alarmsInFlight--;\n if (clean) await this.#clearMemoryLimitStrikesWhenQuiescent();\n }\n await this.#options.rearm();\n }\n\n /**\n * Keep work a job handed off at a bounded return inside this alarm's\n * memory-limit breaker domain (#1825). The alarm itself returns promptly,\n * so other jobs stay live; the handoff is classified when it settles. A\n * memory-limit reset it reports records a strike against the job that\n * handed it off, exactly as an in-alarm reset would. Strikes clear only\n * once no handed-off work is outstanding and the last of it settled clean.\n *\n * @returns True when called from an alarm-driven dispatch or the host\n * alarm hook; false otherwise, in which case nothing is tracked. Tracking\n * the same promise again (a claim-backstop wake for an attempt already\n * handed off) is a no-op.\n */\n trackAlarmWork(work: Promise<unknown>): boolean {\n const scope = this.#alarmScope.getStore();\n if (!scope) return false;\n if (this.#outstandingAlarmWork.has(work)) return true;\n this.#outstandingAlarmWork.add(work);\n void work.then(\n () => this.#settleAlarmWork(work, undefined, scope.executing),\n (error) => this.#settleAlarmWork(work, error, scope.executing)\n );\n return true;\n }\n\n async #settleAlarmWork(\n work: Promise<unknown>,\n error: unknown,\n executing: JobStorageRow | undefined\n ): Promise<void> {\n try {\n if (this.#options.disabled()) return;\n if (isDurableObjectMemoryLimitReset(error)) {\n // Still outstanding while the strike is recorded, so an alarm\n // finishing concurrently cannot clear it from underneath.\n await this.#handleMemoryLimitReset(error, executing);\n return;\n }\n } finally {\n this.#outstandingAlarmWork.delete(work);\n }\n // This settle is itself a quiescence transition — re-check freshly\n // rather than trusting whether an alarm looked in flight before this\n // delete landed (see runAlarm's matching call for why neither side may\n // skip its own check).\n await this.#clearMemoryLimitStrikesWhenQuiescent();\n }\n\n /**\n * Clear the strike counter once the alarm domain is fully quiescent: no\n * alarm invocation in flight, no handed-off work outstanding, and no\n * strike recorded in this isolate that a fresh isolate hasn't yet\n * superseded. Called at every transition that could make either counter\n * newly zero (an alarm ending, a handoff settling) — each call re-reads\n * both fresh, so whichever transition happens last is the one that\n * performs the clear. Idempotent: redundant calls no-op.\n */\n async #clearMemoryLimitStrikesWhenQuiescent(): Promise<void> {\n if (this.#alarmsInFlight > 0) return;\n if (this.#outstandingAlarmWork.size > 0) return;\n if (this.#strikeRecordedThisIsolate) return;\n this.#strike = undefined;\n await this.#clearMemoryLimitStrikes();\n }\n\n /** Drive every due job once, in due-time order. */\n async #driveDueJobs(): Promise<void> {\n const nowMs = Date.now();\n const due = this.#options.queue.due(nowMs);\n if (due.length === 0) return;\n this.#warnBacklog(due);\n\n // Deadman pre-arm: before driving any job, arm a fallback alarm so a\n // death mid-drive that the platform cannot retry (or that swallows its\n // error) still wakes this object to resume. The normal re-arm at the end\n // of the alarm phase overwrites it.\n if (!this.#options.disabled()) {\n await this.#options.storage.setAlarm(nowMs + DEADMAN_ALARM_DELAY_MS);\n }\n\n for (const stale of due) {\n // Host teardown mid-phase: its storage is gone, stop touching it.\n if (this.#options.disabled()) return;\n\n // Refetch before claiming: an earlier dispatch in this loop may have\n // pushed, rescheduled, or cancelled this job since the due snapshot\n // was taken. A row that is gone or no longer due belongs to that\n // newer intent — skip it (the final re-arm owns any future wake). A\n // row that changed but is still due dispatches with its fresh data.\n const row = this.#options.queue.dueRow(stale.id, nowMs);\n if (!row) continue;\n\n if (row.singleflight === 1 && row.running === 1) {\n if (!isHungRow(row, nowMs)) {\n console.warn(\n `Skipping job ${row.id}: previous execution still running`\n );\n continue;\n }\n console.warn(\n `Forcing reset of hung job ${row.id} (started ${Math.round(\n (nowMs - (row.execution_started_at ?? 0)) / 1000\n )}s ago)`\n );\n }\n // Every dispatch is marked, not just single-flight: the marker is\n // what lets a same-id push made mid-dispatch supersede the returned\n // drive result (see JobQueue.applyOutcome).\n this.#options.queue.markRunning(row.id, nowMs);\n\n await this.#driveJob(row);\n }\n }\n\n /** Dispatch one due row to its owner with retry and failure policy. */\n async #driveJob(row: JobStorageRow): Promise<void> {\n const { queue, resolveDispatch, disabled } = this.#options;\n const job = jobFromRow(row);\n const dispatch = await resolveDispatch(row.capability);\n if (!dispatch) {\n console.error(\n `No installed capability or host handler for job ${row.id} ` +\n `(owner ${JSON.stringify(row.capability)}); dropping it`\n );\n queue.delete(row.id);\n return;\n }\n\n const maxAttempts = job.retry?.maxAttempts ?? DEFAULT_JOB_RETRY.maxAttempts;\n\n // Dispatch must be bounded: the drive loop awaits each job inline, so\n // one long dispatch delays every other job on this object. The queue\n // cannot safely abandon owner code, so the contract is enforced by\n // visibility — a dispatch that outlives the job's hung timeout warns\n // loudly and emits telemetry naming the owner.\n const slowWatchdog = setTimeout(() => {\n const seconds = Math.round(hungTimeoutMs(row) / 1000);\n console.warn(\n `Job ${row.id} (${row.capability}/${row.fn}) has been dispatching ` +\n `for over ${seconds}s. Long dispatches starve every other job on ` +\n `this object; onJob must detach unbounded work and return.`\n );\n try {\n this.#options.emit(\"job:slow_dispatch\", {\n capability: row.capability,\n fn: row.fn,\n id: row.id,\n thresholdMs: hungTimeoutMs(row)\n });\n } catch {\n // telemetry never blocks the dispatch\n }\n }, hungTimeoutMs(row));\n\n let outcome: LifecycleJobOutcome | void;\n try {\n outcome = await this.#alarmScope.run({ executing: row }, () =>\n tryN(maxAttempts, (attempt) => dispatch.onJob({ job, attempt }), {\n baseDelayMs: job.retry?.baseDelayMs ?? DEFAULT_JOB_RETRY.baseDelayMs,\n maxDelayMs: job.retry?.maxDelayMs ?? DEFAULT_JOB_RETRY.maxDelayMs,\n // In-process retries are futile on a superseded isolate (code\n // never reloads mid-invocation) and on a memory-limit reset (the\n // isolate is condemned, and a retry can read half-claimed state\n // as \"nothing to do\", converting the reset into a silent success\n // that the breaker never sees). Defer both to the alarm boundary.\n shouldRetry: (error) =>\n !isDurableObjectCodeUpdateReset(error) &&\n !isDurableObjectMemoryLimitReset(error)\n })\n );\n } catch (error) {\n if (disabled()) return;\n if (isPlatformFailure(error)) {\n // Platform-class failure: preserve the job and re-throw so the\n // platform retries a fresh invocation (or the memory-limit breaker\n // engages at the alarm boundary). Best-effort dispatch-marker reset\n // so the preserved job is not mistaken for one still in flight (and\n // a single-flight job does not wait out its hung timeout first).\n try {\n queue.clearRunning(row.id);\n } catch {\n // the hung timeout eventually recovers the flag\n }\n console.warn(\n `Deferring job ${row.id} to a fresh invocation after a ` +\n `platform failure; the job is preserved.`\n );\n // Carry the row out with the error rather than through a shared\n // field: an overlapping alarm's own #driveJob may already be\n // dispatching a different row by the time this unwinds to\n // runAlarm's catch.\n throw new AttributedPlatformFailure(row, error);\n }\n // Application failure after retry exhaustion: the owner observes it\n // and decides advancement; default is completion.\n try {\n outcome = await dispatch.onJobError?.(\n { job, attempt: maxAttempts },\n error\n );\n } catch (hookError) {\n console.error(`Job failure hook threw for ${row.id}`, hookError);\n }\n } finally {\n clearTimeout(slowWatchdog);\n }\n\n if (disabled()) return;\n queue.applyOutcome(row.id, outcome ?? undefined);\n }\n\n #warnBacklog(due: ReadonlyArray<JobStorageRow>): void {\n const counts = new Map<string, number>();\n for (const row of due) {\n counts.set(row.capability, (counts.get(row.capability) ?? 0) + 1);\n }\n for (const [owner, count] of counts) {\n if (count < JOB_BACKLOG_WARNING_THRESHOLD) continue;\n try {\n console.warn(\n `Processing ${count} due jobs for ${JSON.stringify(owner)} ` +\n `in a single alarm cycle. This usually means one-shot jobs are ` +\n `pushed repeatedly without a stable id.`\n );\n this.#options.emit(\"job:backlog_warning\", {\n capability: owner,\n count\n });\n } catch {\n // warning emission never blocks job processing\n }\n }\n }\n\n /**\n * Clear the durable memory-limit strike counter after a clean alarm so the\n * breaker counts CONSECUTIVE resets rather than lifetime ones (#1825).\n * Reads first and only writes when a strike is recorded. Best-effort.\n */\n async #clearMemoryLimitStrikes(): Promise<void> {\n const { storage } = this.#options;\n try {\n const prior = await storage.get<number>(OOM_ALARM_STRIKES_KEY);\n if (typeof prior === \"number\" && prior > 0) {\n await storage.delete(OOM_ALARM_STRIKES_KEY);\n }\n } catch {\n // a stale strike only costs one extra tolerated spike later\n }\n }\n\n /**\n * Alarm-boundary circuit breaker for Durable Object memory-limit resets\n * (#1825). Unhandled, the platform would auto-retry the alarm forever,\n * re-running the doomed work each cycle. A durable strike counter\n * tolerates a few consecutive resets — backing off the executing job and\n * every pending recovery-loop job so the retry is not a hot loop — then\n * seals: those jobs are purged and the capability + host memory-limit\n * policy hooks run.\n *\n * One reset is one event even when several flows observe it. The strike\n * is recorded once per event ({@link #recordMemoryLimitStrike}); every\n * observer then applies the per-job policy for the job it belongs to, and\n * the first observer finishes the event by re-arming, syncing, and\n * resetting the isolate. Each step is best-effort: even these small writes\n * can OOM, but swallowing still halts the platform's auto-retry, and a\n * later wake re-arms legitimate work.\n */\n async #handleMemoryLimitReset(\n error: unknown,\n executing: JobStorageRow | undefined\n ): Promise<void> {\n const { queue } = this.#options;\n const first = this.#strike === undefined;\n // Set before the first await below: closes the window as tightly as\n // possible against a still-outstanding clean sibling reaching quiescence\n // and clearing what this event is about to record.\n this.#strikeRecordedThisIsolate = true;\n this.#strike ??= this.#recordMemoryLimitStrike(error);\n const strike = await this.#strike;\n\n try {\n if (executing) {\n if (strike.sealed) {\n queue.delete(executing.id);\n } else if (strike.nextTime !== undefined) {\n queue.retime(executing.id, strike.nextTime);\n }\n }\n } catch {\n // best-effort at a failure boundary\n }\n\n try {\n await this.#options.onMemoryLimit({\n sealed: strike.sealed,\n nextTime: strike.nextTime,\n executing: executing ? jobFromRow(executing) : undefined,\n purgedRecoveryLoopJobs: first\n ? strike.purgedRecoveryLoopJobs\n : undefined\n });\n } catch {\n // best-effort domain policy; the purge above already broke the loop\n }\n\n if (!first) return;\n\n // Re-arm so unrelated work continues. Wrapped because it can itself OOM;\n // if it does, the next external wake re-arms.\n try {\n await this.#options.rearm();\n } catch {\n // best-effort\n }\n\n // Finish on a fresh isolate: the strike is durable and the backoff alarm\n // owns the next wake, so schedule a reset to reclaim the memory\n // footprint instead of limping on in the pressured isolate. Sync first —\n // a reset cancels unconfirmed writes, and the strike/backoff writes must\n // land. If any of this fails, fall through to the swallow-and-return\n // exit, which still halts the platform's alarm auto-retry.\n try {\n await this.#options.storage.sync();\n this.#options.reset(\n `Alarm memory-limit strike ${strike.strikes}/${strike.limit}${strike.sealed ? \" (sealed)\" : \"\"}; resetting isolate (#1825)`\n );\n } catch {\n // best-effort\n }\n }\n\n /**\n * Record one strike durably and apply the queue-wide policy that belongs\n * to the event rather than to any one job: recovery-loop rows back off (or\n * purge) as a pack, a sealing strike resets the counter, and the event is\n * emitted once.\n */\n async #recordMemoryLimitStrike(error: unknown): Promise<MemoryLimitStrike> {\n const { queue, storage } = this.#options;\n\n let strikes = 1;\n let counted = true;\n try {\n const prior = await storage.get<number>(OOM_ALARM_STRIKES_KEY);\n strikes = (typeof prior === \"number\" ? prior : 0) + 1;\n await storage.put(OOM_ALARM_STRIKES_KEY, strikes);\n } catch {\n // The reset isolate's storage rejects every call, so this strike cannot\n // be counted and the counter cannot reach the seal from here. Chat\n // recovery bounds that loop itself: the next isolate counts the\n // interrupted attempt before re-running it (#2613).\n counted = false;\n }\n\n const limit =\n this.#options.maxMemoryLimitStrikes() ??\n DEFAULT_MAX_ALARM_MEMORY_LIMIT_STRIKES;\n const sealed = strikes >= limit;\n const strikeLabel = counted\n ? `strike ${strikes}/${limit}`\n : \"strike not counted: storage rejected it after the reset\";\n console.error(\n `Alarm hit a Durable Object memory-limit reset (${strikeLabel}` +\n `${sealed ? \", sealing recovery\" : \", will retry with backoff\"}). ` +\n \"Breaking the platform alarm-retry loop (#1825).\",\n error instanceof Error ? error.message : String(error)\n );\n\n const nextTime = sealed\n ? undefined\n : Date.now() + Math.min(300, 30 * strikes) * 1000;\n // Capture routed ownership before sealing deletes the rows. Domain policy\n // runs afterward, when the loop is already broken, and uses this snapshot\n // only to terminalize durable state owned outside the alarm host.\n let purgedRecoveryLoopJobs: LifecycleJob[] | undefined;\n try {\n if (sealed) purgedRecoveryLoopJobs = queue.recoveryLoopJobs();\n } catch {\n // best-effort at a failure boundary\n }\n\n try {\n // Recovery-loop rows travel as a pack: a doomed loop's sibling rows\n // would re-trigger it on the next wake, so they back off (or purge)\n // together with the row that struck.\n if (sealed) {\n queue.purgeRecoveryLoopJobs();\n } else if (nextTime !== undefined) {\n queue.delayRecoveryLoopJobs(nextTime);\n }\n } catch {\n // best-effort at a failure boundary\n }\n\n if (sealed) {\n try {\n await storage.delete(OOM_ALARM_STRIKES_KEY);\n } catch {\n // best-effort counter reset\n }\n }\n\n try {\n this.#options.emit(\"alarm:memory_limit_reset\", {\n strikes,\n limit,\n sealed,\n error: error instanceof Error ? error.message : String(error)\n });\n } catch {\n // event emission is non-critical\n }\n\n return { strikes, limit, sealed, nextTime, purgedRecoveryLoopJobs };\n }\n}\n","// Internal helpers for classifying WebSocket transport errors.\n// Not re-exported from the package entry point; imported by `index.ts` and\n// exercised directly by `tests/transport-errors.test.ts`.\n\n/** Standard `WebSocket.readyState` values. */\nconst CLOSING = 2;\nconst CLOSED = 3;\n\n/**\n * A retryable transport-teardown error (\"Network connection lost\" /\n * \"WebSocket peer disconnected\") that fires on a connection which is already\n * CLOSING/CLOSED is just the socket going away during or right after the close\n * handshake - not an application error. Surfacing it via `onError` spams logs\n * on every abrupt client disconnect, and even on clean closes when the peer\n * tears down its transport before our reciprocal Close frame lands. Suppress\n * it in that specific case only; genuine mid-connection (OPEN) errors still\n * reach `onError`.\n *\n * Detection prefers the structured `retryable` flag over message text so it\n * stays correct across `enhanced-error-serialization` (compat date\n * >= 2026-04-21), with a substring fallback for older error shapes.\n */\nexport function isBenignTeardownError(\n ws: { readyState?: number },\n error: unknown\n): boolean {\n const state = ws.readyState;\n if (state !== CLOSING && state !== CLOSED) return false;\n if (typeof error !== \"object\" || error === null) return false;\n const typed = error as { retryable?: boolean; message?: unknown };\n if (typed.retryable === true) return true;\n const message = typeof typed.message === \"string\" ? typed.message : \"\";\n return /Network connection lost|WebSocket peer disconnected/i.test(message);\n}\n","import { AsyncLocalStorage } from \"node:async_hooks\";\nimport { DurableObject } from \"cloudflare:workers\";\n\nimport { publishDiagnosticsEvent } from \"../observability/diagnostics\";\nimport {\n CapabilityRunner,\n type DurableObjectCapability,\n type LifecycleEvent,\n type LifecycleEventSink\n} from \"./capability-runner\";\nimport { abortWithoutAlarmRetry } from \"./abort\";\nimport { JobDriver, type JobDispatch } from \"./job-driver\";\nimport {\n HOST_JOB_CAPABILITY,\n JobQueue,\n type LifecycleJobs,\n type LifecycleJobPushOptions\n} from \"./job-queue\";\nimport {\n bindLifecycleCapability,\n lifecycleCapabilityId,\n LifecycleCapability,\n type LifecycleHostContextScope,\n type LifecycleRouteAddress,\n type LifecycleServices,\n type LifecycleStatus\n} from \"./capability\";\nimport {\n runInLifecycleHostContext,\n runWithoutCurrentAgent,\n type LifecycleObject\n} from \"./current-agent\";\nimport { isBenignTeardownError } from \"./transport-errors\";\nimport type { WSMessage } from \"./types\";\n\nexport {\n type CapabilityRequestContext,\n type CapabilityWebSocketUpgradeContext,\n type LifecycleEvent,\n type CapabilityStartContext,\n type DurableObjectCapability,\n type MemoryLimitContext\n} from \"./capability-runner\";\nexport {\n type LifecycleJobContext,\n type LifecycleJobs,\n type LifecycleJob,\n type LifecycleJobOutcome,\n type LifecycleJobPushOptions\n} from \"./job-queue\";\nexport * from \"./types\";\n\nconst LEGACY_NAME_STORAGE_KEY = \"__ps_name\";\n\nfunction mutableRequest(request: Request): Request {\n return new Request(request);\n}\n\n/**\n * Decode props from the internal lifecycle props header.\n *\n * Handles both base64-encoded lifecycle props and, for\n * backwards compatibility with stubs/requests created by older versions,\n * raw JSON. Base64 never starts with `{` or `[`, so a leading brace/bracket\n * unambiguously identifies the legacy raw-JSON form.\n */\nfunction decodeProps(header: string): unknown {\n const trimmed = header.trim();\n if (trimmed.startsWith(\"{\") || trimmed.startsWith(\"[\")) {\n return JSON.parse(trimmed);\n }\n const binary = atob(header);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return JSON.parse(new TextDecoder().decode(bytes));\n}\n\n/** Internal envelope transported between routed Lifecycle instances. */\nexport type LifecycleRouteEnvelope = {\n readonly capability: string;\n readonly source: LifecycleRouteAddress | undefined;\n readonly payload: unknown;\n};\n\n/** Internal transport supplied by a host with routed child Lifecycles. */\nexport type LifecycleRouteTransport = {\n readonly source: LifecycleRouteAddress | undefined;\n readonly toRoot: (envelope: LifecycleRouteEnvelope) => Promise<unknown>;\n readonly to: (\n target: LifecycleRouteAddress,\n envelope: LifecycleRouteEnvelope\n ) => Promise<unknown>;\n};\n\ntype LifecycleHost<Env extends object, Props extends object> = LifecycleObject<\n Env,\n Props\n> & {\n readonly ctx: DurableObjectState;\n readonly constructor: { readonly name: string };\n};\n\n/**\n * Boundary wrapping user callbacks that capabilities run through\n * `LifecycleServices.runInHostContext`. The default boundary is\n * {@link runInLifecycleHostContext}; a host composition root may substitute\n * its own invocation wrapper (Agent adds tracing span scope). The optional\n * scope carries the live connection/request the callback runs on behalf of.\n */\nexport type LifecycleHostInvoker = <T>(\n run: () => T,\n scope?: LifecycleHostContextScope\n) => T;\n\nconst lifecycleEventSinks = new WeakMap<object, LifecycleEventSink>();\nconst lifecycleRouteTransports = new WeakMap<object, LifecycleRouteTransport>();\nconst lifecycleHostInvokers = new WeakMap<object, LifecycleHostInvoker>();\n\n/** Lifecycles whose startup the current async context is running inside. */\nconst lifecycleStartupScope = new AsyncLocalStorage<ReadonlySet<object>>();\n\n/** @internal Adapt the host invocation boundary at a composition root. */\nexport function setLifecycleHostInvoker<\n Env extends object,\n Props extends object\n>(lifecycle: Lifecycle<Env, Props>, invoker: LifecycleHostInvoker): void {\n lifecycleHostInvokers.set(lifecycle, invoker);\n}\n\n/** @internal Supply a host's routed Lifecycle transport. */\nexport function setLifecycleRouteTransport<\n Env extends object,\n Props extends object\n>(lifecycle: Lifecycle<Env, Props>, transport: LifecycleRouteTransport): void {\n lifecycleRouteTransports.set(lifecycle, transport);\n}\n\n/** @internal Adapt Lifecycle's default diagnostics sink at a composition root. */\nexport function setLifecycleEventSink<Env extends object, Props extends object>(\n lifecycle: Lifecycle<Env, Props>,\n sink: LifecycleEventSink\n): void {\n lifecycleEventSinks.set(lifecycle, sink);\n}\n\n/** Configuration accepted when constructing a {@link Lifecycle}. */\nexport type LifecycleOptions = {\n /**\n * Consecutive alarm invocations that may end in a Durable Object\n * memory-limit reset before the circuit breaker (#1825) seals recovery\n * work instead of backing it off. Default: 3.\n */\n readonly maxAlarmMemoryLimitStrikes?: number;\n};\n\n/**\n * Installs and coordinates the runtime lifecycle for a Durable Object.\n *\n * Construct this as an instance field on a class that directly extends\n * `DurableObject`, then call {@link Lifecycle.installHandlers}\n * from that class's constructor.\n */\n/** The dispatch hooks a catch-all can monopolize; uniqueness is per hook. */\nconst CATCH_ALL_HOOKS = [\"onRequest\", \"onWebSocketUpgrade\"] as const;\n\nexport class Lifecycle<\n Env extends object = Cloudflare.Env,\n Props extends object = object\n> {\n readonly #host: LifecycleHost<Env, Props>;\n readonly #ctx: DurableObjectState;\n readonly #parentClassName: string;\n readonly #capabilities: DurableObjectCapability<Props>[] = [];\n readonly #capabilityRunner = new CapabilityRunner<Props>(\n () => this.#capabilities\n );\n readonly #jobQueue: JobQueue;\n readonly #jobDriver: JobDriver;\n\n #status: LifecycleStatus = \"zero\";\n #alarmRearmQueue: Promise<void> = Promise.resolve();\n #rearmRequestedDuringStart = false;\n #pendingEvents: LifecycleEvent[] = [];\n #alarmsDisabled = false;\n #capabilitiesLocked = false;\n #handlersInstalled = false;\n\n /**\n * Construct and install a lifecycle in one explicit operation.\n *\n * @param host - The Durable Object whose runtime handlers the lifecycle owns.\n * @returns The installed lifecycle.\n */\n static install<Env extends object, Props extends object = object>(\n host: DurableObject<Env>,\n options?: LifecycleOptions\n ): Lifecycle<Env, Props> {\n const lifecycle = new Lifecycle<Env, Props>(host, options);\n lifecycle.installHandlers();\n return lifecycle;\n }\n\n /**\n * Bind a lifecycle to a Durable Object instance without mutating its handlers.\n *\n * @param host - The Durable Object whose runtime lifecycle this object owns.\n * @param options - Policy configuration for this lifecycle.\n */\n constructor(host: DurableObject<Env>, options?: LifecycleOptions) {\n // SAFETY: DurableObject exposes ctx as protected to subclasses. The\n // lifecycle is constructed by that subclass with `this`, so this boundary\n // accesses the same runtime-owned context without exposing it publicly.\n this.#host = host as unknown as LifecycleHost<Env, Props>;\n this.#ctx = this.#host.ctx;\n this.#parentClassName = this.#host.constructor.name;\n this.#jobQueue = new JobQueue(this.#ctx.storage);\n this.#jobDriver = new JobDriver({\n queue: this.#jobQueue,\n storage: this.#ctx.storage,\n disabled: () => this.#alarmsDisabled,\n resolveDispatch: (owner) => this.#resolveJobDispatch(owner),\n maxMemoryLimitStrikes: () => options?.maxAlarmMemoryLimitStrikes,\n onMemoryLimit: async (context) => {\n // Capabilities first (each best-effort inside the runner), then the\n // host hook — a failed capability policy must not silence the host's.\n await this.#capabilityRunner.memoryLimit(context);\n await runInLifecycleHostContext({ host: this.#host }, () =>\n this.#host.onAlarmMemoryLimit?.(context)\n );\n },\n emit: (type, payload) =>\n this.#emitCapabilityEvent({ source: \"lifecycle\", type, payload }),\n rearm: () => this.rearmAlarm(),\n // Deferred a tick so the current invocation settles (its RPC/alarm\n // completes and its writes confirm) before the instance resets —\n // `abort()` throws an uncatchable error, mirroring Agent.destroy().\n reset: (reason) => {\n setTimeout(() => abortWithoutAlarmRetry(this.#ctx, reason), 0);\n }\n });\n }\n\n /**\n * Install platform fetch, alarm, and hibernating WebSocket handlers.\n *\n * Existing handlers are preserved for framework-owned dispatch such as the\n * Agent's sub-agent router and alarm circuit breaker. Calling this method\n * more than once is an error.\n */\n installHandlers(): void {\n if (this.#handlersInstalled) {\n throw new Error(\n \"Durable Object lifecycle handlers are already installed\"\n );\n }\n this.#handlersInstalled = true;\n\n const handlers = {\n fetch: this.fetch.bind(this),\n alarm: this.alarm.bind(this),\n webSocketMessage: this.webSocketMessage.bind(this),\n webSocketClose: this.webSocketClose.bind(this),\n webSocketError: this.webSocketError.bind(this)\n };\n for (const [name, handler] of Object.entries(handlers)) {\n if (name in this.#host) continue;\n Object.defineProperty(this.#host, name, {\n value: handler,\n configurable: true\n });\n }\n }\n\n /**\n * Add a reusable capability before this lifecycle starts.\n *\n * Capabilities dispatch in registration order, except that a capability\n * declaring `claims: \"catch-all\"` always comes last, whenever it was\n * installed. Catch-alls are unique per dispatch hook: two may coexist\n * when they claim disjoint traffic (one `onRequest`, one\n * `onWebSocketUpgrade`), but a second catch-all for the same hook could\n * never be reached and is refused.\n *\n * @param capability - The capability to add.\n * @returns This lifecycle.\n */\n use(capability: DurableObjectCapability<Props>): this {\n if (this.#capabilitiesLocked) {\n throw new Error(\"Lifecycle capabilities must be added before startup\");\n }\n const capabilityId = lifecycleCapabilityId(capability);\n if (\n capabilityId &&\n this.#capabilities.some(\n (candidate) => lifecycleCapabilityId(candidate) === capabilityId\n )\n ) {\n throw new Error(\n `Lifecycle capability ${JSON.stringify(capabilityId)} is already installed`\n );\n }\n\n const catchAllIndex = this.#capabilities.findIndex(\n (candidate) => candidate.claims === \"catch-all\"\n );\n if (capability.claims === \"catch-all\") {\n for (const hook of CATCH_ALL_HOOKS) {\n if (!capability[hook]) continue;\n const rival = this.#capabilities.find(\n (candidate) => candidate.claims === \"catch-all\" && candidate[hook]\n );\n if (!rival) continue;\n const installed = lifecycleCapabilityId(rival);\n throw new Error(\n `Lifecycle already has a catch-all for ${hook}${\n installed ? ` (${JSON.stringify(installed)})` : \"\"\n }; a second one could never be reached`\n );\n }\n this.#capabilities.push(capability);\n } else {\n this.#capabilities.splice(\n catchAllIndex === -1 ? this.#capabilities.length : catchAllIndex,\n 0,\n capability\n );\n }\n\n if (capability instanceof LifecycleCapability) {\n bindLifecycleCapability(\n capability,\n this.#servicesForCapability(capability.capabilityId)\n );\n }\n return this;\n }\n\n #servicesForCapability(capabilityId: string): LifecycleServices {\n const lifecycle = this;\n const envelope = (payload: unknown): LifecycleRouteEnvelope => ({\n capability: capabilityId,\n source: lifecycleRouteTransports.get(lifecycle)?.source,\n payload\n });\n return Object.freeze({\n get name() {\n return lifecycle.name;\n },\n className: this.#parentClassName,\n storage: this.#ctx.storage,\n sockets: Object.freeze({\n accept: (ws: WebSocket, tags: string[]) =>\n this.#ctx.acceptWebSocket(ws, tags),\n get: (tag?: string) => this.#ctx.getWebSockets(tag)\n }),\n ready: () => this.#readyForCapabilityOperation(),\n status: () => this.#status,\n jobs: this.#jobsForOwner(capabilityId),\n trackAlarmWork: (work: Promise<unknown>) =>\n this.#jobDriver.trackAlarmWork(work),\n runInHostContext: async (\n fn: () => unknown,\n scope?: LifecycleHostContextScope\n ) => this.#runInHostBoundary(fn, scope),\n events: Object.freeze({\n emit: (type: string, payload: unknown) =>\n this.#emitCapabilityEvent({ source: capabilityId, type, payload })\n }),\n routes: Object.freeze({\n get source() {\n return lifecycleRouteTransports.get(lifecycle)?.source;\n },\n toRoot: (payload: unknown) => {\n const transport = lifecycleRouteTransports.get(lifecycle);\n return transport\n ? transport.toRoot(envelope(payload))\n : this.#dispatchRoute(envelope(payload));\n },\n to: (target: LifecycleRouteAddress, payload: unknown) => {\n const transport = lifecycleRouteTransports.get(lifecycle);\n if (!transport) {\n throw new Error(\n \"Lifecycle has no transport for routed capabilities\"\n );\n }\n return transport.to(target, envelope(payload));\n }\n })\n });\n }\n\n /**\n * Run a user callback inside the host invocation boundary — plain host\n * context by default, or the composition root's substitute (Agent installs\n * its tracing invocation scope).\n */\n #runInHostBoundary(\n fn: () => unknown,\n scope?: LifecycleHostContextScope\n ): Promise<unknown> {\n const boundary = lifecycleHostInvokers.get(this);\n return Promise.resolve(\n boundary\n ? boundary(fn, scope)\n : runInLifecycleHostContext(\n {\n host: this.#host,\n connection: scope?.connection,\n request: scope?.request\n },\n fn\n )\n );\n }\n\n #readyForCapabilityOperation(): Promise<void> {\n return this.#ensureInitialized();\n }\n\n async #dispatchRoute(envelope: LifecycleRouteEnvelope): Promise<unknown> {\n await this.#ensureInitialized();\n return runWithoutCurrentAgent(() =>\n this.#capabilityRunner.route(envelope.capability, {\n source: envelope.source,\n payload: envelope.payload\n })\n );\n }\n\n /** @internal Deliver a generic capability envelope to this Lifecycle. */\n route(envelope: LifecycleRouteEnvelope): Promise<unknown> {\n return this.#dispatchRoute(envelope);\n }\n\n #emitCapabilityEvent(event: LifecycleEvent): void {\n if (event.source.trim() === \"\" || event.type.trim() === \"\") {\n throw new Error(\"Lifecycle events require non-empty source and type\");\n }\n if (this.#status !== \"started\") {\n this.#pendingEvents.push(event);\n return;\n }\n this.#publishCapabilityEvent(event);\n }\n\n #publishCapabilityEvent(event: LifecycleEvent): void {\n runWithoutCurrentAgent(() => {\n const sink = lifecycleEventSinks.get(this);\n try {\n if (!sink) {\n publishDiagnosticsEvent({\n source: event.source,\n type: event.type,\n agent: this.#parentClassName,\n name: this.name,\n payload: event.payload,\n timestamp: Date.now()\n });\n return;\n }\n const pending = sink(event);\n if (pending !== undefined) {\n this.#ctx.waitUntil(\n Promise.resolve(pending).catch((error) => {\n this.#reportEventSinkFailure(event, error);\n })\n );\n }\n } catch (error) {\n this.#reportEventSinkFailure(event, error);\n }\n });\n }\n\n #reportEventSinkFailure(event: LifecycleEvent, error: unknown): void {\n console.error(\n `Lifecycle event sink failed for ${event.source}:${event.type}`,\n error\n );\n }\n\n #deliverPendingEvents(): void {\n for (const event of this.#pendingEvents.splice(0)) {\n this.#publishCapabilityEvent(event);\n }\n }\n\n /**\n * Execute SQL queries against the Durable Object's database\n * @template T Type of the returned rows\n * @param strings SQL query template strings\n * @param values Values to be inserted into the query\n * @returns Array of query results\n */\n sql<T = Record<string, string | number | boolean | null>>(\n strings: TemplateStringsArray,\n ...values: (string | number | boolean | null)[]\n ) {\n let query = \"\";\n try {\n // Construct the SQL query with placeholders\n query = strings.reduce(\n (acc, str, i) => acc + str + (i < values.length ? \"?\" : \"\"),\n \"\"\n );\n\n // Execute the SQL query with the provided values\n return [...this.#ctx.storage.sql.exec(query, ...values)] as T[];\n } catch (error) {\n console.error(`failed to execute sql query: ${query}`, error);\n throw error;\n }\n }\n\n /**\n * Handle an incoming request for the owning Durable Object.\n *\n * Non-upgrade requests run through the capability middleware chain first,\n * then fall through to the host's `onRequest`.\n */\n async fetch(request: Request): Promise<Response> {\n try {\n const encodedProps = request.headers.get(\"x-agents-lifecycle-props\");\n if (encodedProps) {\n this.#props = decodeProps(encodedProps) as Props;\n request = mutableRequest(request);\n request.headers.delete(\"x-agents-lifecycle-props\");\n }\n\n await this.#ensureInitialized();\n\n if (request.headers.get(\"Upgrade\")?.toLowerCase() !== \"websocket\") {\n const capabilityResponse = await runWithoutCurrentAgent(() =>\n this.#capabilityRunner.request({ request })\n );\n if (capabilityResponse !== undefined) return capabilityResponse;\n if (this.#host.onRequest) {\n return await runInLifecycleHostContext(\n { host: this.#host, request },\n () => this.#host.onRequest!(request)\n );\n }\n return new Response(\"Not implemented\", { status: 404 });\n } else {\n // Lifecycle does not model WebSockets. A capability that owns\n // connection behavior (e.g. the WebSockets capability) claims the\n // upgrade here; without one, upgrades are not supported.\n const upgradeResponse = await runWithoutCurrentAgent(() =>\n this.#capabilityRunner.webSocketUpgrade({ request })\n );\n if (upgradeResponse !== undefined) return upgradeResponse;\n\n return new Response(\n \"WebSocket upgrades are not enabled on this Durable Object. Install a capability that claims them (e.g. WebSockets).\",\n { status: 404 }\n );\n }\n } catch (err) {\n console.error(\n `Error in ${this.#parentClassName}:${this.#ctx.id.name ?? \"<unnamed>\"} fetch:`,\n err\n );\n if (!(err instanceof Error)) throw err;\n if (request.headers.get(\"Upgrade\") === \"websocket\") {\n // Annoyingly, if we return an HTTP error in response to a WebSocket request, Chrome devtools\n // won't show us the response body! So... let's send a WebSocket response with an error\n // frame instead.\n const pair = new WebSocketPair();\n pair[1].accept();\n pair[1].send(JSON.stringify({ error: err.stack }));\n pair[1].close(1011, \"Uncaught exception during session setup\");\n return new Response(null, { status: 101, webSocket: pair[0] });\n } else {\n return new Response(err.stack, { status: 500 });\n }\n }\n }\n\n /** @internal Dispatch a hibernating WebSocket message. */\n async webSocketMessage(ws: WebSocket, message: WSMessage): Promise<void> {\n try {\n await this.#ensureInitialized();\n\n // Sockets are owned by whichever capability claimed their upgrade\n // (recognized via its own hibernation attachment). Wakes for sockets\n // no capability owns — e.g. `state.acceptWebSocket()` in user code —\n // are ignored.\n await runWithoutCurrentAgent(() =>\n this.#capabilityRunner.webSocketMessage(ws, message)\n );\n } catch (e) {\n console.error(\n `Error in ${this.#parentClassName}:${this.#ctx.id.name ?? \"<unnamed>\"} webSocketMessage:`,\n e\n );\n }\n }\n\n /** @internal Dispatch a hibernating WebSocket close. */\n async webSocketClose(\n ws: WebSocket,\n code: number,\n reason: string,\n wasClean: boolean\n ): Promise<void> {\n try {\n await this.#ensureInitialized();\n // The owning capability also reciprocates the close handshake, as\n // the Hibernation API contract requires.\n await runWithoutCurrentAgent(() =>\n this.#capabilityRunner.webSocketClose(ws, code, reason, wasClean)\n );\n } catch (e) {\n console.error(\n `Error in ${this.#parentClassName}:${this.#ctx.id.name ?? \"<unnamed>\"} webSocketClose:`,\n e\n );\n }\n }\n\n /** @internal Dispatch a hibernating WebSocket error. */\n async webSocketError(ws: WebSocket, error: unknown): Promise<void> {\n // Suppress retryable transport-teardown errors on an already closing/closed\n // socket — the connection going away during/after the close handshake, not\n // an application error. Genuine mid-connection (OPEN) errors still reach\n // the owning handler below.\n if (isBenignTeardownError(ws, error)) {\n return;\n }\n\n try {\n await this.#ensureInitialized();\n await runWithoutCurrentAgent(() =>\n this.#capabilityRunner.webSocketError(ws, error)\n );\n } catch (e) {\n console.error(\n `Error in ${this.#parentClassName}:${this.#ctx.id.name ?? \"<unnamed>\"} webSocketError:`,\n e\n );\n }\n }\n\n /**\n * Start lifecycle capabilities and the owning Durable Object.\n *\n * Runtime fetch, alarm, and WebSocket entry points call this automatically.\n * RPC methods may call it explicitly because native RPC bypasses fetch.\n *\n * Concurrent callers share one startup and all observe its outcome. A call\n * made from inside that startup, such as a capability or `onStart` calling\n * back into the host, returns immediately instead of waiting on itself.\n *\n * @param props - Optional properties supplied to capability and host startup.\n * Ignored while a startup is already in flight.\n */\n async start(props?: Props): Promise<void> {\n if (props !== undefined && this.#startup === undefined) {\n this.#props = props;\n }\n await this.#ensureInitialized();\n }\n\n /**\n * Whether lifecycle startup has completed for this instance.\n *\n * @returns `true` after capabilities and the host `onStart` have finished.\n */\n isStarted(): boolean {\n return this.#status === \"started\";\n }\n\n #startup: Promise<void> | undefined;\n\n #ensureInitialized(): Promise<void> {\n if (this.#status === \"started\") return Promise.resolve();\n if (this.#startup === undefined) {\n // Deferred a tick so `#startup` is assigned before startup can call\n // back into this method synchronously.\n const startup = Promise.resolve()\n .then(() => this.#runStartup())\n .finally(() => {\n if (this.#startup === startup) this.#startup = undefined;\n });\n this.#startup = startup;\n return startup;\n }\n if (lifecycleStartupScope.getStore()?.has(this)) return Promise.resolve();\n return this.#startup;\n }\n\n async #runStartup(): Promise<void> {\n if (this.#ctx.id.name === undefined && this.#legacyName === undefined) {\n this.#legacyName = await this.#ctx.storage.get<string>(\n LEGACY_NAME_STORAGE_KEY\n );\n }\n // Fail before host startup if neither native nor migrated identity exists.\n void this.name;\n\n this.#capabilitiesLocked = true;\n const scope = new Set(lifecycleStartupScope.getStore());\n scope.add(this);\n let error: unknown;\n await this.#ctx.blockConcurrencyWhile(() =>\n lifecycleStartupScope.run(scope, async () => {\n this.#status = \"starting\";\n try {\n await runWithoutCurrentAgent(() =>\n this.#capabilityRunner.start({ props: this.#props })\n );\n await runInLifecycleHostContext({ host: this.#host }, () =>\n this.#host.onStart?.(this.#props)\n );\n this.#status = \"started\";\n } catch (cause) {\n this.#status = \"zero\";\n error = cause;\n }\n })\n );\n // Re-throw outside blockConcurrencyWhile so the input gate is not\n // permanently broken and a later invocation can retry startup.\n if (error) {\n this.#rearmRequestedDuringStart = false;\n this.#pendingEvents.length = 0;\n throw error;\n }\n this.#deliverPendingEvents();\n if (this.#rearmRequestedDuringStart) {\n this.#rearmRequestedDuringStart = false;\n await this.rearmAlarm();\n }\n }\n\n #legacyName: string | undefined;\n\n /**\n * The name used to address this Durable Object.\n *\n * Native `ctx.id.name` is authoritative. A read-only legacy storage fallback\n * lets objects created by older PartyServer releases migrate without new\n * name writes.\n */\n get name(): string {\n const name = this.#ctx.id.name ?? this.#legacyName;\n if (name !== undefined) return name;\n throw new Error(\n `${this.#parentClassName} could not determine its Durable Object name. ` +\n \"Address it with idFromName() or getByName(). In local development, \" +\n \"update Wrangler/workerd and use a current compatibility_date. \" +\n \"newUniqueId(), idFromString(), and names over 1,024 bytes do not \" +\n \"expose ctx.id.name. Alarms created before 2026-03-15 must be \" +\n \"rescheduled from a named fetch or RPC handler.\"\n );\n }\n\n #props?: Props;\n\n /**\n * The host's scoped access to the Lifecycle work queue. Items pushed here\n * are dispatched to the host's `onJob` inside the host invocation\n * boundary.\n */\n get jobs(): LifecycleJobs {\n return this.#jobsForOwner(HOST_JOB_CAPABILITY);\n }\n\n #jobsForOwner(owner: string): LifecycleJobs {\n const rearmAfter = async <T>(mutate: () => T): Promise<T> => {\n const result = mutate();\n await this.rearmAlarm();\n return result;\n };\n return Object.freeze({\n push: (options: LifecycleJobPushOptions) =>\n rearmAfter(() => this.#jobQueue.push(owner, options)),\n cancel: (id: string) =>\n rearmAfter(() => this.#jobQueue.cancel(owner, id)),\n reschedule: (id: string, time: number) =>\n rearmAfter(() => this.#jobQueue.reschedule(owner, id, time)),\n get: (id: string) => this.#jobQueue.get(owner, id),\n list: () => this.#jobQueue.list(owner),\n rearm: () => this.rearmAlarm()\n });\n }\n\n /**\n * Recompute the physical Durable Object alarm from job-queue state.\n *\n * Concurrent requests are serialized so a later durable-state change cannot\n * be overwritten by an earlier alarm calculation. Queue mutations call this\n * automatically; it stays public for composition roots and tests.\n */\n async rearmAlarm(): Promise<void> {\n if (this.#alarmsDisabled) return;\n if (this.#status === \"starting\") {\n this.#rearmRequestedDuringStart = true;\n return;\n }\n\n const prior = this.#alarmRearmQueue;\n const next = prior\n .catch(() => {})\n .then(async () => {\n if (this.#alarmsDisabled) return;\n const alarm = this.#jobQueue.nextAlarmTime(Date.now());\n if (alarm === null) {\n await this.#ctx.storage.deleteAlarm();\n } else {\n await this.#ctx.storage.setAlarm(alarm);\n }\n });\n this.#alarmRearmQueue = next;\n await next;\n }\n\n /**\n * Keep work a job handed off at a bounded return inside the current\n * alarm's memory-limit breaker domain (#1825). Hosts call this where a\n * queue-driven callback detaches long work and returns.\n *\n * @returns True when called during an alarm invocation; false otherwise.\n */\n trackAlarmWork(work: Promise<unknown>): boolean {\n return this.#jobDriver.trackAlarmWork(work);\n }\n\n /** Dispose installed capabilities in reverse registration order. */\n async dispose(): Promise<void> {\n await runWithoutCurrentAgent(() => this.#capabilityRunner.dispose());\n }\n\n /** Permanently disable and clear alarms during explicit object teardown. */\n async disableAlarms(): Promise<void> {\n this.#alarmsDisabled = true;\n await this.#alarmRearmQueue.catch(() => {});\n await this.#ctx.storage.deleteAlarm();\n }\n\n /**\n * Run one alarm invocation. The job driver owns the event loop — deadman\n * pre-arm, due-job dispatch with retry and deferral policy, the alarm\n * memory-limit circuit breaker (#1825) — and re-arms the physical alarm\n * from queue state. The host's `onAlarm()` runs after due jobs, inside\n * the host invocation boundary.\n */\n async alarm(): Promise<void> {\n await this.#jobDriver.runAlarm(\n () => this.#ensureInitialized(),\n () =>\n runInLifecycleHostContext({ host: this.#host }, async () => {\n await this.#host.onAlarm?.();\n })\n );\n }\n\n /**\n * Resolve a job owner to its dispatch hooks. Host jobs run inside the\n * host invocation boundary; capability jobs run outside ambient host\n * context, like every other capability hook.\n */\n async #resolveJobDispatch(owner: string): Promise<JobDispatch | undefined> {\n if (owner === HOST_JOB_CAPABILITY) {\n const host = this.#host;\n if (!host.onJob) return undefined;\n // No host onJobError: a host job's terminal application failure\n // completes it, and the host re-derives its jobs from durable state.\n return {\n onJob: async (context) =>\n runInLifecycleHostContext({ host }, () => host.onJob!(context))\n };\n }\n const capability = await this.#capabilityRunner.findById(owner);\n if (!capability?.onJob) return undefined;\n return {\n onJob: async (context) =>\n runWithoutCurrentAgent(() => capability.onJob!(context)),\n onJobError: capability.onJobError\n ? async (context, error) =>\n runWithoutCurrentAgent(() => capability.onJobError!(context, error))\n : undefined\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0NA,IAAa,mBAAb,MAA6D;;;;;;;CAa3D,YACE,qBACA;;;;;6CAVS,KAAA;EAWT,uBAAA,sBAAA,MAA4B,mBAAA;CAC9B;;;;;;;;;CAUA,MAAM,MAAM,SAAuD;EACjE,IAAA,uBAAA,UAAI,IAAA,GAAe;EAEnB,MAAM,UAAA,uBAAA,eAAU,IAAA;EAChB,IAAI,SAAS;GACX,MAAM;GACN;EACF;EAEA,MAAM,UAAA,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;;;;;;;;CASA,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;GACh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