@nice-code/commander 0.105.0 → 0.106.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.
package/build/cli.mjs CHANGED
@@ -10,11 +10,11 @@ import { createJiti } from "jiti";
10
10
  import { createHash, randomUUID, webcrypto } from "node:crypto";
11
11
  import { createRequire as createRequire$1 } from "module";
12
12
  import { WebSocket as WebSocket$1 } from "ws";
13
- import { homedir, networkInterfaces } from "node:os";
14
13
  import { execFile, spawn } from "node:child_process";
14
+ import { promisify } from "node:util";
15
+ import { homedir, networkInterfaces } from "node:os";
15
16
  import { connect } from "node:net";
16
17
  import { lookup } from "node:dns/promises";
17
- import { promisify } from "node:util";
18
18
  import { createInterface } from "node:readline/promises";
19
19
  //#region \0rolldown/runtime.js
20
20
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
@@ -24085,6 +24085,85 @@ function createRealmAcceptor(options) {
24085
24085
  };
24086
24086
  }
24087
24087
  //#endregion
24088
+ //#region src/daemon/daemonProcesses.ts
24089
+ const exec$2 = promisify(execFile);
24090
+ /** `pid<space>command line` for every process this user can see. */
24091
+ async function processTable() {
24092
+ if (process.platform === "win32") {
24093
+ const { stdout } = await exec$2("powershell.exe", [
24094
+ "-NoProfile",
24095
+ "-NonInteractive",
24096
+ "-Command",
24097
+ "Get-CimInstance Win32_Process | ForEach-Object { \"$($_.ProcessId) $($_.CommandLine)\" }"
24098
+ ], {
24099
+ maxBuffer: 16 * 1024 * 1024,
24100
+ timeout: 15e3,
24101
+ windowsHide: true
24102
+ });
24103
+ return parseTable(stdout);
24104
+ }
24105
+ const { stdout } = await exec$2("ps", [
24106
+ "-axww",
24107
+ "-o",
24108
+ "pid=",
24109
+ "-o",
24110
+ "args="
24111
+ ], {
24112
+ maxBuffer: 16 * 1024 * 1024,
24113
+ timeout: 1e4
24114
+ });
24115
+ return parseTable(stdout);
24116
+ }
24117
+ function parseTable(text) {
24118
+ const rows = [];
24119
+ for (const line of text.split(/\r?\n/)) {
24120
+ const match = /^\s*(\d+)\s+(.*)$/.exec(line);
24121
+ if (match != null) rows.push({
24122
+ pid: Number(match[1]),
24123
+ commandLine: match[2] ?? ""
24124
+ });
24125
+ }
24126
+ return rows;
24127
+ }
24128
+ /**
24129
+ * Is this command line the daemon for `configPath` under `dataDir`? Quotes are dropped first:
24130
+ * Windows quotes an argument holding a space (`--data-dir "C:\…\App Data"`), `ps` does not.
24131
+ */
24132
+ function isDaemonCommandLine(commandLine, configPath, dataDir) {
24133
+ const line = ` ${commandLine.replaceAll("\"", "")} `;
24134
+ return line.includes(` daemon --config ${configPath} `) && line.includes(` --data-dir ${dataDir} `);
24135
+ }
24136
+ /** One sentence naming record-less daemons and the one command that clears them. */
24137
+ function orphanMessage(orphans) {
24138
+ const one = orphans.length === 1;
24139
+ const pids = orphans.map((orphan) => orphan.pid).join(", ");
24140
+ const them = one ? "it" : "them";
24141
+ return `${one ? "a daemon" : `${orphans.length} daemons`} for this config ${one ? "is" : "are"} running without an instance record (pid ${pids}), so this CLI cannot talk to ${them}. Run \`nice-commander shutdown\` (it stops ${them} and everything ${one ? "it runs" : "they run"}), then retry.`;
24142
+ }
24143
+ /**
24144
+ * Every live daemon process for this config and data dir, except `excludePid` (a daemon asking
24145
+ * about its peers, or a caller that already holds the recorded one). Best effort: a process
24146
+ * table that cannot be read answers "none", never an error — this is a fallback, not the path.
24147
+ */
24148
+ async function findDaemonProcesses(configPath, dataDir, excludePid) {
24149
+ let table;
24150
+ try {
24151
+ table = await processTable();
24152
+ } catch {
24153
+ return [];
24154
+ }
24155
+ const found = [];
24156
+ for (const row of table) {
24157
+ if (row.pid === process.pid || row.pid === excludePid) continue;
24158
+ if (!isDaemonCommandLine(row.commandLine, configPath, dataDir)) continue;
24159
+ found.push({
24160
+ pid: row.pid,
24161
+ startStamp: await readProcessStartStamp(row.pid)
24162
+ });
24163
+ }
24164
+ return found;
24165
+ }
24166
+ //#endregion
24088
24167
  //#region src/daemon/dataDir.ts
