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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { AbortCommand, AbortIntent, AgentBindingResolver, CanonicalRecordEnvelope, ConversationNotMaterialized, ConversationStore, ConversationStoreError, DurableAbortFailure, DurableAgentRuntime, DurableAwaitFailure, DurableBindingFailure, DurableExplainFailure, DurableObligationFailure, DurableObserveOptions, DurableRetryFailure, DurableRuntimeConfig, DurableRuntimeFailpointHandler, DurableSubmitAgent, DurableSubmitFailure, DurableSubmitOptions, DurableVerifyFailure, DurableWorkerFailure, IntegrityReport, ObligationReport, ObligationThresholds, OperationDenied, Receipt, RecoveryExplanation, RecoveryReport, ResolvedBinding, RetryCommand, Settlement, SubmissionLedger, ToolReconciler, WakeScheduler } from "@effect-agent/session";
1
+ import { AbortCommand, AbortIntent, AgentBindingResolver, CanonicalRecordEnvelope, ConversationNotMaterialized, ConversationStore, ConversationStoreError, DurableAbortFailure, DurableAgentRuntime, DurableAwaitFailure, DurableBindingFailure, DurableExplainFailure, DurableObligationFailure, DurableObserveOptions, DurableRetryFailure, DurableRuntimeConfig, DurableRuntimeFailpointHandler, DurableSubmitAgent, DurableSubmitFailure, DurableSubmitOptions, DurableVerifyFailure, DurableWorkerFailure, IntegrityReport, ObligationReport, ObligationThresholds, OperationDenied, Receipt, RecoveryExplanation, RecoveryReport, ResolvedBinding, RetryCommand, ScheduleAuthorizer, ScheduleStore, ScheduleValidationError, ScheduleWake, ScheduledInputAdmission, Scheduling, SchedulingLimits, Settlement, SubmissionLedger, ToolReconciler, WakeScheduler } from "@effect-agent/session";
2
2
  import { Context, Duration, Effect, Layer, Schema, Stream } from "effect";
3
3
  import { RunCostEstimator, RunToolFailureObserver } from "@effect-agent/engine";
4
4
  import { SqliteStorageFailpointHandler, SqliteStorageInitializationError } from "@effect-agent/storage-sqlite";
