@jini-ai/sidecar 0.7.1 → 0.7.3-next.1

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 (38) hide show
  1. package/CHANGELOG.md +1 -1
  2. package/dist/daemon-registry.d.ts +7 -5
  3. package/dist/daemon-registry.js +5 -5
  4. package/dist/index.d.ts +1 -1
  5. package/dist/ipc-path.d.ts +2 -2
  6. package/dist/ipc-path.js +2 -2
  7. package/dist/json-file.d.ts +11 -7
  8. package/dist/json-file.js +7 -8
  9. package/dist/json-ipc.d.ts +1 -18
  10. package/dist/json-ipc.js +11 -35
  11. package/dist/net.d.ts +7 -2
  12. package/dist/net.js +2 -2
  13. package/dist/paths.d.ts +11 -11
  14. package/dist/paths.js +11 -11
  15. package/dist/port.js +4 -4
  16. package/dist/supervision/child-entries.d.ts +85 -0
  17. package/dist/supervision/child-entries.js +139 -0
  18. package/dist/supervision/child-exit-signal.d.ts +21 -0
  19. package/dist/supervision/child-exit-signal.js +24 -0
  20. package/dist/supervision/child-orphans.d.ts +37 -0
  21. package/dist/supervision/child-orphans.js +48 -0
  22. package/dist/supervision/child-process-inspection.d.ts +29 -0
  23. package/dist/supervision/child-process-inspection.js +32 -0
  24. package/dist/supervision/child-readiness.d.ts +57 -0
  25. package/dist/supervision/child-readiness.js +83 -0
  26. package/dist/supervision/child-registry.d.ts +98 -0
  27. package/dist/supervision/child-registry.js +118 -0
  28. package/dist/supervision/child-stop.d.ts +39 -0
  29. package/dist/supervision/child-stop.js +81 -0
  30. package/dist/supervision/child-transitions.d.ts +54 -0
  31. package/dist/supervision/child-transitions.js +62 -0
  32. package/dist/supervision/keyed-serializer.d.ts +29 -0
  33. package/dist/supervision/keyed-serializer.js +50 -0
  34. package/dist/supervision/supervisor-node.d.ts +29 -11
  35. package/dist/supervision/supervisor-node.js +40 -29
  36. package/dist/supervision/supervisor.d.ts +3 -0
  37. package/dist/supervision/supervisor.js +312 -276
  38. package/package.json +4 -5
@@ -3,314 +3,347 @@ function giveUpReason({ decision, lastReason }) {
3
3
  return `gave up after ${decision.attempts} consecutive port conflicts: ${lastReason}`;
4
4
  return `gave up after ${decision.attempts} attempts in ${Math.round(decision.windowMs / 1000)}s: ${lastReason}`;
5
5
  }
