@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
@@ -1,768 +0,0 @@
1
- import type { AgentId } from "@effect-agent/core";
2
- import { SubmissionId } from "@effect-agent/core";
3
- import {
4
- AppendConflict,
5
- ConversationNotMaterialized,
6
- ConversationRead,
7
- ConversationStore,
8
- ConversationStoreError,
9
- DigestError,
10
- DurableAgentRuntime,
11
- DurableRuntimeFailpointError,
12
- FenceRejected,
13
- IntegrityReport,
14
- LedgerError,
15
- ObligationReport,
16
- ObligationThresholds,
17
- OperationAuthorizationRequest,
18
- OperationAuthorizer,
19
- OperationDenied,
20
- OwnershipLost,
21
- PersistedJson,
22
- RecoveryExplanation,
23
- RecoveryReport,
24
- RetryCommand,
25
- RetryRefused,
26
- RunJournalError,
27
- SettlementConflict,
28
- SubmissionLedger,
29
- SubmissionLookupByKey,
30
- type DurableSubmitAgent,
31
- } from "@effect-agent/session";
32
- import type { DurableObject as CloudflareDurableObject } from "cloudflare:workers";
33
- import { Effect, Layer, Option, Schema, Stream } from "effect";
34
- import {
35
- DurableObject as EffectCfDurableObject,
36
- DurableObjectState as EffectCfDurableObjectState,
37
- WorkerEnvironment,
38
- } from "effect-cf";
39
-
40
- import {
41
- ConversationMaintenance,
42
- DurableAlarmError,
43
- DurableAlarmService,
44
- type MaintenancePassFailure,
45
- } from "./alarm.ts";
46
- import {
47
- ConversationObjectIdentity,
48
- DurableObjectContext,
49
- ConversationObjectNamespace,
50
- conversationNamespaceFromEnv,
51
- type CloudflareBindingError,
52
- } from "./bindings.ts";
53
- import {
54
- AbortRecorded,
55
- ApprovalRecorded,
56
- HostFailed,
57
- HostProtocolError,
58
- ObservedPage,
59
- SettlementReached,
60
- SubmitSucceeded,
61
- UnknownResolutionRecorded,
62
- boundHostDiagnostic,
63
- decodeAbortCommand,
64
- decodeApprovalDecisionCommand,
65
- decodeObservePageRequest,
66
- decodeReceipt,
67
- decodeSubmitRequest,
68
- decodeUnknownResolutionCommand,
69
- encodeHostResponse,
70
- type HostFailure,
71
- type HostResponse,
72
- } from "./client.ts";
73
- import { AdmissionLimitExceeded, CloudflareDurableRuntimeConfig } from "./config.ts";
74
- import {
75
- CloudflareDurableRuntime,
76
- ConversationObjectPorts,
77
- type CloudflareDurableRuntimeInitializationError,
78
- type CloudflareDurableRuntimeOptions,
79
- type CloudflareDurableRuntimeServices,
80
- } from "./layers.ts";
81
-
82
- /**
83
- * `makeConversationObjectClass(options, observability?)` — the Conversation Durable Object
84
- * (plan §1.4,
85
- * D-P6-1): a factory returning a class that applications export from their Worker entry.
86
- * One SQLite-backed Object per Conversation is the serialized owner (durability §6); the
87
- * Object never runs `runResolvedWorker`'s infinite loop — each ingress event or alarm runs
88
- * ONE bounded `runRecovery` + `processConversationResolved` pass, and the persisted alarm
89
- * (the single multiplexed slot, D-P6-2) finishes accepted work across evictions WITHOUT any
90
- * incoming request.
91
- *
92
- * Constructor gate (`blockConcurrencyWhile`) is LOCAL-ONLY: schema migration and the
93
- * exact-version check, configuration decode, and the defensive ensure-alarm half of the
94
- * alarm invariant. It deliberately does NOT run the recovery pass: parent recovery can
95
- * require child-Object reads and vice versa, and two Objects blocked in constructor gates
96
- * awaiting each other's RPC would deadlock (plan §1.4). Instead every pass runs
97
- * `runRecovery` BEFORE any claim, so reconciliation still strictly precedes new work.
98
- */
99
-
100
- /** Construction options for one deployed Conversation Object class. */
101
- export interface ConversationObjectOptions extends CloudflareDurableRuntimeOptions {
102
- /**
103
- * Name of the Worker `env` binding carrying THIS class's `DurableObjectNamespace` — the
104
- * Object's route back to sibling Conversation Objects for the WP2 cross-Object port calls
105
- * and remote wakes (DEPLOY-010: the binding enters through a Layer, never ambiently).
106
- */
107
- readonly namespaceBinding: string;
108
- }
109
-
110
- type EndpointServices = CloudflareDurableRuntimeServices | DurableObjectContext;
111
- type RuntimeServices = EndpointServices | ConversationObjectNamespace;
112
- type ConversationObjectInitializationError =
113
- | CloudflareDurableRuntimeInitializationError
114
- | CloudflareBindingError
115
- | MaintenancePassFailure;
116
-
117
- /** Port envelope tags whose owner-side execution durably mutates this Object's lane. */
118
- const MUTATING_PORT_TAGS: ReadonlySet<string> = new Set([
119
- "LedgerAdmit",
120
- "LedgerMarkReady",
121
- "LedgerRequestAbort",
122
- "LedgerRecordChildSettled",
123
- "StoreMaterialize",
124
- "StoreAppend",
125
- ]);
126
-
127
- const isMutatingPortRequest = (encoded: unknown): boolean =>
128
- typeof encoded === "object" &&
129
- encoded !== null &&
130
- "_tag" in encoded &&
131
- typeof encoded._tag === "string" &&
132
- MUTATING_PORT_TAGS.has(encoded._tag);
133
-
134
- /** The literal encoded `PortFailed(PortProtocolError)` fallback (same shape as WP2's). */
135
- const encodedPortProtocolFailure = (message: string): unknown => ({
136
- _tag: "PortFailed",
137
- failure: { _tag: "PortProtocolError", message: boundHostDiagnostic(message) },
138
- });
139
-
140
- const protocolFailure = (context: string) => (error: { readonly message: string }) =>
141
- HostProtocolError.make({
142
- message: boundHostDiagnostic(`${context}: ${error.message}`),
143
- });
144
-
145
- /** Fold one endpoint's typed failures into the uniform `HostResponse` envelope. */
146
- const respond = <Result extends HostResponse, Failure extends HostFailure>(
147
- effect: Effect.Effect<Result, Failure, EndpointServices>,
148
- ): Effect.Effect<HostResponse, never, EndpointServices> =>
149
- effect.pipe(
150
- Effect.map((result): HostResponse => result),
151
- Effect.catch((failure) => Effect.succeed<HostResponse>(HostFailed.make({ failure }))),
152
- );
153
-
154
- /** Encode the response envelope; an unencodable response degrades to a protocol failure. */
155
- const encodeResponse = (response: HostResponse): Effect.Effect<unknown> =>
156
- encodeHostResponse(response).pipe(
157
- Effect.catch((error) =>
158
- Effect.succeed<unknown>({
159
- _tag: "HostFailed",
160
- failure: {
161
- _tag: "HostProtocolError",
162
- message: boundHostDiagnostic(`The host response could not be encoded: ${error.message}`),
163
- },
164
- }),
165
- ),
166
- );
167
-
168
- const utf8Bytes = (value: unknown): number =>
169
- new TextEncoder().encode(JSON.stringify(value)).length;
170
-
171
- /**
172
- * The admission-limits gate, BEFORE `runtime.submit` touches the ledger (exit gate
173
- * "resource limits are checked before admission"; DEPLOY-007). A replayed idempotency key is
174
- * exempt: its accepted-work obligation already exists, and returning the original Receipt
175
- * consumes no new quota. Refusals are typed `AdmissionLimitExceeded` and nothing is written.
176
- */
177
- const gateAdmissionLimits = Effect.fn("ConversationObject.gateAdmissionLimits")(
178
- function* (request: {
179
- readonly principal: SubmissionLookupByKey["principal"];
180
- readonly idempotencyKey: SubmissionLookupByKey["idempotencyKey"];
181
- readonly inputPayload: PersistedJson;
182
- }) {
183
- const identity = yield* ConversationObjectIdentity;
184
- const config = yield* CloudflareDurableRuntimeConfig;
185
- const ledger = yield* SubmissionLedger;
186
- const { ctx } = yield* DurableObjectContext;
187
-
188
- const existing = yield* ledger.lookup(
189
- SubmissionLookupByKey.make({
190
- conversationId: identity.conversationId,
191
- principal: request.principal,
192
- idempotencyKey: request.idempotencyKey,
193
- }),
194
- );
195
- if (Option.isSome(existing)) return;
196
-
197
- const inputBytes = utf8Bytes(request.inputPayload);
198
- if (inputBytes > config.limits.maxInputBytes) {
199
- return yield* AdmissionLimitExceeded.make({
200
- limit: "input-bytes",
201
- actual: inputBytes,
202
- maximum: config.limits.maxInputBytes,
203
- });
204
- }
205
-
206
- // One Conversation per Object (durability §5): the local scan IS this lane's queue.
207
- const nonterminal = yield* Stream.runCollect(ledger.scanNonterminal);
208
- if (nonterminal.length >= config.limits.maxQueueDepthPerLane) {
209
- return yield* AdmissionLimitExceeded.make({
210
- limit: "queue-depth",
211
- actual: nonterminal.length,
212
- maximum: config.limits.maxQueueDepthPerLane,
213
- });
214
- }
215
-
216
- const databaseBytes = yield* Effect.sync(() => ctx.storage.sql.databaseSize);
217
- if (databaseBytes > config.limits.maxDatabaseBytes) {
218
- return yield* AdmissionLimitExceeded.make({
219
- limit: "database-bytes",
220
- actual: databaseBytes,
221
- maximum: config.limits.maxDatabaseBytes,
222
- });
223
- }
224
- },
225
- );
226
-
227
- /**
228
- * The submit-capable projection of an Agent Binding on the OBJECT side: the input arrived
229
- * already encoded through the real input schema on the Worker side (`client.ts`), so the
230
- * Object admits the canonical `PersistedJson` payload as-is; the resolved Binding re-derives
231
- * everything else from the stored `(agentId, agentDigests)` at claim time (SUB-023).
232
- */
233
- const passthroughSubmitAgent = (agentId: AgentId): DurableSubmitAgent<typeof PersistedJson> => ({
234
- definition: {
235
- id: agentId,
236
- input: PersistedJson,
237
- },
238
- });
239
-
240
- const submitEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
241
- decodeSubmitRequest(encoded).pipe(
242
- Effect.mapError(protocolFailure("The submit request could not be decoded")),
243
- Effect.flatMap((request) =>
244
- Effect.gen(function* () {
245
- const identity = yield* ConversationObjectIdentity;
246
- const maintenance = yield* ConversationMaintenance;
247
- const runtime = yield* DurableAgentRuntime;
248
- yield* gateAdmissionLimits(request);
249
- // Alarm invariant: the alarm commits BEFORE the admission it will finish (D-P6-2).
250
- yield* maintenance.preArm;
251
- const receipt = yield* runtime.submit(
252
- passthroughSubmitAgent(request.agentId),
253
- request.inputPayload,
254
- {
255
- conversationId: identity.conversationId,
256
- principal: request.principal,
257
- idempotencyKey: request.idempotencyKey,
258
- definitions: request.definitions,
259
- },
260
- );
261
- return SubmitSucceeded.make({ receipt });
262
- }),
263
- ),
264
- respond,
265
- Effect.flatMap(encodeResponse),
266
- );
267
-
268
- const awaitSettlementEndpoint = (
269
- encoded: unknown,
270
- ): Effect.Effect<unknown, never, EndpointServices> =>
271
- decodeReceipt(encoded).pipe(
272
- Effect.mapError(protocolFailure("The receipt could not be decoded")),
273
- Effect.flatMap((receipt) =>
274
- Effect.gen(function* () {
275
- const runtime = yield* DurableAgentRuntime;
276
- const settlement = yield* runtime.awaitSettlement(receipt);
277
- return SettlementReached.make({ settlement });
278
- }),
279
- ),
280
- respond,
281
- Effect.flatMap(encodeResponse),
282
- );
283
-
284
- const observePageEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
285
- decodeObservePageRequest(encoded).pipe(
286
- Effect.mapError(protocolFailure("The observe request could not be decoded")),
287
- Effect.flatMap((request) =>
288
- Effect.gen(function* () {
289
- const identity = yield* ConversationObjectIdentity;
290
- const store = yield* ConversationStore;
291
- // The same fail-closed authorization seam the runtime's `observe` consults (P7 WP1);
292
- // the default reference preserves the possession behavior.
293
- const authorizer = yield* OperationAuthorizer;
294
- yield* authorizer
295
- .authorize(
296
- OperationAuthorizationRequest.make({
297
- operation: "observe",
298
- conversationId: identity.conversationId,
299
- }),
300
- )
301
- .pipe(Effect.catchTag("OperationDenied", deniedToProtocolFailure));
302
- const records = yield* Stream.runCollect(
303
- store.read(
304
- ConversationRead.make({
305
- conversationId: identity.conversationId,
306
- ...(request.afterSequence === undefined
307
- ? {}
308
- : { afterSequence: request.afterSequence }),
309
- limit: request.limit,
310
- }),
311
- ),
312
- );
313
- return ObservedPage.make({ records: [...records] });
314
- }),
315
- ),
316
- respond,
317
- Effect.flatMap(encodeResponse),
318
- );
319
-
320
- const abortEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
321
- decodeAbortCommand(encoded).pipe(
322
- Effect.mapError(protocolFailure("The abort command could not be decoded")),
323
- Effect.flatMap((command) =>
324
- Effect.gen(function* () {
325
- const maintenance = yield* ConversationMaintenance;
326
- const runtime = yield* DurableAgentRuntime;
327
- yield* maintenance.preArm;
328
- const intent = yield* runtime.abort(command);
329
- return AbortRecorded.make({ intent });
330
- }),
331
- ),
332
- respond,
333
- Effect.flatMap(encodeResponse),
334
- );
335
-
336
- /**
337
- * The pre-P7 host protocol's failure union does not carry `OperationDenied` (the Worker client
338
- * predates the authorizer). This assembly always runs the default possession authorizer — no
339
- * `CloudflareDurableRuntimeOptions` authorizer lever exists yet — so a denial here is
340
- * unreachable today; if one ever surfaces it degrades to the protocol failure instead of an
341
- * out-of-contract throw. The four P7 admin entry points below carry `OperationDenied` typed.
342
- */
343
- const deniedToProtocolFailure = (
344
- denied: OperationDenied,
345
- ): Effect.Effect<never, HostProtocolError> =>
346
- Effect.fail(
347
- HostProtocolError.make({
348
- message: boundHostDiagnostic(
349
- `The ${denied.operation} operation was denied: ${denied.reason}`,
350
- ),
351
- }),
352
- );
353
-
354
- const resolveApprovalEndpoint = (
355
- encoded: unknown,
356
- ): Effect.Effect<unknown, never, EndpointServices> =>
357
- decodeApprovalDecisionCommand(encoded).pipe(
358
- Effect.mapError(protocolFailure("The approval command could not be decoded")),
359
- Effect.flatMap((command) =>
360
- Effect.gen(function* () {
361
- const maintenance = yield* ConversationMaintenance;
362
- const runtime = yield* DurableAgentRuntime;
363
- yield* maintenance.preArm;
364
- const intent = yield* runtime
365
- .resolveApproval(command)
366
- .pipe(Effect.catchTag("OperationDenied", deniedToProtocolFailure));
367
- return ApprovalRecorded.make({ intent });
368
- }),
369
- ),
370
- respond,
371
- Effect.flatMap(encodeResponse),
372
- );
373
-
374
- const resolveUnknownEndpoint = (
375
- encoded: unknown,
376
- ): Effect.Effect<unknown, never, EndpointServices> =>
377
- decodeUnknownResolutionCommand(encoded).pipe(
378
- Effect.mapError(protocolFailure("The resolution command could not be decoded")),
379
- Effect.flatMap((command) =>
380
- Effect.gen(function* () {
381
- const maintenance = yield* ConversationMaintenance;
382
- const runtime = yield* DurableAgentRuntime;
383
- yield* maintenance.preArm;
384
- const intent = yield* runtime
385
- .resolveUnknown(command)
386
- .pipe(Effect.catchTag("OperationDenied", deniedToProtocolFailure));
387
- return UnknownResolutionRecorded.make({ intent });
388
- }),
389
- ),
390
- respond,
391
- Effect.flatMap(encodeResponse),
392
- );
393
-
394
- // ---------------------------------------------------------------------------
395
- // P7 administrative entry points (plan §3): explain/verify/retry/obligations over the SAME
396
- // envelope discipline as the host protocol — closed request/response Schema unions, typed
397
- // failures that re-decode to identical tags, protocol anomalies answered typed. The envelopes
398
- // live here (not `client.ts`) because no Worker-side client consumption exists yet; `wake`
399
- // already exists as the `wake()` entry point.
400
- // ---------------------------------------------------------------------------
401
-
402
- /** Explain one Submission (`submissionId` present) or every nonterminal lane member. */
403
- export class AdminExplainRequest extends Schema.Class<AdminExplainRequest>(
404
- "@effect-agent/platform-cloudflare/AdminExplainRequest",
405
- )({
406
- submissionId: Schema.optionalKey(SubmissionId),
407
- }) {}
408
-
409
- /** Verify carries no parameters — the addressed Object IS the lane. */
410
- export class AdminVerifyRequest extends Schema.Class<AdminVerifyRequest>(
411
- "@effect-agent/platform-cloudflare/AdminVerifyRequest",
412
- )({}) {}
413
-
414
- /** Every typed failure of the four admin entry points, plus the protocol's own errors. */
415
- export const AdminFailure = Schema.Union([
416
- OperationDenied,
417
- RetryRefused,
418
- LedgerError,
419
- RunJournalError,
420
- DigestError,
421
- OwnershipLost,
422
- SettlementConflict,
423
- ConversationStoreError,
424
- ConversationNotMaterialized,
425
- AppendConflict,
426
- FenceRejected,
427
- DurableRuntimeFailpointError,
428
- DurableAlarmError,
429
- HostProtocolError,
430
- ]);
431
- export type AdminFailure = typeof AdminFailure.Type;
432
-
433
- export class ExplainedRecovery extends Schema.TaggedClass<ExplainedRecovery>(
434
- "@effect-agent/platform-cloudflare/ExplainedRecovery",
435
- )("ExplainedRecovery", {
436
- explanations: Schema.Array(RecoveryExplanation).check(Schema.isMaxLength(1_024)),
437
- }) {}
438
-
439
- export class VerifiedIntegrity extends Schema.TaggedClass<VerifiedIntegrity>(
440
- "@effect-agent/platform-cloudflare/VerifiedIntegrity",
441
- )("VerifiedIntegrity", {
442
- report: IntegrityReport,
443
- }) {}
444
-
445
- export class RetryExecuted extends Schema.TaggedClass<RetryExecuted>(
446
- "@effect-agent/platform-cloudflare/RetryExecuted",
447
- )("RetryExecuted", {
448
- report: RecoveryReport,
449
- }) {}
450
-
451
- export class ObligationsScanned extends Schema.TaggedClass<ObligationsScanned>(
452
- "@effect-agent/platform-cloudflare/ObligationsScanned",
453
- )("ObligationsScanned", {
454
- report: ObligationReport,
455
- }) {}
456
-
457
- /** The admin entry point failed TYPED on the Object; the failure re-decodes verbatim. */
458
- export class AdminFailed extends Schema.TaggedClass<AdminFailed>(
459
- "@effect-agent/platform-cloudflare/AdminFailed",
460
- )("AdminFailed", {
461
- failure: AdminFailure,
462
- }) {}
463
-
464
- /** The uniform answer of one admin entry point. Callers narrow by the tag their call implies. */
465
- export const AdminResponse = Schema.Union([
466
- ExplainedRecovery,
467
- VerifiedIntegrity,
468
- RetryExecuted,
469
- ObligationsScanned,
470
- AdminFailed,
471
- ]);
472
- export type AdminResponse = typeof AdminResponse.Type;
473
-
474
- export const decodeAdminExplainRequest = Schema.decodeUnknownEffect(AdminExplainRequest);
475
- export const decodeAdminVerifyRequest = Schema.decodeUnknownEffect(AdminVerifyRequest);
476
- export const decodeRetryCommand = Schema.decodeUnknownEffect(RetryCommand);
477
- export const decodeObligationThresholds = Schema.decodeUnknownEffect(ObligationThresholds);
478
- export const encodeAdminResponse = Schema.encodeEffect(AdminResponse);
479
- export const decodeAdminResponse = Schema.decodeUnknownEffect(AdminResponse);
480
-
481
- /** Fold one admin endpoint's typed failures into the uniform `AdminResponse` envelope. */
482
- const respondAdmin = <Result extends AdminResponse, Failure extends AdminFailure>(
483
- effect: Effect.Effect<Result, Failure, EndpointServices>,
484
- ): Effect.Effect<AdminResponse, never, EndpointServices> =>
485
- effect.pipe(
486
- Effect.map((result): AdminResponse => result),
487
- Effect.catch((failure) => Effect.succeed<AdminResponse>(AdminFailed.make({ failure }))),
488
- );
489
-
490
- /** Encode the admin response envelope; an unencodable response degrades to a protocol failure. */
491
- const encodeAdminResponseTotal = (response: AdminResponse): Effect.Effect<unknown> =>
492
- encodeAdminResponse(response).pipe(
493
- Effect.catch((error) =>
494
- Effect.succeed<unknown>({
495
- _tag: "AdminFailed",
496
- failure: {
497
- _tag: "HostProtocolError",
498
- message: boundHostDiagnostic(`The admin response could not be encoded: ${error.message}`),
499
- },
500
- }),
501
- ),
502
- );
503
-
504
- const explainEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
505
- decodeAdminExplainRequest(encoded).pipe(
506
- Effect.mapError(protocolFailure("The explain request could not be decoded")),
507
- Effect.flatMap((request) =>
508
- Effect.gen(function* () {
509
- const identity = yield* ConversationObjectIdentity;
510
- const runtime = yield* DurableAgentRuntime;
511
- const explanations =
512
- request.submissionId === undefined
513
- ? yield* runtime.explainConversation(identity.conversationId)
514
- : [yield* runtime.explain(request.submissionId)];
515
- return ExplainedRecovery.make({ explanations });
516
- }),
517
- ),
518
- respondAdmin,
519
- Effect.flatMap(encodeAdminResponseTotal),
520
- );
521
-
522
- const verifyEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
523
- decodeAdminVerifyRequest(encoded).pipe(
524
- Effect.mapError(protocolFailure("The verify request could not be decoded")),
525
- Effect.flatMap(() =>
526
- Effect.gen(function* () {
527
- const identity = yield* ConversationObjectIdentity;
528
- const runtime = yield* DurableAgentRuntime;
529
- const report = yield* runtime.verify(identity.conversationId);
530
- return VerifiedIntegrity.make({ report });
531
- }),
532
- ),
533
- respondAdmin,
534
- Effect.flatMap(encodeAdminResponseTotal),
535
- );
536
-
537
- const retryEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
538
- decodeRetryCommand(encoded).pipe(
539
- Effect.mapError(protocolFailure("The retry command could not be decoded")),
540
- Effect.flatMap((command) =>
541
- Effect.gen(function* () {
542
- const maintenance = yield* ConversationMaintenance;
543
- const runtime = yield* DurableAgentRuntime;
544
- // Alarm invariant: retry may repair durable state, so the alarm that will finish the
545
- // lane commits BEFORE the mutation (D-P6-2), exactly like abort.
546
- yield* maintenance.preArm;
547
- const report = yield* runtime.retry(command);
548
- return RetryExecuted.make({ report });
549
- }),
550
- ),
551
- respondAdmin,
552
- Effect.flatMap(encodeAdminResponseTotal),
553
- );
554
-
555
- const obligationsEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
556
- decodeObligationThresholds(encoded).pipe(
557
- Effect.mapError(protocolFailure("The obligation thresholds could not be decoded")),
558
- Effect.flatMap((thresholds) =>
559
- Effect.gen(function* () {
560
- const runtime = yield* DurableAgentRuntime;
561
- const report = yield* runtime.scanObligations(thresholds);
562
- return ObligationsScanned.make({ report });
563
- }),
564
- ),
565
- respondAdmin,
566
- Effect.flatMap(encodeAdminResponseTotal),
567
- );
568
-
569
- /**
570
- * Owner-side `portCall`: pre-arm before a mutating envelope (a routed admission committed by
571
- * THIS Object must already carry the alarm that will finish it), execute on the LOCAL facets
572
- * (never the routed decorators), then arm an immediate alarm so the mutated lane is
573
- * processed promptly. Protocol anomalies answer `PortFailed(PortProtocolError)`.
574
- */
575
- const portCallEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
576
- Effect.gen(function* () {
577
- const ports = yield* ConversationObjectPorts;
578
- const maintenance = yield* ConversationMaintenance;
579
- const alarm = yield* DurableAlarmService;
580
- const mutating = isMutatingPortRequest(encoded);
581
- if (mutating) {
582
- const preArmed = yield* maintenance.preArm.pipe(Effect.exit);
583
- if (preArmed._tag === "Failure") {
584
- // Without the committed alarm the invariant cannot be promised; refuse the mutation.
585
- return encodedPortProtocolFailure(
586
- "The owner Object could not arm its maintenance alarm before the mutation.",
587
- );
588
- }
589
- }
590
- const response = yield* ports.handle(encoded);
591
- if (mutating) {
592
- // Prompt processing hint; the pre-armed alarm already guarantees convergence.
593
- yield* alarm.scheduleNow.pipe(
594
- Effect.catch((error) =>
595
- Effect.logWarning("ConversationObject.portCall: immediate re-arm failed", error),
596
- ),
597
- );
598
- }
599
- return response;
600
- });
601
-
602
- const wakeEndpoint: Effect.Effect<void, never, EndpointServices> = Effect.gen(function* () {
603
- const alarm = yield* DurableAlarmService;
604
- // Wake hints are droppable by contract: a failed alarm write is logged and swallowed; the
605
- // sender's own alarm/scan pairing (or this Object's next entry point) restores liveness.
606
- yield* alarm.scheduleNow.pipe(
607
- Effect.catch((error) => Effect.logWarning("ConversationObject.wake dropped", error)),
608
- );
609
- });
610
-
611
- const alarmEndpoint: Effect.Effect<void, MaintenancePassFailure, EndpointServices> = Effect.gen(
612
- function* () {
613
- const maintenance = yield* ConversationMaintenance;
614
- // Typed pass failures propagate: the rejected promise makes workerd retry the alarm
615
- // (at-least-once delivery), and the pass's own pre-arm keeps the slot committed meanwhile.
616
- yield* maintenance.pass;
617
- },
618
- );
619
-
620
- const gateEndpoint: Effect.Effect<void, MaintenancePassFailure, EndpointServices> = Effect.gen(
621
- function* () {
622
- // Forcing ConversationMaintenance forces the whole Layer stack: migration + exact-version
623
- // check + configuration decode (DEPLOY-008 fails typed here, before any mutation), then
624
- // the defensive local ensure-alarm half of the invariant. LOCAL-ONLY by construction.
625
- const maintenance = yield* ConversationMaintenance;
626
- yield* maintenance.ensureAlarm;
627
- },
628
- );
629
-
630
- /**
631
- * Adapter from effect-cf's native Durable Object services to Effect Agent's existing platform
632
- * ports. effect-cf owns the cached ManagedRuntime and supplies these values once per Object
633
- * incarnation; the durable runtime continues to depend only on the narrow services below.
634
- */
635
- const effectCfPlatformLayer = (
636
- namespaceBinding: string,
637
- ): Layer.Layer<
638
- DurableObjectContext | ConversationObjectNamespace,
639
- CloudflareBindingError,
640
- EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment
641
- > => {
642
- const context = Layer.effect(DurableObjectContext)(
643
- Effect.gen(function* () {
644
- const state = yield* EffectCfDurableObjectState.DurableObjectState;
645
- const env = yield* WorkerEnvironment;
646
- return DurableObjectContext.of({ ctx: state.raw, env });
647
- }),
648
- );
649
- const namespace = Layer.effect(ConversationObjectNamespace)(
650
- Effect.gen(function* () {
651
- const env = yield* WorkerEnvironment;
652
- const binding = yield* conversationNamespaceFromEnv(env, namespaceBinding);
653
- return ConversationObjectNamespace.of({ namespace: binding });
654
- }),
655
- );
656
- return Layer.merge(context, namespace);
657
- };
658
-
659
- /** The public endpoint surface of one Conversation Object instance. */
660
- export interface ConversationObjectInstance extends CloudflareDurableObject {
661
- submitEncoded(encoded: unknown): Promise<unknown>;
662
- awaitSettlementEncoded(encoded: unknown): Promise<unknown>;
663
- observePage(encoded: unknown): Promise<unknown>;
664
- abortEncoded(encoded: unknown): Promise<unknown>;
665
- resolveApprovalEncoded(encoded: unknown): Promise<unknown>;
666
- resolveUnknownEncoded(encoded: unknown): Promise<unknown>;
667
- explainEncoded(encoded: unknown): Promise<unknown>;
668
- verifyEncoded(encoded: unknown): Promise<unknown>;
669
- retryEncoded(encoded: unknown): Promise<unknown>;
670
- obligationsEncoded(encoded: unknown): Promise<unknown>;
671
- portCall(encoded: unknown): Promise<unknown>;
672
- wake(): Promise<void>;
673
- alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> | void;
674
- }
675
-
676
- /** The constructor shape workerd instantiates for each Conversation Object. */
677
- export interface ConversationObjectClass {
678
- new (ctx: DurableObjectState, env: Cloudflare.Env): ConversationObjectInstance;
679
- }
680
-
681
- /**
682
- * Build the application's Conversation Object class (export it from the Worker entry).
683
- * effect-cf owns the cached ManagedRuntime, native RPC methods, event scopes, and post-handler
684
- * OTLP flush scheduling for RPC and alarm events. The optional outer Layer is built per native
685
- * event, so a host can install Tracer/Logger/Metric services and `OtlpExporter.Flusher` without
686
- * Effect Agent owning exporter lifecycle machinery.
687
- */
688
- export const makeConversationObjectClass = <EventLayerError = never, EventServices = never>(
689
- options: ConversationObjectOptions,
690
- observability?: Layer.Layer<
691
- EventServices,
692
- EventLayerError,
693
- | DurableObjectContext
694
- | ConversationObjectNamespace
695
- | EffectCfDurableObjectState.DurableObjectState
696
- | WorkerEnvironment
697
- >,
698
- ): ConversationObjectClass => {
699
- const application: Layer.Layer<
700
- RuntimeServices,
701
- CloudflareDurableRuntimeInitializationError | CloudflareBindingError,
702
- EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment
703
- > = CloudflareDurableRuntime.layer(options).pipe(
704
- Layer.provideMerge(effectCfPlatformLayer(options.namespaceBinding)),
705
- );
706
-
707
- // The storage/config Layer must acquire inside Cloudflare's constructor gate. effect-cf owns
708
- // the ManagedRuntime, while this effectContext ensures its first Layer build enters the gate
709
- // before migration, compatibility checks, or alarm inspection touch Object storage.
710
- const runtime: Layer.Layer<
711
- RuntimeServices,
712
- ConversationObjectInitializationError,
713
- EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment
714
- > = Layer.effectContext(
715
- Effect.gen(function* () {
716
- const state = yield* EffectCfDurableObjectState.DurableObjectState;
717
- const scope = yield* Effect.scope;
718
- return yield* state.blockConcurrencyWhile(
719
- Effect.gen(function* () {
720
- const services = yield* Layer.buildWithScope(application, scope);
721
- yield* gateEndpoint.pipe(Effect.provide(services));
722
- return services;
723
- }),
724
- );
725
- }),
726
- );
727
-
728
- const rpc = {
729
- submitEncoded: (encoded: unknown) => submitEndpoint(encoded),
730
- awaitSettlementEncoded: (encoded: unknown) => awaitSettlementEndpoint(encoded),
731
- observePage: (encoded: unknown) => observePageEndpoint(encoded),
732
- abortEncoded: (encoded: unknown) => abortEndpoint(encoded),
733
- resolveApprovalEncoded: (encoded: unknown) => resolveApprovalEndpoint(encoded),
734
- resolveUnknownEncoded: (encoded: unknown) => resolveUnknownEndpoint(encoded),
735
- explainEncoded: (encoded: unknown) => explainEndpoint(encoded),
736
- verifyEncoded: (encoded: unknown) => verifyEndpoint(encoded),
737
- retryEncoded: (encoded: unknown) => retryEndpoint(encoded),
738
- obligationsEncoded: (encoded: unknown) => obligationsEndpoint(encoded),
739
- portCall: (encoded: unknown) => portCallEndpoint(encoded),
740
- wake: () => wakeEndpoint,
741
- } satisfies EffectCfDurableObject.DurableObjectRpc<RuntimeServices | EventServices>;
742
-
743
- const EffectCfConversationObject = EffectCfDurableObject.make<
744
- RuntimeServices,
745
- ConversationObjectInitializationError,
746
- EventServices,
747
- EventLayerError,
748
- typeof rpc
749
- >(runtime, {
750
- ...(observability === undefined ? {} : { eventLayer: observability }),
751
- // Force the gated runtime Layer when Cloudflare loads this Object incarnation. Recovery stays
752
- // in each bounded pass so cross-Object initialization cannot deadlock.
753
- initialize: Effect.void,
754
- rpc,
755
- alarm: () => alarmEndpoint,
756
- });
757
-
758
- // effect-cf's class type keeps `alarm` optional even when the handler option is present. This
759
- // concrete override reflects this factory's stronger contract while delegating execution to
760
- // the effect-cf runtime unchanged.
761
- class ConversationObject extends EffectCfConversationObject {
762
- override alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> | void {
763
- return super.alarm?.(alarmInfo);
764
- }
765
- }
766
-
767
- return ConversationObject;
768
- };