@nice-code/commander 0.92.0 → 0.94.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
  }));
@@ -23564,7 +23567,7 @@ var CommanderDaemonBootError = class extends Error {
23564
23567
  * a live dev environment, and an upgrade must never be the thing that kills one.
23565
23568
  */
23566
23569
  async function replaceSkewedDaemon(paths, skewed) {
23567
- 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" : ""})`;
23568
23571
  let liveIds = [];
23569
23572
  try {
23570
23573
  liveIds = (await openProcessLedger({
@@ -23679,6 +23682,46 @@ const COMMANDER_HEALTH_PATH = "/health";
23679
23682
  */
23680
23683
  const COMMANDER_TICKET_PROTOCOL_PREFIX = "commander-auth.";
23681
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
23682
23725
  //#region src/protocol/control.ts
23683
23726
  /**
23684
23727
  * Per-request timeout for control actions, passed as the channel's `defaultTimeout` by BOTH
@@ -23851,6 +23894,7 @@ function parseActionReport(value) {
23851
23894
  const commanderControlDomain = createActionRootDomain({ domain: "commander" }).createChildDomain({
23852
23895
  domain: "control",
23853
23896
  actions: {
23897
+ ports: actionSchema().input({ schema: handSchema(checkPortsInput) }).output({ schema: handSchema(checkPortsReport) }),
23854
23898
  start: actionSchema().input({ schema: handSchema(checkStart) }).output({ schema: handSchema(checkReport) }),
23855
23899
  stop: actionSchema().input({ schema: handSchema(checkIds) }).output({ schema: handSchema(checkReport) }),
23856
23900
  restart: actionSchema().input({ schema: handSchema(checkStart) }).output({ schema: handSchema(checkReport) }),
@@ -23900,7 +23944,7 @@ async function findDaemon(config) {
23900
23944
  async function findSkewedDaemon(config) {
23901
23945
  const skewed = await readSkewedInstanceRecord(commanderStatePaths(resolveCommanderDataDir(), config.configKey).instanceRecordPath, commanderStatusRealm.schemaHash);
23902
23946
  if (skewed == null || !pidAlive$1(skewed.pid)) return null;
23903
- 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";
23904
23948
  return {
23905
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.`,
23906
23950
  pid: skewed.pid,
@@ -23998,7 +24042,7 @@ async function connectDaemon(handle) {
23998
24042
  const payload = await (await runtime.handleActionPayload(request)).waitForResultPayload();
23999
24043
  if (!payload.result.ok) throw new CliExit(EXIT.failure, `action "${action}" rejected by the daemon`);
24000
24044
  const report = parseActionReport(payload.result.output);
24001
- 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`);
24002
24046
  return report;
24003
24047
  },
24004
24048
  setEnv: async (input) => {
@@ -24214,6 +24258,335 @@ function reportSignalShutdown(ctx, result) {
24214
24258
  }
24215
24259
  }
24216
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
24217
24590
  //#region src/daemon/envOverrides.ts
24218
24591
  const STORE_VERSION = 1;
24219
24592
  /** A knob is a port or a log level, not a payload. Bounds keep a mistake from becoming a file. */
@@ -24346,7 +24719,8 @@ async function diagnose(ctx, handle) {
24346
24719
  const report = {
24347
24720
  ok: [],
24348
24721
  warnings: [...config.warnings],
24349
- info: []
24722
+ info: [],
24723
+ listeners: []
24350
24724
  };
24351
24725
  const paths = commanderStatePaths(resolveCommanderDataDir(), config.configKey);
24352
24726
  report.info.push(handle != null ? `daemon: running (pid ${handle.record.pid}, port ${handle.record.port}, generation ${handle.record.generation})` : `daemon: not running`);
@@ -24421,6 +24795,17 @@ async function diagnose(ctx, handle) {
24421
24795
  if (ACTIVE_LIKE.has(stateById.get(proc.id) ?? "")) continue;
24422
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`));
24423
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}\``}`);
24424
24809
  return report;
24425
24810
  }
24426
24811
  const ACTIVE_LIKE = new Set([
@@ -25516,6 +25901,9 @@ commands:
25516
25901
  --reap collects a crashed daemon's orphans NOW
25517
25902
  (same reap the next boot runs; refused while a
25518
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.
25519
25907
  shutdown stop the daemon (graceful ladder)
25520
25908
 
25521
25909
  status/down/logs/doctor/shutdown never start a missing daemon — they report "not running".
@@ -25533,6 +25921,7 @@ const COMMANDS = {
25533
25921
  run: cmdRun,
25534
25922
  ui: cmdUi,
25535
25923
  doctor: cmdDoctor,
25924
+ ports: cmdPorts,
25536
25925
  shutdown: cmdShutdown
25537
25926
  };
25538
25927
  /**
@@ -25567,7 +25956,7 @@ async function withTimeout(ctx, run) {
25567
25956
  async function main() {
25568
25957
  const argv = process.argv.slice(2);
25569
25958
  if (argv[0] === "daemon") {
25570
- const { runCommanderDaemon } = await import("./main-Gp2uG70g.mjs");
25959
+ const { runCommanderDaemon } = await import("./main-BlAdEbVt.mjs");
25571
25960
  return runCommanderDaemon(argv.slice(1));
25572
25961
  }
25573
25962
  const parsed = parseCliArgs(argv);
@@ -25611,6 +26000,6 @@ main().then((code) => {
25611
26000
  process.exitCode = EXIT.failure;
25612
26001
  });
25613
26002
  //#endregion
25614
- export { envVarViews as A, serveChannel as C, createMemoryStorageAdapter_json as D, RuntimeCoordinate as E, readInstanceRecord as F, recordDaemonAlive as I, removeInstanceRecord as L, loadCommanderConfigFile as M, orderByDependency as N, validateCommanderConfig as O, withDependencies as P, writeInstanceRecord as R, wsAcceptorCarrier as S, ActionRuntime as T, ensureStateDir as _, commanderChannel as a, createRealmServerEngine as b, COMMANDER_HEALTH_PATH as c, COMMANDER_TICKET_PROTOCOL_PREFIX as d, COMMANDER_WS_PATH as f, commanderStatePaths as g, commanderPackageVersion as h, readEnvOverrides as i, overrideFingerprint as j, effectiveEnv as k, COMMANDER_LOGS_PATH as l, commanderRuntimeError 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, resolveCommanderDataDir as v, createDefaultServeLogger as w, httpAcceptorCarrier as x, createRealmAcceptor 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 };
25615
26004
 
25616
26005
  //# sourceMappingURL=cli.mjs.map