@jini-ai/sidecar 0.4.3 → 0.4.4

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.4.4 — 2026-10-22
4
+
5
+ - 2026-10-22: Daemon registry, JSON IPC and respawn-policy refactors, coverage.
6
+
3
7
  ## 0.4.3 — 2026-10-13
4
8
 
5
9
  - Windows: the Node supervisor stops its daemon gracefully by closing a stdin pipe (launch env `JINI_STOP_ON_STDIN_EOF=1`), waits 5s, then falls back to `taskkill /T /F`. POSIX is unchanged. Hosts opt in by running their disposal on stdin `end` when the flag is set.
@@ -48,6 +48,17 @@ export declare function writeDaemonRegistryRecord({ registryPath, record }: {
48
48
  registryPath: string;
49
49
  record: LocalDaemonRegistryRecord;
50
50
  }): Promise<void>;
51
+ /** The two path moves `removeDaemonRegistryRecordIfCurrent` makes; injectable so a race lost to
52
+ * another remover, or a refused restore, can be reproduced without a real filesystem race. */
53
+ export interface DaemonRegistryFilePorts {
54
+ rename(oldPath: string, newPath: string): Promise<void>;
55
+ link(existingPath: string, newPath: string): Promise<void>;
56
+ }
57
+ /** Options for {@link removeDaemonRegistryRecordIfCurrent}. */
58
+ export interface RemoveDaemonRegistryRecordOptions {
59
+ /** Defaults to `node:fs/promises`' `rename` and `link`. */
60
+ readonly files?: DaemonRegistryFilePorts;
61
+ }
51
62
  /**
52
63
  * Remove a daemon's registry record at `registryPath`, but only if it still names `pid` as the
53
64
  * owning process — the same guarded-removal shape `json-file.ts`'s `removePointerIfCurrent` uses
@@ -57,7 +68,7 @@ export declare function writeDaemonRegistryRecord({ registryPath, record }: {
57
68
  export declare function removeDaemonRegistryRecordIfCurrent({ registryPath, pid }: {
58
69
  registryPath: string;
59
70
  pid: number;
60
- }): Promise<void>;
71
+ }, options?: RemoveDaemonRegistryRecordOptions): Promise<void>;
61
72
  /**
62
73
  * Probe whether OS process `pid` is currently alive, via `process.kill(pid, 0)` (sends no
63
74
  * actual signal — `0` only tests deliverability). This is the liveness half of "verify, don't
@@ -41,39 +41,50 @@ export function resolveDaemonRegistryPath({ dataDir }, { fileName = DEFAULT_DAEM
41
41
  export async function writeDaemonRegistryRecord({ registryPath, record }) {
42
42
  await writeJsonFile({ filePath: registryPath, payload: record });
43
43
  }
44
+ const DEFAULT_REGISTRY_FILE_PORTS = { rename, link };
45
+ /** Moves the public record aside; `false` when another remover already detached it (ENOENT). */
46
+ async function detachRecord(files, registryPath, tombstonePath) {
47
+ try {
48
+ await files.rename(registryPath, tombstonePath);
49
+ return true;
50
+ }
51
+ catch (error) {
52
+ if (error.code === "ENOENT")
53
+ return false;
54
+ throw error;
55
+ }
56
+ }
57
+ /** Puts a captured record that turned out to be foreign back, unless a newer one already exists. */
58
+ async function restoreCapturedRecord(files, tombstonePath, registryPath) {
59
+ try {
60
+ // A hard link restores the captured file atomically ONLY if no newer record exists.
61
+ // Rename would overwrite that newer writer. Keep the tombstone if restoration fails.
62
+ await files.link(tombstonePath, registryPath);
63
+ }
64
+ catch (error) {
65
+ if (error.code !== "EEXIST")
66
+ throw error;
67
+ }
68
+ }
44
69
  /**
45
70
  * Remove a daemon's registry record at `registryPath`, but only if it still names `pid` as the
46
71
  * owning process — the same guarded-removal shape `json-file.ts`'s `removePointerIfCurrent` uses
47
72
  * for its own pointer file. Guards a fast crash-restart race on a reused `dataDir`: an old
48
73
  * daemon's delayed shutdown cleanup must never delete a newer daemon's already-written record.
49
74
  */
