@nice-code/commander 0.91.0 → 0.93.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,8 +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 } from "node:os";
14
- import { spawn } from "node:child_process";
13
+ import { homedir, networkInterfaces } from "node:os";
14
+ import { execFile, spawn } from "node:child_process";
15
+ import { createInterface } from "node:readline/promises";
16
+ import { lookup } from "node:dns/promises";
17
+ import { promisify } from "node:util";
15
18
  import { connect } from "node:net";
16
19
  //#region \0rolldown/runtime.js
17
20
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
@@ -31,7 +34,7 @@ const REPEATABLE_VALUE_FLAGS = new Set(["--set", "--unset"]);
31
34
  * `--no-wait="demo"` with NO positionals, which fell through to `defaultSelection` and started
32
35
  * the wrong processes with no error at all (C4). `--flag=value` is always explicit.
33
36
  */
34
- const COMMAND_VALUE_FLAGS = new Set(["--parallel"]);
37
+ const COMMAND_VALUE_FLAGS = new Set(["--parallel", "--kill"]);
35
38
  function parseCliArgs(argv) {
36
39
  const flags = /* @__PURE__ */ new Map();
37
40
  const repeated = /* @__PURE__ */ new Map();
@@ -149,7 +152,7 @@ function validStartStamp(value) {
149
152
  function isInstanceRecord(value) {
150
153
  if (value == null || typeof value !== "object" || Array.isArray(value)) return false;
151
154
  const record = value;
152
- 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 === 4;
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 === 5;
153
156
  }
154
157
  async function writeInstanceRecord(path, record) {
155
158
  await mkdir(dirname(path), {
@@ -199,7 +202,7 @@ async function readSkewedInstanceRecord(path, expectedRealmSchemaHash) {
199
202
  if (!boundedInt(record["protocolVersion"], 0, Number.MAX_SAFE_INTEGER)) return null;
200
203
  if (!boundedInt(record["pid"], 1, Number.MAX_SAFE_INTEGER)) return null;
201
204
  if (!boundedInt(record["port"], 1, 65535)) return null;
202
- const sameProtocol = record["protocolVersion"] === 4;
205
+ const sameProtocol = record["protocolVersion"] === 5;
203
206
  const sameRealm = boundedString(record["realmSchemaHash"]) && record["realmSchemaHash"] === expectedRealmSchemaHash;
204
207
  if (sameProtocol && sameRealm) return null;
205
208
  return {
@@ -2711,7 +2714,7 @@ function padding(bits, chr = "=") {
2711
2714
  /**
2712
2715
  * @__NO_SIDE_EFFECTS__
2713
2716
  */
2714
- function normalize$1(fn) {
2717
+ function normalize$2(fn) {
2715
2718
  afn(fn);
2716
2719
  return {
2717
2720
  encode: (from) => from,
@@ -2788,7 +2791,7 @@ chain(radix2(5), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), padding(5), join$
2788
2791
  chain(radix2(5), alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), join$1(""));
2789
2792
  chain(radix2(5), alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), padding(5), join$1(""));
2790
2793
  chain(radix2(5), alphabet("0123456789ABCDEFGHIJKLMNOPQRSTUV"), join$1(""));
2791
- chain(radix2(5), alphabet("0123456789ABCDEFGHJKMNPQRSTVWXYZ"), join$1(""), normalize$1((s) => s.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1")));
2794
+ chain(radix2(5), alphabet("0123456789ABCDEFGHJKMNPQRSTVWXYZ"), join$1(""), normalize$2((s) => s.toUpperCase().replace(/O/g, "0").replace(/[IL]/g, "1")));
2792
2795
  const hasBase64Builtin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toBase64 === "function" && typeof Uint8Array.fromBase64 === "function")();
2793
2796
  const ASCII_WHITESPACE = /[\t\n\f\r ]/;
2794
2797
  const decodeBase64Builtin = (s, isUrl) => {
@@ -2919,7 +2922,7 @@ function genBech32(encoding) {
2919
2922
  }
2920
2923
  genBech32("bech32");
2921
2924
  genBech32("bech32m");
2922
- /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")() || chain(radix2(4), alphabet("0123456789abcdef"), join$1(""), normalize$1((s) => {
2925
+ /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")() || chain(radix2(4), alphabet("0123456789abcdef"), join$1(""), normalize$2((s) => {
2923
2926
  if (typeof s !== "string" || s.length % 2 !== 0) throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`);
2924
2927
  return s.toLowerCase();
2925
2928
  }));
@@ -9218,6 +9221,8 @@ var AcceptorSecureSession = class {
9218
9221
  _pipe;
9219
9222
  _authed = false;
9220
9223
  _plain = false;
9224
+ _handshakeStarted = false;
9225
+ _handshakeFailed = false;
9221
9226
  /** The channel tags the client advertised in its `hello`, captured for the handler's codec selection. */
9222
9227
  _helloChannels;
9223
9228
  /** Serializes inbound processing (handshake + decryption are async). */
@@ -9231,7 +9236,19 @@ var AcceptorSecureSession = class {
9231
9236
  * acceptor and carried through here because only the decrypted frame reveals its lane.
9232
9237
  */
9233
9238
  receive(frame, wireBytes) {
9234
- this._inboundChain = this._inboundChain.then(() => this._receive(frame, wireBytes)).catch((err) => console.error("[ws-server] failed to process inbound frame", err));
9239
+ this._inboundChain = this._inboundChain.then(() => {
9240
+ if (!this._handshakeFailed) return this._receive(frame, wireBytes);
9241
+ }).catch((err) => {
9242
+ console.error("[ws-server] failed to process inbound frame", err);
9243
+ if (!this._handshakeStarted || this._authed || this._handshakeFailed) return;
9244
+ this._handshakeFailed = true;
9245
+ try {
9246
+ this.config.send(encodeHandshakeMessage({
9247
+ t: "reject",
9248
+ reason: "server handshake failed; check server logs"
9249
+ }));
9250
+ } catch {}
9251
+ });
9235
9252
  }
9236
9253
  async _receive(frame, wireBytes) {
9237
9254
  if (this._plain) {
@@ -9252,6 +9269,7 @@ var AcceptorSecureSession = class {
9252
9269
  bytes: wireBytes ?? 0,
9253
9270
  lane: "handshake"
9254
9271
  });
9272
+ this._handshakeStarted = true;
9255
9273
  await this.config.link.initialize();
9256
9274
  if (this._handshake == null) this._handshake = createServerHandshake({
9257
9275
  link: this.config.link,
@@ -23334,6 +23352,13 @@ async function commanderPackageVersion() {
23334
23352
  return cached;
23335
23353
  }
23336
23354
  //#endregion
23355
+ //#region src/daemon/runtime.ts
23356
+ /** Check before advertising a daemon whose HTTP works but whose wire handshake cannot run. */
23357
+ function commanderRuntimeError() {
23358
+ const runtime = process.versions.bun == null ? `Node ${process.version}` : `Bun ${process.versions.bun}`;
23359
+ if (process.versions.bun == null && Number(process.versions.node.split(".")[0]) < 22 || globalThis.crypto?.subtle == null || typeof globalThis.WebSocket !== "function") return `nice-commander requires Node >=22 or a current Bun with Web Crypto and WebSocket support; running ${runtime} (${process.execPath}). Upgrade Node, or run \`bunx --bun nice-commander\`. Plain \`bunx\` follows the binary's node shebang. If a daemon is already running, run \`nice-commander shutdown\` before retrying; shutdown stops its managed processes.`;
23360
+ }
23361
+ //#endregion
23337
23362
  //#region src/protocol/statusRealm.ts
23338
23363
  /**
23339
23364
  * Read-only viewer for every authenticated identity — control authority lives in the ticket
@@ -23542,7 +23567,7 @@ var CommanderDaemonBootError = class extends Error {
23542
23567
  * a live dev environment, and an upgrade must never be the thing that kills one.
23543
23568
  */
23544
23569
  async function replaceSkewedDaemon(paths, skewed) {
23545
- const daemonLabel = `the daemon for this config (pid ${skewed.pid}, build ${skewed.packageVersion}, protocol v${skewed.protocolVersion}) predates this CLI (protocol v4${skewed.skew === "realm-schema" ? ", different status schema" : ""})`;
23570
+ const daemonLabel = `the daemon for this config (pid ${skewed.pid}, build ${skewed.packageVersion}, protocol v${skewed.protocolVersion}) predates this CLI (protocol v5${skewed.skew === "realm-schema" ? ", different status schema" : ""})`;
23546
23571
  let liveIds = [];
23547
23572
  try {
23548
23573
  liveIds = (await openProcessLedger({
@@ -23567,6 +23592,8 @@ async function replaceSkewedDaemon(paths, skewed) {
23567
23592
  }
23568
23593
  }
23569
23594
  async function ensureDaemon(options) {
23595
+ const runtimeError = commanderRuntimeError();
23596
+ if (runtimeError != null) throw new Error(runtimeError);
23570
23597
  const dataDir = options.dataDir != null ? resolve(options.dataDir) : resolveCommanderDataDir();
23571
23598
  const paths = commanderStatePaths(dataDir, options.config.configKey);
23572
23599
  const timeoutMs = options.handshakeTimeoutMs ?? HANDSHAKE_TIMEOUT_MS;
@@ -23655,6 +23682,46 @@ const COMMANDER_HEALTH_PATH = "/health";
23655
23682
  */
23656
23683
  const COMMANDER_TICKET_PROTOCOL_PREFIX = "commander-auth.";
23657
23684
  //#endregion
23685
+ //#region src/protocol/ports.ts
23686
+ function checkPortsInput(value) {
23687
+ if (value == null || typeof value !== "object") return "expected an object";
23688
+ const v = { ...value };
23689
+ if (!Array.isArray(v.ids) || !v.ids.every((id) => typeof id === "string" && id.length > 0)) return "expected ids";
23690
+ if (v.token != null && (typeof v.token !== "string" || !v.token)) return "expected token";
23691
+ if (v.force != null && typeof v.force !== "boolean") return "expected force boolean";
23692
+ if (v.force && !v.token) return "force requires a listener token";
23693
+ return {
23694
+ ids: v.ids,
23695
+ ...typeof v.token === "string" ? { token: v.token } : {},
23696
+ ...typeof v.force === "boolean" ? { force: v.force } : {}
23697
+ };
23698
+ }
23699
+ function checkPortsReport(value) {
23700
+ if (value == null || typeof value !== "object") return "expected an object";
23701
+ const v = { ...value };
23702
+ if (!Array.isArray(v.warnings) || !v.warnings.every((s) => typeof s === "string") || !Array.isArray(v.listeners)) return "expected listeners and warnings";
23703
+ const listeners = [];
23704
+ for (const item of v.listeners) {
23705
+ if (item == null || typeof item !== "object") return "invalid listener";
23706
+ const r = { ...item };
23707
+ if (![
23708
+ r.id,
23709
+ r.endpoint,
23710
+ r.host,
23711
+ r.command
23712
+ ].every((s) => typeof s === "string") || !Number.isInteger(r.pid) || Number(r.pid) < 1 || !Number.isInteger(r.port) || Number(r.port) < 1 || Number(r.port) > 65535 || !(r.ppid === null || Number.isInteger(r.ppid) && Number(r.ppid) >= 0) || !(r.cwd === null || typeof r.cwd === "string") || ![
23713
+ r.startStamp,
23714
+ r.token,
23715
+ r.refusal
23716
+ ].every((s) => s === null || typeof s === "string")) return "invalid listener";
23717
+ listeners.push(item);
23718
+ }
23719
+ return {
23720
+ listeners,
23721
+ warnings: v.warnings
23722
+ };
23723
+ }
23724
+ //#endregion
23658
23725
  //#region src/protocol/control.ts
23659
23726
  /**
23660
23727
  * Per-request timeout for control actions, passed as the channel's `defaultTimeout` by BOTH
@@ -23827,6 +23894,7 @@ function parseActionReport(value) {
23827
23894
  const commanderControlDomain = createActionRootDomain({ domain: "commander" }).createChildDomain({
23828
23895
  domain: "control",
23829
23896
  actions: {
23897
+ ports: actionSchema().input({ schema: handSchema(checkPortsInput) }).output({ schema: handSchema(checkPortsReport) }),
23830
23898
  start: actionSchema().input({ schema: handSchema(checkStart) }).output({ schema: handSchema(checkReport) }),
23831
23899
  stop: actionSchema().input({ schema: handSchema(checkIds) }).output({ schema: handSchema(checkReport) }),
23832
23900
  restart: actionSchema().input({ schema: handSchema(checkStart) }).output({ schema: handSchema(checkReport) }),
@@ -23841,6 +23909,20 @@ const commanderChannel = defineChannel({
23841
23909
  toConnector: []
23842
23910
  });
23843
23911
  //#endregion
23912
+ //#region src/protocol/waitForStatusRealm.ts
23913
+ /** Retain cold-start retries, but report a failed dial instead of hiding it behind hydration. */
23914
+ async function waitForStatusRealm(connector, realm, timeoutMs) {
23915
+ let connectionError;
23916
+ connector.connect().catch((error) => {
23917
+ connectionError = error;
23918
+ });
23919
+ try {
23920
+ await realm.whenLive({ timeoutMs });
23921
+ } catch (error) {
23922
+ throw realm.attachError ?? connectionError ?? error;
23923
+ }
23924
+ }
23925
+ //#endregion
23844
23926
  //#region src/cli/daemonClient.ts
23845
23927
  /** The running daemon for this config, or null (dead record, failed ping, nothing on disk). */
23846
23928
  async function findDaemon(config) {
@@ -23862,7 +23944,7 @@ async function findDaemon(config) {
23862
23944
  async function findSkewedDaemon(config) {
23863
23945
  const skewed = await readSkewedInstanceRecord(commanderStatePaths(resolveCommanderDataDir(), config.configKey).instanceRecordPath, commanderStatusRealm.schemaHash);
23864
23946
  if (skewed == null || !pidAlive$1(skewed.pid)) return null;
23865
- const difference = skewed.skew === "protocol" ? `speaks protocol v${skewed.protocolVersion}; this build speaks v4` : "was started before an upgrade changed the status schema";
23947
+ const difference = skewed.skew === "protocol" ? `speaks protocol v${skewed.protocolVersion}; this build speaks v5` : "was started before an upgrade changed the status schema";
23866
23948
  return {
23867
23949
  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.`,
23868
23950
  pid: skewed.pid,
@@ -23907,6 +23989,8 @@ async function mintTicket(record) {
23907
23989
  return body.ticket;
23908
23990
  }
23909
23991
  async function connectDaemon(handle) {
23992
+ const runtimeError = commanderRuntimeError();
23993
+ if (runtimeError != null) throw new CliExit(EXIT.failure, runtimeError);
23910
23994
  const { record } = handle;
23911
23995
  if (record.realmSchemaHash !== commanderStatusRealm.schemaHash) throw new CliExit(EXIT.failure, `the daemon for this config (pid ${record.pid}, build ${record.packageVersion}) was started before an upgrade changed the status schema — this CLI (build ${await commanderPackageVersion()}) cannot read its state. Run \`nice-commander shutdown\` (it stops a daemon from any build), then retry.`);
23912
23996
  const ticket = await mintTicket(record);
@@ -23940,12 +24024,12 @@ async function connectDaemon(handle) {
23940
24024
  connection: realmConnection(connector),
23941
24025
  assertOnAttach: () => {}
23942
24026
  });
23943
- connector.connect().catch(() => {});
23944
24027
  try {
23945
- await realm.whenLive({ timeoutMs: 1e4 });
23946
- } catch {
24028
+ await waitForStatusRealm(connector, realm, 1e4);
24029
+ } catch (error) {
24030
+ realm.detach();
23947
24031
  connector.dispose();
23948
- const reason = realm.attachError != null ? String(realm.attachError) : "timeout";
24032
+ const reason = String(error);
23949
24033
  const hint = reason.includes("schema_mismatch") ? ` The daemon (pid ${record.pid}, build ${record.packageVersion}) and this CLI were built from different realm definitions — run \`nice-commander shutdown\` (it stops a daemon from any build), then retry.` : "";
23950
24034
  throw new CliExit(EXIT.failure, `could not attach the status realm (${reason}).${hint}`);
23951
24035
  }
@@ -23958,7 +24042,7 @@ async function connectDaemon(handle) {
23958
24042
  const payload = await (await runtime.handleActionPayload(request)).waitForResultPayload();
23959
24043
  if (!payload.result.ok) throw new CliExit(EXIT.failure, `action "${action}" rejected by the daemon`);
23960
24044
  const report = parseActionReport(payload.result.output);
23961
- if (report == null) throw new CliExit(EXIT.failure, `the daemon answered "${action}" with something this CLI does not recognise — protocol ${record.protocolVersion} vs 4`);
24045
+ if (report == null) throw new CliExit(EXIT.failure, `the daemon answered "${action}" with something this CLI does not recognise — protocol ${record.protocolVersion} vs 5`);
23962
24046
  return report;
23963
24047
  },
23964
24048
  setEnv: async (input) => {
@@ -24174,6 +24258,335 @@ function reportSignalShutdown(ctx, result) {
24174
24258
  }
24175
24259
  }
24176
24260
  //#endregion
24261
+ //#region src/ports/listeners.ts
24262
+ const exec = promisify(execFile);
24263
+ const ACTIVE = new Set([
24264
+ "starting",
24265
+ "running",
24266
+ "ready",
24267
+ "unready",
24268
+ "backoff"
24269
+ ]);
24270
+ const normalize$1 = (host) => host.replace(/^\[|\]$/g, "").replace(/^::ffff:/, "");
24271
+ /** Machine-readable lsof output: keep the address attached to its PID (multiple FDs/PIDs allowed). */
24272
+ function parseLsof(text) {
24273
+ const result = [];
24274
+ let pid = 0;
24275
+ let command = "";
24276
+ for (const line of text.split("\n")) {
24277
+ if (line.startsWith("p")) {
24278
+ pid = Number(line.slice(1));
24279
+ command = "";
24280
+ }
24281
+ if (line.startsWith("c")) command = line.slice(1);
24282
+ if (line.startsWith("n") && Number.isInteger(pid) && pid > 0) result.push({
24283
+ pid,
24284
+ command,
24285
+ address: line.slice(1)
24286
+ });
24287
+ }
24288
+ return result;
24289
+ }
24290
+ async function listeners(port) {
24291
+ if (process.platform === "win32") throw new Error("Port owner inspection requires lsof on macOS/Linux; Windows is not supported yet.");
24292
+ try {
24293
+ const { stdout } = await exec("lsof", [
24294
+ "-nP",
24295
+ `-iTCP:${port}`,
24296
+ "-sTCP:LISTEN",
24297
+ "-Fpcn"
24298
+ ], {
24299
+ timeout: 5e3,
24300
+ maxBuffer: 1024 * 1024
24301
+ });
24302
+ return parseLsof(stdout);
24303
+ } catch (error) {
24304
+ const e = error;
24305
+ if (Number(e.code) === 1 && !e.stderr?.trim()) return parseLsof(e.stdout ?? "");
24306
+ throw new Error(`Cannot inspect TCP ${port}: ${e.code === "ENOENT" ? "install lsof and retry" : e.message}`);
24307
+ }
24308
+ }
24309
+ async function localAddresses(host) {
24310
+ const local = new Set([
24311
+ "127.0.0.1",
24312
+ "::1",
24313
+ "0.0.0.0",
24314
+ "::",
24315
+ ...Object.values(networkInterfaces()).flatMap((entries) => entries?.map((e) => normalize$1(e.address)) ?? [])
24316
+ ]);
24317
+ const addresses = (await lookup(host, { all: true })).map((a) => normalize$1(a.address));
24318
+ if (!addresses.length || addresses.some((a) => !local.has(a) && !a.startsWith("127."))) throw new Error(`Endpoint host ${host} is not local; no local processes will be selected.`);
24319
+ return addresses;
24320
+ }
24321
+ function addressMatches(address, port, hosts) {
24322
+ const split = address.lastIndexOf(":");
24323
+ if (Number(address.slice(split + 1)) !== port) return false;
24324
+ const host = normalize$1(address.slice(0, split));
24325
+ return host === "*" || host === "0.0.0.0" || host === "::" || hosts.includes(host) || hosts.includes("0.0.0.0") || hosts.includes("::");
24326
+ }
24327
+ async function processDetails(pid) {
24328
+ const [ps, cwd] = await Promise.all([exec("ps", [
24329
+ "-p",
24330
+ String(pid),
24331
+ "-o",
24332
+ "ppid=",
24333
+ "-o",
24334
+ "comm="
24335
+ ], { timeout: 5e3 }).catch(() => null), exec("lsof", [
24336
+ "-a",
24337
+ "-p",
24338
+ String(pid),
24339
+ "-d",
24340
+ "cwd",
24341
+ "-Fn"
24342
+ ], { timeout: 5e3 }).catch(() => null)]);
24343
+ const match = ps?.stdout.trim().match(/^(\d+)\s+(.+)$/);
24344
+ return {
24345
+ ppid: match ? Number(match[1]) : null,
24346
+ command: match?.[2],
24347
+ cwd: cwd?.stdout.split("\n").find((l) => l.startsWith("n"))?.slice(1) ?? null
24348
+ };
24349
+ }
24350
+ async function ancestors() {
24351
+ const result = [
24352
+ 1,
24353
+ process.pid,
24354
+ process.ppid
24355
+ ];
24356
+ let pid = process.ppid;
24357
+ while (pid > 1) {
24358
+ const ps = await exec("ps", [
24359
+ "-p",
24360
+ String(pid),
24361
+ "-o",
24362
+ "ppid="
24363
+ ], { timeout: 5e3 }).catch(() => null);
24364
+ const parent = Number(ps?.stdout.trim());
24365
+ if (!Number.isInteger(parent) || parent < 1 || result.includes(parent)) break;
24366
+ result.push(parent);
24367
+ pid = parent;
24368
+ }
24369
+ return result;
24370
+ }
24371
+ /** Inspection and mutation share this service in the CLI and authenticated daemon control plane. */
24372
+ function createPortInspector(options) {
24373
+ const snapshots = /* @__PURE__ */ new Map();
24374
+ async function inspect(ids) {
24375
+ for (const [key, entry] of snapshots) if (entry.expires < Date.now()) snapshots.delete(key);
24376
+ const report = {
24377
+ listeners: [],
24378
+ warnings: []
24379
+ };
24380
+ const states = await options.states();
24381
+ const protectedPids = new Set([...await ancestors(), ...await options.protectedPids?.() ?? []]);
24382
+ const config = options.config();
24383
+ const ports = /* @__PURE__ */ new Map();
24384
+ for (const id of new Set(ids)) {
24385
+ const proc = config.processes.find((p) => p.id === id);
24386
+ if (!proc) {
24387
+ report.warnings.push(`Unknown process: ${id}`);
24388
+ continue;
24389
+ }
24390
+ for (const endpoint of proc.endpoints) {
24391
+ if (endpoint.ownership !== "exclusive") continue;
24392
+ try {
24393
+ const hosts = await localAddresses(endpoint.host);
24394
+ let found = ports.get(endpoint.port);
24395
+ if (!found) {
24396
+ found = await listeners(endpoint.port);
24397
+ ports.set(endpoint.port, found);
24398
+ }
24399
+ const seen = /* @__PURE__ */ new Set();
24400
+ for (const owner of found) {
24401
+ if (!addressMatches(owner.address, endpoint.port, hosts) || seen.has(owner.pid)) continue;
24402
+ seen.add(owner.pid);
24403
+ const stamp = await readProcessStartStamp(owner.pid);
24404
+ const details = await processDetails(owner.pid);
24405
+ const managed = config.processes.some((p) => ACTIVE.has(states.get(p.id) ?? "") && p.endpoints.some((e) => e.port === endpoint.port));
24406
+ const refusal = protectedPids.has(owner.pid) ? "Commander or its parent cannot be terminated here" : managed ? "A configured process using this port is active; use its stop control first" : stamp == null ? "Process identity is unavailable" : null;
24407
+ const listener = {
24408
+ id,
24409
+ endpoint: endpoint.name,
24410
+ host: endpoint.host,
24411
+ port: endpoint.port,
24412
+ pid: owner.pid,
24413
+ command: details.command ?? owner.command,
24414
+ ppid: details.ppid,
24415
+ cwd: details.cwd,
24416
+ startStamp: stamp?.stamp ?? null,
24417
+ refusal,
24418
+ token: refusal == null ? randomUUID() : null
24419
+ };
24420
+ if (listener.token) {
24421
+ if (snapshots.size >= 1e3) snapshots.delete(snapshots.keys().next().value);
24422
+ snapshots.set(listener.token, {
24423
+ listener,
24424
+ expires: Date.now() + 3e5
24425
+ });
24426
+ }
24427
+ report.listeners.push(listener);
24428
+ }
24429
+ } catch (error) {
24430
+ report.warnings.push(`${id}.${endpoint.name}: ${error.message}`);
24431
+ }
24432
+ }
24433
+ }
24434
+ return report;
24435
+ }
24436
+ async function run(input) {
24437
+ if (!input.token) return inspect(input.ids);
24438
+ const snapshot = snapshots.get(input.token);
24439
+ snapshots.delete(input.token);
24440
+ if (!snapshot || snapshot.expires < Date.now() || !input.ids.includes(snapshot.listener.id)) return {
24441
+ listeners: [],
24442
+ warnings: ["Inspection expired or does not match this selection. Inspect ports again."]
24443
+ };
24444
+ const target = snapshot.listener;
24445
+ const fresh = await inspect([target.id]);
24446
+ const current = fresh.listeners.find((l) => l.pid === target.pid && l.endpoint === target.endpoint && l.host === target.host && l.port === target.port && l.startStamp === target.startStamp && l.command === target.command);
24447
+ if (!current || current.refusal) return {
24448
+ listeners: fresh.listeners,
24449
+ warnings: [...fresh.warnings, current?.refusal ?? "Listener changed or exited; nothing was killed. Inspect ports again."]
24450
+ };
24451
+ try {
24452
+ const hosts = await localAddresses(target.host);
24453
+ const owners = await listeners(target.port);
24454
+ const states = await options.states();
24455
+ const config = options.config();
24456
+ const endpointStillConfigured = config.processes.find((p) => p.id === target.id)?.endpoints.some((e) => e.name === target.endpoint && e.host === target.host && e.port === target.port && e.ownership === "exclusive");
24457
+ const managed = config.processes.some((p) => ACTIVE.has(states.get(p.id) ?? "") && p.endpoints.some((e) => e.port === target.port));
24458
+ if (!endpointStillConfigured || managed || !owners.some((p) => p.pid === target.pid && addressMatches(p.address, target.port, hosts))) return {
24459
+ listeners: [],
24460
+ warnings: ["Endpoint ownership changed; nothing was killed. Inspect ports again."]
24461
+ };
24462
+ } catch (error) {
24463
+ return {
24464
+ listeners: [],
24465
+ warnings: [`Cannot verify endpoint ownership: ${error.message}`]
24466
+ };
24467
+ }
24468
+ const stamp = await readProcessStartStamp(target.pid);
24469
+ if (!stamp || stamp.stamp !== target.startStamp) return {
24470
+ listeners: [],
24471
+ warnings: ["Process identity changed; nothing was killed."]
24472
+ };
24473
+ try {
24474
+ process.kill(target.pid, input.force ? "SIGKILL" : "SIGTERM");
24475
+ } catch (error) {
24476
+ return {
24477
+ listeners: fresh.listeners,
24478
+ warnings: [`Cannot stop PID ${target.pid}: ${error.message}`]
24479
+ };
24480
+ }
24481
+ const deadline = Date.now() + 2e3;
24482
+ while (Date.now() < deadline) {
24483
+ await new Promise((resolve) => setTimeout(resolve, 100));
24484
+ const owners = await listeners(target.port).catch(() => null);
24485
+ if (owners && !owners.some((p) => p.pid === target.pid)) return inspect(input.ids);
24486
+ }
24487
+ const after = await inspect(input.ids);
24488
+ after.warnings.push(`PID ${target.pid} was signalled but has not released the port. Inspect again; force kill is a separate choice.`);
24489
+ return after;
24490
+ }
24491
+ return { run };
24492
+ }
24493
+ //#endregion
24494
+ //#region src/cli/commands/ports.ts
24495
+ async function portProcessStates(ctx) {
24496
+ const handle = await findDaemon(ctx.config);
24497
+ if (!handle) return /* @__PURE__ */ new Map();
24498
+ const client = await connectDaemon(handle);
24499
+ try {
24500
+ return new Map(Object.entries(client.state().processes).map(([id, p]) => [id, p.state]));
24501
+ } finally {
24502
+ client.dispose();
24503
+ }
24504
+ }
24505
+ async function cmdPorts(ctx) {
24506
+ const bad = unknownFlags(ctx.args.flags, [
24507
+ "--all",
24508
+ "--kill",
24509
+ "--yes",
24510
+ "--force"
24511
+ ]);
24512
+ if (bad) throw new CliExit(EXIT.usage, bad);
24513
+ const pid = numericFlag(ctx.args.flags, "--kill");
24514
+ if (pid != null && typeof pid !== "number") throw new CliExit(EXIT.usage, pid.error);
24515
+ for (const flag of [
24516
+ "--yes",
24517
+ "--force",
24518
+ "--all"
24519
+ ]) if (ctx.args.flags.has(flag) && ctx.args.flags.get(flag) !== true) throw new CliExit(EXIT.usage, `${flag} takes no value`);
24520
+ if (!pid && (ctx.args.flags.has("--force") || ctx.args.flags.has("--yes"))) throw new CliExit(EXIT.usage, "--force/--yes require --kill PID");
24521
+ const ids = ctx.args.positionals.length || ctx.args.flags.has("--all") ? selectOrExit(ctx, { bare: "required" }).direct : ctx.config.processes.map((p) => p.id);
24522
+ const inspector = createPortInspector({
24523
+ config: () => ctx.config,
24524
+ states: () => portProcessStates(ctx),
24525
+ protectedPids: async () => {
24526
+ const daemon = await findDaemon(ctx.config);
24527
+ return daemon ? [daemon.record.pid] : [];
24528
+ }
24529
+ });
24530
+ const report = await inspector.run({ ids });
24531
+ const print = (result) => {
24532
+ if (ctx.out.json) {
24533
+ ctx.out.printJson(result);
24534
+ return;
24535
+ }
24536
+ ctx.out.print(ctx.out.table([
24537
+ "PROCESS",
24538
+ "ENDPOINT",
24539
+ "PID",
24540
+ "PARENT",
24541
+ "COMMAND",
24542
+ "CWD",
24543
+ "IDENTITY",
24544
+ "STOP"
24545
+ ], result.listeners.map((l) => [
24546
+ l.id,
24547
+ `${l.host}:${l.port}`,
24548
+ String(l.pid),
24549
+ String(l.ppid ?? "unknown"),
24550
+ l.command,
24551
+ l.cwd ?? "unavailable",
24552
+ l.startStamp ?? "unknown",
24553
+ l.refusal ?? "available"
24554
+ ])));
24555
+ if (!result.listeners.length) ctx.out.print("No visible listeners on the selected exclusive TCP endpoints.");
24556
+ for (const warning of result.warnings) ctx.out.warn(warning);
24557
+ };
24558
+ if (!pid) {
24559
+ print(report);
24560
+ return report.warnings.length ? EXIT.failure : EXIT.ok;
24561
+ }
24562
+ const target = report.listeners.find((l) => l.pid === pid);
24563
+ if (!target?.token) {
24564
+ print(report);
24565
+ throw new CliExit(EXIT.failure, target?.refusal ?? `PID ${pid} is not a verified listener on the selected endpoints`);
24566
+ }
24567
+ if (!ctx.args.flags.has("--yes")) {
24568
+ print(report);
24569
+ if (!process.stdin.isTTY || ctx.out.json) throw new CliExit(EXIT.usage, "Stopping requires interactive confirmation, or --yes with --kill PID");
24570
+ const rl = createInterface({
24571
+ input: process.stdin,
24572
+ output: process.stdout
24573
+ });
24574
+ try {
24575
+ const answer = await rl.question(`${ctx.args.flags.has("--force") ? "Force kill" : "Stop"} PID ${pid} (${target.command}) on ${target.host}:${target.port}? [y/N] `);
24576
+ if (!/^y(es)?$/i.test(answer.trim())) return EXIT.ok;
24577
+ } finally {
24578
+ rl.close();
24579
+ }
24580
+ }
24581
+ const result = await inspector.run({
24582
+ ids,
24583
+ token: target.token,
24584
+ force: ctx.args.flags.has("--force")
24585
+ });
24586
+ print(result);
24587
+ return result.warnings.length ? EXIT.failure : EXIT.ok;
24588
+ }
24589
+ //#endregion
24177
24590
  //#region src/daemon/envOverrides.ts
24178
24591
  const STORE_VERSION = 1;
24179
24592
  /** A knob is a port or a log level, not a payload. Bounds keep a mistake from becoming a file. */
@@ -24306,7 +24719,8 @@ async function diagnose(ctx, handle) {
24306
24719
  const report = {
24307
24720
  ok: [],
24308
24721
  warnings: [...config.warnings],
24309
- info: []
24722
+ info: [],
24723
+ listeners: []
24310
24724
  };
24311
24725
  const paths = commanderStatePaths(resolveCommanderDataDir(), config.configKey);
24312
24726
  report.info.push(handle != null ? `daemon: running (pid ${handle.record.pid}, port ${handle.record.port}, generation ${handle.record.generation})` : `daemon: not running`);
@@ -24381,6 +24795,17 @@ async function diagnose(ctx, handle) {
24381
24795
  if (ACTIVE_LIKE.has(stateById.get(proc.id) ?? "")) continue;
24382
24796
  report.warnings.push(`endpoint ${endpoint.name} (${endpoint.host}:${endpoint.port}) on "${proc.id}" accepts connections` + (handle == null ? " while no daemon runs — held by something else" : ` while "${proc.id}" is ${stateById.get(proc.id) ?? "unknown"} — held by something else`));
24383
24797
  }
24798
+ const occupied = await createPortInspector({
24799
+ config: () => config,
24800
+ states: async () => stateById,
24801
+ protectedPids: async () => handle ? [handle.record.pid] : []
24802
+ }).run({ ids: config.processes.filter((p) => !ACTIVE_LIKE.has(stateById.get(p.id) ?? "")).map((p) => p.id) });
24803
+ report.listeners = occupied.listeners.map((l) => ({
24804
+ ...l,
24805
+ token: null
24806
+ }));
24807
+ report.warnings.push(...occupied.warnings);
24808
+ for (const owner of occupied.listeners) report.info.push(`port owner ${owner.id}.${owner.endpoint} (${owner.host}:${owner.port}): PID ${owner.pid}, ${owner.command}, identity ${owner.startStamp ?? "unknown"} — ${owner.refusal ?? `inspect/stop with \`nice-commander ports ${owner.id} --kill ${owner.pid}\``}`);
24384
24809
  return report;
24385
24810
  }
24386
24811
  const ACTIVE_LIKE = new Set([
@@ -25476,6 +25901,9 @@ commands:
25476
25901
  --reap collects a crashed daemon's orphans NOW
25477
25902
  (same reap the next boot runs; refused while a
25478
25903
  daemon is live)
25904
+ ports [sel] [--kill PID] [--force] inspect exclusive TCP port owners; selected PID stop
25905
+ prompts for confirmation (--yes for scripts).
25906
+ --force sends SIGKILL instead of SIGTERM.
25479
25907
  shutdown stop the daemon (graceful ladder)
25480
25908
 
25481
25909
  status/down/logs/doctor/shutdown never start a missing daemon — they report "not running".
@@ -25493,6 +25921,7 @@ const COMMANDS = {
25493
25921
  run: cmdRun,
25494
25922
  ui: cmdUi,
25495
25923
  doctor: cmdDoctor,
25924
+ ports: cmdPorts,
25496
25925
  shutdown: cmdShutdown
25497
25926
  };
25498
25927
  /**
@@ -25527,7 +25956,7 @@ async function withTimeout(ctx, run) {
25527
25956
  async function main() {
25528
25957
  const argv = process.argv.slice(2);
25529
25958
  if (argv[0] === "daemon") {
25530
- const { runCommanderDaemon } = await import("./main-O9jpzqPH.mjs");
25959
+ const { runCommanderDaemon } = await import("./main-BlAdEbVt.mjs");
25531
25960
  return runCommanderDaemon(argv.slice(1));
25532
25961
  }
25533
25962
  const parsed = parseCliArgs(argv);
@@ -25571,6 +26000,6 @@ main().then((code) => {
25571
26000
  process.exitCode = EXIT.failure;
25572
26001
  });
25573
26002
  //#endregion
25574
- export { overrideFingerprint as A, createDefaultServeLogger as C, validateCommanderConfig as D, createMemoryStorageAdapter_json as E, recordDaemonAlive as F, removeInstanceRecord as I, writeInstanceRecord as L, orderByDependency as M, withDependencies as N, effectiveEnv as O, readInstanceRecord as P, serveChannel as S, RuntimeCoordinate as T, resolveCommanderDataDir as _, commanderChannel as a, httpAcceptorCarrier as b, COMMANDER_HEALTH_PATH as c, COMMANDER_TICKET_PROTOCOL_PREFIX as d, COMMANDER_WS_PATH as f, ensureStateDir as g, commanderStatePaths as h, readEnvOverrides as i, loadCommanderConfigFile as j, envVarViews as k, COMMANDER_LOGS_PATH as l, commanderPackageVersion as m, applyEnvMutation as n, commanderControlDomain as o, commanderStatusRealm as p, countOverrides as r, COMMANDER_BOOTSTRAP_PATH as s, parseLogsClientMessage as t, COMMANDER_TICKET_PATH as u, createRealmAcceptor as v, ActionRuntime as w, wsAcceptorCarrier as x, createRealmServerEngine as y };
26003
+ export { effectiveEnv as A, wsAcceptorCarrier as C, RuntimeCoordinate as D, ActionRuntime as E, withDependencies as F, readInstanceRecord as I, recordDaemonAlive as L, overrideFingerprint as M, loadCommanderConfigFile as N, createMemoryStorageAdapter_json as O, orderByDependency as P, removeInstanceRecord as R, httpAcceptorCarrier as S, createDefaultServeLogger as T, commanderStatePaths as _, createPortInspector as a, createRealmAcceptor as b, COMMANDER_BOOTSTRAP_PATH as c, COMMANDER_TICKET_PATH as d, COMMANDER_TICKET_PROTOCOL_PREFIX as f, commanderPackageVersion as g, commanderRuntimeError as h, readEnvOverrides as i, envVarViews as j, validateCommanderConfig as k, COMMANDER_HEALTH_PATH as l, commanderStatusRealm as m, applyEnvMutation as n, commanderChannel as o, COMMANDER_WS_PATH as p, countOverrides as r, commanderControlDomain as s, parseLogsClientMessage as t, COMMANDER_LOGS_PATH as u, ensureStateDir as v, serveChannel as w, createRealmServerEngine as x, resolveCommanderDataDir as y, writeInstanceRecord as z };
25575
26004
 
25576
26005
  //# sourceMappingURL=cli.mjs.map