@effect-agent/platform-cloudflare 0.1.0-beta.86 → 0.1.0-beta.87
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.
- package/dist/Alarm.d.mts +5 -1
- package/dist/Alarm.mjs +5 -5
- package/dist/Alarm.mjs.map +1 -1
- package/dist/CloudflareThreadClient.d.mts +3 -3
- package/dist/{ThreadObject-BT0c-_vx.d.mts → ThreadObject-BMNq8kuv.d.mts} +21 -21
- package/dist/{ThreadObject-B4gJ7t0d.mjs → ThreadObject-DvRG0dDz.mjs} +3 -3
- package/dist/ThreadObject-DvRG0dDz.mjs.map +1 -0
- package/dist/ThreadObject.d.mts +1 -1
- package/dist/ThreadObject.mjs +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/src/Alarm.ts +11 -5
- package/src/internal/message-delivery.ts +7 -2
- package/dist/ThreadObject-B4gJ7t0d.mjs.map +0 -1
package/dist/Alarm.d.mts
CHANGED
|
@@ -135,7 +135,11 @@ declare const ThreadHostMaintenance: Context.Reference<{
|
|
|
135
135
|
/** @internal A committed source operation must not become a failed operation because delivery failed. */
|
|
136
136
|
declare const publishCommitted: Effect.Effect<void, never, ThreadPublication>;
|
|
137
137
|
declare const ThreadMutationGate_base: Context.ServiceClass<ThreadMutationGate, "@effect-agent/platform-cloudflare/internal/ThreadMutationGate", {
|
|
138
|
-
readonly withMutation: <A, E, R>(body: Effect.Effect<A, E, R
|
|
138
|
+
readonly withMutation: <A, E, R>(body: Effect.Effect<A, E, R>,
|
|
139
|
+
/** Indexed host work has its own durable deadline and does not invalidate ledger recovery. */
|
|
140
|
+
options?: {
|
|
141
|
+
readonly invalidatesRecovery: boolean;
|
|
142
|
+
}) => Effect.Effect<A, E | DurableAlarmError, R>;
|
|
139
143
|
readonly withSnapshot: <A, E, R>(body: (active: number) => Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
|
|
140
144
|
}>;
|
|
141
145
|
/**
|
package/dist/Alarm.mjs
CHANGED
|
@@ -198,23 +198,23 @@ var ThreadMutationGate = class ThreadMutationGate extends Context.Service()("@ef
|
|
|
198
198
|
const generationGate = yield* Semaphore.make(1);
|
|
199
199
|
const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));
|
|
200
200
|
const runTransaction = yield* makeStorageOperation;
|
|
201
|
-
const beginMutation = Effect.fn("ThreadMaintenance.beginMutation")(function* () {
|
|
201
|
+
const beginMutation = Effect.fn("ThreadMaintenance.beginMutation")(function* (invalidatesRecovery) {
|
|
202
202
|
yield* failpoint.hit("maintenance:dirty:before");
|
|
203
203
|
const now = yield* Clock.currentTimeMillis;
|
|
204
204
|
yield* runTransaction("advance maintenance generation", () => ctx.storage.transaction(async (transaction) => {
|
|
205
|
-
const { state } = await readMaintenanceState(transaction);
|
|
205
|
+
const { state, initialized } = await readMaintenanceState(transaction);
|
|
206
206
|
const next = ThreadMaintenanceState.make({
|
|
207
207
|
...state,
|
|
208
|
-
dirty: state.dirty + 1n
|
|
208
|
+
dirty: state.dirty + (invalidatesRecovery ? 1n : 0n)
|
|
209
209
|
});
|
|
210
|
-
await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));
|
|
210
|
+
if (invalidatesRecovery || !initialized) await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));
|
|
211
211
|
await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);
|
|
212
212
|
}));
|
|
213
213
|
yield* failpoint.hit("maintenance:dirty:after");
|
|
214
214
|
yield* Ref.update(activeMutations, (active) => active + 1);
|
|
215
215
|
});
|
|
216
216
|
const endMutation = generationGate.withPermit(Ref.update(activeMutations, (active) => Math.max(0, active - 1)));
|
|
217
|
-
const withMutation = (body) => Effect.acquireUseRelease(generationGate.withPermit(beginMutation()), () => failpoint.hit("maintenance:mutation:armed").pipe(Effect.andThen(body), Effect.tap(() => failpoint.hit("maintenance:mutation:finished"))), () => endMutation);
|
|
217
|
+
const withMutation = (body, options) => Effect.acquireUseRelease(generationGate.withPermit(beginMutation(options?.invalidatesRecovery ?? true)), () => failpoint.hit("maintenance:mutation:armed").pipe(Effect.andThen(body), Effect.tap(() => failpoint.hit("maintenance:mutation:finished"))), () => endMutation);
|
|
218
218
|
return ThreadMutationGate.of({
|
|
219
219
|
withMutation,
|
|
220
220
|
withSnapshot: (body) => generationGate.withPermit(Effect.flatMap(Ref.get(activeMutations), body))
|
package/dist/Alarm.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Alarm.mjs","names":[],"sources":["../src/Alarm.ts"],"sourcesContent":["import {\n Cause,\n Clock,\n Context,\n DateTime,\n Deferred,\n Effect,\n Exit,\n Fiber,\n Layer,\n Option,\n Random,\n Ref,\n Schema,\n Semaphore,\n Stream,\n} from \"effect\";\nimport { type DurableBindingFailure } from \"effect-agent/agent-registration\";\nimport {\n DurableAgentRuntime,\n type DurableWorkerFailure,\n type RecoveryReport,\n} from \"effect-agent/durable-agent-runtime\";\nimport { ThreadId } from \"effect-agent/identifiers\";\nimport { SubmissionLedger, type SubmissionSnapshot } from \"effect-agent/submission-ledger\";\nimport {\n ThreadProjectionMaintenance,\n drainDue,\n type ThreadProjectionError,\n} from \"effect-agent/thread-projection-maintenance\";\nimport { SqlClient } from \"effect/unstable/sql/SqlClient\";\n\nimport { DurableObjectContext } from \"./CloudflareBindings.ts\";\nimport { CloudflareDurableRuntimeConfig } from \"./CloudflareConfig.ts\";\nimport { safeCauseMessage } from \"./internal/boundary.ts\";\n\n/**\n * The single multiplexed Durable Object alarm (decision D-P6-2). A Durable Object has ONE\n * alarm slot; every cadence the Node host ran on fibers (wake scan, lease expiry, settlement\n * and abort re-checks, retry backoff) multiplexes into one idempotent maintenance pass, and\n * the slot always holds the EARLIEST deadline any caller asked for.\n *\n * The alarm invariant (plan §1.4): every committed actionable mutation carries a newer durable\n * maintenance generation and a committed alarm. Stable externally-driven waits may be\n * nonterminal without retaining an alarm; their resolving mutation advances the generation and\n * restores the alarm atomically.\n */\n\n/** The Durable Object alarm API failed; surfaces on host entry points as a typed refusal. */\nexport class DurableAlarmError extends Schema.TaggedError<DurableAlarmError>()(\n \"DurableAlarmError\",\n {\n operation: Schema.String,\n message: Schema.String,\n cause: Schema.optionalKey(Schema.Defect()),\n },\n) {}\n\nconst alarmFailure =\n (operation: string) =>\n (cause: unknown): DurableAlarmError =>\n DurableAlarmError.make({\n operation,\n message: safeCauseMessage(cause, \"The Cloudflare alarm API failed without a diagnostic\"),\n cause,\n });\n\n// SQL and raw KV/alarm operations share one physical SQLite transaction. Reserve its\n// connection for each short storage operation, never around a mutation or snapshot body.\nconst makeStorageOperation = Effect.map(\n SqlClient,\n (sql) =>\n <A>(operation: string, execute: () => Promise<A>) =>\n Effect.flatMap(Effect.serviceOption(sql.transactionService), (current) => {\n const body = Effect.uninterruptible(\n Effect.tryPromise({ try: execute, catch: alarmFailure(operation) }),\n );\n\n return current._tag === \"Some\"\n ? body\n : Effect.scoped(\n Effect.andThen(sql.reserve.pipe(Effect.mapError(alarmFailure(operation))), body),\n );\n }),\n);\n\n/** `ctx.storage` alarm slot as an Effect service; storage is truth, never a memory field. */\nexport class DurableAlarmService extends Context.Service<\n DurableAlarmService,\n {\n /** The scheduled deadline in epoch milliseconds, if any. */\n readonly scheduled: Effect.Effect<Option.Option<number>, DurableAlarmError>;\n /** Replace the slot with this deadline. */\n readonly scheduleAt: (epochMillis: number) => Effect.Effect<void, DurableAlarmError>;\n /** Keep the EARLIER of the existing deadline and this one (the multiplexing rule). */\n readonly ensureScheduledBy: (epochMillis: number) => Effect.Effect<void, DurableAlarmError>;\n /**\n * Arm an immediate alarm (the durable, coalescing local wake) — DEFERRED while a\n * maintenance pass is executing. Workerd cancels an in-flight alarm handler when a new\n * EARLIER deadline is written during its execution (`requestScheduledAlarm`), and the\n * maintenance pass runs INSIDE the alarm handler: an immediate wake landing mid-pass\n * (a routed port mutation, a sibling's `wake()`, the coordinator's own local notify)\n * would kill the running Attempt — manufacturing an ownership loss no real eviction\n * caused, and routing open uncertain-class Tool Calls into spurious Unknown Outcomes.\n * Deferral is contract-safe: wakes are droppable hints, every mutating entry point\n * pre-arms BEFORE its first durable mutation (the alarm invariant never rests on this\n * call). The pass's durable generation check observes any racing mutation, so the\n * in-memory hint does not need to be flushed after a stable wait is acknowledged.\n */\n readonly scheduleNow: Effect.Effect<void, DurableAlarmError>;\n /**\n * Run one maintenance pass with wake deferral (see `scheduleNow`). Calls made while `body`\n * executes are droppable promptness hints; correctness rests on the durable generation.\n */\n readonly withWakesDeferred: <A, E, R>(body: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;\n /** Clear the slot; correctness-sensitive clears live in maintenance generation transactions. */\n readonly cancel: Effect.Effect<void, DurableAlarmError>;\n }\n>()(\"@effect-agent/platform-cloudflare/DurableAlarmService\") {\n static readonly layer: Layer.Layer<DurableAlarmService, never, DurableObjectContext | SqlClient> =\n Layer.effect(DurableAlarmService)(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n /**\n * In-memory pass bookkeeping — a pure CACHE, never state: a fresh incarnation has no\n * running pass, and a deferred wake lost to eviction was only ever a promptness hint\n * on top of the already-committed pre-armed alarm.\n */\n const runningPasses = yield* Ref.make(0);\n\n const storageOperation = yield* makeStorageOperation;\n\n const scheduled = storageOperation(\"get alarm\", () => ctx.storage.getAlarm()).pipe(\n Effect.map((deadline) =>\n deadline === null ? Option.none<number>() : Option.some(deadline),\n ),\n );\n\n const scheduleAt = (epochMillis: number) =>\n storageOperation(\"set alarm\", () => ctx.storage.setAlarm(epochMillis));\n\n const ensureScheduledBy = (epochMillis: number) =>\n storageOperation(\"ensure alarm\", () =>\n ctx.storage.transaction(async (transaction) => {\n const existing = await transaction.getAlarm();\n\n if (existing === null || existing > epochMillis) {\n await transaction.setAlarm(epochMillis);\n }\n }),\n );\n\n const armNow = Clock.currentTimeMillis.pipe(\n Effect.flatMap((now) => ensureScheduledBy(now)),\n );\n\n const scheduleNow = Ref.get(runningPasses).pipe(\n Effect.flatMap((passes) => (passes > 0 ? Effect.void : armNow)),\n );\n\n const withWakesDeferred = <A, E, R>(body: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n Ref.update(runningPasses, (passes) => passes + 1).pipe(\n Effect.andThen(body),\n Effect.ensuring(Ref.update(runningPasses, (passes) => passes - 1)),\n );\n\n const cancel = storageOperation(\"delete alarm\", () => ctx.storage.deleteAlarm());\n\n return DurableAlarmService.of({\n scheduled,\n scheduleAt,\n ensureScheduledBy,\n scheduleNow,\n withWakesDeferred,\n cancel,\n });\n }),\n );\n}\n\n/** What one maintenance pass did — auditable evidence mirroring `NodeDurableHost`'s report. */\nexport class MaintenancePassReport extends Schema.Class<MaintenancePassReport>(\n \"@effect-agent/platform-cloudflare/MaintenancePassReport\",\n)({\n /** `caught-up` ran no runtime work (publication may be pending); `actionable` ran recovery. */\n phase: Schema.Literals([\"caught-up\", \"actionable\"]),\n /** Recovery decisions executed (or deferred) BEFORE any new claim in this pass. */\n recovered: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** Whether the head Attempt settled. Joined input may settle with that head. */\n settled: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** Submissions still nonterminal after the pass (suspended/unknown lanes stay honest). */\n nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** `rearmed` for dirty/autonomous work, `cleared` for stable waits or settlement. */\n alarm: Schema.Literals([\"rearmed\", \"cleared\"]),\n}) {}\n\n/** Fault boundaries around every maintenance-owned durable mutation. */\nexport type ThreadMaintenanceFailpointLocation =\n | \"maintenance:dirty:before\"\n | \"maintenance:dirty:after\"\n | \"maintenance:mutation:armed\"\n | \"maintenance:mutation:finished\"\n | \"maintenance:ensure:before\"\n | \"maintenance:ensure:after\"\n | \"maintenance:begin:before\"\n | \"maintenance:begin:after\"\n | \"maintenance:select:before\"\n | \"maintenance:select:after\"\n | \"maintenance:finish:before\"\n | \"maintenance:finish:after\";\n\nexport type ThreadMaintenanceFailpointHandler = (\n location: ThreadMaintenanceFailpointLocation,\n) => Effect.Effect<void>;\n\n/** Test-only fault authority; production uses the inert layer. */\nexport class ThreadMaintenanceFailpoint extends Context.Service<\n ThreadMaintenanceFailpoint,\n {\n readonly hit: ThreadMaintenanceFailpointHandler;\n }\n>()(\"@effect-agent/platform-cloudflare/ThreadMaintenanceFailpoint\") {\n static readonly layer = Layer.succeed(this)({ hit: () => Effect.void });\n}\n\n/**\n * Durable host publication of canonical records and ledger approval/abort/resolution intents.\n * The host owns schema-versioned cursors, destination idempotency and acknowledgement. Delivery\n * is at least once. Hooks must not write the alarm slot or mutate the supplied raw source ports.\n *\n * `invalidate`, `prepareGeneration` and `pendingDeadline` must be bounded local operations.\n * `prepareGeneration` durably invalidates a scan only when its generation changes; repeated\n * calls must preserve partial scan progress. It runs with no source mutation in flight.\n * `drain` performs bounded delivery and persists retries before returning. A pending deadline\n * defers runtime recovery/Attempts, allowing committed host publications to drain first.\n * Unexpected hook failures leave the prearmed generation for retry. Hooks acquire per-call\n * resources with Effect.scoped; Layer construction owns incarnation resources (eviction need\n * not run finalizers). Do not hold a local hook behind network I/O or call back into producers.\n */\nexport interface ThreadPublicationService {\n readonly invalidate: Effect.Effect<void, DurableAlarmError>;\n readonly prepareGeneration: (generation: bigint) => Effect.Effect<void, DurableAlarmError>;\n readonly drain: Effect.Effect<void, DurableAlarmError>;\n readonly pendingDeadline: Effect.Effect<Option.Option<number>, DurableAlarmError>;\n}\n\n/** Opt in with `ThreadObject.layer(registrations, { publication: Layer.effect(ThreadPublication)(...) })`. */\nexport class ThreadPublication extends Context.Service<\n ThreadPublication,\n ThreadPublicationService\n>()(\"@effect-agent/platform-cloudflare/ThreadPublication\") {\n static readonly layer = Layer.succeed(this)({\n invalidate: Effect.void,\n prepareGeneration: () => Effect.void,\n drain: Effect.void,\n pendingDeadline: Effect.succeed(Option.none()),\n });\n}\n\n/**\n * Host-assembled message recovery, supplied by ThreadObject.layer even when the application\n * rebuilds ThreadMaintenance. These obligations outlive source Runs and never defer a ready\n * source Attempt while a destination is processing an accepted message.\n */\nexport const ThreadMessageDelivery = Context.Reference<{\n readonly drain: Effect.Effect<void, DurableAlarmError>;\n /** Drain inserts and due retries during source work, finishing the bounded wave on completion. */\n readonly drainUntil?: (\n finished: Deferred.Deferred<void>,\n ) => Effect.Effect<void, DurableAlarmError>;\n readonly pendingDeadline: Effect.Effect<Option.Option<number>, DurableAlarmError>;\n}>(\"@effect-agent/platform-cloudflare/ThreadMessageDelivery\", {\n defaultValue: () => ({ drain: Effect.void, pendingDeadline: Effect.succeed(Option.none()) }),\n});\n\n/**\n * Application obligations sharing this Object's alarm. The deadline read is local and\n * read-only. Drain beside the native Attempt and always finish one initial bounded wave,\n * even when `finished` was already signalled. Then stop starting new waves on that signal\n * and finish the bounded current wave before returning. Native maintenance joins that work\n * before acknowledging a generation. Mutations use the same ThreadMutationGate; hooks never\n * write the raw alarm slot. Pending host work does not defer a ready model Attempt.\n */\nexport const ThreadHostMaintenance = Context.Reference<{\n readonly pendingDeadline: Effect.Effect<Option.Option<number>, DurableAlarmError>;\n readonly drainUntil: (\n finished: Deferred.Deferred<void>,\n ) => Effect.Effect<void, DurableAlarmError>;\n}>(\"@effect-agent/platform-cloudflare/ThreadHostMaintenance\", {\n defaultValue: () => ({\n pendingDeadline: Effect.succeed(Option.none()),\n drainUntil: () => Effect.void,\n }),\n});\n\nconst earliestDeadline = (\n left: Option.Option<number>,\n right: Option.Option<number>,\n): Option.Option<number> =>\n Option.isSome(left)\n ? Option.isSome(right)\n ? Option.some(Math.min(left.value, right.value))\n : left\n : right;\n\n/** @internal A committed source operation must not become a failed operation because delivery failed. */\nexport const publishCommitted = Effect.gen(function* () {\n const publication = yield* ThreadPublication;\n\n yield* publication.invalidate.pipe(Effect.andThen(publication.drain));\n}).pipe(\n Effect.catchCause((cause) =>\n Cause.hasInterrupts(cause)\n ? Effect.interrupt\n : Effect.logError(\"Thread publication deferred after source commit\", cause),\n ),\n);\n\nconst MaintenanceGeneration = Schema.BigIntFromString.check(\n Schema.isGreaterThanOrEqualToBigInt(0n),\n);\n\n/** Versioned, platform-private maintenance state stored through Durable Object KV. */\nclass ThreadMaintenanceState extends Schema.Class<ThreadMaintenanceState>(\n \"@effect-agent/platform-cloudflare/ThreadMaintenanceState\",\n)({\n schemaVersion: Schema.Literal(1),\n dirty: MaintenanceGeneration,\n processed: MaintenanceGeneration,\n nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** One physical-owner cursor; old single-lane records need no conversion. */\n lastServedThreadId: Schema.optionalKey(ThreadId),\n}) {}\n\nconst MAINTENANCE_STATE_KEY = \"effect-agent:thread-maintenance:v1\";\nconst decodeMaintenanceState = Schema.decodeUnknownSync(ThreadMaintenanceState);\nconst encodeMaintenanceState = Schema.encodeSync(ThreadMaintenanceState);\n\nconst initialMaintenanceState = (): ThreadMaintenanceState =>\n ThreadMaintenanceState.make({\n schemaVersion: 1,\n // Bootstrap Objects created by the pre-generation release without scanning the ledger in\n // the constructor. One useful pass classifies and acknowledges any existing obligation.\n dirty: 1n,\n processed: 0n,\n nonterminal: 0,\n });\n\nconst readMaintenanceState = async (\n transaction: DurableObjectTransaction,\n): Promise<{ readonly state: ThreadMaintenanceState; readonly initialized: boolean }> => {\n const encoded = await transaction.get(MAINTENANCE_STATE_KEY);\n\n return encoded === undefined\n ? { state: initialMaintenanceState(), initialized: false }\n : { state: decodeMaintenanceState(encoded), initialized: true };\n};\n\nconst ensureTransactionAlarmBy = async (\n transaction: DurableObjectTransaction,\n deadline: number,\n): Promise<void> => {\n const scheduled = await transaction.getAlarm();\n\n if (scheduled === null || scheduled > deadline) {\n await transaction.setAlarm(deadline);\n }\n};\n\nconst stableExternalWait = (\n snapshot: SubmissionSnapshot,\n reports: ReadonlyMap<string, RecoveryReport>,\n): boolean => {\n const decision = reports.get(snapshot.submissionId)?.decision._tag;\n\n // An accepted abort still owes cleanup/settlement even if its claim was deferred this pass.\n if (decision === \"SettleAborted\") return false;\n switch (snapshot.state) {\n case \"suspended\":\n case \"joined\":\n return true;\n case \"unknown\":\n return decision === \"AwaitUnknownResolution\" || decision === \"MarkUnknown\";\n case \"admitted\":\n return reports.get(snapshot.submissionId)?.decision._tag === \"AwaitParentEstablishment\";\n case \"input-applied\":\n case \"joining\":\n case \"ready\":\n case \"running\":\n case \"settled\":\n case \"terminalizing\":\n return false;\n }\n};\n\n/**\n * Shared prearm/acknowledgement boundary for ingress and runtime-owned producers.\n * `ThreadObject.layer` provides this same instance in its Services. Rebuilt runtime/maintenance\n * Layers must reuse that instance; a second gate cannot observe the native producers' activity.\n */\nexport class ThreadMutationGate extends Context.Service<\n ThreadMutationGate,\n {\n readonly withMutation: <A, E, R>(\n body: Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | DurableAlarmError, R>;\n readonly withSnapshot: <A, E, R>(\n body: (active: number) => Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E, R>;\n }\n>()(\"@effect-agent/platform-cloudflare/internal/ThreadMutationGate\") {\n static readonly layer = Layer.effect(this)(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n const config = yield* CloudflareDurableRuntimeConfig;\n const failpoint = yield* ThreadMaintenanceFailpoint;\n // A fresh incarnation has no live mutations; durable generations survive eviction.\n const activeMutations = yield* Ref.make(0);\n const generationGate = yield* Semaphore.make(1);\n const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));\n\n const runTransaction = yield* makeStorageOperation;\n\n const beginMutation = Effect.fn(\"ThreadMaintenance.beginMutation\")(function* () {\n yield* failpoint.hit(\"maintenance:dirty:before\");\n const now = yield* Clock.currentTimeMillis;\n\n yield* runTransaction(\"advance maintenance generation\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n const next = ThreadMaintenanceState.make({\n ...state,\n dirty: state.dirty + 1n,\n });\n\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));\n // The earliest configured retry bounds a newly actionable mutation without relying\n // on its best-effort immediate wake hint.\n await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);\n }),\n );\n yield* failpoint.hit(\"maintenance:dirty:after\");\n yield* Ref.update(activeMutations, (active) => active + 1);\n });\n\n const endMutation = generationGate.withPermit(\n Ref.update(activeMutations, (active) => Math.max(0, active - 1)),\n );\n\n const withMutation = <A, E, R>(\n body: Effect.Effect<A, E, R>,\n ): Effect.Effect<A, E | DurableAlarmError, R> =>\n Effect.acquireUseRelease(\n generationGate.withPermit(beginMutation()),\n () =>\n failpoint.hit(\"maintenance:mutation:armed\").pipe(\n Effect.andThen(body),\n Effect.tap(() => failpoint.hit(\"maintenance:mutation:finished\")),\n ),\n () => endMutation,\n );\n\n return ThreadMutationGate.of({\n withMutation,\n withSnapshot: (body) =>\n generationGate.withPermit(Effect.flatMap(Ref.get(activeMutations), body)),\n });\n }),\n );\n}\n\nexport type MaintenancePassFailure =\n | DurableWorkerFailure\n | DurableBindingFailure\n | DurableAlarmError\n | ThreadProjectionError;\n\n/**\n * Incremental, quiescent maintenance over a durable dirty/processed generation (issue #93).\n *\n * `pass` = generation snapshot/pre-arm → recovery → one head Attempt → generation acknowledgement:\n *\n * 1. One storage transaction reads dirty/processed and re-arms before work. A caught-up forced\n * alarm takes an O(1) path without recovery, ledger scans, or canonical-history reads.\n * 2. Recovery strictly precedes a new claim. One head Attempt advances the lane and requests\n * a safe yield after ten minutes. The whole event has a fourteen-minute cooperative timeout.\n * 3. The final transaction acknowledges only the generation observed at pass start. A racing\n * mutation therefore remains `dirty > processed` and retains its atomically-established alarm.\n * 4. Stable external waits acknowledge and clear. Autonomous retry, indeterminate, and lease\n * recovery states leave their generation dirty and retain bounded backoff rearming.\n */\nexport class ThreadMaintenance extends Context.Service<\n ThreadMaintenance,\n {\n /** One idempotent maintenance pass; failures propagate so workerd retries the alarm. */\n readonly pass: Effect.Effect<MaintenancePassReport, MaintenancePassFailure>;\n /**\n * Constructor gate: initialize/inspect only the O(1) maintenance record and ensure a dirty\n * generation has an alarm. It never scans the ledger or canonical history.\n */\n readonly ensureAlarm: Effect.Effect<void, MaintenancePassFailure>;\n /**\n * Serialize the pre-arm boundary with pass acknowledgement, advance the durable dirty\n * generation and arm the alarm in one transaction BEFORE running the caller's mutation.\n * A pass cannot acknowledge while that mutation remains in flight.\n */\n readonly withMutation: <A, E, R>(\n body: Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | DurableAlarmError, R>;\n }\n>()(\"@effect-agent/platform-cloudflare/ThreadMaintenance\") {\n static readonly layer: Layer.Layer<\n ThreadMaintenance,\n never,\n | ThreadMutationGate\n | ThreadPublication\n | ThreadProjectionMaintenance\n | DurableAgentRuntime\n | SubmissionLedger\n | DurableAlarmService\n | ThreadMaintenanceFailpoint\n | CloudflareDurableRuntimeConfig\n | DurableObjectContext\n | SqlClient\n > = Layer.effect(ThreadMaintenance)(\n Effect.gen(function* () {\n const runtime = yield* DurableAgentRuntime;\n const ledger = yield* SubmissionLedger;\n const alarm = yield* DurableAlarmService;\n const config = yield* CloudflareDurableRuntimeConfig;\n const { ctx } = yield* DurableObjectContext;\n const failpoint = yield* ThreadMaintenanceFailpoint;\n\n /**\n * Consecutive no-progress passes — an in-memory CACHE, not state: a fresh incarnation\n * restarts at zero and merely re-arms sooner than a long-lived one would have.\n */\n const stalls = yield* Ref.make(0);\n const mutations = yield* ThreadMutationGate;\n const publication = yield* ThreadPublication;\n const projection = yield* ThreadProjectionMaintenance;\n const messages = yield* ThreadMessageDelivery;\n const host = yield* ThreadHostMaintenance;\n\n // A broken disposable index still needs a retry alarm and must not prevent startup.\n const projectionDeadline = projection.pendingDeadline.pipe(\n Effect.catchCauseIf(\n (cause) => !Cause.hasInterrupts(cause),\n (cause) =>\n Effect.logError(\"Thread projection deadline unavailable\", cause).pipe(\n Effect.as(Option.some(0)),\n ),\n ),\n );\n\n const pendingDeadline = Effect.gen(function* () {\n return earliestDeadline(\n earliestDeadline(yield* publication.pendingDeadline, yield* messages.pendingDeadline),\n earliestDeadline(yield* projectionDeadline, yield* host.pendingDeadline),\n );\n });\n\n const maintenancePassGate = yield* Semaphore.make(1);\n const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));\n\n const runTransaction = yield* makeStorageOperation;\n\n const ensureAlarm = Effect.fn(\"ThreadMaintenance.ensureAlarm\")(function* () {\n yield* failpoint.hit(\"maintenance:ensure:before\");\n const now = yield* Clock.currentTimeMillis;\n\n yield* runTransaction(\"ensure maintenance alarm\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state, initialized } = await readMaintenanceState(transaction);\n\n if (!initialized) {\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));\n }\n if (state.dirty > state.processed) {\n await ensureTransactionAlarmBy(transaction, now + config.wakeScanInterval);\n }\n }),\n );\n const deadline = yield* pendingDeadline;\n\n if (Option.isSome(deadline)) {\n yield* runTransaction(\"ensure publication alarm\", () =>\n ctx.storage.transaction((transaction) =>\n ensureTransactionAlarmBy(\n transaction,\n Math.max(now + minimumAlarmDelay, deadline.value),\n ),\n ),\n );\n }\n yield* failpoint.hit(\"maintenance:ensure:after\");\n });\n\n const beginPass = Effect.fn(\"ThreadMaintenance.beginPass\")(function* () {\n yield* failpoint.hit(\"maintenance:begin:before\");\n const now = yield* Clock.currentTimeMillis;\n\n const result = yield* runTransaction(\"begin maintenance pass\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state, initialized } = await readMaintenanceState(transaction);\n\n if (!initialized) {\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));\n }\n if (state.processed >= state.dirty) {\n // Prearm even a publication-only pass before invoking any host hook.\n await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);\n\n return { _tag: \"CaughtUp\" as const, nonterminal: state.nonterminal };\n }\n // Pre-arm the earliest retry before recovery. A successful finish may move this slot\n // LATER to its bounded backoff, which does not cancel the running handler.\n await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);\n\n return {\n _tag: \"Actionable\" as const,\n generation: state.dirty,\n nonterminal: state.nonterminal,\n };\n }),\n );\n\n yield* failpoint.hit(\"maintenance:begin:after\");\n\n return result;\n });\n\n const rearmDelay = Effect.fn(\"ThreadMaintenance.rearmDelay\")(function* (progressed: boolean) {\n const priorStalls = yield* Ref.getAndUpdate(stalls, (count) =>\n progressed ? 0 : count + 1,\n );\n\n if (progressed) return config.alarmBackoffBase;\n const exponent = Math.min(priorStalls, 30);\n const backoff = Math.min(config.alarmBackoffCap, config.alarmBackoffBase * 2 ** exponent);\n const jitter = yield* Random.next;\n // Full jitter over [backoff/2, backoff]: desynchronizes retry storms without ever\n // waiting longer than the deterministic bound.\n const jittered = Math.ceil(backoff / 2 + (backoff / 2) * jitter);\n\n return Math.min(jittered, config.wakeScanInterval);\n });\n\n const pass = Effect.fn(\"ThreadMaintenance.pass\")(function* (\n yieldAfter: DateTime.Utc,\n ): Effect.fn.Return<MaintenancePassReport, MaintenancePassFailure> {\n const annotate = (report: MaintenancePassReport) =>\n Effect.annotateCurrentSpan({\n phase: report.phase,\n recovered: report.recovered,\n settled: report.settled,\n nonterminal: report.nonterminal,\n alarm: report.alarm,\n }).pipe(Effect.as(report));\n\n const started = yield* mutations.withSnapshot((activeAtStart) =>\n Effect.gen(function* () {\n const generation = yield* beginPass();\n\n if (generation._tag === \"Actionable\" && activeAtStart === 0) {\n // The gate excludes a producer starting between the snapshot and certification.\n yield* publication.prepareGeneration(generation.generation);\n }\n\n return { ...generation, activeAtStart };\n }),\n );\n\n // Deliver beside source work, including messages inserted by the running Attempt.\n // Slow destination RPCs never consume the source execution window. Stop starting\n // waves when source work ends, then join the bounded current wave before acknowledgement.\n const deliveryFinished = yield* Deferred.make<void>();\n\n const delivery = yield* Effect.forkChild(\n messages.drainUntil?.(deliveryFinished) ?? messages.drain,\n );\n\n const hostWork = yield* Effect.forkChild(host.drainUntil(deliveryFinished));\n\n const finishDelivery = Deferred.succeed(deliveryFinished, undefined).pipe(\n Effect.andThen(Fiber.awaitAll([delivery, hostWork])),\n Effect.flatMap((outcomes) =>\n Effect.forEach(outcomes, (outcome) => outcome, { discard: true }),\n ),\n );\n\n // Capture derived-index failures until canonical work has had its turn. Interruption\n // still stops the event; ordinary failures and defects retain the prearmed generation.\n const projected = yield* Effect.exit(\n drainDue.pipe(Effect.provideService(ThreadProjectionMaintenance, projection)),\n );\n\n if (Exit.isFailure(projected) && Cause.hasInterrupts(projected.cause))\n return yield* Effect.failCause(projected.cause);\n const deadline = yield* publication.pendingDeadline;\n\n if (\n started._tag === \"Actionable\" ||\n (Option.isSome(deadline) && deadline.value <= (yield* Clock.currentTimeMillis))\n ) {\n yield* publication.drain;\n }\n const pending = yield* publication.pendingDeadline;\n\n if (started._tag === \"CaughtUp\" || Option.isSome(pending)) {\n yield* finishDelivery;\n if (Exit.isFailure(projected)) return yield* Effect.failCause(projected.cause);\n yield* failpoint.hit(\"maintenance:finish:before\");\n\n const disposition = yield* mutations.withSnapshot((active) =>\n Effect.gen(function* () {\n // Re-read under the producer gate: a concurrent append/host mutation cannot be\n // cleared using a stale empty deadline. Dirty generations bound all producer races.\n const latest = yield* pendingDeadline;\n const now = yield* Clock.currentTimeMillis;\n\n return yield* runTransaction(\"finish publication pass\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n const nativeDeadline =\n active > 0 || state.dirty > state.processed\n ? now + config.wakeScanInterval\n : Infinity;\n\n const next = Option.isSome(latest)\n ? Math.min(nativeDeadline, latest.value)\n : nativeDeadline;\n\n if (Number.isFinite(next)) {\n await transaction.setAlarm(Math.max(now + minimumAlarmDelay, next));\n\n return \"rearmed\" as const;\n }\n await transaction.deleteAlarm();\n\n return \"cleared\" as const;\n }),\n );\n }),\n );\n\n yield* failpoint.hit(\"maintenance:finish:after\");\n\n return yield* annotate(\n MaintenancePassReport.make({\n phase: \"caught-up\",\n recovered: 0,\n settled: 0,\n nonterminal: started.nonterminal,\n alarm: disposition,\n }),\n );\n }\n // Step 2 — reconciliation strictly precedes new work in this pass (exit gate).\n const recovered: ReadonlyArray<RecoveryReport> = yield* runtime.runRecovery;\n const reports = new Map(recovered.map((report) => [report.submissionId, report]));\n const current = yield* Stream.runCollect(ledger.scanNonterminal);\n const heads = new Map<ThreadId, SubmissionSnapshot>();\n\n for (const row of current) {\n if (!heads.has(row.threadId)) heads.set(row.threadId, row);\n }\n\n const eligible = [...heads.values()]\n .filter((head) => !stableExternalWait(head, reports))\n .map((head) => head.threadId)\n .sort();\n\n let selected = eligible[0];\n\n if (heads.size > 1 && selected !== undefined) {\n yield* failpoint.hit(\"maintenance:select:before\");\n selected = yield* runTransaction(\"select maintenance lane\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n const next =\n eligible.find(\n (threadId) =>\n state.lastServedThreadId === undefined || threadId > state.lastServedThreadId,\n ) ?? eligible[0];\n\n if (next !== undefined) {\n // Persist before the Attempt so an eviction or repeated yield cannot\n // monopolize the first lane. The generation and prearmed alarm survive.\n await transaction.put(\n MAINTENANCE_STATE_KEY,\n encodeMaintenanceState(\n ThreadMaintenanceState.make({ ...state, lastServedThreadId: next }),\n ),\n );\n }\n\n return next;\n }),\n );\n yield* failpoint.hit(\"maintenance:select:after\");\n }\n\n // One FIFO head per event, across all local lanes. The runtime keeps its normal\n // bounded Attempt and recovery contracts; followers belong to another alarm.\n const settlement =\n selected === undefined\n ? Option.none()\n : yield* runtime.processThreadHead(selected, { yieldAfter });\n\n yield* finishDelivery;\n if (Exit.isFailure(projected)) return yield* Effect.failCause(projected.cause);\n // Observe residual state before acknowledging this exact pass-start generation.\n const remaining = yield* Stream.runCollect(ledger.scanNonterminal);\n const waitingHeads = new Map<ThreadId, boolean>();\n\n const autonomous = remaining.some((snapshot) => {\n const headWaiting = waitingHeads.get(snapshot.threadId);\n\n if (headWaiting === undefined)\n waitingHeads.set(snapshot.threadId, stableExternalWait(snapshot, reports));\n // FIFO followers cannot execute through a stable external wait. Only plain queued\n // input is dormant here; admission repairs and accepted aborts still need a pass.\n if (\n headWaiting === true &&\n snapshot.state === \"ready\" &&\n reports.get(snapshot.submissionId)?.decision._tag === \"ApplyInput\"\n )\n return false;\n\n return !stableExternalWait(snapshot, reports);\n });\n\n const progressed =\n Option.isSome(settlement) ||\n recovered.some((report) => report.disposition === \"repaired\");\n\n const delay = autonomous ? yield* rearmDelay(progressed) : 0;\n const now = yield* Clock.currentTimeMillis;\n\n yield* failpoint.hit(\"maintenance:finish:before\");\n\n const alarmDisposition = yield* mutations.withSnapshot((active) =>\n Effect.gen(function* () {\n const publicationDeadline = yield* pendingDeadline;\n\n return yield* runTransaction(\"finish maintenance pass\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n // Autonomous work and in-flight mutations intentionally leave the observed\n // generation dirty. Otherwise acknowledge only the pass-start generation.\n const processed =\n autonomous || started.activeAtStart > 0 || active > 0\n ? state.processed\n : state.processed > started.generation\n ? state.processed\n : started.generation;\n\n const next = ThreadMaintenanceState.make({\n ...state,\n processed,\n nonterminal: remaining.length,\n });\n\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));\n if (autonomous) {\n // Replace the crash-fallback slot with this pass's bounded backoff. The target\n // is never earlier than the begin-pass fallback, so workerd does not cancel\n // this running alarm handler before its report/span can complete.\n await transaction.setAlarm(\n Option.isSome(publicationDeadline)\n ? Math.max(\n now + minimumAlarmDelay,\n Math.min(now + delay, publicationDeadline.value),\n )\n : now + delay,\n );\n\n return \"rearmed\" as const;\n }\n if (started.activeAtStart > 0 || active > 0 || next.dirty > next.processed) {\n // A mutation overlapped this pass's observation window or raced\n // acknowledgement. It stays dirty and its pre-armed bounded alarm survives;\n // unseen effects are never acknowledged. Do not accelerate that future alarm\n // from inside the current handler: workerd cancels a running handler when it\n // writes an earlier slot.\n await ensureTransactionAlarmBy(\n transaction,\n Option.isSome(publicationDeadline)\n ? Math.max(\n now + minimumAlarmDelay,\n Math.min(now + config.wakeScanInterval, publicationDeadline.value),\n )\n : now + config.wakeScanInterval,\n );\n\n return \"rearmed\" as const;\n }\n if (Option.isSome(publicationDeadline)) {\n await transaction.setAlarm(\n Math.max(now + minimumAlarmDelay, publicationDeadline.value),\n );\n\n return \"rearmed\" as const;\n }\n await transaction.deleteAlarm();\n\n return \"cleared\" as const;\n }),\n );\n }),\n );\n\n yield* failpoint.hit(\"maintenance:finish:after\");\n if (alarmDisposition === \"cleared\") {\n yield* Ref.set(stalls, 0);\n }\n\n return yield* annotate(\n MaintenancePassReport.make({\n phase: \"actionable\",\n recovered: recovered.length,\n settled: Option.isSome(settlement) ? 1 : 0,\n nonterminal: remaining.length,\n alarm: alarmDisposition,\n }),\n );\n });\n\n return ThreadMaintenance.of({\n // A mid-pass immediate hint is droppable; durable dirty state decides the final alarm.\n pass: Effect.gen(function* () {\n const yieldAfter = DateTime.makeUnsafe((yield* Clock.currentTimeMillis) + 10 * 60_000);\n\n return yield* alarm.withWakesDeferred(maintenancePassGate.withPermit(pass(yieldAfter)));\n }).pipe(\n // Include permit waiting, recovery and acknowledgement in the event deadline.\n // Interruption releases Attempt ownership, leaving the prearmed dirty generation\n // for recovery. It never changes the logical Run duration or settles a policy failure.\n // This cooperative timer cannot preempt synchronous CPU work or stuck finalizers.\n Effect.timeoutOrElse({\n duration: \"14 minutes\",\n orElse: () =>\n DurableAlarmError.make({\n operation: \"maintenance pass deadline\",\n message:\n \"The maintenance event exceeded its 14 minute deadline; durable recovery remains pending\",\n }),\n }),\n ),\n ensureAlarm: mutations.withSnapshot(() => ensureAlarm()),\n withMutation: (body) =>\n mutations.withMutation(\n body.pipe(\n Effect.tap(() =>\n publishCommitted.pipe(Effect.provideService(ThreadPublication, publication)),\n ),\n ),\n ),\n });\n }),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,IAAa,oBAAb,c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qB,WACvB,OAAO,IAAI,IAAI,QAAQ,CAAC;GAG1B,OAAO,OAAO,SACZ,sBAAsB,KAAK;IACzB,OAAO;IACP,WAAW,UAAU;IACrB,SAAS,OAAO,OAAO,UAAU,IAAI,IAAI;IACzC,aAAa,UAAU;IACvB,OAAO;GACT,CAAC,CACH;EACF,CAAC;EAED,OAAO,kBAAkB,GAAG;GAE1B,MAAM,OAAO,IAAI,aAAa;IAC5B,MAAM,aAAa,SAAS,YAAY,OAAO,MAAM,qBAAqB,GAAW;IAErF,OAAO,OAAO,MAAM,kBAAkB,oBAAoB,WAAW,KAAK,UAAU,CAAC,CAAC;GACxF,CAAC,CAAC,CAAC,KAKD,OAAO,cAAc;IACnB,UAAU;IACV,cACE,kBAAkB,KAAK;KACrB,WAAW;KACX,SACE;IACJ,CAAC;GACL,CAAC,CACH;GACA,aAAa,UAAU,mBAAmB,YAAY,CAAC;GACvD,eAAe,SACb,UAAU,aACR,KAAK,KACH,OAAO,UACL,iBAAiB,KAAK,OAAO,eAAe,mBAAmB,WAAW,CAAC,CAC7E,CACF,CACF;EACJ,CAAC;CACH,CAAC,CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"Alarm.mjs","names":[],"sources":["../src/Alarm.ts"],"sourcesContent":["import {\n Cause,\n Clock,\n Context,\n DateTime,\n Deferred,\n Effect,\n Exit,\n Fiber,\n Layer,\n Option,\n Random,\n Ref,\n Schema,\n Semaphore,\n Stream,\n} from \"effect\";\nimport { type DurableBindingFailure } from \"effect-agent/agent-registration\";\nimport {\n DurableAgentRuntime,\n type DurableWorkerFailure,\n type RecoveryReport,\n} from \"effect-agent/durable-agent-runtime\";\nimport { ThreadId } from \"effect-agent/identifiers\";\nimport { SubmissionLedger, type SubmissionSnapshot } from \"effect-agent/submission-ledger\";\nimport {\n ThreadProjectionMaintenance,\n drainDue,\n type ThreadProjectionError,\n} from \"effect-agent/thread-projection-maintenance\";\nimport { SqlClient } from \"effect/unstable/sql/SqlClient\";\n\nimport { DurableObjectContext } from \"./CloudflareBindings.ts\";\nimport { CloudflareDurableRuntimeConfig } from \"./CloudflareConfig.ts\";\nimport { safeCauseMessage } from \"./internal/boundary.ts\";\n\n/**\n * The single multiplexed Durable Object alarm (decision D-P6-2). A Durable Object has ONE\n * alarm slot; every cadence the Node host ran on fibers (wake scan, lease expiry, settlement\n * and abort re-checks, retry backoff) multiplexes into one idempotent maintenance pass, and\n * the slot always holds the EARLIEST deadline any caller asked for.\n *\n * The alarm invariant (plan §1.4): every committed actionable mutation carries a newer durable\n * maintenance generation and a committed alarm. Stable externally-driven waits may be\n * nonterminal without retaining an alarm; their resolving mutation advances the generation and\n * restores the alarm atomically.\n */\n\n/** The Durable Object alarm API failed; surfaces on host entry points as a typed refusal. */\nexport class DurableAlarmError extends Schema.TaggedError<DurableAlarmError>()(\n \"DurableAlarmError\",\n {\n operation: Schema.String,\n message: Schema.String,\n cause: Schema.optionalKey(Schema.Defect()),\n },\n) {}\n\nconst alarmFailure =\n (operation: string) =>\n (cause: unknown): DurableAlarmError =>\n DurableAlarmError.make({\n operation,\n message: safeCauseMessage(cause, \"The Cloudflare alarm API failed without a diagnostic\"),\n cause,\n });\n\n// SQL and raw KV/alarm operations share one physical SQLite transaction. Reserve its\n// connection for each short storage operation, never around a mutation or snapshot body.\nconst makeStorageOperation = Effect.map(\n SqlClient,\n (sql) =>\n <A>(operation: string, execute: () => Promise<A>) =>\n Effect.flatMap(Effect.serviceOption(sql.transactionService), (current) => {\n const body = Effect.uninterruptible(\n Effect.tryPromise({ try: execute, catch: alarmFailure(operation) }),\n );\n\n return current._tag === \"Some\"\n ? body\n : Effect.scoped(\n Effect.andThen(sql.reserve.pipe(Effect.mapError(alarmFailure(operation))), body),\n );\n }),\n);\n\n/** `ctx.storage` alarm slot as an Effect service; storage is truth, never a memory field. */\nexport class DurableAlarmService extends Context.Service<\n DurableAlarmService,\n {\n /** The scheduled deadline in epoch milliseconds, if any. */\n readonly scheduled: Effect.Effect<Option.Option<number>, DurableAlarmError>;\n /** Replace the slot with this deadline. */\n readonly scheduleAt: (epochMillis: number) => Effect.Effect<void, DurableAlarmError>;\n /** Keep the EARLIER of the existing deadline and this one (the multiplexing rule). */\n readonly ensureScheduledBy: (epochMillis: number) => Effect.Effect<void, DurableAlarmError>;\n /**\n * Arm an immediate alarm (the durable, coalescing local wake) — DEFERRED while a\n * maintenance pass is executing. Workerd cancels an in-flight alarm handler when a new\n * EARLIER deadline is written during its execution (`requestScheduledAlarm`), and the\n * maintenance pass runs INSIDE the alarm handler: an immediate wake landing mid-pass\n * (a routed port mutation, a sibling's `wake()`, the coordinator's own local notify)\n * would kill the running Attempt — manufacturing an ownership loss no real eviction\n * caused, and routing open uncertain-class Tool Calls into spurious Unknown Outcomes.\n * Deferral is contract-safe: wakes are droppable hints, every mutating entry point\n * pre-arms BEFORE its first durable mutation (the alarm invariant never rests on this\n * call). The pass's durable generation check observes any racing mutation, so the\n * in-memory hint does not need to be flushed after a stable wait is acknowledged.\n */\n readonly scheduleNow: Effect.Effect<void, DurableAlarmError>;\n /**\n * Run one maintenance pass with wake deferral (see `scheduleNow`). Calls made while `body`\n * executes are droppable promptness hints; correctness rests on the durable generation.\n */\n readonly withWakesDeferred: <A, E, R>(body: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;\n /** Clear the slot; correctness-sensitive clears live in maintenance generation transactions. */\n readonly cancel: Effect.Effect<void, DurableAlarmError>;\n }\n>()(\"@effect-agent/platform-cloudflare/DurableAlarmService\") {\n static readonly layer: Layer.Layer<DurableAlarmService, never, DurableObjectContext | SqlClient> =\n Layer.effect(DurableAlarmService)(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n /**\n * In-memory pass bookkeeping — a pure CACHE, never state: a fresh incarnation has no\n * running pass, and a deferred wake lost to eviction was only ever a promptness hint\n * on top of the already-committed pre-armed alarm.\n */\n const runningPasses = yield* Ref.make(0);\n\n const storageOperation = yield* makeStorageOperation;\n\n const scheduled = storageOperation(\"get alarm\", () => ctx.storage.getAlarm()).pipe(\n Effect.map((deadline) =>\n deadline === null ? Option.none<number>() : Option.some(deadline),\n ),\n );\n\n const scheduleAt = (epochMillis: number) =>\n storageOperation(\"set alarm\", () => ctx.storage.setAlarm(epochMillis));\n\n const ensureScheduledBy = (epochMillis: number) =>\n storageOperation(\"ensure alarm\", () =>\n ctx.storage.transaction(async (transaction) => {\n const existing = await transaction.getAlarm();\n\n if (existing === null || existing > epochMillis) {\n await transaction.setAlarm(epochMillis);\n }\n }),\n );\n\n const armNow = Clock.currentTimeMillis.pipe(\n Effect.flatMap((now) => ensureScheduledBy(now)),\n );\n\n const scheduleNow = Ref.get(runningPasses).pipe(\n Effect.flatMap((passes) => (passes > 0 ? Effect.void : armNow)),\n );\n\n const withWakesDeferred = <A, E, R>(body: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n Ref.update(runningPasses, (passes) => passes + 1).pipe(\n Effect.andThen(body),\n Effect.ensuring(Ref.update(runningPasses, (passes) => passes - 1)),\n );\n\n const cancel = storageOperation(\"delete alarm\", () => ctx.storage.deleteAlarm());\n\n return DurableAlarmService.of({\n scheduled,\n scheduleAt,\n ensureScheduledBy,\n scheduleNow,\n withWakesDeferred,\n cancel,\n });\n }),\n );\n}\n\n/** What one maintenance pass did — auditable evidence mirroring `NodeDurableHost`'s report. */\nexport class MaintenancePassReport extends Schema.Class<MaintenancePassReport>(\n \"@effect-agent/platform-cloudflare/MaintenancePassReport\",\n)({\n /** `caught-up` ran no runtime work (publication may be pending); `actionable` ran recovery. */\n phase: Schema.Literals([\"caught-up\", \"actionable\"]),\n /** Recovery decisions executed (or deferred) BEFORE any new claim in this pass. */\n recovered: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** Whether the head Attempt settled. Joined input may settle with that head. */\n settled: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** Submissions still nonterminal after the pass (suspended/unknown lanes stay honest). */\n nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** `rearmed` for dirty/autonomous work, `cleared` for stable waits or settlement. */\n alarm: Schema.Literals([\"rearmed\", \"cleared\"]),\n}) {}\n\n/** Fault boundaries around every maintenance-owned durable mutation. */\nexport type ThreadMaintenanceFailpointLocation =\n | \"maintenance:dirty:before\"\n | \"maintenance:dirty:after\"\n | \"maintenance:mutation:armed\"\n | \"maintenance:mutation:finished\"\n | \"maintenance:ensure:before\"\n | \"maintenance:ensure:after\"\n | \"maintenance:begin:before\"\n | \"maintenance:begin:after\"\n | \"maintenance:select:before\"\n | \"maintenance:select:after\"\n | \"maintenance:finish:before\"\n | \"maintenance:finish:after\";\n\nexport type ThreadMaintenanceFailpointHandler = (\n location: ThreadMaintenanceFailpointLocation,\n) => Effect.Effect<void>;\n\n/** Test-only fault authority; production uses the inert layer. */\nexport class ThreadMaintenanceFailpoint extends Context.Service<\n ThreadMaintenanceFailpoint,\n {\n readonly hit: ThreadMaintenanceFailpointHandler;\n }\n>()(\"@effect-agent/platform-cloudflare/ThreadMaintenanceFailpoint\") {\n static readonly layer = Layer.succeed(this)({ hit: () => Effect.void });\n}\n\n/**\n * Durable host publication of canonical records and ledger approval/abort/resolution intents.\n * The host owns schema-versioned cursors, destination idempotency and acknowledgement. Delivery\n * is at least once. Hooks must not write the alarm slot or mutate the supplied raw source ports.\n *\n * `invalidate`, `prepareGeneration` and `pendingDeadline` must be bounded local operations.\n * `prepareGeneration` durably invalidates a scan only when its generation changes; repeated\n * calls must preserve partial scan progress. It runs with no source mutation in flight.\n * `drain` performs bounded delivery and persists retries before returning. A pending deadline\n * defers runtime recovery/Attempts, allowing committed host publications to drain first.\n * Unexpected hook failures leave the prearmed generation for retry. Hooks acquire per-call\n * resources with Effect.scoped; Layer construction owns incarnation resources (eviction need\n * not run finalizers). Do not hold a local hook behind network I/O or call back into producers.\n */\nexport interface ThreadPublicationService {\n readonly invalidate: Effect.Effect<void, DurableAlarmError>;\n readonly prepareGeneration: (generation: bigint) => Effect.Effect<void, DurableAlarmError>;\n readonly drain: Effect.Effect<void, DurableAlarmError>;\n readonly pendingDeadline: Effect.Effect<Option.Option<number>, DurableAlarmError>;\n}\n\n/** Opt in with `ThreadObject.layer(registrations, { publication: Layer.effect(ThreadPublication)(...) })`. */\nexport class ThreadPublication extends Context.Service<\n ThreadPublication,\n ThreadPublicationService\n>()(\"@effect-agent/platform-cloudflare/ThreadPublication\") {\n static readonly layer = Layer.succeed(this)({\n invalidate: Effect.void,\n prepareGeneration: () => Effect.void,\n drain: Effect.void,\n pendingDeadline: Effect.succeed(Option.none()),\n });\n}\n\n/**\n * Host-assembled message recovery, supplied by ThreadObject.layer even when the application\n * rebuilds ThreadMaintenance. These obligations outlive source Runs and never defer a ready\n * source Attempt while a destination is processing an accepted message.\n */\nexport const ThreadMessageDelivery = Context.Reference<{\n readonly drain: Effect.Effect<void, DurableAlarmError>;\n /** Drain inserts and due retries during source work, finishing the bounded wave on completion. */\n readonly drainUntil?: (\n finished: Deferred.Deferred<void>,\n ) => Effect.Effect<void, DurableAlarmError>;\n readonly pendingDeadline: Effect.Effect<Option.Option<number>, DurableAlarmError>;\n}>(\"@effect-agent/platform-cloudflare/ThreadMessageDelivery\", {\n defaultValue: () => ({ drain: Effect.void, pendingDeadline: Effect.succeed(Option.none()) }),\n});\n\n/**\n * Application obligations sharing this Object's alarm. The deadline read is local and\n * read-only. Drain beside the native Attempt and always finish one initial bounded wave,\n * even when `finished` was already signalled. Then stop starting new waves on that signal\n * and finish the bounded current wave before returning. Native maintenance joins that work\n * before acknowledging a generation. Mutations use the same ThreadMutationGate; hooks never\n * write the raw alarm slot. Pending host work does not defer a ready model Attempt.\n */\nexport const ThreadHostMaintenance = Context.Reference<{\n readonly pendingDeadline: Effect.Effect<Option.Option<number>, DurableAlarmError>;\n readonly drainUntil: (\n finished: Deferred.Deferred<void>,\n ) => Effect.Effect<void, DurableAlarmError>;\n}>(\"@effect-agent/platform-cloudflare/ThreadHostMaintenance\", {\n defaultValue: () => ({\n pendingDeadline: Effect.succeed(Option.none()),\n drainUntil: () => Effect.void,\n }),\n});\n\nconst earliestDeadline = (\n left: Option.Option<number>,\n right: Option.Option<number>,\n): Option.Option<number> =>\n Option.isSome(left)\n ? Option.isSome(right)\n ? Option.some(Math.min(left.value, right.value))\n : left\n : right;\n\n/** @internal A committed source operation must not become a failed operation because delivery failed. */\nexport const publishCommitted = Effect.gen(function* () {\n const publication = yield* ThreadPublication;\n\n yield* publication.invalidate.pipe(Effect.andThen(publication.drain));\n}).pipe(\n Effect.catchCause((cause) =>\n Cause.hasInterrupts(cause)\n ? Effect.interrupt\n : Effect.logError(\"Thread publication deferred after source commit\", cause),\n ),\n);\n\nconst MaintenanceGeneration = Schema.BigIntFromString.check(\n Schema.isGreaterThanOrEqualToBigInt(0n),\n);\n\n/** Versioned, platform-private maintenance state stored through Durable Object KV. */\nclass ThreadMaintenanceState extends Schema.Class<ThreadMaintenanceState>(\n \"@effect-agent/platform-cloudflare/ThreadMaintenanceState\",\n)({\n schemaVersion: Schema.Literal(1),\n dirty: MaintenanceGeneration,\n processed: MaintenanceGeneration,\n nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n /** One physical-owner cursor; old single-lane records need no conversion. */\n lastServedThreadId: Schema.optionalKey(ThreadId),\n}) {}\n\nconst MAINTENANCE_STATE_KEY = \"effect-agent:thread-maintenance:v1\";\nconst decodeMaintenanceState = Schema.decodeUnknownSync(ThreadMaintenanceState);\nconst encodeMaintenanceState = Schema.encodeSync(ThreadMaintenanceState);\n\nconst initialMaintenanceState = (): ThreadMaintenanceState =>\n ThreadMaintenanceState.make({\n schemaVersion: 1,\n // Bootstrap Objects created by the pre-generation release without scanning the ledger in\n // the constructor. One useful pass classifies and acknowledges any existing obligation.\n dirty: 1n,\n processed: 0n,\n nonterminal: 0,\n });\n\nconst readMaintenanceState = async (\n transaction: DurableObjectTransaction,\n): Promise<{ readonly state: ThreadMaintenanceState; readonly initialized: boolean }> => {\n const encoded = await transaction.get(MAINTENANCE_STATE_KEY);\n\n return encoded === undefined\n ? { state: initialMaintenanceState(), initialized: false }\n : { state: decodeMaintenanceState(encoded), initialized: true };\n};\n\nconst ensureTransactionAlarmBy = async (\n transaction: DurableObjectTransaction,\n deadline: number,\n): Promise<void> => {\n const scheduled = await transaction.getAlarm();\n\n if (scheduled === null || scheduled > deadline) {\n await transaction.setAlarm(deadline);\n }\n};\n\nconst stableExternalWait = (\n snapshot: SubmissionSnapshot,\n reports: ReadonlyMap<string, RecoveryReport>,\n): boolean => {\n const decision = reports.get(snapshot.submissionId)?.decision._tag;\n\n // An accepted abort still owes cleanup/settlement even if its claim was deferred this pass.\n if (decision === \"SettleAborted\") return false;\n switch (snapshot.state) {\n case \"suspended\":\n case \"joined\":\n return true;\n case \"unknown\":\n return decision === \"AwaitUnknownResolution\" || decision === \"MarkUnknown\";\n case \"admitted\":\n return reports.get(snapshot.submissionId)?.decision._tag === \"AwaitParentEstablishment\";\n case \"input-applied\":\n case \"joining\":\n case \"ready\":\n case \"running\":\n case \"settled\":\n case \"terminalizing\":\n return false;\n }\n};\n\n/**\n * Shared prearm/acknowledgement boundary for ingress and runtime-owned producers.\n * `ThreadObject.layer` provides this same instance in its Services. Rebuilt runtime/maintenance\n * Layers must reuse that instance; a second gate cannot observe the native producers' activity.\n */\nexport class ThreadMutationGate extends Context.Service<\n ThreadMutationGate,\n {\n readonly withMutation: <A, E, R>(\n body: Effect.Effect<A, E, R>,\n /** Indexed host work has its own durable deadline and does not invalidate ledger recovery. */\n options?: { readonly invalidatesRecovery: boolean },\n ) => Effect.Effect<A, E | DurableAlarmError, R>;\n readonly withSnapshot: <A, E, R>(\n body: (active: number) => Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E, R>;\n }\n>()(\"@effect-agent/platform-cloudflare/internal/ThreadMutationGate\") {\n static readonly layer = Layer.effect(this)(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n const config = yield* CloudflareDurableRuntimeConfig;\n const failpoint = yield* ThreadMaintenanceFailpoint;\n // A fresh incarnation has no live mutations; durable generations survive eviction.\n const activeMutations = yield* Ref.make(0);\n const generationGate = yield* Semaphore.make(1);\n const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));\n\n const runTransaction = yield* makeStorageOperation;\n\n const beginMutation = Effect.fn(\"ThreadMaintenance.beginMutation\")(function* (\n invalidatesRecovery: boolean,\n ) {\n yield* failpoint.hit(\"maintenance:dirty:before\");\n const now = yield* Clock.currentTimeMillis;\n\n yield* runTransaction(\"advance maintenance generation\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state, initialized } = await readMaintenanceState(transaction);\n\n const next = ThreadMaintenanceState.make({\n ...state,\n dirty: state.dirty + (invalidatesRecovery ? 1n : 0n),\n });\n\n if (invalidatesRecovery || !initialized)\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));\n // The earliest configured retry bounds a newly actionable mutation without relying\n // on its best-effort immediate wake hint.\n await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);\n }),\n );\n yield* failpoint.hit(\"maintenance:dirty:after\");\n yield* Ref.update(activeMutations, (active) => active + 1);\n });\n\n const endMutation = generationGate.withPermit(\n Ref.update(activeMutations, (active) => Math.max(0, active - 1)),\n );\n\n const withMutation = <A, E, R>(\n body: Effect.Effect<A, E, R>,\n options?: { readonly invalidatesRecovery: boolean },\n ): Effect.Effect<A, E | DurableAlarmError, R> =>\n Effect.acquireUseRelease(\n generationGate.withPermit(beginMutation(options?.invalidatesRecovery ?? true)),\n () =>\n failpoint.hit(\"maintenance:mutation:armed\").pipe(\n Effect.andThen(body),\n Effect.tap(() => failpoint.hit(\"maintenance:mutation:finished\")),\n ),\n () => endMutation,\n );\n\n return ThreadMutationGate.of({\n withMutation,\n withSnapshot: (body) =>\n generationGate.withPermit(Effect.flatMap(Ref.get(activeMutations), body)),\n });\n }),\n );\n}\n\nexport type MaintenancePassFailure =\n | DurableWorkerFailure\n | DurableBindingFailure\n | DurableAlarmError\n | ThreadProjectionError;\n\n/**\n * Incremental, quiescent maintenance over a durable dirty/processed generation (issue #93).\n *\n * `pass` = generation snapshot/pre-arm → recovery → one head Attempt → generation acknowledgement:\n *\n * 1. One storage transaction reads dirty/processed and re-arms before work. A caught-up forced\n * alarm takes an O(1) path without recovery, ledger scans, or canonical-history reads.\n * 2. Recovery strictly precedes a new claim. One head Attempt advances the lane and requests\n * a safe yield after ten minutes. The whole event has a fourteen-minute cooperative timeout.\n * 3. The final transaction acknowledges only the generation observed at pass start. A racing\n * mutation therefore remains `dirty > processed` and retains its atomically-established alarm.\n * 4. Stable external waits acknowledge and clear. Autonomous retry, indeterminate, and lease\n * recovery states leave their generation dirty and retain bounded backoff rearming.\n */\nexport class ThreadMaintenance extends Context.Service<\n ThreadMaintenance,\n {\n /** One idempotent maintenance pass; failures propagate so workerd retries the alarm. */\n readonly pass: Effect.Effect<MaintenancePassReport, MaintenancePassFailure>;\n /**\n * Constructor gate: initialize/inspect only the O(1) maintenance record and ensure a dirty\n * generation has an alarm. It never scans the ledger or canonical history.\n */\n readonly ensureAlarm: Effect.Effect<void, MaintenancePassFailure>;\n /**\n * Serialize the pre-arm boundary with pass acknowledgement, advance the durable dirty\n * generation and arm the alarm in one transaction BEFORE running the caller's mutation.\n * A pass cannot acknowledge while that mutation remains in flight.\n */\n readonly withMutation: <A, E, R>(\n body: Effect.Effect<A, E, R>,\n ) => Effect.Effect<A, E | DurableAlarmError, R>;\n }\n>()(\"@effect-agent/platform-cloudflare/ThreadMaintenance\") {\n static readonly layer: Layer.Layer<\n ThreadMaintenance,\n never,\n | ThreadMutationGate\n | ThreadPublication\n | ThreadProjectionMaintenance\n | DurableAgentRuntime\n | SubmissionLedger\n | DurableAlarmService\n | ThreadMaintenanceFailpoint\n | CloudflareDurableRuntimeConfig\n | DurableObjectContext\n | SqlClient\n > = Layer.effect(ThreadMaintenance)(\n Effect.gen(function* () {\n const runtime = yield* DurableAgentRuntime;\n const ledger = yield* SubmissionLedger;\n const alarm = yield* DurableAlarmService;\n const config = yield* CloudflareDurableRuntimeConfig;\n const { ctx } = yield* DurableObjectContext;\n const failpoint = yield* ThreadMaintenanceFailpoint;\n\n /**\n * Consecutive no-progress passes — an in-memory CACHE, not state: a fresh incarnation\n * restarts at zero and merely re-arms sooner than a long-lived one would have.\n */\n const stalls = yield* Ref.make(0);\n const mutations = yield* ThreadMutationGate;\n const publication = yield* ThreadPublication;\n const projection = yield* ThreadProjectionMaintenance;\n const messages = yield* ThreadMessageDelivery;\n const host = yield* ThreadHostMaintenance;\n\n // A broken disposable index still needs a retry alarm and must not prevent startup.\n const projectionDeadline = projection.pendingDeadline.pipe(\n Effect.catchCauseIf(\n (cause) => !Cause.hasInterrupts(cause),\n (cause) =>\n Effect.logError(\"Thread projection deadline unavailable\", cause).pipe(\n Effect.as(Option.some(0)),\n ),\n ),\n );\n\n const pendingDeadline = Effect.gen(function* () {\n return earliestDeadline(\n earliestDeadline(yield* publication.pendingDeadline, yield* messages.pendingDeadline),\n earliestDeadline(yield* projectionDeadline, yield* host.pendingDeadline),\n );\n });\n\n const maintenancePassGate = yield* Semaphore.make(1);\n const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));\n\n const runTransaction = yield* makeStorageOperation;\n\n const ensureAlarm = Effect.fn(\"ThreadMaintenance.ensureAlarm\")(function* () {\n yield* failpoint.hit(\"maintenance:ensure:before\");\n const now = yield* Clock.currentTimeMillis;\n\n yield* runTransaction(\"ensure maintenance alarm\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state, initialized } = await readMaintenanceState(transaction);\n\n if (!initialized) {\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));\n }\n if (state.dirty > state.processed) {\n await ensureTransactionAlarmBy(transaction, now + config.wakeScanInterval);\n }\n }),\n );\n const deadline = yield* pendingDeadline;\n\n if (Option.isSome(deadline)) {\n yield* runTransaction(\"ensure publication alarm\", () =>\n ctx.storage.transaction((transaction) =>\n ensureTransactionAlarmBy(\n transaction,\n Math.max(now + minimumAlarmDelay, deadline.value),\n ),\n ),\n );\n }\n yield* failpoint.hit(\"maintenance:ensure:after\");\n });\n\n const beginPass = Effect.fn(\"ThreadMaintenance.beginPass\")(function* () {\n yield* failpoint.hit(\"maintenance:begin:before\");\n const now = yield* Clock.currentTimeMillis;\n\n const result = yield* runTransaction(\"begin maintenance pass\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state, initialized } = await readMaintenanceState(transaction);\n\n if (!initialized) {\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));\n }\n if (state.processed >= state.dirty) {\n // Prearm even a publication-only pass before invoking any host hook.\n await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);\n\n return { _tag: \"CaughtUp\" as const, nonterminal: state.nonterminal };\n }\n // Pre-arm the earliest retry before recovery. A successful finish may move this slot\n // LATER to its bounded backoff, which does not cancel the running handler.\n await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);\n\n return {\n _tag: \"Actionable\" as const,\n generation: state.dirty,\n nonterminal: state.nonterminal,\n };\n }),\n );\n\n yield* failpoint.hit(\"maintenance:begin:after\");\n\n return result;\n });\n\n const rearmDelay = Effect.fn(\"ThreadMaintenance.rearmDelay\")(function* (progressed: boolean) {\n const priorStalls = yield* Ref.getAndUpdate(stalls, (count) =>\n progressed ? 0 : count + 1,\n );\n\n if (progressed) return config.alarmBackoffBase;\n const exponent = Math.min(priorStalls, 30);\n const backoff = Math.min(config.alarmBackoffCap, config.alarmBackoffBase * 2 ** exponent);\n const jitter = yield* Random.next;\n // Full jitter over [backoff/2, backoff]: desynchronizes retry storms without ever\n // waiting longer than the deterministic bound.\n const jittered = Math.ceil(backoff / 2 + (backoff / 2) * jitter);\n\n return Math.min(jittered, config.wakeScanInterval);\n });\n\n const pass = Effect.fn(\"ThreadMaintenance.pass\")(function* (\n yieldAfter: DateTime.Utc,\n ): Effect.fn.Return<MaintenancePassReport, MaintenancePassFailure> {\n const annotate = (report: MaintenancePassReport) =>\n Effect.annotateCurrentSpan({\n phase: report.phase,\n recovered: report.recovered,\n settled: report.settled,\n nonterminal: report.nonterminal,\n alarm: report.alarm,\n }).pipe(Effect.as(report));\n\n const started = yield* mutations.withSnapshot((activeAtStart) =>\n Effect.gen(function* () {\n const generation = yield* beginPass();\n\n if (generation._tag === \"Actionable\" && activeAtStart === 0) {\n // The gate excludes a producer starting between the snapshot and certification.\n yield* publication.prepareGeneration(generation.generation);\n }\n\n return { ...generation, activeAtStart };\n }),\n );\n\n // Deliver beside source work, including messages inserted by the running Attempt.\n // Slow destination RPCs never consume the source execution window. Stop starting\n // waves when source work ends, then join the bounded current wave before acknowledgement.\n const deliveryFinished = yield* Deferred.make<void>();\n\n const delivery = yield* Effect.forkChild(\n messages.drainUntil?.(deliveryFinished) ?? messages.drain,\n );\n\n const hostWork = yield* Effect.forkChild(host.drainUntil(deliveryFinished));\n\n const finishDelivery = Deferred.succeed(deliveryFinished, undefined).pipe(\n Effect.andThen(Fiber.awaitAll([delivery, hostWork])),\n Effect.flatMap((outcomes) =>\n Effect.forEach(outcomes, (outcome) => outcome, { discard: true }),\n ),\n );\n\n // Capture derived-index failures until canonical work has had its turn. Interruption\n // still stops the event; ordinary failures and defects retain the prearmed generation.\n const projected = yield* Effect.exit(\n drainDue.pipe(Effect.provideService(ThreadProjectionMaintenance, projection)),\n );\n\n if (Exit.isFailure(projected) && Cause.hasInterrupts(projected.cause))\n return yield* Effect.failCause(projected.cause);\n const deadline = yield* publication.pendingDeadline;\n\n if (\n started._tag === \"Actionable\" ||\n (Option.isSome(deadline) && deadline.value <= (yield* Clock.currentTimeMillis))\n ) {\n yield* publication.drain;\n }\n const pending = yield* publication.pendingDeadline;\n\n if (started._tag === \"CaughtUp\" || Option.isSome(pending)) {\n yield* finishDelivery;\n if (Exit.isFailure(projected)) return yield* Effect.failCause(projected.cause);\n yield* failpoint.hit(\"maintenance:finish:before\");\n\n const disposition = yield* mutations.withSnapshot((active) =>\n Effect.gen(function* () {\n // Re-read under the producer gate: a concurrent append/host mutation cannot be\n // cleared using a stale empty deadline. Dirty generations bound all producer races.\n const latest = yield* pendingDeadline;\n const now = yield* Clock.currentTimeMillis;\n\n return yield* runTransaction(\"finish publication pass\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n const nativeDeadline =\n active > 0 || state.dirty > state.processed\n ? now + config.wakeScanInterval\n : Infinity;\n\n const next = Option.isSome(latest)\n ? Math.min(nativeDeadline, latest.value)\n : nativeDeadline;\n\n if (Number.isFinite(next)) {\n await transaction.setAlarm(Math.max(now + minimumAlarmDelay, next));\n\n return \"rearmed\" as const;\n }\n await transaction.deleteAlarm();\n\n return \"cleared\" as const;\n }),\n );\n }),\n );\n\n yield* failpoint.hit(\"maintenance:finish:after\");\n\n return yield* annotate(\n MaintenancePassReport.make({\n phase: \"caught-up\",\n recovered: 0,\n settled: 0,\n nonterminal: started.nonterminal,\n alarm: disposition,\n }),\n );\n }\n // Step 2 — reconciliation strictly precedes new work in this pass (exit gate).\n const recovered: ReadonlyArray<RecoveryReport> = yield* runtime.runRecovery;\n const reports = new Map(recovered.map((report) => [report.submissionId, report]));\n const current = yield* Stream.runCollect(ledger.scanNonterminal);\n const heads = new Map<ThreadId, SubmissionSnapshot>();\n\n for (const row of current) {\n if (!heads.has(row.threadId)) heads.set(row.threadId, row);\n }\n\n const eligible = [...heads.values()]\n .filter((head) => !stableExternalWait(head, reports))\n .map((head) => head.threadId)\n .sort();\n\n let selected = eligible[0];\n\n if (heads.size > 1 && selected !== undefined) {\n yield* failpoint.hit(\"maintenance:select:before\");\n selected = yield* runTransaction(\"select maintenance lane\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n const next =\n eligible.find(\n (threadId) =>\n state.lastServedThreadId === undefined || threadId > state.lastServedThreadId,\n ) ?? eligible[0];\n\n if (next !== undefined) {\n // Persist before the Attempt so an eviction or repeated yield cannot\n // monopolize the first lane. The generation and prearmed alarm survive.\n await transaction.put(\n MAINTENANCE_STATE_KEY,\n encodeMaintenanceState(\n ThreadMaintenanceState.make({ ...state, lastServedThreadId: next }),\n ),\n );\n }\n\n return next;\n }),\n );\n yield* failpoint.hit(\"maintenance:select:after\");\n }\n\n // One FIFO head per event, across all local lanes. The runtime keeps its normal\n // bounded Attempt and recovery contracts; followers belong to another alarm.\n const settlement =\n selected === undefined\n ? Option.none()\n : yield* runtime.processThreadHead(selected, { yieldAfter });\n\n yield* finishDelivery;\n if (Exit.isFailure(projected)) return yield* Effect.failCause(projected.cause);\n // Observe residual state before acknowledging this exact pass-start generation.\n const remaining = yield* Stream.runCollect(ledger.scanNonterminal);\n const waitingHeads = new Map<ThreadId, boolean>();\n\n const autonomous = remaining.some((snapshot) => {\n const headWaiting = waitingHeads.get(snapshot.threadId);\n\n if (headWaiting === undefined)\n waitingHeads.set(snapshot.threadId, stableExternalWait(snapshot, reports));\n // FIFO followers cannot execute through a stable external wait. Only plain queued\n // input is dormant here; admission repairs and accepted aborts still need a pass.\n if (\n headWaiting === true &&\n snapshot.state === \"ready\" &&\n reports.get(snapshot.submissionId)?.decision._tag === \"ApplyInput\"\n )\n return false;\n\n return !stableExternalWait(snapshot, reports);\n });\n\n const progressed =\n Option.isSome(settlement) ||\n recovered.some((report) => report.disposition === \"repaired\");\n\n const delay = autonomous ? yield* rearmDelay(progressed) : 0;\n const now = yield* Clock.currentTimeMillis;\n\n yield* failpoint.hit(\"maintenance:finish:before\");\n\n const alarmDisposition = yield* mutations.withSnapshot((active) =>\n Effect.gen(function* () {\n const publicationDeadline = yield* pendingDeadline;\n\n return yield* runTransaction(\"finish maintenance pass\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n\n // Autonomous work and in-flight mutations intentionally leave the observed\n // generation dirty. Otherwise acknowledge only the pass-start generation.\n const processed =\n autonomous || started.activeAtStart > 0 || active > 0\n ? state.processed\n : state.processed > started.generation\n ? state.processed\n : started.generation;\n\n const next = ThreadMaintenanceState.make({\n ...state,\n processed,\n nonterminal: remaining.length,\n });\n\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));\n if (autonomous) {\n // Replace the crash-fallback slot with this pass's bounded backoff. The target\n // is never earlier than the begin-pass fallback, so workerd does not cancel\n // this running alarm handler before its report/span can complete.\n await transaction.setAlarm(\n Option.isSome(publicationDeadline)\n ? Math.max(\n now + minimumAlarmDelay,\n Math.min(now + delay, publicationDeadline.value),\n )\n : now + delay,\n );\n\n return \"rearmed\" as const;\n }\n if (started.activeAtStart > 0 || active > 0 || next.dirty > next.processed) {\n // A mutation overlapped this pass's observation window or raced\n // acknowledgement. It stays dirty and its pre-armed bounded alarm survives;\n // unseen effects are never acknowledged. Do not accelerate that future alarm\n // from inside the current handler: workerd cancels a running handler when it\n // writes an earlier slot.\n await ensureTransactionAlarmBy(\n transaction,\n Option.isSome(publicationDeadline)\n ? Math.max(\n now + minimumAlarmDelay,\n Math.min(now + config.wakeScanInterval, publicationDeadline.value),\n )\n : now + config.wakeScanInterval,\n );\n\n return \"rearmed\" as const;\n }\n if (Option.isSome(publicationDeadline)) {\n await transaction.setAlarm(\n Math.max(now + minimumAlarmDelay, publicationDeadline.value),\n );\n\n return \"rearmed\" as const;\n }\n await transaction.deleteAlarm();\n\n return \"cleared\" as const;\n }),\n );\n }),\n );\n\n yield* failpoint.hit(\"maintenance:finish:after\");\n if (alarmDisposition === \"cleared\") {\n yield* Ref.set(stalls, 0);\n }\n\n return yield* annotate(\n MaintenancePassReport.make({\n phase: \"actionable\",\n recovered: recovered.length,\n settled: Option.isSome(settlement) ? 1 : 0,\n nonterminal: remaining.length,\n alarm: alarmDisposition,\n }),\n );\n });\n\n return ThreadMaintenance.of({\n // A mid-pass immediate hint is droppable; durable dirty state decides the final alarm.\n pass: Effect.gen(function* () {\n const yieldAfter = DateTime.makeUnsafe((yield* Clock.currentTimeMillis) + 10 * 60_000);\n\n return yield* alarm.withWakesDeferred(maintenancePassGate.withPermit(pass(yieldAfter)));\n }).pipe(\n // Include permit waiting, recovery and acknowledgement in the event deadline.\n // Interruption releases Attempt ownership, leaving the prearmed dirty generation\n // for recovery. It never changes the logical Run duration or settles a policy failure.\n // This cooperative timer cannot preempt synchronous CPU work or stuck finalizers.\n Effect.timeoutOrElse({\n duration: \"14 minutes\",\n orElse: () =>\n DurableAlarmError.make({\n operation: \"maintenance pass deadline\",\n message:\n \"The maintenance event exceeded its 14 minute deadline; durable recovery remains pending\",\n }),\n }),\n ),\n ensureAlarm: mutations.withSnapshot(() => ensureAlarm()),\n withMutation: (body) =>\n mutations.withMutation(\n body.pipe(\n Effect.tap(() =>\n publishCommitted.pipe(Effect.provideService(ThreadPublication, publication)),\n ),\n ),\n ),\n });\n }),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,IAAa,oBAAb,cAAuC,OAAO,YAA+B,CAAC,CAC5E,qBACA;CACE,WAAW,OAAO;CAClB,SAAS,OAAO;CAChB,OAAO,OAAO,YAAY,OAAO,OAAO,CAAC;AAC3C,CACF,CAAC,CAAC,CAAC;AAEH,MAAM,gBACH,eACA,UACC,kBAAkB,KAAK;CACrB;CACA,SAAS,iBAAiB,OAAO,sDAAsD;CACvF;AACF,CAAC;AAIL,MAAM,uBAAuB,OAAO,IAClC,YACC,SACK,WAAmB,YACrB,OAAO,QAAQ,OAAO,cAAc,IAAI,kBAAkB,IAAI,YAAY;CACxE,MAAM,OAAO,OAAO,gBAClB,OAAO,WAAW;EAAE,KAAK;EAAS,OAAO,aAAa,SAAS;CAAE,CAAC,CACpE;CAEA,OAAO,QAAQ,SAAS,SACpB,OACA,OAAO,OACL,OAAO,QAAQ,IAAI,QAAQ,KAAK,OAAO,SAAS,aAAa,SAAS,CAAC,CAAC,GAAG,IAAI,CACjF;AACN,CAAC,CACP;;AAGA,IAAa,sBAAb,MAAa,4BAA4B,QAAQ,QA+B/C,CAAC,CAAC,uDAAuD,CAAC,C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AAO,UACL,iBAAiB,KAAK,OAAO,eAAe,mBAAmB,WAAW,CAAC,CAC7E,CACF,CACF;EACJ,CAAC;CACH,CAAC,CACH;AACF"}
|
|
@@ -1407,14 +1407,14 @@ declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorded | Hos
|
|
|
1407
1407
|
readonly _tag: "JoinedToHost";
|
|
1408
1408
|
readonly submissionId: string;
|
|
1409
1409
|
readonly hostSubmissionId: string;
|
|
1410
|
+
} | {
|
|
1411
|
+
readonly _tag: "HostProtocolError";
|
|
1412
|
+
readonly message: string;
|
|
1410
1413
|
} | {
|
|
1411
1414
|
readonly _tag: "DurableAlarmError";
|
|
1412
1415
|
readonly operation: string;
|
|
1413
1416
|
readonly message: string;
|
|
1414
1417
|
readonly cause?: Schema.Json | undefined;
|
|
1415
|
-
} | {
|
|
1416
|
-
readonly _tag: "HostProtocolError";
|
|
1417
|
-
readonly message: string;
|
|
1418
1418
|
} | {
|
|
1419
1419
|
readonly _tag: "ApprovalConflict";
|
|
1420
1420
|
readonly submissionId: string;
|
|
@@ -344,13 +344,13 @@ declare const encodeAdminResponse: (input: AdminFailed | ExplainedRecovery | Obl
|
|
|
344
344
|
readonly author: string;
|
|
345
345
|
readonly reason: string;
|
|
346
346
|
readonly resolution: {
|
|
347
|
+
readonly _tag: "SafeToRetry";
|
|
348
|
+
} | {
|
|
347
349
|
readonly _tag: "CompletedWithResult";
|
|
348
350
|
readonly result: Schema.Json;
|
|
349
351
|
readonly isFailure: boolean;
|
|
350
352
|
} | {
|
|
351
353
|
readonly _tag: "NeverHappened";
|
|
352
|
-
} | {
|
|
353
|
-
readonly _tag: "SafeToRetry";
|
|
354
354
|
} | {
|
|
355
355
|
readonly _tag: "AbortSubmission";
|
|
356
356
|
};
|
|
@@ -723,40 +723,40 @@ declare const encodeAdminResponse: (input: AdminFailed | ExplainedRecovery | Obl
|
|
|
723
723
|
readonly actualEpoch: number;
|
|
724
724
|
readonly attemptedEpoch: number;
|
|
725
725
|
} | {
|
|
726
|
-
readonly _tag: "
|
|
727
|
-
readonly
|
|
726
|
+
readonly _tag: "OperationDenied";
|
|
727
|
+
readonly operation: "abort" | "awaitSettlement" | "explain" | "observe" | "resolveApproval" | "resolveUnknown" | "retry" | "scanObligations" | "verify" | "wake";
|
|
728
|
+
readonly reason: string;
|
|
729
|
+
readonly threadId?: string | undefined;
|
|
730
|
+
readonly submissionId?: string | undefined;
|
|
728
731
|
} | {
|
|
729
732
|
readonly _tag: "DigestError";
|
|
730
733
|
readonly message: string;
|
|
731
734
|
readonly cause?: Schema.Json | undefined;
|
|
735
|
+
} | {
|
|
736
|
+
readonly _tag: "DurableRuntimeFailpointError";
|
|
737
|
+
readonly location: "abort:after-intent" | "approval:after-request-append" | "approval:after-suspend" | "checkpoint:after-save" | "checkpoint:before-save" | "claim:after-claim" | "compaction:after-canonical-append" | "compaction:before-canonical-append" | "input:after-canonical-append" | "join:after-canonical-append" | "join:after-claim" | "policy:after-reservation-append" | "policy:before-reservation-append" | "resolve:after-intent" | "run:after-start-append" | "run:before-start-append" | "step:after-step-append" | "subagent:after-admit" | "subagent:after-child-abort-intent" | "subagent:after-child-ready" | "subagent:after-join-append" | "subagent:after-release" | "subagent:after-release-pending" | "subagent:after-request-append" | "subagent:after-reserve" | "subagent:after-sibling-settle" | "subagent:after-start-append" | "subagent:after-suspend" | "subagent:before-join-append" | "submit:after-admit" | "submit:after-materialize" | "terminalize:after-canonical-append" | "terminalize:after-reserve" | "tools:after-prepared-append" | "tools:before-prepared-append" | "turn:after-canonical-append" | "turn:after-response-append" | "turn:after-results-append" | "update:after-canonical-append" | "update:after-delivery-insert" | "update:before-canonical-append" | "update:before-delivery-insert" | "worker:after-completion-append" | "worker:after-origin-append" | "worker:after-report-append" | "worker:after-report-delivery" | "worker:after-source-append" | "worker:after-subtree-append" | "worker:before-completion-append" | "worker:before-origin-append" | "worker:before-report-append" | "worker:before-report-delivery" | "worker:before-source-append" | "worker:before-subtree-append";
|
|
738
|
+
} | {
|
|
739
|
+
readonly _tag: "OwnershipLost";
|
|
740
|
+
readonly submissionId: string;
|
|
741
|
+
readonly actualEpoch: number;
|
|
742
|
+
} | {
|
|
743
|
+
readonly _tag: "RunJournalError";
|
|
744
|
+
readonly message: string;
|
|
745
|
+
readonly cause?: Schema.Json | undefined;
|
|
732
746
|
} | {
|
|
733
747
|
readonly _tag: "DurableAlarmError";
|
|
734
748
|
readonly operation: string;
|
|
735
749
|
readonly message: string;
|
|
736
750
|
readonly cause?: Schema.Json | undefined;
|
|
737
751
|
} | {
|
|
738
|
-
readonly _tag: "
|
|
739
|
-
readonly
|
|
740
|
-
} | {
|
|
741
|
-
readonly _tag: "OperationDenied";
|
|
742
|
-
readonly operation: "abort" | "awaitSettlement" | "explain" | "observe" | "resolveApproval" | "resolveUnknown" | "retry" | "scanObligations" | "verify" | "wake";
|
|
743
|
-
readonly reason: string;
|
|
744
|
-
readonly threadId?: string | undefined;
|
|
745
|
-
readonly submissionId?: string | undefined;
|
|
752
|
+
readonly _tag: "HostProtocolError";
|
|
753
|
+
readonly message: string;
|
|
746
754
|
} | {
|
|
747
755
|
readonly _tag: "RetryRefused";
|
|
748
756
|
readonly submissionId: string;
|
|
749
757
|
readonly refusal: "await-approval-decision" | "await-unknown-resolution" | "settled";
|
|
750
758
|
readonly decisionTag: string;
|
|
751
759
|
readonly message: string;
|
|
752
|
-
} | {
|
|
753
|
-
readonly _tag: "RunJournalError";
|
|
754
|
-
readonly message: string;
|
|
755
|
-
readonly cause?: Schema.Json | undefined;
|
|
756
|
-
} | {
|
|
757
|
-
readonly _tag: "OwnershipLost";
|
|
758
|
-
readonly submissionId: string;
|
|
759
|
-
readonly actualEpoch: number;
|
|
760
760
|
};
|
|
761
761
|
}, Schema.SchemaError, never>;
|
|
762
762
|
declare const decodeAdminResponse: (input: unknown, options?: import("effect/SchemaAST").ParseOptions) => Effect.Effect<AdminFailed | ExplainedRecovery | ObligationsScanned | RetryExecuted | VerifiedIntegrity, Schema.SchemaError, never>;
|
|
@@ -809,4 +809,4 @@ interface Class<EventServices = never> {
|
|
|
809
809
|
declare const make: <ApplicationServices, ApplicationError, EventServices = never, EventLayerError = never>(applicationLayer: Layer.Layer<CloudflareDurableRuntimeServices | ApplicationServices, ApplicationError, CloudflareBootstrapServices | DurableObjectState$1.DurableObjectState | WorkerEnvironment | DurableObjectContext | ThreadObjectNamespace>, options: Options<ApplicationServices, EventServices, EventLayerError>) => Class<ApplicationServices | EventServices>;
|
|
810
810
|
//#endregion
|
|
811
811
|
export { ThreadPublicationOptions as A, portCall as C, CloudflareDurableRuntimeOptions as D, CloudflareDurableRuntimeInitializationError as E, layerConfig as M, layerHostConfig as N, CloudflareDurableRuntimeServices as O, layerInHost as P, make as S, CloudflareBootstrapServices as T, decodeAdminVerifyRequest as _, AdminVerifyRequest as a, encodeAdminResponse as b, Instance as c, RetryExecuted as d, ThreadObject_d_exports as f, decodeAdminResponse as g, decodeAdminExplainRequest as h, AdminResponse as i, layer as j, ThreadObjectPorts as k, ObligationsScanned as l, VerifiedIntegrity as m, AdminFailed as n, Class as o, ThreadRpcOperation as p, AdminFailure as r, ExplainedRecovery as s, AdminExplainRequest as t, Options as u, decodeObligationThresholds as v, submit as w, handleRpc as x, decodeRetryCommand as y };
|
|
812
|
-
//# sourceMappingURL=ThreadObject-
|
|
812
|
+
//# sourceMappingURL=ThreadObject-BMNq8kuv.d.mts.map
|
|
@@ -34,7 +34,7 @@ import { MessageDeliveryDriver, MessageDeliveryError, MessageDeliveryStore } fro
|
|
|
34
34
|
import { CurrentToolFailureObserver, RunContextPreparationPassthrough, RunToolAuthorization, toolFailureObserverLayer } from "effect-agent/run-options";
|
|
35
35
|
import { ToolReconciler } from "effect-agent/tool-reconciler";
|
|
36
36
|
//#region src/internal/message-delivery.ts
|
|
37
|
-
/** Every
|
|
37
|
+
/** Every write prearms its owner; the delivery due index owns its recovery deadline. */
|
|
38
38
|
const guardedMessageDeliveryStoreLayer = Layer.effect(MessageDeliveryStore, Effect.gen(function* () {
|
|
39
39
|
const store = yield* MessageDeliveryStore;
|
|
40
40
|
const mutations = yield* ThreadMutationGate;
|
|
@@ -46,7 +46,7 @@ const guardedMessageDeliveryStoreLayer = Layer.effect(MessageDeliveryStore, Effe
|
|
|
46
46
|
reason: "validation",
|
|
47
47
|
operation: "message owner"
|
|
48
48
|
}));
|
|
49
|
-
const mutate = (body) => mutations.withMutation(cacheGate.withPermit(Ref.set(deadline, void 0).pipe(Effect.andThen(body)))).pipe(Effect.catchTag("DurableAlarmError", () => MessageDeliveryError.make({
|
|
49
|
+
const mutate = (body) => mutations.withMutation(cacheGate.withPermit(Ref.set(deadline, void 0).pipe(Effect.andThen(body))), { invalidatesRecovery: false }).pipe(Effect.catchTag("DurableAlarmError", () => MessageDeliveryError.make({
|
|
50
50
|
reason: "storage",
|
|
51
51
|
operation: "prearm message delivery"
|
|
52
52
|
})));
|
|
@@ -832,4 +832,4 @@ const make = (applicationLayer, options) => {
|
|
|
832
832
|
//#endregion
|
|
833
833
|
export { layer as C, layerInHost as E, ThreadObjectPorts as S, layerHostConfig as T, encodeAdminResponse as _, AdminVerifyRequest as a, portCall as b, RetryExecuted as c, VerifiedIntegrity as d, decodeAdminExplainRequest as f, decodeRetryCommand as g, decodeObligationThresholds as h, AdminResponse as i, ThreadObject_exports as l, decodeAdminVerifyRequest as m, AdminFailed as n, ExplainedRecovery as o, decodeAdminResponse as p, AdminFailure as r, ObligationsScanned as s, AdminExplainRequest as t, ThreadRpcOperation as u, handleRpc as v, layerConfig as w, submit as x, make as y };
|
|
834
834
|
|
|
835
|
-
//# sourceMappingURL=ThreadObject-
|
|
835
|
+
//# sourceMappingURL=ThreadObject-DvRG0dDz.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ThreadObject-DvRG0dDz.mjs","names":["EffectCfDurableObjectState","EffectCfDurableObject"],"sources":["../src/internal/message-delivery.ts","../src/internal/progress-wait.ts","../src/internal/transport.ts","../src/internal/layers.ts","../src/ThreadObject.ts"],"sourcesContent":["import { Clock, Context, Deferred, Effect, Layer, Option, Ref, Semaphore, Stream } from \"effect\";\nimport { type ThreadId } from \"effect-agent/identifiers\";\nimport {\n MessageDeliveryDriver,\n MessageDeliveryError,\n MessageDeliveryStore,\n} from \"effect-agent/message-delivery\";\nimport { WakeScheduler } from \"effect-agent/wake-scheduler\";\n\nimport { DurableAlarmError, ThreadMessageDelivery, ThreadMutationGate } from \"../Alarm.ts\";\nimport { ThreadObjectPlacement } from \"../CloudflareBindings.ts\";\nimport { CloudflareDurableRuntimeConfig } from \"../CloudflareConfig.ts\";\n\n/** Every write prearms its owner; the delivery due index owns its recovery deadline. */\nexport const guardedMessageDeliveryStoreLayer = Layer.effect(\n MessageDeliveryStore,\n Effect.gen(function* () {\n const store = yield* MessageDeliveryStore;\n const mutations = yield* ThreadMutationGate;\n const wakes = yield* WakeScheduler;\n const { ownsThread } = yield* ThreadObjectPlacement;\n // Reconstructed as unknown on every incarnation. The gate prevents a racing read from\n // caching an empty deadline across a write; SQL remains the recovery authority.\n const deadline = yield* Ref.make<number | null | undefined>(undefined);\n const cacheGate = yield* Semaphore.make(1);\n\n const local = <A, E>(\n owner: ThreadId | undefined,\n body: Effect.Effect<A, E>,\n ): Effect.Effect<A, E | MessageDeliveryError> =>\n owner === undefined || ownsThread(owner)\n ? body\n : Effect.fail(\n MessageDeliveryError.make({ reason: \"validation\", operation: \"message owner\" }),\n );\n\n const mutate = <A, E>(body: Effect.Effect<A, E>) =>\n mutations\n .withMutation(\n cacheGate.withPermit(Ref.set(deadline, undefined).pipe(Effect.andThen(body))),\n // A foreign receipt changing does not make the source ledger actionable. Keep the\n // prearm and producer gate so eviction and a racing pass cannot lose delivery work.\n { invalidatesRecovery: false },\n )\n .pipe(\n Effect.catchTag(\"DurableAlarmError\", () =>\n MessageDeliveryError.make({ reason: \"storage\", operation: \"prearm message delivery\" }),\n ),\n );\n\n const nextDeadline = cacheGate.withPermit(\n Effect.gen(function* () {\n const cached = yield* Ref.get(deadline);\n\n if (cached !== undefined) return cached;\n const current = yield* store.nextDeadline();\n\n yield* Ref.set(deadline, current);\n\n return current;\n }),\n );\n\n return MessageDeliveryStore.of({\n limits: store.limits,\n maxStoredValueBytes: store.maxStoredValueBytes,\n insert: (record) =>\n local(\n record.key.ownerThreadId,\n mutate(store.insert(record)).pipe(\n Effect.tap(() => wakes.notify(record.key.ownerThreadId)),\n ),\n ),\n get: (key) => local(key.ownerThreadId, store.get(key)),\n list: (request) => local(request.ownerThreadId, store.list(request)),\n change: (key, change) => local(key.ownerThreadId, mutate(store.change(key, change))),\n // Only the trusted physical-owner pump omits an owner. All returned keys still\n // pass placement validation before the driver may dispatch any of the wave.\n due: (nowMillis, limit, owner) =>\n local(owner, store.due(nowMillis, limit, owner)).pipe(\n Effect.filterOrFail(\n (keys) => keys.every((key) => ownsThread(key.ownerThreadId)),\n () => MessageDeliveryError.make({ reason: \"validation\", operation: \"message owner\" }),\n ),\n ),\n nextDeadline: (owner) =>\n local(owner, owner === undefined ? nextDeadline : store.nextDeadline(owner)),\n });\n }),\n);\n\n/** Message progress shares the native alarm slot without blocking source runtime work. */\nexport const threadMessageDeliveryLayer = Layer.effectContext(\n Effect.gen(function* () {\n const driver = yield* MessageDeliveryDriver;\n const store = yield* MessageDeliveryStore;\n const wakes = yield* WakeScheduler;\n const config = yield* CloudflareDurableRuntimeConfig;\n\n const failure = (operation: string) => () =>\n DurableAlarmError.make({\n operation,\n message: \"Durable message recovery remains pending\",\n });\n\n const drain = Effect.gen(function* () {\n const deadline = yield* store.nextDeadline();\n\n if (deadline !== null && deadline <= (yield* Clock.currentTimeMillis)) {\n yield* driver.runDue();\n }\n }).pipe(Effect.mapError(failure(\"drain message delivery\")));\n\n return Context.make(ThreadMessageDelivery, {\n drain,\n drainUntil: Effect.fn(\"ThreadMessageDelivery.drainUntil\")(function* (\n finished: Deferred.Deferred<void>,\n ) {\n // One scoped subscription covers every logical lane in this physical owner.\n // Acquire it before reading durable deadlines; hints remain droppable.\n const notified = (yield* Stream.toPull(wakes.wakes)).pipe(Effect.catch(() => Effect.never));\n\n // Always finish one wave; source completion prevents starting subsequent waves.\n yield* Effect.gen(function* () {\n yield* drain;\n\n const deadline = yield* store\n .nextDeadline()\n .pipe(Effect.mapError(failure(\"read message deadline\")));\n\n // The index includes unfinished waves, lease expiry, retry and settlement polls.\n // Yield at least one millisecond for an already-due deadline instead of spinning.\n const delay =\n deadline === null\n ? config.wakeScanInterval\n : Math.min(\n config.wakeScanInterval,\n Math.max(1, deadline - (yield* Clock.currentTimeMillis)),\n );\n\n yield* Effect.raceFirst(\n Deferred.await(finished),\n Effect.raceFirst(notified, Effect.sleep(delay)),\n );\n }).pipe(Effect.repeat({ until: () => Deferred.isDone(finished) }));\n }, Effect.scoped),\n pendingDeadline: store\n .nextDeadline()\n .pipe(Effect.map(Option.fromNullishOr), Effect.mapError(failure(\"read message deadline\"))),\n });\n }),\n);\n","import { Context, Deferred, Effect, Layer, Ref, type Scope } from \"effect\";\n\n/** Cancellation tombstones are bounded hints, never durable authority. */\nconst MAX_CANCELLATION_TOMBSTONES = 1_024;\n\ntype ActiveRegistration = ReadonlySet<Deferred.Deferred<void>>;\ntype Registration = ActiveRegistration | \"cancelled\";\ntype Registrations = ReadonlyMap<string, Registration>;\n\n/**\n * Per-incarnation cancellation registry for long-lived progress RPCs. The public runtime owns\n * the actual wake registration; this host-only registry lets an interrupted Worker Effect ask\n * the Object to interrupt its scoped wait before the Worker execution context itself ends.\n */\nexport class ProgressWaitRegistry extends Context.Service<\n ProgressWaitRegistry,\n {\n /** Register a Scope-owned cancellation signal, observing any early cancel tombstone. */\n readonly subscribe: (\n waiterId: string,\n ) => Effect.Effect<Effect.Effect<void>, never, Scope.Scope>;\n /** Cancel every attempt and retain a bounded tombstone for later transport attempts. */\n readonly cancel: (waiterId: string) => Effect.Effect<void>;\n }\n>()(\"@effect-agent/platform-cloudflare/ProgressWaitRegistry\") {\n static readonly layer: Layer.Layer<ProgressWaitRegistry> = Layer.effect(\n ProgressWaitRegistry,\n Effect.gen(function* () {\n const registrations = yield* Ref.make<Registrations>(new Map());\n\n const remove = (waiterId: string, deferred: Deferred.Deferred<void>) =>\n Ref.update(registrations, (current) => {\n const existing = current.get(waiterId);\n\n if (existing === undefined || existing === \"cancelled\" || !existing.has(deferred)) {\n return current;\n }\n const next = new Map(current);\n const active = new Set(existing);\n\n active.delete(deferred);\n if (active.size === 0) {\n next.delete(waiterId);\n } else {\n next.set(waiterId, active);\n }\n\n return next;\n });\n\n const subscribe = Effect.fn(\"ProgressWaitRegistry.subscribe\")(\n (waiterId: string): Effect.Effect<Effect.Effect<void>, never, Scope.Scope> =>\n Effect.gen(function* () {\n const deferred = yield* Deferred.make<void>();\n\n yield* Effect.addFinalizer(() => remove(waiterId, deferred));\n\n const cancelled = yield* Ref.modify(registrations, (current) => {\n const existing = current.get(waiterId);\n const next = new Map(current);\n\n if (existing === \"cancelled\") {\n return [true, current] as const;\n }\n const active = new Set(existing ?? []);\n\n active.add(deferred);\n next.set(waiterId, active);\n\n return [false, next] as const;\n });\n\n return { cancelled, deferred };\n }).pipe(\n Effect.map(({ cancelled, deferred }) =>\n cancelled ? Effect.void : Deferred.await(deferred),\n ),\n ),\n );\n\n // Updating the registry and completing captured signals form one nonblocking operation;\n // interruption between them must not strand attempts removed from the active registry.\n const cancel = Effect.fn(\"ProgressWaitRegistry.cancel\")(function* (waiterId: string) {\n const waiters = yield* Ref.modify(\n registrations,\n (current): readonly [ReadonlyArray<Deferred.Deferred<void>>, Registrations] => {\n const existing = current.get(waiterId);\n\n if (existing === \"cancelled\") return [[], current] as const;\n const next = new Map(current);\n\n // A retry may arrive after an active attempt was cancelled. Retain the same\n // tombstone used for early cancellation, ordered by cancellation time.\n next.delete(waiterId);\n next.set(waiterId, \"cancelled\");\n let tombstones = 0;\n\n for (const registration of next.values()) {\n if (registration === \"cancelled\") tombstones += 1;\n }\n if (tombstones > MAX_CANCELLATION_TOMBSTONES) {\n for (const [id, registration] of next) {\n if (registration !== \"cancelled\") continue;\n next.delete(id);\n break;\n }\n }\n\n return [existing === undefined ? [] : [...existing], next] as const;\n },\n );\n\n yield* Effect.forEach(waiters, (waiter) => Deferred.succeed(waiter, undefined), {\n discard: true,\n });\n }, Effect.uninterruptible);\n\n return ProgressWaitRegistry.of({ subscribe, cancel });\n }),\n );\n}\n","import {\n ThreadPortTransport,\n portTransportFailure,\n} from \"@effect-agent/storage-cloudflare/port-routing\";\nimport { Effect, Layer } from \"effect\";\n\nimport { callThreadObject, ThreadObjectNamespace } from \"../CloudflareBindings.ts\";\n\n/**\n * `ThreadPortTransport` over native Durable Object JS RPC (decision D-P6-3): one\n * `portCall(envelope)` on the stub of the Object that owns the addressed Thread\n * (`namespace.idFromName(threadId)` — the identity rule, plan §1.2). The envelopes are\n * already Schema-encoded JSON, so the RPC boundary carries only structured-cloneable values;\n * the protocol module stays transport-agnostic and fetch-with-JSON remains the documented\n * fallback carrier.\n *\n * Every delivery problem — stub construction, RPC rejection, overload, deploy-in-progress —\n * surfaces as `PortTransportError` (preserving the platform stub's own `retryable` signal\n * when present) and NEVER as a fabricated answer: on `resolveAdmission` the routing layer\n * turns exactly this error into `AdmissionIndeterminate` (SUB-031).\n */\nexport const threadPortTransportLayer: Layer.Layer<\n ThreadPortTransport,\n never,\n ThreadObjectNamespace\n> = Layer.effect(ThreadPortTransport)(\n Effect.gen(function* () {\n const namespace = yield* ThreadObjectNamespace;\n\n return ThreadPortTransport.of({\n call: (threadId, request) =>\n callThreadObject(\n threadId,\n (target) => target.portCall(request),\n (cause) => portTransportFailure(threadId, cause),\n ).pipe(\n Effect.provideService(ThreadObjectNamespace, namespace),\n Effect.withSpan(\"CloudflarePortTransport.call\", {\n attributes: { threadId },\n }),\n ),\n });\n }),\n);\n","import { doMessageDeliveryStoreLayer } from \"@effect-agent/storage-cloudflare/do-message-delivery-store\";\nimport {\n type DoStorageFailpointHandler,\n type DoStorageFailpoint,\n} from \"@effect-agent/storage-cloudflare/do-storage-failpoint\";\nimport { submissionLedgerLayer } from \"@effect-agent/storage-cloudflare/do-submission-ledger\";\nimport {\n threadStoreLayer,\n storageConfigLayer,\n storageFailpointLayer,\n type DoStorageInitializationError,\n type DoStorageOptions,\n} from \"@effect-agent/storage-cloudflare/do-thread-store\";\nimport {\n type PortRequest,\n type PortResponse,\n} from \"@effect-agent/storage-cloudflare/port-protocol\";\nimport {\n executePortRequest,\n routedThreadStoreLayer,\n routedSubmissionLedgerLayer,\n} from \"@effect-agent/storage-cloudflare/port-routing\";\nimport { BrowserCrypto } from \"@effect/platform-browser\";\nimport { SqliteClient } from \"@effect/sql-sqlite-do\";\nimport {\n type Crypto,\n Cause,\n Context,\n Duration,\n Effect,\n Layer,\n Schema,\n Semaphore,\n type Option,\n} from \"effect\";\nimport {\n compileRegistrations,\n type AgentRegistration,\n type ResolvedBinding,\n} from \"effect-agent/agent-registration\";\nimport { type DigestError } from \"effect-agent/digest\";\nimport { DurableAgentRuntime, DurableRuntimeConfig } from \"effect-agent/durable-agent-runtime\";\nimport {\n DurableRuntimeFailpoint,\n type DurableRuntimeFailpointHandler,\n} from \"effect-agent/durable-failpoint\";\nimport { ThreadId, type SubmissionId } from \"effect-agent/identifiers\";\nimport {\n type MessageDeliveryStore,\n MessageDeliveryDriver,\n type MessageDeliveryError,\n} from \"effect-agent/message-delivery\";\nimport {\n operationAuthorizerLayer,\n type OperationAuthorizerService,\n} from \"effect-agent/operation-authorizer\";\nimport { type PreparedInputAdmission } from \"effect-agent/prepared-input-admission\";\nimport { ProducerId } from \"effect-agent/records\";\nimport {\n type RunContextPreparation,\n type RunCostEstimator,\n type RunToolFailureObserver,\n} from \"effect-agent/run-options\";\nimport {\n CurrentToolFailureObserver,\n RunContextPreparationPassthrough,\n RunToolAuthorization,\n toolFailureObserverLayer,\n} from \"effect-agent/run-options\";\nimport {\n LedgerError,\n SubmissionLedger,\n SubmissionLookupById,\n type SubmissionSnapshot,\n} from \"effect-agent/submission-ledger\";\nimport { ThreadProjectionMaintenance } from \"effect-agent/thread-projection-maintenance\";\nimport { ThreadStoreError, ThreadStore } from \"effect-agent/thread-store\";\nimport { ToolReconciler } from \"effect-agent/tool-reconciler\";\nimport { type WakeScheduler } from \"effect-agent/wake-scheduler\";\nimport { SqlClient } from \"effect/unstable/sql/SqlClient\";\n\nimport {\n ThreadMaintenance,\n ThreadMutationGate,\n ThreadPublication,\n publishCommitted,\n ThreadMaintenanceFailpoint,\n DurableAlarmService,\n type ThreadMaintenanceFailpointHandler,\n} from \"../Alarm.ts\";\nimport {\n ThreadObjectIdentity,\n ThreadObjectPlacement,\n DurableObjectContext,\n type ThreadObjectNamespace,\n} from \"../CloudflareBindings.ts\";\nimport {\n CLOUDFLARE_RUNTIME_DEFAULTS,\n CloudflareDurableRuntimeConfig,\n CloudflareDurableRuntimeConfigValue,\n CloudflarePlatformConfigError,\n} from \"../CloudflareConfig.ts\";\nimport { CloudflareThreadClient } from \"../CloudflareThreadClient.ts\";\nimport { cloudflareWakeSchedulerLayer } from \"../WakeScheduler.ts\";\nimport {\n guardedMessageDeliveryStoreLayer,\n threadMessageDeliveryLayer,\n} from \"./message-delivery.ts\";\nimport { cloudflarePreparedInputAdmissionLayer } from \"./prepared-admission.ts\";\nimport { ProgressWaitRegistry } from \"./progress-wait.ts\";\nimport { threadPortTransportLayer } from \"./transport.ts\";\n\n/**\n * Raw (unvalidated) construction options for `ThreadObject.make`, mirroring\n * `NodeDurableAgentRuntimeOptions`. Optional fields default to the documented production values\n * (`CLOUDFLARE_RUNTIME_DEFAULTS`); everything is schema-decoded into\n * `CloudflareDurableRuntimeConfigValue` before any resource opens (deployment §5 gate 1).\n */\nexport interface CloudflareDurableRuntimeOptions {\n readonly deploymentId: string;\n /** Head of the minted producer identity `{producerPrefix}:{threadId}`. */\n readonly producerPrefix: string;\n /** Milliseconds; default 30s (D5). */\n readonly ownershipLeaseDuration?: number | undefined;\n /** Milliseconds; default 100. */\n readonly alarmBackoffBase?: number | undefined;\n /** Milliseconds; default 5000. */\n readonly alarmBackoffCap?: number | undefined;\n /** Milliseconds; default 1000. Bounds every alarm re-arm delay. */\n readonly wakeScanInterval?: number | undefined;\n /** Milliseconds; default 500. */\n readonly settlementPollInterval?: number | undefined;\n /** Milliseconds; default 10000. */\n readonly leaseRenewalInterval?: number | undefined;\n /** Milliseconds; default 500. */\n readonly abortPollInterval?: number | undefined;\n /** Deployment-owned pricing authority used by durable cost budgets and settlements. */\n readonly estimateCostMicrousd?: RunCostEstimator | undefined;\n /** Closed trusted Tool failure reporting. Omission masks ambient observers at construction. */\n readonly toolFailureObserver?: RunToolFailureObserver | undefined;\n /** Milliseconds; default 25. */\n readonly observationPollInterval?: number | undefined;\n /** Bytes; default just under the 2 MB platform value limit. */\n readonly maxStoredValueBytes?: number | undefined;\n /** Default false. */\n readonly verifyOnOpen?: boolean | undefined;\n /** Nonterminal Submissions per lane before admission refuses; default 256. */\n readonly maxQueueDepthPerLane?: number | undefined;\n /** Encoded input bytes per Submission; default = the stored-value bound. */\n readonly maxInputBytes?: number | undefined;\n /** `ctx.storage.sql.databaseSize` ceiling at admission; default 9 GB (10 GB platform cap). */\n readonly maxDatabaseBytes?: number | undefined;\n /**\n * Durable Object storage fault injection (`ledger:*` / `append:*` locations). Handlers are\n * constructed per incarnation WITH the live `DurableObjectState`, so eviction harnesses can\n * map an armed hit to `ctx.abort()` — the platform's real failure mode. Default none.\n */\n readonly storageFailpoint?: ((ctx: DurableObjectState) => DoStorageFailpointHandler) | undefined;\n /** Coordinator fault injection (`submit:*` / `terminalize:*` locations); default none. */\n readonly runtimeFailpoint?:\n | ((ctx: DurableObjectState) => DurableRuntimeFailpointHandler)\n | undefined;\n /** Thread-maintenance generation/alarm fault injection; default none. */\n readonly maintenanceFailpoint?:\n | ((ctx: DurableObjectState) => ThreadMaintenanceFailpointHandler)\n | undefined;\n /** Host-supplied fail-closed authorization policy; defaults to service possession. */\n readonly operationAuthorizer?: OperationAuthorizerService | undefined;\n /**\n * Reconciliation policy consulted for open ordinary Tool Calls before an Unknown Outcome\n * is recorded (durability §10, DUR-009). Defaults to the fail-closed\n * `ToolReconciler.uncertain`.\n */\n readonly toolReconciler?: Layer.Layer<ToolReconciler> | undefined;\n}\n\n/** Services supplied before the application graph is built, including its dependencies. */\nexport type CloudflareBootstrapServices =\n | CloudflareDurableRuntimeConfig\n | ThreadObjectIdentity\n | ThreadObjectPlacement\n | DurableRuntimeConfig\n | Crypto.Crypto\n | DoStorageFailpoint\n | DurableRuntimeFailpoint\n | ThreadMaintenanceFailpoint\n | RunContextPreparation\n | RunToolAuthorization\n | ToolReconciler;\n\n/** Every construction failure of the assembled Cloudflare durable runtime stack. */\nexport type CloudflareDurableRuntimeInitializationError =\n | CloudflarePlatformConfigError\n | DigestError\n | MessageDeliveryError\n | DoStorageInitializationError;\n\n/**\n * The services `ThreadObject.layer` provides, including its single owner SQL client.\n * Its Context also supplies ThreadMessageDelivery (a defaulted Reference, with no required R)\n * so application-composed maintenance retains the same native message recovery capability.\n */\nexport type CloudflareDurableRuntimeServices =\n | DurableAgentRuntime\n | SubmissionLedger\n | ThreadStore\n | MessageDeliveryStore\n | WakeScheduler\n | DurableAlarmService\n | ThreadMaintenance\n | ThreadMutationGate\n | ThreadPublication\n | ThreadProjectionMaintenance\n | ThreadObjectPorts\n | ProgressWaitRegistry\n | SqlClient;\n\n/**\n * Owner-side execution port for a `portCall` request the wire endpoint has already decoded.\n * It executes against THIS Object's LOCAL port facets — never the routed decorators, so a\n * request cannot bounce between Objects — and returns the typed response for the endpoint to\n * encode.\n */\nexport class ThreadObjectPorts extends Context.Service<\n ThreadObjectPorts,\n {\n readonly handle: (request: PortRequest) => Effect.Effect<PortResponse>;\n /** Local-only identity check before a bound RPC can read or mutate a Submission. */\n readonly lookupSubmission: (\n submissionId: SubmissionId,\n ) => Effect.Effect<Option.Option<SubmissionSnapshot>, LedgerError>;\n }\n>()(\"@effect-agent/platform-cloudflare/ThreadObjectPorts\") {}\n\nconst decodeConfigValue = Schema.decodeUnknownEffect(CloudflareDurableRuntimeConfigValue);\nconst decodeThreadId = Schema.decodeUnknownEffect(ThreadId);\nconst decodeProducerId = Schema.decodeUnknownEffect(ProducerId);\n\nconst configFromOptions = (\n options: CloudflareDurableRuntimeOptions,\n): Effect.Effect<CloudflareDurableRuntimeConfigValue, CloudflarePlatformConfigError> =>\n decodeConfigValue({\n deploymentId: options.deploymentId,\n producerPrefix: options.producerPrefix,\n ownershipLeaseDuration:\n options.ownershipLeaseDuration ?? CLOUDFLARE_RUNTIME_DEFAULTS.ownershipLeaseDuration,\n alarmBackoffBase: options.alarmBackoffBase ?? CLOUDFLARE_RUNTIME_DEFAULTS.alarmBackoffBase,\n alarmBackoffCap: options.alarmBackoffCap ?? CLOUDFLARE_RUNTIME_DEFAULTS.alarmBackoffCap,\n wakeScanInterval: options.wakeScanInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.wakeScanInterval,\n settlementPollInterval:\n options.settlementPollInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.settlementPollInterval,\n leaseRenewalInterval:\n options.leaseRenewalInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.leaseRenewalInterval,\n abortPollInterval: options.abortPollInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.abortPollInterval,\n observationPollInterval:\n options.observationPollInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.observationPollInterval,\n maxStoredValueBytes:\n options.maxStoredValueBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxStoredValueBytes,\n verifyOnOpen: options.verifyOnOpen ?? CLOUDFLARE_RUNTIME_DEFAULTS.verifyOnOpen,\n limits: {\n maxQueueDepthPerLane:\n options.maxQueueDepthPerLane ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxQueueDepthPerLane,\n maxInputBytes: Math.min(\n options.maxInputBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxInputBytes,\n options.maxStoredValueBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxStoredValueBytes,\n ),\n maxDatabaseBytes: options.maxDatabaseBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxDatabaseBytes,\n },\n }).pipe(\n Effect.mapError((error) =>\n CloudflarePlatformConfigError.make({\n message: `Invalid Cloudflare durable runtime configuration: ${error.message}`,\n cause: error,\n }),\n ),\n );\n\n/**\n * The Thread this Object owns, from the Object identity rule (plan §1.2): Thread\n * Objects are addressed exclusively by `idFromName(threadId)`, so `ctx.id.name` IS the\n * Thread ID. An unnamed Object (from `newUniqueId`) is a deployment error, not a lane.\n */\nconst threadIdFromState = (\n ctx: DurableObjectState,\n): Effect.Effect<ThreadId, CloudflarePlatformConfigError> =>\n ctx.id.name === undefined\n ? Effect.fail(\n CloudflarePlatformConfigError.make({\n message:\n \"This Durable Object was not created via idFromName(threadId); Thread \" +\n \"Objects must be addressed by their Thread identity (plan §1.2).\",\n }),\n )\n : decodeThreadId(ctx.id.name).pipe(\n Effect.mapError((error) =>\n CloudflarePlatformConfigError.make({\n message: `The Durable Object name is not a valid ThreadId: ${error.message}`,\n cause: error,\n }),\n ),\n );\n\n/**\n * Validate deployment settings and derive services before building application dependencies.\n * The native class factory builds this Layer inside its constructor gate. Custom Effect hosts\n * can provide it around the complete application Layer with the native context already supplied.\n */\nconst runtimeConfigLayer = (\n options: CloudflareDurableRuntimeOptions,\n producerId: ProducerId,\n): Layer.Layer<\n Exclude<CloudflareBootstrapServices, ThreadObjectIdentity | ThreadObjectPlacement>,\n CloudflarePlatformConfigError,\n DurableObjectContext\n> =>\n Layer.unwrap(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n const config = yield* configFromOptions(options);\n\n return Layer.mergeAll(\n Layer.succeed(CloudflareDurableRuntimeConfig, config),\n DurableRuntimeConfig.layer({\n deploymentId: config.deploymentId,\n producerId,\n settlementPollInterval: Duration.millis(config.settlementPollInterval),\n leaseRenewalInterval: Duration.millis(config.leaseRenewalInterval),\n abortPollInterval: Duration.millis(config.abortPollInterval),\n ...(options.estimateCostMicrousd === undefined\n ? {}\n : { estimateCostMicrousd: options.estimateCostMicrousd }),\n }),\n BrowserCrypto.layer,\n storageFailpointLayer({ storage: ctx.storage, failpoint: options.storageFailpoint?.(ctx) }),\n options.runtimeFailpoint === undefined\n ? DurableRuntimeFailpoint.layer\n : Layer.succeed(DurableRuntimeFailpoint, { hit: options.runtimeFailpoint(ctx) }),\n options.maintenanceFailpoint === undefined\n ? ThreadMaintenanceFailpoint.layer\n : Layer.succeed(ThreadMaintenanceFailpoint, {\n hit: options.maintenanceFailpoint(ctx),\n }),\n options.toolReconciler ?? ToolReconciler.uncertain,\n options.operationAuthorizer === undefined\n ? Layer.empty\n : operationAuthorizerLayer(options.operationAuthorizer),\n options.toolFailureObserver === undefined\n ? Layer.succeed(CurrentToolFailureObserver, undefined)\n : toolFailureObserverLayer(options.toolFailureObserver),\n RunContextPreparationPassthrough,\n RunToolAuthorization.allowAll,\n );\n }),\n );\n\nconst producerIdentity = (prefix: string, owner: string) =>\n decodeProducerId(`${prefix}:${owner}`).pipe(\n Effect.mapError((error) =>\n CloudflarePlatformConfigError.make({\n message: `The minted producer identity is invalid: ${error.message}`,\n cause: error,\n }),\n ),\n );\n\n/** Native one-Thread configuration; retains its existing producer and logical identities. */\nexport const layerConfig = (\n options: CloudflareDurableRuntimeOptions,\n): Layer.Layer<CloudflareBootstrapServices, CloudflarePlatformConfigError, DurableObjectContext> =>\n Layer.unwrap(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n const threadId = yield* threadIdFromState(ctx);\n const producerId = yield* producerIdentity(options.producerPrefix, threadId);\n\n return Layer.mergeAll(\n runtimeConfigLayer(options, producerId),\n Layer.succeed(ThreadObjectIdentity, { threadId, producerId }),\n Layer.succeed(ThreadObjectPlacement, { ownsThread: (target) => target === threadId }),\n );\n }),\n );\n\n/**\n * Configuration for an application Object owning several logical Threads. The producer is\n * the stable physical Object. No logical identity is installed globally: handleRpc binds and\n * validates it per request using the placement guard and this actual runtime producer.\n */\nexport const layerHostConfig = (\n options: CloudflareDurableRuntimeOptions,\n ownsThread: (threadId: ThreadId) => boolean,\n): Layer.Layer<\n Exclude<CloudflareBootstrapServices, ThreadObjectIdentity>,\n CloudflarePlatformConfigError,\n DurableObjectContext\n> =>\n Layer.unwrap(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n const producerId = yield* producerIdentity(options.producerPrefix, ctx.id.toString());\n\n return Layer.merge(\n runtimeConfigLayer(options, producerId),\n Layer.succeed(ThreadObjectPlacement, { ownsThread }),\n );\n }),\n );\n\nexport interface ThreadPublicationOptions<E = never, R = never, P = never> {\n /**\n * Optional host outbox consumer, built once per incarnation with RAW LOCAL ThreadStore and\n * SubmissionLedger services. Yield DurableObjectContext and ThreadObjectIdentity for native\n * bindings and identity. Initialization is local-only, inside the constructor gate; setup\n * errors and additional requirements remain in the returned Layer. Layer.effect owns Scope.\n * Canonical appends and durable approval, abort and unknown-resolution intents invalidate\n * publication after commit. Custom host facts must use ThreadMaintenance.withMutation.\n */\n readonly publication?: Layer.Layer<ThreadPublication, E, R>;\n /**\n * Disposable index maintenance, built once with the raw local ThreadStore and owner\n * SqlClient. Additional services P are exposed by the returned Layer, allowing Tool\n * handlers and maintenance to share one index instance. Construction is local-only.\n * Live committed batches run before append returns; bounded backfill uses the native\n * alarm without delaying execution behind projection backlog.\n */\n readonly projection?: Layer.Layer<ThreadProjectionMaintenance | P, E, R>;\n}\n\n/**\n * Register typed Agents and version declarations. Hashing and dependency capture happen in\n * this Layer's Scope, after application Layers have been provided. Every Agent's instruction,\n * Tool, Schema, and model requirements remain visible until satisfied by Layer composition.\n * Use Layer.unwrap for registration values that need effectful application setup.\n */\nconst registeredLayer = <\n const Entries extends ReadonlyArray<AgentRegistration>,\n E = never,\n R = never,\n>(\n registrations: Entries,\n options: ThreadPublicationOptions<E, R> = {},\n) =>\n Layer.unwrap(\n Effect.map(compileRegistrations(registrations), (bindings) => boundLayer(bindings, options)),\n );\n\n/** Preserve additional index services only when a projection Layer is actually supplied. */\nexport function layer<\n const Entries extends ReadonlyArray<AgentRegistration>,\n E = never,\n R = never,\n P = never,\n PE = never,\n PR = never,\n>(\n registrations: Entries,\n options: Omit<ThreadPublicationOptions<E, R>, \"projection\"> & {\n readonly projection: Layer.Layer<ThreadProjectionMaintenance | P, PE, PR>;\n },\n): Layer.Layer<\n Layer.Success<ReturnType<typeof registeredLayer<Entries, E | PE, R | PR>>> | P,\n Layer.Error<ReturnType<typeof registeredLayer<Entries, E | PE, R | PR>>>,\n Layer.Services<ReturnType<typeof registeredLayer<Entries, E | PE, R | PR>>>\n>;\n\nexport function layer<const Entries extends ReadonlyArray<AgentRegistration>, E = never, R = never>(\n registrations: Entries,\n options?: ThreadPublicationOptions<E, R>,\n): ReturnType<typeof registeredLayer<Entries, E, R>>;\n\nexport function layer<const Entries extends ReadonlyArray<AgentRegistration>, E = never, R = never>(\n registrations: Entries,\n options: ThreadPublicationOptions<E, R> = {},\n) {\n return registeredLayer(registrations, options);\n}\n\nexport function layerFromBindings<E = never, R = never, P = never, PE = never, PR = never>(\n bindings: ReadonlyArray<ResolvedBinding>,\n options: Omit<ThreadPublicationOptions<E, R>, \"projection\"> & {\n readonly projection: Layer.Layer<ThreadProjectionMaintenance | P, PE, PR>;\n },\n): Layer.Layer<\n CloudflareDurableRuntimeServices | P,\n Layer.Error<ReturnType<typeof boundLayer<E | PE, R | PR>>>,\n Layer.Services<ReturnType<typeof boundLayer<E | PE, R | PR>>>\n>;\n\nexport function layerFromBindings<E = never, R = never>(\n bindings: ReadonlyArray<ResolvedBinding>,\n options?: ThreadPublicationOptions<E, R>,\n): ReturnType<typeof boundLayer<E, R>>;\n\nexport function layerFromBindings(\n bindings: ReadonlyArray<ResolvedBinding>,\n): ReturnType<typeof boundLayer<never, never>>;\n\nexport function layerFromBindings<E = never, R = never>(\n bindings: ReadonlyArray<ResolvedBinding>,\n options: ThreadPublicationOptions<E, R> = {},\n) {\n return boundLayer(bindings, options);\n}\n\n/**\n * Assemble the durable runtime from already-resolved Agent Bindings.\n * Use `ThreadObject.layer` to compile typed Agent registrations instead.\n * Supply host services through `ThreadObject.make` or `ThreadObject.layerConfig` and\n * the Durable Object context and namespace Layers when composing a custom host.\n */\nconst boundLayer = <E = never, R = never>(\n bindings: ReadonlyArray<ResolvedBinding>,\n options: ThreadPublicationOptions<E, R> = {},\n): Layer.Layer<\n CloudflareDurableRuntimeServices,\n DoStorageInitializationError | MessageDeliveryError | E,\n | DurableObjectContext\n | ThreadObjectNamespace\n | CloudflareBootstrapServices\n | Exclude<R, ThreadStore | SubmissionLedger | SqlClient>\n> =>\n Layer.unwrap(\n Effect.map(DurableObjectContext, ({ ctx }) =>\n sharedLayer(DurableAgentRuntime.layerWithBindings(bindings), options).pipe(\n Layer.provideMerge(SqliteClient.layer({ storage: ctx.storage })),\n ),\n ),\n );\n\n/**\n * Build the application runtime over the existing owner SqlClient and native ports, then\n * assemble its one maintenance coordinator. The application may acquire its Bindings from\n * those ports and expose extra services, including ThreadHostMaintenance. It must not acquire\n * another runtime stack or require ThreadMaintenance while constructing this Layer.\n * Supply layerHostConfig and deterministic placement; dispatch addressed ingress with handleRpc.\n */\nexport function layerInHost<A, E, R, P = never, PE = never, PR = never>(\n application: Layer.Layer<DurableAgentRuntime | A, E, R>,\n options: Omit<ThreadPublicationOptions<PE, PR>, \"projection\"> & {\n readonly projection: Layer.Layer<ThreadProjectionMaintenance | P, PE, PR>;\n },\n): Layer.Layer<\n CloudflareDurableRuntimeServices | A | P,\n Layer.Error<ReturnType<typeof sharedLayer<A, E, R, PE, PR>>>,\n Layer.Services<ReturnType<typeof sharedLayer<A, E, Exclude<R, P>, PE, PR>>>\n>;\n\nexport function layerInHost<A, E, R, PE = never, PR = never>(\n application: Layer.Layer<DurableAgentRuntime | A, E, R>,\n options?: ThreadPublicationOptions<PE, PR>,\n): ReturnType<typeof sharedLayer<A, E, R, PE, PR>>;\n\nexport function layerInHost<A, E, R, PE = never, PR = never>(\n application: Layer.Layer<DurableAgentRuntime | A, E, R>,\n options: ThreadPublicationOptions<PE, PR> = {},\n) {\n return sharedLayer(application, options);\n}\n\ntype HostRuntimeServices = Exclude<\n CloudflareDurableRuntimeServices,\n DurableAgentRuntime | ThreadMaintenance\n>;\n\nconst sharedLayer = <A, E, R, PE = never, PR = never>(\n application: Layer.Layer<DurableAgentRuntime | A, E, R>,\n options: ThreadPublicationOptions<PE, PR> = {},\n): Layer.Layer<\n CloudflareDurableRuntimeServices | A,\n DoStorageInitializationError | MessageDeliveryError | E | PE,\n | DurableObjectContext\n | ThreadObjectNamespace\n | Exclude<CloudflareBootstrapServices, ThreadObjectIdentity>\n | SqlClient\n | Exclude<R, HostRuntimeServices | PreparedInputAdmission>\n | Exclude<PR, ThreadStore | SubmissionLedger | SqlClient>\n> =>\n Layer.unwrap(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n const config = yield* CloudflareDurableRuntimeConfig;\n const { ownsThread } = yield* ThreadObjectPlacement;\n\n const storageOptions: DoStorageOptions = {\n storage: ctx.storage,\n observationPollInterval: config.observationPollInterval,\n ownershipLeaseDuration: config.ownershipLeaseDuration,\n maxStoredValueBytes: config.maxStoredValueBytes,\n verifyOnOpen: config.verifyOnOpen,\n };\n\n const infrastructure = Layer.mergeAll(\n storageConfigLayer(storageOptions),\n Layer.effect(SqlClient)(SqlClient),\n );\n\n // The same local ports serve routed decorators and owner-side RPC execution.\n // The RPC executor must never receive routed ports and bounce requests between Objects.\n const rawLocalPorts = Layer.mergeAll(threadStoreLayer, submissionLedgerLayer).pipe(\n Layer.provide(infrastructure),\n );\n\n const base = Layer.mergeAll(DurableAlarmService.layer, ProgressWaitRegistry.layer);\n const wakes = cloudflareWakeSchedulerLayer.pipe(Layer.provide(base));\n\n const messageStore = guardedMessageDeliveryStoreLayer.pipe(\n Layer.provide(doMessageDeliveryStoreLayer().pipe(Layer.provide(infrastructure))),\n Layer.provide(wakes),\n );\n\n const messageRecovery = threadMessageDeliveryLayer.pipe(\n // Each wave is bounded even at the policy's five-minute attempt ceiling. Source\n // completion stops new waves; remaining rows retain their indexed alarm deadline.\n Layer.provide(MessageDeliveryDriver.layer({ batchSize: 4, concurrency: 4 })),\n Layer.provide(cloudflarePreparedInputAdmissionLayer),\n Layer.provide(CloudflareThreadClient.layer),\n Layer.provide(messageStore),\n Layer.provide(wakes),\n );\n\n const publication = (options.publication ?? ThreadPublication.layer).pipe(\n Layer.provide(Layer.mergeAll(rawLocalPorts, Layer.effect(SqlClient)(SqlClient))),\n );\n\n const projection = (options.projection ?? ThreadProjectionMaintenance.layer).pipe(\n Layer.provide(Layer.mergeAll(rawLocalPorts, Layer.effect(SqlClient)(SqlClient))),\n );\n\n const localPorts =\n options.publication === undefined && options.projection === undefined\n ? rawLocalPorts\n : Layer.effectContext(\n Effect.gen(function* () {\n const store = yield* ThreadStore;\n const ledger = yield* SubmissionLedger;\n const mutations = yield* ThreadMutationGate;\n const index = yield* ThreadProjectionMaintenance;\n const publish = yield* Effect.context<ThreadPublication>();\n const afterCommit = publishCommitted.pipe(Effect.provide(publish));\n // A later append cannot mistake its still-projecting predecessor for old backlog.\n // Publication remains outside this local source/index critical section.\n const sourceCommits = yield* Semaphore.make(1);\n\n // Every runtime-owned producer prearms too: a crash between commit and invalidation\n // leaves a NEW, uncertified generation. Source errors keep their native port types.\n const observedStore = ThreadStore.of({\n ...store,\n append: (request) =>\n mutations\n .withMutation(\n sourceCommits\n .withPermit(\n store\n .append(request)\n .pipe(\n Effect.tap((result) =>\n index\n .applyCommitted(request, result)\n .pipe(\n Effect.catchCause((cause) =>\n Cause.hasInterrupts(cause)\n ? Effect.interrupt\n : Effect.logError(\n \"Thread projection deferred after source commit\",\n cause,\n ),\n ),\n ),\n ),\n ),\n )\n .pipe(Effect.tap(() => afterCommit)),\n )\n .pipe(\n Effect.catchTag(\"DurableAlarmError\", (cause) =>\n ThreadStoreError.make({\n operation: \"prearm publication append\",\n message: cause.message,\n cause,\n }),\n ),\n ),\n });\n\n const observeIntent = <A, Failure>(body: Effect.Effect<A, Failure>) =>\n mutations.withMutation(body.pipe(Effect.tap(() => afterCommit))).pipe(\n Effect.catchTag(\"DurableAlarmError\", (cause) =>\n LedgerError.make({\n operation: \"prearm publication intent\",\n message: \"The publication generation could not be armed\",\n cause,\n }),\n ),\n );\n\n return Context.make(ThreadStore, observedStore).pipe(\n Context.add(SubmissionLedger, {\n ...ledger,\n recordApprovalDecision: (request) =>\n observeIntent(ledger.recordApprovalDecision(request)),\n requestAbort: (request) => observeIntent(ledger.requestAbort(request)),\n recordUnknownResolution: (request) =>\n observeIntent(ledger.recordUnknownResolution(request)),\n }),\n );\n }),\n ).pipe(Layer.provide(rawLocalPorts));\n\n const portsEndpointLayer = Layer.effect(ThreadObjectPorts)(\n Effect.gen(function* () {\n const local = yield* Effect.context<SubmissionLedger | ThreadStore>();\n const ledger = Context.get(local, SubmissionLedger);\n\n return ThreadObjectPorts.of({\n handle: (request) => executePortRequest(request).pipe(Effect.provide(local)),\n lookupSubmission: (submissionId) =>\n ledger.lookup(SubmissionLookupById.make({ submissionId })),\n });\n }),\n ).pipe(Layer.provide(localPorts));\n\n const routedPorts = Layer.mergeAll(\n routedSubmissionLedgerLayer({ ownsThread }),\n routedThreadStoreLayer({ ownsThread }),\n ).pipe(Layer.provide(localPorts), Layer.provide(threadPortTransportLayer));\n\n const runtimeStack = application.pipe(\n Layer.provide(\n cloudflarePreparedInputAdmissionLayer.pipe(Layer.provide(CloudflareThreadClient.layer)),\n ),\n Layer.provideMerge(messageStore),\n Layer.provideMerge(routedPorts),\n Layer.provideMerge(wakes),\n Layer.provideMerge(base),\n Layer.provideMerge(portsEndpointLayer),\n );\n\n return Layer.mergeAll(\n runtimeStack,\n ThreadMaintenance.layer.pipe(Layer.provide(runtimeStack), Layer.provide(messageRecovery)),\n portsEndpointLayer,\n messageStore,\n messageRecovery,\n ).pipe(\n Layer.provideMerge(publication),\n Layer.provideMerge(projection),\n Layer.provideMerge(ThreadMutationGate.layer),\n Layer.provideMerge(infrastructure),\n );\n }),\n );\n","import {\n decodePortRequest,\n encodePortResponse,\n LedgerLookupResult,\n PortFailed,\n PortProtocolError,\n PortSucceeded,\n type PortRequest,\n type PortResponse,\n} from \"@effect-agent/storage-cloudflare/port-protocol\";\nimport { Effect, Layer, Option, Schema, Stream } from \"effect\";\nimport {\n IntegrityReport,\n ObligationReport,\n ObligationThresholds,\n RecoveryExplanation,\n RetryCommand,\n RetryRefused,\n} from \"effect-agent/admin\";\nimport { DigestError } from \"effect-agent/digest\";\nimport {\n DurableAgentRuntime,\n DurableRuntimeConfig,\n RecoveryReport,\n type DurableSubmitAgent,\n} from \"effect-agent/durable-agent-runtime\";\nimport { DurableRuntimeFailpointError } from \"effect-agent/durable-failpoint\";\nimport { type AgentId, type ThreadId } from \"effect-agent/identifiers\";\nimport { SubmissionId } from \"effect-agent/identifiers\";\nimport {\n OperationAuthorizationRequest,\n OperationAuthorizer,\n OperationDenied,\n} from \"effect-agent/operation-authorizer\";\nimport { PersistedJson } from \"effect-agent/records\";\nimport { RunJournalError } from \"effect-agent/run-journal\";\nimport {\n AdmissionPolicyError,\n LedgerError,\n OwnershipLost,\n SettlementConflict,\n SubmissionLedger,\n SubmissionLookupByKey,\n} from \"effect-agent/submission-ledger\";\nimport {\n AppendConflict,\n ThreadNotMaterialized,\n ThreadRead,\n ThreadStore,\n ThreadStoreError,\n FenceRejected,\n} from \"effect-agent/thread-store\";\nimport { WakeScheduler } from \"effect-agent/wake-scheduler\";\nimport {\n DurableObject as EffectCfDurableObject,\n DurableObjectState as EffectCfDurableObjectState,\n WorkerEnvironment,\n} from \"effect-cf\";\n\nimport {\n ThreadMaintenance,\n DurableAlarmError,\n DurableAlarmService,\n ThreadMutationGate,\n publishCommitted,\n type MaintenancePassFailure,\n} from \"./Alarm.ts\";\nimport {\n ThreadObjectIdentity,\n ThreadObjectPlacement,\n DurableObjectContext,\n ThreadObjectNamespace,\n threadNamespaceFromEnv,\n type CloudflareBindingError,\n} from \"./CloudflareBindings.ts\";\nimport { AdmissionLimitExceeded, CloudflareDurableRuntimeConfig } from \"./CloudflareConfig.ts\";\nimport {\n AbortRecorded,\n ApprovalRecorded,\n HostFailed,\n HostProtocolError,\n ObservedPage,\n ProgressObserved,\n ProgressCancelled,\n SettlementReached,\n SubmissionStatusResponse,\n SubmitSucceeded,\n UnknownResolutionRecorded,\n boundHostDiagnostic,\n decodeAbortCommand,\n decodeAwaitProgressRequest,\n decodeCancelProgressRequest,\n decodeApprovalDecisionCommand,\n decodeObservePageRequest,\n decodeReceipt,\n decodeSubmitRequest,\n decodeUnknownResolutionCommand,\n encodeHostResponse,\n type HostFailure,\n type HostResponse,\n type SubmitRequest,\n} from \"./CloudflareThreadClient.ts\";\nimport {\n layerConfig,\n ThreadObjectPorts,\n type CloudflareDurableRuntimeInitializationError,\n type CloudflareDurableRuntimeOptions,\n type CloudflareDurableRuntimeServices,\n type CloudflareBootstrapServices,\n} from \"./internal/layers.ts\";\nimport { ProgressWaitRegistry } from \"./internal/progress-wait.ts\";\n\nexport {\n layer,\n layerConfig,\n layerHostConfig,\n layerInHost,\n ThreadObjectPorts,\n type ThreadPublicationOptions as PublicationOptions,\n type CloudflareDurableRuntimeOptions as RuntimeOptions,\n type CloudflareDurableRuntimeServices as Services,\n type CloudflareDurableRuntimeInitializationError as InitializationError,\n type CloudflareBootstrapServices as BootstrapServices,\n} from \"./internal/layers.ts\";\n\n/**\n * `ThreadObject.make(application, options)` — the Thread Durable Object\n * (plan §1.4,\n * D-P6-1): a factory returning a class that applications export from their Worker entry.\n * One SQLite-backed Object per Thread is the serialized owner (durability §6); the\n * Object never runs `runResolvedWorker`'s infinite loop — each ingress event or alarm runs\n * ONE bounded `runRecovery` + `processThreadHead` pass, and the persisted alarm\n * (the single multiplexed slot, D-P6-2) finishes accepted work across evictions WITHOUT any\n * incoming request.\n * `Services` exposes the same owner `SqlClient` used by the Thread stores. Compose optional\n * local repositories after `ThreadObject.layer`; never acquire another independently locked\n * SQL client for the same Object. Exposing the client installs no additional storage schemas.\n *\n * Constructor gate (`blockConcurrencyWhile`) is LOCAL-ONLY: schema migration and the\n * exact-version check, configuration decode, and the defensive ensure-alarm half of the\n * alarm invariant. It deliberately does NOT run the recovery pass: parent recovery can\n * require child-Object reads and vice versa, and two Objects blocked in constructor gates\n * awaiting each other's RPC would deadlock (plan §1.4). Instead every pass runs\n * `runRecovery` BEFORE any claim, so reconciliation still strictly precedes new work.\n */\n\n/** Construction options for one deployed Thread Object class. */\nexport interface Options<\n ApplicationServices = never,\n EventServices = never,\n EventLayerError = never,\n> extends CloudflareDurableRuntimeOptions {\n /** Accept transient native RPC tracing through effect-cf; disabled by default. */\n readonly rpcTracing?: boolean;\n /**\n * Name of the Worker `env` binding carrying THIS class's `DurableObjectNamespace` — the\n * Object's route back to sibling Thread Objects for the WP2 cross-Object port calls\n * and remote wakes (DEPLOY-010: the binding enters through a Layer, never ambiently).\n */\n readonly namespaceBinding: string;\n /** Acquired and finalized per native event, with access to the complete application runtime. */\n readonly eventLayer?: Layer.Layer<\n EventServices,\n EventLayerError,\n | RuntimeServices\n | ApplicationServices\n | EffectCfDurableObjectState.DurableObjectState\n | WorkerEnvironment\n >;\n}\n\ntype EndpointServices =\n | CloudflareDurableRuntimeServices\n | CloudflareBootstrapServices\n | DurableObjectContext;\ntype RuntimeServices = EndpointServices | ThreadObjectNamespace;\ntype ThreadObjectInitializationError =\n | CloudflareDurableRuntimeInitializationError\n | CloudflareBindingError\n | MaintenancePassFailure;\n\n/** Classify only a decoded port request so new protocol members cannot bypass pre-arming. */\nconst isMutatingPortRequest = (request: PortRequest): boolean => {\n switch (request._tag) {\n case \"LedgerAdmit\":\n case \"LedgerMarkReady\":\n case \"LedgerRequestAbort\":\n case \"LedgerRecordChildSettled\":\n case \"StoreMaterialize\":\n case \"StoreAppend\":\n return true;\n case \"LedgerLookup\":\n case \"LedgerResolveAdmission\":\n case \"StoreReadPage\":\n case \"StoreInspectTail\":\n case \"StoreExport\":\n return false;\n }\n request satisfies never;\n\n return false;\n};\n\n/** The literal encoded `PortFailed(PortProtocolError)` fallback (same shape as WP2's). */\nconst encodedPortProtocolFailure = (message: string): unknown => ({\n _tag: \"PortFailed\",\n failure: { _tag: \"PortProtocolError\", message: boundHostDiagnostic(message) },\n});\n\nconst protocolFailure = (context: string) => (error: { readonly message: string }) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`${context}: ${error.message}`),\n });\n\n/** Fold one endpoint's typed failures into the uniform `HostResponse` envelope. */\nconst respond = <Result extends HostResponse, Failure extends HostFailure>(\n effect: Effect.Effect<Result, Failure, EndpointServices>,\n): Effect.Effect<HostResponse, never, EndpointServices> =>\n effect.pipe(\n Effect.map((result): HostResponse => result),\n Effect.catch((failure) => Effect.succeed<HostResponse>(HostFailed.make({ failure }))),\n );\n\n/** Encode the response envelope; an unencodable response degrades to a protocol failure. */\nconst encodeResponse = (response: HostResponse): Effect.Effect<unknown> =>\n encodeHostResponse(response).pipe(\n Effect.catch((error) =>\n Effect.succeed<unknown>({\n _tag: \"HostFailed\",\n failure: {\n _tag: \"HostProtocolError\",\n message: boundHostDiagnostic(`The host response could not be encoded: ${error.message}`),\n },\n }),\n ),\n );\n\nconst utf8Bytes = (value: PersistedJson): number =>\n new TextEncoder().encode(JSON.stringify(value)).length;\n\n/**\n * The admission-limits gate, BEFORE `runtime.submit` touches the ledger (exit gate\n * \"resource limits are checked before admission\"; DEPLOY-007). A replayed idempotency key is\n * exempt: its accepted-work obligation already exists, and returning the original Receipt\n * consumes no new quota. Refusals are typed `AdmissionLimitExceeded` and nothing is written.\n */\nconst gateAdmissionLimits = Effect.fn(\"ThreadObject.gateAdmissionLimits\")(function* (\n threadId: ThreadId,\n request: {\n readonly principal: SubmissionLookupByKey[\"principal\"];\n readonly idempotencyKey: SubmissionLookupByKey[\"idempotencyKey\"];\n readonly inputPayload: PersistedJson;\n },\n) {\n const config = yield* CloudflareDurableRuntimeConfig;\n const ledger = yield* SubmissionLedger;\n const { ctx } = yield* DurableObjectContext;\n\n const existing = yield* ledger.lookup(\n SubmissionLookupByKey.make({\n threadId,\n principal: request.principal,\n idempotencyKey: request.idempotencyKey,\n }),\n );\n\n if (Option.isSome(existing)) return;\n\n const inputBytes = utf8Bytes(request.inputPayload);\n\n if (inputBytes > config.limits.maxInputBytes) {\n return yield* AdmissionLimitExceeded.make({\n limit: \"input-bytes\",\n actual: inputBytes,\n maximum: config.limits.maxInputBytes,\n });\n }\n\n const nonterminal = yield* ledger.scanNonterminal.pipe(\n Stream.filter((submission) => submission.threadId === threadId),\n Stream.runCollect,\n );\n\n if (nonterminal.length >= config.limits.maxQueueDepthPerLane) {\n return yield* AdmissionLimitExceeded.make({\n limit: \"queue-depth\",\n actual: nonterminal.length,\n maximum: config.limits.maxQueueDepthPerLane,\n });\n }\n\n const databaseBytes = yield* Effect.sync(() => ctx.storage.sql.databaseSize);\n\n if (databaseBytes > config.limits.maxDatabaseBytes) {\n return yield* AdmissionLimitExceeded.make({\n limit: \"database-bytes\",\n actual: databaseBytes,\n maximum: config.limits.maxDatabaseBytes,\n });\n }\n});\n\n/**\n * The submit-capable projection of an Agent Binding on the OBJECT side: the input arrived\n * already encoded through the real input schema on the Worker side (`client.ts`), so the\n * Object admits the canonical `PersistedJson` payload as-is; the resolved Binding re-derives\n * everything else from the stored `(agentId, agentDigests)` at claim time (SUB-023).\n */\nconst passthroughSubmitAgent = (agentId: AgentId): DurableSubmitAgent<typeof PersistedJson> => ({\n definition: {\n id: agentId,\n input: PersistedJson,\n },\n});\n\n/** A physical owner may hold other Threads; an addressed request cannot act on their IDs. */\nconst lookupAddressedSubmission = Effect.fn(\"ThreadObject.lookupAddressedSubmission\")(function* (\n submissionId: SubmissionId,\n) {\n const { threadId } = yield* ThreadObjectIdentity;\n const ports = yield* ThreadObjectPorts;\n const submission = yield* ports.lookupSubmission(submissionId);\n\n if (Option.isSome(submission) && submission.value.threadId !== threadId)\n return yield* HostProtocolError.make({ message: \"The Submission belongs to another Thread\" });\n\n return submission;\n});\n\nconst requireSubmissionThread = Effect.fn(\"ThreadObject.requireSubmissionThread\")(function* (\n submissionId: SubmissionId,\n) {\n const submission = yield* lookupAddressedSubmission(submissionId);\n\n if (Option.isNone(submission))\n return yield* LedgerError.make({\n operation: \"addressed Submission lookup\",\n message: \"The addressed Thread has no such Submission\",\n });\n});\n\nconst requireReceiptThread = Effect.fn(\"ThreadObject.requireReceiptThread\")(function* (\n threadId: ThreadId,\n) {\n const identity = yield* ThreadObjectIdentity;\n\n if (threadId !== identity.threadId)\n return yield* HostProtocolError.make({ message: \"The Receipt belongs to another Thread\" });\n});\n\nconst requirePortThread = (request: PortRequest) => {\n switch (request._tag) {\n case \"LedgerLookup\":\n return request.request._tag === \"SubmissionLookupById\"\n ? lookupAddressedSubmission(request.request.submissionId).pipe(Effect.asVoid)\n : requireReceiptThread(request.request.threadId);\n case \"LedgerMarkReady\":\n case \"LedgerRequestAbort\":\n return requireSubmissionThread(request.request.submissionId);\n case \"LedgerRecordChildSettled\":\n return requireSubmissionThread(request.request.parentSubmissionId);\n case \"LedgerAdmit\":\n case \"LedgerResolveAdmission\":\n case \"StoreMaterialize\":\n case \"StoreAppend\":\n case \"StoreReadPage\":\n case \"StoreInspectTail\":\n case \"StoreExport\":\n return requireReceiptThread(request.request.threadId);\n }\n request satisfies never;\n};\n\n/**\n * Admit an already Schema-decoded request to a logical Thread in this physical owner.\n * Custom hosts validate local placement before calling this Effect and provide their same\n * runtime/maintenance instances. The native endpoint uses this path too: queue limits,\n * idempotent receipts and the pre-admission generation/alarm commit have one owner.\n */\nexport const submit = Effect.fn(\"ThreadObject.submit\")(function* (\n threadId: ThreadId,\n request: SubmitRequest,\n) {\n const placement = yield* ThreadObjectPlacement;\n\n if (!placement.ownsThread(threadId))\n return yield* HostProtocolError.make({ message: \"The Thread belongs to another Object\" });\n const mutations = yield* ThreadMutationGate;\n const runtime = yield* DurableAgentRuntime;\n\n yield* gateAdmissionLimits(threadId, request);\n\n return yield* mutations.withMutation(\n runtime\n .submit(passthroughSubmitAgent(request.agentId), request.inputPayload, {\n threadId,\n principal: request.principal,\n idempotencyKey: request.idempotencyKey,\n ...(request.admissionGroup === undefined ? {} : { admissionGroup: request.admissionGroup }),\n ...(request.admissionFence === undefined ? {} : { admissionFence: request.admissionFence }),\n ...(request.workerAdmission === undefined\n ? {}\n : { workerAdmission: request.workerAdmission }),\n ...(request.messageAdmission === undefined\n ? {}\n : { messageAdmission: request.messageAdmission }),\n definitions: request.definitions,\n })\n .pipe(Effect.tap(() => publishCommitted)),\n );\n});\n\nconst submitEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n decodeSubmitRequest(encoded).pipe(\n Effect.mapError(protocolFailure(\"The submit request could not be decoded\")),\n Effect.flatMap((request) =>\n Effect.gen(function* () {\n const identity = yield* ThreadObjectIdentity;\n const receipt = yield* submit(identity.threadId, request);\n\n return SubmitSucceeded.make({ receipt });\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\nconst submissionStatusEndpoint = (\n encoded: unknown,\n): Effect.Effect<unknown, never, EndpointServices> =>\n decodeReceipt(encoded).pipe(\n Effect.mapError(protocolFailure(\"The receipt could not be decoded\")),\n Effect.flatMap((receipt) =>\n Effect.gen(function* () {\n const authorizer = yield* OperationAuthorizer;\n\n yield* authorizer.authorize(\n OperationAuthorizationRequest.make({\n operation: \"awaitSettlement\",\n threadId: receipt.threadId,\n submissionId: receipt.submissionId,\n }),\n );\n yield* requireReceiptThread(receipt.threadId);\n yield* requireSubmissionThread(receipt.submissionId);\n const runtime = yield* DurableAgentRuntime;\n\n return SubmissionStatusResponse.make({ status: yield* runtime.submissionStatus(receipt) });\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\nconst awaitSettlementEndpoint = (\n encoded: unknown,\n): Effect.Effect<unknown, never, EndpointServices> =>\n decodeReceipt(encoded).pipe(\n Effect.mapError(protocolFailure(\"The receipt could not be decoded\")),\n Effect.flatMap((receipt) =>\n Effect.gen(function* () {\n const authorizer = yield* OperationAuthorizer;\n\n yield* authorizer.authorize(\n OperationAuthorizationRequest.make({\n operation: \"awaitSettlement\",\n threadId: receipt.threadId,\n submissionId: receipt.submissionId,\n }),\n );\n yield* requireReceiptThread(receipt.threadId);\n yield* requireSubmissionThread(receipt.submissionId);\n const runtime = yield* DurableAgentRuntime;\n const settlement = yield* runtime.awaitSettlement(receipt);\n\n return SettlementReached.make({ settlement });\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\nconst awaitProgressEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n decodeAwaitProgressRequest(encoded).pipe(\n Effect.mapError(protocolFailure(\"The progress request could not be decoded\")),\n Effect.flatMap((request) =>\n Effect.gen(function* () {\n const identity = yield* ThreadObjectIdentity;\n const runtime = yield* DurableAgentRuntime;\n const registry = yield* ProgressWaitRegistry;\n\n yield* Effect.scoped(\n Effect.gen(function* () {\n const cancelled = yield* registry.subscribe(\n JSON.stringify([identity.threadId, request.waiterId]),\n );\n\n yield* Effect.raceFirst(\n runtime.awaitProgress(identity.threadId, request.afterSequence),\n cancelled,\n );\n }),\n );\n\n return ProgressObserved.make();\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\nconst cancelProgressEndpoint = (\n encoded: unknown,\n): Effect.Effect<unknown, never, EndpointServices> =>\n decodeCancelProgressRequest(encoded).pipe(\n Effect.mapError(protocolFailure(\"The progress cancellation could not be decoded\")),\n Effect.flatMap((request) =>\n Effect.gen(function* () {\n const identity = yield* ThreadObjectIdentity;\n const registry = yield* ProgressWaitRegistry;\n\n yield* registry.cancel(JSON.stringify([identity.threadId, request.waiterId]));\n\n return ProgressCancelled.make();\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\nconst observePageEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n decodeObservePageRequest(encoded).pipe(\n Effect.mapError(protocolFailure(\"The observe request could not be decoded\")),\n Effect.flatMap((request) =>\n Effect.gen(function* () {\n const identity = yield* ThreadObjectIdentity;\n const store = yield* ThreadStore;\n // The same fail-closed authorization seam the runtime's `observe` consults (P7 WP1);\n // the default reference preserves the possession behavior.\n const authorizer = yield* OperationAuthorizer;\n\n yield* authorizer.authorize(\n OperationAuthorizationRequest.make({\n operation: \"observe\",\n threadId: identity.threadId,\n }),\n );\n\n const records = yield* Stream.runCollect(\n store.read(\n ThreadRead.make({\n threadId: identity.threadId,\n ...(request.afterSequence === undefined\n ? {}\n : { afterSequence: request.afterSequence }),\n limit: request.limit,\n }),\n ),\n );\n\n return ObservedPage.make({ records: [...records] });\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\nconst abortEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n decodeAbortCommand(encoded).pipe(\n Effect.mapError(protocolFailure(\"The abort command could not be decoded\")),\n Effect.flatMap((command) =>\n Effect.gen(function* () {\n const authorizer = yield* OperationAuthorizer;\n\n yield* authorizer.authorize(\n OperationAuthorizationRequest.make({\n operation: \"abort\",\n submissionId: command.submissionId,\n }),\n );\n yield* requireSubmissionThread(command.submissionId);\n const maintenance = yield* ThreadMaintenance;\n const runtime = yield* DurableAgentRuntime;\n const intent = yield* maintenance.withMutation(runtime.abort(command));\n\n return AbortRecorded.make({ intent });\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\nconst resolveApprovalEndpoint = (\n encoded: unknown,\n): Effect.Effect<unknown, never, EndpointServices> =>\n decodeApprovalDecisionCommand(encoded).pipe(\n Effect.mapError(protocolFailure(\"The approval command could not be decoded\")),\n Effect.flatMap((command) =>\n Effect.gen(function* () {\n const authorizer = yield* OperationAuthorizer;\n\n yield* authorizer.authorize(\n OperationAuthorizationRequest.make({\n operation: \"resolveApproval\",\n submissionId: command.submissionId,\n }),\n );\n yield* requireSubmissionThread(command.submissionId);\n const maintenance = yield* ThreadMaintenance;\n const runtime = yield* DurableAgentRuntime;\n const intent = yield* maintenance.withMutation(runtime.resolveApproval(command));\n\n return ApprovalRecorded.make({ intent });\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\nconst resolveUnknownEndpoint = (\n encoded: unknown,\n): Effect.Effect<unknown, never, EndpointServices> =>\n decodeUnknownResolutionCommand(encoded).pipe(\n Effect.mapError(protocolFailure(\"The resolution command could not be decoded\")),\n Effect.flatMap((command) =>\n Effect.gen(function* () {\n const authorizer = yield* OperationAuthorizer;\n\n yield* authorizer.authorize(\n OperationAuthorizationRequest.make({\n operation: \"resolveUnknown\",\n submissionId: command.submissionId,\n }),\n );\n yield* requireSubmissionThread(command.submissionId);\n const maintenance = yield* ThreadMaintenance;\n const runtime = yield* DurableAgentRuntime;\n const intent = yield* maintenance.withMutation(runtime.resolveUnknown(command));\n\n return UnknownResolutionRecorded.make({ intent });\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\n// ---------------------------------------------------------------------------\n// P7 administrative entry points (plan §3): explain/verify/retry/obligations over the SAME\n// envelope discipline as the host protocol — closed request/response Schema unions, typed\n// failures that re-decode to identical tags, protocol anomalies answered typed. The envelopes\n// live here (not `client.ts`) because no Worker-side client consumption exists yet; `wake`\n// already exists as the `wake()` entry point.\n// ---------------------------------------------------------------------------\n\n/** Explain one Submission (`submissionId` present) or every nonterminal lane member. */\nexport class AdminExplainRequest extends Schema.Class<AdminExplainRequest>(\n \"@effect-agent/platform-cloudflare/AdminExplainRequest\",\n)({\n submissionId: Schema.optionalKey(SubmissionId),\n}) {}\n\n/** Verify carries no parameters — the addressed Object IS the lane. */\nexport class AdminVerifyRequest extends Schema.Class<AdminVerifyRequest>(\n \"@effect-agent/platform-cloudflare/AdminVerifyRequest\",\n)({}) {}\n\n/** Every typed failure of the four admin entry points, plus the protocol's own errors. */\nexport const AdminFailure = Schema.Union([\n AdmissionPolicyError,\n OperationDenied,\n RetryRefused,\n LedgerError,\n RunJournalError,\n DigestError,\n OwnershipLost,\n SettlementConflict,\n ThreadStoreError,\n ThreadNotMaterialized,\n AppendConflict,\n FenceRejected,\n DurableRuntimeFailpointError,\n DurableAlarmError,\n HostProtocolError,\n]);\n\nexport type AdminFailure = typeof AdminFailure.Type;\n\nexport class ExplainedRecovery extends Schema.TaggedClass<ExplainedRecovery>(\n \"@effect-agent/platform-cloudflare/ExplainedRecovery\",\n)(\"ExplainedRecovery\", {\n explanations: Schema.Array(RecoveryExplanation).check(Schema.isMaxLength(1_024)),\n}) {}\n\nexport class VerifiedIntegrity extends Schema.TaggedClass<VerifiedIntegrity>(\n \"@effect-agent/platform-cloudflare/VerifiedIntegrity\",\n)(\"VerifiedIntegrity\", {\n report: IntegrityReport,\n}) {}\n\nexport class RetryExecuted extends Schema.TaggedClass<RetryExecuted>(\n \"@effect-agent/platform-cloudflare/RetryExecuted\",\n)(\"RetryExecuted\", {\n report: RecoveryReport,\n}) {}\n\nexport class ObligationsScanned extends Schema.TaggedClass<ObligationsScanned>(\n \"@effect-agent/platform-cloudflare/ObligationsScanned\",\n)(\"ObligationsScanned\", {\n report: ObligationReport,\n}) {}\n\n/** The admin entry point failed TYPED on the Object; the failure re-decodes verbatim. */\nexport class AdminFailed extends Schema.TaggedClass<AdminFailed>(\n \"@effect-agent/platform-cloudflare/AdminFailed\",\n)(\"AdminFailed\", {\n failure: AdminFailure,\n}) {}\n\n/** The uniform answer of one admin entry point. Callers narrow by the tag their call implies. */\nexport const AdminResponse = Schema.Union([\n ExplainedRecovery,\n VerifiedIntegrity,\n RetryExecuted,\n ObligationsScanned,\n AdminFailed,\n]);\n\nexport type AdminResponse = typeof AdminResponse.Type;\n\nexport const decodeAdminExplainRequest = Schema.decodeUnknownEffect(AdminExplainRequest);\nexport const decodeAdminVerifyRequest = Schema.decodeUnknownEffect(AdminVerifyRequest);\nexport const decodeRetryCommand = Schema.decodeUnknownEffect(RetryCommand);\nexport const decodeObligationThresholds = Schema.decodeUnknownEffect(ObligationThresholds);\nexport const encodeAdminResponse = Schema.encodeEffect(AdminResponse);\nexport const decodeAdminResponse = Schema.decodeUnknownEffect(AdminResponse);\n\n/** Fold one admin endpoint's typed failures into the uniform `AdminResponse` envelope. */\nconst respondAdmin = <Result extends AdminResponse, Failure extends AdminFailure>(\n effect: Effect.Effect<Result, Failure, EndpointServices>,\n): Effect.Effect<AdminResponse, never, EndpointServices> =>\n effect.pipe(\n Effect.map((result): AdminResponse => result),\n Effect.catch((failure) => Effect.succeed<AdminResponse>(AdminFailed.make({ failure }))),\n );\n\n/** Encode the admin response envelope; an unencodable response degrades to a protocol failure. */\nconst encodeAdminResponseTotal = (response: AdminResponse): Effect.Effect<unknown> =>\n encodeAdminResponse(response).pipe(\n Effect.catch((error) =>\n Effect.succeed<unknown>({\n _tag: \"AdminFailed\",\n failure: {\n _tag: \"HostProtocolError\",\n message: boundHostDiagnostic(`The admin response could not be encoded: ${error.message}`),\n },\n }),\n ),\n );\n\nconst explainEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n decodeAdminExplainRequest(encoded).pipe(\n Effect.mapError(protocolFailure(\"The explain request could not be decoded\")),\n Effect.flatMap((request) =>\n Effect.gen(function* () {\n const identity = yield* ThreadObjectIdentity;\n const runtime = yield* DurableAgentRuntime;\n\n const explanations =\n request.submissionId === undefined\n ? yield* runtime.explainThread(identity.threadId)\n : [yield* runtime.explain(request.submissionId)];\n\n return ExplainedRecovery.make({ explanations });\n }),\n ),\n respondAdmin,\n Effect.flatMap(encodeAdminResponseTotal),\n );\n\nconst verifyEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n decodeAdminVerifyRequest(encoded).pipe(\n Effect.mapError(protocolFailure(\"The verify request could not be decoded\")),\n Effect.flatMap(() =>\n Effect.gen(function* () {\n const identity = yield* ThreadObjectIdentity;\n const runtime = yield* DurableAgentRuntime;\n const report = yield* runtime.verify(identity.threadId);\n\n return VerifiedIntegrity.make({ report });\n }),\n ),\n respondAdmin,\n Effect.flatMap(encodeAdminResponseTotal),\n );\n\nconst retryEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n decodeRetryCommand(encoded).pipe(\n Effect.mapError(protocolFailure(\"The retry command could not be decoded\")),\n Effect.flatMap((command) =>\n Effect.gen(function* () {\n const maintenance = yield* ThreadMaintenance;\n const runtime = yield* DurableAgentRuntime;\n // Retry may repair durable state, so its generation + alarm commit before the mutation.\n const report = yield* maintenance.withMutation(runtime.retry(command));\n\n return RetryExecuted.make({ report });\n }),\n ),\n respondAdmin,\n Effect.flatMap(encodeAdminResponseTotal),\n );\n\nconst obligationsEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n decodeObligationThresholds(encoded).pipe(\n Effect.mapError(protocolFailure(\"The obligation thresholds could not be decoded\")),\n Effect.flatMap((thresholds) =>\n Effect.gen(function* () {\n const runtime = yield* DurableAgentRuntime;\n const report = yield* runtime.scanObligations(thresholds);\n\n return ObligationsScanned.make({ report });\n }),\n ),\n respondAdmin,\n Effect.flatMap(encodeAdminResponseTotal),\n );\n\n/**\n * Owner-side `portCall`: wrap a mutating envelope in the same pre-armed generation protocol as\n * public RPC (a routed mutation committed by THIS Object must already carry the alarm that will\n * finish it), execute on the LOCAL facets (never the routed decorators), then arm an immediate\n * alarm so the mutated lane is processed promptly. Protocol anomalies answer\n * `PortFailed(PortProtocolError)`.\n */\nconst encodePortResponseTotal = (response: PortResponse) =>\n encodePortResponse(response).pipe(\n Effect.catch((error) =>\n Effect.succeed(\n encodedPortProtocolFailure(`The port response could not be encoded: ${error.message}`),\n ),\n ),\n );\n\nconst portGuardFailure = (failure: LedgerError | HostProtocolError): PortFailed =>\n PortFailed.make({\n failure:\n failure._tag === \"LedgerError\"\n ? failure\n : PortProtocolError.make({ message: \"The port request is not for the addressed Thread\" }),\n });\n\nexport const portCall = (\n encoded: unknown,\n): Effect.Effect<\n unknown,\n never,\n ThreadObjectPorts | ThreadMaintenance | DurableAlarmService | ThreadObjectIdentity\n> =>\n Effect.gen(function* () {\n const ports = yield* ThreadObjectPorts;\n const maintenance = yield* ThreadMaintenance;\n const alarm = yield* DurableAlarmService;\n\n const decoded = yield* decodePortRequest(encoded).pipe(\n Effect.map((request) => ({ _tag: \"success\" as const, request })),\n Effect.catch((error) => Effect.succeed({ _tag: \"failure\" as const, message: error.message })),\n );\n\n if (decoded._tag === \"failure\") {\n return encodedPortProtocolFailure(\n `The port request could not be decoded: ${decoded.message}`,\n );\n }\n if (\n decoded.request._tag === \"LedgerLookup\" &&\n decoded.request.request._tag === \"SubmissionLookupById\"\n ) {\n const response = yield* lookupAddressedSubmission(decoded.request.request.submissionId).pipe(\n Effect.map((submission) =>\n PortSucceeded.make({\n result: LedgerLookupResult.make(\n Option.isSome(submission) ? { submission: submission.value } : {},\n ),\n }),\n ),\n Effect.catch((failure) => Effect.succeed(portGuardFailure(failure))),\n );\n\n return yield* encodePortResponseTotal(response);\n }\n const identityCheck = yield* requirePortThread(decoded.request).pipe(Effect.result);\n\n if (identityCheck._tag === \"Failure\")\n return yield* encodePortResponseTotal(portGuardFailure(identityCheck.failure));\n const mutating = isMutatingPortRequest(decoded.request);\n\n const handled = yield* (\n mutating\n ? maintenance.withMutation(ports.handle(decoded.request))\n : ports.handle(decoded.request)\n ).pipe(Effect.exit);\n\n if (handled._tag === \"Failure\") {\n // Without the committed generation/alarm the invariant cannot be promised; refuse before\n // the port mutation runs. `ports.handle` itself is total, so this is the maintenance error.\n return encodedPortProtocolFailure(\n \"The owner Object could not arm its maintenance alarm before the mutation.\",\n );\n }\n\n const response = yield* encodePortResponseTotal(handled.value);\n\n if (mutating) {\n // Prompt processing hint; the pre-armed alarm already guarantees convergence.\n yield* alarm.scheduleNow.pipe(\n Effect.catch((error) =>\n Effect.logWarning(\"ThreadObject.portCall: immediate re-arm failed\", error),\n ),\n );\n }\n\n return response;\n });\n\nconst wakeEndpoint: Effect.Effect<void, never, EndpointServices> = Effect.gen(function* () {\n const identity = yield* ThreadObjectIdentity;\n const wake = yield* WakeScheduler;\n\n // Route the remote hint through this incarnation's scheduler so scoped progress waiters and\n // the alarm receive the same hint. Delivery remains droppable; canonical storage is authority.\n yield* wake.notify(identity.threadId);\n});\n\n/** The per-Thread wire operations supported by native and application-owned endpoints. */\nexport const ThreadRpcOperation = Schema.Literals([\n \"submitEncoded\",\n \"submissionStatusEncoded\",\n \"awaitSettlementEncoded\",\n \"awaitProgressEncoded\",\n \"cancelProgressEncoded\",\n \"observePage\",\n \"abortEncoded\",\n \"resolveApprovalEncoded\",\n \"resolveUnknownEncoded\",\n \"portCall\",\n \"wake\",\n]);\n\nexport type ThreadRpcOperation = typeof ThreadRpcOperation.Type;\n\nconst threadRpc = {\n submitEncoded: submitEndpoint,\n submissionStatusEncoded: submissionStatusEndpoint,\n awaitSettlementEncoded: awaitSettlementEndpoint,\n awaitProgressEncoded: awaitProgressEndpoint,\n cancelProgressEncoded: cancelProgressEndpoint,\n observePage: observePageEndpoint,\n abortEncoded: abortEndpoint,\n resolveApprovalEncoded: resolveApprovalEndpoint,\n resolveUnknownEncoded: resolveUnknownEndpoint,\n portCall,\n wake: () => wakeEndpoint,\n} satisfies Record<\n ThreadRpcOperation,\n (encoded: unknown) => Effect.Effect<unknown, never, EndpointServices>\n>;\n\n/**\n * Bind an addressed request to its logical Thread while sharing one physical runtime. This\n * validates local placement before invoking the same native handlers. Receipts, Submission\n * commands and port envelopes must match this identity; progress cancellation is Thread-scoped.\n * The producer comes from the actual runtime configuration, never from caller input. These\n * guards supplement the existing current model/Tool and operation authorization policies.\n */\nexport const handleRpc = Effect.fn(\"ThreadObject.handleRpc\")(function* (\n threadId: ThreadId,\n operation: ThreadRpcOperation,\n encoded: unknown,\n) {\n const placement = yield* ThreadObjectPlacement;\n\n if (!placement.ownsThread(threadId))\n return yield* HostProtocolError.make({ message: \"The Thread belongs to another Object\" });\n const { producerId } = yield* DurableRuntimeConfig;\n\n return yield* threadRpc[operation](encoded).pipe(\n Effect.provideService(ThreadObjectIdentity, { threadId, producerId }),\n );\n});\n\nconst alarmEndpoint: Effect.Effect<void, MaintenancePassFailure, EndpointServices> = Effect.gen(\n function* () {\n const maintenance = yield* ThreadMaintenance;\n\n // Typed pass failures propagate: the rejected promise makes workerd retry the alarm\n // (at-least-once delivery), and the dirty generation retains a committed slot meanwhile.\n yield* maintenance.pass;\n },\n);\n\nconst gateEndpoint: Effect.Effect<void, MaintenancePassFailure, EndpointServices> = Effect.gen(\n function* () {\n // Forcing ThreadMaintenance forces the whole Layer stack: migration + exact-version\n // check + configuration decode (DEPLOY-008 fails typed here, before any mutation), then\n // the defensive local ensure-alarm half of the invariant. LOCAL-ONLY by construction.\n const maintenance = yield* ThreadMaintenance;\n\n yield* maintenance.ensureAlarm;\n },\n);\n\n/**\n * Adapter from effect-cf's native Durable Object services to Effect Agent's existing platform\n * ports. effect-cf owns the cached ManagedRuntime and supplies these values once per Object\n * incarnation; the durable runtime continues to depend only on the narrow services below.\n */\nconst effectCfPlatformLayer = (\n namespaceBinding: string,\n rpcTracing = false,\n): Layer.Layer<\n DurableObjectContext | ThreadObjectNamespace,\n CloudflareBindingError,\n EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment\n> => {\n const context = Layer.effect(DurableObjectContext)(\n Effect.gen(function* () {\n const state = yield* EffectCfDurableObjectState.DurableObjectState;\n const env = yield* WorkerEnvironment;\n\n return DurableObjectContext.of({ ctx: state.raw, env });\n }),\n );\n\n const namespace = Layer.effect(ThreadObjectNamespace)(\n Effect.gen(function* () {\n const env = yield* WorkerEnvironment;\n const binding = yield* threadNamespaceFromEnv(env, namespaceBinding);\n\n return ThreadObjectNamespace.of({\n get: (threadId) => binding.get(binding.idFromName(threadId)),\n ...(rpcTracing === true ? { rpcTracing: namespaceBinding } : {}),\n });\n }),\n );\n\n return Layer.merge(context, namespace);\n};\n\n/** The public endpoints and effect-cf invocation hook of one Thread Object instance. */\nexport interface Instance<EventServices = never> extends InstanceType<\n EffectCfDurableObject.DurableObjectClass<Record<never, never>, RuntimeServices | EventServices>\n> {\n submitEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n submissionStatusEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n awaitSettlementEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n awaitProgressEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n cancelProgressEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n observePage(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n abortEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n resolveApprovalEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n resolveUnknownEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n explainEncoded(encoded: unknown): Promise<unknown>;\n verifyEncoded(encoded: unknown): Promise<unknown>;\n retryEncoded(encoded: unknown): Promise<unknown>;\n obligationsEncoded(encoded: unknown): Promise<unknown>;\n portCall(encoded: unknown): Promise<unknown>;\n wake(): Promise<void>;\n alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> | void;\n}\n\n/** The constructor shape workerd instantiates for each Thread Object. */\nexport interface Class<EventServices = never> {\n new (ctx: DurableObjectState, env: Cloudflare.Env): Instance<EventServices>;\n}\n\n/**\n * Export a composed application Layer as a native Durable Object class.\n * Bootstrap services are provided to the whole graph before it acquires, so application Layers\n * can yield effect-cf's WorkerEnvironment and DurableObjectState, derived identity, and Crypto.\n * Effect Config reads scalar Worker vars and secrets through effect-cf's environment provider;\n * WorkerEnvironment exposes resource bindings without a separate config Layer.\n * Application dependencies remain visible until Layer.provide satisfies them. effect-cf owns the\n * cached ManagedRuntime, native RPC methods, event scopes, and telemetry flushing.\n * Initialization is local and bounded inside the constructor gate. Cloudflare eviction does not\n * guarantee finalizers; put resources requiring timely release in scoped operations or eventLayer.\n */\nexport const make = <\n ApplicationServices,\n ApplicationError,\n EventServices = never,\n EventLayerError = never,\n>(\n applicationLayer: Layer.Layer<\n CloudflareDurableRuntimeServices | ApplicationServices,\n ApplicationError,\n | CloudflareBootstrapServices\n | EffectCfDurableObjectState.DurableObjectState\n | WorkerEnvironment\n | DurableObjectContext\n | ThreadObjectNamespace\n >,\n options: Options<ApplicationServices, EventServices, EventLayerError>,\n): Class<ApplicationServices | EventServices> => {\n const application = applicationLayer.pipe(\n Layer.provideMerge(layerConfig(options)),\n Layer.provideMerge(effectCfPlatformLayer(options.namespaceBinding, options.rpcTracing)),\n );\n\n // The storage/config Layer must acquire inside Cloudflare's constructor gate. effect-cf owns\n // the ManagedRuntime, while this effectContext ensures its first Layer build enters the gate\n // before migration, compatibility checks, or alarm inspection touch Object storage.\n const runtime: Layer.Layer<\n RuntimeServices | ApplicationServices,\n ThreadObjectInitializationError | ApplicationError,\n EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment\n > = Layer.effectContext(\n Effect.gen(function* () {\n const state = yield* EffectCfDurableObjectState.DurableObjectState;\n const scope = yield* Effect.scope;\n\n return yield* state.blockConcurrencyWhile(\n Effect.gen(function* () {\n const services = yield* Layer.buildWithScope(application, scope);\n\n yield* gateEndpoint.pipe(Effect.provide(services));\n\n return services;\n }),\n );\n }),\n );\n\n const rpc = {\n ...threadRpc,\n explainEncoded: (encoded: unknown) => explainEndpoint(encoded),\n verifyEncoded: (encoded: unknown) => verifyEndpoint(encoded),\n retryEncoded: (encoded: unknown) => retryEndpoint(encoded),\n obligationsEncoded: (encoded: unknown) => obligationsEndpoint(encoded),\n } satisfies EffectCfDurableObject.DurableObjectRpc<\n RuntimeServices | ApplicationServices | EventServices\n >;\n\n type NativeOptions = EffectCfDurableObject.DurableObjectOptions<\n RuntimeServices | ApplicationServices,\n EventServices,\n EventLayerError,\n typeof rpc\n >;\n\n const EffectCfThreadObject = EffectCfDurableObject.make<\n RuntimeServices | ApplicationServices,\n ThreadObjectInitializationError | ApplicationError,\n EventServices,\n EventLayerError,\n typeof rpc\n >(runtime, {\n ...(options.rpcTracing === true ? { rpcTracing: { service: options.namespaceBinding } } : {}),\n ...(options.eventLayer === undefined ? {} : { eventLayer: options.eventLayer }),\n // Force the gated runtime Layer when Cloudflare loads this Object incarnation. Recovery stays\n // in each bounded pass so cross-Object initialization cannot deadlock.\n initialize: Effect.void,\n rpc,\n alarm: () => alarmEndpoint,\n // This host owns the raw alarm and supplies event services through options.eventLayer.\n // Upstream's conditional alarm-registration check cannot reduce over generic application\n // services. Options and the rpc satisfies check above retain their Effect requirements.\n } as NativeOptions);\n\n // effect-cf's class type keeps `alarm` optional even when the handler option is present. This\n // concrete override reflects this factory's stronger contract while delegating execution to\n // the effect-cf runtime unchanged.\n class ThreadObject extends EffectCfThreadObject {\n override alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> | void {\n return super.alarm?.(alarmInfo);\n }\n }\n\n return ThreadObject;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,MAAa,mCAAmC,MAAM,OACpD,sBACA,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,OAAO;CACrB,MAAM,YAAY,OAAO;CACzB,MAAM,QAAQ,OAAO;CACrB,MAAM,EAAE,eAAe,OAAO;CAG9B,MAAM,WAAW,OAAO,IAAI,KAAgC,KAAA,CAAS;CACrE,MAAM,YAAY,OAAO,UAAU,KAAK,CAAC;CAEzC,MAAM,SACJ,OACA,SAEA,UAAU,KAAA,KAAa,WAAW,KAAK,IACnC,OACA,OAAO,KACL,qBAAqB,KAAK;EAAE,QAAQ;EAAc,WAAW;CAAgB,CAAC,CAChF;CAEN,MAAM,UAAgB,SACpB,UACG,aACC,UAAU,WAAW,IAAI,IAAI,UAAU,KAAA,CAAS,CAAC,CAAC,KAAK,OAAO,QAAQ,IAAI,CAAC,CAAC,GAG5E,EAAE,qBAAqB,MAAM,CAC/B,CAAC,CACA,KACC,OAAO,SAAS,2BACd,qBAAqB,KAAK;EAAE,QAAQ;EAAW,WAAW;CAA0B,CAAC,CACvF,CACF;CAEJ,MAAM,eAAe,UAAU,WAC7B,OAAO,IAAI,aAAa;EACtB,MAAM,SAAS,OAAO,IAAI,IAAI,QAAQ;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M,aAAa,sBAAsB,QAAQ,kBAAkB,QAAQ,UAAU,CAAC,CACxF;CAKA,MAAM,UAIF,MAAM,cACR,OAAO,IAAI,aAAa;EACtB,MAAM,QAAQ,OAAOA,mBAA2B;EAChD,MAAM,QAAQ,OAAO,OAAO;EAE5B,OAAO,OAAO,MAAM,sBAClB,OAAO,IAAI,aAAa;GACtB,MAAM,WAAW,OAAO,MAAM,eAAe,aAAa,KAAK;GAE/D,OAAO,aAAa,KAAK,OAAO,QAAQ,QAAQ,CAAC;GAEjD,OAAO;EACT,CAAC,CACH;CACF,CAAC,CACH;CAEA,MAAM,MAAM;EACV,GAAG;EACH,iBAAiB,YAAqB,gBAAgB,OAAO;EAC7D,gBAAgB,YAAqB,eAAe,OAAO;EAC3D,eAAe,YAAqB,cAAc,OAAO;EACzD,qBAAqB,YAAqB,oBAAoB,OAAO;CACvE;CAWA,MAAM,uBAAuBC,cAAsB,KAMjD,SAAS;EACT,GAAI,QAAQ,eAAe,OAAO,EAAE,YAAY,EAAE,SAAS,QAAQ,iBAAiB,EAAE,IAAI,CAAC;EAC3F,GAAI,QAAQ,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY,QAAQ,WAAW;EAG7E,YAAY,OAAO;EACnB;EACA,aAAa;CAIf,CAAkB;CAKlB,MAAM,qBAAqB,qBAAqB;EAC9C,MAAe,WAAuD;GACpE,OAAO,MAAM,QAAQ,SAAS;EAChC;CACF;CAEA,OAAO;AACT"}
|
package/dist/ThreadObject.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { A as ThreadPublicationOptions, C as portCall, D as CloudflareDurableRuntimeOptions, E as CloudflareDurableRuntimeInitializationError, M as layerConfig, N as layerHostConfig, O as CloudflareDurableRuntimeServices, P as layerInHost, S as make, T as CloudflareBootstrapServices, _ as decodeAdminVerifyRequest, a as AdminVerifyRequest, b as encodeAdminResponse, c as Instance, d as RetryExecuted, g as decodeAdminResponse, h as decodeAdminExplainRequest, i as AdminResponse, j as layer, k as ThreadObjectPorts, l as ObligationsScanned, m as VerifiedIntegrity, n as AdminFailed, o as Class, p as ThreadRpcOperation, r as AdminFailure, s as ExplainedRecovery, t as AdminExplainRequest, u as Options, v as decodeObligationThresholds, w as submit, x as handleRpc, y as decodeRetryCommand } from "./ThreadObject-
|
|
1
|
+
import { A as ThreadPublicationOptions, C as portCall, D as CloudflareDurableRuntimeOptions, E as CloudflareDurableRuntimeInitializationError, M as layerConfig, N as layerHostConfig, O as CloudflareDurableRuntimeServices, P as layerInHost, S as make, T as CloudflareBootstrapServices, _ as decodeAdminVerifyRequest, a as AdminVerifyRequest, b as encodeAdminResponse, c as Instance, d as RetryExecuted, g as decodeAdminResponse, h as decodeAdminExplainRequest, i as AdminResponse, j as layer, k as ThreadObjectPorts, l as ObligationsScanned, m as VerifiedIntegrity, n as AdminFailed, o as Class, p as ThreadRpcOperation, r as AdminFailure, s as ExplainedRecovery, t as AdminExplainRequest, u as Options, v as decodeObligationThresholds, w as submit, x as handleRpc, y as decodeRetryCommand } from "./ThreadObject-BMNq8kuv.mjs";
|
|
2
2
|
export { AdminExplainRequest, AdminFailed, AdminFailure, AdminResponse, AdminVerifyRequest, type CloudflareBootstrapServices as BootstrapServices, Class, ExplainedRecovery, type CloudflareDurableRuntimeInitializationError as InitializationError, Instance, ObligationsScanned, Options, type ThreadPublicationOptions as PublicationOptions, RetryExecuted, type CloudflareDurableRuntimeOptions as RuntimeOptions, type CloudflareDurableRuntimeServices as Services, ThreadObjectPorts, ThreadRpcOperation, VerifiedIntegrity, decodeAdminExplainRequest, decodeAdminResponse, decodeAdminVerifyRequest, decodeObligationThresholds, decodeRetryCommand, encodeAdminResponse, handleRpc, layer, layerConfig, layerHostConfig, layerInHost, make, portCall, submit };
|
package/dist/ThreadObject.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import "./CloudflareThreadClient.mjs";
|
|
2
|
-
import { C as layer, E as layerInHost, S as ThreadObjectPorts, T as layerHostConfig, _ as encodeAdminResponse, a as AdminVerifyRequest, b as portCall, c as RetryExecuted, d as VerifiedIntegrity, f as decodeAdminExplainRequest, g as decodeRetryCommand, h as decodeObligationThresholds, i as AdminResponse, m as decodeAdminVerifyRequest, n as AdminFailed, o as ExplainedRecovery, p as decodeAdminResponse, r as AdminFailure, s as ObligationsScanned, t as AdminExplainRequest, u as ThreadRpcOperation, v as handleRpc, w as layerConfig, x as submit, y as make } from "./ThreadObject-
|
|
2
|
+
import { C as layer, E as layerInHost, S as ThreadObjectPorts, T as layerHostConfig, _ as encodeAdminResponse, a as AdminVerifyRequest, b as portCall, c as RetryExecuted, d as VerifiedIntegrity, f as decodeAdminExplainRequest, g as decodeRetryCommand, h as decodeObligationThresholds, i as AdminResponse, m as decodeAdminVerifyRequest, n as AdminFailed, o as ExplainedRecovery, p as decodeAdminResponse, r as AdminFailure, s as ObligationsScanned, t as AdminExplainRequest, u as ThreadRpcOperation, v as handleRpc, w as layerConfig, x as submit, y as make } from "./ThreadObject-DvRG0dDz.mjs";
|
|
3
3
|
export { AdminExplainRequest, AdminFailed, AdminFailure, AdminResponse, AdminVerifyRequest, ExplainedRecovery, ObligationsScanned, RetryExecuted, ThreadObjectPorts, ThreadRpcOperation, VerifiedIntegrity, decodeAdminExplainRequest, decodeAdminResponse, decodeAdminVerifyRequest, decodeObligationThresholds, decodeRetryCommand, encodeAdminResponse, handleRpc, layer, layerConfig, layerHostConfig, layerInHost, make, portCall, submit };
|
package/dist/index.d.mts
CHANGED
|
@@ -8,6 +8,6 @@ import { t as CloudflareMemory_d_exports } from "./CloudflareMemory.mjs";
|
|
|
8
8
|
import { t as CloudflareScheduling_d_exports } from "./CloudflareScheduling.mjs";
|
|
9
9
|
import { t as CloudflareSubscriptions_d_exports } from "./CloudflareSubscriptions.mjs";
|
|
10
10
|
import { t as CloudflareThreadClient_d_exports } from "./CloudflareThreadClient.mjs";
|
|
11
|
-
import { f as ThreadObject_d_exports } from "./ThreadObject-
|
|
11
|
+
import { f as ThreadObject_d_exports } from "./ThreadObject-BMNq8kuv.mjs";
|
|
12
12
|
import { t as WakeScheduler_d_exports } from "./WakeScheduler.mjs";
|
|
13
13
|
export { Alarm_d_exports as Alarm, CloudflareAiGateway_d_exports as CloudflareAiGateway, CloudflareBindings_d_exports as CloudflareBindings, CloudflareBrowser_d_exports as CloudflareBrowser, CloudflareCodeMode_d_exports as CloudflareCodeMode, CloudflareConfig_d_exports as CloudflareConfig, CloudflareMemory_d_exports as CloudflareMemory, CloudflareScheduling_d_exports as CloudflareScheduling, CloudflareSubscriptions_d_exports as CloudflareSubscriptions, CloudflareThreadClient_d_exports as CloudflareThreadClient, ThreadObject_d_exports as ThreadObject, WakeScheduler_d_exports as WakeScheduler };
|
package/dist/index.mjs
CHANGED
|
@@ -8,6 +8,6 @@ import { t as CloudflareThreadClient_exports } from "./CloudflareThreadClient.mj
|
|
|
8
8
|
import { t as CloudflareScheduling_exports } from "./CloudflareScheduling.mjs";
|
|
9
9
|
import { t as CloudflareSubscriptions_exports } from "./CloudflareSubscriptions.mjs";
|
|
10
10
|
import { t as WakeScheduler_exports } from "./WakeScheduler.mjs";
|
|
11
|
-
import { l as ThreadObject_exports } from "./ThreadObject-
|
|
11
|
+
import { l as ThreadObject_exports } from "./ThreadObject-DvRG0dDz.mjs";
|
|
12
12
|
import { t as CloudflareAiGateway_exports } from "./CloudflareAiGateway.mjs";
|
|
13
13
|
export { Alarm_exports as Alarm, CloudflareAiGateway_exports as CloudflareAiGateway, CloudflareBindings_exports as CloudflareBindings, CloudflareBrowser_exports as CloudflareBrowser, CloudflareCodeMode_exports as CloudflareCodeMode, CloudflareConfig_exports as CloudflareConfig, CloudflareMemory_exports as CloudflareMemory, CloudflareScheduling_exports as CloudflareScheduling, CloudflareSubscriptions_exports as CloudflareSubscriptions, CloudflareThreadClient_exports as CloudflareThreadClient, ThreadObject_exports as ThreadObject, WakeScheduler_exports as WakeScheduler };
|
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"@effect-agent/platform-cloudflare","version":"0.1.0-beta.
|
|
1
|
+
{"name":"@effect-agent/platform-cloudflare","version":"0.1.0-beta.87","dependencies":{"@effect-agent/storage-cloudflare":"0.1.0-beta.87","@effect/platform-browser":"4.0.0-rc.112","@effect/sql-sqlite-do":"4.0.0-rc.112","effect-agent":"0.1.0-beta.87"},"devDependencies":{"@cloudflare/puppeteer":"1.1.0","@cloudflare/vitest-pool-workers":"0.21.3","@cloudflare/workers-types":"5.20260825.1","@effect-agent/testing":"0.1.0-beta.87","@effect/platform-node":"4.0.0-rc.112","@effect/sql-d1":"4.0.0-rc.112","@effect/vitest":"4.0.0-rc.112","effect":"4.0.0-rc.112","effect-cf":"0.41.0","esbuild":"0.28.1","miniflare":"5.20260811.1-alpha","typescript":"7.0.2","vite-plus":"0.3.0","vitest":"4.1.11"},"peerDependencies":{"@cloudflare/puppeteer":"^1.1.0","effect":"^4.0.0-rc.112","effect-cf":"^0.41.0"},"exports":{".":{"types":"./dist/index.d.mts","default":"./dist/index.mjs"},"./alarm":{"types":"./dist/Alarm.d.mts","default":"./dist/Alarm.mjs"},"./browser-rest-capture":{"types":"./dist/BrowserRestCapture.d.mts","default":"./dist/BrowserRestCapture.mjs"},"./browser-rest-crawl":{"types":"./dist/BrowserRestCrawl.d.mts","default":"./dist/BrowserRestCrawl.mjs"},"./cloudflare-bindings":{"types":"./dist/CloudflareBindings.d.mts","default":"./dist/CloudflareBindings.mjs"},"./cloudflare-browser":{"types":"./dist/CloudflareBrowser.d.mts","default":"./dist/CloudflareBrowser.mjs"},"./cloudflare-code-mode":{"types":"./dist/CloudflareCodeMode.d.mts","default":"./dist/CloudflareCodeMode.mjs"},"./cloudflare-config":{"types":"./dist/CloudflareConfig.d.mts","default":"./dist/CloudflareConfig.mjs"},"./cloudflare-memory":{"types":"./dist/CloudflareMemory.d.mts","default":"./dist/CloudflareMemory.mjs"},"./cloudflare-scheduling":{"types":"./dist/CloudflareScheduling.d.mts","default":"./dist/CloudflareScheduling.mjs"},"./cloudflare-subscriptions":{"types":"./dist/CloudflareSubscriptions.d.mts","default":"./dist/CloudflareSubscriptions.mjs"},"./cloudflare-thread-client":{"types":"./dist/CloudflareThreadClient.d.mts","default":"./dist/CloudflareThreadClient.mjs"},"./interactive-browser":{"types":"./dist/InteractiveBrowser.d.mts","default":"./dist/InteractiveBrowser.mjs"},"./protected-browser":{"types":"./dist/ProtectedBrowser.d.mts","default":"./dist/ProtectedBrowser.mjs"},"./thread-object":{"types":"./dist/ThreadObject.d.mts","default":"./dist/ThreadObject.mjs"},"./wake-scheduler":{"types":"./dist/WakeScheduler.d.mts","default":"./dist/WakeScheduler.mjs"},"./cloudflare-ai-gateway":{"types":"./dist/CloudflareAiGateway.d.mts","default":"./dist/CloudflareAiGateway.mjs"}},"description":"Cloudflare Layer assembly for Effect Agent: Durable Objects and Browser Run adapters.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/danieljvdm/effect-agent.git","directory":"packages/platform-cloudflare"},"files":["dist","src"],"type":"module","sideEffects":[],"publishConfig":{"access":"public"},"scripts":{"build":"vp pack","check":"tsc --noEmit -p tsconfig.json"},"peerDependenciesMeta":{"@cloudflare/puppeteer":{"optional":true}}}
|
package/src/Alarm.ts
CHANGED
|
@@ -403,6 +403,8 @@ export class ThreadMutationGate extends Context.Service<
|
|
|
403
403
|
{
|
|
404
404
|
readonly withMutation: <A, E, R>(
|
|
405
405
|
body: Effect.Effect<A, E, R>,
|
|
406
|
+
/** Indexed host work has its own durable deadline and does not invalidate ledger recovery. */
|
|
407
|
+
options?: { readonly invalidatesRecovery: boolean },
|
|
406
408
|
) => Effect.Effect<A, E | DurableAlarmError, R>;
|
|
407
409
|
readonly withSnapshot: <A, E, R>(
|
|
408
410
|
body: (active: number) => Effect.Effect<A, E, R>,
|
|
@@ -421,20 +423,23 @@ export class ThreadMutationGate extends Context.Service<
|
|
|
421
423
|
|
|
422
424
|
const runTransaction = yield* makeStorageOperation;
|
|
423
425
|
|
|
424
|
-
const beginMutation = Effect.fn("ThreadMaintenance.beginMutation")(function* (
|
|
426
|
+
const beginMutation = Effect.fn("ThreadMaintenance.beginMutation")(function* (
|
|
427
|
+
invalidatesRecovery: boolean,
|
|
428
|
+
) {
|
|
425
429
|
yield* failpoint.hit("maintenance:dirty:before");
|
|
426
430
|
const now = yield* Clock.currentTimeMillis;
|
|
427
431
|
|
|
428
432
|
yield* runTransaction("advance maintenance generation", () =>
|
|
429
433
|
ctx.storage.transaction(async (transaction) => {
|
|
430
|
-
const { state } = await readMaintenanceState(transaction);
|
|
434
|
+
const { state, initialized } = await readMaintenanceState(transaction);
|
|
431
435
|
|
|
432
436
|
const next = ThreadMaintenanceState.make({
|
|
433
437
|
...state,
|
|
434
|
-
dirty: state.dirty + 1n,
|
|
438
|
+
dirty: state.dirty + (invalidatesRecovery ? 1n : 0n),
|
|
435
439
|
});
|
|
436
440
|
|
|
437
|
-
|
|
441
|
+
if (invalidatesRecovery || !initialized)
|
|
442
|
+
await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(next));
|
|
438
443
|
// The earliest configured retry bounds a newly actionable mutation without relying
|
|
439
444
|
// on its best-effort immediate wake hint.
|
|
440
445
|
await ensureTransactionAlarmBy(transaction, now + minimumAlarmDelay);
|
|
@@ -450,9 +455,10 @@ export class ThreadMutationGate extends Context.Service<
|
|
|
450
455
|
|
|
451
456
|
const withMutation = <A, E, R>(
|
|
452
457
|
body: Effect.Effect<A, E, R>,
|
|
458
|
+
options?: { readonly invalidatesRecovery: boolean },
|
|
453
459
|
): Effect.Effect<A, E | DurableAlarmError, R> =>
|
|
454
460
|
Effect.acquireUseRelease(
|
|
455
|
-
generationGate.withPermit(beginMutation()),
|
|
461
|
+
generationGate.withPermit(beginMutation(options?.invalidatesRecovery ?? true)),
|
|
456
462
|
() =>
|
|
457
463
|
failpoint.hit("maintenance:mutation:armed").pipe(
|
|
458
464
|
Effect.andThen(body),
|
|
@@ -11,7 +11,7 @@ import { DurableAlarmError, ThreadMessageDelivery, ThreadMutationGate } from "..
|
|
|
11
11
|
import { ThreadObjectPlacement } from "../CloudflareBindings.ts";
|
|
12
12
|
import { CloudflareDurableRuntimeConfig } from "../CloudflareConfig.ts";
|
|
13
13
|
|
|
14
|
-
/** Every
|
|
14
|
+
/** Every write prearms its owner; the delivery due index owns its recovery deadline. */
|
|
15
15
|
export const guardedMessageDeliveryStoreLayer = Layer.effect(
|
|
16
16
|
MessageDeliveryStore,
|
|
17
17
|
Effect.gen(function* () {
|
|
@@ -36,7 +36,12 @@ export const guardedMessageDeliveryStoreLayer = Layer.effect(
|
|
|
36
36
|
|
|
37
37
|
const mutate = <A, E>(body: Effect.Effect<A, E>) =>
|
|
38
38
|
mutations
|
|
39
|
-
.withMutation(
|
|
39
|
+
.withMutation(
|
|
40
|
+
cacheGate.withPermit(Ref.set(deadline, undefined).pipe(Effect.andThen(body))),
|
|
41
|
+
// A foreign receipt changing does not make the source ledger actionable. Keep the
|
|
42
|
+
// prearm and producer gate so eviction and a racing pass cannot lose delivery work.
|
|
43
|
+
{ invalidatesRecovery: false },
|
|
44
|
+
)
|
|
40
45
|
.pipe(
|
|
41
46
|
Effect.catchTag("DurableAlarmError", () =>
|
|
42
47
|
MessageDeliveryError.make({ reason: "storage", operation: "prearm message delivery" }),
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ThreadObject-B4gJ7t0d.mjs","names":["EffectCfDurableObjectState","EffectCfDurableObject"],"sources":["../src/internal/message-delivery.ts","../src/internal/progress-wait.ts","../src/internal/transport.ts","../src/internal/layers.ts","../src/ThreadObject.ts"],"sourcesContent":["import { Clock, Context, Deferred, Effect, Layer, Option, Ref, Semaphore, Stream } from \"effect\";\nimport { type ThreadId } from \"effect-agent/identifiers\";\nimport {\n MessageDeliveryDriver,\n MessageDeliveryError,\n MessageDeliveryStore,\n} from \"effect-agent/message-delivery\";\nimport { WakeScheduler } from \"effect-agent/wake-scheduler\";\n\nimport { DurableAlarmError, ThreadMessageDelivery, ThreadMutationGate } from \"../Alarm.ts\";\nimport { ThreadObjectPlacement } from \"../CloudflareBindings.ts\";\nimport { CloudflareDurableRuntimeConfig } from \"../CloudflareConfig.ts\";\n\n/** Every externally requested write prearms the owning Object's maintenance generation. */\nexport const guardedMessageDeliveryStoreLayer = Layer.effect(\n MessageDeliveryStore,\n Effect.gen(function* () {\n const store = yield* MessageDeliveryStore;\n const mutations = yield* ThreadMutationGate;\n const wakes = yield* WakeScheduler;\n const { ownsThread } = yield* ThreadObjectPlacement;\n // Reconstructed as unknown on every incarnation. The gate prevents a racing read from\n // caching an empty deadline across a write; SQL remains the recovery authority.\n const deadline = yield* Ref.make<number | null | undefined>(undefined);\n const cacheGate = yield* Semaphore.make(1);\n\n const local = <A, E>(\n owner: ThreadId | undefined,\n body: Effect.Effect<A, E>,\n ): Effect.Effect<A, E | MessageDeliveryError> =>\n owner === undefined || ownsThread(owner)\n ? body\n : Effect.fail(\n MessageDeliveryError.make({ reason: \"validation\", operation: \"message owner\" }),\n );\n\n const mutate = <A, E>(body: Effect.Effect<A, E>) =>\n mutations\n .withMutation(cacheGate.withPermit(Ref.set(deadline, undefined).pipe(Effect.andThen(body))))\n .pipe(\n Effect.catchTag(\"DurableAlarmError\", () =>\n MessageDeliveryError.make({ reason: \"storage\", operation: \"prearm message delivery\" }),\n ),\n );\n\n const nextDeadline = cacheGate.withPermit(\n Effect.gen(function* () {\n const cached = yield* Ref.get(deadline);\n\n if (cached !== undefined) return cached;\n const current = yield* store.nextDeadline();\n\n yield* Ref.set(deadline, current);\n\n return current;\n }),\n );\n\n return MessageDeliveryStore.of({\n limits: store.limits,\n maxStoredValueBytes: store.maxStoredValueBytes,\n insert: (record) =>\n local(\n record.key.ownerThreadId,\n mutate(store.insert(record)).pipe(\n Effect.tap(() => wakes.notify(record.key.ownerThreadId)),\n ),\n ),\n get: (key) => local(key.ownerThreadId, store.get(key)),\n list: (request) => local(request.ownerThreadId, store.list(request)),\n change: (key, change) => local(key.ownerThreadId, mutate(store.change(key, change))),\n // Only the trusted physical-owner pump omits an owner. All returned keys still\n // pass placement validation before the driver may dispatch any of the wave.\n due: (nowMillis, limit, owner) =>\n local(owner, store.due(nowMillis, limit, owner)).pipe(\n Effect.filterOrFail(\n (keys) => keys.every((key) => ownsThread(key.ownerThreadId)),\n () => MessageDeliveryError.make({ reason: \"validation\", operation: \"message owner\" }),\n ),\n ),\n nextDeadline: (owner) =>\n local(owner, owner === undefined ? nextDeadline : store.nextDeadline(owner)),\n });\n }),\n);\n\n/** Message progress shares the native alarm slot without blocking source runtime work. */\nexport const threadMessageDeliveryLayer = Layer.effectContext(\n Effect.gen(function* () {\n const driver = yield* MessageDeliveryDriver;\n const store = yield* MessageDeliveryStore;\n const wakes = yield* WakeScheduler;\n const config = yield* CloudflareDurableRuntimeConfig;\n\n const failure = (operation: string) => () =>\n DurableAlarmError.make({\n operation,\n message: \"Durable message recovery remains pending\",\n });\n\n const drain = Effect.gen(function* () {\n const deadline = yield* store.nextDeadline();\n\n if (deadline !== null && deadline <= (yield* Clock.currentTimeMillis)) {\n yield* driver.runDue();\n }\n }).pipe(Effect.mapError(failure(\"drain message delivery\")));\n\n return Context.make(ThreadMessageDelivery, {\n drain,\n drainUntil: Effect.fn(\"ThreadMessageDelivery.drainUntil\")(function* (\n finished: Deferred.Deferred<void>,\n ) {\n // One scoped subscription covers every logical lane in this physical owner.\n // Acquire it before reading durable deadlines; hints remain droppable.\n const notified = (yield* Stream.toPull(wakes.wakes)).pipe(Effect.catch(() => Effect.never));\n\n // Always finish one wave; source completion prevents starting subsequent waves.\n yield* Effect.gen(function* () {\n yield* drain;\n\n const deadline = yield* store\n .nextDeadline()\n .pipe(Effect.mapError(failure(\"read message deadline\")));\n\n // The index includes unfinished waves, lease expiry, retry and settlement polls.\n // Yield at least one millisecond for an already-due deadline instead of spinning.\n const delay =\n deadline === null\n ? config.wakeScanInterval\n : Math.min(\n config.wakeScanInterval,\n Math.max(1, deadline - (yield* Clock.currentTimeMillis)),\n );\n\n yield* Effect.raceFirst(\n Deferred.await(finished),\n Effect.raceFirst(notified, Effect.sleep(delay)),\n );\n }).pipe(Effect.repeat({ until: () => Deferred.isDone(finished) }));\n }, Effect.scoped),\n pendingDeadline: store\n .nextDeadline()\n .pipe(Effect.map(Option.fromNullishOr), Effect.mapError(failure(\"read message deadline\"))),\n });\n }),\n);\n","import { Context, Deferred, Effect, Layer, Ref, type Scope } from \"effect\";\n\n/** Cancellation tombstones are bounded hints, never durable authority. */\nconst MAX_CANCELLATION_TOMBSTONES = 1_024;\n\ntype ActiveRegistration = ReadonlySet<Deferred.Deferred<void>>;\ntype Registration = ActiveRegistration | \"cancelled\";\ntype Registrations = ReadonlyMap<string, Registration>;\n\n/**\n * Per-incarnation cancellation registry for long-lived progress RPCs. The public runtime owns\n * the actual wake registration; this host-only registry lets an interrupted Worker Effect ask\n * the Object to interrupt its scoped wait before the Worker execution context itself ends.\n */\nexport class ProgressWaitRegistry extends Context.Service<\n ProgressWaitRegistry,\n {\n /** Register a Scope-owned cancellation signal, observing any early cancel tombstone. */\n readonly subscribe: (\n waiterId: string,\n ) => Effect.Effect<Effect.Effect<void>, never, Scope.Scope>;\n /** Cancel every attempt and retain a bounded tombstone for later transport attempts. */\n readonly cancel: (waiterId: string) => Effect.Effect<void>;\n }\n>()(\"@effect-agent/platform-cloudflare/ProgressWaitRegistry\") {\n static readonly layer: Layer.Layer<ProgressWaitRegistry> = Layer.effect(\n ProgressWaitRegistry,\n Effect.gen(function* () {\n const registrations = yield* Ref.make<Registrations>(new Map());\n\n const remove = (waiterId: string, deferred: Deferred.Deferred<void>) =>\n Ref.update(registrations, (current) => {\n const existing = current.get(waiterId);\n\n if (existing === undefined || existing === \"cancelled\" || !existing.has(deferred)) {\n return current;\n }\n const next = new Map(current);\n const active = new Set(existing);\n\n active.delete(deferred);\n if (active.size === 0) {\n next.delete(waiterId);\n } else {\n next.set(waiterId, active);\n }\n\n return next;\n });\n\n const subscribe = Effect.fn(\"ProgressWaitRegistry.subscribe\")(\n (waiterId: string): Effect.Effect<Effect.Effect<void>, never, Scope.Scope> =>\n Effect.gen(function* () {\n const deferred = yield* Deferred.make<void>();\n\n yield* Effect.addFinalizer(() => remove(waiterId, deferred));\n\n const cancelled = yield* Ref.modify(registrations, (current) => {\n const existing = current.get(waiterId);\n const next = new Map(current);\n\n if (existing === \"cancelled\") {\n return [true, current] as const;\n }\n const active = new Set(existing ?? []);\n\n active.add(deferred);\n next.set(waiterId, active);\n\n return [false, next] as const;\n });\n\n return { cancelled, deferred };\n }).pipe(\n Effect.map(({ cancelled, deferred }) =>\n cancelled ? Effect.void : Deferred.await(deferred),\n ),\n ),\n );\n\n // Updating the registry and completing captured signals form one nonblocking operation;\n // interruption between them must not strand attempts removed from the active registry.\n const cancel = Effect.fn(\"ProgressWaitRegistry.cancel\")(function* (waiterId: string) {\n const waiters = yield* Ref.modify(\n registrations,\n (current): readonly [ReadonlyArray<Deferred.Deferred<void>>, Registrations] => {\n const existing = current.get(waiterId);\n\n if (existing === \"cancelled\") return [[], current] as const;\n const next = new Map(current);\n\n // A retry may arrive after an active attempt was cancelled. Retain the same\n // tombstone used for early cancellation, ordered by cancellation time.\n next.delete(waiterId);\n next.set(waiterId, \"cancelled\");\n let tombstones = 0;\n\n for (const registration of next.values()) {\n if (registration === \"cancelled\") tombstones += 1;\n }\n if (tombstones > MAX_CANCELLATION_TOMBSTONES) {\n for (const [id, registration] of next) {\n if (registration !== \"cancelled\") continue;\n next.delete(id);\n break;\n }\n }\n\n return [existing === undefined ? [] : [...existing], next] as const;\n },\n );\n\n yield* Effect.forEach(waiters, (waiter) => Deferred.succeed(waiter, undefined), {\n discard: true,\n });\n }, Effect.uninterruptible);\n\n return ProgressWaitRegistry.of({ subscribe, cancel });\n }),\n );\n}\n","import {\n ThreadPortTransport,\n portTransportFailure,\n} from \"@effect-agent/storage-cloudflare/port-routing\";\nimport { Effect, Layer } from \"effect\";\n\nimport { callThreadObject, ThreadObjectNamespace } from \"../CloudflareBindings.ts\";\n\n/**\n * `ThreadPortTransport` over native Durable Object JS RPC (decision D-P6-3): one\n * `portCall(envelope)` on the stub of the Object that owns the addressed Thread\n * (`namespace.idFromName(threadId)` — the identity rule, plan §1.2). The envelopes are\n * already Schema-encoded JSON, so the RPC boundary carries only structured-cloneable values;\n * the protocol module stays transport-agnostic and fetch-with-JSON remains the documented\n * fallback carrier.\n *\n * Every delivery problem — stub construction, RPC rejection, overload, deploy-in-progress —\n * surfaces as `PortTransportError` (preserving the platform stub's own `retryable` signal\n * when present) and NEVER as a fabricated answer: on `resolveAdmission` the routing layer\n * turns exactly this error into `AdmissionIndeterminate` (SUB-031).\n */\nexport const threadPortTransportLayer: Layer.Layer<\n ThreadPortTransport,\n never,\n ThreadObjectNamespace\n> = Layer.effect(ThreadPortTransport)(\n Effect.gen(function* () {\n const namespace = yield* ThreadObjectNamespace;\n\n return ThreadPortTransport.of({\n call: (threadId, request) =>\n callThreadObject(\n threadId,\n (target) => target.portCall(request),\n (cause) => portTransportFailure(threadId, cause),\n ).pipe(\n Effect.provideService(ThreadObjectNamespace, namespace),\n Effect.withSpan(\"CloudflarePortTransport.call\", {\n attributes: { threadId },\n }),\n ),\n });\n }),\n);\n","import { doMessageDeliveryStoreLayer } from \"@effect-agent/storage-cloudflare/do-message-delivery-store\";\nimport {\n type DoStorageFailpointHandler,\n type DoStorageFailpoint,\n} from \"@effect-agent/storage-cloudflare/do-storage-failpoint\";\nimport { submissionLedgerLayer } from \"@effect-agent/storage-cloudflare/do-submission-ledger\";\nimport {\n threadStoreLayer,\n storageConfigLayer,\n storageFailpointLayer,\n type DoStorageInitializationError,\n type DoStorageOptions,\n} from \"@effect-agent/storage-cloudflare/do-thread-store\";\nimport {\n type PortRequest,\n type PortResponse,\n} from \"@effect-agent/storage-cloudflare/port-protocol\";\nimport {\n executePortRequest,\n routedThreadStoreLayer,\n routedSubmissionLedgerLayer,\n} from \"@effect-agent/storage-cloudflare/port-routing\";\nimport { BrowserCrypto } from \"@effect/platform-browser\";\nimport { SqliteClient } from \"@effect/sql-sqlite-do\";\nimport {\n type Crypto,\n Cause,\n Context,\n Duration,\n Effect,\n Layer,\n Schema,\n Semaphore,\n type Option,\n} from \"effect\";\nimport {\n compileRegistrations,\n type AgentRegistration,\n type ResolvedBinding,\n} from \"effect-agent/agent-registration\";\nimport { type DigestError } from \"effect-agent/digest\";\nimport { DurableAgentRuntime, DurableRuntimeConfig } from \"effect-agent/durable-agent-runtime\";\nimport {\n DurableRuntimeFailpoint,\n type DurableRuntimeFailpointHandler,\n} from \"effect-agent/durable-failpoint\";\nimport { ThreadId, type SubmissionId } from \"effect-agent/identifiers\";\nimport {\n type MessageDeliveryStore,\n MessageDeliveryDriver,\n type MessageDeliveryError,\n} from \"effect-agent/message-delivery\";\nimport {\n operationAuthorizerLayer,\n type OperationAuthorizerService,\n} from \"effect-agent/operation-authorizer\";\nimport { type PreparedInputAdmission } from \"effect-agent/prepared-input-admission\";\nimport { ProducerId } from \"effect-agent/records\";\nimport {\n type RunContextPreparation,\n type RunCostEstimator,\n type RunToolFailureObserver,\n} from \"effect-agent/run-options\";\nimport {\n CurrentToolFailureObserver,\n RunContextPreparationPassthrough,\n RunToolAuthorization,\n toolFailureObserverLayer,\n} from \"effect-agent/run-options\";\nimport {\n LedgerError,\n SubmissionLedger,\n SubmissionLookupById,\n type SubmissionSnapshot,\n} from \"effect-agent/submission-ledger\";\nimport { ThreadProjectionMaintenance } from \"effect-agent/thread-projection-maintenance\";\nimport { ThreadStoreError, ThreadStore } from \"effect-agent/thread-store\";\nimport { ToolReconciler } from \"effect-agent/tool-reconciler\";\nimport { type WakeScheduler } from \"effect-agent/wake-scheduler\";\nimport { SqlClient } from \"effect/unstable/sql/SqlClient\";\n\nimport {\n ThreadMaintenance,\n ThreadMutationGate,\n ThreadPublication,\n publishCommitted,\n ThreadMaintenanceFailpoint,\n DurableAlarmService,\n type ThreadMaintenanceFailpointHandler,\n} from \"../Alarm.ts\";\nimport {\n ThreadObjectIdentity,\n ThreadObjectPlacement,\n DurableObjectContext,\n type ThreadObjectNamespace,\n} from \"../CloudflareBindings.ts\";\nimport {\n CLOUDFLARE_RUNTIME_DEFAULTS,\n CloudflareDurableRuntimeConfig,\n CloudflareDurableRuntimeConfigValue,\n CloudflarePlatformConfigError,\n} from \"../CloudflareConfig.ts\";\nimport { CloudflareThreadClient } from \"../CloudflareThreadClient.ts\";\nimport { cloudflareWakeSchedulerLayer } from \"../WakeScheduler.ts\";\nimport {\n guardedMessageDeliveryStoreLayer,\n threadMessageDeliveryLayer,\n} from \"./message-delivery.ts\";\nimport { cloudflarePreparedInputAdmissionLayer } from \"./prepared-admission.ts\";\nimport { ProgressWaitRegistry } from \"./progress-wait.ts\";\nimport { threadPortTransportLayer } from \"./transport.ts\";\n\n/**\n * Raw (unvalidated) construction options for `ThreadObject.make`, mirroring\n * `NodeDurableAgentRuntimeOptions`. Optional fields default to the documented production values\n * (`CLOUDFLARE_RUNTIME_DEFAULTS`); everything is schema-decoded into\n * `CloudflareDurableRuntimeConfigValue` before any resource opens (deployment §5 gate 1).\n */\nexport interface CloudflareDurableRuntimeOptions {\n readonly deploymentId: string;\n /** Head of the minted producer identity `{producerPrefix}:{threadId}`. */\n readonly producerPrefix: string;\n /** Milliseconds; default 30s (D5). */\n readonly ownershipLeaseDuration?: number | undefined;\n /** Milliseconds; default 100. */\n readonly alarmBackoffBase?: number | undefined;\n /** Milliseconds; default 5000. */\n readonly alarmBackoffCap?: number | undefined;\n /** Milliseconds; default 1000. Bounds every alarm re-arm delay. */\n readonly wakeScanInterval?: number | undefined;\n /** Milliseconds; default 500. */\n readonly settlementPollInterval?: number | undefined;\n /** Milliseconds; default 10000. */\n readonly leaseRenewalInterval?: number | undefined;\n /** Milliseconds; default 500. */\n readonly abortPollInterval?: number | undefined;\n /** Deployment-owned pricing authority used by durable cost budgets and settlements. */\n readonly estimateCostMicrousd?: RunCostEstimator | undefined;\n /** Closed trusted Tool failure reporting. Omission masks ambient observers at construction. */\n readonly toolFailureObserver?: RunToolFailureObserver | undefined;\n /** Milliseconds; default 25. */\n readonly observationPollInterval?: number | undefined;\n /** Bytes; default just under the 2 MB platform value limit. */\n readonly maxStoredValueBytes?: number | undefined;\n /** Default false. */\n readonly verifyOnOpen?: boolean | undefined;\n /** Nonterminal Submissions per lane before admission refuses; default 256. */\n readonly maxQueueDepthPerLane?: number | undefined;\n /** Encoded input bytes per Submission; default = the stored-value bound. */\n readonly maxInputBytes?: number | undefined;\n /** `ctx.storage.sql.databaseSize` ceiling at admission; default 9 GB (10 GB platform cap). */\n readonly maxDatabaseBytes?: number | undefined;\n /**\n * Durable Object storage fault injection (`ledger:*` / `append:*` locations). Handlers are\n * constructed per incarnation WITH the live `DurableObjectState`, so eviction harnesses can\n * map an armed hit to `ctx.abort()` — the platform's real failure mode. Default none.\n */\n readonly storageFailpoint?: ((ctx: DurableObjectState) => DoStorageFailpointHandler) | undefined;\n /** Coordinator fault injection (`submit:*` / `terminalize:*` locations); default none. */\n readonly runtimeFailpoint?:\n | ((ctx: DurableObjectState) => DurableRuntimeFailpointHandler)\n | undefined;\n /** Thread-maintenance generation/alarm fault injection; default none. */\n readonly maintenanceFailpoint?:\n | ((ctx: DurableObjectState) => ThreadMaintenanceFailpointHandler)\n | undefined;\n /** Host-supplied fail-closed authorization policy; defaults to service possession. */\n readonly operationAuthorizer?: OperationAuthorizerService | undefined;\n /**\n * Reconciliation policy consulted for open ordinary Tool Calls before an Unknown Outcome\n * is recorded (durability §10, DUR-009). Defaults to the fail-closed\n * `ToolReconciler.uncertain`.\n */\n readonly toolReconciler?: Layer.Layer<ToolReconciler> | undefined;\n}\n\n/** Services supplied before the application graph is built, including its dependencies. */\nexport type CloudflareBootstrapServices =\n | CloudflareDurableRuntimeConfig\n | ThreadObjectIdentity\n | ThreadObjectPlacement\n | DurableRuntimeConfig\n | Crypto.Crypto\n | DoStorageFailpoint\n | DurableRuntimeFailpoint\n | ThreadMaintenanceFailpoint\n | RunContextPreparation\n | RunToolAuthorization\n | ToolReconciler;\n\n/** Every construction failure of the assembled Cloudflare durable runtime stack. */\nexport type CloudflareDurableRuntimeInitializationError =\n | CloudflarePlatformConfigError\n | DigestError\n | MessageDeliveryError\n | DoStorageInitializationError;\n\n/**\n * The services `ThreadObject.layer` provides, including its single owner SQL client.\n * Its Context also supplies ThreadMessageDelivery (a defaulted Reference, with no required R)\n * so application-composed maintenance retains the same native message recovery capability.\n */\nexport type CloudflareDurableRuntimeServices =\n | DurableAgentRuntime\n | SubmissionLedger\n | ThreadStore\n | MessageDeliveryStore\n | WakeScheduler\n | DurableAlarmService\n | ThreadMaintenance\n | ThreadMutationGate\n | ThreadPublication\n | ThreadProjectionMaintenance\n | ThreadObjectPorts\n | ProgressWaitRegistry\n | SqlClient;\n\n/**\n * Owner-side execution port for a `portCall` request the wire endpoint has already decoded.\n * It executes against THIS Object's LOCAL port facets — never the routed decorators, so a\n * request cannot bounce between Objects — and returns the typed response for the endpoint to\n * encode.\n */\nexport class ThreadObjectPorts extends Context.Service<\n ThreadObjectPorts,\n {\n readonly handle: (request: PortRequest) => Effect.Effect<PortResponse>;\n /** Local-only identity check before a bound RPC can read or mutate a Submission. */\n readonly lookupSubmission: (\n submissionId: SubmissionId,\n ) => Effect.Effect<Option.Option<SubmissionSnapshot>, LedgerError>;\n }\n>()(\"@effect-agent/platform-cloudflare/ThreadObjectPorts\") {}\n\nconst decodeConfigValue = Schema.decodeUnknownEffect(CloudflareDurableRuntimeConfigValue);\nconst decodeThreadId = Schema.decodeUnknownEffect(ThreadId);\nconst decodeProducerId = Schema.decodeUnknownEffect(ProducerId);\n\nconst configFromOptions = (\n options: CloudflareDurableRuntimeOptions,\n): Effect.Effect<CloudflareDurableRuntimeConfigValue, CloudflarePlatformConfigError> =>\n decodeConfigValue({\n deploymentId: options.deploymentId,\n producerPrefix: options.producerPrefix,\n ownershipLeaseDuration:\n options.ownershipLeaseDuration ?? CLOUDFLARE_RUNTIME_DEFAULTS.ownershipLeaseDuration,\n alarmBackoffBase: options.alarmBackoffBase ?? CLOUDFLARE_RUNTIME_DEFAULTS.alarmBackoffBase,\n alarmBackoffCap: options.alarmBackoffCap ?? CLOUDFLARE_RUNTIME_DEFAULTS.alarmBackoffCap,\n wakeScanInterval: options.wakeScanInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.wakeScanInterval,\n settlementPollInterval:\n options.settlementPollInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.settlementPollInterval,\n leaseRenewalInterval:\n options.leaseRenewalInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.leaseRenewalInterval,\n abortPollInterval: options.abortPollInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.abortPollInterval,\n observationPollInterval:\n options.observationPollInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.observationPollInterval,\n maxStoredValueBytes:\n options.maxStoredValueBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxStoredValueBytes,\n verifyOnOpen: options.verifyOnOpen ?? CLOUDFLARE_RUNTIME_DEFAULTS.verifyOnOpen,\n limits: {\n maxQueueDepthPerLane:\n options.maxQueueDepthPerLane ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxQueueDepthPerLane,\n maxInputBytes: Math.min(\n options.maxInputBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxInputBytes,\n options.maxStoredValueBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxStoredValueBytes,\n ),\n maxDatabaseBytes: options.maxDatabaseBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxDatabaseBytes,\n },\n }).pipe(\n Effect.mapError((error) =>\n CloudflarePlatformConfigError.make({\n message: `Invalid Cloudflare durable runtime configuration: ${error.message}`,\n cause: error,\n }),\n ),\n );\n\n/**\n * The Thread this Object owns, from the Object identity rule (plan §1.2): Thread\n * Objects are addressed exclusively by `idFromName(threadId)`, so `ctx.id.name` IS the\n * Thread ID. An unnamed Object (from `newUniqueId`) is a deployment error, not a lane.\n */\nconst threadIdFromState = (\n ctx: DurableObjectState,\n): Effect.Effect<ThreadId, CloudflarePlatformConfigError> =>\n ctx.id.name === undefined\n ? Effect.fail(\n CloudflarePlatformConfigError.make({\n message:\n \"This Durable Object was not created via idFromName(threadId); Thread \" +\n \"Objects must be addressed by their Thread identity (plan §1.2).\",\n }),\n )\n : decodeThreadId(ctx.id.name).pipe(\n Effect.mapError((error) =>\n CloudflarePlatformConfigError.make({\n message: `The Durable Object name is not a valid ThreadId: ${error.message}`,\n cause: error,\n }),\n ),\n );\n\n/**\n * Validate deployment settings and derive services before building application dependencies.\n * The native class factory builds this Layer inside its constructor gate. Custom Effect hosts\n * can provide it around the complete application Layer with the native context already supplied.\n */\nconst runtimeConfigLayer = (\n options: CloudflareDurableRuntimeOptions,\n producerId: ProducerId,\n): Layer.Layer<\n Exclude<CloudflareBootstrapServices, ThreadObjectIdentity | ThreadObjectPlacement>,\n CloudflarePlatformConfigError,\n DurableObjectContext\n> =>\n Layer.unwrap(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n const config = yield* configFromOptions(options);\n\n return Layer.mergeAll(\n Layer.succeed(CloudflareDurableRuntimeConfig, config),\n DurableRuntimeConfig.layer({\n deploymentId: config.deploymentId,\n producerId,\n settlementPollInterval: Duration.millis(config.settlementPollInterval),\n leaseRenewalInterval: Duration.millis(config.leaseRenewalInterval),\n abortPollInterval: Duration.millis(config.abortPollInterval),\n ...(options.estimateCostMicrousd === undefined\n ? {}\n : { estimateCostMicrousd: options.estimateCostMicrousd }),\n }),\n BrowserCrypto.layer,\n storageFailpointLayer({ storage: ctx.storage, failpoint: options.storageFailpoint?.(ctx) }),\n options.runtimeFailpoint === undefined\n ? DurableRuntimeFailpoint.layer\n : Layer.succeed(DurableRuntimeFailpoint, { hit: options.runtimeFailpoint(ctx) }),\n options.maintenanceFailpoint === undefined\n ? ThreadMaintenanceFailpoint.layer\n : Layer.succeed(ThreadMaintenanceFailpoint, {\n hit: options.maintenanceFailpoint(ctx),\n }),\n options.toolReconciler ?? ToolReconciler.uncertain,\n options.operationAuthorizer === undefined\n ? Layer.empty\n : operationAuthorizerLayer(options.operationAuthorizer),\n options.toolFailureObserver === undefined\n ? Layer.succeed(CurrentToolFailureObserver, undefined)\n : toolFailureObserverLayer(options.toolFailureObserver),\n RunContextPreparationPassthrough,\n RunToolAuthorization.allowAll,\n );\n }),\n );\n\nconst producerIdentity = (prefix: string, owner: string) =>\n decodeProducerId(`${prefix}:${owner}`).pipe(\n Effect.mapError((error) =>\n CloudflarePlatformConfigError.make({\n message: `The minted producer identity is invalid: ${error.message}`,\n cause: error,\n }),\n ),\n );\n\n/** Native one-Thread configuration; retains its existing producer and logical identities. */\nexport const layerConfig = (\n options: CloudflareDurableRuntimeOptions,\n): Layer.Layer<CloudflareBootstrapServices, CloudflarePlatformConfigError, DurableObjectContext> =>\n Layer.unwrap(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n const threadId = yield* threadIdFromState(ctx);\n const producerId = yield* producerIdentity(options.producerPrefix, threadId);\n\n return Layer.mergeAll(\n runtimeConfigLayer(options, producerId),\n Layer.succeed(ThreadObjectIdentity, { threadId, producerId }),\n Layer.succeed(ThreadObjectPlacement, { ownsThread: (target) => target === threadId }),\n );\n }),\n );\n\n/**\n * Configuration for an application Object owning several logical Threads. The producer is\n * the stable physical Object. No logical identity is installed globally: handleRpc binds and\n * validates it per request using the placement guard and this actual runtime producer.\n */\nexport const layerHostConfig = (\n options: CloudflareDurableRuntimeOptions,\n ownsThread: (threadId: ThreadId) => boolean,\n): Layer.Layer<\n Exclude<CloudflareBootstrapServices, ThreadObjectIdentity>,\n CloudflarePlatformConfigError,\n DurableObjectContext\n> =>\n Layer.unwrap(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n const producerId = yield* producerIdentity(options.producerPrefix, ctx.id.toString());\n\n return Layer.merge(\n runtimeConfigLayer(options, producerId),\n Layer.succeed(ThreadObjectPlacement, { ownsThread }),\n );\n }),\n );\n\nexport interface ThreadPublicationOptions<E = never, R = never, P = never> {\n /**\n * Optional host outbox consumer, built once per incarnation with RAW LOCAL ThreadStore and\n * SubmissionLedger services. Yield DurableObjectContext and ThreadObjectIdentity for native\n * bindings and identity. Initialization is local-only, inside the constructor gate; setup\n * errors and additional requirements remain in the returned Layer. Layer.effect owns Scope.\n * Canonical appends and durable approval, abort and unknown-resolution intents invalidate\n * publication after commit. Custom host facts must use ThreadMaintenance.withMutation.\n */\n readonly publication?: Layer.Layer<ThreadPublication, E, R>;\n /**\n * Disposable index maintenance, built once with the raw local ThreadStore and owner\n * SqlClient. Additional services P are exposed by the returned Layer, allowing Tool\n * handlers and maintenance to share one index instance. Construction is local-only.\n * Live committed batches run before append returns; bounded backfill uses the native\n * alarm without delaying execution behind projection backlog.\n */\n readonly projection?: Layer.Layer<ThreadProjectionMaintenance | P, E, R>;\n}\n\n/**\n * Register typed Agents and version declarations. Hashing and dependency capture happen in\n * this Layer's Scope, after application Layers have been provided. Every Agent's instruction,\n * Tool, Schema, and model requirements remain visible until satisfied by Layer composition.\n * Use Layer.unwrap for registration values that need effectful application setup.\n */\nconst registeredLayer = <\n const Entries extends ReadonlyArray<AgentRegistration>,\n E = never,\n R = never,\n>(\n registrations: Entries,\n options: ThreadPublicationOptions<E, R> = {},\n) =>\n Layer.unwrap(\n Effect.map(compileRegistrations(registrations), (bindings) => boundLayer(bindings, options)),\n );\n\n/** Preserve additional index services only when a projection Layer is actually supplied. */\nexport function layer<\n const Entries extends ReadonlyArray<AgentRegistration>,\n E = never,\n R = never,\n P = never,\n PE = never,\n PR = never,\n>(\n registrations: Entries,\n options: Omit<ThreadPublicationOptions<E, R>, \"projection\"> & {\n readonly projection: Layer.Layer<ThreadProjectionMaintenance | P, PE, PR>;\n },\n): Layer.Layer<\n Layer.Success<ReturnType<typeof registeredLayer<Entries, E | PE, R | PR>>> | P,\n Layer.Error<ReturnType<typeof registeredLayer<Entries, E | PE, R | PR>>>,\n Layer.Services<ReturnType<typeof registeredLayer<Entries, E | PE, R | PR>>>\n>;\n\nexport function layer<const Entries extends ReadonlyArray<AgentRegistration>, E = never, R = never>(\n registrations: Entries,\n options?: ThreadPublicationOptions<E, R>,\n): ReturnType<typeof registeredLayer<Entries, E, R>>;\n\nexport function layer<const Entries extends ReadonlyArray<AgentRegistration>, E = never, R = never>(\n registrations: Entries,\n options: ThreadPublicationOptions<E, R> = {},\n) {\n return registeredLayer(registrations, options);\n}\n\nexport function layerFromBindings<E = never, R = never, P = never, PE = never, PR = never>(\n bindings: ReadonlyArray<ResolvedBinding>,\n options: Omit<ThreadPublicationOptions<E, R>, \"projection\"> & {\n readonly projection: Layer.Layer<ThreadProjectionMaintenance | P, PE, PR>;\n },\n): Layer.Layer<\n CloudflareDurableRuntimeServices | P,\n Layer.Error<ReturnType<typeof boundLayer<E | PE, R | PR>>>,\n Layer.Services<ReturnType<typeof boundLayer<E | PE, R | PR>>>\n>;\n\nexport function layerFromBindings<E = never, R = never>(\n bindings: ReadonlyArray<ResolvedBinding>,\n options?: ThreadPublicationOptions<E, R>,\n): ReturnType<typeof boundLayer<E, R>>;\n\nexport function layerFromBindings(\n bindings: ReadonlyArray<ResolvedBinding>,\n): ReturnType<typeof boundLayer<never, never>>;\n\nexport function layerFromBindings<E = never, R = never>(\n bindings: ReadonlyArray<ResolvedBinding>,\n options: ThreadPublicationOptions<E, R> = {},\n) {\n return boundLayer(bindings, options);\n}\n\n/**\n * Assemble the durable runtime from already-resolved Agent Bindings.\n * Use `ThreadObject.layer` to compile typed Agent registrations instead.\n * Supply host services through `ThreadObject.make` or `ThreadObject.layerConfig` and\n * the Durable Object context and namespace Layers when composing a custom host.\n */\nconst boundLayer = <E = never, R = never>(\n bindings: ReadonlyArray<ResolvedBinding>,\n options: ThreadPublicationOptions<E, R> = {},\n): Layer.Layer<\n CloudflareDurableRuntimeServices,\n DoStorageInitializationError | MessageDeliveryError | E,\n | DurableObjectContext\n | ThreadObjectNamespace\n | CloudflareBootstrapServices\n | Exclude<R, ThreadStore | SubmissionLedger | SqlClient>\n> =>\n Layer.unwrap(\n Effect.map(DurableObjectContext, ({ ctx }) =>\n sharedLayer(DurableAgentRuntime.layerWithBindings(bindings), options).pipe(\n Layer.provideMerge(SqliteClient.layer({ storage: ctx.storage })),\n ),\n ),\n );\n\n/**\n * Build the application runtime over the existing owner SqlClient and native ports, then\n * assemble its one maintenance coordinator. The application may acquire its Bindings from\n * those ports and expose extra services, including ThreadHostMaintenance. It must not acquire\n * another runtime stack or require ThreadMaintenance while constructing this Layer.\n * Supply layerHostConfig and deterministic placement; dispatch addressed ingress with handleRpc.\n */\nexport function layerInHost<A, E, R, P = never, PE = never, PR = never>(\n application: Layer.Layer<DurableAgentRuntime | A, E, R>,\n options: Omit<ThreadPublicationOptions<PE, PR>, \"projection\"> & {\n readonly projection: Layer.Layer<ThreadProjectionMaintenance | P, PE, PR>;\n },\n): Layer.Layer<\n CloudflareDurableRuntimeServices | A | P,\n Layer.Error<ReturnType<typeof sharedLayer<A, E, R, PE, PR>>>,\n Layer.Services<ReturnType<typeof sharedLayer<A, E, Exclude<R, P>, PE, PR>>>\n>;\n\nexport function layerInHost<A, E, R, PE = never, PR = never>(\n application: Layer.Layer<DurableAgentRuntime | A, E, R>,\n options?: ThreadPublicationOptions<PE, PR>,\n): ReturnType<typeof sharedLayer<A, E, R, PE, PR>>;\n\nexport function layerInHost<A, E, R, PE = never, PR = never>(\n application: Layer.Layer<DurableAgentRuntime | A, E, R>,\n options: ThreadPublicationOptions<PE, PR> = {},\n) {\n return sharedLayer(application, options);\n}\n\ntype HostRuntimeServices = Exclude<\n CloudflareDurableRuntimeServices,\n DurableAgentRuntime | ThreadMaintenance\n>;\n\nconst sharedLayer = <A, E, R, PE = never, PR = never>(\n application: Layer.Layer<DurableAgentRuntime | A, E, R>,\n options: ThreadPublicationOptions<PE, PR> = {},\n): Layer.Layer<\n CloudflareDurableRuntimeServices | A,\n DoStorageInitializationError | MessageDeliveryError | E | PE,\n | DurableObjectContext\n | ThreadObjectNamespace\n | Exclude<CloudflareBootstrapServices, ThreadObjectIdentity>\n | SqlClient\n | Exclude<R, HostRuntimeServices | PreparedInputAdmission>\n | Exclude<PR, ThreadStore | SubmissionLedger | SqlClient>\n> =>\n Layer.unwrap(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n const config = yield* CloudflareDurableRuntimeConfig;\n const { ownsThread } = yield* ThreadObjectPlacement;\n\n const storageOptions: DoStorageOptions = {\n storage: ctx.storage,\n observationPollInterval: config.observationPollInterval,\n ownershipLeaseDuration: config.ownershipLeaseDuration,\n maxStoredValueBytes: config.maxStoredValueBytes,\n verifyOnOpen: config.verifyOnOpen,\n };\n\n const infrastructure = Layer.mergeAll(\n storageConfigLayer(storageOptions),\n Layer.effect(SqlClient)(SqlClient),\n );\n\n // The same local ports serve routed decorators and owner-side RPC execution.\n // The RPC executor must never receive routed ports and bounce requests between Objects.\n const rawLocalPorts = Layer.mergeAll(threadStoreLayer, submissionLedgerLayer).pipe(\n Layer.provide(infrastructure),\n );\n\n const base = Layer.mergeAll(DurableAlarmService.layer, ProgressWaitRegistry.layer);\n const wakes = cloudflareWakeSchedulerLayer.pipe(Layer.provide(base));\n\n const messageStore = guardedMessageDeliveryStoreLayer.pipe(\n Layer.provide(doMessageDeliveryStoreLayer().pipe(Layer.provide(infrastructure))),\n Layer.provide(wakes),\n );\n\n const messageRecovery = threadMessageDeliveryLayer.pipe(\n // Each wave is bounded even at the policy's five-minute attempt ceiling. Source\n // completion stops new waves; remaining rows retain their indexed alarm deadline.\n Layer.provide(MessageDeliveryDriver.layer({ batchSize: 4, concurrency: 4 })),\n Layer.provide(cloudflarePreparedInputAdmissionLayer),\n Layer.provide(CloudflareThreadClient.layer),\n Layer.provide(messageStore),\n Layer.provide(wakes),\n );\n\n const publication = (options.publication ?? ThreadPublication.layer).pipe(\n Layer.provide(Layer.mergeAll(rawLocalPorts, Layer.effect(SqlClient)(SqlClient))),\n );\n\n const projection = (options.projection ?? ThreadProjectionMaintenance.layer).pipe(\n Layer.provide(Layer.mergeAll(rawLocalPorts, Layer.effect(SqlClient)(SqlClient))),\n );\n\n const localPorts =\n options.publication === undefined && options.projection === undefined\n ? rawLocalPorts\n : Layer.effectContext(\n Effect.gen(function* () {\n const store = yield* ThreadStore;\n const ledger = yield* SubmissionLedger;\n const mutations = yield* ThreadMutationGate;\n const index = yield* ThreadProjectionMaintenance;\n const publish = yield* Effect.context<ThreadPublication>();\n const afterCommit = publishCommitted.pipe(Effect.provide(publish));\n // A later append cannot mistake its still-projecting predecessor for old backlog.\n // Publication remains outside this local source/index critical section.\n const sourceCommits = yield* Semaphore.make(1);\n\n // Every runtime-owned producer prearms too: a crash between commit and invalidation\n // leaves a NEW, uncertified generation. Source errors keep their native port types.\n const observedStore = ThreadStore.of({\n ...store,\n append: (request) =>\n mutations\n .withMutation(\n sourceCommits\n .withPermit(\n store\n .append(request)\n .pipe(\n Effect.tap((result) =>\n index\n .applyCommitted(request, result)\n .pipe(\n Effect.catchCause((cause) =>\n Cause.hasInterrupts(cause)\n ? Effect.interrupt\n : Effect.logError(\n \"Thread projection deferred after source commit\",\n cause,\n ),\n ),\n ),\n ),\n ),\n )\n .pipe(Effect.tap(() => afterCommit)),\n )\n .pipe(\n Effect.catchTag(\"DurableAlarmError\", (cause) =>\n ThreadStoreError.make({\n operation: \"prearm publication append\",\n message: cause.message,\n cause,\n }),\n ),\n ),\n });\n\n const observeIntent = <A, Failure>(body: Effect.Effect<A, Failure>) =>\n mutations.withMutation(body.pipe(Effect.tap(() => afterCommit))).pipe(\n Effect.catchTag(\"DurableAlarmError\", (cause) =>\n LedgerError.make({\n operation: \"prearm publication intent\",\n message: \"The publication generation could not be armed\",\n cause,\n }),\n ),\n );\n\n return Context.make(ThreadStore, observedStore).pipe(\n Context.add(SubmissionLedger, {\n ...ledger,\n recordApprovalDecision: (request) =>\n observeIntent(ledger.recordApprovalDecision(request)),\n requestAbort: (request) => observeIntent(ledger.requestAbort(request)),\n recordUnknownResolution: (request) =>\n observeIntent(ledger.recordUnknownResolution(request)),\n }),\n );\n }),\n ).pipe(Layer.provide(rawLocalPorts));\n\n const portsEndpointLayer = Layer.effect(ThreadObjectPorts)(\n Effect.gen(function* () {\n const local = yield* Effect.context<SubmissionLedger | ThreadStore>();\n const ledger = Context.get(local, SubmissionLedger);\n\n return ThreadObjectPorts.of({\n handle: (request) => executePortRequest(request).pipe(Effect.provide(local)),\n lookupSubmission: (submissionId) =>\n ledger.lookup(SubmissionLookupById.make({ submissionId })),\n });\n }),\n ).pipe(Layer.provide(localPorts));\n\n const routedPorts = Layer.mergeAll(\n routedSubmissionLedgerLayer({ ownsThread }),\n routedThreadStoreLayer({ ownsThread }),\n ).pipe(Layer.provide(localPorts), Layer.provide(threadPortTransportLayer));\n\n const runtimeStack = application.pipe(\n Layer.provide(\n cloudflarePreparedInputAdmissionLayer.pipe(Layer.provide(CloudflareThreadClient.layer)),\n ),\n Layer.provideMerge(messageStore),\n Layer.provideMerge(routedPorts),\n Layer.provideMerge(wakes),\n Layer.provideMerge(base),\n Layer.provideMerge(portsEndpointLayer),\n );\n\n return Layer.mergeAll(\n runtimeStack,\n ThreadMaintenance.layer.pipe(Layer.provide(runtimeStack), Layer.provide(messageRecovery)),\n portsEndpointLayer,\n messageStore,\n messageRecovery,\n ).pipe(\n Layer.provideMerge(publication),\n Layer.provideMerge(projection),\n Layer.provideMerge(ThreadMutationGate.layer),\n Layer.provideMerge(infrastructure),\n );\n }),\n );\n","import {\n decodePortRequest,\n encodePortResponse,\n LedgerLookupResult,\n PortFailed,\n PortProtocolError,\n PortSucceeded,\n type PortRequest,\n type PortResponse,\n} from \"@effect-agent/storage-cloudflare/port-protocol\";\nimport { Effect, Layer, Option, Schema, Stream } from \"effect\";\nimport {\n IntegrityReport,\n ObligationReport,\n ObligationThresholds,\n RecoveryExplanation,\n RetryCommand,\n RetryRefused,\n} from \"effect-agent/admin\";\nimport { DigestError } from \"effect-agent/digest\";\nimport {\n DurableAgentRuntime,\n DurableRuntimeConfig,\n RecoveryReport,\n type DurableSubmitAgent,\n} from \"effect-agent/durable-agent-runtime\";\nimport { DurableRuntimeFailpointError } from \"effect-agent/durable-failpoint\";\nimport { type AgentId, type ThreadId } from \"effect-agent/identifiers\";\nimport { SubmissionId } from \"effect-agent/identifiers\";\nimport {\n OperationAuthorizationRequest,\n OperationAuthorizer,\n OperationDenied,\n} from \"effect-agent/operation-authorizer\";\nimport { PersistedJson } from \"effect-agent/records\";\nimport { RunJournalError } from \"effect-agent/run-journal\";\nimport {\n AdmissionPolicyError,\n LedgerError,\n OwnershipLost,\n SettlementConflict,\n SubmissionLedger,\n SubmissionLookupByKey,\n} from \"effect-agent/submission-ledger\";\nimport {\n AppendConflict,\n ThreadNotMaterialized,\n ThreadRead,\n ThreadStore,\n ThreadStoreError,\n FenceRejected,\n} from \"effect-agent/thread-store\";\nimport { WakeScheduler } from \"effect-agent/wake-scheduler\";\nimport {\n DurableObject as EffectCfDurableObject,\n DurableObjectState as EffectCfDurableObjectState,\n WorkerEnvironment,\n} from \"effect-cf\";\n\nimport {\n ThreadMaintenance,\n DurableAlarmError,\n DurableAlarmService,\n ThreadMutationGate,\n publishCommitted,\n type MaintenancePassFailure,\n} from \"./Alarm.ts\";\nimport {\n ThreadObjectIdentity,\n ThreadObjectPlacement,\n DurableObjectContext,\n ThreadObjectNamespace,\n threadNamespaceFromEnv,\n type CloudflareBindingError,\n} from \"./CloudflareBindings.ts\";\nimport { AdmissionLimitExceeded, CloudflareDurableRuntimeConfig } from \"./CloudflareConfig.ts\";\nimport {\n AbortRecorded,\n ApprovalRecorded,\n HostFailed,\n HostProtocolError,\n ObservedPage,\n ProgressObserved,\n ProgressCancelled,\n SettlementReached,\n SubmissionStatusResponse,\n SubmitSucceeded,\n UnknownResolutionRecorded,\n boundHostDiagnostic,\n decodeAbortCommand,\n decodeAwaitProgressRequest,\n decodeCancelProgressRequest,\n decodeApprovalDecisionCommand,\n decodeObservePageRequest,\n decodeReceipt,\n decodeSubmitRequest,\n decodeUnknownResolutionCommand,\n encodeHostResponse,\n type HostFailure,\n type HostResponse,\n type SubmitRequest,\n} from \"./CloudflareThreadClient.ts\";\nimport {\n layerConfig,\n ThreadObjectPorts,\n type CloudflareDurableRuntimeInitializationError,\n type CloudflareDurableRuntimeOptions,\n type CloudflareDurableRuntimeServices,\n type CloudflareBootstrapServices,\n} from \"./internal/layers.ts\";\nimport { ProgressWaitRegistry } from \"./internal/progress-wait.ts\";\n\nexport {\n layer,\n layerConfig,\n layerHostConfig,\n layerInHost,\n ThreadObjectPorts,\n type ThreadPublicationOptions as PublicationOptions,\n type CloudflareDurableRuntimeOptions as RuntimeOptions,\n type CloudflareDurableRuntimeServices as Services,\n type CloudflareDurableRuntimeInitializationError as InitializationError,\n type CloudflareBootstrapServices as BootstrapServices,\n} from \"./internal/layers.ts\";\n\n/**\n * `ThreadObject.make(application, options)` — the Thread Durable Object\n * (plan §1.4,\n * D-P6-1): a factory returning a class that applications export from their Worker entry.\n * One SQLite-backed Object per Thread is the serialized owner (durability §6); the\n * Object never runs `runResolvedWorker`'s infinite loop — each ingress event or alarm runs\n * ONE bounded `runRecovery` + `processThreadHead` pass, and the persisted alarm\n * (the single multiplexed slot, D-P6-2) finishes accepted work across evictions WITHOUT any\n * incoming request.\n * `Services` exposes the same owner `SqlClient` used by the Thread stores. Compose optional\n * local repositories after `ThreadObject.layer`; never acquire another independently locked\n * SQL client for the same Object. Exposing the client installs no additional storage schemas.\n *\n * Constructor gate (`blockConcurrencyWhile`) is LOCAL-ONLY: schema migration and the\n * exact-version check, configuration decode, and the defensive ensure-alarm half of the\n * alarm invariant. It deliberately does NOT run the recovery pass: parent recovery can\n * require child-Object reads and vice versa, and two Objects blocked in constructor gates\n * awaiting each other's RPC would deadlock (plan §1.4). Instead every pass runs\n * `runRecovery` BEFORE any claim, so reconciliation still strictly precedes new work.\n */\n\n/** Construction options for one deployed Thread Object class. */\nexport interface Options<\n ApplicationServices = never,\n EventServices = never,\n EventLayerError = never,\n> extends CloudflareDurableRuntimeOptions {\n /** Accept transient native RPC tracing through effect-cf; disabled by default. */\n readonly rpcTracing?: boolean;\n /**\n * Name of the Worker `env` binding carrying THIS class's `DurableObjectNamespace` — the\n * Object's route back to sibling Thread Objects for the WP2 cross-Object port calls\n * and remote wakes (DEPLOY-010: the binding enters through a Layer, never ambiently).\n */\n readonly namespaceBinding: string;\n /** Acquired and finalized per native event, with access to the complete application runtime. */\n readonly eventLayer?: Layer.Layer<\n EventServices,\n EventLayerError,\n | RuntimeServices\n | ApplicationServices\n | EffectCfDurableObjectState.DurableObjectState\n | WorkerEnvironment\n >;\n}\n\ntype EndpointServices =\n | CloudflareDurableRuntimeServices\n | CloudflareBootstrapServices\n | DurableObjectContext;\ntype RuntimeServices = EndpointServices | ThreadObjectNamespace;\ntype ThreadObjectInitializationError =\n | CloudflareDurableRuntimeInitializationError\n | CloudflareBindingError\n | MaintenancePassFailure;\n\n/** Classify only a decoded port request so new protocol members cannot bypass pre-arming. */\nconst isMutatingPortRequest = (request: PortRequest): boolean => {\n switch (request._tag) {\n case \"LedgerAdmit\":\n case \"LedgerMarkReady\":\n case \"LedgerRequestAbort\":\n case \"LedgerRecordChildSettled\":\n case \"StoreMaterialize\":\n case \"StoreAppend\":\n return true;\n case \"LedgerLookup\":\n case \"LedgerResolveAdmission\":\n case \"StoreReadPage\":\n case \"StoreInspectTail\":\n case \"StoreExport\":\n return false;\n }\n request satisfies never;\n\n return false;\n};\n\n/** The literal encoded `PortFailed(PortProtocolError)` fallback (same shape as WP2's). */\nconst encodedPortProtocolFailure = (message: string): unknown => ({\n _tag: \"PortFailed\",\n failure: { _tag: \"PortProtocolError\", message: boundHostDiagnostic(message) },\n});\n\nconst protocolFailure = (context: string) => (error: { readonly message: string }) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`${context}: ${error.message}`),\n });\n\n/** Fold one endpoint's typed failures into the uniform `HostResponse` envelope. */\nconst respond = <Result extends HostResponse, Failure extends HostFailure>(\n effect: Effect.Effect<Result, Failure, EndpointServices>,\n): Effect.Effect<HostResponse, never, EndpointServices> =>\n effect.pipe(\n Effect.map((result): HostResponse => result),\n Effect.catch((failure) => Effect.succeed<HostResponse>(HostFailed.make({ failure }))),\n );\n\n/** Encode the response envelope; an unencodable response degrades to a protocol failure. */\nconst encodeResponse = (response: HostResponse): Effect.Effect<unknown> =>\n encodeHostResponse(response).pipe(\n Effect.catch((error) =>\n Effect.succeed<unknown>({\n _tag: \"HostFailed\",\n failure: {\n _tag: \"HostProtocolError\",\n message: boundHostDiagnostic(`The host response could not be encoded: ${error.message}`),\n },\n }),\n ),\n );\n\nconst utf8Bytes = (value: PersistedJson): number =>\n new TextEncoder().encode(JSON.stringify(value)).length;\n\n/**\n * The admission-limits gate, BEFORE `runtime.submit` touches the ledger (exit gate\n * \"resource limits are checked before admission\"; DEPLOY-007). A replayed idempotency key is\n * exempt: its accepted-work obligation already exists, and returning the original Receipt\n * consumes no new quota. Refusals are typed `AdmissionLimitExceeded` and nothing is written.\n */\nconst gateAdmissionLimits = Effect.fn(\"ThreadObject.gateAdmissionLimits\")(function* (\n threadId: ThreadId,\n request: {\n readonly principal: SubmissionLookupByKey[\"principal\"];\n readonly idempotencyKey: SubmissionLookupByKey[\"idempotencyKey\"];\n readonly inputPayload: PersistedJson;\n },\n) {\n const config = yield* CloudflareDurableRuntimeConfig;\n const ledger = yield* SubmissionLedger;\n const { ctx } = yield* DurableObjectContext;\n\n const existing = yield* ledger.lookup(\n SubmissionLookupByKey.make({\n threadId,\n principal: request.principal,\n idempotencyKey: request.idempotencyKey,\n }),\n );\n\n if (Option.isSome(existing)) return;\n\n const inputBytes = utf8Bytes(request.inputPayload);\n\n if (inputBytes > config.limits.maxInputBytes) {\n return yield* AdmissionLimitExceeded.make({\n limit: \"input-bytes\",\n actual: inputBytes,\n maximum: config.limits.maxInputBytes,\n });\n }\n\n const nonterminal = yield* ledger.scanNonterminal.pipe(\n Stream.filter((submission) => submission.threadId === threadId),\n Stream.runCollect,\n );\n\n if (nonterminal.length >= config.limits.maxQueueDepthPerLane) {\n return yield* AdmissionLimitExceeded.make({\n limit: \"queue-depth\",\n actual: nonterminal.length,\n maximum: config.limits.maxQueueDepthPerLane,\n });\n }\n\n const databaseBytes = yield* Effect.sync(() => ctx.storage.sql.databaseSize);\n\n if (databaseBytes > config.limits.maxDatabaseBytes) {\n return yield* AdmissionLimitExceeded.make({\n limit: \"database-bytes\",\n actual: databaseBytes,\n maximum: config.limits.maxDatabaseBytes,\n });\n }\n});\n\n/**\n * The submit-capable projection of an Agent Binding on the OBJECT side: the input arrived\n * already encoded through the real input schema on the Worker side (`client.ts`), so the\n * Object admits the canonical `PersistedJson` payload as-is; the resolved Binding re-derives\n * everything else from the stored `(agentId, agentDigests)` at claim time (SUB-023).\n */\nconst passthroughSubmitAgent = (agentId: AgentId): DurableSubmitAgent<typeof PersistedJson> => ({\n definition: {\n id: agentId,\n input: PersistedJson,\n },\n});\n\n/** A physical owner may hold other Threads; an addressed request cannot act on their IDs. */\nconst lookupAddressedSubmission = Effect.fn(\"ThreadObject.lookupAddressedSubmission\")(function* (\n submissionId: SubmissionId,\n) {\n const { threadId } = yield* ThreadObjectIdentity;\n const ports = yield* ThreadObjectPorts;\n const submission = yield* ports.lookupSubmission(submissionId);\n\n if (Option.isSome(submission) && submission.value.threadId !== threadId)\n return yield* HostProtocolError.make({ message: \"The Submission belongs to another Thread\" });\n\n return submission;\n});\n\nconst requireSubmissionThread = Effect.fn(\"ThreadObject.requireSubmissionThread\")(function* (\n submissionId: SubmissionId,\n) {\n const submission = yield* lookupAddressedSubmission(submissionId);\n\n if (Option.isNone(submission))\n return yield* LedgerError.make({\n operation: \"addressed Submission lookup\",\n message: \"The addressed Thread has no such Submission\",\n });\n});\n\nconst requireReceiptThread = Effect.fn(\"ThreadObject.requireReceiptThread\")(function* (\n threadId: ThreadId,\n) {\n const identity = yield* ThreadObjectIdentity;\n\n if (threadId !== identity.threadId)\n return yield* HostProtocolError.make({ message: \"The Receipt belongs to another Thread\" });\n});\n\nconst requirePortThread = (request: PortRequest) => {\n switch (request._tag) {\n case \"LedgerLookup\":\n return request.request._tag === \"SubmissionLookupById\"\n ? lookupAddressedSubmission(request.request.submissionId).pipe(Effect.asVoid)\n : requireReceiptThread(request.request.threadId);\n case \"LedgerMarkReady\":\n case \"LedgerRequestAbort\":\n return requireSubmissionThread(request.request.submissionId);\n case \"LedgerRecordChildSettled\":\n return requireSubmissionThread(request.request.parentSubmissionId);\n case \"LedgerAdmit\":\n case \"LedgerResolveAdmission\":\n case \"StoreMaterialize\":\n case \"StoreAppend\":\n case \"StoreReadPage\":\n case \"StoreInspectTail\":\n case \"StoreExport\":\n return requireReceiptThread(request.request.threadId);\n }\n request satisfies never;\n};\n\n/**\n * Admit an already Schema-decoded request to a logical Thread in this physical owner.\n * Custom hosts validate local placement before calling this Effect and provide their same\n * runtime/maintenance instances. The native endpoint uses this path too: queue limits,\n * idempotent receipts and the pre-admission generation/alarm commit have one owner.\n */\nexport const submit = Effect.fn(\"ThreadObject.submit\")(function* (\n threadId: ThreadId,\n request: SubmitRequest,\n) {\n const placement = yield* ThreadObjectPlacement;\n\n if (!placement.ownsThread(threadId))\n return yield* HostProtocolError.make({ message: \"The Thread belongs to another Object\" });\n const mutations = yield* ThreadMutationGate;\n const runtime = yield* DurableAgentRuntime;\n\n yield* gateAdmissionLimits(threadId, request);\n\n return yield* mutations.withMutation(\n runtime\n .submit(passthroughSubmitAgent(request.agentId), request.inputPayload, {\n threadId,\n principal: request.principal,\n idempotencyKey: request.idempotencyKey,\n ...(request.admissionGroup === undefined ? {} : { admissionGroup: request.admissionGroup }),\n ...(request.admissionFence === undefined ? {} : { admissionFence: request.admissionFence }),\n ...(request.workerAdmission === undefined\n ? {}\n : { workerAdmission: request.workerAdmission }),\n ...(request.messageAdmission === undefined\n ? {}\n : { messageAdmission: request.messageAdmission }),\n definitions: request.definitions,\n })\n .pipe(Effect.tap(() => publishCommitted)),\n );\n});\n\nconst submitEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n decodeSubmitRequest(encoded).pipe(\n Effect.mapError(protocolFailure(\"The submit request could not be decoded\")),\n Effect.flatMap((request) =>\n Effect.gen(function* () {\n const identity = yield* ThreadObjectIdentity;\n const receipt = yield* submit(identity.threadId, request);\n\n return SubmitSucceeded.make({ receipt });\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\nconst submissionStatusEndpoint = (\n encoded: unknown,\n): Effect.Effect<unknown, never, EndpointServices> =>\n decodeReceipt(encoded).pipe(\n Effect.mapError(protocolFailure(\"The receipt could not be decoded\")),\n Effect.flatMap((receipt) =>\n Effect.gen(function* () {\n const authorizer = yield* OperationAuthorizer;\n\n yield* authorizer.authorize(\n OperationAuthorizationRequest.make({\n operation: \"awaitSettlement\",\n threadId: receipt.threadId,\n submissionId: receipt.submissionId,\n }),\n );\n yield* requireReceiptThread(receipt.threadId);\n yield* requireSubmissionThread(receipt.submissionId);\n const runtime = yield* DurableAgentRuntime;\n\n return SubmissionStatusResponse.make({ status: yield* runtime.submissionStatus(receipt) });\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\nconst awaitSettlementEndpoint = (\n encoded: unknown,\n): Effect.Effect<unknown, never, EndpointServices> =>\n decodeReceipt(encoded).pipe(\n Effect.mapError(protocolFailure(\"The receipt could not be decoded\")),\n Effect.flatMap((receipt) =>\n Effect.gen(function* () {\n const authorizer = yield* OperationAuthorizer;\n\n yield* authorizer.authorize(\n OperationAuthorizationRequest.make({\n operation: \"awaitSettlement\",\n threadId: receipt.threadId,\n submissionId: receipt.submissionId,\n }),\n );\n yield* requireReceiptThread(receipt.threadId);\n yield* requireSubmissionThread(receipt.submissionId);\n const runtime = yield* DurableAgentRuntime;\n const settlement = yield* runtime.awaitSettlement(receipt);\n\n return SettlementReached.make({ settlement });\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\nconst awaitProgressEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n decodeAwaitProgressRequest(encoded).pipe(\n Effect.mapError(protocolFailure(\"The progress request could not be decoded\")),\n Effect.flatMap((request) =>\n Effect.gen(function* () {\n const identity = yield* ThreadObjectIdentity;\n const runtime = yield* DurableAgentRuntime;\n const registry = yield* ProgressWaitRegistry;\n\n yield* Effect.scoped(\n Effect.gen(function* () {\n const cancelled = yield* registry.subscribe(\n JSON.stringify([identity.threadId, request.waiterId]),\n );\n\n yield* Effect.raceFirst(\n runtime.awaitProgress(identity.threadId, request.afterSequence),\n cancelled,\n );\n }),\n );\n\n return ProgressObserved.make();\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\nconst cancelProgressEndpoint = (\n encoded: unknown,\n): Effect.Effect<unknown, never, EndpointServices> =>\n decodeCancelProgressRequest(encoded).pipe(\n Effect.mapError(protocolFailure(\"The progress cancellation could not be decoded\")),\n Effect.flatMap((request) =>\n Effect.gen(function* () {\n const identity = yield* ThreadObjectIdentity;\n const registry = yield* ProgressWaitRegistry;\n\n yield* registry.cancel(JSON.stringify([identity.threadId, request.waiterId]));\n\n return ProgressCancelled.make();\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\nconst observePageEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n decodeObservePageRequest(encoded).pipe(\n Effect.mapError(protocolFailure(\"The observe request could not be decoded\")),\n Effect.flatMap((request) =>\n Effect.gen(function* () {\n const identity = yield* ThreadObjectIdentity;\n const store = yield* ThreadStore;\n // The same fail-closed authorization seam the runtime's `observe` consults (P7 WP1);\n // the default reference preserves the possession behavior.\n const authorizer = yield* OperationAuthorizer;\n\n yield* authorizer.authorize(\n OperationAuthorizationRequest.make({\n operation: \"observe\",\n threadId: identity.threadId,\n }),\n );\n\n const records = yield* Stream.runCollect(\n store.read(\n ThreadRead.make({\n threadId: identity.threadId,\n ...(request.afterSequence === undefined\n ? {}\n : { afterSequence: request.afterSequence }),\n limit: request.limit,\n }),\n ),\n );\n\n return ObservedPage.make({ records: [...records] });\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\nconst abortEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n decodeAbortCommand(encoded).pipe(\n Effect.mapError(protocolFailure(\"The abort command could not be decoded\")),\n Effect.flatMap((command) =>\n Effect.gen(function* () {\n const authorizer = yield* OperationAuthorizer;\n\n yield* authorizer.authorize(\n OperationAuthorizationRequest.make({\n operation: \"abort\",\n submissionId: command.submissionId,\n }),\n );\n yield* requireSubmissionThread(command.submissionId);\n const maintenance = yield* ThreadMaintenance;\n const runtime = yield* DurableAgentRuntime;\n const intent = yield* maintenance.withMutation(runtime.abort(command));\n\n return AbortRecorded.make({ intent });\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\nconst resolveApprovalEndpoint = (\n encoded: unknown,\n): Effect.Effect<unknown, never, EndpointServices> =>\n decodeApprovalDecisionCommand(encoded).pipe(\n Effect.mapError(protocolFailure(\"The approval command could not be decoded\")),\n Effect.flatMap((command) =>\n Effect.gen(function* () {\n const authorizer = yield* OperationAuthorizer;\n\n yield* authorizer.authorize(\n OperationAuthorizationRequest.make({\n operation: \"resolveApproval\",\n submissionId: command.submissionId,\n }),\n );\n yield* requireSubmissionThread(command.submissionId);\n const maintenance = yield* ThreadMaintenance;\n const runtime = yield* DurableAgentRuntime;\n const intent = yield* maintenance.withMutation(runtime.resolveApproval(command));\n\n return ApprovalRecorded.make({ intent });\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\nconst resolveUnknownEndpoint = (\n encoded: unknown,\n): Effect.Effect<unknown, never, EndpointServices> =>\n decodeUnknownResolutionCommand(encoded).pipe(\n Effect.mapError(protocolFailure(\"The resolution command could not be decoded\")),\n Effect.flatMap((command) =>\n Effect.gen(function* () {\n const authorizer = yield* OperationAuthorizer;\n\n yield* authorizer.authorize(\n OperationAuthorizationRequest.make({\n operation: \"resolveUnknown\",\n submissionId: command.submissionId,\n }),\n );\n yield* requireSubmissionThread(command.submissionId);\n const maintenance = yield* ThreadMaintenance;\n const runtime = yield* DurableAgentRuntime;\n const intent = yield* maintenance.withMutation(runtime.resolveUnknown(command));\n\n return UnknownResolutionRecorded.make({ intent });\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\n// ---------------------------------------------------------------------------\n// P7 administrative entry points (plan §3): explain/verify/retry/obligations over the SAME\n// envelope discipline as the host protocol — closed request/response Schema unions, typed\n// failures that re-decode to identical tags, protocol anomalies answered typed. The envelopes\n// live here (not `client.ts`) because no Worker-side client consumption exists yet; `wake`\n// already exists as the `wake()` entry point.\n// ---------------------------------------------------------------------------\n\n/** Explain one Submission (`submissionId` present) or every nonterminal lane member. */\nexport class AdminExplainRequest extends Schema.Class<AdminExplainRequest>(\n \"@effect-agent/platform-cloudflare/AdminExplainRequest\",\n)({\n submissionId: Schema.optionalKey(SubmissionId),\n}) {}\n\n/** Verify carries no parameters — the addressed Object IS the lane. */\nexport class AdminVerifyRequest extends Schema.Class<AdminVerifyRequest>(\n \"@effect-agent/platform-cloudflare/AdminVerifyRequest\",\n)({}) {}\n\n/** Every typed failure of the four admin entry points, plus the protocol's own errors. */\nexport const AdminFailure = Schema.Union([\n AdmissionPolicyError,\n OperationDenied,\n RetryRefused,\n LedgerError,\n RunJournalError,\n DigestError,\n OwnershipLost,\n SettlementConflict,\n ThreadStoreError,\n ThreadNotMaterialized,\n AppendConflict,\n FenceRejected,\n DurableRuntimeFailpointError,\n DurableAlarmError,\n HostProtocolError,\n]);\n\nexport type AdminFailure = typeof AdminFailure.Type;\n\nexport class ExplainedRecovery extends Schema.TaggedClass<ExplainedRecovery>(\n \"@effect-agent/platform-cloudflare/ExplainedRecovery\",\n)(\"ExplainedRecovery\", {\n explanations: Schema.Array(RecoveryExplanation).check(Schema.isMaxLength(1_024)),\n}) {}\n\nexport class VerifiedIntegrity extends Schema.TaggedClass<VerifiedIntegrity>(\n \"@effect-agent/platform-cloudflare/VerifiedIntegrity\",\n)(\"VerifiedIntegrity\", {\n report: IntegrityReport,\n}) {}\n\nexport class RetryExecuted extends Schema.TaggedClass<RetryExecuted>(\n \"@effect-agent/platform-cloudflare/RetryExecuted\",\n)(\"RetryExecuted\", {\n report: RecoveryReport,\n}) {}\n\nexport class ObligationsScanned extends Schema.TaggedClass<ObligationsScanned>(\n \"@effect-agent/platform-cloudflare/ObligationsScanned\",\n)(\"ObligationsScanned\", {\n report: ObligationReport,\n}) {}\n\n/** The admin entry point failed TYPED on the Object; the failure re-decodes verbatim. */\nexport class AdminFailed extends Schema.TaggedClass<AdminFailed>(\n \"@effect-agent/platform-cloudflare/AdminFailed\",\n)(\"AdminFailed\", {\n failure: AdminFailure,\n}) {}\n\n/** The uniform answer of one admin entry point. Callers narrow by the tag their call implies. */\nexport const AdminResponse = Schema.Union([\n ExplainedRecovery,\n VerifiedIntegrity,\n RetryExecuted,\n ObligationsScanned,\n AdminFailed,\n]);\n\nexport type AdminResponse = typeof AdminResponse.Type;\n\nexport const decodeAdminExplainRequest = Schema.decodeUnknownEffect(AdminExplainRequest);\nexport const decodeAdminVerifyRequest = Schema.decodeUnknownEffect(AdminVerifyRequest);\nexport const decodeRetryCommand = Schema.decodeUnknownEffect(RetryCommand);\nexport const decodeObligationThresholds = Schema.decodeUnknownEffect(ObligationThresholds);\nexport const encodeAdminResponse = Schema.encodeEffect(AdminResponse);\nexport const decodeAdminResponse = Schema.decodeUnknownEffect(AdminResponse);\n\n/** Fold one admin endpoint's typed failures into the uniform `AdminResponse` envelope. */\nconst respondAdmin = <Result extends AdminResponse, Failure extends AdminFailure>(\n effect: Effect.Effect<Result, Failure, EndpointServices>,\n): Effect.Effect<AdminResponse, never, EndpointServices> =>\n effect.pipe(\n Effect.map((result): AdminResponse => result),\n Effect.catch((failure) => Effect.succeed<AdminResponse>(AdminFailed.make({ failure }))),\n );\n\n/** Encode the admin response envelope; an unencodable response degrades to a protocol failure. */\nconst encodeAdminResponseTotal = (response: AdminResponse): Effect.Effect<unknown> =>\n encodeAdminResponse(response).pipe(\n Effect.catch((error) =>\n Effect.succeed<unknown>({\n _tag: \"AdminFailed\",\n failure: {\n _tag: \"HostProtocolError\",\n message: boundHostDiagnostic(`The admin response could not be encoded: ${error.message}`),\n },\n }),\n ),\n );\n\nconst explainEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n decodeAdminExplainRequest(encoded).pipe(\n Effect.mapError(protocolFailure(\"The explain request could not be decoded\")),\n Effect.flatMap((request) =>\n Effect.gen(function* () {\n const identity = yield* ThreadObjectIdentity;\n const runtime = yield* DurableAgentRuntime;\n\n const explanations =\n request.submissionId === undefined\n ? yield* runtime.explainThread(identity.threadId)\n : [yield* runtime.explain(request.submissionId)];\n\n return ExplainedRecovery.make({ explanations });\n }),\n ),\n respondAdmin,\n Effect.flatMap(encodeAdminResponseTotal),\n );\n\nconst verifyEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n decodeAdminVerifyRequest(encoded).pipe(\n Effect.mapError(protocolFailure(\"The verify request could not be decoded\")),\n Effect.flatMap(() =>\n Effect.gen(function* () {\n const identity = yield* ThreadObjectIdentity;\n const runtime = yield* DurableAgentRuntime;\n const report = yield* runtime.verify(identity.threadId);\n\n return VerifiedIntegrity.make({ report });\n }),\n ),\n respondAdmin,\n Effect.flatMap(encodeAdminResponseTotal),\n );\n\nconst retryEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n decodeRetryCommand(encoded).pipe(\n Effect.mapError(protocolFailure(\"The retry command could not be decoded\")),\n Effect.flatMap((command) =>\n Effect.gen(function* () {\n const maintenance = yield* ThreadMaintenance;\n const runtime = yield* DurableAgentRuntime;\n // Retry may repair durable state, so its generation + alarm commit before the mutation.\n const report = yield* maintenance.withMutation(runtime.retry(command));\n\n return RetryExecuted.make({ report });\n }),\n ),\n respondAdmin,\n Effect.flatMap(encodeAdminResponseTotal),\n );\n\nconst obligationsEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n decodeObligationThresholds(encoded).pipe(\n Effect.mapError(protocolFailure(\"The obligation thresholds could not be decoded\")),\n Effect.flatMap((thresholds) =>\n Effect.gen(function* () {\n const runtime = yield* DurableAgentRuntime;\n const report = yield* runtime.scanObligations(thresholds);\n\n return ObligationsScanned.make({ report });\n }),\n ),\n respondAdmin,\n Effect.flatMap(encodeAdminResponseTotal),\n );\n\n/**\n * Owner-side `portCall`: wrap a mutating envelope in the same pre-armed generation protocol as\n * public RPC (a routed mutation committed by THIS Object must already carry the alarm that will\n * finish it), execute on the LOCAL facets (never the routed decorators), then arm an immediate\n * alarm so the mutated lane is processed promptly. Protocol anomalies answer\n * `PortFailed(PortProtocolError)`.\n */\nconst encodePortResponseTotal = (response: PortResponse) =>\n encodePortResponse(response).pipe(\n Effect.catch((error) =>\n Effect.succeed(\n encodedPortProtocolFailure(`The port response could not be encoded: ${error.message}`),\n ),\n ),\n );\n\nconst portGuardFailure = (failure: LedgerError | HostProtocolError): PortFailed =>\n PortFailed.make({\n failure:\n failure._tag === \"LedgerError\"\n ? failure\n : PortProtocolError.make({ message: \"The port request is not for the addressed Thread\" }),\n });\n\nexport const portCall = (\n encoded: unknown,\n): Effect.Effect<\n unknown,\n never,\n ThreadObjectPorts | ThreadMaintenance | DurableAlarmService | ThreadObjectIdentity\n> =>\n Effect.gen(function* () {\n const ports = yield* ThreadObjectPorts;\n const maintenance = yield* ThreadMaintenance;\n const alarm = yield* DurableAlarmService;\n\n const decoded = yield* decodePortRequest(encoded).pipe(\n Effect.map((request) => ({ _tag: \"success\" as const, request })),\n Effect.catch((error) => Effect.succeed({ _tag: \"failure\" as const, message: error.message })),\n );\n\n if (decoded._tag === \"failure\") {\n return encodedPortProtocolFailure(\n `The port request could not be decoded: ${decoded.message}`,\n );\n }\n if (\n decoded.request._tag === \"LedgerLookup\" &&\n decoded.request.request._tag === \"SubmissionLookupById\"\n ) {\n const response = yield* lookupAddressedSubmission(decoded.request.request.submissionId).pipe(\n Effect.map((submission) =>\n PortSucceeded.make({\n result: LedgerLookupResult.make(\n Option.isSome(submission) ? { submission: submission.value } : {},\n ),\n }),\n ),\n Effect.catch((failure) => Effect.succeed(portGuardFailure(failure))),\n );\n\n return yield* encodePortResponseTotal(response);\n }\n const identityCheck = yield* requirePortThread(decoded.request).pipe(Effect.result);\n\n if (identityCheck._tag === \"Failure\")\n return yield* encodePortResponseTotal(portGuardFailure(identityCheck.failure));\n const mutating = isMutatingPortRequest(decoded.request);\n\n const handled = yield* (\n mutating\n ? maintenance.withMutation(ports.handle(decoded.request))\n : ports.handle(decoded.request)\n ).pipe(Effect.exit);\n\n if (handled._tag === \"Failure\") {\n // Without the committed generation/alarm the invariant cannot be promised; refuse before\n // the port mutation runs. `ports.handle` itself is total, so this is the maintenance error.\n return encodedPortProtocolFailure(\n \"The owner Object could not arm its maintenance alarm before the mutation.\",\n );\n }\n\n const response = yield* encodePortResponseTotal(handled.value);\n\n if (mutating) {\n // Prompt processing hint; the pre-armed alarm already guarantees convergence.\n yield* alarm.scheduleNow.pipe(\n Effect.catch((error) =>\n Effect.logWarning(\"ThreadObject.portCall: immediate re-arm failed\", error),\n ),\n );\n }\n\n return response;\n });\n\nconst wakeEndpoint: Effect.Effect<void, never, EndpointServices> = Effect.gen(function* () {\n const identity = yield* ThreadObjectIdentity;\n const wake = yield* WakeScheduler;\n\n // Route the remote hint through this incarnation's scheduler so scoped progress waiters and\n // the alarm receive the same hint. Delivery remains droppable; canonical storage is authority.\n yield* wake.notify(identity.threadId);\n});\n\n/** The per-Thread wire operations supported by native and application-owned endpoints. */\nexport const ThreadRpcOperation = Schema.Literals([\n \"submitEncoded\",\n \"submissionStatusEncoded\",\n \"awaitSettlementEncoded\",\n \"awaitProgressEncoded\",\n \"cancelProgressEncoded\",\n \"observePage\",\n \"abortEncoded\",\n \"resolveApprovalEncoded\",\n \"resolveUnknownEncoded\",\n \"portCall\",\n \"wake\",\n]);\n\nexport type ThreadRpcOperation = typeof ThreadRpcOperation.Type;\n\nconst threadRpc = {\n submitEncoded: submitEndpoint,\n submissionStatusEncoded: submissionStatusEndpoint,\n awaitSettlementEncoded: awaitSettlementEndpoint,\n awaitProgressEncoded: awaitProgressEndpoint,\n cancelProgressEncoded: cancelProgressEndpoint,\n observePage: observePageEndpoint,\n abortEncoded: abortEndpoint,\n resolveApprovalEncoded: resolveApprovalEndpoint,\n resolveUnknownEncoded: resolveUnknownEndpoint,\n portCall,\n wake: () => wakeEndpoint,\n} satisfies Record<\n ThreadRpcOperation,\n (encoded: unknown) => Effect.Effect<unknown, never, EndpointServices>\n>;\n\n/**\n * Bind an addressed request to its logical Thread while sharing one physical runtime. This\n * validates local placement before invoking the same native handlers. Receipts, Submission\n * commands and port envelopes must match this identity; progress cancellation is Thread-scoped.\n * The producer comes from the actual runtime configuration, never from caller input. These\n * guards supplement the existing current model/Tool and operation authorization policies.\n */\nexport const handleRpc = Effect.fn(\"ThreadObject.handleRpc\")(function* (\n threadId: ThreadId,\n operation: ThreadRpcOperation,\n encoded: unknown,\n) {\n const placement = yield* ThreadObjectPlacement;\n\n if (!placement.ownsThread(threadId))\n return yield* HostProtocolError.make({ message: \"The Thread belongs to another Object\" });\n const { producerId } = yield* DurableRuntimeConfig;\n\n return yield* threadRpc[operation](encoded).pipe(\n Effect.provideService(ThreadObjectIdentity, { threadId, producerId }),\n );\n});\n\nconst alarmEndpoint: Effect.Effect<void, MaintenancePassFailure, EndpointServices> = Effect.gen(\n function* () {\n const maintenance = yield* ThreadMaintenance;\n\n // Typed pass failures propagate: the rejected promise makes workerd retry the alarm\n // (at-least-once delivery), and the dirty generation retains a committed slot meanwhile.\n yield* maintenance.pass;\n },\n);\n\nconst gateEndpoint: Effect.Effect<void, MaintenancePassFailure, EndpointServices> = Effect.gen(\n function* () {\n // Forcing ThreadMaintenance forces the whole Layer stack: migration + exact-version\n // check + configuration decode (DEPLOY-008 fails typed here, before any mutation), then\n // the defensive local ensure-alarm half of the invariant. LOCAL-ONLY by construction.\n const maintenance = yield* ThreadMaintenance;\n\n yield* maintenance.ensureAlarm;\n },\n);\n\n/**\n * Adapter from effect-cf's native Durable Object services to Effect Agent's existing platform\n * ports. effect-cf owns the cached ManagedRuntime and supplies these values once per Object\n * incarnation; the durable runtime continues to depend only on the narrow services below.\n */\nconst effectCfPlatformLayer = (\n namespaceBinding: string,\n rpcTracing = false,\n): Layer.Layer<\n DurableObjectContext | ThreadObjectNamespace,\n CloudflareBindingError,\n EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment\n> => {\n const context = Layer.effect(DurableObjectContext)(\n Effect.gen(function* () {\n const state = yield* EffectCfDurableObjectState.DurableObjectState;\n const env = yield* WorkerEnvironment;\n\n return DurableObjectContext.of({ ctx: state.raw, env });\n }),\n );\n\n const namespace = Layer.effect(ThreadObjectNamespace)(\n Effect.gen(function* () {\n const env = yield* WorkerEnvironment;\n const binding = yield* threadNamespaceFromEnv(env, namespaceBinding);\n\n return ThreadObjectNamespace.of({\n get: (threadId) => binding.get(binding.idFromName(threadId)),\n ...(rpcTracing === true ? { rpcTracing: namespaceBinding } : {}),\n });\n }),\n );\n\n return Layer.merge(context, namespace);\n};\n\n/** The public endpoints and effect-cf invocation hook of one Thread Object instance. */\nexport interface Instance<EventServices = never> extends InstanceType<\n EffectCfDurableObject.DurableObjectClass<Record<never, never>, RuntimeServices | EventServices>\n> {\n submitEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n submissionStatusEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n awaitSettlementEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n awaitProgressEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n cancelProgressEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n observePage(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n abortEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n resolveApprovalEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n resolveUnknownEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n explainEncoded(encoded: unknown): Promise<unknown>;\n verifyEncoded(encoded: unknown): Promise<unknown>;\n retryEncoded(encoded: unknown): Promise<unknown>;\n obligationsEncoded(encoded: unknown): Promise<unknown>;\n portCall(encoded: unknown): Promise<unknown>;\n wake(): Promise<void>;\n alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> | void;\n}\n\n/** The constructor shape workerd instantiates for each Thread Object. */\nexport interface Class<EventServices = never> {\n new (ctx: DurableObjectState, env: Cloudflare.Env): Instance<EventServices>;\n}\n\n/**\n * Export a composed application Layer as a native Durable Object class.\n * Bootstrap services are provided to the whole graph before it acquires, so application Layers\n * can yield effect-cf's WorkerEnvironment and DurableObjectState, derived identity, and Crypto.\n * Effect Config reads scalar Worker vars and secrets through effect-cf's environment provider;\n * WorkerEnvironment exposes resource bindings without a separate config Layer.\n * Application dependencies remain visible until Layer.provide satisfies them. effect-cf owns the\n * cached ManagedRuntime, native RPC methods, event scopes, and telemetry flushing.\n * Initialization is local and bounded inside the constructor gate. Cloudflare eviction does not\n * guarantee finalizers; put resources requiring timely release in scoped operations or eventLayer.\n */\nexport const make = <\n ApplicationServices,\n ApplicationError,\n EventServices = never,\n EventLayerError = never,\n>(\n applicationLayer: Layer.Layer<\n CloudflareDurableRuntimeServices | ApplicationServices,\n ApplicationError,\n | CloudflareBootstrapServices\n | EffectCfDurableObjectState.DurableObjectState\n | WorkerEnvironment\n | DurableObjectContext\n | ThreadObjectNamespace\n >,\n options: Options<ApplicationServices, EventServices, EventLayerError>,\n): Class<ApplicationServices | EventServices> => {\n const application = applicationLayer.pipe(\n Layer.provideMerge(layerConfig(options)),\n Layer.provideMerge(effectCfPlatformLayer(options.namespaceBinding, options.rpcTracing)),\n );\n\n // The storage/config Layer must acquire inside Cloudflare's constructor gate. effect-cf owns\n // the ManagedRuntime, while this effectContext ensures its first Layer build enters the gate\n // before migration, compatibility checks, or alarm inspection touch Object storage.\n const runtime: Layer.Layer<\n RuntimeServices | ApplicationServices,\n ThreadObjectInitializationError | ApplicationError,\n EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment\n > = Layer.effectContext(\n Effect.gen(function* () {\n const state = yield* EffectCfDurableObjectState.DurableObjectState;\n const scope = yield* Effect.scope;\n\n return yield* state.blockConcurrencyWhile(\n Effect.gen(function* () {\n const services = yield* Layer.buildWithScope(application, scope);\n\n yield* gateEndpoint.pipe(Effect.provide(services));\n\n return services;\n }),\n );\n }),\n );\n\n const rpc = {\n ...threadRpc,\n explainEncoded: (encoded: unknown) => explainEndpoint(encoded),\n verifyEncoded: (encoded: unknown) => verifyEndpoint(encoded),\n retryEncoded: (encoded: unknown) => retryEndpoint(encoded),\n obligationsEncoded: (encoded: unknown) => obligationsEndpoint(encoded),\n } satisfies EffectCfDurableObject.DurableObjectRpc<\n RuntimeServices | ApplicationServices | EventServices\n >;\n\n type NativeOptions = EffectCfDurableObject.DurableObjectOptions<\n RuntimeServices | ApplicationServices,\n EventServices,\n EventLayerError,\n typeof rpc\n >;\n\n const EffectCfThreadObject = EffectCfDurableObject.make<\n RuntimeServices | ApplicationServices,\n ThreadObjectInitializationError | ApplicationError,\n EventServices,\n EventLayerError,\n typeof rpc\n >(runtime, {\n ...(options.rpcTracing === true ? { rpcTracing: { service: options.namespaceBinding } } : {}),\n ...(options.eventLayer === undefined ? {} : { eventLayer: options.eventLayer }),\n // Force the gated runtime Layer when Cloudflare loads this Object incarnation. Recovery stays\n // in each bounded pass so cross-Object initialization cannot deadlock.\n initialize: Effect.void,\n rpc,\n alarm: () => alarmEndpoint,\n // This host owns the raw alarm and supplies event services through options.eventLayer.\n // Upstream's conditional alarm-registration check cannot reduce over generic application\n // services. Options and the rpc satisfies check above retain their Effect requirements.\n } as NativeOptions);\n\n // effect-cf's class type keeps `alarm` optional even when the handler option is present. This\n // concrete override reflects this factory's stronger contract while delegating execution to\n // the effect-cf runtime unchanged.\n class ThreadObject extends EffectCfThreadObject {\n override alarm(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