@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
@@ -0,0 +1,751 @@
1
+ import { doMessageDeliveryStoreLayer } from "@effect-agent/storage-cloudflare/do-message-delivery-store";
2
+ import {
3
+ type DoStorageFailpointHandler,
4
+ type DoStorageFailpoint,
5
+ } from "@effect-agent/storage-cloudflare/do-storage-failpoint";
6
+ import { submissionLedgerLayer } from "@effect-agent/storage-cloudflare/do-submission-ledger";
7
+ import {
8
+ threadStoreLayer,
9
+ storageConfigLayer,
10
+ storageFailpointLayer,
11
+ type DoStorageInitializationError,
12
+ type DoStorageOptions,
13
+ } from "@effect-agent/storage-cloudflare/do-thread-store";
14
+ import {
15
+ type PortRequest,
16
+ type PortResponse,
17
+ } from "@effect-agent/storage-cloudflare/port-protocol";
18
+ import {
19
+ executePortRequest,
20
+ routedThreadStoreLayer,
21
+ routedSubmissionLedgerLayer,
22
+ } from "@effect-agent/storage-cloudflare/port-routing";
23
+ import { BrowserCrypto } from "@effect/platform-browser";
24
+ import { SqliteClient } from "@effect/sql-sqlite-do";
25
+ import {
26
+ type Crypto,
27
+ Cause,
28
+ Context,
29
+ Duration,
30
+ Effect,
31
+ Layer,
32
+ Schema,
33
+ Semaphore,
34
+ type Option,
35
+ } from "effect";
36
+ import {
37
+ compileRegistrations,
38
+ type AgentRegistration,
39
+ type ResolvedBinding,
40
+ } from "effect-agent/agent-registration";
41
+ import { type DigestError } from "effect-agent/digest";
42
+ import { DurableAgentRuntime, DurableRuntimeConfig } from "effect-agent/durable-agent-runtime";
43
+ import {
44
+ DurableRuntimeFailpoint,
45
+ type DurableRuntimeFailpointHandler,
46
+ } from "effect-agent/durable-failpoint";
47
+ import { ThreadId, type SubmissionId } from "effect-agent/identifiers";
48
+ import {
49
+ type MessageDeliveryStore,
50
+ MessageDeliveryDriver,
51
+ type MessageDeliveryError,
52
+ } from "effect-agent/message-delivery";
53
+ import {
54
+ operationAuthorizerLayer,
55
+ type OperationAuthorizerService,
56
+ } from "effect-agent/operation-authorizer";
57
+ import { type PreparedInputAdmission } from "effect-agent/prepared-input-admission";
58
+ import { ProducerId } from "effect-agent/records";
59
+ import {
60
+ type RunContextPreparation,
61
+ type RunCostEstimator,
62
+ type RunToolFailureObserver,
63
+ } from "effect-agent/run-options";
64
+ import {
65
+ CurrentToolFailureObserver,
66
+ RunContextPreparationPassthrough,
67
+ RunToolAuthorization,
68
+ toolFailureObserverLayer,
69
+ } from "effect-agent/run-options";
70
+ import {
71
+ LedgerError,
72
+ SubmissionLedger,
73
+ SubmissionLookupById,
74
+ type SubmissionSnapshot,
75
+ } from "effect-agent/submission-ledger";
76
+ import { ThreadProjectionMaintenance } from "effect-agent/thread-projection-maintenance";
77
+ import { ThreadStoreError, ThreadStore } from "effect-agent/thread-store";
78
+ import { ToolReconciler } from "effect-agent/tool-reconciler";
79
+ import { type WakeScheduler } from "effect-agent/wake-scheduler";
80
+ import { SqlClient } from "effect/unstable/sql/SqlClient";
81
+
82
+ import {
83
+ ThreadMaintenance,
84
+ ThreadMutationGate,
85
+ ThreadPublication,
86
+ publishCommitted,
87
+ ThreadMaintenanceFailpoint,
88
+ DurableAlarmService,
89
+ type ThreadMaintenanceFailpointHandler,
90
+ } from "../Alarm.ts";
91
+ import {
92
+ ThreadObjectIdentity,
93
+ ThreadObjectPlacement,
94
+ DurableObjectContext,
95
+ type ThreadObjectNamespace,
96
+ } from "../CloudflareBindings.ts";
97
+ import {
98
+ CLOUDFLARE_RUNTIME_DEFAULTS,
99
+ CloudflareDurableRuntimeConfig,
100
+ CloudflareDurableRuntimeConfigValue,
101
+ CloudflarePlatformConfigError,
102
+ } from "../CloudflareConfig.ts";
103
+ import { CloudflareThreadClient } from "../CloudflareThreadClient.ts";
104
+ import { cloudflareWakeSchedulerLayer } from "../WakeScheduler.ts";
105
+ import {
106
+ guardedMessageDeliveryStoreLayer,
107
+ threadMessageDeliveryLayer,
108
+ } from "./message-delivery.ts";
109
+ import { cloudflarePreparedInputAdmissionLayer } from "./prepared-admission.ts";
110
+ import { ProgressWaitRegistry } from "./progress-wait.ts";
111
+ import { threadPortTransportLayer } from "./transport.ts";
112
+
113
+ /**
114
+ * Raw (unvalidated) construction options for `ThreadObject.make`, mirroring
115
+ * `NodeDurableAgentRuntimeOptions`. Optional fields default to the documented production values
116
+ * (`CLOUDFLARE_RUNTIME_DEFAULTS`); everything is schema-decoded into
117
+ * `CloudflareDurableRuntimeConfigValue` before any resource opens (deployment §5 gate 1).
118
+ */
119
+ export interface CloudflareDurableRuntimeOptions {
120
+ readonly deploymentId: string;
121
+ /** Head of the minted producer identity `{producerPrefix}:{threadId}`. */
122
+ readonly producerPrefix: string;
123
+ /** Milliseconds; default 30s (D5). */
124
+ readonly ownershipLeaseDuration?: number | undefined;
125
+ /** Milliseconds; default 100. */
126
+ readonly alarmBackoffBase?: number | undefined;
127
+ /** Milliseconds; default 5000. */
128
+ readonly alarmBackoffCap?: number | undefined;
129
+ /** Milliseconds; default 1000. Bounds every alarm re-arm delay. */
130
+ readonly wakeScanInterval?: number | undefined;
131
+ /** Milliseconds; default 500. */
132
+ readonly settlementPollInterval?: number | undefined;
133
+ /** Milliseconds; default 10000. */
134
+ readonly leaseRenewalInterval?: number | undefined;
135
+ /** Milliseconds; default 500. */
136
+ readonly abortPollInterval?: number | undefined;
137
+ /** Deployment-owned pricing authority used by durable cost budgets and settlements. */
138
+ readonly estimateCostMicrousd?: RunCostEstimator | undefined;
139
+ /** Closed trusted Tool failure reporting. Omission masks ambient observers at construction. */
140
+ readonly toolFailureObserver?: RunToolFailureObserver | undefined;
141
+ /** Milliseconds; default 25. */
142
+ readonly observationPollInterval?: number | undefined;
143
+ /** Bytes; default just under the 2 MB platform value limit. */
144
+ readonly maxStoredValueBytes?: number | undefined;
145
+ /** Default false. */
146
+ readonly verifyOnOpen?: boolean | undefined;
147
+ /** Nonterminal Submissions per lane before admission refuses; default 256. */
148
+ readonly maxQueueDepthPerLane?: number | undefined;
149
+ /** Encoded input bytes per Submission; default = the stored-value bound. */
150
+ readonly maxInputBytes?: number | undefined;
151
+ /** `ctx.storage.sql.databaseSize` ceiling at admission; default 9 GB (10 GB platform cap). */
152
+ readonly maxDatabaseBytes?: number | undefined;
153
+ /**
154
+ * Durable Object storage fault injection (`ledger:*` / `append:*` locations). Handlers are
155
+ * constructed per incarnation WITH the live `DurableObjectState`, so eviction harnesses can
156
+ * map an armed hit to `ctx.abort()` — the platform's real failure mode. Default none.
157
+ */
158
+ readonly storageFailpoint?: ((ctx: DurableObjectState) => DoStorageFailpointHandler) | undefined;
159
+ /** Coordinator fault injection (`submit:*` / `terminalize:*` locations); default none. */
160
+ readonly runtimeFailpoint?:
161
+ | ((ctx: DurableObjectState) => DurableRuntimeFailpointHandler)
162
+ | undefined;
163
+ /** Thread-maintenance generation/alarm fault injection; default none. */
164
+ readonly maintenanceFailpoint?:
165
+ | ((ctx: DurableObjectState) => ThreadMaintenanceFailpointHandler)
166
+ | undefined;
167
+ /** Host-supplied fail-closed authorization policy; defaults to service possession. */
168
+ readonly operationAuthorizer?: OperationAuthorizerService | undefined;
169
+ /**
170
+ * Reconciliation policy consulted for open ordinary Tool Calls before an Unknown Outcome
171
+ * is recorded (durability §10, DUR-009). Defaults to the fail-closed
172
+ * `ToolReconciler.uncertain`.
173
+ */
174
+ readonly toolReconciler?: Layer.Layer<ToolReconciler> | undefined;
175
+ }
176
+
177
+ /** Services supplied before the application graph is built, including its dependencies. */
178
+ export type CloudflareBootstrapServices =
179
+ | CloudflareDurableRuntimeConfig
180
+ | ThreadObjectIdentity
181
+ | ThreadObjectPlacement
182
+ | DurableRuntimeConfig
183
+ | Crypto.Crypto
184
+ | DoStorageFailpoint
185
+ | DurableRuntimeFailpoint
186
+ | ThreadMaintenanceFailpoint
187
+ | RunContextPreparation
188
+ | RunToolAuthorization
189
+ | ToolReconciler;
190
+
191
+ /** Every construction failure of the assembled Cloudflare durable runtime stack. */
192
+ export type CloudflareDurableRuntimeInitializationError =
193
+ | CloudflarePlatformConfigError
194
+ | DigestError
195
+ | MessageDeliveryError
196
+ | DoStorageInitializationError;
197
+
198
+ /**
199
+ * The services `ThreadObject.layer` provides, including its single owner SQL client.
200
+ * Its Context also supplies ThreadMessageDelivery (a defaulted Reference, with no required R)
201
+ * so application-composed maintenance retains the same native message recovery capability.
202
+ */
203
+ export type CloudflareDurableRuntimeServices =
204
+ | DurableAgentRuntime
205
+ | SubmissionLedger
206
+ | ThreadStore
207
+ | MessageDeliveryStore
208
+ | WakeScheduler
209
+ | DurableAlarmService
210
+ | ThreadMaintenance
211
+ | ThreadMutationGate
212
+ | ThreadPublication
213
+ | ThreadProjectionMaintenance
214
+ | ThreadObjectPorts
215
+ | ProgressWaitRegistry
216
+ | SqlClient;
217
+
218
+ /**
219
+ * Owner-side execution port for a `portCall` request the wire endpoint has already decoded.
220
+ * It executes against THIS Object's LOCAL port facets — never the routed decorators, so a
221
+ * request cannot bounce between Objects — and returns the typed response for the endpoint to
222
+ * encode.
223
+ */
224
+ export class ThreadObjectPorts extends Context.Service<
225
+ ThreadObjectPorts,
226
+ {
227
+ readonly handle: (request: PortRequest) => Effect.Effect<PortResponse>;
228
+ /** Local-only identity check before a bound RPC can read or mutate a Submission. */
229
+ readonly lookupSubmission: (
230
+ submissionId: SubmissionId,
231
+ ) => Effect.Effect<Option.Option<SubmissionSnapshot>, LedgerError>;
232
+ }
233
+ >()("@effect-agent/platform-cloudflare/ThreadObjectPorts") {}
234
+
235
+ const decodeConfigValue = Schema.decodeUnknownEffect(CloudflareDurableRuntimeConfigValue);
236
+ const decodeThreadId = Schema.decodeUnknownEffect(ThreadId);
237
+ const decodeProducerId = Schema.decodeUnknownEffect(ProducerId);
238
+
239
+ const configFromOptions = (
240
+ options: CloudflareDurableRuntimeOptions,
241
+ ): Effect.Effect<CloudflareDurableRuntimeConfigValue, CloudflarePlatformConfigError> =>
242
+ decodeConfigValue({
243
+ deploymentId: options.deploymentId,
244
+ producerPrefix: options.producerPrefix,
245
+ ownershipLeaseDuration:
246
+ options.ownershipLeaseDuration ?? CLOUDFLARE_RUNTIME_DEFAULTS.ownershipLeaseDuration,
247
+ alarmBackoffBase: options.alarmBackoffBase ?? CLOUDFLARE_RUNTIME_DEFAULTS.alarmBackoffBase,
248
+ alarmBackoffCap: options.alarmBackoffCap ?? CLOUDFLARE_RUNTIME_DEFAULTS.alarmBackoffCap,
249
+ wakeScanInterval: options.wakeScanInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.wakeScanInterval,
250
+ settlementPollInterval:
251
+ options.settlementPollInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.settlementPollInterval,
252
+ leaseRenewalInterval:
253
+ options.leaseRenewalInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.leaseRenewalInterval,
254
+ abortPollInterval: options.abortPollInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.abortPollInterval,
255
+ observationPollInterval:
256
+ options.observationPollInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.observationPollInterval,
257
+ maxStoredValueBytes:
258
+ options.maxStoredValueBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxStoredValueBytes,
259
+ verifyOnOpen: options.verifyOnOpen ?? CLOUDFLARE_RUNTIME_DEFAULTS.verifyOnOpen,
260
+ limits: {
261
+ maxQueueDepthPerLane:
262
+ options.maxQueueDepthPerLane ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxQueueDepthPerLane,
263
+ maxInputBytes: Math.min(
264
+ options.maxInputBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxInputBytes,
265
+ options.maxStoredValueBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxStoredValueBytes,
266
+ ),
267
+ maxDatabaseBytes: options.maxDatabaseBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxDatabaseBytes,
268
+ },
269
+ }).pipe(
270
+ Effect.mapError((error) =>
271
+ CloudflarePlatformConfigError.make({
272
+ message: `Invalid Cloudflare durable runtime configuration: ${error.message}`,
273
+ cause: error,
274
+ }),
275
+ ),
276
+ );
277
+
278
+ /**
279
+ * The Thread this Object owns, from the Object identity rule (plan §1.2): Thread
280
+ * Objects are addressed exclusively by `idFromName(threadId)`, so `ctx.id.name` IS the
281
+ * Thread ID. An unnamed Object (from `newUniqueId`) is a deployment error, not a lane.
282
+ */
283
+ const threadIdFromState = (
284
+ ctx: DurableObjectState,
285
+ ): Effect.Effect<ThreadId, CloudflarePlatformConfigError> =>
286
+ ctx.id.name === undefined
287
+ ? Effect.fail(
288
+ CloudflarePlatformConfigError.make({
289
+ message:
290
+ "This Durable Object was not created via idFromName(threadId); Thread " +
291
+ "Objects must be addressed by their Thread identity (plan §1.2).",
292
+ }),
293
+ )
294
+ : decodeThreadId(ctx.id.name).pipe(
295
+ Effect.mapError((error) =>
296
+ CloudflarePlatformConfigError.make({
297
+ message: `The Durable Object name is not a valid ThreadId: ${error.message}`,
298
+ cause: error,
299
+ }),
300
+ ),
301
+ );
302
+
303
+ /**
304
+ * Validate deployment settings and derive services before building application dependencies.
305
+ * The native class factory builds this Layer inside its constructor gate. Custom Effect hosts
306
+ * can provide it around the complete application Layer with the native context already supplied.
307
+ */
308
+ const runtimeConfigLayer = (
309
+ options: CloudflareDurableRuntimeOptions,
310
+ producerId: ProducerId,
311
+ ): Layer.Layer<
312
+ Exclude<CloudflareBootstrapServices, ThreadObjectIdentity | ThreadObjectPlacement>,
313
+ CloudflarePlatformConfigError,
314
+ DurableObjectContext
315
+ > =>
316
+ Layer.unwrap(
317
+ Effect.gen(function* () {
318
+ const { ctx } = yield* DurableObjectContext;
319
+ const config = yield* configFromOptions(options);
320
+
321
+ return Layer.mergeAll(
322
+ Layer.succeed(CloudflareDurableRuntimeConfig, config),
323
+ DurableRuntimeConfig.layer({
324
+ deploymentId: config.deploymentId,
325
+ producerId,
326
+ settlementPollInterval: Duration.millis(config.settlementPollInterval),
327
+ leaseRenewalInterval: Duration.millis(config.leaseRenewalInterval),
328
+ abortPollInterval: Duration.millis(config.abortPollInterval),
329
+ ...(options.estimateCostMicrousd === undefined
330
+ ? {}
331
+ : { estimateCostMicrousd: options.estimateCostMicrousd }),
332
+ }),
333
+ BrowserCrypto.layer,
334
+ storageFailpointLayer({ storage: ctx.storage, failpoint: options.storageFailpoint?.(ctx) }),
335
+ options.runtimeFailpoint === undefined
336
+ ? DurableRuntimeFailpoint.layer
337
+ : Layer.succeed(DurableRuntimeFailpoint, { hit: options.runtimeFailpoint(ctx) }),
338
+ options.maintenanceFailpoint === undefined
339
+ ? ThreadMaintenanceFailpoint.layer
340
+ : Layer.succeed(ThreadMaintenanceFailpoint, {
341
+ hit: options.maintenanceFailpoint(ctx),
342
+ }),
343
+ options.toolReconciler ?? ToolReconciler.uncertain,
344
+ options.operationAuthorizer === undefined
345
+ ? Layer.empty
346
+ : operationAuthorizerLayer(options.operationAuthorizer),
347
+ options.toolFailureObserver === undefined
348
+ ? Layer.succeed(CurrentToolFailureObserver, undefined)
349
+ : toolFailureObserverLayer(options.toolFailureObserver),
350
+ RunContextPreparationPassthrough,
351
+ RunToolAuthorization.allowAll,
352
+ );
353
+ }),
354
+ );
355
+
356
+ const producerIdentity = (prefix: string, owner: string) =>
357
+ decodeProducerId(`${prefix}:${owner}`).pipe(
358
+ Effect.mapError((error) =>
359
+ CloudflarePlatformConfigError.make({
360
+ message: `The minted producer identity is invalid: ${error.message}`,
361
+ cause: error,
362
+ }),
363
+ ),
364
+ );
365
+
366
+ /** Native one-Thread configuration; retains its existing producer and logical identities. */
367
+ export const layerConfig = (
368
+ options: CloudflareDurableRuntimeOptions,
369
+ ): Layer.Layer<CloudflareBootstrapServices, CloudflarePlatformConfigError, DurableObjectContext> =>
370
+ Layer.unwrap(
371
+ Effect.gen(function* () {
372
+ const { ctx } = yield* DurableObjectContext;
373
+ const threadId = yield* threadIdFromState(ctx);
374
+ const producerId = yield* producerIdentity(options.producerPrefix, threadId);
375
+
376
+ return Layer.mergeAll(
377
+ runtimeConfigLayer(options, producerId),
378
+ Layer.succeed(ThreadObjectIdentity, { threadId, producerId }),
379
+ Layer.succeed(ThreadObjectPlacement, { ownsThread: (target) => target === threadId }),
380
+ );
381
+ }),
382
+ );
383
+
384
+ /**
385
+ * Configuration for an application Object owning several logical Threads. The producer is
386
+ * the stable physical Object. No logical identity is installed globally: handleRpc binds and
387
+ * validates it per request using the placement guard and this actual runtime producer.
388
+ */
389
+ export const layerHostConfig = (
390
+ options: CloudflareDurableRuntimeOptions,
391
+ ownsThread: (threadId: ThreadId) => boolean,
392
+ ): Layer.Layer<
393
+ Exclude<CloudflareBootstrapServices, ThreadObjectIdentity>,
394
+ CloudflarePlatformConfigError,
395
+ DurableObjectContext
396
+ > =>
397
+ Layer.unwrap(
398
+ Effect.gen(function* () {
399
+ const { ctx } = yield* DurableObjectContext;
400
+ const producerId = yield* producerIdentity(options.producerPrefix, ctx.id.toString());
401
+
402
+ return Layer.merge(
403
+ runtimeConfigLayer(options, producerId),
404
+ Layer.succeed(ThreadObjectPlacement, { ownsThread }),
405
+ );
406
+ }),
407
+ );
408
+
409
+ export interface ThreadPublicationOptions<E = never, R = never, P = never> {
410
+ /**
411
+ * Optional host outbox consumer, built once per incarnation with RAW LOCAL ThreadStore and
412
+ * SubmissionLedger services. Yield DurableObjectContext and ThreadObjectIdentity for native
413
+ * bindings and identity. Initialization is local-only, inside the constructor gate; setup
414
+ * errors and additional requirements remain in the returned Layer. Layer.effect owns Scope.
415
+ * Canonical appends and durable approval, abort and unknown-resolution intents invalidate
416
+ * publication after commit. Custom host facts must use ThreadMaintenance.withMutation.
417
+ */
418
+ readonly publication?: Layer.Layer<ThreadPublication, E, R>;
419
+ /**
420
+ * Disposable index maintenance, built once with the raw local ThreadStore and owner
421
+ * SqlClient. Additional services P are exposed by the returned Layer, allowing Tool
422
+ * handlers and maintenance to share one index instance. Construction is local-only.
423
+ * Live committed batches run before append returns; bounded backfill uses the native
424
+ * alarm without delaying execution behind projection backlog.
425
+ */
426
+ readonly projection?: Layer.Layer<ThreadProjectionMaintenance | P, E, R>;
427
+ }
428
+
429
+ /**
430
+ * Register typed Agents and version declarations. Hashing and dependency capture happen in
431
+ * this Layer's Scope, after application Layers have been provided. Every Agent's instruction,
432
+ * Tool, Schema, and model requirements remain visible until satisfied by Layer composition.
433
+ * Use Layer.unwrap for registration values that need effectful application setup.
434
+ */
435
+ const registeredLayer = <
436
+ const Entries extends ReadonlyArray<AgentRegistration>,
437
+ E = never,
438
+ R = never,
439
+ >(
440
+ registrations: Entries,
441
+ options: ThreadPublicationOptions<E, R> = {},
442
+ ) =>
443
+ Layer.unwrap(
444
+ Effect.map(compileRegistrations(registrations), (bindings) => boundLayer(bindings, options)),
445
+ );
446
+
447
+ /** Preserve additional index services only when a projection Layer is actually supplied. */
448
+ export function layer<
449
+ const Entries extends ReadonlyArray<AgentRegistration>,
450
+ E = never,
451
+ R = never,
452
+ P = never,
453
+ PE = never,
454
+ PR = never,
455
+ >(
456
+ registrations: Entries,
457
+ options: Omit<ThreadPublicationOptions<E, R>, "projection"> & {
458
+ readonly projection: Layer.Layer<ThreadProjectionMaintenance | P, PE, PR>;
459
+ },
460
+ ): Layer.Layer<
461
+ Layer.Success<ReturnType<typeof registeredLayer<Entries, E | PE, R | PR>>> | P,
462
+ Layer.Error<ReturnType<typeof registeredLayer<Entries, E | PE, R | PR>>>,
463
+ Layer.Services<ReturnType<typeof registeredLayer<Entries, E | PE, R | PR>>>
464
+ >;
465
+
466
+ export function layer<const Entries extends ReadonlyArray<AgentRegistration>, E = never, R = never>(
467
+ registrations: Entries,
468
+ options?: ThreadPublicationOptions<E, R>,
469
+ ): ReturnType<typeof registeredLayer<Entries, E, R>>;
470
+
471
+ export function layer<const Entries extends ReadonlyArray<AgentRegistration>, E = never, R = never>(
472
+ registrations: Entries,
473
+ options: ThreadPublicationOptions<E, R> = {},
474
+ ) {
475
+ return registeredLayer(registrations, options);
476
+ }
477
+
478
+ export function layerFromBindings<E = never, R = never, P = never, PE = never, PR = never>(
479
+ bindings: ReadonlyArray<ResolvedBinding>,
480
+ options: Omit<ThreadPublicationOptions<E, R>, "projection"> & {
481
+ readonly projection: Layer.Layer<ThreadProjectionMaintenance | P, PE, PR>;
482
+ },
483
+ ): Layer.Layer<
484
+ CloudflareDurableRuntimeServices | P,
485
+ Layer.Error<ReturnType<typeof boundLayer<E | PE, R | PR>>>,
486
+ Layer.Services<ReturnType<typeof boundLayer<E | PE, R | PR>>>
487
+ >;
488
+
489
+ export function layerFromBindings<E = never, R = never>(
490
+ bindings: ReadonlyArray<ResolvedBinding>,
491
+ options?: ThreadPublicationOptions<E, R>,
492
+ ): ReturnType<typeof boundLayer<E, R>>;
493
+
494
+ export function layerFromBindings(
495
+ bindings: ReadonlyArray<ResolvedBinding>,
496
+ ): ReturnType<typeof boundLayer<never, never>>;
497
+
498
+ export function layerFromBindings<E = never, R = never>(
499
+ bindings: ReadonlyArray<ResolvedBinding>,
500
+ options: ThreadPublicationOptions<E, R> = {},
501
+ ) {
502
+ return boundLayer(bindings, options);
503
+ }
504
+
505
+ /**
506
+ * Assemble the durable runtime from already-resolved Agent Bindings.
507
+ * Use `ThreadObject.layer` to compile typed Agent registrations instead.
508
+ * Supply host services through `ThreadObject.make` or `ThreadObject.layerConfig` and
509
+ * the Durable Object context and namespace Layers when composing a custom host.
510
+ */
511
+ const boundLayer = <E = never, R = never>(
512
+ bindings: ReadonlyArray<ResolvedBinding>,
513
+ options: ThreadPublicationOptions<E, R> = {},
514
+ ): Layer.Layer<
515
+ CloudflareDurableRuntimeServices,
516
+ DoStorageInitializationError | MessageDeliveryError | E,
517
+ | DurableObjectContext
518
+ | ThreadObjectNamespace
519
+ | CloudflareBootstrapServices
520
+ | Exclude<R, ThreadStore | SubmissionLedger | SqlClient>
521
+ > =>
522
+ Layer.unwrap(
523
+ Effect.map(DurableObjectContext, ({ ctx }) =>
524
+ sharedLayer(DurableAgentRuntime.layerWithBindings(bindings), options).pipe(
525
+ Layer.provideMerge(SqliteClient.layer({ storage: ctx.storage })),
526
+ ),
527
+ ),
528
+ );
529
+
530
+ /**
531
+ * Build the application runtime over the existing owner SqlClient and native ports, then
532
+ * assemble its one maintenance coordinator. The application may acquire its Bindings from
533
+ * those ports and expose extra services, including ThreadHostMaintenance. It must not acquire
534
+ * another runtime stack or require ThreadMaintenance while constructing this Layer.
535
+ * Supply layerHostConfig and deterministic placement; dispatch addressed ingress with handleRpc.
536
+ */
537
+ export function layerInHost<A, E, R, P = never, PE = never, PR = never>(
538
+ application: Layer.Layer<DurableAgentRuntime | A, E, R>,
539
+ options: Omit<ThreadPublicationOptions<PE, PR>, "projection"> & {
540
+ readonly projection: Layer.Layer<ThreadProjectionMaintenance | P, PE, PR>;
541
+ },
542
+ ): Layer.Layer<
543
+ CloudflareDurableRuntimeServices | A | P,
544
+ Layer.Error<ReturnType<typeof sharedLayer<A, E, R, PE, PR>>>,
545
+ Layer.Services<ReturnType<typeof sharedLayer<A, E, Exclude<R, P>, PE, PR>>>
546
+ >;
547
+
548
+ export function layerInHost<A, E, R, PE = never, PR = never>(
549
+ application: Layer.Layer<DurableAgentRuntime | A, E, R>,
550
+ options?: ThreadPublicationOptions<PE, PR>,
551
+ ): ReturnType<typeof sharedLayer<A, E, R, PE, PR>>;
552
+
553
+ export function layerInHost<A, E, R, PE = never, PR = never>(
554
+ application: Layer.Layer<DurableAgentRuntime | A, E, R>,
555
+ options: ThreadPublicationOptions<PE, PR> = {},
556
+ ) {
557
+ return sharedLayer(application, options);
558
+ }
559
+
560
+ type HostRuntimeServices = Exclude<
561
+ CloudflareDurableRuntimeServices,
562
+ DurableAgentRuntime | ThreadMaintenance
563
+ >;
564
+
565
+ const sharedLayer = <A, E, R, PE = never, PR = never>(
566
+ application: Layer.Layer<DurableAgentRuntime | A, E, R>,
567
+ options: ThreadPublicationOptions<PE, PR> = {},
568
+ ): Layer.Layer<
569
+ CloudflareDurableRuntimeServices | A,
570
+ DoStorageInitializationError | MessageDeliveryError | E | PE,
571
+ | DurableObjectContext
572
+ | ThreadObjectNamespace
573
+ | Exclude<CloudflareBootstrapServices, ThreadObjectIdentity>
574
+ | SqlClient
575
+ | Exclude<R, HostRuntimeServices | PreparedInputAdmission>
576
+ | Exclude<PR, ThreadStore | SubmissionLedger | SqlClient>
577
+ > =>
578
+ Layer.unwrap(
579
+ Effect.gen(function* () {
580
+ const { ctx } = yield* DurableObjectContext;
581
+ const config = yield* CloudflareDurableRuntimeConfig;
582
+ const { ownsThread } = yield* ThreadObjectPlacement;
583
+
584
+ const storageOptions: DoStorageOptions = {
585
+ storage: ctx.storage,
586
+ observationPollInterval: config.observationPollInterval,
587
+ ownershipLeaseDuration: config.ownershipLeaseDuration,
588
+ maxStoredValueBytes: config.maxStoredValueBytes,
589
+ verifyOnOpen: config.verifyOnOpen,
590
+ };
591
+
592
+ const infrastructure = Layer.mergeAll(
593
+ storageConfigLayer(storageOptions),
594
+ Layer.effect(SqlClient)(SqlClient),
595
+ );
596
+
597
+ // The same local ports serve routed decorators and owner-side RPC execution.
598
+ // The RPC executor must never receive routed ports and bounce requests between Objects.
599
+ const rawLocalPorts = Layer.mergeAll(threadStoreLayer, submissionLedgerLayer).pipe(
600
+ Layer.provide(infrastructure),
601
+ );
602
+
603
+ const base = Layer.mergeAll(DurableAlarmService.layer, ProgressWaitRegistry.layer);
604
+ const wakes = cloudflareWakeSchedulerLayer.pipe(Layer.provide(base));
605
+
606
+ const messageStore = guardedMessageDeliveryStoreLayer.pipe(
607
+ Layer.provide(doMessageDeliveryStoreLayer().pipe(Layer.provide(infrastructure))),
608
+ Layer.provide(wakes),
609
+ );
610
+
611
+ const messageRecovery = threadMessageDeliveryLayer.pipe(
612
+ // Each wave is bounded even at the policy's five-minute attempt ceiling. Source
613
+ // completion stops new waves; remaining rows retain their indexed alarm deadline.
614
+ Layer.provide(MessageDeliveryDriver.layer({ batchSize: 4, concurrency: 4 })),
615
+ Layer.provide(cloudflarePreparedInputAdmissionLayer),
616
+ Layer.provide(CloudflareThreadClient.layer),
617
+ Layer.provide(messageStore),
618
+ Layer.provide(wakes),
619
+ );
620
+
621
+ const publication = (options.publication ?? ThreadPublication.layer).pipe(
622
+ Layer.provide(Layer.mergeAll(rawLocalPorts, Layer.effect(SqlClient)(SqlClient))),
623
+ );
624
+
625
+ const projection = (options.projection ?? ThreadProjectionMaintenance.layer).pipe(
626
+ Layer.provide(Layer.mergeAll(rawLocalPorts, Layer.effect(SqlClient)(SqlClient))),
627
+ );
628
+
629
+ const localPorts =
630
+ options.publication === undefined && options.projection === undefined
631
+ ? rawLocalPorts
632
+ : Layer.effectContext(
633
+ Effect.gen(function* () {
634
+ const store = yield* ThreadStore;
635
+ const ledger = yield* SubmissionLedger;
636
+ const mutations = yield* ThreadMutationGate;
637
+ const index = yield* ThreadProjectionMaintenance;
638
+ const publish = yield* Effect.context<ThreadPublication>();
639
+ const afterCommit = publishCommitted.pipe(Effect.provide(publish));
640
+ // A later append cannot mistake its still-projecting predecessor for old backlog.
641
+ // Publication remains outside this local source/index critical section.
642
+ const sourceCommits = yield* Semaphore.make(1);
643
+
644
+ // Every runtime-owned producer prearms too: a crash between commit and invalidation
645
+ // leaves a NEW, uncertified generation. Source errors keep their native port types.
646
+ const observedStore = ThreadStore.of({
647
+ ...store,
648
+ append: (request) =>
649
+ mutations
650
+ .withMutation(
651
+ sourceCommits
652
+ .withPermit(
653
+ store
654
+ .append(request)
655
+ .pipe(
656
+ Effect.tap((result) =>
657
+ index
658
+ .applyCommitted(request, result)
659
+ .pipe(
660
+ Effect.catchCause((cause) =>
661
+ Cause.hasInterrupts(cause)
662
+ ? Effect.interrupt
663
+ : Effect.logError(
664
+ "Thread projection deferred after source commit",
665
+ cause,
666
+ ),
667
+ ),
668
+ ),
669
+ ),
670
+ ),
671
+ )
672
+ .pipe(Effect.tap(() => afterCommit)),
673
+ )
674
+ .pipe(
675
+ Effect.catchTag("DurableAlarmError", (cause) =>
676
+ ThreadStoreError.make({
677
+ operation: "prearm publication append",
678
+ message: cause.message,
679
+ cause,
680
+ }),
681
+ ),
682
+ ),
683
+ });
684
+
685
+ const observeIntent = <A, Failure>(body: Effect.Effect<A, Failure>) =>
686
+ mutations.withMutation(body.pipe(Effect.tap(() => afterCommit))).pipe(
687
+ Effect.catchTag("DurableAlarmError", (cause) =>
688
+ LedgerError.make({
689
+ operation: "prearm publication intent",
690
+ message: "The publication generation could not be armed",
691
+ cause,
692
+ }),
693
+ ),
694
+ );
695
+
696
+ return Context.make(ThreadStore, observedStore).pipe(
697
+ Context.add(SubmissionLedger, {
698
+ ...ledger,
699
+ recordApprovalDecision: (request) =>
700
+ observeIntent(ledger.recordApprovalDecision(request)),
701
+ requestAbort: (request) => observeIntent(ledger.requestAbort(request)),
702
+ recordUnknownResolution: (request) =>
703
+ observeIntent(ledger.recordUnknownResolution(request)),
704
+ }),
705
+ );
706
+ }),
707
+ ).pipe(Layer.provide(rawLocalPorts));
708
+
709
+ const portsEndpointLayer = Layer.effect(ThreadObjectPorts)(
710
+ Effect.gen(function* () {
711
+ const local = yield* Effect.context<SubmissionLedger | ThreadStore>();
712
+ const ledger = Context.get(local, SubmissionLedger);
713
+
714
+ return ThreadObjectPorts.of({
715
+ handle: (request) => executePortRequest(request).pipe(Effect.provide(local)),
716
+ lookupSubmission: (submissionId) =>
717
+ ledger.lookup(SubmissionLookupById.make({ submissionId })),
718
+ });
719
+ }),
720
+ ).pipe(Layer.provide(localPorts));
721
+
722
+ const routedPorts = Layer.mergeAll(
723
+ routedSubmissionLedgerLayer({ ownsThread }),
724
+ routedThreadStoreLayer({ ownsThread }),
725
+ ).pipe(Layer.provide(localPorts), Layer.provide(threadPortTransportLayer));
726
+
727
+ const runtimeStack = application.pipe(
728
+ Layer.provide(
729
+ cloudflarePreparedInputAdmissionLayer.pipe(Layer.provide(CloudflareThreadClient.layer)),
730
+ ),
731
+ Layer.provideMerge(messageStore),
732
+ Layer.provideMerge(routedPorts),
733
+ Layer.provideMerge(wakes),
734
+ Layer.provideMerge(base),
735
+ Layer.provideMerge(portsEndpointLayer),
736
+ );
737
+
738
+ return Layer.mergeAll(
739
+ runtimeStack,
740
+ ThreadMaintenance.layer.pipe(Layer.provide(runtimeStack), Layer.provide(messageRecovery)),
741
+ portsEndpointLayer,
742
+ messageStore,
743
+ messageRecovery,
744
+ ).pipe(
745
+ Layer.provideMerge(publication),
746
+ Layer.provideMerge(projection),
747
+ Layer.provideMerge(ThreadMutationGate.layer),
748
+ Layer.provideMerge(infrastructure),
749
+ );
750
+ }),
751
+ );