@nice-code/commander 0.92.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/README.md +35 -2
- package/build/cli.cjs +401 -11
- package/build/cli.cjs.map +1 -1
- package/build/cli.mjs +403 -14
- package/build/cli.mjs.map +1 -1
- package/build/client/assets/index-BbXO3YnY.js +23 -0
- package/build/client/assets/index-BbXO3YnY.js.map +1 -0
- package/build/client/index.html +1 -1
- package/build/{main-B_0GjEIc.cjs → main-B7EwREFQ.cjs} +8 -3
- package/build/main-B7EwREFQ.cjs.map +1 -0
- package/build/{main-Gp2uG70g.mjs → main-BlAdEbVt.mjs} +9 -4
- package/build/main-BlAdEbVt.mjs.map +1 -0
- package/package.json +7 -6
- package/build/client/assets/index-CNwEukpv.js +0 -23
- package/build/client/assets/index-CNwEukpv.js.map +0 -1
- package/build/main-B_0GjEIc.cjs.map +0 -1
- package/build/main-Gp2uG70g.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -57,8 +57,9 @@ proceed. Run `nice-commander ui` to start it again.
|
|
|
57
57
|
log marker), so `web` never starts against an API that is still compiling.
|
|
58
58
|
- **Stopping ends the tree.** Killing `npm run dev`'s pid leaves the actual server holding the
|
|
59
59
|
port; a POSIX process group / Windows Job Object does not.
|
|
60
|
-
- **
|
|
61
|
-
|
|
60
|
+
- **Starts never kill an unknown port owner.** An occupied exclusive port blocks startup.
|
|
61
|
+
Inspect its owner and explicitly confirm a stop using `ports` or the UI; automatic orphan
|
|
62
|
+
reaping remains limited to verified ledger entries.
|
|
62
63
|
- **A broken config keeps the last good one live.** Nothing restarts silently; changed processes
|
|
63
64
|
are marked stale until you restart them.
|
|
64
65
|
- **Merged logs that actually order.** The daemon stamps every line at receipt, so the timeline is
|
|
@@ -75,6 +76,38 @@ status realm. After upgrading your runtime, run `nice-commander shutdown` (this
|
|
|
75
76
|
processes), then retry, so an existing daemon is replaced too. No extra environment variables
|
|
76
77
|
are needed.
|
|
77
78
|
|
|
79
|
+
## Finding and stopping port owners
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
nice-commander doctor # includes PIDs for occupied, inactive endpoints
|
|
83
|
+
nice-commander ports # inspect all configured exclusive TCP endpoints
|
|
84
|
+
nice-commander ports journey-backend journey-web
|
|
85
|
+
nice-commander ports journey-backend --kill 12345 # review and confirm this PID
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Inspection shows each listener's PID, executable, parent PID, working directory and process-start
|
|
89
|
+
identity. It does not prove that a listener is a duplicate: another application may use the same
|
|
90
|
+
port. Command arguments and environment variables are not collected.
|
|
91
|
+
|
|
92
|
+
`--kill PID` sends SIGTERM after confirmation; `--yes` supplies explicit noninteractive consent.
|
|
93
|
+
If the listener will not stop, inspect again and use `--kill PID --force` to choose SIGKILL.
|
|
94
|
+
Only the selected listener is signalled, not its parent or process tree. A watcher may restart it;
|
|
95
|
+
inspect again to see the replacement. Multiple listeners are listed individually.
|
|
96
|
+
|
|
97
|
+
In the UI, **inspect ports** appears on inactive process rows (including failed starts), and in
|
|
98
|
+
expanded details for active rows. Review the owner, choose **stop PID** or **force kill PID**,
|
|
99
|
+
and confirm. Once the port is free, **retry start** runs the normal startup checks again.
|
|
100
|
+
|
|
101
|
+
The identity and endpoint are rechecked before termination. Inspection tokens expire after five
|
|
102
|
+
minutes and can be used once. Active configured port owners must be stopped with their ordinary
|
|
103
|
+
stop control first; Commander and its ancestors are protected. `ports` works without starting a
|
|
104
|
+
daemon, and `doctor` remains read-only unless `--reap` is explicitly requested.
|
|
105
|
+
|
|
106
|
+
Owner inspection currently supports macOS and Linux with `lsof` and `ps` available. Visibility
|
|
107
|
+
is limited by OS permissions. Remote, shared and observed endpoints are never termination
|
|
108
|
+
targets. A missing tool or unknown identity produces a diagnostic instead of authorizing a kill.
|
|
109
|
+
Windows owner inspection is not supported yet.
|
|
110
|
+
|
|
78
111
|
## Developing the web UI (`bun run dev`)
|
|
79
112
|
|
|
80
113
|
Editing the UI needs a fast loop, so the package ships a dev harness: `bun run dev` (from
|
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 ===
|
|
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"] ===
|
|
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
|
}));
|
|
@@ -23563,7 +23566,7 @@ var CommanderDaemonBootError = class extends Error {
|
|
|
23563
23566
|
* a live dev environment, and an upgrade must never be the thing that kills one.
|
|
23564
23567
|
*/
|
|
23565
23568
|
async function replaceSkewedDaemon(paths, skewed) {
|
|
23566
|
-
const daemonLabel = `the daemon for this config (pid ${skewed.pid}, build ${skewed.packageVersion}, protocol v${skewed.protocolVersion}) predates this CLI (protocol
|
|
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" : ""})`;
|
|
23567
23570
|
let liveIds = [];
|
|
23568
23571
|
try {
|
|
23569
23572
|
liveIds = (await (0, _nice_code_process.openProcessLedger)({
|
|
@@ -23678,6 +23681,46 @@ const COMMANDER_HEALTH_PATH = "/health";
|
|
|
23678
23681
|
*/
|
|
23679
23682
|
const COMMANDER_TICKET_PROTOCOL_PREFIX = "commander-auth.";
|
|
23680
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
|
|
23681
23724
|
//#region src/protocol/control.ts
|
|
23682
23725
|
/**
|
|
23683
23726
|
* Per-request timeout for control actions, passed as the channel's `defaultTimeout` by BOTH
|
|
@@ -23850,6 +23893,7 @@ function parseActionReport(value) {
|
|
|
23850
23893
|
const commanderControlDomain = createActionRootDomain({ domain: "commander" }).createChildDomain({
|
|
23851
23894
|
domain: "control",
|
|
23852
23895
|
actions: {
|
|
23896
|
+
ports: actionSchema().input({ schema: handSchema(checkPortsInput) }).output({ schema: handSchema(checkPortsReport) }),
|
|
23853
23897
|
start: actionSchema().input({ schema: handSchema(checkStart) }).output({ schema: handSchema(checkReport) }),
|
|
23854
23898
|
stop: actionSchema().input({ schema: handSchema(checkIds) }).output({ schema: handSchema(checkReport) }),
|
|
23855
23899
|
restart: actionSchema().input({ schema: handSchema(checkStart) }).output({ schema: handSchema(checkReport) }),
|
|
@@ -23899,7 +23943,7 @@ async function findDaemon(config) {
|
|
|
23899
23943
|
async function findSkewedDaemon(config) {
|
|
23900
23944
|
const skewed = await readSkewedInstanceRecord(commanderStatePaths(resolveCommanderDataDir(), config.configKey).instanceRecordPath, commanderStatusRealm.schemaHash);
|
|
23901
23945
|
if (skewed == null || !pidAlive$1(skewed.pid)) return null;
|
|
23902
|
-
const difference = skewed.skew === "protocol" ? `speaks protocol v${skewed.protocolVersion}; this build speaks
|
|
23946
|
+
const difference = skewed.skew === "protocol" ? `speaks protocol v${skewed.protocolVersion}; this build speaks v5` : "was started before an upgrade changed the status schema";
|
|
23903
23947
|
return {
|
|
23904
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.`,
|
|
23905
23949
|
pid: skewed.pid,
|
|
@@ -23997,7 +24041,7 @@ async function connectDaemon(handle) {
|
|
|
23997
24041
|
const payload = await (await runtime.handleActionPayload(request)).waitForResultPayload();
|
|
23998
24042
|
if (!payload.result.ok) throw new CliExit(EXIT.failure, `action "${action}" rejected by the daemon`);
|
|
23999
24043
|
const report = parseActionReport(payload.result.output);
|
|
24000
|
-
if (report == null) throw new CliExit(EXIT.failure, `the daemon answered "${action}" with something this CLI does not recognise — protocol ${record.protocolVersion} vs
|
|
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`);
|
|
24001
24045
|
return report;
|
|
24002
24046
|
},
|
|
24003
24047
|
setEnv: async (input) => {
|
|
@@ -24213,6 +24257,335 @@ function reportSignalShutdown(ctx, result) {
|
|
|
24213
24257
|
}
|
|
24214
24258
|
}
|
|
24215
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
|
|
24216
24589
|
//#region src/daemon/envOverrides.ts
|
|
24217
24590
|
const STORE_VERSION = 1;
|
|
24218
24591
|
/** A knob is a port or a log level, not a payload. Bounds keep a mistake from becoming a file. */
|
|
@@ -24345,7 +24718,8 @@ async function diagnose(ctx, handle) {
|
|
|
24345
24718
|
const report = {
|
|
24346
24719
|
ok: [],
|
|
24347
24720
|
warnings: [...config.warnings],
|
|
24348
|
-
info: []
|
|
24721
|
+
info: [],
|
|
24722
|
+
listeners: []
|
|
24349
24723
|
};
|
|
24350
24724
|
const paths = commanderStatePaths(resolveCommanderDataDir(), config.configKey);
|
|
24351
24725
|
report.info.push(handle != null ? `daemon: running (pid ${handle.record.pid}, port ${handle.record.port}, generation ${handle.record.generation})` : `daemon: not running`);
|
|
@@ -24420,6 +24794,17 @@ async function diagnose(ctx, handle) {
|
|
|
24420
24794
|
if (ACTIVE_LIKE.has(stateById.get(proc.id) ?? "")) continue;
|
|
24421
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`));
|
|
24422
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}\``}`);
|
|
24423
24808
|
return report;
|
|
24424
24809
|
}
|
|
24425
24810
|
const ACTIVE_LIKE = new Set([
|
|
@@ -25515,6 +25900,9 @@ commands:
|
|
|
25515
25900
|
--reap collects a crashed daemon's orphans NOW
|
|
25516
25901
|
(same reap the next boot runs; refused while a
|
|
25517
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.
|
|
25518
25906
|
shutdown stop the daemon (graceful ladder)
|
|
25519
25907
|
|
|
25520
25908
|
status/down/logs/doctor/shutdown never start a missing daemon — they report "not running".
|
|
@@ -25532,6 +25920,7 @@ const COMMANDS = {
|
|
|
25532
25920
|
run: cmdRun,
|
|
25533
25921
|
ui: cmdUi,
|
|
25534
25922
|
doctor: cmdDoctor,
|
|
25923
|
+
ports: cmdPorts,
|
|
25535
25924
|
shutdown: cmdShutdown
|
|
25536
25925
|
};
|
|
25537
25926
|
/**
|
|
@@ -25566,7 +25955,7 @@ async function withTimeout(ctx, run) {
|
|
|
25566
25955
|
async function main() {
|
|
25567
25956
|
const argv = process.argv.slice(2);
|
|
25568
25957
|
if (argv[0] === "daemon") {
|
|
25569
|
-
const { runCommanderDaemon } = await Promise.resolve().then(() => require("./main-
|
|
25958
|
+
const { runCommanderDaemon } = await Promise.resolve().then(() => require("./main-B7EwREFQ.cjs"));
|
|
25570
25959
|
return runCommanderDaemon(argv.slice(1));
|
|
25571
25960
|
}
|
|
25572
25961
|
const parsed = parseCliArgs(argv);
|
|
@@ -25628,6 +26017,7 @@ exports.commanderStatusRealm = commanderStatusRealm;
|
|
|
25628
26017
|
exports.countOverrides = countOverrides;
|
|
25629
26018
|
exports.createDefaultServeLogger = createDefaultServeLogger;
|
|
25630
26019
|
exports.createMemoryStorageAdapter_json = createMemoryStorageAdapter_json;
|
|
26020
|
+
exports.createPortInspector = createPortInspector;
|
|
25631
26021
|
exports.createRealmAcceptor = createRealmAcceptor;
|
|
25632
26022
|
exports.createRealmServerEngine = createRealmServerEngine;
|
|
25633
26023
|
exports.effectiveEnv = effectiveEnv;
|