@effect-agent/platform-cloudflare 0.0.1-beta.6 → 0.1.0-beta.100

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