home-hosted 0.12.0 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +95 -49
- package/dist/chunks/{archive-DpCwA8Nf.js → archive-DP-XQR8X.js} +15 -2
- package/dist/chunks/archive-DP-XQR8X.js.map +1 -0
- package/dist/chunks/{atomic-CEfCUfkQ.js → atomic-C1PfJpE7.js} +3 -2
- package/dist/chunks/atomic-C1PfJpE7.js.map +1 -0
- package/dist/chunks/{backup-CPrJVPJI.js → backup-CZcVca2a.js} +101 -76
- package/dist/chunks/backup-CZcVca2a.js.map +1 -0
- package/dist/chunks/{backups-Bd2SF2qd.js → backups-CFRaWe_m.js} +881 -536
- package/dist/chunks/backups-CFRaWe_m.js.map +1 -0
- package/dist/chunks/{contracts-ku5ypHXJ.js → contracts-CMBD1TF9.js} +381 -407
- package/dist/chunks/contracts-CMBD1TF9.js.map +1 -0
- package/dist/chunks/{daemon-TwXk5vb8.js → daemon-qKVECISl.js} +52 -20
- package/dist/chunks/daemon-qKVECISl.js.map +1 -0
- package/dist/chunks/{docker-CGv4Uv7w.js → docker-Cy9Lyvda.js} +4 -3
- package/dist/chunks/docker-Cy9Lyvda.js.map +1 -0
- package/dist/chunks/{down-BlX5X3bm.js → down-pKbGCW9d.js} +22 -17
- package/dist/chunks/down-pKbGCW9d.js.map +1 -0
- package/dist/chunks/{init-DdmqHVra.js → init-BZ7hK9Vf.js} +19 -6
- package/dist/chunks/init-BZ7hK9Vf.js.map +1 -0
- package/dist/chunks/{last-stop-BZ08Z89-.js → last-stop-C-BXz_XI.js} +6 -5
- package/dist/chunks/last-stop-C-BXz_XI.js.map +1 -0
- package/dist/chunks/{layout-D74TGUnr.js → layout-DwTtmund.js} +2 -2
- package/dist/chunks/{layout-D74TGUnr.js.map → layout-DwTtmund.js.map} +1 -1
- package/dist/chunks/lazy-Ce5zEAq1.js +66 -0
- package/dist/chunks/lazy-Ce5zEAq1.js.map +1 -0
- package/dist/chunks/{log-buffer-HnP0jKhZ.js → log-buffer-Dy9HHDMD.js} +114 -50
- package/dist/chunks/log-buffer-Dy9HHDMD.js.map +1 -0
- package/dist/chunks/{logs-gI_69Q1P.js → logs---TI_bxM.js} +23 -21
- package/dist/chunks/logs---TI_bxM.js.map +1 -0
- package/dist/chunks/{migrate-BTlsibvF.js → migrate-Cfoq-Vgh.js} +5 -5
- package/dist/chunks/{migrate-BTlsibvF.js.map → migrate-Cfoq-Vgh.js.map} +1 -1
- package/dist/chunks/{nanny-CjnnrIpm.js → nanny-B-Eu0sFW.js} +3 -3
- package/dist/chunks/{nanny-CjnnrIpm.js.map → nanny-B-Eu0sFW.js.map} +1 -1
- package/dist/chunks/{nanny-20aBXL1o.js → nanny-BtWfy0QH.js} +121 -23
- package/dist/chunks/nanny-BtWfy0QH.js.map +1 -0
- package/dist/chunks/{nanny-DUaAfCV-.js → nanny-ChMtq1Zl.js} +3 -3
- package/dist/chunks/{nanny-DUaAfCV-.js.map → nanny-ChMtq1Zl.js.map} +1 -1
- package/dist/chunks/{nanny-sweep-Ca9kPAVi.js → nanny-sweep-DErnlPY1.js} +5 -4
- package/dist/chunks/nanny-sweep-DErnlPY1.js.map +1 -0
- package/dist/chunks/{parse-B9owE47G.js → parse-DhmG26fI.js} +4 -4
- package/dist/chunks/{parse-B9owE47G.js.map → parse-DhmG26fI.js.map} +1 -1
- package/dist/chunks/{paths-BT94q6-w.js → paths-CGlGDrOU.js} +36 -2
- package/dist/chunks/paths-CGlGDrOU.js.map +1 -0
- package/dist/chunks/{restart-UZgeDukG.js → restart-Des4DrAN.js} +25 -59
- package/dist/chunks/restart-Des4DrAN.js.map +1 -0
- package/dist/chunks/{schema-o7Lgk0V1.js → schema-B240VXcV.js} +11 -10
- package/dist/chunks/schema-B240VXcV.js.map +1 -0
- package/dist/chunks/{secrets-D7PdYh71.js → secrets-BieELnZh.js} +22 -4
- package/dist/chunks/secrets-BieELnZh.js.map +1 -0
- package/dist/chunks/{server-BuIeSsRu.js → server-Bge2r2qQ.js} +3 -3
- package/dist/chunks/{server-BuIeSsRu.js.map → server-Bge2r2qQ.js.map} +1 -1
- package/dist/chunks/{set-password-DegMumPh.js → set-password-D5vZqqSX.js} +7 -7
- package/dist/chunks/set-password-D5vZqqSX.js.map +1 -0
- package/dist/chunks/{set-token-21d1FTDC.js → set-token-obPiEJYk.js} +7 -7
- package/dist/chunks/set-token-obPiEJYk.js.map +1 -0
- package/dist/chunks/{settings-BVSBnIwJ.js → settings-xu-XTfWg.js} +126 -35
- package/dist/chunks/settings-xu-XTfWg.js.map +1 -0
- package/dist/chunks/{setup-temp-XiuAtiW2.js → setup-temp-CAN4_bA-.js} +6 -6
- package/dist/chunks/setup-temp-CAN4_bA-.js.map +1 -0
- package/dist/chunks/{src-BL97vLVb.js → src-BtWMFmzZ.js} +2246 -1061
- package/dist/chunks/src-BtWMFmzZ.js.map +1 -0
- package/dist/chunks/{status-EuWdRq8Q.js → status-DT1EsA-B.js} +12 -8
- package/dist/chunks/status-DT1EsA-B.js.map +1 -0
- package/dist/chunks/{ui-DbPuwddJ.js → ui-D562aqw5.js} +9 -7
- package/dist/chunks/ui-D562aqw5.js.map +1 -0
- package/dist/chunks/{ui-revert-BhqOAhmM.js → ui-revert-EkBBwRTt.js} +3 -3
- package/dist/chunks/{ui-revert-BhqOAhmM.js.map → ui-revert-EkBBwRTt.js.map} +1 -1
- package/dist/chunks/{ui-switch-CMoslPO2.js → ui-switch-BnZTdMDd.js} +3 -3
- package/dist/chunks/{ui-switch-CMoslPO2.js.map → ui-switch-BnZTdMDd.js.map} +1 -1
- package/dist/chunks/{ui-update-TTBBoDik.js → ui-update-_xryLYxw.js} +5 -5
- package/dist/chunks/{ui-update-TTBBoDik.js.map → ui-update-_xryLYxw.js.map} +1 -1
- package/dist/chunks/{up-C4H13hBw.js → up-Pdz-l6IH.js} +25 -11
- package/dist/chunks/up-Pdz-l6IH.js.map +1 -0
- package/dist/chunks/{usage-CSBgLRN5.js → usage-DFrCVXpT.js} +29 -3
- package/dist/chunks/usage-DFrCVXpT.js.map +1 -0
- package/dist/chunks/{workspaces-CAln2sQ7.js → workspaces-DYcfvKV_.js} +16 -8
- package/dist/chunks/workspaces-DYcfvKV_.js.map +1 -0
- package/dist/chunks/wsl-temperature-BiCI4iK6.js.map +1 -1
- package/dist/cli.js +80 -70
- package/dist/cli.js.map +1 -1
- package/dist/client.js +25 -1
- package/dist/client.js.map +1 -1
- package/dist/types/api/backups.d.ts +8 -3
- package/dist/types/api/control.d.ts +4 -3
- package/dist/types/api/events.d.ts +2 -1
- package/dist/types/api/health.d.ts +1 -0
- package/dist/types/api/metrics.d.ts +3 -1
- package/dist/types/api/settings.d.ts +2 -2
- package/dist/types/api/state.d.ts +8 -2
- package/dist/types/app.d.ts +26 -11
- package/dist/types/cli/backup.d.ts +7 -0
- package/dist/types/cli/down.d.ts +5 -0
- package/dist/types/cli/logs.d.ts +14 -2
- package/dist/types/cli/restart.d.ts +0 -1
- package/dist/types/cli/set-password.d.ts +2 -2
- package/dist/types/cli/up.d.ts +8 -2
- package/dist/types/client.d.ts +5618 -11
- package/dist/types/config/secrets.d.ts +2 -0
- package/dist/types/config/settings.d.ts +54 -8
- package/dist/types/config/store.d.ts +16 -3
- package/dist/types/config/workspaces.d.ts +4 -1
- package/dist/types/helpers/copy-tree.d.ts +5 -0
- package/dist/types/helpers/daemon.d.ts +20 -7
- package/dist/types/helpers/error.d.ts +8 -0
- package/dist/types/helpers/event-stream.d.ts +21 -0
- package/dist/types/helpers/openapi.d.ts +12 -24
- package/dist/types/helpers/paths.d.ts +18 -0
- package/dist/types/helpers/utf8-chunks.d.ts +15 -0
- package/dist/types/middleware/auth.d.ts +19 -3
- package/dist/types/providers/host.d.ts +1 -1
- package/dist/types/providers/log-tail.d.ts +27 -0
- package/dist/types/providers/nanny-sweep.d.ts +3 -0
- package/dist/types/providers/nanny.d.ts +10 -0
- package/dist/types/providers/proc.d.ts +9 -0
- package/dist/types/providers/process.d.ts +17 -0
- package/dist/types/providers/telegram.d.ts +45 -3
- package/dist/types/providers/wsl-temperature.d.ts +0 -4
- package/dist/types/services/auth.d.ts +36 -4
- package/dist/types/services/backups.d.ts +125 -1
- package/dist/types/services/ddns.d.ts +5 -0
- package/dist/types/services/exposure.d.ts +54 -1
- package/dist/types/services/history.d.ts +1 -0
- package/dist/types/services/host-monitor.d.ts +1 -0
- package/dist/types/services/log-buffer.d.ts +11 -0
- package/dist/types/services/log-files.d.ts +1 -11
- package/dist/types/services/log-relay.d.ts +0 -1
- package/dist/types/services/panel.d.ts +19 -0
- package/dist/types/services/proxy-certificates/certificates.d.ts +116 -0
- package/dist/types/services/proxy.d.ts +46 -69
- package/dist/types/services/state.d.ts +0 -3
- package/dist/types/services/supervisor/entry.d.ts +10 -0
- package/dist/types/services/supervisor/health.d.ts +3 -2
- package/dist/types/services/supervisor/output.d.ts +126 -0
- package/dist/types/services/supervisor/persistent.d.ts +4 -1
- package/dist/types/services/supervisor/records.d.ts +81 -1
- package/dist/types/services/supervisor.d.ts +32 -0
- package/dist/types/shared/action-outcome.d.ts +25 -0
- package/dist/types/shared/api-client.d.ts +218 -4
- package/dist/types/shared/backup-scope.d.ts +58 -0
- package/dist/types/shared/contracts.d.ts +142 -200
- package/dist/types/shared/ddns-form.d.ts +13 -0
- package/dist/types/shared/form-repair.d.ts +6 -0
- package/dist/types/shared/lazy.d.ts +4 -0
- package/dist/types/shared/live-frames.d.ts +22 -0
- package/dist/types/shared/live-series.d.ts +21 -0
- package/dist/types/shared/live-store.d.ts +72 -0
- package/dist/types/shared/patch-diff.d.ts +13 -2
- package/dist/types/shared/proxy-form.d.ts +2 -0
- package/dist/types/shared/server-form.d.ts +121 -0
- package/dist/types/shared/stream-access.d.ts +20 -0
- package/docs/API.md +45 -16
- package/docs/BACKUPS.md +31 -11
- package/docs/CLI.md +34 -61
- package/docs/DDNS.md +3 -1
- package/docs/NOTIFICATIONS.md +7 -1
- package/docs/REVERSE_PROXY.md +7 -1
- package/docs/SECURITY.md +21 -10
- package/docs/SERVERS.md +102 -23
- package/docs/UI_CREATION.md +10 -1
- package/docs/demo/blank-host-restore.sh +4 -3
- package/package.json +5 -7
- package/uis/stock/dist/assets/CopyButton-BUBKRJyY.js +1 -0
- package/uis/stock/dist/assets/GlobalSettingsView-yYMcRWvt.js +1 -0
- package/uis/stock/dist/assets/LogViewer-DIliXy62.js +1 -0
- package/uis/stock/dist/assets/LogsView-B7Z-7RNg.js +1 -0
- package/uis/stock/dist/assets/Modal-DmKa5Qpp.js +39 -0
- package/uis/stock/dist/assets/ProxyView-DvZiNkwb.js +1 -0
- package/uis/stock/dist/assets/ServerDetailView-6idGT_EX.js +2 -0
- package/uis/stock/dist/assets/SettingsShell-CeGtleYI.js +1 -0
- package/uis/stock/dist/assets/SettingsView-BrhJIrmk.js +2 -0
- package/uis/stock/dist/assets/de-BRITeb0H.js +1 -0
- package/uis/stock/dist/assets/es-B2zIEssV.js +1 -0
- package/uis/stock/dist/assets/fr-s0ZOBEqh.js +1 -0
- package/uis/stock/dist/assets/index-C1MehbKy.css +2 -0
- package/uis/stock/dist/assets/index-CnBN54wF.js +15 -0
- package/uis/stock/dist/assets/ja-CU7MR85V.js +1 -0
- package/uis/stock/dist/assets/ko-tL5Me6d-.js +1 -0
- package/uis/stock/dist/assets/ru-92yrvkNJ.js +1 -0
- package/uis/stock/dist/assets/vi-CzvY16k2.js +1 -0
- package/uis/stock/dist/assets/zh-CN-DDwFW_uW.js +1 -0
- package/uis/stock/dist/index.html +3 -2
- package/uis/stock/dist/ui.json +3 -3
- package/dist/chunks/archive-DpCwA8Nf.js.map +0 -1
- package/dist/chunks/atomic-CEfCUfkQ.js.map +0 -1
- package/dist/chunks/backup-CPrJVPJI.js.map +0 -1
- package/dist/chunks/backups-Bd2SF2qd.js.map +0 -1
- package/dist/chunks/contracts-ku5ypHXJ.js.map +0 -1
- package/dist/chunks/daemon-TwXk5vb8.js.map +0 -1
- package/dist/chunks/docker-CGv4Uv7w.js.map +0 -1
- package/dist/chunks/down-BlX5X3bm.js.map +0 -1
- package/dist/chunks/init-DdmqHVra.js.map +0 -1
- package/dist/chunks/last-stop-BZ08Z89-.js.map +0 -1
- package/dist/chunks/log-buffer-HnP0jKhZ.js.map +0 -1
- package/dist/chunks/logs-gI_69Q1P.js.map +0 -1
- package/dist/chunks/nanny-20aBXL1o.js.map +0 -1
- package/dist/chunks/nanny-sweep-Ca9kPAVi.js.map +0 -1
- package/dist/chunks/paths-BT94q6-w.js.map +0 -1
- package/dist/chunks/restart-UZgeDukG.js.map +0 -1
- package/dist/chunks/schema-o7Lgk0V1.js.map +0 -1
- package/dist/chunks/secrets-D7PdYh71.js.map +0 -1
- package/dist/chunks/set-password-DegMumPh.js.map +0 -1
- package/dist/chunks/set-token-21d1FTDC.js.map +0 -1
- package/dist/chunks/settings-BVSBnIwJ.js.map +0 -1
- package/dist/chunks/setup-temp-XiuAtiW2.js.map +0 -1
- package/dist/chunks/src-BL97vLVb.js.map +0 -1
- package/dist/chunks/status-EuWdRq8Q.js.map +0 -1
- package/dist/chunks/ui-DbPuwddJ.js.map +0 -1
- package/dist/chunks/up-C4H13hBw.js.map +0 -1
- package/dist/chunks/usage-CSBgLRN5.js.map +0 -1
- package/dist/chunks/workspaces-CAln2sQ7.js.map +0 -1
- package/docs/RESTORE_DEMO.md +0 -306
- package/uis/stock/dist/assets/de-DyGrM1KK.js +0 -1
- package/uis/stock/dist/assets/es-BebHdc0E.js +0 -1
- package/uis/stock/dist/assets/fr-DsDTrxhI.js +0 -1
- package/uis/stock/dist/assets/index-6LANO2Ua.css +0 -2
- package/uis/stock/dist/assets/index-D06cUZbM.js +0 -56
- package/uis/stock/dist/assets/ja-D3RARJjW.js +0 -1
- package/uis/stock/dist/assets/ko-CKI3dFoD.js +0 -1
- package/uis/stock/dist/assets/ru-DEU5ujXt.js +0 -1
- package/uis/stock/dist/assets/vi-ULKPnasj.js +0 -1
- package/uis/stock/dist/assets/zh-CN-tCvnOxWy.js +0 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
|
|
2
2
|
import "../cli.js";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
3
|
+
import { f as projectDir } from "./paths-CGlGDrOU.js";
|
|
4
|
+
import { t as writeFileAtomic } from "./atomic-C1PfJpE7.js";
|
|
5
|
+
import { M as nannySpecSchema, N as nannyStateSchema } from "./contracts-CMBD1TF9.js";
|
|
6
6
|
import { c as processLiveness, r as isProcessAlive } from "./port-B8WBTRMk.js";
|
|
7
7
|
import process from "node:process";
|
|
8
8
|
import path from "node:path";
|
|
@@ -59,6 +59,19 @@ function parseWindowsCsv(text) {
|
|
|
59
59
|
return rows;
|
|
60
60
|
}
|
|
61
61
|
var clockTicks = null;
|
|
62
|
+
var pageKb = null;
|
|
63
|
+
/** The kernel page size in kB (4 on x86, often 16 or 64 on arm64), read once. */
|
|
64
|
+
async function getPageKb() {
|
|
65
|
+
if (pageKb !== null) return pageKb;
|
|
66
|
+
try {
|
|
67
|
+
const { stdout } = await execFileAsync$2("getconf", ["PAGESIZE"], { timeout: 2e3 });
|
|
68
|
+
const bytes = Number.parseInt(stdout.trim(), 10);
|
|
69
|
+
pageKb = Number.isFinite(bytes) && bytes > 0 ? bytes / 1024 : 4;
|
|
70
|
+
} catch {
|
|
71
|
+
pageKb = 4;
|
|
72
|
+
}
|
|
73
|
+
return pageKb;
|
|
74
|
+
}
|
|
62
75
|
/** Linux jiffies per second; `getconf` is POSIX, with the usual default behind it. */
|
|
63
76
|
async function getClockTicks() {
|
|
64
77
|
if (clockTicks !== null) return clockTicks;
|
|
@@ -75,7 +88,7 @@ async function getClockTicks() {
|
|
|
75
88
|
* `/proc/<pid>/stat` needs care: the comm field is parenthesised and may itself
|
|
76
89
|
* contain spaces or parentheses, so parsing starts after the last `)`.
|
|
77
90
|
*/
|
|
78
|
-
function parseStat(pid, content) {
|
|
91
|
+
function parseStat(pid, content, pageSizeKb = 4) {
|
|
79
92
|
const close = content.lastIndexOf(")");
|
|
80
93
|
if (close < 0) return null;
|
|
81
94
|
const fields = content.slice(close + 2).split(" ");
|
|
@@ -87,10 +100,12 @@ function parseStat(pid, content) {
|
|
|
87
100
|
return {
|
|
88
101
|
pid,
|
|
89
102
|
ppid,
|
|
90
|
-
rssKb: Number.isFinite(rssPages) ? rssPages *
|
|
103
|
+
rssKb: Number.isFinite(rssPages) ? rssPages * pageSizeKb : 0,
|
|
91
104
|
cpuSeconds: utime + stime
|
|
92
105
|
};
|
|
93
106
|
}
|
|
107
|
+
/** Processes read between two turns of the event loop, so a large host never stalls it. */
|
|
108
|
+
var SCAN_BATCH = 64;
|
|
94
109
|
async function readLinux() {
|
|
95
110
|
const rows = [];
|
|
96
111
|
let names = [];
|
|
@@ -99,18 +114,16 @@ async function readLinux() {
|
|
|
99
114
|
} catch {
|
|
100
115
|
return rows;
|
|
101
116
|
}
|
|
117
|
+
const pageSizeKb = await getPageKb();
|
|
118
|
+
let read = 0;
|
|
102
119
|
for (const name of names) {
|
|
103
120
|
if (!/^\d+$/.test(name)) continue;
|
|
104
121
|
const pid = Number.parseInt(name, 10);
|
|
105
122
|
try {
|
|
106
|
-
const row = parseStat(pid, fs.readFileSync(`/proc/${pid}/stat`, "utf8"));
|
|
107
|
-
if (row
|
|
108
|
-
try {
|
|
109
|
-
const vmRss = /^VmRSS:\s+(\d+)\s+kB/m.exec(fs.readFileSync(`/proc/${pid}/status`, "utf8"))?.[1];
|
|
110
|
-
if (vmRss !== void 0) row.rssKb = Number.parseInt(vmRss, 10);
|
|
111
|
-
} catch {}
|
|
112
|
-
rows.push(row);
|
|
123
|
+
const row = parseStat(pid, fs.readFileSync(`/proc/${pid}/stat`, "utf8"), pageSizeKb);
|
|
124
|
+
if (row !== null) rows.push(row);
|
|
113
125
|
} catch {}
|
|
126
|
+
if (++read % SCAN_BATCH === 0) await new Promise((resolve) => setImmediate(resolve));
|
|
114
127
|
}
|
|
115
128
|
return rows;
|
|
116
129
|
}
|
|
@@ -151,11 +164,35 @@ async function readWindows() {
|
|
|
151
164
|
}
|
|
152
165
|
}
|
|
153
166
|
}
|
|
154
|
-
|
|
167
|
+
var scans = 0;
|
|
168
|
+
function scanProcesses() {
|
|
169
|
+
scans += 1;
|
|
155
170
|
if (process.platform === "linux") return readLinux();
|
|
156
171
|
if (process.platform === "win32") return readWindows();
|
|
157
172
|
return readPosix();
|
|
158
173
|
}
|
|
174
|
+
var lastScan = null;
|
|
175
|
+
/**
|
|
176
|
+
* The process table. `reuseMs` lets a caller accept a scan that is in flight or that recent — the
|
|
177
|
+
* resource samplers do, because every workspace has one and entries come due on their own second,
|
|
178
|
+
* so one tick could otherwise walk `/proc` (or spawn PowerShell) once per workspace per due entry.
|
|
179
|
+
* Anything deciding *ownership* passes 0: a process spawned a moment ago must be in its answer.
|
|
180
|
+
*/
|
|
181
|
+
function readProcesses(now = Date.now(), reuseMs = 0) {
|
|
182
|
+
if (reuseMs > 0 && lastScan !== null && now - lastScan.at < reuseMs) return lastScan.scan;
|
|
183
|
+
const scan = scanProcesses().then((rows) => ({
|
|
184
|
+
at: now,
|
|
185
|
+
rows
|
|
186
|
+
}));
|
|
187
|
+
lastScan = {
|
|
188
|
+
at: now,
|
|
189
|
+
scan
|
|
190
|
+
};
|
|
191
|
+
scan.catch(() => {
|
|
192
|
+
if (lastScan?.scan === scan) lastScan = null;
|
|
193
|
+
});
|
|
194
|
+
return scan;
|
|
195
|
+
}
|
|
159
196
|
function collectTree(rootPid, children) {
|
|
160
197
|
const pids = [];
|
|
161
198
|
const stack = [rootPid];
|
|
@@ -235,7 +272,7 @@ async function processTreeOwners(roots) {
|
|
|
235
272
|
for (const root of roots) if (!owners.has(root)) owners.set(root, root);
|
|
236
273
|
if (roots.length === 0) return owners;
|
|
237
274
|
try {
|
|
238
|
-
const rows = await readProcesses();
|
|
275
|
+
const { rows } = await readProcesses();
|
|
239
276
|
const children = /* @__PURE__ */ new Map();
|
|
240
277
|
for (const row of rows) {
|
|
241
278
|
const siblings = children.get(row.ppid) ?? [];
|
|
@@ -257,6 +294,11 @@ async function processTreeOwners(roots) {
|
|
|
257
294
|
* are null rather than wrong.
|
|
258
295
|
*/
|
|
259
296
|
var ProcessSampler = class {
|
|
297
|
+
reuseMs;
|
|
298
|
+
/** `reuseMs`: accept a process scan this recent from any sampler (0 = always scan fresh). */
|
|
299
|
+
constructor(reuseMs = 0) {
|
|
300
|
+
this.reuseMs = reuseMs;
|
|
301
|
+
}
|
|
260
302
|
/**
|
|
261
303
|
* Cumulative CPU seconds per pid, from the **whole process table** of the last scan.
|
|
262
304
|
*
|
|
@@ -281,6 +323,8 @@ var ProcessSampler = class {
|
|
|
281
323
|
* to the restarts that happened since the last one.
|
|
282
324
|
*/
|
|
283
325
|
forgotten = /* @__PURE__ */ new Map();
|
|
326
|
+
/** Each root's latest reading, answered again when the only scan available is one already used. */
|
|
327
|
+
lastReadings = /* @__PURE__ */ new Map();
|
|
284
328
|
async sample(rootPid, now = Date.now()) {
|
|
285
329
|
return (await this.sampleMany([rootPid], now)).get(rootPid) ?? null;
|
|
286
330
|
}
|
|
@@ -288,11 +332,18 @@ var ProcessSampler = class {
|
|
|
288
332
|
const results = /* @__PURE__ */ new Map();
|
|
289
333
|
if (rootPids.length === 0) return results;
|
|
290
334
|
let rows = [];
|
|
335
|
+
let scannedAt = now;
|
|
291
336
|
try {
|
|
292
|
-
|
|
337
|
+
const scan = await readProcesses(now, this.reuseMs);
|
|
338
|
+
rows = scan.rows;
|
|
339
|
+
scannedAt = scan.at;
|
|
293
340
|
} catch {
|
|
294
341
|
rows = [];
|
|
295
342
|
}
|
|
343
|
+
if (this.previousTable !== null && this.previousTable.at === scannedAt && rows.length > 0) {
|
|
344
|
+
for (const rootPid of rootPids) results.set(rootPid, this.lastReadings.get(rootPid) ?? null);
|
|
345
|
+
return results;
|
|
346
|
+
}
|
|
296
347
|
const byPid = new Map(rows.map((row) => [row.pid, row]));
|
|
297
348
|
const children = /* @__PURE__ */ new Map();
|
|
298
349
|
for (const row of rows) {
|
|
@@ -301,7 +352,7 @@ var ProcessSampler = class {
|
|
|
301
352
|
children.set(row.ppid, siblings);
|
|
302
353
|
}
|
|
303
354
|
const before = this.previousTable;
|
|
304
|
-
const elapsedSeconds = before === null ? 0 : (
|
|
355
|
+
const elapsedSeconds = before === null ? 0 : (scannedAt - before.at) / 1e3;
|
|
305
356
|
const ticks = process.platform === "linux" ? await getClockTicks() : 1;
|
|
306
357
|
const tableCpuSeconds = /* @__PURE__ */ new Map();
|
|
307
358
|
for (const row of rows) if (row.cpuSeconds !== void 0) tableCpuSeconds.set(row.pid, row.cpuSeconds / ticks);
|
|
@@ -329,13 +380,15 @@ var ProcessSampler = class {
|
|
|
329
380
|
cpuPercent: cpuPercent === null ? null : Math.round(cpuPercent * 10) / 10,
|
|
330
381
|
rssBytes: Math.round(rssKb * 1024),
|
|
331
382
|
processes: pids.length,
|
|
332
|
-
sampledAt:
|
|
383
|
+
sampledAt: scannedAt
|
|
333
384
|
});
|
|
334
385
|
}
|
|
335
386
|
this.previousTable = {
|
|
336
|
-
at:
|
|
387
|
+
at: scannedAt,
|
|
337
388
|
cpuSeconds: tableCpuSeconds
|
|
338
389
|
};
|
|
390
|
+
for (const [pid, reading] of results) if (reading !== null) this.lastReadings.set(pid, reading);
|
|
391
|
+
else this.lastReadings.delete(pid);
|
|
339
392
|
return results;
|
|
340
393
|
}
|
|
341
394
|
/**
|
|
@@ -347,6 +400,7 @@ var ProcessSampler = class {
|
|
|
347
400
|
* is remembered here and consumed by that root's next sample.
|
|
348
401
|
*/
|
|
349
402
|
forget(rootPid) {
|
|
403
|
+
this.lastReadings.delete(rootPid);
|
|
350
404
|
this.forgotten.set(rootPid, Date.now());
|
|
351
405
|
}
|
|
352
406
|
};
|
|
@@ -669,9 +723,30 @@ function resolveCommand(command, ...searchDirs) {
|
|
|
669
723
|
const local = path.join(dir, "node_modules", ".bin", candidate);
|
|
670
724
|
if (fs.existsSync(local)) return local;
|
|
671
725
|
}
|
|
726
|
+
if (process.platform === "win32" && path.extname(command) === "") return windowsShimOnPath(command) ?? command;
|
|
672
727
|
return command;
|
|
673
728
|
}
|
|
674
729
|
/**
|
|
730
|
+
* A bare name that `PATH` resolves to a `.cmd`/`.bat` (`pnpm`, `npm`, `yarn`) comes back with that
|
|
731
|
+
* extension, so `needsShell` sees it: `spawn` without a shell only finds `.com`/`.exe` and answers
|
|
732
|
+
* `ENOENT`. The name stays bare (`npm.cmd`), so `cmd.exe` searches for it and a `Program Files`
|
|
733
|
+
* path is never split. `null` when the first match by `PATHEXT` order needs no shell, or none exists.
|
|
734
|
+
*/
|
|
735
|
+
function windowsShimOnPath(command) {
|
|
736
|
+
const runnable = /* @__PURE__ */ new Set([
|
|
737
|
+
".com",
|
|
738
|
+
".exe",
|
|
739
|
+
".bat",
|
|
740
|
+
".cmd"
|
|
741
|
+
]);
|
|
742
|
+
const extensions = (process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").map((extension) => extension.trim().toLowerCase()).filter((extension) => runnable.has(extension));
|
|
743
|
+
for (const dir of pathDirs()) for (const extension of extensions) if (isExecutable(path.join(dir, `${command}${extension}`))) return extension === ".bat" || extension === ".cmd" ? `${command}${extension}` : null;
|
|
744
|
+
return null;
|
|
745
|
+
}
|
|
746
|
+
function pathDirs() {
|
|
747
|
+
return (process.env.PATH ?? "").split(path.delimiter).filter((dir) => dir.length > 0);
|
|
748
|
+
}
|
|
749
|
+
/**
|
|
675
750
|
* Does this program exist where `spawn` would look it up, and where?
|
|
676
751
|
*
|
|
677
752
|
* Used only to tell a **pasted command line** apart from a missing program: `spawn` answers both
|
|
@@ -687,8 +762,7 @@ function findProgram(command, cwd = projectDir) {
|
|
|
687
762
|
return isExecutable(resolved) ? resolved : null;
|
|
688
763
|
}
|
|
689
764
|
const extensions = process.platform === "win32" ? ["", ...WINDOWS_SHIM_EXTENSIONS] : [""];
|
|
690
|
-
const
|
|
691
|
-
for (const dir of dirs) for (const extension of extensions) {
|
|
765
|
+
for (const dir of pathDirs()) for (const extension of extensions) {
|
|
692
766
|
const candidate = path.join(dir, `${command}${extension}`);
|
|
693
767
|
if (isExecutable(candidate)) return candidate;
|
|
694
768
|
}
|
|
@@ -721,10 +795,14 @@ function spawnManaged(spec, options = {}) {
|
|
|
721
795
|
...spec.env
|
|
722
796
|
},
|
|
723
797
|
detached: options.detached ?? true,
|
|
724
|
-
stdio: [
|
|
798
|
+
stdio: options.output === void 0 ? [
|
|
725
799
|
"ignore",
|
|
726
800
|
"pipe",
|
|
727
801
|
"pipe"
|
|
802
|
+
] : [
|
|
803
|
+
"ignore",
|
|
804
|
+
options.output.stdout,
|
|
805
|
+
options.output.stderr
|
|
728
806
|
],
|
|
729
807
|
shell: needsShell(spec.command),
|
|
730
808
|
windowsHide: true
|
|
@@ -754,6 +832,10 @@ async function killTreeWindows(pid) {
|
|
|
754
832
|
], { timeout: 5e3 });
|
|
755
833
|
} catch {}
|
|
756
834
|
}
|
|
835
|
+
/** SIGKILL to a `spawnManaged` child and everything it started: its group, or its tree on Windows. */
|
|
836
|
+
function forceKillTree(child) {
|
|
837
|
+
if (child.exitCode === null && child.signalCode === null) signalChild(child, "SIGKILL", true);
|
|
838
|
+
}
|
|
757
839
|
function signalChild(child, signal, killGroup) {
|
|
758
840
|
const pid = child.pid;
|
|
759
841
|
if (pid === void 0) return;
|
|
@@ -824,6 +906,7 @@ var nanny_exports = /* @__PURE__ */ __exportAll({
|
|
|
824
906
|
clearNannyState: () => clearNannyState,
|
|
825
907
|
describeNannyExit: () => describeNannyExit,
|
|
826
908
|
describeSpawnError: () => describeSpawnError,
|
|
909
|
+
nannyChildPid: () => nannyChildPid,
|
|
827
910
|
nannyEntryPoint: () => nannyEntryPoint,
|
|
828
911
|
nannyIsAlive: () => nannyIsAlive,
|
|
829
912
|
nannyLogFile: () => nannyLogFile,
|
|
@@ -1063,7 +1146,22 @@ async function nannyIsAlive(state, id, options = {}) {
|
|
|
1063
1146
|
const words = await processArgv(state.nannyPid);
|
|
1064
1147
|
return words !== null && words.includes("__nanny") && words.some((word) => word.endsWith(`${id}.spec.json`));
|
|
1065
1148
|
}
|
|
1149
|
+
/**
|
|
1150
|
+
* The nanny's child, when that pid is still the process it spawned — `null` otherwise. Used to stop a
|
|
1151
|
+
* child the nanny could not pass a stop on to, which happens *after* the nanny is gone, so a pid alone
|
|
1152
|
+
* could be anybody's by then. The nanny stamps `startedAt` just before it spawns the child, so the
|
|
1153
|
+
* child is born within the stamp's tolerance and a pid born later is a recycled one. Where the
|
|
1154
|
+
* platform reports no birth, the environment marker decides.
|
|
1155
|
+
*/
|
|
1156
|
+
async function nannyChildPid(state, options = {}) {
|
|
1157
|
+
const pid = state.childPid;
|
|
1158
|
+
if (pid === null || pid <= 0) return null;
|
|
1159
|
+
const liveness = await processLiveness(pid, state.startedAt, options);
|
|
1160
|
+
if (liveness === "live") return pid;
|
|
1161
|
+
if (liveness === "unknown" && await processCarriesServerId(pid, state.serverId)) return pid;
|
|
1162
|
+
return null;
|
|
1163
|
+
}
|
|
1066
1164
|
//#endregion
|
|
1067
|
-
export {
|
|
1165
|
+
export { processTreeOwners as A, resolveCwd as C, identifyHolders as D, terminatePid as E, ProcessSampler as O, resolveCommand as S, terminate as T, readNannyState as _, clearNannySpec as a, writeNannyState as b, describeSpawnError as c, nannyIsAlive as d, nannyLogFile as f, nanny_exports as g, nannyStopOptions as h, SPEC_SUFFIX as i, processCarriesServerId as k, nannyChildPid as l, nannyStatePath as m, NANNY_HEARTBEAT_MS as n, clearNannyState as o, nannySpecPath as p, NANNY_TRAPPED_SIGNALS as r, describeNannyExit as s, HEARTBEAT_STALE_MS as t, nannyEntryPoint as u, sweepNannySpecs as v, spawnManaged as w, forceKillTree as x, writeNannySpec as y };
|
|
1068
1166
|
|
|
1069
|
-
//# sourceMappingURL=nanny-
|
|
1167
|
+
//# sourceMappingURL=nanny-BtWfy0QH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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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I,aAAa,UAAU,aAAa,YACtC,OAAO;CACT,IAAI,KAAK,IAAI,IAAI,MAAM,eAAA,KACrB,OAAO;CACT,IAAI,MAAM,uBAAuB,MAAM,UAAU,EAAE,GACjD,OAAO;CAET,MAAM,QAAQ,MAAM,YAAY,MAAM,QAAQ;CAC9C,OAAO,UAAU,QACZ,MAAM,SAAA,SAAsB,KAC5B,MAAM,MAAK,SAAQ,KAAK,SAAS,GAAG,GAAG,WAAW,CAAC;AAC1D;;;;;;;;AASA,eAAsB,cAAc,OAAmB,UAAyE,CAAC,GAA2B;CAC1J,MAAM,MAAM,MAAM;CAClB,IAAI,QAAQ,QAAQ,OAAO,GACzB,OAAO;CACT,MAAM,WAAW,MAAM,gBAAgB,KAAK,MAAM,WAAW,OAAO;CACpE,IAAI,aAAa,QACf,OAAO;CACT,IAAI,aAAa,aAAa,MAAM,uBAAuB,KAAK,MAAM,QAAQ,GAC5E,OAAO;CACT,OAAO;AACT"}
|
|
@@ -26,8 +26,8 @@ var nannyCommand = defineCommand({
|
|
|
26
26
|
}
|
|
27
27
|
},
|
|
28
28
|
run: async ({ args }) => {
|
|
29
|
-
const { takeNannySpec } = await import("./nanny-
|
|
30
|
-
const { runNanny } = await import("./nanny-
|
|
29
|
+
const { takeNannySpec } = await import("./nanny-BtWfy0QH.js").then((n) => n.g);
|
|
30
|
+
const { runNanny } = await import("./nanny-B-Eu0sFW.js");
|
|
31
31
|
const spec = takeNannySpec(args.spec);
|
|
32
32
|
if (spec.serverId !== args.id) throw new Error(`this spec runs "${spec.serverId}", not "${args.id}"`);
|
|
33
33
|
await runNanny(spec, args.state);
|
|
@@ -36,4 +36,4 @@ var nannyCommand = defineCommand({
|
|
|
36
36
|
//#endregion
|
|
37
37
|
export { nannyCommand };
|
|
38
38
|
|
|
39
|
-
//# sourceMappingURL=nanny-
|
|
39
|
+
//# sourceMappingURL=nanny-ChMtq1Zl.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nanny-
|
|
1
|
+
{"version":3,"file":"nanny-ChMtq1Zl.js","names":[],"sources":["../../src/cli/nanny.ts"],"sourcesContent":["import { defineCommand } from 'citty'\nimport { NANNY_COMMAND } from '#src/helpers/runtime'\n\n/**\n * The hidden command that runs one persistent entry. The panel spawns it from the\n * argv in `helpers/runtime.ts`; nothing a person types reaches it, so it stays out of\n * the curated help and keeps citty's own for `--help`.\n */\nexport const nannyCommand = defineCommand({\n meta: { name: NANNY_COMMAND, description: 'internal: run one persistent entry' },\n args: {\n id: { type: 'string', required: true },\n spec: { type: 'string', required: true },\n state: { type: 'string', required: true },\n },\n run: async ({ args }) => {\n const { takeNannySpec } = await import('#src/providers/nanny')\n const { runNanny } = await import('#src/services/nanny')\n\n const spec = takeNannySpec(args.spec)\n if (spec.serverId !== args.id)\n throw new Error(`this spec runs \"${spec.serverId}\", not \"${args.id}\"`)\n\n await runNanny(spec, args.state)\n },\n})\n"],"mappings":";;;;;;;;AAQA,IAAa,eAAe,cAAc;CACxC,MAAM;EAAE,MAAM;EAAe,aAAa;CAAqC;CAC/E,MAAM;EACJ,IAAI;GAAE,MAAM;GAAU,UAAU;EAAK;EACrC,MAAM;GAAE,MAAM;GAAU,UAAU;EAAK;EACvC,OAAO;GAAE,MAAM;GAAU,UAAU;EAAK;CAC1C;CACA,KAAK,OAAO,EAAE,WAAW;EACvB,MAAM,EAAE,kBAAkB,MAAM,OAAO,sBAAA,CAAA,MAAA,MAAA,EAAA,CAAA;EACvC,MAAM,EAAE,aAAa,MAAM,OAAO;EAElC,MAAM,OAAO,cAAc,KAAK,IAAI;EACpC,IAAI,KAAK,aAAa,KAAK,IACzB,MAAM,IAAI,MAAM,mBAAmB,KAAK,SAAS,UAAU,KAAK,GAAG,EAAE;EAEvE,MAAM,SAAS,MAAM,KAAK,KAAK;CACjC;AACF,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { tt as stopSchema } from "./contracts-CMBD1TF9.js";
|
|
2
|
+
import { E as terminatePid, _ as readNannyState, d as nannyIsAlive, h as nannyStopOptions, l as nannyChildPid, m as nannyStatePath, p as nannySpecPath, r as NANNY_TRAPPED_SIGNALS } from "./nanny-BtWfy0QH.js";
|
|
3
3
|
import { r as isProcessAlive } from "./port-B8WBTRMk.js";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import fs from "node:fs";
|
|
@@ -75,7 +75,8 @@ async function stopPersistentEntries(handles, options = {}) {
|
|
|
75
75
|
});
|
|
76
76
|
continue;
|
|
77
77
|
}
|
|
78
|
-
|
|
78
|
+
const child = state.childPid !== null && state.childPid > 0 && !stop.killGroup && (!NANNY_TRAPPED_SIGNALS.has(stop.signal) || nanny === "force-killed") ? await (options.childPid ?? nannyChildPid)(state) : null;
|
|
79
|
+
if (child !== null) await terminate(child, {
|
|
79
80
|
signal: "SIGKILL",
|
|
80
81
|
killGroup: false,
|
|
81
82
|
graceMs: 0
|
|
@@ -101,4 +102,4 @@ function consumeRecord(dir, serverId) {
|
|
|
101
102
|
//#endregion
|
|
102
103
|
export { livePersistentEntries, stopPersistentEntries };
|
|
103
104
|
|
|
104
|
-
//# sourceMappingURL=nanny-sweep-
|
|
105
|
+
//# sourceMappingURL=nanny-sweep-DErnlPY1.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nanny-sweep-DErnlPY1.js","names":[],"sources":["../../src/providers/nanny-sweep.ts"],"sourcesContent":["import type { NannyState, StopConfig } from '#src/shared/contracts'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { NANNY_TRAPPED_SIGNALS, nannyChildPid, nannyIsAlive, nannySpecPath, nannyStatePath, nannyStopOptions, readNannyState, SPEC_SUFFIX } from '#src/providers/nanny'\nimport { isProcessAlive } from '#src/providers/port'\nimport { terminatePid } from '#src/providers/process'\nimport { stopSchema } from '#src/shared/contracts'\n\n/**\n * Finds and ends the persistent entries a host is running, with no panel in the loop.\n *\n * `down` leaves these alone on purpose, so `--with-persistent` is the one caller that has to\n * act on them — often after the panel is already gone. The nanny state files are the only\n * record that survives that, and they are per workspace, so every workspace is read.\n *\n * The **nanny** is what gets signalled: it traps the signal and forwards the entry's own\n * `stop` policy to the child it owns, which is what the panel's stop does. That is also why\n * this cannot go through `/_hh` — after a crash there is nothing left to ask.\n */\n\n/** One live persistent entry, as its state file describes it. */\nexport interface PersistentHandle {\n workspaceId: string\n serverId: string\n state: NannyState\n /** The workspace's `.state` directory, which owns the state file. */\n dir: string\n}\n\n/**\n * Every workspace's state directory.\n *\n * Read here rather than through `workspaceStateDir()`, which resolves from *this* process's\n * `HHOSTED_HOME`: a caller passing `--home` elsewhere would otherwise sweep another host's\n * state — the mistake `backup-offline` already paid for.\n */\nfunction stateDirs(hhDir: string): Array<{ workspaceId: string, dir: string }> {\n try {\n return fs.readdirSync(hhDir, { withFileTypes: true })\n .filter(entry => entry.isDirectory() && !entry.name.startsWith('.'))\n .map(entry => entry.name)\n .filter(id => /^[a-z0-9][a-z0-9_-]*$/.test(id))\n .map(workspaceId => ({ workspaceId, dir: path.join(hhDir, workspaceId, '.state') }))\n }\n catch {\n return []\n }\n}\n\n/**\n * The persistent entries whose nanny is running right now.\n *\n * A `<id>.run.json` file is a *non-persistent* child's own record and carries no nanny, so it\n * is skipped by suffix — the same distinction `backup-offline` relies on. `nannyIsAlive` is\n * the identity check: a live pid alone proves nothing, since pids are reused.\n */\nexport async function livePersistentEntries(hhDir: string): Promise<PersistentHandle[]> {\n const found: PersistentHandle[] = []\n\n for (const { workspaceId, dir } of stateDirs(hhDir)) {\n let names: string[]\n try {\n names = fs.readdirSync(dir)\n }\n catch {\n // No persistent entry was ever started in this workspace.\n continue\n }\n\n for (const name of names) {\n if (!name.endsWith('.json') || name.endsWith(SPEC_SUFFIX))\n continue\n // One file per entry, named for it: a file that disagrees with its own name is not\n // something to act on.\n const serverId = name.slice(0, -'.json'.length)\n const state = readNannyState(path.join(dir, name))\n if (state === null || state.serverId !== serverId)\n continue\n if (await nannyIsAlive(state, serverId))\n found.push({ workspaceId, serverId, state, dir })\n }\n }\n return found\n}\n\n/** What one stop did, so a survivor is reported rather than dressed up as success. */\nexport interface PersistentStop {\n handle: PersistentHandle\n stopped: boolean\n error: string | null\n}\n\n/**\n * Stops these entries and consumes the record of each one that ended.\n *\n * `stopFor` is the entry's own `stop` config, read by the caller from the workspace that\n * declares it: the grace period here has to be the one the entry asked for, or a stop that\n * was still finishing its shutdown reads as a failure and escalates to `SIGKILL`.\n */\nexport async function stopPersistentEntries(\n handles: PersistentHandle[],\n options: {\n stopFor?: (handle: PersistentHandle) => StopConfig\n /**\n * The one thing a test cannot supply: `SIGKILL` is not survivable, and a pid this process\n * may not signal (the real survivor) is a second user this host has no way to create. The\n * seam is the terminator, not the decision — everything below still runs.\n */\n terminate?: typeof terminatePid\n /** Whether the state's child pid is still the process the nanny spawned (`nannyChildPid`). */\n childPid?: typeof nannyChildPid\n } = {},\n): Promise<PersistentStop[]> {\n const results: PersistentStop[] = []\n const terminate = options.terminate ?? terminatePid\n // `.assert` returns the parsed value with the schema's defaults filled in; the plain call\n // type is `Value | errors`, which would make every field a type error to read.\n const defaultStop = stopSchema.assert({})\n\n for (const handle of handles) {\n const stop = options.stopFor?.(handle) ?? defaultStop\n const { state, dir, serverId } = handle\n const nanny = await terminate(state.nannyPid, nannyStopOptions(stop))\n\n // A nanny this process could not signal, or one that outlived `SIGKILL`, keeps its\n // record: it is the only way a later boot can find that process again.\n if (isProcessAlive(state.nannyPid)) {\n results.push({ handle, stopped: false, error: `pid ${state.nannyPid} survived the stop — its record is kept, so the next \\`up\\` can still find it` })\n continue\n }\n\n // A nanny stops its child on the graceful path. A signal it does not trap — `SIGKILL` above\n // all — ends it outright, so nothing was forwarded; and with `killGroup: false` the group\n // signal never reached the child either. The pid in the state file is then the only handle on\n // a server that would otherwise keep serving. The configured signal decides this, never the\n // terminator's own label: `SIGKILL` always reports `force-killed`, which says nothing about\n // whether the nanny had a chance to pass the stop on.\n const orphaned = state.childPid !== null && state.childPid > 0\n && !stop.killGroup\n && (!NANNY_TRAPPED_SIGNALS.has(stop.signal) || nanny === 'force-killed')\n // Only once it is known to be that child: the nanny is gone, so the pid may be recycled already.\n const child = orphaned ? await (options.childPid ?? nannyChildPid)(state) : null\n if (child !== null)\n await terminate(child, { signal: 'SIGKILL', killGroup: false, graceMs: 0 })\n\n consumeRecord(dir, serverId)\n results.push({ handle, stopped: true, error: null })\n }\n return results\n}\n\n/**\n * The record goes only once the process it names is gone: a state file kept past its process\n * is a false reattach waiting, which is what `resumePersistent` exists to prevent.\n */\nfunction consumeRecord(dir: string, serverId: string): void {\n for (const file of [nannyStatePath(dir, serverId), nannySpecPath(dir, serverId)]) {\n try {\n fs.rmSync(file, { force: true })\n }\n catch {\n // A file this process may not remove is the next boot's business, not a stop failure.\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAoCA,SAAS,UAAU,OAA4D;CAC7E,IAAI;EACF,OAAO,GAAG,YAAY,OAAO,EAAE,eAAe,KAAK,CAAC,CAAC,CAClD,QAAO,UAAS,MAAM,YAAY,KAAK,CAAC,MAAM,KAAK,WAAW,GAAG,CAAC,CAAC,CACnE,KAAI,UAAS,MAAM,IAAI,CAAC,CACxB,QAAO,OAAM,wBAAwB,KAAK,EAAE,CAAC,CAAC,CAC9C,KAAI,iBAAgB;GAAE;GAAa,KAAK,KAAK,KAAK,OAAO,aAAa,QAAQ;EAAE,EAAE;CACvF,QACM;EACJ,OAAO,CAAC;CACV;AACF;;;;;;;;AASA,eAAsB,sBAAsB,OAA4C;CACtF,MAAM,QAA4B,CAAC;CAEnC,KAAK,MAAM,EAAE,aAAa,SAAS,UAAU,KAAK,GAAG;EACnD,IAAI;EACJ,IAAI;GACF,QAAQ,GAAG,YAAY,GAAG;EAC5B,QACM;GAEJ;EACF;EAEA,KAAK,MAAM,QAAQ,OAAO;GACxB,IAAI,CAAC,KAAK,SAAS,OAAO,KAAK,KAAK,SAAA,YAAoB,GACtD;GAGF,MAA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MAAM,EAAE,OAAO,KAAK,CAAC;CACjC,QACM,CAEN;AAEJ"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
|
|
2
2
|
import { t as appVersion } from "../cli.js";
|
|
3
3
|
import { t as isRecord } from "./shape-DnTKzjQ2.js";
|
|
4
|
-
import { t as LEGACY_TELEGRAM_ID } from "./secrets-
|
|
5
|
-
import {
|
|
6
|
-
import { a as mergeDefaults, n as SERVERS_FILE_KEYS, r as WORKSPACE_SETTINGS_KEYS, t as GLOBAL_SETTINGS_KEYS } from "./schema-
|
|
4
|
+
import { t as LEGACY_TELEGRAM_ID } from "./secrets-BieELnZh.js";
|
|
5
|
+
import { F as notificationsSchema, T as hostSchema, V as proxyConfigSchema, Y as serverSchema, _ as defaultsSchema, j as logsSchema, m as ddnsConfigSchema, p as controlSchema, u as backupsSchema } from "./contracts-CMBD1TF9.js";
|
|
6
|
+
import { a as mergeDefaults, n as SERVERS_FILE_KEYS, r as WORKSPACE_SETTINGS_KEYS, t as GLOBAL_SETTINGS_KEYS } from "./schema-B240VXcV.js";
|
|
7
7
|
import { type } from "arktype";
|
|
8
8
|
/**
|
|
9
9
|
* The id the pre-list Telegram destination takes.
|
|
@@ -380,4 +380,4 @@ function stampConfig(draft) {
|
|
|
380
380
|
//#endregion
|
|
381
381
|
export { parse_exports as a, planConfigMigrations as c, parseWorkspaceSettings as i, parseServersFile as n, stampConfig as o, parseTolerant as r, applyConfigMigrations as s, parseGlobalSettings as t };
|
|
382
382
|
|
|
383
|
-
//# sourceMappingURL=parse-
|
|
383
|
+
//# sourceMappingURL=parse-DhmG26fI.js.map
|