@systemfsoftware/agent-platform-cloudflare 0.0.0-bootstrap.0 → 0.1.0-beta.192

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 (143) hide show
  1. package/LICENSE +21 -0
  2. package/dist/Alarm-CbhflIzz.mjs +1931 -0
  3. package/dist/Alarm-CbhflIzz.mjs.map +1 -0
  4. package/dist/Alarm-Nz1gIjfv.d.mts +252 -0
  5. package/dist/Alarm.d.mts +3 -0
  6. package/dist/Alarm.mjs +3 -0
  7. package/dist/BrowserCredentials-BWC4RqRn.d.mts +116 -0
  8. package/dist/BrowserCredentials-CktBoPgE.mjs +140 -0
  9. package/dist/BrowserCredentials-CktBoPgE.mjs.map +1 -0
  10. package/dist/BrowserCredentials.d.mts +2 -0
  11. package/dist/BrowserCredentials.mjs +1 -0
  12. package/dist/BrowserRestCapture.d.mts +14 -0
  13. package/dist/BrowserRestCapture.mjs +195 -0
  14. package/dist/BrowserRestCapture.mjs.map +1 -0
  15. package/dist/BrowserSession-5bdpqPIT.d.mts +152 -0
  16. package/dist/BrowserSession-Ce8cWN1A.mjs +673 -0
  17. package/dist/BrowserSession-Ce8cWN1A.mjs.map +1 -0
  18. package/dist/BrowserSession.d.mts +3 -0
  19. package/dist/BrowserSession.mjs +4 -0
  20. package/dist/BrowserUse-Bsi830Yv.mjs +263 -0
  21. package/dist/BrowserUse-Bsi830Yv.mjs.map +1 -0
  22. package/dist/BrowserUse-DF8afbNt.d.mts +59 -0
  23. package/dist/BrowserUse.d.mts +2 -0
  24. package/dist/BrowserUse.mjs +1 -0
  25. package/dist/CloudflareAiGateway-By8C8c5z.mjs +79 -0
  26. package/dist/CloudflareAiGateway-By8C8c5z.mjs.map +1 -0
  27. package/dist/CloudflareAiGateway-ukN34014.d.mts +63 -0
  28. package/dist/CloudflareAiGateway.d.mts +2 -0
  29. package/dist/CloudflareAiGateway.mjs +1 -0
  30. package/dist/CloudflareBindings-Dylkir84.mjs +123 -0
  31. package/dist/CloudflareBindings-Dylkir84.mjs.map +1 -0
  32. package/dist/CloudflareBindings-E1Sty9Vq.d.mts +134 -0
  33. package/dist/CloudflareBindings.d.mts +2 -0
  34. package/dist/CloudflareBindings.mjs +1 -0
  35. package/dist/CloudflareBrowser-CmiQpslZ.d.mts +41 -0
  36. package/dist/CloudflareBrowser-DmMCFeIQ.mjs +397 -0
  37. package/dist/CloudflareBrowser-DmMCFeIQ.mjs.map +1 -0
  38. package/dist/CloudflareBrowser.d.mts +3 -0
  39. package/dist/CloudflareBrowser.mjs +1 -0
  40. package/dist/CloudflareCodeMode-BMva6dCs.mjs +627 -0
  41. package/dist/CloudflareCodeMode-BMva6dCs.mjs.map +1 -0
  42. package/dist/CloudflareCodeMode-CeGXZtHv.d.mts +43 -0
  43. package/dist/CloudflareCodeMode.d.mts +2 -0
  44. package/dist/CloudflareCodeMode.mjs +1 -0
  45. package/dist/CloudflareConfig-BFWgEyhH.d.mts +102 -0
  46. package/dist/CloudflareConfig-rBlbPSIZ.mjs +125 -0
  47. package/dist/CloudflareConfig-rBlbPSIZ.mjs.map +1 -0
  48. package/dist/CloudflareConfig.d.mts +2 -0
  49. package/dist/CloudflareConfig.mjs +1 -0
  50. package/dist/CloudflareMemory-Bzp32ZpR.d.mts +120 -0
  51. package/dist/CloudflareMemory-DejIVKBT.mjs +207 -0
  52. package/dist/CloudflareMemory-DejIVKBT.mjs.map +1 -0
  53. package/dist/CloudflareMemory.d.mts +2 -0
  54. package/dist/CloudflareMemory.mjs +1 -0
  55. package/dist/CloudflareScheduling-BleqfC44.mjs +395 -0
  56. package/dist/CloudflareScheduling-BleqfC44.mjs.map +1 -0
  57. package/dist/CloudflareScheduling-vZ7iSR57.d.mts +54 -0
  58. package/dist/CloudflareScheduling.d.mts +2 -0
  59. package/dist/CloudflareScheduling.mjs +1 -0
  60. package/dist/CloudflareSubscriptions-IHSo19MU.d.mts +91 -0
  61. package/dist/CloudflareSubscriptions-S3fZF-Jo.mjs +529 -0
  62. package/dist/CloudflareSubscriptions-S3fZF-Jo.mjs.map +1 -0
  63. package/dist/CloudflareSubscriptions.d.mts +2 -0
  64. package/dist/CloudflareSubscriptions.mjs +1 -0
  65. package/dist/CloudflareThreadClient-BUv9Te1s.d.mts +2141 -0
  66. package/dist/CloudflareThreadClient-K7QJHYpK.mjs +496 -0
  67. package/dist/CloudflareThreadClient-K7QJHYpK.mjs.map +1 -0
  68. package/dist/CloudflareThreadClient.d.mts +3 -0
  69. package/dist/CloudflareThreadClient.mjs +3 -0
  70. package/dist/InteractiveBrowser-CMbA7YPP.d.mts +228 -0
  71. package/dist/InteractiveBrowser-e8ZvxC1C.mjs +2013 -0
  72. package/dist/InteractiveBrowser-e8ZvxC1C.mjs.map +1 -0
  73. package/dist/InteractiveBrowser.d.mts +2 -0
  74. package/dist/InteractiveBrowser.mjs +1 -0
  75. package/dist/LiveText-CfpcZaGb.d.mts +91 -0
  76. package/dist/LiveText-DaF0tN_p.mjs +148 -0
  77. package/dist/LiveText-DaF0tN_p.mjs.map +1 -0
  78. package/dist/LiveText.d.mts +2 -0
  79. package/dist/LiveText.mjs +1 -0
  80. package/dist/R2ToolResultStorage.d.mts +27 -0
  81. package/dist/R2ToolResultStorage.mjs +84 -0
  82. package/dist/R2ToolResultStorage.mjs.map +1 -0
  83. package/dist/ThreadObject-B2-PqnpT.d.mts +390 -0
  84. package/dist/ThreadObject-D1pCeNrq.mjs +1225 -0
  85. package/dist/ThreadObject-D1pCeNrq.mjs.map +1 -0
  86. package/dist/ThreadObject.d.mts +2 -0
  87. package/dist/ThreadObject.mjs +1 -0
  88. package/dist/WakeScheduler-67UeXBYK.d.mts +22 -0
  89. package/dist/WakeScheduler-DV4J4TRe.mjs +69 -0
  90. package/dist/WakeScheduler-DV4J4TRe.mjs.map +1 -0
  91. package/dist/WakeScheduler.d.mts +2 -0
  92. package/dist/WakeScheduler.mjs +1 -0
  93. package/dist/boundary-YrOnE2zO.mjs +41 -0
  94. package/dist/boundary-YrOnE2zO.mjs.map +1 -0
  95. package/dist/browser-failure-CWBBnf1j.mjs +70 -0
  96. package/dist/browser-failure-CWBBnf1j.mjs.map +1 -0
  97. package/dist/index.d.mts +17 -0
  98. package/dist/index.mjs +17 -0
  99. package/dist/prepared-admission-DngoYN74.mjs +57 -0
  100. package/dist/prepared-admission-DngoYN74.mjs.map +1 -0
  101. package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
  102. package/package.json +132 -5
  103. package/src/Alarm.ts +3402 -0
  104. package/src/BrowserCredentials.ts +181 -0
  105. package/src/BrowserRestCapture.ts +383 -0
  106. package/src/BrowserSession.ts +993 -0
  107. package/src/BrowserUse.ts +438 -0
  108. package/src/CloudflareAiGateway.ts +176 -0
  109. package/src/CloudflareBindings.ts +225 -0
  110. package/src/CloudflareBrowser.ts +9 -0
  111. package/src/CloudflareCodeMode.ts +896 -0
  112. package/src/CloudflareConfig.ts +142 -0
  113. package/src/CloudflareMemory.ts +418 -0
  114. package/src/CloudflareScheduling.ts +736 -0
  115. package/src/CloudflareSubscriptions.ts +1032 -0
  116. package/src/CloudflareThreadClient.ts +980 -0
  117. package/src/InteractiveBrowser.ts +3300 -0
  118. package/src/LiveText.ts +145 -0
  119. package/src/R2ToolResultStorage.ts +131 -0
  120. package/src/ThreadObject.ts +1348 -0
  121. package/src/WakeScheduler.ts +102 -0
  122. package/src/index.ts +16 -0
  123. package/src/internal/boundary.ts +53 -0
  124. package/src/internal/browser-binding.ts +483 -0
  125. package/src/internal/browser-credentials.ts +481 -0
  126. package/src/internal/browser-failure.ts +145 -0
  127. package/src/internal/browser-file-selection.ts +146 -0
  128. package/src/internal/browser-quick-action.ts +666 -0
  129. package/src/internal/browser-readonly-live-view.ts +121 -0
  130. package/src/internal/browser-session-lifecycle.ts +200 -0
  131. package/src/internal/crypto.ts +44 -0
  132. package/src/internal/due-queue.ts +452 -0
  133. package/src/internal/host-protocol-error.ts +23 -0
  134. package/src/internal/layers.ts +1181 -0
  135. package/src/internal/live-text-observation.ts +8 -0
  136. package/src/internal/live-text-protocol.ts +59 -0
  137. package/src/internal/live-text.ts +339 -0
  138. package/src/internal/message-delivery.ts +149 -0
  139. package/src/internal/page-function.ts +12 -0
  140. package/src/internal/prepared-admission.ts +83 -0
  141. package/src/internal/progress-wait.ts +121 -0
  142. package/src/internal/transport.ts +53 -0
  143. package/README.md +0 -3
