@yielded/agent-platform-cloudflare 0.1.0-beta.169 → 0.1.0-beta.171
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/CloudflareScheduling.mjs +2 -2
- package/dist/CloudflareSubscriptions.mjs +2 -2
- package/dist/{CloudflareThreadClient-CLZpN9zU.mjs → CloudflareThreadClient-D0jRV6Jp.mjs} +2 -2
- package/dist/CloudflareThreadClient-D0jRV6Jp.mjs.map +1 -0
- package/dist/CloudflareThreadClient.mjs +1 -1
- package/dist/{ThreadObject-CgXZMlr4.mjs → ThreadObject-AcJYhNnL.mjs} +30 -6
- package/dist/ThreadObject-AcJYhNnL.mjs.map +1 -0
- package/dist/ThreadObject.mjs +1 -1
- package/dist/index.mjs +2 -2
- package/dist/{prepared-admission-B61A7y6O.mjs → prepared-admission-Chy9awEp.mjs} +2 -2
- package/dist/{prepared-admission-B61A7y6O.mjs.map → prepared-admission-Chy9awEp.mjs.map} +1 -1
- package/package.json +1 -1
- package/src/ThreadObject.ts +16 -2
- package/src/internal/crypto.ts +1 -1
- package/src/internal/live-text.ts +34 -12
- package/dist/CloudflareThreadClient-CLZpN9zU.mjs.map +0 -1
- package/dist/ThreadObject-CgXZMlr4.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"CloudflareThreadClient-CLZpN9zU.mjs","names":["LiveTextFrame","WatchTextRequest"],"sources":["../src/internal/crypto.ts","../src/internal/live-text-protocol.ts","../src/CloudflareThreadClient.ts"],"sourcesContent":["// Implement the Effect Crypto service with the Workers native hashing primitive.\n// @effect-diagnostics-next-line nodeBuiltinImport:off\nimport { createHash } from \"node:crypto\";\n\nimport { BrowserCrypto } from \"@effect/platform-browser\";\nimport { Crypto, Effect, Layer, PlatformError } from \"effect\";\n\n/** Workers use native SHA-256 while retaining BrowserCrypto's services and overrides. */\nexport const cloudflareCryptoLayer: Layer.Layer<Crypto.Crypto> = Layer.effect(\n Crypto.Crypto,\n Effect.gen(function* () {\n const base = yield* Crypto.Crypto;\n const webCrypto = yield* BrowserCrypto.WebCrypto;\n const hostGlobals: object = globalThis;\n\n return Crypto.Crypto.of({\n ...base,\n digest: (algorithm, data) => {\n if (\n algorithm !== \"SHA-256\" ||\n !(\"crypto\" in hostGlobals) ||\n webCrypto !== hostGlobals.crypto ||\n typeof webCrypto.subtle?.digest !== \"function\"\n )\n return base.digest(algorithm, data);\n\n return Effect.try({\n try: () => Uint8Array.from(createHash(\"sha256\").update(new Uint8Array(data)).digest()),\n catch: (cause) =>\n PlatformError.systemError({\n module: \"Crypto\",\n method: \"digest\",\n _tag: \"Unknown\",\n description: \"Could not compute digest\",\n cause,\n }),\n });\n },\n });\n }),\n).pipe(Layer.provide(BrowserCrypto.layer));\n","import { ThreadId } from \"@yielded/agent/identifiers\";\nimport { Event } from \"@yielded/agent/provisional-text\";\nimport { Schema } from \"effect\";\n\nexport const MAX_FRAME_BYTES = 32 * 1_024;\nexport const MAX_ID_LENGTH = 256;\nexport const MAX_DELTA_LENGTH = 4_096;\nexport const BUFFER_SIZE = 32;\nexport const MAX_OBSERVERS = 8;\nexport const MAX_DRAFT_PARTS = 32;\nexport const MAX_DRAFT_LENGTH = 2 * 1_024 * 1_024;\n\nconst streamId = Schema.NonEmptyString.check(Schema.isMaxLength(MAX_ID_LENGTH));\n\nexport const Request = Schema.Struct({ schemaVersion: Schema.Literal(1) });\n\n/**\n * Reset replaces all drafts with a snapshot, streamed as native Text parts before live deltas.\n * Each snapshot starts a fresh streamId. Its sequences are unrelated to canonical sequences.\n */\nexport const Frame = Schema.Union([\n Schema.TaggedStruct(\"Reset\", {\n schemaVersion: Schema.Literal(1),\n streamId,\n threadId: ThreadId,\n sequence: Schema.Literal(0),\n }),\n Schema.TaggedStruct(\"Event\", {\n schemaVersion: Schema.Literal(1),\n streamId,\n sequence: Schema.Int.check(Schema.isGreaterThan(0)),\n event: Event,\n }),\n]);\n\nexport type Frame = typeof Frame.Type;\n\n/** Bounds are checked before queueing; provider metadata is deliberately absent. */\nexport const isBoundedEvent = (event: Event): boolean => {\n const ids: string[] = [event.threadId, event.submissionId, event.attemptId];\n\n if (event._tag !== \"AttemptEnded\") ids.push(event.runId, event.turnId);\n if (ids.some((id) => id.length > MAX_ID_LENGTH)) return false;\n\n return (\n event._tag !== \"Text\" ||\n (event.part.id.length <= MAX_ID_LENGTH &&\n Object.keys(event.part.metadata).length === 0 &&\n (event.part.type !== \"text-delta\" || event.part.delta.length <= MAX_DELTA_LENGTH))\n );\n};\n","import { AgentInputError } from \"@yielded/agent/agent-error\";\nimport { DigestError } from \"@yielded/agent/digest\";\nimport {\n Receipt,\n type DurableSubmitAgent,\n type DurableSubmitOptions,\n} from \"@yielded/agent/durable-agent-runtime\";\nimport { DurableRuntimeFailpointError } from \"@yielded/agent/durable-failpoint\";\nimport { AgentId, type ThreadId } from \"@yielded/agent/identifiers\";\nimport { InputMessage } from \"@yielded/agent/messaging\";\nimport { OperationDenied } from \"@yielded/agent/operation-authorizer\";\nimport {\n CanonicalRecordEnvelope,\n CanonicalSequence,\n DefinitionDigests,\n PersistedJson,\n SubmissionSettledRecord,\n WorkerAdmission,\n} from \"@yielded/agent/records\";\nimport {\n AdmissionFence,\n AdmissionGroup,\n AbortCommand,\n AbortIntent,\n AdmissionConflict,\n AdmissionPolicyError,\n ApprovalConflict,\n ApprovalDecisionCommand,\n ApprovalDecisionIntent,\n IdempotencyKey,\n JoinedToHost,\n LedgerError,\n OwnershipLost,\n Principal,\n Settlement,\n SettlementConflict,\n UnknownResolutionCommand,\n UnknownResolutionConflict,\n UnknownResolutionIntent,\n} from \"@yielded/agent/submission-ledger\";\nimport { SubmissionStatus } from \"@yielded/agent/submission-status\";\nimport {\n AppendConflict,\n ThreadNotMaterialized,\n ThreadStoreError,\n} from \"@yielded/agent/thread-store\";\nimport { Context, Crypto, Duration, Effect, Layer, Predicate, Schema, Stream } from \"effect\";\nimport { RpcTargets, RpcTracing } from \"effect-cf\";\n\nimport { DurableAlarmError } from \"./Alarm.ts\";\nimport {\n callThreadObject,\n ThreadObjectNamespace,\n type ThreadObjectRpc,\n} from \"./CloudflareBindings.ts\";\nimport { AdmissionLimitExceeded } from \"./CloudflareConfig.ts\";\nimport { cloudflareFailureSignals, safeCauseMessage } from \"./internal/boundary.ts\";\nimport { cloudflareCryptoLayer } from \"./internal/crypto.ts\";\nimport {\n Frame as LiveTextFrame,\n isBoundedEvent,\n MAX_DRAFT_PARTS,\n MAX_FRAME_BYTES,\n Request as WatchTextRequest,\n} from \"./internal/live-text-protocol.ts\";\n\nexport { Frame as LiveTextFrame } from \"./internal/live-text-protocol.ts\";\n\n/**\n * The Worker↔Thread-Object host protocol (plan §1.4): Schema envelopes for the host\n * entry points (`submitEncoded`, `awaitSettlementEncoded`, `observePage`, `abortEncoded`,\n * `resolveApprovalEncoded`, `resolveUnknownEncoded`) plus the Worker-side client that speaks\n * it. Mirrors the WP2 port protocol: requests and responses are closed Schema unions, typed\n * failures travel as their own tagged classes and RE-DECODE to identical tags on the caller\n * (error-tag fidelity), and protocol anomalies are answered typed instead of thrown.\n */\n\n/** Ceiling for host protocol diagnostic strings. */\nconst MAX_HOST_DIAGNOSTIC_LENGTH = 4_096;\nconst PROGRESS_CANCELLATION_TIMEOUT = \"1 second\";\n\nconst BoundedDiagnostic = Schema.String.check(Schema.isMaxLength(MAX_HOST_DIAGNOSTIC_LENGTH));\n\n/** Truncate a diagnostic string to the host protocol's bounded length. */\nexport const boundHostDiagnostic = (value: string): string =>\n value.length > MAX_HOST_DIAGNOSTIC_LENGTH\n ? `${value.slice(0, MAX_HOST_DIAGNOSTIC_LENGTH - 3)}...`\n : value;\n\n/**\n * The envelope itself could not be honored: the Object could not decode the request, or a\n * response could not be encoded/decoded. Never carries operation semantics.\n */\nexport class HostProtocolError extends Schema.TaggedError<HostProtocolError>()(\n \"HostProtocolError\",\n {\n message: BoundedDiagnostic,\n },\n) {}\n\n/** The Worker-side stub call itself failed (RPC rejection, overload, eviction mid-call). */\nexport class ThreadClientError extends Schema.TaggedError<ThreadClientError>()(\n \"ThreadClientError\",\n {\n threadId: Schema.String,\n message: Schema.String,\n cause: Schema.optionalKey(Schema.Defect()),\n /** Cloudflare's own classification for a failure safe to retry with a fresh stub. */\n retryable: Schema.optionalKey(Schema.Boolean),\n /** Cloudflare overloads are surfaced immediately instead of adding retry pressure. */\n overloaded: Schema.optionalKey(Schema.Boolean),\n },\n) {}\n\n// ---------------------------------------------------------------------------\n// Requests\n// ---------------------------------------------------------------------------\n\n/**\n * One durable submission, input ALREADY encoded by the caller through the Agent Binding's\n * input schema (the Worker bundles the same Agent definitions as the Object, so schema\n * validation happens client-side; the resolved Binding re-validates at claim time). The\n * Thread identity is deliberately absent — the addressed Object IS the lane.\n */\nexport class SubmitRequest extends Schema.Class<SubmitRequest>(\n \"@effect-agent/platform-cloudflare/SubmitRequest\",\n)({\n agentId: AgentId,\n principal: Principal,\n idempotencyKey: IdempotencyKey,\n admissionGroup: Schema.optionalKey(AdmissionGroup),\n admissionFence: Schema.optionalKey(AdmissionFence),\n workerAdmission: Schema.optionalKey(WorkerAdmission),\n messageAdmission: Schema.optionalKey(InputMessage),\n definitions: DefinitionDigests,\n inputPayload: PersistedJson,\n}) {}\n\n/** One bounded page of canonical records after an optional sequence. */\nexport class ObservePageRequest extends Schema.Class<ObservePageRequest>(\n \"@effect-agent/platform-cloudflare/ObservePageRequest\",\n)({\n afterSequence: Schema.optionalKey(CanonicalSequence),\n limit: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1_024)),\n}) {}\n\n/** One event-driven wait for canonical progress strictly after this sequence. */\nexport class AwaitProgressRequest extends Schema.Class<AwaitProgressRequest>(\n \"@effect-agent/platform-cloudflare/AwaitProgressRequest\",\n)({\n afterSequence: CanonicalSequence,\n waiterId: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)),\n}) {}\n\n/** Best-effort cancellation of one in-flight progress RPC. */\nexport class CancelProgressRequest extends Schema.Class<CancelProgressRequest>(\n \"@effect-agent/platform-cloudflare/CancelProgressRequest\",\n)({\n waiterId: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256)),\n}) {}\n\n// ---------------------------------------------------------------------------\n// Responses\n// ---------------------------------------------------------------------------\n\n/**\n * Every typed failure a host entry point can produce, plus the protocol's own errors. Same\n * closed-union discipline as the WP2 `PortFailure`: members re-decode to the SAME tagged\n * classes on the Worker side; `cause` chains travel as Schema defects without instance\n * fidelity (plan §2.8).\n */\nexport const HostFailure = Schema.Union([\n AgentInputError,\n DigestError,\n AdmissionConflict,\n AdmissionPolicyError,\n SettlementConflict,\n ApprovalConflict,\n UnknownResolutionConflict,\n JoinedToHost,\n LedgerError,\n OwnershipLost,\n ThreadStoreError,\n ThreadNotMaterialized,\n AppendConflict,\n DurableRuntimeFailpointError,\n AdmissionLimitExceeded,\n DurableAlarmError,\n OperationDenied,\n HostProtocolError,\n]);\n\nexport type HostFailure = typeof HostFailure.Type;\n\nexport class SubmitSucceeded extends Schema.TaggedClass<SubmitSucceeded>(\n \"@effect-agent/platform-cloudflare/SubmitSucceeded\",\n)(\"SubmitSucceeded\", {\n receipt: Receipt,\n}) {}\n\nexport class SubmissionStatusResponse extends Schema.TaggedClass<SubmissionStatusResponse>(\n \"@effect-agent/platform-cloudflare/SubmissionStatusResponse\",\n)(\"SubmissionStatusResponse\", { status: SubmissionStatus }) {}\n\nexport class SettlementReached extends Schema.TaggedClass<SettlementReached>(\n \"@effect-agent/platform-cloudflare/SettlementReached\",\n)(\"SettlementReached\", {\n settlement: Settlement,\n}) {}\n\n/** The exact canonical record of an operationally finalized Submission. */\nexport class SettlementRecordReached extends Schema.TaggedClass<SettlementRecordReached>(\n \"@effect-agent/platform-cloudflare/SettlementRecordReached\",\n)(\"SettlementRecordReached\", {\n record: SubmissionSettledRecord,\n}) {}\n\nexport class ObservedPage extends Schema.TaggedClass<ObservedPage>(\n \"@effect-agent/platform-cloudflare/ObservedPage\",\n)(\"ObservedPage\", {\n records: Schema.Array(CanonicalRecordEnvelope).check(Schema.isMaxLength(1_024)),\n}) {}\n\n/** A record was already committed or an incarnation-local hint says the caller should re-read. */\nexport class ProgressObserved extends Schema.TaggedClass<ProgressObserved>(\n \"@effect-agent/platform-cloudflare/ProgressObserved\",\n)(\"ProgressObserved\", {}) {}\n\nexport class ProgressCancelled extends Schema.TaggedClass<ProgressCancelled>(\n \"@effect-agent/platform-cloudflare/ProgressCancelled\",\n)(\"ProgressCancelled\", {}) {}\n\nexport class AbortRecorded extends Schema.TaggedClass<AbortRecorded>(\n \"@effect-agent/platform-cloudflare/AbortRecorded\",\n)(\"AbortRecorded\", {\n intent: AbortIntent,\n}) {}\n\nexport class ApprovalRecorded extends Schema.TaggedClass<ApprovalRecorded>(\n \"@effect-agent/platform-cloudflare/ApprovalRecorded\",\n)(\"ApprovalRecorded\", {\n intent: ApprovalDecisionIntent,\n}) {}\n\nexport class UnknownResolutionRecorded extends Schema.TaggedClass<UnknownResolutionRecorded>(\n \"@effect-agent/platform-cloudflare/UnknownResolutionRecorded\",\n)(\"UnknownResolutionRecorded\", {\n intent: UnknownResolutionIntent,\n}) {}\n\n/** The entry point failed TYPED on the Object; the failure re-decodes verbatim. */\nexport class HostFailed extends Schema.TaggedClass<HostFailed>(\n \"@effect-agent/platform-cloudflare/HostFailed\",\n)(\"HostFailed\", {\n failure: HostFailure,\n}) {}\n\n/** The uniform answer of one host entry point. Callers narrow by the tag their call implies. */\nexport const HostResponse = Schema.Union([\n SubmitSucceeded,\n SettlementReached,\n SettlementRecordReached,\n SubmissionStatusResponse,\n ObservedPage,\n ProgressObserved,\n ProgressCancelled,\n AbortRecorded,\n ApprovalRecorded,\n UnknownResolutionRecorded,\n HostFailed,\n]);\n\nexport type HostResponse = typeof HostResponse.Type;\n\n// ---------------------------------------------------------------------------\n// Codecs (shared by the Object endpoints and the Worker client)\n// ---------------------------------------------------------------------------\n\nexport const decodeSubmitRequest = Schema.decodeUnknownEffect(SubmitRequest);\nexport const encodeSubmitRequest = Schema.encodeEffect(SubmitRequest);\nexport const decodeReceipt = Schema.decodeUnknownEffect(Receipt);\nexport const encodeReceipt = Schema.encodeEffect(Receipt);\nexport const decodeObservePageRequest = Schema.decodeUnknownEffect(ObservePageRequest);\nexport const encodeObservePageRequest = Schema.encodeEffect(ObservePageRequest);\nexport const decodeAwaitProgressRequest = Schema.decodeUnknownEffect(AwaitProgressRequest);\nexport const encodeAwaitProgressRequest = Schema.encodeEffect(AwaitProgressRequest);\nexport const decodeCancelProgressRequest = Schema.decodeUnknownEffect(CancelProgressRequest);\nexport const encodeCancelProgressRequest = Schema.encodeEffect(CancelProgressRequest);\nexport const decodeAbortCommand = Schema.decodeUnknownEffect(AbortCommand);\nexport const encodeAbortCommand = Schema.encodeEffect(AbortCommand);\nexport const decodeApprovalDecisionCommand = Schema.decodeUnknownEffect(ApprovalDecisionCommand);\nexport const encodeApprovalDecisionCommand = Schema.encodeEffect(ApprovalDecisionCommand);\nexport const decodeUnknownResolutionCommand = Schema.decodeUnknownEffect(UnknownResolutionCommand);\nexport const encodeUnknownResolutionCommand = Schema.encodeEffect(UnknownResolutionCommand);\nexport const encodeHostResponse = Schema.encodeEffect(HostResponse);\nexport const decodeHostResponse = Schema.decodeUnknownEffect(HostResponse);\n\n// ---------------------------------------------------------------------------\n// Worker-side client\n// ---------------------------------------------------------------------------\n\n/** Failure surface of `CloudflareThreadClient.submit`. */\nconst ClientSubmitHostFailure = Schema.Union([\n AgentInputError,\n DigestError,\n AdmissionConflict,\n AdmissionPolicyError,\n LedgerError,\n OwnershipLost,\n ThreadStoreError,\n ThreadNotMaterialized,\n AppendConflict,\n DurableRuntimeFailpointError,\n AdmissionLimitExceeded,\n DurableAlarmError,\n HostProtocolError,\n]);\n\nconst ClientAwaitHostFailure = Schema.Union([\n LedgerError,\n OwnershipLost,\n SettlementConflict,\n OperationDenied,\n HostProtocolError,\n]);\n\nconst ClientObserveHostFailure = Schema.Union([\n ThreadStoreError,\n ThreadNotMaterialized,\n OperationDenied,\n HostProtocolError,\n]);\n\nconst ClientAbortHostFailure = Schema.Union([\n OperationDenied,\n LedgerError,\n OwnershipLost,\n SettlementConflict,\n JoinedToHost,\n DurableRuntimeFailpointError,\n DurableAlarmError,\n HostProtocolError,\n]);\n\nconst ClientApprovalHostFailure = Schema.Union([\n LedgerError,\n OwnershipLost,\n SettlementConflict,\n ApprovalConflict,\n OperationDenied,\n DurableAlarmError,\n HostProtocolError,\n]);\n\nconst ClientUnknownHostFailure = Schema.Union([\n LedgerError,\n OwnershipLost,\n SettlementConflict,\n UnknownResolutionConflict,\n JoinedToHost,\n DurableRuntimeFailpointError,\n OperationDenied,\n DurableAlarmError,\n HostProtocolError,\n]);\n\nexport type ClientSubmitFailure = typeof ClientSubmitHostFailure.Type | ThreadClientError;\nexport type ClientAwaitFailure = typeof ClientAwaitHostFailure.Type | ThreadClientError;\nexport type ClientObserveFailure = typeof ClientObserveHostFailure.Type | ThreadClientError;\nexport type ClientProgressFailure = ClientObserveFailure;\nexport type ClientAbortFailure = typeof ClientAbortHostFailure.Type | ThreadClientError;\nexport type ClientApprovalFailure = typeof ClientApprovalHostFailure.Type | ThreadClientError;\nexport type ClientUnknownFailure = typeof ClientUnknownHostFailure.Type | ThreadClientError;\n\nconst liveTextProtocolFailure = () =>\n HostProtocolError.make({\n message: \"Provisional text is incomplete or invalid; discard drafts and read canonical records\",\n });\n\nconst decodeLiveText = (\n threadId: ThreadId,\n source: ReadableStream<unknown>,\n): Stream.Stream<LiveTextFrame, HostProtocolError | ThreadClientError> =>\n Stream.suspend(() => {\n const decoder = new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: false });\n const decode = Schema.decodeUnknownSync(Schema.fromJsonString(LiveTextFrame));\n let pending = \"\";\n let pendingBytes = 0;\n let expected = 0;\n let streamId: string | undefined;\n const models = new Map<string, { attemptId: string; parts: Set<string> }>();\n\n const accept = (frame: LiveTextFrame): boolean => {\n if (frame._tag === \"Reset\") {\n if (frame.streamId === streamId || frame.threadId !== threadId)\n throw liveTextProtocolFailure();\n streamId = frame.streamId;\n expected = 1;\n models.clear();\n\n return true;\n }\n if (\n streamId === undefined ||\n frame.streamId !== streamId ||\n frame.sequence !== expected++ ||\n frame.event.threadId !== threadId ||\n !isBoundedEvent(frame.event)\n )\n throw liveTextProtocolFailure();\n const event = frame.event;\n\n if (event._tag === \"AttemptEnded\") {\n for (const [key, model] of models)\n if (model.attemptId === event.attemptId) models.delete(key);\n\n return true;\n }\n const key = JSON.stringify([event.attemptId, event.runId, event.turnId, event.generation]);\n\n if (event._tag === \"Discard\") {\n models.delete(key);\n\n return true;\n }\n let model = models.get(key);\n\n if (event.part.type === \"text-start\") {\n if (model?.parts.has(event.part.id)) throw liveTextProtocolFailure();\n if (\n [...models.values()].reduce((size, value) => size + value.parts.size, 0) >=\n MAX_DRAFT_PARTS\n )\n throw liveTextProtocolFailure();\n if (model === undefined) {\n model = { attemptId: event.attemptId, parts: new Set() };\n models.set(key, model);\n }\n model.parts.add(event.part.id);\n\n return true;\n }\n if (!model?.parts.has(event.part.id)) throw liveTextProtocolFailure();\n if (event.part.type === \"text-end\") {\n model.parts.delete(event.part.id);\n if (model.parts.size === 0) models.delete(key);\n }\n\n return true;\n };\n\n return Stream.fromReadableStream({\n evaluate: () => source,\n // The subscription Scope owns the single bounded cancellation after this reader unlocks.\n releaseLockOnEnd: true,\n onError: (cause) =>\n ThreadClientError.make({\n threadId,\n message: \"Provisional text disconnected; discard drafts and read canonical records\",\n cause,\n }),\n }).pipe(\n Stream.mapEffect((chunk) =>\n Effect.try({\n try: () => {\n if (!(chunk instanceof Uint8Array)) throw liveTextProtocolFailure();\n const frames: LiveTextFrame[] = [];\n\n for (let offset = 0; offset < chunk.byteLength;) {\n const newline = chunk.indexOf(10, offset);\n const end = newline < 0 ? chunk.byteLength : newline;\n\n pendingBytes += end - offset;\n if (pendingBytes > MAX_FRAME_BYTES) throw liveTextProtocolFailure();\n pending += decoder.decode(chunk.subarray(offset, end), { stream: newline < 0 });\n offset = end + 1;\n if (newline < 0) break;\n const frame = decode(pending);\n\n pending = \"\";\n pendingBytes = 0;\n if (accept(frame)) frames.push(frame);\n }\n\n return frames;\n },\n catch: liveTextProtocolFailure,\n }),\n ),\n Stream.flatMap(Stream.fromArray),\n // This connection is open-ended. Clean EOF is also loss of provisional state.\n Stream.concat(Stream.fail(liveTextProtocolFailure())),\n );\n });\n\nconst outOfContract = (threadId: string, operation: string, observed: string): ThreadClientError =>\n ThreadClientError.make({\n threadId,\n message: boundHostDiagnostic(\n `The Thread Object answered ${operation} with the out-of-contract ${observed}.`,\n ),\n });\n\nconst hostRpcMethods = {\n submit: \"submitEncoded\",\n awaitSettlement: \"awaitSettlementEncoded\",\n awaitSettlementRecord: \"awaitSettlementRecordEncoded\",\n submissionStatus: \"submissionStatusEncoded\",\n awaitProgress: \"awaitProgressEncoded\",\n cancelProgress: \"cancelProgressEncoded\",\n observePage: \"observePage\",\n abort: \"abortEncoded\",\n resolveApproval: \"resolveApprovalEncoded\",\n resolveUnknown: \"resolveUnknownEncoded\",\n} as const satisfies Record<string, keyof ThreadObjectRpc>;\n\n/** Worker-side client over the Thread Object namespace (DEPLOY-010). */\nexport class CloudflareThreadClient extends Context.Service<\n CloudflareThreadClient,\n {\n /** Encode the input client-side, then durably submit to the owning Object. */\n readonly submit: <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: DurableSubmitOptions,\n ) => Effect.Effect<Receipt, ClientSubmitFailure, InputSchema[\"EncodingServices\"]>;\n /** Wake-hinted, poll-guaranteed settlement wait executed inside the owning Object. */\n readonly submissionStatus: (\n receipt: Receipt,\n ) => Effect.Effect<SubmissionStatus, ClientAwaitFailure>;\n readonly awaitSettlement: (receipt: Receipt) => Effect.Effect<Settlement, ClientAwaitFailure>;\n /**\n * Wait for finalization and return this Receipt's canonical terminal record in one RPC.\n * Requires both settlement and observation authority. Decode an ordinary completed\n * record's result through the Agent output Schema; joined completion may have no result.\n */\n readonly awaitSettlementRecord: (\n receipt: Receipt,\n ) => Effect.Effect<SubmissionSettledRecord, ClientAwaitFailure>;\n /**\n * Wait without polling until progress after `afterSequence` is already durable or hinted.\n * The result is deliberately void: canonical records remain authoritative and must be read.\n * Interruption waits at most one second for best-effort remote cancellation.\n */\n readonly awaitProgress: (\n threadId: ThreadId,\n afterSequence: CanonicalSequence,\n ) => Effect.Effect<void, ClientProgressFailure>;\n /**\n * Current provisional text followed by native deltas. Reset starts a replacement snapshot,\n * including when a slow consumer exceeds the fixed backlog. Reconcile by\n * Run/Turn identity to canonical records; discard drafts on Discard, AttemptEnded,\n * Reset or stream failure. Snapshots exist only in the Object incarnation's memory.\n * Scope the stream: interruption cancels its remote subscription.\n */\n readonly watchText: (threadId: ThreadId) => Stream.Stream<LiveTextFrame, ClientObserveFailure>;\n /** One bounded page of canonical records. */\n readonly readPage: (\n threadId: ThreadId,\n options?: {\n readonly afterSequence?: CanonicalSequence | undefined;\n readonly limit?: number | undefined;\n },\n ) => Effect.Effect<ReadonlyArray<CanonicalRecordEnvelope>, ClientObserveFailure>;\n /**\n * Every canonical record up to the CURRENT committed tail, via repeated pages. A\n * snapshot read, not a live observation — callers wanting liveness re-read after\n * `awaitSettlement`.\n */\n readonly readAll: (\n threadId: ThreadId,\n ) => Effect.Effect<ReadonlyArray<CanonicalRecordEnvelope>, ClientObserveFailure>;\n /**\n * Submission-addressed operations take the owning Thread explicitly (from the\n * Receipt): minted Submission identities stay OPAQUE outside the storage adapter that\n * minted them (D-P6-5), so the client never parses one to find the lane.\n */\n readonly abort: (\n threadId: ThreadId,\n command: AbortCommand,\n ) => Effect.Effect<AbortIntent, ClientAbortFailure>;\n readonly resolveApproval: (\n threadId: ThreadId,\n command: ApprovalDecisionCommand,\n ) => Effect.Effect<ApprovalDecisionIntent, ClientApprovalFailure>;\n readonly resolveUnknown: (\n threadId: ThreadId,\n command: UnknownResolutionCommand,\n ) => Effect.Effect<UnknownResolutionIntent, ClientUnknownFailure>;\n }\n>()(\"@effect-agent/platform-cloudflare/CloudflareThreadClient\") {\n /**\n * Assemble the client from a resolved namespace and the platform Crypto implementation.\n * rpcTracing is the binding name and remains opt-in. Caller authentication, principals,\n * idempotency keys, and definition digests are still explicit submission inputs.\n */\n static layerFromBinding(options: {\n readonly namespace: DurableObjectNamespace<ThreadObjectRpc>;\n readonly rpcTracing?: string;\n }): Layer.Layer<CloudflareThreadClient> {\n return CloudflareThreadClient.layer.pipe(\n Layer.provide([\n ThreadObjectNamespace.layer(options.namespace, options),\n cloudflareCryptoLayer,\n ]),\n );\n }\n\n static readonly layer: Layer.Layer<\n CloudflareThreadClient,\n never,\n ThreadObjectNamespace | Crypto.Crypto\n > = Layer.effect(CloudflareThreadClient)(\n Effect.gen(function* () {\n const namespace = yield* ThreadObjectNamespace;\n const { rpcTracing } = namespace;\n const crypto = yield* Crypto.Crypto;\n\n const call = Effect.fnUntraced(\n function* (\n threadId: ThreadId,\n operation: keyof typeof hostRpcMethods,\n encoded: unknown,\n ): Effect.fn.Return<HostResponse, ThreadClientError | HostProtocolError> {\n // Empty arguments preserve native arity. Passing `undefined` still adds an argument.\n const traceArgs =\n rpcTracing === undefined ? [] : yield* RpcTracing.withRpcTraceContext([]);\n\n const raw = yield* callThreadObject(\n threadId,\n (stub) => stub[hostRpcMethods[operation]](encoded, ...traceArgs),\n (cause) =>\n ThreadClientError.make({\n threadId,\n message: boundHostDiagnostic(\n `${operation} did not reach the Thread Object: ${safeCauseMessage(\n cause,\n \"the RPC failed without a diagnostic\",\n )}`,\n ),\n cause,\n ...cloudflareFailureSignals(cause),\n }),\n ).pipe(Effect.provideService(ThreadObjectNamespace, namespace));\n\n return yield* decodeHostResponse(raw).pipe(\n Effect.mapError((error): HostProtocolError =>\n HostProtocolError.make({\n message: boundHostDiagnostic(\n `The ${operation} answer could not be decoded: ${error.message}`,\n ),\n }),\n ),\n );\n },\n (effect, threadId, operation) =>\n rpcTracing === undefined\n ? Effect.withSpan(effect, \"CloudflareThreadClient.call\", {\n attributes: { threadId, operation },\n })\n : RpcTracing.withRpcClientSpan(effect, rpcTracing, hostRpcMethods[operation]),\n );\n\n const expect = <ResultSchema extends Schema.Top, FailureSchema extends Schema.Top>(\n threadId: string,\n operation: string,\n resultSchema: ResultSchema,\n failureSchema: FailureSchema,\n ) => {\n const isExpectedResult = Schema.is(resultSchema);\n const isExpectedFailure = Schema.is(failureSchema);\n\n return (\n response: HostResponse,\n ): Effect.Effect<ResultSchema[\"Type\"], FailureSchema[\"Type\"] | ThreadClientError> => {\n if (response._tag === \"HostFailed\") {\n const failure = response.failure;\n\n return isExpectedFailure(failure)\n ? Effect.fail(failure)\n : Effect.fail(outOfContract(threadId, operation, `failure ${failure._tag}`));\n }\n if (!isExpectedResult(response)) {\n return Effect.fail(outOfContract(threadId, operation, `result ${response._tag}`));\n }\n\n return Effect.succeed(response);\n };\n };\n\n const readPage = (\n threadId: ThreadId,\n options?: {\n readonly afterSequence?: CanonicalSequence | undefined;\n readonly limit?: number | undefined;\n },\n ) =>\n Effect.gen(function* () {\n const request = ObservePageRequest.make({\n ...(options?.afterSequence === undefined\n ? {}\n : { afterSequence: options.afterSequence }),\n limit: options?.limit ?? 256,\n });\n\n const encoded = yield* encodeObservePageRequest(request).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`observePage request encode failed: ${error.message}`),\n }),\n ),\n );\n\n const response = yield* call(threadId, \"observePage\", encoded);\n\n const page = yield* expect(\n threadId,\n \"observePage\",\n ObservedPage,\n ClientObserveHostFailure,\n )(response);\n\n return page.records;\n });\n\n const cancelProgress = (threadId: ThreadId, waiterId: string): Effect.Effect<void> =>\n encodeCancelProgressRequest(CancelProgressRequest.make({ waiterId })).pipe(\n Effect.mapError(() => undefined),\n Effect.flatMap((encoded) => call(threadId, \"cancelProgress\", encoded)),\n // Finalizers are uninterruptible; only the foreign RPC branch must remain\n // interruptible so a lost cancellation reply cannot prevent local shutdown.\n Effect.interruptible,\n Effect.timeout(PROGRESS_CANCELLATION_TIMEOUT),\n Effect.asVoid,\n Effect.ignore,\n );\n\n return CloudflareThreadClient.of({\n submit: <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: DurableSubmitOptions,\n ) =>\n Effect.gen(function* () {\n // Client-side half of `DurableAgentRuntime.submit`'s input boundary: encode\n // through the Agent's input schema and prove the canonical persistence bounds.\n const encodedInput = yield* Schema.encodeEffect(agent.definition.input)(input).pipe(\n Effect.mapError((cause) =>\n AgentInputError.make({ message: `Unable to encode Agent input: ${cause.message}` }),\n ),\n );\n\n const inputPayload = yield* Schema.decodeUnknownEffect(PersistedJson)(\n encodedInput,\n ).pipe(\n Effect.mapError(() =>\n AgentInputError.make({\n message: \"Agent input does not satisfy the canonical persistence bounds\",\n }),\n ),\n );\n\n const request = SubmitRequest.make({\n agentId: agent.definition.id,\n principal: options.principal,\n idempotencyKey: options.idempotencyKey,\n ...(options.admissionGroup === undefined\n ? {}\n : { admissionGroup: options.admissionGroup }),\n ...(options.admissionFence === undefined\n ? {}\n : { admissionFence: options.admissionFence }),\n ...(options.workerAdmission === undefined\n ? {}\n : { workerAdmission: options.workerAdmission }),\n ...(options.messageAdmission === undefined\n ? {}\n : { messageAdmission: options.messageAdmission }),\n definitions: options.definitions,\n inputPayload,\n });\n\n const encoded = yield* encodeSubmitRequest(request).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`submit request encode failed: ${error.message}`),\n }),\n ),\n );\n\n const response = yield* call(options.threadId, \"submit\", encoded);\n\n const succeeded = yield* expect(\n options.threadId,\n \"submit\",\n SubmitSucceeded,\n ClientSubmitHostFailure,\n )(response);\n\n return succeeded.receipt;\n }),\n\n submissionStatus: (receipt) =>\n Effect.gen(function* () {\n const encoded = yield* encodeReceipt(receipt).pipe(\n Effect.mapError(() => HostProtocolError.make({ message: \"Invalid receipt\" })),\n );\n\n const response = yield* call(receipt.threadId, \"submissionStatus\", encoded);\n\n const result = yield* expect(\n receipt.threadId,\n \"submissionStatus\",\n SubmissionStatusResponse,\n ClientAwaitHostFailure,\n )(response);\n\n return result.status;\n }),\n awaitSettlement: (receipt) =>\n Effect.gen(function* () {\n const encoded = yield* encodeReceipt(receipt).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`receipt encode failed: ${error.message}`),\n }),\n ),\n );\n\n const response = yield* call(receipt.threadId, \"awaitSettlement\", encoded);\n\n const settled = yield* expect(\n receipt.threadId,\n \"awaitSettlement\",\n SettlementReached,\n ClientAwaitHostFailure,\n )(response);\n\n return settled.settlement;\n }),\n\n awaitSettlementRecord: (receipt) =>\n Effect.gen(function* () {\n const encoded = yield* encodeReceipt(receipt).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`receipt encode failed: ${error.message}`),\n }),\n ),\n );\n\n const response = yield* call(receipt.threadId, \"awaitSettlementRecord\", encoded);\n\n const settled = yield* expect(\n receipt.threadId,\n \"awaitSettlementRecord\",\n SettlementRecordReached,\n ClientAwaitHostFailure,\n )(response);\n\n return settled.record;\n }),\n\n awaitProgress: (threadId, afterSequence) =>\n Effect.gen(function* () {\n const waiterId = yield* crypto.randomUUIDv4().pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(\n `awaitProgress cancellation identity generation failed: ${error.message}`,\n ),\n }),\n ),\n );\n\n const request = AwaitProgressRequest.make({ afterSequence, waiterId });\n\n const encoded = yield* encodeAwaitProgressRequest(request).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(\n `awaitProgress request encode failed: ${error.message}`,\n ),\n }),\n ),\n );\n\n const attempt = (retry: number): Effect.Effect<void, ClientProgressFailure> =>\n call(threadId, \"awaitProgress\", encoded).pipe(\n Effect.flatMap(\n expect(threadId, \"awaitProgress\", ProgressObserved, ClientObserveHostFailure),\n ),\n Effect.asVoid,\n Effect.catchTag(\"ThreadClientError\", (error) =>\n error.retryable === true && error.overloaded !== true && retry < 5\n ? Effect.sleep(Duration.millis(10 * 2 ** retry)).pipe(\n Effect.andThen(attempt(retry + 1)),\n )\n : Effect.fail(error),\n ),\n );\n\n yield* attempt(0).pipe(Effect.onInterrupt(() => cancelProgress(threadId, waiterId)));\n }),\n\n watchText: (threadId) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const traceArgs =\n rpcTracing === undefined ? [] : yield* RpcTracing.withRpcTraceContext([]);\n\n const openingFailure = (cause: unknown) =>\n ThreadClientError.make({\n threadId,\n message: \"Provisional text observation could not reach the Thread Object\",\n cause,\n ...cloudflareFailureSignals(cause),\n });\n\n // Retain the original RPC promise: resolving through callThreadObject would\n // erase its optional native disposer before an interrupted opening can use it.\n const target = yield* RpcTargets.get(namespace, threadId, () =>\n namespace.get(threadId),\n ).pipe(Effect.mapError(openingFailure));\n\n let request: Promise<unknown> | undefined;\n let received: unknown;\n let closed = false;\n\n const cancel = () => {\n const value = received;\n\n received = undefined;\n\n return value instanceof ReadableStream && !value.locked\n ? value.cancel().catch(() => undefined)\n : Promise.resolve();\n };\n\n // Install ownership before invoking foreign code, not after its promise settles.\n yield* Effect.addFinalizer(() =>\n Effect.try({\n try: () => {\n closed = true;\n if (Predicate.hasProperty(request, Symbol.dispose)) {\n const dispose = request[Symbol.dispose];\n\n if (typeof dispose === \"function\") dispose.call(request);\n }\n },\n catch: () => undefined,\n }).pipe(\n Effect.ignore,\n Effect.andThen(\n Effect.tryPromise({ try: cancel, catch: () => undefined }).pipe(\n Effect.interruptible,\n Effect.timeout(PROGRESS_CANCELLATION_TIMEOUT),\n Effect.ignore,\n ),\n ),\n ),\n );\n\n const raw = yield* Effect.tryPromise({\n try: () => {\n request = target.watchTextEncoded(\n Schema.encodeSync(WatchTextRequest)({ schemaVersion: 1 }),\n ...traceArgs,\n );\n\n return request.then((value) => {\n received = value;\n\n // A custom endpoint may return a plain, non-cancellable promise. Keep\n // late cleanup on that native promise chain; it starts no Effect fiber.\n return closed ? cancel().then(() => value) : value;\n });\n },\n catch: openingFailure,\n }).pipe(\n Effect.interruptible,\n Effect.tapCause(() => RpcTargets.invalidate(target)),\n );\n\n if (raw instanceof ReadableStream) return decodeLiveText(threadId, raw);\n\n const response = yield* decodeHostResponse(raw).pipe(\n Effect.mapError(liveTextProtocolFailure),\n );\n\n if (\n response._tag === \"HostFailed\" &&\n Schema.is(ClientObserveHostFailure)(response.failure)\n )\n return yield* response.failure;\n\n return yield* liveTextProtocolFailure();\n }),\n ),\n\n readPage,\n\n readAll: (threadId) =>\n Effect.gen(function* () {\n const all: Array<CanonicalRecordEnvelope> = [];\n let after: CanonicalSequence | undefined;\n\n for (;;) {\n const page = yield* readPage(threadId, { afterSequence: after, limit: 1_024 });\n\n all.push(...page);\n const last = page.at(-1);\n\n if (page.length < 1_024 || last === undefined) return all;\n after = last.sequence;\n }\n }),\n\n abort: (threadId, command) =>\n Effect.gen(function* () {\n const encoded = yield* encodeAbortCommand(command).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`abort command encode failed: ${error.message}`),\n }),\n ),\n );\n\n const response = yield* call(threadId, \"abort\", encoded);\n\n const recorded = yield* expect(\n threadId,\n \"abort\",\n AbortRecorded,\n ClientAbortHostFailure,\n )(response);\n\n return recorded.intent;\n }),\n\n resolveApproval: (threadId, command) =>\n Effect.gen(function* () {\n const encoded = yield* encodeApprovalDecisionCommand(command).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(`approval command encode failed: ${error.message}`),\n }),\n ),\n );\n\n const response = yield* call(threadId, \"resolveApproval\", encoded);\n\n const recorded = yield* expect(\n threadId,\n \"resolveApproval\",\n ApprovalRecorded,\n ClientApprovalHostFailure,\n )(response);\n\n return recorded.intent;\n }),\n\n resolveUnknown: (threadId, command) =>\n Effect.gen(function* () {\n const encoded = yield* encodeUnknownResolutionCommand(command).pipe(\n Effect.mapError((error) =>\n HostProtocolError.make({\n message: boundHostDiagnostic(\n `resolution command encode failed: ${error.message}`,\n ),\n }),\n ),\n );\n\n const response = yield* call(threadId, \"resolveUnknown\", encoded);\n\n const recorded = yield* expect(\n threadId,\n \"resolveUnknown\",\n UnknownResolutionRecorded,\n ClientUnknownHostFailure,\n )(response);\n\n return recorded.intent;\n }),\n });\n }),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAQA,MAAa,wBAAoD,MAAM,OACrE,OAAO,QACP,OAAO,IAAI,aAAa;CACtB,MAAM,OAAO,OAAO,OAAO;CAC3B,MAAM,YAAY,OAAO,cAAc;CACvC,MAAM,cAAsB;CAE5B,OAAO,OAAO,OAAO,GAAG;EACtB,GAAG;EACH,SAAS,WAAW,SAAS;GAC3B,IACE,cAAc,aACd,EAAE,YAAY,gBACd,cAAc,YAAY,UAC1B,OAAO,UAAU,QAAQ,WAAW,YAEpC,OAAO,KAAK,OAAO,WAAW,IAAI;GAEpC,OAAO,OAAO,IAAI;IAChB,WAAW,WAAW,KAAK,WAAW,QAAQ,CAAC,CAAC,OAAO,IAAI,WAAW,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC;IACrF,QAAQ,UACN,cAAc,YAAY;KACxB,QAAQ;KACR,QAAQ;KACR,MAAM;KACN,aAAa;KACb;IACF,CAAC;GACL,CAAC;EACH;CACF,CAAC;AACH,CAAC,CACH,CAAC,CAAC,KAAK,MAAM,QAAQ,cAAc,KAAK,CAAC;;;ACpCzC,MAAa,kBAAkB;AAE/B,MAAa,mBAAmB;AAIhC,MAAa,mBAAmB;AAEhC,MAAM,WAAW,OAAO,eAAe,MAAM,OAAO,YAAA,GAAyB,CAAC;AAE9E,MAAa,UAAU,OAAO,OAAO,EAAE,eAAe,OAAO,QAAQ,CAAC,EAAE,CAAC;;;;;AAMzE,MAAa,QAAQ,OAAO,MAAM,CAChC,OAAO,aAAa,SAAS;CAC3B,eAAe,OAAO,QAAQ,CAAC;CAC/B;CACA,UA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AAa;IACtB,MAAM,UAAU,OAAO,mBAAmB,OAAO,CAAC,CAAC,KACjD,OAAO,UAAU,UACf,kBAAkB,KAAK,EACrB,SAAS,oBAAoB,gCAAgC,MAAM,SAAS,EAC9E,CAAC,CACH,CACF;IAEA,MAAM,WAAW,OAAO,KAAK,UAAU,SAAS,OAAO;IASvD,QAAO,OAPiB,OACtB,UACA,SACA,eACA,sBACF,CAAC,CAAC,QAAQ,EAAA,CAEM;GAClB,CAAC;GAEH,kBAAkB,UAAU,YAC1B,OAAO,IAAI,aAAa;IACtB,MAAM,UAAU,OAAO,8BAA8B,OAAO,CAAC,CAAC,KAC5D,OAAO,UAAU,UACf,kBAAkB,KAAK,EACrB,SAAS,oBAAoB,mCAAmC,MAAM,SAAS,EACjF,CAAC,CACH,CACF;IAEA,MAAM,WAAW,OAAO,KAAK,UAAU,mBAAmB,OAAO;IASjE,QAAO,OAPiB,OACtB,UACA,mBACA,kBACA,yBACF,CAAC,CAAC,QAAQ,EAAA,CAEM;GAClB,CAAC;GAEH,iBAAiB,UAAU,YACzB,OAAO,IAAI,aAAa;IACtB,MAAM,UAAU,OAAO,+BAA+B,OAAO,CAAC,CAAC,KAC7D,OAAO,UAAU,UACf,kBAAkB,KAAK,EACrB,SAAS,oBACP,qCAAqC,MAAM,SAC7C,EACF,CAAC,CACH,CACF;IAEA,MAAM,WAAW,OAAO,KAAK,UAAU,kBAAkB,OAAO;IAShE,QAAO,OAPiB,OACtB,UACA,kBACA,2BACA,wBACF,CAAC,CAAC,QAAQ,EAAA,CAEM;GAClB,CAAC;EACL,CAAC;CACH,CAAC,CACH;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ThreadObject-CgXZMlr4.mjs","names":["DueQueue.Messages","DueQueue.Lifecycle","layer","DueQueue.Native","DueQueue.Publication","DueQueue.Projection","DueQueue.Messages","DueQueue.Lifecycle","DueQueue.HostLaneId","runStorageLayer","WatchTextRequest","EffectCfDurableObjectState","EffectCfDurableObject"],"sources":["../src/internal/live-text.ts","../src/internal/message-delivery.ts","../src/internal/progress-wait.ts","../src/internal/transport.ts","../src/internal/layers.ts","../src/ThreadObject.ts"],"sourcesContent":["import { type ThreadId } from \"@yielded/agent/identifiers\";\nimport { Publisher, type Event } from \"@yielded/agent/provisional-text\";\nimport { Cause, Context, Effect, Exit, Layer, Queue, Schema, Scope, Stream } from \"effect\";\nimport * as Response from \"effect/ai/Response\";\n\nimport { HostProtocolError } from \"../CloudflareThreadClient.ts\";\nimport {\n BUFFER_SIZE,\n Frame,\n isBoundedEvent,\n MAX_DELTA_LENGTH,\n MAX_DRAFT_LENGTH,\n MAX_DRAFT_PARTS,\n MAX_FRAME_BYTES,\n MAX_ID_LENGTH,\n MAX_OBSERVERS,\n} from \"./live-text-protocol.ts\";\n\ntype TextEvent = Extract<Event, { readonly _tag: \"Text\" }>;\n\ninterface Draft {\n readonly start: TextEvent;\n text: string;\n ended: boolean;\n}\n\ninterface Observer {\n readonly threadId: ThreadId;\n readonly queue: Queue.Queue<Event | undefined, HostProtocolError>;\n snapshot: boolean;\n streamId: string;\n sequence: number;\n}\n\n/** One Object incarnation; owns drafts and subscriptions independently of RPC event scopes. */\nexport class LiveTextHub extends Context.Service<\n LiveTextHub,\n {\n readonly open: (\n threadId: ThreadId,\n ) => Effect.Effect<ReadableStream<Uint8Array>, HostProtocolError>;\n }\n>()(\"@effect-agent/platform-cloudflare/LiveTextHub\") {\n static readonly layer: Layer.Layer<LiveTextHub> = Layer.effectContext(\n Effect.gen(function* () {\n const owner = yield* Effect.scope;\n const observers = new Set<Observer>();\n const drafts = new Map<string, Draft>();\n let length = 0;\n\n let unavailable:\n | { readonly error: HostProtocolError; readonly attemptId: Event[\"attemptId\"] }\n | undefined;\n\n const encode = Schema.encodeEffect(Schema.fromJsonString(Frame));\n const encoder = new TextEncoder();\n\n yield* Effect.addFinalizer(() => Effect.sync(() => drafts.clear()));\n\n const fail = (attemptId: Event[\"attemptId\"]) => {\n const error = HostProtocolError.make({\n message:\n \"Provisional text exceeds its draft bounds or is invalid; read canonical records\",\n });\n\n unavailable = { error, attemptId };\n drafts.clear();\n length = 0;\n for (const observer of observers) {\n observer.snapshot = true;\n Queue.failCauseUnsafe(observer.queue, Cause.fail(error));\n Queue.shutdownUnsafe(observer.queue);\n }\n\n return false;\n };\n\n const offerUnsafe = (event: Event): boolean => {\n // Retain drafts even without subscribers. Invalid input disables previews until an\n // offending Attempt ends; canonical execution never depends on the observer's state.\n if (event._tag === \"AttemptEnded\" && event.attemptId === unavailable?.attemptId)\n unavailable = undefined;\n if (unavailable !== undefined) return false;\n if (!isBoundedEvent(event)) {\n // Drop an oversized terminal frame without disabling an already-ended Attempt.\n return event._tag === \"AttemptEnded\" ? false : fail(event.attemptId);\n }\n\n if (event._tag === \"Text\") {\n const key = JSON.stringify([\n event.threadId,\n event.submissionId,\n event.attemptId,\n event.runId,\n event.turnId,\n event.generation,\n event.part.id,\n ]);\n\n const draft = drafts.get(key);\n\n if (event.part.type === \"text-start\") {\n if (draft !== undefined || drafts.size >= MAX_DRAFT_PARTS) return fail(event.attemptId);\n drafts.set(key, { start: event, text: \"\", ended: false });\n } else {\n // After invalidation, never expose an orphaned suffix as a complete prefix.\n if (draft === undefined) return false;\n if (draft.ended) return fail(event.attemptId);\n if (event.part.type === \"text-delta\") {\n if (length + event.part.delta.length > MAX_DRAFT_LENGTH) return fail(event.attemptId);\n draft.text += event.part.delta;\n length += event.part.delta.length;\n } else {\n draft.ended = true;\n }\n }\n } else {\n for (const [key, draft] of drafts) {\n const start = draft.start;\n\n if (\n start.threadId === event.threadId &&\n start.submissionId === event.submissionId &&\n start.attemptId === event.attemptId &&\n (event._tag === \"AttemptEnded\" ||\n (start.runId === event.runId &&\n start.turnId === event.turnId &&\n start.generation === event.generation))\n ) {\n drafts.delete(key);\n length -= draft.text.length;\n }\n }\n }\n\n // No snapshot copying, encoding, I/O or awaited work on the producer's path.\n for (const observer of observers) {\n if (observer.threadId !== event.threadId) continue;\n if (!Queue.offerUnsafe(observer.queue, event)) observer.snapshot = true;\n }\n\n return true;\n };\n\n const open = Effect.fnUntraced(function* (threadId: ThreadId) {\n if (unavailable !== undefined) return yield* unavailable.error;\n if (threadId.length > MAX_ID_LENGTH || observers.size >= MAX_OBSERVERS)\n return yield* HostProtocolError.make({\n message: \"Provisional text observation capacity exceeded\",\n });\n const scope = yield* Scope.fork(owner);\n const queue = yield* Queue.dropping<Event | undefined, HostProtocolError>(BUFFER_SIZE);\n\n const observer: Observer = {\n threadId,\n queue,\n snapshot: true,\n streamId: \"\",\n sequence: 0,\n };\n\n const close = Scope.close(scope, Exit.void);\n\n yield* Scope.addFinalizer(\n scope,\n Effect.sync(() => {\n observer.snapshot = true;\n observers.delete(observer);\n Queue.shutdownUnsafe(queue);\n }),\n );\n observers.add(observer);\n Queue.offerUnsafe(queue, undefined);\n\n const frame = (event: Event): Frame => ({\n _tag: \"Event\",\n schemaVersion: 1,\n streamId: observer.streamId,\n sequence: ++observer.sequence,\n event,\n });\n\n const snapshot = function* (): Generator<Frame> {\n // Capture immutable strings once, then encode bounded slices on consumer pulls.\n // Queue drain and capture are synchronous so no delta can straddle the snapshot.\n while (Queue.sizeUnsafe(queue) > 0) Queue.takeUnsafe(queue);\n\n const current = Array.from(drafts.values())\n .filter((draft) => draft.start.threadId === threadId)\n .map((draft) => ({ ...draft }));\n\n observer.snapshot = false;\n observer.streamId = crypto.randomUUID();\n observer.sequence = 0;\n yield {\n _tag: \"Reset\",\n schemaVersion: 1,\n streamId: observer.streamId,\n threadId,\n sequence: 0,\n };\n for (const draft of current) {\n yield frame(draft.start);\n for (let offset = 0; offset < draft.text.length; offset += MAX_DELTA_LENGTH) {\n yield frame({\n ...draft.start,\n part: Response.makePart(\"text-delta\", {\n id: draft.start.part.id,\n delta: draft.text.slice(offset, offset + MAX_DELTA_LENGTH),\n }),\n });\n }\n if (draft.ended)\n yield frame({\n ...draft.start,\n part: Response.makePart(\"text-end\", { id: draft.start.part.id }),\n });\n }\n };\n\n const toBytes = Effect.fnUntraced(function* (value: Frame) {\n const json = yield* encode(value).pipe(\n Effect.mapError(() =>\n HostProtocolError.make({ message: \"Provisional text frame is invalid\" }),\n ),\n );\n\n const bytes = encoder.encode(json + \"\\n\");\n\n if (bytes.byteLength > MAX_FRAME_BYTES)\n return yield* HostProtocolError.make({\n message: \"Provisional text frame exceeds its wire bound\",\n });\n\n return bytes;\n });\n\n const frames = Stream.fromEffectRepeat(Queue.take(queue)).pipe(\n Stream.flatMap((event) =>\n observer.snapshot || event === undefined\n ? Stream.fromIterable(snapshot(), { chunkSize: 1 }).pipe(\n Stream.takeWhile(() => !observer.snapshot),\n )\n : Stream.succeed(frame(event)),\n ),\n Stream.mapEffect(toBytes),\n Stream.ensuring(close),\n );\n\n return yield* Stream.toReadableStreamEffect(frames);\n });\n\n return Context.make(LiveTextHub, { open }).pipe(Context.add(Publisher, { offerUnsafe }));\n }),\n );\n}\n","import { type ThreadId } from \"@yielded/agent/identifiers\";\nimport {\n MessageDeliveryDriver,\n MessageDeliveryError,\n MessageDeliveryStore,\n} from \"@yielded/agent/message-delivery\";\nimport { WakeScheduler } from \"@yielded/agent/wake-scheduler\";\nimport { Clock, Context, Effect, Layer, Option } from \"effect\";\n\nimport { DurableAlarmError, ThreadMessageDelivery, ThreadMutationGate } from \"../Alarm.ts\";\nimport { ThreadObjectPlacement } from \"../CloudflareBindings.ts\";\nimport * as DueQueue from \"./due-queue.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\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(body, {\n invalidatesRecovery: false,\n lanes: [\n DueQueue.Messages,\n ...(store.lifecyclePublications === undefined ? [] : [DueQueue.Lifecycle]),\n ],\n })\n .pipe(\n Effect.catchTag(\"DurableAlarmError\", (cause) =>\n MessageDeliveryError.make({\n reason: \"storage\",\n operation: \"prearm message delivery\",\n cause,\n }),\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) => local(owner, 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.succeed(Option.fromNullishOr(deadline)) };\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(\n Effect.andThen(store.nextDeadline()),\n Effect.map(Option.fromNullishOr),\n Effect.mapError(failure(\"dispatch message delivery\")),\n ),\n };\n }).pipe(Effect.mapError(failure(\"prepare message delivery\")));\n\n return Context.make(ThreadMessageDelivery, {\n prepare,\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.fnUntraced(function* (\n waiterId: string,\n ): Effect.fn.Return<Effect.Effect<void>, never, Scope.Scope> {\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 ? Effect.void : Deferred.await(deferred);\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.fnUntraced(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 \"@yielded/agent-storage-cloudflare/port-routing\";\nimport type { ThreadId } from \"@yielded/agent/identifiers\";\nimport { Effect, Layer } from \"effect\";\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.fnUntraced(\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 { SqliteClient } from \"@effect/sql-sqlite-do\";\nimport { doMessageDeliveryStoreLayer } from \"@yielded/agent-storage-cloudflare/do-message-delivery-store\";\nimport {\n type DoStorageFailpointHandler,\n type DoStorageFailpoint,\n} from \"@yielded/agent-storage-cloudflare/do-storage-failpoint\";\nimport { submissionLedgerLayer } from \"@yielded/agent-storage-cloudflare/do-submission-ledger\";\nimport {\n threadStoreLayer,\n storageConfigLayer,\n storageFailpointLayer,\n sqlOwnerLayer,\n type DoStorageInitializationError,\n type DoStorageOptions,\n} from \"@yielded/agent-storage-cloudflare/do-thread-store\";\nimport {\n type PortRequest,\n type PortResponse,\n} from \"@yielded/agent-storage-cloudflare/port-protocol\";\nimport {\n executePortRequest,\n makeLocalSubmissionLookup,\n routedMessageDeliveryStoreLayer,\n routedThreadStoreLayer,\n routedSubmissionLedgerLayer,\n routedSettlementPublisherLayer,\n routedWorkerAdmissionLayer,\n} from \"@yielded/agent-storage-cloudflare/port-routing\";\nimport {\n SqlStorageProgress,\n SqlStorageProgressError,\n} from \"@yielded/agent-storage-sql/sql-storage-progress\";\nimport {\n compileRegistrations,\n type AgentRegistration,\n type ResolvedBinding,\n} from \"@yielded/agent/agent-registration\";\nimport { type DigestError } from \"@yielded/agent/digest\";\nimport { DurableAgentRuntime, DurableRuntimeConfig } from \"@yielded/agent/durable-agent-runtime\";\nimport {\n DurableRuntimeFailpoint,\n type DurableRuntimeFailpointHandler,\n} from \"@yielded/agent/durable-failpoint\";\nimport { ThreadId, type SubmissionId } from \"@yielded/agent/identifiers\";\nimport type { LifecyclePublicationHandler } from \"@yielded/agent/lifecycle-publication\";\nimport {\n drainLifecyclePublications,\n LifecyclePublicationError,\n LifecyclePublicationFact,\n lifecyclePublicationLayer,\n} from \"@yielded/agent/lifecycle-publication\";\nimport {\n type MessageDeliveryStore,\n MessageDeliveryDriver,\n type MessageDeliveryError,\n} from \"@yielded/agent/message-delivery\";\nimport {\n operationAuthorizerLayer,\n type OperationAuthorizerService,\n} from \"@yielded/agent/operation-authorizer\";\nimport { ProducerId } from \"@yielded/agent/records\";\nimport {\n type RunContextPreparation,\n type RunCostEstimator,\n type RunToolFailureObserver,\n} from \"@yielded/agent/run-options\";\nimport {\n CurrentToolFailureObserver,\n RunContextPreparationPassthrough,\n RunToolAuthorization,\n toolFailureObserverLayer,\n} from \"@yielded/agent/run-options\";\nimport type { RunStorage } from \"@yielded/agent/run-storage\";\nimport { layer as runStorageLayer, StorageOwner } from \"@yielded/agent/run-storage\";\nimport { SettlementPublisher, validatePublication } from \"@yielded/agent/settlement-publisher\";\nimport { SqlStorageOwner } from \"@yielded/agent/sql-memory-store\";\nimport {\n LedgerError,\n SubmissionLedger,\n type SubmissionSnapshot,\n type AdmissionRequest,\n type SettlementFinalization,\n type WorkerStopCommand,\n} from \"@yielded/agent/submission-ledger\";\nimport { ThreadProjectionMaintenance } from \"@yielded/agent/thread-projection-maintenance\";\nimport type { ThreadReader } from \"@yielded/agent/thread-store\";\nimport { AppendResult, ThreadStoreError, ThreadStore } from \"@yielded/agent/thread-store\";\nimport { ToolReconciler } from \"@yielded/agent/tool-reconciler\";\nimport { type WakeScheduler } from \"@yielded/agent/wake-scheduler\";\nimport {\n type Crypto,\n Cause,\n Clock,\n Context,\n Duration,\n Effect,\n Exit,\n ErrorReporter,\n Layer,\n Match,\n Schema,\n Semaphore,\n Option,\n} from \"effect\";\nimport { SqlClient } from \"effect/sql/SqlClient\";\n\nimport {\n type ThreadRecoveryEvents,\n DurableAlarmError,\n ThreadMaintenance,\n ThreadNativeMaintenance,\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} 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 { cloudflareCryptoLayer } from \"./crypto.ts\";\nimport * as DueQueue from \"./due-queue.ts\";\nimport { LiveTextHub } from \"./live-text.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 100. */\n readonly alarmBackoffBase?: number | undefined;\n /** Failed/no-progress exponential backoff ceiling in milliseconds; default 5000. */\n readonly alarmBackoffCap?: number | undefined;\n /** Milliseconds; default 500. */\n readonly settlementPollInterval?: 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 | LiveTextHub;\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 the defaulted ThreadMessageDelivery and ThreadHostMaintenance\n * references so rebuilt maintenance retains message recovery and lifecycle publication lanes.\n */\nexport type CloudflareDurableRuntimeServices =\n | DurableAgentRuntime\n | SubmissionLedger\n | ThreadStore\n | ThreadReader\n | RunStorage\n | StorageOwner\n | SettlementPublisher\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 alarmBackoffBase: options.alarmBackoffBase ?? CLOUDFLARE_RUNTIME_DEFAULTS.alarmBackoffBase,\n alarmBackoffCap: options.alarmBackoffCap ?? CLOUDFLARE_RUNTIME_DEFAULTS.alarmBackoffCap,\n settlementPollInterval:\n options.settlementPollInterval ?? CLOUDFLARE_RUNTIME_DEFAULTS.settlementPollInterval,\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 abortPollInterval: Duration.millis(config.abortPollInterval),\n ...(options.estimateCostMicrousd === undefined\n ? {}\n : { estimateCostMicrousd: options.estimateCostMicrousd }),\n }),\n cloudflareCryptoLayer,\n LiveTextHub.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, {\n threadId,\n ownsThread: (target) => target === threadId,\n }),\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\n/** Native source mutations which can create independently retained application obligations. */\nexport type ThreadHostMutation =\n | { readonly _tag: \"Admission\"; readonly request: AdmissionRequest }\n | { readonly _tag: \"Settlement\"; readonly request: SettlementFinalization }\n | { readonly _tag: \"WorkerStop\"; readonly request: WorkerStopCommand };\n\nexport interface ThreadPublicationOptions<E = never, R = never, P = never> {\n /** Pure, bounded selection of affected host lane IDs. The native owner prearms and guards\n * these lanes through the source mutation, including replay and recovery-only finalization.\n * Return only registered host IDs; do not perform I/O or acquire maintenance services here.\n * Delivery is independent of lifecycle publication and remains at least once.\n */\n readonly hostLanesForMutation?: (mutation: ThreadHostMutation) => ReadonlyArray<string>;\n /** Per-Submission recovery fault transitions. Capture host services once per incarnation;\n * acknowledge only after durable application or outbox retention. Delivery runs in a\n * separate bounded maintenance lane and does not gate native execution.\n */\n readonly recoveryEvents?: Layer.Layer<ThreadRecoveryEvents, E, R>;\n /** Typed native facts, retained atomically and published asynchronously in owner batches.\n * The handler returns after the application batch and its receipts commit. No journal\n * scan is needed. The handler receives private native evidence, not pre-authorized UI data.\n */\n readonly lifecyclePublication?: Layer.Layer<LifecyclePublicationHandler, E, R>;\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) =>\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\nconst sharedLayer = <A, E, R, PE = never, PR = never>(\n application: Layer.Layer<DurableAgentRuntime | A, E, R>,\n options: ThreadPublicationOptions<PE, PR> = {},\n) =>\n Layer.unwrap(\n Effect.gen(function* () {\n const { ctx } = yield* DurableObjectContext;\n const config = yield* CloudflareDurableRuntimeConfig;\n const placement = yield* ThreadObjectPlacement;\n const { ownsThread } = placement;\n\n const storageOptions: DoStorageOptions = {\n storage: ctx.storage,\n observationPollInterval: config.observationPollInterval,\n maxStoredValueBytes: config.maxStoredValueBytes,\n verifyOnOpen: config.verifyOnOpen,\n };\n\n const infrastructure = Layer.mergeAll(\n options.lifecyclePublication === undefined ? Layer.empty : lifecyclePublicationLayer,\n storageConfigLayer(storageOptions),\n Layer.effect(SqlClient)(SqlClient),\n );\n\n // Preserve the database owner's reader gate and rollback invalidators, while\n // making source transactions explicitly own the due-queue flush.\n const sourceOwner = Layer.effect(SqlStorageOwner)(\n Effect.gen(function* () {\n const owner = yield* SqlStorageOwner;\n const mutations = yield* ThreadMutationGate;\n\n if (owner === undefined) return yield* Effect.die(new Error(\"SQL owner unavailable\"));\n\n return {\n identity: owner.identity ?? owner,\n read: owner.read,\n invalidators: owner.invalidators,\n transaction: <A, E, R>(body: Effect.Effect<A, E, R>) =>\n owner.read(\n mutations.withTransaction(body).pipe(\n Effect.onExit((exit) =>\n Exit.isFailure(exit)\n ? Effect.sync(() => {\n for (const invalidate of owner.invalidators) invalidate();\n })\n : Effect.void,\n ),\n ),\n ),\n };\n }),\n ).pipe(Layer.provide(sqlOwnerLayer));\n\n const localInfrastructure = Layer.mergeAll(infrastructure, sourceOwner);\n\n const sourceProgress = Layer.effect(SqlStorageProgress)(\n Effect.gen(function* () {\n const mutations = yield* ThreadMutationGate;\n\n return {\n committed: (kind) => {\n const lanes = Match.value(kind).pipe(\n Match.when(\"canonical\", () => [\n DueQueue.Native,\n DueQueue.Publication,\n ...(options.projection === undefined ? [] : [DueQueue.Projection]),\n ]),\n Match.whenOr(\"submission\", \"control\", () => [\n DueQueue.Native,\n DueQueue.Publication,\n ]),\n Match.when(\"delivery\", () => [\n DueQueue.Messages,\n ...(options.lifecyclePublication === undefined ? [] : [DueQueue.Lifecycle]),\n ]),\n Match.whenOr(\"lifecycle\", \"lifecycle-ack\", () =>\n options.lifecyclePublication === undefined ? [] : [DueQueue.Lifecycle],\n ),\n Match.exhaustive,\n );\n\n return mutations.recordProgress(lanes).pipe(\n Effect.catchCause((cause) =>\n Effect.failCause(\n Cause.map(cause, (failure) =>\n SqlStorageProgressError.make({\n operation: \"record maintenance progress\",\n message: \"Committed source work could not enroll maintenance\",\n cause: failure,\n }),\n ),\n ),\n ),\n );\n },\n };\n }),\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(localInfrastructure),\n Layer.provide(sourceProgress),\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(\n doMessageDeliveryStoreLayer().pipe(\n Layer.provide(localInfrastructure),\n Layer.provide(sourceProgress),\n ),\n ),\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 &&\n options.projection === undefined &&\n options.hostLanesForMutation === undefined &&\n options.lifecyclePublication === undefined\n ? rawLocalPorts\n : Layer.effectContext(\n Effect.gen(function* () {\n const store = yield* ThreadStore;\n const ledger = yield* SubmissionLedger;\n const storageOwner = yield* StorageOwner;\n const settlementPublisher = yield* SettlementPublisher;\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 ...(store.lifecyclePublications === undefined\n ? {}\n : {\n lifecyclePublications: {\n ...store.lifecyclePublications,\n retryParked: (ownerThreadId, nowMillis) =>\n mutations\n .withMutation(\n store.lifecyclePublications!.retryParked(ownerThreadId, nowMillis),\n { invalidatesRecovery: false, lanes: [DueQueue.Lifecycle] },\n )\n .pipe(\n Effect.catchTag(\"DurableAlarmError\", (cause) =>\n LifecyclePublicationError.make({ reason: \"unavailable\", cause }),\n ),\n ),\n },\n }),\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 lanes: [\n ...(options.projection === undefined ? [] : [DueQueue.Projection]),\n ...(options.lifecyclePublication === undefined ||\n !request.batch.records.some((record) =>\n Schema.is(Schema.toType(LifecyclePublicationFact))(record.payload),\n )\n ? []\n : [DueQueue.Lifecycle]),\n ],\n },\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>(\n body: Effect.Effect<A, Failure>,\n invalidatesRecovery = true,\n hostLanes: ReadonlyArray<string> = [],\n ) =>\n mutations\n .withMutation(\n body.pipe(\n Effect.tap(() => (invalidatesRecovery ? afterCommit : Effect.void)),\n ),\n {\n invalidatesRecovery,\n lanes: [\n ...hostLanes,\n ...(options.lifecyclePublication === undefined\n ? []\n : [DueQueue.Lifecycle]),\n ],\n },\n )\n .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 observeMutation = <A, Failure>(\n mutation: ThreadHostMutation,\n body: Effect.Effect<A, Failure>,\n invalidatesRecovery: boolean,\n ) =>\n Effect.suspend(() =>\n Schema.decodeEffect(Schema.Array(DueQueue.HostLaneId))([\n ...new Set(options.hostLanesForMutation?.(mutation) ?? []),\n ]),\n ).pipe(\n Effect.mapError((cause) =>\n LedgerError.make({\n operation: \"select host maintenance lanes\",\n message: \"Native mutation selected an invalid host lane ID\",\n cause,\n }),\n ),\n Effect.flatMap((lanes) => observeIntent(body, invalidatesRecovery, lanes)),\n );\n\n const stopWorker = ledger.stopWorker;\n\n return Context.make(ThreadStore, observedStore).pipe(\n Context.add(StorageOwner, storageOwner),\n Context.add(SettlementPublisher, {\n publish: (input) =>\n Effect.gen(function* () {\n const { request } = yield* validatePublication(input);\n\n return yield* mutations\n .withMutation(\n sourceCommits\n .withPermit(\n settlementPublisher.publish(request).pipe(\n Effect.tap((result) =>\n result.replayed\n ? Effect.void\n : index\n .applyCommitted(\n request.append,\n AppendResult.make({\n firstSequence: result.tailSequence,\n lastSequence: result.tailSequence,\n\n replayed: false,\n }),\n )\n .pipe(\n Effect.catchCause((cause) =>\n Cause.hasInterrupts(cause)\n ? Effect.interrupt\n : Effect.logError(\n \"Thread projection deferred after settlement publication\",\n cause,\n ),\n ),\n ),\n ),\n ),\n )\n .pipe(Effect.tap(() => afterCommit)),\n {\n lanes: [\n ...(options.projection === undefined ? [] : [DueQueue.Projection]),\n ...(options.lifecyclePublication === undefined\n ? []\n : [DueQueue.Lifecycle]),\n ],\n },\n )\n .pipe(\n Effect.catchTag(\"DurableAlarmError\", (cause) =>\n ThreadStoreError.make({\n operation: \"prearm settlement publication\",\n message: cause.message,\n cause,\n }),\n ),\n );\n }),\n }),\n Context.add(SubmissionLedger, {\n ...ledger,\n ...(options.hostLanesForMutation === undefined\n ? {}\n : {\n admit: (request: AdmissionRequest) =>\n observeMutation(\n { _tag: \"Admission\", request },\n ledger.admit(request),\n false,\n ),\n }),\n ...(options.lifecyclePublication === undefined\n ? {}\n : {\n markReady: (request) => observeIntent(ledger.markReady(request), false),\n suspend: (request) => observeIntent(ledger.suspend(request), false),\n markUnknown: (request) =>\n observeIntent(ledger.markUnknown(request), false),\n recordChildSettled: (request) =>\n observeIntent(ledger.recordChildSettled(request), false),\n }),\n ...(options.lifecyclePublication === undefined &&\n options.hostLanesForMutation === undefined\n ? {}\n : {\n finalizeSettlement: (request: SettlementFinalization) =>\n observeMutation(\n { _tag: \"Settlement\", request },\n ledger.finalizeSettlement(request),\n false,\n ),\n }),\n recordApprovalDecision: (request) =>\n observeIntent(ledger.recordApprovalDecision(request)),\n ...(stopWorker === undefined\n ? {}\n : {\n stopWorker: (request: Parameters<NonNullable<typeof stopWorker>>[0]) =>\n observeMutation(\n { _tag: \"WorkerStop\", request },\n stopWorker(request),\n true,\n ),\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\n | SettlementPublisher\n | ThreadStore\n | MessageDeliveryStore\n | WakeScheduler\n | DurableRuntimeFailpoint\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), Layer.provide(wakes));\n\n const routedPorts = Layer.mergeAll(\n Layer.effect(StorageOwner, StorageOwner),\n routedSubmissionLedgerLayer({ ownsThread }),\n routedSettlementPublisherLayer({ ownsThread }),\n routedThreadStoreLayer({ ownsThread }),\n routedWorkerAdmissionLayer({ 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.provideMerge(runStorageLayer()),\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 const maintenanceRuntime =\n options.lifecyclePublication === undefined\n ? runtimeStack\n : Layer.merge(\n runtimeStack,\n Layer.effect(ThreadNativeMaintenance)(\n Effect.gen(function* () {\n const previous = yield* ThreadNativeMaintenance;\n const store = yield* ThreadStore;\n const storage = store.lifecyclePublications;\n\n const context = yield* Effect.context<\n LifecyclePublicationHandler | ThreadStore | ThreadReader | SubmissionLedger\n >();\n\n const failure = (cause: unknown) => {\n const error = DurableAlarmError.make({\n operation: \"publish native lifecycle\",\n message: \"Native lifecycle publication remains pending\",\n cause,\n });\n\n return ErrorReporter.isIgnored(cause)\n ? Object.assign(error, { [ErrorReporter.ignore]: true })\n : error;\n };\n\n const deadline = (\n storage === undefined\n ? Effect.fail(failure(\"Native lifecycle storage unavailable\"))\n : storage.pendingDeadline.pipe(Effect.mapError(failure))\n ).pipe(\n Effect.withErrorReporting,\n Effect.catchCauseIf(\n (cause) => !Cause.hasInterrupts(cause),\n (cause) =>\n Effect.logError(\"Lifecycle publication deadline unavailable\", cause).pipe(\n Effect.andThen(\n Effect.map(Clock.currentTimeMillis, (now) => Option.some(now + 60_000)),\n ),\n ),\n ),\n );\n\n return {\n lanes: [\n ...previous.lanes,\n {\n id: DueQueue.Lifecycle,\n // Source commits enroll one concurrent lane. Materialize a bounded\n // journal suffix per wave; never wait for publication in native work.\n // Four owner batches, each with a 10s host timeout, plus local commits/cleanup.\n dispatchTimeoutMillis: 60_000,\n run:\n storage === undefined\n ? Effect.fail(failure(\"Native lifecycle storage unavailable\"))\n : drainLifecyclePublications(storage).pipe(\n Effect.provide(context),\n Effect.mapError(failure),\n Effect.andThen(deadline),\n ),\n },\n ],\n };\n }),\n ).pipe(\n Layer.provide(rawLocalPorts),\n Layer.provide(options.lifecyclePublication.pipe(Layer.provide(rawLocalPorts))),\n Layer.provide(runtimeStack),\n ),\n );\n\n return Layer.mergeAll(\n maintenanceRuntime,\n ThreadMaintenance.layer.pipe(\n Layer.provide(options.recoveryEvents ?? Layer.empty),\n Layer.provide(\n Layer.effect(ThreadNativeMaintenance)(\n Effect.gen(function* () {\n const previous = yield* ThreadNativeMaintenance;\n const runtime = yield* DurableAgentRuntime;\n\n return {\n lanes: previous.lanes,\n ...(placement.threadId === undefined ? {} : { singleThreadRuntime: runtime }),\n };\n }),\n ),\n ),\n Layer.provide(maintenanceRuntime),\n Layer.provide(messageRecovery),\n ),\n portsEndpointLayer,\n routedMessages,\n messageRecovery,\n ).pipe(\n Layer.provideMerge(sourceProgress),\n Layer.provideMerge(publication),\n Layer.provideMerge(projection),\n Layer.provideMerge(sourceOwner),\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 \"@yielded/agent-storage-cloudflare/port-protocol\";\nimport {\n IntegrityReport,\n ObligationReport,\n ObligationThresholds,\n RecoveryExplanation,\n RetryCommand,\n RetryRefused,\n} from \"@yielded/agent/admin\";\nimport { DigestError } from \"@yielded/agent/digest\";\nimport {\n ApprovalSuspensionError,\n DurableAgentRuntime,\n DurableRuntimeConfig,\n RecoveryReport,\n RecoveryBlocked,\n type DurableSubmitAgent,\n} from \"@yielded/agent/durable-agent-runtime\";\nimport { DurableRuntimeFailpointError } from \"@yielded/agent/durable-failpoint\";\nimport { type AgentId, type ThreadId } from \"@yielded/agent/identifiers\";\nimport { SubmissionId } from \"@yielded/agent/identifiers\";\nimport {\n OperationAuthorizationRequest,\n OperationAuthorizer,\n OperationDenied,\n} from \"@yielded/agent/operation-authorizer\";\nimport { PersistedJson } from \"@yielded/agent/records\";\nimport { RunJournalError } from \"@yielded/agent/run-journal\";\nimport {\n AdmissionPolicyError,\n LedgerError,\n OwnershipLost,\n SettlementConflict,\n SubmissionLedger,\n SubmissionLookupByKey,\n} from \"@yielded/agent/submission-ledger\";\nimport {\n AppendConflict,\n ThreadNotMaterialized,\n ThreadRead,\n ThreadStore,\n ThreadStoreError,\n} from \"@yielded/agent/thread-store\";\nimport { WorkDiscoveryUnavailable } from \"@yielded/agent/thread-work\";\nimport { WakeScheduler } from \"@yielded/agent/wake-scheduler\";\nimport { Effect, Layer, Option, Schema, Stream, type Scope } from \"effect\";\nimport {\n DurableObject as EffectCfDurableObject,\n DurableObjectAlarm,\n DurableObjectState as EffectCfDurableObjectState,\n WorkerEnvironment,\n} from \"effect-cf\";\n\nimport {\n ThreadMaintenance,\n ThreadMaintenanceAlarm,\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 SettlementRecordReached,\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 { Request as WatchTextRequest } from \"./internal/live-text-protocol.ts\";\nimport { LiveTextHub } from \"./internal/live-text.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 ThreadHostMutation,\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\ntype ApplicationAlarmRegistration<ApplicationServices, EventServices, AlarmServices, AlarmError> =\n DurableObjectAlarm.AlarmRegistration<\n AlarmServices,\n | RuntimeServices\n | ApplicationServices\n | EventServices\n | NoInfer<AlarmServices>\n | EffectCfDurableObjectState.DurableObjectState\n | WorkerEnvironment\n | Scope.Scope,\n AlarmError\n >;\n\n/** Construction options for one deployed Thread Object class. */\nexport type Options<\n ApplicationServices = never,\n EventServices = never,\n EventLayerError = never,\n AlarmServices = never,\n AlarmError = never,\n> = BaseOptions<ApplicationServices, EventServices, EventLayerError, AlarmServices> &\n ([AlarmServices] extends [never]\n ? {\n readonly alarms?: ApplicationAlarmRegistration<\n ApplicationServices,\n EventServices,\n AlarmServices,\n AlarmError\n >;\n }\n : {\n readonly alarms: ApplicationAlarmRegistration<\n ApplicationServices,\n EventServices,\n AlarmServices,\n AlarmError\n >;\n });\n\ninterface BaseOptions<\n ApplicationServices,\n EventServices,\n EventLayerError,\n AlarmServices,\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 | NoInfer<AlarmServices>\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 \"WorkerAdmit\":\n case \"LedgerAdmit\":\n case \"LedgerMarkReady\":\n case \"LedgerStopWorker\":\n case \"LedgerRequestAbort\":\n case \"LedgerRecordChildSettled\":\n case \"StoreMaterialize\":\n case \"StoreAppend\":\n case \"StoreWorkRebuild\":\n case \"StoreRangeSeal\":\n case \"StoreRangeArchive\":\n case \"SettlementPublish\":\n case \"MessageDeliveryComplete\":\n return true;\n case \"LedgerInspectWorker\":\n case \"LedgerLookup\":\n case \"LedgerResolveAdmission\":\n case \"LedgerFundingOwner\":\n case \"StoreReadPage\":\n case \"StoreReadPrompt\":\n case \"StoreReadExecution\":\n case \"StoreWorkPage\":\n case \"StoreInspectTail\":\n case \"StoreReadIdentity\":\n case \"StoreCountPeerMessages\":\n case \"StoreExport\":\n case \"StoreRangePage\":\n case \"StoreRangeVerify\":\n case \"StoreVerification\":\n case \"StoreWorkerCapacity\":\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.fnUntraced(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.fnUntraced(function* (submissionId: SubmissionId) {\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.fnUntraced(function* (submissionId: SubmissionId) {\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.fnUntraced(function* (threadId: ThreadId) {\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 \"SettlementPublish\":\n return requireReceiptThread(request.request.append.threadId).pipe(\n Effect.andThen(requireSubmissionThread(request.request.submissionId)),\n );\n case \"MessageDeliveryComplete\":\n return requireReceiptThread(request.key.ownerThreadId);\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 \"LedgerFundingOwner\":\n return requireReceiptThread(request.request.threadId).pipe(\n Effect.andThen(requireSubmissionThread(request.request.submissionId)),\n );\n case \"LedgerInspectWorker\":\n case \"LedgerStopWorker\":\n case \"WorkerAdmit\":\n case \"LedgerAdmit\":\n case \"LedgerResolveAdmission\":\n case \"StoreMaterialize\":\n case \"StoreAppend\":\n case \"StoreReadPage\":\n case \"StoreReadPrompt\":\n case \"StoreReadExecution\":\n case \"StoreInspectTail\":\n case \"StoreReadIdentity\":\n case \"StoreCountPeerMessages\":\n case \"StoreExport\":\n case \"StoreWorkPage\":\n case \"StoreWorkRebuild\":\n case \"StoreRangePage\":\n case \"StoreRangeSeal\":\n case \"StoreRangeArchive\":\n case \"StoreRangeVerify\":\n case \"StoreVerification\":\n case \"StoreWorkerCapacity\":\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 and alarm 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.fnUntraced(function* (threadId: ThreadId, request: SubmitRequest) {\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 const alarm = yield* DurableAlarmService;\n\n yield* gateAdmissionLimits(threadId, request);\n\n // The mutation gate pre-arms durable maintenance; publication keeps its own wake behavior.\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(\n alarm.withHintsDeferred,\n Effect.tap(() => publishCommitted),\n ),\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 const scheduling = yield* DurableObjectAlarm.ScheduleConfiguration;\n\n if (scheduling.dispatchAfterEvent === true) {\n const alarms = yield* DurableAlarmService;\n\n // Make accepted work eligible for post-response dispatch without changing queue retry floors.\n yield* alarms.scheduleNow.pipe(\n Effect.catch((error) =>\n Effect.logWarning(\"Post-admission maintenance hint failed\", error),\n ),\n );\n }\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 includeRecord = false,\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 if (includeRecord)\n yield* authorizer.authorize(\n OperationAuthorizationRequest.make({\n operation: \"observe\",\n threadId: receipt.threadId,\n }),\n );\n yield* requireReceiptThread(receipt.threadId);\n yield* requireSubmissionThread(receipt.submissionId);\n const runtime = yield* DurableAgentRuntime;\n\n if (includeRecord)\n return SettlementRecordReached.make({\n record: yield* runtime.awaitSettlementRecord(receipt),\n });\n\n return SettlementReached.make({ settlement: yield* runtime.awaitSettlement(receipt) });\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 watchTextEndpoint = (encoded: unknown): Effect.Effect<unknown, never, EndpointServices> =>\n Schema.decodeUnknownEffect(WatchTextRequest)(encoded).pipe(\n Effect.mapError(protocolFailure(\"The provisional text request could not be decoded\")),\n Effect.flatMap(() =>\n Effect.gen(function* () {\n const { threadId } = yield* ThreadObjectIdentity;\n const authorizer = yield* OperationAuthorizer;\n\n yield* authorizer.authorize(\n OperationAuthorizationRequest.make({ operation: \"observe\", threadId }),\n );\n const hub = yield* LiveTextHub;\n\n return yield* hub.open(threadId);\n }),\n ),\n Effect.catch((failure) => encodeResponse(HostFailed.make({ failure }))),\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 DurableRuntimeFailpointError,\n DurableAlarmError,\n HostProtocolError,\n RecoveryBlocked,\n WorkDiscoveryUnavailable,\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 \"awaitSettlementRecordEncoded\",\n \"awaitProgressEncoded\",\n \"cancelProgressEncoded\",\n \"watchTextEncoded\",\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 awaitSettlementRecordEncoded: (encoded) => awaitSettlementEndpoint(encoded, true),\n awaitProgressEncoded: awaitProgressEndpoint,\n cancelProgressEncoded: cancelProgressEndpoint,\n watchTextEncoded: watchTextEndpoint,\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.fnUntraced(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\n/** Compose with application registrations on a shared physical object. */\nexport const alarms = ThreadMaintenanceAlarm.handlers({\n \"@yielded/agent/thread-maintenance\": () =>\n Effect.flatMap(ThreadMaintenance, (maintenance) => Effect.asVoid(maintenance.pass)),\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<\n Record<never, never>,\n RuntimeServices | EventServices | ThreadMaintenanceAlarm\n >\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 awaitSettlementRecordEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n awaitProgressEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n cancelProgressEncoded(encoded: unknown, traceContext?: unknown): Promise<unknown>;\n watchTextEncoded(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 AlarmServices = never,\n AlarmError = never,\n>(\n applicationLayer: Layer.Layer<\n CloudflareDurableRuntimeServices | ApplicationServices,\n ApplicationError,\n | CloudflareBootstrapServices\n | ThreadMaintenanceAlarm\n | NoInfer<AlarmServices>\n | EffectCfDurableObjectState.DurableObjectState\n | WorkerEnvironment\n | DurableObjectContext\n | ThreadObjectNamespace\n >,\n options: Options<ApplicationServices, EventServices, EventLayerError, AlarmServices, AlarmError>,\n): Class<ApplicationServices | EventServices | AlarmServices> => {\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\n | WorkerEnvironment\n | ThreadMaintenanceAlarm\n | AlarmServices\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 ThreadMaintenanceAlarm | AlarmServices\n >;\n\n return EffectCfDurableObject.make<\n RuntimeServices | ApplicationServices,\n ThreadObjectInitializationError | ApplicationError,\n EventServices,\n EventLayerError,\n typeof rpc,\n ThreadMaintenanceAlarm | AlarmServices\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 alarms:\n options.alarms === undefined ? alarms : DurableObjectAlarm.mergeAll(options.alarms, alarms),\n // The named registration supplies its scheduler before the constructor builds application services.\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,IAAa,cAAb,MAAa,oBAAoB,QAAQ,QAOvC,CAAC,CAAC,+CAA+C,CAAC,CAAC;CACnD,OAAgB,QAAkC,MAAM,cACtD,OAAO,IAAI,aAAa;EACtB,MAAM,QAAQ,OAAO,OAAO;EAC5B,MAAM,4BAAY,IAAI,IAAc;EACpC,MAAM,yBAAS,IAAI,IAAmB;EACtC,IAAI,SAAS;EAEb,IAAI;EAIJ,MAAM,SAAS,OAAO,aAAa,OAAO,eAAe,KAAK,CAAC;EAC/D,MAAM,UAAU,IAAI,YAAY;EAEhC,OAAO,OAAO,mBAAmB,OAAO,WAAW,OAAO,MAAM,CAAC,CAAC;EAElE,MAAM,QAAQ,cAAkC;GAC9C,MAAM,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