@effect-agent/platform-cloudflare 0.1.0-beta.6 → 0.1.0-beta.60

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 (95) hide show
  1. package/dist/Alarm.d.mts +168 -0
  2. package/dist/Alarm.mjs +415 -0
  3. package/dist/Alarm.mjs.map +1 -0
  4. package/dist/BrowserRestCapture.d.mts +35 -0
  5. package/dist/BrowserRestCapture.mjs +238 -0
  6. package/dist/BrowserRestCapture.mjs.map +1 -0
  7. package/dist/BrowserRestCrawl.d.mts +17 -0
  8. package/dist/BrowserRestCrawl.mjs +244 -0
  9. package/dist/BrowserRestCrawl.mjs.map +1 -0
  10. package/dist/CloudflareBindings.d.mts +105 -0
  11. package/dist/CloudflareBindings.mjs +98 -0
  12. package/dist/CloudflareBindings.mjs.map +1 -0
  13. package/dist/CloudflareBrowser-Bj22nNUT.mjs +466 -0
  14. package/dist/CloudflareBrowser-Bj22nNUT.mjs.map +1 -0
  15. package/dist/CloudflareBrowser-DJq53niJ.d.mts +80 -0
  16. package/dist/CloudflareBrowser.d.mts +2 -0
  17. package/dist/CloudflareBrowser.mjs +2 -0
  18. package/dist/CloudflareCodeMode.d.mts +44 -0
  19. package/dist/CloudflareCodeMode.mjs +611 -0
  20. package/dist/CloudflareCodeMode.mjs.map +1 -0
  21. package/dist/CloudflareConfig-f3CqTel1.d.mts +101 -0
  22. package/dist/CloudflareConfig.d.mts +2 -0
  23. package/dist/CloudflareConfig.mjs +122 -0
  24. package/dist/CloudflareConfig.mjs.map +1 -0
  25. package/dist/CloudflareMemory.d.mts +140 -0
  26. package/dist/CloudflareMemory.mjs +168 -0
  27. package/dist/CloudflareMemory.mjs.map +1 -0
  28. package/dist/CloudflareScheduling.d.mts +52 -0
  29. package/dist/CloudflareScheduling.mjs +389 -0
  30. package/dist/CloudflareScheduling.mjs.map +1 -0
  31. package/dist/CloudflareSubscriptions.d.mts +87 -0
  32. package/dist/CloudflareSubscriptions.mjs +524 -0
  33. package/dist/CloudflareSubscriptions.mjs.map +1 -0
  34. package/dist/CloudflareThreadClient.d.mts +1214 -0
  35. package/dist/CloudflareThreadClient.mjs +386 -0
  36. package/dist/CloudflareThreadClient.mjs.map +1 -0
  37. package/dist/InteractiveBrowser.d.mts +144 -0
  38. package/dist/InteractiveBrowser.mjs +1090 -0
  39. package/dist/InteractiveBrowser.mjs.map +1 -0
  40. package/dist/ProtectedBrowser.d.mts +65 -0
  41. package/dist/ProtectedBrowser.mjs +859 -0
  42. package/dist/ProtectedBrowser.mjs.map +1 -0
  43. package/dist/ThreadObject-CvnEnVQH.d.mts +772 -0
  44. package/dist/ThreadObject-s5w3V_co.mjs +675 -0
  45. package/dist/ThreadObject-s5w3V_co.mjs.map +1 -0
  46. package/dist/ThreadObject.d.mts +2 -0
  47. package/dist/ThreadObject.mjs +3 -0
  48. package/dist/WakeScheduler.d.mts +23 -0
  49. package/dist/WakeScheduler.mjs +60 -0
  50. package/dist/WakeScheduler.mjs.map +1 -0
  51. package/dist/boundary-BguazVkh.mjs +42 -0
  52. package/dist/boundary-BguazVkh.mjs.map +1 -0
  53. package/dist/browser-session-lifecycle-CUbVfEgP.mjs +84 -0
  54. package/dist/browser-session-lifecycle-CUbVfEgP.mjs.map +1 -0
  55. package/dist/browser-session-lifecycle-DJpqLXy_.d.mts +21 -0
  56. package/dist/index.d.mts +12 -1543
  57. package/dist/index.mjs +12 -1636
  58. package/dist/prepared-admission-G7N4DDqS.mjs +73 -0
  59. package/dist/prepared-admission-G7N4DDqS.mjs.map +1 -0
  60. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  61. package/package.json +1 -53
  62. package/src/Alarm.ts +862 -0
  63. package/src/BrowserRestCapture.ts +477 -0
  64. package/src/BrowserRestCrawl.ts +540 -0
  65. package/src/CloudflareBindings.ts +171 -0
  66. package/src/CloudflareBrowser.ts +15 -0
  67. package/src/{code-mode-executor.ts → CloudflareCodeMode.ts} +367 -204
  68. package/src/{config.ts → CloudflareConfig.ts} +9 -8
  69. package/src/CloudflareMemory.ts +359 -0
  70. package/src/CloudflareScheduling.ts +733 -0
  71. package/src/CloudflareSubscriptions.ts +1045 -0
  72. package/src/CloudflareThreadClient.ts +807 -0
  73. package/src/InteractiveBrowser.ts +2357 -0
  74. package/src/ProtectedBrowser.ts +2 -0
  75. package/src/{conversation-object.ts → ThreadObject.ts} +423 -239
  76. package/src/{wake-scheduler.ts → WakeScheduler.ts} +23 -23
  77. package/src/index.ts +11 -23
  78. package/src/internal/boundary.ts +55 -0
  79. package/src/internal/browser-quick-action.ts +818 -0
  80. package/src/internal/browser-session-lifecycle.ts +160 -0
  81. package/src/internal/layers.ts +615 -0
  82. package/src/internal/message-delivery.ts +90 -0
  83. package/src/internal/prepared-admission.ts +116 -0
  84. package/src/internal/progress-wait.ts +121 -0
  85. package/src/internal/transport.ts +42 -0
  86. package/src/protected-browser/binding.ts +187 -0
  87. package/src/protected-browser/inspect-frame.ts +125 -0
  88. package/src/protected-browser/native.ts +429 -0
  89. package/src/protected-browser/policy.ts +719 -0
  90. package/dist/index.mjs.map +0 -1
  91. package/src/alarm.ts +0 -334
  92. package/src/bindings.ts +0 -145
  93. package/src/client.ts +0 -646
  94. package/src/layers.ts +0 -376
  95. package/src/transport.ts +0 -38
