@nice-code/commander 0.105.0 → 0.107.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.cjs CHANGED
@@ -13,11 +13,11 @@ let jiti = require("jiti");
13
13
  let node_crypto = require("node:crypto");
14
14
  let module$1 = require("module");
15
15
  let ws = require("ws");
16
- let node_os = require("node:os");
17
16
  let node_child_process = require("node:child_process");
17
+ let node_util = require("node:util");
18
+ let node_os = require("node:os");
18
19
  let node_net = require("node:net");
19
20
  let node_dns_promises = require("node:dns/promises");
20
- let node_util = require("node:util");
21
21
  let node_readline_promises = require("node:readline/promises");
22
22
  //#region src/cli/args.ts
23
23
  const GLOBAL_VALUE_FLAGS = new Set(["--config", "--timeout"]);
@@ -234,8 +234,7 @@ async function recordDaemonAlive(record) {
234
234
  if (error.code !== "EPERM") return false;
235
235
  }
236
236
  if (record.startStamp == null) return true;
237
- const stamp = await (0, _nice_code_process.readProcessStartStamp)(record.pid);
238
- return stamp != null && stamp.stamp === record.startStamp.stamp;
237
+ return await (0, _nice_code_process.matchProcessStartStamp)(record.pid, record.startStamp.stamp) === "match";
239
238
  }
240
239
  /**
241
240
  * Protocol-independent shutdown: verify the record's pid is still the daemon it claims to be
@@ -258,8 +257,7 @@ async function signalDaemonShutdown(target, waitMs = 15e3) {
258
257
  outcome: "identity-unverified",
259
258
  pid
260
259
  };
261
- const stamp = await (0, _nice_code_process.readProcessStartStamp)(pid);
262
- if (stamp == null || stamp.stamp !== startStamp.stamp) return {
260
+ if (await (0, _nice_code_process.matchProcessStartStamp)(pid, startStamp.stamp) !== "match") return {
263
261
  outcome: "identity-unverified",
264
262
  pid
265
263
  };
@@ -24084,6 +24082,85 @@ function createRealmAcceptor(options) {
24084
24082
  };
24085
24083
  }
24086
24084
  //#endregion
24085
+ //#region src/daemon/daemonProcesses.ts
24086
+ const exec$2 = (0, node_util.promisify)(node_child_process.execFile);
24087
+ /** `pid<space>command line` for every process this user can see. */
24088
+ async function processTable() {
24089
+ if (process.platform === "win32") {
24090
+ const { stdout } = await exec$2("powershell.exe", [
24091
+ "-NoProfile",
24092
+ "-NonInteractive",
24093
+ "-Command",
24094
+ "Get-CimInstance Win32_Process | ForEach-Object { \"$($_.ProcessId) $($_.CommandLine)\" }"
24095
+ ], {
24096
+ maxBuffer: 16 * 1024 * 1024,
24097
+ timeout: 15e3,
24098
+ windowsHide: true
24099
+ });
24100
+ return parseTable(stdout);
24101
+ }
24102
+ const { stdout } = await exec$2("ps", [
24103
+ "-axww",
24104
+ "-o",
24105
+ "pid=",
24106
+ "-o",
24107
+ "args="
24108
+ ], {
24109
+ maxBuffer: 16 * 1024 * 1024,
24110
+ timeout: 1e4
24111
+ });
24112
+ return parseTable(stdout);
24113
+ }
24114
+ function parseTable(text) {
24115
+ const rows = [];
24116
+ for (const line of text.split(/\r?\n/)) {
24117
+ const match = /^\s*(\d+)\s+(.*)$/.exec(line);
24118
+ if (match != null) rows.push({
24119
+ pid: Number(match[1]),
24120
+ commandLine: match[2] ?? ""
24121
+ });
24122
+ }
24123
+ return rows;
24124
+ }
24125
+ /**
24126
+ * Is this command line the daemon for `configPath` under `dataDir`? Quotes are dropped first:
24127
+ * Windows quotes an argument holding a space (`--data-dir "C:\…\App Data"`), `ps` does not.
24128
+ */
24129
+ function isDaemonCommandLine(commandLine, configPath, dataDir) {
24130
+ const line = ` ${commandLine.replaceAll("\"", "")} `;
24131
+ return line.includes(` daemon --config ${configPath} `) && line.includes(` --data-dir ${dataDir} `);
24132
+ }
24133
+ /** One sentence naming record-less daemons and the one command that clears them. */
24134
+ function orphanMessage(orphans) {
24135
+ const one = orphans.length === 1;
24136
+ const pids = orphans.map((orphan) => orphan.pid).join(", ");
24137
+ const them = one ? "it" : "them";
24138
+ 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.`;
24139
+ }
24140
+ /**
24141
+ * Every live daemon process for this config and data dir, except `excludePid` (a daemon asking
24142
+ * about its peers, or a caller that already holds the recorded one). Best effort: a process
24143
+ * table that cannot be read answers "none", never an error — this is a fallback, not the path.
24144
+ */
24145
+ async function findDaemonProcesses(configPath, dataDir, excludePid) {
24146
+ let table;
24147
+ try {
24148
+ table = await processTable();
24149
+ } catch {
24150
+ return [];
24151
+ }
24152
+ const found = [];
24153
+ for (const row of table) {
24154
+ if (row.pid === process.pid || row.pid === excludePid) continue;
24155
+ if (!isDaemonCommandLine(row.commandLine, configPath, dataDir)) continue;
24156
+ found.push({
24157
+ pid: row.pid,
24158
+ startStamp: await (0, _nice_code_process.readProcessStartStamp)(row.pid)
24159
+ });
24160
+ }
24161
+ return found;
24162
+ }
24163
+ //#endregion
24087
24164
  //#region src/daemon/dataDir.ts
24088
24165
  function resolveCommanderDataDir(environment = process.env, platform = process.platform) {
24089
24166
  const override = environment["NICE_COMMANDER_DATA_DIR"];
@@ -24408,6 +24485,16 @@ async function replaceSkewedDaemon(paths, skewed) {
24408
24485
  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}.`);
