@jini-ai/sidecar 0.7.1 → 0.7.3-next.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 (38) hide show
  1. package/CHANGELOG.md +1 -1
  2. package/dist/daemon-registry.d.ts +7 -5
  3. package/dist/daemon-registry.js +5 -5
  4. package/dist/index.d.ts +1 -1
  5. package/dist/ipc-path.d.ts +2 -2
  6. package/dist/ipc-path.js +2 -2
  7. package/dist/json-file.d.ts +11 -7
  8. package/dist/json-file.js +7 -8
  9. package/dist/json-ipc.d.ts +1 -18
  10. package/dist/json-ipc.js +11 -35
  11. package/dist/net.d.ts +7 -2
  12. package/dist/net.js +2 -2
  13. package/dist/paths.d.ts +11 -11
  14. package/dist/paths.js +11 -11
  15. package/dist/port.js +4 -4
  16. package/dist/supervision/child-entries.d.ts +85 -0
  17. package/dist/supervision/child-entries.js +139 -0
  18. package/dist/supervision/child-exit-signal.d.ts +21 -0
  19. package/dist/supervision/child-exit-signal.js +24 -0
  20. package/dist/supervision/child-orphans.d.ts +37 -0
  21. package/dist/supervision/child-orphans.js +48 -0
  22. package/dist/supervision/child-process-inspection.d.ts +29 -0
  23. package/dist/supervision/child-process-inspection.js +32 -0
  24. package/dist/supervision/child-readiness.d.ts +57 -0
  25. package/dist/supervision/child-readiness.js +83 -0
  26. package/dist/supervision/child-registry.d.ts +98 -0
  27. package/dist/supervision/child-registry.js +118 -0
  28. package/dist/supervision/child-stop.d.ts +39 -0
  29. package/dist/supervision/child-stop.js +81 -0
  30. package/dist/supervision/child-transitions.d.ts +54 -0
  31. package/dist/supervision/child-transitions.js +62 -0
  32. package/dist/supervision/keyed-serializer.d.ts +29 -0
  33. package/dist/supervision/keyed-serializer.js +50 -0
  34. package/dist/supervision/supervisor-node.d.ts +29 -11
  35. package/dist/supervision/supervisor-node.js +40 -29
  36. package/dist/supervision/supervisor.d.ts +3 -0
  37. package/dist/supervision/supervisor.js +312 -276
  38. package/package.json +4 -5
@@ -1,20 +1,18 @@
1
1
  import { execFileSync, spawn } from "node:child_process";
2
2
  import { randomUUID } from "node:crypto";
3
- import { createCommandInvocation } from "@jini-ai/platform/command";
4
- import { omitEnvironmentKeys } from "@jini-ai/platform/child-environment";
5
- import { collectProcessTreePids, listProcessSnapshots, stopProcesses, waitForProcessExit } from "@jini-ai/platform/process";
3
+ import { omitEnvironmentKeys, collectProcessTreePids, planCommandInvocation } from "@jini-ai/core/contracts/runtime";
6
4
  import { readLiveDaemonRegistryRecord, removeDaemonRegistryRecordIfCurrent, writeDaemonRegistryRecord } from "../daemon-registry.js";
7
5
  /**
8
6
  * Reuse the sidecar registry's atomic records, liveness checks and ownership-guarded removal.
9
7
  * The child calls write only after it actually starts listening.
10
- * @param required Host-owned registry path.
8
+ * @param required Host-owned registry path and the host's atomic JSON writer.
11
9
  * @returns A registry port with object arguments at all data-bearing boundaries.
12
10
  * @complexity O(1) operations, excluding filesystem I/O.
13
11
  */
