@effect-agent/platform-cloudflare 0.1.0-beta.36 → 0.1.0-beta.37

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scheduling-B-OFqoS9.mjs","names":["ScheduleScopeSchema","ScheduleSnapshotPageSchema","EffectCfDurableObjectState","EffectCfDurableObject"],"sources":["../src/bindings.ts","../src/config.ts","../src/boundary.ts","../src/alarm.ts","../src/client.ts","../src/scheduling.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 { 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 { AgentId } from \"@effect-agent/core\";\nimport {\n DefinitionDigests,\n PersistedJson,\n type DurableSubmitAgent,\n ScheduleAuthorizationError,\n type ScheduleAuthorizer,\n ScheduleCapacityError,\n ScheduleConflict,\n ScheduleDestination,\n ScheduleFailpointError,\n ScheduleId,\n type SchedulingLimits,\n ScheduleNotFound,\n ScheduleOwner,\n type ScheduleScope,\n ScheduleScope as ScheduleScopeSchema,\n ScheduleSnapshot,\n ScheduleSnapshotPage as ScheduleSnapshotPageSchema,\n ScheduleStorageError,\n ScheduleTimingRequest,\n ScheduleValidationError,\n ScheduledInputAdmission,\n ScheduledInputRetryable,\n type ScheduledEnvelope,\n Scheduling,\n ScheduleDriver,\n type ScheduleManagementFailure,\n defaultSchedulingLimits,\n scheduleOwnerKey,\n ScheduleWakeNoop,\n} from \"@effect-agent/session\";\nimport {\n DoScheduleAlarmControl,\n DoScheduleTransaction,\n scheduleStoreLayer,\n} from \"@effect-agent/storage-cloudflare\";\nimport { BrowserCrypto } from \"@effect/platform-browser\";\nimport { SqliteClient } from \"@effect/sql-sqlite-do\";\nimport { Clock, Context, DateTime, Effect, Layer, Schema } from \"effect\";\nimport {\n DurableObject as EffectCfDurableObject,\n DurableObjectAlarm,\n DurableObjectState as EffectCfDurableObjectState,\n type WorkerEnvironment,\n} from \"effect-cf\";\n\nimport type { ConversationObjectNamespace } from \"./bindings.ts\";\nimport { CloudflareConversationClient, type ConversationClientError } from \"./client.ts\";\n\nconst SCHEDULE_ALARM_TAG = \"effect-agent/ScheduleOwnerWake\";\nconst SCHEDULE_ALARM_ID = \"driver\";\n\nconst ScheduleAlarmPayload = Schema.Struct({\n schemaVersion: Schema.Literal(1),\n generation: Schema.Int.check(Schema.isGreaterThan(0)),\n});\n\nexport class ScheduleAlarmProtocolError extends Schema.TaggedError<ScheduleAlarmProtocolError>()(\n \"ScheduleAlarmProtocolError\",\n { message: Schema.String },\n) {}\n\nconst boundedProtocolMessage = (message: string): string =>\n message.length <= 4_096 ? message : `${message.slice(0, 4_093)}...`;\n\nexport class ScheduleOwnerProtocolError extends Schema.TaggedError<ScheduleOwnerProtocolError>()(\n \"ScheduleOwnerProtocolError\",\n { message: Schema.String.check(Schema.isMaxLength(4_096)) },\n) {}\n\nconst ScheduleMutationRequestFields = {\n schemaVersion: Schema.Literal(1),\n agentId: AgentId,\n input: PersistedJson,\n scope: ScheduleScopeSchema,\n scheduleId: ScheduleId,\n timing: ScheduleTimingRequest,\n destination: ScheduleDestination,\n deliveryPrincipal: ScheduleScopeSchema.fields.principal,\n definitions: DefinitionDigests,\n};\n\nconst ScheduleCreateRequest = Schema.TaggedStruct(\"Create\", ScheduleMutationRequestFields);\n\nconst ScheduleUpdateRequest = Schema.TaggedStruct(\"Update\", {\n ...ScheduleMutationRequestFields,\n expectedRevision: Schema.Int.check(Schema.isGreaterThan(0)),\n});\n\nconst ScheduleGetRequest = Schema.TaggedStruct(\"Get\", {\n schemaVersion: Schema.Literal(1),\n scope: ScheduleScopeSchema,\n scheduleId: ScheduleId,\n});\n\nconst ScheduleListRequest = Schema.TaggedStruct(\"List\", {\n schemaVersion: Schema.Literal(1),\n scope: ScheduleScopeSchema,\n after: Schema.optionalKey(ScheduleId),\n limit: Schema.optionalKey(\n Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(100)),\n ),\n});\n\nconst ScheduleControlRequest = Schema.TaggedStruct(\"Control\", {\n schemaVersion: Schema.Literal(1),\n operation: Schema.Literals([\"pause\", \"resume\", \"cancel\"]),\n scope: ScheduleScopeSchema,\n scheduleId: ScheduleId,\n expectedRevision: Schema.Int.check(Schema.isGreaterThan(0)),\n});\n\nconst ScheduleOwnerRequest = Schema.Union([\n ScheduleCreateRequest,\n ScheduleUpdateRequest,\n ScheduleGetRequest,\n ScheduleListRequest,\n ScheduleControlRequest,\n]);\ntype ScheduleOwnerRequest = typeof ScheduleOwnerRequest.Type;\n\nconst ScheduleOwnerFailure = Schema.Union([\n ScheduleValidationError,\n ScheduleAuthorizationError,\n ScheduleConflict,\n ScheduleNotFound,\n ScheduleCapacityError,\n ScheduleStorageError,\n ScheduleFailpointError,\n ScheduleOwnerProtocolError,\n]);\ntype ScheduleOwnerFailure = typeof ScheduleOwnerFailure.Type;\n\nconst ScheduleOwnerResponse = Schema.Union([\n Schema.TaggedStruct(\"Snapshot\", { value: ScheduleSnapshot }),\n Schema.TaggedStruct(\"Page\", { value: ScheduleSnapshotPageSchema }),\n Schema.TaggedStruct(\"Failed\", { failure: ScheduleOwnerFailure }),\n]);\ntype ScheduleOwnerResponse = typeof ScheduleOwnerResponse.Type;\n\nconst decodeScheduleOwnerRequest = Schema.decodeUnknownEffect(ScheduleOwnerRequest);\nconst encodeScheduleOwnerRequest = Schema.encodeEffect(ScheduleOwnerRequest);\nconst decodeScheduleOwnerResponse = Schema.decodeUnknownEffect(ScheduleOwnerResponse);\nconst encodeScheduleOwnerResponse = Schema.encodeEffect(ScheduleOwnerResponse);\n\nconst scheduleProtocolFailure = (message: string): ScheduleOwnerResponse => ({\n _tag: \"Failed\",\n failure: ScheduleOwnerProtocolError.make({ message: boundedProtocolMessage(message) }),\n});\n\nexport interface ScheduleOwnerObjectRpc extends Rpc.DurableObjectBranded {\n schedule(encoded: unknown): Promise<unknown>;\n}\n\nexport class ScheduleOwnerNamespace extends Context.Service<\n ScheduleOwnerNamespace,\n { readonly namespace: DurableObjectNamespace<ScheduleOwnerObjectRpc> }\n>()(\"@effect-agent/platform-cloudflare/ScheduleOwnerNamespace\") {}\n\nconst passthroughAgent = (agentId: AgentId): DurableSubmitAgent<typeof PersistedJson> => ({\n definition: { id: agentId, input: PersistedJson },\n});\n\nconst requestOwner = (request: ScheduleOwnerRequest): ScheduleOwner => request.scope.owner;\n\n/** Provides the same authorized management service as NodeScheduling.layer. */\nexport class CloudflareSchedulingClient {\n static readonly layer: Layer.Layer<Scheduling, never, ScheduleOwnerNamespace> = Layer.effect(\n Scheduling,\n Effect.gen(function* () {\n const { namespace } = yield* ScheduleOwnerNamespace;\n\n const call = Effect.fn(\"CloudflareSchedulingClient.call\")(function* (\n owner: ScheduleOwner,\n request: ScheduleOwnerRequest,\n ): Effect.fn.Return<ScheduleOwnerResponse, ScheduleManagementFailure> {\n const encoded = yield* encodeScheduleOwnerRequest(request).pipe(\n Effect.mapError(() =>\n ScheduleStorageError.make({ operation: \"Schedule Owner protocol\", reason: \"corrupt\" }),\n ),\n );\n const raw = yield* Effect.tryPromise({\n try: () => namespace.get(namespace.idFromName(scheduleOwnerKey(owner))).schedule(encoded),\n catch: () =>\n ScheduleStorageError.make({\n operation: \"call Schedule Owner\",\n reason: \"unavailable\",\n }),\n });\n const response = yield* decodeScheduleOwnerResponse(raw).pipe(\n Effect.mapError(() =>\n ScheduleStorageError.make({ operation: \"Schedule Owner protocol\", reason: \"corrupt\" }),\n ),\n );\n if (response._tag !== \"Failed\") return response;\n return yield* response.failure._tag === \"ScheduleOwnerProtocolError\"\n ? ScheduleStorageError.make({ operation: \"Schedule Owner protocol\", reason: \"corrupt\" })\n : response.failure;\n });\n\n const encodeInput = Effect.fn(\"CloudflareSchedulingClient.encodeInput\")(function* <\n InputSchema extends Schema.Top,\n >(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n ): Effect.fn.Return<PersistedJson, ScheduleValidationError, InputSchema[\"EncodingServices\"]> {\n const encoded = yield* Schema.encodeEffect(agent.definition.input)(input).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({\n message: \"Unable to encode Agent input\",\n }),\n ),\n );\n return yield* Schema.decodeUnknownEffect(PersistedJson)(encoded).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({\n message: \"Agent input does not satisfy the canonical persistence bounds\",\n }),\n ),\n );\n });\n\n const create: Scheduling[\"Service\"][\"create\"] = (agent, input, options) =>\n Effect.gen(function* () {\n const payload = yield* encodeInput(agent, input);\n const response = yield* call(options.scope.owner, {\n _tag: \"Create\",\n schemaVersion: 1,\n agentId: agent.definition.id,\n input: payload,\n ...options,\n });\n return response._tag === \"Snapshot\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n const update: Scheduling[\"Service\"][\"update\"] = (agent, input, options) =>\n Effect.gen(function* () {\n const payload = yield* encodeInput(agent, input);\n const response = yield* call(options.scope.owner, {\n _tag: \"Update\",\n schemaVersion: 1,\n agentId: agent.definition.id,\n input: payload,\n ...options,\n });\n return response._tag === \"Snapshot\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n const get: Scheduling[\"Service\"][\"get\"] = (scope, scheduleId) =>\n Effect.gen(function* () {\n const response = yield* call(scope.owner, {\n _tag: \"Get\",\n schemaVersion: 1,\n scope,\n scheduleId,\n });\n return response._tag === \"Snapshot\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n const list: Scheduling[\"Service\"][\"list\"] = (scope, options = {}) =>\n Effect.gen(function* () {\n const response = yield* call(scope.owner, {\n _tag: \"List\",\n schemaVersion: 1,\n scope,\n ...(options.after === undefined ? {} : { after: options.after }),\n ...(options.limit === undefined ? {} : { limit: options.limit }),\n });\n return response._tag === \"Page\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n const control = (\n operation: \"pause\" | \"resume\" | \"cancel\",\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n ) =>\n Effect.gen(function* () {\n const response = yield* call(scope.owner, {\n _tag: \"Control\",\n schemaVersion: 1,\n operation,\n scope,\n scheduleId,\n expectedRevision,\n });\n return response._tag === \"Snapshot\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n return Scheduling.of({\n create,\n update,\n get,\n list,\n pause: (scope, id, revision) => control(\"pause\", scope, id, revision),\n resume: (scope, id, revision) => control(\"resume\", scope, id, revision),\n cancel: (scope, id, revision) => control(\"cancel\", scope, id, revision),\n });\n }),\n );\n}\n\nexport class ScheduleOwnerIdentity extends Context.Service<\n ScheduleOwnerIdentity,\n { readonly owner: ScheduleOwner }\n>()(\"@effect-agent/platform-cloudflare/ScheduleOwnerIdentity\") {}\n\nconst decodeOwnerName = Effect.fn(\"decodeScheduleOwnerName\")(function* (\n name: string | null | undefined,\n): Effect.fn.Return<ScheduleOwner, ScheduleOwnerProtocolError> {\n if (name === null || name === undefined) {\n return yield* ScheduleOwnerProtocolError.make({\n message: \"Schedule Owner objects require an idFromName identity\",\n });\n }\n const tuple = yield* Schema.decodeUnknownEffect(\n Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.String])),\n )(name).pipe(\n Effect.mapError(() =>\n ScheduleOwnerProtocolError.make({ message: \"Schedule Owner object name is malformed\" }),\n ),\n );\n return yield* Schema.decodeUnknownEffect(ScheduleOwner)({\n tenantId: tuple[0],\n ownerId: tuple[1],\n }).pipe(\n Effect.mapError(() =>\n ScheduleOwnerProtocolError.make({ message: \"Schedule Owner object identity is invalid\" }),\n ),\n );\n});\n\nconst alarmStorageError = (operation: string) => (error: { readonly _tag: string }) =>\n ScheduleStorageError.make({\n operation,\n reason: error._tag === \"StorageOperationError\" ? \"unavailable\" : \"corrupt\",\n });\n\nconst transactionLayer: Layer.Layer<\n DoScheduleTransaction,\n never,\n DurableObjectAlarm.DurableObjectAlarm\n> = Layer.effect(\n DoScheduleTransaction,\n Effect.gen(function* () {\n const alarms = yield* DurableObjectAlarm.DurableObjectAlarm;\n return DoScheduleTransaction.of({\n run: (body) =>\n Effect.gen(function* () {\n const nowMillis = yield* Clock.currentTimeMillis;\n return yield* alarms\n .transaction((transaction) =>\n body((replacement) =>\n replacement.deadlineAtMillis === null\n ? transaction\n .cancelAlarm({ id: SCHEDULE_ALARM_ID, tag: SCHEDULE_ALARM_TAG })\n .pipe(Effect.mapError(alarmStorageError(\"cancel Schedule Owner alarm\")))\n : Effect.fromOption(\n DateTime.make(Math.max(replacement.deadlineAtMillis, nowMillis + 1)),\n ).pipe(\n Effect.mapError(() =>\n ScheduleStorageError.make({\n operation: \"validate Schedule Owner alarm deadline\",\n reason: \"corrupt\",\n }),\n ),\n Effect.flatMap((runAt) =>\n transaction\n .scheduleAlarm({\n id: SCHEDULE_ALARM_ID,\n tag: SCHEDULE_ALARM_TAG,\n runAt,\n payload: {\n schemaVersion: 1,\n generation: replacement.generation,\n },\n })\n .pipe(\n Effect.mapError(alarmStorageError(\"schedule Schedule Owner alarm\")),\n ),\n ),\n ),\n ),\n )\n .pipe(\n Effect.catchTag(\"StorageOperationError\", () =>\n ScheduleStorageError.make({\n operation: \"commit Schedule Owner transaction\",\n reason: \"unavailable\",\n }),\n ),\n );\n }),\n });\n }),\n);\n\nconst admissionLayer: Layer.Layer<ScheduledInputAdmission, never, CloudflareConversationClient> =\n Layer.effect(\n ScheduledInputAdmission,\n Effect.gen(function* () {\n const client = yield* CloudflareConversationClient;\n const submit = (envelope: ScheduledEnvelope) =>\n client\n .submit(passthroughAgent(envelope.agentId), envelope.input, {\n conversationId: envelope.conversationId,\n principal: envelope.deliveryPrincipal,\n idempotencyKey: envelope.admissionKey,\n definitions: envelope.definitions,\n })\n .pipe(\n Effect.catchTags({\n AdmissionConflict: () =>\n ScheduleStorageError.make({ operation: \"scheduled admission\", reason: \"corrupt\" }),\n AdmissionLimitExceeded: () => ScheduledInputRetryable.make({ reason: \"capacity\" }),\n ConversationClientError: (error: ConversationClientError) =>\n ScheduledInputRetryable.make({\n reason: error.overloaded === true ? \"capacity\" : \"transport\",\n }),\n HostProtocolError: () => ScheduledInputRetryable.make({ reason: \"ambiguous\" }),\n LedgerError: () => ScheduledInputRetryable.make({ reason: \"storage\" }),\n ConversationStoreError: () => ScheduledInputRetryable.make({ reason: \"storage\" }),\n DurableAlarmError: () => ScheduledInputRetryable.make({ reason: \"storage\" }),\n AgentInputError: () =>\n ScheduleStorageError.make({ operation: \"scheduled admission\", reason: \"corrupt\" }),\n DigestError: () =>\n ScheduleStorageError.make({ operation: \"scheduled admission\", reason: \"corrupt\" }),\n ConversationNotMaterialized: () =>\n ScheduledInputRetryable.make({ reason: \"storage\" }),\n AppendConflict: () => ScheduledInputRetryable.make({ reason: \"ambiguous\" }),\n FenceRejected: () => ScheduledInputRetryable.make({ reason: \"ambiguous\" }),\n DurableRuntimeFailpointError: () =>\n ScheduledInputRetryable.make({ reason: \"ambiguous\" }),\n }),\n );\n return ScheduledInputAdmission.of({ submit });\n }),\n );\n\ntype ScheduleRuntimeServices =\n | Scheduling\n | ScheduleDriver\n | DoScheduleAlarmControl\n | ScheduleOwnerIdentity\n | DurableObjectAlarm.DurableObjectAlarm;\n\nconst ensureOwner = (\n expected: ScheduleOwner,\n request: ScheduleOwnerRequest,\n): Effect.Effect<void, ScheduleOwnerProtocolError> => {\n const observed = requestOwner(request);\n return observed.tenantId === expected.tenantId && observed.ownerId === expected.ownerId\n ? Effect.void\n : Effect.fail(\n ScheduleOwnerProtocolError.make({\n message: \"The request owner does not match the addressed Schedule Owner object\",\n }),\n );\n};\n\nconst handleScheduleRequest = Effect.fn(\"ScheduleOwner.handleRequest\")(function* (\n encoded: unknown,\n): Effect.fn.Return<unknown, never, Scheduling | ScheduleOwnerIdentity> {\n const decoded = yield* decodeScheduleOwnerRequest(encoded).pipe(Effect.result);\n if (decoded._tag === \"Failure\") {\n return yield* encodeScheduleOwnerResponse(\n scheduleProtocolFailure(\"The Schedule request could not be decoded\"),\n ).pipe(Effect.orDie);\n }\n const request = decoded.success;\n const { owner } = yield* ScheduleOwnerIdentity;\n const scheduling = yield* Scheduling;\n const response = yield* Effect.gen(function* () {\n yield* ensureOwner(owner, request);\n switch (request._tag) {\n case \"Create\": {\n const value = yield* scheduling.create(passthroughAgent(request.agentId), request.input, {\n scope: request.scope,\n scheduleId: request.scheduleId,\n timing: request.timing,\n destination: request.destination,\n deliveryPrincipal: request.deliveryPrincipal,\n definitions: request.definitions,\n });\n return { _tag: \"Snapshot\" as const, value };\n }\n case \"Update\": {\n const value = yield* scheduling.update(passthroughAgent(request.agentId), request.input, {\n scope: request.scope,\n scheduleId: request.scheduleId,\n timing: request.timing,\n destination: request.destination,\n deliveryPrincipal: request.deliveryPrincipal,\n definitions: request.definitions,\n expectedRevision: request.expectedRevision,\n });\n return { _tag: \"Snapshot\" as const, value };\n }\n case \"Get\":\n return {\n _tag: \"Snapshot\" as const,\n value: yield* scheduling.get(request.scope, request.scheduleId),\n };\n case \"List\":\n return {\n _tag: \"Page\" as const,\n value: yield* scheduling.list(request.scope, {\n ...(request.after === undefined ? {} : { after: request.after }),\n ...(request.limit === undefined ? {} : { limit: request.limit }),\n }),\n };\n case \"Control\": {\n const value =\n request.operation === \"pause\"\n ? yield* scheduling.pause(request.scope, request.scheduleId, request.expectedRevision)\n : request.operation === \"resume\"\n ? yield* scheduling.resume(\n request.scope,\n request.scheduleId,\n request.expectedRevision,\n )\n : yield* scheduling.cancel(\n request.scope,\n request.scheduleId,\n request.expectedRevision,\n );\n return { _tag: \"Snapshot\" as const, value };\n }\n }\n }).pipe(\n Effect.map((value): ScheduleOwnerResponse => value),\n Effect.catch((failure) =>\n Schema.is(ScheduleOwnerFailure)(failure)\n ? Effect.succeed({ _tag: \"Failed\" as const, failure })\n : Effect.succeed(\n scheduleProtocolFailure(\"The Schedule operation failed outside its public contract\"),\n ),\n ),\n );\n return yield* encodeScheduleOwnerResponse(response).pipe(Effect.orDie);\n});\n\nconst scheduleAlarmHandler = (limits: SchedulingLimits) =>\n DurableObjectAlarm.processDue(\n (event) =>\n Effect.gen(function* () {\n if (event.tag !== SCHEDULE_ALARM_TAG || event.id !== SCHEDULE_ALARM_ID) {\n return yield* ScheduleAlarmProtocolError.make({\n message: `Unsupported Schedule Owner alarm ${event.tag}/${event.id}`,\n });\n }\n yield* Schema.decodeUnknownEffect(ScheduleAlarmPayload)(event.payload).pipe(\n Effect.mapError(() =>\n ScheduleAlarmProtocolError.make({\n message: \"Unsupported Schedule Owner alarm payload version\",\n }),\n ),\n );\n const scheduling = yield* ScheduleDriver;\n const alarmControl = yield* DoScheduleAlarmControl;\n const { owner } = yield* ScheduleOwnerIdentity;\n const nowMillis = yield* Clock.currentTimeMillis;\n yield* alarmControl.prearm(nowMillis + limits.recoveryPollMillis);\n const pass = yield* scheduling.runDue(owner);\n if (pass.failed > 0) {\n yield* alarmControl.prearm((yield* Clock.currentTimeMillis) + limits.recoveryPollMillis);\n } else {\n yield* alarmControl.reconcile;\n }\n }),\n { mode: \"ordered\" },\n ).pipe(Effect.asVoid);\n\nexport interface ScheduleOwnerObjectInstance extends InstanceType<\n EffectCfDurableObject.DurableObjectClass<Record<never, never>, ScheduleRuntimeServices>\n> {\n schedule(encoded: unknown): Promise<unknown>;\n alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> | void;\n}\n\nexport interface ScheduleOwnerObjectClass {\n new (ctx: DurableObjectState, env: Cloudflare.Env): ScheduleOwnerObjectInstance;\n}\n\n/**\n * The host Layer supplies authorization and routing and is cached for the object incarnation.\n * Cloudflare eviction does not guarantee its finalizers run. Do not acquire resources requiring\n * cleanup in this Layer; acquire them inside scoped `manage` / `prepare` operations instead.\n * Native services belong to effect-cf; the database and alarm runtime remain instance-owned.\n */\nexport const makeScheduleOwnerObjectClass = <E>(\n host: Layer.Layer<\n ScheduleAuthorizer | ConversationObjectNamespace,\n E,\n EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment | ScheduleOwnerIdentity\n >,\n limits: SchedulingLimits = defaultSchedulingLimits,\n): ScheduleOwnerObjectClass => {\n const ownerLayer = Layer.effect(\n ScheduleOwnerIdentity,\n Effect.gen(function* () {\n const state = yield* EffectCfDurableObjectState.DurableObjectState;\n return ScheduleOwnerIdentity.of({ owner: yield* decodeOwnerName(state.raw.id.name) });\n }),\n );\n const sqlLayer = Layer.unwrap(\n Effect.map(EffectCfDurableObjectState.DurableObjectState, (state) =>\n SqliteClient.layer({ storage: state.raw.storage }),\n ),\n );\n const application = Layer.merge(Scheduling.layer(limits), ScheduleDriver.layer(limits)).pipe(\n Layer.provideMerge(\n scheduleStoreLayer.pipe(Layer.provide(transactionLayer), Layer.provide(sqlLayer)),\n ),\n Layer.provide(admissionLayer.pipe(Layer.provide(CloudflareConversationClient.layer))),\n Layer.provide(ScheduleWakeNoop),\n Layer.provide(BrowserCrypto.layer),\n Layer.provideMerge(DurableObjectAlarm.DurableObjectAlarm.layer),\n Layer.provide(host),\n Layer.provideMerge(ownerLayer),\n );\n const runtime: Layer.Layer<\n ScheduleRuntimeServices,\n E | ScheduleStorageError | ScheduleOwnerProtocolError | ScheduleValidationError,\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(Layer.buildWithScope(application, scope));\n }),\n );\n\n const rpc = {\n schedule: (encoded: unknown) => handleScheduleRequest(encoded),\n } satisfies EffectCfDurableObject.DurableObjectRpc<ScheduleRuntimeServices>;\n\n const Base = EffectCfDurableObject.make(runtime, {\n initialize: Effect.void,\n rpc,\n alarms: scheduleAlarmHandler(limits),\n });\n\n class ScheduleOwnerObject extends Base {\n override alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> | void {\n return super.alarm?.(alarmInfo);\n }\n }\n return ScheduleOwnerObject;\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,eA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AAO,EAK3D;EACF,QAAQ,qBAAqB,MAAM;CACrC,CAAC;CAED,MAAM,4BAA4B,KAAK;EACrC,MAAe,WAAuD;GACpE,OAAO,MAAM,QAAQ,SAAS;EAChC;CACF;CACA,OAAO;AACT"}
@@ -0,0 +1,142 @@
1
+ import { Context, Effect, Layer, Schema } from "effect";
2
+ import { ProducerId, ScheduleAuthorizer, ScheduleDriver, ScheduleOwner, Scheduling, SchedulingLimits } from "@effect-agent/session";
3
+ import { DoScheduleAlarmControl } from "@effect-agent/storage-cloudflare";
4
+ import { ConversationId } from "@effect-agent/core";
5
+ import { DurableObject, DurableObjectAlarm, DurableObjectState as DurableObjectState$1, WorkerEnvironment } from "effect-cf";
6
+ //#region src/bindings.d.ts
7
+ declare const CloudflareBindingError_base: Schema.Class<CloudflareBindingError, Schema.TaggedStruct<"CloudflareBindingError", {
8
+ readonly binding: Schema.String;
9
+ readonly message: Schema.String;
10
+ }>, import("effect/Cause").YieldableError>;
11
+ /**
12
+ * Cloudflare platform bindings as Effect services (DEPLOY-010: "Cloudflare platform bindings
13
+ * are supplied as Effect services/Layers"). Application code never reads `env` or touches a
14
+ * `DurableObjectState` directly — the Conversation Object class constructs these Layers once
15
+ * per incarnation and everything downstream consumes the services.
16
+ */
17
+ /** A Cloudflare platform binding was missing or carried the wrong shape (DEPLOY-003/010). */
18
+ declare class CloudflareBindingError extends CloudflareBindingError_base {}
19
+ /**
20
+ * The RPC surface one Conversation Durable Object exposes to Workers and to sibling
21
+ * Conversation Objects. `makeConversationObjectClass` implements it; the Worker-side client
22
+ * and the cross-Object transport call it through `DurableObjectNamespace` stubs. Every
23
+ * `encoded` value is a Schema-encoded envelope (`client.ts` wire schemas for host entry
24
+ * points, `@effect-agent/storage-cloudflare` port envelopes for `portCall`), so the RPC
25
+ * boundary carries only structured-cloneable JSON. The optional trailing trace context is
26
+ * transient native RPC metadata, stripped by an opted-in effect-cf receiver before decoding
27
+ * the host envelope. It never enters durable state.
28
+ */
29
+ interface ConversationObjectRpc extends Rpc.DurableObjectBranded {
30
+ /** Admission-limits gate + `DurableAgentRuntime.submit`; answers a `SubmitResponse`. */
31
+ submitEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;
32
+ /** Wake-hinted, poll-guaranteed settlement wait; answers an `AwaitSettlementResponse`. */
33
+ awaitSettlementEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;
34
+ /** Event-driven durable progress wait; answers a `ProgressObserved` host response. */
35
+ awaitProgressEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;
36
+ /** Best-effort cancellation for one in-flight progress wait. */
37
+ cancelProgressEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;
38
+ /** One bounded page of canonical records; answers an `ObservePageResponse`. */
39
+ observePage(encoded: unknown, traceContext?: unknown): Promise<unknown>;
40
+ /** Durable abort intent; answers an `AbortResponse`. */
41
+ abortEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;
42
+ /** Durable approval decision (plan §2.6); answers a `ResolveApprovalResponse`. */
43
+ resolveApprovalEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;
44
+ /** Authorized DUR-017 Unknown-Outcome resolution; answers a `ResolveUnknownResponse`. */
45
+ resolveUnknownEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;
46
+ /** Owner-side cross-Object port endpoint (WP2 envelopes, executed on LOCAL facets). */
47
+ portCall(encoded: unknown): Promise<unknown>;
48
+ /** Droppable liveness hint from another Object: arms an immediate alarm. */
49
+ wake(): Promise<void>;
50
+ }
51
+ declare const ConversationObjectNamespace_base: Context.ServiceClass<ConversationObjectNamespace, "@effect-agent/platform-cloudflare/ConversationObjectNamespace", {
52
+ readonly namespace: DurableObjectNamespace<ConversationObjectRpc>;
53
+ /** Stable binding name for opted-in native RPC tracing; absent by default. */
54
+ readonly rpcTracing?: string;
55
+ }>;
56
+ /**
57
+ * The `DurableObjectNamespace` binding that addresses Conversation Objects. The Object
58
+ * identity rule is `namespace.idFromName(conversationId)` (plan §1.2): Conversation IDs are
59
+ * globally unique, so the mapping is total and deterministic and no directory service exists.
60
+ */
61
+ declare class ConversationObjectNamespace extends ConversationObjectNamespace_base {
62
+ static layer(namespace: DurableObjectNamespace<ConversationObjectRpc>): Layer.Layer<ConversationObjectNamespace>;
63
+ }
64
+ /**
65
+ * Narrow one `env` member to a `DurableObjectNamespace`. `env` is an untyped platform value,
66
+ * and a namespace binding is a host object no Schema can decode, so this is the documented
67
+ * narrowest-boundary check (structural probe for the namespace surface the transport uses);
68
+ * a missing or misshaped binding fails typed before any Layer is built.
69
+ */
70
+ declare const conversationNamespaceFromEnv: (env: unknown, binding: string) => Effect.Effect<DurableObjectNamespace<ConversationObjectRpc>, CloudflareBindingError, never>;
71
+ /**
72
+ * Build the namespace from Worker `env` (fails typed). Enable `rpcTracing` only when the
73
+ * receiver also opts into the effect-cf native RPC trace-context contract.
74
+ */
75
+ declare const conversationNamespaceLayer: (env: unknown, binding: string, options?: {
76
+ readonly rpcTracing?: boolean;
77
+ }) => Layer.Layer<ConversationObjectNamespace, CloudflareBindingError>;
78
+ declare const DurableObjectContext_base: Context.ServiceClass<DurableObjectContext, "@effect-agent/platform-cloudflare/DurableObjectContext", {
79
+ readonly ctx: DurableObjectState;
80
+ readonly env: unknown;
81
+ }>;
82
+ /**
83
+ * The live Durable Object execution context of THIS incarnation. Only Layer construction and
84
+ * the alarm service consume it; important state never lives on it (`ctx.storage` is truth,
85
+ * everything in memory is a cache — deployment spec §11).
86
+ */
87
+ declare class DurableObjectContext extends DurableObjectContext_base {
88
+ static layer(ctx: DurableObjectState, env: unknown): Layer.Layer<DurableObjectContext>;
89
+ }
90
+ declare const ConversationObjectIdentity_base: Context.ServiceClass<ConversationObjectIdentity, "@effect-agent/platform-cloudflare/ConversationObjectIdentity", {
91
+ readonly conversationId: ConversationId;
92
+ readonly producerId: ProducerId;
93
+ }>;
94
+ /**
95
+ * The Conversation identity this Object serializes and the producer identity its Attempts
96
+ * write with (`{producerPrefix}:{conversationId}`, plan §1.4). Derived once per incarnation
97
+ * from `ctx.id.name` — the Object identity rule guarantees the name IS the Conversation ID.
98
+ */
99
+ declare class ConversationObjectIdentity extends ConversationObjectIdentity_base {}
100
+ //#endregion
101
+ //#region src/scheduling.d.ts
102
+ declare const ScheduleAlarmProtocolError_base: Schema.Class<ScheduleAlarmProtocolError, Schema.TaggedStruct<"ScheduleAlarmProtocolError", {
103
+ readonly message: Schema.String;
104
+ }>, import("effect/Cause").YieldableError>;
105
+ declare class ScheduleAlarmProtocolError extends ScheduleAlarmProtocolError_base {}
106
+ declare const ScheduleOwnerProtocolError_base: Schema.Class<ScheduleOwnerProtocolError, Schema.TaggedStruct<"ScheduleOwnerProtocolError", {
107
+ readonly message: Schema.String;
108
+ }>, import("effect/Cause").YieldableError>;
109
+ declare class ScheduleOwnerProtocolError extends ScheduleOwnerProtocolError_base {}
110
+ interface ScheduleOwnerObjectRpc extends Rpc.DurableObjectBranded {
111
+ schedule(encoded: unknown): Promise<unknown>;
112
+ }
113
+ declare const ScheduleOwnerNamespace_base: Context.ServiceClass<ScheduleOwnerNamespace, "@effect-agent/platform-cloudflare/ScheduleOwnerNamespace", {
114
+ readonly namespace: DurableObjectNamespace<ScheduleOwnerObjectRpc>;
115
+ }>;
116
+ declare class ScheduleOwnerNamespace extends ScheduleOwnerNamespace_base {}
117
+ /** Provides the same authorized management service as NodeScheduling.layer. */
118
+ declare class CloudflareSchedulingClient {
119
+ static readonly layer: Layer.Layer<Scheduling, never, ScheduleOwnerNamespace>;
120
+ }
121
+ declare const ScheduleOwnerIdentity_base: Context.ServiceClass<ScheduleOwnerIdentity, "@effect-agent/platform-cloudflare/ScheduleOwnerIdentity", {
122
+ readonly owner: ScheduleOwner;
123
+ }>;
124
+ declare class ScheduleOwnerIdentity extends ScheduleOwnerIdentity_base {}
125
+ type ScheduleRuntimeServices = Scheduling | ScheduleDriver | DoScheduleAlarmControl | ScheduleOwnerIdentity | DurableObjectAlarm.DurableObjectAlarm;
126
+ interface ScheduleOwnerObjectInstance extends InstanceType<DurableObject.DurableObjectClass<Record<never, never>, ScheduleRuntimeServices>> {
127
+ schedule(encoded: unknown): Promise<unknown>;
128
+ alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> | void;
129
+ }
130
+ interface ScheduleOwnerObjectClass {
131
+ new (ctx: DurableObjectState, env: Cloudflare.Env): ScheduleOwnerObjectInstance;
132
+ }
133
+ /**
134
+ * The host Layer supplies authorization and routing and is cached for the object incarnation.
135
+ * Cloudflare eviction does not guarantee its finalizers run. Do not acquire resources requiring
136
+ * cleanup in this Layer; acquire them inside scoped `manage` / `prepare` operations instead.
137
+ * Native services belong to effect-cf; the database and alarm runtime remain instance-owned.
138
+ */
139
+ declare const makeScheduleOwnerObjectClass: <E>(host: Layer.Layer<ScheduleAuthorizer | ConversationObjectNamespace, E, DurableObjectState$1.DurableObjectState | WorkerEnvironment | ScheduleOwnerIdentity>, limits?: SchedulingLimits) => ScheduleOwnerObjectClass;
140
+ //#endregion
141
+ export { ScheduleOwnerObjectClass as a, ScheduleOwnerProtocolError as c, ConversationObjectIdentity as d, ConversationObjectNamespace as f, conversationNamespaceLayer as g, conversationNamespaceFromEnv as h, ScheduleOwnerNamespace as i, makeScheduleOwnerObjectClass as l, DurableObjectContext as m, ScheduleAlarmProtocolError as n, ScheduleOwnerObjectInstance as o, ConversationObjectRpc as p, ScheduleOwnerIdentity as r, ScheduleOwnerObjectRpc as s, CloudflareSchedulingClient as t, CloudflareBindingError as u };
142
+ //# sourceMappingURL=scheduling-BJs_kHTx.d.mts.map
@@ -0,0 +1,2 @@
1
+ import { a as ScheduleOwnerObjectClass, c as ScheduleOwnerProtocolError, i as ScheduleOwnerNamespace, l as makeScheduleOwnerObjectClass, n as ScheduleAlarmProtocolError, o as ScheduleOwnerObjectInstance, r as ScheduleOwnerIdentity, s as ScheduleOwnerObjectRpc, t as CloudflareSchedulingClient } from "./scheduling-BJs_kHTx.mjs";
2
+ export { CloudflareSchedulingClient, ScheduleAlarmProtocolError, ScheduleOwnerIdentity, ScheduleOwnerNamespace, ScheduleOwnerObjectClass, ScheduleOwnerObjectInstance, ScheduleOwnerObjectRpc, ScheduleOwnerProtocolError, makeScheduleOwnerObjectClass };
@@ -0,0 +1,2 @@
1
+ import { a as ScheduleOwnerProtocolError, i as ScheduleOwnerNamespace, n as ScheduleAlarmProtocolError, o as makeScheduleOwnerObjectClass, r as ScheduleOwnerIdentity, t as CloudflareSchedulingClient } from "./scheduling-B-OFqoS9.mjs";
2
+ export { CloudflareSchedulingClient, ScheduleAlarmProtocolError, ScheduleOwnerIdentity, ScheduleOwnerNamespace, ScheduleOwnerProtocolError, makeScheduleOwnerObjectClass };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@effect-agent/platform-cloudflare",
3
- "version": "0.1.0-beta.36",
3
+ "version": "0.1.0-beta.37",
4
4
  "exports": {
5
5
  ".": {
6
6
  "types": "./dist/index.d.mts",
@@ -25,17 +25,17 @@
25
25
  },
26
26
  "dependencies": {
27
27
  "@cloudflare/puppeteer": "1.1.0",
28
- "@effect-agent/core": "0.1.0-beta.36",
29
- "@effect-agent/engine": "0.1.0-beta.36",
30
- "@effect-agent/sandbox": "0.1.0-beta.36",
31
- "@effect-agent/session": "0.1.0-beta.36",
32
- "@effect-agent/storage-cloudflare": "0.1.0-beta.36",
28
+ "@effect-agent/core": "0.1.0-beta.37",
29
+ "@effect-agent/engine": "0.1.0-beta.37",
30
+ "@effect-agent/sandbox": "0.1.0-beta.37",
31
+ "@effect-agent/session": "0.1.0-beta.37",
32
+ "@effect-agent/storage-cloudflare": "0.1.0-beta.37",
33
33
  "@effect/platform-browser": "4.0.0-rc.111",
34
34
  "@effect/sql-sqlite-do": "4.0.0-rc.111",
35
35
  "effect": "4.0.0-rc.111"
36
36
  },
37
37
  "peerDependencies": {
38
- "effect-cf": "^0.34.0"
38
+ "effect-cf": "^0.37.0"
39
39
  },
40
40
  "description": "Cloudflare Layer assembly for Effect Agent: Durable Objects and Browser Run adapters.",
41
41
  "license": "MIT",
@@ -59,11 +59,12 @@
59
59
  "devDependencies": {
60
60
  "@cloudflare/vitest-pool-workers": "0.21.3",
61
61
  "@cloudflare/workers-types": "5.20260825.1",
62
- "@effect-agent/capabilities": "0.1.0-beta.33",
63
- "@effect-agent/testing": "0.1.0-beta.33",
62
+ "@effect-agent/capabilities": "0.1.0-beta.35",
63
+ "@effect-agent/testing": "0.1.0-beta.35",
64
+ "@effect/platform-node": "4.0.0-rc.111",
64
65
  "@effect/sql-d1": "4.0.0-rc.111",
65
66
  "@effect/vitest": "4.0.0-rc.111",
66
- "effect-cf": "0.34.0",
67
+ "effect-cf": "0.37.0",
67
68
  "esbuild": "0.28.1",
68
69
  "miniflare": "5.20260811.1-alpha",
69
70
  "typescript": "7.0.2",
package/src/index.ts CHANGED
@@ -22,6 +22,7 @@ export * from "./transport.ts";
22
22
  export * from "./layers.ts";
23
23
  export * from "./conversation-object.ts";
24
24
  export * from "./client.ts";
25
+ export * from "./scheduling.ts";
25
26
  export * from "./code-mode-executor.ts";
26
27
  export * from "./browser-quick-action.ts";
27
28
  export * from "./browser-rest-capture.ts";