@effect-agent/storage-cloudflare 0.1.0-beta.47 → 0.1.0-beta.49
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/DoMemoryStore.d.mts +5 -0
- package/dist/DoMemoryStore.mjs +6 -1
- package/dist/DoMemoryStore.mjs.map +1 -1
- package/dist/DoSubmissionLedger.mjs +48 -3
- package/dist/DoSubmissionLedger.mjs.map +1 -1
- package/dist/{DoThreadStore-D9ebIYPv.mjs → DoThreadStore-D00TdRAa.mjs} +61 -46
- package/dist/DoThreadStore-D00TdRAa.mjs.map +1 -0
- package/dist/DoThreadStore.mjs +1 -1
- package/dist/MemoryProtocol.mjs +2 -2
- package/dist/MemoryProtocol.mjs.map +1 -1
- package/dist/PortRouting.mjs +1 -0
- package/dist/PortRouting.mjs.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/src/DoMemoryStore.ts +5 -0
- package/src/DoSubmissionLedger.ts +82 -0
- package/src/DoThreadStore.ts +15 -10
- package/src/MemoryProtocol.ts +2 -2
- package/src/PortRouting.ts +9 -0
- package/src/internal/do-journal.ts +82 -48
- package/dist/DoThreadStore-D9ebIYPv.mjs.map +0 -1
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 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,UAAU,iBAAiB,QAAQ,MAAM,UAAU;EAEzD,OAAO,oBAAoB,OAAO,YAAY,WAAW,UAAU,OAAO,OAAO,CAAC;CACpF,QAAQ;EACN,OAAO;CACT;AACF;AAEA,MAAM,4BAA4B,UAAwC;CACxE,IAAI,CAAC,UAAU,gBAAgB,KAAK,GAAG,OAAO,KAAA;CAC9C,IAAI;EACF,MAAM,SAAS,QAAQ,IAAI,OAAO,WAAW;EAE7C,OAAO,OAAO,WAAW,YAAY,SAAS,KAAA;CAChD,QAAQ;EACN;CACF;AACF;;;;;AAMA,MAAa,wBAAwB,QAAgB,UAAuC;CAC1F,MAAM,YAAY,yBAAyB,KAAK;CAEhD,OAAO,mBAAmB,KAAK;EAC7B;EACA,SAAS,wBAAwB,KAAK;EACtC,GAAI,cAAc,KAAA,IAAY,CAAC,IAAI,EAAE,UAAU;EAC/C;CACF,CAAC;AACH;;;;;;;;;AAUA,IAAa,sBAAb,cAAyC,QAAQ,QAQ/C,CAAC,CAAC,sDAAsD,CAAC,CAAC,CAAC;AAi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C,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 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,OA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,QAAQ,CAAC,CAAC,KACzC,OAAO,OAAO,UACZ,OAAO,QACL,uBAAuB,2CAA2C,MAAM,SAAS,CACnF,CACF,CACF;AACF,CACF"}
|
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-D00TdRAa.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";
|
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.49","dependencies":{"@effect-agent/core":"0.1.0-beta.49","@effect-agent/thread":"0.1.0-beta.49","@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.49","@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/DoMemoryStore.ts
CHANGED
|
@@ -13,6 +13,8 @@ export class DoMemoryStorageLimits extends Schema.Class<DoMemoryStorageLimits>(
|
|
|
13
13
|
maxStorageBytes: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 536_870_912 })),
|
|
14
14
|
maxDocuments: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100_000 })),
|
|
15
15
|
maxReceipts: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 1_000_000 })),
|
|
16
|
+
reservedWithdrawalBytes: Schema.optional(Schema.Natural),
|
|
17
|
+
reservedWithdrawalReceipts: Schema.optional(Schema.Natural),
|
|
16
18
|
}) {}
|
|
17
19
|
|
|
18
20
|
export const defaultDoMemoryStorageLimits = DoMemoryStorageLimits.make({
|
|
@@ -26,6 +28,9 @@ export const defaultDoMemoryStorageLimits = DoMemoryStorageLimits.make({
|
|
|
26
28
|
* Local memory only, without Thread tables. Keep one SQL client per owner and pass the
|
|
27
29
|
* full storage handle: sql-only handles cannot provide atomic receipts and revisions.
|
|
28
30
|
* Byte limits conservatively count encoded rows, not SQLite page/index overhead.
|
|
31
|
+
* Optional withdrawal reserves default to zero and stay within hard byte/receipt limits.
|
|
32
|
+
* Ordinary Put cannot consume them. Deploy exclusively upgraded writers before relying
|
|
33
|
+
* on reserves; the SQL accounting migration preserves older writers and their receipts.
|
|
29
34
|
*/
|
|
30
35
|
export const doMemoryStoreLayerWithFailpoints = (
|
|
31
36
|
storage: NonNullable<SqliteClient.SqliteClientConfig["storage"]>,
|
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
import {
|
|
13
13
|
AbortCommand,
|
|
14
14
|
AbortIntent,
|
|
15
|
+
AbortIntentRequest,
|
|
15
16
|
AdmissionAdmitted,
|
|
16
17
|
AdmissionConflict,
|
|
17
18
|
AdmissionNotAdmitted,
|
|
@@ -217,6 +218,15 @@ class MaxQueueSequenceRow extends Schema.Class<MaxQueueSequenceRow>("MaxQueueSeq
|
|
|
217
218
|
max_queue_sequence: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
|
|
218
219
|
}) {}
|
|
219
220
|
|
|
221
|
+
class AbortIntentLookupRow extends Schema.Class<AbortIntentLookupRow>("AbortIntentLookupRow")({
|
|
222
|
+
submission_id: BoundedIdentifier,
|
|
223
|
+
abort_submission_id: Schema.NullOr(BoundedIdentifier),
|
|
224
|
+
author: Schema.NullOr(BoundedIdentifier),
|
|
225
|
+
reason: Schema.NullOr(BoundedStoredText),
|
|
226
|
+
requested_at: Schema.NullOr(BoundedTimestamp),
|
|
227
|
+
canonical_record_id: Schema.NullOr(BoundedIdentifier),
|
|
228
|
+
}) {}
|
|
229
|
+
|
|
220
230
|
class CanonicalRecordIdRow extends Schema.Class<CanonicalRecordIdRow>("CanonicalRecordIdRow")({
|
|
221
231
|
record_id: BoundedIdentifier,
|
|
222
232
|
}) {}
|
|
@@ -3012,6 +3022,77 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
3012
3022
|
LedgerError
|
|
3013
3023
|
>(undefined, scanPage);
|
|
3014
3024
|
|
|
3025
|
+
const readAbortIntentForSubmission: SubmissionLedger["Service"]["readAbortIntent"] = Effect.fn(
|
|
3026
|
+
"DoSubmissionLedger.readAbortIntentForSubmission",
|
|
3027
|
+
)(function* (request) {
|
|
3028
|
+
const operation = "ledger read abort intent";
|
|
3029
|
+
|
|
3030
|
+
const validated = yield* Schema.decodeUnknownEffect(Schema.toType(AbortIntentRequest))(
|
|
3031
|
+
request,
|
|
3032
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
3033
|
+
|
|
3034
|
+
const recordId = submissionAbortRecordId(validated.submissionId);
|
|
3035
|
+
|
|
3036
|
+
const rows = yield* sql<Record<string, unknown>>`
|
|
3037
|
+
SELECT
|
|
3038
|
+
submission.submission_id,
|
|
3039
|
+
abort.submission_id AS abort_submission_id,
|
|
3040
|
+
abort.author,
|
|
3041
|
+
abort.reason,
|
|
3042
|
+
abort.requested_at,
|
|
3043
|
+
canonical.record_id AS canonical_record_id
|
|
3044
|
+
FROM effect_agent_submissions AS submission
|
|
3045
|
+
LEFT JOIN effect_agent_abort_intents AS abort
|
|
3046
|
+
ON abort.submission_id = submission.submission_id
|
|
3047
|
+
LEFT JOIN effect_agent_canonical_records AS canonical
|
|
3048
|
+
ON canonical.thread_id = submission.thread_id
|
|
3049
|
+
AND canonical.record_id = ${recordId}
|
|
3050
|
+
WHERE submission.submission_id = ${validated.submissionId}
|
|
3051
|
+
`.pipe(Effect.mapError(sqlFailure(operation)));
|
|
3052
|
+
|
|
3053
|
+
const decoded = yield* decodeRows(
|
|
3054
|
+
Schema.Array(AbortIntentLookupRow),
|
|
3055
|
+
"effect_agent_abort_intents",
|
|
3056
|
+
validated.submissionId,
|
|
3057
|
+
rows,
|
|
3058
|
+
).pipe(Effect.mapError(internalFailure(operation)));
|
|
3059
|
+
|
|
3060
|
+
if (decoded.length === 0) {
|
|
3061
|
+
return yield* LedgerError.make({
|
|
3062
|
+
operation,
|
|
3063
|
+
message: `Unknown submission ${validated.submissionId}.`,
|
|
3064
|
+
});
|
|
3065
|
+
}
|
|
3066
|
+
if (decoded.length !== 1) {
|
|
3067
|
+
return yield* corruptionFailure(
|
|
3068
|
+
operation,
|
|
3069
|
+
"effect_agent_abort_intents",
|
|
3070
|
+
validated.submissionId,
|
|
3071
|
+
"An abort intent lookup returned more than one row.",
|
|
3072
|
+
);
|
|
3073
|
+
}
|
|
3074
|
+
const row = decoded[0];
|
|
3075
|
+
|
|
3076
|
+
if (row.abort_submission_id === null) return undefined;
|
|
3077
|
+
|
|
3078
|
+
return yield* decodeAbortIntent({
|
|
3079
|
+
submissionId: row.abort_submission_id,
|
|
3080
|
+
author: row.author,
|
|
3081
|
+
reason: row.reason,
|
|
3082
|
+
requestedAt: row.requested_at,
|
|
3083
|
+
...(row.canonical_record_id === null ? {} : { canonicalRecordId: row.canonical_record_id }),
|
|
3084
|
+
}).pipe(
|
|
3085
|
+
Effect.mapError((error) =>
|
|
3086
|
+
corruptionFailure(
|
|
3087
|
+
operation,
|
|
3088
|
+
"effect_agent_abort_intents",
|
|
3089
|
+
validated.submissionId,
|
|
3090
|
+
error.message,
|
|
3091
|
+
),
|
|
3092
|
+
),
|
|
3093
|
+
);
|
|
3094
|
+
});
|
|
3095
|
+
|
|
3015
3096
|
const loadRecoverySnapshot: SubmissionLedger["Service"]["loadRecoverySnapshot"] = Effect.fn(
|
|
3016
3097
|
"DoSubmissionLedger.loadRecoverySnapshot",
|
|
3017
3098
|
)(function* (request: RecoverySnapshotRequest) {
|
|
@@ -3281,6 +3362,7 @@ const makeServices = Effect.fn("DoSubmissionLedger.makeServices")(function* () {
|
|
|
3281
3362
|
releaseChildBudget,
|
|
3282
3363
|
scanNonterminal,
|
|
3283
3364
|
loadRecoverySnapshot,
|
|
3365
|
+
readAbortIntent: readAbortIntentForSubmission,
|
|
3284
3366
|
}),
|
|
3285
3367
|
);
|
|
3286
3368
|
});
|
package/src/DoThreadStore.ts
CHANGED
|
@@ -616,11 +616,17 @@ const makeServices = Effect.fn("DoThreadStore.makeServices")(function* () {
|
|
|
616
616
|
});
|
|
617
617
|
|
|
618
618
|
const loadRecords = Effect.fn("DoThreadStore.loadRecords")(function* (request: RawReadRequest) {
|
|
619
|
-
const
|
|
619
|
+
const result = yield* journal
|
|
620
620
|
.read(request)
|
|
621
621
|
.pipe(Effect.mapError((error) => storeError("read canonical records", error)));
|
|
622
622
|
|
|
623
|
-
return
|
|
623
|
+
return {
|
|
624
|
+
count: result.count,
|
|
625
|
+
records: result.records.pipe(
|
|
626
|
+
Stream.mapError((error) => storeError("read canonical records", error)),
|
|
627
|
+
Stream.mapEffect(decodeEnvelope),
|
|
628
|
+
),
|
|
629
|
+
};
|
|
624
630
|
});
|
|
625
631
|
|
|
626
632
|
const readEffect = Effect.fn("DoThreadStore.read")(function* (request: ThreadRead) {
|
|
@@ -630,7 +636,7 @@ const makeServices = Effect.fn("DoThreadStore.makeServices")(function* () {
|
|
|
630
636
|
|
|
631
637
|
yield* requireThread(journal, validated.threadId);
|
|
632
638
|
|
|
633
|
-
const
|
|
639
|
+
const result = yield* loadRecords(
|
|
634
640
|
RawReadRequest.make({
|
|
635
641
|
threadId: validated.threadId,
|
|
636
642
|
fromSequenceExclusive: validated.afterSequence ?? ZERO_CANONICAL_SEQUENCE,
|
|
@@ -638,7 +644,7 @@ const makeServices = Effect.fn("DoThreadStore.makeServices")(function* () {
|
|
|
638
644
|
}),
|
|
639
645
|
);
|
|
640
646
|
|
|
641
|
-
return
|
|
647
|
+
return result.records;
|
|
642
648
|
});
|
|
643
649
|
|
|
644
650
|
const read: ThreadStore["Service"]["read"] = (request) => Stream.unwrap(readEffect(request));
|
|
@@ -655,7 +661,7 @@ const makeServices = Effect.fn("DoThreadStore.makeServices")(function* () {
|
|
|
655
661
|
const poll = Effect.fn("DoThreadStore.observePoll")(function* () {
|
|
656
662
|
const fromSequenceExclusive = yield* Ref.get(cursor);
|
|
657
663
|
|
|
658
|
-
const
|
|
664
|
+
const result = yield* loadRecords(
|
|
659
665
|
RawReadRequest.make({
|
|
660
666
|
threadId: validated.threadId,
|
|
661
667
|
fromSequenceExclusive,
|
|
@@ -663,17 +669,16 @@ const makeServices = Effect.fn("DoThreadStore.makeServices")(function* () {
|
|
|
663
669
|
}),
|
|
664
670
|
);
|
|
665
671
|
|
|
666
|
-
if (
|
|
672
|
+
if (result.count === 0) {
|
|
667
673
|
yield* Effect.sleep(config.observationPollInterval);
|
|
668
674
|
|
|
669
|
-
return
|
|
675
|
+
return Stream.empty;
|
|
670
676
|
}
|
|
671
|
-
yield* Ref.set(cursor, records[records.length - 1].sequence);
|
|
672
677
|
|
|
673
|
-
return records;
|
|
678
|
+
return result.records.pipe(Stream.tap((record) => Ref.set(cursor, record.sequence)));
|
|
674
679
|
});
|
|
675
680
|
|
|
676
|
-
return Stream.
|
|
681
|
+
return Stream.fromEffectRepeat(poll()).pipe(Stream.flatten);
|
|
677
682
|
});
|
|
678
683
|
|
|
679
684
|
const observe: ThreadStore["Service"]["observe"] = (request) =>
|
package/src/MemoryProtocol.ts
CHANGED
|
@@ -28,7 +28,7 @@ import {
|
|
|
28
28
|
revalidateSemanticMemoryCandidates,
|
|
29
29
|
} from "@effect-agent/core/SemanticMemoryRevalidation";
|
|
30
30
|
import { Principal } from "@effect-agent/thread/SubmissionLedger";
|
|
31
|
-
import { Clock, Context, Effect,
|
|
31
|
+
import { Clock, Context, Effect, Schema } from "effect";
|
|
32
32
|
|
|
33
33
|
export class MemoryRpcError extends Schema.TaggedError<MemoryRpcError>()("MemoryRpcError", {
|
|
34
34
|
reason: Schema.Literals(["denied", "protocol", "budget", "timeout", "unavailable"]),
|
|
@@ -127,7 +127,7 @@ export class MemoryOwnerIdentity extends Context.Service<
|
|
|
127
127
|
}
|
|
128
128
|
>()("@effect-agent/storage-cloudflare/MemoryOwnerIdentity") {}
|
|
129
129
|
|
|
130
|
-
export const memoryWireBytes = (text: string): number =>
|
|
130
|
+
export const memoryWireBytes = (text: string): number => new TextEncoder().encode(text).byteLength;
|
|
131
131
|
|
|
132
132
|
export const decodeMemoryWire = Effect.fn("decodeMemoryWire")(function* <A, I>(
|
|
133
133
|
schema: Schema.Codec<A, I, never>,
|
package/src/PortRouting.ts
CHANGED
|
@@ -692,6 +692,15 @@ const makeRoutedLedgerServices = Effect.fn("DoPortRouting.makeRoutedLedgerServic
|
|
|
692
692
|
// The local scan IS the whole worklist: one Thread per Object (durability §5).
|
|
693
693
|
scanNonterminal: local.scanNonterminal,
|
|
694
694
|
|
|
695
|
+
readAbortIntent: (request) =>
|
|
696
|
+
submissionTarget("ledger read abort intent", request.submissionId).pipe(
|
|
697
|
+
Effect.flatMap((target) =>
|
|
698
|
+
target._tag === "local"
|
|
699
|
+
? local.readAbortIntent(request)
|
|
700
|
+
: Effect.fail(crossThreadLedgerError("ledger read abort intent", target.threadId)),
|
|
701
|
+
),
|
|
702
|
+
),
|
|
703
|
+
|
|
695
704
|
loadRecoverySnapshot: (request) =>
|
|
696
705
|
submissionTarget("ledger load recovery snapshot", request.submissionId).pipe(
|
|
697
706
|
Effect.flatMap((target) =>
|