@effect-agent/platform-node 0.1.0-beta.37 → 0.1.0-beta.39

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":"index.mjs","names":[],"sources":["../src/wake-scheduler.ts","../src/layers.ts","../src/host.ts","../src/scheduling.ts"],"sourcesContent":["import type { ConversationId } from \"@effect-agent/core\";\nimport { makeWakeSubscriptionHub, SubmissionLedger, WakeScheduler } from \"@effect-agent/session\";\nimport { Context, Duration, Effect, Layer, PubSub, Stream } from \"effect\";\n\n/**\n * Bounded in-process wake buffer. Wake hints are droppable by contract (the ledger-scan fallback\n * keeps liveness), so a full buffer slides out the oldest hint instead of growing without bound.\n */\nconst WAKE_BUFFER_CAPACITY = 1_024;\n\n/** Cadence authority for the Node wake scheduler's ledger-scan fallback loop. */\nexport class NodeWakeSchedulerConfig extends Context.Service<\n NodeWakeSchedulerConfig,\n {\n /** Interval between ledger scans that re-emit every nonterminal Conversation lane. */\n readonly scanInterval: Duration.Duration;\n }\n>()(\"@effect-agent/platform-node/NodeWakeSchedulerConfig\") {\n static layer(options: {\n readonly scanInterval: Duration.Duration;\n }): Layer.Layer<NodeWakeSchedulerConfig> {\n return Layer.succeed(NodeWakeSchedulerConfig)({ scanInterval: options.scanInterval });\n }\n}\n\nconst makeWakeScheduler = Effect.gen(function* () {\n const ledger = yield* SubmissionLedger;\n const config = yield* NodeWakeSchedulerConfig;\n const hints = yield* PubSub.sliding<ConversationId>(WAKE_BUFFER_CAPACITY);\n const progress = yield* makeWakeSubscriptionHub;\n yield* Effect.addFinalizer(() => PubSub.shutdown(hints));\n\n /**\n * One fallback scan: every Conversation lane with nonterminal work, deduplicated. A scan\n * failure degrades to \"no hints this round\" — the wake channel has no error contract and the\n * next round retries — but is logged so a persistently failing ledger stays visible.\n */\n const scanOnce: Effect.Effect<ReadonlyArray<ConversationId>> = Stream.runCollect(\n ledger.scanNonterminal,\n ).pipe(\n Effect.map((snapshots) => {\n const lanes = new Set<ConversationId>();\n for (const snapshot of snapshots) {\n lanes.add(snapshot.conversationId);\n }\n return [...lanes];\n }),\n Effect.catch((error) =>\n Effect.logWarning(\"NodeWakeScheduler fallback scan failed\", error).pipe(\n Effect.as([] as ReadonlyArray<ConversationId>),\n ),\n ),\n );\n\n /**\n * Deployment §3: correctness must not depend on in-memory notifications, so every `wakes` run\n * merges its PubSub subscription with a Clock-driven ledger-scan loop. Both live entirely in\n * the consuming run's Scope; no fiber outlives its subscriber.\n */\n const fallbackScans: Stream.Stream<ConversationId> = Stream.fromIterableEffectRepeat(\n Effect.sleep(config.scanInterval).pipe(Effect.andThen(scanOnce)),\n );\n\n return WakeScheduler.of({\n notify: (conversationId) =>\n progress\n .notify(conversationId)\n .pipe(Effect.andThen(PubSub.publish(hints, conversationId)), Effect.asVoid),\n subscribe: progress.subscribe,\n wakes: Stream.merge(Stream.fromPubSub(hints), fallbackScans),\n });\n});\n\n/**\n * In-process Node `WakeScheduler`: `notify` publishes to a bounded sliding PubSub for prompt\n * same-process wakeups, and every `wakes` subscription additionally runs a periodic\n * `SubmissionLedger.scanNonterminal` fallback so a dropped, coalesced, or never-sent notification\n * can never strand accepted work (persistence §14). Delivery may duplicate; consumers already\n * treat wakes as pure liveness hints.\n */\nexport const nodeWakeSchedulerLayer: Layer.Layer<\n WakeScheduler,\n never,\n SubmissionLedger | NodeWakeSchedulerConfig\n> = Layer.effect(WakeScheduler)(makeWakeScheduler);\n","import type { SubmissionId } from \"@effect-agent/core\";\nimport {\n CurrentToolFailureObserver,\n toolFailureObserverLayer,\n type RunCostEstimator,\n type RunToolFailureObserver,\n} from \"@effect-agent/engine\";\nimport type { ScheduleStore } from \"@effect-agent/session\";\nimport {\n type ConversationStore,\n type WakeScheduler,\n AgentBindingResolver,\n DEFAULT_OWNERSHIP_LEASE_DURATION,\n DeploymentId,\n DurableAgentRuntime,\n DurableRuntimeConfig,\n DurableRuntimeFailpoint,\n ProducerId,\n ReleaseOwnershipRequest,\n SubmissionLedger,\n ToolReconciler,\n type DurableRuntimeFailpointHandler,\n type OwnershipToken,\n type ResolvedBinding,\n} from \"@effect-agent/session\";\nimport {\n conversationStoreLayer,\n scheduleStoreLayer,\n SqliteStorageConfig,\n SqliteStorageConfigValue,\n storageFailpointLayer,\n submissionLedgerLayer,\n type SqliteStorageFailpointHandler,\n type SqliteStorageInitializationError,\n} from \"@effect-agent/storage-sqlite\";\nimport { NodeCrypto } from \"@effect/platform-node\";\nimport { SqliteClient } from \"@effect/sql-sqlite-node\";\nimport { Context, Duration, Effect, Layer, Ref, Schema } from \"effect\";\n\nimport { NodeWakeSchedulerConfig, nodeWakeSchedulerLayer } from \"./wake-scheduler.ts\";\n\nconst PositiveMillis = Schema.Int.check(Schema.isGreaterThan(0));\nconst NonNegativeMillis = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));\nconst WorkerConcurrency = Schema.Int.check(\n Schema.isGreaterThanOrEqualTo(1),\n Schema.isLessThanOrEqualTo(64),\n);\n\n/** The supplied Node durable runtime configuration failed schema validation (DEPLOY-003). */\nexport class NodePlatformConfigError extends Schema.TaggedError<NodePlatformConfigError>()(\n \"NodePlatformConfigError\",\n {\n message: Schema.String,\n cause: Schema.optionalKey(Schema.Defect()),\n },\n) {}\n\n/**\n * Validated Node durable runtime configuration (deployment §4: decoded once during Layer\n * construction, exposed as a typed service). Every cadence is in milliseconds and every bound is\n * finite; `workerConcurrency` caps how many worker loops `NodeDurableHost.runWorkers` drives.\n */\nexport class NodeDurableRuntimeConfigValue extends Schema.Class<NodeDurableRuntimeConfigValue>(\n \"@effect-agent/platform-node/NodeDurableRuntimeConfigValue\",\n)({\n /** SQLite database file backing BOTH the Conversation Log and the Submission Ledger. */\n filename: Schema.NonEmptyString,\n deploymentId: DeploymentId,\n producerId: ProducerId,\n /** Submission ownership lease duration (D5); liveness hint only, epochs stay authoritative. */\n ownershipLeaseDuration: PositiveMillis,\n /** Finite bound on concurrent worker loops per host (rule 10). */\n workerConcurrency: WorkerConcurrency,\n /** Ledger-scan fallback cadence of the Node wake scheduler (deployment §3). */\n wakeScanInterval: PositiveMillis,\n /** `awaitSettlement` ledger re-check cadence when no wake arrives. */\n settlementPollInterval: PositiveMillis,\n /** Worker ownership-lease renewal cadence. */\n leaseRenewalInterval: PositiveMillis,\n /** Active-Run abort-intent poll cadence. */\n abortPollInterval: PositiveMillis,\n /** Bounded SQLITE_BUSY retry window for write-lock acquisition. */\n busyTimeout: NonNegativeMillis,\n /** Canonical observation poll cadence of the SQLite store. */\n observationPollInterval: NonNegativeMillis,\n /** Opt-in full payload/digest-chain audit while opening the store. */\n verifyOnOpen: Schema.Boolean,\n}) {}\n\n/** Explicit configuration authority for the assembled Node durable runtime. */\nexport class NodeDurableRuntimeConfig extends Context.Service<\n NodeDurableRuntimeConfig,\n NodeDurableRuntimeConfigValue\n>()(\"@effect-agent/platform-node/NodeDurableRuntimeConfig\") {}\n\n/**\n * Raw (unvalidated) construction options for `NodeDurableRuntime.layer`. Optional fields default\n * to the documented production values; everything is schema-decoded into\n * `NodeDurableRuntimeConfigValue` before any resource opens (deployment §5 gate 1).\n */\nexport interface NodeDurableRuntimeOptions {\n readonly filename: string;\n readonly deploymentId: string;\n readonly producerId: string;\n /** Milliseconds; default `DEFAULT_OWNERSHIP_LEASE_DURATION` (30s, D5). */\n readonly ownershipLeaseDuration?: number | undefined;\n /** Default 1; bounded to 1..64. */\n readonly workerConcurrency?: number | undefined;\n /** Milliseconds; default 1000. */\n readonly wakeScanInterval?: number | undefined;\n /** Milliseconds; default 500. */\n readonly settlementPollInterval?: number | undefined;\n /** Milliseconds; default 10000. */\n readonly leaseRenewalInterval?: number | undefined;\n /** Milliseconds; default 500. */\n readonly abortPollInterval?: number | undefined;\n /** Deployment-owned pricing authority used by durable cost budgets and settlements. */\n readonly estimateCostMicrousd?: RunCostEstimator | undefined;\n /** Closed trusted Tool failure reporting. Omission masks ambient observers at construction. */\n readonly toolFailureObserver?: RunToolFailureObserver | undefined;\n /** Milliseconds; default 5000. */\n readonly busyTimeout?: number | undefined;\n /** Milliseconds; default 25. */\n readonly observationPollInterval?: number | undefined;\n /** Default false. */\n readonly verifyOnOpen?: boolean | undefined;\n /** SQLite adapter fault injection (`ledger:*` / `append:*` locations); default none. */\n readonly storageFailpoint?: SqliteStorageFailpointHandler | undefined;\n /** Coordinator fault injection (`submit:*` / `terminalize:*` locations); default none. */\n readonly runtimeFailpoint?: DurableRuntimeFailpointHandler | undefined;\n /**\n * Reconciliation policy consulted for open ordinary Tool Calls before an Unknown Outcome is\n * recorded (durability §10, DUR-009). Defaults to the fail-closed `ToolReconciler.uncertain`:\n * with no registered policy, every open call stays Unknown and routes to the authorized\n * DUR-017 resolution path.\n */\n readonly toolReconciler?: Layer.Layer<ToolReconciler> | undefined;\n /**\n * Registered worker Bindings resolved at durable claim time:\n * build each with `DurableWorkerBinding.make(binding, digests)` so\n * `NodeDurableHost.runResolvedWorkers` / `DurableAgentRuntime.runResolvedWorker` can serve\n * parent and child lanes from one pool with exact-digest resolution (SUB-023). Defaults to\n * the empty registration: every resolved claim then fails closed (`BindingUnavailable` for a\n * root, the framework `ChildCompatibilityFailure` Settlement for a parent-linked child).\n */\n readonly bindings?: ReadonlyArray<ResolvedBinding> | undefined;\n}\n\n/** Every construction failure of the assembled Node durable runtime stack. */\nexport type NodeDurableRuntimeInitializationError =\n | NodePlatformConfigError\n | SqliteStorageInitializationError;\n\n/** The services `NodeDurableRuntime.layer` provides. */\nexport type NodeDurableRuntimeServices =\n | DurableAgentRuntime\n | SubmissionLedger\n | ConversationStore\n | ScheduleStore\n | WakeScheduler\n | DurableRuntimeConfig\n | NodeDurableRuntimeConfig\n | AgentBindingResolver;\n\nconst decodeConfigValue = Schema.decodeUnknownEffect(NodeDurableRuntimeConfigValue);\n\nconst configFromOptions = (\n options: NodeDurableRuntimeOptions,\n): Effect.Effect<NodeDurableRuntimeConfigValue, NodePlatformConfigError> =>\n decodeConfigValue({\n filename: options.filename,\n deploymentId: options.deploymentId,\n producerId: options.producerId,\n ownershipLeaseDuration:\n options.ownershipLeaseDuration ?? Duration.toMillis(DEFAULT_OWNERSHIP_LEASE_DURATION),\n workerConcurrency: options.workerConcurrency ?? 1,\n wakeScanInterval: options.wakeScanInterval ?? 1_000,\n settlementPollInterval: options.settlementPollInterval ?? 500,\n leaseRenewalInterval: options.leaseRenewalInterval ?? 10_000,\n abortPollInterval: options.abortPollInterval ?? 500,\n busyTimeout: options.busyTimeout ?? 5_000,\n observationPollInterval: options.observationPollInterval ?? 25,\n verifyOnOpen: options.verifyOnOpen ?? false,\n }).pipe(\n Effect.mapError((error) =>\n NodePlatformConfigError.make({\n message: `Invalid Node durable runtime configuration: ${error.message}`,\n cause: error,\n }),\n ),\n );\n\n/** SQLite storage configuration derived from the single validated Node configuration. */\nconst sqliteStorageConfigLayer: Layer.Layer<SqliteStorageConfig, never, NodeDurableRuntimeConfig> =\n Layer.effect(SqliteStorageConfig)(\n Effect.gen(function* () {\n const config = yield* NodeDurableRuntimeConfig;\n return SqliteStorageConfigValue.make({\n observationPollInterval: config.observationPollInterval,\n busyTimeout: config.busyTimeout,\n ownershipLeaseDuration: config.ownershipLeaseDuration,\n verifyOnOpen: config.verifyOnOpen,\n });\n }),\n );\n\n/** Session coordinator configuration derived from the single validated Node configuration. */\nconst durableRuntimeConfigLayer = (\n estimateCostMicrousd: RunCostEstimator | undefined,\n): Layer.Layer<DurableRuntimeConfig, never, NodeDurableRuntimeConfig> =>\n Layer.effect(DurableRuntimeConfig)(\n Effect.gen(function* () {\n const config = yield* NodeDurableRuntimeConfig;\n return DurableRuntimeConfig.make({\n deploymentId: config.deploymentId,\n producerId: config.producerId,\n settlementPollInterval: Duration.millis(config.settlementPollInterval),\n leaseRenewalInterval: Duration.millis(config.leaseRenewalInterval),\n abortPollInterval: Duration.millis(config.abortPollInterval),\n ...(estimateCostMicrousd === undefined ? {} : { estimateCostMicrousd }),\n });\n }),\n );\n\n/** Wake fallback-scan cadence derived from the single validated Node configuration. */\nconst wakeSchedulerConfigLayer: Layer.Layer<\n NodeWakeSchedulerConfig,\n never,\n NodeDurableRuntimeConfig\n> = Layer.effect(NodeWakeSchedulerConfig)(\n Effect.gen(function* () {\n const config = yield* NodeDurableRuntimeConfig;\n return { scanInterval: Duration.millis(config.wakeScanInterval) };\n }),\n);\n\nconst releaseTrackedOwnership = (\n ledger: SubmissionLedger[\"Service\"],\n registry: Ref.Ref<ReadonlyMap<SubmissionId, OwnershipToken>>,\n): Effect.Effect<void> =>\n Effect.gen(function* () {\n const tracked = yield* Ref.getAndSet(registry, new Map<SubmissionId, OwnershipToken>());\n for (const [submissionId, ownershipToken] of tracked) {\n yield* ledger\n .releaseOwnership(ReleaseOwnershipRequest.make({ submissionId, ownershipToken }))\n .pipe(\n Effect.catchTags({\n // A newer epoch already owns (or settled) the lane: nothing left to drain.\n OwnershipLost: () => Effect.void,\n // Drain is best-effort by design: the lease still expires and the durability protocol,\n // not graceful shutdown, provides correctness (DEPLOY-006).\n LedgerError: (error) =>\n Effect.logWarning(\"Ownership drain failed; the lease will expire instead\", error),\n }),\n );\n }\n });\n\n/**\n * Shutdown-drain decorator for a `SubmissionLedger` (deployment §6 step 6): every ownership\n * period granted through this Layer is tracked — claims start tracking, renewals follow token\n * rotation, releases and settlement finalizations stop it — and every ownership still held when\n * the Layer's Scope closes is released so another host can claim the lane immediately instead of\n * waiting for lease expiry. The drain is a liveness courtesy only; producer-epoch fencing remains\n * the correctness authority (DUR-006), and a forced kill simply falls back to lease expiry.\n */\nexport const ownershipDrainLayer: Layer.Layer<SubmissionLedger, never, SubmissionLedger> =\n Layer.effect(SubmissionLedger)(\n Effect.gen(function* () {\n const ledger = yield* SubmissionLedger;\n const registry = yield* Ref.make<ReadonlyMap<SubmissionId, OwnershipToken>>(\n new Map<SubmissionId, OwnershipToken>(),\n );\n\n const track = (submissionId: SubmissionId, ownershipToken: OwnershipToken) =>\n Ref.update(registry, (tracked) => new Map(tracked).set(submissionId, ownershipToken));\n const untrack = (submissionId: SubmissionId) =>\n Ref.update(registry, (tracked) => {\n const next = new Map(tracked);\n next.delete(submissionId);\n return next;\n });\n\n yield* Effect.addFinalizer(() => releaseTrackedOwnership(ledger, registry));\n\n return SubmissionLedger.of({\n capabilities: ledger.capabilities,\n admit: ledger.admit,\n markReady: ledger.markReady,\n lookup: ledger.lookup,\n // The S2 subagent ops forward untouched: none of them grants an ownership period, so\n // the drain has nothing to track for them (`suspend` below already stops tracking the\n // waitingForChild ownership period the moment it ends).\n resolveAdmission: ledger.resolveAdmission,\n recordChildSettled: ledger.recordChildSettled,\n reserveChildBudget: ledger.reserveChildBudget,\n attachChildToReservation: ledger.attachChildToReservation,\n beginChildBudgetRelease: ledger.beginChildBudgetRelease,\n releaseChildBudget: ledger.releaseChildBudget,\n claim: (request) =>\n ledger\n .claim(request)\n .pipe(\n Effect.tap((claimed) =>\n claimed._tag === \"Some\"\n ? track(claimed.value.submissionId, claimed.value.ownershipToken)\n : Effect.void,\n ),\n ),\n renewOwnership: (request) =>\n ledger.renewOwnership(request).pipe(\n Effect.tap((renewal) => track(request.submissionId, renewal.ownershipToken)),\n Effect.tapError((error) =>\n error._tag === \"OwnershipLost\" ? untrack(request.submissionId) : Effect.void,\n ),\n ),\n releaseOwnership: (request) =>\n ledger.releaseOwnership(request).pipe(\n Effect.tap(() => untrack(request.submissionId)),\n Effect.tapError((error) =>\n error._tag === \"OwnershipLost\" ? untrack(request.submissionId) : Effect.void,\n ),\n ),\n markInputApplied: ledger.markInputApplied,\n reserveSettlement: ledger.reserveSettlement,\n finalizeSettlement: (request) =>\n ledger.finalizeSettlement(request).pipe(Effect.tap(() => untrack(request.submissionId))),\n requestAbort: ledger.requestAbort,\n claimJoining: ledger.claimJoining,\n markJoined: ledger.markJoined,\n revertJoining: ledger.revertJoining,\n // Suspension ends the ownership period by contract, so the drain stops tracking it.\n suspend: (request) =>\n ledger.suspend(request).pipe(Effect.tap(() => untrack(request.submissionId))),\n recordApprovalDecision: ledger.recordApprovalDecision,\n markUnknown: ledger.markUnknown,\n recordUnknownResolution: ledger.recordUnknownResolution,\n scanNonterminal: ledger.scanNonterminal,\n loadRecoverySnapshot: ledger.loadRecoverySnapshot,\n });\n }),\n );\n\n/**\n * The DN Layer assembly (deployment §12: a Layer-assembly library, not an app entrypoint).\n * `layer(options)` decodes the configuration, opens ONE SQLite database serving both the\n * Conversation Log and the Submission Ledger (so claims fence the same producer epochs), wires\n * the Node wake scheduler with its ledger-scan fallback, wraps the ledger with the shutdown\n * ownership drain, defaults the Tool reconciliation policy to the fail-closed\n * `ToolReconciler.uncertain` (override via `options.toolReconciler`), and provides a ready\n * `DurableAgentRuntime` on top. Storage compatibility is\n * verified during construction: an incompatible database file fails the Layer with\n * `SqliteStorageCompatibilityError` before anything is mutated (DEPLOY-008).\n */\nexport class NodeDurableRuntime {\n /** Validated configuration Layer; fails typed when the supplied options are out of bounds. */\n static configLayer(\n options: NodeDurableRuntimeOptions,\n ): Layer.Layer<NodeDurableRuntimeConfig, NodePlatformConfigError> {\n return Layer.effect(NodeDurableRuntimeConfig)(configFromOptions(options));\n }\n\n /** The full DN runtime stack over one SQLite file. */\n static layer(\n options: NodeDurableRuntimeOptions,\n ): Layer.Layer<NodeDurableRuntimeServices, NodeDurableRuntimeInitializationError> {\n return Layer.unwrap(\n Effect.map(configFromOptions(options), (config) => {\n const nodeConfigLayer = Layer.succeed(NodeDurableRuntimeConfig)(config);\n const infrastructure = Layer.mergeAll(\n sqliteStorageConfigLayer,\n storageFailpointLayer({\n filename: config.filename,\n failpoint: options.storageFailpoint,\n }),\n SqliteClient.layer({ filename: config.filename }),\n NodeCrypto.layer,\n );\n const runtimeFailpointLayer =\n options.runtimeFailpoint === undefined\n ? DurableRuntimeFailpoint.layer\n : Layer.succeed(DurableRuntimeFailpoint)({ hit: options.runtimeFailpoint });\n const reconcilerLayer = options.toolReconciler ?? ToolReconciler.uncertain;\n const observerLayer =\n options.toolFailureObserver === undefined\n ? Layer.succeed(CurrentToolFailureObserver)(undefined)\n : toolFailureObserverLayer(options.toolFailureObserver);\n const bindingResolverLayer = AgentBindingResolver.layer(options.bindings ?? []);\n const ports = Layer.mergeAll(\n conversationStoreLayer,\n scheduleStoreLayer,\n nodeWakeSchedulerLayer.pipe(\n Layer.provideMerge(ownershipDrainLayer.pipe(Layer.provide(submissionLedgerLayer))),\n ),\n );\n return DurableAgentRuntime.layer.pipe(\n Layer.provideMerge(\n Layer.mergeAll(\n ports,\n durableRuntimeConfigLayer(options.estimateCostMicrousd),\n bindingResolverLayer,\n ),\n ),\n Layer.provide(\n Layer.mergeAll(\n wakeSchedulerConfigLayer,\n runtimeFailpointLayer,\n reconcilerLayer,\n observerLayer,\n ),\n ),\n Layer.provideMerge(infrastructure),\n Layer.provideMerge(nodeConfigLayer),\n );\n }),\n );\n }\n}\n","import type { ConversationId, SubmissionId } from \"@effect-agent/core\";\nimport {\n AgentBindingResolver,\n DurableAgentRuntime,\n type AbortCommand,\n type AbortIntent,\n type CanonicalRecordEnvelope,\n type ConversationNotMaterialized,\n type ConversationStoreError,\n type DurableAbortFailure,\n type DurableAwaitFailure,\n type DurableBindingFailure,\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 IntegrityReport,\n type ObligationReport,\n type ObligationThresholds,\n type OperationDenied,\n type Receipt,\n type RecoveryExplanation,\n type RecoveryReport,\n type RetryCommand,\n type Settlement,\n} from \"@effect-agent/session\";\nimport { Context, Effect, Layer, Ref, Schema, Stream } from \"effect\";\n\nimport {\n NodeDurableRuntime,\n NodeDurableRuntimeConfig,\n type NodeDurableRuntimeInitializationError,\n type NodeDurableRuntimeOptions,\n type NodeDurableRuntimeServices,\n} from \"./layers.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.gen(function* () {\n const runtime = yield* DurableAgentRuntime;\n const config = yield* NodeDurableRuntimeConfig;\n const bindingResolver = yield* AgentBindingResolver;\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 // Shutdown step 1 (DEPLOY-005): admission closes before the ownership drain in the runtime\n // Layer below releases claims and before the stores close in reverse acquisition order.\n yield* Effect.addFinalizer(() => Ref.set(admission, false));\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 runWorkers = <A, E, R>(worker: Effect.Effect<A, E, R>): Effect.Effect<void, E, R> =>\n Effect.forEach(\n Array.from({ length: config.workerConcurrency }, (_, index) => index),\n () => worker,\n { concurrency: \"unbounded\", discard: true },\n );\n\n // S2 multi-binding pool: every claimed head resolves its exact registered Binding through\n // the host's `AgentBindingResolver` (`NodeDurableRuntimeOptions.bindings`), 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(\n runtime.runResolvedWorker.pipe(Effect.provideService(AgentBindingResolver, bindingResolver)),\n );\n\n return NodeDurableHost.of({\n startupRecovery,\n admissionOpen: Ref.get(admission),\n submit,\n awaitSettlement: runtime.awaitSettlement,\n observe: runtime.observe,\n abort: runtime.abort,\n explain: runtime.explain,\n explainConversation: runtime.explainConversation,\n verify: runtime.verify,\n retry: runtime.retry,\n wake: runtime.wake,\n scanObligations: runtime.scanObligations,\n runWorkers,\n runResolvedWorkers,\n });\n});\n\n/**\n * Operational host lifecycle for the DN runtime (deployment §2/§5/§6).\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 /** `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 awaitSettlement: (receipt: Receipt) => Effect.Effect<Settlement, DurableAwaitFailure>;\n readonly observe: (\n receipt: Receipt,\n options?: DurableObserveOptions,\n ) => Stream.Stream<\n CanonicalRecordEnvelope,\n ConversationStoreError | ConversationNotMaterialized | 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.explainConversation` — explain every nonterminal lane member. */\n readonly explainConversation: (\n conversationId: ConversationId,\n ) => Effect.Effect<ReadonlyArray<RecoveryExplanation>, DurableExplainFailure>;\n /** `DurableAgentRuntime.verify` — read-only integrity checks, never a repair (P7). */\n readonly verify: (\n conversationId: ConversationId,\n ) => 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: (conversationId: ConversationId) => 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 * bound is the validated finite configuration value; 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 */\n readonly runResolvedWorkers: Effect.Effect<void, DurableWorkerFailure | DurableBindingFailure>;\n }\n>()(\"@effect-agent/platform-node/NodeDurableHost\") {\n /** Host gates over an already-assembled `NodeDurableRuntime` stack. */\n static readonly layer: Layer.Layer<\n NodeDurableHost,\n DurableWorkerFailure,\n DurableAgentRuntime | NodeDurableRuntimeConfig | AgentBindingResolver\n > = Layer.effect(NodeDurableHost)(makeHost);\n\n /** The complete DN host: `NodeDurableRuntime.layer(options)` plus the host lifecycle gates. */\n static layerStack(\n options: NodeDurableRuntimeOptions,\n ): Layer.Layer<\n NodeDurableHost | NodeDurableRuntimeServices,\n DurableWorkerFailure | NodeDurableRuntimeInitializationError\n > {\n return NodeDurableHost.layer.pipe(Layer.provideMerge(NodeDurableRuntime.layer(options)));\n }\n}\n","import type { AgentId } from \"@effect-agent/core\";\nimport {\n type DurableSubmitAgent,\n type ScheduleProcessFailure,\n type ScheduleAuthorizer,\n type SchedulingLimits,\n ScheduleStorageError,\n ScheduleStore,\n type ScheduleValidationError,\n ScheduledInputAdmission,\n ScheduledInputRetryable,\n ScheduleWake,\n Scheduling,\n ScheduleDriver,\n defaultSchedulingLimits,\n PersistedJson,\n} from \"@effect-agent/session\";\nimport { NodeCrypto } from \"@effect/platform-node\";\nimport { Cause, Duration, Effect, Layer, Option, PubSub, Result } from \"effect\";\n\nimport { NodeDurableHost } from \"./host.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/**\n * Scheduled admission through the existing host gate. Once the gate admits the call, every\n * runtime failure stays ambiguous because the Submission may already have committed.\n */\nexport const nodeScheduledInputAdmissionLayer: Layer.Layer<\n ScheduledInputAdmission,\n never,\n NodeDurableHost\n> = Layer.effect(\n ScheduledInputAdmission,\n Effect.gen(function* () {\n const host = yield* NodeDurableHost;\n return ScheduledInputAdmission.of({\n submit: (envelope) =>\n host\n .submit(passthroughSubmitAgent(envelope.agentId), envelope.input, {\n conversationId: envelope.conversationId,\n principal: envelope.deliveryPrincipal,\n idempotencyKey: envelope.admissionKey,\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(\"scheduled admission input\")),\n AdmissionConflict: () => Effect.fail(corrupt(\"scheduled admission conflict\")),\n DigestError: () => Effect.fail(ambiguous()),\n LedgerError: () => Effect.fail(ambiguous()),\n ConversationStoreError: () => Effect.fail(ambiguous()),\n ConversationNotMaterialized: () => Effect.fail(ambiguous()),\n AppendConflict: () => Effect.fail(ambiguous()),\n FenceRejected: () => Effect.fail(ambiguous()),\n DurableRuntimeFailpointError: () => Effect.fail(ambiguous()),\n }),\n ),\n });\n }),\n);\n\n/** One bounded hint slot for the single supported Node scheduler. Indexed polling repairs loss. */\nexport const nodeScheduleWakeLayer: Layer.Layer<ScheduleWake> = Layer.effect(\n ScheduleWake,\n Effect.gen(function* () {\n const hints = yield* PubSub.sliding<void>(1);\n const subscription = yield* PubSub.subscribe(hints);\n yield* Effect.addFinalizer(() => PubSub.shutdown(hints));\n return ScheduleWake.of({\n notify: PubSub.publish(hints, undefined).pipe(Effect.asVoid),\n await: PubSub.take(subscription),\n });\n }),\n);\n\nconst reportPassFailure = (cause: Cause.Cause<ScheduleProcessFailure>): Effect.Effect<boolean> =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.interrupt\n : Effect.logWarning(\"Node scheduling pass failed\").pipe(\n Effect.annotateLogs({\n failureTag: Option.match(Cause.findErrorOption(cause), {\n onNone: () => \"Defect\",\n onSome: (error) => error._tag,\n }),\n }),\n Effect.as(false),\n );\n\nconst nodeSchedulingDriverLayer = (\n limits: SchedulingLimits,\n): Layer.Layer<never, never, ScheduleDriver | ScheduleStore | ScheduleWake> =>\n Layer.effectDiscard(\n Effect.gen(function* () {\n const scheduling = yield* ScheduleDriver;\n const store = yield* ScheduleStore;\n const wake = yield* ScheduleWake;\n\n const run = Effect.gen(function* () {\n while (true) {\n const passSucceeded = yield* scheduling.runDue().pipe(\n Effect.map((pass) => pass.failed === 0),\n Effect.catchCause(reportPassFailure),\n );\n const deadlineResult = passSucceeded\n ? yield* store.nextDeadline().pipe(Effect.result)\n : Result.fail(\n ScheduleStorageError.make({ operation: \"driver pass\", reason: \"unavailable\" }),\n );\n if (Result.isFailure(deadlineResult) && passSucceeded) {\n yield* Effect.logWarning(\"Node scheduling deadline query failed\");\n }\n const nowMillis = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n const deadlineDelay =\n Result.isSuccess(deadlineResult) && deadlineResult.success !== null\n ? Math.max(0, deadlineResult.success - nowMillis)\n : limits.recoveryPollMillis;\n const delay = Math.min(deadlineDelay, limits.recoveryPollMillis);\n yield* Effect.raceFirst(wake.await, Effect.sleep(Duration.millis(delay)));\n }\n });\n\n yield* Effect.forkScoped(run);\n }),\n );\n\nexport interface NodeSchedulingOptions {\n readonly limits?: SchedulingLimits | undefined;\n}\n\n/**\n * Optional Scope-owned Node scheduling service and driver. The caller must provide the existing\n * host, its SQLite ScheduleStore, and an explicit ScheduleAuthorizer.\n */\nexport class NodeScheduling {\n static layer(\n options: NodeSchedulingOptions = {},\n ): Layer.Layer<\n Scheduling,\n ScheduleValidationError,\n NodeDurableHost | ScheduleStore | ScheduleAuthorizer\n > {\n const limits = options.limits ?? defaultSchedulingLimits;\n const schedulingWithDriver = nodeSchedulingDriverLayer(limits).pipe(\n Layer.provide(ScheduleDriver.layer(limits)),\n Layer.merge(Scheduling.layer(limits)),\n );\n return schedulingWithDriver.pipe(\n Layer.provide(\n Layer.mergeAll(nodeScheduledInputAdmissionLayer, nodeScheduleWakeLayer, NodeCrypto.layer),\n ),\n );\n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qBAAqB,KAAK;IAAE,WAAW;IAAe,QAAQ;GAAc,CAAC,CAC/E;GACJ,IAAI,OAAO,UAAU,cAAc,KAAK,eACtC,OAAO,OAAO,WAAW,uCAAuC;GAElE,MAAM,YAAY,OAAO,OAAO,WAAW,UAAU,MAAM,iBAAiB;GAC5E,MAAM,gBACJ,OAAO,UAAU,cAAc,KAAK,eAAe,YAAY,OAC3D,KAAK,IAAI,GAAG,eAAe,UAAU,SAAS,IAC9C,OAAO;GACb,MAAM,QAAQ,KAAK,IAAI,eAAe,OAAO,kBAAkB;GAC/D,OAAO,OAAO,UAAU,KAAK,OAAO,OAAO,MAAM,SAAS,OAAO,KAAK,CAAC,CAAC;EAC1E;CACF,CAAC;CAED,OAAO,OAAO,WAAW,GAAG;AAC9B,CAAC,CACH;;;;;AAUF,IAAa,iBAAb,MAA4B;CAC1B,OAAO,MACL,UAAiC,CAAC,GAKlC;EACA,MAAM,SAAS,QAAQ,UAAU;EAKjC,OAJ6B,0BAA0B,MAAM,CAAC,CAAC,KAC7D,MAAM,QAAQ,eAAe,MAAM,MAAM,CAAC,GAC1C,MAAM,MAAM,WAAW,MAAM,MAAM,CAAC,CAEZ,CAAC,CAAC,KAC1B,MAAM,QACJ,MAAM,SAAS,kCAAkC,uBAAuB,WAAW,KAAK,CAC1F,CACF;CACF;AACF"}
1
+ {"version":3,"file":"index.mjs","names":["reportPassFailure"],"sources":["../src/wake-scheduler.ts","../src/layers.ts","../src/host.ts","../src/subscriptions.ts","../src/scheduling.ts"],"sourcesContent":["import type { ThreadId } from \"@effect-agent/core\";\nimport { makeWakeSubscriptionHub, SubmissionLedger, WakeScheduler } from \"@effect-agent/thread\";\nimport type { Duration } from \"effect\";\nimport { Context, Effect, Layer, PubSub, Stream } from \"effect\";\n\n/**\n * Bounded in-process wake buffer. Wake hints are droppable by contract (the ledger-scan fallback\n * keeps liveness), so a full buffer slides out the oldest hint instead of growing without bound.\n */\nconst WAKE_BUFFER_CAPACITY = 1_024;\n\n/** Cadence authority for the Node wake scheduler's ledger-scan fallback loop. */\nexport class NodeWakeSchedulerConfig extends Context.Service<\n NodeWakeSchedulerConfig,\n {\n /** Interval between ledger scans that re-emit every nonterminal Thread lane. */\n readonly scanInterval: Duration.Duration;\n }\n>()(\"@effect-agent/platform-node/NodeWakeSchedulerConfig\") {\n static layer(options: {\n readonly scanInterval: Duration.Duration;\n }): Layer.Layer<NodeWakeSchedulerConfig> {\n return Layer.succeed(NodeWakeSchedulerConfig)({ scanInterval: options.scanInterval });\n }\n}\n\nconst makeWakeScheduler = Effect.gen(function* () {\n const ledger = yield* SubmissionLedger;\n const config = yield* NodeWakeSchedulerConfig;\n const hints = yield* PubSub.sliding<ThreadId>(WAKE_BUFFER_CAPACITY);\n const progress = yield* makeWakeSubscriptionHub;\n yield* Effect.addFinalizer(() => PubSub.shutdown(hints));\n\n /**\n * One fallback scan: every Thread lane with nonterminal work, deduplicated. A scan\n * failure degrades to \"no hints this round\" — the wake channel has no error contract and the\n * next round retries — but is logged so a persistently failing ledger stays visible.\n */\n const scanOnce: Effect.Effect<ReadonlyArray<ThreadId>> = Stream.runCollect(\n ledger.scanNonterminal,\n ).pipe(\n Effect.map((snapshots) => {\n const lanes = new Set<ThreadId>();\n for (const snapshot of snapshots) {\n lanes.add(snapshot.threadId);\n }\n return [...lanes];\n }),\n Effect.catch((error) =>\n Effect.logWarning(\"NodeWakeScheduler fallback scan failed\", error).pipe(\n Effect.as([] as ReadonlyArray<ThreadId>),\n ),\n ),\n );\n\n /**\n * Deployment §3: correctness must not depend on in-memory notifications, so every `wakes` run\n * merges its PubSub subscription with a Clock-driven ledger-scan loop. Both live entirely in\n * the consuming run's Scope; no fiber outlives its subscriber.\n */\n const fallbackScans: Stream.Stream<ThreadId> = Stream.fromIterableEffectRepeat(\n Effect.sleep(config.scanInterval).pipe(Effect.andThen(scanOnce)),\n );\n\n return WakeScheduler.of({\n notify: (threadId) =>\n progress\n .notify(threadId)\n .pipe(Effect.andThen(PubSub.publish(hints, threadId)), Effect.asVoid),\n subscribe: progress.subscribe,\n wakes: Stream.merge(Stream.fromPubSub(hints), fallbackScans),\n });\n});\n\n/**\n * In-process Node `WakeScheduler`: `notify` publishes to a bounded sliding PubSub for prompt\n * same-process wakeups, and every `wakes` subscription additionally runs a periodic\n * `SubmissionLedger.scanNonterminal` fallback so a dropped, coalesced, or never-sent notification\n * can never strand accepted work (persistence §14). Delivery may duplicate; consumers already\n * treat wakes as pure liveness hints.\n */\nexport const nodeWakeSchedulerLayer: Layer.Layer<\n WakeScheduler,\n never,\n SubmissionLedger | NodeWakeSchedulerConfig\n> = Layer.effect(WakeScheduler)(makeWakeScheduler);\n","import type { SubmissionId } from \"@effect-agent/core\";\nimport {\n CurrentToolFailureObserver,\n RunContextPreparationPassthrough,\n RunToolAuthorization,\n toolFailureObserverLayer,\n type RunContextPreparation,\n type RunCostEstimator,\n type RunToolFailureObserver,\n} from \"@effect-agent/engine\";\nimport {\n threadStoreLayer,\n scheduleStoreLayer,\n SqliteStorageConfig,\n SqliteStorageConfigValue,\n storageFailpointLayer,\n submissionLedgerLayer,\n type SqliteStorageFailpointHandler,\n type SqliteStorageInitializationError,\n} from \"@effect-agent/storage-sqlite\";\nimport {\n type ScheduleStore,\n type ThreadStore,\n type WakeScheduler,\n DEFAULT_OWNERSHIP_LEASE_DURATION,\n DeploymentId,\n DurableAgentRuntime,\n DurableRuntimeConfig,\n DurableRuntimeFailpoint,\n ProducerId,\n ReleaseOwnershipRequest,\n SubmissionLedger,\n ToolReconciler,\n type DurableRuntimeFailpointHandler,\n type OwnershipToken,\n} from \"@effect-agent/thread\";\nimport { NodeCrypto } from \"@effect/platform-node\";\nimport { SqliteClient } from \"@effect/sql-sqlite-node\";\nimport { Context, type Crypto, Duration, Effect, Layer, Ref, Schema } from \"effect\";\n\nimport { NodeWakeSchedulerConfig, nodeWakeSchedulerLayer } from \"./wake-scheduler.ts\";\n\nconst PositiveMillis = Schema.Int.check(Schema.isGreaterThan(0));\nconst NonNegativeMillis = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));\nconst WorkerConcurrency = Schema.Int.check(\n Schema.isGreaterThanOrEqualTo(1),\n Schema.isLessThanOrEqualTo(64),\n);\n\n/** The supplied Node durable runtime configuration failed schema validation (DEPLOY-003). */\nexport class NodePlatformConfigError extends Schema.TaggedError<NodePlatformConfigError>()(\n \"NodePlatformConfigError\",\n {\n message: Schema.String,\n cause: Schema.optionalKey(Schema.Defect()),\n },\n) {}\n\n/**\n * Validated Node durable runtime configuration (deployment §4: decoded once during Layer\n * construction, exposed as a typed service). Every cadence is in milliseconds and every bound is\n * finite; `workerConcurrency` caps how many worker loops `NodeDurableHost.runWorkers` drives.\n */\nexport class NodeDurableRuntimeConfigValue extends Schema.Class<NodeDurableRuntimeConfigValue>(\n \"@effect-agent/platform-node/NodeDurableRuntimeConfigValue\",\n)({\n /** SQLite database file backing BOTH the Thread Log and the Submission Ledger. */\n filename: Schema.NonEmptyString,\n deploymentId: DeploymentId,\n producerId: ProducerId,\n /** Submission ownership lease duration (D5); liveness hint only, epochs stay authoritative. */\n ownershipLeaseDuration: PositiveMillis,\n /** Finite bound on concurrent worker loops per host (rule 10). */\n workerConcurrency: WorkerConcurrency,\n /** Ledger-scan fallback cadence of the Node wake scheduler (deployment §3). */\n wakeScanInterval: PositiveMillis,\n /** `awaitSettlement` ledger re-check cadence when no wake arrives. */\n settlementPollInterval: PositiveMillis,\n /** Worker ownership-lease renewal cadence. */\n leaseRenewalInterval: PositiveMillis,\n /** Active-Run abort-intent poll cadence. */\n abortPollInterval: PositiveMillis,\n /** Bounded SQLITE_BUSY retry window for write-lock acquisition. */\n busyTimeout: NonNegativeMillis,\n /** Canonical observation poll cadence of the SQLite store. */\n observationPollInterval: NonNegativeMillis,\n /** Opt-in full payload/digest-chain audit while opening the store. */\n verifyOnOpen: Schema.Boolean,\n}) {}\n\n/** Explicit configuration authority for the assembled Node durable runtime. */\nexport class NodeDurableRuntimeConfig extends Context.Service<\n NodeDurableRuntimeConfig,\n NodeDurableRuntimeConfigValue\n>()(\"@effect-agent/platform-node/NodeDurableRuntimeConfig\") {}\n\n/**\n * Raw (unvalidated) construction options for `NodeDurableRuntime.layer`. Optional fields default\n * to the documented production values; everything is schema-decoded into\n * `NodeDurableRuntimeConfigValue` before any resource opens (deployment §5 gate 1).\n */\nexport interface NodeDurableRuntimeOptions<\n ContextError = never,\n ContextRequirements = never,\n AuthorizationError = never,\n AuthorizationRequirements = never,\n> {\n readonly filename: string;\n readonly deploymentId: string;\n readonly producerId: string;\n /** Milliseconds; default `DEFAULT_OWNERSHIP_LEASE_DURATION` (30s, D5). */\n readonly ownershipLeaseDuration?: number | undefined;\n /** Default 1; bounded to 1..64. */\n readonly workerConcurrency?: number | undefined;\n /** Milliseconds; default 1000. */\n readonly wakeScanInterval?: number | undefined;\n /** Milliseconds; default 500. */\n readonly settlementPollInterval?: number | undefined;\n /** Milliseconds; default 10000. */\n readonly leaseRenewalInterval?: number | undefined;\n /** Milliseconds; default 500. */\n readonly abortPollInterval?: number | undefined;\n /** Deployment-owned pricing authority used by durable cost budgets and settlements. */\n readonly estimateCostMicrousd?: RunCostEstimator | undefined;\n /** Closed trusted Tool failure reporting. Omission masks ambient observers at construction. */\n readonly toolFailureObserver?: RunToolFailureObserver | undefined;\n /** Milliseconds; default 5000. */\n readonly busyTimeout?: number | undefined;\n /** Milliseconds; default 25. */\n readonly observationPollInterval?: number | undefined;\n /** Default false. */\n readonly verifyOnOpen?: boolean | undefined;\n /** SQLite adapter fault injection (`ledger:*` / `append:*` locations); default none. */\n readonly storageFailpoint?: SqliteStorageFailpointHandler | undefined;\n /** Coordinator fault injection (`submit:*` / `terminalize:*` locations); default none. */\n readonly runtimeFailpoint?: DurableRuntimeFailpointHandler | undefined;\n /**\n * Reconciliation policy consulted for open ordinary Tool Calls before an Unknown Outcome is\n * recorded (durability §10, DUR-009). Defaults to the fail-closed `ToolReconciler.uncertain`:\n * with no registered policy, every open call stays Unknown and routes to the authorized\n * DUR-017 resolution path.\n */\n readonly toolReconciler?: Layer.Layer<ToolReconciler> | undefined;\n /** Host prompt preparation/compaction, acquired once with the runtime; default pass-through. */\n readonly runContext?:\n | Layer.Layer<RunContextPreparation, ContextError, ContextRequirements | Crypto.Crypto>\n | undefined;\n /**\n * Independent action-time Tool authority, acquired once with the runtime; default allow-all.\n * Construction errors and application dependencies remain in the assembled Layer's E and R.\n * The platform supplies Crypto to both extension Layers.\n */\n readonly toolAuthorization?:\n | Layer.Layer<\n RunToolAuthorization,\n AuthorizationError,\n AuthorizationRequirements | Crypto.Crypto\n >\n | undefined;\n}\n\n/** Built-in construction failures. `layer` also preserves supplied service Layers' errors. */\nexport type NodeDurableRuntimeInitializationError =\n | NodePlatformConfigError\n | SqliteStorageInitializationError;\n\n/** The services `NodeDurableRuntime.layer` provides. */\nexport type NodeDurableRuntimeServices =\n | DurableAgentRuntime\n | SubmissionLedger\n | ThreadStore\n | ScheduleStore\n | WakeScheduler\n | DurableRuntimeConfig\n | NodeDurableRuntimeConfig;\n\nconst decodeConfigValue = Schema.decodeUnknownEffect(NodeDurableRuntimeConfigValue);\n\nconst configFromOptions = (\n options: Omit<NodeDurableRuntimeOptions, \"runContext\" | \"toolAuthorization\">,\n): Effect.Effect<NodeDurableRuntimeConfigValue, NodePlatformConfigError> =>\n decodeConfigValue({\n filename: options.filename,\n deploymentId: options.deploymentId,\n producerId: options.producerId,\n ownershipLeaseDuration:\n options.ownershipLeaseDuration ?? Duration.toMillis(DEFAULT_OWNERSHIP_LEASE_DURATION),\n workerConcurrency: options.workerConcurrency ?? 1,\n wakeScanInterval: options.wakeScanInterval ?? 1_000,\n settlementPollInterval: options.settlementPollInterval ?? 500,\n leaseRenewalInterval: options.leaseRenewalInterval ?? 10_000,\n abortPollInterval: options.abortPollInterval ?? 500,\n busyTimeout: options.busyTimeout ?? 5_000,\n observationPollInterval: options.observationPollInterval ?? 25,\n verifyOnOpen: options.verifyOnOpen ?? false,\n }).pipe(\n Effect.mapError((error) =>\n NodePlatformConfigError.make({\n message: `Invalid Node durable runtime configuration: ${error.message}`,\n cause: error,\n }),\n ),\n );\n\n/** SQLite storage configuration derived from the single validated Node configuration. */\nconst sqliteStorageConfigLayer: Layer.Layer<SqliteStorageConfig, never, NodeDurableRuntimeConfig> =\n Layer.effect(SqliteStorageConfig)(\n Effect.gen(function* () {\n const config = yield* NodeDurableRuntimeConfig;\n return SqliteStorageConfigValue.make({\n observationPollInterval: config.observationPollInterval,\n busyTimeout: config.busyTimeout,\n ownershipLeaseDuration: config.ownershipLeaseDuration,\n verifyOnOpen: config.verifyOnOpen,\n });\n }),\n );\n\n/** Thread coordinator configuration derived from the single validated Node configuration. */\nconst durableRuntimeConfigLayer = (\n estimateCostMicrousd: RunCostEstimator | undefined,\n): Layer.Layer<DurableRuntimeConfig, never, NodeDurableRuntimeConfig> =>\n Layer.effect(DurableRuntimeConfig)(\n Effect.gen(function* () {\n const config = yield* NodeDurableRuntimeConfig;\n return DurableRuntimeConfig.make({\n deploymentId: config.deploymentId,\n producerId: config.producerId,\n settlementPollInterval: Duration.millis(config.settlementPollInterval),\n leaseRenewalInterval: Duration.millis(config.leaseRenewalInterval),\n abortPollInterval: Duration.millis(config.abortPollInterval),\n ...(estimateCostMicrousd === undefined ? {} : { estimateCostMicrousd }),\n });\n }),\n );\n\n/** Wake fallback-scan cadence derived from the single validated Node configuration. */\nconst wakeSchedulerConfigLayer: Layer.Layer<\n NodeWakeSchedulerConfig,\n never,\n NodeDurableRuntimeConfig\n> = Layer.effect(NodeWakeSchedulerConfig)(\n Effect.gen(function* () {\n const config = yield* NodeDurableRuntimeConfig;\n return { scanInterval: Duration.millis(config.wakeScanInterval) };\n }),\n);\n\nconst releaseTrackedOwnership = (\n ledger: SubmissionLedger[\"Service\"],\n registry: Ref.Ref<ReadonlyMap<SubmissionId, OwnershipToken>>,\n): Effect.Effect<void> =>\n Effect.gen(function* () {\n const tracked = yield* Ref.getAndSet(registry, new Map<SubmissionId, OwnershipToken>());\n for (const [submissionId, ownershipToken] of tracked) {\n yield* ledger\n .releaseOwnership(ReleaseOwnershipRequest.make({ submissionId, ownershipToken }))\n .pipe(\n Effect.catchTags({\n // A newer epoch already owns (or settled) the lane: nothing left to drain.\n OwnershipLost: () => Effect.void,\n // Drain is best-effort by design: the lease still expires and the durability protocol,\n // not graceful shutdown, provides correctness (DEPLOY-006).\n LedgerError: (error) =>\n Effect.logWarning(\"Ownership drain failed; the lease will expire instead\", error),\n }),\n );\n }\n });\n\n/**\n * Shutdown-drain decorator for a `SubmissionLedger` (deployment §6 step 6): every ownership\n * period granted through this Layer is tracked — claims start tracking, renewals follow token\n * rotation, releases and settlement finalizations stop it — and every ownership still held when\n * the Layer's Scope closes is released so another host can claim the lane immediately instead of\n * waiting for lease expiry. The drain is a liveness courtesy only; producer-epoch fencing remains\n * the correctness authority (DUR-006), and a forced kill simply falls back to lease expiry.\n */\nexport const ownershipDrainLayer: Layer.Layer<SubmissionLedger, never, SubmissionLedger> =\n Layer.effect(SubmissionLedger)(\n Effect.gen(function* () {\n const ledger = yield* SubmissionLedger;\n const registry = yield* Ref.make<ReadonlyMap<SubmissionId, OwnershipToken>>(\n new Map<SubmissionId, OwnershipToken>(),\n );\n\n const track = (submissionId: SubmissionId, ownershipToken: OwnershipToken) =>\n Ref.update(registry, (tracked) => new Map(tracked).set(submissionId, ownershipToken));\n const untrack = (submissionId: SubmissionId) =>\n Ref.update(registry, (tracked) => {\n const next = new Map(tracked);\n next.delete(submissionId);\n return next;\n });\n\n yield* Effect.addFinalizer(() => releaseTrackedOwnership(ledger, registry));\n\n return SubmissionLedger.of({\n capabilities: ledger.capabilities,\n admit: ledger.admit,\n markReady: ledger.markReady,\n lookup: ledger.lookup,\n // The S2 subagent ops forward untouched: none of them grants an ownership period, so\n // the drain has nothing to track for them (`suspend` below already stops tracking the\n // waitingForChild ownership period the moment it ends).\n resolveAdmission: ledger.resolveAdmission,\n recordChildSettled: ledger.recordChildSettled,\n reserveChildBudget: ledger.reserveChildBudget,\n attachChildToReservation: ledger.attachChildToReservation,\n beginChildBudgetRelease: ledger.beginChildBudgetRelease,\n releaseChildBudget: ledger.releaseChildBudget,\n claim: (request) =>\n ledger\n .claim(request)\n .pipe(\n Effect.tap((claimed) =>\n claimed._tag === \"Some\"\n ? track(claimed.value.submissionId, claimed.value.ownershipToken)\n : Effect.void,\n ),\n ),\n renewOwnership: (request) =>\n ledger.renewOwnership(request).pipe(\n Effect.tap((renewal) => track(request.submissionId, renewal.ownershipToken)),\n Effect.tapError((error) =>\n error._tag === \"OwnershipLost\" ? untrack(request.submissionId) : Effect.void,\n ),\n ),\n releaseOwnership: (request) =>\n ledger.releaseOwnership(request).pipe(\n Effect.tap(() => untrack(request.submissionId)),\n Effect.tapError((error) =>\n error._tag === \"OwnershipLost\" ? untrack(request.submissionId) : Effect.void,\n ),\n ),\n markInputApplied: ledger.markInputApplied,\n reserveSettlement: ledger.reserveSettlement,\n finalizeSettlement: (request) =>\n ledger.finalizeSettlement(request).pipe(Effect.tap(() => untrack(request.submissionId))),\n requestAbort: ledger.requestAbort,\n claimJoining: ledger.claimJoining,\n markJoined: ledger.markJoined,\n revertJoining: ledger.revertJoining,\n // Suspension ends the ownership period by contract, so the drain stops tracking it.\n suspend: (request) =>\n ledger.suspend(request).pipe(Effect.tap(() => untrack(request.submissionId))),\n recordApprovalDecision: ledger.recordApprovalDecision,\n markUnknown: ledger.markUnknown,\n recordUnknownResolution: ledger.recordUnknownResolution,\n scanNonterminal: ledger.scanNonterminal,\n loadRecoverySnapshot: ledger.loadRecoverySnapshot,\n });\n }),\n );\n\n/**\n * The DN Layer assembly (deployment §12: a Layer-assembly library, not an app entrypoint).\n * `layer(options)` decodes the configuration, opens ONE SQLite database serving both the\n * Thread Log and the Submission Ledger (so claims fence the same producer epochs), wires\n * the Node wake scheduler with its ledger-scan fallback, wraps the ledger with the shutdown\n * ownership drain, defaults the Tool reconciliation policy to the fail-closed\n * `ToolReconciler.uncertain` (override via `options.toolReconciler`), and provides a ready\n * `DurableAgentRuntime` on top. Storage compatibility is\n * verified during construction: an incompatible database file fails the Layer with\n * `SqliteStorageCompatibilityError` before anything is mutated (DEPLOY-008).\n */\nexport class NodeDurableRuntime {\n /** Validated configuration Layer; fails typed when the supplied options are out of bounds. */\n static configLayer<\n ContextError = never,\n ContextRequirements = never,\n AuthorizationError = never,\n AuthorizationRequirements = never,\n >(\n options: NodeDurableRuntimeOptions<\n ContextError,\n ContextRequirements,\n AuthorizationError,\n AuthorizationRequirements\n >,\n ): Layer.Layer<NodeDurableRuntimeConfig, NodePlatformConfigError> {\n return Layer.effect(NodeDurableRuntimeConfig)(configFromOptions(options));\n }\n\n /** The full DN runtime stack over one SQLite file. */\n static layer<\n ContextError = never,\n ContextRequirements = never,\n AuthorizationError = never,\n AuthorizationRequirements = never,\n >(\n options: NodeDurableRuntimeOptions<\n ContextError,\n ContextRequirements,\n AuthorizationError,\n AuthorizationRequirements\n >,\n ): Layer.Layer<\n NodeDurableRuntimeServices,\n NodeDurableRuntimeInitializationError | ContextError | AuthorizationError,\n Exclude<ContextRequirements | AuthorizationRequirements, Crypto.Crypto>\n > {\n return Layer.unwrap(\n Effect.map(configFromOptions(options), (config) => {\n const nodeConfigLayer = Layer.succeed(NodeDurableRuntimeConfig)(config);\n const infrastructure = Layer.mergeAll(\n sqliteStorageConfigLayer,\n storageFailpointLayer({\n filename: config.filename,\n failpoint: options.storageFailpoint,\n }),\n SqliteClient.layer({ filename: config.filename }),\n NodeCrypto.layer,\n );\n const runtimeFailpointLayer =\n options.runtimeFailpoint === undefined\n ? DurableRuntimeFailpoint.layer\n : Layer.succeed(DurableRuntimeFailpoint)({ hit: options.runtimeFailpoint });\n const reconcilerLayer = options.toolReconciler ?? ToolReconciler.uncertain;\n const observerLayer =\n options.toolFailureObserver === undefined\n ? Layer.succeed(CurrentToolFailureObserver)(undefined)\n : toolFailureObserverLayer(options.toolFailureObserver);\n const ports = Layer.mergeAll(\n threadStoreLayer,\n scheduleStoreLayer,\n nodeWakeSchedulerLayer.pipe(\n Layer.provideMerge(ownershipDrainLayer.pipe(Layer.provide(submissionLedgerLayer))),\n ),\n );\n return DurableAgentRuntime.layerWithServices.pipe(\n Layer.provideMerge(\n Layer.mergeAll(ports, durableRuntimeConfigLayer(options.estimateCostMicrousd)),\n ),\n Layer.provide(\n Layer.mergeAll(\n wakeSchedulerConfigLayer,\n runtimeFailpointLayer,\n reconcilerLayer,\n observerLayer,\n ),\n ),\n Layer.provideMerge(infrastructure),\n Layer.provideMerge(nodeConfigLayer),\n Layer.provide(\n Layer.mergeAll(\n options.runContext ?? RunContextPreparationPassthrough,\n options.toolAuthorization ?? RunToolAuthorization.allowAll,\n ).pipe(Layer.provide(NodeCrypto.layer)),\n ),\n );\n }),\n );\n }\n}\n","import type { ThreadId, SubmissionId } from \"@effect-agent/core\";\nimport {\n DurableAgentRuntime,\n type AbortCommand,\n type AbortIntent,\n type CanonicalRecordEnvelope,\n type ThreadNotMaterialized,\n type ThreadStoreError,\n type DurableAbortFailure,\n type DurableAwaitFailure,\n type ResolvedBinding,\n type DurableBindingFailure,\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 IntegrityReport,\n type ObligationReport,\n type ObligationThresholds,\n type OperationDenied,\n type Receipt,\n type RecoveryExplanation,\n type RecoveryReport,\n type RetryCommand,\n type Settlement,\n} from \"@effect-agent/thread\";\nimport type { Stream } from \"effect\";\nimport { Context, type Crypto, Effect, Layer, Ref, Schema } from \"effect\";\n\nimport {\n NodeDurableRuntime,\n NodeDurableRuntimeConfig,\n type NodeDurableRuntimeInitializationError,\n type NodeDurableRuntimeOptions,\n type NodeDurableRuntimeServices,\n} from \"./layers.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 = (bindings: ReadonlyArray<ResolvedBinding>) =>\n Effect.gen(function* () {\n const runtime = yield* DurableAgentRuntime;\n const config = yield* NodeDurableRuntimeConfig;\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 // Shutdown step 1 (DEPLOY-005): admission closes before the ownership drain in the runtime\n // Layer below releases claims and before the stores close in reverse acquisition order.\n yield* Effect.addFinalizer(() => Ref.set(admission, false));\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 runWorkers = <A, E, R>(worker: Effect.Effect<A, E, R>): Effect.Effect<void, E, R> =>\n Effect.forEach(\n Array.from({ length: config.workerConcurrency }, (_, index) => index),\n () => worker,\n { concurrency: \"unbounded\", discard: true },\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(bindings));\n\n return NodeDurableHost.of({\n startupRecovery,\n admissionOpen: Ref.get(admission),\n submit,\n awaitSettlement: runtime.awaitSettlement,\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 runResolvedWorkers,\n });\n });\n\n/**\n * Operational host lifecycle for the DN runtime (deployment §2/§5/§6).\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 /** `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 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 * bound is the validated finite configuration value; 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 */\n readonly runResolvedWorkers: Effect.Effect<void, DurableWorkerFailure | DurableBindingFailure>;\n }\n>()(\"@effect-agent/platform-node/NodeDurableHost\") {\n /**\n * Host gates over an assembled `NodeDurableRuntime` stack. Bindings must carry the exact\n * digests stored by submitters. Omission registers no Agents, so resolved work fails closed.\n */\n static readonly layer = (\n bindings: ReadonlyArray<ResolvedBinding> = [],\n ): Layer.Layer<\n NodeDurableHost,\n DurableWorkerFailure,\n DurableAgentRuntime | NodeDurableRuntimeConfig\n > => Layer.effect(NodeDurableHost)(makeHost(bindings));\n\n /** The complete DN host: `NodeDurableRuntime.layer(options)` plus the host lifecycle gates. */\n static layerStack<\n ContextError = never,\n ContextRequirements = never,\n AuthorizationError = never,\n AuthorizationRequirements = never,\n >(\n options: NodeDurableRuntimeOptions<\n ContextError,\n ContextRequirements,\n AuthorizationError,\n AuthorizationRequirements\n > & { readonly bindings?: ReadonlyArray<ResolvedBinding> },\n ): Layer.Layer<\n NodeDurableHost | NodeDurableRuntimeServices,\n | DurableWorkerFailure\n | NodeDurableRuntimeInitializationError\n | ContextError\n | AuthorizationError,\n Exclude<ContextRequirements | AuthorizationRequirements, Crypto.Crypto>\n > {\n const { bindings = [], ...runtimeOptions } = options;\n return NodeDurableHost.layer(bindings).pipe(\n Layer.provideMerge(NodeDurableRuntime.layer(runtimeOptions)),\n );\n }\n}\n","import type { AgentId } from \"@effect-agent/core\";\nimport {\n type DurableSubmitAgent,\n type EventSources,\n type SubscriptionInputBindings,\n PersistedJson,\n type PreparedInput,\n PreparedInputAdmission,\n type ScheduledEnvelope,\n ScheduledInputAdmission,\n ScheduledInputRetryable,\n type SubscriptionAuthorizer,\n SubscriptionDriver,\n type SubscriptionError,\n SubscriptionIntake,\n type SubscriptionLimits,\n type SubscriptionStoreFailure,\n SubscriptionStore,\n Subscriptions,\n defaultSubscriptionLimits,\n ScheduleStorageError,\n} from \"@effect-agent/thread\";\nimport { NodeCrypto } from \"@effect/platform-node\";\nimport { Cause, Duration, Effect, Exit, Layer, Option } from \"effect\";\n\nimport { NodeDurableHost } from \"./host.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/** Ordinary prepared admission through the Scope-owned Node host gate. */\nexport const nodePreparedInputAdmissionLayer: Layer.Layer<\n PreparedInputAdmission,\n never,\n NodeDurableHost\n> = Layer.effect(\n PreparedInputAdmission,\n Effect.gen(function* () {\n const host = yield* NodeDurableHost;\n return PreparedInputAdmission.of({\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 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 LedgerError: () => Effect.fail(ambiguous()),\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);\n\nconst preparedFromSchedule = (envelope: ScheduledEnvelope): PreparedInput => ({\n schemaVersion: 1,\n threadId: envelope.threadId,\n deliveryPrincipal: envelope.deliveryPrincipal,\n agentId: envelope.agentId,\n definitions: envelope.definitions,\n input: envelope.input,\n inputDigest: envelope.inputDigest,\n admissionKey: envelope.admissionKey,\n authorization: envelope.authorization,\n});\n\n/** Compatibility adapter retaining the public scheduling admission port. */\nconst nodeScheduledInputAdmissionFromPreparedLayer: Layer.Layer<\n ScheduledInputAdmission,\n never,\n PreparedInputAdmission\n> = Layer.effect(\n ScheduledInputAdmission,\n Effect.map(PreparedInputAdmission, (admission) =>\n ScheduledInputAdmission.of({\n submit: (envelope) => admission.submit(preparedFromSchedule(envelope)),\n }),\n ),\n);\n\nexport const nodeScheduledInputAdmissionLayer: Layer.Layer<\n ScheduledInputAdmission,\n never,\n NodeDurableHost\n> = nodeScheduledInputAdmissionFromPreparedLayer.pipe(\n Layer.provide(nodePreparedInputAdmissionLayer),\n);\n\nconst reportPassFailure = (cause: Cause.Cause<SubscriptionStoreFailure>): Effect.Effect<boolean> =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.interrupt\n : Effect.logWarning(\"Node subscription pass failed\").pipe(\n Effect.annotateLogs({\n failureTag: Option.match(Cause.findErrorOption(cause), {\n onNone: () => \"Defect\",\n onSome: (error) => error._tag,\n }),\n }),\n Effect.as(false),\n );\n\nconst nodeSubscriptionDriverLayer = (\n limits: SubscriptionLimits,\n): Layer.Layer<never, never, SubscriptionDriver | SubscriptionStore> =>\n Layer.effectDiscard(\n Effect.gen(function* () {\n const driver = yield* SubscriptionDriver;\n const store = yield* SubscriptionStore;\n\n const run = Effect.gen(function* () {\n while (true) {\n const passSucceeded = yield* driver.runDue.pipe(\n Effect.map((pass) => pass.failed === 0),\n Effect.catchCause(reportPassFailure),\n );\n\n if (!passSucceeded) {\n yield* Effect.sleep(Duration.millis(limits.retryMillis));\n continue;\n }\n\n const deadline = yield* store.nextDeadline.pipe(Effect.exit);\n if (Exit.isFailure(deadline)) {\n yield* reportPassFailure(deadline.cause);\n yield* Effect.sleep(Duration.millis(limits.retryMillis));\n continue;\n }\n\n const nowMillis = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n const delay =\n deadline.value === null\n ? limits.retryMillis\n : Math.max(1, Math.min(deadline.value - nowMillis, limits.retryMillis));\n yield* Effect.sleep(Duration.millis(delay));\n }\n });\n\n yield* Effect.forkScoped(run);\n }),\n );\n\nexport interface NodeSubscriptionsOptions {\n readonly limits?: SubscriptionLimits | undefined;\n}\n\n/**\n * One Scope-owned subscription partition in the sole process owning its SQLite database.\n * Indexed polling repairs restart and lost wake state; closing the Scope interrupts the driver.\n */\nexport class NodeSubscriptions {\n static layer(\n options: NodeSubscriptionsOptions = {},\n ): Layer.Layer<\n Subscriptions | SubscriptionIntake,\n SubscriptionError,\n | NodeDurableHost\n | SubscriptionStore\n | SubscriptionAuthorizer\n | EventSources\n | SubscriptionInputBindings\n > {\n const limits = options.limits ?? defaultSubscriptionLimits;\n const publicServices = Layer.merge(\n Subscriptions.layer(limits),\n SubscriptionIntake.layer(limits),\n );\n const driver = nodeSubscriptionDriverLayer(limits).pipe(\n Layer.provide(SubscriptionDriver.layer(limits)),\n );\n return Layer.merge(publicServices, driver).pipe(\n Layer.provide(nodePreparedInputAdmissionLayer),\n Layer.provide(NodeCrypto.layer),\n );\n }\n}\n","import {\n type ScheduleProcessFailure,\n type ScheduleAuthorizer,\n type SchedulingLimits,\n ScheduleStorageError,\n ScheduleStore,\n type ScheduleValidationError,\n ScheduleWake,\n Scheduling,\n ScheduleDriver,\n defaultSchedulingLimits,\n} from \"@effect-agent/thread\";\nimport { NodeCrypto } from \"@effect/platform-node\";\nimport { Cause, Duration, Effect, Layer, Option, PubSub, Result } from \"effect\";\n\nimport type { NodeDurableHost } from \"./host.ts\";\nimport { nodeScheduledInputAdmissionLayer } from \"./subscriptions.ts\";\n\n/** One bounded hint slot for the single supported Node scheduler. Indexed polling repairs loss. */\nexport const nodeScheduleWakeLayer: Layer.Layer<ScheduleWake> = Layer.effect(\n ScheduleWake,\n Effect.gen(function* () {\n const hints = yield* PubSub.sliding<void>(1);\n const subscription = yield* PubSub.subscribe(hints);\n yield* Effect.addFinalizer(() => PubSub.shutdown(hints));\n return ScheduleWake.of({\n notify: PubSub.publish(hints, undefined).pipe(Effect.asVoid),\n await: PubSub.take(subscription),\n });\n }),\n);\n\nconst reportPassFailure = (cause: Cause.Cause<ScheduleProcessFailure>): Effect.Effect<boolean> =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.interrupt\n : Effect.logWarning(\"Node scheduling pass failed\").pipe(\n Effect.annotateLogs({\n failureTag: Option.match(Cause.findErrorOption(cause), {\n onNone: () => \"Defect\",\n onSome: (error) => error._tag,\n }),\n }),\n Effect.as(false),\n );\n\nconst nodeSchedulingDriverLayer = (\n limits: SchedulingLimits,\n): Layer.Layer<never, never, ScheduleDriver | ScheduleStore | ScheduleWake> =>\n Layer.effectDiscard(\n Effect.gen(function* () {\n const scheduling = yield* ScheduleDriver;\n const store = yield* ScheduleStore;\n const wake = yield* ScheduleWake;\n\n const run = Effect.gen(function* () {\n while (true) {\n const passSucceeded = yield* scheduling.runDue().pipe(\n Effect.map((pass) => pass.failed === 0),\n Effect.catchCause(reportPassFailure),\n );\n const deadlineResult = passSucceeded\n ? yield* store.nextDeadline().pipe(Effect.result)\n : Result.fail(\n ScheduleStorageError.make({ operation: \"driver pass\", reason: \"unavailable\" }),\n );\n if (Result.isFailure(deadlineResult) && passSucceeded) {\n yield* Effect.logWarning(\"Node scheduling deadline query failed\");\n }\n const nowMillis = yield* Effect.clockWith((clock) => clock.currentTimeMillis);\n const deadlineDelay =\n Result.isSuccess(deadlineResult) && deadlineResult.success !== null\n ? Math.max(0, deadlineResult.success - nowMillis)\n : limits.recoveryPollMillis;\n const delay = Math.min(deadlineDelay, limits.recoveryPollMillis);\n yield* Effect.raceFirst(wake.await, Effect.sleep(Duration.millis(delay)));\n }\n });\n\n yield* Effect.forkScoped(run);\n }),\n );\n\nexport interface NodeSchedulingOptions {\n readonly limits?: SchedulingLimits | undefined;\n}\n\n/**\n * Optional Scope-owned Node scheduling service and driver. The caller must provide the existing\n * host, its SQLite ScheduleStore, and an explicit ScheduleAuthorizer.\n */\nexport class NodeScheduling {\n static layer(\n options: NodeSchedulingOptions = {},\n ): Layer.Layer<\n Scheduling,\n ScheduleValidationError,\n NodeDurableHost | ScheduleStore | ScheduleAuthorizer\n > {\n const limits = options.limits ?? defaultSchedulingLimits;\n const schedulingWithDriver = nodeSchedulingDriverLayer(limits).pipe(\n Layer.provide(ScheduleDriver.layer(limits)),\n Layer.merge(Scheduling.layer(limits)),\n );\n return schedulingWithDriver.pipe(\n Layer.provide(\n Layer.mergeAll(nodeScheduledInputAdmissionLayer, nodeScheduleWakeLayer, NodeCrypto.layer),\n ),\n );\n }\n}\n"],"mappings":";;;;;;;;;;;AASA,MAAM,uBAAuB;;AAG7B,IAAa,0BAAb,MAAa,gCAAgC,QAAQ,QAMnD,CAAC,CAAC,qDAAqD,CAAC,CAAC;CACzD,OAAO,MAAM,SAE4B;EACvC,OAAO,MAAM,QAAQ,uBAAuB,CAAC,CAAC,EAAE,cAAc,QAAQ,aAAa,CAAC;CACtF;AACF;AAEA,MAAM,oBAAoB,OAAO,IAAI,aAAa;CAChD,MAAM,SAAS,OAAO;CACtB,MAAM,SAAS,OAAO;CACtB,MAAM,QAAQ,OAAO,OAAO,QAAkB,oBAAoB;CAClE,MAAM,WAAW,OAAO;CACxB,OAAO,OAAO,mBAAmB,OAAO,SAAS,KAAK,CAAC;;;;;;CAOvD,MAAM,WAAmD,OAAO,WAC9D,OAAO,eACT,CAAC,CAAC,KACA,OAAO,KAAK,cAAc;EACxB,MAAM,wBAAQ,IAAI,IAAc;EAChC,KAAK,MAAM,YAAY,WACrB,MAAM,IAAI,SAAS,QAAQ;EAE7B,OAAO,CAAC,GAAG,KAAK;CAClB,CAAC,GACD,OAAO,OAAO,UACZ,OAAO,WAAW,0CAA0C,KAAK,CAAC,CAAC,KACjE,OAAO,GAAG,CAAC,CAA4B,CACzC,CACF,CACF;;;;;;CAOA,MAAM,gBAAyC,OAAO,yBACpD,OAAO,MAAM,OAAO,YAAY,CAAC,CAAC,KAAK,OAAO,QAAQ,QAAQ,CAAC,CACjE;CAEA,OAAO,cAAc,GAAG;EACtB,SAAS,aACP,SACG,OAAO,QAAQ,CAAC,CAChB,KAAK,OAAO,QAAQ,OAAO,QAAQ,OAAO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Y,OAC3D,KAAK,IAAI,GAAG,eAAe,UAAU,SAAS,IAC9C,OAAO;GACb,MAAM,QAAQ,KAAK,IAAI,eAAe,OAAO,kBAAkB;GAC/D,OAAO,OAAO,UAAU,KAAK,OAAO,OAAO,MAAM,SAAS,OAAO,KAAK,CAAC,CAAC;EAC1E;CACF,CAAC;CAED,OAAO,OAAO,WAAW,GAAG;AAC9B,CAAC,CACH;;;;;AAUF,IAAa,iBAAb,MAA4B;CAC1B,OAAO,MACL,UAAiC,CAAC,GAKlC;EACA,MAAM,SAAS,QAAQ,UAAU;EAKjC,OAJ6B,0BAA0B,MAAM,CAAC,CAAC,KAC7D,MAAM,QAAQ,eAAe,MAAM,MAAM,CAAC,GAC1C,MAAM,MAAM,WAAW,MAAM,MAAM,CAAC,CAEZ,CAAC,CAAC,KAC1B,MAAM,QACJ,MAAM,SAAS,kCAAkC,uBAAuB,WAAW,KAAK,CAC1F,CACF;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@effect-agent/platform-node",
3
- "version": "0.1.0-beta.37",
3
+ "version": "0.1.0-beta.39",
4
4
  "exports": {
5
5
  ".": {
6
6
  "types": "./dist/index.d.mts",
@@ -8,13 +8,15 @@
8
8
  }
9
9
  },
10
10
  "dependencies": {
11
- "@effect-agent/core": "0.1.0-beta.37",
12
- "@effect-agent/engine": "0.1.0-beta.37",
13
- "@effect-agent/session": "0.1.0-beta.37",
14
- "@effect-agent/storage-sqlite": "0.1.0-beta.37",
11
+ "@effect-agent/core": "0.1.0-beta.39",
12
+ "@effect-agent/engine": "0.1.0-beta.39",
13
+ "@effect-agent/storage-sqlite": "0.1.0-beta.39",
14
+ "@effect-agent/thread": "0.1.0-beta.39",
15
15
  "@effect/platform-node": "4.0.0-rc.111",
16
- "@effect/sql-sqlite-node": "4.0.0-rc.111",
17
- "effect": "4.0.0-rc.111"
16
+ "@effect/sql-sqlite-node": "4.0.0-rc.111"
17
+ },
18
+ "peerDependencies": {
19
+ "effect": "^4.0.0-rc.111"
18
20
  },
19
21
  "description": "Class DN layer assembly for Effect Agent: the durable Node/SQLite runtime host, wake scheduler, and ownership drain.",
20
22
  "license": "MIT",
@@ -37,8 +39,9 @@
37
39
  "test": "vp test --passWithNoTests"
38
40
  },
