@effect-agent/platform-cloudflare 0.1.0-beta.13 → 0.1.0-beta.131

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