@jini-ai/sidecar 0.3.0 → 0.4.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 (46) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/README.md +39 -13
  3. package/dist/bootstrap.d.ts +6 -3
  4. package/dist/bootstrap.js +9 -14
  5. package/dist/daemon-registry.d.ts +20 -6
  6. package/dist/daemon-registry.js +38 -12
  7. package/dist/index.d.ts +3 -1
  8. package/dist/index.js +2 -0
  9. package/dist/ipc-path.d.ts +6 -2
  10. package/dist/ipc-path.js +3 -3
  11. package/dist/json-file.d.ts +17 -6
  12. package/dist/json-file.js +16 -14
  13. package/dist/json-ipc.d.ts +12 -4
  14. package/dist/json-ipc.js +15 -15
  15. package/dist/paths.d.ts +10 -7
  16. package/dist/paths.js +15 -15
  17. package/dist/port.d.ts +10 -2
  18. package/dist/port.js +5 -5
  19. package/dist/respawn-policy.d.ts +51 -0
  20. package/dist/respawn-policy.js +46 -0
  21. package/dist/supervisor-node.d.ts +62 -0
  22. package/dist/supervisor-node.js +98 -0
  23. package/dist/supervisor.d.ts +106 -0
  24. package/dist/supervisor.js +178 -0
  25. package/dist/types.d.ts +32 -12
  26. package/package.json +40 -5
  27. package/dist/bootstrap.d.ts.map +0 -1
  28. package/dist/bootstrap.js.map +0 -1
  29. package/dist/daemon-registry.d.ts.map +0 -1
  30. package/dist/daemon-registry.js.map +0 -1
  31. package/dist/index.d.ts.map +0 -1
  32. package/dist/index.js.map +0 -1
  33. package/dist/ipc-path.d.ts.map +0 -1
  34. package/dist/ipc-path.js.map +0 -1
  35. package/dist/json-file.d.ts.map +0 -1
  36. package/dist/json-file.js.map +0 -1
  37. package/dist/json-ipc.d.ts.map +0 -1
  38. package/dist/json-ipc.js.map +0 -1
  39. package/dist/net.d.ts.map +0 -1
  40. package/dist/net.js.map +0 -1
  41. package/dist/paths.d.ts.map +0 -1
  42. package/dist/paths.js.map +0 -1
  43. package/dist/port.d.ts.map +0 -1
  44. package/dist/port.js.map +0 -1
  45. package/dist/types.d.ts.map +0 -1
  46. package/dist/types.js.map +0 -1