39
41
  "devDependencies": {
40
- "@effect-agent/capabilities": "0.1.0-beta.35",
42
+ "@effect-agent/capabilities": "0.1.0-beta.38",
41
43
  "@effect/vitest": "4.0.0-rc.111",
44
+ "effect": "4.0.0-rc.111",
42
45
  "typescript": "7.0.2",
43
46
  "vite-plus": "0.2.6"
44
47
  }
package/src/host.ts CHANGED
@@ -1,14 +1,14 @@
1
- import type { ConversationId, SubmissionId } from "@effect-agent/core";
1
+ import type { ThreadId, SubmissionId } from "@effect-agent/core";
2
2
  import {
3
- AgentBindingResolver,
4
3
  DurableAgentRuntime,
5
4
  type AbortCommand,
6
5
  type AbortIntent,
7
6
  type CanonicalRecordEnvelope,
8
- type ConversationNotMaterialized,
9
- type ConversationStoreError,
7
+ type ThreadNotMaterialized,
8
+ type ThreadStoreError,
10
9
  type DurableAbortFailure,
11
10
  type DurableAwaitFailure,
11
+ type ResolvedBinding,
12
12
  type DurableBindingFailure,
13
13
  type DurableExplainFailure,
14
14
  type DurableObserveOptions,
@@ -28,8 +28,9 @@ import {
28
28
  type RecoveryReport,
29
29
  type RetryCommand,
30
30
  type Settlement,
31
- } from "@effect-agent/session";
32
- import { Context, Effect, Layer, Ref, Schema, Stream } from "effect";
31
+ } from "@effect-agent/thread";
32
+ import type { Stream } from "effect";
33
+ import { Context, type Crypto, Effect, Layer, Ref, Schema } from "effect";
33
34
 
