@nice-code/commander 0.104.0 → 0.105.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
@@ -152,7 +152,7 @@ function validStartStamp(value) {
152
152
  function isInstanceRecord(value) {
153
153
  if (value == null || typeof value !== "object" || Array.isArray(value)) return false;
154
154
  const record = value;
155
- return record.service === "nice-commander" && boundedString(record.instanceId) && boundedInt(record.generation, 0, Number.MAX_SAFE_INTEGER) && boundedInt(record.pid, 1, Number.MAX_SAFE_INTEGER) && boundedInt(record.port, 1, 65535) && boundedString(record.token) && boundedString(record.configKey) && boundedString(record.configRevisionHash) && boundedString(record.configPath) && boundedString(record.packageVersion) && boundedString(record.realmSchemaHash) && validStartStamp(record.startStamp) && record.protocolVersion === 7;
155
+ return record.service === "nice-commander" && boundedString(record.instanceId) && boundedInt(record.generation, 0, Number.MAX_SAFE_INTEGER) && boundedInt(record.pid, 1, Number.MAX_SAFE_INTEGER) && boundedInt(record.port, 1, 65535) && boundedString(record.token) && boundedString(record.configKey) && boundedString(record.configRevisionHash) && boundedString(record.configPath) && boundedString(record.packageVersion) && boundedString(record.realmSchemaHash) && validStartStamp(record.startStamp) && (record.servesOwnClient == null || typeof record.servesOwnClient === "boolean") && record.protocolVersion === 7;
156
156
  }
157
157
  async function writeInstanceRecord(path, record) {
158
158
  await mkdir(dirname(path), {
@@ -211,7 +211,8 @@ async function readSkewedInstanceRecord(path, expectedRealmSchemaHash) {
211
211
  protocolVersion: record["protocolVersion"],
212
212
  packageVersion: boundedString(record["packageVersion"]) ? record["packageVersion"] : "unknown",
213
213
  startStamp: validStartStamp(record["startStamp"]) ? record["startStamp"] ?? null : null,
214
- skew: sameProtocol ? "realm-schema" : "protocol"
214
+ skew: sameProtocol ? "realm-schema" : "protocol",
215
+ servesOwnClient: record["servesOwnClient"] === true
215
216
  };
216
217
  }
217
218
  /** Liveness only — enough to say "something is there", never enough to authorize a kill (C1). */
@@ -24494,6 +24495,11 @@ const COMMANDER_TICKET_PATH = "/ticket";
24494
24495
  /** CLI liveness/discovery probe (instance-record root token only). */
24495
24496
  const COMMANDER_HEALTH_PATH = "/health";
24496
24497
  /**
24498
+ * Plain-HTTP shutdown, capability-gated. It needs no realm, so a page from another build — one
24499
+ * that can never attach the status realm — can still stop the daemon it is stuck on.
24500
+ */
24501
+ const COMMANDER_SHUTDOWN_PATH = "/shutdown";
24502
+ /**
24497
24503
  * ws tickets ride the subprotocol negotiation (browsers cannot set arbitrary ws headers):
24498
24504
  * the client offers `commander-auth.<ticket>`, the daemon selects it to complete the upgrade.
24499
24505
  */
@@ -24838,7 +24844,10 @@ async function findSkewedDaemon(config) {
24838
24844
  return {
24839
24845
  message: `the daemon for this config (pid ${skewed.pid}, port ${skewed.port}, build ${skewed.packageVersion}) ${difference} — this CLI (build ${await commanderPackageVersion()}) cannot talk to it. Run \`nice-commander shutdown\` (it stops a daemon from any build), then retry.`,
24840
24846
  pid: skewed.pid,
24841
- startStamp: skewed.startStamp
24847
+ port: skewed.port,
24848
+ packageVersion: skewed.packageVersion,
24849
+ startStamp: skewed.startStamp,
24850
+ servesOwnClient: skewed.servesOwnClient
24842
24851
  };
24843
24852
  }
24844
24853
  /** Read-only commands' daemon-or-report: never starts anything, exit 3 when not running. */
@@ -27063,6 +27072,7 @@ async function candidates() {
27063
27072
  }
27064
27073
  /** Try each opener in turn; resolves true when one spawns without an immediate failure. */
27065
27074
  async function openBrowser(url) {
27075
+ if (process.env["NICE_COMMANDER_NO_BROWSER"] === "1") return false;
27066
27076
  for (const candidate of await candidates()) if (await new Promise((resolve) => {
27067
27077
  try {
27068
27078
  const child = spawn(candidate.command, candidate.args(url), {
@@ -27081,20 +27091,88 @@ async function openBrowser(url) {
27081
27091
  }
27082
27092
  //#endregion
27083
27093
  //#region src/cli/commands/ui.ts
27094
+ /** How long a wire-requested shutdown gets to finish its ladder before a signal follows it. */
27095
+ const FRESH_EXIT_WAIT_MS = 3e4;
27084
27096
  async function cmdUi(ctx) {
27085
- const bad = unknownFlags(ctx.args.flags, []);
27097
+ const bad = unknownFlags(ctx.args.flags, ["--fresh"]);
27086
27098
  if (bad != null) throw new CliExit(EXIT.usage, bad);
27099
+ const { out } = ctx;
27100
+ if (ctx.args.flags.get("--fresh") === true) await stopExistingDaemon(ctx);
27101
+ else {
27102
+ const skewed = await findSkewedDaemon(ctx.config);
27103
+ if (skewed?.servesOwnClient === true) {
27104
+ const url = `http://127.0.0.1:${skewed.port}`;
27105
+ const opened = await openBrowser(url);
27106
+ if (out.json) out.printJson({
27107
+ url,
27108
+ opened,
27109
+ attached: true,
27110
+ daemonBuild: skewed.packageVersion
27111
+ });
27112
+ else {
27113
+ out.print(opened ? `opened ${url}` : `could not open a browser — visit ${url}`);
27114
+ out.print(out.paint("gray", `attached to the running daemon (build ${skewed.packageVersion}; this CLI is ${await commanderPackageVersion()}). \`nice-commander ui --fresh\` restarts it on this build — that stops everything it runs.`));
27115
+ }
27116
+ return EXIT.ok;
27117
+ }
27118
+ }
27087
27119
  const handle = await ensureDaemonRunning(ctx.config);
27088
27120
  ctx.spawnedDaemon = handle.spawned;
27089
27121
  const url = `http://127.0.0.1:${handle.record.port}`;
27090
27122
  const opened = await openBrowser(url);
27091
- if (ctx.out.json) ctx.out.printJson({
27123
+ if (out.json) out.printJson({
27092
27124
  url,
27093
- opened
27125
+ opened,
27126
+ attached: !handle.spawned
27094
27127
  });
27095
- else ctx.out.print(opened ? `opened ${url}` : `could not open a browser — visit ${url}`);
27128
+ else {
27129
+ if (handle.replaced != null) out.print(out.paint("gray", `replaced an idle daemon from build ${handle.replaced.packageVersion} (pid ${handle.replaced.pid})`));
27130
+ out.print(opened ? `opened ${url}` : `could not open a browser — visit ${url}`);
27131
+ }
27096
27132
  return EXIT.ok;
27097
27133
  }
27134
+ /**
27135
+ * `--fresh`: stop this config's daemon, whatever build it is, and wait until it has exited — the
27136
+ * boot that follows must not find (and reuse) a daemon that is still walking its ladder.
27137
+ * The wire goes first when it speaks our build: a signal is the fallback, because on Windows it
27138
+ * is a hard kill that skips the ladder.
27139
+ */
27140
+ async function stopExistingDaemon(ctx) {
27141
+ const { config, out } = ctx;
27142
+ const live = await findDaemon(config);
27143
+ const skewed = live == null ? await findSkewedDaemon(config) : null;
27144
+ const target = live != null ? {
27145
+ pid: live.record.pid,
27146
+ startStamp: live.record.startStamp
27147
+ } : skewed != null ? {
27148
+ pid: skewed.pid,
27149
+ startStamp: skewed.startStamp
27150
+ } : 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 {
27154
+ const client = await connectDaemon(live);
27155
+ try {
27156
+ await client.shutdown();
27157
+ } finally {
27158
+ client.dispose();
27159
+ }
27160
+ if (await waitForExit(target.pid, FRESH_EXIT_WAIT_MS)) return;
27161
+ } catch (error) {
27162
+ if (!(error instanceof CliExit)) throw error;
27163
+ }
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`);
27167
+ }
27168
+ async function waitForExit(pid, timeoutMs) {
27169
+ const deadline = Date.now() + timeoutMs;
27170
+ while (Date.now() < deadline) {
27171
+ if (!pidAlive$1(pid)) return true;
27172
+ await new Promise((resolve) => setTimeout(resolve, 150));
27173
+ }
27174
+ return !pidAlive$1(pid);
27175
+ }
27098
27176
  //#endregion
27099
27177
  //#region src/daemon/savedFilters.ts
27100
27178
  const STORE_VERSION = 1;
@@ -27217,7 +27295,10 @@ const COMMAND_HELP = [
27217
27295
  non-zero. Children inherit THIS shell's environment;
27218
27296
  daemon-owned processes (up) inherit the daemon's
27219
27297
  boot-time snapshot instead — see doctor.`],
27220
- ["ui", " ui ensure the daemon and open the browser (prints URL)"],
27298
+ ["ui", ` ui [--fresh] open the browser at this config's daemon (prints URL),
27299
+ starting one if none runs. A running daemon is attached
27300
+ to, even from an older build. --fresh stops it (and
27301
+ everything it runs) and starts one on this build.`],
27221
27302
  ["doctor", ` doctor [--reap] [--reap-strays [--yes] [--force]]
27222
27303
  diagnostics: ledger, capability, endpoints (each port
27223
27304
  owner marked STRAY or not), env.
@@ -27297,7 +27378,7 @@ async function withTimeout(ctx, run) {
27297
27378
  async function main() {
27298
27379
  const argv = process.argv.slice(2);
27299
27380
  if (argv[0] === "daemon") {
27300
- const { runCommanderDaemon } = await import("./main-KhpDJbPT.mjs");
27381
+ const { runCommanderDaemon } = await import("./main-C5HqmZgp.mjs");
27301
27382
  return runCommanderDaemon(argv.slice(1));
27302
27383
  }
27303
27384
  const parsed = parseCliArgs(argv);
@@ -27342,6 +27423,6 @@ main().then((code) => {
27342
27423
  process.exitCode = EXIT.failure;
27343
27424
  });
27344
27425
  //#endregion
27345
- export { serveChannel as A, loadCommanderConfigFile as B, commanderPackageVersion as C, createRealmAcceptor as D, resolveCommanderDataDir as E, validateCommanderConfig as F, readInstanceRecord as G, stopSetWithDependencies as H, effectiveEnv as I, writeInstanceRecord as J, recordDaemonAlive as K, envVarViews as L, RuntimeCoordinate as M, createMemoryStorageAdapter_json as N, createRealmServerEngine as O, wsAcceptorCarrier as P, overrideFingerprint as R, commanderRuntimeError as S, ensureStateDir as T, withDependencies as U, orderByDependency as V, savedFilterId as W, COMMANDER_LOGS_PATH as _, parseLogsClientMessage as a, COMMANDER_WS_PATH as b, identifyEndpointOwner as c, countOverrides as d, readEnvOverrides as f, COMMANDER_HEALTH_PATH as g, COMMANDER_BOOTSTRAP_PATH as h, runTaskPool as i, createDefaultServeLogger as j, httpAcceptorCarrier as k, signalStray as l, commanderControlDomain as m, readSavedFilters as n, ancestors as o, commanderChannel as p, removeInstanceRecord as q, writeSavedFilters as r, createPortInspector as s, mutateSavedFilters as t, applyEnvMutation as u, COMMANDER_TICKET_PATH as v, commanderStatePaths as w, commanderStatusRealm as x, COMMANDER_TICKET_PROTOCOL_PREFIX as y, hashCanonical as z };
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 };
27346
27427
 
27347
27428
  //# sourceMappingURL=cli.mjs.map