@effect-agent/platform-cloudflare 0.1.0-beta.9 → 0.1.0-beta.91

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/dist/Alarm.d.mts +188 -0
  2. package/dist/Alarm.mjs +451 -0
  3. package/dist/Alarm.mjs.map +1 -0
  4. package/dist/BrowserRestCapture.d.mts +35 -0
  5. package/dist/BrowserRestCapture.mjs +238 -0
  6. package/dist/BrowserRestCapture.mjs.map +1 -0
  7. package/dist/BrowserRestCrawl.d.mts +17 -0
  8. package/dist/BrowserRestCrawl.mjs +244 -0
  9. package/dist/BrowserRestCrawl.mjs.map +1 -0
  10. package/dist/CloudflareAiGateway.d.mts +64 -0
  11. package/dist/CloudflareAiGateway.mjs +70 -0
  12. package/dist/CloudflareAiGateway.mjs.map +1 -0
  13. package/dist/CloudflareBindings.d.mts +115 -0
  14. package/dist/CloudflareBindings.mjs +113 -0
  15. package/dist/CloudflareBindings.mjs.map +1 -0
  16. package/dist/CloudflareBrowser-DV6kya1H.mjs +495 -0
  17. package/dist/CloudflareBrowser-DV6kya1H.mjs.map +1 -0
  18. package/dist/CloudflareBrowser-Doe1M7R5.d.mts +80 -0
  19. package/dist/CloudflareBrowser.d.mts +2 -0
  20. package/dist/CloudflareBrowser.mjs +2 -0
  21. package/dist/CloudflareCodeMode.d.mts +44 -0
  22. package/dist/CloudflareCodeMode.mjs +616 -0
  23. package/dist/CloudflareCodeMode.mjs.map +1 -0
  24. package/dist/CloudflareConfig-f3CqTel1.d.mts +101 -0
  25. package/dist/CloudflareConfig.d.mts +2 -0
  26. package/dist/CloudflareConfig.mjs +122 -0
  27. package/dist/CloudflareConfig.mjs.map +1 -0
  28. package/dist/CloudflareMemory.d.mts +142 -0
  29. package/dist/CloudflareMemory.mjs +202 -0
  30. package/dist/CloudflareMemory.mjs.map +1 -0
  31. package/dist/CloudflareScheduling.d.mts +52 -0
  32. package/dist/CloudflareScheduling.mjs +396 -0
  33. package/dist/CloudflareScheduling.mjs.map +1 -0
  34. package/dist/CloudflareSubscriptions.d.mts +87 -0
  35. package/dist/CloudflareSubscriptions.mjs +530 -0
  36. package/dist/CloudflareSubscriptions.mjs.map +1 -0
  37. package/dist/CloudflareThreadClient.d.mts +1496 -0
  38. package/dist/CloudflareThreadClient.mjs +382 -0
  39. package/dist/CloudflareThreadClient.mjs.map +1 -0
  40. package/dist/InteractiveBrowser-DUE_m12-.d.mts +161 -0
  41. package/dist/InteractiveBrowser-DupDtfw2.mjs +1169 -0
  42. package/dist/InteractiveBrowser-DupDtfw2.mjs.map +1 -0
  43. package/dist/InteractiveBrowser.d.mts +2 -0
  44. package/dist/InteractiveBrowser.mjs +2 -0
  45. package/dist/ProtectedBrowser.d.mts +123 -0
  46. package/dist/ProtectedBrowser.mjs +1135 -0
  47. package/dist/ProtectedBrowser.mjs.map +1 -0
  48. package/dist/ThreadObject-CIbmXZCY.d.mts +812 -0
  49. package/dist/ThreadObject-DvRG0dDz.mjs +835 -0
  50. package/dist/ThreadObject-DvRG0dDz.mjs.map +1 -0
  51. package/dist/ThreadObject.d.mts +2 -0
  52. package/dist/ThreadObject.mjs +3 -0
  53. package/dist/WakeScheduler.d.mts +23 -0
  54. package/dist/WakeScheduler.mjs +57 -0
  55. package/dist/WakeScheduler.mjs.map +1 -0
  56. package/dist/boundary-BguazVkh.mjs +42 -0
  57. package/dist/boundary-BguazVkh.mjs.map +1 -0
  58. package/dist/index.d.mts +13 -1548
  59. package/dist/index.mjs +13 -1636
  60. package/dist/prepared-admission-DU0_T-ev.mjs +73 -0
  61. package/dist/prepared-admission-DU0_T-ev.mjs.map +1 -0
  62. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  63. package/package.json +1 -53
  64. package/src/Alarm.ts +973 -0
  65. package/src/BrowserRestCapture.ts +477 -0
  66. package/src/BrowserRestCrawl.ts +540 -0
  67. package/src/CloudflareAiGateway.ts +170 -0
  68. package/src/CloudflareBindings.ts +199 -0
  69. package/src/CloudflareBrowser.ts +15 -0
  70. package/src/{code-mode-executor.ts → CloudflareCodeMode.ts} +372 -204
  71. package/src/{config.ts → CloudflareConfig.ts} +9 -8
  72. package/src/CloudflareMemory.ts +420 -0
  73. package/src/CloudflareScheduling.ts +747 -0
  74. package/src/CloudflareSubscriptions.ts +1041 -0
  75. package/src/CloudflareThreadClient.ts +809 -0
  76. package/src/InteractiveBrowser.ts +2354 -0
  77. package/src/ProtectedBrowser.ts +9 -0
  78. package/src/ThreadObject.ts +1179 -0
  79. package/src/{wake-scheduler.ts → WakeScheduler.ts} +32 -26
  80. package/src/index.ts +12 -23
  81. package/src/internal/boundary.ts +55 -0
  82. package/src/internal/browser-quick-action.ts +857 -0
  83. package/src/internal/browser-session-lifecycle.ts +160 -0
  84. package/src/internal/layers.ts +751 -0
  85. package/src/internal/message-delivery.ts +152 -0
  86. package/src/internal/prepared-admission.ts +116 -0
  87. package/src/internal/progress-wait.ts +121 -0
  88. package/src/internal/transport.ts +44 -0
  89. package/src/protected-browser/binding.ts +313 -0
  90. package/src/protected-browser/host.ts +344 -0
  91. package/src/protected-browser/inspect-frame.ts +125 -0
  92. package/src/protected-browser/native.ts +445 -0
  93. package/src/protected-browser/policy.ts +821 -0
  94. package/dist/index.mjs.map +0 -1
  95. package/src/alarm.ts +0 -334
  96. package/src/bindings.ts +0 -145
  97. package/src/client.ts +0 -646
  98. package/src/conversation-object.ts +0 -768
  99. package/src/layers.ts +0 -376
  100. package/src/transport.ts +0 -38