@@ -86,7 +86,7 @@ interface NodeDurableRuntimeOptions {
86
86
  */
87
87
  readonly toolReconciler?: Layer.Layer<ToolReconciler> | undefined;
88
88
  /**
89
- * Registered worker Bindings resolved at durable claim time (S2, spec/subagents.md §11):
89
+ * Registered worker Bindings resolved at durable claim time:
90
90
  * build each with `DurableWorkerBinding.make(binding, digests)` so
91
91
  * `NodeDurableHost.runResolvedWorkers` / `DurableAgentRuntime.runResolvedWorker` can serve
92
92
  * parent and child lanes from one pool with exact-digest resolution (SUB-023). Defaults to
@@ -98,7 +98,7 @@ interface NodeDurableRuntimeOptions {
98
98
  /** Every construction failure of the assembled Node durable runtime stack. */
99
99
  type NodeDurableRuntimeInitializationError = NodePlatformConfigError | SqliteStorageInitializationError;
100
100
  /** The services `NodeDurableRuntime.layer` provides. */
101
- type NodeDurableRuntimeServices = DurableAgentRuntime | SubmissionLedger | ConversationStore | WakeScheduler | DurableRuntimeConfig | NodeDurableRuntimeConfig | AgentBindingResolver;
101
+ type NodeDurableRuntimeServices = DurableAgentRuntime | SubmissionLedger | ConversationStore | ScheduleStore | WakeScheduler | DurableRuntimeConfig | NodeDurableRuntimeConfig | AgentBindingResolver;
102
102
  /**
103
103
  * Shutdown-drain decorator for a `SubmissionLedger` (deployment §6 step 6): every ownership
104
104
  * period granted through this Layer is tracked — claims start tracking, renewals follow token
@@ -195,6 +195,25 @@ declare class NodeDurableHost extends NodeDurableHost_base {
195
195
  static layerStack(options: NodeDurableRuntimeOptions): Layer.Layer<NodeDurableHost | NodeDurableRuntimeServices, DurableWorkerFailure | NodeDurableRuntimeInitializationError>;
196
196
  }
197
197
  //#endregion
198
+ //#region src/scheduling.d.ts
199
+ /**
200
+ * Scheduled admission through the existing host gate. Once the gate admits the call, every
201
+ * runtime failure stays ambiguous because the Submission may already have committed.
202
+ */
203
+ declare const nodeScheduledInputAdmissionLayer: Layer.Layer<ScheduledInputAdmission, never, NodeDurableHost>;
204
+ /** One bounded hint slot for the single supported Node scheduler. Indexed polling repairs loss. */
205
+ declare const nodeScheduleWakeLayer: Layer.Layer<ScheduleWake>;
206
+ interface NodeSchedulingOptions {
207
+ readonly limits?: SchedulingLimits | undefined;
208
+ }
209
+ /**
210
+ * Optional Scope-owned Node scheduling service and driver. The caller must provide the existing
211
+ * host, its SQLite ScheduleStore, and an explicit ScheduleAuthorizer.
212
+ */
213
+ declare class NodeScheduling {
214
+ static layer(options?: NodeSchedulingOptions): Layer.Layer<Scheduling, ScheduleValidationError, NodeDurableHost | ScheduleStore | ScheduleAuthorizer>;
215
+ }
216
+ //#endregion
198
217
  //#region src/wake-scheduler.d.ts
199
218
  declare const NodeWakeSchedulerConfig_base: Context.ServiceClass<NodeWakeSchedulerConfig, "@effect-agent/platform-node/NodeWakeSchedulerConfig", {
200
219
  /** Interval between ledger scans that re-emit every nonterminal Conversation lane. */
@@ -215,5 +234,5 @@ declare class NodeWakeSchedulerConfig extends NodeWakeSchedulerConfig_base {
215
234
  */
216
235
  declare const nodeWakeSchedulerLayer: Layer.Layer<WakeScheduler, never, SubmissionLedger | NodeWakeSchedulerConfig>;
217
236
  //#endregion
218
- export { AdmissionClosed, NodeDurableHost, NodeDurableRuntime, NodeDurableRuntimeConfig, NodeDurableRuntimeConfigValue, NodeDurableRuntimeInitializationError, NodeDurableRuntimeOptions, NodeDurableRuntimeServices, NodePlatformConfigError, NodeWakeSchedulerConfig, nodeWakeSchedulerLayer, ownershipDrainLayer };
237
+ export { AdmissionClosed, NodeDurableHost, NodeDurableRuntime, NodeDurableRuntimeConfig, NodeDurableRuntimeConfigValue, NodeDurableRuntimeInitializationError, NodeDurableRuntimeOptions, NodeDurableRuntimeServices, NodePlatformConfigError, NodeScheduling, NodeSchedulingOptions, NodeWakeSchedulerConfig, nodeScheduleWakeLayer, nodeScheduledInputAdmissionLayer, nodeWakeSchedulerLayer, ownershipDrainLayer };
219
238
  //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import { AgentBindingResolver, DEFAULT_OWNERSHIP_LEASE_DURATION, DeploymentId, DurableAgentRuntime, DurableRuntimeConfig, DurableRuntimeFailpoint, ProducerId, ReleaseOwnershipRequest, SubmissionLedger, ToolReconciler, WakeScheduler, makeWakeSubscriptionHub } from "@effect-agent/session";
2
- import { Context, Duration, Effect, Layer, PubSub, Ref, Schema, Stream } from "effect";
1
+ import { AgentBindingResolver, DEFAULT_OWNERSHIP_LEASE_DURATION, DeploymentId, DurableAgentRuntime, DurableRuntimeConfig, DurableRuntimeFailpoint, PersistedJson, ProducerId, ReleaseOwnershipRequest, ScheduleDriver, ScheduleStorageError, ScheduleStore, ScheduleWake, ScheduledInputAdmission, ScheduledInputRetryable, Scheduling, SubmissionLedger, ToolReconciler, WakeScheduler, defaultSchedulingLimits, makeWakeSubscriptionHub } from "@effect-agent/session";
2
+ import { Cause, Context, Duration, Effect, Layer, Option, PubSub, Ref, Result, Schema, Stream } from "effect";
3
3
  import { CurrentToolFailureObserver, toolFailureObserverLayer } from "@effect-agent/engine";
4
- import { SqliteStorageConfig, SqliteStorageConfigValue, conversationStoreLayer, storageFailpointLayer, submissionLedgerLayer } from "@effect-agent/storage-sqlite";
4
+ import { SqliteStorageConfig, SqliteStorageConfigValue, conversationStoreLayer, scheduleStoreLayer, storageFailpointLayer, submissionLedgerLayer } from "@effect-agent/storage-sqlite";
5
5
  import { NodeCrypto } from "@effect/platform-node";
6
6
  import { SqliteClient } from "@effect/sql-sqlite-node";
7
7
  //#region src/wake-scheduler.ts
@@ -223,7 +223,7 @@ var NodeDurableRuntime = class {
223
223
  const reconcilerLayer = options.toolReconciler ?? ToolReconciler.uncertain;
224
224
  const observerLayer = options.toolFailureObserver === void 0 ? Layer.succeed(CurrentToolFailureObserver)(void 0) : toolFailureObserverLayer(options.toolFailureObserver);
225
225
  const bindingResolverLayer = AgentBindingResolver.layer(options.bindings ?? []);
226
- const ports = Layer.mergeAll(conversationStoreLayer, nodeWakeSchedulerLayer.pipe(Layer.provideMerge(ownershipDrainLayer.pipe(Layer.provide(submissionLedgerLayer)))));
226
+ const ports = Layer.mergeAll(conversationStoreLayer, scheduleStoreLayer, nodeWakeSchedulerLayer.pipe(Layer.provideMerge(ownershipDrainLayer.pipe(Layer.provide(submissionLedgerLayer)))));
227
227
  return DurableAgentRuntime.layer.pipe(Layer.provideMerge(Layer.mergeAll(ports, durableRuntimeConfigLayer(options.estimateCostMicrousd), bindingResolverLayer)), Layer.provide(Layer.mergeAll(wakeSchedulerConfigLayer, runtimeFailpointLayer, reconcilerLayer, observerLayer)), Layer.provideMerge(infrastructure), Layer.provideMerge(nodeConfigLayer));
228
228
  }));
229
229
  }