package/dist/json-ipc.js CHANGED
@@ -99,7 +99,7 @@ function errorMessage(error) {
99
99
  * hand today — matching this repo's "extract into a directly-testable pure
100
100
  * function" convention rather than narrowing the type away.
101
101
  */
102
- export function jsonIpcError(error) {
102
+ export function jsonIpcError({ error }) {
103
103
  return {
104
104
  ...(errorCode(error) == null ? {} : { code: errorCode(error) }),
105
105
  message: errorMessage(error),
@@ -130,7 +130,7 @@ async function staleUnixSocketExists(socketPath) {
130
130
  // was provably unreachable (verified empirically this session: forcing
131
131
  // a second event through a fake socket finds zero listeners and crashes
132
132
  // the process outright, rather than reaching that guard — see
133
- // source-map.md's 2026-07-22 entry) — removed as a real refactor rather
133
+ // archived provenance ledger's 2026-07-22 entry) — removed as a real refactor rather
134
134
  // than padded with a test that can't exercise real behavior.
135
135
  const settle = (callback) => {
136
136
  socket.removeAllListeners();
@@ -160,8 +160,8 @@ async function staleUnixSocketExists(socketPath) {
160
160
  * Windows. Testing this function directly (asserting no filesystem call
161
161
  * happens) verifies the real behavior on every platform this runs on.
162
162
  */
163
- export async function prepareIpcPath(socketPath) {
164
- if (isWindowsNamedPipePath(socketPath))
163
+ export async function prepareIpcPath({ socketPath }) {
164
+ if (isWindowsNamedPipePath({ value: socketPath }))
165
165
  return;
166
166
  await mkdir(dirname(socketPath), { recursive: true });
167
167
  if (await staleUnixSocketExists(socketPath))
@@ -173,8 +173,8 @@ export async function prepareIpcPath(socketPath) {
173
173
  * `{ok:true,result}` (or `{ok:false,error}` on parse/handler failure).
174
174
  * @returns A handle whose `close()` stops the server and unlinks the socket.
175
175
  */
176
- export async function createJsonIpcServer({ handler, socketPath, maxFrameBytes = DEFAULT_MAX_FRAME_BYTES, idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS, }) {
177
- await prepareIpcPath(socketPath);
176
+ export async function createJsonIpcServer({ handler, socketPath, }, { maxFrameBytes = DEFAULT_MAX_FRAME_BYTES, idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS } = {}) {
177
+ await prepareIpcPath({ socketPath });
178
178
  const server = createNetServer((socket) => {
179
179
  let buffer = "";
180
180
  let receivedBytes = 0;
@@ -206,7 +206,7 @@ export async function createJsonIpcServer({ handler, socketPath, maxFrameBytes =
206
206
  // execution model means no other callback (including this one) can
207
207
  // run in between that assignment and the `clearTimeout` call. Kept as
208
208
  // a real fail-safe (in case a future edit reorders that sequence)
209
- // rather than asserted away — see source-map.md's 2026-07-22 entry.
209
+ // rather than asserted away — see archived provenance ledger's 2026-07-22 entry.
210
210
  if (handled)
211
211
  return;
212
212
  handled = true;
@@ -228,7 +228,7 @@ export async function createJsonIpcServer({ handler, socketPath, maxFrameBytes =
228
228
  // the installed `@types/node`'s `net.d.ts` this session; not asserted
229
229
  // away since a test would have to manually `.emit()` a fabricated
230
230
  // non-Error value to reach the other side, which isn't real socket
231
- // behavior (see source-map.md's 2026-07-22 entry).
231
+ // behavior (see archived provenance ledger's 2026-07-22 entry).
232
232
  traceJsonIpc("server.socket_error", {
233
233
  durationMs: jsonIpcTraceDurationMs(startedAt),
234
234
  error: error instanceof Error ? error.message : String(error),
@@ -288,7 +288,7 @@ export async function createJsonIpcServer({ handler, socketPath, maxFrameBytes =
288
288
  // genuine `SyntaxError` (an `Error` instance) for any string input
289
289
  // — never a non-Error value — matching the same reasoning as the
290
290
  // socket-error `instanceof Error` checks above (see
291
- // source-map.md's 2026-07-22 entry).
291
+ // archived provenance ledger's 2026-07-22 entry).
292
292
  traceJsonIpc("server.frame_parse_failed", {
293
293
  durationMs: jsonIpcTraceDurationMs(startedAt),
294
294
  error: error instanceof Error ? error.message : String(error),
@@ -298,7 +298,7 @@ export async function createJsonIpcServer({ handler, socketPath, maxFrameBytes =
298
298
  });
299
299
  socket.end(`${JSON.stringify({
300
300
  ok: false,
301
- error: jsonIpcError(error),
301
+ error: jsonIpcError({ error }),
302
302
  })}\n`);
303
303
  return;
304
304
  }
@@ -317,7 +317,7 @@ export async function createJsonIpcServer({ handler, socketPath, maxFrameBytes =
317
317
  socketPath,
318
318
  traceId,
319
319
  });
320
- const result = await handler(message);
320
+ const result = await handler({ message });
321
321
  traceJsonIpc("server.handler_success", {
322
322
  durationMs: jsonIpcTraceDurationMs(startedAt),
323
323
  message: messageSummary,
@@ -331,7 +331,7 @@ export async function createJsonIpcServer({ handler, socketPath, maxFrameBytes =
331
331
  // same trust-boundary concern as SEC-005's HTTP fix). The peer gets a stable code plus
332
332
  // the traceId as a correlation handle; the real detail is redacted and logged
333
333
  // server-side only, unconditionally (not gated behind JINI_JSON_IPC_TRACE).
334
- const redactedDetail = redactSecrets(error instanceof Error ? error.message : String(error));
334
+ const redactedDetail = redactSecrets({ input: error instanceof Error ? error.message : String(error) });
335
335
  // eslint-disable-next-line no-console
336
336
  console.error(`[@jini-ai/sidecar] json-ipc handler failed (traceId=${traceId})`, redactedDetail);
337
337
  traceJsonIpc("server.handler_failed", {
@@ -358,7 +358,7 @@ export async function createJsonIpcServer({ handler, socketPath, maxFrameBytes =
358
358
  return {
359
359
  async close() {
360
360
  await closeServer(server);
361
- if (!isWindowsNamedPipePath(socketPath))
361
+ if (!isWindowsNamedPipePath({ value: socketPath }))
362
362
  await rm(socketPath, { force: true });
363
363
  },
364
364
  };
@@ -368,7 +368,7 @@ export async function createJsonIpcServer({ handler, socketPath, maxFrameBytes =
368
368
  * resolve with the server's `result`, rejecting on error response or timeout.
369
369
  * @returns The server's `result` payload.
370
370
  */
371
- export async function requestJsonIpc(socketPath, payload, { timeoutMs = 1500 } = {}) {
371
+ export async function requestJsonIpc({ socketPath, payload }, { timeoutMs = 1500 } = {}) {
372
372
  return await new Promise((resolveRequest, rejectRequest) => {
373
373
  const socket = createConnection(socketPath);
374
374
  const traceId = nextJsonIpcTraceId();
@@ -475,7 +475,7 @@ export async function requestJsonIpc(socketPath, payload, { timeoutMs = 1500 } =
475
475
  socket.on("error", (error) => {
476
476
  // Same defense-in-depth, not-reachable-through-real-usage reasoning as
477
477
  // the server-side `error instanceof Error` check above (see that
478
- // comment + source-map.md's 2026-07-22 entry).
478
+ // comment + archived provenance ledger's 2026-07-22 entry).
479
479
  traceJsonIpc("client.socket_error", {
480
480
  durationMs: jsonIpcTraceDurationMs(startedAt),
481
481
  error: error instanceof Error ? error.message : String(error),
package/dist/paths.d.ts CHANGED
@@ -8,18 +8,20 @@
8
8
  * product-specific strings are hardcoded here. Depends on `node:path` and the
9
9
  * public types.
10
10
  */
11
- import type { AppIpcPathRequest, AppRuntimePathRequest, BaseResolutionOptions, NamespaceResolutionOptions, ProjectRuntimePathRequest, RuntimePathRequest, RuntimeRootRequest, SidecarContractDescriptor, SidecarRuntimeContext, SidecarStampShape } from "./types.js";
11
+ import type { AppIpcPathRequest, AppRuntimePathRequest, BaseResolutionOptions, BaseResolutionOptionsOptionalArgs, AppIpcPathRequestOptionalArgs, NamespaceResolutionOptions, NamespaceOptionalArgs, ProjectRuntimePathRequest, RuntimePathRequest, RuntimeRootRequest, SidecarContractDescriptor, SidecarRuntimeContext, SidecarStampShape } from "./types.js";
12
12
  /**
13
13
  * Resolve the effective namespace from an explicit value, the env var named by
14
14
  * the contract, or the contract default — then normalize it.
15
15
  * @returns The normalized namespace.
16
16
  */
17
- export declare function resolveNamespace<TStamp extends SidecarStampShape>(options: NamespaceResolutionOptions<TStamp>): string;
17
+ export declare function resolveNamespace<TStamp extends SidecarStampShape>({ contract }: Pick<NamespaceResolutionOptions<TStamp>, "contract">, options?: NamespaceOptionalArgs): string;
18
18
  /**
19
19
  * Validate and resolve a project root to an absolute path.
20
20
  * @returns The resolved absolute project root.
21
21
  */
22
- export declare function resolveProjectRoot(projectRoot: string): string;
22
+ export declare function resolveProjectRoot({ projectRoot }: {
23
+ projectRoot: string;
24
+ }): string;
23
25
  /**
24
26
  * Resolve the project's tmp root (`<projectRoot>/<projectTmpDirName>`).
25
27
  * @returns The resolved tmp root path.
@@ -38,7 +40,7 @@ export declare function resolveSourceRuntimeRoot<TStamp extends SidecarStampShap
38
40
  * contract, or the source runtime root.
39
41
  * @returns The resolved absolute base path.
40
42
  */
41
- export declare function resolveSidecarBase<TStamp extends SidecarStampShape>({ base, contract, env, projectRoot, source, }: BaseResolutionOptions<TStamp>): string;
43
+ export declare function resolveSidecarBase<TStamp extends SidecarStampShape>({ contract, source, }: BaseResolutionOptions<TStamp>, { base, env, projectRoot }?: BaseResolutionOptionsOptionalArgs): string;
42
44
  /**
43
45
  * Resolve the namespace root (`<base>/<namespace>`).
44
46
  * @returns The resolved namespace root path.
@@ -103,11 +105,12 @@ export declare function resolveLogsDir<TStamp extends SidecarStampShape>({ app,
103
105
  * Resolve an app's log file (`<logsDir>/<fileName>`, default `latest.log`).
104
106
  * @returns The resolved log file path.
105
107
  */
106
- export declare function resolveLogFilePath<TStamp extends SidecarStampShape>({ app, contract, fileName, runtimeRoot, }: {
108
+ export declare function resolveLogFilePath<TStamp extends SidecarStampShape>({ app, contract, runtimeRoot, }: {
107
109
  app: TStamp["app"] | string;
108
110
  contract: SidecarContractDescriptor<TStamp>;
109
- fileName?: string;
110
111
  runtimeRoot: string;
112
+ }, { fileName }?: {
113
+ fileName?: string;
111
114
  }): string;
112
115
  /**
113
116
  * Resolve an app's runtime dir under a namespace root (`<namespaceRoot>/<app>`).
@@ -126,5 +129,5 @@ export declare function resolveAppRuntimePath<TStamp extends SidecarStampShape>(
126
129
  * `<ipcBase>/<namespace>/<app>.sock`.
127
130
  * @returns The resolved IPC socket/pipe path.
128
131
  */
129
- export declare function resolveAppIpcPath<TStamp extends SidecarStampShape>({ app, contract, env, namespace, }: AppIpcPathRequest<TStamp>): string;
132
+ export declare function resolveAppIpcPath<TStamp extends SidecarStampShape>({ app, contract, namespace, }: AppIpcPathRequest<TStamp>, { env }?: AppIpcPathRequestOptionalArgs): string;
130
133
  //# sourceMappingURL=paths.d.ts.map
package/dist/paths.js CHANGED
@@ -14,16 +14,16 @@ import { dirname, isAbsolute, join, resolve } from "node:path";
14
14
  * the contract, or the contract default — then normalize it.
15
15
  * @returns The normalized namespace.
16
16
  */
17
- export function resolveNamespace(options) {
18
- return options.contract.normalizeNamespace(options.namespace ??
19
- options.env?.[options.contract.env.namespace] ??
20
- options.contract.defaults.namespace);
17
+ export function resolveNamespace({ contract }, options = {}) {
18
+ return contract.normalizeNamespace({ namespace: options.namespace ??
19
+ options.env?.[contract.env.namespace] ??
20
+ contract.defaults.namespace });
21
21
  }
22
22
  /**
23
23
  * Validate and resolve a project root to an absolute path.
24
24
  * @returns The resolved absolute project root.
25
25
  */
26
- export function resolveProjectRoot(projectRoot) {
26
+ export function resolveProjectRoot({ projectRoot }) {
27
27
  if (typeof projectRoot !== "string" || projectRoot.trim().length === 0) {
28
28
  throw new Error("projectRoot must be a non-empty string");
29
29
  }
@@ -34,21 +34,21 @@ export function resolveProjectRoot(projectRoot) {
34
34
  * @returns The resolved tmp root path.
35
35
  */
36
36
  export function resolveProjectTmpRoot({ contract, projectRoot, }) {
37
- return join(resolveProjectRoot(projectRoot), contract.defaults.projectTmpDirName);
37
+ return join(resolveProjectRoot({ projectRoot }), contract.defaults.projectTmpDirName);
38
38
  }
39
39
  /**
40
40
  * Resolve the source-scoped runtime root (`<projectTmpRoot>/<source>`).
41
41
  * @returns The resolved source runtime root path.
42
42
  */
43
43
  export function resolveSourceRuntimeRoot({ contract, projectRoot, source, }) {
44
- return join(resolveProjectTmpRoot({ contract, projectRoot }), contract.normalizeSource(source));
44
+ return join(resolveProjectTmpRoot({ contract, projectRoot }), contract.normalizeSource({ source }));
45
45
  }
46
46
  /**
47
47
  * Resolve the sidecar base from an explicit value, the env var named by the
48
48
  * contract, or the source runtime root.
49
49
  * @returns The resolved absolute base path.
50
50
  */
51
- export function resolveSidecarBase({ base, contract, env = process.env, projectRoot = process.cwd(), source, }) {
51
+ export function resolveSidecarBase({ contract, source, }, { base, env = process.env, projectRoot = process.cwd() } = {}) {
52
52
  return resolve(base ?? env[contract.env.base] ?? resolveSourceRuntimeRoot({ contract, projectRoot, source }));
53
53
  }
54
54
  /**
@@ -56,7 +56,7 @@ export function resolveSidecarBase({ base, contract, env = process.env, projectR
56
56
  * @returns The resolved namespace root path.
57
57
  */
58
58
  export function resolveNamespaceRoot({ base, contract, namespace, }) {
59
- return join(resolve(base), contract.normalizeNamespace(namespace));
59
+ return join(resolve(base), contract.normalizeNamespace({ namespace }));
60
60
  }
61
61
  /**
62
62
  * Resolve the namespace root (the directory that holds `logs/`, `runs/`,
@@ -117,13 +117,13 @@ export function resolveManifestPath({ runtimeRoot }) {
117
117
  * @returns The resolved logs directory path.
118
118
  */
119
119
  export function resolveLogsDir({ app, contract, runtimeRoot, }) {
120
- return join(runtimeRoot, "logs", contract.normalizeApp(app));
120
+ return join(runtimeRoot, "logs", contract.normalizeApp({ app }));
121
121
  }
122
122
  /**
123
123
  * Resolve an app's log file (`<logsDir>/<fileName>`, default `latest.log`).
124
124
  * @returns The resolved log file path.
125
125
  */
126
- export function resolveLogFilePath({ app, contract, fileName = "latest.log", runtimeRoot, }) {
126
+ export function resolveLogFilePath({ app, contract, runtimeRoot, }, { fileName = "latest.log" } = {}) {
127
127
  return join(resolveLogsDir({ app, contract, runtimeRoot }), fileName);
128
128
  }
129
129
  /**
@@ -131,7 +131,7 @@ export function resolveLogFilePath({ app, contract, fileName = "latest.log", run
131
131
  * @returns The resolved app runtime directory path.
132
132
  */
133
133
  export function resolveAppRuntimeDir({ app, contract, namespaceRoot, }) {
134
- return join(namespaceRoot, contract.normalizeApp(app));
134
+ return join(namespaceRoot, contract.normalizeApp({ app }));
135
135
  }
136
136
  /**
137
137
  * Resolve a file inside an app's runtime dir, rejecting non-simple file names.
@@ -148,9 +148,9 @@ export function resolveAppRuntimePath({ app, contract, fileName, namespaceRoot,
148
148
  * `<ipcBase>/<namespace>/<app>.sock`.
149
149
  * @returns The resolved IPC socket/pipe path.
150
150
  */
151
- export function resolveAppIpcPath({ app, contract, env = process.env, namespace, }) {
152
- const normalizedApp = contract.normalizeApp(app);
153
- const normalizedNamespace = contract.normalizeNamespace(namespace);
151
+ export function resolveAppIpcPath({ app, contract, namespace, }, { env = process.env } = {}) {
152
+ const normalizedApp = contract.normalizeApp({ app });
153
+ const normalizedNamespace = contract.normalizeNamespace({ namespace });
154
154
  if (process.platform === "win32") {
155
155
  return `\\\\.\\pipe\\${contract.defaults.windowsPipePrefix}-${normalizedNamespace}-${normalizedApp}`;
156
156
  }
package/dist/port.d.ts CHANGED
@@ -14,11 +14,19 @@ import type { PortAllocation, PortRequest } from "./types.js";
14
14
  * platform-specific and not something a test should depend on for a hard-coded 20-reserved-port
15
15
  * scenario. `allocatePort` always calls this with the real {@link probeEphemeralPort}.
16
16
  */
17
- export declare function allocateDynamicPort(label: string, host: string, reserved: Set<number>, probe?: (host: string) => Promise<number>): Promise<PortAllocation>;
17
+ export declare function allocateDynamicPort({ label, host, reserved }: {
18
+ label: string;
19
+ host: string;
20
+ reserved: Set<number>;
21
+ }, { probe }?: {
22
+ probe?: (requiredArgs: {
23
+ host: string;
24
+ }) => Promise<number>;
25
+ }): Promise<PortAllocation>;
18
26
  /**
19
27
  * Allocate a port: a forced port when one is supplied, otherwise a dynamic one,
20
28
  * recording it in the `reserved` set to avoid double-allocation.
21
29
  * @returns The port allocation (port + how it was chosen).
22
30
  */
23
- export declare function allocatePort({ host, label, port, reserved, }?: PortRequest): Promise<PortAllocation>;
31
+ export declare function allocatePort(_requiredArgs: Record<string, never>, { host, label, port, reserved, }?: PortRequest): Promise<PortAllocation>;
24
32
  //# sourceMappingURL=port.d.ts.map
package/dist/port.js CHANGED
@@ -59,7 +59,7 @@ async function allocateForcedPort(port, label, host, reserved) {
59
59
  * @internal Probes one ephemeral port via a real bind(0)-listen-then-close cycle — the OS
60
60
  * hands back whatever port it currently considers free.
61
61
  */
62
- async function probeEphemeralPort(host) {
62
+ async function probeEphemeralPort({ host }) {
63
63
  const server = await listenOnPort(0, host);
64
64
  const address = server.address();
65
65
  await closeServer(server);
@@ -76,9 +76,9 @@ async function probeEphemeralPort(host) {
76
76
  * platform-specific and not something a test should depend on for a hard-coded 20-reserved-port
77
77
  * scenario. `allocatePort` always calls this with the real {@link probeEphemeralPort}.
78
78
  */
79
- export async function allocateDynamicPort(label, host, reserved, probe = probeEphemeralPort) {
79
+ export async function allocateDynamicPort({ label, host, reserved }, { probe = probeEphemeralPort } = {}) {
80
80
  for (let attempt = 0; attempt < 20; attempt += 1) {
81
- const port = await probe(host);
81
+ const port = await probe({ host });
82
82
  if (!reserved.has(port)) {
83
83
  reserved.add(port);
84
84
  return { port, source: "dynamic" };
@@ -91,10 +91,10 @@ export async function allocateDynamicPort(label, host, reserved, probe = probeEp
91
91
  * recording it in the `reserved` set to avoid double-allocation.
92
92
  * @returns The port allocation (port + how it was chosen).
93
93
  */
94
- export async function allocatePort({ host = "127.0.0.1", label = "runtime", port, reserved = new Set(), } = {}) {
94
+ export async function allocatePort(_requiredArgs, { host = "127.0.0.1", label = "runtime", port, reserved = new Set(), } = {}) {
95
95
  const forcedPort = parsePort(port, label);
96
96
  return forcedPort == null
97
- ? await allocateDynamicPort(label, host, reserved)
97
+ ? await allocateDynamicPort({ label, host, reserved })
98
98
  : await allocateForcedPort(forcedPort, label, host, reserved);
99
99
  }
100
100
  //# sourceMappingURL=port.js.map
@@ -0,0 +1,51 @@
1
+ /** Rolling failure-window backoff with an independent consecutive port-conflict cap. */
2
+ /**
3
+ * Keep retry decisions free of process I/O and timers so an injected clock can exercise the
4
+ * policy without real delays or child processes. Backoff uses the same rolling window as the
5
+ * crash-loop cap, rather than lifetime attempts: hosts without a healthy-start acknowledgment
6
+ * still self-heal after quiet periods, and an isolated late crash starts at the fast end again.
7
+ * Consecutive port conflicts get a separate, tighter cap. A leaked port either clears during
8
+ * the first short retries or does not; climbing the entire crash ladder cannot fix a stuck port.
9
+ * A different failure resets that counter because it tracks this specific problem, not general health.
10
+ */
11
+ export interface RespawnPolicyOptions {
12
+ backoffScheduleMs?: readonly number[];
13
+ crashLoopWindowMs?: number;
14
+ crashLoopMaxFailures?: number;
15
+ portConflictMaxAttempts?: number;
16
+ }
17
+ export interface RespawnFailureInput {
18
+ isPortConflict: boolean;
19
+ }
20
+ export type RespawnDecision = {
21
+ action: "retry";
22
+ delayMs: number;
23
+ attempt: number;
24
+ } | {
25
+ action: "give-up";
26
+ kind: "crash-loop";
27
+ attempts: number;
28
+ windowMs: number;
29
+ } | {
30
+ action: "give-up";
31
+ kind: "port-conflict";
32
+ attempts: number;
33
+ };
34
+ export interface RespawnPolicy {
35
+ recordFailure(input: RespawnFailureInput): RespawnDecision;
36
+ /** Manual recovery clears counters and the trip so an operator can force a fresh attempt. */
37
+ reset(): void;
38
+ isTripped(): boolean;
39
+ }
40
+ /**
41
+ * Create an independent retry policy; a caller-owned clock is mandatory.
42
+ * @param required Clock port, read once for each recorded failure.
43
+ * @param options Backoff ladder and rolling/consecutive failure thresholds.
44
+ * @returns Stateful policy with explicit reset for manual recovery.
45
+ * @throws RangeError for empty/negative backoff or invalid thresholds.
46
+ * @complexity O(w) per failure for w retained timestamps; reset is O(1).
47
+ */
48
+ export declare function createRespawnPolicy({ now }: {
49
+ now: () => number;
50
+ }, options?: RespawnPolicyOptions): RespawnPolicy;
51
+ //# sourceMappingURL=respawn-policy.d.ts.map
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Create an independent retry policy; a caller-owned clock is mandatory.
3
+ * @param required Clock port, read once for each recorded failure.
4
+ * @param options Backoff ladder and rolling/consecutive failure thresholds.
5
+ * @returns Stateful policy with explicit reset for manual recovery.
6
+ * @throws RangeError for empty/negative backoff or invalid thresholds.
7
+ * @complexity O(w) per failure for w retained timestamps; reset is O(1).
8
+ */
9
+ export function createRespawnPolicy({ now }, options = {}) {
10
+ const backoffScheduleMs = [...(options.backoffScheduleMs ?? [1000, 2000, 4000, 8000, 16000, 30000])];
11
+ const crashLoopWindowMs = options.crashLoopWindowMs ?? 60000;
12
+ const crashLoopMaxFailures = options.crashLoopMaxFailures ?? 5;
13
+ const portConflictMaxAttempts = options.portConflictMaxAttempts ?? 3;
14
+ if (backoffScheduleMs.length === 0 || backoffScheduleMs.some((delay) => !Number.isFinite(delay) || delay < 0)) {
15
+ throw new RangeError("backoffScheduleMs must contain finite non-negative delays");
16
+ }
17
+ if (!Number.isFinite(crashLoopWindowMs) || crashLoopWindowMs <= 0)
18
+ throw new RangeError("crashLoopWindowMs must be positive and finite");
19
+ for (const count of [crashLoopMaxFailures, portConflictMaxAttempts]) {
20
+ if (!Number.isSafeInteger(count) || count < 1)
21
+ throw new RangeError("failure thresholds must be positive safe integers");
22
+ }
23
+ let timestamps = [];
24
+ let consecutivePortConflicts = 0;
25
+ let tripped = false;
26
+ return {
27
+ recordFailure({ isPortConflict }) {
28
+ consecutivePortConflicts = isPortConflict ? consecutivePortConflicts + 1 : 0;
29
+ const time = now();
30
+ timestamps = [...timestamps.filter((stamp) => stamp > time - crashLoopWindowMs), time];
31
+ if (consecutivePortConflicts >= portConflictMaxAttempts) {
32
+ tripped = true;
33
+ return { action: "give-up", kind: "port-conflict", attempts: consecutivePortConflicts };
34
+ }
35
+ if (timestamps.length >= crashLoopMaxFailures) {
36
+ tripped = true;
37
+ return { action: "give-up", kind: "crash-loop", attempts: timestamps.length, windowMs: crashLoopWindowMs };
38
+ }
39
+ const attempt = timestamps.length;
40
+ return { action: "retry", delayMs: backoffScheduleMs[Math.min(attempt - 1, backoffScheduleMs.length - 1)], attempt };
41
+ },
42
+ reset() { timestamps = []; consecutivePortConflicts = 0; tripped = false; },
43
+ isTripped() { return tripped; },
44
+ };
45
+ }
46
+ //# sourceMappingURL=respawn-policy.js.map
@@ -0,0 +1,62 @@
1
+ import type { Writable } from "node:stream";
2
+ import type { ChildProcess, SpawnOptions } from "node:child_process";
3
+ import type { LocalDaemonRegistryRecord } from "./daemon-registry.js";
4
+ import type { SpawnedDaemonProcess, SupervisorScheduler } from "./supervisor.js";
5
+ export interface SupervisorRegistry {
6
+ readLive(): Promise<LocalDaemonRegistryRecord | null>;
7
+ write(input: {
8
+ record: LocalDaemonRegistryRecord;
9
+ }): Promise<void>;
10
+ removeIfCurrent(input: {
11
+ pid: number;
12
+ }): Promise<void>;
13
+ }
14
+ /**
15
+ * Reuse the sidecar registry's atomic records, liveness checks and ownership-guarded removal.
16
+ * The child calls write only after it actually starts listening.
17
+ * @param required Host-owned registry path.
18
+ * @returns A registry port with object arguments at all data-bearing boundaries.
19
+ * @complexity O(1) operations, excluding filesystem I/O.
20
+ */
21
+ export declare function createSupervisorRegistry({ registryPath }: {
22
+ registryPath: string;
23
+ }): SupervisorRegistry;
24
+ export interface NodeDaemonProcessRequired {
25
+ command: string;
26
+ args: readonly string[];
27
+ cwd: string;
28
+ env: NodeJS.ProcessEnv;
29
+ registry: SupervisorRegistry;
30
+ }
31
+ export interface NodeDaemonProcessOptions {
32
+ stdout?: Writable;
33
+ stderr?: Writable;
34
+ platform?: NodeJS.Platform;
35
+ /** Native spawn effect port; the adapter still constructs argv, environment and process options. */
36
+ spawn?: (input: {
37
+ command: string;
38
+ args: string[];
39
+ options: SpawnOptions;
40
+ }, optional?: Record<string, never>) => ChildProcess;
41
+ }
42
+ /**
43
+ * Node launch/tree-stop adapter using platform command quoting, snapshots and signal escalation.
44
+ * @param required Complete host launch settings and the shared sidecar registry port.
45
+ * @param options Optional native spawn port and sinks; output is piped through the parent rather than inherited.
46
+ * @returns Supervisor process ports. Construction has no process or filesystem effects.
47
+ * @complexity Tree stop is O(p) for p process snapshots, plus platform exit polling.
48
+ */
49
+ export declare function createNodeDaemonProcessAdapter(required: NodeDaemonProcessRequired, options?: NodeDaemonProcessOptions): {
50
+ spawnDaemonProcess(): SpawnedDaemonProcess;
51
+ terminateProcess(input: {
52
+ child: SpawnedDaemonProcess;
53
+ }): Promise<void>;
54
+ };
55
+ /**
56
+ * Node timer adapter; importing/constructing it schedules no work.
57
+ * @param required Empty required arguments object.
58
+ * @returns Scheduler using setTimeout and clearTimeout.
59
+ * @complexity O(1) per schedule/cancel.
60
+ */
61
+ export declare function createNodeSupervisorScheduler(_required: Record<string, never>): SupervisorScheduler;
62
+ //# sourceMappingURL=supervisor-node.d.ts.map
@@ -0,0 +1,98 @@
1
+ import { execFileSync, spawn } from "node:child_process";
2
+ import { collectProcessTreePids, createCommandInvocation, listProcessSnapshots, stopProcesses } from "@jini-ai/platform";
3
+ import { readLiveDaemonRegistryRecord, removeDaemonRegistryRecordIfCurrent, writeDaemonRegistryRecord } from "./daemon-registry.js";
4
+ /**
5
+ * Reuse the sidecar registry's atomic records, liveness checks and ownership-guarded removal.
6
+ * The child calls write only after it actually starts listening.
7
+ * @param required Host-owned registry path.
8
+ * @returns A registry port with object arguments at all data-bearing boundaries.
9
+ * @complexity O(1) operations, excluding filesystem I/O.
10
+ */
11
+ export function createSupervisorRegistry({ registryPath }) {
12
+ return {
13
+ readLive: () => readLiveDaemonRegistryRecord({ registryPath }),
14
+ write: ({ record }) => writeDaemonRegistryRecord({ registryPath, record }),
15
+ removeIfCurrent: ({ pid }) => removeDaemonRegistryRecordIfCurrent({ registryPath, pid }),
16
+ };
17
+ }
18
+ /**
19
+ * Node launch/tree-stop adapter using platform command quoting, snapshots and signal escalation.
20
+ * @param required Complete host launch settings and the shared sidecar registry port.
21
+ * @param options Optional native spawn port and sinks; output is piped through the parent rather than inherited.
22
+ * @returns Supervisor process ports. Construction has no process or filesystem effects.
23
+ * @complexity Tree stop is O(p) for p process snapshots, plus platform exit polling.
24
+ */
25
+ export function createNodeDaemonProcessAdapter(required, options = {}) {
26
+ return {
27
+ spawnDaemonProcess() {
28
+ const invocation = createCommandInvocation({ command: required.command, args: [...required.args], env: required.env });
29
+ // detached creates a POSIX process group so teardown reaches the daemon below a
30
+ // launcher hop; windowsHide avoids an otherwise visible detached Windows console.
31
+ // Pipe output through the parent instead of inheriting its descriptors: an orphan
32
+ // retaining those descriptors previously kept parent/test teardown waiting forever.
33
+ const spawnOptions = {
34
+ cwd: required.cwd, env: { ...required.env }, detached: true, windowsHide: true,
35
+ stdio: ["ignore", "pipe", "pipe"],
36
+ ...(invocation.windowsVerbatimArguments === undefined ? {} : { windowsVerbatimArguments: invocation.windowsVerbatimArguments }),
37
+ };
38
+ const child = options.spawn
39
+ ? options.spawn({ command: invocation.command, args: invocation.args, options: spawnOptions }, {})
40
+ : spawn(invocation.command, invocation.args, spawnOptions);
41
+ if (options.stdout !== undefined)
42
+ child.stdout?.pipe(options.stdout);
43
+ else
44
+ child.stdout?.resume();
45
+ if (options.stderr !== undefined)
46
+ child.stderr?.pipe(options.stderr);
47
+ else
48
+ child.stderr?.resume();
49
+ return {
50
+ get pid() { return child.pid; },
51
+ on(input) {
52
+ if (input.event === "exit")
53
+ child.on("exit", (code, signal) => input.listener({ code, signal }));
54
+ else
55
+ child.on("error", (error) => input.listener({ error }));
56
+ },
57
+ kill(_required, { signal } = {}) { return child.kill(signal); },
58
+ };
59
+ },
60
+ async terminateProcess({ child }) {
61
+ if (child.pid === undefined)
62
+ return;
63
+ const pid = child.pid;
64
+ const snapshotRequest = listProcessSnapshots();
65
+ // Signal before the first await: even a parent exiting immediately after shutdown reaps its tree.
66
+ // Windows has no group signal, so taskkill supplies the synchronous tree-stop equivalent.
67
+ // Windows has no POSIX group signal. Killing only the immediate launcher would
68
+ // orphan its daemon; taskkill /T walks the entire descendant tree instead.
69
+ try {
70
+ if ((options.platform ?? process.platform) === "win32") {
71
+ execFileSync("taskkill", ["/pid", String(pid), "/T", "/F"], { stdio: "ignore" });
72
+ }
73
+ else {
74
+ process.kill(-pid, "SIGTERM");
75
+ }
76
+ }
77
+ catch {
78
+ child.kill({}, { signal: "SIGTERM" });
79
+ }
80
+ const snapshots = await snapshotRequest;
81
+ const pids = collectProcessTreePids(snapshots, [pid]);
82
+ const result = await stopProcesses(pids);
83
+ if (result.remainingPids.length > 0)
84
+ throw new Error(`daemon processes still running: ${result.remainingPids.join(", ")}`);
85
+ await required.registry.removeIfCurrent({ pid });
86
+ },
87
+ };
88
+ }
89
+ /**
90
+ * Node timer adapter; importing/constructing it schedules no work.
91
+ * @param required Empty required arguments object.
92
+ * @returns Scheduler using setTimeout and clearTimeout.
93
+ * @complexity O(1) per schedule/cancel.
94
+ */
95
+ export function createNodeSupervisorScheduler(_required) {
96
+ return { schedule: ({ delayMs, run }) => { const timer = setTimeout(run, delayMs); return () => clearTimeout(timer); } };
97
+ }
98
+ //# sourceMappingURL=supervisor-node.js.map