@effect-agent/platform-node 0.1.0-beta.96 → 0.1.0-beta.98
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.
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NodeDurableHost-CG2xAhfb.mjs","names":[],"sources":["../src/internal/message-delivery.ts","../src/internal/prepared-admission.ts","../src/NodeDurableHost.ts"],"sourcesContent":["import { Cause, Clock, Effect, Exit, Option } from \"effect\";\nimport {\n MessageDeliveryDriver,\n type MessageDeliveryFailure,\n MessageDeliveryStore,\n} from \"effect-agent/message-delivery\";\n\nconst reportFailure = (cause: Cause.Cause<MessageDeliveryFailure>): Effect.Effect<void> =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.interrupt\n : Effect.logWarning(\"Node message delivery pass failed\").pipe(\n Effect.annotateLogs({\n failureTag: Option.match(Cause.findErrorOption(cause), {\n onNone: () => \"Defect\",\n onSome: (failure) => failure._tag,\n }),\n }),\n );\n\n/** Caller-owned loop. Indexed scans repair absent hints even when both Threads have settled. */\nexport const runNodeMessageDeliveries = Effect.fn(\"NodeMessageDelivery.run\")(function* (\n scanInterval: number,\n) {\n const driver = yield* MessageDeliveryDriver;\n const store = yield* MessageDeliveryStore;\n\n while (true) {\n const pass = yield* driver.runDue().pipe(Effect.exit);\n\n if (Exit.isFailure(pass)) {\n yield* reportFailure(pass.cause);\n yield* Effect.sleep(scanInterval);\n continue;\n }\n\n const deadline = yield* store.nextDeadline().pipe(Effect.exit);\n\n if (Exit.isFailure(deadline)) {\n yield* reportFailure(deadline.cause);\n yield* Effect.sleep(scanInterval);\n continue;\n }\n\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const delay =\n deadline.value === null\n ? scanInterval\n : Math.max(1, Math.min(deadline.value - nowMillis, scanInterval));\n\n yield* Effect.sleep(delay);\n }\n});\n","import { Context, Effect } from \"effect\";\nimport { type DurableSubmitAgent } from \"effect-agent/durable-agent-runtime\";\nimport { type AgentId } from \"effect-agent/identifiers\";\nimport { PreparedInputAdmission } from \"effect-agent/prepared-input-admission\";\nimport { PersistedJson } from \"effect-agent/records\";\nimport {\n ScheduledInputRetryable,\n ScheduledInputRefused,\n ScheduleStorageError,\n} from \"effect-agent/schedule\";\n\nimport { type NodeDurableHost } from \"../NodeDurableHost.ts\";\n\nconst passthroughSubmitAgent = (agentId: AgentId): DurableSubmitAgent<typeof PersistedJson> => ({\n definition: { id: agentId, input: PersistedJson },\n});\n\nconst ambiguous = (): ScheduledInputRetryable =>\n ScheduledInputRetryable.make({ reason: \"ambiguous\" });\n\nconst corrupt = (operation: string): ScheduleStorageError =>\n ScheduleStorageError.make({ operation, reason: \"corrupt\" });\n\n/** Host-owned admission gate, available while the host's worker pool is being assembled. */\nexport class NodeAdmission extends Context.Service<\n NodeAdmission,\n Pick<NodeDurableHost[\"Service\"], \"submit\" | \"submissionStatus\">\n>()(\"@effect-agent/platform-node/internal/NodeAdmission\") {}\n\n/** Acquire the gated source once; worker callers cannot replace its admission authority. */\nexport const makeNodePreparedInputAdmission = Effect.gen(function* () {\n const host = yield* NodeAdmission;\n\n return PreparedInputAdmission.of({\n submissionStatus: (receipt) =>\n host\n .submissionStatus(receipt)\n .pipe(Effect.mapError(() => ScheduledInputRetryable.make({ reason: \"storage\" }))),\n submit: (envelope) =>\n host\n .submit(passthroughSubmitAgent(envelope.agentId), envelope.input, {\n threadId: envelope.threadId,\n principal: envelope.deliveryPrincipal,\n idempotencyKey: envelope.admissionKey,\n ...(envelope.admissionGroup === undefined\n ? {}\n : { admissionGroup: envelope.admissionGroup }),\n ...(envelope.admissionFence === undefined\n ? {}\n : { admissionFence: envelope.admissionFence }),\n ...(envelope.workerAdmission === undefined\n ? {}\n : { workerAdmission: envelope.workerAdmission }),\n ...(envelope.messageAdmission === undefined\n ? {}\n : { messageAdmission: envelope.messageAdmission }),\n definitions: envelope.definitions,\n })\n .pipe(\n Effect.catchTags({\n AdmissionClosed: () =>\n Effect.fail(ScheduledInputRetryable.make({ reason: \"host-closed\" })),\n AgentInputError: () => Effect.fail(corrupt(\"prepared admission input\")),\n AdmissionConflict: () => Effect.fail(corrupt(\"prepared admission conflict\")),\n DigestError: () => Effect.fail(ambiguous()),\n AdmissionPolicyError: (error) =>\n error.reason === \"refused\"\n ? ScheduledInputRefused.make({ code: error.code })\n : ScheduledInputRetryable.make({\n reason: error.reason === \"occupied\" ? \"capacity\" : \"storage\",\n }),\n LedgerError: () => ScheduledInputRetryable.make({ reason: \"storage\" }),\n ThreadStoreError: () => Effect.fail(ambiguous()),\n ThreadNotMaterialized: () => Effect.fail(ambiguous()),\n AppendConflict: () => Effect.fail(ambiguous()),\n FenceRejected: () => Effect.fail(ambiguous()),\n DurableRuntimeFailpointError: () => Effect.fail(ambiguous()),\n }),\n ),\n });\n});\n","import { NodeCrypto } from \"@effect/platform-node\";\nimport { type Stream, Context, Effect, Fiber, Layer, Ref, Schema } from \"effect\";\nimport {\n type IntegrityReport,\n type ObligationReport,\n type ObligationThresholds,\n type RecoveryExplanation,\n type RetryCommand,\n} from \"effect-agent/admin\";\nimport {\n type AgentRegistration,\n type ResolvedBinding,\n type DurableBindingFailure,\n} from \"effect-agent/agent-registration\";\nimport {\n DurableAgentRuntime,\n type DurableAbortFailure,\n type DurableAwaitFailure,\n type DurableExplainFailure,\n type DurableObserveOptions,\n type DurableObligationFailure,\n type DurableRetryFailure,\n type DurableSubmitAgent,\n type DurableSubmitFailure,\n type DurableSubmitOptions,\n type DurableVerifyFailure,\n type DurableWorkerFailure,\n type Receipt,\n type RecoveryReport,\n} from \"effect-agent/durable-agent-runtime\";\nimport { type ThreadId, type SubmissionId } from \"effect-agent/identifiers\";\nimport {\n type MessageDeliveryStore,\n MessageDeliveryDriver,\n type MessageDeliveryError,\n} from \"effect-agent/message-delivery\";\nimport { type OperationDenied } from \"effect-agent/operation-authorizer\";\nimport { PreparedInputAdmission } from \"effect-agent/prepared-input-admission\";\nimport { type CanonicalRecordEnvelope } from \"effect-agent/records\";\nimport {\n type AbortCommand,\n type AbortIntent,\n type Settlement,\n} from \"effect-agent/submission-ledger\";\nimport { type ThreadNotMaterialized, type ThreadStoreError } from \"effect-agent/thread-store\";\n\nimport { runNodeMessageDeliveries } from \"./internal/message-delivery.ts\";\nimport { makeNodePreparedInputAdmission, NodeAdmission } from \"./internal/prepared-admission.ts\";\nimport {\n NodeDurableAgentRuntime,\n NodeDurableAgentRuntimeConfig,\n type NodeDurableAgentRuntimeOptions,\n} from \"./NodeDurableAgentRuntime.ts\";\n\n/**\n * Admission is not open on this host: it is shutting down (deployment §6 step 1, DEPLOY-005).\n * Accepted work is unaffected — only NEW admissions are refused.\n */\nexport class AdmissionClosed extends Schema.TaggedError<AdmissionClosed>()(\"AdmissionClosed\", {\n message: Schema.String,\n}) {}\n\nconst makeHost = Effect.fn(\"NodeDurableHost.make\")(function* (startWorkers: boolean) {\n const runtime = yield* DurableAgentRuntime;\n const config = yield* NodeDurableAgentRuntimeConfig;\n\n // Startup gate (deployment §5, plan §host): configuration decoding and storage compatibility\n // already gated this Layer's dependencies; the last gate before admission opens is recovering\n // EVERY nonterminal Submission. Work needing a live Agent Binding is reported `deferred` and\n // stays a visible obligation for `runWorkers`; lanes durably blocked on an Unknown Outcome are\n // reported `unknown` and wait for the authorized `resolveUnknown` path (DUR-017) — they consume\n // no worker permit while the settlement obligation stays owed.\n const startupRecovery = yield* runtime.runRecovery;\n\n const admission = yield* Ref.make(true);\n\n const requireAdmission: Effect.Effect<void, AdmissionClosed> = Ref.get(admission).pipe(\n Effect.flatMap((open) =>\n open\n ? Effect.void\n : Effect.fail(\n AdmissionClosed.make({ message: \"The host is shutting down; admission is closed.\" }),\n ),\n ),\n );\n\n const submit = <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: DurableSubmitOptions,\n ): Effect.Effect<\n Receipt,\n AdmissionClosed | DurableSubmitFailure,\n InputSchema[\"EncodingServices\"]\n > => requireAdmission.pipe(Effect.andThen(runtime.submit(agent, input, options)));\n\n const deliveryServices = yield* Effect.context<MessageDeliveryStore>();\n\n const deliveryContext = yield* Layer.build(\n MessageDeliveryDriver.layer({\n batchSize: 100,\n concurrency: Math.min(config.workerConcurrency, 32),\n }).pipe(\n Layer.provide(NodeCrypto.layer),\n Layer.provide(\n Layer.effect(PreparedInputAdmission, makeNodePreparedInputAdmission).pipe(\n Layer.provide(\n Layer.succeed(NodeAdmission, { submit, submissionStatus: runtime.submissionStatus }),\n ),\n ),\n ),\n ),\n );\n\n const runDeliveries = runNodeMessageDeliveries(config.wakeScanInterval).pipe(\n Effect.provide(Context.merge(deliveryServices, deliveryContext)),\n );\n\n const runWorkers = <A, E, R>(worker: Effect.Effect<A, E, R>): Effect.Effect<void, E, R> =>\n Effect.scoped(\n // Either side exiting stops and joins the other; delivery interruption cannot leave\n // an apparently healthy worker pool running without message recovery.\n Effect.raceFirst(\n Effect.forEach(\n Array.from({ length: config.workerConcurrency }, (_, index) => index),\n () => worker,\n { concurrency: \"unbounded\", discard: true },\n ),\n runDeliveries,\n ),\n );\n\n // S2 multi-binding pool: every claimed head resolves its exact registered Binding through\n // the host's exact registrations, so one bounded\n // pool serves parent and child lanes — the spec §12 smallest-pool suspension/wakeup proof\n // runs `workerConcurrency: 1` over exactly this loop.\n const runResolvedWorkers = runWorkers(runtime.runResolvedWorker);\n\n const run = startWorkers\n ? Fiber.join(\n yield* runResolvedWorkers.pipe(\n Effect.onExit(() => Ref.set(admission, false)),\n Effect.forkScoped,\n ),\n )\n : runResolvedWorkers;\n\n // Register after the worker fiber: close admission, interrupt/join workers, drain\n // runtime ownership, then close storage and captured application services.\n yield* Effect.addFinalizer(() => Ref.set(admission, false));\n\n return NodeDurableHost.of({\n startupRecovery,\n admissionOpen: Ref.get(admission),\n submit,\n awaitSettlement: runtime.awaitSettlement,\n submissionStatus: runtime.submissionStatus,\n observe: runtime.observe,\n abort: runtime.abort,\n explain: runtime.explain,\n explainThread: runtime.explainThread,\n verify: runtime.verify,\n retry: runtime.retry,\n wake: runtime.wake,\n scanObligations: runtime.scanObligations,\n runWorkers,\n run,\n runResolvedWorkers: run,\n });\n});\n\n/**\n * Operational host service. Prefer the module's `layer` and `run` for managed workers.\n * The static constructors on this class retain explicit, manual worker ownership.\n *\n * Startup gates run during Layer construction, so the service existing implies readiness:\n * configuration was schema-decoded, the SQLite file passed the exact-version compatibility check,\n * and every nonterminal Submission went through one full recovery pass BEFORE admission opened.\n * `startupRecovery` is the auditable evidence of that reconciliation pass.\n *\n * Shutdown runs in reverse Layer order when the owning Scope closes: `submit` starts refusing\n * with `AdmissionClosed` first, then the runtime Layer's ownership drain releases every claim\n * still held so another host can take over the lanes immediately, then the SQLite resources\n * close. Forced termination at any point stays safe — the durability protocol, not graceful\n * shutdown, provides correctness (DEPLOY-006).\n */\nexport class NodeDurableHost extends Context.Service<\n NodeDurableHost,\n {\n /**\n * The recovery decisions executed (or deferred) by this host's startup reconciliation.\n * Reports with the `unknown` disposition identify lanes blocked on Unknown Outcomes that\n * only the authorized DUR-017 resolution path can release.\n */\n readonly startupRecovery: ReadonlyArray<RecoveryReport>;\n /** Admission-role readiness (deployment §7): true until shutdown begins. */\n readonly admissionOpen: Effect.Effect<boolean>;\n /** Observe the managed worker pool, preserving its failure. Manual hosts start their pool here. */\n readonly run: Effect.Effect<void, DurableWorkerFailure | DurableBindingFailure>;\n /** `DurableAgentRuntime.submit` behind the host admission gate. */\n readonly submit: <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: DurableSubmitOptions,\n ) => Effect.Effect<\n Receipt,\n AdmissionClosed | DurableSubmitFailure,\n InputSchema[\"EncodingServices\"]\n >;\n readonly submissionStatus: DurableAgentRuntime[\"Service\"][\"submissionStatus\"];\n readonly awaitSettlement: (receipt: Receipt) => Effect.Effect<Settlement, DurableAwaitFailure>;\n readonly observe: (\n receipt: Receipt,\n options?: DurableObserveOptions,\n ) => Stream.Stream<\n CanonicalRecordEnvelope,\n ThreadStoreError | ThreadNotMaterialized | OperationDenied\n >;\n readonly abort: (command: AbortCommand) => Effect.Effect<AbortIntent, DurableAbortFailure>;\n /** `DurableAgentRuntime.explain` — read-only recovery explanation of one Submission (P7). */\n readonly explain: (\n submissionId: SubmissionId,\n ) => Effect.Effect<RecoveryExplanation, DurableExplainFailure>;\n /** `DurableAgentRuntime.explainThread` — explain every nonterminal lane member. */\n readonly explainThread: (\n threadId: ThreadId,\n ) => Effect.Effect<ReadonlyArray<RecoveryExplanation>, DurableExplainFailure>;\n /** `DurableAgentRuntime.verify` — read-only integrity checks, never a repair (P7). */\n readonly verify: (threadId: ThreadId) => Effect.Effect<IntegrityReport, DurableVerifyFailure>;\n /** `DurableAgentRuntime.retry` — audited single-Submission re-drive with typed refusals. */\n readonly retry: (command: RetryCommand) => Effect.Effect<RecoveryReport, DurableRetryFailure>;\n /** `DurableAgentRuntime.wake` — the documented operator liveness nudge for one lane. */\n readonly wake: (threadId: ThreadId) => Effect.Effect<void, OperationDenied>;\n /** `DurableAgentRuntime.scanObligations` — the scan-based DUR-017/OPS-001 report. */\n readonly scanObligations: (\n thresholds: ObligationThresholds,\n ) => Effect.Effect<ObligationReport, DurableObligationFailure>;\n /**\n * Run `workerConcurrency` copies of the given worker effect (typically\n * `DurableAgentRuntime.runWorker(agent)`) until the caller's Scope interrupts them. The\n * same Scope drives pending message admission and settlement observation independently\n * of Submission liveness. The host never forks daemon fibers.\n */\n readonly runWorkers: <A, E, R>(worker: Effect.Effect<A, E, R>) => Effect.Effect<void, E, R>;\n /**\n * Run `workerConcurrency` copies of `DurableAgentRuntime.runResolvedWorker` over the host's\n * registered Bindings (S2): every claimed head resolves its exact stored Binding before any\n * code runs (SUB-023), so one bounded pool serves parent and attached-child lanes.\n * Hosts built with the module-level `layer` instead join their existing pool.\n */\n readonly runResolvedWorkers: Effect.Effect<void, DurableWorkerFailure | DurableBindingFailure>;\n }\n>()(\"@effect-agent/platform-node/NodeDurableHost\") {\n /**\n * Compile typed registrations and acquire the complete host in one Layer Scope.\n * Node supplies Crypto; model, tool, instruction, and schema services remain required.\n * Startup recovery and shutdown gates are unchanged. Workers start only when the caller\n * runs runResolvedWorkers; this constructor never starts a background worker.\n */\n static layerRegistered<\n const Entries extends ReadonlyArray<AgentRegistration>,\n ContextError = never,\n ContextRequirements = never,\n AuthorizationError = never,\n AuthorizationRequirements = never,\n ReconcilerError = never,\n ReconcilerRequirements = never,\n >(\n registrations: Entries,\n options: NodeDurableAgentRuntimeOptions<\n ContextError,\n ContextRequirements,\n AuthorizationError,\n AuthorizationRequirements,\n ReconcilerError,\n ReconcilerRequirements\n >,\n ) {\n return NodeDurableHost.layer.pipe(\n Layer.provideMerge(NodeDurableAgentRuntime.layerRegistered(registrations, options)),\n );\n }\n\n /**\n * Host gates over an assembled `NodeDurableAgentRuntime` stack. The runtime Layer owns\n * executable registrations; omission registers no Agents, so resolved work fails closed.\n */\n static readonly layer: Layer.Layer<\n NodeDurableHost,\n DurableWorkerFailure | MessageDeliveryError,\n DurableAgentRuntime | NodeDurableAgentRuntimeConfig | MessageDeliveryStore\n > = Layer.effect(NodeDurableHost)(makeHost(false));\n\n /** The complete DN host: `NodeDurableAgentRuntime.layer(options)` plus the host lifecycle gates. */\n static layerStack<\n ContextError = never,\n ContextRequirements = never,\n AuthorizationError = never,\n AuthorizationRequirements = never,\n ReconcilerError = never,\n ReconcilerRequirements = never,\n >(\n options: NodeDurableAgentRuntimeOptions<\n ContextError,\n ContextRequirements,\n AuthorizationError,\n AuthorizationRequirements,\n ReconcilerError,\n ReconcilerRequirements\n > & { readonly bindings?: ReadonlyArray<ResolvedBinding> },\n ) {\n const { bindings = [], ...runtimeOptions } = options;\n\n return NodeDurableHost.layer.pipe(\n Layer.provideMerge(NodeDurableAgentRuntime.layerWithBindings(bindings, runtimeOptions)),\n );\n }\n}\n\n/**\n * Acquire a complete Node host and start one bounded, scoped worker pool after recovery.\n * Provide model, tool, instruction, and schema dependencies to this Layer. Reusing the Layer\n * shares the same pool. A worker failure closes admission; observe it with `run` at the process\n * boundary so the application exits and releases the host instead of remaining idle.\n */\nexport const layer = <\n const Entries extends ReadonlyArray<AgentRegistration>,\n ContextError = never,\n ContextRequirements = never,\n AuthorizationError = never,\n AuthorizationRequirements = never,\n ReconcilerError = never,\n ReconcilerRequirements = never,\n>(\n registrations: Entries,\n options: NodeDurableAgentRuntimeOptions<\n ContextError,\n ContextRequirements,\n AuthorizationError,\n AuthorizationRequirements,\n ReconcilerError,\n ReconcilerRequirements\n >,\n) =>\n Layer.effect(NodeDurableHost)(makeHost(true)).pipe(\n Layer.provideMerge(NodeDurableAgentRuntime.layerRegistered(registrations, options)),\n );\n\n/**\n * Supervise the host's existing workers without starting another pool. Use with\n * `Effect.provide(HostLive)` and `NodeRuntime.runMain`; race it with a server Effect when\n * the same process also serves requests. Unlike `Layer.launch`, this observes worker failures.\n */\nexport const run = Effect.gen(function* () {\n const host = yield* NodeDurableHost;\n\n return yield* host.run;\n});\n"],"mappings":";;;;;;;;;;;;;;;;AAOA,MAAM,iBAAiB,UACrB,MAAM,kBAAkB,KAAK,IACzB,OAAO,YACP,OAAO,WAAW,mCAAmC,CAAC,CAAC,KACrD,OAAO,aAAa,EAClB,YAAY,OAAO,MAAM,MAAM,gBAAgB,KAAK,GAAG;CACrD,cAAc;CACd,SAAS,YAAY,QAAQ;AAC/B,CAAC,EACH,CAAC,CACH;;AAGN,MAAa,2BAA2B,OAAO,GAAG,yBAAyB,CAAC,CAAC,WAC3E,cACA;CACA,MAAM,SAAS,OAAO;CACtB,MAAM,QAAQ,OAAO;CAErB,OAAO,MAAM;EACX,MAAM,OAAO,OAAO,OAAO,OAAO,CAAC,CAAC,KAAK,OAAO,IAAI;EAEpD,IAAI,KAAK,UAAU,IAAI,GAAG;GACxB,OAAO,cAAc,KAAK,KAAK;GAC/B,OAAO,OAAO,MAAM,YAAY;GAChC;EACF;EAEA,MAAM,WAAW,OAAO,MAAM,aAAa,CAA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iBAAiB,QAAQ;EACzB;EACA;EACA,oBAAoB;CACtB,CAAC;AACH,CAAC;;;;;;;;;;;;;;;;AAiBD,IAAa,kBAAb,MAAa,wBAAwB,QAAQ,QAkE3C,CAAC,CAAC,6CAA6C,CAAC,CAAC;;;;;;;CAOjD,OAAO,gBASL,eACA,SAQA;EACA,OAAO,gBAAgB,MAAM,KAC3B,MAAM,aAAa,wBAAwB,gBAAgB,eAAe,OAAO,CAAC,CACpF;CACF;;;;;CAMA,OAAgB,QAIZ,MAAM,OAAO,eAAe,CAAC,CAAC,SAAS,KAAK,CAAC;;CAGjD,OAAO,WAQL,SAQA;EACA,MAAM,EAAE,WAAW,CAAC,GAAG,GAAG,mBAAmB;EAE7C,OAAO,gBAAgB,MAAM,KAC3B,MAAM,aAAa,wBAAwB,kBAAkB,UAAU,cAAc,CAAC,CACxF;CACF;AACF;;;;;;;AAQA,MAAa,SASX,eACA,YASA,MAAM,OAAO,eAAe,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC,KAC5C,MAAM,aAAa,wBAAwB,gBAAgB,eAAe,OAAO,CAAC,CACpF;;;;;;AAOF,MAAa,MAAM,OAAO,IAAI,aAAa;CAGzC,OAAO,QAAO,OAFM,gBAAA,CAED;AACrB,CAAC"}
|
|
1
|
+
{"version":3,"file":"NodeDurableHost-CG2xAhfb.mjs","names":[],"sources":["../src/internal/message-delivery.ts","../src/internal/prepared-admission.ts","../src/NodeDurableHost.ts"],"sourcesContent":["import { Cause, Clock, Effect, Exit, Option } from \"effect\";\nimport {\n MessageDeliveryDriver,\n type MessageDeliveryFailure,\n MessageDeliveryStore,\n} from \"effect-agent/message-delivery\";\n\nconst reportFailure = (cause: Cause.Cause<MessageDeliveryFailure>): Effect.Effect<void> =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.interrupt\n : Effect.logWarning(\"Node message delivery pass failed\").pipe(\n Effect.annotateLogs({\n failureTag: Option.match(Cause.findErrorOption(cause), {\n onNone: () => \"Defect\",\n onSome: (failure) => failure._tag,\n }),\n }),\n );\n\n/** Caller-owned loop. Indexed scans repair absent hints even when both Threads have settled. */\nexport const runNodeMessageDeliveries = Effect.fn(\"NodeMessageDelivery.run\")(function* (\n scanInterval: number,\n) {\n const driver = yield* MessageDeliveryDriver;\n const store = yield* MessageDeliveryStore;\n\n while (true) {\n const pass = yield* driver.runDue().pipe(Effect.exit);\n\n if (Exit.isFailure(pass)) {\n yield* reportFailure(pass.cause);\n yield* Effect.sleep(scanInterval);\n continue;\n }\n\n const deadline = yield* store.nextDeadline().pipe(Effect.exit);\n\n if (Exit.isFailure(deadline)) {\n yield* reportFailure(deadline.cause);\n yield* Effect.sleep(scanInterval);\n continue;\n }\n\n const nowMillis = yield* Clock.currentTimeMillis;\n\n const delay =\n deadline.value === null\n ? scanInterval\n : Math.max(1, Math.min(deadline.value - nowMillis, scanInterval));\n\n yield* Effect.sleep(delay);\n }\n});\n","import { Context, Effect } from \"effect\";\nimport { type DurableSubmitAgent } from \"effect-agent/durable-agent-runtime\";\nimport { type AgentId } from \"effect-agent/identifiers\";\nimport { PreparedInputAdmission } from \"effect-agent/prepared-input-admission\";\nimport { PersistedJson } from \"effect-agent/records\";\nimport {\n ScheduledInputRetryable,\n ScheduledInputRefused,\n ScheduleStorageError,\n} from \"effect-agent/schedule\";\n\nimport { type NodeDurableHost } from \"../NodeDurableHost.ts\";\n\nconst passthroughSubmitAgent = (agentId: AgentId): DurableSubmitAgent<typeof PersistedJson> => ({\n definition: { id: agentId, input: PersistedJson },\n});\n\nconst ambiguous = (): ScheduledInputRetryable =>\n ScheduledInputRetryable.make({ reason: \"ambiguous\" });\n\nconst corrupt = (operation: string): ScheduleStorageError =>\n ScheduleStorageError.make({ operation, reason: \"corrupt\" });\n\n/** Host-owned admission gate, available while the host's worker pool is being assembled. */\nexport class NodeAdmission extends Context.Service<\n NodeAdmission,\n Pick<NodeDurableHost[\"Service\"], \"submit\" | \"submissionStatus\">\n>()(\"@effect-agent/platform-node/internal/NodeAdmission\") {}\n\n/** Acquire the gated source once; worker callers cannot replace its admission authority. */\nexport const makeNodePreparedInputAdmission = Effect.gen(function* () {\n const host = yield* NodeAdmission;\n\n return PreparedInputAdmission.of({\n submissionStatus: (receipt) =>\n host\n .submissionStatus(receipt)\n .pipe(Effect.mapError(() => ScheduledInputRetryable.make({ reason: \"storage\" }))),\n submit: (envelope) =>\n host\n .submit(passthroughSubmitAgent(envelope.agentId), envelope.input, {\n threadId: envelope.threadId,\n principal: envelope.deliveryPrincipal,\n idempotencyKey: envelope.admissionKey,\n ...(envelope.admissionGroup === undefined\n ? {}\n : { admissionGroup: envelope.admissionGroup }),\n ...(envelope.admissionFence === undefined\n ? {}\n : { admissionFence: envelope.admissionFence }),\n ...(envelope.workerAdmission === undefined\n ? {}\n : { workerAdmission: envelope.workerAdmission }),\n ...(envelope.messageAdmission === undefined\n ? {}\n : { messageAdmission: envelope.messageAdmission }),\n definitions: envelope.definitions,\n })\n .pipe(\n Effect.catchTags({\n AdmissionClosed: () =>\n Effect.fail(ScheduledInputRetryable.make({ reason: \"host-closed\" })),\n AgentInputError: () => Effect.fail(corrupt(\"prepared admission input\")),\n AdmissionConflict: () => Effect.fail(corrupt(\"prepared admission conflict\")),\n DigestError: () => Effect.fail(ambiguous()),\n AdmissionPolicyError: (error) =>\n error.reason === \"refused\"\n ? ScheduledInputRefused.make({ code: error.code })\n : ScheduledInputRetryable.make({\n reason: error.reason === \"occupied\" ? \"capacity\" : \"storage\",\n }),\n LedgerError: () => ScheduledInputRetryable.make({ reason: \"storage\" }),\n ThreadStoreError: () => Effect.fail(ambiguous()),\n ThreadNotMaterialized: () => Effect.fail(ambiguous()),\n AppendConflict: () => Effect.fail(ambiguous()),\n FenceRejected: () => Effect.fail(ambiguous()),\n DurableRuntimeFailpointError: () => Effect.fail(ambiguous()),\n }),\n ),\n });\n});\n","import { NodeCrypto } from \"@effect/platform-node\";\nimport { type Stream, Context, Effect, Fiber, Layer, Ref, Schema } from \"effect\";\nimport {\n type IntegrityReport,\n type ObligationReport,\n type ObligationThresholds,\n type RecoveryExplanation,\n type RetryCommand,\n} from \"effect-agent/admin\";\nimport {\n type AgentRegistration,\n type ResolvedBinding,\n type DurableBindingFailure,\n} from \"effect-agent/agent-registration\";\nimport {\n DurableAgentRuntime,\n type DurableAbortFailure,\n type DurableAwaitFailure,\n type DurableExplainFailure,\n type DurableObserveOptions,\n type DurableObligationFailure,\n type DurableRetryFailure,\n type DurableSubmitAgent,\n type DurableSubmitFailure,\n type DurableSubmitOptions,\n type DurableVerifyFailure,\n type DurableWorkerFailure,\n type Receipt,\n type RecoveryReport,\n} from \"effect-agent/durable-agent-runtime\";\nimport { type ThreadId, type SubmissionId } from \"effect-agent/identifiers\";\nimport {\n type MessageDeliveryStore,\n MessageDeliveryDriver,\n type MessageDeliveryError,\n} from \"effect-agent/message-delivery\";\nimport { type OperationDenied } from \"effect-agent/operation-authorizer\";\nimport { PreparedInputAdmission } from \"effect-agent/prepared-input-admission\";\nimport { type CanonicalRecordEnvelope } from \"effect-agent/records\";\nimport {\n type AbortCommand,\n type AbortIntent,\n type Settlement,\n} from \"effect-agent/submission-ledger\";\nimport { type ThreadNotMaterialized, type ThreadStoreError } from \"effect-agent/thread-store\";\n\nimport { runNodeMessageDeliveries } from \"./internal/message-delivery.ts\";\nimport { makeNodePreparedInputAdmission, NodeAdmission } from \"./internal/prepared-admission.ts\";\nimport {\n NodeDurableAgentRuntime,\n NodeDurableAgentRuntimeConfig,\n type NodeDurableAgentRuntimeOptions,\n} from \"./NodeDurableAgentRuntime.ts\";\n\n/**\n * Admission is not open on this host: it is shutting down (deployment §6 step 1, DEPLOY-005).\n * Accepted work is unaffected — only NEW admissions are refused.\n */\nexport class AdmissionClosed extends Schema.TaggedError<AdmissionClosed>()(\"AdmissionClosed\", {\n message: Schema.String,\n}) {}\n\nconst makeHost = Effect.fn(\"NodeDurableHost.make\")(function* (startWorkers: boolean) {\n const runtime = yield* DurableAgentRuntime;\n const config = yield* NodeDurableAgentRuntimeConfig;\n\n // Startup gate (deployment §5, plan §host): configuration decoding and storage compatibility\n // already gated this Layer's dependencies; the last gate before admission opens is recovering\n // EVERY nonterminal Submission. Work needing a live Agent Binding is reported `deferred` and\n // stays a visible obligation for `runWorkers`; submissions parked on an Unknown Outcome are\n // reported `unknown` and wait for the authorized `resolveUnknown` path (DUR-017) — they consume\n // no worker permit while the settlement obligation stays owed and later input can run.\n const startupRecovery = yield* runtime.runRecovery;\n\n const admission = yield* Ref.make(true);\n\n const requireAdmission: Effect.Effect<void, AdmissionClosed> = Ref.get(admission).pipe(\n Effect.flatMap((open) =>\n open\n ? Effect.void\n : Effect.fail(\n AdmissionClosed.make({ message: \"The host is shutting down; admission is closed.\" }),\n ),\n ),\n );\n\n const submit = <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: DurableSubmitOptions,\n ): Effect.Effect<\n Receipt,\n AdmissionClosed | DurableSubmitFailure,\n InputSchema[\"EncodingServices\"]\n > => requireAdmission.pipe(Effect.andThen(runtime.submit(agent, input, options)));\n\n const deliveryServices = yield* Effect.context<MessageDeliveryStore>();\n\n const deliveryContext = yield* Layer.build(\n MessageDeliveryDriver.layer({\n batchSize: 100,\n concurrency: Math.min(config.workerConcurrency, 32),\n }).pipe(\n Layer.provide(NodeCrypto.layer),\n Layer.provide(\n Layer.effect(PreparedInputAdmission, makeNodePreparedInputAdmission).pipe(\n Layer.provide(\n Layer.succeed(NodeAdmission, { submit, submissionStatus: runtime.submissionStatus }),\n ),\n ),\n ),\n ),\n );\n\n const runDeliveries = runNodeMessageDeliveries(config.wakeScanInterval).pipe(\n Effect.provide(Context.merge(deliveryServices, deliveryContext)),\n );\n\n const runWorkers = <A, E, R>(worker: Effect.Effect<A, E, R>): Effect.Effect<void, E, R> =>\n Effect.scoped(\n // Either side exiting stops and joins the other; delivery interruption cannot leave\n // an apparently healthy worker pool running without message recovery.\n Effect.raceFirst(\n Effect.forEach(\n Array.from({ length: config.workerConcurrency }, (_, index) => index),\n () => worker,\n { concurrency: \"unbounded\", discard: true },\n ),\n runDeliveries,\n ),\n );\n\n // Every claimed head resolves the current Binding for its stable agentId, so one bounded\n // pool serves parent and child lanes — the spec §12 smallest-pool suspension/wakeup proof\n // runs `workerConcurrency: 1` over exactly this loop.\n const runResolvedWorkers = runWorkers(runtime.runResolvedWorker);\n\n const run = startWorkers\n ? Fiber.join(\n yield* runResolvedWorkers.pipe(\n Effect.onExit(() => Ref.set(admission, false)),\n Effect.forkScoped,\n ),\n )\n : runResolvedWorkers;\n\n // Register after the worker fiber: close admission, interrupt/join workers, drain\n // runtime ownership, then close storage and captured application services.\n yield* Effect.addFinalizer(() => Ref.set(admission, false));\n\n return NodeDurableHost.of({\n startupRecovery,\n admissionOpen: Ref.get(admission),\n submit,\n awaitSettlement: runtime.awaitSettlement,\n submissionStatus: runtime.submissionStatus,\n observe: runtime.observe,\n abort: runtime.abort,\n explain: runtime.explain,\n explainThread: runtime.explainThread,\n verify: runtime.verify,\n retry: runtime.retry,\n wake: runtime.wake,\n scanObligations: runtime.scanObligations,\n runWorkers,\n run,\n runResolvedWorkers: run,\n });\n});\n\n/**\n * Operational host service. Prefer the module's `layer` and `run` for managed workers.\n * The static constructors on this class retain explicit, manual worker ownership.\n *\n * Startup gates run during Layer construction, so the service existing implies readiness:\n * configuration was schema-decoded, the SQLite file passed the exact-version compatibility check,\n * and every nonterminal Submission went through one full recovery pass BEFORE admission opened.\n * `startupRecovery` is the auditable evidence of that reconciliation pass.\n *\n * Shutdown runs in reverse Layer order when the owning Scope closes: `submit` starts refusing\n * with `AdmissionClosed` first, then the runtime Layer's ownership drain releases every claim\n * still held so another host can take over the lanes immediately, then the SQLite resources\n * close. Forced termination at any point stays safe — the durability protocol, not graceful\n * shutdown, provides correctness (DEPLOY-006).\n */\nexport class NodeDurableHost extends Context.Service<\n NodeDurableHost,\n {\n /**\n * The recovery decisions executed (or deferred) by this host's startup reconciliation.\n * Reports with the `unknown` disposition identify parked Submissions with Unknown Outcomes.\n * They retain their settlement obligation while later input can run; authorized resolution\n * or abort advances the parked Submission.\n */\n readonly startupRecovery: ReadonlyArray<RecoveryReport>;\n /** Admission-role readiness (deployment §7): true until shutdown begins. */\n readonly admissionOpen: Effect.Effect<boolean>;\n /** Observe the managed worker pool, preserving its failure. Manual hosts start their pool here. */\n readonly run: Effect.Effect<void, DurableWorkerFailure | DurableBindingFailure>;\n /** `DurableAgentRuntime.submit` behind the host admission gate. */\n readonly submit: <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema[\"Type\"],\n options: DurableSubmitOptions,\n ) => Effect.Effect<\n Receipt,\n AdmissionClosed | DurableSubmitFailure,\n InputSchema[\"EncodingServices\"]\n >;\n readonly submissionStatus: DurableAgentRuntime[\"Service\"][\"submissionStatus\"];\n readonly awaitSettlement: (receipt: Receipt) => Effect.Effect<Settlement, DurableAwaitFailure>;\n readonly observe: (\n receipt: Receipt,\n options?: DurableObserveOptions,\n ) => Stream.Stream<\n CanonicalRecordEnvelope,\n ThreadStoreError | ThreadNotMaterialized | OperationDenied\n >;\n readonly abort: (command: AbortCommand) => Effect.Effect<AbortIntent, DurableAbortFailure>;\n /** `DurableAgentRuntime.explain` — read-only recovery explanation of one Submission (P7). */\n readonly explain: (\n submissionId: SubmissionId,\n ) => Effect.Effect<RecoveryExplanation, DurableExplainFailure>;\n /** `DurableAgentRuntime.explainThread` — explain every nonterminal lane member. */\n readonly explainThread: (\n threadId: ThreadId,\n ) => Effect.Effect<ReadonlyArray<RecoveryExplanation>, DurableExplainFailure>;\n /** `DurableAgentRuntime.verify` — read-only integrity checks, never a repair (P7). */\n readonly verify: (threadId: ThreadId) => Effect.Effect<IntegrityReport, DurableVerifyFailure>;\n /** `DurableAgentRuntime.retry` — audited single-Submission re-drive with typed refusals. */\n readonly retry: (command: RetryCommand) => Effect.Effect<RecoveryReport, DurableRetryFailure>;\n /** `DurableAgentRuntime.wake` — the documented operator liveness nudge for one lane. */\n readonly wake: (threadId: ThreadId) => Effect.Effect<void, OperationDenied>;\n /** `DurableAgentRuntime.scanObligations` — the scan-based DUR-017/OPS-001 report. */\n readonly scanObligations: (\n thresholds: ObligationThresholds,\n ) => Effect.Effect<ObligationReport, DurableObligationFailure>;\n /**\n * Run `workerConcurrency` copies of the given worker effect (typically\n * `DurableAgentRuntime.runWorker(agent)`) until the caller's Scope interrupts them. The\n * same Scope drives pending message admission and settlement observation independently\n * of Submission liveness. The host never forks daemon fibers.\n */\n readonly runWorkers: <A, E, R>(worker: Effect.Effect<A, E, R>) => Effect.Effect<void, E, R>;\n /**\n * Run `workerConcurrency` copies of `DurableAgentRuntime.runResolvedWorker` over the host's\n * registered Bindings: every claimed head resolves the current Binding for its stable\n * agentId, so one bounded pool serves parent and attached-child lanes.\n * Hosts built with the module-level `layer` instead join their existing pool.\n */\n readonly runResolvedWorkers: Effect.Effect<void, DurableWorkerFailure | DurableBindingFailure>;\n }\n>()(\"@effect-agent/platform-node/NodeDurableHost\") {\n /**\n * Compile typed registrations and acquire the complete host in one Layer Scope.\n * Node supplies Crypto; model, tool, instruction, and schema services remain required.\n * Startup recovery and shutdown gates are unchanged. Workers start only when the caller\n * runs runResolvedWorkers; this constructor never starts a background worker.\n */\n static layerRegistered<\n const Entries extends ReadonlyArray<AgentRegistration>,\n ContextError = never,\n ContextRequirements = never,\n AuthorizationError = never,\n AuthorizationRequirements = never,\n ReconcilerError = never,\n ReconcilerRequirements = never,\n >(\n registrations: Entries,\n options: NodeDurableAgentRuntimeOptions<\n ContextError,\n ContextRequirements,\n AuthorizationError,\n AuthorizationRequirements,\n ReconcilerError,\n ReconcilerRequirements\n >,\n ) {\n return NodeDurableHost.layer.pipe(\n Layer.provideMerge(NodeDurableAgentRuntime.layerRegistered(registrations, options)),\n );\n }\n\n /**\n * Host gates over an assembled `NodeDurableAgentRuntime` stack. The runtime Layer owns\n * executable registrations; omission registers no Agents, so resolved work fails closed.\n */\n static readonly layer: Layer.Layer<\n NodeDurableHost,\n DurableWorkerFailure | MessageDeliveryError,\n DurableAgentRuntime | NodeDurableAgentRuntimeConfig | MessageDeliveryStore\n > = Layer.effect(NodeDurableHost)(makeHost(false));\n\n /** The complete DN host: `NodeDurableAgentRuntime.layer(options)` plus the host lifecycle gates. */\n static layerStack<\n ContextError = never,\n ContextRequirements = never,\n AuthorizationError = never,\n AuthorizationRequirements = never,\n ReconcilerError = never,\n ReconcilerRequirements = never,\n >(\n options: NodeDurableAgentRuntimeOptions<\n ContextError,\n ContextRequirements,\n AuthorizationError,\n AuthorizationRequirements,\n ReconcilerError,\n ReconcilerRequirements\n > & { readonly bindings?: ReadonlyArray<ResolvedBinding> },\n ) {\n const { bindings = [], ...runtimeOptions } = options;\n\n return NodeDurableHost.layer.pipe(\n Layer.provideMerge(NodeDurableAgentRuntime.layerWithBindings(bindings, runtimeOptions)),\n );\n }\n}\n\n/**\n * Acquire a complete Node host and start one bounded, scoped worker pool after recovery.\n * Provide model, tool, instruction, and schema dependencies to this Layer. Reusing the Layer\n * shares the same pool. A worker failure closes admission; observe it with `run` at the process\n * boundary so the application exits and releases the host instead of remaining idle.\n */\nexport const layer = <\n const Entries extends ReadonlyArray<AgentRegistration>,\n ContextError = never,\n ContextRequirements = never,\n AuthorizationError = never,\n AuthorizationRequirements = never,\n ReconcilerError = never,\n ReconcilerRequirements = never,\n>(\n registrations: Entries,\n options: NodeDurableAgentRuntimeOptions<\n ContextError,\n ContextRequirements,\n AuthorizationError,\n AuthorizationRequirements,\n ReconcilerError,\n ReconcilerRequirements\n >,\n) =>\n Layer.effect(NodeDurableHost)(makeHost(true)).pipe(\n Layer.provideMerge(NodeDurableAgentRuntime.layerRegistered(registrations, options)),\n );\n\n/**\n * Supervise the host's existing workers without starting another pool. Use with\n * `Effect.provide(HostLive)` and `NodeRuntime.runMain`; race it with a server Effect when\n * the same process also serves requests. Unlike `Layer.launch`, this observes worker failures.\n */\nexport const run = Effect.gen(function* () {\n const host = yield* Node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,SAAS,IAAI,CAAC,CAAC,CAAC,KAC5C,MAAM,aAAa,wBAAwB,gBAAgB,eAAe,OAAO,CAAC,CACpF;;;;;;AAOF,MAAa,MAAM,OAAO,IAAI,aAAa;CAGzC,OAAO,QAAO,OAFM,gBAAA,CAED;AACrB,CAAC"}
|
|
@@ -24,8 +24,9 @@ declare class AdmissionClosed extends AdmissionClosed_base {}
|
|
|
24
24
|
declare const NodeDurableHost_base: Context.ServiceClass<NodeDurableHost, "@effect-agent/platform-node/NodeDurableHost", {
|
|
25
25
|
/**
|
|
26
26
|
* The recovery decisions executed (or deferred) by this host's startup reconciliation.
|
|
27
|
-
* Reports with the `unknown` disposition identify
|
|
28
|
-
*
|
|
27
|
+
* Reports with the `unknown` disposition identify parked Submissions with Unknown Outcomes.
|
|
28
|
+
* They retain their settlement obligation while later input can run; authorized resolution
|
|
29
|
+
* or abort advances the parked Submission.
|
|
29
30
|
*/
|
|
30
31
|
readonly startupRecovery: ReadonlyArray<RecoveryReport>;
|
|
31
32
|
/** Admission-role readiness (deployment §7): true until shutdown begins. */
|
|
@@ -59,8 +60,8 @@ declare const NodeDurableHost_base: Context.ServiceClass<NodeDurableHost, "@effe
|
|
|
59
60
|
readonly runWorkers: <A, E, R>(worker: Effect.Effect<A, E, R>) => Effect.Effect<void, E, R>;
|
|
60
61
|
/**
|
|
61
62
|
* Run `workerConcurrency` copies of `DurableAgentRuntime.runResolvedWorker` over the host's
|
|
62
|
-
* registered Bindings
|
|
63
|
-
*
|
|
63
|
+
* registered Bindings: every claimed head resolves the current Binding for its stable
|
|
64
|
+
* agentId, so one bounded pool serves parent and attached-child lanes.
|
|
64
65
|
* Hosts built with the module-level `layer` instead join their existing pool.
|
|
65
66
|
*/
|
|
66
67
|
readonly runResolvedWorkers: Effect.Effect<void, DurableWorkerFailure | DurableBindingFailure>;
|
|
@@ -154,7 +155,7 @@ declare const layer: <const Entries extends ReadonlyArray<AgentRegistration>, Co
|
|
|
154
155
|
* `Effect.provide(HostLive)` and `NodeRuntime.runMain`; race it with a server Effect when
|
|
155
156
|
* the same process also serves requests. Unlike `Layer.launch`, this observes worker failures.
|
|
156
157
|
*/
|
|
157
|
-
declare const run: Effect.Effect<void,
|
|
158
|
+
declare const run: Effect.Effect<void, import("effect-agent/agent-registration").BindingUnavailable | DurableWorkerFailure, NodeDurableHost>;
|
|
158
159
|
//#endregion
|
|
159
160
|
export { AdmissionClosed, NodeDurableHost, layer, run, NodeDurableHost_d_exports as t };
|
|
160
161
|
//# sourceMappingURL=NodeDurableHost.d.mts.map
|
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"@effect-agent/platform-node","version":"0.1.0-beta.
|
|
1
|
+
{"name":"@effect-agent/platform-node","version":"0.1.0-beta.98","dependencies":{"@effect-agent/storage-sqlite":"0.1.0-beta.98","@effect-agent/workflow":"0.1.0-beta.98","@effect/platform-node":"4.0.0-rc.115","@effect/sql-sqlite-node":"4.0.0-rc.115","effect-agent":"0.1.0-beta.98"},"devDependencies":{"@effect/vitest":"4.0.0-rc.115","effect":"4.0.0-rc.115","typescript":"7.0.2","vite-plus":"0.3.0"},"peerDependencies":{"effect":"^4.0.0-rc.115"},"exports":{".":{"types":"./dist/index.d.mts","default":"./dist/index.mjs"},"./node-durable-agent-runtime":{"types":"./dist/NodeDurableAgentRuntime.d.mts","default":"./dist/NodeDurableAgentRuntime.mjs"},"./node-durable-host":{"types":"./dist/NodeDurableHost.d.mts","default":"./dist/NodeDurableHost.mjs"},"./node-scheduling":{"types":"./dist/NodeScheduling.d.mts","default":"./dist/NodeScheduling.mjs"},"./node-subscriptions":{"types":"./dist/NodeSubscriptions.d.mts","default":"./dist/NodeSubscriptions.mjs"},"./node-wake-scheduler":{"types":"./dist/NodeWakeScheduler.d.mts","default":"./dist/NodeWakeScheduler.mjs"},"./node-workflow":{"types":"./dist/NodeWorkflow.d.mts","default":"./dist/NodeWorkflow.mjs"}},"description":"Class DN layer assembly for Effect Agent: the durable Node/SQLite runtime host, wake scheduler, and ownership drain.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/danieljvdm/effect-agent.git","directory":"packages/platform-node"},"files":["dist","src"],"type":"module","sideEffects":[],"publishConfig":{"access":"public"},"scripts":{"build":"vp pack","check":"tsc --noEmit -p tsconfig.json"}}
|
package/src/NodeDurableHost.ts
CHANGED
|
@@ -67,9 +67,9 @@ const makeHost = Effect.fn("NodeDurableHost.make")(function* (startWorkers: bool
|
|
|
67
67
|
// Startup gate (deployment §5, plan §host): configuration decoding and storage compatibility
|
|
68
68
|
// already gated this Layer's dependencies; the last gate before admission opens is recovering
|
|
69
69
|
// EVERY nonterminal Submission. Work needing a live Agent Binding is reported `deferred` and
|
|
70
|
-
// stays a visible obligation for `runWorkers`;
|
|
70
|
+
// stays a visible obligation for `runWorkers`; submissions parked on an Unknown Outcome are
|
|
71
71
|
// reported `unknown` and wait for the authorized `resolveUnknown` path (DUR-017) — they consume
|
|
72
|
-
// no worker permit while the settlement obligation stays owed.
|
|
72
|
+
// no worker permit while the settlement obligation stays owed and later input can run.
|
|
73
73
|
const startupRecovery = yield* runtime.runRecovery;
|
|
74
74
|
|
|
75
75
|
const admission = yield* Ref.make(true);
|
|
@@ -130,8 +130,7 @@ const makeHost = Effect.fn("NodeDurableHost.make")(function* (startWorkers: bool
|
|
|
130
130
|
),
|
|
131
131
|
);
|
|
132
132
|
|
|
133
|
-
//
|
|
134
|
-
// the host's exact registrations, so one bounded
|
|
133
|
+
// Every claimed head resolves the current Binding for its stable agentId, so one bounded
|
|
135
134
|
// pool serves parent and child lanes — the spec §12 smallest-pool suspension/wakeup proof
|
|
136
135
|
// runs `workerConcurrency: 1` over exactly this loop.
|
|
137
136
|
const runResolvedWorkers = runWorkers(runtime.runResolvedWorker);
|
|
@@ -189,8 +188,9 @@ export class NodeDurableHost extends Context.Service<
|
|
|
189
188
|
{
|
|
190
189
|
/**
|
|
191
190
|
* The recovery decisions executed (or deferred) by this host's startup reconciliation.
|
|
192
|
-
* Reports with the `unknown` disposition identify
|
|
193
|
-
*
|
|
191
|
+
* Reports with the `unknown` disposition identify parked Submissions with Unknown Outcomes.
|
|
192
|
+
* They retain their settlement obligation while later input can run; authorized resolution
|
|
193
|
+
* or abort advances the parked Submission.
|
|
194
194
|
*/
|
|
195
195
|
readonly startupRecovery: ReadonlyArray<RecoveryReport>;
|
|
196
196
|
/** Admission-role readiness (deployment §7): true until shutdown begins. */
|
|
@@ -244,8 +244,8 @@ export class NodeDurableHost extends Context.Service<
|
|
|
244
244
|
readonly runWorkers: <A, E, R>(worker: Effect.Effect<A, E, R>) => Effect.Effect<void, E, R>;
|
|
245
245
|
/**
|
|
246
246
|
* Run `workerConcurrency` copies of `DurableAgentRuntime.runResolvedWorker` over the host's
|
|
247
|
-
* registered Bindings
|
|
248
|
-
*
|
|
247
|
+
* registered Bindings: every claimed head resolves the current Binding for its stable
|
|
248
|
+
* agentId, so one bounded pool serves parent and attached-child lanes.
|
|
249
249
|
* Hosts built with the module-level `layer` instead join their existing pool.
|
|
250
250
|
*/
|
|
251
251
|
readonly runResolvedWorkers: Effect.Effect<void, DurableWorkerFailure | DurableBindingFailure>;
|