@jini-ai/sidecar 0.6.17 → 0.6.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # @jini-ai/sidecar
2
2
 
3
+ ## 0.6.21
4
+
5
+ - Native IPC carries a handler's explicit public `refusalReason` (1–1024 characters) back to the caller instead of a generic "IPC request refused"; raw handler errors still never cross the channel.
6
+
3
7
  ## 0.6.17
4
8
 
5
9
  ### Patch Changes
@@ -65,7 +69,7 @@
65
69
  - Atomic filesystem handling is canonical in platform and Node supervisor defaults are isolated in ./supervisor/node.
66
70
  - Distribution includes runtime output, release documentation and required assets only. Process records and per-job neutrality checks are no longer part of the package surface.
67
71
 
68
- ## Unreleased
72
+ ## 0.6.19
69
73
 
70
74
  - Fix supervisor test compilation by checking event-array emptiness without narrowing later lifecycle events to `never`.
71
75
 
@@ -1,5 +1,6 @@
1
1
  import type { Writable } from "node:stream";
2
2
  import type { ChildProcess, SpawnOptions } from "node:child_process";
3
+ import type { Serializable } from "node:child_process";
3
4
  import { listProcessSnapshots, stopProcesses, waitForProcessExit } from "@jini-ai/platform/process";
4
5
  import type { LocalDaemonRegistryRecord } from "./daemon-registry.js";
5
6
  import type { SpawnedDaemonProcess, SupervisorScheduler } from "./supervisor.js";
@@ -30,6 +31,10 @@ export interface NodeDaemonProcessRequired {
30
31
  registry: SupervisorRegistry;
31
32
  }
