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