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