@effect-agent/platform-cloudflare 0.1.0-beta.131 → 0.1.0-beta.133
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/Alarm.mjs +3 -1
- package/dist/Alarm.mjs.map +1 -1
- package/dist/CloudflareBindings.d.mts +2 -2
- package/dist/CloudflareBindings.mjs.map +1 -1
- package/dist/CloudflareThreadClient.d.mts +47 -47
- package/dist/{ThreadObject-CVhZC-7l.mjs → ThreadObject-BkLV7hMd.mjs} +15 -7
- package/dist/ThreadObject-BkLV7hMd.mjs.map +1 -0
- package/dist/{ThreadObject-D8GzJxJB.d.mts → ThreadObject-D1CWZ8j3.d.mts} +27 -24
- 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/package.json +1 -1
- package/src/Alarm.ts +12 -2
- package/src/CloudflareBindings.ts +2 -2
- package/src/ThreadObject.ts +3 -1
- package/src/internal/layers.ts +7 -4
- package/src/internal/transport.ts +23 -11
- package/dist/ThreadObject-CVhZC-7l.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CloudflareBindings.mjs","names":[],"sources":["../src/CloudflareBindings.ts"],"sourcesContent":["import { Context, Effect, Layer, Predicate, Schema } from \"effect\";\nimport { type ThreadId } from \"effect-agent/identifiers\";\nimport { type ProducerId } from \"effect-agent/records\";\nimport { RpcTargets } from \"effect-cf\";\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/** A logical Thread endpoint may be bound to an application Object without forging its brand. */\nexport type ThreadObjectClient = Omit<ThreadObjectRpc, keyof Rpc.DurableObjectBranded>;\n\n/**\n * Deterministic logical Thread placement. The native adapter uses `idFromName(threadId)`;\n * a shared application owner can bind that logical identity into its RPC adapter instead.\n * Lookup performs no I/O and grants no authority. Calls reuse a native target within\n * one invocation; incoming requests and durable retries acquire their own targets.\n */\nexport class ThreadObjectNamespace extends Context.Service<\n ThreadObjectNamespace,\n {\n readonly get: (threadId: ThreadId) => ThreadObjectClient;\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 get: (threadId) => namespace.get(namespace.idFromName(threadId)),\n ...(options.rpcTracing === undefined ? {} : { rpcTracing: options.rpcTracing }),\n });\n }\n}\n\n/** Invoke a placed Thread using the current invocation's native RPC channel. */\nexport const callThreadObject = Effect.fn(\"callThreadObject\")(function* <A, E>(\n threadId: ThreadId,\n invoke: (target: ThreadObjectClient) => Promise<A>,\n onError: (cause: unknown) => E,\n): Effect.fn.Return<A, E, ThreadObjectNamespace> {\n const namespace = yield* ThreadObjectNamespace;\n\n const target = yield* RpcTargets.get(namespace, threadId, () => namespace.get(threadId)).pipe(\n Effect.mapError(onError),\n );\n\n return yield* Effect.tryPromise({ try: () => invoke(target), catch: onError }).pipe(\n Effect.tapCause(() => RpcTargets.invalidate(target)),\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 get: (threadId) => namespace.get(namespace.idFromName(threadId)),\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\n/** Logical Threads whose canonical stores and admission ledger live in this physical Object. */\nexport class ThreadObjectPlacement extends Context.Service<\n ThreadObjectPlacement,\n { readonly ownsThread: (threadId: ThreadId) => boolean }\n>()(\"@effect-agent/platform-cloudflare/ThreadObjectPlacement\") {}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAaA,IAAa,yBAAb,cAA4C,OAAO,YAAoC,CAAC,CACtF,0BACA;CACE,SAAS,OAAO;CAChB,SAAS,OAAO;AAClB,CACF,CAAC,CAAC,CAAC;;;;;;;AA6CH,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,MAAM,aAAa,UAAU,IAAI,UAAU,WAAW,QAAQ,CAAC;GAC/D,GAAI,QAAQ,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY,QAAQ,WAAW;EAC/E,CAAC;CACH;AACF;;AAGA,MAAa,mBAAmB,OAAO,GAAG,kBAAkB,CAAC,CAAC,WAC5D,UACA,QACA,SAC+C;CAC/C,MAAM,YAAY,OAAO;CAEzB,MAAM,SAAS,OAAO,WAAW,IAAI,W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,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;;AAG/D,IAAa,wBAAb,cAA2C,QAAQ,QAGjD,CAAC,CAAC,yDAAyD,CAAC,CAAC,CAAC"}
|
|
1
|
+
{"version":3,"file":"CloudflareBindings.mjs","names":[],"sources":["../src/CloudflareBindings.ts"],"sourcesContent":["import { Context, Effect, Layer, Predicate, Schema } from \"effect\";\nimport { type ThreadId } from \"effect-agent/identifiers\";\nimport { type ProducerId } from \"effect-agent/records\";\nimport { RpcTargets } from \"effect-cf\";\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 or port 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, traceContext?: unknown): Promise<unknown>;\n /** Droppable liveness hint from another Object: arms an immediate alarm. */\n wake(): Promise<void>;\n}\n\n/** A logical Thread endpoint may be bound to an application Object without forging its brand. */\nexport type ThreadObjectClient = Omit<ThreadObjectRpc, keyof Rpc.DurableObjectBranded>;\n\n/**\n * Deterministic logical Thread placement. The native adapter uses `idFromName(threadId)`;\n * a shared application owner can bind that logical identity into its RPC adapter instead.\n * Lookup performs no I/O and grants no authority. Calls reuse a native target within\n * one invocation; incoming requests and durable retries acquire their own targets.\n */\nexport class ThreadObjectNamespace extends Context.Service<\n ThreadObjectNamespace,\n {\n readonly get: (threadId: ThreadId) => ThreadObjectClient;\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 get: (threadId) => namespace.get(namespace.idFromName(threadId)),\n ...(options.rpcTracing === undefined ? {} : { rpcTracing: options.rpcTracing }),\n });\n }\n}\n\n/** Invoke a placed Thread using the current invocation's native RPC channel. */\nexport const callThreadObject = Effect.fn(\"callThreadObject\")(function* <A, E>(\n threadId: ThreadId,\n invoke: (target: ThreadObjectClient) => Promise<A>,\n onError: (cause: unknown) => E,\n): Effect.fn.Return<A, E, ThreadObjectNamespace> {\n const namespace = yield* ThreadObjectNamespace;\n\n const target = yield* RpcTargets.get(namespace, threadId, () => namespace.get(threadId)).pipe(\n Effect.mapError(onError),\n );\n\n return yield* Effect.tryPromise({ try: () => invoke(target), catch: onError }).pipe(\n Effect.tapCause(() => RpcTargets.invalidate(target)),\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 get: (threadId) => namespace.get(namespace.idFromName(threadId)),\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\n/** Logical Threads whose canonical stores and admission ledger live in this physical Object. */\nexport class ThreadObjectPlacement extends Context.Service<\n ThreadObjectPlacement,\n { readonly ownsThread: (threadId: ThreadId) => boolean }\n>()(\"@effect-agent/platform-cloudflare/ThreadObjectPlacement\") {}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAaA,IAAa,yBAAb,cAA4C,OAAO,YAAoC,CAAC,CACtF,0BACA;CACE,SAAS,OAAO;CAChB,SAAS,OAAO;AAClB,CACF,CAAC,CAAC,CAAC;;;;;;;AA6CH,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,MAAM,aAAa,UAAU,IAAI,UAAU,WAAW,QAAQ,CAAC;GAC/D,GAAI,QAAQ,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY,QAAQ,WAAW;EAC/E,CAAC;CACH;AACF;;AAGA,MAAa,mBAAmB,OAAO,GAAG,kBAAkB,CAAC,CAAC,WAC5D,UACA,QACA,SAC+C;CAC/C,MAAM,YAAY,OAAO;CAEzB,MAAM,SAAS,OAAO,WAAW,IAAI,WAAW,gBAAgB,UAAU,IAAI,QAAQ,CAAC,CAAC,CAAC,KACvF,OAAO,SAAS,OAAO,CACzB;CAEA,OAAO,OAAO,OAAO,WAAW;EAAE,WAAW,OAAO,MAAM;EAAG,OAAO;CAAQ,CAAC,CAAC,CAAC,KAC7E,OAAO,eAAe,WAAW,WAAW,MAAM,CAAC,CACrD;AACF,CAAC;;;;;;;AAQD,MAAa,yBAAyB,OAAO,GAAG,wBAAwB,CAAC,CAAC,WACxE,KACA,SACmF;CACnF,IAAI,CAAC,UAAU,gBAAgB,GAAG,GAChC,OAAO,OAAO,uBAAuB,KAAK;EACxC;EACA,SA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
|
522
522
|
readonly author: string;
|
|
523
523
|
readonly reason: string;
|
|
524
524
|
readonly resolution: {
|
|
525
|
+
readonly _tag: "SafeToRetry";
|
|
526
|
+
} | {
|
|
525
527
|
readonly _tag: "CompletedWithResult";
|
|
526
528
|
readonly result: Schema.Json;
|
|
527
529
|
readonly isFailure: boolean;
|
|
528
530
|
} | {
|
|
529
531
|
readonly _tag: "NeverHappened";
|
|
530
|
-
} | {
|
|
531
|
-
readonly _tag: "SafeToRetry";
|
|
532
532
|
} | {
|
|
533
533
|
readonly _tag: "AbortSubmission";
|
|
534
534
|
};
|
|
@@ -692,6 +692,19 @@ export declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorde
|
|
|
692
692
|
readonly createdAt: string;
|
|
693
693
|
readonly deploymentId: string;
|
|
694
694
|
readonly payload: {
|
|
695
|
+
readonly _tag: "SubagentStarted";
|
|
696
|
+
readonly runId: string;
|
|
697
|
+
readonly toolCallId: string;
|
|
698
|
+
readonly childThreadId: string;
|
|
699
|
+
readonly childSubmissionId: string;
|
|
700
|
+
readonly childReceiptId: string;
|
|
701
|
+
readonly childRunId: string;
|
|
702
|
+
} | {
|
|
703
|
+
readonly _tag: "AbortRequested";
|
|
704
|
+
readonly submissionId: string;
|
|
705
|
+
readonly author: string;
|
|
706
|
+
readonly reason: string;
|
|
707
|
+
} | {
|
|
695
708
|
readonly _tag: "ThreadCreated";
|
|
696
709
|
readonly agentId: string;
|
|
697
710
|
readonly definitions: {
|
|
@@ -969,11 +982,6 @@ export declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorde
|
|
|
969
982
|
readonly runDisposition?: Schema.Json | undefined;
|
|
970
983
|
readonly finishReason?: "budget-exhausted" | undefined;
|
|
971
984
|
readonly exhausted?: "tokens" | "tool-calls" | "turns" | undefined;
|
|
972
|
-
} | {
|
|
973
|
-
readonly _tag: "AbortRequested";
|
|
974
|
-
readonly submissionId: string;
|
|
975
|
-
readonly author: string;
|
|
976
|
-
readonly reason: string;
|
|
977
985
|
} | {
|
|
978
986
|
readonly _tag: "SubmissionSettled";
|
|
979
987
|
readonly submissionId: string;
|
|
@@ -1108,14 +1116,6 @@ export declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorde
|
|
|
1108
1116
|
readonly childLifetimes?: readonly ("attached" | "background")[] | undefined;
|
|
1109
1117
|
} | undefined;
|
|
1110
1118
|
readonly depth?: number | undefined;
|
|
1111
|
-
} | {
|
|
1112
|
-
readonly _tag: "SubagentStarted";
|
|
1113
|
-
readonly runId: string;
|
|
1114
|
-
readonly toolCallId: string;
|
|
1115
|
-
readonly childThreadId: string;
|
|
1116
|
-
readonly childSubmissionId: string;
|
|
1117
|
-
readonly childReceiptId: string;
|
|
1118
|
-
readonly childRunId: string;
|
|
1119
1119
|
} | {
|
|
1120
1120
|
readonly _tag: "SubagentJoined";
|
|
1121
1121
|
readonly runId: string;
|
|
@@ -1579,13 +1579,13 @@ export declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorde
|
|
|
1579
1579
|
readonly author: string;
|
|
1580
1580
|
readonly reason: string;
|
|
1581
1581
|
readonly resolution: {
|
|
1582
|
+
readonly _tag: "SafeToRetry";
|
|
1583
|
+
} | {
|
|
1582
1584
|
readonly _tag: "CompletedWithResult";
|
|
1583
1585
|
readonly result: Schema.Json;
|
|
1584
1586
|
readonly isFailure: boolean;
|
|
1585
1587
|
} | {
|
|
1586
1588
|
readonly _tag: "NeverHappened";
|
|
1587
|
-
} | {
|
|
1588
|
-
readonly _tag: "SafeToRetry";
|
|
1589
1589
|
} | {
|
|
1590
1590
|
readonly _tag: "AbortSubmission";
|
|
1591
1591
|
};
|
|
@@ -1595,13 +1595,31 @@ export declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorde
|
|
|
1595
1595
|
} | {
|
|
1596
1596
|
readonly _tag: "HostFailed";
|
|
1597
1597
|
readonly failure: {
|
|
1598
|
-
readonly _tag: "
|
|
1598
|
+
readonly _tag: "AdmissionConflict";
|
|
1599
|
+
readonly threadId: string;
|
|
1600
|
+
readonly principal: string;
|
|
1601
|
+
readonly idempotencyKey: string;
|
|
1602
|
+
readonly existingInputDigest: string;
|
|
1603
|
+
readonly attemptedInputDigest: string;
|
|
1604
|
+
} | {
|
|
1605
|
+
readonly _tag: "AdmissionPolicyError";
|
|
1606
|
+
readonly reason: "occupied" | "refused" | "unavailable";
|
|
1607
|
+
readonly code: string;
|
|
1608
|
+
readonly cause?: import("effect-agent/failure-diagnostic").Diagnostic | undefined;
|
|
1609
|
+
readonly stack?: string | undefined;
|
|
1610
|
+
} | {
|
|
1611
|
+
readonly _tag: "SettlementConflict";
|
|
1612
|
+
readonly submissionId: string;
|
|
1613
|
+
readonly existingOutcome: "aborted" | "completed" | "failed";
|
|
1614
|
+
} | {
|
|
1615
|
+
readonly _tag: "JoinedToHost";
|
|
1616
|
+
readonly submissionId: string;
|
|
1617
|
+
readonly hostSubmissionId: string;
|
|
1618
|
+
} | {
|
|
1619
|
+
readonly _tag: "LedgerError";
|
|
1599
1620
|
readonly operation: string;
|
|
1600
1621
|
readonly message: string;
|
|
1601
|
-
readonly cause?:
|
|
1602
|
-
} | {
|
|
1603
|
-
readonly _tag: "ThreadNotMaterialized";
|
|
1604
|
-
readonly threadId: string;
|
|
1622
|
+
readonly cause?: import("effect-agent/failure-diagnostic").Diagnostic | undefined;
|
|
1605
1623
|
} | {
|
|
1606
1624
|
readonly _tag: "ThreadStoreError";
|
|
1607
1625
|
readonly operation: string;
|
|
@@ -1615,10 +1633,8 @@ export declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorde
|
|
|
1615
1633
|
readonly sequence?: number | undefined;
|
|
1616
1634
|
} | undefined;
|
|
1617
1635
|
} | {
|
|
1618
|
-
readonly _tag: "
|
|
1619
|
-
readonly
|
|
1620
|
-
readonly message: string;
|
|
1621
|
-
readonly cause?: import("effect-agent/failure-diagnostic").Diagnostic | undefined;
|
|
1636
|
+
readonly _tag: "ThreadNotMaterialized";
|
|
1637
|
+
readonly threadId: string;
|
|
1622
1638
|
} | {
|
|
1623
1639
|
readonly _tag: "AppendConflict";
|
|
1624
1640
|
readonly threadId: string;
|
|
@@ -1631,25 +1647,17 @@ export declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorde
|
|
|
1631
1647
|
readonly threadId: string;
|
|
1632
1648
|
readonly actualEpoch: number;
|
|
1633
1649
|
readonly attemptedEpoch: number;
|
|
1650
|
+
} | {
|
|
1651
|
+
readonly _tag: "DurableAlarmError";
|
|
1652
|
+
readonly operation: string;
|
|
1653
|
+
readonly message: string;
|
|
1654
|
+
readonly cause?: Schema.Json | undefined;
|
|
1634
1655
|
} | {
|
|
1635
1656
|
readonly _tag: "OperationDenied";
|
|
1636
1657
|
readonly operation: "abort" | "awaitSettlement" | "explain" | "observe" | "resolveApproval" | "resolveUnknown" | "retry" | "scanObligations" | "verify" | "wake";
|
|
1637
1658
|
readonly reason: string;
|
|
1638
1659
|
readonly threadId?: string | undefined;
|
|
1639
1660
|
readonly submissionId?: string | undefined;
|
|
1640
|
-
} | {
|
|
1641
|
-
readonly _tag: "AdmissionConflict";
|
|
1642
|
-
readonly threadId: string;
|
|
1643
|
-
readonly principal: string;
|
|
1644
|
-
readonly idempotencyKey: string;
|
|
1645
|
-
readonly existingInputDigest: string;
|
|
1646
|
-
readonly attemptedInputDigest: string;
|
|
1647
|
-
} | {
|
|
1648
|
-
readonly _tag: "AdmissionPolicyError";
|
|
1649
|
-
readonly reason: "occupied" | "refused" | "unavailable";
|
|
1650
|
-
readonly code: string;
|
|
1651
|
-
readonly cause?: import("effect-agent/failure-diagnostic").Diagnostic | undefined;
|
|
1652
|
-
readonly stack?: string | undefined;
|
|
1653
1661
|
} | {
|
|
1654
1662
|
readonly _tag: "AgentInputError";
|
|
1655
1663
|
readonly message: string;
|
|
@@ -1660,14 +1668,6 @@ export declare const encodeHostResponse: (input: AbortRecorded | ApprovalRecorde
|
|
|
1660
1668
|
} | {
|
|
1661
1669
|
readonly _tag: "DurableRuntimeFailpointError";
|
|
1662
1670
|
readonly location: "abort:after-intent" | "approval:after-request-append" | "approval:after-suspend" | "checkpoint:after-save" | "checkpoint:before-save" | "claim:after-claim" | "compaction:after-canonical-append" | "compaction:before-canonical-append" | "input:after-canonical-append" | "join:after-canonical-append" | "join:after-claim" | "policy:after-reservation-append" | "policy:before-reservation-append" | "resolve:after-intent" | "run:after-duration-append" | "run:after-start-append" | "run:before-duration-append" | "run:before-start-append" | "step:after-step-append" | "subagent:after-admit" | "subagent:after-child-abort-intent" | "subagent:after-child-ready" | "subagent:after-join-append" | "subagent:after-release" | "subagent:after-release-pending" | "subagent:after-request-append" | "subagent:after-reserve" | "subagent:after-sibling-settle" | "subagent:after-start-append" | "subagent:after-suspend" | "subagent:before-join-append" | "submit:after-admit" | "submit:after-materialize" | "terminalize:after-canonical-append" | "terminalize:after-reserve" | "tools:after-prepared-append" | "tools:after-unavailable-append" | "tools:before-prepared-append" | "tools:before-unavailable-append" | "turn:after-canonical-append" | "turn:after-response-append" | "turn:after-results-append" | "update:after-canonical-append" | "update:after-delivery-insert" | "update:before-canonical-append" | "update:before-delivery-insert" | "worker:after-completion-append" | "worker:after-origin-append" | "worker:after-report-append" | "worker:after-report-delivery" | "worker:after-source-append" | "worker:after-stop-append" | "worker:after-stop-seal" | "worker:after-subtree-append" | "worker:before-completion-append" | "worker:before-origin-append" | "worker:before-report-append" | "worker:before-report-delivery" | "worker:before-source-append" | "worker:before-stop-append" | "worker:before-stop-seal" | "worker:before-subtree-append";
|
|
1663
|
-
} | {
|
|
1664
|
-
readonly _tag: "SettlementConflict";
|
|
1665
|
-
readonly submissionId: string;
|
|
1666
|
-
readonly existingOutcome: "aborted" | "completed" | "failed";
|
|
1667
|
-
} | {
|
|
1668
|
-
readonly _tag: "JoinedToHost";
|
|
1669
|
-
readonly submissionId: string;
|
|
1670
|
-
readonly hostSubmissionId: string;
|
|
1671
1671
|
} | {
|
|
1672
1672
|
readonly _tag: "AdmissionLimitExceeded";
|
|
1673
1673
|
readonly limit: "database-bytes" | "input-bytes" | "queue-depth";
|
|
@@ -10,10 +10,10 @@ import { compileRegistrations } from "effect-agent/agent-registration";
|
|
|
10
10
|
import { ApprovalSuspensionError, DurableAgentRuntime, DurableRuntimeConfig, RecoveryReport } from "effect-agent/durable-agent-runtime";
|
|
11
11
|
import { SubmissionId, ThreadId } from "effect-agent/identifiers";
|
|
12
12
|
import { OperationAuthorizationRequest, OperationAuthorizer, OperationDenied, operationAuthorizerLayer } from "effect-agent/operation-authorizer";
|
|
13
|
-
import { AdmissionPolicyError, LedgerError, OwnershipLost, SettlementConflict, SubmissionLedger,
|
|
13
|
+
import { AdmissionPolicyError, LedgerError, OwnershipLost, SettlementConflict, SubmissionLedger, SubmissionLookupByKey } from "effect-agent/submission-ledger";
|
|
14
14
|
import { ThreadProjectionMaintenance } from "effect-agent/thread-projection-maintenance";
|
|
15
15
|
import { WakeScheduler } from "effect-agent/wake-scheduler";
|
|
16
|
-
import { DurableObject, DurableObjectState, WorkerEnvironment } from "effect-cf";
|
|
16
|
+
import { DurableObject, DurableObjectState, RpcTracing, WorkerEnvironment } from "effect-cf";
|
|
17
17
|
import { SqlClient } from "effect/unstable/sql/SqlClient";
|
|
18
18
|
import { PersistedJson, ProducerId } from "effect-agent/records";
|
|
19
19
|
import { BrowserCrypto } from "@effect/platform-browser";
|
|
@@ -29,7 +29,7 @@ import { doMessageDeliveryStoreLayer } from "@effect-agent/storage-cloudflare/do
|
|
|
29
29
|
import "@effect-agent/storage-cloudflare/do-storage-failpoint";
|
|
30
30
|
import { submissionLedgerLayer } from "@effect-agent/storage-cloudflare/do-submission-ledger";
|
|
31
31
|
import { storageConfigLayer, storageFailpointLayer, threadStoreLayer } from "@effect-agent/storage-cloudflare/do-thread-store";
|
|
32
|
-
import { ThreadPortTransport, executePortRequest, portTransportFailure, routedMessageDeliveryStoreLayer, routedSubmissionLedgerLayer, routedThreadStoreLayer } from "@effect-agent/storage-cloudflare/port-routing";
|
|
32
|
+
import { ThreadPortTransport, executePortRequest, makeLocalSubmissionLookup, portTransportFailure, routedMessageDeliveryStoreLayer, routedSubmissionLedgerLayer, routedThreadStoreLayer } from "@effect-agent/storage-cloudflare/port-routing";
|
|
33
33
|
import { MessageDeliveryDriver, MessageDeliveryError, MessageDeliveryStore } from "effect-agent/message-delivery";
|
|
34
34
|
import { CurrentToolFailureObserver, RunContextPreparationPassthrough, RunToolAuthorization, toolFailureObserverLayer } from "effect-agent/run-options";
|
|
35
35
|
import { ToolReconciler } from "effect-agent/tool-reconciler";
|
|
@@ -171,6 +171,8 @@ var ProgressWaitRegistry = class ProgressWaitRegistry extends Context.Service()(
|
|
|
171
171
|
* already Schema-encoded JSON, so the RPC boundary carries only structured-cloneable values;
|
|
172
172
|
* the protocol module stays transport-agnostic and fetch-with-JSON remains the documented
|
|
173
173
|
* fallback carrier.
|
|
174
|
+
* The namespace's optional `rpcTracing` setting uses the same transient trailing context
|
|
175
|
+
* as host calls; it never changes the encoded port envelope.
|
|
174
176
|
*
|
|
175
177
|
* Every delivery problem — stub construction, RPC rejection, overload, deploy-in-progress —
|
|
176
178
|
* surfaces as `PortTransportError` (preserving the platform stub's own `retryable` signal
|
|
@@ -179,7 +181,11 @@ var ProgressWaitRegistry = class ProgressWaitRegistry extends Context.Service()(
|
|
|
179
181
|
*/
|
|
180
182
|
const threadPortTransportLayer = Layer.effect(ThreadPortTransport)(Effect.gen(function* () {
|
|
181
183
|
const namespace = yield* ThreadObjectNamespace;
|
|
182
|
-
|
|
184
|
+
const { rpcTracing } = namespace;
|
|
185
|
+
return ThreadPortTransport.of({ call: Effect.fn(function* (threadId, request) {
|
|
186
|
+
const traceArgs = rpcTracing === void 0 ? [] : yield* RpcTracing.withRpcTraceContext([]);
|
|
187
|
+
return yield* callThreadObject(threadId, (target) => target.portCall(request, ...traceArgs), (cause) => portTransportFailure(threadId, cause)).pipe(Effect.provideService(ThreadObjectNamespace, namespace));
|
|
188
|
+
}, (effect, threadId) => rpcTracing === void 0 ? Effect.withSpan(effect, "CloudflarePortTransport.call", { attributes: { threadId } }) : RpcTracing.withRpcClientSpan(effect, rpcTracing, "portCall")) });
|
|
183
189
|
}));
|
|
184
190
|
//#endregion
|
|
185
191
|
//#region src/internal/layers.ts
|
|
@@ -343,10 +349,10 @@ const sharedLayer = (application, options = {}) => Layer.unwrap(Effect.gen(funct
|
|
|
343
349
|
})).pipe(Layer.provide(rawLocalPorts));
|
|
344
350
|
const portsEndpointLayer = Layer.effect(ThreadObjectPorts)(Effect.gen(function* () {
|
|
345
351
|
const local = yield* Effect.context();
|
|
346
|
-
const
|
|
352
|
+
const lookupSubmission = makeLocalSubmissionLookup({ ownsThread });
|
|
347
353
|
return ThreadObjectPorts.of({
|
|
348
354
|
handle: (request) => executePortRequest(request).pipe(Effect.provide(local)),
|
|
349
|
-
lookupSubmission: (submissionId) =>
|
|
355
|
+
lookupSubmission: (submissionId) => lookupSubmission(submissionId).pipe(Effect.provide(local))
|
|
350
356
|
});
|
|
351
357
|
})).pipe(Layer.provide(localPorts), Layer.provide(messageStore));
|
|
352
358
|
const routedPorts = Layer.mergeAll(routedSubmissionLedgerLayer({ ownsThread }), routedThreadStoreLayer({ ownsThread })).pipe(Layer.provide(localPorts), Layer.provide(threadPortTransportLayer));
|
|
@@ -398,6 +404,7 @@ const isMutatingPortRequest = (request) => {
|
|
|
398
404
|
case "LedgerResolveAdmission":
|
|
399
405
|
case "StoreReadPage":
|
|
400
406
|
case "StoreInspectTail":
|
|
407
|
+
case "StoreReadIdentity":
|
|
401
408
|
case "StoreCountPeerMessages":
|
|
402
409
|
case "StoreExport":
|
|
403
410
|
case "MessageDeliveryList": return false;
|
|
@@ -501,6 +508,7 @@ const requirePortThread = (request) => {
|
|
|
501
508
|
case "StoreAppend":
|
|
502
509
|
case "StoreReadPage":
|
|
503
510
|
case "StoreInspectTail":
|
|
511
|
+
case "StoreReadIdentity":
|
|
504
512
|
case "StoreCountPeerMessages":
|
|
505
513
|
case "StoreExport": return requireReceiptThread(request.request.threadId);
|
|
506
514
|
}
|
|
@@ -846,4 +854,4 @@ const make = (applicationLayer, options) => {
|
|
|
846
854
|
//#endregion
|
|
847
855
|
export { layer as C, layerInHost as E, ThreadObjectPorts as S, layerHostConfig as T, encodeAdminResponse as _, AdminVerifyRequest as a, portCall as b, RetryExecuted as c, VerifiedIntegrity as d, decodeAdminExplainRequest as f, decodeRetryCommand as g, decodeObligationThresholds as h, AdminResponse as i, ThreadObject_exports as l, decodeAdminVerifyRequest as m, AdminFailed as n, ExplainedRecovery as o, decodeAdminResponse as p, AdminFailure as r, ObligationsScanned as s, AdminExplainRequest as t, ThreadRpcOperation as u, handleRpc as v, layerConfig as w, submit as x, make as y };
|
|
848
856
|
|
|
849
|
-
//# sourceMappingURL=ThreadObject-
|
|
857
|
+
//# sourceMappingURL=ThreadObject-BkLV7hMd.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ThreadObject-BkLV7hMd.mjs","names":["EffectCfDurableObjectState","EffectCfDurableObject"],"sources":["../src/internal/message-delivery.ts","../src/internal/progress-wait.ts","../src/internal/transport.ts","../src/internal/layers.ts","../src/ThreadObject.ts"],"sourcesContent":["import { Clock, Context, Effect, Layer, Option, Ref, Semaphore } from \"effect\";\nimport { type ThreadId } from \"effect-agent/identifiers\";\nimport {\n MessageDeliveryDriver,\n MessageDeliveryError,\n MessageDeliveryStore,\n} from \"effect-agent/message-delivery\";\nimport { WakeScheduler } from \"effect-agent/wake-scheduler\";\n\nimport { DurableAlarmError, ThreadMessageDelivery, ThreadMutationGate } from \"../Alarm.ts\";\nimport { ThreadObjectPlacement } from \"../CloudflareBindings.ts\";\n\n/** Every write prearms its owner; the delivery due index owns its recovery deadline. */\nexport const guardedMessageDeliveryStoreLayer = Layer.effect(\n MessageDeliveryStore,\n Effect.gen(function* () {\n const store = yield* MessageDeliveryStore;\n const mutations = yield* ThreadMutationGate;\n const wakes = yield* WakeScheduler;\n const { ownsThread } = yield* ThreadObjectPlacement;\n // Reconstructed as unknown on every incarnation. The gate prevents a racing read from\n // caching an empty deadline across a write; SQL remains the recovery authority.\n const deadline = yield* Ref.make<number | null | undefined>(undefined);\n const cacheGate = yield* Semaphore.make(1);\n\n const local = <A, E>(\n owner: ThreadId | undefined,\n body: Effect.Effect<A, E>,\n ): Effect.Effect<A, E | MessageDeliveryError> =>\n owner === undefined || ownsThread(owner)\n ? body\n : Effect.fail(\n MessageDeliveryError.make({ reason: \"validation\", operation: \"message owner\" }),\n );\n\n const mutate = <A, E>(body: Effect.Effect<A, E>) =>\n mutations\n .withMutation(\n cacheGate.withPermit(Ref.set(deadline, undefined).pipe(Effect.andThen(body))),\n // A foreign receipt changing does not make the source ledger actionable. Keep the\n // prearm and producer gate so eviction and a racing pass cannot lose delivery work.\n { invalidatesRecovery: false },\n )\n .pipe(\n Effect.catchTag(\"DurableAlarmError\", () =>\n MessageDeliveryError.make({ reason: \"storage\", operation: \"prearm message delivery\" }),\n ),\n );\n\n const nextDeadline = cacheGate.withPermit(\n Effect.gen(function* () {\n const cached = yield* Ref.get(deadline);\n\n if (cached !== undefined) return cached;\n const current = yield* store.nextDeadline();\n\n yield* Ref.set(deadline, current);\n\n return current;\n }),\n );\n\n return MessageDeliveryStore.of({\n limits: store.limits,\n maxStoredValueBytes: store.maxStoredValueBytes,\n insert: (record) =>\n local(\n record.key.ownerThreadId,\n mutate(store.insert(record)).pipe(\n Effect.tap(() => wakes.notify(record.key.ownerThreadId)),\n ),\n ),\n get: (key) => local(key.ownerThreadId, store.get(key)),\n list: (request) => local(request.ownerThreadId, store.list(request)),\n change: (key, change) => local(key.ownerThreadId, mutate(store.change(key, change))),\n // Only the trusted physical-owner selection omits an owner. All returned keys still\n // pass placement validation before the driver may dispatch any of the wave.\n due: (nowMillis, limit, owner) =>\n local(owner, store.due(nowMillis, limit, owner)).pipe(\n Effect.filterOrFail(\n (keys) => keys.every((key) => ownsThread(key.ownerThreadId)),\n () => MessageDeliveryError.make({ reason: \"validation\", operation: \"message owner\" }),\n ),\n ),\n nextDeadline: (owner) =>\n local(owner, owner === undefined ? nextDeadline : store.nextDeadline(owner)),\n });\n }),\n);\n\n/** Message progress shares the native alarm slot without blocking source runtime work. */\nexport const threadMessageDeliveryLayer = Layer.effectContext(\n Effect.gen(function* () {\n const driver = yield* MessageDeliveryDriver;\n const store = yield* MessageDeliveryStore;\n\n const failure = (operation: string) => () =>\n DurableAlarmError.make({\n operation,\n message: \"Durable message recovery remains pending\",\n });\n\n const prepare = Effect.gen(function* () {\n const deadline = yield* store.nextDeadline();\n\n if (deadline === null || deadline > (yield* Clock.currentTimeMillis))\n return { timeoutMillis: 1, run: Effect.void };\n // The assembled driver has four permits: a wave is one parallel attempt window.\n const keys = yield* store.due(yield* Clock.currentTimeMillis, 4);\n const records = yield* Effect.forEach(keys, (key) => store.get(key));\n\n return {\n timeoutMillis: Math.max(\n 1,\n ...records.map((record) => record?.policy.attemptTimeoutMillis ?? 1),\n ),\n run: Effect.forEach(keys, (key) => driver.process(key), {\n concurrency: 4,\n discard: true,\n }).pipe(Effect.mapError(failure(\"dispatch message delivery\"))),\n };\n }).pipe(Effect.mapError(failure(\"prepare message delivery\")));\n\n return Context.make(ThreadMessageDelivery, {\n prepare,\n pendingDeadline: store\n .nextDeadline()\n .pipe(Effect.map(Option.fromNullishOr), Effect.mapError(failure(\"read message deadline\"))),\n });\n }),\n);\n","import { Context, Deferred, Effect, Layer, Ref, type Scope } from \"effect\";\n\n/** Cancellation tombstones are bounded hints, never durable authority. */\nconst MAX_CANCELLATION_TOMBSTONES = 1_024;\n\ntype ActiveRegistration = ReadonlySet<Deferred.Deferred<void>>;\ntype Registration = ActiveRegistration | \"cancelled\";\ntype Registrations = ReadonlyMap<string, Registration>;\n\n/**\n * Per-incarnation cancellation registry for long-lived progress RPCs. The public runtime owns\n * the actual wake registration; this host-only registry lets an interrupted Worker Effect ask\n * the Object to interrupt its scoped wait before the Worker execution context itself ends.\n */\nexport class ProgressWaitRegistry extends Context.Service<\n ProgressWaitRegistry,\n {\n /** Register a Scope-owned cancellation signal, observing any early cancel tombstone. */\n readonly subscribe: (\n waiterId: string,\n ) => Effect.Effect<Effect.Effect<void>, never, Scope.Scope>;\n /** Cancel every attempt and retain a bounded tombstone for later transport attempts. */\n readonly cancel: (waiterId: string) => Effect.Effect<void>;\n }\n>()(\"@effect-agent/platform-cloudflare/ProgressWaitRegistry\") {\n static readonly layer: Layer.Layer<ProgressWaitRegistry> = Layer.effect(\n ProgressWaitRegistry,\n Effect.gen(function* () {\n const registrations = yield* Ref.make<Registrations>(new Map());\n\n const remove = (waiterId: string, deferred: Deferred.Deferred<void>) =>\n Ref.update(registrations, (current) => {\n const existing = current.get(waiterId);\n\n if (existing === undefined || existing === \"cancelled\" || !existing.has(deferred)) {\n return current;\n }\n const next = new Map(current);\n const active = new Set(existing);\n\n active.delete(deferred);\n if (active.size === 0) {\n next.delete(waiterId);\n } else {\n next.set(waiterId, active);\n }\n\n return next;\n });\n\n const subscribe = Effect.fn(\"ProgressWaitRegistry.subscribe\")(\n (waiterId: string): Effect.Effect<Effect.Effect<void>, never, Scope.Scope> =>\n Effect.gen(function* () {\n const deferred = yield* Deferred.make<void>();\n\n yield* Effect.addFinalizer(() => remove(waiterId, deferred));\n\n const cancelled = yield* Ref.modify(registrations, (current) => {\n const existing = current.get(waiterId);\n const next = new Map(current);\n\n if (existing === \"cancelled\") {\n return [true, current] as const;\n }\n const active = new Set(existing ?? []);\n\n active.add(deferred);\n next.set(waiterId, active);\n\n return [false, next] as const;\n });\n\n return { cancelled, deferred };\n }).pipe(\n Effect.map(({ cancelled, deferred }) =>\n cancelled ? Effect.void : Deferred.await(deferred),\n ),\n ),\n );\n\n // Updating the registry and completing captured signals form one nonblocking operation;\n // interruption between them must not strand attempts removed from the active registry.\n const cancel = Effect.fn(\"ProgressWaitRegistry.cancel\")(function* (waiterId: string) {\n const waiters = yield* Ref.modify(\n registrations,\n (current): readonly [ReadonlyArray<Deferred.Deferred<void>>, Registrations] => {\n const existing = current.get(waiterId);\n\n if (existing === \"cancelled\") return [[], current] as const;\n const next = new Map(current);\n\n // A retry may arrive after an active attempt was cancelled. Retain the same\n // tombstone used for early cancellation, ordered by cancellation time.\n next.delete(waiterId);\n next.set(waiterId, \"cancelled\");\n let tombstones = 0;\n\n for (const registration of next.values()) {\n if (registration === \"cancelled\") tombstones += 1;\n }\n if (tombstones > MAX_CANCELLATION_TOMBSTONES) {\n for (const [id, registration] of next) {\n if (registration !== \"cancelled\") continue;\n next.delete(id);\n break;\n }\n }\n\n return [existing === undefined ? [] : [...existing], next] as const;\n },\n );\n\n yield* Effect.forEach(waiters, (waiter) => Deferred.succeed(waiter, undefined), {\n discard: true,\n });\n }, Effect.uninterruptible);\n\n return ProgressWaitRegistry.of({ subscribe, cancel });\n }),\n );\n}\n","import {\n ThreadPortTransport,\n portTransportFailure,\n} from \"@effect-agent/storage-cloudflare/port-routing\";\nimport { Effect, Layer } from \"effect\";\nimport type { ThreadId } from \"effect-agent/identifiers\";\nimport { RpcTracing } from \"effect-cf\";\n\nimport { callThreadObject, ThreadObjectNamespace } from \"../CloudflareBindings.ts\";\n\n/**\n * `ThreadPortTransport` over native Durable Object JS RPC (decision D-P6-3): one\n * `portCall(envelope)` on the stub of the Object that owns the addressed Thread\n * (`namespace.idFromName(threadId)` — the identity rule, plan §1.2). The envelopes are\n * already Schema-encoded JSON, so the RPC boundary carries only structured-cloneable values;\n * the protocol module stays transport-agnostic and fetch-with-JSON remains the documented\n * fallback carrier.\n * The namespace's optional `rpcTracing` setting uses the same transient trailing context\n * as host calls; it never changes the encoded port envelope.\n *\n * Every delivery problem — stub construction, RPC rejection, overload, deploy-in-progress —\n * surfaces as `PortTransportError` (preserving the platform stub's own `retryable` signal\n * when present) and NEVER as a fabricated answer: on `resolveAdmission` the routing layer\n * turns exactly this error into `AdmissionIndeterminate` (SUB-031).\n */\nexport const threadPortTransportLayer: Layer.Layer<\n ThreadPortTransport,\n never,\n ThreadObjectNamespace\n> = Layer.effect(ThreadPortTransport)(\n Effect.gen(function* () {\n const namespace = yield* ThreadObjectNamespace;\n const { rpcTracing } = namespace;\n\n return ThreadPortTransport.of({\n call: Effect.fn(\n function* (threadId: ThreadId, request: unknown) {\n const traceArgs =\n rpcTracing === undefined ? [] : yield* RpcTracing.withRpcTraceContext([]);\n\n return yield* callThreadObject(\n threadId,\n (target) => target.portCall(request, ...traceArgs),\n (cause) => portTransportFailure(threadId, cause),\n ).pipe(Effect.provideService(ThreadObjectNamespace, namespace));\n },\n (effect, threadId) =>\n rpcTracing === undefined\n ? Effect.withSpan(effect, \"CloudflarePortTransport.call\", {\n attributes: { threadId },\n })\n : RpcTracing.withRpcClientSpan(effect, rpcTracing, \"portCall\"),\n ),\n });\n }),\n);\n","import { doMessageDeliveryStoreLayer } from \"@effect-agent/storage-cloudflare/do-message-delivery-store\";\nimport {\n type DoStorageFailpointHandler,\n type DoStorageFailpoint,\n} from \"@effect-agent/storage-cloudflare/do-storage-failpoint\";\nimport { submissionLedgerLayer } from \"@effect-agent/storage-cloudflare/do-submission-ledger\";\nimport {\n threadStoreLayer,\n storageConfigLayer,\n storageFailpointLayer,\n type DoStorageInitializationError,\n type DoStorageOptions,\n} from \"@effect-agent/storage-cloudflare/do-thread-store\";\nimport {\n type PortRequest,\n type PortResponse,\n} from \"@effect-agent/storage-cloudflare/port-protocol\";\nimport {\n executePortRequest,\n makeLocalSubmissionLookup,\n routedMessageDeliveryStoreLayer,\n routedThreadStoreLayer,\n routedSubmissionLedgerLayer,\n} from \"@effect-agent/storage-cloudflare/port-routing\";\nimport { BrowserCrypto } from \"@effect/platform-browser\";\nimport { SqliteClient } from \"@effect/sql-sqlite-do\";\nimport {\n type Crypto,\n Cause,\n Context,\n Duration,\n Effect,\n Layer,\n Schema,\n Semaphore,\n type Option,\n} from \"effect\";\nimport {\n compileRegistrations,\n type AgentRegistration,\n type ResolvedBinding,\n} from \"effect-agent/agent-registration\";\nimport { type DigestError } from \"effect-agent/digest\";\nimport { DurableAgentRuntime, DurableRuntimeConfig } from \"effect-agent/durable-agent-runtime\";\nimport {\n DurableRuntimeFailpoint,\n type DurableRuntimeFailpointHandler,\n} from \"effect-agent/durable-failpoint\";\nimport { ThreadId, type SubmissionId } from \"effect-agent/identifiers\";\nimport {\n type MessageDeliveryStore,\n MessageDeliveryDriver,\n type MessageDeliveryError,\n} from \"effect-agent/message-delivery\";\nimport {\n operationAuthorizerLayer,\n type OperationAuthorizerService,\n} from \"effect-agent/operation-authorizer\";\nimport { type PreparedInputAdmission } from \"effect-agent/prepared-input-admission\";\nimport { ProducerId } from \"effect-agent/records\";\nimport {\n type RunContextPreparation,\n type RunCostEstimator,\n type RunToolFailureObserver,\n} from \"effect-agent/run-options\";\nimport {\n CurrentToolFailureObserver,\n RunContextPreparationPassthrough,\n RunToolAuthorization,\n toolFailureObserverLayer,\n} from \"effect-agent/run-options\";\nimport {\n LedgerError,\n SubmissionLedger,\n type SubmissionSnapshot,\n} from \"effect-agent/submission-ledger\";\nimport { ThreadProjectionMaintenance } from \"effect-agent/thread-projection-maintenance\";\nimport { ThreadStoreError, ThreadStore } from \"effect-agent/thread-store\";\nimport { ToolReconciler } from \"effect-agent/tool-reconciler\";\nimport { type WakeScheduler } from \"effect-agent/wake-scheduler\";\nimport { SqlClient } from \"effect/unstable/sql/SqlClient\";\n\nimport {\n ThreadMaintenance,\n ThreadMutationGate,\n ThreadPublication,\n publishCommitted,\n ThreadMaintenanceFailpoint,\n DurableAlarmService,\n type ThreadMaintenanceFailpointHandler,\n} from \"../Alarm.ts\";\nimport {\n ThreadObjectIdentity,\n ThreadObjectPlacement,\n DurableObjectContext,\n type ThreadObjectNamespace,\n} from \"../CloudflareBindings.ts\";\nimport {\n CLOUDFLARE_RUNTIME_DEFAULTS,\n CloudflareDurableRuntimeConfig,\n CloudflareDurableRuntimeConfigValue,\n CloudflarePlatformConfigError,\n} from \"../CloudflareConfig.ts\";\nimport { CloudflareThreadClient } from \"../CloudflareThreadClient.ts\";\nimport { cloudflareWakeSchedulerLayer } from \"../WakeScheduler.ts\";\nimport {\n guardedMessageDeliveryStoreLayer,\n threadMessageDeliveryLayer,\n} from \"./message-delivery.ts\";\nimport { cloudflarePreparedInputAdmissionLayer } from \"./prepared-admission.ts\";\nimport { ProgressWaitRegistry } from \"./progress-wait.ts\";\nimport { threadPortTransportLayer } from \"./transport.ts\";\n\n/**\n * Raw (unvalidated) construction options for `ThreadObject.make`, mirroring\n * `NodeDurableAgentRuntimeOptions`. Optional fields default to the documented production values\n * (`CLOUDFLARE_RUNTIME_DEFAULTS`); everything is schema-decoded into\n * `CloudflareDurableRuntimeConfigValue` before any resource opens (deployment §5 gate 1).\n */\nexport interface CloudflareDurableRuntimeOptions {\n readonly deploymentId: string;\n /** Head of the minted producer identity `{producerPrefix}:{threadId}`. */\n readonly producerPrefix: string;\n /** Milliseconds; default 30s (D5). */\n readonly ownershipLeaseDuration?: number | undefined;\n /** Milliseconds; default 100. */\n readonly alarmBackoffBase?: number | undefined;\n /** Failed/no-progress exponential backoff ceiling in milliseconds; default 5000. */\n readonly alarmBackoffCap?: number | undefined;\n /** Fallback scan cadence for newly dirty work in milliseconds; default 1000. */\n readonly wakeScanInterval?: number | undefined;\n /** Milliseconds; default 500. */\n readonly settlementPollInterval?: number | undefined;\n /** Milliseconds; default 10000. */\n readonly leaseRenewalInterval?: number | undefined;\n /** Milliseconds; default 500. */\n readonly abortPollInterval?: number | undefined;\n /** Deployment-owned pricing authority used by durable cost budgets and settlements. */\n readonly estimateCostMicrousd?: RunCostEstimator | undefined;\n /** Closed trusted Tool failure reporting. Omission masks ambient observers at construction. */\n readonly toolFailureObserver?: RunToolFailureObserver | undefined;\n /** Milliseconds; default 25. */\n readonly observationPollInterval?: number | undefined;\n /** Whole disposable projection wave in milliseconds, 1..300000; default 30000. */\n readonly projectionDispatchTimeoutMillis?: number | undefined;\n /** Bytes; default just under the 2 MB platform value limit. */\n readonly maxStoredValueBytes?: number | undefined;\n /** Default false. */\n readonly verifyOnOpen?: boolean | undefined;\n /** Nonterminal Submissions per lane before admission refuses; default 256. */\n readonly maxQueueDepthPerLane?: number | undefined;\n /** Encoded input bytes per Submission; default = the stored-value bound. */\n readonly maxInputBytes?: number | undefined;\n /** `ctx.storage.sql.databaseSize` ceiling at admission; default 9 GB (10 GB platform cap). */\n readonly maxDatabaseBytes?: number | undefined;\n /**\n * Durable Object storage fault injection (`ledger:*` / `append:*` locations). Handlers are\n * constructed per incarnation WITH the live `DurableObjectState`, so eviction harnesses can\n * map an armed hit to `ctx.abort()` — the platform's real failure mode. Default none.\n */\n readonly storageFailpoint?: ((ctx: DurableObjectState) => DoStorageFailpointHandler) | undefined;\n /** Coordinator fault injection (`submit:*` / `terminalize:*` locations); default none. */\n readonly runtimeFailpoint?:\n | ((ctx: DurableObjectState) => DurableRuntimeFailpointHandler)\n | undefined;\n /** Thread-maintenance generation/alarm fault injection; default none. */\n readonly maintenanceFailpoint?:\n | ((ctx: DurableObjectState) => ThreadMaintenanceFailpointHandler)\n | undefined;\n /** Host-supplied fail-closed authorization policy; defaults to service possession. */\n readonly operationAuthorizer?: OperationAuthorizerService | undefined;\n /**\n * Reconciliation policy consulted for open ordinary Tool Calls before an Unknown Outcome\n * is recorded (durability §10, DUR-009). Defaults to the fail-closed\n * `ToolReconciler.uncertain`.\n */\n readonly toolReconciler?: Layer.Layer<ToolReconciler> | undefined;\n}\n\n/** Services supplied before the application graph is built, including its dependencies. */\nexport type CloudflareBootstrapServices =\n | CloudflareDurableRuntimeConfig\n | ThreadObjectIdentity\n | ThreadObjectPlacement\n | DurableRuntimeConfig\n | Crypto.Crypto\n | DoStorageFailpoint\n | DurableRuntimeFailpoint\n | ThreadMaintenanceFailpoint\n | RunContextPreparation\n | RunToolAuthorization\n | ToolReconciler;\n\n/** Every construction failure of the assembled Cloudflare durable runtime stack. */\nexport type CloudflareDurableRuntimeInitializationError =\n | CloudflarePlatformConfigError\n | DigestError\n | MessageDeliveryError\n | DoStorageInitializationError;\n\n/**\n * The services `ThreadObject.layer` provides, including its single owner SQL client.\n * Its Context also supplies ThreadMessageDelivery (a defaulted Reference, with no required R)\n * so application-composed maintenance retains the same native message recovery capability.\n */\nexport type CloudflareDurableRuntimeServices =\n | DurableAgentRuntime\n | SubmissionLedger\n | ThreadStore\n | MessageDeliveryStore\n | WakeScheduler\n | DurableAlarmService\n | ThreadMaintenance\n | ThreadMutationGate\n | ThreadPublication\n | ThreadProjectionMaintenance\n | ThreadObjectPorts\n | ProgressWaitRegistry\n | SqlClient;\n\n/**\n * Owner-side execution port for a `portCall` request the wire endpoint has already decoded.\n * It executes against THIS Object's LOCAL port facets — never the routed decorators, so a\n * request cannot bounce between Objects — and returns the typed response for the endpoint to\n * encode.\n */\nexport class ThreadObjectPorts extends Context.Service<\n ThreadObjectPorts,\n {\n readonly handle: (request: PortRequest) => Effect.Effect<PortResponse>;\n /**\n * Local-only lookup: encoded identities and returned rows must belong to this physical\n * owner. Addressed RPCs additionally validate the exact logical Thread.\n */\n readonly lookupSubmission: (\n submissionId: SubmissionId,\n ) => Effect.Effect<Option.Option<SubmissionSnapshot>, LedgerError>;\n }\n>()(\"@effect-agent/platform-cloudflare/ThreadObjectPorts\") {}\n\nconst decodeConfigValue = Schema.decodeUnknownEffect(CloudflareDurableRuntimeConfigValue);\nconst decodeThreadId = Schema.decodeUnknownEffect(ThreadId);\nconst decodeProducerId = Schema.decodeUnknownEffect(ProducerId);\n\nconst configFromOptions = (\n options: CloudflareDurableRuntimeOptions,\n): Effect.Effect<CloudflareDurableRuntimeConfigValue, CloudflarePlatformConfigError> =>\n decodeConfigValue({\n deploymentId: options.deploymentId,\n producerPrefix: options.producerPrefix,\n ownershipLeaseDuration:\n options.ownershipLeaseDuration ?? CLOUDFLARE_RUNTIME_DEFAULTS.ownershipLeaseDuration,\n alarmBackoffBase: options.alarmBackoffBase ?? CLOUDFLARE_RUNTIME_DEFAULTS.alarmBackoffBase,\n alarmBackoffCap: options.alarmBackoffCap ?? CLOUDFLARE_RUNTIME_DEFAULTS.alarmBackoffCap,\n wakeScanInterval: options.wakeScanInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.wakeScanInterval,\n settlementPollInterval:\n options.settlementPollInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.settlementPollInterval,\n leaseRenewalInterval:\n options.leaseRenewalInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.leaseRenewalInterval,\n abortPollInterval: options.abortPollInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.abortPollInterval,\n observationPollInterval:\n options.observationPollInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.observationPollInterval,\n projectionDispatchTimeoutMillis:\n options.projectionDispatchTimeoutMillis ??\n CLOUDFLARE_RUNTIME_DEFAULTS.projectionDispatchTimeoutMillis,\n maxStoredValueBytes:\n options.maxStoredValueBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxStoredValueBytes,\n verifyOnOpen: options.verifyOnOpen ?? CLOUDFLARE_RUNTIME_DEFAULTS.verifyOnOpen,\n limits: {\n maxQueueDepthPerLane:\n options.maxQueueDepthPerLane ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxQueueDepthPerLane,\n maxInputBytes: Math.min(\n options.maxInputBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxInputBytes,\n options.maxStoredValueBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxStoredValueBytes,\n ),\n maxDatabaseBytes: options.maxDatabaseBytes ?? CLOUDFLARE_RUNTIME_DEFAULTS.maxDatabaseBytes,\n },\n }).pipe(\n Effect.mapError((error) =>\n CloudflarePlatformConfigError.make({\n message: `Invalid Cloudflare durable runtime configuration: ${error.message}`,\n cause: error,\n }),\n ),\n );\n\n/**\n * The Thread this Object owns, from the Object identity rule (plan §1.2): Thread\n * Objects are addressed exclusively by `idFromName(threadId)`, so `ctx.id.name` IS the\n * Thread ID. An unnamed Object (from `newUniqueId`) is a deployment error, not a lane.\n */\nconst threadIdFromState = (\n ctx: DurableObjectState,\n): Effect.Effect<ThreadId, CloudflarePlatformConfigError> =>\n ctx.id.name === undefined\n ? Effect.fail(\n CloudflarePlatformConfigError.make({\n message:\n \"This Durable Object was not created via idFromName(threadId); Thread \" +\n \"Objects must be addressed by their Thread identity (plan §1.2).\",\n }),\n )\n : decodeThreadId(ctx.id.name).pipe(\n Effect.mapError((error) =>\n CloudflarePlatformConfigError.make({\n message: `The Durable Object name is not a valid ThreadId: ${error.message}`,\n cause: error,\n }),\n ),\n );\n\n/**\n * Validate deployment settings and derive services before building application dependencies.\n * The native class factory builds this Layer inside its constructor gate. Custom Effect hosts\n * can provide it around the complete application Layer with the native context already supplied.\n */\nconst runtimeConfigLayer = (\n options: CloudflareDurableRuntimeOptions,\n producerId: ProducerId,\n): Layer.Layer<\n Exclude<CloudflareBootstrapServices, ThreadObjectIdentity | ThreadObjectPlacement>,\n CloudflarePlatformConfigError,\n DurableObjectContext\n> =>\n Layer.unwrap(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n const config = yield* configFromOptions(options);\n\n return Layer.mergeAll(\n Layer.succeed(CloudflareDurableRuntimeConfig, config),\n DurableRuntimeConfig.layer({\n deploymentId: config.deploymentId,\n producerId,\n settlementPollInterval: Duration.millis(config.settlementPollInterval),\n leaseRenewalInterval: Duration.millis(config.leaseRenewalInterval),\n abortPollInterval: Duration.millis(config.abortPollInterval),\n ...(options.estimateCostMicrousd === undefined\n ? {}\n : { estimateCostMicrousd: options.estimateCostMicrousd }),\n }),\n BrowserCrypto.layer,\n storageFailpointLayer({ storage: ctx.storage, failpoint: options.storageFailpoint?.(ctx) }),\n options.runtimeFailpoint === undefined\n ? DurableRuntimeFailpoint.layer\n : Layer.succeed(DurableRuntimeFailpoint, { hit: options.runtimeFailpoint(ctx) }),\n options.maintenanceFailpoint === undefined\n ? ThreadMaintenanceFailpoint.layer\n : Layer.succeed(ThreadMaintenanceFailpoint, {\n hit: options.maintenanceFailpoint(ctx),\n }),\n options.toolReconciler ?? ToolReconciler.uncertain,\n options.operationAuthorizer === undefined\n ? Layer.empty\n : operationAuthorizerLayer(options.operationAuthorizer),\n options.toolFailureObserver === undefined\n ? Layer.succeed(CurrentToolFailureObserver, undefined)\n : toolFailureObserverLayer(options.toolFailureObserver),\n RunContextPreparationPassthrough,\n RunToolAuthorization.allowAll,\n );\n }),\n );\n\nconst producerIdentity = (prefix: string, owner: string) =>\n decodeProducerId(`${prefix}:${owner}`).pipe(\n Effect.mapError((error) =>\n CloudflarePlatformConfigError.make({\n message: `The minted producer identity is invalid: ${error.message}`,\n cause: error,\n }),\n ),\n );\n\n/** Native one-Thread configuration; retains its existing producer and logical identities. */\nexport const layerConfig = (\n options: CloudflareDurableRuntimeOptions,\n): Layer.Layer<CloudflareBootstrapServices, CloudflarePlatformConfigError, DurableObjectContext> =>\n Layer.unwrap(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n const threadId = yield* threadIdFromState(ctx);\n const producerId = yield* producerIdentity(options.producerPrefix, threadId);\n\n return Layer.mergeAll(\n runtimeConfigLayer(options, producerId),\n Layer.succeed(ThreadObjectIdentity, { threadId, producerId }),\n Layer.succeed(ThreadObjectPlacement, { ownsThread: (target) => target === threadId }),\n );\n }),\n );\n\n/**\n * Configuration for an application Object owning several logical Threads. The producer is\n * the stable physical Object. No logical identity is installed globally: handleRpc binds and\n * validates it per request using the placement guard and this actual runtime producer.\n */\nexport const layerHostConfig = (\n options: CloudflareDurableRuntimeOptions,\n ownsThread: (threadId: ThreadId) => boolean,\n): Layer.Layer<\n Exclude<CloudflareBootstrapServices, ThreadObjectIdentity>,\n CloudflarePlatformConfigError,\n DurableObjectContext\n> =>\n Layer.unwrap(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n const producerId = yield* producerIdentity(options.producerPrefix, ctx.id.toString());\n\n return Layer.merge(\n runtimeConfigLayer(options, producerId),\n Layer.succeed(ThreadObjectPlacement, { ownsThread }),\n );\n }),\n );\n\nexport interface ThreadPublicationOptions<E = never, R = never, P = never> {\n /**\n * Optional host outbox consumer, built once per incarnation with RAW LOCAL ThreadStore and\n * SubmissionLedger services. Yield DurableObjectContext and ThreadObjectIdentity for native\n * bindings and identity. Initialization is local-only, inside the constructor gate; setup\n * errors and additional requirements remain in the returned Layer. Layer.effect owns Scope.\n * Canonical appends and durable approval, abort and unknown-resolution intents invalidate\n * publication after commit. Custom host facts must use ThreadMaintenance.withMutation.\n */\n readonly publication?: Layer.Layer<ThreadPublication, E, R>;\n /**\n * Disposable index maintenance, built once with the raw local ThreadStore and owner\n * SqlClient. Additional services P are exposed by the returned Layer, allowing Tool\n * handlers and maintenance to share one index instance. Construction is local-only.\n * Live committed batches run before append returns; bounded backfill uses the native\n * alarm without delaying execution behind projection backlog.\n */\n readonly projection?: Layer.Layer<ThreadProjectionMaintenance | P, E, R>;\n}\n\n/**\n * Register typed Agents and version declarations. Hashing and dependency capture happen in\n * this Layer's Scope, after application Layers have been provided. Every Agent's instruction,\n * Tool, Schema, and model requirements remain visible until satisfied by Layer composition.\n * Use Layer.unwrap for registration values that need effectful application setup.\n */\nconst registeredLayer = <\n const Entries extends ReadonlyArray<AgentRegistration>,\n E = never,\n R = never,\n>(\n registrations: Entries,\n options: ThreadPublicationOptions<E, R> = {},\n) =>\n Layer.unwrap(\n Effect.map(compileRegistrations(registrations), (bindings) => boundLayer(bindings, options)),\n );\n\n/** Preserve additional index services only when a projection Layer is actually supplied. */\nexport function layer<\n const Entries extends ReadonlyArray<AgentRegistration>,\n E = never,\n R = never,\n P = never,\n PE = never,\n PR = never,\n>(\n registrations: Entries,\n options: Omit<ThreadPublicationOptions<E, R>, \"projection\"> & {\n readonly projection: Layer.Layer<ThreadProjectionMaintenance | P, PE, PR>;\n },\n): Layer.Layer<\n Layer.Success<ReturnType<typeof registeredLayer<Entries, E | PE, R | PR>>> | P,\n Layer.Error<ReturnType<typeof registeredLayer<Entries, E | PE, R | PR>>>,\n Layer.Services<ReturnType<typeof registeredLayer<Entries, E | PE, R | PR>>>\n>;\n\nexport function layer<const Entries extends ReadonlyArray<AgentRegistration>, E = never, R = never>(\n registrations: Entries,\n options?: ThreadPublicationOptions<E, R>,\n): ReturnType<typeof registeredLayer<Entries, E, R>>;\n\nexport function layer<const Entries extends ReadonlyArray<AgentRegistration>, E = never, R = never>(\n registrations: Entries,\n options: ThreadPublicationOptions<E, R> = {},\n) {\n return registeredLayer(registrations, options);\n}\n\nexport function layerFromBindings<E = never, R = never, P = never, PE = never, PR = never>(\n bindings: ReadonlyArray<ResolvedBinding>,\n options: Omit<ThreadPublicationOptions<E, R>, \"projection\"> & {\n readonly projection: Layer.Layer<ThreadProjectionMaintenance | P, PE, PR>;\n },\n): Layer.Layer<\n CloudflareDurableRuntimeServices | P,\n Layer.Error<ReturnType<typeof boundLayer<E | PE, R | PR>>>,\n Layer.Services<ReturnType<typeof boundLayer<E | PE, R | PR>>>\n>;\n\nexport function layerFromBindings<E = never, R = never>(\n bindings: ReadonlyArray<ResolvedBinding>,\n options?: ThreadPublicationOptions<E, R>,\n): ReturnType<typeof boundLayer<E, R>>;\n\nexport function layerFromBindings(\n bindings: ReadonlyArray<ResolvedBinding>,\n): ReturnType<typeof boundLayer<never, never>>;\n\nexport function layerFromBindings<E = never, R = never>(\n bindings: ReadonlyArray<ResolvedBinding>,\n options: ThreadPublicationOptions<E, R> = {},\n) {\n return boundLayer(bindings, options);\n}\n\n/**\n * Assemble the durable runtime from already-resolved Agent Bindings.\n * Use `ThreadObject.layer` to compile typed Agent registrations instead.\n * Supply host services through `ThreadObject.make` or `ThreadObject.layerConfig` and\n * the Durable Object context and namespace Layers when composing a custom host.\n */\nconst boundLayer = <E = never, R = never>(\n bindings: ReadonlyArray<ResolvedBinding>,\n options: ThreadPublicationOptions<E, R> = {},\n): Layer.Layer<\n CloudflareDurableRuntimeServices,\n DoStorageInitializationError | MessageDeliveryError | E,\n | DurableObjectContext\n | ThreadObjectNamespace\n | CloudflareBootstrapServices\n | Exclude<R, ThreadStore | SubmissionLedger | SqlClient>\n> =>\n Layer.unwrap(\n Effect.map(DurableObjectContext, ({ ctx }) =>\n sharedLayer(DurableAgentRuntime.layerWithBindings(bindings), options).pipe(\n Layer.provideMerge(SqliteClient.layer({ storage: ctx.storage })),\n ),\n ),\n );\n\n/**\n * Build the application runtime over the existing owner SqlClient and native ports, then\n * assemble its one maintenance coordinator. The application may acquire its Bindings from\n * those ports and expose extra services, including ThreadHostMaintenance. It must not acquire\n * another runtime stack or require ThreadMaintenance while constructing this Layer.\n * Supply layerHostConfig and deterministic placement; dispatch addressed ingress with handleRpc.\n */\nexport function layerInHost<A, E, R, P = never, PE = never, PR = never>(\n application: Layer.Layer<DurableAgentRuntime | A, E, R>,\n options: Omit<ThreadPublicationOptions<PE, PR>, \"projection\"> & {\n readonly projection: Layer.Layer<ThreadProjectionMaintenance | P, PE, PR>;\n },\n): Layer.Layer<\n CloudflareDurableRuntimeServices | A | P,\n Layer.Error<ReturnType<typeof sharedLayer<A, E, R, PE, PR>>>,\n Layer.Services<ReturnType<typeof sharedLayer<A, E, Exclude<R, P>, PE, PR>>>\n>;\n\nexport function layerInHost<A, E, R, PE = never, PR = never>(\n application: Layer.Layer<DurableAgentRuntime | A, E, R>,\n options?: ThreadPublicationOptions<PE, PR>,\n): ReturnType<typeof sharedLayer<A, E, R, PE, PR>>;\n\nexport function layerInHost<A, E, R, PE = never, PR = never>(\n application: Layer.Layer<DurableAgentRuntime | A, E, R>,\n options: ThreadPublicationOptions<PE, PR> = {},\n) {\n return sharedLayer(application, options);\n}\n\ntype HostRuntimeServices = Exclude<\n CloudflareDurableRuntimeServices,\n DurableAgentRuntime | ThreadMaintenance\n>;\n\nconst sharedLayer = <A, E, R, PE = never, PR = never>(\n application: Layer.Layer<DurableAgentRuntime | A, E, R>,\n options: ThreadPublicationOptions<PE, PR> = {},\n): Layer.Layer<\n CloudflareDurableRuntimeServices | A,\n DoStorageInitializationError | MessageDeliveryError | E | PE,\n | DurableObjectContext\n | ThreadObjectNamespace\n | Exclude<CloudflareBootstrapServices, ThreadObjectIdentity>\n | SqlClient\n | Exclude<R, HostRuntimeServices | PreparedInputAdmission>\n | Exclude<PR, ThreadStore | SubmissionLedger | SqlClient>\n> =>\n Layer.unwrap(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n const config = yield* CloudflareDurableRuntimeConfig;\n const { ownsThread } = yield* ThreadObjectPlacement;\n\n const storageOptions: DoStorageOptions = {\n storage: ctx.storage,\n observationPollInterval: config.observationPollInterval,\n ownershipLeaseDuration: config.ownershipLeaseDuration,\n maxStoredValueBytes: config.maxStoredValueBytes,\n verifyOnOpen: config.verifyOnOpen,\n };\n\n const infrastructure = Layer.mergeAll(\n storageConfigLayer(storageOptions),\n Layer.effect(SqlClient)(SqlClient),\n );\n\n // The same local ports serve routed decorators and owner-side RPC execution.\n // The RPC executor must never receive routed ports and bounce requests between Objects.\n const rawLocalPorts = Layer.mergeAll(threadStoreLayer, submissionLedgerLayer).pipe(\n Layer.provide(infrastructure),\n );\n\n const base = Layer.mergeAll(DurableAlarmService.layer, ProgressWaitRegistry.layer);\n const wakes = cloudflareWakeSchedulerLayer.pipe(Layer.provide(base));\n\n const messageStore = guardedMessageDeliveryStoreLayer.pipe(\n Layer.provide(doMessageDeliveryStoreLayer().pipe(Layer.provide(infrastructure))),\n Layer.provide(wakes),\n );\n\n const messageRecovery = threadMessageDeliveryLayer.pipe(\n // Four parallel attempts per wave. Native completion stops new wake-driven waves;\n // retained retry deadlines schedule future alarms.\n Layer.provide(MessageDeliveryDriver.layer({ batchSize: 4, concurrency: 4 })),\n Layer.provide(cloudflarePreparedInputAdmissionLayer),\n Layer.provide(CloudflareThreadClient.layer),\n Layer.provide(messageStore),\n Layer.provide(wakes),\n );\n\n const publication = (options.publication ?? ThreadPublication.layer).pipe(\n Layer.provide(Layer.mergeAll(rawLocalPorts, Layer.effect(SqlClient)(SqlClient))),\n );\n\n const projection = (options.projection ?? ThreadProjectionMaintenance.layer).pipe(\n Layer.provide(Layer.mergeAll(rawLocalPorts, Layer.effect(SqlClient)(SqlClient))),\n );\n\n const localPorts =\n options.publication === undefined && options.projection === undefined\n ? rawLocalPorts\n : Layer.effectContext(\n Effect.gen(function* () {\n const store = yield* ThreadStore;\n const ledger = yield* SubmissionLedger;\n const mutations = yield* ThreadMutationGate;\n const index = yield* ThreadProjectionMaintenance;\n const publish = yield* Effect.context<ThreadPublication>();\n const afterCommit = publishCommitted.pipe(Effect.provide(publish));\n // A later append cannot mistake its still-projecting predecessor for old backlog.\n // Publication remains outside this local source/index critical section.\n const sourceCommits = yield* Semaphore.make(1);\n\n // Every runtime-owned producer prearms too: a crash between commit and invalidation\n // leaves a NEW, uncertified generation. Source errors keep their native port types.\n const observedStore = ThreadStore.of({\n ...store,\n append: (request) =>\n mutations\n .withMutation(\n sourceCommits\n .withPermit(\n store\n .append(request)\n .pipe(\n Effect.tap((result) =>\n index\n .applyCommitted(request, result)\n .pipe(\n Effect.catchCause((cause) =>\n Cause.hasInterrupts(cause)\n ? Effect.interrupt\n : Effect.logError(\n \"Thread projection deferred after source commit\",\n cause,\n ),\n ),\n ),\n ),\n ),\n )\n .pipe(Effect.tap(() => afterCommit)),\n )\n .pipe(\n Effect.catchTag(\"DurableAlarmError\", (cause) =>\n ThreadStoreError.make({\n operation: \"prearm publication append\",\n message: cause.message,\n cause,\n }),\n ),\n ),\n });\n\n const observeIntent = <A, Failure>(body: Effect.Effect<A, Failure>) =>\n mutations.withMutation(body.pipe(Effect.tap(() => afterCommit))).pipe(\n Effect.catchTag(\"DurableAlarmError\", (cause) =>\n LedgerError.make({\n operation: \"prearm publication intent\",\n message: \"The publication generation could not be armed\",\n cause,\n }),\n ),\n );\n\n const stopWorker = ledger.stopWorker;\n\n return Context.make(ThreadStore, observedStore).pipe(\n Context.add(SubmissionLedger, {\n ...ledger,\n recordApprovalDecision: (request) =>\n observeIntent(ledger.recordApprovalDecision(request)),\n ...(stopWorker === undefined\n ? {}\n : {\n stopWorker: (request: Parameters<NonNullable<typeof stopWorker>>[0]) =>\n observeIntent(stopWorker(request)),\n }),\n requestAbort: (request) => observeIntent(ledger.requestAbort(request)),\n recordUnknownResolution: (request) =>\n observeIntent(ledger.recordUnknownResolution(request)),\n }),\n );\n }),\n ).pipe(Layer.provide(rawLocalPorts));\n\n const portsEndpointLayer = Layer.effect(ThreadObjectPorts)(\n Effect.gen(function* () {\n const local = yield* Effect.context<\n SubmissionLedger | ThreadStore | MessageDeliveryStore\n >();\n\n const lookupSubmission = makeLocalSubmissionLookup({ ownsThread });\n\n return ThreadObjectPorts.of({\n handle: (request) => executePortRequest(request).pipe(Effect.provide(local)),\n lookupSubmission: (submissionId) =>\n lookupSubmission(submissionId).pipe(Effect.provide(local)),\n });\n }),\n ).pipe(Layer.provide(localPorts), Layer.provide(messageStore));\n\n const routedPorts = Layer.mergeAll(\n routedSubmissionLedgerLayer({ ownsThread }),\n routedThreadStoreLayer({ ownsThread }),\n ).pipe(Layer.provide(localPorts), Layer.provide(threadPortTransportLayer));\n\n const routedMessages = routedMessageDeliveryStoreLayer({ ownsThread }).pipe(\n Layer.provide(messageStore),\n Layer.provide(threadPortTransportLayer),\n );\n\n const runtimeStack = application.pipe(\n Layer.provide(\n cloudflarePreparedInputAdmissionLayer.pipe(Layer.provide(CloudflareThreadClient.layer)),\n ),\n Layer.provideMerge(routedMessages),\n Layer.provideMerge(routedPorts),\n Layer.provideMerge(wakes),\n Layer.provideMerge(base),\n Layer.provideMerge(portsEndpointLayer),\n );\n\n return Layer.mergeAll(\n runtimeStack,\n ThreadMaintenance.layer.pipe(Layer.provide(runtimeStack), Layer.provide(messageRecovery)),\n portsEndpointLayer,\n routedMessages,\n messageRecovery,\n ).pipe(\n Layer.provideMerge(publication),\n Layer.provideMerge(projection),\n Layer.provideMerge(ThreadMutationGate.layer),\n Layer.provideMerge(infrastructure),\n );\n }),\n );\n","import {\n decodePortRequest,\n encodePortResponse,\n LedgerLookupResult,\n PortFailed,\n PortProtocolError,\n PortSucceeded,\n type PortRequest,\n type PortResponse,\n} from \"@effect-agent/storage-cloudflare/port-protocol\";\nimport { Effect, Layer, Option, Schema, Stream } from \"effect\";\nimport {\n IntegrityReport,\n ObligationReport,\n ObligationThresholds,\n RecoveryExplanation,\n RetryCommand,\n RetryRefused,\n} from \"effect-agent/admin\";\nimport { DigestError } from \"effect-agent/digest\";\nimport {\n ApprovalSuspensionError,\n DurableAgentRuntime,\n DurableRuntimeConfig,\n RecoveryReport,\n type DurableSubmitAgent,\n} from \"effect-agent/durable-agent-runtime\";\nimport { DurableRuntimeFailpointError } from \"effect-agent/durable-failpoint\";\nimport { type AgentId, type ThreadId } from \"effect-agent/identifiers\";\nimport { SubmissionId } from \"effect-agent/identifiers\";\nimport {\n OperationAuthorizationRequest,\n OperationAuthorizer,\n OperationDenied,\n} from \"effect-agent/operation-authorizer\";\nimport { PersistedJson } from \"effect-agent/records\";\nimport { RunJournalError } from \"effect-agent/run-journal\";\nimport {\n AdmissionPolicyError,\n LedgerError,\n OwnershipLost,\n SettlementConflict,\n SubmissionLedger,\n SubmissionLookupByKey,\n} from \"effect-agent/submission-ledger\";\nimport {\n AppendConflict,\n ThreadNotMaterialized,\n ThreadRead,\n ThreadStore,\n ThreadStoreError,\n FenceRejected,\n} from \"effect-agent/thread-store\";\nimport { WakeScheduler } from \"effect-agent/wake-scheduler\";\nimport {\n DurableObject as EffectCfDurableObject,\n DurableObjectState as EffectCfDurableObjectState,\n WorkerEnvironment,\n} from \"effect-cf\";\n\nimport {\n ThreadMaintenance,\n DurableAlarmError,\n DurableAlarmService,\n ThreadMutationGate,\n publishCommitted,\n type MaintenancePassFailure,\n} from \"./Alarm.ts\";\nimport {\n ThreadObjectIdentity,\n ThreadObjectPlacement,\n DurableObjectContext,\n ThreadObjectNamespace,\n threadNamespaceFromEnv,\n type CloudflareBindingError,\n} from \"./CloudflareBindings.ts\";\nimport { AdmissionLimitExceeded, CloudflareDurableRuntimeConfig } from \"./CloudflareConfig.ts\";\nimport {\n AbortRecorded,\n ApprovalRecorded,\n HostFailed,\n HostProtocolError,\n ObservedPage,\n ProgressObserved,\n ProgressCancelled,\n SettlementReached,\n SubmissionStatusResponse,\n SubmitSucceeded,\n UnknownResolutionRecorded,\n boundHostDiagnostic,\n decodeAbortCommand,\n decodeAwaitProgressRequest,\n decodeCancelProgressRequest,\n decodeApprovalDecisionCommand,\n decodeObservePageRequest,\n decodeReceipt,\n decodeSubmitRequest,\n decodeUnknownResolutionCommand,\n encodeHostResponse,\n type HostFailure,\n type HostResponse,\n type SubmitRequest,\n} from \"./CloudflareThreadClient.ts\";\nimport {\n layerConfig,\n ThreadObjectPorts,\n type CloudflareDurableRuntimeInitializationError,\n type CloudflareDurableRuntimeOptions,\n type CloudflareDurableRuntimeServices,\n type CloudflareBootstrapServices,\n} from \"./internal/layers.ts\";\nimport { ProgressWaitRegistry } from \"./internal/progress-wait.ts\";\n\nexport {\n layer,\n layerConfig,\n layerHostConfig,\n layerInHost,\n ThreadObjectPorts,\n type ThreadPublicationOptions as PublicationOptions,\n type CloudflareDurableRuntimeOptions as RuntimeOptions,\n type CloudflareDurableRuntimeServices as Services,\n type CloudflareDurableRuntimeInitializationError as InitializationError,\n type CloudflareBootstrapServices as BootstrapServices,\n} from \"./internal/layers.ts\";\n\n/**\n * `ThreadObject.make(application, options)` — the Thread Durable Object\n * (plan §1.4,\n * D-P6-1): a factory returning a class that applications export from their Worker entry.\n * One SQLite-backed Object per Thread is the serialized owner (durability §6); the\n * Object never runs `runResolvedWorker`'s infinite loop — each ingress event or alarm runs\n * ONE bounded maintenance event with selected-Thread recovery and old cleanup, and the persisted alarm\n * (the single multiplexed slot, D-P6-2) finishes accepted work across evictions WITHOUT any\n * incoming request.\n * `Services` exposes the same owner `SqlClient` used by the Thread stores. Compose optional\n * local repositories after `ThreadObject.layer`; never acquire another independently locked\n * SQL client for the same Object. Exposing the client installs no additional storage schemas.\n *\n * Constructor gate (`blockConcurrencyWhile`) is LOCAL-ONLY: schema migration and the\n * exact-version check, configuration decode, and the defensive ensure-alarm half of the\n * alarm invariant. It deliberately does NOT run the recovery pass: parent recovery can\n * require child-Object reads and vice versa, and two Objects blocked in constructor gates\n * awaiting each other's RPC would deadlock (plan §1.4). Instead every pass runs\n * `runRecovery({ threadId })` BEFORE that Thread's claim; old recovery cannot gate fresh dispatch.\n */\n\n/** Construction options for one deployed Thread Object class. */\nexport interface Options<\n ApplicationServices = never,\n EventServices = never,\n EventLayerError = never,\n> extends CloudflareDurableRuntimeOptions {\n /** Accept transient native RPC tracing through effect-cf; disabled by default. */\n readonly rpcTracing?: boolean;\n /**\n * Name of the Worker `env` binding carrying THIS class's `DurableObjectNamespace` — the\n * Object's route back to sibling Thread Objects for the WP2 cross-Object port calls\n * and remote wakes (DEPLOY-010: the binding enters through a Layer, never ambiently).\n */\n readonly namespaceBinding: string;\n /** Acquired and finalized per native event, with access to the complete application runtime. */\n readonly eventLayer?: Layer.Layer<\n EventServices,\n EventLayerError,\n | RuntimeServices\n | ApplicationServices\n | EffectCfDurableObjectState.DurableObjectState\n | WorkerEnvironment\n >;\n}\n\ntype EndpointServices =\n | CloudflareDurableRuntimeServices\n | CloudflareBootstrapServices\n | DurableObjectContext;\ntype RuntimeServices = EndpointServices | ThreadObjectNamespace;\ntype ThreadObjectInitializationError =\n | CloudflareDurableRuntimeInitializationError\n | CloudflareBindingError\n | MaintenancePassFailure;\n\n/** Classify only a decoded port request so new protocol members cannot bypass pre-arming. */\nconst isMutatingPortRequest = (request: PortRequest): boolean => {\n switch (request._tag) {\n case \"LedgerAdmit\":\n case \"LedgerMarkReady\":\n case \"LedgerStopWorker\":\n case \"LedgerRequestAbort\":\n case \"LedgerRecordChildSettled\":\n case \"StoreMaterialize\":\n case \"StoreAppend\":\n return true;\n case \"LedgerInspectWorker\":\n case \"LedgerLookup\":\n case \"LedgerResolveAdmission\":\n case \"StoreReadPage\":\n case \"StoreInspectTail\":\n case \"StoreReadIdentity\":\n case \"StoreCountPeerMessages\":\n case \"StoreExport\":\n case \"MessageDeliveryList\":\n return false;\n }\n request satisfies never;\n\n return false;\n};\n\n/** The literal encoded `PortFailed(PortProtocolError)` fallback (same shape as WP2's). */\nconst encodedPortProtocolFailure = (message: string): unknown => ({\n _tag: \"PortFailed\",\n failure: { _tag: \"PortProtocolError\", message: boundHostDiagnostic(message) },\n});\n\nconst protocolFailure = (context: string) => (error: { readonly message: string }) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`${context}: ${error.message}`),\n });\n\n/** Fold one endpoint's typed failures into the uniform `HostResponse` envelope. */\nconst respond = <Result extends HostResponse, Failure extends HostFailure>(\n effect: Effect.Effect<Result, Failure, EndpointServices>,\n): Effect.Effect<HostResponse, never, EndpointServices> =>\n effect.pipe(\n Effect.map((result): HostResponse => result),\n Effect.catch((failure) => Effect.succeed<HostResponse>(HostFailed.make({ failure }))),\n );\n\n/** Encode the response envelope; an unencodable response degrades to a protocol failure. */\nconst encodeResponse = (response: HostResponse): Effect.Effect<unknown> =>\n encodeHostResponse(response).pipe(\n Effect.catch((error) =>\n Effect.succeed<unknown>({\n _tag: \"HostFailed\",\n failure: {\n _tag: \"HostProtocolError\",\n message: boundHostDiagnostic(`The host response could not be encoded: ${error.message}`),\n },\n }),\n ),\n );\n\nconst utf8Bytes = (value: PersistedJson): number =>\n new TextEncoder().encode(JSON.stringify(value)).length;\n\n/**\n * The admission-limits gate, BEFORE `runtime.submit` touches the ledger (exit gate\n * \"resource limits are checked before admission\"; DEPLOY-007). A replayed idempotency key is\n * exempt: its accepted-work obligation already exists, and returning the original Receipt\n * consumes no new quota. Refusals are typed `AdmissionLimitExceeded` and nothing is written.\n */\nconst gateAdmissionLimits = Effect.fn(\"ThreadObject.gateAdmissionLimits\")(function* (\n threadId: ThreadId,\n request: {\n readonly principal: SubmissionLookupByKey[\"principal\"];\n readonly idempotencyKey: SubmissionLookupByKey[\"idempotencyKey\"];\n readonly inputPayload: PersistedJson;\n },\n) {\n const config = yield* CloudflareDurableRuntimeConfig;\n const ledger = yield* SubmissionLedger;\n const { ctx } = yield* DurableObjectContext;\n\n const existing = yield* ledger.lookup(\n SubmissionLookupByKey.make({\n threadId,\n principal: request.principal,\n idempotencyKey: request.idempotencyKey,\n }),\n );\n\n if (Option.isSome(existing)) return;\n\n const inputBytes = utf8Bytes(request.inputPayload);\n\n if (inputBytes > config.limits.maxInputBytes) {\n return yield* AdmissionLimitExceeded.make({\n limit: \"input-bytes\",\n actual: inputBytes,\n maximum: config.limits.maxInputBytes,\n });\n }\n\n const nonterminal = yield* ledger.scanNonterminal.pipe(\n Stream.filter((submission) => submission.threadId === threadId),\n Stream.runCollect,\n );\n\n if (nonterminal.length >= config.limits.maxQueueDepthPerLane) {\n return yield* AdmissionLimitExceeded.make({\n limit: \"queue-depth\",\n actual: nonterminal.length,\n maximum: config.limits.maxQueueDepthPerLane,\n });\n }\n\n const databaseBytes = yield* Effect.sync(() => ctx.storage.sql.databaseSize);\n\n if (databaseBytes > config.limits.maxDatabaseBytes) {\n return yield* AdmissionLimitExceeded.make({\n limit: \"database-bytes\",\n actual: databaseBytes,\n maximum: config.limits.maxDatabaseBytes,\n });\n }\n});\n\n/**\n * The submit-capable projection of an Agent Binding on the OBJECT side: the input arrived\n * already encoded through the real input schema on the Worker side (`client.ts`), so the\n * Object admits the canonical `PersistedJson` payload as-is; the resolved Binding re-derives\n * everything else from the stored `(agentId, agentDigests)` at claim time (SUB-023).\n */\nconst passthroughSubmitAgent = (agentId: AgentId): DurableSubmitAgent<typeof PersistedJson> => ({\n definition: {\n id: agentId,\n input: PersistedJson,\n },\n});\n\n/** A physical owner may hold other Threads; an addressed request cannot act on their IDs. */\nconst lookupAddressedSubmission = Effect.fn(\"ThreadObject.lookupAddressedSubmission\")(function* (\n submissionId: SubmissionId,\n) {\n const { threadId } = yield* ThreadObjectIdentity;\n const ports = yield* ThreadObjectPorts;\n const submission = yield* ports.lookupSubmission(submissionId);\n\n if (Option.isSome(submission) && submission.value.threadId !== threadId)\n return yield* HostProtocolError.make({ message: \"The Submission belongs to another Thread\" });\n\n return submission;\n});\n\nconst requireSubmissionThread = Effect.fn(\"ThreadObject.requireSubmissionThread\")(function* (\n submissionId: SubmissionId,\n) {\n const submission = yield* lookupAddressedSubmission(submissionId);\n\n if (Option.isNone(submission))\n return yield* LedgerError.make({\n operation: \"addressed Submission lookup\",\n message: \"The addressed Thread has no such Submission\",\n });\n});\n\nconst requireReceiptThread = Effect.fn(\"ThreadObject.requireReceiptThread\")(function* (\n threadId: ThreadId,\n) {\n const identity = yield* ThreadObjectIdentity;\n\n if (threadId !== identity.threadId)\n return yield* HostProtocolError.make({ message: \"The Receipt belongs to another Thread\" });\n});\n\nconst requirePortThread = (request: PortRequest) => {\n switch (request._tag) {\n case \"MessageDeliveryList\":\n return requireReceiptThread(request.request.ownerThreadId);\n case \"LedgerLookup\":\n return request.request._tag === \"SubmissionLookupById\"\n ? lookupAddressedSubmission(request.request.submissionId).pipe(Effect.asVoid)\n : requireReceiptThread(request.request.threadId);\n case \"LedgerMarkReady\":\n case \"LedgerRequestAbort\":\n return requireSubmissionThread(request.request.submissionId);\n case \"LedgerRecordChildSettled\":\n return requireSubmissionThread(request.request.parentSubmissionId);\n case \"LedgerInspectWorker\":\n case \"LedgerStopWorker\":\n case \"LedgerAdmit\":\n case \"LedgerResolveAdmission\":\n case \"StoreMaterialize\":\n case \"StoreAppend\":\n case \"StoreReadPage\":\n case \"StoreInspectTail\":\n case \"StoreReadIdentity\":\n case \"StoreCountPeerMessages\":\n case \"StoreExport\":\n return requireReceiptThread(request.request.threadId);\n }\n request satisfies never;\n};\n\n/**\n * Admit an already Schema-decoded request to a logical Thread in this physical owner.\n * Custom hosts validate local placement before calling this Effect and provide their same\n * runtime/maintenance instances. The native endpoint uses this path too: queue limits,\n * idempotent receipts and the pre-admission generation/alarm commit have one owner.\n */\nexport const submit = Effect.fn(\"ThreadObject.submit\")(function* (\n threadId: ThreadId,\n request: SubmitRequest,\n) {\n const placement = yield* ThreadObjectPlacement;\n\n if (!placement.ownsThread(threadId))\n return yield* HostProtocolError.make({ message: \"The Thread belongs to another Object\" });\n const mutations = yield* ThreadMutationGate;\n const runtime = yield* DurableAgentRuntime;\n\n yield* gateAdmissionLimits(threadId, request);\n\n return yield* mutations.withMutation(\n runtime\n .submit(passthroughSubmitAgent(request.agentId), request.inputPayload, {\n threadId,\n principal: request.principal,\n idempotencyKey: request.idempotencyKey,\n ...(request.admissionGroup === undefined ? {} : { admissionGroup: request.admissionGroup }),\n ...(request.admissionFence === undefined ? {} : { admissionFence: request.admissionFence }),\n ...(request.workerAdmission === undefined\n ? {}\n : { workerAdmission: request.workerAdmission }),\n ...(request.messageAdmission === undefined\n ? {}\n : { messageAdmission: request.messageAdmission }),\n definitions: request.definitions,\n })\n .pipe(Effect.tap(() => publishCommitted)),\n );\n});\n\nconst submitEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n decodeSubmitRequest(encoded).pipe(\n Effect.mapError(protocolFailure(\"The submit request could not be decoded\")),\n Effect.flatMap((request) =>\n Effect.gen(function* () {\n const identity = yield* ThreadObjectIdentity;\n const receipt = yield* submit(identity.threadId, request);\n\n return SubmitSucceeded.make({ receipt });\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\nconst submissionStatusEndpoint = (\n encoded: unknown,\n): Effect.Effect<unknown, never, EndpointServices> =>\n decodeReceipt(encoded).pipe(\n Effect.mapError(protocolFailure(\"The receipt could not be decoded\")),\n Effect.flatMap((receipt) =>\n Effect.gen(function* () {\n const authorizer = yield* OperationAuthorizer;\n\n yield* authorizer.authorize(\n OperationAuthorizationRequest.make({\n operation: \"awaitSettlement\",\n threadId: receipt.threadId,\n submissionId: receipt.submissionId,\n }),\n );\n yield* requireReceiptThread(receipt.threadId);\n yield* requireSubmissionThread(receipt.submissionId);\n const runtime = yield* DurableAgentRuntime;\n\n return SubmissionStatusResponse.make({ status: yield* runtime.submissionStatus(receipt) });\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\nconst awaitSettlementEndpoint = (\n encoded: unknown,\n): Effect.Effect<unknown, never, EndpointServices> =>\n decodeReceipt(encoded).pipe(\n Effect.mapError(protocolFailure(\"The receipt could not be decoded\")),\n Effect.flatMap((receipt) =>\n Effect.gen(function* () {\n const authorizer = yield* OperationAuthorizer;\n\n yield* authorizer.authorize(\n OperationAuthorizationRequest.make({\n operation: \"awaitSettlement\",\n threadId: receipt.threadId,\n submissionId: receipt.submissionId,\n }),\n );\n yield* requireReceiptThread(receipt.threadId);\n yield* requireSubmissionThread(receipt.submissionId);\n const runtime = yield* DurableAgentRuntime;\n const settlement = yield* runtime.awaitSettlement(receipt);\n\n return SettlementReached.make({ settlement });\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\nconst awaitProgressEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n decodeAwaitProgressRequest(encoded).pipe(\n Effect.mapError(protocolFailure(\"The progress request could not be decoded\")),\n Effect.flatMap((request) =>\n Effect.gen(function* () {\n const identity = yield* ThreadObjectIdentity;\n const runtime = yield* DurableAgentRuntime;\n const registry = yield* ProgressWaitRegistry;\n\n yield* Effect.scoped(\n Effect.gen(function* () {\n const cancelled = yield* registry.subscribe(\n JSON.stringify([identity.threadId, request.waiterId]),\n );\n\n yield* Effect.raceFirst(\n runtime.awaitProgress(identity.threadId, request.afterSequence),\n cancelled,\n );\n }),\n );\n\n return ProgressObserved.make();\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\nconst cancelProgressEndpoint = (\n encoded: unknown,\n): Effect.Effect<unknown, never, EndpointServices> =>\n decodeCancelProgressRequest(encoded).pipe(\n Effect.mapError(protocolFailure(\"The progress cancellation could not be decoded\")),\n Effect.flatMap((request) =>\n Effect.gen(function* () {\n const identity = yield* ThreadObjectIdentity;\n const registry = yield* ProgressWaitRegistry;\n\n yield* registry.cancel(JSON.stringify([identity.threadId, request.waiterId]));\n\n return ProgressCancelled.make();\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\nconst observePageEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n decodeObservePageRequest(encoded).pipe(\n Effect.mapError(protocolFailure(\"The observe request could not be decoded\")),\n Effect.flatMap((request) =>\n Effect.gen(function* () {\n const identity = yield* ThreadObjectIdentity;\n const store = yield* ThreadStore;\n // The same fail-closed authorization seam the runtime's `observe` consults (P7 WP1);\n // the default reference preserves the possession behavior.\n const authorizer = yield* OperationAuthorizer;\n\n yield* authorizer.authorize(\n OperationAuthorizationRequest.make({\n operation: \"observe\",\n threadId: identity.threadId,\n }),\n );\n\n const records = yield* Stream.runCollect(\n store.read(\n ThreadRead.make({\n threadId: identity.threadId,\n ...(request.afterSequence === undefined\n ? {}\n : { afterSequence: request.afterSequence }),\n limit: request.limit,\n }),\n ),\n );\n\n return ObservedPage.make({ records: [...records] });\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\nconst abortEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n decodeAbortCommand(encoded).pipe(\n Effect.mapError(protocolFailure(\"The abort command could not be decoded\")),\n Effect.flatMap((command) =>\n Effect.gen(function* () {\n const authorizer = yield* OperationAuthorizer;\n\n yield* authorizer.authorize(\n OperationAuthorizationRequest.make({\n operation: \"abort\",\n submissionId: command.submissionId,\n }),\n );\n yield* requireSubmissionThread(command.submissionId);\n const maintenance = yield* ThreadMaintenance;\n const runtime = yield* DurableAgentRuntime;\n const intent = yield* maintenance.withMutation(runtime.abort(command));\n\n return AbortRecorded.make({ intent });\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\nconst resolveApprovalEndpoint = (\n encoded: unknown,\n): Effect.Effect<unknown, never, EndpointServices> =>\n decodeApprovalDecisionCommand(encoded).pipe(\n Effect.mapError(protocolFailure(\"The approval command could not be decoded\")),\n Effect.flatMap((command) =>\n Effect.gen(function* () {\n const authorizer = yield* OperationAuthorizer;\n\n yield* authorizer.authorize(\n OperationAuthorizationRequest.make({\n operation: \"resolveApproval\",\n submissionId: command.submissionId,\n }),\n );\n yield* requireSubmissionThread(command.submissionId);\n const maintenance = yield* ThreadMaintenance;\n const runtime = yield* DurableAgentRuntime;\n const intent = yield* maintenance.withMutation(runtime.resolveApproval(command));\n\n return ApprovalRecorded.make({ intent });\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\nconst resolveUnknownEndpoint = (\n encoded: unknown,\n): Effect.Effect<unknown, never, EndpointServices> =>\n decodeUnknownResolutionCommand(encoded).pipe(\n Effect.mapError(protocolFailure(\"The resolution command could not be decoded\")),\n Effect.flatMap((command) =>\n Effect.gen(function* () {\n const authorizer = yield* OperationAuthorizer;\n\n yield* authorizer.authorize(\n OperationAuthorizationRequest.make({\n operation: \"resolveUnknown\",\n submissionId: command.submissionId,\n }),\n );\n yield* requireSubmissionThread(command.submissionId);\n const maintenance = yield* ThreadMaintenance;\n const runtime = yield* DurableAgentRuntime;\n const intent = yield* maintenance.withMutation(runtime.resolveUnknown(command));\n\n return UnknownResolutionRecorded.make({ intent });\n }),\n ),\n respond,\n Effect.flatMap(encodeResponse),\n );\n\n// ---------------------------------------------------------------------------\n// P7 administrative entry points (plan §3): explain/verify/retry/obligations over the SAME\n// envelope discipline as the host protocol — closed request/response Schema unions, typed\n// failures that re-decode to identical tags, protocol anomalies answered typed. The envelopes\n// live here (not `client.ts`) because no Worker-side client consumption exists yet; `wake`\n// already exists as the `wake()` entry point.\n// ---------------------------------------------------------------------------\n\n/** Explain one Submission (`submissionId` present) or every nonterminal lane member. */\nexport class AdminExplainRequest extends Schema.Class<AdminExplainRequest>(\n \"@effect-agent/platform-cloudflare/AdminExplainRequest\",\n)({\n submissionId: Schema.optionalKey(SubmissionId),\n}) {}\n\n/** Verify carries no parameters — the addressed Object IS the lane. */\nexport class AdminVerifyRequest extends Schema.Class<AdminVerifyRequest>(\n \"@effect-agent/platform-cloudflare/AdminVerifyRequest\",\n)({}) {}\n\n/** Every typed failure of the four admin entry points, plus the protocol's own errors. */\nexport const AdminFailure = Schema.Union([\n AdmissionPolicyError,\n ApprovalSuspensionError,\n OperationDenied,\n RetryRefused,\n LedgerError,\n RunJournalError,\n DigestError,\n OwnershipLost,\n SettlementConflict,\n ThreadStoreError,\n ThreadNotMaterialized,\n AppendConflict,\n FenceRejected,\n DurableRuntimeFailpointError,\n DurableAlarmError,\n HostProtocolError,\n]);\n\nexport type AdminFailure = typeof AdminFailure.Type;\n\nexport class ExplainedRecovery extends Schema.TaggedClass<ExplainedRecovery>(\n \"@effect-agent/platform-cloudflare/ExplainedRecovery\",\n)(\"ExplainedRecovery\", {\n explanations: Schema.Array(RecoveryExplanation).check(Schema.isMaxLength(1_024)),\n}) {}\n\nexport class VerifiedIntegrity extends Schema.TaggedClass<VerifiedIntegrity>(\n \"@effect-agent/platform-cloudflare/VerifiedIntegrity\",\n)(\"VerifiedIntegrity\", {\n report: IntegrityReport,\n}) {}\n\nexport class RetryExecuted extends Schema.TaggedClass<RetryExecuted>(\n \"@effect-agent/platform-cloudflare/RetryExecuted\",\n)(\"RetryExecuted\", {\n report: RecoveryReport,\n}) {}\n\nexport class ObligationsScanned extends Schema.TaggedClass<ObligationsScanned>(\n \"@effect-agent/platform-cloudflare/ObligationsScanned\",\n)(\"ObligationsScanned\", {\n report: ObligationReport,\n}) {}\n\n/** The admin entry point failed TYPED on the Object; the failure re-decodes verbatim. */\nexport class AdminFailed extends Schema.TaggedClass<AdminFailed>(\n \"@effect-agent/platform-cloudflare/AdminFailed\",\n)(\"AdminFailed\", {\n failure: AdminFailure,\n}) {}\n\n/** The uniform answer of one admin entry point. Callers narrow by the tag their call implies. */\nexport const AdminResponse = Schema.Union([\n ExplainedRecovery,\n VerifiedIntegrity,\n RetryExecuted,\n ObligationsScanned,\n AdminFailed,\n]);\n\nexport type AdminResponse = typeof AdminResponse.Type;\n\nexport const decodeAdminExplainRequest = Schema.decodeUnknownEffect(AdminExplainRequest);\nexport const decodeAdminVerifyRequest = Schema.decodeUnknownEffect(AdminVerifyRequest);\nexport const decodeRetryCommand = Schema.decodeUnknownEffect(RetryCommand);\nexport const decodeObligationThresholds = Schema.decodeUnknownEffect(ObligationThresholds);\nexport const encodeAdminResponse = Schema.encodeEffect(AdminResponse);\nexport const decodeAdminResponse = Schema.decodeUnknownEffect(AdminResponse);\n\n/** Fold one admin endpoint's typed failures into the uniform `AdminResponse` envelope. */\nconst respondAdmin = <Result extends AdminResponse, Failure extends AdminFailure>(\n effect: Effect.Effect<Result, Failure, EndpointServices>,\n): Effect.Effect<AdminResponse, never, EndpointServices> =>\n effect.pipe(\n Effect.map((result): AdminResponse => result),\n Effect.catch((failure) => Effect.succeed<AdminResponse>(AdminFailed.make({ failure }))),\n );\n\n/** Encode the admin response envelope; an unencodable response degrades to a protocol failure. */\nconst encodeAdminResponseTotal = (response: AdminResponse): Effect.Effect<unknown> =>\n encodeAdminResponse(response).pipe(\n Effect.catch((error) =>\n Effect.succeed<unknown>({\n _tag: \"AdminFailed\",\n failure: {\n _tag: \"HostProtocolError\",\n message: boundHostDiagnostic(`The admin response could not be encoded: ${error.message}`),\n },\n }),\n ),\n );\n\nconst explainEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n decodeAdminExplainRequest(encoded).pipe(\n Effect.mapError(protocolFailure(\"The explain request could not be decoded\")),\n Effect.flatMap((request) =>\n Effect.gen(function* () {\n const identity = yield* ThreadObjectIdentity;\n const runtime = yield* DurableAgentRuntime;\n\n const explanations =\n request.submissionId === undefined\n ? yield* runtime.explainThread(identity.threadId)\n : [yield* runtime.explain(request.submissionId)];\n\n return ExplainedRecovery.make({ explanations });\n }),\n ),\n respondAdmin,\n Effect.flatMap(encodeAdminResponseTotal),\n );\n\nconst verifyEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n decodeAdminVerifyRequest(encoded).pipe(\n Effect.mapError(protocolFailure(\"The verify request could not be decoded\")),\n Effect.flatMap(() =>\n Effect.gen(function* () {\n const identity = yield* ThreadObjectIdentity;\n const runtime = yield* DurableAgentRuntime;\n const report = yield* runtime.verify(identity.threadId);\n\n return VerifiedIntegrity.make({ report });\n }),\n ),\n respondAdmin,\n Effect.flatMap(encodeAdminResponseTotal),\n );\n\nconst retryEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n decodeRetryCommand(encoded).pipe(\n Effect.mapError(protocolFailure(\"The retry command could not be decoded\")),\n Effect.flatMap((command) =>\n Effect.gen(function* () {\n const maintenance = yield* ThreadMaintenance;\n const runtime = yield* DurableAgentRuntime;\n // Retry may repair durable state, so its generation + alarm commit before the mutation.\n const report = yield* maintenance.withMutation(runtime.retry(command));\n\n return RetryExecuted.make({ report });\n }),\n ),\n respondAdmin,\n Effect.flatMap(encodeAdminResponseTotal),\n );\n\nconst obligationsEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n decodeObligationThresholds(encoded).pipe(\n Effect.mapError(protocolFailure(\"The obligation thresholds could not be decoded\")),\n Effect.flatMap((thresholds) =>\n Effect.gen(function* () {\n const runtime = yield* DurableAgentRuntime;\n const report = yield* runtime.scanObligations(thresholds);\n\n return ObligationsScanned.make({ report });\n }),\n ),\n respondAdmin,\n Effect.flatMap(encodeAdminResponseTotal),\n );\n\n/**\n * Owner-side `portCall`: wrap a mutating envelope in the same pre-armed generation protocol as\n * public RPC (a routed mutation committed by THIS Object must already carry the alarm that will\n * finish it), execute on the LOCAL facets (never the routed decorators), then arm an immediate\n * alarm so the mutated lane is processed promptly. Protocol anomalies answer\n * `PortFailed(PortProtocolError)`.\n */\nconst encodePortResponseTotal = (response: PortResponse) =>\n encodePortResponse(response).pipe(\n Effect.catch((error) =>\n Effect.succeed(\n encodedPortProtocolFailure(`The port response could not be encoded: ${error.message}`),\n ),\n ),\n );\n\nconst portGuardFailure = (failure: LedgerError | HostProtocolError): PortFailed =>\n PortFailed.make({\n failure:\n failure._tag === \"LedgerError\"\n ? failure\n : PortProtocolError.make({ message: \"The port request is not for the addressed Thread\" }),\n });\n\nexport const portCall = (\n encoded: unknown,\n): Effect.Effect<\n unknown,\n never,\n ThreadObjectPorts | ThreadMaintenance | DurableAlarmService | ThreadObjectIdentity\n> =>\n Effect.gen(function* () {\n const ports = yield* ThreadObjectPorts;\n const maintenance = yield* ThreadMaintenance;\n const alarm = yield* DurableAlarmService;\n\n const decoded = yield* decodePortRequest(encoded).pipe(\n Effect.map((request) => ({ _tag: \"success\" as const, request })),\n Effect.catch((error) => Effect.succeed({ _tag: \"failure\" as const, message: error.message })),\n );\n\n if (decoded._tag === \"failure\") {\n return encodedPortProtocolFailure(\n `The port request could not be decoded: ${decoded.message}`,\n );\n }\n if (\n decoded.request._tag === \"LedgerLookup\" &&\n decoded.request.request._tag === \"SubmissionLookupById\"\n ) {\n const response = yield* lookupAddressedSubmission(decoded.request.request.submissionId).pipe(\n Effect.map((submission) =>\n PortSucceeded.make({\n result: LedgerLookupResult.make(\n Option.isSome(submission) ? { submission: submission.value } : {},\n ),\n }),\n ),\n Effect.catch((failure) => Effect.succeed(portGuardFailure(failure))),\n );\n\n return yield* encodePortResponseTotal(response);\n }\n const identityCheck = yield* requirePortThread(decoded.request).pipe(Effect.result);\n\n if (identityCheck._tag === \"Failure\")\n return yield* encodePortResponseTotal(portGuardFailure(identityCheck.failure));\n const mutating = isMutatingPortRequest(decoded.request);\n\n const handled = yield* (\n mutating\n ? maintenance.withMutation(ports.handle(decoded.request))\n : ports.handle(decoded.request)\n ).pipe(Effect.exit);\n\n if (handled._tag === \"Failure\") {\n // Without the committed generation/alarm the invariant cannot be promised; refuse before\n // the port mutation runs. `ports.handle` itself is total, so this is the maintenance error.\n return encodedPortProtocolFailure(\n \"The owner Object could not arm its maintenance alarm before the mutation.\",\n );\n }\n\n const response = yield* encodePortResponseTotal(handled.value);\n\n if (mutating) {\n // Prompt processing hint; the pre-armed alarm already guarantees convergence.\n yield* alarm.scheduleNow.pipe(\n Effect.catch((error) =>\n Effect.logWarning(\"ThreadObject.portCall: immediate re-arm failed\", error),\n ),\n );\n }\n\n return response;\n });\n\nconst wakeEndpoint: Effect.Effect<void, never, EndpointServices> = Effect.gen(function* () {\n const identity = yield* ThreadObjectIdentity;\n const wake = yield* WakeScheduler;\n\n // Route the remote hint through this incarnation's scheduler so scoped progress waiters and\n // the alarm receive the same hint. Delivery remains droppable; canonical storage is authority.\n yield* wake.notify(identity.threadId);\n});\n\n/** The per-Thread wire operations supported by native and application-owned endpoints. */\nexport const ThreadRpcOperation = Schema.Literals([\n \"submitEncoded\",\n \"submissionStatusEncoded\",\n \"awaitSettlementEncoded\",\n \"awaitProgressEncoded\",\n \"cancelProgressEncoded\",\n \"observePage\",\n \"abortEncoded\",\n \"resolveApprovalEncoded\",\n \"resolveUnknownEncoded\",\n \"portCall\",\n \"wake\",\n]);\n\nexport type ThreadRpcOperation = typeof ThreadRpcOperation.Type;\n\nconst threadRpc = {\n submitEncoded: submitEndpoint,\n submissionStatusEncoded: submissionStatusEndpoint,\n awaitSettlementEncoded: awaitSettlementEndpoint,\n awaitProgressEncoded: awaitProgressEndpoint,\n cancelProgressEncoded: cancelProgressEndpoint,\n observePage: observePageEndpoint,\n abortEncoded: abortEndpoint,\n resolveApprovalEncoded: resolveApprovalEndpoint,\n resolveUnknownEncoded: resolveUnknownEndpoint,\n portCall,\n wake: () => wakeEndpoint,\n} satisfies Record<\n ThreadRpcOperation,\n (encoded: unknown) => Effect.Effect<unknown, never, EndpointServices>\n>;\n\n/**\n * Bind an addressed request to its logical Thread while sharing one physical runtime. This\n * validates local placement before invoking the same native handlers. Receipts, Submission\n * commands and port envelopes must match this identity; progress cancellation is Thread-scoped.\n * The producer comes from the actual runtime configuration, never from caller input. These\n * guards supplement the existing current model/Tool and operation authorization policies.\n */\nexport const handleRpc = Effect.fn(\"ThreadObject.handleRpc\")(function* (\n threadId: ThreadId,\n operation: ThreadRpcOperation,\n encoded: unknown,\n) {\n const placement = yield* ThreadObjectPlacement;\n\n if (!placement.ownsThread(threadId))\n return yield* HostProtocolError.make({ message: \"The Thread belongs to another Object\" });\n const { producerId } = yield* DurableRuntimeConfig;\n\n return yield* threadRpc[operation](encoded).pipe(\n Effect.provideService(ThreadObjectIdentity, { threadId, producerId }),\n );\n});\n\nconst alarmEndpoint: Effect.Effect<void, MaintenancePassFailure, EndpointServices> = Effect.gen(\n function* () {\n const maintenance = yield* ThreadMaintenance;\n\n // Typed pass failures propagate: the rejected promise makes workerd retry the alarm\n // (at-least-once delivery), and the dirty generation retains a committed slot meanwhile.\n yield* maintenance.pass;\n },\n);\n\nconst gateEndpoint: Effect.Effect<void, MaintenancePassFailure, EndpointServices> = Effect.gen(\n function* () {\n // Forcing ThreadMaintenance forces the whole Layer stack: migration + exact-version\n // check + configuration decode (DEPLOY-008 fails typed here, before any mutation), then\n // the defensive local ensure-alarm half of the invariant. LOCAL-ONLY by construction.\n const maintenance = yield* ThreadMaintenance;\n\n yield* maintenance.ensureAlarm;\n },\n);\n\n/**\n * Adapter from effect-cf's native Durable Object services to Effect Agent's existing platform\n * ports. effect-cf owns the cached ManagedRuntime and supplies these values once per Object\n * incarnation; the durable runtime continues to depend only on the narrow services below.\n */\nconst effectCfPlatformLayer = (\n namespaceBinding: string,\n rpcTracing = false,\n): Layer.Layer<\n DurableObjectContext | ThreadObjectNamespace,\n CloudflareBindingError,\n EffectCfDurableObjectState.DurableObjectState | WorkerEnvironment\n> => {\n const context = Layer.effect(DurableObjectContext)(\n Effect.gen(function* () {\n const state = yield* EffectCfDurableObjectState.DurableObjectState;\n const env = yield* WorkerEnvironment;\n\n return DurableObjectContext.of({ ctx: state.raw, env });\n }),\n );\n\n const namespace = Layer.effect(ThreadObjectNamespace)(\n Effect.gen(function* () {\n const env = yield* WorkerEnvironment;\n const binding = yield* threadNamespaceFromEnv(env, namespaceBinding);\n\n return ThreadObjectNamespace.of({\n get: (threadId) => binding.get(binding.idFromName(threadId)),\n ...(rpcTracing === true ? { rpcTracing: namespaceBinding } : {}),\n });\n }),\n );\n\n return Layer.merge(context, namespace);\n};\n\n/** The public endpoints and effect-cf invocation hook of one Thread Object instance. */\nexport interface Instance<EventServices = never> extends InstanceType<\n EffectCfDurableObject.DurableObjectClass<Record<never, never>, RuntimeServices | EventServices>\n> {\n submitEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n submissionStatusEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n awaitSettlementEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n awaitProgressEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n cancelProgressEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n observePage(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n abortEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n resolveApprovalEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n resolveUnknownEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n explainEncoded(encoded: unknown): Promise<unknown>;\n verifyEncoded(encoded: unknown): Promise<unknown>;\n retryEncoded(encoded: unknown): Promise<unknown>;\n obligationsEncoded(encoded: unknown): Promise<unknown>;\n portCall(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n wake(): Promise<void>;\n alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> | void;\n}\n\n/** The constructor shape workerd instantiates for each Thread Object. */\nexport interface Class<EventServices = never> {\n new (ctx: DurableObjectState, env: Cloudflare.Env): Instance<EventServices>;\n}\n\n/**\n * Export a composed application Layer as a native Durable Object class.\n * Bootstrap services are provided to the whole graph before it acquires, so application Layers\n * can yield effect-cf's WorkerEnvironment and DurableObjectState, derived identity, and Crypto.\n * Effect Config reads scalar Worker vars and secrets through effect-cf's environment provider;\n * WorkerEnvironment exposes resource bindings without a separate config Layer.\n * Application dependencies remain visible until Layer.provide satisfies them. effect-cf owns the\n * cached ManagedRuntime, native RPC methods, event scopes, and telemetry flushing.\n * Initialization is local and bounded inside the constructor gate. Cloudflare eviction does not\n * guarantee finalizers; put resources requiring timely release in scoped operations or eventLayer.\n */\nexport const make = <\n ApplicationServices,\n ApplicationError,\n EventServices = never,\n EventLayerError = never,\n>(\n applicationLayer: Layer.Layer<\n CloudflareDurableRuntimeServices | ApplicationServices,\n ApplicationError,\n | CloudflareBootstrapServices\n | EffectCfDurableObjectState.DurableObjectState\n | WorkerEnvironment\n | DurableObjectContext\n | ThreadObjectNamespace\n >,\n options: Options<ApplicationServices, EventServices, EventLayerError>,\n): Class<ApplicationServices | EventServices> => {\n const application = applicationLayer.pipe(\n Layer.provideMerge(layerConfig(options)),\n Layer.provideMerge(effectCfPlatformLayer(options.namespaceBinding, options.rpcTracing)),\n );\n\n // The storage/config Layer must acquire inside Cloudflare's constructor gate. effect-cf owns\n // the ManagedRuntime, while this effectContext ensures its first Layer build enters the gate\n // before migration, compatibility checks, or alarm inspection touch Object storage.\n const runtime: Layer.Layer<\n RuntimeServices | ApplicationServices,\n ThreadObjectInitializationError | ApplicationError,\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(\n Effect.gen(function* () {\n const services = yield* Layer.buildWithScope(application, scope);\n\n yield* gateEndpoint.pipe(Effect.provide(services));\n\n return services;\n }),\n );\n }),\n );\n\n const rpc = {\n ...threadRpc,\n explainEncoded: (encoded: unknown) => explainEndpoint(encoded),\n verifyEncoded: (encoded: unknown) => verifyEndpoint(encoded),\n retryEncoded: (encoded: unknown) => retryEndpoint(encoded),\n obligationsEncoded: (encoded: unknown) => obligationsEndpoint(encoded),\n } satisfies EffectCfDurableObject.DurableObjectRpc<\n RuntimeServices | ApplicationServices | EventServices\n >;\n\n type NativeOptions = EffectCfDurableObject.DurableObjectOptions<\n RuntimeServices | ApplicationServices,\n EventServices,\n EventLayerError,\n typeof rpc\n >;\n\n const EffectCfThreadObject = EffectCfDurableObject.make<\n RuntimeServices | ApplicationServices,\n ThreadObjectInitializationError | ApplicationError,\n EventServices,\n EventLayerError,\n typeof rpc\n >(runtime, {\n ...(options.rpcTracing === true ? { rpcTracing: { service: options.namespaceBinding } } : {}),\n ...(options.eventLayer === undefined ? {} : { eventLayer: options.eventLayer }),\n // Force the gated runtime Layer when Cloudflare loads this Object incarnation. Recovery stays\n // in each bounded pass so cross-Object initialization cannot deadlock.\n initialize: Effect.void,\n rpc,\n alarm: () => alarmEndpoint,\n // This host owns the raw alarm and supplies event services through options.eventLayer.\n // Upstream's conditional alarm-registration check cannot reduce over generic application\n // services. Options and the rpc satisfies check above retain their Effect requirements.\n } as NativeOptions);\n\n // effect-cf's class type keeps `alarm` optional even when the handler option is present. This\n // concrete override reflects this factory's stronger contract while delegating execution to\n // the effect-cf runtime unchanged.\n class ThreadObject extends EffectCfThreadObject {\n override alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> | void {\n return super.alarm?.(alarmInfo);\n }\n }\n\n return ThreadObject;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,MAAa,mCAAmC,MAAM,OACpD,sBACA,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,OAAO;CACrB,MAAM,YAAY,OAAO;CACzB,MAAM,QAAQ,OAAO;CACrB,MAAM,EAAE,eAAe,OAAO;CAG9B,MAAM,WAAW,OAAO,IAAI,KAAgC,KAAA,CAAS;CACrE,MAAM,YAAY,OAAO,UAAU,KAAK,CAAC;CAEzC,MAAM,SACJ,OACA,SAEA,UAAU,KAAA,KAAa,WAAW,KAAK,IACnC,OACA,OAAO,KACL,qBAAqB,KAAK;EAAE,QAAQ;EAAc,WAAW;CAAgB,CAAC,CAChF;CAEN,MAAM,UAAgB,SACpB,UACG,aACC,UAAU,WAAW,IAAI,IAAI,UAAU,KAAA,CAAS,CAAC,CAAC,KAAK,OAAO,QAAQ,IAAI,CAAC,CAAC,GAG5E,EAAE,qBAAqB,MAAM,CAC/B,CAAC,CACA,KACC,OAAO,SAAS,2B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