@@ -289,6 +289,85 @@ var NodeDurableHost = class NodeDurableHost extends Context.Service()("@effect-a
289
289
  }
290
290
  };
291
291
  //#endregion
292
- export { AdmissionClosed, NodeDurableHost, NodeDurableRuntime, NodeDurableRuntimeConfig, NodeDurableRuntimeConfigValue, NodePlatformConfigError, NodeWakeSchedulerConfig, nodeWakeSchedulerLayer, ownershipDrainLayer };
292
+ //#region src/scheduling.ts
293
+ const passthroughSubmitAgent = (agentId) => ({ definition: {
294
+ id: agentId,
295
+ input: PersistedJson
296
+ } });
297
+ const ambiguous = () => ScheduledInputRetryable.make({ reason: "ambiguous" });
298
+ const corrupt = (operation) => ScheduleStorageError.make({
299
+ operation,
300
+ reason: "corrupt"
301
+ });
302
+ /**
303
+ * Scheduled admission through the existing host gate. Once the gate admits the call, every
304
+ * runtime failure stays ambiguous because the Submission may already have committed.
305
+ */
306
+ const nodeScheduledInputAdmissionLayer = Layer.effect(ScheduledInputAdmission, Effect.gen(function* () {
307
+ const host = yield* NodeDurableHost;
308
+ return ScheduledInputAdmission.of({ submit: (envelope) => host.submit(passthroughSubmitAgent(envelope.agentId), envelope.input, {
309
+ conversationId: envelope.conversationId,
310
+ principal: envelope.deliveryPrincipal,
311
+ idempotencyKey: envelope.admissionKey,
312
+ definitions: envelope.definitions
313
+ }).pipe(Effect.catchTags({
314
+ AdmissionClosed: () => Effect.fail(ScheduledInputRetryable.make({ reason: "host-closed" })),
315
+ AgentInputError: () => Effect.fail(corrupt("scheduled admission input")),
316
+ AdmissionConflict: () => Effect.fail(corrupt("scheduled admission conflict")),
317
+ DigestError: () => Effect.fail(ambiguous()),
318
+ LedgerError: () => Effect.fail(ambiguous()),
319
+ ConversationStoreError: () => Effect.fail(ambiguous()),
320
+ ConversationNotMaterialized: () => Effect.fail(ambiguous()),
321
+ AppendConflict: () => Effect.fail(ambiguous()),
322
+ FenceRejected: () => Effect.fail(ambiguous()),
323
+ DurableRuntimeFailpointError: () => Effect.fail(ambiguous())
324
+ })) });
325
+ }));
326
+ /** One bounded hint slot for the single supported Node scheduler. Indexed polling repairs loss. */
327
+ const nodeScheduleWakeLayer = Layer.effect(ScheduleWake, Effect.gen(function* () {
328
+ const hints = yield* PubSub.sliding(1);
329
+ const subscription = yield* PubSub.subscribe(hints);
330
+ yield* Effect.addFinalizer(() => PubSub.shutdown(hints));
331
+ return ScheduleWake.of({
332
+ notify: PubSub.publish(hints, void 0).pipe(Effect.asVoid),
333
+ await: PubSub.take(subscription)
334
+ });
335
+ }));
336
+ const reportPassFailure = (cause) => Cause.hasInterruptsOnly(cause) ? Effect.interrupt : Effect.logWarning("Node scheduling pass failed").pipe(Effect.annotateLogs({ failureTag: Option.match(Cause.findErrorOption(cause), {
337
+ onNone: () => "Defect",
338
+ onSome: (error) => error._tag
339
+ }) }), Effect.as(false));
340
+ const nodeSchedulingDriverLayer = (limits) => Layer.effectDiscard(Effect.gen(function* () {
341
+ const scheduling = yield* ScheduleDriver;
342
+ const store = yield* ScheduleStore;
343
+ const wake = yield* ScheduleWake;
344
+ const run = Effect.gen(function* () {
345
+ while (true) {
346
+ const passSucceeded = yield* scheduling.runDue().pipe(Effect.map((pass) => pass.failed === 0), Effect.catchCause(reportPassFailure));
347
+ const deadlineResult = passSucceeded ? yield* store.nextDeadline().pipe(Effect.result) : Result.fail(ScheduleStorageError.make({
348
+ operation: "driver pass",
349
+ reason: "unavailable"
350
+ }));
351
+ if (Result.isFailure(deadlineResult) && passSucceeded) yield* Effect.logWarning("Node scheduling deadline query failed");
352
+ const nowMillis = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
353
+ const deadlineDelay = Result.isSuccess(deadlineResult) && deadlineResult.success !== null ? Math.max(0, deadlineResult.success - nowMillis) : limits.recoveryPollMillis;
354
+ const delay = Math.min(deadlineDelay, limits.recoveryPollMillis);
355
+ yield* Effect.raceFirst(wake.await, Effect.sleep(Duration.millis(delay)));
356
+ }
357
+ });
358
+ yield* Effect.forkScoped(run);
359
+ }));
360
+ /**
361
+ * Optional Scope-owned Node scheduling service and driver. The caller must provide the existing
362
+ * host, its SQLite ScheduleStore, and an explicit ScheduleAuthorizer.
363
+ */
364
+ var NodeScheduling = class {
365
+ static layer(options = {}) {
366
+ const limits = options.limits ?? defaultSchedulingLimits;
367
+ return nodeSchedulingDriverLayer(limits).pipe(Layer.provide(ScheduleDriver.layer(limits)), Layer.merge(Scheduling.layer(limits))).pipe(Layer.provide(Layer.mergeAll(nodeScheduledInputAdmissionLayer, nodeScheduleWakeLayer, NodeCrypto.layer)));
368
+ }
369
+ };
370
+ //#endregion
371
+ export { AdmissionClosed, NodeDurableHost, NodeDurableRuntime, NodeDurableRuntimeConfig, NodeDurableRuntimeConfigValue, NodePlatformConfigError, NodeScheduling, NodeWakeSchedulerConfig, nodeScheduleWakeLayer, nodeScheduledInputAdmissionLayer, nodeWakeSchedulerLayer, ownershipDrainLayer };
293
372
 
