@effect-agent/platform-cloudflare 0.0.1-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,1073 @@
1
+ import { Clock, Context, Duration, Effect, Layer, ManagedRuntime, Option, PubSub, Random, Ref, Schema, Stream } from "effect";
2
+ import { AbortCommand, AbortIntent, AdmissionConflict, AgentBindingResolver, AppendConflict, ApprovalConflict, ApprovalDecisionCommand, ApprovalDecisionIntent, CanonicalRecordEnvelope, CanonicalSequence, ConversationNotMaterialized, ConversationRead, ConversationStore, ConversationStoreError, DEFAULT_OWNERSHIP_LEASE_DURATION, DefinitionDigests, DeploymentId, DigestError, DurableAgentRuntime, DurableRuntimeConfig, DurableRuntimeFailpoint, DurableRuntimeFailpointError, FenceRejected, IdempotencyKey, IntegrityReport, JoinedToHost, LedgerError, ObligationReport, ObligationThresholds, OperationAuthorizationRequest, OperationAuthorizer, OperationDenied, OwnershipLost, PersistedJson, Principal, ProducerId, Receipt, RecoveryExplanation, RecoveryReport, RetryCommand, RetryRefused, RunJournalError, Settlement, SettlementConflict, SubmissionLedger, SubmissionLookupByKey, ToolReconciler, UnknownResolutionCommand, UnknownResolutionConflict, UnknownResolutionIntent, WakeScheduler } from "@effect-agent/session";
3
+ import { ConversationPortTransport, DEFAULT_MAX_STORED_VALUE_BYTES, conversationStoreLayer, handleEncodedPortRequest, portTransportFailure, routedConversationStoreLayer, routedSubmissionLedgerLayer, storageConfigLayer, storageFailpointLayer, submissionLedgerLayer } from "@effect-agent/storage-cloudflare";
4
+ import { AgentId, AgentInputError, ConversationId, SubmissionId } from "@effect-agent/core";
5
+ import { BrowserCrypto } from "@effect/platform-browser";
6
+ import { SqliteClient } from "@effect/sql-sqlite-do";
7
+ import { DurableObject } from "cloudflare:workers";
8
+ //#region src/bindings.ts
9
+ /**
10
+ * Cloudflare platform bindings as Effect services (DEPLOY-010: "Cloudflare platform bindings
11
+ * are supplied as Effect services/Layers"). Application code never reads `env` or touches a
12
+ * `DurableObjectState` directly — the Conversation Object class constructs these Layers once
13
+ * per incarnation and everything downstream consumes the services.
14
+ */
15
+ /** A Cloudflare platform binding was missing or carried the wrong shape (DEPLOY-003/010). */
16
+ var CloudflareBindingError = class extends Schema.TaggedError()("CloudflareBindingError", {
17
+ binding: Schema.String,
18
+ message: Schema.String
19
+ }) {};
20
+ /**
21
+ * The `DurableObjectNamespace` binding that addresses Conversation Objects. The Object
22
+ * identity rule is `namespace.idFromName(conversationId)` (plan §1.2): Conversation IDs are
23
+ * globally unique, so the mapping is total and deterministic and no directory service exists.
24
+ */
25
+ var ConversationObjectNamespace = class ConversationObjectNamespace extends Context.Service()("@effect-agent/platform-cloudflare/ConversationObjectNamespace") {
26
+ static layer(namespace) {
27
+ return Layer.succeed(ConversationObjectNamespace)({ namespace });
28
+ }
29
+ };
30
+ /**
31
+ * Narrow one `env` member to a `DurableObjectNamespace`. `env` is an untyped platform value,
32
+ * and a namespace binding is a host object no Schema can decode, so this is the documented
33
+ * narrowest-boundary check (structural probe for the namespace surface the transport uses);
34
+ * a missing or misshaped binding fails typed before any Layer is built.
35
+ */
36
+ const conversationNamespaceFromEnv = (env, binding) => Effect.suspend(() => {
37
+ if (typeof env !== "object" || env === null) return Effect.fail(CloudflareBindingError.make({
38
+ binding,
39
+ message: "The Worker environment is not an object; no bindings are available."
40
+ }));
41
+ const candidate = env[binding];
42
+ if (typeof candidate === "object" && candidate !== null && "idFromName" in candidate && typeof candidate.idFromName === "function" && "get" in candidate && typeof candidate.get === "function") return Effect.succeed(candidate);
43
+ return Effect.fail(CloudflareBindingError.make({
44
+ binding,
45
+ message: `env.${binding} is not a DurableObjectNamespace binding; declare the Conversation Object class under this binding in the Worker configuration.`
46
+ }));
47
+ });
48
+ /** `ConversationObjectNamespace` built from the untyped Worker `env` (fails typed). */
49
+ const conversationNamespaceLayer = (env, binding) => Layer.effect(ConversationObjectNamespace)(Effect.map(conversationNamespaceFromEnv(env, binding), (namespace) => ({ namespace })));
50
+ /**
51
+ * The live Durable Object execution context of THIS incarnation. Only Layer construction and
52
+ * the alarm service consume it; important state never lives on it (`ctx.storage` is truth,
53
+ * everything in memory is a cache — deployment spec §11).
54
+ */
55
+ var DurableObjectContext = class DurableObjectContext extends Context.Service()("@effect-agent/platform-cloudflare/DurableObjectContext") {
56
+ static layer(ctx, env) {
57
+ return Layer.succeed(DurableObjectContext)({
58
+ ctx,
59
+ env
60
+ });
61
+ }
62
+ };
63
+ /**
64
+ * The Conversation identity this Object serializes and the producer identity its Attempts
65
+ * write with (`{producerPrefix}:{conversationId}`, plan §1.4). Derived once per incarnation
66
+ * from `ctx.id.name` — the Object identity rule guarantees the name IS the Conversation ID.
67
+ */
68
+ var ConversationObjectIdentity = class extends Context.Service()("@effect-agent/platform-cloudflare/ConversationObjectIdentity") {};
69
+ //#endregion
70
+ //#region src/config.ts
71
+ /**
72
+ * Schema-validated configuration for the Cloudflare durable runtime (deployment spec §4:
73
+ * decoded once during Layer construction, exposed as a typed service; DEPLOY-003). Every
74
+ * cadence is in milliseconds; every bound is finite and checked before any resource opens.
75
+ */
76
+ const PositiveMillis = Schema.Int.check(Schema.isGreaterThan(0));
77
+ const NonNegativeMillis = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
78
+ /** The supplied Cloudflare durable runtime configuration failed validation (DEPLOY-003). */
79
+ var CloudflarePlatformConfigError = class extends Schema.TaggedError()("CloudflarePlatformConfigError", {
80
+ message: Schema.String,
81
+ cause: Schema.optionalKey(Schema.Defect())
82
+ }) {};
83
+ /**
84
+ * An admission was refused by a host resource limit BEFORE any ledger row existed
85
+ * (deployment spec §8, DEPLOY-007: "Admission has explicit bounded quota and overload
86
+ * behavior... a typed rejection"). This is the DC analogue of `NodeDurableHost`'s
87
+ * `AdmissionClosed` host gate: the port surface stays untouched, the refusal happens in the
88
+ * Conversation Object's submit entry point before `DurableAgentRuntime.submit` runs, and
89
+ * nothing was admitted or written.
90
+ */
91
+ var AdmissionLimitExceeded = class extends Schema.TaggedError()("AdmissionLimitExceeded", {
92
+ limit: Schema.Literals([
93
+ "queue-depth",
94
+ "input-bytes",
95
+ "database-bytes"
96
+ ]),
97
+ actual: Schema.Int,
98
+ maximum: Schema.Int
99
+ }) {
100
+ get message() {
101
+ return `Admission refused before any ledger row existed: ${this.limit} ${this.actual} exceeds the configured maximum ${this.maximum}. Accepted work is unaffected; retry after the lane drains or raise the limit (DEPLOY-007).`;
102
+ }
103
+ };
104
+ /** The platform's hard per-Object database cap (10 GB, developers.cloudflare.com limits). */
105
+ const CLOUDFLARE_DATABASE_CAP_BYTES = 1e10;
106
+ /** Default database-size admission ceiling: a 1 GB safety margin under the platform cap. */
107
+ const DEFAULT_MAX_DATABASE_BYTES = 9e9;
108
+ /**
109
+ * Explicit bounded admission quotas checked by the Conversation Object BEFORE admission
110
+ * (exit gate "resource limits are checked before admission").
111
+ */
112
+ var CloudflareAdmissionLimitsValue = class extends Schema.Class("@effect-agent/platform-cloudflare/CloudflareAdmissionLimitsValue")({
113
+ /** Maximum nonterminal Submissions per Conversation lane before new admissions refuse. */
114
+ maxQueueDepthPerLane: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1e5)),
115
+ /** Maximum encoded input bytes; never above the storage per-value bound. */
116
+ maxInputBytes: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(2e6)),
117
+ /** Maximum `ctx.storage.sql.databaseSize` at admission; stays under the 10 GB platform cap. */
118
+ maxDatabaseBytes: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(CLOUDFLARE_DATABASE_CAP_BYTES))
119
+ }) {};
120
+ /**
121
+ * Validated Cloudflare durable runtime configuration. The producer identity of one
122
+ * Conversation Object is `{producerPrefix}:{conversationId}` — stable across incarnations of
123
+ * the same deployment, distinct across deployments — and producer-epoch fencing (not the
124
+ * producer name) remains the correctness authority (DUR-006).
125
+ */
126
+ var CloudflareDurableRuntimeConfigValue = class extends Schema.Class("@effect-agent/platform-cloudflare/CloudflareDurableRuntimeConfigValue")({
127
+ deploymentId: DeploymentId,
128
+ /** Head of the minted producer identity `{producerPrefix}:{conversationId}`. */
129
+ producerPrefix: Schema.NonEmptyString.check(Schema.isMaxLength(256)),
130
+ /** Submission ownership lease duration (D5); fences work across Object incarnations. */
131
+ ownershipLeaseDuration: PositiveMillis,
132
+ /** Base delay of the alarm re-arm backoff when a pass makes no progress. */
133
+ alarmBackoffBase: PositiveMillis,
134
+ /** Ceiling of the alarm re-arm backoff. */
135
+ alarmBackoffCap: PositiveMillis,
136
+ /**
137
+ * The maintenance-pass scan cadence and the ceiling of every re-arm delay: nonterminal
138
+ * work is revisited at least this often (wake/scan pairing, persistence §14).
139
+ */
140
+ wakeScanInterval: PositiveMillis,
141
+ /** `awaitSettlement` ledger re-check cadence when no wake arrives. */
142
+ settlementPollInterval: PositiveMillis,
143
+ /** Worker ownership-lease renewal cadence during an active Attempt. */
144
+ leaseRenewalInterval: PositiveMillis,
145
+ /** Active-Run abort-intent poll cadence. */
146
+ abortPollInterval: PositiveMillis,
147
+ /** Canonical observation poll cadence of the Durable Object store. */
148
+ observationPollInterval: NonNegativeMillis,
149
+ /** Per-value byte bound; must stay under the platform's 2 MB SQLite value limit. */
150
+ maxStoredValueBytes: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(2e6)),
151
+ /** Opt-in full payload/digest-chain audit while opening the store. */
152
+ verifyOnOpen: Schema.Boolean,
153
+ limits: CloudflareAdmissionLimitsValue
154
+ }) {};
155
+ /** Explicit configuration authority for the assembled Cloudflare durable runtime. */
156
+ var CloudflareDurableRuntimeConfig = class extends Context.Service()("@effect-agent/platform-cloudflare/CloudflareDurableRuntimeConfig") {};
157
+ /** Documented production defaults applied by `CloudflareDurableRuntime.layer`. */
158
+ const CLOUDFLARE_RUNTIME_DEFAULTS = {
159
+ ownershipLeaseDuration: Duration.toMillis(DEFAULT_OWNERSHIP_LEASE_DURATION),
160
+ alarmBackoffBase: 100,
161
+ alarmBackoffCap: 5e3,
162
+ wakeScanInterval: 1e3,
163
+ settlementPollInterval: 500,
164
+ leaseRenewalInterval: 1e4,
165
+ abortPollInterval: 500,
166
+ observationPollInterval: 25,
167
+ maxStoredValueBytes: DEFAULT_MAX_STORED_VALUE_BYTES,
168
+ verifyOnOpen: false,
169
+ maxQueueDepthPerLane: 256,
170
+ maxInputBytes: DEFAULT_MAX_STORED_VALUE_BYTES,
171
+ maxDatabaseBytes: DEFAULT_MAX_DATABASE_BYTES
172
+ };
173
+ //#endregion
174
+ //#region src/alarm.ts
175
+ /**
176
+ * The single multiplexed Durable Object alarm (decision D-P6-2). A Durable Object has ONE
177
+ * alarm slot; every cadence the Node host ran on fibers (wake scan, lease expiry, settlement
178
+ * and abort re-checks, retry backoff) multiplexes into one idempotent maintenance pass, and
179
+ * the slot always holds the EARLIEST deadline any caller asked for.
180
+ *
181
+ * The alarm invariant (plan §1.4): committed nonterminal work implies a committed alarm.
182
+ * It is established by pre-arming — every mutating entry point and every pass arms the alarm
183
+ * BEFORE its durable mutations — so an eviction at any failpoint leaves a persisted alarm
184
+ * that workerd re-delivers to a fresh incarnation WITHOUT any incoming request. Spurious
185
+ * alarms are harmless by design: a pass over an all-settled lane simply deletes the slot.
186
+ */
187
+ /** The Durable Object alarm API failed; surfaces on host entry points as a typed refusal. */
188
+ var DurableAlarmError = class extends Schema.TaggedError()("DurableAlarmError", {
189
+ operation: Schema.String,
190
+ message: Schema.String,
191
+ cause: Schema.optionalKey(Schema.Defect())
192
+ }) {};
193
+ const alarmFailure = (operation) => (cause) => DurableAlarmError.make({
194
+ operation,
195
+ message: cause instanceof Error ? cause.message : String(cause),
196
+ cause
197
+ });
198
+ /** `ctx.storage` alarm slot as an Effect service; storage is truth, never a memory field. */
199
+ var DurableAlarmService = class DurableAlarmService extends Context.Service()("@effect-agent/platform-cloudflare/DurableAlarmService") {
200
+ static layer = Layer.effect(DurableAlarmService)(Effect.gen(function* () {
201
+ const { ctx } = yield* DurableObjectContext;
202
+ /**
203
+ * In-memory pass bookkeeping — a pure CACHE, never state: a fresh incarnation has no
204
+ * running pass, and a deferred wake lost to eviction was only ever a promptness hint
205
+ * on top of the already-committed pre-armed alarm.
206
+ */
207
+ const runningPasses = yield* Ref.make(0);
208
+ const wakeDeferred = yield* Ref.make(false);
209
+ const scheduled = Effect.tryPromise({
210
+ try: () => ctx.storage.getAlarm(),
211
+ catch: alarmFailure("get alarm")
212
+ }).pipe(Effect.map((deadline) => deadline === null ? Option.none() : Option.some(deadline)));
213
+ const scheduleAt = (epochMillis) => Effect.tryPromise({
214
+ try: () => ctx.storage.setAlarm(epochMillis),
215
+ catch: alarmFailure("set alarm")
216
+ });
217
+ const ensureScheduledBy = (epochMillis) => scheduled.pipe(Effect.flatMap((existing) => Option.isSome(existing) && existing.value <= epochMillis ? Effect.void : scheduleAt(epochMillis)));
218
+ const armNow = Clock.currentTimeMillis.pipe(Effect.flatMap((now) => ensureScheduledBy(now)));
219
+ const scheduleNow = Ref.get(runningPasses).pipe(Effect.flatMap((passes) => passes > 0 ? Ref.set(wakeDeferred, true) : armNow));
220
+ /**
221
+ * Flush after the LAST concurrent pass: the re-arm lands at the very end of the alarm
222
+ * handler, where a superseding cancellation only re-delivers to the already-idempotent
223
+ * pass. Runs inside `Effect.ensuring`, so flush failures are logged, never raised.
224
+ */
225
+ const flushDeferredWake = Ref.get(runningPasses).pipe(Effect.flatMap((passes) => passes > 0 ? Effect.void : Ref.getAndSet(wakeDeferred, false).pipe(Effect.flatMap((wanted) => wanted ? armNow : Effect.void))), Effect.catch((error) => Effect.logWarning("DurableAlarmService: deferred wake flush failed", error)));
226
+ const withWakesDeferred = (body) => Ref.update(runningPasses, (passes) => passes + 1).pipe(Effect.andThen(body), Effect.ensuring(Ref.update(runningPasses, (passes) => passes - 1).pipe(Effect.andThen(flushDeferredWake))));
227
+ const cancel = Effect.tryPromise({
228
+ try: () => ctx.storage.deleteAlarm(),
229
+ catch: alarmFailure("delete alarm")
230
+ });
231
+ return DurableAlarmService.of({
232
+ scheduled,
233
+ scheduleAt,
234
+ ensureScheduledBy,
235
+ scheduleNow,
236
+ withWakesDeferred,
237
+ cancel
238
+ });
239
+ }));
240
+ };
241
+ /** What one maintenance pass did — auditable evidence mirroring `NodeDurableHost`'s report. */
242
+ var MaintenancePassReport = class extends Schema.Class("@effect-agent/platform-cloudflare/MaintenancePassReport")({
243
+ /** Recovery decisions executed (or deferred) BEFORE any new claim in this pass. */
244
+ recovered: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
245
+ /** Settlements the drain pass finalized. */
246
+ settled: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
247
+ /** Submissions still nonterminal after the pass (suspended/unknown lanes stay honest). */
248
+ nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
249
+ /** `rearmed` while nonterminal work remains, `cleared` once everything settled. */
250
+ alarm: Schema.Literals(["rearmed", "cleared"])
251
+ }) {};
252
+ /**
253
+ * The idempotent maintenance pass and the alarm-invariant helpers (plan §1.4, D-P6-1/2).
254
+ *
255
+ * `pass` = pre-arm → `runRecovery` → `processConversationResolved` → re-arm-or-clear:
256
+ *
257
+ * 1. **Pre-arm**: the alarm is re-armed at `now + wakeScanInterval` BEFORE any work, so an
258
+ * eviction (or thrown failure → workerd alarm retry) at any point of the pass leaves a
259
+ * committed alarm and the fresh incarnation converges without an incoming request.
260
+ * 2. **Reconcile before new work** (exit gate): every pass classifies and repairs every
261
+ * nonterminal Submission before the drain claims anything; the pure classifier and the
262
+ * repair executors are idempotent, so at-least-once alarm delivery re-runs them safely.
263
+ * 3. **Drain**: one bounded `processConversationResolved` pass over this Object's lane — the
264
+ * D-P6-1 shape; no infinite `runResolvedWorker` loop ever pins the Object.
265
+ * 4. **Re-arm policy**: nonterminal work re-arms at `now + min(backoff-with-jitter,
266
+ * wakeScanInterval)` — the scan interval bounds every wait (lease expiry of a dead
267
+ * incarnation included, since claims retry each pass) and the backoff (reset on progress,
268
+ * grown otherwise) keeps stuck lanes from busy-spinning; all settled clears the slot.
269
+ *
270
+ * Every step is a durability-protocol step that already tolerates re-execution, which is
271
+ * what makes double-fired alarms harmless (the alarm.test.ts gate).
272
+ */
273
+ var ConversationMaintenance = class ConversationMaintenance extends Context.Service()("@effect-agent/platform-cloudflare/ConversationMaintenance") {
274
+ static layer = Layer.effect(ConversationMaintenance)(Effect.gen(function* () {
275
+ const runtime = yield* DurableAgentRuntime;
276
+ const resolver = yield* AgentBindingResolver;
277
+ const ledger = yield* SubmissionLedger;
278
+ const alarm = yield* DurableAlarmService;
279
+ const config = yield* CloudflareDurableRuntimeConfig;
280
+ const identity = yield* ConversationObjectIdentity;
281
+ /**
282
+ * Consecutive no-progress passes — an in-memory CACHE, not state: a fresh incarnation
283
+ * restarts at zero and merely re-arms sooner than a long-lived one would have.
284
+ */
285
+ const stalls = yield* Ref.make(0);
286
+ const preArm = Clock.currentTimeMillis.pipe(Effect.flatMap((now) => alarm.ensureScheduledBy(now + config.wakeScanInterval)));
287
+ const countNonterminal = Stream.runCollect(ledger.scanNonterminal).pipe(Effect.map((snapshots) => snapshots.length));
288
+ const rearmDelay = Effect.fn("ConversationMaintenance.rearmDelay")(function* (progressed) {
289
+ const priorStalls = yield* Ref.getAndUpdate(stalls, (count) => progressed ? 0 : count + 1);
290
+ if (progressed) return config.alarmBackoffBase;
291
+ const exponent = Math.min(priorStalls, 30);
292
+ const backoff = Math.min(config.alarmBackoffCap, config.alarmBackoffBase * 2 ** exponent);
293
+ const jitter = yield* Random.next;
294
+ const jittered = Math.ceil(backoff / 2 + backoff / 2 * jitter);
295
+ return Math.min(jittered, config.wakeScanInterval);
296
+ });
297
+ const pass = Effect.fn("ConversationMaintenance.pass")(function* () {
298
+ yield* preArm;
299
+ const recovered = yield* runtime.runRecovery;
300
+ const settlements = yield* runtime.processConversationResolved(identity.conversationId).pipe(Effect.provideService(AgentBindingResolver, resolver));
301
+ const nonterminal = yield* countNonterminal;
302
+ if (nonterminal === 0) {
303
+ yield* alarm.cancel;
304
+ yield* Ref.set(stalls, 0);
305
+ const appeared = yield* countNonterminal;
306
+ if (appeared > 0) {
307
+ yield* preArm;
308
+ return MaintenancePassReport.make({
309
+ recovered: recovered.length,
310
+ settled: settlements.length,
311
+ nonterminal: appeared,
312
+ alarm: "rearmed"
313
+ });
314
+ }
315
+ return MaintenancePassReport.make({
316
+ recovered: recovered.length,
317
+ settled: settlements.length,
318
+ nonterminal,
319
+ alarm: "cleared"
320
+ });
321
+ }
322
+ const progressed = settlements.length > 0 || recovered.some((report) => report.disposition === "repaired");
323
+ const delay = yield* rearmDelay(progressed);
324
+ const now = yield* Clock.currentTimeMillis;
325
+ yield* alarm.ensureScheduledBy(now + delay);
326
+ return MaintenancePassReport.make({
327
+ recovered: recovered.length,
328
+ settled: settlements.length,
329
+ nonterminal,
330
+ alarm: "rearmed"
331
+ });
332
+ });
333
+ const ensureAlarm = Effect.fn("ConversationMaintenance.ensureAlarm")(function* () {
334
+ if ((yield* countNonterminal) === 0) return;
335
+ yield* preArm;
336
+ });
337
+ return ConversationMaintenance.of({
338
+ pass: alarm.withWakesDeferred(pass()),
339
+ ensureAlarm: ensureAlarm(),
340
+ preArm
341
+ });
342
+ }));
343
+ };
344
+ //#endregion
345
+ //#region src/wake-scheduler.ts
346
+ /**
347
+ * Bounded in-memory wake buffer for same-incarnation `awaitSettlement` subscribers. Wake
348
+ * hints are droppable by contract (consumers pair every subscription with ledger polls), so
349
+ * a full buffer slides out the oldest hint and an eviction simply loses the buffer — the
350
+ * poll interval and the persisted alarm keep liveness (persistence §14).
351
+ */
352
+ const WAKE_BUFFER_CAPACITY = 1024;
353
+ /** A remote wake stub call failed; always swallowed and logged (hints are droppable). */
354
+ var RemoteWakeDropped = class extends Schema.TaggedError()("RemoteWakeDropped", {
355
+ conversationId: Schema.String,
356
+ message: Schema.String,
357
+ cause: Schema.optionalKey(Schema.Defect())
358
+ }) {};
359
+ /**
360
+ * The DC `WakeScheduler` (plan §1.4):
361
+ *
362
+ * - `notify(local)` → `setAlarm(now)` — durable, cheap, coalescing (the alarm slot keeps the
363
+ * earliest deadline) — plus a same-incarnation PubSub hint for `awaitSettlement` waiters.
364
+ * - `notify(remote)` → fire-and-forget `wake()` on the owning Object's stub with every error
365
+ * swallowed and logged: hints are droppable, and the target's own alarm/scan pairing (the
366
+ * maintenance pass re-polls unsettled children) guarantees liveness without this call.
367
+ * - `wakes` → the bounded sliding PubSub only. No important state lives in memory: the
368
+ * subscription accelerates waiters within one incarnation and the settlement poll interval
369
+ * is the correctness path.
370
+ */
371
+ const cloudflareWakeSchedulerLayer = Layer.effect(WakeScheduler)(Effect.gen(function* () {
372
+ const alarm = yield* DurableAlarmService;
373
+ const identity = yield* ConversationObjectIdentity;
374
+ const { namespace } = yield* ConversationObjectNamespace;
375
+ const hints = yield* PubSub.sliding(WAKE_BUFFER_CAPACITY);
376
+ yield* Effect.addFinalizer(() => PubSub.shutdown(hints));
377
+ const notifyLocal = (conversationId) => PubSub.publish(hints, conversationId).pipe(Effect.andThen(alarm.scheduleNow), Effect.catch((error) => Effect.logWarning("CloudflareWakeScheduler: local alarm wake failed", error)), Effect.asVoid);
378
+ const notifyRemote = (conversationId) => Effect.tryPromise({
379
+ try: () => namespace.get(namespace.idFromName(conversationId)).wake(),
380
+ catch: (cause) => RemoteWakeDropped.make({
381
+ conversationId,
382
+ message: cause instanceof Error ? cause.message : String(cause),
383
+ cause
384
+ })
385
+ }).pipe(Effect.catch((error) => Effect.logWarning(`CloudflareWakeScheduler: remote wake of ${conversationId} dropped`, error)), Effect.asVoid);
386
+ return WakeScheduler.of({
387
+ notify: (conversationId) => conversationId === identity.conversationId ? notifyLocal(conversationId) : notifyRemote(conversationId),
388
+ wakes: Stream.fromPubSub(hints)
389
+ });
390
+ }));
391
+ //#endregion
392
+ //#region src/transport.ts
393
+ /**
394
+ * `ConversationPortTransport` over native Durable Object JS RPC (decision D-P6-3): one
395
+ * `portCall(envelope)` on the stub of the Object that owns the addressed Conversation
396
+ * (`namespace.idFromName(conversationId)` — the identity rule, plan §1.2). The envelopes are
397
+ * already Schema-encoded JSON, so the RPC boundary carries only structured-cloneable values;
398
+ * the protocol module stays transport-agnostic and fetch-with-JSON remains the documented
399
+ * fallback carrier.
400
+ *
401
+ * Every delivery problem — stub construction, RPC rejection, overload, deploy-in-progress —
402
+ * surfaces as `PortTransportError` (preserving the platform stub's own `retryable` signal
403
+ * when present) and NEVER as a fabricated answer: on `resolveAdmission` the routing layer
404
+ * turns exactly this error into `AdmissionIndeterminate` (SUB-031).
405
+ */
406
+ const conversationPortTransportLayer = Layer.effect(ConversationPortTransport)(Effect.gen(function* () {
407
+ const { namespace } = yield* ConversationObjectNamespace;
408
+ return ConversationPortTransport.of({ call: (conversationId, request) => Effect.tryPromise({
409
+ try: () => namespace.get(namespace.idFromName(conversationId)).portCall(request),
410
+ catch: (cause) => portTransportFailure(conversationId, cause)
411
+ }).pipe(Effect.withSpan("CloudflarePortTransport.call", { attributes: { conversationId } })) });
412
+ }));
413
+ //#endregion
414
+ //#region src/layers.ts
415
+ /**
416
+ * Owner-side endpoint body for the Conversation Object's `portCall` (plan §1.3): decode,
417
+ * execute against THIS Object's LOCAL port facets — never the routed decorators, so a
418
+ * request cannot bounce between Objects — and answer the encoded response envelope. Total by
419
+ * construction (protocol anomalies answer `PortFailed(PortProtocolError)`).
420
+ */
421
+ var ConversationObjectPorts = class extends Context.Service()("@effect-agent/platform-cloudflare/ConversationObjectPorts") {};
422
+ const decodeConfigValue = Schema.decodeUnknownEffect(CloudflareDurableRuntimeConfigValue);
423
+ const decodeConversationId = Schema.decodeUnknownEffect(ConversationId);
424
+ const decodeProducerId = Schema.decodeUnknownEffect(ProducerId);
425
+ const configFromOptions = (options) => decodeConfigValue({
426
+ deploymentId: options.deploymentId,
427
+ producerPrefix: options.producerPrefix,
428
+ ownershipLeaseDuration: options.ownershipLeaseDuration ?? CLOUDFLARE_RUNTIME_DEFAULTS.ownershipLeaseDuration,
429
+ alarmBackoffBase: options.alarmBackoffBase ?? CLOUDFLARE_RUNTIME_DEFAULTS.alarmBackoffBase,
430
+ alarmBackoffCap: options.alarmBackoffCap ?? CLOUDFLARE_RUNTIME_DEFAULTS.alarmBackoffCap,
431
+ wakeScanInterval: options.wakeScanInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.wakeScanInterval,
432
+ settlementPollInterval: options.settlementPollInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.settlementPollInterval,
433
+ leaseRenewalInterval: options.leaseRenewalInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.leaseRenewalInterval,
434
+ abortPollInterval: options.abortPollInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.abortPollInterval,
435
+ observationPollInterval: options.observationPollInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.observationPollInterval,
436
+ maxStoredValueBytes: options.maxStoredValueBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxStoredValueBytes,
437
+ verifyOnOpen: options.verifyOnOpen ?? CLOUDFLARE_RUNTIME_DEFAULTS.verifyOnOpen,
438
+ limits: {
439
+ maxQueueDepthPerLane: options.maxQueueDepthPerLane ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxQueueDepthPerLane,
440
+ maxInputBytes: Math.min(options.maxInputBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxInputBytes, options.maxStoredValueBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxStoredValueBytes),
441
+ maxDatabaseBytes: options.maxDatabaseBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxDatabaseBytes
442
+ }
443
+ }).pipe(Effect.mapError((error) => CloudflarePlatformConfigError.make({
444
+ message: `Invalid Cloudflare durable runtime configuration: ${error.message}`,
445
+ cause: error
446
+ })));
447
+ /**
448
+ * The Conversation this Object owns, from the Object identity rule (plan §1.2): Conversation
449
+ * Objects are addressed exclusively by `idFromName(conversationId)`, so `ctx.id.name` IS the
450
+ * Conversation ID. An unnamed Object (from `newUniqueId`) is a deployment error, not a lane.
451
+ */
452
+ const conversationIdFromState = (ctx) => ctx.id.name === void 0 ? Effect.fail(CloudflarePlatformConfigError.make({ message: "This Durable Object was not created via idFromName(conversationId); Conversation Objects must be addressed by their Conversation identity (plan §1.2)." })) : decodeConversationId(ctx.id.name).pipe(Effect.mapError((error) => CloudflarePlatformConfigError.make({
453
+ message: `The Durable Object name is not a valid ConversationId: ${error.message}`,
454
+ cause: error
455
+ })));
456
+ const resolveBindings = (source, context) => source === void 0 ? Effect.succeed([]) : Effect.isEffect(source) ? source : typeof source === "function" ? Effect.suspend(() => {
457
+ const bindings = source(context);
458
+ return Effect.isEffect(bindings) ? bindings : Effect.succeed(bindings);
459
+ }) : Effect.succeed(source);
460
+ /**
461
+ * The DC Layer assembly (deployment §12: a Layer-assembly library, not an app entrypoint;
462
+ * plan §1.4). `layer(options)` decodes the configuration, derives this Object's Conversation
463
+ * and producer identities, opens the Object's private SQLite database through
464
+ * `@effect/sql-sqlite-do` for BOTH the Conversation Log and the Submission Ledger (so claims
465
+ * fence the same producer epochs — ADR-0011 D7 transposed), wraps the local port facets with
466
+ * the WP2 cross-Object routing decorators over the Durable Object RPC transport, wires the
467
+ * alarm-backed wake scheduler and the maintenance pass, defaults reconciliation to the
468
+ * fail-closed `ToolReconciler.uncertain`, and provides a ready `DurableAgentRuntime` on top.
469
+ *
470
+ * Storage compatibility is verified during construction: an incompatible database fails the
471
+ * Layer typed (`DoStorageCompatibilityError`) before anything is mutated (DEPLOY-008).
472
+ *
473
+ * Requires only the two binding services (`DurableObjectContext`,
474
+ * `ConversationObjectNamespace`) — platform values enter exclusively through Layers
475
+ * (DEPLOY-010).
476
+ */
477
+ var CloudflareDurableRuntime = class {
478
+ static layer(options) {
479
+ return Layer.unwrap(Effect.gen(function* () {
480
+ const { ctx, env } = yield* DurableObjectContext;
481
+ const config = yield* configFromOptions(options);
482
+ const conversationId = yield* conversationIdFromState(ctx);
483
+ const producerId = yield* decodeProducerId(`${config.producerPrefix}:${conversationId}`).pipe(Effect.mapError((error) => CloudflarePlatformConfigError.make({
484
+ message: `The minted producer identity is invalid: ${error.message}`,
485
+ cause: error
486
+ })));
487
+ const identityLayer = Layer.succeed(ConversationObjectIdentity)({
488
+ conversationId,
489
+ producerId
490
+ });
491
+ const cloudflareConfigLayer = Layer.succeed(CloudflareDurableRuntimeConfig)(config);
492
+ const storageOptions = {
493
+ storage: ctx.storage,
494
+ observationPollInterval: config.observationPollInterval,
495
+ ownershipLeaseDuration: config.ownershipLeaseDuration,
496
+ maxStoredValueBytes: config.maxStoredValueBytes,
497
+ verifyOnOpen: config.verifyOnOpen,
498
+ failpoint: options.storageFailpoint?.(ctx)
499
+ };
500
+ const infrastructure = Layer.mergeAll(storageConfigLayer(storageOptions), storageFailpointLayer(storageOptions), SqliteClient.layer({ storage: ctx.storage }), BrowserCrypto.layer);
501
+ /**
502
+ * ONE local-facet instance (a shared Layer value) serves both the routed decorators
503
+ * and the owner-side `portCall` executor — the executor must never see the routed
504
+ * ports (plan §1.3: re-routing could bounce a request between Objects).
505
+ */
506
+ const localPorts = Layer.mergeAll(conversationStoreLayer, submissionLedgerLayer).pipe(Layer.provide(infrastructure));
507
+ const portsEndpointLayer = Layer.effect(ConversationObjectPorts)(Effect.gen(function* () {
508
+ const local = yield* Effect.context();
509
+ return ConversationObjectPorts.of({ handle: (encoded) => handleEncodedPortRequest(encoded).pipe(Effect.provide(local)) });
510
+ })).pipe(Layer.provide(localPorts));
511
+ const routedPorts = Layer.mergeAll(routedSubmissionLedgerLayer({ localConversationId: conversationId }), routedConversationStoreLayer({ localConversationId: conversationId })).pipe(Layer.provide(localPorts), Layer.provide(conversationPortTransportLayer));
512
+ const runtimeConfigLayer = Layer.succeed(DurableRuntimeConfig)(DurableRuntimeConfig.make({
513
+ deploymentId: config.deploymentId,
514
+ producerId,
515
+ settlementPollInterval: Duration.millis(config.settlementPollInterval),
516
+ leaseRenewalInterval: Duration.millis(config.leaseRenewalInterval),
517
+ abortPollInterval: Duration.millis(config.abortPollInterval)
518
+ }));
519
+ const runtimeFailpointLayer = options.runtimeFailpoint === void 0 ? DurableRuntimeFailpoint.layer : Layer.succeed(DurableRuntimeFailpoint)({ hit: options.runtimeFailpoint(ctx) });
520
+ const reconcilerLayer = options.toolReconciler ?? ToolReconciler.uncertain;
521
+ const bindingResolverLayer = Layer.effect(AgentBindingResolver)(Effect.map(resolveBindings(options.bindings, {
522
+ ctx,
523
+ env,
524
+ conversationId,
525
+ producerId
526
+ }), (bindings) => AgentBindingResolver.fromBindings(bindings)));
527
+ const base = Layer.mergeAll(identityLayer, cloudflareConfigLayer, DurableAlarmService.layer);
528
+ const runtimeStack = DurableAgentRuntime.layer.pipe(Layer.provideMerge(routedPorts), Layer.provideMerge(cloudflareWakeSchedulerLayer), Layer.provideMerge(runtimeConfigLayer), Layer.provideMerge(bindingResolverLayer), Layer.provide(Layer.mergeAll(runtimeFailpointLayer, reconcilerLayer, BrowserCrypto.layer)), Layer.provideMerge(base));
529
+ return Layer.mergeAll(runtimeStack, ConversationMaintenance.layer.pipe(Layer.provide(runtimeStack)), portsEndpointLayer);
530
+ }));
531
+ }
532
+ };
533
+ //#endregion
534
+ //#region src/client.ts
535
+ /**
536
+ * The Worker↔Conversation-Object host protocol (plan §1.4): Schema envelopes for the host
537
+ * entry points (`submitEncoded`, `awaitSettlementEncoded`, `observePage`, `abortEncoded`,
538
+ * `resolveApprovalEncoded`, `resolveUnknownEncoded`) plus the Worker-side client that speaks
539
+ * it. Mirrors the WP2 port protocol: requests and responses are closed Schema unions, typed
540
+ * failures travel as their own tagged classes and RE-DECODE to identical tags on the caller
541
+ * (error-tag fidelity), and protocol anomalies are answered typed instead of thrown.
542
+ */
543
+ /** Ceiling for host protocol diagnostic strings. */
544
+ const MAX_HOST_DIAGNOSTIC_LENGTH = 4096;
545
+ const BoundedDiagnostic = Schema.String.check(Schema.isMaxLength(MAX_HOST_DIAGNOSTIC_LENGTH));
546
+ /** Truncate a diagnostic string to the host protocol's bounded length. */
547
+ const boundHostDiagnostic = (value) => value.length > MAX_HOST_DIAGNOSTIC_LENGTH ? `${value.slice(0, MAX_HOST_DIAGNOSTIC_LENGTH - 3)}...` : value;
548
+ /**
549
+ * The envelope itself could not be honored: the Object could not decode the request, or a
550
+ * response could not be encoded/decoded. Never carries operation semantics.
551
+ */
552
+ var HostProtocolError = class extends Schema.TaggedError()("HostProtocolError", { message: BoundedDiagnostic }) {};
553
+ /** The Worker-side stub call itself failed (RPC rejection, overload, eviction mid-call). */
554
+ var ConversationClientError = class extends Schema.TaggedError()("ConversationClientError", {
555
+ conversationId: Schema.String,
556
+ message: Schema.String,
557
+ cause: Schema.optionalKey(Schema.Defect())
558
+ }) {};
559
+ /**
560
+ * One durable submission, input ALREADY encoded by the caller through the Agent Binding's
561
+ * input schema (the Worker bundles the same Agent definitions as the Object, so schema
562
+ * validation happens client-side; the resolved Binding re-validates at claim time). The
563
+ * Conversation identity is deliberately absent — the addressed Object IS the lane.
564
+ */
565
+ var SubmitRequest = class extends Schema.Class("@effect-agent/platform-cloudflare/SubmitRequest")({
566
+ agentId: AgentId,
567
+ principal: Principal,
568
+ idempotencyKey: IdempotencyKey,
569
+ definitions: DefinitionDigests,
570
+ inputPayload: PersistedJson
571
+ }) {};
572
+ /** One bounded page of canonical records after an optional sequence. */
573
+ var ObservePageRequest = class extends Schema.Class("@effect-agent/platform-cloudflare/ObservePageRequest")({
574
+ afterSequence: Schema.optionalKey(CanonicalSequence),
575
+ limit: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1024))
576
+ }) {};
577
+ /**
578
+ * Every typed failure a host entry point can produce, plus the protocol's own errors. Same
579
+ * closed-union discipline as the WP2 `PortFailure`: members re-decode to the SAME tagged
580
+ * classes on the Worker side; `cause` chains travel as Schema defects without instance
581
+ * fidelity (plan §2.8).
582
+ */
583
+ const HostFailure = Schema.Union([
584
+ AgentInputError,
585
+ DigestError,
586
+ AdmissionConflict,
587
+ SettlementConflict,
588
+ ApprovalConflict,
589
+ UnknownResolutionConflict,
590
+ JoinedToHost,
591
+ LedgerError,
592
+ ConversationStoreError,
593
+ ConversationNotMaterialized,
594
+ AppendConflict,
595
+ FenceRejected,
596
+ DurableRuntimeFailpointError,
597
+ AdmissionLimitExceeded,
598
+ DurableAlarmError,
599
+ HostProtocolError
600
+ ]);
601
+ var SubmitSucceeded = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/SubmitSucceeded")("SubmitSucceeded", { receipt: Receipt }) {};
602
+ var SettlementReached = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/SettlementReached")("SettlementReached", { settlement: Settlement }) {};
603
+ var ObservedPage = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/ObservedPage")("ObservedPage", { records: Schema.Array(CanonicalRecordEnvelope).check(Schema.isMaxLength(1024)) }) {};
604
+ var AbortRecorded = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/AbortRecorded")("AbortRecorded", { intent: AbortIntent }) {};
605
+ var ApprovalRecorded = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/ApprovalRecorded")("ApprovalRecorded", { intent: ApprovalDecisionIntent }) {};
606
+ var UnknownResolutionRecorded = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/UnknownResolutionRecorded")("UnknownResolutionRecorded", { intent: UnknownResolutionIntent }) {};
607
+ /** The entry point failed TYPED on the Object; the failure re-decodes verbatim. */
608
+ var HostFailed = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/HostFailed")("HostFailed", { failure: HostFailure }) {};
609
+ /** The uniform answer of one host entry point. Callers narrow by the tag their call implies. */
610
+ const HostResponse = Schema.Union([
611
+ SubmitSucceeded,
612
+ SettlementReached,
613
+ ObservedPage,
614
+ AbortRecorded,
615
+ ApprovalRecorded,
616
+ UnknownResolutionRecorded,
617
+ HostFailed
618
+ ]);
619
+ const decodeSubmitRequest = Schema.decodeUnknownEffect(SubmitRequest);
620
+ const encodeSubmitRequest = Schema.encodeEffect(SubmitRequest);
621
+ const decodeReceipt = Schema.decodeUnknownEffect(Receipt);
622
+ const encodeReceipt = Schema.encodeEffect(Receipt);
623
+ const decodeObservePageRequest = Schema.decodeUnknownEffect(ObservePageRequest);
624
+ const encodeObservePageRequest = Schema.encodeEffect(ObservePageRequest);
625
+ const decodeAbortCommand = Schema.decodeUnknownEffect(AbortCommand);
626
+ const encodeAbortCommand = Schema.encodeEffect(AbortCommand);
627
+ const decodeApprovalDecisionCommand = Schema.decodeUnknownEffect(ApprovalDecisionCommand);
628
+ const encodeApprovalDecisionCommand = Schema.encodeEffect(ApprovalDecisionCommand);
629
+ const decodeUnknownResolutionCommand = Schema.decodeUnknownEffect(UnknownResolutionCommand);
630
+ const encodeUnknownResolutionCommand = Schema.encodeEffect(UnknownResolutionCommand);
631
+ const encodeHostResponse = Schema.encodeEffect(HostResponse);
632
+ const decodeHostResponse = Schema.decodeUnknownEffect(HostResponse);
633
+ const SUBMIT_FAILURE_TAGS = /* @__PURE__ */ new Set([
634
+ "AgentInputError",
635
+ "DigestError",
636
+ "AdmissionConflict",
637
+ "LedgerError",
638
+ "ConversationStoreError",
639
+ "ConversationNotMaterialized",
640
+ "AppendConflict",
641
+ "FenceRejected",
642
+ "DurableRuntimeFailpointError",
643
+ "AdmissionLimitExceeded",
644
+ "DurableAlarmError",
645
+ "HostProtocolError"
646
+ ]);
647
+ const AWAIT_FAILURE_TAGS = /* @__PURE__ */ new Set([
648
+ "LedgerError",
649
+ "SettlementConflict",
650
+ "HostProtocolError"
651
+ ]);
652
+ const OBSERVE_FAILURE_TAGS = /* @__PURE__ */ new Set([
653
+ "ConversationStoreError",
654
+ "ConversationNotMaterialized",
655
+ "HostProtocolError"
656
+ ]);
657
+ const ABORT_FAILURE_TAGS = /* @__PURE__ */ new Set([
658
+ "LedgerError",
659
+ "SettlementConflict",
660
+ "JoinedToHost",
661
+ "DurableRuntimeFailpointError",
662
+ "DurableAlarmError",
663
+ "HostProtocolError"
664
+ ]);
665
+ const APPROVAL_FAILURE_TAGS = /* @__PURE__ */ new Set([
666
+ "LedgerError",
667
+ "SettlementConflict",
668
+ "ApprovalConflict",
669
+ "DurableAlarmError",
670
+ "HostProtocolError"
671
+ ]);
672
+ const UNKNOWN_FAILURE_TAGS = /* @__PURE__ */ new Set([
673
+ "LedgerError",
674
+ "SettlementConflict",
675
+ "UnknownResolutionConflict",
676
+ "JoinedToHost",
677
+ "DurableRuntimeFailpointError",
678
+ "DurableAlarmError",
679
+ "HostProtocolError"
680
+ ]);
681
+ const outOfContract = (conversationId, operation, observed) => ConversationClientError.make({
682
+ conversationId,
683
+ message: boundHostDiagnostic(`The Conversation Object answered ${operation} with the out-of-contract ${observed}.`)
684
+ });
685
+ /**
686
+ * Narrow one decoded `HostFailed.failure` to the operation's declared failure family; an
687
+ * out-of-contract tag folds into `ConversationClientError` instead of being erased or
688
+ * re-thrown raw (the WP2 discipline). The predicate is the single documented narrowing over
689
+ * the closed `HostFailure` union.
690
+ */
691
+ const narrowFailure = (tags) => (failure) => tags.has(failure._tag);
692
+ /** Worker-side client over the Conversation Object namespace (DEPLOY-010). */
693
+ var CloudflareConversationClient = class CloudflareConversationClient extends Context.Service()("@effect-agent/platform-cloudflare/CloudflareConversationClient") {
694
+ static layer = Layer.effect(CloudflareConversationClient)(Effect.gen(function* () {
695
+ const { namespace } = yield* ConversationObjectNamespace;
696
+ const call = (conversationId, operation, invoke) => Effect.tryPromise({
697
+ try: () => invoke(namespace.get(namespace.idFromName(conversationId))),
698
+ catch: (cause) => ConversationClientError.make({
699
+ conversationId,
700
+ message: boundHostDiagnostic(`${operation} did not reach the Conversation Object: ${cause instanceof Error ? cause.message : String(cause)}`),
701
+ cause
702
+ })
703
+ }).pipe(Effect.flatMap((raw) => decodeHostResponse(raw).pipe(Effect.mapError((error) => HostProtocolError.make({ message: boundHostDiagnostic(`The ${operation} answer could not be decoded: ${error.message}`) })))), Effect.withSpan("CloudflareConversationClient.call", { attributes: {
704
+ conversationId,
705
+ operation
706
+ } }));
707
+ const expect = (conversationId, operation, resultTag, tags) => {
708
+ const isExpected = narrowFailure(tags);
709
+ return (response) => {
710
+ if (response._tag === "HostFailed") {
711
+ const failure = response.failure;
712
+ return isExpected(failure) ? Effect.fail(failure) : Effect.fail(outOfContract(conversationId, operation, `failure ${failure._tag}`));
713
+ }
714
+ if (response._tag !== resultTag) return Effect.fail(outOfContract(conversationId, operation, `result ${response._tag}`));
715
+ return Effect.succeed(response);
716
+ };
717
+ };
718
+ const readPage = (conversationId, options) => Effect.gen(function* () {
719
+ const request = ObservePageRequest.make({
720
+ ...options?.afterSequence === void 0 ? {} : { afterSequence: options.afterSequence },
721
+ limit: options?.limit ?? 256
722
+ });
723
+ const encoded = yield* encodeObservePageRequest(request).pipe(Effect.mapError((error) => HostProtocolError.make({ message: boundHostDiagnostic(`observePage request encode failed: ${error.message}`) })));
724
+ const response = yield* call(conversationId, "observePage", (stub) => stub.observePage(encoded));
725
+ return (yield* expect(conversationId, "observePage", "ObservedPage", OBSERVE_FAILURE_TAGS)(response)).records;
726
+ });
727
+ return CloudflareConversationClient.of({
728
+ submit: (agent, input, options) => Effect.gen(function* () {
729
+ const encodedInput = yield* Schema.encodeEffect(agent.definition.input)(input).pipe(Effect.mapError((cause) => AgentInputError.make({ message: `Unable to encode Agent input: ${cause.message}` })));
730
+ const inputPayload = yield* Schema.decodeUnknownEffect(PersistedJson)(encodedInput).pipe(Effect.mapError(() => AgentInputError.make({ message: "Agent input does not satisfy the canonical persistence bounds" })));
731
+ const request = SubmitRequest.make({
732
+ agentId: agent.definition.id,
733
+ principal: options.principal,
734
+ idempotencyKey: options.idempotencyKey,
735
+ definitions: options.definitions,
736
+ inputPayload
737
+ });
738
+ const encoded = yield* encodeSubmitRequest(request).pipe(Effect.mapError((error) => HostProtocolError.make({ message: boundHostDiagnostic(`submit request encode failed: ${error.message}`) })));
739
+ const response = yield* call(options.conversationId, "submit", (stub) => stub.submitEncoded(encoded));
740
+ return (yield* expect(options.conversationId, "submit", "SubmitSucceeded", SUBMIT_FAILURE_TAGS)(response)).receipt;
741
+ }),
742
+ awaitSettlement: (receipt) => Effect.gen(function* () {
743
+ const encoded = yield* encodeReceipt(receipt).pipe(Effect.mapError((error) => HostProtocolError.make({ message: boundHostDiagnostic(`receipt encode failed: ${error.message}`) })));
744
+ const response = yield* call(receipt.conversationId, "awaitSettlement", (stub) => stub.awaitSettlementEncoded(encoded));
745
+ return (yield* expect(receipt.conversationId, "awaitSettlement", "SettlementReached", AWAIT_FAILURE_TAGS)(response)).settlement;
746
+ }),
747
+ readPage,
748
+ readAll: (conversationId) => Effect.gen(function* () {
749
+ const all = [];
750
+ let after;
751
+ for (;;) {
752
+ const page = yield* readPage(conversationId, {
753
+ afterSequence: after,
754
+ limit: 1024
755
+ });
756
+ all.push(...page);
757
+ const last = page.at(-1);
758
+ if (page.length < 1024 || last === void 0) return all;
759
+ after = last.sequence;
760
+ }
761
+ }),
762
+ abort: (conversationId, command) => Effect.gen(function* () {
763
+ const encoded = yield* encodeAbortCommand(command).pipe(Effect.mapError((error) => HostProtocolError.make({ message: boundHostDiagnostic(`abort command encode failed: ${error.message}`) })));
764
+ const response = yield* call(conversationId, "abort", (stub) => stub.abortEncoded(encoded));
765
+ return (yield* expect(conversationId, "abort", "AbortRecorded", ABORT_FAILURE_TAGS)(response)).intent;
766
+ }),
767
+ resolveApproval: (conversationId, command) => Effect.gen(function* () {
768
+ const encoded = yield* encodeApprovalDecisionCommand(command).pipe(Effect.mapError((error) => HostProtocolError.make({ message: boundHostDiagnostic(`approval command encode failed: ${error.message}`) })));
769
+ const response = yield* call(conversationId, "resolveApproval", (stub) => stub.resolveApprovalEncoded(encoded));
770
+ return (yield* expect(conversationId, "resolveApproval", "ApprovalRecorded", APPROVAL_FAILURE_TAGS)(response)).intent;
771
+ }),
772
+ resolveUnknown: (conversationId, command) => Effect.gen(function* () {
773
+ const encoded = yield* encodeUnknownResolutionCommand(command).pipe(Effect.mapError((error) => HostProtocolError.make({ message: boundHostDiagnostic(`resolution command encode failed: ${error.message}`) })));
774
+ const response = yield* call(conversationId, "resolveUnknown", (stub) => stub.resolveUnknownEncoded(encoded));
775
+ return (yield* expect(conversationId, "resolveUnknown", "UnknownResolutionRecorded", UNKNOWN_FAILURE_TAGS)(response)).intent;
776
+ })
777
+ });
778
+ }));
779
+ };
780
+ //#endregion
781
+ //#region src/conversation-object.ts
782
+ /** Port envelope tags whose owner-side execution durably mutates this Object's lane. */
783
+ const MUTATING_PORT_TAGS = /* @__PURE__ */ new Set([
784
+ "LedgerAdmit",
785
+ "LedgerMarkReady",
786
+ "LedgerRequestAbort",
787
+ "LedgerRecordChildSettled",
788
+ "StoreMaterialize",
789
+ "StoreAppend"
790
+ ]);
791
+ const isMutatingPortRequest = (encoded) => typeof encoded === "object" && encoded !== null && "_tag" in encoded && typeof encoded._tag === "string" && MUTATING_PORT_TAGS.has(encoded._tag);
792
+ /** The literal encoded `PortFailed(PortProtocolError)` fallback (same shape as WP2's). */
793
+ const encodedPortProtocolFailure = (message) => ({
794
+ _tag: "PortFailed",
795
+ failure: {
796
+ _tag: "PortProtocolError",
797
+ message: boundHostDiagnostic(message)
798
+ }
799
+ });
800
+ const protocolFailure = (context) => (error) => HostProtocolError.make({ message: boundHostDiagnostic(`${context}: ${error.message}`) });
801
+ /** Fold one endpoint's typed failures into the uniform `HostResponse` envelope. */
802
+ const respond = (effect) => effect.pipe(Effect.map((result) => result), Effect.catch((failure) => Effect.succeed(HostFailed.make({ failure }))));
803
+ /** Encode the response envelope; an unencodable response degrades to a protocol failure. */
804
+ const encodeResponse = (response) => encodeHostResponse(response).pipe(Effect.catch((error) => Effect.succeed({
805
+ _tag: "HostFailed",
806
+ failure: {
807
+ _tag: "HostProtocolError",
808
+ message: boundHostDiagnostic(`The host response could not be encoded: ${error.message}`)
809
+ }
810
+ })));
811
+ const utf8Bytes = (value) => new TextEncoder().encode(JSON.stringify(value)).length;
812
+ /**
813
+ * The admission-limits gate, BEFORE `runtime.submit` touches the ledger (exit gate
814
+ * "resource limits are checked before admission"; DEPLOY-007). A replayed idempotency key is
815
+ * exempt: its accepted-work obligation already exists, and returning the original Receipt
816
+ * consumes no new quota. Refusals are typed `AdmissionLimitExceeded` and nothing is written.
817
+ */
818
+ const gateAdmissionLimits = Effect.fn("ConversationObject.gateAdmissionLimits")(function* (request) {
819
+ const identity = yield* ConversationObjectIdentity;
820
+ const config = yield* CloudflareDurableRuntimeConfig;
821
+ const ledger = yield* SubmissionLedger;
822
+ const { ctx } = yield* DurableObjectContext;
823
+ const existing = yield* ledger.lookup(SubmissionLookupByKey.make({
824
+ conversationId: identity.conversationId,
825
+ principal: request.principal,
826
+ idempotencyKey: request.idempotencyKey
827
+ }));
828
+ if (Option.isSome(existing)) return;
829
+ const inputBytes = utf8Bytes(request.inputPayload);
830
+ if (inputBytes > config.limits.maxInputBytes) return yield* AdmissionLimitExceeded.make({
831
+ limit: "input-bytes",
832
+ actual: inputBytes,
833
+ maximum: config.limits.maxInputBytes
834
+ });
835
+ const nonterminal = yield* Stream.runCollect(ledger.scanNonterminal);
836
+ if (nonterminal.length >= config.limits.maxQueueDepthPerLane) return yield* AdmissionLimitExceeded.make({
837
+ limit: "queue-depth",
838
+ actual: nonterminal.length,
839
+ maximum: config.limits.maxQueueDepthPerLane
840
+ });
841
+ const databaseBytes = yield* Effect.sync(() => ctx.storage.sql.databaseSize);
842
+ if (databaseBytes > config.limits.maxDatabaseBytes) return yield* AdmissionLimitExceeded.make({
843
+ limit: "database-bytes",
844
+ actual: databaseBytes,
845
+ maximum: config.limits.maxDatabaseBytes
846
+ });
847
+ });
848
+ /**
849
+ * The submit-capable projection of an Agent Binding on the OBJECT side: the input arrived
850
+ * already encoded through the real input schema on the Worker side (`client.ts`), so the
851
+ * Object admits the canonical `PersistedJson` payload as-is; the resolved Binding re-derives
852
+ * everything else from the stored `(agentId, agentDigests)` at claim time (SUB-023).
853
+ */
854
+ const passthroughSubmitAgent = (agentId) => ({ definition: {
855
+ id: agentId,
856
+ input: PersistedJson
857
+ } });
858
+ const submitEndpoint = (encoded) => decodeSubmitRequest(encoded).pipe(Effect.mapError(protocolFailure("The submit request could not be decoded")), Effect.flatMap((request) => Effect.gen(function* () {
859
+ const identity = yield* ConversationObjectIdentity;
860
+ const maintenance = yield* ConversationMaintenance;
861
+ const runtime = yield* DurableAgentRuntime;
862
+ yield* gateAdmissionLimits(request);
863
+ yield* maintenance.preArm;
864
+ const receipt = yield* runtime.submit(passthroughSubmitAgent(request.agentId), request.inputPayload, {
865
+ conversationId: identity.conversationId,
866
+ principal: request.principal,
867
+ idempotencyKey: request.idempotencyKey,
868
+ definitions: request.definitions
869
+ });
870
+ return SubmitSucceeded.make({ receipt });
871
+ })), respond, Effect.flatMap(encodeResponse));
872
+ const awaitSettlementEndpoint = (encoded) => decodeReceipt(encoded).pipe(Effect.mapError(protocolFailure("The receipt could not be decoded")), Effect.flatMap((receipt) => Effect.gen(function* () {
873
+ const settlement = yield* (yield* DurableAgentRuntime).awaitSettlement(receipt);
874
+ return SettlementReached.make({ settlement });
875
+ })), respond, Effect.flatMap(encodeResponse));
876
+ const observePageEndpoint = (encoded) => decodeObservePageRequest(encoded).pipe(Effect.mapError(protocolFailure("The observe request could not be decoded")), Effect.flatMap((request) => Effect.gen(function* () {
877
+ const identity = yield* ConversationObjectIdentity;
878
+ const store = yield* ConversationStore;
879
+ yield* (yield* OperationAuthorizer).authorize(OperationAuthorizationRequest.make({
880
+ operation: "observe",
881
+ conversationId: identity.conversationId
882
+ })).pipe(Effect.catchTag("OperationDenied", deniedToProtocolFailure));
883
+ const records = yield* Stream.runCollect(store.read(ConversationRead.make({
884
+ conversationId: identity.conversationId,
885
+ ...request.afterSequence === void 0 ? {} : { afterSequence: request.afterSequence },
886
+ limit: request.limit
887
+ })));
888
+ return ObservedPage.make({ records: [...records] });
889
+ })), respond, Effect.flatMap(encodeResponse));
890
+ const abortEndpoint = (encoded) => decodeAbortCommand(encoded).pipe(Effect.mapError(protocolFailure("The abort command could not be decoded")), Effect.flatMap((command) => Effect.gen(function* () {
891
+ const maintenance = yield* ConversationMaintenance;
892
+ const runtime = yield* DurableAgentRuntime;
893
+ yield* maintenance.preArm;
894
+ const intent = yield* runtime.abort(command);
895
+ return AbortRecorded.make({ intent });
896
+ })), respond, Effect.flatMap(encodeResponse));
897
+ /**
898
+ * The pre-P7 host protocol's failure union does not carry `OperationDenied` (the Worker client
899
+ * predates the authorizer). This assembly always runs the default possession authorizer — no
900
+ * `CloudflareDurableRuntimeOptions` authorizer lever exists yet — so a denial here is
901
+ * unreachable today; if one ever surfaces it degrades to the protocol failure instead of an
902
+ * out-of-contract throw. The four P7 admin entry points below carry `OperationDenied` typed.
903
+ */
904
+ const deniedToProtocolFailure = (denied) => Effect.fail(HostProtocolError.make({ message: boundHostDiagnostic(`The ${denied.operation} operation was denied: ${denied.reason}`) }));
905
+ const resolveApprovalEndpoint = (encoded) => decodeApprovalDecisionCommand(encoded).pipe(Effect.mapError(protocolFailure("The approval command could not be decoded")), Effect.flatMap((command) => Effect.gen(function* () {
906
+ const maintenance = yield* ConversationMaintenance;
907
+ const runtime = yield* DurableAgentRuntime;
908
+ yield* maintenance.preArm;
909
+ const intent = yield* runtime.resolveApproval(command).pipe(Effect.catchTag("OperationDenied", deniedToProtocolFailure));
910
+ return ApprovalRecorded.make({ intent });
911
+ })), respond, Effect.flatMap(encodeResponse));
912
+ const resolveUnknownEndpoint = (encoded) => decodeUnknownResolutionCommand(encoded).pipe(Effect.mapError(protocolFailure("The resolution command could not be decoded")), Effect.flatMap((command) => Effect.gen(function* () {
913
+ const maintenance = yield* ConversationMaintenance;
914
+ const runtime = yield* DurableAgentRuntime;
915
+ yield* maintenance.preArm;
916
+ const intent = yield* runtime.resolveUnknown(command).pipe(Effect.catchTag("OperationDenied", deniedToProtocolFailure));
917
+ return UnknownResolutionRecorded.make({ intent });
918
+ })), respond, Effect.flatMap(encodeResponse));
919
+ /** Explain one Submission (`submissionId` present) or every nonterminal lane member. */
920
+ var AdminExplainRequest = class extends Schema.Class("@effect-agent/platform-cloudflare/AdminExplainRequest")({ submissionId: Schema.optionalKey(SubmissionId) }) {};
921
+ /** Verify carries no parameters — the addressed Object IS the lane. */
922
+ var AdminVerifyRequest = class extends Schema.Class("@effect-agent/platform-cloudflare/AdminVerifyRequest")({}) {};
923
+ /** Every typed failure of the four admin entry points, plus the protocol's own errors. */
924
+ const AdminFailure = Schema.Union([
925
+ OperationDenied,
926
+ RetryRefused,
927
+ LedgerError,
928
+ RunJournalError,
929
+ DigestError,
930
+ OwnershipLost,
931
+ SettlementConflict,
932
+ ConversationStoreError,
933
+ ConversationNotMaterialized,
934
+ AppendConflict,
935
+ FenceRejected,
936
+ DurableRuntimeFailpointError,
937
+ DurableAlarmError,
938
+ HostProtocolError
939
+ ]);
940
+ var ExplainedRecovery = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/ExplainedRecovery")("ExplainedRecovery", { explanations: Schema.Array(RecoveryExplanation).check(Schema.isMaxLength(1024)) }) {};
941
+ var VerifiedIntegrity = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/VerifiedIntegrity")("VerifiedIntegrity", { report: IntegrityReport }) {};
942
+ var RetryExecuted = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/RetryExecuted")("RetryExecuted", { report: RecoveryReport }) {};
943
+ var ObligationsScanned = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/ObligationsScanned")("ObligationsScanned", { report: ObligationReport }) {};
944
+ /** The admin entry point failed TYPED on the Object; the failure re-decodes verbatim. */
945
+ var AdminFailed = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/AdminFailed")("AdminFailed", { failure: AdminFailure }) {};
946
+ /** The uniform answer of one admin entry point. Callers narrow by the tag their call implies. */
947
+ const AdminResponse = Schema.Union([
948
+ ExplainedRecovery,
949
+ VerifiedIntegrity,
950
+ RetryExecuted,
951
+ ObligationsScanned,
952
+ AdminFailed
953
+ ]);
954
+ const decodeAdminExplainRequest = Schema.decodeUnknownEffect(AdminExplainRequest);
955
+ const decodeAdminVerifyRequest = Schema.decodeUnknownEffect(AdminVerifyRequest);
956
+ const decodeRetryCommand = Schema.decodeUnknownEffect(RetryCommand);
957
+ const decodeObligationThresholds = Schema.decodeUnknownEffect(ObligationThresholds);
958
+ const encodeAdminResponse = Schema.encodeEffect(AdminResponse);
959
+ const decodeAdminResponse = Schema.decodeUnknownEffect(AdminResponse);
960
+ /** Fold one admin endpoint's typed failures into the uniform `AdminResponse` envelope. */
961
+ const respondAdmin = (effect) => effect.pipe(Effect.map((result) => result), Effect.catch((failure) => Effect.succeed(AdminFailed.make({ failure }))));
962
+ /** Encode the admin response envelope; an unencodable response degrades to a protocol failure. */
963
+ const encodeAdminResponseTotal = (response) => encodeAdminResponse(response).pipe(Effect.catch((error) => Effect.succeed({
964
+ _tag: "AdminFailed",
965
+ failure: {
966
+ _tag: "HostProtocolError",
967
+ message: boundHostDiagnostic(`The admin response could not be encoded: ${error.message}`)
968
+ }
969
+ })));
970
+ const explainEndpoint = (encoded) => decodeAdminExplainRequest(encoded).pipe(Effect.mapError(protocolFailure("The explain request could not be decoded")), Effect.flatMap((request) => Effect.gen(function* () {
971
+ const identity = yield* ConversationObjectIdentity;
972
+ const runtime = yield* DurableAgentRuntime;
973
+ const explanations = request.submissionId === void 0 ? yield* runtime.explainConversation(identity.conversationId) : [yield* runtime.explain(request.submissionId)];
974
+ return ExplainedRecovery.make({ explanations });
975
+ })), respondAdmin, Effect.flatMap(encodeAdminResponseTotal));
976
+ const verifyEndpoint = (encoded) => decodeAdminVerifyRequest(encoded).pipe(Effect.mapError(protocolFailure("The verify request could not be decoded")), Effect.flatMap(() => Effect.gen(function* () {
977
+ const identity = yield* ConversationObjectIdentity;
978
+ const report = yield* (yield* DurableAgentRuntime).verify(identity.conversationId);
979
+ return VerifiedIntegrity.make({ report });
980
+ })), respondAdmin, Effect.flatMap(encodeAdminResponseTotal));
981
+ const retryEndpoint = (encoded) => decodeRetryCommand(encoded).pipe(Effect.mapError(protocolFailure("The retry command could not be decoded")), Effect.flatMap((command) => Effect.gen(function* () {
982
+ const maintenance = yield* ConversationMaintenance;
983
+ const runtime = yield* DurableAgentRuntime;
984
+ yield* maintenance.preArm;
985
+ const report = yield* runtime.retry(command);
986
+ return RetryExecuted.make({ report });
987
+ })), respondAdmin, Effect.flatMap(encodeAdminResponseTotal));
988
+ const obligationsEndpoint = (encoded) => decodeObligationThresholds(encoded).pipe(Effect.mapError(protocolFailure("The obligation thresholds could not be decoded")), Effect.flatMap((thresholds) => Effect.gen(function* () {
989
+ const report = yield* (yield* DurableAgentRuntime).scanObligations(thresholds);
990
+ return ObligationsScanned.make({ report });
991
+ })), respondAdmin, Effect.flatMap(encodeAdminResponseTotal));
992
+ /**
993
+ * Owner-side `portCall`: pre-arm before a mutating envelope (a routed admission committed by
994
+ * THIS Object must already carry the alarm that will finish it), execute on the LOCAL facets
995
+ * (never the routed decorators), then arm an immediate alarm so the mutated lane is
996
+ * processed promptly. Protocol anomalies answer `PortFailed(PortProtocolError)`.
997
+ */
998
+ const portCallEndpoint = (encoded) => Effect.gen(function* () {
999
+ const ports = yield* ConversationObjectPorts;
1000
+ const maintenance = yield* ConversationMaintenance;
1001
+ const alarm = yield* DurableAlarmService;
1002
+ const mutating = isMutatingPortRequest(encoded);
1003
+ if (mutating) {
1004
+ if ((yield* maintenance.preArm.pipe(Effect.exit))._tag === "Failure") return encodedPortProtocolFailure("The owner Object could not arm its maintenance alarm before the mutation.");
1005
+ }
1006
+ const response = yield* ports.handle(encoded);
1007
+ if (mutating) yield* alarm.scheduleNow.pipe(Effect.catch((error) => Effect.logWarning("ConversationObject.portCall: immediate re-arm failed", error)));
1008
+ return response;
1009
+ });
1010
+ const wakeEndpoint = Effect.gen(function* () {
1011
+ yield* (yield* DurableAlarmService).scheduleNow.pipe(Effect.catch((error) => Effect.logWarning("ConversationObject.wake dropped", error)));
1012
+ });
1013
+ const alarmEndpoint = Effect.gen(function* () {
1014
+ yield* (yield* ConversationMaintenance).pass;
1015
+ });
1016
+ const gateEndpoint = Effect.gen(function* () {
1017
+ yield* (yield* ConversationMaintenance).ensureAlarm;
1018
+ });
1019
+ /** Build the application's Conversation Object class (export it from the Worker entry). */
1020
+ const makeConversationObjectClass = (options) => {
1021
+ class ConversationObject extends DurableObject {
1022
+ #runtime;
1023
+ constructor(ctx, env) {
1024
+ super(ctx, env);
1025
+ this.#runtime = ManagedRuntime.make(CloudflareDurableRuntime.layer(options).pipe(Layer.provideMerge(Layer.mergeAll(DurableObjectContext.layer(ctx, env), conversationNamespaceLayer(env, options.namespaceBinding)))));
1026
+ ctx.blockConcurrencyWhile(() => this.#runtime.runPromise(gateEndpoint));
1027
+ }
1028
+ async submitEncoded(encoded) {
1029
+ return this.#runtime.runPromise(submitEndpoint(encoded));
1030
+ }
1031
+ async awaitSettlementEncoded(encoded) {
1032
+ return this.#runtime.runPromise(awaitSettlementEndpoint(encoded));
1033
+ }
1034
+ async observePage(encoded) {
1035
+ return this.#runtime.runPromise(observePageEndpoint(encoded));
1036
+ }
1037
+ async abortEncoded(encoded) {
1038
+ return this.#runtime.runPromise(abortEndpoint(encoded));
1039
+ }
1040
+ async resolveApprovalEncoded(encoded) {
1041
+ return this.#runtime.runPromise(resolveApprovalEndpoint(encoded));
1042
+ }
1043
+ async resolveUnknownEncoded(encoded) {
1044
+ return this.#runtime.runPromise(resolveUnknownEndpoint(encoded));
1045
+ }
1046
+ async explainEncoded(encoded) {
1047
+ return this.#runtime.runPromise(explainEndpoint(encoded));
1048
+ }
1049
+ async verifyEncoded(encoded) {
1050
+ return this.#runtime.runPromise(verifyEndpoint(encoded));
1051
+ }
1052
+ async retryEncoded(encoded) {
1053
+ return this.#runtime.runPromise(retryEndpoint(encoded));
1054
+ }
1055
+ async obligationsEncoded(encoded) {
1056
+ return this.#runtime.runPromise(obligationsEndpoint(encoded));
1057
+ }
1058
+ async portCall(encoded) {
1059
+ return this.#runtime.runPromise(portCallEndpoint(encoded));
1060
+ }
1061
+ async wake() {
1062
+ await this.#runtime.runPromise(wakeEndpoint);
1063
+ }
1064
+ async alarm() {
1065
+ await this.#runtime.runPromise(alarmEndpoint);
1066
+ }
1067
+ }
1068
+ return ConversationObject;
1069
+ };
1070
+ //#endregion
1071
+ export { AbortRecorded, AdminExplainRequest, AdminFailed, AdminFailure, AdminResponse, AdminVerifyRequest, AdmissionLimitExceeded, ApprovalRecorded, CLOUDFLARE_DATABASE_CAP_BYTES, CLOUDFLARE_RUNTIME_DEFAULTS, CloudflareAdmissionLimitsValue, CloudflareBindingError, CloudflareConversationClient, CloudflareDurableRuntime, CloudflareDurableRuntimeConfig, CloudflareDurableRuntimeConfigValue, CloudflarePlatformConfigError, ConversationClientError, ConversationMaintenance, ConversationObjectIdentity, ConversationObjectNamespace, ConversationObjectPorts, DEFAULT_MAX_DATABASE_BYTES, DurableAlarmError, DurableAlarmService, DurableObjectContext, ExplainedRecovery, HostFailed, HostFailure, HostProtocolError, HostResponse, MaintenancePassReport, ObligationsScanned, ObservePageRequest, ObservedPage, RetryExecuted, SettlementReached, SubmitRequest, SubmitSucceeded, UnknownResolutionRecorded, VerifiedIntegrity, boundHostDiagnostic, cloudflareWakeSchedulerLayer, conversationNamespaceFromEnv, conversationNamespaceLayer, conversationPortTransportLayer, decodeAbortCommand, decodeAdminExplainRequest, decodeAdminResponse, decodeAdminVerifyRequest, decodeApprovalDecisionCommand, decodeHostResponse, decodeObligationThresholds, decodeObservePageRequest, decodeReceipt, decodeRetryCommand, decodeSubmitRequest, decodeUnknownResolutionCommand, encodeAbortCommand, encodeAdminResponse, encodeApprovalDecisionCommand, encodeHostResponse, encodeObservePageRequest, encodeReceipt, encodeSubmitRequest, encodeUnknownResolutionCommand, makeConversationObjectClass };
1072
+
1073
+ //# sourceMappingURL=index.mjs.map