package/dist/index.mjs CHANGED
@@ -1,1636 +1,13 @@
1
- import { Clock, Context, Duration, Effect, Fiber, Layer, 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, DurableObjectState, WorkerEnvironment } from "effect-cf";
8
- import { CodeExecutionHost, CodeExecutionProtocolError, CodeExecutionResourceUse, CodeExecutionResult, CodeExecutionTimeoutError, CodeExecutor, CodeExecutorStartError, CodeExecutorTerminatedError, CodeExecutorUnsupportedError, CodeHostCall, CodeHostCallLimitError, CodeOutputLimitError, CodeProgramFailedError, CodeSourceError, SandboxImplementation } from "@effect-agent/sandbox";
9
- import { WorkerEntrypoint } from "cloudflare:workers";
10
- //#region src/bindings.ts
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
- var CloudflareBindingError = class extends Schema.TaggedError()("CloudflareBindingError", {
19
- binding: Schema.String,
20
- message: Schema.String
21
- }) {};
22
- /**
23
- * The `DurableObjectNamespace` binding that addresses Conversation Objects. The Object
24
- * identity rule is `namespace.idFromName(conversationId)` (plan §1.2): Conversation IDs are
25
- * globally unique, so the mapping is total and deterministic and no directory service exists.
26
- */
27
- var ConversationObjectNamespace = class ConversationObjectNamespace extends Context.Service()("@effect-agent/platform-cloudflare/ConversationObjectNamespace") {
28
- static layer(namespace) {
29
- return Layer.succeed(ConversationObjectNamespace)({ namespace });
30
- }
31
- };
32
- /**
33
- * Narrow one `env` member to a `DurableObjectNamespace`. `env` is an untyped platform value,
34
- * and a namespace binding is a host object no Schema can decode, so this is the documented
35
- * narrowest-boundary check (structural probe for the namespace surface the transport uses);
36
- * a missing or misshaped binding fails typed before any Layer is built.
37
- */
38
- const conversationNamespaceFromEnv = (env, binding) => Effect.suspend(() => {
39
- if (typeof env !== "object" || env === null) return Effect.fail(CloudflareBindingError.make({
40
- binding,
41
- message: "The Worker environment is not an object; no bindings are available."
42
- }));
43
- const candidate = env[binding];
44
- if (typeof candidate === "object" && candidate !== null && "idFromName" in candidate && typeof candidate.idFromName === "function" && "get" in candidate && typeof candidate.get === "function") return Effect.succeed(candidate);
45
- return Effect.fail(CloudflareBindingError.make({
46
- binding,
47
- message: `env.${binding} is not a DurableObjectNamespace binding; declare the Conversation Object class under this binding in the Worker configuration.`
48
- }));
49
- });
50
- /** `ConversationObjectNamespace` built from the untyped Worker `env` (fails typed). */
51
- const conversationNamespaceLayer = (env, binding) => Layer.effect(ConversationObjectNamespace)(Effect.map(conversationNamespaceFromEnv(env, binding), (namespace) => ({ namespace })));
52
- /**
53
- * The live Durable Object execution context of THIS incarnation. Only Layer construction and
54
- * the alarm service consume it; important state never lives on it (`ctx.storage` is truth,
55
- * everything in memory is a cache — deployment spec §11).
56
- */
57
- var DurableObjectContext = class DurableObjectContext extends Context.Service()("@effect-agent/platform-cloudflare/DurableObjectContext") {
58
- static layer(ctx, env) {
59
- return Layer.succeed(DurableObjectContext)({
60
- ctx,
61
- env
62
- });
63
- }
64
- };
65
- /**
66
- * The Conversation identity this Object serializes and the producer identity its Attempts
67
- * write with (`{producerPrefix}:{conversationId}`, plan §1.4). Derived once per incarnation
68
- * from `ctx.id.name` — the Object identity rule guarantees the name IS the Conversation ID.
69
- */
70
- var ConversationObjectIdentity = class extends Context.Service()("@effect-agent/platform-cloudflare/ConversationObjectIdentity") {};
71
- //#endregion
72
- //#region src/config.ts
73
- /**
74
- * Schema-validated configuration for the Cloudflare durable runtime (deployment spec §4:
75
- * decoded once during Layer construction, exposed as a typed service; DEPLOY-003). Every
76
- * cadence is in milliseconds; every bound is finite and checked before any resource opens.
77
- */
78
- const PositiveMillis = Schema.Int.check(Schema.isGreaterThan(0));
79
- const NonNegativeMillis = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
80
- /** The supplied Cloudflare durable runtime configuration failed validation (DEPLOY-003). */
81
- var CloudflarePlatformConfigError = class extends Schema.TaggedError()("CloudflarePlatformConfigError", {
82
- message: Schema.String,
83
- cause: Schema.optionalKey(Schema.Defect())
84
- }) {};
85
- /**
86
- * An admission was refused by a host resource limit BEFORE any ledger row existed
87
- * (deployment spec §8, DEPLOY-007: "Admission has explicit bounded quota and overload
88
- * behavior... a typed rejection"). This is the DC analogue of `NodeDurableHost`'s
89
- * `AdmissionClosed` host gate: the port surface stays untouched, the refusal happens in the
90
- * Conversation Object's submit entry point before `DurableAgentRuntime.submit` runs, and
91
- * nothing was admitted or written.
92
- */
93
- var AdmissionLimitExceeded = class extends Schema.TaggedError()("AdmissionLimitExceeded", {
94
- limit: Schema.Literals([
95
- "queue-depth",
96
- "input-bytes",
97
- "database-bytes"
98
- ]),
99
- actual: Schema.Int,
100
- maximum: Schema.Int
101
- }) {
102
- get message() {
103
- 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).`;
104
- }
105
- };
106
- /** The platform's hard per-Object database cap (10 GB, developers.cloudflare.com limits). */
107
- const CLOUDFLARE_DATABASE_CAP_BYTES = 1e10;
108
- /** Default database-size admission ceiling: a 1 GB safety margin under the platform cap. */
109
- const DEFAULT_MAX_DATABASE_BYTES = 9e9;
110
- /**
111
- * Explicit bounded admission quotas checked by the Conversation Object BEFORE admission
112
- * (exit gate "resource limits are checked before admission").
113
- */
114
- var CloudflareAdmissionLimitsValue = class extends Schema.Class("@effect-agent/platform-cloudflare/CloudflareAdmissionLimitsValue")({
115
- /** Maximum nonterminal Submissions per Conversation lane before new admissions refuse. */
116
- maxQueueDepthPerLane: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1e5)),
117
- /** Maximum encoded input bytes; never above the storage per-value bound. */
118
- maxInputBytes: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(2e6)),
119
- /** Maximum `ctx.storage.sql.databaseSize` at admission; stays under the 10 GB platform cap. */
120
- maxDatabaseBytes: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(CLOUDFLARE_DATABASE_CAP_BYTES))
121
- }) {};
122
- /**
123
- * Validated Cloudflare durable runtime configuration. The producer identity of one
124
- * Conversation Object is `{producerPrefix}:{conversationId}` — stable across incarnations of
125
- * the same deployment, distinct across deployments — and producer-epoch fencing (not the
126
- * producer name) remains the correctness authority (DUR-006).
127
- */
128
- var CloudflareDurableRuntimeConfigValue = class extends Schema.Class("@effect-agent/platform-cloudflare/CloudflareDurableRuntimeConfigValue")({
129
- deploymentId: DeploymentId,
130
- /** Head of the minted producer identity `{producerPrefix}:{conversationId}`. */
131
- producerPrefix: Schema.NonEmptyString.check(Schema.isMaxLength(256)),
132
- /** Submission ownership lease duration (D5); fences work across Object incarnations. */
133
- ownershipLeaseDuration: PositiveMillis,
134
- /** Base delay of the alarm re-arm backoff when a pass makes no progress. */
135
- alarmBackoffBase: PositiveMillis,
136
- /** Ceiling of the alarm re-arm backoff. */
137
- alarmBackoffCap: PositiveMillis,
138
- /**
139
- * The maintenance-pass scan cadence and the ceiling of every re-arm delay: nonterminal
140
- * work is revisited at least this often (wake/scan pairing, persistence §14).
141
- */
142
- wakeScanInterval: PositiveMillis,
143
- /** `awaitSettlement` ledger re-check cadence when no wake arrives. */
144
- settlementPollInterval: PositiveMillis,
145
- /** Worker ownership-lease renewal cadence during an active Attempt. */
146
- leaseRenewalInterval: PositiveMillis,
147
- /** Active-Run abort-intent poll cadence. */
148
- abortPollInterval: PositiveMillis,
149
- /** Canonical observation poll cadence of the Durable Object store. */
150
- observationPollInterval: NonNegativeMillis,
151
- /** Per-value byte bound; must stay under the platform's 2 MB SQLite value limit. */
152
- maxStoredValueBytes: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(2e6)),
153
- /** Opt-in full payload/digest-chain audit while opening the store. */
154
- verifyOnOpen: Schema.Boolean,
155
- limits: CloudflareAdmissionLimitsValue
156
- }) {};
157
- /** Explicit configuration authority for the assembled Cloudflare durable runtime. */
158
- var CloudflareDurableRuntimeConfig = class extends Context.Service()("@effect-agent/platform-cloudflare/CloudflareDurableRuntimeConfig") {};
159
- /** Documented production defaults applied by `CloudflareDurableRuntime.layer`. */
160
- const CLOUDFLARE_RUNTIME_DEFAULTS = {
161
- ownershipLeaseDuration: Duration.toMillis(DEFAULT_OWNERSHIP_LEASE_DURATION),
162
- alarmBackoffBase: 100,
163
- alarmBackoffCap: 5e3,
164
- wakeScanInterval: 1e3,
165
- settlementPollInterval: 500,
166
- leaseRenewalInterval: 1e4,
167
- abortPollInterval: 500,
168
- observationPollInterval: 25,
169
- maxStoredValueBytes: DEFAULT_MAX_STORED_VALUE_BYTES,
170
- verifyOnOpen: false,
171
- maxQueueDepthPerLane: 256,
172
- maxInputBytes: DEFAULT_MAX_STORED_VALUE_BYTES,
173
- maxDatabaseBytes: DEFAULT_MAX_DATABASE_BYTES
174
- };
175
- //#endregion
176
- //#region src/alarm.ts
177
- /**
178
- * The single multiplexed Durable Object alarm (decision D-P6-2). A Durable Object has ONE
179
- * alarm slot; every cadence the Node host ran on fibers (wake scan, lease expiry, settlement
180
- * and abort re-checks, retry backoff) multiplexes into one idempotent maintenance pass, and
181
- * the slot always holds the EARLIEST deadline any caller asked for.
182
- *
183
- * The alarm invariant (plan §1.4): committed nonterminal work implies a committed alarm.
184
- * It is established by pre-arming — every mutating entry point and every pass arms the alarm
185
- * BEFORE its durable mutations — so an eviction at any failpoint leaves a persisted alarm
186
- * that workerd re-delivers to a fresh incarnation WITHOUT any incoming request. Spurious
187
- * alarms are harmless by design: a pass over an all-settled lane simply deletes the slot.
188
- */
189
- /** The Durable Object alarm API failed; surfaces on host entry points as a typed refusal. */
190
- var DurableAlarmError = class extends Schema.TaggedError()("DurableAlarmError", {
191
- operation: Schema.String,
192
- message: Schema.String,
193
- cause: Schema.optionalKey(Schema.Defect())
194
- }) {};
195
- const alarmFailure = (operation) => (cause) => DurableAlarmError.make({
196
- operation,
197
- message: cause instanceof Error ? cause.message : String(cause),
198
- cause
199
- });
200
- /** `ctx.storage` alarm slot as an Effect service; storage is truth, never a memory field. */
201
- var DurableAlarmService = class DurableAlarmService extends Context.Service()("@effect-agent/platform-cloudflare/DurableAlarmService") {
202
- static layer = Layer.effect(DurableAlarmService)(Effect.gen(function* () {
203
- const { ctx } = yield* DurableObjectContext;
204
- /**
205
- * In-memory pass bookkeeping — a pure CACHE, never state: a fresh incarnation has no
206
- * running pass, and a deferred wake lost to eviction was only ever a promptness hint
207
- * on top of the already-committed pre-armed alarm.
208
- */
209
- const runningPasses = yield* Ref.make(0);
210
- const wakeDeferred = yield* Ref.make(false);
211
- const scheduled = Effect.tryPromise({
212
- try: () => ctx.storage.getAlarm(),
213
- catch: alarmFailure("get alarm")
214
- }).pipe(Effect.map((deadline) => deadline === null ? Option.none() : Option.some(deadline)));
215
- const scheduleAt = (epochMillis) => Effect.tryPromise({
216
- try: () => ctx.storage.setAlarm(epochMillis),
217
- catch: alarmFailure("set alarm")
218
- });
219
- const ensureScheduledBy = (epochMillis) => scheduled.pipe(Effect.flatMap((existing) => Option.isSome(existing) && existing.value <= epochMillis ? Effect.void : scheduleAt(epochMillis)));
220
- const armNow = Clock.currentTimeMillis.pipe(Effect.flatMap((now) => ensureScheduledBy(now)));
221
- const scheduleNow = Ref.get(runningPasses).pipe(Effect.flatMap((passes) => passes > 0 ? Ref.set(wakeDeferred, true) : armNow));
222
- /**
223
- * Flush after the LAST concurrent pass: the re-arm lands at the very end of the alarm
224
- * handler, where a superseding cancellation only re-delivers to the already-idempotent
225
- * pass. Runs inside `Effect.ensuring`, so flush failures are logged, never raised.
226
- */
227
- 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)));
228
- 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))));
229
- const cancel = Effect.tryPromise({
230
- try: () => ctx.storage.deleteAlarm(),
231
- catch: alarmFailure("delete alarm")
232
- });
233
- return DurableAlarmService.of({
234
- scheduled,
235
- scheduleAt,
236
- ensureScheduledBy,
237
- scheduleNow,
238
- withWakesDeferred,
239
- cancel
240
- });
241
- }));
242
- };
243
- /** What one maintenance pass did — auditable evidence mirroring `NodeDurableHost`'s report. */
244
- var MaintenancePassReport = class extends Schema.Class("@effect-agent/platform-cloudflare/MaintenancePassReport")({
245
- /** Recovery decisions executed (or deferred) BEFORE any new claim in this pass. */
246
- recovered: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
247
- /** Settlements the drain pass finalized. */
248
- settled: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
249
- /** Submissions still nonterminal after the pass (suspended/unknown lanes stay honest). */
250
- nonterminal: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
251
- /** `rearmed` while nonterminal work remains, `cleared` once everything settled. */
252
- alarm: Schema.Literals(["rearmed", "cleared"])
253
- }) {};
254
- /**
255
- * The idempotent maintenance pass and the alarm-invariant helpers (plan §1.4, D-P6-1/2).
256
- *
257
- * `pass` = pre-arm → `runRecovery` → `processConversationResolved` → re-arm-or-clear:
258
- *
259
- * 1. **Pre-arm**: the alarm is re-armed at `now + wakeScanInterval` BEFORE any work, so an
260
- * eviction (or thrown failure → workerd alarm retry) at any point of the pass leaves a
261
- * committed alarm and the fresh incarnation converges without an incoming request.
262
- * 2. **Reconcile before new work** (exit gate): every pass classifies and repairs every
263
- * nonterminal Submission before the drain claims anything; the pure classifier and the
264
- * repair executors are idempotent, so at-least-once alarm delivery re-runs them safely.
265
- * 3. **Drain**: one bounded `processConversationResolved` pass over this Object's lane — the
266
- * D-P6-1 shape; no infinite `runResolvedWorker` loop ever pins the Object.
267
- * 4. **Re-arm policy**: nonterminal work re-arms at `now + min(backoff-with-jitter,
268
- * wakeScanInterval)` — the scan interval bounds every wait (lease expiry of a dead
269
- * incarnation included, since claims retry each pass) and the backoff (reset on progress,
270
- * grown otherwise) keeps stuck lanes from busy-spinning; all settled clears the slot.
271
- *
272
- * Every step is a durability-protocol step that already tolerates re-execution, which is
273
- * what makes double-fired alarms harmless (the alarm.test.ts gate).
274
- */
275
- var ConversationMaintenance = class ConversationMaintenance extends Context.Service()("@effect-agent/platform-cloudflare/ConversationMaintenance") {
276
- static layer = Layer.effect(ConversationMaintenance)(Effect.gen(function* () {
277
- const runtime = yield* DurableAgentRuntime;
278
- const resolver = yield* AgentBindingResolver;
279
- const ledger = yield* SubmissionLedger;
280
- const alarm = yield* DurableAlarmService;
281
- const config = yield* CloudflareDurableRuntimeConfig;
282
- const identity = yield* ConversationObjectIdentity;
283
- /**
284
- * Consecutive no-progress passes — an in-memory CACHE, not state: a fresh incarnation
285
- * restarts at zero and merely re-arms sooner than a long-lived one would have.
286
- */
287
- const stalls = yield* Ref.make(0);
288
- const preArm = Clock.currentTimeMillis.pipe(Effect.flatMap((now) => alarm.ensureScheduledBy(now + config.wakeScanInterval)));
289
- const countNonterminal = Stream.runCollect(ledger.scanNonterminal).pipe(Effect.map((snapshots) => snapshots.length));
290
- const rearmDelay = Effect.fn("ConversationMaintenance.rearmDelay")(function* (progressed) {
291
- const priorStalls = yield* Ref.getAndUpdate(stalls, (count) => progressed ? 0 : count + 1);
292
- if (progressed) return config.alarmBackoffBase;
293
- const exponent = Math.min(priorStalls, 30);
294
- const backoff = Math.min(config.alarmBackoffCap, config.alarmBackoffBase * 2 ** exponent);
295
- const jitter = yield* Random.next;
296
- const jittered = Math.ceil(backoff / 2 + backoff / 2 * jitter);
297
- return Math.min(jittered, config.wakeScanInterval);
298
- });
299
- const pass = Effect.fn("ConversationMaintenance.pass")(function* () {
300
- yield* preArm;
301
- const recovered = yield* runtime.runRecovery;
302
- const settlements = yield* runtime.processConversationResolved(identity.conversationId).pipe(Effect.provideService(AgentBindingResolver, resolver));
303
- const nonterminal = yield* countNonterminal;
304
- if (nonterminal === 0) {
305
- yield* alarm.cancel;
306
- yield* Ref.set(stalls, 0);
307
- const appeared = yield* countNonterminal;
308
- if (appeared > 0) {
309
- yield* preArm;
310
- return MaintenancePassReport.make({
311
- recovered: recovered.length,
312
- settled: settlements.length,
313
- nonterminal: appeared,
314
- alarm: "rearmed"
315
- });
316
- }
317
- return MaintenancePassReport.make({
318
- recovered: recovered.length,
319
- settled: settlements.length,
320
- nonterminal,
321
- alarm: "cleared"
322
- });
323
- }
324
- const progressed = settlements.length > 0 || recovered.some((report) => report.disposition === "repaired");
325
- const delay = yield* rearmDelay(progressed);
326
- const now = yield* Clock.currentTimeMillis;
327
- yield* alarm.ensureScheduledBy(now + delay);
328
- return MaintenancePassReport.make({
329
- recovered: recovered.length,
330
- settled: settlements.length,
331
- nonterminal,
332
- alarm: "rearmed"
333
- });
334
- });
335
- const ensureAlarm = Effect.fn("ConversationMaintenance.ensureAlarm")(function* () {
336
- if ((yield* countNonterminal) === 0) return;
337
- yield* preArm;
338
- });
339
- return ConversationMaintenance.of({
340
- pass: alarm.withWakesDeferred(pass()),
341
- ensureAlarm: ensureAlarm(),
342
- preArm
343
- });
344
- }));
345
- };
346
- //#endregion
347
- //#region src/wake-scheduler.ts
348
- /**
349
- * Bounded in-memory wake buffer for same-incarnation `awaitSettlement` subscribers. Wake
350
- * hints are droppable by contract (consumers pair every subscription with ledger polls), so
351
- * a full buffer slides out the oldest hint and an eviction simply loses the buffer — the
352
- * poll interval and the persisted alarm keep liveness (persistence §14).
353
- */
354
- const WAKE_BUFFER_CAPACITY = 1024;
355
- /** A remote wake stub call failed; always swallowed and logged (hints are droppable). */
356
- var RemoteWakeDropped = class extends Schema.TaggedError()("RemoteWakeDropped", {
357
- conversationId: Schema.String,
358
- message: Schema.String,
359
- cause: Schema.optionalKey(Schema.Defect())
360
- }) {};
361
- /**
362
- * The DC `WakeScheduler` (plan §1.4):
363
- *
364
- * - `notify(local)` → `setAlarm(now)` — durable, cheap, coalescing (the alarm slot keeps the
365
- * earliest deadline) — plus a same-incarnation PubSub hint for `awaitSettlement` waiters.
366
- * - `notify(remote)` → fire-and-forget `wake()` on the owning Object's stub with every error
367
- * swallowed and logged: hints are droppable, and the target's own alarm/scan pairing (the
368
- * maintenance pass re-polls unsettled children) guarantees liveness without this call.
369
- * - `wakes` → the bounded sliding PubSub only. No important state lives in memory: the
370
- * subscription accelerates waiters within one incarnation and the settlement poll interval
371
- * is the correctness path.
372
- */
373
- const cloudflareWakeSchedulerLayer = Layer.effect(WakeScheduler)(Effect.gen(function* () {
374
- const alarm = yield* DurableAlarmService;
375
- const identity = yield* ConversationObjectIdentity;
376
- const { namespace } = yield* ConversationObjectNamespace;
377
- const hints = yield* PubSub.sliding(WAKE_BUFFER_CAPACITY);
378
- yield* Effect.addFinalizer(() => PubSub.shutdown(hints));
379
- 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);
380
- const notifyRemote = (conversationId) => Effect.tryPromise({
381
- try: () => namespace.get(namespace.idFromName(conversationId)).wake(),
382
- catch: (cause) => RemoteWakeDropped.make({
383
- conversationId,
384
- message: cause instanceof Error ? cause.message : String(cause),
385
- cause
386
- })
387
- }).pipe(Effect.catch((error) => Effect.logWarning(`CloudflareWakeScheduler: remote wake of ${conversationId} dropped`, error)), Effect.asVoid);
388
- return WakeScheduler.of({
389
- notify: (conversationId) => conversationId === identity.conversationId ? notifyLocal(conversationId) : notifyRemote(conversationId),
390
- wakes: Stream.fromPubSub(hints)
391
- });
392
- }));
393
- //#endregion
394
- //#region src/transport.ts
395
- /**
396
- * `ConversationPortTransport` over native Durable Object JS RPC (decision D-P6-3): one
397
- * `portCall(envelope)` on the stub of the Object that owns the addressed Conversation
398
- * (`namespace.idFromName(conversationId)` — the identity rule, plan §1.2). The envelopes are
399
- * already Schema-encoded JSON, so the RPC boundary carries only structured-cloneable values;
400
- * the protocol module stays transport-agnostic and fetch-with-JSON remains the documented
401
- * fallback carrier.
402
- *
403
- * Every delivery problem — stub construction, RPC rejection, overload, deploy-in-progress —
404
- * surfaces as `PortTransportError` (preserving the platform stub's own `retryable` signal
405
- * when present) and NEVER as a fabricated answer: on `resolveAdmission` the routing layer
406
- * turns exactly this error into `AdmissionIndeterminate` (SUB-031).
407
- */
408
- const conversationPortTransportLayer = Layer.effect(ConversationPortTransport)(Effect.gen(function* () {
409
- const { namespace } = yield* ConversationObjectNamespace;
410
- return ConversationPortTransport.of({ call: (conversationId, request) => Effect.tryPromise({
411
- try: () => namespace.get(namespace.idFromName(conversationId)).portCall(request),
412
- catch: (cause) => portTransportFailure(conversationId, cause)
413
- }).pipe(Effect.withSpan("CloudflarePortTransport.call", { attributes: { conversationId } })) });
414
- }));
415
- //#endregion
416
- //#region src/layers.ts
417
- /**
418
- * Owner-side endpoint body for the Conversation Object's `portCall` (plan §1.3): decode,
419
- * execute against THIS Object's LOCAL port facets — never the routed decorators, so a
420
- * request cannot bounce between Objects — and answer the encoded response envelope. Total by
421
- * construction (protocol anomalies answer `PortFailed(PortProtocolError)`).
422
- */
423
- var ConversationObjectPorts = class extends Context.Service()("@effect-agent/platform-cloudflare/ConversationObjectPorts") {};
424
- const decodeConfigValue = Schema.decodeUnknownEffect(CloudflareDurableRuntimeConfigValue);
425
- const decodeConversationId = Schema.decodeUnknownEffect(ConversationId);
426
- const decodeProducerId = Schema.decodeUnknownEffect(ProducerId);
427
- const configFromOptions = (options) => decodeConfigValue({
428
- deploymentId: options.deploymentId,
429
- producerPrefix: options.producerPrefix,
430
- ownershipLeaseDuration: options.ownershipLeaseDuration ?? CLOUDFLARE_RUNTIME_DEFAULTS.ownershipLeaseDuration,
431
- alarmBackoffBase: options.alarmBackoffBase ?? CLOUDFLARE_RUNTIME_DEFAULTS.alarmBackoffBase,
432
- alarmBackoffCap: options.alarmBackoffCap ?? CLOUDFLARE_RUNTIME_DEFAULTS.alarmBackoffCap,
433
- wakeScanInterval: options.wakeScanInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.wakeScanInterval,
434
- settlementPollInterval: options.settlementPollInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.settlementPollInterval,
435
- leaseRenewalInterval: options.leaseRenewalInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.leaseRenewalInterval,
436
- abortPollInterval: options.abortPollInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.abortPollInterval,
437
- observationPollInterval: options.observationPollInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.observationPollInterval,
438
- maxStoredValueBytes: options.maxStoredValueBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxStoredValueBytes,
439
- verifyOnOpen: options.verifyOnOpen ?? CLOUDFLARE_RUNTIME_DEFAULTS.verifyOnOpen,
440
- limits: {
441
- maxQueueDepthPerLane: options.maxQueueDepthPerLane ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxQueueDepthPerLane,
442
- maxInputBytes: Math.min(options.maxInputBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxInputBytes, options.maxStoredValueBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxStoredValueBytes),
443
- maxDatabaseBytes: options.maxDatabaseBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxDatabaseBytes
444
- }
445
- }).pipe(Effect.mapError((error) => CloudflarePlatformConfigError.make({
446
- message: `Invalid Cloudflare durable runtime configuration: ${error.message}`,
447
- cause: error
448
- })));
449
- /**
450
- * The Conversation this Object owns, from the Object identity rule (plan §1.2): Conversation
451
- * Objects are addressed exclusively by `idFromName(conversationId)`, so `ctx.id.name` IS the
452
- * Conversation ID. An unnamed Object (from `newUniqueId`) is a deployment error, not a lane.
453
- */
454
- 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({
455
- message: `The Durable Object name is not a valid ConversationId: ${error.message}`,
456
- cause: error
457
- })));
458
- const resolveBindings = (source, context) => source === void 0 ? Effect.succeed([]) : Effect.isEffect(source) ? source : typeof source === "function" ? Effect.suspend(() => {
459
- const bindings = source(context);
460
- return Effect.isEffect(bindings) ? bindings : Effect.succeed(bindings);
461
- }) : Effect.succeed(source);
462
- /**
463
- * The DC Layer assembly (deployment §12: a Layer-assembly library, not an app entrypoint;
464
- * plan §1.4). `layer(options)` decodes the configuration, derives this Object's Conversation
465
- * and producer identities, opens the Object's private SQLite database through
466
- * `@effect/sql-sqlite-do` for BOTH the Conversation Log and the Submission Ledger (so claims
467
- * fence the same producer epochs — ADR-0011 D7 transposed), wraps the local port facets with
468
- * the WP2 cross-Object routing decorators over the Durable Object RPC transport, wires the
469
- * alarm-backed wake scheduler and the maintenance pass, defaults reconciliation to the
470
- * fail-closed `ToolReconciler.uncertain`, and provides a ready `DurableAgentRuntime` on top.
471
- *
472
- * Storage compatibility is verified during construction: an incompatible database fails the
473
- * Layer typed (`DoStorageCompatibilityError`) before anything is mutated (DEPLOY-008).
474
- *
475
- * Requires only the two binding services (`DurableObjectContext`,
476
- * `ConversationObjectNamespace`) — platform values enter exclusively through Layers
477
- * (DEPLOY-010).
478
- */
479
- var CloudflareDurableRuntime = class {
480
- static layer(options) {
481
- return Layer.unwrap(Effect.gen(function* () {
482
- const { ctx, env } = yield* DurableObjectContext;
483
- const config = yield* configFromOptions(options);
484
- const conversationId = yield* conversationIdFromState(ctx);
485
- const producerId = yield* decodeProducerId(`${config.producerPrefix}:${conversationId}`).pipe(Effect.mapError((error) => CloudflarePlatformConfigError.make({
486
- message: `The minted producer identity is invalid: ${error.message}`,
487
- cause: error
488
- })));
489
- const identityLayer = Layer.succeed(ConversationObjectIdentity)({
490
- conversationId,
491
- producerId
492
- });
493
- const cloudflareConfigLayer = Layer.succeed(CloudflareDurableRuntimeConfig)(config);
494
- const storageOptions = {
495
- storage: ctx.storage,
496
- observationPollInterval: config.observationPollInterval,
497
- ownershipLeaseDuration: config.ownershipLeaseDuration,
498
- maxStoredValueBytes: config.maxStoredValueBytes,
499
- verifyOnOpen: config.verifyOnOpen,
500
- failpoint: options.storageFailpoint?.(ctx)
501
- };
502
- const infrastructure = Layer.mergeAll(storageConfigLayer(storageOptions), storageFailpointLayer(storageOptions), SqliteClient.layer({ storage: ctx.storage }), BrowserCrypto.layer);
503
- /**
504
- * ONE local-facet instance (a shared Layer value) serves both the routed decorators
505
- * and the owner-side `portCall` executor — the executor must never see the routed
506
- * ports (plan §1.3: re-routing could bounce a request between Objects).
507
- */
508
- const localPorts = Layer.mergeAll(conversationStoreLayer, submissionLedgerLayer).pipe(Layer.provide(infrastructure));
509
- const portsEndpointLayer = Layer.effect(ConversationObjectPorts)(Effect.gen(function* () {
510
- const local = yield* Effect.context();
511
- return ConversationObjectPorts.of({ handle: (encoded) => handleEncodedPortRequest(encoded).pipe(Effect.provide(local)) });
512
- })).pipe(Layer.provide(localPorts));
513
- const routedPorts = Layer.mergeAll(routedSubmissionLedgerLayer({ localConversationId: conversationId }), routedConversationStoreLayer({ localConversationId: conversationId })).pipe(Layer.provide(localPorts), Layer.provide(conversationPortTransportLayer));
514
- const runtimeConfigLayer = Layer.succeed(DurableRuntimeConfig)(DurableRuntimeConfig.make({
515
- deploymentId: config.deploymentId,
516
- producerId,
517
- settlementPollInterval: Duration.millis(config.settlementPollInterval),
518
- leaseRenewalInterval: Duration.millis(config.leaseRenewalInterval),
519
- abortPollInterval: Duration.millis(config.abortPollInterval)
520
- }));
521
- const runtimeFailpointLayer = options.runtimeFailpoint === void 0 ? DurableRuntimeFailpoint.layer : Layer.succeed(DurableRuntimeFailpoint)({ hit: options.runtimeFailpoint(ctx) });
522
- const reconcilerLayer = options.toolReconciler ?? ToolReconciler.uncertain;
523
- const bindingResolverLayer = Layer.effect(AgentBindingResolver)(Effect.map(resolveBindings(options.bindings, {
524
- ctx,
525
- env,
526
- conversationId,
527
- producerId
528
- }), (bindings) => AgentBindingResolver.fromBindings(bindings)));
529
- const base = Layer.mergeAll(identityLayer, cloudflareConfigLayer, DurableAlarmService.layer);
530
- 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));
531
- return Layer.mergeAll(runtimeStack, ConversationMaintenance.layer.pipe(Layer.provide(runtimeStack)), portsEndpointLayer);
532
- }));
533
- }
534
- };
535
- //#endregion
536
- //#region src/client.ts
537
- /**
538
- * The Worker↔Conversation-Object host protocol (plan §1.4): Schema envelopes for the host
539
- * entry points (`submitEncoded`, `awaitSettlementEncoded`, `observePage`, `abortEncoded`,
540
- * `resolveApprovalEncoded`, `resolveUnknownEncoded`) plus the Worker-side client that speaks
541
- * it. Mirrors the WP2 port protocol: requests and responses are closed Schema unions, typed
542
- * failures travel as their own tagged classes and RE-DECODE to identical tags on the caller
543
- * (error-tag fidelity), and protocol anomalies are answered typed instead of thrown.
544
- */
545
- /** Ceiling for host protocol diagnostic strings. */
546
- const MAX_HOST_DIAGNOSTIC_LENGTH = 4096;
547
- const BoundedDiagnostic = Schema.String.check(Schema.isMaxLength(MAX_HOST_DIAGNOSTIC_LENGTH));
548
- /** Truncate a diagnostic string to the host protocol's bounded length. */
549
- const boundHostDiagnostic = (value) => value.length > MAX_HOST_DIAGNOSTIC_LENGTH ? `${value.slice(0, MAX_HOST_DIAGNOSTIC_LENGTH - 3)}...` : value;
550
- /**
551
- * The envelope itself could not be honored: the Object could not decode the request, or a
552
- * response could not be encoded/decoded. Never carries operation semantics.
553
- */
554
- var HostProtocolError = class extends Schema.TaggedError()("HostProtocolError", { message: BoundedDiagnostic }) {};
555
- /** The Worker-side stub call itself failed (RPC rejection, overload, eviction mid-call). */
556
- var ConversationClientError = class extends Schema.TaggedError()("ConversationClientError", {
557
- conversationId: Schema.String,
558
- message: Schema.String,
559
- cause: Schema.optionalKey(Schema.Defect())
560
- }) {};
561
- /**
562
- * One durable submission, input ALREADY encoded by the caller through the Agent Binding's
563
- * input schema (the Worker bundles the same Agent definitions as the Object, so schema
564
- * validation happens client-side; the resolved Binding re-validates at claim time). The
565
- * Conversation identity is deliberately absent — the addressed Object IS the lane.
566
- */
567
- var SubmitRequest = class extends Schema.Class("@effect-agent/platform-cloudflare/SubmitRequest")({
568
- agentId: AgentId,
569
- principal: Principal,
570
- idempotencyKey: IdempotencyKey,
571
- definitions: DefinitionDigests,
572
- inputPayload: PersistedJson
573
- }) {};
574
- /** One bounded page of canonical records after an optional sequence. */
575
- var ObservePageRequest = class extends Schema.Class("@effect-agent/platform-cloudflare/ObservePageRequest")({
576
- afterSequence: Schema.optionalKey(CanonicalSequence),
577
- limit: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1024))
578
- }) {};
579
- /**
580
- * Every typed failure a host entry point can produce, plus the protocol's own errors. Same
581
- * closed-union discipline as the WP2 `PortFailure`: members re-decode to the SAME tagged
582
- * classes on the Worker side; `cause` chains travel as Schema defects without instance
583
- * fidelity (plan §2.8).
584
- */
585
- const HostFailure = Schema.Union([
586
- AgentInputError,
587
- DigestError,
588
- AdmissionConflict,
589
- SettlementConflict,
590
- ApprovalConflict,
591
- UnknownResolutionConflict,
592
- JoinedToHost,
593
- LedgerError,
594
- ConversationStoreError,
595
- ConversationNotMaterialized,
596
- AppendConflict,
597
- FenceRejected,
598
- DurableRuntimeFailpointError,
599
- AdmissionLimitExceeded,
600
- DurableAlarmError,
601
- HostProtocolError
602
- ]);
603
- var SubmitSucceeded = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/SubmitSucceeded")("SubmitSucceeded", { receipt: Receipt }) {};
604
- var SettlementReached = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/SettlementReached")("SettlementReached", { settlement: Settlement }) {};
605
- var ObservedPage = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/ObservedPage")("ObservedPage", { records: Schema.Array(CanonicalRecordEnvelope).check(Schema.isMaxLength(1024)) }) {};
606
- var AbortRecorded = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/AbortRecorded")("AbortRecorded", { intent: AbortIntent }) {};
607
- var ApprovalRecorded = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/ApprovalRecorded")("ApprovalRecorded", { intent: ApprovalDecisionIntent }) {};
608
- var UnknownResolutionRecorded = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/UnknownResolutionRecorded")("UnknownResolutionRecorded", { intent: UnknownResolutionIntent }) {};
609
- /** The entry point failed TYPED on the Object; the failure re-decodes verbatim. */
610
- var HostFailed = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/HostFailed")("HostFailed", { failure: HostFailure }) {};
611
- /** The uniform answer of one host entry point. Callers narrow by the tag their call implies. */
612
- const HostResponse = Schema.Union([
613
- SubmitSucceeded,
614
- SettlementReached,
615
- ObservedPage,
616
- AbortRecorded,
617
- ApprovalRecorded,
618
- UnknownResolutionRecorded,
619
- HostFailed
620
- ]);
621
- const decodeSubmitRequest = Schema.decodeUnknownEffect(SubmitRequest);
622
- const encodeSubmitRequest = Schema.encodeEffect(SubmitRequest);
623
- const decodeReceipt = Schema.decodeUnknownEffect(Receipt);
624
- const encodeReceipt = Schema.encodeEffect(Receipt);
625
- const decodeObservePageRequest = Schema.decodeUnknownEffect(ObservePageRequest);
626
- const encodeObservePageRequest = Schema.encodeEffect(ObservePageRequest);
627
- const decodeAbortCommand = Schema.decodeUnknownEffect(AbortCommand);
628
- const encodeAbortCommand = Schema.encodeEffect(AbortCommand);
629
- const decodeApprovalDecisionCommand = Schema.decodeUnknownEffect(ApprovalDecisionCommand);
630
- const encodeApprovalDecisionCommand = Schema.encodeEffect(ApprovalDecisionCommand);
631
- const decodeUnknownResolutionCommand = Schema.decodeUnknownEffect(UnknownResolutionCommand);
632
- const encodeUnknownResolutionCommand = Schema.encodeEffect(UnknownResolutionCommand);
633
- const encodeHostResponse = Schema.encodeEffect(HostResponse);
634
- const decodeHostResponse = Schema.decodeUnknownEffect(HostResponse);
635
- const SUBMIT_FAILURE_TAGS = /* @__PURE__ */ new Set([
636
- "AgentInputError",
637
- "DigestError",
638
- "AdmissionConflict",
639
- "LedgerError",
640
- "ConversationStoreError",
641
- "ConversationNotMaterialized",
642
- "AppendConflict",
643
- "FenceRejected",
644
- "DurableRuntimeFailpointError",
645
- "AdmissionLimitExceeded",
646
- "DurableAlarmError",
647
- "HostProtocolError"
648
- ]);
649
- const AWAIT_FAILURE_TAGS = /* @__PURE__ */ new Set([
650
- "LedgerError",
651
- "SettlementConflict",
652
- "HostProtocolError"
653
- ]);
654
- const OBSERVE_FAILURE_TAGS = /* @__PURE__ */ new Set([
655
- "ConversationStoreError",
656
- "ConversationNotMaterialized",
657
- "HostProtocolError"
658
- ]);
659
- const ABORT_FAILURE_TAGS = /* @__PURE__ */ new Set([
660
- "LedgerError",
661
- "SettlementConflict",
662
- "JoinedToHost",
663
- "DurableRuntimeFailpointError",
664
- "DurableAlarmError",
665
- "HostProtocolError"
666
- ]);
667
- const APPROVAL_FAILURE_TAGS = /* @__PURE__ */ new Set([
668
- "LedgerError",
669
- "SettlementConflict",
670
- "ApprovalConflict",
671
- "DurableAlarmError",
672
- "HostProtocolError"
673
- ]);
674
- const UNKNOWN_FAILURE_TAGS = /* @__PURE__ */ new Set([
675
- "LedgerError",
676
- "SettlementConflict",
677
- "UnknownResolutionConflict",
678
- "JoinedToHost",
679
- "DurableRuntimeFailpointError",
680
- "DurableAlarmError",
681
- "HostProtocolError"
682
- ]);
683
- const outOfContract = (conversationId, operation, observed) => ConversationClientError.make({
684
- conversationId,
685
- message: boundHostDiagnostic(`The Conversation Object answered ${operation} with the out-of-contract ${observed}.`)
686
- });
687
- /**
688
- * Narrow one decoded `HostFailed.failure` to the operation's declared failure family; an
689
- * out-of-contract tag folds into `ConversationClientError` instead of being erased or
690
- * re-thrown raw (the WP2 discipline). The predicate is the single documented narrowing over
691
- * the closed `HostFailure` union.
692
- */
693
- const narrowFailure = (tags) => (failure) => tags.has(failure._tag);
694
- /** Worker-side client over the Conversation Object namespace (DEPLOY-010). */
695
- var CloudflareConversationClient = class CloudflareConversationClient extends Context.Service()("@effect-agent/platform-cloudflare/CloudflareConversationClient") {
696
- static layer = Layer.effect(CloudflareConversationClient)(Effect.gen(function* () {
697
- const { namespace } = yield* ConversationObjectNamespace;
698
- const call = (conversationId, operation, invoke) => Effect.tryPromise({
699
- try: () => invoke(namespace.get(namespace.idFromName(conversationId))),
700
- catch: (cause) => ConversationClientError.make({
701
- conversationId,
702
- message: boundHostDiagnostic(`${operation} did not reach the Conversation Object: ${cause instanceof Error ? cause.message : String(cause)}`),
703
- cause
704
- })
705
- }).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: {
706
- conversationId,
707
- operation
708
- } }));
709
- const expect = (conversationId, operation, resultTag, tags) => {
710
- const isExpected = narrowFailure(tags);
711
- return (response) => {
712
- if (response._tag === "HostFailed") {
713
- const failure = response.failure;
714
- return isExpected(failure) ? Effect.fail(failure) : Effect.fail(outOfContract(conversationId, operation, `failure ${failure._tag}`));
715
- }
716
- if (response._tag !== resultTag) return Effect.fail(outOfContract(conversationId, operation, `result ${response._tag}`));
717
- return Effect.succeed(response);
718
- };
719
- };
720
- const readPage = (conversationId, options) => Effect.gen(function* () {
721
- const request = ObservePageRequest.make({
722
- ...options?.afterSequence === void 0 ? {} : { afterSequence: options.afterSequence },
723
- limit: options?.limit ?? 256
724
- });
725
- const encoded = yield* encodeObservePageRequest(request).pipe(Effect.mapError((error) => HostProtocolError.make({ message: boundHostDiagnostic(`observePage request encode failed: ${error.message}`) })));
726
- const response = yield* call(conversationId, "observePage", (stub) => stub.observePage(encoded));
727
- return (yield* expect(conversationId, "observePage", "ObservedPage", OBSERVE_FAILURE_TAGS)(response)).records;
728
- });
729
- return CloudflareConversationClient.of({
730
- submit: (agent, input, options) => Effect.gen(function* () {
731
- const encodedInput = yield* Schema.encodeEffect(agent.definition.input)(input).pipe(Effect.mapError((cause) => AgentInputError.make({ message: `Unable to encode Agent input: ${cause.message}` })));
732
- const inputPayload = yield* Schema.decodeUnknownEffect(PersistedJson)(encodedInput).pipe(Effect.mapError(() => AgentInputError.make({ message: "Agent input does not satisfy the canonical persistence bounds" })));
733
- const request = SubmitRequest.make({
734
- agentId: agent.definition.id,
735
- principal: options.principal,
736
- idempotencyKey: options.idempotencyKey,
737
- definitions: options.definitions,
738
- inputPayload
739
- });
740
- const encoded = yield* encodeSubmitRequest(request).pipe(Effect.mapError((error) => HostProtocolError.make({ message: boundHostDiagnostic(`submit request encode failed: ${error.message}`) })));
741
- const response = yield* call(options.conversationId, "submit", (stub) => stub.submitEncoded(encoded));
742
- return (yield* expect(options.conversationId, "submit", "SubmitSucceeded", SUBMIT_FAILURE_TAGS)(response)).receipt;
743
- }),
744
- awaitSettlement: (receipt) => Effect.gen(function* () {
745
- const encoded = yield* encodeReceipt(receipt).pipe(Effect.mapError((error) => HostProtocolError.make({ message: boundHostDiagnostic(`receipt encode failed: ${error.message}`) })));
746
- const response = yield* call(receipt.conversationId, "awaitSettlement", (stub) => stub.awaitSettlementEncoded(encoded));
747
- return (yield* expect(receipt.conversationId, "awaitSettlement", "SettlementReached", AWAIT_FAILURE_TAGS)(response)).settlement;
748
- }),
749
- readPage,
750
- readAll: (conversationId) => Effect.gen(function* () {
751
- const all = [];
752
- let after;
753
- for (;;) {
754
- const page = yield* readPage(conversationId, {
755
- afterSequence: after,
756
- limit: 1024
757
- });
758
- all.push(...page);
759
- const last = page.at(-1);
760
- if (page.length < 1024 || last === void 0) return all;
761
- after = last.sequence;
762
- }
763
- }),
764
- abort: (conversationId, command) => Effect.gen(function* () {
765
- const encoded = yield* encodeAbortCommand(command).pipe(Effect.mapError((error) => HostProtocolError.make({ message: boundHostDiagnostic(`abort command encode failed: ${error.message}`) })));
766
- const response = yield* call(conversationId, "abort", (stub) => stub.abortEncoded(encoded));
767
- return (yield* expect(conversationId, "abort", "AbortRecorded", ABORT_FAILURE_TAGS)(response)).intent;
768
- }),
769
- resolveApproval: (conversationId, command) => Effect.gen(function* () {
770
- const encoded = yield* encodeApprovalDecisionCommand(command).pipe(Effect.mapError((error) => HostProtocolError.make({ message: boundHostDiagnostic(`approval command encode failed: ${error.message}`) })));
771
- const response = yield* call(conversationId, "resolveApproval", (stub) => stub.resolveApprovalEncoded(encoded));
772
- return (yield* expect(conversationId, "resolveApproval", "ApprovalRecorded", APPROVAL_FAILURE_TAGS)(response)).intent;
773
- }),
774
- resolveUnknown: (conversationId, command) => Effect.gen(function* () {
775
- const encoded = yield* encodeUnknownResolutionCommand(command).pipe(Effect.mapError((error) => HostProtocolError.make({ message: boundHostDiagnostic(`resolution command encode failed: ${error.message}`) })));
776
- const response = yield* call(conversationId, "resolveUnknown", (stub) => stub.resolveUnknownEncoded(encoded));
777
- return (yield* expect(conversationId, "resolveUnknown", "UnknownResolutionRecorded", UNKNOWN_FAILURE_TAGS)(response)).intent;
778
- })
779
- });
780
- }));
781
- };
782
- //#endregion
783
- //#region src/conversation-object.ts
784
- /** Port envelope tags whose owner-side execution durably mutates this Object's lane. */
785
- const MUTATING_PORT_TAGS = /* @__PURE__ */ new Set([
786
- "LedgerAdmit",
787
- "LedgerMarkReady",
788
- "LedgerRequestAbort",
789
- "LedgerRecordChildSettled",
790
- "StoreMaterialize",
791
- "StoreAppend"
792
- ]);
793
- const isMutatingPortRequest = (encoded) => typeof encoded === "object" && encoded !== null && "_tag" in encoded && typeof encoded._tag === "string" && MUTATING_PORT_TAGS.has(encoded._tag);
794
- /** The literal encoded `PortFailed(PortProtocolError)` fallback (same shape as WP2's). */
795
- const encodedPortProtocolFailure = (message) => ({
796
- _tag: "PortFailed",
797
- failure: {
798
- _tag: "PortProtocolError",
799
- message: boundHostDiagnostic(message)
800
- }
801
- });
802
- const protocolFailure = (context) => (error) => HostProtocolError.make({ message: boundHostDiagnostic(`${context}: ${error.message}`) });
803
- /** Fold one endpoint's typed failures into the uniform `HostResponse` envelope. */
804
- const respond = (effect) => effect.pipe(Effect.map((result) => result), Effect.catch((failure) => Effect.succeed(HostFailed.make({ failure }))));
805
- /** Encode the response envelope; an unencodable response degrades to a protocol failure. */
806
- const encodeResponse = (response) => encodeHostResponse(response).pipe(Effect.catch((error) => Effect.succeed({
807
- _tag: "HostFailed",
808
- failure: {
809
- _tag: "HostProtocolError",
810
- message: boundHostDiagnostic(`The host response could not be encoded: ${error.message}`)
811
- }
812
- })));
813
- const utf8Bytes = (value) => new TextEncoder().encode(JSON.stringify(value)).length;
814
- /**
815
- * The admission-limits gate, BEFORE `runtime.submit` touches the ledger (exit gate
816
- * "resource limits are checked before admission"; DEPLOY-007). A replayed idempotency key is
817
- * exempt: its accepted-work obligation already exists, and returning the original Receipt
818
- * consumes no new quota. Refusals are typed `AdmissionLimitExceeded` and nothing is written.
819
- */
820
- const gateAdmissionLimits = Effect.fn("ConversationObject.gateAdmissionLimits")(function* (request) {
821
- const identity = yield* ConversationObjectIdentity;
822
- const config = yield* CloudflareDurableRuntimeConfig;
823
- const ledger = yield* SubmissionLedger;
824
- const { ctx } = yield* DurableObjectContext;
825
- const existing = yield* ledger.lookup(SubmissionLookupByKey.make({
826
- conversationId: identity.conversationId,
827
- principal: request.principal,
828
- idempotencyKey: request.idempotencyKey
829
- }));
830
- if (Option.isSome(existing)) return;
831
- const inputBytes = utf8Bytes(request.inputPayload);
832
- if (inputBytes > config.limits.maxInputBytes) return yield* AdmissionLimitExceeded.make({
833
- limit: "input-bytes",
834
- actual: inputBytes,
835
- maximum: config.limits.maxInputBytes
836
- });
837
- const nonterminal = yield* Stream.runCollect(ledger.scanNonterminal);
838
- if (nonterminal.length >= config.limits.maxQueueDepthPerLane) return yield* AdmissionLimitExceeded.make({
839
- limit: "queue-depth",
840
- actual: nonterminal.length,
841
- maximum: config.limits.maxQueueDepthPerLane
842
- });
843
- const databaseBytes = yield* Effect.sync(() => ctx.storage.sql.databaseSize);
844
- if (databaseBytes > config.limits.maxDatabaseBytes) return yield* AdmissionLimitExceeded.make({
845
- limit: "database-bytes",
846
- actual: databaseBytes,
847
- maximum: config.limits.maxDatabaseBytes
848
- });
849
- });
850
- /**
851
- * The submit-capable projection of an Agent Binding on the OBJECT side: the input arrived
852
- * already encoded through the real input schema on the Worker side (`client.ts`), so the
853
- * Object admits the canonical `PersistedJson` payload as-is; the resolved Binding re-derives
854
- * everything else from the stored `(agentId, agentDigests)` at claim time (SUB-023).
855
- */
856
- const passthroughSubmitAgent = (agentId) => ({ definition: {
857
- id: agentId,
858
- input: PersistedJson
859
- } });
860
- const submitEndpoint = (encoded) => decodeSubmitRequest(encoded).pipe(Effect.mapError(protocolFailure("The submit request could not be decoded")), Effect.flatMap((request) => Effect.gen(function* () {
861
- const identity = yield* ConversationObjectIdentity;
862
- const maintenance = yield* ConversationMaintenance;
863
- const runtime = yield* DurableAgentRuntime;
864
- yield* gateAdmissionLimits(request);
865
- yield* maintenance.preArm;
866
- const receipt = yield* runtime.submit(passthroughSubmitAgent(request.agentId), request.inputPayload, {
867
- conversationId: identity.conversationId,
868
- principal: request.principal,
869
- idempotencyKey: request.idempotencyKey,
870
- definitions: request.definitions
871
- });
872
- return SubmitSucceeded.make({ receipt });
873
- })), respond, Effect.flatMap(encodeResponse));
874
- const awaitSettlementEndpoint = (encoded) => decodeReceipt(encoded).pipe(Effect.mapError(protocolFailure("The receipt could not be decoded")), Effect.flatMap((receipt) => Effect.gen(function* () {
875
- const settlement = yield* (yield* DurableAgentRuntime).awaitSettlement(receipt);
876
- return SettlementReached.make({ settlement });
877
- })), respond, Effect.flatMap(encodeResponse));
878
- const observePageEndpoint = (encoded) => decodeObservePageRequest(encoded).pipe(Effect.mapError(protocolFailure("The observe request could not be decoded")), Effect.flatMap((request) => Effect.gen(function* () {
879
- const identity = yield* ConversationObjectIdentity;
880
- const store = yield* ConversationStore;
881
- yield* (yield* OperationAuthorizer).authorize(OperationAuthorizationRequest.make({
882
- operation: "observe",
883
- conversationId: identity.conversationId
884
- })).pipe(Effect.catchTag("OperationDenied", deniedToProtocolFailure));
885
- const records = yield* Stream.runCollect(store.read(ConversationRead.make({
886
- conversationId: identity.conversationId,
887
- ...request.afterSequence === void 0 ? {} : { afterSequence: request.afterSequence },
888
- limit: request.limit
889
- })));
890
- return ObservedPage.make({ records: [...records] });
891
- })), respond, Effect.flatMap(encodeResponse));
892
- const abortEndpoint = (encoded) => decodeAbortCommand(encoded).pipe(Effect.mapError(protocolFailure("The abort command could not be decoded")), Effect.flatMap((command) => Effect.gen(function* () {
893
- const maintenance = yield* ConversationMaintenance;
894
- const runtime = yield* DurableAgentRuntime;
895
- yield* maintenance.preArm;
896
- const intent = yield* runtime.abort(command);
897
- return AbortRecorded.make({ intent });
898
- })), respond, Effect.flatMap(encodeResponse));
899
- /**
900
- * The pre-P7 host protocol's failure union does not carry `OperationDenied` (the Worker client
901
- * predates the authorizer). This assembly always runs the default possession authorizer — no
902
- * `CloudflareDurableRuntimeOptions` authorizer lever exists yet — so a denial here is
903
- * unreachable today; if one ever surfaces it degrades to the protocol failure instead of an
904
- * out-of-contract throw. The four P7 admin entry points below carry `OperationDenied` typed.
905
- */
906
- const deniedToProtocolFailure = (denied) => Effect.fail(HostProtocolError.make({ message: boundHostDiagnostic(`The ${denied.operation} operation was denied: ${denied.reason}`) }));
907
- const resolveApprovalEndpoint = (encoded) => decodeApprovalDecisionCommand(encoded).pipe(Effect.mapError(protocolFailure("The approval command could not be decoded")), Effect.flatMap((command) => Effect.gen(function* () {
908
- const maintenance = yield* ConversationMaintenance;
909
- const runtime = yield* DurableAgentRuntime;
910
- yield* maintenance.preArm;
911
- const intent = yield* runtime.resolveApproval(command).pipe(Effect.catchTag("OperationDenied", deniedToProtocolFailure));
912
- return ApprovalRecorded.make({ intent });
913
- })), respond, Effect.flatMap(encodeResponse));
914
- const resolveUnknownEndpoint = (encoded) => decodeUnknownResolutionCommand(encoded).pipe(Effect.mapError(protocolFailure("The resolution command could not be decoded")), Effect.flatMap((command) => Effect.gen(function* () {
915
- const maintenance = yield* ConversationMaintenance;
916
- const runtime = yield* DurableAgentRuntime;
917
- yield* maintenance.preArm;
918
- const intent = yield* runtime.resolveUnknown(command).pipe(Effect.catchTag("OperationDenied", deniedToProtocolFailure));
919
- return UnknownResolutionRecorded.make({ intent });
920
- })), respond, Effect.flatMap(encodeResponse));
921
- /** Explain one Submission (`submissionId` present) or every nonterminal lane member. */
922
- var AdminExplainRequest = class extends Schema.Class("@effect-agent/platform-cloudflare/AdminExplainRequest")({ submissionId: Schema.optionalKey(SubmissionId) }) {};
923
- /** Verify carries no parameters — the addressed Object IS the lane. */
924
- var AdminVerifyRequest = class extends Schema.Class("@effect-agent/platform-cloudflare/AdminVerifyRequest")({}) {};
925
- /** Every typed failure of the four admin entry points, plus the protocol's own errors. */
926
- const AdminFailure = Schema.Union([
927
- OperationDenied,
928
- RetryRefused,
929
- LedgerError,
930
- RunJournalError,
931
- DigestError,
932
- OwnershipLost,
933
- SettlementConflict,
934
- ConversationStoreError,
935
- ConversationNotMaterialized,
936
- AppendConflict,
937
- FenceRejected,
938
- DurableRuntimeFailpointError,
939
- DurableAlarmError,
940
- HostProtocolError
941
- ]);
942
- var ExplainedRecovery = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/ExplainedRecovery")("ExplainedRecovery", { explanations: Schema.Array(RecoveryExplanation).check(Schema.isMaxLength(1024)) }) {};
943
- var VerifiedIntegrity = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/VerifiedIntegrity")("VerifiedIntegrity", { report: IntegrityReport }) {};
944
- var RetryExecuted = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/RetryExecuted")("RetryExecuted", { report: RecoveryReport }) {};
945
- var ObligationsScanned = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/ObligationsScanned")("ObligationsScanned", { report: ObligationReport }) {};
946
- /** The admin entry point failed TYPED on the Object; the failure re-decodes verbatim. */
947
- var AdminFailed = class extends Schema.TaggedClass("@effect-agent/platform-cloudflare/AdminFailed")("AdminFailed", { failure: AdminFailure }) {};
948
- /** The uniform answer of one admin entry point. Callers narrow by the tag their call implies. */
949
- const AdminResponse = Schema.Union([
950
- ExplainedRecovery,
951
- VerifiedIntegrity,
952
- RetryExecuted,
953
- ObligationsScanned,
954
- AdminFailed
955
- ]);
956
- const decodeAdminExplainRequest = Schema.decodeUnknownEffect(AdminExplainRequest);
957
- const decodeAdminVerifyRequest = Schema.decodeUnknownEffect(AdminVerifyRequest);
958
- const decodeRetryCommand = Schema.decodeUnknownEffect(RetryCommand);
959
- const decodeObligationThresholds = Schema.decodeUnknownEffect(ObligationThresholds);
960
- const encodeAdminResponse = Schema.encodeEffect(AdminResponse);
961
- const decodeAdminResponse = Schema.decodeUnknownEffect(AdminResponse);
962
- /** Fold one admin endpoint's typed failures into the uniform `AdminResponse` envelope. */
963
- const respondAdmin = (effect) => effect.pipe(Effect.map((result) => result), Effect.catch((failure) => Effect.succeed(AdminFailed.make({ failure }))));
964
- /** Encode the admin response envelope; an unencodable response degrades to a protocol failure. */
965
- const encodeAdminResponseTotal = (response) => encodeAdminResponse(response).pipe(Effect.catch((error) => Effect.succeed({
966
- _tag: "AdminFailed",
967
- failure: {
968
- _tag: "HostProtocolError",
969
- message: boundHostDiagnostic(`The admin response could not be encoded: ${error.message}`)
970
- }
971
- })));
972
- const explainEndpoint = (encoded) => decodeAdminExplainRequest(encoded).pipe(Effect.mapError(protocolFailure("The explain request could not be decoded")), Effect.flatMap((request) => Effect.gen(function* () {
973
- const identity = yield* ConversationObjectIdentity;
974
- const runtime = yield* DurableAgentRuntime;
975
- const explanations = request.submissionId === void 0 ? yield* runtime.explainConversation(identity.conversationId) : [yield* runtime.explain(request.submissionId)];
976
- return ExplainedRecovery.make({ explanations });
977
- })), respondAdmin, Effect.flatMap(encodeAdminResponseTotal));
978
- const verifyEndpoint = (encoded) => decodeAdminVerifyRequest(encoded).pipe(Effect.mapError(protocolFailure("The verify request could not be decoded")), Effect.flatMap(() => Effect.gen(function* () {
979
- const identity = yield* ConversationObjectIdentity;
980
- const report = yield* (yield* DurableAgentRuntime).verify(identity.conversationId);
981
- return VerifiedIntegrity.make({ report });
982
- })), respondAdmin, Effect.flatMap(encodeAdminResponseTotal));
983
- const retryEndpoint = (encoded) => decodeRetryCommand(encoded).pipe(Effect.mapError(protocolFailure("The retry command could not be decoded")), Effect.flatMap((command) => Effect.gen(function* () {
984
- const maintenance = yield* ConversationMaintenance;
985
- const runtime = yield* DurableAgentRuntime;
986
- yield* maintenance.preArm;
987
- const report = yield* runtime.retry(command);
988
- return RetryExecuted.make({ report });
989
- })), respondAdmin, Effect.flatMap(encodeAdminResponseTotal));
990
- const obligationsEndpoint = (encoded) => decodeObligationThresholds(encoded).pipe(Effect.mapError(protocolFailure("The obligation thresholds could not be decoded")), Effect.flatMap((thresholds) => Effect.gen(function* () {
991
- const report = yield* (yield* DurableAgentRuntime).scanObligations(thresholds);
992
- return ObligationsScanned.make({ report });
993
- })), respondAdmin, Effect.flatMap(encodeAdminResponseTotal));
994
- /**
995
- * Owner-side `portCall`: pre-arm before a mutating envelope (a routed admission committed by
996
- * THIS Object must already carry the alarm that will finish it), execute on the LOCAL facets
997
- * (never the routed decorators), then arm an immediate alarm so the mutated lane is
998
- * processed promptly. Protocol anomalies answer `PortFailed(PortProtocolError)`.
999
- */
1000
- const portCallEndpoint = (encoded) => Effect.gen(function* () {
1001
- const ports = yield* ConversationObjectPorts;
1002
- const maintenance = yield* ConversationMaintenance;
1003
- const alarm = yield* DurableAlarmService;
1004
- const mutating = isMutatingPortRequest(encoded);
1005
- if (mutating) {
1006
- if ((yield* maintenance.preArm.pipe(Effect.exit))._tag === "Failure") return encodedPortProtocolFailure("The owner Object could not arm its maintenance alarm before the mutation.");
1007
- }
1008
- const response = yield* ports.handle(encoded);
1009
- if (mutating) yield* alarm.scheduleNow.pipe(Effect.catch((error) => Effect.logWarning("ConversationObject.portCall: immediate re-arm failed", error)));
1010
- return response;
1011
- });
1012
- const wakeEndpoint = Effect.gen(function* () {
1013
- yield* (yield* DurableAlarmService).scheduleNow.pipe(Effect.catch((error) => Effect.logWarning("ConversationObject.wake dropped", error)));
1014
- });
1015
- const alarmEndpoint = Effect.gen(function* () {
1016
- yield* (yield* ConversationMaintenance).pass;
1017
- });
1018
- const gateEndpoint = Effect.gen(function* () {
1019
- yield* (yield* ConversationMaintenance).ensureAlarm;
1020
- });
1021
- /**
1022
- * Adapter from effect-cf's native Durable Object services to Effect Agent's existing platform
1023
- * ports. effect-cf owns the cached ManagedRuntime and supplies these values once per Object
1024
- * incarnation; the durable runtime continues to depend only on the narrow services below.
1025
- */
1026
- const effectCfPlatformLayer = (namespaceBinding) => {
1027
- const context = Layer.effect(DurableObjectContext)(Effect.gen(function* () {
1028
- const state = yield* DurableObjectState.DurableObjectState;
1029
- const env = yield* WorkerEnvironment;
1030
- return DurableObjectContext.of({
1031
- ctx: state.raw,
1032
- env
1033
- });
1034
- }));
1035
- const namespace = Layer.effect(ConversationObjectNamespace)(Effect.gen(function* () {
1036
- const binding = yield* conversationNamespaceFromEnv(yield* WorkerEnvironment, namespaceBinding);
1037
- return ConversationObjectNamespace.of({ namespace: binding });
1038
- }));
1039
- return Layer.merge(context, namespace);
1040
- };
1041
- /**
1042
- * Build the application's Conversation Object class (export it from the Worker entry).
1043
- * effect-cf owns the cached ManagedRuntime, native RPC methods, event scopes, and post-handler
1044
- * OTLP flush scheduling for RPC and alarm events. The optional outer Layer is built per native
1045
- * event, so a host can install Tracer/Logger/Metric services and `OtlpExporter.Flusher` without
1046
- * Effect Agent owning exporter lifecycle machinery.
1047
- */
1048
- const makeConversationObjectClass = (options, observability) => {
1049
- const application = CloudflareDurableRuntime.layer(options).pipe(Layer.provideMerge(effectCfPlatformLayer(options.namespaceBinding)));
1050
- const runtime = Layer.effectContext(Effect.gen(function* () {
1051
- const state = yield* DurableObjectState.DurableObjectState;
1052
- const scope = yield* Effect.scope;
1053
- return yield* state.blockConcurrencyWhile(Effect.gen(function* () {
1054
- const services = yield* Layer.buildWithScope(application, scope);
1055
- yield* gateEndpoint.pipe(Effect.provide(services));
1056
- return services;
1057
- }));
1058
- }));
1059
- const rpc = {
1060
- submitEncoded: (encoded) => submitEndpoint(encoded),
1061
- awaitSettlementEncoded: (encoded) => awaitSettlementEndpoint(encoded),
1062
- observePage: (encoded) => observePageEndpoint(encoded),
1063
- abortEncoded: (encoded) => abortEndpoint(encoded),
1064
- resolveApprovalEncoded: (encoded) => resolveApprovalEndpoint(encoded),
1065
- resolveUnknownEncoded: (encoded) => resolveUnknownEndpoint(encoded),
1066
- explainEncoded: (encoded) => explainEndpoint(encoded),
1067
- verifyEncoded: (encoded) => verifyEndpoint(encoded),
1068
- retryEncoded: (encoded) => retryEndpoint(encoded),
1069
- obligationsEncoded: (encoded) => obligationsEndpoint(encoded),
1070
- portCall: (encoded) => portCallEndpoint(encoded),
1071
- wake: () => wakeEndpoint
1072
- };
1073
- const EffectCfConversationObject = DurableObject.make(runtime, {
1074
- ...observability === void 0 ? {} : { eventLayer: observability },
1075
- initialize: Effect.void,
1076
- rpc,
1077
- alarm: () => alarmEndpoint
1078
- });
1079
- class ConversationObject extends EffectCfConversationObject {
1080
- alarm(alarmInfo) {
1081
- return super.alarm?.(alarmInfo);
1082
- }
1083
- }
1084
- return ConversationObject;
1085
- };
1086
- //#endregion
1087
- //#region src/code-mode-executor.ts
1088
- /**
1089
- * The Cloudflare Dynamic Worker `CodeExecutor` adapter (C4 of ADR-0017;
1090
- * DEPLOY-011). Each pass loads one fresh Worker through the Worker Loader
1091
- * with `globalOutbound: null`, so generated code has no ambient network,
1092
- * bindings, or secrets; its only authority is the pass-scoped host stub that
1093
- * routes back to `CodeModeHostEntrypoint` and, from there, into the pass's
1094
- * `CodeExecutionHost` service. Platform CPU limits stop synchronous runaway
1095
- * programs; the executor-owned wall-clock deadline interrupts asynchronously
1096
- * suspended passes. Deployment class `E` only: the adapter records no
1097
- * persistent state and a later pass may run in a completely different
1098
- * isolate.
1099
- */
1100
- const dynamicWorkerImplementation = SandboxImplementation.make({
1101
- isolation: "isolated",
1102
- identity: "cloudflare-dynamic-worker"
1103
- });
1104
- /**
1105
- * Live passes by identity. Entries are Scope-managed: registered when a pass
1106
- * opens and removed by its finalizer, so a stale harness (or a forged
1107
- * `passId`) cannot reach any host authority.
1108
- */
1109
- const passRegistry = /* @__PURE__ */ new Map();
1110
- /**
1111
- * The host-side RPC target for dynamic workers. The application exposes it
1112
- * from its Worker entry (`export { CodeModeHostEntrypoint }`) and hands the
1113
- * adapter a same-instance stub — `ctx.exports.CodeModeHostEntrypoint()` in
1114
- * production (a self service binding may reach a different instance and must
1115
- * not be used there); tests bind it through Miniflare's `kCurrentWorker`.
1116
- */
1117
- var CodeModeHostEntrypoint = class extends WorkerEntrypoint {
1118
- async call(passId, hostCall) {
1119
- const pass = passRegistry.get(String(passId));
1120
- if (pass === void 0) throw new Error("Unknown Code Mode pass");
1121
- return pass.dispatch(hostCall);
1122
- }
1123
- };
1124
- /**
1125
- * The fixed harness loaded as the dynamic worker's main module. The generated
1126
- * source becomes `program.mjs` (`export default (<expression>);`) — a module,
1127
- * never `eval`. The harness installs namespace globals and a bounded console,
1128
- * imports the program, invokes it exactly once, and returns one envelope the
1129
- * host validates through Effect Schema.
1130
- */
1131
- const HARNESS_MODULE = String.raw`
1132
- import { WorkerEntrypoint } from "cloudflare:workers";
1133
- import programDefault from "./program.js";
1134
-
1135
- const encoder = new TextEncoder();
1136
- const utf8 = (text) => encoder.encode(text).byteLength;
1137
- const safeText = (value) => {
1138
- try {
1139
- if (value instanceof Error) return (value.name + ": " + value.message).slice(0, 4000);
1140
- if (typeof value === "string") return value.slice(0, 4000);
1141
- const encoded = JSON.stringify(value);
1142
- return (encoded === undefined ? String(value) : encoded).slice(0, 4000);
1143
- } catch {
1144
- return "[unserializable value]";
1145
- }
1146
- };
1147
- const safeJson = (value) => {
1148
- try {
1149
- const encoded = JSON.stringify(value);
1150
- if (encoded !== undefined && encoded.length <= 4000) return JSON.parse(encoded);
1151
- } catch {}
1152
- return safeText(value);
1153
- };
1154
-
1155
- export default class CodeModeHarness extends WorkerEntrypoint {
1156
- async run() {
1157
- const config = JSON.parse(this.env.CODE_MODE_PASS);
1158
- const host = this.env.CODE_MODE_HOST;
1159
- const limits = config.limits;
1160
- const logs = [];
1161
- let logBytes = 0;
1162
- let fatal;
1163
- const boundedLogs = () => logs.slice(0, 4096);
1164
- const write = (...values) => {
1165
- const joined = values.map(safeText).join(" ");
1166
- const line = joined.length > 16000 ? joined.slice(0, 15999) + "…" : joined;
1167
- const bytes = utf8(line);
1168
- if (logs.length >= 4096 || logBytes + bytes > limits.maxLogBytes) {
1169
- fatal = fatal ?? { _tag: "log-limit", observed: logBytes + bytes, logs: boundedLogs() };
1170
- throw new Error("code-mode log limit exceeded");
1171
- }
1172
- logs.push(line);
1173
- logBytes += bytes;
1174
- };
1175
- globalThis.console = { log: write, info: write, warn: write, error: write, debug: write };
1176
-
1177
- let hostCalls = 0;
1178
- const makeMethod = (namespace, method) => async (argument) => {
1179
- hostCalls += 1;
1180
- if (hostCalls > limits.maxHostCalls) {
1181
- fatal = fatal ?? { _tag: "host-call-limit", logs: boundedLogs() };
1182
- throw new Error("code-mode host-call limit exceeded");
1183
- }
1184
- let argText;
1185
- try {
1186
- argText = JSON.stringify(argument);
1187
- } catch {}
1188
- if (argText === undefined || utf8(argText) > limits.maxHostCallArgumentBytes) {
1189
- fatal = fatal ?? {
1190
- _tag: "argument-limit",
1191
- observed: argText === undefined ? 0 : utf8(argText),
1192
- logs: boundedLogs(),
1193
- };
1194
- throw new Error("code-mode host-call argument limit exceeded");
1195
- }
1196
- const outcome = await host.call(config.passId, {
1197
- namespace,
1198
- method,
1199
- argument: JSON.parse(argText),
1200
- });
1201
- if (outcome !== null && typeof outcome === "object" && outcome._tag === "CodeHostCallSuccess") {
1202
- return outcome.value;
1203
- }
1204
- if (outcome !== null && typeof outcome === "object" && outcome._tag === "CodeHostCallFailure") {
1205
- throw outcome.error;
1206
- }
1207
- fatal = fatal ?? { _tag: "protocol", message: "host returned an unrecognized outcome" };
1208
- throw new Error("code-mode host protocol violation");
1209
- };
1210
- for (const namespace of config.namespaces) {
1211
- const methods = {};
1212
- for (const method of namespace.methods) {
1213
- methods[method] = makeMethod(namespace.name, method);
1214
- }
1215
- globalThis[namespace.name] = methods;
1216
- }
1217
-
1218
- // program.js is imported statically at the top of this module, so a
1219
- // syntactically invalid program fails the whole harness at load (mapped
1220
- // to a source error by the host). Using a static import keeps this module
1221
- // free of dynamic-import expressions, which single-script Miniflare hosts
1222
- // reject. The isolation boundary does NOT depend on the ordering of this
1223
- // import versus the console/namespace shims installed below: the loaded
1224
- // Worker has globalOutbound: null and no bindings, secrets, or env from
1225
- // the Worker Loader config BEFORE any module in the graph evaluates, so
1226
- // module-level program code has no ambient authority regardless. The
1227
- // shims below are usability wrappers (bounded console, namespace globals),
1228
- // and the accepted program is a single async-function expression whose
1229
- // body runs only when invoked here — after the shims exist.
1230
- const program = programDefault;
1231
- if (typeof program !== "function") {
1232
- return { _tag: "source-not-a-function", actual: typeof program };
1233
- }
1234
- try {
1235
- const value = await program();
1236
- if (fatal !== undefined) return fatal;
1237
- let text;
1238
- try {
1239
- text = JSON.stringify(value);
1240
- } catch {}
1241
- if (text === undefined) {
1242
- return {
1243
- _tag: "program-failed",
1244
- reason: "non-json-result",
1245
- thrown: null,
1246
- message: "The program must return a JSON value",
1247
- logs: boundedLogs(),
1248
- };
1249
- }
1250
- const resultBytes = utf8(text);
1251
- if (resultBytes > limits.maxResultBytes) {
1252
- return { _tag: "result-limit", observed: resultBytes, logs: boundedLogs() };
1253
- }
1254
- return {
1255
- _tag: "completed",
1256
- value: JSON.parse(text),
1257
- logs: boundedLogs(),
1258
- hostCalls,
1259
- logBytes,
1260
- resultBytes,
1261
- };
1262
- } catch (cause) {
1263
- if (fatal !== undefined) return fatal;
1264
- return {
1265
- _tag: "program-failed",
1266
- reason: cause instanceof Error ? "threw" : "rejected",
1267
- thrown: safeJson(cause),
1268
- message: safeText(cause),
1269
- logs: boundedLogs(),
1270
- };
1271
- }
1272
- }
1273
- }
1274
- `;
1275
- const BoundedLogs = Schema.Array(Schema.String.check(Schema.isMaxLength(16 * 1024))).check(Schema.isMaxLength(4096));
1276
- const HarnessCompleted = Schema.Struct({
1277
- _tag: Schema.Literal("completed"),
1278
- value: Schema.Json,
1279
- logs: BoundedLogs,
1280
- hostCalls: Schema.Natural,
1281
- logBytes: Schema.Natural,
1282
- resultBytes: Schema.Natural
1283
- });
1284
- const HarnessSourceInvalid = Schema.Struct({
1285
- _tag: Schema.Literal("source-invalid"),
1286
- message: Schema.String
1287
- });
1288
- const HarnessNotAFunction = Schema.Struct({
1289
- _tag: Schema.Literal("source-not-a-function"),
1290
- actual: Schema.String
1291
- });
1292
- const HarnessProgramFailed = Schema.Struct({
1293
- _tag: Schema.Literal("program-failed"),
1294
- reason: Schema.Literals([
1295
- "threw",
1296
- "rejected",
1297
- "non-json-result"
1298
- ]),
1299
- thrown: Schema.Json,
1300
- message: Schema.String,
1301
- logs: BoundedLogs
1302
- });
1303
- const HarnessLogLimit = Schema.Struct({
1304
- _tag: Schema.Literal("log-limit"),
1305
- observed: Schema.Natural,
1306
- logs: BoundedLogs
1307
- });
1308
- const HarnessArgumentLimit = Schema.Struct({
1309
- _tag: Schema.Literal("argument-limit"),
1310
- observed: Schema.Natural,
1311
- logs: BoundedLogs
1312
- });
1313
- const HarnessResultLimit = Schema.Struct({
1314
- _tag: Schema.Literal("result-limit"),
1315
- observed: Schema.Natural,
1316
- logs: BoundedLogs
1317
- });
1318
- const HarnessHostCallLimit = Schema.Struct({
1319
- _tag: Schema.Literal("host-call-limit"),
1320
- logs: BoundedLogs
1321
- });
1322
- const HarnessProtocol = Schema.Struct({
1323
- _tag: Schema.Literal("protocol"),
1324
- message: Schema.String
1325
- });
1326
- const HarnessOutcome = Schema.Union([
1327
- HarnessCompleted,
1328
- HarnessSourceInvalid,
1329
- HarnessNotAFunction,
1330
- HarnessProgramFailed,
1331
- HarnessLogLimit,
1332
- HarnessArgumentLimit,
1333
- HarnessResultLimit,
1334
- HarnessHostCallLimit,
1335
- HarnessProtocol
1336
- ]);
1337
- const decodeHarnessOutcome = (value) => {
1338
- try {
1339
- return Schema.decodeUnknownOption(HarnessOutcome)(value);
1340
- } catch {
1341
- return Option.none();
1342
- }
1343
- };
1344
- const decodeHostCall = (value) => {
1345
- try {
1346
- return Schema.decodeUnknownOption(CodeHostCall)(value);
1347
- } catch {
1348
- return Option.none();
1349
- }
1350
- };
1351
- /**
1352
- * Project a host outcome to the plain JSON envelope the harness reads. A
1353
- * `CodeExecutionHost` may return either real `CodeHostCallResult` instances
1354
- * (the substitute and conformance kit) or plain-object equivalents (the Code
1355
- * Mode capability's broker route), so this reads the shared fields rather than
1356
- * `Schema.encodeSync`, which would reject a plain object.
1357
- */
1358
- const hostResultEnvelope = (outcome) => outcome._tag === "CodeHostCallSuccess" ? {
1359
- _tag: "CodeHostCallSuccess",
1360
- value: outcome.value
1361
- } : {
1362
- _tag: "CodeHostCallFailure",
1363
- error: outcome.error
1364
- };
1365
- const utf8ByteLength = (value) => {
1366
- let total = 0;
1367
- for (const character of value) {
1368
- const codePoint = character.codePointAt(0) ?? 0;
1369
- total += codePoint <= 127 ? 1 : codePoint <= 2047 ? 2 : codePoint <= 65535 ? 3 : 4;
1370
- }
1371
- return total;
1372
- };
1373
- const encodedJsonByteLength = (value) => {
1374
- try {
1375
- const encoded = JSON.stringify(value);
1376
- return encoded === void 0 ? void 0 : utf8ByteLength(encoded);
1377
- } catch {
1378
- return;
1379
- }
1380
- };
1381
- /** Reserved global names the harness owns inside the dynamic worker. */
1382
- const reservedHarnessGlobals = /* @__PURE__ */ new Set(["console"]);
1383
- const passCounterState = { next: 0 };
1384
- const makeExecute = (options) => Effect.fn("DynamicWorkerCodeExecutor.execute")(function* (request) {
1385
- if (request.network._tag !== "NetworkDisabled") return yield* CodeExecutorUnsupportedError.make({
1386
- implementation: dynamicWorkerImplementation,
1387
- feature: "network",
1388
- message: "The Dynamic Worker executor denies all egress with globalOutbound: null; an allowlist is not supported in the first slice"
1389
- });
1390
- const sourceBytes = utf8ByteLength(request.source);
1391
- if (sourceBytes > request.limits.maxSourceBytes) return yield* CodeSourceError.make({
1392
- implementation: dynamicWorkerImplementation,
1393
- reason: "oversized",
1394
- message: `Source is ${sourceBytes} bytes; the request allows ${request.limits.maxSourceBytes}`
1395
- });
1396
- for (const namespace of request.namespaces) if (reservedHarnessGlobals.has(namespace.name)) return yield* CodeExecutorUnsupportedError.make({
1397
- implementation: dynamicWorkerImplementation,
1398
- feature: "namespaces",
1399
- message: `Namespace ${namespace.name} collides with a harness binding`
1400
- });
1401
- const host = yield* CodeExecutionHost;
1402
- passCounterState.next += 1;
1403
- const passId = `code-mode-pass-${passCounterState.next}-${crypto.randomUUID()}`;
1404
- const pending = [];
1405
- let wake;
1406
- let issuedHostCalls = 0;
1407
- const dispatch = (hostCall) => new Promise((resolve, reject) => {
1408
- issuedHostCalls += 1;
1409
- if (issuedHostCalls > request.limits.maxHostCalls + 1) {
1410
- reject(/* @__PURE__ */ new Error("host-call limit exceeded"));
1411
- return;
1412
- }
1413
- pending.push({
1414
- hostCall,
1415
- resolve,
1416
- reject
1417
- });
1418
- wake?.();
1419
- });
1420
- yield* Effect.acquireRelease(Effect.sync(() => {
1421
- passRegistry.set(passId, { dispatch });
1422
- }), () => Effect.sync(() => {
1423
- passRegistry.delete(passId);
1424
- }));
1425
- const nextPending = Effect.suspend(() => {
1426
- const item = pending.shift();
1427
- if (item !== void 0) return Effect.succeed(item);
1428
- return Effect.callback((resume) => {
1429
- wake = () => {
1430
- wake = void 0;
1431
- const next = pending.shift();
1432
- if (next !== void 0) resume(Effect.succeed(next));
1433
- };
1434
- });
1435
- });
1436
- const serveHostCalls = Effect.gen(function* () {
1437
- let served = 0;
1438
- while (true) {
1439
- const item = yield* nextPending;
1440
- served += 1;
1441
- if (served > request.limits.maxHostCalls) return yield* CodeHostCallLimitError.make({
1442
- implementation: dynamicWorkerImplementation,
1443
- limit: request.limits.maxHostCalls,
1444
- logs: []
1445
- });
1446
- const decoded = decodeHostCall(item.hostCall);
1447
- if (Option.isNone(decoded)) {
1448
- item.reject(/* @__PURE__ */ new TypeError("host calls must match the CodeHostCall schema"));
1449
- continue;
1450
- }
1451
- const outcome = yield* host.call(decoded.value);
1452
- if (outcome._tag === "CodeHostCallSuccess") {
1453
- const bytes = encodedJsonByteLength(outcome.value);
1454
- if (bytes === void 0 || bytes > request.limits.maxHostCallResultBytes) return yield* CodeOutputLimitError.make({
1455
- implementation: dynamicWorkerImplementation,
1456
- surface: "host-call-result",
1457
- limit: request.limits.maxHostCallResultBytes,
1458
- observed: bytes ?? 0,
1459
- logs: []
1460
- });
1461
- }
1462
- item.resolve(hostResultEnvelope(outcome));
1463
- }
1464
- });
1465
- const workerCode = {
1466
- compatibilityDate: options.compatibilityDate ?? "2025-05-01",
1467
- allowExperimental: true,
1468
- mainModule: "harness.js",
1469
- modules: {
1470
- "harness.js": HARNESS_MODULE,
1471
- "program.js": `export default (\n${request.source}\n);`
1472
- },
1473
- env: {
1474
- CODE_MODE_HOST: options.hostStub,
1475
- CODE_MODE_PASS: JSON.stringify({
1476
- passId,
1477
- namespaces: request.namespaces.map((namespace) => ({
1478
- name: namespace.name,
1479
- methods: namespace.methods
1480
- })),
1481
- limits: {
1482
- maxLogBytes: request.limits.maxLogBytes,
1483
- maxResultBytes: request.limits.maxResultBytes,
1484
- maxHostCalls: request.limits.maxHostCalls,
1485
- maxHostCallArgumentBytes: request.limits.maxHostCallArgumentBytes
1486
- }
1487
- })
1488
- },
1489
- globalOutbound: null,
1490
- ...request.limits.cpuMillis === void 0 ? {} : { limits: {
1491
- cpuMs: request.limits.cpuMillis,
1492
- subRequests: request.limits.maxHostCalls + 8
1493
- } }
1494
- };
1495
- const startedAt = yield* Clock.currentTimeMillis;
1496
- const worker = yield* Effect.acquireRelease(Effect.try({
1497
- try: () => options.loader.load(workerCode),
1498
- catch: (cause) => {
1499
- const text = cause instanceof Error ? cause.message : String(cause);
1500
- if (/syntaxerror|failed to (compile|parse)/i.test(text)) return CodeSourceError.make({
1501
- implementation: dynamicWorkerImplementation,
1502
- reason: "invalid",
1503
- message: text.slice(0, 8e3)
1504
- });
1505
- return CodeExecutorStartError.make({
1506
- implementation: dynamicWorkerImplementation,
1507
- message: `The Worker Loader rejected the pass: ${text}`.slice(0, 8e3),
1508
- cause
1509
- });
1510
- }
1511
- }), (stub) => Effect.sync(() => {
1512
- stub[Symbol.dispose]?.();
1513
- }));
1514
- const server = yield* serveHostCalls.pipe(Effect.forkScoped);
1515
- const rpc = Effect.tryPromise({
1516
- try: async () => {
1517
- return await worker.getEntrypoint().run();
1518
- },
1519
- catch: (cause) => classifyWorkerFailure(cause, request.limits.maxWallTime)
1520
- });
1521
- const raw = yield* Effect.raceFirst(rpc, Fiber.join(server)).pipe(Effect.timeoutOrElse({
1522
- duration: request.limits.maxWallTime,
1523
- orElse: () => CodeExecutionTimeoutError.make({
1524
- implementation: dynamicWorkerImplementation,
1525
- kind: "wall-clock",
1526
- maxWallTime: request.limits.maxWallTime,
1527
- logs: []
1528
- })
1529
- }), Effect.ensuring(Fiber.interrupt(server)));
1530
- const finishedAt = yield* Clock.currentTimeMillis;
1531
- const outcome = decodeHarnessOutcome(raw);
1532
- if (Option.isNone(outcome)) return yield* CodeExecutionProtocolError.make({
1533
- implementation: dynamicWorkerImplementation,
1534
- message: "The dynamic worker returned a value outside the harness envelope schema"
1535
- });
1536
- switch (outcome.value._tag) {
1537
- case "completed": return CodeExecutionResult.make({
1538
- implementation: dynamicWorkerImplementation,
1539
- value: outcome.value.value,
1540
- logs: outcome.value.logs,
1541
- resourceUse: CodeExecutionResourceUse.make({
1542
- wallTime: Duration.millis(Math.max(0, finishedAt - startedAt)),
1543
- hostCalls: outcome.value.hostCalls,
1544
- logBytes: outcome.value.logBytes,
1545
- resultBytes: outcome.value.resultBytes
1546
- })
1547
- });
1548
- case "source-invalid": return yield* CodeSourceError.make({
1549
- implementation: dynamicWorkerImplementation,
1550
- reason: "invalid",
1551
- message: outcome.value.message.slice(0, 8e3)
1552
- });
1553
- case "source-not-a-function": return yield* CodeSourceError.make({
1554
- implementation: dynamicWorkerImplementation,
1555
- reason: "not-a-function",
1556
- message: `The source expression evaluated to ${outcome.value.actual}; it must evaluate to one async function`
1557
- });
1558
- case "program-failed": return yield* CodeProgramFailedError.make({
1559
- implementation: dynamicWorkerImplementation,
1560
- reason: outcome.value.reason,
1561
- thrown: outcome.value.thrown,
1562
- message: outcome.value.message.slice(0, 8e3),
1563
- logs: outcome.value.logs
1564
- });
1565
- case "log-limit": return yield* CodeOutputLimitError.make({
1566
- implementation: dynamicWorkerImplementation,
1567
- surface: "logs",
1568
- limit: request.limits.maxLogBytes,
1569
- observed: outcome.value.observed,
1570
- logs: outcome.value.logs
1571
- });
1572
- case "argument-limit": return yield* CodeOutputLimitError.make({
1573
- implementation: dynamicWorkerImplementation,
1574
- surface: "host-call-argument",
1575
- limit: request.limits.maxHostCallArgumentBytes,
1576
- observed: outcome.value.observed,
1577
- logs: outcome.value.logs
1578
- });
1579
- case "result-limit": return yield* CodeOutputLimitError.make({
1580
- implementation: dynamicWorkerImplementation,
1581
- surface: "result",
1582
- limit: request.limits.maxResultBytes,
1583
- observed: outcome.value.observed,
1584
- logs: outcome.value.logs
1585
- });
1586
- case "host-call-limit": return yield* CodeHostCallLimitError.make({
1587
- implementation: dynamicWorkerImplementation,
1588
- limit: request.limits.maxHostCalls,
1589
- logs: outcome.value.logs
1590
- });
1591
- case "protocol": return yield* CodeExecutionProtocolError.make({
1592
- implementation: dynamicWorkerImplementation,
1593
- message: outcome.value.message.slice(0, 8e3)
1594
- });
1595
- }
1596
- });
1597
- /**
1598
- * Expected worker-level failures map into the typed union with bounded
1599
- * diagnostics; anything unrecognized stays a start/termination error rather
1600
- * than a fabricated program result.
1601
- */
1602
- const classifyWorkerFailure = (cause, maxWallTime) => {
1603
- const text = (() => {
1604
- try {
1605
- return cause instanceof Error ? `${cause.name}: ${cause.message}` : String(cause);
1606
- } catch {
1607
- return "[unserializable worker failure]";
1608
- }
1609
- })();
1610
- if (/syntaxerror|failed to (compile|parse)/i.test(text)) return CodeSourceError.make({
1611
- implementation: dynamicWorkerImplementation,
1612
- reason: "invalid",
1613
- message: text.slice(0, 8e3)
1614
- });
1615
- if (/cpu/i.test(text)) return CodeExecutionTimeoutError.make({
1616
- implementation: dynamicWorkerImplementation,
1617
- kind: "cpu",
1618
- maxWallTime,
1619
- logs: []
1620
- });
1621
- if (/failed to start worker/i.test(text)) return CodeExecutorStartError.make({
1622
- implementation: dynamicWorkerImplementation,
1623
- message: text.slice(0, 8e3),
1624
- cause
1625
- });
1626
- return CodeExecutorTerminatedError.make({
1627
- implementation: dynamicWorkerImplementation,
1628
- message: text.slice(0, 8e3)
1629
- });
1630
- };
1631
- /** Layer building the Dynamic Worker `CodeExecutor` from resolved bindings. */
1632
- const dynamicWorkerCodeExecutorLayer = (options) => Layer.succeed(CodeExecutor)(CodeExecutor.of({ execute: makeExecute(options) }));
1633
- //#endregion
1634
- export { AbortRecorded, AdminExplainRequest, AdminFailed, AdminFailure, AdminResponse, AdminVerifyRequest, AdmissionLimitExceeded, ApprovalRecorded, CLOUDFLARE_DATABASE_CAP_BYTES, CLOUDFLARE_RUNTIME_DEFAULTS, CloudflareAdmissionLimitsValue, CloudflareBindingError, CloudflareConversationClient, CloudflareDurableRuntime, CloudflareDurableRuntimeConfig, CloudflareDurableRuntimeConfigValue, CloudflarePlatformConfigError, CodeModeHostEntrypoint, 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, dynamicWorkerCodeExecutorLayer, dynamicWorkerImplementation, encodeAbortCommand, encodeAdminResponse, encodeApprovalDecisionCommand, encodeHostResponse, encodeObservePageRequest, encodeReceipt, encodeSubmitRequest, encodeUnknownResolutionCommand, makeConversationObjectClass };
1635
-
1636
- //# sourceMappingURL=index.mjs.map
1
+ import { t as CloudflareBindings_exports } from "./CloudflareBindings.mjs";
2
+ import { t as CloudflareConfig_exports } from "./CloudflareConfig.mjs";
3
+ import { t as Alarm_exports } from "./Alarm.mjs";
4
+ import { t as CloudflareBrowser_exports } from "./CloudflareBrowser-DV6kya1H.mjs";
5
+ import { t as CloudflareCodeMode_exports } from "./CloudflareCodeMode.mjs";
6
+ import { t as CloudflareMemory_exports } from "./CloudflareMemory.mjs";
7
+ import { t as CloudflareThreadClient_exports } from "./CloudflareThreadClient.mjs";
8
+ import { t as CloudflareScheduling_exports } from "./CloudflareScheduling.mjs";
9
+ import { t as CloudflareSubscriptions_exports } from "./CloudflareSubscriptions.mjs";
10
+ import { t as WakeScheduler_exports } from "./WakeScheduler.mjs";
11
+ import { l as ThreadObject_exports } from "./ThreadObject-DvRG0dDz.mjs";
12
+ import { t as CloudflareAiGateway_exports } from "./CloudflareAiGateway.mjs";
13
+ export { Alarm_exports as Alarm, CloudflareAiGateway_exports as CloudflareAiGateway, CloudflareBindings_exports as CloudflareBindings, CloudflareBrowser_exports as CloudflareBrowser, CloudflareCodeMode_exports as CloudflareCodeMode, CloudflareConfig_exports as CloudflareConfig, CloudflareMemory_exports as CloudflareMemory, CloudflareScheduling_exports as CloudflareScheduling, CloudflareSubscriptions_exports as CloudflareSubscriptions, CloudflareThreadClient_exports as CloudflareThreadClient, ThreadObject_exports as ThreadObject, WakeScheduler_exports as WakeScheduler };