14
- export function createSupervisorRegistry({ registryPath }) {
12
+ export function createSupervisorRegistry({ registryPath, writer }, _optional = {}) {
15
13
  return {
16
14
  readLive: () => readLiveDaemonRegistryRecord({ registryPath }),
17
- write: ({ record }) => writeDaemonRegistryRecord({ registryPath, record }),
15
+ write: ({ record }) => writeDaemonRegistryRecord({ registryPath, record, writer }),
18
16
  removeIfCurrent: ({ pid }) => removeDaemonRegistryRecordIfCurrent({ registryPath, pid }),
19
17
  };
20
18
  }
@@ -25,7 +23,7 @@ function relayProcessOutput({ stream, sink }, _options = {}) {
25
23
  else
26
24
  stream?.resume();
27
25
  }
28
- async function stopWindowsProcess({ child, pid }, options = {}) {
26
+ async function stopWindowsProcess({ child, pid, processes }, options = {}) {
29
27
  // Windows has no group signal, so taskkill supplies the tree-stop escalation.
30
28
  // Windows has no POSIX group signal. Killing only the immediate launcher would
31
29
  // orphan its daemon; taskkill /T walks the entire descendant tree instead.
@@ -34,7 +32,7 @@ async function stopWindowsProcess({ child, pid }, options = {}) {
34
32
  try {
35
33
  child.closeStdin({});
36
34
  // Reuse platform's existing 5s grace before any forced Windows termination.
37
- exited = await (options.waitForProcessExit ?? waitForProcessExit)(pid);
35
+ exited = await processes.waitForProcessExit({ pid });
38
36
  }
39
37
  catch { /* A broken pipe cannot request shutdown; escalate to the whole tree. */ }
40
38
  }
@@ -63,7 +61,8 @@ function daemonLaunchEnvironment(required, options = {}) {
63
61
  function daemonLaunchPlan(required, options = {}) {
64
62
  const win32 = (options.platform ?? process.platform) === 'win32';
65
63
  const env = daemonLaunchEnvironment(required, options);
66
- const invocation = createCommandInvocation({ command: required.command, args: [...required.args], env });
64
+ const { commandShell } = required;
65
+ const invocation = planCommandInvocation({ command: required.command, platform: commandShell.platform, env }, { args: [...required.args], fallbackComSpec: commandShell.fallbackComSpec });
67
66
  const ipc = options.ipc || options.startupSecrets !== undefined;
68
67
  const spawnOptions = {
69
68
  cwd: required.cwd, env: { ...env, ...(win32 ? { JINI_STOP_ON_STDIN_EOF: '1' } : {}) }, detached: true, windowsHide: true,
@@ -73,8 +72,8 @@ function daemonLaunchPlan(required, options = {}) {
73
72
  return { invocation, spawnOptions, win32 };
74
73
  }
75
74
  /**
76
- * Node launch/tree-stop adapter using platform command quoting, snapshots and signal escalation.
77
- * @param required Complete host launch settings and the shared sidecar registry port.
75
+ * Node launch/tree-stop adapter: core's command planner, the host's process control port and signal escalation.
76
+ * @param required Complete host launch settings, the shared sidecar registry port, the process control port and the command shell.
78
77
  * @param options Optional native spawn port and sinks; output is piped through the parent rather than inherited.
79
78
  * @returns Supervisor process ports. Construction has no process or filesystem effects.
80
79
  * @complexity Tree stop is O(p) for p process snapshots, plus platform exit polling.
@@ -115,10 +114,10 @@ export function createNodeDaemonProcessAdapter(required, options = {}) {
115
114
  if (child.pid === undefined)
116
115
  return;
117
116
  const pid = child.pid;
118
- const snapshotRequest = (options.listProcessSnapshots ?? listProcessSnapshots)();
117
+ const snapshotRequest = required.process.listProcessSnapshots({}, {});
119
118
  // Request stop before the first await: even a parent exiting immediately starts tree teardown.
120
119
  if ((options.platform ?? process.platform) === "win32") {
121
- await stopWindowsProcess({ child, pid }, options);
120
+ await stopWindowsProcess({ child, pid, processes: required.process }, options);
122
121
  }
123
122
  else {
124
123
  try {
@@ -129,8 +128,8 @@ export function createNodeDaemonProcessAdapter(required, options = {}) {
129
128
  }
130
129
  }
131
130
  const snapshots = await snapshotRequest;
132
- const pids = collectProcessTreePids(snapshots, [pid]);
133
- const result = await (options.stopProcesses ?? stopProcesses)(pids);
131
+ const pids = collectProcessTreePids({ processes: snapshots, rootPids: [pid] });
132
+ const result = await required.process.stopProcesses({ pids });
134
133
  if (result.remainingPids.length > 0)
135
134
  throw new Error(`daemon processes still running: ${result.remainingPids.join(", ")}`);
136
135
  await required.registry.removeIfCurrent({ pid });
@@ -143,7 +142,7 @@ export function createNodeDaemonProcessAdapter(required, options = {}) {
143
142
  * @returns Scheduler using setTimeout and clearTimeout.
144
143
  * @complexity O(1) per schedule/cancel.
145
144
  */
146
- export function createNodeSupervisorScheduler(_required) {
145
+ export function createNodeSupervisorScheduler(_required, _optional = {}) {
147
146
  return { schedule: ({ delayMs, run }) => { const timer = setTimeout(run, delayMs); return () => clearTimeout(timer); } };
148
147
  }
149
148
  /** Native deserialization supplies plain objects; accept only this channel's envelope. O(1). */
@@ -163,6 +162,23 @@ export function ipcRefusalReason({ value }, _optional = {}) {
163
162
  return undefined;
164
163
  return reason.length > 0 && reason.length <= 1024 ? reason : undefined;
165
164
  }
165
+ /** Complete only a matching request, preserving explicit public refusals. O(1) lookup. */
166
+ function completePendingReply({ pending, message }, _optional = {}) {
167
+ const refusalReason = ipcRefusalReason({ value: message });
168
+ const error = message.ok === true ? null : Object.assign(new Error(refusalReason ?? "IPC request refused"), refusalReason === undefined ? {} : { refusalReason });
169
+ pending.get(message.id)?.finish(error, message.payload);
170
+ }
171
+ /** Run the handler for one inbound request and send exactly one reply; a handler error is never echoed, only its opt-in refusalReason. */
172
+ function serveIpcRequest({ id, payload, handle, reply, onSettled }) {
173
+ void Promise.resolve().then(() => handle(payload)).then(payload => reply({ jiniIpc: 1, kind: "reply", id, ok: true, payload }), error => {
174
+ const refusalReason = ipcRefusalReason({ value: error });
175
+ reply({ jiniIpc: 1, kind: "reply", id, ok: false, ...(refusalReason ? { refusalReason } : {}) });
176
+ }).catch(() => { }).finally(onSettled); // A disconnected peer cannot receive its reply.
177
+ }
178
+ /** Only the size refusal is specific enough to surface; any other send failure stays generic. */
179
+ function ipcSendFailure({ error }) {
180
+ return new Error(error instanceof Error && error.message === "IPC envelope too large" ? error.message : "IPC send failed");
181
+ }
166
182
  /** Native request/reply with bounded pending work. Errors never echo a request, payload or raw handler error.
167
183
  * Handlers may opt into public diagnostics by throwing an error with a `refusalReason` string
168
184
  * (1–1024 characters), e.g. `Object.assign(new Error(), { refusalReason: "This session ended." })`.
@@ -193,18 +209,12 @@ export function createNodeIpcChannel({ peer }, { handle, timeoutMs = 30_000, max
193
209
  dispose({});
194
210
  } // A departing peer cannot receive a refusal.
195
211
  }
196
- /** Complete only a matching request, preserving explicit public refusals. O(1) lookup. */
197
- function receiveReply({ message }, _optional = {}) {
198
- const refusalReason = ipcRefusalReason({ value: message });
199
- const error = message.ok === true ? null : Object.assign(new Error(refusalReason ?? "IPC request refused"), refusalReason === undefined ? {} : { refusalReason });
200
- pending.get(message.id)?.finish(error, message.payload);
201
- }
202
212
  function receive(message) {
203
213
  if (disposed || !isIpcEnvelope(message) || message.channel !== channel)
204
214
  return;
205
215
  const { id } = message;
206
216
  if (message.kind === "reply") {
207
- receiveReply({ message });
217
+ completePendingReply({ pending, message });
208
218
  }
209
219
  else if (message.kind === "request" && handle) {
210
220
  if (handling >= maxPending) {
@@ -212,10 +222,7 @@ export function createNodeIpcChannel({ peer }, { handle, timeoutMs = 30_000, max
212
222
  return;
213
223
  }
214
224
  handling++;
215
- void Promise.resolve().then(() => handle(message.payload)).then(payload => reply({ jiniIpc: 1, kind: "reply", id, ok: true, payload }), error => {
216
- const refusalReason = ipcRefusalReason({ value: error });
217
- reply({ jiniIpc: 1, kind: "reply", id, ok: false, ...(refusalReason ? { refusalReason } : {}) });
218
- }).catch(() => { }).finally(() => { handling--; }); // A disconnected peer cannot receive its reply.
225
+ serveIpcRequest({ id, payload: message.payload, handle, reply, onSettled: () => { handling--; } });
219
226
  }
220
227
  }
221
228
  function dispose(_required, _optional = {}) {
@@ -245,8 +252,7 @@ export function createNodeIpcChannel({ peer }, { handle, timeoutMs = 30_000, max
245
252
  send({ jiniIpc: 1, kind: "request", id, payload });
246
253
  }
247
254
  catch (error) {
248
- const reason = error instanceof Error && error.message === "IPC envelope too large" ? error.message : "IPC send failed";
249
- pending.get(id)?.finish(new Error(reason));
255
+ pending.get(id)?.finish(ipcSendFailure({ error }));
250
256
  }
251
257
  });
252
258
  },
@@ -312,4 +318,9 @@ export async function receiveNodeStartupSecrets({ peer }, { timeoutMs = 30_000,
312
318
  channel.dispose({});
313
319
  }
314
320
  }
321
+ export { createChildRegistry } from "./child-registry.js";
322
+ export { createChildProcessInspection } from "./child-process-inspection.js";
323
+ export { waitForChildReady } from "./child-readiness.js";
324
+ export { stopSpawnedChild } from "./child-stop.js";
325
+ export { createChildExitSignal } from "./child-exit-signal.js";
315
326
  //# sourceMappingURL=supervisor-node.js.map
@@ -125,4 +125,7 @@ export interface DaemonSupervisor {
125
125
  * @complexity O(1) state/work per event, excluding injected ports and policy window pruning.
126
126
  */
127
127
  export declare function createDaemonSupervisor(deps: DaemonSupervisorRequired, options?: DaemonSupervisorOptions): DaemonSupervisor;
128
+ export { createKeyedSerializer, type KeyedSerializer } from "./keyed-serializer.js";
129
+ export { createChildTransitions, type ChildTransition, type ChildTransitions } from "./child-transitions.js";
130
+ export { createChildEntries, type ChildExit, type ObservedServer, type ChildEntry, type ChildEntriesRequired, type ChildEntries } from "./child-entries.js";
128
131
  //# sourceMappingURL=supervisor.d.ts.map