@effect-agent/platform-cloudflare 0.1.0-beta.34 → 0.1.0-beta.36
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/index.mjs +9 -2
- package/dist/index.mjs.map +1 -1
- package/dist/interactive-browser.mjs +21 -9
- package/dist/interactive-browser.mjs.map +1 -1
- package/package.json +6 -6
- package/src/alarm.ts +19 -2
- package/src/interactive-browser.ts +34 -14
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["EffectCfDurableObjectState","EffectCfDurableObject","#dispatch"],"sources":["../src/bindings.ts","../src/config.ts","../src/boundary.ts","../src/alarm.ts","../src/wake-scheduler.ts","../src/progress-wait.ts","../src/transport.ts","../src/layers.ts","../src/client.ts","../src/conversation-object.ts","../src/code-mode-executor.ts"],"sourcesContent":["import type { ConversationId } from \"@effect-agent/core\";\nimport type { ProducerId } from \"@effect-agent/session\";\nimport { Context, Effect, Layer, Predicate, Schema } from \"effect\";\n\n/**\n * Cloudflare platform bindings as Effect services (DEPLOY-010: \"Cloudflare platform bindings\n * are supplied as Effect services/Layers\"). Application code never reads `env` or touches a\n * `DurableObjectState` directly — the Conversation Object class constructs these Layers once\n * per incarnation and everything downstream consumes the services.\n */\n\n/** A Cloudflare platform binding was missing or carried the wrong shape (DEPLOY-003/010). */\nexport class CloudflareBindingError extends Schema.TaggedError<CloudflareBindingError>()(\n \"CloudflareBindingError\",\n {\n binding: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/**\n * The RPC surface one Conversation Durable Object exposes to Workers and to sibling\n * Conversation Objects. `makeConversationObjectClass` implements it; the Worker-side client\n * and the cross-Object transport call it through `DurableObjectNamespace` stubs. Every\n * `encoded` value is a Schema-encoded envelope (`client.ts` wire schemas for host entry\n * points, `@effect-agent/storage-cloudflare` port envelopes for `portCall`), so the RPC\n * boundary carries only structured-cloneable JSON. The optional trailing trace context is\n * transient native RPC metadata, stripped by an opted-in effect-cf receiver before decoding\n * the host envelope. It never enters durable state.\n */\nexport interface ConversationObjectRpc extends Rpc.DurableObjectBranded {\n /** Admission-limits gate + `DurableAgentRuntime.submit`; answers a `SubmitResponse`. */\n submitEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Wake-hinted, poll-guaranteed settlement wait; answers an `AwaitSettlementResponse`. */\n awaitSettlementEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Event-driven durable progress wait; answers a `ProgressObserved` host response. */\n awaitProgressEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Best-effort cancellation for one in-flight progress wait. */\n cancelProgressEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** One bounded page of canonical records; answers an `ObservePageResponse`. */\n observePage(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Durable abort intent; answers an `AbortResponse`. */\n abortEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Durable approval decision (plan §2.6); answers a `ResolveApprovalResponse`. */\n resolveApprovalEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Authorized DUR-017 Unknown-Outcome resolution; answers a `ResolveUnknownResponse`. */\n resolveUnknownEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Owner-side cross-Object port endpoint (WP2 envelopes, executed on LOCAL facets). */\n portCall(encoded: unknown): Promise<unknown>;\n /** Droppable liveness hint from another Object: arms an immediate alarm. */\n wake(): Promise<void>;\n}\n\n/**\n * The `DurableObjectNamespace` binding that addresses Conversation Objects. The Object\n * identity rule is `namespace.idFromName(conversationId)` (plan §1.2): Conversation IDs are\n * globally unique, so the mapping is total and deterministic and no directory service exists.\n */\nexport class ConversationObjectNamespace extends Context.Service<\n ConversationObjectNamespace,\n {\n readonly namespace: DurableObjectNamespace<ConversationObjectRpc>;\n /** Stable binding name for opted-in native RPC tracing; absent by default. */\n readonly rpcTracing?: string;\n }\n>()(\"@effect-agent/platform-cloudflare/ConversationObjectNamespace\") {\n static layer(\n namespace: DurableObjectNamespace<ConversationObjectRpc>,\n ): Layer.Layer<ConversationObjectNamespace> {\n return Layer.succeed(ConversationObjectNamespace)({ namespace });\n }\n}\n\n/**\n * Narrow one `env` member to a `DurableObjectNamespace`. `env` is an untyped platform value,\n * and a namespace binding is a host object no Schema can decode, so this is the documented\n * narrowest-boundary check (structural probe for the namespace surface the transport uses);\n * a missing or misshaped binding fails typed before any Layer is built.\n */\nexport const conversationNamespaceFromEnv = Effect.fn(\"conversationNamespaceFromEnv\")(function* (\n env: unknown,\n binding: string,\n): Effect.fn.Return<DurableObjectNamespace<ConversationObjectRpc>, CloudflareBindingError> {\n if (!Predicate.isObjectKeyword(env)) {\n return yield* CloudflareBindingError.make({\n binding,\n message: \"The Worker environment is not an object; no bindings are available.\",\n });\n }\n const candidate = yield* Effect.try({\n try: () => {\n const value: unknown = Reflect.get(env, binding);\n if (!Predicate.isObjectKeyword(value)) return undefined;\n const idFromName: unknown = Reflect.get(value, \"idFromName\");\n const get: unknown = Reflect.get(value, \"get\");\n return typeof idFromName === \"function\" && typeof get === \"function\" ? value : undefined;\n },\n catch: () =>\n CloudflareBindingError.make({\n binding,\n message: `env.${binding} could not be inspected as a DurableObjectNamespace binding.`,\n }),\n });\n if (candidate !== undefined) {\n // The structural probe above is the entire runtime contract this package relies on;\n // the assertion records that `idFromName`/`get` name a DurableObjectNamespace.\n return candidate as unknown as DurableObjectNamespace<ConversationObjectRpc>;\n }\n return yield* CloudflareBindingError.make({\n binding,\n message:\n `env.${binding} is not a DurableObjectNamespace binding; declare the Conversation ` +\n \"Object class under this binding in the Worker configuration.\",\n });\n});\n\n/**\n * Build the namespace from Worker `env` (fails typed). Enable `rpcTracing` only when the\n * receiver also opts into the effect-cf native RPC trace-context contract.\n */\nexport const conversationNamespaceLayer = (\n env: unknown,\n binding: string,\n options: { readonly rpcTracing?: boolean } = {},\n): Layer.Layer<ConversationObjectNamespace, CloudflareBindingError> =>\n Layer.effect(ConversationObjectNamespace)(\n Effect.map(conversationNamespaceFromEnv(env, binding), (namespace) => ({\n namespace,\n ...(options.rpcTracing === true ? { rpcTracing: binding } : {}),\n })),\n );\n\n/**\n * The live Durable Object execution context of THIS incarnation. Only Layer construction and\n * the alarm service consume it; important state never lives on it (`ctx.storage` is truth,\n * everything in memory is a cache — deployment spec §11).\n */\nexport class DurableObjectContext extends Context.Service<\n DurableObjectContext,\n {\n readonly ctx: DurableObjectState;\n readonly env: unknown;\n }\n>()(\"@effect-agent/platform-cloudflare/DurableObjectContext\") {\n static layer(ctx: DurableObjectState, env: unknown): Layer.Layer<DurableObjectContext> {\n return Layer.succeed(DurableObjectContext)({ ctx, env });\n }\n}\n\n/**\n * The Conversation identity this Object serializes and the producer identity its Attempts\n * write with (`{producerPrefix}:{conversationId}`, plan §1.4). Derived once per incarnation\n * from `ctx.id.name` — the Object identity rule guarantees the name IS the Conversation ID.\n */\nexport class ConversationObjectIdentity extends Context.Service<\n ConversationObjectIdentity,\n {\n readonly conversationId: ConversationId;\n readonly producerId: ProducerId;\n }\n>()(\"@effect-agent/platform-cloudflare/ConversationObjectIdentity\") {}\n","import { DEFAULT_OWNERSHIP_LEASE_DURATION, DeploymentId } from \"@effect-agent/session\";\nimport { DEFAULT_MAX_STORED_VALUE_BYTES } from \"@effect-agent/storage-cloudflare\";\nimport { Context, Duration, Schema } from \"effect\";\n\n/**\n * Schema-validated configuration for the Cloudflare durable runtime (deployment spec §4:\n * decoded once during Layer construction, exposed as a typed service; DEPLOY-003). Every\n * cadence is in milliseconds; every bound is finite and checked before any resource opens.\n */\n\nconst PositiveMillis = Schema.Int.check(Schema.isGreaterThan(0));\nconst NonNegativeMillis = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));\n\n/** The supplied Cloudflare durable runtime configuration failed validation (DEPLOY-003). */\nexport class CloudflarePlatformConfigError extends Schema.TaggedError<CloudflarePlatformConfigError>()(\n \"CloudflarePlatformConfigError\",\n {\n message: Schema.String,\n cause: Schema.optionalKey(Schema.Defect()),\n },\n) {}\n\n/**\n * An admission was refused by a host resource limit BEFORE any ledger row existed\n * (deployment spec §8, DEPLOY-007: \"Admission has explicit bounded quota and overload\n * behavior... a typed rejection\"). This is the DC analogue of `NodeDurableHost`'s\n * `AdmissionClosed` host gate: the port surface stays untouched, the refusal happens in the\n * Conversation Object's submit entry point before `DurableAgentRuntime.submit` runs, and\n * nothing was admitted or written.\n */\nexport class AdmissionLimitExceeded extends Schema.TaggedError<AdmissionLimitExceeded>()(\n \"AdmissionLimitExceeded\",\n {\n limit: Schema.Literals([\"queue-depth\", \"input-bytes\", \"database-bytes\"]),\n actual: Schema.Int,\n maximum: Schema.Int,\n },\n) {\n override get message() {\n return (\n `Admission refused before any ledger row existed: ${this.limit} ${this.actual} exceeds ` +\n `the configured maximum ${this.maximum}. Accepted work is unaffected; retry after the ` +\n \"lane drains or raise the limit (DEPLOY-007).\"\n );\n }\n}\n\n/** The platform's hard per-Object database cap (10 GB, developers.cloudflare.com limits). */\nexport const CLOUDFLARE_DATABASE_CAP_BYTES = 10_000_000_000;\n\n/** Default database-size admission ceiling: a 1 GB safety margin under the platform cap. */\nexport const DEFAULT_MAX_DATABASE_BYTES = 9_000_000_000;\n\n/**\n * Explicit bounded admission quotas checked by the Conversation Object BEFORE admission\n * (exit gate \"resource limits are checked before admission\").\n */\nexport class CloudflareAdmissionLimitsValue extends Schema.Class<CloudflareAdmissionLimitsValue>(\n \"@effect-agent/platform-cloudflare/CloudflareAdmissionLimitsValue\",\n)({\n /** Maximum nonterminal Submissions per Conversation lane before new admissions refuse. */\n maxQueueDepthPerLane: Schema.Int.check(\n Schema.isGreaterThan(0),\n Schema.isLessThanOrEqualTo(100_000),\n ),\n /** Maximum encoded input bytes; never above the storage per-value bound. */\n maxInputBytes: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(2_000_000)),\n /** Maximum `ctx.storage.sql.databaseSize` at admission; stays under the 10 GB platform cap. */\n maxDatabaseBytes: Schema.Int.check(\n Schema.isGreaterThan(0),\n Schema.isLessThanOrEqualTo(CLOUDFLARE_DATABASE_CAP_BYTES),\n ),\n}) {}\n\n/**\n * Validated Cloudflare durable runtime configuration. The producer identity of one\n * Conversation Object is `{producerPrefix}:{conversationId}` — stable across incarnations of\n * the same deployment, distinct across deployments — and producer-epoch fencing (not the\n * producer name) remains the correctness authority (DUR-006).\n */\nexport class CloudflareDurableRuntimeConfigValue extends Schema.Class<CloudflareDurableRuntimeConfigValue>(\n \"@effect-agent/platform-cloudflare/CloudflareDurableRuntimeConfigValue\",\n)({\n deploymentId: DeploymentId,\n /** Head of the minted producer identity `{producerPrefix}:{conversationId}`. */\n producerPrefix: Schema.NonEmptyString.check(Schema.isMaxLength(256)),\n /** Submission ownership lease duration (D5); fences work across Object incarnations. */\n ownershipLeaseDuration: PositiveMillis,\n /** Base delay of the alarm re-arm backoff when a pass makes no progress. */\n alarmBackoffBase: PositiveMillis,\n /** Ceiling of the alarm re-arm backoff. */\n alarmBackoffCap: PositiveMillis,\n /**\n * The maintenance-pass scan cadence and the ceiling of every re-arm delay: nonterminal\n * work is revisited at least this often (wake/scan pairing, persistence §14).\n */\n wakeScanInterval: PositiveMillis,\n /** `awaitSettlement` ledger re-check cadence when no wake arrives. */\n settlementPollInterval: PositiveMillis,\n /** Worker ownership-lease renewal cadence during an active Attempt. */\n leaseRenewalInterval: PositiveMillis,\n /** Active-Run abort-intent poll cadence. */\n abortPollInterval: PositiveMillis,\n /** Canonical observation poll cadence of the Durable Object store. */\n observationPollInterval: NonNegativeMillis,\n /** Per-value byte bound; must stay under the platform's 2 MB SQLite value limit. */\n maxStoredValueBytes: Schema.Int.check(\n Schema.isGreaterThan(0),\n Schema.isLessThanOrEqualTo(2_000_000),\n ),\n /** Opt-in full payload/digest-chain audit while opening the store. */\n verifyOnOpen: Schema.Boolean,\n limits: CloudflareAdmissionLimitsValue,\n}) {}\n\n/** Explicit configuration authority for the assembled Cloudflare durable runtime. */\nexport class CloudflareDurableRuntimeConfig extends Context.Service<\n CloudflareDurableRuntimeConfig,\n CloudflareDurableRuntimeConfigValue\n>()(\"@effect-agent/platform-cloudflare/CloudflareDurableRuntimeConfig\") {}\n\n/** Documented production defaults applied by `CloudflareDurableRuntime.layer`. */\nexport const CLOUDFLARE_RUNTIME_DEFAULTS = {\n ownershipLeaseDuration: Duration.toMillis(DEFAULT_OWNERSHIP_LEASE_DURATION),\n alarmBackoffBase: 100,\n alarmBackoffCap: 5_000,\n wakeScanInterval: 1_000,\n settlementPollInterval: 500,\n leaseRenewalInterval: 10_000,\n abortPollInterval: 500,\n observationPollInterval: 25,\n maxStoredValueBytes: DEFAULT_MAX_STORED_VALUE_BYTES,\n verifyOnOpen: false,\n maxQueueDepthPerLane: 256,\n maxInputBytes: DEFAULT_MAX_STORED_VALUE_BYTES,\n maxDatabaseBytes: DEFAULT_MAX_DATABASE_BYTES,\n} as const;\n","import { Predicate } from \"effect\";\n\nconst MAX_FOREIGN_DIAGNOSTIC_LENGTH = 8_192;\n\nconst boundForeignDiagnostic = (message: string): string =>\n message.slice(0, MAX_FOREIGN_DIAGNOSTIC_LENGTH);\n\n/** Render a foreign failure without trusting accessors or coercion hooks on the value. */\nexport const safeCauseMessage = (cause: unknown, fallback: string): string => {\n try {\n const message = cause instanceof Error ? cause.message : cause;\n return boundForeignDiagnostic(typeof message === \"string\" ? message : String(message));\n } catch {\n return boundForeignDiagnostic(fallback);\n }\n};\n\n/** Include an Error name when worker-failure classification needs it. */\nexport const safeCauseDiagnostic = (cause: unknown, fallback: string): string => {\n try {\n return cause instanceof Error\n ? boundForeignDiagnostic(`${cause.name}: ${cause.message}`)\n : safeCauseMessage(cause, fallback);\n } catch {\n return boundForeignDiagnostic(fallback);\n }\n};\n\nexport interface CloudflareFailureSignals {\n readonly retryable?: boolean | undefined;\n readonly overloaded?: boolean | undefined;\n}\n\n/** Read Cloudflare RPC classifications without letting a hostile proxy defect the client. */\nexport const cloudflareFailureSignals = (cause: unknown): CloudflareFailureSignals => {\n if (!Predicate.isObjectKeyword(cause)) return {};\n try {\n const retryableValue = Reflect.get(cause, \"retryable\");\n const overloadedValue = Reflect.get(cause, \"overloaded\");\n const resetValue = Reflect.get(cause, \"durableObjectReset\");\n const retryable =\n typeof retryableValue === \"boolean\" ? retryableValue : resetValue === true ? true : undefined;\n const overloaded = typeof overloadedValue === \"boolean\" ? overloadedValue : undefined;\n return {\n ...(retryable === undefined ? {} : { retryable }),\n ...(overloaded === undefined ? {} : { overloaded }),\n };\n } catch {\n return {};\n }\n};\n","import {\n AgentBindingResolver,\n DurableAgentRuntime,\n SubmissionLedger,\n type DurableBindingFailure,\n type DurableWorkerFailure,\n type RecoveryReport,\n type SubmissionSnapshot,\n} from \"@effect-agent/session\";\nimport {\n Clock,\n Context,\n Effect,\n Layer,\n Option,\n Random,\n Ref,\n Schema,\n Semaphore,\n Stream,\n} from \"effect\";\n\nimport { ConversationObjectIdentity, DurableObjectContext } from \"./bindings.ts\";\nimport { safeCauseMessage } from \"./boundary.ts\";\nimport { CloudflareDurableRuntimeConfig } from \"./config.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/** `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> =\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 const scheduled = Effect.tryPromise({\n try: () => ctx.storage.getAlarm(),\n catch: alarmFailure(\"get alarm\"),\n }).pipe(\n Effect.map((deadline) =>\n deadline === null ? Option.none<number>() : Option.some(deadline),\n ),\n );\n const scheduleAt = (epochMillis: number) =>\n Effect.tryPromise({\n try: () => ctx.storage.setAlarm(epochMillis),\n catch: alarmFailure(\"set alarm\"),\n });\n const ensureScheduledBy = (epochMillis: number) =>\n scheduled.pipe(\n Effect.flatMap((existing) =>\n Option.isSome(existing) && existing.value <= epochMillis\n ? Effect.void\n : scheduleAt(epochMillis),\n ),\n );\n const armNow = Clock.currentTimeMillis.pipe(\n Effect.flatMap((now) => ensureScheduledBy(now)),\n );\n const scheduleNow = Ref.get(runningPasses).pipe(\n Effect.flatMap((passes) => (passes > 0 ? Effect.void : armNow)),\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 const cancel = Effect.tryPromise({\n try: () => ctx.storage.deleteAlarm(),\n catch: alarmFailure(\"delete alarm\"),\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` is generation-only; `actionable` ran recovery and one bounded drain. */\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 /** Settlements the drain pass finalized. */\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 ConversationMaintenanceFailpointLocation =\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:finish:before\"\n | \"maintenance:finish:after\";\n\nexport type ConversationMaintenanceFailpointHandler = (\n location: ConversationMaintenanceFailpointLocation,\n) => Effect.Effect<void>;\n\n/** Test-only fault authority; production uses the inert layer. */\nexport class ConversationMaintenanceFailpoint extends Context.Service<\n ConversationMaintenanceFailpoint,\n {\n readonly hit: ConversationMaintenanceFailpointHandler;\n }\n>()(\"@effect-agent/platform-cloudflare/ConversationMaintenanceFailpoint\") {\n static readonly layer = Layer.succeed(this)({ hit: () => Effect.void });\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 ConversationMaintenanceState extends Schema.Class<ConversationMaintenanceState>(\n \"@effect-agent/platform-cloudflare/ConversationMaintenanceState\",\n)({\n schemaVersion: Schema.Literal(1),\n dirty: MaintenanceGeneration,\n processed: MaintenanceGeneration,\n nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\nconst MAINTENANCE_STATE_KEY = \"effect-agent:conversation-maintenance:v1\";\nconst decodeMaintenanceState = Schema.decodeUnknownSync(ConversationMaintenanceState);\nconst encodeMaintenanceState = Schema.encodeSync(ConversationMaintenanceState);\n\nconst initialMaintenanceState = (): ConversationMaintenanceState =>\n ConversationMaintenanceState.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: ConversationMaintenanceState; readonly initialized: boolean }> => {\n const encoded = await transaction.get(MAINTENANCE_STATE_KEY);\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 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 switch (snapshot.state) {\n case \"suspended\":\n case \"unknown\":\n case \"joined\":\n return true;\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\nexport type MaintenancePassFailure =\n | DurableWorkerFailure\n | DurableBindingFailure\n | DurableAlarmError;\n\n/**\n * Incremental, quiescent maintenance over a durable dirty/processed generation (issue #93).\n *\n * `pass` = generation snapshot/pre-arm → recovery → bounded drain → 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 still strictly precedes a new claim, and one bounded drain advances the lane.\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 ConversationMaintenance extends Context.Service<\n ConversationMaintenance,\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/ConversationMaintenance\") {\n static readonly layer: Layer.Layer<\n ConversationMaintenance,\n never,\n | DurableAgentRuntime\n | AgentBindingResolver\n | SubmissionLedger\n | DurableAlarmService\n | ConversationMaintenanceFailpoint\n | CloudflareDurableRuntimeConfig\n | ConversationObjectIdentity\n | DurableObjectContext\n > = Layer.effect(ConversationMaintenance)(\n Effect.gen(function* () {\n const runtime = yield* DurableAgentRuntime;\n const resolver = yield* AgentBindingResolver;\n const ledger = yield* SubmissionLedger;\n const alarm = yield* DurableAlarmService;\n const config = yield* CloudflareDurableRuntimeConfig;\n const identity = yield* ConversationObjectIdentity;\n const { ctx } = yield* DurableObjectContext;\n const failpoint = yield* ConversationMaintenanceFailpoint;\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 /**\n * Incarnation-local mutation count guarded with the generation transactions below. It is\n * deliberately not durable: after eviction every begun mutation has stopped, while its\n * pre-armed dirty generation remains durable for recovery. The short gate never spans the\n * caller's mutation or cross-Object I/O.\n */\n const activeMutations = yield* Ref.make(0);\n const generationGate = yield* Semaphore.make(1);\n // At-least-once deliveries are idempotent, but overlapping pass bodies could otherwise\n // acknowledge state while a sibling pass is still mutating it. Port/RPC mutations do not\n // take this permit, so cross-Object I/O cannot deadlock the maintenance serialization.\n const maintenancePassGate = yield* Semaphore.make(1);\n const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));\n\n const runTransaction = <A>(\n operation: string,\n transaction: () => Promise<A>,\n ): Effect.Effect<A, DurableAlarmError> =>\n Effect.tryPromise({\n try: transaction,\n catch: alarmFailure(operation),\n });\n\n const beginMutation = Effect.fn(\"ConversationMaintenance.beginMutation\")(function* () {\n yield* failpoint.hit(\"maintenance:dirty:before\");\n const now = yield* Clock.currentTimeMillis;\n yield* runTransaction(\"advance maintenance generation\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n const next = ConversationMaintenanceState.make({\n ...state,\n dirty: state.dirty + 1n,\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 const ensureAlarm = Effect.fn(\"ConversationMaintenance.ensureAlarm\")(function* () {\n yield* failpoint.hit(\"maintenance:ensure:before\");\n const now = yield* Clock.currentTimeMillis;\n yield* runTransaction(\"ensure maintenance alarm\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state, initialized } = await readMaintenanceState(transaction);\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 yield* failpoint.hit(\"maintenance:ensure:after\");\n });\n\n const beginPass = Effect.fn(\"ConversationMaintenance.beginPass\")(function* () {\n yield* failpoint.hit(\"maintenance:begin:before\");\n const now = yield* Clock.currentTimeMillis;\n const result = yield* runTransaction(\"begin maintenance pass\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state, initialized } = await readMaintenanceState(transaction);\n if (!initialized) {\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));\n }\n if (state.processed >= state.dirty) {\n await transaction.deleteAlarm();\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 return { _tag: \"Actionable\" as const, generation: state.dirty };\n }),\n );\n yield* failpoint.hit(\"maintenance:begin:after\");\n return result;\n });\n\n const rearmDelay = Effect.fn(\"ConversationMaintenance.rearmDelay\")(function* (\n progressed: boolean,\n ) {\n const priorStalls = yield* Ref.getAndUpdate(stalls, (count) =>\n progressed ? 0 : count + 1,\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 return Math.min(jittered, config.wakeScanInterval);\n });\n\n const pass = Effect.fn(\"ConversationMaintenance.pass\")(function* (): Effect.fn.Return<\n MaintenancePassReport,\n MaintenancePassFailure\n > {\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* generationGate.withPermit(\n Effect.gen(function* () {\n const activeAtStart = yield* Ref.get(activeMutations);\n const generation = yield* beginPass();\n return { ...generation, activeAtStart };\n }),\n );\n if (started._tag === \"CaughtUp\") {\n return yield* annotate(\n MaintenancePassReport.make({\n phase: \"caught-up\",\n recovered: 0,\n settled: 0,\n nonterminal: started.nonterminal,\n alarm: \"cleared\",\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 // Step 3 — one bounded drain pass over this Object's own lane.\n const settlements = yield* runtime\n .processConversationResolved(identity.conversationId)\n .pipe(Effect.provideService(AgentBindingResolver, resolver));\n // Observe residual state before acknowledging this exact pass-start generation.\n const remaining = yield* Stream.runCollect(ledger.scanNonterminal);\n const reports = new Map(recovered.map((report) => [report.submissionId, report]));\n const autonomous = remaining.some((snapshot) => !stableExternalWait(snapshot, reports));\n const progressed =\n settlements.length > 0 || recovered.some((report) => report.disposition === \"repaired\");\n const delay = autonomous ? yield* rearmDelay(progressed) : 0;\n const now = yield* Clock.currentTimeMillis;\n yield* failpoint.hit(\"maintenance:finish:before\");\n const alarmDisposition = yield* generationGate.withPermit(\n Effect.gen(function* () {\n const active = yield* Ref.get(activeMutations);\n return yield* runTransaction(\"finish maintenance pass\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\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 const next = ConversationMaintenanceState.make({\n ...state,\n processed,\n nonterminal: remaining.length,\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(now + delay);\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(transaction, now + config.wakeScanInterval);\n return \"rearmed\" as const;\n }\n await transaction.deleteAlarm();\n return \"cleared\" as const;\n }),\n );\n }),\n );\n yield* failpoint.hit(\"maintenance:finish:after\");\n if (alarmDisposition === \"cleared\") {\n yield* Ref.set(stalls, 0);\n }\n return yield* annotate(\n MaintenancePassReport.make({\n phase: \"actionable\",\n recovered: recovered.length,\n settled: settlements.length,\n nonterminal: remaining.length,\n alarm: alarmDisposition,\n }),\n );\n });\n\n return ConversationMaintenance.of({\n // A mid-pass immediate hint is droppable; durable dirty state decides the final alarm.\n pass: alarm.withWakesDeferred(maintenancePassGate.withPermit(pass())),\n ensureAlarm: ensureAlarm(),\n withMutation,\n });\n }),\n );\n}\n","import type { ConversationId } from \"@effect-agent/core\";\nimport { makeWakeSubscriptionHub, WakeScheduler } from \"@effect-agent/session\";\nimport { Effect, Layer, PubSub, Schema, Stream } from \"effect\";\n\nimport { DurableAlarmService } from \"./alarm.ts\";\nimport { ConversationObjectIdentity, ConversationObjectNamespace } from \"./bindings.ts\";\nimport { safeCauseMessage } from \"./boundary.ts\";\n\n/**\n * Bounded in-memory wake buffer for same-incarnation `awaitSettlement` subscribers. Wake\n * hints are droppable by contract (consumers pair every subscription with ledger polls), so\n * a full buffer slides out the oldest hint and an eviction simply loses the buffer — the\n * poll interval and the persisted alarm keep liveness (persistence §14).\n */\nconst WAKE_BUFFER_CAPACITY = 1_024;\n\n/** A remote wake stub call failed; always swallowed and logged (hints are droppable). */\nclass RemoteWakeDropped extends Schema.TaggedError<RemoteWakeDropped>()(\"RemoteWakeDropped\", {\n conversationId: Schema.String,\n message: Schema.String,\n cause: Schema.optionalKey(Schema.Defect()),\n}) {}\n\n/**\n * The DC `WakeScheduler` (plan §1.4):\n *\n * - `notify(local)` → `setAlarm(now)` — durable, cheap, coalescing (the alarm slot keeps the\n * earliest deadline) — plus a same-incarnation PubSub hint for `awaitSettlement` waiters.\n * - `notify(remote)` → fire-and-forget `wake()` on the owning Object's stub with every error\n * swallowed and logged: hints are droppable, and the target's own alarm/scan pairing (the\n * maintenance pass re-polls unsettled children) guarantees liveness without this call.\n * - `wakes` → the bounded sliding PubSub only. No important state lives in memory: the\n * subscription accelerates waiters within one incarnation and the settlement poll interval\n * is the correctness path.\n */\nexport const cloudflareWakeSchedulerLayer: Layer.Layer<\n WakeScheduler,\n never,\n DurableAlarmService | ConversationObjectIdentity | ConversationObjectNamespace\n> = Layer.effect(WakeScheduler)(\n Effect.gen(function* () {\n const alarm = yield* DurableAlarmService;\n const identity = yield* ConversationObjectIdentity;\n const { namespace } = yield* ConversationObjectNamespace;\n const hints = yield* PubSub.sliding<ConversationId>(WAKE_BUFFER_CAPACITY);\n const progress = yield* makeWakeSubscriptionHub;\n yield* Effect.addFinalizer(() => PubSub.shutdown(hints));\n\n const notifyLocal = (conversationId: ConversationId) =>\n progress.notify(conversationId).pipe(\n Effect.andThen(PubSub.publish(hints, conversationId)),\n Effect.andThen(alarm.scheduleNow),\n Effect.catch((error) =>\n // `notify` never fails by contract; a failed alarm write degrades to \"hint lost\"\n // and the pass re-arm (or the next entry point's pre-arm) restores the invariant.\n Effect.logWarning(\"CloudflareWakeScheduler: local alarm wake failed\", error),\n ),\n Effect.asVoid,\n );\n\n const notifyRemote = (conversationId: ConversationId) =>\n Effect.tryPromise({\n try: () => namespace.get(namespace.idFromName(conversationId)).wake(),\n catch: (cause) =>\n RemoteWakeDropped.make({\n conversationId,\n message: safeCauseMessage(cause, \"The remote wake failed without a diagnostic\"),\n cause,\n }),\n }).pipe(\n Effect.catch((error) =>\n Effect.logWarning(\n `CloudflareWakeScheduler: remote wake of ${conversationId} dropped`,\n error,\n ),\n ),\n Effect.asVoid,\n );\n\n return WakeScheduler.of({\n notify: (conversationId) =>\n conversationId === identity.conversationId\n ? notifyLocal(conversationId)\n : notifyRemote(conversationId),\n subscribe: progress.subscribe,\n wakes: Stream.fromPubSub(hints),\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 a registered waiter, or remember a bounded early cancellation. */\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 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 active.delete(deferred);\n if (active.size === 0) {\n next.delete(waiterId);\n } else {\n next.set(waiterId, active);\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 yield* Effect.addFinalizer(() => remove(waiterId, deferred));\n const cancelled = yield* Ref.modify(registrations, (current) => {\n const existing = current.get(waiterId);\n const next = new Map(current);\n if (existing === \"cancelled\") {\n return [true, current] as const;\n }\n const active = new Set(existing ?? []);\n active.add(deferred);\n next.set(waiterId, active);\n return [false, next] as const;\n });\n return { cancelled, deferred };\n }).pipe(\n Effect.map(({ cancelled, deferred }) =>\n cancelled ? Effect.void : Deferred.await(deferred),\n ),\n ),\n );\n\n const cancel = Effect.fn(\"ProgressWaitRegistry.cancel\")(function* (waiterId: string) {\n const waiters = yield* Ref.modify(registrations, (current) => {\n const existing = current.get(waiterId);\n const next = new Map(current);\n if (existing === undefined) {\n next.set(waiterId, \"cancelled\");\n let tombstones = 0;\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 return [[], next] as const;\n }\n if (existing === \"cancelled\") return [[], current] as const;\n next.delete(waiterId);\n return [[...existing], next] as const;\n });\n yield* Effect.forEach(waiters, (waiter) => Deferred.succeed(waiter, undefined), {\n discard: true,\n });\n });\n\n return ProgressWaitRegistry.of({ subscribe, cancel });\n }),\n );\n}\n","import { ConversationPortTransport, portTransportFailure } from \"@effect-agent/storage-cloudflare\";\nimport { Effect, Layer } from \"effect\";\n\nimport { ConversationObjectNamespace } from \"./bindings.ts\";\n\n/**\n * `ConversationPortTransport` over native Durable Object JS RPC (decision D-P6-3): one\n * `portCall(envelope)` on the stub of the Object that owns the addressed Conversation\n * (`namespace.idFromName(conversationId)` — 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 conversationPortTransportLayer: Layer.Layer<\n ConversationPortTransport,\n never,\n ConversationObjectNamespace\n> = Layer.effect(ConversationPortTransport)(\n Effect.gen(function* () {\n const { namespace } = yield* ConversationObjectNamespace;\n return ConversationPortTransport.of({\n call: (conversationId, request) =>\n Effect.tryPromise({\n try: () => namespace.get(namespace.idFromName(conversationId)).portCall(request),\n catch: (cause) => portTransportFailure(conversationId, cause),\n }).pipe(\n Effect.withSpan(\"CloudflarePortTransport.call\", {\n attributes: { conversationId },\n }),\n ),\n });\n }),\n);\n","import { ConversationId } from \"@effect-agent/core\";\nimport type {\n RunContextPreparation,\n RunCostEstimator,\n RunToolFailureObserver,\n} from \"@effect-agent/engine\";\nimport {\n CurrentToolFailureObserver,\n RunContextPreparationPassthrough,\n toolFailureObserverLayer,\n} from \"@effect-agent/engine\";\nimport {\n AgentBindingResolver,\n DurableAgentRuntime,\n DurableRuntimeConfig,\n DurableRuntimeFailpoint,\n ProducerId,\n operationAuthorizerLayer,\n ToolReconciler,\n type ConversationStore,\n type DurableRuntimeFailpointHandler,\n type OperationAuthorizerService,\n type ResolvedBinding,\n type SubmissionLedger,\n type WakeScheduler,\n} from \"@effect-agent/session\";\nimport {\n conversationStoreLayer,\n executePortRequest,\n routedConversationStoreLayer,\n routedSubmissionLedgerLayer,\n storageConfigLayer,\n storageFailpointLayer,\n submissionLedgerLayer,\n type DoStorageFailpointHandler,\n type DoStorageInitializationError,\n type DoStorageOptions,\n type PortRequest,\n type PortResponse,\n} from \"@effect-agent/storage-cloudflare\";\nimport { BrowserCrypto } from \"@effect/platform-browser\";\nimport { SqliteClient } from \"@effect/sql-sqlite-do\";\nimport type { Crypto } from \"effect\";\nimport { Context, Duration, Effect, Layer, Schema } from \"effect\";\n\nimport {\n ConversationMaintenance,\n ConversationMaintenanceFailpoint,\n DurableAlarmService,\n type ConversationMaintenanceFailpointHandler,\n} from \"./alarm.ts\";\nimport {\n ConversationObjectIdentity,\n DurableObjectContext,\n type ConversationObjectNamespace,\n} from \"./bindings.ts\";\nimport {\n CLOUDFLARE_RUNTIME_DEFAULTS,\n CloudflareDurableRuntimeConfig,\n CloudflareDurableRuntimeConfigValue,\n CloudflarePlatformConfigError,\n} from \"./config.ts\";\nimport { ProgressWaitRegistry } from \"./progress-wait.ts\";\nimport { conversationPortTransportLayer } from \"./transport.ts\";\nimport { cloudflareWakeSchedulerLayer } from \"./wake-scheduler.ts\";\n\n/**\n * Raw (unvalidated) construction options for `CloudflareDurableRuntime.layer`, mirroring\n * `NodeDurableRuntimeOptions`. 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}:{conversationId}`. */\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 /** Conversation-maintenance generation/alarm fault injection; default none. */\n readonly maintenanceFailpoint?:\n | ((ctx: DurableObjectState) => ConversationMaintenanceFailpointHandler)\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 * Registered worker Bindings resolved at durable claim time (S2, spec/subagents.md §11):\n * build each with `DurableWorkerBinding.make(binding, digests)`. The callback receives the live\n * Object context and derived identities and is evaluated once per incarnation during Layer\n * construction. Defaults to the empty registration (every resolved claim fails closed).\n */\n readonly bindings?: CloudflareBindingSource | undefined;\n /**\n * Generic Run context acquired with this Durable Object incarnation. It may prepare model\n * context and/or authorize exact model-declared application Tool Calls at action time. The\n * Layer may depend\n * only on `Crypto.Crypto`, which this platform supplies with `BrowserCrypto`; hosts must close\n * every application-specific service before passing it here. Default absent.\n */\n readonly runContext?: CloudflareRunContextSource | undefined;\n}\n\n/** Per-incarnation host values available to Effect-native runtime extension factories. */\nexport interface CloudflareRuntimeSourceContext {\n readonly ctx: DurableObjectState;\n readonly env: unknown;\n readonly conversationId: ConversationId;\n readonly producerId: ProducerId;\n}\n\n/** Per-incarnation host values available while registered worker Bindings are captured. */\nexport interface CloudflareBindingSourceContext extends CloudflareRuntimeSourceContext {}\n\n/** Captures registered worker Bindings once for each Durable Object incarnation. */\nexport type CloudflareBindingSource = (\n context: CloudflareBindingSourceContext,\n) => Effect.Effect<ReadonlyArray<ResolvedBinding>, never, never>;\n\n/** A closed Run-context service whose only remaining requirement is platform Crypto. */\nexport type CloudflareRunContextLayer = Layer.Layer<RunContextPreparation, never, Crypto.Crypto>;\n\n/** One Layer or a per-incarnation factory over explicit Cloudflare host values. */\nexport type CloudflareRunContextSource =\n | CloudflareRunContextLayer\n | ((context: CloudflareRuntimeSourceContext) => CloudflareRunContextLayer);\n\n/** Every construction failure of the assembled Cloudflare durable runtime stack. */\nexport type CloudflareDurableRuntimeInitializationError =\n | CloudflarePlatformConfigError\n | DoStorageInitializationError;\n\n/** The services `CloudflareDurableRuntime.layer` provides. */\nexport type CloudflareDurableRuntimeServices =\n | DurableAgentRuntime\n | SubmissionLedger\n | ConversationStore\n | WakeScheduler\n | DurableRuntimeConfig\n | AgentBindingResolver\n | CloudflareDurableRuntimeConfig\n | ConversationObjectIdentity\n | DurableAlarmService\n | ConversationMaintenance\n | ConversationObjectPorts\n | ProgressWaitRegistry;\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 ConversationObjectPorts extends Context.Service<\n ConversationObjectPorts,\n {\n readonly handle: (request: PortRequest) => Effect.Effect<PortResponse>;\n }\n>()(\"@effect-agent/platform-cloudflare/ConversationObjectPorts\") {}\n\nconst decodeConfigValue = Schema.decodeUnknownEffect(CloudflareDurableRuntimeConfigValue);\nconst decodeConversationId = Schema.decodeUnknownEffect(ConversationId);\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 Conversation this Object owns, from the Object identity rule (plan §1.2): Conversation\n * Objects are addressed exclusively by `idFromName(conversationId)`, so `ctx.id.name` IS the\n * Conversation ID. An unnamed Object (from `newUniqueId`) is a deployment error, not a lane.\n */\nconst conversationIdFromState = (\n ctx: DurableObjectState,\n): Effect.Effect<ConversationId, CloudflarePlatformConfigError> =>\n ctx.id.name === undefined\n ? Effect.fail(\n CloudflarePlatformConfigError.make({\n message:\n \"This Durable Object was not created via idFromName(conversationId); Conversation \" +\n \"Objects must be addressed by their Conversation identity (plan §1.2).\",\n }),\n )\n : decodeConversationId(ctx.id.name).pipe(\n Effect.mapError((error) =>\n CloudflarePlatformConfigError.make({\n message: `The Durable Object name is not a valid ConversationId: ${error.message}`,\n cause: error,\n }),\n ),\n );\n\nconst resolveBindings = (\n source: CloudflareDurableRuntimeOptions[\"bindings\"],\n context: CloudflareBindingSourceContext,\n): Effect.Effect<ReadonlyArray<ResolvedBinding>> =>\n source === undefined ? Effect.succeed([]) : Effect.suspend(() => source(context));\n\nconst resolveRunContext = (\n source: CloudflareRunContextSource,\n context: CloudflareRuntimeSourceContext,\n): CloudflareRunContextLayer => (typeof source === \"function\" ? source(context) : source);\n\n/**\n * The DC Layer assembly (deployment §12: a Layer-assembly library, not an app entrypoint;\n * plan §1.4). `layer(options)` decodes the configuration, derives this Object's Conversation\n * and producer identities, opens the Object's private SQLite database through\n * `@effect/sql-sqlite-do` for BOTH the Conversation Log and the Submission Ledger (so claims\n * fence the same producer epochs — ADR-0011 D7 transposed), wraps the local port facets with\n * the WP2 cross-Object routing decorators over the Durable Object RPC transport, wires the\n * alarm-backed wake scheduler and the maintenance pass, defaults reconciliation to the\n * fail-closed `ToolReconciler.uncertain`, and provides a ready `DurableAgentRuntime` on top.\n *\n * Storage compatibility is verified during construction: an incompatible database fails the\n * Layer typed (`DoStorageCompatibilityError`) before anything is mutated (DEPLOY-008).\n *\n * Requires only the two binding services (`DurableObjectContext`,\n * `ConversationObjectNamespace`) — platform values enter exclusively through Layers\n * (DEPLOY-010).\n */\nexport class CloudflareDurableRuntime {\n static layer(\n options: CloudflareDurableRuntimeOptions,\n ): Layer.Layer<\n CloudflareDurableRuntimeServices,\n CloudflareDurableRuntimeInitializationError,\n DurableObjectContext | ConversationObjectNamespace\n > {\n return Layer.unwrap(\n Effect.gen(function* () {\n const { ctx, env } = yield* DurableObjectContext;\n const config = yield* configFromOptions(options);\n const conversationId = yield* conversationIdFromState(ctx);\n const producerId = yield* decodeProducerId(\n `${config.producerPrefix}:${conversationId}`,\n ).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 const identityLayer = Layer.succeed(ConversationObjectIdentity)({\n conversationId,\n producerId,\n });\n const cloudflareConfigLayer = Layer.succeed(CloudflareDurableRuntimeConfig)(config);\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 failpoint: options.storageFailpoint?.(ctx),\n };\n const infrastructure = Layer.mergeAll(\n storageConfigLayer(storageOptions),\n storageFailpointLayer(storageOptions),\n SqliteClient.layer({ storage: ctx.storage }),\n BrowserCrypto.layer,\n );\n\n /**\n * ONE local-facet instance (a shared Layer value) serves both the routed decorators\n * and the owner-side `portCall` executor — the executor must never see the routed\n * ports (plan §1.3: re-routing could bounce a request between Objects).\n */\n const localPorts = Layer.mergeAll(conversationStoreLayer, submissionLedgerLayer).pipe(\n Layer.provide(infrastructure),\n );\n\n const portsEndpointLayer = Layer.effect(ConversationObjectPorts)(\n Effect.gen(function* () {\n const local = yield* Effect.context<SubmissionLedger | ConversationStore>();\n return ConversationObjectPorts.of({\n handle: (request) => executePortRequest(request).pipe(Effect.provide(local)),\n });\n }),\n ).pipe(Layer.provide(localPorts));\n\n const routedPorts = Layer.mergeAll(\n routedSubmissionLedgerLayer({ localConversationId: conversationId }),\n routedConversationStoreLayer({ localConversationId: conversationId }),\n ).pipe(Layer.provide(localPorts), Layer.provide(conversationPortTransportLayer));\n\n const runtimeConfigLayer = Layer.succeed(DurableRuntimeConfig)(\n DurableRuntimeConfig.make({\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 );\n\n const runtimeFailpointLayer =\n options.runtimeFailpoint === undefined\n ? DurableRuntimeFailpoint.layer\n : Layer.succeed(DurableRuntimeFailpoint)({ hit: options.runtimeFailpoint(ctx) });\n const maintenanceFailpointLayer =\n options.maintenanceFailpoint === undefined\n ? ConversationMaintenanceFailpoint.layer\n : Layer.succeed(ConversationMaintenanceFailpoint)({\n hit: options.maintenanceFailpoint(ctx),\n });\n const reconcilerLayer = options.toolReconciler ?? ToolReconciler.uncertain;\n const authorizerLayer =\n options.operationAuthorizer === undefined\n ? Layer.empty\n : operationAuthorizerLayer(options.operationAuthorizer);\n const observerLayer =\n options.toolFailureObserver === undefined\n ? Layer.succeed(CurrentToolFailureObserver)(undefined)\n : toolFailureObserverLayer(options.toolFailureObserver);\n const bindingResolverLayer = Layer.effect(AgentBindingResolver)(\n Effect.map(\n resolveBindings(options.bindings, { ctx, env, conversationId, producerId }),\n (bindings) => AgentBindingResolver.fromBindings(bindings),\n ),\n );\n const runContextLayer =\n options.runContext === undefined\n ? RunContextPreparationPassthrough\n : resolveRunContext(options.runContext, { ctx, env, conversationId, producerId }).pipe(\n Layer.provide(BrowserCrypto.layer),\n );\n\n const base = Layer.mergeAll(\n identityLayer,\n cloudflareConfigLayer,\n DurableAlarmService.layer,\n maintenanceFailpointLayer,\n ProgressWaitRegistry.layer,\n );\n\n const runtimeStack = DurableAgentRuntime.layerWithContext.pipe(\n Layer.provideMerge(routedPorts),\n Layer.provideMerge(cloudflareWakeSchedulerLayer),\n Layer.provideMerge(runtimeConfigLayer),\n Layer.provideMerge(bindingResolverLayer),\n Layer.provide(\n Layer.mergeAll(\n runtimeFailpointLayer,\n reconcilerLayer,\n authorizerLayer,\n observerLayer,\n runContextLayer,\n BrowserCrypto.layer,\n ),\n ),\n Layer.provideMerge(base),\n );\n\n return Layer.mergeAll(\n runtimeStack,\n ConversationMaintenance.layer.pipe(Layer.provide(runtimeStack)),\n portsEndpointLayer,\n );\n }),\n );\n }\n}\n","import { AgentId, AgentInputError, type ConversationId } from \"@effect-agent/core\";\nimport {\n AbortCommand,\n AbortIntent,\n AdmissionConflict,\n AppendConflict,\n ApprovalConflict,\n ApprovalDecisionCommand,\n ApprovalDecisionIntent,\n CanonicalRecordEnvelope,\n CanonicalSequence,\n ConversationNotMaterialized,\n ConversationStoreError,\n DefinitionDigests,\n DigestError,\n DurableRuntimeFailpointError,\n FenceRejected,\n IdempotencyKey,\n JoinedToHost,\n LedgerError,\n OperationDenied,\n PersistedJson,\n Principal,\n Receipt,\n Settlement,\n SettlementConflict,\n UnknownResolutionCommand,\n UnknownResolutionConflict,\n UnknownResolutionIntent,\n type DurableSubmitAgent,\n type DurableSubmitOptions,\n} from \"@effect-agent/session\";\nimport { Context, Crypto, Duration, Effect, Layer, Schema } from \"effect\";\nimport { RpcTracing } from \"effect-cf\";\n\nimport { DurableAlarmError } from \"./alarm.ts\";\nimport { ConversationObjectNamespace, type ConversationObjectRpc } from \"./bindings.ts\";\nimport { cloudflareFailureSignals, safeCauseMessage } from \"./boundary.ts\";\nimport { AdmissionLimitExceeded } from \"./config.ts\";\n\n/**\n * The Worker↔Conversation-Object host protocol (plan §1.4): Schema envelopes for the host\n * entry points (`submitEncoded`, `awaitSettlementEncoded`, `observePage`, `abortEncoded`,\n * `resolveApprovalEncoded`, `resolveUnknownEncoded`) plus the Worker-side client that speaks\n * it. Mirrors the WP2 port protocol: requests and responses are closed Schema unions, typed\n * failures travel as their own tagged classes and RE-DECODE to identical tags on the caller\n * (error-tag fidelity), and protocol anomalies are answered typed instead of thrown.\n */\n\n/** Ceiling for host protocol diagnostic strings. */\nconst MAX_HOST_DIAGNOSTIC_LENGTH = 4_096;\n\nconst BoundedDiagnostic = Schema.String.check(Schema.isMaxLength(MAX_HOST_DIAGNOSTIC_LENGTH));\n\n/** Truncate a diagnostic string to the host protocol's bounded length. */\nexport const boundHostDiagnostic = (value: string): string =>\n value.length > MAX_HOST_DIAGNOSTIC_LENGTH\n ? `${value.slice(0, MAX_HOST_DIAGNOSTIC_LENGTH - 3)}...`\n : value;\n\n/**\n * The envelope itself could not be honored: the Object could not decode the request, or a\n * response could not be encoded/decoded. Never carries operation semantics.\n */\nexport class HostProtocolError extends Schema.TaggedError<HostProtocolError>()(\n \"HostProtocolError\",\n {\n message: BoundedDiagnostic,\n },\n) {}\n\n/** The Worker-side stub call itself failed (RPC rejection, overload, eviction mid-call). */\nexport class ConversationClientError extends Schema.TaggedError<ConversationClientError>()(\n \"ConversationClientError\",\n {\n conversationId: Schema.String,\n message: Schema.String,\n cause: Schema.optionalKey(Schema.Defect()),\n /** Cloudflare's own classification for a failure safe to retry with a fresh stub. */\n retryable: Schema.optionalKey(Schema.Boolean),\n /** Cloudflare overloads are surfaced immediately instead of adding retry pressure. */\n overloaded: Schema.optionalKey(Schema.Boolean),\n },\n) {}\n\n// ---------------------------------------------------------------------------\n// Requests\n// ---------------------------------------------------------------------------\n\n/**\n * One durable submission, input ALREADY encoded by the caller through the Agent Binding's\n * input schema (the Worker bundles the same Agent definitions as the Object, so schema\n * validation happens client-side; the resolved Binding re-validates at claim time). The\n * Conversation identity is deliberately absent — the addressed Object IS the lane.\n */\nexport class SubmitRequest extends Schema.Class<SubmitRequest>(\n \"@effect-agent/platform-cloudflare/SubmitRequest\",\n)({\n agentId: AgentId,\n principal: Principal,\n idempotencyKey: IdempotencyKey,\n definitions: DefinitionDigests,\n inputPayload: PersistedJson,\n}) {}\n\n/** One bounded page of canonical records after an optional sequence. */\nexport class ObservePageRequest extends Schema.Class<ObservePageRequest>(\n \"@effect-agent/platform-cloudflare/ObservePageRequest\",\n)({\n afterSequence: Schema.optionalKey(CanonicalSequence),\n limit: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1_024)),\n}) {}\n\n/** One event-driven wait for canonical progress strictly after this sequence. */\nexport class AwaitProgressRequest extends Schema.Class<AwaitProgressRequest>(\n \"@effect-agent/platform-cloudflare/AwaitProgressRequest\",\n)({\n afterSequence: CanonicalSequence,\n waiterId: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)),\n}) {}\n\n/** Best-effort cancellation of one in-flight progress RPC. */\nexport class CancelProgressRequest extends Schema.Class<CancelProgressRequest>(\n \"@effect-agent/platform-cloudflare/CancelProgressRequest\",\n)({\n waiterId: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)),\n}) {}\n\n// ---------------------------------------------------------------------------\n// Responses\n// ---------------------------------------------------------------------------\n\n/**\n * Every typed failure a host entry point can produce, plus the protocol's own errors. Same\n * closed-union discipline as the WP2 `PortFailure`: members re-decode to the SAME tagged\n * classes on the Worker side; `cause` chains travel as Schema defects without instance\n * fidelity (plan §2.8).\n */\nexport const HostFailure = Schema.Union([\n AgentInputError,\n DigestError,\n AdmissionConflict,\n SettlementConflict,\n ApprovalConflict,\n UnknownResolutionConflict,\n JoinedToHost,\n LedgerError,\n ConversationStoreError,\n ConversationNotMaterialized,\n AppendConflict,\n FenceRejected,\n DurableRuntimeFailpointError,\n AdmissionLimitExceeded,\n DurableAlarmError,\n OperationDenied,\n HostProtocolError,\n]);\nexport type HostFailure = typeof HostFailure.Type;\n\nexport class SubmitSucceeded extends Schema.TaggedClass<SubmitSucceeded>(\n \"@effect-agent/platform-cloudflare/SubmitSucceeded\",\n)(\"SubmitSucceeded\", {\n receipt: Receipt,\n}) {}\n\nexport class SettlementReached extends Schema.TaggedClass<SettlementReached>(\n \"@effect-agent/platform-cloudflare/SettlementReached\",\n)(\"SettlementReached\", {\n settlement: Settlement,\n}) {}\n\nexport class ObservedPage extends Schema.TaggedClass<ObservedPage>(\n \"@effect-agent/platform-cloudflare/ObservedPage\",\n)(\"ObservedPage\", {\n records: Schema.Array(CanonicalRecordEnvelope).check(Schema.isMaxLength(1_024)),\n}) {}\n\n/** A record was already committed or an incarnation-local hint says the caller should re-read. */\nexport class ProgressObserved extends Schema.TaggedClass<ProgressObserved>(\n \"@effect-agent/platform-cloudflare/ProgressObserved\",\n)(\"ProgressObserved\", {}) {}\n\nexport class ProgressCancelled extends Schema.TaggedClass<ProgressCancelled>(\n \"@effect-agent/platform-cloudflare/ProgressCancelled\",\n)(\"ProgressCancelled\", {}) {}\n\nexport class AbortRecorded extends Schema.TaggedClass<AbortRecorded>(\n \"@effect-agent/platform-cloudflare/AbortRecorded\",\n)(\"AbortRecorded\", {\n intent: AbortIntent,\n}) {}\n\nexport class ApprovalRecorded extends Schema.TaggedClass<ApprovalRecorded>(\n \"@effect-agent/platform-cloudflare/ApprovalRecorded\",\n)(\"ApprovalRecorded\", {\n intent: ApprovalDecisionIntent,\n}) {}\n\nexport class UnknownResolutionRecorded extends Schema.TaggedClass<UnknownResolutionRecorded>(\n \"@effect-agent/platform-cloudflare/UnknownResolutionRecorded\",\n)(\"UnknownResolutionRecorded\", {\n intent: UnknownResolutionIntent,\n}) {}\n\n/** The entry point failed TYPED on the Object; the failure re-decodes verbatim. */\nexport class HostFailed extends Schema.TaggedClass<HostFailed>(\n \"@effect-agent/platform-cloudflare/HostFailed\",\n)(\"HostFailed\", {\n failure: HostFailure,\n}) {}\n\n/** The uniform answer of one host entry point. Callers narrow by the tag their call implies. */\nexport const HostResponse = Schema.Union([\n SubmitSucceeded,\n SettlementReached,\n ObservedPage,\n ProgressObserved,\n ProgressCancelled,\n AbortRecorded,\n ApprovalRecorded,\n UnknownResolutionRecorded,\n HostFailed,\n]);\nexport type HostResponse = typeof HostResponse.Type;\n\n// ---------------------------------------------------------------------------\n// Codecs (shared by the Object endpoints and the Worker client)\n// ---------------------------------------------------------------------------\n\nexport const decodeSubmitRequest = Schema.decodeUnknownEffect(SubmitRequest);\nexport const encodeSubmitRequest = Schema.encodeEffect(SubmitRequest);\nexport const decodeReceipt = Schema.decodeUnknownEffect(Receipt);\nexport const encodeReceipt = Schema.encodeEffect(Receipt);\nexport const decodeObservePageRequest = Schema.decodeUnknownEffect(ObservePageRequest);\nexport const encodeObservePageRequest = Schema.encodeEffect(ObservePageRequest);\nexport const decodeAwaitProgressRequest = Schema.decodeUnknownEffect(AwaitProgressRequest);\nexport const encodeAwaitProgressRequest = Schema.encodeEffect(AwaitProgressRequest);\nexport const decodeCancelProgressRequest = Schema.decodeUnknownEffect(CancelProgressRequest);\nexport const encodeCancelProgressRequest = Schema.encodeEffect(CancelProgressRequest);\nexport const decodeAbortCommand = Schema.decodeUnknownEffect(AbortCommand);\nexport const encodeAbortCommand = Schema.encodeEffect(AbortCommand);\nexport const decodeApprovalDecisionCommand = Schema.decodeUnknownEffect(ApprovalDecisionCommand);\nexport const encodeApprovalDecisionCommand = Schema.encodeEffect(ApprovalDecisionCommand);\nexport const decodeUnknownResolutionCommand = Schema.decodeUnknownEffect(UnknownResolutionCommand);\nexport const encodeUnknownResolutionCommand = Schema.encodeEffect(UnknownResolutionCommand);\nexport const encodeHostResponse = Schema.encodeEffect(HostResponse);\nexport const decodeHostResponse = Schema.decodeUnknownEffect(HostResponse);\n\n// ---------------------------------------------------------------------------\n// Worker-side client\n// ---------------------------------------------------------------------------\n\n/** Failure surface of `CloudflareConversationClient.submit`. */\nconst ClientSubmitHostFailure = Schema.Union([\n AgentInputError,\n DigestError,\n AdmissionConflict,\n LedgerError,\n ConversationStoreError,\n ConversationNotMaterialized,\n AppendConflict,\n FenceRejected,\n DurableRuntimeFailpointError,\n AdmissionLimitExceeded,\n DurableAlarmError,\n HostProtocolError,\n]);\nconst ClientAwaitHostFailure = Schema.Union([LedgerError, SettlementConflict, HostProtocolError]);\nconst ClientObserveHostFailure = Schema.Union([\n ConversationStoreError,\n ConversationNotMaterialized,\n OperationDenied,\n HostProtocolError,\n]);\nconst ClientAbortHostFailure = Schema.Union([\n LedgerError,\n SettlementConflict,\n JoinedToHost,\n DurableRuntimeFailpointError,\n DurableAlarmError,\n HostProtocolError,\n]);\nconst ClientApprovalHostFailure = Schema.Union([\n LedgerError,\n SettlementConflict,\n ApprovalConflict,\n OperationDenied,\n DurableAlarmError,\n HostProtocolError,\n]);\nconst ClientUnknownHostFailure = Schema.Union([\n LedgerError,\n SettlementConflict,\n UnknownResolutionConflict,\n JoinedToHost,\n DurableRuntimeFailpointError,\n OperationDenied,\n DurableAlarmError,\n HostProtocolError,\n]);\n\nexport type ClientSubmitFailure = typeof ClientSubmitHostFailure.Type | ConversationClientError;\nexport type ClientAwaitFailure = typeof ClientAwaitHostFailure.Type | ConversationClientError;\nexport type ClientObserveFailure = typeof ClientObserveHostFailure.Type | ConversationClientError;\nexport type ClientProgressFailure = ClientObserveFailure;\nexport type ClientAbortFailure = typeof ClientAbortHostFailure.Type | ConversationClientError;\nexport type ClientApprovalFailure = typeof ClientApprovalHostFailure.Type | ConversationClientError;\nexport type ClientUnknownFailure = typeof ClientUnknownHostFailure.Type | ConversationClientError;\n\nconst outOfContract = (\n conversationId: string,\n operation: string,\n observed: string,\n): ConversationClientError =>\n ConversationClientError.make({\n conversationId,\n message: boundHostDiagnostic(\n `The Conversation Object answered ${operation} with the out-of-contract ${observed}.`,\n ),\n });\n\nconst hostRpcMethods = {\n submit: \"submitEncoded\",\n awaitSettlement: \"awaitSettlementEncoded\",\n awaitProgress: \"awaitProgressEncoded\",\n cancelProgress: \"cancelProgressEncoded\",\n observePage: \"observePage\",\n abort: \"abortEncoded\",\n resolveApproval: \"resolveApprovalEncoded\",\n resolveUnknown: \"resolveUnknownEncoded\",\n} as const satisfies Record<string, keyof ConversationObjectRpc>;\n\n/** Worker-side client over the Conversation Object namespace (DEPLOY-010). */\nexport class CloudflareConversationClient extends Context.Service<\n CloudflareConversationClient,\n {\n /** Encode the input client-side, then durably submit to the owning Object. */\n readonly submit: <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: DurableSubmitOptions,\n ) => Effect.Effect<Receipt, ClientSubmitFailure, InputSchema[\"EncodingServices\"]>;\n /** Wake-hinted, poll-guaranteed settlement wait executed inside the owning Object. */\n readonly awaitSettlement: (receipt: Receipt) => Effect.Effect<Settlement, ClientAwaitFailure>;\n /**\n * Wait without polling until progress after `afterSequence` is already durable or hinted.\n * The result is deliberately void: canonical records remain authoritative and must be read.\n */\n readonly awaitProgress: (\n conversationId: ConversationId,\n afterSequence: CanonicalSequence,\n ) => Effect.Effect<void, ClientProgressFailure>;\n /** One bounded page of canonical records. */\n readonly readPage: (\n conversationId: ConversationId,\n options?: {\n readonly afterSequence?: CanonicalSequence | undefined;\n readonly limit?: number | undefined;\n },\n ) => Effect.Effect<ReadonlyArray<CanonicalRecordEnvelope>, ClientObserveFailure>;\n /**\n * Every canonical record up to the CURRENT committed tail, via repeated pages. A\n * snapshot read, not a live observation — callers wanting liveness re-read after\n * `awaitSettlement`.\n */\n readonly readAll: (\n conversationId: ConversationId,\n ) => Effect.Effect<ReadonlyArray<CanonicalRecordEnvelope>, ClientObserveFailure>;\n /**\n * Submission-addressed operations take the owning Conversation explicitly (from the\n * Receipt): minted Submission identities stay OPAQUE outside the storage adapter that\n * minted them (D-P6-5), so the client never parses one to find the lane.\n */\n readonly abort: (\n conversationId: ConversationId,\n command: AbortCommand,\n ) => Effect.Effect<AbortIntent, ClientAbortFailure>;\n readonly resolveApproval: (\n conversationId: ConversationId,\n command: ApprovalDecisionCommand,\n ) => Effect.Effect<ApprovalDecisionIntent, ClientApprovalFailure>;\n readonly resolveUnknown: (\n conversationId: ConversationId,\n command: UnknownResolutionCommand,\n ) => Effect.Effect<UnknownResolutionIntent, ClientUnknownFailure>;\n }\n>()(\"@effect-agent/platform-cloudflare/CloudflareConversationClient\") {\n static readonly layer: Layer.Layer<\n CloudflareConversationClient,\n never,\n ConversationObjectNamespace | Crypto.Crypto\n > = Layer.effect(CloudflareConversationClient)(\n Effect.gen(function* () {\n const { namespace, rpcTracing } = yield* ConversationObjectNamespace;\n const crypto = yield* Crypto.Crypto;\n\n const call = Effect.fn(\n function* (\n conversationId: string,\n operation: keyof typeof hostRpcMethods,\n encoded: unknown,\n ): Effect.fn.Return<HostResponse, ConversationClientError | HostProtocolError> {\n // Empty arguments preserve native arity. Passing `undefined` still adds an argument.\n const traceArgs =\n rpcTracing === undefined ? [] : yield* RpcTracing.withRpcTraceContext([]);\n const raw = yield* Effect.tryPromise({\n try: () => {\n const stub = namespace.get(namespace.idFromName(conversationId));\n return stub[hostRpcMethods[operation]](encoded, ...traceArgs);\n },\n catch: (cause) =>\n ConversationClientError.make({\n conversationId,\n message: boundHostDiagnostic(\n `${operation} did not reach the Conversation Object: ${safeCauseMessage(\n cause,\n \"the RPC failed without a diagnostic\",\n )}`,\n ),\n cause,\n ...cloudflareFailureSignals(cause),\n }),\n });\n return yield* decodeHostResponse(raw).pipe(\n Effect.mapError(\n (error): HostProtocolError =>\n HostProtocolError.make({\n message: boundHostDiagnostic(\n `The ${operation} answer could not be decoded: ${error.message}`,\n ),\n }),\n ),\n );\n },\n (effect, conversationId, operation) =>\n rpcTracing === undefined\n ? Effect.withSpan(effect, \"CloudflareConversationClient.call\", {\n attributes: { conversationId, operation },\n })\n : RpcTracing.withRpcClientSpan(effect, rpcTracing, hostRpcMethods[operation]),\n );\n\n const expect = <ResultSchema extends Schema.Top, FailureSchema extends Schema.Top>(\n conversationId: string,\n operation: string,\n resultSchema: ResultSchema,\n failureSchema: FailureSchema,\n ) => {\n const isExpectedResult = Schema.is(resultSchema);\n const isExpectedFailure = Schema.is(failureSchema);\n return (\n response: HostResponse,\n ): Effect.Effect<ResultSchema[\"Type\"], FailureSchema[\"Type\"] | ConversationClientError> => {\n if (response._tag === \"HostFailed\") {\n const failure = response.failure;\n return isExpectedFailure(failure)\n ? Effect.fail(failure)\n : Effect.fail(outOfContract(conversationId, operation, `failure ${failure._tag}`));\n }\n if (!isExpectedResult(response)) {\n return Effect.fail(outOfContract(conversationId, operation, `result ${response._tag}`));\n }\n return Effect.succeed(response);\n };\n };\n\n const readPage = (\n conversationId: ConversationId,\n options?: {\n readonly afterSequence?: CanonicalSequence | undefined;\n readonly limit?: number | undefined;\n },\n ) =>\n Effect.gen(function* () {\n const request = ObservePageRequest.make({\n ...(options?.afterSequence === undefined\n ? {}\n : { afterSequence: options.afterSequence }),\n limit: options?.limit ?? 256,\n });\n const encoded = yield* encodeObservePageRequest(request).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`observePage request encode failed: ${error.message}`),\n }),\n ),\n );\n const response = yield* call(conversationId, \"observePage\", encoded);\n const page = yield* expect(\n conversationId,\n \"observePage\",\n ObservedPage,\n ClientObserveHostFailure,\n )(response);\n return page.records;\n });\n\n const cancelProgress = (\n conversationId: ConversationId,\n waiterId: string,\n ): Effect.Effect<void> =>\n encodeCancelProgressRequest(CancelProgressRequest.make({ waiterId })).pipe(\n Effect.mapError(() => undefined),\n Effect.flatMap((encoded) => call(conversationId, \"cancelProgress\", encoded)),\n Effect.asVoid,\n Effect.ignore,\n );\n\n return CloudflareConversationClient.of({\n submit: <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: DurableSubmitOptions,\n ) =>\n Effect.gen(function* () {\n // Client-side half of `DurableAgentRuntime.submit`'s input boundary: encode\n // through the Agent's input schema and prove the canonical persistence bounds.\n const encodedInput = yield* Schema.encodeEffect(agent.definition.input)(input).pipe(\n Effect.mapError((cause) =>\n AgentInputError.make({ message: `Unable to encode Agent input: ${cause.message}` }),\n ),\n );\n const inputPayload = yield* Schema.decodeUnknownEffect(PersistedJson)(\n encodedInput,\n ).pipe(\n Effect.mapError(() =>\n AgentInputError.make({\n message: \"Agent input does not satisfy the canonical persistence bounds\",\n }),\n ),\n );\n const request = SubmitRequest.make({\n agentId: agent.definition.id,\n principal: options.principal,\n idempotencyKey: options.idempotencyKey,\n definitions: options.definitions,\n inputPayload,\n });\n const encoded = yield* encodeSubmitRequest(request).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`submit request encode failed: ${error.message}`),\n }),\n ),\n );\n const response = yield* call(options.conversationId, \"submit\", encoded);\n const succeeded = yield* expect(\n options.conversationId,\n \"submit\",\n SubmitSucceeded,\n ClientSubmitHostFailure,\n )(response);\n return succeeded.receipt;\n }),\n\n awaitSettlement: (receipt) =>\n Effect.gen(function* () {\n const encoded = yield* encodeReceipt(receipt).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`receipt encode failed: ${error.message}`),\n }),\n ),\n );\n const response = yield* call(receipt.conversationId, \"awaitSettlement\", encoded);\n const settled = yield* expect(\n receipt.conversationId,\n \"awaitSettlement\",\n SettlementReached,\n ClientAwaitHostFailure,\n )(response);\n return settled.settlement;\n }),\n\n awaitProgress: (conversationId, afterSequence) =>\n Effect.gen(function* () {\n const waiterId = yield* crypto.randomUUIDv4.pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(\n `awaitProgress cancellation identity generation failed: ${error.message}`,\n ),\n }),\n ),\n );\n const request = AwaitProgressRequest.make({ afterSequence, waiterId });\n const encoded = yield* encodeAwaitProgressRequest(request).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(\n `awaitProgress request encode failed: ${error.message}`,\n ),\n }),\n ),\n );\n\n const attempt = (retry: number): Effect.Effect<void, ClientProgressFailure> =>\n call(conversationId, \"awaitProgress\", encoded).pipe(\n Effect.flatMap(\n expect(\n conversationId,\n \"awaitProgress\",\n ProgressObserved,\n ClientObserveHostFailure,\n ),\n ),\n Effect.asVoid,\n Effect.catchTag(\"ConversationClientError\", (error) =>\n error.retryable === true && error.overloaded !== true && retry < 5\n ? Effect.sleep(Duration.millis(10 * 2 ** retry)).pipe(\n Effect.andThen(attempt(retry + 1)),\n )\n : Effect.fail(error),\n ),\n );\n\n yield* attempt(0).pipe(\n Effect.onInterrupt(() => cancelProgress(conversationId, waiterId)),\n );\n }),\n\n readPage,\n\n readAll: (conversationId) =>\n Effect.gen(function* () {\n const all: Array<CanonicalRecordEnvelope> = [];\n let after: CanonicalSequence | undefined;\n for (;;) {\n const page = yield* readPage(conversationId, { afterSequence: after, limit: 1_024 });\n all.push(...page);\n const last = page.at(-1);\n if (page.length < 1_024 || last === undefined) return all;\n after = last.sequence;\n }\n }),\n\n abort: (conversationId, command) =>\n Effect.gen(function* () {\n const encoded = yield* encodeAbortCommand(command).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`abort command encode failed: ${error.message}`),\n }),\n ),\n );\n const response = yield* call(conversationId, \"abort\", encoded);\n const recorded = yield* expect(\n conversationId,\n \"abort\",\n AbortRecorded,\n ClientAbortHostFailure,\n )(response);\n return recorded.intent;\n }),\n\n resolveApproval: (conversationId, command) =>\n Effect.gen(function* () {\n const encoded = yield* encodeApprovalDecisionCommand(command).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`approval command encode failed: ${error.message}`),\n }),\n ),\n );\n const response = yield* call(conversationId, \"resolveApproval\", encoded);\n const recorded = yield* expect(\n conversationId,\n \"resolveApproval\",\n ApprovalRecorded,\n ClientApprovalHostFailure,\n )(response);\n return recorded.intent;\n }),\n\n resolveUnknown: (conversationId, command) =>\n Effect.gen(function* () {\n const encoded = yield* encodeUnknownResolutionCommand(command).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(\n `resolution command encode failed: ${error.message}`,\n ),\n }),\n ),\n );\n const response = yield* call(conversationId, \"resolveUnknown\", encoded);\n const recorded = yield* expect(\n conversationId,\n \"resolveUnknown\",\n UnknownResolutionRecorded,\n ClientUnknownHostFailure,\n )(response);\n return recorded.intent;\n }),\n });\n }),\n );\n}\n","import type { AgentId } from \"@effect-agent/core\";\nimport { SubmissionId } from \"@effect-agent/core\";\nimport {\n AppendConflict,\n ConversationNotMaterialized,\n ConversationRead,\n ConversationStore,\n ConversationStoreError,\n DigestError,\n DurableAgentRuntime,\n DurableRuntimeFailpointError,\n FenceRejected,\n IntegrityReport,\n LedgerError,\n ObligationReport,\n ObligationThresholds,\n OperationAuthorizationRequest,\n OperationAuthorizer,\n OperationDenied,\n OwnershipLost,\n PersistedJson,\n RecoveryExplanation,\n RecoveryReport,\n RetryCommand,\n RetryRefused,\n RunJournalError,\n SettlementConflict,\n SubmissionLedger,\n SubmissionLookupByKey,\n WakeScheduler,\n type DurableSubmitAgent,\n} from \"@effect-agent/session\";\nimport {\n decodePortRequest,\n encodePortResponse,\n type PortRequest,\n} from \"@effect-agent/storage-cloudflare\";\nimport { Effect, Layer, Option, Schema, Stream } from \"effect\";\nimport {\n DurableObject as EffectCfDurableObject,\n DurableObjectState as EffectCfDurableObjectState,\n WorkerEnvironment,\n} from \"effect-cf\";\n\nimport {\n ConversationMaintenance,\n DurableAlarmError,\n DurableAlarmService,\n type MaintenancePassFailure,\n} from \"./alarm.ts\";\nimport {\n ConversationObjectIdentity,\n DurableObjectContext,\n ConversationObjectNamespace,\n conversationNamespaceFromEnv,\n type CloudflareBindingError,\n} from \"./bindings.ts\";\nimport {\n AbortRecorded,\n ApprovalRecorded,\n HostFailed,\n HostProtocolError,\n ObservedPage,\n ProgressObserved,\n ProgressCancelled,\n SettlementReached,\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} from \"./client.ts\";\nimport { AdmissionLimitExceeded, CloudflareDurableRuntimeConfig } from \"./config.ts\";\nimport {\n CloudflareDurableRuntime,\n ConversationObjectPorts,\n type CloudflareDurableRuntimeInitializationError,\n type CloudflareDurableRuntimeOptions,\n type CloudflareDurableRuntimeServices,\n} from \"./layers.ts\";\nimport { ProgressWaitRegistry } from \"./progress-wait.ts\";\n\n/**\n * `makeConversationObjectClass(options, observability?)` — the Conversation 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 Conversation 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` + `processConversationResolved` pass, and the persisted alarm\n * (the single multiplexed slot, D-P6-2) finishes accepted work across evictions WITHOUT any\n * incoming request.\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 Conversation Object class. */\nexport interface ConversationObjectOptions 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 Conversation 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}\n\ntype EndpointServices = CloudflareDurableRuntimeServices | DurableObjectContext;\ntype RuntimeServices = EndpointServices | ConversationObjectNamespace;\ntype ConversationObjectInitializationError =\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 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(\"ConversationObject.gateAdmissionLimits\")(\n function* (request: {\n readonly principal: SubmissionLookupByKey[\"principal\"];\n readonly idempotencyKey: SubmissionLookupByKey[\"idempotencyKey\"];\n readonly inputPayload: PersistedJson;\n }) {\n const identity = yield* ConversationObjectIdentity;\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 conversationId: identity.conversationId,\n principal: request.principal,\n idempotencyKey: request.idempotencyKey,\n }),\n );\n if (Option.isSome(existing)) return;\n\n const inputBytes = utf8Bytes(request.inputPayload);\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 // One Conversation per Object (durability §5): the local scan IS this lane's queue.\n const nonterminal = yield* Stream.runCollect(ledger.scanNonterminal);\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 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/**\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\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* ConversationObjectIdentity;\n const maintenance = yield* ConversationMaintenance;\n const runtime = yield* DurableAgentRuntime;\n yield* gateAdmissionLimits(request);\n // Alarm invariant: the generation + alarm commit BEFORE the admission, and maintenance\n // cannot acknowledge that generation until this mutation leaves its public RPC seam.\n const receipt = yield* maintenance.withMutation(\n runtime.submit(passthroughSubmitAgent(request.agentId), request.inputPayload, {\n conversationId: identity.conversationId,\n principal: request.principal,\n idempotencyKey: request.idempotencyKey,\n definitions: request.definitions,\n }),\n );\n return SubmitSucceeded.make({ 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 runtime = yield* DurableAgentRuntime;\n const settlement = yield* runtime.awaitSettlement(receipt);\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* ConversationObjectIdentity;\n const runtime = yield* DurableAgentRuntime;\n const registry = yield* ProgressWaitRegistry;\n yield* Effect.scoped(\n Effect.gen(function* () {\n const cancelled = yield* registry.subscribe(request.waiterId);\n yield* Effect.raceFirst(\n runtime.awaitProgress(identity.conversationId, request.afterSequence),\n cancelled,\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 registry = yield* ProgressWaitRegistry;\n yield* registry.cancel(request.waiterId);\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* ConversationObjectIdentity;\n const store = yield* ConversationStore;\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 yield* authorizer.authorize(\n OperationAuthorizationRequest.make({\n operation: \"observe\",\n conversationId: identity.conversationId,\n }),\n );\n const records = yield* Stream.runCollect(\n store.read(\n ConversationRead.make({\n conversationId: identity.conversationId,\n ...(request.afterSequence === undefined\n ? {}\n : { afterSequence: request.afterSequence }),\n limit: request.limit,\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 maintenance = yield* ConversationMaintenance;\n const runtime = yield* DurableAgentRuntime;\n const intent = yield* maintenance.withMutation(runtime.abort(command));\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 maintenance = yield* ConversationMaintenance;\n const runtime = yield* DurableAgentRuntime;\n const intent = yield* maintenance.withMutation(runtime.resolveApproval(command));\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 maintenance = yield* ConversationMaintenance;\n const runtime = yield* DurableAgentRuntime;\n const intent = yield* maintenance.withMutation(runtime.resolveUnknown(command));\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 OperationDenied,\n RetryRefused,\n LedgerError,\n RunJournalError,\n DigestError,\n OwnershipLost,\n SettlementConflict,\n ConversationStoreError,\n ConversationNotMaterialized,\n AppendConflict,\n FenceRejected,\n DurableRuntimeFailpointError,\n DurableAlarmError,\n HostProtocolError,\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]);\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* ConversationObjectIdentity;\n const runtime = yield* DurableAgentRuntime;\n const explanations =\n request.submissionId === undefined\n ? yield* runtime.explainConversation(identity.conversationId)\n : [yield* runtime.explain(request.submissionId)];\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* ConversationObjectIdentity;\n const runtime = yield* DurableAgentRuntime;\n const report = yield* runtime.verify(identity.conversationId);\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* ConversationMaintenance;\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 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 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 portCallEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n Effect.gen(function* () {\n const ports = yield* ConversationObjectPorts;\n const maintenance = yield* ConversationMaintenance;\n const alarm = yield* DurableAlarmService;\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 if (decoded._tag === \"failure\") {\n return encodedPortProtocolFailure(\n `The port request could not be decoded: ${decoded.message}`,\n );\n }\n const mutating = isMutatingPortRequest(decoded.request);\n const handled = yield* (\n mutating\n ? maintenance.withMutation(ports.handle(decoded.request))\n : ports.handle(decoded.request)\n ).pipe(Effect.exit);\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 const response = yield* encodePortResponse(handled.value).pipe(\n Effect.catch((error) =>\n Effect.succeed(\n encodedPortProtocolFailure(`The port response could not be encoded: ${error.message}`),\n ),\n ),\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(\"ConversationObject.portCall: immediate re-arm failed\", error),\n ),\n );\n }\n return response;\n });\n\nconst wakeEndpoint: Effect.Effect<void, never, EndpointServices> = Effect.gen(function* () {\n const identity = yield* ConversationObjectIdentity;\n const wake = yield* WakeScheduler;\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.conversationId);\n});\n\nconst alarmEndpoint: Effect.Effect<void, MaintenancePassFailure, EndpointServices> = Effect.gen(\n function* () {\n const maintenance = yield* ConversationMaintenance;\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 ConversationMaintenance 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* ConversationMaintenance;\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 | ConversationObjectNamespace,\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 return DurableObjectContext.of({ ctx: state.raw, env });\n }),\n );\n const namespace = Layer.effect(ConversationObjectNamespace)(\n Effect.gen(function* () {\n const env = yield* WorkerEnvironment;\n const binding = yield* conversationNamespaceFromEnv(env, namespaceBinding);\n return ConversationObjectNamespace.of({\n namespace: binding,\n ...(rpcTracing === true ? { rpcTracing: namespaceBinding } : {}),\n });\n }),\n );\n return Layer.merge(context, namespace);\n};\n\n/** The public endpoints and effect-cf invocation hook of one Conversation Object instance. */\nexport interface ConversationObjectInstance<EventServices = never> extends InstanceType<\n EffectCfDurableObject.DurableObjectClass<Record<never, never>, RuntimeServices | EventServices>\n> {\n submitEncoded(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 Conversation Object. */\nexport interface ConversationObjectClass<EventServices = never> {\n new (ctx: DurableObjectState, env: Cloudflare.Env): ConversationObjectInstance<EventServices>;\n}\n\n/**\n * Build the application's Conversation Object class (export it from the Worker entry).\n * effect-cf owns the cached ManagedRuntime, native RPC methods, event scopes, and post-handler\n * OTLP flush scheduling for RPC and alarm events. The optional outer Layer is built per native\n * event, so a host can install Tracer/Logger/Metric services and `OtlpExporter.Flusher` without\n * Effect Agent owning exporter lifecycle machinery.\n */\nexport const makeConversationObjectClass = <EventLayerError = never, EventServices = never>(\n options: ConversationObjectOptions,\n observability?: Layer.Layer<\n EventServices,\n EventLayerError,\n | DurableObjectContext\n | ConversationObjectNamespace\n | EffectCfDurableObjectState.DurableObjectState\n | WorkerEnvironment\n >,\n): ConversationObjectClass<EventServices> => {\n const application: Layer.Layer<\n RuntimeServices,\n CloudflareDurableRuntimeInitializationError | CloudflareBindingError,\n EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment\n > = CloudflareDurableRuntime.layer(options).pipe(\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,\n ConversationObjectInitializationError,\n EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment\n > = Layer.effectContext(\n Effect.gen(function* () {\n const state = yield* EffectCfDurableObjectState.DurableObjectState;\n const scope = yield* Effect.scope;\n return yield* state.blockConcurrencyWhile(\n Effect.gen(function* () {\n const services = yield* Layer.buildWithScope(application, scope);\n yield* gateEndpoint.pipe(Effect.provide(services));\n return services;\n }),\n );\n }),\n );\n\n const rpc = {\n submitEncoded: (encoded: unknown) => submitEndpoint(encoded),\n awaitSettlementEncoded: (encoded: unknown) => awaitSettlementEndpoint(encoded),\n awaitProgressEncoded: (encoded: unknown) => awaitProgressEndpoint(encoded),\n cancelProgressEncoded: (encoded: unknown) => cancelProgressEndpoint(encoded),\n observePage: (encoded: unknown) => observePageEndpoint(encoded),\n abortEncoded: (encoded: unknown) => abortEndpoint(encoded),\n resolveApprovalEncoded: (encoded: unknown) => resolveApprovalEndpoint(encoded),\n resolveUnknownEncoded: (encoded: unknown) => resolveUnknownEndpoint(encoded),\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 portCall: (encoded: unknown) => portCallEndpoint(encoded),\n wake: () => wakeEndpoint,\n } satisfies EffectCfDurableObject.DurableObjectRpc<RuntimeServices | EventServices>;\n\n const EffectCfConversationObject = EffectCfDurableObject.make<\n RuntimeServices,\n ConversationObjectInitializationError,\n EventServices,\n EventLayerError,\n typeof rpc\n >(runtime, {\n ...(options.rpcTracing === true ? { rpcTracing: { service: options.namespaceBinding } } : {}),\n ...(observability === undefined ? {} : { eventLayer: observability }),\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 });\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 ConversationObject extends EffectCfConversationObject {\n override alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> | void {\n return super.alarm?.(alarmInfo);\n }\n }\n\n return ConversationObject;\n};\n","import {\n CodeExecutionHost,\n CodeExecutionResourceUse,\n CodeExecutionResult,\n CodeExecutionTimeoutError,\n CodeExecutor,\n CodeExecutorStartError,\n CodeExecutorTerminatedError,\n CodeExecutorUnsupportedError,\n CodeExecutionProtocolError,\n CodeHostCall,\n CodeHostCallLimitError,\n CodeHostCallResult,\n CodeOutputLimitError,\n CodeProgramFailedError,\n CodeSourceError,\n SandboxImplementation,\n type CodeExecutorExecute,\n type CodeExecutionRequest,\n} from \"@effect-agent/sandbox\";\nimport { RpcTarget } from \"cloudflare:workers\";\nimport { Clock, Duration, Effect, Exit, Fiber, Layer, Option, Queue, Schema } from \"effect\";\n\nimport { safeCauseDiagnostic, safeCauseMessage } from \"./boundary.ts\";\n\n/**\n * The Cloudflare Dynamic Worker `CodeExecutor` adapter (C4 of ADR-0017;\n * DEPLOY-011). Each pass loads one fresh Worker through the Worker Loader\n * with `globalOutbound: null`, so generated code has no ambient network,\n * bindings, or secrets; its only authority is the pass-scoped RPC target that\n * routes back into the owning event's `CodeExecutionHost` service. Platform\n * CPU limits stop synchronous runaway programs; the executor-owned wall-clock\n * deadline interrupts asynchronously suspended passes. Deployment class `E`\n * only: the adapter records no persistent state and a later pass may run in a\n * completely different isolate.\n */\nexport const dynamicWorkerImplementation = SandboxImplementation.make({\n isolation: \"isolated\",\n identity: \"cloudflare-dynamic-worker\",\n});\n\ninterface CodeModePassHost extends Rpc.RpcTargetBranded {\n readonly call: (hostCall: unknown) => Promise<unknown>;\n}\n\ninterface CodeModeHarnessEntrypoint extends Rpc.WorkerEntrypointBranded {\n readonly run: (host: CodeModePassHost) => Promise<unknown>;\n}\n\n/**\n * One object-capability endpoint for one execution pass. Workers RPC invokes\n * the target in the request context where it was created, so the native\n * Promise returned by `dispatch` and the Effect fiber that settles it share\n * one I/O owner. Passing the target as `run()`'s argument also scopes the\n * remote stub to that RPC call; no request state lives at module scope.\n */\nclass CodeModePassHostTarget extends RpcTarget implements CodeModePassHost {\n readonly #dispatch: (hostCall: unknown) => Promise<unknown>;\n\n constructor(dispatch: (hostCall: unknown) => Promise<unknown>) {\n super();\n this.#dispatch = dispatch;\n }\n\n call(hostCall: unknown): Promise<unknown> {\n return this.#dispatch(hostCall);\n }\n}\n\n/**\n * The fixed harness loaded as the dynamic worker's main module. The generated\n * source becomes `program.mjs` (`export default (<expression>);`) — a module,\n * never `eval`. The harness installs namespace globals and a bounded console,\n * imports the program, invokes it exactly once, and returns one envelope the\n * host validates through Effect Schema.\n */\nconst HARNESS_MODULE = String.raw`\nimport { WorkerEntrypoint } from \"cloudflare:workers\";\nimport programDefault from \"./program.js\";\n\nconst encoder = new TextEncoder();\nconst utf8 = (text) => encoder.encode(text).byteLength;\nconst safeText = (value) => {\n try {\n if (value instanceof Error) return (value.name + \": \" + value.message).slice(0, 4000);\n if (typeof value === \"string\") return value.slice(0, 4000);\n const encoded = JSON.stringify(value);\n return (encoded === undefined ? String(value) : encoded).slice(0, 4000);\n } catch {\n return \"[unserializable value]\";\n }\n};\nconst safeJson = (value) => {\n try {\n const encoded = JSON.stringify(value);\n if (encoded !== undefined && encoded.length <= 4000) return JSON.parse(encoded);\n } catch {}\n return safeText(value);\n};\n\nexport default class CodeModeHarness extends WorkerEntrypoint {\n async run(host) {\n const config = this.env.CODE_MODE_PASS;\n const limits = config.limits;\n const logs = [];\n let logBytes = 0;\n let fatal;\n const boundedLogs = () => logs.slice(0, 4096);\n const write = (...values) => {\n const joined = values.map(safeText).join(\" \");\n const line = joined.length > 16000 ? joined.slice(0, 15999) + \"…\" : joined;\n const bytes = utf8(line);\n if (logs.length >= 4096 || logBytes + bytes > limits.maxLogBytes) {\n fatal = fatal ?? { _tag: \"log-limit\", observed: logBytes + bytes, logs: boundedLogs() };\n throw new Error(\"code-mode log limit exceeded\");\n }\n logs.push(line);\n logBytes += bytes;\n };\n globalThis.console = { log: write, info: write, warn: write, error: write, debug: write };\n\n let hostCalls = 0;\n const makeMethod = (namespace, method) => async (argument) => {\n hostCalls += 1;\n if (hostCalls > limits.maxHostCalls) {\n fatal = fatal ?? { _tag: \"host-call-limit\", logs: boundedLogs() };\n throw new Error(\"code-mode host-call limit exceeded\");\n }\n let argText;\n try {\n argText = JSON.stringify(argument);\n } catch {}\n if (argText === undefined || utf8(argText) > limits.maxHostCallArgumentBytes) {\n fatal = fatal ?? {\n _tag: \"argument-limit\",\n observed: argText === undefined ? 0 : utf8(argText),\n logs: boundedLogs(),\n };\n throw new Error(\"code-mode host-call argument limit exceeded\");\n }\n const outcome = await host.call({\n namespace,\n method,\n argument: JSON.parse(argText),\n });\n if (outcome !== null && typeof outcome === \"object\" && outcome._tag === \"CodeHostCallSuccess\") {\n return outcome.value;\n }\n if (outcome !== null && typeof outcome === \"object\" && outcome._tag === \"CodeHostCallFailure\") {\n throw outcome.error;\n }\n fatal = fatal ?? { _tag: \"protocol\", message: \"host returned an unrecognized outcome\" };\n throw new Error(\"code-mode host protocol violation\");\n };\n for (const namespace of config.namespaces) {\n const methods = {};\n for (const method of namespace.methods) {\n methods[method] = makeMethod(namespace.name, method);\n }\n globalThis[namespace.name] = methods;\n }\n\n // program.js is imported statically at the top of this module, so a\n // syntactically invalid program fails the whole harness at load (mapped\n // to a source error by the host). Using a static import keeps this module\n // free of dynamic-import expressions, which single-script Miniflare hosts\n // reject. The isolation boundary does NOT depend on the ordering of this\n // import versus the console/namespace shims installed below: the loaded\n // Worker has globalOutbound: null and no bindings, secrets, or env from\n // the Worker Loader config BEFORE any module in the graph evaluates, so\n // module-level program code has no ambient authority regardless. The\n // shims below are usability wrappers (bounded console, namespace globals),\n // and the accepted program is a single async-function expression whose\n // body runs only when invoked here — after the shims exist.\n const program = programDefault;\n if (typeof program !== \"function\") {\n return { _tag: \"source-not-a-function\", actual: typeof program };\n }\n try {\n const value = await program();\n if (fatal !== undefined) return fatal;\n let text;\n try {\n text = JSON.stringify(value);\n } catch {}\n if (text === undefined) {\n return {\n _tag: \"program-failed\",\n reason: \"non-json-result\",\n thrown: null,\n message: \"The program must return a JSON value\",\n logs: boundedLogs(),\n };\n }\n const resultBytes = utf8(text);\n if (resultBytes > limits.maxResultBytes) {\n return { _tag: \"result-limit\", observed: resultBytes, logs: boundedLogs() };\n }\n return {\n _tag: \"completed\",\n value: JSON.parse(text),\n logs: boundedLogs(),\n hostCalls,\n logBytes,\n resultBytes,\n };\n } catch (cause) {\n if (fatal !== undefined) return fatal;\n return {\n _tag: \"program-failed\",\n reason: cause instanceof Error ? \"threw\" : \"rejected\",\n thrown: safeJson(cause),\n message: safeText(cause),\n logs: boundedLogs(),\n };\n }\n }\n}\n`;\n\nconst BoundedLogs = Schema.Array(Schema.String.check(Schema.isMaxLength(16 * 1024))).check(\n Schema.isMaxLength(4_096),\n);\n\nconst HarnessCompleted = Schema.TaggedStruct(\"completed\", {\n value: Schema.Json,\n logs: BoundedLogs,\n hostCalls: Schema.Natural,\n logBytes: Schema.Natural,\n resultBytes: Schema.Natural,\n});\nconst HarnessSourceInvalid = Schema.TaggedStruct(\"source-invalid\", {\n message: Schema.String,\n});\nconst HarnessNotAFunction = Schema.TaggedStruct(\"source-not-a-function\", {\n actual: Schema.String,\n});\nconst HarnessProgramFailed = Schema.TaggedStruct(\"program-failed\", {\n reason: Schema.Literals([\"threw\", \"rejected\", \"non-json-result\"]),\n thrown: Schema.Json,\n message: Schema.String,\n logs: BoundedLogs,\n});\nconst HarnessLogLimit = Schema.TaggedStruct(\"log-limit\", {\n observed: Schema.Natural,\n logs: BoundedLogs,\n});\nconst HarnessArgumentLimit = Schema.TaggedStruct(\"argument-limit\", {\n observed: Schema.Natural,\n logs: BoundedLogs,\n});\nconst HarnessResultLimit = Schema.TaggedStruct(\"result-limit\", {\n observed: Schema.Natural,\n logs: BoundedLogs,\n});\nconst HarnessHostCallLimit = Schema.TaggedStruct(\"host-call-limit\", {\n logs: BoundedLogs,\n});\nconst HarnessProtocol = Schema.TaggedStruct(\"protocol\", {\n message: Schema.String,\n});\nconst HarnessOutcome = Schema.Union([\n HarnessCompleted,\n HarnessSourceInvalid,\n HarnessNotAFunction,\n HarnessProgramFailed,\n HarnessLogLimit,\n HarnessArgumentLimit,\n HarnessResultLimit,\n HarnessHostCallLimit,\n HarnessProtocol,\n]);\n\nconst HarnessPassConfig = Schema.Struct({\n namespaces: Schema.Array(\n Schema.Struct({\n name: Schema.NonEmptyString,\n methods: Schema.Array(Schema.NonEmptyString).check(Schema.isMaxLength(64)),\n }),\n ).check(Schema.isMaxLength(32)),\n limits: Schema.Struct({\n maxLogBytes: Schema.Natural,\n maxResultBytes: Schema.Natural,\n maxHostCalls: Schema.Natural,\n maxHostCallArgumentBytes: Schema.Natural,\n }),\n});\n\nconst encodeHarnessPassConfig = Schema.encodeSync(HarnessPassConfig);\nconst encodeJsonPayload = Schema.encodeSync(Schema.fromJsonString(Schema.Json));\nconst decodeJsonPayload = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Json));\n\nconst decodeHarnessOutcome = (value: unknown) => {\n try {\n return Schema.decodeUnknownOption(HarnessOutcome)(value);\n } catch {\n return Option.none<typeof HarnessOutcome.Type>();\n }\n};\n\nconst decodeHostCall = (value: unknown) => {\n try {\n return Schema.decodeUnknownOption(CodeHostCall)(value);\n } catch {\n return Option.none<CodeHostCall>();\n }\n};\n\nconst decodeHostCallResult = (value: unknown) => {\n try {\n return Schema.decodeUnknownOption(CodeHostCallResult)(value);\n } catch {\n return Option.none<CodeHostCallResult>();\n }\n};\n\n/** Dispose a Cloudflare RPC handle when the runtime supplies its untyped disposal hook. @internal */\nexport const disposeRpcHandle = (handle: unknown): Effect.Effect<void> =>\n Effect.try({\n try: () => {\n if ((typeof handle !== \"object\" && typeof handle !== \"function\") || handle === null) return;\n if (!(Symbol.dispose in handle)) return;\n const dispose = Reflect.get(handle, Symbol.dispose);\n if (typeof dispose === \"function\") {\n Reflect.apply(dispose, handle, []);\n }\n },\n catch: (cause) =>\n safeCauseDiagnostic(cause, \"The Cloudflare RPC disposal hook failed without a diagnostic\"),\n }).pipe(\n Effect.catch((diagnostic) =>\n Effect.logWarning(`Cloudflare RPC handle disposal failed: ${diagnostic}`).pipe(\n Effect.ignoreCause,\n ),\n ),\n );\n\n/**\n * Project a host outcome to the plain JSON envelope the harness reads. A\n * `CodeExecutionHost` may return either real `CodeHostCallResult` instances\n * (the substitute and conformance kit) or plain-object equivalents (the Code\n * Mode capability's broker route), so this reads the shared fields rather than\n * `Schema.encodeSync`, which would reject a plain object.\n */\ninterface EncodedHostResultPayload {\n readonly encodedPayload: string;\n readonly resultBytes: number;\n}\n\nconst encodeHostResultPayload = (\n outcome: CodeHostCallResult,\n): EncodedHostResultPayload | undefined => {\n try {\n const payload = outcome._tag === \"CodeHostCallSuccess\" ? outcome.value : outcome.error;\n const encodedPayload = encodeJsonPayload(payload);\n return {\n encodedPayload,\n resultBytes: utf8ByteLength(encodedPayload),\n };\n } catch {\n return undefined;\n }\n};\n\nconst utf8ByteLength = (value: string): number => {\n let total = 0;\n for (const character of value) {\n const codePoint = character.codePointAt(0) ?? 0;\n total += codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4;\n }\n return total;\n};\n\ninterface QueuedHostCall {\n readonly call: CodeHostCall;\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n}\n\ntype HostWork =\n | { readonly _tag: \"call\"; readonly queued: QueuedHostCall }\n | { readonly _tag: \"limit\" };\n\ntype HostDispatchError =\n | CodeExecutionTimeoutError\n | CodeOutputLimitError\n | CodeExecutionProtocolError\n | CodeHostCallLimitError;\n\n/** Reserved global names the harness owns inside the dynamic worker. */\nconst reservedHarnessGlobals = new Set([\"console\"]);\n\nexport interface DynamicWorkerCodeExecutorOptions {\n /** The `worker_loader` binding. */\n readonly loader: WorkerLoader;\n /** Compatibility date for dynamic workers; defaults to `2025-05-01`. */\n readonly compatibilityDate?: string | undefined;\n}\n\nconst makeExecute = (\n options: DynamicWorkerCodeExecutorOptions,\n clock: Clock.Clock,\n): CodeExecutorExecute =>\n Effect.fn(\"DynamicWorkerCodeExecutor.execute\")(function* (request: CodeExecutionRequest) {\n if (request.network._tag !== \"NetworkDisabled\") {\n return yield* CodeExecutorUnsupportedError.make({\n implementation: dynamicWorkerImplementation,\n feature: \"network\",\n message:\n \"The Dynamic Worker executor denies all egress with globalOutbound: null; an allowlist is not supported in the first slice\",\n });\n }\n const sourceBytes = utf8ByteLength(request.source);\n if (sourceBytes > request.limits.maxSourceBytes) {\n return yield* CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"oversized\",\n message: `Source is ${sourceBytes} bytes; the request allows ${request.limits.maxSourceBytes}`,\n });\n }\n for (const namespace of request.namespaces) {\n if (reservedHarnessGlobals.has(namespace.name)) {\n return yield* CodeExecutorUnsupportedError.make({\n implementation: dynamicWorkerImplementation,\n feature: \"namespaces\",\n message: `Namespace ${namespace.name} collides with a harness binding`,\n });\n }\n }\n const host = yield* CodeExecutionHost;\n\n // This synchronous clock access is confined to callbacks that must compute a timeout\n // immediately. The Clock service remains the authority, so tests and hosts can replace it.\n const startedAt = clock.monotonicTimeNanosUnsafe();\n const passDeadline = startedAt + Duration.toNanosUnsafe(request.limits.maxWallTime);\n const remainingPassWallTime = (): Duration.Duration => {\n const now = clock.monotonicTimeNanosUnsafe();\n return Duration.nanos(passDeadline > now ? passDeadline - now : 0n);\n };\n let issuedHostCalls = 0;\n let passOpen = true;\n const queuedHostCalls: Array<QueuedHostCall> = [];\n let passFailure: HostDispatchError | undefined;\n const failPass = (error: HostDispatchError): void => {\n if (passFailure === undefined) passFailure = error;\n };\n const rejectQueuedHostCalls = (reason: Error): void => {\n for (const queued of queuedHostCalls.splice(0)) {\n queued.reject(reason);\n }\n };\n const queue = yield* Queue.unbounded<HostWork>();\n\n const deliverHostOutcome = (\n queued: QueuedHostCall,\n outcome: CodeHostCallResult,\n ): Effect.Effect<void, CodeExecutionProtocolError | CodeOutputLimitError> =>\n Effect.gen(function* () {\n const decoded = decodeHostCallResult(outcome);\n if (Option.isNone(decoded)) {\n const error = CodeExecutionProtocolError.make({\n implementation: dynamicWorkerImplementation,\n message: \"The execution host returned a value outside the CodeHostCallResult schema\",\n });\n failPass(error);\n return yield* error;\n }\n const encoded = encodeHostResultPayload(decoded.value);\n if (encoded === undefined || encoded.resultBytes > request.limits.maxHostCallResultBytes) {\n const error = CodeOutputLimitError.make({\n implementation: dynamicWorkerImplementation,\n surface: \"host-call-result\",\n limit: request.limits.maxHostCallResultBytes,\n observed: encoded?.resultBytes ?? 0,\n logs: [],\n });\n failPass(error);\n return yield* error;\n }\n const normalizedPayload = decodeJsonPayload(encoded.encodedPayload);\n if (Option.isNone(normalizedPayload)) {\n const error = CodeExecutionProtocolError.make({\n implementation: dynamicWorkerImplementation,\n message: \"The execution host returned a result that could not cross the JSON boundary\",\n });\n failPass(error);\n return yield* error;\n }\n queued.resolve(\n decoded.value._tag === \"CodeHostCallSuccess\"\n ? { _tag: \"CodeHostCallSuccess\", value: normalizedPayload.value }\n : { _tag: \"CodeHostCallFailure\", error: normalizedPayload.value },\n );\n });\n\n // Workers RPC into the loader isolate cannot settle on the fiber blocked\n // in `entrypoint.run()`. A Scope-owned sibling fiber keeps that\n // independence while inheriting the pass Context and dying with the Scope.\n const serveHostCalls = Effect.gen(function* () {\n while (true) {\n const work = yield* Queue.take(queue);\n if (work._tag === \"limit\") {\n const error = CodeHostCallLimitError.make({\n implementation: dynamicWorkerImplementation,\n limit: request.limits.maxHostCalls,\n logs: [],\n });\n failPass(error);\n return yield* error;\n }\n const queued = work.queued;\n yield* host.call(queued.call).pipe(\n Effect.timeoutOrElse({\n duration: remainingPassWallTime(),\n orElse: () => {\n const error = CodeExecutionTimeoutError.make({\n implementation: dynamicWorkerImplementation,\n kind: \"wall-clock\",\n maxWallTime: request.limits.maxWallTime,\n logs: [],\n });\n failPass(error);\n return error;\n },\n }),\n Effect.flatMap((outcome) => deliverHostOutcome(queued, outcome)),\n Effect.tapError(() =>\n Effect.sync(() => queued.reject(new Error(\"Code Mode host call failed\"))),\n ),\n Effect.onInterrupt(() =>\n Effect.sync(() => queued.reject(new Error(\"Code Mode pass is closing\"))),\n ),\n );\n }\n });\n const server = yield* serveHostCalls.pipe(Effect.forkScoped);\n\n const dispatch = (hostCall: unknown): Promise<unknown> => {\n if (!passOpen) {\n return Promise.reject(new Error(\"Code Mode pass is closing\"));\n }\n issuedHostCalls += 1;\n if (issuedHostCalls > request.limits.maxHostCalls) {\n const error = CodeHostCallLimitError.make({\n implementation: dynamicWorkerImplementation,\n limit: request.limits.maxHostCalls,\n logs: [],\n });\n failPass(error);\n Queue.offerUnsafe(queue, { _tag: \"limit\" });\n return Promise.reject(new Error(\"host-call limit exceeded\"));\n }\n const decoded = decodeHostCall(hostCall);\n if (Option.isNone(decoded)) {\n return Promise.reject(new TypeError(\"host calls must match the CodeHostCall schema\"));\n }\n return new Promise((resolve, reject) => {\n const queued = { call: decoded.value, resolve, reject };\n queuedHostCalls.push(queued);\n Queue.offerUnsafe(queue, { _tag: \"call\", queued });\n });\n };\n\n const closeAdmission = Effect.sync(() => {\n passOpen = false;\n rejectQueuedHostCalls(new Error(\"Code Mode pass is closing\"));\n });\n yield* Effect.addFinalizer(() => closeAdmission.pipe(Effect.andThen(Fiber.interrupt(server))));\n\n // No `allowExperimental`: the runtime only accepts it when the CALLING\n // worker carries the `experimental` compatibility flag, which deployed\n // consumers cannot set — the option would reject every pass in\n // production. The harness needs no experimental runtime features.\n const workerCode: WorkerLoaderWorkerCode = {\n compatibilityDate: options.compatibilityDate ?? \"2025-05-01\",\n mainModule: \"harness.js\",\n modules: {\n \"harness.js\": HARNESS_MODULE,\n \"program.js\": `export default (\\n${request.source}\\n);`,\n },\n env: {\n CODE_MODE_PASS: encodeHarnessPassConfig({\n namespaces: request.namespaces.map((namespace) => ({\n name: namespace.name,\n methods: namespace.methods,\n })),\n limits: {\n maxLogBytes: request.limits.maxLogBytes,\n maxResultBytes: request.limits.maxResultBytes,\n maxHostCalls: request.limits.maxHostCalls,\n maxHostCallArgumentBytes: request.limits.maxHostCallArgumentBytes,\n },\n }),\n },\n globalOutbound: null,\n ...(request.limits.cpuMillis === undefined\n ? {}\n : {\n limits: {\n cpuMs: request.limits.cpuMillis,\n subRequests: request.limits.maxHostCalls + 8,\n },\n }),\n };\n\n const worker = yield* Effect.acquireRelease(\n Effect.try({\n try: () => options.loader.load(workerCode),\n catch: (cause) => {\n const text = safeCauseMessage(cause, \"The Worker Loader failed without a diagnostic\");\n // Blame the program's source ONLY on a genuine compile diagnostic;\n // any other load rejection is an infrastructure start failure, not\n // the model's fault (see classifyWorkerFailure for the same split).\n if (/syntaxerror|failed to (compile|parse)/i.test(text)) {\n return CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"invalid\",\n message: text.slice(0, 8_000),\n });\n }\n return CodeExecutorStartError.make({\n implementation: dynamicWorkerImplementation,\n message: `The Worker Loader rejected the pass: ${text}`.slice(0, 8_000),\n cause,\n });\n },\n }),\n disposeRpcHandle,\n );\n\n const entrypoint = yield* Effect.acquireRelease(\n Effect.try({\n try: () => worker.getEntrypoint<CodeModeHarnessEntrypoint>(),\n catch: (cause) => classifyWorkerFailure(cause, request.limits.maxWallTime),\n }),\n disposeRpcHandle,\n );\n\n const rpc = Effect.tryPromise({\n try: () => entrypoint.run(new CodeModePassHostTarget(dispatch)),\n catch: (cause) => classifyWorkerFailure(cause, request.limits.maxWallTime),\n });\n\n const exit = yield* Effect.raceFirst(\n rpc.pipe(\n Effect.timeoutOrElse({\n duration: remainingPassWallTime(),\n orElse: () =>\n CodeExecutionTimeoutError.make({\n implementation: dynamicWorkerImplementation,\n kind: \"wall-clock\",\n maxWallTime: request.limits.maxWallTime,\n logs: [],\n }),\n }),\n ),\n Fiber.join(server),\n ).pipe(Effect.exit);\n yield* closeAdmission;\n yield* Fiber.interrupt(server);\n if (passFailure !== undefined) {\n return yield* passFailure;\n }\n if (Exit.isFailure(exit)) {\n return yield* Effect.failCause(exit.cause);\n }\n const raw = exit.value;\n const finishedAt = clock.monotonicTimeNanosUnsafe();\n\n const outcome = decodeHarnessOutcome(raw);\n if (Option.isNone(outcome)) {\n return yield* CodeExecutionProtocolError.make({\n implementation: dynamicWorkerImplementation,\n message: \"The dynamic worker returned a value outside the harness envelope schema\",\n });\n }\n switch (outcome.value._tag) {\n case \"completed\": {\n return CodeExecutionResult.make({\n implementation: dynamicWorkerImplementation,\n value: outcome.value.value,\n logs: outcome.value.logs,\n resourceUse: CodeExecutionResourceUse.make({\n wallTime: Duration.nanos(finishedAt > startedAt ? finishedAt - startedAt : 0n),\n hostCalls: outcome.value.hostCalls,\n logBytes: outcome.value.logBytes,\n resultBytes: outcome.value.resultBytes,\n }),\n });\n }\n case \"source-invalid\": {\n return yield* CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"invalid\",\n message: outcome.value.message.slice(0, 8_000),\n });\n }\n case \"source-not-a-function\": {\n return yield* CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"not-a-function\",\n message: `The source expression evaluated to ${outcome.value.actual}; it must evaluate to one async function`,\n });\n }\n case \"program-failed\": {\n return yield* CodeProgramFailedError.make({\n implementation: dynamicWorkerImplementation,\n reason: outcome.value.reason,\n thrown: outcome.value.thrown,\n message: outcome.value.message.slice(0, 8_000),\n logs: outcome.value.logs,\n });\n }\n case \"log-limit\": {\n return yield* CodeOutputLimitError.make({\n implementation: dynamicWorkerImplementation,\n surface: \"logs\",\n limit: request.limits.maxLogBytes,\n observed: outcome.value.observed,\n logs: outcome.value.logs,\n });\n }\n case \"argument-limit\": {\n return yield* CodeOutputLimitError.make({\n implementation: dynamicWorkerImplementation,\n surface: \"host-call-argument\",\n limit: request.limits.maxHostCallArgumentBytes,\n observed: outcome.value.observed,\n logs: outcome.value.logs,\n });\n }\n case \"result-limit\": {\n return yield* CodeOutputLimitError.make({\n implementation: dynamicWorkerImplementation,\n surface: \"result\",\n limit: request.limits.maxResultBytes,\n observed: outcome.value.observed,\n logs: outcome.value.logs,\n });\n }\n case \"host-call-limit\": {\n return yield* CodeHostCallLimitError.make({\n implementation: dynamicWorkerImplementation,\n limit: request.limits.maxHostCalls,\n logs: outcome.value.logs,\n });\n }\n case \"protocol\": {\n return yield* CodeExecutionProtocolError.make({\n implementation: dynamicWorkerImplementation,\n message: outcome.value.message.slice(0, 8_000),\n });\n }\n }\n });\n\n/**\n * Expected worker-level failures map into the typed union with bounded\n * diagnostics; anything unrecognized stays a start/termination error rather\n * than a fabricated program result.\n */\nconst classifyWorkerFailure = (\n cause: unknown,\n maxWallTime: Duration.Duration,\n):\n | CodeExecutionTimeoutError\n | CodeExecutorTerminatedError\n | CodeExecutorStartError\n | CodeSourceError => {\n const text = safeCauseDiagnostic(cause, \"[unserializable worker failure]\");\n // `WorkerLoader.load()` is lazy, so a module-compile error in the generated\n // program surfaces here at first use. Blame the program's source ONLY on a\n // genuine compile diagnostic (a `SyntaxError` or an explicit compile\n // failure) — the fixed harness is valid, so the fault is in program.js. A\n // bare \"failed to start Worker\" without a compile diagnostic is an\n // infrastructure start failure, not the model's fault, so it must NOT be\n // misclassified as a source error.\n if (/syntaxerror|failed to (compile|parse)/i.test(text)) {\n return CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"invalid\",\n message: text.slice(0, 8_000),\n });\n }\n if (/cpu/i.test(text)) {\n return CodeExecutionTimeoutError.make({\n implementation: dynamicWorkerImplementation,\n kind: \"cpu\",\n maxWallTime,\n logs: [],\n });\n }\n if (/failed to start worker/i.test(text)) {\n return CodeExecutorStartError.make({\n implementation: dynamicWorkerImplementation,\n message: text.slice(0, 8_000),\n cause,\n });\n }\n return CodeExecutorTerminatedError.make({\n implementation: dynamicWorkerImplementation,\n message: text.slice(0, 8_000),\n });\n};\n\n/** Layer building the Dynamic Worker `CodeExecutor` from resolved bindings. */\nexport const dynamicWorkerCodeExecutorLayer = (\n options: DynamicWorkerCodeExecutorOptions,\n): Layer.Layer<CodeExecutor> =>\n Layer.effect(\n CodeExecutor,\n Effect.gen(function* () {\n const clock = yield* Clock.Clock;\n return CodeExecutor.of({ execute: makeExecute(options, clock) });\n }),\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAYA,IAAa,yBAAb,cAA4C,OAAO,YAAoC,CAAC,CACtF,0BACA;CACE,SAAS,OAAO;CAChB,SAAS,OAAO;AAClB,CACF,CAAC,CAAC,CAAC;;;;;;AAwCH,IAAa,8BAAb,MAAa,oCAAoC,QAAQ,QAOvD,CAAC,CAAC,+DAA+D,CAAC,CAAC;CACnE,OAAO,MACL,WAC0C;EAC1C,OAAO,MAAM,QAAQ,2BAA2B,CAAC,CAAC,EAAE,UAAU,CAAC;CACjE;AACF;;;;;;;AAQA,MAAa,+BAA+B,OAAO,GAAG,8BAA8B,CAAC,CAAC,WACpF,KACA,SACyF;CACzF,IAAI,CAAC,UAAU,gBAAgB,GAAG,GAChC,OAAO,OAAO,uBAAuB,KAAK;EACxC;EACA,SAAS;CACX,CAAC;CAEH,MAAM,YAAY,OAAO,OAAO,IAAI;EAClC,WAAW;GACT,MAAM,QAAiB,QAAQ,IAAI,KAAK,OAAO;GAC/C,IAAI,CAAC,UAAU,gBAAgB,KAAK,GAAG,OAAO,KAAA;GAC9C,MAAM,aAAsB,QAAQ,IAAI,OAAO,YAAY;GAC3D,MAAM,MAAe,QAAQ,IAAI,OAAO,KAAK;GAC7C,OAAO,OAAO,eAAe,cAAc,OAAO,QAAQ,aAAa,QAAQ,KAAA;EACjF;EACA,aACE,uBAAuB,KAAK;GAC1B;GACA,SAAS,OA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B,OAAO,iCAAiC;CAQzE,IAAI,yCAAyC,KAAK,IAAI,GACpD,OAAO,gBAAgB,KAAK;EAC1B,gBAAgB;EAChB,QAAQ;EACR,SAAS,KAAK,MAAM,GAAG,GAAK;CAC9B,CAAC;CAEH,IAAI,OAAO,KAAK,IAAI,GAClB,OAAO,0BAA0B,KAAK;EACpC,gBAAgB;EAChB,MAAM;EACN;EACA,MAAM,CAAC;CACT,CAAC;CAEH,IAAI,0BAA0B,KAAK,IAAI,GACrC,OAAO,uBAAuB,KAAK;EACjC,gBAAgB;EAChB,SAAS,KAAK,MAAM,GAAG,GAAK;EAC5B;CACF,CAAC;CAEH,OAAO,4BAA4B,KAAK;EACtC,gBAAgB;EAChB,SAAS,KAAK,MAAM,GAAG,GAAK;CAC9B,CAAC;AACH;;AAGA,MAAa,kCACX,YAEA,MAAM,OACJ,cACA,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,OAAO,MAAM;CAC3B,OAAO,aAAa,GAAG,EAAE,SAAS,YAAY,SAAS,KAAK,EAAE,CAAC;AACjE,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["EffectCfDurableObjectState","EffectCfDurableObject","#dispatch"],"sources":["../src/bindings.ts","../src/config.ts","../src/boundary.ts","../src/alarm.ts","../src/wake-scheduler.ts","../src/progress-wait.ts","../src/transport.ts","../src/layers.ts","../src/client.ts","../src/conversation-object.ts","../src/code-mode-executor.ts"],"sourcesContent":["import type { ConversationId } from \"@effect-agent/core\";\nimport type { ProducerId } from \"@effect-agent/session\";\nimport { Context, Effect, Layer, Predicate, Schema } from \"effect\";\n\n/**\n * Cloudflare platform bindings as Effect services (DEPLOY-010: \"Cloudflare platform bindings\n * are supplied as Effect services/Layers\"). Application code never reads `env` or touches a\n * `DurableObjectState` directly — the Conversation Object class constructs these Layers once\n * per incarnation and everything downstream consumes the services.\n */\n\n/** A Cloudflare platform binding was missing or carried the wrong shape (DEPLOY-003/010). */\nexport class CloudflareBindingError extends Schema.TaggedError<CloudflareBindingError>()(\n \"CloudflareBindingError\",\n {\n binding: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/**\n * The RPC surface one Conversation Durable Object exposes to Workers and to sibling\n * Conversation Objects. `makeConversationObjectClass` implements it; the Worker-side client\n * and the cross-Object transport call it through `DurableObjectNamespace` stubs. Every\n * `encoded` value is a Schema-encoded envelope (`client.ts` wire schemas for host entry\n * points, `@effect-agent/storage-cloudflare` port envelopes for `portCall`), so the RPC\n * boundary carries only structured-cloneable JSON. The optional trailing trace context is\n * transient native RPC metadata, stripped by an opted-in effect-cf receiver before decoding\n * the host envelope. It never enters durable state.\n */\nexport interface ConversationObjectRpc extends Rpc.DurableObjectBranded {\n /** Admission-limits gate + `DurableAgentRuntime.submit`; answers a `SubmitResponse`. */\n submitEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Wake-hinted, poll-guaranteed settlement wait; answers an `AwaitSettlementResponse`. */\n awaitSettlementEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Event-driven durable progress wait; answers a `ProgressObserved` host response. */\n awaitProgressEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Best-effort cancellation for one in-flight progress wait. */\n cancelProgressEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** One bounded page of canonical records; answers an `ObservePageResponse`. */\n observePage(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Durable abort intent; answers an `AbortResponse`. */\n abortEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Durable approval decision (plan §2.6); answers a `ResolveApprovalResponse`. */\n resolveApprovalEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Authorized DUR-017 Unknown-Outcome resolution; answers a `ResolveUnknownResponse`. */\n resolveUnknownEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Owner-side cross-Object port endpoint (WP2 envelopes, executed on LOCAL facets). */\n portCall(encoded: unknown): Promise<unknown>;\n /** Droppable liveness hint from another Object: arms an immediate alarm. */\n wake(): Promise<void>;\n}\n\n/**\n * The `DurableObjectNamespace` binding that addresses Conversation Objects. The Object\n * identity rule is `namespace.idFromName(conversationId)` (plan §1.2): Conversation IDs are\n * globally unique, so the mapping is total and deterministic and no directory service exists.\n */\nexport class ConversationObjectNamespace extends Context.Service<\n ConversationObjectNamespace,\n {\n readonly namespace: DurableObjectNamespace<ConversationObjectRpc>;\n /** Stable binding name for opted-in native RPC tracing; absent by default. */\n readonly rpcTracing?: string;\n }\n>()(\"@effect-agent/platform-cloudflare/ConversationObjectNamespace\") {\n static layer(\n namespace: DurableObjectNamespace<ConversationObjectRpc>,\n ): Layer.Layer<ConversationObjectNamespace> {\n return Layer.succeed(ConversationObjectNamespace)({ namespace });\n }\n}\n\n/**\n * Narrow one `env` member to a `DurableObjectNamespace`. `env` is an untyped platform value,\n * and a namespace binding is a host object no Schema can decode, so this is the documented\n * narrowest-boundary check (structural probe for the namespace surface the transport uses);\n * a missing or misshaped binding fails typed before any Layer is built.\n */\nexport const conversationNamespaceFromEnv = Effect.fn(\"conversationNamespaceFromEnv\")(function* (\n env: unknown,\n binding: string,\n): Effect.fn.Return<DurableObjectNamespace<ConversationObjectRpc>, CloudflareBindingError> {\n if (!Predicate.isObjectKeyword(env)) {\n return yield* CloudflareBindingError.make({\n binding,\n message: \"The Worker environment is not an object; no bindings are available.\",\n });\n }\n const candidate = yield* Effect.try({\n try: () => {\n const value: unknown = Reflect.get(env, binding);\n if (!Predicate.isObjectKeyword(value)) return undefined;\n const idFromName: unknown = Reflect.get(value, \"idFromName\");\n const get: unknown = Reflect.get(value, \"get\");\n return typeof idFromName === \"function\" && typeof get === \"function\" ? value : undefined;\n },\n catch: () =>\n CloudflareBindingError.make({\n binding,\n message: `env.${binding} could not be inspected as a DurableObjectNamespace binding.`,\n }),\n });\n if (candidate !== undefined) {\n // The structural probe above is the entire runtime contract this package relies on;\n // the assertion records that `idFromName`/`get` name a DurableObjectNamespace.\n return candidate as unknown as DurableObjectNamespace<ConversationObjectRpc>;\n }\n return yield* CloudflareBindingError.make({\n binding,\n message:\n `env.${binding} is not a DurableObjectNamespace binding; declare the Conversation ` +\n \"Object class under this binding in the Worker configuration.\",\n });\n});\n\n/**\n * Build the namespace from Worker `env` (fails typed). Enable `rpcTracing` only when the\n * receiver also opts into the effect-cf native RPC trace-context contract.\n */\nexport const conversationNamespaceLayer = (\n env: unknown,\n binding: string,\n options: { readonly rpcTracing?: boolean } = {},\n): Layer.Layer<ConversationObjectNamespace, CloudflareBindingError> =>\n Layer.effect(ConversationObjectNamespace)(\n Effect.map(conversationNamespaceFromEnv(env, binding), (namespace) => ({\n namespace,\n ...(options.rpcTracing === true ? { rpcTracing: binding } : {}),\n })),\n );\n\n/**\n * The live Durable Object execution context of THIS incarnation. Only Layer construction and\n * the alarm service consume it; important state never lives on it (`ctx.storage` is truth,\n * everything in memory is a cache — deployment spec §11).\n */\nexport class DurableObjectContext extends Context.Service<\n DurableObjectContext,\n {\n readonly ctx: DurableObjectState;\n readonly env: unknown;\n }\n>()(\"@effect-agent/platform-cloudflare/DurableObjectContext\") {\n static layer(ctx: DurableObjectState, env: unknown): Layer.Layer<DurableObjectContext> {\n return Layer.succeed(DurableObjectContext)({ ctx, env });\n }\n}\n\n/**\n * The Conversation identity this Object serializes and the producer identity its Attempts\n * write with (`{producerPrefix}:{conversationId}`, plan §1.4). Derived once per incarnation\n * from `ctx.id.name` — the Object identity rule guarantees the name IS the Conversation ID.\n */\nexport class ConversationObjectIdentity extends Context.Service<\n ConversationObjectIdentity,\n {\n readonly conversationId: ConversationId;\n readonly producerId: ProducerId;\n }\n>()(\"@effect-agent/platform-cloudflare/ConversationObjectIdentity\") {}\n","import { DEFAULT_OWNERSHIP_LEASE_DURATION, DeploymentId } from \"@effect-agent/session\";\nimport { DEFAULT_MAX_STORED_VALUE_BYTES } from \"@effect-agent/storage-cloudflare\";\nimport { Context, Duration, Schema } from \"effect\";\n\n/**\n * Schema-validated configuration for the Cloudflare durable runtime (deployment spec §4:\n * decoded once during Layer construction, exposed as a typed service; DEPLOY-003). Every\n * cadence is in milliseconds; every bound is finite and checked before any resource opens.\n */\n\nconst PositiveMillis = Schema.Int.check(Schema.isGreaterThan(0));\nconst NonNegativeMillis = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));\n\n/** The supplied Cloudflare durable runtime configuration failed validation (DEPLOY-003). */\nexport class CloudflarePlatformConfigError extends Schema.TaggedError<CloudflarePlatformConfigError>()(\n \"CloudflarePlatformConfigError\",\n {\n message: Schema.String,\n cause: Schema.optionalKey(Schema.Defect()),\n },\n) {}\n\n/**\n * An admission was refused by a host resource limit BEFORE any ledger row existed\n * (deployment spec §8, DEPLOY-007: \"Admission has explicit bounded quota and overload\n * behavior... a typed rejection\"). This is the DC analogue of `NodeDurableHost`'s\n * `AdmissionClosed` host gate: the port surface stays untouched, the refusal happens in the\n * Conversation Object's submit entry point before `DurableAgentRuntime.submit` runs, and\n * nothing was admitted or written.\n */\nexport class AdmissionLimitExceeded extends Schema.TaggedError<AdmissionLimitExceeded>()(\n \"AdmissionLimitExceeded\",\n {\n limit: Schema.Literals([\"queue-depth\", \"input-bytes\", \"database-bytes\"]),\n actual: Schema.Int,\n maximum: Schema.Int,\n },\n) {\n override get message() {\n return (\n `Admission refused before any ledger row existed: ${this.limit} ${this.actual} exceeds ` +\n `the configured maximum ${this.maximum}. Accepted work is unaffected; retry after the ` +\n \"lane drains or raise the limit (DEPLOY-007).\"\n );\n }\n}\n\n/** The platform's hard per-Object database cap (10 GB, developers.cloudflare.com limits). */\nexport const CLOUDFLARE_DATABASE_CAP_BYTES = 10_000_000_000;\n\n/** Default database-size admission ceiling: a 1 GB safety margin under the platform cap. */\nexport const DEFAULT_MAX_DATABASE_BYTES = 9_000_000_000;\n\n/**\n * Explicit bounded admission quotas checked by the Conversation Object BEFORE admission\n * (exit gate \"resource limits are checked before admission\").\n */\nexport class CloudflareAdmissionLimitsValue extends Schema.Class<CloudflareAdmissionLimitsValue>(\n \"@effect-agent/platform-cloudflare/CloudflareAdmissionLimitsValue\",\n)({\n /** Maximum nonterminal Submissions per Conversation lane before new admissions refuse. */\n maxQueueDepthPerLane: Schema.Int.check(\n Schema.isGreaterThan(0),\n Schema.isLessThanOrEqualTo(100_000),\n ),\n /** Maximum encoded input bytes; never above the storage per-value bound. */\n maxInputBytes: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(2_000_000)),\n /** Maximum `ctx.storage.sql.databaseSize` at admission; stays under the 10 GB platform cap. */\n maxDatabaseBytes: Schema.Int.check(\n Schema.isGreaterThan(0),\n Schema.isLessThanOrEqualTo(CLOUDFLARE_DATABASE_CAP_BYTES),\n ),\n}) {}\n\n/**\n * Validated Cloudflare durable runtime configuration. The producer identity of one\n * Conversation Object is `{producerPrefix}:{conversationId}` — stable across incarnations of\n * the same deployment, distinct across deployments — and producer-epoch fencing (not the\n * producer name) remains the correctness authority (DUR-006).\n */\nexport class CloudflareDurableRuntimeConfigValue extends Schema.Class<CloudflareDurableRuntimeConfigValue>(\n \"@effect-agent/platform-cloudflare/CloudflareDurableRuntimeConfigValue\",\n)({\n deploymentId: DeploymentId,\n /** Head of the minted producer identity `{producerPrefix}:{conversationId}`. */\n producerPrefix: Schema.NonEmptyString.check(Schema.isMaxLength(256)),\n /** Submission ownership lease duration (D5); fences work across Object incarnations. */\n ownershipLeaseDuration: PositiveMillis,\n /** Base delay of the alarm re-arm backoff when a pass makes no progress. */\n alarmBackoffBase: PositiveMillis,\n /** Ceiling of the alarm re-arm backoff. */\n alarmBackoffCap: PositiveMillis,\n /**\n * The maintenance-pass scan cadence and the ceiling of every re-arm delay: nonterminal\n * work is revisited at least this often (wake/scan pairing, persistence §14).\n */\n wakeScanInterval: PositiveMillis,\n /** `awaitSettlement` ledger re-check cadence when no wake arrives. */\n settlementPollInterval: PositiveMillis,\n /** Worker ownership-lease renewal cadence during an active Attempt. */\n leaseRenewalInterval: PositiveMillis,\n /** Active-Run abort-intent poll cadence. */\n abortPollInterval: PositiveMillis,\n /** Canonical observation poll cadence of the Durable Object store. */\n observationPollInterval: NonNegativeMillis,\n /** Per-value byte bound; must stay under the platform's 2 MB SQLite value limit. */\n maxStoredValueBytes: Schema.Int.check(\n Schema.isGreaterThan(0),\n Schema.isLessThanOrEqualTo(2_000_000),\n ),\n /** Opt-in full payload/digest-chain audit while opening the store. */\n verifyOnOpen: Schema.Boolean,\n limits: CloudflareAdmissionLimitsValue,\n}) {}\n\n/** Explicit configuration authority for the assembled Cloudflare durable runtime. */\nexport class CloudflareDurableRuntimeConfig extends Context.Service<\n CloudflareDurableRuntimeConfig,\n CloudflareDurableRuntimeConfigValue\n>()(\"@effect-agent/platform-cloudflare/CloudflareDurableRuntimeConfig\") {}\n\n/** Documented production defaults applied by `CloudflareDurableRuntime.layer`. */\nexport const CLOUDFLARE_RUNTIME_DEFAULTS = {\n ownershipLeaseDuration: Duration.toMillis(DEFAULT_OWNERSHIP_LEASE_DURATION),\n alarmBackoffBase: 100,\n alarmBackoffCap: 5_000,\n wakeScanInterval: 1_000,\n settlementPollInterval: 500,\n leaseRenewalInterval: 10_000,\n abortPollInterval: 500,\n observationPollInterval: 25,\n maxStoredValueBytes: DEFAULT_MAX_STORED_VALUE_BYTES,\n verifyOnOpen: false,\n maxQueueDepthPerLane: 256,\n maxInputBytes: DEFAULT_MAX_STORED_VALUE_BYTES,\n maxDatabaseBytes: DEFAULT_MAX_DATABASE_BYTES,\n} as const;\n","import { Predicate } from \"effect\";\n\nconst MAX_FOREIGN_DIAGNOSTIC_LENGTH = 8_192;\n\nconst boundForeignDiagnostic = (message: string): string =>\n message.slice(0, MAX_FOREIGN_DIAGNOSTIC_LENGTH);\n\n/** Render a foreign failure without trusting accessors or coercion hooks on the value. */\nexport const safeCauseMessage = (cause: unknown, fallback: string): string => {\n try {\n const message = cause instanceof Error ? cause.message : cause;\n return boundForeignDiagnostic(typeof message === \"string\" ? message : String(message));\n } catch {\n return boundForeignDiagnostic(fallback);\n }\n};\n\n/** Include an Error name when worker-failure classification needs it. */\nexport const safeCauseDiagnostic = (cause: unknown, fallback: string): string => {\n try {\n return cause instanceof Error\n ? boundForeignDiagnostic(`${cause.name}: ${cause.message}`)\n : safeCauseMessage(cause, fallback);\n } catch {\n return boundForeignDiagnostic(fallback);\n }\n};\n\nexport interface CloudflareFailureSignals {\n readonly retryable?: boolean | undefined;\n readonly overloaded?: boolean | undefined;\n}\n\n/** Read Cloudflare RPC classifications without letting a hostile proxy defect the client. */\nexport const cloudflareFailureSignals = (cause: unknown): CloudflareFailureSignals => {\n if (!Predicate.isObjectKeyword(cause)) return {};\n try {\n const retryableValue = Reflect.get(cause, \"retryable\");\n const overloadedValue = Reflect.get(cause, \"overloaded\");\n const resetValue = Reflect.get(cause, \"durableObjectReset\");\n const retryable =\n typeof retryableValue === \"boolean\" ? retryableValue : resetValue === true ? true : undefined;\n const overloaded = typeof overloadedValue === \"boolean\" ? overloadedValue : undefined;\n return {\n ...(retryable === undefined ? {} : { retryable }),\n ...(overloaded === undefined ? {} : { overloaded }),\n };\n } catch {\n return {};\n }\n};\n","import {\n AgentBindingResolver,\n DurableAgentRuntime,\n SubmissionLedger,\n type DurableBindingFailure,\n type DurableWorkerFailure,\n type RecoveryReport,\n type SubmissionSnapshot,\n} from \"@effect-agent/session\";\nimport {\n Clock,\n Context,\n Effect,\n Layer,\n Option,\n Random,\n Ref,\n Schema,\n Semaphore,\n Stream,\n} from \"effect\";\n\nimport { ConversationObjectIdentity, DurableObjectContext } from \"./bindings.ts\";\nimport { safeCauseMessage } from \"./boundary.ts\";\nimport { CloudflareDurableRuntimeConfig } from \"./config.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/** `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> =\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 const scheduled = Effect.tryPromise({\n try: () => ctx.storage.getAlarm(),\n catch: alarmFailure(\"get alarm\"),\n }).pipe(\n Effect.map((deadline) =>\n deadline === null ? Option.none<number>() : Option.some(deadline),\n ),\n );\n const scheduleAt = (epochMillis: number) =>\n Effect.tryPromise({\n try: () => ctx.storage.setAlarm(epochMillis),\n catch: alarmFailure(\"set alarm\"),\n });\n const ensureScheduledBy = (epochMillis: number) =>\n scheduled.pipe(\n Effect.flatMap((existing) =>\n Option.isSome(existing) && existing.value <= epochMillis\n ? Effect.void\n : scheduleAt(epochMillis),\n ),\n );\n const armNow = Clock.currentTimeMillis.pipe(\n Effect.flatMap((now) => ensureScheduledBy(now)),\n );\n const scheduleNow = Ref.get(runningPasses).pipe(\n Effect.flatMap((passes) => (passes > 0 ? Effect.void : armNow)),\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 const cancel = Effect.tryPromise({\n try: () => ctx.storage.deleteAlarm(),\n catch: alarmFailure(\"delete alarm\"),\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` is generation-only; `actionable` ran recovery and one bounded drain. */\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 /** Settlements the drain pass finalized. */\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 ConversationMaintenanceFailpointLocation =\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:finish:before\"\n | \"maintenance:finish:after\";\n\nexport type ConversationMaintenanceFailpointHandler = (\n location: ConversationMaintenanceFailpointLocation,\n) => Effect.Effect<void>;\n\n/** Test-only fault authority; production uses the inert layer. */\nexport class ConversationMaintenanceFailpoint extends Context.Service<\n ConversationMaintenanceFailpoint,\n {\n readonly hit: ConversationMaintenanceFailpointHandler;\n }\n>()(\"@effect-agent/platform-cloudflare/ConversationMaintenanceFailpoint\") {\n static readonly layer = Layer.succeed(this)({ hit: () => Effect.void });\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 ConversationMaintenanceState extends Schema.Class<ConversationMaintenanceState>(\n \"@effect-agent/platform-cloudflare/ConversationMaintenanceState\",\n)({\n schemaVersion: Schema.Literal(1),\n dirty: MaintenanceGeneration,\n processed: MaintenanceGeneration,\n nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),\n}) {}\n\nconst MAINTENANCE_STATE_KEY = \"effect-agent:conversation-maintenance:v1\";\nconst decodeMaintenanceState = Schema.decodeUnknownSync(ConversationMaintenanceState);\nconst encodeMaintenanceState = Schema.encodeSync(ConversationMaintenanceState);\n\nconst initialMaintenanceState = (): ConversationMaintenanceState =>\n ConversationMaintenanceState.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: ConversationMaintenanceState; readonly initialized: boolean }> => {\n const encoded = await transaction.get(MAINTENANCE_STATE_KEY);\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 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 // 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\nexport type MaintenancePassFailure =\n | DurableWorkerFailure\n | DurableBindingFailure\n | DurableAlarmError;\n\n/**\n * Incremental, quiescent maintenance over a durable dirty/processed generation (issue #93).\n *\n * `pass` = generation snapshot/pre-arm → recovery → bounded drain → 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 still strictly precedes a new claim, and one bounded drain advances the lane.\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 ConversationMaintenance extends Context.Service<\n ConversationMaintenance,\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/ConversationMaintenance\") {\n static readonly layer: Layer.Layer<\n ConversationMaintenance,\n never,\n | DurableAgentRuntime\n | AgentBindingResolver\n | SubmissionLedger\n | DurableAlarmService\n | ConversationMaintenanceFailpoint\n | CloudflareDurableRuntimeConfig\n | ConversationObjectIdentity\n | DurableObjectContext\n > = Layer.effect(ConversationMaintenance)(\n Effect.gen(function* () {\n const runtime = yield* DurableAgentRuntime;\n const resolver = yield* AgentBindingResolver;\n const ledger = yield* SubmissionLedger;\n const alarm = yield* DurableAlarmService;\n const config = yield* CloudflareDurableRuntimeConfig;\n const identity = yield* ConversationObjectIdentity;\n const { ctx } = yield* DurableObjectContext;\n const failpoint = yield* ConversationMaintenanceFailpoint;\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 /**\n * Incarnation-local mutation count guarded with the generation transactions below. It is\n * deliberately not durable: after eviction every begun mutation has stopped, while its\n * pre-armed dirty generation remains durable for recovery. The short gate never spans the\n * caller's mutation or cross-Object I/O.\n */\n const activeMutations = yield* Ref.make(0);\n const generationGate = yield* Semaphore.make(1);\n // At-least-once deliveries are idempotent, but overlapping pass bodies could otherwise\n // acknowledge state while a sibling pass is still mutating it. Port/RPC mutations do not\n // take this permit, so cross-Object I/O cannot deadlock the maintenance serialization.\n const maintenancePassGate = yield* Semaphore.make(1);\n const minimumAlarmDelay = Math.max(1, Math.ceil(config.alarmBackoffBase / 2));\n\n const runTransaction = <A>(\n operation: string,\n transaction: () => Promise<A>,\n ): Effect.Effect<A, DurableAlarmError> =>\n Effect.tryPromise({\n try: transaction,\n catch: alarmFailure(operation),\n });\n\n const beginMutation = Effect.fn(\"ConversationMaintenance.beginMutation\")(function* () {\n yield* failpoint.hit(\"maintenance:dirty:before\");\n const now = yield* Clock.currentTimeMillis;\n yield* runTransaction(\"advance maintenance generation\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\n const next = ConversationMaintenanceState.make({\n ...state,\n dirty: state.dirty + 1n,\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 const ensureAlarm = Effect.fn(\"ConversationMaintenance.ensureAlarm\")(function* () {\n yield* failpoint.hit(\"maintenance:ensure:before\");\n const now = yield* Clock.currentTimeMillis;\n yield* runTransaction(\"ensure maintenance alarm\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state, initialized } = await readMaintenanceState(transaction);\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 yield* failpoint.hit(\"maintenance:ensure:after\");\n });\n\n const beginPass = Effect.fn(\"ConversationMaintenance.beginPass\")(function* () {\n yield* failpoint.hit(\"maintenance:begin:before\");\n const now = yield* Clock.currentTimeMillis;\n const result = yield* runTransaction(\"begin maintenance pass\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state, initialized } = await readMaintenanceState(transaction);\n if (!initialized) {\n await transaction.put(MAINTENANCE_STATE_KEY, encodeMaintenanceState(state));\n }\n if (state.processed >= state.dirty) {\n await transaction.deleteAlarm();\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 return { _tag: \"Actionable\" as const, generation: state.dirty };\n }),\n );\n yield* failpoint.hit(\"maintenance:begin:after\");\n return result;\n });\n\n const rearmDelay = Effect.fn(\"ConversationMaintenance.rearmDelay\")(function* (\n progressed: boolean,\n ) {\n const priorStalls = yield* Ref.getAndUpdate(stalls, (count) =>\n progressed ? 0 : count + 1,\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 return Math.min(jittered, config.wakeScanInterval);\n });\n\n const pass = Effect.fn(\"ConversationMaintenance.pass\")(function* (): Effect.fn.Return<\n MaintenancePassReport,\n MaintenancePassFailure\n > {\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* generationGate.withPermit(\n Effect.gen(function* () {\n const activeAtStart = yield* Ref.get(activeMutations);\n const generation = yield* beginPass();\n return { ...generation, activeAtStart };\n }),\n );\n if (started._tag === \"CaughtUp\") {\n return yield* annotate(\n MaintenancePassReport.make({\n phase: \"caught-up\",\n recovered: 0,\n settled: 0,\n nonterminal: started.nonterminal,\n alarm: \"cleared\",\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 // Step 3 — one bounded drain pass over this Object's own lane.\n const settlements = yield* runtime\n .processConversationResolved(identity.conversationId)\n .pipe(Effect.provideService(AgentBindingResolver, resolver));\n // Observe residual state before acknowledging this exact pass-start generation.\n const remaining = yield* Stream.runCollect(ledger.scanNonterminal);\n const reports = new Map(recovered.map((report) => [report.submissionId, report]));\n const head = remaining[0];\n const headWaiting = head !== undefined && stableExternalWait(head, reports);\n const autonomous = remaining.some((snapshot, index) => {\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 index > 0 &&\n headWaiting &&\n snapshot.state === \"ready\" &&\n reports.get(snapshot.submissionId)?.decision._tag === \"ApplyInput\"\n )\n return false;\n return !stableExternalWait(snapshot, reports);\n });\n const progressed =\n settlements.length > 0 || recovered.some((report) => report.disposition === \"repaired\");\n const delay = autonomous ? yield* rearmDelay(progressed) : 0;\n const now = yield* Clock.currentTimeMillis;\n yield* failpoint.hit(\"maintenance:finish:before\");\n const alarmDisposition = yield* generationGate.withPermit(\n Effect.gen(function* () {\n const active = yield* Ref.get(activeMutations);\n return yield* runTransaction(\"finish maintenance pass\", () =>\n ctx.storage.transaction(async (transaction) => {\n const { state } = await readMaintenanceState(transaction);\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 const next = ConversationMaintenanceState.make({\n ...state,\n processed,\n nonterminal: remaining.length,\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(now + delay);\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(transaction, now + config.wakeScanInterval);\n return \"rearmed\" as const;\n }\n await transaction.deleteAlarm();\n return \"cleared\" as const;\n }),\n );\n }),\n );\n yield* failpoint.hit(\"maintenance:finish:after\");\n if (alarmDisposition === \"cleared\") {\n yield* Ref.set(stalls, 0);\n }\n return yield* annotate(\n MaintenancePassReport.make({\n phase: \"actionable\",\n recovered: recovered.length,\n settled: settlements.length,\n nonterminal: remaining.length,\n alarm: alarmDisposition,\n }),\n );\n });\n\n return ConversationMaintenance.of({\n // A mid-pass immediate hint is droppable; durable dirty state decides the final alarm.\n pass: alarm.withWakesDeferred(maintenancePassGate.withPermit(pass())),\n ensureAlarm: ensureAlarm(),\n withMutation,\n });\n }),\n );\n}\n","import type { ConversationId } from \"@effect-agent/core\";\nimport { makeWakeSubscriptionHub, WakeScheduler } from \"@effect-agent/session\";\nimport { Effect, Layer, PubSub, Schema, Stream } from \"effect\";\n\nimport { DurableAlarmService } from \"./alarm.ts\";\nimport { ConversationObjectIdentity, ConversationObjectNamespace } from \"./bindings.ts\";\nimport { safeCauseMessage } from \"./boundary.ts\";\n\n/**\n * Bounded in-memory wake buffer for same-incarnation `awaitSettlement` subscribers. Wake\n * hints are droppable by contract (consumers pair every subscription with ledger polls), so\n * a full buffer slides out the oldest hint and an eviction simply loses the buffer — the\n * poll interval and the persisted alarm keep liveness (persistence §14).\n */\nconst WAKE_BUFFER_CAPACITY = 1_024;\n\n/** A remote wake stub call failed; always swallowed and logged (hints are droppable). */\nclass RemoteWakeDropped extends Schema.TaggedError<RemoteWakeDropped>()(\"RemoteWakeDropped\", {\n conversationId: Schema.String,\n message: Schema.String,\n cause: Schema.optionalKey(Schema.Defect()),\n}) {}\n\n/**\n * The DC `WakeScheduler` (plan §1.4):\n *\n * - `notify(local)` → `setAlarm(now)` — durable, cheap, coalescing (the alarm slot keeps the\n * earliest deadline) — plus a same-incarnation PubSub hint for `awaitSettlement` waiters.\n * - `notify(remote)` → fire-and-forget `wake()` on the owning Object's stub with every error\n * swallowed and logged: hints are droppable, and the target's own alarm/scan pairing (the\n * maintenance pass re-polls unsettled children) guarantees liveness without this call.\n * - `wakes` → the bounded sliding PubSub only. No important state lives in memory: the\n * subscription accelerates waiters within one incarnation and the settlement poll interval\n * is the correctness path.\n */\nexport const cloudflareWakeSchedulerLayer: Layer.Layer<\n WakeScheduler,\n never,\n DurableAlarmService | ConversationObjectIdentity | ConversationObjectNamespace\n> = Layer.effect(WakeScheduler)(\n Effect.gen(function* () {\n const alarm = yield* DurableAlarmService;\n const identity = yield* ConversationObjectIdentity;\n const { namespace } = yield* ConversationObjectNamespace;\n const hints = yield* PubSub.sliding<ConversationId>(WAKE_BUFFER_CAPACITY);\n const progress = yield* makeWakeSubscriptionHub;\n yield* Effect.addFinalizer(() => PubSub.shutdown(hints));\n\n const notifyLocal = (conversationId: ConversationId) =>\n progress.notify(conversationId).pipe(\n Effect.andThen(PubSub.publish(hints, conversationId)),\n Effect.andThen(alarm.scheduleNow),\n Effect.catch((error) =>\n // `notify` never fails by contract; a failed alarm write degrades to \"hint lost\"\n // and the pass re-arm (or the next entry point's pre-arm) restores the invariant.\n Effect.logWarning(\"CloudflareWakeScheduler: local alarm wake failed\", error),\n ),\n Effect.asVoid,\n );\n\n const notifyRemote = (conversationId: ConversationId) =>\n Effect.tryPromise({\n try: () => namespace.get(namespace.idFromName(conversationId)).wake(),\n catch: (cause) =>\n RemoteWakeDropped.make({\n conversationId,\n message: safeCauseMessage(cause, \"The remote wake failed without a diagnostic\"),\n cause,\n }),\n }).pipe(\n Effect.catch((error) =>\n Effect.logWarning(\n `CloudflareWakeScheduler: remote wake of ${conversationId} dropped`,\n error,\n ),\n ),\n Effect.asVoid,\n );\n\n return WakeScheduler.of({\n notify: (conversationId) =>\n conversationId === identity.conversationId\n ? notifyLocal(conversationId)\n : notifyRemote(conversationId),\n subscribe: progress.subscribe,\n wakes: Stream.fromPubSub(hints),\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 a registered waiter, or remember a bounded early cancellation. */\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 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 active.delete(deferred);\n if (active.size === 0) {\n next.delete(waiterId);\n } else {\n next.set(waiterId, active);\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 yield* Effect.addFinalizer(() => remove(waiterId, deferred));\n const cancelled = yield* Ref.modify(registrations, (current) => {\n const existing = current.get(waiterId);\n const next = new Map(current);\n if (existing === \"cancelled\") {\n return [true, current] as const;\n }\n const active = new Set(existing ?? []);\n active.add(deferred);\n next.set(waiterId, active);\n return [false, next] as const;\n });\n return { cancelled, deferred };\n }).pipe(\n Effect.map(({ cancelled, deferred }) =>\n cancelled ? Effect.void : Deferred.await(deferred),\n ),\n ),\n );\n\n const cancel = Effect.fn(\"ProgressWaitRegistry.cancel\")(function* (waiterId: string) {\n const waiters = yield* Ref.modify(registrations, (current) => {\n const existing = current.get(waiterId);\n const next = new Map(current);\n if (existing === undefined) {\n next.set(waiterId, \"cancelled\");\n let tombstones = 0;\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 return [[], next] as const;\n }\n if (existing === \"cancelled\") return [[], current] as const;\n next.delete(waiterId);\n return [[...existing], next] as const;\n });\n yield* Effect.forEach(waiters, (waiter) => Deferred.succeed(waiter, undefined), {\n discard: true,\n });\n });\n\n return ProgressWaitRegistry.of({ subscribe, cancel });\n }),\n );\n}\n","import { ConversationPortTransport, portTransportFailure } from \"@effect-agent/storage-cloudflare\";\nimport { Effect, Layer } from \"effect\";\n\nimport { ConversationObjectNamespace } from \"./bindings.ts\";\n\n/**\n * `ConversationPortTransport` over native Durable Object JS RPC (decision D-P6-3): one\n * `portCall(envelope)` on the stub of the Object that owns the addressed Conversation\n * (`namespace.idFromName(conversationId)` — 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 conversationPortTransportLayer: Layer.Layer<\n ConversationPortTransport,\n never,\n ConversationObjectNamespace\n> = Layer.effect(ConversationPortTransport)(\n Effect.gen(function* () {\n const { namespace } = yield* ConversationObjectNamespace;\n return ConversationPortTransport.of({\n call: (conversationId, request) =>\n Effect.tryPromise({\n try: () => namespace.get(namespace.idFromName(conversationId)).portCall(request),\n catch: (cause) => portTransportFailure(conversationId, cause),\n }).pipe(\n Effect.withSpan(\"CloudflarePortTransport.call\", {\n attributes: { conversationId },\n }),\n ),\n });\n }),\n);\n","import { ConversationId } from \"@effect-agent/core\";\nimport type {\n RunContextPreparation,\n RunCostEstimator,\n RunToolFailureObserver,\n} from \"@effect-agent/engine\";\nimport {\n CurrentToolFailureObserver,\n RunContextPreparationPassthrough,\n toolFailureObserverLayer,\n} from \"@effect-agent/engine\";\nimport {\n AgentBindingResolver,\n DurableAgentRuntime,\n DurableRuntimeConfig,\n DurableRuntimeFailpoint,\n ProducerId,\n operationAuthorizerLayer,\n ToolReconciler,\n type ConversationStore,\n type DurableRuntimeFailpointHandler,\n type OperationAuthorizerService,\n type ResolvedBinding,\n type SubmissionLedger,\n type WakeScheduler,\n} from \"@effect-agent/session\";\nimport {\n conversationStoreLayer,\n executePortRequest,\n routedConversationStoreLayer,\n routedSubmissionLedgerLayer,\n storageConfigLayer,\n storageFailpointLayer,\n submissionLedgerLayer,\n type DoStorageFailpointHandler,\n type DoStorageInitializationError,\n type DoStorageOptions,\n type PortRequest,\n type PortResponse,\n} from \"@effect-agent/storage-cloudflare\";\nimport { BrowserCrypto } from \"@effect/platform-browser\";\nimport { SqliteClient } from \"@effect/sql-sqlite-do\";\nimport type { Crypto } from \"effect\";\nimport { Context, Duration, Effect, Layer, Schema } from \"effect\";\n\nimport {\n ConversationMaintenance,\n ConversationMaintenanceFailpoint,\n DurableAlarmService,\n type ConversationMaintenanceFailpointHandler,\n} from \"./alarm.ts\";\nimport {\n ConversationObjectIdentity,\n DurableObjectContext,\n type ConversationObjectNamespace,\n} from \"./bindings.ts\";\nimport {\n CLOUDFLARE_RUNTIME_DEFAULTS,\n CloudflareDurableRuntimeConfig,\n CloudflareDurableRuntimeConfigValue,\n CloudflarePlatformConfigError,\n} from \"./config.ts\";\nimport { ProgressWaitRegistry } from \"./progress-wait.ts\";\nimport { conversationPortTransportLayer } from \"./transport.ts\";\nimport { cloudflareWakeSchedulerLayer } from \"./wake-scheduler.ts\";\n\n/**\n * Raw (unvalidated) construction options for `CloudflareDurableRuntime.layer`, mirroring\n * `NodeDurableRuntimeOptions`. 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}:{conversationId}`. */\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 /** Conversation-maintenance generation/alarm fault injection; default none. */\n readonly maintenanceFailpoint?:\n | ((ctx: DurableObjectState) => ConversationMaintenanceFailpointHandler)\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 * Registered worker Bindings resolved at durable claim time (S2, spec/subagents.md §11):\n * build each with `DurableWorkerBinding.make(binding, digests)`. The callback receives the live\n * Object context and derived identities and is evaluated once per incarnation during Layer\n * construction. Defaults to the empty registration (every resolved claim fails closed).\n */\n readonly bindings?: CloudflareBindingSource | undefined;\n /**\n * Generic Run context acquired with this Durable Object incarnation. It may prepare model\n * context and/or authorize exact model-declared application Tool Calls at action time. The\n * Layer may depend\n * only on `Crypto.Crypto`, which this platform supplies with `BrowserCrypto`; hosts must close\n * every application-specific service before passing it here. Default absent.\n */\n readonly runContext?: CloudflareRunContextSource | undefined;\n}\n\n/** Per-incarnation host values available to Effect-native runtime extension factories. */\nexport interface CloudflareRuntimeSourceContext {\n readonly ctx: DurableObjectState;\n readonly env: unknown;\n readonly conversationId: ConversationId;\n readonly producerId: ProducerId;\n}\n\n/** Per-incarnation host values available while registered worker Bindings are captured. */\nexport interface CloudflareBindingSourceContext extends CloudflareRuntimeSourceContext {}\n\n/** Captures registered worker Bindings once for each Durable Object incarnation. */\nexport type CloudflareBindingSource = (\n context: CloudflareBindingSourceContext,\n) => Effect.Effect<ReadonlyArray<ResolvedBinding>, never, never>;\n\n/** A closed Run-context service whose only remaining requirement is platform Crypto. */\nexport type CloudflareRunContextLayer = Layer.Layer<RunContextPreparation, never, Crypto.Crypto>;\n\n/** One Layer or a per-incarnation factory over explicit Cloudflare host values. */\nexport type CloudflareRunContextSource =\n | CloudflareRunContextLayer\n | ((context: CloudflareRuntimeSourceContext) => CloudflareRunContextLayer);\n\n/** Every construction failure of the assembled Cloudflare durable runtime stack. */\nexport type CloudflareDurableRuntimeInitializationError =\n | CloudflarePlatformConfigError\n | DoStorageInitializationError;\n\n/** The services `CloudflareDurableRuntime.layer` provides. */\nexport type CloudflareDurableRuntimeServices =\n | DurableAgentRuntime\n | SubmissionLedger\n | ConversationStore\n | WakeScheduler\n | DurableRuntimeConfig\n | AgentBindingResolver\n | CloudflareDurableRuntimeConfig\n | ConversationObjectIdentity\n | DurableAlarmService\n | ConversationMaintenance\n | ConversationObjectPorts\n | ProgressWaitRegistry;\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 ConversationObjectPorts extends Context.Service<\n ConversationObjectPorts,\n {\n readonly handle: (request: PortRequest) => Effect.Effect<PortResponse>;\n }\n>()(\"@effect-agent/platform-cloudflare/ConversationObjectPorts\") {}\n\nconst decodeConfigValue = Schema.decodeUnknownEffect(CloudflareDurableRuntimeConfigValue);\nconst decodeConversationId = Schema.decodeUnknownEffect(ConversationId);\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 Conversation this Object owns, from the Object identity rule (plan §1.2): Conversation\n * Objects are addressed exclusively by `idFromName(conversationId)`, so `ctx.id.name` IS the\n * Conversation ID. An unnamed Object (from `newUniqueId`) is a deployment error, not a lane.\n */\nconst conversationIdFromState = (\n ctx: DurableObjectState,\n): Effect.Effect<ConversationId, CloudflarePlatformConfigError> =>\n ctx.id.name === undefined\n ? Effect.fail(\n CloudflarePlatformConfigError.make({\n message:\n \"This Durable Object was not created via idFromName(conversationId); Conversation \" +\n \"Objects must be addressed by their Conversation identity (plan §1.2).\",\n }),\n )\n : decodeConversationId(ctx.id.name).pipe(\n Effect.mapError((error) =>\n CloudflarePlatformConfigError.make({\n message: `The Durable Object name is not a valid ConversationId: ${error.message}`,\n cause: error,\n }),\n ),\n );\n\nconst resolveBindings = (\n source: CloudflareDurableRuntimeOptions[\"bindings\"],\n context: CloudflareBindingSourceContext,\n): Effect.Effect<ReadonlyArray<ResolvedBinding>> =>\n source === undefined ? Effect.succeed([]) : Effect.suspend(() => source(context));\n\nconst resolveRunContext = (\n source: CloudflareRunContextSource,\n context: CloudflareRuntimeSourceContext,\n): CloudflareRunContextLayer => (typeof source === \"function\" ? source(context) : source);\n\n/**\n * The DC Layer assembly (deployment §12: a Layer-assembly library, not an app entrypoint;\n * plan §1.4). `layer(options)` decodes the configuration, derives this Object's Conversation\n * and producer identities, opens the Object's private SQLite database through\n * `@effect/sql-sqlite-do` for BOTH the Conversation Log and the Submission Ledger (so claims\n * fence the same producer epochs — ADR-0011 D7 transposed), wraps the local port facets with\n * the WP2 cross-Object routing decorators over the Durable Object RPC transport, wires the\n * alarm-backed wake scheduler and the maintenance pass, defaults reconciliation to the\n * fail-closed `ToolReconciler.uncertain`, and provides a ready `DurableAgentRuntime` on top.\n *\n * Storage compatibility is verified during construction: an incompatible database fails the\n * Layer typed (`DoStorageCompatibilityError`) before anything is mutated (DEPLOY-008).\n *\n * Requires only the two binding services (`DurableObjectContext`,\n * `ConversationObjectNamespace`) — platform values enter exclusively through Layers\n * (DEPLOY-010).\n */\nexport class CloudflareDurableRuntime {\n static layer(\n options: CloudflareDurableRuntimeOptions,\n ): Layer.Layer<\n CloudflareDurableRuntimeServices,\n CloudflareDurableRuntimeInitializationError,\n DurableObjectContext | ConversationObjectNamespace\n > {\n return Layer.unwrap(\n Effect.gen(function* () {\n const { ctx, env } = yield* DurableObjectContext;\n const config = yield* configFromOptions(options);\n const conversationId = yield* conversationIdFromState(ctx);\n const producerId = yield* decodeProducerId(\n `${config.producerPrefix}:${conversationId}`,\n ).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 const identityLayer = Layer.succeed(ConversationObjectIdentity)({\n conversationId,\n producerId,\n });\n const cloudflareConfigLayer = Layer.succeed(CloudflareDurableRuntimeConfig)(config);\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 failpoint: options.storageFailpoint?.(ctx),\n };\n const infrastructure = Layer.mergeAll(\n storageConfigLayer(storageOptions),\n storageFailpointLayer(storageOptions),\n SqliteClient.layer({ storage: ctx.storage }),\n BrowserCrypto.layer,\n );\n\n /**\n * ONE local-facet instance (a shared Layer value) serves both the routed decorators\n * and the owner-side `portCall` executor — the executor must never see the routed\n * ports (plan §1.3: re-routing could bounce a request between Objects).\n */\n const localPorts = Layer.mergeAll(conversationStoreLayer, submissionLedgerLayer).pipe(\n Layer.provide(infrastructure),\n );\n\n const portsEndpointLayer = Layer.effect(ConversationObjectPorts)(\n Effect.gen(function* () {\n const local = yield* Effect.context<SubmissionLedger | ConversationStore>();\n return ConversationObjectPorts.of({\n handle: (request) => executePortRequest(request).pipe(Effect.provide(local)),\n });\n }),\n ).pipe(Layer.provide(localPorts));\n\n const routedPorts = Layer.mergeAll(\n routedSubmissionLedgerLayer({ localConversationId: conversationId }),\n routedConversationStoreLayer({ localConversationId: conversationId }),\n ).pipe(Layer.provide(localPorts), Layer.provide(conversationPortTransportLayer));\n\n const runtimeConfigLayer = Layer.succeed(DurableRuntimeConfig)(\n DurableRuntimeConfig.make({\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 );\n\n const runtimeFailpointLayer =\n options.runtimeFailpoint === undefined\n ? DurableRuntimeFailpoint.layer\n : Layer.succeed(DurableRuntimeFailpoint)({ hit: options.runtimeFailpoint(ctx) });\n const maintenanceFailpointLayer =\n options.maintenanceFailpoint === undefined\n ? ConversationMaintenanceFailpoint.layer\n : Layer.succeed(ConversationMaintenanceFailpoint)({\n hit: options.maintenanceFailpoint(ctx),\n });\n const reconcilerLayer = options.toolReconciler ?? ToolReconciler.uncertain;\n const authorizerLayer =\n options.operationAuthorizer === undefined\n ? Layer.empty\n : operationAuthorizerLayer(options.operationAuthorizer);\n const observerLayer =\n options.toolFailureObserver === undefined\n ? Layer.succeed(CurrentToolFailureObserver)(undefined)\n : toolFailureObserverLayer(options.toolFailureObserver);\n const bindingResolverLayer = Layer.effect(AgentBindingResolver)(\n Effect.map(\n resolveBindings(options.bindings, { ctx, env, conversationId, producerId }),\n (bindings) => AgentBindingResolver.fromBindings(bindings),\n ),\n );\n const runContextLayer =\n options.runContext === undefined\n ? RunContextPreparationPassthrough\n : resolveRunContext(options.runContext, { ctx, env, conversationId, producerId }).pipe(\n Layer.provide(BrowserCrypto.layer),\n );\n\n const base = Layer.mergeAll(\n identityLayer,\n cloudflareConfigLayer,\n DurableAlarmService.layer,\n maintenanceFailpointLayer,\n ProgressWaitRegistry.layer,\n );\n\n const runtimeStack = DurableAgentRuntime.layerWithContext.pipe(\n Layer.provideMerge(routedPorts),\n Layer.provideMerge(cloudflareWakeSchedulerLayer),\n Layer.provideMerge(runtimeConfigLayer),\n Layer.provideMerge(bindingResolverLayer),\n Layer.provide(\n Layer.mergeAll(\n runtimeFailpointLayer,\n reconcilerLayer,\n authorizerLayer,\n observerLayer,\n runContextLayer,\n BrowserCrypto.layer,\n ),\n ),\n Layer.provideMerge(base),\n );\n\n return Layer.mergeAll(\n runtimeStack,\n ConversationMaintenance.layer.pipe(Layer.provide(runtimeStack)),\n portsEndpointLayer,\n );\n }),\n );\n }\n}\n","import { AgentId, AgentInputError, type ConversationId } from \"@effect-agent/core\";\nimport {\n AbortCommand,\n AbortIntent,\n AdmissionConflict,\n AppendConflict,\n ApprovalConflict,\n ApprovalDecisionCommand,\n ApprovalDecisionIntent,\n CanonicalRecordEnvelope,\n CanonicalSequence,\n ConversationNotMaterialized,\n ConversationStoreError,\n DefinitionDigests,\n DigestError,\n DurableRuntimeFailpointError,\n FenceRejected,\n IdempotencyKey,\n JoinedToHost,\n LedgerError,\n OperationDenied,\n PersistedJson,\n Principal,\n Receipt,\n Settlement,\n SettlementConflict,\n UnknownResolutionCommand,\n UnknownResolutionConflict,\n UnknownResolutionIntent,\n type DurableSubmitAgent,\n type DurableSubmitOptions,\n} from \"@effect-agent/session\";\nimport { Context, Crypto, Duration, Effect, Layer, Schema } from \"effect\";\nimport { RpcTracing } from \"effect-cf\";\n\nimport { DurableAlarmError } from \"./alarm.ts\";\nimport { ConversationObjectNamespace, type ConversationObjectRpc } from \"./bindings.ts\";\nimport { cloudflareFailureSignals, safeCauseMessage } from \"./boundary.ts\";\nimport { AdmissionLimitExceeded } from \"./config.ts\";\n\n/**\n * The Worker↔Conversation-Object host protocol (plan §1.4): Schema envelopes for the host\n * entry points (`submitEncoded`, `awaitSettlementEncoded`, `observePage`, `abortEncoded`,\n * `resolveApprovalEncoded`, `resolveUnknownEncoded`) plus the Worker-side client that speaks\n * it. Mirrors the WP2 port protocol: requests and responses are closed Schema unions, typed\n * failures travel as their own tagged classes and RE-DECODE to identical tags on the caller\n * (error-tag fidelity), and protocol anomalies are answered typed instead of thrown.\n */\n\n/** Ceiling for host protocol diagnostic strings. */\nconst MAX_HOST_DIAGNOSTIC_LENGTH = 4_096;\n\nconst BoundedDiagnostic = Schema.String.check(Schema.isMaxLength(MAX_HOST_DIAGNOSTIC_LENGTH));\n\n/** Truncate a diagnostic string to the host protocol's bounded length. */\nexport const boundHostDiagnostic = (value: string): string =>\n value.length > MAX_HOST_DIAGNOSTIC_LENGTH\n ? `${value.slice(0, MAX_HOST_DIAGNOSTIC_LENGTH - 3)}...`\n : value;\n\n/**\n * The envelope itself could not be honored: the Object could not decode the request, or a\n * response could not be encoded/decoded. Never carries operation semantics.\n */\nexport class HostProtocolError extends Schema.TaggedError<HostProtocolError>()(\n \"HostProtocolError\",\n {\n message: BoundedDiagnostic,\n },\n) {}\n\n/** The Worker-side stub call itself failed (RPC rejection, overload, eviction mid-call). */\nexport class ConversationClientError extends Schema.TaggedError<ConversationClientError>()(\n \"ConversationClientError\",\n {\n conversationId: Schema.String,\n message: Schema.String,\n cause: Schema.optionalKey(Schema.Defect()),\n /** Cloudflare's own classification for a failure safe to retry with a fresh stub. */\n retryable: Schema.optionalKey(Schema.Boolean),\n /** Cloudflare overloads are surfaced immediately instead of adding retry pressure. */\n overloaded: Schema.optionalKey(Schema.Boolean),\n },\n) {}\n\n// ---------------------------------------------------------------------------\n// Requests\n// ---------------------------------------------------------------------------\n\n/**\n * One durable submission, input ALREADY encoded by the caller through the Agent Binding's\n * input schema (the Worker bundles the same Agent definitions as the Object, so schema\n * validation happens client-side; the resolved Binding re-validates at claim time). The\n * Conversation identity is deliberately absent — the addressed Object IS the lane.\n */\nexport class SubmitRequest extends Schema.Class<SubmitRequest>(\n \"@effect-agent/platform-cloudflare/SubmitRequest\",\n)({\n agentId: AgentId,\n principal: Principal,\n idempotencyKey: IdempotencyKey,\n definitions: DefinitionDigests,\n inputPayload: PersistedJson,\n}) {}\n\n/** One bounded page of canonical records after an optional sequence. */\nexport class ObservePageRequest extends Schema.Class<ObservePageRequest>(\n \"@effect-agent/platform-cloudflare/ObservePageRequest\",\n)({\n afterSequence: Schema.optionalKey(CanonicalSequence),\n limit: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1_024)),\n}) {}\n\n/** One event-driven wait for canonical progress strictly after this sequence. */\nexport class AwaitProgressRequest extends Schema.Class<AwaitProgressRequest>(\n \"@effect-agent/platform-cloudflare/AwaitProgressRequest\",\n)({\n afterSequence: CanonicalSequence,\n waiterId: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)),\n}) {}\n\n/** Best-effort cancellation of one in-flight progress RPC. */\nexport class CancelProgressRequest extends Schema.Class<CancelProgressRequest>(\n \"@effect-agent/platform-cloudflare/CancelProgressRequest\",\n)({\n waiterId: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)),\n}) {}\n\n// ---------------------------------------------------------------------------\n// Responses\n// ---------------------------------------------------------------------------\n\n/**\n * Every typed failure a host entry point can produce, plus the protocol's own errors. Same\n * closed-union discipline as the WP2 `PortFailure`: members re-decode to the SAME tagged\n * classes on the Worker side; `cause` chains travel as Schema defects without instance\n * fidelity (plan §2.8).\n */\nexport const HostFailure = Schema.Union([\n AgentInputError,\n DigestError,\n AdmissionConflict,\n SettlementConflict,\n ApprovalConflict,\n UnknownResolutionConflict,\n JoinedToHost,\n LedgerError,\n ConversationStoreError,\n ConversationNotMaterialized,\n AppendConflict,\n FenceRejected,\n DurableRuntimeFailpointError,\n AdmissionLimitExceeded,\n DurableAlarmError,\n OperationDenied,\n HostProtocolError,\n]);\nexport type HostFailure = typeof HostFailure.Type;\n\nexport class SubmitSucceeded extends Schema.TaggedClass<SubmitSucceeded>(\n \"@effect-agent/platform-cloudflare/SubmitSucceeded\",\n)(\"SubmitSucceeded\", {\n receipt: Receipt,\n}) {}\n\nexport class SettlementReached extends Schema.TaggedClass<SettlementReached>(\n \"@effect-agent/platform-cloudflare/SettlementReached\",\n)(\"SettlementReached\", {\n settlement: Settlement,\n}) {}\n\nexport class ObservedPage extends Schema.TaggedClass<ObservedPage>(\n \"@effect-agent/platform-cloudflare/ObservedPage\",\n)(\"ObservedPage\", {\n records: Schema.Array(CanonicalRecordEnvelope).check(Schema.isMaxLength(1_024)),\n}) {}\n\n/** A record was already committed or an incarnation-local hint says the caller should re-read. */\nexport class ProgressObserved extends Schema.TaggedClass<ProgressObserved>(\n \"@effect-agent/platform-cloudflare/ProgressObserved\",\n)(\"ProgressObserved\", {}) {}\n\nexport class ProgressCancelled extends Schema.TaggedClass<ProgressCancelled>(\n \"@effect-agent/platform-cloudflare/ProgressCancelled\",\n)(\"ProgressCancelled\", {}) {}\n\nexport class AbortRecorded extends Schema.TaggedClass<AbortRecorded>(\n \"@effect-agent/platform-cloudflare/AbortRecorded\",\n)(\"AbortRecorded\", {\n intent: AbortIntent,\n}) {}\n\nexport class ApprovalRecorded extends Schema.TaggedClass<ApprovalRecorded>(\n \"@effect-agent/platform-cloudflare/ApprovalRecorded\",\n)(\"ApprovalRecorded\", {\n intent: ApprovalDecisionIntent,\n}) {}\n\nexport class UnknownResolutionRecorded extends Schema.TaggedClass<UnknownResolutionRecorded>(\n \"@effect-agent/platform-cloudflare/UnknownResolutionRecorded\",\n)(\"UnknownResolutionRecorded\", {\n intent: UnknownResolutionIntent,\n}) {}\n\n/** The entry point failed TYPED on the Object; the failure re-decodes verbatim. */\nexport class HostFailed extends Schema.TaggedClass<HostFailed>(\n \"@effect-agent/platform-cloudflare/HostFailed\",\n)(\"HostFailed\", {\n failure: HostFailure,\n}) {}\n\n/** The uniform answer of one host entry point. Callers narrow by the tag their call implies. */\nexport const HostResponse = Schema.Union([\n SubmitSucceeded,\n SettlementReached,\n ObservedPage,\n ProgressObserved,\n ProgressCancelled,\n AbortRecorded,\n ApprovalRecorded,\n UnknownResolutionRecorded,\n HostFailed,\n]);\nexport type HostResponse = typeof HostResponse.Type;\n\n// ---------------------------------------------------------------------------\n// Codecs (shared by the Object endpoints and the Worker client)\n// ---------------------------------------------------------------------------\n\nexport const decodeSubmitRequest = Schema.decodeUnknownEffect(SubmitRequest);\nexport const encodeSubmitRequest = Schema.encodeEffect(SubmitRequest);\nexport const decodeReceipt = Schema.decodeUnknownEffect(Receipt);\nexport const encodeReceipt = Schema.encodeEffect(Receipt);\nexport const decodeObservePageRequest = Schema.decodeUnknownEffect(ObservePageRequest);\nexport const encodeObservePageRequest = Schema.encodeEffect(ObservePageRequest);\nexport const decodeAwaitProgressRequest = Schema.decodeUnknownEffect(AwaitProgressRequest);\nexport const encodeAwaitProgressRequest = Schema.encodeEffect(AwaitProgressRequest);\nexport const decodeCancelProgressRequest = Schema.decodeUnknownEffect(CancelProgressRequest);\nexport const encodeCancelProgressRequest = Schema.encodeEffect(CancelProgressRequest);\nexport const decodeAbortCommand = Schema.decodeUnknownEffect(AbortCommand);\nexport const encodeAbortCommand = Schema.encodeEffect(AbortCommand);\nexport const decodeApprovalDecisionCommand = Schema.decodeUnknownEffect(ApprovalDecisionCommand);\nexport const encodeApprovalDecisionCommand = Schema.encodeEffect(ApprovalDecisionCommand);\nexport const decodeUnknownResolutionCommand = Schema.decodeUnknownEffect(UnknownResolutionCommand);\nexport const encodeUnknownResolutionCommand = Schema.encodeEffect(UnknownResolutionCommand);\nexport const encodeHostResponse = Schema.encodeEffect(HostResponse);\nexport const decodeHostResponse = Schema.decodeUnknownEffect(HostResponse);\n\n// ---------------------------------------------------------------------------\n// Worker-side client\n// ---------------------------------------------------------------------------\n\n/** Failure surface of `CloudflareConversationClient.submit`. */\nconst ClientSubmitHostFailure = Schema.Union([\n AgentInputError,\n DigestError,\n AdmissionConflict,\n LedgerError,\n ConversationStoreError,\n ConversationNotMaterialized,\n AppendConflict,\n FenceRejected,\n DurableRuntimeFailpointError,\n AdmissionLimitExceeded,\n DurableAlarmError,\n HostProtocolError,\n]);\nconst ClientAwaitHostFailure = Schema.Union([LedgerError, SettlementConflict, HostProtocolError]);\nconst ClientObserveHostFailure = Schema.Union([\n ConversationStoreError,\n ConversationNotMaterialized,\n OperationDenied,\n HostProtocolError,\n]);\nconst ClientAbortHostFailure = Schema.Union([\n LedgerError,\n SettlementConflict,\n JoinedToHost,\n DurableRuntimeFailpointError,\n DurableAlarmError,\n HostProtocolError,\n]);\nconst ClientApprovalHostFailure = Schema.Union([\n LedgerError,\n SettlementConflict,\n ApprovalConflict,\n OperationDenied,\n DurableAlarmError,\n HostProtocolError,\n]);\nconst ClientUnknownHostFailure = Schema.Union([\n LedgerError,\n SettlementConflict,\n UnknownResolutionConflict,\n JoinedToHost,\n DurableRuntimeFailpointError,\n OperationDenied,\n DurableAlarmError,\n HostProtocolError,\n]);\n\nexport type ClientSubmitFailure = typeof ClientSubmitHostFailure.Type | ConversationClientError;\nexport type ClientAwaitFailure = typeof ClientAwaitHostFailure.Type | ConversationClientError;\nexport type ClientObserveFailure = typeof ClientObserveHostFailure.Type | ConversationClientError;\nexport type ClientProgressFailure = ClientObserveFailure;\nexport type ClientAbortFailure = typeof ClientAbortHostFailure.Type | ConversationClientError;\nexport type ClientApprovalFailure = typeof ClientApprovalHostFailure.Type | ConversationClientError;\nexport type ClientUnknownFailure = typeof ClientUnknownHostFailure.Type | ConversationClientError;\n\nconst outOfContract = (\n conversationId: string,\n operation: string,\n observed: string,\n): ConversationClientError =>\n ConversationClientError.make({\n conversationId,\n message: boundHostDiagnostic(\n `The Conversation Object answered ${operation} with the out-of-contract ${observed}.`,\n ),\n });\n\nconst hostRpcMethods = {\n submit: \"submitEncoded\",\n awaitSettlement: \"awaitSettlementEncoded\",\n awaitProgress: \"awaitProgressEncoded\",\n cancelProgress: \"cancelProgressEncoded\",\n observePage: \"observePage\",\n abort: \"abortEncoded\",\n resolveApproval: \"resolveApprovalEncoded\",\n resolveUnknown: \"resolveUnknownEncoded\",\n} as const satisfies Record<string, keyof ConversationObjectRpc>;\n\n/** Worker-side client over the Conversation Object namespace (DEPLOY-010). */\nexport class CloudflareConversationClient extends Context.Service<\n CloudflareConversationClient,\n {\n /** Encode the input client-side, then durably submit to the owning Object. */\n readonly submit: <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: DurableSubmitOptions,\n ) => Effect.Effect<Receipt, ClientSubmitFailure, InputSchema[\"EncodingServices\"]>;\n /** Wake-hinted, poll-guaranteed settlement wait executed inside the owning Object. */\n readonly awaitSettlement: (receipt: Receipt) => Effect.Effect<Settlement, ClientAwaitFailure>;\n /**\n * Wait without polling until progress after `afterSequence` is already durable or hinted.\n * The result is deliberately void: canonical records remain authoritative and must be read.\n */\n readonly awaitProgress: (\n conversationId: ConversationId,\n afterSequence: CanonicalSequence,\n ) => Effect.Effect<void, ClientProgressFailure>;\n /** One bounded page of canonical records. */\n readonly readPage: (\n conversationId: ConversationId,\n options?: {\n readonly afterSequence?: CanonicalSequence | undefined;\n readonly limit?: number | undefined;\n },\n ) => Effect.Effect<ReadonlyArray<CanonicalRecordEnvelope>, ClientObserveFailure>;\n /**\n * Every canonical record up to the CURRENT committed tail, via repeated pages. A\n * snapshot read, not a live observation — callers wanting liveness re-read after\n * `awaitSettlement`.\n */\n readonly readAll: (\n conversationId: ConversationId,\n ) => Effect.Effect<ReadonlyArray<CanonicalRecordEnvelope>, ClientObserveFailure>;\n /**\n * Submission-addressed operations take the owning Conversation explicitly (from the\n * Receipt): minted Submission identities stay OPAQUE outside the storage adapter that\n * minted them (D-P6-5), so the client never parses one to find the lane.\n */\n readonly abort: (\n conversationId: ConversationId,\n command: AbortCommand,\n ) => Effect.Effect<AbortIntent, ClientAbortFailure>;\n readonly resolveApproval: (\n conversationId: ConversationId,\n command: ApprovalDecisionCommand,\n ) => Effect.Effect<ApprovalDecisionIntent, ClientApprovalFailure>;\n readonly resolveUnknown: (\n conversationId: ConversationId,\n command: UnknownResolutionCommand,\n ) => Effect.Effect<UnknownResolutionIntent, ClientUnknownFailure>;\n }\n>()(\"@effect-agent/platform-cloudflare/CloudflareConversationClient\") {\n static readonly layer: Layer.Layer<\n CloudflareConversationClient,\n never,\n ConversationObjectNamespace | Crypto.Crypto\n > = Layer.effect(CloudflareConversationClient)(\n Effect.gen(function* () {\n const { namespace, rpcTracing } = yield* ConversationObjectNamespace;\n const crypto = yield* Crypto.Crypto;\n\n const call = Effect.fn(\n function* (\n conversationId: string,\n operation: keyof typeof hostRpcMethods,\n encoded: unknown,\n ): Effect.fn.Return<HostResponse, ConversationClientError | HostProtocolError> {\n // Empty arguments preserve native arity. Passing `undefined` still adds an argument.\n const traceArgs =\n rpcTracing === undefined ? [] : yield* RpcTracing.withRpcTraceContext([]);\n const raw = yield* Effect.tryPromise({\n try: () => {\n const stub = namespace.get(namespace.idFromName(conversationId));\n return stub[hostRpcMethods[operation]](encoded, ...traceArgs);\n },\n catch: (cause) =>\n ConversationClientError.make({\n conversationId,\n message: boundHostDiagnostic(\n `${operation} did not reach the Conversation Object: ${safeCauseMessage(\n cause,\n \"the RPC failed without a diagnostic\",\n )}`,\n ),\n cause,\n ...cloudflareFailureSignals(cause),\n }),\n });\n return yield* decodeHostResponse(raw).pipe(\n Effect.mapError(\n (error): HostProtocolError =>\n HostProtocolError.make({\n message: boundHostDiagnostic(\n `The ${operation} answer could not be decoded: ${error.message}`,\n ),\n }),\n ),\n );\n },\n (effect, conversationId, operation) =>\n rpcTracing === undefined\n ? Effect.withSpan(effect, \"CloudflareConversationClient.call\", {\n attributes: { conversationId, operation },\n })\n : RpcTracing.withRpcClientSpan(effect, rpcTracing, hostRpcMethods[operation]),\n );\n\n const expect = <ResultSchema extends Schema.Top, FailureSchema extends Schema.Top>(\n conversationId: string,\n operation: string,\n resultSchema: ResultSchema,\n failureSchema: FailureSchema,\n ) => {\n const isExpectedResult = Schema.is(resultSchema);\n const isExpectedFailure = Schema.is(failureSchema);\n return (\n response: HostResponse,\n ): Effect.Effect<ResultSchema[\"Type\"], FailureSchema[\"Type\"] | ConversationClientError> => {\n if (response._tag === \"HostFailed\") {\n const failure = response.failure;\n return isExpectedFailure(failure)\n ? Effect.fail(failure)\n : Effect.fail(outOfContract(conversationId, operation, `failure ${failure._tag}`));\n }\n if (!isExpectedResult(response)) {\n return Effect.fail(outOfContract(conversationId, operation, `result ${response._tag}`));\n }\n return Effect.succeed(response);\n };\n };\n\n const readPage = (\n conversationId: ConversationId,\n options?: {\n readonly afterSequence?: CanonicalSequence | undefined;\n readonly limit?: number | undefined;\n },\n ) =>\n Effect.gen(function* () {\n const request = ObservePageRequest.make({\n ...(options?.afterSequence === undefined\n ? {}\n : { afterSequence: options.afterSequence }),\n limit: options?.limit ?? 256,\n });\n const encoded = yield* encodeObservePageRequest(request).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`observePage request encode failed: ${error.message}`),\n }),\n ),\n );\n const response = yield* call(conversationId, \"observePage\", encoded);\n const page = yield* expect(\n conversationId,\n \"observePage\",\n ObservedPage,\n ClientObserveHostFailure,\n )(response);\n return page.records;\n });\n\n const cancelProgress = (\n conversationId: ConversationId,\n waiterId: string,\n ): Effect.Effect<void> =>\n encodeCancelProgressRequest(CancelProgressRequest.make({ waiterId })).pipe(\n Effect.mapError(() => undefined),\n Effect.flatMap((encoded) => call(conversationId, \"cancelProgress\", encoded)),\n Effect.asVoid,\n Effect.ignore,\n );\n\n return CloudflareConversationClient.of({\n submit: <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: DurableSubmitOptions,\n ) =>\n Effect.gen(function* () {\n // Client-side half of `DurableAgentRuntime.submit`'s input boundary: encode\n // through the Agent's input schema and prove the canonical persistence bounds.\n const encodedInput = yield* Schema.encodeEffect(agent.definition.input)(input).pipe(\n Effect.mapError((cause) =>\n AgentInputError.make({ message: `Unable to encode Agent input: ${cause.message}` }),\n ),\n );\n const inputPayload = yield* Schema.decodeUnknownEffect(PersistedJson)(\n encodedInput,\n ).pipe(\n Effect.mapError(() =>\n AgentInputError.make({\n message: \"Agent input does not satisfy the canonical persistence bounds\",\n }),\n ),\n );\n const request = SubmitRequest.make({\n agentId: agent.definition.id,\n principal: options.principal,\n idempotencyKey: options.idempotencyKey,\n definitions: options.definitions,\n inputPayload,\n });\n const encoded = yield* encodeSubmitRequest(request).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`submit request encode failed: ${error.message}`),\n }),\n ),\n );\n const response = yield* call(options.conversationId, \"submit\", encoded);\n const succeeded = yield* expect(\n options.conversationId,\n \"submit\",\n SubmitSucceeded,\n ClientSubmitHostFailure,\n )(response);\n return succeeded.receipt;\n }),\n\n awaitSettlement: (receipt) =>\n Effect.gen(function* () {\n const encoded = yield* encodeReceipt(receipt).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`receipt encode failed: ${error.message}`),\n }),\n ),\n );\n const response = yield* call(receipt.conversationId, \"awaitSettlement\", encoded);\n const settled = yield* expect(\n receipt.conversationId,\n \"awaitSettlement\",\n SettlementReached,\n ClientAwaitHostFailure,\n )(response);\n return settled.settlement;\n }),\n\n awaitProgress: (conversationId, afterSequence) =>\n Effect.gen(function* () {\n const waiterId = yield* crypto.randomUUIDv4.pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(\n `awaitProgress cancellation identity generation failed: ${error.message}`,\n ),\n }),\n ),\n );\n const request = AwaitProgressRequest.make({ afterSequence, waiterId });\n const encoded = yield* encodeAwaitProgressRequest(request).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(\n `awaitProgress request encode failed: ${error.message}`,\n ),\n }),\n ),\n );\n\n const attempt = (retry: number): Effect.Effect<void, ClientProgressFailure> =>\n call(conversationId, \"awaitProgress\", encoded).pipe(\n Effect.flatMap(\n expect(\n conversationId,\n \"awaitProgress\",\n ProgressObserved,\n ClientObserveHostFailure,\n ),\n ),\n Effect.asVoid,\n Effect.catchTag(\"ConversationClientError\", (error) =>\n error.retryable === true && error.overloaded !== true && retry < 5\n ? Effect.sleep(Duration.millis(10 * 2 ** retry)).pipe(\n Effect.andThen(attempt(retry + 1)),\n )\n : Effect.fail(error),\n ),\n );\n\n yield* attempt(0).pipe(\n Effect.onInterrupt(() => cancelProgress(conversationId, waiterId)),\n );\n }),\n\n readPage,\n\n readAll: (conversationId) =>\n Effect.gen(function* () {\n const all: Array<CanonicalRecordEnvelope> = [];\n let after: CanonicalSequence | undefined;\n for (;;) {\n const page = yield* readPage(conversationId, { afterSequence: after, limit: 1_024 });\n all.push(...page);\n const last = page.at(-1);\n if (page.length < 1_024 || last === undefined) return all;\n after = last.sequence;\n }\n }),\n\n abort: (conversationId, command) =>\n Effect.gen(function* () {\n const encoded = yield* encodeAbortCommand(command).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`abort command encode failed: ${error.message}`),\n }),\n ),\n );\n const response = yield* call(conversationId, \"abort\", encoded);\n const recorded = yield* expect(\n conversationId,\n \"abort\",\n AbortRecorded,\n ClientAbortHostFailure,\n )(response);\n return recorded.intent;\n }),\n\n resolveApproval: (conversationId, command) =>\n Effect.gen(function* () {\n const encoded = yield* encodeApprovalDecisionCommand(command).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`approval command encode failed: ${error.message}`),\n }),\n ),\n );\n const response = yield* call(conversationId, \"resolveApproval\", encoded);\n const recorded = yield* expect(\n conversationId,\n \"resolveApproval\",\n ApprovalRecorded,\n ClientApprovalHostFailure,\n )(response);\n return recorded.intent;\n }),\n\n resolveUnknown: (conversationId, command) =>\n Effect.gen(function* () {\n const encoded = yield* encodeUnknownResolutionCommand(command).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(\n `resolution command encode failed: ${error.message}`,\n ),\n }),\n ),\n );\n const response = yield* call(conversationId, \"resolveUnknown\", encoded);\n const recorded = yield* expect(\n conversationId,\n \"resolveUnknown\",\n UnknownResolutionRecorded,\n ClientUnknownHostFailure,\n )(response);\n return recorded.intent;\n }),\n });\n }),\n );\n}\n","import type { AgentId } from \"@effect-agent/core\";\nimport { SubmissionId } from \"@effect-agent/core\";\nimport {\n AppendConflict,\n ConversationNotMaterialized,\n ConversationRead,\n ConversationStore,\n ConversationStoreError,\n DigestError,\n DurableAgentRuntime,\n DurableRuntimeFailpointError,\n FenceRejected,\n IntegrityReport,\n LedgerError,\n ObligationReport,\n ObligationThresholds,\n OperationAuthorizationRequest,\n OperationAuthorizer,\n OperationDenied,\n OwnershipLost,\n PersistedJson,\n RecoveryExplanation,\n RecoveryReport,\n RetryCommand,\n RetryRefused,\n RunJournalError,\n SettlementConflict,\n SubmissionLedger,\n SubmissionLookupByKey,\n WakeScheduler,\n type DurableSubmitAgent,\n} from \"@effect-agent/session\";\nimport {\n decodePortRequest,\n encodePortResponse,\n type PortRequest,\n} from \"@effect-agent/storage-cloudflare\";\nimport { Effect, Layer, Option, Schema, Stream } from \"effect\";\nimport {\n DurableObject as EffectCfDurableObject,\n DurableObjectState as EffectCfDurableObjectState,\n WorkerEnvironment,\n} from \"effect-cf\";\n\nimport {\n ConversationMaintenance,\n DurableAlarmError,\n DurableAlarmService,\n type MaintenancePassFailure,\n} from \"./alarm.ts\";\nimport {\n ConversationObjectIdentity,\n DurableObjectContext,\n ConversationObjectNamespace,\n conversationNamespaceFromEnv,\n type CloudflareBindingError,\n} from \"./bindings.ts\";\nimport {\n AbortRecorded,\n ApprovalRecorded,\n HostFailed,\n HostProtocolError,\n ObservedPage,\n ProgressObserved,\n ProgressCancelled,\n SettlementReached,\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} from \"./client.ts\";\nimport { AdmissionLimitExceeded, CloudflareDurableRuntimeConfig } from \"./config.ts\";\nimport {\n CloudflareDurableRuntime,\n ConversationObjectPorts,\n type CloudflareDurableRuntimeInitializationError,\n type CloudflareDurableRuntimeOptions,\n type CloudflareDurableRuntimeServices,\n} from \"./layers.ts\";\nimport { ProgressWaitRegistry } from \"./progress-wait.ts\";\n\n/**\n * `makeConversationObjectClass(options, observability?)` — the Conversation 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 Conversation 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` + `processConversationResolved` pass, and the persisted alarm\n * (the single multiplexed slot, D-P6-2) finishes accepted work across evictions WITHOUT any\n * incoming request.\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 Conversation Object class. */\nexport interface ConversationObjectOptions 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 Conversation 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}\n\ntype EndpointServices = CloudflareDurableRuntimeServices | DurableObjectContext;\ntype RuntimeServices = EndpointServices | ConversationObjectNamespace;\ntype ConversationObjectInitializationError =\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 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(\"ConversationObject.gateAdmissionLimits\")(\n function* (request: {\n readonly principal: SubmissionLookupByKey[\"principal\"];\n readonly idempotencyKey: SubmissionLookupByKey[\"idempotencyKey\"];\n readonly inputPayload: PersistedJson;\n }) {\n const identity = yield* ConversationObjectIdentity;\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 conversationId: identity.conversationId,\n principal: request.principal,\n idempotencyKey: request.idempotencyKey,\n }),\n );\n if (Option.isSome(existing)) return;\n\n const inputBytes = utf8Bytes(request.inputPayload);\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 // One Conversation per Object (durability §5): the local scan IS this lane's queue.\n const nonterminal = yield* Stream.runCollect(ledger.scanNonterminal);\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 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/**\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\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* ConversationObjectIdentity;\n const maintenance = yield* ConversationMaintenance;\n const runtime = yield* DurableAgentRuntime;\n yield* gateAdmissionLimits(request);\n // Alarm invariant: the generation + alarm commit BEFORE the admission, and maintenance\n // cannot acknowledge that generation until this mutation leaves its public RPC seam.\n const receipt = yield* maintenance.withMutation(\n runtime.submit(passthroughSubmitAgent(request.agentId), request.inputPayload, {\n conversationId: identity.conversationId,\n principal: request.principal,\n idempotencyKey: request.idempotencyKey,\n definitions: request.definitions,\n }),\n );\n return SubmitSucceeded.make({ 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 runtime = yield* DurableAgentRuntime;\n const settlement = yield* runtime.awaitSettlement(receipt);\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* ConversationObjectIdentity;\n const runtime = yield* DurableAgentRuntime;\n const registry = yield* ProgressWaitRegistry;\n yield* Effect.scoped(\n Effect.gen(function* () {\n const cancelled = yield* registry.subscribe(request.waiterId);\n yield* Effect.raceFirst(\n runtime.awaitProgress(identity.conversationId, request.afterSequence),\n cancelled,\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 registry = yield* ProgressWaitRegistry;\n yield* registry.cancel(request.waiterId);\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* ConversationObjectIdentity;\n const store = yield* ConversationStore;\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 yield* authorizer.authorize(\n OperationAuthorizationRequest.make({\n operation: \"observe\",\n conversationId: identity.conversationId,\n }),\n );\n const records = yield* Stream.runCollect(\n store.read(\n ConversationRead.make({\n conversationId: identity.conversationId,\n ...(request.afterSequence === undefined\n ? {}\n : { afterSequence: request.afterSequence }),\n limit: request.limit,\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 maintenance = yield* ConversationMaintenance;\n const runtime = yield* DurableAgentRuntime;\n const intent = yield* maintenance.withMutation(runtime.abort(command));\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 maintenance = yield* ConversationMaintenance;\n const runtime = yield* DurableAgentRuntime;\n const intent = yield* maintenance.withMutation(runtime.resolveApproval(command));\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 maintenance = yield* ConversationMaintenance;\n const runtime = yield* DurableAgentRuntime;\n const intent = yield* maintenance.withMutation(runtime.resolveUnknown(command));\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 OperationDenied,\n RetryRefused,\n LedgerError,\n RunJournalError,\n DigestError,\n OwnershipLost,\n SettlementConflict,\n ConversationStoreError,\n ConversationNotMaterialized,\n AppendConflict,\n FenceRejected,\n DurableRuntimeFailpointError,\n DurableAlarmError,\n HostProtocolError,\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]);\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* ConversationObjectIdentity;\n const runtime = yield* DurableAgentRuntime;\n const explanations =\n request.submissionId === undefined\n ? yield* runtime.explainConversation(identity.conversationId)\n : [yield* runtime.explain(request.submissionId)];\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* ConversationObjectIdentity;\n const runtime = yield* DurableAgentRuntime;\n const report = yield* runtime.verify(identity.conversationId);\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* ConversationMaintenance;\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 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 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 portCallEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n Effect.gen(function* () {\n const ports = yield* ConversationObjectPorts;\n const maintenance = yield* ConversationMaintenance;\n const alarm = yield* DurableAlarmService;\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 if (decoded._tag === \"failure\") {\n return encodedPortProtocolFailure(\n `The port request could not be decoded: ${decoded.message}`,\n );\n }\n const mutating = isMutatingPortRequest(decoded.request);\n const handled = yield* (\n mutating\n ? maintenance.withMutation(ports.handle(decoded.request))\n : ports.handle(decoded.request)\n ).pipe(Effect.exit);\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 const response = yield* encodePortResponse(handled.value).pipe(\n Effect.catch((error) =>\n Effect.succeed(\n encodedPortProtocolFailure(`The port response could not be encoded: ${error.message}`),\n ),\n ),\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(\"ConversationObject.portCall: immediate re-arm failed\", error),\n ),\n );\n }\n return response;\n });\n\nconst wakeEndpoint: Effect.Effect<void, never, EndpointServices> = Effect.gen(function* () {\n const identity = yield* ConversationObjectIdentity;\n const wake = yield* WakeScheduler;\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.conversationId);\n});\n\nconst alarmEndpoint: Effect.Effect<void, MaintenancePassFailure, EndpointServices> = Effect.gen(\n function* () {\n const maintenance = yield* ConversationMaintenance;\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 ConversationMaintenance 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* ConversationMaintenance;\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 | ConversationObjectNamespace,\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 return DurableObjectContext.of({ ctx: state.raw, env });\n }),\n );\n const namespace = Layer.effect(ConversationObjectNamespace)(\n Effect.gen(function* () {\n const env = yield* WorkerEnvironment;\n const binding = yield* conversationNamespaceFromEnv(env, namespaceBinding);\n return ConversationObjectNamespace.of({\n namespace: binding,\n ...(rpcTracing === true ? { rpcTracing: namespaceBinding } : {}),\n });\n }),\n );\n return Layer.merge(context, namespace);\n};\n\n/** The public endpoints and effect-cf invocation hook of one Conversation Object instance. */\nexport interface ConversationObjectInstance<EventServices = never> extends InstanceType<\n EffectCfDurableObject.DurableObjectClass<Record<never, never>, RuntimeServices | EventServices>\n> {\n submitEncoded(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 Conversation Object. */\nexport interface ConversationObjectClass<EventServices = never> {\n new (ctx: DurableObjectState, env: Cloudflare.Env): ConversationObjectInstance<EventServices>;\n}\n\n/**\n * Build the application's Conversation Object class (export it from the Worker entry).\n * effect-cf owns the cached ManagedRuntime, native RPC methods, event scopes, and post-handler\n * OTLP flush scheduling for RPC and alarm events. The optional outer Layer is built per native\n * event, so a host can install Tracer/Logger/Metric services and `OtlpExporter.Flusher` without\n * Effect Agent owning exporter lifecycle machinery.\n */\nexport const makeConversationObjectClass = <EventLayerError = never, EventServices = never>(\n options: ConversationObjectOptions,\n observability?: Layer.Layer<\n EventServices,\n EventLayerError,\n | DurableObjectContext\n | ConversationObjectNamespace\n | EffectCfDurableObjectState.DurableObjectState\n | WorkerEnvironment\n >,\n): ConversationObjectClass<EventServices> => {\n const application: Layer.Layer<\n RuntimeServices,\n CloudflareDurableRuntimeInitializationError | CloudflareBindingError,\n EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment\n > = CloudflareDurableRuntime.layer(options).pipe(\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,\n ConversationObjectInitializationError,\n EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment\n > = Layer.effectContext(\n Effect.gen(function* () {\n const state = yield* EffectCfDurableObjectState.DurableObjectState;\n const scope = yield* Effect.scope;\n return yield* state.blockConcurrencyWhile(\n Effect.gen(function* () {\n const services = yield* Layer.buildWithScope(application, scope);\n yield* gateEndpoint.pipe(Effect.provide(services));\n return services;\n }),\n );\n }),\n );\n\n const rpc = {\n submitEncoded: (encoded: unknown) => submitEndpoint(encoded),\n awaitSettlementEncoded: (encoded: unknown) => awaitSettlementEndpoint(encoded),\n awaitProgressEncoded: (encoded: unknown) => awaitProgressEndpoint(encoded),\n cancelProgressEncoded: (encoded: unknown) => cancelProgressEndpoint(encoded),\n observePage: (encoded: unknown) => observePageEndpoint(encoded),\n abortEncoded: (encoded: unknown) => abortEndpoint(encoded),\n resolveApprovalEncoded: (encoded: unknown) => resolveApprovalEndpoint(encoded),\n resolveUnknownEncoded: (encoded: unknown) => resolveUnknownEndpoint(encoded),\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 portCall: (encoded: unknown) => portCallEndpoint(encoded),\n wake: () => wakeEndpoint,\n } satisfies EffectCfDurableObject.DurableObjectRpc<RuntimeServices | EventServices>;\n\n const EffectCfConversationObject = EffectCfDurableObject.make<\n RuntimeServices,\n ConversationObjectInitializationError,\n EventServices,\n EventLayerError,\n typeof rpc\n >(runtime, {\n ...(options.rpcTracing === true ? { rpcTracing: { service: options.namespaceBinding } } : {}),\n ...(observability === undefined ? {} : { eventLayer: observability }),\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 });\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 ConversationObject extends EffectCfConversationObject {\n override alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> | void {\n return super.alarm?.(alarmInfo);\n }\n }\n\n return ConversationObject;\n};\n","import {\n CodeExecutionHost,\n CodeExecutionResourceUse,\n CodeExecutionResult,\n CodeExecutionTimeoutError,\n CodeExecutor,\n CodeExecutorStartError,\n CodeExecutorTerminatedError,\n CodeExecutorUnsupportedError,\n CodeExecutionProtocolError,\n CodeHostCall,\n CodeHostCallLimitError,\n CodeHostCallResult,\n CodeOutputLimitError,\n CodeProgramFailedError,\n CodeSourceError,\n SandboxImplementation,\n type CodeExecutorExecute,\n type CodeExecutionRequest,\n} from \"@effect-agent/sandbox\";\nimport { RpcTarget } from \"cloudflare:workers\";\nimport { Clock, Duration, Effect, Exit, Fiber, Layer, Option, Queue, Schema } from \"effect\";\n\nimport { safeCauseDiagnostic, safeCauseMessage } from \"./boundary.ts\";\n\n/**\n * The Cloudflare Dynamic Worker `CodeExecutor` adapter (C4 of ADR-0017;\n * DEPLOY-011). Each pass loads one fresh Worker through the Worker Loader\n * with `globalOutbound: null`, so generated code has no ambient network,\n * bindings, or secrets; its only authority is the pass-scoped RPC target that\n * routes back into the owning event's `CodeExecutionHost` service. Platform\n * CPU limits stop synchronous runaway programs; the executor-owned wall-clock\n * deadline interrupts asynchronously suspended passes. Deployment class `E`\n * only: the adapter records no persistent state and a later pass may run in a\n * completely different isolate.\n */\nexport const dynamicWorkerImplementation = SandboxImplementation.make({\n isolation: \"isolated\",\n identity: \"cloudflare-dynamic-worker\",\n});\n\ninterface CodeModePassHost extends Rpc.RpcTargetBranded {\n readonly call: (hostCall: unknown) => Promise<unknown>;\n}\n\ninterface CodeModeHarnessEntrypoint extends Rpc.WorkerEntrypointBranded {\n readonly run: (host: CodeModePassHost) => Promise<unknown>;\n}\n\n/**\n * One object-capability endpoint for one execution pass. Workers RPC invokes\n * the target in the request context where it was created, so the native\n * Promise returned by `dispatch` and the Effect fiber that settles it share\n * one I/O owner. Passing the target as `run()`'s argument also scopes the\n * remote stub to that RPC call; no request state lives at module scope.\n */\nclass CodeModePassHostTarget extends RpcTarget implements CodeModePassHost {\n readonly #dispatch: (hostCall: unknown) => Promise<unknown>;\n\n constructor(dispatch: (hostCall: unknown) => Promise<unknown>) {\n super();\n this.#dispatch = dispatch;\n }\n\n call(hostCall: unknown): Promise<unknown> {\n return this.#dispatch(hostCall);\n }\n}\n\n/**\n * The fixed harness loaded as the dynamic worker's main module. The generated\n * source becomes `program.mjs` (`export default (<expression>);`) — a module,\n * never `eval`. The harness installs namespace globals and a bounded console,\n * imports the program, invokes it exactly once, and returns one envelope the\n * host validates through Effect Schema.\n */\nconst HARNESS_MODULE = String.raw`\nimport { WorkerEntrypoint } from \"cloudflare:workers\";\nimport programDefault from \"./program.js\";\n\nconst encoder = new TextEncoder();\nconst utf8 = (text) => encoder.encode(text).byteLength;\nconst safeText = (value) => {\n try {\n if (value instanceof Error) return (value.name + \": \" + value.message).slice(0, 4000);\n if (typeof value === \"string\") return value.slice(0, 4000);\n const encoded = JSON.stringify(value);\n return (encoded === undefined ? String(value) : encoded).slice(0, 4000);\n } catch {\n return \"[unserializable value]\";\n }\n};\nconst safeJson = (value) => {\n try {\n const encoded = JSON.stringify(value);\n if (encoded !== undefined && encoded.length <= 4000) return JSON.parse(encoded);\n } catch {}\n return safeText(value);\n};\n\nexport default class CodeModeHarness extends WorkerEntrypoint {\n async run(host) {\n const config = this.env.CODE_MODE_PASS;\n const limits = config.limits;\n const logs = [];\n let logBytes = 0;\n let fatal;\n const boundedLogs = () => logs.slice(0, 4096);\n const write = (...values) => {\n const joined = values.map(safeText).join(\" \");\n const line = joined.length > 16000 ? joined.slice(0, 15999) + \"…\" : joined;\n const bytes = utf8(line);\n if (logs.length >= 4096 || logBytes + bytes > limits.maxLogBytes) {\n fatal = fatal ?? { _tag: \"log-limit\", observed: logBytes + bytes, logs: boundedLogs() };\n throw new Error(\"code-mode log limit exceeded\");\n }\n logs.push(line);\n logBytes += bytes;\n };\n globalThis.console = { log: write, info: write, warn: write, error: write, debug: write };\n\n let hostCalls = 0;\n const makeMethod = (namespace, method) => async (argument) => {\n hostCalls += 1;\n if (hostCalls > limits.maxHostCalls) {\n fatal = fatal ?? { _tag: \"host-call-limit\", logs: boundedLogs() };\n throw new Error(\"code-mode host-call limit exceeded\");\n }\n let argText;\n try {\n argText = JSON.stringify(argument);\n } catch {}\n if (argText === undefined || utf8(argText) > limits.maxHostCallArgumentBytes) {\n fatal = fatal ?? {\n _tag: \"argument-limit\",\n observed: argText === undefined ? 0 : utf8(argText),\n logs: boundedLogs(),\n };\n throw new Error(\"code-mode host-call argument limit exceeded\");\n }\n const outcome = await host.call({\n namespace,\n method,\n argument: JSON.parse(argText),\n });\n if (outcome !== null && typeof outcome === \"object\" && outcome._tag === \"CodeHostCallSuccess\") {\n return outcome.value;\n }\n if (outcome !== null && typeof outcome === \"object\" && outcome._tag === \"CodeHostCallFailure\") {\n throw outcome.error;\n }\n fatal = fatal ?? { _tag: \"protocol\", message: \"host returned an unrecognized outcome\" };\n throw new Error(\"code-mode host protocol violation\");\n };\n for (const namespace of config.namespaces) {\n const methods = {};\n for (const method of namespace.methods) {\n methods[method] = makeMethod(namespace.name, method);\n }\n globalThis[namespace.name] = methods;\n }\n\n // program.js is imported statically at the top of this module, so a\n // syntactically invalid program fails the whole harness at load (mapped\n // to a source error by the host). Using a static import keeps this module\n // free of dynamic-import expressions, which single-script Miniflare hosts\n // reject. The isolation boundary does NOT depend on the ordering of this\n // import versus the console/namespace shims installed below: the loaded\n // Worker has globalOutbound: null and no bindings, secrets, or env from\n // the Worker Loader config BEFORE any module in the graph evaluates, so\n // module-level program code has no ambient authority regardless. The\n // shims below are usability wrappers (bounded console, namespace globals),\n // and the accepted program is a single async-function expression whose\n // body runs only when invoked here — after the shims exist.\n const program = programDefault;\n if (typeof program !== \"function\") {\n return { _tag: \"source-not-a-function\", actual: typeof program };\n }\n try {\n const value = await program();\n if (fatal !== undefined) return fatal;\n let text;\n try {\n text = JSON.stringify(value);\n } catch {}\n if (text === undefined) {\n return {\n _tag: \"program-failed\",\n reason: \"non-json-result\",\n thrown: null,\n message: \"The program must return a JSON value\",\n logs: boundedLogs(),\n };\n }\n const resultBytes = utf8(text);\n if (resultBytes > limits.maxResultBytes) {\n return { _tag: \"result-limit\", observed: resultBytes, logs: boundedLogs() };\n }\n return {\n _tag: \"completed\",\n value: JSON.parse(text),\n logs: boundedLogs(),\n hostCalls,\n logBytes,\n resultBytes,\n };\n } catch (cause) {\n if (fatal !== undefined) return fatal;\n return {\n _tag: \"program-failed\",\n reason: cause instanceof Error ? \"threw\" : \"rejected\",\n thrown: safeJson(cause),\n message: safeText(cause),\n logs: boundedLogs(),\n };\n }\n }\n}\n`;\n\nconst BoundedLogs = Schema.Array(Schema.String.check(Schema.isMaxLength(16 * 1024))).check(\n Schema.isMaxLength(4_096),\n);\n\nconst HarnessCompleted = Schema.TaggedStruct(\"completed\", {\n value: Schema.Json,\n logs: BoundedLogs,\n hostCalls: Schema.Natural,\n logBytes: Schema.Natural,\n resultBytes: Schema.Natural,\n});\nconst HarnessSourceInvalid = Schema.TaggedStruct(\"source-invalid\", {\n message: Schema.String,\n});\nconst HarnessNotAFunction = Schema.TaggedStruct(\"source-not-a-function\", {\n actual: Schema.String,\n});\nconst HarnessProgramFailed = Schema.TaggedStruct(\"program-failed\", {\n reason: Schema.Literals([\"threw\", \"rejected\", \"non-json-result\"]),\n thrown: Schema.Json,\n message: Schema.String,\n logs: BoundedLogs,\n});\nconst HarnessLogLimit = Schema.TaggedStruct(\"log-limit\", {\n observed: Schema.Natural,\n logs: BoundedLogs,\n});\nconst HarnessArgumentLimit = Schema.TaggedStruct(\"argument-limit\", {\n observed: Schema.Natural,\n logs: BoundedLogs,\n});\nconst HarnessResultLimit = Schema.TaggedStruct(\"result-limit\", {\n observed: Schema.Natural,\n logs: BoundedLogs,\n});\nconst HarnessHostCallLimit = Schema.TaggedStruct(\"host-call-limit\", {\n logs: BoundedLogs,\n});\nconst HarnessProtocol = Schema.TaggedStruct(\"protocol\", {\n message: Schema.String,\n});\nconst HarnessOutcome = Schema.Union([\n HarnessCompleted,\n HarnessSourceInvalid,\n HarnessNotAFunction,\n HarnessProgramFailed,\n HarnessLogLimit,\n HarnessArgumentLimit,\n HarnessResultLimit,\n HarnessHostCallLimit,\n HarnessProtocol,\n]);\n\nconst HarnessPassConfig = Schema.Struct({\n namespaces: Schema.Array(\n Schema.Struct({\n name: Schema.NonEmptyString,\n methods: Schema.Array(Schema.NonEmptyString).check(Schema.isMaxLength(64)),\n }),\n ).check(Schema.isMaxLength(32)),\n limits: Schema.Struct({\n maxLogBytes: Schema.Natural,\n maxResultBytes: Schema.Natural,\n maxHostCalls: Schema.Natural,\n maxHostCallArgumentBytes: Schema.Natural,\n }),\n});\n\nconst encodeHarnessPassConfig = Schema.encodeSync(HarnessPassConfig);\nconst encodeJsonPayload = Schema.encodeSync(Schema.fromJsonString(Schema.Json));\nconst decodeJsonPayload = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Json));\n\nconst decodeHarnessOutcome = (value: unknown) => {\n try {\n return Schema.decodeUnknownOption(HarnessOutcome)(value);\n } catch {\n return Option.none<typeof HarnessOutcome.Type>();\n }\n};\n\nconst decodeHostCall = (value: unknown) => {\n try {\n return Schema.decodeUnknownOption(CodeHostCall)(value);\n } catch {\n return Option.none<CodeHostCall>();\n }\n};\n\nconst decodeHostCallResult = (value: unknown) => {\n try {\n return Schema.decodeUnknownOption(CodeHostCallResult)(value);\n } catch {\n return Option.none<CodeHostCallResult>();\n }\n};\n\n/** Dispose a Cloudflare RPC handle when the runtime supplies its untyped disposal hook. @internal */\nexport const disposeRpcHandle = (handle: unknown): Effect.Effect<void> =>\n Effect.try({\n try: () => {\n if ((typeof handle !== \"object\" && typeof handle !== \"function\") || handle === null) return;\n if (!(Symbol.dispose in handle)) return;\n const dispose = Reflect.get(handle, Symbol.dispose);\n if (typeof dispose === \"function\") {\n Reflect.apply(dispose, handle, []);\n }\n },\n catch: (cause) =>\n safeCauseDiagnostic(cause, \"The Cloudflare RPC disposal hook failed without a diagnostic\"),\n }).pipe(\n Effect.catch((diagnostic) =>\n Effect.logWarning(`Cloudflare RPC handle disposal failed: ${diagnostic}`).pipe(\n Effect.ignoreCause,\n ),\n ),\n );\n\n/**\n * Project a host outcome to the plain JSON envelope the harness reads. A\n * `CodeExecutionHost` may return either real `CodeHostCallResult` instances\n * (the substitute and conformance kit) or plain-object equivalents (the Code\n * Mode capability's broker route), so this reads the shared fields rather than\n * `Schema.encodeSync`, which would reject a plain object.\n */\ninterface EncodedHostResultPayload {\n readonly encodedPayload: string;\n readonly resultBytes: number;\n}\n\nconst encodeHostResultPayload = (\n outcome: CodeHostCallResult,\n): EncodedHostResultPayload | undefined => {\n try {\n const payload = outcome._tag === \"CodeHostCallSuccess\" ? outcome.value : outcome.error;\n const encodedPayload = encodeJsonPayload(payload);\n return {\n encodedPayload,\n resultBytes: utf8ByteLength(encodedPayload),\n };\n } catch {\n return undefined;\n }\n};\n\nconst utf8ByteLength = (value: string): number => {\n let total = 0;\n for (const character of value) {\n const codePoint = character.codePointAt(0) ?? 0;\n total += codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4;\n }\n return total;\n};\n\ninterface QueuedHostCall {\n readonly call: CodeHostCall;\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n}\n\ntype HostWork =\n | { readonly _tag: \"call\"; readonly queued: QueuedHostCall }\n | { readonly _tag: \"limit\" };\n\ntype HostDispatchError =\n | CodeExecutionTimeoutError\n | CodeOutputLimitError\n | CodeExecutionProtocolError\n | CodeHostCallLimitError;\n\n/** Reserved global names the harness owns inside the dynamic worker. */\nconst reservedHarnessGlobals = new Set([\"console\"]);\n\nexport interface DynamicWorkerCodeExecutorOptions {\n /** The `worker_loader` binding. */\n readonly loader: WorkerLoader;\n /** Compatibility date for dynamic workers; defaults to `2025-05-01`. */\n readonly compatibilityDate?: string | undefined;\n}\n\nconst makeExecute = (\n options: DynamicWorkerCodeExecutorOptions,\n clock: Clock.Clock,\n): CodeExecutorExecute =>\n Effect.fn(\"DynamicWorkerCodeExecutor.execute\")(function* (request: CodeExecutionRequest) {\n if (request.network._tag !== \"NetworkDisabled\") {\n return yield* CodeExecutorUnsupportedError.make({\n implementation: dynamicWorkerImplementation,\n feature: \"network\",\n message:\n \"The Dynamic Worker executor denies all egress with globalOutbound: null; an allowlist is not supported in the first slice\",\n });\n }\n const sourceBytes = utf8ByteLength(request.source);\n if (sourceBytes > request.limits.maxSourceBytes) {\n return yield* CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"oversized\",\n message: `Source is ${sourceBytes} bytes; the request allows ${request.limits.maxSourceBytes}`,\n });\n }\n for (const namespace of request.namespaces) {\n if (reservedHarnessGlobals.has(namespace.name)) {\n return yield* CodeExecutorUnsupportedError.make({\n implementation: dynamicWorkerImplementation,\n feature: \"namespaces\",\n message: `Namespace ${namespace.name} collides with a harness binding`,\n });\n }\n }\n const host = yield* CodeExecutionHost;\n\n // This synchronous clock access is confined to callbacks that must compute a timeout\n // immediately. The Clock service remains the authority, so tests and hosts can replace it.\n const startedAt = clock.monotonicTimeNanosUnsafe();\n const passDeadline = startedAt + Duration.toNanosUnsafe(request.limits.maxWallTime);\n const remainingPassWallTime = (): Duration.Duration => {\n const now = clock.monotonicTimeNanosUnsafe();\n return Duration.nanos(passDeadline > now ? passDeadline - now : 0n);\n };\n let issuedHostCalls = 0;\n let passOpen = true;\n const queuedHostCalls: Array<QueuedHostCall> = [];\n let passFailure: HostDispatchError | undefined;\n const failPass = (error: HostDispatchError): void => {\n if (passFailure === undefined) passFailure = error;\n };\n const rejectQueuedHostCalls = (reason: Error): void => {\n for (const queued of queuedHostCalls.splice(0)) {\n queued.reject(reason);\n }\n };\n const queue = yield* Queue.unbounded<HostWork>();\n\n const deliverHostOutcome = (\n queued: QueuedHostCall,\n outcome: CodeHostCallResult,\n ): Effect.Effect<void, CodeExecutionProtocolError | CodeOutputLimitError> =>\n Effect.gen(function* () {\n const decoded = decodeHostCallResult(outcome);\n if (Option.isNone(decoded)) {\n const error = CodeExecutionProtocolError.make({\n implementation: dynamicWorkerImplementation,\n message: \"The execution host returned a value outside the CodeHostCallResult schema\",\n });\n failPass(error);\n return yield* error;\n }\n const encoded = encodeHostResultPayload(decoded.value);\n if (encoded === undefined || encoded.resultBytes > request.limits.maxHostCallResultBytes) {\n const error = CodeOutputLimitError.make({\n implementation: dynamicWorkerImplementation,\n surface: \"host-call-result\",\n limit: request.limits.maxHostCallResultBytes,\n observed: encoded?.resultBytes ?? 0,\n logs: [],\n });\n failPass(error);\n return yield* error;\n }\n const normalizedPayload = decodeJsonPayload(encoded.encodedPayload);\n if (Option.isNone(normalizedPayload)) {\n const error = CodeExecutionProtocolError.make({\n implementation: dynamicWorkerImplementation,\n message: \"The execution host returned a result that could not cross the JSON boundary\",\n });\n failPass(error);\n return yield* error;\n }\n queued.resolve(\n decoded.value._tag === \"CodeHostCallSuccess\"\n ? { _tag: \"CodeHostCallSuccess\", value: normalizedPayload.value }\n : { _tag: \"CodeHostCallFailure\", error: normalizedPayload.value },\n );\n });\n\n // Workers RPC into the loader isolate cannot settle on the fiber blocked\n // in `entrypoint.run()`. A Scope-owned sibling fiber keeps that\n // independence while inheriting the pass Context and dying with the Scope.\n const serveHostCalls = Effect.gen(function* () {\n while (true) {\n const work = yield* Queue.take(queue);\n if (work._tag === \"limit\") {\n const error = CodeHostCallLimitError.make({\n implementation: dynamicWorkerImplementation,\n limit: request.limits.maxHostCalls,\n logs: [],\n });\n failPass(error);\n return yield* error;\n }\n const queued = work.queued;\n yield* host.call(queued.call).pipe(\n Effect.timeoutOrElse({\n duration: remainingPassWallTime(),\n orElse: () => {\n const error = CodeExecutionTimeoutError.make({\n implementation: dynamicWorkerImplementation,\n kind: \"wall-clock\",\n maxWallTime: request.limits.maxWallTime,\n logs: [],\n });\n failPass(error);\n return error;\n },\n }),\n Effect.flatMap((outcome) => deliverHostOutcome(queued, outcome)),\n Effect.tapError(() =>\n Effect.sync(() => queued.reject(new Error(\"Code Mode host call failed\"))),\n ),\n Effect.onInterrupt(() =>\n Effect.sync(() => queued.reject(new Error(\"Code Mode pass is closing\"))),\n ),\n );\n }\n });\n const server = yield* serveHostCalls.pipe(Effect.forkScoped);\n\n const dispatch = (hostCall: unknown): Promise<unknown> => {\n if (!passOpen) {\n return Promise.reject(new Error(\"Code Mode pass is closing\"));\n }\n issuedHostCalls += 1;\n if (issuedHostCalls > request.limits.maxHostCalls) {\n const error = CodeHostCallLimitError.make({\n implementation: dynamicWorkerImplementation,\n limit: request.limits.maxHostCalls,\n logs: [],\n });\n failPass(error);\n Queue.offerUnsafe(queue, { _tag: \"limit\" });\n return Promise.reject(new Error(\"host-call limit exceeded\"));\n }\n const decoded = decodeHostCall(hostCall);\n if (Option.isNone(decoded)) {\n return Promise.reject(new TypeError(\"host calls must match the CodeHostCall schema\"));\n }\n return new Promise((resolve, reject) => {\n const queued = { call: decoded.value, resolve, reject };\n queuedHostCalls.push(queued);\n Queue.offerUnsafe(queue, { _tag: \"call\", queued });\n });\n };\n\n const closeAdmission = Effect.sync(() => {\n passOpen = false;\n rejectQueuedHostCalls(new Error(\"Code Mode pass is closing\"));\n });\n yield* Effect.addFinalizer(() => closeAdmission.pipe(Effect.andThen(Fiber.interrupt(server))));\n\n // No `allowExperimental`: the runtime only accepts it when the CALLING\n // worker carries the `experimental` compatibility flag, which deployed\n // consumers cannot set — the option would reject every pass in\n // production. The harness needs no experimental runtime features.\n const workerCode: WorkerLoaderWorkerCode = {\n compatibilityDate: options.compatibilityDate ?? \"2025-05-01\",\n mainModule: \"harness.js\",\n modules: {\n \"harness.js\": HARNESS_MODULE,\n \"program.js\": `export default (\\n${request.source}\\n);`,\n },\n env: {\n CODE_MODE_PASS: encodeHarnessPassConfig({\n namespaces: request.namespaces.map((namespace) => ({\n name: namespace.name,\n methods: namespace.methods,\n })),\n limits: {\n maxLogBytes: request.limits.maxLogBytes,\n maxResultBytes: request.limits.maxResultBytes,\n maxHostCalls: request.limits.maxHostCalls,\n maxHostCallArgumentBytes: request.limits.maxHostCallArgumentBytes,\n },\n }),\n },\n globalOutbound: null,\n ...(request.limits.cpuMillis === undefined\n ? {}\n : {\n limits: {\n cpuMs: request.limits.cpuMillis,\n subRequests: request.limits.maxHostCalls + 8,\n },\n }),\n };\n\n const worker = yield* Effect.acquireRelease(\n Effect.try({\n try: () => options.loader.load(workerCode),\n catch: (cause) => {\n const text = safeCauseMessage(cause, \"The Worker Loader failed without a diagnostic\");\n // Blame the program's source ONLY on a genuine compile diagnostic;\n // any other load rejection is an infrastructure start failure, not\n // the model's fault (see classifyWorkerFailure for the same split).\n if (/syntaxerror|failed to (compile|parse)/i.test(text)) {\n return CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"invalid\",\n message: text.slice(0, 8_000),\n });\n }\n return CodeExecutorStartError.make({\n implementation: dynamicWorkerImplementation,\n message: `The Worker Loader rejected the pass: ${text}`.slice(0, 8_000),\n cause,\n });\n },\n }),\n disposeRpcHandle,\n );\n\n const entrypoint = yield* Effect.acquireRelease(\n Effect.try({\n try: () => worker.getEntrypoint<CodeModeHarnessEntrypoint>(),\n catch: (cause) => classifyWorkerFailure(cause, request.limits.maxWallTime),\n }),\n disposeRpcHandle,\n );\n\n const rpc = Effect.tryPromise({\n try: () => entrypoint.run(new CodeModePassHostTarget(dispatch)),\n catch: (cause) => classifyWorkerFailure(cause, request.limits.maxWallTime),\n });\n\n const exit = yield* Effect.raceFirst(\n rpc.pipe(\n Effect.timeoutOrElse({\n duration: remainingPassWallTime(),\n orElse: () =>\n CodeExecutionTimeoutError.make({\n implementation: dynamicWorkerImplementation,\n kind: \"wall-clock\",\n maxWallTime: request.limits.maxWallTime,\n logs: [],\n }),\n }),\n ),\n Fiber.join(server),\n ).pipe(Effect.exit);\n yield* closeAdmission;\n yield* Fiber.interrupt(server);\n if (passFailure !== undefined) {\n return yield* passFailure;\n }\n if (Exit.isFailure(exit)) {\n return yield* Effect.failCause(exit.cause);\n }\n const raw = exit.value;\n const finishedAt = clock.monotonicTimeNanosUnsafe();\n\n const outcome = decodeHarnessOutcome(raw);\n if (Option.isNone(outcome)) {\n return yield* CodeExecutionProtocolError.make({\n implementation: dynamicWorkerImplementation,\n message: \"The dynamic worker returned a value outside the harness envelope schema\",\n });\n }\n switch (outcome.value._tag) {\n case \"completed\": {\n return CodeExecutionResult.make({\n implementation: dynamicWorkerImplementation,\n value: outcome.value.value,\n logs: outcome.value.logs,\n resourceUse: CodeExecutionResourceUse.make({\n wallTime: Duration.nanos(finishedAt > startedAt ? finishedAt - startedAt : 0n),\n hostCalls: outcome.value.hostCalls,\n logBytes: outcome.value.logBytes,\n resultBytes: outcome.value.resultBytes,\n }),\n });\n }\n case \"source-invalid\": {\n return yield* CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"invalid\",\n message: outcome.value.message.slice(0, 8_000),\n });\n }\n case \"source-not-a-function\": {\n return yield* CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"not-a-function\",\n message: `The source expression evaluated to ${outcome.value.actual}; it must evaluate to one async function`,\n });\n }\n case \"program-failed\": {\n return yield* CodeProgramFailedError.make({\n implementation: dynamicWorkerImplementation,\n reason: outcome.value.reason,\n thrown: outcome.value.thrown,\n message: outcome.value.message.slice(0, 8_000),\n logs: outcome.value.logs,\n });\n }\n case \"log-limit\": {\n return yield* CodeOutputLimitError.make({\n implementation: dynamicWorkerImplementation,\n surface: \"logs\",\n limit: request.limits.maxLogBytes,\n observed: outcome.value.observed,\n logs: outcome.value.logs,\n });\n }\n case \"argument-limit\": {\n return yield* CodeOutputLimitError.make({\n implementation: dynamicWorkerImplementation,\n surface: \"host-call-argument\",\n limit: request.limits.maxHostCallArgumentBytes,\n observed: outcome.value.observed,\n logs: outcome.value.logs,\n });\n }\n case \"result-limit\": {\n return yield* CodeOutputLimitError.make({\n implementation: dynamicWorkerImplementation,\n surface: \"result\",\n limit: request.limits.maxResultBytes,\n observed: outcome.value.observed,\n logs: outcome.value.logs,\n });\n }\n case \"host-call-limit\": {\n return yield* CodeHostCallLimitError.make({\n implementation: dynamicWorkerImplementation,\n limit: request.limits.maxHostCalls,\n logs: outcome.value.logs,\n });\n }\n case \"protocol\": {\n return yield* CodeExecutionProtocolError.make({\n implementation: dynamicWorkerImplementation,\n message: outcome.value.message.slice(0, 8_000),\n });\n }\n }\n });\n\n/**\n * Expected worker-level failures map into the typed union with bounded\n * diagnostics; anything unrecognized stays a start/termination error rather\n * than a fabricated program result.\n */\nconst classifyWorkerFailure = (\n cause: unknown,\n maxWallTime: Duration.Duration,\n):\n | CodeExecutionTimeoutError\n | CodeExecutorTerminatedError\n | CodeExecutorStartError\n | CodeSourceError => {\n const text = safeCauseDiagnostic(cause, \"[unserializable worker failure]\");\n // `WorkerLoader.load()` is lazy, so a module-compile error in the generated\n // program surfaces here at first use. Blame the program's source ONLY on a\n // genuine compile diagnostic (a `SyntaxError` or an explicit compile\n // failure) — the fixed harness is valid, so the fault is in program.js. A\n // bare \"failed to start Worker\" without a compile diagnostic is an\n // infrastructure start failure, not the model's fault, so it must NOT be\n // misclassified as a source error.\n if (/syntaxerror|failed to (compile|parse)/i.test(text)) {\n return CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"invalid\",\n message: text.slice(0, 8_000),\n });\n }\n if (/cpu/i.test(text)) {\n return CodeExecutionTimeoutError.make({\n implementation: dynamicWorkerImplementation,\n kind: \"cpu\",\n maxWallTime,\n logs: [],\n });\n }\n if (/failed to start worker/i.test(text)) {\n return CodeExecutorStartError.make({\n implementation: dynamicWorkerImplementation,\n message: text.slice(0, 8_000),\n cause,\n });\n }\n return CodeExecutorTerminatedError.make({\n implementation: dynamicWorkerImplementation,\n message: text.slice(0, 8_000),\n });\n};\n\n/** Layer building the Dynamic Worker `CodeExecutor` from resolved bindings. */\nexport const dynamicWorkerCodeExecutorLayer = (\n options: DynamicWorkerCodeExecutorOptions,\n): Layer.Layer<CodeExecutor> =>\n Layer.effect(\n CodeExecutor,\n Effect.gen(function* () {\n const clock = yield* Clock.Clock;\n return CodeExecutor.of({ execute: makeExecute(options, clock) });\n }),\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAYA,IAAa,yBAAb,cAA4C,OAAO,YAAoC,CAAC,CACtF,0BACA;CACE,SAAS,OAAO;CAChB,SAAS,OAAO;AAClB,CACF,CAAC,CAAC,CAAC;;;;;;AAwC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