@jini-ai/sidecar 0.1.2 → 0.4.0

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 +87 -0
  2. package/README.md +132 -0
  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 +55 -0
  22. package/dist/supervisor-node.js +95 -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 +32 -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/CHANGELOG.md ADDED
@@ -0,0 +1,87 @@
1
+ # @jini-ai/sidecar
2
+
3
+ ## 0.4.0 — 2026-10-02
4
+
5
+ ### BREAKING
6
+
7
+ - Atomic filesystem handling is canonical in platform and Node supervisor defaults are isolated in ./supervisor/node.
8
+ - 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.
9
+
10
+ ## Unreleased
11
+
12
+ - Fix supervisor test compilation by checking event-array emptiness without narrowing later lifecycle events to `never`.
13
+
14
+ - BREAKING: Node supervisor defaults and their types are available only from `./supervisor/node`, no longer the root or generic supervisor. The generic supervisor keeps its injected process ports and universal runtime entry.
15
+
16
+ - Adopt shared kernel contracts and preserve the module rationale in neutral documentation.
17
+ - Runtime JSON writes now preserve destination modes and fsync file plus parent directory, reject unserializable JSON, and clean failed owned temp writes.
18
+
19
+
20
+ - **BREAKING:** Existing public helpers and data-bearing ports now take required and optional argument objects. Registry adapters and supervisor event/kill ports follow the same convention; migrate callers using `API.md` and the archived migration inventory.
21
+ - Expose the respawn policy and supervisor from the library barrel; declare runtimes for all subpaths.
22
+
23
+ - Add respawn-policy and supervisor subpaths with injected lifecycle ports, platform process/tree adapters and shared daemon registry support.
24
+
25
+ ## 0.1.2
26
+
27
+ ### Patch Changes
28
+
29
+ - Add top-level `main`/`types` fields alongside the existing `exports` map. A consumer on
30
+ TypeScript's classic `moduleResolution: "node"` (node10) — which ignores `package.json#exports`
31
+ entirely — could not resolve this package's types at all (`TS2307: Cannot find module`) even
32
+ after the previous exports-map fix restored `require()` at runtime; type resolution and runtime
33
+ resolution are separate algorithms. Verified against a real external consumer (whose
34
+ tsconfig uses this legacy resolution mode): adding these two fields, with its tsconfig completely
35
+ unchanged, made the error disappear. Also fixes absolute-path `require()` (distinct from a bare
36
+ specifier, which already worked) for the same reason — `main` was previously absent.
37
+
38
+ Purely additive: every modern resolver (Node's own runtime `exports` resolution, TypeScript's
39
+ `bundler`/`node16`/`nodenext`) prefers `exports` over `main`/`types` when both are present, so
40
+ this changes nothing for a consumer already on a modern resolver.
41
+
42
+ - Updated dependencies
43
+ - @jini-ai/core@0.1.2
44
+
45
+ ## 0.1.1
46
+
47
+ ### Patch Changes
48
+
49
+ - Add a `"default"` export condition to every published package's `exports` map — every one of
50
+ them lacked it, which meant `require()` failed with `ERR_PACKAGE_PATH_NOT_EXPORTED` for any
51
+ CommonJS consumer (found via a real external integration attempt; Node needs `require(esm)`
52
+ support, i.e. Node >=22.12, for this to resolve).
53
+
54
+ `@jini-ai/agent-runtime`:
55
+
56
+ - **New**: `RuntimeBuildOptions.permissionMode` (`'bypass' | 'restricted'`) lets a caller opt a
57
+ run OUT of the auto-approve-every-permission-prompt flag every def with one
58
+ (`bypassPermissions` / `--yolo` / `--dangerously-skip-permissions`) previously pushed
59
+ unconditionally, with no way to turn it off. Omitting it keeps today's default (bypass)
60
+ behavior unchanged.
61
+ - **New**: `ClaudeStreamEvent`, `CopilotStreamEvent`, and `QoderEvent` are now real exported
62
+ discriminated unions instead of `Record<string, unknown>` — a real external consumer guessed a
63
+ nonexistent field name (`event.text` instead of the actual `event.delta`) against the old
64
+ untyped sink and silently lost every streamed token with no compile or runtime error.
65
+ - Fixed a doc/implementation mismatch in `claude-stream.ts`: the module doc claimed `tool_result`
66
+ events carry `{ tool_use_id, content, is_error }`; the actual emitted shape is
67
+ `{ toolUseId, content, isError }`.
68
+
69
+ `@jini-ai/daemon`: `AgentExecutorRunInput.permissionMode` forwards the new
70
+ `RuntimeBuildOptions.permissionMode` through to `buildArgs`, so a host can actually reach the new
71
+ opt-out from the daemon's real run-input surface, not just from `@jini-ai/agent-runtime` in
72
+ isolation.
73
+
74
+ `@jini-ai/agentic`: `setAtPointer` no longer throws on a malformed (e.g. missing leading `/`)
75
+ `updateDataModel` path — degrades to a no-op like its sibling `getAtPointer`, matching this
76
+ package's own "a bad binding must not crash the renderer" contract. That path is agent-authored
77
+ wire data with no error boundary above it in any host, so the uncaught throw could unmount an
78
+ entire chat UI from ~40 bytes of malformed input.
79
+
80
+ `@jini-ai/chat-react`: a local (client-resolved) A2UI button action is no longer a silent no-op —
81
+ `A2uiSurfaceCard` now surfaces the resolved value. New `ExtEventErrorBoundary` confines a
82
+ `kind: 'ext'` event group's renderer to its own card instead of letting a render/effect-phase
83
+ throw from agent-controlled content unmount the whole chat root (there was no error boundary
84
+ anywhere in this package or its hosts before this).
85
+
86
+ - Updated dependencies
87
+ - @jini-ai/core@0.1.1
package/README.md ADDED
@@ -0,0 +1,132 @@
1
+ # `@jini-ai/sidecar`
2
+
3
+ Process-runtime plumbing for an application that runs a long-lived helper process ("sidecar") next
4
+ to a shell or CLI. It answers the boring-but-load-bearing questions such a setup keeps asking: where
5
+ does this app's runtime directory live, what IPC socket path is safe on this platform, which TCP
6
+ port can I bind, how does the child validate the stamp its parent launched it with, and how does an
7
+ unrelated process later find the daemon that is already running. Nothing here starts an HTTP server
8
+ or knows what your sidecar actually does — it is the filesystem/IPC/port layer underneath that.
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ npm install @jini-ai/sidecar
14
+ ```
15
+
16
+ No peer dependencies. Its dependencies are `@jini-ai/core` and `@jini-ai/platform` (installed automatically); everything
17
+ else it uses is a Node built-in.
18
+
19
+ ## What you get
20
+
21
+ **Path resolution** — a namespace/project-scoped layout resolved from a caller-supplied
22
+ `SidecarContractDescriptor` (its env-var names, defaults, and normalizers) rather than from
23
+ hardcoded product constants: `resolveNamespace`, `resolveNamespaceRoot`, `resolveRuntimeRoot`,
24
+ `resolveRuntimeNamespaceRoot`, `resolveSourceRuntimeRoot`, `resolveProjectRoot`,
25
+ `resolveProjectTmpRoot`, `resolveSidecarBase`, `resolveAppRuntimeDir`, `resolveAppRuntimePath`,
26
+ `resolveLogsDir`, `resolveLogFilePath`, `resolveManifestPath`, `resolvePointerPath`.
27
+
28
+ **IPC paths** — `normalizeIpcPath` and `isWindowsNamedPipePath` (Windows named pipes vs. Unix
29
+ domain sockets), plus `resolveAppIpcPath` for the app-scoped socket path.
30
+
31
+ **JSON IPC** — `createJsonIpcServer({ socketPath, handler }, { maxFrameBytes, idleTimeoutMs })` and
32
+ `requestJsonIpc({ socketPath, payload }, { timeoutMs })`: a newline-delimited JSON request/response
33
+ channel over a local socket, with a per-frame byte cap and an idle-connection timeout.
34
+
35
+ **Port allocation** — `allocatePort({}, { host, label, port, reserved })`, which either honors a forced
36
+ port or finds a free dynamic one, returning `{ port, source: 'dynamic' | 'forced' }`.
37
+
38
+ **Launch and bootstrap** — `createSidecarLaunchEnv` (parent side: build the child's environment) and
39
+ `bootstrapSidecarRuntime({ stampInput, env, app, contract }, options)` (child side: validate the stamp against the expected
40
+ app via the injected contract and return a `SidecarRuntimeContext`). A stamp mismatch throws rather
41
+ than starting a sidecar that belongs to a different app.
42
+
43
+ **Local daemon registry** — a `dataDir`-scoped pointer file recording a running daemon's
44
+ URL/host/port/pid/start time, plus liveness checking: `resolveDaemonRegistryPath({ dataDir })`,
45
+ `writeDaemonRegistryRecord`, `readLiveDaemonRegistryRecord` (returns `null` when the recorded pid is
46
+ gone), `removeDaemonRegistryRecordIfCurrent`, `isProcessAlive`.
47
+
48
+ **JSON file helpers** — `readJsonFile`, `writeJsonFile`, `removeFile`, `removePointerIfCurrent`.
49
+
50
+ ## Usage
51
+
52
+ ```ts
53
+ import {
54
+ allocatePort,
55
+ createJsonIpcServer,
56
+ requestJsonIpc,
57
+ resolveDaemonRegistryPath,
58
+ readLiveDaemonRegistryRecord,
59
+ writeDaemonRegistryRecord,
60
+ type LocalDaemonRegistryRecord,
61
+ } from '@jini-ai/sidecar';
62
+
63
+ const { port } = await allocatePort({}, { host: '127.0.0.1', label: 'daemon' });
64
+
65
+ const registryPath = resolveDaemonRegistryPath({ dataDir: '/var/lib/example' });
66
+ const record: LocalDaemonRegistryRecord = {
67
+ url: `http://127.0.0.1:${port}`,
68
+ host: '127.0.0.1',
69
+ port,
70
+ pid: process.pid,
71
+ startedAt: new Date().toISOString(),
72
+ };
73
+ await writeDaemonRegistryRecord({ registryPath, record });
74
+
75
+ // Any other process, later — `null` when nothing is actually running.
76
+ const live = await readLiveDaemonRegistryRecord({ registryPath });
77
+
78
+ const ipc = await createJsonIpcServer({
79
+ socketPath: '/tmp/example/daemon.sock',
80
+ handler: async ({ message }) => ({ echo: message }),
81
+ });
82
+ const reply = await requestJsonIpc<{ echo: unknown }>({ socketPath: '/tmp/example/daemon.sock', payload: { ping: true } });
83
+ await ipc.close();
84
+ ```
85
+
86
+ The path resolvers each additionally take a `contract: SidecarContractDescriptor` describing your
87
+ app's env-var names and defaults — see `src/types.ts` for its shape before wiring those up.
88
+
89
+ ## What's swappable
90
+
91
+ `SidecarContractDescriptor` is the seam, and it is why this package carries no product strings: your
92
+ app supplies its own env-var names, path defaults, and `normalizeStamp`/`normalizeApp`/
93
+ `normalizeNamespace` functions, and every path resolver plus `bootstrapSidecarRuntime` reads them
94
+ from there. `createJsonIpcServer` takes the message handler and its two safety bounds. Everything
95
+ else (socket framing, port probing, the registry record's field set and its pid-guarded removal) is
96
+ fixed concrete behavior with no injection point.
97
+
98
+ ## Runtime
99
+
100
+ `jini.runtime: "node"` — uses `node:net`, `node:fs`, `node:os`, and `process`.
101
+ ESM only — ships `"type": "module"` with no CommonJS `require` build.
102
+
103
+ ## Provenance
104
+
105
+ See the archived provenance ledger for per-file provenance and scope decisions. Apache-2.0,
106
+ inherited from Open Design — see the repo `NOTICE`.
107
+
108
+ ## Argument convention and runtime subpaths
109
+
110
+ See [API.md](https://github.com/AINSEP/Jini/blob/main/packages/sidecar/API.md) for supervisor ports and the required/optional object convention. `./respawn-policy` and `./supervisor` are universal; `./supervisor/node` and the root entry use Node.
111
+
112
+ ## Kernel contracts
113
+
114
+ Runtime JSON state writes delegate to `@jini-ai/platform/fs`'s async atomic writer.
115
+ `writeJsonFile({ filePath, payload })` keeps pretty JSON and its trailing newline. Existing
116
+ permissions survive replacement; new files keep the usual umask-filtered create mode.
117
+ The writer exclusively creates its sibling temp, syncs file bytes before rename, syncs the
118
+ parent directory afterward, and propagates failures (including a sync failure after replacement).
119
+
120
+ ## Isolated supervisor Node defaults
121
+
122
+ `@jini-ai/sidecar/supervisor` exports only the generic process-port supervisor
123
+ and its types. `createNodeDaemonProcessAdapter`, `createSupervisorRegistry`,
124
+ `createNodeSupervisorScheduler` and the adapter types are exported exclusively
125
+ from `@jini-ai/sidecar/supervisor/node`. They are no longer re-exported from the
126
+ root or generic entry. Generic supervisor construction still requires the same
127
+ process, clock, scheduler and reporting ports and starts no work on import.
128
+
129
+ ## Development typechecking
130
+
131
+ The package TypeScript configuration includes production source and `src/**/__tests__`.
132
+ `npx tsc -p tsconfig.json --noEmit`, run from this package directory, checks both without running tests.
@@ -7,18 +7,21 @@
7
7
  * app/ipc/env, writes the canonical env back, and returns the live runtime
8
8
  * context. Depends on the path resolvers and the public types.
9
9
  */
10
- import type { BootstrapSidecarRuntimeOptions, SidecarLaunchEnvRequest, SidecarRuntimeContext, SidecarStampShape } from "./types.js";
10
+ import type { BootstrapSidecarRuntimeOptions, BootstrapSidecarRuntimeOptionsOptionalArgs, SidecarLaunchEnvRequestOptionalArgs, SidecarLaunchEnvRequest, SidecarRuntimeContext, SidecarStampShape } from "./types.js";
11
11
  /**
12
12
  * Compose the environment a child sidecar is launched with: the resolved base,
13
13
  * the stamp's ipc path, namespace, and source, layered over `extraEnv`.
14
14
  * @returns The launch environment.
15
15
  */
16
- export declare function createSidecarLaunchEnv<TStamp extends SidecarStampShape>({ base, contract, extraEnv, stamp, }: SidecarLaunchEnvRequest<TStamp>): NodeJS.ProcessEnv;
16
+ export declare function createSidecarLaunchEnv<TStamp extends SidecarStampShape>({ base, contract, stamp, }: SidecarLaunchEnvRequest<TStamp>, { extraEnv }?: SidecarLaunchEnvRequestOptionalArgs): NodeJS.ProcessEnv;
17
17
  /**
18
18
  * Bootstrap a sidecar runtime from an incoming stamp and env: validate app and
19
19
  * ipc path, confirm no conflicting env, write the canonical env back, and return
20
20
  * the resolved live runtime context.
21
21
  * @returns The resolved {@link SidecarRuntimeContext}.
22
22
  */
23
- export declare function bootstrapSidecarRuntime<TStamp extends SidecarStampShape>(stampInput: unknown, env: NodeJS.ProcessEnv, options: BootstrapSidecarRuntimeOptions<TStamp>): SidecarRuntimeContext<TStamp>;
23
+ export declare function bootstrapSidecarRuntime<TStamp extends SidecarStampShape>({ stampInput, env, app, contract }: BootstrapSidecarRuntimeOptions<TStamp> & {
24
+ stampInput: unknown;
25
+ env: NodeJS.ProcessEnv;
26
+ }, optionalArgs?: BootstrapSidecarRuntimeOptionsOptionalArgs): SidecarRuntimeContext<TStamp>;
24
27
  //# sourceMappingURL=bootstrap.d.ts.map
package/dist/bootstrap.js CHANGED
@@ -13,11 +13,11 @@ import { resolveAppIpcPath, resolveSidecarBase } from "./paths.js";
13
13
  * the stamp's ipc path, namespace, and source, layered over `extraEnv`.
14
14
  * @returns The launch environment.
15
15
  */
16
- export function createSidecarLaunchEnv({ base, contract, extraEnv = process.env, stamp, }) {
17
- const normalizedStamp = contract.normalizeStamp(stamp);
16
+ export function createSidecarLaunchEnv({ base, contract, stamp, }, { extraEnv = process.env } = {}) {
17
+ const normalizedStamp = contract.normalizeStamp({ input: stamp });
18
18
  return {
19
19
  ...extraEnv,
20
- [contract.env.base]: resolveSidecarBase({ base, contract, env: extraEnv, source: normalizedStamp.source }),
20
+ [contract.env.base]: resolveSidecarBase({ contract, source: normalizedStamp.source }, { base, env: extraEnv }),
21
21
  [contract.env.ipcPath]: normalizedStamp.ipc,
22
22
  [contract.env.namespace]: normalizedStamp.namespace,
23
23
  [contract.env.source]: normalizedStamp.source,
@@ -39,20 +39,15 @@ function assertMatchingEnv(env, key, expected) {
39
39
  * the resolved live runtime context.
40
40
  * @returns The resolved {@link SidecarRuntimeContext}.
41
41
  */
42
- export function bootstrapSidecarRuntime(stampInput, env, options) {
43
- const stamp = options.contract.normalizeStamp(stampInput);
44
- const expectedApp = options.contract.normalizeApp(options.app);
42
+ export function bootstrapSidecarRuntime({ stampInput, env, app, contract }, optionalArgs = {}) {
43
+ const options = { app, contract, ...optionalArgs };
44
+ const stamp = options.contract.normalizeStamp({ input: stampInput });
45
+ const expectedApp = options.contract.normalizeApp({ app: options.app });
45
46
  if (stamp.app !== expectedApp) {
46
47
  throw new Error(`sidecar stamp app mismatch: expected ${expectedApp}, received ${stamp.app}`);
47
48
  }
48
- const base = resolveSidecarBase({
49
- base: options.base ?? null,
50
- contract: options.contract,
51
- env,
52
- ...(options.projectRoot === undefined ? {} : { projectRoot: options.projectRoot }),
53
- source: stamp.source,
54
- });
55
- const ipc = resolveAppIpcPath({ app: stamp.app, contract: options.contract, env, namespace: stamp.namespace });
49
+ const base = resolveSidecarBase({ contract: options.contract, source: stamp.source }, { base: options.base ?? null, env, ...(options.projectRoot === undefined ? {} : { projectRoot: options.projectRoot }) });
50
+ const ipc = resolveAppIpcPath({ app: stamp.app, contract: options.contract, namespace: stamp.namespace }, { env });
56
51
  if (stamp.ipc !== ipc) {
57
52
  throw new Error(`sidecar ipc path mismatch: expected ${ipc}, received ${stamp.ipc}`);
58
53
  }
@@ -34,20 +34,30 @@ export interface LocalDaemonRegistryRecord {
34
34
  * @returns The resolved absolute registry file path.
35
35
  * @throws When `dataDir` is not a non-empty string.
36
36
  */
37
- export declare function resolveDaemonRegistryPath(dataDir: string, fileName?: string): string;
37
+ export declare function resolveDaemonRegistryPath({ dataDir }: {
38
+ dataDir: string;
39
+ }, { fileName }?: {
40
+ fileName?: string;
41
+ }): string;
38
42
  /**
39
43
  * Durably (atomically, via `json-file.ts`'s temp-file-rename writer) record a daemon's identity
40
44
  * at `registryPath`. Safe under concurrent writers — the last writer to complete its rename wins,
41
45
  * and every reader only ever observes a fully-written file, never a partial one.
42
46
  */
43
- export declare function writeDaemonRegistryRecord(registryPath: string, record: LocalDaemonRegistryRecord): Promise<void>;
47
+ export declare function writeDaemonRegistryRecord({ registryPath, record }: {
48
+ registryPath: string;
49
+ record: LocalDaemonRegistryRecord;
50
+ }): Promise<void>;
44
51
  /**
45
52
  * Remove a daemon's registry record at `registryPath`, but only if it still names `pid` as the
46
53
  * owning process — the same guarded-removal shape `json-file.ts`'s `removePointerIfCurrent` uses
47
54
  * for its own pointer file. Guards a fast crash-restart race on a reused `dataDir`: an old
48
55
  * daemon's delayed shutdown cleanup must never delete a newer daemon's already-written record.
49
56
  */
50
- export declare function removeDaemonRegistryRecordIfCurrent(registryPath: string, pid: number): Promise<void>;
57
+ export declare function removeDaemonRegistryRecordIfCurrent({ registryPath, pid }: {
58
+ registryPath: string;
59
+ pid: number;
60
+ }): Promise<void>;
51
61
  /**
52
62
  * Probe whether OS process `pid` is currently alive, via `process.kill(pid, 0)` (sends no
53
63
  * actual signal — `0` only tests deliverability). This is the liveness half of "verify, don't
@@ -59,15 +69,19 @@ export declare function removeDaemonRegistryRecordIfCurrent(registryPath: string
59
69
  * discovery purposes). `false` for a non-positive/non-integer `pid`, a `pid` that does not exist
60
70
  * (`ESRCH`), or any other unexpected failure (treated conservatively as not confirmed alive).
61
71
  */
62
- export declare function isProcessAlive(pid: number): boolean;
72
+ export declare function isProcessAlive({ pid }: {
73
+ pid: number;
74
+ }): boolean;
63
75
  /**
64
76
  * Read a daemon's registry record at `registryPath` and return it only if it is well-formed AND
65
77
  * its recorded `pid` is still alive — the combined "read, don't just trust" discovery primitive a
66
- * CLI-side `resolveDaemonUrl({ discover })` probe needs. A stale record from a daemon that crashed
78
+ * CLI-side `resolveDaemonUrl({}, { discover })` probe needs. A stale record from a daemon that crashed
67
79
  * (pid no longer alive), a missing file, or a malformed/foreign JSON file all resolve to `null`
68
80
  * rather than throwing — discovery failing is an expected, non-exceptional outcome (the caller
69
81
  * falls through to its own `defaultUrl`/error, per `resolveDaemonUrl`'s own contract).
70
82
  * @returns The live record, or `null` when nothing live was found.
71
83
  */
72
- export declare function readLiveDaemonRegistryRecord(registryPath: string): Promise<LocalDaemonRegistryRecord | null>;
84
+ export declare function readLiveDaemonRegistryRecord({ registryPath }: {
85
+ registryPath: string;
86
+ }): Promise<LocalDaemonRegistryRecord | null>;
73
87
  //# sourceMappingURL=daemon-registry.d.ts.map
@@ -11,6 +11,8 @@
11
11
  * existing module in this package needed before. Depends on `node:path` and this package's
12
12
  * own `json-file.ts`.
13
13
  */
14
+ import { randomUUID } from "node:crypto";
15
+ import { link, rename } from "node:fs/promises";
14
16
  import { join, resolve } from "node:path";
15
17
  import { readJsonFile, removeFile, writeJsonFile } from "./json-file.js";
16
18
  /** Default file name for a daemon's registry record, resolved relative to its `dataDir`. */
@@ -25,7 +27,7 @@ const DEFAULT_DAEMON_REGISTRY_FILE_NAME = "daemon.json";
25
27
  * @returns The resolved absolute registry file path.
26
28
  * @throws When `dataDir` is not a non-empty string.
27
29
  */
28
- export function resolveDaemonRegistryPath(dataDir, fileName = DEFAULT_DAEMON_REGISTRY_FILE_NAME) {
30
+ export function resolveDaemonRegistryPath({ dataDir }, { fileName = DEFAULT_DAEMON_REGISTRY_FILE_NAME } = {}) {
29
31
  if (typeof dataDir !== "string" || dataDir.trim().length === 0) {
30
32
  throw new Error("dataDir must be a non-empty string");
31
33
  }
@@ -36,8 +38,8 @@ export function resolveDaemonRegistryPath(dataDir, fileName = DEFAULT_DAEMON_REG
36
38
  * at `registryPath`. Safe under concurrent writers — the last writer to complete its rename wins,
37
39
  * and every reader only ever observes a fully-written file, never a partial one.
38
40
  */
39
- export async function writeDaemonRegistryRecord(registryPath, record) {
40
- await writeJsonFile(registryPath, record);
41
+ export async function writeDaemonRegistryRecord({ registryPath, record }) {
42
+ await writeJsonFile({ filePath: registryPath, payload: record });
41
43
  }
42
44
  /**
43
45
  * Remove a daemon's registry record at `registryPath`, but only if it still names `pid` as the
@@ -45,10 +47,34 @@ export async function writeDaemonRegistryRecord(registryPath, record) {
45
47
  * for its own pointer file. Guards a fast crash-restart race on a reused `dataDir`: an old
46
48
  * daemon's delayed shutdown cleanup must never delete a newer daemon's already-written record.
47
49
  */
48
- export async function removeDaemonRegistryRecordIfCurrent(registryPath, pid) {
49
- const record = await readJsonFile(registryPath);
50
- if (record?.pid === pid)
51
- await removeFile(registryPath);
50
+ export async function removeDaemonRegistryRecordIfCurrent({ registryPath, pid }) {
51
+ const record = await readJsonFile({ filePath: registryPath });
52
+ if (record?.pid !== pid)
53
+ return;
54
+ // Detach first, then check the captured record: a writer may replace the public path
55
+ // between the initial read and this rename. Only the captured file is ever removed.
56
+ 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
+ }
65
+ 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
+ }
77
+ await removeFile({ filePath: tombstonePath });
52
78
  }
53
79
  /**
54
80
  * Probe whether OS process `pid` is currently alive, via `process.kill(pid, 0)` (sends no
@@ -61,7 +87,7 @@ export async function removeDaemonRegistryRecordIfCurrent(registryPath, pid) {
61
87
  * discovery purposes). `false` for a non-positive/non-integer `pid`, a `pid` that does not exist
62
88
  * (`ESRCH`), or any other unexpected failure (treated conservatively as not confirmed alive).
63
89
  */
64
- export function isProcessAlive(pid) {
90
+ export function isProcessAlive({ pid }) {
65
91
  if (!Number.isInteger(pid) || pid <= 0)
66
92
  return false;
67
93
  try {
@@ -98,17 +124,17 @@ function isValidRegistryRecord(value) {
98
124
  /**
99
125
  * Read a daemon's registry record at `registryPath` and return it only if it is well-formed AND
100
126
  * its recorded `pid` is still alive — the combined "read, don't just trust" discovery primitive a
101
- * CLI-side `resolveDaemonUrl({ discover })` probe needs. A stale record from a daemon that crashed
127
+ * CLI-side `resolveDaemonUrl({}, { discover })` probe needs. A stale record from a daemon that crashed
102
128
  * (pid no longer alive), a missing file, or a malformed/foreign JSON file all resolve to `null`
103
129
  * rather than throwing — discovery failing is an expected, non-exceptional outcome (the caller
104
130
  * falls through to its own `defaultUrl`/error, per `resolveDaemonUrl`'s own contract).
105
131
  * @returns The live record, or `null` when nothing live was found.
106
132
  */
107
- export async function readLiveDaemonRegistryRecord(registryPath) {
108
- const record = await readJsonFile(registryPath);
133
+ export async function readLiveDaemonRegistryRecord({ registryPath }) {
134
+ const record = await readJsonFile({ filePath: registryPath });
109
135
  if (!isValidRegistryRecord(record))
110
136
  return null;
111
- if (!isProcessAlive(record.pid))
137
+ if (!isProcessAlive({ pid: record.pid }))
112
138
  return null;
113
139
  return record;
114
140
  }
package/dist/index.d.ts CHANGED
@@ -9,7 +9,7 @@
9
9
  * running daemon's URL/host/port/pid, and a liveness-checked reader. This file
10
10
  * contains no logic; every implementation lives in a concern module beside it.
11
11
  */
12
- export type { AppIpcPathRequest, AppRuntimePathRequest, BaseResolutionOptions, BootstrapSidecarRuntimeOptions, JsonIpcHandler, JsonIpcServerHandle, NamespaceResolutionOptions, PortAllocation, PortRequest, ProjectRuntimePathRequest, RuntimePathRequest, RuntimeRootRequest, SidecarContractDescriptor, SidecarLaunchEnvRequest, SidecarRuntimeContext, SidecarStampShape, } from "./types.js";
12
+ export type { AppIpcPathRequest, AppRuntimePathRequest, BaseResolutionOptions, BootstrapSidecarRuntimeOptions, JsonIpcHandler, JsonIpcServerHandle, NamespaceResolutionOptions, NamespaceOptionalArgs, BaseResolutionOptionsOptionalArgs, AppIpcPathRequestOptionalArgs, SidecarLaunchEnvRequestOptionalArgs, BootstrapSidecarRuntimeOptionsOptionalArgs, PortAllocation, PortRequest, ProjectRuntimePathRequest, RuntimePathRequest, RuntimeRootRequest, SidecarContractDescriptor, SidecarLaunchEnvRequest, SidecarRuntimeContext, SidecarStampShape, } from "./types.js";
13
13
  export { isWindowsNamedPipePath, normalizeIpcPath } from "./ipc-path.js";
14
14
  export { resolveAppIpcPath, resolveAppRuntimeDir, resolveAppRuntimePath, resolveLogFilePath, resolveLogsDir, resolveManifestPath, resolveNamespace, resolveNamespaceRoot, resolvePointerPath, resolveProjectRoot, resolveProjectTmpRoot, resolveRuntimeNamespaceRoot, resolveRuntimeRoot, resolveSidecarBase, resolveSourceRuntimeRoot, } from "./paths.js";
15
15
  export { bootstrapSidecarRuntime, createSidecarLaunchEnv } from "./bootstrap.js";
@@ -18,4 +18,6 @@ export { readJsonFile, removeFile, removePointerIfCurrent, writeJsonFile } from
18
18
  export { createJsonIpcServer, requestJsonIpc } from "./json-ipc.js";
19
19
  export type { LocalDaemonRegistryRecord } from "./daemon-registry.js";
20
20
  export { isProcessAlive, readLiveDaemonRegistryRecord, removeDaemonRegistryRecordIfCurrent, resolveDaemonRegistryPath, writeDaemonRegistryRecord, } from "./daemon-registry.js";
21
+ export * from "./respawn-policy.js";
22
+ export * from "./supervisor.js";
21
23
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -16,4 +16,6 @@ export { allocatePort } from "./port.js";
16
16
  export { readJsonFile, removeFile, removePointerIfCurrent, writeJsonFile } from "./json-file.js";
17
17
  export { createJsonIpcServer, requestJsonIpc } from "./json-ipc.js";
18
18
  export { isProcessAlive, readLiveDaemonRegistryRecord, removeDaemonRegistryRecordIfCurrent, resolveDaemonRegistryPath, writeDaemonRegistryRecord, } from "./daemon-registry.js";
19
+ export * from "./respawn-policy.js";
20
+ export * from "./supervisor.js";
19
21
  //# sourceMappingURL=index.js.map
@@ -9,11 +9,15 @@
9
9
  * Detect whether a value is a Windows named-pipe path (`\\.\pipe\...`).
10
10
  * @returns `true` when `value` is such a pipe path.
11
11
  */
12
- export declare function isWindowsNamedPipePath(value: unknown): boolean;
12
+ export declare function isWindowsNamedPipePath({ value }: {
13
+ value: unknown;
14
+ }): boolean;
13
15
  /**
14
16
  * Validate and return an IPC path: a Windows named pipe is accepted as-is, and
15
17
  * any other value must be a non-empty, un-padded, null-byte-free absolute path.
16
18
  * @returns The validated IPC path.
17
19
  */
18
- export declare function normalizeIpcPath(ipc: unknown): string;
20
+ export declare function normalizeIpcPath({ ipc }: {
21
+ ipc: unknown;
22
+ }): string;
19
23
  //# sourceMappingURL=ipc-path.d.ts.map
package/dist/ipc-path.js CHANGED
@@ -10,7 +10,7 @@ import { isAbsolute } from "node:path";
10
10
  * Detect whether a value is a Windows named-pipe path (`\\.\pipe\...`).
11
11
  * @returns `true` when `value` is such a pipe path.
12
12
  */
13
- export function isWindowsNamedPipePath(value) {
13
+ export function isWindowsNamedPipePath({ value }) {
14
14
  return typeof value === "string" && value.startsWith("\\\\.\\pipe\\");
15
15
  }
16
16
  /**
@@ -18,7 +18,7 @@ export function isWindowsNamedPipePath(value) {
18
18
  * any other value must be a non-empty, un-padded, null-byte-free absolute path.
19
19
  * @returns The validated IPC path.
20
20
  */
21
- export function normalizeIpcPath(ipc) {
21
+ export function normalizeIpcPath({ ipc }) {
22
22
  if (typeof ipc !== "string")
23
23
  throw new Error("sidecar ipc path must be a string");
24
24
  if (ipc.length === 0)
@@ -27,7 +27,7 @@ export function normalizeIpcPath(ipc) {
27
27
  throw new Error("sidecar ipc path must not contain leading or trailing whitespace");
28
28
  if (ipc.includes("\0"))
29
29
  throw new Error("sidecar ipc path must not contain null bytes");
30
- if (isWindowsNamedPipePath(ipc))
30
+ if (isWindowsNamedPipePath({ value: ipc }))
31
31
  return ipc;
32
32
  if (!isAbsolute(ipc))
33
33
  throw new Error(`sidecar ipc path must be absolute: ${ipc}`);
@@ -5,24 +5,35 @@
5
5
  * any failure), an atomic pretty-printed writer via temp-file rename, a
6
6
  * best-effort remove, and a guarded pointer removal that only deletes when the
7
7
  * pointer still names the given run. Depends on `node:fs/promises` and
8
- * `node:path`.
8
+ * the platform filesystem writer for shared atomic replacement and durability.
9
9
  */
10
10
  /**
11
11
  * Read and parse a JSON file, swallowing any read/parse error.
12
12
  * @returns The parsed value, or `null` if missing or unreadable.
13
13
  */
14
- export declare function readJsonFile<T = any>(filePath: string): Promise<T | null>;
14
+ export declare function readJsonFile<T = any>({ filePath }: {
15
+ filePath: string;
16
+ }): Promise<T | null>;
15
17
  /**
16
18
  * Atomically write `payload` as pretty-printed JSON via a temp-file rename,
17
- * creating the parent directory if needed.
19
+ * creating the parent directory if needed. Existing modes are preserved; file bytes
20
+ * are synced before rename and the parent directory afterward. Sync failures propagate.
18
21
  */
19
- export declare function writeJsonFile(filePath: string, payload: unknown): Promise<void>;
22
+ export declare function writeJsonFile({ filePath, payload }: {
23
+ filePath: string;
24
+ payload: unknown;
25
+ }): Promise<void>;
20
26
  /**
21
27
  * Remove a file, forcing (no error if absent).
22
28
  */
23
- export declare function removeFile(filePath: string): Promise<void>;
29
+ export declare function removeFile({ filePath }: {
30
+ filePath: string;
31
+ }): Promise<void>;
24
32
  /**
25
33
  * Remove a pointer file only if it still points at `runId`.
26
34
  */
27
- export declare function removePointerIfCurrent(pointerPath: string, runId: string): Promise<void>;
35
+ export declare function removePointerIfCurrent({ pointerPath, runId }: {
36
+ pointerPath: string;
37
+ runId: string;
38
+ }): Promise<void>;
28
39
  //# sourceMappingURL=json-file.d.ts.map
package/dist/json-file.js CHANGED
@@ -5,15 +5,16 @@
5
5
  * any failure), an atomic pretty-printed writer via temp-file rename, a
6
6
  * best-effort remove, and a guarded pointer removal that only deletes when the
7
7
  * pointer still names the given run. Depends on `node:fs/promises` and
8
- * `node:path`.
8
+ * the platform filesystem writer for shared atomic replacement and durability.
9
9
  */
10
- import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
11
- import { dirname } from "node:path";
10
+ import { randomUUID } from "node:crypto";
11
+ import { readFile, rm } from "node:fs/promises";
12
+ import { writeJsonFileAtomicAsync } from "@jini-ai/platform/fs";
12
13
  /**
13
14
  * Read and parse a JSON file, swallowing any read/parse error.
14
15
  * @returns The parsed value, or `null` if missing or unreadable.
15
16
  */
16
- export async function readJsonFile(filePath) {
17
+ export async function readJsonFile({ filePath }) {
17
18
  try {
18
19
  return JSON.parse(await readFile(filePath, "utf8"));
19
20
  }
@@ -23,26 +24,27 @@ export async function readJsonFile(filePath) {
23
24
  }
24
25
  /**
25
26
  * Atomically write `payload` as pretty-printed JSON via a temp-file rename,
26
- * creating the parent directory if needed.
27
+ * creating the parent directory if needed. Existing modes are preserved; file bytes
28
+ * are synced before rename and the parent directory afterward. Sync failures propagate.
27
29
  */
28
- export async function writeJsonFile(filePath, payload) {
29
- await mkdir(dirname(filePath), { recursive: true });
30
- const tmpPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
31
- await writeFile(tmpPath, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
32
- await rename(tmpPath, filePath);
30
+ export async function writeJsonFile({ filePath, payload }) {
31
+ await writeJsonFileAtomicAsync({ filePath, data: payload }, {
32
+ createParent: true, trailingNewline: true, defaultMode: 0o666 & ~process.umask(),
33
+ tempPath: () => `${filePath}.${process.pid}.${randomUUID()}.tmp`,
34
+ });
33
35
  }
34
36
  /**
35
37
  * Remove a file, forcing (no error if absent).
36
38
  */
37
- export async function removeFile(filePath) {
39
+ export async function removeFile({ filePath }) {
38
40
  await rm(filePath, { force: true });
39
41
  }
40
42
  /**
41
43
  * Remove a pointer file only if it still points at `runId`.
42
44
  */
43
- export async function removePointerIfCurrent(pointerPath, runId) {
44
- const pointer = await readJsonFile(pointerPath);
45
+ export async function removePointerIfCurrent({ pointerPath, runId }) {
46
+ const pointer = await readJsonFile({ filePath: pointerPath });
45
47
  if (pointer?.runId === runId)
46
- await removeFile(pointerPath);
48
+ await removeFile({ filePath: pointerPath });
47
49
  }
48
50
  //# sourceMappingURL=json-file.js.map