@@ -0,0 +1,1348 @@
1
+ import {
2
+ decodePortRequest,
3
+ encodePortResponse,
4
+ LedgerLookupResult,
5
+ PortFailed,
6
+ PortProtocolError,
7
+ type PortRequest,
8
+ type PortResponse,
9
+ PortSucceeded,
10
+ } from '@systemfsoftware/agent-storage-cloudflare/port-protocol'
11
+ import {
12
+ IntegrityReport,
13
+ ObligationReport,
14
+ ObligationThresholds,
15
+ RecoveryExplanation,
16
+ RetryCommand,
17
+ RetryRefused,
18
+ } from '@systemfsoftware/agent/admin'
19
+ import { DigestError } from '@systemfsoftware/agent/digest'
20
+ import {
21
+ ApprovalSuspensionError,
22
+ DurableAgentRuntime,
23
+ DurableRuntimeConfig,
24
+ type DurableSubmitAgent,
25
+ RecoveryBlocked,
26
+ RecoveryReport,
27
+ } from '@systemfsoftware/agent/durable-agent-runtime'
28
+ import { DurableRuntimeFailpointError } from '@systemfsoftware/agent/durable-failpoint'
29
+ import { type AgentId, type ThreadId } from '@systemfsoftware/agent/identifiers'
30
+ import { SubmissionId } from '@systemfsoftware/agent/identifiers'
31
+ import {
32
+ OperationAuthorizationRequest,
33
+ OperationAuthorizer,
34
+ OperationDenied,
35
+ } from '@systemfsoftware/agent/operation-authorizer'
36
+ import { PersistedJson } from '@systemfsoftware/agent/records'
37
+ import { RunJournalError } from '@systemfsoftware/agent/run-journal'
38
+ import {
39
+ AdmissionPolicyError,
40
+ LedgerError,
41
+ OwnershipLost,
42
+ SettlementConflict,
43
+ SubmissionLedger,
44
+ SubmissionLookupByKey,
45
+ } from '@systemfsoftware/agent/submission-ledger'
46
+ import {
47
+ AppendConflict,
48
+ ThreadNotMaterialized,
49
+ ThreadRead,
50
+ ThreadStore,
51
+ ThreadStoreError,
52
+ } from '@systemfsoftware/agent/thread-store'
53
+ import { WorkDiscoveryUnavailable } from '@systemfsoftware/agent/thread-work'
54
+ import { WakeScheduler } from '@systemfsoftware/agent/wake-scheduler'
55
+ import {
56
+ DurableObject as EffectCfDurableObject,
57
+ DurableObjectAlarm,
58
+ DurableObjectState as EffectCfDurableObjectState,
59
+ WorkerEnvironment,
60
+ } from 'effect-cf'
61
+ import * as Context from 'effect/Context'
62
+ import * as Effect from 'effect/Effect'
63
+ import * as Layer from 'effect/Layer'
64
+ import * as Option from 'effect/Option'
65
+ import * as Schema from 'effect/Schema'
66
+ import type * as Scope from 'effect/Scope'
67
+ import * as Stream from 'effect/Stream'
68
+
69
+ import {
70
+ DurableAlarmError,
71
+ DurableAlarmService,
72
+ type MaintenancePassFailure,
73
+ publishCommitted,
74
+ ThreadMaintenance,
75
+ ThreadMaintenanceAlarm,
76
+ ThreadMutationGate,
77
+ } from './Alarm'
78
+ import {
79
+ type CloudflareBindingError,
80
+ DurableObjectContext,
81
+ threadNamespaceFromEnv,
82
+ ThreadObjectIdentity,
83
+ ThreadObjectNamespace,
84
+ ThreadObjectPlacement,
85
+ } from './CloudflareBindings'
86
+ import { AdmissionLimitExceeded, CloudflareDurableRuntimeConfig } from './CloudflareConfig'
87
+ import {
88
+ AbortRecorded,
89
+ ApprovalRecorded,
90
+ boundHostDiagnostic,
91
+ decodeAbortCommand,
92
+ decodeApprovalDecisionCommand,
93
+ decodeAwaitProgressRequest,
94
+ decodeAwaitSettlementRequest,
95
+ decodeCancelProgressRequest,
96
+ decodeObservePageRequest,
97
+ decodeReceipt,
98
+ decodeSubmitRequest,
99
+ decodeUnknownResolutionCommand,
100
+ encodeHostResponse,
101
+ HostFailed,
102
+ type HostFailure,
103
+ HostProtocolError,
104
+ type HostResponse,
105
+ ObservedPage,
106
+ ProgressCancelled,
107
+ ProgressObserved,
108
+ SettlementReached,
109
+ SettlementRecordReached,
110
+ SubmissionStatusResponse,
111
+ type SubmitRequest,
112
+ SubmitSucceeded,
113
+ UnknownResolutionRecorded,
114
+ } from './CloudflareThreadClient'
115
+ import {
116
+ type CloudflareBootstrapServices,
117
+ type CloudflareDurableRuntimeInitializationError,
118
+ type CloudflareDurableRuntimeOptions,
119
+ type CloudflareDurableRuntimeServices,
120
+ layerConfig,
121
+ ThreadObjectPorts,
122
+ } from './internal/layers'
123
+ import { LiveTextHub } from './internal/live-text'
124
+ import { Request as WatchTextRequest } from './internal/live-text-protocol'
125
+ import { ProgressWaitRegistry } from './internal/progress-wait'
126
+
127
+ export {
128
+ type CloudflareBootstrapServices as BootstrapServices,
129
+ type CloudflareDurableRuntimeInitializationError as InitializationError,
130
+ type CloudflareDurableRuntimeOptions as RuntimeOptions,
131
+ type CloudflareDurableRuntimeServices as Services,
132
+ layer,
133
+ layerConfig,
134
+ layerHostConfig,
135
+ layerInHost,
136
+ type ThreadHostMutation,
137
+ ThreadObjectPorts,
138
+ type ThreadPublicationOptions as PublicationOptions,
139
+ } from './internal/layers'
140
+
141
+ /**
142
+ * `ThreadObject.make(application, options)` — the Thread Durable Object
143
+ * (plan §1.4,
144
+ * D-P6-1): a factory returning a class that applications export from their Worker entry.
145
+ * One SQLite-backed Object per Thread is the serialized owner (durability §6); the
146
+ * Object never runs `runResolvedWorker`'s infinite loop — each ingress event or alarm runs
147
+ * ONE bounded maintenance event with selected-Thread recovery and old cleanup, and the persisted alarm
148
+ * (the single multiplexed slot, D-P6-2) finishes accepted work across evictions WITHOUT any
149
+ * incoming request.
150
+ * `Services` exposes the same owner `SqlClient` used by the Thread stores. Compose optional
151
+ * local repositories after `ThreadObject.layer`; never acquire another independently locked
152
+ * SQL client for the same Object. Exposing the client installs no additional storage schemas.
153
+ *
154
+ * Constructor gate (`blockConcurrencyWhile`) is LOCAL-ONLY: schema migration and the
155
+ * exact-version check, configuration decode, and the defensive ensure-alarm half of the
156
+ * alarm invariant. It deliberately does NOT run the recovery pass: parent recovery can
157
+ * require child-Object reads and vice versa, and two Objects blocked in constructor gates
158
+ * awaiting each other's RPC would deadlock (plan §1.4). Instead every pass runs
159
+ * `runRecovery({ threadId })` BEFORE that Thread's claim; old recovery cannot gate fresh dispatch.
160
+ */
161
+
162
+ type ApplicationAlarmRegistration<ApplicationServices, EventServices, AlarmServices, AlarmError> =
163
+ DurableObjectAlarm.AlarmRegistration<
164
+ AlarmServices,
165
+ | RuntimeServices
166
+ | ApplicationServices
167
+ | EventServices
168
+ | NoInfer<AlarmServices>
169
+ | EffectCfDurableObjectState.DurableObjectState
170
+ | WorkerEnvironment
171
+ | Scope.Scope,
172
+ AlarmError
173
+ >
174
+
175
+ /** Construction options for one deployed Thread Object class. */
176
+ export type Options<
177
+ ApplicationServices = never,
178
+ EventServices = never,
179
+ EventLayerError = never,
180
+ AlarmServices = never,
181
+ AlarmError = never,
182
+ > =
183
+ & BaseOptions<ApplicationServices, EventServices, EventLayerError, AlarmServices>
184
+ & ([AlarmServices] extends [never] ? {
185
+ readonly alarms?: ApplicationAlarmRegistration<
186
+ ApplicationServices,
187
+ EventServices,
188
+ AlarmServices,
189
+ AlarmError
190
+ >
191
+ }
192
+ : {
193
+ readonly alarms: ApplicationAlarmRegistration<
194
+ ApplicationServices,
195
+ EventServices,
196
+ AlarmServices,
197
+ AlarmError
198
+ >
199
+ })
200
+
201
+ interface BaseOptions<
202
+ ApplicationServices,
203
+ EventServices,
204
+ EventLayerError,
205
+ AlarmServices,
206
+ > extends CloudflareDurableRuntimeOptions {
207
+ /** Accept transient native RPC tracing through effect-cf; disabled by default. */
208
+ readonly rpcTracing?: boolean
209
+ /**
210
+ * Name of the Worker `env` binding carrying THIS class's `DurableObjectNamespace` — the
211
+ * Object's route back to sibling Thread Objects for the WP2 cross-Object port calls
212
+ * and remote wakes (DEPLOY-010: the binding enters through a Layer, never ambiently).
213
+ */
214
+ readonly namespaceBinding: string
215
+ /** Acquired and finalized per native event, with access to the complete application runtime. */
216
+ readonly eventLayer?: Layer.Layer<
217
+ EventServices,
218
+ EventLayerError,
219
+ | RuntimeServices
220
+ | ApplicationServices
221
+ | NoInfer<AlarmServices>
222
+ | EffectCfDurableObjectState.DurableObjectState
223
+ | WorkerEnvironment
224
+ >
225
+ }
226
+
227
+ type EndpointServices =
228
+ | CloudflareDurableRuntimeServices
229
+ | CloudflareBootstrapServices
230
+ | DurableObjectContext
231
+ type RuntimeServices = EndpointServices | ThreadObjectNamespace
232
+ type ThreadObjectInitializationError =
233
+ | CloudflareDurableRuntimeInitializationError
234
+ | CloudflareBindingError
235
+ | MaintenancePassFailure
236
+
237
+ /** Classify only a decoded port request so new protocol members cannot bypass pre-arming. */
238
+ const isMutatingPortRequest = (request: PortRequest): boolean => {
239
+ switch (request._tag) {
240
+ case 'WorkerAdmit':
241
+ case 'LedgerAdmit':
242
+ case 'LedgerMarkReady':
243
+ case 'LedgerStopWorker':
244
+ case 'LedgerRequestAbort':
245
+ case 'LedgerRecordChildSettled':
246
+ case 'StoreMaterialize':
247
+ case 'StoreAppend':
248
+ case 'StoreWorkRebuild':
249
+ case 'StoreRangeSeal':
250
+ case 'StoreRangeArchive':
251
+ case 'SettlementPublish':
252
+ case 'MessageDeliveryComplete':
253
+ return true
254
+ case 'LedgerInspectWorker':
255
+ case 'LedgerLookup':
256
+ case 'LedgerResolveAdmission':
257
+ case 'LedgerFundingOwner':
258
+ case 'StoreReadPage':
259
+ case 'StoreReadPrompt':
260
+ case 'StoreReadExecution':
261
+ case 'StoreWorkPage':
262
+ case 'StoreInspectTail':
263
+ case 'StoreReadIdentity':
264
+ case 'StoreCountPeerMessages':
265
+ case 'StoreExport':
266
+ case 'StoreRangePage':
267
+ case 'StoreRangeVerify':
268
+ case 'StoreVerification':
269
+ case 'StoreWorkerCapacity':
270
+ case 'MessageDeliveryList':
271
+ return false
272
+ }
273
+ request satisfies never
274
+
275
+ return false
276
+ }
277
+
278
+ /** The literal encoded `PortFailed(PortProtocolError)` fallback (same shape as WP2's). */
279
+ const encodedPortProtocolFailure = (message: string): unknown => ({
280
+ _tag: 'PortFailed',
281
+ failure: { _tag: 'PortProtocolError', message: boundHostDiagnostic(message) },
282
+ })
283
+
284
+ const protocolFailure = (context: string) => (error: { readonly message: string }) =>
285
+ HostProtocolError.make({
286
+ message: boundHostDiagnostic(`${context}: ${error.message}`),
287
+ })
288
+
289
+ /** Fold one endpoint's typed failures into the uniform `HostResponse` envelope. */
290
+ const respond = <Result extends HostResponse, Failure extends HostFailure>(
291
+ effect: Effect.Effect<Result, Failure, EndpointServices>,
292
+ ): Effect.Effect<HostResponse, never, EndpointServices> =>
293
+ effect.pipe(
294
+ Effect.map((result): HostResponse => result),
295
+ Effect.catch((failure) => Effect.succeed<HostResponse>(HostFailed.make({ failure }))),
296
+ )
297
+
298
+ /** Encode the response envelope; an unencodable response degrades to a protocol failure. */
299
+ const encodeResponse = (response: HostResponse): Effect.Effect<unknown> =>
300
+ encodeHostResponse(response).pipe(
301
+ Effect.catch((error) =>
302
+ Effect.succeed<unknown>({
303
+ _tag: 'HostFailed',
304
+ failure: {
305
+ _tag: 'HostProtocolError',
306
+ message: boundHostDiagnostic(`The host response could not be encoded: ${error.message}`),
307
+ },
308
+ })
309
+ ),
310
+ )
311
+
312
+ const utf8Bytes = (value: PersistedJson): number => new TextEncoder().encode(JSON.stringify(value)).length
313
+
314
+ /**
315
+ * The admission-limits gate, BEFORE `runtime.submit` touches the ledger (exit gate
316
+ * "resource limits are checked before admission"; DEPLOY-007). A replayed idempotency key is
317
+ * exempt: its accepted-work obligation already exists, and returning the original Receipt
318
+ * consumes no new quota. Refusals are typed `AdmissionLimitExceeded` and nothing is written.
319
+ */
320
+ const gateAdmissionLimits = Effect.fnUntraced(function*(
321
+ threadId: ThreadId,
322
+ request: {
323
+ readonly principal: SubmissionLookupByKey['principal']
324
+ readonly idempotencyKey: SubmissionLookupByKey['idempotencyKey']
325
+ readonly inputPayload: PersistedJson
326
+ },
327
+ ) {
328
+ const config = yield* CloudflareDurableRuntimeConfig
329
+ const ledger = yield* SubmissionLedger
330
+ const { ctx } = yield* DurableObjectContext
331
+
332
+ // Admission checks the key durably. The host needs an extra lookup only to
333
+ // exempt a retained receipt when a current limit would otherwise refuse it.
334
+ const refuseFresh = (error: AdmissionLimitExceeded) =>
335
+ ledger
336
+ .lookup(
337
+ SubmissionLookupByKey.make({
338
+ threadId,
339
+ principal: request.principal,
340
+ idempotencyKey: request.idempotencyKey,
341
+ }),
342
+ )
343
+ .pipe(
344
+ Effect.flatMap((existing) => (Option.isSome(existing) ? Effect.void : Effect.fail(error))),
345
+ )
346
+
347
+ const inputBytes = utf8Bytes(request.inputPayload)
348
+
349
+ if (inputBytes > config.limits.maxInputBytes) {
350
+ return yield* refuseFresh(
351
+ AdmissionLimitExceeded.make({
352
+ limit: 'input-bytes',
353
+ actual: inputBytes,
354
+ maximum: config.limits.maxInputBytes,
355
+ }),
356
+ )
357
+ }
358
+
359
+ const queueDepth = yield* Stream.runFold(
360
+ ledger.scanNonterminal,
361
+ () => 0,
362
+ (depth, submission) => depth + (submission.threadId === threadId ? 1 : 0),
363
+ )
364
+
365
+ if (queueDepth >= config.limits.maxQueueDepthPerLane) {
366
+ return yield* refuseFresh(
367
+ AdmissionLimitExceeded.make({
368
+ limit: 'queue-depth',
369
+ actual: queueDepth,
370
+ maximum: config.limits.maxQueueDepthPerLane,
371
+ }),
372
+ )
373
+ }
374
+
375
+ const databaseBytes = yield* Effect.sync(() => ctx.storage.sql.databaseSize)
376
+
377
+ if (databaseBytes > config.limits.maxDatabaseBytes) {
378
+ return yield* refuseFresh(
379
+ AdmissionLimitExceeded.make({
380
+ limit: 'database-bytes',
381
+ actual: databaseBytes,
382
+ maximum: config.limits.maxDatabaseBytes,
383
+ }),
384
+ )
385
+ }
386
+ })
387
+
388
+ /**
389
+ * The submit-capable projection of an Agent Binding on the OBJECT side: the input arrived
390
+ * already encoded through the real input schema on the Worker side (`client.ts`), so the
391
+ * Object admits the canonical `PersistedJson` payload as-is; the resolved Binding re-derives
392
+ * everything else from the stored `(agentId, agentDigests)` at claim time (SUB-023).
393
+ */
394
+ const passthroughSubmitAgent = (agentId: AgentId): DurableSubmitAgent<typeof PersistedJson> => ({
395
+ definition: {
396
+ id: agentId,
397
+ input: PersistedJson,
398
+ },
399
+ })
400
+
401
+ /** A physical owner may hold other Threads; an addressed request cannot act on their IDs. */
402
+ const lookupAddressedSubmission = Effect.fnUntraced(function*(submissionId: SubmissionId) {
403
+ const { threadId } = yield* ThreadObjectIdentity
404
+ const ports = yield* ThreadObjectPorts
405
+ const submission = yield* ports.lookupSubmission(submissionId)
406
+
407
+ if (Option.isSome(submission) && submission.value.threadId !== threadId) {
408
+ return yield* HostProtocolError.make({ message: 'The Submission belongs to another Thread' })
409
+ }
410
+
411
+ return submission
412
+ })
413
+
414
+ const requireSubmissionThread = Effect.fnUntraced(function*(submissionId: SubmissionId) {
415
+ const submission = yield* lookupAddressedSubmission(submissionId)
416
+
417
+ if (Option.isNone(submission)) {
418
+ return yield* LedgerError.make({
419
+ operation: 'addressed Submission lookup',
420
+ message: 'The addressed Thread has no such Submission',
421
+ })
422
+ }
423
+ })
424
+
425
+ const requireReceiptThread = Effect.fnUntraced(function*(threadId: ThreadId) {
426
+ const identity = yield* ThreadObjectIdentity
427
+
428
+ if (threadId !== identity.threadId) {
429
+ return yield* HostProtocolError.make({ message: 'The Receipt belongs to another Thread' })
430
+ }
431
+ })
432
+
433
+ const requirePortThread = (request: PortRequest) => {
434
+ switch (request._tag) {
435
+ case 'SettlementPublish':
436
+ return requireReceiptThread(request.request.append.threadId).pipe(
437
+ Effect.andThen(requireSubmissionThread(request.request.submissionId)),
438
+ )
439
+ case 'MessageDeliveryComplete':
440
+ return requireReceiptThread(request.key.ownerThreadId)
441
+ case 'MessageDeliveryList':
442
+ return requireReceiptThread(request.request.ownerThreadId)
443
+ case 'LedgerLookup':
444
+ return request.request._tag === 'SubmissionLookupById'
445
+ ? lookupAddressedSubmission(request.request.submissionId).pipe(Effect.asVoid)
446
+ : requireReceiptThread(request.request.threadId)
447
+ case 'LedgerMarkReady':
448
+ case 'LedgerRequestAbort':
449
+ return requireSubmissionThread(request.request.submissionId)
450
+ case 'LedgerRecordChildSettled':
451
+ return requireSubmissionThread(request.request.parentSubmissionId)
452
+ case 'LedgerFundingOwner':
453
+ return requireReceiptThread(request.request.threadId).pipe(
454
+ Effect.andThen(requireSubmissionThread(request.request.submissionId)),
455
+ )
456
+ case 'LedgerInspectWorker':
457
+ case 'LedgerStopWorker':
458
+ case 'WorkerAdmit':
459
+ case 'LedgerAdmit':
460
+ case 'LedgerResolveAdmission':
461
+ case 'StoreMaterialize':
462
+ case 'StoreAppend':
463
+ case 'StoreReadPage':
464
+ case 'StoreReadPrompt':
465
+ case 'StoreReadExecution':
466
+ case 'StoreInspectTail':
467
+ case 'StoreReadIdentity':
468
+ case 'StoreCountPeerMessages':
469
+ case 'StoreExport':
470
+ case 'StoreWorkPage':
471
+ case 'StoreWorkRebuild':
472
+ case 'StoreRangePage':
473
+ case 'StoreRangeSeal':
474
+ case 'StoreRangeArchive':
475
+ case 'StoreRangeVerify':
476
+ case 'StoreVerification':
477
+ case 'StoreWorkerCapacity':
478
+ return requireReceiptThread(request.request.threadId)
479
+ }
480
+ request satisfies never
481
+ }
482
+
483
+ /**
484
+ * Admit an already Schema-decoded request to a logical Thread in this physical owner.
485
+ * Custom hosts validate local placement before calling this Effect and provide their same
486
+ * runtime, maintenance and alarm instances. The native endpoint uses this path too: queue limits,
487
+ * idempotent receipts and the pre-admission generation/alarm commit have one owner.
488
+ */
489
+ export const submit = Effect.fnUntraced(function*(threadId: ThreadId, request: SubmitRequest) {
490
+ const placement = yield* ThreadObjectPlacement
491
+
492
+ if (!placement.ownsThread(threadId)) {
493
+ return yield* HostProtocolError.make({ message: 'The Thread belongs to another Object' })
494
+ }
495
+ const mutations = yield* ThreadMutationGate
496
+ const runtime = yield* DurableAgentRuntime
497
+ const alarm = yield* DurableAlarmService
498
+
499
+ yield* gateAdmissionLimits(threadId, request)
500
+
501
+ // The mutation gate pre-arms durable maintenance; publication keeps its own wake behavior.
502
+ return yield* mutations.withMutation(
503
+ runtime
504
+ .submit(passthroughSubmitAgent(request.agentId), request.inputPayload, {
505
+ threadId,
506
+ principal: request.principal,
507
+ idempotencyKey: request.idempotencyKey,
508
+ ...(request.admissionGroup === undefined ? {} : { admissionGroup: request.admissionGroup }),
509
+ ...(request.admissionFence === undefined ? {} : { admissionFence: request.admissionFence }),
510
+ ...(request.workerAdmission === undefined
511
+ ? {}
512
+ : { workerAdmission: request.workerAdmission }),
513
+ ...(request.messageAdmission === undefined
514
+ ? {}
515
+ : { messageAdmission: request.messageAdmission }),
516
+ definitions: request.definitions,
517
+ })
518
+ .pipe(
519
+ alarm.withHintsDeferred,
520
+ Effect.tap(() => publishCommitted),
521
+ ),
522
+ )
523
+ })
524
+
525
+ const submitEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
526
+ decodeSubmitRequest(encoded).pipe(
527
+ Effect.mapError(protocolFailure('The submit request could not be decoded')),
528
+ Effect.flatMap((request) =>
529
+ Effect.gen(function*() {
530
+ const identity = yield* ThreadObjectIdentity
531
+ const receipt = yield* submit(identity.threadId, request)
532
+ const scheduling = yield* DurableObjectAlarm.ScheduleConfiguration
533
+
534
+ if (scheduling.dispatchAfterEvent === true) {
535
+ const maintenance = yield* ThreadMaintenance
536
+
537
+ // effect-cf owns the background scope and native event lifetime. Admission is
538
+ // already durable; neither the Attempt nor its model request delays this receipt.
539
+ yield* maintenance.start(receipt)
540
+ }
541
+
542
+ return SubmitSucceeded.make({ receipt })
543
+ })
544
+ ),
545
+ respond,
546
+ Effect.flatMap(encodeResponse),
547
+ )
548
+
549
+ const submissionStatusEndpoint = (
550
+ encoded: unknown,
551
+ ): Effect.Effect<unknown, never, EndpointServices> =>
552
+ decodeReceipt(encoded).pipe(
553
+ Effect.mapError(protocolFailure('The receipt could not be decoded')),
554
+ Effect.flatMap((receipt) =>
555
+ Effect.gen(function*() {
556
+ const authorizer = yield* OperationAuthorizer
557
+
558
+ yield* authorizer.authorize(
559
+ OperationAuthorizationRequest.make({
560
+ operation: 'awaitSettlement',
561
+ threadId: receipt.threadId,
562
+ submissionId: receipt.submissionId,
563
+ }),
564
+ )
565
+ yield* requireReceiptThread(receipt.threadId)
566
+ yield* requireSubmissionThread(receipt.submissionId)
567
+ const runtime = yield* DurableAgentRuntime
568
+
569
+ return SubmissionStatusResponse.make({ status: yield* runtime.submissionStatus(receipt) })
570
+ })
571
+ ),
572
+ respond,
573
+ Effect.flatMap(encodeResponse),
574
+ )
575
+
576
+ const awaitSettlementEndpoint = (
577
+ encoded: unknown,
578
+ includeRecord = false,
579
+ ): Effect.Effect<unknown, never, EndpointServices> =>
580
+ decodeAwaitSettlementRequest(encoded).pipe(
581
+ Effect.mapError(protocolFailure('The receipt could not be decoded')),
582
+ Effect.flatMap((receipt) =>
583
+ Effect.gen(function*() {
584
+ const authorizer = yield* OperationAuthorizer
585
+
586
+ yield* authorizer.authorize(
587
+ OperationAuthorizationRequest.make({
588
+ operation: 'awaitSettlement',
589
+ threadId: receipt.threadId,
590
+ submissionId: receipt.submissionId,
591
+ }),
592
+ )
593
+ if (includeRecord) {
594
+ yield* authorizer.authorize(
595
+ OperationAuthorizationRequest.make({
596
+ operation: 'observe',
597
+ threadId: receipt.threadId,
598
+ }),
599
+ )
600
+ }
601
+ yield* requireReceiptThread(receipt.threadId)
602
+ yield* requireSubmissionThread(receipt.submissionId)
603
+ const runtime = yield* DurableAgentRuntime
604
+
605
+ const wait = Effect.gen(function*() {
606
+ if (includeRecord) {
607
+ return SettlementRecordReached.make({
608
+ record: yield* runtime.awaitSettlementRecord(receipt),
609
+ })
610
+ }
611
+
612
+ return SettlementReached.make({ settlement: yield* runtime.awaitSettlement(receipt) })
613
+ })
614
+
615
+ if (receipt.waiterId === undefined) return yield* wait
616
+ const registry = yield* ProgressWaitRegistry
617
+
618
+ return yield* Effect.scoped(
619
+ Effect.gen(function*() {
620
+ const cancelled = yield* registry.subscribe(
621
+ JSON.stringify([receipt.threadId, receipt.waiterId]),
622
+ )
623
+
624
+ return yield* Effect.raceFirst(
625
+ wait,
626
+ cancelled.pipe(Effect.as(ProgressCancelled.make())),
627
+ )
628
+ }),
629
+ )
630
+ })
631
+ ),
632
+ respond,
633
+ Effect.flatMap(encodeResponse),
634
+ )
635
+
636
+ const awaitProgressEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
637
+ decodeAwaitProgressRequest(encoded).pipe(
638
+ Effect.mapError(protocolFailure('The progress request could not be decoded')),
639
+ Effect.flatMap((request) =>
640
+ Effect.gen(function*() {
641
+ const identity = yield* ThreadObjectIdentity
642
+ const runtime = yield* DurableAgentRuntime
643
+ const registry = yield* ProgressWaitRegistry
644
+
645
+ yield* Effect.scoped(
646
+ Effect.gen(function*() {
647
+ const cancelled = yield* registry.subscribe(
648
+ JSON.stringify([identity.threadId, request.waiterId]),
649
+ )
650
+
651
+ yield* Effect.raceFirst(
652
+ runtime.awaitProgress(identity.threadId, request.afterSequence),
653
+ cancelled,
654
+ )
655
+ }),
656
+ )
657
+
658
+ return ProgressObserved.make()
659
+ })
660
+ ),
661
+ respond,
662
+ Effect.flatMap(encodeResponse),
663
+ )
664
+
665
+ const cancelProgressEndpoint = (
666
+ encoded: unknown,
667
+ ): Effect.Effect<unknown, never, EndpointServices> =>
668
+ decodeCancelProgressRequest(encoded).pipe(
669
+ Effect.mapError(protocolFailure('The progress cancellation could not be decoded')),
670
+ Effect.flatMap((request) =>
671
+ Effect.gen(function*() {
672
+ const identity = yield* ThreadObjectIdentity
673
+ const registry = yield* ProgressWaitRegistry
674
+
675
+ yield* registry.cancel(JSON.stringify([identity.threadId, request.waiterId]))
676
+
677
+ return ProgressCancelled.make()
678
+ })
679
+ ),
680
+ respond,
681
+ Effect.flatMap(encodeResponse),
682
+ )
683
+
684
+ const observePageEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
685
+ decodeObservePageRequest(encoded).pipe(
686
+ Effect.mapError(protocolFailure('The observe request could not be decoded')),
687
+ Effect.flatMap((request) =>
688
+ Effect.gen(function*() {
689
+ const identity = yield* ThreadObjectIdentity
690
+ const store = yield* ThreadStore
691
+ // The same fail-closed authorization seam the runtime's `observe` consults (P7 WP1);
692
+ // the default reference preserves the possession behavior.
693
+ const authorizer = yield* OperationAuthorizer
694
+
695
+ yield* authorizer.authorize(
696
+ OperationAuthorizationRequest.make({
697
+ operation: 'observe',
698
+ threadId: identity.threadId,
699
+ }),
700
+ )
701
+
702
+ const records = yield* Stream.runCollect(
703
+ store.read(
704
+ ThreadRead.make({
705
+ threadId: identity.threadId,
706
+ ...(request.afterSequence === undefined
707
+ ? {}
708
+ : { afterSequence: request.afterSequence }),
709
+ limit: request.limit,
710
+ }),
711
+ ),
712
+ )
713
+
714
+ return ObservedPage.make({ records: [...records] })
715
+ })
716
+ ),
717
+ respond,
718
+ Effect.flatMap(encodeResponse),
719
+ )
720
+
721
+ const watchTextEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
722
+ Schema.decodeUnknownEffect(WatchTextRequest)(encoded).pipe(
723
+ Effect.mapError(protocolFailure('The provisional text request could not be decoded')),
724
+ Effect.flatMap(() =>
725
+ Effect.gen(function*() {
726
+ const { threadId } = yield* ThreadObjectIdentity
727
+ const authorizer = yield* OperationAuthorizer
728
+
729
+ yield* authorizer.authorize(
730
+ OperationAuthorizationRequest.make({ operation: 'observe', threadId }),
731
+ )
732
+ const hub = yield* LiveTextHub
733
+
734
+ return yield* hub.open(threadId)
735
+ })
736
+ ),
737
+ Effect.catch((failure) => encodeResponse(HostFailed.make({ failure }))),
738
+ )
739
+
740
+ const abortEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
741
+ decodeAbortCommand(encoded).pipe(
742
+ Effect.mapError(protocolFailure('The abort command could not be decoded')),
743
+ Effect.flatMap((command) =>
744
+ Effect.gen(function*() {
745
+ const authorizer = yield* OperationAuthorizer
746
+
747
+ yield* authorizer.authorize(
748
+ OperationAuthorizationRequest.make({
749
+ operation: 'abort',
750
+ submissionId: command.submissionId,
751
+ }),
752
+ )
753
+ yield* requireSubmissionThread(command.submissionId)
754
+ const maintenance = yield* ThreadMaintenance
755
+ const runtime = yield* DurableAgentRuntime
756
+ const intent = yield* maintenance.withMutation(runtime.abort(command))
757
+
758
+ return AbortRecorded.make({ intent })
759
+ })
760
+ ),
761
+ respond,
762
+ Effect.flatMap(encodeResponse),
763
+ )
764
+
765
+ const resolveApprovalEndpoint = (
766
+ encoded: unknown,
767
+ ): Effect.Effect<unknown, never, EndpointServices> =>
768
+ decodeApprovalDecisionCommand(encoded).pipe(
769
+ Effect.mapError(protocolFailure('The approval command could not be decoded')),
770
+ Effect.flatMap((command) =>
771
+ Effect.gen(function*() {
772
+ const authorizer = yield* OperationAuthorizer
773
+
774
+ yield* authorizer.authorize(
775
+ OperationAuthorizationRequest.make({
776
+ operation: 'resolveApproval',
777
+ submissionId: command.submissionId,
778
+ }),
779
+ )
780
+ yield* requireSubmissionThread(command.submissionId)
781
+ const maintenance = yield* ThreadMaintenance
782
+ const runtime = yield* DurableAgentRuntime
783
+ const intent = yield* maintenance.withMutation(runtime.resolveApproval(command))
784
+
785
+ return ApprovalRecorded.make({ intent })
786
+ })
787
+ ),
788
+ respond,
789
+ Effect.flatMap(encodeResponse),
790
+ )
791
+
792
+ const resolveUnknownEndpoint = (
793
+ encoded: unknown,
794
+ ): Effect.Effect<unknown, never, EndpointServices> =>
795
+ decodeUnknownResolutionCommand(encoded).pipe(
796
+ Effect.mapError(protocolFailure('The resolution command could not be decoded')),
797
+ Effect.flatMap((command) =>
798
+ Effect.gen(function*() {
799
+ const authorizer = yield* OperationAuthorizer
800
+
801
+ yield* authorizer.authorize(
802
+ OperationAuthorizationRequest.make({
803
+ operation: 'resolveUnknown',
804
+ submissionId: command.submissionId,
805
+ }),
806
+ )
807
+ yield* requireSubmissionThread(command.submissionId)
808
+ const maintenance = yield* ThreadMaintenance
809
+ const runtime = yield* DurableAgentRuntime
810
+ const intent = yield* maintenance.withMutation(runtime.resolveUnknown(command))
811
+
812
+ return UnknownResolutionRecorded.make({ intent })
813
+ })
814
+ ),
815
+ respond,
816
+ Effect.flatMap(encodeResponse),
817
+ )
818
+
819
+ // ---------------------------------------------------------------------------
820
+ // P7 administrative entry points (plan §3): explain/verify/retry/obligations over the SAME
821
+ // envelope discipline as the host protocol — closed request/response Schema unions, typed
822
+ // failures that re-decode to identical tags, protocol anomalies answered typed. The envelopes
823
+ // live here (not `client.ts`) because no Worker-side client consumption exists yet; `wake`
824
+ // already exists as the `wake()` entry point.
825
+ // ---------------------------------------------------------------------------
826
+
827
+ /** Explain one Submission (`submissionId` present) or every nonterminal lane member. */
828
+ export class AdminExplainRequest extends Schema.Class<AdminExplainRequest>(
829
+ '@effect-agent/platform-cloudflare/AdminExplainRequest',
830
+ )({
831
+ submissionId: Schema.optionalKey(SubmissionId),
832
+ }) {}
833
+
834
+ /** Verify carries no parameters — the addressed Object IS the lane. */
835
+ export class AdminVerifyRequest extends Schema.Class<AdminVerifyRequest>(
836
+ '@effect-agent/platform-cloudflare/AdminVerifyRequest',
837
+ )({}) {}
838
+
839
+ /** Every typed failure of the four admin entry points, plus the protocol's own errors. */
840
+ export const AdminFailure = Schema.Union([
841
+ AdmissionPolicyError,
842
+ ApprovalSuspensionError,
843
+ OperationDenied,
844
+ RetryRefused,
845
+ LedgerError,
846
+ RunJournalError,
847
+ DigestError,
848
+ OwnershipLost,
849
+ SettlementConflict,
850
+ ThreadStoreError,
851
+ ThreadNotMaterialized,
852
+ AppendConflict,
853
+ DurableRuntimeFailpointError,
854
+ DurableAlarmError,
855
+ HostProtocolError,
856
+ RecoveryBlocked,
857
+ WorkDiscoveryUnavailable,
858
+ ])
859
+
860
+ export type AdminFailure = typeof AdminFailure.Type
861
+
862
+ export class ExplainedRecovery extends Schema.TaggedClass<ExplainedRecovery>(
863
+ '@effect-agent/platform-cloudflare/ExplainedRecovery',
864
+ )('ExplainedRecovery', {
865
+ explanations: Schema.Array(RecoveryExplanation).check(Schema.isMaxLength(1_024)),
866
+ }) {}
867
+
868
+ export class VerifiedIntegrity extends Schema.TaggedClass<VerifiedIntegrity>(
869
+ '@effect-agent/platform-cloudflare/VerifiedIntegrity',
870
+ )('VerifiedIntegrity', {
871
+ report: IntegrityReport,
872
+ }) {}
873
+
874
+ export class RetryExecuted extends Schema.TaggedClass<RetryExecuted>(
875
+ '@effect-agent/platform-cloudflare/RetryExecuted',
876
+ )('RetryExecuted', {
877
+ report: RecoveryReport,
878
+ }) {}
879
+
880
+ export class ObligationsScanned extends Schema.TaggedClass<ObligationsScanned>(
881
+ '@effect-agent/platform-cloudflare/ObligationsScanned',
882
+ )('ObligationsScanned', {
883
+ report: ObligationReport,
884
+ }) {}
885
+
886
+ /** The admin entry point failed TYPED on the Object; the failure re-decodes verbatim. */
887
+ export class AdminFailed extends Schema.TaggedClass<AdminFailed>(
888
+ '@effect-agent/platform-cloudflare/AdminFailed',
889
+ )('AdminFailed', {
890
+ failure: AdminFailure,
891
+ }) {}
892
+
893
+ /** The uniform answer of one admin entry point. Callers narrow by the tag their call implies. */
894
+ export const AdminResponse = Schema.Union([
895
+ ExplainedRecovery,
896
+ VerifiedIntegrity,
897
+ RetryExecuted,
898
+ ObligationsScanned,
899
+ AdminFailed,
900
+ ])
901
+
902
+ export type AdminResponse = typeof AdminResponse.Type
903
+
904
+ export const decodeAdminExplainRequest = Schema.decodeUnknownEffect(AdminExplainRequest)
905
+ export const decodeAdminVerifyRequest = Schema.decodeUnknownEffect(AdminVerifyRequest)
906
+ export const decodeRetryCommand = Schema.decodeUnknownEffect(RetryCommand)
907
+ export const decodeObligationThresholds = Schema.decodeUnknownEffect(ObligationThresholds)
908
+
909
+ export const encodeAdminResponse: ReturnType<typeof Schema.encodeEffect<typeof AdminResponse>> = (...args) =>
910
+ Schema.encodeEffect(AdminResponse)(...args)
911
+
912
+ export const decodeAdminResponse = Schema.decodeUnknownEffect(AdminResponse)
913
+
914
+ /** Fold one admin endpoint's typed failures into the uniform `AdminResponse` envelope. */
915
+ const respondAdmin = <Result extends AdminResponse, Failure extends AdminFailure>(
916
+ effect: Effect.Effect<Result, Failure, EndpointServices>,
917
+ ): Effect.Effect<AdminResponse, never, EndpointServices> =>
918
+ effect.pipe(
919
+ Effect.map((result): AdminResponse => result),
920
+ Effect.catch((failure) => Effect.succeed<AdminResponse>(AdminFailed.make({ failure }))),
921
+ )
922
+
923
+ /** Encode the admin response envelope; an unencodable response degrades to a protocol failure. */
924
+ const encodeAdminResponseTotal = (response: AdminResponse): Effect.Effect<unknown> =>
925
+ encodeAdminResponse(response).pipe(
926
+ Effect.catch((error) =>
927
+ Effect.succeed<unknown>({
928
+ _tag: 'AdminFailed',
929
+ failure: {
930
+ _tag: 'HostProtocolError',
931
+ message: boundHostDiagnostic(`The admin response could not be encoded: ${error.message}`),
932
+ },
933
+ })
934
+ ),
935
+ )
936
+
937
+ const explainEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
938
+ decodeAdminExplainRequest(encoded).pipe(
939
+ Effect.mapError(protocolFailure('The explain request could not be decoded')),
940
+ Effect.flatMap((request) =>
941
+ Effect.gen(function*() {
942
+ const identity = yield* ThreadObjectIdentity
943
+ const runtime = yield* DurableAgentRuntime
944
+
945
+ const explanations = request.submissionId === undefined
946
+ ? yield* runtime.explainThread(identity.threadId)
947
+ : [yield* runtime.explain(request.submissionId)]
948
+
949
+ return ExplainedRecovery.make({ explanations })
950
+ })
951
+ ),
952
+ respondAdmin,
953
+ Effect.flatMap(encodeAdminResponseTotal),
954
+ )
955
+
956
+ const verifyEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
957
+ decodeAdminVerifyRequest(encoded).pipe(
958
+ Effect.mapError(protocolFailure('The verify request could not be decoded')),
959
+ Effect.flatMap(() =>
960
+ Effect.gen(function*() {
961
+ const identity = yield* ThreadObjectIdentity
962
+ const runtime = yield* DurableAgentRuntime
963
+ const report = yield* runtime.verify(identity.threadId)
964
+
965
+ return VerifiedIntegrity.make({ report })
966
+ })
967
+ ),
968
+ respondAdmin,
969
+ Effect.flatMap(encodeAdminResponseTotal),
970
+ )
971
+
972
+ const retryEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
973
+ decodeRetryCommand(encoded).pipe(
974
+ Effect.mapError(protocolFailure('The retry command could not be decoded')),
975
+ Effect.flatMap((command) =>
976
+ Effect.gen(function*() {
977
+ const maintenance = yield* ThreadMaintenance
978
+ const runtime = yield* DurableAgentRuntime
979
+ // Retry may repair durable state, so its generation + alarm commit before the mutation.
980
+ const report = yield* maintenance.withMutation(runtime.retry(command))
981
+
982
+ return RetryExecuted.make({ report })
983
+ })
984
+ ),
985
+ respondAdmin,
986
+ Effect.flatMap(encodeAdminResponseTotal),
987
+ )
988
+
989
+ const obligationsEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>
990
+ decodeObligationThresholds(encoded).pipe(
991
+ Effect.mapError(protocolFailure('The obligation thresholds could not be decoded')),
992
+ Effect.flatMap((thresholds) =>
993
+ Effect.gen(function*() {
994
+ const runtime = yield* DurableAgentRuntime
995
+ const report = yield* runtime.scanObligations(thresholds)
996
+
997
+ return ObligationsScanned.make({ report })
998
+ })
999
+ ),
1000
+ respondAdmin,
1001
+ Effect.flatMap(encodeAdminResponseTotal),
1002
+ )
1003
+
1004
+ /**
1005
+ * Owner-side `portCall`: wrap a mutating envelope in the same pre-armed generation protocol as
1006
+ * public RPC (a routed mutation committed by THIS Object must already carry the alarm that will
1007
+ * finish it), execute on the LOCAL facets (never the routed decorators), then arm an immediate
1008
+ * alarm so the mutated lane is processed promptly. Protocol anomalies answer
1009
+ * `PortFailed(PortProtocolError)`.
1010
+ */
1011
+ const encodePortResponseTotal = (response: PortResponse) =>
1012
+ encodePortResponse(response).pipe(
1013
+ Effect.catch((error) =>
1014
+ Effect.succeed(
1015
+ encodedPortProtocolFailure(`The port response could not be encoded: ${error.message}`),
1016
+ )
1017
+ ),
1018
+ )
1019
+
1020
+ const portGuardFailure = (failure: LedgerError | HostProtocolError): PortFailed =>
1021
+ PortFailed.make({
1022
+ failure: failure._tag === 'LedgerError'
1023
+ ? failure
1024
+ : PortProtocolError.make({ message: 'The port request is not for the addressed Thread' }),
1025
+ })
1026
+
1027
+ export const portCall = (
1028
+ encoded: unknown,
1029
+ ): Effect.Effect<
1030
+ unknown,
1031
+ never,
1032
+ ThreadObjectPorts | ThreadMaintenance | DurableAlarmService | ThreadObjectIdentity
1033
+ > =>
1034
+ Effect.gen(function*() {
1035
+ const ports = yield* ThreadObjectPorts
1036
+ const maintenance = yield* ThreadMaintenance
1037
+ const alarm = yield* DurableAlarmService
1038
+
1039
+ const decoded = yield* decodePortRequest(encoded).pipe(
1040
+ Effect.map((request) => ({ _tag: 'success' as const, request })),
1041
+ Effect.catch((error) => Effect.succeed({ _tag: 'failure' as const, message: error.message })),
1042
+ )
1043
+
1044
+ if (decoded._tag === 'failure') {
1045
+ return encodedPortProtocolFailure(
1046
+ `The port request could not be decoded: ${decoded.message}`,
1047
+ )
1048
+ }
1049
+ if (
1050
+ decoded.request._tag === 'LedgerLookup' &&
1051
+ decoded.request.request._tag === 'SubmissionLookupById'
1052
+ ) {
1053
+ const response = yield* lookupAddressedSubmission(decoded.request.request.submissionId).pipe(
1054
+ Effect.map((submission) =>
1055
+ PortSucceeded.make({
1056
+ result: LedgerLookupResult.make(
1057
+ Option.isSome(submission) ? { submission: submission.value } : {},
1058
+ ),
1059
+ })
1060
+ ),
1061
+ Effect.catch((failure) => Effect.succeed(portGuardFailure(failure))),
1062
+ )
1063
+
1064
+ return yield* encodePortResponseTotal(response)
1065
+ }
1066
+ const identityCheck = yield* requirePortThread(decoded.request).pipe(Effect.result)
1067
+
1068
+ if (identityCheck._tag === 'Failure') {
1069
+ return yield* encodePortResponseTotal(portGuardFailure(identityCheck.failure))
1070
+ }
1071
+ const mutating = isMutatingPortRequest(decoded.request)
1072
+
1073
+ const handled = yield* (
1074
+ mutating
1075
+ ? maintenance.withMutation(ports.handle(decoded.request))
1076
+ : ports.handle(decoded.request)
1077
+ ).pipe(Effect.exit)
1078
+
1079
+ if (handled._tag === 'Failure') {
1080
+ // Without the committed generation/alarm the invariant cannot be promised; refuse before
1081
+ // the port mutation runs. `ports.handle` itself is total, so this is the maintenance error.
1082
+ return encodedPortProtocolFailure(
1083
+ 'The owner Object could not arm its maintenance alarm before the mutation.',
1084
+ )
1085
+ }
1086
+
1087
+ const response = yield* encodePortResponseTotal(handled.value)
1088
+
1089
+ if (mutating) {
1090
+ // Prompt processing hint; the pre-armed alarm already guarantees convergence.
1091
+ yield* alarm.scheduleNow.pipe(
1092
+ Effect.catch((error) => Effect.logWarning('ThreadObject.portCall: immediate re-arm failed', error)),
1093
+ )
1094
+ }
1095
+
1096
+ return response
1097
+ })
1098
+
1099
+ const wakeEndpoint: Effect.Effect<void, never, EndpointServices> = Effect.gen(function*() {
1100
+ const identity = yield* ThreadObjectIdentity
1101
+ const wake = yield* WakeScheduler
1102
+
1103
+ // Route the remote hint through this incarnation's scheduler so scoped progress waiters and
1104
+ // the alarm receive the same hint. Delivery remains droppable; canonical storage is authority.
1105
+ yield* wake.notify(identity.threadId)
1106
+ })
1107
+
1108
+ /** The per-Thread wire operations supported by native and application-owned endpoints. */
1109
+ export const ThreadRpcOperation = Schema.Literals([
1110
+ 'submitEncoded',
1111
+ 'submissionStatusEncoded',
1112
+ 'awaitSettlementEncoded',
1113
+ 'awaitSettlementRecordEncoded',
1114
+ 'awaitProgressEncoded',
1115
+ 'cancelProgressEncoded',
1116
+ 'watchTextEncoded',
1117
+ 'observePage',
1118
+ 'abortEncoded',
1119
+ 'resolveApprovalEncoded',
1120
+ 'resolveUnknownEncoded',
1121
+ 'portCall',
1122
+ 'wake',
1123
+ ])
1124
+
1125
+ export type ThreadRpcOperation = typeof ThreadRpcOperation.Type
1126
+
1127
+ const threadRpc = {
1128
+ submitEncoded: submitEndpoint,
1129
+ submissionStatusEncoded: submissionStatusEndpoint,
1130
+ awaitSettlementEncoded: awaitSettlementEndpoint,
1131
+ awaitSettlementRecordEncoded: (encoded) => awaitSettlementEndpoint(encoded, true),
1132
+ awaitProgressEncoded: awaitProgressEndpoint,
1133
+ cancelProgressEncoded: cancelProgressEndpoint,
1134
+ watchTextEncoded: watchTextEndpoint,
1135
+ observePage: observePageEndpoint,
1136
+ abortEncoded: abortEndpoint,
1137
+ resolveApprovalEncoded: resolveApprovalEndpoint,
1138
+ resolveUnknownEncoded: resolveUnknownEndpoint,
1139
+ portCall,
1140
+ wake: () => wakeEndpoint,
1141
+ } satisfies Record<
1142
+ ThreadRpcOperation,
1143
+ (encoded: unknown) => Effect.Effect<unknown, never, EndpointServices>
1144
+ >
1145
+
1146
+ /**
1147
+ * Bind an addressed request to its logical Thread while sharing one physical runtime. This
1148
+ * validates local placement before invoking the same native handlers. Receipts, Submission
1149
+ * commands and port envelopes must match this identity; progress cancellation is Thread-scoped.
1150
+ * The producer comes from the actual runtime configuration, never from caller input. These
1151
+ * guards supplement the existing current model/Tool and operation authorization policies.
1152
+ */
1153
+ export const handleRpc = Effect.fnUntraced(function*(
1154
+ threadId: ThreadId,
1155
+ operation: ThreadRpcOperation,
1156
+ encoded: unknown,
1157
+ ) {
1158
+ const placement = yield* ThreadObjectPlacement
1159
+
1160
+ if (!placement.ownsThread(threadId)) {
1161
+ return yield* HostProtocolError.make({ message: 'The Thread belongs to another Object' })
1162
+ }
1163
+ const { producerId } = yield* DurableRuntimeConfig
1164
+
1165
+ return yield* threadRpc[operation](encoded).pipe(
1166
+ Effect.provideService(ThreadObjectIdentity, { threadId, producerId }),
1167
+ )
1168
+ })
1169
+
1170
+ /** Compose with application registrations on a shared physical object. */
1171
+ export const alarms = ThreadMaintenanceAlarm.handlers({
1172
+ '@systemfsoftware/agent/thread-maintenance': () =>
1173
+ Effect.flatMap(ThreadMaintenance, (maintenance) => Effect.asVoid(maintenance.pass)),
1174
+ })
1175
+
1176
+ const gateEndpoint: Effect.Effect<void, MaintenancePassFailure, EndpointServices> = Effect.gen(
1177
+ function*() {
1178
+ // Forcing ThreadMaintenance forces the whole Layer stack: migration + exact-version
1179
+ // check + configuration decode (DEPLOY-008 fails typed here, before any mutation), then
1180
+ // the defensive local ensure-alarm half of the invariant. LOCAL-ONLY by construction.
1181
+ const maintenance = yield* ThreadMaintenance
1182
+
1183
+ yield* maintenance.ensureAlarm
1184
+ },
1185
+ )
1186
+
1187
+ /**
1188
+ * Adapter from effect-cf's native Durable Object services to Effect Agent's existing platform
1189
+ * ports. effect-cf owns the cached ManagedRuntime and supplies these values once per Object
1190
+ * incarnation; the durable runtime continues to depend only on the narrow services below.
1191
+ */
1192
+ const effectCfPlatformLayer = (
1193
+ namespaceBinding: string,
1194
+ rpcTracing = false,
1195
+ ): Layer.Layer<
1196
+ DurableObjectContext | ThreadObjectNamespace,
1197
+ CloudflareBindingError,
1198
+ EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment
1199
+ > =>
1200
+ Layer.effectContext(
1201
+ Effect.gen(function*() {
1202
+ const state = yield* EffectCfDurableObjectState.DurableObjectState
1203
+ const env = yield* WorkerEnvironment
1204
+ const binding = yield* threadNamespaceFromEnv(env, namespaceBinding)
1205
+
1206
+ return Context.make(DurableObjectContext, { ctx: state.raw, env }).pipe(
1207
+ Context.add(
1208
+ ThreadObjectNamespace,
1209
+ ThreadObjectNamespace.of({
1210
+ get: (threadId) => binding.get(binding.idFromName(threadId)),
1211
+ ...(rpcTracing === true ? { rpcTracing: namespaceBinding } : {}),
1212
+ }),
1213
+ ),
1214
+ )
1215
+ }),
1216
+ )
1217
+
1218
+ /** The public endpoints and effect-cf invocation hook of one Thread Object instance. */
1219
+ export interface Instance<EventServices = never> extends
1220
+ InstanceType<
1221
+ EffectCfDurableObject.DurableObjectClass<
1222
+ Record<never, never>,
1223
+ RuntimeServices | EventServices | ThreadMaintenanceAlarm
1224
+ >
1225
+ >
1226
+ {
1227
+ submitEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>
1228
+ submissionStatusEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>
1229
+ awaitSettlementEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>
1230
+ awaitSettlementRecordEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>
1231
+ awaitProgressEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>
1232
+ cancelProgressEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>
1233
+ watchTextEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>
1234
+ observePage(encoded: unknown, traceContext?: unknown): Promise<unknown>
1235
+ abortEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>
1236
+ resolveApprovalEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>
1237
+ resolveUnknownEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>
1238
+ explainEncoded(encoded: unknown): Promise<unknown>
1239
+ verifyEncoded(encoded: unknown): Promise<unknown>
1240
+ retryEncoded(encoded: unknown): Promise<unknown>
1241
+ obligationsEncoded(encoded: unknown): Promise<unknown>
1242
+ portCall(encoded: unknown, traceContext?: unknown): Promise<unknown>
1243
+ wake(): Promise<void>
1244
+ alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> | void
1245
+ }
1246
+
1247
+ /** The constructor shape workerd instantiates for each Thread Object. */
1248
+ export interface Class<EventServices = never> {
1249
+ new(ctx: DurableObjectState, env: Cloudflare.Env): Instance<EventServices>
1250
+ }
1251
+
1252
+ /**
1253
+ * Export a composed application Layer as a native Durable Object class.
1254
+ * Bootstrap services are provided to the whole graph before it acquires, so application Layers
1255
+ * can yield effect-cf's WorkerEnvironment and DurableObjectState, derived identity, Digest, and SecureRandom.
1256
+ * Effect Config reads scalar Worker vars and secrets through effect-cf's environment provider;
1257
+ * WorkerEnvironment exposes resource bindings without a separate config Layer.
1258
+ * Application dependencies remain visible until Layer.provide satisfies them. effect-cf owns the
1259
+ * cached ManagedRuntime, native RPC methods, event scopes, and telemetry flushing.
1260
+ * Initialization is local and bounded inside the constructor gate. Cloudflare eviction does not
1261
+ * guarantee finalizers; put resources requiring timely release in scoped operations or eventLayer.
1262
+ */
1263
+ export const make = <
1264
+ ApplicationServices,
1265
+ ApplicationError,
1266
+ EventServices = never,
1267
+ EventLayerError = never,
1268
+ AlarmServices = never,
1269
+ AlarmError = never,
1270
+ >(
1271
+ applicationLayer: Layer.Layer<
1272
+ CloudflareDurableRuntimeServices | ApplicationServices,
1273
+ ApplicationError,
1274
+ | CloudflareBootstrapServices
1275
+ | ThreadMaintenanceAlarm
1276
+ | NoInfer<AlarmServices>
1277
+ | EffectCfDurableObjectState.DurableObjectState
1278
+ | WorkerEnvironment
1279
+ | DurableObjectContext
1280
+ | ThreadObjectNamespace
1281
+ >,
1282
+ options: Options<ApplicationServices, EventServices, EventLayerError, AlarmServices, AlarmError>,
1283
+ ): Class<ApplicationServices | EventServices | AlarmServices> => {
1284
+ const application = applicationLayer.pipe(
1285
+ Layer.provideMerge(layerConfig(options)),
1286
+ Layer.provideMerge(effectCfPlatformLayer(options.namespaceBinding, options.rpcTracing)),
1287
+ )
1288
+
1289
+ // effect-cf builds this entire Layer inside its constructor gate. Keep alarm inspection in
1290
+ // that build, after application acquisition, using the same per-Object MemoMap and Scope.
1291
+ const runtime: Layer.Layer<
1292
+ RuntimeServices | ApplicationServices,
1293
+ ThreadObjectInitializationError | ApplicationError,
1294
+ | EffectCfDurableObjectState.DurableObjectState
1295
+ | WorkerEnvironment
1296
+ | ThreadMaintenanceAlarm
1297
+ | AlarmServices
1298
+ > = Layer.flatMap(application, (applicationServices) => {
1299
+ const scheduling = Context.get(applicationServices, DurableObjectAlarm.ScheduleConfiguration)
1300
+ const config = Context.get(applicationServices, CloudflareDurableRuntimeConfig)
1301
+
1302
+ const services = Context.add(applicationServices, DurableObjectAlarm.ScheduleConfiguration, {
1303
+ ...scheduling,
1304
+ dispatchAfterEvent: scheduling.dispatchAfterEvent ?? true,
1305
+ inFlightRecovery: config.recoveryWindowMillis || (scheduling.inFlightRecovery ?? 1_000),
1306
+ })
1307
+
1308
+ return Layer.effectContext(gateEndpoint.pipe(Effect.provide(services), Effect.as(services)))
1309
+ })
1310
+
1311
+ const rpc = {
1312
+ ...threadRpc,
1313
+ explainEncoded: (encoded: unknown) => explainEndpoint(encoded),
1314
+ verifyEncoded: (encoded: unknown) => verifyEndpoint(encoded),
1315
+ retryEncoded: (encoded: unknown) => retryEndpoint(encoded),
1316
+ obligationsEncoded: (encoded: unknown) => obligationsEndpoint(encoded),
1317
+ } satisfies EffectCfDurableObject.DurableObjectRpc<
1318
+ RuntimeServices | ApplicationServices | EventServices
1319
+ >
1320
+
1321
+ type NativeOptions = EffectCfDurableObject.DurableObjectOptions<
1322
+ RuntimeServices | ApplicationServices,
1323
+ EventServices,
1324
+ EventLayerError,
1325
+ typeof rpc,
1326
+ ThreadMaintenanceAlarm | AlarmServices
1327
+ >
1328
+
1329
+ return EffectCfDurableObject.make<
1330
+ RuntimeServices | ApplicationServices,
1331
+ ThreadObjectInitializationError | ApplicationError,
1332
+ EventServices,
1333
+ EventLayerError,
1334
+ typeof rpc,
1335
+ ThreadMaintenanceAlarm | AlarmServices
1336
+ >(runtime, {
1337
+ ...(options.rpcTracing === true ? { rpcTracing: { service: options.namespaceBinding } } : {}),
1338
+ ...(options.eventLayer === undefined ? {} : { eventLayer: options.eventLayer }),
1339
+ // Force the gated runtime Layer when Cloudflare loads this Object incarnation. Recovery stays
1340
+ // in each bounded pass so cross-Object initialization cannot deadlock.
1341
+ initialize: Effect.void,
1342
+ rpc,
1343
+ alarms: options.alarms === undefined ? alarms : DurableObjectAlarm.mergeAll(options.alarms, alarms),
1344
+ // The named registration supplies its scheduler before the constructor builds application services.
1345
+ // Upstream's conditional alarm-registration check cannot reduce over generic application
1346
+ // services. Options and the rpc satisfies check above retain their Effect requirements.
1347
+ } as NativeOptions)
1348
+ }