34
35
  import {
35
36
  NodeDurableRuntime,
@@ -47,76 +48,74 @@ export class AdmissionClosed extends Schema.TaggedError<AdmissionClosed>()("Admi
47
48
  message: Schema.String,
48
49
  }) {}
49
50
 
50
- const makeHost = Effect.gen(function* () {
51
- const runtime = yield* DurableAgentRuntime;
52
- const config = yield* NodeDurableRuntimeConfig;
53
- const bindingResolver = yield* AgentBindingResolver;
51
+ const makeHost = (bindings: ReadonlyArray<ResolvedBinding>) =>
52
+ Effect.gen(function* () {
53
+ const runtime = yield* DurableAgentRuntime;
54
+ const config = yield* NodeDurableRuntimeConfig;
54
55
 
55
- // Startup gate (deployment §5, plan §host): configuration decoding and storage compatibility
56
- // already gated this Layer's dependencies; the last gate before admission opens is recovering
57
- // EVERY nonterminal Submission. Work needing a live Agent Binding is reported `deferred` and
58
- // stays a visible obligation for `runWorkers`; lanes durably blocked on an Unknown Outcome are
59
- // reported `unknown` and wait for the authorized `resolveUnknown` path (DUR-017) — they consume
60
- // no worker permit while the settlement obligation stays owed.
61
- const startupRecovery = yield* runtime.runRecovery;
56
+ // Startup gate (deployment §5, plan §host): configuration decoding and storage compatibility
57
+ // already gated this Layer's dependencies; the last gate before admission opens is recovering
58
+ // EVERY nonterminal Submission. Work needing a live Agent Binding is reported `deferred` and
59
+ // stays a visible obligation for `runWorkers`; lanes durably blocked on an Unknown Outcome are
60
+ // reported `unknown` and wait for the authorized `resolveUnknown` path (DUR-017) — they consume
61
+ // no worker permit while the settlement obligation stays owed.
62
+ const startupRecovery = yield* runtime.runRecovery;
62
63
 
63
- const admission = yield* Ref.make(true);
64
- // Shutdown step 1 (DEPLOY-005): admission closes before the ownership drain in the runtime
65
- // Layer below releases claims and before the stores close in reverse acquisition order.
66
- yield* Effect.addFinalizer(() => Ref.set(admission, false));
64
+ const admission = yield* Ref.make(true);
65
+ // Shutdown step 1 (DEPLOY-005): admission closes before the ownership drain in the runtime
66
+ // Layer below releases claims and before the stores close in reverse acquisition order.
67
+ yield* Effect.addFinalizer(() => Ref.set(admission, false));
67
68
 
68
- const requireAdmission: Effect.Effect<void, AdmissionClosed> = Ref.get(admission).pipe(
69
- Effect.flatMap((open) =>
70
- open
71
- ? Effect.void
72
- : Effect.fail(
73
- AdmissionClosed.make({ message: "The host is shutting down; admission is closed." }),
74
- ),
75
- ),
76
- );
69
+ const requireAdmission: Effect.Effect<void, AdmissionClosed> = Ref.get(admission).pipe(
70
+ Effect.flatMap((open) =>
71
+ open
72
+ ? Effect.void
73
+ : Effect.fail(
74
+ AdmissionClosed.make({ message: "The host is shutting down; admission is closed." }),
75
+ ),
76
+ ),
77
+ );
77
78
 
78
- const submit = <InputSchema extends Schema.Top>(
79
- agent: DurableSubmitAgent<InputSchema>,
80
- input: InputSchema["Type"],
81
- options: DurableSubmitOptions,
82
- ): Effect.Effect<
83
- Receipt,
84
- AdmissionClosed | DurableSubmitFailure,
85
- InputSchema["EncodingServices"]
86
- > => requireAdmission.pipe(Effect.andThen(runtime.submit(agent, input, options)));
79
+ const submit = <InputSchema extends Schema.Top>(
80
+ agent: DurableSubmitAgent<InputSchema>,
81
+ input: InputSchema["Type"],
82
+ options: DurableSubmitOptions,
83
+ ): Effect.Effect<
84
+ Receipt,
85
+ AdmissionClosed | DurableSubmitFailure,
86
+ InputSchema["EncodingServices"]
87
+ > => requireAdmission.pipe(Effect.andThen(runtime.submit(agent, input, options)));
87
88
 
88
- const runWorkers = <A, E, R>(worker: Effect.Effect<A, E, R>): Effect.Effect<void, E, R> =>
89
- Effect.forEach(
90
- Array.from({ length: config.workerConcurrency }, (_, index) => index),
91
- () => worker,
92
- { concurrency: "unbounded", discard: true },
93
- );
89
+ const runWorkers = <A, E, R>(worker: Effect.Effect<A, E, R>): Effect.Effect<void, E, R> =>
90
+ Effect.forEach(
91
+ Array.from({ length: config.workerConcurrency }, (_, index) => index),
92
+ () => worker,
93
+ { concurrency: "unbounded", discard: true },
94
+ );
94
95
 
95
- // S2 multi-binding pool: every claimed head resolves its exact registered Binding through
96
- // the host's `AgentBindingResolver` (`NodeDurableRuntimeOptions.bindings`), so ONE bounded
97
- // pool serves parent and child lanes — the spec §12 smallest-pool suspension/wakeup proof
98
- // runs `workerConcurrency: 1` over exactly this loop.
99
- const runResolvedWorkers = runWorkers(
100
- runtime.runResolvedWorker.pipe(Effect.provideService(AgentBindingResolver, bindingResolver)),
101
- );
96
+ // S2 multi-binding pool: every claimed head resolves its exact registered Binding through
97
+ // the host's exact registrations, so one bounded
98
+ // pool serves parent and child lanes — the spec §12 smallest-pool suspension/wakeup proof
99
+ // runs `workerConcurrency: 1` over exactly this loop.
100
+ const runResolvedWorkers = runWorkers(runtime.runResolvedWorker(bindings));
102
101
 
103
- return NodeDurableHost.of({
104
- startupRecovery,
105
- admissionOpen: Ref.get(admission),
106
- submit,
107
- awaitSettlement: runtime.awaitSettlement,
108
- observe: runtime.observe,
109
- abort: runtime.abort,
110
- explain: runtime.explain,
111
- explainConversation: runtime.explainConversation,
112
- verify: runtime.verify,
113
- retry: runtime.retry,
114
- wake: runtime.wake,
115
- scanObligations: runtime.scanObligations,
116
- runWorkers,
117
- runResolvedWorkers,
102
+ return NodeDurableHost.of({
103
+ startupRecovery,
104
+ admissionOpen: Ref.get(admission),
105
+ submit,
106
+ awaitSettlement: runtime.awaitSettlement,
107
+ observe: runtime.observe,
108
+ abort: runtime.abort,
109
+ explain: runtime.explain,
110
+ explainThread: runtime.explainThread,
111
+ verify: runtime.verify,
112
+ retry: runtime.retry,
113
+ wake: runtime.wake,
114
+ scanObligations: runtime.scanObligations,
115
+ runWorkers,
116
+ runResolvedWorkers,
117
+ });
118
118
  });
119
- });
120
119
 
121
120
  /**
122
121
  * Operational host lifecycle for the DN runtime (deployment §2/§5/§6).
@@ -159,25 +158,23 @@ export class NodeDurableHost extends Context.Service<
159
158
  options?: DurableObserveOptions,
160
159
  ) => Stream.Stream<
161
160
  CanonicalRecordEnvelope,
162
- ConversationStoreError | ConversationNotMaterialized | OperationDenied
161
+ ThreadStoreError | ThreadNotMaterialized | OperationDenied
163
162
  >;
164
163
  readonly abort: (command: AbortCommand) => Effect.Effect<AbortIntent, DurableAbortFailure>;
165
164
  /** `DurableAgentRuntime.explain` — read-only recovery explanation of one Submission (P7). */
166
165
  readonly explain: (
167
166
  submissionId: SubmissionId,
168
167
  ) => Effect.Effect<RecoveryExplanation, DurableExplainFailure>;
169
- /** `DurableAgentRuntime.explainConversation` — explain every nonterminal lane member. */
170
- readonly explainConversation: (
171
- conversationId: ConversationId,
168
+ /** `DurableAgentRuntime.explainThread` — explain every nonterminal lane member. */
169
+ readonly explainThread: (
170
+ threadId: ThreadId,
172
171
  ) => Effect.Effect<ReadonlyArray<RecoveryExplanation>, DurableExplainFailure>;
173
172
  /** `DurableAgentRuntime.verify` — read-only integrity checks, never a repair (P7). */
174
- readonly verify: (
175
- conversationId: ConversationId,
176
- ) => Effect.Effect<IntegrityReport, DurableVerifyFailure>;
173
+ readonly verify: (threadId: ThreadId) => Effect.Effect<IntegrityReport, DurableVerifyFailure>;
177
174
  /** `DurableAgentRuntime.retry` — audited single-Submission re-drive with typed refusals. */
178
175
  readonly retry: (command: RetryCommand) => Effect.Effect<RecoveryReport, DurableRetryFailure>;
179
176
  /** `DurableAgentRuntime.wake` — the documented operator liveness nudge for one lane. */
180
- readonly wake: (conversationId: ConversationId) => Effect.Effect<void, OperationDenied>;
177
+ readonly wake: (threadId: ThreadId) => Effect.Effect<void, OperationDenied>;
181
178
  /** `DurableAgentRuntime.scanObligations` — the scan-based DUR-017/OPS-001 report. */
182
179
  readonly scanObligations: (
183
180
  thresholds: ObligationThresholds,
@@ -196,20 +193,42 @@ export class NodeDurableHost extends Context.Service<
196
193
  readonly runResolvedWorkers: Effect.Effect<void, DurableWorkerFailure | DurableBindingFailure>;
197
194
  }
198
195
  >()("@effect-agent/platform-node/NodeDurableHost") {
199
- /** Host gates over an already-assembled `NodeDurableRuntime` stack. */
200
- static readonly layer: Layer.Layer<
196
+ /**
197
+ * Host gates over an assembled `NodeDurableRuntime` stack. Bindings must carry the exact
198
+ * digests stored by submitters. Omission registers no Agents, so resolved work fails closed.
199
+ */
200
+ static readonly layer = (
201
+ bindings: ReadonlyArray<ResolvedBinding> = [],
202
+ ): Layer.Layer<
201
203
  NodeDurableHost,
202
204
  DurableWorkerFailure,
203
- DurableAgentRuntime | NodeDurableRuntimeConfig | AgentBindingResolver
204
- > = Layer.effect(NodeDurableHost)(makeHost);
205
+ DurableAgentRuntime | NodeDurableRuntimeConfig
206
+ > => Layer.effect(NodeDurableHost)(makeHost(bindings));
205
207
 
206
208
  /** The complete DN host: `NodeDurableRuntime.layer(options)` plus the host lifecycle gates. */
207
- static layerStack(
208
- options: NodeDurableRuntimeOptions,
209
+ static layerStack<
210
+ ContextError = never,
211
+ ContextRequirements = never,
212
+ AuthorizationError = never,
213
+ AuthorizationRequirements = never,
214
+ >(
215
+ options: NodeDurableRuntimeOptions<
216
+ ContextError,
217
+ ContextRequirements,
218
+ AuthorizationError,
219
+ AuthorizationRequirements
220
+ > & { readonly bindings?: ReadonlyArray<ResolvedBinding> },
209
221
  ): Layer.Layer<
210
222
  NodeDurableHost | NodeDurableRuntimeServices,
211
- DurableWorkerFailure | NodeDurableRuntimeInitializationError
223
+ | DurableWorkerFailure
224
+ | NodeDurableRuntimeInitializationError
225
+ | ContextError
226
+ | AuthorizationError,
227
+ Exclude<ContextRequirements | AuthorizationRequirements, Crypto.Crypto>
212
228
  > {
213
- return NodeDurableHost.layer.pipe(Layer.provideMerge(NodeDurableRuntime.layer(options)));
229
+ const { bindings = [], ...runtimeOptions } = options;
230
+ return NodeDurableHost.layer(bindings).pipe(
231
+ Layer.provideMerge(NodeDurableRuntime.layer(runtimeOptions)),
232
+ );
214
233
  }
215
234
  }
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from "./host.ts";
2
2
  export * from "./layers.ts";
3
3
  export * from "./scheduling.ts";
4
+ export * from "./subscriptions.ts";
4
5
  export * from "./wake-scheduler.ts";