294
373
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/wake-scheduler.ts","../src/layers.ts","../src/host.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 {\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 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 (S2, spec/subagents.md §11):\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 | 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 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(NodeDur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iBAAiB,QAAQ;EACzB,SAAS,QAAQ;EACjB,OAAO,QAAQ;EACf,SAAS,QAAQ;EACjB,qBAAqB,QAAQ;EAC7B,QAAQ,QAAQ;EAChB,OAAO,QAAQ;EACf,MAAM,QAAQ;EACd,iBAAiB,QAAQ;EACzB;EACA;CACF,CAAC;AACH,CAAC;;;;;;;;;;;;;;;AAgBD,IAAa,kBAAb,MAAa,wBAAwB,QAAQ,QA+D3C,CAAC,CAAC,6CAA6C,CAAC,CAAC;;CAEjD,OAAgB,QAIZ,MAAM,OAAO,eAAe,CAAC,CAAC,QAAQ;;CAG1C,OAAO,WACL,SAIA;EACA,OAAO,gBAAgB,MAAM,KAAK,MAAM,aAAa,mBAAmB,MAAM,OAAO,CAAC,CAAC;CACzF;AACF"}
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 }\n}\n"],"mappings":";;;;;;;;;;;AAQA,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,QAAwB,oBAAoB;CACxE,MAAM,WAAW,OAAO;CACxB,OAAO,OAAO,mBAAmB,OAAO,SAAS,KAAK,CAAC;;;;;;CAOvD,MAAM,WAAyD,OAAO,WACpE,OAAO,eACT,CAAC,CAAC,KACA,OAAO,KAAK,cAAc;EACxB,MAAM,wBAAQ,IAAI,IAAoB;EACtC,KAAK,MAAM,YAAY,WACrB,MAAM,IAAI,SAAS,cAAc;EAEnC,OAAO,CAAC,GAAG,KAAK;CAClB,CAAC,GACD,OAAO,OAAO,UACZ,OAAO,WAAW,0CAA0C,KAAK,CAAC,CAAC,KACjE,OAAO,GAAG,CAAC,CAAkC,CAC/C,CACF,CACF;;;;;;CAOA,MAAM,gBAA+C,OAAO,yBAC1D,OAAO,MAAM,OAAO,YAAY,CAAC,CAAC,KAAK,OAAO,QAAQ,QAAQ,CAAC,CACj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
3
- "version": "0.1.0-beta.35",
3
+ "version": "0.1.0-beta.37",
4
4
  "exports": {
5
5
  ".": {
6
6
  "types": "./dist/index.d.mts",
@@ -8,10 +8,10 @@
8
8
  }
9
9
  },