6
- /**
7
- * Wire a caller-owned process lifecycle to retry decisions without global handlers or host defaults.
8
- * @param deps Required process, policy, clock, scheduler, readiness and observability ports.
9
- * @param options On-demand cooldown, park exit codes, routine-event suppression and give-up formatter.
10
- * @returns Inspectable lifecycle with idempotent start, demand wake, manual replacement and terminal shutdown.
11
- * @throws RangeError for a negative or non-finite cooldown.
12
- * @complexity O(1) state/work per event, excluding injected ports and policy window pruning.
13
- */
14
- export function createDaemonSupervisor(deps, options = {}) {
15
- const cooldown = options.onDemandCooldownMs ?? 30000;
16
- if (!Number.isFinite(cooldown) || cooldown < 0)
17
- throw new RangeError("onDemandCooldownMs must be finite and non-negative");
18
- const formatGiveUp = options.formatGiveUp ?? giveUpReason;
19
- const parkedExitCodes = new Set(options.parkedExitCodes);
20
- let parked = false;
21
- let current;
22
- let cancelRetry;
23
- // Terminal shutdown is a one-way latch, unlike a tripped retry cap. A restart racing
24
- // host teardown must not resurrect a child that the host is actively trying to kill.
25
- let terminating = false;
26
- let spawnAttempts = 0;
27
- let lastOnDemandAttemptAt;
28
- let readyChild;
29
- let readyWork;
30
- let discoveryWork;
31
- let cancelReadiness;
32
- function isCurrentLive({ candidate }) {
33
- return candidate !== undefined && current === candidate && !terminating && !candidate.exited && !candidate.stopping && !candidate.parking;
34
- }
35
- function isReady() {
36
- return readyChild !== undefined && isCurrentLive({ candidate: readyChild });
37
- }
38
- /** An exited child can still own unfinished termination work. O(1), no process effects. */
39
- function hasUnreapedChild() {
40
- return current !== undefined && (!current.exited || current.stopping);
41
- }
42
- /** Discovery outlives individual request deadlines; never re-enter the demand cooldown.
43
- * O(1) state and at most one discovery read per 250ms, excluding the injected read itself. */
44
- function waitForReady() {
45
- return new Promise((resolve, reject) => {
46
- let settled = false;
47
- let cancelPoll;
48
- cancelReadiness = (error = new Error("shutting down")) => finish(error);
49
- function finish(error) {
50
- if (settled)
51
- return;
52
- settled = true;
53
- cancelPoll?.();
54
- cancelReadiness = undefined;
55
- if (error)
56
- reject(error);
57
- else
58
- resolve();
59
- }
60
- async function poll() {
61
- if (settled)
62
- return;
63
- const candidate = current;
64
- try {
65
- if (candidate?.child.pid !== undefined && isCurrentLive({ candidate })) {
66
- const discovered = await deps.readiness.isReady({ pid: candidate.child.pid });
67
- // The read may have crossed an exit/replacement or terminal shutdown.
68
- if (discovered && !settled && isCurrentLive({ candidate })) {
69
- readyChild = candidate;
70
- deps.failureReporter.clear();
71
- finish();
72
- return;
73
- }
6
+ function isCurrentLive(context, { candidate }) {
7
+ return candidate !== undefined && context.current === candidate && !context.terminating && !candidate.exited && !candidate.stopping && !candidate.parking;
8
+ }
9
+ function isReady(context) {
10
+ return context.readyChild !== undefined && isCurrentLive(context, { candidate: context.readyChild });
11
+ }
12
+ /** An exited child can still own unfinished termination work. O(1), no process effects. */
13
+ function hasUnreapedChild(context) {
14
+ return context.current !== undefined && (!context.current.exited || context.current.stopping);
15
+ }
16
+ /** Discovery outlives individual request deadlines; never re-enter the demand cooldown.
17
+ * O(1) state and at most one discovery read per 250ms, excluding the injected read itself. */
18
+ function waitForReady(context) {
19
+ const { deps } = context;
20
+ return new Promise((resolve, reject) => {
21
+ let settled = false;
22
+ let cancelPoll;
23
+ context.cancelReadiness = (error = new Error("shutting down")) => finish(error);
24
+ function finish(error) {
25
+ if (settled)
26
+ return;
27
+ settled = true;
28
+ cancelPoll?.();
29
+ context.cancelReadiness = undefined;
30
+ if (error)
31
+ reject(error);
32
+ else
33
+ resolve();
34
+ }
35
+ async function poll() {
36
+ if (settled)
37
+ return;
38
+ const candidate = context.current;
39
+ try {
40
+ if (candidate?.child.pid !== undefined && isCurrentLive(context, { candidate })) {
41
+ const discovered = await deps.readiness.isReady({ pid: candidate.child.pid });
42
+ // The read may have crossed an exit/replacement or terminal shutdown.
43
+ if (discovered && !settled && isCurrentLive(context, { candidate })) {
44
+ context.readyChild = candidate;
45
+ deps.failureReporter.clear();
46
+ finish();
47
+ return;
74
48
  }
75
49
  }
76
- catch { /* Missing or partly-published discovery is not readiness; keep waiting. */ }
77
- if (!settled)
78
- cancelPoll = deps.scheduler.schedule({ delayMs: 250, run: () => { void poll(); } });
79
50
  }
80
- void poll();
81
- });
82
- }
83
- /** One monitor spans demand and replacement; background shutdown rejection is observed.
84
- * @complexity O(1) state; one PID probe immediately, then at most once per 250ms until ready.
85
- */
86
- function discoverReadiness() {
87
- if (!discoveryWork) {
88
- const discovery = waitForReady().finally(() => { if (discoveryWork === discovery)
89
- discoveryWork = undefined; });
90
- discoveryWork = discovery;
91
- void discovery.catch(() => { });
51
+ catch { /* Missing or partly-published discovery is not readiness; keep waiting. */ }
52
+ if (!settled)
53
+ cancelPoll = deps.scheduler.schedule({ delayMs: 250, run: () => { void poll(); } });
92
54
  }
93
- return discoveryWork;
55
+ void poll();
56
+ });
57
+ }
58
+ /** One monitor spans demand and replacement; background shutdown rejection is observed.
59
+ * @complexity O(1) state; one PID probe immediately, then at most once per 250ms until ready.
60
+ */
61
+ function discoverReadiness(context) {
62
+ if (!context.discoveryWork) {
63
+ const discovery = waitForReady(context).finally(() => { if (context.discoveryWork === discovery)
64
+ context.discoveryWork = undefined; });
65
+ context.discoveryWork = discovery;
66
+ void discovery.catch(() => { });
94
67
  }
95
- function ensureReady(_required, { signal } = {}) {
96
- if (signal?.aborted)
97
- return Promise.reject(signal.reason);
98
- if (terminating)
99
- return Promise.reject(new Error("shutting down"));
100
- if (isReady())
101
- return Promise.resolve();
102
- if (!deps.readiness)
103
- return Promise.reject(new Error("readiness port is not configured"));
104
- // A shared discovery may already exist; this demand still has to request replacement after
105
- // the retiring child exits. Reuse that discovery rather than canceling its current waiters.
106
- if (current?.parking)
107
- supervisor.ensureStarted();
108
- if (!readyWork) {
109
- const start = supervisor.ensureStarted();
110
- if (!start.ok)
111
- return Promise.reject(new Error(start.reason));
112
- // A slow healthy child must keep being discovered after an HTTP caller gives up.
113
- // Share the monitor across subsequent demands; shutdown or parking cancels polling.
114
- // A parked waiter's cleanup must not clear a fresh wake's discovery or request work.
115
- const ready = readinessDeadline({ work: discoverReadiness(), scheduler: deps.scheduler }).finally(() => { if (readyWork === ready)
116
- readyWork = undefined; });
117
- readyWork = ready;
118
- }
119
- return signal ? awaitForCaller({ work: readyWork, signal }) : readyWork;
68
+ return context.discoveryWork;
69
+ }
70
+ /** Return immediate readiness outcomes before starting or joining discovery. O(1) time/space. */
71
+ function readinessPreflight(context, { signal }) {
72
+ const { deps } = context;
73
+ if (signal?.aborted)
74
+ return Promise.reject(signal.reason);
75
+ if (context.terminating)
76
+ return Promise.reject(new Error("shutting down"));
77
+ if (isReady(context))
78
+ return Promise.resolve();
79
+ if (!deps.readiness)
80
+ return Promise.reject(new Error("readiness port is not configured"));
81
+ return undefined;
82
+ }
83
+ function ensureReady(context, _required, { signal } = {}) {
84
+ const { deps } = context;
85
+ const preflight = readinessPreflight(context, { signal });
86
+ if (preflight !== undefined)
87
+ return preflight;
88
+ // A shared discovery may already exist; this demand still has to request replacement after
89
+ // the retiring child exits. Reuse that discovery rather than canceling its current waiters.
90
+ if (context.current?.parking)
91
+ context.supervisor.ensureStarted();
92
+ if (!context.readyWork) {
93
+ const start = context.supervisor.ensureStarted();
94
+ if (!start.ok)
95
+ return Promise.reject(new Error(start.reason));
96
+ // A slow healthy child must keep being discovered after an HTTP caller gives up.
97
+ // Share the monitor across subsequent demands; shutdown or parking cancels polling.
98
+ // A parked waiter's cleanup must not clear a fresh wake's discovery or request work.
99
+ const ready = readinessDeadline({ work: discoverReadiness(context), scheduler: deps.scheduler }).finally(() => { if (context.readyWork === ready)
100
+ context.readyWork = undefined; });
101
+ context.readyWork = ready;
120
102
  }
121
- function reportFailure(reason, decision) {
122
- deps.failureReporter.record({ reason });
123
- deps.logger.emit({ type: "failure", at: deps.now(), reason, ...(decision === undefined ? {} : { decision }) });
103
+ return signal ? awaitForCaller({ work: context.readyWork, signal }) : context.readyWork;
104
+ }
105
+ function reportFailure(context, reason, decision) {
106
+ const { deps } = context;
107
+ deps.failureReporter.record({ reason });
108
+ deps.logger.emit({ type: "failure", at: deps.now(), reason, ...(decision === undefined ? {} : { decision }) });
109
+ }
110
+ function cancelPendingRetry(context) {
111
+ const cancelRetry = context.cancelRetry;
112
+ cancelRetry?.();
113
+ context.cancelRetry = undefined;
114
+ }
115
+ function terminate(context, state) {
116
+ const { deps } = context;
117
+ state.stopping = true;
118
+ function stopped() {
119
+ state.stopping = false;
120
+ if (context.current === state && state.exited && state.replaceAfterExit && !context.terminating)
121
+ attemptSpawn(context);
124
122
  }
125
- function cancelPendingRetry() { cancelRetry?.(); cancelRetry = undefined; }
126
- function terminate(state) {
127
- state.stopping = true;
128
- function stopped() {
129
- state.stopping = false;
130
- if (current === state && state.exited && state.replaceAfterExit && !terminating)
131
- attemptSpawn();
132
- }
133
- function failed(error) {
134
- state.stopping = false;
135
- state.replaceAfterExit = false;
136
- // A failed replacement must not suppress recovery from a later crash.
137
- state.deliberate = false;
138
- if (current === state)
139
- reportFailure(`failed to stop daemon: ${String(error)}`);
140
- }
141
- try {
142
- const result = deps.terminateProcess({ child: state.child });
143
- if (result !== undefined) {
144
- void result.then(stopped, failed);
145
- return;
146
- }
147
- stopped();
148
- }
149
- catch (error) {
150
- failed(error);
151
- }
123
+ function failed(error) {
124
+ state.stopping = false;
125
+ state.replaceAfterExit = false;
126
+ // A failed replacement must not suppress recovery from a later crash.
127
+ state.deliberate = false;
128
+ if (context.current === state)
129
+ reportFailure(context, `failed to stop daemon: ${String(error)}`);
152
130
  }
153
- function handleUnexpectedExit(code, signal) {
154
- // Recognize the host's normal park code before classification can charge a crash or bind failure.
155
- if (code !== null && parkedExitCodes.has(code)) {
156
- parked = true;
157
- cancelPendingRetry();
158
- cancelReadiness?.(new Error("daemon parked"));
159
- readyChild = undefined;
160
- readyWork = undefined;
161
- discoveryWork = undefined;
162
- return;
163
- }
164
- const classification = deps.classifyExit({ code, signal });
165
- reportFailure(classification.reason);
166
- const decision = deps.policy.recordFailure({ isPortConflict: classification.isPortConflict });
167
- if (decision.action === "give-up") {
168
- reportFailure(formatGiveUp({ decision, lastReason: classification.reason }), decision);
131
+ try {
132
+ const result = deps.terminateProcess({ child: state.child });
133
+ if (result !== undefined) {
134
+ void result.then(stopped, failed);
169
135
  return;
170
136
  }
171
- cancelRetry = deps.scheduler.schedule({ delayMs: decision.delayMs, run: () => { cancelRetry = undefined; attemptSpawn(); } });
137
+ stopped();
172
138
  }
173
- function attemptSpawn() {
174
- if (terminating || parked || hasUnreapedChild())
175
- return;
176
- // A new attempt must not inherit a stale readiness failure from an earlier child.
177
- deps.failureReporter.clear();
178
- let child;
179
- try {
180
- child = deps.spawnDaemonProcess();
181
- }
182
- catch (error) {
183
- reportFailure(`failed to start daemon: ${error instanceof Error ? error.message : String(error)}`);
184
- return;
185
- }
186
- const state = { child, exited: false, deliberate: false, replaceAfterExit: false, stopping: false, parking: false };
187
- // Assign synchronously: run-to-completion makes request-driven recovery single-flight
188
- // without a lock or an await between checking the current child and publishing it.
189
- current = state;
190
- // A respawn ends every run in flight. Timestamped lifecycle events let operators
191
- // correlate apparently stalled work with a replacement, including deliberate exits
192
- // when routine lifecycle logging is enabled.
193
- spawnAttempts++;
194
- if (!options.quietRoutineLifecycle || spawnAttempts > 1) {
195
- deps.logger.emit({ type: "spawn", at: deps.now(), pid: child.pid, attempt: spawnAttempts });
196
- }
197
- // Missing scripts/permissions are not transient crashes: repeating the broken spawn
198
- // on backoff only burns the retry cap. Manual or cooldown-limited recovery can try
199
- // again after the underlying launch problem is repaired.
200
- child.on({ event: "error", listener: ({ error }) => {
201
- if (current !== state || state.exited)
202
- return;
203
- // Spawn failure has no pid and never emits exit. A live child's error may instead be a failed kill.
204
- if (child.pid === undefined)
205
- state.exited = true;
206
- reportFailure(`failed to start daemon: ${error.message}`);
207
- } });
208
- child.on({ event: "exit", listener: ({ code, signal }) => {
209
- if (current !== state || state.exited)
210
- return;
211
- state.exited = true;
212
- if (!options.quietRoutineLifecycle || !state.deliberate) {
213
- deps.logger.emit({ type: "exit", at: deps.now(), pid: child.pid, code, signal, deliberate: state.deliberate });
214
- }
215
- if (terminating)
216
- return;
217
- if (state.replaceAfterExit) {
218
- if (!state.stopping)
219
- attemptSpawn();
220
- return;
221
- }
222
- if (!state.deliberate)
223
- handleUnexpectedExit(code, signal);
224
- } });
225
- // Cold construction and an idle park do no discovery. A replacement must still publish
226
- // readiness when no caller is waiting; reuse the current monitor if startup is ongoing.
227
- if (spawnAttempts > 1 && deps.readiness)
228
- void discoverReadiness();
139
+ catch (error) {
140
+ failed(error);
141
+ }
142
+ }
143
+ function handleUnexpectedExit(context, code, signal) {
144
+ const { deps, parkedExitCodes, formatGiveUp } = context;
145
+ // Recognize the host's normal park code before classification can charge a crash or bind failure.
146
+ if (code !== null && parkedExitCodes.has(code)) {
147
+ context.parked = true;
148
+ cancelPendingRetry(context);
149
+ context.cancelReadiness?.(new Error("daemon parked"));
150
+ context.readyChild = undefined;
151
+ context.readyWork = undefined;
152
+ context.discoveryWork = undefined;
153
+ return;
154
+ }
155
+ const classification = deps.classifyExit({ code, signal });
156
+ reportFailure(context, classification.reason);
157
+ const decision = deps.policy.recordFailure({ isPortConflict: classification.isPortConflict });
158
+ if (decision.action === "give-up") {
159
+ reportFailure(context, formatGiveUp({ decision, lastReason: classification.reason }), decision);
160
+ return;
161
+ }
162
+ context.cancelRetry = deps.scheduler.schedule({ delayMs: decision.delayMs, run: () => { context.cancelRetry = undefined; attemptSpawn(context); } });
163
+ }
164
+ function attemptSpawn(context) {
165
+ const { deps, options } = context;
166
+ if (context.terminating || context.parked || hasUnreapedChild(context))
167
+ return;
168
+ // A new attempt must not inherit a stale readiness failure from an earlier child.
169
+ deps.failureReporter.clear();
170
+ let child;
171
+ try {
172
+ child = deps.spawnDaemonProcess();
173
+ }
174
+ catch (error) {
175
+ reportFailure(context, `failed to start daemon: ${error instanceof Error ? error.message : String(error)}`);
176
+ return;
177
+ }
178
+ const state = { child, exited: false, deliberate: false, replaceAfterExit: false, stopping: false, parking: false };
179
+ // Assign synchronously: run-to-completion makes request-driven recovery single-flight
180
+ // without a lock or an await between checking the current child and publishing it.
181
+ context.current = state;
182
+ // A respawn ends every run in flight. Timestamped lifecycle events let operators
183
+ // correlate apparently stalled work with a replacement, including deliberate exits
184
+ // when routine lifecycle logging is enabled.
185
+ context.spawnAttempts++;
186
+ if (!options.quietRoutineLifecycle || context.spawnAttempts > 1) {
187
+ deps.logger.emit({ type: "spawn", at: deps.now(), pid: child.pid, attempt: context.spawnAttempts });
188
+ }
189
+ subscribeToChild(context, state);
190
+ // Cold construction and an idle park do no discovery. A replacement must still publish
191
+ // readiness when no caller is waiting; reuse the current monitor if startup is ongoing.
192
+ if (context.spawnAttempts > 1 && deps.readiness)
193
+ void discoverReadiness(context);
194
+ }
195
+ // Wait for a still-live child to exit before replacement: spawning alongside it would
196
+ // collide on its listening port and manufacture the bind failure we are recovering from.
197
+ function forceFreshSpawn(context) {
198
+ context.parked = false;
199
+ if (context.current?.stopping) {
200
+ context.current.replaceAfterExit = true;
201
+ return;
229
202
  }
230
- // Wait for a still-live child to exit before replacement: spawning alongside it would
231
- // collide on its listening port and manufacture the bind failure we are recovering from.
232
- function forceFreshSpawn() {
233
- parked = false;
234
- if (current?.stopping) {
235
- current.replaceAfterExit = true;
203
+ if (context.current !== undefined && !context.current.exited) {
204
+ if (context.current.replaceAfterExit)
236
205
  return;
237
- }
238
- if (current !== undefined && !current.exited) {
239
- if (current.replaceAfterExit)
206
+ context.current.deliberate = true;
207
+ context.current.replaceAfterExit = true;
208
+ terminate(context, context.current);
209
+ return;
210
+ }
211
+ attemptSpawn(context);
212
+ }
213
+ function subscribeToChild(context, state) {
214
+ const { deps, options } = context;
215
+ const { child } = state;
216
+ // Missing scripts/permissions are not transient crashes: repeating the broken spawn
217
+ // on backoff only burns the retry cap. Manual or cooldown-limited recovery can try
218
+ // again after the underlying launch problem is repaired.
219
+ child.on({ event: "error", listener: ({ error }) => {
220
+ if (context.current !== state || state.exited)
240
221
  return;
241
- current.deliberate = true;
242
- current.replaceAfterExit = true;
243
- terminate(current);
244
- return;
245
- }
246
- attemptSpawn();
222
+ // Spawn failure has no pid and never emits exit. A live child's error may instead be a failed kill.
223
+ if (child.pid === undefined)
224
+ state.exited = true;
225
+ reportFailure(context, `failed to start daemon: ${error.message}`);
226
+ } });
227
+ child.on({ event: "exit", listener: ({ code, signal }) => {
228
+ if (context.current !== state || state.exited)
229
+ return;
230
+ state.exited = true;
231
+ if (!options.quietRoutineLifecycle || !state.deliberate) {
232
+ deps.logger.emit({ type: "exit", at: deps.now(), pid: child.pid, code, signal, deliberate: state.deliberate });
233
+ }
234
+ if (context.terminating)
235
+ return;
236
+ if (state.replaceAfterExit) {
237
+ if (!state.stopping)
238
+ attemptSpawn(context);
239
+ return;
240
+ }
241
+ if (!state.deliberate)
242
+ handleUnexpectedExit(context, code, signal);
243
+ } });
244
+ }
245
+ function ensureStarted(context) {
246
+ const { deps, cooldown } = context;
247
+ if (context.terminating)
248
+ return { ok: false, reason: "shutting down" };
249
+ if (context.current?.parking && !context.current.exited) {
250
+ context.current.replaceAfterExit = true;
251
+ return { ok: true };
247
252
  }
248
- const supervisor = {
249
- isReady, ensureReady,
253
+ // A scheduled retry keeps its own backoff; request traffic must not accelerate it.
254
+ if (hasUnreapedChild(context) || context.cancelRetry !== undefined)
255
+ return { ok: true };
256
+ // Parking is healthy idleness: wake immediately, retaining all earlier crash history.
257
+ if (context.parked) {
258
+ context.lastOnDemandAttemptAt = deps.now();
259
+ forceFreshSpawn(context);
260
+ return { ok: true };
261
+ }
262
+ // Single-flight alone cannot stop a storm against a durably broken launch. The 30s
263
+ // default floor matches the standard backoff ceiling, bounding traffic-driven retries
264
+ // to the same worst-case rate as timer-driven recovery after a cap or spawn failure.
265
+ const now = deps.now();
266
+ if (context.lastOnDemandAttemptAt !== undefined && now - context.lastOnDemandAttemptAt < cooldown)
267
+ return { ok: false, reason: "cooling down before trying again" };
268
+ context.lastOnDemandAttemptAt = now;
269
+ deps.policy.reset();
270
+ forceFreshSpawn(context);
271
+ return { ok: true };
272
+ }
273
+ function createSupervisorActions(context) {
274
+ const { deps } = context;
275
+ return {
276
+ isReady: () => isReady(context),
277
+ ensureReady: (_required, optional = {}) => ensureReady(context, _required, optional),
250
278
  markParking({ pid }, _optional = {}) {
251
- if (!current || current.child.pid !== pid || current.exited || terminating)
279
+ if (!context.current || context.current.child.pid !== pid || context.current.exited || context.terminating)
252
280
  return;
253
- current.parking = true;
254
- readyChild = undefined;
281
+ context.current.parking = true;
282
+ context.readyChild = undefined;
255
283
  },
256
284
  getState() {
257
- if (terminating)
285
+ if (context.terminating)
258
286
  return "shutting-down";
259
- if (parked)
287
+ if (context.parked)
260
288
  return "parked";
261
- return current !== undefined && !current.exited ? "running" : "stopped";
289
+ return context.current !== undefined && !context.current.exited ? "running" : "stopped";
262
290
  },
263
- start() { if (cancelRetry === undefined)
264
- attemptSpawn(); },
291
+ start() { if (context.cancelRetry === undefined)
292
+ attemptSpawn(context); },
265
293
  restart() {
266
- if (terminating)
267
- return { ok: false, reason: "shutting down" };
268
- cancelPendingRetry();
269
- deps.policy.reset();
270
- forceFreshSpawn();
271
- return { ok: true };
272
- },
273
- ensureStarted() {
274
- if (terminating)
294
+ if (context.terminating)
275
295
  return { ok: false, reason: "shutting down" };
276
- if (current?.parking && !current.exited) {
277
- current.replaceAfterExit = true;
278
- return { ok: true };
279
- }
280
- // A scheduled retry keeps its own backoff; request traffic must not accelerate it.
281
- if (hasUnreapedChild() || cancelRetry !== undefined)
282
- return { ok: true };
283
- // Parking is healthy idleness: wake immediately, retaining all earlier crash history.
284
- if (parked) {
285
- lastOnDemandAttemptAt = deps.now();
286
- forceFreshSpawn();
287
- return { ok: true };
288
- }
289
- // Single-flight alone cannot stop a storm against a durably broken launch. The 30s
290
- // default floor matches the standard backoff ceiling, bounding traffic-driven retries
291
- // to the same worst-case rate as timer-driven recovery after a cap or spawn failure.
292
- const now = deps.now();
293
- if (lastOnDemandAttemptAt !== undefined && now - lastOnDemandAttemptAt < cooldown)
294
- return { ok: false, reason: "cooling down before trying again" };
295
- lastOnDemandAttemptAt = now;
296
+ cancelPendingRetry(context);
296
297
  deps.policy.reset();
297
- forceFreshSpawn();
298
+ forceFreshSpawn(context);
298
299
  return { ok: true };
299
300
  },
301
+ ensureStarted() { return ensureStarted(context); },
300
302
  shutdown() {
301
- if (terminating)
303
+ if (context.terminating)
302
304
  return;
303
- terminating = true;
304
- cancelPendingRetry();
305
- cancelReadiness?.();
306
- if (current === undefined)
305
+ context.terminating = true;
306
+ cancelPendingRetry(context);
307
+ context.cancelReadiness?.();
308
+ if (context.current === undefined)
307
309
  return;
308
- current.deliberate = true;
309
- current.replaceAfterExit = false;
310
- if (!current.exited && !current.stopping)
311
- terminate(current);
310
+ context.current.deliberate = true;
311
+ context.current.replaceAfterExit = false;
312
+ if (!context.current.exited && !context.current.stopping)
313
+ terminate(context, context.current);
312
314
  },
313
315
  };
316
+ }
317
+ /**
318
+ * Wire a caller-owned process lifecycle to retry decisions without global handlers or host defaults.
319
+ * @param deps Required process, policy, clock, scheduler, readiness and observability ports.
320
+ * @param options On-demand cooldown, park exit codes, routine-event suppression and give-up formatter.
321
+ * @returns Inspectable lifecycle with idempotent start, demand wake, manual replacement and terminal shutdown.
322
+ * @throws RangeError for a negative or non-finite cooldown.
323
+ * @complexity O(1) state/work per event, excluding injected ports and policy window pruning.
324
+ */
325
+ export function createDaemonSupervisor(deps, options = {}) {
326
+ const cooldown = options.onDemandCooldownMs ?? 30000;
327
+ if (!Number.isFinite(cooldown) || cooldown < 0)
328
+ throw new RangeError("onDemandCooldownMs must be finite and non-negative");
329
+ const formatGiveUp = options.formatGiveUp ?? giveUpReason;
330
+ const parkedExitCodes = new Set(options.parkedExitCodes);
331
+ const context = {
332
+ deps, options, cooldown, formatGiveUp, parkedExitCodes,
333
+ parked: false,
334
+ current: undefined,
335
+ cancelRetry: undefined,
336
+ terminating: false,
337
+ spawnAttempts: 0,
338
+ lastOnDemandAttemptAt: undefined,
339
+ readyChild: undefined,
340
+ readyWork: undefined,
341
+ discoveryWork: undefined,
342
+ cancelReadiness: undefined,
343
+ supervisor: undefined,
344
+ };
345
+ const supervisor = createSupervisorActions(context);
346
+ context.supervisor = supervisor;
314
347
  return supervisor;
315
348
  }
316
349
  /** Bound demand waits without cancelling shared discovery. O(1) timers and handlers per wait. */
@@ -328,4 +361,7 @@ function awaitForCaller({ work, signal }) {
328
361
  work.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
329
362
  });
330
363
  }
364
+ export { createKeyedSerializer } from "./keyed-serializer.js";
365
+ export { createChildTransitions } from "./child-transitions.js";
366
+ export { createChildEntries } from "./child-entries.js";
331
367
  //# sourceMappingURL=supervisor.js.map