home-hosted 0.13.0 → 0.13.1
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/dist/chunks/{backup-CZcVca2a.js → backup-DeAJ3pbO.js} +6 -6
- package/dist/chunks/{backup-CZcVca2a.js.map → backup-DeAJ3pbO.js.map} +1 -1
- package/dist/chunks/{backups-CFRaWe_m.js → backups-twva7x2n.js} +3 -3
- package/dist/chunks/{backups-CFRaWe_m.js.map → backups-twva7x2n.js.map} +1 -1
- package/dist/chunks/{daemon-qKVECISl.js → daemon-CofN9k6Q.js} +3 -3
- package/dist/chunks/{daemon-qKVECISl.js.map → daemon-CofN9k6Q.js.map} +1 -1
- package/dist/chunks/{down-pKbGCW9d.js → down-C59ne5aM.js} +5 -5
- package/dist/chunks/{down-pKbGCW9d.js.map → down-C59ne5aM.js.map} +1 -1
- package/dist/chunks/{nanny-BtWfy0QH.js → nanny-COyCJXj9.js} +10 -5
- package/dist/chunks/nanny-COyCJXj9.js.map +1 -0
- package/dist/chunks/{nanny-ChMtq1Zl.js → nanny-Dnun3hVB.js} +3 -3
- package/dist/chunks/{nanny-ChMtq1Zl.js.map → nanny-Dnun3hVB.js.map} +1 -1
- package/dist/chunks/{nanny-B-Eu0sFW.js → nanny-rewguyXg.js} +2 -2
- package/dist/chunks/{nanny-B-Eu0sFW.js.map → nanny-rewguyXg.js.map} +1 -1
- package/dist/chunks/{nanny-sweep-DErnlPY1.js → nanny-sweep-ClVuNJRo.js} +3 -3
- package/dist/chunks/{nanny-sweep-DErnlPY1.js.map → nanny-sweep-ClVuNJRo.js.map} +1 -1
- package/dist/chunks/{port-B8WBTRMk.js → port-k5VBw8t9.js} +5 -2
- package/dist/chunks/{port-B8WBTRMk.js.map → port-k5VBw8t9.js.map} +1 -1
- package/dist/chunks/{restart-Des4DrAN.js → restart-BYu_E7x5.js} +5 -5
- package/dist/chunks/{restart-Des4DrAN.js.map → restart-BYu_E7x5.js.map} +1 -1
- package/dist/chunks/{server-Bge2r2qQ.js → server-By-zktjx.js} +3 -3
- package/dist/chunks/{server-Bge2r2qQ.js.map → server-By-zktjx.js.map} +1 -1
- package/dist/chunks/{set-token-obPiEJYk.js → set-token-xJkA1IZp.js} +2 -2
- package/dist/chunks/{set-token-obPiEJYk.js.map → set-token-xJkA1IZp.js.map} +1 -1
- package/dist/chunks/{src-BtWMFmzZ.js → src-BOBh9MBf.js} +9 -6
- package/dist/chunks/src-BOBh9MBf.js.map +1 -0
- package/dist/chunks/{status-DT1EsA-B.js → status-B6f2-qhs.js} +2 -2
- package/dist/chunks/{status-DT1EsA-B.js.map → status-B6f2-qhs.js.map} +1 -1
- package/dist/chunks/{up-Pdz-l6IH.js → up-DNZuTi2q.js} +4 -4
- package/dist/chunks/{up-Pdz-l6IH.js.map → up-DNZuTi2q.js.map} +1 -1
- package/dist/chunks/{usage-DFrCVXpT.js → usage-BrnDARNM.js} +2 -2
- package/dist/chunks/{usage-DFrCVXpT.js.map → usage-BrnDARNM.js.map} +1 -1
- package/dist/cli.js +11 -11
- package/package.json +1 -1
- package/uis/stock/dist/ui.json +2 -2
- package/dist/chunks/nanny-BtWfy0QH.js.map +0 -1
- package/dist/chunks/src-BtWMFmzZ.js.map +0 -1
|
@@ -10,7 +10,7 @@ var statusArgs = { json: {
|
|
|
10
10
|
description: "print machine-readable JSON"
|
|
11
11
|
} };
|
|
12
12
|
async function runStatus(json) {
|
|
13
|
-
const { configuredPanelAddress, isLiveLiveness, probeRuntime, readRuntime, runtimeLiveness } = await import("./daemon-
|
|
13
|
+
const { configuredPanelAddress, isLiveLiveness, probeRuntime, readRuntime, runtimeLiveness } = await import("./daemon-CofN9k6Q.js");
|
|
14
14
|
const { customUiInstalled, uiIdentity } = await import("./ui-dir-CsU3uLNV.js").then((n) => n.r);
|
|
15
15
|
const { hhDir: dataRoot, workspaceDir, workspacesPath } = await import("./paths-CGlGDrOU.js").then((n) => n.d);
|
|
16
16
|
const { readLastStop } = await import("./last-stop-C-BXz_XI.js").then((n) => n.t);
|
|
@@ -120,4 +120,4 @@ var statusCommand = defineCommand({
|
|
|
120
120
|
//#endregion
|
|
121
121
|
export { statusCommand };
|
|
122
122
|
|
|
123
|
-
//# sourceMappingURL=status-
|
|
123
|
+
//# sourceMappingURL=status-B6f2-qhs.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"status-DT1EsA-B.js","names":[],"sources":["../../src/cli/status.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { defineCommand } from 'citty'\nimport { bold, dim, firstRunPassword, green, invocation, paint } from '#src/cli/io'\n\n/** `status` answers \"is it running, where, and how do I reach it\". */\n\nexport const statusArgs = {\n json: { type: 'boolean', description: 'print machine-readable JSON' },\n} as const\n\nexport async function runStatus(json: boolean): Promise<void> {\n const { configuredPanelAddress, isLiveLiveness, probeRuntime, readRuntime, runtimeLiveness } = await import('#src/helpers/daemon')\n const { customUiInstalled, uiIdentity } = await import('#src/helpers/ui-dir')\n const { hhDir: dataRoot, workspaceDir, workspacesPath } = await import('#src/helpers/paths')\n const { readLastStop } = await import('#src/helpers/last-stop')\n // The per-server log directory is the **default workspace's**, and \"which one is the default\" is\n // the panel's own rule (`defaultWorkspaceId`), not the `default` id: a host that declares only\n // `[\"media\"]` writes `.hh/media/.logs/<id>.log`, and the literal path printed here named a\n // directory that never existed. Measured against a live panel of that shape, in both outputs.\n const { readDefaultWorkspaceId } = await import('#src/config/workspaces')\n const serverLogsDir = path.join(workspaceDir(readDefaultWorkspaceId(workspacesPath)), '.logs')\n const runtime = readRuntime()\n\n if (runtime === null) {\n // \"Not running\" and \"never set up\" are different answers: the first says wait or start it, the\n // second says there is nothing here yet. `workspaces.json` is what tells them apart — it is\n // written by the first successful `up`/`init`, so its absence means nothing was ever created.\n const initialised = fs.existsSync(workspacesPath)\n // \"You stopped it\" and \"it died\" both leave no record: `down` deletes the record a clean stop\n // ends, and `up` deletes the one a crash left behind. Only a deliberate stop writes\n // `.last-stop.json`, so that file is the difference — reported as a field rather than left for\n // a script to infer from which keys happen to be missing.\n const lastStop = readLastStop()\n // A record is not the machine. With `run.json` gone, this branch printed \"home-hosted is not\n // running\" while the panel on the port its own `settings.json` names answered `GET /healthz`\n // with 200 — so a `status` in a diagnostic session denied the very panel being diagnosed.\n // `down` already probes for this shape (it refuses rather than let `down && up` start a second\n // panel over a live one); the same probe answers here, and nothing is signalled — without a\n // record there is no pid this command can prove it owns, so no pid is reported either.\n const listener = await configuredPanelAddress()\n const answering = listener?.kind === 'panel' ? listener.url : null\n // Another home's panel, or anything else, on the port this home is configured for: not ours, but\n // `up` will fail on it, so it is worth saying.\n const portTaken = listener?.kind === 'other' ? listener.port : null\n if (json) {\n // `liveness` is always present, because the contract says so and a script should not have to\n // branch on whether a record exists. No `run.json` is not \"unknown\": nothing is behind the\n // pid, which is exactly `gone` — a fact, not an omission. `answering` is what tells the two\n // situations apart: a stopped panel and one still serving without its record both read\n // `running: false`, and only this field separates them.\n process.stdout.write(`${JSON.stringify({\n running: false,\n initialised,\n liveness: 'gone',\n // True only when a `down` recorded it. A crash writes no marker, so this stays false.\n exitedCleanly: lastStop !== null,\n ...(lastStop === null ? {} : { lastStopAt: lastStop.at }),\n ...(answering === null ? {} : { answeringWithoutRecord: answering }),\n ...(portTaken === null ? {} : { portTakenByOther: portTaken }),\n }, null, 2)}\\n`)\n }\n else if (answering !== null) {\n process.stdout.write(`home-hosted is not running, but this home's panel is answering on ${answering} — no run.json records which process owns it, so this cannot name or signal a pid; stop it yourself, or free that port, then run \\`${invocation()} up\\`\\n`)\n }\n else if (portTaken !== null) {\n process.stdout.write(`home-hosted is not running — its port ${portTaken} is taken by another process (another home's panel, or something else); free it or start with \\`${invocation()} up --port <port>\\`\\n`)\n }\n else if (initialised) {\n process.stdout.write(`home-hosted is not running — start it with \\`${invocation()} up\\`\\n`)\n }\n else {\n process.stdout.write(`home-hosted is not running — nothing is set up here yet; \\`${invocation()} init\\` creates a project, \\`${invocation()} up\\` starts one here\\n`)\n }\n process.exitCode = 1\n return\n }\n\n // A pid that is merely *alive* is not the panel: the OS recycles pids, so the record's own\n // `startedAt` decides whether the process behind it is still this daemon.\n const liveness = await runtimeLiveness(runtime)\n const running = isLiveLiveness(liveness)\n const probe = running ? await probeRuntime(runtime) : { reachable: false, degraded: false, servers: null }\n\n // Read once, above both outputs, so they cannot disagree about which UI is installed — the text\n // form prints it as a row and a script asking for JSON needs it just as much.\n const ui = { custom: customUiInstalled(dataRoot) }\n const uiMeta = uiIdentity(dataRoot)\n const uiLabel = ui.custom ? uiMeta.name ?? 'installed' : 'stock'\n\n if (json) {\n // The token is what authorises a local shutdown; a script only needs the rest.\n const { token: _token, ...safe } = runtime\n // `logsDir` belongs here too: the text output prints it, and a script asking for JSON needs\n // the same paths — the panel console's file is not where a *server's* log lives.\n process.stdout.write(`${JSON.stringify({\n running,\n // The reason `running` is false: a dead pid (`gone`) and one the OS recycled (`recycled`)\n // are different problems, and `answering: false` alone reads as a panel that is up but wedged.\n liveness,\n answering: probe.reachable,\n degraded: probe.degraded,\n // \"Did everything come back after the reboot\" is what `running` cannot answer: a panel up with\n // every entry stopped reads exactly like a healthy one. `null` rather than `0` when the panel\n // did not report a count, so an older panel is not shown as supervising nothing.\n servers: probe.servers,\n // A record still here whose process is not is the other half of the question: nobody stopped\n // this panel, so it died. Reported as a fact rather than inferred from a leftover `pid`.\n exitedCleanly: false,\n ...safe,\n logsDir: serverLogsDir,\n ui: { custom: ui.custom, name: uiLabel, version: uiMeta.version },\n }, null, 2)}\\n`)\n if (!running)\n process.exitCode = 1\n return\n }\n\n const uptime = formatDuration(Date.now() - runtime.startedAt)\n const state = !running\n ? liveness === 'recycled'\n // Distinct from a dead pid: the number in this record now belongs to something else, which is\n // what made `up` refuse with \"already running\" while nothing was actually serving.\n ? paint('31', 'stale (the pid belongs to another process now)')\n : paint('31', 'stale (the process is gone)')\n : probe.degraded\n ? paint('33', 'running — a server needs attention')\n : probe.reachable ? green('running') : paint('33', 'running, but not answering')\n\n const rows: Array<[string, string]> = [\n ['status', state],\n // The inventory: a reboot script's whole question is \"3 of 3 came back\". Shown only while the\n // panel is up, and `n/a` when it answered without a count rather than claiming zero entries.\n ...(running ? [['servers', serversRow(probe.servers)] as [string, string]] : []),\n ['pid', running ? `${runtime.pid} · up ${uptime}` : String(runtime.pid)],\n ['url', `${runtime.url} ${dim(`(${runtime.protocol})`)}`],\n ['version', runtime.version],\n ['project', runtime.projectDir],\n ['state', runtime.dataRoot],\n ['internal', runtime.configPath],\n ['log', runtime.logFile],\n // The per-server logs sit beside the workspace's config, not beside the console log — and\n // the README says `status` prints the paths, so the one an operator needs to read a\n // *server's* log belongs here too. The filename convention is part of the answer: knowing the\n // directory does not tell you that the entry `api` writes `api.log`, and `home-hosted logs`\n // reads the *panel's* console, not a server's, so there is otherwise no CLI hint at all.\n // Shown only when the directory exists, because naming a convention for logs never written\n // would send someone looking for a file that is not there.\n ['serverlogs', fs.existsSync(serverLogsDir) ? `${serverLogsDir} (one file per server: <id>.log)` : serverLogsDir],\n ['ui', ui.custom ? `custom — ${uiLabel} (revert with \\`${invocation()} ui-revert\\`)` : 'stock'],\n ]\n const initial = await firstRunPassword()\n if (initial !== null)\n rows.push(['password', `${paint('33', initial)} ${dim('(first-run password — change it in Global settings → Authentication)')}`])\n\n process.stdout.write(`${bold(`home-hosted ${runtime.version}`)}\\n`)\n // Width from the rows, not a literal: the column was hard-coded at 8 until a 10-character\n // label (\"serverlogs\") was added and pushed every value out of alignment.\n const width = Math.max(...rows.map(([label]) => label.length))\n for (const [label, value] of rows)\n process.stdout.write(` ${dim(label.padEnd(width))} ${value}\\n`)\n if (!running)\n process.exitCode = 1\n}\n\n/**\n * \"3 of 3 up\" — the inventory row, or `n/a` when the panel answered without a count.\n *\n * A stopped entry is not a failure (an operator stops what they do not need), so this reads as\n * neutral; the *degraded* sentence on the status row is what marks something broken.\n */\nfunction serversRow(counts: { total: number, running: number } | null): string {\n if (counts === null)\n return dim('n/a (the panel did not report a count)')\n if (counts.total === 0)\n return 'none configured'\n return counts.running === counts.total\n ? green(`${counts.running} of ${counts.total} up`)\n : `${counts.running} of ${counts.total} up`\n}\n\nfunction formatDuration(ms: number): string {\n const seconds = Math.max(0, Math.round(ms / 1000))\n if (seconds < 60)\n return `${seconds}s`\n const minutes = Math.floor(seconds / 60)\n if (minutes < 60)\n return `${minutes}m`\n const hours = Math.floor(minutes / 60)\n if (hours < 24)\n return `${hours}h ${minutes % 60}m`\n return `${Math.floor(hours / 24)}d ${hours % 24}h`\n}\n\nexport const statusCommand = defineCommand({\n meta: { name: 'status' },\n args: statusArgs,\n run: async ({ args }) => {\n await runStatus(args.json === true)\n },\n})\n"],"mappings":";;;;;;;AAQA,IAAa,aAAa,EACxB,MAAM;CAAE,MAAM;CAAW,aAAa;AAA8B,EACtE;AAEA,eAAsB,UAAU,MAA8B;CAC5D,MAAM,EAAE,wBAAwB,gBAAgB,cAAc,aAAa,oBAAoB,MAAM,OAAO;CAC5G,MAAM,EAAE,mBAAmB,eAAe,MAAM,OAAO,uBAAA,CAAA,MAAA,MAAA,EAAA,CAAA;CACvD,MAAM,EAAE,OAAO,UAAU,cAAc,mBAAmB,MAAM,OAAO,sBAAA,CAAA,MAAA,MAAA,EAAA,CAAA;CACvE,MAAM,EAAE,iBAAiB,MAAM,OAAO,0BAAA,CAAA,MAAA,MAAA,EAAA,CAAA;CAKtC,MAAM,EAAE,2BAA2B,MAAM,OAAO,2BAAA,CAAA,MAAA,MAAA,EAAA,CAAA;CAChD,MAAM,gBAAgB,KAAK,KAAK,aAAa,uBAAuB,cAAc,CAAC,GAAG,OAAO;CAC7F,MAAM,UAAU,YAAY;CAE5B,IAAI,YAAY,MAAM;EAIpB,MAAM,cAAc,GAAG,WAAW,cAAc;EAKhD,MAAM,WAAW,aAAa;EAO9B,MAAM,WAAW,MAAM,uBAAuB;EAC9C,MAAM,YAAY,UAAU,SAAS,UAAU,SAAS,MAAM;EAG9D,M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AM,CAAC;CAC7D,KAAK,MAAM,CAAC,OAAO,UAAU,MAC3B,QAAQ,OAAO,MAAM,KAAK,IAAI,MAAM,OAAO,KAAK,CAAC,EAAE,GAAG,MAAM,GAAG;CACjE,IAAI,CAAC,SACH,QAAQ,WAAW;AACvB;;;;;;;AAQA,SAAS,WAAW,QAA2D;CAC7E,IAAI,WAAW,MACb,OAAO,IAAI,wCAAwC;CACrD,IAAI,OAAO,UAAU,GACnB,OAAO;CACT,OAAO,OAAO,YAAY,OAAO,QAC7B,MAAM,GAAG,OAAO,QAAQ,MAAM,OAAO,MAAM,IAAI,IAC/C,GAAG,OAAO,QAAQ,MAAM,OAAO,MAAM;AAC3C;AAEA,SAAS,eAAe,IAAoB;CAC1C,MAAM,UAAU,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,GAAI,CAAC;CACjD,IAAI,UAAU,IACZ,OAAO,GAAG,QAAQ;CACpB,MAAM,UAAU,KAAK,MAAM,UAAU,EAAE;CACvC,IAAI,UAAU,IACZ,OAAO,GAAG,QAAQ;CACpB,MAAM,QAAQ,KAAK,MAAM,UAAU,EAAE;CACrC,IAAI,QAAQ,IACV,OAAO,GAAG,MAAM,IAAI,UAAU,GAAG;CACnC,OAAO,GAAG,KAAK,MAAM,QAAQ,EAAE,EAAE,IAAI,QAAQ,GAAG;AAClD;AAEA,IAAa,gBAAgB,cAAc;CACzC,MAAM,EAAE,MAAM,SAAS;CACvB,MAAM;CACN,KAAK,OAAO,EAAE,WAAW;EACvB,MAAM,UAAU,KAAK,SAAS,IAAI;CACpC;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"status-B6f2-qhs.js","names":[],"sources":["../../src/cli/status.ts"],"sourcesContent":["import fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { defineCommand } from 'citty'\nimport { bold, dim, firstRunPassword, green, invocation, paint } from '#src/cli/io'\n\n/** `status` answers \"is it running, where, and how do I reach it\". */\n\nexport const statusArgs = {\n json: { type: 'boolean', description: 'print machine-readable JSON' },\n} as const\n\nexport async function runStatus(json: boolean): Promise<void> {\n const { configuredPanelAddress, isLiveLiveness, probeRuntime, readRuntime, runtimeLiveness } = await import('#src/helpers/daemon')\n const { customUiInstalled, uiIdentity } = await import('#src/helpers/ui-dir')\n const { hhDir: dataRoot, workspaceDir, workspacesPath } = await import('#src/helpers/paths')\n const { readLastStop } = await import('#src/helpers/last-stop')\n // The per-server log directory is the **default workspace's**, and \"which one is the default\" is\n // the panel's own rule (`defaultWorkspaceId`), not the `default` id: a host that declares only\n // `[\"media\"]` writes `.hh/media/.logs/<id>.log`, and the literal path printed here named a\n // directory that never existed. Measured against a live panel of that shape, in both outputs.\n const { readDefaultWorkspaceId } = await import('#src/config/workspaces')\n const serverLogsDir = path.join(workspaceDir(readDefaultWorkspaceId(workspacesPath)), '.logs')\n const runtime = readRuntime()\n\n if (runtime === null) {\n // \"Not running\" and \"never set up\" are different answers: the first says wait or start it, the\n // second says there is nothing here yet. `workspaces.json` is what tells them apart — it is\n // written by the first successful `up`/`init`, so its absence means nothing was ever created.\n const initialised = fs.existsSync(workspacesPath)\n // \"You stopped it\" and \"it died\" both leave no record: `down` deletes the record a clean stop\n // ends, and `up` deletes the one a crash left behind. Only a deliberate stop writes\n // `.last-stop.json`, so that file is the difference — reported as a field rather than left for\n // a script to infer from which keys happen to be missing.\n const lastStop = readLastStop()\n // A record is not the machine. With `run.json` gone, this branch printed \"home-hosted is not\n // running\" while the panel on the port its own `settings.json` names answered `GET /healthz`\n // with 200 — so a `status` in a diagnostic session denied the very panel being diagnosed.\n // `down` already probes for this shape (it refuses rather than let `down && up` start a second\n // panel over a live one); the same probe answers here, and nothing is signalled — without a\n // record there is no pid this command can prove it owns, so no pid is reported either.\n const listener = await configuredPanelAddress()\n const answering = listener?.kind === 'panel' ? listener.url : null\n // Another home's panel, or anything else, on the port this home is configured for: not ours, but\n // `up` will fail on it, so it is worth saying.\n const portTaken = listener?.kind === 'other' ? listener.port : null\n if (json) {\n // `liveness` is always present, because the contract says so and a script should not have to\n // branch on whether a record exists. No `run.json` is not \"unknown\": nothing is behind the\n // pid, which is exactly `gone` — a fact, not an omission. `answering` is what tells the two\n // situations apart: a stopped panel and one still serving without its record both read\n // `running: false`, and only this field separates them.\n process.stdout.write(`${JSON.stringify({\n running: false,\n initialised,\n liveness: 'gone',\n // True only when a `down` recorded it. A crash writes no marker, so this stays false.\n exitedCleanly: lastStop !== null,\n ...(lastStop === null ? {} : { lastStopAt: lastStop.at }),\n ...(answering === null ? {} : { answeringWithoutRecord: answering }),\n ...(portTaken === null ? {} : { portTakenByOther: portTaken }),\n }, null, 2)}\\n`)\n }\n else if (answering !== null) {\n process.stdout.write(`home-hosted is not running, but this home's panel is answering on ${answering} — no run.json records which process owns it, so this cannot name or signal a pid; stop it yourself, or free that port, then run \\`${invocation()} up\\`\\n`)\n }\n else if (portTaken !== null) {\n process.stdout.write(`home-hosted is not running — its port ${portTaken} is taken by another process (another home's panel, or something else); free it or start with \\`${invocation()} up --port <port>\\`\\n`)\n }\n else if (initialised) {\n process.stdout.write(`home-hosted is not running — start it with \\`${invocation()} up\\`\\n`)\n }\n else {\n process.stdout.write(`home-hosted is not running — nothing is set up here yet; \\`${invocation()} init\\` creates a project, \\`${invocation()} up\\` starts one here\\n`)\n }\n process.exitCode = 1\n return\n }\n\n // A pid that is merely *alive* is not the panel: the OS recycles pids, so the record's own\n // `startedAt` decides whether the process behind it is still this daemon.\n const liveness = await runtimeLiveness(runtime)\n const running = isLiveLiveness(liveness)\n const probe = running ? await probeRuntime(runtime) : { reachable: false, degraded: false, servers: null }\n\n // Read once, above both outputs, so they cannot disagree about which UI is installed — the text\n // form prints it as a row and a script asking for JSON needs it just as much.\n const ui = { custom: customUiInstalled(dataRoot) }\n const uiMeta = uiIdentity(dataRoot)\n const uiLabel = ui.custom ? uiMeta.name ?? 'installed' : 'stock'\n\n if (json) {\n // The token is what authorises a local shutdown; a script only needs the rest.\n const { token: _token, ...safe } = runtime\n // `logsDir` belongs here too: the text output prints it, and a script asking for JSON needs\n // the same paths — the panel console's file is not where a *server's* log lives.\n process.stdout.write(`${JSON.stringify({\n running,\n // The reason `running` is false: a dead pid (`gone`) and one the OS recycled (`recycled`)\n // are different problems, and `answering: false` alone reads as a panel that is up but wedged.\n liveness,\n answering: probe.reachable,\n degraded: probe.degraded,\n // \"Did everything come back after the reboot\" is what `running` cannot answer: a panel up with\n // every entry stopped reads exactly like a healthy one. `null` rather than `0` when the panel\n // did not report a count, so an older panel is not shown as supervising nothing.\n servers: probe.servers,\n // A record still here whose process is not is the other half of the question: nobody stopped\n // this panel, so it died. Reported as a fact rather than inferred from a leftover `pid`.\n exitedCleanly: false,\n ...safe,\n logsDir: serverLogsDir,\n ui: { custom: ui.custom, name: uiLabel, version: uiMeta.version },\n }, null, 2)}\\n`)\n if (!running)\n process.exitCode = 1\n return\n }\n\n const uptime = formatDuration(Date.now() - runtime.startedAt)\n const state = !running\n ? liveness === 'recycled'\n // Distinct from a dead pid: the number in this record now belongs to something else, which is\n // what made `up` refuse with \"already running\" while nothing was actually serving.\n ? paint('31', 'stale (the pid belongs to another process now)')\n : paint('31', 'stale (the process is gone)')\n : probe.degraded\n ? paint('33', 'running — a server needs attention')\n : probe.reachable ? green('running') : paint('33', 'running, but not answering')\n\n const rows: Array<[string, string]> = [\n ['status', state],\n // The inventory: a reboot script's whole question is \"3 of 3 came back\". Shown only while the\n // panel is up, and `n/a` when it answered without a count rather than claiming zero entries.\n ...(running ? [['servers', serversRow(probe.servers)] as [string, string]] : []),\n ['pid', running ? `${runtime.pid} · up ${uptime}` : String(runtime.pid)],\n ['url', `${runtime.url} ${dim(`(${runtime.protocol})`)}`],\n ['version', runtime.version],\n ['project', runtime.projectDir],\n ['state', runtime.dataRoot],\n ['internal', runtime.configPath],\n ['log', runtime.logFile],\n // The per-server logs sit beside the workspace's config, not beside the console log — and\n // the README says `status` prints the paths, so the one an operator needs to read a\n // *server's* log belongs here too. The filename convention is part of the answer: knowing the\n // directory does not tell you that the entry `api` writes `api.log`, and `home-hosted logs`\n // reads the *panel's* console, not a server's, so there is otherwise no CLI hint at all.\n // Shown only when the directory exists, because naming a convention for logs never written\n // would send someone looking for a file that is not there.\n ['serverlogs', fs.existsSync(serverLogsDir) ? `${serverLogsDir} (one file per server: <id>.log)` : serverLogsDir],\n ['ui', ui.custom ? `custom — ${uiLabel} (revert with \\`${invocation()} ui-revert\\`)` : 'stock'],\n ]\n const initial = await firstRunPassword()\n if (initial !== null)\n rows.push(['password', `${paint('33', initial)} ${dim('(first-run password — change it in Global settings → Authentication)')}`])\n\n process.stdout.write(`${bold(`home-hosted ${runtime.version}`)}\\n`)\n // Width from the rows, not a literal: the column was hard-coded at 8 until a 10-character\n // label (\"serverlogs\") was added and pushed every value out of alignment.\n const width = Math.max(...rows.map(([label]) => label.length))\n for (const [label, value] of rows)\n process.stdout.write(` ${dim(label.padEnd(width))} ${value}\\n`)\n if (!running)\n process.exitCode = 1\n}\n\n/**\n * \"3 of 3 up\" — the inventory row, or `n/a` when the panel answered without a count.\n *\n * A stopped entry is not a failure (an operator stops what they do not need), so this reads as\n * neutral; the *degraded* sentence on the status row is what marks something broken.\n */\nfunction serversRow(counts: { total: number, running: number } | null): string {\n if (counts === null)\n return dim('n/a (the panel did not report a count)')\n if (counts.total === 0)\n return 'none configured'\n return counts.running === counts.total\n ? green(`${counts.running} of ${counts.total} up`)\n : `${counts.running} of ${counts.total} up`\n}\n\nfunction formatDuration(ms: number): string {\n const seconds = Math.max(0, Math.round(ms / 1000))\n if (seconds < 60)\n return `${seconds}s`\n const minutes = Math.floor(seconds / 60)\n if (minutes < 60)\n return `${minutes}m`\n const hours = Math.floor(minutes / 60)\n if (hours < 24)\n return `${hours}h ${minutes % 60}m`\n return `${Math.floor(hours / 24)}d ${hours % 24}h`\n}\n\nexport const statusCommand = defineCommand({\n meta: { name: 'status' },\n args: statusArgs,\n run: async ({ args }) => {\n await runStatus(args.json === true)\n },\n})\n"],"mappings":";;;;;;;AAQA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,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,GAAI,CAAC;CACjD,IAAI,UAAU,IACZ,OAAO,GAAG,QAAQ;CACpB,MAAM,UAAU,KAAK,MAAM,UAAU,EAAE;CACvC,IAAI,UAAU,IACZ,OAAO,GAAG,QAAQ;CACpB,MAAM,QAAQ,KAAK,MAAM,UAAU,EAAE;CACrC,IAAI,QAAQ,IACV,OAAO,GAAG,MAAM,IAAI,UAAU,GAAG;CACnC,OAAO,GAAG,KAAK,MAAM,QAAQ,EAAE,EAAE,IAAI,QAAQ,GAAG;AAClD;AAEA,IAAa,gBAAgB,cAAc;CACzC,MAAM,EAAE,MAAM,SAAS;CACvB,MAAM;CACN,KAAK,OAAO,EAAE,WAAW;EACvB,MAAM,UAAU,KAAK,SAAS,IAAI;CACpC;AACF,CAAC"}
|
|
@@ -102,7 +102,7 @@ function alreadyRunningConflict(flags, runtime) {
|
|
|
102
102
|
}
|
|
103
103
|
async function runUp(flags, entry) {
|
|
104
104
|
if (flags.foreground || flags.printConfig) {
|
|
105
|
-
const { runControlPlane } = await import("./src-
|
|
105
|
+
const { runControlPlane } = await import("./src-BOBh9MBf.js");
|
|
106
106
|
await runControlPlane({
|
|
107
107
|
port: flags.port,
|
|
108
108
|
host: flags.host,
|
|
@@ -112,7 +112,7 @@ async function runUp(flags, entry) {
|
|
|
112
112
|
});
|
|
113
113
|
return;
|
|
114
114
|
}
|
|
115
|
-
const { clearRuntime, readRuntime, runtimeIsAlive, runtimeIsGone } = await import("./daemon-
|
|
115
|
+
const { clearRuntime, readRuntime, runtimeIsAlive, runtimeIsGone } = await import("./daemon-CofN9k6Q.js");
|
|
116
116
|
const { daemonLogPath, dataRoot, ensureStateDir, projectDir } = await import("./paths-CGlGDrOU.js").then((n) => n.d);
|
|
117
117
|
const existing = readRuntime();
|
|
118
118
|
if (existing !== null && await runtimeIsAlive(existing)) {
|
|
@@ -185,7 +185,7 @@ async function warnIfWslTemperatureMissing() {
|
|
|
185
185
|
process.stdout.write(`${paint("33", "note")} WSL2 detected: the guest exposes no CPU temperature, so Host vitals shows n/a\n ${dim(`set it up with ${invocation()} setup-temp --wsl`)}\n`);
|
|
186
186
|
}
|
|
187
187
|
async function waitForStartup(child, timeoutMs = 2e4) {
|
|
188
|
-
const { readRuntime } = await import("./daemon-
|
|
188
|
+
const { readRuntime } = await import("./daemon-CofN9k6Q.js");
|
|
189
189
|
const deadline = Date.now() + timeoutMs;
|
|
190
190
|
for (;;) {
|
|
191
191
|
if (child.exitCode !== null || child.signalCode !== null) return null;
|
|
@@ -207,4 +207,4 @@ function upCommand(entry) {
|
|
|
207
207
|
//#endregion
|
|
208
208
|
export { checkedUpFlags, runUp, upArgs, upCommand };
|
|
209
209
|
|
|
210
|
-
//# sourceMappingURL=up-
|
|
210
|
+
//# sourceMappingURL=up-DNZuTi2q.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"up-Pdz-l6IH.js","names":[],"sources":["../../src/cli/up.ts"],"sourcesContent":["import type { ChildProcess } from 'node:child_process'\nimport type { UpFlags } from '#src/cli/args'\nimport { spawn } from 'node:child_process'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { defineCommand } from 'citty'\nimport { buildDaemonArgv } from '#src/cli/args'\nimport { bold, delay, dim, fail, firstRunPassword, green, invocation, paint } from '#src/cli/io'\nimport { rotateLog, tailLog } from '#src/helpers/daemon-log'\nimport { runtimeArgs } from '#src/helpers/runtime'\nimport { versionMismatchNote } from '#src/helpers/version'\n\n/** `up` starts the panel; without `--foreground` it re-spawns itself detached. */\n\nconst DEFAULT_PORT = 3999\n\nexport const upArgs = {\n port: { type: 'string', alias: 'p', description: `control panel port (default: ${DEFAULT_PORT})` },\n host: { type: 'string', description: 'local | lan | an ipv4 address (default: local)' },\n // No `default: true`: `toUpFlags` reads \"not given\" as on, and `restart <id>` needs `undefined`\n // to tell \"not given\" from `--no-autostart`.\n autostart: { type: 'boolean', negativeDescription: 'do not start the entries marked autostart' },\n open: { type: 'boolean', description: 'open the panel in a browser once it is up' },\n foreground: { type: 'boolean', description: 'run in this process instead of detaching (systemd/docker)' },\n printConfig: { type: 'boolean', description: 'print the effective config and exit' },\n} as const\n\ninterface RawUpArgs {\n port?: string\n host?: string\n autostart?: boolean\n open?: boolean\n foreground?: boolean\n printConfig?: boolean\n}\n\n/** citty only parses; the port's range and the boolean defaults are decided here. */\nexport function toUpFlags(args: RawUpArgs): UpFlags {\n let port: number | undefined\n if (args.port !== undefined) {\n // The whole argument must be a decimal integer. `Number.parseInt` takes a prefix, so a\n // partial parse slipped past the range check as a *valid* port: `--port 1e3` started the\n // panel on port 1 (privileged, and not what anyone typed) and `--port 8000x` on 8000.\n const raw = args.port.trim()\n port = /^\\d+$/.test(raw) ? Number.parseInt(raw, 10) : Number.NaN\n if (!Number.isInteger(port) || port <= 0 || port > 65535)\n fail(`invalid port: ${args.port}`)\n }\n\n return {\n port,\n host: args.host,\n autostart: args.autostart !== false,\n open: args.open === true,\n foreground: args.foreground === true,\n printConfig: args.printConfig === true,\n }\n}\n\n/**\n * `toUpFlags`, plus the check of `--host` that only the panel's own boot used to make.\n *\n * Async because the bind parser lives with the schemas, which a detaching `up` otherwise never\n * loads. Run before anything happens, so `up --host nope` is refused here rather than in a daemon\n * log, and `restart --host nope` before the panel is stopped.\n */\nexport async function checkedUpFlags(args: RawUpArgs): Promise<UpFlags> {\n const flags = toUpFlags(args)\n if (flags.host !== undefined) {\n const { parseBind } = await import('#src/shared/contracts')\n if (parseBind(flags.host) === null)\n fail(`invalid control host: ${flags.host} (expected local, lan or an ipv4 address)`)\n }\n return flags\n}\n\n/**\n * A bind value as the address it resolves to.\n *\n * Deliberately local and dependency-free: this module must stay importable without a state graph\n * (`test/cli/isolation`), and `helpers/bind.ts` caches `os.networkInterfaces()`, which a pure\n * comparison has no business triggering.\n */\nfunction bindAddress(bind: string): string {\n return bind === 'local' ? '127.0.0.1' : bind === 'lan' ? '0.0.0.0' : bind\n}\n\n/**\n * Which `up` flags the live panel contradicts, as one sentence — or `null` when it agrees.\n *\n * `up` on a live panel reports \"already running\" and exits 0, which is right: the common use is\n * \"make sure it is running\". But it used to swallow `--port`, `--host` and `--open` on that path,\n * so `up --port 4800` against a panel on 3999 printed a success line and exited 0 having changed\n * nothing — a deploy script reading `$?` concluded the port move worked. AGENTS.md settles the\n * direction: a flag the command cannot honour is refused, and `restart --workspace` without an id\n * already exits 1 for the same reason. `--open` is refused too, because it is not \"make sure it is\n * running\" either — it asks for a browser, and none opens on a panel this command did not start.\n *\n * `--no-autostart` is deliberately **not** here. It is not contradicted by the live panel: it\n * expresses a wish about a boot this command is not performing, and the panel has already booted,\n * so there is nothing to honour or refuse. Refusing it would break `up --no-autostart` in a retry\n * loop, which is the one spelling a script uses to keep its hands off the entries.\n */\nexport function alreadyRunningConflict(flags: UpFlags, runtime: { url: string, port: number, bindHost: string }): string | null {\n const asked: string[] = []\n if (flags.port !== undefined && flags.port !== runtime.port)\n asked.push(`--port ${flags.port}`)\n // Compared through `bindHost`, never as text: the record stores the address that was bound, so a\n // panel started with `--host lan` reads `bindHost: '0.0.0.0'` and the same flag compared raw would\n // always look unhonoured — refusing the idempotent re-run this command exists for. `--host` naming\n // the live bind is the same request as `--port` naming the live port, which is already let through.\n if (flags.host !== undefined && bindAddress(flags.host) !== runtime.bindHost)\n asked.push(`--host ${flags.host}`)\n if (flags.open)\n asked.push('--open')\n\n if (asked.length === 0)\n return null\n\n const what = asked.join(' and ')\n // \"so --port 4800 it was not honoured\" is not English: one flag reads \"was not\", several \"were\n // not\", and the flag names are the subject either way.\n const clause = asked.length === 1 ? `${what} was not honoured` : `${what} were not honoured`\n return `home-hosted is already running at ${runtime.url} — ${clause}. Stop it and start it again with those flags, or use \\`${invocation()} restart\\` to move it.`\n}\n\nexport async function runUp(flags: UpFlags, entry: string): Promise<void> {\n // `--print-config` reports the effective config and returns; it never detaches,\n // because there would be a daemon left with nothing to serve.\n if (flags.foreground || flags.printConfig) {\n // Imported here rather than at the top of the function: detaching does not need the daemon's\n // graph at all, and loading it costs ~1s of the parent's ~2.5s before the child even spawns.\n const { runControlPlane } = await import('#src/index')\n await runControlPlane({\n port: flags.port,\n host: flags.host,\n autostart: flags.autostart,\n open: flags.open,\n printConfig: flags.printConfig,\n })\n return\n }\n\n const { clearRuntime, readRuntime, runtimeIsAlive, runtimeIsGone } = await import('#src/helpers/daemon')\n const { daemonLogPath, dataRoot, ensureStateDir, projectDir } = await import('#src/helpers/paths')\n\n const existing = readRuntime()\n if (existing !== null && await runtimeIsAlive(existing)) {\n // A flag this path cannot honour is refused, and a refusal is one message on one stream: the\n // whole thing — where the panel is, which flag was dropped, what to run — goes to stderr, so\n // stdout stays empty and a script reading it does not see a success line for a move that did\n // not happen.\n const conflict = alreadyRunningConflict(flags, existing)\n if (conflict !== null)\n fail(conflict)\n\n process.stdout.write(`${green('already running')} home-hosted ${existing.version} (pid ${existing.pid}) at ${existing.url}\\n`)\n const note = versionMismatchNote(existing.version)\n if (note !== null)\n process.stdout.write(`${dim(note)}\\n`)\n // The user may have arrived via `npx`, which leaves no `home-hosted` on their PATH.\n process.stdout.write(`${dim(`stop it with \\`${invocation()} down\\``)}\\n`)\n return\n }\n // Only a record with *nothing* behind its pid is deleted. A pid that merely looks recycled is left\n // for the panel this starts to overwrite, because the birth time is wall-clock-derived on Linux and\n // a clock step can make a live panel look recycled — deleting its record would orphan it.\n if (existing !== null && await runtimeIsGone(existing))\n clearRuntime()\n\n ensureStateDir(path.dirname(daemonLogPath))\n rotateLog(daemonLogPath)\n // `0600`: the daemon's stderr lands here, and on a first boot that carries the generated password.\n // Without a mode the file is `0644` under the usual umask, so any local account could read a\n // credential the panel otherwise keeps in a 0600 file.\n const log = fs.openSync(daemonLogPath, 'a', 0o600)\n\n const child = spawn(process.execPath, [...runtimeArgs(), entry, ...buildDaemonArgv(flags)], {\n detached: true,\n cwd: projectDir,\n env: { ...process.env, HHOSTED_HOME: dataRoot, HHOSTED_PROJECT: projectDir },\n stdio: ['ignore', log, log],\n windowsHide: true,\n })\n child.unref()\n fs.closeSync(log)\n\n const runtime = await waitForStartup(child)\n if (runtime === null) {\n const output = tailLog(daemonLogPath)\n process.stderr.write(`${paint('31', 'error')} the control panel did not start\\n`)\n if (output.length > 0)\n process.stderr.write(`${dim(`${daemonLogPath}:`)}\\n${output}\\n`)\n process.exit(1)\n }\n\n process.stdout.write(`${green(`home-hosted ${runtime.version} is up`)} (pid ${runtime.pid})\\n`)\n process.stdout.write(` ${bold(runtime.url)}\\n`)\n process.stdout.write(` ${dim(`project ${runtime.projectDir}`)}\\n`)\n process.stdout.write(` ${dim(`state ${runtime.dataRoot}`)}\\n`)\n process.stdout.write(` ${dim(`log ${runtime.logFile}`)}\\n`)\n const initial = await firstRunPassword()\n if (initial !== null)\n process.stdout.write(`${paint('33', 'password')} ${bold(initial)} ${dim('— the first-run password; change it in Global settings → Authentication')}\\n`)\n await warnIfWslTemperatureMissing()\n}\n\n/**\n * Say once, on `up`, that this box cannot read its own temperature and that it can be fixed.\n *\n * A WSL2 guest has no sensor the kernel exposes, so the Host vitals tile reads `n/a` and looks\n * broken. Nothing tells a person why — the settings page has the button, but only if they go\n * looking. This is the one line that turns \"the panel is broken\" into \"run one command\".\n *\n * Silent when a command is already configured, and on any platform that is not WSL.\n */\nasync function warnIfWslTemperatureMissing(): Promise<void> {\n const { isWsl } = await import('#src/providers/wsl-temperature')\n if (!isWsl())\n return\n const { GlobalSettingsStore } = await import('#src/config/settings')\n const { globalSettingsPath } = await import('#src/helpers/paths')\n const store = new GlobalSettingsStore(globalSettingsPath)\n store.load()\n if (store.host.tempCommand.trim().length > 0)\n return\n process.stdout.write(\n `${paint('33', 'note')} WSL2 detected: the guest exposes no CPU temperature, so Host vitals shows n/a\\n`\n + ` ${dim(`set it up with ${invocation()} setup-temp --wsl`)}\\n`,\n )\n}\n\nasync function waitForStartup(child: ChildProcess, timeoutMs = 20000) {\n const { readRuntime } = await import('#src/helpers/daemon')\n const deadline = Date.now() + timeoutMs\n\n for (;;) {\n if (child.exitCode !== null || child.signalCode !== null)\n return null\n\n const runtime = readRuntime()\n if (runtime !== null && runtime.pid === child.pid)\n return runtime\n\n if (Date.now() > deadline)\n return null\n await delay(150)\n }\n}\n\nexport function upCommand(entry: string) {\n return defineCommand({\n meta: { name: 'up' },\n args: upArgs,\n run: async ({ args }) => {\n await runUp(await checkedUpFlags(args), entry)\n },\n })\n}\n"],"mappings":";;;;;;;AAiBA,IAAa,SAAS;CACpB,MAAM;EAAE,MAAM;EAAU,OAAO;EAAK,aAAa;CAAgD;CACjG,MAAM;EAAE,MAAM;EAAU,aAAa;CAAiD;CAGtF,WAAW;EAAE,MAAM;EAAW,qBAAqB;CAA4C;CAC/F,MAAM;EAAE,MAAM;EAAW,aAAa;CAA4C;CAClF,YAAY;EAAE,MAAM;EAAW,aAAa;CAA4D;CACxG,aAAa;EAAE,MAAM;EAAW,aAAa;CAAsC;AACrF;;AAYA,SAAgB,UAAU,MAA0B;CAClD,IAAI;CACJ,IAAI,KAAK,SAAS,KAAA,GAAW;EAI3B,MAAM,MAAM,KAAK,KAAK,KAAK;EAC3B,OAAO,QAAQ,KAAK,GAAG,IAAI,OAAO,SAAS,KAAK,EAAE,IAAI;EACtD,IAAI,CAAC,OAAO,UAAU,IAAI,KAAK,QAAQ,KAAK,OAAO,OACjD,KAAK,iBAAiB,KAAK,MAAM;CACrC;CAEA,OAAO;EACL;EACA,MAAM,KAAK;EACX,WAAW,KAAK,cAAc;EAC9B,MAAM,KAAK,SAAS;EACpB,YAAY,KAAK,eAAe;EAChC,aAAa,KAAK,gBAAgB;CACpC;AACF;;;;;;;;AASA,eAAsB,eAAe,MAAmC;CACtE,MAAM,QAAQ,UAAU,IAAI;CAC5B,IAAI,MAAM,SAAS,KAAA,GAAW;EAC5B,MAAM,EAAE,cAAc,MAAM,OAAO,0BAAA,CAAA,MAAA,MAAA,EAAA,CAAA;EACnC,IAAI,UAAU,MAAM,IAAI,MAAM,MAC5B,KAA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ACF;AAEA,SAAgB,UAAU,OAAe;CACvC,OAAO,cAAc;EACnB,MAAM,EAAE,MAAM,KAAK;EACnB,MAAM;EACN,KAAK,OAAO,EAAE,WAAW;GACvB,MAAM,MAAM,MAAM,eAAe,IAAI,GAAG,KAAK;EAC/C;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"up-DNZuTi2q.js","names":[],"sources":["../../src/cli/up.ts"],"sourcesContent":["import type { ChildProcess } from 'node:child_process'\nimport type { UpFlags } from '#src/cli/args'\nimport { spawn } from 'node:child_process'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { defineCommand } from 'citty'\nimport { buildDaemonArgv } from '#src/cli/args'\nimport { bold, delay, dim, fail, firstRunPassword, green, invocation, paint } from '#src/cli/io'\nimport { rotateLog, tailLog } from '#src/helpers/daemon-log'\nimport { runtimeArgs } from '#src/helpers/runtime'\nimport { versionMismatchNote } from '#src/helpers/version'\n\n/** `up` starts the panel; without `--foreground` it re-spawns itself detached. */\n\nconst DEFAULT_PORT = 3999\n\nexport const upArgs = {\n port: { type: 'string', alias: 'p', description: `control panel port (default: ${DEFAULT_PORT})` },\n host: { type: 'string', description: 'local | lan | an ipv4 address (default: local)' },\n // No `default: true`: `toUpFlags` reads \"not given\" as on, and `restart <id>` needs `undefined`\n // to tell \"not given\" from `--no-autostart`.\n autostart: { type: 'boolean', negativeDescription: 'do not start the entries marked autostart' },\n open: { type: 'boolean', description: 'open the panel in a browser once it is up' },\n foreground: { type: 'boolean', description: 'run in this process instead of detaching (systemd/docker)' },\n printConfig: { type: 'boolean', description: 'print the effective config and exit' },\n} as const\n\ninterface RawUpArgs {\n port?: string\n host?: string\n autostart?: boolean\n open?: boolean\n foreground?: boolean\n printConfig?: boolean\n}\n\n/** citty only parses; the port's range and the boolean defaults are decided here. */\nexport function toUpFlags(args: RawUpArgs): UpFlags {\n let port: number | undefined\n if (args.port !== undefined) {\n // The whole argument must be a decimal integer. `Number.parseInt` takes a prefix, so a\n // partial parse slipped past the range check as a *valid* port: `--port 1e3` started the\n // panel on port 1 (privileged, and not what anyone typed) and `--port 8000x` on 8000.\n const raw = args.port.trim()\n port = /^\\d+$/.test(raw) ? Number.parseInt(raw, 10) : Number.NaN\n if (!Number.isInteger(port) || port <= 0 || port > 65535)\n fail(`invalid port: ${args.port}`)\n }\n\n return {\n port,\n host: args.host,\n autostart: args.autostart !== false,\n open: args.open === true,\n foreground: args.foreground === true,\n printConfig: args.printConfig === true,\n }\n}\n\n/**\n * `toUpFlags`, plus the check of `--host` that only the panel's own boot used to make.\n *\n * Async because the bind parser lives with the schemas, which a detaching `up` otherwise never\n * loads. Run before anything happens, so `up --host nope` is refused here rather than in a daemon\n * log, and `restart --host nope` before the panel is stopped.\n */\nexport async function checkedUpFlags(args: RawUpArgs): Promise<UpFlags> {\n const flags = toUpFlags(args)\n if (flags.host !== undefined) {\n const { parseBind } = await import('#src/shared/contracts')\n if (parseBind(flags.host) === null)\n fail(`invalid control host: ${flags.host} (expected local, lan or an ipv4 address)`)\n }\n return flags\n}\n\n/**\n * A bind value as the address it resolves to.\n *\n * Deliberately local and dependency-free: this module must stay importable without a state graph\n * (`test/cli/isolation`), and `helpers/bind.ts` caches `os.networkInterfaces()`, which a pure\n * comparison has no business triggering.\n */\nfunction bindAddress(bind: string): string {\n return bind === 'local' ? '127.0.0.1' : bind === 'lan' ? '0.0.0.0' : bind\n}\n\n/**\n * Which `up` flags the live panel contradicts, as one sentence — or `null` when it agrees.\n *\n * `up` on a live panel reports \"already running\" and exits 0, which is right: the common use is\n * \"make sure it is running\". But it used to swallow `--port`, `--host` and `--open` on that path,\n * so `up --port 4800` against a panel on 3999 printed a success line and exited 0 having changed\n * nothing — a deploy script reading `$?` concluded the port move worked. AGENTS.md settles the\n * direction: a flag the command cannot honour is refused, and `restart --workspace` without an id\n * already exits 1 for the same reason. `--open` is refused too, because it is not \"make sure it is\n * running\" either — it asks for a browser, and none opens on a panel this command did not start.\n *\n * `--no-autostart` is deliberately **not** here. It is not contradicted by the live panel: it\n * expresses a wish about a boot this command is not performing, and the panel has already booted,\n * so there is nothing to honour or refuse. Refusing it would break `up --no-autostart` in a retry\n * loop, which is the one spelling a script uses to keep its hands off the entries.\n */\nexport function alreadyRunningConflict(flags: UpFlags, runtime: { url: string, port: number, bindHost: string }): string | null {\n const asked: string[] = []\n if (flags.port !== undefined && flags.port !== runtime.port)\n asked.push(`--port ${flags.port}`)\n // Compared through `bindHost`, never as text: the record stores the address that was bound, so a\n // panel started with `--host lan` reads `bindHost: '0.0.0.0'` and the same flag compared raw would\n // always look unhonoured — refusing the idempotent re-run this command exists for. `--host` naming\n // the live bind is the same request as `--port` naming the live port, which is already let through.\n if (flags.host !== undefined && bindAddress(flags.host) !== runtime.bindHost)\n asked.push(`--host ${flags.host}`)\n if (flags.open)\n asked.push('--open')\n\n if (asked.length === 0)\n return null\n\n const what = asked.join(' and ')\n // \"so --port 4800 it was not honoured\" is not English: one flag reads \"was not\", several \"were\n // not\", and the flag names are the subject either way.\n const clause = asked.length === 1 ? `${what} was not honoured` : `${what} were not honoured`\n return `home-hosted is already running at ${runtime.url} — ${clause}. Stop it and start it again with those flags, or use \\`${invocation()} restart\\` to move it.`\n}\n\nexport async function runUp(flags: UpFlags, entry: string): Promise<void> {\n // `--print-config` reports the effective config and returns; it never detaches,\n // because there would be a daemon left with nothing to serve.\n if (flags.foreground || flags.printConfig) {\n // Imported here rather than at the top of the function: detaching does not need the daemon's\n // graph at all, and loading it costs ~1s of the parent's ~2.5s before the child even spawns.\n const { runControlPlane } = await import('#src/index')\n await runControlPlane({\n port: flags.port,\n host: flags.host,\n autostart: flags.autostart,\n open: flags.open,\n printConfig: flags.printConfig,\n })\n return\n }\n\n const { clearRuntime, readRuntime, runtimeIsAlive, runtimeIsGone } = await import('#src/helpers/daemon')\n const { daemonLogPath, dataRoot, ensureStateDir, projectDir } = await import('#src/helpers/paths')\n\n const existing = readRuntime()\n if (existing !== null && await runtimeIsAlive(existing)) {\n // A flag this path cannot honour is refused, and a refusal is one message on one stream: the\n // whole thing — where the panel is, which flag was dropped, what to run — goes to stderr, so\n // stdout stays empty and a script reading it does not see a success line for a move that did\n // not happen.\n const conflict = alreadyRunningConflict(flags, existing)\n if (conflict !== null)\n fail(conflict)\n\n process.stdout.write(`${green('already running')} home-hosted ${existing.version} (pid ${existing.pid}) at ${existing.url}\\n`)\n const note = versionMismatchNote(existing.version)\n if (note !== null)\n process.stdout.write(`${dim(note)}\\n`)\n // The user may have arrived via `npx`, which leaves no `home-hosted` on their PATH.\n process.stdout.write(`${dim(`stop it with \\`${invocation()} down\\``)}\\n`)\n return\n }\n // Only a record with *nothing* behind its pid is deleted. A pid that merely looks recycled is left\n // for the panel this starts to overwrite, because the birth time is wall-clock-derived on Linux and\n // a clock step can make a live panel look recycled — deleting its record would orphan it.\n if (existing !== null && await runtimeIsGone(existing))\n clearRuntime()\n\n ensureStateDir(path.dirname(daemonLogPath))\n rotateLog(daemonLogPath)\n // `0600`: the daemon's stderr lands here, and on a first boot that carries the generated password.\n // Without a mode the file is `0644` under the usual umask, so any local account could read a\n // credential the panel otherwise keeps in a 0600 file.\n const log = fs.openSync(daemonLogPath, 'a', 0o600)\n\n const child = spawn(process.execPath, [...runtimeArgs(), entry, ...buildDaemonArgv(flags)], {\n detached: true,\n cwd: projectDir,\n env: { ...process.env, HHOSTED_HOME: dataRoot, HHOSTED_PROJECT: projectDir },\n stdio: ['ignore', log, log],\n windowsHide: true,\n })\n child.unref()\n fs.closeSync(log)\n\n const runtime = await waitForStartup(child)\n if (runtime === null) {\n const output = tailLog(daemonLogPath)\n process.stderr.write(`${paint('31', 'error')} the control panel did not start\\n`)\n if (output.length > 0)\n process.stderr.write(`${dim(`${daemonLogPath}:`)}\\n${output}\\n`)\n process.exit(1)\n }\n\n process.stdout.write(`${green(`home-hosted ${runtime.version} is up`)} (pid ${runtime.pid})\\n`)\n process.stdout.write(` ${bold(runtime.url)}\\n`)\n process.stdout.write(` ${dim(`project ${runtime.projectDir}`)}\\n`)\n process.stdout.write(` ${dim(`state ${runtime.dataRoot}`)}\\n`)\n process.stdout.write(` ${dim(`log ${runtime.logFile}`)}\\n`)\n const initial = await firstRunPassword()\n if (initial !== null)\n process.stdout.write(`${paint('33', 'password')} ${bold(initial)} ${dim('— the first-run password; change it in Global settings → Authentication')}\\n`)\n await warnIfWslTemperatureMissing()\n}\n\n/**\n * Say once, on `up`, that this box cannot read its own temperature and that it can be fixed.\n *\n * A WSL2 guest has no sensor the kernel exposes, so the Host vitals tile reads `n/a` and looks\n * broken. Nothing tells a person why — the settings page has the button, but only if they go\n * looking. This is the one line that turns \"the panel is broken\" into \"run one command\".\n *\n * Silent when a command is already configured, and on any platform that is not WSL.\n */\nasync function warnIfWslTemperatureMissing(): Promise<void> {\n const { isWsl } = await import('#src/providers/wsl-temperature')\n if (!isWsl())\n return\n const { GlobalSettingsStore } = await import('#src/config/settings')\n const { globalSettingsPath } = await import('#src/helpers/paths')\n const store = new GlobalSettingsStore(globalSettingsPath)\n store.load()\n if (store.host.tempCommand.trim().length > 0)\n return\n process.stdout.write(\n `${paint('33', 'note')} WSL2 detected: the guest exposes no CPU temperature, so Host vitals shows n/a\\n`\n + ` ${dim(`set it up with ${invocation()} setup-temp --wsl`)}\\n`,\n )\n}\n\nasync function waitForStartup(child: ChildProcess, timeoutMs = 20000) {\n const { readRuntime } = await import('#src/helpers/daemon')\n const deadline = Date.now() + timeoutMs\n\n for (;;) {\n if (child.exitCode !== null || child.signalCode !== null)\n return null\n\n const runtime = readRuntime()\n if (runtime !== null && runtime.pid === child.pid)\n return runtime\n\n if (Date.now() > deadline)\n return null\n await delay(150)\n }\n}\n\nexport function upCommand(entry: string) {\n return defineCommand({\n meta: { name: 'up' },\n args: upArgs,\n run: async ({ args }) => {\n await runUp(await checkedUpFlags(args), entry)\n },\n })\n}\n"],"mappings":";;;;;;;AAiBA,IAAa,SAAS;CACpB,MAAM;EAAE,MAAM;EAAU,OAAO;EAAK,aAAa;CAA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CACxJ,MAAM,4BAA4B;AACpC;;;;;;;;;;AAWA,eAAe,8BAA6C;CAC1D,MAAM,EAAE,UAAU,MAAM,OAAO,gCAAA,CAAA,MAAA,MAAA,EAAA,CAAA;CAC/B,IAAI,CAAC,MAAM,GACT;CACF,MAAM,EAAE,wBAAwB,MAAM,OAAO,yBAAA,CAAA,MAAA,MAAA,EAAA,CAAA;CAC7C,MAAM,EAAE,uBAAuB,MAAM,OAAO,sBAAA,CAAA,MAAA,MAAA,EAAA,CAAA;CAC5C,MAAM,QAAQ,IAAI,oBAAoB,kBAAkB;CACxD,MAAM,KAAK;CACX,IAAI,MAAM,KAAK,YAAY,KAAK,CAAC,CAAC,SAAS,GACzC;CACF,QAAQ,OAAO,MACb,GAAG,MAAM,MAAM,MAAM,EAAE,oFAChB,IAAI,kBAAkB,WAAW,EAAE,kBAAkB,EAAE,GAChE;AACF;AAEA,eAAe,eAAe,OAAqB,YAAY,KAAO;CACpE,MAAM,EAAE,gBAAgB,MAAM,OAAO;CACrC,MAAM,WAAW,KAAK,IAAI,IAAI;CAE9B,SAAS;EACP,IAAI,MAAM,aAAa,QAAQ,MAAM,eAAe,MAClD,OAAO;EAET,MAAM,UAAU,YAAY;EAC5B,IAAI,YAAY,QAAQ,QAAQ,QAAQ,MAAM,KAC5C,OAAO;EAET,IAAI,KAAK,IAAI,IAAI,UACf,OAAO;EACT,MAAM,MAAM,GAAG;CACjB;AACF;AAEA,SAAgB,UAAU,OAAe;CACvC,OAAO,cAAc;EACnB,MAAM,EAAE,MAAM,KAAK;EACnB,MAAM;EACN,KAAK,OAAO,EAAE,WAAW;GACvB,MAAM,MAAM,MAAM,eAAe,IAAI,GAAG,KAAK;EAC/C;CACF,CAAC;AACH"}
|
|
@@ -49,7 +49,7 @@ function toJson(body) {
|
|
|
49
49
|
};
|
|
50
50
|
}
|
|
51
51
|
async function runUsage(input) {
|
|
52
|
-
const { readRuntime, requestControl, runtimeIsAlive, runtimeIsGone, clearRuntime } = await import("./daemon-
|
|
52
|
+
const { readRuntime, requestControl, runtimeIsAlive, runtimeIsGone, clearRuntime } = await import("./daemon-CofN9k6Q.js");
|
|
53
53
|
const runtime = readRuntime();
|
|
54
54
|
if (runtime === null || !await runtimeIsAlive(runtime)) {
|
|
55
55
|
if (runtime !== null && await runtimeIsGone(runtime)) clearRuntime();
|
|
@@ -108,4 +108,4 @@ var usageCommand = defineCommand({
|
|
|
108
108
|
//#endregion
|
|
109
109
|
export { usageCommand };
|
|
110
110
|
|
|
111
|
-
//# sourceMappingURL=usage-
|
|
111
|
+
//# sourceMappingURL=usage-BrnDARNM.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"usage-
|
|
1
|
+
{"version":3,"file":"usage-BrnDARNM.js","names":[],"sources":["../../src/cli/usage.ts"],"sourcesContent":["import process from 'node:process'\nimport { defineCommand } from 'citty'\nimport { bold, dim, fail, invocation, paint } from '#src/cli/io'\nimport { errorMessage } from '#src/shared/error-message'\n\n/**\n * `usage` answers \"which of my servers is eating the machine\" without a browser.\n *\n * It reads one server's live CPU and memory from the panel it supervises, over the same local\n * token-plus-loopback channel `down` uses — no session, no API token, and no new `/api` route. An\n * entry with no sample says so instead of printing `0`, because a zero on a CPU column reads as\n * \"idle\" and hides a server nobody is measuring.\n */\n\nexport const usageArgs = {\n json: { type: 'boolean', description: 'print machine-readable JSON' },\n} as const\n\ninterface UsageEntry {\n id: string\n workspaceId: string\n label: string\n status: string\n cpuPercent?: number\n rssBytes?: number\n processes?: number\n /**\n * How many times the entry was **started** inside the panel's history window, so the first start\n * of a never-restarted server counts 1.\n *\n * The wire field is `restarts`, which is a different quantity wearing the same name: the API's\n * `server.restarts` is the crash budget spent on the current sequence (`x/maxRetries`), reset by a\n * start someone asked for. Counting starts is not that, and \"starts minus one\" is not either — it\n * undercounts the moment the window clips the first start (a server up for months, restarted twice\n * today, has 2 starts in the window and 1 real restart). So the column is named for what is\n * counted, and `starts` is read too when a newer panel sends the renamed field.\n */\n starts?: number\n /** The pre-rename spelling of `starts`, still what a current panel sends. */\n restarts?: number\n crashes?: number\n uptimeRatio?: number\n}\n\n/** Bytes as a short human figure; `MB`/`GB` with one decimal, the unit an operator reads. */\nfunction formatBytes(bytes: number): string {\n const mb = bytes / 1024 / 1024\n if (mb < 1024)\n return `${mb.toFixed(1)} MB`\n return `${(mb / 1024).toFixed(2)} GB`\n}\n\n/** One reading, or a dash — never `0` for something that was not measured. */\nfunction cell(read: number | undefined, render: (value: number) => string): string {\n return read === undefined ? dim('—') : render(read)\n}\n\n/**\n * The number of starts in the history window, from whichever spelling the panel sent.\n *\n * A panel on this release or older sends `restarts` (its route copies `ServerView.history.restarts`,\n * which counts `start` events); a panel that renames the field sends `starts`. Both are read so the\n * table is right against either, and `--json` always reports it as `starts`.\n */\nfunction startsOf(entry: UsageEntry): number | undefined {\n return entry.starts ?? entry.restarts\n}\n\n/** The `--json` document, with the count named for what it counts rather than for the wire field. */\nfunction toJson(body: { servers?: UsageEntry[], sampledAt?: number }): Record<string, unknown> {\n const servers = (body.servers ?? []).map((entry) => {\n const count = startsOf(entry)\n const renamed: Record<string, unknown> = { ...entry }\n // One spelling on stdout: the wire name would otherwise sit beside a STARTS column.\n delete renamed.restarts\n if (count !== undefined)\n renamed.starts = count\n return renamed\n })\n return { ...(body.sampledAt === undefined ? {} : { sampledAt: body.sampledAt }), servers }\n}\n\nexport async function runUsage(input: { json?: boolean }): Promise<void> {\n const { readRuntime, requestControl, runtimeIsAlive, runtimeIsGone, clearRuntime } = await import('#src/helpers/daemon')\n\n const runtime = readRuntime()\n if (runtime === null || !await runtimeIsAlive(runtime)) {\n if (runtime !== null && await runtimeIsGone(runtime))\n clearRuntime()\n fail(`home-hosted is not running — start it with \\`${invocation()} up\\``)\n }\n\n const answer = await requestControl(runtime, '/_hh/usage', 15_000, 'GET')\n if (answer === null)\n fail(`the control panel is not answering on ${runtime.probeUrl}`)\n if (answer.status !== 200)\n fail(`the panel answered ${answer.status} — it may predate this command; restart it on this release`)\n\n const body = (answer.body ?? {}) as { servers?: UsageEntry[], sampledAt?: number }\n const servers = body.servers ?? []\n\n if (input.json === true) {\n process.stdout.write(`${JSON.stringify(toJson(body), null, 2)}\\n`)\n return\n }\n\n if (servers.length === 0) {\n process.stdout.write(`${dim('no servers are configured in this panel')}\\n`)\n return\n }\n\n // Sorted loudest first: the question is \"what is eating the machine\", so the answer leads.\n const ranked = [...servers].sort((a, b) => (b.rssBytes ?? 0) - (a.rssBytes ?? 0))\n const rows = ranked.map(entry => [\n entry.workspaceId === 'default' ? entry.id : `${entry.workspaceId}/${entry.id}`,\n entry.status,\n cell(entry.cpuPercent, value => `${value.toFixed(1)}%`),\n cell(entry.rssBytes, formatBytes),\n cell(entry.processes, value => String(value)),\n // The window, not the instant: a flapping entry uses almost nothing at any sample and is\n // still the one thing on this list worth fixing. Starts as well as crashes: an entry that exits\n // and is brought back counts no crash until the panel gives up on it, so CRASH alone read 0 for\n // one restarting every minute.\n cell(startsOf(entry), value => (value === 0 ? dim('0') : String(value))),\n cell(entry.crashes, value => (value === 0 ? dim('0') : paint('31', String(value)))),\n cell(entry.uptimeRatio, value => `${Math.round(value * 100)}%`),\n ])\n\n // STARTS, not RESTARTS: the count includes the first start, and the panel's own `restarts` (the\n // crash budget, `x/maxRetries`) is a different number under the same name. See `UsageEntry.starts`.\n const headers = ['SERVER', 'STATUS', 'CPU', 'MEMORY', 'PROCS', 'STARTS', 'CRASH', 'UP']\n const widths = headers.map((header, index) =>\n Math.max(header.length, ...rows.map(row => (row[index] ?? '').length)))\n const line = (columns: string[]): string =>\n columns.map((column, index) => column.padEnd(widths[index]!)).join(' ').trimEnd()\n\n process.stdout.write(`${bold(line(headers))}\\n`)\n for (const row of rows)\n process.stdout.write(`${line(row)}\\n`)\n\n if (body.sampledAt === undefined)\n process.stdout.write(`${dim('no host sample yet — readings appear once the panel has sampled')}\\n`)\n}\n\nexport const usageCommand = defineCommand({\n meta: { name: 'usage' },\n args: usageArgs,\n async run({ args }) {\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,KAAK,QAAQ,UAAU,OAAO,OAAO,OAAO,MAAO,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,QAAQ;CAEnF,QAAQ,OAAO,MAAM,GAAG,KAAK,KAAK,OAAO,CAAC,EAAE,GAAG;CAC/C,KAAK,MAAM,OAAO,MAChB,QAAQ,OAAO,MAAM,GAAG,KAAK,GAAG,EAAE,GAAG;CAEvC,IAAI,KAAK,cAAc,KAAA,GACrB,QAAQ,OAAO,MAAM,GAAG,IAAI,iEAAiE,EAAE,GAAG;AACtG;AAEA,IAAa,eAAe,cAAc;CACxC,MAAM,EAAE,MAAM,QAAQ;CACtB,MAAM;CACN,MAAM,IAAI,EAAE,QAAQ;EAClB,IAAI;GACF,MAAM,SAAS,EAAE,MAAM,KAAK,KAAK,CAAC;EACpC,SACO,OAAO;GACZ,KAAK,aAAa,KAAK,CAAC;EAC1B;CACF;AACF,CAAC"}
|
package/dist/cli.js
CHANGED
|
@@ -808,24 +808,24 @@ function version() {
|
|
|
808
808
|
* command's `#src` modules are only evaluated once `applyDirFlags()` has run.
|
|
809
809
|
*/
|
|
810
810
|
var COMMANDS = {
|
|
811
|
-
"up": () => import("./chunks/up-
|
|
812
|
-
"down": () => import("./chunks/down-
|
|
813
|
-
"restart": () => import("./chunks/restart-
|
|
814
|
-
"status": () => import("./chunks/status-
|
|
811
|
+
"up": () => import("./chunks/up-DNZuTi2q.js").then((module) => module.upCommand(CLI_ENTRY)),
|
|
812
|
+
"down": () => import("./chunks/down-C59ne5aM.js").then((module) => module.downCommand),
|
|
813
|
+
"restart": () => import("./chunks/restart-BYu_E7x5.js").then((module) => module.restartCommand(CLI_ENTRY)),
|
|
814
|
+
"status": () => import("./chunks/status-B6f2-qhs.js").then((module) => module.statusCommand),
|
|
815
815
|
"logs": () => import("./chunks/logs---TI_bxM.js").then((module) => module.logsCommand),
|
|
816
|
-
"usage": () => import("./chunks/usage-
|
|
817
|
-
"start": () => import("./chunks/server-
|
|
818
|
-
"stop": () => import("./chunks/server-
|
|
819
|
-
"free-port": () => import("./chunks/server-
|
|
816
|
+
"usage": () => import("./chunks/usage-BrnDARNM.js").then((module) => module.usageCommand),
|
|
817
|
+
"start": () => import("./chunks/server-By-zktjx.js").then((module) => module.startCommand),
|
|
818
|
+
"stop": () => import("./chunks/server-By-zktjx.js").then((module) => module.stopCommand),
|
|
819
|
+
"free-port": () => import("./chunks/server-By-zktjx.js").then((module) => module.freePortCommand),
|
|
820
820
|
"set-password": () => import("./chunks/set-password-D5vZqqSX.js").then((module) => module.setPasswordCommand),
|
|
821
|
-
"set-token": () => import("./chunks/set-token-
|
|
821
|
+
"set-token": () => import("./chunks/set-token-xJkA1IZp.js").then((module) => module.setTokenCommand),
|
|
822
822
|
"setup-temp": () => import("./chunks/setup-temp-CAN4_bA-.js").then((module) => module.setupTempCommand),
|
|
823
823
|
"migrate": () => import("./chunks/migrate-Cfoq-Vgh.js").then((module) => module.migrateCommand),
|
|
824
824
|
"init": () => import("./chunks/init-BZ7hK9Vf.js").then((module) => module.initCommand),
|
|
825
825
|
"ui-switch": () => import("./chunks/ui-switch-BnZTdMDd.js").then((module) => module.uiSwitchCommand),
|
|
826
826
|
"ui-update": () => import("./chunks/ui-update-_xryLYxw.js").then((module) => module.uiUpdateCommand),
|
|
827
827
|
"ui-revert": () => import("./chunks/ui-revert-EkBBwRTt.js").then((module) => module.uiRevertCommand),
|
|
828
|
-
"backup": () => import("./chunks/backup-
|
|
828
|
+
"backup": () => import("./chunks/backup-DeAJ3pbO.js").then((module) => module.backupCommand)
|
|
829
829
|
};
|
|
830
830
|
var rootCommand = defineCommand({
|
|
831
831
|
meta: {
|
|
@@ -842,7 +842,7 @@ async function main() {
|
|
|
842
842
|
if (dirFlags.error !== void 0) fail(dirFlags.error);
|
|
843
843
|
applyDirFlags(dirFlags);
|
|
844
844
|
if (dirFlags.rest[0] === "__nanny") {
|
|
845
|
-
const { nannyCommand } = await import("./chunks/nanny-
|
|
845
|
+
const { nannyCommand } = await import("./chunks/nanny-Dnun3hVB.js");
|
|
846
846
|
try {
|
|
847
847
|
await runCommand(nannyCommand, { rawArgs: dirFlags.rest });
|
|
848
848
|
} catch (error) {
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "home-hosted",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.13.
|
|
4
|
+
"version": "0.13.1",
|
|
5
5
|
"packageManager": "pnpm@12.5.1",
|
|
6
6
|
"description": "Self-hosted control panel that keeps your home-server processes alive: supervision, restarts, port conflicts, logs — and a UI you can replace.",
|
|
7
7
|
"author": "NamesMT <dangquoctrung123@gmail.com>",
|
package/uis/stock/dist/ui.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"nanny-BtWfy0QH.js","names":["execFileAsync","execFileAsync"],"sources":["../../src/providers/proc.ts","../../src/providers/identity.ts","../../src/providers/process.ts","../../src/providers/nanny.ts"],"sourcesContent":["import type { ProcessResources } from '#src/shared/contracts'\nimport { execFile } from 'node:child_process'\nimport fs from 'node:fs'\nimport process from 'node:process'\nimport { promisify } from 'node:util'\n\nconst execFileAsync = promisify(execFile)\n\ninterface ProcRow {\n pid: number\n ppid: number\n rssKb: number\n /** Cumulative CPU seconds, when the platform reports it (Linux, Windows). */\n cpuSeconds?: number\n /** Instantaneous/decaying CPU percent, when the platform reports it (macOS). */\n cpuPercent?: number\n}\n\nexport function parsePsOutput(text: string): ProcRow[] {\n const rows: ProcRow[] = []\n for (const line of text.split('\\n')) {\n const parts = line.trim().split(/\\s+/)\n if (parts.length < 4)\n continue\n const [pid, ppid, rss, cpu] = parts.map(entry => Number.parseFloat(entry))\n if (pid === undefined || ppid === undefined || rss === undefined || !Number.isFinite(pid))\n continue\n rows.push({ pid, ppid, rssKb: rss, cpuPercent: Number.isFinite(cpu) ? cpu : undefined })\n }\n return rows\n}\n\n/** CSV from `Get-CimInstance ... | ConvertTo-Csv`, or wmic's `/format:csv`. */\nexport function parseWindowsCsv(text: string): ProcRow[] {\n const rows: ProcRow[] = []\n const lines = text.split(/\\r?\\n/).filter(line => line.trim().length > 0)\n const header = lines.shift()\n if (header === undefined)\n return rows\n\n const columns = header.split(',').map(entry => entry.replace(/\"/g, '').trim().toLowerCase())\n const index = (name: string): number => columns.indexOf(name.toLowerCase())\n const pidAt = index('ProcessId')\n const ppidAt = index('ParentProcessId')\n const rssAt = index('WorkingSetSize')\n const kernelAt = index('KernelModeTime')\n const userAt = index('UserModeTime')\n\n for (const line of lines) {\n const cells = line.split(',').map(entry => entry.replace(/\"/g, '').trim())\n const pid = Number.parseInt(cells[pidAt] ?? '', 10)\n if (!Number.isFinite(pid))\n continue\n\n // A missing time column must read as \"unknown\", never as zero CPU.\n const kernel = kernelAt >= 0 ? Number.parseInt(cells[kernelAt] ?? '', 10) : Number.NaN\n const user = userAt >= 0 ? Number.parseInt(cells[userAt] ?? '', 10) : Number.NaN\n const hasTimes = Number.isFinite(kernel) && Number.isFinite(user)\n\n rows.push({\n pid,\n ppid: Number.parseInt(cells[ppidAt] ?? '', 10) || 0,\n // WorkingSetSize is bytes on Windows; the sampler sums kilobytes.\n rssKb: (Number.parseInt(cells[rssAt] ?? '', 10) || 0) / 1024,\n cpuSeconds: hasTimes ? (kernel + user) / 1e7 /* 100ns units */ : undefined,\n })\n }\n\n return rows\n}\n\nlet clockTicks: number | null = null\nlet pageKb: number | null = null\n\n/** The kernel page size in kB (4 on x86, often 16 or 64 on arm64), read once. */\nasync function getPageKb(): Promise<number> {\n if (pageKb !== null)\n return pageKb\n try {\n const { stdout } = await execFileAsync('getconf', ['PAGESIZE'], { timeout: 2000 })\n const bytes = Number.parseInt(stdout.trim(), 10)\n pageKb = Number.isFinite(bytes) && bytes > 0 ? bytes / 1024 : 4\n }\n catch {\n pageKb = 4\n }\n return pageKb\n}\n\n/** Linux jiffies per second; `getconf` is POSIX, with the usual default behind it. */\nasync function getClockTicks(): Promise<number> {\n if (clockTicks !== null)\n return clockTicks\n try {\n const { stdout } = await execFileAsync('getconf', ['CLK_TCK'], { timeout: 2000 })\n const parsed = Number.parseInt(stdout.trim(), 10)\n clockTicks = Number.isFinite(parsed) && parsed > 0 ? parsed : 100\n }\n catch {\n clockTicks = 100\n }\n return clockTicks\n}\n\n/**\n * `/proc/<pid>/stat` needs care: the comm field is parenthesised and may itself\n * contain spaces or parentheses, so parsing starts after the last `)`.\n */\nfunction parseStat(pid: number, content: string, pageSizeKb = 4): ProcRow | null {\n const close = content.lastIndexOf(')')\n if (close < 0)\n return null\n const fields = content.slice(close + 2).split(' ')\n const ppid = Number.parseInt(fields[1] ?? '', 10)\n const utime = Number.parseInt(fields[11] ?? '', 10)\n const stime = Number.parseInt(fields[12] ?? '', 10)\n const rssPages = Number.parseInt(fields[21] ?? '', 10)\n\n if (!Number.isFinite(ppid) || !Number.isFinite(utime) || !Number.isFinite(stime))\n return null\n return { pid, ppid, rssKb: Number.isFinite(rssPages) ? rssPages * pageSizeKb : 0, cpuSeconds: utime + stime }\n}\n\n/** Processes read between two turns of the event loop, so a large host never stalls it. */\nconst SCAN_BATCH = 64\n\nasync function readLinux(): Promise<ProcRow[]> {\n const rows: ProcRow[] = []\n let names: string[] = []\n try {\n names = fs.readdirSync('/proc')\n }\n catch {\n return rows\n }\n\n // One read per process: `stat`'s resident page count times the real page size is VmRSS.\n const pageSizeKb = await getPageKb()\n let read = 0\n for (const name of names) {\n if (!/^\\d+$/.test(name))\n continue\n const pid = Number.parseInt(name, 10)\n try {\n const row = parseStat(pid, fs.readFileSync(`/proc/${pid}/stat`, 'utf8'), pageSizeKb)\n if (row !== null)\n rows.push(row)\n }\n catch {\n // Exited between listing and reading.\n }\n if (++read % SCAN_BATCH === 0)\n await new Promise(resolve => setImmediate(resolve))\n }\n\n return rows\n}\n\nasync function readPosix(): Promise<ProcRow[]> {\n const { stdout } = await execFileAsync('ps', ['-Ao', 'pid=,ppid=,rss=,%cpu='], { timeout: 5000, maxBuffer: 16 * 1024 * 1024 })\n return parsePsOutput(stdout)\n}\n\nasync function readWindows(): Promise<ProcRow[]> {\n const script = 'Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,WorkingSetSize,KernelModeTime,UserModeTime | ConvertTo-Csv -NoTypeInformation'\n try {\n const { stdout } = await execFileAsync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {\n timeout: 8000,\n maxBuffer: 16 * 1024 * 1024,\n })\n return parseWindowsCsv(stdout)\n }\n catch {\n try {\n const { stdout } = await execFileAsync('wmic', [\n 'process',\n 'get',\n 'ProcessId,ParentProcessId,WorkingSetSize,KernelModeTime,UserModeTime',\n '/format:csv',\n ], { timeout: 8000, maxBuffer: 16 * 1024 * 1024 })\n return parseWindowsCsv(stdout)\n }\n catch {\n // Neither tool is available; resource sampling degrades to \"unknown\".\n return []\n }\n }\n}\n\nlet scans = 0\n\n/** Test hook: how many real process-table scans have run. */\nexport function processScanCount(): number {\n return scans\n}\n\nfunction scanProcesses(): Promise<ProcRow[]> {\n scans += 1\n if (process.platform === 'linux')\n return readLinux()\n if (process.platform === 'win32')\n return readWindows()\n return readPosix()\n}\n\ninterface ProcessScan { at: number, rows: ProcRow[] }\nlet lastScan: { at: number, scan: Promise<ProcessScan> } | null = null\n\n/**\n * The process table. `reuseMs` lets a caller accept a scan that is in flight or that recent — the\n * resource samplers do, because every workspace has one and entries come due on their own second,\n * so one tick could otherwise walk `/proc` (or spawn PowerShell) once per workspace per due entry.\n * Anything deciding *ownership* passes 0: a process spawned a moment ago must be in its answer.\n */\nfunction readProcesses(now = Date.now(), reuseMs = 0): Promise<ProcessScan> {\n if (reuseMs > 0 && lastScan !== null && now - lastScan.at < reuseMs)\n return lastScan.scan\n // Stamped with when it was taken, so a sampler handed a reused scan times its CPU delta right.\n const scan = scanProcesses().then(rows => ({ at: now, rows }))\n lastScan = { at: now, scan }\n scan.catch(() => {\n if (lastScan?.scan === scan)\n lastScan = null\n })\n return scan\n}\n\n/** Test hook: the next read scans afresh. */\nexport function forgetProcessScan(): void {\n lastScan = null\n}\n\nfunction collectTree(rootPid: number, children: Map<number, number[]>): number[] {\n const pids: number[] = []\n const stack = [rootPid]\n const seen = new Set<number>()\n\n while (stack.length > 0) {\n const pid = stack.pop()!\n if (seen.has(pid))\n continue\n seen.add(pid)\n pids.push(pid)\n for (const child of children.get(pid) ?? []) stack.push(child)\n }\n\n return pids\n}\n\n/**\n * CPU time a tree used over one interval, from per-pid cumulative counters.\n *\n * Pure, and separated from the scan because this is where both CPU bugs lived — and a scan of the\n * live process table cannot pin arithmetic that depends on a child appearing or vanishing between\n * two reads.\n *\n * `previous` is the **whole process table** of the prior scan, not just this tree: that is what\n * lets a process which joins the tree later be charged only its interval, and what the caller\n * guarantees.\n *\n * Three rules make the answer a real interval:\n *\n * - A pid in both maps contributes the difference. `next >= previous` is required: a recycled pid\n * reports less than the process that used to hold it, and that is not a delta.\n * - A pid only in `next` was **born inside the window**, so its whole counter accrued in it.\n * - A pid only in `previous` **exited inside the window**; its time is already accounted for by the\n * samples where it was alive, and it contributes nothing. The old code summed the tree on both\n * sides, so an exit made the total *drop*, the delta went negative and the reading was discarded\n * — the gap. Summing only pids present in `next` is what removes it.\n *\n * `null` when the map has nothing usable, so a caller reports \"unknown\" instead of `0`.\n */\nexport function treeCpuUsedSeconds(\n previous: Map<number, number>,\n next: Map<number, number>,\n treePids: number[],\n): number | null {\n let used = 0\n let sawAny = false\n for (const pid of treePids) {\n const current = next.get(pid)\n if (current === undefined)\n continue\n const before = previous.get(pid)\n if (before === undefined) {\n used += current\n sawAny = true\n continue\n }\n if (current >= before) {\n used += current - before\n sawAny = true\n }\n }\n return sawAny ? used : null\n}\n\n/**\n * The same walk, keeping *which root* each pid belongs to.\n *\n * A refusal has to name the server to go and stop, and a pid on its own is not that: the panel\n * supervised 14 entries and told the operator \"held by pid 135113, which this panel supervises —\n * stop that server instead\", with no way to tell which of the 14 it meant. The tree loses that\n * fact, so the attribution is collected here, where the walk already happens, rather than by a\n * second scan.\n *\n * Ownership has to mean the *tree*: a persistent entry runs under a nanny, and a wrapper entry\n * spawns the real server one generation down. Both keep the pid the panel recorded, but the process\n * holding the port is a descendant of it — and a descendant classified as a stranger is one\n * `kill`/`free-port` away from stopping a server this panel is responsible for.\n *\n * A backend that cannot run answers with the roots alone, which is the old, narrower behaviour\n * rather than a wrong one.\n *\n * When two roots are nested, the ancestor keeps the pid: it is the older claim and still true.\n */\nexport async function processTreeOwners(roots: number[]): Promise<Map<number, number>> {\n const owners = new Map<number, number>()\n for (const root of roots) {\n if (!owners.has(root))\n owners.set(root, root)\n }\n if (roots.length === 0)\n return owners\n\n try {\n const { rows } = await readProcesses()\n const children = new Map<number, number[]>()\n for (const row of rows) {\n const siblings = children.get(row.ppid) ?? []\n siblings.push(row.pid)\n children.set(row.ppid, siblings)\n }\n for (const root of roots) {\n for (const pid of collectTree(root, children)) {\n if (!owners.has(pid))\n owners.set(pid, root)\n }\n }\n }\n catch {\n // Sampling already treats an unreadable table as \"nothing to say\".\n }\n\n return owners\n}\n\n/**\n * Samples CPU and RSS for a process *and its descendants*.\n *\n * Descendants matter: a wrapper that spawns the real server detached owns the\n * tree, and only the tree's RSS means anything.\n *\n * Backends: `/proc` on Linux, `ps` on macOS/other POSIX, and Win32_Process via\n * PowerShell (wmic as a fallback) on Windows. When a backend cannot run, samples\n * are null rather than wrong.\n */\nexport class ProcessSampler {\n /** `reuseMs`: accept a process scan this recent from any sampler (0 = always scan fresh). */\n constructor(private readonly reuseMs = 0) {}\n\n /**\n * Cumulative CPU seconds per pid, from the **whole process table** of the last scan.\n *\n * A tree is not a fixed set of processes: a wrapper spawns and reaps children continuously, so\n * \"the sum over whatever is in the tree now\" is not comparable with the previous sum. Measuring\n * that rule against a wrapper respawning a 1.5 s worker, **two samples in every three were\n * discarded**: the child's exit made the sum drop, the delta went negative, and the reading was\n * thrown away — the gaps a person sees on a live server.\n *\n * Baselining every pid the scan saw, rather than only the tree's, is what makes each delta a\n * real interval. A process that was already running has a previous counter even if it only\n * joined this tree afterwards, so it cannot be charged its whole lifetime; and a pid absent from\n * the previous scan was born inside the window, so its counter really did accrue in it.\n */\n private previousTable: { at: number, cpuSeconds: Map<number, number> } | null = null\n\n /**\n * Roots whose next sample must not be differenced, stamped with when they were forgotten.\n *\n * `forget` is called when an entry stops, exits or is restarted: the pid is gone, so the reading\n * after it must be `null` rather than a delta against a previous life. The baseline is one table\n * for the whole scan, so this is the per-root suppression. Pruned at each scan, which bounds it\n * to the restarts that happened since the last one.\n */\n private readonly forgotten = new Map<number, number>()\n\n /** Each root's latest reading, answered again when the only scan available is one already used. */\n private readonly lastReadings = new Map<number, ProcessResources>()\n\n async sample(rootPid: number, now = Date.now()): Promise<ProcessResources | null> {\n const samples = await this.sampleMany([rootPid], now)\n return samples.get(rootPid) ?? null\n }\n\n async sampleMany(rootPids: number[], now = Date.now()): Promise<Map<number, ProcessResources | null>> {\n const results = new Map<number, ProcessResources | null>()\n if (rootPids.length === 0)\n return results\n\n let rows: ProcRow[] = []\n let scannedAt = now\n try {\n const scan = await readProcesses(now, this.reuseMs)\n rows = scan.rows\n scannedAt = scan.at\n }\n catch {\n rows = []\n }\n\n // The same scan this sampler already differenced: a second delta would be zero, not a reading.\n if (this.previousTable !== null && this.previousTable.at === scannedAt && rows.length > 0) {\n for (const rootPid of rootPids)\n results.set(rootPid, this.lastReadings.get(rootPid) ?? null)\n return results\n }\n\n const byPid = new Map(rows.map(row => [row.pid, row]))\n const children = new Map<number, number[]>()\n for (const row of rows) {\n const siblings = children.get(row.ppid) ?? []\n siblings.push(row.pid)\n children.set(row.ppid, siblings)\n }\n\n // One baseline for the scan, shared by every root: they were all read at the same instant.\n const before = this.previousTable\n const elapsedSeconds = before === null ? 0 : (scannedAt - before.at) / 1000\n const ticks = process.platform === 'linux' ? await getClockTicks() : 1\n // Stored in *seconds*, the unit the comparison uses. Keeping raw jiffies here made every\n // Linux delta compare `seconds` against `jiffies`, so each one looked negative and was skipped.\n const tableCpuSeconds = new Map<number, number>()\n for (const row of rows) {\n if (row.cpuSeconds !== undefined)\n tableCpuSeconds.set(row.pid, row.cpuSeconds / ticks)\n }\n\n for (const rootPid of rootPids) {\n if (!byPid.has(rootPid)) {\n results.set(rootPid, null)\n continue\n }\n\n // A root forgotten since the last scan has no baseline to be measured against: its next\n // reading is the first of a new life, so it reports \"no window yet\" and re-baselines.\n const wasForgotten = this.forgotten.delete(rootPid)\n const pids = collectTree(rootPid, children)\n let rssKb = 0\n let percentAverage: number | null = null\n // Per-pid cumulative seconds for this tree, in the unit the comparison uses. Linux reports\n // jiffies; every other backend reports seconds already.\n const treeSeconds = new Map<number, number>()\n\n for (const pid of pids) {\n const row = byPid.get(pid)\n if (!row)\n continue\n rssKb += row.rssKb\n if (row.cpuPercent !== undefined)\n percentAverage = (percentAverage ?? 0) + row.cpuPercent\n if (row.cpuSeconds !== undefined)\n treeSeconds.set(pid, row.cpuSeconds / ticks)\n }\n\n const usedSeconds = before === null\n ? null\n : treeCpuUsedSeconds(before.cpuSeconds, treeSeconds, pids)\n let cpuPercent: number | null = percentAverage\n if (cpuPercent === null && !wasForgotten && usedSeconds !== null && elapsedSeconds > 0)\n cpuPercent = (usedSeconds / elapsedSeconds) * 100\n\n results.set(rootPid, {\n cpuPercent: cpuPercent === null ? null : Math.round(cpuPercent * 10) / 10,\n rssBytes: Math.round(rssKb * 1024),\n processes: pids.length,\n sampledAt: scannedAt,\n })\n }\n\n this.previousTable = { at: scannedAt, cpuSeconds: tableCpuSeconds }\n for (const [pid, reading] of results) {\n if (reading !== null)\n this.lastReadings.set(pid, reading)\n else\n this.lastReadings.delete(pid)\n }\n return results\n }\n\n /**\n * Marks a root's next reading as the first of a new life.\n *\n * Called when an entry stops, exits or is restarted. Without it a recycled pid — or the very\n * next sample of the same root — would be differenced against a counter from the previous run,\n * which is not an interval. The scan-wide table cannot be cleared per root, so the suppression\n * is remembered here and consumed by that root's next sample.\n */\n forget(rootPid: number): void {\n this.lastReadings.delete(rootPid)\n this.forgotten.set(rootPid, Date.now())\n }\n}\n\n/**\n * Does this process carry the environment the supervisor gave the entry?\n *\n * A program that restarts itself — especially a plugin doing it — leaves behind a\n * detached process that still inherits `HHOSTED_SERVER_ID`, and that marker is what\n * tells a legitimate successor apart from a stranger squatting on the port.\n *\n * Linux reads `/proc`; macOS asks `ps -E`; Windows has no per-process environment,\n * so the answer is always \"no\" there and ownership falls back to the port policy.\n */\nexport async function processCarriesServerId(pid: number, serverId: string): Promise<boolean> {\n if (serverId.length === 0)\n return false\n const needle = `HHOSTED_SERVER_ID=${serverId}`\n\n if (process.platform === 'linux') {\n try {\n const raw = await fs.promises.readFile(`/proc/${pid}/environ`, 'utf8')\n return raw.split('\\0').includes(needle)\n }\n catch {\n return false\n }\n }\n\n if (process.platform === 'darwin') {\n try {\n const { stdout } = await execFileAsync('ps', ['-p', String(pid), '-E', '-ww', '-o', 'command='], { timeout: 3000 })\n // Values with spaces are unquoted in this output, so the marker is matched as a word.\n return new RegExp(`(?:^|\\\\s)${needle}(?:\\\\s|$)`).test(stdout)\n }\n catch {\n return false\n }\n }\n\n return false\n}\n","import { execFile } from 'node:child_process'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { promisify } from 'node:util'\nimport { processCarriesServerId } from '#src/providers/proc'\n\nconst execFileAsync = promisify(execFile)\n\n/** What the panel actually spawned for an entry: the argv it has to recognize again. */\nexport interface SpawnInfo {\n command: string\n args: string[]\n cwd: string\n}\n\n/**\n * Splits a command line into words, undoing the quoting Windows put there. `CommandLine`\n * is the raw string from the spawn call, so `\"C:\\a b\\x.cmd\" /c` is one argv entry plus\n * two words, and a quoted argument that contains spaces has to come back as one word.\n *\n * Windows also *escapes* a quote inside an argument as `\\\"` (Node does this for any argv\n * containing a quote), so the escape is undone here — otherwise every argument with a\n * quote in it survives as a stray backslash and never matches what the panel spawned.\n */\nexport function splitCommandLine(line: string): string[] {\n const words: string[] = []\n let current = ''\n let quoted = false\n let started = false\n\n const chars = [...line.trim()]\n for (let index = 0; index < chars.length; index += 1) {\n const char = chars[index]!\n\n // A backslash run escapes only the quote that follows it; any other backslash is a\n // literal path separator. Node emits `\\\"` for an argument's own quote, and treating\n // that quote as a delimiter closed the argument early — so the rest of the line\n // (including the *next* argument) was swallowed into the same word, and an entry\n // whose argv contains a quote was not recognized as its own successor.\n if (char === '\\\\') {\n let run = 0\n while (chars[index + run] === '\\\\') run += 1\n const next = chars[index + run]\n if (next !== '\"') {\n current += '\\\\'.repeat(run)\n started = true\n index += run - 1\n continue\n }\n // 2n backslashes then a quote: n literal backslashes, and the quote is a real\n // delimiter. 2n+1: n literal backslashes and a literal quote.\n current += '\\\\'.repeat(Math.floor(run / 2))\n started = true\n if (run % 2 === 1) {\n current += '\"'\n index += run\n continue\n }\n quoted = !quoted\n index += run\n continue\n }\n\n if (char === '\"') {\n quoted = !quoted\n // A quote is both a delimiter and proof that a (possibly empty) word exists.\n started = true\n continue\n }\n if (!quoted && /\\s/.test(char)) {\n if (started)\n words.push(current)\n current = ''\n started = false\n continue\n }\n current += char\n started = true\n }\n\n if (started)\n words.push(current)\n return words\n}\n\nfunction comparable(target: string): string {\n // Quotes around a whole word are stripped; whitespace never is. `SpawnInfo.args` is the\n // argv `spawn` was handed, where a whitespace argument is still an argument, so trimming\n // here would make it compare equal to a missing one. A `\\\"` is Windows' escape for a\n // quote inside an argument, and the word it sits in is compared against the raw argv.\n const value = target.replace(/^\"(.*)\"$/, '$1').replace(/\\\\(?=\")/g, '')\n return process.platform === 'win32' ? value.toLowerCase() : value\n}\n\n/**\n * Literal comparison for an argument: the same text, modulo the case folding Windows needs\n * and the quoting a command line shuffles around.\n *\n * Deliberately *not* `sameWord`: folding an argument to its basename would let this\n * entry's `/srv/web/build/server.js` equal a stranger's `/tmp/evil/build/server.js`, and a\n * match here is what `reclaim` kills. Nor is it a plain string equality: reading an argv\n * back out of a Windows `CommandLine` cannot preserve quotes exactly — the OS escapes an\n * argument's own quote as `\\\"` and strips the structural ones — so quotes and backslashes\n * are dropped from both sides. That leaves the arguments' actual text, which is what the\n * match is about.\n */\nfunction sameArg(a: string, b: string): boolean {\n const normalize = (value: string): string => comparable(value).replace(/[\"\\\\]/g, '')\n return normalize(a) === normalize(b)\n}\n\n/** Whether a value names a file with no directory part, under either platform's separator. */\nfunction isBare(value: string): boolean {\n return !value.includes('/') && !value.includes('\\\\')\n}\n\n/**\n * The same file spelled differently compares equal — but only while one of the two spellings is a\n * bare name, which is the case the fallback exists for: the config says `node` and the process table\n * reports `/usr/bin/node`, or the reverse on Windows.\n *\n * When **both** spellings name a directory, they are two different files. Comparing basenames\n * unconditionally made `/tmp/evil/server.js` match `/srv/web/server.js`, and a false match here is\n * not cosmetic: the panel would treat a process it never spawned as its own entry, so `follow` adopts\n * a stranger and `reclaim`/`kill` may remove one.\n */\nfunction sameWord(a: string, b: string): boolean {\n const left = comparable(a)\n const right = comparable(b)\n if (left === right)\n return true\n if (!isBare(left) && !isBare(right))\n return false\n return path.basename(left) === path.basename(right)\n || (path.extname(b) === '' && path.basename(left, path.extname(left)) === right)\n || (path.extname(a) === '' && path.basename(right, path.extname(right)) === left)\n}\n\n/**\n * True when the argv a process is running is the entry's own: the image must match where\n * `spawn` would have looked it up — the image Path, or the first word of the command line\n * — and the words after it must open with the entry's args, compared literally. So\n * `spawn --port 4000` also covers `spawn -p 4000 --extra`, which is what a self-restarting\n * wrapper does, while `/tmp/evil/server.js` never covers `/srv/web/server.js` — two paths that name\n * a directory are different files, and the basename fallback applies only while one spelling is bare\n * (see `sameWord`).\n *\n * `words` must already be the process's own argv. A command-line *string* is only correct\n * on Windows, where the OS hands one out; `/proc/<pid>/cmdline` quotes are literal bytes\n * of an argument, so re-joining that argv into one string corrupts it.\n */\nexport function matchesSpawn(info: { words: string[], imagePath?: string | null }, spawn: SpawnInfo): boolean {\n const { words } = info\n const first = words[0] ?? ''\n\n // The image may be the first word, or absent from the command line entirely — a shim or\n // an interpreter reports its own image while the argv still carries what we passed.\n const imageMatches = sameWord(first, spawn.command)\n || (info.imagePath != null && info.imagePath !== '' && sameWord(info.imagePath, spawn.command))\n if (!imageMatches)\n return false\n\n // `>` rather than `>=`: a process has to have *more* words than we have args, so an\n // argument can never be satisfied by a word that is not there.\n const offset = sameWord(first, spawn.command) ? 1 : 0\n if (words.length < spawn.args.length + offset)\n return false\n\n return spawn.args.every((arg, index) => sameArg(words[index + offset]!, arg))\n}\n\n/** The argv of a pid on the platforms whose process table can answer it; null otherwise. */\nexport async function processArgv(pid: number): Promise<string[] | null> {\n if (process.platform === 'win32')\n return null\n\n if (process.platform === 'linux') {\n try {\n const raw = await fs.promises.readFile(`/proc/${pid}/cmdline`)\n // Every word is NUL-terminated, so the file ends with an empty element to drop — and only\n // that one. An argument may itself be empty, which is two NULs, and filtering every empty\n // string pulled the words after it into its place: the entry's own successor stopped\n // matching its argv, and a stranger's did.\n const words = raw.toString('utf8').split('\\0')\n if (words.at(-1) === '')\n words.pop()\n return words.length > 0 ? words : null\n }\n catch {\n return null\n }\n }\n\n try {\n const { stdout } = await execFileAsync('ps', ['-p', String(pid), '-ww', '-o', 'command='], { timeout: 3000 })\n // macOS receives one line and has to split it back into words here. `ps` joins argv\n // with spaces and quotes none of them, so an argument that itself contains a space\n // cannot be told from two arguments — that entry then fails to match and blocks,\n // which is the safe direction to be wrong in.\n const words = splitCommandLine(stdout.trim())\n return words.length > 0 ? words : null\n }\n catch {\n return null\n }\n}\n\nconst windowsFilter = /^\\d+$/\n\n/**\n * The first two rows of `ConvertTo-Csv` output: the header and the first record. PowerShell\n * quotes and doubles its way around CSV, so `a,\"b\"\"c\"` is three fields with the second\n * reading `b\"c`.\n */\nfunction parseCsvRows(output: string): [string[] | null, string[] | null] {\n const rows: string[][] = []\n let row: string[] = []\n let field = ''\n let quoted = false\n\n for (let index = 0; index < output.length; index++) {\n const char = output[index]!\n if (quoted) {\n if (char !== '\"') {\n field += char\n continue\n }\n if (output[index + 1] === '\"') {\n field += '\"'\n index++\n continue\n }\n quoted = false\n continue\n }\n\n if (char === '\"') {\n quoted = true\n continue\n }\n if (char === ',') {\n row.push(field)\n field = ''\n continue\n }\n if (char === '\\n') {\n row.push(field.replace(/\\r$/, ''))\n rows.push(row)\n row = []\n field = ''\n continue\n }\n field += char\n }\n\n if (field.length > 0 || row.length > 0)\n rows.push([...row, field.replace(/\\r$/, '')])\n\n return [rows[0] ?? null, rows[1] ?? null]\n}\n\n/**\n * `Win32_Process` for one pid, or null when it cannot be read.\n *\n * The whole round trip — launching PowerShell, loading the CIM provider, serializing —\n * costs seconds on a cold runner, so the timeout is generous and the result is converted\n * to CSV rather than JSON: CSV survives a value that contains a quote or a newline, which\n * an argv legitimately can.\n */\nexport async function windowsProcessInfo(pid: number): Promise<{ commandLine: string, imagePath: string | null } | null> {\n if (!windowsFilter.test(String(pid)))\n return null\n\n try {\n const script = `Get-CimInstance Win32_Process -Filter \"ProcessId=${pid}\" | Select-Object CommandLine,ExecutablePath | ConvertTo-Csv -NoTypeInformation`\n const { stdout } = await execFileAsync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], { timeout: 20000, windowsHide: true })\n const [headers, values] = parseCsvRows(stdout)\n if (!headers || !values)\n return null\n\n const commandLineIndex = headers.indexOf('CommandLine')\n const imageIndex = headers.indexOf('ExecutablePath')\n const commandLine = commandLineIndex >= 0 ? values[commandLineIndex] : undefined\n if (commandLine === undefined || commandLine.length === 0)\n return null\n\n const imagePath = imageIndex >= 0 ? values[imageIndex] : undefined\n return { commandLine, imagePath: imagePath && imagePath.length > 0 ? imagePath : null }\n }\n catch {\n return null\n }\n}\n\n/**\n * Which of these pids look like this entry's own detached successor. The environment\n * marker is authoritative where the platform can read it; otherwise the answer rests on\n * the entry's own argv, which is the only signal a detached successor is obliged to keep\n * — and the only one Windows exposes at all.\n */\nexport async function identifyHolders(serverId: string, spawn: SpawnInfo, pids: number[]): Promise<number[]> {\n const found: number[] = []\n\n for (const pid of pids) {\n if (await processCarriesServerId(pid, serverId)) {\n found.push(pid)\n continue\n }\n\n // An empty argv proves nothing, so a marker is the only way in without it.\n if (spawn.args.length === 0)\n continue\n\n if (process.platform === 'win32') {\n const info = await windowsProcessInfo(pid)\n if (info && matchesSpawn({ words: splitCommandLine(info.commandLine), imagePath: info.imagePath }, spawn))\n found.push(pid)\n continue\n }\n\n const argv = await processArgv(pid)\n if (argv !== null && matchesSpawn({ words: argv }, spawn))\n found.push(pid)\n }\n\n return found\n}\n","import type { ChildProcess } from 'node:child_process'\nimport { execFile, spawn } from 'node:child_process'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { promisify } from 'node:util'\nimport { projectDir } from '#src/helpers/paths'\nimport { isProcessAlive } from '#src/providers/port'\n\nconst execFileAsync = promisify(execFile)\n\nexport interface SpawnSpec {\n command: string\n args: string[]\n cwd: string\n env: Record<string, string>\n}\n\n/**\n * The files `npm`/`pnpm` write into `node_modules/.bin` on Windows, in the order Node can\n * actually start them.\n *\n * All of `foo`, `foo.cmd` and `foo.ps1` exist there — the extension-less one is a `#!/bin/sh`\n * script, which is the POSIX shim, not a program Windows can spawn. Preferring it (the order\n * `[command, ...shims]` gave) resolved to a file whose first line is `#!/bin/sh`: Node has no\n * shell to hand it to, so the entry started nothing. `spawn` reports that as `ENOENT` and the\n * panel used to blame the missing program.\n *\n * `.exe` leads because it needs no shell; `.cmd`/`.bat` follow and go through `needsShell()`.\n * `.ps1` is last: it is a PowerShell script, which `cmd.exe` does not run on its own.\n */\nconst WINDOWS_SHIM_EXTENSIONS = ['.exe', '.cmd', '.bat', '.ps1']\n\n/**\n * Resolves a bare command through the entry's own directory and the project's\n * `node_modules/.bin` first, so a server installed as a project dependency is\n * found even when the launcher's PATH has no pnpm-injected bin dir.\n */\nexport function resolveCommand(command: string, ...searchDirs: string[]): string {\n if (command.includes('/') || command.includes('\\\\'))\n return command\n\n const candidates = process.platform === 'win32' && path.extname(command) === ''\n ? WINDOWS_SHIM_EXTENSIONS.map(extension => `${command}${extension}`)\n : [command]\n\n for (const dir of searchDirs) {\n for (const candidate of candidates) {\n const local = path.join(dir, 'node_modules', '.bin', candidate)\n if (fs.existsSync(local))\n return local\n }\n }\n\n if (process.platform === 'win32' && path.extname(command) === '')\n return windowsShimOnPath(command) ?? command\n return command\n}\n\n/**\n * A bare name that `PATH` resolves to a `.cmd`/`.bat` (`pnpm`, `npm`, `yarn`) comes back with that\n * extension, so `needsShell` sees it: `spawn` without a shell only finds `.com`/`.exe` and answers\n * `ENOENT`. The name stays bare (`npm.cmd`), so `cmd.exe` searches for it and a `Program Files`\n * path is never split. `null` when the first match by `PATHEXT` order needs no shell, or none exists.\n */\nfunction windowsShimOnPath(command: string): string | null {\n const runnable = new Set(['.com', '.exe', '.bat', '.cmd'])\n const extensions = (process.env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD')\n .split(';')\n .map(extension => extension.trim().toLowerCase())\n .filter(extension => runnable.has(extension))\n for (const dir of pathDirs()) {\n for (const extension of extensions) {\n if (isExecutable(path.join(dir, `${command}${extension}`)))\n return extension === '.bat' || extension === '.cmd' ? `${command}${extension}` : null\n }\n }\n return null\n}\n\nfunction pathDirs(): string[] {\n return (process.env.PATH ?? '').split(path.delimiter).filter(dir => dir.length > 0)\n}\n\n/**\n * Does this program exist where `spawn` would look it up, and where?\n *\n * Used only to tell a **pasted command line** apart from a missing program: `spawn` answers both\n * with the same `ENOENT`, and the two have opposite fixes. `null` means it was not found anywhere\n * this process would search.\n *\n * A bare name is searched on `PATH` (plus `.exe`/`.cmd`/`.bat` on Windows, because that is what\n * the OS appends); anything with a separator is a path and is stat'd as written.\n */\nexport function findProgram(command: string, cwd: string = projectDir): string | null {\n const isPath = command.includes('/') || command.includes('\\\\')\n if (isPath) {\n const resolved = path.resolve(cwd, command)\n return isExecutable(resolved) ? resolved : null\n }\n\n const extensions = process.platform === 'win32' ? ['', ...WINDOWS_SHIM_EXTENSIONS] : ['']\n for (const dir of pathDirs()) {\n for (const extension of extensions) {\n const candidate = path.join(dir, `${command}${extension}`)\n if (isExecutable(candidate))\n return candidate\n }\n }\n return null\n}\n\n/** A file this user may run. A directory named like a program is not one. */\nfunction isExecutable(file: string): boolean {\n try {\n if (!fs.statSync(file).isFile())\n return false\n if (process.platform === 'win32')\n return true\n fs.accessSync(file, fs.constants.X_OK)\n return true\n }\n catch {\n return false\n }\n}\n\n/** Relative entry paths belong to the project that launched the panel. */\nexport function resolveCwd(cwd: string, base: string = projectDir): string {\n return path.resolve(base, cwd)\n}\n\n/** Node cannot spawn a Windows `.cmd`/`.bat` shim without a shell (EINVAL). */\nexport function needsShell(command: string): boolean {\n return process.platform === 'win32' && /\\.(?:cmd|bat)$/i.test(command)\n}\n\nexport interface SpawnOptions {\n /**\n * A supervised child gets its own process group, so one `kill(-pid)` stops the tree.\n * A child spawned by a nanny does not: it shares the nanny's group, which is the\n * group the panel signals — so the same one-signal semantics still reach both.\n */\n detached?: boolean\n /**\n * Open descriptors for the child's output, instead of a pipe this process reads.\n *\n * A pipe makes this process its **read end**, so the child does not survive us: kill the panel,\n * the read end closes, and the child's next write to stdout fails with `EPIPE` — which ends a\n * process that was supposed to outlive the panel. A file the child opens takes this process out of\n * the chain: the descriptor belongs to the child, and the panel reads the bytes back afterwards.\n *\n * The caller owns these (it opens them with `openOutput` and closes its own copies after the\n * spawn); `spawn` duplicates them onto the child's table.\n */\n output?: { stdout: number, stderr: number }\n}\n\nexport function spawnManaged(spec: SpawnSpec, options: SpawnOptions = {}): ChildProcess {\n return spawn(spec.command, spec.args, {\n cwd: spec.cwd,\n env: { ...process.env, ...spec.env },\n // Own process group: a stop can signal the whole tree with one kill(-pid).\n detached: options.detached ?? true,\n // A descriptor the child inherits, or a pipe we hold the other end of — see `SpawnOptions`.\n stdio: options.output === undefined\n ? ['ignore', 'pipe', 'pipe']\n : ['ignore', options.output.stdout, options.output.stderr],\n shell: needsShell(spec.command),\n windowsHide: true,\n })\n}\n\nexport interface TerminateOptions {\n signal: NodeJS.Signals\n killGroup: boolean\n graceMs: number\n /** The SIGKILL escalation reaches the group even when the graceful signal went to the pid alone. */\n escalateGroup?: boolean\n}\n\n/** SIGTERM (default) to the child, escalating to SIGKILL after the grace period. */\nexport async function terminate(child: ChildProcess, options: TerminateOptions): Promise<'exited' | 'force-killed'> {\n if (child.exitCode !== null || child.signalCode !== null)\n return 'exited'\n\n const exited = waitForExit(child, options.graceMs)\n signalChild(child, options.signal, options.killGroup)\n\n if (await exited)\n return 'exited'\n\n signalChild(child, 'SIGKILL', options.escalateGroup ?? options.killGroup)\n await waitForExit(child, 2000)\n return 'force-killed'\n}\n\n/**\n * Windows has no process groups and no SIGTERM: `taskkill /T` walks the tree and\n * `/F` is the only reliable way to stop a console process.\n */\nexport async function killTreeWindows(pid: number): Promise<void> {\n try {\n await execFileAsync('taskkill', ['/pid', String(pid), '/T', '/F'], { timeout: 5000 })\n }\n catch {\n // Already gone, or taskkill is unavailable.\n }\n}\n\n/** SIGKILL to a `spawnManaged` child and everything it started: its group, or its tree on Windows. */\nexport function forceKillTree(child: ChildProcess): void {\n if (child.exitCode === null && child.signalCode === null)\n signalChild(child, 'SIGKILL', true)\n}\n\nfunction signalChild(child: ChildProcess, signal: NodeJS.Signals, killGroup: boolean): void {\n const pid = child.pid\n if (pid === undefined)\n return\n signalPid(pid, signal, killGroup)\n}\n\nfunction signalPid(pid: number, signal: NodeJS.Signals, killGroup: boolean): void {\n if (process.platform === 'win32') {\n if (killGroup) {\n void killTreeWindows(pid)\n }\n else {\n try {\n process.kill(pid, signal)\n }\n catch {\n // already exited\n }\n }\n return\n }\n\n if (killGroup) {\n try {\n process.kill(-pid, signal)\n return\n }\n catch {\n // group already gone, fall through to the single pid\n }\n }\n\n try {\n process.kill(pid, signal)\n }\n catch {\n // already exited\n }\n}\n\n/**\n * The same shutdown a supervised child gets, for a process we adopted instead of\n * spawned: a detached successor is not our child, so it is signalled by pid (and\n * by process group when asked) and its exit is polled rather than awaited.\n *\n * Liveness comes from `isProcessAlive`, never a local signal-0 copy: a second definition returned\n * `false` for `EPERM`, so a process that was there but not ours to signal read as \"exited\" and\n * `'force-killed'` was returned for one still running. One predicate, one answer.\n */\nexport async function terminatePid(pid: number, options: TerminateOptions): Promise<'exited' | 'force-killed'> {\n if (!isProcessAlive(pid))\n return 'exited'\n\n signalPid(pid, options.signal, options.killGroup)\n\n const deadline = Date.now() + Math.max(0, options.graceMs)\n while (Date.now() < deadline && isProcessAlive(pid))\n await delay(50)\n if (!isProcessAlive(pid))\n return 'exited'\n\n signalPid(pid, 'SIGKILL', options.escalateGroup ?? options.killGroup)\n const hardDeadline = Date.now() + 2000\n while (Date.now() < hardDeadline && isProcessAlive(pid))\n await delay(50)\n return 'force-killed'\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms))\n}\n\nfunction waitForExit(child: ChildProcess, timeoutMs: number): Promise<boolean> {\n if (child.exitCode !== null || child.signalCode !== null)\n return Promise.resolve(true)\n if (timeoutMs <= 0)\n return Promise.resolve(false)\n\n return new Promise((resolve) => {\n const timer = setTimeout(() => {\n child.removeListener('exit', onExit)\n resolve(false)\n }, timeoutMs)\n\n function onExit(): void {\n clearTimeout(timer)\n resolve(true)\n }\n\n child.once('exit', onExit)\n })\n}\n","import type { ProcessBirth } from '#src/providers/port'\nimport type { TerminateOptions } from '#src/providers/process'\nimport type { NannyExit, NannySpec, NannyState, StopConfig } from '#src/shared/contracts'\nimport fs from 'node:fs'\nimport os from 'node:os'\nimport path from 'node:path'\nimport process from 'node:process'\nimport { type } from 'arktype'\nimport { writeFileAtomic } from '#src/helpers/atomic'\nimport { NANNY_COMMAND } from '#src/helpers/runtime'\nimport { processArgv } from '#src/providers/identity'\nimport { processLiveness } from '#src/providers/port'\nimport { processCarriesServerId } from '#src/providers/proc'\nimport { findProgram } from '#src/providers/process'\nimport { nannySpecSchema, nannyStateSchema } from '#src/shared/contracts'\n\n/**\n * A persistent entry is not run by the panel: the panel spawns a *nanny* that owns\n * the child's pipes, writes its output to the entry's JSONL log and keeps a small\n * state file. That is what lets the entry survive a panel stop, restart or kill\n * without losing its log or its identity — the pipes belong to a process that stays.\n *\n * These are the files and the liveness rules behind that arrangement; the nanny\n * itself is `src/services/nanny.ts`.\n */\n\n/** The spec carries expanded `env`, so it lives only from spawn to read. */\nconst SPEC_MODE = 0o600\n\n/** Suffix of a spawn spec, so a sweep and the state reader can tell them apart. */\nexport const SPEC_SUFFIX = '.spec.json'\n\n/**\n * The signals a nanny traps and forwards to its child. Any other signal ends the nanny outright,\n * so nothing was forwarded — see `stopPersistentEntries`, which then signals the child directly.\n */\nexport const NANNY_TRAPPED_SIGNALS: ReadonlySet<NodeJS.Signals> = new Set(['SIGTERM', 'SIGINT'])\n\n/**\n * How a nanny is stopped. A trapped signal goes to the nanny's pid alone and the nanny signals its\n * own group once (`killGroup` is honoured there): signalling the group from here as well delivered\n * the stop to the child twice. The SIGKILL escalation still covers the whole group. Windows has no\n * signal a nanny can trap, so its stop is unchanged.\n */\nexport function nannyStopOptions(stop: StopConfig, platform: NodeJS.Platform = process.platform): TerminateOptions {\n if (platform === 'win32' || !stop.killGroup || !NANNY_TRAPPED_SIGNALS.has(stop.signal))\n return stop\n return { ...stop, killGroup: false, escalateGroup: true }\n}\n\n/** How often a nanny rewrites its state file. */\nexport const NANNY_HEARTBEAT_MS = 5000\n\n/** A heartbeat older than this is not evidence of anything. */\nexport const HEARTBEAT_STALE_MS = 30_000\n\n/**\n * The state directory is passed in rather than read from a global: the panel injects\n * `$HHOSTED_HOME/.state`, and a test injects its own temp directory.\n */\nexport function nannySpecPath(dir: string, id: string): string {\n return path.join(dir, `${id}${SPEC_SUFFIX}`)\n}\n\nexport function nannyStatePath(dir: string, id: string): string {\n return path.join(dir, `${id}.json`)\n}\n\n/** The file a nanny writes and the panel tails; one derivation, so they cannot drift. */\nexport function nannyLogFile(logDir: string, id: string): string {\n return path.join(logDir, `${id}.log`)\n}\n\n/**\n * How to run this CLI again as a nanny. The panel was itself launched through this\n * entry point (`up` re-spawns itself with it), so `process.argv[1]` is the one path\n * that works under tsx, from `dist/cli.js` and through the published bin alike.\n */\nexport function nannyEntryPoint(): string {\n return process.argv[1] ?? ''\n}\n\n/** Written before the spawn, consumed by the nanny, never left behind. */\nexport function writeNannySpec(file: string, spec: NannySpec): void {\n writeFileAtomic(file, JSON.stringify(spec), { mode: SPEC_MODE })\n}\n\nexport function clearNannySpec(file: string): void {\n fs.rmSync(file, { force: true })\n}\n\n/**\n * Reads and unlinks in one step: the spec holds expanded secrets, and a spec left\n * behind — a nanny that died before reading it, a panel killed mid-spawn — is a\n * secret file with no owner. It is consumed even when it cannot be parsed.\n */\nexport function takeNannySpec(file: string): NannySpec {\n const raw = fs.readFileSync(file, 'utf8')\n fs.rmSync(file, { force: true })\n\n const parsed = nannySpecSchema(JSON.parse(raw))\n if (parsed instanceof type.errors)\n throw new Error(`invalid nanny spec: ${parsed.summary}`)\n return parsed\n}\n\n/**\n * Nothing can be waiting on a spec before this panel has spawned a nanny, so every\n * one still on disk at boot belongs to a nanny that never read it.\n */\nexport function sweepNannySpecs(dir: string): number {\n let swept = 0\n for (const name of readSpecNames(dir)) {\n fs.rmSync(path.join(dir, name), { force: true })\n swept += 1\n }\n return swept\n}\n\nfunction readSpecNames(dir: string): string[] {\n try {\n return fs.readdirSync(dir).filter(name => name.endsWith(SPEC_SUFFIX))\n }\n catch {\n return []\n }\n}\n\n/** A stale or foreign file reads as \"no state\", never as a throw. */\nexport function readNannyState(file: string): NannyState | null {\n try {\n const parsed = nannyStateSchema(JSON.parse(fs.readFileSync(file, 'utf8')))\n return parsed instanceof type.errors ? null : parsed\n }\n catch {\n return null\n }\n}\n\nexport function writeNannyState(file: string, state: NannyState): void {\n writeFileAtomic(file, JSON.stringify(state))\n}\n\nexport function clearNannyState(file: string): void {\n fs.rmSync(file, { force: true })\n}\n\n/**\n * The same wording the supervisor uses for a child's exit, so history reads alike — plus a hint\n * when the code has a conventional meaning, because `code 137` alone tells an operator nothing and\n * that is the one they most want explained (a container limit or the kernel OOM killer).\n *\n * The hint is worded as a possibility, never a claim: 128+N is a shell convention, and a program\n * is free to exit 137 for its own reasons — a JVM reports OOM that way itself. 126 and 127 are\n * firmer, since the shell sets those when it cannot run the command at all.\n */\nexport function describeNannyExit(exit: NannyExit): string {\n if (exit.signal !== null)\n return `signal ${exit.signal}`\n const hint = exitCodeHint(exit.code)\n return hint === null ? `code ${exit.code}` : `code ${exit.code} (${hint})`\n}\n\n/** What a conventional exit code usually means, or null when there is nothing to add. */\nfunction exitCodeHint(code: number | null): string | null {\n if (code === null || code === 0)\n return null\n if (code === 126)\n return 'the command is not executable'\n if (code === 127)\n return 'the command was not found'\n if (code <= 128 || code > 128 + 64)\n return null\n const signal = signalName(code - 128)\n if (signal === null)\n return null\n return code === 137\n ? `${signal} — which the kernel sends when memory runs out`\n : `${signal}, if the shell reported the kill`\n}\n\n/**\n * A spawn failure in words a person can act on.\n *\n * Node reports a missing program as `spawn <cmd> ENOENT` — the same errno as a missing *file*, and\n * the same wording whichever of the two it is. A user who pasted `java -jar server.jar` into\n * `command` saw exactly that and had nothing to go on: the message names the whole line, so it\n * reads as \"the program is missing\" even when the program is fine and only the argument is wrong.\n *\n * `command` is the configured program, so the two cases can be told apart: if a bare name has no\n * path separator, the shell would have searched `PATH` and this one did not.\n *\n * A **missing working directory** is the third cause of the same errno, and it is the one a\n * deployment hits: `spawn` resolves `cwd` before it looks for the program, so an entry whose `cwd`\n * does not exist *under this launch directory* fails exactly like an uninstalled program. That read\n * sent a person to `which node` while `node` was fine and only the relative path was wrong (a unit\n * file with no `WorkingDirectory=`, a container started from `/`). `cwd` is therefore checked first:\n * if it is not an existing directory, nothing else about the spawn could have worked.\n */\nexport function describeSpawnError(error: NodeJS.ErrnoException, command: string, cwd?: string): string {\n const missingDir = cwd === undefined ? null : describeMissingDir(cwd)\n if (missingDir !== null && (error.code === 'ENOENT' || error.code === 'ENOTDIR'))\n return missingDir\n\n if (error.code === 'ENOENT') {\n const pasted = describePastedCommandLine(command, cwd)\n if (pasted !== null)\n return pasted\n return command.includes('/') || command.includes('\\\\')\n // A path was given, so the path is what is missing — the file, or a directory on the way.\n ? `\\`${command}\\` does not exist — check the path, and any directory on the way to it`\n // A bare name: spawn does not search a shell's PATH aliases, and the program may simply\n // not be installed. Naming the program is the whole value here.\n : `\\`${command}\\` was not found — is it installed, and is it on PATH for the user running the panel?`\n }\n if (error.code === 'EACCES')\n return `\\`${command}\\` exists but is not executable — ${notExecutableHint()}`\n return `${error.message} (while running \\`${command}\\`)`\n}\n\n/**\n * What to do about `EACCES`, in the shell of the platform the panel is running on.\n *\n * `chmod +x` is not a Windows program: `cmd.exe` answers `'chmod' is not recognized…`, so the one\n * line that exists to offer a way out sent the reader to a second dead end. The platform is the\n * only signal available, exactly as it is for `shellQuote` (`helpers/shell.ts`); one function so a\n * second `EACCES` message cannot be written with the POSIX half alone.\n */\nfunction notExecutableHint(): string {\n return process.platform === 'win32'\n // Windows has no executable bit: `EACCES` there means an ACL or a blocked file, not a mode.\n ? 'check its permissions (Windows has no executable bit — look at the file\\'s Security tab for a denied account)'\n : 'check its permissions (chmod +x)'\n}\n\n/**\n * The first mistake the Add-server form invites: a whole command line typed into `Command`.\n *\n * `Command` is spawned **without a shell** and `Arguments` is a separate field, so `node server.js`\n * names a program called `node server.js`. The fix is to split it — and the sentence has to say so,\n * because the alternative reading (\"node is not installed\") is what sends someone to `which node`\n * while `node` is right there.\n *\n * Only claimed when the evidence is unambiguous: the field has whitespace, and the program it opens\n * with **does** resolve. So a genuinely missing program keeps the message about PATH, and a path with\n * a space in it is never split (it has no bare first word that resolves). See `findProgram`.\n */\nfunction describePastedCommandLine(command: string, cwd?: string): string | null {\n const words = command.trim().split(/\\s+/)\n if (words.length < 2)\n return null\n const program = words[0]!\n if (findProgram(program, cwd) === null)\n return null\n return `\\`${command}\\` is a whole command line, but \\`Command\\` is spawned without a shell — this release looks for a program named \\`${command}\\`. Put \\`${program}\\` in \\`Command\\` and the rest in \\`Arguments\\`, one argument per line`\n}\n\n/** Why a working directory cannot be used, in one sentence, or null when it can. */\nfunction describeMissingDir(cwd: string): string | null {\n try {\n if (fs.statSync(cwd).isDirectory())\n return null\n return `the working directory \\`${cwd}\\` is not a directory — a relative \\`cwd\\` resolves against the directory the panel was started from`\n }\n catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return `the working directory \\`${cwd}\\` does not exist — a relative \\`cwd\\` resolves against the directory the panel was started from, so a service started from elsewhere (systemd, docker, a login shell) looks in a different place`\n }\n return `the working directory \\`${cwd}\\` cannot be read — check its permissions`\n }\n}\n\n/** `SIGKILL` for 9, or null when the number names nothing. */\nfunction signalName(number: number): string | null {\n for (const [name, value] of Object.entries(os.constants.signals)) {\n if (value === number)\n return name\n }\n return null\n}\n\n/**\n * Is the nanny this state describes still ours? A live pid proves nothing on its\n * own — pids are reused, and the heartbeat is written *into the file*, not by the\n * process the file names, so a recycled pid with a recent write reads as running.\n * `startedAt` settles that first (`processLiveness`), exactly as `run.json` uses it:\n * the nanny stamps its record during its own boot, so its process is always born\n * before the stamp. The environment marker (Linux, macOS) or the argv we spawned it\n * with answers the rest, Windows included.\n */\nexport async function nannyIsAlive(state: NannyState, id: string, options: { readBirth?: (pid: number) => Promise<ProcessBirth | null> } = {}): Promise<boolean> {\n if (state.nannyPid <= 0)\n return false\n // `'recycled'` is decisive and needs no threshold: a pid born after the record cannot be the\n // nanny that wrote it. `'gone'` is the plain dead pid. `'live'` and `'unknown'` both carry on —\n // a platform that cannot report a birth time must not have its running nanny dismissed.\n const liveness = await processLiveness(state.nannyPid, state.startedAt, options)\n if (liveness === 'gone' || liveness === 'recycled')\n return false\n if (Date.now() - state.heartbeatAt <= HEARTBEAT_STALE_MS)\n return true\n if (await processCarriesServerId(state.nannyPid, id))\n return true\n\n const words = await processArgv(state.nannyPid)\n return words !== null\n && words.includes(NANNY_COMMAND)\n && words.some(word => word.endsWith(`${id}.spec.json`))\n}\n\n/**\n * The nanny's child, when that pid is still the process it spawned — `null` otherwise. Used to stop a\n * child the nanny could not pass a stop on to, which happens *after* the nanny is gone, so a pid alone\n * could be anybody's by then. The nanny stamps `startedAt` just before it spawns the child, so the\n * child is born within the stamp's tolerance and a pid born later is a recycled one. Where the\n * platform reports no birth, the environment marker decides.\n */\nexport async function nannyChildPid(state: NannyState, options: { readBirth?: (pid: number) => Promise<ProcessBirth | null> } = {}): Promise<number | null> {\n const pid = state.childPid\n if (pid === null || pid <= 0)\n return null\n const liveness = await processLiveness(pid, state.startedAt, options)\n if (liveness === 'live')\n return pid\n if (liveness === 'unknown' && await processCarriesServerId(pid, state.serverId))\n return pid\n return null\n}\n"],"mappings":";;;;;;;;;;;;;;AAMA,IAAMA,kBAAgB,UAAU,QAAQ;AAYxC,SAAgB,cAAc,MAAyB;CACrD,MAAM,OAAkB,CAAC;CACzB,KAAK,MAAM,QAAQ,KAAK,MAAM,IAAI,GAAG;EACnC,MAAM,QAAQ,KAAK,KAAK,CAAC,CAAC,MAAM,KAAK;EACrC,IAAI,MAAM,SAAS,GACjB;EACF,MAAM,CAAC,KAAK,MAAM,KAAK,OAAO,MAAM,KAAI,UAAS,OAAO,WAAW,KAAK,CAAC;EACzE,IAAI,QAAQ,KAAA,KAAa,SAAS,KAAA,KAAa,QAAQ,KAAA,KAAa,CAAC,OAAO,SAAS,GAAG,GACtF;EACF,KAAK,KAAK;GAAE;GAAK;GAAM,OAAO;GAAK,YAAY,OAAO,SAAS,GAAG,IAAI,MAAM,KAAA;EAAU,CAAC;CACzF;CACA,OAAO;AACT;;AAGA,SAAgB,gBAAgB,MAAyB;CACvD,MAAM,OAAkB,CAAC;CACzB,MAAM,QAAQ,KAAK,MAAM,OAAO,CAAC,CAAC,QAAO,SAAQ,KAAK,KAAK,CAAC,CAAC,SAAS,CAAC;CACvE,MAAM,SAAS,MAAM,MAAM;CAC3B,IAAI,WAAW,KAAA,GACb,OAAO;CAET,MAAM,UAAU,OAAO,MAAM,GAAG,CAAC,CAAC,KAAI,UAAS,MAAM,QAAQ,MAAM,EAAE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