@systemfsoftware/agent-platform-node 0.0.0-bootstrap.0 → 0.1.0-beta.192

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.
Files changed (42) hide show
  1. package/LICENSE +21 -0
  2. package/dist/NodeDurableAgentRuntime-C5SFn9kf.mjs +218 -0
  3. package/dist/NodeDurableAgentRuntime-C5SFn9kf.mjs.map +1 -0
  4. package/dist/NodeDurableAgentRuntime-CUrOl39W.d.mts +163 -0
  5. package/dist/NodeDurableAgentRuntime.d.mts +2 -0
  6. package/dist/NodeDurableAgentRuntime.mjs +1 -0
  7. package/dist/NodeDurableHost-BztkzCGh.mjs +271 -0
  8. package/dist/NodeDurableHost-BztkzCGh.mjs.map +1 -0
  9. package/dist/NodeDurableHost-CFvVn1w1.d.mts +153 -0
  10. package/dist/NodeDurableHost.d.mts +2 -0
  11. package/dist/NodeDurableHost.mjs +1 -0
  12. package/dist/NodeScheduling-CD_CZvQ6.d.mts +20 -0
  13. package/dist/NodeScheduling-gNj8jB4g.mjs +64 -0
  14. package/dist/NodeScheduling-gNj8jB4g.mjs.map +1 -0
  15. package/dist/NodeScheduling.d.mts +2 -0
  16. package/dist/NodeScheduling.mjs +1 -0
  17. package/dist/NodeSubscriptions-Bd_3VxqD.d.mts +23 -0
  18. package/dist/NodeSubscriptions-KgvkfIMl.mjs +62 -0
  19. package/dist/NodeSubscriptions-KgvkfIMl.mjs.map +1 -0
  20. package/dist/NodeSubscriptions.d.mts +2 -0
  21. package/dist/NodeSubscriptions.mjs +1 -0
  22. package/dist/NodeWakeScheduler-Dyha4GZJ.d.mts +28 -0
  23. package/dist/NodeWakeScheduler-dVNAHWsN.mjs +58 -0
  24. package/dist/NodeWakeScheduler-dVNAHWsN.mjs.map +1 -0
  25. package/dist/NodeWakeScheduler.d.mts +2 -0
  26. package/dist/NodeWakeScheduler.mjs +1 -0
  27. package/dist/index.d.mts +6 -0
  28. package/dist/index.mjs +6 -0
  29. package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
  30. package/package.json +66 -5
  31. package/src/NodeDurableAgentRuntime.ts +603 -0
  32. package/src/NodeDurableHost.ts +403 -0
  33. package/src/NodeScheduling.ts +122 -0
  34. package/src/NodeSubscriptions.ts +124 -0
  35. package/src/NodeWakeScheduler.ts +94 -0
  36. package/src/index.ts +5 -0
  37. package/src/internal/application-context.ts +25 -0
  38. package/src/internal/exclusive-host.ts +7 -0
  39. package/src/internal/message-delivery.ts +54 -0
  40. package/src/internal/prepared-admission.ts +79 -0
  41. package/src/internal/worker-dispatch.ts +116 -0
  42. package/README.md +0 -3
