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

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.
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Self-termination watchdog, symmetric to `agent-daemon-server.ts`'s own `startParentWatchdog()`
3
+ * one level up (`ADS-memory/reports/analysis/2026-08-05-symmetric-watchdog.md` has the full
4
+ * measurement trail this comment summarizes).
5
+ *
6
+ * That daemon watchdog closes "the daemon becomes an orphan when THIS process dies without
7
+ * running `reap()`". This is the other half: THIS process becomes the orphan when whatever was
8
+ * supposed to be driving it dies without ever sending it a catchable signal — measured three times
9
+ * independently for one concrete trigger (an external kill of Playwright's own top-level CLI
10
+ * process bypasses its `teardown()`/`gracefulShutdown` entirely; see the root-cause doc's Round
11
+ * 2/4) and confirmed live for every agent that kills its own runs, which this repo's own traps say
12
+ * is routine, not a corner case.
13
+ *
14
+ * Two independent checks, because measurement showed one pid source does not cover every real
15
+ * launch context:
16
+ *
17
+ * 1. **`process.ppid` liveness (always on, no env var).** Node does not cache `process.ppid` at
18
+ * startup — it re-reads the OS's current parent pid on every access, and flips the moment this
19
+ * process is reparented (POSIX: to pid 1 on macOS/most Linux; to the nearest registered
20
+ * subreaper where one exists — comparing against the value recorded at boot, rather than
21
+ * testing `=== 1`, is what makes this correct in both cases without needing to know which one
22
+ * applies). Verified directly, twice: a child spawned the same way Playwright spawns its
23
+ * `webServer` (`shell: true`, per `playwright/lib/runner/index.js:841`) logged its own
24
+ * `process.ppid` flipping from the real parent's pid to the reparent target within ~300ms of
25
+ * the parent dying — once via a plain `process.exit()`, once via an actual external `kill -9`
26
+ * on the parent (the literal shape of the still-open gap). No ambiguous-error case exists here
27
+ * the way `EPERM` vs `ESRCH` is ambiguous for `kill(pid, 0)` below: reading `process.ppid` never
28
+ * fails or needs a permission check, and reparenting is never transient (the original parent
29
+ * cannot come back to life under the same pid), so there is no false-positive path — every
30
+ * observed change is a real, permanent parent death. It also has no PID-reuse blind spot the
31
+ * way `kill(pid, 0)` does: this never probes an external pid's continued existence at all, it
32
+ * only compares the kernel's own live record of THIS process's parent against what was recorded
33
+ * at boot, so a coincidental pid reuse elsewhere cannot spoof it either direction.
34
+ *
35
+ * Measured, this check's DIRECT OS parent is the real driving process in three of the four
36
+ * launch contexts investigated: Playwright's `webServer` (confirmed via `ps` — `shell: true`
37
+ * plus a single trailing simple command makes the shell exec-replace itself into `node`, so
38
+ * this process's ppid IS Playwright's own top-level CLI process directly, no intermediate `sh`
39
+ * hop); a bare/manual `node --import tsx src/index.ts` from an interactive shell (same one-hop
40
+ * shape — the shell IS the parent); and CI, where this repository's own `.github/workflows/
41
+ * ci.yml` never boots this file at all today (`npm test` is the plain unit-test runner, no
42
+ * Playwright/e2e step exists in CI), so there is nothing to verify there yet, not merely
43
+ * something unverified.
44
+ *
45
+ * 2. **The host's dev-supervisor pid variable (`envNames.devSupervisorPid`; opt-in, mirrors the daemon's own parent-pid variable exactly).**
46
+ * The one launch context measured to need it: `npm run dev`'s `tsx watch`. Confirmed via `ps`
47
+ * that `npx`/`tsx watch` are themselves Node-based CLI wrappers that do NOT exec-replace, so
48
+ * this process's real OS ppid there is the `tsx watch` supervisor two hops below `dev.mjs`, not
49
+ * `dev.mjs` itself — and that supervisor does not die just because `dev.mjs` does. Reproduced
50
+ * the resulting gap directly, isolated: booted the real `dev.mjs` tree, `kill -9`'d only
51
+ * `dev.mjs`'s own pid, and the API and daemon were both still alive and bound, unchanged, 2s
52
+ * later — the exact same shape as the Playwright gap, one supervisor layer up. `dev.mjs` now
53
+ * sets this var to its own pid for exactly this check; same `ESRCH`-confirms-death,
54
+ * everything-else-is-inconclusive logic as the daemon's own watchdog, including its accepted
55
+ * PID-reuse limitation — not closed here for the same reason it was not closed there: no
56
+ * portable, cheap Node API exists to read an arbitrary pid's start time, for a benefit that is
57
+ * marginal given the short poll window and low pid churn on a single dev machine.
58
+ *
59
+ * `<envNames.disable>=1` is an escape hatch for a launch shape neither this file nor the
60
+ * analysis doc enumerated: intentional daemonization (e.g. `nohup ... &` followed by logout, or any
61
+ * double-fork pattern) deliberately arranges for this process to outlive the parent that started
62
+ * it — that is that operator's explicit intent, not an orphan to clean up, and check #1 above
63
+ * cannot tell the two apart on its own. Checked this repo for an existing such launch path before
64
+ * relying on that distinction mattering here: no Dockerfile, docker-compose, systemd `.service`,
65
+ * launchd `.plist`, Procfile, or deploy script exists in this repository, and nothing greps for
66
+ * `nohup`/`daemonize`/`setsid` applied TO this file (only this file and `dev.mjs` daemonizing their
67
+ * OWN children, which is a different relationship). Production boots via `npm start` -> bare `node
68
+ * dist/src/index.js`, no wrapper. That rules out what is committed here; it says nothing about how
69
+ * an operator might run this on a bare VM outside this repo, which is exactly why the escape hatch
70
+ * exists unconditionally rather than being gated on what this search did or didn't find.
71
+ *
72
+ * Does not fight `tsx watch`'s own restart-on-save cycle: that delivers a real, catchable signal to
73
+ * the OLD process first (already handled by the `SIGINT`/`SIGTERM`/`SIGHUP` handlers
74
+ * `startAssistantDaemon` registers — see `daemon-supervisor.ts`), and each fresh incarnation of
75
+ * this file gets its own fresh `bootPpid`/interval at module load — no state carries over from the
76
+ * process being replaced.
77
+ *
78
+ * Windows: not verified. Playwright's own `attemptToGracefullyClose()` throws unconditionally on
79
+ * `win32` for this exact family of behavior (root-cause doc, quoting `playwright/lib/runner/
80
+ * index.js`) — this inherits that same "not supported" posture rather than assuming parity.
81
+ *
82
+ * `process.exit()` from inside this function's interval callback fires the existing
83
+ * `process.on("exit", ...)` listener `startAssistantDaemon` registers (a standard Node guarantee
84
+ * already relied on by this file's own SIGINT/SIGTERM/SIGHUP handlers), so a self-exit here cleans
85
+ * up the agent daemon exactly like every other termination path already does — no separate call
86
+ * needed here.
87
+ */
88
+ /**
89
+ * The process-level effects the watchdog needs, injected so every branch is testable with fakes;
90
+ * {@link startOwnParentWatchdog}'s callers wire the live `process`/`console`/`setInterval` at the
91
+ * composition edge (the host's entry module).
92
+ */
93
+ export type ParentWatchdogEvent =
94
+ /** The escape hatch is set; no probe or poll is armed. `disableEnvName` is the variable that was set. */
95
+ {
96
+ readonly kind: "disabled";
97
+ readonly disableEnvName: string;
98
+ }
99
+ /** The recorded parent was already gone when the boot probe ran; the process exits. */
100
+ | {
101
+ readonly kind: "parent-gone-at-boot";
102
+ readonly parentPid: number;
103
+ }
104
+ /** The supervisor-pid variable is not a positive integer; only that check is disabled. */
105
+ | {
106
+ readonly kind: "invalid-supervisor-pid";
107
+ readonly envName: string;
108
+ readonly raw: string;
109
+ }
110
+ /** The dev supervisor is confirmed gone (`ESRCH`); the process exits. */
111
+ | {
112
+ readonly kind: "supervisor-gone";
113
+ readonly supervisorPid: number;
114
+ }
115
+ /** The live parent pid differs from the one recorded at boot; the process exits. */
116
+ | {
117
+ readonly kind: "parent-reparented";
118
+ readonly parentPid: number;
119
+ readonly currentPid: number;
120
+ };
121
+ export interface ParentWatchdogPorts {
122
+ readonly env: Readonly<Record<string, string | undefined>>;
123
+ /** The host's env variable names: `disable` (set to `"1"` to opt out) and `devSupervisorPid`. */
124
+ readonly envNames: {
125
+ readonly disable: string;
126
+ readonly devSupervisorPid: string;
127
+ };
128
+ /** Read on every poll: the live parent pid (Node updates `process.ppid` after a reparent). */
129
+ readonly ppid: () => number;
130
+ /** `process.kill(pid, 0)` — throws an `ErrnoException` when the pid cannot be signalled. */
131
+ readonly signalZero: (pid: number) => void;
132
+ readonly exit: (code: number) => void;
133
+ /**
134
+ * Receives every watchdog event. The host owns the wording, the line prefix and whether an event
135
+ * goes to its info or error stream; events that end the process are reported before `exit` runs.
136
+ */
137
+ readonly report: (event: ParentWatchdogEvent) => void;
138
+ readonly setInterval: (callback: () => void, ms: number) => unknown;
139
+ }
140
+ /**
141
+ * Arms the parent watchdog described in this file's header.
142
+ * @complexity O(1) per poll.
143
+ */
144
+ export declare function startOwnParentWatchdog(ports: ParentWatchdogPorts, _options?: Record<string, never>): void;
145
+ //# sourceMappingURL=parent-watchdog.d.ts.map
@@ -0,0 +1,88 @@
1
+ const POLL_INTERVAL_MS = 3_000;
2
+ function errnoCode({ error }, _optional = {}) {
3
+ return error.code;
4
+ }
5
+ // Confirms the recorded parent was actually alive at the instant we captured it — closes a real
6
+ // race, found by probe rather than reasoned about: `node --import tsx` takes several real
7
+ // seconds to finish transforming/loading this module before ANY of this file's own code runs
8
+ // (measured live: ~4-8s), and no JS on earth can run earlier than that. If the real parent dies
9
+ // during that window, `process.ppid` already reads the reparent target by the time this line
10
+ // executes, and adopting THAT as the "normal" baseline would mean the comparison below can never
11
+ // fire again — silently defeating the whole watchdog for exactly the boot-time version of the
12
+ // failure it exists to catch. Same ESRCH-confirms-death, everything-else-is-inconclusive logic as
13
+ // every other check in this family: only a confirmed absence is treated as death.
14
+ function parentGoneAtBoot({ ports, bootPpid }) {
15
+ try {
16
+ ports.signalZero(bootPpid);
17
+ }
18
+ catch (error) {
19
+ if (errnoCode({ error }) === "ESRCH") {
20
+ ports.report({ kind: "parent-gone-at-boot", parentPid: bootPpid });
21
+ ports.exit(1);
22
+ return true;
23
+ }
24
+ }
25
+ return false;
26
+ }
27
+ /** The dev-supervisor pid variable as a positive integer pid, or `undefined` (reporting an invalid value). */
28
+ function resolveDevSupervisorPid(ports) {
29
+ const rawSupervisorPid = ports.env[ports.envNames.devSupervisorPid];
30
+ if (rawSupervisorPid === undefined)
31
+ return undefined;
32
+ const parsed = Number(rawSupervisorPid);
33
+ if (Number.isInteger(parsed) && parsed > 0)
34
+ return parsed;
35
+ ports.report({ kind: "invalid-supervisor-pid", envName: ports.envNames.devSupervisorPid, raw: rawSupervisorPid });
36
+ return undefined;
37
+ }
38
+ /** One supervisor liveness check: exits only on a confirmed (`ESRCH`) absence. */
39
+ function checkDevSupervisor({ ports, devSupervisorPid }) {
40
+ try {
41
+ // See this function's own doc: signal 0 has no side effect, it only answers "does this pid
42
+ // still exist".
43
+ ports.signalZero(devSupervisorPid);
44
+ }
45
+ catch (error) {
46
+ if (errnoCode({ error }) !== "ESRCH") {
47
+ // Anything other than "no such process" (e.g. a transient EPERM) is inconclusive, not a
48
+ // confirmed death — skip this poll rather than risk a false-positive self-kill on a
49
+ // supervisor that is actually still alive. Mirrors the daemon watchdog's own logic.
50
+ return;
51
+ }
52
+ ports.report({ kind: "supervisor-gone", supervisorPid: devSupervisorPid });
53
+ ports.exit(1);
54
+ }
55
+ }
56
+ /** One poll: a reparent or a confirmed-dead dev supervisor self-terminates this process. */
57
+ function pollParents({ ports, bootPpid, devSupervisorPid }) {
58
+ const currentPpid = ports.ppid();
59
+ if (currentPpid !== bootPpid) {
60
+ ports.report({ kind: "parent-reparented", parentPid: bootPpid, currentPid: currentPpid });
61
+ ports.exit(1);
62
+ return;
63
+ }
64
+ if (devSupervisorPid !== undefined)
65
+ checkDevSupervisor({ ports, devSupervisorPid });
66
+ }
67
+ /**
68
+ * Arms the parent watchdog described in this file's header.
69
+ * @complexity O(1) per poll.
70
+ */
71
+ export function startOwnParentWatchdog(ports, _options = {}) {
72
+ if (ports.env[ports.envNames.disable] === "1") {
73
+ ports.report({ kind: "disabled", disableEnvName: ports.envNames.disable });
74
+ return;
75
+ }
76
+ const bootPpid = ports.ppid();
77
+ if (parentGoneAtBoot({ ports, bootPpid }))
78
+ return;
79
+ const devSupervisorPid = resolveDevSupervisorPid(ports);
80
+ // Same 3s interval as the daemon's own watchdog, same rationale: fast enough that a leaked
81
+ // process closes long before it could collide with a later boot attempt, slow enough to cost
82
+ // nothing meaningful against a process spending most of its time idle between real requests.
83
+ // Not `.unref()`'d, for the same reason as the daemon's own timer: this interval's entire job is
84
+ // to keep watching for as long as its parent is, and letting it fall out of the event loop early
85
+ // would undermine that.
86
+ ports.setInterval(() => pollParents({ ports, bootPpid, devSupervisorPid }), POLL_INTERVAL_MS);
87
+ }
88
+ //# sourceMappingURL=parent-watchdog.js.map
@@ -31,7 +31,7 @@ export interface NodeDaemonProcessRequired {
31
31
  cwd: string;
32
32
  env: NodeJS.ProcessEnv;
33
33
  registry: SupervisorRegistry;
34
- /** The host's process control (snapshots, tree stop, exit wait); Node hosts pass `nodeProcessControl` of `@jini-ai/node-adapters/process`. */
34
+ /** The host's process control (snapshots, tree stop, exit wait); Node hosts pass `createProcessControlPort` of `@jini-ai/node-adapters/process` over `@jini-ai/platform/process`'s functions. */
35
35
  process: ProcessControlPort;
36
36
  /** The two host inputs of core's pure command planner: the platform and the `ComSpec` a Windows `.cmd` shim falls back to
37
37
  * when the launch env has none. Node hosts pass `nodeCommandShell({ env: process.env })` of `@jini-ai/node-adapters/process`,
@@ -1,9 +1,3 @@
1
- /**
2
- * Process signal handlers belong to the host boot wrapper, not the spawn loop: registering
3
- * them on each automatic respawn would leak another set of global listeners. Retry
4
- * decisions stay in the pure policy so backoff rules need neither real timers nor children.
5
- * Construction is safe to import in tests because it does not invoke the host bootstrap.
6
- */
7
1
  import type { RespawnDecision, RespawnPolicy } from "./respawn-policy.js";
8
2
  export type DaemonProcessSubscription = {
9
3
  event: "exit";
@@ -1,3 +1,10 @@
1
+ /**
2
+ * Process signal handlers belong to the host boot wrapper, not the spawn loop: registering
3
+ * them on each automatic respawn would leak another set of global listeners. Retry
4
+ * decisions stay in the pure policy so backoff rules need neither real timers nor children.
5
+ * Construction is safe to import in tests because it does not invoke the host bootstrap.
6
+ */
7
+ import { observed } from '@jini-ai/core/errors/idioms';
1
8
  function giveUpReason({ decision, lastReason }) {
2
9
  if (decision.kind === "port-conflict")
3
10
  return `gave up after ${decision.attempts} consecutive port conflicts: ${lastReason}`;
@@ -63,7 +70,8 @@ function discoverReadiness(context) {
63
70
  const discovery = waitForReady(context).finally(() => { if (context.discoveryWork === discovery)
64
71
  context.discoveryWork = undefined; });
65
72
  context.discoveryWork = discovery;
66
- void discovery.catch(() => { });
73
+ /* Parking or shutdown also ends caller-free discovery. */
74
+ observed({ promise: discovery });
67
75
  }
68
76
  return context.discoveryWork;
69
77
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/sidecar",
3
- "version": "0.7.3-next.1",
3
+ "version": "0.7.3-next.3",
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": {
@@ -15,7 +15,10 @@
15
15
  ".": "node",
16
16
  "./respawn-policy": "universal",
17
17
  "./supervisor": "universal",
18
- "./supervisor/node": "node"
18
+ "./supervisor/node": "node",
19
+ "./daemon-origin": "node",
20
+ "./daemon-park-recovery": "universal",
21
+ "./daemon-connection": "universal"
19
22
  },
20
23
  "runtime": "node"
21
24
  },
@@ -43,6 +46,21 @@
43
46
  "types": "./dist/supervision/supervisor-node.d.ts",
44
47
  "import": "./dist/supervision/supervisor-node.js",
45
48
  "default": "./dist/supervision/supervisor-node.js"
49
+ },
50
+ "./daemon-origin": {
51
+ "types": "./dist/daemon-origin.d.ts",
52
+ "import": "./dist/daemon-origin.js",
53
+ "default": "./dist/daemon-origin.js"
54
+ },
55
+ "./daemon-park-recovery": {
56
+ "types": "./dist/daemon-park-recovery.d.ts",
57
+ "import": "./dist/daemon-park-recovery.js",
58
+ "default": "./dist/daemon-park-recovery.js"
59
+ },
60
+ "./daemon-connection": {
61
+ "types": "./dist/daemon-connection.d.ts",
62
+ "import": "./dist/daemon-connection.js",
63
+ "default": "./dist/daemon-connection.js"
46
64
  }
47
65
  },
48
66
  "files": [
@@ -62,12 +80,12 @@
62
80
  "registry": "https://registry.npmjs.org"
63
81
  },
64
82
  "devDependencies": {
65
- "@vitest/coverage-v8": "^2.1.9",
66
- "@jini-ai/core": "0.7.3-next.1",
67
- "@jini-ai/platform": "0.7.3-next.1"
83
+ "@vitest/coverage-v8": "^3.2.6",
84
+ "@jini-ai/core": "0.7.3-next.3",
85
+ "@jini-ai/platform": "0.7.3-next.3"
68
86
  },
69
87
  "dependencies": {
70
- "@jini-ai/core": "^0.7.3-next.1"
88
+ "@jini-ai/core": "^0.7.3-next.3"
71
89
  },
72
90
  "scripts": {
73
91
  "build": "tsc -p tsconfig.json",