package/src/Alarm.ts ADDED
@@ -0,0 +1,862 @@
1
+ import { type DurableBindingFailure } from "@effect-agent/thread/AgentRegistration";
2
+ import {
3
+ DurableAgentRuntime,
4
+ type DurableWorkerFailure,
5
+ type RecoveryReport,
6
+ } from "@effect-agent/thread/DurableAgentRuntime";
7
+ import { SubmissionLedger, type SubmissionSnapshot } from "@effect-agent/thread/SubmissionLedger";
8
+ import {
9
+ ThreadProjectionMaintenance,
10
+ drainDue,
11
+ type ThreadProjectionError,
12
+ } from "@effect-agent/thread/ThreadProjectionMaintenance";
13
+ import {
14
+ Cause,
15
+ Clock,
16
+ Context,
17
+ DateTime,
18
+ Effect,
19
+ Exit,
20
+ Fiber,
21
+ Layer,
22
+ Option,
23
+ Random,
24
+ Ref,
25
+ Schema,
26
+ Semaphore,
27
+ Stream,
28
+ } from "effect";
29
+
30
+ import { ThreadObjectIdentity, DurableObjectContext } from "./CloudflareBindings.ts";
31
+ import { CloudflareDurableRuntimeConfig } from "./CloudflareConfig.ts";
32
+ import { safeCauseMessage } from "./internal/boundary.ts";
33
+
34
+ /**
35
+ * The single multiplexed Durable Object alarm (decision D-P6-2). A Durable Object has ONE
36
+ * alarm slot; every cadence the Node host ran on fibers (wake scan, lease expiry, settlement
37
+ * and abort re-checks, retry backoff) multiplexes into one idempotent maintenance pass, and
38
+ * the slot always holds the EARLIEST deadline any caller asked for.
39
+ *
40
+ * The alarm invariant (plan §1.4): every committed actionable mutation carries a newer durable
41
+ * maintenance generation and a committed alarm. Stable externally-driven waits may be
42
+ * nonterminal without retaining an alarm; their resolving mutation advances the generation and
43
+ * restores the alarm atomically.
44
+ */
45
+
46
+ /** The Durable Object alarm API failed; surfaces on host entry points as a typed refusal. */
47
+ export class DurableAlarmError extends Schema.TaggedError<DurableAlarmError>()(
48
+ "DurableAlarmError",
49
+ {
50
+ operation: Schema.String,
51
+ message: Schema.String,
52
+ cause: Schema.optionalKey(Schema.Defect()),
53
+ },
54
+ ) {}
55
+
56
+ const alarmFailure =
57
+ (operation: string) =>
58
+ (cause: unknown): DurableAlarmError =>
59
+ DurableAlarmError.make({
60
+ operation,
61
+ message: safeCauseMessage(cause, "The Cloudflare alarm API failed without a diagnostic"),
62
+ cause,
63
+ });
64
+
65
+ /** `ctx.storage` alarm slot as an Effect service; storage is truth, never a memory field. */
66
+ export class DurableAlarmService extends Context.Service<
67
+ DurableAlarmService,
68
+ {
69
+ /** The scheduled deadline in epoch milliseconds, if any. */
70
+ readonly scheduled: Effect.Effect<Option.Option<number>, DurableAlarmError>;
71
+ /** Replace the slot with this deadline. */
72
+ readonly scheduleAt: (epochMillis: number) => Effect.Effect<void, DurableAlarmError>;
73
+ /** Keep the EARLIER of the existing deadline and this one (the multiplexing rule). */
74
+ readonly ensureScheduledBy: (epochMillis: number) => Effect.Effect<void, DurableAlarmError>;
75
+ /**
76
+ * Arm an immediate alarm (the durable, coalescing local wake) — DEFERRED while a
77
+ * maintenance pass is executing. Workerd cancels an in-flight alarm handler when a new
78
+ * EARLIER deadline is written during its execution (`requestScheduledAlarm`), and the
79
+ * maintenance pass runs INSIDE the alarm handler: an immediate wake landing mid-pass
80
+ * (a routed port mutation, a sibling's `wake()`, the coordinator's own local notify)
81
+ * would kill the running Attempt — manufacturing an ownership loss no real eviction
82
+ * caused, and routing open uncertain-class Tool Calls into spurious Unknown Outcomes.
83
+ * Deferral is contract-safe: wakes are droppable hints, every mutating entry point
84
+ * pre-arms BEFORE its first durable mutation (the alarm invariant never rests on this
85
+ * call). The pass's durable generation check observes any racing mutation, so the
86
+ * in-memory hint does not need to be flushed after a stable wait is acknowledged.
87
+ */
88
+ readonly scheduleNow: Effect.Effect<void, DurableAlarmError>;
89
+ /**
90
+ * Run one maintenance pass with wake deferral (see `scheduleNow`). Calls made while `body`
91
+ * executes are droppable promptness hints; correctness rests on the durable generation.
92
+ */
93
+ readonly withWakesDeferred: <A, E, R>(body: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
94
+ /** Clear the slot; correctness-sensitive clears live in maintenance generation transactions. */
95
+ readonly cancel: Effect.Effect<void, DurableAlarmError>;
96
+ }
97
+ >()("@effect-agent/platform-cloudflare/DurableAlarmService") {
98
+ static readonly layer: Layer.Layer<DurableAlarmService, never, DurableObjectContext> =
99
+ Layer.effect(DurableAlarmService)(
100
+ Effect.gen(function* () {
101
+ const { ctx } = yield* DurableObjectContext;
102
+ /**
103
+ * In-memory pass bookkeeping — a pure CACHE, never state: a fresh incarnation has no
104
+ * running pass, and a deferred wake lost to eviction was only ever a promptness hint
105
+ * on top of the already-committed pre-armed alarm.
106
+ */
107
+ const runningPasses = yield* Ref.make(0);
108
+
109
+ const scheduled = Effect.tryPromise({
110
+ try: () => ctx.storage.getAlarm(),
111
+ catch: alarmFailure("get alarm"),
112
+ }).pipe(
113
+ Effect.map((deadline) =>
114
+ deadline === null ? Option.none<number>() : Option.some(deadline),
115
+ ),
116
+ );
117
+
118
+ const scheduleAt = (epochMillis: number) =>
119
+ Effect.tryPromise({
120
+ try: () => ctx.storage.setAlarm(epochMillis),
121
+ catch: alarmFailure("set alarm"),
122
+ });
123
+
124
+ const ensureScheduledBy = (epochMillis: number) =>
125
+ scheduled.pipe(
126
+ Effect.flatMap((existing) =>
127
+ Option.isSome(existing) && existing.value <= epochMillis
128
+ ? Effect.void
129
+ : scheduleAt(epochMillis),
130
+ ),
131
+ );
132
+
133
+ const armNow = Clock.currentTimeMillis.pipe(
134
+ Effect.flatMap((now) => ensureScheduledBy(now)),
135
+ );
136
+
137
+ const scheduleNow = Ref.get(runningPasses).pipe(
138
+ Effect.flatMap((passes) => (passes > 0 ? Effect.void : armNow)),
139
+ );
140
+
141
+ const withWakesDeferred = <A, E, R>(body: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
142
+ Ref.update(runningPasses, (passes) => passes + 1).pipe(
143
+ Effect.andThen(body),
144
+ Effect.ensuring(Ref.update(runningPasses, (passes) => passes - 1)),
145
+ );
146
+
147
+ const cancel = Effect.tryPromise({
148
+ try: () => ctx.storage.deleteAlarm(),
149
+ catch: alarmFailure("delete alarm"),
150
+ });
151
+
152
+ return DurableAlarmService.of({
153
+ scheduled,
154
+ scheduleAt,
155
+ ensureScheduledBy,
156
+ scheduleNow,
157
+ withWakesDeferred,
158
+ cancel,
159
+ });
160
+ }),
161
+ );
162
+ }
163
+
164
+ /** What one maintenance pass did — auditable evidence mirroring `NodeDurableHost`'s report. */
165
+ export class MaintenancePassReport extends Schema.Class<MaintenancePassReport>(
166
+ "@effect-agent/platform-cloudflare/MaintenancePassReport",
167
+ )({
168
+ /** `caught-up` ran no runtime work (publication may be pending); `actionable` ran recovery. */
169
+ phase: Schema.Literals(["caught-up", "actionable"]),
170
+ /** Recovery decisions executed (or deferred) BEFORE any new claim in this pass. */
171
+ recovered: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
172
+ /** Whether the head Attempt settled. Joined input may settle with that head. */
173
+ settled: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
174
+ /** Submissions still nonterminal after the pass (suspended/unknown lanes stay honest). */
175
+ nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
176
+ /** `rearmed` for dirty/autonomous work, `cleared` for stable waits or settlement. */
177
+ alarm: Schema.Literals(["rearmed", "cleared"]),
178
+ }) {}
179
+
180
+ /** Fault boundaries around every maintenance-owned durable mutation. */
181
+ export type ThreadMaintenanceFailpointLocation =
182
+ | "maintenance:dirty:before"
183
+ | "maintenance:dirty:after"
184
+ | "maintenance:mutation:armed"
185
+ | "maintenance:mutation:finished"
186
+ | "maintenance:ensure:before"
187
+ | "maintenance:ensure:after"
188
+ | "maintenance:begin:before"
189
+ | "maintenance:begin:after"
190
+ | "maintenance:finish:before"
191
+ | "maintenance:finish:after";
192
+
193
+ export type ThreadMaintenanceFailpointHandler = (
194
+ location: ThreadMaintenanceFailpointLocation,
195
+ ) => Effect.Effect<void>;
196
+
197
+ /** Test-only fault authority; production uses the inert layer. */
198
+ export class ThreadMaintenanceFailpoint extends Context.Service<
199
+ ThreadMaintenanceFailpoint,
200
+ {
201
+ readonly hit: ThreadMaintenanceFailpointHandler;
202
+ }
203
+ >()("@effect-agent/platform-cloudflare/ThreadMaintenanceFailpoint") {
204
+ static readonly layer = Layer.succeed(this)({ hit: () => Effect.void });
205
+ }
206
+
207
+ /**
208
+ * Durable host publication of canonical records and ledger approval/abort/resolution intents.
209
+ * The host owns schema-versioned cursors, destination idempotency and acknowledgement. Delivery
210
+ * is at least once. Hooks must not write the alarm slot or mutate the supplied raw source ports.
211
+ *
212
+ * `invalidate`, `prepareGeneration` and `pendingDeadline` must be bounded local operations.
213
+ * `prepareGeneration` durably invalidates a scan only when its generation changes; repeated
214
+ * calls must preserve partial scan progress. It runs with no source mutation in flight.
215
+ * `drain` performs bounded delivery and persists retries before returning. A pending deadline
216
+ * defers runtime recovery/Attempts, allowing committed host publications to drain first.
217
+ * Unexpected hook failures leave the prearmed generation for retry. Hooks acquire per-call
218
+ * resources with Effect.scoped; Layer construction owns incarnation resources (eviction need
219
+ * not run finalizers). Do not hold a local hook behind network I/O or call back into producers.
220
+ */
221
+ export interface ThreadPublicationService {
222
+ readonly invalidate: Effect.Effect<void, DurableAlarmError>;
223
+ readonly prepareGeneration: (generation: bigint) => Effect.Effect<void, DurableAlarmError>;
224
+ readonly drain: Effect.Effect<void, DurableAlarmError>;
225
+ readonly pendingDeadline: Effect.Effect<Option.Option<number>, DurableAlarmError>;
226
+ }
227
+
228
+ /** Opt in with `ThreadObject.layer(registrations, { publication: Layer.effect(ThreadPublication)(...) })`. */
229
+ export class ThreadPublication extends Context.Service<
230
+ ThreadPublication,
231
+ ThreadPublicationService
232
+ >()("@effect-agent/platform-cloudflare/ThreadPublication") {
233
+ static readonly layer = Layer.succeed(this)({
234
+ invalidate: Effect.void,
235
+ prepareGeneration: () => Effect.void,
236
+ drain: Effect.void,
237
+ pendingDeadline: Effect.succeed(Option.none()),
238
+ });
239
+ }
240
+
241
+ /**
242
+ * @internal Host-assembled message recovery. These obligations outlive source Runs and never
243
+ * defer a ready source Attempt while a destination is processing an accepted message.
244
+ */
245
+ export const ThreadMessageDelivery = Context.Reference<{
246
+ readonly drain: Effect.Effect<void, DurableAlarmError>;
247
+ readonly pendingDeadline: Effect.Effect<Option.Option<number>, DurableAlarmError>;
248
+ }>("@effect-agent/platform-cloudflare/ThreadMessageDelivery", {
249
+ defaultValue: () => ({ drain: Effect.void, pendingDeadline: Effect.succeed(Option.none()) }),
250
+ });
251
+
252
+ const earliestDeadline = (
253
+ left: Option.Option<number>,
254
+ right: Option.Option<number>,
255
+ ): Option.Option<number> =>
256
+ Option.isSome(left)
257
+ ? Option.isSome(right)
258
+ ? Option.some(Math.min(left.value, right.value))
259
+ : left
260
+ : right;
261
+
262
+ /** @internal A committed source operation must not become a failed operation because delivery failed. */
263
+ export const publishCommitted = Effect.gen(function* () {
264
+ const publication = yield* ThreadPublication;
265
+
266
+ yield* publication.invalidate.pipe(Effect.andThen(publication.drain));
267
+ }).pipe(
268
+ Effect.catchCause((cause) =>
269
+ Cause.hasInterrupts(cause)
270
+ ? Effect.interrupt
271
+ : Effect.logError("Thread publication deferred after source commit", cause),
272
+ ),
273
+ );
274
+
275
+ const MaintenanceGeneration = Schema.BigIntFromString.check(
276
+ Schema.isGreaterThanOrEqualToBigInt(0n),
277
+ );
278
+
279
+ /** Versioned, platform-private maintenance state stored through Durable Object KV. */
280
+ class ThreadMaintenanceState extends Schema.Class<ThreadMaintenanceState>(
281
+ "@effect-agent/platform-cloudflare/ThreadMaintenanceState",
282
+ )({
283
+ schemaVersion: Schema.Literal(1),
284
+ dirty: MaintenanceGeneration,
285
+ processed: MaintenanceGeneration,
286
+ nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
287
+ }) {}
288
+
289
+ const MAINTENANCE_STATE_KEY = "effect-agent:thread-maintenance:v1";
290
+ const decodeMaintenanceState = Schema.decodeUnknownSync(ThreadMaintenanceState);
291
+ const encodeMaintenanceState = Schema.encodeSync(ThreadMaintenanceState);
292
+
293
+ const initialMaintenanceState = (): ThreadMaintenanceState =>
294
+ ThreadMaintenanceState.make({
295
+ schemaVersion: 1,
296
+ // Bootstrap Objects created by the pre-generation release without scanning the ledger in
297
+ // the constructor. One useful pass classifies and acknowledges any existing obligation.
298
+ dirty: 1n,
299
+ processed: 0n,
300
+ nonterminal: 0,
301
+ });
302
+
303
+ const readMaintenanceState = async (
304
+ transaction: DurableObjectTransaction,
305
+ ): Promise<{ readonly state: ThreadMaintenanceState; readonly initialized: boolean }> => {
306
+ const encoded = await transaction.get(MAINTENANCE_STATE_KEY);
307
+
308
+ return encoded === undefined
309
+ ? { state: initialMaintenanceState(), initialized: false }
310
+ : { state: decodeMaintenanceState(encoded), initialized: true };
311
+ };
312
+
313
+ const ensureTransactionAlarmBy = async (
314
+ transaction: DurableObjectTransaction,
315
+ deadline: number,
316
+ ): Promise<void> => {
317
+ const scheduled = await transaction.getAlarm();
318
+
319
+ if (scheduled === null || scheduled > deadline) {
320
+ await transaction.setAlarm(deadline);
321
+ }
322
+ };
323
+
324
+ const stableExternalWait = (
325
+ snapshot: SubmissionSnapshot,
326
+ reports: ReadonlyMap<string, RecoveryReport>,
327
+ ): boolean => {
328
+ const decision = reports.get(snapshot.submissionId)?.decision._tag;
329
+
330
+ // An accepted abort still owes cleanup/settlement even if its claim was deferred this pass.
331
+ if (decision === "SettleAborted") return false;
332
+ switch (snapshot.state) {
333
+ case "suspended":
334
+ case "joined":
335
+ return true;
336
+ case "unknown":
337
+ return decision === "AwaitUnknownResolution" || decision === "MarkUnknown";
338
+ case "admitted":
339
+ return reports.get(snapshot.submissionId)?.decision._tag === "AwaitParentEstablishment";
340
+ case "input-applied":
341
+ case "joining":
342
+ case "ready":
343
+ case "running":
344
+ case "settled":
345
+ case "terminalizing":
346
+ return false;
347
+ }
348
+ };
349
+
350
+ /**
351
+ * Shared prearm/acknowledgement boundary for ingress and runtime-owned producers.
352
+ * `ThreadObject.layer` provides this same instance in its Services. Rebuilt runtime/maintenance
353
+ * Layers must reuse that instance; a second gate cannot observe the native producers' activity.
354
+ */
355
+ export class ThreadMutationGate extends Context.Service<
356
+ ThreadMutationGate,
357
+ {
358
+ readonly withMutation: <A, E, R>(
359
+ body: Effect.Effect<A, E, R>,
360
+ ) => Effect.Effect<A, E | DurableAlarmError, R>;
361
+ readonly withSnapshot: <A, E, R>(
362
+ body: (active: number) => Effect.Effect<A, E, R>,
363
+ ) => Effect.Effect<A, E, R>;
364
+ }
365
+ >()("@effect-agent/platform-cloudflare/internal/ThreadMutationGate") {
366
+ static readonly layer = Layer.effect(this)(
367
+ Effect.gen(function* () {
368
+ const { ctx } = yield* DurableObjectContext;
369
+ const config = yield* CloudflareDurableRuntimeConfig;
370
+ const failpoint = yield* ThreadMaintenanceFailpoint;
371
+ // A fresh incarnation has no live mutations; durable generations survive eviction.
372
+ const activeMutations = yield* Ref.make(0);
373
+ const generationGate = yield* Semaphore.make(1);
374
+ const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));
375
+
376
+ const runTransaction = <A>(operation: string, transaction: () => Promise<A>) =>
377
+ Effect.tryPromise({ try: transaction, catch: alarmFailure(operation) });
378
+
379
+ const beginMutation = Effect.fn("ThreadMaintenance.beginMutation")(function* () {
380
+ yield* failpoint.hit("maintenance:dirty:before");
381
+ const now = yield* Clock.currentTimeMillis;
382
+
383
+ yield* runTransaction("advance maintenance generation", () =>
384
+ ctx.storage.transaction(async (transaction) => {
385
+ const { state } = await readMaintenanceState(transaction);
386
+
387
+ const next = ThreadMaintenanceState.make({
388
+ ...state,
389
+ dirty: state.dirty + 1n,
390
+ });
391
+
392
+ await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));
393
+ // The earliest configured retry bounds a newly actionable mutation without relying
394
+ // on its best-effort immediate wake hint.
395
+ await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);
396
+ }),
397
+ );
398
+ yield* failpoint.hit("maintenance:dirty:after");
399
+ yield* Ref.update(activeMutations, (active) => active + 1);
400
+ });
401
+
402
+ const endMutation = generationGate.withPermit(
403
+ Ref.update(activeMutations, (active) => Math.max(0, active - 1)),
404
+ );
405
+
406
+ const withMutation = <A, E, R>(
407
+ body: Effect.Effect<A, E, R>,
408
+ ): Effect.Effect<A, E | DurableAlarmError, R> =>
409
+ Effect.acquireUseRelease(
410
+ generationGate.withPermit(beginMutation()),
411
+ () =>
412
+ failpoint.hit("maintenance:mutation:armed").pipe(
413
+ Effect.andThen(body),
414
+ Effect.tap(() => failpoint.hit("maintenance:mutation:finished")),
415
+ ),
416
+ () => endMutation,
417
+ );
418
+
419
+ return ThreadMutationGate.of({
420
+ withMutation,
421
+ withSnapshot: (body) =>
422
+ generationGate.withPermit(Effect.flatMap(Ref.get(activeMutations), body)),
423
+ });
424
+ }),
425
+ );
426
+ }
427
+
428
+ export type MaintenancePassFailure =
429
+ | DurableWorkerFailure
430
+ | DurableBindingFailure
431
+ | DurableAlarmError
432
+ | ThreadProjectionError;
433
+
434
+ /**
435
+ * Incremental, quiescent maintenance over a durable dirty/processed generation (issue #93).
436
+ *
437
+ * `pass` = generation snapshot/pre-arm → recovery → one head Attempt → generation acknowledgement:
438
+ *
439
+ * 1. One storage transaction reads dirty/processed and re-arms before work. A caught-up forced
440
+ * alarm takes an O(1) path without recovery, ledger scans, or canonical-history reads.
441
+ * 2. Recovery strictly precedes a new claim. One head Attempt advances the lane and requests
442
+ * a safe yield after ten minutes. The whole event has a fourteen-minute cooperative timeout.
443
+ * 3. The final transaction acknowledges only the generation observed at pass start. A racing
444
+ * mutation therefore remains `dirty > processed` and retains its atomically-established alarm.
445
+ * 4. Stable external waits acknowledge and clear. Autonomous retry, indeterminate, and lease
446
+ * recovery states leave their generation dirty and retain bounded backoff rearming.
447
+ */
448
+ export class ThreadMaintenance extends Context.Service<
449
+ ThreadMaintenance,
450
+ {
451
+ /** One idempotent maintenance pass; failures propagate so workerd retries the alarm. */
452
+ readonly pass: Effect.Effect<MaintenancePassReport, MaintenancePassFailure>;
453
+ /**
454
+ * Constructor gate: initialize/inspect only the O(1) maintenance record and ensure a dirty
455
+ * generation has an alarm. It never scans the ledger or canonical history.
456
+ */
457
+ readonly ensureAlarm: Effect.Effect<void, MaintenancePassFailure>;
458
+ /**
459
+ * Serialize the pre-arm boundary with pass acknowledgement, advance the durable dirty
460
+ * generation and arm the alarm in one transaction BEFORE running the caller's mutation.
461
+ * A pass cannot acknowledge while that mutation remains in flight.
462
+ */
463
+ readonly withMutation: <A, E, R>(
464
+ body: Effect.Effect<A, E, R>,
465
+ ) => Effect.Effect<A, E | DurableAlarmError, R>;
466
+ }
467
+ >()("@effect-agent/platform-cloudflare/ThreadMaintenance") {
468
+ static readonly layer: Layer.Layer<
469
+ ThreadMaintenance,
470
+ never,
471
+ | ThreadMutationGate
472
+ | ThreadPublication
473
+ | ThreadProjectionMaintenance
474
+ | DurableAgentRuntime
475
+ | SubmissionLedger
476
+ | DurableAlarmService
477
+ | ThreadMaintenanceFailpoint
478
+ | CloudflareDurableRuntimeConfig
479
+ | ThreadObjectIdentity
480
+ | DurableObjectContext
481
+ > = Layer.effect(ThreadMaintenance)(
482
+ Effect.gen(function* () {
483
+ const runtime = yield* DurableAgentRuntime;
484
+ const ledger = yield* SubmissionLedger;
485
+ const alarm = yield* DurableAlarmService;
486
+ const config = yield* CloudflareDurableRuntimeConfig;
487
+ const identity = yield* ThreadObjectIdentity;
488
+ const { ctx } = yield* DurableObjectContext;
489
+ const failpoint = yield* ThreadMaintenanceFailpoint;
490
+
491
+ /**
492
+ * Consecutive no-progress passes — an in-memory CACHE, not state: a fresh incarnation
493
+ * restarts at zero and merely re-arms sooner than a long-lived one would have.
494
+ */
495
+ const stalls = yield* Ref.make(0);
496
+ const mutations = yield* ThreadMutationGate;
497
+ const publication = yield* ThreadPublication;
498
+ const projection = yield* ThreadProjectionMaintenance;
499
+ const messages = yield* ThreadMessageDelivery;
500
+
501
+ // A broken disposable index still needs a retry alarm and must not prevent startup.
502
+ const projectionDeadline = projection.pendingDeadline.pipe(
503
+ Effect.catchCause((cause) =>
504
+ Cause.hasInterrupts(cause)
505
+ ? Effect.failCause(cause)
506
+ : Effect.logError("Thread projection deadline unavailable", cause).pipe(
507
+ Effect.as(Option.some(0)),
508
+ ),
509
+ ),
510
+ );
511
+
512
+ const pendingDeadline = Effect.gen(function* () {
513
+ return earliestDeadline(
514
+ earliestDeadline(yield* publication.pendingDeadline, yield* messages.pendingDeadline),
515
+ yield* projectionDeadline,
516
+ );
517
+ });
518
+
519
+ const maintenancePassGate = yield* Semaphore.make(1);
520
+ const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));
521
+
522
+ const runTransaction = <A>(operation: string, transaction: () => Promise<A>) =>
523
+ Effect.tryPromise({ try: transaction, catch: alarmFailure(operation) });
524
+
525
+ const ensureAlarm = Effect.fn("ThreadMaintenance.ensureAlarm")(function* () {
526
+ yield* failpoint.hit("maintenance:ensure:before");
527
+ const now = yield* Clock.currentTimeMillis;
528
+
529
+ yield* runTransaction("ensure maintenance alarm", () =>
530
+ ctx.storage.transaction(async (transaction) => {
531
+ const { state, initialized } = await readMaintenanceState(transaction);
532
+
533
+ if (!initialized) {
534
+ await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));
535
+ }
536
+ if (state.dirty > state.processed) {
537
+ await ensureTransactionAlarmBy(transaction, now + config.wakeScanInterval);
538
+ }
539
+ }),
540
+ );
541
+ const deadline = yield* pendingDeadline;
542
+
543
+ if (Option.isSome(deadline)) {
544
+ yield* runTransaction("ensure publication alarm", () =>
545
+ ctx.storage.transaction((transaction) =>
546
+ ensureTransactionAlarmBy(
547
+ transaction,
548
+ Math.max(now + minimumAlarmDelay, deadline.value),
549
+ ),
550
+ ),
551
+ );
552
+ }
553
+ yield* failpoint.hit("maintenance:ensure:after");
554
+ });
555
+
556
+ const beginPass = Effect.fn("ThreadMaintenance.beginPass")(function* () {
557
+ yield* failpoint.hit("maintenance:begin:before");
558
+ const now = yield* Clock.currentTimeMillis;
559
+
560
+ const result = yield* runTransaction("begin maintenance pass", () =>
561
+ ctx.storage.transaction(async (transaction) => {
562
+ const { state, initialized } = await readMaintenanceState(transaction);
563
+
564
+ if (!initialized) {
565
+ await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));
566
+ }
567
+ if (state.processed >= state.dirty) {
568
+ // Prearm even a publication-only pass before invoking any host hook.
569
+ await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);
570
+
571
+ return { _tag: "CaughtUp" as const, nonterminal: state.nonterminal };
572
+ }
573
+ // Pre-arm the earliest retry before recovery. A successful finish may move this slot
574
+ // LATER to its bounded backoff, which does not cancel the running handler.
575
+ await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);
576
+
577
+ return {
578
+ _tag: "Actionable" as const,
579
+ generation: state.dirty,
580
+ nonterminal: state.nonterminal,
581
+ };
582
+ }),
583
+ );
584
+
585
+ yield* failpoint.hit("maintenance:begin:after");
586
+
587
+ return result;
588
+ });
589
+
590
+ const rearmDelay = Effect.fn("ThreadMaintenance.rearmDelay")(function* (progressed: boolean) {
591
+ const priorStalls = yield* Ref.getAndUpdate(stalls, (count) =>
592
+ progressed ? 0 : count + 1,
593
+ );
594
+
595
+ if (progressed) return config.alarmBackoffBase;
596
+ const exponent = Math.min(priorStalls, 30);
597
+ const backoff = Math.min(config.alarmBackoffCap, config.alarmBackoffBase * 2 ** exponent);
598
+ const jitter = yield* Random.next;
599
+ // Full jitter over [backoff/2, backoff]: desynchronizes retry storms without ever
600
+ // waiting longer than the deterministic bound.
601
+ const jittered = Math.ceil(backoff / 2 + (backoff / 2) * jitter);
602
+
603
+ return Math.min(jittered, config.wakeScanInterval);
604
+ });
605
+
606
+ const pass = Effect.fn("ThreadMaintenance.pass")(function* (
607
+ yieldAfter: DateTime.Utc,
608
+ ): Effect.fn.Return<MaintenancePassReport, MaintenancePassFailure> {
609
+ const annotate = (report: MaintenancePassReport) =>
610
+ Effect.annotateCurrentSpan({
611
+ phase: report.phase,
612
+ recovered: report.recovered,
613
+ settled: report.settled,
614
+ nonterminal: report.nonterminal,
615
+ alarm: report.alarm,
616
+ }).pipe(Effect.as(report));
617
+
618
+ const started = yield* mutations.withSnapshot((activeAtStart) =>
619
+ Effect.gen(function* () {
620
+ const generation = yield* beginPass();
621
+
622
+ if (generation._tag === "Actionable" && activeAtStart === 0) {
623
+ // The gate excludes a producer starting between the snapshot and certification.
624
+ yield* publication.prepareGeneration(generation.generation);
625
+ }
626
+
627
+ return { ...generation, activeAtStart };
628
+ }),
629
+ );
630
+
631
+ // Run one bounded message wave beside source work. Slow destination admission or
632
+ // status RPCs cannot consume the source Attempt's execution window. Join before
633
+ // acknowledging the alarm so the final deadline includes all delivery mutations.
634
+ const delivery = yield* Effect.forkChild(messages.drain);
635
+
636
+ // Capture derived-index failures until canonical work has had its turn. Interruption
637
+ // still stops the event; ordinary failures and defects retain the prearmed generation.
638
+ const projected = yield* Effect.exit(
639
+ drainDue.pipe(Effect.provideService(ThreadProjectionMaintenance, projection)),
640
+ );
641
+
642
+ if (Exit.isFailure(projected) && Cause.hasInterrupts(projected.cause))
643
+ return yield* Effect.failCause(projected.cause);
644
+ const deadline = yield* publication.pendingDeadline;
645
+
646
+ if (
647
+ started._tag === "Actionable" ||
648
+ (Option.isSome(deadline) && deadline.value <= (yield* Clock.currentTimeMillis))
649
+ ) {
650
+ yield* publication.drain;
651
+ }
652
+ const pending = yield* publication.pendingDeadline;
653
+
654
+ if (started._tag === "CaughtUp" || Option.isSome(pending)) {
655
+ yield* Fiber.join(delivery);
656
+ if (Exit.isFailure(projected)) return yield* Effect.failCause(projected.cause);
657
+ yield* failpoint.hit("maintenance:finish:before");
658
+
659
+ const disposition = yield* mutations.withSnapshot((active) =>
660
+ Effect.gen(function* () {
661
+ // Re-read under the producer gate: a concurrent append/host mutation cannot be
662
+ // cleared using a stale empty deadline. Dirty generations bound all producer races.
663
+ const latest = yield* pendingDeadline;
664
+ const now = yield* Clock.currentTimeMillis;
665
+
666
+ return yield* runTransaction("finish publication pass", () =>
667
+ ctx.storage.transaction(async (transaction) => {
668
+ const { state } = await readMaintenanceState(transaction);
669
+
670
+ const nativeDeadline =
671
+ active > 0 || state.dirty > state.processed
672
+ ? now + config.wakeScanInterval
673
+ : Infinity;
674
+
675
+ const next = Option.isSome(latest)
676
+ ? Math.min(nativeDeadline, latest.value)
677
+ : nativeDeadline;
678
+
679
+ if (Number.isFinite(next)) {
680
+ await transaction.setAlarm(Math.max(now + minimumAlarmDelay, next));
681
+
682
+ return "rearmed" as const;
683
+ }
684
+ await transaction.deleteAlarm();
685
+
686
+ return "cleared" as const;
687
+ }),
688
+ );
689
+ }),
690
+ );
691
+
692
+ yield* failpoint.hit("maintenance:finish:after");
693
+
694
+ return yield* annotate(
695
+ MaintenancePassReport.make({
696
+ phase: "caught-up",
697
+ recovered: 0,
698
+ settled: 0,
699
+ nonterminal: started.nonterminal,
700
+ alarm: disposition,
701
+ }),
702
+ );
703
+ }
704
+ // Step 2 — reconciliation strictly precedes new work in this pass (exit gate).
705
+ const recovered: ReadonlyArray<RecoveryReport> = yield* runtime.runRecovery;
706
+ // One head Attempt per event. The runtime yields after a committed turn when the
707
+ // soft deadline is reached; queued followers belong to a subsequent alarm.
708
+ const settlement = yield* runtime.processThreadHead(identity.threadId, { yieldAfter });
709
+
710
+ yield* Fiber.join(delivery);
711
+ if (Exit.isFailure(projected)) return yield* Effect.failCause(projected.cause);
712
+ // Observe residual state before acknowledging this exact pass-start generation.
713
+ const remaining = yield* Stream.runCollect(ledger.scanNonterminal);
714
+ const reports = new Map(recovered.map((report) => [report.submissionId, report]));
715
+ const head = remaining[0];
716
+ const headWaiting = head !== undefined && stableExternalWait(head, reports);
717
+
718
+ const autonomous = remaining.some((snapshot, index) => {
719
+ // FIFO followers cannot execute through a stable external wait. Only plain queued
720
+ // input is dormant here; admission repairs and accepted aborts still need a pass.
721
+ if (
722
+ index > 0 &&
723
+ headWaiting &&
724
+ snapshot.state === "ready" &&
725
+ reports.get(snapshot.submissionId)?.decision._tag === "ApplyInput"
726
+ )
727
+ return false;
728
+
729
+ return !stableExternalWait(snapshot, reports);
730
+ });
731
+
732
+ const progressed =
733
+ Option.isSome(settlement) ||
734
+ recovered.some((report) => report.disposition === "repaired");
735
+
736
+ const delay = autonomous ? yield* rearmDelay(progressed) : 0;
737
+ const now = yield* Clock.currentTimeMillis;
738
+
739
+ yield* failpoint.hit("maintenance:finish:before");
740
+
741
+ const alarmDisposition = yield* mutations.withSnapshot((active) =>
742
+ Effect.gen(function* () {
743
+ const publicationDeadline = yield* pendingDeadline;
744
+
745
+ return yield* runTransaction("finish maintenance pass", () =>
746
+ ctx.storage.transaction(async (transaction) => {
747
+ const { state } = await readMaintenanceState(transaction);
748
+
749
+ // Autonomous work and in-flight mutations intentionally leave the observed
750
+ // generation dirty. Otherwise acknowledge only the pass-start generation.
751
+ const processed =
752
+ autonomous || started.activeAtStart > 0 || active > 0
753
+ ? state.processed
754
+ : state.processed > started.generation
755
+ ? state.processed
756
+ : started.generation;
757
+
758
+ const next = ThreadMaintenanceState.make({
759
+ ...state,
760
+ processed,
761
+ nonterminal: remaining.length,
762
+ });
763
+
764
+ await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));
765
+ if (autonomous) {
766
+ // Replace the crash-fallback slot with this pass's bounded backoff. The target
767
+ // is never earlier than the begin-pass fallback, so workerd does not cancel
768
+ // this running alarm handler before its report/span can complete.
769
+ await transaction.setAlarm(
770
+ Option.isSome(publicationDeadline)
771
+ ? Math.max(
772
+ now + minimumAlarmDelay,
773
+ Math.min(now + delay, publicationDeadline.value),
774
+ )
775
+ : now + delay,
776
+ );
777
+
778
+ return "rearmed" as const;
779
+ }
780
+ if (started.activeAtStart > 0 || active > 0 || next.dirty > next.processed) {
781
+ // A mutation overlapped this pass's observation window or raced
782
+ // acknowledgement. It stays dirty and its pre-armed bounded alarm survives;
783
+ // unseen effects are never acknowledged. Do not accelerate that future alarm
784
+ // from inside the current handler: workerd cancels a running handler when it
785
+ // writes an earlier slot.
786
+ await ensureTransactionAlarmBy(
787
+ transaction,
788
+ Option.isSome(publicationDeadline)
789
+ ? Math.max(
790
+ now + minimumAlarmDelay,
791
+ Math.min(now + config.wakeScanInterval, publicationDeadline.value),
792
+ )
793
+ : now + config.wakeScanInterval,
794
+ );
795
+
796
+ return "rearmed" as const;
797
+ }
798
+ if (Option.isSome(publicationDeadline)) {
799
+ await transaction.setAlarm(
800
+ Math.max(now + minimumAlarmDelay, publicationDeadline.value),
801
+ );
802
+
803
+ return "rearmed" as const;
804
+ }
805
+ await transaction.deleteAlarm();
806
+
807
+ return "cleared" as const;
808
+ }),
809
+ );
810
+ }),
811
+ );
812
+
813
+ yield* failpoint.hit("maintenance:finish:after");
814
+ if (alarmDisposition === "cleared") {
815
+ yield* Ref.set(stalls, 0);
816
+ }
817
+
818
+ return yield* annotate(
819
+ MaintenancePassReport.make({
820
+ phase: "actionable",
821
+ recovered: recovered.length,
822
+ settled: Option.isSome(settlement) ? 1 : 0,
823
+ nonterminal: remaining.length,
824
+ alarm: alarmDisposition,
825
+ }),
826
+ );
827
+ });
828
+
829
+ return ThreadMaintenance.of({
830
+ // A mid-pass immediate hint is droppable; durable dirty state decides the final alarm.
831
+ pass: Effect.gen(function* () {
832
+ const yieldAfter = DateTime.makeUnsafe((yield* Clock.currentTimeMillis) + 10 * 60_000);
833
+
834
+ return yield* alarm.withWakesDeferred(maintenancePassGate.withPermit(pass(yieldAfter)));
835
+ }).pipe(
836
+ // Include permit waiting, recovery and acknowledgement in the event deadline.
837
+ // Interruption releases Attempt ownership, leaving the prearmed dirty generation
838
+ // for recovery. It never changes the logical Run duration or settles a policy failure.
839
+ // This cooperative timer cannot preempt synchronous CPU work or stuck finalizers.
840
+ Effect.timeoutOrElse({
841
+ duration: "14 minutes",
842
+ orElse: () =>
843
+ DurableAlarmError.make({
844
+ operation: "maintenance pass deadline",
845
+ message:
846
+ "The maintenance event exceeded its 14 minute deadline; durable recovery remains pending",
847
+ }),
848
+ }),
849
+ ),
850
+ ensureAlarm: mutations.withSnapshot(() => ensureAlarm()),
851
+ withMutation: (body) =>
852
+ mutations.withMutation(
853
+ body.pipe(
854
+ Effect.tap(() =>
855
+ publishCommitted.pipe(Effect.provideService(ThreadPublication, publication)),
856
+ ),
857
+ ),
858
+ ),
859
+ });
860
+ }),
861
+ );
862
+ }