@effect-agent/storage-cloudflare 0.1.0-beta.50 → 0.1.0-beta.51
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/DoScheduleStore.mjs +1 -1
- package/dist/DoScheduleStore.mjs.map +1 -1
- package/dist/{DoStorageVersion-KrYUXqeJ.d.mts → DoStorageVersion-DxqcVgDE.d.mts} +2 -2
- package/dist/DoStorageVersion.d.mts +1 -1
- package/dist/DoStorageVersion.mjs +2 -2
- package/dist/DoSubmissionLedger.mjs +35 -6
- package/dist/DoSubmissionLedger.mjs.map +1 -1
- package/dist/DoSubscriptionStore.mjs +8 -4
- package/dist/DoSubscriptionStore.mjs.map +1 -1
- package/dist/{DoThreadStore-D00TdRAa.mjs → DoThreadStore-JqjeFOga.mjs} +8 -8
- package/dist/{DoThreadStore-D00TdRAa.mjs.map → DoThreadStore-JqjeFOga.mjs.map} +1 -1
- package/dist/DoThreadStore.mjs +1 -1
- package/dist/PortProtocol.d.mts +25 -3
- package/dist/PortProtocol.mjs +2 -1
- package/dist/PortProtocol.mjs.map +1 -1
- package/dist/PortRouting.mjs +2 -2
- package/dist/PortRouting.mjs.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{migrations-Bo4GU-pp.mjs → migrations-B-jiT7vx.mjs} +9 -3
- package/dist/migrations-B-jiT7vx.mjs.map +1 -0
- package/package.json +1 -1
- package/src/DoScheduleStore.ts +1 -1
- package/src/DoSubmissionLedger.ts +61 -3
- package/src/DoSubscriptionStore.ts +8 -4
- package/src/PortProtocol.ts +2 -0
- package/src/PortRouting.ts +2 -1
- package/src/internal/migrations.ts +8 -1
- package/dist/migrations-Bo4GU-pp.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PortProtocol.mjs","names":[],"sources":["../src/PortProtocol.ts"],"sourcesContent":["import { CanonicalRecordEnvelope } from \"@effect-agent/thread/Records\";\nimport {\n AbortCommand,\n AbortIntent,\n AdmissionConflict,\n AdmissionRequest,\n AdmissionResolution,\n AdmissionResult,\n ChildSettledNotification,\n ChildSettledOutcome,\n JoinedToHost,\n LedgerError,\n MarkReadyRequest,\n SettlementConflict,\n SubmissionLookup,\n SubmissionLookupByKey,\n SubmissionSnapshot,\n} from \"@effect-agent/thread/SubmissionLedger\";\nimport {\n AppendConflict,\n AppendResult,\n ThreadExport,\n ThreadExportRequest,\n ThreadMaterialization,\n ThreadNotMaterialized,\n ThreadRead,\n ThreadStoreError,\n ThreadTail,\n ThreadTailRequest,\n FenceRejected,\n FencedAppendRequest,\n} from \"@effect-agent/thread/ThreadStore\";\nimport { Schema } from \"effect\";\n\n/**\n * The cross-Durable-Object port protocol (plan §1.3, D-P6-3): Schema request/response/error\n * envelopes for the CLOSED route-capable subset of the thread ports. One Thread's\n * Durable Object executes another Thread's request against its OWN local facets; the\n * envelopes here are the only values that cross the Object boundary, and they are\n * transport-agnostic — native Durable Object JS RPC is the shipped carrier, fetch-with-JSON\n * the documented fallback, and both move the same Schema-encoded JSON.\n *\n * The closed subset is exactly the set of operations the durable coordinator performs against\n * a FOREIGN Thread (parent/child establishment, status checks, abort propagation,\n * child-settlement notification, and the child-thread store operations used by\n * establishment, `verifySettledChild`, and result projection):\n *\n * - ledger: `admit`, `markReady`, `lookup`, `resolveAdmission`, `requestAbort`,\n * `recordChildSettled`;\n * - store: `materialize`, `append`, `read` (one page), `inspectTail`, `export`.\n *\n * Every other port operation is lane-local by construction and is NOT given an envelope:\n * honesty over accidental distribution — the routing layer fails such calls fast and typed\n * instead of quietly widening the distributed surface.\n *\n * Failures cross the boundary as the `PortFailure` union and re-decode on the caller side to\n * the SAME tagged error types the local facet would have produced, so routed calls keep\n * error-tag fidelity. `cause` chains inside `LedgerError`/`ThreadStoreError` travel as\n * Schema defects and do not claim instance fidelity across Objects (plan §2.8).\n */\n\n/** Ceiling for protocol diagnostic strings; matches `AdmissionIndeterminate.reason`. */\nexport const MAX_PORT_DIAGNOSTIC_LENGTH = 4_096;\n\nconst BoundedDiagnostic = Schema.String.check(Schema.isMaxLength(MAX_PORT_DIAGNOSTIC_LENGTH));\n\n/** Truncate a diagnostic string to the protocol's bounded diagnostic length. */\nexport const boundPortDiagnostic = (value: string): string =>\n value.length > MAX_PORT_DIAGNOSTIC_LENGTH\n ? `${value.slice(0, MAX_PORT_DIAGNOSTIC_LENGTH - 3)}...`\n : value;\n\n/**\n * The envelope itself could not be honored: the receiving Object could not decode the\n * request, or a response could not be encoded/decoded. It never carries port semantics —\n * callers fold it into the operation's base error (`LedgerError`/`ThreadStoreError`),\n * except `resolveAdmission`, which folds it into `AdmissionIndeterminate` because a\n * non-answer is never proof of absence (SUB-031).\n */\nexport class PortProtocolError extends Schema.TaggedError<PortProtocolError>()(\n \"PortProtocolError\",\n {\n message: BoundedDiagnostic,\n },\n) {}\n\n// ---------------------------------------------------------------------------\n// Requests\n// ---------------------------------------------------------------------------\n\n/** Routed `SubmissionLedger.admit` — child establishment admits INTO the owning Object. */\nexport class LedgerAdmitCall extends Schema.TaggedClass<LedgerAdmitCall>(\n \"@effect-agent/storage-cloudflare/LedgerAdmitCall\",\n)(\"LedgerAdmit\", {\n request: AdmissionRequest,\n}) {}\n\n/** Routed `SubmissionLedger.markReady` for a Submission owned by another Object. */\nexport class LedgerMarkReadyCall extends Schema.TaggedClass<LedgerMarkReadyCall>(\n \"@effect-agent/storage-cloudflare/LedgerMarkReadyCall\",\n)(\"LedgerMarkReady\", {\n request: MarkReadyRequest,\n}) {}\n\n/** Routed `SubmissionLedger.lookup` (by identity or scoped idempotency key). */\nexport class LedgerLookupCall extends Schema.TaggedClass<LedgerLookupCall>(\n \"@effect-agent/storage-cloudflare/LedgerLookupCall\",\n)(\"LedgerLookup\", {\n request: SubmissionLookup,\n}) {}\n\n/** Routed `SubmissionLedger.resolveAdmission` — the SUB-031 tri-state authority call. */\nexport class LedgerResolveAdmissionCall extends Schema.TaggedClass<LedgerResolveAdmissionCall>(\n \"@effect-agent/storage-cloudflare/LedgerResolveAdmissionCall\",\n)(\"LedgerResolveAdmission\", {\n request: SubmissionLookupByKey,\n}) {}\n\n/** Routed `SubmissionLedger.requestAbort` — abort propagation across Objects. */\nexport class LedgerRequestAbortCall extends Schema.TaggedClass<LedgerRequestAbortCall>(\n \"@effect-agent/storage-cloudflare/LedgerRequestAbortCall\",\n)(\"LedgerRequestAbort\", {\n request: AbortCommand,\n}) {}\n\n/** Routed `SubmissionLedger.recordChildSettled` — the child→parent durable notification. */\nexport class LedgerRecordChildSettledCall extends Schema.TaggedClass<LedgerRecordChildSettledCall>(\n \"@effect-agent/storage-cloudflare/LedgerRecordChildSettledCall\",\n)(\"LedgerRecordChildSettled\", {\n request: ChildSettledNotification,\n}) {}\n\n/** Routed `ThreadStore.materialize` against the owning Object. */\nexport class StoreMaterializeCall extends Schema.TaggedClass<StoreMaterializeCall>(\n \"@effect-agent/storage-cloudflare/StoreMaterializeCall\",\n)(\"StoreMaterialize\", {\n request: ThreadMaterialization,\n}) {}\n\n/** Routed `ThreadStore.append` against the owning Object. */\nexport class StoreAppendCall extends Schema.TaggedClass<StoreAppendCall>(\n \"@effect-agent/storage-cloudflare/StoreAppendCall\",\n)(\"StoreAppend\", {\n request: FencedAppendRequest,\n}) {}\n\n/** Routed one-page `ThreadStore.read`; the page bound is the request's own `limit`. */\nexport class StoreReadPageCall extends Schema.TaggedClass<StoreReadPageCall>(\n \"@effect-agent/storage-cloudflare/StoreReadPageCall\",\n)(\"StoreReadPage\", {\n request: ThreadRead,\n}) {}\n\n/** Routed `ThreadStore.inspectTail` against the owning Object. */\nexport class StoreInspectTailCall extends Schema.TaggedClass<StoreInspectTailCall>(\n \"@effect-agent/storage-cloudflare/StoreInspectTailCall\",\n)(\"StoreInspectTail\", {\n request: ThreadTailRequest,\n}) {}\n\n/** Routed `ThreadStore.export` against the owning Object. */\nexport class StoreExportCall extends Schema.TaggedClass<StoreExportCall>(\n \"@effect-agent/storage-cloudflare/StoreExportCall\",\n)(\"StoreExport\", {\n request: ThreadExportRequest,\n}) {}\n\n/** Every request that may cross a Durable Object boundary — the CLOSED route-capable subset. */\nexport const PortRequest = Schema.Union([\n LedgerAdmitCall,\n LedgerMarkReadyCall,\n LedgerLookupCall,\n LedgerResolveAdmissionCall,\n LedgerRequestAbortCall,\n LedgerRecordChildSettledCall,\n StoreMaterializeCall,\n StoreAppendCall,\n StoreReadPageCall,\n StoreInspectTailCall,\n StoreExportCall,\n]);\n\nexport type PortRequest = typeof PortRequest.Type;\n\n/** The wire form of one port request (what a transport actually carries). */\nexport type PortRequestEnvelope = typeof PortRequest.Encoded;\n\n// ---------------------------------------------------------------------------\n// Results\n// ---------------------------------------------------------------------------\n\nexport class LedgerAdmitResult extends Schema.TaggedClass<LedgerAdmitResult>(\n \"@effect-agent/storage-cloudflare/LedgerAdmitResult\",\n)(\"LedgerAdmitResult\", {\n result: AdmissionResult,\n}) {}\n\nexport class LedgerMarkReadyResult extends Schema.TaggedClass<LedgerMarkReadyResult>(\n \"@effect-agent/storage-cloudflare/LedgerMarkReadyResult\",\n)(\"LedgerMarkReadyResult\", {}) {}\n\n/** `submission` is absent exactly when the lookup answered `Option.none`. */\nexport class LedgerLookupResult extends Schema.TaggedClass<LedgerLookupResult>(\n \"@effect-agent/storage-cloudflare/LedgerLookupResult\",\n)(\"LedgerLookupResult\", {\n submission: Schema.optionalKey(SubmissionSnapshot),\n}) {}\n\nexport class LedgerResolveAdmissionResult extends Schema.TaggedClass<LedgerResolveAdmissionResult>(\n \"@effect-agent/storage-cloudflare/LedgerResolveAdmissionResult\",\n)(\"LedgerResolveAdmissionResult\", {\n resolution: AdmissionResolution,\n}) {}\n\nexport class LedgerRequestAbortResult extends Schema.TaggedClass<LedgerRequestAbortResult>(\n \"@effect-agent/storage-cloudflare/LedgerRequestAbortResult\",\n)(\"LedgerRequestAbortResult\", {\n intent: AbortIntent,\n}) {}\n\nexport class LedgerRecordChildSettledResult extends Schema.TaggedClass<LedgerRecordChildSettledResult>(\n \"@effect-agent/storage-cloudflare/LedgerRecordChildSettledResult\",\n)(\"LedgerRecordChildSettledResult\", {\n outcome: ChildSettledOutcome,\n}) {}\n\nexport class StoreMaterializeResult extends Schema.TaggedClass<StoreMaterializeResult>(\n \"@effect-agent/storage-cloudflare/StoreMaterializeResult\",\n)(\"StoreMaterializeResult\", {}) {}\n\nexport class StoreAppendResult extends Schema.TaggedClass<StoreAppendResult>(\n \"@effect-agent/storage-cloudflare/StoreAppendResult\",\n)(\"StoreAppendResult\", {\n result: AppendResult,\n}) {}\n\n/** One page of canonical records, bounded by the request's `limit` (≤ 1,024). */\nexport class StoreReadPageResult extends Schema.TaggedClass<StoreReadPageResult>(\n \"@effect-agent/storage-cloudflare/StoreReadPageResult\",\n)(\"StoreReadPageResult\", {\n records: Schema.Array(CanonicalRecordEnvelope).check(Schema.isMaxLength(1_024)),\n}) {}\n\nexport class StoreInspectTailResult extends Schema.TaggedClass<StoreInspectTailResult>(\n \"@effect-agent/storage-cloudflare/StoreInspectTailResult\",\n)(\"StoreInspectTailResult\", {\n tail: ThreadTail,\n}) {}\n\nexport class StoreExportResult extends Schema.TaggedClass<StoreExportResult>(\n \"@effect-agent/storage-cloudflare/StoreExportResult\",\n)(\"StoreExportResult\", {\n export: ThreadExport,\n}) {}\n\n/** Every successful routed result. Callers narrow by the tag their request implies. */\nexport const PortResult = Schema.Union([\n LedgerAdmitResult,\n LedgerMarkReadyResult,\n LedgerLookupResult,\n LedgerResolveAdmissionResult,\n LedgerRequestAbortResult,\n LedgerRecordChildSettledResult,\n StoreMaterializeResult,\n StoreAppendResult,\n StoreReadPageResult,\n StoreInspectTailResult,\n StoreExportResult,\n]);\n\nexport type PortResult = typeof PortResult.Type;\n\n// ---------------------------------------------------------------------------\n// Failures and the response envelope\n// ---------------------------------------------------------------------------\n\n/**\n * Every typed failure a route-capable operation can produce on its owning Object, plus the\n * protocol's own `PortProtocolError`. Members re-decode to the SAME tagged classes the\n * thread ports declare, so a routed caller observes identical error tags and fields.\n */\nexport const PortFailure = Schema.Union([\n AdmissionConflict,\n SettlementConflict,\n JoinedToHost,\n LedgerError,\n ThreadStoreError,\n ThreadNotMaterialized,\n AppendConflict,\n FenceRejected,\n PortProtocolError,\n]);\n\nexport type PortFailure = typeof PortFailure.Type;\n\n/** The routed operation succeeded on its owning Object. */\nexport class PortSucceeded extends Schema.TaggedClass<PortSucceeded>(\n \"@effect-agent/storage-cloudflare/PortSucceeded\",\n)(\"PortSucceeded\", {\n result: PortResult,\n}) {}\n\n/** The routed operation failed TYPED on its owning Object; the failure re-decodes verbatim. */\nexport class PortFailed extends Schema.TaggedClass<PortFailed>(\n \"@effect-agent/storage-cloudflare/PortFailed\",\n)(\"PortFailed\", {\n failure: PortFailure,\n}) {}\n\n/** The uniform answer of one `portCall`: op-specific success or a re-decodable typed failure. */\nexport const PortResponse = Schema.Union([PortSucceeded, PortFailed]);\nexport type PortResponse = typeof PortResponse.Type;\n\n/** The wire form of one port response (what a transport actually carries). */\nexport type PortResponseEnvelope = typeof PortResponse.Encoded;\n\n// ---------------------------------------------------------------------------\n// Codecs\n// ---------------------------------------------------------------------------\n\nexport const encodePortRequest = Schema.encodeEffect(PortRequest);\nexport const decodePortRequest = Schema.decodeUnknownEffect(PortRequest);\nexport const encodePortResponse = Schema.encodeEffect(PortResponse);\nexport const decodePortResponse = Schema.decodeUnknownEffect(PortResponse);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DA,MAAa,6BAA6B;AAE1C,MAAM,oBAAoB,OAAO,OAAO,MAAM,OAAO,YAAY,0BAA0B,CAAC;;AAG5F,MAAa,uBAAuB,UAClC,MAAM,SAAA,OACF,GAAG,MAAM,MAAM,GAAG,IAA8B,EAAE,OAClD;;;;;;;;AASN,IAAa,oBAAb,cAAuC,OAAO,YAA+B,CAAC,CAC5E,qBACA,EACE,SAAS,kBACX,CACF,CAAC,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EJ,IAAa,oBAAb,cAAuC,OAAO,YAC5C,oDACF,CAAC,CAAC,qBAAqB,EACrB,QAAQ,aACV,CAAC,CAAC,CAAC,CAAC;;AAGJ,MAAa,aAAa,OAAO,MAAM;CACrC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;AAaD,MAAa,cAAc,OAAO,MAAM;CACtC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAKD,IAAa,gBAAb,cAAmC,OAAO,YACxC,gDACF,CAAC,CAAC,iBAAiB,EACjB,QAAQ,WACV,CAAC,CAAC,CAAC,CAAC;;AAGJ,IAAa,aAAb,cAAgC,OAAO,YACrC,6CACF,CAAC,CAAC,cAAc,EACd,SAAS,YACX,CAAC,CAAC,CAAC,CAAC;;AAGJ,MAAa,eAAe,OAAO,MAAM,CAAC,eAAe,UAAU,CAAC;AAUpE,MAAa,oBAAoB,OAAO,aAAa,WAAW;AAChE,MAAa,oBAAoB,OAAO,oBAAoB,WAAW;AACvE,MAAa,qBAAqB,OAAO,aAAa,YAAY;AAClE,MAAa,qBAAqB,OAAO,oBAAoB,YAAY"}
|
|
1
|
+
{"version":3,"file":"PortProtocol.mjs","names":[],"sources":["../src/PortProtocol.ts"],"sourcesContent":["import { CanonicalRecordEnvelope } from \"@effect-agent/thread/Records\";\nimport {\n AbortCommand,\n AbortIntent,\n AdmissionConflict,\n AdmissionPolicyError,\n AdmissionRequest,\n AdmissionResolution,\n AdmissionResult,\n ChildSettledNotification,\n ChildSettledOutcome,\n JoinedToHost,\n LedgerError,\n MarkReadyRequest,\n SettlementConflict,\n SubmissionLookup,\n SubmissionLookupByKey,\n SubmissionSnapshot,\n} from \"@effect-agent/thread/SubmissionLedger\";\nimport {\n AppendConflict,\n AppendResult,\n ThreadExport,\n ThreadExportRequest,\n ThreadMaterialization,\n ThreadNotMaterialized,\n ThreadRead,\n ThreadStoreError,\n ThreadTail,\n ThreadTailRequest,\n FenceRejected,\n FencedAppendRequest,\n} from \"@effect-agent/thread/ThreadStore\";\nimport { Schema } from \"effect\";\n\n/**\n * The cross-Durable-Object port protocol (plan §1.3, D-P6-3): Schema request/response/error\n * envelopes for the CLOSED route-capable subset of the thread ports. One Thread's\n * Durable Object executes another Thread's request against its OWN local facets; the\n * envelopes here are the only values that cross the Object boundary, and they are\n * transport-agnostic — native Durable Object JS RPC is the shipped carrier, fetch-with-JSON\n * the documented fallback, and both move the same Schema-encoded JSON.\n *\n * The closed subset is exactly the set of operations the durable coordinator performs against\n * a FOREIGN Thread (parent/child establishment, status checks, abort propagation,\n * child-settlement notification, and the child-thread store operations used by\n * establishment, `verifySettledChild`, and result projection):\n *\n * - ledger: `admit`, `markReady`, `lookup`, `resolveAdmission`, `requestAbort`,\n * `recordChildSettled`;\n * - store: `materialize`, `append`, `read` (one page), `inspectTail`, `export`.\n *\n * Every other port operation is lane-local by construction and is NOT given an envelope:\n * honesty over accidental distribution — the routing layer fails such calls fast and typed\n * instead of quietly widening the distributed surface.\n *\n * Failures cross the boundary as the `PortFailure` union and re-decode on the caller side to\n * the SAME tagged error types the local facet would have produced, so routed calls keep\n * error-tag fidelity. `cause` chains inside `LedgerError`/`ThreadStoreError` travel as\n * Schema defects and do not claim instance fidelity across Objects (plan §2.8).\n */\n\n/** Ceiling for protocol diagnostic strings; matches `AdmissionIndeterminate.reason`. */\nexport const MAX_PORT_DIAGNOSTIC_LENGTH = 4_096;\n\nconst BoundedDiagnostic = Schema.String.check(Schema.isMaxLength(MAX_PORT_DIAGNOSTIC_LENGTH));\n\n/** Truncate a diagnostic string to the protocol's bounded diagnostic length. */\nexport const boundPortDiagnostic = (value: string): string =>\n value.length > MAX_PORT_DIAGNOSTIC_LENGTH\n ? `${value.slice(0, MAX_PORT_DIAGNOSTIC_LENGTH - 3)}...`\n : value;\n\n/**\n * The envelope itself could not be honored: the receiving Object could not decode the\n * request, or a response could not be encoded/decoded. It never carries port semantics —\n * callers fold it into the operation's base error (`LedgerError`/`ThreadStoreError`),\n * except `resolveAdmission`, which folds it into `AdmissionIndeterminate` because a\n * non-answer is never proof of absence (SUB-031).\n */\nexport class PortProtocolError extends Schema.TaggedError<PortProtocolError>()(\n \"PortProtocolError\",\n {\n message: BoundedDiagnostic,\n },\n) {}\n\n// ---------------------------------------------------------------------------\n// Requests\n// ---------------------------------------------------------------------------\n\n/** Routed `SubmissionLedger.admit` — child establishment admits INTO the owning Object. */\nexport class LedgerAdmitCall extends Schema.TaggedClass<LedgerAdmitCall>(\n \"@effect-agent/storage-cloudflare/LedgerAdmitCall\",\n)(\"LedgerAdmit\", {\n request: AdmissionRequest,\n}) {}\n\n/** Routed `SubmissionLedger.markReady` for a Submission owned by another Object. */\nexport class LedgerMarkReadyCall extends Schema.TaggedClass<LedgerMarkReadyCall>(\n \"@effect-agent/storage-cloudflare/LedgerMarkReadyCall\",\n)(\"LedgerMarkReady\", {\n request: MarkReadyRequest,\n}) {}\n\n/** Routed `SubmissionLedger.lookup` (by identity or scoped idempotency key). */\nexport class LedgerLookupCall extends Schema.TaggedClass<LedgerLookupCall>(\n \"@effect-agent/storage-cloudflare/LedgerLookupCall\",\n)(\"LedgerLookup\", {\n request: SubmissionLookup,\n}) {}\n\n/** Routed `SubmissionLedger.resolveAdmission` — the SUB-031 tri-state authority call. */\nexport class LedgerResolveAdmissionCall extends Schema.TaggedClass<LedgerResolveAdmissionCall>(\n \"@effect-agent/storage-cloudflare/LedgerResolveAdmissionCall\",\n)(\"LedgerResolveAdmission\", {\n request: SubmissionLookupByKey,\n}) {}\n\n/** Routed `SubmissionLedger.requestAbort` — abort propagation across Objects. */\nexport class LedgerRequestAbortCall extends Schema.TaggedClass<LedgerRequestAbortCall>(\n \"@effect-agent/storage-cloudflare/LedgerRequestAbortCall\",\n)(\"LedgerRequestAbort\", {\n request: AbortCommand,\n}) {}\n\n/** Routed `SubmissionLedger.recordChildSettled` — the child→parent durable notification. */\nexport class LedgerRecordChildSettledCall extends Schema.TaggedClass<LedgerRecordChildSettledCall>(\n \"@effect-agent/storage-cloudflare/LedgerRecordChildSettledCall\",\n)(\"LedgerRecordChildSettled\", {\n request: ChildSettledNotification,\n}) {}\n\n/** Routed `ThreadStore.materialize` against the owning Object. */\nexport class StoreMaterializeCall extends Schema.TaggedClass<StoreMaterializeCall>(\n \"@effect-agent/storage-cloudflare/StoreMaterializeCall\",\n)(\"StoreMaterialize\", {\n request: ThreadMaterialization,\n}) {}\n\n/** Routed `ThreadStore.append` against the owning Object. */\nexport class StoreAppendCall extends Schema.TaggedClass<StoreAppendCall>(\n \"@effect-agent/storage-cloudflare/StoreAppendCall\",\n)(\"StoreAppend\", {\n request: FencedAppendRequest,\n}) {}\n\n/** Routed one-page `ThreadStore.read`; the page bound is the request's own `limit`. */\nexport class StoreReadPageCall extends Schema.TaggedClass<StoreReadPageCall>(\n \"@effect-agent/storage-cloudflare/StoreReadPageCall\",\n)(\"StoreReadPage\", {\n request: ThreadRead,\n}) {}\n\n/** Routed `ThreadStore.inspectTail` against the owning Object. */\nexport class StoreInspectTailCall extends Schema.TaggedClass<StoreInspectTailCall>(\n \"@effect-agent/storage-cloudflare/StoreInspectTailCall\",\n)(\"StoreInspectTail\", {\n request: ThreadTailRequest,\n}) {}\n\n/** Routed `ThreadStore.export` against the owning Object. */\nexport class StoreExportCall extends Schema.TaggedClass<StoreExportCall>(\n \"@effect-agent/storage-cloudflare/StoreExportCall\",\n)(\"StoreExport\", {\n request: ThreadExportRequest,\n}) {}\n\n/** Every request that may cross a Durable Object boundary — the CLOSED route-capable subset. */\nexport const PortRequest = Schema.Union([\n LedgerAdmitCall,\n LedgerMarkReadyCall,\n LedgerLookupCall,\n LedgerResolveAdmissionCall,\n LedgerRequestAbortCall,\n LedgerRecordChildSettledCall,\n StoreMaterializeCall,\n StoreAppendCall,\n StoreReadPageCall,\n StoreInspectTailCall,\n StoreExportCall,\n]);\n\nexport type PortRequest = typeof PortRequest.Type;\n\n/** The wire form of one port request (what a transport actually carries). */\nexport type PortRequestEnvelope = typeof PortRequest.Encoded;\n\n// ---------------------------------------------------------------------------\n// Results\n// ---------------------------------------------------------------------------\n\nexport class LedgerAdmitResult extends Schema.TaggedClass<LedgerAdmitResult>(\n \"@effect-agent/storage-cloudflare/LedgerAdmitResult\",\n)(\"LedgerAdmitResult\", {\n result: AdmissionResult,\n}) {}\n\nexport class LedgerMarkReadyResult extends Schema.TaggedClass<LedgerMarkReadyResult>(\n \"@effect-agent/storage-cloudflare/LedgerMarkReadyResult\",\n)(\"LedgerMarkReadyResult\", {}) {}\n\n/** `submission` is absent exactly when the lookup answered `Option.none`. */\nexport class LedgerLookupResult extends Schema.TaggedClass<LedgerLookupResult>(\n \"@effect-agent/storage-cloudflare/LedgerLookupResult\",\n)(\"LedgerLookupResult\", {\n submission: Schema.optionalKey(SubmissionSnapshot),\n}) {}\n\nexport class LedgerResolveAdmissionResult extends Schema.TaggedClass<LedgerResolveAdmissionResult>(\n \"@effect-agent/storage-cloudflare/LedgerResolveAdmissionResult\",\n)(\"LedgerResolveAdmissionResult\", {\n resolution: AdmissionResolution,\n}) {}\n\nexport class LedgerRequestAbortResult extends Schema.TaggedClass<LedgerRequestAbortResult>(\n \"@effect-agent/storage-cloudflare/LedgerRequestAbortResult\",\n)(\"LedgerRequestAbortResult\", {\n intent: AbortIntent,\n}) {}\n\nexport class LedgerRecordChildSettledResult extends Schema.TaggedClass<LedgerRecordChildSettledResult>(\n \"@effect-agent/storage-cloudflare/LedgerRecordChildSettledResult\",\n)(\"LedgerRecordChildSettledResult\", {\n outcome: ChildSettledOutcome,\n}) {}\n\nexport class StoreMaterializeResult extends Schema.TaggedClass<StoreMaterializeResult>(\n \"@effect-agent/storage-cloudflare/StoreMaterializeResult\",\n)(\"StoreMaterializeResult\", {}) {}\n\nexport class StoreAppendResult extends Schema.TaggedClass<StoreAppendResult>(\n \"@effect-agent/storage-cloudflare/StoreAppendResult\",\n)(\"StoreAppendResult\", {\n result: AppendResult,\n}) {}\n\n/** One page of canonical records, bounded by the request's `limit` (≤ 1,024). */\nexport class StoreReadPageResult extends Schema.TaggedClass<StoreReadPageResult>(\n \"@effect-agent/storage-cloudflare/StoreReadPageResult\",\n)(\"StoreReadPageResult\", {\n records: Schema.Array(CanonicalRecordEnvelope).check(Schema.isMaxLength(1_024)),\n}) {}\n\nexport class StoreInspectTailResult extends Schema.TaggedClass<StoreInspectTailResult>(\n \"@effect-agent/storage-cloudflare/StoreInspectTailResult\",\n)(\"StoreInspectTailResult\", {\n tail: ThreadTail,\n}) {}\n\nexport class StoreExportResult extends Schema.TaggedClass<StoreExportResult>(\n \"@effect-agent/storage-cloudflare/StoreExportResult\",\n)(\"StoreExportResult\", {\n export: ThreadExport,\n}) {}\n\n/** Every successful routed result. Callers narrow by the tag their request implies. */\nexport const PortResult = Schema.Union([\n LedgerAdmitResult,\n LedgerMarkReadyResult,\n LedgerLookupResult,\n LedgerResolveAdmissionResult,\n LedgerRequestAbortResult,\n LedgerRecordChildSettledResult,\n StoreMaterializeResult,\n StoreAppendResult,\n StoreReadPageResult,\n StoreInspectTailResult,\n StoreExportResult,\n]);\n\nexport type PortResult = typeof PortResult.Type;\n\n// ---------------------------------------------------------------------------\n// Failures and the response envelope\n// ---------------------------------------------------------------------------\n\n/**\n * Every typed failure a route-capable operation can produce on its owning Object, plus the\n * protocol's own `PortProtocolError`. Members re-decode to the SAME tagged classes the\n * thread ports declare, so a routed caller observes identical error tags and fields.\n */\nexport const PortFailure = Schema.Union([\n AdmissionConflict,\n AdmissionPolicyError,\n SettlementConflict,\n JoinedToHost,\n LedgerError,\n ThreadStoreError,\n ThreadNotMaterialized,\n AppendConflict,\n FenceRejected,\n PortProtocolError,\n]);\n\nexport type PortFailure = typeof PortFailure.Type;\n\n/** The routed operation succeeded on its owning Object. */\nexport class PortSucceeded extends Schema.TaggedClass<PortSucceeded>(\n \"@effect-agent/storage-cloudflare/PortSucceeded\",\n)(\"PortSucceeded\", {\n result: PortResult,\n}) {}\n\n/** The routed operation failed TYPED on its owning Object; the failure re-decodes verbatim. */\nexport class PortFailed extends Schema.TaggedClass<PortFailed>(\n \"@effect-agent/storage-cloudflare/PortFailed\",\n)(\"PortFailed\", {\n failure: PortFailure,\n}) {}\n\n/** The uniform answer of one `portCall`: op-specific success or a re-decodable typed failure. */\nexport const PortResponse = Schema.Union([PortSucceeded, PortFailed]);\nexport type PortResponse = typeof PortResponse.Type;\n\n/** The wire form of one port response (what a transport actually carries). */\nexport type PortResponseEnvelope = typeof PortResponse.Encoded;\n\n// ---------------------------------------------------------------------------\n// Codecs\n// ---------------------------------------------------------------------------\n\nexport const encodePortRequest = Schema.encodeEffect(PortRequest);\nexport const decodePortRequest = Schema.decodeUnknownEffect(PortRequest);\nexport const encodePortResponse = Schema.encodeEffect(PortResponse);\nexport const decodePortResponse = Schema.decodeUnknownEffect(PortResponse);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA,MAAa,6BAA6B;AAE1C,MAAM,oBAAoB,OAAO,OAAO,MAAM,OAAO,YAAY,0BAA0B,CAAC;;AAG5F,MAAa,uBAAuB,UAClC,MAAM,SAAA,OACF,GAAG,MAAM,MAAM,GAAG,IAA8B,EAAE,OAClD;;;;;;;;AASN,IAAa,oBAAb,cAAuC,OAAO,YAA+B,CAAC,CAC5E,qBACA,EACE,SAAS,kBACX,CACF,CAAC,CAAC,CAAC;;AAOH,IAAa,kBAAb,cAAqC,OAAO,YAC1C,kDACF,CAAC,CAAC,eAAe,EACf,SAAS,iBACX,CAAC,CAAC,CAAC,CAAC;;AAGJ,IAAa,sBAAb,cAAyC,OAAO,YAC9C,sDACF,CAAC,CAAC,mBAAmB,EACnB,SAAS,iBACX,CAAC,CAAC,CAAC,CAAC;;AAGJ,IAAa,mBAAb,cAAsC,OAAO,YAC3C,mDACF,CAAC,CAAC,gBAAgB,EAChB,SAAS,iBACX,CAAC,CAAC,CAAC,CAAC;;AAGJ,IAAa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CAAC,iBAAiB,EACjB,QAAQ,WACV,CAAC,CAAC,CAAC,CAAC;;AAGJ,IAAa,aAAb,cAAgC,OAAO,YACrC,6CACF,CAAC,CAAC,cAAc,EACd,SAAS,YACX,CAAC,CAAC,CAAC,CAAC;;AAGJ,MAAa,eAAe,OAAO,MAAM,CAAC,eAAe,UAAU,CAAC;AAUpE,MAAa,oBAAoB,OAAO,aAAa,WAAW;AAChE,MAAa,oBAAoB,OAAO,oBAAoB,WAAW;AACvE,MAAa,qBAAqB,OAAO,aAAa,YAAY;AAClE,MAAa,qBAAqB,OAAO,oBAAoB,YAAY"}
|
package/dist/PortRouting.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
|
|
2
2
|
import { LedgerAdmitCall, LedgerAdmitResult, LedgerLookupCall, LedgerLookupResult, LedgerMarkReadyCall, LedgerMarkReadyResult, LedgerRecordChildSettledCall, LedgerRecordChildSettledResult, LedgerRequestAbortCall, LedgerRequestAbortResult, LedgerResolveAdmissionCall, LedgerResolveAdmissionResult, PortFailed, PortProtocolError, PortSucceeded, StoreAppendCall, StoreAppendResult, StoreExportCall, StoreExportResult, StoreInspectTailCall, StoreInspectTailResult, StoreMaterializeCall, StoreMaterializeResult, StoreReadPageCall, StoreReadPageResult, boundPortDiagnostic, decodePortRequest, decodePortResponse, encodePortRequest, encodePortResponse } from "./PortProtocol.mjs";
|
|
3
3
|
import { Context, Effect, Layer, Option, Predicate, Schema, Stream } from "effect";
|
|
4
|
-
import { AdmissionConflict, AdmissionIndeterminate, ChildAttachmentSnapshot, JoinedToHost, LedgerError, RecoverySnapshot, SettlementConflict, SubmissionLedger, SubmissionLookupById } from "@effect-agent/thread/SubmissionLedger";
|
|
4
|
+
import { AdmissionConflict, AdmissionIndeterminate, AdmissionPolicyError, ChildAttachmentSnapshot, JoinedToHost, LedgerError, RecoverySnapshot, SettlementConflict, SubmissionLedger, SubmissionLookupById } from "@effect-agent/thread/SubmissionLedger";
|
|
5
5
|
import { AppendConflict, FenceRejected, ThreadMaterialization, ThreadNotMaterialized, ThreadStore, ThreadStoreError } from "@effect-agent/thread/ThreadStore";
|
|
6
6
|
//#region src/PortRouting.ts
|
|
7
7
|
var PortRouting_exports = /* @__PURE__ */ __exportAll({
|
|
@@ -225,7 +225,7 @@ const makeRoutedLedgerServices = Effect.fn("DoPortRouting.makeRoutedLedgerServic
|
|
|
225
225
|
});
|
|
226
226
|
const routed = SubmissionLedger.of({
|
|
227
227
|
capabilities: local.capabilities,
|
|
228
|
-
admit: (request) => request.threadId === options.localThreadId ? local.admit(request) : foreignLedgerCall("ledger admit", request.threadId, LedgerAdmitCall.make({ request }), LedgerAdmitResult, AdmissionConflict).pipe(Effect.map((reply) => reply.result)),
|
|
228
|
+
admit: (request) => request.threadId === options.localThreadId ? local.admit(request) : foreignLedgerCall("ledger admit", request.threadId, LedgerAdmitCall.make({ request }), LedgerAdmitResult, Schema.Union([AdmissionConflict, AdmissionPolicyError])).pipe(Effect.map((reply) => reply.result)),
|
|
229
229
|
markReady: (request) => submissionTarget("ledger mark ready", request.submissionId).pipe(Effect.flatMap((target) => target._tag === "local" ? local.markReady(request) : foreignLedgerCall("ledger mark ready", target.threadId, LedgerMarkReadyCall.make({ request }), LedgerMarkReadyResult, NoAdditionalPortFailure).pipe(Effect.asVoid))),
|
|
230
230
|
lookup: (request) => request._tag === "SubmissionLookupById" ? submissionTarget("ledger lookup", request.submissionId).pipe(Effect.flatMap((target) => target._tag === "local" ? local.lookup(request) : foreignLookupById("ledger lookup", target.threadId, request.submissionId))) : request.threadId === options.localThreadId ? local.lookup(request) : foreignLedgerCall("ledger lookup", request.threadId, LedgerLookupCall.make({ request }), LedgerLookupResult, NoAdditionalPortFailure).pipe(Effect.map((result) => result.submission === void 0 ? Option.none() : Option.some(result.submission))),
|
|
231
231
|
resolveAdmission: (request) => request.threadId === options.localThreadId ? local.resolveAdmission(request) : resolveForeignAdmission(request.threadId, request),
|
package/dist/PortRouting.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PortRouting.mjs","names":[],"sources":["../src/PortRouting.ts"],"sourcesContent":["import {\n AdmissionIndeterminate,\n AdmissionConflict,\n ChildAttachmentSnapshot,\n JoinedToHost,\n LedgerError,\n RecoverySnapshot,\n SettlementConflict,\n SubmissionLedger,\n SubmissionLookupById,\n type SubmissionLookupByKey,\n type SubmissionSnapshot,\n} from \"@effect-agent/thread/SubmissionLedger\";\nimport {\n AppendConflict,\n ThreadMaterialization,\n ThreadNotMaterialized,\n ThreadStore,\n ThreadStoreError,\n FenceRejected,\n} from \"@effect-agent/thread/ThreadStore\";\nimport { Context, Effect, Layer, Option, Predicate, Schema, Stream } from \"effect\";\n\nimport {\n boundPortDiagnostic,\n decodePortRequest,\n decodePortResponse,\n encodePortRequest,\n encodePortResponse,\n LedgerAdmitCall,\n LedgerAdmitResult,\n LedgerLookupCall,\n LedgerLookupResult,\n LedgerMarkReadyCall,\n LedgerMarkReadyResult,\n LedgerRecordChildSettledCall,\n LedgerRecordChildSettledResult,\n LedgerRequestAbortCall,\n LedgerRequestAbortResult,\n LedgerResolveAdmissionCall,\n LedgerResolveAdmissionResult,\n PortFailed,\n PortProtocolError,\n PortSucceeded,\n StoreAppendCall,\n StoreAppendResult,\n StoreExportCall,\n StoreExportResult,\n StoreInspectTailCall,\n StoreInspectTailResult,\n StoreMaterializeCall,\n StoreMaterializeResult,\n StoreReadPageCall,\n StoreReadPageResult,\n type PortFailure,\n type PortRequest,\n type PortRequestEnvelope,\n type PortResponse,\n type PortResult,\n} from \"./PortProtocol.ts\";\n\ntype ThreadId = ThreadMaterialization[\"threadId\"];\ntype SubmissionId = SubmissionSnapshot[\"submissionId\"];\n\nconst ThreadIdSchema = ThreadMaterialization.fields.threadId;\nconst decodeThreadId = Schema.decodeUnknownEffect(ThreadIdSchema);\n\n/**\n * The ledger row bound routable Submission identities must respect (mirrors the local\n * facet's `MAX_IDENTIFIER_LENGTH`; the minting side already refuses longer identities typed\n * at admission, so a longer identity presented here cannot name any stored row).\n */\nconst MAX_ROUTABLE_SUBMISSION_ID_LENGTH = 1_024;\n\n/** The `{uuidv7}` head of a DC-minted routable Submission identity. */\nconst UUID_HEAD_PATTERN =\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;\n\n/**\n * A transport could not deliver a port request to (or an answer from) the owning\n * Thread's Durable Object. `retryable` carries the platform's own stub signal when one\n * exists. This error never crosses the wire — it is the CALLER-side evidence that the\n * authority was unreachable, which is exactly the case `AdmissionIndeterminate` was\n * specified for (SUB-031).\n */\nexport class PortTransportError extends Schema.TaggedError<PortTransportError>()(\n \"PortTransportError\",\n {\n target: Schema.String,\n message: Schema.String,\n retryable: Schema.optionalKey(Schema.Boolean),\n cause: Schema.optionalKey(Schema.Defect()),\n },\n) {}\n\nconst safeTransportDiagnostic = (cause: unknown): string => {\n try {\n const message = cause instanceof Error ? cause.message : cause;\n\n return boundPortDiagnostic(typeof message === \"string\" ? message : String(message));\n } catch {\n return \"[unavailable transport diagnostic]\";\n }\n};\n\nconst transportRetryableSignal = (cause: unknown): boolean | undefined => {\n if (!Predicate.isObjectKeyword(cause)) return undefined;\n try {\n const signal = Reflect.get(cause, \"retryable\");\n\n return typeof signal === \"boolean\" ? signal : undefined;\n } catch {\n return undefined;\n }\n};\n\n/**\n * Build a `PortTransportError` from an arbitrary thrown transport cause, preserving the\n * platform stub's own `retryable` signal when present.\n */\nexport const portTransportFailure = (target: string, cause: unknown): PortTransportError => {\n const retryable = transportRetryableSignal(cause);\n\n return PortTransportError.make({\n target,\n message: safeTransportDiagnostic(cause),\n ...(retryable === undefined ? {} : { retryable }),\n cause,\n });\n};\n\n/**\n * Delivery of Schema-encoded port envelopes to the Durable Object that owns a FOREIGN\n * Thread (plan §1.3, D-P6-3). The shipped implementation (platform-cloudflare, WP3)\n * calls the owner's `portCall` over native Durable Object JS RPC via\n * `namespace.idFromName(threadId)`; the protocol is transport-agnostic and any carrier\n * that moves the encoded envelopes verbatim satisfies this service. Implementations MUST\n * surface every delivery problem as `PortTransportError` and must never fabricate an answer.\n */\nexport class ThreadPortTransport extends Context.Service<\n ThreadPortTransport,\n {\n readonly call: (\n threadId: ThreadId,\n request: PortRequestEnvelope,\n ) => Effect.Effect<unknown, PortTransportError>;\n }\n>()(\"@effect-agent/storage-cloudflare/ThreadPortTransport\") {}\n\n/** Construction options shared by both routed port Layers. */\nexport interface RoutedPortOptions {\n /**\n * The Thread this Durable Object owns (the Object identity rule is\n * `namespace.idFromName(threadId)`). Requests addressed here execute on the local\n * facet; requests addressed anywhere else route through the transport or fail fast typed.\n */\n readonly localThreadId: ThreadId;\n}\n\n/** Where one port request must execute. */\ntype RouteTarget =\n | { readonly _tag: \"local\" }\n | { readonly _tag: \"foreign\"; readonly threadId: ThreadId };\n\nconst LOCAL: RouteTarget = { _tag: \"local\" };\n\n/**\n * Parse a DC-minted routable Submission identity — `{uuidv7}:{threadId}`, split at the\n * FIRST `:` because the Thread tail may itself contain colons (D-P6-5). This adapter\n * minted the format at admission and is the ONLY component that parses it; identities that do\n * not carry the minted shape (no separator, non-UUID head, empty tail) fall back to the local\n * facet, which is the only authority this Object can consult without inventing an owner.\n * Identities beyond the ledger's 1,024-character row bound fail typed: the minting side\n * refused them at admission, so they cannot name any stored row anywhere.\n */\nconst routableSubmissionTarget = (\n localThreadId: ThreadId,\n): ((operation: string, submissionId: string) => Effect.Effect<RouteTarget, LedgerError>) =>\n Effect.fn(\"DoPortRouting.routableSubmissionTarget\")(function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<RouteTarget, LedgerError> {\n if (submissionId.length > MAX_ROUTABLE_SUBMISSION_ID_LENGTH) {\n return yield* LedgerError.make({\n operation,\n message:\n `A Submission identity of ${submissionId.length} characters exceeds the ` +\n `${MAX_ROUTABLE_SUBMISSION_ID_LENGTH}-character routable identity bound; admission ` +\n \"refuses such identities, so it cannot name any stored row.\",\n });\n }\n const separator = submissionId.indexOf(\":\");\n\n if (separator === -1) return LOCAL;\n if (!UUID_HEAD_PATTERN.test(submissionId.slice(0, separator))) return LOCAL;\n const tail = submissionId.slice(separator + 1);\n\n if (tail === localThreadId) return LOCAL;\n\n return yield* decodeThreadId(tail).pipe(\n Effect.map((threadId): RouteTarget => ({ _tag: \"foreign\", threadId })),\n Effect.orElseSucceed(() => LOCAL),\n );\n });\n\nconst NoAdditionalPortFailure = Schema.Never;\nconst AbortPortFailure = Schema.Union([SettlementConflict, JoinedToHost]);\nconst AppendPortFailure = Schema.Union([ThreadNotMaterialized, AppendConflict, FenceRejected]);\n\n/**\n * The fail-fast refusal for any foreign operation OUTSIDE the closed route-capable subset\n * (plan §1.3): honesty over accidental distribution.\n */\nconst crossThreadLedgerError = (operation: string, target: string): LedgerError =>\n LedgerError.make({\n operation,\n message:\n `${operation} addressed to foreign Thread ${target} is not route-capable; the ` +\n \"closed cross-Object subset is admit, markReady, lookup, resolveAdmission, \" +\n \"requestAbort, and recordChildSettled. Every other ledger operation is lane-local by \" +\n \"construction and must execute inside the owning Thread's Durable Object.\",\n });\n\nconst crossThreadStoreError = (operation: string, target: string): ThreadStoreError =>\n ThreadStoreError.make({\n operation,\n message:\n `${operation} addressed to foreign Thread ${target} is not route-capable; the ` +\n \"closed cross-Object subset is materialize, append, read (paged), inspectTail, and \" +\n \"export. Observation and checkpoints are lane-local by construction and must execute \" +\n \"inside the owning Thread's Durable Object.\",\n });\n\nconst makeTransportCall = (transport: ThreadPortTransport[\"Service\"]) =>\n Effect.fn(\"DoPortRouting.transportCall\")(function* (target: ThreadId, call: PortRequest) {\n const encoded = yield* encodePortRequest(call).pipe(\n Effect.mapError((error) =>\n PortProtocolError.make({\n message: boundPortDiagnostic(`The port request could not be encoded: ${error.message}`),\n }),\n ),\n );\n\n const raw = yield* transport.call(target, encoded);\n\n return yield* decodePortResponse(raw).pipe(\n Effect.mapError((error) =>\n PortProtocolError.make({\n message: boundPortDiagnostic(`The port response could not be decoded: ${error.message}`),\n }),\n ),\n );\n });\n\ntype TransportCall = ReturnType<typeof makeTransportCall>;\n\nconst makeRoutedLedgerServices = Effect.fn(\"DoPortRouting.makeRoutedLedgerServices\")(function* (\n options: RoutedPortOptions,\n) {\n const local = yield* SubmissionLedger;\n const transport = yield* ThreadPortTransport;\n const transportCall: TransportCall = makeTransportCall(transport);\n const submissionTarget = routableSubmissionTarget(options.localThreadId);\n\n const routeFailure =\n (operation: string, target: string) =>\n (error: PortTransportError | PortProtocolError): LedgerError =>\n LedgerError.make({\n operation,\n message: boundPortDiagnostic(\n `Routed ${operation} to the Thread Object owning ${target} failed: ${error.message}`,\n ),\n cause: error,\n });\n\n /**\n * One routed ledger call: encode, deliver, decode, then narrow the uniform envelope to the\n * operation's own result and failure surface. A foreign `LedgerError` is always in-channel;\n * any failure outside the operation's declared surface — including protocol anomalies — is\n * folded into a `LedgerError` naming the anomaly instead of being erased or re-thrown raw.\n */\n const foreignLedgerCall = <ResultSchema extends Schema.Top, FailureSchema extends Schema.Top>(\n operation: string,\n target: ThreadId,\n call: PortRequest,\n resultSchema: ResultSchema,\n failureSchema: FailureSchema,\n ): Effect.Effect<ResultSchema[\"Type\"], FailureSchema[\"Type\"] | LedgerError> => {\n const isExpectedResult = Schema.is(resultSchema);\n const isExpectedFailure = Schema.is(failureSchema);\n\n return transportCall(target, call).pipe(\n Effect.mapError(routeFailure(operation, target)),\n Effect.flatMap(\n (response): Effect.Effect<ResultSchema[\"Type\"], FailureSchema[\"Type\"] | LedgerError> => {\n if (response._tag === \"PortFailed\") {\n const failure = response.failure;\n\n if (isExpectedFailure(failure)) return Effect.fail(failure);\n if (failure._tag === \"LedgerError\") return Effect.fail(failure);\n\n return Effect.fail(\n LedgerError.make({\n operation,\n message: boundPortDiagnostic(\n `The Thread Object owning ${target} answered ${operation} with the ` +\n `out-of-contract failure ${failure._tag}: ${failure.message}`,\n ),\n cause: failure,\n }),\n );\n }\n const result = response.result;\n\n if (!isExpectedResult(result)) {\n return Effect.fail(\n LedgerError.make({\n operation,\n message:\n `The Thread Object owning ${target} answered ${operation} with the ` +\n `mismatched result ${result._tag}.`,\n }),\n );\n }\n\n return Effect.succeed(result);\n },\n ),\n Effect.withSpan(\"DoPortRouting.foreignLedgerCall\", {\n attributes: { operation, target },\n }),\n );\n };\n\n /**\n * Routed `resolveAdmission` — where the S2 tri-state becomes real (plan §1.3): when the\n * owning Object cannot be reached, or its answer cannot be understood, the routed adapter\n * answers `AdmissionIndeterminate{reason}` and NEVER `NotAdmitted` — an unreachable\n * authority proves nothing, and only `NotAdmitted` permits an admission attempt (SUB-031).\n * A typed `LedgerError` answered BY the authority still fails typed: the authority was\n * reached and reported its own storage failure.\n */\n const resolveForeignAdmission = (\n target: ThreadId,\n request: SubmissionLookupByKey,\n ): Effect.Effect<\n | AdmissionIndeterminate\n | Extract<PortResult, { readonly _tag: \"LedgerResolveAdmissionResult\" }>[\"resolution\"],\n LedgerError\n > =>\n transportCall(target, LedgerResolveAdmissionCall.make({ request })).pipe(\n Effect.flatMap((response) => {\n if (response._tag === \"PortFailed\") {\n if (response.failure._tag === \"LedgerError\") return Effect.fail(response.failure);\n\n return Effect.succeed(\n AdmissionIndeterminate.make({\n reason: boundPortDiagnostic(\n `The Thread Object owning ${target} answered resolveAdmission with the ` +\n `out-of-contract failure ${response.failure._tag}: ${response.failure.message}`,\n ),\n }),\n );\n }\n if (response.result._tag !== \"LedgerResolveAdmissionResult\") {\n return Effect.succeed(\n AdmissionIndeterminate.make({\n reason: boundPortDiagnostic(\n `The Thread Object owning ${target} answered resolveAdmission with the ` +\n `mismatched result ${response.result._tag}.`,\n ),\n }),\n );\n }\n\n return Effect.succeed(response.result.resolution);\n }),\n Effect.catchTags({\n PortTransportError: (error) =>\n Effect.succeed(\n AdmissionIndeterminate.make({\n reason: boundPortDiagnostic(\n `The Thread Object owning ${target} is unreachable: ${error.message}`,\n ),\n }),\n ),\n PortProtocolError: (error) =>\n Effect.succeed(\n AdmissionIndeterminate.make({\n reason: boundPortDiagnostic(\n `The answer of the Thread Object owning ${target} could not be ` +\n `understood: ${error.message}`,\n ),\n }),\n ),\n }),\n Effect.withSpan(\"DoPortRouting.resolveForeignAdmission\", { attributes: { target } }),\n );\n\n const foreignLookupById = (\n operation: string,\n target: ThreadId,\n submissionId: SubmissionId,\n ): Effect.Effect<Option.Option<SubmissionSnapshot>, LedgerError> =>\n foreignLedgerCall(\n operation,\n target,\n LedgerLookupCall.make({ request: SubmissionLookupById.make({ submissionId }) }),\n LedgerLookupResult,\n NoAdditionalPortFailure,\n ).pipe(\n Effect.map((result) =>\n result.submission === undefined ? Option.none() : Option.some(result.submission),\n ),\n );\n\n /**\n * Enrich a LOCAL parent's recovery snapshot with the lane state of attached children whose\n * rows live in other Durable Objects (plan §1.3): markers first (the local facet already\n * consulted them), then a routed per-child `lookup` for any attached child that is neither\n * local nor marker-settled. A transport failure surfaces as `LedgerError` so the alarm\n * pass retries; the child's canonical Settlement remains the only authority (DUR-015).\n */\n const enrichChildAttachments = Effect.fn(\"DoPortRouting.enrichChildAttachments\")(function* (\n snapshot: RecoverySnapshot,\n ): Effect.fn.Return<RecoverySnapshot, LedgerError> {\n const operation = \"ledger load recovery snapshot\";\n\n const attachments = new Map(\n snapshot.childAttachments.map((attachment) => [attachment.childSubmissionId, attachment]),\n );\n\n let enriched = false;\n\n for (const reservation of snapshot.childReservations) {\n const childSubmissionId = reservation.childSubmissionId;\n\n if (childSubmissionId === undefined || attachments.has(childSubmissionId)) continue;\n const target = yield* submissionTarget(operation, childSubmissionId);\n\n // A local or opaque child identity was already answered authoritatively by the local\n // facet; absence there means the child admission never committed.\n if (target._tag !== \"foreign\") continue;\n const child = yield* foreignLookupById(operation, target.threadId, childSubmissionId);\n\n if (Option.isNone(child)) continue;\n attachments.set(\n childSubmissionId,\n ChildAttachmentSnapshot.make({\n toolCallId: reservation.parentToolCallId,\n childSubmissionId,\n childState: child.value.state,\n ...(child.value.settledOutcome === undefined\n ? {}\n : { childOutcome: child.value.settledOutcome }),\n }),\n );\n enriched = true;\n }\n if (!enriched) return snapshot;\n // Rebuild in reservation (parent Tool Call) order, the order the local facet documents.\n const ordered: Array<ChildAttachmentSnapshot> = [];\n\n for (const reservation of snapshot.childReservations) {\n if (reservation.childSubmissionId === undefined) continue;\n const attachment = attachments.get(reservation.childSubmissionId);\n\n if (attachment !== undefined) ordered.push(attachment);\n }\n\n return RecoverySnapshot.make({ ...snapshot, childAttachments: ordered });\n });\n\n const routed = SubmissionLedger.of({\n capabilities: local.capabilities,\n\n admit: (request) =>\n request.threadId === options.localThreadId\n ? local.admit(request)\n : foreignLedgerCall(\n \"ledger admit\",\n request.threadId,\n LedgerAdmitCall.make({ request }),\n LedgerAdmitResult,\n AdmissionConflict,\n ).pipe(Effect.map((reply) => reply.result)),\n\n markReady: (request) =>\n submissionTarget(\"ledger mark ready\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.markReady(request)\n : foreignLedgerCall(\n \"ledger mark ready\",\n target.threadId,\n LedgerMarkReadyCall.make({ request }),\n LedgerMarkReadyResult,\n NoAdditionalPortFailure,\n ).pipe(Effect.asVoid),\n ),\n ),\n\n lookup: (request) =>\n request._tag === \"SubmissionLookupById\"\n ? submissionTarget(\"ledger lookup\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.lookup(request)\n : foreignLookupById(\"ledger lookup\", target.threadId, request.submissionId),\n ),\n )\n : request.threadId === options.localThreadId\n ? local.lookup(request)\n : foreignLedgerCall(\n \"ledger lookup\",\n request.threadId,\n LedgerLookupCall.make({ request }),\n LedgerLookupResult,\n NoAdditionalPortFailure,\n ).pipe(\n Effect.map((result) =>\n result.submission === undefined ? Option.none() : Option.some(result.submission),\n ),\n ),\n\n resolveAdmission: (request) =>\n request.threadId === options.localThreadId\n ? local.resolveAdmission(request)\n : resolveForeignAdmission(request.threadId, request),\n\n requestAbort: (request) =>\n submissionTarget(\"ledger request abort\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.requestAbort(request)\n : foreignLedgerCall(\n \"ledger request abort\",\n target.threadId,\n LedgerRequestAbortCall.make({ request }),\n LedgerRequestAbortResult,\n AbortPortFailure,\n ).pipe(Effect.map((reply) => reply.intent)),\n ),\n ),\n\n recordChildSettled: (request) =>\n submissionTarget(\"ledger record child settled\", request.parentSubmissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.recordChildSettled(request)\n : foreignLedgerCall(\n \"ledger record child settled\",\n target.threadId,\n LedgerRecordChildSettledCall.make({ request }),\n LedgerRecordChildSettledResult,\n NoAdditionalPortFailure,\n ).pipe(Effect.map((reply) => reply.outcome)),\n ),\n ),\n\n // Every operation below is lane-local by construction (plan §1.3): a foreign address is\n // an out-of-contract call and fails fast typed instead of being quietly distributed.\n claim: (request) =>\n request.threadId === options.localThreadId\n ? local.claim(request)\n : Effect.fail(crossThreadLedgerError(\"ledger claim\", request.threadId)),\n\n claimJoining: (request) =>\n request.threadId === options.localThreadId\n ? local.claimJoining(request)\n : Effect.fail(crossThreadLedgerError(\"ledger claim joining\", request.threadId)),\n\n renewOwnership: (request) =>\n submissionTarget(\"ledger renew ownership\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.renewOwnership(request)\n : Effect.fail(crossThreadLedgerError(\"ledger renew ownership\", target.threadId)),\n ),\n ),\n\n releaseOwnership: (request) =>\n submissionTarget(\"ledger release ownership\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.releaseOwnership(request)\n : Effect.fail(crossThreadLedgerError(\"ledger release ownership\", target.threadId)),\n ),\n ),\n\n markInputApplied: (request) =>\n submissionTarget(\"ledger mark input applied\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.markInputApplied(request)\n : Effect.fail(crossThreadLedgerError(\"ledger mark input applied\", target.threadId)),\n ),\n ),\n\n reserveSettlement: (request) =>\n submissionTarget(\"ledger reserve settlement\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.reserveSettlement(request)\n : Effect.fail(crossThreadLedgerError(\"ledger reserve settlement\", target.threadId)),\n ),\n ),\n\n finalizeSettlement: (request) =>\n submissionTarget(\"ledger finalize settlement\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.finalizeSettlement(request)\n : Effect.fail(crossThreadLedgerError(\"ledger finalize settlement\", target.threadId)),\n ),\n ),\n\n markJoined: (request) =>\n submissionTarget(\"ledger mark joined\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.markJoined(request)\n : Effect.fail(crossThreadLedgerError(\"ledger mark joined\", target.threadId)),\n ),\n ),\n\n revertJoining: (request) =>\n submissionTarget(\"ledger revert joining\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.revertJoining(request)\n : Effect.fail(crossThreadLedgerError(\"ledger revert joining\", target.threadId)),\n ),\n ),\n\n suspend: (request) =>\n submissionTarget(\"ledger suspend\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.suspend(request)\n : Effect.fail(crossThreadLedgerError(\"ledger suspend\", target.threadId)),\n ),\n ),\n\n recordApprovalDecision: (command) =>\n submissionTarget(\"ledger record approval decision\", command.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.recordApprovalDecision(command)\n : Effect.fail(\n crossThreadLedgerError(\"ledger record approval decision\", target.threadId),\n ),\n ),\n ),\n\n markUnknown: (request) =>\n submissionTarget(\"ledger mark unknown\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.markUnknown(request)\n : Effect.fail(crossThreadLedgerError(\"ledger mark unknown\", target.threadId)),\n ),\n ),\n\n recordUnknownResolution: (command) =>\n submissionTarget(\"ledger record unknown resolution\", command.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.recordUnknownResolution(command)\n : Effect.fail(\n crossThreadLedgerError(\"ledger record unknown resolution\", target.threadId),\n ),\n ),\n ),\n\n reserveChildBudget: (request) =>\n submissionTarget(\"ledger reserve child budget\", request.parentSubmissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.reserveChildBudget(request)\n : Effect.fail(crossThreadLedgerError(\"ledger reserve child budget\", target.threadId)),\n ),\n ),\n\n // Reservation identities carry no Thread address; the reservation row lives in the\n // parent's own Object and these transitions are parent-lane-local by construction, so\n // they always execute on the local facet (which fails typed for an unknown row).\n attachChildToReservation: local.attachChildToReservation,\n beginChildBudgetRelease: local.beginChildBudgetRelease,\n releaseChildBudget: local.releaseChildBudget,\n\n // The local scan IS the whole worklist: one Thread per Object (durability §5).\n scanNonterminal: local.scanNonterminal,\n\n readAbortIntent: (request) =>\n submissionTarget(\"ledger read abort intent\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.readAbortIntent(request)\n : Effect.fail(crossThreadLedgerError(\"ledger read abort intent\", target.threadId)),\n ),\n ),\n\n loadRecoverySnapshot: (request) =>\n submissionTarget(\"ledger load recovery snapshot\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.loadRecoverySnapshot(request).pipe(Effect.flatMap(enrichChildAttachments))\n : Effect.fail(crossThreadLedgerError(\"ledger load recovery snapshot\", target.threadId)),\n ),\n ),\n });\n\n return Context.make(SubmissionLedger, routed);\n});\n\nconst makeRoutedStoreServices = Effect.fn(\"DoPortRouting.makeRoutedStoreServices\")(function* (\n options: RoutedPortOptions,\n) {\n const local = yield* ThreadStore;\n const checkpoints = local.checkpoints;\n const transport = yield* ThreadPortTransport;\n const transportCall: TransportCall = makeTransportCall(transport);\n\n const routeFailure =\n (operation: string, target: string) =>\n (error: PortTransportError | PortProtocolError): ThreadStoreError =>\n ThreadStoreError.make({\n operation,\n message: boundPortDiagnostic(\n `Routed ${operation} to the Thread Object owning ${target} failed: ${error.message}`,\n ),\n cause: error,\n });\n\n /** The store twin of `foreignLedgerCall` with `ThreadStoreError` as the base error. */\n const foreignStoreCall = <ResultSchema extends Schema.Top, FailureSchema extends Schema.Top>(\n operation: string,\n target: ThreadId,\n call: PortRequest,\n resultSchema: ResultSchema,\n failureSchema: FailureSchema,\n ): Effect.Effect<ResultSchema[\"Type\"], FailureSchema[\"Type\"] | ThreadStoreError> => {\n const isExpectedResult = Schema.is(resultSchema);\n const isExpectedFailure = Schema.is(failureSchema);\n\n return transportCall(target, call).pipe(\n Effect.mapError(routeFailure(operation, target)),\n Effect.flatMap(\n (\n response,\n ): Effect.Effect<ResultSchema[\"Type\"], FailureSchema[\"Type\"] | ThreadStoreError> => {\n if (response._tag === \"PortFailed\") {\n const failure = response.failure;\n\n if (isExpectedFailure(failure)) return Effect.fail(failure);\n if (failure._tag === \"ThreadStoreError\") return Effect.fail(failure);\n\n return Effect.fail(\n ThreadStoreError.make({\n operation,\n message: boundPortDiagnostic(\n `The Thread Object owning ${target} answered ${operation} with the ` +\n `out-of-contract failure ${failure._tag}: ${failure.message}`,\n ),\n cause: failure,\n }),\n );\n }\n const result = response.result;\n\n if (!isExpectedResult(result)) {\n return Effect.fail(\n ThreadStoreError.make({\n operation,\n message:\n `The Thread Object owning ${target} answered ${operation} with the ` +\n `mismatched result ${result._tag}.`,\n }),\n );\n }\n\n return Effect.succeed(result);\n },\n ),\n Effect.withSpan(\"DoPortRouting.foreignStoreCall\", {\n attributes: { operation, target },\n }),\n );\n };\n\n const routed = ThreadStore.of({\n materialize: (request) =>\n request.threadId === options.localThreadId\n ? local.materialize(request)\n : foreignStoreCall(\n \"thread materialize\",\n request.threadId,\n StoreMaterializeCall.make({ request }),\n StoreMaterializeResult,\n FenceRejected,\n ).pipe(Effect.asVoid),\n\n append: (request) =>\n request.threadId === options.localThreadId\n ? local.append(request)\n : foreignStoreCall(\n \"thread append\",\n request.threadId,\n StoreAppendCall.make({ request }),\n StoreAppendResult,\n AppendPortFailure,\n ).pipe(Effect.map((reply) => reply.result)),\n\n read: (request) =>\n request.threadId === options.localThreadId\n ? local.read(request)\n : Stream.unwrap(\n foreignStoreCall(\n \"thread read\",\n request.threadId,\n StoreReadPageCall.make({ request }),\n StoreReadPageResult,\n ThreadNotMaterialized,\n ).pipe(Effect.map((reply) => Stream.fromIterable(reply.records))),\n ),\n\n inspectTail: (request) =>\n request.threadId === options.localThreadId\n ? local.inspectTail(request)\n : foreignStoreCall(\n \"thread inspect tail\",\n request.threadId,\n StoreInspectTailCall.make({ request }),\n StoreInspectTailResult,\n ThreadNotMaterialized,\n ).pipe(Effect.map((reply) => reply.tail)),\n\n export: (request) =>\n request.threadId === options.localThreadId\n ? local.export(request)\n : foreignStoreCall(\n \"thread export\",\n request.threadId,\n StoreExportCall.make({ request }),\n StoreExportResult,\n ThreadNotMaterialized,\n ).pipe(Effect.map((reply) => reply.export)),\n\n // Observation and checkpoints are lane-local by construction (plan §1.3): the closed\n // route-capable store subset is materialize/append/read/inspectTail/export, and a\n // foreign address on anything else fails fast typed.\n observe: (request) =>\n request.threadId === options.localThreadId\n ? local.observe(request)\n : Stream.unwrap(Effect.fail(crossThreadStoreError(\"thread observe\", request.threadId))),\n\n ...(checkpoints === undefined\n ? {}\n : {\n checkpoints: {\n save: (request) =>\n request.checkpoint.threadId === options.localThreadId\n ? checkpoints.save(request)\n : Effect.fail(\n crossThreadStoreError(\"thread save checkpoint\", request.checkpoint.threadId),\n ),\n load: (request) =>\n request.threadId === options.localThreadId\n ? checkpoints.load(request)\n : Effect.fail(crossThreadStoreError(\"thread load checkpoint\", request.threadId)),\n },\n }),\n });\n\n return Context.make(ThreadStore, routed);\n});\n\n/**\n * Routing decorator over the LOCAL `SubmissionLedger` facet (plan §1.3): a request addressing\n * this Object's Thread executes locally; a route-capable request addressing another\n * Thread is Schema-encoded onto the `ThreadPortTransport` and executed by the\n * owning Object's local facet; any other foreign request fails fast typed. Provide the WP1\n * local facet (`submissionLedgerLayer`/`ledgerLayer`) and a transport to close it.\n */\nexport const routedSubmissionLedgerLayer = (\n options: RoutedPortOptions,\n): Layer.Layer<SubmissionLedger, never, SubmissionLedger | ThreadPortTransport> =>\n Layer.effectContext(makeRoutedLedgerServices(options));\n\n/**\n * Routing decorator over the LOCAL `ThreadStore` facet (plan §1.3): this-thread\n * requests execute locally; foreign materialize/append/read/inspectTail/export travel the\n * transport; foreign observation and checkpoints fail fast typed.\n */\nexport const routedThreadStoreLayer = (\n options: RoutedPortOptions,\n): Layer.Layer<ThreadStore, never, ThreadStore | ThreadPortTransport> =>\n Layer.effectContext(makeRoutedStoreServices(options));\n\n// ---------------------------------------------------------------------------\n// Owner-side execution\n// ---------------------------------------------------------------------------\n\n/** Fold one port operation's typed failures into the uniform response envelope. */\nconst capture = <Failure extends PortFailure>(\n effect: Effect.Effect<PortResult, Failure>,\n): Effect.Effect<PortResponse> =>\n effect.pipe(\n Effect.map((result): PortResponse => PortSucceeded.make({ result })),\n Effect.catch((failure) => Effect.succeed<PortResponse>(PortFailed.make({ failure }))),\n );\n\n/**\n * Execute one decoded port request against THIS Object's LOCAL facets — the owner-side half\n * of the routed ports (plan §1.3). Callers must provide the WP1 local facets, never the\n * routed decorators: the routing layer already established that this Object owns the\n * addressed Thread, and re-routing here could bounce a request between Objects.\n * Failures never escape — every typed port failure becomes a `PortFailed` envelope that\n * re-decodes on the caller side.\n */\nexport const executePortRequest = Effect.fn(\"DoPortRouting.executePortRequest\")(function* (\n request: PortRequest,\n): Effect.fn.Return<PortResponse, never, SubmissionLedger | ThreadStore> {\n switch (request._tag) {\n case \"LedgerAdmit\": {\n const ledger = yield* SubmissionLedger;\n\n return yield* capture(\n ledger\n .admit(request.request)\n .pipe(Effect.map((result) => LedgerAdmitResult.make({ result }))),\n );\n }\n case \"LedgerMarkReady\": {\n const ledger = yield* SubmissionLedger;\n\n return yield* capture(\n ledger.markReady(request.request).pipe(Effect.map(() => LedgerMarkReadyResult.make({}))),\n );\n }\n case \"LedgerLookup\": {\n const ledger = yield* SubmissionLedger;\n\n return yield* capture(\n ledger\n .lookup(request.request)\n .pipe(\n Effect.map((submission) =>\n Option.isSome(submission)\n ? LedgerLookupResult.make({ submission: submission.value })\n : LedgerLookupResult.make({}),\n ),\n ),\n );\n }\n case \"LedgerResolveAdmission\": {\n const ledger = yield* SubmissionLedger;\n\n return yield* capture(\n ledger\n .resolveAdmission(request.request)\n .pipe(Effect.map((resolution) => LedgerResolveAdmissionResult.make({ resolution }))),\n );\n }\n case \"LedgerRequestAbort\": {\n const ledger = yield* SubmissionLedger;\n\n return yield* capture(\n ledger\n .requestAbort(request.request)\n .pipe(Effect.map((intent) => LedgerRequestAbortResult.make({ intent }))),\n );\n }\n case \"LedgerRecordChildSettled\": {\n const ledger = yield* SubmissionLedger;\n\n return yield* capture(\n ledger\n .recordChildSettled(request.request)\n .pipe(Effect.map((outcome) => LedgerRecordChildSettledResult.make({ outcome }))),\n );\n }\n case \"StoreMaterialize\": {\n const store = yield* ThreadStore;\n\n return yield* capture(\n store.materialize(request.request).pipe(Effect.map(() => StoreMaterializeResult.make({}))),\n );\n }\n case \"StoreAppend\": {\n const store = yield* ThreadStore;\n\n return yield* capture(\n store\n .append(request.request)\n .pipe(Effect.map((result) => StoreAppendResult.make({ result }))),\n );\n }\n case \"StoreReadPage\": {\n const store = yield* ThreadStore;\n\n return yield* capture(\n store.read(request.request).pipe(\n Stream.runCollect,\n Effect.map((records) => StoreReadPageResult.make({ records: [...records] })),\n ),\n );\n }\n case \"StoreInspectTail\": {\n const store = yield* ThreadStore;\n\n return yield* capture(\n store\n .inspectTail(request.request)\n .pipe(Effect.map((tail) => StoreInspectTailResult.make({ tail }))),\n );\n }\n case \"StoreExport\": {\n const store = yield* ThreadStore;\n\n return yield* capture(\n store\n .export(request.request)\n .pipe(Effect.map((threadExport) => StoreExportResult.make({ export: threadExport }))),\n );\n }\n }\n});\n\n/**\n * The last-resort wire fallback when even encoding a response fails: the literal encoded\n * form of `PortFailed(PortProtocolError)` — tagged classes of bounded strings encode to\n * exactly this shape, so no Schema round trip is needed to produce it.\n */\nconst encodedProtocolFailure = (message: string): unknown => ({\n _tag: \"PortFailed\",\n failure: { _tag: \"PortProtocolError\", message: boundPortDiagnostic(message) },\n});\n\n/**\n * The complete owner-side endpoint body for `portCall` (D-P6-3): decode the wire request,\n * execute it against this Object's LOCAL facets, and answer with the encoded response\n * envelope. Total by construction — a request that cannot be decoded, or a response that\n * cannot be encoded, answers `PortFailed(PortProtocolError)` instead of throwing, so the\n * transport never has to interpret exceptions as protocol answers.\n */\nexport const handleEncodedPortRequest = Effect.fn(\"DoPortRouting.handleEncodedPortRequest\")(\n function* (encoded: unknown): Effect.fn.Return<unknown, never, SubmissionLedger | ThreadStore> {\n const response = yield* decodePortRequest(encoded).pipe(\n Effect.flatMap(executePortRequest),\n Effect.catch((error) =>\n Effect.succeed<PortResponse>(\n PortFailed.make({\n failure: PortProtocolError.make({\n message: boundPortDiagnostic(\n `The port request could not be decoded: ${error.message}`,\n ),\n }),\n }),\n ),\n ),\n );\n\n return yield* encodePortResponse(response).pipe(\n Effect.catch((error) =>\n Effect.succeed(\n encodedProtocolFailure(`The port response could not be encoded: ${error.message}`),\n ),\n ),\n );\n },\n);\n"],"mappings":";;;;;;;;;;;;;;;AAgEA,MAAM,iBAAiB,sBAAsB,OAAO;AACpD,MAAM,iBAAiB,OAAO,oBAAoB,cAAc;;;;;;AAOhE,MAAM,oCAAoC;;AAG1C,MAAM,oBACJ;;;;;;;;AASF,IAAa,qBAAb,cAAwC,OAAO,YAAgC,CAAC,CAC9E,sBACA;CACE,QAAQ,OAAO;CACf,SAAS,OAAO;CAChB,WAAW,OAAO,YAAY,OAAO,OAAO;CAC5C,OAAO,OAAO,YAAY,OAAO,OAAO,CAAC;AAC3C,CACF,CAAC,CAAC,CAAC;AAEH,MAAM,2BAA2B,UAA2B;CAC1D,IAAI;EACF,MAAM,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GAErB,OAAO,OAAO,QACZ,MAAM,KAAK,QAAQ,OAAO,CAAC,CAAC,KAC1B,OAAO,YACP,OAAO,KAAK,YAAY,oBAAoB,KAAK,EAAE,SAAS,CAAC,GAAG,OAAO,EAAE,CAAC,CAAC,CAC7E,CACF;EACF;EACA,KAAK,oBAAoB;GACvB,MAAM,QAAQ,OAAO;GAErB,OAAO,OAAO,QACZ,MACG,YAAY,QAAQ,OAAO,CAAC,CAC5B,KAAK,OAAO,KAAK,SAAS,uBAAuB,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,CACrE;EACF;EACA,KAAK,eAAe;GAClB,MAAM,QAAQ,OAAO;GAErB,OAAO,OAAO,QACZ,MACG,OAAO,QAAQ,OAAO,CAAC,CACvB,KAAK,OAAO,KAAK,iBAAiB,kBAAkB,KAAK,EAAE,QAAQ,aAAa,CAAC,CAAC,CAAC,CACxF;EACF;CACF;AACF,CAAC;;;;;;AAOD,MAAM,0BAA0B,aAA8B;CAC5D,MAAM;CACN,SAAS;EAAE,MAAM;EAAqB,SAAS,oBAAoB,OAAO;CAAE;AAC9E;;;;;;;;AASA,MAAa,2BAA2B,OAAO,GAAG,wCAAwC,CAAC,CACzF,WAAW,SAAoF;CAC7F,MAAM,WAAW,OAAO,kBAAkB,OAAO,CAAC,CAAC,KACjD,OAAO,QAAQ,kBAAkB,GACjC,OAAO,OAAO,UACZ,OAAO,QACL,WAAW,KAAK,EACd,SAAS,kBAAkB,KAAK,EAC9B,SAAS,oBACP,0CAA0C,MAAM,SAClD,EACF,CAAC,EACH,CAAC,CACH,CACF,CACF;CAEA,OAAO,OAAO,mBAAmB,QAAQ,CAAC,CAAC,KACzC,OAAO,OAAO,UACZ,OAAO,QACL,uBAAuB,2CAA2C,MAAM,SAAS,CACnF,CACF,CACF;AACF,CACF"}
|
|
1
|
+
{"version":3,"file":"PortRouting.mjs","names":[],"sources":["../src/PortRouting.ts"],"sourcesContent":["import {\n AdmissionIndeterminate,\n AdmissionConflict,\n AdmissionPolicyError,\n ChildAttachmentSnapshot,\n JoinedToHost,\n LedgerError,\n RecoverySnapshot,\n SettlementConflict,\n SubmissionLedger,\n SubmissionLookupById,\n type SubmissionLookupByKey,\n type SubmissionSnapshot,\n} from \"@effect-agent/thread/SubmissionLedger\";\nimport {\n AppendConflict,\n ThreadMaterialization,\n ThreadNotMaterialized,\n ThreadStore,\n ThreadStoreError,\n FenceRejected,\n} from \"@effect-agent/thread/ThreadStore\";\nimport { Context, Effect, Layer, Option, Predicate, Schema, Stream } from \"effect\";\n\nimport {\n boundPortDiagnostic,\n decodePortRequest,\n decodePortResponse,\n encodePortRequest,\n encodePortResponse,\n LedgerAdmitCall,\n LedgerAdmitResult,\n LedgerLookupCall,\n LedgerLookupResult,\n LedgerMarkReadyCall,\n LedgerMarkReadyResult,\n LedgerRecordChildSettledCall,\n LedgerRecordChildSettledResult,\n LedgerRequestAbortCall,\n LedgerRequestAbortResult,\n LedgerResolveAdmissionCall,\n LedgerResolveAdmissionResult,\n PortFailed,\n PortProtocolError,\n PortSucceeded,\n StoreAppendCall,\n StoreAppendResult,\n StoreExportCall,\n StoreExportResult,\n StoreInspectTailCall,\n StoreInspectTailResult,\n StoreMaterializeCall,\n StoreMaterializeResult,\n StoreReadPageCall,\n StoreReadPageResult,\n type PortFailure,\n type PortRequest,\n type PortRequestEnvelope,\n type PortResponse,\n type PortResult,\n} from \"./PortProtocol.ts\";\n\ntype ThreadId = ThreadMaterialization[\"threadId\"];\ntype SubmissionId = SubmissionSnapshot[\"submissionId\"];\n\nconst ThreadIdSchema = ThreadMaterialization.fields.threadId;\nconst decodeThreadId = Schema.decodeUnknownEffect(ThreadIdSchema);\n\n/**\n * The ledger row bound routable Submission identities must respect (mirrors the local\n * facet's `MAX_IDENTIFIER_LENGTH`; the minting side already refuses longer identities typed\n * at admission, so a longer identity presented here cannot name any stored row).\n */\nconst MAX_ROUTABLE_SUBMISSION_ID_LENGTH = 1_024;\n\n/** The `{uuidv7}` head of a DC-minted routable Submission identity. */\nconst UUID_HEAD_PATTERN =\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;\n\n/**\n * A transport could not deliver a port request to (or an answer from) the owning\n * Thread's Durable Object. `retryable` carries the platform's own stub signal when one\n * exists. This error never crosses the wire — it is the CALLER-side evidence that the\n * authority was unreachable, which is exactly the case `AdmissionIndeterminate` was\n * specified for (SUB-031).\n */\nexport class PortTransportError extends Schema.TaggedError<PortTransportError>()(\n \"PortTransportError\",\n {\n target: Schema.String,\n message: Schema.String,\n retryable: Schema.optionalKey(Schema.Boolean),\n cause: Schema.optionalKey(Schema.Defect()),\n },\n) {}\n\nconst safeTransportDiagnostic = (cause: unknown): string => {\n try {\n const message = cause instanceof Error ? cause.message : cause;\n\n return boundPortDiagnostic(typeof message === \"string\" ? message : String(message));\n } catch {\n return \"[unavailable transport diagnostic]\";\n }\n};\n\nconst transportRetryableSignal = (cause: unknown): boolean | undefined => {\n if (!Predicate.isObjectKeyword(cause)) return undefined;\n try {\n const signal = Reflect.get(cause, \"retryable\");\n\n return typeof signal === \"boolean\" ? signal : undefined;\n } catch {\n return undefined;\n }\n};\n\n/**\n * Build a `PortTransportError` from an arbitrary thrown transport cause, preserving the\n * platform stub's own `retryable` signal when present.\n */\nexport const portTransportFailure = (target: string, cause: unknown): PortTransportError => {\n const retryable = transportRetryableSignal(cause);\n\n return PortTransportError.make({\n target,\n message: safeTransportDiagnostic(cause),\n ...(retryable === undefined ? {} : { retryable }),\n cause,\n });\n};\n\n/**\n * Delivery of Schema-encoded port envelopes to the Durable Object that owns a FOREIGN\n * Thread (plan §1.3, D-P6-3). The shipped implementation (platform-cloudflare, WP3)\n * calls the owner's `portCall` over native Durable Object JS RPC via\n * `namespace.idFromName(threadId)`; the protocol is transport-agnostic and any carrier\n * that moves the encoded envelopes verbatim satisfies this service. Implementations MUST\n * surface every delivery problem as `PortTransportError` and must never fabricate an answer.\n */\nexport class ThreadPortTransport extends Context.Service<\n ThreadPortTransport,\n {\n readonly call: (\n threadId: ThreadId,\n request: PortRequestEnvelope,\n ) => Effect.Effect<unknown, PortTransportError>;\n }\n>()(\"@effect-agent/storage-cloudflare/ThreadPortTransport\") {}\n\n/** Construction options shared by both routed port Layers. */\nexport interface RoutedPortOptions {\n /**\n * The Thread this Durable Object owns (the Object identity rule is\n * `namespace.idFromName(threadId)`). Requests addressed here execute on the local\n * facet; requests addressed anywhere else route through the transport or fail fast typed.\n */\n readonly localThreadId: ThreadId;\n}\n\n/** Where one port request must execute. */\ntype RouteTarget =\n | { readonly _tag: \"local\" }\n | { readonly _tag: \"foreign\"; readonly threadId: ThreadId };\n\nconst LOCAL: RouteTarget = { _tag: \"local\" };\n\n/**\n * Parse a DC-minted routable Submission identity — `{uuidv7}:{threadId}`, split at the\n * FIRST `:` because the Thread tail may itself contain colons (D-P6-5). This adapter\n * minted the format at admission and is the ONLY component that parses it; identities that do\n * not carry the minted shape (no separator, non-UUID head, empty tail) fall back to the local\n * facet, which is the only authority this Object can consult without inventing an owner.\n * Identities beyond the ledger's 1,024-character row bound fail typed: the minting side\n * refused them at admission, so they cannot name any stored row anywhere.\n */\nconst routableSubmissionTarget = (\n localThreadId: ThreadId,\n): ((operation: string, submissionId: string) => Effect.Effect<RouteTarget, LedgerError>) =>\n Effect.fn(\"DoPortRouting.routableSubmissionTarget\")(function* (\n operation: string,\n submissionId: string,\n ): Effect.fn.Return<RouteTarget, LedgerError> {\n if (submissionId.length > MAX_ROUTABLE_SUBMISSION_ID_LENGTH) {\n return yield* LedgerError.make({\n operation,\n message:\n `A Submission identity of ${submissionId.length} characters exceeds the ` +\n `${MAX_ROUTABLE_SUBMISSION_ID_LENGTH}-character routable identity bound; admission ` +\n \"refuses such identities, so it cannot name any stored row.\",\n });\n }\n const separator = submissionId.indexOf(\":\");\n\n if (separator === -1) return LOCAL;\n if (!UUID_HEAD_PATTERN.test(submissionId.slice(0, separator))) return LOCAL;\n const tail = submissionId.slice(separator + 1);\n\n if (tail === localThreadId) return LOCAL;\n\n return yield* decodeThreadId(tail).pipe(\n Effect.map((threadId): RouteTarget => ({ _tag: \"foreign\", threadId })),\n Effect.orElseSucceed(() => LOCAL),\n );\n });\n\nconst NoAdditionalPortFailure = Schema.Never;\nconst AbortPortFailure = Schema.Union([SettlementConflict, JoinedToHost]);\nconst AppendPortFailure = Schema.Union([ThreadNotMaterialized, AppendConflict, FenceRejected]);\n\n/**\n * The fail-fast refusal for any foreign operation OUTSIDE the closed route-capable subset\n * (plan §1.3): honesty over accidental distribution.\n */\nconst crossThreadLedgerError = (operation: string, target: string): LedgerError =>\n LedgerError.make({\n operation,\n message:\n `${operation} addressed to foreign Thread ${target} is not route-capable; the ` +\n \"closed cross-Object subset is admit, markReady, lookup, resolveAdmission, \" +\n \"requestAbort, and recordChildSettled. Every other ledger operation is lane-local by \" +\n \"construction and must execute inside the owning Thread's Durable Object.\",\n });\n\nconst crossThreadStoreError = (operation: string, target: string): ThreadStoreError =>\n ThreadStoreError.make({\n operation,\n message:\n `${operation} addressed to foreign Thread ${target} is not route-capable; the ` +\n \"closed cross-Object subset is materialize, append, read (paged), inspectTail, and \" +\n \"export. Observation and checkpoints are lane-local by construction and must execute \" +\n \"inside the owning Thread's Durable Object.\",\n });\n\nconst makeTransportCall = (transport: ThreadPortTransport[\"Service\"]) =>\n Effect.fn(\"DoPortRouting.transportCall\")(function* (target: ThreadId, call: PortRequest) {\n const encoded = yield* encodePortRequest(call).pipe(\n Effect.mapError((error) =>\n PortProtocolError.make({\n message: boundPortDiagnostic(`The port request could not be encoded: ${error.message}`),\n }),\n ),\n );\n\n const raw = yield* transport.call(target, encoded);\n\n return yield* decodePortResponse(raw).pipe(\n Effect.mapError((error) =>\n PortProtocolError.make({\n message: boundPortDiagnostic(`The port response could not be decoded: ${error.message}`),\n }),\n ),\n );\n });\n\ntype TransportCall = ReturnType<typeof makeTransportCall>;\n\nconst makeRoutedLedgerServices = Effect.fn(\"DoPortRouting.makeRoutedLedgerServices\")(function* (\n options: RoutedPortOptions,\n) {\n const local = yield* SubmissionLedger;\n const transport = yield* ThreadPortTransport;\n const transportCall: TransportCall = makeTransportCall(transport);\n const submissionTarget = routableSubmissionTarget(options.localThreadId);\n\n const routeFailure =\n (operation: string, target: string) =>\n (error: PortTransportError | PortProtocolError): LedgerError =>\n LedgerError.make({\n operation,\n message: boundPortDiagnostic(\n `Routed ${operation} to the Thread Object owning ${target} failed: ${error.message}`,\n ),\n cause: error,\n });\n\n /**\n * One routed ledger call: encode, deliver, decode, then narrow the uniform envelope to the\n * operation's own result and failure surface. A foreign `LedgerError` is always in-channel;\n * any failure outside the operation's declared surface — including protocol anomalies — is\n * folded into a `LedgerError` naming the anomaly instead of being erased or re-thrown raw.\n */\n const foreignLedgerCall = <ResultSchema extends Schema.Top, FailureSchema extends Schema.Top>(\n operation: string,\n target: ThreadId,\n call: PortRequest,\n resultSchema: ResultSchema,\n failureSchema: FailureSchema,\n ): Effect.Effect<ResultSchema[\"Type\"], FailureSchema[\"Type\"] | LedgerError> => {\n const isExpectedResult = Schema.is(resultSchema);\n const isExpectedFailure = Schema.is(failureSchema);\n\n return transportCall(target, call).pipe(\n Effect.mapError(routeFailure(operation, target)),\n Effect.flatMap(\n (response): Effect.Effect<ResultSchema[\"Type\"], FailureSchema[\"Type\"] | LedgerError> => {\n if (response._tag === \"PortFailed\") {\n const failure = response.failure;\n\n if (isExpectedFailure(failure)) return Effect.fail(failure);\n if (failure._tag === \"LedgerError\") return Effect.fail(failure);\n\n return Effect.fail(\n LedgerError.make({\n operation,\n message: boundPortDiagnostic(\n `The Thread Object owning ${target} answered ${operation} with the ` +\n `out-of-contract failure ${failure._tag}: ${failure.message}`,\n ),\n cause: failure,\n }),\n );\n }\n const result = response.result;\n\n if (!isExpectedResult(result)) {\n return Effect.fail(\n LedgerError.make({\n operation,\n message:\n `The Thread Object owning ${target} answered ${operation} with the ` +\n `mismatched result ${result._tag}.`,\n }),\n );\n }\n\n return Effect.succeed(result);\n },\n ),\n Effect.withSpan(\"DoPortRouting.foreignLedgerCall\", {\n attributes: { operation, target },\n }),\n );\n };\n\n /**\n * Routed `resolveAdmission` — where the S2 tri-state becomes real (plan §1.3): when the\n * owning Object cannot be reached, or its answer cannot be understood, the routed adapter\n * answers `AdmissionIndeterminate{reason}` and NEVER `NotAdmitted` — an unreachable\n * authority proves nothing, and only `NotAdmitted` permits an admission attempt (SUB-031).\n * A typed `LedgerError` answered BY the authority still fails typed: the authority was\n * reached and reported its own storage failure.\n */\n const resolveForeignAdmission = (\n target: ThreadId,\n request: SubmissionLookupByKey,\n ): Effect.Effect<\n | AdmissionIndeterminate\n | Extract<PortResult, { readonly _tag: \"LedgerResolveAdmissionResult\" }>[\"resolution\"],\n LedgerError\n > =>\n transportCall(target, LedgerResolveAdmissionCall.make({ request })).pipe(\n Effect.flatMap((response) => {\n if (response._tag === \"PortFailed\") {\n if (response.failure._tag === \"LedgerError\") return Effect.fail(response.failure);\n\n return Effect.succeed(\n AdmissionIndeterminate.make({\n reason: boundPortDiagnostic(\n `The Thread Object owning ${target} answered resolveAdmission with the ` +\n `out-of-contract failure ${response.failure._tag}: ${response.failure.message}`,\n ),\n }),\n );\n }\n if (response.result._tag !== \"LedgerResolveAdmissionResult\") {\n return Effect.succeed(\n AdmissionIndeterminate.make({\n reason: boundPortDiagnostic(\n `The Thread Object owning ${target} answered resolveAdmission with the ` +\n `mismatched result ${response.result._tag}.`,\n ),\n }),\n );\n }\n\n return Effect.succeed(response.result.resolution);\n }),\n Effect.catchTags({\n PortTransportError: (error) =>\n Effect.succeed(\n AdmissionIndeterminate.make({\n reason: boundPortDiagnostic(\n `The Thread Object owning ${target} is unreachable: ${error.message}`,\n ),\n }),\n ),\n PortProtocolError: (error) =>\n Effect.succeed(\n AdmissionIndeterminate.make({\n reason: boundPortDiagnostic(\n `The answer of the Thread Object owning ${target} could not be ` +\n `understood: ${error.message}`,\n ),\n }),\n ),\n }),\n Effect.withSpan(\"DoPortRouting.resolveForeignAdmission\", { attributes: { target } }),\n );\n\n const foreignLookupById = (\n operation: string,\n target: ThreadId,\n submissionId: SubmissionId,\n ): Effect.Effect<Option.Option<SubmissionSnapshot>, LedgerError> =>\n foreignLedgerCall(\n operation,\n target,\n LedgerLookupCall.make({ request: SubmissionLookupById.make({ submissionId }) }),\n LedgerLookupResult,\n NoAdditionalPortFailure,\n ).pipe(\n Effect.map((result) =>\n result.submission === undefined ? Option.none() : Option.some(result.submission),\n ),\n );\n\n /**\n * Enrich a LOCAL parent's recovery snapshot with the lane state of attached children whose\n * rows live in other Durable Objects (plan §1.3): markers first (the local facet already\n * consulted them), then a routed per-child `lookup` for any attached child that is neither\n * local nor marker-settled. A transport failure surfaces as `LedgerError` so the alarm\n * pass retries; the child's canonical Settlement remains the only authority (DUR-015).\n */\n const enrichChildAttachments = Effect.fn(\"DoPortRouting.enrichChildAttachments\")(function* (\n snapshot: RecoverySnapshot,\n ): Effect.fn.Return<RecoverySnapshot, LedgerError> {\n const operation = \"ledger load recovery snapshot\";\n\n const attachments = new Map(\n snapshot.childAttachments.map((attachment) => [attachment.childSubmissionId, attachment]),\n );\n\n let enriched = false;\n\n for (const reservation of snapshot.childReservations) {\n const childSubmissionId = reservation.childSubmissionId;\n\n if (childSubmissionId === undefined || attachments.has(childSubmissionId)) continue;\n const target = yield* submissionTarget(operation, childSubmissionId);\n\n // A local or opaque child identity was already answered authoritatively by the local\n // facet; absence there means the child admission never committed.\n if (target._tag !== \"foreign\") continue;\n const child = yield* foreignLookupById(operation, target.threadId, childSubmissionId);\n\n if (Option.isNone(child)) continue;\n attachments.set(\n childSubmissionId,\n ChildAttachmentSnapshot.make({\n toolCallId: reservation.parentToolCallId,\n childSubmissionId,\n childState: child.value.state,\n ...(child.value.settledOutcome === undefined\n ? {}\n : { childOutcome: child.value.settledOutcome }),\n }),\n );\n enriched = true;\n }\n if (!enriched) return snapshot;\n // Rebuild in reservation (parent Tool Call) order, the order the local facet documents.\n const ordered: Array<ChildAttachmentSnapshot> = [];\n\n for (const reservation of snapshot.childReservations) {\n if (reservation.childSubmissionId === undefined) continue;\n const attachment = attachments.get(reservation.childSubmissionId);\n\n if (attachment !== undefined) ordered.push(attachment);\n }\n\n return RecoverySnapshot.make({ ...snapshot, childAttachments: ordered });\n });\n\n const routed = SubmissionLedger.of({\n capabilities: local.capabilities,\n\n admit: (request) =>\n request.threadId === options.localThreadId\n ? local.admit(request)\n : foreignLedgerCall(\n \"ledger admit\",\n request.threadId,\n LedgerAdmitCall.make({ request }),\n LedgerAdmitResult,\n Schema.Union([AdmissionConflict, AdmissionPolicyError]),\n ).pipe(Effect.map((reply) => reply.result)),\n\n markReady: (request) =>\n submissionTarget(\"ledger mark ready\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.markReady(request)\n : foreignLedgerCall(\n \"ledger mark ready\",\n target.threadId,\n LedgerMarkReadyCall.make({ request }),\n LedgerMarkReadyResult,\n NoAdditionalPortFailure,\n ).pipe(Effect.asVoid),\n ),\n ),\n\n lookup: (request) =>\n request._tag === \"SubmissionLookupById\"\n ? submissionTarget(\"ledger lookup\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.lookup(request)\n : foreignLookupById(\"ledger lookup\", target.threadId, request.submissionId),\n ),\n )\n : request.threadId === options.localThreadId\n ? local.lookup(request)\n : foreignLedgerCall(\n \"ledger lookup\",\n request.threadId,\n LedgerLookupCall.make({ request }),\n LedgerLookupResult,\n NoAdditionalPortFailure,\n ).pipe(\n Effect.map((result) =>\n result.submission === undefined ? Option.none() : Option.some(result.submission),\n ),\n ),\n\n resolveAdmission: (request) =>\n request.threadId === options.localThreadId\n ? local.resolveAdmission(request)\n : resolveForeignAdmission(request.threadId, request),\n\n requestAbort: (request) =>\n submissionTarget(\"ledger request abort\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.requestAbort(request)\n : foreignLedgerCall(\n \"ledger request abort\",\n target.threadId,\n LedgerRequestAbortCall.make({ request }),\n LedgerRequestAbortResult,\n AbortPortFailure,\n ).pipe(Effect.map((reply) => reply.intent)),\n ),\n ),\n\n recordChildSettled: (request) =>\n submissionTarget(\"ledger record child settled\", request.parentSubmissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.recordChildSettled(request)\n : foreignLedgerCall(\n \"ledger record child settled\",\n target.threadId,\n LedgerRecordChildSettledCall.make({ request }),\n LedgerRecordChildSettledResult,\n NoAdditionalPortFailure,\n ).pipe(Effect.map((reply) => reply.outcome)),\n ),\n ),\n\n // Every operation below is lane-local by construction (plan §1.3): a foreign address is\n // an out-of-contract call and fails fast typed instead of being quietly distributed.\n claim: (request) =>\n request.threadId === options.localThreadId\n ? local.claim(request)\n : Effect.fail(crossThreadLedgerError(\"ledger claim\", request.threadId)),\n\n claimJoining: (request) =>\n request.threadId === options.localThreadId\n ? local.claimJoining(request)\n : Effect.fail(crossThreadLedgerError(\"ledger claim joining\", request.threadId)),\n\n renewOwnership: (request) =>\n submissionTarget(\"ledger renew ownership\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.renewOwnership(request)\n : Effect.fail(crossThreadLedgerError(\"ledger renew ownership\", target.threadId)),\n ),\n ),\n\n releaseOwnership: (request) =>\n submissionTarget(\"ledger release ownership\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.releaseOwnership(request)\n : Effect.fail(crossThreadLedgerError(\"ledger release ownership\", target.threadId)),\n ),\n ),\n\n markInputApplied: (request) =>\n submissionTarget(\"ledger mark input applied\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.markInputApplied(request)\n : Effect.fail(crossThreadLedgerError(\"ledger mark input applied\", target.threadId)),\n ),\n ),\n\n reserveSettlement: (request) =>\n submissionTarget(\"ledger reserve settlement\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.reserveSettlement(request)\n : Effect.fail(crossThreadLedgerError(\"ledger reserve settlement\", target.threadId)),\n ),\n ),\n\n finalizeSettlement: (request) =>\n submissionTarget(\"ledger finalize settlement\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.finalizeSettlement(request)\n : Effect.fail(crossThreadLedgerError(\"ledger finalize settlement\", target.threadId)),\n ),\n ),\n\n markJoined: (request) =>\n submissionTarget(\"ledger mark joined\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.markJoined(request)\n : Effect.fail(crossThreadLedgerError(\"ledger mark joined\", target.threadId)),\n ),\n ),\n\n revertJoining: (request) =>\n submissionTarget(\"ledger revert joining\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.revertJoining(request)\n : Effect.fail(crossThreadLedgerError(\"ledger revert joining\", target.threadId)),\n ),\n ),\n\n suspend: (request) =>\n submissionTarget(\"ledger suspend\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.suspend(request)\n : Effect.fail(crossThreadLedgerError(\"ledger suspend\", target.threadId)),\n ),\n ),\n\n recordApprovalDecision: (command) =>\n submissionTarget(\"ledger record approval decision\", command.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.recordApprovalDecision(command)\n : Effect.fail(\n crossThreadLedgerError(\"ledger record approval decision\", target.threadId),\n ),\n ),\n ),\n\n markUnknown: (request) =>\n submissionTarget(\"ledger mark unknown\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.markUnknown(request)\n : Effect.fail(crossThreadLedgerError(\"ledger mark unknown\", target.threadId)),\n ),\n ),\n\n recordUnknownResolution: (command) =>\n submissionTarget(\"ledger record unknown resolution\", command.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.recordUnknownResolution(command)\n : Effect.fail(\n crossThreadLedgerError(\"ledger record unknown resolution\", target.threadId),\n ),\n ),\n ),\n\n reserveChildBudget: (request) =>\n submissionTarget(\"ledger reserve child budget\", request.parentSubmissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.reserveChildBudget(request)\n : Effect.fail(crossThreadLedgerError(\"ledger reserve child budget\", target.threadId)),\n ),\n ),\n\n // Reservation identities carry no Thread address; the reservation row lives in the\n // parent's own Object and these transitions are parent-lane-local by construction, so\n // they always execute on the local facet (which fails typed for an unknown row).\n attachChildToReservation: local.attachChildToReservation,\n beginChildBudgetRelease: local.beginChildBudgetRelease,\n releaseChildBudget: local.releaseChildBudget,\n\n // The local scan IS the whole worklist: one Thread per Object (durability §5).\n scanNonterminal: local.scanNonterminal,\n\n readAbortIntent: (request) =>\n submissionTarget(\"ledger read abort intent\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.readAbortIntent(request)\n : Effect.fail(crossThreadLedgerError(\"ledger read abort intent\", target.threadId)),\n ),\n ),\n\n loadRecoverySnapshot: (request) =>\n submissionTarget(\"ledger load recovery snapshot\", request.submissionId).pipe(\n Effect.flatMap((target) =>\n target._tag === \"local\"\n ? local.loadRecoverySnapshot(request).pipe(Effect.flatMap(enrichChildAttachments))\n : Effect.fail(crossThreadLedgerError(\"ledger load recovery snapshot\", target.threadId)),\n ),\n ),\n });\n\n return Context.make(SubmissionLedger, routed);\n});\n\nconst makeRoutedStoreServices = Effect.fn(\"DoPortRouting.makeRoutedStoreServices\")(function* (\n options: RoutedPortOptions,\n) {\n const local = yield* ThreadStore;\n const checkpoints = local.checkpoints;\n const transport = yield* ThreadPortTransport;\n const transportCall: TransportCall = makeTransportCall(transport);\n\n const routeFailure =\n (operation: string, target: string) =>\n (error: PortTransportError | PortProtocolError): ThreadStoreError =>\n ThreadStoreError.make({\n operation,\n message: boundPortDiagnostic(\n `Routed ${operation} to the Thread Object owning ${target} failed: ${error.message}`,\n ),\n cause: error,\n });\n\n /** The store twin of `foreignLedgerCall` with `ThreadStoreError` as the base error. */\n const foreignStoreCall = <ResultSchema extends Schema.Top, FailureSchema extends Schema.Top>(\n operation: string,\n target: ThreadId,\n call: PortRequest,\n resultSchema: ResultSchema,\n failureSchema: FailureSchema,\n ): Effect.Effect<ResultSchema[\"Type\"], FailureSchema[\"Type\"] | ThreadStoreError> => {\n const isExpectedResult = Schema.is(resultSchema);\n const isExpectedFailure = Schema.is(failureSchema);\n\n return transportCall(target, call).pipe(\n Effect.mapError(routeFailure(operation, target)),\n Effect.flatMap(\n (\n response,\n ): Effect.Effect<ResultSchema[\"Type\"], FailureSchema[\"Type\"] | ThreadStoreError> => {\n if (response._tag === \"PortFailed\") {\n const failure = response.failure;\n\n if (isExpectedFailure(failure)) return Effect.fail(failure);\n if (failure._tag === \"ThreadStoreError\") return Effect.fail(failure);\n\n return Effect.fail(\n ThreadStoreError.make({\n operation,\n message: boundPortDiagnostic(\n `The Thread Object owning ${target} answered ${operation} with the ` +\n `out-of-contract failure ${failure._tag}: ${failure.message}`,\n ),\n cause: failure,\n }),\n );\n }\n const result = response.result;\n\n if (!isExpectedResult(result)) {\n return Effect.fail(\n ThreadStoreError.make({\n operation,\n message:\n `The Thread Object owning ${target} answered ${operation} with the ` +\n `mismatched result ${result._tag}.`,\n }),\n );\n }\n\n return Effect.succeed(result);\n },\n ),\n Effect.withSpan(\"DoPortRouting.foreignStoreCall\", {\n attributes: { operation, target },\n }),\n );\n };\n\n const routed = ThreadStore.of({\n materialize: (request) =>\n request.threadId === options.localThreadId\n ? local.materialize(request)\n : foreignStoreCall(\n \"thread materialize\",\n request.threadId,\n StoreMaterializeCall.make({ request }),\n StoreMaterializeResult,\n FenceRejected,\n ).pipe(Effect.asVoid),\n\n append: (request) =>\n request.threadId === options.localThreadId\n ? local.append(request)\n : foreignStoreCall(\n \"thread append\",\n request.threadId,\n StoreAppendCall.make({ request }),\n StoreAppendResult,\n AppendPortFailure,\n ).pipe(Effect.map((reply) => reply.result)),\n\n read: (request) =>\n request.threadId === options.localThreadId\n ? local.read(request)\n : Stream.unwrap(\n foreignStoreCall(\n \"thread read\",\n request.threadId,\n StoreReadPageCall.make({ request }),\n StoreReadPageResult,\n ThreadNotMaterialized,\n ).pipe(Effect.map((reply) => Stream.fromIterable(reply.records))),\n ),\n\n inspectTail: (request) =>\n request.threadId === options.localThreadId\n ? local.inspectTail(request)\n : foreignStoreCall(\n \"thread inspect tail\",\n request.threadId,\n StoreInspectTailCall.make({ request }),\n StoreInspectTailResult,\n ThreadNotMaterialized,\n ).pipe(Effect.map((reply) => reply.tail)),\n\n export: (request) =>\n request.threadId === options.localThreadId\n ? local.export(request)\n : foreignStoreCall(\n \"thread export\",\n request.threadId,\n StoreExportCall.make({ request }),\n StoreExportResult,\n ThreadNotMaterialized,\n ).pipe(Effect.map((reply) => reply.export)),\n\n // Observation and checkpoints are lane-local by construction (plan §1.3): the closed\n // route-capable store subset is materialize/append/read/inspectTail/export, and a\n // foreign address on anything else fails fast typed.\n observe: (request) =>\n request.threadId === options.localThreadId\n ? local.observe(request)\n : Stream.unwrap(Effect.fail(crossThreadStoreError(\"thread observe\", request.threadId))),\n\n ...(checkpoints === undefined\n ? {}\n : {\n checkpoints: {\n save: (request) =>\n request.checkpoint.threadId === options.localThreadId\n ? checkpoints.save(request)\n : Effect.fail(\n crossThreadStoreError(\"thread save checkpoint\", request.checkpoint.threadId),\n ),\n load: (request) =>\n request.threadId === options.localThreadId\n ? checkpoints.load(request)\n : Effect.fail(crossThreadStoreError(\"thread load checkpoint\", request.threadId)),\n },\n }),\n });\n\n return Context.make(ThreadStore, routed);\n});\n\n/**\n * Routing decorator over the LOCAL `SubmissionLedger` facet (plan §1.3): a request addressing\n * this Object's Thread executes locally; a route-capable request addressing another\n * Thread is Schema-encoded onto the `ThreadPortTransport` and executed by the\n * owning Object's local facet; any other foreign request fails fast typed. Provide the WP1\n * local facet (`submissionLedgerLayer`/`ledgerLayer`) and a transport to close it.\n */\nexport const routedSubmissionLedgerLayer = (\n options: RoutedPortOptions,\n): Layer.Layer<SubmissionLedger, never, SubmissionLedger | ThreadPortTransport> =>\n Layer.effectContext(makeRoutedLedgerServices(options));\n\n/**\n * Routing decorator over the LOCAL `ThreadStore` facet (plan §1.3): this-thread\n * requests execute locally; foreign materialize/append/read/inspectTail/export travel the\n * transport; foreign observation and checkpoints fail fast typed.\n */\nexport const routedThreadStoreLayer = (\n options: RoutedPortOptions,\n): Layer.Layer<ThreadStore, never, ThreadStore | ThreadPortTransport> =>\n Layer.effectContext(makeRoutedStoreServices(options));\n\n// ---------------------------------------------------------------------------\n// Owner-side execution\n// ---------------------------------------------------------------------------\n\n/** Fold one port operation's typed failures into the uniform response envelope. */\nconst capture = <Failure extends PortFailure>(\n effect: Effect.Effect<PortResult, Failure>,\n): Effect.Effect<PortResponse> =>\n effect.pipe(\n Effect.map((result): PortResponse => PortSucceeded.make({ result })),\n Effect.catch((failure) => Effect.succeed<PortResponse>(PortFailed.make({ failure }))),\n );\n\n/**\n * Execute one decoded port request against THIS Object's LOCAL facets — the owner-side half\n * of the routed ports (plan §1.3). Callers must provide the WP1 local facets, never the\n * routed decorators: the routing layer already established that this Object owns the\n * addressed Thread, and re-routing here could bounce a request between Objects.\n * Failures never escape — every typed port failure becomes a `PortFailed` envelope that\n * re-decodes on the caller side.\n */\nexport const executePortRequest = Effect.fn(\"DoPortRouting.executePortRequest\")(function* (\n request: PortRequest,\n): Effect.fn.Return<PortResponse, never, SubmissionLedger | ThreadStore> {\n switch (request._tag) {\n case \"LedgerAdmit\": {\n const ledger = yield* SubmissionLedger;\n\n return yield* capture(\n ledger\n .admit(request.request)\n .pipe(Effect.map((result) => LedgerAdmitResult.make({ result }))),\n );\n }\n case \"LedgerMarkReady\": {\n const ledger = yield* SubmissionLedger;\n\n return yield* capture(\n ledger.markReady(request.request).pipe(Effect.map(() => LedgerMarkReadyResult.make({}))),\n );\n }\n case \"LedgerLookup\": {\n const ledger = yield* SubmissionLedger;\n\n return yield* capture(\n ledger\n .lookup(request.request)\n .pipe(\n Effect.map((submission) =>\n Option.isSome(submission)\n ? LedgerLookupResult.make({ submission: submission.value })\n : LedgerLookupResult.make({}),\n ),\n ),\n );\n }\n case \"LedgerResolveAdmission\": {\n const ledger = yield* SubmissionLedger;\n\n return yield* capture(\n ledger\n .resolveAdmission(request.request)\n .pipe(Effect.map((resolution) => LedgerResolveAdmissionResult.make({ resolution }))),\n );\n }\n case \"LedgerRequestAbort\": {\n const ledger = yield* SubmissionLedger;\n\n return yield* capture(\n ledger\n .requestAbort(request.request)\n .pipe(Effect.map((intent) => LedgerRequestAbortResult.make({ intent }))),\n );\n }\n case \"LedgerRecordChildSettled\": {\n const ledger = yield* SubmissionLedger;\n\n return yield* capture(\n ledger\n .recordChildSettled(request.request)\n .pipe(Effect.map((outcome) => LedgerRecordChildSettledResult.make({ outcome }))),\n );\n }\n case \"StoreMaterialize\": {\n const store = yield* ThreadStore;\n\n return yield* capture(\n store.materialize(request.request).pipe(Effect.map(() => StoreMaterializeResult.make({}))),\n );\n }\n case \"StoreAppend\": {\n const store = yield* ThreadStore;\n\n return yield* capture(\n store\n .append(request.request)\n .pipe(Effect.map((result) => StoreAppendResult.make({ result }))),\n );\n }\n case \"StoreReadPage\": {\n const store = yield* ThreadStore;\n\n return yield* capture(\n store.read(request.request).pipe(\n Stream.runCollect,\n Effect.map((records) => StoreReadPageResult.make({ records: [...records] })),\n ),\n );\n }\n case \"StoreInspectTail\": {\n const store = yield* ThreadStore;\n\n return yield* capture(\n store\n .inspectTail(request.request)\n .pipe(Effect.map((tail) => StoreInspectTailResult.make({ tail }))),\n );\n }\n case \"StoreExport\": {\n const store = yield* ThreadStore;\n\n return yield* capture(\n store\n .export(request.request)\n .pipe(Effect.map((threadExport) => StoreExportResult.make({ export: threadExport }))),\n );\n }\n }\n});\n\n/**\n * The last-resort wire fallback when even encoding a response fails: the literal encoded\n * form of `PortFailed(PortProtocolError)` — tagged classes of bounded strings encode to\n * exactly this shape, so no Schema round trip is needed to produce it.\n */\nconst encodedProtocolFailure = (message: string): unknown => ({\n _tag: \"PortFailed\",\n failure: { _tag: \"PortProtocolError\", message: boundPortDiagnostic(message) },\n});\n\n/**\n * The complete owner-side endpoint body for `portCall` (D-P6-3): decode the wire request,\n * execute it against this Object's LOCAL facets, and answer with the encoded response\n * envelope. Total by construction — a request that cannot be decoded, or a response that\n * cannot be encoded, answers `PortFailed(PortProtocolError)` instead of throwing, so the\n * transport never has to interpret exceptions as protocol answers.\n */\nexport const handleEncodedPortRequest = Effect.fn(\"DoPortRouting.handleEncodedPortRequest\")(\n function* (encoded: unknown): Effect.fn.Return<unknown, never, SubmissionLedger | ThreadStore> {\n const response = yield* decodePortRequest(encoded).pipe(\n Effect.flatMap(executePortRequest),\n Effect.catch((error) =>\n Effect.succeed<PortResponse>(\n PortFailed.make({\n failure: PortProtocolError.make({\n message: boundPortDiagnostic(\n `The port request could not be decoded: ${error.message}`,\n ),\n }),\n }),\n ),\n ),\n );\n\n return yield* encodePortResponse(response).pipe(\n Effect.catch((error) =>\n Effect.succeed(\n encodedProtocolFailure(`The port response could not be encoded: ${error.message}`),\n ),\n ),\n );\n },\n);\n"],"mappings":";;;;;;;;;;;;;;;AAiEA,MAAM,iBAAiB,sBAAsB,OAAO;AACpD,MAAM,iBAAiB,OAAO,oBAAoB,cAAc;;;;;;AAOhE,MAAM,oCAAoC;;AAG1C,MAAM,oBACJ;;;;;;;;AASF,IAAa,qBAAb,cAAwC,OAAO,YAAgC,CAAC,CAC9E,sBACA;CACE,QAAQ,OAAO;CACf,SAAS,OAAO;CAChB,WAAW,OAAO,YAAY,OAAO,OAAO;CAC5C,OAAO,OAAO,YAAY,OAAO,OAAO,CAAC;AAC3C,CACF,CAAC,CAAC,CAAC;AAEH,MAAM,2BAA2B,UAA2B;CAC1D,IAAI;EACF,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU;EAEzD,OAAO,oBAAoB,OAAO,YAAY,WAAW,UAAU,OAAO,OAAO,CAAC;CACpF,QAAQ;EACN,OAAO;CACT;AACF;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,YAAY,oBAAoB,KAAK,EAAE,SAAS,CAAC,GAAG,OAAO,EAAE,CAAC,CAAC,CAC7E,CACF;EACF;EACA,KAAK,oBAAoB;GACvB,MAAM,QAAQ,OAAO;GAErB,OAAO,OAAO,QACZ,MACG,YAAY,QAAQ,OAAO,CAAC,CAC5B,KAAK,OAAO,KAAK,SAAS,uBAAuB,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,CACrE;EACF;EACA,KAAK,eAAe;GAClB,MAAM,QAAQ,OAAO;GAErB,OAAO,OAAO,QACZ,MACG,OAAO,QAAQ,OAAO,CAAC,CACvB,KAAK,OAAO,KAAK,iBAAiB,kBAAkB,KAAK,EAAE,QAAQ,aAAa,CAAC,CAAC,CAAC,CACxF;EACF;CACF;AACF,CAAC;;;;;;AAOD,MAAM,0BAA0B,aAA8B;CAC5D,MAAM;CACN,SAAS;EAAE,MAAM;EAAqB,SAAS,oBAAoB,OAAO;CAAE;AAC9E;;;;;;;;AASA,MAAa,2BAA2B,OAAO,GAAG,wCAAwC,CAAC,CACzF,WAAW,SAAoF;CAC7F,MAAM,WAAW,OAAO,kBAAkB,OAAO,CAAC,CAAC,KACjD,OAAO,QAAQ,kBAAkB,GACjC,OAAO,OAAO,UACZ,OAAO,QACL,WAAW,KAAK,EACd,SAAS,kBAAkB,KAAK,EAC9B,SAAS,oBACP,0CAA0C,MAAM,SAClD,EACF,CAAC,EACH,CAAC,CACH,CACF,CACF;CAEA,OAAO,OAAO,mBAAmB,QAAQ,CAAC,CAAC,KACzC,OAAO,OAAO,UACZ,OAAO,QACL,uBAAuB,2CAA2C,MAAM,SAAS,CACnF,CACF,CACF;AACF,CACF"}
|
package/dist/index.d.mts
CHANGED
|
@@ -3,7 +3,7 @@ import { t as DoScheduleStore_d_exports } from "./DoScheduleStore.mjs";
|
|
|
3
3
|
import { t as DoStorageConfig_d_exports } from "./DoStorageConfig.mjs";
|
|
4
4
|
import { c as DoStorageError_d_exports } from "./DoStorageError-Qwybzk0O.mjs";
|
|
5
5
|
import { t as DoStorageFailpoint_d_exports } from "./DoStorageFailpoint.mjs";
|
|
6
|
-
import { t as DoStorageVersion_d_exports } from "./DoStorageVersion-
|
|
6
|
+
import { t as DoStorageVersion_d_exports } from "./DoStorageVersion-DxqcVgDE.mjs";
|
|
7
7
|
import { t as DoThreadStore_d_exports } from "./DoThreadStore.mjs";
|
|
8
8
|
import { t as DoSubmissionLedger_d_exports } from "./DoSubmissionLedger.mjs";
|
|
9
9
|
import { t as DoSubscriptionStore_d_exports } from "./DoSubscriptionStore.mjs";
|
package/dist/index.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import { t as DoStorageConfig_exports } from "./DoStorageConfig.mjs";
|
|
|
4
4
|
import { t as DoStorageError_exports } from "./DoStorageError.mjs";
|
|
5
5
|
import { t as DoStorageFailpoint_exports } from "./DoStorageFailpoint.mjs";
|
|
6
6
|
import { t as DoStorageVersion_exports } from "./DoStorageVersion.mjs";
|
|
7
|
-
import { t as DoThreadStore_exports } from "./DoThreadStore-
|
|
7
|
+
import { t as DoThreadStore_exports } from "./DoThreadStore-JqjeFOga.mjs";
|
|
8
8
|
import { t as DoSubmissionLedger_exports } from "./DoSubmissionLedger.mjs";
|
|
9
9
|
import { t as DoSubscriptionStore_exports } from "./DoSubscriptionStore.mjs";
|
|
10
10
|
import { t as MemoryProtocol_exports } from "./MemoryProtocol.mjs";
|
|
@@ -3,7 +3,7 @@ import { Effect } from "effect";
|
|
|
3
3
|
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
|
4
4
|
//#region src/internal/migrations.ts
|
|
5
5
|
/** The current storage version recorded in `effect_agent_meta`. */
|
|
6
|
-
const CurrentDoStorageVersion =
|
|
6
|
+
const CurrentDoStorageVersion = 3;
|
|
7
7
|
/**
|
|
8
8
|
* The Thread Durable Object schema shares its thread and ledger tables with Node/SQLite.
|
|
9
9
|
* Schedules and subscriptions use separate Durable Objects. Two DC-specific additions:
|
|
@@ -98,6 +98,8 @@ const doMigrations = SqliteMigrator.fromRecord({ "1_current_cloudflare_thread_ob
|
|
|
98
98
|
unknown_tool_call_ids_json TEXT,
|
|
99
99
|
parent_submission_id TEXT,
|
|
100
100
|
parent_tool_call_id TEXT,
|
|
101
|
+
admission_group TEXT,
|
|
102
|
+
admission_fence_json TEXT,
|
|
101
103
|
UNIQUE (thread_id, principal, idempotency_key),
|
|
102
104
|
UNIQUE (thread_id, queue_sequence)
|
|
103
105
|
)
|
|
@@ -109,6 +111,10 @@ const doMigrations = SqliteMigrator.fromRecord({ "1_current_cloudflare_thread_ob
|
|
|
109
111
|
yield* sql`
|
|
110
112
|
CREATE INDEX effect_agent_submissions_parent
|
|
111
113
|
ON effect_agent_submissions (parent_submission_id)
|
|
114
|
+
`.withoutTransform;
|
|
115
|
+
yield* sql`
|
|
116
|
+
CREATE INDEX effect_agent_submissions_group
|
|
117
|
+
ON effect_agent_submissions (thread_id, admission_group, state)
|
|
112
118
|
`.withoutTransform;
|
|
113
119
|
yield* sql`
|
|
114
120
|
CREATE TABLE effect_agent_submission_ownership (
|
|
@@ -227,10 +233,10 @@ const doMigrations = SqliteMigrator.fromRecord({ "1_current_cloudflare_thread_ob
|
|
|
227
233
|
`.withoutTransform;
|
|
228
234
|
yield* sql`
|
|
229
235
|
INSERT INTO effect_agent_meta (key, value)
|
|
230
|
-
VALUES ('storage_version', ${String(
|
|
236
|
+
VALUES ('storage_version', ${String(3)})
|
|
231
237
|
`.withoutTransform;
|
|
232
238
|
}) });
|
|
233
239
|
//#endregion
|
|
234
240
|
export { doMigrations as n, CurrentDoStorageVersion as t };
|
|
235
241
|
|
|
236
|
-
//# sourceMappingURL=migrations-
|
|
242
|
+
//# sourceMappingURL=migrations-B-jiT7vx.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"migrations-B-jiT7vx.mjs","names":[],"sources":["../src/internal/migrations.ts"],"sourcesContent":["import { SqliteMigrator } from \"@effect/sql-sqlite-do\";\nimport { Effect } from \"effect\";\nimport * as SqlClient from \"effect/unstable/sql/SqlClient\";\n\n/** The current storage version recorded in `effect_agent_meta`. */\nexport const CurrentDoStorageVersion = 3;\n\n/**\n * The Thread Durable Object schema shares its thread and ledger tables with Node/SQLite.\n * Schedules and subscriptions use separate Durable Objects. Two DC-specific additions:\n *\n * 1. `effect_agent_meta` replaces `PRAGMA user_version` as the exact-or-fresh version gate —\n * a meta table is portable regardless of which PRAGMAs Durable Object SQL storage allows.\n * 2. `effect_agent_child_settlements` is the durable cross-store notification marker the\n * SubmissionLedger port contract mandates for cross-store adapters (`suspend`'s covering\n * check and `recordChildSettled`'s wake both consult it): parent and child Threads\n * live in different Durable Objects, so a child settlement reported before the parent's\n * suspend commits must be observable from the PARENT's own storage.\n */\nexport const doMigrations = SqliteMigrator.fromRecord({\n \"1_current_cloudflare_thread_object\": Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n\n yield* sql`\n CREATE TABLE effect_agent_threads (\n thread_id TEXT PRIMARY KEY NOT NULL,\n created_at TEXT NOT NULL,\n tail_sequence INTEGER NOT NULL,\n tail_digest TEXT NOT NULL,\n producer_epoch INTEGER NOT NULL\n )\n `.withoutTransform;\n\n yield* sql`\n CREATE TABLE effect_agent_canonical_batches (\n thread_id TEXT NOT NULL,\n batch_id TEXT NOT NULL,\n first_sequence INTEGER NOT NULL,\n last_sequence INTEGER NOT NULL,\n batch_digest TEXT NOT NULL,\n tail_digest TEXT NOT NULL,\n batch_json TEXT NOT NULL,\n PRIMARY KEY (thread_id, batch_id),\n FOREIGN KEY (thread_id)\n REFERENCES effect_agent_threads(thread_id)\n ON DELETE RESTRICT\n )\n `.withoutTransform;\n\n yield* sql`\n CREATE TABLE effect_agent_canonical_records (\n thread_id TEXT NOT NULL,\n sequence INTEGER NOT NULL,\n record_id TEXT NOT NULL,\n batch_id TEXT NOT NULL,\n record_json TEXT NOT NULL,\n PRIMARY KEY (thread_id, sequence),\n UNIQUE (thread_id, record_id),\n FOREIGN KEY (thread_id, batch_id)\n REFERENCES effect_agent_canonical_batches(thread_id, batch_id)\n ON DELETE RESTRICT\n )\n `.withoutTransform;\n\n yield* sql`\n CREATE INDEX effect_agent_canonical_records_batch\n ON effect_agent_canonical_records (thread_id, batch_id, sequence)\n `.withoutTransform;\n\n yield* sql`\n CREATE TABLE effect_agent_checkpoints (\n thread_id TEXT NOT NULL,\n through_sequence INTEGER NOT NULL,\n tail_digest TEXT NOT NULL,\n checkpoint_json TEXT NOT NULL,\n PRIMARY KEY (thread_id, through_sequence),\n FOREIGN KEY (thread_id)\n REFERENCES effect_agent_threads(thread_id)\n ON DELETE RESTRICT\n )\n `.withoutTransform;\n\n // Admission rows exist before Thread materialization (durability §4), so\n // thread_id intentionally carries no foreign key into effect_agent_threads.\n yield* sql`\n CREATE TABLE effect_agent_submissions (\n submission_id TEXT PRIMARY KEY NOT NULL,\n thread_id TEXT NOT NULL,\n queue_sequence INTEGER NOT NULL,\n principal TEXT NOT NULL,\n idempotency_key TEXT NOT NULL,\n agent_id TEXT NOT NULL,\n agent_digests_json TEXT NOT NULL,\n deployment_id TEXT NOT NULL,\n input_json TEXT NOT NULL,\n input_digest TEXT NOT NULL,\n receipt_id TEXT NOT NULL,\n state TEXT NOT NULL,\n settled_outcome TEXT,\n created_at TEXT NOT NULL,\n ready_at TEXT,\n input_applied_record_id TEXT,\n input_applied_sequence INTEGER,\n joined_host_submission_id TEXT,\n suspended_reason_json TEXT,\n suspended_at TEXT,\n unknown_reason TEXT,\n unknown_tool_call_ids_json TEXT,\n parent_submission_id TEXT,\n parent_tool_call_id TEXT,\n admission_group TEXT,\n admission_fence_json TEXT,\n UNIQUE (thread_id, principal, idempotency_key),\n UNIQUE (thread_id, queue_sequence)\n )\n `.withoutTransform;\n\n yield* sql`\n CREATE INDEX effect_agent_submissions_joined_host\n ON effect_agent_submissions (joined_host_submission_id)\n `.withoutTransform;\n\n yield* sql`\n CREATE INDEX effect_agent_submissions_parent\n ON effect_agent_submissions (parent_submission_id)\n `.withoutTransform;\n\n yield* sql`\n CREATE INDEX effect_agent_submissions_group\n ON effect_agent_submissions (thread_id, admission_group, state)\n `.withoutTransform;\n\n yield* sql`\n CREATE TABLE effect_agent_submission_ownership (\n submission_id TEXT PRIMARY KEY NOT NULL,\n attempt_id TEXT NOT NULL,\n ownership_token TEXT NOT NULL,\n producer_epoch INTEGER NOT NULL,\n owner_producer_id TEXT NOT NULL,\n lease_expires_at TEXT NOT NULL,\n FOREIGN KEY (submission_id)\n REFERENCES effect_agent_submissions(submission_id)\n ON DELETE RESTRICT\n )\n `.withoutTransform;\n\n yield* sql`\n CREATE TABLE effect_agent_attempts (\n attempt_id TEXT PRIMARY KEY NOT NULL,\n submission_id TEXT NOT NULL,\n thread_id TEXT NOT NULL,\n owner_producer_id TEXT NOT NULL,\n producer_epoch INTEGER NOT NULL,\n claimed_at TEXT NOT NULL,\n FOREIGN KEY (submission_id)\n REFERENCES effect_agent_submissions(submission_id)\n ON DELETE RESTRICT\n )\n `.withoutTransform;\n\n yield* sql`\n CREATE TABLE effect_agent_settlement_reservations (\n submission_id TEXT PRIMARY KEY NOT NULL,\n settlement_id TEXT NOT NULL,\n outcome TEXT NOT NULL,\n record_id TEXT NOT NULL,\n record_json TEXT NOT NULL,\n record_digest TEXT NOT NULL,\n reserved_at TEXT NOT NULL,\n finalized_at TEXT,\n FOREIGN KEY (submission_id)\n REFERENCES effect_agent_submissions(submission_id)\n ON DELETE RESTRICT\n )\n `.withoutTransform;\n\n yield* sql`\n CREATE TABLE effect_agent_abort_intents (\n submission_id TEXT PRIMARY KEY NOT NULL,\n author TEXT NOT NULL,\n reason TEXT NOT NULL,\n requested_at TEXT NOT NULL,\n canonical_record_id TEXT,\n FOREIGN KEY (submission_id)\n REFERENCES effect_agent_submissions(submission_id)\n ON DELETE RESTRICT\n )\n `.withoutTransform;\n\n yield* sql`\n CREATE TABLE effect_agent_approval_decisions (\n submission_id TEXT NOT NULL,\n tool_call_id TEXT NOT NULL,\n decision TEXT NOT NULL,\n resolver TEXT NOT NULL,\n reason TEXT NOT NULL,\n decided_at TEXT NOT NULL,\n PRIMARY KEY (submission_id, tool_call_id),\n FOREIGN KEY (submission_id)\n REFERENCES effect_agent_submissions(submission_id)\n ON DELETE RESTRICT\n )\n `.withoutTransform;\n\n yield* sql`\n CREATE TABLE effect_agent_unknown_resolutions (\n submission_id TEXT NOT NULL,\n tool_call_id TEXT NOT NULL,\n author TEXT NOT NULL,\n reason TEXT NOT NULL,\n resolution_json TEXT NOT NULL,\n resolved_at TEXT NOT NULL,\n PRIMARY KEY (submission_id, tool_call_id),\n FOREIGN KEY (submission_id)\n REFERENCES effect_agent_submissions(submission_id)\n ON DELETE RESTRICT\n )\n `.withoutTransform;\n\n yield* sql`\n CREATE TABLE effect_agent_child_reservations (\n reservation_id TEXT PRIMARY KEY NOT NULL,\n parent_submission_id TEXT NOT NULL,\n parent_tool_call_id TEXT NOT NULL,\n child_submission_id TEXT,\n status TEXT NOT NULL,\n allocation_json TEXT NOT NULL,\n allocation_digest TEXT NOT NULL,\n accounting_json TEXT,\n reserved_at TEXT NOT NULL,\n release_began_at TEXT,\n released_at TEXT,\n UNIQUE (parent_submission_id, parent_tool_call_id),\n FOREIGN KEY (parent_submission_id)\n REFERENCES effect_agent_submissions(submission_id)\n ON DELETE RESTRICT\n )\n `.withoutTransform;\n\n // Durable cross-store child-settlement notification marker (parent-side; the child's row\n // lives in ANOTHER Durable Object). child_outcome is nullable: the notification command\n // carries identities only, and the child's canonical Settlement stays the outcome\n // authority (DUR-015). No foreign keys: the parent row is checked by the operation, and\n // the child row is intentionally foreign.\n yield* sql`\n CREATE TABLE effect_agent_child_settlements (\n parent_submission_id TEXT NOT NULL,\n child_submission_id TEXT NOT NULL,\n child_outcome TEXT,\n recorded_at TEXT NOT NULL,\n PRIMARY KEY (parent_submission_id, child_submission_id)\n )\n `.withoutTransform;\n\n yield* sql`\n CREATE TABLE effect_agent_meta (\n key TEXT PRIMARY KEY NOT NULL,\n value TEXT NOT NULL\n )\n `.withoutTransform;\n\n yield* sql`\n INSERT INTO effect_agent_meta (key, value)\n VALUES ('storage_version', ${String(CurrentDoStorageVersion)})\n `.withoutTransform;\n }),\n});\n"],"mappings":";;;;;AAKA,MAAa,0BAA0B;;;;;;;;;;;;;AAcvC,MAAa,eAAe,eAAe,WAAW,EACpD,sCAAsC,OAAO,IAAI,aAAa;CAC5D,MAAM,MAAM,OAAO,UAAU;CAE7B,OAAO,GAAG;;;;;;;;MAQR;CAEF,OAAO,GAAG;;;;;;;;;;;;;;MAcR;CAEF,OAAO,GAAG;;;;;;;;;;;;;MAaR;CAEF,OAAO,GAAG;;;MAGR;CAEF,OAAO,GAAG;;;;;;;;;;;MAWR;CAIF,OAAO,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MA+BR;CAEF,OAAO,GAAG;;;MAGR;CAEF,OAAO,GAAG;;;MAGR;CAEF,OAAO,GAAG;;;MAGR;CAEF,OAAO,GAAG;;;;;;;;;;;;MAYR;CAEF,OAAO,GAAG;;;;;;;;;;;;MAYR;CAEF,OAAO,GAAG;;;;;;;;;;;;;;MAcR;CAEF,OAAO,GAAG;;;;;;;;;;;MAWR;CAEF,OAAO,GAAG;;;;;;;;;;;;;MAaR;CAEF,OAAO,GAAG;;;;;;;;;;;;;MAaR;CAEF,OAAO,GAAG;;;;;;;;;;;;;;;;;;MAkBR;CAOF,OAAO,GAAG;;;;;;;;MAQR;CAEF,OAAO,GAAG;;;;;MAKR;CAEF,OAAO,GAAG;;mCAEqB,OAAA,CAA8B,EAAE;MAC7D;AACJ,CAAC,EACH,CAAC"}
|
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"@effect-agent/storage-cloudflare","version":"0.1.0-beta.
|
|
1
|
+
{"name":"@effect-agent/storage-cloudflare","version":"0.1.0-beta.51","dependencies":{"@effect-agent/core":"0.1.0-beta.51","@effect-agent/thread":"0.1.0-beta.51","@effect/platform-browser":"4.0.0-rc.112","@effect/sql-sqlite-do":"4.0.0-rc.112"},"devDependencies":{"@cloudflare/vitest-pool-workers":"0.21.3","@cloudflare/workers-types":"5.20260825.1","@effect-agent/testing":"0.1.0-beta.51","@effect/vitest":"4.0.0-rc.112","effect":"4.0.0-rc.112","typescript":"7.0.2","vite-plus":"0.3.0","vitest":"4.1.11"},"peerDependencies":{"effect":"^4.0.0-rc.112"},"exports":{".":{"types":"./dist/index.d.mts","default":"./dist/index.mjs"},"./DoMemoryStore":{"types":"./dist/DoMemoryStore.d.mts","default":"./dist/DoMemoryStore.mjs"},"./DoScheduleStore":{"types":"./dist/DoScheduleStore.d.mts","default":"./dist/DoScheduleStore.mjs"},"./DoStorageConfig":{"types":"./dist/DoStorageConfig.d.mts","default":"./dist/DoStorageConfig.mjs"},"./DoStorageError":{"types":"./dist/DoStorageError.d.mts","default":"./dist/DoStorageError.mjs"},"./DoStorageFailpoint":{"types":"./dist/DoStorageFailpoint.d.mts","default":"./dist/DoStorageFailpoint.mjs"},"./DoStorageVersion":{"types":"./dist/DoStorageVersion.d.mts","default":"./dist/DoStorageVersion.mjs"},"./DoSubmissionLedger":{"types":"./dist/DoSubmissionLedger.d.mts","default":"./dist/DoSubmissionLedger.mjs"},"./DoSubscriptionStore":{"types":"./dist/DoSubscriptionStore.d.mts","default":"./dist/DoSubscriptionStore.mjs"},"./DoThreadStore":{"types":"./dist/DoThreadStore.d.mts","default":"./dist/DoThreadStore.mjs"},"./MemoryProtocol":{"types":"./dist/MemoryProtocol.d.mts","default":"./dist/MemoryProtocol.mjs"},"./PortProtocol":{"types":"./dist/PortProtocol.d.mts","default":"./dist/PortProtocol.mjs"},"./PortRouting":{"types":"./dist/PortRouting.d.mts","default":"./dist/PortRouting.mjs"},"./testing/DoStorageFailpointTesting":{"types":"./dist/DoStorageFailpointTesting.d.mts","default":"./dist/DoStorageFailpointTesting.mjs"}},"description":"Durable Object SQLite storage adapters and the routed port protocol for Effect Agent on Cloudflare.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/danieljvdm/effect-agent.git","directory":"packages/storage-cloudflare"},"files":["dist","src"],"type":"module","sideEffects":[],"publishConfig":{"access":"public"},"scripts":{"build":"vp pack","check":"tsc --noEmit -p tsconfig.json"}}
|
package/src/DoScheduleStore.ts
CHANGED
|
@@ -25,7 +25,7 @@ import {
|
|
|
25
25
|
import { Context, Effect, Layer, Result, Schema } from "effect";
|
|
26
26
|
import * as SqlClientService from "effect/unstable/sql/SqlClient";
|
|
27
27
|
|
|
28
|
-
const CURRENT_SCHEDULE_STORE_VERSION =
|
|
28
|
+
const CURRENT_SCHEDULE_STORE_VERSION = 3;
|
|
29
29
|
const MAX_STORED_SCHEDULE_BYTES = 1_900_000;
|
|
30
30
|
|
|
31
31
|
const StoredScheduleJson = Schema.String.check(Schema.isMaxLength(MAX_STORED_SCHEDULE_BYTES));
|