32
33
  export interface NodeDaemonProcessOptions {
34
+ /** Inherit a separate native control channel; stdin remains the Windows EOF shutdown pipe. */
35
+ ipc?: boolean;
36
+ /** Delivered once over native IPC, removed case-insensitively from the OS environment. */
37
+ startupSecrets?: Readonly<Record<string, string>>;
33
38
  stdout?: Writable;
34
39
  stderr?: Writable;
35
40
  platform?: NodeJS.Platform;
@@ -68,4 +73,77 @@ export declare function createNodeDaemonProcessAdapter(required: NodeDaemonProce
68
73
  * @complexity O(1) per schedule/cancel.
69
74
  */
70
75
  export declare function createNodeSupervisorScheduler(_required: Record<string, never>): SupervisorScheduler;
76
+ /** A channel bound to one native child (or its process end), never an address supplied by a caller. */
77
+ export interface NodeIpcPeer {
78
+ readonly connected?: boolean;
79
+ send?: (message: Serializable, callback: (error: Error | null) => void) => boolean;
80
+ on(event: "message" | "disconnect", listener: (message: unknown) => void): unknown;
81
+ removeListener(event: "message" | "disconnect", listener: (message: unknown) => void): unknown;
82
+ }
83
+ /** Only explicitly public, bounded refusal text may cross IPC. Raw handler messages stay private.
84
+ * @complexity O(1); the caller owns choosing a reason that contains no private data.
85
+ */
86
+ export declare function ipcRefusalReason({ value }: {
87
+ value: unknown;
88
+ }, _optional?: {}): string | undefined;
89
+ /** Native request/reply with bounded pending work. Errors never echo a request, payload or raw handler error.
90
+ * Handlers may opt into public diagnostics by throwing an error with a `refusalReason` string
91
+ * (1–1024 characters), e.g. `Object.assign(new Error(), { refusalReason: "This session ended." })`.
92
+ * @param required The actual spawned child or inherited process channel.
93
+ * @param optional Handler, deadline and pending-request cap; construction starts no requests.
94
+ * @returns Request and idempotent disposal; disconnect rejects and clears every pending request.
95
+ * @throws On disconnected IPC, timeout, refusal, >1 MiB envelope or capacity overflow.
96
+ * @complexity O(payload bytes) per send, O(p) disconnect for at most maxPending requests.
97
+ */
98
+ export declare function createNodeIpcChannel({ peer }: {
99
+ peer: NodeIpcPeer;
100
+ }, { handle, timeoutMs, maxPending, channel, }?: {
101
+ handle?: (payload: unknown) => Promise<Serializable>;
102
+ timeoutMs?: number;
103
+ maxPending?: number;
104
+ channel?: string;
105
+ }): {
106
+ request({ payload }: {
107
+ payload: Serializable;
108
+ }, _optional?: {}): Promise<unknown>;
109
+ dispose: (_required: Record<string, never>, _optional?: {}) => void;
110
+ };
111
+ /** Non-secret launch marker; the payload itself never enters argv or process.env. */
112
+ export declare const STARTUP_SECRETS_ENV = "JINI_STARTUP_SECRETS_IPC";
113
+ /** Separate host-selected capabilities from a launch environment without mutating it.
114
+ * Windows case variants map to the canonical host key; absent values create no credential.
115
+ * @returns Independent environment and capability records; throws beyond the 64 KiB/256-key limit.
116
+ * @complexity O(e + k) time/space.
117
+ * @example splitNodeStartupSecrets({ env, keys: ['HOST_TOKEN'] });
118
+ */
119
+ export declare function splitNodeStartupSecrets({ env, keys }: {
120
+ env: Readonly<NodeJS.ProcessEnv>;
121
+ keys: readonly string[];
122
+ }, _optional?: Record<string, never>): {
123
+ env: NodeJS.ProcessEnv;
124
+ secrets: Record<string, string>;
125
+ };
126
+ /** Offer credentials to this native child once, sharing IPC with the existing control owner.
127
+ * @returns A disposer for child exit/error; disconnect also clears the channel.
128
+ * @throws For an invalid/oversized record. Refusals never contain credentials.
129
+ * @complexity O(bytes) bounded copy; one in-memory record until the child's first read.
130
+ * @example provideNodeStartupSecrets({ peer: child, secrets: { HOST_TOKEN: token } });
131
+ */
132
+ export declare function provideNodeStartupSecrets({ peer, secrets }: {
133
+ peer: NodeIpcPeer;
134
+ secrets: Readonly<Record<string, string>>;
135
+ }, _optional?: Record<string, never>): {
136
+ dispose(_required?: Record<string, never>, _options?: Record<string, never>): void;
137
+ };
138
+ /** Read credentials over inherited IPC and release the receiver even on timeout/disconnect.
139
+ * The caller retains the returned record in memory; it must never assign it to process.env.
140
+ * @throws On unavailable IPC, refusal, timeout or malformed credentials.
141
+ * @complexity O(bytes) bounded validation; one request with a 30s default deadline.
142
+ * @example const secrets = await receiveNodeStartupSecrets({ peer: process });
143
+ */
144
+ export declare function receiveNodeStartupSecrets({ peer }: {
145
+ peer: NodeIpcPeer;
146
+ }, { timeoutMs, }?: {
147
+ timeoutMs?: number;
148
+ }): Promise<Record<string, string>>;
71
149
  //# sourceMappingURL=supervisor-node.d.ts.map
@@ -1,5 +1,7 @@
1
1
  import { execFileSync, spawn } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
2
3
  import { createCommandInvocation } from "@jini-ai/platform/command";
4
+ import { omitEnvironmentKeys } from "@jini-ai/platform/child-environment";
3
5
  import { collectProcessTreePids, listProcessSnapshots, stopProcesses, waitForProcessExit } from "@jini-ai/platform/process";
4
6
  import { readLiveDaemonRegistryRecord, removeDaemonRegistryRecordIfCurrent, writeDaemonRegistryRecord } from "./daemon-registry.js";
5
7
  /**
@@ -45,6 +47,31 @@ async function stopWindowsProcess({ child, pid }, options = {}) {
45
47
  }
46
48
  }
47
49
  }
50
+ /** Build an OS environment, reserving IPC for capabilities while stdin remains the stop pipe.
51
+ * @returns A detached launch environment. @complexity O(e + k) for env entries and secret keys.
52
+ */
53
+ function daemonLaunchEnvironment(required, options = {}) {
54
+ if (options.startupSecrets === undefined)
55
+ return required.env;
56
+ return { ...splitNodeStartupSecrets({ env: required.env, keys: Object.keys(options.startupSecrets) }).env,
57
+ [STARTUP_SECRETS_ENV]: '1' };
58
+ }
59
+ /** Resolve command quoting and native descriptors without creating a process.
60
+ * Detached groups enable tree stopping; parent output pipes cannot strand inherited descriptors.
61
+ * @returns The command invocation, Windows mode and native spawn options. @complexity O(e) env copy.
62
+ */
63
+ function daemonLaunchPlan(required, options = {}) {
64
+ const win32 = (options.platform ?? process.platform) === 'win32';
65
+ const env = daemonLaunchEnvironment(required, options);
66
+ const invocation = createCommandInvocation({ command: required.command, args: [...required.args], env });
67
+ const ipc = options.ipc || options.startupSecrets !== undefined;
68
+ const spawnOptions = {
69
+ cwd: required.cwd, env: { ...env, ...(win32 ? { JINI_STOP_ON_STDIN_EOF: '1' } : {}) }, detached: true, windowsHide: true,
70
+ stdio: [win32 ? 'pipe' : 'ignore', 'pipe', 'pipe', ...(ipc ? ['ipc'] : [])],
71
+ ...(invocation.windowsVerbatimArguments === undefined ? {} : { windowsVerbatimArguments: invocation.windowsVerbatimArguments }),
72
+ };
73
+ return { invocation, spawnOptions, win32 };
74
+ }
48
75
  /**
49
76
  * Node launch/tree-stop adapter using platform command quoting, snapshots and signal escalation.
50
77
  * @param required Complete host launch settings and the shared sidecar registry port.
@@ -53,22 +80,20 @@ async function stopWindowsProcess({ child, pid }, options = {}) {
53
80
  * @complexity Tree stop is O(p) for p process snapshots, plus platform exit polling.
54
81
  */
55
82
  export function createNodeDaemonProcessAdapter(required, options = {}) {
83
+ // Validate/snapshot before spawning: a launch must not orphan a child when delivery is refused.
84
+ const startupSecrets = options.startupSecrets === undefined ? undefined : startupSecretRecord(options.startupSecrets);
85
+ const launchOptions = startupSecrets === undefined ? options : { ...options, startupSecrets };
56
86
  return {
57
87
  spawnDaemonProcess() {
58
- const win32 = (options.platform ?? process.platform) === "win32";
59
- const invocation = createCommandInvocation({ command: required.command, args: [...required.args], env: required.env });
60
- // detached creates a POSIX process group so teardown reaches the daemon below a
61
- // launcher hop; windowsHide avoids an otherwise visible detached Windows console.
62
- // Pipe output through the parent instead of inheriting its descriptors: an orphan
63
- // retaining those descriptors previously kept parent/test teardown waiting forever.
64
- const spawnOptions = {
65
- cwd: required.cwd, env: { ...required.env, ...(win32 ? { JINI_STOP_ON_STDIN_EOF: "1" } : {}) }, detached: true, windowsHide: true,
66
- stdio: [win32 ? "pipe" : "ignore", "pipe", "pipe"],
67
- ...(invocation.windowsVerbatimArguments === undefined ? {} : { windowsVerbatimArguments: invocation.windowsVerbatimArguments }),
68
- };
88
+ const { invocation, spawnOptions, win32 } = daemonLaunchPlan(required, launchOptions);
69
89
  const child = options.spawn
70
90
  ? options.spawn({ command: invocation.command, args: invocation.args, options: spawnOptions }, {})
71
91
  : spawn(invocation.command, invocation.args, spawnOptions);
92
+ if (startupSecrets !== undefined) {
93
+ const delivery = provideNodeStartupSecrets({ peer: child, secrets: startupSecrets });
94
+ child.once('exit', () => delivery.dispose({}));
95
+ child.once('error', () => delivery.dispose({}));
96
+ }
72
97
  relayProcessOutput({ stream: child.stdout, sink: options.stdout });
73
98
  relayProcessOutput({ stream: child.stderr, sink: options.stderr });
74
99
  return {
@@ -121,4 +146,170 @@ export function createNodeDaemonProcessAdapter(required, options = {}) {
121
146
  export function createNodeSupervisorScheduler(_required) {
122
147
  return { schedule: ({ delayMs, run }) => { const timer = setTimeout(run, delayMs); return () => clearTimeout(timer); } };
123
148
  }
149
+ /** Native deserialization supplies plain objects; accept only this channel's envelope. O(1). */
150
+ function isIpcEnvelope(message) {
151
+ if (typeof message !== "object" || message === null)
152
+ return false;
153
+ return "jiniIpc" in message && message.jiniIpc === 1 && "id" in message && typeof message.id === "string" && "kind" in message;
154
+ }
155
+ /** Only explicitly public, bounded refusal text may cross IPC. Raw handler messages stay private.
156
+ * @complexity O(1); the caller owns choosing a reason that contains no private data.
157
+ */
158
+ export function ipcRefusalReason({ value }, _optional = {}) {
159
+ if (typeof value !== "object" || value === null || !("refusalReason" in value))
160
+ return undefined;
161
+ const reason = value.refusalReason;
162
+ if (typeof reason !== "string")
163
+ return undefined;
164
+ return reason.length > 0 && reason.length <= 1024 ? reason : undefined;
165
+ }
166
+ /** Native request/reply with bounded pending work. Errors never echo a request, payload or raw handler error.
167
+ * Handlers may opt into public diagnostics by throwing an error with a `refusalReason` string
168
+ * (1–1024 characters), e.g. `Object.assign(new Error(), { refusalReason: "This session ended." })`.
169
+ * @param required The actual spawned child or inherited process channel.
170
+ * @param optional Handler, deadline and pending-request cap; construction starts no requests.
171
+ * @returns Request and idempotent disposal; disconnect rejects and clears every pending request.
172
+ * @throws On disconnected IPC, timeout, refusal, >1 MiB envelope or capacity overflow.
173
+ * @complexity O(payload bytes) per send, O(p) disconnect for at most maxPending requests.
174
+ */
175
+ export function createNodeIpcChannel({ peer }, { handle, timeoutMs = 30_000, maxPending = 64, channel, } = {}) {
176
+ const pending = new Map();
177
+ let disposed = false;
178
+ let handling = 0;
179
+ function send(envelope) {
180
+ const message = channel === undefined ? envelope : { ...envelope, channel };
181
+ if (disposed || !peer.connected || !peer.send)
182
+ throw new Error("IPC disconnected");
183
+ if (Buffer.byteLength(JSON.stringify(message)) > 1024 * 1024)
184
+ throw new Error("IPC envelope too large");
185
+ peer.send(message, error => { if (error)
186
+ dispose({}); });
187
+ }
188
+ function reply(message) {
189
+ try {
190
+ send(message);
191
+ }
192
+ catch {
193
+ dispose({});
194
+ } // A departing peer cannot receive a refusal.
195
+ }
196
+ /** Complete only a matching request, preserving explicit public refusals. O(1) lookup. */
197
+ function receiveReply({ message }, _optional = {}) {
198
+ const refusalReason = ipcRefusalReason({ value: message });
199
+ const error = message.ok === true ? null : Object.assign(new Error(refusalReason ?? "IPC request refused"), refusalReason === undefined ? {} : { refusalReason });
200
+ pending.get(message.id)?.finish(error, message.payload);
201
+ }
202
+ function receive(message) {
203
+ if (disposed || !isIpcEnvelope(message) || message.channel !== channel)
204
+ return;
205
+ const { id } = message;
206
+ if (message.kind === "reply") {
207
+ receiveReply({ message });
208
+ }
209
+ else if (message.kind === "request" && handle) {
210
+ if (handling >= maxPending) {
211
+ reply({ jiniIpc: 1, kind: "reply", id, ok: false });
212
+ return;
213
+ }
214
+ handling++;
215
+ void Promise.resolve().then(() => handle(message.payload)).then(payload => reply({ jiniIpc: 1, kind: "reply", id, ok: true, payload }), error => {
216
+ const refusalReason = ipcRefusalReason({ value: error });
217
+ reply({ jiniIpc: 1, kind: "reply", id, ok: false, ...(refusalReason ? { refusalReason } : {}) });
218
+ }).catch(() => { }).finally(() => { handling--; }); // A disconnected peer cannot receive its reply.
219
+ }
220
+ }
221
+ function dispose(_required, _optional = {}) {
222
+ disposed = true;
223
+ peer.removeListener("message", receive);
224
+ peer.removeListener("disconnect", disconnect);
225
+ for (const request of pending.values())
226
+ request.finish(new Error("IPC disconnected"));
227
+ }
228
+ const disconnect = () => dispose({});
229
+ peer.on("message", receive);
230
+ peer.on("disconnect", disconnect);
231
+ return {
232
+ request({ payload }, _optional = {}) {
233
+ if (disposed || !peer.connected)
234
+ return Promise.reject(new Error("IPC disconnected"));
235
+ if (pending.size >= maxPending)
236
+ return Promise.reject(new Error("IPC capacity exceeded"));
237
+ const id = randomUUID();
238
+ return new Promise((resolve, reject) => {
239
+ const timer = setTimeout(() => pending.get(id)?.finish(new Error("IPC request timed out")), timeoutMs);
240
+ pending.set(id, { finish(error, value) { clearTimeout(timer); pending.delete(id); if (error)
241
+ reject(error);
242
+ else
243
+ resolve(value); } });
244
+ try {
245
+ send({ jiniIpc: 1, kind: "request", id, payload });
246
+ }
247
+ catch (error) {
248
+ const reason = error instanceof Error && error.message === "IPC envelope too large" ? error.message : "IPC send failed";
249
+ pending.get(id)?.finish(new Error(reason));
250
+ }
251
+ });
252
+ },
253
+ dispose,
254
+ };
255
+ }
256
+ /** Non-secret launch marker; the payload itself never enters argv or process.env. */
257
+ export const STARTUP_SECRETS_ENV = 'JINI_STARTUP_SECRETS_IPC';
258
+ /** Separate host-selected capabilities from a launch environment without mutating it.
259
+ * Windows case variants map to the canonical host key; absent values create no credential.
260
+ * @returns Independent environment and capability records; throws beyond the 64 KiB/256-key limit.
261
+ * @complexity O(e + k) time/space.
262
+ * @example splitNodeStartupSecrets({ env, keys: ['HOST_TOKEN'] });
263
+ */
264
+ export function splitNodeStartupSecrets({ env, keys }, _optional = {}) {
265
+ const names = new Map(keys.map(key => [key.toUpperCase(), key]));
266
+ const secrets = Object.fromEntries(Object.entries(env).flatMap(([key, value]) => {
267
+ const name = names.get(key.toUpperCase());
268
+ return name !== undefined && value !== undefined ? [[name, value]] : [];
269
+ }));
270
+ return { env: omitEnvironmentKeys({ env, keys }, { caseInsensitive: true }).env, secrets: startupSecretRecord(secrets) };
271
+ }
272
+ /** Validate the small startup record without echoing values into diagnostics. O(bytes), capped at 64 KiB. */
273
+ function startupSecretRecord(value) {
274
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
275
+ throw new Error('Invalid startup credentials');
276
+ const entries = Object.entries(value);
277
+ if (entries.length > 256 || entries.some(([, secret]) => typeof secret !== 'string'))
278
+ throw new Error('Invalid startup credentials');
279
+ if (Buffer.byteLength(JSON.stringify(value)) > 65536)
280
+ throw new Error('Startup credentials exceed limit');
281
+ return Object.fromEntries(entries);
282
+ }
283
+ /** Offer credentials to this native child once, sharing IPC with the existing control owner.
284
+ * @returns A disposer for child exit/error; disconnect also clears the channel.
285
+ * @throws For an invalid/oversized record. Refusals never contain credentials.
286
+ * @complexity O(bytes) bounded copy; one in-memory record until the child's first read.
287
+ * @example provideNodeStartupSecrets({ peer: child, secrets: { HOST_TOKEN: token } });
288
+ */
289
+ export function provideNodeStartupSecrets({ peer, secrets }, _optional = {}) {
290
+ let remaining = startupSecretRecord(secrets);
291
+ const channel = createNodeIpcChannel({ peer }, { channel: 'startup-secrets', handle: async (payload) => {
292
+ if (payload !== 'read' || remaining === undefined)
293
+ throw new Error('Startup credentials already consumed');
294
+ const result = remaining;
295
+ remaining = undefined;
296
+ return result;
297
+ } });
298
+ return { dispose(_required = {}, _options = {}) { remaining = undefined; channel.dispose({}); } };
299
+ }
300
+ /** Read credentials over inherited IPC and release the receiver even on timeout/disconnect.
301
+ * The caller retains the returned record in memory; it must never assign it to process.env.
302
+ * @throws On unavailable IPC, refusal, timeout or malformed credentials.
303
+ * @complexity O(bytes) bounded validation; one request with a 30s default deadline.
304
+ * @example const secrets = await receiveNodeStartupSecrets({ peer: process });
305
+ */
306
+ export async function receiveNodeStartupSecrets({ peer }, { timeoutMs = 30_000, } = {}) {
307
+ const channel = createNodeIpcChannel({ peer }, { channel: 'startup-secrets', timeoutMs });
308
+ try {
309
+ return startupSecretRecord(await channel.request({ payload: 'read' }, {}));
310
+ }
311
+ finally {
312
+ channel.dispose({});
313
+ }
314
+ }
124
315
  //# sourceMappingURL=supervisor-node.js.map
@@ -85,6 +85,8 @@ export interface DaemonSupervisorRequired {
85
85
  export interface DaemonSupervisorOptions {
86
86
  onDemandCooldownMs?: number;
87
87
  quietRoutineLifecycle?: boolean;
88
+ /** Normal exit codes that park until demand or manual restart, without charging the retry budget. */
89
+ parkedExitCodes?: readonly number[];
88
90
  formatGiveUp?: (input: {
89
91
  decision: Extract<RespawnDecision, {
90
92
  action: "give-up";
@@ -96,7 +98,15 @@ export interface DaemonSupervisorActionResult {
96
98
  ok: boolean;
97
99
  reason?: string;
98
100
  }
101
+ /** Lifecycle inspection; running describes a child, not discovery readiness. */
102
+ export type DaemonSupervisorState = "stopped" | "running" | "parked" | "shutting-down";
99
103
  export interface DaemonSupervisor {
104
+ /** Inspect lifecycle synchronously without starting a child or changing retry policy. */
105
+ getState(): DaemonSupervisorState;
106
+ /** Child refused intake before its normal park exit. Demand waits for exit before replacing it. */
107
+ markParking(requiredArgs: {
108
+ pid: number;
109
+ }, optionalArgs?: Record<string, never>): void;
100
110
  start(): void;
101
111
  restart(): DaemonSupervisorActionResult;
102
112
  ensureStarted(): DaemonSupervisorActionResult;
@@ -109,8 +119,8 @@ export interface DaemonSupervisor {
109
119
  /**
110
120
  * Wire a caller-owned process lifecycle to retry decisions without global handlers or host defaults.
111
121
  * @param deps Required process, policy, clock, scheduler, readiness and observability ports.
112
- * @param options On-demand cooldown, routine-event suppression and give-up message formatter.
113
- * @returns Idempotent start, manual replacement, cooldown-limited recovery and terminal shutdown.
122
+ * @param options On-demand cooldown, park exit codes, routine-event suppression and give-up formatter.
123
+ * @returns Inspectable lifecycle with idempotent start, demand wake, manual replacement and terminal shutdown.
114
124
  * @throws RangeError for a negative or non-finite cooldown.
115
125
  * @complexity O(1) state/work per event, excluding injected ports and policy window pruning.
116
126
  */
@@ -6,8 +6,8 @@ function giveUpReason({ decision, lastReason }) {
6
6
  /**
7
7
  * Wire a caller-owned process lifecycle to retry decisions without global handlers or host defaults.
8
8
  * @param deps Required process, policy, clock, scheduler, readiness and observability ports.
9
- * @param options On-demand cooldown, routine-event suppression and give-up message formatter.
10
- * @returns Idempotent start, manual replacement, cooldown-limited recovery and terminal shutdown.
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
11
  * @throws RangeError for a negative or non-finite cooldown.
12
12
  * @complexity O(1) state/work per event, excluding injected ports and policy window pruning.
13
13
  */
@@ -16,6 +16,8 @@ export function createDaemonSupervisor(deps, options = {}) {
16
16
  if (!Number.isFinite(cooldown) || cooldown < 0)
17
17
  throw new RangeError("onDemandCooldownMs must be finite and non-negative");
18
18
  const formatGiveUp = options.formatGiveUp ?? giveUpReason;
19
+ const parkedExitCodes = new Set(options.parkedExitCodes);
20
+ let parked = false;
19
21
  let current;
20
22
  let cancelRetry;
21
23
  // Terminal shutdown is a one-way latch, unlike a tripped retry cap. A restart racing
@@ -28,18 +30,22 @@ export function createDaemonSupervisor(deps, options = {}) {
28
30
  let discoveryWork;
29
31
  let cancelReadiness;
30
32
  function isCurrentLive({ candidate }) {
31
- return candidate !== undefined && current === candidate && !terminating && !candidate.exited && !candidate.stopping;
33
+ return candidate !== undefined && current === candidate && !terminating && !candidate.exited && !candidate.stopping && !candidate.parking;
32
34
  }
33
35
  function isReady() {
34
36
  return readyChild !== undefined && isCurrentLive({ candidate: readyChild });
35
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
+ }
36
42
  /** Discovery outlives individual request deadlines; never re-enter the demand cooldown.
37
43
  * O(1) state and at most one discovery read per 250ms, excluding the injected read itself. */
38
44
  function waitForReady() {
39
45
  return new Promise((resolve, reject) => {
40
46
  let settled = false;
41
47
  let cancelPoll;
42
- cancelReadiness = () => finish(new Error("shutting down"));
48
+ cancelReadiness = (error = new Error("shutting down")) => finish(error);
43
49
  function finish(error) {
44
50
  if (settled)
45
51
  return;
@@ -83,14 +89,25 @@ export function createDaemonSupervisor(deps, options = {}) {
83
89
  return Promise.resolve();
84
90
  if (!deps.readiness)
85
91
  return Promise.reject(new Error("readiness port is not configured"));
92
+ // A shared discovery may already exist; this demand still has to request replacement after
93
+ // the retiring child exits. Reuse that discovery rather than canceling its current waiters.
94
+ if (current?.parking)
95
+ supervisor.ensureStarted();
86
96
  if (!readyWork) {
87
97
  const start = supervisor.ensureStarted();
88
98
  if (!start.ok)
89
99
  return Promise.reject(new Error(start.reason));
90
100
  // A slow healthy child must keep being discovered after an HTTP caller gives up.
91
- // Share the monitor across subsequent demands; only shutdown cancels background polling.
92
- discoveryWork ??= waitForReady().finally(() => { discoveryWork = undefined; });
93
- readyWork = readinessDeadline({ work: discoveryWork, scheduler: deps.scheduler }).finally(() => { readyWork = undefined; });
101
+ // Share the monitor across subsequent demands; shutdown or parking cancels polling.
102
+ // A parked waiter's cleanup must not clear a fresh wake's discovery or request work.
103
+ if (!discoveryWork) {
104
+ const discovery = waitForReady().finally(() => { if (discoveryWork === discovery)
105
+ discoveryWork = undefined; });
106
+ discoveryWork = discovery;
107
+ }
108
+ const ready = readinessDeadline({ work: discoveryWork, scheduler: deps.scheduler }).finally(() => { if (readyWork === ready)
109
+ readyWork = undefined; });
110
+ readyWork = ready;
94
111
  }
95
112
  return signal ? awaitForCaller({ work: readyWork, signal }) : readyWork;
96
113
  }
@@ -127,6 +144,16 @@ export function createDaemonSupervisor(deps, options = {}) {
127
144
  }
128
145
  }
129
146
  function handleUnexpectedExit(code, signal) {
147
+ // Recognize the host's normal park code before classification can charge a crash or bind failure.
148
+ if (code !== null && parkedExitCodes.has(code)) {
149
+ parked = true;
150
+ cancelPendingRetry();
151
+ cancelReadiness?.(new Error("daemon parked"));
152
+ readyChild = undefined;
153
+ readyWork = undefined;
154
+ discoveryWork = undefined;
155
+ return;
156
+ }
130
157
  const classification = deps.classifyExit({ code, signal });
131
158
  reportFailure(classification.reason);
132
159
  const decision = deps.policy.recordFailure({ isPortConflict: classification.isPortConflict });
@@ -137,7 +164,7 @@ export function createDaemonSupervisor(deps, options = {}) {
137
164
  cancelRetry = deps.scheduler.schedule({ delayMs: decision.delayMs, run: () => { cancelRetry = undefined; attemptSpawn(); } });
138
165
  }
139
166
  function attemptSpawn() {
140
- if (terminating || (current !== undefined && (!current.exited || current.stopping)))
167
+ if (terminating || parked || hasUnreapedChild())
141
168
  return;
142
169
  // A new attempt must not inherit a stale readiness failure from an earlier child.
143
170
  deps.failureReporter.clear();
@@ -149,7 +176,7 @@ export function createDaemonSupervisor(deps, options = {}) {
149
176
  reportFailure(`failed to start daemon: ${error instanceof Error ? error.message : String(error)}`);
150
177
  return;
151
178
  }
152
- const state = { child, exited: false, deliberate: false, replaceAfterExit: false, stopping: false };
179
+ const state = { child, exited: false, deliberate: false, replaceAfterExit: false, stopping: false, parking: false };
153
180
  // Assign synchronously: run-to-completion makes request-driven recovery single-flight
154
181
  // without a lock or an await between checking the current child and publishing it.
155
182
  current = state;
@@ -192,6 +219,7 @@ export function createDaemonSupervisor(deps, options = {}) {
192
219
  // Wait for a still-live child to exit before replacement: spawning alongside it would
193
220
  // collide on its listening port and manufacture the bind failure we are recovering from.
194
221
  function forceFreshSpawn() {
222
+ parked = false;
195
223
  if (current?.stopping) {
196
224
  current.replaceAfterExit = true;
197
225
  return;
@@ -208,6 +236,19 @@ export function createDaemonSupervisor(deps, options = {}) {
208
236
  }
209
237
  const supervisor = {
210
238
  isReady, ensureReady,
239
+ markParking({ pid }, _optional = {}) {
240
+ if (!current || current.child.pid !== pid || current.exited || terminating)
241
+ return;
242
+ current.parking = true;
243
+ readyChild = undefined;
244
+ },
245
+ getState() {
246
+ if (terminating)
247
+ return "shutting-down";
248
+ if (parked)
249
+ return "parked";
250
+ return current !== undefined && !current.exited ? "running" : "stopped";
251
+ },
211
252
  start() { if (cancelRetry === undefined)
212
253
  attemptSpawn(); },
213
254
  restart() {
@@ -221,9 +262,19 @@ export function createDaemonSupervisor(deps, options = {}) {
221
262
  ensureStarted() {
222
263
  if (terminating)
223
264
  return { ok: false, reason: "shutting down" };
265
+ if (current?.parking && !current.exited) {
266
+ current.replaceAfterExit = true;
267
+ return { ok: true };
268
+ }
224
269
  // A scheduled retry keeps its own backoff; request traffic must not accelerate it.
225
- if ((current !== undefined && (!current.exited || current.stopping)) || cancelRetry !== undefined)
270
+ if (hasUnreapedChild() || cancelRetry !== undefined)
271
+ return { ok: true };
272
+ // Parking is healthy idleness: wake immediately, retaining all earlier crash history.
273
+ if (parked) {
274
+ lastOnDemandAttemptAt = deps.now();
275
+ forceFreshSpawn();
226
276
  return { ok: true };
277
+ }
227
278
  // Single-flight alone cannot stop a storm against a durably broken launch. The 30s
228
279
  // default floor matches the standard backoff ceiling, bounding traffic-driven retries
229
280
  // to the same worst-case rate as timer-driven recovery after a cap or spawn failure.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/sidecar",
3
- "version": "0.6.17",
3
+ "version": "0.6.21",
4
4
  "description": "Sidecar process runtime: JSON-IPC server and client, IPC path validation, namespace/runtime path resolution, port allocation, launch bootstrap, and a local daemon registry.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -63,12 +63,12 @@
63
63
  },
64
64
  "devDependencies": {
65
65
  "@vitest/coverage-v8": "^2.1.9",
66
- "@jini-ai/platform": "0.6.17",
67
- "@jini-ai/core": "0.6.17"
66
+ "@jini-ai/core": "0.6.21",
67
+ "@jini-ai/platform": "0.6.19"
68
68
  },
69
69
  "dependencies": {
70
- "@jini-ai/core": "^0.6.17",
71
- "@jini-ai/platform": "^0.6.17"
70
+ "@jini-ai/core": "^0.6.21",
71
+ "@jini-ai/platform": "^0.6.19"
72
72
  },
73
73
  "scripts": {
74
74
  "build": "tsc -p tsconfig.json",