10
10
  "dependencies": {
11
- "@effect-agent/core": "0.1.0-beta.35",
12
- "@effect-agent/engine": "0.1.0-beta.35",
13
- "@effect-agent/session": "0.1.0-beta.35",
14
- "@effect-agent/storage-sqlite": "0.1.0-beta.35",
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",
15
15
  "@effect/platform-node": "4.0.0-rc.111",
16
16
  "@effect/sql-sqlite-node": "4.0.0-rc.111",
17
17
  "effect": "4.0.0-rc.111"
@@ -37,7 +37,7 @@
37
37
  "test": "vp test --passWithNoTests"
38
38
  },
39
39
  "devDependencies": {
40
- "@effect-agent/capabilities": "0.1.0-beta.33",
40
+ "@effect-agent/capabilities": "0.1.0-beta.35",
41
41
  "@effect/vitest": "4.0.0-rc.111",
42
42
  "typescript": "7.0.2",
43
43
  "vite-plus": "0.2.6"
package/src/index.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export * from "./host.ts";
2
2
  export * from "./layers.ts";
3
+ export * from "./scheduling.ts";
3
4
  export * from "./wake-scheduler.ts";
package/src/layers.ts CHANGED
@@ -5,6 +5,7 @@ import {
5
5
  type RunCostEstimator,
6
6
  type RunToolFailureObserver,
7
7
  } from "@effect-agent/engine";
8
+ import type { ScheduleStore } from "@effect-agent/session";
8
9
  import {
9
10
  type ConversationStore,
10
11
  type WakeScheduler,
@@ -24,6 +25,7 @@ import {
24
25
  } from "@effect-agent/session";
25
26
  import {
26
27
  conversationStoreLayer,
28
+ scheduleStoreLayer,
27
29
  SqliteStorageConfig,
28
30
  SqliteStorageConfigValue,
29
31
  storageFailpointLayer,
@@ -134,7 +136,7 @@ export interface NodeDurableRuntimeOptions {
134
136
  */
135
137
  readonly toolReconciler?: Layer.Layer<ToolReconciler> | undefined;
136
138
  /**
137
- * Registered worker Bindings resolved at durable claim time (S2, spec/subagents.md §11):
139
+ * Registered worker Bindings resolved at durable claim time:
138
140
  * build each with `DurableWorkerBinding.make(binding, digests)` so
139
141
  * `NodeDurableHost.runResolvedWorkers` / `DurableAgentRuntime.runResolvedWorker` can serve
140
142
  * parent and child lanes from one pool with exact-digest resolution (SUB-023). Defaults to
@@ -154,6 +156,7 @@ export type NodeDurableRuntimeServices =
154
156
  | DurableAgentRuntime
155
157
  | SubmissionLedger
156
158
  | ConversationStore
159
+ | ScheduleStore
157
160
  | WakeScheduler
158
161
  | DurableRuntimeConfig
159
162
  | NodeDurableRuntimeConfig
@@ -385,6 +388,7 @@ export class NodeDurableRuntime {
385
388
  const bindingResolverLayer = AgentBindingResolver.layer(options.bindings ?? []);
386
389
  const ports = Layer.mergeAll(
387
390
  conversationStoreLayer,
391
+ scheduleStoreLayer,
388
392
  nodeWakeSchedulerLayer.pipe(
389
393
  Layer.provideMerge(ownershipDrainLayer.pipe(Layer.provide(submissionLedgerLayer))),
390
394
  ),
@@ -0,0 +1,164 @@
1
+ import type { AgentId } from "@effect-agent/core";
2
+ import {
3
+ type DurableSubmitAgent,
4
+ type ScheduleProcessFailure,
5
+ type ScheduleAuthorizer,
6
+ type SchedulingLimits,
7
+ ScheduleStorageError,
8
+ ScheduleStore,
9
+ type ScheduleValidationError,
10
+ ScheduledInputAdmission,
11
+ ScheduledInputRetryable,
12
+ ScheduleWake,
13
+ Scheduling,
14
+ ScheduleDriver,
15
+ defaultSchedulingLimits,
16
+ PersistedJson,
17
+ } from "@effect-agent/session";
18
+ import { NodeCrypto } from "@effect/platform-node";
19
+ import { Cause, Duration, Effect, Layer, Option, PubSub, Result } from "effect";
20
+
21
+ import { NodeDurableHost } from "./host.ts";
22
+
23
+ const passthroughSubmitAgent = (agentId: AgentId): DurableSubmitAgent<typeof PersistedJson> => ({
24
+ definition: { id: agentId, input: PersistedJson },
25
+ });
26
+
27
+ const ambiguous = (): ScheduledInputRetryable =>
28
+ ScheduledInputRetryable.make({ reason: "ambiguous" });
29
+
30
+ const corrupt = (operation: string): ScheduleStorageError =>
31
+ ScheduleStorageError.make({ operation, reason: "corrupt" });
32
+
33
+ /**
34
+ * Scheduled admission through the existing host gate. Once the gate admits the call, every
35
+ * runtime failure stays ambiguous because the Submission may already have committed.
36
+ */
37
+ export const nodeScheduledInputAdmissionLayer: Layer.Layer<
38
+ ScheduledInputAdmission,
39
+ never,
40
+ NodeDurableHost
41
+ > = Layer.effect(
42
+ ScheduledInputAdmission,
43
+ Effect.gen(function* () {
44
+ const host = yield* NodeDurableHost;
45
+ return ScheduledInputAdmission.of({
46
+ submit: (envelope) =>
47
+ host
48
+ .submit(passthroughSubmitAgent(envelope.agentId), envelope.input, {
49
+ conversationId: envelope.conversationId,
50
+ principal: envelope.deliveryPrincipal,
51
+ idempotencyKey: envelope.admissionKey,
52
+ definitions: envelope.definitions,
53
+ })
54
+ .pipe(
55
+ Effect.catchTags({
56
+ AdmissionClosed: () =>
57
+ Effect.fail(ScheduledInputRetryable.make({ reason: "host-closed" })),
58
+ AgentInputError: () => Effect.fail(corrupt("scheduled admission input")),
59
+ AdmissionConflict: () => Effect.fail(corrupt("scheduled admission conflict")),
60
+ DigestError: () => Effect.fail(ambiguous()),
61
+ LedgerError: () => Effect.fail(ambiguous()),
62
+ ConversationStoreError: () => Effect.fail(ambiguous()),
63
+ ConversationNotMaterialized: () => Effect.fail(ambiguous()),
64
+ AppendConflict: () => Effect.fail(ambiguous()),
65
+ FenceRejected: () => Effect.fail(ambiguous()),
66
+ DurableRuntimeFailpointError: () => Effect.fail(ambiguous()),
67
+ }),
68
+ ),
69
+ });
70
+ }),
71
+ );
72
+
73
+ /** One bounded hint slot for the single supported Node scheduler. Indexed polling repairs loss. */
74
+ export const nodeScheduleWakeLayer: Layer.Layer<ScheduleWake> = Layer.effect(
75
+ ScheduleWake,
76
+ Effect.gen(function* () {
77
+ const hints = yield* PubSub.sliding<void>(1);
78
+ const subscription = yield* PubSub.subscribe(hints);
79
+ yield* Effect.addFinalizer(() => PubSub.shutdown(hints));
80
+ return ScheduleWake.of({
81
+ notify: PubSub.publish(hints, undefined).pipe(Effect.asVoid),
82
+ await: PubSub.take(subscription),
83
+ });
84
+ }),
85
+ );
86
+
87
+ const reportPassFailure = (cause: Cause.Cause<ScheduleProcessFailure>): Effect.Effect<boolean> =>
88
+ Cause.hasInterruptsOnly(cause)
89
+ ? Effect.interrupt
90
+ : Effect.logWarning("Node scheduling pass failed").pipe(
91
+ Effect.annotateLogs({
92
+ failureTag: Option.match(Cause.findErrorOption(cause), {
93
+ onNone: () => "Defect",
94
+ onSome: (error) => error._tag,
95
+ }),
96
+ }),
97
+ Effect.as(false),
98
+ );
99
+
100
+ const nodeSchedulingDriverLayer = (
101
+ limits: SchedulingLimits,
102
+ ): Layer.Layer<never, never, ScheduleDriver | ScheduleStore | ScheduleWake> =>
103
+ Layer.effectDiscard(
104
+ Effect.gen(function* () {
105
+ const scheduling = yield* ScheduleDriver;
106
+ const store = yield* ScheduleStore;
107
+ const wake = yield* ScheduleWake;
108
+
109
+ const run = Effect.gen(function* () {
110
+ while (true) {
111
+ const passSucceeded = yield* scheduling.runDue().pipe(
112
+ Effect.map((pass) => pass.failed === 0),
113
+ Effect.catchCause(reportPassFailure),
114
+ );
115
+ const deadlineResult = passSucceeded
116
+ ? yield* store.nextDeadline().pipe(Effect.result)
117
+ : Result.fail(
118
+ ScheduleStorageError.make({ operation: "driver pass", reason: "unavailable" }),
119
+ );
120
+ if (Result.isFailure(deadlineResult) && passSucceeded) {
121
+ yield* Effect.logWarning("Node scheduling deadline query failed");
122
+ }
123
+ const nowMillis = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
124
+ const deadlineDelay =
125
+ Result.isSuccess(deadlineResult) && deadlineResult.success !== null
126
+ ? Math.max(0, deadlineResult.success - nowMillis)
127
+ : limits.recoveryPollMillis;
128
+ const delay = Math.min(deadlineDelay, limits.recoveryPollMillis);
129
+ yield* Effect.raceFirst(wake.await, Effect.sleep(Duration.millis(delay)));
130
+ }
131
+ });
132
+
133
+ yield* Effect.forkScoped(run);
134
+ }),
135
+ );
136
+
137
+ export interface NodeSchedulingOptions {
138
+ readonly limits?: SchedulingLimits | undefined;
139
+ }
140
+
141
+ /**
142
+ * Optional Scope-owned Node scheduling service and driver. The caller must provide the existing
143
+ * host, its SQLite ScheduleStore, and an explicit ScheduleAuthorizer.
144
+ */
145
+ export class NodeScheduling {
146
+ static layer(
147
+ options: NodeSchedulingOptions = {},
148
+ ): Layer.Layer<
149
+ Scheduling,
150
+ ScheduleValidationError,
151
+ NodeDurableHost | ScheduleStore | ScheduleAuthorizer
152
+ > {
153
+ const limits = options.limits ?? defaultSchedulingLimits;
154
+ const schedulingWithDriver = nodeSchedulingDriverLayer(limits).pipe(
155
+ Layer.provide(ScheduleDriver.layer(limits)),
156
+ Layer.merge(Scheduling.layer(limits)),
157
+ );
158
+ return schedulingWithDriver.pipe(
159
+ Layer.provide(
160
+ Layer.mergeAll(nodeScheduledInputAdmissionLayer, nodeScheduleWakeLayer, NodeCrypto.layer),
161
+ ),
162
+ );
163
+ }
164
+ }