@effect-agent/platform-cloudflare 0.1.0-beta.49 → 0.1.0-beta.51
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.
- package/dist/CloudflareBindings.d.mts +1 -0
- package/dist/CloudflareBindings.mjs.map +1 -1
- package/dist/CloudflareCodeMode.mjs +0 -7
- package/dist/CloudflareCodeMode.mjs.map +1 -1
- package/dist/CloudflareScheduling.mjs +36 -3
- package/dist/CloudflareScheduling.mjs.map +1 -1
- package/dist/CloudflareSubscriptions.d.mts +31 -4
- package/dist/CloudflareSubscriptions.mjs +170 -11
- package/dist/CloudflareSubscriptions.mjs.map +1 -1
- package/dist/CloudflareThreadClient.d.mts +150 -74
- package/dist/CloudflareThreadClient.mjs +18 -2
- package/dist/CloudflareThreadClient.mjs.map +1 -1
- package/dist/InteractiveBrowser.mjs +2 -1
- package/dist/InteractiveBrowser.mjs.map +1 -1
- package/dist/{ThreadObject-IrGuIO4a.mjs → ThreadObject-BY8axaWT.mjs} +11 -3
- package/dist/ThreadObject-BY8axaWT.mjs.map +1 -0
- package/dist/{ThreadObject-D-NmQZC0.d.mts → ThreadObject-sDr1JBCj.d.mts} +37 -32
- package/dist/ThreadObject.d.mts +1 -1
- package/dist/ThreadObject.mjs +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/prepared-admission-9rvlHI0y.mjs +71 -0
- package/dist/prepared-admission-9rvlHI0y.mjs.map +1 -0
- package/package.json +1 -1
- package/src/CloudflareBindings.ts +1 -0
- package/src/CloudflareCodeMode.ts +0 -12
- package/src/CloudflareScheduling.ts +52 -0
- package/src/CloudflareSubscriptions.ts +321 -8
- package/src/CloudflareThreadClient.ts +40 -0
- package/src/InteractiveBrowser.ts +3 -1
- package/src/ThreadObject.ts +27 -0
- package/src/internal/prepared-admission.ts +19 -0
- package/dist/ThreadObject-IrGuIO4a.mjs.map +0 -1
- package/dist/prepared-admission-DRBhl2Sp.mjs +0 -63
- package/dist/prepared-admission-DRBhl2Sp.mjs.map +0 -1
|
@@ -30,6 +30,7 @@ interface ThreadObjectRpc extends Rpc.DurableObjectBranded {
|
|
|
30
30
|
/** Admission-limits gate + `DurableAgentRuntime.submit`; answers a `SubmitResponse`. */
|
|
31
31
|
submitEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;
|
|
32
32
|
/** Wake-hinted, poll-guaranteed settlement wait; answers an `AwaitSettlementResponse`. */
|
|
33
|
+
submissionStatusEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;
|
|
33
34
|
awaitSettlementEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;
|
|
34
35
|
/** Event-driven durable progress wait; answers a `ProgressObserved` host response. */
|
|
35
36
|
awaitProgressEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CloudflareBindings.mjs","names":[],"sources":["../src/CloudflareBindings.ts"],"sourcesContent":["import { type ThreadId } from \"@effect-agent/core/Identifiers\";\nimport { type ProducerId } from \"@effect-agent/thread/Records\";\nimport { Context, Effect, Layer, Predicate, Schema } from \"effect\";\n\n/**\n * Cloudflare platform bindings as Effect services (DEPLOY-010: \"Cloudflare platform bindings\n * are supplied as Effect services/Layers\"). Application code never reads `env` or touches a\n * `DurableObjectState` directly — the Thread Object class constructs these Layers once\n * per incarnation and everything downstream consumes the services.\n */\n\n/** A Cloudflare platform binding was missing or carried the wrong shape (DEPLOY-003/010). */\nexport class CloudflareBindingError extends Schema.TaggedError<CloudflareBindingError>()(\n \"CloudflareBindingError\",\n {\n binding: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/**\n * The RPC surface one Thread Durable Object exposes to Workers and to sibling\n * Thread Objects. `ThreadObject.make` implements it; the Worker-side client\n * and the cross-Object transport call it through `DurableObjectNamespace` stubs. Every\n * `encoded` value is a Schema-encoded envelope (`client.ts` wire schemas for host entry\n * points, `@effect-agent/storage-cloudflare` port envelopes for `portCall`), so the RPC\n * boundary carries only structured-cloneable JSON. The optional trailing trace context is\n * transient native RPC metadata, stripped by an opted-in effect-cf receiver before decoding\n * the host envelope. It never enters durable state.\n */\nexport interface ThreadObjectRpc extends Rpc.DurableObjectBranded {\n /** Admission-limits gate + `DurableAgentRuntime.submit`; answers a `SubmitResponse`. */\n submitEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Wake-hinted, poll-guaranteed settlement wait; answers an `AwaitSettlementResponse`. */\n awaitSettlementEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Event-driven durable progress wait; answers a `ProgressObserved` host response. */\n awaitProgressEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Best-effort cancellation for one in-flight progress wait. */\n cancelProgressEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** One bounded page of canonical records; answers an `ObservePageResponse`. */\n observePage(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Durable abort intent; answers an `AbortResponse`. */\n abortEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Durable approval decision (plan §2.6); answers a `ResolveApprovalResponse`. */\n resolveApprovalEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Authorized DUR-017 Unknown-Outcome resolution; answers a `ResolveUnknownResponse`. */\n resolveUnknownEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Owner-side cross-Object port endpoint (WP2 envelopes, executed on LOCAL facets). */\n portCall(encoded: unknown): Promise<unknown>;\n /** Droppable liveness hint from another Object: arms an immediate alarm. */\n wake(): Promise<void>;\n}\n\n/**\n * The `DurableObjectNamespace` binding that addresses Thread Objects. The Object\n * identity rule is `namespace.idFromName(threadId)` (plan §1.2): Thread IDs are\n * globally unique, so the mapping is total and deterministic and no directory service exists.\n */\nexport class ThreadObjectNamespace extends Context.Service<\n ThreadObjectNamespace,\n {\n readonly namespace: DurableObjectNamespace<ThreadObjectRpc>;\n /** Stable binding name for opted-in native RPC tracing; absent by default. */\n readonly rpcTracing?: string;\n }\n>()(\"@effect-agent/platform-cloudflare/ThreadObjectNamespace\") {\n static layer(\n namespace: DurableObjectNamespace<ThreadObjectRpc>,\n options: { readonly rpcTracing?: string } = {},\n ): Layer.Layer<ThreadObjectNamespace> {\n return Layer.succeed(ThreadObjectNamespace)({\n namespace,\n ...(options.rpcTracing === undefined ? {} : { rpcTracing: options.rpcTracing }),\n });\n }\n}\n\n/**\n * Narrow one `env` member to a `DurableObjectNamespace`. `env` is an untyped platform value,\n * and a namespace binding is a host object no Schema can decode, so this is the documented\n * narrowest-boundary check (structural probe for the namespace surface the transport uses);\n * a missing or misshaped binding fails typed before any Layer is built.\n */\nexport const threadNamespaceFromEnv = Effect.fn(\"threadNamespaceFromEnv\")(function* (\n env: unknown,\n binding: string,\n): Effect.fn.Return<DurableObjectNamespace<ThreadObjectRpc>, CloudflareBindingError> {\n if (!Predicate.isObjectKeyword(env)) {\n return yield* CloudflareBindingError.make({\n binding,\n message: \"The Worker environment is not an object; no bindings are available.\",\n });\n }\n\n const candidate = yield* Effect.try({\n try: () => {\n const value: unknown = Reflect.get(env, binding);\n\n if (!Predicate.isObjectKeyword(value)) return undefined;\n const idFromName: unknown = Reflect.get(value, \"idFromName\");\n const get: unknown = Reflect.get(value, \"get\");\n\n return typeof idFromName === \"function\" && typeof get === \"function\" ? value : undefined;\n },\n catch: () =>\n CloudflareBindingError.make({\n binding,\n message: `env.${binding} could not be inspected as a DurableObjectNamespace binding.`,\n }),\n });\n\n if (candidate !== undefined) {\n // The structural probe above is the entire runtime contract this package relies on;\n // the assertion records that `idFromName`/`get` name a DurableObjectNamespace.\n return candidate as unknown as DurableObjectNamespace<ThreadObjectRpc>;\n }\n\n return yield* CloudflareBindingError.make({\n binding,\n message:\n `env.${binding} is not a DurableObjectNamespace binding; declare the Thread ` +\n \"Object class under this binding in the Worker configuration.\",\n });\n});\n\n/**\n * Build the namespace from Worker `env` (fails typed). Enable `rpcTracing` only when the\n * receiver also opts into the effect-cf native RPC trace-context contract.\n */\nexport const threadNamespaceLayer = (\n env: unknown,\n binding: string,\n options: { readonly rpcTracing?: boolean } = {},\n): Layer.Layer<ThreadObjectNamespace, CloudflareBindingError> =>\n Layer.effect(ThreadObjectNamespace)(\n Effect.map(threadNamespaceFromEnv(env, binding), (namespace) => ({\n namespace,\n ...(options.rpcTracing === true ? { rpcTracing: binding } : {}),\n })),\n );\n\n/**\n * The live Durable Object execution context of THIS incarnation. Only Layer construction and\n * the alarm service consume it; important state never lives on it (`ctx.storage` is truth,\n * everything in memory is a cache — deployment spec §11).\n */\nexport class DurableObjectContext extends Context.Service<\n DurableObjectContext,\n {\n readonly ctx: DurableObjectState;\n readonly env: unknown;\n }\n>()(\"@effect-agent/platform-cloudflare/DurableObjectContext\") {\n static layer(ctx: DurableObjectState, env: unknown): Layer.Layer<DurableObjectContext> {\n return Layer.succeed(DurableObjectContext)({ ctx, env });\n }\n}\n\n/**\n * The Thread identity this Object serializes and the producer identity its Attempts\n * write with (`{producerPrefix}:{threadId}`, plan §1.4). Derived once per incarnation\n * from `ctx.id.name` — the Object identity rule guarantees the name IS the Thread ID.\n */\nexport class ThreadObjectIdentity extends Context.Service<\n ThreadObjectIdentity,\n {\n readonly threadId: ThreadId;\n readonly producerId: ProducerId;\n }\n>()(\"@effect-agent/platform-cloudflare/ThreadObjectIdentity\") {}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAYA,IAAa,yBAAb,cAA4C,OAAO,YAAoC,CAAC,CACtF,0BACA;CACE,SAAS,OAAO;CAChB,SAAS,OAAO;AAClB,CACF,CAAC,CAAC,CAAC;;;;;;
|
|
1
|
+
{"version":3,"file":"CloudflareBindings.mjs","names":[],"sources":["../src/CloudflareBindings.ts"],"sourcesContent":["import { type ThreadId } from \"@effect-agent/core/Identifiers\";\nimport { type ProducerId } from \"@effect-agent/thread/Records\";\nimport { Context, Effect, Layer, Predicate, Schema } from \"effect\";\n\n/**\n * Cloudflare platform bindings as Effect services (DEPLOY-010: \"Cloudflare platform bindings\n * are supplied as Effect services/Layers\"). Application code never reads `env` or touches a\n * `DurableObjectState` directly — the Thread Object class constructs these Layers once\n * per incarnation and everything downstream consumes the services.\n */\n\n/** A Cloudflare platform binding was missing or carried the wrong shape (DEPLOY-003/010). */\nexport class CloudflareBindingError extends Schema.TaggedError<CloudflareBindingError>()(\n \"CloudflareBindingError\",\n {\n binding: Schema.String,\n message: Schema.String,\n },\n) {}\n\n/**\n * The RPC surface one Thread Durable Object exposes to Workers and to sibling\n * Thread Objects. `ThreadObject.make` implements it; the Worker-side client\n * and the cross-Object transport call it through `DurableObjectNamespace` stubs. Every\n * `encoded` value is a Schema-encoded envelope (`client.ts` wire schemas for host entry\n * points, `@effect-agent/storage-cloudflare` port envelopes for `portCall`), so the RPC\n * boundary carries only structured-cloneable JSON. The optional trailing trace context is\n * transient native RPC metadata, stripped by an opted-in effect-cf receiver before decoding\n * the host envelope. It never enters durable state.\n */\nexport interface ThreadObjectRpc extends Rpc.DurableObjectBranded {\n /** Admission-limits gate + `DurableAgentRuntime.submit`; answers a `SubmitResponse`. */\n submitEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Wake-hinted, poll-guaranteed settlement wait; answers an `AwaitSettlementResponse`. */\n submissionStatusEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n awaitSettlementEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Event-driven durable progress wait; answers a `ProgressObserved` host response. */\n awaitProgressEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Best-effort cancellation for one in-flight progress wait. */\n cancelProgressEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** One bounded page of canonical records; answers an `ObservePageResponse`. */\n observePage(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Durable abort intent; answers an `AbortResponse`. */\n abortEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Durable approval decision (plan §2.6); answers a `ResolveApprovalResponse`. */\n resolveApprovalEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Authorized DUR-017 Unknown-Outcome resolution; answers a `ResolveUnknownResponse`. */\n resolveUnknownEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n /** Owner-side cross-Object port endpoint (WP2 envelopes, executed on LOCAL facets). */\n portCall(encoded: unknown): Promise<unknown>;\n /** Droppable liveness hint from another Object: arms an immediate alarm. */\n wake(): Promise<void>;\n}\n\n/**\n * The `DurableObjectNamespace` binding that addresses Thread Objects. The Object\n * identity rule is `namespace.idFromName(threadId)` (plan §1.2): Thread IDs are\n * globally unique, so the mapping is total and deterministic and no directory service exists.\n */\nexport class ThreadObjectNamespace extends Context.Service<\n ThreadObjectNamespace,\n {\n readonly namespace: DurableObjectNamespace<ThreadObjectRpc>;\n /** Stable binding name for opted-in native RPC tracing; absent by default. */\n readonly rpcTracing?: string;\n }\n>()(\"@effect-agent/platform-cloudflare/ThreadObjectNamespace\") {\n static layer(\n namespace: DurableObjectNamespace<ThreadObjectRpc>,\n options: { readonly rpcTracing?: string } = {},\n ): Layer.Layer<ThreadObjectNamespace> {\n return Layer.succeed(ThreadObjectNamespace)({\n namespace,\n ...(options.rpcTracing === undefined ? {} : { rpcTracing: options.rpcTracing }),\n });\n }\n}\n\n/**\n * Narrow one `env` member to a `DurableObjectNamespace`. `env` is an untyped platform value,\n * and a namespace binding is a host object no Schema can decode, so this is the documented\n * narrowest-boundary check (structural probe for the namespace surface the transport uses);\n * a missing or misshaped binding fails typed before any Layer is built.\n */\nexport const threadNamespaceFromEnv = Effect.fn(\"threadNamespaceFromEnv\")(function* (\n env: unknown,\n binding: string,\n): Effect.fn.Return<DurableObjectNamespace<ThreadObjectRpc>, CloudflareBindingError> {\n if (!Predicate.isObjectKeyword(env)) {\n return yield* CloudflareBindingError.make({\n binding,\n message: \"The Worker environment is not an object; no bindings are available.\",\n });\n }\n\n const candidate = yield* Effect.try({\n try: () => {\n const value: unknown = Reflect.get(env, binding);\n\n if (!Predicate.isObjectKeyword(value)) return undefined;\n const idFromName: unknown = Reflect.get(value, \"idFromName\");\n const get: unknown = Reflect.get(value, \"get\");\n\n return typeof idFromName === \"function\" && typeof get === \"function\" ? value : undefined;\n },\n catch: () =>\n CloudflareBindingError.make({\n binding,\n message: `env.${binding} could not be inspected as a DurableObjectNamespace binding.`,\n }),\n });\n\n if (candidate !== undefined) {\n // The structural probe above is the entire runtime contract this package relies on;\n // the assertion records that `idFromName`/`get` name a DurableObjectNamespace.\n return candidate as unknown as DurableObjectNamespace<ThreadObjectRpc>;\n }\n\n return yield* CloudflareBindingError.make({\n binding,\n message:\n `env.${binding} is not a DurableObjectNamespace binding; declare the Thread ` +\n \"Object class under this binding in the Worker configuration.\",\n });\n});\n\n/**\n * Build the namespace from Worker `env` (fails typed). Enable `rpcTracing` only when the\n * receiver also opts into the effect-cf native RPC trace-context contract.\n */\nexport const threadNamespaceLayer = (\n env: unknown,\n binding: string,\n options: { readonly rpcTracing?: boolean } = {},\n): Layer.Layer<ThreadObjectNamespace, CloudflareBindingError> =>\n Layer.effect(ThreadObjectNamespace)(\n Effect.map(threadNamespaceFromEnv(env, binding), (namespace) => ({\n namespace,\n ...(options.rpcTracing === true ? { rpcTracing: binding } : {}),\n })),\n );\n\n/**\n * The live Durable Object execution context of THIS incarnation. Only Layer construction and\n * the alarm service consume it; important state never lives on it (`ctx.storage` is truth,\n * everything in memory is a cache — deployment spec §11).\n */\nexport class DurableObjectContext extends Context.Service<\n DurableObjectContext,\n {\n readonly ctx: DurableObjectState;\n readonly env: unknown;\n }\n>()(\"@effect-agent/platform-cloudflare/DurableObjectContext\") {\n static layer(ctx: DurableObjectState, env: unknown): Layer.Layer<DurableObjectContext> {\n return Layer.succeed(DurableObjectContext)({ ctx, env });\n }\n}\n\n/**\n * The Thread identity this Object serializes and the producer identity its Attempts\n * write with (`{producerPrefix}:{threadId}`, plan §1.4). Derived once per incarnation\n * from `ctx.id.name` — the Object identity rule guarantees the name IS the Thread ID.\n */\nexport class ThreadObjectIdentity extends Context.Service<\n ThreadObjectIdentity,\n {\n readonly threadId: ThreadId;\n readonly producerId: ProducerId;\n }\n>()(\"@effect-agent/platform-cloudflare/ThreadObjectIdentity\") {}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAYA,IAAa,yBAAb,cAA4C,OAAO,YAAoC,CAAC,CACtF,0BACA;CACE,SAAS,OAAO;CAChB,SAAS,OAAO;AAClB,CACF,CAAC,CAAC,CAAC;;;;;;AAyCH,IAAa,wBAAb,MAAa,8BAA8B,QAAQ,QAOjD,CAAC,CAAC,yDAAyD,CAAC,CAAC;CAC7D,OAAO,MACL,WACA,UAA4C,CAAC,GACT;EACpC,OAAO,MAAM,QAAQ,qBAAqB,CAAC,CAAC;GAC1C;GACA,GAAI,QAAQ,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY,QAAQ,WAAW;EAC/E,CAAC;CACH;AACF;;;;;;;AAQA,MAAa,yBAAyB,OAAO,GAAG,wBAAwB,CAAC,CAAC,WACxE,KACA,SACmF;CACnF,IAAI,CAAC,UAAU,gBAAgB,GAAG,GAChC,OAAO,OAAO,uBAAuB,KAAK;EACxC;EACA,SAAS;CACX,CAAC;CAGH,MAAM,YAAY,OAAO,OAAO,IAAI;EAClC,WAAW;GACT,MAAM,QAAiB,QAAQ,IAAI,KAAK,OAAO;GAE/C,IAAI,CAAC,UAAU,gBAAgB,KAAK,GAAG,OAAO,KAAA;GAC9C,MAAM,aAAsB,QAAQ,IAAI,OAAO,YAAY;GAC3D,MAAM,MAAe,QAAQ,IAAI,OAAO,KAAK;GAE7C,OAAO,OAAO,eAAe,cAAc,OAAO,QAAQ,aAAa,QAAQ,KAAA;EACjF;EACA,aACE,uBAAuB,KAAK;GAC1B;GACA,SAAS,OAAO,QAAQ;EAC1B,CAAC;CACL,CAAC;CAED,IAAI,cAAc,KAAA,GAGhB,OAAO;CAGT,OAAO,OAAO,uBAAuB,KAAK;EACxC;EACA,SACE,OAAO,QAAQ;CAEnB,CAAC;AACH,CAAC;;;;;AAMD,MAAa,wBACX,KACA,SACA,UAA6C,CAAC,MAE9C,MAAM,OAAO,qBAAqB,CAAC,CACjC,OAAO,IAAI,uBAAuB,KAAK,OAAO,IAAI,eAAe;CAC/D;CACA,GAAI,QAAQ,eAAe,OAAO,EAAE,YAAY,QAAQ,IAAI,CAAC;AAC/D,EAAE,CACJ;;;;;;AAOF,IAAa,uBAAb,MAAa,6BAA6B,QAAQ,QAMhD,CAAC,CAAC,wDAAwD,CAAC,CAAC;CAC5D,OAAO,MAAM,KAAyB,KAAiD;EACrF,OAAO,MAAM,QAAQ,oBAAoB,CAAC,CAAC;GAAE;GAAK;EAAI,CAAC;CACzD;AACF;;;;;;AAOA,IAAa,uBAAb,cAA0C,QAAQ,QAMhD,CAAC,CAAC,wDAAwD,CAAC,CAAC,CAAC"}
|
|
@@ -201,7 +201,6 @@ const HarnessCompleted = Schema.TaggedStruct("completed", {
|
|
|
201
201
|
logBytes: Schema.Natural,
|
|
202
202
|
resultBytes: Schema.Natural
|
|
203
203
|
});
|
|
204
|
-
const HarnessSourceInvalid = Schema.TaggedStruct("source-invalid", { message: Schema.String });
|
|
205
204
|
const HarnessNotAFunction = Schema.TaggedStruct("source-not-a-function", { actual: Schema.String });
|
|
206
205
|
const HarnessProgramFailed = Schema.TaggedStruct("program-failed", {
|
|
207
206
|
reason: Schema.Literals([
|
|
@@ -229,7 +228,6 @@ const HarnessHostCallLimit = Schema.TaggedStruct("host-call-limit", { logs: Boun
|
|
|
229
228
|
const HarnessProtocol = Schema.TaggedStruct("protocol", { message: Schema.String });
|
|
230
229
|
const HarnessOutcome = Schema.Union([
|
|
231
230
|
HarnessCompleted,
|
|
232
|
-
HarnessSourceInvalid,
|
|
233
231
|
HarnessNotAFunction,
|
|
234
232
|
HarnessProgramFailed,
|
|
235
233
|
HarnessLogLimit,
|
|
@@ -522,11 +520,6 @@ const makeExecute = (options, clock) => Effect.fn("DynamicWorkerCodeExecutor.exe
|
|
|
522
520
|
resultBytes: outcome.value.resultBytes
|
|
523
521
|
})
|
|
524
522
|
});
|
|
525
|
-
case "source-invalid": return yield* CodeSourceError.make({
|
|
526
|
-
implementation: dynamicWorkerImplementation,
|
|
527
|
-
reason: "invalid",
|
|
528
|
-
message: outcome.value.message.slice(0, 8e3)
|
|
529
|
-
});
|
|
530
523
|
case "source-not-a-function": return yield* CodeSourceError.make({
|
|
531
524
|
implementation: dynamicWorkerImplementation,
|
|
532
525
|
reason: "not-a-function",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CloudflareCodeMode.mjs","names":["#dispatch"],"sources":["../src/CloudflareCodeMode.ts"],"sourcesContent":["import {\n CodeExecutionHost,\n CodeExecutionResourceUse,\n CodeExecutionResult,\n CodeExecutionTimeoutError,\n CodeExecutor,\n CodeExecutorStartError,\n CodeExecutorTerminatedError,\n CodeExecutorUnsupportedError,\n CodeExecutionProtocolError,\n CodeHostCall,\n CodeHostCallLimitError,\n CodeHostCallResult,\n CodeOutputLimitError,\n CodeProgramFailedError,\n CodeSourceError,\n type CodeExecutorExecute,\n type CodeExecutionRequest,\n} from \"@effect-agent/sandbox/CodeExecutor\";\nimport { SandboxImplementation } from \"@effect-agent/sandbox/Sandbox\";\nimport { RpcTarget } from \"cloudflare:workers\";\nimport { Clock, Duration, Effect, Exit, Fiber, Layer, Option, Queue, Schema } from \"effect\";\n\nimport { safeCauseDiagnostic, safeCauseMessage } from \"./internal/boundary.ts\";\n\n/**\n * The Cloudflare Dynamic Worker `CodeExecutor` adapter (C4 of ADR-0017;\n * DEPLOY-011). Each pass loads one fresh Worker through the Worker Loader\n * with `globalOutbound: null`, so generated code has no ambient network,\n * bindings, or secrets; its only authority is the pass-scoped RPC target that\n * routes back into the owning event's `CodeExecutionHost` service. Platform\n * CPU limits stop synchronous runaway programs; the executor-owned wall-clock\n * deadline interrupts asynchronously suspended passes. Deployment class `E`\n * only: the adapter records no persistent state and a later pass may run in a\n * completely different isolate.\n */\nexport const dynamicWorkerImplementation = SandboxImplementation.make({\n isolation: \"isolated\",\n identity: \"cloudflare-dynamic-worker\",\n});\n\ninterface CodeModePassHost extends Rpc.RpcTargetBranded {\n readonly call: (hostCall: unknown) => Promise<unknown>;\n}\n\ninterface CodeModeHarnessEntrypoint extends Rpc.WorkerEntrypointBranded {\n readonly run: (host: CodeModePassHost) => Promise<unknown>;\n}\n\n/**\n * One object-capability endpoint for one execution pass. Workers RPC invokes\n * the target in the request context where it was created, so the native\n * Promise returned by `dispatch` and the Effect fiber that settles it share\n * one I/O owner. Passing the target as `run()`'s argument also scopes the\n * remote stub to that RPC call; no request state lives at module scope.\n */\nclass CodeModePassHostTarget extends RpcTarget implements CodeModePassHost {\n readonly #dispatch: (hostCall: unknown) => Promise<unknown>;\n\n constructor(dispatch: (hostCall: unknown) => Promise<unknown>) {\n super();\n this.#dispatch = dispatch;\n }\n\n call(hostCall: unknown): Promise<unknown> {\n return this.#dispatch(hostCall);\n }\n}\n\n/**\n * The fixed harness loaded as the dynamic worker's main module. The generated\n * source becomes `program.mjs` (`export default (<expression>);`) — a module,\n * never `eval`. The harness installs namespace globals and a bounded console,\n * imports the program, invokes it exactly once, and returns one envelope the\n * host validates through Effect Schema.\n */\nconst HARNESS_MODULE = String.raw`\nimport { WorkerEntrypoint } from \"cloudflare:workers\";\nimport programDefault from \"./program.js\";\n\nconst encoder = new TextEncoder();\nconst utf8 = (text) => encoder.encode(text).byteLength;\nconst safeText = (value) => {\n try {\n if (value instanceof Error) return (value.name + \": \" + value.message).slice(0, 4000);\n if (typeof value === \"string\") return value.slice(0, 4000);\n const encoded = JSON.stringify(value);\n return (encoded === undefined ? String(value) : encoded).slice(0, 4000);\n } catch {\n return \"[unserializable value]\";\n }\n};\nconst safeJson = (value) => {\n try {\n const encoded = JSON.stringify(value);\n if (encoded !== undefined && encoded.length <= 4000) return JSON.parse(encoded);\n } catch {}\n return safeText(value);\n};\n\nexport default class CodeModeHarness extends WorkerEntrypoint {\n async run(host) {\n const config = this.env.CODE_MODE_PASS;\n const limits = config.limits;\n const logs = [];\n let logBytes = 0;\n let fatal;\n const boundedLogs = () => logs.slice(0, 4096);\n const write = (...values) => {\n const joined = values.map(safeText).join(\" \");\n const line = joined.length > 16000 ? joined.slice(0, 15999) + \"…\" : joined;\n const bytes = utf8(line);\n if (logs.length >= 4096 || logBytes + bytes > limits.maxLogBytes) {\n fatal = fatal ?? { _tag: \"log-limit\", observed: logBytes + bytes, logs: boundedLogs() };\n throw new Error(\"code-mode log limit exceeded\");\n }\n logs.push(line);\n logBytes += bytes;\n };\n globalThis.console = { log: write, info: write, warn: write, error: write, debug: write };\n\n let hostCalls = 0;\n const makeMethod = (namespace, method) => async (argument) => {\n hostCalls += 1;\n if (hostCalls > limits.maxHostCalls) {\n fatal = fatal ?? { _tag: \"host-call-limit\", logs: boundedLogs() };\n throw new Error(\"code-mode host-call limit exceeded\");\n }\n let argText;\n try {\n argText = JSON.stringify(argument);\n } catch {}\n if (argText === undefined || utf8(argText) > limits.maxHostCallArgumentBytes) {\n fatal = fatal ?? {\n _tag: \"argument-limit\",\n observed: argText === undefined ? 0 : utf8(argText),\n logs: boundedLogs(),\n };\n throw new Error(\"code-mode host-call argument limit exceeded\");\n }\n const outcome = await host.call({\n namespace,\n method,\n argument: JSON.parse(argText),\n });\n if (outcome !== null && typeof outcome === \"object\" && outcome._tag === \"CodeHostCallSuccess\") {\n return outcome.value;\n }\n if (outcome !== null && typeof outcome === \"object\" && outcome._tag === \"CodeHostCallFailure\") {\n throw outcome.error;\n }\n fatal = fatal ?? { _tag: \"protocol\", message: \"host returned an unrecognized outcome\" };\n throw new Error(\"code-mode host protocol violation\");\n };\n for (const namespace of config.namespaces) {\n const methods = {};\n for (const method of namespace.methods) {\n methods[method] = makeMethod(namespace.name, method);\n }\n globalThis[namespace.name] = methods;\n }\n\n // program.js is imported statically at the top of this module, so a\n // syntactically invalid program fails the whole harness at load (mapped\n // to a source error by the host). Using a static import keeps this module\n // free of dynamic-import expressions, which single-script Miniflare hosts\n // reject. The isolation boundary does NOT depend on the ordering of this\n // import versus the console/namespace shims installed below: the loaded\n // Worker has globalOutbound: null and no bindings, secrets, or env from\n // the Worker Loader config BEFORE any module in the graph evaluates, so\n // module-level program code has no ambient authority regardless. The\n // shims below are usability wrappers (bounded console, namespace globals),\n // and the accepted program is a single async-function expression whose\n // body runs only when invoked here — after the shims exist.\n const program = programDefault;\n if (typeof program !== \"function\") {\n return { _tag: \"source-not-a-function\", actual: typeof program };\n }\n try {\n const value = await program();\n if (fatal !== undefined) return fatal;\n let text;\n try {\n text = JSON.stringify(value);\n } catch {}\n if (text === undefined) {\n return {\n _tag: \"program-failed\",\n reason: \"non-json-result\",\n thrown: null,\n message: \"The program must return a JSON value\",\n logs: boundedLogs(),\n };\n }\n const resultBytes = utf8(text);\n if (resultBytes > limits.maxResultBytes) {\n return { _tag: \"result-limit\", observed: resultBytes, logs: boundedLogs() };\n }\n return {\n _tag: \"completed\",\n value: JSON.parse(text),\n logs: boundedLogs(),\n hostCalls,\n logBytes,\n resultBytes,\n };\n } catch (cause) {\n if (fatal !== undefined) return fatal;\n return {\n _tag: \"program-failed\",\n reason: cause instanceof Error ? \"threw\" : \"rejected\",\n thrown: safeJson(cause),\n message: safeText(cause),\n logs: boundedLogs(),\n };\n }\n }\n}\n`;\n\nconst BoundedLogs = Schema.Array(Schema.String.check(Schema.isMaxLength(16 * 1024))).check(\n Schema.isMaxLength(4_096),\n);\n\nconst HarnessCompleted = Schema.TaggedStruct(\"completed\", {\n value: Schema.Json,\n logs: BoundedLogs,\n hostCalls: Schema.Natural,\n logBytes: Schema.Natural,\n resultBytes: Schema.Natural,\n});\n\nconst HarnessSourceInvalid = Schema.TaggedStruct(\"source-invalid\", {\n message: Schema.String,\n});\n\nconst HarnessNotAFunction = Schema.TaggedStruct(\"source-not-a-function\", {\n actual: Schema.String,\n});\n\nconst HarnessProgramFailed = Schema.TaggedStruct(\"program-failed\", {\n reason: Schema.Literals([\"threw\", \"rejected\", \"non-json-result\"]),\n thrown: Schema.Json,\n message: Schema.String,\n logs: BoundedLogs,\n});\n\nconst HarnessLogLimit = Schema.TaggedStruct(\"log-limit\", {\n observed: Schema.Natural,\n logs: BoundedLogs,\n});\n\nconst HarnessArgumentLimit = Schema.TaggedStruct(\"argument-limit\", {\n observed: Schema.Natural,\n logs: BoundedLogs,\n});\n\nconst HarnessResultLimit = Schema.TaggedStruct(\"result-limit\", {\n observed: Schema.Natural,\n logs: BoundedLogs,\n});\n\nconst HarnessHostCallLimit = Schema.TaggedStruct(\"host-call-limit\", {\n logs: BoundedLogs,\n});\n\nconst HarnessProtocol = Schema.TaggedStruct(\"protocol\", {\n message: Schema.String,\n});\n\nconst HarnessOutcome = Schema.Union([\n HarnessCompleted,\n HarnessSourceInvalid,\n HarnessNotAFunction,\n HarnessProgramFailed,\n HarnessLogLimit,\n HarnessArgumentLimit,\n HarnessResultLimit,\n HarnessHostCallLimit,\n HarnessProtocol,\n]);\n\nconst HarnessPassConfig = Schema.Struct({\n namespaces: Schema.Array(\n Schema.Struct({\n name: Schema.NonEmptyString,\n methods: Schema.Array(Schema.NonEmptyString).check(Schema.isMaxLength(64)),\n }),\n ).check(Schema.isMaxLength(32)),\n limits: Schema.Struct({\n maxLogBytes: Schema.Natural,\n maxResultBytes: Schema.Natural,\n maxHostCalls: Schema.Natural,\n maxHostCallArgumentBytes: Schema.Natural,\n }),\n});\n\nconst encodeHarnessPassConfig = Schema.encodeSync(HarnessPassConfig);\nconst encodeJsonPayload = Schema.encodeSync(Schema.fromJsonString(Schema.Json));\nconst decodeJsonPayload = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Json));\n\nconst decodeHarnessOutcome = (value: unknown) => {\n try {\n return Schema.decodeUnknownOption(HarnessOutcome)(value);\n } catch {\n return Option.none<typeof HarnessOutcome.Type>();\n }\n};\n\nconst decodeHostCall = (value: unknown) => {\n try {\n return Schema.decodeUnknownOption(CodeHostCall)(value);\n } catch {\n return Option.none<CodeHostCall>();\n }\n};\n\nconst decodeHostCallResult = (value: unknown) => {\n try {\n return Schema.decodeUnknownOption(CodeHostCallResult)(value);\n } catch {\n return Option.none<CodeHostCallResult>();\n }\n};\n\n/** Dispose a Cloudflare RPC handle when the runtime supplies its untyped disposal hook. @internal */\nexport const disposeRpcHandle = (handle: unknown): Effect.Effect<void> =>\n Effect.try({\n try: () => {\n if ((typeof handle !== \"object\" && typeof handle !== \"function\") || handle === null) return;\n if (!(Symbol.dispose in handle)) return;\n const dispose = Reflect.get(handle, Symbol.dispose);\n\n if (typeof dispose === \"function\") {\n Reflect.apply(dispose, handle, []);\n }\n },\n catch: (cause) =>\n safeCauseDiagnostic(cause, \"The Cloudflare RPC disposal hook failed without a diagnostic\"),\n }).pipe(\n Effect.catch((diagnostic) =>\n Effect.logWarning(`Cloudflare RPC handle disposal failed: ${diagnostic}`).pipe(\n Effect.ignoreCause,\n ),\n ),\n );\n\n/**\n * Project a host outcome to the plain JSON envelope the harness reads. A\n * `CodeExecutionHost` may return either real `CodeHostCallResult` instances\n * (the substitute and conformance kit) or plain-object equivalents (the Code\n * Mode capability's broker route), so this reads the shared fields rather than\n * `Schema.encodeSync`, which would reject a plain object.\n */\ninterface EncodedHostResultPayload {\n readonly encodedPayload: string;\n readonly resultBytes: number;\n}\n\nconst encodeHostResultPayload = (\n outcome: CodeHostCallResult,\n): EncodedHostResultPayload | undefined => {\n try {\n const payload = outcome._tag === \"CodeHostCallSuccess\" ? outcome.value : outcome.error;\n const encodedPayload = encodeJsonPayload(payload);\n\n return {\n encodedPayload,\n resultBytes: utf8ByteLength(encodedPayload),\n };\n } catch {\n return undefined;\n }\n};\n\nconst utf8ByteLength = (value: string): number => {\n let total = 0;\n\n for (const character of value) {\n const codePoint = character.codePointAt(0) ?? 0;\n\n total += codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4;\n }\n\n return total;\n};\n\ninterface QueuedHostCall {\n readonly call: CodeHostCall;\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n}\n\ntype HostWork =\n | { readonly _tag: \"call\"; readonly queued: QueuedHostCall }\n | { readonly _tag: \"limit\" };\n\ntype HostDispatchError =\n | CodeExecutionTimeoutError\n | CodeOutputLimitError\n | CodeExecutionProtocolError\n | CodeHostCallLimitError;\n\n/** Reserved global names the harness owns inside the dynamic worker. */\nconst reservedHarnessGlobals = new Set([\"console\"]);\n\nexport interface DynamicWorkerCodeExecutorOptions {\n /** The `worker_loader` binding. */\n readonly loader: WorkerLoader;\n /** Compatibility date for dynamic workers; defaults to `2025-05-01`. */\n readonly compatibilityDate?: string | undefined;\n}\n\nconst makeExecute = (\n options: DynamicWorkerCodeExecutorOptions,\n clock: Clock.Clock,\n): CodeExecutorExecute =>\n Effect.fn(\"DynamicWorkerCodeExecutor.execute\")(function* (request: CodeExecutionRequest) {\n if (request.network._tag !== \"NetworkDisabled\") {\n return yield* CodeExecutorUnsupportedError.make({\n implementation: dynamicWorkerImplementation,\n feature: \"network\",\n message:\n \"The Dynamic Worker executor denies all egress with globalOutbound: null; an allowlist is not supported in the first slice\",\n });\n }\n const sourceBytes = utf8ByteLength(request.source);\n\n if (sourceBytes > request.limits.maxSourceBytes) {\n return yield* CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"oversized\",\n message: `Source is ${sourceBytes} bytes; the request allows ${request.limits.maxSourceBytes}`,\n });\n }\n for (const namespace of request.namespaces) {\n if (reservedHarnessGlobals.has(namespace.name)) {\n return yield* CodeExecutorUnsupportedError.make({\n implementation: dynamicWorkerImplementation,\n feature: \"namespaces\",\n message: `Namespace ${namespace.name} collides with a harness binding`,\n });\n }\n }\n const host = yield* CodeExecutionHost;\n\n // This synchronous clock access is confined to callbacks that must compute a timeout\n // immediately. The Clock service remains the authority, so tests and hosts can replace it.\n const startedAt = clock.monotonicTimeNanosUnsafe();\n const passDeadline = startedAt + Duration.toNanosUnsafe(request.limits.maxWallTime);\n\n const remainingPassWallTime = (): Duration.Duration => {\n const now = clock.monotonicTimeNanosUnsafe();\n\n return Duration.nanos(passDeadline > now ? passDeadline - now : 0n);\n };\n\n let issuedHostCalls = 0;\n let passOpen = true;\n const queuedHostCalls: Array<QueuedHostCall> = [];\n let passFailure: HostDispatchError | undefined;\n\n const failPass = (error: HostDispatchError): void => {\n if (passFailure === undefined) passFailure = error;\n };\n\n const rejectQueuedHostCalls = (reason: Error): void => {\n for (const queued of queuedHostCalls.splice(0)) {\n queued.reject(reason);\n }\n };\n\n const queue = yield* Queue.unbounded<HostWork>();\n\n const deliverHostOutcome = (\n queued: QueuedHostCall,\n outcome: CodeHostCallResult,\n ): Effect.Effect<void, CodeExecutionProtocolError | CodeOutputLimitError> =>\n Effect.gen(function* () {\n const decoded = decodeHostCallResult(outcome);\n\n if (Option.isNone(decoded)) {\n const error = CodeExecutionProtocolError.make({\n implementation: dynamicWorkerImplementation,\n message: \"The execution host returned a value outside the CodeHostCallResult schema\",\n });\n\n failPass(error);\n\n return yield* error;\n }\n const encoded = encodeHostResultPayload(decoded.value);\n\n if (encoded === undefined || encoded.resultBytes > request.limits.maxHostCallResultBytes) {\n const error = CodeOutputLimitError.make({\n implementation: dynamicWorkerImplementation,\n surface: \"host-call-result\",\n limit: request.limits.maxHostCallResultBytes,\n observed: encoded?.resultBytes ?? 0,\n logs: [],\n });\n\n failPass(error);\n\n return yield* error;\n }\n const normalizedPayload = decodeJsonPayload(encoded.encodedPayload);\n\n if (Option.isNone(normalizedPayload)) {\n const error = CodeExecutionProtocolError.make({\n implementation: dynamicWorkerImplementation,\n message: \"The execution host returned a result that could not cross the JSON boundary\",\n });\n\n failPass(error);\n\n return yield* error;\n }\n queued.resolve(\n decoded.value._tag === \"CodeHostCallSuccess\"\n ? { _tag: \"CodeHostCallSuccess\", value: normalizedPayload.value }\n : { _tag: \"CodeHostCallFailure\", error: normalizedPayload.value },\n );\n });\n\n // Workers RPC into the loader isolate cannot settle on the fiber blocked\n // in `entrypoint.run()`. A Scope-owned sibling fiber keeps that\n // independence while inheriting the pass Context and dying with the Scope.\n const serveHostCalls = Effect.gen(function* () {\n while (true) {\n const work = yield* Queue.take(queue);\n\n if (work._tag === \"limit\") {\n const error = CodeHostCallLimitError.make({\n implementation: dynamicWorkerImplementation,\n limit: request.limits.maxHostCalls,\n logs: [],\n });\n\n failPass(error);\n\n return yield* error;\n }\n const queued = work.queued;\n\n yield* host.call(queued.call).pipe(\n Effect.timeoutOrElse({\n duration: remainingPassWallTime(),\n orElse: () => {\n const error = CodeExecutionTimeoutError.make({\n implementation: dynamicWorkerImplementation,\n kind: \"wall-clock\",\n maxWallTime: request.limits.maxWallTime,\n logs: [],\n });\n\n failPass(error);\n\n return error;\n },\n }),\n Effect.flatMap((outcome) => deliverHostOutcome(queued, outcome)),\n Effect.tapError(() =>\n Effect.sync(() => queued.reject(new Error(\"Code Mode host call failed\"))),\n ),\n Effect.onInterrupt(() =>\n Effect.sync(() => queued.reject(new Error(\"Code Mode pass is closing\"))),\n ),\n );\n }\n });\n\n const server = yield* serveHostCalls.pipe(Effect.forkScoped);\n\n const dispatch = (hostCall: unknown): Promise<unknown> => {\n if (!passOpen) {\n return Promise.reject(new Error(\"Code Mode pass is closing\"));\n }\n issuedHostCalls += 1;\n if (issuedHostCalls > request.limits.maxHostCalls) {\n const error = CodeHostCallLimitError.make({\n implementation: dynamicWorkerImplementation,\n limit: request.limits.maxHostCalls,\n logs: [],\n });\n\n failPass(error);\n Queue.offerUnsafe(queue, { _tag: \"limit\" });\n\n return Promise.reject(new Error(\"host-call limit exceeded\"));\n }\n const decoded = decodeHostCall(hostCall);\n\n if (Option.isNone(decoded)) {\n return Promise.reject(new TypeError(\"host calls must match the CodeHostCall schema\"));\n }\n\n return new Promise((resolve, reject) => {\n const queued = { call: decoded.value, resolve, reject };\n\n queuedHostCalls.push(queued);\n Queue.offerUnsafe(queue, { _tag: \"call\", queued });\n });\n };\n\n const closeAdmission = Effect.sync(() => {\n passOpen = false;\n rejectQueuedHostCalls(new Error(\"Code Mode pass is closing\"));\n });\n\n yield* Effect.addFinalizer(() => closeAdmission.pipe(Effect.andThen(Fiber.interrupt(server))));\n\n // No `allowExperimental`: the runtime only accepts it when the CALLING\n // worker carries the `experimental` compatibility flag, which deployed\n // consumers cannot set — the option would reject every pass in\n // production. The harness needs no experimental runtime features.\n const workerCode: WorkerLoaderWorkerCode = {\n compatibilityDate: options.compatibilityDate ?? \"2025-05-01\",\n mainModule: \"harness.js\",\n modules: {\n \"harness.js\": HARNESS_MODULE,\n \"program.js\": `export default (\\n${request.source}\\n);`,\n },\n env: {\n CODE_MODE_PASS: encodeHarnessPassConfig({\n namespaces: request.namespaces.map((namespace) => ({\n name: namespace.name,\n methods: namespace.methods,\n })),\n limits: {\n maxLogBytes: request.limits.maxLogBytes,\n maxResultBytes: request.limits.maxResultBytes,\n maxHostCalls: request.limits.maxHostCalls,\n maxHostCallArgumentBytes: request.limits.maxHostCallArgumentBytes,\n },\n }),\n },\n globalOutbound: null,\n ...(request.limits.cpuMillis === undefined\n ? {}\n : {\n limits: {\n cpuMs: request.limits.cpuMillis,\n subRequests: request.limits.maxHostCalls + 8,\n },\n }),\n };\n\n const worker = yield* Effect.acquireRelease(\n Effect.try({\n try: () => options.loader.load(workerCode),\n catch: (cause) => {\n const text = safeCauseMessage(cause, \"The Worker Loader failed without a diagnostic\");\n\n // Blame the program's source ONLY on a genuine compile diagnostic;\n // any other load rejection is an infrastructure start failure, not\n // the model's fault (see classifyWorkerFailure for the same split).\n if (/syntaxerror|failed to (compile|parse)/i.test(text)) {\n return CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"invalid\",\n message: text.slice(0, 8_000),\n });\n }\n\n return CodeExecutorStartError.make({\n implementation: dynamicWorkerImplementation,\n message: `The Worker Loader rejected the pass: ${text}`.slice(0, 8_000),\n cause,\n });\n },\n }),\n disposeRpcHandle,\n );\n\n const entrypoint = yield* Effect.acquireRelease(\n Effect.try({\n try: () => worker.getEntrypoint<CodeModeHarnessEntrypoint>(),\n catch: (cause) => classifyWorkerFailure(cause, request.limits.maxWallTime),\n }),\n disposeRpcHandle,\n );\n\n const rpc = Effect.tryPromise({\n try: () => entrypoint.run(new CodeModePassHostTarget(dispatch)),\n catch: (cause) => classifyWorkerFailure(cause, request.limits.maxWallTime),\n });\n\n const exit = yield* Effect.raceFirst(\n rpc.pipe(\n Effect.timeoutOrElse({\n duration: remainingPassWallTime(),\n orElse: () =>\n CodeExecutionTimeoutError.make({\n implementation: dynamicWorkerImplementation,\n kind: \"wall-clock\",\n maxWallTime: request.limits.maxWallTime,\n logs: [],\n }),\n }),\n ),\n Fiber.join(server),\n ).pipe(Effect.exit);\n\n yield* closeAdmission;\n yield* Fiber.interrupt(server);\n if (passFailure !== undefined) {\n return yield* passFailure;\n }\n if (Exit.isFailure(exit)) {\n return yield* Effect.failCause(exit.cause);\n }\n const raw = exit.value;\n const finishedAt = clock.monotonicTimeNanosUnsafe();\n\n const outcome = decodeHarnessOutcome(raw);\n\n if (Option.isNone(outcome)) {\n return yield* CodeExecutionProtocolError.make({\n implementation: dynamicWorkerImplementation,\n message: \"The dynamic worker returned a value outside the harness envelope schema\",\n });\n }\n switch (outcome.value._tag) {\n case \"completed\": {\n return CodeExecutionResult.make({\n implementation: dynamicWorkerImplementation,\n value: outcome.value.value,\n logs: outcome.value.logs,\n resourceUse: CodeExecutionResourceUse.make({\n wallTime: Duration.nanos(finishedAt > startedAt ? finishedAt - startedAt : 0n),\n hostCalls: outcome.value.hostCalls,\n logBytes: outcome.value.logBytes,\n resultBytes: outcome.value.resultBytes,\n }),\n });\n }\n case \"source-invalid\": {\n return yield* CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"invalid\",\n message: outcome.value.message.slice(0, 8_000),\n });\n }\n case \"source-not-a-function\": {\n return yield* CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"not-a-function\",\n message: `The source expression evaluated to ${outcome.value.actual}; it must evaluate to one async function`,\n });\n }\n case \"program-failed\": {\n return yield* CodeProgramFailedError.make({\n implementation: dynamicWorkerImplementation,\n reason: outcome.value.reason,\n thrown: outcome.value.thrown,\n message: outcome.value.message.slice(0, 8_000),\n logs: outcome.value.logs,\n });\n }\n case \"log-limit\": {\n return yield* CodeOutputLimitError.make({\n implementation: dynamicWorkerImplementation,\n surface: \"logs\",\n limit: request.limits.maxLogBytes,\n observed: outcome.value.observed,\n logs: outcome.value.logs,\n });\n }\n case \"argument-limit\": {\n return yield* CodeOutputLimitError.make({\n implementation: dynamicWorkerImplementation,\n surface: \"host-call-argument\",\n limit: request.limits.maxHostCallArgumentBytes,\n observed: outcome.value.observed,\n logs: outcome.value.logs,\n });\n }\n case \"result-limit\": {\n return yield* CodeOutputLimitError.make({\n implementation: dynamicWorkerImplementation,\n surface: \"result\",\n limit: request.limits.maxResultBytes,\n observed: outcome.value.observed,\n logs: outcome.value.logs,\n });\n }\n case \"host-call-limit\": {\n return yield* CodeHostCallLimitError.make({\n implementation: dynamicWorkerImplementation,\n limit: request.limits.maxHostCalls,\n logs: outcome.value.logs,\n });\n }\n case \"protocol\": {\n return yield* CodeExecutionProtocolError.make({\n implementation: dynamicWorkerImplementation,\n message: outcome.value.message.slice(0, 8_000),\n });\n }\n }\n });\n\n/**\n * Expected worker-level failures map into the typed union with bounded\n * diagnostics; anything unrecognized stays a start/termination error rather\n * than a fabricated program result.\n */\nconst classifyWorkerFailure = (\n cause: unknown,\n maxWallTime: Duration.Duration,\n):\n | CodeExecutionTimeoutError\n | CodeExecutorTerminatedError\n | CodeExecutorStartError\n | CodeSourceError => {\n const text = safeCauseDiagnostic(cause, \"[unserializable worker failure]\");\n\n // `WorkerLoader.load()` is lazy, so a module-compile error in the generated\n // program surfaces here at first use. Blame the program's source ONLY on a\n // genuine compile diagnostic (a `SyntaxError` or an explicit compile\n // failure) — the fixed harness is valid, so the fault is in program.js. A\n // bare \"failed to start Worker\" without a compile diagnostic is an\n // infrastructure start failure, not the model's fault, so it must NOT be\n // misclassified as a source error.\n if (/syntaxerror|failed to (compile|parse)/i.test(text)) {\n return CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"invalid\",\n message: text.slice(0, 8_000),\n });\n }\n if (/cpu/i.test(text)) {\n return CodeExecutionTimeoutError.make({\n implementation: dynamicWorkerImplementation,\n kind: \"cpu\",\n maxWallTime,\n logs: [],\n });\n }\n if (/failed to start worker/i.test(text)) {\n return CodeExecutorStartError.make({\n implementation: dynamicWorkerImplementation,\n message: text.slice(0, 8_000),\n cause,\n });\n }\n\n return CodeExecutorTerminatedError.make({\n implementation: dynamicWorkerImplementation,\n message: text.slice(0, 8_000),\n });\n};\n\n/** Layer building the Dynamic Worker `CodeExecutor` from resolved bindings. */\nexport const dynamicWorkerCodeExecutorLayer = (\n options: DynamicWorkerCodeExecutorOptions,\n): Layer.Layer<CodeExecutor> =>\n Layer.effect(\n CodeExecutor,\n Effect.gen(function* () {\n const clock = yield* Clock.Clock;\n\n return CodeExecutor.of({ execute: makeExecute(options, clock) });\n }),\n );\n\n/** Assemble Code Mode handlers with the isolated Dynamic Worker executor. */\nexport const CloudflareCodeMode = {\n /**\n * Provide the selected tool handlers at construction, where Code Mode captures them.\n * Their errors and remaining dependencies stay visible. The definition still owns the\n * allowlist and limits; the runtime supplies the live Tool broker for each scoped pass.\n */\n layer: <A, E, R, Handlers, HandlerError, HandlerRequirements>(\n definition: { readonly handlers: Layer.Layer<A, E, R> },\n options: DynamicWorkerCodeExecutorOptions & {\n readonly handlers: Layer.Layer<Handlers, HandlerError, HandlerRequirements>;\n },\n ) =>\n definition.handlers.pipe(\n Layer.provide(options.handlers),\n Layer.provide(dynamicWorkerCodeExecutorLayer(options)),\n ),\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAa,8BAA8B,sBAAsB,KAAK;CACpE,WAAW;CACX,UAAU;AACZ,CAAC;;;;;;;;AAiBD,IAAM,yBAAN,cAAqC,UAAsC;CACzE;CAEA,YAAY,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atch"],"sources":["../src/CloudflareCodeMode.ts"],"sourcesContent":["import {\n CodeExecutionHost,\n CodeExecutionResourceUse,\n CodeExecutionResult,\n CodeExecutionTimeoutError,\n CodeExecutor,\n CodeExecutorStartError,\n CodeExecutorTerminatedError,\n CodeExecutorUnsupportedError,\n CodeExecutionProtocolError,\n CodeHostCall,\n CodeHostCallLimitError,\n CodeHostCallResult,\n CodeOutputLimitError,\n CodeProgramFailedError,\n CodeSourceError,\n type CodeExecutorExecute,\n type CodeExecutionRequest,\n} from \"@effect-agent/sandbox/CodeExecutor\";\nimport { SandboxImplementation } from \"@effect-agent/sandbox/Sandbox\";\nimport { RpcTarget } from \"cloudflare:workers\";\nimport { Clock, Duration, Effect, Exit, Fiber, Layer, Option, Queue, Schema } from \"effect\";\n\nimport { safeCauseDiagnostic, safeCauseMessage } from \"./internal/boundary.ts\";\n\n/**\n * The Cloudflare Dynamic Worker `CodeExecutor` adapter (C4 of ADR-0017;\n * DEPLOY-011). Each pass loads one fresh Worker through the Worker Loader\n * with `globalOutbound: null`, so generated code has no ambient network,\n * bindings, or secrets; its only authority is the pass-scoped RPC target that\n * routes back into the owning event's `CodeExecutionHost` service. Platform\n * CPU limits stop synchronous runaway programs; the executor-owned wall-clock\n * deadline interrupts asynchronously suspended passes. Deployment class `E`\n * only: the adapter records no persistent state and a later pass may run in a\n * completely different isolate.\n */\nexport const dynamicWorkerImplementation = SandboxImplementation.make({\n isolation: \"isolated\",\n identity: \"cloudflare-dynamic-worker\",\n});\n\ninterface CodeModePassHost extends Rpc.RpcTargetBranded {\n readonly call: (hostCall: unknown) => Promise<unknown>;\n}\n\ninterface CodeModeHarnessEntrypoint extends Rpc.WorkerEntrypointBranded {\n readonly run: (host: CodeModePassHost) => Promise<unknown>;\n}\n\n/**\n * One object-capability endpoint for one execution pass. Workers RPC invokes\n * the target in the request context where it was created, so the native\n * Promise returned by `dispatch` and the Effect fiber that settles it share\n * one I/O owner. Passing the target as `run()`'s argument also scopes the\n * remote stub to that RPC call; no request state lives at module scope.\n */\nclass CodeModePassHostTarget extends RpcTarget implements CodeModePassHost {\n readonly #dispatch: (hostCall: unknown) => Promise<unknown>;\n\n constructor(dispatch: (hostCall: unknown) => Promise<unknown>) {\n super();\n this.#dispatch = dispatch;\n }\n\n call(hostCall: unknown): Promise<unknown> {\n return this.#dispatch(hostCall);\n }\n}\n\n/**\n * The fixed harness loaded as the dynamic worker's main module. The generated\n * source becomes `program.mjs` (`export default (<expression>);`) — a module,\n * never `eval`. The harness installs namespace globals and a bounded console,\n * imports the program, invokes it exactly once, and returns one envelope the\n * host validates through Effect Schema.\n */\nconst HARNESS_MODULE = String.raw`\nimport { WorkerEntrypoint } from \"cloudflare:workers\";\nimport programDefault from \"./program.js\";\n\nconst encoder = new TextEncoder();\nconst utf8 = (text) => encoder.encode(text).byteLength;\nconst safeText = (value) => {\n try {\n if (value instanceof Error) return (value.name + \": \" + value.message).slice(0, 4000);\n if (typeof value === \"string\") return value.slice(0, 4000);\n const encoded = JSON.stringify(value);\n return (encoded === undefined ? String(value) : encoded).slice(0, 4000);\n } catch {\n return \"[unserializable value]\";\n }\n};\nconst safeJson = (value) => {\n try {\n const encoded = JSON.stringify(value);\n if (encoded !== undefined && encoded.length <= 4000) return JSON.parse(encoded);\n } catch {}\n return safeText(value);\n};\n\nexport default class CodeModeHarness extends WorkerEntrypoint {\n async run(host) {\n const config = this.env.CODE_MODE_PASS;\n const limits = config.limits;\n const logs = [];\n let logBytes = 0;\n let fatal;\n const boundedLogs = () => logs.slice(0, 4096);\n const write = (...values) => {\n const joined = values.map(safeText).join(\" \");\n const line = joined.length > 16000 ? joined.slice(0, 15999) + \"…\" : joined;\n const bytes = utf8(line);\n if (logs.length >= 4096 || logBytes + bytes > limits.maxLogBytes) {\n fatal = fatal ?? { _tag: \"log-limit\", observed: logBytes + bytes, logs: boundedLogs() };\n throw new Error(\"code-mode log limit exceeded\");\n }\n logs.push(line);\n logBytes += bytes;\n };\n globalThis.console = { log: write, info: write, warn: write, error: write, debug: write };\n\n let hostCalls = 0;\n const makeMethod = (namespace, method) => async (argument) => {\n hostCalls += 1;\n if (hostCalls > limits.maxHostCalls) {\n fatal = fatal ?? { _tag: \"host-call-limit\", logs: boundedLogs() };\n throw new Error(\"code-mode host-call limit exceeded\");\n }\n let argText;\n try {\n argText = JSON.stringify(argument);\n } catch {}\n if (argText === undefined || utf8(argText) > limits.maxHostCallArgumentBytes) {\n fatal = fatal ?? {\n _tag: \"argument-limit\",\n observed: argText === undefined ? 0 : utf8(argText),\n logs: boundedLogs(),\n };\n throw new Error(\"code-mode host-call argument limit exceeded\");\n }\n const outcome = await host.call({\n namespace,\n method,\n argument: JSON.parse(argText),\n });\n if (outcome !== null && typeof outcome === \"object\" && outcome._tag === \"CodeHostCallSuccess\") {\n return outcome.value;\n }\n if (outcome !== null && typeof outcome === \"object\" && outcome._tag === \"CodeHostCallFailure\") {\n throw outcome.error;\n }\n fatal = fatal ?? { _tag: \"protocol\", message: \"host returned an unrecognized outcome\" };\n throw new Error(\"code-mode host protocol violation\");\n };\n for (const namespace of config.namespaces) {\n const methods = {};\n for (const method of namespace.methods) {\n methods[method] = makeMethod(namespace.name, method);\n }\n globalThis[namespace.name] = methods;\n }\n\n // program.js is imported statically at the top of this module, so a\n // syntactically invalid program fails the whole harness at load (mapped\n // to a source error by the host). Using a static import keeps this module\n // free of dynamic-import expressions, which single-script Miniflare hosts\n // reject. The isolation boundary does NOT depend on the ordering of this\n // import versus the console/namespace shims installed below: the loaded\n // Worker has globalOutbound: null and no bindings, secrets, or env from\n // the Worker Loader config BEFORE any module in the graph evaluates, so\n // module-level program code has no ambient authority regardless. The\n // shims below are usability wrappers (bounded console, namespace globals),\n // and the accepted program is a single async-function expression whose\n // body runs only when invoked here — after the shims exist.\n const program = programDefault;\n if (typeof program !== \"function\") {\n return { _tag: \"source-not-a-function\", actual: typeof program };\n }\n try {\n const value = await program();\n if (fatal !== undefined) return fatal;\n let text;\n try {\n text = JSON.stringify(value);\n } catch {}\n if (text === undefined) {\n return {\n _tag: \"program-failed\",\n reason: \"non-json-result\",\n thrown: null,\n message: \"The program must return a JSON value\",\n logs: boundedLogs(),\n };\n }\n const resultBytes = utf8(text);\n if (resultBytes > limits.maxResultBytes) {\n return { _tag: \"result-limit\", observed: resultBytes, logs: boundedLogs() };\n }\n return {\n _tag: \"completed\",\n value: JSON.parse(text),\n logs: boundedLogs(),\n hostCalls,\n logBytes,\n resultBytes,\n };\n } catch (cause) {\n if (fatal !== undefined) return fatal;\n return {\n _tag: \"program-failed\",\n reason: cause instanceof Error ? \"threw\" : \"rejected\",\n thrown: safeJson(cause),\n message: safeText(cause),\n logs: boundedLogs(),\n };\n }\n }\n}\n`;\n\nconst BoundedLogs = Schema.Array(Schema.String.check(Schema.isMaxLength(16 * 1024))).check(\n Schema.isMaxLength(4_096),\n);\n\nconst HarnessCompleted = Schema.TaggedStruct(\"completed\", {\n value: Schema.Json,\n logs: BoundedLogs,\n hostCalls: Schema.Natural,\n logBytes: Schema.Natural,\n resultBytes: Schema.Natural,\n});\n\nconst HarnessNotAFunction = Schema.TaggedStruct(\"source-not-a-function\", {\n actual: Schema.String,\n});\n\nconst HarnessProgramFailed = Schema.TaggedStruct(\"program-failed\", {\n reason: Schema.Literals([\"threw\", \"rejected\", \"non-json-result\"]),\n thrown: Schema.Json,\n message: Schema.String,\n logs: BoundedLogs,\n});\n\nconst HarnessLogLimit = Schema.TaggedStruct(\"log-limit\", {\n observed: Schema.Natural,\n logs: BoundedLogs,\n});\n\nconst HarnessArgumentLimit = Schema.TaggedStruct(\"argument-limit\", {\n observed: Schema.Natural,\n logs: BoundedLogs,\n});\n\nconst HarnessResultLimit = Schema.TaggedStruct(\"result-limit\", {\n observed: Schema.Natural,\n logs: BoundedLogs,\n});\n\nconst HarnessHostCallLimit = Schema.TaggedStruct(\"host-call-limit\", {\n logs: BoundedLogs,\n});\n\nconst HarnessProtocol = Schema.TaggedStruct(\"protocol\", {\n message: Schema.String,\n});\n\nconst HarnessOutcome = Schema.Union([\n HarnessCompleted,\n HarnessNotAFunction,\n HarnessProgramFailed,\n HarnessLogLimit,\n HarnessArgumentLimit,\n HarnessResultLimit,\n HarnessHostCallLimit,\n HarnessProtocol,\n]);\n\nconst HarnessPassConfig = Schema.Struct({\n namespaces: Schema.Array(\n Schema.Struct({\n name: Schema.NonEmptyString,\n methods: Schema.Array(Schema.NonEmptyString).check(Schema.isMaxLength(64)),\n }),\n ).check(Schema.isMaxLength(32)),\n limits: Schema.Struct({\n maxLogBytes: Schema.Natural,\n maxResultBytes: Schema.Natural,\n maxHostCalls: Schema.Natural,\n maxHostCallArgumentBytes: Schema.Natural,\n }),\n});\n\nconst encodeHarnessPassConfig = Schema.encodeSync(HarnessPassConfig);\nconst encodeJsonPayload = Schema.encodeSync(Schema.fromJsonString(Schema.Json));\nconst decodeJsonPayload = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Json));\n\nconst decodeHarnessOutcome = (value: unknown) => {\n try {\n return Schema.decodeUnknownOption(HarnessOutcome)(value);\n } catch {\n return Option.none<typeof HarnessOutcome.Type>();\n }\n};\n\nconst decodeHostCall = (value: unknown) => {\n try {\n return Schema.decodeUnknownOption(CodeHostCall)(value);\n } catch {\n return Option.none<CodeHostCall>();\n }\n};\n\nconst decodeHostCallResult = (value: unknown) => {\n try {\n return Schema.decodeUnknownOption(CodeHostCallResult)(value);\n } catch {\n return Option.none<CodeHostCallResult>();\n }\n};\n\n/** Dispose a Cloudflare RPC handle when the runtime supplies its untyped disposal hook. @internal */\nexport const disposeRpcHandle = (handle: unknown): Effect.Effect<void> =>\n Effect.try({\n try: () => {\n if ((typeof handle !== \"object\" && typeof handle !== \"function\") || handle === null) return;\n if (!(Symbol.dispose in handle)) return;\n const dispose = Reflect.get(handle, Symbol.dispose);\n\n if (typeof dispose === \"function\") {\n Reflect.apply(dispose, handle, []);\n }\n },\n catch: (cause) =>\n safeCauseDiagnostic(cause, \"The Cloudflare RPC disposal hook failed without a diagnostic\"),\n }).pipe(\n Effect.catch((diagnostic) =>\n Effect.logWarning(`Cloudflare RPC handle disposal failed: ${diagnostic}`).pipe(\n Effect.ignoreCause,\n ),\n ),\n );\n\n/**\n * Project a host outcome to the plain JSON envelope the harness reads. A\n * `CodeExecutionHost` may return either real `CodeHostCallResult` instances\n * (the substitute and conformance kit) or plain-object equivalents (the Code\n * Mode capability's broker route), so this reads the shared fields rather than\n * `Schema.encodeSync`, which would reject a plain object.\n */\ninterface EncodedHostResultPayload {\n readonly encodedPayload: string;\n readonly resultBytes: number;\n}\n\nconst encodeHostResultPayload = (\n outcome: CodeHostCallResult,\n): EncodedHostResultPayload | undefined => {\n try {\n const payload = outcome._tag === \"CodeHostCallSuccess\" ? outcome.value : outcome.error;\n const encodedPayload = encodeJsonPayload(payload);\n\n return {\n encodedPayload,\n resultBytes: utf8ByteLength(encodedPayload),\n };\n } catch {\n return undefined;\n }\n};\n\nconst utf8ByteLength = (value: string): number => {\n let total = 0;\n\n for (const character of value) {\n const codePoint = character.codePointAt(0) ?? 0;\n\n total += codePoint <= 0x7f ? 1 : codePoint <= 0x7ff ? 2 : codePoint <= 0xffff ? 3 : 4;\n }\n\n return total;\n};\n\ninterface QueuedHostCall {\n readonly call: CodeHostCall;\n readonly resolve: (value: unknown) => void;\n readonly reject: (reason: unknown) => void;\n}\n\ntype HostWork =\n | { readonly _tag: \"call\"; readonly queued: QueuedHostCall }\n | { readonly _tag: \"limit\" };\n\ntype HostDispatchError =\n | CodeExecutionTimeoutError\n | CodeOutputLimitError\n | CodeExecutionProtocolError\n | CodeHostCallLimitError;\n\n/** Reserved global names the harness owns inside the dynamic worker. */\nconst reservedHarnessGlobals = new Set([\"console\"]);\n\nexport interface DynamicWorkerCodeExecutorOptions {\n /** The `worker_loader` binding. */\n readonly loader: WorkerLoader;\n /** Compatibility date for dynamic workers; defaults to `2025-05-01`. */\n readonly compatibilityDate?: string | undefined;\n}\n\nconst makeExecute = (\n options: DynamicWorkerCodeExecutorOptions,\n clock: Clock.Clock,\n): CodeExecutorExecute =>\n Effect.fn(\"DynamicWorkerCodeExecutor.execute\")(function* (request: CodeExecutionRequest) {\n if (request.network._tag !== \"NetworkDisabled\") {\n return yield* CodeExecutorUnsupportedError.make({\n implementation: dynamicWorkerImplementation,\n feature: \"network\",\n message:\n \"The Dynamic Worker executor denies all egress with globalOutbound: null; an allowlist is not supported in the first slice\",\n });\n }\n const sourceBytes = utf8ByteLength(request.source);\n\n if (sourceBytes > request.limits.maxSourceBytes) {\n return yield* CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"oversized\",\n message: `Source is ${sourceBytes} bytes; the request allows ${request.limits.maxSourceBytes}`,\n });\n }\n for (const namespace of request.namespaces) {\n if (reservedHarnessGlobals.has(namespace.name)) {\n return yield* CodeExecutorUnsupportedError.make({\n implementation: dynamicWorkerImplementation,\n feature: \"namespaces\",\n message: `Namespace ${namespace.name} collides with a harness binding`,\n });\n }\n }\n const host = yield* CodeExecutionHost;\n\n // This synchronous clock access is confined to callbacks that must compute a timeout\n // immediately. The Clock service remains the authority, so tests and hosts can replace it.\n const startedAt = clock.monotonicTimeNanosUnsafe();\n const passDeadline = startedAt + Duration.toNanosUnsafe(request.limits.maxWallTime);\n\n const remainingPassWallTime = (): Duration.Duration => {\n const now = clock.monotonicTimeNanosUnsafe();\n\n return Duration.nanos(passDeadline > now ? passDeadline - now : 0n);\n };\n\n let issuedHostCalls = 0;\n let passOpen = true;\n const queuedHostCalls: Array<QueuedHostCall> = [];\n let passFailure: HostDispatchError | undefined;\n\n const failPass = (error: HostDispatchError): void => {\n if (passFailure === undefined) passFailure = error;\n };\n\n const rejectQueuedHostCalls = (reason: Error): void => {\n for (const queued of queuedHostCalls.splice(0)) {\n queued.reject(reason);\n }\n };\n\n const queue = yield* Queue.unbounded<HostWork>();\n\n const deliverHostOutcome = (\n queued: QueuedHostCall,\n outcome: CodeHostCallResult,\n ): Effect.Effect<void, CodeExecutionProtocolError | CodeOutputLimitError> =>\n Effect.gen(function* () {\n const decoded = decodeHostCallResult(outcome);\n\n if (Option.isNone(decoded)) {\n const error = CodeExecutionProtocolError.make({\n implementation: dynamicWorkerImplementation,\n message: \"The execution host returned a value outside the CodeHostCallResult schema\",\n });\n\n failPass(error);\n\n return yield* error;\n }\n const encoded = encodeHostResultPayload(decoded.value);\n\n if (encoded === undefined || encoded.resultBytes > request.limits.maxHostCallResultBytes) {\n const error = CodeOutputLimitError.make({\n implementation: dynamicWorkerImplementation,\n surface: \"host-call-result\",\n limit: request.limits.maxHostCallResultBytes,\n observed: encoded?.resultBytes ?? 0,\n logs: [],\n });\n\n failPass(error);\n\n return yield* error;\n }\n const normalizedPayload = decodeJsonPayload(encoded.encodedPayload);\n\n if (Option.isNone(normalizedPayload)) {\n const error = CodeExecutionProtocolError.make({\n implementation: dynamicWorkerImplementation,\n message: \"The execution host returned a result that could not cross the JSON boundary\",\n });\n\n failPass(error);\n\n return yield* error;\n }\n queued.resolve(\n decoded.value._tag === \"CodeHostCallSuccess\"\n ? { _tag: \"CodeHostCallSuccess\", value: normalizedPayload.value }\n : { _tag: \"CodeHostCallFailure\", error: normalizedPayload.value },\n );\n });\n\n // Workers RPC into the loader isolate cannot settle on the fiber blocked\n // in `entrypoint.run()`. A Scope-owned sibling fiber keeps that\n // independence while inheriting the pass Context and dying with the Scope.\n const serveHostCalls = Effect.gen(function* () {\n while (true) {\n const work = yield* Queue.take(queue);\n\n if (work._tag === \"limit\") {\n const error = CodeHostCallLimitError.make({\n implementation: dynamicWorkerImplementation,\n limit: request.limits.maxHostCalls,\n logs: [],\n });\n\n failPass(error);\n\n return yield* error;\n }\n const queued = work.queued;\n\n yield* host.call(queued.call).pipe(\n Effect.timeoutOrElse({\n duration: remainingPassWallTime(),\n orElse: () => {\n const error = CodeExecutionTimeoutError.make({\n implementation: dynamicWorkerImplementation,\n kind: \"wall-clock\",\n maxWallTime: request.limits.maxWallTime,\n logs: [],\n });\n\n failPass(error);\n\n return error;\n },\n }),\n Effect.flatMap((outcome) => deliverHostOutcome(queued, outcome)),\n Effect.tapError(() =>\n Effect.sync(() => queued.reject(new Error(\"Code Mode host call failed\"))),\n ),\n Effect.onInterrupt(() =>\n Effect.sync(() => queued.reject(new Error(\"Code Mode pass is closing\"))),\n ),\n );\n }\n });\n\n const server = yield* serveHostCalls.pipe(Effect.forkScoped);\n\n const dispatch = (hostCall: unknown): Promise<unknown> => {\n if (!passOpen) {\n return Promise.reject(new Error(\"Code Mode pass is closing\"));\n }\n issuedHostCalls += 1;\n if (issuedHostCalls > request.limits.maxHostCalls) {\n const error = CodeHostCallLimitError.make({\n implementation: dynamicWorkerImplementation,\n limit: request.limits.maxHostCalls,\n logs: [],\n });\n\n failPass(error);\n Queue.offerUnsafe(queue, { _tag: \"limit\" });\n\n return Promise.reject(new Error(\"host-call limit exceeded\"));\n }\n const decoded = decodeHostCall(hostCall);\n\n if (Option.isNone(decoded)) {\n return Promise.reject(new TypeError(\"host calls must match the CodeHostCall schema\"));\n }\n\n return new Promise((resolve, reject) => {\n const queued = { call: decoded.value, resolve, reject };\n\n queuedHostCalls.push(queued);\n Queue.offerUnsafe(queue, { _tag: \"call\", queued });\n });\n };\n\n const closeAdmission = Effect.sync(() => {\n passOpen = false;\n rejectQueuedHostCalls(new Error(\"Code Mode pass is closing\"));\n });\n\n yield* Effect.addFinalizer(() => closeAdmission.pipe(Effect.andThen(Fiber.interrupt(server))));\n\n // No `allowExperimental`: the runtime only accepts it when the CALLING\n // worker carries the `experimental` compatibility flag, which deployed\n // consumers cannot set — the option would reject every pass in\n // production. The harness needs no experimental runtime features.\n const workerCode: WorkerLoaderWorkerCode = {\n compatibilityDate: options.compatibilityDate ?? \"2025-05-01\",\n mainModule: \"harness.js\",\n modules: {\n \"harness.js\": HARNESS_MODULE,\n \"program.js\": `export default (\\n${request.source}\\n);`,\n },\n env: {\n CODE_MODE_PASS: encodeHarnessPassConfig({\n namespaces: request.namespaces.map((namespace) => ({\n name: namespace.name,\n methods: namespace.methods,\n })),\n limits: {\n maxLogBytes: request.limits.maxLogBytes,\n maxResultBytes: request.limits.maxResultBytes,\n maxHostCalls: request.limits.maxHostCalls,\n maxHostCallArgumentBytes: request.limits.maxHostCallArgumentBytes,\n },\n }),\n },\n globalOutbound: null,\n ...(request.limits.cpuMillis === undefined\n ? {}\n : {\n limits: {\n cpuMs: request.limits.cpuMillis,\n subRequests: request.limits.maxHostCalls + 8,\n },\n }),\n };\n\n const worker = yield* Effect.acquireRelease(\n Effect.try({\n try: () => options.loader.load(workerCode),\n catch: (cause) => {\n const text = safeCauseMessage(cause, \"The Worker Loader failed without a diagnostic\");\n\n // Blame the program's source ONLY on a genuine compile diagnostic;\n // any other load rejection is an infrastructure start failure, not\n // the model's fault (see classifyWorkerFailure for the same split).\n if (/syntaxerror|failed to (compile|parse)/i.test(text)) {\n return CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"invalid\",\n message: text.slice(0, 8_000),\n });\n }\n\n return CodeExecutorStartError.make({\n implementation: dynamicWorkerImplementation,\n message: `The Worker Loader rejected the pass: ${text}`.slice(0, 8_000),\n cause,\n });\n },\n }),\n disposeRpcHandle,\n );\n\n const entrypoint = yield* Effect.acquireRelease(\n Effect.try({\n try: () => worker.getEntrypoint<CodeModeHarnessEntrypoint>(),\n catch: (cause) => classifyWorkerFailure(cause, request.limits.maxWallTime),\n }),\n disposeRpcHandle,\n );\n\n const rpc = Effect.tryPromise({\n try: () => entrypoint.run(new CodeModePassHostTarget(dispatch)),\n catch: (cause) => classifyWorkerFailure(cause, request.limits.maxWallTime),\n });\n\n const exit = yield* Effect.raceFirst(\n rpc.pipe(\n Effect.timeoutOrElse({\n duration: remainingPassWallTime(),\n orElse: () =>\n CodeExecutionTimeoutError.make({\n implementation: dynamicWorkerImplementation,\n kind: \"wall-clock\",\n maxWallTime: request.limits.maxWallTime,\n logs: [],\n }),\n }),\n ),\n Fiber.join(server),\n ).pipe(Effect.exit);\n\n yield* closeAdmission;\n yield* Fiber.interrupt(server);\n if (passFailure !== undefined) {\n return yield* passFailure;\n }\n if (Exit.isFailure(exit)) {\n return yield* Effect.failCause(exit.cause);\n }\n const raw = exit.value;\n const finishedAt = clock.monotonicTimeNanosUnsafe();\n\n const outcome = decodeHarnessOutcome(raw);\n\n if (Option.isNone(outcome)) {\n return yield* CodeExecutionProtocolError.make({\n implementation: dynamicWorkerImplementation,\n message: \"The dynamic worker returned a value outside the harness envelope schema\",\n });\n }\n switch (outcome.value._tag) {\n case \"completed\": {\n return CodeExecutionResult.make({\n implementation: dynamicWorkerImplementation,\n value: outcome.value.value,\n logs: outcome.value.logs,\n resourceUse: CodeExecutionResourceUse.make({\n wallTime: Duration.nanos(finishedAt > startedAt ? finishedAt - startedAt : 0n),\n hostCalls: outcome.value.hostCalls,\n logBytes: outcome.value.logBytes,\n resultBytes: outcome.value.resultBytes,\n }),\n });\n }\n case \"source-not-a-function\": {\n return yield* CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"not-a-function\",\n message: `The source expression evaluated to ${outcome.value.actual}; it must evaluate to one async function`,\n });\n }\n case \"program-failed\": {\n return yield* CodeProgramFailedError.make({\n implementation: dynamicWorkerImplementation,\n reason: outcome.value.reason,\n thrown: outcome.value.thrown,\n message: outcome.value.message.slice(0, 8_000),\n logs: outcome.value.logs,\n });\n }\n case \"log-limit\": {\n return yield* CodeOutputLimitError.make({\n implementation: dynamicWorkerImplementation,\n surface: \"logs\",\n limit: request.limits.maxLogBytes,\n observed: outcome.value.observed,\n logs: outcome.value.logs,\n });\n }\n case \"argument-limit\": {\n return yield* CodeOutputLimitError.make({\n implementation: dynamicWorkerImplementation,\n surface: \"host-call-argument\",\n limit: request.limits.maxHostCallArgumentBytes,\n observed: outcome.value.observed,\n logs: outcome.value.logs,\n });\n }\n case \"result-limit\": {\n return yield* CodeOutputLimitError.make({\n implementation: dynamicWorkerImplementation,\n surface: \"result\",\n limit: request.limits.maxResultBytes,\n observed: outcome.value.observed,\n logs: outcome.value.logs,\n });\n }\n case \"host-call-limit\": {\n return yield* CodeHostCallLimitError.make({\n implementation: dynamicWorkerImplementation,\n limit: request.limits.maxHostCalls,\n logs: outcome.value.logs,\n });\n }\n case \"protocol\": {\n return yield* CodeExecutionProtocolError.make({\n implementation: dynamicWorkerImplementation,\n message: outcome.value.message.slice(0, 8_000),\n });\n }\n }\n });\n\n/**\n * Expected worker-level failures map into the typed union with bounded\n * diagnostics; anything unrecognized stays a start/termination error rather\n * than a fabricated program result.\n */\nconst classifyWorkerFailure = (\n cause: unknown,\n maxWallTime: Duration.Duration,\n):\n | CodeExecutionTimeoutError\n | CodeExecutorTerminatedError\n | CodeExecutorStartError\n | CodeSourceError => {\n const text = safeCauseDiagnostic(cause, \"[unserializable worker failure]\");\n\n // `WorkerLoader.load()` is lazy, so a module-compile error in the generated\n // program surfaces here at first use. Blame the program's source ONLY on a\n // genuine compile diagnostic (a `SyntaxError` or an explicit compile\n // failure) — the fixed harness is valid, so the fault is in program.js. A\n // bare \"failed to start Worker\" without a compile diagnostic is an\n // infrastructure start failure, not the model's fault, so it must NOT be\n // misclassified as a source error.\n if (/syntaxerror|failed to (compile|parse)/i.test(text)) {\n return CodeSourceError.make({\n implementation: dynamicWorkerImplementation,\n reason: \"invalid\",\n message: text.slice(0, 8_000),\n });\n }\n if (/cpu/i.test(text)) {\n return CodeExecutionTimeoutError.make({\n implementation: dynamicWorkerImplementation,\n kind: \"cpu\",\n maxWallTime,\n logs: [],\n });\n }\n if (/failed to start worker/i.test(text)) {\n return CodeExecutorStartError.make({\n implementation: dynamicWorkerImplementation,\n message: text.slice(0, 8_000),\n cause,\n });\n }\n\n return CodeExecutorTerminatedError.make({\n implementation: dynamicWorkerImplementation,\n message: text.slice(0, 8_000),\n });\n};\n\n/** Layer building the Dynamic Worker `CodeExecutor` from resolved bindings. */\nexport const dynamicWorkerCodeExecutorLayer = (\n options: DynamicWorkerCodeExecutorOptions,\n): Layer.Layer<CodeExecutor> =>\n Layer.effect(\n CodeExecutor,\n Effect.gen(function* () {\n const clock = yield* Clock.Clock;\n\n return CodeExecutor.of({ execute: makeExecute(options, clock) });\n }),\n );\n\n/** Assemble Code Mode handlers with the isolated Dynamic Worker executor. */\nexport const CloudflareCodeMode = {\n /**\n * Provide the selected tool handlers at construction, where Code Mode captures them.\n * Their errors and remaining dependencies stay visible. The definition still owns the\n * allowlist and limits; the runtime supplies the live Tool broker for each scoped pass.\n */\n layer: <A, E, R, Handlers, HandlerError, HandlerRequirements>(\n definition: { readonly handlers: Layer.Layer<A, E, R> },\n options: DynamicWorkerCodeExecutorOptions & {\n readonly handlers: Layer.Layer<Handlers, HandlerError, HandlerRequirements>;\n },\n ) =>\n definition.handlers.pipe(\n Layer.provide(options.handlers),\n Layer.provide(dynamicWorkerCodeExecutorLayer(options)),\n ),\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAa,8BAA8B,sBAAsB,KAAK;CACpE,WAAW;CACX,UAAU;AACZ,CAAC;;;;;;;;AAiBD,IAAM,yBAAN,cAAqC,UAAsC;CACzE;CAEA,YAAY,UAAmD;EAC7D,MAAM;EACN,KAAKA,YAAY;CACnB;CAEA,KAAK,UAAqC;EACxC,OAAO,KAAKA,UAAU,QAAQ;CAChC;AACF;;;;;;;;AASA,MAAM,iBAAiB,OAAO,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgJjC,MAAM,cAAc,OAAO,MAAM,OAAO,OAAO,MAAM,OAAO,YAAY,KAAS,CAAC,CAAC,CAAC,CAAC,MACnF,OAAO,YAAY,IAAK,CAC1B;AAEA,MAAM,mBAAmB,OAAO,aAAa,aAAa;CACxD,OAAO,OAAO;CACd,MAAM;CACN,WAAW,OAAO;CAClB,UAAU,OAAO;CACjB,aAAa,OAAO;AACtB,CAAC;AAED,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ACtC,gBAAgB;EAChB,SAAS,KAAK,MAAM,GAAG,GAAK;CAC9B,CAAC;AACH;;AAGA,MAAa,kCACX,YAEA,MAAM,OACJ,cACA,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,OAAO,MAAM;CAE3B,OAAO,aAAa,GAAG,EAAE,SAAS,YAAY,SAAS,KAAK,EAAE,CAAC;AACjE,CAAC,CACH;;AAGF,MAAa,qBAAqB;;;;;;AAMhC,QACE,YACA,YAIA,WAAW,SAAS,KAClB,MAAM,QAAQ,QAAQ,QAAQ,GAC9B,MAAM,QAAQ,+BAA+B,OAAO,CAAC,CACvD,EACJ"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
|
|
2
2
|
import { CloudflareThreadClient } from "./CloudflareThreadClient.mjs";
|
|
3
|
-
import { n as cloudflareScheduledInputAdmissionLayer, t as cloudflarePreparedInputAdmissionLayer } from "./prepared-admission-
|
|
3
|
+
import { n as cloudflareScheduledInputAdmissionLayer, t as cloudflarePreparedInputAdmissionLayer } from "./prepared-admission-9rvlHI0y.mjs";
|
|
4
4
|
import "@effect-agent/thread/DurableAgentRuntime";
|
|
5
|
+
import { AdmissionFence } from "@effect-agent/thread/SubmissionLedger";
|
|
5
6
|
import { Clock, Context, DateTime, Effect, Layer, Schema } from "effect";
|
|
6
7
|
import { AgentId } from "@effect-agent/core/Identifiers";
|
|
7
8
|
import { DefinitionDigests, PersistedJson } from "@effect-agent/thread/Records";
|
|
@@ -40,7 +41,9 @@ const ScheduleMutationRequestFields = {
|
|
|
40
41
|
timing: ScheduleTimingRequest,
|
|
41
42
|
destination: ScheduleDestination,
|
|
42
43
|
deliveryPrincipal: ScheduleScope.fields.principal,
|
|
43
|
-
definitions: DefinitionDigests
|
|
44
|
+
definitions: DefinitionDigests,
|
|
45
|
+
admissionGroup: Schema.optionalKey(Schema.NonEmptyString.check(Schema.isMaxLength(256))),
|
|
46
|
+
admissionFence: Schema.optionalKey(AdmissionFence)
|
|
44
47
|
};
|
|
45
48
|
const ScheduleCreateRequest = Schema.TaggedStruct("Create", ScheduleMutationRequestFields);
|
|
46
49
|
const ScheduleUpdateRequest = Schema.TaggedStruct("Update", {
|
|
@@ -69,7 +72,15 @@ const ScheduleControlRequest = Schema.TaggedStruct("Control", {
|
|
|
69
72
|
scheduleId: ScheduleId,
|
|
70
73
|
expectedRevision: Schema.Int.check(Schema.isGreaterThan(0))
|
|
71
74
|
});
|
|
75
|
+
const ScheduleRecoverRequest = Schema.TaggedStruct("Recover", {
|
|
76
|
+
schemaVersion: Schema.Literal(1),
|
|
77
|
+
scope: ScheduleScope,
|
|
78
|
+
scheduleId: ScheduleId,
|
|
79
|
+
expectedRevision: Schema.Int.check(Schema.isGreaterThan(0)),
|
|
80
|
+
expectedGeneration: Schema.Natural
|
|
81
|
+
});
|
|
72
82
|
const ScheduleOwnerRequest = Schema.Union([
|
|
83
|
+
ScheduleRecoverRequest,
|
|
73
84
|
ScheduleCreateRequest,
|
|
74
85
|
ScheduleUpdateRequest,
|
|
75
86
|
ScheduleGetRequest,
|
|
@@ -209,6 +220,20 @@ var CloudflareSchedulingClient = class {
|
|
|
209
220
|
list,
|
|
210
221
|
pause: (scope, id, revision) => control("pause", scope, id, revision),
|
|
211
222
|
resume: (scope, id, revision) => control("resume", scope, id, revision),
|
|
223
|
+
recover: (scope, scheduleId, expectedRevision, expectedGeneration) => Effect.gen(function* () {
|
|
224
|
+
const response = yield* call(scope.owner, {
|
|
225
|
+
_tag: "Recover",
|
|
226
|
+
schemaVersion: 1,
|
|
227
|
+
scope,
|
|
228
|
+
scheduleId,
|
|
229
|
+
expectedRevision,
|
|
230
|
+
expectedGeneration
|
|
231
|
+
});
|
|
232
|
+
return response._tag === "Snapshot" ? response.value : yield* ScheduleStorageError.make({
|
|
233
|
+
operation: "Schedule Owner protocol",
|
|
234
|
+
reason: "corrupt"
|
|
235
|
+
});
|
|
236
|
+
}),
|
|
212
237
|
cancel: (scope, id, revision) => control("cancel", scope, id, revision)
|
|
213
238
|
});
|
|
214
239
|
}));
|
|
@@ -271,7 +296,9 @@ const handleScheduleRequest = Effect.fn("ScheduleOwner.handleRequest")(function*
|
|
|
271
296
|
timing: request.timing,
|
|
272
297
|
destination: request.destination,
|
|
273
298
|
deliveryPrincipal: request.deliveryPrincipal,
|
|
274
|
-
definitions: request.definitions
|
|
299
|
+
definitions: request.definitions,
|
|
300
|
+
...request.admissionGroup === void 0 ? {} : { admissionGroup: request.admissionGroup },
|
|
301
|
+
...request.admissionFence === void 0 ? {} : { admissionFence: request.admissionFence }
|
|
275
302
|
})
|
|
276
303
|
};
|
|
277
304
|
case "Update": return {
|
|
@@ -283,6 +310,8 @@ const handleScheduleRequest = Effect.fn("ScheduleOwner.handleRequest")(function*
|
|
|
283
310
|
destination: request.destination,
|
|
284
311
|
deliveryPrincipal: request.deliveryPrincipal,
|
|
285
312
|
definitions: request.definitions,
|
|
313
|
+
...request.admissionGroup === void 0 ? {} : { admissionGroup: request.admissionGroup },
|
|
314
|
+
...request.admissionFence === void 0 ? {} : { admissionFence: request.admissionFence },
|
|
286
315
|
expectedRevision: request.expectedRevision
|
|
287
316
|
})
|
|
288
317
|
};
|
|
@@ -297,6 +326,10 @@ const handleScheduleRequest = Effect.fn("ScheduleOwner.handleRequest")(function*
|
|
|
297
326
|
...request.limit === void 0 ? {} : { limit: request.limit }
|
|
298
327
|
})
|
|
299
328
|
};
|
|
329
|
+
case "Recover": return {
|
|
330
|
+
_tag: "Snapshot",
|
|
331
|
+
value: yield* scheduling.recover(request.scope, request.scheduleId, request.expectedRevision, request.expectedGeneration)
|
|
332
|
+
};
|
|
300
333
|
case "Control": return {
|
|
301
334
|
_tag: "Snapshot",
|
|
302
335
|
value: request.operation === "pause" ? yield* scheduling.pause(request.scope, request.scheduleId, request.expectedRevision) : request.operation === "resume" ? yield* scheduling.resume(request.scope, request.scheduleId, request.expectedRevision) : yield* scheduling.cancel(request.scope, request.scheduleId, request.expectedRevision)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CloudflareScheduling.mjs","names":["ScheduleScopeSchema","ScheduleSnapshotPageSchema","EffectCfDurableObjectState","EffectCfDurableObject"],"sources":["../src/CloudflareScheduling.ts"],"sourcesContent":["import { AgentId } from \"@effect-agent/core/Identifiers\";\nimport {\n DoScheduleAlarmControl,\n DoScheduleTransaction,\n scheduleStoreLayer,\n} from \"@effect-agent/storage-cloudflare/DoScheduleStore\";\nimport { type DurableSubmitAgent } from \"@effect-agent/thread/DurableAgentRuntime\";\nimport { DefinitionDigests, PersistedJson } from \"@effect-agent/thread/Records\";\nimport {\n ScheduleAuthorizationError,\n type ScheduleAuthorizer,\n ScheduleCapacityError,\n ScheduleConflict,\n ScheduleDestination,\n ScheduleFailpointError,\n ScheduleId,\n type SchedulingLimits,\n ScheduleNotFound,\n ScheduleOwner,\n type ScheduleScope,\n ScheduleScope as ScheduleScopeSchema,\n ScheduleSnapshot,\n ScheduleSnapshotPage as ScheduleSnapshotPageSchema,\n ScheduleStorageError,\n ScheduleTimingRequest,\n ScheduleValidationError,\n defaultSchedulingLimits,\n} from \"@effect-agent/thread/Schedule\";\nimport { scheduleOwnerKey } from \"@effect-agent/thread/ScheduleTransition\";\nimport {\n Scheduling,\n ScheduleDriver,\n type ScheduleManagementFailure,\n ScheduleWakeNoop,\n} from \"@effect-agent/thread/Scheduling\";\nimport { BrowserCrypto } from \"@effect/platform-browser\";\nimport { SqliteClient } from \"@effect/sql-sqlite-do\";\nimport { Clock, Context, DateTime, Effect, Layer, Schema } from \"effect\";\nimport {\n DurableObject as EffectCfDurableObject,\n DurableObjectAlarm,\n DurableObjectState as EffectCfDurableObjectState,\n type WorkerEnvironment,\n} from \"effect-cf\";\n\nimport type { ThreadObjectNamespace } from \"./CloudflareBindings.ts\";\nimport { CloudflareThreadClient } from \"./CloudflareThreadClient.ts\";\nimport {\n cloudflarePreparedInputAdmissionLayer,\n cloudflareScheduledInputAdmissionLayer,\n} from \"./internal/prepared-admission.ts\";\n\nconst SCHEDULE_ALARM_TAG = \"effect-agent/ScheduleOwnerWake\";\nconst SCHEDULE_ALARM_ID = \"driver\";\n\nconst ScheduleAlarmPayload = Schema.Struct({\n schemaVersion: Schema.Literal(1),\n generation: Schema.Int.check(Schema.isGreaterThan(0)),\n});\n\nexport class ScheduleAlarmProtocolError extends Schema.TaggedError<ScheduleAlarmProtocolError>()(\n \"ScheduleAlarmProtocolError\",\n { message: Schema.String },\n) {}\n\nconst boundedProtocolMessage = (message: string): string =>\n message.length <= 4_096 ? message : `${message.slice(0, 4_093)}...`;\n\nexport class ScheduleOwnerProtocolError extends Schema.TaggedError<ScheduleOwnerProtocolError>()(\n \"ScheduleOwnerProtocolError\",\n { message: Schema.String.check(Schema.isMaxLength(4_096)) },\n) {}\n\nconst ScheduleMutationRequestFields = {\n schemaVersion: Schema.Literal(1),\n agentId: AgentId,\n input: PersistedJson,\n scope: ScheduleScopeSchema,\n scheduleId: ScheduleId,\n timing: ScheduleTimingRequest,\n destination: ScheduleDestination,\n deliveryPrincipal: ScheduleScopeSchema.fields.principal,\n definitions: DefinitionDigests,\n};\n\nconst ScheduleCreateRequest = Schema.TaggedStruct(\"Create\", ScheduleMutationRequestFields);\n\nconst ScheduleUpdateRequest = Schema.TaggedStruct(\"Update\", {\n ...ScheduleMutationRequestFields,\n expectedRevision: Schema.Int.check(Schema.isGreaterThan(0)),\n});\n\nconst ScheduleGetRequest = Schema.TaggedStruct(\"Get\", {\n schemaVersion: Schema.Literal(1),\n scope: ScheduleScopeSchema,\n scheduleId: ScheduleId,\n});\n\nconst ScheduleListRequest = Schema.TaggedStruct(\"List\", {\n schemaVersion: Schema.Literal(1),\n scope: ScheduleScopeSchema,\n after: Schema.optionalKey(ScheduleId),\n limit: Schema.optionalKey(\n Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(100)),\n ),\n});\n\nconst ScheduleControlRequest = Schema.TaggedStruct(\"Control\", {\n schemaVersion: Schema.Literal(1),\n operation: Schema.Literals([\"pause\", \"resume\", \"cancel\"]),\n scope: ScheduleScopeSchema,\n scheduleId: ScheduleId,\n expectedRevision: Schema.Int.check(Schema.isGreaterThan(0)),\n});\n\nconst ScheduleOwnerRequest = Schema.Union([\n ScheduleCreateRequest,\n ScheduleUpdateRequest,\n ScheduleGetRequest,\n ScheduleListRequest,\n ScheduleControlRequest,\n]);\n\ntype ScheduleOwnerRequest = typeof ScheduleOwnerRequest.Type;\n\nconst ScheduleOwnerFailure = Schema.Union([\n ScheduleValidationError,\n ScheduleAuthorizationError,\n ScheduleConflict,\n ScheduleNotFound,\n ScheduleCapacityError,\n ScheduleStorageError,\n ScheduleFailpointError,\n ScheduleOwnerProtocolError,\n]);\n\ntype ScheduleOwnerFailure = typeof ScheduleOwnerFailure.Type;\n\nconst ScheduleOwnerResponse = Schema.Union([\n Schema.TaggedStruct(\"Snapshot\", { value: ScheduleSnapshot }),\n Schema.TaggedStruct(\"Page\", { value: ScheduleSnapshotPageSchema }),\n Schema.TaggedStruct(\"Failed\", { failure: ScheduleOwnerFailure }),\n]);\n\ntype ScheduleOwnerResponse = typeof ScheduleOwnerResponse.Type;\n\nconst decodeScheduleOwnerRequest = Schema.decodeUnknownEffect(ScheduleOwnerRequest);\nconst encodeScheduleOwnerRequest = Schema.encodeEffect(ScheduleOwnerRequest);\nconst decodeScheduleOwnerResponse = Schema.decodeUnknownEffect(ScheduleOwnerResponse);\nconst encodeScheduleOwnerResponse = Schema.encodeEffect(ScheduleOwnerResponse);\n\nconst scheduleProtocolFailure = (message: string): ScheduleOwnerResponse => ({\n _tag: \"Failed\",\n failure: ScheduleOwnerProtocolError.make({ message: boundedProtocolMessage(message) }),\n});\n\nexport interface ScheduleOwnerObjectRpc extends Rpc.DurableObjectBranded {\n schedule(encoded: unknown): Promise<unknown>;\n}\n\nexport class ScheduleOwnerNamespace extends Context.Service<\n ScheduleOwnerNamespace,\n { readonly namespace: DurableObjectNamespace<ScheduleOwnerObjectRpc> }\n>()(\"@effect-agent/platform-cloudflare/ScheduleOwnerNamespace\") {}\n\nconst passthroughAgent = (agentId: AgentId): DurableSubmitAgent<typeof PersistedJson> => ({\n definition: { id: agentId, input: PersistedJson },\n});\n\nconst requestOwner = (request: ScheduleOwnerRequest): ScheduleOwner => request.scope.owner;\n\n/** Provides the same authorized management service as NodeScheduling.layer. */\nexport class CloudflareSchedulingClient {\n static readonly layer: Layer.Layer<Scheduling, never, ScheduleOwnerNamespace> = Layer.effect(\n Scheduling,\n Effect.gen(function* () {\n const { namespace } = yield* ScheduleOwnerNamespace;\n\n const call = Effect.fn(\"CloudflareSchedulingClient.call\")(function* (\n owner: ScheduleOwner,\n request: ScheduleOwnerRequest,\n ): Effect.fn.Return<ScheduleOwnerResponse, ScheduleManagementFailure> {\n const encoded = yield* encodeScheduleOwnerRequest(request).pipe(\n Effect.mapError(() =>\n ScheduleStorageError.make({ operation: \"Schedule Owner protocol\", reason: \"corrupt\" }),\n ),\n );\n\n const raw = yield* Effect.tryPromise({\n try: () => namespace.get(namespace.idFromName(scheduleOwnerKey(owner))).schedule(encoded),\n catch: () =>\n ScheduleStorageError.make({\n operation: \"call Schedule Owner\",\n reason: \"unavailable\",\n }),\n });\n\n const response = yield* decodeScheduleOwnerResponse(raw).pipe(\n Effect.mapError(() =>\n ScheduleStorageError.make({ operation: \"Schedule Owner protocol\", reason: \"corrupt\" }),\n ),\n );\n\n if (response._tag !== \"Failed\") return response;\n\n return yield* response.failure._tag === \"ScheduleOwnerProtocolError\"\n ? ScheduleStorageError.make({ operation: \"Schedule Owner protocol\", reason: \"corrupt\" })\n : response.failure;\n });\n\n const encodeInput = Effect.fn(\"CloudflareSchedulingClient.encodeInput\")(function* <\n InputSchema extends Schema.Top,\n >(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n ): Effect.fn.Return<PersistedJson, ScheduleValidationError, InputSchema[\"EncodingServices\"]> {\n const encoded = yield* Schema.encodeEffect(agent.definition.input)(input).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({\n message: \"Unable to encode Agent input\",\n }),\n ),\n );\n\n return yield* Schema.decodeUnknownEffect(PersistedJson)(encoded).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({\n message: \"Agent input does not satisfy the canonical persistence bounds\",\n }),\n ),\n );\n });\n\n const create: Scheduling[\"Service\"][\"create\"] = (agent, input, options) =>\n Effect.gen(function* () {\n const payload = yield* encodeInput(agent, input);\n\n const response = yield* call(options.scope.owner, {\n _tag: \"Create\",\n schemaVersion: 1,\n agentId: agent.definition.id,\n input: payload,\n ...options,\n });\n\n return response._tag === \"Snapshot\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n const update: Scheduling[\"Service\"][\"update\"] = (agent, input, options) =>\n Effect.gen(function* () {\n const payload = yield* encodeInput(agent, input);\n\n const response = yield* call(options.scope.owner, {\n _tag: \"Update\",\n schemaVersion: 1,\n agentId: agent.definition.id,\n input: payload,\n ...options,\n });\n\n return response._tag === \"Snapshot\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n const get: Scheduling[\"Service\"][\"get\"] = (scope, scheduleId) =>\n Effect.gen(function* () {\n const response = yield* call(scope.owner, {\n _tag: \"Get\",\n schemaVersion: 1,\n scope,\n scheduleId,\n });\n\n return response._tag === \"Snapshot\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n const list: Scheduling[\"Service\"][\"list\"] = (scope, options = {}) =>\n Effect.gen(function* () {\n const response = yield* call(scope.owner, {\n _tag: \"List\",\n schemaVersion: 1,\n scope,\n ...(options.after === undefined ? {} : { after: options.after }),\n ...(options.limit === undefined ? {} : { limit: options.limit }),\n });\n\n return response._tag === \"Page\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n const control = (\n operation: \"pause\" | \"resume\" | \"cancel\",\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n ) =>\n Effect.gen(function* () {\n const response = yield* call(scope.owner, {\n _tag: \"Control\",\n schemaVersion: 1,\n operation,\n scope,\n scheduleId,\n expectedRevision,\n });\n\n return response._tag === \"Snapshot\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n return Scheduling.of({\n create,\n update,\n get,\n list,\n pause: (scope, id, revision) => control(\"pause\", scope, id, revision),\n resume: (scope, id, revision) => control(\"resume\", scope, id, revision),\n cancel: (scope, id, revision) => control(\"cancel\", scope, id, revision),\n });\n }),\n );\n}\n\nexport class ScheduleOwnerIdentity extends Context.Service<\n ScheduleOwnerIdentity,\n { readonly owner: ScheduleOwner }\n>()(\"@effect-agent/platform-cloudflare/ScheduleOwnerIdentity\") {}\n\nconst decodeOwnerName = Effect.fn(\"decodeScheduleOwnerName\")(function* (\n name: string | null | undefined,\n): Effect.fn.Return<ScheduleOwner, ScheduleOwnerProtocolError> {\n if (name === null || name === undefined) {\n return yield* ScheduleOwnerProtocolError.make({\n message: \"Schedule Owner objects require an idFromName identity\",\n });\n }\n\n const tuple = yield* Schema.decodeUnknownEffect(\n Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.String])),\n )(name).pipe(\n Effect.mapError(() =>\n ScheduleOwnerProtocolError.make({ message: \"Schedule Owner object name is malformed\" }),\n ),\n );\n\n return yield* Schema.decodeUnknownEffect(ScheduleOwner)({\n tenantId: tuple[0],\n ownerId: tuple[1],\n }).pipe(\n Effect.mapError(() =>\n ScheduleOwnerProtocolError.make({ message: \"Schedule Owner object identity is invalid\" }),\n ),\n );\n});\n\nconst alarmStorageError = (operation: string) => (error: { readonly _tag: string }) =>\n ScheduleStorageError.make({\n operation,\n reason: error._tag === \"StorageOperationError\" ? \"unavailable\" : \"corrupt\",\n });\n\nconst transactionLayer: Layer.Layer<\n DoScheduleTransaction,\n never,\n DurableObjectAlarm.DurableObjectAlarm\n> = Layer.effect(\n DoScheduleTransaction,\n Effect.gen(function* () {\n const alarms = yield* DurableObjectAlarm.DurableObjectAlarm;\n\n return DoScheduleTransaction.of({\n run: (body) =>\n Effect.gen(function* () {\n const nowMillis = yield* Clock.currentTimeMillis;\n\n return yield* alarms\n .transaction((transaction) =>\n body((replacement) =>\n replacement.deadlineAtMillis === null\n ? transaction\n .cancelAlarm({ id: SCHEDULE_ALARM_ID, tag: SCHEDULE_ALARM_TAG })\n .pipe(Effect.mapError(alarmStorageError(\"cancel Schedule Owner alarm\")))\n : Effect.fromOption(\n DateTime.make(Math.max(replacement.deadlineAtMillis, nowMillis + 1)),\n ).pipe(\n Effect.mapError(() =>\n ScheduleStorageError.make({\n operation: \"validate Schedule Owner alarm deadline\",\n reason: \"corrupt\",\n }),\n ),\n Effect.flatMap((runAt) =>\n transaction\n .scheduleAlarm({\n id: SCHEDULE_ALARM_ID,\n tag: SCHEDULE_ALARM_TAG,\n runAt,\n payload: {\n schemaVersion: 1,\n generation: replacement.generation,\n },\n })\n .pipe(\n Effect.mapError(alarmStorageError(\"schedule Schedule Owner alarm\")),\n ),\n ),\n ),\n ),\n )\n .pipe(\n Effect.catchTag(\"StorageOperationError\", () =>\n ScheduleStorageError.make({\n operation: \"commit Schedule Owner transaction\",\n reason: \"unavailable\",\n }),\n ),\n );\n }),\n });\n }),\n);\n\ntype ScheduleRuntimeServices =\n | Scheduling\n | ScheduleDriver\n | DoScheduleAlarmControl\n | ScheduleOwnerIdentity\n | DurableObjectAlarm.DurableObjectAlarm;\n\nconst ensureOwner = (\n expected: ScheduleOwner,\n request: ScheduleOwnerRequest,\n): Effect.Effect<void, ScheduleOwnerProtocolError> => {\n const observed = requestOwner(request);\n\n return observed.tenantId === expected.tenantId && observed.ownerId === expected.ownerId\n ? Effect.void\n : Effect.fail(\n ScheduleOwnerProtocolError.make({\n message: \"The request owner does not match the addressed Schedule Owner object\",\n }),\n );\n};\n\nconst handleScheduleRequest = Effect.fn(\"ScheduleOwner.handleRequest\")(function* (\n encoded: unknown,\n): Effect.fn.Return<unknown, never, Scheduling | ScheduleOwnerIdentity> {\n const decoded = yield* decodeScheduleOwnerRequest(encoded).pipe(Effect.result);\n\n if (decoded._tag === \"Failure\") {\n return yield* encodeScheduleOwnerResponse(\n scheduleProtocolFailure(\"The Schedule request could not be decoded\"),\n ).pipe(Effect.orDie);\n }\n const request = decoded.success;\n const { owner } = yield* ScheduleOwnerIdentity;\n const scheduling = yield* Scheduling;\n\n const response = yield* Effect.gen(function* () {\n yield* ensureOwner(owner, request);\n switch (request._tag) {\n case \"Create\": {\n const value = yield* scheduling.create(passthroughAgent(request.agentId), request.input, {\n scope: request.scope,\n scheduleId: request.scheduleId,\n timing: request.timing,\n destination: request.destination,\n deliveryPrincipal: request.deliveryPrincipal,\n definitions: request.definitions,\n });\n\n return { _tag: \"Snapshot\" as const, value };\n }\n case \"Update\": {\n const value = yield* scheduling.update(passthroughAgent(request.agentId), request.input, {\n scope: request.scope,\n scheduleId: request.scheduleId,\n timing: request.timing,\n destination: request.destination,\n deliveryPrincipal: request.deliveryPrincipal,\n definitions: request.definitions,\n expectedRevision: request.expectedRevision,\n });\n\n return { _tag: \"Snapshot\" as const, value };\n }\n case \"Get\":\n return {\n _tag: \"Snapshot\" as const,\n value: yield* scheduling.get(request.scope, request.scheduleId),\n };\n case \"List\":\n return {\n _tag: \"Page\" as const,\n value: yield* scheduling.list(request.scope, {\n ...(request.after === undefined ? {} : { after: request.after }),\n ...(request.limit === undefined ? {} : { limit: request.limit }),\n }),\n };\n case \"Control\": {\n const value =\n request.operation === \"pause\"\n ? yield* scheduling.pause(request.scope, request.scheduleId, request.expectedRevision)\n : request.operation === \"resume\"\n ? yield* scheduling.resume(\n request.scope,\n request.scheduleId,\n request.expectedRevision,\n )\n : yield* scheduling.cancel(\n request.scope,\n request.scheduleId,\n request.expectedRevision,\n );\n\n return { _tag: \"Snapshot\" as const, value };\n }\n }\n }).pipe(\n Effect.map((value): ScheduleOwnerResponse => value),\n Effect.catch((failure) =>\n Schema.is(ScheduleOwnerFailure)(failure)\n ? Effect.succeed({ _tag: \"Failed\" as const, failure })\n : Effect.succeed(\n scheduleProtocolFailure(\"The Schedule operation failed outside its public contract\"),\n ),\n ),\n );\n\n return yield* encodeScheduleOwnerResponse(response).pipe(Effect.orDie);\n});\n\n/** @internal The complete native alarm operation, including its event deadline. */\nexport const scheduleAlarmHandler = (limits: SchedulingLimits) =>\n DurableObjectAlarm.processDue(\n (event) =>\n Effect.gen(function* () {\n if (event.tag !== SCHEDULE_ALARM_TAG || event.id !== SCHEDULE_ALARM_ID) {\n return yield* ScheduleAlarmProtocolError.make({\n message: `Unsupported Schedule Owner alarm ${event.tag}/${event.id}`,\n });\n }\n yield* Schema.decodeUnknownEffect(ScheduleAlarmPayload)(event.payload).pipe(\n Effect.mapError(() =>\n ScheduleAlarmProtocolError.make({\n message: \"Unsupported Schedule Owner alarm payload version\",\n }),\n ),\n );\n const scheduling = yield* ScheduleDriver;\n const alarmControl = yield* DoScheduleAlarmControl;\n const { owner } = yield* ScheduleOwnerIdentity;\n const nowMillis = yield* Clock.currentTimeMillis;\n\n yield* alarmControl.prearm(nowMillis + limits.recoveryPollMillis);\n const pass = yield* scheduling.runDue(owner);\n\n if (pass.failed > 0) {\n yield* alarmControl.prearm((yield* Clock.currentTimeMillis) + limits.recoveryPollMillis);\n } else {\n yield* alarmControl.reconcile;\n }\n }),\n { mode: \"ordered\" },\n ).pipe(\n // Bound due acquisition and acknowledgement as well as admission. Prepared occurrences\n // and their replacement alarm survive interruption and retain their idempotency keys.\n Effect.timeout(\"14 minutes\"),\n Effect.asVoid,\n );\n\nexport interface ScheduleOwnerObjectInstance extends InstanceType<\n EffectCfDurableObject.DurableObjectClass<Record<never, never>, ScheduleRuntimeServices>\n> {\n schedule(encoded: unknown): Promise<unknown>;\n alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> | void;\n}\n\nexport interface ScheduleOwnerObjectClass {\n new (ctx: DurableObjectState, env: Cloudflare.Env): ScheduleOwnerObjectInstance;\n}\n\n/**\n * The host Layer supplies authorization and routing and is cached for the object incarnation.\n * Cloudflare eviction does not guarantee its finalizers run. Do not acquire resources requiring\n * cleanup in this Layer; acquire them inside scoped `manage` / `prepare` operations instead.\n * Native services belong to effect-cf; the database and alarm runtime remain instance-owned.\n */\nexport const makeScheduleOwnerObjectClass = <E>(\n host: Layer.Layer<\n ScheduleAuthorizer | ThreadObjectNamespace,\n E,\n EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment | ScheduleOwnerIdentity\n >,\n limits: SchedulingLimits = defaultSchedulingLimits,\n): ScheduleOwnerObjectClass => {\n const ownerLayer = Layer.effect(\n ScheduleOwnerIdentity,\n Effect.gen(function* () {\n const state = yield* EffectCfDurableObjectState.DurableObjectState;\n\n return ScheduleOwnerIdentity.of({ owner: yield* decodeOwnerName(state.raw.id.name) });\n }),\n );\n\n const sqlLayer = Layer.unwrap(\n Effect.map(EffectCfDurableObjectState.DurableObjectState, (state) =>\n SqliteClient.layer({ storage: state.raw.storage }),\n ),\n );\n\n const application = Layer.merge(Scheduling.layer(limits), ScheduleDriver.layer(limits)).pipe(\n Layer.provideMerge(\n scheduleStoreLayer.pipe(Layer.provide(transactionLayer), Layer.provide(sqlLayer)),\n ),\n Layer.provide(\n cloudflareScheduledInputAdmissionLayer.pipe(\n Layer.provide(cloudflarePreparedInputAdmissionLayer),\n Layer.provide(CloudflareThreadClient.layer),\n ),\n ),\n Layer.provide(ScheduleWakeNoop),\n Layer.provide(BrowserCrypto.layer),\n Layer.provideMerge(DurableObjectAlarm.DurableObjectAlarm.layer),\n Layer.provide(host),\n Layer.provideMerge(ownerLayer),\n );\n\n const runtime: Layer.Layer<\n ScheduleRuntimeServices,\n E | ScheduleStorageError | ScheduleOwnerProtocolError | ScheduleValidationError,\n EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment\n > = Layer.effectContext(\n Effect.gen(function* () {\n const state = yield* EffectCfDurableObjectState.DurableObjectState;\n const scope = yield* Effect.scope;\n\n return yield* state.blockConcurrencyWhile(Layer.buildWithScope(application, scope));\n }),\n );\n\n const rpc = {\n schedule: (encoded: unknown) => handleScheduleRequest(encoded),\n } satisfies EffectCfDurableObject.DurableObjectRpc<ScheduleRuntimeServices>;\n\n const Base = EffectCfDurableObject.make(runtime, {\n initialize: Effect.void,\n rpc,\n alarms: scheduleAlarmHandler(limits),\n });\n\n class ScheduleOwnerObject extends Base {\n override alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> | void {\n return super.alarm?.(alarmInfo);\n }\n }\n\n return ScheduleOwnerObject;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAoDA,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAE1B,MAAM,uBAAuB,OAAO,OAAO;CACzC,eAAe,OAAO,QAAQ,CAAC;CAC/B,YAAY,OAAO,IAAI,MAAM,OAAO,cAAc,CAAC,CAAC;AACtD,CAAC;AAED,IAAa,6BAAb,cAAgD,OAAO,YAAwC,CAAC,CAC9F,8BACA,EAAE,SAAS,OAAO,OAAO,CAC3B,CAAC,CAAC,CAAC;AAEH,MAAM,0BAA0B,YAC9B,QAAQ,UAAU,OAAQ,UAAU,GAAG,QAAQ,MAAM,GAAG,IAAK,EAAE;AAEjE,IAAa,6BAAb,cAAgD,OAAO,YAAwC,CAAC,CAC9F,8BACA,EAAE,SAAS,OAAO,OAAO,MAAM,OAAO,YAAY,IAAK,CAAC,EAAE,CAC5D,CAAC,CAAC,CAAC;AAEH,MAAM,gCAAgC;CACpC,eAAe,OAAO,QAAQ,CAAC;CAC/B,SAAS;CACT,OAAO;CACP,OAAOA;CACP,YAAY;CACZ,QAAQ;CACR,aAAa;CACb,mBAAmBA,cAAoB,OAAO;CAC9C,aAAa;AACf;AAEA,MAAM,wBAAwB,OAAO,aAAa,UAAU,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AAC;CACpF,CAAC,CACH;CAMA,MAAM,OAAOC,cAAsB,KAAK,SAAS;EAC/C,YAAY,OAAO;EACnB,KAAA,EALA,WAAW,YAAqB,sBAAsB,OAAO,EAK3D;EACF,QAAQ,qBAAqB,MAAM;CACrC,CAAC;CAED,MAAM,4BAA4B,KAAK;EACrC,MAAe,WAAuD;GACpE,OAAO,MAAM,QAAQ,SAAS;EAChC;CACF;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"CloudflareScheduling.mjs","names":["ScheduleScopeSchema","ScheduleSnapshotPageSchema","EffectCfDurableObjectState","EffectCfDurableObject"],"sources":["../src/CloudflareScheduling.ts"],"sourcesContent":["import { AgentId } from \"@effect-agent/core/Identifiers\";\nimport {\n DoScheduleAlarmControl,\n DoScheduleTransaction,\n scheduleStoreLayer,\n} from \"@effect-agent/storage-cloudflare/DoScheduleStore\";\nimport { type DurableSubmitAgent } from \"@effect-agent/thread/DurableAgentRuntime\";\nimport { DefinitionDigests, PersistedJson } from \"@effect-agent/thread/Records\";\nimport {\n ScheduleAuthorizationError,\n type ScheduleAuthorizer,\n ScheduleCapacityError,\n ScheduleConflict,\n ScheduleDestination,\n ScheduleFailpointError,\n ScheduleId,\n type SchedulingLimits,\n ScheduleNotFound,\n ScheduleOwner,\n type ScheduleScope,\n ScheduleScope as ScheduleScopeSchema,\n ScheduleSnapshot,\n ScheduleSnapshotPage as ScheduleSnapshotPageSchema,\n ScheduleStorageError,\n ScheduleTimingRequest,\n ScheduleValidationError,\n defaultSchedulingLimits,\n} from \"@effect-agent/thread/Schedule\";\nimport { scheduleOwnerKey } from \"@effect-agent/thread/ScheduleTransition\";\nimport {\n Scheduling,\n ScheduleDriver,\n type ScheduleManagementFailure,\n ScheduleWakeNoop,\n} from \"@effect-agent/thread/Scheduling\";\nimport { AdmissionFence } from \"@effect-agent/thread/SubmissionLedger\";\nimport { BrowserCrypto } from \"@effect/platform-browser\";\nimport { SqliteClient } from \"@effect/sql-sqlite-do\";\nimport { Clock, Context, DateTime, Effect, Layer, Schema } from \"effect\";\nimport {\n DurableObject as EffectCfDurableObject,\n DurableObjectAlarm,\n DurableObjectState as EffectCfDurableObjectState,\n type WorkerEnvironment,\n} from \"effect-cf\";\n\nimport type { ThreadObjectNamespace } from \"./CloudflareBindings.ts\";\nimport { CloudflareThreadClient } from \"./CloudflareThreadClient.ts\";\nimport {\n cloudflarePreparedInputAdmissionLayer,\n cloudflareScheduledInputAdmissionLayer,\n} from \"./internal/prepared-admission.ts\";\n\nconst SCHEDULE_ALARM_TAG = \"effect-agent/ScheduleOwnerWake\";\nconst SCHEDULE_ALARM_ID = \"driver\";\n\nconst ScheduleAlarmPayload = Schema.Struct({\n schemaVersion: Schema.Literal(1),\n generation: Schema.Int.check(Schema.isGreaterThan(0)),\n});\n\nexport class ScheduleAlarmProtocolError extends Schema.TaggedError<ScheduleAlarmProtocolError>()(\n \"ScheduleAlarmProtocolError\",\n { message: Schema.String },\n) {}\n\nconst boundedProtocolMessage = (message: string): string =>\n message.length <= 4_096 ? message : `${message.slice(0, 4_093)}...`;\n\nexport class ScheduleOwnerProtocolError extends Schema.TaggedError<ScheduleOwnerProtocolError>()(\n \"ScheduleOwnerProtocolError\",\n { message: Schema.String.check(Schema.isMaxLength(4_096)) },\n) {}\n\nconst ScheduleMutationRequestFields = {\n schemaVersion: Schema.Literal(1),\n agentId: AgentId,\n input: PersistedJson,\n scope: ScheduleScopeSchema,\n scheduleId: ScheduleId,\n timing: ScheduleTimingRequest,\n destination: ScheduleDestination,\n deliveryPrincipal: ScheduleScopeSchema.fields.principal,\n definitions: DefinitionDigests,\n admissionGroup: Schema.optionalKey(Schema.NonEmptyString.check(Schema.isMaxLength(256))),\n admissionFence: Schema.optionalKey(AdmissionFence),\n};\n\nconst ScheduleCreateRequest = Schema.TaggedStruct(\"Create\", ScheduleMutationRequestFields);\n\nconst ScheduleUpdateRequest = Schema.TaggedStruct(\"Update\", {\n ...ScheduleMutationRequestFields,\n expectedRevision: Schema.Int.check(Schema.isGreaterThan(0)),\n});\n\nconst ScheduleGetRequest = Schema.TaggedStruct(\"Get\", {\n schemaVersion: Schema.Literal(1),\n scope: ScheduleScopeSchema,\n scheduleId: ScheduleId,\n});\n\nconst ScheduleListRequest = Schema.TaggedStruct(\"List\", {\n schemaVersion: Schema.Literal(1),\n scope: ScheduleScopeSchema,\n after: Schema.optionalKey(ScheduleId),\n limit: Schema.optionalKey(\n Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(100)),\n ),\n});\n\nconst ScheduleControlRequest = Schema.TaggedStruct(\"Control\", {\n schemaVersion: Schema.Literal(1),\n operation: Schema.Literals([\"pause\", \"resume\", \"cancel\"]),\n scope: ScheduleScopeSchema,\n scheduleId: ScheduleId,\n expectedRevision: Schema.Int.check(Schema.isGreaterThan(0)),\n});\n\nconst ScheduleRecoverRequest = Schema.TaggedStruct(\"Recover\", {\n schemaVersion: Schema.Literal(1),\n scope: ScheduleScopeSchema,\n scheduleId: ScheduleId,\n expectedRevision: Schema.Int.check(Schema.isGreaterThan(0)),\n expectedGeneration: Schema.Natural,\n});\n\nconst ScheduleOwnerRequest = Schema.Union([\n ScheduleRecoverRequest,\n ScheduleCreateRequest,\n ScheduleUpdateRequest,\n ScheduleGetRequest,\n ScheduleListRequest,\n ScheduleControlRequest,\n]);\n\ntype ScheduleOwnerRequest = typeof ScheduleOwnerRequest.Type;\n\nconst ScheduleOwnerFailure = Schema.Union([\n ScheduleValidationError,\n ScheduleAuthorizationError,\n ScheduleConflict,\n ScheduleNotFound,\n ScheduleCapacityError,\n ScheduleStorageError,\n ScheduleFailpointError,\n ScheduleOwnerProtocolError,\n]);\n\ntype ScheduleOwnerFailure = typeof ScheduleOwnerFailure.Type;\n\nconst ScheduleOwnerResponse = Schema.Union([\n Schema.TaggedStruct(\"Snapshot\", { value: ScheduleSnapshot }),\n Schema.TaggedStruct(\"Page\", { value: ScheduleSnapshotPageSchema }),\n Schema.TaggedStruct(\"Failed\", { failure: ScheduleOwnerFailure }),\n]);\n\ntype ScheduleOwnerResponse = typeof ScheduleOwnerResponse.Type;\n\nconst decodeScheduleOwnerRequest = Schema.decodeUnknownEffect(ScheduleOwnerRequest);\nconst encodeScheduleOwnerRequest = Schema.encodeEffect(ScheduleOwnerRequest);\nconst decodeScheduleOwnerResponse = Schema.decodeUnknownEffect(ScheduleOwnerResponse);\nconst encodeScheduleOwnerResponse = Schema.encodeEffect(ScheduleOwnerResponse);\n\nconst scheduleProtocolFailure = (message: string): ScheduleOwnerResponse => ({\n _tag: \"Failed\",\n failure: ScheduleOwnerProtocolError.make({ message: boundedProtocolMessage(message) }),\n});\n\nexport interface ScheduleOwnerObjectRpc extends Rpc.DurableObjectBranded {\n schedule(encoded: unknown): Promise<unknown>;\n}\n\nexport class ScheduleOwnerNamespace extends Context.Service<\n ScheduleOwnerNamespace,\n { readonly namespace: DurableObjectNamespace<ScheduleOwnerObjectRpc> }\n>()(\"@effect-agent/platform-cloudflare/ScheduleOwnerNamespace\") {}\n\nconst passthroughAgent = (agentId: AgentId): DurableSubmitAgent<typeof PersistedJson> => ({\n definition: { id: agentId, input: PersistedJson },\n});\n\nconst requestOwner = (request: ScheduleOwnerRequest): ScheduleOwner => request.scope.owner;\n\n/** Provides the same authorized management service as NodeScheduling.layer. */\nexport class CloudflareSchedulingClient {\n static readonly layer: Layer.Layer<Scheduling, never, ScheduleOwnerNamespace> = Layer.effect(\n Scheduling,\n Effect.gen(function* () {\n const { namespace } = yield* ScheduleOwnerNamespace;\n\n const call = Effect.fn(\"CloudflareSchedulingClient.call\")(function* (\n owner: ScheduleOwner,\n request: ScheduleOwnerRequest,\n ): Effect.fn.Return<ScheduleOwnerResponse, ScheduleManagementFailure> {\n const encoded = yield* encodeScheduleOwnerRequest(request).pipe(\n Effect.mapError(() =>\n ScheduleStorageError.make({ operation: \"Schedule Owner protocol\", reason: \"corrupt\" }),\n ),\n );\n\n const raw = yield* Effect.tryPromise({\n try: () => namespace.get(namespace.idFromName(scheduleOwnerKey(owner))).schedule(encoded),\n catch: () =>\n ScheduleStorageError.make({\n operation: \"call Schedule Owner\",\n reason: \"unavailable\",\n }),\n });\n\n const response = yield* decodeScheduleOwnerResponse(raw).pipe(\n Effect.mapError(() =>\n ScheduleStorageError.make({ operation: \"Schedule Owner protocol\", reason: \"corrupt\" }),\n ),\n );\n\n if (response._tag !== \"Failed\") return response;\n\n return yield* response.failure._tag === \"ScheduleOwnerProtocolError\"\n ? ScheduleStorageError.make({ operation: \"Schedule Owner protocol\", reason: \"corrupt\" })\n : response.failure;\n });\n\n const encodeInput = Effect.fn(\"CloudflareSchedulingClient.encodeInput\")(function* <\n InputSchema extends Schema.Top,\n >(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n ): Effect.fn.Return<PersistedJson, ScheduleValidationError, InputSchema[\"EncodingServices\"]> {\n const encoded = yield* Schema.encodeEffect(agent.definition.input)(input).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({\n message: \"Unable to encode Agent input\",\n }),\n ),\n );\n\n return yield* Schema.decodeUnknownEffect(PersistedJson)(encoded).pipe(\n Effect.mapError(() =>\n ScheduleValidationError.make({\n message: \"Agent input does not satisfy the canonical persistence bounds\",\n }),\n ),\n );\n });\n\n const create: Scheduling[\"Service\"][\"create\"] = (agent, input, options) =>\n Effect.gen(function* () {\n const payload = yield* encodeInput(agent, input);\n\n const response = yield* call(options.scope.owner, {\n _tag: \"Create\",\n schemaVersion: 1,\n agentId: agent.definition.id,\n input: payload,\n ...options,\n });\n\n return response._tag === \"Snapshot\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n const update: Scheduling[\"Service\"][\"update\"] = (agent, input, options) =>\n Effect.gen(function* () {\n const payload = yield* encodeInput(agent, input);\n\n const response = yield* call(options.scope.owner, {\n _tag: \"Update\",\n schemaVersion: 1,\n agentId: agent.definition.id,\n input: payload,\n ...options,\n });\n\n return response._tag === \"Snapshot\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n const get: Scheduling[\"Service\"][\"get\"] = (scope, scheduleId) =>\n Effect.gen(function* () {\n const response = yield* call(scope.owner, {\n _tag: \"Get\",\n schemaVersion: 1,\n scope,\n scheduleId,\n });\n\n return response._tag === \"Snapshot\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n const list: Scheduling[\"Service\"][\"list\"] = (scope, options = {}) =>\n Effect.gen(function* () {\n const response = yield* call(scope.owner, {\n _tag: \"List\",\n schemaVersion: 1,\n scope,\n ...(options.after === undefined ? {} : { after: options.after }),\n ...(options.limit === undefined ? {} : { limit: options.limit }),\n });\n\n return response._tag === \"Page\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n const control = (\n operation: \"pause\" | \"resume\" | \"cancel\",\n scope: ScheduleScope,\n scheduleId: ScheduleId,\n expectedRevision: number,\n ) =>\n Effect.gen(function* () {\n const response = yield* call(scope.owner, {\n _tag: \"Control\",\n schemaVersion: 1,\n operation,\n scope,\n scheduleId,\n expectedRevision,\n });\n\n return response._tag === \"Snapshot\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n });\n\n return Scheduling.of({\n create,\n update,\n get,\n list,\n pause: (scope, id, revision) => control(\"pause\", scope, id, revision),\n resume: (scope, id, revision) => control(\"resume\", scope, id, revision),\n recover: (scope, scheduleId, expectedRevision, expectedGeneration) =>\n Effect.gen(function* () {\n const response = yield* call(scope.owner, {\n _tag: \"Recover\",\n schemaVersion: 1,\n scope,\n scheduleId,\n expectedRevision,\n expectedGeneration,\n });\n\n return response._tag === \"Snapshot\"\n ? response.value\n : yield* ScheduleStorageError.make({\n operation: \"Schedule Owner protocol\",\n reason: \"corrupt\",\n });\n }),\n cancel: (scope, id, revision) => control(\"cancel\", scope, id, revision),\n });\n }),\n );\n}\n\nexport class ScheduleOwnerIdentity extends Context.Service<\n ScheduleOwnerIdentity,\n { readonly owner: ScheduleOwner }\n>()(\"@effect-agent/platform-cloudflare/ScheduleOwnerIdentity\") {}\n\nconst decodeOwnerName = Effect.fn(\"decodeScheduleOwnerName\")(function* (\n name: string | null | undefined,\n): Effect.fn.Return<ScheduleOwner, ScheduleOwnerProtocolError> {\n if (name === null || name === undefined) {\n return yield* ScheduleOwnerProtocolError.make({\n message: \"Schedule Owner objects require an idFromName identity\",\n });\n }\n\n const tuple = yield* Schema.decodeUnknownEffect(\n Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.String])),\n )(name).pipe(\n Effect.mapError(() =>\n ScheduleOwnerProtocolError.make({ message: \"Schedule Owner object name is malformed\" }),\n ),\n );\n\n return yield* Schema.decodeUnknownEffect(ScheduleOwner)({\n tenantId: tuple[0],\n ownerId: tuple[1],\n }).pipe(\n Effect.mapError(() =>\n ScheduleOwnerProtocolError.make({ message: \"Schedule Owner object identity is invalid\" }),\n ),\n );\n});\n\nconst alarmStorageError = (operation: string) => (error: { readonly _tag: string }) =>\n ScheduleStorageError.make({\n operation,\n reason: error._tag === \"StorageOperationError\" ? \"unavailable\" : \"corrupt\",\n });\n\nconst transactionLayer: Layer.Layer<\n DoScheduleTransaction,\n never,\n DurableObjectAlarm.DurableObjectAlarm\n> = Layer.effect(\n DoScheduleTransaction,\n Effect.gen(function* () {\n const alarms = yield* DurableObjectAlarm.DurableObjectAlarm;\n\n return DoScheduleTransaction.of({\n run: (body) =>\n Effect.gen(function* () {\n const nowMillis = yield* Clock.currentTimeMillis;\n\n return yield* alarms\n .transaction((transaction) =>\n body((replacement) =>\n replacement.deadlineAtMillis === null\n ? transaction\n .cancelAlarm({ id: SCHEDULE_ALARM_ID, tag: SCHEDULE_ALARM_TAG })\n .pipe(Effect.mapError(alarmStorageError(\"cancel Schedule Owner alarm\")))\n : Effect.fromOption(\n DateTime.make(Math.max(replacement.deadlineAtMillis, nowMillis + 1)),\n ).pipe(\n Effect.mapError(() =>\n ScheduleStorageError.make({\n operation: \"validate Schedule Owner alarm deadline\",\n reason: \"corrupt\",\n }),\n ),\n Effect.flatMap((runAt) =>\n transaction\n .scheduleAlarm({\n id: SCHEDULE_ALARM_ID,\n tag: SCHEDULE_ALARM_TAG,\n runAt,\n payload: {\n schemaVersion: 1,\n generation: replacement.generation,\n },\n })\n .pipe(\n Effect.mapError(alarmStorageError(\"schedule Schedule Owner alarm\")),\n ),\n ),\n ),\n ),\n )\n .pipe(\n Effect.catchTag(\"StorageOperationError\", () =>\n ScheduleStorageError.make({\n operation: \"commit Schedule Owner transaction\",\n reason: \"unavailable\",\n }),\n ),\n );\n }),\n });\n }),\n);\n\ntype ScheduleRuntimeServices =\n | Scheduling\n | ScheduleDriver\n | DoScheduleAlarmControl\n | ScheduleOwnerIdentity\n | DurableObjectAlarm.DurableObjectAlarm;\n\nconst ensureOwner = (\n expected: ScheduleOwner,\n request: ScheduleOwnerRequest,\n): Effect.Effect<void, ScheduleOwnerProtocolError> => {\n const observed = requestOwner(request);\n\n return observed.tenantId === expected.tenantId && observed.ownerId === expected.ownerId\n ? Effect.void\n : Effect.fail(\n ScheduleOwnerProtocolError.make({\n message: \"The request owner does not match the addressed Schedule Owner object\",\n }),\n );\n};\n\nconst handleScheduleRequest = Effect.fn(\"ScheduleOwner.handleRequest\")(function* (\n encoded: unknown,\n): Effect.fn.Return<unknown, never, Scheduling | ScheduleOwnerIdentity> {\n const decoded = yield* decodeScheduleOwnerRequest(encoded).pipe(Effect.result);\n\n if (decoded._tag === \"Failure\") {\n return yield* encodeScheduleOwnerResponse(\n scheduleProtocolFailure(\"The Schedule request could not be decoded\"),\n ).pipe(Effect.orDie);\n }\n const request = decoded.success;\n const { owner } = yield* ScheduleOwnerIdentity;\n const scheduling = yield* Scheduling;\n\n const response = yield* Effect.gen(function* () {\n yield* ensureOwner(owner, request);\n switch (request._tag) {\n case \"Create\": {\n const value = yield* scheduling.create(passthroughAgent(request.agentId), request.input, {\n scope: request.scope,\n scheduleId: request.scheduleId,\n timing: request.timing,\n destination: request.destination,\n deliveryPrincipal: request.deliveryPrincipal,\n definitions: request.definitions,\n ...(request.admissionGroup === undefined\n ? {}\n : { admissionGroup: request.admissionGroup }),\n ...(request.admissionFence === undefined\n ? {}\n : { admissionFence: request.admissionFence }),\n });\n\n return { _tag: \"Snapshot\" as const, value };\n }\n case \"Update\": {\n const value = yield* scheduling.update(passthroughAgent(request.agentId), request.input, {\n scope: request.scope,\n scheduleId: request.scheduleId,\n timing: request.timing,\n destination: request.destination,\n deliveryPrincipal: request.deliveryPrincipal,\n definitions: request.definitions,\n ...(request.admissionGroup === undefined\n ? {}\n : { admissionGroup: request.admissionGroup }),\n ...(request.admissionFence === undefined\n ? {}\n : { admissionFence: request.admissionFence }),\n expectedRevision: request.expectedRevision,\n });\n\n return { _tag: \"Snapshot\" as const, value };\n }\n case \"Get\":\n return {\n _tag: \"Snapshot\" as const,\n value: yield* scheduling.get(request.scope, request.scheduleId),\n };\n case \"List\":\n return {\n _tag: \"Page\" as const,\n value: yield* scheduling.list(request.scope, {\n ...(request.after === undefined ? {} : { after: request.after }),\n ...(request.limit === undefined ? {} : { limit: request.limit }),\n }),\n };\n case \"Recover\":\n return {\n _tag: \"Snapshot\" as const,\n value: yield* scheduling.recover(\n request.scope,\n request.scheduleId,\n request.expectedRevision,\n request.expectedGeneration,\n ),\n };\n case \"Control\": {\n const value =\n request.operation === \"pause\"\n ? yield* scheduling.pause(request.scope, request.scheduleId, request.expectedRevision)\n : request.operation === \"resume\"\n ? yield* scheduling.resume(\n request.scope,\n request.scheduleId,\n request.expectedRevision,\n )\n : yield* scheduling.cancel(\n request.scope,\n request.scheduleId,\n request.expectedRevision,\n );\n\n return { _tag: \"Snapshot\" as const, value };\n }\n }\n }).pipe(\n Effect.map((value): ScheduleOwnerResponse => value),\n Effect.catch((failure) =>\n Schema.is(ScheduleOwnerFailure)(failure)\n ? Effect.succeed({ _tag: \"Failed\" as const, failure })\n : Effect.succeed(\n scheduleProtocolFailure(\"The Schedule operation failed outside its public contract\"),\n ),\n ),\n );\n\n return yield* encodeScheduleOwnerResponse(response).pipe(Effect.orDie);\n});\n\n/** @internal The complete native alarm operation, including its event deadline. */\nexport const scheduleAlarmHandler = (limits: SchedulingLimits) =>\n DurableObjectAlarm.processDue(\n (event) =>\n Effect.gen(function* () {\n if (event.tag !== SCHEDULE_ALARM_TAG || event.id !== SCHEDULE_ALARM_ID) {\n return yield* ScheduleAlarmProtocolError.make({\n message: `Unsupported Schedule Owner alarm ${event.tag}/${event.id}`,\n });\n }\n yield* Schema.decodeUnknownEffect(ScheduleAlarmPayload)(event.payload).pipe(\n Effect.mapError(() =>\n ScheduleAlarmProtocolError.make({\n message: \"Unsupported Schedule Owner alarm payload version\",\n }),\n ),\n );\n const scheduling = yield* ScheduleDriver;\n const alarmControl = yield* DoScheduleAlarmControl;\n const { owner } = yield* ScheduleOwnerIdentity;\n const nowMillis = yield* Clock.currentTimeMillis;\n\n yield* alarmControl.prearm(nowMillis + limits.recoveryPollMillis);\n const pass = yield* scheduling.runDue(owner);\n\n if (pass.failed > 0) {\n yield* alarmControl.prearm((yield* Clock.currentTimeMillis) + limits.recoveryPollMillis);\n } else {\n yield* alarmControl.reconcile;\n }\n }),\n { mode: \"ordered\" },\n ).pipe(\n // Bound due acquisition and acknowledgement as well as admission. Prepared occurrences\n // and their replacement alarm survive interruption and retain their idempotency keys.\n Effect.timeout(\"14 minutes\"),\n Effect.asVoid,\n );\n\nexport interface ScheduleOwnerObjectInstance extends InstanceType<\n EffectCfDurableObject.DurableObjectClass<Record<never, never>, ScheduleRuntimeServices>\n> {\n schedule(encoded: unknown): Promise<unknown>;\n alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> | void;\n}\n\nexport interface ScheduleOwnerObjectClass {\n new (ctx: DurableObjectState, env: Cloudflare.Env): ScheduleOwnerObjectInstance;\n}\n\n/**\n * The host Layer supplies authorization and routing and is cached for the object incarnation.\n * Cloudflare eviction does not guarantee its finalizers run. Do not acquire resources requiring\n * cleanup in this Layer; acquire them inside scoped `manage` / `prepare` operations instead.\n * Native services belong to effect-cf; the database and alarm runtime remain instance-owned.\n */\nexport const makeScheduleOwnerObjectClass = <E>(\n host: Layer.Layer<\n ScheduleAuthorizer | ThreadObjectNamespace,\n E,\n EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment | ScheduleOwnerIdentity\n >,\n limits: SchedulingLimits = defaultSchedulingLimits,\n): ScheduleOwnerObjectClass => {\n const ownerLayer = Layer.effect(\n ScheduleOwnerIdentity,\n Effect.gen(function* () {\n const state = yield* EffectCfDurableObjectState.DurableObjectState;\n\n return ScheduleOwnerIdentity.of({ owner: yield* decodeOwnerName(state.raw.id.name) });\n }),\n );\n\n const sqlLayer = Layer.unwrap(\n Effect.map(EffectCfDurableObjectState.DurableObjectState, (state) =>\n SqliteClient.layer({ storage: state.raw.storage }),\n ),\n );\n\n const application = Layer.merge(Scheduling.layer(limits), ScheduleDriver.layer(limits)).pipe(\n Layer.provideMerge(\n scheduleStoreLayer.pipe(Layer.provide(transactionLayer), Layer.provide(sqlLayer)),\n ),\n Layer.provide(\n cloudflareScheduledInputAdmissionLayer.pipe(\n Layer.provide(cloudflarePreparedInputAdmissionLayer),\n Layer.provide(CloudflareThreadClient.layer),\n ),\n ),\n Layer.provide(ScheduleWakeNoop),\n Layer.provide(BrowserCrypto.layer),\n Layer.provideMerge(DurableObjectAlarm.DurableObjectAlarm.layer),\n Layer.provide(host),\n Layer.provideMerge(ownerLayer),\n );\n\n const runtime: Layer.Layer<\n ScheduleRuntimeServices,\n E | ScheduleStorageError | ScheduleOwnerProtocolError | ScheduleValidationError,\n EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment\n > = Layer.effectContext(\n Effect.gen(function* () {\n const state = yield* EffectCfDurableObjectState.DurableObjectState;\n const scope = yield* Effect.scope;\n\n return yield* state.blockConcurrencyWhile(Layer.buildWithScope(application, scope));\n }),\n );\n\n const rpc = {\n schedule: (encoded: unknown) => handleScheduleRequest(encoded),\n } satisfies EffectCfDurableObject.DurableObjectRpc<ScheduleRuntimeServices>;\n\n const Base = EffectCfDurableObject.make(runtime, {\n initialize: Effect.void,\n rpc,\n alarms: scheduleAlarmHandler(limits),\n });\n\n class ScheduleOwnerObject extends Base {\n override alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> | void {\n return super.alarm?.(alarmInfo);\n }\n }\n\n return ScheduleOwnerObject;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAE1B,MAAM,uBAAuB,OAAO,OAAO;CACzC,eAAe,OAAO,QAAQ,CAAC;CAC/B,YAAY,OAAO,IAAI,MAAM,OAAO,cAAc,CAAC,CAAC;AACtD,CAAC;AAED,IAAa,6BAAb,cAAgD,OAAO,YAAwC,CAAC,CAC9F,8BACA,EAAE,SAAS,OAAO,OAAO,CAC3B,CAAC,CAAC,CAAC;AAEH,MAAM,0BAA0B,YAC9B,QAAQ,UAAU,OAAQ,UAAU,GAAG,QAAQ,MAAM,GAAG,IAAK,EAAE;AAEjE,IAAa,6BAAb,cAAgD,OAAO,YAAwC,CAAC,CAC9F,8BACA,EAAE,SAAS,OAAO,OAAO,MAAM,OAAO,YAAY,IAAK,CAAC,EAAE,CAC5D,CAAC,CAAC,CAAC;AAEH,MAAM,gCAAgC;CACpC,eAAe,OAAO,QAAQ,CAAC;CAC/B,SAAS;CACT,OAAO;CACP,OAAOA;CACP,YAAY;CACZ,QAAQ;CACR,aAAa;CACb,mBAAmBA,cAAoB,OAAO;CAC9C,aAAa;CACb,gBAAgB,OAAO,YAAY,OAAO,eAAe,MAAM,OAAO,YAAY,GAAG,CAAC,CAAC;CACvF,gBAAgB,OAAO,YAAY,cAAc;AACnD;AAEA,MAAM,wBAAwB,OAAO,aAAa,U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