24409
24486
  }
24410
24487
  }
24488
+ /** How long `ensureDaemon` lets a record-less daemon finish exiting before calling it an orphan. */
24489
+ const ORPHAN_GRACE_MS = 5e3;
24490
+ async function waitForOrphansToExit(configPath, dataDir, recordedPid) {
24491
+ const deadline = Date.now() + ORPHAN_GRACE_MS;
24492
+ for (;;) {
24493
+ const orphans = await findDaemonProcesses(configPath, dataDir, recordedPid);
24494
+ if (orphans.length === 0 || Date.now() > deadline) return orphans;
24495
+ await new Promise((resolveWait) => setTimeout(resolveWait, 250));
24496
+ }
24497
+ }
24411
24498
  async function ensureDaemon(options) {
24412
24499
  const runtimeError = commanderRuntimeError();
24413
24500
  if (runtimeError != null) throw new Error(runtimeError);
@@ -24429,6 +24516,9 @@ async function ensureDaemon(options) {
24429
24516
  const skewed = await readSkewedInstanceRecord(paths.instanceRecordPath, commanderStatusRealm.schemaHash);
24430
24517
  if (skewed != null && pidAlive$1(skewed.pid)) replaced = await replaceSkewedDaemon(paths, skewed);
24431
24518
  }
24519
+ const recordedPid = existing != null ? existing.pid : void 0;
24520
+ const orphans = await waitForOrphansToExit(options.config.configPath, dataDir, recordedPid);
24521
+ if (orphans.length > 0) throw new Error(orphanMessage(orphans));
24432
24522
  await ensureStateDir(paths);
24433
24523
  const bootFd = (0, node_fs.openSync)(paths.bootLogPath, "w", 384);
24434
24524
  const child = (0, node_child_process.spawn)(process.execPath, [
@@ -24849,12 +24939,21 @@ async function findSkewedDaemon(config) {
24849
24939
  servesOwnClient: skewed.servesOwnClient
24850
24940
  };
24851
24941
  }
24942
+ /**
24943
+ * This config's daemons that no instance record points at (see `daemonProcesses.ts`). The CLI
24944
+ * cannot talk to them — no token — but it can name them, and `shutdown` can stop them.
24945
+ */
24946
+ async function findOrphanDaemons(config, recordedPid) {
24947
+ return findDaemonProcesses(config.configPath, resolveCommanderDataDir(), recordedPid);
24948
+ }
24852
24949
  /** Read-only commands' daemon-or-report: never starts anything, exit 3 when not running. */
24853
24950
  async function requireDaemon(config) {
24854
24951
  const handle = await findDaemon(config);
24855
24952
  if (handle != null) return handle;
24856
24953
  const skewed = await findSkewedDaemon(config);
24857
24954
  if (skewed != null) throw new CliExit(EXIT.notRunning, skewed.message);
24955
+ const orphans = await findOrphanDaemons(config);
24956
+ if (orphans.length > 0) throw new CliExit(EXIT.notRunning, orphanMessage(orphans));
24858
24957
  throw new CliExit(EXIT.notRunning, `daemon not running for "${config.name}" (start one with \`up\`)`);
24859
24958
  }
24860
24959
  /** `up`/`ui`'s spawn-or-reuse; the daemon child reruns THIS bin (`daemon` subcommand). */
@@ -25145,17 +25244,47 @@ async function cmdRestart(ctx) {
25145
25244
  async function cmdShutdown(ctx) {
25146
25245
  const bad = unknownFlags(ctx.args.flags, []);
25147
25246
  if (bad != null) throw new CliExit(EXIT.usage, bad);
25148
- const { out } = ctx;
25149
- const handle = await findDaemon(ctx.config);
25150
- if (handle != null) try {
25247
+ const { out, config } = ctx;
25248
+ const reports = [];
25249
+ let code = null;
25250
+ let recordedPid;
25251
+ const handle = await findDaemon(config);
25252
+ if (handle != null) {
25253
+ recordedPid = handle.record.pid;
25254
+ code = await shutdownRecorded(ctx, handle, reports);
25255
+ } else {
25256
+ const skewed = await findSkewedDaemon(config);
25257
+ if (skewed != null) {
25258
+ recordedPid = skewed.pid;
25259
+ if (!out.json) out.print(out.paint("gray", skewed.message));
25260
+ code = reportSignalShutdown(ctx, await signalDaemonShutdown({
25261
+ pid: skewed.pid,
25262
+ startStamp: skewed.startStamp
25263
+ }), "could not be reached over the wire", reports);
25264
+ }
25265
+ }
25266
+ for (const orphan of await findOrphanDaemons(config, recordedPid)) {
25267
+ const next = reportSignalShutdown(ctx, await signalDaemonShutdown(orphan), "was running without an instance record (the CLI had lost track of it)", reports);
25268
+ code = code == null ? next : Math.max(code, next);
25269
+ }
25270
+ if (code == null) throw new CliExit(EXIT.notRunning, `daemon not running for "${config.name}"`);
25271
+ if (out.json) out.printJson(reports.length === 1 ? reports[0] : {
25272
+ ok: reports.every((report) => report["ok"] === true),
25273
+ daemons: reports
25274
+ });
25275
+ return code;
25276
+ }
25277
+ /** The recorded daemon: the wire first (the graceful ask), a verified signal when it refuses. */
25278
+ async function shutdownRecorded(ctx, handle, reports) {
25279
+ try {
25151
25280
  const client = await connectDaemon(handle);
25152
25281
  try {
25153
25282
  await client.shutdown();
25154
- if (out.json) out.printJson({
25283
+ reports.push({
25155
25284
  ok: true,
25156
25285
  via: "wire"
25157
25286
  });
25158
- else out.print(`daemon for "${ctx.config.name}" is shutting down`);
25287
+ if (!ctx.out.json) ctx.out.print(`daemon for "${ctx.config.name}" is shutting down`);
25159
25288
  return EXIT.ok;
25160
25289
  } finally {
25161
25290
  client.dispose();
@@ -25165,42 +25294,33 @@ async function cmdShutdown(ctx) {
25165
25294
  return reportSignalShutdown(ctx, await signalDaemonShutdown({
25166
25295
  pid: handle.record.pid,
25167
25296
  startStamp: handle.record.startStamp
25168
- }));
25169
- }
25170
- const skewed = await findSkewedDaemon(ctx.config);
25171
- if (skewed != null) {
25172
- if (!out.json) out.print(out.paint("gray", skewed.message));
25173
- return reportSignalShutdown(ctx, await signalDaemonShutdown({
25174
- pid: skewed.pid,
25175
- startStamp: skewed.startStamp
25176
- }));
25297
+ }), "could not be reached over the wire", reports);
25177
25298
  }
25178
- throw new CliExit(EXIT.notRunning, `daemon not running for "${ctx.config.name}"`);
25179
25299
  }
25180
- function reportSignalShutdown(ctx, result) {
25300
+ function reportSignalShutdown(ctx, result, why, reports) {
25181
25301
  const { out } = ctx;
25182
- if (out.json) {
25183
- out.printJson({
25184
- ok: result.outcome === "exited",
25185
- via: "signal",
25186
- ...result
25187
- });
25188
- return result.outcome === "exited" ? EXIT.ok : EXIT.failure;
25189
- }
25302
+ const code = result.outcome === "exited" || result.outcome === "not-running" ? EXIT.ok : EXIT.failure;
25303
+ reports.push({
25304
+ ok: result.outcome === "exited",
25305
+ via: "signal",
25306
+ ...result
25307
+ });
25308
+ if (out.json) return code;
25190
25309
  switch (result.outcome) {
25191
25310
  case "exited":
25192
- 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)`);
25193
- return EXIT.ok;
25311
+ out.print(`daemon for "${ctx.config.name}" (pid ${result.pid}) ${why} — stopped via signal (its own shutdown ladder ran)`);
25312
+ break;
25194
25313
  case "still-stopping":
25195
25314
  out.print(out.paint("yellow", `⚠ daemon (pid ${result.pid}) was signalled and is still stopping — run \`shutdown\` again to escalate if it stays stuck`));
25196
- return EXIT.failure;
25315
+ break;
25197
25316
  case "identity-unverified":
25198
- 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.`));
25199
- return EXIT.failure;
25317
+ 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.`));
25318
+ break;
25200
25319
  case "not-running":
25201
25320
  out.print(`daemon not running for "${ctx.config.name}" (stale record)`);
25202
- return EXIT.ok;
25321
+ break;
25203
25322
  }
25323
+ return code;
25204
25324
  }
25205
25325
  //#endregion
25206
25326
  //#region src/daemon/envOverrides.ts
@@ -25886,8 +26006,7 @@ async function diagnose(ctx, handle) {
25886
26006
  continue;
25887
26007
  }
25888
26008
  if (record.startStamp != null) {
25889
- const stamp = await (0, _nice_code_process.readProcessStartStamp)(record.pid);
25890
- if (stamp == null || stamp.stamp !== record.startStamp) {
26009
+ if (await (0, _nice_code_process.matchProcessStartStamp)(record.pid, record.startStamp) !== "match") {
25891
26010
  report.warnings.push(`ledger "${record.id}": pid ${record.pid} fails the fingerprint check (reuse?) — quarantine-suspect`);
25892
26011
  continue;
25893
26012
  }
@@ -27140,29 +27259,36 @@ async function stopExistingDaemon(ctx) {
27140
27259
  const { config, out } = ctx;
27141
27260
  const live = await findDaemon(config);
27142
27261
  const skewed = live == null ? await findSkewedDaemon(config) : null;
27143
- const target = live != null ? {
27262
+ const recorded = live != null ? {
27144
27263
  pid: live.record.pid,
27145
27264
  startStamp: live.record.startStamp
27146
27265
  } : skewed != null ? {
27147
27266
  pid: skewed.pid,
27148
27267
  startStamp: skewed.startStamp
27149
27268
  } : null;
27150
- if (target == null) return;
27151
- if (!out.json) out.print(out.paint("gray", `--fresh: stopping the daemon (pid ${target.pid})…`));
27152
- if (live != null) try {
27269
+ const targets = [...recorded != null ? [recorded] : [], ...await findOrphanDaemons(config, recorded?.pid)];
27270
+ for (const target of targets) {
27271
+ if (!out.json) out.print(out.paint("gray", `--fresh: stopping the daemon (pid ${target.pid})…`));
27272
+ if (target === recorded && live != null && await stopOverWire(live)) continue;
27273
+ const result = await signalDaemonShutdown(target);
27274
+ if (result.outcome === "exited" || result.outcome === "not-running") continue;
27275
+ 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`);
27276
+ }
27277
+ }
27278
+ /** The graceful ask; false when the wire refuses us or the ladder outlasts the wait. */
27279
+ async function stopOverWire(live) {
27280
+ try {
27153
27281
  const client = await connectDaemon(live);
27154
27282
  try {
27155
27283
  await client.shutdown();
27156
27284
  } finally {
27157
27285
  client.dispose();
27158
27286
  }
27159
- if (await waitForExit(target.pid, FRESH_EXIT_WAIT_MS)) return;
27160
27287
  } catch (error) {
27161
27288
  if (!(error instanceof CliExit)) throw error;
27289
+ return false;
27162
27290
  }
27163
- const result = await signalDaemonShutdown(target);
27164
- if (result.outcome === "exited" || result.outcome === "not-running") return;
27165
- 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`);
27291
+ return waitForExit(live.record.pid, FRESH_EXIT_WAIT_MS);
27166
27292
  }
27167
27293
  async function waitForExit(pid, timeoutMs) {
27168
27294
  const deadline = Date.now() + timeoutMs;
@@ -27377,7 +27503,7 @@ async function withTimeout(ctx, run) {
27377
27503
  async function main() {
27378
27504
  const argv = process.argv.slice(2);
27379
27505
  if (argv[0] === "daemon") {
27380
- const { runCommanderDaemon } = await Promise.resolve().then(() => require("./main-vXl0q1X7.cjs"));
27506
+ const { runCommanderDaemon } = await Promise.resolve().then(() => require("./main-BHPsC_5Q.cjs"));
27381
27507
  return runCommanderDaemon(argv.slice(1));
27382
27508
  }
27383
27509
  const parsed = parseCliArgs(argv);
@@ -27447,6 +27573,7 @@ exports.createRealmServerEngine = createRealmServerEngine;
27447
27573
  exports.effectiveEnv = effectiveEnv;
27448
27574
  exports.ensureStateDir = ensureStateDir;
27449
27575
  exports.envVarViews = envVarViews;
27576
+ exports.findDaemonProcesses = findDaemonProcesses;
27450
27577
  exports.hashCanonical = hashCanonical;
27451
27578
  exports.httpAcceptorCarrier = httpAcceptorCarrier;
27452
27579
  exports.identifyEndpointOwner = identifyEndpointOwner;