@systemfsoftware/agent-platform-cloudflare 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/LICENSE +21 -0
  2. package/dist/Alarm-CbhflIzz.mjs +1931 -0
  3. package/dist/Alarm-CbhflIzz.mjs.map +1 -0
  4. package/dist/Alarm-Nz1gIjfv.d.mts +252 -0
  5. package/dist/Alarm.d.mts +3 -0
  6. package/dist/Alarm.mjs +3 -0
  7. package/dist/BrowserCredentials-BWC4RqRn.d.mts +116 -0
  8. package/dist/BrowserCredentials-CktBoPgE.mjs +140 -0
  9. package/dist/BrowserCredentials-CktBoPgE.mjs.map +1 -0
  10. package/dist/BrowserCredentials.d.mts +2 -0
  11. package/dist/BrowserCredentials.mjs +1 -0
  12. package/dist/BrowserRestCapture.d.mts +14 -0
  13. package/dist/BrowserRestCapture.mjs +195 -0
  14. package/dist/BrowserRestCapture.mjs.map +1 -0
  15. package/dist/BrowserSession-5bdpqPIT.d.mts +152 -0
  16. package/dist/BrowserSession-Ce8cWN1A.mjs +673 -0
  17. package/dist/BrowserSession-Ce8cWN1A.mjs.map +1 -0
  18. package/dist/BrowserSession.d.mts +3 -0
  19. package/dist/BrowserSession.mjs +4 -0
  20. package/dist/BrowserUse-Bsi830Yv.mjs +263 -0
  21. package/dist/BrowserUse-Bsi830Yv.mjs.map +1 -0
  22. package/dist/BrowserUse-DF8afbNt.d.mts +59 -0
  23. package/dist/BrowserUse.d.mts +2 -0
  24. package/dist/BrowserUse.mjs +1 -0
  25. package/dist/CloudflareAiGateway-By8C8c5z.mjs +79 -0
  26. package/dist/CloudflareAiGateway-By8C8c5z.mjs.map +1 -0
  27. package/dist/CloudflareAiGateway-ukN34014.d.mts +63 -0
  28. package/dist/CloudflareAiGateway.d.mts +2 -0
  29. package/dist/CloudflareAiGateway.mjs +1 -0
  30. package/dist/CloudflareBindings-Dylkir84.mjs +123 -0
  31. package/dist/CloudflareBindings-Dylkir84.mjs.map +1 -0
  32. package/dist/CloudflareBindings-E1Sty9Vq.d.mts +134 -0
  33. package/dist/CloudflareBindings.d.mts +2 -0
  34. package/dist/CloudflareBindings.mjs +1 -0
  35. package/dist/CloudflareBrowser-CmiQpslZ.d.mts +41 -0
  36. package/dist/CloudflareBrowser-DmMCFeIQ.mjs +397 -0
  37. package/dist/CloudflareBrowser-DmMCFeIQ.mjs.map +1 -0
  38. package/dist/CloudflareBrowser.d.mts +3 -0
  39. package/dist/CloudflareBrowser.mjs +1 -0
  40. package/dist/CloudflareCodeMode-BMva6dCs.mjs +627 -0
  41. package/dist/CloudflareCodeMode-BMva6dCs.mjs.map +1 -0
  42. package/dist/CloudflareCodeMode-CeGXZtHv.d.mts +43 -0
  43. package/dist/CloudflareCodeMode.d.mts +2 -0
  44. package/dist/CloudflareCodeMode.mjs +1 -0
  45. package/dist/CloudflareConfig-BFWgEyhH.d.mts +102 -0
  46. package/dist/CloudflareConfig-rBlbPSIZ.mjs +125 -0
  47. package/dist/CloudflareConfig-rBlbPSIZ.mjs.map +1 -0
  48. package/dist/CloudflareConfig.d.mts +2 -0
  49. package/dist/CloudflareConfig.mjs +1 -0
  50. package/dist/CloudflareMemory-Bzp32ZpR.d.mts +120 -0
  51. package/dist/CloudflareMemory-DejIVKBT.mjs +207 -0
  52. package/dist/CloudflareMemory-DejIVKBT.mjs.map +1 -0
  53. package/dist/CloudflareMemory.d.mts +2 -0
  54. package/dist/CloudflareMemory.mjs +1 -0
  55. package/dist/CloudflareScheduling-BleqfC44.mjs +395 -0
  56. package/dist/CloudflareScheduling-BleqfC44.mjs.map +1 -0
  57. package/dist/CloudflareScheduling-vZ7iSR57.d.mts +54 -0
  58. package/dist/CloudflareScheduling.d.mts +2 -0
  59. package/dist/CloudflareScheduling.mjs +1 -0
  60. package/dist/CloudflareSubscriptions-IHSo19MU.d.mts +91 -0
  61. package/dist/CloudflareSubscriptions-S3fZF-Jo.mjs +529 -0
  62. package/dist/CloudflareSubscriptions-S3fZF-Jo.mjs.map +1 -0
  63. package/dist/CloudflareSubscriptions.d.mts +2 -0
  64. package/dist/CloudflareSubscriptions.mjs +1 -0
  65. package/dist/CloudflareThreadClient-BUv9Te1s.d.mts +2141 -0
  66. package/dist/CloudflareThreadClient-K7QJHYpK.mjs +496 -0
  67. package/dist/CloudflareThreadClient-K7QJHYpK.mjs.map +1 -0
  68. package/dist/CloudflareThreadClient.d.mts +3 -0
  69. package/dist/CloudflareThreadClient.mjs +3 -0
  70. package/dist/InteractiveBrowser-CMbA7YPP.d.mts +228 -0
  71. package/dist/InteractiveBrowser-e8ZvxC1C.mjs +2013 -0
  72. package/dist/InteractiveBrowser-e8ZvxC1C.mjs.map +1 -0
  73. package/dist/InteractiveBrowser.d.mts +2 -0
  74. package/dist/InteractiveBrowser.mjs +1 -0
  75. package/dist/LiveText-CfpcZaGb.d.mts +91 -0
  76. package/dist/LiveText-DaF0tN_p.mjs +148 -0
  77. package/dist/LiveText-DaF0tN_p.mjs.map +1 -0
  78. package/dist/LiveText.d.mts +2 -0
  79. package/dist/LiveText.mjs +1 -0
  80. package/dist/R2ToolResultStorage.d.mts +27 -0
  81. package/dist/R2ToolResultStorage.mjs +84 -0
  82. package/dist/R2ToolResultStorage.mjs.map +1 -0
  83. package/dist/ThreadObject-B2-PqnpT.d.mts +390 -0
  84. package/dist/ThreadObject-D1pCeNrq.mjs +1225 -0
  85. package/dist/ThreadObject-D1pCeNrq.mjs.map +1 -0
  86. package/dist/ThreadObject.d.mts +2 -0
  87. package/dist/ThreadObject.mjs +1 -0
  88. package/dist/WakeScheduler-67UeXBYK.d.mts +22 -0
  89. package/dist/WakeScheduler-DV4J4TRe.mjs +69 -0
  90. package/dist/WakeScheduler-DV4J4TRe.mjs.map +1 -0
  91. package/dist/WakeScheduler.d.mts +2 -0
  92. package/dist/WakeScheduler.mjs +1 -0
  93. package/dist/boundary-YrOnE2zO.mjs +41 -0
  94. package/dist/boundary-YrOnE2zO.mjs.map +1 -0
  95. package/dist/browser-failure-CWBBnf1j.mjs +70 -0
  96. package/dist/browser-failure-CWBBnf1j.mjs.map +1 -0
  97. package/dist/index.d.mts +17 -0
  98. package/dist/index.mjs +17 -0
  99. package/dist/prepared-admission-DngoYN74.mjs +57 -0
  100. package/dist/prepared-admission-DngoYN74.mjs.map +1 -0
  101. package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
  102. package/package.json +134 -3
  103. package/src/Alarm.ts +3402 -0
  104. package/src/BrowserCredentials.ts +181 -0
  105. package/src/BrowserRestCapture.ts +383 -0
  106. package/src/BrowserSession.ts +993 -0
  107. package/src/BrowserUse.ts +438 -0
  108. package/src/CloudflareAiGateway.ts +176 -0
  109. package/src/CloudflareBindings.ts +225 -0
  110. package/src/CloudflareBrowser.ts +9 -0
  111. package/src/CloudflareCodeMode.ts +896 -0
  112. package/src/CloudflareConfig.ts +142 -0
  113. package/src/CloudflareMemory.ts +418 -0
  114. package/src/CloudflareScheduling.ts +736 -0
  115. package/src/CloudflareSubscriptions.ts +1032 -0
  116. package/src/CloudflareThreadClient.ts +980 -0
  117. package/src/InteractiveBrowser.ts +3300 -0
  118. package/src/LiveText.ts +145 -0
  119. package/src/R2ToolResultStorage.ts +131 -0
  120. package/src/ThreadObject.ts +1348 -0
  121. package/src/WakeScheduler.ts +102 -0
  122. package/src/index.ts +16 -0
  123. package/src/internal/boundary.ts +53 -0
  124. package/src/internal/browser-binding.ts +483 -0
  125. package/src/internal/browser-credentials.ts +481 -0
  126. package/src/internal/browser-failure.ts +145 -0
  127. package/src/internal/browser-file-selection.ts +146 -0
  128. package/src/internal/browser-quick-action.ts +666 -0
  129. package/src/internal/browser-readonly-live-view.ts +121 -0
  130. package/src/internal/browser-session-lifecycle.ts +200 -0
  131. package/src/internal/crypto.ts +44 -0
  132. package/src/internal/due-queue.ts +452 -0
  133. package/src/internal/host-protocol-error.ts +23 -0
  134. package/src/internal/layers.ts +1181 -0
  135. package/src/internal/live-text-observation.ts +8 -0
  136. package/src/internal/live-text-protocol.ts +59 -0
  137. package/src/internal/live-text.ts +339 -0
  138. package/src/internal/message-delivery.ts +149 -0
  139. package/src/internal/page-function.ts +12 -0
  140. package/src/internal/prepared-admission.ts +83 -0
  141. package/src/internal/progress-wait.ts +121 -0
  142. package/src/internal/transport.ts +53 -0
  143. package/README.md +0 -3