@@ -0,0 +1,271 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D3KUYPsf.mjs";
2
+ import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3
+ import "@systemfsoftware/agent/agent-registration";
4
+ import { DurableAgentRuntime } from "@systemfsoftware/agent/durable-agent-runtime";
5
+ import { MessageDeliveryDriver, MessageDeliveryStore } from "@systemfsoftware/agent/message-delivery";
6
+ import "@systemfsoftware/agent/operation-authorizer";
7
+ import { PreparedInputAdmission, PreparedInputRefused, PreparedInputRetryable } from "@systemfsoftware/agent/prepared-input-admission";
8
+ import { PersistedJson } from "@systemfsoftware/agent/records";
9
+ import { SubmissionLedger } from "@systemfsoftware/agent/submission-ledger";
10
+ import { ThreadReader } from "@systemfsoftware/agent/thread-store";
11
+ import { MAX_RECOVERY_WORK_ITEMS } from "@systemfsoftware/agent/thread-work";
12
+ import { WakeScheduler } from "@systemfsoftware/agent/wake-scheduler";
13
+ import * as Context from "effect/Context";
14
+ import * as Effect from "effect/Effect";
15
+ import * as Fiber from "effect/Fiber";
16
+ import * as Layer from "effect/Layer";
17
+ import * as Ref from "effect/Ref";
18
+ import * as Schema from "effect/Schema";
19
+ import { n as NodeDurableAgentRuntimeConfig, o as ExclusiveSqliteHost, s as applicationInvocationContext, t as NodeDurableAgentRuntime } from "./NodeDurableAgentRuntime-C5SFn9kf.mjs";
20
+ import * as Cause from "effect/Cause";
21
+ import * as Clock from "effect/Clock";
22
+ import * as Exit from "effect/Exit";
23
+ import * as Option from "effect/Option";
24
+ import "@systemfsoftware/agent/identifiers";
25
+ import { ScheduleStorageError } from "@systemfsoftware/agent/schedule";
26
+ import * as Queue from "effect/Queue";
27
+ import * as Stream from "effect/Stream";
28
+ // src/internal/message-delivery.ts
29
+ const reportFailure = (cause) => Cause.hasInterruptsOnly(cause) ? Effect.interrupt : Effect.logWarning("Node message delivery pass failed").pipe(Effect.annotateLogs({ failureTag: Option.match(Cause.findErrorOption(cause), {
30
+ onNone: () => "Defect",
31
+ onSome: (failure) => failure._tag
32
+ }) }));
33
+ /** Caller-owned loop. Indexed scans repair absent hints even when both Threads have settled. */
34
+ const runNodeMessageDeliveries = Effect.fnUntraced(function* (scanInterval) {
35
+ const driver = yield* MessageDeliveryDriver;
36
+ const store = yield* MessageDeliveryStore;
37
+ while (true) {
38
+ const pass = yield* driver.runDue().pipe(Effect.exit);
39
+ if (Exit.isFailure(pass)) {
40
+ yield* reportFailure(pass.cause);
41
+ yield* Effect.sleep(scanInterval);
42
+ continue;
43
+ }
44
+ const deadline = yield* store.nextDeadline().pipe(Effect.exit);
45
+ if (Exit.isFailure(deadline)) {
46
+ yield* reportFailure(deadline.cause);
47
+ yield* Effect.sleep(scanInterval);
48
+ continue;
49
+ }
50
+ const nowMillis = yield* Clock.currentTimeMillis;
51
+ const delay = deadline.value === null ? scanInterval : Math.max(1, Math.min(deadline.value - nowMillis, scanInterval));
52
+ yield* Effect.sleep(delay);
53
+ }
54
+ });
55
+ // src/internal/prepared-admission.ts
56
+ const passthroughSubmitAgent = (agentId) => ({ definition: {
57
+ id: agentId,
58
+ input: PersistedJson
59
+ } });
60
+ const ambiguous = () => PreparedInputRetryable.make({ reason: "ambiguous" });
61
+ const corrupt = (operation) => ScheduleStorageError.make({
62
+ operation,
63
+ reason: "corrupt"
64
+ });
65
+ /** Host-owned admission gate, available while the host's worker pool is being assembled. */
66
+ var NodeAdmission = class extends Context.Service()("@effect-agent/platform-node/internal/NodeAdmission") {};
67
+ /** Acquire the gated source once; worker callers cannot replace its admission authority. */
68
+ const makeNodePreparedInputAdmission = Effect.gen(function* () {
69
+ const host = yield* NodeAdmission;
70
+ return PreparedInputAdmission.of({
71
+ submissionStatus: (receipt) => host.submissionStatus(receipt).pipe(Effect.mapError(() => PreparedInputRetryable.make({ reason: "storage" }))),
72
+ submit: (envelope) => host.submit(passthroughSubmitAgent(envelope.agentId), envelope.input, {
73
+ threadId: envelope.threadId,
74
+ principal: envelope.deliveryPrincipal,
75
+ idempotencyKey: envelope.admissionKey,
76
+ ...envelope.admissionGroup === void 0 ? {} : { admissionGroup: envelope.admissionGroup },
77
+ ...envelope.admissionFence === void 0 ? {} : { admissionFence: envelope.admissionFence },
78
+ ...envelope.workerAdmission === void 0 ? {} : { workerAdmission: envelope.workerAdmission },
79
+ ...envelope.messageAdmission === void 0 ? {} : { messageAdmission: envelope.messageAdmission },
80
+ definitions: envelope.definitions
81
+ }).pipe(Effect.catchTags({
82
+ AdmissionClosed: () => Effect.fail(PreparedInputRetryable.make({ reason: "host-closed" })),
83
+ AgentInputError: () => Effect.fail(corrupt("prepared admission input")),
84
+ AdmissionConflict: () => Effect.fail(corrupt("prepared admission conflict")),
85
+ DigestError: () => Effect.fail(ambiguous()),
86
+ AdmissionPolicyError: (error) => error.reason === "refused" ? PreparedInputRefused.make({ code: error.code }) : PreparedInputRetryable.make({ reason: error.reason === "occupied" ? "capacity" : "storage" }),
87
+ LedgerError: () => PreparedInputRetryable.make({ reason: "storage" }),
88
+ ThreadStoreError: () => Effect.fail(ambiguous()),
89
+ ThreadNotMaterialized: () => Effect.fail(ambiguous()),
90
+ AppendConflict: () => Effect.fail(ambiguous()),
91
+ OwnershipLost: () => Effect.fail(ambiguous()),
92
+ DurableRuntimeFailpointError: () => Effect.fail(ambiguous())
93
+ }))
94
+ });
95
+ });
96
+ // src/internal/worker-dispatch.ts
97
+ const PENDING_CAPACITY = 1024;
98
+ /**
99
+ * One discovery path feeds bounded concurrent Thread drains. Hints carry no authority:
100
+ * the runtime still claims, fences, parks and releases every Attempt. Concurrency has
101
+ * already been validated by the host configuration.
102
+ */
103
+ const runNodeWorkerDispatch = (concurrency) => Effect.scoped(Effect.gen(function* () {
104
+ const runtime = yield* DurableAgentRuntime;
105
+ const wake = yield* WakeScheduler;
106
+ const pending = yield* Queue.bounded(PENDING_CAPACITY);
107
+ const states = /* @__PURE__ */ new Map();
108
+ yield* Effect.addFinalizer(() => Queue.shutdown(pending));
109
+ const enqueue = Effect.fnUntraced(function* (threadId) {
110
+ if (yield* Effect.sync(() => {
111
+ const state = states.get(threadId);
112
+ if (state === "pending" || state === "dirty") return false;
113
+ if (state === "active") {
114
+ states.set(threadId, "dirty");
115
+ return false;
116
+ }
117
+ states.set(threadId, "pending");
118
+ return true;
119
+ })) yield* Queue.offer(pending, threadId);
120
+ });
121
+ const initial = Stream.paginate(void 0, (afterThreadId) => runtime.discoverWorkThreads({
122
+ limit: 32,
123
+ ...afterThreadId === void 0 ? {} : { afterThreadId }
124
+ }).pipe(Effect.map((page) => [page.threadIds, page.afterThreadId === void 0 ? Option.none() : Option.some(page.afterThreadId)])));
125
+ const ingress = Stream.merge(initial, wake.wakes, { haltStrategy: "right" }).pipe(Stream.runForEach(enqueue));
126
+ const consume = Effect.gen(function* () {
127
+ const threadId = yield* Queue.take(pending);
128
+ yield* Effect.sync(() => states.set(threadId, "active"));
129
+ let again = true;
130
+ let recoveryCursor;
131
+ while (again) {
132
+ const recovered = yield* runtime.runRecovery({
133
+ threadId,
134
+ ...recoveryCursor === void 0 ? {} : { cursor: recoveryCursor }
135
+ });
136
+ const blocked = recovered.blocked[0];
137
+ if (blocked !== void 0) return yield* blocked;
138
+ recoveryCursor = recovered.cursor;
139
+ yield* runtime.processThreadResolved(threadId);
140
+ again = yield* Effect.sync(() => {
141
+ if (states.get(threadId) === "dirty" || recoveryCursor !== void 0) {
142
+ states.set(threadId, "active");
143
+ return true;
144
+ }
145
+ states.delete(threadId);
146
+ return false;
147
+ });
148
+ }
149
+ }).pipe(Effect.forever);
150
+ yield* Effect.raceAllFirst([ingress, ...Array.from({ length: concurrency }, () => consume)]);
151
+ }));
152
+ // src/NodeDurableHost.ts
153
+ var NodeDurableHost_exports = /* @__PURE__ */ __exportAll({
154
+ AdmissionClosed: () => AdmissionClosed,
155
+ NodeDurableHost: () => NodeDurableHost,
156
+ layer: () => layer,
157
+ run: () => run
158
+ });
159
+ /**
160
+ * Admission is not open on this host: it is shutting down (deployment §6 step 1, DEPLOY-005).
161
+ * Accepted work is unaffected — only NEW admissions are refused.
162
+ */
163
+ var AdmissionClosed = class extends Schema.TaggedError()("AdmissionClosed", { message: Schema.String }) {};
164
+ const makeHost = Effect.fnUntraced(function* (managedWorkers) {
165
+ const runtime = yield* DurableAgentRuntime;
166
+ const config = yield* NodeDurableAgentRuntimeConfig;
167
+ let recoveryCursor;
168
+ let startupReports = [];
169
+ do {
170
+ const recovered = yield* runtime.runRecovery(recoveryCursor === void 0 ? void 0 : { cursor: recoveryCursor });
171
+ const blocked = recovered.blocked[0];
172
+ if (blocked !== void 0) return yield* blocked;
173
+ startupReports = [...startupReports, ...recovered.reports].slice(-MAX_RECOVERY_WORK_ITEMS);
174
+ recoveryCursor = recovered.cursor;
175
+ } while (recoveryCursor !== void 0);
176
+ const admission = yield* Ref.make(true);
177
+ const requireAdmission = Ref.get(admission).pipe(Effect.flatMap((open) => open ? Effect.void : Effect.fail(AdmissionClosed.make({ message: "The host is shutting down; admission is closed." }))));
178
+ const submit = (agent, input, options) => requireAdmission.pipe(Effect.andThen(runtime.submit(agent, input, options)));
179
+ const deliveryServices = (yield* Effect.context()).pipe(Context.pick(MessageDeliveryStore));
180
+ const deliveryContext = yield* Layer.build(MessageDeliveryDriver.layer({
181
+ batchSize: 100,
182
+ concurrency: Math.min(config.workerConcurrency, 32)
183
+ }).pipe(Layer.provide(NodeCrypto.layer), Layer.provide(Layer.effect(PreparedInputAdmission, makeNodePreparedInputAdmission).pipe(Layer.provide(Layer.succeed(NodeAdmission, {
184
+ submit,
185
+ submissionStatus: runtime.submissionStatus
186
+ }))))));
187
+ const runDeliveries = Effect.contextWith((live) => runNodeMessageDeliveries(config.wakeScanInterval).pipe(Effect.setContext(Context.mergeAll(applicationInvocationContext(live), deliveryServices, deliveryContext))));
188
+ const withDeliveries = (worker) => Effect.scoped(Effect.raceFirst(worker, runDeliveries).pipe(Effect.asVoid));
189
+ const runWorkers = (worker) => withDeliveries(Effect.forEach(Array.from({ length: config.workerConcurrency }, (_, index) => index), () => worker, {
190
+ concurrency: "unbounded",
191
+ discard: true
192
+ }));
193
+ const runResolvedWorkers = managedWorkers === void 0 ? runWorkers(runtime.runResolvedWorker) : withDeliveries(managedWorkers);
194
+ const run = managedWorkers !== void 0 ? Fiber.join(yield* runResolvedWorkers.pipe(Effect.onExit(() => Ref.set(admission, false)), Effect.forkScoped)) : runResolvedWorkers;
195
+ yield* Effect.addFinalizer(() => Ref.set(admission, false));
196
+ return NodeDurableHost.of({
197
+ startupRecovery: startupReports,
198
+ admissionOpen: Ref.get(admission),
199
+ submit,
200
+ awaitSettlement: runtime.awaitSettlement,
201
+ submissionStatus: runtime.submissionStatus,
202
+ observe: runtime.observe,
203
+ abort: runtime.abort,
204
+ runWorkers,
205
+ run,
206
+ runResolvedWorkers: run
207
+ });
208
+ });
209
+ /**
210
+ * Operational host service. Prefer the module's `layer` and `run` for managed workers.
211
+ * The static constructors on this class retain explicit, manual worker ownership.
212
+ * Use the accompanying `DurableAgentRuntime` service for inspection and recovery operations.
213
+ *
214
+ * Startup gates run during Layer construction, so the service existing implies readiness:
215
+ * configuration was schema-decoded, the SQLite file passed the exact-version compatibility check,
216
+ * and the complete native work inventory passed recovery BEFORE admission opened.
217
+ * `startupRecovery` retains the last bounded page of Submission decisions.
218
+ *
219
+ * Shutdown runs in reverse Layer order when the owning Scope closes: `submit` starts refusing
220
+ * with `AdmissionClosed` first, then workers stop and local owner generations close before
221
+ * SQLite resources. Accepted work remains recoverable after forced termination (DEPLOY-006).
222
+ */
223
+ var NodeDurableHost = class NodeDurableHost extends Context.Service()("@effect-agent/platform-node/NodeDurableHost") {
224
+ /**
225
+ * Compile typed registrations and acquire the complete host in one Layer Scope.
226
+ * Node supplies Digest and SecureRandom; model, tool, instruction, and schema services remain required.
227
+ * Startup recovery and shutdown gates are unchanged. Workers start only when the caller
228
+ * runs runResolvedWorkers; this constructor never starts a background worker.
229
+ */
230
+ static layerRegistered(registrations, options) {
231
+ return NodeDurableHost.layer.pipe(Layer.provideMerge(NodeDurableAgentRuntime.layerRegistered(registrations, options)));
232
+ }
233
+ /**
234
+ * Host gates over an assembled `NodeDurableAgentRuntime` stack. The runtime Layer owns
235
+ * executable registrations; omission registers no Agents, so resolved work fails closed.
236
+ */
237
+ static layer = Layer.effect(NodeDurableHost)(makeHost());
238
+ /** The complete DN host: `NodeDurableAgentRuntime.layer(options)` plus the host lifecycle gates. */
239
+ static layerStack(options) {
240
+ const { bindings = [], ...runtimeOptions } = options;
241
+ return NodeDurableHost.layer.pipe(Layer.provideMerge(NodeDurableAgentRuntime.layerWithBindings(bindings, runtimeOptions)));
242
+ }
243
+ };
244
+ /**
245
+ * Acquire a complete Node host and start one bounded, scoped worker pool after recovery.
246
+ * Own the SQLite file exclusively until the host and its storage close. A second connection
247
+ * fails construction. Process death releases the file lock; a replacement acquires it before
248
+ * recovering retained work with fresh local generations. Use this host's services for live inspection.
249
+ * Provide model, tool, instruction, and schema dependencies to this Layer. Reusing the Layer
250
+ * shares the same pool. A worker failure closes admission; observe it with `run` at the process
251
+ * boundary so the application exits and releases the host instead of remaining idle.
252
+ */
253
+ const layer = (registrations, options) => Layer.effectContext(Effect.gen(function* () {
254
+ const services = yield* Layer.build(NodeDurableAgentRuntime.layerRegistered(registrations, options).pipe(Layer.provide(Layer.succeed(ExclusiveSqliteHost, true))));
255
+ const config = Context.get(services, NodeDurableAgentRuntimeConfig);
256
+ const workerServices = services.pipe(Context.pick(DurableAgentRuntime, SubmissionLedger, WakeScheduler));
257
+ const hostServices = services.pipe(Context.pick(DurableAgentRuntime, NodeDurableAgentRuntimeConfig, MessageDeliveryStore));
258
+ const host = yield* makeHost(Effect.contextWith((live) => runNodeWorkerDispatch(config.workerConcurrency).pipe(Effect.setContext(Context.merge(applicationInvocationContext(live), workerServices))))).pipe(Effect.provide(hostServices));
259
+ return services.pipe(Context.pick(DurableAgentRuntime, ThreadReader, NodeDurableAgentRuntimeConfig, MessageDeliveryStore), Context.add(NodeDurableHost, host));
260
+ }));
261
+ /**
262
+ * Supervise the host's existing workers without starting another pool. Use with
263
+ * `Effect.provide(HostLive)` and `NodeRuntime.runMain`; race it with a server Effect when
264
+ * the same process also serves requests. Unlike `Layer.launch`, this observes worker failures.
265
+ */
266
+ const run = Effect.gen(function* () {
267
+ return yield* (yield* NodeDurableHost).run;
268
+ });
269
+ export { run as a, layer as i, NodeDurableHost as n, NodeAdmission as o, NodeDurableHost_exports as r, makeNodePreparedInputAdmission as s, AdmissionClosed as t };
270
+
271
+ //# sourceMappingURL=NodeDurableHost-BztkzCGh.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"NodeDurableHost-BztkzCGh.mjs","names":[],"sources":["../src/internal/message-delivery.ts","../src/internal/prepared-admission.ts","../src/internal/worker-dispatch.ts","../src/NodeDurableHost.ts"],"sourcesContent":["import {\n MessageDeliveryDriver,\n type MessageDeliveryFailure,\n MessageDeliveryStore,\n} from '@systemfsoftware/agent/message-delivery'\nimport * as Cause from 'effect/Cause'\nimport * as Clock from 'effect/Clock'\nimport * as Effect from 'effect/Effect'\nimport * as Exit from 'effect/Exit'\nimport * as Option from 'effect/Option'\n\nconst reportFailure = (cause: Cause.Cause<MessageDeliveryFailure>): Effect.Effect<void> =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.interrupt\n : Effect.logWarning('Node message delivery pass failed').pipe(\n Effect.annotateLogs({\n failureTag: Option.match(Cause.findErrorOption(cause), {\n onNone: () => 'Defect',\n onSome: (failure) => failure._tag,\n }),\n }),\n )\n\n/** Caller-owned loop. Indexed scans repair absent hints even when both Threads have settled. */\nexport const runNodeMessageDeliveries = Effect.fnUntraced(function*(scanInterval: number) {\n const driver = yield* MessageDeliveryDriver\n const store = yield* MessageDeliveryStore\n\n while (true) {\n const pass = yield* driver.runDue().pipe(Effect.exit)\n\n if (Exit.isFailure(pass)) {\n yield* reportFailure(pass.cause)\n yield* Effect.sleep(scanInterval)\n continue\n }\n\n const deadline = yield* store.nextDeadline().pipe(Effect.exit)\n\n if (Exit.isFailure(deadline)) {\n yield* reportFailure(deadline.cause)\n yield* Effect.sleep(scanInterval)\n continue\n }\n\n const nowMillis = yield* Clock.currentTimeMillis\n\n const delay = deadline.value === null\n ? scanInterval\n : Math.max(1, Math.min(deadline.value - nowMillis, scanInterval))\n\n yield* Effect.sleep(delay)\n }\n})\n","import { type DurableSubmitAgent } from '@systemfsoftware/agent/durable-agent-runtime'\nimport { type AgentId } from '@systemfsoftware/agent/identifiers'\nimport {\n PreparedInputAdmission,\n PreparedInputRefused,\n PreparedInputRetryable,\n} from '@systemfsoftware/agent/prepared-input-admission'\nimport { PersistedJson } from '@systemfsoftware/agent/records'\nimport { ScheduleStorageError } from '@systemfsoftware/agent/schedule'\nimport * as Context from 'effect/Context'\nimport * as Effect from 'effect/Effect'\n\nimport { type NodeDurableHost } from '../NodeDurableHost'\n\nconst passthroughSubmitAgent = (agentId: AgentId): DurableSubmitAgent<typeof PersistedJson> => ({\n definition: { id: agentId, input: PersistedJson },\n})\n\nconst ambiguous = (): PreparedInputRetryable => PreparedInputRetryable.make({ reason: 'ambiguous' })\n\nconst corrupt = (operation: string): ScheduleStorageError => ScheduleStorageError.make({ operation, reason: 'corrupt' })\n\n/** Host-owned admission gate, available while the host's worker pool is being assembled. */\nexport class NodeAdmission extends Context.Service<\n NodeAdmission,\n Pick<NodeDurableHost['Service'], 'submit' | 'submissionStatus'>\n>()('@effect-agent/platform-node/internal/NodeAdmission') {}\n\n/** Acquire the gated source once; worker callers cannot replace its admission authority. */\nexport const makeNodePreparedInputAdmission = Effect.gen(function*() {\n const host = yield* NodeAdmission\n\n return PreparedInputAdmission.of({\n submissionStatus: (receipt) =>\n host\n .submissionStatus(receipt)\n .pipe(Effect.mapError(() => PreparedInputRetryable.make({ reason: 'storage' }))),\n submit: (envelope) =>\n host\n .submit(passthroughSubmitAgent(envelope.agentId), envelope.input, {\n threadId: envelope.threadId,\n principal: envelope.deliveryPrincipal,\n idempotencyKey: envelope.admissionKey,\n ...(envelope.admissionGroup === undefined\n ? {}\n : { admissionGroup: envelope.admissionGroup }),\n ...(envelope.admissionFence === undefined\n ? {}\n : { admissionFence: envelope.admissionFence }),\n ...(envelope.workerAdmission === undefined\n ? {}\n : { workerAdmission: envelope.workerAdmission }),\n ...(envelope.messageAdmission === undefined\n ? {}\n : { messageAdmission: envelope.messageAdmission }),\n definitions: envelope.definitions,\n })\n .pipe(\n Effect.catchTags({\n AdmissionClosed: () => Effect.fail(PreparedInputRetryable.make({ reason: 'host-closed' })),\n AgentInputError: () => Effect.fail(corrupt('prepared admission input')),\n AdmissionConflict: () => Effect.fail(corrupt('prepared admission conflict')),\n DigestError: () => Effect.fail(ambiguous()),\n AdmissionPolicyError: (error) =>\n error.reason === 'refused'\n ? PreparedInputRefused.make({ code: error.code })\n : PreparedInputRetryable.make({\n reason: error.reason === 'occupied' ? 'capacity' : 'storage',\n }),\n LedgerError: () => PreparedInputRetryable.make({ reason: 'storage' }),\n ThreadStoreError: () => Effect.fail(ambiguous()),\n ThreadNotMaterialized: () => Effect.fail(ambiguous()),\n AppendConflict: () => Effect.fail(ambiguous()),\n OwnershipLost: () => Effect.fail(ambiguous()),\n DurableRuntimeFailpointError: () => Effect.fail(ambiguous()),\n }),\n ),\n })\n})\n","import type { DurableBindingFailure } from '@systemfsoftware/agent/agent-registration'\nimport { DurableAgentRuntime, type DurableWorkerFailure } from '@systemfsoftware/agent/durable-agent-runtime'\nimport type { ThreadId } from '@systemfsoftware/agent/identifiers'\nimport { WakeScheduler } from '@systemfsoftware/agent/wake-scheduler'\nimport * as Effect from 'effect/Effect'\nimport * as Option from 'effect/Option'\nimport * as Queue from 'effect/Queue'\nimport * as Stream from 'effect/Stream'\n\nconst PENDING_CAPACITY = 1_024\n\ntype DispatchState = 'pending' | 'active' | 'dirty'\n\n/**\n * One discovery path feeds bounded concurrent Thread drains. Hints carry no authority:\n * the runtime still claims, fences, parks and releases every Attempt. Concurrency has\n * already been validated by the host configuration.\n */\nexport const runNodeWorkerDispatch = (\n concurrency: number,\n): Effect.Effect<\n void,\n DurableWorkerFailure | DurableBindingFailure,\n DurableAgentRuntime | WakeScheduler\n> =>\n Effect.scoped(\n Effect.gen(function*() {\n const runtime = yield* DurableAgentRuntime\n const wake = yield* WakeScheduler\n const pending = yield* Queue.bounded<ThreadId>(PENDING_CAPACITY)\n const states = new Map<ThreadId, DispatchState>()\n\n yield* Effect.addFinalizer(() => Queue.shutdown(pending))\n\n const enqueue = Effect.fnUntraced(function*(threadId: ThreadId) {\n const offer = yield* Effect.sync(() => {\n const state = states.get(threadId)\n\n if (state === 'pending' || state === 'dirty') return false\n if (state === 'active') {\n states.set(threadId, 'dirty')\n\n return false\n }\n\n states.set(threadId, 'pending')\n\n return true\n })\n\n // The single ingress can reserve at most one entry beyond queue capacity.\n // Backpressure retains scan tails instead of repeatedly dropping later lanes.\n if (offer) yield* Queue.offer(pending, threadId)\n })\n\n const initial = Stream.paginate(undefined, (afterThreadId: ThreadId | undefined) =>\n runtime\n .discoverWorkThreads({\n limit: 32,\n ...(afterThreadId === undefined ? {} : { afterThreadId }),\n })\n .pipe(\n Effect.map(\n (page): readonly [ReadonlyArray<ThreadId>, Option.Option<ThreadId | undefined>] => [\n page.threadIds,\n page.afterThreadId === undefined ? Option.none() : Option.some(page.afterThreadId),\n ],\n ),\n ))\n\n // Merge acquires both streams concurrently; it does not guarantee that the wake\n // subscription precedes the initial read. The scheduler's fallback repairs lost hints.\n // Initial completion is normal; wake completion must stop the entire pool.\n const ingress = Stream.merge(initial, wake.wakes, { haltStrategy: 'right' }).pipe(\n Stream.runForEach(enqueue),\n )\n\n const consume = Effect.gen(function*() {\n const threadId = yield* Queue.take(pending)\n\n yield* Effect.sync(() => states.set(threadId, 'active'))\n\n let again = true\n let recoveryCursor: string | undefined\n\n while (again) {\n const recovered = yield* runtime.runRecovery({\n threadId,\n ...(recoveryCursor === undefined ? {} : { cursor: recoveryCursor }),\n })\n\n const blocked = recovered.blocked[0]\n\n if (blocked !== undefined) return yield* blocked\n recoveryCursor = recovered.cursor\n yield* runtime.processThreadResolved(threadId)\n again = yield* Effect.sync(() => {\n if (states.get(threadId) === 'dirty' || recoveryCursor !== undefined) {\n states.set(threadId, 'active')\n\n return true\n }\n\n states.delete(threadId)\n\n return false\n })\n // Re-drain inline: workers re-enqueuing into a full queue can all deadlock.\n // This retains the runtime's drain-to-empty fairness, including parked returns.\n }\n }).pipe(Effect.forever)\n\n // Any exit stops and joins every other participant; no detached producer or worker.\n yield* Effect.raceAllFirst([ingress, ...Array.from({ length: concurrency }, () => consume)])\n }),\n )\n","import * as NodeCrypto from '@effect/platform-node/NodeCrypto'\nimport {\n type AgentRegistration,\n type DurableBindingFailure,\n type ResolvedBinding,\n} from '@systemfsoftware/agent/agent-registration'\nimport {\n type DurableAbortFailure,\n DurableAgentRuntime,\n type DurableAwaitFailure,\n type DurableObserveOptions,\n type DurableSubmitAgent,\n type DurableSubmitFailure,\n type DurableSubmitOptions,\n type DurableWorkerFailure,\n type Receipt,\n type RecoveryBlocked,\n type RecoveryReport,\n} from '@systemfsoftware/agent/durable-agent-runtime'\nimport {\n MessageDeliveryDriver,\n type MessageDeliveryError,\n MessageDeliveryStore,\n} from '@systemfsoftware/agent/message-delivery'\nimport { type OperationDenied } from '@systemfsoftware/agent/operation-authorizer'\nimport { PreparedInputAdmission } from '@systemfsoftware/agent/prepared-input-admission'\nimport { type CanonicalRecordEnvelope } from '@systemfsoftware/agent/records'\nimport {\n type AbortCommand,\n type AbortIntent,\n type Settlement,\n SubmissionLedger,\n} from '@systemfsoftware/agent/submission-ledger'\nimport { type ThreadNotMaterialized, ThreadReader, type ThreadStoreError } from '@systemfsoftware/agent/thread-store'\nimport { MAX_RECOVERY_WORK_ITEMS } from '@systemfsoftware/agent/thread-work'\nimport { WakeScheduler } from '@systemfsoftware/agent/wake-scheduler'\nimport * as Context from 'effect/Context'\nimport * as Effect from 'effect/Effect'\nimport * as Fiber from 'effect/Fiber'\nimport * as Layer from 'effect/Layer'\nimport * as Ref from 'effect/Ref'\nimport * as Schema from 'effect/Schema'\nimport type * as Stream from 'effect/Stream'\n\nimport { applicationInvocationContext } from './internal/application-context'\nimport { ExclusiveSqliteHost } from './internal/exclusive-host'\nimport { runNodeMessageDeliveries } from './internal/message-delivery'\nimport { makeNodePreparedInputAdmission, NodeAdmission } from './internal/prepared-admission'\nimport { runNodeWorkerDispatch } from './internal/worker-dispatch'\nimport {\n NodeDurableAgentRuntime,\n NodeDurableAgentRuntimeConfig,\n type NodeDurableAgentRuntimeOptions,\n} from './NodeDurableAgentRuntime'\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.fnUntraced(function*(\n managedWorkers?: Effect.Effect<void, DurableWorkerFailure | DurableBindingFailure>,\n) {\n const runtime = yield* DurableAgentRuntime\n const config = yield* NodeDurableAgentRuntimeConfig\n\n // Startup gate (deployment §5, plan §host): configuration decoding and storage compatibility\n // already gated this Layer's dependencies; the last gate before admission opens is recovering\n // EVERY nonterminal Submission. Work needing a live Agent Binding is reported `deferred` and\n // stays a visible obligation for `runWorkers`; submissions parked on an Unknown Outcome are\n // reported `unknown` and wait for the authorized `resolveUnknown` path (DUR-017) — they consume\n // no worker permit while the settlement obligation stays owed and later input can run.\n let recoveryCursor: string | undefined\n let startupReports: ReadonlyArray<RecoveryReport> = []\n\n do {\n const recovered = yield* runtime.runRecovery(\n recoveryCursor === undefined ? undefined : { cursor: recoveryCursor },\n )\n\n // This host opens one shared pool; every selected owner must pass the readiness gate.\n const blocked = recovered.blocked[0]\n\n if (blocked !== undefined) return yield* blocked\n startupReports = [...startupReports, ...recovered.reports].slice(-MAX_RECOVERY_WORK_ITEMS)\n recoveryCursor = recovered.cursor\n } while (recoveryCursor !== undefined)\n\n const admission = yield* Ref.make(true)\n\n const requireAdmission: Effect.Effect<void, AdmissionClosed> = Ref.get(admission).pipe(\n Effect.flatMap((open) =>\n open\n ? Effect.void\n : Effect.fail(\n AdmissionClosed.make({ message: 'The host is shutting down; admission is closed.' }),\n )\n ),\n )\n\n const submit = <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema['Type'],\n options: DurableSubmitOptions,\n ): Effect.Effect<\n Receipt,\n AdmissionClosed | DurableSubmitFailure,\n InputSchema['EncodingServices']\n > => requireAdmission.pipe(Effect.andThen(runtime.submit(agent, input, options)))\n\n const deliveryServices = (yield* Effect.context<MessageDeliveryStore>()).pipe(\n Context.pick(MessageDeliveryStore),\n )\n\n const deliveryContext = yield* Layer.build(\n MessageDeliveryDriver.layer({\n batchSize: 100,\n concurrency: Math.min(config.workerConcurrency, 32),\n }).pipe(\n Layer.provide(NodeCrypto.layer),\n Layer.provide(\n Layer.effect(PreparedInputAdmission, makeNodePreparedInputAdmission).pipe(\n Layer.provide(\n Layer.succeed(NodeAdmission, { submit, submissionStatus: runtime.submissionStatus }),\n ),\n ),\n ),\n ),\n )\n\n const runDeliveries = Effect.contextWith((live: Context.Context<never>) =>\n runNodeMessageDeliveries(config.wakeScanInterval).pipe(\n Effect.setContext(\n Context.mergeAll(applicationInvocationContext(live), deliveryServices, deliveryContext),\n ),\n )\n )\n\n const withDeliveries = <A, E, R>(worker: Effect.Effect<A, E, R>): Effect.Effect<void, E, R> =>\n Effect.scoped(\n // Either side exiting stops and joins the other; delivery interruption cannot leave\n // an apparently healthy worker pool running without message recovery.\n Effect.raceFirst(worker, runDeliveries).pipe(Effect.asVoid),\n )\n\n const runWorkers = <A, E, R>(worker: Effect.Effect<A, E, R>): Effect.Effect<void, E, R> =>\n withDeliveries(\n Effect.forEach(\n Array.from({ length: config.workerConcurrency }, (_, index) => index),\n () => worker,\n { concurrency: 'unbounded', discard: true },\n ),\n )\n\n // Managed hosts dispatch each lane once. Bare host layers retain their existing service\n // requirements and generic worker-loop composition.\n const runResolvedWorkers = managedWorkers === undefined\n ? runWorkers(runtime.runResolvedWorker)\n : withDeliveries(managedWorkers)\n\n const run = managedWorkers !== undefined\n ? Fiber.join(\n yield* runResolvedWorkers.pipe(\n Effect.onExit(() => Ref.set(admission, false)),\n Effect.forkScoped,\n ),\n )\n : runResolvedWorkers\n\n // Register after the worker fiber: close admission, interrupt/join workers, close\n // local owner generations, then close storage and captured application services.\n yield* Effect.addFinalizer(() => Ref.set(admission, false))\n\n return NodeDurableHost.of({\n startupRecovery: startupReports,\n admissionOpen: Ref.get(admission),\n submit,\n awaitSettlement: runtime.awaitSettlement,\n submissionStatus: runtime.submissionStatus,\n observe: runtime.observe,\n abort: runtime.abort,\n runWorkers,\n run,\n runResolvedWorkers: run,\n })\n})\n\n/**\n * Operational host service. Prefer the module's `layer` and `run` for managed workers.\n * The static constructors on this class retain explicit, manual worker ownership.\n * Use the accompanying `DurableAgentRuntime` service for inspection and recovery operations.\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 the complete native work inventory passed recovery BEFORE admission opened.\n * `startupRecovery` retains the last bounded page of Submission decisions.\n *\n * Shutdown runs in reverse Layer order when the owning Scope closes: `submit` starts refusing\n * with `AdmissionClosed` first, then workers stop and local owner generations close before\n * SQLite resources. Accepted work remains recoverable after forced termination (DEPLOY-006).\n */\nexport class NodeDurableHost extends Context.Service<\n NodeDurableHost,\n {\n /**\n * The last 32 Submission decisions executed (or deferred) at startup. Earlier pages are\n * released as reconciliation advances, so startup memory does not grow with Thread count.\n * Reports with the `unknown` disposition identify parked Submissions with Unknown Outcomes.\n * They retain their settlement obligation while later input can run; authorized resolution\n * or abort advances the parked Submission.\n */\n readonly startupRecovery: ReadonlyArray<RecoveryReport>\n /** Admission-role readiness (deployment §7): true until shutdown begins. */\n readonly admissionOpen: Effect.Effect<boolean>\n /** Observe the managed worker pool, preserving its failure. Manual hosts start their pool here. */\n readonly run: Effect.Effect<void, DurableWorkerFailure | DurableBindingFailure>\n /** `DurableAgentRuntime.submit` behind the host admission gate. */\n readonly submit: <InputSchema extends Schema.Top>(\n agent: DurableSubmitAgent<InputSchema>,\n input: InputSchema['Type'],\n options: DurableSubmitOptions,\n ) => Effect.Effect<\n Receipt,\n AdmissionClosed | DurableSubmitFailure,\n InputSchema['EncodingServices']\n >\n readonly submissionStatus: DurableAgentRuntime['Service']['submissionStatus']\n readonly awaitSettlement: (receipt: Receipt) => Effect.Effect<Settlement, DurableAwaitFailure>\n readonly observe: (\n receipt: Receipt,\n options?: DurableObserveOptions,\n ) => Stream.Stream<\n CanonicalRecordEnvelope,\n ThreadStoreError | ThreadNotMaterialized | OperationDenied\n >\n readonly abort: (command: AbortCommand) => Effect.Effect<AbortIntent, DurableAbortFailure>\n /**\n * Run `workerConcurrency` copies of the given worker effect (typically\n * `DurableAgentRuntime.runResolvedWorker`) until the caller's Scope interrupts them. The\n * same Scope drives pending message admission and settlement observation independently\n * of Submission liveness. The host never forks daemon fibers.\n */\n readonly runWorkers: <A, E, R>(worker: Effect.Effect<A, E, R>) => Effect.Effect<void, E, R>\n /**\n * Run `workerConcurrency` copies of `DurableAgentRuntime.runResolvedWorker` over the host's\n * registered Bindings: every claimed head resolves the current Binding for its stable\n * agentId, so one bounded pool serves parent and attached-child lanes.\n * Hosts built with the module-level `layer` instead join their existing pool, which\n * dispatches distinct Thread lanes through one bounded queue.\n */\n readonly runResolvedWorkers: Effect.Effect<void, DurableWorkerFailure | DurableBindingFailure>\n }\n>()('@effect-agent/platform-node/NodeDurableHost') {\n /**\n * Compile typed registrations and acquire the complete host in one Layer Scope.\n * Node supplies Digest and SecureRandom; model, tool, instruction, and schema services remain required.\n * Startup recovery and shutdown gates are unchanged. Workers start only when the caller\n * runs runResolvedWorkers; this constructor never starts a background worker.\n */\n static layerRegistered<\n const Entries extends ReadonlyArray<AgentRegistration>,\n ContextError = never,\n ContextRequirements = never,\n AuthorizationError = never,\n AuthorizationRequirements = never,\n ReconcilerError = never,\n ReconcilerRequirements = never,\n >(\n registrations: Entries,\n options: NodeDurableAgentRuntimeOptions<\n ContextError,\n ContextRequirements,\n AuthorizationError,\n AuthorizationRequirements,\n ReconcilerError,\n ReconcilerRequirements\n >,\n ) {\n return NodeDurableHost.layer.pipe(\n Layer.provideMerge(NodeDurableAgentRuntime.layerRegistered(registrations, options)),\n )\n }\n\n /**\n * Host gates over an assembled `NodeDurableAgentRuntime` stack. The runtime Layer owns\n * executable registrations; omission registers no Agents, so resolved work fails closed.\n */\n static readonly layer: Layer.Layer<\n NodeDurableHost,\n DurableWorkerFailure | RecoveryBlocked | MessageDeliveryError,\n DurableAgentRuntime | NodeDurableAgentRuntimeConfig | MessageDeliveryStore\n > = Layer.effect(NodeDurableHost)(makeHost())\n\n /** The complete DN host: `NodeDurableAgentRuntime.layer(options)` plus the host lifecycle gates. */\n static layerStack<\n ContextError = never,\n ContextRequirements = never,\n AuthorizationError = never,\n AuthorizationRequirements = never,\n ReconcilerError = never,\n ReconcilerRequirements = never,\n >(\n options:\n & NodeDurableAgentRuntimeOptions<\n ContextError,\n ContextRequirements,\n AuthorizationError,\n AuthorizationRequirements,\n ReconcilerError,\n ReconcilerRequirements\n >\n & { readonly bindings?: ReadonlyArray<ResolvedBinding> },\n ) {\n const { bindings = [], ...runtimeOptions } = options\n\n return NodeDurableHost.layer.pipe(\n Layer.provideMerge(NodeDurableAgentRuntime.layerWithBindings(bindings, runtimeOptions)),\n )\n }\n}\n\n/**\n * Acquire a complete Node host and start one bounded, scoped worker pool after recovery.\n * Own the SQLite file exclusively until the host and its storage close. A second connection\n * fails construction. Process death releases the file lock; a replacement acquires it before\n * recovering retained work with fresh local generations. Use this host's services for live inspection.\n * Provide model, tool, instruction, and schema dependencies to this Layer. Reusing the Layer\n * shares the same pool. A worker failure closes admission; observe it with `run` at the process\n * boundary so the application exits and releases the host instead of remaining idle.\n */\nexport const layer = <\n const Entries extends ReadonlyArray<AgentRegistration>,\n ContextError = never,\n ContextRequirements = never,\n AuthorizationError = never,\n AuthorizationRequirements = never,\n ReconcilerError = never,\n ReconcilerRequirements = never,\n>(\n registrations: Entries,\n options: NodeDurableAgentRuntimeOptions<\n ContextError,\n ContextRequirements,\n AuthorizationError,\n AuthorizationRequirements,\n ReconcilerError,\n ReconcilerRequirements\n >,\n) =>\n Layer.effectContext(\n Effect.gen(function*() {\n // The runtime compiles registrations in application Context before acquiring storage.\n const services = yield* Layer.build(\n NodeDurableAgentRuntime.layerRegistered(registrations, options).pipe(\n Layer.provide(Layer.succeed(ExclusiveSqliteHost, true)),\n ),\n )\n\n const config = Context.get(services, NodeDurableAgentRuntimeConfig)\n\n const workerServices = services.pipe(\n Context.pick(DurableAgentRuntime, SubmissionLedger, WakeScheduler),\n )\n\n const hostServices = services.pipe(\n Context.pick(DurableAgentRuntime, NodeDurableAgentRuntimeConfig, MessageDeliveryStore),\n )\n\n const host = yield* makeHost(\n Effect.contextWith((live: Context.Context<never>) =>\n runNodeWorkerDispatch(config.workerConcurrency).pipe(\n Effect.setContext(Context.merge(applicationInvocationContext(live), workerServices)),\n )\n ),\n ).pipe(Effect.provide(hostServices))\n\n // Export actual capabilities: canonical reads and the separately owned delivery queue.\n // Raw SQL, canonical writes and submission ownership remain private.\n return services.pipe(\n Context.pick(\n DurableAgentRuntime,\n ThreadReader,\n NodeDurableAgentRuntimeConfig,\n MessageDeliveryStore,\n ),\n Context.add(NodeDurableHost, host),\n )\n }),\n )\n\n/**\n * Supervise the host's existing workers without starting another pool. Use with\n * `Effect.provide(HostLive)` and `NodeRuntime.runMain`; race it with a server Effect when\n * the same process also serves requests. Unlike `Layer.launch`, this observes worker failures.\n */\nexport const run = Effect.gen(function*() {\n const host = yield* NodeDurableHost\n\n return yield* host.run\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAWA,MAAM,iBAAiB,UACrB,MAAM,kBAAkB,KAAK,IACzB,OAAO,YACP,OAAO,WAAW,mCAAmC,CAAC,CAAC,KACvD,OAAO,aAAa,EAClB,YAAY,OAAO,MAAM,MAAM,gBAAgB,KAAK,GAAG;CACrD,cAAc;CACd,SAAS,YAAY,QAAQ;AAC/B,CAAC,EACH,CAAC,CACH;;AAGJ,MAAa,2BAA2B,OAAO,WAAW,WAAU,cAAsB;CACxF,MAAM,SAAS,OAAO;CACtB,MAAM,QAAQ,OAAO;CAErB,OAAO,MAAM;EACX,MAAM,OAAO,OAAO,OAAO,OAAO,CAAC,CAAC,KAAK,OAAO,IAAI;EAEpD,IAAI,KAAK,UAAU,IAAI,GAAG;GACxB,OAAO,cAAc,KAAK,KAAK;GAC/B,OAAO,OAAO,MAAM,YAAY;GAChC;EACF;EAEA,MAAM,WAAW,OAAO,MAAM,aAAa,CAAC,CAAC,KAAK,OAAO,IAAI;EAE7D,IAAI,KAAK,UAAU,QAAQ,GAAG;GAC5B,OAAO,cAAc,SAAS,KAAK;GACnC,OAAO,OAAO,MAAM,YAAY;GAChC;EACF;EAEA,MAAM,YAAY,OAAO,MAAM;EAE/B,MAAM,QAAQ,SAAS,UAAU,OAC7B,eACA,KAAK,IAAI,GAAG,KAAK,IAAI,SAAS,QAAQ,WAAW,YAAY,CAAC;EAElE,OAAO,OAAO,MAAM,KAAK;CAC3B;AACF,CAAC;;ACvCD,MAAM,0BAA0B,aAAgE,EAC9F,YAAY;CAAE,IAAI;CAAS,OAAO;AAAc,EAClD;AAEA,MAA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CAAC,KAC9D,MAAM,QAAQ,MAAM,QAAQ,qBAAqB,IAAI,CAAC,CACxD,CACF;CAEA,MAAM,SAAS,QAAQ,IAAI,UAAU,6BAA6B;CAElE,MAAM,iBAAiB,SAAS,KAC9B,QAAQ,KAAK,qBAAqB,kBAAkB,aAAa,CACnE;CAEA,MAAM,eAAe,SAAS,KAC5B,QAAQ,KAAK,qBAAqB,+BAA+B,oBAAoB,CACvF;CAEA,MAAM,OAAO,OAAO,SAClB,OAAO,aAAa,SAClB,sBAAsB,OAAO,iBAAiB,CAAC,CAAC,KAC9C,OAAO,WAAW,QAAQ,MAAM,6BAA6B,IAAI,GAAG,cAAc,CAAC,CACrF,CACF,CACF,CAAC,CAAC,KAAK,OAAO,QAAQ,YAAY,CAAC;CAInC,OAAO,SAAS,KACd,QAAQ,KACN,qBACA,cACA,+BACA,oBACF,GACA,QAAQ,IAAI,iBAAiB,IAAI,CACnC;AACF,CAAC,CACH;;;;;;AAOF,MAAa,MAAM,OAAO,IAAI,aAAY;CAGxC,OAAO,QAAO,OAFM,gBAAA,CAED;AACrB,CAAC"}
@@ -0,0 +1,153 @@
1
+ import { a as NodeDurableAgentRuntimeOptions, c as NodePlatformConfigError, n as NodeDurableAgentRuntimeConfig } from "./NodeDurableAgentRuntime-CUrOl39W.mjs";
2
+ import { AgentRegistration, DurableBindingFailure, ResolvedBinding } from "@systemfsoftware/agent/agent-registration";
3
+ import { DurableAbortFailure, DurableAgentRuntime, DurableAwaitFailure, DurableObserveOptions, DurableSubmitAgent, DurableSubmitFailure, DurableSubmitOptions, DurableWorkerFailure, Receipt, RecoveryBlocked, RecoveryReport } from "@systemfsoftware/agent/durable-agent-runtime";
4
+ import { MessageDeliveryError, MessageDeliveryStore } from "@systemfsoftware/agent/message-delivery";
5
+ import { OperationDenied } from "@systemfsoftware/agent/operation-authorizer";
6
+ import { CanonicalRecordEnvelope } from "@systemfsoftware/agent/records";
7
+ import { AbortCommand, AbortIntent, Settlement, SubmissionLedger } from "@systemfsoftware/agent/submission-ledger";
8
+ import { ThreadNotMaterialized, ThreadReader, ThreadStoreError } from "@systemfsoftware/agent/thread-store";
9
+ import { WakeScheduler } from "@systemfsoftware/agent/wake-scheduler";
10
+ import * as Context from "effect/Context";
11
+ import * as Effect from "effect/Effect";
12
+ import * as Layer from "effect/Layer";
13
+ import * as Schema from "effect/Schema";
14
+ import * as Stream from "effect/Stream";
15
+ declare namespace NodeDurableHost_d_exports {
16
+ export { AdmissionClosed, NodeDurableHost, layer, run };
17
+ }
18
+ declare const AdmissionClosed_base: Schema.Class<AdmissionClosed, Schema.TaggedStruct<"AdmissionClosed", {
19
+ readonly message: Schema.String;
20
+ }>, import("effect/Cause").YieldableError>;
21
+ /**
22
+ * Admission is not open on this host: it is shutting down (deployment §6 step 1, DEPLOY-005).
23
+ * Accepted work is unaffected — only NEW admissions are refused.
24
+ */
25
+ declare class AdmissionClosed extends AdmissionClosed_base {}
26
+ declare const NodeDurableHost_base: Context.ServiceClass<NodeDurableHost, "@effect-agent/platform-node/NodeDurableHost", {
27
+ /**
28
+ * The last 32 Submission decisions executed (or deferred) at startup. Earlier pages are
29
+ * released as reconciliation advances, so startup memory does not grow with Thread count.
30
+ * Reports with the `unknown` disposition identify parked Submissions with Unknown Outcomes.
31
+ * They retain their settlement obligation while later input can run; authorized resolution
32
+ * or abort advances the parked Submission.
33
+ */
34
+ readonly startupRecovery: ReadonlyArray<RecoveryReport>;
35
+ /** Admission-role readiness (deployment §7): true until shutdown begins. */
36
+ readonly admissionOpen: Effect.Effect<boolean>;
37
+ /** Observe the managed worker pool, preserving its failure. Manual hosts start their pool here. */
38
+ readonly run: Effect.Effect<void, DurableWorkerFailure | DurableBindingFailure>;
39
+ /** `DurableAgentRuntime.submit` behind the host admission gate. */
40
+ readonly submit: <InputSchema extends Schema.Top>(agent: DurableSubmitAgent<InputSchema>, input: InputSchema['Type'], options: DurableSubmitOptions) => Effect.Effect<Receipt, AdmissionClosed | DurableSubmitFailure, InputSchema['EncodingServices']>;
41
+ readonly submissionStatus: DurableAgentRuntime['Service']['submissionStatus'];
42
+ readonly awaitSettlement: (receipt: Receipt) => Effect.Effect<Settlement, DurableAwaitFailure>;
43
+ readonly observe: (receipt: Receipt, options?: DurableObserveOptions) => Stream.Stream<CanonicalRecordEnvelope, ThreadStoreError | ThreadNotMaterialized | OperationDenied>;
44
+ readonly abort: (command: AbortCommand) => Effect.Effect<AbortIntent, DurableAbortFailure>;
45
+ /**
46
+ * Run `workerConcurrency` copies of the given worker effect (typically
47
+ * `DurableAgentRuntime.runResolvedWorker`) until the caller's Scope interrupts them. The
48
+ * same Scope drives pending message admission and settlement observation independently
49
+ * of Submission liveness. The host never forks daemon fibers.
50
+ */
51
+ readonly runWorkers: <A, E, R>(worker: Effect.Effect<A, E, R>) => Effect.Effect<void, E, R>;
52
+ /**
53
+ * Run `workerConcurrency` copies of `DurableAgentRuntime.runResolvedWorker` over the host's
54
+ * registered Bindings: every claimed head resolves the current Binding for its stable
55
+ * agentId, so one bounded pool serves parent and attached-child lanes.
56
+ * Hosts built with the module-level `layer` instead join their existing pool, which
57
+ * dispatches distinct Thread lanes through one bounded queue.
58
+ */
59
+ readonly runResolvedWorkers: Effect.Effect<void, DurableWorkerFailure | DurableBindingFailure>;
60
+ }>;
61
+ /**
62
+ * Operational host service. Prefer the module's `layer` and `run` for managed workers.
63
+ * The static constructors on this class retain explicit, manual worker ownership.
64
+ * Use the accompanying `DurableAgentRuntime` service for inspection and recovery operations.
65
+ *
66
+ * Startup gates run during Layer construction, so the service existing implies readiness:
67
+ * configuration was schema-decoded, the SQLite file passed the exact-version compatibility check,
68
+ * and the complete native work inventory passed recovery BEFORE admission opened.
69
+ * `startupRecovery` retains the last bounded page of Submission decisions.
70
+ *
71
+ * Shutdown runs in reverse Layer order when the owning Scope closes: `submit` starts refusing
72
+ * with `AdmissionClosed` first, then workers stop and local owner generations close before
73
+ * SQLite resources. Accepted work remains recoverable after forced termination (DEPLOY-006).
74
+ */
75
+ declare class NodeDurableHost extends NodeDurableHost_base {
76
+ /**
77
+ * Compile typed registrations and acquire the complete host in one Layer Scope.
78
+ * Node supplies Digest and SecureRandom; model, tool, instruction, and schema services remain required.
79
+ * Startup recovery and shutdown gates are unchanged. Workers start only when the caller
80
+ * runs runResolvedWorkers; this constructor never starts a background worker.
81
+ */
82
+ static layerRegistered<const Entries extends ReadonlyArray<AgentRegistration>, ContextError = never, ContextRequirements = never, AuthorizationError = never, AuthorizationRequirements = never, ReconcilerError = never, ReconcilerRequirements = never>(registrations: Entries, options: NodeDurableAgentRuntimeOptions<ContextError, ContextRequirements, AuthorizationError, AuthorizationRequirements, ReconcilerError, ReconcilerRequirements>): Layer.Layer<import("effect/crypto/Aead").Aead | import("effect/crypto/Cipher").Cipher | import("effect/crypto/Digest").Digest | DurableAgentRuntime | import("@systemfsoftware/agent/durable-agent-runtime").DurableRuntimeConfig | import("effect/crypto/Kdf").Kdf | import("effect/crypto/KeyAgreement").KeyAgreement | import("effect/crypto/KeyWrap").KeyWrap | import("effect/crypto/Mac").Mac | MessageDeliveryStore | NodeDurableAgentRuntimeConfig | NodeDurableHost | import("@systemfsoftware/agent/run-storage").RunStorage | import("@systemfsoftware/agent/schedule").ScheduleStore | import("effect/crypto/SecureRandom").SecureRandom | import("@systemfsoftware/agent/settlement-publisher").SettlementPublisher | import("effect/crypto/Signature").Signature | import("effect/sql/SqlClient").SqlClient | import("@effect/sql-sqlite-node/SqliteClient").SqliteClient | import("@systemfsoftware/agent-storage-sqlite/sqlite-storage-config").SqliteStorageConfig | import("@systemfsoftware/agent-storage-sqlite/sqlite-storage-failpoint").SqliteStorageFailpoint | import("@systemfsoftware/agent/run-storage").StorageOwner | SubmissionLedger | import("@systemfsoftware/agent/thread-import").ThreadImport | ThreadReader | import("@systemfsoftware/agent/thread-store").ThreadStore | WakeScheduler, AuthorizationError | ContextError | ReconcilerError | MessageDeliveryError | NodePlatformConfigError | DurableWorkerFailure | import("@systemfsoftware/agent-storage-sqlite/sqlite-thread-store").SqliteStorageInitializationError, Exclude<Exclude<AuthorizationRequirements, import("effect/crypto/Aead").Aead | import("effect/crypto/Cipher").Cipher | import("effect/crypto/Digest").Digest | import("effect/crypto/Kdf").Kdf | import("effect/crypto/KeyAgreement").KeyAgreement | import("effect/crypto/KeyWrap").KeyWrap | import("effect/crypto/Mac").Mac | import("effect/crypto/SecureRandom").SecureRandom | import("effect/crypto/Signature").Signature>, import("effect/Scope").Scope> | Exclude<Exclude<ContextRequirements, import("effect/crypto/Aead").Aead | import("effect/crypto/Cipher").Cipher | import("effect/crypto/Digest").Digest | import("effect/crypto/Kdf").Kdf | import("effect/crypto/KeyAgreement").KeyAgreement | import("effect/crypto/KeyWrap").KeyWrap | import("effect/crypto/Mac").Mac | import("effect/crypto/SecureRandom").SecureRandom | import("effect/crypto/Signature").Signature>, import("effect/Scope").Scope> | Exclude<Exclude<ReconcilerRequirements, import("effect/crypto/Aead").Aead | import("effect/crypto/Cipher").Cipher | import("effect/crypto/Digest").Digest | import("effect/crypto/Kdf").Kdf | import("effect/crypto/KeyAgreement").KeyAgreement | import("effect/crypto/KeyWrap").KeyWrap | import("effect/crypto/Mac").Mac | import("effect/crypto/SecureRandom").SecureRandom | import("effect/crypto/Signature").Signature>, import("effect/Scope").Scope> | Exclude<Exclude<Entries[number] extends (infer T_3) ? T_3 extends Entries[number] ? T_3 extends unknown ? (("attemptLayer" extends keyof T_3 ? T_3[keyof T_3 & "attemptLayer"] : undefined) extends (infer T_4) ? T_4 extends ("attemptLayer" extends keyof T_3 ? T_3[keyof T_3 & "attemptLayer"] : undefined) ? T_4 extends ((context: import("@systemfsoftware/agent/agent-registration").AgentAttemptContext) => Layer.Layer<infer Provides, never, infer Requires>) ? Requires | Exclude<T_3 extends {
83
+ readonly agent: infer A extends import("@systemfsoftware/agent/agent-registration").ExecutableAgentBinding;
84
+ } ? import("@systemfsoftware/agent/durable-agent-runtime").DurableWorkerRequirements<A> : T_3 extends {
85
+ readonly agent: infer D extends import("@systemfsoftware/agent/agent").Definition<Schema.Top, Schema.Top, unknown, import("effect/ai/Toolkit").Any, import("@systemfsoftware/agent/agent").RunDispositionDeclaration<never, Schema.Top> | undefined, unknown, Schema.Top | undefined> & {
86
+ readonly instructions: import("@systemfsoftware/agent/agent").InstructionSource<never, unknown, unknown>;
87
+ readonly inputPrompt?: import("@systemfsoftware/agent/agent").InputPromptSource<never, unknown, unknown> | undefined;
88
+ };
89
+ readonly model: infer M extends import("@systemfsoftware/agent/agent-registration").ExecutableAgentBinding['model'];
90
+ } ? import("@systemfsoftware/agent/durable-agent-runtime").DurableWorkerRequirements<{
91
+ readonly definition: D;
92
+ readonly model: M;
93
+ }> : never, Provides> : T_3 extends {
94
+ readonly agent: infer A extends import("@systemfsoftware/agent/agent-registration").ExecutableAgentBinding;
95
+ } ? import("@systemfsoftware/agent/durable-agent-runtime").DurableWorkerRequirements<A> : T_3 extends {
96
+ readonly agent: infer D extends import("@systemfsoftware/agent/agent").Definition<Schema.Top, Schema.Top, unknown, import("effect/ai/Toolkit").Any, import("@systemfsoftware/agent/agent").RunDispositionDeclaration<never, Schema.Top> | undefined, unknown, Schema.Top | undefined> & {
97
+ readonly instructions: import("@systemfsoftware/agent/agent").InstructionSource<never, unknown, unknown>;
98
+ readonly inputPrompt?: import("@systemfsoftware/agent/agent").InputPromptSource<never, unknown, unknown> | undefined;
99
+ };
100
+ readonly model: infer M extends import("@systemfsoftware/agent/agent-registration").ExecutableAgentBinding['model'];
101
+ } ? import("@systemfsoftware/agent/durable-agent-runtime").DurableWorkerRequirements<{
102
+ readonly definition: D;
103
+ readonly model: M;
104
+ }> : never : never : never) | (("reporting" extends keyof T_3 ? T_3[keyof T_3 & "reporting"] : undefined) extends (infer T_5) ? T_5 extends ("reporting" extends keyof T_3 ? T_3[keyof T_3 & "reporting"] : undefined) ? T_5 extends readonly import("@systemfsoftware/agent/subagent-host").WorkerReporting<infer _E, infer R>[] ? Exclude<R, import("effect/Scope").Scope> : never : never : never) : never : never : never, import("effect/crypto/Aead").Aead | import("effect/crypto/Cipher").Cipher | import("effect/crypto/Digest").Digest | import("effect/crypto/Kdf").Kdf | import("effect/crypto/KeyAgreement").KeyAgreement | import("effect/crypto/KeyWrap").KeyWrap | import("effect/crypto/Mac").Mac | import("effect/crypto/SecureRandom").SecureRandom | import("effect/crypto/Signature").Signature>, import("effect/Scope").Scope>>;
105
+ /**
106
+ * Host gates over an assembled `NodeDurableAgentRuntime` stack. The runtime Layer owns
107
+ * executable registrations; omission registers no Agents, so resolved work fails closed.
108
+ */
109
+ static readonly layer: Layer.Layer<NodeDurableHost, DurableWorkerFailure | RecoveryBlocked | MessageDeliveryError, DurableAgentRuntime | NodeDurableAgentRuntimeConfig | MessageDeliveryStore>;
110
+ /** The complete DN host: `NodeDurableAgentRuntime.layer(options)` plus the host lifecycle gates. */
111
+ static layerStack<ContextError = never, ContextRequirements = never, AuthorizationError = never, AuthorizationRequirements = never, ReconcilerError = never, ReconcilerRequirements = never>(options: NodeDurableAgentRuntimeOptions<ContextError, ContextRequirements, AuthorizationError, AuthorizationRequirements, ReconcilerError, ReconcilerRequirements> & {
112
+ readonly bindings?: ReadonlyArray<ResolvedBinding>;
113
+ }): Layer.Layer<import("effect/crypto/Aead").Aead | import("effect/crypto/Cipher").Cipher | import("effect/crypto/Digest").Digest | DurableAgentRuntime | import("@systemfsoftware/agent/durable-agent-runtime").DurableRuntimeConfig | import("effect/crypto/Kdf").Kdf | import("effect/crypto/KeyAgreement").KeyAgreement | import("effect/crypto/KeyWrap").KeyWrap | import("effect/crypto/Mac").Mac | MessageDeliveryStore | NodeDurableAgentRuntimeConfig | NodeDurableHost | import("@systemfsoftware/agent/run-storage").RunStorage | import("@systemfsoftware/agent/schedule").ScheduleStore | import("effect/crypto/SecureRandom").SecureRandom | import("@systemfsoftware/agent/settlement-publisher").SettlementPublisher | import("effect/crypto/Signature").Signature | import("effect/sql/SqlClient").SqlClient | import("@effect/sql-sqlite-node/SqliteClient").SqliteClient | import("@systemfsoftware/agent-storage-sqlite/sqlite-storage-config").SqliteStorageConfig | import("@systemfsoftware/agent-storage-sqlite/sqlite-storage-failpoint").SqliteStorageFailpoint | import("@systemfsoftware/agent/run-storage").StorageOwner | SubmissionLedger | import("@systemfsoftware/agent/thread-import").ThreadImport | ThreadReader | import("@systemfsoftware/agent/thread-store").ThreadStore | WakeScheduler, AuthorizationError | ContextError | ReconcilerError | MessageDeliveryError | NodePlatformConfigError | DurableWorkerFailure | import("@systemfsoftware/agent-storage-sqlite/sqlite-thread-store").SqliteStorageInitializationError, Exclude<Exclude<AuthorizationRequirements, import("effect/crypto/Aead").Aead | import("effect/crypto/Cipher").Cipher | import("effect/crypto/Digest").Digest | import("effect/crypto/Kdf").Kdf | import("effect/crypto/KeyAgreement").KeyAgreement | import("effect/crypto/KeyWrap").KeyWrap | import("effect/crypto/Mac").Mac | import("effect/crypto/SecureRandom").SecureRandom | import("effect/crypto/Signature").Signature>, import("effect/Scope").Scope> | Exclude<Exclude<ContextRequirements, import("effect/crypto/Aead").Aead | import("effect/crypto/Cipher").Cipher | import("effect/crypto/Digest").Digest | import("effect/crypto/Kdf").Kdf | import("effect/crypto/KeyAgreement").KeyAgreement | import("effect/crypto/KeyWrap").KeyWrap | import("effect/crypto/Mac").Mac | import("effect/crypto/SecureRandom").SecureRandom | import("effect/crypto/Signature").Signature>, import("effect/Scope").Scope> | Exclude<Exclude<ReconcilerRequirements, import("effect/crypto/Aead").Aead | import("effect/crypto/Cipher").Cipher | import("effect/crypto/Digest").Digest | import("effect/crypto/Kdf").Kdf | import("effect/crypto/KeyAgreement").KeyAgreement | import("effect/crypto/KeyWrap").KeyWrap | import("effect/crypto/Mac").Mac | import("effect/crypto/SecureRandom").SecureRandom | import("effect/crypto/Signature").Signature>, import("effect/Scope").Scope>>;
114
+ }
115
+ /**
116
+ * Acquire a complete Node host and start one bounded, scoped worker pool after recovery.
117
+ * Own the SQLite file exclusively until the host and its storage close. A second connection
118
+ * fails construction. Process death releases the file lock; a replacement acquires it before
119
+ * recovering retained work with fresh local generations. Use this host's services for live inspection.
120
+ * Provide model, tool, instruction, and schema dependencies to this Layer. Reusing the Layer
121
+ * shares the same pool. A worker failure closes admission; observe it with `run` at the process
122
+ * boundary so the application exits and releases the host instead of remaining idle.
123
+ */
124
+ declare const layer: <const Entries extends ReadonlyArray<AgentRegistration>, ContextError = never, ContextRequirements = never, AuthorizationError = never, AuthorizationRequirements = never, ReconcilerError = never, ReconcilerRequirements = never>(registrations: Entries, options: NodeDurableAgentRuntimeOptions<ContextError, ContextRequirements, AuthorizationError, AuthorizationRequirements, ReconcilerError, ReconcilerRequirements>) => Layer.Layer<DurableAgentRuntime | MessageDeliveryStore | NodeDurableAgentRuntimeConfig | NodeDurableHost | ThreadReader | (import("effect/sql/SqlClient").SqlClient & DurableAgentRuntime) | (import("effect/sql/SqlClient").SqlClient & MessageDeliveryStore) | (import("effect/sql/SqlClient").SqlClient & NodeDurableAgentRuntimeConfig) | (import("effect/sql/SqlClient").SqlClient & ThreadReader) | (import("@effect/sql-sqlite-node/SqliteClient").SqliteClient & DurableAgentRuntime) | (import("@effect/sql-sqlite-node/SqliteClient").SqliteClient & MessageDeliveryStore) | (import("@effect/sql-sqlite-node/SqliteClient").SqliteClient & NodeDurableAgentRuntimeConfig) | (import("@effect/sql-sqlite-node/SqliteClient").SqliteClient & ThreadReader), AuthorizationError | ContextError | ReconcilerError | MessageDeliveryError | NodePlatformConfigError | DurableWorkerFailure | import("@systemfsoftware/agent-storage-sqlite/sqlite-thread-store").SqliteStorageInitializationError, Exclude<Exclude<Exclude<Exclude<AuthorizationRequirements, import("effect/crypto/Aead").Aead | import("effect/crypto/Cipher").Cipher | import("effect/crypto/Digest").Digest | import("effect/crypto/Kdf").Kdf | import("effect/crypto/KeyAgreement").KeyAgreement | import("effect/crypto/KeyWrap").KeyWrap | import("effect/crypto/Mac").Mac | import("effect/crypto/SecureRandom").SecureRandom | import("effect/crypto/Signature").Signature>, import("effect/Scope").Scope>, never>, import("effect/Scope").Scope> | Exclude<Exclude<Exclude<Exclude<ContextRequirements, import("effect/crypto/Aead").Aead | import("effect/crypto/Cipher").Cipher | import("effect/crypto/Digest").Digest | import("effect/crypto/Kdf").Kdf | import("effect/crypto/KeyAgreement").KeyAgreement | import("effect/crypto/KeyWrap").KeyWrap | import("effect/crypto/Mac").Mac | import("effect/crypto/SecureRandom").SecureRandom | import("effect/crypto/Signature").Signature>, import("effect/Scope").Scope>, never>, import("effect/Scope").Scope> | Exclude<Exclude<Exclude<Exclude<ReconcilerRequirements, import("effect/crypto/Aead").Aead | import("effect/crypto/Cipher").Cipher | import("effect/crypto/Digest").Digest | import("effect/crypto/Kdf").Kdf | import("effect/crypto/KeyAgreement").KeyAgreement | import("effect/crypto/KeyWrap").KeyWrap | import("effect/crypto/Mac").Mac | import("effect/crypto/SecureRandom").SecureRandom | import("effect/crypto/Signature").Signature>, import("effect/Scope").Scope>, never>, import("effect/Scope").Scope> | Exclude<Exclude<Exclude<Exclude<Entries[number] extends (infer T_3) ? T_3 extends Entries[number] ? T_3 extends unknown ? (("attemptLayer" extends keyof T_3 ? T_3[keyof T_3 & "attemptLayer"] : undefined) extends (infer T_4) ? T_4 extends ("attemptLayer" extends keyof T_3 ? T_3[keyof T_3 & "attemptLayer"] : undefined) ? T_4 extends ((context: import("@systemfsoftware/agent/agent-registration").AgentAttemptContext) => Layer.Layer<infer Provides, never, infer Requires>) ? Requires | Exclude<T_3 extends {
125
+ readonly agent: infer A extends import("@systemfsoftware/agent/agent-registration").ExecutableAgentBinding;
126
+ } ? import("@systemfsoftware/agent/durable-agent-runtime").DurableWorkerRequirements<A> : T_3 extends {
127
+ readonly agent: infer D extends import("@systemfsoftware/agent/agent").Definition<Schema.Top, Schema.Top, unknown, import("effect/ai/Toolkit").Any, import("@systemfsoftware/agent/agent").RunDispositionDeclaration<never, Schema.Top> | undefined, unknown, Schema.Top | undefined> & {
128
+ readonly instructions: import("@systemfsoftware/agent/agent").InstructionSource<never, unknown, unknown>;
129
+ readonly inputPrompt?: import("@systemfsoftware/agent/agent").InputPromptSource<never, unknown, unknown> | undefined;
130
+ };
131
+ readonly model: infer M extends import("@systemfsoftware/agent/agent-registration").ExecutableAgentBinding['model'];
132
+ } ? import("@systemfsoftware/agent/durable-agent-runtime").DurableWorkerRequirements<{
133
+ readonly definition: D;
134
+ readonly model: M;
135
+ }> : never, Provides> : T_3 extends {
136
+ readonly agent: infer A extends import("@systemfsoftware/agent/agent-registration").ExecutableAgentBinding;
137
+ } ? import("@systemfsoftware/agent/durable-agent-runtime").DurableWorkerRequirements<A> : T_3 extends {
138
+ readonly agent: infer D extends import("@systemfsoftware/agent/agent").Definition<Schema.Top, Schema.Top, unknown, import("effect/ai/Toolkit").Any, import("@systemfsoftware/agent/agent").RunDispositionDeclaration<never, Schema.Top> | undefined, unknown, Schema.Top | undefined> & {
139
+ readonly instructions: import("@systemfsoftware/agent/agent").InstructionSource<never, unknown, unknown>;
140
+ readonly inputPrompt?: import("@systemfsoftware/agent/agent").InputPromptSource<never, unknown, unknown> | undefined;
141
+ };
142
+ readonly model: infer M extends import("@systemfsoftware/agent/agent-registration").ExecutableAgentBinding['model'];
143
+ } ? import("@systemfsoftware/agent/durable-agent-runtime").DurableWorkerRequirements<{
144
+ readonly definition: D;
145
+ readonly model: M;
146
+ }> : never : never : never) | (("reporting" extends keyof T_3 ? T_3[keyof T_3 & "reporting"] : undefined) extends (infer T_5) ? T_5 extends ("reporting" extends keyof T_3 ? T_3[keyof T_3 & "reporting"] : undefined) ? T_5 extends readonly import("@systemfsoftware/agent/subagent-host").WorkerReporting<infer _E, infer R>[] ? Exclude<R, import("effect/Scope").Scope> : never : never : never) : never : never : never, import("effect/crypto/Aead").Aead | import("effect/crypto/Cipher").Cipher | import("effect/crypto/Digest").Digest | import("effect/crypto/Kdf").Kdf | import("effect/crypto/KeyAgreement").KeyAgreement | import("effect/crypto/KeyWrap").KeyWrap | import("effect/crypto/Mac").Mac | import("effect/crypto/SecureRandom").SecureRandom | import("effect/crypto/Signature").Signature>, import("effect/Scope").Scope>, never>, import("effect/Scope").Scope>>;
147
+ /**
148
+ * Supervise the host's existing workers without starting another pool. Use with
149
+ * `Effect.provide(HostLive)` and `NodeRuntime.runMain`; race it with a server Effect when
150
+ * the same process also serves requests. Unlike `Layer.launch`, this observes worker failures.
151
+ */
152
+ declare const run: Effect.Effect<void, import("@systemfsoftware/agent/agent-registration").BindingUnavailable | DurableWorkerFailure, NodeDurableHost>;
153
+ export { run as a, layer as i, NodeDurableHost as n, NodeDurableHost_d_exports as r, AdmissionClosed as t };
@@ -0,0 +1,2 @@
1
+ import { a as run, i as layer, n as NodeDurableHost, t as AdmissionClosed } from "./NodeDurableHost-CFvVn1w1.mjs";
2
+ export { AdmissionClosed, NodeDurableHost, layer, run };
@@ -0,0 +1 @@
1
+ export { t as AdmissionClosed, n as NodeDurableHost, i as layer, a as run } from "./NodeDurableHost-BztkzCGh.mjs";
@@ -0,0 +1,20 @@
1
+ import { ScheduleAuthorizer, ScheduleStore, ScheduleValidationError, ScheduleWake, SchedulingLimits } from "@systemfsoftware/agent/schedule";
2
+ import { Scheduling } from "@systemfsoftware/agent/scheduling";
3
+ import * as Layer from "effect/Layer";
4
+ import { n as NodeDurableHost } from "./NodeDurableHost-CFvVn1w1.mjs";
5
+ declare namespace NodeScheduling_d_exports {
6
+ export { NodeScheduling, NodeSchedulingOptions, nodeScheduleWakeLayer };
7
+ }
8
+ /** One bounded hint slot for the single supported Node scheduler. Indexed polling repairs loss. */
9
+ declare const nodeScheduleWakeLayer: Layer.Layer<ScheduleWake>;
10
+ interface NodeSchedulingOptions {
11
+ readonly limits?: SchedulingLimits | undefined;
12
+ }
13
+ /**
14
+ * Optional Scope-owned Node scheduling service and driver. The caller must provide the existing
15
+ * host, its SQLite ScheduleStore, and an explicit ScheduleAuthorizer.
16
+ */
17
+ declare class NodeScheduling {
18
+ static layer(options?: NodeSchedulingOptions): Layer.Layer<Scheduling, ScheduleValidationError, NodeDurableHost | ScheduleStore | ScheduleAuthorizer>;
19
+ }
20
+ export { nodeScheduleWakeLayer as i, NodeSchedulingOptions as n, NodeScheduling_d_exports as r, NodeScheduling as t };
@@ -0,0 +1,64 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D3KUYPsf.mjs";
2
+ import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3
+ import { ScheduleStorageError, ScheduleStore, ScheduleWake, defaultSchedulingLimits } from "@systemfsoftware/agent/schedule";
4
+ import { ScheduleDriver, Scheduling } from "@systemfsoftware/agent/scheduling";
5
+ import * as Cause from "effect/Cause";
6
+ import * as Duration from "effect/Duration";
7
+ import * as Effect from "effect/Effect";
8
+ import * as Layer from "effect/Layer";
9
+ import * as Option from "effect/Option";
10
+ import * as PubSub from "effect/PubSub";
11
+ import * as Result from "effect/Result";
12
+ import { r as nodePreparedInputAdmissionLayer } from "./NodeSubscriptions-KgvkfIMl.mjs";
13
+ // src/NodeScheduling.ts
14
+ var NodeScheduling_exports = /* @__PURE__ */ __exportAll({
15
+ NodeScheduling: () => NodeScheduling,
16
+ nodeScheduleWakeLayer: () => nodeScheduleWakeLayer
17
+ });
18
+ /** One bounded hint slot for the single supported Node scheduler. Indexed polling repairs loss. */
19
+ const nodeScheduleWakeLayer = Layer.effect(ScheduleWake, Effect.gen(function* () {
20
+ const hints = yield* PubSub.sliding(1);
21
+ const subscription = yield* PubSub.subscribe(hints);
22
+ yield* Effect.addFinalizer(() => PubSub.shutdown(hints));
23
+ return ScheduleWake.of({
24
+ notify: PubSub.publish(hints, void 0).pipe(Effect.asVoid),
25
+ await: PubSub.take(subscription)
26
+ });
27
+ }));
28
+ const reportPassFailure = (cause) => Cause.hasInterruptsOnly(cause) ? Effect.interrupt : Effect.logWarning("Node scheduling pass failed").pipe(Effect.annotateLogs({ failureTag: Option.match(Cause.findErrorOption(cause), {
29
+ onNone: () => "Defect",
30
+ onSome: (error) => error._tag
31
+ }) }), Effect.as(false));
32
+ const nodeSchedulingDriverLayer = (limits) => Layer.effectDiscard(Effect.gen(function* () {
33
+ const scheduling = yield* ScheduleDriver;
34
+ const store = yield* ScheduleStore;
35
+ const wake = yield* ScheduleWake;
36
+ const run = Effect.gen(function* () {
37
+ while (true) {
38
+ const passSucceeded = yield* scheduling.runDue().pipe(Effect.map((pass) => pass.failed === 0), Effect.catchCause(reportPassFailure));
39
+ const deadlineResult = passSucceeded ? yield* store.nextDeadline().pipe(Effect.result) : Result.fail(ScheduleStorageError.make({
40
+ operation: "driver pass",
41
+ reason: "unavailable"
42
+ }));
43
+ if (Result.isFailure(deadlineResult) && passSucceeded) yield* Effect.logWarning("Node scheduling deadline query failed");
44
+ const nowMillis = yield* Effect.clockWith((clock) => clock.currentTimeMillis);
45
+ const deadlineDelay = Result.isSuccess(deadlineResult) && deadlineResult.success !== null ? Math.max(0, deadlineResult.success - nowMillis) : limits.recoveryPollMillis;
46
+ const delay = Math.min(deadlineDelay, limits.recoveryPollMillis);
47
+ yield* Effect.raceFirst(wake.await, Effect.sleep(Duration.millis(delay)));
48
+ }
49
+ });
50
+ yield* Effect.forkScoped(run);
51
+ }));
52
+ /**
53
+ * Optional Scope-owned Node scheduling service and driver. The caller must provide the existing
54
+ * host, its SQLite ScheduleStore, and an explicit ScheduleAuthorizer.
55
+ */
56
+ var NodeScheduling = class {
57
+ static layer(options = {}) {
58
+ const limits = options.limits ?? defaultSchedulingLimits;
59
+ return nodeSchedulingDriverLayer(limits).pipe(Layer.provide(ScheduleDriver.layer(limits)), Layer.merge(Scheduling.layer(limits))).pipe(Layer.provide(Layer.mergeAll(nodePreparedInputAdmissionLayer, nodeScheduleWakeLayer, NodeCrypto.layer)));
60
+ }
61
+ };
62
+ export { NodeScheduling_exports as n, nodeScheduleWakeLayer as r, NodeScheduling as t };
63
+
64
+ //# sourceMappingURL=NodeScheduling-gNj8jB4g.mjs.map