24089
24168
  function resolveCommanderDataDir(environment = process.env, platform = process.platform) {
24090
24169
  const override = environment["NICE_COMMANDER_DATA_DIR"];
@@ -24409,6 +24488,16 @@ async function replaceSkewedDaemon(paths, skewed) {
24409
24488
  case "identity-unverified": throw new Error(`${daemonLabel}, but pid ${skewed.pid} could not be verified as that daemon (start stamp missing or changed — possibly pid reuse). Nothing was killed. Verify the pid yourself, and if the daemon is really gone remove ${paths.instanceRecordPath}.`);
24410
24489
  }
24411
24490
  }
24491
+ /** How long `ensureDaemon` lets a record-less daemon finish exiting before calling it an orphan. */
24492
+ const ORPHAN_GRACE_MS = 5e3;
24493
+ async function waitForOrphansToExit(configPath, dataDir, recordedPid) {
24494
+ const deadline = Date.now() + ORPHAN_GRACE_MS;
24495
+ for (;;) {
24496
+ const orphans = await findDaemonProcesses(configPath, dataDir, recordedPid);
24497
+ if (orphans.length === 0 || Date.now() > deadline) return orphans;
24498
+ await new Promise((resolveWait) => setTimeout(resolveWait, 250));
24499
+ }
24500
+ }
24412
24501
  async function ensureDaemon(options) {
24413
24502
  const runtimeError = commanderRuntimeError();
24414
24503
  if (runtimeError != null) throw new Error(runtimeError);
@@ -24430,6 +24519,9 @@ async function ensureDaemon(options) {
24430
24519
  const skewed = await readSkewedInstanceRecord(paths.instanceRecordPath, commanderStatusRealm.schemaHash);
24431
24520
  if (skewed != null && pidAlive$1(skewed.pid)) replaced = await replaceSkewedDaemon(paths, skewed);
24432
24521
  }
24522
+ const recordedPid = existing != null ? existing.pid : void 0;
24523
+ const orphans = await waitForOrphansToExit(options.config.configPath, dataDir, recordedPid);
24524
+ if (orphans.length > 0) throw new Error(orphanMessage(orphans));
24433
24525
  await ensureStateDir(paths);
24434
24526
  const bootFd = openSync(paths.bootLogPath, "w", 384);
24435
24527
  const child = spawn(process.execPath, [
@@ -24850,12 +24942,21 @@ async function findSkewedDaemon(config) {
24850
24942
  servesOwnClient: skewed.servesOwnClient
24851
24943
  };
24852
24944
  }
24945
+ /**
24946
+ * This config's daemons that no instance record points at (see `daemonProcesses.ts`). The CLI
24947
+ * cannot talk to them — no token — but it can name them, and `shutdown` can stop them.
24948
+ */
24949
+ async function findOrphanDaemons(config, recordedPid) {
24950
+ return findDaemonProcesses(config.configPath, resolveCommanderDataDir(), recordedPid);
24951
+ }
24853
24952
  /** Read-only commands' daemon-or-report: never starts anything, exit 3 when not running. */
24854
24953
  async function requireDaemon(config) {
24855
24954
  const handle = await findDaemon(config);
24856
24955
  if (handle != null) return handle;
24857
24956
  const skewed = await findSkewedDaemon(config);
24858
24957
  if (skewed != null) throw new CliExit(EXIT.notRunning, skewed.message);
24958
+ const orphans = await findOrphanDaemons(config);
24959
+ if (orphans.length > 0) throw new CliExit(EXIT.notRunning, orphanMessage(orphans));
24859
24960
  throw new CliExit(EXIT.notRunning, `daemon not running for "${config.name}" (start one with \`up\`)`);
24860
24961
  }
24861
24962
  /** `up`/`ui`'s spawn-or-reuse; the daemon child reruns THIS bin (`daemon` subcommand). */
@@ -25146,17 +25247,47 @@ async function cmdRestart(ctx) {
25146
25247
  async function cmdShutdown(ctx) {
25147
25248
  const bad = unknownFlags(ctx.args.flags, []);
25148
25249
  if (bad != null) throw new CliExit(EXIT.usage, bad);
25149
- const { out } = ctx;
25150
- const handle = await findDaemon(ctx.config);
25151
- if (handle != null) try {
25250
+ const { out, config } = ctx;
25251
+ const reports = [];
25252
+ let code = null;
25253
+ let recordedPid;
25254
+ const handle = await findDaemon(config);
25255
+ if (handle != null) {
25256
+ recordedPid = handle.record.pid;
25257
+ code = await shutdownRecorded(ctx, handle, reports);
25258
+ } else {
25259
+ const skewed = await findSkewedDaemon(config);
25260
+ if (skewed != null) {
25261
+ recordedPid = skewed.pid;
25262
+ if (!out.json) out.print(out.paint("gray", skewed.message));
25263
+ code = reportSignalShutdown(ctx, await signalDaemonShutdown({
25264
+ pid: skewed.pid,
25265
+ startStamp: skewed.startStamp
25266
+ }), "could not be reached over the wire", reports);
25267
+ }
25268
+ }
25269
+ for (const orphan of await findOrphanDaemons(config, recordedPid)) {
25270
+ const next = reportSignalShutdown(ctx, await signalDaemonShutdown(orphan), "was running without an instance record (the CLI had lost track of it)", reports);
25271
+ code = code == null ? next : Math.max(code, next);
25272
+ }
25273
+ if (code == null) throw new CliExit(EXIT.notRunning, `daemon not running for "${config.name}"`);
25274
+ if (out.json) out.printJson(reports.length === 1 ? reports[0] : {
25275
+ ok: reports.every((report) => report["ok"] === true),
25276
+ daemons: reports
25277
+ });
25278
+ return code;
25279
+ }
25280
+ /** The recorded daemon: the wire first (the graceful ask), a verified signal when it refuses. */
25281
+ async function shutdownRecorded(ctx, handle, reports) {
25282
+ try {
25152
25283
  const client = await connectDaemon(handle);
25153
25284
  try {
25154
25285
  await client.shutdown();
25155
- if (out.json) out.printJson({
25286
+ reports.push({
25156
25287
  ok: true,
25157
25288
  via: "wire"
25158
25289
  });
25159
- else out.print(`daemon for "${ctx.config.name}" is shutting down`);
25290
+ if (!ctx.out.json) ctx.out.print(`daemon for "${ctx.config.name}" is shutting down`);
25160
25291
  return EXIT.ok;
25161
25292
  } finally {
25162
25293
  client.dispose();
@@ -25166,42 +25297,33 @@ async function cmdShutdown(ctx) {
25166
25297
  return reportSignalShutdown(ctx, await signalDaemonShutdown({
25167
25298
  pid: handle.record.pid,
25168
25299
  startStamp: handle.record.startStamp
25169
- }));
25170
- }
25171
- const skewed = await findSkewedDaemon(ctx.config);
25172
- if (skewed != null) {
25173
- if (!out.json) out.print(out.paint("gray", skewed.message));
25174
- return reportSignalShutdown(ctx, await signalDaemonShutdown({
25175
- pid: skewed.pid,
25176
- startStamp: skewed.startStamp
25177
- }));
25300
+ }), "could not be reached over the wire", reports);
25178
25301
  }
25179
- throw new CliExit(EXIT.notRunning, `daemon not running for "${ctx.config.name}"`);
25180
25302
  }
25181
- function reportSignalShutdown(ctx, result) {
25303
+ function reportSignalShutdown(ctx, result, why, reports) {
25182
25304
  const { out } = ctx;
25183
- if (out.json) {
25184
- out.printJson({
25185
- ok: result.outcome === "exited",
25186
- via: "signal",
25187
- ...result
25188
- });
25189
- return result.outcome === "exited" ? EXIT.ok : EXIT.failure;
25190
- }
25305
+ const code = result.outcome === "exited" || result.outcome === "not-running" ? EXIT.ok : EXIT.failure;
25306
+ reports.push({
25307
+ ok: result.outcome === "exited",
25308
+ via: "signal",
25309
+ ...result
25310
+ });
25311
+ if (out.json) return code;
25191
25312
  switch (result.outcome) {
25192
25313
  case "exited":
25193
- out.print(`daemon for "${ctx.config.name}" (pid ${result.pid}) could not be reached over the wire — stopped via signal (its own shutdown ladder ran)`);
25194
- return EXIT.ok;
25314
+ out.print(`daemon for "${ctx.config.name}" (pid ${result.pid}) ${why} — stopped via signal (its own shutdown ladder ran)`);
25315
+ break;
25195
25316
  case "still-stopping":
25196
25317
  out.print(out.paint("yellow", `⚠ daemon (pid ${result.pid}) was signalled and is still stopping — run \`shutdown\` again to escalate if it stays stuck`));
25197
- return EXIT.failure;
25318
+ break;
25198
25319
  case "identity-unverified":
25199
- out.print(out.paint("yellow", `⚠ pid ${result.pid} could not be verified as the recorded daemon (start stamp missing or changed — possibly pid reuse). Nothing was killed; verify the pid yourself, and remove the instance record if the daemon is really gone.`));
25200
- return EXIT.failure;
25320
+ out.print(out.paint("yellow", `⚠ pid ${result.pid} could not be verified as this config's daemon (start stamp missing or changed — possibly pid reuse). Nothing was killed; verify the pid yourself, and remove the instance record if the daemon is really gone.`));
25321
+ break;
25201
25322
  case "not-running":
25202
25323
  out.print(`daemon not running for "${ctx.config.name}" (stale record)`);
25203
- return EXIT.ok;
25324
+ break;
25204
25325
  }
25326
+ return code;
25205
25327
  }
25206
25328
  //#endregion
25207
25329
  //#region src/daemon/envOverrides.ts
@@ -27141,29 +27263,36 @@ async function stopExistingDaemon(ctx) {
27141
27263
  const { config, out } = ctx;
27142
27264
  const live = await findDaemon(config);
27143
27265
  const skewed = live == null ? await findSkewedDaemon(config) : null;
27144
- const target = live != null ? {
27266
+ const recorded = live != null ? {
27145
27267
  pid: live.record.pid,
27146
27268
  startStamp: live.record.startStamp
27147
27269
  } : skewed != null ? {
27148
27270
  pid: skewed.pid,
27149
27271
  startStamp: skewed.startStamp
27150
27272
  } : null;
27151
- if (target == null) return;
27152
- if (!out.json) out.print(out.paint("gray", `--fresh: stopping the daemon (pid ${target.pid})…`));
27153
- if (live != null) try {
27273
+ const targets = [...recorded != null ? [recorded] : [], ...await findOrphanDaemons(config, recorded?.pid)];
27274
+ for (const target of targets) {
27275
+ if (!out.json) out.print(out.paint("gray", `--fresh: stopping the daemon (pid ${target.pid})…`));
27276
+ if (target === recorded && live != null && await stopOverWire(live)) continue;
27277
+ const result = await signalDaemonShutdown(target);
27278
+ if (result.outcome === "exited" || result.outcome === "not-running") continue;
27279
+ throw new CliExit(EXIT.failure, result.outcome === "still-stopping" ? `--fresh: the daemon (pid ${target.pid}) is still stopping — retry in a moment` : `--fresh: pid ${target.pid} could not be verified as this config's daemon (possibly pid reuse), so nothing was stopped — verify it yourself, then retry`);
27280
+ }
27281
+ }
27282
+ /** The graceful ask; false when the wire refuses us or the ladder outlasts the wait. */
27283
+ async function stopOverWire(live) {
27284
+ try {
27154
27285
  const client = await connectDaemon(live);
27155
27286
  try {
27156
27287
  await client.shutdown();
27157
27288
  } finally {
27158
27289
  client.dispose();
27159
27290
  }
27160
- if (await waitForExit(target.pid, FRESH_EXIT_WAIT_MS)) return;
27161
27291
  } catch (error) {
27162
27292
  if (!(error instanceof CliExit)) throw error;
27293
+ return false;
27163
27294
  }
27164
- const result = await signalDaemonShutdown(target);
27165
- if (result.outcome === "exited" || result.outcome === "not-running") return;
27166
- throw new CliExit(EXIT.failure, result.outcome === "still-stopping" ? `--fresh: the daemon (pid ${target.pid}) is still stopping — retry in a moment` : `--fresh: pid ${target.pid} could not be verified as this config's daemon (possibly pid reuse), so nothing was stopped — verify it yourself, then retry`);
27295
+ return waitForExit(live.record.pid, FRESH_EXIT_WAIT_MS);
27167
27296
  }
27168
27297
  async function waitForExit(pid, timeoutMs) {
27169
27298
  const deadline = Date.now() + timeoutMs;
@@ -27378,7 +27507,7 @@ async function withTimeout(ctx, run) {
27378
27507
  async function main() {
27379
27508
  const argv = process.argv.slice(2);
27380
27509
  if (argv[0] === "daemon") {
27381
- const { runCommanderDaemon } = await import("./main-C5HqmZgp.mjs");
27510
+ const { runCommanderDaemon } = await import("./main-1B7viLr8.mjs");
27382
27511
  return runCommanderDaemon(argv.slice(1));
27383
27512
  }
27384
27513
  const parsed = parseCliArgs(argv);
@@ -27423,6 +27552,6 @@ main().then((code) => {
27423
27552
  process.exitCode = EXIT.failure;
27424
27553
  });
27425
27554
  //#endregion
27426
- export { httpAcceptorCarrier as A, hashCanonical as B, commanderRuntimeError as C, resolveCommanderDataDir as D, ensureStateDir as E, wsAcceptorCarrier as F, savedFilterId as G, orderByDependency as H, validateCommanderConfig as I, removeInstanceRecord as J, readInstanceRecord as K, effectiveEnv as L, createDefaultServeLogger as M, RuntimeCoordinate as N, createRealmAcceptor as O, createMemoryStorageAdapter_json as P, envVarViews as R, commanderStatusRealm as S, commanderStatePaths as T, stopSetWithDependencies as U, loadCommanderConfigFile as V, withDependencies as W, writeInstanceRecord as Y, COMMANDER_LOGS_PATH as _, parseLogsClientMessage as a, COMMANDER_TICKET_PROTOCOL_PREFIX as b, identifyEndpointOwner as c, countOverrides as d, readEnvOverrides as f, COMMANDER_HEALTH_PATH as g, COMMANDER_BOOTSTRAP_PATH as h, runTaskPool as i, serveChannel as j, createRealmServerEngine as k, signalStray as l, commanderControlDomain as m, readSavedFilters as n, ancestors as o, commanderChannel as p, recordDaemonAlive as q, writeSavedFilters as r, createPortInspector as s, mutateSavedFilters as t, applyEnvMutation as u, COMMANDER_SHUTDOWN_PATH as v, commanderPackageVersion as w, COMMANDER_WS_PATH as x, COMMANDER_TICKET_PATH as y, overrideFingerprint as z };
27555
+ export { createRealmServerEngine as A, overrideFingerprint as B, commanderRuntimeError as C, resolveCommanderDataDir as D, ensureStateDir as E, createMemoryStorageAdapter_json as F, withDependencies as G, loadCommanderConfigFile as H, wsAcceptorCarrier as I, recordDaemonAlive as J, savedFilterId as K, validateCommanderConfig as L, serveChannel as M, createDefaultServeLogger as N, findDaemonProcesses as O, RuntimeCoordinate as P, effectiveEnv as R, commanderStatusRealm as S, commanderStatePaths as T, orderByDependency as U, hashCanonical as V, stopSetWithDependencies as W, writeInstanceRecord as X, removeInstanceRecord as Y, COMMANDER_LOGS_PATH as _, parseLogsClientMessage as a, COMMANDER_TICKET_PROTOCOL_PREFIX as b, identifyEndpointOwner as c, countOverrides as d, readEnvOverrides as f, COMMANDER_HEALTH_PATH as g, COMMANDER_BOOTSTRAP_PATH as h, runTaskPool as i, httpAcceptorCarrier as j, createRealmAcceptor as k, signalStray as l, commanderControlDomain as m, readSavedFilters as n, ancestors as o, commanderChannel as p, readInstanceRecord as q, writeSavedFilters as r, createPortInspector as s, mutateSavedFilters as t, applyEnvMutation as u, COMMANDER_SHUTDOWN_PATH as v, commanderPackageVersion as w, COMMANDER_WS_PATH as x, COMMANDER_TICKET_PATH as y, envVarViews as z };
27427
27556
 
27428
27557
  //# sourceMappingURL=cli.mjs.map