@@ -0,0 +1,736 @@
1
+ import * as SqliteClient from '@effect/sql-sqlite-do/SqliteClient'
2
+ import {
3
+ DoScheduleAlarmControl,
4
+ DoScheduleTransaction,
5
+ scheduleStoreLayer,
6
+ } from '@systemfsoftware/agent-storage-cloudflare/do-schedule-store'
7
+ import { type DurableSubmitAgent } from '@systemfsoftware/agent/durable-agent-runtime'
8
+ import { AgentId } from '@systemfsoftware/agent/identifiers'
9
+ import { DefinitionDigests, PersistedJson } from '@systemfsoftware/agent/records'
10
+ import {
11
+ defaultSchedulingLimits,
12
+ ScheduleAuthorizationError,
13
+ type ScheduleAuthorizer,
14
+ ScheduleCapacityError,
15
+ ScheduleConflict,
16
+ ScheduleDestination,
17
+ ScheduleFailpointError,
18
+ ScheduleId,
19
+ ScheduleNotFound,
20
+ ScheduleOwner,
21
+ type ScheduleScope,
22
+ ScheduleScope as ScheduleScopeSchema,
23
+ ScheduleSnapshot,
24
+ ScheduleSnapshotPage as ScheduleSnapshotPageSchema,
25
+ ScheduleStorageError,
26
+ ScheduleTimingRequest,
27
+ ScheduleValidationError,
28
+ type SchedulingLimits,
29
+ } from '@systemfsoftware/agent/schedule'
30
+ import { scheduleOwnerKey } from '@systemfsoftware/agent/schedule-transition'
31
+ import {
32
+ ScheduleDriver,
33
+ type ScheduleManagementFailure,
34
+ ScheduleWakeNoop,
35
+ Scheduling,
36
+ } from '@systemfsoftware/agent/scheduling'
37
+ import { AdmissionFence } from '@systemfsoftware/agent/submission-ledger'
38
+ import {
39
+ DurableObject as EffectCfDurableObject,
40
+ DurableObjectAlarm,
41
+ DurableObjectState as EffectCfDurableObjectState,
42
+ RpcTargets,
43
+ type WorkerEnvironment,
44
+ } from 'effect-cf'
45
+ import * as Clock from 'effect/Clock'
46
+ import * as Context from 'effect/Context'
47
+ import * as SecureRandom from 'effect/crypto/SecureRandom'
48
+ import * as DateTime from 'effect/DateTime'
49
+ import * as Effect from 'effect/Effect'
50
+ import * as Layer from 'effect/Layer'
51
+ import * as Schema from 'effect/Schema'
52
+
53
+ import type { ThreadObjectNamespace } from './CloudflareBindings'
54
+ import { CloudflareThreadClient } from './CloudflareThreadClient'
55
+ import { cloudflareCryptoLayer } from './internal/crypto'
56
+ import { cloudflarePreparedInputAdmissionLayer } from './internal/prepared-admission'
57
+
58
+ const SCHEDULE_ALARM_TAG = 'effect-agent/ScheduleOwnerWake'
59
+ const SCHEDULE_ALARM_ID = 'driver'
60
+
61
+ const ScheduleAlarmPayload = Schema.Struct({
62
+ schemaVersion: Schema.Literal(1),
63
+ generation: Schema.Int.check(Schema.isGreaterThan(0)),
64
+ })
65
+
66
+ export class ScheduleAlarmProtocolError extends Schema.TaggedError<ScheduleAlarmProtocolError>()(
67
+ 'ScheduleAlarmProtocolError',
68
+ { message: Schema.String },
69
+ ) {}
70
+
71
+ const boundedProtocolMessage = (message: string): string =>
72
+ message.length <= 4_096 ? message : `${message.slice(0, 4_093)}...`
73
+
74
+ export class ScheduleOwnerProtocolError extends Schema.TaggedError<ScheduleOwnerProtocolError>()(
75
+ 'ScheduleOwnerProtocolError',
76
+ { message: Schema.String.check(Schema.isMaxLength(4_096)) },
77
+ ) {}
78
+
79
+ const ScheduleMutationRequestFields = {
80
+ schemaVersion: Schema.Literal(1),
81
+ agentId: AgentId,
82
+ input: PersistedJson,
83
+ scope: ScheduleScopeSchema,
84
+ scheduleId: ScheduleId,
85
+ timing: ScheduleTimingRequest,
86
+ destination: ScheduleDestination,
87
+ deliveryPrincipal: ScheduleScopeSchema.fields.principal,
88
+ definitions: DefinitionDigests,
89
+ admissionGroup: Schema.optionalKey(Schema.NonEmptyString.check(Schema.isMaxLength(256))),
90
+ admissionFence: Schema.optionalKey(AdmissionFence),
91
+ }
92
+
93
+ const ScheduleCreateRequest = Schema.TaggedStruct('Create', ScheduleMutationRequestFields)
94
+
95
+ const ScheduleUpdateRequest = Schema.TaggedStruct('Update', {
96
+ ...ScheduleMutationRequestFields,
97
+ expectedRevision: Schema.Int.check(Schema.isGreaterThan(0)),
98
+ })
99
+
100
+ const ScheduleGetRequest = Schema.TaggedStruct('Get', {
101
+ schemaVersion: Schema.Literal(1),
102
+ scope: ScheduleScopeSchema,
103
+ scheduleId: ScheduleId,
104
+ })
105
+
106
+ const ScheduleListRequest = Schema.TaggedStruct('List', {
107
+ schemaVersion: Schema.Literal(1),
108
+ scope: ScheduleScopeSchema,
109
+ after: Schema.optionalKey(ScheduleId),
110
+ limit: Schema.optionalKey(
111
+ Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(100)),
112
+ ),
113
+ })
114
+
115
+ const ScheduleControlRequest = Schema.TaggedStruct('Control', {
116
+ schemaVersion: Schema.Literal(1),
117
+ operation: Schema.Literals(['pause', 'resume', 'cancel']),
118
+ scope: ScheduleScopeSchema,
119
+ scheduleId: ScheduleId,
120
+ expectedRevision: Schema.Int.check(Schema.isGreaterThan(0)),
121
+ })
122
+
123
+ const ScheduleRecoverRequest = Schema.TaggedStruct('Recover', {
124
+ schemaVersion: Schema.Literal(1),
125
+ scope: ScheduleScopeSchema,
126
+ scheduleId: ScheduleId,
127
+ expectedRevision: Schema.Int.check(Schema.isGreaterThan(0)),
128
+ expectedGeneration: Schema.Natural,
129
+ })
130
+
131
+ const ScheduleOwnerRequest = Schema.Union([
132
+ ScheduleRecoverRequest,
133
+ ScheduleCreateRequest,
134
+ ScheduleUpdateRequest,
135
+ ScheduleGetRequest,
136
+ ScheduleListRequest,
137
+ ScheduleControlRequest,
138
+ ])
139
+
140
+ type ScheduleOwnerRequest = typeof ScheduleOwnerRequest.Type
141
+
142
+ const ScheduleOwnerFailure = Schema.Union([
143
+ ScheduleValidationError,
144
+ ScheduleAuthorizationError,
145
+ ScheduleConflict,
146
+ ScheduleNotFound,
147
+ ScheduleCapacityError,
148
+ ScheduleStorageError,
149
+ ScheduleFailpointError,
150
+ ScheduleOwnerProtocolError,
151
+ ])
152
+
153
+ type ScheduleOwnerFailure = typeof ScheduleOwnerFailure.Type
154
+
155
+ const ScheduleOwnerResponse = Schema.Union([
156
+ Schema.TaggedStruct('Snapshot', { value: ScheduleSnapshot }),
157
+ Schema.TaggedStruct('Page', { value: ScheduleSnapshotPageSchema }),
158
+ Schema.TaggedStruct('Failed', { failure: ScheduleOwnerFailure }),
159
+ ])
160
+
161
+ type ScheduleOwnerResponse = typeof ScheduleOwnerResponse.Type
162
+
163
+ const decodeScheduleOwnerRequest = Schema.decodeUnknownEffect(ScheduleOwnerRequest)
164
+ const encodeScheduleOwnerRequest = Schema.encodeEffect(ScheduleOwnerRequest)
165
+ const decodeScheduleOwnerResponse = Schema.decodeUnknownEffect(ScheduleOwnerResponse)
166
+ const encodeScheduleOwnerResponse = Schema.encodeEffect(ScheduleOwnerResponse)
167
+
168
+ const scheduleProtocolFailure = (message: string): ScheduleOwnerResponse => ({
169
+ _tag: 'Failed',
170
+ failure: ScheduleOwnerProtocolError.make({ message: boundedProtocolMessage(message) }),
171
+ })
172
+
173
+ export interface ScheduleOwnerObjectRpc extends Rpc.DurableObjectBranded {
174
+ schedule(encoded: unknown): Promise<unknown>
175
+ }
176
+
177
+ export class ScheduleOwnerNamespace extends Context.Service<
178
+ ScheduleOwnerNamespace,
179
+ { readonly namespace: DurableObjectNamespace<ScheduleOwnerObjectRpc> }
180
+ >()('@effect-agent/platform-cloudflare/ScheduleOwnerNamespace') {}
181
+
182
+ const passthroughAgent = (agentId: AgentId): DurableSubmitAgent<typeof PersistedJson> => ({
183
+ definition: { id: agentId, input: PersistedJson },
184
+ })
185
+
186
+ const requestOwner = (request: ScheduleOwnerRequest): ScheduleOwner => request.scope.owner
187
+
188
+ /** Provides the same authorized management service as NodeScheduling.layer. */
189
+ export class CloudflareSchedulingClient {
190
+ static readonly layer: Layer.Layer<Scheduling, never, ScheduleOwnerNamespace> = Layer.effect(
191
+ Scheduling,
192
+ Effect.gen(function*() {
193
+ const { namespace } = yield* ScheduleOwnerNamespace
194
+
195
+ const call = Effect.fnUntraced(function*(
196
+ owner: ScheduleOwner,
197
+ request: ScheduleOwnerRequest,
198
+ ): Effect.fn.Return<ScheduleOwnerResponse, ScheduleManagementFailure> {
199
+ const encoded = yield* encodeScheduleOwnerRequest(request).pipe(
200
+ Effect.mapError(() => ScheduleStorageError.make({ operation: 'Schedule Owner protocol', reason: 'corrupt' })),
201
+ )
202
+
203
+ const unavailable = (cause: unknown) => {
204
+ const error = ScheduleStorageError.make({
205
+ operation: 'call Schedule Owner',
206
+ reason: 'unavailable',
207
+ })
208
+
209
+ error.cause = cause
210
+
211
+ return error
212
+ }
213
+
214
+ const address = scheduleOwnerKey(owner)
215
+
216
+ const target = yield* RpcTargets.get(namespace, address, () => namespace.get(namespace.idFromName(address)))
217
+ .pipe(Effect.mapError(unavailable))
218
+
219
+ const raw = yield* Effect.tryPromise({
220
+ try: () => target.schedule(encoded),
221
+ catch: unavailable,
222
+ }).pipe(Effect.tapCause(() => RpcTargets.invalidate(target)))
223
+
224
+ const response = yield* decodeScheduleOwnerResponse(raw).pipe(
225
+ Effect.mapError(() => ScheduleStorageError.make({ operation: 'Schedule Owner protocol', reason: 'corrupt' })),
226
+ )
227
+
228
+ if (response._tag !== 'Failed') return response
229
+
230
+ return yield* response.failure._tag === 'ScheduleOwnerProtocolError'
231
+ ? ScheduleStorageError.make({ operation: 'Schedule Owner protocol', reason: 'corrupt' })
232
+ : response.failure
233
+ })
234
+
235
+ const encodeInput = Effect.fnUntraced(function*<InputSchema extends Schema.Top>(
236
+ agent: DurableSubmitAgent<InputSchema>,
237
+ input: InputSchema['Type'],
238
+ ): Effect.fn.Return<PersistedJson, ScheduleValidationError, InputSchema['EncodingServices']> {
239
+ const encoded = yield* Schema.encodeEffect(agent.definition.input)(input).pipe(
240
+ Effect.mapError(() =>
241
+ ScheduleValidationError.make({
242
+ message: 'Unable to encode Agent input',
243
+ })
244
+ ),
245
+ )
246
+
247
+ return yield* Schema.decodeUnknownEffect(PersistedJson)(encoded).pipe(
248
+ Effect.mapError(() =>
249
+ ScheduleValidationError.make({
250
+ message: 'Agent input does not satisfy the canonical persistence bounds',
251
+ })
252
+ ),
253
+ )
254
+ })
255
+
256
+ const create: Scheduling['Service']['create'] = Effect.fnUntraced(
257
+ function*(agent, input, options) {
258
+ const payload = yield* encodeInput(agent, input)
259
+
260
+ const response = yield* call(options.scope.owner, {
261
+ _tag: 'Create',
262
+ schemaVersion: 1,
263
+ agentId: agent.definition.id,
264
+ input: payload,
265
+ ...options,
266
+ })
267
+
268
+ return response._tag === 'Snapshot'
269
+ ? response.value
270
+ : yield* ScheduleStorageError.make({
271
+ operation: 'Schedule Owner protocol',
272
+ reason: 'corrupt',
273
+ })
274
+ },
275
+ )
276
+
277
+ const update: Scheduling['Service']['update'] = Effect.fnUntraced(
278
+ function*(agent, input, options) {
279
+ const payload = yield* encodeInput(agent, input)
280
+
281
+ const response = yield* call(options.scope.owner, {
282
+ _tag: 'Update',
283
+ schemaVersion: 1,
284
+ agentId: agent.definition.id,
285
+ input: payload,
286
+ ...options,
287
+ })
288
+
289
+ return response._tag === 'Snapshot'
290
+ ? response.value
291
+ : yield* ScheduleStorageError.make({
292
+ operation: 'Schedule Owner protocol',
293
+ reason: 'corrupt',
294
+ })
295
+ },
296
+ )
297
+
298
+ const get: Scheduling['Service']['get'] = Effect.fnUntraced(function*(scope, scheduleId) {
299
+ const response = yield* call(scope.owner, {
300
+ _tag: 'Get',
301
+ schemaVersion: 1,
302
+ scope,
303
+ scheduleId,
304
+ })
305
+
306
+ return response._tag === 'Snapshot'
307
+ ? response.value
308
+ : yield* ScheduleStorageError.make({
309
+ operation: 'Schedule Owner protocol',
310
+ reason: 'corrupt',
311
+ })
312
+ })
313
+
314
+ const list: Scheduling['Service']['list'] = Effect.fnUntraced(function*(
315
+ scope,
316
+ options = {},
317
+ ) {
318
+ const response = yield* call(scope.owner, {
319
+ _tag: 'List',
320
+ schemaVersion: 1,
321
+ scope,
322
+ ...(options.after === undefined ? {} : { after: options.after }),
323
+ ...(options.limit === undefined ? {} : { limit: options.limit }),
324
+ })
325
+
326
+ return response._tag === 'Page'
327
+ ? response.value
328
+ : yield* ScheduleStorageError.make({
329
+ operation: 'Schedule Owner protocol',
330
+ reason: 'corrupt',
331
+ })
332
+ })
333
+
334
+ const control = Effect.fnUntraced(function*(
335
+ operation: 'pause' | 'resume' | 'cancel',
336
+ scope: ScheduleScope,
337
+ scheduleId: ScheduleId,
338
+ expectedRevision: number,
339
+ ) {
340
+ const response = yield* call(scope.owner, {
341
+ _tag: 'Control',
342
+ schemaVersion: 1,
343
+ operation,
344
+ scope,
345
+ scheduleId,
346
+ expectedRevision,
347
+ })
348
+
349
+ return response._tag === 'Snapshot'
350
+ ? response.value
351
+ : yield* ScheduleStorageError.make({
352
+ operation: 'Schedule Owner protocol',
353
+ reason: 'corrupt',
354
+ })
355
+ })
356
+
357
+ return Scheduling.of({
358
+ create,
359
+ update,
360
+ get,
361
+ list,
362
+ pause: (scope, id, revision) => control('pause', scope, id, revision),
363
+ resume: (scope, id, revision) => control('resume', scope, id, revision),
364
+ recover: Effect.fnUntraced(
365
+ function*(scope, scheduleId, expectedRevision, expectedGeneration) {
366
+ const response = yield* call(scope.owner, {
367
+ _tag: 'Recover',
368
+ schemaVersion: 1,
369
+ scope,
370
+ scheduleId,
371
+ expectedRevision,
372
+ expectedGeneration,
373
+ })
374
+
375
+ return response._tag === 'Snapshot'
376
+ ? response.value
377
+ : yield* ScheduleStorageError.make({
378
+ operation: 'Schedule Owner protocol',
379
+ reason: 'corrupt',
380
+ })
381
+ },
382
+ ),
383
+ cancel: (scope, id, revision) => control('cancel', scope, id, revision),
384
+ })
385
+ }),
386
+ )
387
+ }
388
+
389
+ export class ScheduleOwnerIdentity extends Context.Service<
390
+ ScheduleOwnerIdentity,
391
+ { readonly owner: ScheduleOwner }
392
+ >()('@effect-agent/platform-cloudflare/ScheduleOwnerIdentity') {}
393
+
394
+ const decodeOwnerName = Effect.fnUntraced(function*(
395
+ name: string | null | undefined,
396
+ ): Effect.fn.Return<ScheduleOwner, ScheduleOwnerProtocolError> {
397
+ if (name === null || name === undefined) {
398
+ return yield* ScheduleOwnerProtocolError.make({
399
+ message: 'Schedule Owner objects require an idFromName identity',
400
+ })
401
+ }
402
+
403
+ const tuple = yield* Schema.decodeEffect(
404
+ Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.String])),
405
+ )(name).pipe(
406
+ Effect.mapError(() => ScheduleOwnerProtocolError.make({ message: 'Schedule Owner object name is malformed' })),
407
+ )
408
+
409
+ return yield* Schema.decodeEffect(ScheduleOwner)({
410
+ tenantId: tuple[0],
411
+ ownerId: tuple[1],
412
+ }).pipe(
413
+ Effect.mapError(() => ScheduleOwnerProtocolError.make({ message: 'Schedule Owner object identity is invalid' })),
414
+ )
415
+ })
416
+
417
+ const alarmStorageError = (operation: string) => (error: { readonly _tag: string }) =>
418
+ ScheduleStorageError.make({
419
+ operation,
420
+ reason: error._tag === 'StorageOperationError' ? 'unavailable' : 'corrupt',
421
+ })
422
+
423
+ const transactionLayer: Layer.Layer<
424
+ DoScheduleTransaction,
425
+ never,
426
+ DurableObjectAlarm.DurableObjectAlarm | SecureRandom.SecureRandom
427
+ > = Layer.effect(
428
+ DoScheduleTransaction,
429
+ Effect.gen(function*() {
430
+ const alarms = yield* DurableObjectAlarm.DurableObjectAlarm
431
+ const random = yield* SecureRandom.SecureRandom
432
+
433
+ return DoScheduleTransaction.of({
434
+ run: Effect.fnUntraced(function*(body) {
435
+ const nowMillis = yield* Clock.currentTimeMillis
436
+
437
+ return yield* alarms
438
+ .transaction((transaction) =>
439
+ body((replacement) =>
440
+ replacement.deadlineAtMillis === null
441
+ ? transaction
442
+ .cancelAlarm({ id: SCHEDULE_ALARM_ID, tag: SCHEDULE_ALARM_TAG })
443
+ .pipe(Effect.mapError(alarmStorageError('cancel Schedule Owner alarm')))
444
+ : Effect.fromOption(
445
+ DateTime.make(Math.max(replacement.deadlineAtMillis, nowMillis + 1)),
446
+ ).pipe(
447
+ Effect.mapError(() =>
448
+ ScheduleStorageError.make({
449
+ operation: 'validate Schedule Owner alarm deadline',
450
+ reason: 'corrupt',
451
+ })
452
+ ),
453
+ Effect.flatMap((runAt) =>
454
+ transaction
455
+ .scheduleAlarm({
456
+ id: SCHEDULE_ALARM_ID,
457
+ tag: SCHEDULE_ALARM_TAG,
458
+ runAt,
459
+ payload: {
460
+ schemaVersion: 1,
461
+ generation: replacement.generation,
462
+ },
463
+ })
464
+ .pipe(
465
+ Effect.provideService(SecureRandom.SecureRandom, random),
466
+ Effect.mapError(alarmStorageError('schedule Schedule Owner alarm')),
467
+ )
468
+ ),
469
+ )
470
+ )
471
+ )
472
+ .pipe(
473
+ Effect.catchTag('StorageOperationError', () =>
474
+ ScheduleStorageError.make({
475
+ operation: 'commit Schedule Owner transaction',
476
+ reason: 'unavailable',
477
+ })),
478
+ )
479
+ }),
480
+ })
481
+ }),
482
+ )
483
+
484
+ type ScheduleRuntimeServices =
485
+ | Scheduling
486
+ | ScheduleDriver
487
+ | DoScheduleAlarmControl
488
+ | ScheduleOwnerIdentity
489
+ | DurableObjectAlarm.DurableObjectAlarm
490
+
491
+ const ensureOwner = (
492
+ expected: ScheduleOwner,
493
+ request: ScheduleOwnerRequest,
494
+ ): Effect.Effect<void, ScheduleOwnerProtocolError> => {
495
+ const observed = requestOwner(request)
496
+
497
+ return observed.tenantId === expected.tenantId && observed.ownerId === expected.ownerId
498
+ ? Effect.void
499
+ : Effect.fail(
500
+ ScheduleOwnerProtocolError.make({
501
+ message: 'The request owner does not match the addressed Schedule Owner object',
502
+ }),
503
+ )
504
+ }
505
+
506
+ const handleScheduleRequest = Effect.fnUntraced(function*(
507
+ encoded: unknown,
508
+ ): Effect.fn.Return<unknown, never, Scheduling | ScheduleOwnerIdentity> {
509
+ const decoded = yield* decodeScheduleOwnerRequest(encoded).pipe(Effect.result)
510
+
511
+ if (decoded._tag === 'Failure') {
512
+ return yield* encodeScheduleOwnerResponse(
513
+ scheduleProtocolFailure('The Schedule request could not be decoded'),
514
+ ).pipe(Effect.orDie)
515
+ }
516
+ const request = decoded.success
517
+ const { owner } = yield* ScheduleOwnerIdentity
518
+ const scheduling = yield* Scheduling
519
+
520
+ const response = yield* Effect.gen(function*() {
521
+ yield* ensureOwner(owner, request)
522
+ switch (request._tag) {
523
+ case 'Create': {
524
+ const value = yield* scheduling.create(passthroughAgent(request.agentId), request.input, {
525
+ scope: request.scope,
526
+ scheduleId: request.scheduleId,
527
+ timing: request.timing,
528
+ destination: request.destination,
529
+ deliveryPrincipal: request.deliveryPrincipal,
530
+ definitions: request.definitions,
531
+ ...(request.admissionGroup === undefined
532
+ ? {}
533
+ : { admissionGroup: request.admissionGroup }),
534
+ ...(request.admissionFence === undefined
535
+ ? {}
536
+ : { admissionFence: request.admissionFence }),
537
+ })
538
+
539
+ return { _tag: 'Snapshot' as const, value }
540
+ }
541
+ case 'Update': {
542
+ const value = yield* scheduling.update(passthroughAgent(request.agentId), request.input, {
543
+ scope: request.scope,
544
+ scheduleId: request.scheduleId,
545
+ timing: request.timing,
546
+ destination: request.destination,
547
+ deliveryPrincipal: request.deliveryPrincipal,
548
+ definitions: request.definitions,
549
+ ...(request.admissionGroup === undefined
550
+ ? {}
551
+ : { admissionGroup: request.admissionGroup }),
552
+ ...(request.admissionFence === undefined
553
+ ? {}
554
+ : { admissionFence: request.admissionFence }),
555
+ expectedRevision: request.expectedRevision,
556
+ })
557
+
558
+ return { _tag: 'Snapshot' as const, value }
559
+ }
560
+ case 'Get':
561
+ return {
562
+ _tag: 'Snapshot' as const,
563
+ value: yield* scheduling.get(request.scope, request.scheduleId),
564
+ }
565
+ case 'List':
566
+ return {
567
+ _tag: 'Page' as const,
568
+ value: yield* scheduling.list(request.scope, {
569
+ ...(request.after === undefined ? {} : { after: request.after }),
570
+ ...(request.limit === undefined ? {} : { limit: request.limit }),
571
+ }),
572
+ }
573
+ case 'Recover':
574
+ return {
575
+ _tag: 'Snapshot' as const,
576
+ value: yield* scheduling.recover(
577
+ request.scope,
578
+ request.scheduleId,
579
+ request.expectedRevision,
580
+ request.expectedGeneration,
581
+ ),
582
+ }
583
+ case 'Control': {
584
+ const value = request.operation === 'pause'
585
+ ? yield* scheduling.pause(request.scope, request.scheduleId, request.expectedRevision)
586
+ : request.operation === 'resume'
587
+ ? yield* scheduling.resume(
588
+ request.scope,
589
+ request.scheduleId,
590
+ request.expectedRevision,
591
+ )
592
+ : yield* scheduling.cancel(
593
+ request.scope,
594
+ request.scheduleId,
595
+ request.expectedRevision,
596
+ )
597
+
598
+ return { _tag: 'Snapshot' as const, value }
599
+ }
600
+ }
601
+ }).pipe(
602
+ Effect.map((value): ScheduleOwnerResponse => value),
603
+ Effect.catch((failure) =>
604
+ Schema.is(ScheduleOwnerFailure)(failure)
605
+ ? Effect.succeed({ _tag: 'Failed' as const, failure })
606
+ : Effect.succeed(
607
+ scheduleProtocolFailure('The Schedule operation failed outside its public contract'),
608
+ )
609
+ ),
610
+ )
611
+
612
+ return yield* encodeScheduleOwnerResponse(response).pipe(Effect.orDie)
613
+ })
614
+
615
+ /** @internal The complete native alarm operation, including its event deadline. */
616
+ export const scheduleAlarmHandler = (limits: SchedulingLimits) =>
617
+ DurableObjectAlarm.processDue((event) =>
618
+ Effect.gen(function*() {
619
+ if (event.tag !== SCHEDULE_ALARM_TAG || event.id !== SCHEDULE_ALARM_ID) {
620
+ return yield* ScheduleAlarmProtocolError.make({
621
+ message: `Unsupported Schedule Owner alarm ${event.tag}/${event.id}`,
622
+ })
623
+ }
624
+ yield* Schema.decodeUnknownEffect(ScheduleAlarmPayload)(event.payload).pipe(
625
+ Effect.mapError(() =>
626
+ ScheduleAlarmProtocolError.make({
627
+ message: 'Unsupported Schedule Owner alarm payload version',
628
+ })
629
+ ),
630
+ )
631
+ const scheduling = yield* ScheduleDriver
632
+ const alarmControl = yield* DoScheduleAlarmControl
633
+ const { owner } = yield* ScheduleOwnerIdentity
634
+ const nowMillis = yield* Clock.currentTimeMillis
635
+
636
+ yield* alarmControl.prearm(nowMillis + limits.recoveryPollMillis)
637
+ const pass = yield* scheduling.runDue(owner)
638
+
639
+ if (pass.failed > 0) {
640
+ yield* alarmControl.prearm((yield* Clock.currentTimeMillis) + limits.recoveryPollMillis)
641
+ } else {
642
+ yield* alarmControl.reconcile
643
+ }
644
+ })
645
+ ).pipe(
646
+ // Bound due acquisition and acknowledgement as well as admission. Prepared occurrences
647
+ // and their replacement alarm survive interruption and retain their idempotency keys.
648
+ Effect.timeout('14 minutes'),
649
+ Effect.asVoid,
650
+ )
651
+
652
+ export interface ScheduleOwnerObjectInstance extends
653
+ InstanceType<
654
+ EffectCfDurableObject.DurableObjectClass<Record<never, never>, ScheduleRuntimeServices>
655
+ >
656
+ {
657
+ schedule(encoded: unknown): Promise<unknown>
658
+ alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> | void
659
+ }
660
+
661
+ export interface ScheduleOwnerObjectClass {
662
+ new(ctx: DurableObjectState, env: Cloudflare.Env): ScheduleOwnerObjectInstance
663
+ }
664
+
665
+ /**
666
+ * The host Layer supplies authorization and routing and is cached for the object incarnation.
667
+ * Cloudflare eviction does not guarantee its finalizers run. Do not acquire resources requiring
668
+ * cleanup in this Layer; acquire them inside scoped `manage` / `prepare` operations instead.
669
+ * Native services belong to effect-cf; the database and alarm runtime remain instance-owned.
670
+ */
671
+ export const makeScheduleOwnerObjectClass = <E>(
672
+ host: Layer.Layer<
673
+ ScheduleAuthorizer | ThreadObjectNamespace,
674
+ E,
675
+ | EffectCfDurableObjectState.DurableObjectState
676
+ | WorkerEnvironment
677
+ | ScheduleOwnerIdentity
678
+ | SecureRandom.SecureRandom
679
+ >,
680
+ limits: SchedulingLimits = defaultSchedulingLimits,
681
+ ): ScheduleOwnerObjectClass => {
682
+ const ownerLayer = Layer.effect(
683
+ ScheduleOwnerIdentity,
684
+ Effect.gen(function*() {
685
+ const state = yield* EffectCfDurableObjectState.DurableObjectState
686
+
687
+ return ScheduleOwnerIdentity.of({ owner: yield* decodeOwnerName(state.raw.id.name) })
688
+ }),
689
+ )
690
+
691
+ const sqlLayer = Layer.unwrap(
692
+ Effect.map(
693
+ EffectCfDurableObjectState.DurableObjectState,
694
+ (state) => SqliteClient.layer({ storage: state.raw.storage }),
695
+ ),
696
+ )
697
+
698
+ const application = Layer.merge(Scheduling.layer(limits), ScheduleDriver.layer(limits)).pipe(
699
+ Layer.provideMerge(
700
+ scheduleStoreLayer.pipe(Layer.provide(transactionLayer), Layer.provide(sqlLayer)),
701
+ ),
702
+ Layer.provide(
703
+ cloudflarePreparedInputAdmissionLayer.pipe(Layer.provide(CloudflareThreadClient.layer)),
704
+ ),
705
+ Layer.provide(ScheduleWakeNoop),
706
+ Layer.provideMerge(DurableObjectAlarm.DurableObjectAlarm.layer),
707
+ Layer.provide(host),
708
+ Layer.provideMerge(ownerLayer),
709
+ Layer.provide(cloudflareCryptoLayer),
710
+ )
711
+
712
+ const runtime: Layer.Layer<
713
+ ScheduleRuntimeServices,
714
+ E | ScheduleStorageError | ScheduleOwnerProtocolError | ScheduleValidationError,
715
+ EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment
716
+ > = Layer.effectContext(
717
+ Effect.gen(function*() {
718
+ const state = yield* EffectCfDurableObjectState.DurableObjectState
719
+ const scope = yield* Effect.scope
720
+
721
+ return yield* state.blockConcurrencyWhile(Layer.buildWithScope(application, scope))
722
+ }),
723
+ )
724
+
725
+ const rpc = {
726
+ schedule: (encoded: unknown) => handleScheduleRequest(encoded),
727
+ } satisfies EffectCfDurableObject.DurableObjectRpc<ScheduleRuntimeServices>
728
+
729
+ const ScheduleOwnerObject = EffectCfDurableObject.make(runtime, {
730
+ initialize: Effect.void,
731
+ rpc,
732
+ alarms: scheduleAlarmHandler(limits),
733
+ })
734
+
735
+ return ScheduleOwnerObject
736
+ }