50
- export async function removeDaemonRegistryRecordIfCurrent({ registryPath, pid }) {
75
+ export async function removeDaemonRegistryRecordIfCurrent({ registryPath, pid }, options = {}) {
51
76
  const record = await readJsonFile({ filePath: registryPath });
52
77
  if (record?.pid !== pid)
53
78
  return;
79
+ const files = options.files ?? DEFAULT_REGISTRY_FILE_PORTS;
54
80
  // Detach first, then check the captured record: a writer may replace the public path
55
81
  // between the initial read and this rename. Only the captured file is ever removed.
56
82
  const tombstonePath = `${registryPath}.${process.pid}.${randomUUID()}.removed`;
57
- try {
58
- await rename(registryPath, tombstonePath);
59
- }
60
- catch (error) {
61
- if (error.code === "ENOENT")
62
- return;
63
- throw error;
64
- }
83
+ if (!(await detachRecord(files, registryPath, tombstonePath)))
84
+ return;
65
85
  const captured = await readJsonFile({ filePath: tombstonePath });
66
- if (captured?.pid !== pid) {
67
- try {
68
- // A hard link restores the captured file atomically ONLY if no newer record exists.
69
- // Rename would overwrite that newer writer. Keep the tombstone if restoration fails.
70
- await link(tombstonePath, registryPath);
71
- }
72
- catch (error) {
73
- if (error.code !== "EEXIST")
74
- throw error;
75
- }
76
- }
86
+ if (captured?.pid !== pid)
87
+ await restoreCapturedRecord(files, tombstonePath, registryPath);
77
88
  await removeFile({ filePath: tombstonePath });
78
89
  }
79
90
  /**
@@ -99,6 +110,9 @@ export function isProcessAlive({ pid }) {
99
110
  return code === "EPERM";
100
111
  }
101
112
  }
113
+ function isPositiveInteger({ value }, _options = {}) {
114
+ return typeof value === "number" && Number.isInteger(value) && value > 0;
115
+ }
102
116
  /**
103
117
  * @internal Structural + type validation for a value read back from a registry file — a
104
118
  * cross-process JSON file is untrusted input (wrong version, hand-edited, truncated write from
@@ -112,12 +126,8 @@ function isValidRegistryRecord(value) {
112
126
  record.url.length > 0 &&
113
127
  typeof record.host === "string" &&
114
128
  record.host.length > 0 &&
115
- typeof record.port === "number" &&
116
- Number.isInteger(record.port) &&
117
- record.port > 0 &&
118
- typeof record.pid === "number" &&
119
- Number.isInteger(record.pid) &&
120
- record.pid > 0 &&
129
+ isPositiveInteger({ value: record.port }) &&
130
+ isPositiveInteger({ value: record.pid }) &&
121
131
  typeof record.startedAt === "string" &&
122
132
  record.startedAt.length > 0);
123
133
  }
package/dist/json-ipc.js CHANGED
@@ -198,17 +198,12 @@ export async function createJsonIpcServer({ handler, socketPath, }, { maxFrameBy
198
198
  // newline-terminated frame (or dribbles bytes indefinitely) would otherwise hold the
199
199
  // connection — and this closure's buffer — open forever.
200
200
  const idleTimer = setTimeout(() => {
201
- // Defense-in-depth, not reachable through any real timer/socket
202
- // interleaving: every real path that sets `handled = true` (a
203
- // complete frame arriving, or the oversized-frame guard) calls
204
- // `clearTimeout(idleTimer)` in the very same synchronous prefix of a
205
- // single `data`-listener invocation — and Node/V8's single-threaded
206
- // execution model means no other callback (including this one) can
207
- // run in between that assignment and the `clearTimeout` call. Kept as
208
- // a real fail-safe (in case a future edit reorders that sequence)
209
- // rather than asserted away — see archived provenance ledger's 2026-07-22 entry.
210
- if (handled)
211
- return;
201
+ // No `handled` re-check is needed here: the only way to set `handled` from a `data`
202
+ // event is `claimFrame()` below, which clears this timer in the same synchronous step —
203
+ // and Node/V8's single-threaded execution model means no other callback (including this
204
+ // one) can run in between that assignment and the `clearTimeout` call. The fail-safe the
205
+ // archived provenance ledger's 2026-07-22 entry kept against a future edit reordering that
206
+ // sequence is now structural: the two steps live in one function and cannot be split.
212
207
  handled = true;
213
208
  traceJsonIpc("server.idle_timeout", {
214
209
  durationMs: jsonIpcTraceDurationMs(startedAt),
@@ -219,6 +214,11 @@ export async function createJsonIpcServer({ handler, socketPath, }, { maxFrameBy
219
214
  socket.destroy();
220
215
  }, idleTimeoutMs);
221
216
  idleTimer.unref();
217
+ /** Claim this connection's one frame: stop accepting data and cancel the idle deadline together. */
218
+ const claimFrame = () => {
219
+ handled = true;
220
+ clearTimeout(idleTimer);
221
+ };
222
222
  socket.on("error", (error) => {
223
223
  // `error instanceof Error` here is defense-in-depth, not reachable
224
224
  // through real socket usage: @types/node itself types a `Socket`'s
@@ -231,7 +231,7 @@ export async function createJsonIpcServer({ handler, socketPath, }, { maxFrameBy
231
231
  // behavior (see archived provenance ledger's 2026-07-22 entry).
232
232
  traceJsonIpc("server.socket_error", {
233
233
  durationMs: jsonIpcTraceDurationMs(startedAt),
234
- error: error instanceof Error ? error.message : String(error),
234
+ error: errorMessage(error),
235
235
  socketPath,
236
236
  traceId,
237
237
  });
@@ -255,8 +255,7 @@ export async function createJsonIpcServer({ handler, socketPath, }, { maxFrameBy
255
255
  });
256
256
  receivedBytes += chunk.byteLength;
257
257
  if (receivedBytes > maxFrameBytes) {
258
- handled = true;
259
- clearTimeout(idleTimer);
258
+ claimFrame();
260
259
  traceJsonIpc("server.frame_too_large", {
261
260
  durationMs: jsonIpcTraceDurationMs(startedAt),
262
261
  maxFrameBytes,
@@ -274,8 +273,7 @@ export async function createJsonIpcServer({ handler, socketPath, }, { maxFrameBy
274
273
  const newlineIndex = buffer.indexOf("\n");
275
274
  if (newlineIndex < 0)
276
275
  return;
277
- handled = true; // Claim the connection before awaiting the handler — see the flag's own doc above.
278
- clearTimeout(idleTimer);
276
+ claimFrame(); // Claim the connection before awaiting the handler — see the flag's own doc above.
279
277
  const frame = buffer.slice(0, newlineIndex);
280
278
  buffer = buffer.slice(newlineIndex + 1);
281
279
  let message;
@@ -291,7 +289,7 @@ export async function createJsonIpcServer({ handler, socketPath, }, { maxFrameBy
291
289
  // archived provenance ledger's 2026-07-22 entry).
292
290
  traceJsonIpc("server.frame_parse_failed", {
293
291
  durationMs: jsonIpcTraceDurationMs(startedAt),
294
- error: error instanceof Error ? error.message : String(error),
292
+ error: errorMessage(error),
295
293
  frameBytes: Buffer.byteLength(frame),
296
294
  socketPath,
297
295
  traceId,
@@ -331,7 +329,7 @@ export async function createJsonIpcServer({ handler, socketPath, }, { maxFrameBy
331
329
  // same trust-boundary concern as SEC-005's HTTP fix). The peer gets a stable code plus
332
330
  // the traceId as a correlation handle; the real detail is redacted and logged
333
331
  // server-side only, unconditionally (not gated behind JINI_JSON_IPC_TRACE).
334
- const redactedDetail = redactSecrets({ input: error instanceof Error ? error.message : String(error) });
332
+ const redactedDetail = redactSecrets({ input: errorMessage(error) });
335
333
  // eslint-disable-next-line no-console
336
334
  console.error(`[@jini-ai/sidecar] json-ipc handler failed (traceId=${traceId})`, redactedDetail);
337
335
  traceJsonIpc("server.handler_failed", {
@@ -478,7 +476,7 @@ export async function requestJsonIpc({ socketPath, payload }, { timeoutMs = 1500
478
476
  // comment + archived provenance ledger's 2026-07-22 entry).
479
477
  traceJsonIpc("client.socket_error", {
480
478
  durationMs: jsonIpcTraceDurationMs(startedAt),
481
- error: error instanceof Error ? error.message : String(error),
479
+ error: errorMessage(error),
482
480
  message: messageSummary,
483
481
  socketPath,
484
482
  traceId,
@@ -1,3 +1,14 @@
1
+ function validateRespawnOptions({ backoffScheduleMs, crashLoopWindowMs, crashLoopMaxFailures, portConflictMaxAttempts }, _options = {}) {
2
+ if (backoffScheduleMs.length === 0 || backoffScheduleMs.some((delay) => !Number.isFinite(delay) || delay < 0)) {
3
+ throw new RangeError("backoffScheduleMs must contain finite non-negative delays");
4
+ }
5
+ if (!Number.isFinite(crashLoopWindowMs) || crashLoopWindowMs <= 0)
6
+ throw new RangeError("crashLoopWindowMs must be positive and finite");
7
+ for (const count of [crashLoopMaxFailures, portConflictMaxAttempts]) {
8
+ if (!Number.isSafeInteger(count) || count < 1)
9
+ throw new RangeError("failure thresholds must be positive safe integers");
10
+ }
11
+ }
1
12
  /**
2
13
  * Create an independent retry policy; a caller-owned clock is mandatory.
3
14
  * @param required Clock port, read once for each recorded failure.
@@ -11,15 +22,7 @@ export function createRespawnPolicy({ now }, options = {}) {
11
22
  const crashLoopWindowMs = options.crashLoopWindowMs ?? 60000;
12
23
  const crashLoopMaxFailures = options.crashLoopMaxFailures ?? 5;
13
24
  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
- }
25
+ validateRespawnOptions({ backoffScheduleMs, crashLoopWindowMs, crashLoopMaxFailures, portConflictMaxAttempts });
23
26
  let timestamps = [];
24
27
  let consecutivePortConflicts = 0;
25
28
  let tripped = false;
@@ -16,6 +16,34 @@ export function createSupervisorRegistry({ registryPath }) {
16
16
  removeIfCurrent: ({ pid }) => removeDaemonRegistryRecordIfCurrent({ registryPath, pid }),
17
17
  };
18
18
  }
19
+ function relayProcessOutput({ stream, sink }, _options = {}) {
20
+ if (sink !== undefined)
21
+ stream?.pipe(sink);
22
+ else
23
+ stream?.resume();
24
+ }
25
+ async function stopWindowsProcess({ child, pid }, options = {}) {
26
+ // Windows has no group signal, so taskkill supplies the tree-stop escalation.
27
+ // Windows has no POSIX group signal. Killing only the immediate launcher would
28
+ // orphan its daemon; taskkill /T walks the entire descendant tree instead.
29
+ let exited = false;
30
+ if (child.closeStdin !== undefined) {
31
+ try {
32
+ child.closeStdin({});
33
+ // Reuse platform's existing 5s grace before any forced Windows termination.
34
+ exited = await (options.waitForProcessExit ?? waitForProcessExit)(pid);
35
+ }
36
+ catch { /* A broken pipe cannot request shutdown; escalate to the whole tree. */ }
37
+ }
38
+ if (!exited) {
39
+ try {
40
+ (options.execFileSync ?? execFileSync)("taskkill", ["/pid", String(pid), "/T", "/F"], { stdio: "ignore" });
41
+ }
42
+ catch {
43
+ child.kill({}, { signal: "SIGTERM" });
44
+ }
45
+ }
46
+ }
19
47
  /**
20
48
  * Node launch/tree-stop adapter using platform command quoting, snapshots and signal escalation.
21
49
  * @param required Complete host launch settings and the shared sidecar registry port.
@@ -40,14 +68,8 @@ export function createNodeDaemonProcessAdapter(required, options = {}) {
40
68
  const child = options.spawn
41
69
  ? options.spawn({ command: invocation.command, args: invocation.args, options: spawnOptions }, {})
42
70
  : spawn(invocation.command, invocation.args, spawnOptions);
43
- if (options.stdout !== undefined)
44
- child.stdout?.pipe(options.stdout);
45
- else
46
- child.stdout?.resume();
47
- if (options.stderr !== undefined)
48
- child.stderr?.pipe(options.stderr);
49
- else
50
- child.stderr?.resume();
71
+ relayProcessOutput({ stream: child.stdout, sink: options.stdout });
72
+ relayProcessOutput({ stream: child.stderr, sink: options.stderr });
51
73
  return {
52
74
  get pid() { return child.pid; },
53
75
  on(input) {
@@ -69,27 +91,8 @@ export function createNodeDaemonProcessAdapter(required, options = {}) {
69
91
  const pid = child.pid;
70
92
  const snapshotRequest = (options.listProcessSnapshots ?? listProcessSnapshots)();
71
93
  // Request stop before the first await: even a parent exiting immediately starts tree teardown.
72
- // Windows has no group signal, so taskkill supplies the tree-stop escalation.
73
- // Windows has no POSIX group signal. Killing only the immediate launcher would
74
- // orphan its daemon; taskkill /T walks the entire descendant tree instead.
75
94
  if ((options.platform ?? process.platform) === "win32") {
76
- let exited = false;
77
- if (child.closeStdin !== undefined) {
78
- try {
79
- child.closeStdin({});
80
- // Reuse platform's existing 5s grace before any forced Windows termination.
81
- exited = await (options.waitForProcessExit ?? waitForProcessExit)(pid);
82
- }
83
- catch { /* A broken pipe cannot request shutdown; escalate to the whole tree. */ }
84
- }
85
- if (!exited) {
86
- try {
87
- (options.execFileSync ?? execFileSync)("taskkill", ["/pid", String(pid), "/T", "/F"], { stdio: "ignore" });
88
- }
89
- catch {
90
- child.kill({}, { signal: "SIGTERM" });
91
- }
92
- }
95
+ await stopWindowsProcess({ child, pid }, options);
93
96
  }
94
97
  else {
95
98
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/sidecar",
3
- "version": "0.4.3",
3
+ "version": "0.4.4",
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,11 +63,11 @@
63
63
  },
64
64
  "devDependencies": {
65
65
  "@vitest/coverage-v8": "^2.1.9",
66
- "@jini-ai/platform": "0.5.5",
67
- "@jini-ai/core": "0.4.4"
66
+ "@jini-ai/core": "0.4.9",
67
+ "@jini-ai/platform": "0.5.10"
68
68
  },
69
69
  "dependencies": {
70
- "@jini-ai/core": "^0.4.4"
70
+ "@jini-ai/core": "^0.4.9"
71
71
  },
72
72
  "peerDependencies": {
73
73
  "@jini-ai/platform": "^0.5.5"